| 1 |
|
| 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 |
|
| 14 |
|
| 15 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 54 |
|
| 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 |
|
| 62 |
|
| 63 |
|
| 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 |
|
| 80 |
switch ut := btf.UnderlyingType(t).(type) { |
| 81 |
case *btf.Struct, *btf.Union, *btf.Enum: |
| 82 |
return t |
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
case *btf.Array: |
| 88 |
return selectType(ut.Type) |
| 89 |
} |
| 90 |
|
| 91 |
return nil |
| 92 |
} |