From eafdbd271980382d7425b4489f8f3b0f0120ec4f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matth=C3=ADas=20=C3=81=2E=20J=C3=B3nsson?= Date: Tue, 2 Sep 2025 11:22:15 +0000 Subject: [PATCH] bpf2go: Generate constant names for maps, programs, and variables MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matthías Á. Jónsson --- cmd/bpf2go/gen/output.tpl | 28 ++++++++++++++++++++++++++++ cmd/bpf2go/gen/output_test.go | 6 +++++- 2 files changed, 33 insertions(+), 1 deletion(-) 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) {