-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathunionsize.go
More file actions
206 lines (177 loc) · 5.35 KB
/
unionsize.go
File metadata and controls
206 lines (177 loc) · 5.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
package main
import (
"fmt"
"go/types"
"os"
"path/filepath"
"sort"
"golang.org/x/tools/go/packages"
)
// unionTypeInfo holds the inferred size and pointer layout of a union member.
type unionTypeInfo struct {
words int // total size in pointer-sized words
ptrWords []int // which word offsets contain pointers (sorted)
}
// inferUnionLayout loads the package containing the grammar, inspects
// each type declared in %union, and returns:
// - dataWords: number of uintptr words needed to hold the largest member
// - maxPtrs: maximum number of pointer words across all members
// - typeLayouts: per-member-name layout info (pointer word offsets)
func inferUnionLayout() (dataWords int, maxPtrs int, typeLayouts map[string]*unionTypeInfo, err error) {
var typeNames []string
for _, gt := range gotypes {
typeNames = append(typeNames, gt.typename)
}
if len(typeNames) == 0 {
return 0, 0, nil, nil
}
absOutput, err := filepath.Abs(oflag)
if err != nil {
return 0, 0, nil, fmt.Errorf("inferUnionLayout: %w", err)
}
pkgDir := filepath.Dir(absOutput)
loaded, err := packages.Load(&packages.Config{
Mode: packages.NeedName | packages.NeedTypes | packages.NeedTypesSizes,
Dir: pkgDir,
}, ".")
if err != nil {
return 0, 0, nil, fmt.Errorf("inferUnionLayout: failed to load package: %w", err)
}
if len(loaded) == 0 {
return 0, 0, nil, fmt.Errorf("inferUnionLayout: %s", "no packages loaded")
}
pkg := loaded[0]
if pkg.Types == nil {
return 0, 0, nil, fmt.Errorf("inferUnionLayout: %s", "package types not available")
}
sizes := pkg.TypesSizes
ptrSize := sizes.Sizeof(types.Typ[types.UnsafePointer])
typeLayouts = make(map[string]*unionTypeInfo)
for member, gt := range gotypes {
t := resolveType(pkg.Types, gt.typename)
if t == nil {
fmt.Fprintf(os.Stderr, "inferUnionLayout: cannot resolve type %q\n", gt.typename)
continue
}
sz := sizes.Sizeof(t)
words := int((sz + ptrSize - 1) / ptrSize)
if words > dataWords {
dataWords = words
}
ptrs := pointerWords(t, sizes, 0)
sort.Ints(ptrs)
if len(ptrs) > maxPtrs {
maxPtrs = len(ptrs)
}
typeLayouts[member] = &unionTypeInfo{
words: words,
ptrWords: ptrs,
}
}
if dataWords == 0 {
return 0, 0, nil, fmt.Errorf("inferUnionLayout: %s", "could not determine any type sizes")
}
return dataWords, maxPtrs, typeLayouts, nil
}
// resolveType looks up a type name in the package scope, handling
// built-in types, pointers, and slices.
func resolveType(pkg *types.Package, expr string) types.Type {
t, err := evalType(pkg, expr)
if err != nil {
return nil
}
return t
}
// pointerWords returns the word offsets (at ptrSize granularity) that
// contain pointer values for the given type. This is used to determine
// which words from the uintptr data array need to be copied to the
// unsafe.Pointer keepalive array.
func pointerWords(t types.Type, sizes types.Sizes, baseOffset int64) []int {
ptrSize := sizes.Sizeof(types.Typ[types.UnsafePointer])
switch t := t.Underlying().(type) {
case *types.Pointer:
return []int{int(baseOffset / ptrSize)}
case *types.Interface:
// Two words: type pointer + data pointer.
return []int{
int(baseOffset / ptrSize),
int(baseOffset/ptrSize) + 1,
}
case *types.Slice:
// Three words: data pointer, len, cap. Only first is a pointer.
return []int{int(baseOffset / ptrSize)}
case *types.Basic:
switch t.Kind() {
case types.String:
// Two words: data pointer + length. Only first is a pointer.
return []int{int(baseOffset / ptrSize)}
case types.UnsafePointer:
return []int{int(baseOffset / ptrSize)}
default:
return nil
}
case *types.Map, *types.Chan, *types.Signature:
return []int{int(baseOffset / ptrSize)}
case *types.Struct:
var ptrs []int
offsets := sizes.Offsetsof(structFields(t))
for i := range t.NumFields() {
ptrs = append(ptrs, pointerWords(t.Field(i).Type(), sizes, baseOffset+offsets[i])...)
}
return ptrs
case *types.Array:
elemSize := sizes.Sizeof(t.Elem())
var ptrs []int
for i := range t.Len() {
ptrs = append(ptrs, pointerWords(t.Elem(), sizes, baseOffset+int64(i)*elemSize)...)
}
return ptrs
default:
return nil
}
}
// structFields extracts the field list from a struct type for use with Offsetsof.
func structFields(s *types.Struct) []*types.Var {
fields := make([]*types.Var, s.NumFields())
for i := range s.NumFields() {
fields[i] = s.Field(i)
}
return fields
}
// evalType parses a Go type expression like "*String", "[]Expr", "bool"
// in the context of the given package.
func evalType(pkg *types.Package, expr string) (types.Type, error) {
if len(expr) > 0 && expr[0] == '*' {
inner, err := evalType(pkg, expr[1:])
if err != nil {
return nil, err
}
return types.NewPointer(inner), nil
}
if len(expr) > 2 && expr[0] == '[' && expr[1] == ']' {
inner, err := evalType(pkg, expr[2:])
if err != nil {
return nil, err
}
return types.NewSlice(inner), nil
}
switch expr {
case "string":
return types.Typ[types.String], nil
case "bool":
return types.Typ[types.Bool], nil
case "int":
return types.Typ[types.Int], nil
case "int64":
return types.Typ[types.Int64], nil
case "byte":
return types.Typ[types.Byte], nil
case "struct{}":
return types.NewStruct(nil, nil), nil
}
obj := pkg.Scope().Lookup(expr)
if obj == nil {
return nil, fmt.Errorf("type %q not found in package %s", expr, pkg.Name())
}
return obj.Type(), nil
}