Debian Codegraph @

btf/ext_info.go

raw symbols SCIP
1 package btf
2
3 import (
4 "bytes"
5 "encoding/binary"
6 "errors"
7 "fmt"
8 "io"
9 "math"
10 "sort"
11
12 "github.com/cilium/ebpf/asm"
13 "github.com/cilium/ebpf/internal"
14 )
15
16 // ExtInfos contains raw, per-section extended BTF metadata from the .BTF.ext
17 // ELF section.
18 type ExtInfos struct {
19 Funcs map[string]FuncOffsets
20 Lines map[string]LineOffsets
21 CORERelos map[string]CORERelocationOffsets
22 }
23
24 // Section returns the FuncOffsets, LineOffsets and CORERelocationOffsets for
25 // the given section name. Returns all nils if ExtInfos is nil, or individual
26 // nils if there is no metadata of that type for the section.
27 func (ei *ExtInfos) Section(name string) (FuncOffsets, LineOffsets, CORERelocationOffsets) {
28 if ei == nil {
29 return nil, nil, nil
30 }
31
32 return ei.Funcs[name], ei.Lines[name], ei.CORERelos[name]
33 }
34
35 // loadExtInfosFromELF parses ext infos from the .BTF.ext section in an ELF.
36 //
37 // Returns an error wrapping ErrNotFound if no ext infos are present.
38 func loadExtInfosFromELF(file *internal.SafeELFFile, spec *Spec) (*ExtInfos, error) {
39 section := file.Section(".BTF.ext")
40 if section == nil {
41 return nil, fmt.Errorf("btf ext infos: %w", ErrNotFound)
42 }
43
44 if section.ReaderAt == nil {
45 return nil, fmt.Errorf("compressed ext_info is not supported")
46 }
47
48 return loadExtInfos(section.ReaderAt, file.ByteOrder, spec)
49 }
50
51 // loadExtInfos parses bare ext infos.
52 func loadExtInfos(r io.ReaderAt, bo binary.ByteOrder, spec *Spec) (*ExtInfos, error) {
53 // Open unbuffered section reader. binary.Read() calls io.ReadFull on
54 // the header structs, resulting in one syscall per header.
55 headerRd := io.NewSectionReader(r, 0, math.MaxInt64)
56 extHeader, err := parseBTFExtHeader(headerRd, bo)
57 if err != nil {
58 return nil, fmt.Errorf("parsing BTF extension header: %w", err)
59 }
60
61 coreHeader, err := parseBTFExtCOREHeader(headerRd, bo, extHeader)
62 if err != nil {
63 return nil, fmt.Errorf("parsing BTF CO-RE header: %w", err)
64 }
65
66 buf := internal.NewBufferedSectionReader(r, extHeader.funcInfoStart(), int64(extHeader.FuncInfoLen))
67 btfFuncInfos, err := parseFuncInfos(buf, bo, spec.strings)
68 if err != nil {
69 return nil, fmt.Errorf("parsing BTF function info: %w", err)
70 }
71
72 funcInfos := make(map[string]FuncOffsets, len(btfFuncInfos))
73 for section, bfis := range btfFuncInfos {
74 funcInfos[section], err = newFuncOffsets(bfis, spec)
75 if err != nil {
76 return nil, fmt.Errorf("section %s: func infos: %w", section, err)
77 }
78 }
79
80 buf = internal.NewBufferedSectionReader(r, extHeader.lineInfoStart(), int64(extHeader.LineInfoLen))
81 btfLineInfos, err := parseLineInfos(buf, bo, spec.strings)
82 if err != nil {
83 return nil, fmt.Errorf("parsing BTF line info: %w", err)
84 }
85
86 lineInfos := make(map[string]LineOffsets, len(btfLineInfos))
87 for section, blis := range btfLineInfos {
88 lineInfos[section], err = newLineInfos(blis, spec.strings)
89 if err != nil {
90 return nil, fmt.Errorf("section %s: line infos: %w", section, err)
91 }
92 }
93
94 if coreHeader == nil || coreHeader.COREReloLen == 0 {
95 return &ExtInfos{funcInfos, lineInfos, nil}, nil
96 }
97
98 var btfCORERelos map[string][]bpfCORERelo
99 buf = internal.NewBufferedSectionReader(r, extHeader.coreReloStart(coreHeader), int64(coreHeader.COREReloLen))
100 btfCORERelos, err = parseCORERelos(buf, bo, spec.strings)
101 if err != nil {
102 return nil, fmt.Errorf("parsing CO-RE relocation info: %w", err)
103 }
104
105 coreRelos := make(map[string]CORERelocationOffsets, len(btfCORERelos))
106 for section, brs := range btfCORERelos {
107 coreRelos[section], err = newRelocationInfos(brs, spec, spec.strings)
108 if err != nil {
109 return nil, fmt.Errorf("section %s: CO-RE relocations: %w", section, err)
110 }
111 }
112
113 return &ExtInfos{funcInfos, lineInfos, coreRelos}, nil
114 }
115
116 // MarshalExtInfos encodes function and line info embedded in insns into kernel
117 // wire format.
118 //
119 // If an instruction has an [asm.Comment], it will be synthesized into a mostly
120 // empty line info.
121 func MarshalExtInfos(insns asm.Instructions, b *Builder) (funcInfos, lineInfos []byte, _ error) {
122 iter := insns.Iterate()
123 for iter.Next() {
124 if iter.Ins.Source() != nil || FuncMetadata(iter.Ins) != nil {
125 goto marshal
126 }
127 }
128
129 return nil, nil, nil
130
131 marshal:
132 var fiBuf, liBuf bytes.Buffer
133 for {
134 if fn := FuncMetadata(iter.Ins); fn != nil {
135 fi := &FuncOffset{
136 Func: fn,
137 Offset: iter.Offset,
138 }
139 if err := fi.marshal(&fiBuf, b); err != nil {
140 return nil, nil, fmt.Errorf("write func info: %w", err)
141 }
142 }
143
144 if source := iter.Ins.Source(); source != nil {
145 var line *Line
146 if l, ok := source.(*Line); ok {
147 line = l
148 } else {
149 line = &Line{
150 line: source.String(),
151 }
152 }
153
154 li := &LineOffset{
155 Offset: iter.Offset,
156 Line: line,
157 }
158 if err := li.marshal(&liBuf, b); err != nil {
159 return nil, nil, fmt.Errorf("write line info: %w", err)
160 }
161 }
162
163 if !iter.Next() {
164 break
165 }
166 }
167
168 return fiBuf.Bytes(), liBuf.Bytes(), nil
169 }
170
171 // btfExtHeader is found at the start of the .BTF.ext section.
172 type btfExtHeader struct {
173 Magic uint16
174 Version uint8
175 Flags uint8
176
177 // HdrLen is larger than the size of struct btfExtHeader when it is
178 // immediately followed by a btfExtCOREHeader.
179 HdrLen uint32
180
181 FuncInfoOff uint32
182 FuncInfoLen uint32
183 LineInfoOff uint32
184 LineInfoLen uint32
185 }
186
187 // parseBTFExtHeader parses the header of the .BTF.ext section.
188 func parseBTFExtHeader(r io.Reader, bo binary.ByteOrder) (*btfExtHeader, error) {
189 var header btfExtHeader
190 if err := binary.Read(r, bo, &header); err != nil {
191 return nil, fmt.Errorf("can't read header: %v", err)
192 }
193
194 if header.Magic != btfMagic {
195 return nil, fmt.Errorf("incorrect magic value %v", header.Magic)
196 }
197
198 if header.Version != 1 {
199 return nil, fmt.Errorf("unexpected version %v", header.Version)
200 }
201
202 if header.Flags != 0 {
203 return nil, fmt.Errorf("unsupported flags %v", header.Flags)
204 }
205
206 if int64(header.HdrLen) < int64(binary.Size(&header)) {
207 return nil, fmt.Errorf("header length shorter than btfExtHeader size")
208 }
209
210 return &header, nil
211 }
212
213 // funcInfoStart returns the offset from the beginning of the .BTF.ext section
214 // to the start of its func_info entries.
215 func (h *btfExtHeader) funcInfoStart() int64 {
216 return int64(h.HdrLen + h.FuncInfoOff)
217 }
218
219 // lineInfoStart returns the offset from the beginning of the .BTF.ext section
220 // to the start of its line_info entries.
221 func (h *btfExtHeader) lineInfoStart() int64 {
222 return int64(h.HdrLen + h.LineInfoOff)
223 }
224
225 // coreReloStart returns the offset from the beginning of the .BTF.ext section
226 // to the start of its CO-RE relocation entries.
227 func (h *btfExtHeader) coreReloStart(ch *btfExtCOREHeader) int64 {
228 return int64(h.HdrLen + ch.COREReloOff)
229 }
230
231 // btfExtCOREHeader is found right after the btfExtHeader when its HdrLen
232 // field is larger than its size.
233 type btfExtCOREHeader struct {
234 COREReloOff uint32
235 COREReloLen uint32
236 }
237
238 // parseBTFExtCOREHeader parses the tail of the .BTF.ext header. If additional
239 // header bytes are present, extHeader.HdrLen will be larger than the struct,
240 // indicating the presence of a CO-RE extension header.
241 func parseBTFExtCOREHeader(r io.Reader, bo binary.ByteOrder, extHeader *btfExtHeader) (*btfExtCOREHeader, error) {
242 extHdrSize := int64(binary.Size(&extHeader))
243 remainder := int64(extHeader.HdrLen) - extHdrSize
244
245 if remainder == 0 {
246 return nil, nil
247 }
248
249 var coreHeader btfExtCOREHeader
250 if err := binary.Read(r, bo, &coreHeader); err != nil {
251 return nil, fmt.Errorf("can't read header: %v", err)
252 }
253
254 return &coreHeader, nil
255 }
256
257 type btfExtInfoSec struct {
258 SecNameOff uint32
259 NumInfo uint32
260 }
261
262 // parseExtInfoSec parses a btf_ext_info_sec header within .BTF.ext,
263 // appearing within func_info and line_info sub-sections.
264 // These headers appear once for each program section in the ELF and are
265 // followed by one or more func/line_info records for the section.
266 func parseExtInfoSec(r io.Reader, bo binary.ByteOrder, strings *stringTable) (string, *btfExtInfoSec, error) {
267 var infoHeader btfExtInfoSec
268 if err := binary.Read(r, bo, &infoHeader); err != nil {
269 return "", nil, fmt.Errorf("read ext info header: %w", err)
270 }
271
272 secName, err := strings.Lookup(infoHeader.SecNameOff)
273 if err != nil {
274 return "", nil, fmt.Errorf("get section name: %w", err)
275 }
276 if secName == "" {
277 return "", nil, fmt.Errorf("extinfo header refers to empty section name")
278 }
279
280 if infoHeader.NumInfo == 0 {
281 return "", nil, fmt.Errorf("section %s has zero records", secName)
282 }
283
284 return secName, &infoHeader, nil
285 }
286
287 // parseExtInfoRecordSize parses the uint32 at the beginning of a func_infos
288 // or line_infos segment that describes the length of all extInfoRecords in
289 // that segment.
290 func parseExtInfoRecordSize(r io.Reader, bo binary.ByteOrder) (uint32, error) {
291 const maxRecordSize = 256
292
293 var recordSize uint32
294 if err := binary.Read(r, bo, &recordSize); err != nil {
295 return 0, fmt.Errorf("can't read record size: %v", err)
296 }
297
298 if recordSize < 4 {
299 // Need at least InsnOff worth of bytes per record.
300 return 0, errors.New("record size too short")
301 }
302 if recordSize > maxRecordSize {
303 return 0, fmt.Errorf("record size %v exceeds %v", recordSize, maxRecordSize)
304 }
305
306 return recordSize, nil
307 }
308
309 // FuncOffsets is a slice of FuncOffsets sorted by offset.
310 type FuncOffsets = []FuncOffset
311
312 // The size of a FuncInfo in BTF wire format.
313 var FuncInfoSize = uint32(binary.Size(bpfFuncInfo{}))
314
315 // FuncOffset represents a [btf.Func] and its raw instruction offset within a
316 // BPF program.
317 type FuncOffset struct {
318 Offset asm.RawInstructionOffset
319 Func *Func
320 }
321
322 type bpfFuncInfo struct {
323 // Instruction offset of the function within an ELF section.
324 InsnOff uint32
325 TypeID TypeID
326 }
327
328 func newFuncOffset(fi bpfFuncInfo, spec *Spec) (*FuncOffset, error) {
329 typ, err := spec.TypeByID(fi.TypeID)
330 if err != nil {
331 return nil, err
332 }
333
334 fn, ok := typ.(*Func)
335 if !ok {
336 return nil, fmt.Errorf("type ID %d is a %T, but expected a Func", fi.TypeID, typ)
337 }
338
339 // C doesn't have anonymous functions, but check just in case.
340 if fn.Name == "" {
341 return nil, fmt.Errorf("func with type ID %d doesn't have a name", fi.TypeID)
342 }
343
344 return &FuncOffset{
345 asm.RawInstructionOffset(fi.InsnOff),
346 fn,
347 }, nil
348 }
349
350 func newFuncOffsets(bfis []bpfFuncInfo, spec *Spec) (FuncOffsets, error) {
351 fos := make(FuncOffsets, 0, len(bfis))
352
353 for _, bfi := range bfis {
354 fi, err := newFuncOffset(bfi, spec)
355 if err != nil {
356 return FuncOffsets{}, fmt.Errorf("offset %d: %w", bfi.InsnOff, err)
357 }
358 fos = append(fos, *fi)
359 }
360 sort.Slice(fos, func(i, j int) bool {
361 return fos[i].Offset <= fos[j].Offset
362 })
363 return fos, nil
364 }
365
366 // LoadFuncInfos parses BTF func info from kernel wire format into a
367 // [FuncOffsets], a sorted slice of [btf.Func]s of (sub)programs within a BPF
368 // program with their corresponding raw instruction offsets.
369 func LoadFuncInfos(reader io.Reader, bo binary.ByteOrder, recordNum uint32, spec *Spec) (FuncOffsets, error) {
370 fis, err := parseFuncInfoRecords(
371 reader,
372 bo,
373 FuncInfoSize,
374 recordNum,
375 false,
376 )
377 if err != nil {
378 return FuncOffsets{}, fmt.Errorf("parsing BTF func info: %w", err)
379 }
380
381 return newFuncOffsets(fis, spec)
382 }
383
384 // marshal into the BTF wire format.
385 func (fi *FuncOffset) marshal(w *bytes.Buffer, b *Builder) error {
386 id, err := b.Add(fi.Func)
387 if err != nil {
388 return err
389 }
390 bfi := bpfFuncInfo{
391 InsnOff: uint32(fi.Offset),
392 TypeID: id,
393 }
394 buf := make([]byte, FuncInfoSize)
395 internal.NativeEndian.PutUint32(buf, bfi.InsnOff)
396 internal.NativeEndian.PutUint32(buf[4:], uint32(bfi.TypeID))
397 _, err = w.Write(buf)
398 return err
399 }
400
401 // parseFuncInfos parses a func_info sub-section within .BTF.ext ito a map of
402 // func infos indexed by section name.
403 func parseFuncInfos(r io.Reader, bo binary.ByteOrder, strings *stringTable) (map[string][]bpfFuncInfo, error) {
404 recordSize, err := parseExtInfoRecordSize(r, bo)
405 if err != nil {
406 return nil, err
407 }
408
409 result := make(map[string][]bpfFuncInfo)
410 for {
411 secName, infoHeader, err := parseExtInfoSec(r, bo, strings)
412 if errors.Is(err, io.EOF) {
413 return result, nil
414 }
415 if err != nil {
416 return nil, err
417 }
418
419 records, err := parseFuncInfoRecords(r, bo, recordSize, infoHeader.NumInfo, true)
420 if err != nil {
421 return nil, fmt.Errorf("section %v: %w", secName, err)
422 }
423
424 result[secName] = records
425 }
426 }
427
428 // parseFuncInfoRecords parses a stream of func_infos into a funcInfos.
429 // These records appear after a btf_ext_info_sec header in the func_info
430 // sub-section of .BTF.ext.
431 func parseFuncInfoRecords(r io.Reader, bo binary.ByteOrder, recordSize uint32, recordNum uint32, offsetInBytes bool) ([]bpfFuncInfo, error) {
432 var out []bpfFuncInfo
433 var fi bpfFuncInfo
434
435 if exp, got := FuncInfoSize, recordSize; exp != got {
436 // BTF blob's record size is longer than we know how to parse.
437 return nil, fmt.Errorf("expected FuncInfo record size %d, but BTF blob contains %d", exp, got)
438 }
439
440 for range recordNum {
441 if err := binary.Read(r, bo, &fi); err != nil {
442 return nil, fmt.Errorf("can't read function info: %v", err)
443 }
444
445 if offsetInBytes {
446 if fi.InsnOff%asm.InstructionSize != 0 {
447 return nil, fmt.Errorf("offset %v is not aligned with instruction size", fi.InsnOff)
448 }
449
450 // ELF tracks offset in bytes, the kernel expects raw BPF instructions.
451 // Convert as early as possible.
452 fi.InsnOff /= asm.InstructionSize
453 }
454
455 out = append(out, fi)
456 }
457
458 return out, nil
459 }
460
461 var LineInfoSize = uint32(binary.Size(bpfLineInfo{}))
462
463 // Line represents the location and contents of a single line of source
464 // code a BPF ELF was compiled from.
465 type Line struct {
466 fileName string
467 line string
468 lineNumber uint32
469 lineColumn uint32
470 }
471
472 func (li *Line) FileName() string {
473 return li.fileName
474 }
475
476 func (li *Line) Line() string {
477 return li.line
478 }
479
480 func (li *Line) LineNumber() uint32 {
481 return li.lineNumber
482 }
483
484 func (li *Line) LineColumn() uint32 {
485 return li.lineColumn
486 }
487
488 func (li *Line) String() string {
489 return li.line
490 }
491
492 // LineOffsets is a slice of LineOffsets sorted by offset.
493 type LineOffsets = []LineOffset
494
495 // LineOffset represents a line info and its raw instruction offset.
496 type LineOffset struct {
497 Offset asm.RawInstructionOffset
498 Line *Line
499 }
500
501 // Constants for the format of bpfLineInfo.LineCol.
502 const (
503 bpfLineShift = 10
504 bpfLineMax = (1 << (32 - bpfLineShift)) - 1
505 bpfColumnMax = (1 << bpfLineShift) - 1
506 )
507
508 type bpfLineInfo struct {
509 // Instruction offset of the line within the whole instruction stream, in instructions.
510 InsnOff uint32
511 FileNameOff uint32
512 LineOff uint32
513 LineCol uint32
514 }
515
516 // LoadLineInfos parses BTF line info in kernel wire format.
517 func LoadLineInfos(reader io.Reader, bo binary.ByteOrder, recordNum uint32, spec *Spec) (LineOffsets, error) {
518 lis, err := parseLineInfoRecords(
519 reader,
520 bo,
521 LineInfoSize,
522 recordNum,
523 false,
524 )
525 if err != nil {
526 return LineOffsets{}, fmt.Errorf("parsing BTF line info: %w", err)
527 }
528
529 return newLineInfos(lis, spec.strings)
530 }
531
532 func newLineInfo(li bpfLineInfo, strings *stringTable) (LineOffset, error) {
533 line, err := strings.LookupCached(li.LineOff)
534 if err != nil {
535 return LineOffset{}, fmt.Errorf("lookup of line: %w", err)
536 }
537
538 fileName, err := strings.LookupCached(li.FileNameOff)
539 if err != nil {
540 return LineOffset{}, fmt.Errorf("lookup of filename: %w", err)
541 }
542
543 lineNumber := li.LineCol >> bpfLineShift
544 lineColumn := li.LineCol & bpfColumnMax
545
546 return LineOffset{
547 asm.RawInstructionOffset(li.InsnOff),
548 &Line{
549 fileName,
550 line,
551 lineNumber,
552 lineColumn,
553 },
554 }, nil
555 }
556
557 func newLineInfos(blis []bpfLineInfo, strings *stringTable) (LineOffsets, error) {
558 lis := make([]LineOffset, 0, len(blis))
559 for _, bli := range blis {
560 li, err := newLineInfo(bli, strings)
561 if err != nil {
562 return LineOffsets{}, fmt.Errorf("offset %d: %w", bli.InsnOff, err)
563 }
564 lis = append(lis, li)
565 }
566 sort.Slice(lis, func(i, j int) bool {
567 return lis[i].Offset <= lis[j].Offset
568 })
569 return lis, nil
570 }
571
572 // marshal writes the binary representation of the LineInfo to w.
573 func (li *LineOffset) marshal(w *bytes.Buffer, b *Builder) error {
574 line := li.Line
575 if line.lineNumber > bpfLineMax {
576 return fmt.Errorf("line %d exceeds %d", line.lineNumber, bpfLineMax)
577 }
578
579 if line.lineColumn > bpfColumnMax {
580 return fmt.Errorf("column %d exceeds %d", line.lineColumn, bpfColumnMax)
581 }
582
583 fileNameOff, err := b.addString(line.fileName)
584 if err != nil {
585 return fmt.Errorf("file name %q: %w", line.fileName, err)
586 }
587
588 lineOff, err := b.addString(line.line)
589 if err != nil {
590 return fmt.Errorf("line %q: %w", line.line, err)
591 }
592
593 bli := bpfLineInfo{
594 uint32(li.Offset),
595 fileNameOff,
596 lineOff,
597 (line.lineNumber << bpfLineShift) | line.lineColumn,
598 }
599
600 buf := make([]byte, LineInfoSize)
601 internal.NativeEndian.PutUint32(buf, bli.InsnOff)
602 internal.NativeEndian.PutUint32(buf[4:], bli.FileNameOff)
603 internal.NativeEndian.PutUint32(buf[8:], bli.LineOff)
604 internal.NativeEndian.PutUint32(buf[12:], bli.LineCol)
605 _, err = w.Write(buf)
606 return err
607 }
608
609 // parseLineInfos parses a line_info sub-section within .BTF.ext ito a map of
610 // line infos indexed by section name.
611 func parseLineInfos(r io.Reader, bo binary.ByteOrder, strings *stringTable) (map[string][]bpfLineInfo, error) {
612 recordSize, err := parseExtInfoRecordSize(r, bo)
613 if err != nil {
614 return nil, err
615 }
616
617 result := make(map[string][]bpfLineInfo)
618 for {
619 secName, infoHeader, err := parseExtInfoSec(r, bo, strings)
620 if errors.Is(err, io.EOF) {
621 return result, nil
622 }
623 if err != nil {
624 return nil, err
625 }
626
627 records, err := parseLineInfoRecords(r, bo, recordSize, infoHeader.NumInfo, true)
628 if err != nil {
629 return nil, fmt.Errorf("section %v: %w", secName, err)
630 }
631
632 result[secName] = records
633 }
634 }
635
636 // parseLineInfoRecords parses a stream of line_infos into a lineInfos.
637 // These records appear after a btf_ext_info_sec header in the line_info
638 // sub-section of .BTF.ext.
639 func parseLineInfoRecords(r io.Reader, bo binary.ByteOrder, recordSize uint32, recordNum uint32, offsetInBytes bool) ([]bpfLineInfo, error) {
640 if exp, got := uint32(binary.Size(bpfLineInfo{})), recordSize; exp != got {
641 // BTF blob's record size is longer than we know how to parse.
642 return nil, fmt.Errorf("expected LineInfo record size %d, but BTF blob contains %d", exp, got)
643 }
644
645 out := make([]bpfLineInfo, 0)
646 chunk := make([]bpfLineInfo, min(1024, recordNum))
647 for remaining := recordNum; remaining > 0; {
648 n := min(uint32(1024), remaining)
649 if err := binary.Read(r, bo, chunk[:n]); err != nil {
650 return nil, fmt.Errorf("can't read line info: %v", err)
651 }
652 out = append(out, chunk[:n]...)
653 remaining -= n
654 }
655
656 if offsetInBytes {
657 for i := range out {
658 li := &out[i]
659 if li.InsnOff%asm.InstructionSize != 0 {
660 return nil, fmt.Errorf("offset %v is not aligned with instruction size", li.InsnOff)
661 }
662
663 // ELF tracks offset in bytes, the kernel expects raw BPF instructions.
664 // Convert as early as possible.
665 li.InsnOff /= asm.InstructionSize
666 }
667 }
668
669 return out, nil
670 }
671
672 // bpfCORERelo matches the kernel's struct bpf_core_relo.
673 type bpfCORERelo struct {
674 InsnOff uint32
675 TypeID TypeID
676 AccessStrOff uint32
677 Kind coreKind
678 }
679
680 type CORERelocation struct {
681 // The local type of the relocation, stripped of typedefs and qualifiers.
682 typ Type
683 accessor coreAccessor
684 kind coreKind
685 // The ID of the local type in the source BTF.
686 id TypeID
687 }
688
689 func (cr *CORERelocation) String() string {
690 return fmt.Sprintf("CORERelocation(%s, %s[%s], local_id=%d)", cr.kind, cr.typ, cr.accessor, cr.id)
691 }
692
693 type coreRelocationMeta struct{}
694
695 // CORERelocationMetadata returns the CORERelocation associated with ins.
696 func CORERelocationMetadata(ins *asm.Instruction) *CORERelocation {
697 relo, _ := ins.Metadata.Get(coreRelocationMeta{}).(*CORERelocation)
698 return relo
699 }
700
701 // WithCORERelocationMetadata associates a CORERelocation with ins and returns
702 // the modified Instruction.
703 func WithCORERelocationMetadata(ins asm.Instruction, relo *CORERelocation) asm.Instruction {
704 ins.Metadata.Set(coreRelocationMeta{}, relo)
705 return ins
706 }
707
708 // CORERelocationOffsets is a slice of CORERelocationOffsets sorted by offset.
709 type CORERelocationOffsets = []CORERelocationOffset
710
711 // CORERelocationOffset represents a CO-RE relocation and an offset at which it
712 // should be applied.
713 type CORERelocationOffset struct {
714 Relo *CORERelocation
715 Offset asm.RawInstructionOffset
716 }
717
718 func newRelocationInfo(relo bpfCORERelo, spec *Spec, strings *stringTable) (*CORERelocationOffset, error) {
719 typ, err := spec.TypeByID(relo.TypeID)
720 if err != nil {
721 return nil, err
722 }
723
724 accessorStr, err := strings.Lookup(relo.AccessStrOff)
725 if err != nil {
726 return nil, err
727 }
728
729 accessor, err := parseCOREAccessor(accessorStr)
730 if err != nil {
731 return nil, fmt.Errorf("accessor %q: %s", accessorStr, err)
732 }
733
734 return &CORERelocationOffset{
735 &CORERelocation{
736 typ,
737 accessor,
738 relo.Kind,
739 relo.TypeID,
740 },
741 asm.RawInstructionOffset(relo.InsnOff),
742 }, nil
743 }
744
745 func newRelocationInfos(brs []bpfCORERelo, spec *Spec, strings *stringTable) (CORERelocationOffsets, error) {
746 rs := make(CORERelocationOffsets, 0, len(brs))
747
748 for _, br := range brs {
749 relo, err := newRelocationInfo(br, spec, strings)
750 if err != nil {
751 return nil, fmt.Errorf("offset %d: %w", br.InsnOff, err)
752 }
753 rs = append(rs, *relo)
754 }
755
756 sort.Slice(rs, func(i, j int) bool {
757 return rs[i].Offset < rs[j].Offset
758 })
759
760 return rs, nil
761 }
762
763 var extInfoReloSize = binary.Size(bpfCORERelo{})
764
765 // parseCORERelos parses a core_relos sub-section within .BTF.ext ito a map of
766 // CO-RE relocations indexed by section name.
767 func parseCORERelos(r io.Reader, bo binary.ByteOrder, strings *stringTable) (map[string][]bpfCORERelo, error) {
768 recordSize, err := parseExtInfoRecordSize(r, bo)
769 if err != nil {
770 return nil, err
771 }
772
773 if recordSize != uint32(extInfoReloSize) {
774 return nil, fmt.Errorf("expected record size %d, got %d", extInfoReloSize, recordSize)
775 }
776
777 result := make(map[string][]bpfCORERelo)
778 for {
779 secName, infoHeader, err := parseExtInfoSec(r, bo, strings)
780 if errors.Is(err, io.EOF) {
781 return result, nil
782 }
783 if err != nil {
784 return nil, err
785 }
786
787 records, err := parseCOREReloRecords(r, bo, infoHeader.NumInfo)
788 if err != nil {
789 return nil, fmt.Errorf("section %v: %w", secName, err)
790 }
791
792 result[secName] = records
793 }
794 }
795
796 // parseCOREReloRecords parses a stream of CO-RE relocation entries into a
797 // coreRelos. These records appear after a btf_ext_info_sec header in the
798 // core_relos sub-section of .BTF.ext.
799 func parseCOREReloRecords(r io.Reader, bo binary.ByteOrder, recordNum uint32) ([]bpfCORERelo, error) {
800 var out []bpfCORERelo
801
802 var relo bpfCORERelo
803 for range recordNum {
804 if err := binary.Read(r, bo, &relo); err != nil {
805 return nil, fmt.Errorf("can't read CO-RE relocation: %v", err)
806 }
807
808 if relo.InsnOff%asm.InstructionSize != 0 {
809 return nil, fmt.Errorf("offset %v is not aligned with instruction size", relo.InsnOff)
810 }
811
812 // ELF tracks offset in bytes, the kernel expects raw BPF instructions.
813 // Convert as early as possible.
814 relo.InsnOff /= asm.InstructionSize
815
816 out = append(out, relo)
817 }
818
819 return out, nil
820 }