Debian Codegraph @

btf/types_test.go

raw symbols SCIP
1 package btf
2
3 import (
4 "encoding/binary"
5 "fmt"
6 "reflect"
7 "testing"
8
9 "github.com/go-quicktest/qt"
10 "github.com/google/go-cmp/cmp"
11
12 "github.com/cilium/ebpf/internal/testutils"
13 )
14
15 func TestSizeof(t *testing.T) {
16 testcases := []struct {
17 size int
18 typ Type
19 }{
20 {0, (*Void)(nil)},
21 {1, &Int{Size: 1}},
22 {8, &Enum{Size: 8}},
23 {0, &Array{Type: &Pointer{Target: (*Void)(nil)}, Nelems: 0}},
24 {12, &Array{Type: &Enum{Size: 4}, Nelems: 3}},
25 }
26
27 for _, tc := range testcases {
28 name := fmt.Sprint(tc.typ)
29 t.Run(name, func(t *testing.T) {
30 have, err := Sizeof(tc.typ)
31 if err != nil {
32 t.Fatal("Can't calculate size:", err)
33 }
34 if have != tc.size {
35 t.Errorf("Expected size %d, got %d", tc.size, have)
36 }
37 })
38 }
39 }
40
41 func TestCopy(t *testing.T) {
42 i := &Int{Size: 4}
43 tags := []string{"bar:foo"}
44
45 got := Copy(&Struct{
46 Members: []Member{
47 {Name: "a", Type: i},
48 {Name: "b", Type: i},
49 },
50 })
51 members := got.(*Struct).Members
52 qt.Check(t, qt.Equals(members[0].Type.(*Int), members[1].Type.(*Int)), qt.Commentf("identity should be preserved"))
53
54 for _, test := range []struct {
55 name string
56 typ Type
57 }{
58 {"nil", nil},
59 {"void", (*Void)(nil)},
60 {"int", i},
61 {"cyclical", newCyclicalType(2)},
62 {"struct tags", &Struct{Tags: tags, Members: []Member{{Tags: tags}}}},
63 {"union tags", &Union{Tags: tags, Members: []Member{{Tags: tags}}}},
64 {"typedef tags", &Typedef{Type: i, Tags: tags}},
65 {"var tags", &Var{Type: i, Tags: tags}},
66 {"func tags", &Func{Tags: tags, ParamTags: [][]string{tags}}},
67 } {
68 t.Run(test.name, func(t *testing.T) {
69 cpy := Copy(test.typ)
70 qt.Assert(t, testutils.IsDeepCopy(cpy, test.typ))
71 })
72 }
73 }
74
75 func TestAs(t *testing.T) {
76 i := &Int{}
77 ptr := &Pointer{i}
78 td := &Typedef{Type: ptr}
79 cst := &Const{td}
80 vol := &Volatile{cst}
81
82 // It's possible to retrieve qualifiers and Typedefs.
83 haveVol, ok := As[*Volatile](vol)
84 qt.Assert(t, qt.IsTrue(ok))
85 qt.Assert(t, qt.Equals(haveVol, vol))
86
87 haveTd, ok := As[*Typedef](vol)
88 qt.Assert(t, qt.IsTrue(ok))
89 qt.Assert(t, qt.Equals(haveTd, td))
90
91 haveCst, ok := As[*Const](vol)
92 qt.Assert(t, qt.IsTrue(ok))
93 qt.Assert(t, qt.Equals(haveCst, cst))
94
95 // Make sure we don't skip Pointer.
96 haveI, ok := As[*Int](vol)
97 qt.Assert(t, qt.IsFalse(ok))
98 qt.Assert(t, qt.IsNil(haveI))
99
100 // Make sure we can always retrieve Pointer.
101 for _, typ := range []Type{
102 td, cst, vol, ptr,
103 } {
104 have, ok := As[*Pointer](typ)
105 qt.Assert(t, qt.IsTrue(ok))
106 qt.Assert(t, qt.Equals(have, ptr))
107 }
108 }
109
110 func BenchmarkCopy(b *testing.B) {
111 typ := newCyclicalType(10)
112
113 b.ReportAllocs()
114
115 for b.Loop() {
116 Copy(typ)
117 }
118 }
119
120 // The following are valid Types.
121 //
122 // There currently is no better way to document which
123 // types implement an interface.
124 func ExampleType_validTypes() {
125 var _ Type = &Void{}
126 var _ Type = &Int{}
127 var _ Type = &Pointer{}
128 var _ Type = &Array{}
129 var _ Type = &Struct{}
130 var _ Type = &Union{}
131 var _ Type = &Enum{}
132 var _ Type = &Fwd{}
133 var _ Type = &Typedef{}
134 var _ Type = &Volatile{}
135 var _ Type = &Const{}
136 var _ Type = &Restrict{}
137 var _ Type = &Func{}
138 var _ Type = &FuncProto{}
139 var _ Type = &Var{}
140 var _ Type = &Datasec{}
141 var _ Type = &Float{}
142 }
143
144 func TestType(t *testing.T) {
145 types := []func() Type{
146 func() Type { return &Void{} },
147 func() Type { return &Int{Size: 2} },
148 func() Type { return &Pointer{Target: &Void{}} },
149 func() Type { return &Array{Type: &Int{}} },
150 func() Type {
151 return &Struct{
152 Members: []Member{{Type: &Void{}}},
153 }
154 },
155 func() Type {
156 return &Union{
157 Members: []Member{{Type: &Void{}}},
158 }
159 },
160 func() Type { return &Enum{} },
161 func() Type { return &Fwd{Name: "thunk"} },
162 func() Type { return &Typedef{Type: &Void{}} },
163 func() Type { return &Volatile{Type: &Void{}} },
164 func() Type { return &Const{Type: &Void{}} },
165 func() Type { return &Restrict{Type: &Void{}} },
166 func() Type { return &Func{Name: "foo", Type: &Void{}} },
167 func() Type {
168 return &FuncProto{
169 Params: []FuncParam{{Name: "bar", Type: &Void{}}},
170 Return: &Void{},
171 }
172 },
173 func() Type { return &Var{Type: &Void{}} },
174 func() Type {
175 return &Datasec{
176 Vars: []VarSecinfo{{Type: &Void{}}},
177 }
178 },
179 func() Type { return &Float{} },
180 func() Type { return &TypeTag{Type: &Void{}} },
181 func() Type { return &cycle{&Void{}} },
182 }
183
184 compareTypes := cmp.Comparer(func(a, b *Type) bool {
185 return a == b
186 })
187
188 for _, fn := range types {
189 typ := fn()
190 t.Run(fmt.Sprintf("%T", typ), func(t *testing.T) {
191 t.Logf("%v", typ)
192
193 if typ == typ.copy() {
194 t.Error("Copy doesn't copy")
195 }
196
197 var a []*Type
198 for t := range children(typ) {
199 a = append(a, t)
200 }
201
202 if _, ok := typ.(*cycle); !ok {
203 if n := countChildren(t, reflect.TypeOf(typ)); len(a) < n {
204 t.Errorf("walkType visited %d children, expected at least %d", len(a), n)
205 }
206 }
207
208 var b []*Type
209 for t := range children(typ) {
210 b = append(b, t)
211 }
212
213 if diff := cmp.Diff(a, b, compareTypes); diff != "" {
214 t.Errorf("Walk mismatch (-want +got):\n%s", diff)
215 }
216 })
217 }
218 }
219
220 func TestTagMarshaling(t *testing.T) {
221 for _, typ := range []Type{
222 &TypeTag{&Int{}, "foo"},
223 &Struct{Members: []Member{
224 {Type: &Int{}, Tags: []string{"bar"}},
225 }, Tags: []string{"foo"}},
226 &Union{Members: []Member{
227 {Type: &Int{}, Tags: []string{"bar"}},
228 {Type: &Int{}, Tags: []string{"baz"}},
229 }, Tags: []string{"foo"}},
230 &Func{Type: &FuncProto{Return: &Int{}, Params: []FuncParam{
231 {Name: "param1", Type: &Int{}},
232 }}, Tags: []string{"foo"}, ParamTags: [][]string{{"bar"}}},
233 &Var{Name: "var1", Type: &Int{}, Tags: []string{"foo"}},
234 &Typedef{Name: "baz", Type: &Int{}, Tags: []string{"foo"}},
235 } {
236 t.Run(fmt.Sprint(typ), func(t *testing.T) {
237 s := specFromTypes(t, []Type{typ})
238
239 have, err := s.TypeByID(1)
240 qt.Assert(t, qt.IsNil(err))
241
242 qt.Assert(t, qt.DeepEquals(have, typ))
243 })
244 }
245 }
246
247 func countChildren(t *testing.T, typ reflect.Type) int {
248 if typ.Kind() != reflect.Pointer {
249 t.Fatal("Expected pointer, got", typ.Kind())
250 }
251
252 typ = typ.Elem()
253 if typ.Kind() != reflect.Struct {
254 t.Fatal("Expected struct, got", typ.Kind())
255 }
256
257 var n int
258 for i := 0; i < typ.NumField(); i++ {
259 if typ.Field(i).Type == reflect.TypeFor[Type]() {
260 n++
261 }
262 }
263
264 return n
265 }
266
267 type testFormattableType struct {
268 name string
269 extra []any
270 }
271
272 var _ formattableType = (*testFormattableType)(nil)
273
274 func (tft *testFormattableType) TypeName() string { return tft.name }
275 func (tft *testFormattableType) Format(fs fmt.State, verb rune) {
276 formatType(fs, verb, tft, tft.extra...)
277 }
278
279 func TestFormatType(t *testing.T) {
280 t1 := &testFormattableType{"", []any{"extra"}}
281 t1Addr := fmt.Sprintf("%#p", t1)
282 goType := reflect.TypeOf(t1).Elem().Name()
283
284 t2 := &testFormattableType{"foo", []any{t1}}
285
286 t3 := &testFormattableType{extra: []any{""}}
287
288 tests := []struct {
289 t formattableType
290 fmt string
291 contains []string
292 omits []string
293 }{
294 // %s doesn't contain address or extra.
295 {t1, "%s", []string{goType}, []string{t1Addr, "extra"}},
296 // %+s doesn't contain extra.
297 {t1, "%+s", []string{goType, t1Addr}, []string{"extra"}},
298 // %v does contain extra.
299 {t1, "%v", []string{goType, "extra"}, []string{t1Addr}},
300 // %+v does contain address.
301 {t1, "%+v", []string{goType, "extra", t1Addr}, nil},
302 // %v doesn't print nested types' extra.
303 {t2, "%v", []string{goType, t2.name}, []string{"extra"}},
304 // %1v does print nested types' extra.
305 {t2, "%1v", []string{goType, t2.name, "extra"}, nil},
306 // empty strings in extra don't emit anything.
307 {t3, "%v", []string{"[]"}, nil},
308 }
309
310 for _, test := range tests {
311 t.Run(test.fmt, func(t *testing.T) {
312 str := fmt.Sprintf(test.fmt, test.t)
313 t.Log(str)
314
315 for _, want := range test.contains {
316 qt.Assert(t, qt.StringContains(str, want))
317 }
318
319 for _, notWant := range test.omits {
320 qt.Assert(t, qt.Not(qt.StringContains(str, notWant)))
321 }
322 })
323 }
324 }
325
326 func TestFormatCompoundTypes(t *testing.T) {
327 u := &Union{
328 Name: "u",
329 Members: []Member{{Name: "a"}, {Name: "b"}, {Name: "c"}, {Name: "d"}, {Name: "e"}, {Name: "f"}},
330 }
331 qt.Assert(t, qt.Equals(fmt.Sprintf("%v", u), `Union:"u"[fields=6 fieldNames=[a b c d e ...]]`))
332 qt.Assert(t, qt.Equals(fmt.Sprintf("%1v", u), `Union:"u"[fields=6 fieldNames=[a ...]]`))
333 qt.Assert(t, qt.Equals(fmt.Sprintf("%6v", u), `Union:"u"[fields=6 fieldNames=[a b c d e f]]`))
334
335 s := &Struct{
336 Name: "s",
337 Members: []Member{{Name: "a"}, {Name: "b"}, {Name: "c"}},
338 }
339 qt.Assert(t, qt.Equals(fmt.Sprintf("%v", s), `Struct:"s"[fields=3 fieldNames=[a b c]]`))
340 qt.Assert(t, qt.Equals(fmt.Sprintf("%1v", s), `Struct:"s"[fields=3 fieldNames=[a ...]]`))
341 }
342
343 func newCyclicalType(n int) Type {
344 ptr := &Pointer{}
345 prev := Type(ptr)
346 for i := range n {
347 switch i % 5 {
348 case 0:
349 prev = &Struct{
350 Members: []Member{
351 {Type: prev},
352 },
353 }
354
355 case 1:
356 prev = &Const{Type: prev}
357 case 2:
358 prev = &Volatile{Type: prev}
359 case 3:
360 prev = &Typedef{Type: prev}
361 case 4:
362 prev = &Array{Type: prev, Index: &Int{Size: 1}}
363 }
364 }
365 ptr.Target = prev
366 return ptr
367 }
368
369 func TestUnderlyingType(t *testing.T) {
370 wrappers := []struct {
371 name string
372 fn func(Type) Type
373 }{
374 {"const", func(t Type) Type { return &Const{Type: t} }},
375 {"volatile", func(t Type) Type { return &Volatile{Type: t} }},
376 {"restrict", func(t Type) Type { return &Restrict{Type: t} }},
377 {"typedef", func(t Type) Type { return &Typedef{Type: t} }},
378 {"type tag", func(t Type) Type { return &TypeTag{Type: t} }},
379 }
380
381 for _, test := range wrappers {
382 t.Run(test.name+" cycle", func(t *testing.T) {
383 root := &Volatile{}
384 root.Type = test.fn(root)
385
386 got, ok := UnderlyingType(root).(*cycle)
387 qt.Assert(t, qt.IsTrue(ok))
388 qt.Assert(t, qt.Equals[Type](got.root, root))
389 })
390 }
391
392 for _, test := range wrappers {
393 t.Run(test.name, func(t *testing.T) {
394 want := &Int{}
395 got := UnderlyingType(test.fn(want))
396 qt.Assert(t, qt.Equals[Type](got, want))
397 })
398 }
399 }
400
401 func TestInflateLegacyBitfield(t *testing.T) {
402 const offset = 3
403 const size = 5
404
405 addHeaderAndStringTable := func(types ...any) []byte {
406 var buf []byte
407 var err error
408 for _, typ := range types {
409 buf, err = binary.Append(buf, binary.LittleEndian, typ)
410 qt.Assert(t, qt.IsNil(err))
411 }
412
413 header, err := binary.Append(nil, binary.LittleEndian, &btfHeader{
414 Magic: btfMagic,
415 Version: 1,
416 Flags: 0,
417 HdrLen: uint32(btfHeaderLen),
418 TypeOff: 0,
419 TypeLen: uint32(len(buf)),
420 StringOff: uint32(len(buf)),
421 StringLen: 1,
422 })
423 qt.Assert(t, qt.IsNil(err))
424
425 buf = append(header, buf...)
426 buf = append(buf, 0) // string table
427 return buf
428 }
429
430 var placeholder struct {
431 btfType
432 btfInt
433 }
434 placeholder.SetKind(kindInt)
435 placeholder.SetSize(4)
436 placeholder.SetOffset(offset)
437 placeholder.SetBits(size)
438
439 var structFirst struct {
440 btfType
441 Members [1]btfMember
442 }
443 structFirst.SetKind(kindStruct)
444 structFirst.SetVlen(1)
445 structFirst.Members = [...]btfMember{{Type: 2}}
446
447 before := addHeaderAndStringTable(&structFirst, &placeholder)
448
449 structSecond := structFirst
450 structSecond.Members = [...]btfMember{{Type: 1}}
451
452 after := addHeaderAndStringTable(&placeholder, &structSecond)
453
454 for _, test := range []struct {
455 name string
456 buf []byte
457 }{
458 {"struct before int", before},
459 {"struct after int", after},
460 } {
461 t.Run(test.name, func(t *testing.T) {
462 spec, err := loadRawSpec(test.buf, nil)
463 qt.Assert(t, qt.IsNil(err))
464
465 for _, typ := range typesFromSpec(t, spec) {
466 s, ok := typ.(*Struct)
467 if !ok {
468 continue
469 }
470
471 i := s.Members[0]
472 if i.BitfieldSize != size {
473 t.Errorf("Expected bitfield size %d, got %d", size, i.BitfieldSize)
474 }
475
476 if i.Offset != offset {
477 t.Errorf("Expected offset %d, got %d", offset, i.Offset)
478 }
479
480 return
481 }
482
483 t.Fatal("No Struct returned from inflateRawTypes")
484 })
485 }
486 }
487
488 func TestMemberNames(t *testing.T) {
489 members := []Member{{Name: "foo"}, {}, {Name: "bar"}}
490
491 qt.Assert(t, qt.ContentEquals(memberNames(members, 3),
492 []string{"foo", "<1>", "bar"}))
493
494 qt.Assert(t, qt.ContentEquals(memberNames(members, 2),
495 []string{"foo", "<1>", "..."}))
496 }
497
498 func BenchmarkWalk(b *testing.B) {
499 types := []Type{
500 &Void{},
501 &Int{},
502 &Pointer{},
503 &Array{},
504 &Struct{Members: make([]Member, 2)},
505 &Union{Members: make([]Member, 2)},
506 &Enum{},
507 &Fwd{},
508 &Typedef{},
509 &Volatile{},
510 &Const{},
511 &Restrict{},
512 &Func{},
513 &FuncProto{Params: make([]FuncParam, 2)},
514 &Var{},
515 &Datasec{Vars: make([]VarSecinfo, 2)},
516 }
517
518 for _, typ := range types {
519 b.Run(fmt.Sprint(typ), func(b *testing.B) {
520 b.ReportAllocs()
521
522 for b.Loop() {
523 var dq typeDeque
524 for child := range children(typ) {
525 dq.Push(child)
526 }
527 }
528 })
529 }
530 }
531
532 func TestTagUnmarshaling(t *testing.T) {
533 testutils.Files(t, testutils.Glob(t, "testdata/tags-*.elf"), func(t *testing.T, file string) {
534 spec, err := LoadSpec(file)
535 qt.Assert(t, qt.IsNil(err))
536
537 var s *Struct
538 err = spec.TypeByName("s", &s)
539 qt.Assert(t, qt.IsNil(err))
540 qt.Assert(t, qt.ContentEquals(s.Tags, []string{"c"}))
541 qt.Assert(t, qt.ContentEquals(s.Members[0].Tags, []string{"a"}))
542 qt.Assert(t, qt.ContentEquals(s.Members[1].Tags, []string{"b"}))
543
544 var u *Union
545 err = spec.TypeByName("u", &u)
546 qt.Assert(t, qt.IsNil(err))
547 qt.Assert(t, qt.ContentEquals(u.Tags, []string{"c"}))
548 qt.Assert(t, qt.ContentEquals(u.Members[0].Tags, []string{"a"}))
549 qt.Assert(t, qt.ContentEquals(u.Members[1].Tags, []string{"b"}))
550
551 var td *Typedef
552 err = spec.TypeByName("td", &td)
553 qt.Assert(t, qt.IsNil(err))
554 qt.Assert(t, qt.ContentEquals(td.Tags, []string{"b"}))
555
556 var s1 *Var
557 err = spec.TypeByName("s1", &s1)
558 qt.Assert(t, qt.IsNil(err))
559 qt.Assert(t, qt.ContentEquals(s1.Tags, []string{"d"}))
560
561 var s2 *Var
562 err = spec.TypeByName("u1", &s2)
563 qt.Assert(t, qt.IsNil(err))
564 qt.Assert(t, qt.ContentEquals(s2.Tags, []string{"e"}))
565
566 var t1 *Var
567 err = spec.TypeByName("t1", &t1)
568 qt.Assert(t, qt.IsNil(err))
569 qt.Assert(t, qt.ContentEquals(t1.Tags, []string{"a"}))
570
571 var extFunc *Func
572 err = spec.TypeByName("fwdDecl", &extFunc)
573 qt.Assert(t, qt.IsNil(err))
574 qt.Assert(t, qt.ContentEquals(extFunc.Tags, []string{"a", "b"}))
575 qt.Assert(t, qt.ContentEquals(extFunc.ParamTags, [][]string{{"c"}, {"d"}}))
576
577 var normalFunc *Func
578 err = spec.TypeByName("normalDecl1", &normalFunc)
579 qt.Assert(t, qt.IsNil(err))
580 qt.Assert(t, qt.ContentEquals(normalFunc.Tags, []string{"e"}))
581 qt.Assert(t, qt.ContentEquals(normalFunc.ParamTags, [][]string{{"b"}, {"c"}}))
582
583 err = spec.TypeByName("normalDecl2", &normalFunc)
584 qt.Assert(t, qt.IsNil(err))
585 qt.Assert(t, qt.ContentEquals(normalFunc.Tags, []string{"e"}))
586 qt.Assert(t, qt.ContentEquals(normalFunc.ParamTags, [][]string{{"b"}, {"c"}}))
587 })
588 }
589
590 func BenchmarkUnderlyingType(b *testing.B) {
591 b.Run("no unwrapping", func(b *testing.B) {
592 v := &Int{}
593 b.ReportAllocs()
594
595 for b.Loop() {
596 UnderlyingType(v)
597 }
598 })
599
600 b.Run("single unwrapping", func(b *testing.B) {
601 v := &Typedef{Type: &Int{}}
602 b.ReportAllocs()
603
604 for b.Loop() {
605 UnderlyingType(v)
606 }
607 })
608 }
609
610 // As can be used to strip qualifiers from a Type.
611 func ExampleAs() {
612 a := &Volatile{Type: &Pointer{Target: &Typedef{Name: "foo", Type: &Int{Size: 2}}}}
613 fmt.Println(As[*Pointer](a))
614 // Output: Pointer[target=Typedef:"foo"] true
615 }