Debian Codegraph @

btf/btf.go

raw symbols SCIP
1 package btf
2
3 import (
4 "debug/elf"
5 "errors"
6 "fmt"
7 "io"
8 "iter"
9 "maps"
10 "math"
11 "os"
12 "reflect"
13 "slices"
14
15 "github.com/cilium/ebpf/internal"
16 "github.com/cilium/ebpf/internal/sys"
17 )
18
19 const btfMagic = 0xeB9F
20
21 // Errors returned by BTF functions.
22 var (
23 ErrNotSupported = internal.ErrNotSupported
24 ErrNotFound = errors.New("not found")
25 ErrNoExtendedInfo = errors.New("no extended info")
26 ErrMultipleMatches = errors.New("multiple matching types")
27 )
28
29 // ID represents the unique ID of a BTF object.
30 type ID = sys.BTFID
31
32 type elfData struct {
33 sectionSizes map[string]uint32
34 symbolOffsets map[elfSymbol]uint32
35 fixups map[Type]bool
36 }
37
38 type elfSymbol struct {
39 section string
40 name string
41 }
42
43 // Spec allows querying a set of Types and loading the set into the
44 // kernel.
45 type Spec struct {
46 *decoder
47
48 // Additional data from ELF, may be nil.
49 elf *elfData
50 }
51
52 // LoadSpec opens file and calls LoadSpecFromReader on it.
53 func LoadSpec(file string) (*Spec, error) {
54 fh, err := os.Open(file)
55 if err != nil {
56 return nil, err
57 }
58 defer fh.Close()
59
60 return LoadSpecFromReader(fh)
61 }
62
63 // LoadSpecFromReader reads from an ELF or a raw BTF blob.
64 //
65 // Returns ErrNotFound if reading from an ELF which contains no BTF. ExtInfos
66 // may be nil.
67 func LoadSpecFromReader(rd io.ReaderAt) (*Spec, error) {
68 file, err := internal.NewSafeELFFile(rd)
69 if err != nil {
70 raw, err := io.ReadAll(io.NewSectionReader(rd, 0, math.MaxInt64))
71 if err != nil {
72 return nil, fmt.Errorf("read raw BTF: %w", err)
73 }
74
75 return loadRawSpec(raw, nil)
76 }
77
78 return loadSpecFromELF(file)
79 }
80
81 // LoadSpecAndExtInfosFromReader reads from an ELF.
82 //
83 // ExtInfos may be nil if the ELF doesn't contain section metadata.
84 // Returns ErrNotFound if the ELF contains no BTF.
85 func LoadSpecAndExtInfosFromReader(rd io.ReaderAt) (*Spec, *ExtInfos, error) {
86 file, err := internal.NewSafeELFFile(rd)
87 if err != nil {
88 return nil, nil, err
89 }
90
91 spec, err := loadSpecFromELF(file)
92 if err != nil {
93 return nil, nil, err
94 }
95
96 extInfos, err := loadExtInfosFromELF(file, spec)
97 if err != nil && !errors.Is(err, ErrNotFound) {
98 return nil, nil, err
99 }
100
101 return spec, extInfos, nil
102 }
103
104 // symbolOffsets extracts all symbols offsets from an ELF and indexes them by
105 // section and variable name.
106 //
107 // References to variables in BTF data sections carry unsigned 32-bit offsets.
108 // Some ELF symbols (e.g. in vmlinux) may point to virtual memory that is well
109 // beyond this range. Since these symbols cannot be described by BTF info,
110 // ignore them here.
111 func symbolOffsets(file *internal.SafeELFFile) (map[elfSymbol]uint32, error) {
112 symbols, err := file.Symbols()
113 if err != nil {
114 return nil, fmt.Errorf("can't read symbols: %v", err)
115 }
116
117 offsets := make(map[elfSymbol]uint32)
118 for _, sym := range symbols {
119 if idx := sym.Section; idx >= elf.SHN_LORESERVE && idx <= elf.SHN_HIRESERVE {
120 // Ignore things like SHN_ABS
121 continue
122 }
123
124 if sym.Value > math.MaxUint32 {
125 // VarSecinfo offset is u32, cannot reference symbols in higher regions.
126 continue
127 }
128
129 if int(sym.Section) >= len(file.Sections) {
130 return nil, fmt.Errorf("symbol %s: invalid section %d", sym.Name, sym.Section)
131 }
132
133 secName := file.Sections[sym.Section].Name
134 offsets[elfSymbol{secName, sym.Name}] = uint32(sym.Value)
135 }
136
137 return offsets, nil
138 }
139
140 func loadSpecFromELF(file *internal.SafeELFFile) (*Spec, error) {
141 var (
142 btfSection *elf.Section
143 sectionSizes = make(map[string]uint32)
144 )
145
146 for _, sec := range file.Sections {
147 switch sec.Name {
148 case ".BTF":
149 btfSection = sec
150 default:
151 if sec.Type != elf.SHT_PROGBITS && sec.Type != elf.SHT_NOBITS {
152 break
153 }
154
155 if sec.Size > math.MaxUint32 {
156 return nil, fmt.Errorf("section %s exceeds maximum size", sec.Name)
157 }
158
159 sectionSizes[sec.Name] = uint32(sec.Size)
160 }
161 }
162
163 if btfSection == nil {
164 return nil, fmt.Errorf("btf: %w", ErrNotFound)
165 }
166
167 offsets, err := symbolOffsets(file)
168 if err != nil {
169 return nil, err
170 }
171
172 rawBTF, err := btfSection.Data()
173 if err != nil {
174 return nil, fmt.Errorf("reading .BTF section: %w", err)
175 }
176
177 spec, err := loadRawSpec(rawBTF, nil)
178 if err != nil {
179 return nil, err
180 }
181
182 if spec.decoder.byteOrder != file.ByteOrder {
183 return nil, fmt.Errorf("BTF byte order %s does not match ELF byte order %s", spec.decoder.byteOrder, file.ByteOrder)
184 }
185
186 spec.elf = &elfData{
187 sectionSizes,
188 offsets,
189 make(map[Type]bool),
190 }
191
192 return spec, nil
193 }
194
195 func loadRawSpec(btf []byte, base *Spec) (*Spec, error) {
196 var (
197 baseDecoder *decoder
198 baseStrings *stringTable
199 err error
200 )
201
202 if base != nil {
203 baseDecoder = base.decoder
204 baseStrings = base.strings
205 }
206
207 header, _, bo, err := parseBTFHeader(btf)
208 if err != nil {
209 return nil, fmt.Errorf("parsing .BTF header: %v", err)
210 }
211
212 if header.HdrLen > uint32(len(btf)) {
213 return nil, fmt.Errorf("BTF header length is out of bounds")
214 }
215 btf = btf[header.HdrLen:]
216
217 if uint64(header.StringOff)+uint64(header.StringLen) > uint64(len(btf)) {
218 return nil, fmt.Errorf("string table is out of bounds")
219 }
220 stringsSection := btf[header.StringOff : header.StringOff+header.StringLen]
221
222 rawStrings, err := newStringTable(stringsSection, baseStrings)
223 if err != nil {
224 return nil, fmt.Errorf("read string section: %w", err)
225 }
226
227 if uint64(header.TypeOff)+uint64(header.TypeLen) > uint64(len(btf)) {
228 return nil, fmt.Errorf("types section is out of bounds")
229 }
230 typesSection := btf[header.TypeOff : header.TypeOff+header.TypeLen]
231
232 decoder, err := newDecoder(typesSection, bo, rawStrings, baseDecoder)
233 if err != nil {
234 return nil, err
235 }
236
237 return &Spec{decoder, nil}, nil
238 }
239
240 // fixupDatasec attempts to patch up missing info in Datasecs and its members by
241 // supplementing them with information from the ELF headers and symbol table.
242 func (elf *elfData) fixupDatasec(typ Type) error {
243 if elf == nil {
244 return nil
245 }
246
247 if ds, ok := typ.(*Datasec); ok {
248 if elf.fixups[ds] {
249 return nil
250 }
251 elf.fixups[ds] = true
252
253 name := ds.Name
254
255 // Some Datasecs are virtual and don't have corresponding ELF sections.
256 switch name {
257 case ".ksyms":
258 // .ksyms describes forward declarations of kfunc signatures, as well as
259 // references to kernel symbols.
260 // Nothing to fix up, all sizes and offsets are 0.
261 for _, vsi := range ds.Vars {
262 switch t := vsi.Type.(type) {
263 case *Func:
264 continue
265 case *Var:
266 if _, ok := t.Type.(*Void); !ok {
267 return fmt.Errorf("data section %s: expected %s to be *Void, not %T: %w", name, vsi.Type.TypeName(), vsi.Type, ErrNotSupported)
268 }
269 default:
270 return fmt.Errorf("data section %s: expected to be either *btf.Func or *btf.Var, not %T: %w", name, vsi.Type, ErrNotSupported)
271 }
272 }
273
274 return nil
275 case ".kconfig":
276 // .kconfig has a size of 0 and has all members' offsets set to 0.
277 // Fix up all offsets and set the Datasec's size.
278 if err := fixupDatasecLayout(ds); err != nil {
279 return err
280 }
281
282 // Fix up extern to global linkage to avoid a BTF verifier error.
283 for _, vsi := range ds.Vars {
284 vsi.Type.(*Var).Linkage = GlobalVar
285 }
286
287 return nil
288 }
289
290 if ds.Size != 0 {
291 return nil
292 }
293
294 ds.Size, ok = elf.sectionSizes[name]
295 if !ok {
296 return fmt.Errorf("data section %s: missing size", name)
297 }
298
299 for i := range ds.Vars {
300 symName := ds.Vars[i].Type.TypeName()
301 ds.Vars[i].Offset, ok = elf.symbolOffsets[elfSymbol{name, symName}]
302 if !ok {
303 return fmt.Errorf("data section %s: missing offset for symbol %s", name, symName)
304 }
305 }
306 }
307
308 return nil
309 }
310
311 // fixupDatasecLayout populates ds.Vars[].Offset according to var sizes and
312 // alignment. Calculate and set ds.Size.
313 func fixupDatasecLayout(ds *Datasec) error {
314 var off uint32
315
316 for i, vsi := range ds.Vars {
317 v, ok := vsi.Type.(*Var)
318 if !ok {
319 return fmt.Errorf("member %d: unsupported type %T", i, vsi.Type)
320 }
321
322 size, err := Sizeof(v.Type)
323 if err != nil {
324 return fmt.Errorf("variable %s: getting size: %w", v.Name, err)
325 }
326 align, err := alignof(v.Type)
327 if err != nil {
328 return fmt.Errorf("variable %s: getting alignment: %w", v.Name, err)
329 }
330
331 // Align the current member based on the offset of the end of the previous
332 // member and the alignment of the current member.
333 off = internal.Align(off, uint32(align))
334
335 ds.Vars[i].Offset = off
336
337 off += uint32(size)
338 }
339
340 ds.Size = off
341
342 return nil
343 }
344
345 // Copy a Spec.
346 //
347 // All contained types are duplicated while preserving any modifications made
348 // to them.
349 func (s *Spec) Copy() *Spec {
350 if s == nil {
351 return nil
352 }
353
354 cpy := &Spec{
355 s.decoder.Copy(),
356 nil,
357 }
358
359 if s.elf != nil {
360 cpy.elf = &elfData{
361 s.elf.sectionSizes,
362 s.elf.symbolOffsets,
363 maps.Clone(s.elf.fixups),
364 }
365 }
366
367 return cpy
368 }
369
370 // TypeByID returns the BTF Type with the given type ID.
371 //
372 // Returns an error wrapping ErrNotFound if a Type with the given ID
373 // does not exist in the Spec.
374 func (s *Spec) TypeByID(id TypeID) (Type, error) {
375 typ, err := s.decoder.TypeByID(id)
376 if err != nil {
377 return nil, fmt.Errorf("inflate type: %w", err)
378 }
379
380 if err := s.elf.fixupDatasec(typ); err != nil {
381 return nil, err
382 }
383
384 return typ, nil
385 }
386
387 // TypeID returns the ID for a given Type.
388 //
389 // Returns an error wrapping [ErrNotFound] if the type isn't part of the Spec.
390 func (s *Spec) TypeID(typ Type) (TypeID, error) {
391 return s.decoder.TypeID(typ)
392 }
393
394 // AnyTypesByName returns a list of BTF Types with the given name.
395 //
396 // If the BTF blob describes multiple compilation units like vmlinux, multiple
397 // Types with the same name and kind can exist, but might not describe the same
398 // data structure.
399 //
400 // Returns an error wrapping ErrNotFound if no matching Type exists in the Spec.
401 func (s *Spec) AnyTypesByName(name string) ([]Type, error) {
402 types, err := s.TypesByName(newEssentialName(name))
403 if err != nil {
404 return nil, err
405 }
406
407 for i := 0; i < len(types); i++ {
408 // Match against the full name, not just the essential one
409 // in case the type being looked up is a struct flavor.
410 if types[i].TypeName() != name {
411 types = slices.Delete(types, i, i+1)
412 continue
413 }
414
415 if err := s.elf.fixupDatasec(types[i]); err != nil {
416 return nil, err
417 }
418 }
419
420 return types, nil
421 }
422
423 // AnyTypeByName returns a Type with the given name.
424 //
425 // Returns an error if multiple types of that name exist.
426 func (s *Spec) AnyTypeByName(name string) (Type, error) {
427 types, err := s.AnyTypesByName(name)
428 if err != nil {
429 return nil, err
430 }
431
432 if len(types) > 1 {
433 return nil, fmt.Errorf("found multiple types: %v", types)
434 }
435
436 return types[0], nil
437 }
438
439 // TypeByName searches for a Type with a specific name. Since multiple Types
440 // with the same name can exist, the parameter typ is taken to narrow down the
441 // search in case of a clash.
442 //
443 // typ must be a non-nil pointer to an implementation of a Type. On success, the
444 // address of the found Type will be copied to typ.
445 //
446 // Returns an error wrapping ErrNotFound if no matching Type exists in the Spec.
447 // Returns an error wrapping ErrMultipleTypes if multiple candidates are found.
448 func (s *Spec) TypeByName(name string, typ any) error {
449 if err := internal.IsNilPointer(typ); err != nil {
450 return fmt.Errorf("type argument: %w", err)
451 }
452
453 typeInterface := reflect.TypeFor[Type]()
454
455 // typ may be **T or *Type
456 typValue := reflect.ValueOf(typ)
457 if typValue.Kind() != reflect.Pointer {
458 return fmt.Errorf("%T is not a pointer", typ)
459 }
460 typPtr := typValue.Elem()
461 if !typPtr.CanSet() {
462 return fmt.Errorf("%T cannot be set", typ)
463 }
464
465 wanted := typPtr.Type()
466 if wanted == typeInterface {
467 // This is *Type. Unwrap the value's type.
468 if typPtr.IsNil() {
469 return fmt.Errorf("%T points to a nil Type", typ)
470 }
471 wanted = typPtr.Elem().Type()
472 }
473
474 if !wanted.AssignableTo(typeInterface) {
475 return fmt.Errorf("%T does not satisfy Type interface", typ)
476 }
477
478 types, err := s.AnyTypesByName(name)
479 if err != nil {
480 return err
481 }
482
483 var candidate Type
484 for _, typ := range types {
485 if reflect.TypeOf(typ) != wanted {
486 continue
487 }
488
489 if candidate != nil {
490 return fmt.Errorf("type %s(%T): %w", name, typ, ErrMultipleMatches)
491 }
492
493 candidate = typ
494 }
495
496 if candidate == nil {
497 return fmt.Errorf("%s %s: %w", wanted, name, ErrNotFound)
498 }
499
500 typPtr.Set(reflect.ValueOf(candidate))
501
502 return nil
503 }
504
505 // LoadSplitSpec loads split BTF from the given file.
506 //
507 // Types from base are used to resolve references in the split BTF.
508 // The returned Spec only contains types from the split BTF, not from the base.
509 func LoadSplitSpec(file string, base *Spec) (*Spec, error) {
510 fh, err := os.Open(file)
511 if err != nil {
512 return nil, err
513 }
514 defer fh.Close()
515
516 return LoadSplitSpecFromReader(fh, base)
517 }
518
519 // LoadSplitSpecFromReader loads split BTF from a reader.
520 //
521 // Types from base are used to resolve references in the split BTF.
522 // The returned Spec only contains types from the split BTF, not from the base.
523 func LoadSplitSpecFromReader(r io.ReaderAt, base *Spec) (*Spec, error) {
524 raw, err := io.ReadAll(io.NewSectionReader(r, 0, math.MaxInt64))
525 if err != nil {
526 return nil, fmt.Errorf("read raw BTF: %w", err)
527 }
528
529 return loadRawSpec(raw, base)
530 }
531
532 // All iterates over all types.
533 func (s *Spec) All() iter.Seq2[Type, error] {
534 return func(yield func(Type, error) bool) {
535 for id := s.firstTypeID; ; id++ {
536 typ, err := s.TypeByID(id)
537 if errors.Is(err, ErrNotFound) {
538 return
539 } else if err != nil {
540 yield(nil, err)
541 return
542 }
543
544 // Skip declTags, during unmarshaling declTags become `Tags` fields of other types.
545 // We keep them in the spec to avoid holes in the ID space, but for the purposes of
546 // iteration, they are not useful to the user.
547 if _, ok := typ.(*declTag); ok {
548 continue
549 }
550
551 if !yield(typ, nil) {
552 return
553 }
554 }
555 }
556 }