forked from cilium/ebpf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prog_test.go
1177 lines (990 loc) · 25 KB
/
prog_test.go
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package ebpf
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"math"
"os"
"path/filepath"
"runtime"
"slices"
"strings"
"syscall"
"testing"
"time"
"github.com/go-quicktest/qt"
"github.com/cilium/ebpf/asm"
"github.com/cilium/ebpf/btf"
"github.com/cilium/ebpf/internal"
"github.com/cilium/ebpf/internal/sys"
"github.com/cilium/ebpf/internal/testutils"
"github.com/cilium/ebpf/internal/unix"
)
func TestProgramRun(t *testing.T) {
testutils.SkipOnOldKernel(t, "4.8", "XDP program")
pat := []byte{0xDE, 0xAD, 0xBE, 0xEF}
buf := internal.EmptyBPFContext
// r1 : ctx_start
// r1+4: ctx_end
ins := asm.Instructions{
// r2 = *(r1+4)
asm.LoadMem(asm.R2, asm.R1, 4, asm.Word),
// r1 = *(r1+0)
asm.LoadMem(asm.R1, asm.R1, 0, asm.Word),
// r3 = r1
asm.Mov.Reg(asm.R3, asm.R1),
// r3 += len(buf)
asm.Add.Imm(asm.R3, int32(len(buf))),
// if r3 > r2 goto +len(pat)
asm.JGT.Reg(asm.R3, asm.R2, "out"),
}
for i, b := range pat {
ins = append(ins, asm.StoreImm(asm.R1, int16(i), int64(b), asm.Byte))
}
ins = append(ins,
// return 42
asm.LoadImm(asm.R0, 42, asm.DWord).WithSymbol("out"),
asm.Return(),
)
t.Log(ins)
prog, err := NewProgram(&ProgramSpec{
Name: "test",
Type: XDP,
Instructions: ins,
License: "MIT",
})
if err != nil {
t.Fatal(err)
}
defer prog.Close()
p2, err := prog.Clone()
if err != nil {
t.Fatal("Can't clone program")
}
defer p2.Close()
prog.Close()
prog = p2
ret, out, err := prog.Test(buf)
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal(err)
}
if ret != 42 {
t.Error("Expected return value to be 42, got", ret)
}
if !bytes.Equal(out[:len(pat)], pat) {
t.Errorf("Expected %v, got %v", pat, out)
}
}
func TestProgramRunWithOptions(t *testing.T) {
testutils.SkipOnOldKernel(t, "5.15", "XDP ctx_in/ctx_out")
ins := asm.Instructions{
// Return XDP_ABORTED
asm.LoadImm(asm.R0, 0, asm.DWord),
asm.Return(),
}
prog, err := NewProgram(&ProgramSpec{
Name: "test",
Type: XDP,
Instructions: ins,
License: "MIT",
})
if err != nil {
t.Fatal(err)
}
defer prog.Close()
buf := internal.EmptyBPFContext
xdp := sys.XdpMd{
Data: 0,
DataEnd: uint32(len(buf)),
}
xdpOut := sys.XdpMd{}
opts := RunOptions{
Data: buf,
Context: xdp,
ContextOut: &xdpOut,
}
ret, err := prog.Run(&opts)
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal(err)
}
if ret != 0 {
t.Error("Expected return value to be 0, got", ret)
}
if xdp != xdpOut {
t.Errorf("Expect xdp (%+v) == xdpOut (%+v)", xdp, xdpOut)
}
}
func TestProgramRunRawTracepoint(t *testing.T) {
testutils.SkipOnOldKernel(t, "5.10", "RawTracepoint test run")
ins := asm.Instructions{
// Return 0
asm.LoadImm(asm.R0, 0, asm.DWord),
asm.Return(),
}
prog, err := NewProgram(&ProgramSpec{
Name: "test",
Type: RawTracepoint,
Instructions: ins,
License: "MIT",
})
if err != nil {
t.Fatal(err)
}
defer prog.Close()
ret, err := prog.Run(&RunOptions{})
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal(err)
}
if ret != 0 {
t.Error("Expected return value to be 0, got", ret)
}
}
func TestProgramRunEmptyData(t *testing.T) {
testutils.SkipOnOldKernel(t, "5.13", "sk_lookup BPF_PROG_RUN")
ins := asm.Instructions{
// Return SK_DROP
asm.LoadImm(asm.R0, 0, asm.DWord),
asm.Return(),
}
prog, err := NewProgram(&ProgramSpec{
Name: "test",
Type: SkLookup,
AttachType: AttachSkLookup,
Instructions: ins,
License: "MIT",
})
if err != nil {
t.Fatal(err)
}
defer prog.Close()
opts := RunOptions{
Context: sys.SkLookup{
Family: syscall.AF_INET,
},
}
ret, err := prog.Run(&opts)
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal(err)
}
if ret != 0 {
t.Error("Expected return value to be 0, got", ret)
}
}
func TestProgramBenchmark(t *testing.T) {
prog := mustSocketFilter(t)
ret, duration, err := prog.Benchmark(internal.EmptyBPFContext, 1, nil)
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal("Error from Benchmark:", err)
}
if ret != 2 {
t.Error("Expected return value 2, got", ret)
}
if duration == 0 {
t.Error("Expected non-zero duration")
}
}
func TestProgramTestRunInterrupt(t *testing.T) {
testutils.SkipOnOldKernel(t, "5.0", "EINTR from BPF_PROG_TEST_RUN")
prog := mustSocketFilter(t)
var (
tgid = unix.Getpid()
tidChan = make(chan int, 1)
exit = make(chan struct{})
errs = make(chan error, 1)
timeout = time.After(5 * time.Second)
)
defer close(exit)
go func() {
runtime.LockOSThread()
defer func() {
// Wait for the test to allow us to unlock the OS thread, to
// ensure that we don't send SIGUSR1 to the wrong thread.
<-exit
runtime.UnlockOSThread()
}()
tidChan <- unix.Gettid()
// Block this thread in the BPF syscall, so that we can
// trigger EINTR by sending a signal.
opts := RunOptions{
Data: internal.EmptyBPFContext,
Repeat: math.MaxInt32,
Reset: func() {
// We don't know how long finishing the
// test run would take, so flag that we've seen
// an interruption and abort the goroutine.
close(errs)
runtime.Goexit()
},
}
_, _, err := prog.run(&opts)
errs <- err
}()
tid := <-tidChan
for {
err := unix.Tgkill(tgid, tid, unix.SIGUSR1)
if err != nil {
t.Fatal("Can't send signal to goroutine thread:", err)
}
select {
case err, ok := <-errs:
if !ok {
return
}
testutils.SkipIfNotSupported(t, err)
if err == nil {
t.Fatal("testRun wasn't interrupted")
}
t.Fatal("testRun returned an error:", err)
case <-timeout:
t.Fatal("Timed out trying to interrupt the goroutine")
default:
}
}
}
func TestProgramClose(t *testing.T) {
prog := mustSocketFilter(t)
if err := prog.Close(); err != nil {
t.Fatal("Can't close program:", err)
}
}
func TestProgramPin(t *testing.T) {
prog := mustSocketFilter(t)
tmp := testutils.TempBPFFS(t)
path := filepath.Join(tmp, "program")
if err := prog.Pin(path); err != nil {
t.Fatal(err)
}
pinned := prog.IsPinned()
qt.Assert(t, qt.IsTrue(pinned))
prog.Close()
prog, err := LoadPinnedProgram(path, nil)
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal(err)
}
defer prog.Close()
if prog.Type() != SocketFilter {
t.Error("Expected pinned program to have type SocketFilter, but got", prog.Type())
}
if haveObjName() == nil {
if prog.name != "test" {
t.Errorf("Expected program to have object name 'test', got '%s'", prog.name)
}
} else {
if prog.name != "program" {
t.Errorf("Expected program to have file name 'program', got '%s'", prog.name)
}
}
if !prog.IsPinned() {
t.Error("Expected IsPinned to be true")
}
}
func TestProgramUnpin(t *testing.T) {
prog := mustSocketFilter(t)
tmp := testutils.TempBPFFS(t)
path := filepath.Join(tmp, "program")
if err := prog.Pin(path); err != nil {
t.Fatal(err)
}
pinned := prog.IsPinned()
qt.Assert(t, qt.IsTrue(pinned))
if err := prog.Unpin(); err != nil {
t.Fatal("Failed to unpin program:", err)
}
if _, err := os.Stat(path); err == nil {
t.Fatal("Pinned program path still exists after unpinning:", err)
}
}
func TestProgramLoadPinnedWithFlags(t *testing.T) {
// Introduced in commit 6e71b04a8224.
testutils.SkipOnOldKernel(t, "4.14", "file_flags in BPF_OBJ_GET")
prog := mustSocketFilter(t)
tmp := testutils.TempBPFFS(t)
path := filepath.Join(tmp, "program")
if err := prog.Pin(path); err != nil {
t.Fatal(err)
}
prog.Close()
_, err := LoadPinnedProgram(path, &LoadPinOptions{
Flags: math.MaxUint32,
})
testutils.SkipIfNotSupported(t, err)
if !errors.Is(err, unix.EINVAL) {
t.Fatal("Invalid flags don't trigger an error:", err)
}
}
func TestProgramVerifierOutputOnError(t *testing.T) {
_, err := NewProgram(&ProgramSpec{
Type: SocketFilter,
Instructions: asm.Instructions{
asm.Return(),
},
License: "MIT",
})
if err == nil {
t.Fatal("Expected program to be invalid")
}
ve, ok := err.(*VerifierError)
if !ok {
t.Fatal("NewProgram does return an unwrapped VerifierError")
}
if !strings.Contains(ve.Error(), "R0 !read_ok") {
t.Logf("%+v", ve)
t.Error("Missing verifier log in error summary")
}
}
func TestProgramKernelVersion(t *testing.T) {
testutils.SkipOnOldKernel(t, "4.20", "KernelVersion")
prog, err := NewProgram(&ProgramSpec{
Type: Kprobe,
Instructions: asm.Instructions{
asm.LoadImm(asm.R0, 0, asm.DWord),
asm.Return(),
},
KernelVersion: 42,
License: "MIT",
})
if err != nil {
t.Fatal("Could not load Kprobe program")
}
defer prog.Close()
}
func TestProgramVerifierOutput(t *testing.T) {
prog, err := NewProgramWithOptions(socketFilterSpec, ProgramOptions{
LogLevel: LogLevelInstruction,
})
if err != nil {
t.Fatal(err)
}
defer prog.Close()
if prog.VerifierLog == "" {
t.Error("Expected VerifierLog to be present")
}
// Issue 64
_, err = NewProgramWithOptions(&ProgramSpec{
Type: SocketFilter,
Instructions: asm.Instructions{
asm.Mov.Reg(asm.R0, asm.R1),
},
License: "MIT",
}, ProgramOptions{
LogLevel: LogLevelInstruction,
})
if err == nil {
t.Fatal("Expected an error from invalid program")
}
var ve *internal.VerifierError
if !errors.As(err, &ve) {
t.Error("Error is not a VerifierError")
}
}
func TestProgramVerifierLog(t *testing.T) {
check := func(t *testing.T, err error) {
t.Helper()
var ve *internal.VerifierError
qt.Assert(t, qt.ErrorAs(err, &ve))
}
// Generate a base program of sufficient size whose verifier log does not fit
// a 128-byte buffer. This should always result in ENOSPC, setting the
// VerifierError.Truncated flag.
var base asm.Instructions
for i := 0; i < 32; i++ {
base = append(base, asm.Mov.Reg(asm.R0, asm.R1))
}
// Touch R10 (read-only frame pointer) to reliably force a verifier error.
invalid := slices.Clone(base)
invalid = append(invalid, asm.Mov.Reg(asm.R10, asm.R0))
invalid = append(invalid, asm.Return())
valid := slices.Clone(base)
valid = append(valid, asm.Return())
// Start out with testing against the invalid program.
spec := &ProgramSpec{
Type: SocketFilter,
License: "MIT",
Instructions: invalid,
}
// Set an undersized log buffer without explicitly requesting a verifier log
// for an invalid program.
_, err := NewProgramWithOptions(spec, ProgramOptions{})
check(t, err)
// Explicitly request a verifier log for an invalid program.
_, err = NewProgramWithOptions(spec, ProgramOptions{
LogLevel: LogLevelInstruction,
})
check(t, err)
// Run tests against a valid program from here on out.
spec.Instructions = valid
// Don't request a verifier log, only set LogSize. Expect the valid program to
// be created without errors.
prog, err := NewProgramWithOptions(spec, ProgramOptions{})
qt.Assert(t, qt.IsNil(err))
prog.Close()
// Explicitly request verifier log for a valid program. If a log is requested
// and the buffer is too small, ENOSPC occurs even for valid programs.
prog, err = NewProgramWithOptions(spec, ProgramOptions{
LogLevel: LogLevelInstruction,
})
qt.Assert(t, qt.IsNil(err))
prog.Close()
}
func TestProgramWithUnsatisfiedMap(t *testing.T) {
coll, err := LoadCollectionSpec("testdata/loader-el.elf")
if err != nil {
t.Fatal(err)
}
// The program will have at least one map reference.
progSpec := coll.Programs["xdp_prog"]
progSpec.ByteOrder = nil
_, err = NewProgram(progSpec)
testutils.SkipIfNotSupported(t, err)
if !errors.Is(err, asm.ErrUnsatisfiedMapReference) {
t.Fatal("Expected an error wrapping asm.ErrUnsatisfiedMapReference, got", err)
}
t.Log(err)
}
func TestProgramName(t *testing.T) {
if err := haveObjName(); err != nil {
t.Skip(err)
}
prog := mustSocketFilter(t)
var info sys.ProgInfo
if err := sys.ObjInfo(prog.fd, &info); err != nil {
t.Fatal(err)
}
if name := unix.ByteSliceToString(info.Name[:]); name != "test" {
t.Errorf("Name is not test, got '%s'", name)
}
}
func TestSanitizeName(t *testing.T) {
for input, want := range map[string]string{
"test": "test",
"t-est": "test",
"t_est": "t_est",
"hörnchen": "hrnchen",
} {
if have := SanitizeName(input, -1); have != want {
t.Errorf("Wanted '%s' got '%s'", want, have)
}
}
}
func TestProgramCloneNil(t *testing.T) {
p, err := (*Program)(nil).Clone()
if err != nil {
t.Fatal(err)
}
if p != nil {
t.Fatal("Cloning a nil Program doesn't return nil")
}
}
func TestProgramMarshaling(t *testing.T) {
const idx = uint32(0)
arr := createProgramArray(t)
defer arr.Close()
prog := mustSocketFilter(t)
if err := arr.Put(idx, prog); err != nil {
t.Fatal("Can't put program:", err)
}
if err := arr.Lookup(idx, Program{}); err == nil {
t.Fatal("Lookup accepts non-pointer Program")
}
var prog2 *Program
defer prog2.Close()
if err := arr.Lookup(idx, prog2); err == nil {
t.Fatal("Get accepts *Program")
}
testutils.SkipOnOldKernel(t, "4.12", "lookup for ProgramArray")
if err := arr.Lookup(idx, &prog2); err != nil {
t.Fatal("Can't unmarshal program:", err)
}
defer prog2.Close()
if prog2 == nil {
t.Fatal("Unmarshalling set program to nil")
}
}
func TestProgramFromFD(t *testing.T) {
prog := mustSocketFilter(t)
// If you're thinking about copying this, don't. Use
// Clone() instead.
prog2, err := NewProgramFromFD(dupFD(t, prog.FD()))
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal(err)
}
defer prog2.Close()
// Name and type are supposed to be copied from program info.
if haveObjName() == nil && prog2.name != "test" {
t.Errorf("Expected program to have name test, got '%s'", prog2.name)
}
if prog2.typ != SocketFilter {
t.Errorf("Expected program to have type SocketFilter, got '%s'", prog2.typ)
}
}
func TestHaveProgTestRun(t *testing.T) {
testutils.CheckFeatureTest(t, haveProgRun)
}
func TestProgramGetNextID(t *testing.T) {
testutils.SkipOnOldKernel(t, "4.13", "bpf_prog_get_next_id")
// Ensure there is at least one program loaded
_ = mustSocketFilter(t)
// As there can be multiple eBPF programs, we loop over all of them and
// make sure, the IDs increase and the last call will return ErrNotExist
last := ProgramID(0)
for {
next, err := ProgramGetNextID(last)
if errors.Is(err, os.ErrNotExist) {
if last == 0 {
t.Fatal("Got ErrNotExist on the first iteration")
}
break
}
if err != nil {
t.Fatal("Unexpected error:", err)
}
if next <= last {
t.Fatalf("Expected next ID (%d) to be higher than the last ID (%d)", next, last)
}
last = next
}
}
func TestNewProgramFromID(t *testing.T) {
prog := mustSocketFilter(t)
info, err := prog.Info()
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal("Could not get program info:", err)
}
id, ok := info.ID()
if !ok {
t.Skip("Program ID not supported")
}
prog2, err := NewProgramFromID(id)
if err != nil {
t.Fatalf("Can't get FD for program ID %d: %v", id, err)
}
prog2.Close()
// As there can be multiple programs, we use max(uint32) as ProgramID to trigger an expected error.
_, err = NewProgramFromID(ProgramID(math.MaxUint32))
if !errors.Is(err, os.ErrNotExist) {
t.Fatal("Expected ErrNotExist, got:", err)
}
}
func TestProgramRejectIncorrectByteOrder(t *testing.T) {
spec := socketFilterSpec.Copy()
spec.ByteOrder = binary.BigEndian
if spec.ByteOrder == internal.NativeEndian {
spec.ByteOrder = binary.LittleEndian
}
_, err := NewProgram(spec)
if err == nil {
t.Error("Incorrect ByteOrder should be rejected at load time")
}
}
func TestProgramSpecCopy(t *testing.T) {
a := &ProgramSpec{
"test",
1,
1,
"attach",
nil, // Can't copy Program
"section",
asm.Instructions{
asm.Return(),
},
1,
"license",
1,
binary.LittleEndian,
}
qt.Check(t, qt.IsNil((*ProgramSpec)(nil).Copy()))
qt.Assert(t, testutils.IsDeepCopy(a.Copy(), a))
}
func TestProgramSpecTag(t *testing.T) {
arr := createArray(t)
spec := &ProgramSpec{
Type: SocketFilter,
Instructions: asm.Instructions{
asm.LoadImm(asm.R0, -1, asm.DWord),
asm.LoadMapPtr(asm.R1, arr.FD()),
asm.Mov.Imm32(asm.R0, 0),
asm.Return(),
},
License: "MIT",
}
prog, err := NewProgram(spec)
if err != nil {
t.Fatal(err)
}
defer prog.Close()
info, err := prog.Info()
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal(err)
}
tag, err := spec.Tag()
if err != nil {
t.Fatal("Can't calculate tag:", err)
}
if tag != info.Tag {
t.Errorf("Calculated tag %s doesn't match kernel tag %s", tag, info.Tag)
}
}
func TestProgramAttachToKernel(t *testing.T) {
// See https://github.com/torvalds/linux/commit/290248a5b7d829871b3ea3c62578613a580a1744
testutils.SkipOnOldKernel(t, "5.5", "attach_btf_id")
haveTestmod := haveTestmod(t)
tests := []struct {
attachTo string
programType ProgramType
attachType AttachType
flags uint32
}{
{
attachTo: "task_getpgid",
programType: LSM,
attachType: AttachLSMMac,
},
{
attachTo: "inet_dgram_connect",
programType: Tracing,
attachType: AttachTraceFEntry,
},
{
attachTo: "inet_dgram_connect",
programType: Tracing,
attachType: AttachTraceFExit,
},
{
attachTo: "bpf_modify_return_test",
programType: Tracing,
attachType: AttachModifyReturn,
},
{
attachTo: "kfree_skb",
programType: Tracing,
attachType: AttachTraceRawTp,
},
{
attachTo: "bpf_testmod_test_read",
programType: Tracing,
attachType: AttachTraceFEntry,
},
{
attachTo: "bpf_testmod_test_read",
programType: Tracing,
attachType: AttachTraceFExit,
},
{
attachTo: "bpf_testmod_test_read",
programType: Tracing,
attachType: AttachModifyReturn,
},
{
attachTo: "bpf_testmod_test_read",
programType: Tracing,
attachType: AttachTraceRawTp,
},
}
for _, test := range tests {
name := fmt.Sprintf("%s:%s", test.attachType, test.attachTo)
t.Run(name, func(t *testing.T) {
if strings.HasPrefix(test.attachTo, "bpf_testmod_") && !haveTestmod {
t.Skip("bpf_testmod not loaded")
}
prog, err := NewProgram(&ProgramSpec{
AttachTo: test.attachTo,
AttachType: test.attachType,
Instructions: asm.Instructions{
asm.LoadImm(asm.R0, 0, asm.DWord),
asm.Return(),
},
License: "GPL",
Type: test.programType,
Flags: test.flags,
})
if err != nil {
t.Fatal("Can't load program:", err)
}
prog.Close()
})
}
}
func TestProgramKernelTypes(t *testing.T) {
if _, err := os.Stat("/sys/kernel/btf/vmlinux"); os.IsNotExist(err) {
t.Skip("/sys/kernel/btf/vmlinux not present")
}
btfSpec, err := btf.LoadSpec("/sys/kernel/btf/vmlinux")
if err != nil {
t.Fatal(err)
}
prog, err := NewProgramWithOptions(&ProgramSpec{
Type: Tracing,
AttachType: AttachTraceIter,
AttachTo: "bpf_map",
Instructions: asm.Instructions{
asm.Mov.Imm(asm.R0, 0),
asm.Return(),
},
License: "MIT",
}, ProgramOptions{
KernelTypes: btfSpec,
})
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal("NewProgram with Target:", err)
}
prog.Close()
}
func TestProgramBindMap(t *testing.T) {
testutils.SkipOnOldKernel(t, "5.10", "BPF_PROG_BIND_MAP")
arr, err := NewMap(&MapSpec{
Type: Array,
KeySize: 4,
ValueSize: 4,
MaxEntries: 1,
})
if err != nil {
t.Errorf("Failed to load map: %v", err)
}
defer arr.Close()
prog := mustSocketFilter(t)
// The attached map does not contain BTF information. So
// the metadata part of the program will be empty. This
// test just makes sure that we can bind a map to a program.
if err := prog.BindMap(arr); err != nil {
t.Errorf("Failed to bind map to program: %v", err)
}
}
func TestProgramInstructions(t *testing.T) {
name := "test_prog"
spec := &ProgramSpec{
Type: SocketFilter,
Name: name,
Instructions: asm.Instructions{
asm.LoadImm(asm.R0, -1, asm.DWord).WithSymbol(name),
asm.Return(),
},
License: "MIT",
}
prog, err := NewProgram(spec)
if err != nil {
t.Fatal(err)
}
defer prog.Close()
pi, err := prog.Info()
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal(err)
}
insns, err := pi.Instructions()
if err != nil {
t.Fatal(err)
}
tag, err := spec.Tag()
if err != nil {
t.Fatal(err)
}
tagXlated, err := insns.Tag(internal.NativeEndian)
if err != nil {
t.Fatal(err)
}
if tag != tagXlated {
t.Fatalf("tag %s differs from xlated instructions tag %s", tag, tagXlated)
}
}
func TestProgramLoadErrors(t *testing.T) {
testutils.SkipOnOldKernel(t, "4.10", "stable verifier log output")
spec, err := LoadCollectionSpec(testutils.NativeFile(t, "testdata/errors-%s.elf"))
qt.Assert(t, qt.IsNil(err))
var b btf.Builder
raw, err := b.Marshal(nil, nil)
qt.Assert(t, qt.IsNil(err))
empty, err := btf.LoadSpecFromReader(bytes.NewReader(raw))
qt.Assert(t, qt.IsNil(err))
for _, test := range []struct {
name string
want error
}{
{"poisoned_single", errBadRelocation},
{"poisoned_double", errBadRelocation},
{"poisoned_kfunc", errUnknownKfunc},
} {
progSpec := spec.Programs[test.name]
qt.Assert(t, qt.IsNotNil(progSpec))
t.Run(test.name, func(t *testing.T) {
t.Log(progSpec.Instructions)
_, err := NewProgramWithOptions(progSpec, ProgramOptions{
KernelTypes: empty,
})
testutils.SkipIfNotSupported(t, err)
var ve *VerifierError
qt.Assert(t, qt.ErrorAs(err, &ve))
t.Logf("%-5v", ve)
qt.Assert(t, qt.ErrorIs(err, test.want))
})
}
}
func BenchmarkNewProgram(b *testing.B) {
testutils.SkipOnOldKernel(b, "5.18", "kfunc support")
spec, err := LoadCollectionSpec(testutils.NativeFile(b, "testdata/kfunc-%s.elf"))
qt.Assert(b, qt.IsNil(err))
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, err := NewProgram(spec.Programs["benchmark"])