Debian Codegraph @

btf/btf_test.go

raw symbols SCIP
1 package btf
2
3 import (
4 "bytes"
5 "encoding/binary"
6 "errors"
7 "fmt"
8 "io/fs"
9 "os"
10 "runtime"
11 "sync"
12 "sync/atomic"
13 "testing"
14
15 "github.com/go-quicktest/qt"
16
17 "github.com/cilium/ebpf/internal"
18 "github.com/cilium/ebpf/internal/testutils"
19 )
20
21 func vmlinuxSpec(tb testing.TB) *Spec {
22 tb.Helper()
23
24 // /sys/kernel/btf was introduced in 341dfcf8d78e ("btf: expose BTF info
25 // through sysfs"), which shipped in Linux 5.4.
26 if _, err := os.Stat("/sys/kernel/btf/vmlinux"); errors.Is(err, fs.ErrNotExist) {
27 tb.Skip("No /sys/kernel/btf/vmlinux")
28 }
29
30 spec, err := LoadKernelSpec()
31 if err != nil {
32 tb.Fatal(err)
33 }
34 return spec
35 }
36
37 type specAndRawBTF struct {
38 raw []byte
39 spec *Spec
40 }
41
42 var vmlinuxTestdata = sync.OnceValues(func() (specAndRawBTF, error) {
43 b, err := internal.ReadAllCompressed("testdata/vmlinux.btf.gz")
44 if err != nil {
45 return specAndRawBTF{}, err
46 }
47
48 spec, err := loadRawSpec(b, nil)
49 if err != nil {
50 return specAndRawBTF{}, err
51 }
52
53 return specAndRawBTF{b, spec}, nil
54 })
55
56 func vmlinuxTestdataSpec(tb testing.TB) *Spec {
57 tb.Helper()
58
59 td, err := vmlinuxTestdata()
60 if err != nil {
61 tb.Fatal(err)
62 }
63
64 return td.spec.Copy()
65 }
66
67 func vmlinuxTestdataBytes(tb testing.TB) []byte {
68 tb.Helper()
69
70 td, err := vmlinuxTestdata()
71 if err != nil {
72 tb.Fatal(err)
73 }
74
75 return td.raw
76 }
77
78 func parseELFBTF(tb testing.TB, file string) *Spec {
79 tb.Helper()
80
81 spec, err := LoadSpec(file)
82 if err != nil {
83 tb.Fatal("Can't load BTF:", err)
84 }
85
86 return spec
87 }
88
89 func TestAnyTypesByName(t *testing.T) {
90 testutils.Files(t, testutils.Glob(t, "testdata/relocs-*.elf"), func(t *testing.T, file string) {
91 spec := parseELFBTF(t, file)
92
93 types, err := spec.AnyTypesByName("ambiguous")
94 if err != nil {
95 t.Fatal(err)
96 }
97
98 if len(types) != 1 {
99 t.Fatalf("expected to receive exactly 1 types from querying ambiguous type, got: %v", types)
100 }
101
102 types, err = spec.AnyTypesByName("ambiguous___flavour")
103 if err != nil {
104 t.Fatal(err)
105 }
106
107 if len(types) != 1 {
108 t.Fatalf("expected to receive exactly 1 type from querying ambiguous flavour, got: %v", types)
109 }
110 })
111 }
112
113 func TestTypeByNameAmbiguous(t *testing.T) {
114 testutils.Files(t, testutils.Glob(t, "testdata/relocs-*.elf"), func(t *testing.T, file string) {
115 spec := parseELFBTF(t, file)
116
117 var typ *Struct
118 if err := spec.TypeByName("ambiguous", &typ); err != nil {
119 t.Fatal(err)
120 }
121
122 if name := typ.TypeName(); name != "ambiguous" {
123 t.Fatal("expected type name 'ambiguous', got:", name)
124 }
125
126 if err := spec.TypeByName("ambiguous___flavour", &typ); err != nil {
127 t.Fatal(err)
128 }
129
130 if name := typ.TypeName(); name != "ambiguous___flavour" {
131 t.Fatal("expected type name 'ambiguous___flavour', got:", name)
132 }
133 })
134 }
135
136 func TestTypeByName(t *testing.T) {
137 spec := vmlinuxTestdataSpec(t)
138
139 for _, typ := range []any{
140 nil,
141 Type(nil),
142 Struct{},
143 &Struct{},
144 []Struct{},
145 &[]Struct{},
146 map[int]Struct{},
147 &map[int]Struct{},
148 int(0),
149 new(int),
150 } {
151 t.Run(fmt.Sprintf("%T", typ), func(t *testing.T) {
152 // spec.TypeByName MUST fail if typ is a nil btf.Type.
153 if err := spec.TypeByName("iphdr", typ); err == nil {
154 t.Fatalf("TypeByName does not fail with type %T", typ)
155 }
156 })
157 }
158
159 // spec.TypeByName MUST return the same address for multiple calls with the same type name.
160 var iphdr1, iphdr2 *Struct
161 if err := spec.TypeByName("iphdr", &iphdr1); err != nil {
162 t.Fatal(err)
163 }
164 if err := spec.TypeByName("iphdr", &iphdr2); err != nil {
165 t.Fatal(err)
166 }
167
168 if iphdr1 != iphdr2 {
169 t.Fatal("multiple TypeByName calls for `iphdr` name do not return the same addresses")
170 }
171
172 // It's valid to pass a *Type to TypeByName.
173 typ := Type(iphdr2)
174 if err := spec.TypeByName("iphdr", &typ); err != nil {
175 t.Fatal("Can't look up using *Type:", err)
176 }
177
178 var nt Type
179 qt.Assert(t, qt.IsNotNil(spec.TypeByName("a", &nt)))
180
181 // Excerpt from linux/ip.h, https://elixir.bootlin.com/linux/latest/A/ident/iphdr
182 //
183 // struct iphdr {
184 // #if defined(__LITTLE_ENDIAN_BITFIELD)
185 // __u8 ihl:4, version:4;
186 // #elif defined (__BIG_ENDIAN_BITFIELD)
187 // __u8 version:4, ihl:4;
188 // #else
189 // ...
190 // }
191 //
192 // The BTF we test against is for little endian.
193 m := iphdr1.Members[1]
194 if m.Name != "version" {
195 t.Fatal("Expected version as the second member, got", m.Name)
196 }
197 td, ok := m.Type.(*Typedef)
198 if !ok {
199 t.Fatalf("version member of iphdr should be a __u8 typedef: actual: %T", m.Type)
200 }
201 u8, ok := td.Type.(*Int)
202 if !ok {
203 t.Fatalf("__u8 typedef should point to an Int type: actual: %T", td.Type)
204 }
205 if m.BitfieldSize != 4 {
206 t.Fatalf("incorrect bitfield size: expected: 4 actual: %d", m.BitfieldSize)
207 }
208 if u8.Encoding != 0 {
209 t.Fatalf("incorrect encoding of an __u8 int: expected: 0 actual: %x", u8.Encoding)
210 }
211 if m.Offset != 4 {
212 t.Fatalf("incorrect bitfield offset: expected: 4 actual: %d", m.Offset)
213 }
214 }
215
216 func BenchmarkParseVmlinux(b *testing.B) {
217 vmlinux := vmlinuxTestdataBytes(b)
218 b.ReportAllocs()
219
220 for b.Loop() {
221 if _, err := loadRawSpec(vmlinux, nil); err != nil {
222 b.Fatal("Can't load BTF:", err)
223 }
224 }
225 }
226
227 func BenchmarkIterateVmlinux(b *testing.B) {
228 vmlinux := vmlinuxTestdataBytes(b)
229 b.ReportAllocs()
230
231 for b.Loop() {
232 spec, err := loadRawSpec(vmlinux, nil)
233 if err != nil {
234 b.Fatal("Can't load BTF:", err)
235 }
236
237 for range spec.All() {
238 }
239 }
240 }
241
242 func TestParseCurrentKernelBTF(t *testing.T) {
243 spec := vmlinuxSpec(t)
244
245 if len(spec.offsets) == 0 {
246 t.Fatal("Empty kernel BTF")
247 }
248 }
249
250 func TestFindVMLinux(t *testing.T) {
251 file, err := findVMLinux()
252 testutils.SkipIfNotSupported(t, err)
253 if err != nil {
254 t.Fatal("Can't find vmlinux:", err)
255 }
256 defer file.Close()
257
258 spec, err := LoadSpecFromReader(file)
259 if err != nil {
260 t.Fatal("Can't load BTF:", err)
261 }
262
263 if len(spec.offsets) == 0 {
264 t.Fatal("Empty kernel BTF")
265 }
266 }
267
268 func TestLoadSpecFromElf(t *testing.T) {
269 testutils.Files(t, testutils.Glob(t, "../testdata/loader-e*.elf"), func(t *testing.T, file string) {
270 spec := parseELFBTF(t, file)
271
272 vt, err := spec.TypeByID(0)
273 if err != nil {
274 t.Error("Can't retrieve void type by ID:", err)
275 }
276 if _, ok := vt.(*Void); !ok {
277 t.Errorf("Expected Void for type id 0, but got: %T", vt)
278 }
279
280 var bpfMapDef *Struct
281 if err := spec.TypeByName("bpf_map_def", &bpfMapDef); err != nil {
282 t.Error("Can't find bpf_map_def:", err)
283 }
284
285 var tmp *Void
286 if err := spec.TypeByName("totally_bogus_type", &tmp); !errors.Is(err, ErrNotFound) {
287 t.Error("TypeByName doesn't return ErrNotFound:", err)
288 }
289
290 var fn *Func
291 if err := spec.TypeByName("global_fn", &fn); err != nil {
292 t.Error("Can't find global_fn():", err)
293 } else {
294 if fn.Linkage != GlobalFunc {
295 t.Error("Expected global linkage:", fn)
296 }
297 }
298
299 var v *Var
300 if err := spec.TypeByName("key3", &v); err != nil {
301 t.Error("Can't find key3:", err)
302 } else {
303 if v.Linkage != GlobalVar {
304 t.Error("Expected global linkage:", v)
305 }
306 }
307 })
308 }
309
310 func TestVerifierError(t *testing.T) {
311 b, err := NewBuilder([]Type{&Int{Encoding: 255}}, nil)
312 qt.Assert(t, qt.IsNil(err))
313 _, err = NewHandle(b)
314 testutils.SkipIfNotSupported(t, err)
315 var ve *internal.VerifierError
316 if !errors.As(err, &ve) {
317 t.Fatalf("expected a VerifierError, got: %v", err)
318 }
319 }
320
321 func TestSpecCopy(t *testing.T) {
322 qt.Check(t, qt.IsNil((*Spec)(nil).Copy()))
323
324 spec := parseELFBTF(t, "../testdata/loader-el.elf")
325 cpy := spec.Copy()
326
327 have := typesFromSpec(t, spec)
328 qt.Assert(t, qt.IsTrue(len(have) > 0))
329
330 want := typesFromSpec(t, cpy)
331 qt.Assert(t, qt.HasLen(want, len(have)))
332
333 for i := range want {
334 if _, ok := have[i].(*Void); ok {
335 // Since Void is an empty struct, a Type interface value containing
336 // &Void{} stores (*Void, nil). Since interface equality first compares
337 // the type and then the concrete value, Void is always equal.
338 continue
339 }
340
341 if have[i] == want[i] {
342 t.Fatalf("Type at index %d is not a copy: %T == %T", i, have[i], want[i])
343 }
344 }
345 }
346
347 func TestSpecCopyModifications(t *testing.T) {
348 spec := specFromTypes(t, []Type{&Int{Name: "a", Size: 4}})
349
350 typ, err := spec.TypeByID(1)
351 qt.Assert(t, qt.IsNil(err))
352
353 i := typ.(*Int)
354 i.Name = "b"
355 i.Size = 2
356
357 cpy := spec.Copy()
358 typ2, err := cpy.TypeByID(1)
359 qt.Assert(t, qt.IsNil(err))
360 i2 := typ2.(*Int)
361
362 qt.Assert(t, qt.Not(qt.Equals(i2, i)), qt.Commentf("Types are distinct"))
363 qt.Assert(t, qt.DeepEquals(i2, i), qt.Commentf("Modifications are preserved"))
364
365 i.Name = "bar"
366 qt.Assert(t, qt.Equals(i2.Name, "b"))
367 }
368
369 func TestSpecTypeByID(t *testing.T) {
370 spec := specFromTypes(t, nil)
371
372 _, err := spec.TypeByID(0)
373 qt.Assert(t, qt.IsNil(err))
374
375 _, err = spec.TypeByID(1)
376 qt.Assert(t, qt.ErrorIs(err, ErrNotFound))
377 }
378
379 func ExampleSpec_TypeByName() {
380 // Acquire a Spec via one of its constructors.
381 spec := new(Spec)
382
383 // Declare a variable of the desired type
384 var foo *Struct
385
386 if err := spec.TypeByName("foo", &foo); err != nil {
387 // There is no struct with name foo, or there
388 // are multiple possibilities.
389 }
390
391 // We've found struct foo
392 fmt.Println(foo.Name)
393 }
394
395 func TestTypesIterator(t *testing.T) {
396 types := []Type{(*Void)(nil), &Int{Size: 4}, &Int{Size: 2}}
397
398 b, err := NewBuilder(types[1:], nil)
399 if err != nil {
400 t.Fatal(err)
401 }
402
403 raw, err := b.Marshal(nil, nil)
404 if err != nil {
405 t.Fatal(err)
406 }
407
408 spec, err := LoadSpecFromReader(bytes.NewReader(raw))
409 if err != nil {
410 t.Fatal(err)
411 }
412
413 var have []Type
414 for typ, err := range spec.All() {
415 qt.Assert(t, qt.IsNil(err))
416 have = append(have, typ)
417 }
418
419 qt.Assert(t, qt.DeepEquals(have, types))
420 }
421
422 func TestLoadSplitSpec(t *testing.T) {
423 spec, err := LoadSpec("testdata/btf_testmod.btf.base")
424 if err != nil {
425 t.Fatal(err)
426 }
427
428 splitSpec, err := LoadSplitSpec("testdata/btf_testmod.btf", spec)
429 if err != nil {
430 t.Fatal(err)
431 }
432
433 var fnType *Func
434 qt.Assert(t, qt.IsNil(splitSpec.TypeByName("bpf_testmod_init", &fnType)))
435 typeID, err := splitSpec.TypeID(fnType)
436 qt.Assert(t, qt.IsNil(err))
437
438 typeByID, err := splitSpec.TypeByID(typeID)
439 qt.Assert(t, qt.IsNil(err))
440 qt.Assert(t, qt.Equals(typeByID, Type(fnType)))
441
442 fnProto := fnType.Type.(*FuncProto)
443 // 'int' is defined in the base BTF...
444 intType, err := spec.AnyTypeByName("int")
445 qt.Assert(t, qt.IsNil(err))
446
447 // ... but not in the split BTF
448 _, err = splitSpec.AnyTypeByName("int")
449 qt.Assert(t, qt.ErrorIs(err, ErrNotFound))
450
451 qt.Assert(t, qt.Equals(fnProto.Return, intType),
452 qt.Commentf("types found in base of split spec should be reused"))
453
454 fnProto.Params = []FuncParam{{"a", &Pointer{(*Void)(nil)}}}
455
456 // The behaviour of copying a split spec is quite subtle. When initially
457 // creating a split spec, types in the split base are shared. This allows
458 // amortising the cost of decoding vmlinux.
459 //
460 // However, we currently define copying a spec to be like forking a process:
461 // in-memory changes to types are preserved. After the copy finished we have
462 // two fully independent states.
463 //
464 // For split BTF this means that we also need to copy the base and ensure
465 // that future references to a modified type work correctly.
466 splitSpecCopy := splitSpec.Copy()
467
468 var fnCopyType *Func
469 qt.Assert(t, qt.IsNil(splitSpecCopy.TypeByName("bpf_testmod_init", &fnCopyType)))
470 qt.Assert(t, testutils.IsDeepCopy(fnCopyType, fnType))
471
472 // Pull out a second type which refers to "int" in the base, but which hasn't
473 // been inflated yet. This forces inflating int from the base.
474 var str *Struct
475 qt.Assert(t, qt.IsNil(splitSpecCopy.TypeByName("bpf_testmod_struct_arg_1", &str)))
476
477 // Ensure that the int types are indeed the same.
478 qt.Assert(t, qt.Equals(str.Members[0].Type, fnCopyType.Type.(*FuncProto).Return))
479
480 copyTypeID, err := splitSpecCopy.TypeID(fnCopyType)
481 qt.Assert(t, qt.IsNil(err))
482 qt.Assert(t, qt.Equals(copyTypeID, typeID), qt.Commentf("ID of copied type must match"))
483 }
484
485 func TestFixupDatasecLayout(t *testing.T) {
486 ds := &Datasec{
487 Size: 0, // Populated by fixup.
488 Vars: []VarSecinfo{
489 {Type: &Var{Type: &Int{Size: 4}}},
490 {Type: &Var{Type: &Int{Size: 1}}},
491 {Type: &Var{Type: &Int{Size: 1}}},
492 {Type: &Var{Type: &Int{Size: 2}}},
493 {Type: &Var{Type: &Int{Size: 16}}},
494 {Type: &Var{Type: &Int{Size: 8}}},
495 },
496 }
497
498 qt.Assert(t, qt.IsNil(fixupDatasecLayout(ds)))
499
500 qt.Assert(t, qt.Equals(ds.Size, 40))
501 qt.Assert(t, qt.Equals(ds.Vars[0].Offset, 0))
502 qt.Assert(t, qt.Equals(ds.Vars[1].Offset, 4))
503 qt.Assert(t, qt.Equals(ds.Vars[2].Offset, 5))
504 qt.Assert(t, qt.Equals(ds.Vars[3].Offset, 6))
505 qt.Assert(t, qt.Equals(ds.Vars[4].Offset, 16))
506 qt.Assert(t, qt.Equals(ds.Vars[5].Offset, 32))
507 }
508
509 func TestSpecConcurrentAccess(t *testing.T) {
510 spec := vmlinuxTestdataSpec(t)
511
512 maxprocs := runtime.GOMAXPROCS(0)
513 if maxprocs < 2 {
514 t.Error("GOMAXPROCS is lower than 2:", maxprocs)
515 }
516
517 var cond atomic.Int64
518 var wg sync.WaitGroup
519 for range maxprocs {
520 wg.Go(func() {
521
522 n := cond.Add(1)
523 for cond.Load() != int64(maxprocs) {
524 // Spin to increase the chances of a race.
525 }
526
527 if n%2 == 0 {
528 _, _ = spec.AnyTypeByName("gov_update_cpu_data")
529 } else {
530 _ = spec.Copy()
531 }
532 })
533
534 // Try to get the Goroutines scheduled and spinning.
535 runtime.Gosched()
536 }
537 wg.Wait()
538 }
539
540 func TestLoadEmptyRawSpec(t *testing.T) {
541 buf, err := binary.Append(nil, binary.LittleEndian, &btfHeader{
542 Magic: btfMagic,
543 Version: 1,
544 Flags: 0,
545 HdrLen: uint32(btfHeaderLen),
546 TypeOff: 0,
547 TypeLen: 0,
548 StringOff: 0,
549 StringLen: 0,
550 })
551 qt.Assert(t, qt.IsNil(err))
552
553 _, err = loadRawSpec(buf, nil)
554 qt.Assert(t, qt.IsNil(err))
555 }
556
557 func BenchmarkSpecCopy(b *testing.B) {
558 spec := vmlinuxTestdataSpec(b)
559
560 for b.Loop() {
561 spec.Copy()
562 }
563 }
564
565 func BenchmarkSpecTypeByID(b *testing.B) {
566 spec := vmlinuxTestdataSpec(b)
567
568 b.ReportAllocs()
569 for b.Loop() {
570 _, err := spec.TypeByID(1)
571 if err != nil {
572 b.Fatal(err)
573 }
574 }
575 }
576
577 func BenchmarkInspektorGadget(b *testing.B) {
578 // This benchmark is the baseline for what Inspektor Gadget loads for a
579 // common configuration.
580 types := []string{
581 "pt_regs",
582 "file",
583 "inode",
584 "super_block",
585 "socket",
586 "syscall_trace_enter",
587 "task_struct",
588 "nsproxy",
589 "mnt_namespace",
590 // "fanotify_event",
591 "pid",
592 "trace_event_raw_sched_process_exec",
593 "fs_struct",
594 "path",
595 "mount",
596 "qstr",
597 "vfsmount",
598 "dentry",
599 // "bpf_func_id",
600 "mm_struct",
601 "syscall_trace_exit",
602 "linux_binprm",
603 "sock",
604 "net",
605 "inet_sock",
606 }
607
608 vmlinux, err := internal.ReadAllCompressed("testdata/vmlinux.btf.gz")
609 qt.Assert(b, qt.IsNil(err))
610
611 var rd bytes.Reader
612
613 for b.Loop() {
614 rd.Reset(vmlinux)
615 spec, err := LoadSpecFromReader(&rd)
616 if err != nil {
617 b.Fatal(err)
618 }
619
620 var s *Struct
621 for _, name := range types {
622 if err := spec.TypeByName(name, &s); err != nil {
623 b.Fatal(name, err)
624 }
625 }
626 }
627 }