Skip to content

Commit 3f9adc7

Browse files
RonFedti-mo
andcommitted
bpf2go: import package structs when all structs are typedefs
When deciding whether to import package structs, the logic only considered typical struct declarations. Typedefs also need to be taken into account. Signed-off-by: Ron Federman <ron@odigos.io> Co-authored-by: Timo Beckers <timo@isovalent.com>
1 parent df9ebe8 commit 3f9adc7

2 files changed

Lines changed: 54 additions & 1 deletion

File tree

cmd/bpf2go/gen/output.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ func Generate(args GenerateArgs) error {
169169
if err != nil {
170170
return fmt.Errorf("generating %s: %w", name, err)
171171
}
172-
_, ok := typ.(*btf.Struct)
172+
_, ok := btf.As[*btf.Struct](typ)
173173
needsStructsPkg = needsStructsPkg || ok
174174
typeDecls = append(typeDecls, decl)
175175
}

cmd/bpf2go/gen/output_test.go

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,3 +118,56 @@ func TestObjects(t *testing.T) {
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\"`"))
120120
}
121+
122+
func TestGenerateStructTypes(t *testing.T) {
123+
ts := &btf.Struct{
124+
Name: "test_struct",
125+
Size: 8,
126+
Members: []btf.Member{
127+
{
128+
Name: "field1",
129+
Type: &btf.Int{Size: 8, Encoding: btf.Unsigned},
130+
Offset: 0,
131+
},
132+
},
133+
}
134+
td := &btf.Typedef{
135+
Name: "test_typedef",
136+
Type: ts,
137+
}
138+
139+
tests := []struct {
140+
name string
141+
types []btf.Type
142+
expected string
143+
}{
144+
{
145+
name: "simple struct",
146+
types: []btf.Type{ts},
147+
expected: "type stemTestStruct struct {\n\t_ structs.HostLayout\n\tField1 uint64\n}",
148+
},
149+
{
150+
name: "typedef struct",
151+
types: []btf.Type{td},
152+
expected: "type stemTestTypedef struct {\n\t_ structs.HostLayout\n\tField1 uint64\n}",
153+
},
154+
}
155+
156+
for _, tt := range tests {
157+
t.Run(tt.name, func(t *testing.T) {
158+
var buf bytes.Buffer
159+
err := Generate(GenerateArgs{
160+
Package: "test",
161+
Stem: "stem",
162+
Types: tt.types,
163+
Output: &buf,
164+
Constraints: nil,
165+
})
166+
qt.Assert(t, qt.IsNil(err))
167+
168+
str := buf.String()
169+
qt.Assert(t, qt.StringContains(str, tt.expected))
170+
qt.Assert(t, qt.StringContains(str, "\"structs\""))
171+
})
172+
}
173+
}

0 commit comments

Comments
 (0)