Skip to content

Commit fd33a78

Browse files
committed
btf: add Builder.Spec
When collecting and merging BTF types from multiple ELFs, it's convenient to be able to query the resulting Spec in a single step. This commit adds the Builder.Spec method to avoid having to write the BTF blob out to a file and read it back from the filesystem. Also add a test that checks if two identical types get correctly deduplicated so they can be queried with AnyTypeByName afterwards. Signed-off-by: Timo Beckers <timo@isovalent.com>
1 parent 1d2a2ae commit fd33a78

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

btf/marshal.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,6 +168,19 @@ func (b *Builder) Add(typ Type) (TypeID, error) {
168168
return id, nil
169169
}
170170

171+
// Spec marshals the Builder's types and returns a new Spec to query them.
172+
//
173+
// The resulting Spec does not share any state with the Builder, subsequent
174+
// additions to the Builder will not affect the Spec.
175+
func (b *Builder) Spec() (*Spec, error) {
176+
buf, err := b.Marshal(make([]byte, 0), nil)
177+
if err != nil {
178+
return nil, err
179+
}
180+
181+
return loadRawSpec(buf, nil)
182+
}
183+
171184
// Marshal encodes all types in the Marshaler into BTF wire format.
172185
//
173186
// opts may be nil.

btf/marshal_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,22 @@ func TestBuilderAdd(t *testing.T) {
6868
qt.Assert(t, qt.Equals(id, TypeID(3)))
6969
}
7070

71+
func TestBuilderSpec(t *testing.T) {
72+
b, err := NewBuilder([]Type{
73+
&Int{Name: "foo", Size: 2},
74+
&Int{Name: "foo", Size: 2},
75+
}, &BuilderOptions{Deduplicate: true})
76+
qt.Assert(t, qt.IsNil(err))
77+
78+
spec, err := b.Spec()
79+
qt.Assert(t, qt.IsNil(err))
80+
81+
// With deduplication enabled, both ints should be merged into one,
82+
// allowing queries with AnyTypeByName.
83+
_, err = spec.AnyTypeByName("foo")
84+
qt.Assert(t, qt.IsNil(err))
85+
}
86+
7187
func TestRoundtripVMlinux(t *testing.T) {
7288
types := typesFromSpec(t, vmlinuxSpec(t))
7389

0 commit comments

Comments
 (0)