Debian Codegraph @

btf/core.go

raw symbols SCIP
1 package btf
2
3 import (
4 "encoding/binary"
5 "errors"
6 "fmt"
7 "math"
8 "reflect"
9 "strconv"
10 "strings"
11
12 "github.com/cilium/ebpf/asm"
13 "github.com/cilium/ebpf/internal"
14 "github.com/cilium/ebpf/internal/platform"
15 )
16
17 // Code in this file is derived from libbpf, which is available under a BSD
18 // 2-Clause license.
19
20 // A constant used when CO-RE relocation has to remove instructions.
21 //
22 // Taken from libbpf.
23 const COREBadRelocationSentinel = 0xbad2310
24
25 // COREFixup is the result of computing a CO-RE relocation for a target.
26 type COREFixup struct {
27 kind coreKind
28 local uint64
29 target uint64
30 // True if there is no valid fixup. The instruction is replaced with an
31 // invalid dummy.
32 poison bool
33 // True if the validation of the local value should be skipped. Used by
34 // some kinds of bitfield relocations.
35 skipLocalValidation bool
36 }
37
38 func (f *COREFixup) equal(other COREFixup) bool {
39 return f.local == other.local && f.target == other.target
40 }
41
42 func (f *COREFixup) String() string {
43 if f.poison {
44 return fmt.Sprintf("%s=poison", f.kind)
45 }
46 return fmt.Sprintf("%s=%d->%d", f.kind, f.local, f.target)
47 }
48
49 func (f *COREFixup) Apply(ins *asm.Instruction) error {
50 if !platform.IsLinux {
51 return fmt.Errorf("CO-RE fixup: %w", internal.ErrNotSupportedOnOS)
52 }
53
54 if f.poison {
55 // Relocation is poisoned, replace the instruction with an invalid one.
56 if ins.OpCode.IsDWordLoad() {
57 // Replace a dword load with a invalid dword load to preserve instruction size.
58 *ins = asm.LoadImm(asm.R10, COREBadRelocationSentinel, asm.DWord)
59 } else {
60 // Replace all single size instruction with a invalid call instruction.
61 *ins = asm.BuiltinFunc(COREBadRelocationSentinel).Call()
62 }
63
64 // Add context to the kernel verifier output.
65 if source := ins.Source(); source != nil {
66 *ins = ins.WithSource(asm.Comment(fmt.Sprintf("instruction poisoned by CO-RE: %s", source)))
67 } else {
68 *ins = ins.WithSource(asm.Comment("instruction poisoned by CO-RE"))
69 }
70
71 return nil
72 }
73
74 switch class := ins.OpCode.Class(); class {
75 case asm.LdXClass, asm.StClass, asm.StXClass:
76 if want := int16(f.local); !f.skipLocalValidation && want != ins.Offset {
77 return fmt.Errorf("invalid offset %d, expected %d", ins.Offset, f.local)
78 }
79
80 if f.target > math.MaxInt16 {
81 return fmt.Errorf("offset %d exceeds MaxInt16", f.target)
82 }
83
84 ins.Offset = int16(f.target)
85
86 case asm.LdClass:
87 if !ins.IsConstantLoad(asm.DWord) {
88 return fmt.Errorf("not a dword-sized immediate load")
89 }
90
91 if want := int64(f.local); !f.skipLocalValidation && want != ins.Constant {
92 return fmt.Errorf("invalid immediate %d, expected %d (fixup: %v)", ins.Constant, want, f)
93 }
94
95 ins.Constant = int64(f.target)
96
97 case asm.ALUClass:
98 if ins.OpCode.ALUOp() == asm.Swap {
99 return fmt.Errorf("relocation against swap")
100 }
101
102 fallthrough
103
104 case asm.ALU64Class:
105 if src := ins.OpCode.Source(); src != asm.ImmSource {
106 return fmt.Errorf("invalid source %s", src)
107 }
108
109 if want := int64(f.local); !f.skipLocalValidation && want != ins.Constant {
110 return fmt.Errorf("invalid immediate %d, expected %d (fixup: %v, kind: %v, ins: %v)", ins.Constant, want, f, f.kind, ins)
111 }
112
113 if f.target > math.MaxInt32 {
114 return fmt.Errorf("immediate %d exceeds MaxInt32", f.target)
115 }
116
117 ins.Constant = int64(f.target)
118
119 default:
120 return fmt.Errorf("invalid class %s", class)
121 }
122
123 return nil
124 }
125
126 func (f COREFixup) isNonExistant() bool {
127 return f.kind.checksForExistence() && f.target == 0
128 }
129
130 // coreKind is the type of CO-RE relocation as specified in BPF source code.
131 type coreKind uint32
132
133 const (
134 reloFieldByteOffset coreKind = iota /* field byte offset */
135 reloFieldByteSize /* field size in bytes */
136 reloFieldExists /* field existence in target kernel */
137 reloFieldSigned /* field signedness (0 - unsigned, 1 - signed) */
138 reloFieldLShiftU64 /* bitfield-specific left bitshift */
139 reloFieldRShiftU64 /* bitfield-specific right bitshift */
140 reloTypeIDLocal /* type ID in local BPF object */
141 reloTypeIDTarget /* type ID in target kernel */
142 reloTypeExists /* type existence in target kernel */
143 reloTypeSize /* type size in bytes */
144 reloEnumvalExists /* enum value existence in target kernel */
145 reloEnumvalValue /* enum value integer value */
146 reloTypeMatches /* type matches kernel type */
147 )
148
149 func (k coreKind) checksForExistence() bool {
150 return k == reloEnumvalExists || k == reloTypeExists || k == reloFieldExists || k == reloTypeMatches
151 }
152
153 func (k coreKind) String() string {
154 switch k {
155 case reloFieldByteOffset:
156 return "byte_off"
157 case reloFieldByteSize:
158 return "byte_sz"
159 case reloFieldExists:
160 return "field_exists"
161 case reloFieldSigned:
162 return "signed"
163 case reloFieldLShiftU64:
164 return "lshift_u64"
165 case reloFieldRShiftU64:
166 return "rshift_u64"
167 case reloTypeIDLocal:
168 return "local_type_id"
169 case reloTypeIDTarget:
170 return "target_type_id"
171 case reloTypeExists:
172 return "type_exists"
173 case reloTypeSize:
174 return "type_size"
175 case reloEnumvalExists:
176 return "enumval_exists"
177 case reloEnumvalValue:
178 return "enumval_value"
179 case reloTypeMatches:
180 return "type_matches"
181 default:
182 return fmt.Sprintf("unknown (%d)", k)
183 }
184 }
185
186 // CORERelocate calculates changes needed to adjust eBPF instructions for differences
187 // in types.
188 //
189 // targets forms the set of types to relocate against. The first element has to be
190 // BTF for vmlinux, the following must be types for kernel modules.
191 //
192 // resolveLocalTypeID is called for each local type which requires a stable TypeID.
193 // Calling the function with the same type multiple times must produce the same
194 // result. It is the callers responsibility to ensure that the relocated instructions
195 // are loaded with matching BTF.
196 //
197 // Returns a list of fixups which can be applied to instructions to make them
198 // match the target type(s).
199 //
200 // Fixups are returned in the order of relos, e.g. fixup[i] is the solution
201 // for relos[i].
202 func CORERelocate(relos []*CORERelocation, targets []*Spec, bo binary.ByteOrder, resolveLocalTypeID func(Type) (TypeID, error)) ([]COREFixup, error) {
203 if len(targets) == 0 {
204 // Explicitly check for nil here since the argument used to be optional.
205 return nil, fmt.Errorf("targets must be provided")
206 }
207
208 // We can't encode type IDs that aren't for vmlinux into instructions at the
209 // moment.
210 resolveTargetTypeID := targets[0].TypeID
211
212 for _, target := range targets {
213 if bo != target.byteOrder {
214 return nil, fmt.Errorf("can't relocate %s against %s", bo, target.byteOrder)
215 }
216 }
217
218 type reloGroup struct {
219 relos []*CORERelocation
220 // Position of each relocation in relos.
221 indices []int
222 }
223
224 // Split relocations into per Type lists.
225 relosByType := make(map[Type]*reloGroup)
226 result := make([]COREFixup, len(relos))
227 for i, relo := range relos {
228 if relo.kind == reloTypeIDLocal {
229 // Filtering out reloTypeIDLocal here makes our lives a lot easier
230 // down the line, since it doesn't have a target at all.
231 if len(relo.accessor) > 1 || relo.accessor[0] != 0 {
232 return nil, fmt.Errorf("%s: unexpected accessor %v", relo.kind, relo.accessor)
233 }
234
235 id, err := resolveLocalTypeID(relo.typ)
236 if err != nil {
237 return nil, fmt.Errorf("%s: get type id: %w", relo.kind, err)
238 }
239
240 result[i] = COREFixup{
241 kind: relo.kind,
242 local: uint64(relo.id),
243 target: uint64(id),
244 }
245 continue
246 }
247
248 group, ok := relosByType[relo.typ]
249 if !ok {
250 group = &reloGroup{}
251 relosByType[relo.typ] = group
252 }
253 group.relos = append(group.relos, relo)
254 group.indices = append(group.indices, i)
255 }
256
257 for localType, group := range relosByType {
258 localTypeName := localType.TypeName()
259 if localTypeName == "" {
260 return nil, fmt.Errorf("relocate unnamed or anonymous type %s: %w", localType, ErrNotSupported)
261 }
262
263 essentialName := newEssentialName(localTypeName)
264
265 var targetTypes []Type
266 for _, target := range targets {
267 namedTypes, err := target.TypesByName(essentialName)
268 if errors.Is(err, ErrNotFound) {
269 continue
270 } else if err != nil {
271 return nil, err
272 }
273
274 targetTypes = append(targetTypes, namedTypes...)
275 }
276
277 fixups, err := coreCalculateFixups(group.relos, targetTypes, bo, resolveTargetTypeID)
278 if err != nil {
279 return nil, fmt.Errorf("relocate %s: %w", localType, err)
280 }
281
282 for j, index := range group.indices {
283 result[index] = fixups[j]
284 }
285 }
286
287 return result, nil
288 }
289
290 var errAmbiguousRelocation = errors.New("ambiguous relocation")
291 var errImpossibleRelocation = errors.New("impossible relocation")
292 var errIncompatibleTypes = errors.New("incompatible types")
293
294 // coreCalculateFixups finds the target type that best matches all relocations.
295 //
296 // All relos must target the same type.
297 //
298 // The best target is determined by scoring: the less poisoning we have to do
299 // the better the target is.
300 func coreCalculateFixups(relos []*CORERelocation, targets []Type, bo binary.ByteOrder, resolveTargetTypeID func(Type) (TypeID, error)) ([]COREFixup, error) {
301 bestScore := len(relos)
302 var bestFixups []COREFixup
303 for _, target := range targets {
304 score := 0 // lower is better
305 fixups := make([]COREFixup, 0, len(relos))
306 for _, relo := range relos {
307 fixup, err := coreCalculateFixup(relo, target, bo, resolveTargetTypeID)
308 if err != nil {
309 return nil, fmt.Errorf("target %s: %s: %w", target, relo.kind, err)
310 }
311 if fixup.poison || fixup.isNonExistant() {
312 score++
313 }
314 fixups = append(fixups, fixup)
315 }
316
317 if score > bestScore {
318 // We have a better target already, ignore this one.
319 continue
320 }
321
322 if score < bestScore {
323 // This is the best target yet, use it.
324 bestScore = score
325 bestFixups = fixups
326 continue
327 }
328
329 // Some other target has the same score as the current one. Make sure
330 // the fixups agree with each other.
331 for i, fixup := range bestFixups {
332 if !fixup.equal(fixups[i]) {
333 return nil, fmt.Errorf("%s: multiple types match: %w", fixup.kind, errAmbiguousRelocation)
334 }
335 }
336 }
337
338 if bestFixups == nil {
339 // Nothing at all matched, probably because there are no suitable
340 // targets at all.
341 //
342 // Poison everything except checksForExistence.
343 bestFixups = make([]COREFixup, len(relos))
344 for i, relo := range relos {
345 if relo.kind.checksForExistence() {
346 bestFixups[i] = COREFixup{kind: relo.kind, local: 1, target: 0}
347 } else {
348 bestFixups[i] = COREFixup{kind: relo.kind, poison: true}
349 }
350 }
351 }
352
353 return bestFixups, nil
354 }
355
356 var errNoSignedness = errors.New("no signedness")
357
358 // coreCalculateFixup calculates the fixup given a relocation and a target type.
359 func coreCalculateFixup(relo *CORERelocation, target Type, bo binary.ByteOrder, resolveTargetTypeID func(Type) (TypeID, error)) (COREFixup, error) {
360 fixup := func(local, target uint64) (COREFixup, error) {
361 return COREFixup{kind: relo.kind, local: local, target: target}, nil
362 }
363 fixupWithoutValidation := func(local, target uint64) (COREFixup, error) {
364 return COREFixup{kind: relo.kind, local: local, target: target, skipLocalValidation: true}, nil
365 }
366 poison := func() (COREFixup, error) {
367 if relo.kind.checksForExistence() {
368 return fixup(1, 0)
369 }
370 return COREFixup{kind: relo.kind, poison: true}, nil
371 }
372 zero := COREFixup{}
373
374 local := relo.typ
375
376 switch relo.kind {
377 case reloTypeMatches:
378 if len(relo.accessor) > 1 || relo.accessor[0] != 0 {
379 return zero, fmt.Errorf("unexpected accessor %v", relo.accessor)
380 }
381
382 err := coreTypesMatch(local, target, nil)
383 if errors.Is(err, errIncompatibleTypes) {
384 return poison()
385 }
386 if err != nil {
387 return zero, err
388 }
389
390 return fixup(1, 1)
391
392 case reloTypeIDTarget, reloTypeSize, reloTypeExists:
393 if len(relo.accessor) > 1 || relo.accessor[0] != 0 {
394 return zero, fmt.Errorf("unexpected accessor %v", relo.accessor)
395 }
396
397 err := CheckTypeCompatibility(local, target)
398 if errors.Is(err, errIncompatibleTypes) {
399 return poison()
400 }
401 if err != nil {
402 return zero, err
403 }
404
405 switch relo.kind {
406 case reloTypeExists:
407 return fixup(1, 1)
408
409 case reloTypeIDTarget:
410 targetID, err := resolveTargetTypeID(target)
411 if errors.Is(err, ErrNotFound) {
412 // Probably a relocation trying to get the ID
413 // of a type from a kmod.
414 return poison()
415 }
416 if err != nil {
417 return zero, err
418 }
419 return fixup(uint64(relo.id), uint64(targetID))
420
421 case reloTypeSize:
422 localSize, err := Sizeof(local)
423 if err != nil {
424 return zero, err
425 }
426
427 targetSize, err := Sizeof(target)
428 if err != nil {
429 return zero, err
430 }
431
432 return fixup(uint64(localSize), uint64(targetSize))
433 }
434
435 case reloEnumvalValue, reloEnumvalExists:
436 localValue, targetValue, err := coreFindEnumValue(local, relo.accessor, target)
437 if errors.Is(err, errImpossibleRelocation) {
438 return poison()
439 }
440 if err != nil {
441 return zero, err
442 }
443
444 switch relo.kind {
445 case reloEnumvalExists:
446 return fixup(1, 1)
447
448 case reloEnumvalValue:
449 return fixup(localValue.Value, targetValue.Value)
450 }
451
452 case reloFieldByteOffset, reloFieldByteSize, reloFieldExists, reloFieldLShiftU64, reloFieldRShiftU64, reloFieldSigned:
453 if _, ok := As[*Fwd](target); ok {
454 // We can't relocate fields using a forward declaration, so
455 // skip it. If a non-forward declaration is present in the BTF
456 // we'll find it in one of the other iterations.
457 return poison()
458 }
459
460 localField, targetField, err := coreFindField(local, relo.accessor, target)
461 if errors.Is(err, errImpossibleRelocation) {
462 return poison()
463 }
464 if err != nil {
465 return zero, err
466 }
467
468 maybeSkipValidation := func(f COREFixup, err error) (COREFixup, error) {
469 f.skipLocalValidation = localField.bitfieldSize > 0
470 return f, err
471 }
472
473 switch relo.kind {
474 case reloFieldExists:
475 return fixup(1, 1)
476
477 case reloFieldByteOffset:
478 return maybeSkipValidation(fixup(uint64(localField.offset), uint64(targetField.offset)))
479
480 case reloFieldByteSize:
481 localSize, err := Sizeof(localField.Type)
482 if err != nil {
483 return zero, err
484 }
485
486 targetSize, err := Sizeof(targetField.Type)
487 if err != nil {
488 return zero, err
489 }
490 return maybeSkipValidation(fixup(uint64(localSize), uint64(targetSize)))
491
492 case reloFieldLShiftU64:
493 var target uint64
494 if bo == binary.LittleEndian {
495 targetSize, err := targetField.sizeBits()
496 if err != nil {
497 return zero, err
498 }
499
500 target = uint64(64 - targetField.bitfieldOffset - targetSize)
501 } else {
502 loadWidth, err := Sizeof(targetField.Type)
503 if err != nil {
504 return zero, err
505 }
506
507 target = uint64(64 - Bits(loadWidth*8) + targetField.bitfieldOffset)
508 }
509 return fixupWithoutValidation(0, target)
510
511 case reloFieldRShiftU64:
512 targetSize, err := targetField.sizeBits()
513 if err != nil {
514 return zero, err
515 }
516
517 return fixupWithoutValidation(0, uint64(64-targetSize))
518
519 case reloFieldSigned:
520 switch local := UnderlyingType(localField.Type).(type) {
521 case *Enum:
522 target, ok := As[*Enum](targetField.Type)
523 if !ok {
524 return zero, fmt.Errorf("target isn't *Enum but %T", targetField.Type)
525 }
526
527 return fixup(boolToUint64(local.Signed), boolToUint64(target.Signed))
528 case *Int:
529 target, ok := As[*Int](targetField.Type)
530 if !ok {
531 return zero, fmt.Errorf("target isn't *Int but %T", targetField.Type)
532 }
533
534 return fixup(
535 uint64(local.Encoding&Signed),
536 uint64(target.Encoding&Signed),
537 )
538 default:
539 return zero, fmt.Errorf("type %T: %w", local, errNoSignedness)
540 }
541 }
542 }
543
544 return zero, ErrNotSupported
545 }
546
547 func boolToUint64(val bool) uint64 {
548 if val {
549 return 1
550 }
551 return 0
552 }
553
554 /* coreAccessor contains a path through a struct. It contains at least one index.
555 *
556 * The interpretation depends on the kind of the relocation. The following is
557 * taken from struct bpf_core_relo in libbpf_internal.h:
558 *
559 * - for field-based relocations, string encodes an accessed field using
560 * a sequence of field and array indices, separated by colon (:). It's
561 * conceptually very close to LLVM's getelementptr ([0]) instruction's
562 * arguments for identifying offset to a field.
563 * - for type-based relocations, strings is expected to be just "0";
564 * - for enum value-based relocations, string contains an index of enum
565 * value within its enum type;
566 *
567 * Example to provide a better feel.
568 *
569 * struct sample {
570 * int a;
571 * struct {
572 * int b[10];
573 * };
574 * };
575 *
576 * struct sample s = ...;
577 * int x = &s->a; // encoded as "0:0" (a is field #0)
578 * int y = &s->b[5]; // encoded as "0:1:0:5" (anon struct is field #1,
579 * // b is field #0 inside anon struct, accessing elem #5)
580 * int z = &s[10]->b; // encoded as "10:1" (ptr is used as an array)
581 */
582 type coreAccessor []int
583
584 func parseCOREAccessor(accessor string) (coreAccessor, error) {
585 if accessor == "" {
586 return nil, fmt.Errorf("empty accessor")
587 }
588
589 parts := strings.Split(accessor, ":")
590 result := make(coreAccessor, 0, len(parts))
591 for _, part := range parts {
592 // 31 bits to avoid overflowing int on 32 bit platforms.
593 index, err := strconv.ParseUint(part, 10, 31)
594 if err != nil {
595 return nil, fmt.Errorf("accessor index %q: %s", part, err)
596 }
597
598 result = append(result, int(index))
599 }
600
601 return result, nil
602 }
603
604 func (ca coreAccessor) String() string {
605 strs := make([]string, 0, len(ca))
606 for _, i := range ca {
607 strs = append(strs, strconv.Itoa(i))
608 }
609 return strings.Join(strs, ":")
610 }
611
612 func (ca coreAccessor) enumValue(t Type) (*EnumValue, error) {
613 e, ok := As[*Enum](t)
614 if !ok {
615 return nil, fmt.Errorf("not an enum: %s", t)
616 }
617
618 if len(ca) > 1 {
619 return nil, fmt.Errorf("invalid accessor %s for enum", ca)
620 }
621
622 i := ca[0]
623 if i >= len(e.Values) {
624 return nil, fmt.Errorf("invalid index %d for %s", i, e)
625 }
626
627 return &e.Values[i], nil
628 }
629
630 // coreField represents the position of a "child" of a composite type from the
631 // start of that type.
632 //
633 // /- start of composite
634 // | offset * 8 | bitfieldOffset | bitfieldSize | ... |
635 // \- start of field end of field -/
636 type coreField struct {
637 Type Type
638
639 // The position of the field from the start of the composite type in bytes.
640 offset uint32
641
642 // The offset of the bitfield in bits from the start of the field.
643 bitfieldOffset Bits
644
645 // The size of the bitfield in bits.
646 //
647 // Zero if the field is not a bitfield.
648 bitfieldSize Bits
649 }
650
651 func (cf *coreField) adjustOffsetToNthElement(n int) error {
652 if n == 0 {
653 return nil
654 }
655
656 size, err := Sizeof(cf.Type)
657 if err != nil {
658 return err
659 }
660
661 cf.offset += uint32(n) * uint32(size)
662 return nil
663 }
664
665 func (cf *coreField) adjustOffsetBits(offset Bits) error {
666 align, err := alignof(cf.Type)
667 if err != nil {
668 return err
669 }
670
671 // We can compute the load offset by:
672 // 1) converting the bit offset to bytes with a flooring division.
673 // 2) dividing and multiplying that offset by the alignment, yielding the
674 // load size aligned offset.
675 offsetBytes := uint32(offset/8) / uint32(align) * uint32(align)
676
677 // The number of bits remaining is the bit offset less the number of bits
678 // we can "skip" with the aligned offset.
679 cf.bitfieldOffset = offset - Bits(offsetBytes*8)
680
681 // We know that cf.offset is aligned at to at least align since we get it
682 // from the compiler via BTF. Adding an aligned offsetBytes preserves the
683 // alignment.
684 cf.offset += offsetBytes
685 return nil
686 }
687
688 func (cf *coreField) sizeBits() (Bits, error) {
689 if cf.bitfieldSize > 0 {
690 return cf.bitfieldSize, nil
691 }
692
693 // Someone is trying to access a non-bitfield via a bit shift relocation.
694 // This happens when a field changes from a bitfield to a regular field
695 // between kernel versions. Synthesise the size to make the shifts work.
696 size, err := Sizeof(cf.Type)
697 if err != nil {
698 return 0, err
699 }
700 return Bits(size * 8), nil
701 }
702
703 // coreFindField descends into the local type using the accessor and tries to
704 // find an equivalent field in target at each step.
705 //
706 // Returns the field and the offset of the field from the start of
707 // target in bits.
708 func coreFindField(localT Type, localAcc coreAccessor, targetT Type) (coreField, coreField, error) {
709 local := coreField{Type: localT}
710 target := coreField{Type: targetT}
711
712 if err := coreAreMembersCompatible(local.Type, target.Type); err != nil {
713 return coreField{}, coreField{}, fmt.Errorf("fields: %w", err)
714 }
715
716 // The first index is used to offset a pointer of the base type like
717 // when accessing an array.
718 if err := local.adjustOffsetToNthElement(localAcc[0]); err != nil {
719 return coreField{}, coreField{}, err
720 }
721
722 if err := target.adjustOffsetToNthElement(localAcc[0]); err != nil {
723 return coreField{}, coreField{}, err
724 }
725
726 var localMaybeFlex, targetMaybeFlex bool
727 for i, acc := range localAcc[1:] {
728 switch localType := UnderlyingType(local.Type).(type) {
729 case composite:
730 // For composite types acc is used to find the field in the local type,
731 // and then we try to find a field in target with the same name.
732 localMembers := localType.members()
733 if acc >= len(localMembers) {
734 return coreField{}, coreField{}, fmt.Errorf("invalid accessor %d for %s", acc, localType)
735 }
736
737 localMember := localMembers[acc]
738 if localMember.Name == "" {
739 localMemberType, ok := As[composite](localMember.Type)
740 if !ok {
741 return coreField{}, coreField{}, fmt.Errorf("unnamed field with type %s: %s", localMember.Type, ErrNotSupported)
742 }
743
744 // This is an anonymous struct or union, ignore it.
745 local = coreField{
746 Type: localMemberType,
747 offset: local.offset + localMember.Offset.Bytes(),
748 }
749 localMaybeFlex = false
750 continue
751 }
752
753 targetType, ok := As[composite](target.Type)
754 if !ok {
755 return coreField{}, coreField{}, fmt.Errorf("target not composite: %w", errImpossibleRelocation)
756 }
757
758 targetMember, last, err := coreFindMember(targetType, localMember.Name)
759 if err != nil {
760 return coreField{}, coreField{}, err
761 }
762
763 local = coreField{
764 Type: localMember.Type,
765 offset: local.offset,
766 bitfieldSize: localMember.BitfieldSize,
767 }
768 localMaybeFlex = acc == len(localMembers)-1
769
770 target = coreField{
771 Type: targetMember.Type,
772 offset: target.offset,
773 bitfieldSize: targetMember.BitfieldSize,
774 }
775 targetMaybeFlex = last
776
777 if local.bitfieldSize == 0 && target.bitfieldSize == 0 {
778 local.offset += localMember.Offset.Bytes()
779 target.offset += targetMember.Offset.Bytes()
780 break
781 }
782
783 // Either of the members is a bitfield. Make sure we're at the
784 // end of the accessor.
785 if next := i + 1; next < len(localAcc[1:]) {
786 return coreField{}, coreField{}, fmt.Errorf("can't descend into bitfield")
787 }
788
789 if err := local.adjustOffsetBits(localMember.Offset); err != nil {
790 return coreField{}, coreField{}, err
791 }
792
793 if err := target.adjustOffsetBits(targetMember.Offset); err != nil {
794 return coreField{}, coreField{}, err
795 }
796
797 case *Array:
798 // For arrays, acc is the index in the target.
799 targetType, ok := As[*Array](target.Type)
800 if !ok {
801 return coreField{}, coreField{}, fmt.Errorf("target not array: %w", errImpossibleRelocation)
802 }
803
804 if localType.Nelems == 0 && !localMaybeFlex {
805 return coreField{}, coreField{}, fmt.Errorf("local type has invalid flexible array")
806 }
807 if targetType.Nelems == 0 && !targetMaybeFlex {
808 return coreField{}, coreField{}, fmt.Errorf("target type has invalid flexible array")
809 }
810
811 if localType.Nelems > 0 && acc >= int(localType.Nelems) {
812 return coreField{}, coreField{}, fmt.Errorf("invalid access of %s at index %d", localType, acc)
813 }
814 if targetType.Nelems > 0 && acc >= int(targetType.Nelems) {
815 return coreField{}, coreField{}, fmt.Errorf("out of bounds access of target: %w", errImpossibleRelocation)
816 }
817
818 local = coreField{
819 Type: localType.Type,
820 offset: local.offset,
821 }
822 localMaybeFlex = false
823
824 if err := local.adjustOffsetToNthElement(acc); err != nil {
825 return coreField{}, coreField{}, err
826 }
827
828 target = coreField{
829 Type: targetType.Type,
830 offset: target.offset,
831 }
832 targetMaybeFlex = false
833
834 if err := target.adjustOffsetToNthElement(acc); err != nil {
835 return coreField{}, coreField{}, err
836 }
837
838 default:
839 return coreField{}, coreField{}, fmt.Errorf("relocate field of %T: %w", localType, ErrNotSupported)
840 }
841
842 if err := coreAreMembersCompatible(local.Type, target.Type); err != nil {
843 return coreField{}, coreField{}, err
844 }
845 }
846
847 return local, target, nil
848 }
849
850 // coreFindMember finds a member in a composite type while handling anonymous
851 // structs and unions.
852 func coreFindMember(typ composite, name string) (Member, bool, error) {
853 if name == "" {
854 return Member{}, false, errors.New("can't search for anonymous member")
855 }
856
857 type offsetTarget struct {
858 composite
859 offset Bits
860 }
861
862 targets := []offsetTarget{{typ, 0}}
863 visited := make(map[composite]bool)
864
865 for i := 0; i < len(targets); i++ {
866 target := targets[i]
867
868 // Only visit targets once to prevent infinite recursion.
869 if visited[target] {
870 continue
871 }
872 if len(visited) >= maxResolveDepth {
873 // This check is different than libbpf, which restricts the entire
874 // path to BPF_CORE_SPEC_MAX_LEN items.
875 return Member{}, false, fmt.Errorf("type is nested too deep")
876 }
877 visited[target] = true
878
879 members := target.members()
880 for j, member := range members {
881 if member.Name == name {
882 // NB: This is safe because member is a copy.
883 member.Offset += target.offset
884 return member, j == len(members)-1, nil
885 }
886
887 // The names don't match, but this member could be an anonymous struct
888 // or union.
889 if member.Name != "" {
890 continue
891 }
892
893 comp, ok := As[composite](member.Type)
894 if !ok {
895 return Member{}, false, fmt.Errorf("anonymous non-composite type %T not allowed", member.Type)
896 }
897
898 targets = append(targets, offsetTarget{comp, target.offset + member.Offset})
899 }
900 }
901
902 return Member{}, false, fmt.Errorf("no matching member: %w", errImpossibleRelocation)
903 }
904
905 // coreFindEnumValue follows localAcc to find the equivalent enum value in target.
906 func coreFindEnumValue(local Type, localAcc coreAccessor, target Type) (localValue, targetValue *EnumValue, _ error) {
907 localValue, err := localAcc.enumValue(local)
908 if err != nil {
909 return nil, nil, err
910 }
911
912 targetEnum, ok := As[*Enum](target)
913 if !ok {
914 return nil, nil, errImpossibleRelocation
915 }
916
917 localName := newEssentialName(localValue.Name)
918 for i, targetValue := range targetEnum.Values {
919 if newEssentialName(targetValue.Name) != localName {
920 continue
921 }
922
923 return localValue, &targetEnum.Values[i], nil
924 }
925
926 return nil, nil, errImpossibleRelocation
927 }
928
929 // CheckTypeCompatibility checks local and target types for Compatibility according to CO-RE rules.
930 //
931 // Only layout compatibility is checked, ignoring names of the root type.
932 func CheckTypeCompatibility(localType Type, targetType Type) error {
933 return coreAreTypesCompatible(localType, targetType, nil)
934 }
935
936 type pair struct {
937 A, B Type
938 }
939
940 /* The comment below is from bpf_core_types_are_compat in libbpf.c:
941 *
942 * Check local and target types for compatibility. This check is used for
943 * type-based CO-RE relocations and follow slightly different rules than
944 * field-based relocations. This function assumes that root types were already
945 * checked for name match. Beyond that initial root-level name check, names
946 * are completely ignored. Compatibility rules are as follows:
947 * - any two STRUCTs/UNIONs/FWDs/ENUMs/INTs are considered compatible, but
948 * kind should match for local and target types (i.e., STRUCT is not
949 * compatible with UNION);
950 * - for ENUMs, the size is ignored;
951 * - for INT, size and signedness are ignored;
952 * - for ARRAY, dimensionality is ignored, element types are checked for
953 * compatibility recursively;
954 * - CONST/VOLATILE/RESTRICT modifiers are ignored;
955 * - TYPEDEFs/PTRs are compatible if types they pointing to are compatible;
956 * - FUNC_PROTOs are compatible if they have compatible signature: same
957 * number of input args and compatible return and argument types.
958 * These rules are not set in stone and probably will be adjusted as we get
959 * more experience with using BPF CO-RE relocations.
960 *
961 * Returns errIncompatibleTypes if types are not compatible.
962 */
963 func coreAreTypesCompatible(localType Type, targetType Type, visited map[pair]struct{}) error {
964 localType = UnderlyingType(localType)
965 targetType = UnderlyingType(targetType)
966
967 if reflect.TypeOf(localType) != reflect.TypeOf(targetType) {
968 return fmt.Errorf("type mismatch between %v and %v: %w", localType, targetType, errIncompatibleTypes)
969 }
970
971 if _, ok := visited[pair{localType, targetType}]; ok {
972 return nil
973 }
974 if visited == nil {
975 visited = make(map[pair]struct{})
976 }
977 visited[pair{localType, targetType}] = struct{}{}
978
979 switch lv := localType.(type) {
980 case *Void, *Struct, *Union, *Enum, *Fwd, *Int:
981 return nil
982
983 case *Pointer:
984 tv := targetType.(*Pointer)
985 return coreAreTypesCompatible(lv.Target, tv.Target, visited)
986
987 case *Array:
988 tv := targetType.(*Array)
989 if err := coreAreTypesCompatible(lv.Index, tv.Index, visited); err != nil {
990 return err
991 }
992
993 return coreAreTypesCompatible(lv.Type, tv.Type, visited)
994
995 case *FuncProto:
996 tv := targetType.(*FuncProto)
997 if err := coreAreTypesCompatible(lv.Return, tv.Return, visited); err != nil {
998 return err
999 }
1000
1001 if len(lv.Params) != len(tv.Params) {
1002 return fmt.Errorf("function param mismatch: %w", errIncompatibleTypes)
1003 }
1004
1005 for i, localParam := range lv.Params {
1006 targetParam := tv.Params[i]
1007 if err := coreAreTypesCompatible(localParam.Type, targetParam.Type, visited); err != nil {
1008 return err
1009 }
1010 }
1011
1012 return nil
1013
1014 default:
1015 return fmt.Errorf("unsupported type %T", localType)
1016 }
1017 }
1018
1019 /* coreAreMembersCompatible checks two types for field-based relocation compatibility.
1020 *
1021 * The comment below is from bpf_core_fields_are_compat in libbpf.c:
1022 *
1023 * Check two types for compatibility for the purpose of field access
1024 * relocation. const/volatile/restrict and typedefs are skipped to ensure we
1025 * are relocating semantically compatible entities:
1026 * - any two STRUCTs/UNIONs are compatible and can be mixed;
1027 * - any two FWDs are compatible, if their names match (modulo flavor suffix);
1028 * - any two PTRs are always compatible;
1029 * - for ENUMs, names should be the same (ignoring flavor suffix) or at
1030 * least one of enums should be anonymous;
1031 * - for ENUMs, check sizes, names are ignored;
1032 * - for INT, size and signedness are ignored;
1033 * - any two FLOATs are always compatible;
1034 * - for ARRAY, dimensionality is ignored, element types are checked for
1035 * compatibility recursively;
1036 * [ NB: coreAreMembersCompatible doesn't recurse, this check is done
1037 * by coreFindField. ]
1038 * - everything else shouldn't be ever a target of relocation.
1039 * These rules are not set in stone and probably will be adjusted as we get
1040 * more experience with using BPF CO-RE relocations.
1041 *
1042 * Returns errImpossibleRelocation if the members are not compatible.
1043 */
1044 func coreAreMembersCompatible(localType Type, targetType Type) error {
1045 localType = UnderlyingType(localType)
1046 targetType = UnderlyingType(targetType)
1047
1048 _, lok := localType.(composite)
1049 _, tok := targetType.(composite)
1050 if lok && tok {
1051 return nil
1052 }
1053
1054 if reflect.TypeOf(localType) != reflect.TypeOf(targetType) {
1055 return fmt.Errorf("type mismatch: %w", errImpossibleRelocation)
1056 }
1057
1058 switch lv := localType.(type) {
1059 case *Array, *Pointer, *Float, *Int:
1060 return nil
1061
1062 case *Enum:
1063 tv := targetType.(*Enum)
1064 if !coreEssentialNamesMatch(lv.Name, tv.Name) {
1065 return fmt.Errorf("names %q and %q don't match: %w", lv.Name, tv.Name, errImpossibleRelocation)
1066 }
1067
1068 return nil
1069
1070 case *Fwd:
1071 tv := targetType.(*Fwd)
1072 if !coreEssentialNamesMatch(lv.Name, tv.Name) {
1073 return fmt.Errorf("names %q and %q don't match: %w", lv.Name, tv.Name, errImpossibleRelocation)
1074 }
1075
1076 return nil
1077
1078 default:
1079 return fmt.Errorf("type %s: %w", localType, ErrNotSupported)
1080 }
1081 }
1082
1083 // coreEssentialNamesMatch compares two names while ignoring their flavour suffix.
1084 //
1085 // This should only be used on names which are in the global scope, like struct
1086 // names, typedefs or enum values.
1087 func coreEssentialNamesMatch(a, b string) bool {
1088 if a == "" || b == "" {
1089 // allow anonymous and named type to match
1090 return true
1091 }
1092
1093 return newEssentialName(a) == newEssentialName(b)
1094 }
1095
1096 /* The comment below is from __bpf_core_types_match in relo_core.c:
1097 *
1098 * Check that two types "match". This function assumes that root types were
1099 * already checked for name match.
1100 *
1101 * The matching relation is defined as follows:
1102 * - modifiers and typedefs are stripped (and, hence, effectively ignored)
1103 * - generally speaking types need to be of same kind (struct vs. struct, union
1104 * vs. union, etc.)
1105 * - exceptions are struct/union behind a pointer which could also match a
1106 * forward declaration of a struct or union, respectively, and enum vs.
1107 * enum64 (see below)
1108 * Then, depending on type:
1109 * - integers:
1110 * - match if size and signedness match
1111 * - arrays & pointers:
1112 * - target types are recursively matched
1113 * - structs & unions:
1114 * - local members need to exist in target with the same name
1115 * - for each member we recursively check match unless it is already behind a
1116 * pointer, in which case we only check matching names and compatible kind
1117 * - enums:
1118 * - local variants have to have a match in target by symbolic name (but not
1119 * numeric value)
1120 * - size has to match (but enum may match enum64 and vice versa)
1121 * - function pointers:
1122 * - number and position of arguments in local type has to match target
1123 * - for each argument and the return value we recursively check match
1124 */
1125 func coreTypesMatch(localType Type, targetType Type, visited map[pair]struct{}) error {
1126 localType = UnderlyingType(localType)
1127 targetType = UnderlyingType(targetType)
1128
1129 if !coreEssentialNamesMatch(localType.TypeName(), targetType.TypeName()) {
1130 return fmt.Errorf("type name %q don't match %q: %w", localType.TypeName(), targetType.TypeName(), errIncompatibleTypes)
1131 }
1132
1133 if reflect.TypeOf(localType) != reflect.TypeOf(targetType) {
1134 return fmt.Errorf("type mismatch between %v and %v: %w", localType, targetType, errIncompatibleTypes)
1135 }
1136
1137 if _, ok := visited[pair{localType, targetType}]; ok {
1138 return nil
1139 }
1140 if visited == nil {
1141 visited = make(map[pair]struct{})
1142 }
1143 visited[pair{localType, targetType}] = struct{}{}
1144
1145 switch lv := (localType).(type) {
1146 case *Void:
1147
1148 case *Fwd:
1149 if targetType.(*Fwd).Kind != lv.Kind {
1150 return fmt.Errorf("fwd kind mismatch between %v and %v: %w", localType, targetType, errIncompatibleTypes)
1151 }
1152
1153 case *Enum:
1154 return coreEnumsMatch(lv, targetType.(*Enum))
1155
1156 case composite:
1157 tv := targetType.(composite)
1158
1159 if len(lv.members()) > len(tv.members()) {
1160 return errIncompatibleTypes
1161 }
1162
1163 localMembers := lv.members()
1164 targetMembers := map[string]Member{}
1165 for _, member := range tv.members() {
1166 targetMembers[member.Name] = member
1167 }
1168
1169 for _, localMember := range localMembers {
1170 targetMember, found := targetMembers[localMember.Name]
1171 if !found {
1172 return fmt.Errorf("no field %q in %v: %w", localMember.Name, targetType, errIncompatibleTypes)
1173 }
1174
1175 err := coreTypesMatch(localMember.Type, targetMember.Type, visited)
1176 if err != nil {
1177 return err
1178 }
1179 }
1180
1181 case *Int:
1182 if !coreEncodingMatches(lv, targetType.(*Int)) {
1183 return fmt.Errorf("int mismatch between %v and %v: %w", localType, targetType, errIncompatibleTypes)
1184 }
1185
1186 case *Pointer:
1187 tv := targetType.(*Pointer)
1188
1189 // Allow a pointer to a forward declaration to match a struct
1190 // or union.
1191 if fwd, ok := As[*Fwd](lv.Target); ok && fwd.matches(tv.Target) {
1192 return nil
1193 }
1194
1195 if fwd, ok := As[*Fwd](tv.Target); ok && fwd.matches(lv.Target) {
1196 return nil
1197 }
1198
1199 return coreTypesMatch(lv.Target, tv.Target, visited)
1200
1201 case *Array:
1202 tv := targetType.(*Array)
1203
1204 if lv.Nelems != tv.Nelems {
1205 return fmt.Errorf("array mismatch between %v and %v: %w", localType, targetType, errIncompatibleTypes)
1206 }
1207
1208 return coreTypesMatch(lv.Type, tv.Type, visited)
1209
1210 case *FuncProto:
1211 tv := targetType.(*FuncProto)
1212
1213 if len(lv.Params) != len(tv.Params) {
1214 return fmt.Errorf("function param mismatch: %w", errIncompatibleTypes)
1215 }
1216
1217 for i, lparam := range lv.Params {
1218 if err := coreTypesMatch(lparam.Type, tv.Params[i].Type, visited); err != nil {
1219 return err
1220 }
1221 }
1222
1223 return coreTypesMatch(lv.Return, tv.Return, visited)
1224
1225 default:
1226 return fmt.Errorf("unsupported type %T", localType)
1227 }
1228
1229 return nil
1230 }
1231
1232 // coreEncodingMatches returns true if both ints have the same size and signedness.
1233 // All encodings other than `Signed` are considered unsigned.
1234 func coreEncodingMatches(local, target *Int) bool {
1235 return local.Size == target.Size && (local.Encoding == Signed) == (target.Encoding == Signed)
1236 }
1237
1238 // coreEnumsMatch checks two enums match, which is considered to be the case if the following is true:
1239 // - size has to match (but enum may match enum64 and vice versa)
1240 // - local variants have to have a match in target by symbolic name (but not numeric value)
1241 func coreEnumsMatch(local *Enum, target *Enum) error {
1242 if local.Size != target.Size {
1243 return fmt.Errorf("size mismatch between %v and %v: %w", local, target, errIncompatibleTypes)
1244 }
1245
1246 // If there are more values in the local than the target, there must be at least one value in the local
1247 // that isn't in the target, and therefor the types are incompatible.
1248 if len(local.Values) > len(target.Values) {
1249 return fmt.Errorf("local has more values than target: %w", errIncompatibleTypes)
1250 }
1251
1252 outer:
1253 for _, lv := range local.Values {
1254 for _, rv := range target.Values {
1255 if coreEssentialNamesMatch(lv.Name, rv.Name) {
1256 continue outer
1257 }
1258 }
1259
1260 return fmt.Errorf("no match for %v in %v: %w", lv, target, errIncompatibleTypes)
1261 }
1262
1263 return nil
1264 }