Debian Codegraph @

link/iter.go

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