-
Notifications
You must be signed in to change notification settings - Fork 699
/
map_test.go
2537 lines (2162 loc) · 53.4 KB
/
map_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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package ebpf
import (
"bytes"
"errors"
"fmt"
"math"
"os"
"path/filepath"
"sort"
"testing"
"unsafe"
"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"
"github.com/go-quicktest/qt"
)
var (
spec1 = &MapSpec{
Name: "foo",
Type: Hash,
KeySize: 4,
ValueSize: 4,
MaxEntries: 1,
Pinning: PinByName,
}
)
// newHash returns a new Map of type Hash. Cleanup is handled automatically.
func newHash(t *testing.T) *Map {
hash, err := NewMap(&MapSpec{
Type: Hash,
KeySize: 5,
ValueSize: 4,
MaxEntries: 10,
})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { hash.Close() })
return hash
}
func TestMap(t *testing.T) {
m := createArray(t)
t.Log(m)
if err := m.Put(uint32(0), uint32(42)); err != nil {
t.Fatal("Can't put:", err)
}
if err := m.Put(uint32(1), uint32(4242)); err != nil {
t.Fatal("Can't put:", err)
}
m2, err := m.Clone()
if err != nil {
t.Fatal("Can't clone map:", err)
}
defer m2.Close()
m.Close()
m = m2
var v uint32
if err := m.Lookup(uint32(0), &v); err != nil {
t.Fatal("Can't lookup 0:", err)
}
if v != 42 {
t.Error("Want value 42, got", v)
}
sliceVal := make([]uint32, 1)
qt.Assert(t, qt.IsNil(m.Lookup(uint32(0), sliceVal)))
qt.Assert(t, qt.DeepEquals(sliceVal, []uint32{42}))
var slice []byte
qt.Assert(t, qt.IsNil(m.Lookup(uint32(0), &slice)))
qt.Assert(t, qt.DeepEquals(slice, internal.NativeEndian.AppendUint32(nil, 42)))
var k uint32
if err := m.NextKey(uint32(0), &k); err != nil {
t.Fatal("Can't get:", err)
}
if k != 1 {
t.Error("Want key 1, got", k)
}
}
func TestMapSpecCopy(t *testing.T) {
a := &MapSpec{
"foo",
Hash,
4,
4,
1,
1,
PinByName,
1,
[]MapKV{{1, 2}}, // Can't copy Contents, use value types
nil, // InnerMap
bytes.NewReader(nil),
&btf.Int{},
&btf.Int{},
}
a.InnerMap = a
qt.Check(t, qt.IsNil((*MapSpec)(nil).Copy()))
qt.Assert(t, testutils.IsDeepCopy(a.Copy(), a))
}
func TestMapBatch(t *testing.T) {
if err := haveBatchAPI(); err != nil {
t.Skipf("batch api not available: %v", err)
}
contents := []uint32{
42, 4242, 23, 2323,
}
mustNewMap := func(t *testing.T, mapType MapType, max uint32) *Map {
m, err := NewMap(&MapSpec{
Type: mapType,
KeySize: 4,
ValueSize: 4,
MaxEntries: max,
})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { m.Close() })
return m
}
keysAndValuesForMap := func(m *Map, contents []uint32) (keys, values []uint32, stride int) {
possibleCPU := 1
if m.Type().hasPerCPUValue() {
possibleCPU = MustPossibleCPU()
}
keys = make([]uint32, 0, len(contents))
values = make([]uint32, 0, len(contents)*possibleCPU)
for key, value := range contents {
keys = append(keys, uint32(key))
for i := 0; i < possibleCPU; i++ {
values = append(values, value*uint32((i+1)))
}
}
return keys, values, possibleCPU
}
for _, typ := range []MapType{Array, PerCPUArray} {
t.Run(typ.String(), func(t *testing.T) {
if typ == PerCPUArray {
// https://lore.kernel.org/bpf/[email protected]/
testutils.SkipOnOldKernel(t, "5.13", "batched ops support for percpu array")
}
m := mustNewMap(t, typ, uint32(len(contents)))
keys, values, _ := keysAndValuesForMap(m, contents)
count, err := m.BatchUpdate(keys, values, nil)
qt.Assert(t, qt.IsNil(err))
qt.Assert(t, qt.Equals(count, len(contents)))
lookupKeys := make([]uint32, len(keys))
lookupValues := make([]uint32, len(values))
var cursor MapBatchCursor
count, err = m.BatchLookup(&cursor, lookupKeys, lookupValues, nil)
qt.Assert(t, qt.IsNil(err))
qt.Assert(t, qt.Equals(count, len(contents)))
qt.Assert(t, qt.ContentEquals(lookupKeys, keys))
qt.Assert(t, qt.ContentEquals(lookupValues, values))
count, err = m.BatchLookup(&cursor, lookupKeys, lookupValues, nil)
qt.Assert(t, qt.ErrorIs(err, ErrKeyNotExist))
qt.Assert(t, qt.Equals(count, 0))
})
}
for _, typ := range []MapType{Hash, PerCPUHash} {
t.Run(typ.String(), func(t *testing.T) {
m := mustNewMap(t, typ, uint32(len(contents)))
keys, values, stride := keysAndValuesForMap(m, contents)
count, err := m.BatchUpdate(keys, values, nil)
qt.Assert(t, qt.IsNil(err))
qt.Assert(t, qt.Equals(count, len(contents)))
// BPF hash tables seem to have lots of collisions when keys
// are following a sequence.
// This causes ENOSPC since a single large bucket may be larger
// than the batch size. We work around this by making the batch size
// equal to the map size.
lookupKeys := make([]uint32, len(keys))
lookupValues := make([]uint32, len(values))
var cursor MapBatchCursor
count, err = m.BatchLookup(&cursor, lookupKeys, lookupValues, nil)
qt.Assert(t, qt.ErrorIs(err, ErrKeyNotExist))
qt.Assert(t, qt.Equals(count, len(contents)))
qt.Assert(t, qt.ContentEquals(lookupKeys, keys))
qt.Assert(t, qt.ContentEquals(lookupValues, values))
cursor = MapBatchCursor{}
count, err = m.BatchLookupAndDelete(&cursor, lookupKeys, lookupValues, nil)
qt.Assert(t, qt.ErrorIs(err, ErrKeyNotExist))
qt.Assert(t, qt.Equals(count, len(contents)))
qt.Assert(t, qt.ContentEquals(lookupKeys, keys))
qt.Assert(t, qt.ContentEquals(lookupValues, values))
if stride > 1 {
values := make([]uint32, stride)
qt.Assert(t, qt.ErrorIs(m.Lookup(uint32(0), values), ErrKeyNotExist))
} else {
var v uint32
qt.Assert(t, qt.ErrorIs(m.Lookup(uint32(0), &v), ErrKeyNotExist))
}
})
}
}
func TestMapBatchCursorReuse(t *testing.T) {
spec := &MapSpec{
Type: Array,
KeySize: 4,
ValueSize: 4,
MaxEntries: 4,
}
arr1, err := NewMap(spec)
if err != nil {
t.Fatal(err)
}
defer arr1.Close()
arr2, err := NewMap(spec)
if err != nil {
t.Fatal(err)
}
defer arr2.Close()
tmp := make([]uint32, 2)
var cursor MapBatchCursor
_, err = arr1.BatchLookup(&cursor, tmp, tmp, nil)
testutils.SkipIfNotSupported(t, err)
qt.Assert(t, qt.IsNil(err))
_, err = arr2.BatchLookup(&cursor, tmp, tmp, nil)
qt.Assert(t, qt.IsNotNil(err))
}
func TestMapLookupKeyTooSmall(t *testing.T) {
m := createArray(t)
defer m.Close()
var small uint16
qt.Assert(t, qt.IsNil(m.Put(uint32(0), uint32(1234))))
qt.Assert(t, qt.IsNotNil(m.Lookup(uint32(0), &small)))
}
func TestMapLookupKeyNotFoundAllocations(t *testing.T) {
m := createArray(t)
defer m.Close()
var key, out uint32 = 3, 0
allocs := testing.AllocsPerRun(5, func() {
_ = m.Lookup(&key, &out)
})
qt.Assert(t, qt.Equals(allocs, float64(0)))
}
func TestBatchAPIMapDelete(t *testing.T) {
if err := haveBatchAPI(); err != nil {
t.Skipf("batch api not available: %v", err)
}
m, err := NewMap(&MapSpec{
Type: Hash,
KeySize: 4,
ValueSize: 4,
MaxEntries: 10,
})
if err != nil {
t.Fatal(err)
}
defer m.Close()
var (
keys = []uint32{0, 1}
values = []uint32{42, 4242}
)
count, err := m.BatchUpdate(keys, values, nil)
if err != nil {
t.Fatalf("BatchUpdate: %v", err)
}
if count != len(keys) {
t.Fatalf("BatchUpdate: expected count, %d, to be %d", count, len(keys))
}
var v uint32
if err := m.Lookup(uint32(0), &v); err != nil {
t.Fatal("Can't lookup 0:", err)
}
if v != 42 {
t.Error("Want value 42, got", v)
}
count, err = m.BatchDelete(keys, nil)
if err != nil {
t.Fatalf("BatchDelete: %v", err)
}
if count != len(keys) {
t.Fatalf("BatchDelete: expected %d deletions got %d", len(keys), count)
}
if err := m.Lookup(uint32(0), &v); !errors.Is(err, ErrKeyNotExist) {
t.Fatalf("Lookup should have failed with error, %v, instead error is %v", ErrKeyNotExist, err)
}
}
func TestMapClose(t *testing.T) {
m := createArray(t)
if err := m.Close(); err != nil {
t.Fatal("Can't close map:", err)
}
if err := m.Put(uint32(0), uint32(42)); !errors.Is(err, sys.ErrClosedFd) {
t.Fatal("Put doesn't check for closed fd", err)
}
if _, err := m.LookupBytes(uint32(0)); !errors.Is(err, sys.ErrClosedFd) {
t.Fatal("Get doesn't check for closed fd", err)
}
}
func TestBatchMapWithLock(t *testing.T) {
testutils.SkipOnOldKernel(t, "5.13", "MAP BATCH BPF_F_LOCK")
file := testutils.NativeFile(t, "testdata/map_spin_lock-%s.elf")
spec, err := LoadCollectionSpec(file)
if err != nil {
t.Fatal("Can't parse ELF:", err)
}
coll, err := NewCollection(spec)
if err != nil {
t.Fatal("Can't parse ELF:", err)
}
defer coll.Close()
type spinLockValue struct {
Cnt uint32
Padding uint32
}
m, ok := coll.Maps["spin_lock_map"]
if !ok {
t.Fatal(err)
}
keys := []uint32{0, 1}
values := []spinLockValue{{Cnt: 42}, {Cnt: 4242}}
count, err := m.BatchUpdate(keys, values, &BatchOptions{ElemFlags: uint64(UpdateLock)})
if err != nil {
t.Fatalf("BatchUpdate: %v", err)
}
if count != len(keys) {
t.Fatalf("BatchUpdate: expected count, %d, to be %d", count, len(keys))
}
var cursor MapBatchCursor
lookupKeys := make([]uint32, 2)
lookupValues := make([]spinLockValue, 2)
count, err = m.BatchLookup(&cursor, lookupKeys, lookupValues, &BatchOptions{ElemFlags: uint64(LookupLock)})
if !errors.Is(err, ErrKeyNotExist) {
t.Fatalf("BatchLookup: %v", err)
}
if count != 2 {
t.Fatalf("BatchLookup: expected two keys, got %d", count)
}
cursor = MapBatchCursor{}
deleteKeys := []uint32{0, 1}
deleteValues := make([]spinLockValue, 2)
count, err = m.BatchLookupAndDelete(&cursor, deleteKeys, deleteValues, nil)
if !errors.Is(err, ErrKeyNotExist) {
t.Fatalf("BatchLookupAndDelete: %v", err)
}
if count != 2 {
t.Fatalf("BatchLookupAndDelete: expected two keys, got %d", count)
}
}
func TestMapWithLock(t *testing.T) {
testutils.SkipOnOldKernel(t, "5.13", "MAP BPF_F_LOCK")
file := testutils.NativeFile(t, "testdata/map_spin_lock-%s.elf")
spec, err := LoadCollectionSpec(file)
if err != nil {
t.Fatal("Can't parse ELF:", err)
}
coll, err := NewCollection(spec)
if err != nil {
t.Fatal("Can't parse ELF:", err)
}
defer coll.Close()
type spinLockValue struct {
Cnt uint32
Padding uint32
}
m, ok := coll.Maps["spin_lock_map"]
if !ok {
t.Fatal(err)
}
key := uint32(1)
value := spinLockValue{Cnt: 5}
err = m.Update(key, value, UpdateLock)
if err != nil {
t.Fatal(err)
}
value.Cnt = 0
err = m.LookupWithFlags(&key, &value, LookupLock)
if err != nil {
t.Fatal(err)
}
if value.Cnt != 5 {
t.Fatalf("Want value 5, got %d", value.Cnt)
}
t.Run("LookupAndDelete", func(t *testing.T) {
testutils.SkipOnOldKernel(t, "5.14", "LOOKUP_AND_DELETE flags")
value.Cnt = 0
err = m.LookupAndDeleteWithFlags(&key, &value, LookupLock)
if err != nil {
t.Fatal(err)
}
if value.Cnt != 5 {
t.Fatalf("Want value 5, got %d", value.Cnt)
}
err = m.LookupWithFlags(&key, &value, LookupLock)
if err != nil && !errors.Is(err, ErrKeyNotExist) {
t.Fatal(err)
}
})
}
func TestMapCloneNil(t *testing.T) {
m, err := (*Map)(nil).Clone()
if err != nil {
t.Fatal(err)
}
if m != nil {
t.Fatal("Cloning a nil map doesn't return nil")
}
}
func TestMapPin(t *testing.T) {
m := createArray(t)
if err := m.Put(uint32(0), uint32(42)); err != nil {
t.Fatal("Can't put:", err)
}
tmp := testutils.TempBPFFS(t)
path := filepath.Join(tmp, "map")
if err := m.Pin(path); err != nil {
testutils.SkipIfNotSupported(t, err)
t.Fatal(err)
}
pinned := m.IsPinned()
qt.Assert(t, qt.IsTrue(pinned))
m.Close()
m, err := LoadPinnedMap(path, nil)
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal(err)
}
defer m.Close()
var v uint32
if err := m.Lookup(uint32(0), &v); err != nil {
t.Fatal("Can't lookup 0:", err)
}
if v != 42 {
t.Error("Want value 42, got", v)
}
}
func TestNestedMapPin(t *testing.T) {
m, err := NewMap(&MapSpec{
Type: ArrayOfMaps,
KeySize: 4,
ValueSize: 4,
MaxEntries: 2,
InnerMap: &MapSpec{
Type: Array,
KeySize: 4,
ValueSize: 4,
MaxEntries: 1,
},
})
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal(err)
}
defer m.Close()
tmp, err := os.MkdirTemp("/sys/fs/bpf", "ebpf-test")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmp)
path := filepath.Join(tmp, "nested")
if err := m.Pin(path); err != nil {
t.Fatal(err)
}
m.Close()
m, err = LoadPinnedMap(path, nil)
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal(err)
}
defer m.Close()
}
func TestNestedMapPinNested(t *testing.T) {
if _, err := NewMap(&MapSpec{
Type: ArrayOfMaps,
KeySize: 4,
ValueSize: 4,
MaxEntries: 2,
InnerMap: &MapSpec{
Name: "inner",
Type: Array,
KeySize: 4,
ValueSize: 4,
MaxEntries: 1,
Pinning: PinByName,
},
}); err == nil {
t.Error("Inner maps should not be pinnable")
}
}
func TestMapPinMultiple(t *testing.T) {
testutils.SkipOnOldKernel(t, "4.9", "atomic re-pinning was introduced in 4.9 series")
tmp := testutils.TempBPFFS(t)
spec := spec1.Copy()
m1, err := NewMapWithOptions(spec, MapOptions{PinPath: tmp})
if err != nil {
t.Fatal("Can't create map:", err)
}
defer m1.Close()
pinned := m1.IsPinned()
qt.Assert(t, qt.IsTrue(pinned))
newPath := filepath.Join(tmp, "bar")
err = m1.Pin(newPath)
testutils.SkipIfNotSupported(t, err)
qt.Assert(t, qt.IsNil(err))
oldPath := filepath.Join(tmp, spec.Name)
if _, err := os.Stat(oldPath); err == nil {
t.Fatal("Previous pinned map path still exists:", err)
}
m2, err := LoadPinnedMap(newPath, nil)
qt.Assert(t, qt.IsNil(err))
pinned = m2.IsPinned()
qt.Assert(t, qt.IsTrue(pinned))
defer m2.Close()
}
func TestMapPinWithEmptyPath(t *testing.T) {
m := createArray(t)
err := m.Pin("")
qt.Assert(t, qt.Not(qt.IsNil(err)))
}
func TestMapPinFailReplace(t *testing.T) {
tmp := testutils.TempBPFFS(t)
spec := spec1.Copy()
spec2 := spec1.Copy()
spec2.Name = spec1.Name + "bar"
m, err := NewMapWithOptions(spec, MapOptions{PinPath: tmp})
if err != nil {
t.Fatal("Failed to create map:", err)
}
defer m.Close()
m2, err := NewMapWithOptions(spec2, MapOptions{PinPath: tmp})
if err != nil {
t.Fatal("Failed to create map2:", err)
}
defer m2.Close()
qt.Assert(t, qt.IsTrue(m.IsPinned()))
newPath := filepath.Join(tmp, spec2.Name)
qt.Assert(t, qt.Not(qt.IsNil(m.Pin(newPath))), qt.Commentf("Pin didn't"+
" fail new path from replacing an existing path"))
}
func TestMapUnpin(t *testing.T) {
tmp := testutils.TempBPFFS(t)
spec := spec1.Copy()
m, err := NewMapWithOptions(spec, MapOptions{PinPath: tmp})
if err != nil {
t.Fatal("Failed to create map:", err)
}
defer m.Close()
pinned := m.IsPinned()
qt.Assert(t, qt.IsTrue(pinned))
path := filepath.Join(tmp, spec.Name)
m2, err := LoadPinnedMap(path, nil)
testutils.SkipIfNotSupported(t, err)
qt.Assert(t, qt.IsNil(err))
defer m2.Close()
if err = m.Unpin(); err != nil {
t.Fatal("Failed to unpin map:", err)
}
if _, err := os.Stat(path); err == nil {
t.Fatal("Pinned map path still exists after unpinning:", err)
}
}
func TestMapLoadPinned(t *testing.T) {
tmp := testutils.TempBPFFS(t)
spec := spec1.Copy()
m1, err := NewMapWithOptions(spec, MapOptions{PinPath: tmp})
qt.Assert(t, qt.IsNil(err))
defer m1.Close()
pinned := m1.IsPinned()
qt.Assert(t, qt.IsTrue(pinned))
path := filepath.Join(tmp, spec.Name)
m2, err := LoadPinnedMap(path, nil)
testutils.SkipIfNotSupported(t, err)
qt.Assert(t, qt.IsNil(err))
defer m2.Close()
pinned = m2.IsPinned()
qt.Assert(t, qt.IsTrue(pinned))
}
func TestMapLoadReusePinned(t *testing.T) {
for _, typ := range []MapType{Array, Hash, DevMap, DevMapHash} {
t.Run(typ.String(), func(t *testing.T) {
if typ == DevMap {
testutils.SkipOnOldKernel(t, "4.14", "devmap")
}
if typ == DevMapHash {
testutils.SkipOnOldKernel(t, "5.4", "devmap_hash")
}
tmp := testutils.TempBPFFS(t)
spec := &MapSpec{
Name: "pinmap",
Type: typ,
KeySize: 4,
ValueSize: 4,
MaxEntries: 1,
Pinning: PinByName,
}
m1, err := NewMapWithOptions(spec, MapOptions{PinPath: tmp})
qt.Assert(t, qt.IsNil(err))
defer m1.Close()
m2, err := NewMapWithOptions(spec, MapOptions{PinPath: tmp})
qt.Assert(t, qt.IsNil(err))
defer m2.Close()
})
}
}
func TestMapLoadPinnedUnpin(t *testing.T) {
tmp := testutils.TempBPFFS(t)
spec := spec1.Copy()
m1, err := NewMapWithOptions(spec, MapOptions{PinPath: tmp})
qt.Assert(t, qt.IsNil(err))
defer m1.Close()
pinned := m1.IsPinned()
qt.Assert(t, qt.IsTrue(pinned))
path := filepath.Join(tmp, spec.Name)
m2, err := LoadPinnedMap(path, nil)
testutils.SkipIfNotSupported(t, err)
qt.Assert(t, qt.IsNil(err))
defer m2.Close()
err = m1.Unpin()
qt.Assert(t, qt.IsNil(err))
err = m2.Unpin()
qt.Assert(t, qt.IsNil(err))
}
func TestMapLoadPinnedWithOptions(t *testing.T) {
// Introduced in commit 6e71b04a8224.
testutils.SkipOnOldKernel(t, "4.15", "file_flags in BPF_OBJ_GET")
array := createArray(t)
tmp := testutils.TempBPFFS(t)
path := filepath.Join(tmp, "map")
if err := array.Pin(path); err != nil {
t.Fatal(err)
}
if err := array.Put(uint32(0), uint32(123)); err != nil {
t.Fatal(err)
}
array.Close()
t.Run("read-only", func(t *testing.T) {
array, err := LoadPinnedMap(path, &LoadPinOptions{
ReadOnly: true,
})
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal("Can't load map:", err)
}
defer array.Close()
if err := array.Put(uint32(0), uint32(1)); !errors.Is(err, unix.EPERM) {
t.Fatal("Expected EPERM from Put, got", err)
}
})
t.Run("write-only", func(t *testing.T) {
array, err := LoadPinnedMap(path, &LoadPinOptions{
WriteOnly: true,
})
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal("Can't load map:", err)
}
defer array.Close()
var value uint32
if err := array.Lookup(uint32(0), &value); !errors.Is(err, unix.EPERM) {
t.Fatal("Expected EPERM from Lookup, got", err)
}
})
}
func TestMapPinFlags(t *testing.T) {
tmp := testutils.TempBPFFS(t)
spec := &MapSpec{
Name: "map",
Type: Array,
KeySize: 4,
ValueSize: 4,
MaxEntries: 1,
Pinning: PinByName,
}
m, err := NewMapWithOptions(spec, MapOptions{
PinPath: tmp,
})
qt.Assert(t, qt.IsNil(err))
m.Close()
_, err = NewMapWithOptions(spec, MapOptions{
PinPath: tmp,
LoadPinOptions: LoadPinOptions{
Flags: math.MaxUint32,
},
})
if !errors.Is(err, unix.EINVAL) {
t.Fatal("Invalid flags should trigger EINVAL:", err)
}
}
func createArray(t *testing.T) *Map {
t.Helper()
m, err := NewMap(&MapSpec{
Type: Array,
KeySize: 4,
ValueSize: 4,
MaxEntries: 2,
})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { m.Close() })
return m
}
func TestMapQueue(t *testing.T) {
testutils.SkipOnOldKernel(t, "4.20", "map type queue")
m, err := NewMap(&MapSpec{
Type: Queue,
ValueSize: 4,
MaxEntries: 2,
})
if err != nil {
t.Fatal(err)
}
defer m.Close()
for _, v := range []uint32{42, 4242} {
if err := m.Put(nil, v); err != nil {
t.Fatalf("Can't put %d: %s", v, err)
}
}
var v uint32
if err := m.Lookup(nil, &v); err != nil {
t.Fatal("Lookup (Peek) on Queue:", err)
}
if v != 42 {
t.Error("Want value 42, got", v)
}
v = 0
if err := m.LookupAndDelete(nil, &v); err != nil {
t.Fatal("Can't lookup and delete element:", err)
}
if v != 42 {
t.Error("Want value 42, got", v)
}
v = 0
if err := m.LookupAndDelete(nil, unsafe.Pointer(&v)); err != nil {
t.Fatal("Can't lookup and delete element using unsafe.Pointer:", err)
}
if v != 4242 {
t.Error("Want value 4242, got", v)
}
if err := m.LookupAndDelete(nil, &v); !errors.Is(err, ErrKeyNotExist) {
t.Fatal("Lookup and delete on empty Queue:", err)
}
if err := m.Lookup(nil, &v); !errors.Is(err, ErrKeyNotExist) {
t.Fatal("Lookup (Peek) on empty Queue:", err)
}
}
func TestMapInMap(t *testing.T) {
for _, typ := range []MapType{ArrayOfMaps, HashOfMaps} {
t.Run(typ.String(), func(t *testing.T) {
spec := &MapSpec{
Type: typ,
KeySize: 4,
MaxEntries: 2,
InnerMap: &MapSpec{
Type: Array,
KeySize: 4,
ValueSize: 4,
MaxEntries: 2,
},
}
inner, err := NewMap(spec.InnerMap)
if err != nil {
t.Fatal(err)
}
if err := inner.Put(uint32(1), uint32(4242)); err != nil {
t.Fatal(err)
}
defer inner.Close()
outer, err := NewMap(spec)
testutils.SkipIfNotSupported(t, err)
if err != nil {
t.Fatal(err)
}
defer outer.Close()
if err := outer.Put(uint32(0), inner); err != nil {
t.Fatal("Can't put inner map:", err)
}
if err := outer.Put(uint32(0), (*Map)(nil)); err == nil {
t.Fatal("Put accepted a nil Map")
}
var inner2 *Map
if err := outer.Lookup(uint32(0), &inner2); err != nil {
t.Fatal("Can't lookup 0:", err)
}
defer inner2.Close()
var v uint32
if err := inner2.Lookup(uint32(1), &v); err != nil {
t.Fatal("Can't lookup 1 in inner2:", err)
}
if v != 4242 {
t.Error("Expected value 4242, got", v)
}
inner2.Close()
// Make sure we can still access the original map
if err := inner.Lookup(uint32(1), &v); err != nil {
t.Fatal("Can't lookup 1 in inner:", err)
}
if v != 4242 {
t.Error("Expected value 4242, got", v)
}
})
}
}
func TestNewMapInMapFromFD(t *testing.T) {
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()
// Do not copy this, use Clone instead.
another, err := NewMapFromFD(dupFD(t, nested.FD()))
if err != nil {
t.Fatal("Can't create a new nested map from an FD")
}
another.Close()
}
func TestPerfEventArray(t *testing.T) {
specs := []*MapSpec{
{Type: PerfEventArray},
{Type: PerfEventArray, KeySize: 4},
{Type: PerfEventArray, ValueSize: 4},
}
for _, spec := range specs {
m, err := NewMap(spec)
if err != nil {
t.Errorf("Can't create perf event array from %v: %s", spec, err)
} else {
m.Close()
}
}
}
func createMapInMap(t *testing.T, typ MapType) *Map {
t.Helper()
spec := &MapSpec{
Type: typ,
KeySize: 4,
MaxEntries: 2,
InnerMap: &MapSpec{
Type: Array,
KeySize: 4,
ValueSize: 4,
MaxEntries: 2,
},
}
m, err := NewMap(spec)
testutils.SkipIfNotSupported(t, err)