Debian Codegraph @

variable_test.go

raw symbols SCIP
1 package ebpf
2
3 import (
4 "encoding/binary"
5 "math"
6 "runtime"
7 "structs"
8 "sync/atomic"
9 "testing"
10 "time"
11 "unsafe"
12
13 "github.com/go-quicktest/qt"
14
15 "github.com/cilium/ebpf/btf"
16 "github.com/cilium/ebpf/internal"
17 "github.com/cilium/ebpf/internal/testutils"
18 )
19
20 func TestVariableSpec(t *testing.T) {
21 file := testutils.NativeFile(t, "testdata/variables-%s.elf")
22 spec, err := LoadCollectionSpec(file)
23 qt.Assert(t, qt.IsNil(err))
24
25 qt.Assert(t, qt.IsNil(spec.Variables["hidden"]))
26 qt.Assert(t, qt.IsNotNil(spec.Variables["weak"]))
27
28 const want uint32 = 12345
29
30 // Update a variable in each type of data section (.bss,.data,.rodata)
31 qt.Assert(t, qt.IsNil(spec.Variables["var_bss"].Set(want)))
32 qt.Assert(t, qt.IsNil(spec.Variables["var_data"].Set(want)))
33 qt.Assert(t, qt.IsNil(spec.Variables["var_rodata"].Set(want)))
34
35 var v uint32
36 qt.Assert(t, qt.IsNil(spec.Variables["var_bss"].Get(&v)))
37 qt.Assert(t, qt.Equals(v, want))
38 qt.Assert(t, qt.IsNil(spec.Variables["var_data"].Get(&v)))
39 qt.Assert(t, qt.Equals(v, want))
40 qt.Assert(t, qt.IsNil(spec.Variables["var_rodata"].Get(&v)))
41 qt.Assert(t, qt.Equals(v, want))
42
43 // Composite values.
44 type structT struct {
45 A, B uint64
46 }
47 qt.Assert(t, qt.IsNil(spec.Variables["var_struct"].Set(&structT{1, 2})))
48
49 var s structT
50 qt.Assert(t, qt.IsNil(spec.Variables["var_struct"].Get(&s)))
51 qt.Assert(t, qt.Equals(s, structT{1, 2}))
52 }
53
54 func TestVariableSpecCopy(t *testing.T) {
55 file := testutils.NativeFile(t, "testdata/variables-%s.elf")
56 spec, err := LoadCollectionSpec(file)
57 if err != nil {
58 t.Fatal(err)
59 }
60
61 cpy := spec.Copy()
62
63 // Update a variable in a section with only a single variable (.rodata).
64 const want uint32 = 0xfefefefe
65 wantb := []byte{0xfe, 0xfe, 0xfe, 0xfe} // Same byte sequence regardless of endianness
66 qt.Assert(t, qt.IsNil(cpy.Variables["var_rodata"].Set(want)))
67 qt.Assert(t, qt.DeepEquals(cpy.Variables["var_rodata"].Value, wantb))
68
69 // Verify that the original underlying MapSpec was not modified.
70 zero := make([]byte, 4)
71 qt.Assert(t, qt.DeepEquals(spec.Maps[".rodata"].Contents[0].Value.([]byte), zero))
72
73 // Check that modifications to the VariableSpec's Type don't affect the
74 // underlying MapSpec's type information on either the original or the copy.
75 cpy.Variables["var_rodata"].Type.Name = "modified"
76 spec.Variables["var_rodata"].Type.Name = "modified"
77
78 qt.Assert(t, qt.Equals(cpy.Maps[".rodata"].Value.(*btf.Datasec).Vars[0].Type.(*btf.Var).Name, "var_rodata"))
79 qt.Assert(t, qt.Equals(spec.Maps[".rodata"].Value.(*btf.Datasec).Vars[0].Type.(*btf.Var).Name, "var_rodata"))
80 }
81
82 func TestVariableSpecEmptyValue(t *testing.T) {
83 spec := &VariableSpec{
84 Type: &btf.Var{
85 Type: &btf.Int{
86 Size: 4,
87 },
88 },
89 }
90
91 value := uint32(0x12345678)
92 raw, err := binary.Append(nil, internal.NativeEndian, value)
93 qt.Assert(t, qt.IsNil(err))
94
95 qt.Assert(t, qt.IsNotNil(spec.Get(new(uint32))))
96
97 qt.Assert(t, qt.IsNotNil(spec.Set(uint64(0))), qt.Commentf("Setting a value of incorrect size should fail"))
98
99 qt.Assert(t, qt.IsNil(spec.Set(value)))
100 qt.Assert(t, qt.DeepEquals(spec.Value, raw))
101
102 spec.Value = nil
103 spec.Type = nil
104 qt.Assert(t, qt.IsNil(spec.Set(uint64(0))), qt.Commentf("Setting an empty value without a type should accept any type"))
105 qt.Assert(t, qt.HasLen(spec.Value, 8))
106 }
107
108 func mustReturn(tb testing.TB, prog *Program, value uint32) {
109 tb.Helper()
110
111 ret, _, err := prog.Test(internal.EmptyBPFContext)
112 qt.Assert(tb, qt.IsNil(err))
113 qt.Assert(tb, qt.Equals(ret, value))
114 }
115
116 func TestVariable(t *testing.T) {
117 testutils.SkipIfNotSupported(t, haveMmapableMaps())
118
119 file := testutils.NativeFile(t, "testdata/variables-%s.elf")
120 spec, err := LoadCollectionSpec(file)
121 qt.Assert(t, qt.IsNil(err))
122
123 obj := struct {
124 GetBSS *Program `ebpf:"get_bss"`
125 GetData *Program `ebpf:"get_data"`
126 CheckStruct *Program `ebpf:"check_struct"`
127
128 BSS *Variable `ebpf:"var_bss"`
129 Data *Variable `ebpf:"var_data"`
130 Struct *Variable `ebpf:"var_struct"`
131 Array *Variable `ebpf:"var_array"`
132 }{}
133
134 qt.Assert(t, qt.IsNil(loadAndAssign(t, spec, &obj, nil)))
135 t.Cleanup(func() {
136 obj.GetBSS.Close()
137 obj.GetData.Close()
138 obj.CheckStruct.Close()
139 })
140
141 mustReturn(t, obj.GetBSS, 0)
142 mustReturn(t, obj.GetData, 0)
143 mustReturn(t, obj.CheckStruct, 0)
144
145 want := uint32(4242424242)
146 qt.Assert(t, qt.IsNil(obj.BSS.Set(want)))
147 mustReturn(t, obj.GetBSS, want)
148 qt.Assert(t, qt.IsNil(obj.Data.Set(want)))
149 mustReturn(t, obj.GetData, want)
150 qt.Assert(t, qt.IsNil(obj.Struct.Set(&struct{ A, B uint64 }{0xa, 0xb})))
151 mustReturn(t, obj.CheckStruct, 1)
152
153 // Ensure page-aligned array variable can be accessed in its entirety.
154 arr := make([]byte, obj.Array.Size())
155 qt.Assert(t, qt.IsNil(obj.Array.Get(arr)))
156 qt.Assert(t, qt.IsNil(obj.Array.Set(arr)))
157
158 typ := obj.BSS.Type()
159 qt.Assert(t, qt.IsNotNil(typ))
160 i, ok := btf.As[*btf.Int](typ.Type)
161 qt.Assert(t, qt.IsTrue(ok))
162 qt.Assert(t, qt.Equals(i.Size, 4))
163
164 qt.Assert(t, qt.IsNotNil(obj.Data.Type()))
165 qt.Assert(t, qt.IsNotNil(obj.Struct.Type()))
166 }
167
168 func TestVariableConst(t *testing.T) {
169 testutils.SkipIfNotSupported(t, haveMmapableMaps())
170
171 file := testutils.NativeFile(t, "testdata/variables-%s.elf")
172 spec, err := LoadCollectionSpec(file)
173 qt.Assert(t, qt.IsNil(err))
174
175 want := uint32(12345)
176 qt.Assert(t, qt.IsNil(spec.Variables["var_rodata"].Set(want)))
177
178 obj := struct {
179 GetRodata *Program `ebpf:"get_rodata"`
180 Rodata *Variable `ebpf:"var_rodata"`
181 }{}
182
183 qt.Assert(t, qt.IsNil(loadAndAssign(t, spec, &obj, nil)))
184 t.Cleanup(func() {
185 obj.GetRodata.Close()
186 })
187
188 var got uint32
189 qt.Assert(t, qt.IsNil(obj.Rodata.Get(&got)))
190 qt.Assert(t, qt.Equals(got, want))
191 mustReturn(t, obj.GetRodata, want)
192
193 qt.Assert(t, qt.IsTrue(obj.Rodata.ReadOnly()))
194 qt.Assert(t, qt.ErrorIs(obj.Rodata.Set(want), ErrReadOnly))
195 }
196
197 func TestVariableFallback(t *testing.T) {
198 // LoadAndAssign should work on Variable regardless of BPF_F_MMAPABLE support.
199 file := testutils.NativeFile(t, "testdata/variables-%s.elf")
200 spec, err := LoadCollectionSpec(file)
201 qt.Assert(t, qt.IsNil(err))
202
203 obj := struct {
204 Data *Variable `ebpf:"var_data"`
205 }{}
206
207 mustLoadAndAssign(t, spec, &obj, nil)
208
209 // Expect either success or ErrNotSupported on all systems.
210 u32 := uint32(0)
211 if err := obj.Data.Get(&u32); err != nil {
212 qt.Assert(t, qt.ErrorIs(err, ErrNotSupported))
213 }
214
215 if err := obj.Data.Set(&u32); err != nil {
216 qt.Assert(t, qt.ErrorIs(err, ErrNotSupported))
217 }
218 }
219
220 func TestVariablePointer(t *testing.T) {
221 testutils.SkipIfNotSupported(t, haveMmapableMaps())
222
223 file := testutils.NativeFile(t, "testdata/variables-%s.elf")
224 spec, err := LoadCollectionSpec(file)
225 qt.Assert(t, qt.IsNil(err))
226
227 obj := struct {
228 AddAtomic *Program `ebpf:"add_atomic"`
229 CheckStructPad *Program `ebpf:"check_struct_pad"`
230 CheckArray *Program `ebpf:"check_array"`
231
232 Atomic *Variable `ebpf:"var_atomic"`
233 StructPad *Variable `ebpf:"var_struct_pad"`
234 Array *Variable `ebpf:"var_array"`
235 }{}
236
237 unsafeMemory = true
238 t.Cleanup(func() {
239 unsafeMemory = false
240 })
241
242 qt.Assert(t, qt.IsNil(loadAndAssign(t, spec, &obj, nil)))
243 t.Cleanup(func() {
244 obj.AddAtomic.Close()
245 obj.CheckStructPad.Close()
246 obj.CheckArray.Close()
247 })
248
249 // Bump the value by 1 using a bpf program.
250 want := uint32(1338)
251 a32, err := VariablePointer[atomic.Uint32](obj.Atomic)
252 qt.Assert(t, qt.IsNil(err))
253 a32.Store(want - 1)
254
255 mustReturn(t, obj.AddAtomic, 0)
256 qt.Assert(t, qt.Equals(a32.Load(), want))
257
258 _, err = VariablePointer[*uint32](obj.Atomic)
259 qt.Assert(t, qt.ErrorIs(err, ErrInvalidType))
260
261 _, err = VariablePointer[struct{ _ *uint64 }](obj.StructPad)
262 qt.Assert(t, qt.ErrorIs(err, ErrInvalidType))
263
264 type S struct {
265 _ structs.HostLayout
266 A uint32
267 B uint64
268 C uint16
269 D [5]byte
270 E uint64
271 }
272
273 s, err := VariablePointer[S](obj.StructPad)
274 qt.Assert(t, qt.IsNil(err))
275 *s = S{A: 0xa, B: 0xb, C: 0xc, D: [5]byte{0xd, 0, 0, 0, 0}, E: 0xe}
276 mustReturn(t, obj.CheckStructPad, 1)
277
278 a, err := VariablePointer[[8192]byte](obj.Array)
279 qt.Assert(t, qt.IsNil(err))
280 a[len(a)-1] = 0xff
281 mustReturn(t, obj.CheckArray, 1)
282 }
283
284 func TestVariablePointerError(t *testing.T) {
285 testutils.SkipIfNotSupported(t, haveMmapableMaps())
286
287 file := testutils.NativeFile(t, "testdata/variables-%s.elf")
288 spec, err := LoadCollectionSpec(file)
289 qt.Assert(t, qt.IsNil(err))
290
291 obj := struct {
292 Atomic *Variable `ebpf:"var_atomic"`
293 }{}
294
295 qt.Assert(t, qt.IsNil(loadAndAssign(t, spec, &obj, nil)))
296
297 _, err = VariablePointer[atomic.Uint32](obj.Atomic)
298 qt.Assert(t, qt.ErrorIs(err, ErrNotSupported))
299 }
300
301 func TestVariablePointerOffsetOverflow(t *testing.T) {
302 mm := &Memory{b: make([]byte, 8)}
303
304 // An offset whose end wraps around uint32 must be rejected rather than
305 // accepted and later used to index into the backing slice.
306 _, err := newVariable("overflow", math.MaxUint32-3, 4, nil, mm)
307 qt.Assert(t, qt.IsNotNil(err))
308
309 // Even if a Variable carries such an offset, taking a pointer to it returns
310 // an error instead of panicking with an out-of-range index.
311 v := &Variable{name: "overflow", offset: math.MaxUint32 - 3, size: 4, mm: mm}
312 _, err = VariablePointer[uint32](v)
313 qt.Assert(t, qt.IsNotNil(err))
314 }
315
316 func TestVariablePointerGC(t *testing.T) {
317 testutils.SkipIfNotSupported(t, haveMmapableMaps())
318
319 file := testutils.NativeFile(t, "testdata/variables-%s.elf")
320 spec, err := LoadCollectionSpec(file)
321 qt.Assert(t, qt.IsNil(err))
322
323 cancel := make(chan struct{})
324
325 type obj_s struct {
326 AddAtomic *Program `ebpf:"add_atomic"`
327 Atomic *Variable `ebpf:"var_atomic"`
328 AtomicMap *Map `ebpf:".data.atomic"`
329 }
330
331 unsafeMemory = true
332 t.Cleanup(func() {
333 unsafeMemory = false
334 })
335 var obj obj_s
336 qt.Assert(t, qt.IsNil(loadAndAssign(t, spec, &obj, nil)))
337
338 // Set cleanup on obj to get notified when it is collected.
339 ogc := make(chan struct{})
340 runtime.AddCleanup(&obj, func(*byte) {
341 close(ogc)
342 }, nil)
343 mem, err := obj.AtomicMap.unsafeMemory()
344 qt.Assert(t, qt.IsNil(err))
345 obj.AtomicMap.Close()
346
347 // Start a goroutine that panics if the finalizer runs before we expect it to.
348 mgc := make(chan struct{})
349 go func() {
350 select {
351 case <-mgc:
352 panic("memory cleanup ran unexpectedly")
353 case <-cancel:
354 return
355 }
356 }()
357
358 // Set cleanup on the Memory's backing array to get notified when it is
359 // collected.
360 runtime.AddCleanup(unsafe.SliceData(mem.b), func(*byte) {
361 close(mgc)
362 }, nil)
363
364 // Pull out Program handle and Variable pointer so reference to obj is
365 // dropped.
366 prog := obj.AddAtomic
367 t.Cleanup(func() {
368 prog.Close()
369 })
370
371 a32, err := VariablePointer[atomic.Uint32](obj.Atomic)
372 qt.Assert(t, qt.IsNil(err))
373
374 // No references to obj past this point. Trigger GC and wait for the obj
375 // finalizer to complete.
376 runtime.GC()
377 testutils.WaitChan(t, ogc, time.Second)
378
379 // Trigger prog and read memory to ensure variable reference is still valid.
380 mustReturn(t, prog, 0)
381 qt.Assert(t, qt.Equals(a32.Load(), 1))
382
383 // Close the cancel channel while holding a backing array reference to avoid
384 // false-positive panics in case we get a GC cycle before the manual call to
385 // runtime.GC below.
386 close(cancel)
387 runtime.KeepAlive(a32)
388
389 // More GC cycles to collect the backing array. As long as the unsafe memory
390 // implementation is still on SetFinalizer, this needs multiple cycles to
391 // work, since finalizers can resurrect objects. 3 GCs seems to work reliably.
392 runtime.GC()
393 runtime.GC()
394 runtime.GC()
395
396 // Wait for backing array to be finalized.
397 testutils.WaitChan(t, mgc, time.Second*5)
398 }