Debian Codegraph @

cmd/bpf2go/gen/types.go

raw symbols SCIP
1 //go:build !windows
2
3 package gen
4
5 import (
6 "cmp"
7 "slices"
8
9 "github.com/cilium/ebpf"
10 "github.com/cilium/ebpf/btf"
11 )
12
13 // CollectGlobalTypes finds all types which are used in the global scope.
14 //
15 // This currently includes the types of variables, map keys and values.
16 func CollectGlobalTypes(spec *ebpf.CollectionSpec) []btf.Type {
17 var types []btf.Type
18
19 types = collectMapTypes(types, spec.Maps)
20 types = collectVariableTypes(types, spec.Variables)
21
22 slices.SortStableFunc(types, func(a, b btf.Type) int {
23 return cmp.Compare(a.TypeName(), b.TypeName())
24 })
25
26 return types
27 }
28
29 // collectMapTypes collects all types used by MapSpecs.
30 func collectMapTypes(types []btf.Type, maps map[string]*ebpf.MapSpec) []btf.Type {
31 for _, m := range maps {
32 if m.Key != nil && m.Key.TypeName() != "" {
33 types = addType(types, m.Key)
34 }
35
36 if m.Value != nil && m.Value.TypeName() != "" {
37 types = addType(types, m.Value)
38 }
39 }
40
41 return types
42 }
43
44 // collectVariableTypes collects all types used by VariableSpecs.
45 func collectVariableTypes(types []btf.Type, vars map[string]*ebpf.VariableSpec) []btf.Type {
46 for _, vs := range vars {
47 types = addType(types, vs.Type.Type)
48 }
49
50 return types
51 }
52
53 // addType adds a type to types if not already present. Types that don't need to
54 // be generated are not added to types.
55 func addType(types []btf.Type, incoming btf.Type) []btf.Type {
56 incoming = selectType(incoming)
57 if incoming == nil {
58 return types
59 }
60
61 // Strip only the qualifiers (not typedefs) from the incoming type. Retain
62 // typedefs since they carry the name of the anonymous type they point to,
63 // without which we can't generate a named Go type.
64 incoming = btf.QualifiedType(incoming)
65 if incoming.TypeName() == "" {
66 return types
67 }
68
69 exists := func(existing btf.Type) bool {
70 return existing.TypeName() == incoming.TypeName()
71 }
72 if !slices.ContainsFunc(types, exists) {
73 types = append(types, incoming)
74 }
75 return types
76 }
77
78 func selectType(t btf.Type) btf.Type {
79 // Obtain a concrete type with qualifiers and typedefs stripped.
80 switch ut := btf.UnderlyingType(t).(type) {
81 case *btf.Struct, *btf.Union, *btf.Enum:
82 return t
83
84 // Collect the array's element type. Note: qualifiers on array-type variables
85 // typically appear after the array, e.g. a const volatile int[4] is actually
86 // an array of const volatile ints.
87 case *btf.Array:
88 return selectType(ut.Type)
89 }
90
91 return nil
92 }