diff --git a/cmd/bpf2go/gen/output.tpl b/cmd/bpf2go/gen/output.tpl index 350b0cab7..1ad996c7d 100644 --- a/cmd/bpf2go/gen/output.tpl +++ b/cmd/bpf2go/gen/output.tpl @@ -22,6 +22,34 @@ import ( {{ end }} {{- end }} +{{- if or .Maps (or .Variables .Programs) }} +// Constant names for all maps, variables, and programs as defined in the ELF file. +// +// They can be passed to ebpf.CollectionSpec and ebpf.Collection map fields. +const ( +{{- if .Maps }} + // {{ .Name }} map names. +{{- range $name, $id := .Maps }} + {{ $.Name }}MapName{{ $id }} = "{{ $name }}" +{{- end }} +{{- end }} + +{{- if .Variables }} + // {{ .Name }} variable names. +{{- range $name, $id := .Variables }} + {{ $.Name }}VariableName{{ $id }} = "{{ $name }}" +{{- end }} +{{- end }} + +{{- if .Programs }} + // {{ .Name }} program names. +{{- range $name, $id := .Programs }} + {{ $.Name }}ProgramName{{ $id }} = "{{ $name }}" +{{- end }} +{{- end }} +) +{{- end }} + // {{ .Name.Load }} returns the embedded CollectionSpec for {{ .Name }}. func {{ .Name.Load }}() (*ebpf.CollectionSpec, error) { reader := bytes.NewReader({{ .Name.Bytes }}) diff --git a/cmd/bpf2go/gen/output_test.go b/cmd/bpf2go/gen/output_test.go index 539620c26..b2a14101e 100644 --- a/cmd/bpf2go/gen/output_test.go +++ b/cmd/bpf2go/gen/output_test.go @@ -95,7 +95,7 @@ func TestCustomIdentifier(t *testing.T) { qt.Assert(t, qt.StringContains(buf.String(), "DO_THING")) } -func TestObjects(t *testing.T) { +func TestObjectsAndConstants(t *testing.T) { var buf bytes.Buffer args := GenerateArgs{ Package: "foo", @@ -117,6 +117,10 @@ func TestObjects(t *testing.T) { qt.Assert(t, qt.StringContains(str, "Map1 *ebpf.Map `ebpf:\"map1\"`")) qt.Assert(t, qt.StringContains(str, "Var1 *ebpf.Variable `ebpf:\"var_1\"`")) qt.Assert(t, qt.StringContains(str, "ProgFoo1 *ebpf.Program `ebpf:\"prog_foo_1\"`")) + + qt.Assert(t, qt.StringContains(str, "barMapNameMap1 = \"map1\"")) + qt.Assert(t, qt.StringContains(str, "barVariableNameVar1 = \"var_1\"")) + qt.Assert(t, qt.StringContains(str, "barProgramNameProgFoo1 = \"prog_foo_1\"")) } func TestGenerateStructTypes(t *testing.T) {