iter.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package link
  2. import (
  3. "fmt"
  4. "io"
  5. "unsafe"
  6. "github.com/cilium/ebpf"
  7. "github.com/cilium/ebpf/internal/sys"
  8. )
  9. type IterOptions struct {
  10. // Program must be of type Tracing with attach type
  11. // AttachTraceIter. The kind of iterator to attach to is
  12. // determined at load time via the AttachTo field.
  13. //
  14. // AttachTo requires the kernel to include BTF of itself,
  15. // and it to be compiled with a recent pahole (>= 1.16).
  16. Program *ebpf.Program
  17. // Map specifies the target map for bpf_map_elem and sockmap iterators.
  18. // It may be nil.
  19. Map *ebpf.Map
  20. }
  21. // AttachIter attaches a BPF seq_file iterator.
  22. func AttachIter(opts IterOptions) (*Iter, error) {
  23. if err := haveBPFLink(); err != nil {
  24. return nil, err
  25. }
  26. progFd := opts.Program.FD()
  27. if progFd < 0 {
  28. return nil, fmt.Errorf("invalid program: %s", sys.ErrClosedFd)
  29. }
  30. var info bpfIterLinkInfoMap
  31. if opts.Map != nil {
  32. mapFd := opts.Map.FD()
  33. if mapFd < 0 {
  34. return nil, fmt.Errorf("invalid map: %w", sys.ErrClosedFd)
  35. }
  36. info.map_fd = uint32(mapFd)
  37. }
  38. attr := sys.LinkCreateIterAttr{
  39. ProgFd: uint32(progFd),
  40. AttachType: sys.AttachType(ebpf.AttachTraceIter),
  41. IterInfo: sys.NewPointer(unsafe.Pointer(&info)),
  42. IterInfoLen: uint32(unsafe.Sizeof(info)),
  43. }
  44. fd, err := sys.LinkCreateIter(&attr)
  45. if err != nil {
  46. return nil, fmt.Errorf("can't link iterator: %w", err)
  47. }
  48. return &Iter{RawLink{fd, ""}}, err
  49. }
  50. // Iter represents an attached bpf_iter.
  51. type Iter struct {
  52. RawLink
  53. }
  54. // Open creates a new instance of the iterator.
  55. //
  56. // Reading from the returned reader triggers the BPF program.
  57. func (it *Iter) Open() (io.ReadCloser, error) {
  58. attr := &sys.IterCreateAttr{
  59. LinkFd: it.fd.Uint(),
  60. }
  61. fd, err := sys.IterCreate(attr)
  62. if err != nil {
  63. return nil, fmt.Errorf("can't create iterator: %w", err)
  64. }
  65. return fd.File("bpf_iter"), nil
  66. }
  67. // union bpf_iter_link_info.map
  68. type bpfIterLinkInfoMap struct {
  69. map_fd uint32
  70. }