| 1 | package pin |
| 2 | |
| 3 | import ( |
| 4 | "path/filepath" |
| 5 | "testing" |
| 6 | |
| 7 | "github.com/go-quicktest/qt" |
| 8 | |
| 9 | "github.com/cilium/ebpf" |
| 10 | "github.com/cilium/ebpf/asm" |
| 11 | "github.com/cilium/ebpf/internal/platform" |
| 12 | "github.com/cilium/ebpf/internal/testutils" |
| 13 | "github.com/cilium/ebpf/internal/testutils/testmain" |
| 14 | ) |
| 15 | |
| 16 | func mustPinnedProgram(t *testing.T, path string) *ebpf.Program { |
| 17 | t.Helper() |
| 18 | |
| 19 | typ := ebpf.SocketFilter |
| 20 | if platform.IsWindows { |
| 21 | typ = ebpf.WindowsSample |
| 22 | } |
| 23 | |
| 24 | spec := &ebpf.ProgramSpec{ |
| 25 | Name: "test", |
| 26 | Type: typ, |
| 27 | Instructions: asm.Instructions{ |
| 28 | asm.LoadImm(asm.R0, 2, asm.DWord), |
| 29 | asm.Return(), |
| 30 | }, |
| 31 | License: "MIT", |
| 32 | } |
| 33 | |
| 34 | p, err := ebpf.NewProgram(spec) |
| 35 | if err != nil { |
| 36 | t.Fatal(err) |
| 37 | } |
| 38 | t.Cleanup(func() { p.Close() }) |
| 39 | |
| 40 | if err := p.Pin(path); err != nil { |
| 41 | t.Fatal(err) |
| 42 | } |
| 43 | |
| 44 | return p |
| 45 | } |
| 46 | |
| 47 | func mustPinnedMap(t *testing.T, path string) *ebpf.Map { |
| 48 | t.Helper() |
| 49 | |
| 50 | typ := ebpf.Array |
| 51 | if platform.IsWindows { |
| 52 | typ = ebpf.WindowsArray |
| 53 | } |
| 54 | |
| 55 | spec := &ebpf.MapSpec{ |
| 56 | Name: "test", |
| 57 | Type: typ, |
| 58 | KeySize: 4, |
| 59 | ValueSize: 4, |
| 60 | MaxEntries: 1, |
| 61 | } |
| 62 | |
| 63 | m, err := ebpf.NewMap(spec) |
| 64 | if err != nil { |
| 65 | t.Fatal(err) |
| 66 | } |
| 67 | t.Cleanup(func() { m.Close() }) |
| 68 | |
| 69 | if err := m.Pin(path); err != nil { |
| 70 | t.Fatal(err) |
| 71 | } |
| 72 | |
| 73 | return m |
| 74 | } |
| 75 | |
| 76 | func TestLoad(t *testing.T) { |
| 77 | testutils.SkipOnOldKernel(t, "4.10", "reading program fdinfo") |
| 78 | |
| 79 | tmp := testutils.TempBPFFS(t) |
| 80 | |
| 81 | mpath := filepath.Join(tmp, "map") |
| 82 | ppath := filepath.Join(tmp, "prog") |
| 83 | |
| 84 | mustPinnedMap(t, mpath) |
| 85 | mustPinnedProgram(t, ppath) |
| 86 | |
| 87 | _, err := Load(tmp, nil) |
| 88 | qt.Assert(t, qt.IsNotNil(err)) |
| 89 | |
| 90 | m, err := Load(mpath, nil) |
| 91 | qt.Assert(t, qt.IsNil(err)) |
| 92 | defer m.Close() |
| 93 | qt.Assert(t, qt.Satisfies(m, testutils.Contains[*ebpf.Map])) |
| 94 | |
| 95 | p, err := Load(ppath, nil) |
| 96 | qt.Assert(t, qt.IsNil(err)) |
| 97 | defer p.Close() |
| 98 | qt.Assert(t, qt.Satisfies(p, testutils.Contains[*ebpf.Program])) |
| 99 | } |
| 100 | |
| 101 | func TestMain(m *testing.M) { |
| 102 | testmain.Run(m) |
| 103 | } |