Debian Codegraph @

info.go

raw symbols SCIP
1 package ebpf
2
3 import (
4 "bufio"
5 "bytes"
6 "encoding/hex"
7 "errors"
8 "fmt"
9 "io"
10 "os"
11 "reflect"
12 "time"
13
14 "github.com/cilium/ebpf/asm"
15 "github.com/cilium/ebpf/btf"
16 "github.com/cilium/ebpf/internal"
17 "github.com/cilium/ebpf/internal/platform"
18 "github.com/cilium/ebpf/internal/sys"
19 "github.com/cilium/ebpf/internal/unix"
20 )
21
22 // The *Info structs expose metadata about a program or map. Most
23 // fields are exposed via a getter:
24 //
25 // func (*MapInfo) ID() (MapID, bool)
26 //
27 // This is because the metadata available changes based on kernel version.
28 // The second boolean return value indicates whether a particular field is
29 // available on the current kernel.
30 //
31 // Always add new metadata as such a getter, unless you can somehow get the
32 // value of the field on all supported kernels. Also document which version
33 // a particular field first appeared in.
34 //
35 // Some metadata is a buffer which needs additional parsing. In this case,
36 // store the undecoded data in the Info struct and provide a getter which
37 // decodes it when necessary. See ProgramInfo.Instructions for an example.
38
39 // MapInfo describes a map.
40 type MapInfo struct {
41 // Type of the map.
42 Type MapType
43 // KeySize is the size of the map key in bytes.
44 KeySize uint32
45 // ValueSize is the size of the map value in bytes.
46 ValueSize uint32
47 // MaxEntries is the maximum number of entries the map can hold. Its meaning
48 // is map-specific.
49 MaxEntries uint32
50 // Flags used during map creation.
51 Flags uint32
52 // Name as supplied by user space at load time. Available from 4.15.
53 Name string
54
55 id MapID
56 btf btf.ID
57 mapExtra uint64
58 memlock uint64
59 frozen bool
60 }
61
62 // minimalMapInfoFromFd queries the minimum information needed to create a Map
63 // based on a file descriptor. This requires the map type, key/value sizes,
64 // maxentries and flags.
65 //
66 // Does not fall back to fdinfo since the version gap between fdinfo (4.10) and
67 // [sys.ObjInfo] (4.13) is small and both kernels are EOL since at least Nov
68 // 2017.
69 //
70 // Requires at least Linux 4.13.
71 func minimalMapInfoFromFd(fd *sys.FD) (*MapInfo, error) {
72 var info sys.MapInfo
73 if err := sys.ObjInfo(fd, &info); err != nil {
74 return nil, fmt.Errorf("getting object info: %w", err)
75 }
76
77 typ, err := MapTypeForPlatform(platform.Native, info.Type)
78 if err != nil {
79 return nil, fmt.Errorf("map type: %w", err)
80 }
81
82 return &MapInfo{
83 Type: typ,
84 KeySize: info.KeySize,
85 ValueSize: info.ValueSize,
86 MaxEntries: info.MaxEntries,
87 Flags: uint32(info.MapFlags),
88 Name: unix.ByteSliceToString(info.Name[:]),
89 }, nil
90 }
91
92 // newMapInfoFromFd queries map information about the given fd. [sys.ObjInfo] is
93 // attempted first, supplementing any missing values with information from
94 // /proc/self/fdinfo. Ignores EINVAL from ObjInfo as well as ErrNotSupported
95 // from reading fdinfo (indicating the file exists, but no fields of interest
96 // were found). If both fail, an error is always returned.
97 func newMapInfoFromFd(fd *sys.FD) (*MapInfo, error) {
98 var info sys.MapInfo
99 err1 := sys.ObjInfo(fd, &info)
100 // EINVAL means the kernel doesn't support BPF_OBJ_GET_INFO_BY_FD. Continue
101 // with fdinfo if that's the case.
102 if err1 != nil && !errors.Is(err1, unix.EINVAL) {
103 return nil, fmt.Errorf("getting object info: %w", err1)
104 }
105
106 typ, err := MapTypeForPlatform(platform.Native, info.Type)
107 if err != nil {
108 return nil, fmt.Errorf("map type: %w", err)
109 }
110
111 mi := &MapInfo{
112 typ,
113 info.KeySize,
114 info.ValueSize,
115 info.MaxEntries,
116 uint32(info.MapFlags),
117 unix.ByteSliceToString(info.Name[:]),
118 MapID(info.Id),
119 btf.ID(info.BtfId),
120 info.MapExtra,
121 0,
122 false,
123 }
124
125 // Supplement OBJ_INFO with data from /proc/self/fdinfo. It contains fields
126 // like memlock and frozen that are not present in OBJ_INFO.
127 err2 := readMapInfoFromProc(fd, mi)
128 if err2 != nil && !errors.Is(err2, ErrNotSupported) {
129 return nil, fmt.Errorf("getting map info from fdinfo: %w", err2)
130 }
131
132 if err1 != nil && err2 != nil {
133 return nil, fmt.Errorf("ObjInfo and fdinfo both failed: objinfo: %w, fdinfo: %w", err1, err2)
134 }
135
136 return mi, nil
137 }
138
139 // readMapInfoFromProc queries map information about the given fd from
140 // /proc/self/fdinfo. It only writes data into fields that have a zero value.
141 func readMapInfoFromProc(fd *sys.FD, mi *MapInfo) error {
142 var mapType uint32
143 err := scanFdInfo(fd, map[string]any{
144 "map_type": &mapType,
145 "map_id": &mi.id,
146 "key_size": &mi.KeySize,
147 "value_size": &mi.ValueSize,
148 "max_entries": &mi.MaxEntries,
149 "map_flags": &mi.Flags,
150 "map_extra": &mi.mapExtra,
151 "memlock": &mi.memlock,
152 "frozen": &mi.frozen,
153 })
154 if err != nil {
155 return err
156 }
157
158 if mi.Type == 0 {
159 mi.Type, err = MapTypeForPlatform(platform.Linux, mapType)
160 if err != nil {
161 return fmt.Errorf("map type: %w", err)
162 }
163 }
164
165 return nil
166 }
167
168 // ID returns the map ID.
169 //
170 // Available from 4.13.
171 //
172 // The bool return value indicates whether this optional field is available.
173 func (mi *MapInfo) ID() (MapID, bool) {
174 return mi.id, mi.id > 0
175 }
176
177 // BTFID returns the BTF ID associated with the Map.
178 //
179 // The ID is only valid as long as the associated Map is kept alive.
180 // Available from 4.18.
181 //
182 // The bool return value indicates whether this optional field is available and
183 // populated. (The field may be available but not populated if the kernel
184 // supports the field but the Map was loaded without BTF information.)
185 func (mi *MapInfo) BTFID() (btf.ID, bool) {
186 return mi.btf, mi.btf > 0
187 }
188
189 // MapExtra returns an opaque field whose meaning is map-specific.
190 //
191 // Available from 5.16.
192 //
193 // The bool return value indicates whether this optional field is available and
194 // populated, if it was specified during Map creation.
195 func (mi *MapInfo) MapExtra() (uint64, bool) {
196 return mi.mapExtra, mi.mapExtra > 0
197 }
198
199 // Memlock returns an approximate number of bytes allocated to this map.
200 //
201 // Available from 4.10.
202 //
203 // The bool return value indicates whether this optional field is available.
204 func (mi *MapInfo) Memlock() (uint64, bool) {
205 return mi.memlock, mi.memlock > 0
206 }
207
208 // Frozen indicates whether [Map.Freeze] was called on this map. If true,
209 // modifications from user space are not allowed.
210 //
211 // Available from 5.2. Requires access to procfs.
212 //
213 // If the kernel doesn't support map freezing, this field will always be false.
214 func (mi *MapInfo) Frozen() bool {
215 return mi.frozen
216 }
217
218 // ProgramStats contains runtime statistics for a single [Program], returned by
219 // [Program.Stats].
220 //
221 // Will contain mostly zero values if the collection of statistics is not
222 // enabled, see [EnableStats].
223 type ProgramStats struct {
224 // Total accumulated runtime of the Program.
225 //
226 // Requires at least Linux 5.8.
227 Runtime time.Duration
228
229 // Total number of times the Program has executed.
230 //
231 // Requires at least Linux 5.8.
232 RunCount uint64
233
234 // Total number of times the program was not executed due to recursion. This
235 // can happen when another bpf program is already running on the cpu, when bpf
236 // program execution is interrupted, for example.
237 //
238 // Requires at least Linux 5.12.
239 RecursionMisses uint64
240 }
241
242 func newProgramStatsFromFd(fd *sys.FD) (*ProgramStats, error) {
243 var info sys.ProgInfo
244 if err := sys.ObjInfo(fd, &info); err != nil {
245 return nil, fmt.Errorf("getting program info: %w", err)
246 }
247
248 return &ProgramStats{
249 Runtime: time.Duration(info.RunTimeNs),
250 RunCount: info.RunCnt,
251 RecursionMisses: info.RecursionMisses,
252 }, nil
253 }
254
255 // programJitedInfo holds information about JITed info of a program.
256 type programJitedInfo struct {
257 // ksyms holds the ksym addresses of the BPF program, including those of its
258 // subprograms.
259 //
260 // Available from 4.18.
261 ksyms []uint64
262 numKsyms uint32
263
264 // insns holds the JITed machine native instructions of the program,
265 // including those of its subprograms.
266 //
267 // Available from 4.13.
268 insns []byte
269 numInsns uint32
270
271 // lineInfos holds the JITed line infos, which are kernel addresses.
272 //
273 // Available from 5.0.
274 lineInfos []uint64
275 numLineInfos uint32
276
277 // lineInfoRecSize is the size of a single line info record.
278 //
279 // Available from 5.0.
280 lineInfoRecSize uint32
281
282 // funcLens holds the insns length of each function.
283 //
284 // Available from 4.18.
285 funcLens []uint32
286 numFuncLens uint32
287 }
288
289 // ProgramInfo describes a Program's immutable metadata. For runtime statistics,
290 // see [ProgramStats].
291 type ProgramInfo struct {
292 Type ProgramType
293 id ProgramID
294 // Truncated hash of the BPF bytecode. Available from 4.13.
295 Tag string
296 // Name as supplied by user space at load time. Available from 4.15.
297 Name string
298
299 createdByUID uint32
300 haveCreatedByUID bool
301 btf btf.ID
302 loadTime time.Duration
303
304 restricted bool
305
306 maps []MapID
307 insns []byte
308 numInsns uint32
309 jitedSize uint32
310 verifiedInstructions uint32
311
312 jitedInfo programJitedInfo
313
314 lineInfos []byte
315 numLineInfos uint32
316 funcInfos []byte
317 numFuncInfos uint32
318
319 memlock uint64
320 }
321
322 // minimalProgramFromFd queries the minimum information needed to create a
323 // Program based on a file descriptor, requiring at least the program type.
324 //
325 // Does not fall back to fdinfo since the version gap between fdinfo (4.10) and
326 // [sys.ObjInfo] (4.13) is small and both kernels are EOL since at least Nov
327 // 2017.
328 //
329 // Requires at least Linux 4.13.
330 func minimalProgramInfoFromFd(fd *sys.FD) (*ProgramInfo, error) {
331 var info sys.ProgInfo
332 if err := sys.ObjInfo(fd, &info); err != nil {
333 return nil, fmt.Errorf("getting object info: %w", err)
334 }
335
336 typ, err := ProgramTypeForPlatform(platform.Native, info.Type)
337 if err != nil {
338 return nil, fmt.Errorf("program type: %w", err)
339 }
340
341 return &ProgramInfo{
342 Type: typ,
343 Name: unix.ByteSliceToString(info.Name[:]),
344 }, nil
345 }
346
347 // newProgramInfoFromFd queries program information about the given fd.
348 //
349 // [sys.ObjInfo] is attempted first, supplementing any missing values with
350 // information from /proc/self/fdinfo. Ignores EINVAL from ObjInfo as well as
351 // ErrNotSupported from reading fdinfo (indicating the file exists, but no
352 // fields of interest were found). If both fail, an error is always returned.
353 func newProgramInfoFromFd(fd *sys.FD) (*ProgramInfo, error) {
354 var info sys.ProgInfo
355 err1 := sys.ObjInfo(fd, &info)
356 // EINVAL means the kernel doesn't support BPF_OBJ_GET_INFO_BY_FD. Continue
357 // with fdinfo if that's the case.
358 if err1 != nil && !errors.Is(err1, unix.EINVAL) {
359 return nil, fmt.Errorf("getting object info: %w", err1)
360 }
361
362 typ, err := ProgramTypeForPlatform(platform.Native, info.Type)
363 if err != nil {
364 return nil, fmt.Errorf("program type: %w", err)
365 }
366
367 pi := ProgramInfo{
368 Type: typ,
369 id: ProgramID(info.Id),
370 Tag: hex.EncodeToString(info.Tag[:]),
371 Name: unix.ByteSliceToString(info.Name[:]),
372 btf: btf.ID(info.BtfId),
373 jitedSize: info.JitedProgLen,
374 loadTime: time.Duration(info.LoadTime),
375 verifiedInstructions: info.VerifiedInsns,
376 numInsns: info.XlatedProgLen,
377 }
378
379 // Supplement OBJ_INFO with data from /proc/self/fdinfo. It contains fields
380 // like memlock that is not present in OBJ_INFO.
381 err2 := readProgramInfoFromProc(fd, &pi)
382 if err2 != nil && !errors.Is(err2, ErrNotSupported) {
383 return nil, fmt.Errorf("getting map info from fdinfo: %w", err2)
384 }
385
386 if err1 != nil && err2 != nil {
387 return nil, fmt.Errorf("ObjInfo and fdinfo both failed: objinfo: %w, fdinfo: %w", err1, err2)
388 }
389
390 if platform.IsWindows && info.Tag == [8]uint8{} {
391 // Windows doesn't support the tag field, clear it for now.
392 pi.Tag = ""
393 }
394
395 // Start with a clean struct for the second call, otherwise we may get EFAULT.
396 var info2 sys.ProgInfo
397
398 makeSecondCall := false
399
400 if info.NrMapIds > 0 {
401 pi.maps = make([]MapID, info.NrMapIds)
402 info2.NrMapIds = info.NrMapIds
403 info2.MapIds = sys.SlicePointer(pi.maps)
404 makeSecondCall = true
405 } else if haveProgramInfoMapIDs() == nil {
406 // This program really has no associated maps.
407 pi.maps = make([]MapID, 0)
408 } else {
409 // The kernel doesn't report associated maps.
410 pi.maps = nil
411 }
412
413 // createdByUID and NrMapIds were introduced in the same kernel version.
414 if pi.maps != nil && platform.IsLinux {
415 pi.createdByUID = info.CreatedByUid
416 pi.haveCreatedByUID = true
417 }
418
419 if info.XlatedProgLen > 0 {
420 pi.insns = make([]byte, info.XlatedProgLen)
421 var info3 sys.ProgInfo
422 info3.XlatedProgLen = info.XlatedProgLen
423 info3.XlatedProgInsns = sys.SlicePointer(pi.insns)
424
425 // When kernel.kptr_restrict and net.core.bpf_jit_harden are both set, it causes the
426 // syscall to abort when trying to readback xlated instructions, skipping other info
427 // as well. So request xlated instructions separately.
428 if err := sys.ObjInfo(fd, &info3); err != nil {
429 return nil, err
430 }
431 if info3.XlatedProgInsns.IsNil() {
432 pi.restricted = true
433 pi.insns = nil
434 }
435 }
436
437 if info.NrLineInfo > 0 {
438 pi.lineInfos = make([]byte, btf.LineInfoSize*info.NrLineInfo)
439 info2.LineInfo = sys.SlicePointer(pi.lineInfos)
440 info2.LineInfoRecSize = btf.LineInfoSize
441 info2.NrLineInfo = info.NrLineInfo
442 pi.numLineInfos = info.NrLineInfo
443 makeSecondCall = true
444 }
445
446 if info.NrFuncInfo > 0 {
447 pi.funcInfos = make([]byte, btf.FuncInfoSize*info.NrFuncInfo)
448 info2.FuncInfo = sys.SlicePointer(pi.funcInfos)
449 info2.FuncInfoRecSize = btf.FuncInfoSize
450 info2.NrFuncInfo = info.NrFuncInfo
451 pi.numFuncInfos = info.NrFuncInfo
452 makeSecondCall = true
453 }
454
455 pi.jitedInfo.lineInfoRecSize = info.JitedLineInfoRecSize
456 if info.JitedProgLen > 0 {
457 pi.jitedInfo.numInsns = info.JitedProgLen
458 pi.jitedInfo.insns = make([]byte, info.JitedProgLen)
459 info2.JitedProgLen = info.JitedProgLen
460 info2.JitedProgInsns = sys.SlicePointer(pi.jitedInfo.insns)
461 makeSecondCall = true
462 }
463
464 if info.NrJitedFuncLens > 0 {
465 pi.jitedInfo.numFuncLens = info.NrJitedFuncLens
466 pi.jitedInfo.funcLens = make([]uint32, info.NrJitedFuncLens)
467 info2.NrJitedFuncLens = info.NrJitedFuncLens
468 info2.JitedFuncLens = sys.SlicePointer(pi.jitedInfo.funcLens)
469 makeSecondCall = true
470 }
471
472 if info.NrJitedLineInfo > 0 {
473 pi.jitedInfo.numLineInfos = info.NrJitedLineInfo
474 pi.jitedInfo.lineInfos = make([]uint64, info.NrJitedLineInfo)
475 info2.NrJitedLineInfo = info.NrJitedLineInfo
476 info2.JitedLineInfo = sys.SlicePointer(pi.jitedInfo.lineInfos)
477 info2.JitedLineInfoRecSize = info.JitedLineInfoRecSize
478 makeSecondCall = true
479 }
480
481 if info.NrJitedKsyms > 0 {
482 pi.jitedInfo.numKsyms = info.NrJitedKsyms
483 pi.jitedInfo.ksyms = make([]uint64, info.NrJitedKsyms)
484 info2.JitedKsyms = sys.SlicePointer(pi.jitedInfo.ksyms)
485 info2.NrJitedKsyms = info.NrJitedKsyms
486 makeSecondCall = true
487 }
488
489 if makeSecondCall {
490 if err := sys.ObjInfo(fd, &info2); err != nil {
491 return nil, err
492 }
493 if info.JitedProgLen > 0 && info2.JitedProgInsns.IsNil() {
494 // JIT information is not available due to kernel.kptr_restrict
495 pi.jitedInfo.lineInfos = nil
496 pi.jitedInfo.ksyms = nil
497 pi.jitedInfo.insns = nil
498 pi.jitedInfo.funcLens = nil
499 }
500 }
501
502 if len(pi.Name) == len(info.Name)-1 { // Possibly truncated, check BTF info for full name
503 name, err := readNameFromFunc(&pi)
504 if err == nil {
505 pi.Name = name
506 } // If an error occurs, keep the truncated name, which is better than none
507 }
508
509 return &pi, nil
510 }
511
512 func readNameFromFunc(pi *ProgramInfo) (string, error) {
513 if pi.numFuncInfos == 0 {
514 return "", errors.New("no function info")
515 }
516
517 spec, err := pi.btfSpec()
518 if err != nil {
519 return "", err
520 }
521
522 funcInfos, err := btf.LoadFuncInfos(
523 bytes.NewReader(pi.funcInfos),
524 internal.NativeEndian,
525 pi.numFuncInfos,
526 spec,
527 )
528 if err != nil {
529 return "", err
530 }
531
532 for _, funcInfo := range funcInfos {
533 if funcInfo.Offset == 0 { // Information about the whole program
534 return funcInfo.Func.Name, nil
535 }
536 }
537 return "", errors.New("no function info about program")
538 }
539
540 func readProgramInfoFromProc(fd *sys.FD, pi *ProgramInfo) error {
541 var progType uint32
542 err := scanFdInfo(fd, map[string]any{
543 "prog_type": &progType,
544 "prog_tag": &pi.Tag,
545 "memlock": &pi.memlock,
546 })
547 if errors.Is(err, ErrNotSupported) && !errors.Is(err, internal.ErrNotSupportedOnOS) {
548 return &internal.UnsupportedFeatureError{
549 Name: "reading program info from /proc/self/fdinfo",
550 MinimumVersion: internal.Version{4, 10, 0},
551 }
552 }
553 if err != nil {
554 return err
555 }
556
557 pi.Type, err = ProgramTypeForPlatform(platform.Linux, progType)
558 if err != nil {
559 return fmt.Errorf("program type: %w", err)
560 }
561
562 return nil
563 }
564
565 // ID returns the program ID.
566 //
567 // Available from 4.13.
568 //
569 // The bool return value indicates whether this optional field is available.
570 func (pi *ProgramInfo) ID() (ProgramID, bool) {
571 return pi.id, pi.id > 0
572 }
573
574 // CreatedByUID returns the Uid that created the program.
575 //
576 // Available from 4.15.
577 //
578 // The bool return value indicates whether this optional field is available.
579 func (pi *ProgramInfo) CreatedByUID() (uint32, bool) {
580 return pi.createdByUID, pi.haveCreatedByUID
581 }
582
583 // BTFID returns the BTF ID associated with the program.
584 //
585 // The ID is only valid as long as the associated program is kept alive.
586 // Available from 5.0.
587 //
588 // The bool return value indicates whether this optional field is available and
589 // populated. (The field may be available but not populated if the kernel
590 // supports the field but the program was loaded without BTF information.)
591 func (pi *ProgramInfo) BTFID() (btf.ID, bool) {
592 return pi.btf, pi.btf > 0
593 }
594
595 // btfSpec returns the BTF spec associated with the program.
596 func (pi *ProgramInfo) btfSpec() (*btf.Spec, error) {
597 id, ok := pi.BTFID()
598 if !ok {
599 return nil, fmt.Errorf("program created without BTF or unsupported kernel: %w", ErrNotSupported)
600 }
601
602 h, err := btf.NewHandleFromID(id)
603 if err != nil {
604 return nil, fmt.Errorf("get BTF handle: %w", err)
605 }
606 defer h.Close()
607
608 spec, err := h.Spec(nil)
609 if err != nil {
610 return nil, fmt.Errorf("get BTF spec: %w", err)
611 }
612
613 return spec, nil
614 }
615
616 // ErrRestrictedKernel is returned when kernel address information is restricted
617 // by kernel.kptr_restrict and/or net.core.bpf_jit_harden sysctls.
618 var ErrRestrictedKernel = internal.ErrRestrictedKernel
619
620 // LineInfos returns the BTF line information of the program.
621 //
622 // Available from 5.0.
623 //
624 // Returns an error wrapping [ErrRestrictedKernel] if line infos are restricted
625 // by sysctls.
626 //
627 // Requires CAP_SYS_ADMIN or equivalent for reading BTF information. Returns
628 // ErrNotSupported if the program was created without BTF or if the kernel
629 // doesn't support the field.
630 func (pi *ProgramInfo) LineInfos() (btf.LineOffsets, error) {
631 if len(pi.lineInfos) == 0 {
632 return nil, fmt.Errorf("insufficient permissions or unsupported kernel: %w", ErrNotSupported)
633 }
634
635 spec, err := pi.btfSpec()
636 if err != nil {
637 return nil, err
638 }
639
640 return btf.LoadLineInfos(
641 bytes.NewReader(pi.lineInfos),
642 internal.NativeEndian,
643 pi.numLineInfos,
644 spec,
645 )
646 }
647
648 // Instructions returns the 'xlated' instruction stream of the program
649 // after it has been verified and rewritten by the kernel. These instructions
650 // cannot be loaded back into the kernel as-is, this is mainly used for
651 // inspecting loaded programs for troubleshooting, dumping, etc.
652 //
653 // For example, map accesses are made to reference their kernel map IDs,
654 // not the FDs they had when the program was inserted. Note that before
655 // the introduction of bpf_insn_prepare_dump in kernel 4.16, xlated
656 // instructions were not sanitized, making the output even less reusable
657 // and less likely to round-trip or evaluate to the same program Tag.
658 //
659 // The first instruction is marked as a symbol using the Program's name.
660 //
661 // If available, the instructions will be annotated with metadata from the
662 // BTF. This includes line information and function information. Reading
663 // this metadata requires CAP_SYS_ADMIN or equivalent. If capability is
664 // unavailable, the instructions will be returned without metadata.
665 //
666 // Returns an error wrapping [ErrRestrictedKernel] if instructions are
667 // restricted by sysctls.
668 //
669 // Available from 4.13. Requires CAP_BPF or equivalent for plain instructions.
670 // Requires CAP_SYS_ADMIN for instructions with metadata.
671 func (pi *ProgramInfo) Instructions() (asm.Instructions, error) {
672 if platform.IsWindows && len(pi.insns) == 0 {
673 return nil, fmt.Errorf("read instructions: %w", internal.ErrNotSupportedOnOS)
674 }
675
676 if pi.restricted {
677 return nil, fmt.Errorf("instructions: %w", ErrRestrictedKernel)
678 }
679
680 // If the calling process is not BPF-capable or if the kernel doesn't
681 // support getting xlated instructions, the field will be zero.
682 if len(pi.insns) == 0 {
683 return nil, fmt.Errorf("insufficient permissions or unsupported kernel: %w", ErrNotSupported)
684 }
685
686 r := bytes.NewReader(pi.insns)
687 insns, err := asm.AppendInstructions(nil, r, internal.NativeEndian, platform.Native)
688 if err != nil {
689 return nil, fmt.Errorf("unmarshaling instructions: %w", err)
690 }
691
692 if pi.btf != 0 {
693 btfh, err := btf.NewHandleFromID(pi.btf)
694 if err != nil {
695 // Getting a BTF handle requires CAP_SYS_ADMIN, if not available we get an -EPERM.
696 // Ignore it and fall back to instructions without metadata.
697 if !errors.Is(err, unix.EPERM) {
698 return nil, fmt.Errorf("unable to get BTF handle: %w", err)
699 }
700 }
701
702 // If we have a BTF handle, we can use it to assign metadata to the instructions.
703 if btfh != nil {
704 defer btfh.Close()
705
706 spec, err := btfh.Spec(nil)
707 if err != nil {
708 return nil, fmt.Errorf("unable to get BTF spec: %w", err)
709 }
710
711 lineInfos, err := btf.LoadLineInfos(bytes.NewReader(pi.lineInfos), internal.NativeEndian, pi.numLineInfos, spec)
712 if err != nil {
713 return nil, fmt.Errorf("parse line info: %w", err)
714 }
715
716 funcInfos, err := btf.LoadFuncInfos(bytes.NewReader(pi.funcInfos), internal.NativeEndian, pi.numFuncInfos, spec)
717 if err != nil {
718 return nil, fmt.Errorf("parse func info: %w", err)
719 }
720
721 iter := insns.Iterate()
722 for iter.Next() {
723 assignMetadata(iter.Ins, iter.Offset, &funcInfos, &lineInfos, nil)
724 }
725 }
726 }
727
728 fn := btf.FuncMetadata(&insns[0])
729 name := pi.Name
730 if fn != nil {
731 name = fn.Name
732 }
733 insns[0] = insns[0].WithSymbol(name)
734
735 return insns, nil
736 }
737
738 // JitedSize returns the size of the program's JIT-compiled machine code in
739 // bytes, which is the actual code executed on the host's CPU. This field
740 // requires the BPF JIT compiler to be enabled.
741 //
742 // Returns an error wrapping [ErrRestrictedKernel] if jited program size is
743 // restricted by sysctls.
744 //
745 // Available from 4.13. Reading this metadata requires CAP_BPF or equivalent.
746 func (pi *ProgramInfo) JitedSize() (uint32, error) {
747 if pi.jitedSize == 0 {
748 return 0, fmt.Errorf("insufficient permissions, unsupported kernel, or JIT compiler disabled: %w", ErrNotSupported)
749 }
750 return pi.jitedSize, nil
751 }
752
753 // TranslatedSize returns the size of the program's translated instructions in
754 // bytes, after it has been verified and rewritten by the kernel.
755 //
756 // Available from 4.13. Reading this metadata requires CAP_BPF or equivalent.
757 func (pi *ProgramInfo) TranslatedSize() (int, error) {
758 if pi.numInsns == 0 {
759 return 0, fmt.Errorf("insufficient permissions or unsupported kernel: %w", ErrNotSupported)
760 }
761 return int(pi.numInsns), nil
762 }
763
764 // MapIDs returns the maps related to the program.
765 //
766 // Available from 4.15.
767 //
768 // The bool return value indicates whether this optional field is available.
769 func (pi *ProgramInfo) MapIDs() ([]MapID, bool) {
770 return pi.maps, pi.maps != nil
771 }
772
773 // LoadTime returns when the program was loaded since boot time.
774 //
775 // Available from 4.15.
776 //
777 // The bool return value indicates whether this optional field is available.
778 func (pi *ProgramInfo) LoadTime() (time.Duration, bool) {
779 // loadTime and NrMapIds were introduced in the same kernel version.
780 return pi.loadTime, pi.loadTime > 0
781 }
782
783 // VerifiedInstructions returns the number verified instructions in the program.
784 //
785 // Available from 5.16.
786 //
787 // The bool return value indicates whether this optional field is available.
788 func (pi *ProgramInfo) VerifiedInstructions() (uint32, bool) {
789 return pi.verifiedInstructions, pi.verifiedInstructions > 0
790 }
791
792 // JitedKsymAddrs returns the ksym addresses of the BPF program, including its
793 // subprograms. The addresses correspond to their symbols in /proc/kallsyms.
794 //
795 // Available from 4.18. Note that before 5.x, this field can be empty for
796 // programs without subprograms (bpf2bpf calls).
797 //
798 // The bool return value indicates whether this optional field is available.
799 //
800 // When a kernel address can't fit into uintptr (which is usually the case when
801 // running 32 bit program on a 64 bit kernel), this returns an empty slice and
802 // a false.
803 func (pi *ProgramInfo) JitedKsymAddrs() ([]uintptr, bool) {
804 ksyms := make([]uintptr, 0, len(pi.jitedInfo.ksyms))
805 if cap(ksyms) == 0 {
806 return ksyms, false
807 }
808 // Check if a kernel address fits into uintptr (it might not when
809 // using a 32 bit binary on a 64 bit kernel). This check should work
810 // with any kernel address, since they have 1s at the highest bits.
811 if a := pi.jitedInfo.ksyms[0]; uint64(uintptr(a)) != a {
812 return nil, false
813 }
814 for _, ksym := range pi.jitedInfo.ksyms {
815 ksyms = append(ksyms, uintptr(ksym))
816 }
817 return ksyms, true
818 }
819
820 // JitedInsns returns the JITed machine native instructions of the program.
821 //
822 // Available from 4.13.
823 //
824 // The bool return value indicates whether this optional field is available.
825 func (pi *ProgramInfo) JitedInsns() ([]byte, bool) {
826 return pi.jitedInfo.insns, len(pi.jitedInfo.insns) > 0
827 }
828
829 // JitedLineInfos returns the JITed line infos of the program.
830 //
831 // Available from 5.0.
832 //
833 // The bool return value indicates whether this optional field is available.
834 func (pi *ProgramInfo) JitedLineInfos() ([]uint64, bool) {
835 return pi.jitedInfo.lineInfos, len(pi.jitedInfo.lineInfos) > 0
836 }
837
838 // JitedFuncLens returns the insns length of each function in the JITed program.
839 //
840 // Available from 4.18.
841 //
842 // The bool return value indicates whether this optional field is available.
843 func (pi *ProgramInfo) JitedFuncLens() ([]uint32, bool) {
844 return pi.jitedInfo.funcLens, len(pi.jitedInfo.funcLens) > 0
845 }
846
847 // FuncInfos returns the offset and function information of all (sub)programs in
848 // a BPF program.
849 //
850 // Available from 5.0.
851 //
852 // Returns an error wrapping [ErrRestrictedKernel] if function information is
853 // restricted by sysctls.
854 //
855 // Requires CAP_SYS_ADMIN or equivalent for reading BTF information. Returns
856 // ErrNotSupported if the program was created without BTF or if the kernel
857 // doesn't support the field.
858 func (pi *ProgramInfo) FuncInfos() (btf.FuncOffsets, error) {
859 if len(pi.funcInfos) == 0 {
860 return nil, fmt.Errorf("insufficient permissions or unsupported kernel: %w", ErrNotSupported)
861 }
862
863 spec, err := pi.btfSpec()
864 if err != nil {
865 return nil, err
866 }
867
868 return btf.LoadFuncInfos(
869 bytes.NewReader(pi.funcInfos),
870 internal.NativeEndian,
871 pi.numFuncInfos,
872 spec,
873 )
874 }
875
876 // ProgramInfo returns an approximate number of bytes allocated to this program.
877 //
878 // Available from 4.10.
879 //
880 // The bool return value indicates whether this optional field is available.
881 func (pi *ProgramInfo) Memlock() (uint64, bool) {
882 return pi.memlock, pi.memlock > 0
883 }
884
885 func scanFdInfo(fd *sys.FD, fields map[string]any) error {
886 if platform.IsWindows {
887 return fmt.Errorf("read fdinfo: %w", internal.ErrNotSupportedOnOS)
888 }
889
890 fh, err := os.Open(fmt.Sprintf("/proc/self/fdinfo/%d", fd.Int()))
891 if err != nil {
892 return err
893 }
894 defer fh.Close()
895
896 if err := scanFdInfoReader(fh, fields); err != nil {
897 return fmt.Errorf("%s: %w", fh.Name(), err)
898 }
899 return nil
900 }
901
902 func scanFdInfoReader(r io.Reader, fields map[string]any) error {
903 var (
904 scanner = bufio.NewScanner(r)
905 scanned int
906 reader bytes.Reader
907 )
908
909 for scanner.Scan() {
910 key, rest, found := bytes.Cut(scanner.Bytes(), []byte(":"))
911 if !found {
912 // Line doesn't contain a colon, skip.
913 continue
914 }
915 field, ok := fields[string(key)]
916 if !ok {
917 continue
918 }
919 // If field already contains a non-zero value, don't overwrite it with fdinfo.
920 if !zero(field) {
921 scanned++
922 continue
923 }
924
925 // Cut the \t following the : as well as any potential trailing whitespace.
926 rest = bytes.TrimSpace(rest)
927
928 reader.Reset(rest)
929 if n, err := fmt.Fscan(&reader, field); err != nil || n != 1 {
930 return fmt.Errorf("can't parse field %s: %v", key, err)
931 }
932
933 scanned++
934 }
935
936 if err := scanner.Err(); err != nil {
937 return fmt.Errorf("scanning fdinfo: %w", err)
938 }
939
940 if len(fields) > 0 && scanned == 0 {
941 return ErrNotSupported
942 }
943
944 return nil
945 }
946
947 func zero(arg any) bool {
948 v := reflect.ValueOf(arg)
949
950 // Unwrap pointers and interfaces.
951 for v.Kind() == reflect.Pointer ||
952 v.Kind() == reflect.Interface {
953 v = v.Elem()
954 }
955
956 return v.IsZero()
957 }
958
959 // EnableStats starts collecting runtime statistics of eBPF programs, like the
960 // amount of program executions and the cumulative runtime.
961 //
962 // Specify a BPF_STATS_* constant to select which statistics to collect, like
963 // [unix.BPF_STATS_RUN_TIME]. Closing the returned [io.Closer] will stop
964 // collecting statistics.
965 //
966 // Collecting statistics may have a performance impact.
967 //
968 // Requires at least Linux 5.8.
969 func EnableStats(which uint32) (io.Closer, error) {
970 fd, err := sys.EnableStats(&sys.EnableStatsAttr{
971 Type: which,
972 })
973 if err != nil {
974 return nil, err
975 }
976 return fd, nil
977 }
978
979 var haveProgramInfoMapIDs = internal.NewFeatureTest("map IDs in program info", func() error {
980 if platform.IsWindows {
981 // We only support efW versions which have this feature, no need to probe.
982 return nil
983 }
984
985 prog, err := progLoad(asm.Instructions{
986 asm.LoadImm(asm.R0, 0, asm.DWord),
987 asm.Return(),
988 }, SocketFilter, "MIT")
989 if err != nil {
990 return err
991 }
992 defer prog.Close()
993
994 err = sys.ObjInfo(prog, &sys.ProgInfo{
995 // NB: Don't need to allocate MapIds since the program isn't using
996 // any maps.
997 NrMapIds: 1,
998 })
999 if errors.Is(err, unix.EINVAL) {
1000 // Most likely the syscall doesn't exist.
1001 return internal.ErrNotSupported
1002 }
1003 if errors.Is(err, unix.E2BIG) {
1004 // We've hit check_uarg_tail_zero on older kernels.
1005 return internal.ErrNotSupported
1006 }
1007
1008 return err
1009 }, "4.15", "windows:0.21.0")