Debian Codegraph @

link/kprobe.go

raw symbols SCIP
1 //go:build !windows
2
3 package link
4
5 import (
6 "errors"
7 "fmt"
8 "os"
9 "runtime"
10 "strings"
11 "unsafe"
12
13 "github.com/cilium/ebpf"
14 "github.com/cilium/ebpf/internal"
15 "github.com/cilium/ebpf/internal/linux"
16 "github.com/cilium/ebpf/internal/sys"
17 "github.com/cilium/ebpf/internal/tracefs"
18 "github.com/cilium/ebpf/internal/unix"
19 )
20
21 // KprobeOptions defines additional parameters that will be used
22 // when loading Kprobes.
23 type KprobeOptions struct {
24 // Arbitrary value that can be fetched from an eBPF program
25 // via `bpf_get_attach_cookie()`.
26 //
27 // Needs kernel 5.15+.
28 Cookie uint64
29 // Offset of the kprobe relative to the traced symbol.
30 // Can be used to insert kprobes at arbitrary offsets in kernel functions,
31 // e.g. in places where functions have been inlined.
32 Offset uint64
33 // Increase the maximum number of concurrent invocations of a kretprobe.
34 // Required when tracing some long running functions in the kernel.
35 //
36 // Warning: this setting forces the use of an outdated kernel API and is
37 // not portable across kernel versions. On supported kernels, consider using
38 // fexit programs instead, as they don't have this MaxActive limitation.
39 RetprobeMaxActive int
40 // Prefix used for the event name if the kprobe must be attached using tracefs.
41 // The group name will be formatted as `<prefix>_<randomstr>`.
42 // The default empty string is equivalent to "ebpf" as the prefix.
43 TraceFSPrefix string
44 }
45
46 func (ko *KprobeOptions) cookie() uint64 {
47 if ko == nil {
48 return 0
49 }
50 return ko.Cookie
51 }
52
53 // Kprobe attaches the given eBPF program to a perf event that fires when the
54 // given kernel symbol starts executing. See /proc/kallsyms for available
55 // symbols. For example, printk():
56 //
57 // kp, err := Kprobe("printk", prog, nil)
58 //
59 // Losing the reference to the resulting Link (kp) will close the Kprobe
60 // and prevent further execution of prog. The Link must be Closed during
61 // program shutdown to avoid leaking system resources.
62 //
63 // If attaching to symbol fails, automatically retries with the running
64 // platform's syscall prefix (e.g. __x64_) to support attaching to syscalls
65 // in a portable fashion.
66 //
67 // On kernels 6.11 and later, setting a kprobe on a nonexistent symbol using
68 // tracefs incorrectly returns [unix.EINVAL] instead of [os.ErrNotExist].
69 //
70 // The returned Link may implement [PerfEvent].
71 func Kprobe(symbol string, prog *ebpf.Program, opts *KprobeOptions) (Link, error) {
72 k, err := kprobe(symbol, prog, opts, false)
73 if err != nil {
74 return nil, err
75 }
76
77 lnk, err := attachPerfEvent(k, prog, opts.cookie())
78 if err != nil {
79 k.Close()
80 return nil, err
81 }
82
83 return lnk, nil
84 }
85
86 // Kretprobe attaches the given eBPF program to a perf event that fires right
87 // before the given kernel symbol exits, with the function stack left intact.
88 // See /proc/kallsyms for available symbols. For example, printk():
89 //
90 // kp, err := Kretprobe("printk", prog, nil)
91 //
92 // Losing the reference to the resulting Link (kp) will close the Kretprobe
93 // and prevent further execution of prog. The Link must be Closed during
94 // program shutdown to avoid leaking system resources.
95 //
96 // If attaching to symbol fails, automatically retries with the running
97 // platform's syscall prefix (e.g. __x64_) to support attaching to syscalls
98 // in a portable fashion.
99 //
100 // On kernels 5.10 and earlier, setting a kretprobe on a nonexistent symbol
101 // incorrectly returns [unix.EINVAL] instead of [os.ErrNotExist].
102 //
103 // The returned Link may implement [PerfEvent].
104 func Kretprobe(symbol string, prog *ebpf.Program, opts *KprobeOptions) (Link, error) {
105 k, err := kprobe(symbol, prog, opts, true)
106 if err != nil {
107 return nil, err
108 }
109
110 lnk, err := attachPerfEvent(k, prog, opts.cookie())
111 if err != nil {
112 k.Close()
113 return nil, err
114 }
115
116 return lnk, nil
117 }
118
119 // isValidKprobeSymbol implements the equivalent of a regex match
120 // against "^[a-zA-Z_][0-9a-zA-Z_.]*$".
121 func isValidKprobeSymbol(s string) bool {
122 if len(s) < 1 {
123 return false
124 }
125
126 for i, c := range []byte(s) {
127 switch {
128 case c >= 'a' && c <= 'z':
129 case c >= 'A' && c <= 'Z':
130 case c == '_':
131 case i > 0 && c >= '0' && c <= '9':
132
133 // Allow `.` in symbol name. GCC-compiled kernel may change symbol name
134 // to have a `.isra.$n` suffix, like `udp_send_skb.isra.52`.
135 // See: https://gcc.gnu.org/gcc-10/changes.html
136 case i > 0 && c == '.':
137
138 default:
139 return false
140 }
141 }
142
143 return true
144 }
145
146 // kprobe opens a perf event on the given symbol and attaches prog to it.
147 // If ret is true, create a kretprobe.
148 func kprobe(symbol string, prog *ebpf.Program, opts *KprobeOptions, ret bool) (*perfEvent, error) {
149 if symbol == "" {
150 return nil, fmt.Errorf("symbol name cannot be empty: %w", errInvalidInput)
151 }
152 if prog == nil {
153 return nil, fmt.Errorf("prog cannot be nil: %w", errInvalidInput)
154 }
155 if !isValidKprobeSymbol(symbol) {
156 return nil, fmt.Errorf("symbol '%s' must be a valid symbol in /proc/kallsyms: %w", symbol, errInvalidInput)
157 }
158 if prog.Type() != ebpf.Kprobe {
159 return nil, fmt.Errorf("eBPF program type %s is not a Kprobe: %w", prog.Type(), errInvalidInput)
160 }
161
162 args := tracefs.ProbeArgs{
163 Type: tracefs.Kprobe,
164 Pid: perfAllThreads,
165 Symbol: symbol,
166 Ret: ret,
167 }
168
169 if opts != nil {
170 args.RetprobeMaxActive = opts.RetprobeMaxActive
171 args.Cookie = opts.Cookie
172 args.Offset = opts.Offset
173 args.Group = opts.TraceFSPrefix
174 }
175
176 // Use kprobe PMU if the kernel has it available.
177 tp, err := pmuProbe(args)
178 if errors.Is(err, os.ErrNotExist) || errors.Is(err, unix.EINVAL) {
179 if prefix := linux.PlatformPrefix(); prefix != "" {
180 args.Symbol = prefix + symbol
181 tp, err = pmuProbe(args)
182 }
183 }
184 if err == nil {
185 return tp, nil
186 }
187 if !errors.Is(err, ErrNotSupported) {
188 return nil, fmt.Errorf("creating perf_kprobe PMU (arch-specific fallback for %q): %w", symbol, err)
189 }
190
191 // Use tracefs if kprobe PMU is missing.
192 args.Symbol = symbol
193 tp, err = tracefsProbe(args)
194 if errors.Is(err, os.ErrNotExist) || errors.Is(err, unix.EINVAL) {
195 if prefix := linux.PlatformPrefix(); prefix != "" {
196 args.Symbol = prefix + symbol
197 tp, err = tracefsProbe(args)
198 }
199 }
200 if err != nil {
201 return nil, fmt.Errorf("creating tracefs event (arch-specific fallback for %q): %w", symbol, err)
202 }
203
204 return tp, nil
205 }
206
207 // pmuProbe opens a perf event based on a Performance Monitoring Unit.
208 //
209 // Requires at least a 4.17 kernel.
210 // e12f03d7031a "perf/core: Implement the 'perf_kprobe' PMU"
211 // 33ea4b24277b "perf/core: Implement the 'perf_uprobe' PMU"
212 //
213 // Returns ErrNotSupported if the kernel doesn't support perf_[k,u]probe PMU
214 func pmuProbe(args tracefs.ProbeArgs) (*perfEvent, error) {
215 // Getting the PMU type will fail if the kernel doesn't support
216 // the perf_[k,u]probe PMU.
217 eventType, err := internal.ReadUint64FromFileOnce("%d\n", "/sys/bus/event_source/devices", args.Type.String(), "type")
218 if errors.Is(err, os.ErrNotExist) {
219 return nil, fmt.Errorf("%s: %w", args.Type, ErrNotSupported)
220 }
221 if err != nil {
222 return nil, err
223 }
224
225 // Use tracefs if we want to set kretprobe's retprobeMaxActive.
226 if args.RetprobeMaxActive != 0 {
227 return nil, fmt.Errorf("pmu probe: non-zero retprobeMaxActive: %w", ErrNotSupported)
228 }
229
230 var config uint64
231 if args.Ret {
232 bit, err := internal.ReadUint64FromFileOnce("config:%d\n", "/sys/bus/event_source/devices", args.Type.String(), "/format/retprobe")
233 if err != nil {
234 return nil, err
235 }
236 config |= 1 << bit
237 }
238
239 var (
240 attr unix.PerfEventAttr
241 sp unsafe.Pointer
242 token string
243 )
244 switch args.Type {
245 case tracefs.Kprobe:
246 // Create a pointer to a NUL-terminated string for the kernel.
247 sp, err = unsafeStringPtr(args.Symbol)
248 if err != nil {
249 return nil, err
250 }
251
252 token = tracefs.KprobeToken(args)
253
254 attr = unix.PerfEventAttr{
255 // The minimum size required for PMU kprobes is PERF_ATTR_SIZE_VER1,
256 // since it added the config2 (Ext2) field. Use Ext2 as probe_offset.
257 Size: unix.PERF_ATTR_SIZE_VER1,
258 Type: uint32(eventType), // PMU event type read from sysfs
259 Ext1: uint64(uintptr(sp)), // Kernel symbol to trace
260 Ext2: args.Offset, // Kernel symbol offset
261 Config: config, // Retprobe flag
262 }
263 case tracefs.Uprobe:
264 sp, err = unsafeStringPtr(args.Path)
265 if err != nil {
266 return nil, err
267 }
268
269 if args.RefCtrOffset != 0 {
270 config |= args.RefCtrOffset << uprobeRefCtrOffsetShift
271 }
272
273 token = tracefs.UprobeToken(args)
274
275 attr = unix.PerfEventAttr{
276 // The minimum size required for PMU uprobes is PERF_ATTR_SIZE_VER1,
277 // since it added the config2 (Ext2) field. The Size field controls the
278 // size of the internal buffer the kernel allocates for reading the
279 // perf_event_attr argument from userspace.
280 Size: unix.PERF_ATTR_SIZE_VER1,
281 Type: uint32(eventType), // PMU event type read from sysfs
282 Ext1: uint64(uintptr(sp)), // Uprobe path
283 Ext2: args.Offset, // Uprobe offset
284 Config: config, // RefCtrOffset, Retprobe flag
285 }
286 }
287
288 cpu := 0
289 if args.Pid != perfAllThreads {
290 cpu = -1
291 }
292 rawFd, err := unix.PerfEventOpen(&attr, args.Pid, cpu, -1, unix.PERF_FLAG_FD_CLOEXEC)
293
294 // On some old kernels, kprobe PMU doesn't allow `.` in symbol names and
295 // return -EINVAL. Return ErrNotSupported to allow falling back to tracefs.
296 // https://github.com/torvalds/linux/blob/94710cac0ef4/kernel/trace/trace_kprobe.c#L340-L343
297 if errors.Is(err, unix.EINVAL) && strings.Contains(args.Symbol, ".") {
298 return nil, fmt.Errorf("token %s: older kernels don't accept dots: %w", token, ErrNotSupported)
299 }
300 // Since commit 97c753e62e6c, ENOENT is correctly returned instead of EINVAL
301 // when trying to create a retprobe for a missing symbol.
302 if errors.Is(err, os.ErrNotExist) {
303 return nil, fmt.Errorf("token %s: not found: %w", token, err)
304 }
305 // Since commit ab105a4fb894, EILSEQ is returned when a kprobe sym+offset is resolved
306 // to an invalid insn boundary. The exact conditions that trigger this error are
307 // arch specific however.
308 if errors.Is(err, unix.EILSEQ) {
309 return nil, fmt.Errorf("token %s: bad insn boundary: %w", token, os.ErrNotExist)
310 }
311 // Since at least commit cb9a19fe4aa51, ENOTSUPP is returned
312 // when attempting to set a uprobe on a trap instruction.
313 if errors.Is(err, sys.ENOTSUPP) {
314 return nil, fmt.Errorf("token %s: failed setting uprobe on offset %#x (possible trap insn): %w", token, args.Offset, err)
315 }
316
317 if err != nil {
318 return nil, fmt.Errorf("token %s: opening perf event: %w", token, err)
319 }
320
321 // Ensure the string pointer is not collected before PerfEventOpen returns.
322 runtime.KeepAlive(sp)
323
324 fd, err := sys.NewFD(rawFd)
325 if err != nil {
326 return nil, err
327 }
328
329 // Kernel has perf_[k,u]probe PMU available, initialize perf event.
330 return newPerfEvent(fd, nil), nil
331 }
332
333 // tracefsProbe creates a trace event by writing an entry to <tracefs>/[k,u]probe_events.
334 // A new trace event group name is generated on every call to support creating
335 // multiple trace events for the same kernel or userspace symbol.
336 // Path and offset are only set in the case of uprobe(s) and are used to set
337 // the executable/library path on the filesystem and the offset where the probe is inserted.
338 // A perf event is then opened on the newly-created trace event and returned to the caller.
339 func tracefsProbe(args tracefs.ProbeArgs) (*perfEvent, error) {
340 groupPrefix := "ebpf"
341 if args.Group != "" {
342 groupPrefix = args.Group
343 }
344
345 // Generate a random string for each trace event we attempt to create.
346 // This value is used as the 'group' token in tracefs to allow creating
347 // multiple kprobe trace events with the same name.
348 group, err := tracefs.RandomGroup(groupPrefix)
349 if err != nil {
350 return nil, fmt.Errorf("randomizing group name: %w", err)
351 }
352 args.Group = group
353
354 // Create the [k,u]probe trace event using tracefs.
355 evt, err := tracefs.NewEvent(args)
356 if err != nil {
357 return nil, fmt.Errorf("creating probe entry on tracefs: %w", err)
358 }
359
360 // Kprobes are ephemeral tracepoints and share the same perf event type.
361 fd, err := openTracepointPerfEvent(evt.ID(), args.Pid)
362 if err != nil {
363 // Make sure we clean up the created tracefs event when we return error.
364 // If a livepatch handler is already active on the symbol, the write to
365 // tracefs will succeed, a trace event will show up, but creating the
366 // perf event will fail with EBUSY.
367 _ = evt.Close()
368 return nil, err
369 }
370
371 return newPerfEvent(fd, evt), nil
372 }