/
output.go
388 lines (324 loc) · 8.58 KB
/
output.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
package main
import (
"bytes"
"fmt"
"go/token"
"io"
"io/ioutil"
"path/filepath"
"sort"
"strings"
"text/template"
"github.com/cilium/ebpf"
"github.com/cilium/ebpf/internal"
"github.com/cilium/ebpf/internal/btf"
)
const ebpfModule = "github.com/cilium/ebpf"
const commonRaw = `// Code generated by bpf2go; DO NOT EDIT.
{{- range .Tags }}
// +build {{ . }}
{{- end }}
package {{ .Package }}
import (
"bytes"
_ "embed"
"fmt"
"io"
"{{ .Module }}"
)
{{- if .Types }}
{{- range $type := .Types }}
{{ $.TypeDeclaration (index $.TypeNames $type) $type }}
{{ end }}
{{- end }}
// {{ .Name.Load }} returns the embedded CollectionSpec for {{ .Name }}.
func {{ .Name.Load }}() (*ebpf.CollectionSpec, error) {
reader := bytes.NewReader({{ .Name.Bytes }})
spec, err := ebpf.LoadCollectionSpecFromReader(reader)
if err != nil {
return nil, fmt.Errorf("can't load {{ .Name }}: %w", err)
}
return spec, err
}
// {{ .Name.LoadObjects }} loads {{ .Name }} and converts it into a struct.
//
// The following types are suitable as obj argument:
//
// *{{ .Name.Objects }}
// *{{ .Name.Programs }}
// *{{ .Name.Maps }}
//
// See ebpf.CollectionSpec.LoadAndAssign documentation for details.
func {{ .Name.LoadObjects }}(obj interface{}, opts *ebpf.CollectionOptions) (error) {
spec, err := {{ .Name.Load }}()
if err != nil {
return err
}
return spec.LoadAndAssign(obj, opts)
}
// {{ .Name.Specs }} contains maps and programs before they are loaded into the kernel.
//
// It can be passed ebpf.CollectionSpec.Assign.
type {{ .Name.Specs }} struct {
{{ .Name.ProgramSpecs }}
{{ .Name.MapSpecs }}
}
// {{ .Name.Specs }} contains programs before they are loaded into the kernel.
//
// It can be passed ebpf.CollectionSpec.Assign.
type {{ .Name.ProgramSpecs }} struct {
{{- range $name, $id := .Programs }}
{{ $id }} *ebpf.ProgramSpec {{ tag $name }}
{{- end }}
}
// {{ .Name.MapSpecs }} contains maps before they are loaded into the kernel.
//
// It can be passed ebpf.CollectionSpec.Assign.
type {{ .Name.MapSpecs }} struct {
{{- range $name, $id := .Maps }}
{{ $id }} *ebpf.MapSpec {{ tag $name }}
{{- end }}
}
// {{ .Name.Objects }} contains all objects after they have been loaded into the kernel.
//
// It can be passed to {{ .Name.LoadObjects }} or ebpf.CollectionSpec.LoadAndAssign.
type {{ .Name.Objects }} struct {
{{ .Name.Programs }}
{{ .Name.Maps }}
}
func (o *{{ .Name.Objects }}) Close() error {
return {{ .Name.CloseHelper }}(
&o.{{ .Name.Programs }},
&o.{{ .Name.Maps }},
)
}
// {{ .Name.Maps }} contains all maps after they have been loaded into the kernel.
//
// It can be passed to {{ .Name.LoadObjects }} or ebpf.CollectionSpec.LoadAndAssign.
type {{ .Name.Maps }} struct {
{{- range $name, $id := .Maps }}
{{ $id }} *ebpf.Map {{ tag $name }}
{{- end }}
}
func (m *{{ .Name.Maps }}) Close() error {
return {{ .Name.CloseHelper }}(
{{- range $id := .Maps }}
m.{{ $id }},
{{- end }}
)
}
// {{ .Name.Programs }} contains all programs after they have been loaded into the kernel.
//
// It can be passed to {{ .Name.LoadObjects }} or ebpf.CollectionSpec.LoadAndAssign.
type {{ .Name.Programs }} struct {
{{- range $name, $id := .Programs }}
{{ $id }} *ebpf.Program {{ tag $name }}
{{- end }}
}
func (p *{{ .Name.Programs }}) Close() error {
return {{ .Name.CloseHelper }}(
{{- range $id := .Programs }}
p.{{ $id }},
{{- end }}
)
}
func {{ .Name.CloseHelper }}(closers ...io.Closer) error {
for _, closer := range closers {
if err := closer.Close(); err != nil {
return err
}
}
return nil
}
// Do not access this directly.
//go:embed {{ .File }}
var {{ .Name.Bytes }} []byte
`
var (
tplFuncs = map[string]interface{}{
"tag": tag,
}
commonTemplate = template.Must(template.New("common").Funcs(tplFuncs).Parse(commonRaw))
)
type templateName string
func (n templateName) maybeExport(str string) string {
if token.IsExported(string(n)) {
return toUpperFirst(str)
}
return str
}
func (n templateName) Bytes() string {
return "_" + toUpperFirst(string(n)) + "Bytes"
}
func (n templateName) Specs() string {
return string(n) + "Specs"
}
func (n templateName) ProgramSpecs() string {
return string(n) + "ProgramSpecs"
}
func (n templateName) MapSpecs() string {
return string(n) + "MapSpecs"
}
func (n templateName) Load() string {
return n.maybeExport("load" + toUpperFirst(string(n)))
}
func (n templateName) LoadObjects() string {
return n.maybeExport("load" + toUpperFirst(string(n)) + "Objects")
}
func (n templateName) Objects() string {
return string(n) + "Objects"
}
func (n templateName) Maps() string {
return string(n) + "Maps"
}
func (n templateName) Programs() string {
return string(n) + "Programs"
}
func (n templateName) CloseHelper() string {
return "_" + toUpperFirst(string(n)) + "Close"
}
type outputArgs struct {
pkg string
ident string
tags []string
cTypes []string
skipGlobalTypes bool
obj string
out io.Writer
}
func output(args outputArgs) error {
obj, err := ioutil.ReadFile(args.obj)
if err != nil {
return fmt.Errorf("read object file contents: %s", err)
}
rd := bytes.NewReader(obj)
spec, err := ebpf.LoadCollectionSpecFromReader(rd)
if err != nil {
return fmt.Errorf("can't load BPF from ELF: %s", err)
}
maps := make(map[string]string)
for name := range spec.Maps {
if strings.HasPrefix(name, ".") {
// Skip .rodata, .data, .bss, etc. sections
continue
}
maps[name] = internal.Identifier(name)
}
programs := make(map[string]string)
for name := range spec.Programs {
programs[name] = internal.Identifier(name)
}
// Collect any types which we've been asked for explicitly.
cTypes, err := collectCTypes(spec.Types, args.cTypes)
if err != nil {
return err
}
typeNames := make(map[btf.Type]string)
for _, cType := range cTypes {
typeNames[cType] = args.ident + internal.Identifier(cType.TypeName())
}
// Collect map key and value types, unless we've been asked not to.
if !args.skipGlobalTypes {
for _, typ := range collectMapTypes(spec.Maps) {
switch btf.UnderlyingType(typ).(type) {
case *btf.Datasec:
// Avoid emitting .rodata, .bss, etc. for now. We might want to
// name these types differently, etc.
continue
case *btf.Int:
// Don't emit primitive types by default.
continue
}
typeNames[typ] = args.ident + internal.Identifier(typ.TypeName())
}
}
// Ensure we don't have conflicting names and generate a sorted list of
// named types so that the output is stable.
types, err := sortTypes(typeNames)
if err != nil {
return err
}
gf := &btf.GoFormatter{
Names: typeNames,
Identifier: internal.Identifier,
}
ctx := struct {
*btf.GoFormatter
Module string
Package string
Tags []string
Name templateName
Maps map[string]string
Programs map[string]string
Types []btf.Type
TypeNames map[btf.Type]string
File string
}{
gf,
ebpfModule,
args.pkg,
args.tags,
templateName(args.ident),
maps,
programs,
types,
typeNames,
filepath.Base(args.obj),
}
var buf bytes.Buffer
if err := commonTemplate.Execute(&buf, &ctx); err != nil {
return fmt.Errorf("can't generate types: %s", err)
}
return internal.WriteFormatted(buf.Bytes(), args.out)
}
func collectCTypes(types *btf.Spec, names []string) ([]btf.Type, error) {
var result []btf.Type
for _, cType := range names {
typ, err := types.AnyTypeByName(cType)
if err != nil {
return nil, err
}
result = append(result, typ)
}
return result, nil
}
// collectMapTypes returns a list of all types used as map keys or values.
func collectMapTypes(maps map[string]*ebpf.MapSpec) []btf.Type {
var result []btf.Type
for _, m := range maps {
if m.BTF == nil {
continue
}
if m.BTF.Key != nil && m.BTF.Key.TypeName() != "" {
result = append(result, m.BTF.Key)
}
if m.BTF.Value != nil && m.BTF.Value.TypeName() != "" {
result = append(result, m.BTF.Value)
}
}
return result
}
// sortTypes returns a list of types sorted by their (generated) Go type name.
//
// Duplicate Go type names are rejected.
func sortTypes(typeNames map[btf.Type]string) ([]btf.Type, error) {
var types []btf.Type
var names []string
for typ, name := range typeNames {
i := sort.SearchStrings(names, name)
if i >= len(names) {
types = append(types, typ)
names = append(names, name)
continue
}
if names[i] == name {
return nil, fmt.Errorf("type name %q is used multiple times", name)
}
types = append(types[:i], append([]btf.Type{typ}, types[i:]...)...)
names = append(names[:i], append([]string{name}, names[i:]...)...)
}
return types, nil
}
func tag(str string) string {
return "`ebpf:\"" + str + "\"`"
}