-
Notifications
You must be signed in to change notification settings - Fork 842
Expand file tree
/
Copy pathinfo_test.go
More file actions
616 lines (502 loc) · 14.7 KB
/
info_test.go
File metadata and controls
616 lines (502 loc) · 14.7 KB
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
package ebpf
import (
"fmt"
"os"
"reflect"
"runtime"
"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"
)
var btfFn = &btf.Func{
Name: "_",
Type: &btf.FuncProto{
Return: &btf.Int{Size: 16},
Params: []btf.FuncParam{},
},
Linkage: btf.StaticFunc,
}
var hashMapSpec = &MapSpec{
Type: Hash,
KeySize: 4,
ValueSize: 5,
MaxEntries: 2,
Flags: sys.BPF_F_NO_PREALLOC,
}
var multiprogSpec = &ProgramSpec{
Name: "test",
Type: SocketFilter,
Instructions: asm.Instructions{
btf.WithFuncMetadata(asm.LoadImm(asm.R0, 0, asm.DWord), btfFn).
WithSource(asm.Comment("line info")),
asm.Call.Label("fn"),
asm.Return(),
btf.WithFuncMetadata(asm.LoadImm(asm.R0, 0, asm.DWord), btfFn).
WithSource(asm.Comment("line info")).WithSymbol("fn"),
asm.Return(),
},
License: "MIT",
}
func validateMapInfo(t *testing.T, info *MapInfo, spec *MapSpec) {
t.Helper()
qt.Assert(t, qt.Equals(info.Type, spec.Type))
qt.Assert(t, qt.Equals(info.KeySize, spec.KeySize))
qt.Assert(t, qt.Equals(info.ValueSize, spec.ValueSize))
qt.Assert(t, qt.Equals(info.MaxEntries, spec.MaxEntries))
qt.Assert(t, qt.Equals(info.Flags, spec.Flags))
memlock, _ := info.Memlock()
qt.Assert(t, qt.Not(qt.Equals(memlock, 0)))
}
func TestMapInfo(t *testing.T) {
m := mustNewMap(t, hashMapSpec, nil)
info, err := m.Info()
qt.Assert(t, qt.IsNil(err))
validateMapInfo(t, info, hashMapSpec)
}
func TestMapInfoFromProc(t *testing.T) {
hash := mustNewMap(t, hashMapSpec, nil)
var info MapInfo
err := readMapInfoFromProc(hash.fd, &info)
testutils.SkipIfNotSupported(t, err)
qt.Assert(t, qt.IsNil(err))
validateMapInfo(t, &info, hashMapSpec)
}
func TestMapInfoFromProcOuterMap(t *testing.T) {
outer := &MapSpec{
Type: ArrayOfMaps,
KeySize: 4,
ValueSize: 4,
MaxEntries: 2,
InnerMap: &MapSpec{
Type: Array,
KeySize: 4,
ValueSize: 4,
MaxEntries: 2,
},
}
m := mustNewMap(t, outer, nil)
var info MapInfo
err := readMapInfoFromProc(m.fd, &info)
testutils.SkipIfNotSupported(t, err)
qt.Assert(t, qt.IsNil(err))
validateMapInfo(t, &info, outer)
}
func BenchmarkNewMapFromFD(b *testing.B) {
b.ReportAllocs()
m := mustNewMap(b, hashMapSpec, nil)
for b.Loop() {
if _, err := newMapFromFD(m.fd); err != nil {
b.Fatal(err)
}
}
}
func BenchmarkMapInfo(b *testing.B) {
b.ReportAllocs()
m := mustNewMap(b, hashMapSpec, nil)
for b.Loop() {
if _, err := newMapInfoFromFd(m.fd); err != nil {
b.Fatal(err)
}
}
}
func validateProgInfo(t *testing.T, spec *ProgramSpec, info *ProgramInfo) {
t.Helper()
qt.Assert(t, qt.Equals(info.Type, spec.Type))
if info.Tag != "" {
qt.Assert(t, qt.SliceAny(
[]string{
"d7edec644f05498d", // SHA1, pre-6.18
"01e57aadad14352b", // SHA256
},
qt.F2(qt.Equals, info.Tag),
))
}
memlock, ok := info.Memlock()
if ok {
qt.Assert(t, qt.Equals(memlock, uint64(os.Getpagesize())))
}
}
func TestProgramInfo(t *testing.T) {
spec := fixupProgramSpec(basicProgramSpec)
prog := mustNewProgram(t, spec, nil)
info, err := newProgramInfoFromFd(prog.fd)
testutils.SkipIfNotSupported(t, err)
qt.Assert(t, qt.IsNil(err))
validateProgInfo(t, spec, info)
id, ok := info.ID()
qt.Assert(t, qt.IsTrue(ok))
qt.Assert(t, qt.Not(qt.Equals(id, 0)))
if testutils.IsVersionLessThan(t, "4.15", "windows:0.20") {
qt.Assert(t, qt.Equals(info.Name, ""))
} else {
qt.Assert(t, qt.Equals(info.Name, "test"))
}
if jitedSize, err := info.JitedSize(); testutils.IsVersionLessThan(t, "4.13") {
qt.Assert(t, qt.IsNotNil(err))
} else {
qt.Assert(t, qt.IsNil(err))
qt.Assert(t, qt.IsTrue(jitedSize > 0))
}
if xlatedSize, err := info.TranslatedSize(); testutils.IsVersionLessThan(t, "4.13") {
qt.Assert(t, qt.IsNotNil(err))
} else {
qt.Assert(t, qt.IsNil(err))
qt.Assert(t, qt.IsTrue(xlatedSize > 0))
}
if uid, ok := info.CreatedByUID(); testutils.IsVersionLessThan(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())))
}
if loadTime, ok := info.LoadTime(); testutils.IsVersionLessThan(t, "4.15") {
qt.Assert(t, qt.IsFalse(ok))
} else {
qt.Assert(t, qt.IsTrue(ok))
qt.Assert(t, qt.IsTrue(loadTime > 0))
}
if verifiedInsns, ok := info.VerifiedInstructions(); testutils.IsVersionLessThan(t, "5.16") {
qt.Assert(t, qt.IsFalse(ok))
} else {
qt.Assert(t, qt.IsTrue(ok))
qt.Assert(t, qt.IsTrue(verifiedInsns > 0))
}
if insns, ok := info.JitedInsns(); testutils.IsVersionLessThan(t, "4.13") {
qt.Assert(t, qt.IsFalse(ok))
} else {
qt.Assert(t, qt.IsTrue(ok))
qt.Assert(t, qt.IsTrue(len(insns) > 0))
}
}
func BenchmarkNewProgramFromFD(b *testing.B) {
b.ReportAllocs()
spec := fixupProgramSpec(basicProgramSpec)
prog := mustNewProgram(b, spec, nil)
for b.Loop() {
if _, err := newProgramFromFD(prog.fd); err != nil {
b.Fatal(err)
}
}
}
func BenchmarkProgramInfo(b *testing.B) {
b.ReportAllocs()
spec := fixupProgramSpec(basicProgramSpec)
prog := mustNewProgram(b, spec, nil)
for b.Loop() {
if _, err := newProgramInfoFromFd(prog.fd); err != nil {
b.Fatal(err)
}
}
}
func TestProgramInfoProc(t *testing.T) {
spec := fixupProgramSpec(basicProgramSpec)
prog := mustNewProgram(t, spec, nil)
var info ProgramInfo
err := readProgramInfoFromProc(prog.fd, &info)
testutils.SkipIfNotSupported(t, err)
qt.Assert(t, qt.IsNil(err))
validateProgInfo(t, spec, &info)
}
func TestProgramInfoBTF(t *testing.T) {
prog, err := newProgram(t, multiprogSpec, nil)
testutils.SkipIfNotSupported(t, err)
qt.Assert(t, qt.IsNil(err))
info, err := prog.Info()
testutils.SkipIfNotSupported(t, err)
qt.Assert(t, qt.IsNil(err))
// On kernels before 5.x, nr_jited_ksyms is not set for programs without subprogs.
// It's included here since this test uses a bpf program with subprogs.
if addrs, ok := info.JitedKsymAddrs(); testutils.IsVersionLessThan(t, "4.18") {
qt.Assert(t, qt.IsFalse(ok))
} else {
qt.Assert(t, qt.IsTrue(ok))
qt.Assert(t, qt.IsTrue(len(addrs) > 0))
}
if lens, ok := info.JitedFuncLens(); testutils.IsVersionLessThan(t, "4.18") {
qt.Assert(t, qt.IsFalse(ok))
} else {
qt.Assert(t, qt.IsTrue(ok))
qt.Assert(t, qt.IsTrue(len(lens) > 0))
}
if infos, ok := info.JitedLineInfos(); testutils.IsVersionLessThan(t, "5.0") {
qt.Assert(t, qt.IsFalse(ok))
} else {
qt.Assert(t, qt.IsTrue(ok))
qt.Assert(t, qt.IsTrue(len(infos) > 0))
}
if funcs, err := info.FuncInfos(); testutils.IsVersionLessThan(t, "5.0") {
qt.Assert(t, qt.IsNotNil(err))
} else {
qt.Assert(t, qt.IsNil(err))
qt.Assert(t, qt.HasLen(funcs, 2))
qt.Assert(t, qt.ContentEquals(funcs[0].Func, btfFn))
qt.Assert(t, qt.ContentEquals(funcs[1].Func, btfFn))
}
if lines, err := info.LineInfos(); testutils.IsVersionLessThan(t, "5.0") {
qt.Assert(t, qt.IsNotNil(err))
} else {
qt.Assert(t, qt.IsNil(err))
qt.Assert(t, qt.HasLen(lines, 2))
qt.Assert(t, qt.Equals(lines[0].Line.Line(), "line info"))
qt.Assert(t, qt.Equals(lines[1].Line.Line(), "line info"))
}
}
func TestProgramInfoMapIDs(t *testing.T) {
arr := createMap(t, Array, 1)
prog := mustNewProgram(t, &ProgramSpec{
Type: SocketFilter,
Instructions: asm.Instructions{
asm.LoadMapPtr(asm.R0, arr.FD()),
asm.LoadImm(asm.R0, 2, asm.DWord),
asm.Return(),
},
License: "MIT",
}, nil)
info, err := prog.Info()
testutils.SkipIfNotSupported(t, err)
qt.Assert(t, qt.IsNil(err))
ids, ok := info.MapIDs()
switch {
case testutils.IsVersionLessThan(t, "4.15", "windows:0.20"):
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 := createBasicProgram(t)
info, err := prog.Info()
testutils.SkipIfNotSupported(t, err)
qt.Assert(t, qt.IsNil(err))
ids, ok := info.MapIDs()
switch {
case testutils.IsVersionLessThan(t, "4.15", "windows:0.20"):
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)
}
}
}
}
func BenchmarkScanFdInfoReader(b *testing.B) {
b.ReportAllocs()
// Pathological case with 9 fields we're not interested in, and one
// field we are, all the way at the very end.
input := strings.Repeat("ignore:\tthis\n", 9)
input += "foo:\tbar\n"
r := strings.NewReader(input)
var val string
fields := map[string]any{"foo": &val}
for b.Loop() {
val = ""
r.Reset(input)
if err := scanFdInfoReader(r, fields); err != nil {
b.Fatal(err)
}
if val != "bar" {
b.Fatal("unexpected value:", val)
}
}
}
// TestProgramStats loads a BPF program once and executes back-to-back test runs
// of the program. See testStats for details.
func TestProgramStats(t *testing.T) {
testutils.SkipOnOldKernel(t, "5.8", "BPF_ENABLE_STATS")
prog := createBasicProgram(t)
s, err := prog.Stats()
qt.Assert(t, qt.IsNil(err))
qt.Assert(t, qt.Equals(s.RunCount, 0))
qt.Assert(t, qt.Equals(s.RecursionMisses, 0))
if runtime.GOARCH != "arm64" {
// Runtime is flaky on arm64.
qt.Assert(t, qt.Equals(s.Runtime, 0))
}
if err := testStats(t, prog); err != nil {
testutils.SkipIfNotSupportedOnOS(t, err)
t.Error(err)
}
}
// BenchmarkStats is a benchmark of TestStats. See testStats for details.
func BenchmarkStats(b *testing.B) {
b.ReportAllocs()
testutils.SkipOnOldKernel(b, "5.8", "BPF_ENABLE_STATS")
prog := createBasicProgram(b)
for b.Loop() {
if err := testStats(b, prog); err != nil {
testutils.SkipIfNotSupportedOnOS(b, err)
b.Fatal(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(tb testing.TB, prog *Program) error {
tb.Helper()
in := internal.EmptyBPFContext
stats, err := EnableStats(uint32(sys.BPF_STATS_RUN_TIME))
if err != nil {
return fmt.Errorf("failed to enable stats: %w", err)
}
defer stats.Close()
// Program execution with runtime statistics enabled.
// Should increase both runtime and run counter.
mustRun(tb, prog, &RunOptions{Data: in})
s1, err := prog.Stats()
qt.Assert(tb, qt.IsNil(err))
qt.Assert(tb, qt.Not(qt.Equals(s1.RunCount, 0)), qt.Commentf("expected run count to be at least 1 after first invocation"))
qt.Assert(tb, qt.Not(qt.Equals(s1.Runtime, 0)), qt.Commentf("expected runtime to be at least 1ns after first invocation"))
qt.Assert(tb, qt.IsNil(stats.Close()))
// Second program execution, with runtime statistics gathering disabled.
// Total runtime and run counters are not expected to increase.
mustRun(tb, prog, &RunOptions{Data: in})
s2, err := prog.Stats()
qt.Assert(tb, qt.IsNil(err))
qt.Assert(tb, qt.Equals(s2.RunCount, s1.RunCount), qt.Commentf("run count (%d) increased after first invocation (%d)", s2.RunCount, s1.RunCount))
qt.Assert(tb, qt.Equals(s2.Runtime, s1.Runtime), qt.Commentf("runtime (%d) increased after first invocation (%d)", s2.Runtime, s1.Runtime))
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(testutils.NativeFile(t, "testdata/loader-%s.elf"))
if err != nil {
t.Fatal(err)
}
var obj struct {
Main *Program `ebpf:"xdp_prog"`
}
err = loadAndAssign(t, spec, &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 := 28
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)
}
}
}
func TestInfoExportedFields(t *testing.T) {
// It is highly unlikely that you should be adjusting the asserts below.
// See the comment at the top of info.go for more information.
var names []string
for _, field := range reflect.VisibleFields(reflect.TypeOf(MapInfo{})) {
if field.IsExported() {
names = append(names, field.Name)
}
}
qt.Assert(t, qt.ContentEquals(names, []string{
"Type",
"KeySize",
"ValueSize",
"MaxEntries",
"Flags",
"Name",
}))
names = nil
for _, field := range reflect.VisibleFields(reflect.TypeOf(ProgramInfo{})) {
if field.IsExported() {
names = append(names, field.Name)
}
}
qt.Assert(t, qt.ContentEquals(names, []string{
"Type",
"Tag",
"Name",
}))
}
func TestZero(t *testing.T) {
var (
empty = ""
nul uint32 = 0
one uint32 = 1
iempty any = ""
inul any = uint32(0)
ione any = uint32(1)
)
qt.Assert(t, qt.IsTrue(zero(empty)))
qt.Assert(t, qt.IsTrue(zero(nul)))
qt.Assert(t, qt.IsFalse(zero(one)))
qt.Assert(t, qt.IsTrue(zero(&empty)))
qt.Assert(t, qt.IsTrue(zero(&nul)))
qt.Assert(t, qt.IsFalse(zero(&one)))
qt.Assert(t, qt.IsTrue(zero(iempty)))
qt.Assert(t, qt.IsTrue(zero(inul)))
qt.Assert(t, qt.IsFalse(zero(ione)))
qt.Assert(t, qt.IsTrue(zero(&iempty)))
qt.Assert(t, qt.IsTrue(zero(&inul)))
qt.Assert(t, qt.IsFalse(zero(&ione)))
}