Debian Codegraph @

prog.go

raw symbols SCIP
1 package ebpf
2
3 import (
4 "bytes"
5 "encoding/binary"
6 "errors"
7 "fmt"
8 "math"
9 "path/filepath"
10 "runtime"
11 "slices"
12 "strings"
13 "time"
14
15 "github.com/cilium/ebpf/asm"
16 "github.com/cilium/ebpf/btf"
17 "github.com/cilium/ebpf/internal"
18 "github.com/cilium/ebpf/internal/linux"
19 "github.com/cilium/ebpf/internal/platform"
20 "github.com/cilium/ebpf/internal/sys"
21 "github.com/cilium/ebpf/internal/sysenc"
22 "github.com/cilium/ebpf/internal/unix"
23 )
24
25 // ErrNotSupported is returned whenever the kernel doesn't support a feature.
26 var ErrNotSupported = internal.ErrNotSupported
27
28 // ErrProgIncompatible is returned when a loaded Program is incompatible with a
29 // given spec.
30 var ErrProgIncompatible = errors.New("program is incompatible")
31
32 // errBadRelocation is returned when the verifier rejects a program due to a
33 // bad CO-RE relocation.
34 //
35 // This error is detected based on heuristics and therefore may not be reliable.
36 var errBadRelocation = errors.New("bad CO-RE relocation")
37
38 // errUnknownKfunc is returned when the verifier rejects a program due to an
39 // unknown kfunc.
40 //
41 // This error is detected based on heuristics and therefore may not be reliable.
42 var errUnknownKfunc = errors.New("unknown kfunc")
43
44 // ProgramID represents the unique ID of an eBPF program.
45 type ProgramID = sys.ProgramID
46
47 const (
48 // Number of bytes to pad the output buffer for BPF_PROG_TEST_RUN.
49 // This is currently the maximum of spare space allocated for SKB
50 // and XDP programs, and equal to XDP_PACKET_HEADROOM + NET_IP_ALIGN.
51 outputPad = 256 + 2
52 )
53
54 // minVerifierLogSize is the default number of bytes allocated for the
55 // verifier log.
56 const minVerifierLogSize = 64 * 1024
57
58 // maxVerifierLogSize is the maximum size of verifier log buffer the kernel
59 // will accept before returning EINVAL. May be increased to MaxUint32 in the
60 // future, but avoid the unnecessary EINVAL for now.
61 const maxVerifierLogSize = math.MaxUint32 >> 2
62
63 // maxVerifierAttempts is the maximum number of times the verifier will retry
64 // loading a program with a growing log buffer before giving up. Since we double
65 // the log size on every attempt, this is the absolute maximum number of
66 // attempts before the buffer reaches [maxVerifierLogSize].
67 const maxVerifierAttempts = 30
68
69 // ProgramOptions control loading a program into the kernel.
70 type ProgramOptions struct {
71 // Bitmap controlling the detail emitted by the kernel's eBPF verifier log.
72 // LogLevel-type values can be ORed together to request specific kinds of
73 // verifier output. See the documentation on [ebpf.LogLevel] for details.
74 //
75 // opts.LogLevel = (ebpf.LogLevelBranch | ebpf.LogLevelStats)
76 //
77 // If left to its default value, the program will first be loaded without
78 // verifier output enabled. Upon error, the program load will be repeated
79 // with LogLevelBranch and the given (or default) LogSize value.
80 //
81 // Unless LogDisabled is set, setting this to a non-zero value will enable the verifier
82 // log, populating the [ebpf.Program.VerifierLog] field on successful loads
83 // and including detailed verifier errors if the program is rejected. This
84 // will always allocate an output buffer, but will result in only a single
85 // attempt at loading the program.
86 LogLevel LogLevel
87
88 // Starting size of the verifier log buffer. If the verifier log is larger
89 // than this size, the buffer will be grown to fit the entire log. Leave at
90 // its default value unless troubleshooting.
91 LogSizeStart uint32
92
93 // Disables the verifier log completely, regardless of other options.
94 LogDisabled bool
95
96 // Type information used for CO-RE relocations.
97 //
98 // This is useful in environments where the kernel BTF is not available
99 // (containers) or where it is in a non-standard location. Defaults to
100 // use the kernel BTF from a well-known location if nil.
101 KernelTypes *btf.Spec
102
103 // Additional targets to consider for CO-RE relocations. This can be used to
104 // pass BTF information for kernel modules when it's not present on
105 // KernelTypes.
106 ExtraRelocationTargets []*btf.Spec
107 }
108
109 // ProgramSpec defines a Program.
110 type ProgramSpec struct {
111 // Name is passed to the kernel as a debug aid.
112 //
113 // Unsupported characters will be stripped.
114 Name string
115
116 // Type determines at which hook in the kernel a program will run.
117 Type ProgramType
118
119 // Network interface index the user intends to attach this program to after
120 // loading. Only valid for some program types.
121 //
122 // Provides driver-specific context about the target interface to the
123 // verifier, required when using certain BPF helpers.
124 Ifindex uint32
125
126 // AttachType of the program, needed to differentiate allowed context
127 // accesses in some newer program types like CGroupSockAddr.
128 //
129 // Available on kernels 4.17 and later.
130 AttachType AttachType
131
132 // Name of a kernel data structure or function to attach to. Its
133 // interpretation depends on Type and AttachType.
134 AttachTo string
135
136 // The program to attach to. Must be provided manually.
137 AttachTarget *Program
138
139 // The name of the ELF section this program originated from.
140 SectionName string
141
142 Instructions asm.Instructions
143
144 // Flags is passed to the kernel and specifies additional program
145 // load attributes.
146 Flags uint32
147
148 // License of the program. Some helpers are only available if
149 // the license is deemed compatible with the GPL.
150 //
151 // See https://www.kernel.org/doc/html/latest/process/license-rules.html#id1
152 License string
153
154 // Version used by Kprobe programs.
155 //
156 // Deprecated on kernels 5.0 and later. Leave empty to let the library
157 // detect this value automatically.
158 KernelVersion uint32
159
160 // The byte order this program was compiled for, may be nil.
161 ByteOrder binary.ByteOrder
162 }
163
164 // Copy returns a copy of the spec.
165 func (ps *ProgramSpec) Copy() *ProgramSpec {
166 if ps == nil {
167 return nil
168 }
169
170 cpy := *ps
171 cpy.Instructions = make(asm.Instructions, len(ps.Instructions))
172 copy(cpy.Instructions, ps.Instructions)
173 return &cpy
174 }
175
176 // Tag calculates the kernel tag for a series of instructions.
177 //
178 // Use asm.Instructions.Tag if you need to calculate for non-native endianness.
179 //
180 // Deprecated: The value produced by this method no longer matches tags produced
181 // by the kernel since Linux 6.18. Use [ProgramSpec.Compatible] instead.
182 func (ps *ProgramSpec) Tag() (string, error) {
183 return ps.Instructions.Tag(internal.NativeEndian)
184 }
185
186 // Compatible returns nil if a loaded Program's kernel tag matches the one of
187 // the ProgramSpec.
188 //
189 // Returns [ErrProgIncompatible] if the tags do not match.
190 func (ps *ProgramSpec) Compatible(info *ProgramInfo) error {
191 if platform.IsWindows {
192 return fmt.Errorf("%w: Windows does not support tag readback from kernel", internal.ErrNotSupportedOnOS)
193 }
194
195 ok, err := ps.Instructions.HasTag(info.Tag, internal.NativeEndian)
196 if err != nil {
197 return err
198 }
199
200 if !ok {
201 return fmt.Errorf("%w: ProgramSpec and Program tags do not match", ErrProgIncompatible)
202 }
203
204 return nil
205 }
206
207 // targetsKernelModule returns true if the program supports being attached to a
208 // symbol provided by a kernel module.
209 func (ps *ProgramSpec) targetsKernelModule() bool {
210 if ps.AttachTo == "" {
211 return false
212 }
213
214 switch ps.Type {
215 case Tracing:
216 switch ps.AttachType {
217 case AttachTraceFEntry, AttachTraceFExit:
218 return true
219 }
220 case Kprobe:
221 return true
222 }
223
224 return false
225 }
226
227 // VerifierError is returned by [NewProgram] and [NewProgramWithOptions] if a
228 // program is rejected by the verifier.
229 //
230 // Use [errors.As] to access the error.
231 type VerifierError = internal.VerifierError
232
233 // Program represents BPF program loaded into the kernel.
234 //
235 // It is not safe to close a Program which is used by other goroutines.
236 type Program struct {
237 // Contains the output of the kernel verifier if enabled,
238 // otherwise it is empty.
239 VerifierLog string
240
241 fd *sys.FD
242 name string
243 pinnedPath string
244 typ ProgramType
245
246 btf *btf.Handle
247 }
248
249 // NewProgram creates a new Program.
250 //
251 // See [NewProgramWithOptions] for details.
252 //
253 // Returns a [VerifierError] containing the full verifier log if the program is
254 // rejected by the kernel.
255 func NewProgram(spec *ProgramSpec) (*Program, error) {
256 return NewProgramWithOptions(spec, ProgramOptions{})
257 }
258
259 // NewProgramWithOptions creates a new Program.
260 //
261 // Loading a program for the first time will perform
262 // feature detection by loading small, temporary programs.
263 //
264 // Returns a [VerifierError] containing the full verifier log if the program is
265 // rejected by the kernel.
266 func NewProgramWithOptions(spec *ProgramSpec, opts ProgramOptions) (*Program, error) {
267 if spec == nil {
268 return nil, errors.New("can't load a program from a nil spec")
269 }
270
271 prog, err := newProgramWithOptions(spec, opts, btf.NewCache())
272 if errors.Is(err, asm.ErrUnsatisfiedMapReference) {
273 return nil, fmt.Errorf("cannot load program without loading its whole collection: %w", err)
274 }
275 return prog, err
276 }
277
278 var (
279 coreBadLoad = fmt.Appendf(nil, "(18) r10 = 0x%x\n", btf.COREBadRelocationSentinel)
280 // This log message was introduced by ebb676daa1a3 ("bpf: Print function name in
281 // addition to function id") which first appeared in v4.10 and has remained
282 // unchanged since.
283 coreBadCall = fmt.Appendf(nil, "invalid func unknown#%d\n", btf.COREBadRelocationSentinel)
284 kfuncBadCall = fmt.Appendf(nil, "invalid func unknown#%d\n", kfuncCallPoisonBase)
285 )
286
287 func newProgramWithOptions(spec *ProgramSpec, opts ProgramOptions, c *btf.Cache) (result *Program, _ error) {
288 if len(spec.Instructions) == 0 {
289 return nil, errors.New("instructions cannot be empty")
290 }
291
292 if spec.Type == UnspecifiedProgram {
293 return nil, errors.New("can't load program of unspecified type")
294 }
295
296 if spec.ByteOrder != nil && spec.ByteOrder != internal.NativeEndian {
297 return nil, fmt.Errorf("can't load %s program on %s", spec.ByteOrder, internal.NativeEndian)
298 }
299
300 // Kernels before 5.0 (6c4fc209fcf9 "bpf: remove useless version check for prog load")
301 // require the version field to be set to the value of the KERNEL_VERSION
302 // macro for kprobe-type programs.
303 // Overwrite Kprobe program version if set to zero or the magic version constant.
304 kv := spec.KernelVersion
305 if spec.Type == Kprobe && (kv == 0 || kv == internal.MagicKernelVersion) {
306 v, err := linux.KernelVersion()
307 if err != nil {
308 return nil, fmt.Errorf("detecting kernel version: %w", err)
309 }
310 kv = v.Kernel()
311 }
312
313 p, progType := platform.DecodeConstant(spec.Type)
314 if p != platform.Native {
315 return nil, fmt.Errorf("program type %s (%s): %w", spec.Type, p, internal.ErrNotSupportedOnOS)
316 }
317
318 attr := &sys.ProgLoadAttr{
319 ProgName: maybeFillObjName(spec.Name),
320 ProgType: sys.ProgType(progType),
321 ProgFlags: spec.Flags,
322 ProgIfindex: spec.Ifindex,
323 ExpectedAttachType: sys.AttachType(spec.AttachType),
324 License: sys.NewStringPointer(spec.License),
325 KernVersion: kv,
326 }
327
328 insns := make(asm.Instructions, len(spec.Instructions))
329 copy(insns, spec.Instructions)
330
331 var b btf.Builder
332 if err := applyRelocations(insns, spec.ByteOrder, &b, c, opts.KernelTypes, opts.ExtraRelocationTargets); err != nil {
333 return nil, fmt.Errorf("apply CO-RE relocations: %w", err)
334 }
335
336 errExtInfos := haveProgramExtInfos()
337 if !b.Empty() && errors.Is(errExtInfos, ErrNotSupported) {
338 // There is at least one CO-RE relocation which relies on a stable local
339 // type ID.
340 // Return ErrNotSupported instead of E2BIG if there is no BTF support.
341 return nil, errExtInfos
342 }
343
344 if errExtInfos == nil {
345 // Only add func and line info if the kernel supports it. This allows
346 // BPF compiled with modern toolchains to work on old kernels.
347 fib, lib, err := btf.MarshalExtInfos(insns, &b)
348 if err != nil {
349 return nil, fmt.Errorf("marshal ext_infos: %w", err)
350 }
351
352 attr.FuncInfoRecSize = btf.FuncInfoSize
353 attr.FuncInfoCnt = uint32(len(fib)) / btf.FuncInfoSize
354 attr.FuncInfo = sys.SlicePointer(fib)
355
356 attr.LineInfoRecSize = btf.LineInfoSize
357 attr.LineInfoCnt = uint32(len(lib)) / btf.LineInfoSize
358 attr.LineInfo = sys.SlicePointer(lib)
359 }
360
361 var handle *btf.Handle
362 if !b.Empty() {
363 var err error
364 handle, err = btf.NewHandle(&b)
365 if err != nil {
366 return nil, fmt.Errorf("load BTF: %w", err)
367 }
368 defer func() {
369 if result == nil || result.btf != handle {
370 handle.Close()
371 }
372 }()
373
374 attr.ProgBtfFd = uint32(handle.FD())
375 }
376
377 kconfig, err := resolveKconfigReferences(insns)
378 if err != nil {
379 return nil, fmt.Errorf("resolve .kconfig: %w", err)
380 }
381 defer kconfig.Close()
382
383 if err := resolveKsymReferences(insns); err != nil {
384 return nil, fmt.Errorf("resolve .ksyms: %w", err)
385 }
386
387 if err := fixupAndValidate(insns); err != nil {
388 return nil, err
389 }
390
391 handles, err := fixupKfuncs(insns, c)
392 if err != nil {
393 return nil, fmt.Errorf("fixing up kfuncs: %w", err)
394 }
395 defer handles.Close()
396
397 if len(handles) > 0 {
398 fdArray := handles.fdArray()
399 attr.FdArray = sys.SlicePointer(fdArray)
400 }
401
402 buf := bytes.NewBuffer(make([]byte, 0, insns.Size()))
403 err = insns.Marshal(buf, internal.NativeEndian)
404 if err != nil {
405 return nil, err
406 }
407
408 bytecode := buf.Bytes()
409 attr.Insns = sys.SlicePointer(bytecode)
410 attr.InsnCnt = uint32(len(bytecode) / asm.InstructionSize)
411
412 if spec.AttachTarget != nil {
413 targetID, err := findTargetInProgram(spec.AttachTarget, spec.AttachTo, spec.Type, spec.AttachType)
414 if err != nil {
415 return nil, fmt.Errorf("attach %s/%s: %w", spec.Type, spec.AttachType, err)
416 }
417
418 attr.AttachBtfId = targetID
419 attr.AttachBtfObjFd = uint32(spec.AttachTarget.FD())
420 defer runtime.KeepAlive(spec.AttachTarget)
421 } else if spec.AttachTo != "" {
422 var targetMember string
423 attachTo := spec.AttachTo
424
425 if spec.Type == StructOps {
426 attachTo, targetMember, _ = strings.Cut(attachTo, ":")
427 if targetMember == "" {
428 return nil, fmt.Errorf("struct_ops: AttachTo must be '<ops>:<member>' (got %s)", spec.AttachTo)
429 }
430 }
431
432 module, targetID, err := findProgramTargetInKernel(attachTo, spec.Type, spec.AttachType, c)
433 if err != nil && !errors.Is(err, errUnrecognizedAttachType) {
434 // We ignore errUnrecognizedAttachType since AttachTo may be non-empty
435 // for programs that don't attach anywhere.
436 return nil, fmt.Errorf("attach %s/%s: %w", spec.Type, spec.AttachType, err)
437 }
438
439 if spec.Type == StructOps {
440 var s *btf.Spec
441
442 target := btf.Type((*btf.Struct)(nil))
443 s, module, err = findTargetInKernel(attachTo, &target, c)
444 if err != nil {
445 return nil, fmt.Errorf("lookup struct_ops kern type %q: %w", attachTo, err)
446 }
447 kType := target.(*btf.Struct)
448
449 targetID, err = s.TypeID(kType)
450 if err != nil {
451 return nil, fmt.Errorf("type id for %s: %w", kType.TypeName(), err)
452 }
453
454 idx := slices.IndexFunc(kType.Members, func(m btf.Member) bool {
455 return m.Name == targetMember
456 })
457 if idx < 0 {
458 return nil, fmt.Errorf("member %q not found in %s", targetMember, kType.Name)
459 }
460
461 // ExpectedAttachType: index of the target member in the struct
462 attr.ExpectedAttachType = sys.AttachType(idx)
463 }
464
465 attr.AttachBtfId = targetID
466 if module != nil && attr.AttachBtfObjFd == 0 {
467 attr.AttachBtfObjFd = uint32(module.FD())
468 defer module.Close()
469 }
470 }
471
472 if platform.IsWindows && opts.LogLevel != 0 {
473 return nil, fmt.Errorf("log level: %w", internal.ErrNotSupportedOnOS)
474 }
475
476 var logBuf []byte
477 var fd *sys.FD
478 if opts.LogDisabled {
479 // Loading with logging disabled should never retry.
480 fd, err = sys.ProgLoad(attr)
481 if err == nil {
482 return &Program{"", fd, spec.Name, "", spec.Type, handle}, nil
483 }
484 } else {
485 // Only specify log size if log level is also specified. Setting size
486 // without level results in EINVAL. Level will be bumped to LogLevelBranch
487 // if the first load fails.
488 if opts.LogLevel != 0 {
489 attr.LogLevel = opts.LogLevel
490 attr.LogSize = internal.Between(opts.LogSizeStart, minVerifierLogSize, maxVerifierLogSize)
491 }
492
493 attempts := 1
494 for {
495 if attr.LogLevel != 0 {
496 logBuf = make([]byte, attr.LogSize)
497 attr.LogBuf = sys.SlicePointer(logBuf)
498 }
499
500 fd, err = sys.ProgLoad(attr)
501 if err == nil {
502 return &Program{unix.ByteSliceToString(logBuf), fd, spec.Name, "", spec.Type, handle}, nil
503 }
504
505 if !retryLogAttrs(attr, opts.LogSizeStart, err) {
506 break
507 }
508
509 if attempts >= maxVerifierAttempts {
510 return nil, fmt.Errorf("load program: %w (bug: hit %d verifier attempts)", err, maxVerifierAttempts)
511 }
512 attempts++
513 }
514 }
515
516 if errors.Is(err, sys.ErrTokenCapabilities) {
517 return nil, fmt.Errorf("load program: %w", err)
518 }
519
520 end := bytes.IndexByte(logBuf, 0)
521 if end < 0 {
522 end = len(logBuf)
523 }
524
525 tail := logBuf[max(end-256, 0):end]
526 switch {
527 case errors.Is(err, unix.EPERM):
528 if len(logBuf) > 0 && logBuf[0] == 0 {
529 // EPERM due to RLIMIT_MEMLOCK happens before the verifier, so we can
530 // check that the log is empty to reduce false positives.
531 return nil, fmt.Errorf("load program: %w (MEMLOCK may be too low, consider rlimit.RemoveMemlock)", err)
532 }
533
534 case errors.Is(err, unix.EFAULT):
535 // EFAULT is returned when the kernel hits a verifier bug, and always
536 // overrides ENOSPC, defeating the buffer growth strategy. Warn the user
537 // that they may need to increase the buffer size manually.
538 return nil, fmt.Errorf("load program: %w (hit verifier bug, increase LogSizeStart to fit the log and check dmesg)", err)
539
540 case errors.Is(err, unix.EINVAL):
541 if bytes.Contains(tail, coreBadCall) {
542 err = errBadRelocation
543 break
544 } else if bytes.Contains(tail, kfuncBadCall) {
545 err = errUnknownKfunc
546 break
547 }
548
549 case errors.Is(err, unix.EACCES):
550 if bytes.Contains(tail, coreBadLoad) {
551 err = errBadRelocation
552 break
553 }
554 }
555
556 // hasFunctionReferences may be expensive, so check it last.
557 if (errors.Is(err, unix.EINVAL) || errors.Is(err, unix.EPERM)) &&
558 hasFunctionReferences(spec.Instructions) {
559 if err := haveBPFToBPFCalls(); err != nil {
560 return nil, fmt.Errorf("load program: %w", err)
561 }
562 }
563
564 return nil, internal.ErrorWithLog("load program", err, logBuf)
565 }
566
567 func retryLogAttrs(attr *sys.ProgLoadAttr, startSize uint32, err error) bool {
568 if attr.LogSize == maxVerifierLogSize {
569 // Maximum buffer size reached, don't grow or retry.
570 return false
571 }
572
573 // ENOSPC means the log was enabled on the previous iteration, so we only
574 // need to grow the buffer.
575 if errors.Is(err, unix.ENOSPC) {
576 if attr.LogTrueSize != 0 {
577 // Kernel supports LogTrueSize and previous iteration undershot the buffer
578 // size. Try again with the given true size.
579 attr.LogSize = attr.LogTrueSize
580 return true
581 }
582
583 // Ensure the size doesn't overflow.
584 const factor = 2
585 if attr.LogSize >= maxVerifierLogSize/factor {
586 attr.LogSize = maxVerifierLogSize
587 return true
588 }
589
590 // Make an educated guess how large the buffer should be by multiplying. Due
591 // to int division, this rounds down odd sizes.
592 attr.LogSize = internal.Between(attr.LogSize, minVerifierLogSize, maxVerifierLogSize/factor)
593 attr.LogSize *= factor
594
595 return true
596 }
597
598 if attr.LogLevel == 0 {
599 // Loading the program failed, it wasn't a buffer-related error, and the log
600 // was disabled the previous iteration. Enable basic logging and retry.
601 attr.LogLevel = LogLevelBranch
602 attr.LogSize = internal.Between(startSize, minVerifierLogSize, maxVerifierLogSize)
603 return true
604 }
605
606 // Loading the program failed for a reason other than buffer size and the log
607 // was already enabled the previous iteration. Don't retry.
608 return false
609 }
610
611 // NewProgramFromFD creates a [Program] around a raw fd.
612 //
613 // You should not use fd after calling this function.
614 //
615 // Requires at least Linux 4.13. Returns an error on Windows.
616 func NewProgramFromFD(fd int) (*Program, error) {
617 f, err := sys.NewFD(fd)
618 if err != nil {
619 return nil, err
620 }
621
622 return newProgramFromFD(f)
623 }
624
625 // NewProgramFromID returns the [Program] for a given program id. Returns
626 // [ErrNotExist] if there is no eBPF program with the given id.
627 //
628 // Requires at least Linux 4.13.
629 func NewProgramFromID(id ProgramID) (*Program, error) {
630 fd, err := sys.ProgGetFdById(&sys.ProgGetFdByIdAttr{
631 Id: uint32(id),
632 })
633 if err != nil {
634 return nil, fmt.Errorf("get program by id: %w", err)
635 }
636
637 return newProgramFromFD(fd)
638 }
639
640 func newProgramFromFD(fd *sys.FD) (*Program, error) {
641 info, err := minimalProgramInfoFromFd(fd)
642 if err != nil {
643 fd.Close()
644 return nil, fmt.Errorf("discover program type: %w", err)
645 }
646
647 return &Program{"", fd, info.Name, "", info.Type, nil}, nil
648 }
649
650 func (p *Program) String() string {
651 if p.name != "" {
652 return fmt.Sprintf("%s(%s)#%v", p.typ, p.name, p.fd)
653 }
654 return fmt.Sprintf("%s(%v)", p.typ, p.fd)
655 }
656
657 // Type returns the underlying type of the program.
658 func (p *Program) Type() ProgramType {
659 return p.typ
660 }
661
662 // Info returns metadata about the program.
663 //
664 // Requires at least 4.10.
665 func (p *Program) Info() (*ProgramInfo, error) {
666 return newProgramInfoFromFd(p.fd)
667 }
668
669 // Stats returns runtime statistics about the Program. Requires BPF statistics
670 // collection to be enabled, see [EnableStats].
671 //
672 // Requires at least Linux 5.8.
673 func (p *Program) Stats() (*ProgramStats, error) {
674 return newProgramStatsFromFd(p.fd)
675 }
676
677 // Handle returns a reference to the program's type information in the kernel.
678 //
679 // Returns ErrNotSupported if the kernel has no BTF support, or if there is no
680 // BTF associated with the program.
681 func (p *Program) Handle() (*btf.Handle, error) {
682 if p.btf != nil {
683 return p.btf.Clone()
684 }
685
686 info, err := p.Info()
687 if err != nil {
688 return nil, err
689 }
690
691 id, ok := info.BTFID()
692 if !ok {
693 return nil, fmt.Errorf("program %s: retrieve BTF ID: %w", p, ErrNotSupported)
694 }
695
696 return btf.NewHandleFromID(id)
697 }
698
699 // SetHandle caches program's type information so that subsequent
700 // Handle() call doesn't need to query it from the kernel (requires
701 // CAP_SYS_ADMIN).
702 //
703 // The caller remains responsible for closing the btf.Handle; SetHandle
704 // makes a private copy.
705 //
706 // Type info is auto-cached for Programs loaded by the library itself.
707 // Use SetHandle() with program references obtained via NewProgramFromFD
708 // and LoadPinnedProgram.
709 func (p *Program) SetHandle(h *btf.Handle) error {
710 if h == nil {
711 return fmt.Errorf("nil BTF handle")
712 }
713
714 info, err := p.Info()
715 if err != nil {
716 return err
717 }
718
719 handleInfo, err := h.Info()
720 if err != nil {
721 return err
722 }
723
724 if id, ok := info.BTFID(); !ok || id != handleInfo.ID {
725 return fmt.Errorf("program/BTF mismatch")
726 }
727
728 if p.btf != nil {
729 return nil
730 }
731
732 dup, err := h.Clone()
733 if err != nil {
734 return err
735 }
736
737 p.btf = dup
738 return nil
739 }
740
741 // FD gets the file descriptor of the Program.
742 //
743 // It is invalid to call this function after Close has been called.
744 func (p *Program) FD() int {
745 return p.fd.Int()
746 }
747
748 // Clone creates a duplicate of the Program.
749 //
750 // Closing the duplicate does not affect the original, and vice versa.
751 //
752 // Cloning a nil Program returns nil.
753 func (p *Program) Clone() (*Program, error) {
754 if p == nil {
755 return nil, nil
756 }
757
758 btfClone, err := p.btf.Clone()
759 if err != nil {
760 return nil, fmt.Errorf("can't clone program: %w", err)
761 }
762
763 dup, err := p.fd.Dup()
764 if err != nil {
765 btfClone.Close()
766 return nil, fmt.Errorf("can't clone program: %w", err)
767 }
768
769 return &Program{p.VerifierLog, dup, p.name, "", p.typ, btfClone}, nil
770 }
771
772 // Pin persists the Program on the BPF virtual file system past the lifetime of
773 // the process that created it
774 //
775 // Calling Pin on a previously pinned program will overwrite the path, except when
776 // the new path already exists. Re-pinning across filesystems is not supported.
777 //
778 // This requires bpffs to be mounted above fileName.
779 // See https://docs.cilium.io/en/stable/network/kubernetes/configuration/#mounting-bpffs-with-systemd
780 func (p *Program) Pin(fileName string) error {
781 if err := sys.Pin(p.pinnedPath, fileName, p.fd); err != nil {
782 return err
783 }
784 p.pinnedPath = fileName
785 return nil
786 }
787
788 // Unpin removes the persisted state for the Program from the BPF virtual filesystem.
789 //
790 // Failed calls to Unpin will not alter the state returned by IsPinned.
791 //
792 // Unpinning an unpinned Program returns nil.
793 func (p *Program) Unpin() error {
794 if err := sys.Unpin(p.pinnedPath); err != nil {
795 return err
796 }
797 p.pinnedPath = ""
798 return nil
799 }
800
801 // IsPinned returns true if the Program has a non-empty pinned path.
802 func (p *Program) IsPinned() bool {
803 return p.pinnedPath != ""
804 }
805
806 // Close the Program's underlying file descriptor, which could unload
807 // the program from the kernel if it is not pinned or attached to a
808 // kernel hook.
809 func (p *Program) Close() error {
810 if p == nil {
811 return nil
812 }
813
814 if err := p.btf.Close(); err != nil {
815 return err
816 }
817
818 return p.fd.Close()
819 }
820
821 // Various options for Run'ing a Program
822 type RunOptions struct {
823 // Program's data input. Required field.
824 //
825 // The kernel expects at least 14 bytes input for an ethernet header for
826 // XDP and SKB programs.
827 Data []byte
828 // Program's data after Program has run. Caller must allocate. Optional field.
829 DataOut []byte
830 // Program's context input. Optional field.
831 Context any
832 // Program's context after Program has run. Must be a pointer or slice. Optional field.
833 ContextOut any
834 // Minimum number of times to run Program. Optional field. Defaults to 1.
835 //
836 // The program may be executed more often than this due to interruptions, e.g.
837 // when runtime.AllThreadsSyscall is invoked.
838 Repeat uint32
839 // Optional flags.
840 Flags uint32
841 // CPU to run Program on. Optional field.
842 // Note not all program types support this field.
843 CPU uint32
844 // BatchSize (default 64) affects the kernel's packet buffer allocation behaviour when running
845 // programs with BPF_F_TEST_XDP_LIVE_FRAMES and a non-zero [RunOptions.Repeat] value.
846 // For more details, see the kernel documentation on BPF_PROG_RUN:
847 // https://docs.kernel.org/bpf/bpf_prog_run.html#running-xdp-programs-in-live-frame-mode
848 BatchSize uint32
849 // Called whenever the syscall is interrupted, and should be set to testing.B.ResetTimer
850 // or similar. Typically used during benchmarking. Optional field.
851 //
852 // Deprecated: use [testing.B.ReportMetric] with unit "ns/op" instead.
853 Reset func()
854 }
855
856 // Test runs the Program in the kernel with the given input and returns the
857 // value returned by the eBPF program.
858 //
859 // Note: the kernel expects at least 14 bytes input for an ethernet header for
860 // XDP and SKB programs.
861 //
862 // This function requires at least Linux 4.12.
863 func (p *Program) Test(in []byte) (uint32, []byte, error) {
864 // Older kernels ignore the dataSizeOut argument when copying to user space.
865 // Combined with things like bpf_xdp_adjust_head() we don't really know what the final
866 // size will be. Hence we allocate an output buffer which we hope will always be large
867 // enough, and panic if the kernel wrote past the end of the allocation.
868 // See https://patchwork.ozlabs.org/cover/1006822/
869 var out []byte
870 if len(in) > 0 {
871 out = make([]byte, len(in)+outputPad)
872 }
873
874 opts := RunOptions{
875 Data: in,
876 DataOut: out,
877 Repeat: 1,
878 }
879
880 ret, _, err := p.run(&opts)
881 if err != nil {
882 return ret, nil, fmt.Errorf("test program: %w", err)
883 }
884 return ret, opts.DataOut, nil
885 }
886
887 // Run runs the Program in kernel with given RunOptions.
888 //
889 // Note: the same restrictions from Test apply.
890 func (p *Program) Run(opts *RunOptions) (uint32, error) {
891 if opts == nil {
892 opts = &RunOptions{}
893 }
894
895 ret, _, err := p.run(opts)
896 if err != nil {
897 return ret, fmt.Errorf("run program: %w", err)
898 }
899 return ret, nil
900 }
901
902 // Benchmark runs the Program with the given input for a number of times
903 // and returns the time taken per iteration.
904 //
905 // Returns the result of the last execution of the program and the time per
906 // run or an error. reset is called whenever the benchmark syscall is
907 // interrupted, and should be set to testing.B.ResetTimer or similar.
908 //
909 // This function requires at least Linux 4.12.
910 func (p *Program) Benchmark(in []byte, repeat int, reset func()) (uint32, time.Duration, error) {
911 if uint(repeat) > math.MaxUint32 {
912 return 0, 0, fmt.Errorf("repeat is too high")
913 }
914
915 opts := RunOptions{
916 Data: in,
917 Repeat: uint32(repeat),
918 Reset: reset,
919 }
920
921 ret, total, err := p.run(&opts)
922 if err != nil {
923 return ret, total, fmt.Errorf("benchmark program: %w", err)
924 }
925 return ret, total, nil
926 }
927
928 var haveProgRun = internal.NewFeatureTest("BPF_PROG_RUN", func() error {
929 if platform.IsWindows {
930 return nil
931 }
932
933 prog, err := NewProgram(&ProgramSpec{
934 // SocketFilter does not require privileges on newer kernels.
935 Type: SocketFilter,
936 Instructions: asm.Instructions{
937 asm.LoadImm(asm.R0, 0, asm.DWord),
938 asm.Return(),
939 },
940 License: "MIT",
941 })
942 if err != nil {
943 // This may be because we lack sufficient permissions, etc.
944 return err
945 }
946 defer prog.Close()
947
948 in := internal.EmptyBPFContext
949 attr := sys.ProgRunAttr{
950 ProgFd: uint32(prog.FD()),
951 DataSizeIn: uint32(len(in)),
952 DataIn: sys.SlicePointer(in),
953 }
954
955 err = sys.ProgRun(&attr)
956 switch {
957 case errors.Is(err, unix.EINVAL):
958 // Check for EINVAL specifically, rather than err != nil since we
959 // otherwise misdetect due to insufficient permissions.
960 return internal.ErrNotSupported
961
962 case errors.Is(err, unix.EINTR):
963 // We know that PROG_TEST_RUN is supported if we get EINTR.
964 return nil
965
966 case errors.Is(err, sys.ENOTSUPP):
967 // The first PROG_TEST_RUN patches shipped in 4.12 didn't include
968 // a test runner for SocketFilter. ENOTSUPP means PROG_TEST_RUN is
969 // supported, but not for the program type used in the probe.
970 return nil
971 }
972
973 return err
974 }, "4.12", "windows:0.20")
975
976 func (p *Program) run(opts *RunOptions) (uint32, time.Duration, error) {
977 if uint(len(opts.Data)) > math.MaxUint32 {
978 return 0, 0, fmt.Errorf("input is too long")
979 }
980
981 if err := haveProgRun(); err != nil {
982 return 0, 0, err
983 }
984
985 var ctxIn []byte
986 if opts.Context != nil {
987 var err error
988 ctxIn, err = binary.Append(nil, internal.NativeEndian, opts.Context)
989 if err != nil {
990 return 0, 0, fmt.Errorf("cannot serialize context: %v", err)
991 }
992 }
993
994 var ctxOut []byte
995 if opts.ContextOut != nil {
996 ctxOut = make([]byte, binary.Size(opts.ContextOut))
997 } else if platform.IsWindows && len(ctxIn) > 0 {
998 // Windows rejects a non-zero ctxIn with a nil ctxOut.
999 ctxOut = make([]byte, len(ctxIn))
1000 }
1001
1002 attr := sys.ProgRunAttr{
1003 ProgFd: p.fd.Uint(),
1004 DataSizeIn: uint32(len(opts.Data)),
1005 DataSizeOut: uint32(len(opts.DataOut)),
1006 DataIn: sys.SlicePointer(opts.Data),
1007 DataOut: sys.SlicePointer(opts.DataOut),
1008 Repeat: uint32(opts.Repeat),
1009 CtxSizeIn: uint32(len(ctxIn)),
1010 CtxSizeOut: uint32(len(ctxOut)),
1011 CtxIn: sys.SlicePointer(ctxIn),
1012 CtxOut: sys.SlicePointer(ctxOut),
1013 Flags: opts.Flags,
1014 Cpu: opts.CPU,
1015 BatchSize: opts.BatchSize,
1016 }
1017
1018 if p.Type() == Syscall && ctxIn != nil && ctxOut != nil {
1019 // Linux syscall program errors on non-nil ctxOut, uses ctxIn
1020 // for both input and output. Shield the user from this wart.
1021 if len(ctxIn) != len(ctxOut) {
1022 return 0, 0, errors.New("length mismatch: Context and ContextOut")
1023 }
1024 attr.CtxOut, attr.CtxSizeOut = sys.TypedPointer[uint8]{}, 0
1025 ctxOut = ctxIn
1026 }
1027
1028 retry:
1029 for {
1030 err := sys.ProgRun(&attr)
1031 if err == nil {
1032 break retry
1033 }
1034
1035 if errors.Is(err, unix.EINTR) {
1036 if attr.Repeat <= 1 {
1037 // Older kernels check whether enough repetitions have been
1038 // executed only after checking for pending signals.
1039 //
1040 // run signal? done? run ...
1041 //
1042 // As a result we can get EINTR for repeat==1 even though
1043 // the program was run exactly once. Treat this as a
1044 // successful run instead.
1045 //
1046 // Since commit 607b9cc92bd7 ("bpf: Consolidate shared test timing code")
1047 // the conditions are reversed:
1048 // run done? signal? ...
1049 break retry
1050 }
1051
1052 if opts.Reset != nil {
1053 opts.Reset()
1054 }
1055 continue retry
1056 }
1057
1058 if errors.Is(err, sys.ENOTSUPP) {
1059 return 0, 0, fmt.Errorf("kernel doesn't support running %s: %w", p.Type(), ErrNotSupported)
1060 }
1061
1062 return 0, 0, err
1063 }
1064
1065 if opts.DataOut != nil {
1066 if int(attr.DataSizeOut) > cap(opts.DataOut) {
1067 // Houston, we have a problem. The program created more data than we allocated,
1068 // and the kernel wrote past the end of our buffer.
1069 panic("kernel wrote past end of output buffer")
1070 }
1071 opts.DataOut = opts.DataOut[:int(attr.DataSizeOut)]
1072 }
1073
1074 if opts.ContextOut != nil {
1075 b := bytes.NewReader(ctxOut)
1076 if err := binary.Read(b, internal.NativeEndian, opts.ContextOut); err != nil {
1077 return 0, 0, fmt.Errorf("failed to decode ContextOut: %v", err)
1078 }
1079 }
1080
1081 total := time.Duration(attr.Duration) * time.Nanosecond
1082 return attr.Retval, total, nil
1083 }
1084
1085 func unmarshalProgram(buf sysenc.Buffer) (*Program, error) {
1086 var id uint32
1087 if err := buf.Unmarshal(&id); err != nil {
1088 return nil, err
1089 }
1090
1091 // Looking up an entry in a nested map or prog array returns an id,
1092 // not an fd.
1093 return NewProgramFromID(ProgramID(id))
1094 }
1095
1096 func marshalProgram(p *Program, length int) ([]byte, error) {
1097 if p == nil {
1098 return nil, errors.New("can't marshal a nil Program")
1099 }
1100
1101 if length != 4 {
1102 return nil, fmt.Errorf("can't marshal program to %d bytes", length)
1103 }
1104
1105 buf := make([]byte, 4)
1106 internal.NativeEndian.PutUint32(buf, p.fd.Uint())
1107 return buf, nil
1108 }
1109
1110 // LoadPinnedProgram loads a Program from a pin (file) on the BPF virtual
1111 // filesystem.
1112 //
1113 // Requires at least Linux 4.11.
1114 func LoadPinnedProgram(fileName string, opts *LoadPinOptions) (*Program, error) {
1115 fd, typ, err := sys.ObjGetTyped(&sys.ObjGetAttr{
1116 Pathname: sys.NewStringPointer(fileName),
1117 FileFlags: opts.Marshal(),
1118 })
1119 if err != nil {
1120 return nil, err
1121 }
1122
1123 if typ != sys.BPF_TYPE_PROG {
1124 _ = fd.Close()
1125 return nil, fmt.Errorf("%s is not a Program", fileName)
1126 }
1127
1128 p, err := newProgramFromFD(fd)
1129 if err == nil {
1130 p.pinnedPath = fileName
1131
1132 if haveObjName() != nil {
1133 p.name = filepath.Base(fileName)
1134 }
1135 }
1136
1137 return p, err
1138 }
1139
1140 // ProgramGetNextID returns the ID of the next eBPF program.
1141 //
1142 // Returns ErrNotExist, if there is no next eBPF program.
1143 func ProgramGetNextID(startID ProgramID) (ProgramID, error) {
1144 attr := &sys.ProgGetNextIdAttr{Id: uint32(startID)}
1145 return ProgramID(attr.NextId), sys.ProgGetNextId(attr)
1146 }
1147
1148 // BindMap binds map to the program and is only released once program is released.
1149 //
1150 // This may be used in cases where metadata should be associated with the program
1151 // which otherwise does not contain any references to the map.
1152 func (p *Program) BindMap(m *Map) error {
1153 attr := &sys.ProgBindMapAttr{
1154 ProgFd: uint32(p.FD()),
1155 MapFd: uint32(m.FD()),
1156 }
1157
1158 return sys.ProgBindMap(attr)
1159 }
1160
1161 var errUnrecognizedAttachType = errors.New("unrecognized attach type")
1162
1163 // find an attach target type in the kernel.
1164 //
1165 // name, progType and attachType determine which type we need to attach to.
1166 //
1167 // The attach target may be in a loaded kernel module.
1168 // In that case the returned handle will be non-nil.
1169 // The caller is responsible for closing the handle.
1170 //
1171 // Returns errUnrecognizedAttachType if the combination of progType and attachType
1172 // is not recognised.
1173 func findProgramTargetInKernel(name string, progType ProgramType, attachType AttachType, cache *btf.Cache) (*btf.Handle, btf.TypeID, error) {
1174 type match struct {
1175 p ProgramType
1176 a AttachType
1177 }
1178
1179 var (
1180 typeName, featureName string
1181 target btf.Type
1182 )
1183
1184 switch (match{progType, attachType}) {
1185 case match{StructOps, AttachStructOps}:
1186 typeName = name
1187 featureName = "struct_ops " + name
1188 target = (*btf.Struct)(nil)
1189 case match{LSM, AttachLSMMac}:
1190 typeName = "bpf_lsm_" + name
1191 featureName = name + " LSM hook"
1192 target = (*btf.Func)(nil)
1193 case match{Tracing, AttachTraceIter}:
1194 typeName = "bpf_iter_" + name
1195 featureName = name + " iterator"
1196 target = (*btf.Func)(nil)
1197 case match{Tracing, AttachTraceFEntry}:
1198 typeName = name
1199 featureName = fmt.Sprintf("fentry %s", name)
1200 target = (*btf.Func)(nil)
1201 case match{Tracing, AttachTraceFExit}:
1202 typeName = name
1203 featureName = fmt.Sprintf("fexit %s", name)
1204 target = (*btf.Func)(nil)
1205 case match{Tracing, AttachModifyReturn}:
1206 typeName = name
1207 featureName = fmt.Sprintf("fmod_ret %s", name)
1208 target = (*btf.Func)(nil)
1209 case match{Tracing, AttachTraceRawTp}:
1210 typeName = fmt.Sprintf("btf_trace_%s", name)
1211 featureName = fmt.Sprintf("raw_tp %s", name)
1212 target = (*btf.Typedef)(nil)
1213 default:
1214 return nil, 0, errUnrecognizedAttachType
1215 }
1216
1217 spec, module, err := findTargetInKernel(typeName, &target, cache)
1218 if errors.Is(err, btf.ErrNotFound) {
1219 return nil, 0, &internal.UnsupportedFeatureError{Name: featureName}
1220 }
1221 // See cilium/ebpf#894. Until we can disambiguate between equally-named kernel
1222 // symbols, we should explicitly refuse program loads. They will not reliably
1223 // do what the caller intended.
1224 if errors.Is(err, btf.ErrMultipleMatches) {
1225 return nil, 0, fmt.Errorf("attaching to ambiguous kernel symbol is not supported: %w", err)
1226 }
1227 if err != nil {
1228 return nil, 0, fmt.Errorf("find target for %s: %w", featureName, err)
1229 }
1230
1231 id, err := spec.TypeID(target)
1232 if err != nil {
1233 module.Close()
1234 return nil, 0, err
1235 }
1236
1237 return module, id, nil
1238 }
1239
1240 // findTargetInKernel attempts to find a named type in the current kernel.
1241 //
1242 // target will point at the found type after a successful call. Searches both
1243 // vmlinux and any loaded modules.
1244 //
1245 // Returns a non-nil handle if the type was found in a module, [btf.ErrNotFound]
1246 // if the type wasn't found or if BTF is not enabled.
1247 func findTargetInKernel(typeName string, target *btf.Type, cache *btf.Cache) (*btf.Spec, *btf.Handle, error) {
1248 kernelSpec, err := cache.Kernel()
1249 if err != nil {
1250 return nil, nil, fmt.Errorf("load kernel spec: %w (%w)", btf.ErrNotFound, err)
1251 }
1252
1253 err = kernelSpec.TypeByName(typeName, target)
1254 if errors.Is(err, btf.ErrNotFound) {
1255 spec, module, err := findTargetInModule(typeName, target, cache)
1256 if err != nil {
1257 // EPERM may be returned when we do not have CAP_SYS_ADMIN.
1258 // Wrap error with btf.ErrNotFound so callers can handle it accordingly.
1259 if errors.Is(err, unix.EPERM) {
1260 return spec, nil, fmt.Errorf("find target in modules: %w (%w)", btf.ErrNotFound, err)
1261 }
1262
1263 return nil, nil, fmt.Errorf("find target in modules: %w", err)
1264 }
1265 return spec, module, nil
1266 }
1267 if err != nil {
1268 return nil, nil, fmt.Errorf("find target in vmlinux: %w", err)
1269 }
1270 return kernelSpec, nil, err
1271 }
1272
1273 // findTargetInModule attempts to find a named type in any loaded module.
1274 //
1275 // base must contain the kernel's types and is used to parse kmod BTF. Modules
1276 // are searched in the order they were loaded.
1277 //
1278 // Returns btf.ErrNotFound if the target can't be found in any module.
1279 func findTargetInModule(typeName string, target *btf.Type, cache *btf.Cache) (*btf.Spec, *btf.Handle, error) {
1280 it := new(btf.HandleIterator)
1281 defer it.Handle.Close()
1282
1283 for it.Next() {
1284 info, err := it.Handle.Info()
1285 if err != nil {
1286 return nil, nil, fmt.Errorf("get info for BTF ID %d: %w", it.ID, err)
1287 }
1288
1289 if !info.IsModule() {
1290 continue
1291 }
1292
1293 spec, err := cache.Module(info.Name)
1294 if err != nil {
1295 return nil, nil, fmt.Errorf("parse types for module %s: %w", info.Name, err)
1296 }
1297
1298 err = spec.TypeByName(typeName, target)
1299 if errors.Is(err, btf.ErrNotFound) {
1300 continue
1301 }
1302 if err != nil {
1303 return nil, nil, fmt.Errorf("lookup type in module %s: %w", info.Name, err)
1304 }
1305
1306 return spec, it.Take(), nil
1307 }
1308 if err := it.Err(); err != nil {
1309 return nil, nil, fmt.Errorf("iterate modules: %w", err)
1310 }
1311
1312 return nil, nil, btf.ErrNotFound
1313 }
1314
1315 // find an attach target type in a program.
1316 //
1317 // Returns errUnrecognizedAttachType.
1318 func findTargetInProgram(prog *Program, name string, progType ProgramType, attachType AttachType) (btf.TypeID, error) {
1319 type match struct {
1320 p ProgramType
1321 a AttachType
1322 }
1323
1324 var typeName string
1325 switch (match{progType, attachType}) {
1326 case match{Extension, AttachNone},
1327 match{Tracing, AttachTraceFEntry},
1328 match{Tracing, AttachTraceFExit}:
1329 typeName = name
1330 default:
1331 return 0, errUnrecognizedAttachType
1332 }
1333
1334 btfHandle, err := prog.Handle()
1335 if err != nil {
1336 return 0, fmt.Errorf("load target BTF: %w", err)
1337 }
1338 defer btfHandle.Close()
1339
1340 spec, err := btfHandle.Spec(nil)
1341 if err != nil {
1342 return 0, err
1343 }
1344
1345 var targetFunc *btf.Func
1346 err = spec.TypeByName(typeName, &targetFunc)
1347 if err != nil {
1348 return 0, fmt.Errorf("find target %s: %w", typeName, err)
1349 }
1350
1351 return spec.TypeID(targetFunc)
1352 }