Debian Codegraph @

prog_test.go

raw symbols SCIP
1 package ebpf
2
3 import (
4 "bytes"
5 "encoding/binary"
6 "errors"
7 "fmt"
8 "math"
9 "os"
10 "path/filepath"
11 "runtime"
12 "strings"
13 "syscall"
14 "testing"
15
16 "github.com/go-quicktest/qt"
17
18 "github.com/cilium/ebpf/asm"
19 "github.com/cilium/ebpf/btf"
20 "github.com/cilium/ebpf/internal"
21 "github.com/cilium/ebpf/internal/platform"
22 "github.com/cilium/ebpf/internal/sys"
23 "github.com/cilium/ebpf/internal/testutils"
24 "github.com/cilium/ebpf/internal/unix"
25 )
26
27 func TestProgramRun(t *testing.T) {
28 pat := []byte{0xDE, 0xAD, 0xBE, 0xEF}
29 buf := internal.EmptyBPFContext
30
31 // r1 : ctx_start
32 // r1+4: ctx_end
33 ins := asm.Instructions{
34 // r2 = *(r1+4)
35 asm.LoadMem(asm.R2, asm.R1, 4, asm.Word),
36 // r1 = *(r1+0)
37 asm.LoadMem(asm.R1, asm.R1, 0, asm.Word),
38 // r3 = r1
39 asm.Mov.Reg(asm.R3, asm.R1),
40 // r3 += len(buf)
41 asm.Add.Imm(asm.R3, int32(len(buf))),
42 // if r3 > r2 goto +len(pat)
43 asm.JGT.Reg(asm.R3, asm.R2, "out"),
44 }
45 for i, b := range pat {
46 ins = append(ins, asm.StoreImm(asm.R1, int16(i), int64(b), asm.Byte))
47 }
48 ins = append(ins,
49 // return 42
50 asm.LoadImm(asm.R0, 42, asm.DWord).WithSymbol("out"),
51 asm.Return(),
52 )
53
54 if platform.IsWindows {
55 // Windows uses an incompatible context for XDP. Pointers are
56 // 64 bit.
57 // See https://github.com/microsoft/ebpf-for-windows/issues/3873
58 // r2 = *(r1+8)
59 ins[0] = asm.LoadMem(asm.R2, asm.R1, 8, asm.DWord)
60 // r1 = *(r1+0)
61 ins[1] = asm.LoadMem(asm.R1, asm.R1, 0, asm.DWord)
62 }
63
64 t.Log(ins)
65
66 prog := mustNewProgram(t, &ProgramSpec{
67 Name: "test",
68 Type: XDP,
69 Instructions: ins,
70 License: "MIT",
71 }, nil)
72
73 p2, err := prog.Clone()
74 if err != nil {
75 t.Fatal("Can't clone program")
76 }
77 defer p2.Close()
78
79 prog.Close()
80 prog = p2
81
82 out := make([]byte, len(buf))
83 ret := mustRun(t, prog, &RunOptions{Data: buf, DataOut: out})
84 qt.Assert(t, qt.Equals(ret, 42))
85 qt.Assert(t, qt.DeepEquals(out[:len(pat)], pat))
86 }
87
88 func TestProgramRunWithOptions(t *testing.T) {
89 testutils.SkipOnOldKernel(t, "5.15", "XDP ctx_in/ctx_out")
90
91 buf := internal.EmptyBPFContext
92 var prog *Program
93 var in, out any
94 if platform.IsWindows {
95 type winSampleProgramContext struct {
96 _ uint64 // data_start (currently leaks kernel pointer)
97 _ uint64 // data_end (currently leaks kernel pointer)
98 Uint32Data uint32
99 Uint16Data uint16
100 _ uint16
101 HelperData1 uint32
102 HelperData2 uint32
103 }
104 prog = createProgram(t, WindowsSample, 0)
105 in = &winSampleProgramContext{Uint32Data: 23, HelperData2: 42}
106 out = &winSampleProgramContext{Uint32Data: 23, HelperData2: 42}
107 } else {
108 prog = createProgram(t, XDP, int64(sys.XDP_ABORTED))
109 in = &sys.XdpMd{Data: 0, DataEnd: uint32(len(buf))}
110 out = &sys.XdpMd{}
111 }
112
113 opts := RunOptions{
114 Data: buf,
115 Context: in,
116 ContextOut: out,
117 }
118 ret, err := prog.Run(&opts)
119 testutils.SkipIfNotSupported(t, err)
120 if err != nil {
121 t.Fatal(err)
122 }
123
124 if ret != 0 {
125 t.Error("Expected return value to be 0, got", ret)
126 }
127
128 qt.Assert(t, qt.DeepEquals(out, in))
129 }
130
131 func TestProgramRunRawTracepoint(t *testing.T) {
132 testutils.SkipOnOldKernel(t, "5.10", "RawTracepoint test run")
133
134 prog := createProgram(t, RawTracepoint, 0)
135
136 ret, err := prog.Run(&RunOptions{})
137 testutils.SkipIfNotSupported(t, err)
138 if err != nil {
139 t.Fatal(err)
140 }
141
142 if ret != 0 {
143 t.Error("Expected return value to be 0, got", ret)
144 }
145 }
146
147 func TestProgramRunEmptyData(t *testing.T) {
148 prog := createProgram(t, SocketFilter, 0)
149 _, err := prog.Run(nil)
150 testutils.SkipIfNotSupported(t, err)
151 qt.Assert(t, qt.ErrorIs(err, unix.EINVAL))
152 }
153
154 func TestProgramBenchmark(t *testing.T) {
155 if platform.IsWindows {
156 t.Skip("BPF_PROG_TEST_RUN requires providing context on Windows")
157 }
158
159 prog := createBasicProgram(t)
160
161 ret, duration, err := prog.Benchmark(internal.EmptyBPFContext, 1, nil)
162 testutils.SkipIfNotSupported(t, err)
163 if err != nil {
164 t.Fatal("Error from Benchmark:", err)
165 }
166
167 if ret != 2 {
168 t.Error("Expected return value 2, got", ret)
169 }
170
171 if duration == 0 {
172 t.Error("Expected non-zero duration")
173 }
174 }
175
176 func TestProgramClose(t *testing.T) {
177 prog := createBasicProgram(t)
178
179 if err := prog.Close(); err != nil {
180 t.Fatal("Can't close program:", err)
181 }
182 }
183
184 func TestProgramPin(t *testing.T) {
185 spec := fixupProgramSpec(basicProgramSpec)
186 prog := mustNewProgram(t, spec, nil)
187
188 tmp := testutils.TempBPFFS(t)
189
190 path := filepath.Join(tmp, "program")
191 if err := prog.Pin(path); err != nil {
192 t.Fatal(err)
193 }
194
195 pinned := prog.IsPinned()
196 qt.Assert(t, qt.IsTrue(pinned))
197
198 prog.Close()
199
200 prog, err := LoadPinnedProgram(path, nil)
201 testutils.SkipIfNotSupported(t, err)
202 if err != nil {
203 t.Fatal(err)
204 }
205 defer prog.Close()
206
207 qt.Assert(t, qt.Equals(prog.Type(), spec.Type))
208
209 if haveObjName() == nil {
210 qt.Assert(t, qt.Equals(prog.name, "test"))
211 } else {
212 qt.Assert(t, qt.Equals(prog.name, "program"))
213 }
214
215 if !prog.IsPinned() {
216 t.Error("Expected IsPinned to be true")
217 }
218 }
219
220 func TestProgramUnpin(t *testing.T) {
221 prog := createBasicProgram(t)
222
223 tmp := testutils.TempBPFFS(t)
224
225 path := filepath.Join(tmp, "program")
226 if err := prog.Pin(path); err != nil {
227 t.Fatal(err)
228 }
229
230 pinned := prog.IsPinned()
231 qt.Assert(t, qt.IsTrue(pinned))
232
233 if err := prog.Unpin(); err != nil {
234 t.Fatal("Failed to unpin program:", err)
235 }
236 if _, err := os.Stat(path); err == nil {
237 t.Fatal("Pinned program path still exists after unpinning:", err)
238 }
239 }
240
241 func TestProgramLoadPinnedWithFlags(t *testing.T) {
242 // Introduced in commit 6e71b04a8224.
243 testutils.SkipOnOldKernel(t, "4.14", "file_flags in BPF_OBJ_GET")
244
245 prog := createBasicProgram(t)
246
247 tmp := testutils.TempBPFFS(t)
248
249 path := filepath.Join(tmp, "program")
250 if err := prog.Pin(path); err != nil {
251 t.Fatal(err)
252 }
253
254 prog.Close()
255
256 _, err := LoadPinnedProgram(path, &LoadPinOptions{
257 Flags: math.MaxUint32,
258 })
259 testutils.SkipIfNotSupported(t, err)
260 if !errors.Is(err, unix.EINVAL) {
261 t.Fatal("Invalid flags don't trigger an error:", err)
262 }
263 }
264
265 func TestProgramVerifierOutputOnError(t *testing.T) {
266 _, err := newProgram(t, &ProgramSpec{
267 Type: SocketFilter,
268 Instructions: asm.Instructions{
269 asm.Return(),
270 },
271 License: "MIT",
272 }, nil)
273 if err == nil {
274 t.Fatal("Expected program to be invalid")
275 }
276
277 ve, ok := err.(*VerifierError)
278 if !ok {
279 t.Fatal("NewProgram does return an unwrapped VerifierError")
280 }
281
282 switch {
283 case platform.IsLinux:
284 if !strings.Contains(ve.Error(), "R0 !read_ok") {
285 t.Logf("%+v", ve)
286 t.Error("Missing verifier log in error summary")
287 }
288 case platform.IsWindows:
289 if !strings.Contains(ve.Error(), "r0.type == number") {
290 t.Logf("%+v", ve)
291 t.Error("Missing verifier log in error summary")
292 }
293 default:
294 t.Error("Unsupported platform", runtime.GOOS)
295 }
296 }
297
298 func TestProgramKernelVersion(t *testing.T) {
299 testutils.SkipOnOldKernel(t, "4.20", "KernelVersion")
300
301 _ = mustNewProgram(t, &ProgramSpec{
302 Type: Kprobe,
303 Instructions: asm.Instructions{
304 asm.LoadImm(asm.R0, 0, asm.DWord),
305 asm.Return(),
306 },
307 KernelVersion: 42,
308 License: "MIT",
309 }, nil)
310 }
311
312 func TestProgramVerifierLog(t *testing.T) {
313 check := func(t *testing.T, err error) {
314 t.Helper()
315
316 var ve *internal.VerifierError
317 qt.Assert(t, qt.ErrorAs(err, &ve))
318 loglen := 0
319 for _, line := range ve.Log {
320 loglen += len(line)
321 }
322 qt.Assert(t, qt.IsTrue(loglen > 0))
323 }
324
325 // Touch R10 (read-only frame pointer) to reliably force a verifier error.
326 invalid := asm.Instructions{
327 asm.Mov.Reg(asm.R10, asm.R0),
328 asm.Return(),
329 }
330
331 valid := asm.Instructions{
332 asm.Mov.Imm(asm.R0, 0),
333 asm.Return(),
334 }
335
336 // Start out with testing against the invalid program.
337 spec := &ProgramSpec{
338 Type: SocketFilter,
339 License: "MIT",
340 Instructions: invalid,
341 }
342
343 // Don't explicitly request a verifier log for an invalid program.
344 _, err := newProgram(t, spec, nil)
345 check(t, err)
346
347 // Disabling the verifier log should result in a VerifierError without a log.
348 _, err = newProgram(t, spec, &ProgramOptions{
349 LogDisabled: true,
350 })
351 var ve *internal.VerifierError
352 qt.Assert(t, qt.ErrorAs(err, &ve))
353 qt.Assert(t, qt.HasLen(ve.Log, 0))
354
355 // Explicitly request a verifier log for an invalid program.
356 _, err = newProgram(t, spec, &ProgramOptions{
357 LogLevel: LogLevelInstruction,
358 })
359 check(t, err)
360
361 // Run tests against a valid program from here on out.
362 spec.Instructions = valid
363
364 // Don't request a verifier log, expect the valid program to be created
365 // without errors.
366 prog := mustNewProgram(t, spec, nil)
367 qt.Assert(t, qt.HasLen(prog.VerifierLog, 0))
368
369 // Explicitly request verifier log for a valid program.
370 prog = mustNewProgram(t, spec, &ProgramOptions{
371 LogLevel: LogLevelInstruction,
372 })
373 qt.Assert(t, qt.Not(qt.HasLen(prog.VerifierLog, 0)))
374 }
375
376 func TestProgramVerifierLogRetry(t *testing.T) {
377 someError := errors.New("not a buffer error")
378
379 t.Run("retry with oversized buffer, no log_true_size", func(t *testing.T) {
380 // First load failure, without logging enabled. Retry with logging enabled.
381 attr := &sys.ProgLoadAttr{LogLevel: 0, LogSize: 0}
382 qt.Assert(t, qt.IsTrue(retryLogAttrs(attr, 0, someError)))
383 qt.Assert(t, qt.Equals(attr.LogLevel, LogLevelBranch))
384 qt.Assert(t, qt.Equals(attr.LogSize, minVerifierLogSize))
385
386 // Second failure with logging enabled. No buffer error, don't retry.
387 qt.Assert(t, qt.IsFalse(retryLogAttrs(attr, 0, someError)))
388 qt.Assert(t, qt.Equals(attr.LogLevel, LogLevelBranch))
389 qt.Assert(t, qt.Equals(attr.LogSize, minVerifierLogSize))
390 })
391
392 t.Run("retry with oversized buffer, with log_true_size", func(t *testing.T) {
393 // First load failure, without logging enabled. Retry with larger buffer.
394 attr := &sys.ProgLoadAttr{LogLevel: 0, LogSize: 0}
395 qt.Assert(t, qt.IsTrue(retryLogAttrs(attr, 0, someError)))
396
397 // Buffer was sufficiently large and log_true_size was set. Don't retry and
398 // don't modify LogSize to LogTrueSize.
399 attr.LogTrueSize = 123
400 qt.Assert(t, qt.IsFalse(retryLogAttrs(attr, 0, someError)))
401 qt.Assert(t, qt.Equals(attr.LogSize, minVerifierLogSize))
402 })
403
404 t.Run("retry with undersized buffer, no log_true_size", func(t *testing.T) {
405 // First load failure, without logging enabled. Retry with larger buffer.
406 attr := &sys.ProgLoadAttr{LogLevel: 0, LogSize: 0}
407 qt.Assert(t, qt.IsTrue(retryLogAttrs(attr, 0, someError)))
408
409 // Second failure, this time the kernel signals an undersized buffer. Retry
410 // with double the size.
411 qt.Assert(t, qt.IsTrue(retryLogAttrs(attr, 0, unix.ENOSPC)))
412 qt.Assert(t, qt.Equals(attr.LogSize, minVerifierLogSize*2))
413 })
414
415 t.Run("retry with undersized buffer, with log_true_size", func(t *testing.T) {
416 // First load failure, without logging enabled. Retry with larger buffer.
417 attr := &sys.ProgLoadAttr{LogLevel: 0, LogSize: 0}
418 qt.Assert(t, qt.IsTrue(retryLogAttrs(attr, 0, someError)))
419
420 // Second failure, the kernel signals undersized buffer and also sets
421 // log_true_size. Retry with the exact size required.
422 attr.LogTrueSize = 123
423 qt.Assert(t, qt.IsTrue(retryLogAttrs(attr, 0, unix.ENOSPC)))
424 qt.Assert(t, qt.Equals(attr.LogSize, 123))
425 })
426
427 t.Run("grow to maximum buffer size", func(t *testing.T) {
428 // Previous loads pushed the log size to (or above) half of the maximum,
429 // which would make it overflow on the next retry. Make sure the log size
430 // actually hits the maximum so we can bail out.
431 attr := &sys.ProgLoadAttr{LogLevel: LogLevelBranch, LogSize: maxVerifierLogSize / 2}
432 qt.Assert(t, qt.IsTrue(retryLogAttrs(attr, 0, unix.ENOSPC)))
433 qt.Assert(t, qt.Equals(attr.LogSize, maxVerifierLogSize))
434
435 // Don't retry if the buffer is already at the maximum size, no matter
436 // the return code.
437 qt.Assert(t, qt.IsFalse(retryLogAttrs(attr, 0, someError)))
438 qt.Assert(t, qt.IsFalse(retryLogAttrs(attr, 0, unix.ENOSPC)))
439 })
440
441 t.Run("start at maximum buffer size", func(t *testing.T) {
442 // The user requested a log buffer exceeding the maximum size, but no log
443 // level. Retry with the maximum size and default log level.
444 attr := &sys.ProgLoadAttr{LogLevel: 0, LogSize: 0}
445 qt.Assert(t, qt.IsTrue(retryLogAttrs(attr, math.MaxUint32, unix.EINVAL)))
446 qt.Assert(t, qt.Equals(attr.LogLevel, LogLevelBranch))
447 qt.Assert(t, qt.Equals(attr.LogSize, maxVerifierLogSize))
448
449 // Log still doesn't fit maximum-size buffer. Don't retry.
450 qt.Assert(t, qt.IsFalse(retryLogAttrs(attr, 0, unix.ENOSPC)))
451 })
452
453 t.Run("ensure growth terminates within max attempts", func(t *testing.T) {
454 attr := &sys.ProgLoadAttr{LogLevel: 0, LogSize: 0}
455 var terminated bool
456 for i := 1; i <= maxVerifierAttempts; i++ {
457 if !retryLogAttrs(attr, 0, syscall.ENOSPC) {
458 terminated = true
459 }
460 }
461 qt.Assert(t, qt.IsTrue(terminated))
462 })
463 }
464
465 func TestProgramWithUnsatisfiedMap(t *testing.T) {
466 coll, err := LoadCollectionSpec("testdata/loader-el.elf")
467 if err != nil {
468 t.Fatal(err)
469 }
470
471 // The program will have at least one map reference.
472 progSpec := coll.Programs["xdp_prog"]
473 progSpec.ByteOrder = nil
474
475 _, err = newProgram(t, progSpec, nil)
476 if !errors.Is(err, asm.ErrUnsatisfiedMapReference) {
477 t.Fatal("Expected an error wrapping asm.ErrUnsatisfiedMapReference, got", err)
478 }
479 t.Log(err)
480 }
481
482 func TestProgramName(t *testing.T) {
483 testutils.SkipIfNotSupported(t, haveObjName())
484
485 prog := mustNewProgram(t, &ProgramSpec{
486 Name: "test*123",
487 Type: SocketFilter,
488 Instructions: asm.Instructions{
489 asm.LoadImm(asm.R0, 1, asm.DWord),
490 asm.Return(),
491 },
492 License: "MIT",
493 }, nil)
494
495 var info sys.ProgInfo
496 if err := sys.ObjInfo(prog.fd, &info); err != nil {
497 t.Fatal(err)
498 }
499
500 name := unix.ByteSliceToString(info.Name[:])
501 qt.Assert(t, qt.Equals(name, "test123"))
502 }
503
504 func TestProgramCloneNil(t *testing.T) {
505 p, err := (*Program)(nil).Clone()
506 if err != nil {
507 t.Fatal(err)
508 }
509
510 if p != nil {
511 t.Fatal("Cloning a nil Program doesn't return nil")
512 }
513 }
514
515 func TestProgramMarshaling(t *testing.T) {
516 const idx = uint32(0)
517
518 arr := createMap(t, ProgramArray, 1)
519 defer arr.Close()
520
521 if err := arr.Put(idx, (*Program)(nil)); err == nil {
522 t.Fatal("Put accepted a nil Program")
523 }
524
525 prog := createBasicProgram(t)
526
527 if err := arr.Put(idx, prog); err != nil {
528 t.Fatal("Can't put program:", err)
529 }
530
531 if err := arr.Lookup(idx, Program{}); err == nil {
532 t.Fatal("Lookup accepts non-pointer Program")
533 }
534
535 var prog2 *Program
536 defer prog2.Close()
537
538 if err := arr.Lookup(idx, prog2); err == nil {
539 t.Fatal("Get accepts *Program")
540 }
541
542 testutils.SkipOnOldKernel(t, "4.12", "lookup for ProgramArray")
543
544 if err := arr.Lookup(idx, &prog2); err != nil {
545 t.Fatal("Can't unmarshal program:", err)
546 }
547 defer prog2.Close()
548
549 if prog2 == nil {
550 t.Fatal("Unmarshalling set program to nil")
551 }
552 }
553
554 func TestProgramFromFD(t *testing.T) {
555 spec := fixupProgramSpec(basicProgramSpec)
556 prog := mustNewProgram(t, spec, nil)
557
558 // If you're thinking about copying this, don't. Use
559 // Clone() instead.
560 prog2, err := NewProgramFromFD(testutils.DupFD(t, prog.FD()))
561 testutils.SkipIfNotSupported(t, err)
562 if err != nil {
563 t.Fatal(err)
564 }
565 defer prog2.Close()
566
567 // Name and type are supposed to be copied from program info.
568 if haveObjName() == nil && prog2.name != "test" {
569 t.Errorf("Expected program to have name test, got '%s'", prog2.name)
570 }
571
572 qt.Assert(t, qt.Equals(prog2.Type(), spec.Type))
573 }
574
575 func TestHaveProgTestRun(t *testing.T) {
576 testutils.CheckFeatureTest(t, haveProgRun)
577 }
578
579 func TestProgramGetNextID(t *testing.T) {
580 testutils.SkipOnOldKernel(t, "4.13", "bpf_prog_get_next_id")
581
582 // Ensure there is at least one program loaded
583 _ = createBasicProgram(t)
584
585 // As there can be multiple eBPF programs, we loop over all of them and
586 // make sure, the IDs increase and the last call will return ErrNotExist
587 last := ProgramID(0)
588 for {
589 next, err := ProgramGetNextID(last)
590 if errors.Is(err, os.ErrNotExist) {
591 if last == 0 {
592 t.Fatal("Got ErrNotExist on the first iteration")
593 }
594 break
595 }
596 if err != nil {
597 t.Fatal("Unexpected error:", err)
598 }
599 if next <= last {
600 t.Fatalf("Expected next ID (%d) to be higher than the last ID (%d)", next, last)
601 }
602 last = next
603 }
604 }
605
606 func TestNewProgramFromID(t *testing.T) {
607 prog := createBasicProgram(t)
608
609 info, err := prog.Info()
610 testutils.SkipIfNotSupported(t, err)
611 if err != nil {
612 t.Fatal("Could not get program info:", err)
613 }
614
615 id, ok := info.ID()
616 if !ok {
617 t.Skip("Program ID not supported")
618 }
619
620 prog2, err := NewProgramFromID(id)
621 if err != nil {
622 t.Fatalf("Can't get FD for program ID %d: %v", id, err)
623 }
624 prog2.Close()
625
626 // As there can be multiple programs, we use max(uint32) as ProgramID to trigger an expected error.
627 _, err = NewProgramFromID(ProgramID(math.MaxUint32))
628 if !errors.Is(err, os.ErrNotExist) {
629 t.Fatal("Expected ErrNotExist, got:", err)
630 }
631 }
632
633 func TestProgramRejectIncorrectByteOrder(t *testing.T) {
634 spec := basicProgramSpec.Copy()
635
636 spec.ByteOrder = binary.BigEndian
637 if spec.ByteOrder == internal.NativeEndian {
638 spec.ByteOrder = binary.LittleEndian
639 }
640
641 _, err := newProgram(t, spec, nil)
642 if err == nil {
643 t.Error("Incorrect ByteOrder should be rejected at load time")
644 }
645 }
646
647 // This uses unkeyed fields on purpose to force setting a non-zero value when
648 // a new field is added.
649 func TestProgramSpecCopy(t *testing.T) {
650 a := &ProgramSpec{
651 "test",
652 1,
653 1,
654 1,
655 "attach",
656 nil, // Can't copy Program
657 "section",
658 asm.Instructions{
659 asm.Return(),
660 },
661 1,
662 "license",
663 1,
664 binary.LittleEndian,
665 }
666
667 qt.Check(t, qt.IsNil((*ProgramSpec)(nil).Copy()))
668 qt.Assert(t, testutils.IsDeepCopy(a.Copy(), a))
669 }
670
671 func TestProgramSpecCompatible(t *testing.T) {
672 arr := createMap(t, Array, 2)
673
674 spec := &ProgramSpec{
675 Type: SocketFilter,
676 Instructions: asm.Instructions{
677 asm.LoadImm(asm.R0, -1, asm.DWord),
678 asm.LoadMapPtr(asm.R1, arr.FD()),
679 asm.Mov.Imm32(asm.R0, 0),
680 asm.Return(),
681 },
682 License: "MIT",
683 }
684
685 prog := mustNewProgram(t, spec, nil)
686
687 info, err := prog.Info()
688 testutils.SkipIfNotSupported(t, err)
689 qt.Assert(t, qt.IsNil(err))
690
691 err = spec.Compatible(info)
692 testutils.SkipIfNotSupportedOnOS(t, err)
693 qt.Assert(t, qt.IsNil(err))
694 }
695
696 func TestProgramAttachToKernel(t *testing.T) {
697 // See https://github.com/torvalds/linux/commit/290248a5b7d829871b3ea3c62578613a580a1744
698 testutils.SkipOnOldKernel(t, "5.5", "attach_btf_id")
699
700 tests := []struct {
701 attachTo string
702 programType ProgramType
703 attachType AttachType
704 flags uint32
705 }{
706 {
707 attachTo: "task_getpgid",
708 programType: LSM,
709 attachType: AttachLSMMac,
710 },
711 {
712 attachTo: "inet_dgram_connect",
713 programType: Tracing,
714 attachType: AttachTraceFEntry,
715 },
716 {
717 attachTo: "inet_dgram_connect",
718 programType: Tracing,
719 attachType: AttachTraceFExit,
720 },
721 {
722 attachTo: "bpf_modify_return_test",
723 programType: Tracing,
724 attachType: AttachModifyReturn,
725 },
726 {
727 attachTo: "kfree_skb",
728 programType: Tracing,
729 attachType: AttachTraceRawTp,
730 },
731 {
732 attachTo: "bpf_testmod_test_read",
733 programType: Tracing,
734 attachType: AttachTraceFEntry,
735 },
736 {
737 attachTo: "bpf_testmod_test_read",
738 programType: Tracing,
739 attachType: AttachTraceFExit,
740 },
741 {
742 attachTo: "bpf_testmod_test_read",
743 programType: Tracing,
744 attachType: AttachModifyReturn,
745 },
746 {
747 attachTo: "bpf_testmod_test_read",
748 programType: Tracing,
749 attachType: AttachTraceRawTp,
750 },
751 }
752 for _, test := range tests {
753 name := fmt.Sprintf("%s:%s", test.attachType, test.attachTo)
754 t.Run(name, func(t *testing.T) {
755 if strings.HasPrefix(test.attachTo, "bpf_testmod_") {
756 requireTestmod(t)
757 }
758
759 _ = mustNewProgram(t, &ProgramSpec{
760 AttachTo: test.attachTo,
761 AttachType: test.attachType,
762 Instructions: asm.Instructions{
763 asm.LoadImm(asm.R0, 0, asm.DWord),
764 asm.Return(),
765 },
766 License: "GPL",
767 Type: test.programType,
768 Flags: test.flags,
769 }, nil)
770 })
771 }
772 }
773
774 func TestProgramKernelTypes(t *testing.T) {
775 if _, err := os.Stat("/sys/kernel/btf/vmlinux"); os.IsNotExist(err) {
776 t.Skip("/sys/kernel/btf/vmlinux not present")
777 }
778
779 btfSpec, err := btf.LoadSpec("/sys/kernel/btf/vmlinux")
780 if err != nil {
781 t.Fatal(err)
782 }
783
784 _, err = newProgram(t, &ProgramSpec{
785 Type: Tracing,
786 AttachType: AttachTraceIter,
787 AttachTo: "bpf_map",
788 Instructions: asm.Instructions{
789 asm.Mov.Imm(asm.R0, 0),
790 asm.Return(),
791 },
792 License: "MIT",
793 }, &ProgramOptions{
794 KernelTypes: btfSpec,
795 })
796 testutils.SkipIfNotSupported(t, err)
797 qt.Assert(t, qt.IsNil(err))
798 }
799
800 func TestProgramBindMap(t *testing.T) {
801 testutils.SkipOnOldKernel(t, "5.10", "BPF_PROG_BIND_MAP")
802
803 arr := createMap(t, Array, 2)
804 prog := createBasicProgram(t)
805
806 // The attached map does not contain BTF information. So
807 // the metadata part of the program will be empty. This
808 // test just makes sure that we can bind a map to a program.
809 if err := prog.BindMap(arr); err != nil {
810 t.Errorf("Failed to bind map to program: %v", err)
811 }
812 }
813
814 func TestProgramInstructions(t *testing.T) {
815 name := "test_prog"
816 spec := &ProgramSpec{
817 Type: SocketFilter,
818 Name: name,
819 Instructions: asm.Instructions{
820 asm.LoadImm(asm.R0, -1, asm.DWord).WithSymbol(name),
821 asm.Return(),
822 },
823 License: "MIT",
824 }
825
826 prog := mustNewProgram(t, spec, nil)
827
828 pi, err := prog.Info()
829 testutils.SkipIfNotSupported(t, err)
830 if err != nil {
831 t.Fatal(err)
832 }
833
834 if platform.IsWindows {
835 t.Skip("prog.Info() does not return a valid Tag on Windows")
836 }
837
838 ok, err := spec.Instructions.HasTag(pi.Tag, internal.NativeEndian)
839 qt.Assert(t, qt.IsNil(err))
840 qt.Assert(t, qt.IsTrue(ok), qt.Commentf("ProgramSpec tag differs from xlated instructions"))
841 }
842
843 func TestProgramLoadErrors(t *testing.T) {
844 testutils.SkipOnOldKernel(t, "4.10", "stable verifier log output")
845
846 spec, err := LoadCollectionSpec(testutils.NativeFile(t, "testdata/errors-%s.elf"))
847 qt.Assert(t, qt.IsNil(err))
848
849 var b btf.Builder
850 raw, err := b.Marshal(nil, nil)
851 qt.Assert(t, qt.IsNil(err))
852 empty, err := btf.LoadSpecFromReader(bytes.NewReader(raw))
853 qt.Assert(t, qt.IsNil(err))
854
855 for _, test := range []struct {
856 name string
857 want error
858 }{
859 {"poisoned_single", errBadRelocation},
860 {"poisoned_double", errBadRelocation},
861 {"poisoned_kfunc", errUnknownKfunc},
862 } {
863 progSpec := spec.Programs[test.name]
864 qt.Assert(t, qt.IsNotNil(progSpec))
865
866 t.Run(test.name, func(t *testing.T) {
867 t.Log(progSpec.Instructions)
868 _, err := newProgram(t, progSpec, &ProgramOptions{
869 KernelTypes: empty,
870 })
871 testutils.SkipIfNotSupported(t, err)
872
873 var ve *VerifierError
874 qt.Assert(t, qt.ErrorAs(err, &ve))
875 t.Logf("%-5v", ve)
876
877 qt.Assert(t, qt.ErrorIs(err, test.want))
878 })
879 }
880 }
881
882 func TestProgramTargetsKernelModule(t *testing.T) {
883 ps := ProgramSpec{Type: Kprobe}
884 qt.Assert(t, qt.IsFalse(ps.targetsKernelModule()))
885
886 ps.AttachTo = "bpf_testmod_test_read"
887 qt.Assert(t, qt.IsTrue(ps.targetsKernelModule()))
888 }
889
890 func TestProgramLoadBoundToDevice(t *testing.T) {
891 testutils.SkipOnOldKernel(t, "6.3", "device-bound XDP programs")
892
893 ins := asm.Instructions{
894 asm.LoadImm(asm.R0, 2, asm.DWord).WithSymbol("out"),
895 asm.Return(),
896 }
897
898 _, err := NewProgram(&ProgramSpec{
899 Type: XDP,
900 Ifindex: math.MaxUint32,
901 AttachType: AttachXDP,
902 Instructions: ins,
903 Flags: sys.BPF_F_XDP_DEV_BOUND_ONLY,
904 License: "MIT",
905 })
906 testutils.SkipIfNotSupportedOnOS(t, err)
907
908 // Binding to loopback leads to crashes, yet is only explicitly disallowed
909 // since 3595599fa836 ("net: xdp: Disallow attaching device-bound programs in
910 // generic mode"). This only landed in 6.14 and returns EOPNOTSUPP.
911 //
912 // However, since attaching to loopback quietly succeeds on older kernels, use
913 // a non-existent ifindex to trigger EINVAL on all kernels. Without specifying
914 // ifindex, loading the program succeeds if the kernel knows the
915 // DEV_BOUND_ONLY flag.
916 qt.Assert(t, qt.ErrorIs(err, unix.EINVAL))
917 }
918
919 func TestProgramWithToken(t *testing.T) {
920 testutils.RunWithToken(t, "no-cmd", testutils.Delegated{
921 Cmds: []sys.Cmd{},
922 Progs: []sys.ProgType{sys.BPF_PROG_TYPE_SOCKET_FILTER},
923 AttachTypes: []sys.AttachType{sys.BPF_CGROUP_INET_INGRESS},
924 }, func(t *testing.T) {
925 _, err := newProgram(t, basicProgramSpec, nil)
926 qt.Assert(t, qt.ErrorIs(err, unix.EPERM))
927 })
928
929 testutils.RunWithToken(t, "no-prog", testutils.Delegated{
930 Cmds: []sys.Cmd{sys.BPF_PROG_LOAD},
931 Progs: []sys.ProgType{},
932 AttachTypes: []sys.AttachType{sys.BPF_CGROUP_INET_INGRESS},
933 }, func(t *testing.T) {
934 _, err := newProgram(t, basicProgramSpec, nil)
935 qt.Assert(t, qt.ErrorIs(err, unix.EPERM))
936 })
937
938 testutils.RunWithToken(t, "no-attach-type", testutils.Delegated{
939 Cmds: []sys.Cmd{sys.BPF_PROG_LOAD},
940 Progs: []sys.ProgType{sys.BPF_PROG_TYPE_SOCKET_FILTER},
941 AttachTypes: []sys.AttachType{},
942 }, func(t *testing.T) {
943 _, err := newProgram(t, basicProgramSpec, nil)
944 qt.Assert(t, qt.ErrorIs(err, unix.EPERM))
945 })
946
947 testutils.RunWithToken(t, "success", testutils.Delegated{
948 Cmds: []sys.Cmd{sys.BPF_PROG_LOAD},
949 Progs: []sys.ProgType{sys.BPF_PROG_TYPE_SOCKET_FILTER},
950 AttachTypes: []sys.AttachType{sys.BPF_CGROUP_INET_INGRESS},
951 }, func(t *testing.T) {
952 _, err := newProgram(t, basicProgramSpec, nil)
953 qt.Assert(t, qt.IsNil(err))
954 })
955 }
956
957 func BenchmarkNewProgram(b *testing.B) {
958 testutils.SkipOnOldKernel(b, "5.18", "kfunc support")
959 spec, err := LoadCollectionSpec(testutils.NativeFile(b, "testdata/kfunc-%s.elf"))
960 qt.Assert(b, qt.IsNil(err))
961
962 b.ReportAllocs()
963
964 for b.Loop() {
965 _, err := NewProgram(spec.Programs["benchmark"])
966 if !errors.Is(err, unix.EACCES) {
967 b.Fatal("Unexpected error:", err)
968 }
969 }
970 }
971
972 // Print the full verifier log when loading a program fails.
973 func ExampleVerifierError_retrieveFullLog() {
974 _, err := NewProgram(&ProgramSpec{
975 Type: SocketFilter,
976 Instructions: asm.Instructions{
977 asm.LoadImm(asm.R0, 0, asm.DWord),
978 // Missing Return
979 },
980 License: "MIT",
981 })
982
983 var ve *VerifierError
984 if errors.As(err, &ve) {
985 // Using %+v will print the whole verifier error, not just the last
986 // few lines.
987 fmt.Printf("Verifier error: %+v\n", ve)
988 }
989 }
990
991 // VerifierLog understands a variety of formatting flags.
992 func ExampleVerifierError() {
993 err := internal.ErrorWithLog(
994 "catastrophe",
995 syscall.ENOSPC,
996 []byte("first\nsecond\nthird"),
997 )
998
999 fmt.Printf("With %%s: %s\n", err)
1000 fmt.Printf("All log lines: %+v\n", err)
1001 fmt.Printf("First line: %+1v\n", err)
1002 fmt.Printf("Last two lines: %-2v\n", err)
1003
1004 // Output: With %s: catastrophe: no space left on device: third (2 line(s) omitted)
1005 // All log lines: catastrophe: no space left on device:
1006 // first
1007 // second
1008 // third
1009 // First line: catastrophe: no space left on device:
1010 // first
1011 // (2 line(s) omitted)
1012 // Last two lines: catastrophe: no space left on device:
1013 // (1 line(s) omitted)
1014 // second
1015 // third
1016 }
1017
1018 // Use NewProgramWithOptions if you'd like to get the verifier output
1019 // for a program, or if you want to change the buffer size used when
1020 // generating error messages.
1021 func ExampleProgram_retrieveVerifierLog() {
1022 spec := &ProgramSpec{
1023 Type: SocketFilter,
1024 Instructions: asm.Instructions{
1025 asm.LoadImm(asm.R0, 0, asm.DWord),
1026 asm.Return(),
1027 },
1028 License: "MIT",
1029 }
1030
1031 prog, err := NewProgramWithOptions(spec, ProgramOptions{
1032 LogLevel: LogLevelInstruction,
1033 })
1034 if err != nil {
1035 panic(err)
1036 }
1037 defer prog.Close()
1038
1039 fmt.Println("The verifier output is:")
1040 fmt.Println(prog.VerifierLog)
1041 }
1042
1043 // It's possible to read a program directly from a ProgramArray.
1044 func ExampleProgram_unmarshalFromMap() {
1045 progArray, err := LoadPinnedMap("/path/to/map", nil)
1046 if err != nil {
1047 panic(err)
1048 }
1049 defer progArray.Close()
1050
1051 // Load a single program
1052 var prog *Program
1053 if err := progArray.Lookup(uint32(0), &prog); err != nil {
1054 panic(err)
1055 }
1056 defer prog.Close()
1057
1058 fmt.Println("first prog:", prog)
1059
1060 // Iterate all programs
1061 var (
1062 key uint32
1063 entries = progArray.Iterate()
1064 )
1065
1066 for entries.Next(&key, &prog) {
1067 fmt.Println(key, "is", prog)
1068 }
1069
1070 if err := entries.Err(); err != nil {
1071 panic(err)
1072 }
1073 }
1074
1075 func ExampleProgramSpec_Compatible() {
1076 spec := &ProgramSpec{
1077 Type: SocketFilter,
1078 Instructions: asm.Instructions{
1079 asm.LoadImm(asm.R0, 0, asm.DWord),
1080 asm.Return(),
1081 },
1082 License: "MIT",
1083 }
1084
1085 prog, _ := NewProgram(spec)
1086 info, _ := prog.Info()
1087
1088 if err := spec.Compatible(info); err != nil {
1089 fmt.Printf("The programs are incompatible: %s\n", err)
1090 } else {
1091 fmt.Println("The programs are compatible")
1092 }
1093 }