tracepoint.go 1.8 KB

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