Debian Codegraph @

link/kprobe_test.go

raw symbols SCIP
1 //go:build !windows
2
3 package link
4
5 import (
6 "errors"
7 "os"
8 "testing"
9
10 "github.com/go-quicktest/qt"
11
12 "github.com/cilium/ebpf"
13 "github.com/cilium/ebpf/asm"
14 "github.com/cilium/ebpf/internal/testutils"
15 "github.com/cilium/ebpf/internal/tracefs"
16 "github.com/cilium/ebpf/internal/unix"
17 )
18
19 // Global symbol, present on all tested kernels.
20 var ksym = "vprintk"
21
22 // Collection of various symbols present in all tested kernels.
23 // Compiler optimizations result in different names for these symbols.
24 var symTests = []string{
25 "echo_char.isra.0", // function optimized by -fipa-sra
26 "proc_get_long.constprop.0", // optimized function with constant operands
27 "unregister_kprobes.part.0", // function body that was split and partially inlined
28 }
29
30 func TestKprobe(t *testing.T) {
31 prog := mustLoadProgram(t, ebpf.Kprobe, 0, "")
32
33 for _, tt := range symTests {
34 t.Run(tt, func(t *testing.T) {
35 k, err := Kprobe(tt, prog, nil)
36 if err != nil {
37 t.Fatal(err)
38 }
39 defer k.Close()
40 })
41 }
42
43 k, err := Kprobe("bogus", prog, nil)
44 qt.Assert(t, qt.ErrorIs(err, os.ErrNotExist), qt.Commentf("got error: %s", err))
45 if k != nil {
46 k.Close()
47 }
48
49 k, err = Kprobe(ksym, prog, nil)
50 qt.Assert(t, qt.IsNil(err))
51 defer k.Close()
52
53 testLink(t, k, prog)
54 }
55
56 func TestKprobeInfo(t *testing.T) {
57 testutils.SkipOnOldKernel(t, "6.6", "bpf_link_info_perf_event")
58
59 prog := mustLoadProgram(t, ebpf.Kprobe, 0, "")
60
61 k, err := Kprobe(ksym, prog, nil)
62 qt.Assert(t, qt.IsNil(err))
63 defer k.Close()
64
65 info, err := k.Info()
66 qt.Assert(t, qt.IsNil(err))
67 qt.Assert(t, qt.Equals(info.PerfEvent().Kprobe().Function, ksym))
68 qt.Assert(t, qt.Equals(info.PerfEvent().Kprobe().Offset, 0))
69 }
70
71 func TestKprobeOffset(t *testing.T) {
72 prog := mustLoadProgram(t, ebpf.Kprobe, 0, "")
73
74 // The layout of a function is compiler and arch dependent, so we try to
75 // find a valid attach target in the first few bytes of the function.
76 for i := uint64(1); i < 16; i++ {
77 k, err := Kprobe("inet6_release", prog, &KprobeOptions{Offset: i})
78 if err != nil {
79 continue
80 }
81 k.Close()
82 return
83 }
84
85 t.Fatal("Can't attach with non-zero offset")
86 }
87
88 func TestKretprobeMaxActive(t *testing.T) {
89 prog := mustLoadProgram(t, ebpf.Kprobe, 0, "")
90 defer prog.Close()
91
92 _, err := Kprobe("do_sys_open", prog, &KprobeOptions{RetprobeMaxActive: 4096})
93 if !errors.Is(err, tracefs.ErrInvalidMaxActive) {
94 t.Fatal("Expected ErrInvalidMaxActive, got", err)
95 }
96
97 k, err := Kretprobe("__put_task_struct", prog, &KprobeOptions{RetprobeMaxActive: 4096})
98 testutils.SkipIfNotSupported(t, err)
99 if err != nil {
100 t.Fatal("Kretprobe with maxactive returned an error:", err)
101 }
102 if err := k.Close(); err != nil {
103 t.Fatal("Closing kretprobe:", err)
104 }
105 }
106
107 func TestKretprobe(t *testing.T) {
108 prog := mustLoadProgram(t, ebpf.Kprobe, 0, "")
109
110 for _, tt := range symTests {
111 t.Run(tt, func(t *testing.T) {
112 k, err := Kretprobe(tt, prog, nil)
113 if err != nil {
114 t.Fatal(err)
115 }
116 defer k.Close()
117 })
118 }
119
120 k, err := Kretprobe("bogus", prog, nil)
121 if !errors.Is(err, os.ErrNotExist) && !errors.Is(err, unix.EINVAL) {
122 t.Fatal(err)
123 }
124 if k != nil {
125 k.Close()
126 }
127
128 k, err = Kretprobe(ksym, prog, nil)
129 qt.Assert(t, qt.IsNil(err))
130 defer k.Close()
131
132 testLink(t, k, prog)
133 }
134
135 func TestKprobeErrors(t *testing.T) {
136 // Invalid Kprobe incantations. Kretprobe uses the same code paths
137 // with a different ret flag.
138 _, err := Kprobe("", nil, nil) // empty symbol
139 qt.Assert(t, qt.ErrorIs(err, errInvalidInput))
140
141 _, err = Kprobe("_", nil, nil) // empty prog
142 qt.Assert(t, qt.ErrorIs(err, errInvalidInput))
143
144 _, err = Kprobe(".", &ebpf.Program{}, nil) // illegal chars in symbol
145 qt.Assert(t, qt.ErrorIs(err, errInvalidInput))
146
147 _, err = Kprobe("foo", &ebpf.Program{}, nil) // wrong prog type
148 qt.Assert(t, qt.ErrorIs(err, errInvalidInput))
149 }
150
151 // Test k(ret)probe creation using perf_kprobe PMU.
152 func TestKprobeCreatePMU(t *testing.T) {
153 // Requires at least 4.17 (e12f03d7031a "perf/core: Implement the 'perf_kprobe' PMU")
154 testutils.SkipOnOldKernel(t, "4.17", "perf_kprobe PMU")
155
156 // kprobe happy path. printk is always present.
157 pk, err := pmuProbe(tracefs.ProbeArgs{Type: tracefs.Kprobe, Symbol: ksym})
158 qt.Assert(t, qt.IsNil(err))
159 defer pk.Close()
160
161 // kretprobe happy path.
162 pr, err := pmuProbe(tracefs.ProbeArgs{Type: tracefs.Kprobe, Symbol: ksym, Ret: true})
163 qt.Assert(t, qt.IsNil(err))
164 defer pr.Close()
165
166 // Expect os.ErrNotExist when specifying a non-existent kernel symbol
167 // on kernels 4.17 and up.
168 _, err = pmuProbe(tracefs.ProbeArgs{Type: tracefs.Kprobe, Symbol: "bogus"})
169 qt.Assert(t, qt.ErrorIs(err, os.ErrNotExist), qt.Commentf("got error: %s", err))
170
171 // A kernel bug was fixed in 97c753e62e6c where EINVAL was returned instead
172 // of ENOENT, but only for kretprobes.
173 _, err = pmuProbe(tracefs.ProbeArgs{Type: tracefs.Kprobe, Symbol: "bogus", Ret: true})
174 qt.Assert(t, qt.ErrorIs(err, os.ErrNotExist), qt.Commentf("got error: %s", err))
175 }
176
177 // Test fallback behaviour on kernels without perf_kprobe PMU available.
178 func TestKprobePMUUnavailable(t *testing.T) {
179 pk, err := pmuProbe(tracefs.ProbeArgs{Type: tracefs.Kprobe, Symbol: ksym})
180 if err == nil {
181 pk.Close()
182 t.Skipf("Kernel supports perf_kprobe PMU, not asserting error.")
183 }
184
185 // Only allow a PMU creation with a valid kernel symbol to fail with ErrNotSupported.
186 qt.Assert(t, qt.ErrorIs(err, ErrNotSupported), qt.Commentf("got error: %s", err))
187 }
188
189 func BenchmarkKprobeCreatePMU(b *testing.B) {
190 for b.Loop() {
191 pr, err := pmuProbe(tracefs.ProbeArgs{Type: tracefs.Kprobe, Symbol: ksym})
192 if err != nil {
193 b.Error("error creating perf_kprobe PMU:", err)
194 }
195
196 if err := pr.Close(); err != nil {
197 b.Error("error closing perf_kprobe PMU:", err)
198 }
199 }
200 }
201
202 // Test tracefs k(ret)probe creation on all kernel versions.
203 func TestKprobeTraceFS(t *testing.T) {
204 // Open and close tracefs k(ret)probes, checking all errors.
205 kp, err := tracefsProbe(tracefs.ProbeArgs{Type: tracefs.Kprobe, Symbol: ksym})
206 qt.Assert(t, qt.IsNil(err))
207 qt.Assert(t, qt.IsNil(kp.Close()))
208
209 kp, err = tracefsProbe(tracefs.ProbeArgs{Type: tracefs.Kprobe, Symbol: ksym, Ret: true})
210 qt.Assert(t, qt.IsNil(err))
211 qt.Assert(t, qt.IsNil(kp.Close()))
212
213 // Create two identical trace events, ensure their IDs differ.
214 k1, err := tracefsProbe(tracefs.ProbeArgs{Type: tracefs.Kprobe, Symbol: ksym})
215 qt.Assert(t, qt.IsNil(err))
216 defer k1.Close()
217 qt.Assert(t, qt.IsNotNil(k1.tracefsEvent))
218
219 k2, err := tracefsProbe(tracefs.ProbeArgs{Type: tracefs.Kprobe, Symbol: ksym})
220 qt.Assert(t, qt.IsNil(err))
221 defer k2.Close()
222 qt.Assert(t, qt.IsNotNil(k2.tracefsEvent))
223
224 // Compare the kprobes' tracefs IDs.
225 qt.Assert(t, qt.Not(qt.Equals(k1.tracefsEvent.ID(), k2.tracefsEvent.ID())))
226
227 // Expect an error when supplying an invalid custom group name
228 _, err = tracefsProbe(tracefs.ProbeArgs{Type: tracefs.Kprobe, Symbol: ksym, Group: "/"})
229 qt.Assert(t, qt.Not(qt.IsNil(err)))
230
231 cg := "customgroup"
232 k3, err := tracefsProbe(tracefs.ProbeArgs{Type: tracefs.Kprobe, Symbol: ksym, Group: cg})
233 qt.Assert(t, qt.IsNil(err))
234 defer k3.Close()
235 qt.Assert(t, qt.Matches(k3.tracefsEvent.Group(), `customgroup_[a-f0-9]{16}`))
236
237 // Prepare probe args.
238 args := tracefs.ProbeArgs{Type: tracefs.Kprobe, Group: "testgroup", Symbol: "symbol"}
239
240 // Write a k(ret)probe event for a non-existing symbol.
241 _, err = tracefs.NewEvent(args)
242 // A kernel bug was introduced in 9d8616034f16 that causes EINVAL to be returned
243 // instead of ENOENT when trying to attach kprobes to non-existing symbols.
244 qt.Assert(t, qt.IsTrue(errors.Is(err, os.ErrNotExist) || errors.Is(err, unix.EINVAL)), qt.Commentf("got error: %s", err))
245
246 // A kernel bug was fixed in 97c753e62e6c where EINVAL was returned instead
247 // of ENOENT, but only for kretprobes.
248 args.Ret = true
249 _, err = tracefs.NewEvent(args)
250 qt.Assert(t, qt.IsTrue(errors.Is(err, os.ErrNotExist) || errors.Is(err, unix.EINVAL)), qt.Commentf("got error: %s", err))
251 }
252
253 func BenchmarkKprobeCreateTraceFS(b *testing.B) {
254 for b.Loop() {
255 // Include <tracefs>/kprobe_events operations in the benchmark loop
256 // because we create one per perf event.
257 pr, err := tracefsProbe(tracefs.ProbeArgs{Symbol: ksym})
258 if err != nil {
259 b.Error("error creating tracefs perf event:", err)
260 }
261
262 if err := pr.Close(); err != nil {
263 b.Error("error closing tracefs perf event:", err)
264 }
265 }
266 }
267
268 func TestKprobeProgramCall(t *testing.T) {
269 m, p := newUpdaterMapProg(t, ebpf.Kprobe, 0)
270
271 // Open Kprobe on `sys_getpid` and attach it
272 // to the ebpf program created above.
273 k, err := Kprobe("sys_getpid", p, nil)
274 if err != nil {
275 t.Fatal(err)
276 }
277
278 // Trigger ebpf program call.
279 unix.Getpid()
280
281 // Assert that the value got incremented to at least 1, while allowing
282 // for bigger values, because we could race with other getpid callers.
283 assertMapValueGE(t, m, 0, 1)
284
285 // Detach the Kprobe.
286 if err := k.Close(); err != nil {
287 t.Fatal(err)
288 }
289
290 // Reset map value to 0 at index 0.
291 if err := m.Update(uint32(0), uint32(0), ebpf.UpdateExist); err != nil {
292 t.Fatal(err)
293 }
294
295 // Retrigger the ebpf program call.
296 unix.Getpid()
297
298 // Assert that this time the value has not been updated.
299 assertMapValue(t, m, 0, 0)
300 }
301
302 func newUpdaterMapProg(t *testing.T, typ ebpf.ProgramType, attach ebpf.AttachType) (*ebpf.Map, *ebpf.Program) {
303 // Create ebpf map. Will contain only one key with initial value 0.
304 m, err := ebpf.NewMap(&ebpf.MapSpec{
305 Type: ebpf.Array,
306 KeySize: 4,
307 ValueSize: 4,
308 MaxEntries: 1,
309 })
310 if err != nil {
311 t.Fatal(err)
312 }
313
314 // Create ebpf program. When called, will increase the value of key 0 by 1
315 // in the map created above.
316 p, err := ebpf.NewProgram(&ebpf.ProgramSpec{
317 Type: typ,
318 Instructions: asm.Instructions{
319 // R1 map
320 asm.LoadMapPtr(asm.R1, m.FD()),
321
322 // R2 key
323 asm.Mov.Reg(asm.R2, asm.R10),
324 asm.Add.Imm(asm.R2, -4),
325 asm.StoreImm(asm.R2, 0, 0, asm.Word),
326
327 // Lookup map[0]
328 asm.FnMapLookupElem.Call(),
329 asm.JEq.Imm(asm.R0, 0, "ret"),
330
331 // u32 val = R0++
332 asm.LoadMem(asm.R1, asm.R0, 0, asm.Word),
333 asm.Add.Imm(asm.R1, 1),
334 asm.StoreMem(asm.RFP, -8, asm.R1, asm.Word),
335
336 // u32 key = 0
337 asm.Mov.Imm(asm.R1, 0),
338 asm.StoreMem(asm.RFP, -4, asm.R1, asm.Word),
339
340 // bpf_map_update_elem(...)
341 asm.Mov.Reg(asm.R2, asm.RFP),
342 asm.Add.Imm(asm.R2, -4),
343 asm.Mov.Reg(asm.R3, asm.RFP),
344 asm.Add.Imm(asm.R3, -8),
345 asm.LoadMapPtr(asm.R1, m.FD()),
346 asm.Mov.Imm(asm.R4, 0),
347 asm.FnMapUpdateElem.Call(),
348
349 // exit 0
350 asm.Mov.Imm(asm.R0, 0),
351 asm.Return().WithSymbol("ret"),
352 },
353 AttachType: attach,
354 License: "Dual MIT/GPL",
355 })
356 if err != nil {
357 t.Fatal(err)
358 }
359
360 // Close the program and map on test teardown.
361 t.Cleanup(func() {
362 m.Close()
363 p.Close()
364 })
365
366 return m, p
367 }
368
369 func assertMapValue(t *testing.T, m *ebpf.Map, k, v uint32) {
370 var val uint32
371 if err := m.Lookup(k, &val); err != nil {
372 t.Fatal(err)
373 }
374 if val != v {
375 t.Fatalf("unexpected value: want '%d', got '%d'", v, val)
376 }
377 }
378
379 func assertMapValueGE(t *testing.T, m *ebpf.Map, k, v uint32) {
380 var val uint32
381 if err := m.Lookup(k, &val); err != nil {
382 t.Fatal(err)
383 }
384 if val < v {
385 t.Fatalf("unexpected value: want >= '%d', got '%d'", v, val)
386 }
387 }
388
389 func TestKprobeCookie(t *testing.T) {
390 testutils.SkipOnOldKernel(t, "5.15", "bpf_perf_link")
391
392 prog := mustLoadProgram(t, ebpf.Kprobe, 0, "")
393 k, err := Kprobe(ksym, prog, &KprobeOptions{Cookie: 1000})
394 if err != nil {
395 t.Fatal(err)
396 }
397 k.Close()
398 }