-
Notifications
You must be signed in to change notification settings - Fork 314
/
bpf_test.go
688 lines (598 loc) · 16.8 KB
/
bpf_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
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
// +build integration
// Copyright 2016 PLUMgrid
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package bpf
import (
"bytes"
"encoding/binary"
"fmt"
"os"
"path/filepath"
"strconv"
"syscall"
"testing"
"unsafe"
"github.com/iovisor/gobpf/bcc"
"github.com/iovisor/gobpf/elf"
"github.com/iovisor/gobpf/pkg/bpffs"
"github.com/iovisor/gobpf/pkg/progtestrun"
)
// redefine flags here as cgo in test is not supported
const (
BPF_ANY = 0 /* create new element or update existing */
BPF_NOEXIST = 1 /* create new element if it didn't exist */
BPF_EXIST = 2
)
var simple1 string = `
BPF_TABLE("hash", int, int, table1, 10);
int func1(void *ctx) {
return 0;
}
`
var simple2 = `
struct key {
int key;
};
struct leaf {
int value;
};
BPF_HASH(table2, struct key, struct leaf, 10);
int func2(void *ctx) {
return 0;
}
`
type key struct {
key uint32
}
type leaf struct {
value uint32
}
var kernelVersion uint32
var (
kernelVersion46 uint32
kernelVersion47 uint32
kernelVersion48 uint32
kernelVersion410 uint32
kernelVersion412 uint32
kernelVersion414 uint32
)
func init() {
kernelVersion46, _ = elf.KernelVersionFromReleaseString("4.6.0")
kernelVersion47, _ = elf.KernelVersionFromReleaseString("4.7.0")
kernelVersion48, _ = elf.KernelVersionFromReleaseString("4.8.0")
kernelVersion410, _ = elf.KernelVersionFromReleaseString("4.10.0")
kernelVersion412, _ = elf.KernelVersionFromReleaseString("4.12.0")
kernelVersion414, _ = elf.KernelVersionFromReleaseString("4.14.0")
}
func TestModuleLoadBCC(t *testing.T) {
b := bcc.NewModule(simple1, []string{})
if b == nil {
t.Fatal("prog is nil")
}
defer b.Close()
_, err := b.LoadKprobe("func1")
if err != nil {
t.Fatal(err)
}
}
func fillTable1(b *bcc.Module) (*bcc.Table, error) {
table := bcc.NewTable(b.TableId("table1"), b)
key, _ := table.KeyStrToBytes("1")
leaf, _ := table.LeafStrToBytes("11")
if err := table.Set(key, leaf); err != nil {
return nil, fmt.Errorf("table.Set key 1 failed: %v", err)
}
key, leaf = make([]byte, 4), make([]byte, 4)
bcc.GetHostByteOrder().PutUint32(key, 2)
bcc.GetHostByteOrder().PutUint32(leaf, 22)
if err := table.Set(key, leaf); err != nil {
return nil, fmt.Errorf("table.Set key 2 failed: %v", err)
}
return table, nil
}
func TestBCCIterTable(t *testing.T) {
b := bcc.NewModule(simple1, []string{})
if b == nil {
t.Fatal("prog is nil")
}
defer b.Close()
table, err := fillTable1(b)
if err != nil {
t.Fatalf("fill table1 failed: %v", err)
}
hostEndian := bcc.GetHostByteOrder()
resIter := make(map[int32]int32)
iter := table.Iter()
for iter.Next() {
key, leaf := iter.Key(), iter.Leaf()
keyStr, err := table.KeyBytesToStr(key)
if err != nil {
t.Fatalf("table.Iter/KeyBytesToStr failed: cannot print value: %v", err)
}
leafStr, err := table.LeafBytesToStr(leaf)
if err != nil {
t.Fatalf("table.Iter/LeafBytesToStr failed: cannot print value: %v", err)
}
var k, v int32
if err := binary.Read(bytes.NewBuffer(key), hostEndian, &k); err != nil {
t.Fatalf("table.Iter failed: cannot decode key: %v", err)
}
if err := binary.Read(bytes.NewBuffer(leaf), hostEndian, &v); err != nil {
t.Fatalf("table.Iter failed: cannot decode value: %v", err)
}
resIter[k] = v
kS, err := strconv.ParseInt(keyStr[2:], 16, 32)
if err != nil {
t.Fatalf("table.Iter failed: non-number key: %v", err)
}
vS, err := strconv.ParseInt(leafStr[2:], 16, 32)
if err != nil {
t.Fatalf("table.Iter failed: non-number value: %v", err)
}
if int32(kS) != k || int32(vS) != v {
t.Errorf("table.iter.Values() inconsistent with string values: (%v, %v) vs (%v, %v)", k, v, kS, vS)
}
}
if iter.Err() != nil {
t.Fatalf("table.Iter failed: iteration finished with unexpected error: %v", iter.Err())
}
if count := len(resIter); count != 2 {
t.Fatalf("expected 2 entries in Iter table, not %d", count)
}
for _, te := range [][]int32{{1, 11}, {2, 22}} {
res := resIter[te[0]]
if res != te[1] {
t.Fatalf("expected entry %d in Iter table to contain %d, but got %d", te[0], te[1], res)
}
}
}
func TestBCCTableSetPGetPDeleteP(t *testing.T) {
b := bcc.NewModule(simple2, []string{})
if b == nil {
t.Fatal("prog is nil")
}
defer b.Close()
table := bcc.NewTable(b.TableId("table2"), b)
k := &key{0}
l := &leaf{1}
err := table.SetP(unsafe.Pointer(k), unsafe.Pointer(l))
if err != nil {
t.Fatal(err)
}
p, err := table.GetP(unsafe.Pointer(k))
if err != nil {
t.Fatal(err)
}
v := (*leaf)(p)
if v.value != 1 {
t.Fatalf("expected 1, not %d", v.value)
}
err = table.DeleteP(unsafe.Pointer(k))
if err != nil {
t.Fatal(err)
}
_, err = table.GetP(unsafe.Pointer(k))
if !os.IsNotExist(err) {
t.Fatal(err)
}
}
func TestBCCTableDeleteAll(t *testing.T) {
b := bcc.NewModule(simple1, []string{})
if b == nil {
t.Fatal("prog is nil")
}
defer b.Close()
table, err := fillTable1(b)
if err != nil {
t.Fatalf("fill table1 failed: %v", err)
}
count := 0
for it := table.Iter(); it.Next(); {
count++
}
if count != 2 {
t.Fatalf("expected 2 entries in table, not %d", count)
}
if err := table.DeleteAll(); err != nil {
t.Fatalf("table.DeleteAll failed: %v", err)
}
count = 0
for it := table.Iter(); it.Next(); {
count++
}
if count != 0 {
t.Fatalf("expected 0 entries in table, not %d", count)
}
}
func containsMap(maps []*elf.Map, name string) bool {
for _, m := range maps {
if m.Name == name {
return true
}
}
return false
}
func containsProbe(probes []*elf.Kprobe, name string) bool {
for _, k := range probes {
if k.Name == name {
return true
}
}
return false
}
func containsUprobe(uprobes []*elf.Uprobe, name string) bool {
for _, u := range uprobes {
if u.Name == name {
return true
}
}
return false
}
func containsCgroupProg(cgroupProgs []*elf.CgroupProgram, name string) bool {
for _, c := range cgroupProgs {
if c.Name == name {
return true
}
}
return false
}
func containsTracepointProg(tracepointProgs []*elf.TracepointProgram, name string) bool {
for _, c := range tracepointProgs {
if c.Name == name {
return true
}
}
return false
}
func containsSocketFilter(socketFilters []*elf.SocketFilter, name string) bool {
for _, c := range socketFilters {
if c.Name == name {
return true
}
}
return false
}
func checkMaps(t *testing.T, b *elf.Module) {
var expectedMaps = []string{
"dummy_hash",
"dummy_array",
"dummy_prog_array",
"dummy_perf",
"dummy_array_custom",
}
if kernelVersion >= kernelVersion46 {
kernel46Maps := []string{
"dummy_percpu_hash",
"dummy_percpu_array",
"dummy_stack_trace",
}
expectedMaps = append(expectedMaps, kernel46Maps...)
} else {
t.Logf("kernel doesn't support percpu maps and stacktrace maps. Skipping...")
}
if kernelVersion >= kernelVersion48 {
kernel48Maps := []string{
"dummy_cgroup_array",
}
expectedMaps = append(expectedMaps, kernel48Maps...)
} else {
t.Logf("kernel doesn't support cgroup array maps. Skipping...")
}
var maps []*elf.Map
for m := range b.IterMaps() {
maps = append(maps, m)
}
if len(maps) != len(expectedMaps) {
t.Fatalf("unexpected number of maps. Got %d, expected %d", len(maps), len(expectedMaps))
}
for _, em := range expectedMaps {
if !containsMap(maps, em) {
t.Fatalf("map %q not found", em)
}
}
}
func checkProbes(t *testing.T, b *elf.Module) {
var expectedProbes = []string{
"kprobe/dummy",
"kretprobe/dummy",
}
var probes []*elf.Kprobe
for p := range b.IterKprobes() {
probes = append(probes, p)
}
if len(probes) != len(expectedProbes) {
t.Fatalf("unexpected number of probes. Got %d, expected %d", len(probes), len(expectedProbes))
}
for _, ek := range expectedProbes {
if !containsProbe(probes, ek) {
t.Fatalf("probe %q not found", ek)
}
}
}
func checkUprobes(t *testing.T, b *elf.Module) {
var expectedUprobes = []string{
"uprobe/dummy",
"uretprobe/dummy",
}
var uprobes []*elf.Uprobe
for p := range b.IterUprobes() {
uprobes = append(uprobes, p)
}
if len(uprobes) != len(expectedUprobes) {
t.Fatalf("unexpected number of uprobes. Got %d, expected %d", len(uprobes), len(expectedUprobes))
}
for _, ek := range expectedUprobes {
if !containsUprobe(uprobes, ek) {
t.Fatalf("uprobe %q not found", ek)
}
}
}
func checkCgroupProgs(t *testing.T, b *elf.Module) {
if kernelVersion < kernelVersion410 {
t.Logf("kernel doesn't support cgroup-bpf. Skipping...")
return
}
var expectedCgroupProgs = []string{
"cgroup/skb",
"cgroup/sock",
}
var cgroupProgs []*elf.CgroupProgram
for p := range b.IterCgroupProgram() {
cgroupProgs = append(cgroupProgs, p)
}
if len(cgroupProgs) != len(expectedCgroupProgs) {
t.Fatalf("unexpected number of cgroup programs. Got %d, expected %v", len(cgroupProgs), len(expectedCgroupProgs))
}
for _, cp := range expectedCgroupProgs {
if !containsCgroupProg(cgroupProgs, cp) {
t.Fatalf("cgroup program %q not found", cp)
}
}
}
func checkXDPProgs(t *testing.T, b *elf.Module) {
if kernelVersion < kernelVersion48 {
t.Logf("kernel doesn't support XDP. Skipping...")
t.Skip()
}
var expectedXDPProgs = []string{
"xdp/prog1",
"xdp/prog2",
}
var xdpProgs []*elf.XDPProgram
for p := range b.IterXDPProgram() {
xdpProgs = append(xdpProgs, p)
}
if len(xdpProgs) != len(expectedXDPProgs) {
t.Fatalf("unexpected number of XDP programs. Got %d, expected %v", len(xdpProgs), len(expectedXDPProgs))
}
}
func checkTracepointProgs(t *testing.T, b *elf.Module) {
if kernelVersion < kernelVersion47 {
t.Logf("kernel doesn't support bpf programs for tracepoints. Skipping...")
return
}
var expectedTracepointProgs = []string{
"tracepoint/raw_syscalls/sys_enter",
}
var tracepointProgs []*elf.TracepointProgram
for p := range b.IterTracepointProgram() {
tracepointProgs = append(tracepointProgs, p)
}
if len(tracepointProgs) != len(expectedTracepointProgs) {
t.Fatalf("unexpected number of tracepoint programs. Got %d, expected %v", len(tracepointProgs), len(expectedTracepointProgs))
}
for _, p := range expectedTracepointProgs {
if !containsTracepointProg(tracepointProgs, p) {
t.Fatalf("tracepoint program %q not found", p)
}
}
}
func checkSocketFilters(t *testing.T, b *elf.Module) {
var expectedSocketFilters = []string{
"socket/dummy",
}
var socketFilters []*elf.SocketFilter
for sf := range b.IterSocketFilter() {
socketFilters = append(socketFilters, sf)
}
if len(socketFilters) != len(expectedSocketFilters) {
t.Fatalf("unexpected number of socket filters. Got %d, expected %d", len(socketFilters), len(expectedSocketFilters))
}
for _, sf := range expectedSocketFilters {
if !containsSocketFilter(socketFilters, sf) {
t.Fatalf("socket filter %q not found", sf)
}
}
fd, err := syscall.Socket(syscall.AF_PACKET, syscall.SOCK_RAW, syscall.ETH_P_ALL)
if err != nil {
t.Fatalf("unable to open a raw socket: %s", err)
}
defer syscall.Close(fd)
socketFilter := b.SocketFilter("socket/dummy")
if socketFilter == nil {
t.Fatal("socket filter dummy not found")
}
if err := elf.AttachSocketFilter(socketFilter, fd); err != nil {
t.Fatalf("failed trying to attach socket filter: %s", err)
}
if err := elf.DetachSocketFilter(socketFilter, fd); err != nil {
t.Fatalf("failed trying to detach socket filter: %s", err)
}
}
func checkPinConfig(t *testing.T, expectedPaths []string) {
for _, p := range expectedPaths {
if fi, err := os.Stat(p); os.IsNotExist(err) || !fi.Mode().IsRegular() {
t.Fatalf("pinned object %q not found", p)
}
}
}
func checkPinConfigCleanup(t *testing.T, expectedPaths []string) {
for _, p := range expectedPaths {
if _, err := os.Stat(p); !os.IsNotExist(err) {
t.Fatalf("pinned object %q is not cleaned up", p)
}
}
}
func checkUpdateDeleteElement(t *testing.T, b *elf.Module) {
mp := b.Map("dummy_hash")
if mp == nil {
t.Fatal("unable to find dummy_hash map")
}
key := 1000
value := 1000
if err := b.UpdateElement(mp, unsafe.Pointer(&key), unsafe.Pointer(&value), BPF_ANY); err != nil {
t.Fatal("failed trying to update an element with BPF_ANY")
}
if err := b.UpdateElement(mp, unsafe.Pointer(&key), unsafe.Pointer(&value), BPF_NOEXIST); err == nil {
t.Fatal("succeeded updating element with BPF_NOEXIST, but an element with the same key was added to the map before")
}
if err := b.UpdateElement(mp, unsafe.Pointer(&key), unsafe.Pointer(&value), BPF_EXIST); err != nil {
t.Fatal("failed trying to update an element with BPF_EXIST while the key was added to the map before")
}
if err := b.DeleteElement(mp, unsafe.Pointer(&key)); err != nil {
t.Fatal("failed to delete an element")
}
if err := b.UpdateElement(mp, unsafe.Pointer(&key), unsafe.Pointer(&value), BPF_EXIST); err == nil {
t.Fatal("succeeded updating element with BPF_EXIST, but the element was deleted from the map before")
}
}
func checkLookupElement(t *testing.T, b *elf.Module) {
mp := b.Map("dummy_hash")
if mp == nil {
t.Fatal("unable to find dummy_hash map")
}
key := 2000
value := 2000
if err := b.UpdateElement(mp, unsafe.Pointer(&key), unsafe.Pointer(&value), BPF_ANY); err != nil {
t.Fatal("failed trying to update an element with BPF_ANY")
}
var lvalue int
if err := b.LookupElement(mp, unsafe.Pointer(&key), unsafe.Pointer(&lvalue)); err != nil {
t.Fatal("failed trying to lookup an element previously added")
}
if value != lvalue {
t.Fatalf("wrong value returned, expected %d, got %d", value, lvalue)
}
key = 3000
if err := b.LookupElement(mp, unsafe.Pointer(&key), unsafe.Pointer(&lvalue)); err == nil {
t.Fatalf("succeeded to find an element which wasn't added previously")
}
found := map[int]bool{2000: false}
for i := 4000; i != 4010; i++ {
key = i
value = i
if err := b.UpdateElement(mp, unsafe.Pointer(&key), unsafe.Pointer(&value), BPF_ANY); err != nil {
t.Fatal("failed trying to update an element with BPF_ANY")
}
found[key] = false
}
key = 0
nextKey := 0
for {
f, err := b.LookupNextElement(mp, unsafe.Pointer(&key), unsafe.Pointer(&nextKey), unsafe.Pointer(&lvalue))
if err != nil {
t.Fatalf("failed trying to lookup the next element: %s", err)
}
if !f {
break
}
if nextKey != lvalue {
t.Fatalf("key %d not corresponding to value %d", nextKey, lvalue)
}
if _, ok := found[nextKey]; !ok {
t.Fatalf("key %d found", nextKey)
}
found[nextKey] = true
key = nextKey
}
for key, f := range found {
if !f {
t.Fatalf("expected key %d not found", key)
}
}
}
func checkProgTestRun(t *testing.T, b *elf.Module) {
if kernelVersion < kernelVersion412 {
t.Logf("kernel doesn't support BPF_PROG_TEST_RUN. Skipping...")
return
}
prog := b.CgroupProgram("cgroup/skb")
if prog == nil {
t.Fatal("unable to find prog")
}
// minimum amount of input data, but unused
data := make([]byte, 14)
returnValue, _, _, err := progtestrun.Run(prog.Fd(), 1, data, nil)
if err != nil {
t.Fatalf("bpf_prog_test_run failed: %v", err)
}
if returnValue != 1 {
t.Fatalf("expected return value 1, got %d", returnValue)
}
}
func TestModuleLoadELF(t *testing.T) {
var err error
kernelVersion, err = elf.CurrentKernelVersion()
if err != nil {
t.Fatalf("error getting current kernel version: %v", err)
}
dummyELF := "./tests/dummy.o"
if kernelVersion > kernelVersion414 {
dummyELF = "./tests/dummy-414.o"
} else if kernelVersion > kernelVersion410 {
dummyELF = "./tests/dummy-410.o"
} else if kernelVersion > kernelVersion48 {
dummyELF = "./tests/dummy-48.o"
} else if kernelVersion > kernelVersion46 {
dummyELF = "./tests/dummy-46.o"
}
var secParams = map[string]elf.SectionParams{
"maps/dummy_array_custom": elf.SectionParams{
PinPath: filepath.Join("gobpf-test", "testgroup1"),
},
}
var closeOptions = map[string]elf.CloseOptions{
"maps/dummy_array_custom": elf.CloseOptions{
Unpin: true,
PinPath: filepath.Join("gobpf-test", "testgroup1"),
},
}
if err := bpffs.Mount(); err != nil {
t.Fatalf("error mounting bpf fs: %v", err)
}
b := elf.NewModule(dummyELF)
if b == nil {
t.Fatal("prog is nil")
}
if err := b.Load(secParams); err != nil {
t.Fatal(err)
}
defer func() {
if err := b.CloseExt(closeOptions); err != nil {
t.Fatal(err)
}
checkPinConfigCleanup(t, []string{"/sys/fs/bpf/gobpf-test/testgroup1"})
}()
checkMaps(t, b)
checkProbes(t, b)
checkUprobes(t, b)
checkCgroupProgs(t, b)
checkSocketFilters(t, b)
checkTracepointProgs(t, b)
checkXDPProgs(t, b)
checkPinConfig(t, []string{"/sys/fs/bpf/gobpf-test/testgroup1"})
checkUpdateDeleteElement(t, b)
checkLookupElement(t, b)
checkProgTestRun(t, b)
}