Debian Codegraph @

internal/tracefs/kprobe.go

raw symbols SCIP
1 package tracefs
2
3 import (
4 "crypto/rand"
5 "errors"
6 "fmt"
7 "os"
8 "path/filepath"
9 "runtime"
10 "strings"
11 "sync"
12 "syscall"
13
14 "github.com/cilium/ebpf/internal"
15 "github.com/cilium/ebpf/internal/linux"
16 "github.com/cilium/ebpf/internal/mountinfo"
17 "github.com/cilium/ebpf/internal/platform"
18 "github.com/cilium/ebpf/internal/unix"
19 )
20
21 var (
22 ErrInvalidInput = errors.New("invalid input")
23
24 ErrInvalidMaxActive = errors.New("can only set maxactive on kretprobes")
25 )
26
27 //go:generate go tool stringer -type=ProbeType -linecomment
28
29 type ProbeType uint8
30
31 const (
32 Kprobe ProbeType = iota // kprobe
33 Uprobe // uprobe
34 )
35
36 func (pt ProbeType) eventsFile() (*os.File, error) {
37 path, err := sanitizeTracefsPath(fmt.Sprintf("%s_events", pt.String()))
38 if err != nil {
39 return nil, err
40 }
41
42 return os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0666)
43 }
44
45 type ProbeArgs struct {
46 Type ProbeType
47 Symbol, Group, Path string
48 Offset, RefCtrOffset, Cookie uint64
49 Pid, RetprobeMaxActive int
50 Ret bool
51 }
52
53 // RandomGroup generates a pseudorandom string for use as a tracefs group name.
54 // Returns an error when the output string would exceed 63 characters (kernel
55 // limitation), when rand.Read() fails or when prefix contains characters not
56 // allowed by IsValidTraceID.
57 func RandomGroup(prefix string) (string, error) {
58 if !validIdentifier(prefix) {
59 return "", fmt.Errorf("prefix '%s' must be alphanumeric or underscore: %w", prefix, ErrInvalidInput)
60 }
61
62 b := make([]byte, 8)
63 if _, err := rand.Read(b); err != nil {
64 return "", fmt.Errorf("reading random bytes: %w", err)
65 }
66
67 group := fmt.Sprintf("%s_%x", prefix, b)
68 if len(group) > 63 {
69 return "", fmt.Errorf("group name '%s' cannot be longer than 63 characters: %w", group, ErrInvalidInput)
70 }
71
72 return group, nil
73 }
74
75 // validIdentifier implements the equivalent of a regex match
76 // against "^[a-zA-Z_][0-9a-zA-Z_-]*$".
77 //
78 // Trace event groups, names and kernel symbols must adhere to this set of
79 // characters. Non-empty, first character must not be a number or hyphen, all
80 // characters must be alphanumeric, underscore or hyphen.
81 func validIdentifier(s string) bool {
82 if len(s) < 1 {
83 return false
84 }
85 for i, c := range []byte(s) {
86 switch {
87 case c >= 'a' && c <= 'z':
88 case c >= 'A' && c <= 'Z':
89 case c == '_':
90 case i > 0 && (c == '-' || c >= '0' && c <= '9'):
91
92 default:
93 return false
94 }
95 }
96
97 return true
98 }
99
100 func sanitizeTracefsPath(path ...string) (string, error) {
101 base, err := getTracefsPath()
102 if err != nil {
103 return "", err
104 }
105 l := filepath.Join(path...)
106 p := filepath.Join(base, l)
107 if !strings.HasPrefix(p, base) {
108 return "", fmt.Errorf("path '%s' attempts to escape base path '%s': %w", l, base, ErrInvalidInput)
109 }
110 return p, nil
111 }
112
113 // getTracefsPath returns a correct path to the tracefs mount point.
114 //
115 // The discovery order is:
116 //
117 // 1. Any tracefs mount listed in /proc/self/mountinfo (kernel 4.1+).
118 // This works regardless of where the mount sits in the filesystem,
119 // so containers that bind-mount tracefs at a non-canonical path are
120 // supported automatically.
121 // 2. A debugfs mount with a tracing/ subdirectory, for older systems
122 // where tracefs has not been lifted out of debugfs.
123 // 3. As a final fallback, probe the canonical kernel paths
124 // (/sys/kernel/tracing, /sys/kernel/debug/tracing) directly with
125 // statfs. This catches edge cases where /proc/self/mountinfo is
126 // unavailable or doesn't report the mount.
127 var getTracefsPath = sync.OnceValues(func() (string, error) {
128 if !platform.IsLinux {
129 return "", fmt.Errorf("tracefs: %w", internal.ErrNotSupportedOnOS)
130 }
131
132 if entries, err := mountinfo.Read(); err == nil {
133 if path := findTracefsInEntries(entries); path != "" {
134 return path, nil
135 }
136 }
137
138 for _, p := range []struct {
139 path string
140 fsType int64
141 }{
142 {"/sys/kernel/tracing", unix.TRACEFS_MAGIC},
143 {"/sys/kernel/debug/tracing", unix.TRACEFS_MAGIC},
144 // RHEL/CentOS
145 {"/sys/kernel/debug/tracing", unix.DEBUGFS_MAGIC},
146 } {
147 if fsType, err := linux.FSType(p.path); err == nil && fsType == p.fsType {
148 return p.path, nil
149 }
150 }
151
152 return "", errors.New("neither debugfs nor tracefs are mounted")
153 })
154
155 // findTracefsInEntries returns the first occurrence of a tracefs in the
156 // given entries.
157 //
158 // Returns an empty string when no usable mount is found.
159 func findTracefsInEntries(entries []mountinfo.Entry) string {
160 for _, e := range entries {
161 if e.FSType == "tracefs" && e.Root == "/" {
162 return e.MountPoint
163 }
164 }
165 for _, e := range entries {
166 if e.FSType != "debugfs" || e.Root != "/" {
167 continue
168 }
169 tracing := filepath.Join(e.MountPoint, "tracing")
170 if info, err := os.Stat(tracing); err == nil && info.IsDir() {
171 return tracing
172 }
173 }
174 return ""
175 }
176
177 // sanitizeIdentifier replaces every invalid character for the tracefs api with an underscore.
178 //
179 // It is equivalent to calling regexp.MustCompile("[^a-zA-Z0-9]+").ReplaceAllString("_").
180 func sanitizeIdentifier(s string) string {
181 var skip bool
182 return strings.Map(func(c rune) rune {
183 switch {
184 case c >= 'a' && c <= 'z',
185 c >= 'A' && c <= 'Z',
186 c >= '0' && c <= '9':
187 skip = false
188 return c
189
190 case skip:
191 return -1
192
193 default:
194 skip = true
195 return '_'
196 }
197 }, s)
198 }
199
200 // EventID reads a trace event's ID from tracefs given its group and name.
201 // The kernel requires group and name to be alphanumeric or underscore.
202 func EventID(group, name string) (uint64, error) {
203 if !validIdentifier(group) {
204 return 0, fmt.Errorf("invalid tracefs group: %q", group)
205 }
206
207 if !validIdentifier(name) {
208 return 0, fmt.Errorf("invalid tracefs name: %q", name)
209 }
210
211 path, err := sanitizeTracefsPath("events", group, name, "id")
212 if err != nil {
213 return 0, err
214 }
215 tid, err := internal.ReadUint64FromFile("%d\n", path)
216 if errors.Is(err, os.ErrNotExist) {
217 return 0, err
218 }
219 if err != nil {
220 return 0, fmt.Errorf("reading trace event ID of %s/%s: %w", group, name, err)
221 }
222
223 return tid, nil
224 }
225
226 func probePrefix(ret bool, maxActive int) string {
227 if ret {
228 if maxActive > 0 {
229 return fmt.Sprintf("r%d", maxActive)
230 }
231 return "r"
232 }
233 return "p"
234 }
235
236 // Event represents an entry in a tracefs probe events file.
237 type Event struct {
238 typ ProbeType
239 group, name string
240 // event id allocated by the kernel. 0 if the event has already been removed.
241 id uint64
242
243 cleanup runtime.Cleanup
244 }
245
246 // NewEvent creates a new ephemeral trace event.
247 //
248 // Returns os.ErrNotExist if symbol is not a valid
249 // kernel symbol, or if it is not traceable with kprobes. Returns os.ErrExist
250 // if a probe with the same group and symbol already exists. Returns an error if
251 // args.RetprobeMaxActive is used on non kprobe types. Returns ErrNotSupported if
252 // the kernel is too old to support kretprobe maxactive.
253 func NewEvent(args ProbeArgs) (*Event, error) {
254 // Before attempting to create a trace event through tracefs,
255 // check if an event with the same group and name already exists.
256 // Kernels 4.x and earlier don't return os.ErrExist on writing a duplicate
257 // entry, so we need to rely on reads for detecting uniqueness.
258 eventName := sanitizeIdentifier(args.Symbol)
259 _, err := EventID(args.Group, eventName)
260 if err == nil {
261 return nil, fmt.Errorf("trace event %s/%s: %w", args.Group, eventName, os.ErrExist)
262 }
263 if errors.Is(err, unix.EINVAL) {
264 return nil, fmt.Errorf("trace event %s/%s: %w (unknown symbol?)", args.Group, eventName, err)
265 }
266 if !errors.Is(err, os.ErrNotExist) {
267 return nil, fmt.Errorf("checking trace event %s/%s: %w", args.Group, eventName, err)
268 }
269
270 // Open the kprobe_events file in tracefs.
271 f, err := args.Type.eventsFile()
272 if err != nil {
273 return nil, err
274 }
275 defer f.Close()
276
277 var pe, token string
278 switch args.Type {
279 case Kprobe:
280 // The kprobe_events syntax is as follows (see Documentation/trace/kprobetrace.txt):
281 // p[:[GRP/]EVENT] [MOD:]SYM[+offs]|MEMADDR [FETCHARGS] : Set a probe
282 // r[MAXACTIVE][:[GRP/]EVENT] [MOD:]SYM[+0] [FETCHARGS] : Set a return probe
283 // -:[GRP/]EVENT : Clear a probe
284 //
285 // Some examples:
286 // r:ebpf_1234/r_my_kretprobe nf_conntrack_destroy
287 // p:ebpf_5678/p_my_kprobe __x64_sys_execve
288 //
289 // Leaving the kretprobe's MAXACTIVE set to 0 (or absent) will make the
290 // kernel default to NR_CPUS. This is desired in most eBPF cases since
291 // subsampling or rate limiting logic can be more accurately implemented in
292 // the eBPF program itself.
293 // See Documentation/kprobes.txt for more details.
294 if args.RetprobeMaxActive != 0 && !args.Ret {
295 return nil, ErrInvalidMaxActive
296 }
297 token = KprobeToken(args)
298 pe = fmt.Sprintf("%s:%s/%s %s", probePrefix(args.Ret, args.RetprobeMaxActive), args.Group, eventName, token)
299 case Uprobe:
300 // The uprobe_events syntax is as follows:
301 // p[:[GRP/]EVENT] PATH:OFFSET [FETCHARGS] : Set a probe
302 // r[:[GRP/]EVENT] PATH:OFFSET [FETCHARGS] : Set a return probe
303 // -:[GRP/]EVENT : Clear a probe
304 //
305 // Some examples:
306 // r:ebpf_1234/readline /bin/bash:0x12345
307 // p:ebpf_5678/main_mySymbol /bin/mybin:0x12345(0x123)
308 //
309 // See Documentation/trace/uprobetracer.txt for more details.
310 if args.RetprobeMaxActive != 0 {
311 return nil, ErrInvalidMaxActive
312 }
313 token = UprobeToken(args)
314 pe = fmt.Sprintf("%s:%s/%s %s", probePrefix(args.Ret, 0), args.Group, eventName, token)
315 }
316 _, err = f.WriteString(pe)
317
318 // Since commit 97c753e62e6c, ENOENT is correctly returned instead of EINVAL
319 // when trying to create a retprobe for a missing symbol.
320 if errors.Is(err, os.ErrNotExist) {
321 return nil, fmt.Errorf("token %s: not found: %w", token, err)
322 }
323 // Since commit ab105a4fb894, EILSEQ is returned when a kprobe sym+offset is resolved
324 // to an invalid insn boundary. The exact conditions that trigger this error are
325 // arch specific however.
326 if errors.Is(err, syscall.EILSEQ) {
327 return nil, fmt.Errorf("token %s: bad insn boundary: %w", token, os.ErrNotExist)
328 }
329 // ERANGE is returned when the `SYM[+offs]` token is too big and cannot
330 // be resolved.
331 if errors.Is(err, syscall.ERANGE) {
332 return nil, fmt.Errorf("token %s: offset too big: %w", token, os.ErrNotExist)
333 }
334
335 if err != nil {
336 return nil, fmt.Errorf("token %s: writing '%s': %w", token, pe, err)
337 }
338
339 // Get the newly-created trace event's id.
340 tid, err := EventID(args.Group, eventName)
341 if args.RetprobeMaxActive != 0 && errors.Is(err, os.ErrNotExist) {
342 // Kernels < 4.12 don't support maxactive and therefore auto generate
343 // group and event names from the symbol and offset. The symbol is used
344 // without any sanitization.
345 // See https://elixir.bootlin.com/linux/v4.10/source/kernel/trace/trace_kprobe.c#L712
346 event := fmt.Sprintf("kprobes/r_%s_%d", args.Symbol, args.Offset)
347 if err := removeEvent(args.Type, event); err != nil {
348 return nil, fmt.Errorf("failed to remove spurious maxactive event: %s", err)
349 }
350
351 return nil, &internal.UnsupportedFeatureError{
352 MinimumVersion: internal.Version{4, 12},
353 Name: "trace event with non-default maxactive",
354 }
355 }
356 if err != nil {
357 return nil, fmt.Errorf("get trace event id: %w", err)
358 }
359
360 evt := &Event{typ: args.Type, group: args.Group, name: eventName, id: tid}
361 evt.cleanup = runtime.AddCleanup(evt, func(*byte) {
362 _ = removeEvent(args.Type, fmt.Sprintf("%s/%s", args.Group, eventName))
363 }, nil)
364
365 return evt, nil
366 }
367
368 // Close removes the event from tracefs.
369 //
370 // Returns os.ErrClosed if the event has already been closed before.
371 func (evt *Event) Close() error {
372 if evt.id == 0 {
373 return os.ErrClosed
374 }
375
376 evt.id = 0
377 evt.cleanup.Stop()
378 pe := fmt.Sprintf("%s/%s", evt.group, evt.name)
379 return removeEvent(evt.typ, pe)
380 }
381
382 func removeEvent(typ ProbeType, pe string) error {
383 f, err := typ.eventsFile()
384 if err != nil {
385 return err
386 }
387 defer f.Close()
388
389 // See [k,u]probe_events syntax above. The probe type does not need to be specified
390 // for removals.
391 if _, err = f.WriteString("-:" + pe); err != nil {
392 return fmt.Errorf("remove event %q from %s: %w", pe, f.Name(), err)
393 }
394
395 return nil
396 }
397
398 // ID returns the tracefs ID associated with the event.
399 func (evt *Event) ID() uint64 {
400 return evt.id
401 }
402
403 // Group returns the tracefs group used by the event.
404 func (evt *Event) Group() string {
405 return evt.group
406 }
407
408 // KprobeToken creates the SYM[+offs] token for the tracefs api.
409 func KprobeToken(args ProbeArgs) string {
410 po := args.Symbol
411
412 if args.Offset != 0 {
413 po += fmt.Sprintf("+%#x", args.Offset)
414 }
415
416 return po
417 }