Debian Codegraph @

btf/types.go

raw symbols SCIP
1 package btf
2
3 import (
4 "errors"
5 "fmt"
6 "io"
7 "math"
8 "strings"
9
10 "github.com/cilium/ebpf/asm"
11 "github.com/cilium/ebpf/internal"
12 "github.com/cilium/ebpf/internal/sys"
13 )
14
15 // Mirrors MAX_RESOLVE_DEPTH in libbpf.
16 // https://github.com/libbpf/libbpf/blob/e26b84dc330c9644c07428c271ab491b0f01f4e1/src/btf.c#L761
17 const maxResolveDepth = 32
18
19 // TypeID identifies a type in a BTF section.
20 type TypeID = sys.TypeID
21
22 // Type represents a type described by BTF.
23 //
24 // A Type has three properties where compared to other Types.
25 //
26 // Identity: follows the [Go specification], two Types are considered identical
27 // if they have the same concrete type and the same dynamic value, aka they point
28 // at the same location in memory. This means that the following Types are
29 // considered distinct even though they have the same "shape".
30 //
31 // a := &Int{Size: 1}
32 // b := &Int{Size: 1}
33 // a != b
34 //
35 // Equivalence: two Types are considered equivalent if they have the same shape
36 // and thus are functionally interchangeable, even if they are located at different
37 // memory addresses. The above two Int types are equivalent.
38 //
39 // Compatibility: two Types are considered compatible according to the rules of CO-RE
40 // see [coreAreTypesCompatible] for details. This is a non-commutative property,
41 // so A may be compatible with B, but B not compatible with A.
42 //
43 // [Go specification]: https://go.dev/ref/spec#Comparison_operators
44 type Type interface {
45 // Type can be formatted using the %s and %v verbs. %s outputs only the
46 // identity of the type, without any detail. %v outputs additional detail.
47 //
48 // Use the '+' flag to include the address of the type.
49 //
50 // Use the width to specify how many levels of detail to output, for example
51 // %1v will output detail for the root type and a short description of its
52 // children. %2v would output details of the root type and its children
53 // as well as a short description of the grandchildren.
54 fmt.Formatter
55
56 // Name of the type, empty for anonymous types and types that cannot
57 // carry a name, like Void and Pointer.
58 TypeName() string
59
60 // Make a copy of the type, without copying Type members.
61 copy() Type
62
63 // New implementations must update children, deduper.typeHash, and typesEquivalent.
64 }
65
66 var (
67 _ Type = (*Int)(nil)
68 _ Type = (*Struct)(nil)
69 _ Type = (*Union)(nil)
70 _ Type = (*Enum)(nil)
71 _ Type = (*Fwd)(nil)
72 _ Type = (*Func)(nil)
73 _ Type = (*Typedef)(nil)
74 _ Type = (*Var)(nil)
75 _ Type = (*Datasec)(nil)
76 _ Type = (*Float)(nil)
77 _ Type = (*declTag)(nil)
78 _ Type = (*TypeTag)(nil)
79 _ Type = (*cycle)(nil)
80 )
81
82 // Void is the unit type of BTF.
83 type Void struct{}
84
85 func (v *Void) Format(fs fmt.State, verb rune) { formatType(fs, verb, v) }
86 func (v *Void) TypeName() string { return "" }
87 func (v *Void) size() uint32 { return 0 }
88 func (v *Void) copy() Type { return (*Void)(nil) }
89
90 type IntEncoding byte
91
92 // Valid IntEncodings.
93 //
94 // These may look like they are flags, but they aren't.
95 const (
96 Unsigned IntEncoding = 0
97 Signed IntEncoding = 1
98 Char IntEncoding = 2
99 Bool IntEncoding = 4
100 )
101
102 func (ie IntEncoding) String() string {
103 switch ie {
104 case Char:
105 // NB: There is no way to determine signedness for char.
106 return "char"
107 case Bool:
108 return "bool"
109 case Signed:
110 return "signed"
111 case Unsigned:
112 return "unsigned"
113 default:
114 return fmt.Sprintf("IntEncoding(%d)", byte(ie))
115 }
116 }
117
118 // Int is an integer of a given length.
119 //
120 // See https://www.kernel.org/doc/html/latest/bpf/btf.html#btf-kind-int
121 type Int struct {
122 Name string
123
124 // The size of the integer in bytes.
125 Size uint32
126 Encoding IntEncoding
127 }
128
129 func (i *Int) Format(fs fmt.State, verb rune) {
130 formatType(fs, verb, i, i.Encoding, "size=", i.Size)
131 }
132
133 func (i *Int) TypeName() string { return i.Name }
134 func (i *Int) size() uint32 { return i.Size }
135 func (i *Int) copy() Type {
136 cpy := *i
137 return &cpy
138 }
139
140 // Pointer is a pointer to another type.
141 type Pointer struct {
142 Target Type
143 }
144
145 func (p *Pointer) Format(fs fmt.State, verb rune) {
146 formatType(fs, verb, p, "target=", p.Target)
147 }
148
149 func (p *Pointer) TypeName() string { return "" }
150 func (p *Pointer) size() uint32 { return 8 }
151 func (p *Pointer) copy() Type {
152 cpy := *p
153 return &cpy
154 }
155
156 // Array is an array with a fixed number of elements.
157 type Array struct {
158 Index Type
159 Type Type
160 Nelems uint32
161 }
162
163 func (arr *Array) Format(fs fmt.State, verb rune) {
164 formatType(fs, verb, arr, "index=", arr.Index, "type=", arr.Type, "n=", arr.Nelems)
165 }
166
167 func (arr *Array) TypeName() string { return "" }
168
169 func (arr *Array) copy() Type {
170 cpy := *arr
171 return &cpy
172 }
173
174 // Struct is a compound type of consecutive members.
175 type Struct struct {
176 Name string
177 // The size of the struct including padding, in bytes
178 Size uint32
179 Members []Member
180 Tags []string
181 }
182
183 // Format supports the width option to %v to limit or extend the number of
184 // struct member names printed (default 5).
185 //
186 // For example, %1v will print only the first member name followed by '...':
187 //
188 // Struct:"struct"[fields=3 fieldNames=[a ...]]
189 func (s *Struct) Format(fs fmt.State, verb rune) {
190 max, _ := fs.Width()
191 formatType(fs, verb, s, "fields=", len(s.Members), "fieldNames=", memberNames(s.Members, max))
192 }
193
194 func (s *Struct) TypeName() string { return s.Name }
195
196 func (s *Struct) size() uint32 { return s.Size }
197
198 func (s *Struct) copy() Type {
199 cpy := *s
200 cpy.Members = copyMembers(s.Members)
201 cpy.Tags = copyTags(cpy.Tags)
202 return &cpy
203 }
204
205 func (s *Struct) members() []Member {
206 return s.Members
207 }
208
209 // Union is a compound type where members occupy the same memory.
210 type Union struct {
211 Name string
212 // The size of the union including padding, in bytes.
213 Size uint32
214 Members []Member
215 Tags []string
216 }
217
218 // Format supports the width option to %v to limit or extend the number of
219 // union member names printed (default 5).
220 //
221 // For example, %1v will print only the first member name followed by '...':
222 //
223 // Union:"union"[fields=3 fieldNames=[a ...]]
224 func (u *Union) Format(fs fmt.State, verb rune) {
225 max, _ := fs.Width()
226 formatType(fs, verb, u, "fields=", len(u.Members), "fieldNames=", memberNames(u.Members, max))
227 }
228
229 func (u *Union) TypeName() string { return u.Name }
230
231 func (u *Union) size() uint32 { return u.Size }
232
233 func (u *Union) copy() Type {
234 cpy := *u
235 cpy.Members = copyMembers(u.Members)
236 cpy.Tags = copyTags(cpy.Tags)
237 return &cpy
238 }
239
240 func (u *Union) members() []Member {
241 return u.Members
242 }
243
244 // memberNames returns the names of members, or its index in the list of members
245 // if the name is empty.
246 //
247 // Returns up to max entries (default 5), followed by '...'.
248 func memberNames(members []Member, max int) []string {
249 if max <= 0 {
250 max = 5
251 }
252 names := make([]string, min(len(members), max+1))
253 for i, m := range members {
254 if i >= max {
255 names[i] = "..."
256 break
257 }
258 if m.Name == "" {
259 names[i] = fmt.Sprintf("<%d>", i)
260 continue
261 }
262 names[i] = m.Name
263 }
264 return names
265 }
266
267 func copyMembers(orig []Member) []Member {
268 cpy := make([]Member, len(orig))
269 copy(cpy, orig)
270 for i, member := range cpy {
271 cpy[i].Tags = copyTags(member.Tags)
272 }
273 return cpy
274 }
275
276 func copyTags(orig []string) []string {
277 if orig == nil { // preserve nil vs zero-len slice distinction
278 return nil
279 }
280 cpy := make([]string, len(orig))
281 copy(cpy, orig)
282 return cpy
283 }
284
285 type composite interface {
286 Type
287 members() []Member
288 }
289
290 var (
291 _ composite = (*Struct)(nil)
292 _ composite = (*Union)(nil)
293 )
294
295 // A value in bits.
296 type Bits uint32
297
298 // Bytes converts a bit value into bytes.
299 func (b Bits) Bytes() uint32 {
300 return uint32(b / 8)
301 }
302
303 // Member is part of a Struct or Union.
304 //
305 // It is not a valid Type.
306 type Member struct {
307 Name string
308 Type Type
309 Offset Bits
310 BitfieldSize Bits
311 Tags []string
312 }
313
314 // Enum lists possible values.
315 type Enum struct {
316 Name string
317 // Size of the enum value in bytes.
318 Size uint32
319 // True if the values should be interpreted as signed integers.
320 Signed bool
321 Values []EnumValue
322 }
323
324 func (e *Enum) Format(fs fmt.State, verb rune) {
325 formatType(fs, verb, e, "size=", e.Size, "values=", len(e.Values))
326 }
327
328 func (e *Enum) TypeName() string { return e.Name }
329
330 // EnumValue is part of an Enum
331 //
332 // Is is not a valid Type
333 type EnumValue struct {
334 Name string
335 Value uint64
336 }
337
338 func (e *Enum) size() uint32 { return e.Size }
339 func (e *Enum) copy() Type {
340 cpy := *e
341 cpy.Values = make([]EnumValue, len(e.Values))
342 copy(cpy.Values, e.Values)
343 return &cpy
344 }
345
346 // FwdKind is the type of forward declaration.
347 type FwdKind int
348
349 // Valid types of forward declaration.
350 const (
351 FwdStruct FwdKind = iota
352 FwdUnion
353 )
354
355 func (fk FwdKind) String() string {
356 switch fk {
357 case FwdStruct:
358 return "struct"
359 case FwdUnion:
360 return "union"
361 default:
362 return fmt.Sprintf("%T(%d)", fk, int(fk))
363 }
364 }
365
366 // Fwd is a forward declaration of a Type.
367 type Fwd struct {
368 Name string
369 Kind FwdKind
370 }
371
372 func (f *Fwd) Format(fs fmt.State, verb rune) {
373 formatType(fs, verb, f, f.Kind)
374 }
375
376 func (f *Fwd) TypeName() string { return f.Name }
377
378 func (f *Fwd) copy() Type {
379 cpy := *f
380 return &cpy
381 }
382
383 func (f *Fwd) matches(typ Type) bool {
384 if _, ok := As[*Struct](typ); ok && f.Kind == FwdStruct {
385 return true
386 }
387
388 if _, ok := As[*Union](typ); ok && f.Kind == FwdUnion {
389 return true
390 }
391
392 return false
393 }
394
395 // Typedef is an alias of a Type.
396 type Typedef struct {
397 Name string
398 Type Type
399 Tags []string
400 }
401
402 func (td *Typedef) Format(fs fmt.State, verb rune) {
403 formatType(fs, verb, td, td.Type)
404 }
405
406 func (td *Typedef) TypeName() string { return td.Name }
407
408 func (td *Typedef) copy() Type {
409 cpy := *td
410 cpy.Tags = copyTags(td.Tags)
411 return &cpy
412 }
413
414 // Volatile is a qualifier.
415 type Volatile struct {
416 Type Type
417 }
418
419 func (v *Volatile) Format(fs fmt.State, verb rune) {
420 formatType(fs, verb, v, v.Type)
421 }
422
423 func (v *Volatile) TypeName() string { return "" }
424
425 func (v *Volatile) qualify() Type { return v.Type }
426 func (v *Volatile) copy() Type {
427 cpy := *v
428 return &cpy
429 }
430
431 // Const is a qualifier.
432 type Const struct {
433 Type Type
434 }
435
436 func (c *Const) Format(fs fmt.State, verb rune) {
437 formatType(fs, verb, c, c.Type)
438 }
439
440 func (c *Const) TypeName() string { return "" }
441
442 func (c *Const) qualify() Type { return c.Type }
443 func (c *Const) copy() Type {
444 cpy := *c
445 return &cpy
446 }
447
448 // Restrict is a qualifier.
449 type Restrict struct {
450 Type Type
451 }
452
453 func (r *Restrict) Format(fs fmt.State, verb rune) {
454 formatType(fs, verb, r, r.Type)
455 }
456
457 func (r *Restrict) TypeName() string { return "" }
458
459 func (r *Restrict) qualify() Type { return r.Type }
460 func (r *Restrict) copy() Type {
461 cpy := *r
462 return &cpy
463 }
464
465 // Func is a function definition.
466 type Func struct {
467 Name string
468 Type Type
469 Linkage FuncLinkage
470 Tags []string
471 // ParamTags holds a list of tags for each parameter of the FuncProto to which `Type` points.
472 // If no tags are present for any param, the outer slice will be nil/len(ParamTags)==0.
473 // If at least 1 param has a tag, the outer slice will have the same length as the number of params.
474 // The inner slice contains the tags and may be nil/len(ParamTags[i])==0 if no tags are present for that param.
475 ParamTags [][]string
476 }
477
478 type funcInfoMeta struct{}
479
480 func FuncMetadata(ins *asm.Instruction) *Func {
481 fn, _ := ins.Metadata.Get(funcInfoMeta{}).(*Func)
482 return fn
483 }
484
485 // WithFuncMetadata adds a btf.Func to the Metadata of asm.Instruction.
486 func WithFuncMetadata(ins asm.Instruction, fn *Func) asm.Instruction {
487 ins.Metadata.Set(funcInfoMeta{}, fn)
488 return ins
489 }
490
491 func (f *Func) Format(fs fmt.State, verb rune) {
492 formatType(fs, verb, f, f.Linkage, "proto=", f.Type)
493 }
494
495 func (f *Func) TypeName() string { return f.Name }
496
497 func (f *Func) copy() Type {
498 cpy := *f
499 cpy.Tags = copyTags(f.Tags)
500 if f.ParamTags != nil { // preserve nil vs zero-len slice distinction
501 ptCopy := make([][]string, len(f.ParamTags))
502 for i, tags := range f.ParamTags {
503 ptCopy[i] = copyTags(tags)
504 }
505 cpy.ParamTags = ptCopy
506 }
507 return &cpy
508 }
509
510 // FuncProto is a function declaration.
511 type FuncProto struct {
512 Return Type
513 Params []FuncParam
514 }
515
516 func (fp *FuncProto) Format(fs fmt.State, verb rune) {
517 formatType(fs, verb, fp, "args=", len(fp.Params), "return=", fp.Return)
518 }
519
520 func (fp *FuncProto) TypeName() string { return "" }
521
522 func (fp *FuncProto) copy() Type {
523 cpy := *fp
524 cpy.Params = make([]FuncParam, len(fp.Params))
525 copy(cpy.Params, fp.Params)
526 return &cpy
527 }
528
529 type FuncParam struct {
530 Name string
531 Type Type
532 }
533
534 // Var is a global variable.
535 type Var struct {
536 Name string
537 Type Type
538 Linkage VarLinkage
539 Tags []string
540 }
541
542 func (v *Var) Format(fs fmt.State, verb rune) {
543 formatType(fs, verb, v, v.Linkage)
544 }
545
546 func (v *Var) TypeName() string { return v.Name }
547
548 func (v *Var) copy() Type {
549 cpy := *v
550 cpy.Tags = copyTags(v.Tags)
551 return &cpy
552 }
553
554 // Datasec is a global program section containing data.
555 type Datasec struct {
556 Name string
557 Size uint32
558 Vars []VarSecinfo
559 }
560
561 func (ds *Datasec) Format(fs fmt.State, verb rune) {
562 formatType(fs, verb, ds)
563 }
564
565 func (ds *Datasec) TypeName() string { return ds.Name }
566
567 func (ds *Datasec) size() uint32 { return ds.Size }
568
569 func (ds *Datasec) copy() Type {
570 cpy := *ds
571 cpy.Vars = make([]VarSecinfo, len(ds.Vars))
572 copy(cpy.Vars, ds.Vars)
573 return &cpy
574 }
575
576 // VarSecinfo describes variable in a Datasec.
577 //
578 // It is not a valid Type.
579 type VarSecinfo struct {
580 // Var or Func.
581 Type Type
582 Offset uint32
583 Size uint32
584 }
585
586 // Float is a float of a given length.
587 type Float struct {
588 Name string
589
590 // The size of the float in bytes.
591 Size uint32
592 }
593
594 func (f *Float) Format(fs fmt.State, verb rune) {
595 formatType(fs, verb, f, "size=", f.Size*8)
596 }
597
598 func (f *Float) TypeName() string { return f.Name }
599 func (f *Float) size() uint32 { return f.Size }
600 func (f *Float) copy() Type {
601 cpy := *f
602 return &cpy
603 }
604
605 // declTag associates metadata with a declaration.
606 type declTag struct {
607 Type Type
608 Value string
609 // The index this tag refers to in the target type. For composite types,
610 // a value of -1 indicates that the tag refers to the whole type. Otherwise
611 // it indicates which member or argument the tag applies to.
612 Index int
613 }
614
615 func (dt *declTag) Format(fs fmt.State, verb rune) {
616 formatType(fs, verb, dt, "type=", dt.Type, "value=", dt.Value, "index=", dt.Index)
617 }
618
619 func (dt *declTag) TypeName() string { return "" }
620 func (dt *declTag) copy() Type {
621 cpy := *dt
622 return &cpy
623 }
624
625 // TypeTag associates metadata with a pointer type. Tag types act as a custom
626 // modifier(const, restrict, volatile) for the target type. Unlike declTags,
627 // TypeTags are ordered so the order in which they are added matters.
628 //
629 // One of their uses is to mark pointers as `__kptr` meaning a pointer points
630 // to kernel memory. Adding a `__kptr` to pointers in map values allows you
631 // to store pointers to kernel memory in maps.
632 type TypeTag struct {
633 Type Type
634 Value string
635 }
636
637 func (tt *TypeTag) Format(fs fmt.State, verb rune) {
638 formatType(fs, verb, tt, "type=", tt.Type, "value=", tt.Value)
639 }
640
641 func (tt *TypeTag) TypeName() string { return "" }
642 func (tt *TypeTag) qualify() Type { return tt.Type }
643 func (tt *TypeTag) copy() Type {
644 cpy := *tt
645 return &cpy
646 }
647
648 // cycle is a type which had to be elided since it exceeded maxTypeDepth.
649 type cycle struct {
650 root Type
651 }
652
653 func (c *cycle) ID() TypeID { return math.MaxUint32 }
654 func (c *cycle) Format(fs fmt.State, verb rune) { formatType(fs, verb, c, "root=", c.root) }
655 func (c *cycle) TypeName() string { return "" }
656 func (c *cycle) copy() Type {
657 cpy := *c
658 return &cpy
659 }
660
661 type sizer interface {
662 size() uint32
663 }
664
665 var (
666 _ sizer = (*Int)(nil)
667 _ sizer = (*Pointer)(nil)
668 _ sizer = (*Struct)(nil)
669 _ sizer = (*Union)(nil)
670 _ sizer = (*Enum)(nil)
671 _ sizer = (*Datasec)(nil)
672 )
673
674 type qualifier interface {
675 qualify() Type
676 }
677
678 var (
679 _ qualifier = (*Const)(nil)
680 _ qualifier = (*Restrict)(nil)
681 _ qualifier = (*Volatile)(nil)
682 _ qualifier = (*TypeTag)(nil)
683 )
684
685 var errUnsizedType = errors.New("type is unsized")
686
687 // Sizeof returns the size of a type in bytes.
688 //
689 // Returns an error if the size can't be computed.
690 func Sizeof(typ Type) (int, error) {
691 var (
692 n = int64(1)
693 elem int64
694 )
695
696 for range maxResolveDepth {
697 switch v := typ.(type) {
698 case *Array:
699 if n > 0 && int64(v.Nelems) > math.MaxInt64/n {
700 return 0, fmt.Errorf("type %s: overflow", typ)
701 }
702
703 // Arrays may be of zero length, which allows
704 // n to be zero as well.
705 n *= int64(v.Nelems)
706 typ = v.Type
707 continue
708
709 case sizer:
710 elem = int64(v.size())
711
712 case *Typedef:
713 typ = v.Type
714 continue
715
716 case qualifier:
717 typ = v.qualify()
718 continue
719
720 default:
721 return 0, fmt.Errorf("type %T: %w", typ, errUnsizedType)
722 }
723
724 if n > 0 && elem > math.MaxInt64/n {
725 return 0, fmt.Errorf("type %s: overflow", typ)
726 }
727
728 size := n * elem
729 if int64(int(size)) != size {
730 return 0, fmt.Errorf("type %s: overflow", typ)
731 }
732
733 return int(size), nil
734 }
735
736 return 0, fmt.Errorf("type %s: exceeded type depth", typ)
737 }
738
739 // alignof returns the alignment of a type.
740 //
741 // Returns an error if the Type can't be aligned, like an integer with an uneven
742 // size. Currently only supports the subset of types necessary for bitfield
743 // relocations.
744 func alignof(typ Type) (int, error) {
745 var n int
746
747 switch t := UnderlyingType(typ).(type) {
748 case *Enum:
749 n = int(t.size())
750 case *Int:
751 n = int(t.Size)
752 case *Array:
753 return alignof(t.Type)
754 default:
755 return 0, fmt.Errorf("can't calculate alignment of %T", t)
756 }
757
758 if !internal.IsPow(n) {
759 return 0, fmt.Errorf("alignment value %d is not a power of two", n)
760 }
761
762 return n, nil
763 }
764
765 // Copy a Type recursively.
766 //
767 // typ may form a cycle.
768 func Copy(typ Type) Type {
769 return copyType(typ, nil, make(map[Type]Type), nil)
770 }
771
772 func copyType(typ Type, ids map[Type]TypeID, copies map[Type]Type, copiedIDs map[Type]TypeID) Type {
773 if typ == nil {
774 return nil
775 }
776
777 cpy, ok := copies[typ]
778 if ok {
779 // This has been copied previously, no need to continue.
780 return cpy
781 }
782
783 cpy = typ.copy()
784 copies[typ] = cpy
785
786 if id, ok := ids[typ]; ok {
787 copiedIDs[cpy] = id
788 }
789
790 for child := range children(cpy) {
791 *child = copyType(*child, ids, copies, copiedIDs)
792 }
793
794 return cpy
795 }
796
797 type typeDeque = internal.Deque[*Type]
798
799 // essentialName represents the name of a BTF type stripped of any flavor
800 // suffixes after a ___ delimiter.
801 type essentialName string
802
803 // newEssentialName returns name without a ___ suffix.
804 //
805 // CO-RE has the concept of 'struct flavors', which are used to deal with
806 // changes in kernel data structures. Anything after three underscores
807 // in a type name is ignored for the purpose of finding a candidate type
808 // in the kernel's BTF.
809 func newEssentialName(name string) essentialName {
810 if name == "" {
811 return ""
812 }
813 lastIdx := strings.LastIndex(name, "___")
814 if lastIdx > 0 {
815 return essentialName(name[:lastIdx])
816 }
817 return essentialName(name)
818 }
819
820 // UnderlyingType skips qualifiers and Typedefs.
821 func UnderlyingType(typ Type) Type {
822 result := typ
823 for depth := 0; depth <= maxResolveDepth; depth++ {
824 switch v := (result).(type) {
825 case qualifier:
826 result = v.qualify()
827 case *Typedef:
828 result = v.Type
829 default:
830 return result
831 }
832 }
833 return &cycle{typ}
834 }
835
836 // QualifiedType returns the type with all qualifiers removed.
837 func QualifiedType(typ Type) Type {
838 result := typ
839 for depth := 0; depth <= maxResolveDepth; depth++ {
840 switch v := (result).(type) {
841 case qualifier:
842 result = v.qualify()
843 default:
844 return result
845 }
846 }
847 return &cycle{typ}
848 }
849
850 // As returns typ if is of type T. Otherwise it peels qualifiers and Typedefs
851 // until it finds a T.
852 //
853 // Returns the zero value and false if there is no T or if the type is nested
854 // too deeply.
855 func As[T Type](typ Type) (T, bool) {
856 // NB: We can't make this function return (*T) since then
857 // we can't assert that a type matches an interface which
858 // embeds Type: as[composite](T).
859 for depth := 0; depth <= maxResolveDepth; depth++ {
860 switch v := (typ).(type) {
861 case T:
862 return v, true
863 case qualifier:
864 typ = v.qualify()
865 case *Typedef:
866 typ = v.Type
867 default:
868 goto notFound
869 }
870 }
871 notFound:
872 var zero T
873 return zero, false
874 }
875
876 type formatState struct {
877 fmt.State
878 depth int
879 }
880
881 // formattableType is a subset of Type, to ease unit testing of formatType.
882 type formattableType interface {
883 fmt.Formatter
884 TypeName() string
885 }
886
887 // formatType formats a type in a canonical form.
888 //
889 // Handles cyclical types by only printing cycles up to a certain depth. Elements
890 // in extra are separated by spaces unless the preceding element is a string
891 // ending in '='.
892 func formatType(f fmt.State, verb rune, t formattableType, extra ...any) {
893 if verb != 'v' && verb != 's' {
894 fmt.Fprintf(f, "{UNRECOGNIZED: %c}", verb)
895 return
896 }
897
898 _, _ = io.WriteString(f, internal.GoTypeName(t))
899
900 if name := t.TypeName(); name != "" {
901 // Output BTF type name if present.
902 fmt.Fprintf(f, ":%q", name)
903 }
904
905 if f.Flag('+') {
906 // Output address if requested.
907 fmt.Fprintf(f, ":%#p", t)
908 }
909
910 if verb == 's' {
911 // %s omits details.
912 return
913 }
914
915 var depth int
916 if ps, ok := f.(*formatState); ok {
917 depth = ps.depth
918 f = ps.State
919 }
920
921 maxDepth, ok := f.Width()
922 if !ok {
923 maxDepth = 0
924 }
925
926 if depth > maxDepth {
927 // We've reached the maximum depth. This avoids infinite recursion even
928 // for cyclical types.
929 return
930 }
931
932 if len(extra) == 0 {
933 return
934 }
935
936 wantSpace := false
937 _, _ = io.WriteString(f, "[")
938 for _, arg := range extra {
939 if wantSpace {
940 _, _ = io.WriteString(f, " ")
941 }
942
943 switch v := arg.(type) {
944 case string:
945 _, _ = io.WriteString(f, v)
946 wantSpace = len(v) > 0 && v[len(v)-1] != '='
947 continue
948
949 case formattableType:
950 v.Format(&formatState{f, depth + 1}, verb)
951
952 default:
953 fmt.Fprint(f, arg)
954 }
955
956 wantSpace = true
957 }
958 _, _ = io.WriteString(f, "]")
959 }