tracepoint.go 2.1 KB

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