Debian Codegraph @

btf/format.go

raw symbols SCIP
1 package btf
2
3 import (
4 "errors"
5 "fmt"
6 "strings"
7 )
8
9 var errNestedTooDeep = errors.New("nested too deep")
10
11 // GoFormatter converts a Type to Go syntax.
12 //
13 // A zero GoFormatter is valid to use.
14 type GoFormatter struct {
15 w strings.Builder
16
17 // Types present in this map are referred to using the given name if they
18 // are encountered when outputting another type.
19 Names map[Type]string
20
21 // Identifier is called for each field of struct-like types. By default the
22 // field name is used as is.
23 Identifier func(string) string
24
25 // EnumIdentifier is called for each element of an enum. By default the
26 // name of the enum type is concatenated with Identifier(element).
27 EnumIdentifier func(name, element string) string
28 }
29
30 // TypeDeclaration generates a Go type declaration for a BTF type.
31 func (gf *GoFormatter) TypeDeclaration(name string, typ Type) (string, error) {
32 gf.w.Reset()
33 if err := gf.writeTypeDecl(name, typ); err != nil {
34 return "", err
35 }
36 return gf.w.String(), nil
37 }
38
39 func (gf *GoFormatter) identifier(s string) string {
40 if gf.Identifier != nil {
41 return gf.Identifier(s)
42 }
43
44 return s
45 }
46
47 func (gf *GoFormatter) enumIdentifier(name, element string) string {
48 if gf.EnumIdentifier != nil {
49 return gf.EnumIdentifier(name, element)
50 }
51
52 return name + gf.identifier(element)
53 }
54
55 // writeTypeDecl outputs a declaration of the given type.
56 //
57 // It encodes https://golang.org/ref/spec#Type_declarations:
58 //
59 // type foo struct { _ structs.HostLayout; bar uint32; }
60 // type bar int32
61 func (gf *GoFormatter) writeTypeDecl(name string, typ Type) error {
62 if name == "" {
63 return fmt.Errorf("need a name for type %s", typ)
64 }
65
66 typ = skipQualifiers(typ)
67 fmt.Fprintf(&gf.w, "type %s ", name)
68 if err := gf.writeTypeLit(typ, 0); err != nil {
69 return err
70 }
71
72 e, ok := typ.(*Enum)
73 if !ok || len(e.Values) == 0 {
74 return nil
75 }
76
77 gf.w.WriteString("; const ( ")
78 for _, ev := range e.Values {
79 id := gf.enumIdentifier(name, ev.Name)
80 var value any
81 if e.Signed {
82 value = int64(ev.Value)
83 } else {
84 value = ev.Value
85 }
86 fmt.Fprintf(&gf.w, "%s %s = %d; ", id, name, value)
87 }
88 gf.w.WriteString(")")
89
90 return nil
91 }
92
93 // writeType outputs the name of a named type or a literal describing the type.
94 //
95 // It encodes https://golang.org/ref/spec#Types.
96 //
97 // foo (if foo is a named type)
98 // uint32
99 func (gf *GoFormatter) writeType(typ Type, depth int) error {
100 typ = skipQualifiers(typ)
101
102 name := gf.Names[typ]
103 if name != "" {
104 gf.w.WriteString(name)
105 return nil
106 }
107
108 return gf.writeTypeLit(typ, depth)
109 }
110
111 // writeTypeLit outputs a literal describing the type.
112 //
113 // The function ignores named types.
114 //
115 // It encodes https://golang.org/ref/spec#TypeLit.
116 //
117 // struct { _ structs.HostLayout; bar uint32; }
118 // uint32
119 func (gf *GoFormatter) writeTypeLit(typ Type, depth int) error {
120 depth++
121 if depth > maxResolveDepth {
122 return errNestedTooDeep
123 }
124
125 var err error
126 switch v := skipQualifiers(typ).(type) {
127 case *Int:
128 err = gf.writeIntLit(v)
129
130 case *Enum:
131 if !v.Signed {
132 gf.w.WriteRune('u')
133 }
134 switch v.Size {
135 case 1:
136 gf.w.WriteString("int8")
137 case 2:
138 gf.w.WriteString("int16")
139 case 4:
140 gf.w.WriteString("int32")
141 case 8:
142 gf.w.WriteString("int64")
143 default:
144 err = fmt.Errorf("invalid enum size %d", v.Size)
145 }
146
147 case *Typedef:
148 err = gf.writeType(v.Type, depth)
149
150 case *Array:
151 fmt.Fprintf(&gf.w, "[%d]", v.Nelems)
152 err = gf.writeType(v.Type, depth)
153
154 case *Struct:
155 err = gf.writeStructLit(v.Size, v.Members, depth)
156
157 case *Union:
158 // Always choose the first member to represent the union in Go.
159 err = gf.writeStructLit(v.Size, v.Members[:1], depth)
160
161 case *Datasec:
162 err = gf.writeDatasecLit(v, depth)
163
164 case *Var:
165 err = gf.writeTypeLit(v.Type, depth)
166
167 default:
168 return fmt.Errorf("type %T: %w", v, ErrNotSupported)
169 }
170
171 if err != nil {
172 return fmt.Errorf("%s: %w", typ, err)
173 }
174
175 return nil
176 }
177
178 func (gf *GoFormatter) writeIntLit(i *Int) error {
179 bits := i.Size * 8
180 switch i.Encoding {
181 case Bool:
182 if i.Size != 1 {
183 return fmt.Errorf("bool with size %d", i.Size)
184 }
185 gf.w.WriteString("bool")
186 case Char:
187 if i.Size != 1 {
188 return fmt.Errorf("char with size %d", i.Size)
189 }
190 // BTF doesn't have a way to specify the signedness of a char. Assume
191 // we are dealing with unsigned, since this works nicely with []byte
192 // in Go code.
193 fallthrough
194 case Unsigned, Signed:
195 stem := "uint"
196 if i.Encoding == Signed {
197 stem = "int"
198 }
199 if i.Size > 8 {
200 fmt.Fprintf(&gf.w, "[%d]byte /* %s%d */", i.Size, stem, i.Size*8)
201 } else {
202 fmt.Fprintf(&gf.w, "%s%d", stem, bits)
203 }
204 default:
205 return fmt.Errorf("can't encode %s", i.Encoding)
206 }
207 return nil
208 }
209
210 func (gf *GoFormatter) writeStructLit(size uint32, members []Member, depth int) error {
211 gf.w.WriteString("struct { _ structs.HostLayout; ")
212
213 prevOffset := uint32(0)
214 skippedBitfield := false
215 for i, m := range members {
216 if m.BitfieldSize > 0 {
217 skippedBitfield = true
218 continue
219 }
220
221 offset := m.Offset.Bytes()
222 if n := offset - prevOffset; skippedBitfield && n > 0 {
223 fmt.Fprintf(&gf.w, "_ [%d]byte /* unsupported bitfield */; ", n)
224 } else {
225 gf.writePadding(n)
226 }
227
228 fieldSize, err := Sizeof(m.Type)
229 if err != nil {
230 return fmt.Errorf("field %d: %w", i, err)
231 }
232
233 prevOffset = offset + uint32(fieldSize)
234 if prevOffset > size {
235 return fmt.Errorf("field %d of size %d exceeds type size %d", i, fieldSize, size)
236 }
237
238 if err := gf.writeStructField(m, depth); err != nil {
239 return fmt.Errorf("field %d: %w", i, err)
240 }
241 }
242
243 gf.writePadding(size - prevOffset)
244 gf.w.WriteString("}")
245 return nil
246 }
247
248 func (gf *GoFormatter) writeStructField(m Member, depth int) error {
249 if m.BitfieldSize > 0 {
250 return fmt.Errorf("bitfields are not supported")
251 }
252 if m.Offset%8 != 0 {
253 return fmt.Errorf("unsupported offset %d", m.Offset)
254 }
255
256 if m.Name == "" {
257 // Special case a nested anonymous union like
258 // struct foo { union { int bar; int baz }; }
259 // by replacing the whole union with its first member.
260 union, ok := m.Type.(*Union)
261 if !ok {
262 return fmt.Errorf("anonymous fields are not supported")
263
264 }
265
266 if len(union.Members) == 0 {
267 return errors.New("empty anonymous union")
268 }
269
270 depth++
271 if depth > maxResolveDepth {
272 return errNestedTooDeep
273 }
274
275 m := union.Members[0]
276 size, err := Sizeof(m.Type)
277 if err != nil {
278 return err
279 }
280
281 if err := gf.writeStructField(m, depth); err != nil {
282 return err
283 }
284
285 gf.writePadding(union.Size - uint32(size))
286 return nil
287
288 }
289
290 fmt.Fprintf(&gf.w, "%s ", gf.identifier(m.Name))
291
292 if err := gf.writeType(m.Type, depth); err != nil {
293 return err
294 }
295
296 gf.w.WriteString("; ")
297 return nil
298 }
299
300 func (gf *GoFormatter) writeDatasecLit(ds *Datasec, depth int) error {
301 gf.w.WriteString("struct { _ structs.HostLayout; ")
302
303 prevOffset := uint32(0)
304 for i, vsi := range ds.Vars {
305 v, ok := vsi.Type.(*Var)
306 if !ok {
307 return fmt.Errorf("can't format %s as part of data section", vsi.Type)
308 }
309
310 if v.Linkage != GlobalVar {
311 // Ignore static, extern, etc. for now.
312 continue
313 }
314
315 if v.Name == "" {
316 return fmt.Errorf("variable %d: empty name", i)
317 }
318
319 gf.writePadding(vsi.Offset - prevOffset)
320 prevOffset = vsi.Offset + vsi.Size
321
322 fmt.Fprintf(&gf.w, "%s ", gf.identifier(v.Name))
323
324 if err := gf.writeType(v.Type, depth); err != nil {
325 return fmt.Errorf("variable %d: %w", i, err)
326 }
327
328 gf.w.WriteString("; ")
329 }
330
331 gf.writePadding(ds.Size - prevOffset)
332 gf.w.WriteString("}")
333 return nil
334 }
335
336 func (gf *GoFormatter) writePadding(bytes uint32) {
337 if bytes > 0 {
338 fmt.Fprintf(&gf.w, "_ [%d]byte; ", bytes)
339 }
340 }
341
342 func skipQualifiers(typ Type) Type {
343 result := typ
344 for depth := 0; depth <= maxResolveDepth; depth++ {
345 switch v := (result).(type) {
346 case qualifier:
347 result = v.qualify()
348 default:
349 return result
350 }
351 }
352 return &cycle{typ}
353 }