Debian Codegraph @

link/tracepoint.go

raw symbols SCIP
1 //go:build !windows
2
3 package link
4
5 import (
6 "fmt"
7
8 "github.com/cilium/ebpf"
9 "github.com/cilium/ebpf/internal/tracefs"
10 )
11
12 // TracepointOptions defines additional parameters that will be used
13 // when loading Tracepoints.
14 type TracepointOptions struct {
15 // Arbitrary value that can be fetched from an eBPF program
16 // via `bpf_get_attach_cookie()`.
17 //
18 // Needs kernel 5.15+.
19 Cookie uint64
20 }
21
22 // Tracepoint attaches the given eBPF program to the tracepoint with the given
23 // group and name. See /sys/kernel/tracing/events to find available
24 // tracepoints. The top-level directory is the group, the event's subdirectory
25 // is the name. Example:
26 //
27 // tp, err := Tracepoint("syscalls", "sys_enter_fork", prog, nil)
28 //
29 // Losing the reference to the resulting Link (tp) will close the Tracepoint
30 // and prevent further execution of prog. The Link must be Closed during
31 // program shutdown to avoid leaking system resources.
32 //
33 // Note that attaching eBPF programs to syscalls (sys_enter_*/sys_exit_*) is
34 // only possible as of kernel 4.14 (commit cf5f5ce).
35 //
36 // The returned Link may implement [PerfEvent].
37 func Tracepoint(group, name string, prog *ebpf.Program, opts *TracepointOptions) (Link, error) {
38 if group == "" || name == "" {
39 return nil, fmt.Errorf("group and name cannot be empty: %w", errInvalidInput)
40 }
41 if prog == nil {
42 return nil, fmt.Errorf("prog cannot be nil: %w", errInvalidInput)
43 }
44 if prog.Type() != ebpf.TracePoint {
45 return nil, fmt.Errorf("eBPF program type %s is not a Tracepoint: %w", prog.Type(), errInvalidInput)
46 }
47
48 tid, err := tracefs.EventID(group, name)
49 if err != nil {
50 return nil, err
51 }
52
53 fd, err := openTracepointPerfEvent(tid, perfAllThreads)
54 if err != nil {
55 return nil, err
56 }
57
58 var cookie uint64
59 if opts != nil {
60 cookie = opts.Cookie
61 }
62
63 pe := newPerfEvent(fd, nil)
64
65 lnk, err := attachPerfEvent(pe, prog, cookie)
66 if err != nil {
67 pe.Close()
68 return nil, err
69 }
70
71 return lnk, nil
72 }