Debian Codegraph @

linker.go

raw symbols SCIP
1 package ebpf
2
3 import (
4 "debug/elf"
5 "encoding/binary"
6 "errors"
7 "fmt"
8 "io"
9 "io/fs"
10 "math"
11 "slices"
12 "strings"
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/kallsyms"
18 "github.com/cilium/ebpf/internal/platform"
19 )
20
21 // handles stores handle objects to avoid gc cleanup
22 type handles []*btf.Handle
23
24 func (hs *handles) add(h *btf.Handle) (int, error) {
25 if h == nil {
26 return 0, nil
27 }
28
29 if len(*hs) == math.MaxInt16 {
30 return 0, fmt.Errorf("can't add more than %d module FDs to fdArray", math.MaxInt16)
31 }
32
33 *hs = append(*hs, h)
34
35 // return length of slice so that indexes start at 1
36 return len(*hs), nil
37 }
38
39 func (hs handles) fdArray() []int32 {
40 // first element of fda is reserved as no module can be indexed with 0
41 fda := []int32{0}
42 for _, h := range hs {
43 fda = append(fda, int32(h.FD()))
44 }
45
46 return fda
47 }
48
49 func (hs *handles) Close() error {
50 var errs []error
51 for _, h := range *hs {
52 errs = append(errs, h.Close())
53 }
54 return errors.Join(errs...)
55 }
56
57 // The linker is responsible for resolving bpf-to-bpf calls between programs
58 // within an ELF. Each BPF program must be a self-contained binary blob,
59 // so when an instruction in one ELF program section wants to jump to
60 // a function in another, the linker needs to pull in the bytecode
61 // (and BTF info) of the target function and concatenate the instruction
62 // streams.
63 //
64 // Later on in the pipeline, all call sites are fixed up with relative jumps
65 // within this newly-created instruction stream to then finally hand off to
66 // the kernel with BPF_PROG_LOAD.
67 //
68 // Each function is denoted by an ELF symbol and the compiler takes care of
69 // register setup before each jump instruction.
70
71 // hasFunctionReferences returns true if insns contains one or more bpf2bpf
72 // function references.
73 func hasFunctionReferences(insns asm.Instructions) bool {
74 for _, i := range insns {
75 if i.IsFunctionReference() {
76 return true
77 }
78 }
79 return false
80 }
81
82 // applyRelocations collects and applies any CO-RE relocations in insns.
83 //
84 // insns are modified in place.
85 func applyRelocations(insns asm.Instructions, bo binary.ByteOrder, b *btf.Builder, c *btf.Cache, kernelOverride *btf.Spec, extraTargets []*btf.Spec) error {
86 var relos []*btf.CORERelocation
87 var reloInsns []*asm.Instruction
88 iter := insns.Iterate()
89 for iter.Next() {
90 if relo := btf.CORERelocationMetadata(iter.Ins); relo != nil {
91 relos = append(relos, relo)
92 reloInsns = append(reloInsns, iter.Ins)
93 }
94 }
95
96 if len(relos) == 0 {
97 return nil
98 }
99
100 if bo == nil {
101 bo = internal.NativeEndian
102 }
103
104 var targets []*btf.Spec
105 if kernelOverride == nil {
106 kernel, err := c.Kernel()
107 if err != nil {
108 return fmt.Errorf("load kernel spec: %w", err)
109 }
110
111 modules, err := c.Modules()
112 // Ignore ErrNotExists to cater to kernels which have CONFIG_DEBUG_INFO_BTF_MODULES
113 // or CONFIG_DEBUG_INFO_BTF disabled.
114 if err != nil && !errors.Is(err, fs.ErrNotExist) {
115 return err
116 }
117
118 targets = make([]*btf.Spec, 0, 1+len(modules)+len(extraTargets))
119 targets = append(targets, kernel)
120
121 for _, kmod := range modules {
122 spec, err := c.Module(kmod)
123 if err != nil {
124 return fmt.Errorf("load BTF for kmod %s: %w", kmod, err)
125 }
126
127 targets = append(targets, spec)
128 }
129 } else {
130 // We expect kernelOverride to contain the merged types
131 // of vmlinux and kernel modules, as distributed by btfhub.
132 targets = []*btf.Spec{kernelOverride}
133 }
134
135 targets = append(targets, extraTargets...)
136
137 fixups, err := btf.CORERelocate(relos, targets, bo, b.Add)
138 if err != nil {
139 return err
140 }
141
142 for i, fixup := range fixups {
143 if err := fixup.Apply(reloInsns[i]); err != nil {
144 return fmt.Errorf("fixup for %s: %w", relos[i], err)
145 }
146 }
147
148 return nil
149 }
150
151 // flattenPrograms resolves bpf-to-bpf calls for a set of programs.
152 //
153 // Links all programs in names by modifying their ProgramSpec in progs.
154 func flattenPrograms(progs map[string]*ProgramSpec, names []string) {
155 // Pre-calculate all function references.
156 refs := make(map[*ProgramSpec][]string)
157 for _, prog := range progs {
158 refs[prog] = prog.Instructions.FunctionReferences()
159 }
160
161 // Create a flattened instruction stream, but don't modify progs yet to
162 // avoid linking multiple times.
163 flattened := make([]asm.Instructions, 0, len(names))
164 for _, name := range names {
165 flattened = append(flattened, flattenInstructions(name, progs, refs))
166 }
167
168 // Finally, assign the flattened instructions.
169 for i, name := range names {
170 progs[name].Instructions = flattened[i]
171 }
172 }
173
174 // flattenInstructions resolves bpf-to-bpf calls for a single program.
175 //
176 // Flattens the instructions of prog by concatenating the instructions of all
177 // direct and indirect dependencies.
178 //
179 // progs contains all referenceable programs, while refs contain the direct
180 // dependencies of each program.
181 func flattenInstructions(name string, progs map[string]*ProgramSpec, refs map[*ProgramSpec][]string) asm.Instructions {
182 prog := progs[name]
183 progRefs := refs[prog]
184
185 if len(progRefs) == 0 {
186 // No references, nothing to do.
187 return prog.Instructions
188 }
189
190 insns := make(asm.Instructions, len(prog.Instructions))
191 copy(insns, prog.Instructions)
192
193 // Add all direct references of prog to the list of to be linked programs.
194 pending := make([]string, len(progRefs))
195 copy(pending, progRefs)
196
197 // All references for which we've appended instructions.
198 linked := make(map[string]bool)
199
200 // Iterate all pending references. We can't use a range since pending is
201 // modified in the body below.
202 for len(pending) > 0 {
203 var ref string
204 ref, pending = pending[0], pending[1:]
205
206 if linked[ref] {
207 // We've already linked this ref, don't append instructions again.
208 continue
209 }
210
211 progRef := progs[ref]
212 if progRef == nil {
213 // We don't have instructions that go with this reference. This
214 // happens when calling extern functions.
215 continue
216 }
217
218 insns = append(insns, progRef.Instructions...)
219 linked[ref] = true
220
221 // Make sure we link indirect references.
222 pending = append(pending, refs[progRef]...)
223 }
224
225 return insns
226 }
227
228 // fixupAndValidate is called by the ELF reader right before marshaling the
229 // instruction stream. It performs last-minute adjustments to the program and
230 // runs some sanity checks before sending it off to the kernel.
231 func fixupAndValidate(insns asm.Instructions) error {
232 iter := insns.Iterate()
233 for iter.Next() {
234 ins := iter.Ins
235
236 // Map load was tagged with a Reference, but does not contain a Map pointer.
237 needsMap := ins.Reference() != "" || ins.Metadata.Get(kconfigMetaKey{}) != nil
238 if ins.IsLoadFromMap() && needsMap && ins.Map() == nil {
239 return fmt.Errorf("instruction %d: %w", iter.Index, asm.ErrUnsatisfiedMapReference)
240 }
241
242 fixupProbeReadKernel(ins)
243 }
244
245 return nil
246 }
247
248 // A constant used to poison calls to non-existent kfuncs.
249 //
250 // Similar POISON_CALL_KFUNC_BASE in libbpf, except that we use a value lower
251 // than 2^28 to fit into a tagged constant.
252 const kfuncCallPoisonBase = 0xdedc0de
253
254 // fixupKfuncs loops over all instructions in search for kfunc calls.
255 // If at least one is found, the current kernels BTF and module BTFis are searched to set Instruction.Constant
256 // and Instruction.Offset to the correct values.
257 func fixupKfuncs(insns asm.Instructions, cache *btf.Cache) (_ handles, err error) {
258 closeOnError := func(c io.Closer) {
259 if err != nil {
260 c.Close()
261 }
262 }
263
264 iter := insns.Iterate()
265 for iter.Next() {
266 ins := iter.Ins
267 if metadata := ins.Metadata.Get(kfuncMetaKey{}); metadata != nil {
268 goto fixups
269 }
270 }
271
272 return nil, nil
273
274 fixups:
275 // Only load kernel BTF if we found at least one kfunc call. kernelSpec can be
276 // nil if the kernel does not have BTF, in which case we poison all kfunc
277 // calls.
278 _, err = cache.Kernel()
279 // ErrNotSupportedOnOS wraps ErrNotSupported, check for it first.
280 if errors.Is(err, internal.ErrNotSupportedOnOS) {
281 return nil, fmt.Errorf("kfuncs are not supported on this platform: %w", err)
282 }
283 if err != nil && !errors.Is(err, ErrNotSupported) {
284 return nil, err
285 }
286
287 fdArray := make(handles, 0)
288 defer closeOnError(&fdArray)
289
290 for {
291 ins := iter.Ins
292
293 metadata := ins.Metadata.Get(kfuncMetaKey{})
294 if metadata == nil {
295 if !iter.Next() {
296 // break loop if this was the last instruction in the stream.
297 break
298 }
299 continue
300 }
301
302 // check meta, if no meta return err
303 kfm, _ := metadata.(*kfuncMeta)
304 if kfm == nil {
305 return nil, fmt.Errorf("kfuncMetaKey doesn't contain kfuncMeta")
306 }
307
308 // findTargetInKernel returns [btf.ErrNotFound] if the target can't be found
309 // or if BTF is not enabled.
310 target := btf.Type((*btf.Func)(nil))
311 spec, module, err := findTargetInKernel(kfm.Func.Name, &target, cache)
312 if errors.Is(err, btf.ErrNotFound) {
313 if kfm.Binding == elf.STB_WEAK {
314 if ins.IsKfuncCall() {
315 // If the kfunc call is weak and not found, poison the call. Use a
316 // recognizable constant to make it easier to debug.
317 fn, err := asm.BuiltinFuncForPlatform(platform.Native, kfuncCallPoisonBase)
318 if err != nil {
319 return nil, err
320 }
321 *ins = fn.Call()
322 } else if ins.OpCode.IsDWordLoad() {
323 // If the kfunc DWordLoad is weak and not found, set its address to 0.
324 ins.Constant = 0
325 ins.Src = 0
326 } else {
327 return nil, fmt.Errorf("only kfunc calls and dword loads may have kfunc metadata")
328 }
329
330 iter.Next()
331 continue
332 }
333
334 // Error on non-weak kfunc not found.
335 return nil, fmt.Errorf("kfunc %q: %w", kfm.Func.Name, ErrNotSupported)
336 }
337 if err != nil {
338 return nil, fmt.Errorf("finding kfunc in kernel: %w", err)
339 }
340
341 idx, err := fdArray.add(module)
342 if err != nil {
343 return nil, err
344 }
345
346 if err := btf.CheckTypeCompatibility(kfm.Func.Type, target.(*btf.Func).Type); err != nil {
347 return nil, &incompatibleKfuncError{kfm.Func.Name, err}
348 }
349
350 id, err := spec.TypeID(target)
351 if err != nil {
352 return nil, err
353 }
354
355 ins.Constant = int64(id)
356 ins.Offset = int16(idx)
357
358 if !iter.Next() {
359 break
360 }
361 }
362
363 return fdArray, nil
364 }
365
366 type incompatibleKfuncError struct {
367 name string
368 err error
369 }
370
371 func (ike *incompatibleKfuncError) Error() string {
372 return fmt.Sprintf("kfunc %q: %s", ike.name, ike.err)
373 }
374
375 // fixupProbeReadKernel replaces calls to bpf_probe_read_{kernel,user}(_str)
376 // with bpf_probe_read(_str) on kernels that don't support it yet.
377 func fixupProbeReadKernel(ins *asm.Instruction) {
378 if !ins.IsBuiltinCall() {
379 return
380 }
381
382 // Kernel supports bpf_probe_read_kernel, nothing to do.
383 if haveProbeReadKernel() == nil {
384 return
385 }
386
387 switch asm.BuiltinFunc(ins.Constant) {
388 case asm.FnProbeReadKernel, asm.FnProbeReadUser:
389 ins.Constant = int64(asm.FnProbeRead)
390 case asm.FnProbeReadKernelStr, asm.FnProbeReadUserStr:
391 ins.Constant = int64(asm.FnProbeReadStr)
392 }
393 }
394
395 // resolveKconfigReferences creates and populates a .kconfig map if necessary.
396 //
397 // Returns a nil Map and no error if no references exist.
398 func resolveKconfigReferences(insns asm.Instructions) (_ *Map, err error) {
399 closeOnError := func(c io.Closer) {
400 if err != nil {
401 c.Close()
402 }
403 }
404
405 var spec *MapSpec
406 iter := insns.Iterate()
407 for iter.Next() {
408 meta, _ := iter.Ins.Metadata.Get(kconfigMetaKey{}).(*kconfigMeta)
409 if meta != nil {
410 spec = meta.Map
411 break
412 }
413 }
414
415 if spec == nil {
416 return nil, nil
417 }
418
419 cpy := spec.Copy()
420 if err := resolveKconfig(cpy); err != nil {
421 return nil, err
422 }
423
424 kconfig, err := NewMap(cpy)
425 if err != nil {
426 return nil, err
427 }
428 defer closeOnError(kconfig)
429
430 // Resolve all instructions which load from .kconfig map with actual map
431 // and offset inside it.
432 iter = insns.Iterate()
433 for iter.Next() {
434 meta, _ := iter.Ins.Metadata.Get(kconfigMetaKey{}).(*kconfigMeta)
435 if meta == nil {
436 continue
437 }
438
439 if meta.Map != spec {
440 return nil, fmt.Errorf("instruction %d: reference to multiple .kconfig maps is not allowed", iter.Index)
441 }
442
443 if err := iter.Ins.AssociateMap(kconfig); err != nil {
444 return nil, fmt.Errorf("instruction %d: %w", iter.Index, err)
445 }
446
447 // Encode a map read at the offset of the var in the datasec.
448 iter.Ins.Constant = int64(uint64(meta.Offset) << 32)
449 iter.Ins.Metadata.Set(kconfigMetaKey{}, nil)
450 }
451
452 return kconfig, nil
453 }
454
455 func resolveKsymReferences(insns asm.Instructions) error {
456 type fixup struct {
457 *asm.Instruction
458 *ksymMeta
459 }
460
461 var symbols map[string]uint64
462 var fixups []fixup
463
464 iter := insns.Iterate()
465 for iter.Next() {
466 ins := iter.Ins
467 meta, _ := ins.Metadata.Get(ksymMetaKey{}).(*ksymMeta)
468 if meta == nil {
469 continue
470 }
471
472 if symbols == nil {
473 symbols = make(map[string]uint64)
474 }
475
476 symbols[meta.Name] = 0
477 fixups = append(fixups, fixup{
478 iter.Ins, meta,
479 })
480 }
481
482 if len(symbols) == 0 {
483 return nil
484 }
485
486 err := kallsyms.AssignAddresses(symbols)
487 // Tolerate ErrRestrictedKernel during initial lookup, user may have all weak
488 // ksyms and a fallback path.
489 if err != nil && !errors.Is(err, ErrRestrictedKernel) {
490 return fmt.Errorf("resolve ksyms: %w", err)
491 }
492
493 var missing []string
494 for _, fixup := range fixups {
495 addr := symbols[fixup.Name]
496 // A weak ksym variable in eBPF C means its resolution is optional.
497 if addr == 0 && fixup.Binding != elf.STB_WEAK {
498 if !slices.Contains(missing, fixup.Name) {
499 missing = append(missing, fixup.Name)
500 }
501 continue
502 }
503
504 fixup.Constant = int64(addr)
505 }
506
507 if len(missing) > 0 {
508 if err != nil {
509 // Program contains required ksyms, return the error from above.
510 return fmt.Errorf("resolve required ksyms: %s: %w", strings.Join(missing, ","), err)
511 }
512
513 return fmt.Errorf("kernel is missing symbol: %s", strings.Join(missing, ","))
514 }
515
516 return nil
517 }