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