Skip to content

Commit eafdbd2

Browse files
committed
bpf2go: Generate constant names for maps, programs, and variables
Signed-off-by: Matthías Á. Jónsson <[email protected]>
1 parent d1a69ef commit eafdbd2

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

cmd/bpf2go/gen/output.tpl

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,34 @@ import (
2222
{{ end }}
2323
{{- end }}
2424

25+
{{- if or .Maps (or .Variables .Programs) }}
26+
// Constant names for all maps, variables, and programs as defined in the ELF file.
27+
//
28+
// They can be passed to ebpf.CollectionSpec and ebpf.Collection map fields.
29+
const (
30+
{{- if .Maps }}
31+
// {{ .Name }} map names.
32+
{{- range $name, $id := .Maps }}
33+
{{ $.Name }}MapName{{ $id }} = "{{ $name }}"
34+
{{- end }}
35+
{{- end }}
36+
37+
{{- if .Variables }}
38+
// {{ .Name }} variable names.
39+
{{- range $name, $id := .Variables }}
40+
{{ $.Name }}VariableName{{ $id }} = "{{ $name }}"
41+
{{- end }}
42+
{{- end }}
43+
44+
{{- if .Programs }}
45+
// {{ .Name }} program names.
46+
{{- range $name, $id := .Programs }}
47+
{{ $.Name }}ProgramName{{ $id }} = "{{ $name }}"
48+
{{- end }}
49+
{{- end }}
50+
)
51+
{{- end }}
52+
2553
// {{ .Name.Load }} returns the embedded CollectionSpec for {{ .Name }}.
2654
func {{ .Name.Load }}() (*ebpf.CollectionSpec, error) {
2755
reader := bytes.NewReader({{ .Name.Bytes }})

cmd/bpf2go/gen/output_test.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ func TestCustomIdentifier(t *testing.T) {
9595
qt.Assert(t, qt.StringContains(buf.String(), "DO_THING"))
9696
}
9797

98-
func TestObjects(t *testing.T) {
98+
func TestObjectsAndConstants(t *testing.T) {
9999
var buf bytes.Buffer
100100
args := GenerateArgs{
101101
Package: "foo",
@@ -117,6 +117,10 @@ func TestObjects(t *testing.T) {
117117
qt.Assert(t, qt.StringContains(str, "Map1 *ebpf.Map `ebpf:\"map1\"`"))
118118
qt.Assert(t, qt.StringContains(str, "Var1 *ebpf.Variable `ebpf:\"var_1\"`"))
119119
qt.Assert(t, qt.StringContains(str, "ProgFoo1 *ebpf.Program `ebpf:\"prog_foo_1\"`"))
120+
121+
qt.Assert(t, qt.StringContains(str, "barMapNameMap1 = \"map1\""))
122+
qt.Assert(t, qt.StringContains(str, "barVariableNameVar1 = \"var_1\""))
123+
qt.Assert(t, qt.StringContains(str, "barProgramNameProgFoo1 = \"prog_foo_1\""))
120124
}
121125

122126
func TestGenerateStructTypes(t *testing.T) {

0 commit comments

Comments
 (0)