tracepoint.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package link
  2. import (
  3. "fmt"
  4. "github.com/cilium/ebpf"
  5. )
  6. // Tracepoint attaches the given eBPF program to the tracepoint with the given
  7. // group and name. See /sys/kernel/debug/tracing/events to find available
  8. // tracepoints. The top-level directory is the group, the event's subdirectory
  9. // is the name. Example:
  10. //
  11. // Tracepoint("syscalls", "sys_enter_fork")
  12. //
  13. // Note that attaching eBPF programs to syscalls (sys_enter_*/sys_exit_*) is
  14. // only possible as of kernel 4.14 (commit cf5f5ce).
  15. func Tracepoint(group, name string, prog *ebpf.Program) (Link, error) {
  16. if group == "" || name == "" {
  17. return nil, fmt.Errorf("group and name cannot be empty: %w", errInvalidInput)
  18. }
  19. if prog == nil {
  20. return nil, fmt.Errorf("prog cannot be nil: %w", errInvalidInput)
  21. }
  22. if !rgxTraceEvent.MatchString(group) || !rgxTraceEvent.MatchString(name) {
  23. return nil, fmt.Errorf("group and name '%s/%s' must be alphanumeric or underscore: %w", group, name, errInvalidInput)
  24. }
  25. if prog.Type() != ebpf.TracePoint {
  26. return nil, fmt.Errorf("eBPF program type %s is not a Tracepoint: %w", prog.Type(), errInvalidInput)
  27. }
  28. tid, err := getTraceEventID(group, name)
  29. if err != nil {
  30. return nil, err
  31. }
  32. fd, err := openTracepointPerfEvent(tid)
  33. if err != nil {
  34. return nil, err
  35. }
  36. pe := &perfEvent{
  37. fd: fd,
  38. tracefsID: tid,
  39. group: group,
  40. name: name,
  41. progType: ebpf.TracePoint,
  42. }
  43. if err := pe.attach(prog); err != nil {
  44. pe.Close()
  45. return nil, err
  46. }
  47. return pe, nil
  48. }