forked from cilium/ebpf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
info_test.go
430 lines (362 loc) · 9.88 KB
/
info_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
package ebpf
import (
"errors"
"fmt"
"os"
"strings"
"testing"
"github.com/go-quicktest/qt"
"github.com/cilium/ebpf/asm"
"github.com/cilium/ebpf/btf"
"github.com/cilium/ebpf/internal"
"github.com/cilium/ebpf/internal/sys"
"github.com/cilium/ebpf/internal/testutils"
"github.com/cilium/ebpf/internal/unix"
)
func TestMapInfoFromProc(t *testing.T) {
hash, err := NewMap(&MapSpec{
Name: "testing",
Type: Hash,
KeySize: 4,
ValueSize: 5,
MaxEntries: 2,
Flags: unix.BPF_F_NO_PREALLOC,
})
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal(err)
}
defer hash.Close()
info, err := newMapInfoFromProc(hash.fd)
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal("Can't get map info:", err)
}
if info.Type != Hash {
t.Error("Expected Hash, got", info.Type)
}
if info.KeySize != 4 {
t.Error("Expected KeySize of 4, got", info.KeySize)
}
if info.ValueSize != 5 {
t.Error("Expected ValueSize of 5, got", info.ValueSize)
}
if info.MaxEntries != 2 {
t.Error("Expected MaxEntries of 2, got", info.MaxEntries)
}
if info.Flags != unix.BPF_F_NO_PREALLOC {
t.Errorf("Expected Flags to be %d, got %d", unix.BPF_F_NO_PREALLOC, info.Flags)
}
if info.Name != "" && info.Name != "testing" {
t.Error("Expected name to be testing, got", info.Name)
}
if _, ok := info.ID(); ok {
t.Error("Expected ID to not be available")
}
nested, err := NewMap(&MapSpec{
Type: ArrayOfMaps,
KeySize: 4,
MaxEntries: 2,
InnerMap: &MapSpec{
Type: Array,
KeySize: 4,
ValueSize: 4,
MaxEntries: 2,
},
})
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal(err)
}
defer nested.Close()
_, err = newMapInfoFromProc(nested.fd)
if err != nil {
t.Fatal("Can't get nested map info from /proc:", err)
}
}
func TestProgramInfo(t *testing.T) {
prog := mustSocketFilter(t)
for name, fn := range map[string]func(*sys.FD) (*ProgramInfo, error){
"generic": newProgramInfoFromFd,
"proc": newProgramInfoFromProc,
} {
t.Run(name, func(t *testing.T) {
info, err := fn(prog.fd)
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal("Can't get program info:", err)
}
if info.Type != SocketFilter {
t.Error("Expected Type to be SocketFilter, got", info.Type)
}
if info.Name != "" && info.Name != "test" {
t.Error("Expected Name to be test, got", info.Name)
}
if want := "d7edec644f05498d"; info.Tag != want {
t.Errorf("Expected Tag to be %s, got %s", want, info.Tag)
}
if id, ok := info.ID(); ok && id == 0 {
t.Error("Expected a valid ID:", id)
} else if name == "proc" && ok {
t.Error("Expected ID to not be available")
}
if name == "proc" {
_, ok := info.CreatedByUID()
qt.Assert(t, qt.IsFalse(ok))
} else {
uid, ok := info.CreatedByUID()
if testutils.IsKernelLessThan(t, "4.15") {
qt.Assert(t, qt.IsFalse(ok))
} else {
qt.Assert(t, qt.IsTrue(ok))
qt.Assert(t, qt.Equals(uid, uint32(os.Getuid())))
}
}
})
}
}
func TestProgramInfoMapIDs(t *testing.T) {
arr, err := NewMap(&MapSpec{
Type: Array,
KeySize: 4,
ValueSize: 4,
MaxEntries: 1,
})
qt.Assert(t, qt.IsNil(err))
defer arr.Close()
prog, err := NewProgram(&ProgramSpec{
Type: SocketFilter,
Instructions: asm.Instructions{
asm.LoadMapPtr(asm.R0, arr.FD()),
asm.LoadImm(asm.R0, 2, asm.DWord),
asm.Return(),
},
License: "MIT",
})
qt.Assert(t, qt.IsNil(err))
defer prog.Close()
info, err := prog.Info()
testutils.SkipIfNotSupported(t, err)
qt.Assert(t, qt.IsNil(err))
ids, ok := info.MapIDs()
switch {
case testutils.IsKernelLessThan(t, "4.15"):
qt.Assert(t, qt.IsFalse(ok))
qt.Assert(t, qt.HasLen(ids, 0))
default:
qt.Assert(t, qt.IsTrue(ok))
mapInfo, err := arr.Info()
qt.Assert(t, qt.IsNil(err))
mapID, ok := mapInfo.ID()
qt.Assert(t, qt.IsTrue(ok))
qt.Assert(t, qt.ContentEquals(ids, []MapID{mapID}))
}
}
func TestProgramInfoMapIDsNoMaps(t *testing.T) {
prog, err := NewProgram(&ProgramSpec{
Type: SocketFilter,
Instructions: asm.Instructions{
asm.LoadImm(asm.R0, 0, asm.DWord),
asm.Return(),
},
License: "MIT",
})
qt.Assert(t, qt.IsNil(err))
defer prog.Close()
info, err := prog.Info()
testutils.SkipIfNotSupported(t, err)
qt.Assert(t, qt.IsNil(err))
ids, ok := info.MapIDs()
switch {
case testutils.IsKernelLessThan(t, "4.15"):
qt.Assert(t, qt.IsFalse(ok))
qt.Assert(t, qt.HasLen(ids, 0))
default:
qt.Assert(t, qt.IsTrue(ok))
qt.Assert(t, qt.HasLen(ids, 0))
}
}
func TestScanFdInfoReader(t *testing.T) {
tests := []struct {
fields map[string]interface{}
valid bool
}{
{nil, true},
{map[string]interface{}{"foo": new(string)}, true},
{map[string]interface{}{"zap": new(string)}, false},
{map[string]interface{}{"foo": new(int)}, false},
}
for _, test := range tests {
err := scanFdInfoReader(strings.NewReader("foo:\tbar\n"), test.fields)
if test.valid {
if err != nil {
t.Errorf("fields %v returns an error: %s", test.fields, err)
}
} else {
if err == nil {
t.Errorf("fields %v doesn't return an error", test.fields)
}
}
}
}
// TestStats loads a BPF program once and executes back-to-back test runs
// of the program. See testStats for details.
func TestStats(t *testing.T) {
testutils.SkipOnOldKernel(t, "5.8", "BPF_ENABLE_STATS")
prog := mustSocketFilter(t)
pi, err := prog.Info()
if err != nil {
t.Errorf("failed to get ProgramInfo: %v", err)
}
rc, ok := pi.RunCount()
if !ok {
t.Errorf("expected run count info to be available")
}
if rc != 0 {
t.Errorf("expected a run count of 0 but got %d", rc)
}
rt, ok := pi.Runtime()
if !ok {
t.Errorf("expected runtime info to be available")
}
if rt != 0 {
t.Errorf("expected a runtime of 0ns but got %v", rt)
}
if err := testStats(prog); err != nil {
t.Error(err)
}
}
// BenchmarkStats is a benchmark of TestStats. See testStats for details.
func BenchmarkStats(b *testing.B) {
testutils.SkipOnOldKernel(b, "5.8", "BPF_ENABLE_STATS")
prog := mustSocketFilter(b)
for n := 0; n < b.N; n++ {
if err := testStats(prog); err != nil {
b.Fatal(fmt.Errorf("iter %d: %w", n, err))
}
}
}
// testStats implements the behaviour under test for TestStats
// and BenchmarkStats. First, a test run is executed with runtime statistics
// enabled, followed by another with runtime stats disabled. Counters are only
// expected to increase on the runs where runtime stats are enabled.
//
// Due to runtime behaviour on Go 1.14 and higher, the syscall backing
// (*Program).Test() could be invoked multiple times for each call to Test(),
// resulting in RunCount incrementing by more than one. Expecting RunCount to
// be of a specific value after a call to Test() is therefore not possible.
// See https://golang.org/doc/go1.14#runtime for more details.
func testStats(prog *Program) error {
in := internal.EmptyBPFContext
stats, err := EnableStats(uint32(unix.BPF_STATS_RUN_TIME))
if err != nil {
return fmt.Errorf("failed to enable stats: %v", err)
}
defer stats.Close()
// Program execution with runtime statistics enabled.
// Should increase both runtime and run counter.
if _, _, err := prog.Test(in); err != nil {
return fmt.Errorf("failed to trigger program: %v", err)
}
pi, err := prog.Info()
if err != nil {
return fmt.Errorf("failed to get ProgramInfo: %v", err)
}
rc, ok := pi.RunCount()
if !ok {
return errors.New("expected run count info to be available")
}
if rc < 1 {
return fmt.Errorf("expected a run count of at least 1 but got %d", rc)
}
// Store the run count for the next invocation.
lc := rc
rt, ok := pi.Runtime()
if !ok {
return errors.New("expected runtime info to be available")
}
if rt == 0 {
return errors.New("expected a runtime other than 0ns")
}
// Store the runtime value for the next invocation.
lt := rt
if err := stats.Close(); err != nil {
return fmt.Errorf("failed to disable statistics: %v", err)
}
// Second program execution, with runtime statistics gathering disabled.
// Total runtime and run counters are not expected to increase.
if _, _, err := prog.Test(in); err != nil {
return fmt.Errorf("failed to trigger program: %v", err)
}
pi, err = prog.Info()
if err != nil {
return fmt.Errorf("failed to get ProgramInfo: %v", err)
}
rc, ok = pi.RunCount()
if !ok {
return errors.New("expected run count info to be available")
}
if rc != lc {
return fmt.Errorf("run count unexpectedly increased over previous value (current: %v, prev: %v)", rc, lc)
}
rt, ok = pi.Runtime()
if !ok {
return errors.New("expected runtime info to be available")
}
if rt != lt {
return fmt.Errorf("runtime unexpectedly increased over the previous value (current: %v, prev: %v)", rt, lt)
}
return nil
}
func TestHaveProgramInfoMapIDs(t *testing.T) {
testutils.CheckFeatureTest(t, haveProgramInfoMapIDs)
}
func TestProgInfoExtBTF(t *testing.T) {
testutils.SkipOnOldKernel(t, "5.0", "Program BTF (func/line_info)")
spec, err := LoadCollectionSpec(fmt.Sprintf("testdata/loader-%s.elf", internal.ClangEndian))
if err != nil {
t.Fatal(err)
}
var obj struct {
Main *Program `ebpf:"xdp_prog"`
}
err = spec.LoadAndAssign(&obj, nil)
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal(err)
}
defer obj.Main.Close()
info, err := obj.Main.Info()
if err != nil {
t.Fatal(err)
}
inst, err := info.Instructions()
if err != nil {
t.Fatal(err)
}
expectedLineInfoCount := 26
expectedFuncInfo := map[string]bool{
"xdp_prog": false,
"static_fn": false,
"global_fn2": false,
"global_fn3": false,
}
lineInfoCount := 0
for _, ins := range inst {
if ins.Source() != nil {
lineInfoCount++
}
fn := btf.FuncMetadata(&ins)
if fn != nil {
expectedFuncInfo[fn.Name] = true
}
}
if lineInfoCount != expectedLineInfoCount {
t.Errorf("expected %d line info entries, got %d", expectedLineInfoCount, lineInfoCount)
}
for fn, found := range expectedFuncInfo {
if !found {
t.Errorf("func %q not found", fn)
}
}
}