Debian Codegraph @

elf_reader.go

raw symbols SCIP
1 package ebpf
2
3 import (
4 "bufio"
5 "bytes"
6 "debug/elf"
7 "encoding/binary"
8 "errors"
9 "fmt"
10 "io"
11 "iter"
12 "maps"
13 "math"
14 "os"
15 "slices"
16 "strings"
17
18 "github.com/cilium/ebpf/asm"
19 "github.com/cilium/ebpf/btf"
20 "github.com/cilium/ebpf/internal"
21 "github.com/cilium/ebpf/internal/platform"
22 "github.com/cilium/ebpf/internal/sys"
23 )
24
25 type kconfigMetaKey struct{}
26
27 type kconfigMeta struct {
28 Map *MapSpec
29 Offset uint32
30 }
31
32 type kfuncMetaKey struct{}
33
34 type kfuncMeta struct {
35 Binding elf.SymBind
36 Func *btf.Func
37 }
38
39 type ksymMetaKey struct{}
40
41 type ksymMeta struct {
42 Binding elf.SymBind
43 Name string
44 }
45
46 // elfCode is a convenience to reduce the amount of arguments that have to
47 // be passed around explicitly. You should treat its contents as immutable.
48 type elfCode struct {
49 *internal.SafeELFFile
50 sections map[elf.SectionIndex]*elfSection
51 license string
52 version uint32
53 btf *btf.Spec
54 extInfo *btf.ExtInfos
55 maps map[string]*MapSpec
56 vars map[string]*VariableSpec
57 kfuncs map[string]*btf.Func
58 ksyms map[string]struct{}
59 kconfig *MapSpec
60 }
61
62 // LoadCollectionSpec parses an ELF file into a CollectionSpec.
63 func LoadCollectionSpec(file string) (*CollectionSpec, error) {
64 f, err := os.Open(file)
65 if err != nil {
66 return nil, err
67 }
68 defer f.Close()
69
70 spec, err := LoadCollectionSpecFromReader(f)
71 if err != nil {
72 return nil, fmt.Errorf("file %s: %w", file, err)
73 }
74 return spec, nil
75 }
76
77 // LoadCollectionSpecFromReader parses an ELF file into a CollectionSpec.
78 func LoadCollectionSpecFromReader(rd io.ReaderAt) (*CollectionSpec, error) {
79 f, err := internal.NewSafeELFFile(rd)
80 if err != nil {
81 return nil, err
82 }
83
84 // Checks if the ELF file is for BPF data.
85 // Old LLVM versions set e_machine to EM_NONE.
86 if f.Machine != elf.EM_NONE && f.Machine != elf.EM_BPF {
87 return nil, fmt.Errorf("unexpected machine type for BPF ELF: %s", f.Machine)
88 }
89
90 var (
91 licenseSection *elf.Section
92 versionSection *elf.Section
93 sections = make(map[elf.SectionIndex]*elfSection)
94 relSections = make(map[elf.SectionIndex]*elf.Section)
95 )
96
97 // This is the target of relocations generated by inline assembly.
98 sections[elf.SHN_UNDEF] = newElfSection(new(elf.Section), undefSection)
99
100 // Collect all the sections we're interested in. This includes relocations
101 // which we parse later.
102 //
103 // Keep the documentation at docs/ebpf/loading/elf-sections.md up-to-date.
104 for i, sec := range f.Sections {
105 idx := elf.SectionIndex(i)
106
107 switch {
108 case strings.HasPrefix(sec.Name, "license"):
109 licenseSection = sec
110 case strings.HasPrefix(sec.Name, "version"):
111 versionSection = sec
112 case strings.HasPrefix(sec.Name, "maps"):
113 sections[idx] = newElfSection(sec, mapSection)
114 case sec.Name == ".maps":
115 sections[idx] = newElfSection(sec, btfMapSection)
116 case isDataSection(sec.Name):
117 sections[idx] = newElfSection(sec, dataSection)
118 case sec.Type == elf.SHT_REL:
119 // Store relocations under the section index of the target
120 relSections[elf.SectionIndex(sec.Info)] = sec
121 case sec.Type == elf.SHT_PROGBITS && sec.Size > 0:
122 if (sec.Flags&elf.SHF_EXECINSTR) != 0 && sec.Size > 0 {
123 sections[idx] = newElfSection(sec, programSection)
124 } else if sec.Name == structOpsLinkSec {
125 // classification based on sec names so that struct_ops-specific
126 // sections (.struct_ops.link) is correctly recognized
127 // as non-executable PROGBITS, allowing value placement and link metadata to be loaded.
128 sections[idx] = newElfSection(sec, structOpsSection)
129 } else if sec.Name == structOpsSec {
130 return nil, fmt.Errorf("section %q: got '.struct_ops' section: %w", sec.Name, ErrNotSupported)
131 }
132 }
133 }
134
135 license, err := loadLicense(licenseSection)
136 if err != nil {
137 return nil, fmt.Errorf("load license: %w", err)
138 }
139
140 version, err := loadVersion(versionSection, f.ByteOrder)
141 if err != nil {
142 return nil, fmt.Errorf("load version: %w", err)
143 }
144
145 btfSpec, btfExtInfo, err := btf.LoadSpecAndExtInfosFromReader(rd)
146 if err != nil && !errors.Is(err, btf.ErrNotFound) {
147 return nil, fmt.Errorf("load BTF: %w", err)
148 }
149
150 ec := &elfCode{
151 SafeELFFile: f,
152 sections: sections,
153 license: license,
154 version: version,
155 btf: btfSpec,
156 extInfo: btfExtInfo,
157 maps: make(map[string]*MapSpec),
158 vars: make(map[string]*VariableSpec),
159 kfuncs: make(map[string]*btf.Func),
160 ksyms: make(map[string]struct{}),
161 }
162
163 symbols, err := f.Symbols()
164 if err != nil {
165 return nil, fmt.Errorf("load symbols: %v", err)
166 }
167
168 ec.assignSymbols(symbols)
169
170 if err := ec.loadRelocations(relSections, symbols); err != nil {
171 return nil, fmt.Errorf("load relocations: %w", err)
172 }
173
174 if err := ec.loadMaps(); err != nil {
175 return nil, fmt.Errorf("load maps: %w", err)
176 }
177
178 if err := ec.loadBTFMaps(); err != nil {
179 return nil, fmt.Errorf("load BTF maps: %w", err)
180 }
181
182 if err := ec.loadDataSections(); err != nil {
183 return nil, fmt.Errorf("load data sections: %w", err)
184 }
185
186 if err := ec.loadKconfigSection(); err != nil {
187 return nil, fmt.Errorf("load virtual .kconfig section: %w", err)
188 }
189
190 if err := ec.loadKsymsSection(); err != nil {
191 return nil, fmt.Errorf("load virtual .ksyms section: %w", err)
192 }
193
194 // Finally, collect programs and link them.
195 progs, err := ec.loadProgramSections()
196 if err != nil {
197 return nil, fmt.Errorf("load programs: %w", err)
198 }
199
200 // assiociate members in structs with ProgramSpecs using relo
201 if err := ec.associateStructOpsRelocs(progs); err != nil {
202 return nil, fmt.Errorf("load struct_ops: %w", err)
203 }
204
205 return &CollectionSpec{
206 ec.maps,
207 progs,
208 ec.vars,
209 btfSpec,
210 ec.ByteOrder,
211 }, nil
212 }
213
214 func loadLicense(sec *elf.Section) (string, error) {
215 if sec == nil {
216 return "", nil
217 }
218
219 data, err := sec.Data()
220 if err != nil {
221 return "", fmt.Errorf("section %s: %v", sec.Name, err)
222 }
223 return string(bytes.TrimRight(data, "\000")), nil
224 }
225
226 func loadVersion(sec *elf.Section, bo binary.ByteOrder) (uint32, error) {
227 if sec == nil {
228 return 0, nil
229 }
230
231 var version uint32
232 if err := binary.Read(sec.Open(), bo, &version); err != nil {
233 return 0, fmt.Errorf("section %s: %v", sec.Name, err)
234 }
235 return version, nil
236 }
237
238 func isDataSection(name string) bool {
239 return name == ".bss" || strings.HasPrefix(name, ".data") || strings.HasPrefix(name, ".rodata")
240 }
241
242 func isConstantDataSection(name string) bool {
243 return strings.HasPrefix(name, ".rodata")
244 }
245
246 func isKconfigSection(name string) bool {
247 return name == ".kconfig"
248 }
249
250 type elfSectionKind int
251
252 const (
253 undefSection elfSectionKind = iota
254 mapSection
255 btfMapSection
256 programSection
257 dataSection
258 structOpsSection
259 )
260
261 type elfSection struct {
262 *elf.Section
263 kind elfSectionKind
264 // Offset from the start of the section to a symbol
265 symbols map[uint64]elf.Symbol
266 // Offset from the start of the section to a relocation, which points at
267 // a symbol in another section.
268 relocations map[uint64]elf.Symbol
269 // The number of relocations pointing at this section.
270 references int
271 }
272
273 func newElfSection(section *elf.Section, kind elfSectionKind) *elfSection {
274 return &elfSection{
275 section,
276 kind,
277 make(map[uint64]elf.Symbol),
278 make(map[uint64]elf.Symbol),
279 0,
280 }
281 }
282
283 // symbolsSorted returns the section's symbols sorted by offset.
284 func (es *elfSection) symbolsSorted() iter.Seq2[uint64, elf.Symbol] {
285 return func(yield func(uint64, elf.Symbol) bool) {
286 for _, off := range slices.Sorted(maps.Keys(es.symbols)) {
287 if !yield(off, es.symbols[off]) {
288 return
289 }
290 }
291 }
292 }
293
294 // assignSymbols takes a list of symbols and assigns them to their
295 // respective sections, indexed by name.
296 func (ec *elfCode) assignSymbols(symbols []elf.Symbol) {
297 for _, symbol := range symbols {
298 symType := elf.ST_TYPE(symbol.Info)
299 symSection := ec.sections[symbol.Section]
300 if symSection == nil {
301 continue
302 }
303
304 // Anonymous symbols only occur in debug sections which we don't process
305 // relocations for. Anonymous symbols are not referenced from other sections.
306 if symbol.Name == "" {
307 continue
308 }
309
310 // Older versions of LLVM don't tag symbols correctly, so keep
311 // all NOTYPE ones.
312 switch symSection.kind {
313 case mapSection, btfMapSection, dataSection:
314 if symType != elf.STT_NOTYPE && symType != elf.STT_OBJECT {
315 continue
316 }
317 case programSection:
318 if symType != elf.STT_NOTYPE && symType != elf.STT_FUNC {
319 continue
320 }
321
322 // Program sections may contain NOTYPE symbols with local scope, these are
323 // usually labels for jumps. We do not care for these for the purposes of
324 // linking and they may overlap with function symbols.
325 if symType == elf.STT_NOTYPE && elf.ST_BIND(symbol.Info) == elf.STB_LOCAL {
326 continue
327 }
328 // Only collect symbols that occur in program/maps/data sections.
329 default:
330 continue
331 }
332
333 symSection.symbols[symbol.Value] = symbol
334 }
335 }
336
337 // loadRelocations iterates .rel* sections and extracts relocation entries for
338 // sections of interest. Makes sure relocations point at valid sections.
339 func (ec *elfCode) loadRelocations(relSections map[elf.SectionIndex]*elf.Section, symbols []elf.Symbol) error {
340 for idx, relSection := range relSections {
341 section := ec.sections[idx]
342 if section == nil {
343 continue
344 }
345
346 rels, err := ec.loadSectionRelocations(relSection, symbols)
347 if err != nil {
348 return fmt.Errorf("relocation for section %q: %w", section.Name, err)
349 }
350
351 for _, rel := range rels {
352 target := ec.sections[rel.Section]
353 if target == nil {
354 return fmt.Errorf("section %q: reference to %q in section %s: %w", section.Name, rel.Name, rel.Section, ErrNotSupported)
355 }
356
357 target.references++
358 }
359
360 section.relocations = rels
361 }
362
363 return nil
364 }
365
366 // loadProgramSections iterates ec's sections and emits a ProgramSpec
367 // for each function it finds.
368 //
369 // The resulting map is indexed by function name.
370 func (ec *elfCode) loadProgramSections() (map[string]*ProgramSpec, error) {
371
372 progs := make(map[string]*ProgramSpec)
373
374 // Generate a ProgramSpec for each function found in each program section.
375 var export []string
376 for _, sec := range ec.sections {
377 if sec.kind != programSection {
378 continue
379 }
380
381 if len(sec.symbols) == 0 {
382 return nil, fmt.Errorf("section %v: missing symbols", sec.Name)
383 }
384
385 if sec.ReaderAt == nil {
386 return nil, fmt.Errorf("compressed program section is not supported")
387 }
388
389 funcs, err := ec.loadFunctions(sec)
390 if err != nil {
391 return nil, fmt.Errorf("section %v: %w", sec.Name, err)
392 }
393
394 progType, attachType, progFlags, attachTo := getProgType(sec.Name)
395
396 for name, insns := range funcs {
397 spec := &ProgramSpec{
398 Name: name,
399 Type: progType,
400 Flags: progFlags,
401 AttachType: attachType,
402 AttachTo: attachTo,
403 SectionName: sec.Name,
404 License: ec.license,
405 KernelVersion: ec.version,
406 Instructions: insns,
407 ByteOrder: ec.ByteOrder,
408 }
409
410 // Function names must be unique within a single ELF blob.
411 if progs[name] != nil {
412 return nil, fmt.Errorf("duplicate program name %s", name)
413 }
414 progs[name] = spec
415
416 if spec.SectionName != ".text" {
417 export = append(export, name)
418 }
419 }
420 }
421
422 flattenPrograms(progs, export)
423
424 // Hide programs (e.g. library functions) that were not explicitly emitted
425 // to an ELF section. These could be exposed in a separate CollectionSpec
426 // field later to allow them to be modified.
427 for n, p := range progs {
428 if p.SectionName == ".text" {
429 delete(progs, n)
430 }
431 }
432
433 return progs, nil
434 }
435
436 // loadFunctions extracts instruction streams from the given program section
437 // starting at each symbol in the section. The section's symbols must already
438 // be narrowed down to STT_NOTYPE (emitted by clang <8) or STT_FUNC.
439 //
440 // The resulting map is indexed by function name.
441 func (ec *elfCode) loadFunctions(sec *elfSection) (map[string]asm.Instructions, error) {
442 progs := make(map[string]asm.Instructions)
443
444 // Pull out ExtInfos once per section to avoid map lookups on every
445 // instruction.
446 fo, lo, ro := ec.extInfo.Section(sec.Name)
447
448 // Raw instruction count since start of the section. ExtInfos point at raw
449 // insn offsets and ignore the gaps between symbols in case of linked objects.
450 // We need to count them, we can't obtain this info by any other means.
451 var raw asm.RawInstructionOffset
452
453 // Sort symbols by offset so we can track instructions by their raw offsets.
454 for _, sym := range sec.symbolsSorted() {
455 if progs[sym.Name] != nil {
456 return nil, fmt.Errorf("duplicate symbol %s in section %s", sym.Name, sec.Name)
457 }
458
459 if sym.Value > math.MaxUint32 || sym.Size > math.MaxUint32 {
460 return nil, fmt.Errorf("symbol %s: offset or size exceeds 32 bits in section %s", sym.Name, sec.Name)
461 }
462 if sym.Value+sym.Size > sec.Size {
463 return nil, fmt.Errorf("symbol %s: size goes out of bounds of section %s", sym.Name, sec.Name)
464 }
465
466 // Decode the symbol's instruction stream, limited to its size.
467 sr := internal.NewBufferedSectionReader(sec, int64(sym.Value), int64(sym.Size))
468 insns := make(asm.Instructions, 0, sym.Size/asm.InstructionSize)
469 insns, err := asm.AppendInstructions(insns, sr, ec.ByteOrder, platform.Linux)
470 if err != nil {
471 return nil, fmt.Errorf("decoding instructions for symbol %s in section %s: %w", sym.Name, sec.Name, err)
472 }
473 if len(insns) == 0 {
474 return nil, fmt.Errorf("no instructions found for symbol %s in section %s", sym.Name, sec.Name)
475 }
476
477 // Mark the first instruction as the start of a function.
478 insns[0] = insns[0].WithSymbol(sym.Name)
479
480 iter := insns.Iterate()
481 for iter.Next() {
482 // Global byte offset of the instruction within the ELF section.
483 offset := sym.Value + iter.Offset.Bytes()
484
485 // Apply any relocations for the current instruction. If no relocation is
486 // present, resolve any section-relative function calls.
487 if rel, ok := sec.relocations[offset]; ok {
488 if err := ec.relocateInstruction(iter.Ins, rel); err != nil {
489 return nil, fmt.Errorf("offset %d in section %s: relocating instruction: %w", offset, sec.Name, err)
490 }
491 } else {
492 if err := referenceRelativeJump(iter.Ins, offset, sec.symbols); err != nil {
493 return nil, fmt.Errorf("offset %d in section %s: resolving relative jump: %w", offset, sec.Name, err)
494 }
495 }
496
497 assignMetadata(iter.Ins, raw, &fo, &lo, &ro)
498
499 raw += iter.Ins.Width()
500 }
501
502 // Emit the program's instructions.
503 progs[sym.Name] = insns
504 }
505
506 return progs, nil
507 }
508
509 // take pops and returns the first item in q if it matches the given predicate
510 // f. Otherwise, it returns nil.
511 func take[T any](q *[]T, f func(T) bool) *T {
512 if q == nil || len(*q) == 0 {
513 return nil
514 }
515
516 out := (*q)[0]
517 if f(out) {
518 *q = (*q)[1:]
519 return &out
520 }
521
522 return nil
523 }
524
525 // Tag the instruction with any ExtInfo metadata that's pointing at the given
526 // raw instruction.
527 func assignMetadata(ins *asm.Instruction, raw asm.RawInstructionOffset,
528 fo *btf.FuncOffsets, lo *btf.LineOffsets, ro *btf.CORERelocationOffsets) {
529
530 if f := take(fo, func(f btf.FuncOffset) bool { return f.Offset == raw }); f != nil {
531 *ins = btf.WithFuncMetadata(*ins, f.Func)
532 }
533
534 if l := take(lo, func(l btf.LineOffset) bool { return l.Offset == raw }); l != nil {
535 *ins = ins.WithSource(l.Line)
536 }
537
538 if r := take(ro, func(r btf.CORERelocationOffset) bool { return r.Offset == raw }); r != nil {
539 *ins = btf.WithCORERelocationMetadata(*ins, r.Relo)
540 }
541 }
542
543 // referenceRelativeJump turns a relative jump to another bpf subprogram within
544 // the same ELF section into a Reference Instruction.
545 //
546 // Up to LLVM 9, calls to subprograms within the same ELF section are sometimes
547 // encoded using relative jumps instead of relocation entries. These jumps go
548 // out of bounds of the current program, so their targets must be memoized
549 // before the section's instruction stream is split.
550 //
551 // The relative jump Constant is blinded to -1 and the target Symbol is set as
552 // the Instruction's Reference so it can be resolved by the linker.
553 func referenceRelativeJump(ins *asm.Instruction, offset uint64, symbols map[uint64]elf.Symbol) error {
554 if !ins.IsFunctionReference() || ins.Constant == -1 {
555 return nil
556 }
557
558 tgt := jumpTarget(offset, *ins)
559 sym := symbols[tgt].Name
560 if sym == "" {
561 return fmt.Errorf("no jump target found at offset %d", tgt)
562 }
563
564 *ins = ins.WithReference(sym)
565 ins.Constant = -1
566
567 return nil
568 }
569
570 // jumpTarget takes ins' offset within an instruction stream (in bytes)
571 // and returns its absolute jump destination (in bytes) within the
572 // instruction stream.
573 func jumpTarget(offset uint64, ins asm.Instruction) uint64 {
574 // A relative jump instruction describes the amount of raw BPF instructions
575 // to jump, convert the offset into bytes.
576 dest := ins.Constant * asm.InstructionSize
577
578 // The starting point of the jump is the end of the current instruction.
579 dest += int64(offset + asm.InstructionSize)
580
581 if dest < 0 {
582 return 0
583 }
584
585 return uint64(dest)
586 }
587
588 var errUnsupportedBinding = errors.New("unsupported binding")
589
590 func (ec *elfCode) relocateInstruction(ins *asm.Instruction, rel elf.Symbol) error {
591 var (
592 typ = elf.ST_TYPE(rel.Info)
593 bind = elf.ST_BIND(rel.Info)
594 name = rel.Name
595 )
596
597 target := ec.sections[rel.Section]
598
599 switch target.kind {
600 case mapSection, btfMapSection:
601 if bind == elf.STB_LOCAL {
602 return fmt.Errorf("possible erroneous static qualifier on map definition: found reference to %q", name)
603 }
604
605 if bind != elf.STB_GLOBAL {
606 return fmt.Errorf("map %q: %w: %s", name, errUnsupportedBinding, bind)
607 }
608
609 if typ != elf.STT_OBJECT && typ != elf.STT_NOTYPE {
610 // STT_NOTYPE is generated on clang < 8 which doesn't tag
611 // relocations appropriately.
612 return fmt.Errorf("map load: incorrect relocation type %v", typ)
613 }
614
615 ins.Src = asm.PseudoMapFD
616
617 case dataSection:
618 var offset uint32
619 switch typ {
620 case elf.STT_SECTION:
621 if bind != elf.STB_LOCAL {
622 return fmt.Errorf("direct load: %s: %w: %s", name, errUnsupportedBinding, bind)
623 }
624
625 // This is really a reference to a static symbol, which clang doesn't
626 // emit a symbol table entry for. Instead it encodes the offset in
627 // the instruction itself.
628 offset = uint32(uint64(ins.Constant))
629
630 case elf.STT_OBJECT:
631 // LLVM 9 emits OBJECT-LOCAL symbols for anonymous constants.
632 if bind != elf.STB_GLOBAL && bind != elf.STB_LOCAL && bind != elf.STB_WEAK {
633 return fmt.Errorf("direct load: %s: %w: %s", name, errUnsupportedBinding, bind)
634 }
635
636 offset = uint32(rel.Value)
637
638 case elf.STT_NOTYPE:
639 // LLVM 7 emits NOTYPE-LOCAL symbols for anonymous constants.
640 if bind != elf.STB_LOCAL {
641 return fmt.Errorf("direct load: %s: %w: %s", name, errUnsupportedBinding, bind)
642 }
643
644 offset = uint32(rel.Value)
645
646 default:
647 return fmt.Errorf("incorrect relocation type %v for direct map load", typ)
648 }
649
650 // We rely on using the name of the data section as the reference. It
651 // would be nicer to keep the real name in case of an STT_OBJECT, but
652 // it's not clear how to encode that into Instruction.
653 name = target.Name
654
655 // The kernel expects the offset in the second basic BPF instruction.
656 ins.Constant = int64(uint64(offset) << 32)
657 ins.Src = asm.PseudoMapValue
658
659 case programSection:
660 switch opCode := ins.OpCode; {
661 case opCode.JumpOp() == asm.Call:
662 if ins.Src != asm.PseudoCall {
663 return fmt.Errorf("call: %s: incorrect source register", name)
664 }
665
666 switch typ {
667 case elf.STT_NOTYPE, elf.STT_FUNC:
668 if bind != elf.STB_GLOBAL && bind != elf.STB_WEAK {
669 return fmt.Errorf("call: %s: %w: %s", name, errUnsupportedBinding, bind)
670 }
671
672 case elf.STT_SECTION:
673 if bind != elf.STB_LOCAL {
674 return fmt.Errorf("call: %s: %w: %s", name, errUnsupportedBinding, bind)
675 }
676
677 // The function we want to call is in the indicated section,
678 // at the offset encoded in the instruction itself. Reverse
679 // the calculation to find the real function we're looking for.
680 // A value of -1 references the first instruction in the section.
681 offset := int64(int32(ins.Constant)+1) * asm.InstructionSize
682 sym, ok := target.symbols[uint64(offset)]
683 if !ok {
684 return fmt.Errorf("call: no symbol at offset %d", offset)
685 }
686
687 name = sym.Name
688 ins.Constant = -1
689
690 default:
691 return fmt.Errorf("call: %s: invalid symbol type %s", name, typ)
692 }
693 case opCode.IsDWordLoad():
694 switch typ {
695 case elf.STT_FUNC:
696 if bind != elf.STB_GLOBAL {
697 return fmt.Errorf("load: %s: %w: %s", name, errUnsupportedBinding, bind)
698 }
699
700 case elf.STT_SECTION:
701 if bind != elf.STB_LOCAL {
702 return fmt.Errorf("load: %s: %w: %s", name, errUnsupportedBinding, bind)
703 }
704
705 // ins.Constant already contains the offset in bytes from the
706 // start of the section. This is different than a call to a
707 // static function.
708
709 default:
710 return fmt.Errorf("load: %s: invalid symbol type %s", name, typ)
711 }
712
713 sym, ok := target.symbols[uint64(ins.Constant)]
714 if !ok {
715 return fmt.Errorf("load: no symbol at offset %d", ins.Constant)
716 }
717
718 name = sym.Name
719 ins.Constant = -1
720 ins.Src = asm.PseudoFunc
721
722 default:
723 return fmt.Errorf("neither a call nor a load instruction: %v", ins)
724 }
725
726 // The Undefined section is used for 'virtual' symbols that aren't backed by
727 // an ELF section. This includes symbol references from inline asm, forward
728 // function declarations, as well as extern kfunc declarations using __ksym
729 // and extern kconfig variables declared using __kconfig.
730 case undefSection:
731 if bind != elf.STB_GLOBAL && bind != elf.STB_WEAK {
732 return fmt.Errorf("asm relocation: %s: %w: %s", name, errUnsupportedBinding, bind)
733 }
734
735 if typ != elf.STT_NOTYPE {
736 return fmt.Errorf("asm relocation: %s: unsupported type %s", name, typ)
737 }
738
739 kf := ec.kfuncs[name]
740 _, ks := ec.ksyms[name]
741
742 switch {
743 // If a Call / DWordLoad instruction is found and the datasec has a btf.Func with a Name
744 // that matches the symbol name we mark the instruction as a referencing a kfunc.
745 case kf != nil && ins.OpCode.JumpOp() == asm.Call:
746 ins.Metadata.Set(kfuncMetaKey{}, &kfuncMeta{
747 Func: kf,
748 Binding: bind,
749 })
750
751 ins.Src = asm.PseudoKfuncCall
752 ins.Constant = -1
753
754 case kf != nil && ins.OpCode.IsDWordLoad():
755 ins.Metadata.Set(kfuncMetaKey{}, &kfuncMeta{
756 Func: kf,
757 Binding: bind,
758 })
759
760 ins.Constant = 0
761
762 case ks && ins.OpCode.IsDWordLoad():
763 if bind != elf.STB_GLOBAL && bind != elf.STB_WEAK {
764 return fmt.Errorf("asm relocation: %s: %w: %s", name, errUnsupportedBinding, bind)
765 }
766 ins.Metadata.Set(ksymMetaKey{}, &ksymMeta{
767 Binding: bind,
768 Name: name,
769 })
770
771 // If no kconfig map is found, this must be a symbol reference from inline
772 // asm (see testdata/loader.c:asm_relocation()) or a call to a forward
773 // function declaration (see testdata/fwd_decl.c). Don't interfere, These
774 // remain standard symbol references.
775 // extern __kconfig reads are represented as dword loads that need to be
776 // rewritten to pseudo map loads from .kconfig. If the map is present,
777 // require it to contain the symbol to disambiguate between inline asm
778 // relos and kconfigs.
779 case ec.kconfig != nil && ins.OpCode.IsDWordLoad():
780 if bind != elf.STB_GLOBAL {
781 return fmt.Errorf("asm relocation: %s: %w: %s", name, errUnsupportedBinding, bind)
782 }
783
784 for _, vsi := range ec.kconfig.Value.(*btf.Datasec).Vars {
785 if vsi.Type.(*btf.Var).Name != rel.Name {
786 continue
787 }
788
789 ins.Src = asm.PseudoMapValue
790 ins.Metadata.Set(kconfigMetaKey{}, &kconfigMeta{ec.kconfig, vsi.Offset})
791 return nil
792 }
793
794 return fmt.Errorf("kconfig %s not found in .kconfig", rel.Name)
795 }
796
797 default:
798 return fmt.Errorf("relocation to %q: %w", target.Name, ErrNotSupported)
799 }
800
801 *ins = ins.WithReference(name)
802 return nil
803 }
804
805 // loadMaps iterates over all ELF sections marked as map sections (like .maps)
806 // and parses each symbol into a MapSpec.
807 func (ec *elfCode) loadMaps() error {
808 for _, sec := range ec.sections {
809 if sec.kind != mapSection {
810 continue
811 }
812
813 if len(sec.symbols) == 0 {
814 return fmt.Errorf("section %v: no symbols", sec.Name)
815 }
816
817 if sec.ReaderAt == nil {
818 return fmt.Errorf("compressed map section is not supported")
819 }
820
821 vars, err := ec.sectionVars(ec.btf, sec.Name)
822 if err != nil {
823 return fmt.Errorf("section %v: loading map variable BTF: %w", sec.Name, err)
824 }
825
826 for _, sym := range sec.symbols {
827 name := sym.Name
828 if ec.maps[name] != nil {
829 return fmt.Errorf("duplicate symbol %s in section %s", name, sec.Name)
830 }
831
832 if sym.Value > math.MaxUint32 || sym.Size > math.MaxUint32 {
833 return fmt.Errorf("symbol %s: offset or size exceeds 32 bits in section %s", sym.Name, sec.Name)
834 }
835 if sym.Value+sym.Size > sec.Size {
836 return fmt.Errorf("symbol %s: size goes out of bounds of section %s", name, sec.Name)
837 }
838
839 sr := internal.NewBufferedSectionReader(sec, int64(sym.Value), int64(sym.Size))
840
841 spec := MapSpec{
842 Name: sanitizeName(name, -1),
843 }
844 switch {
845 case binary.Read(sr, ec.ByteOrder, &spec.Type) != nil:
846 return fmt.Errorf("map %s: missing type", name)
847 case binary.Read(sr, ec.ByteOrder, &spec.KeySize) != nil:
848 return fmt.Errorf("map %s: missing key size", name)
849 case binary.Read(sr, ec.ByteOrder, &spec.ValueSize) != nil:
850 return fmt.Errorf("map %s: missing value size", name)
851 case binary.Read(sr, ec.ByteOrder, &spec.MaxEntries) != nil:
852 return fmt.Errorf("map %s: missing max entries", name)
853 case binary.Read(sr, ec.ByteOrder, &spec.Flags) != nil:
854 return fmt.Errorf("map %s: missing flags", name)
855 }
856
857 extra, err := io.ReadAll(sr)
858 if err != nil {
859 return fmt.Errorf("map %s: reading map tail: %w", name, err)
860 }
861 if len(extra) > 0 {
862 spec.Extra = bytes.NewReader(extra)
863 }
864
865 if v, ok := vars[name]; ok {
866 spec.Tags = slices.Clone(v.Tags)
867 }
868
869 ec.maps[name] = &spec
870 }
871 }
872
873 return nil
874 }
875
876 // sectionVars looks up the BTF Datasec for the given section name and returns a
877 // map of variable names to their btf.Var definitions.
878 func (ec *elfCode) sectionVars(spec *btf.Spec, sec string) (map[string]*btf.Var, error) {
879 vars := make(map[string]*btf.Var)
880
881 if spec == nil {
882 return vars, nil
883 }
884
885 var ds *btf.Datasec
886 if err := ec.btf.TypeByName(sec, &ds); err != nil {
887 return vars, nil
888 }
889
890 for _, vsi := range ds.Vars {
891 v, ok := btf.As[*btf.Var](vsi.Type)
892 if !ok {
893 return nil, fmt.Errorf("btf.VarSecInfo doesn't point to a *btf.Var: %T", vsi.Type)
894 }
895 vars[string(v.Name)] = v
896 }
897
898 return vars, nil
899 }
900
901 // loadBTFMaps iterates over all ELF sections marked as BTF map sections
902 // (like .maps) and parses them into MapSpecs. Dump the .maps section and
903 // any relocations with `readelf -x .maps -r <elf_file>`.
904 func (ec *elfCode) loadBTFMaps() error {
905 for _, sec := range ec.sections {
906 if sec.kind != btfMapSection {
907 continue
908 }
909
910 if ec.btf == nil {
911 return fmt.Errorf("missing BTF")
912 }
913
914 if sec.ReaderAt == nil {
915 return fmt.Errorf("compressed BTF map section is not supported")
916 }
917
918 vars, err := ec.sectionVars(ec.btf, sec.Name)
919 if err != nil {
920 return fmt.Errorf("section %v: loading map variable BTF: %w", sec.Name, err)
921 }
922
923 if len(vars) != len(sec.symbols) {
924 return fmt.Errorf("section %v: contains %d symbols but %d btf.Vars", sec.Name, len(sec.symbols), len(vars))
925 }
926
927 syms := make(map[string]elf.Symbol)
928 for _, sym := range sec.symbols {
929 syms[sym.Name] = sym
930 }
931
932 for _, v := range vars {
933 name := v.Name
934
935 // Find the ELF symbol corresponding to this Var.
936 sym, ok := syms[name]
937 if !ok {
938 return fmt.Errorf("section %v: missing symbol for map %s", sec.Name, name)
939 }
940
941 if sym.Value > math.MaxUint32 || sym.Size > math.MaxUint32 {
942 return fmt.Errorf("symbol %s: offset or size exceeds 32 bits in section %s", sym.Name, sec.Name)
943 }
944 if sym.Value+sym.Size > sec.Size {
945 return fmt.Errorf("section %v: symbol %s: size goes out of bounds of section", sec.Name, name)
946 }
947
948 sr := internal.NewBufferedSectionReader(sec, int64(sym.Value), int64(sym.Size))
949
950 // The BTF metadata for each Var contains the full length of the map
951 // declaration, so read the corresponding amount of bytes from the ELF.
952 // This way, we can pinpoint which map declaration contains unexpected
953 // (and therefore unsupported) data.
954 if _, err = io.Copy(internal.DiscardZeroes{}, sr); err != nil {
955 return fmt.Errorf("section %v: map %s: initializing BTF map definitions: %w", sec.Name, name, internal.ErrNotSupported)
956 }
957
958 if ec.maps[name] != nil {
959 return fmt.Errorf("section %v: map %s already exists", sec.Name, name)
960 }
961
962 // Each Var representing a BTF map definition contains a Struct.
963 mapStruct, ok := btf.UnderlyingType(v.Type).(*btf.Struct)
964 if !ok {
965 return fmt.Errorf("expected struct, got %s", v.Type)
966 }
967
968 spec, err := mapSpecFromBTF(sec, sym, v, mapStruct, ec.btf, name, false)
969 if err != nil {
970 return fmt.Errorf("map %v: %w", name, err)
971 }
972
973 ec.maps[name] = spec
974 }
975 }
976
977 return nil
978 }
979
980 // mapSpecFromBTF produces a MapSpec based on a btf.Struct def representing
981 // a BTF map definition. The name and spec arguments will be copied to the
982 // resulting MapSpec, and inner must be true on any recursive invocations.
983 func mapSpecFromBTF(es *elfSection, sym elf.Symbol, v *btf.Var, def *btf.Struct, spec *btf.Spec, name string, inner bool) (*MapSpec, error) {
984 var (
985 key, value btf.Type
986 keySize, valueSize uint64
987 mapType MapType
988 flags, maxEntries uint64
989 pinType PinType
990 mapExtra uint64
991 innerMapSpec *MapSpec
992 contents []MapKV
993 err error
994 )
995
996 for i, member := range def.Members {
997 switch member.Name {
998 case "type":
999 mt, err := uintFromBTF(member.Type)
1000 if err != nil {
1001 return nil, fmt.Errorf("can't get type: %w", err)
1002 }
1003 mapType = MapType(mt)
1004
1005 case "map_flags":
1006 flags, err = uintFromBTF(member.Type)
1007 if err != nil {
1008 return nil, fmt.Errorf("can't get BTF map flags: %w", err)
1009 }
1010
1011 case "max_entries":
1012 maxEntries, err = uintFromBTF(member.Type)
1013 if err != nil {
1014 return nil, fmt.Errorf("can't get BTF map max entries: %w", err)
1015 }
1016
1017 case "key":
1018 if keySize != 0 {
1019 return nil, errors.New("both key and key_size given")
1020 }
1021
1022 pk, ok := member.Type.(*btf.Pointer)
1023 if !ok {
1024 return nil, fmt.Errorf("key type is not a pointer: %T", member.Type)
1025 }
1026
1027 key = pk.Target
1028
1029 size, err := btf.Sizeof(pk.Target)
1030 if err != nil {
1031 return nil, fmt.Errorf("can't get size of BTF key: %w", err)
1032 }
1033
1034 keySize = uint64(size)
1035
1036 case "value":
1037 if valueSize != 0 {
1038 return nil, errors.New("both value and value_size given")
1039 }
1040
1041 vk, ok := member.Type.(*btf.Pointer)
1042 if !ok {
1043 return nil, fmt.Errorf("value type is not a pointer: %T", member.Type)
1044 }
1045
1046 value = vk.Target
1047
1048 size, err := btf.Sizeof(vk.Target)
1049 if err != nil {
1050 return nil, fmt.Errorf("can't get size of BTF value: %w", err)
1051 }
1052
1053 valueSize = uint64(size)
1054
1055 case "key_size":
1056 // Key needs to be nil and keySize needs to be 0 for key_size to be
1057 // considered a valid member.
1058 if key != nil || keySize != 0 {
1059 return nil, errors.New("both key and key_size given")
1060 }
1061
1062 keySize, err = uintFromBTF(member.Type)
1063 if err != nil {
1064 return nil, fmt.Errorf("can't get BTF key size: %w", err)
1065 }
1066
1067 case "value_size":
1068 // Value needs to be nil and valueSize needs to be 0 for value_size to be
1069 // considered a valid member.
1070 if value != nil || valueSize != 0 {
1071 return nil, errors.New("both value and value_size given")
1072 }
1073
1074 valueSize, err = uintFromBTF(member.Type)
1075 if err != nil {
1076 return nil, fmt.Errorf("can't get BTF value size: %w", err)
1077 }
1078
1079 case "pinning":
1080 if inner {
1081 return nil, errors.New("inner maps can't be pinned")
1082 }
1083
1084 pinning, err := uintFromBTF(member.Type)
1085 if err != nil {
1086 return nil, fmt.Errorf("can't get pinning: %w", err)
1087 }
1088
1089 pinType = PinType(pinning)
1090
1091 case "values":
1092 // The 'values' field in BTF map definitions is used for declaring map
1093 // value types that are references to other BPF objects, like other maps
1094 // or programs. It is always expected to be an array of pointers.
1095 if i != len(def.Members)-1 {
1096 return nil, errors.New("'values' must be the last member in a BTF map definition")
1097 }
1098
1099 if valueSize != 0 && valueSize != 4 {
1100 return nil, errors.New("value_size must be 0 or 4")
1101 }
1102 valueSize = 4
1103
1104 valueType, err := resolveBTFArrayMacro(member.Type)
1105 if err != nil {
1106 return nil, fmt.Errorf("can't resolve type of member 'values': %w", err)
1107 }
1108
1109 switch t := valueType.(type) {
1110 case *btf.Struct:
1111 // The values member pointing to an array of structs means we're expecting
1112 // a map-in-map declaration.
1113 if mapType != ArrayOfMaps && mapType != HashOfMaps {
1114 return nil, errors.New("outer map needs to be an array or a hash of maps")
1115 }
1116 if inner {
1117 return nil, fmt.Errorf("nested inner maps are not supported")
1118 }
1119
1120 // This inner map spec is used as a map template, but it needs to be
1121 // created as a traditional map before it can be used to do so.
1122 // libbpf names the inner map template '<outer_name>.inner', but we
1123 // opted for _inner to simplify validation logic. (dots only supported
1124 // on kernels 5.2 and up)
1125 // Pass the BTF spec from the parent object, since both parent and
1126 // child must be created from the same BTF blob (on kernels that support BTF).
1127 innerMapSpec, err = mapSpecFromBTF(es, sym, v, t, spec, name+"_inner", true)
1128 if err != nil {
1129 return nil, fmt.Errorf("can't parse BTF map definition of inner map: %w", err)
1130 }
1131
1132 case *btf.FuncProto:
1133 // The values member contains an array of function pointers, meaning an
1134 // autopopulated PROG_ARRAY.
1135 if mapType != ProgramArray {
1136 return nil, errors.New("map needs to be a program array")
1137 }
1138
1139 default:
1140 return nil, fmt.Errorf("unsupported value type %q in 'values' field", t)
1141 }
1142
1143 contents, err = resolveBTFValuesContents(es, sym, member)
1144 if err != nil {
1145 return nil, fmt.Errorf("resolving values contents: %w", err)
1146 }
1147
1148 case "map_extra":
1149 mapExtra, err = uintFromBTF(member.Type)
1150 if err != nil {
1151 return nil, fmt.Errorf("resolving map_extra: %w", err)
1152 }
1153
1154 default:
1155 return nil, fmt.Errorf("unrecognized field %s in BTF map definition", member.Name)
1156 }
1157 }
1158
1159 // Some maps don't support value sizes, but annotating their map definitions
1160 // with __type macros can still be useful, especially to let bpf2go generate
1161 // type definitions for them.
1162 if value != nil && !mapType.canHaveValueSize() {
1163 valueSize = 0
1164 }
1165
1166 return &MapSpec{
1167 Name: sanitizeName(name, -1),
1168 Type: MapType(mapType),
1169 KeySize: uint32(keySize),
1170 ValueSize: uint32(valueSize),
1171 MaxEntries: uint32(maxEntries),
1172 Flags: uint32(flags),
1173 Key: key,
1174 Value: value,
1175 Pinning: pinType,
1176 InnerMap: innerMapSpec,
1177 Contents: contents,
1178 Tags: slices.Clone(v.Tags),
1179 MapExtra: mapExtra,
1180 }, nil
1181 }
1182
1183 // uintFromBTF resolves the __uint and __ulong macros.
1184 //
1185 // __uint emits a pointer to a sized array. For int (*foo)[10], this function
1186 // will return 10.
1187 //
1188 // __ulong emits an enum with a single value that can represent a 64-bit
1189 // integer. The first (and only) enum value is returned.
1190 func uintFromBTF(typ btf.Type) (uint64, error) {
1191 switch t := typ.(type) {
1192 case *btf.Pointer:
1193 arr, ok := t.Target.(*btf.Array)
1194 if !ok {
1195 return 0, fmt.Errorf("not a pointer to array: %v", typ)
1196 }
1197 return uint64(arr.Nelems), nil
1198
1199 case *btf.Enum:
1200 if len(t.Values) == 0 {
1201 return 0, errors.New("enum has no values")
1202 }
1203 return t.Values[0].Value, nil
1204
1205 default:
1206 return 0, fmt.Errorf("not a pointer or enum: %v", typ)
1207 }
1208 }
1209
1210 // resolveBTFArrayMacro resolves the __array macro, which declares an array
1211 // of pointers to a given type. This function returns the target Type of
1212 // the pointers in the array.
1213 func resolveBTFArrayMacro(typ btf.Type) (btf.Type, error) {
1214 arr, ok := typ.(*btf.Array)
1215 if !ok {
1216 return nil, fmt.Errorf("not an array: %v", typ)
1217 }
1218
1219 ptr, ok := arr.Type.(*btf.Pointer)
1220 if !ok {
1221 return nil, fmt.Errorf("not an array of pointers: %v", typ)
1222 }
1223
1224 return ptr.Target, nil
1225 }
1226
1227 // valuesRelocations returns an iterator over the relocations in the ELF section
1228 // corresponding to the elements of a .values array in a BTF map definition. Each
1229 // iteration yields the array index and the symbol referenced by the relocation
1230 // at that index. Empty indices are skipped.
1231 func valuesRelocations(es *elfSection, sym elf.Symbol, member btf.Member) iter.Seq2[uint32, elf.Symbol] {
1232 // The elements of a .values pointer array are not encoded in BTF itself.
1233 // Instead, each array index receives a relocation pointing at a symbol
1234 // (map/prog) in another section. However, it's possible to leave certain
1235 // array indices empty, so all indices' offsets need to be checked for emitted
1236 // relocations.
1237
1238 // Absolute offset of the .values member within the section.
1239 start := sym.Value + uint64(member.Offset.Bytes())
1240
1241 // .values is a variable-length struct member, so its contents run until the
1242 // end of the symbol. The symbol offset + size is the absolute offset of the
1243 // end of the array in the section.
1244 end := sym.Value + sym.Size
1245
1246 // The size of an address in this section. This determines the width of an
1247 // index in the array.
1248 align := es.Addralign
1249
1250 // Amount of elements in the .values array.
1251 elems := (end - start) / align
1252
1253 return func(yield func(uint32, elf.Symbol) bool) {
1254 for i := range uint32(elems) {
1255 // off increases by align on each iteration, starting at .values.
1256 off := start + (uint64(i) * align)
1257
1258 r, ok := es.relocations[off]
1259 if !ok {
1260 continue
1261 }
1262
1263 if !yield(i, r) {
1264 return
1265 }
1266 }
1267 }
1268
1269 }
1270
1271 // resolveBTFValuesContents looks up the symbols referenced by the relocations
1272 // in a .values array and returns them as MapKV pairs, where the key is the
1273 // array index and the value is the symbol name. Empty indices are skipped.
1274 func resolveBTFValuesContents(es *elfSection, sym elf.Symbol, member btf.Member) ([]MapKV, error) {
1275 var contents []MapKV
1276
1277 if member.Offset.Bytes() > uint32(sym.Size) {
1278 return nil, fmt.Errorf("member offset %d exceeds symbol size %d", member.Offset.Bytes(), sym.Size)
1279 }
1280
1281 if es.Addralign == 0 {
1282 return nil, fmt.Errorf("section has no address alignment, can't resolve .values contents")
1283 }
1284
1285 for i, sym := range valuesRelocations(es, sym, member) {
1286 // Emit a value stub based on the type of relocation to be replaced by a
1287 // real fd later in the pipeline before populating the Map.
1288 switch t := elf.ST_TYPE(sym.Info); t {
1289 case elf.STT_FUNC:
1290 contents = append(contents, MapKV{i, sym.Name})
1291 case elf.STT_OBJECT:
1292 contents = append(contents, MapKV{i, sym.Name})
1293 default:
1294 return nil, fmt.Errorf("unknown relocation type %v for symbol %s", t, sym.Name)
1295 }
1296 }
1297
1298 return contents, nil
1299 }
1300
1301 func (ec *elfCode) loadDataSections() error {
1302 for _, sec := range ec.sections {
1303 if sec.kind != dataSection {
1304 continue
1305 }
1306
1307 // If a section has no references, it will be freed as soon as the
1308 // Collection closes, so creating and populating it is wasteful. If it has
1309 // no symbols, it is likely an ephemeral section used during compilation
1310 // that wasn't sanitized by the bpf linker. (like .rodata.str1.1)
1311 //
1312 // No symbols means no VariableSpecs can be generated from it, making it
1313 // pointless to emit a data section for.
1314 if sec.references == 0 && len(sec.symbols) == 0 {
1315 continue
1316 }
1317
1318 if sec.Size > math.MaxUint32 {
1319 return fmt.Errorf("data section %s: contents exceed maximum size", sec.Name)
1320 }
1321
1322 mapSpec := &MapSpec{
1323 Name: sanitizeName(sec.Name, -1),
1324 Type: Array,
1325 KeySize: 4,
1326 ValueSize: uint32(sec.Size),
1327 MaxEntries: 1,
1328 }
1329
1330 if isConstantDataSection(sec.Name) {
1331 mapSpec.Flags = sys.BPF_F_RDONLY_PROG
1332 }
1333
1334 var data []byte
1335 switch sec.Type {
1336 // Only open the section if we know there's actual data to be read.
1337 case elf.SHT_PROGBITS:
1338 var err error
1339 data, err = sec.Data()
1340 if err != nil {
1341 return fmt.Errorf("data section %s: can't get contents: %w", sec.Name, err)
1342 }
1343
1344 case elf.SHT_NOBITS:
1345 // NOBITS sections like .bss contain only zeroes and are not allocated in
1346 // the ELF. Since data sections are Arrays, the kernel can preallocate
1347 // them. Don't attempt reading zeroes from the ELF, instead allocate the
1348 // zeroed memory to support getting and setting VariableSpecs for sections
1349 // like .bss.
1350 data = make([]byte, sec.Size)
1351
1352 default:
1353 return fmt.Errorf("data section %s: unknown section type %s", sec.Name, sec.Type)
1354 }
1355
1356 mapSpec.Contents = []MapKV{{uint32(0), data}}
1357
1358 for off, sym := range sec.symbols {
1359 // Skip symbols marked with the 'hidden' attribute.
1360 if elf.ST_VISIBILITY(sym.Other) == elf.STV_HIDDEN ||
1361 elf.ST_VISIBILITY(sym.Other) == elf.STV_INTERNAL {
1362 continue
1363 }
1364
1365 // Only accept symbols with global or weak bindings. The common
1366 // alternative is STB_LOCAL, which are either function-scoped or declared
1367 // 'static'.
1368 if elf.ST_BIND(sym.Info) != elf.STB_GLOBAL &&
1369 elf.ST_BIND(sym.Info) != elf.STB_WEAK {
1370 continue
1371 }
1372
1373 if ec.vars[sym.Name] != nil {
1374 return fmt.Errorf("data section %s: duplicate variable %s", sec.Name, sym.Name)
1375 }
1376
1377 // Skip symbols starting with a dot, they are compiler-internal symbols
1378 // emitted by clang 11 and earlier and are not cleaned up by the bpf
1379 // compiler backend (e.g. symbols named .Lconstinit.1 in sections like
1380 // .rodata.cst32). Variables in C cannot start with a dot, so filter these
1381 // out.
1382 if strings.HasPrefix(sym.Name, ".") {
1383 continue
1384 }
1385
1386 if off+sym.Size > uint64(len(data)) {
1387 return fmt.Errorf("data section %s: variable %s exceeds section bounds", sec.Name, sym.Name)
1388 }
1389
1390 if off > math.MaxUint32 {
1391 return fmt.Errorf("data section %s: variable %s offset %d exceeds maximum", sec.Name, sym.Name, off)
1392 }
1393
1394 if sym.Size > math.MaxUint32 {
1395 return fmt.Errorf("data section %s: variable %s size %d exceeds maximum", sec.Name, sym.Name, sym.Size)
1396 }
1397
1398 ec.vars[sym.Name] = &VariableSpec{
1399 SectionName: sec.Name,
1400 Name: sym.Name,
1401 Offset: uint32(off),
1402 Value: slices.Clone(data[off : off+sym.Size]),
1403 }
1404 }
1405
1406 // It is possible for a data section to exist without a corresponding BTF Datasec
1407 // if it only contains anonymous values like macro-defined arrays.
1408 if ec.btf != nil {
1409 var ds *btf.Datasec
1410 if ec.btf.TypeByName(sec.Name, &ds) == nil {
1411 // Assign the spec's key and BTF only if the Datasec lookup was successful.
1412 mapSpec.Key = &btf.Void{}
1413 mapSpec.Value = ds
1414
1415 // Populate VariableSpecs with type information, if available.
1416 for _, v := range ds.Vars {
1417 name := v.Type.TypeName()
1418 if name == "" {
1419 return fmt.Errorf("data section %s: anonymous variable %v", sec.Name, v)
1420 }
1421
1422 vt, ok := v.Type.(*btf.Var)
1423 if !ok {
1424 return fmt.Errorf("data section %s: unexpected type %T for variable %s", sec.Name, v.Type, name)
1425 }
1426
1427 ev := ec.vars[name]
1428 if ev == nil {
1429 // Hidden symbols appear in the BTF Datasec but don't receive a VariableSpec.
1430 continue
1431 }
1432
1433 if v.Offset != ev.Offset {
1434 return fmt.Errorf("data section %s: variable %s datasec offset (%d) doesn't match ELF symbol offset (%d)", sec.Name, name, v.Offset, ev.Offset)
1435 }
1436
1437 if v.Size != ev.Size() {
1438 return fmt.Errorf("data section %s: variable %s size in datasec (%d) doesn't match ELF symbol size (%d)", sec.Name, name, v.Size, ev.Size())
1439 }
1440
1441 // Decouple the Var in the VariableSpec from the underlying DataSec in
1442 // the MapSpec to avoid modifications from affecting map loads later on.
1443 ev.Type = btf.Copy(vt).(*btf.Var)
1444 }
1445 }
1446 }
1447
1448 ec.maps[sec.Name] = mapSpec
1449 }
1450
1451 return nil
1452 }
1453
1454 // loadKconfigSection handles the 'virtual' Datasec .kconfig that doesn't
1455 // have a corresponding ELF section and exist purely in BTF.
1456 func (ec *elfCode) loadKconfigSection() error {
1457 if ec.btf == nil {
1458 return nil
1459 }
1460
1461 var ds *btf.Datasec
1462 err := ec.btf.TypeByName(".kconfig", &ds)
1463 if errors.Is(err, btf.ErrNotFound) {
1464 return nil
1465 }
1466 if err != nil {
1467 return err
1468 }
1469
1470 if ds.Size == 0 {
1471 return errors.New("zero-length .kconfig")
1472 }
1473
1474 ec.kconfig = &MapSpec{
1475 Name: ".kconfig",
1476 Type: Array,
1477 KeySize: uint32(4),
1478 ValueSize: ds.Size,
1479 MaxEntries: 1,
1480 Flags: sys.BPF_F_RDONLY_PROG,
1481 Key: &btf.Int{Size: 4},
1482 Value: ds,
1483 }
1484
1485 return nil
1486 }
1487
1488 // loadKsymsSection handles the 'virtual' Datasec .ksyms that doesn't
1489 // have a corresponding ELF section and exist purely in BTF.
1490 func (ec *elfCode) loadKsymsSection() error {
1491 if ec.btf == nil {
1492 return nil
1493 }
1494
1495 var ds *btf.Datasec
1496 err := ec.btf.TypeByName(".ksyms", &ds)
1497 if errors.Is(err, btf.ErrNotFound) {
1498 return nil
1499 }
1500 if err != nil {
1501 return err
1502 }
1503
1504 for _, v := range ds.Vars {
1505 switch t := v.Type.(type) {
1506 case *btf.Func:
1507 ec.kfuncs[t.TypeName()] = t
1508 case *btf.Var:
1509 ec.ksyms[t.TypeName()] = struct{}{}
1510 default:
1511 return fmt.Errorf("unexpected variable type in .ksyms: %T", v)
1512 }
1513 }
1514
1515 return nil
1516 }
1517
1518 // associateStructOpsRelocs handles `.struct_ops.link`
1519 // and associates the target function with the correct struct member in the map.
1520 func (ec *elfCode) associateStructOpsRelocs(progs map[string]*ProgramSpec) error {
1521 for _, sec := range ec.sections {
1522 if sec.kind != structOpsSection {
1523 continue
1524 }
1525
1526 userData, err := sec.Data()
1527 if err != nil {
1528 return fmt.Errorf("failed to read section data: %w", err)
1529 }
1530
1531 if ec.btf == nil {
1532 return fmt.Errorf("struct_ops section %s: missing BTF", sec.Name)
1533 }
1534
1535 // Resolve the BTF datasec describing variables in this section.
1536 var ds *btf.Datasec
1537 if err := ec.btf.TypeByName(sec.Name, &ds); err != nil {
1538 return fmt.Errorf("datasec %s: %w", sec.Name, err)
1539 }
1540
1541 // Set flags for .struct_ops.link (BPF_F_LINK).
1542 flags := uint32(0)
1543 if sec.Name == structOpsLinkSec {
1544 flags = sys.BPF_F_LINK
1545 }
1546
1547 for _, vsi := range ds.Vars {
1548 userSt, baseOff, err := ec.createStructOpsMap(vsi, userData, flags)
1549 if err != nil {
1550 return err
1551 }
1552
1553 if err := structOpsSetAttachTo(sec, baseOff, userSt, progs); err != nil {
1554 return err
1555 }
1556 }
1557 }
1558
1559 return nil
1560 }
1561
1562 // createStructOpsMap() creates and registers a MapSpec for a struct_ops
1563 func (ec *elfCode) createStructOpsMap(vsi btf.VarSecinfo, userData []byte, flags uint32) (*btf.Struct, uint32, error) {
1564 varType, ok := btf.As[*btf.Var](vsi.Type)
1565 if !ok {
1566 return nil, 0, fmt.Errorf("vsi: expect var, got %T", vsi.Type)
1567 }
1568
1569 mapName := varType.Name
1570
1571 userSt, ok := btf.As[*btf.Struct](varType.Type)
1572 if !ok {
1573 return nil, 0, fmt.Errorf("var %s: expect struct, got %T", varType.Name, varType.Type)
1574 }
1575
1576 userSize := userSt.Size
1577 baseOff := vsi.Offset
1578 if uint64(baseOff)+uint64(userSize) > uint64(len(userData)) {
1579 return nil, 0, fmt.Errorf("%s exceeds section", mapName)
1580 }
1581
1582 // Register the MapSpec for this struct_ops instance if doesn't exist
1583 if _, exists := ec.maps[mapName]; exists {
1584 return nil, 0, fmt.Errorf("struct_ops map %s: already exists", mapName)
1585 }
1586
1587 ec.maps[mapName] = &MapSpec{
1588 Name: mapName,
1589 Type: StructOpsMap,
1590 Key: &btf.Int{Size: 4},
1591 KeySize: structOpsKeySize,
1592 ValueSize: userSize, // length of the user-struct type
1593 Value: userSt,
1594 Flags: flags,
1595 MaxEntries: 1,
1596 Contents: []MapKV{
1597 {
1598 Key: uint32(0),
1599 Value: append([]byte(nil), userData[baseOff:baseOff+userSize]...),
1600 },
1601 },
1602 }
1603
1604 return userSt, baseOff, nil
1605 }
1606
1607 type libbpfElfSectionDef struct {
1608 pattern string
1609 programType sys.ProgType
1610 attachType sys.AttachType
1611 flags libbpfElfSectionFlag
1612 }
1613
1614 type libbpfElfSectionFlag uint32
1615
1616 // The values correspond to enum sec_def_flags in libbpf.
1617 const (
1618 _SEC_NONE libbpfElfSectionFlag = 0
1619
1620 _SEC_EXP_ATTACH_OPT libbpfElfSectionFlag = 1 << (iota - 1)
1621 _SEC_ATTACHABLE
1622 _SEC_ATTACH_BTF
1623 _SEC_SLEEPABLE
1624 _SEC_XDP_FRAGS
1625 _SEC_USDT
1626
1627 _SEC_ATTACHABLE_OPT = _SEC_ATTACHABLE | _SEC_EXP_ATTACH_OPT
1628 )
1629
1630 func getProgType(sectionName string) (ProgramType, AttachType, uint32, string) {
1631 // Skip optional program marking for now.
1632 sectionName = strings.TrimPrefix(sectionName, "?")
1633
1634 for _, t := range elfSectionDefs {
1635 extra, ok := matchSectionName(sectionName, t.pattern)
1636 if !ok {
1637 continue
1638 }
1639
1640 programType := ProgramType(t.programType)
1641 attachType := AttachType(t.attachType)
1642
1643 var flags uint32
1644 if t.flags&_SEC_SLEEPABLE > 0 {
1645 flags |= sys.BPF_F_SLEEPABLE
1646 }
1647 if t.flags&_SEC_XDP_FRAGS > 0 {
1648 flags |= sys.BPF_F_XDP_HAS_FRAGS
1649 }
1650
1651 // The libbpf documentation on program types states: 'The struct_ops attach
1652 // format supports struct_ops[.s]/<name> convention, but name is ignored and
1653 // it is recommended to just use plain SEC("struct_ops[.s]").'
1654 //
1655 // Ignore any extra for struct_ops to match libbpf behaviour.
1656 if programType == StructOps {
1657 extra = ""
1658 }
1659
1660 return programType, attachType, flags, extra
1661 }
1662
1663 return UnspecifiedProgram, AttachNone, 0, ""
1664 }
1665
1666 // matchSectionName checks a section name against a pattern.
1667 //
1668 // It's behaviour mirrors that of libbpf's sec_def_matches.
1669 func matchSectionName(sectionName, pattern string) (extra string, found bool) {
1670 have, extra, found := strings.Cut(sectionName, "/")
1671 want := strings.TrimRight(pattern, "+/")
1672
1673 if strings.HasSuffix(pattern, "/") {
1674 // Section name must have a slash and extra may be empty.
1675 return extra, have == want && found
1676 } else if strings.HasSuffix(pattern, "+") {
1677 // Section name may have a slash and extra may be empty.
1678 return extra, have == want
1679 }
1680
1681 // Section name must have a prefix. extra is ignored.
1682 return "", strings.HasPrefix(sectionName, pattern)
1683 }
1684
1685 func (ec *elfCode) loadSectionRelocations(sec *elf.Section, symbols []elf.Symbol) (map[uint64]elf.Symbol, error) {
1686 rels := make(map[uint64]elf.Symbol)
1687
1688 if sec.Entsize < 16 {
1689 return nil, fmt.Errorf("section %s: relocations are less than 16 bytes", sec.Name)
1690 }
1691
1692 r := bufio.NewReader(sec.Open())
1693 for off := uint64(0); off < sec.Size; off += sec.Entsize {
1694 ent := io.LimitReader(r, int64(sec.Entsize))
1695
1696 var rel elf.Rel64
1697 if binary.Read(ent, ec.ByteOrder, &rel) != nil {
1698 return nil, fmt.Errorf("can't parse relocation at offset %v", off)
1699 }
1700
1701 symNo := int(elf.R_SYM64(rel.Info) - 1)
1702 if symNo >= len(symbols) {
1703 return nil, fmt.Errorf("offset %d: symbol %d doesn't exist", off, symNo)
1704 }
1705
1706 symbol := symbols[symNo]
1707 rels[rel.Off] = symbol
1708 }
1709
1710 return rels, nil
1711 }