program.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package link
  2. import (
  3. "fmt"
  4. "github.com/cilium/ebpf"
  5. "github.com/cilium/ebpf/internal/sys"
  6. )
  7. type RawAttachProgramOptions struct {
  8. // File descriptor to attach to. This differs for each attach type.
  9. Target int
  10. // Program to attach.
  11. Program *ebpf.Program
  12. // Program to replace (cgroups).
  13. Replace *ebpf.Program
  14. // Attach must match the attach type of Program (and Replace).
  15. Attach ebpf.AttachType
  16. // Flags control the attach behaviour. This differs for each attach type.
  17. Flags uint32
  18. }
  19. // RawAttachProgram is a low level wrapper around BPF_PROG_ATTACH.
  20. //
  21. // You should use one of the higher level abstractions available in this
  22. // package if possible.
  23. func RawAttachProgram(opts RawAttachProgramOptions) error {
  24. if err := haveProgAttach(); err != nil {
  25. return err
  26. }
  27. var replaceFd uint32
  28. if opts.Replace != nil {
  29. replaceFd = uint32(opts.Replace.FD())
  30. }
  31. attr := sys.ProgAttachAttr{
  32. TargetFd: uint32(opts.Target),
  33. AttachBpfFd: uint32(opts.Program.FD()),
  34. ReplaceBpfFd: replaceFd,
  35. AttachType: uint32(opts.Attach),
  36. AttachFlags: uint32(opts.Flags),
  37. }
  38. if err := sys.ProgAttach(&attr); err != nil {
  39. return fmt.Errorf("can't attach program: %w", err)
  40. }
  41. return nil
  42. }
  43. type RawDetachProgramOptions struct {
  44. Target int
  45. Program *ebpf.Program
  46. Attach ebpf.AttachType
  47. }
  48. // RawDetachProgram is a low level wrapper around BPF_PROG_DETACH.
  49. //
  50. // You should use one of the higher level abstractions available in this
  51. // package if possible.
  52. func RawDetachProgram(opts RawDetachProgramOptions) error {
  53. if err := haveProgAttach(); err != nil {
  54. return err
  55. }
  56. attr := sys.ProgDetachAttr{
  57. TargetFd: uint32(opts.Target),
  58. AttachBpfFd: uint32(opts.Program.FD()),
  59. AttachType: uint32(opts.Attach),
  60. }
  61. if err := sys.ProgDetach(&attr); err != nil {
  62. return fmt.Errorf("can't detach program: %w", err)
  63. }
  64. return nil
  65. }