Debian Codegraph @

cmd/bpf2go/gen/output.go

raw symbols SCIP
1 //go:build !windows
2
3 package gen
4
5 import (
6 "bytes"
7 _ "embed"
8 "fmt"
9 "go/build/constraint"
10 "go/token"
11 "io"
12 "sort"
13 "strings"
14 "text/template"
15 "unicode"
16 "unicode/utf8"
17
18 "github.com/cilium/ebpf/btf"
19 b2gInt "github.com/cilium/ebpf/cmd/bpf2go/internal"
20 "github.com/cilium/ebpf/internal"
21 )
22
23 //go:embed output.tpl
24 var commonRaw string
25
26 var commonTemplate = template.Must(template.New("common").Parse(commonRaw))
27
28 type templateName string
29
30 func (n templateName) maybeExport(str string) string {
31 if token.IsExported(string(n)) {
32 return toUpperFirst(str)
33 }
34
35 return str
36 }
37
38 func (n templateName) Bytes() string {
39 return "_" + toUpperFirst(string(n)) + "Bytes"
40 }
41
42 func (n templateName) Specs() string {
43 return string(n) + "Specs"
44 }
45
46 func (n templateName) ProgramSpecs() string {
47 return string(n) + "ProgramSpecs"
48 }
49
50 func (n templateName) MapSpecs() string {
51 return string(n) + "MapSpecs"
52 }
53
54 func (n templateName) VariableSpecs() string {
55 return string(n) + "VariableSpecs"
56 }
57
58 func (n templateName) Load() string {
59 return n.maybeExport("load" + toUpperFirst(string(n)))
60 }
61
62 func (n templateName) LoadObjects() string {
63 return n.maybeExport("load" + toUpperFirst(string(n)) + "Objects")
64 }
65
66 func (n templateName) Objects() string {
67 return string(n) + "Objects"
68 }
69
70 func (n templateName) Maps() string {
71 return string(n) + "Maps"
72 }
73
74 func (n templateName) Variables() string {
75 return string(n) + "Variables"
76 }
77
78 func (n templateName) Programs() string {
79 return string(n) + "Programs"
80 }
81
82 func (n templateName) CloseHelper() string {
83 return "_" + toUpperFirst(string(n)) + "Close"
84 }
85
86 type GenerateArgs struct {
87 // Package of the resulting file.
88 Package string
89 // The prefix of all names declared at the top-level.
90 Stem string
91 // Build Constraints included in the resulting file.
92 Constraints constraint.Expr
93 // Maps to be emitted.
94 Maps []string
95 // Variables to be emitted.
96 Variables []string
97 // Programs to be emitted.
98 Programs []string
99 // Types to be emitted.
100 Types []btf.Type
101 // Filename of the object to embed.
102 ObjectFile string
103 // Output to write template to.
104 Output io.Writer
105 // Function which transforms the input into a valid go identifier. Uses the default behaviour if nil
106 Identifier func(string) string
107 }
108
109 // Generate bindings for a BPF ELF file.
110 func Generate(args GenerateArgs) error {
111 if args.Identifier == nil {
112 args.Identifier = internal.Identifier
113 }
114 if !token.IsIdentifier(args.Stem) {
115 return fmt.Errorf("%q is not a valid identifier", args.Stem)
116 }
117
118 if strings.ContainsAny(args.ObjectFile, "\n") {
119 // Prevent injecting newlines into the template.
120 return fmt.Errorf("file %q contains an invalid character", args.ObjectFile)
121 }
122
123 for _, typ := range args.Types {
124 if _, ok := btf.As[*btf.Datasec](typ); ok {
125 // Avoid emitting .rodata, .bss, etc. for now. We might want to
126 // name these types differently, etc.
127 return fmt.Errorf("can't output btf.Datasec: %s", typ)
128 }
129 }
130
131 maps := make(map[string]string)
132 for _, name := range args.Maps {
133 maps[name] = args.Identifier(name)
134 }
135
136 variables := make(map[string]string)
137 for _, name := range args.Variables {
138 variables[name] = args.Identifier(name)
139 }
140
141 programs := make(map[string]string)
142 for _, name := range args.Programs {
143 programs[name] = args.Identifier(name)
144 }
145
146 typeNames := make(map[btf.Type]string)
147 for _, typ := range args.Types {
148 // NB: This also deduplicates types.
149 typeNames[typ] = args.Stem + args.Identifier(typ.TypeName())
150 }
151
152 // Ensure we don't have conflicting names and generate a sorted list of
153 // named types so that the output is stable.
154 types, err := sortTypes(typeNames)
155 if err != nil {
156 return err
157 }
158
159 gf := &btf.GoFormatter{
160 Names: typeNames,
161 Identifier: args.Identifier,
162 }
163
164 var typeDecls []string
165 needsStructsPkg := false
166 for _, typ := range types {
167 name := typeNames[typ]
168 decl, err := gf.TypeDeclaration(name, typ)
169 if err != nil {
170 return fmt.Errorf("generating %s: %w", name, err)
171 }
172 _, ok := btf.As[*btf.Struct](typ)
173 needsStructsPkg = needsStructsPkg || ok
174 typeDecls = append(typeDecls, decl)
175 }
176
177 ctx := struct {
178 Module string
179 Package string
180 Constraints constraint.Expr
181 Name templateName
182 Maps map[string]string
183 Variables map[string]string
184 Programs map[string]string
185 TypeDeclarations []string
186 File string
187 NeedsStructsPkg bool
188 }{
189 b2gInt.CurrentModule,
190 args.Package,
191 args.Constraints,
192 templateName(args.Stem),
193 maps,
194 variables,
195 programs,
196 typeDecls,
197 args.ObjectFile,
198 needsStructsPkg,
199 }
200
201 var buf bytes.Buffer
202 if err := commonTemplate.Execute(&buf, &ctx); err != nil {
203 return fmt.Errorf("can't generate types: %s", err)
204 }
205
206 return internal.WriteFormatted(buf.Bytes(), args.Output)
207 }
208
209 // sortTypes returns a list of types sorted by their (generated) Go type name.
210 //
211 // Duplicate Go type names are rejected.
212 func sortTypes(typeNames map[btf.Type]string) ([]btf.Type, error) {
213 var types []btf.Type
214 var names []string
215 for typ, name := range typeNames {
216 i := sort.SearchStrings(names, name)
217 if i >= len(names) {
218 types = append(types, typ)
219 names = append(names, name)
220 continue
221 }
222
223 if names[i] == name {
224 return nil, fmt.Errorf("type name %q is used multiple times (remove its --type flag?)", name)
225 }
226
227 types = append(types[:i], append([]btf.Type{typ}, types[i:]...)...)
228 names = append(names[:i], append([]string{name}, names[i:]...)...)
229 }
230
231 return types, nil
232 }
233
234 func toUpperFirst(str string) string {
235 first, n := utf8.DecodeRuneInString(str)
236 return string(unicode.ToUpper(first)) + str[n:]
237 }