Debian Codegraph @

btf/handle.go

raw symbols SCIP
1 package btf
2
3 import (
4 "errors"
5 "fmt"
6 "math"
7 "os"
8
9 "github.com/cilium/ebpf/internal"
10 "github.com/cilium/ebpf/internal/platform"
11 "github.com/cilium/ebpf/internal/sys"
12 "github.com/cilium/ebpf/internal/unix"
13 )
14
15 // Handle is a reference to BTF loaded into the kernel.
16 type Handle struct {
17 fd *sys.FD
18
19 // Size of the raw BTF in bytes.
20 size uint32
21
22 needsKernelBase bool
23 }
24
25 // NewHandle loads the contents of a [Builder] into the kernel.
26 //
27 // Returns an error wrapping ErrNotSupported if the kernel doesn't support BTF.
28 func NewHandle(b *Builder) (*Handle, error) {
29 small := getByteSlice()
30 defer putByteSlice(small)
31
32 buf, err := b.Marshal(*small, KernelMarshalOptions())
33 if err != nil {
34 return nil, fmt.Errorf("marshal BTF: %w", err)
35 }
36
37 return NewHandleFromRawBTF(buf)
38 }
39
40 // NewHandleFromRawBTF loads raw BTF into the kernel.
41 //
42 // Returns an error wrapping ErrNotSupported if the kernel doesn't support BTF.
43 func NewHandleFromRawBTF(btf []byte) (*Handle, error) {
44 const minLogSize = 64 * 1024
45
46 if platform.IsWindows {
47 return nil, fmt.Errorf("btf: handle: %w", internal.ErrNotSupportedOnOS)
48 }
49
50 if uint64(len(btf)) > math.MaxUint32 {
51 return nil, errors.New("BTF exceeds the maximum size")
52 }
53
54 attr := &sys.BtfLoadAttr{
55 Btf: sys.SlicePointer(btf),
56 BtfSize: uint32(len(btf)),
57 }
58
59 var (
60 logBuf []byte
61 err error
62 )
63 for {
64 var fd *sys.FD
65 fd, err = sys.BtfLoad(attr)
66 if err == nil {
67 return &Handle{fd, attr.BtfSize, false}, nil
68 }
69
70 if attr.BtfLogTrueSize != 0 && attr.BtfLogSize >= attr.BtfLogTrueSize {
71 // The log buffer already has the correct size.
72 break
73 }
74
75 if attr.BtfLogSize != 0 && !errors.Is(err, unix.ENOSPC) {
76 // Up until at least kernel 6.0, the BTF verifier does not return ENOSPC
77 // if there are other verification errors. ENOSPC is only returned when
78 // the BTF blob is correct, a log was requested, and the provided buffer
79 // is too small. We're therefore not sure whether we got the full
80 // log or not.
81 break
82 }
83
84 // Make an educated guess how large the buffer should be. Start
85 // at a reasonable minimum and then double the size.
86 logSize := uint32(max(len(logBuf)*2, minLogSize))
87 if int(logSize) < len(logBuf) {
88 return nil, errors.New("overflow while probing log buffer size")
89 }
90
91 if attr.BtfLogTrueSize != 0 {
92 // The kernel has given us a hint how large the log buffer has to be.
93 logSize = attr.BtfLogTrueSize
94 }
95
96 logBuf = make([]byte, logSize)
97 attr.BtfLogSize = logSize
98 attr.BtfLogBuf = sys.SlicePointer(logBuf)
99 attr.BtfLogLevel = 1
100 }
101
102 if errors.Is(err, sys.ErrTokenCapabilities) {
103 return nil, fmt.Errorf("load btf: %w", err)
104 }
105
106 if err := haveBTF(); err != nil {
107 return nil, err
108 }
109
110 return nil, internal.ErrorWithLog("load btf", err, logBuf)
111 }
112
113 // NewHandleFromID returns the BTF handle for a given id.
114 //
115 // Prefer calling [ebpf.Program.Handle] or [ebpf.Map.Handle] if possible.
116 //
117 // Returns ErrNotExist, if there is no BTF with the given id.
118 //
119 // Requires CAP_SYS_ADMIN.
120 func NewHandleFromID(id ID) (*Handle, error) {
121 if platform.IsWindows {
122 return nil, fmt.Errorf("btf: handle: %w", internal.ErrNotSupportedOnOS)
123 }
124
125 fd, err := sys.BtfGetFdById(&sys.BtfGetFdByIdAttr{
126 Id: uint32(id),
127 })
128 if err != nil {
129 return nil, fmt.Errorf("get FD for ID %d: %w", id, err)
130 }
131
132 info, err := newHandleInfoFromFD(fd)
133 if err != nil {
134 _ = fd.Close()
135 return nil, err
136 }
137
138 return &Handle{fd, info.size, info.IsModule()}, nil
139 }
140
141 // Spec parses the kernel BTF into Go types.
142 //
143 // base must contain type information for vmlinux if the handle is for
144 // a kernel module. It may be nil otherwise.
145 func (h *Handle) Spec(base *Spec) (*Spec, error) {
146 var btfInfo sys.BtfInfo
147 btfBuffer := make([]byte, h.size)
148 btfInfo.Btf = sys.SlicePointer(btfBuffer)
149 btfInfo.BtfSize = uint32(len(btfBuffer))
150
151 if err := sys.ObjInfo(h.fd, &btfInfo); err != nil {
152 return nil, err
153 }
154
155 if h.needsKernelBase && base == nil {
156 return nil, fmt.Errorf("missing base types")
157 }
158
159 return loadRawSpec(btfBuffer, base)
160 }
161
162 // Close destroys the handle.
163 //
164 // Subsequent calls to FD will return an invalid value.
165 func (h *Handle) Close() error {
166 if h == nil {
167 return nil
168 }
169
170 return h.fd.Close()
171 }
172
173 // FD returns the file descriptor for the handle.
174 func (h *Handle) FD() int {
175 return h.fd.Int()
176 }
177
178 // Clone creates a duplicate of the handle.
179 //
180 // Closing the duplicate does not affect the original, and vice versa.
181 //
182 // Cloning a nil Handle returns nil.
183 func (h *Handle) Clone() (*Handle, error) {
184 if h == nil {
185 return nil, nil
186 }
187
188 dup, err := h.fd.Dup()
189 if err != nil {
190 return nil, fmt.Errorf("can't clone handle: %w", err)
191 }
192
193 return &Handle{dup, h.size, h.needsKernelBase}, nil
194 }
195
196 // Info returns metadata about the handle.
197 func (h *Handle) Info() (*HandleInfo, error) {
198 return newHandleInfoFromFD(h.fd)
199 }
200
201 // HandleInfo describes a Handle.
202 type HandleInfo struct {
203 // ID of this handle in the kernel. The ID is only valid as long as the
204 // associated handle is kept alive.
205 ID ID
206
207 // Name is an identifying name for the BTF, currently only used by the
208 // kernel.
209 Name string
210
211 // IsKernel is true if the BTF originated with the kernel and not
212 // userspace.
213 IsKernel bool
214
215 // Size of the raw BTF in bytes.
216 size uint32
217 }
218
219 func newHandleInfoFromFD(fd *sys.FD) (*HandleInfo, error) {
220 // We invoke the syscall once with a empty BTF and name buffers to get size
221 // information to allocate buffers. Then we invoke it a second time with
222 // buffers to receive the data.
223 var btfInfo sys.BtfInfo
224 if err := sys.ObjInfo(fd, &btfInfo); err != nil {
225 return nil, fmt.Errorf("get BTF info for fd %s: %w", fd, err)
226 }
227
228 if btfInfo.NameLen > 0 {
229 // NameLen doesn't account for the terminating NUL.
230 btfInfo.NameLen++
231 }
232
233 // Don't pull raw BTF by default, since it may be quite large.
234 btfSize := btfInfo.BtfSize
235 btfInfo.BtfSize = 0
236
237 nameBuffer := make([]byte, btfInfo.NameLen)
238 btfInfo.Name = sys.SlicePointer(nameBuffer)
239 btfInfo.NameLen = uint32(len(nameBuffer))
240 if err := sys.ObjInfo(fd, &btfInfo); err != nil {
241 return nil, err
242 }
243
244 return &HandleInfo{
245 ID: ID(btfInfo.Id),
246 Name: unix.ByteSliceToString(nameBuffer),
247 IsKernel: btfInfo.KernelBtf != 0,
248 size: btfSize,
249 }, nil
250 }
251
252 // IsVmlinux returns true if the BTF is for the kernel itself.
253 func (i *HandleInfo) IsVmlinux() bool {
254 return i.IsKernel && i.Name == "vmlinux"
255 }
256
257 // IsModule returns true if the BTF is for a kernel module.
258 func (i *HandleInfo) IsModule() bool {
259 return i.IsKernel && i.Name != "vmlinux"
260 }
261
262 // HandleIterator allows enumerating BTF blobs loaded into the kernel.
263 type HandleIterator struct {
264 // The ID of the current handle. Only valid after a call to Next.
265 ID ID
266 // The current Handle. Only valid until a call to Next.
267 // See Take if you want to retain the handle.
268 Handle *Handle
269 err error
270 }
271
272 // Next retrieves a handle for the next BTF object.
273 //
274 // Returns true if another BTF object was found. Call [HandleIterator.Err] after
275 // the function returns false.
276 func (it *HandleIterator) Next() bool {
277 if platform.IsWindows {
278 it.err = fmt.Errorf("btf: %w", internal.ErrNotSupportedOnOS)
279 return false
280 }
281
282 id := it.ID
283 for {
284 attr := &sys.BtfGetNextIdAttr{Id: id}
285 err := sys.BtfGetNextId(attr)
286 if errors.Is(err, os.ErrNotExist) {
287 // There are no more BTF objects.
288 break
289 } else if err != nil {
290 it.err = fmt.Errorf("get next BTF ID: %w", err)
291 break
292 }
293
294 id = attr.NextId
295 handle, err := NewHandleFromID(id)
296 if errors.Is(err, os.ErrNotExist) {
297 // Try again with the next ID.
298 continue
299 } else if err != nil {
300 it.err = fmt.Errorf("retrieve handle for ID %d: %w", id, err)
301 break
302 }
303
304 it.Handle.Close()
305 it.ID, it.Handle = id, handle
306 return true
307 }
308
309 // No more handles or we encountered an error.
310 it.Handle.Close()
311 it.Handle = nil
312 return false
313 }
314
315 // Take the ownership of the current handle.
316 //
317 // It's the callers responsibility to close the handle.
318 func (it *HandleIterator) Take() *Handle {
319 handle := it.Handle
320 it.Handle = nil
321 return handle
322 }
323
324 // Err returns an error if iteration failed for some reason.
325 func (it *HandleIterator) Err() error {
326 return it.err
327 }
328
329 // FindHandle returns the first handle for which predicate returns true.
330 //
331 // Requires CAP_SYS_ADMIN.
332 //
333 // Returns an error wrapping ErrNotFound if predicate never returns true or if
334 // there is no BTF loaded into the kernel.
335 func FindHandle(predicate func(info *HandleInfo) bool) (*Handle, error) {
336 it := new(HandleIterator)
337 defer it.Handle.Close()
338
339 for it.Next() {
340 info, err := it.Handle.Info()
341 if err != nil {
342 return nil, fmt.Errorf("info for ID %d: %w", it.ID, err)
343 }
344
345 if predicate(info) {
346 return it.Take(), nil
347 }
348 }
349 if err := it.Err(); err != nil {
350 return nil, fmt.Errorf("iterate handles: %w", err)
351 }
352
353 return nil, fmt.Errorf("find handle: %w", ErrNotFound)
354 }