Debian Codegraph @

elf_reader_test.go

raw symbols SCIP
1 package ebpf
2
3 import (
4 "bytes"
5 "encoding/binary"
6 "errors"
7 "flag"
8 "fmt"
9 "maps"
10 "os"
11 "path/filepath"
12 "strings"
13 "syscall"
14 "testing"
15
16 "github.com/cilium/ebpf/asm"
17 "github.com/cilium/ebpf/btf"
18 "github.com/cilium/ebpf/internal"
19 "github.com/cilium/ebpf/internal/kallsyms"
20 "github.com/cilium/ebpf/internal/sys"
21 "github.com/cilium/ebpf/internal/testutils"
22
23 "github.com/google/go-cmp/cmp"
24 "github.com/google/go-cmp/cmp/cmpopts"
25
26 "github.com/go-quicktest/qt"
27 )
28
29 var csCmpOpts = cmp.Options{
30 // Dummy Comparer that works with empty readers to support test cases.
31 cmp.Comparer(func(a, b bytes.Reader) bool {
32 if a.Len() == 0 && b.Len() == 0 {
33 return true
34 }
35 return false
36 }),
37 cmpopts.IgnoreTypes(btf.Spec{}),
38 cmpopts.IgnoreFields(CollectionSpec{}, "ByteOrder", "Types"),
39 cmpopts.IgnoreFields(ProgramSpec{}, "Instructions", "ByteOrder"),
40 cmpopts.IgnoreFields(MapSpec{}, "Key", "Value", "Contents"),
41 cmpopts.IgnoreFields(VariableSpec{}, "Type", "Value"),
42 cmpopts.IgnoreUnexported(ProgramSpec{}),
43 }
44
45 func TestLoadCollectionSpec(t *testing.T) {
46 coll := &CollectionSpec{
47 Maps: map[string]*MapSpec{
48 "hash_map": {
49 Name: "hash_map",
50 Type: Hash,
51 KeySize: 4,
52 ValueSize: 8,
53 MaxEntries: 1,
54 Flags: sys.BPF_F_NO_PREALLOC,
55 },
56 "hash_map2": {
57 Name: "hash_map2",
58 Type: Hash,
59 KeySize: 4,
60 ValueSize: 8,
61 MaxEntries: 2,
62 },
63 "perf_event_array": {
64 Name: "perf_event_array",
65 Type: PerfEventArray,
66 MaxEntries: 4096,
67 },
68 ".bss": {
69 Name: ".bss",
70 Type: Array,
71 KeySize: 4,
72 ValueSize: 4,
73 MaxEntries: 1,
74 },
75 ".data": {
76 Name: ".data",
77 Type: Array,
78 KeySize: 4,
79 ValueSize: 4,
80 MaxEntries: 1,
81 },
82 ".data.test": {
83 Name: ".data.test",
84 Type: Array,
85 KeySize: 4,
86 ValueSize: 4,
87 MaxEntries: 1,
88 },
89 ".rodata": {
90 Name: ".rodata",
91 Type: Array,
92 KeySize: 4,
93 ValueSize: 24,
94 MaxEntries: 1,
95 Flags: sys.BPF_F_RDONLY_PROG,
96 },
97 ".rodata.test": {
98 Name: ".rodata.test",
99 Type: Array,
100 KeySize: 4,
101 ValueSize: 4,
102 MaxEntries: 1,
103 Flags: sys.BPF_F_RDONLY_PROG,
104 },
105 ".rodata.cst32": {
106 Name: ".rodata.cst32",
107 Type: Array,
108 KeySize: 4,
109 ValueSize: 32,
110 MaxEntries: 1,
111 Flags: sys.BPF_F_RDONLY_PROG,
112 },
113 },
114 Programs: map[string]*ProgramSpec{
115 "xdp_prog": {
116 Name: "xdp_prog",
117 Type: XDP,
118 SectionName: "xdp",
119 AttachType: AttachXDP,
120 License: "MIT",
121 },
122 "no_relocation": {
123 Name: "no_relocation",
124 Type: SocketFilter,
125 SectionName: "socket",
126 License: "MIT",
127 },
128 "asm_relocation": {
129 Name: "asm_relocation",
130 Type: SocketFilter,
131 SectionName: "socket/2",
132 License: "MIT",
133 },
134 "data_sections": {
135 Name: "data_sections",
136 Type: SocketFilter,
137 SectionName: "socket/3",
138 License: "MIT",
139 },
140 "global_fn3": {
141 Name: "global_fn3",
142 Type: UnspecifiedProgram,
143 SectionName: "other",
144 License: "MIT",
145 },
146 "static_fn": {
147 Name: "static_fn",
148 Type: UnspecifiedProgram,
149 SectionName: "static",
150 License: "MIT",
151 },
152 "anon_const": {
153 Name: "anon_const",
154 Type: SocketFilter,
155 SectionName: "socket/4",
156 License: "MIT",
157 },
158 },
159 Variables: map[string]*VariableSpec{
160 "arg": {Name: "arg", SectionName: ".rodata", Offset: 4},
161 "arg2": {Name: "arg2", SectionName: ".rodata.test", Offset: 0},
162 "arg3": {Name: "arg3", SectionName: ".data.test", Offset: 0},
163 "key1": {Name: "key1", SectionName: ".bss", Offset: 0},
164 "key2": {Name: "key2", SectionName: ".data", Offset: 0},
165 "key3": {Name: "key3", SectionName: ".rodata", Offset: 0},
166 "neg": {Name: "neg", SectionName: ".rodata", Offset: 12},
167 "uneg": {Name: "uneg", SectionName: ".rodata", Offset: 8},
168 },
169 }
170
171 // BTF-only maps.
172 btfOnly := map[string]*MapSpec{
173 "btf_pin": {
174 Name: "btf_pin",
175 Type: Hash,
176 KeySize: 4,
177 ValueSize: 8,
178 MaxEntries: 1,
179 Pinning: PinByName,
180 },
181 "bpf_decl_map": {
182 Name: "bpf_decl_map",
183 Type: Array,
184 KeySize: 4,
185 ValueSize: 8,
186 MaxEntries: 1,
187 Tags: []string{"a", "b"},
188 },
189 "btf_decl_map": {
190 Name: "btf_decl_map",
191 Type: Array,
192 KeySize: 4,
193 ValueSize: 8,
194 MaxEntries: 1,
195 Tags: []string{"a", "b"},
196 },
197 "btf_outer_map": {
198 Name: "btf_outer_map",
199 Type: ArrayOfMaps,
200 KeySize: 4,
201 ValueSize: 4,
202 MaxEntries: 1,
203 InnerMap: &MapSpec{
204 Name: "btf_outer_map_inner",
205 Type: Hash,
206 KeySize: 4,
207 ValueSize: 4,
208 MaxEntries: 1,
209 },
210 },
211 "btf_outer_map_anon": {
212 Name: "btf_outer_map_anon",
213 Type: ArrayOfMaps,
214 KeySize: 4,
215 ValueSize: 4,
216 MaxEntries: 1,
217 InnerMap: &MapSpec{
218 Name: "btf_outer_map_anon_inner",
219 Type: Hash,
220 KeySize: 4,
221 ValueSize: 4,
222 MaxEntries: 1,
223 },
224 },
225 "btf_typedef_map": {
226 Name: "btf_typedef_map",
227 Type: Array,
228 KeySize: 4,
229 ValueSize: 8,
230 MaxEntries: 1,
231 },
232 }
233
234 testutils.Files(t, testutils.Glob(t, "testdata/loader-*.elf"), func(t *testing.T, file string) {
235 got, err := LoadCollectionSpec(file)
236 qt.Assert(t, qt.IsNil(err))
237
238 // BTF map definition contains a value type, but the size should remain 0.
239 // The value type needs to be reflected in the MapSpec.
240 qt.Assert(t, qt.Equals(got.Maps["perf_event_array"].ValueSize, 0))
241 qt.Assert(t, qt.IsNotNil(got.Maps["perf_event_array"].Value))
242
243 // Copy and extend the CollectionSpec with BTF-only objects.
244 want := coll.Copy()
245 maps.Copy(want.Maps, btfOnly)
246
247 testLoadCollectionSpec(t, got, want)
248 })
249
250 testutils.Files(t, testutils.Glob(t, "testdata/loader_nobtf-*.elf"), func(t *testing.T, file string) {
251 got, err := LoadCollectionSpec(file)
252 qt.Assert(t, qt.IsNil(err))
253
254 testLoadCollectionSpec(t, got, coll.Copy())
255 })
256 }
257
258 func testLoadCollectionSpec(t *testing.T, got, want *CollectionSpec) {
259 t.Helper()
260
261 qt.Assert(t, qt.CmpEquals(got, want, csCmpOpts))
262
263 coll, err := newCollection(t, got, &CollectionOptions{
264 Maps: MapOptions{PinPath: testutils.TempBPFFS(t)},
265 Programs: ProgramOptions{LogLevel: LogLevelBranch},
266 })
267 testutils.SkipIfNotSupported(t, err)
268 qt.Assert(t, qt.IsNil(err))
269
270 ret := mustRun(t, coll.Programs["xdp_prog"], nil)
271 qt.Assert(t, qt.Equals(ret, 7))
272 }
273
274 func BenchmarkELFLoader(b *testing.B) {
275 b.ReportAllocs()
276
277 for b.Loop() {
278 _, _ = LoadCollectionSpec("testdata/loader-el.elf")
279 }
280 }
281
282 func TestLoadAndAssign(t *testing.T) {
283 file := testutils.NativeFile(t, "testdata/loader-%s.elf")
284 coll, err := LoadCollectionSpec(file)
285 qt.Assert(t, qt.IsNil(err))
286
287 var obj struct {
288 Program *Program `ebpf:"xdp_prog"`
289 }
290 mustLoadAndAssign(t, coll, &obj, nil)
291 defer obj.Program.Close()
292
293 // Invalid arguments should not panic.
294 qt.Assert(t, qt.IsNotNil(coll.LoadAndAssign(nil, nil)))
295 qt.Assert(t, qt.IsNotNil(coll.LoadAndAssign((*int)(nil), nil)))
296 qt.Assert(t, qt.IsNotNil(coll.LoadAndAssign(0, nil)))
297
298 // Valid objects without an eligible assignment candidate should not error.
299 qt.Assert(t, qt.IsNil(coll.LoadAndAssign(new(struct{ Foo int }), nil)))
300
301 // Unexported, tagged fields are not assignable and should cause an error.
302 var u struct {
303 foo *Map `ebpf:"hash_map"`
304 }
305 qt.Assert(t, qt.IsNotNil(coll.LoadAndAssign(&u, nil)))
306 }
307
308 func TestDataSections(t *testing.T) {
309 file := testutils.NativeFile(t, "testdata/loader-%s.elf")
310 coll, err := LoadCollectionSpec(file)
311 if err != nil {
312 t.Fatal(err)
313 }
314
315 t.Log(coll.Programs["data_sections"].Instructions)
316
317 var obj struct {
318 Program *Program `ebpf:"data_sections"`
319 }
320
321 mustLoadAndAssign(t, coll, &obj, nil)
322 defer obj.Program.Close()
323
324 ret := mustRun(t, obj.Program, nil)
325 if ret != 0 {
326 t.Error("BPF assertion failed on line", ret)
327 }
328 }
329
330 func TestInlineASMConstant(t *testing.T) {
331 file := testutils.NativeFile(t, "testdata/loader-%s.elf")
332 coll, err := LoadCollectionSpec(file)
333 if err != nil {
334 t.Fatal(err)
335 }
336
337 spec := coll.Programs["asm_relocation"]
338 if spec.Instructions[0].Reference() != "MY_CONST" {
339 t.Fatal("First instruction is not a reference to MY_CONST")
340 }
341
342 // -1 is used by the loader to find unrewritten maps.
343 spec.Instructions[0].Constant = -1
344
345 t.Log(spec.Instructions)
346
347 var obj struct {
348 Program *Program `ebpf:"asm_relocation"`
349 }
350
351 mustLoadAndAssign(t, coll, &obj, nil)
352 obj.Program.Close()
353 }
354
355 func TestFreezeRodata(t *testing.T) {
356 testutils.SkipOnOldKernel(t, "5.9", "sk_lookup program type")
357
358 file := testutils.NativeFile(t, "testdata/constants-%s.elf")
359 spec, err := LoadCollectionSpec(file)
360 if err != nil {
361 t.Fatal(err)
362 }
363
364 var obj struct {
365 Program *Program `ebpf:"freeze_rodata"`
366 }
367
368 qt.Assert(t, qt.IsNil(spec.Variables["ret"].Set(uint32(1))))
369
370 mustLoadAndAssign(t, spec, &obj, nil)
371 obj.Program.Close()
372 }
373
374 func TestCollectionSpecDetach(t *testing.T) {
375 coll := Collection{
376 Maps: map[string]*Map{
377 "foo": new(Map),
378 },
379 Programs: map[string]*Program{
380 "bar": new(Program),
381 },
382 }
383
384 foo := coll.DetachMap("foo")
385 if foo == nil {
386 t.Error("Program not returned from DetachMap")
387 }
388
389 if _, ok := coll.Programs["foo"]; ok {
390 t.Error("DetachMap doesn't remove map from Maps")
391 }
392
393 bar := coll.DetachProgram("bar")
394 if bar == nil {
395 t.Fatal("Program not returned from DetachProgram")
396 }
397
398 if _, ok := coll.Programs["bar"]; ok {
399 t.Error("DetachProgram doesn't remove program from Programs")
400 }
401 }
402
403 func TestLoadInvalidMap(t *testing.T) {
404 file := testutils.NativeFile(t, "testdata/invalid_map-%s.elf")
405 cs, err := LoadCollectionSpec(file)
406 if err != nil {
407 t.Fatal("Can't load CollectionSpec", err)
408 }
409
410 ms, ok := cs.Maps["invalid_map"]
411 if !ok {
412 t.Fatal("invalid_map not found in CollectionSpec")
413 }
414
415 m, err := NewMap(ms)
416 t.Log(err)
417 if err == nil {
418 m.Close()
419 t.Fatal("Creating a Map from a MapSpec with non-zero Extra is expected to fail.")
420 }
421 }
422
423 func TestLoadInvalidMapMissingSymbol(t *testing.T) {
424 file := testutils.NativeFile(t, "testdata/invalid_map_static-%s.elf")
425 _, err := LoadCollectionSpec(file)
426 t.Log(err)
427 if err == nil {
428 t.Fatal("Loading a map with static qualifier should fail")
429 }
430 }
431
432 func TestLoadInitializedBTFMap(t *testing.T) {
433 testutils.Files(t, testutils.Glob(t, "testdata/btf_map_init-*.elf"), func(t *testing.T, file string) {
434 coll, err := LoadCollectionSpec(file)
435 if err != nil {
436 t.Fatal(err)
437 }
438
439 t.Run("NewCollection", func(t *testing.T) {
440 _, err := newCollection(t, coll, nil)
441 testutils.SkipIfNotSupported(t, err)
442 if err != nil {
443 t.Fatal("NewCollection failed:", err)
444 }
445 })
446
447 t.Run("prog_array", func(t *testing.T) {
448 m, ok := coll.Maps["prog_array_init"]
449 if !ok {
450 t.Fatal("map prog_array_init not found in program")
451 }
452
453 if len(m.Contents) != 1 {
454 t.Error("expecting exactly 1 item in MapSpec contents")
455 }
456
457 p := m.Contents[0]
458 if cmp.Equal(p.Key, 1) {
459 t.Errorf("expecting MapSpec entry Key to equal 1, got %v", p.Key)
460 }
461
462 if _, ok := p.Value.(string); !ok {
463 t.Errorf("expecting MapSpec entry Value to be a string, got %T", p.Value)
464 }
465
466 if p.Value != "tail_1" {
467 t.Errorf("expected MapSpec entry Value 'tail_1', got: %s", p.Value)
468 }
469 })
470
471 t.Run("array_of_maps", func(t *testing.T) {
472 m, ok := coll.Maps["outer_map_init"]
473 if !ok {
474 t.Fatal("map outer_map_init not found in program")
475 }
476
477 if len(m.Contents) != 1 {
478 t.Error("expecting exactly 1 item in MapSpec contents")
479 }
480
481 if m.Key == nil {
482 t.Error("Expected non-nil key")
483 }
484
485 if m.Value == nil {
486 t.Error("Expected non-nil value")
487 }
488
489 if m.InnerMap.Key == nil {
490 t.Error("Expected non-nil InnerMap key")
491 }
492
493 if m.InnerMap.Value == nil {
494 t.Error("Expected non-nil InnerMap value")
495 }
496
497 p := m.Contents[0]
498 if cmp.Equal(p.Key, 1) {
499 t.Errorf("expecting MapSpec entry Key to equal 1, got %v", p.Key)
500 }
501
502 if _, ok := p.Value.(string); !ok {
503 t.Errorf("expecting MapSpec entry Value to be a string, got %T", p.Value)
504 }
505
506 if p.Value != "inner_map" {
507 t.Errorf("expected MapSpec entry Value 'inner_map', got: %s", p.Value)
508 }
509 })
510 })
511 }
512
513 func TestLoadInvalidInitializedBTFMap(t *testing.T) {
514 file := testutils.NativeFile(t, "testdata/invalid_btf_map_init-%s.elf")
515 _, err := LoadCollectionSpec(file)
516 t.Log(err)
517 if !errors.Is(err, internal.ErrNotSupported) {
518 t.Fatal("Loading an initialized BTF map should be unsupported")
519 }
520 }
521
522 func TestStringSection(t *testing.T) {
523 file := testutils.NativeFile(t, "testdata/strings-%s.elf")
524 spec, err := LoadCollectionSpec(file)
525 if err != nil {
526 t.Fatalf("load collection spec: %s", err)
527 }
528
529 for name := range spec.Maps {
530 t.Log(name)
531 }
532
533 strMap := spec.Maps[".rodata.str1.1"]
534 if strMap == nil {
535 t.Fatal("Unable to find map '.rodata.str1.1' in loaded collection")
536 }
537
538 if !strMap.readOnly() {
539 t.Fatal("Read only data maps should be frozen")
540 }
541
542 if strMap.Flags != sys.BPF_F_RDONLY_PROG {
543 t.Fatal("Read only data maps should have the prog-read-only flag set")
544 }
545
546 coll, err := newCollection(t, spec, nil)
547 testutils.SkipIfNotSupported(t, err)
548 if err != nil {
549 t.Fatalf("new collection: %s", err)
550 }
551
552 prog := coll.Programs["filter"]
553 if prog == nil {
554 t.Fatal("program not found")
555 }
556
557 testMap := coll.Maps["my_map"]
558 if testMap == nil {
559 t.Fatal("test map not found")
560 }
561
562 _, err = prog.Run(&RunOptions{
563 Data: internal.EmptyBPFContext, // Min size for XDP programs
564 })
565 if err != nil {
566 t.Fatalf("prog run: %s", err)
567 }
568
569 key := []byte("This string is allocated in the string section\n\x00")
570 var value uint32
571 if err = testMap.Lookup(&key, &value); err != nil {
572 t.Fatalf("test map lookup: %s", err)
573 }
574
575 if value != 1 {
576 t.Fatal("Test map value not 1!")
577 }
578 }
579
580 func TestLoadRawTracepoint(t *testing.T) {
581 testutils.SkipOnOldKernel(t, "4.17", "BPF_RAW_TRACEPOINT API")
582
583 file := testutils.NativeFile(t, "testdata/raw_tracepoint-%s.elf")
584 spec, err := LoadCollectionSpec(file)
585 if err != nil {
586 t.Fatal("Can't parse ELF:", err)
587 }
588
589 coll, err := NewCollectionWithOptions(spec, CollectionOptions{
590 Programs: ProgramOptions{
591 LogLevel: LogLevelBranch,
592 },
593 })
594 testutils.SkipIfNotSupported(t, err)
595 if err != nil {
596 t.Fatal("Can't create collection:", err)
597 }
598
599 coll.Close()
600 }
601
602 func TestTailCall(t *testing.T) {
603 file := testutils.NativeFile(t, "testdata/btf_map_init-%s.elf")
604 spec, err := LoadCollectionSpec(file)
605 if err != nil {
606 t.Fatal(err)
607 }
608
609 var obj struct {
610 TailMain *Program `ebpf:"tail_main"`
611 ProgArray *Map `ebpf:"prog_array_init"`
612 // Windows evicts programs from the tail call array when the last
613 // user space reference is closed. This is not the case on Linux.
614 Tail *Program `ebpf:"tail_1"`
615 }
616
617 err = loadAndAssign(t, spec, &obj, nil)
618 testutils.SkipIfNotSupported(t, err)
619 if err != nil {
620 t.Fatal(err)
621 }
622 defer obj.TailMain.Close()
623 defer obj.Tail.Close()
624 defer obj.ProgArray.Close()
625
626 ret := mustRun(t, obj.Tail, nil)
627
628 // Expect the tail_1 tail call to be taken, returning value 42.
629 if ret != 42 {
630 t.Fatalf("Expected tail call to return value 42, got %d", ret)
631 }
632 }
633
634 func TestKconfig(t *testing.T) {
635 file := testutils.NativeFile(t, "testdata/kconfig-%s.elf")
636 spec, err := LoadCollectionSpec(file)
637 if err != nil {
638 t.Fatal(err)
639 }
640
641 var obj struct {
642 Main *Program `ebpf:"kconfig"`
643 }
644
645 err = spec.LoadAndAssign(&obj, nil)
646 testutils.SkipIfNotSupported(t, err)
647 if err != nil {
648 t.Fatal(err)
649 }
650 defer obj.Main.Close()
651
652 ret := mustRun(t, obj.Main, nil)
653 qt.Assert(t, qt.Equals(ret, 0), qt.Commentf("Failed assertion at line %d in testdata/kconfig.c", ret))
654 }
655
656 func TestKsym(t *testing.T) {
657 file := testutils.NativeFile(t, "testdata/ksym-%s.elf")
658 spec, err := LoadCollectionSpec(file)
659 qt.Assert(t, qt.IsNil(err))
660
661 var obj struct {
662 Main *Program `ebpf:"ksym_test"`
663 ArrayMap *Map `ebpf:"array_map"`
664 }
665
666 err = spec.LoadAndAssign(&obj, nil)
667 testutils.SkipIfNotSupported(t, err)
668 qt.Assert(t, qt.IsNil(err))
669 defer obj.Main.Close()
670 defer obj.ArrayMap.Close()
671
672 mustRun(t, obj.Main, nil)
673
674 ksyms := map[string]uint64{
675 "bpf_init": 0,
676 "bpf_trace_run1": 0,
677 }
678
679 qt.Assert(t, qt.IsNil(kallsyms.AssignAddresses(ksyms)))
680 qt.Assert(t, qt.Not(qt.Equals(ksyms["bpf_init"], 0)))
681 qt.Assert(t, qt.Not(qt.Equals(ksyms["bpf_trace_run1"], 0)))
682
683 var value uint64
684 qt.Assert(t, qt.IsNil(obj.ArrayMap.Lookup(uint32(0), &value)))
685 qt.Assert(t, qt.Equals(value, ksyms["bpf_init"]))
686
687 qt.Assert(t, qt.IsNil(obj.ArrayMap.Lookup(uint32(1), &value)))
688 qt.Assert(t, qt.Equals(value, ksyms["bpf_trace_run1"]))
689 }
690
691 func TestKsymWeakMissing(t *testing.T) {
692 file := testutils.NativeFile(t, "testdata/ksym-%s.elf")
693 spec, err := LoadCollectionSpec(file)
694 qt.Assert(t, qt.IsNil(err))
695
696 var obj struct {
697 Main *Program `ebpf:"ksym_missing_test"`
698 }
699
700 err = spec.LoadAndAssign(&obj, nil)
701 testutils.SkipIfNotSupported(t, err)
702 qt.Assert(t, qt.IsNil(err))
703 defer obj.Main.Close()
704
705 ret := mustRun(t, obj.Main, nil)
706 qt.Assert(t, qt.Equals(ret, 1))
707 }
708
709 func TestKfunc(t *testing.T) {
710 testutils.SkipOnOldKernel(t, "5.18", "kfunc support")
711 file := testutils.NativeFile(t, "testdata/kfunc-%s.elf")
712 spec, err := LoadCollectionSpec(file)
713 if err != nil {
714 t.Fatal(err)
715 }
716
717 var obj struct {
718 Main *Program `ebpf:"call_kfunc"`
719 }
720
721 err = spec.LoadAndAssign(&obj, nil)
722 testutils.SkipIfNotSupported(t, err)
723 if err != nil {
724 t.Fatalf("%+v", err)
725 }
726 defer obj.Main.Close()
727
728 ret := mustRun(t, obj.Main, nil)
729
730 if ret != 1 {
731 t.Fatalf("Expected kfunc to return value 1, got %d", ret)
732 }
733 }
734
735 func TestWeakKfunc(t *testing.T) {
736 testutils.SkipOnOldKernel(t, "5.18", "kfunc support")
737
738 // CAP_SYS_ADMIN is required to load kfuncs implemented in kernel modules.
739 // Assert that when kfuncs are weak, loading still works without the capability.
740 // CAP_BPF and CAP_PERFMON are still required to load BPF raw tracepoints programs
741 // such as the one in this test.
742 testutils.WithCapabilities(t, []testutils.Capability{testutils.CAP_BPF, testutils.CAP_PERFMON}, func() {
743 file := testutils.NativeFile(t, "testdata/kfunc-%s.elf")
744 spec, err := LoadCollectionSpec(file)
745 if err != nil {
746 t.Fatal(err)
747 }
748
749 var obj struct {
750 Missing *Program `ebpf:"weak_kfunc_missing"`
751 Calling *Program `ebpf:"call_weak_kfunc"`
752 }
753
754 err = spec.LoadAndAssign(&obj, nil)
755 testutils.SkipIfNotSupported(t, err)
756 if err != nil {
757 t.Fatalf("%+v", err)
758 }
759 defer obj.Missing.Close()
760 defer obj.Calling.Close()
761 })
762 }
763
764 func TestInvalidKfunc(t *testing.T) {
765 testutils.SkipOnOldKernel(t, "5.18", "kfunc support")
766 requireTestmod(t)
767
768 file := testutils.NativeFile(t, "testdata/invalid-kfunc-%s.elf")
769 coll, err := LoadCollection(file)
770 if err == nil {
771 coll.Close()
772 t.Fatal("Expected an error")
773 }
774
775 var ike *incompatibleKfuncError
776 if !errors.As(err, &ike) {
777 t.Fatalf("Expected an error wrapping incompatibleKfuncError, got %s", err)
778 }
779 }
780
781 func TestKfuncKmod(t *testing.T) {
782 testutils.SkipOnOldKernel(t, "5.18", "Kernel module function calls")
783 requireTestmod(t)
784
785 file := testutils.NativeFile(t, "testdata/kfunc-kmod-%s.elf")
786 spec, err := LoadCollectionSpec(file)
787 if err != nil {
788 t.Fatal(err)
789 }
790
791 var obj struct {
792 Main *Program `ebpf:"call_kfunc"`
793 }
794
795 err = spec.LoadAndAssign(&obj, nil)
796 testutils.SkipIfNotSupported(t, err)
797 if err != nil {
798 t.Fatalf("%v+", err)
799 }
800 defer obj.Main.Close()
801
802 ret := mustRun(t, obj.Main, nil)
803
804 if ret != 1 {
805 t.Fatalf("Expected kfunc to return value 1, got %d", ret)
806 }
807 }
808
809 func TestSubprogRelocation(t *testing.T) {
810 testutils.SkipOnOldKernel(t, "5.13", "bpf_for_each_map_elem")
811
812 file := testutils.NativeFile(t, "testdata/subprog_reloc-%s.elf")
813 spec, err := LoadCollectionSpec(file)
814 if err != nil {
815 t.Fatal(err)
816 }
817
818 var obj struct {
819 Main *Program `ebpf:"fp_relocation"`
820 HashMap *Map `ebpf:"hash_map"`
821 }
822
823 err = loadAndAssign(t, spec, &obj, nil)
824 testutils.SkipIfNotSupported(t, err)
825 if err != nil {
826 t.Fatal(err)
827 }
828 defer obj.Main.Close()
829 defer obj.HashMap.Close()
830
831 ret := mustRun(t, obj.Main, nil)
832
833 if ret != 42 {
834 t.Fatalf("Expected subprog reloc to return value 42, got %d", ret)
835 }
836 }
837
838 func TestUnassignedProgArray(t *testing.T) {
839 file := testutils.NativeFile(t, "testdata/btf_map_init-%s.elf")
840 spec, err := LoadCollectionSpec(file)
841 if err != nil {
842 t.Fatal(err)
843 }
844
845 // tail_main references a ProgArray that is not being assigned
846 // to this struct. Normally, this would clear all its entries
847 // and make any tail calls into the ProgArray result in a miss.
848 // The library needs to explicitly refuse such operations.
849 var obj struct {
850 TailMain *Program `ebpf:"tail_main"`
851 // ProgArray *Map `ebpf:"prog_array_init"`
852 }
853
854 err = loadAndAssign(t, spec, &obj, nil)
855 testutils.SkipIfNotSupported(t, err)
856 defer obj.TailMain.Close()
857 qt.Assert(t, qt.IsNotNil(err))
858 }
859
860 func TestIPRoute2Compat(t *testing.T) {
861 file := testutils.NativeFile(t, "testdata/iproute2_map_compat-%s.elf")
862 spec, err := LoadCollectionSpec(file)
863 if err != nil {
864 t.Fatal("Can't parse ELF:", err)
865 }
866
867 ms, ok := spec.Maps["hash_map"]
868 if !ok {
869 t.Fatal("Map hash_map not found")
870 }
871
872 var id, pinning, innerID, innerIndex uint32
873
874 if ms.Extra == nil {
875 t.Fatal("missing extra bytes")
876 }
877
878 switch {
879 case binary.Read(ms.Extra, spec.ByteOrder, &id) != nil:
880 t.Fatal("missing id")
881 case binary.Read(ms.Extra, spec.ByteOrder, &pinning) != nil:
882 t.Fatal("missing pinning")
883 case binary.Read(ms.Extra, spec.ByteOrder, &innerID) != nil:
884 t.Fatal("missing inner_id")
885 case binary.Read(ms.Extra, spec.ByteOrder, &innerIndex) != nil:
886 t.Fatal("missing inner_idx")
887 }
888
889 if id != 0 || innerID != 0 || innerIndex != 0 {
890 t.Fatal("expecting id, inner_id and inner_idx to be zero")
891 }
892
893 if pinning != 2 {
894 t.Fatal("expecting pinning field to be 2 (PIN_GLOBAL_NS)")
895 }
896
897 // iproute2 (tc) pins maps in /sys/fs/bpf/tc/globals with PIN_GLOBAL_NS,
898 // which needs to be configured in this library using MapOptions.PinPath.
899 // For the sake of the test, we use a tempdir on bpffs below.
900 ms.Pinning = PinByName
901
902 coll, err := NewCollectionWithOptions(spec, CollectionOptions{
903 Maps: MapOptions{
904 PinPath: testutils.TempBPFFS(t),
905 },
906 })
907 testutils.SkipIfNotSupported(t, err)
908 if err != nil {
909 t.Fatal("Can't create collection:", err)
910 }
911
912 coll.Close()
913 }
914
915 func TestArena(t *testing.T) {
916 file := testutils.NativeFile(t, "testdata/arena-%s.elf")
917 coll, err := LoadCollectionSpec(file)
918 qt.Assert(t, qt.IsNil(err))
919
920 want := &CollectionSpec{
921 Maps: map[string]*MapSpec{
922 "arena": {
923 Name: "arena",
924 Type: Arena,
925 MaxEntries: 100,
926 Flags: sys.BPF_F_MMAPABLE,
927 MapExtra: 1 << 44,
928 },
929 },
930 Programs: map[string]*ProgramSpec{},
931 Variables: map[string]*VariableSpec{},
932 }
933 qt.Assert(t, qt.CmpEquals(coll, want, csCmpOpts))
934
935 testutils.SkipOnOldKernel(t, "6.9", "arena maps")
936 mustNewCollection(t, coll, nil)
937 }
938
939 func TestStructOps(t *testing.T) {
940 file := testutils.NativeFile(t, "testdata/struct_ops-%s.elf")
941 coll, err := LoadCollectionSpec(file)
942 qt.Assert(t, qt.IsNil(err))
943
944 userData := []byte{
945 // test_1 func ptr (8B)
946 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
947 // test_2 func ptr (8B)
948 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
949 // data (4B) + padding (4B)
950 0xef, 0xbe, 0xad, 0xde, 0x00, 0x00, 0x00, 0x00,
951 }
952
953 want := &CollectionSpec{
954 Maps: map[string]*MapSpec{
955 "testmod_ops": {
956 Name: "testmod_ops",
957 Type: StructOpsMap,
958 MaxEntries: 1,
959 Flags: sys.BPF_F_LINK,
960 Key: &btf.Int{Size: 4},
961 KeySize: 4,
962 ValueSize: 24,
963 Value: &btf.Struct{
964 Name: "bpf_testmod_ops",
965 Size: 24,
966 Members: []btf.Member{
967 {
968 Name: "test_1",
969 Type: &btf.Pointer{
970 Target: &btf.FuncProto{
971 Params: []btf.FuncParam{},
972 Return: &btf.Int{Name: "int", Size: 4, Encoding: btf.Signed}}},
973 Offset: 0,
974 },
975 {
976 Name: "test_2",
977 Type: &btf.Pointer{
978 Target: &btf.FuncProto{
979 Params: []btf.FuncParam{
980 {Type: &btf.Int{Name: "int", Size: 4, Encoding: btf.Signed}},
981 {Type: &btf.Int{Name: "int", Size: 4, Encoding: btf.Signed}},
982 },
983 Return: (*btf.Void)(nil),
984 },
985 },
986 Offset: 64,
987 },
988 {
989 Name: "data",
990 Type: &btf.Int{Name: "int", Size: 4, Encoding: btf.Signed},
991 Offset: 128, // bits
992 },
993 },
994 },
995 Contents: []MapKV{
996 {
997 Key: uint32(0),
998 Value: userData,
999 },
1000 },
1001 },
1002 },
1003 Programs: map[string]*ProgramSpec{
1004 "test_1": {
1005 Name: "test_1",
1006 Type: StructOps,
1007 AttachTo: "bpf_testmod_ops:test_1",
1008 License: "GPL",
1009 SectionName: "struct_ops/test_1",
1010 Instructions: asm.Instructions{
1011 asm.Mov.Imm(asm.R0, 0),
1012 asm.Return(),
1013 },
1014 },
1015 },
1016 Variables: map[string]*VariableSpec{},
1017 }
1018
1019 testModOps, ok := coll.Maps["testmod_ops"]
1020 if !ok {
1021 t.Fatalf("testmod_ops doesn't exist")
1022 }
1023
1024 data, ok := testModOps.Contents[0].Value.([]byte)
1025 if !ok {
1026 t.Fatalf("Contents[0].Value should be an array of byte")
1027 }
1028
1029 qt.Assert(t, qt.CmpEquals(coll.Programs, want.Programs, csCmpOpts))
1030 qt.Assert(t, qt.CmpEquals(coll.Maps, want.Maps, csCmpOpts))
1031 qt.Assert(t, qt.CmpEquals(testModOps.Value, want.Maps["testmod_ops"].Value, csCmpOpts))
1032 qt.Assert(t, qt.CmpEquals(data, userData, csCmpOpts))
1033 }
1034
1035 var (
1036 elfPath = flag.String("elfs", os.Getenv("CI_KERNEL_SELFTESTS"), "`Path` containing libbpf-compatible ELFs (defaults to $CI_KERNEL_SELFTESTS)")
1037 elfPattern = flag.String("elf-pattern", "*.o", "Glob `pattern` for object files that should be tested")
1038 )
1039
1040 func TestLibBPFCompat(t *testing.T) {
1041 if *elfPath == "" {
1042 // Specify the path to the directory containing the eBPF for
1043 // the kernel's selftests if you want to run this test.
1044 // As of 5.2 that is tools/testing/selftests/bpf/
1045 t.Skip("No path specified")
1046 }
1047
1048 load := func(t *testing.T, spec *CollectionSpec, opts CollectionOptions, valid bool) {
1049 // Disable retrying a program load with the log enabled, it leads
1050 // to OOM kills.
1051 opts.Programs.LogDisabled = true
1052
1053 coll, err := NewCollectionWithOptions(spec, opts)
1054 testutils.SkipIfNotSupported(t, err)
1055 var errno syscall.Errno
1056 if errors.As(err, &errno) {
1057 // This error is most likely from a syscall and caused by us not
1058 // replicating some fixups done in the selftests or the test
1059 // intentionally failing. This is expected, so skip the test
1060 // instead of failing.
1061 t.Skip("Skipping since the kernel rejected the program:", err)
1062 }
1063 if err == nil {
1064 coll.Close()
1065 }
1066 if !valid {
1067 if err == nil {
1068 t.Fatal("Expected an error during load")
1069 }
1070 } else if err != nil {
1071 t.Fatal("Error during loading:", err)
1072 }
1073 }
1074
1075 files := testutils.Glob(t, filepath.Join(*elfPath, *elfPattern),
1076 // These files are only used as a source of btf.
1077 "btf__core_reloc_*",
1078 )
1079
1080 testutils.Files(t, files, func(t *testing.T, path string) {
1081 name := selftestName(path)
1082 switch name {
1083 case "test_map_in_map", "test_select_reuseport_kern":
1084 t.Skip("Skipping due to missing InnerMap in map definition")
1085 case "test_core_autosize":
1086 t.Skip("Skipping since the test generates dynamic BTF")
1087 case "test_static_linked":
1088 t.Skip("Skipping since .text contains 'subprog' twice")
1089 case "netif_receive_skb",
1090 "local_kptr_stash",
1091 "local_kptr_stash_fail",
1092 "type_cast",
1093 "preempted_bpf_ma_op",
1094 "percpu_alloc_fail":
1095 // Error message like
1096 // fixup for CORERelocation(local_type_id, Struct:"bin_data"[0],
1097 // local_id=27): invalid immediate 31, expected 27 (fixup: local_type_id=27->1)
1098 // See https://github.com/cilium/ebpf/issues/739
1099 t.Skip("Skipping due to bug in libbpf type deduplication")
1100 case "test_usdt", "test_urandom_usdt", "test_usdt_multispec":
1101 t.Skip("Skipping due to missing support for usdt.bpf.h")
1102 case "lsm_cgroup", "bpf_iter_ipv6_route", "test_core_extern",
1103 "profiler1", "profiler2", "profiler3":
1104 t.Skip("Skipping due to using weak CONFIG_* variables")
1105 case "linked_maps", "linked_maps1", "linked_maps2", "linked_funcs1", "linked_funcs2",
1106 "test_subskeleton", "test_subskeleton_lib":
1107 t.Skip("Skipping due to relying on cross ELF linking")
1108 case "test_log_fixup":
1109 t.Skip("Skipping due to intentionally broken CO-RE relocations")
1110 }
1111
1112 t.Parallel()
1113
1114 spec, err := LoadCollectionSpec(path)
1115 testutils.SkipIfNotSupported(t, err)
1116 if errors.Is(err, errUnsupportedBinding) {
1117 t.Skip(err)
1118 }
1119 if err != nil {
1120 t.Fatal(err)
1121 }
1122
1123 switch name {
1124 case "test_sk_assign":
1125 // Test contains a legacy iproute2 bpf_elf_map definition.
1126 for _, m := range spec.Maps {
1127 if m.Extra == nil || m.Extra.Len() == 0 {
1128 t.Fatalf("Expected extra bytes in map %s", m.Name)
1129 }
1130 m.Extra = nil
1131 }
1132
1133 case "fexit_bpf2bpf",
1134 "freplace_get_constant",
1135 "freplace_global_func":
1136 loadTargetProgram(t, spec, "test_pkt_access.bpf.o", "test_pkt_access")
1137
1138 case "freplace_cls_redirect":
1139 loadTargetProgram(t, spec, "test_cls_redirect.bpf.o", "cls_redirect")
1140
1141 case "test_trace_ext":
1142 loadTargetProgram(t, spec, "test_pkt_md_access.bpf.o", "test_pkt_md_access")
1143
1144 case "freplace_progmap":
1145 loadTargetProgram(t, spec, "xdp_dummy.bpf.o", "xdp_dummy_prog")
1146
1147 if prog := spec.Programs["xdp_cpumap_prog"]; prog.AttachTo == "" {
1148 prog.AttachTo = "xdp_dummy_prog"
1149 }
1150
1151 case "freplace_attach_probe":
1152 // Looks like the test should have a target, but 6.6 selftests don't
1153 // seem to be using it.
1154 }
1155
1156 var opts CollectionOptions
1157 for _, mapSpec := range spec.Maps {
1158 if mapSpec.Pinning != PinNone {
1159 opts.Maps.PinPath = testutils.TempBPFFS(t)
1160 break
1161 }
1162 }
1163
1164 coreFiles := sourceOfBTF(t, path)
1165 if len(coreFiles) == 0 {
1166 // NB: test_core_reloc_kernel.o doesn't have dedicated BTF and
1167 // therefore goes via this code path.
1168 load(t, spec, opts, true)
1169 return
1170 }
1171
1172 for _, coreFile := range coreFiles {
1173 name := selftestName(coreFile)
1174 t.Run(name, func(t *testing.T) {
1175 // Some files like btf__core_reloc_arrays___err_too_small.o
1176 // trigger an error on purpose. Use the name to infer whether
1177 // the test should succeed.
1178 var valid bool
1179 switch name {
1180 case "btf__core_reloc_existence___err_wrong_arr_kind",
1181 "btf__core_reloc_existence___err_wrong_arr_value_type",
1182 "btf__core_reloc_existence___err_wrong_int_kind",
1183 "btf__core_reloc_existence___err_wrong_int_sz",
1184 "btf__core_reloc_existence___err_wrong_int_type",
1185 "btf__core_reloc_existence___err_wrong_struct_type":
1186 // These tests are buggy upstream, see https://lore.kernel.org/bpf/[email protected]/
1187 valid = true
1188 case "btf__core_reloc_ints___err_wrong_sz_16",
1189 "btf__core_reloc_ints___err_wrong_sz_32",
1190 "btf__core_reloc_ints___err_wrong_sz_64",
1191 "btf__core_reloc_ints___err_wrong_sz_8",
1192 "btf__core_reloc_arrays___err_wrong_val_type1",
1193 "btf__core_reloc_arrays___err_wrong_val_type2":
1194 // These tests are valid according to current libbpf behaviour,
1195 // see commit 42765ede5c54ca915de5bfeab83be97207e46f68.
1196 valid = true
1197 case "btf__core_reloc_type_id___missing_targets",
1198 "btf__core_reloc_flavors__err_wrong_name":
1199 valid = false
1200 case "btf__core_reloc_ints___err_bitfield":
1201 // Bitfields are now valid.
1202 valid = true
1203 default:
1204 valid = !strings.Contains(name, "___err_")
1205 }
1206
1207 fh, err := os.Open(coreFile)
1208 if err != nil {
1209 t.Fatal(err)
1210 }
1211 defer fh.Close()
1212
1213 btfSpec, err := btf.LoadSpec(coreFile)
1214 if err != nil {
1215 t.Fatal(err)
1216 }
1217
1218 opts := opts // copy
1219 opts.Programs.KernelTypes = btfSpec
1220 load(t, spec, opts, valid)
1221 })
1222 }
1223 })
1224 }
1225
1226 func loadTargetProgram(tb testing.TB, spec *CollectionSpec, file, program string) {
1227 targetSpec, err := LoadCollectionSpec(filepath.Join(*elfPath, file))
1228 if errors.Is(err, os.ErrNotExist) && strings.HasSuffix(file, ".bpf.o") {
1229 // Prior to v6.1 BPF ELF used a plain .o suffix.
1230 file = strings.TrimSuffix(file, ".bpf.o") + ".o"
1231 targetSpec, err = LoadCollectionSpec(filepath.Join(*elfPath, file))
1232 }
1233 if err != nil {
1234 tb.Fatalf("Can't read %s: %s", file, err)
1235 }
1236
1237 qt.Assert(tb, qt.IsNotNil(targetSpec.Programs[program]))
1238
1239 coll, err := NewCollectionWithOptions(targetSpec, CollectionOptions{
1240 Programs: ProgramOptions{LogDisabled: true},
1241 })
1242 if err != nil {
1243 tb.Fatalf("Can't load target: %s", err)
1244 }
1245 tb.Cleanup(func() { coll.Close() })
1246
1247 target := coll.Programs[program]
1248 for _, prog := range spec.Programs {
1249 if prog.Type == Extension && prog.AttachType == AttachNone {
1250 prog.AttachTarget = target
1251 continue
1252 }
1253
1254 if prog.Type == Tracing {
1255 switch prog.AttachType {
1256 case AttachTraceFEntry, AttachTraceFExit, AttachModifyReturn:
1257 prog.AttachTarget = target
1258 continue
1259 }
1260 }
1261 }
1262 }
1263
1264 func sourceOfBTF(tb testing.TB, path string) []string {
1265 const testPrefix = "test_core_reloc_"
1266 const btfPrefix = "btf__core_reloc_"
1267
1268 dir, base := filepath.Split(path)
1269 if !strings.HasPrefix(base, testPrefix) {
1270 return nil
1271 }
1272
1273 base = strings.TrimSuffix(base[len(testPrefix):], ".o")
1274 switch base {
1275 case "bitfields_direct", "bitfields_probed":
1276 base = "bitfields"
1277 }
1278
1279 return testutils.Glob(tb, filepath.Join(dir, btfPrefix+base+"*.o"))
1280 }
1281
1282 func TestELFSectionProgramTypes(t *testing.T) {
1283 type testcase struct {
1284 Section string
1285 ProgramType ProgramType
1286 AttachType AttachType
1287 Flags uint32
1288 Extra string
1289 }
1290
1291 testcases := []testcase{
1292 {"socket", SocketFilter, AttachNone, 0, ""},
1293 {"socket/garbage", SocketFilter, AttachNone, 0, ""},
1294 {"sk_reuseport/migrate", SkReuseport, AttachSkReuseportSelectOrMigrate, 0, ""},
1295 {"sk_reuseport", SkReuseport, AttachSkReuseportSelect, 0, ""},
1296 {"kprobe/", Kprobe, AttachNone, 0, ""},
1297 {"kprobe/func", Kprobe, AttachNone, 0, "func"},
1298 {"uprobe/", Kprobe, AttachNone, 0, ""},
1299 {"kretprobe/", Kprobe, AttachNone, 0, ""},
1300 {"uretprobe/", Kprobe, AttachNone, 0, ""},
1301 {"tc", SchedCLS, AttachNone, 0, ""},
1302 {"classifier", SchedCLS, AttachNone, 0, ""},
1303 {"action", SchedACT, AttachNone, 0, ""},
1304 {"tracepoint/", TracePoint, AttachNone, 0, ""},
1305 {"tp/", TracePoint, AttachNone, 0, ""},
1306 {"raw_tracepoint/", RawTracepoint, AttachNone, 0, ""},
1307 {"raw_tp/", RawTracepoint, AttachNone, 0, ""},
1308 {"raw_tracepoint.w/", RawTracepointWritable, AttachNone, 0, ""},
1309 {"raw_tp.w/", RawTracepointWritable, AttachNone, 0, ""},
1310 {"tp_btf/", Tracing, AttachTraceRawTp, 0, ""},
1311 {"fentry/", Tracing, AttachTraceFEntry, 0, ""},
1312 {"fmod_ret/", Tracing, AttachModifyReturn, 0, ""},
1313 {"fexit/", Tracing, AttachTraceFExit, 0, ""},
1314 {"fentry.s/", Tracing, AttachTraceFEntry, sys.BPF_F_SLEEPABLE, ""},
1315 {"fmod_ret.s/", Tracing, AttachModifyReturn, sys.BPF_F_SLEEPABLE, ""},
1316 {"fexit.s/", Tracing, AttachTraceFExit, sys.BPF_F_SLEEPABLE, ""},
1317 {"freplace/", Extension, AttachNone, 0, ""},
1318 {"lsm/foo", LSM, AttachLSMMac, 0, "foo"},
1319 {"lsm.s/foo", LSM, AttachLSMMac, sys.BPF_F_SLEEPABLE, "foo"},
1320 {"iter/bpf_map", Tracing, AttachTraceIter, 0, "bpf_map"},
1321 {"iter.s/", Tracing, AttachTraceIter, sys.BPF_F_SLEEPABLE, ""},
1322 {"syscall", Syscall, AttachNone, sys.BPF_F_SLEEPABLE, ""},
1323 {"xdp.frags/devmap", XDP, AttachXDPDevMap, sys.BPF_F_XDP_HAS_FRAGS, ""},
1324 {"xdp/devmap", XDP, AttachXDPDevMap, 0, ""},
1325 {"xdp.frags/cpumap", XDP, AttachXDPCPUMap, sys.BPF_F_XDP_HAS_FRAGS, ""},
1326 {"xdp/cpumap", XDP, AttachXDPCPUMap, 0, ""},
1327 {"xdp.frags", XDP, AttachXDP, sys.BPF_F_XDP_HAS_FRAGS, ""},
1328 {"xdp", XDP, AttachXDP, 0, ""},
1329 {"perf_event", PerfEvent, AttachNone, 0, ""},
1330 {"lwt_in", LWTIn, AttachNone, 0, ""},
1331 {"lwt_out", LWTOut, AttachNone, 0, ""},
1332 {"lwt_xmit", LWTXmit, AttachNone, 0, ""},
1333 {"lwt_seg6local", LWTSeg6Local, AttachNone, 0, ""},
1334 {"cgroup_skb/ingress", CGroupSKB, AttachCGroupInetIngress, 0, ""},
1335 {"cgroup_skb/egress", CGroupSKB, AttachCGroupInetEgress, 0, ""},
1336 {"cgroup/skb", CGroupSKB, AttachNone, 0, ""},
1337 {"cgroup/sock_create", CGroupSock, AttachCGroupInetSockCreate, 0, ""},
1338 {"cgroup/sock_release", CGroupSock, AttachCgroupInetSockRelease, 0, ""},
1339 {"cgroup/sock", CGroupSock, AttachCGroupInetSockCreate, 0, ""},
1340 {"cgroup/post_bind4", CGroupSock, AttachCGroupInet4PostBind, 0, ""},
1341 {"cgroup/post_bind6", CGroupSock, AttachCGroupInet6PostBind, 0, ""},
1342 {"cgroup/dev", CGroupDevice, AttachCGroupDevice, 0, ""},
1343 {"sockops", SockOps, AttachCGroupSockOps, 0, ""},
1344 {"sk_skb/stream_parser", SkSKB, AttachSkSKBStreamParser, 0, ""},
1345 {"sk_skb/stream_verdict", SkSKB, AttachSkSKBStreamVerdict, 0, ""},
1346 {"sk_skb/stream_verdict/foo", SkSKB, AttachSkSKBStreamVerdict, 0, ""},
1347 {"sk_skb", SkSKB, AttachNone, 0, ""},
1348 {"sk_skb/bar", SkSKB, AttachNone, 0, ""},
1349 {"sk_msg", SkMsg, AttachSkMsgVerdict, 0, ""},
1350 {"lirc_mode2", LircMode2, AttachLircMode2, 0, ""},
1351 {"flow_dissector", FlowDissector, AttachFlowDissector, 0, ""},
1352 {"cgroup/bind4", CGroupSockAddr, AttachCGroupInet4Bind, 0, ""},
1353 {"cgroup/bind6", CGroupSockAddr, AttachCGroupInet6Bind, 0, ""},
1354 {"cgroup/connect4", CGroupSockAddr, AttachCGroupInet4Connect, 0, ""},
1355 {"cgroup/connect6", CGroupSockAddr, AttachCGroupInet6Connect, 0, ""},
1356 {"cgroup/sendmsg4", CGroupSockAddr, AttachCGroupUDP4Sendmsg, 0, ""},
1357 {"cgroup/sendmsg6", CGroupSockAddr, AttachCGroupUDP6Sendmsg, 0, ""},
1358 {"cgroup/recvmsg4", CGroupSockAddr, AttachCGroupUDP4Recvmsg, 0, ""},
1359 {"cgroup/recvmsg6", CGroupSockAddr, AttachCGroupUDP6Recvmsg, 0, ""},
1360 {"cgroup/getpeername4", CGroupSockAddr, AttachCgroupInet4GetPeername, 0, ""},
1361 {"cgroup/getpeername6", CGroupSockAddr, AttachCgroupInet6GetPeername, 0, ""},
1362 {"cgroup/getsockname4", CGroupSockAddr, AttachCgroupInet4GetSockname, 0, ""},
1363 {"cgroup/getsockname6", CGroupSockAddr, AttachCgroupInet6GetSockname, 0, ""},
1364 {"cgroup/sysctl", CGroupSysctl, AttachCGroupSysctl, 0, ""},
1365 {"cgroup/getsockopt", CGroupSockopt, AttachCGroupGetsockopt, 0, ""},
1366 {"cgroup/setsockopt", CGroupSockopt, AttachCGroupSetsockopt, 0, ""},
1367 {"sk_lookup/", SkLookup, AttachSkLookup, 0, ""},
1368 {"kprobe.multi", Kprobe, AttachTraceKprobeMulti, 0, ""},
1369 {"kretprobe.multi", Kprobe, AttachTraceKprobeMulti, 0, ""},
1370 {"struct_ops", StructOps, AttachNone, 0, ""},
1371 {"struct_ops.s", StructOps, AttachNone, sys.BPF_F_SLEEPABLE, ""},
1372 {"struct_ops/foo", StructOps, AttachNone, 0, ""},
1373 }
1374
1375 for _, tc := range testcases {
1376 t.Run(tc.Section, func(t *testing.T) {
1377 pt, at, fl, extra := getProgType(tc.Section)
1378 have := testcase{tc.Section, pt, at, fl, extra}
1379 qt.Assert(t, qt.DeepEquals(have, tc))
1380 })
1381 }
1382 }
1383
1384 func TestMatchSectionName(t *testing.T) {
1385 for _, testcase := range []struct {
1386 pattern string
1387 input string
1388 matches bool
1389 extra string
1390 }{
1391 {"prefix/", "prefix/", true, ""},
1392 {"prefix/", "prefix/a", true, "a"},
1393 {"prefix/", "prefix/b", true, "b"},
1394 {"prefix/", "prefix", false, ""},
1395 {"prefix/", "junk", false, ""},
1396
1397 {"prefix+", "prefix/", true, ""},
1398 {"prefix+", "prefix/a", true, "a"},
1399 {"prefix+", "prefix/b", true, "b"},
1400 {"prefix+", "prefix", true, ""},
1401 {"prefix+", "junk", false, ""},
1402
1403 {"exact", "exact", true, ""},
1404 {"exact", "exact/", true, ""},
1405 {"exact", "exact/a", true, ""},
1406 {"exact", "exactement", true, ""},
1407 {"exact", "junk", false, ""},
1408 } {
1409 name := fmt.Sprintf("%s:%s", testcase.pattern, testcase.input)
1410 t.Run(name, func(t *testing.T) {
1411 extra, matches := matchSectionName(testcase.input, testcase.pattern)
1412 qt.Assert(t, qt.Equals(matches, testcase.matches))
1413 if testcase.matches {
1414 qt.Assert(t, qt.Equals(extra, testcase.extra))
1415 }
1416 })
1417 }
1418 }
1419
1420 // selftestName takes a path to a file and derives a canonical name from it.
1421 //
1422 // It strips various suffixes used by the selftest build system.
1423 func selftestName(path string) string {
1424 file := filepath.Base(path)
1425
1426 name := strings.TrimSuffix(file, ".o")
1427 // Strip various suffixes.
1428 // Various linking suffixes.
1429 name = strings.TrimSuffix(name, ".linked3")
1430 name = strings.TrimSuffix(name, ".llinked1")
1431 name = strings.TrimSuffix(name, ".llinked2")
1432 name = strings.TrimSuffix(name, ".llinked3")
1433 // v6.1 started adding .bpf to all BPF ELF.
1434 name = strings.TrimSuffix(name, ".bpf")
1435
1436 return name
1437 }