Debian Codegraph @

map_test.go

raw symbols SCIP
1 package ebpf
2
3 import (
4 "bytes"
5 "errors"
6 "fmt"
7 "math"
8 "os"
9 "path/filepath"
10 "runtime"
11 "slices"
12 "sort"
13 "testing"
14 "unsafe"
15
16 "github.com/go-quicktest/qt"
17
18 "github.com/cilium/ebpf/asm"
19 "github.com/cilium/ebpf/btf"
20 "github.com/cilium/ebpf/internal"
21 "github.com/cilium/ebpf/internal/platform"
22 "github.com/cilium/ebpf/internal/sys"
23 "github.com/cilium/ebpf/internal/testutils"
24 "github.com/cilium/ebpf/internal/unix"
25 )
26
27 var (
28 spec1 = &MapSpec{
29 Name: "foo",
30 Type: Hash,
31 KeySize: 4,
32 ValueSize: 4,
33 MaxEntries: 1,
34 Pinning: PinByName,
35 }
36 )
37
38 func TestMap(t *testing.T) {
39 m := createMap(t, Array, 2)
40
41 t.Log(m)
42
43 if err := m.Put(uint32(0), uint32(42)); err != nil {
44 t.Fatal("Can't put:", err)
45 }
46 if err := m.Put(uint32(1), uint32(4242)); err != nil {
47 t.Fatal("Can't put:", err)
48 }
49
50 m2, err := m.Clone()
51 if err != nil {
52 t.Fatal("Can't clone map:", err)
53 }
54 defer m2.Close()
55
56 m.Close()
57 m = m2
58
59 var v uint32
60 if err := m.Lookup(uint32(0), &v); err != nil {
61 t.Fatal("Can't lookup 0:", err)
62 }
63 if v != 42 {
64 t.Error("Want value 42, got", v)
65 }
66
67 sliceVal := make([]uint32, 1)
68 qt.Assert(t, qt.IsNil(m.Lookup(uint32(0), sliceVal)))
69 qt.Assert(t, qt.DeepEquals(sliceVal, []uint32{42}))
70
71 var slice []byte
72 qt.Assert(t, qt.IsNil(m.Lookup(uint32(0), &slice)))
73 qt.Assert(t, qt.DeepEquals(slice, internal.NativeEndian.AppendUint32(nil, 42)))
74
75 var k uint32
76 if err := m.NextKey(uint32(0), &k); err != nil {
77 t.Fatal("Can't get:", err)
78 }
79 if k != 1 {
80 t.Error("Want key 1, got", k)
81 }
82 }
83
84 func TestMapSpecCopy(t *testing.T) {
85 a := &MapSpec{
86 "foo",
87 Hash,
88 4,
89 4,
90 1,
91 1,
92 PinByName,
93 1,
94 []MapKV{{1, 2}}, // Can't copy Contents, use value types
95 nil, // InnerMap
96 0, // MapExtra
97 bytes.NewReader(nil),
98 &btf.Int{},
99 &btf.Int{},
100 nil,
101 }
102 a.InnerMap = a
103
104 qt.Check(t, qt.IsNil((*MapSpec)(nil).Copy()))
105 qt.Assert(t, testutils.IsDeepCopy(a.Copy(), a))
106 }
107
108 func TestMapBatch(t *testing.T) {
109 contents := []uint32{
110 42, 4242, 23, 2323,
111 }
112
113 keysAndValuesForMap := func(m *Map, contents []uint32) (keys, values []uint32, stride int) {
114 possibleCPU := 1
115 if m.Type().hasPerCPUValue() {
116 possibleCPU = MustPossibleCPU()
117 }
118
119 keys = make([]uint32, 0, len(contents))
120 values = make([]uint32, 0, len(contents)*possibleCPU)
121 for key, value := range contents {
122 keys = append(keys, uint32(key))
123 for i := 0; i < possibleCPU; i++ {
124 values = append(values, value*uint32((i+1)))
125 }
126 }
127
128 return keys, values, possibleCPU
129 }
130
131 for _, typ := range []MapType{Array, PerCPUArray} {
132 t.Run(typ.String(), func(t *testing.T) {
133 if typ == PerCPUArray {
134 // https://lore.kernel.org/bpf/[email protected]/
135 testutils.SkipOnOldKernel(t, "5.13", "batched ops support for percpu array")
136 }
137
138 m := createMap(t, typ, uint32(len(contents)))
139 keys, values, _ := keysAndValuesForMap(m, contents)
140 count, err := m.BatchUpdate(keys, values, nil)
141 testutils.SkipIfNotSupported(t, err)
142 qt.Assert(t, qt.IsNil(err))
143 qt.Assert(t, qt.Equals(count, len(contents)))
144
145 lookupKeys := make([]uint32, len(keys))
146 lookupValues := make([]uint32, len(values))
147
148 var cursor MapBatchCursor
149 count, err = m.BatchLookup(&cursor, lookupKeys, lookupValues, nil)
150 qt.Assert(t, qt.IsNil(err))
151 qt.Assert(t, qt.Equals(count, len(contents)))
152 qt.Assert(t, qt.ContentEquals(lookupKeys, keys))
153 qt.Assert(t, qt.ContentEquals(lookupValues, values))
154
155 count, err = m.BatchLookup(&cursor, lookupKeys, lookupValues, nil)
156 qt.Assert(t, qt.ErrorIs(err, ErrKeyNotExist))
157 qt.Assert(t, qt.Equals(count, 0))
158 })
159 }
160
161 for _, typ := range []MapType{Hash, PerCPUHash} {
162 t.Run(typ.String(), func(t *testing.T) {
163 m := createMap(t, typ, uint32(len(contents)))
164 keys, values, stride := keysAndValuesForMap(m, contents)
165 count, err := m.BatchUpdate(keys, values, nil)
166 testutils.SkipIfNotSupported(t, err)
167 qt.Assert(t, qt.IsNil(err))
168 qt.Assert(t, qt.Equals(count, len(contents)))
169
170 // BPF hash tables seem to have lots of collisions when keys
171 // are following a sequence.
172 // This causes ENOSPC since a single large bucket may be larger
173 // than the batch size. We work around this by making the batch size
174 // equal to the map size.
175 lookupKeys := make([]uint32, len(keys))
176 lookupValues := make([]uint32, len(values))
177
178 var cursor MapBatchCursor
179 count, err = m.BatchLookup(&cursor, lookupKeys, lookupValues, nil)
180 qt.Assert(t, qt.ErrorIs(err, ErrKeyNotExist))
181 qt.Assert(t, qt.Equals(count, len(contents)))
182
183 qt.Assert(t, qt.ContentEquals(lookupKeys, keys))
184 qt.Assert(t, qt.ContentEquals(lookupValues, values))
185
186 cursor = MapBatchCursor{}
187 count, err = m.BatchLookupAndDelete(&cursor, lookupKeys, lookupValues, nil)
188 qt.Assert(t, qt.ErrorIs(err, ErrKeyNotExist))
189 qt.Assert(t, qt.Equals(count, len(contents)))
190
191 qt.Assert(t, qt.ContentEquals(lookupKeys, keys))
192 qt.Assert(t, qt.ContentEquals(lookupValues, values))
193
194 if stride > 1 {
195 values := make([]uint32, stride)
196 qt.Assert(t, qt.ErrorIs(m.Lookup(uint32(0), values), ErrKeyNotExist))
197 } else {
198 var v uint32
199 qt.Assert(t, qt.ErrorIs(m.Lookup(uint32(0), &v), ErrKeyNotExist))
200 }
201 })
202 }
203 }
204
205 func TestMapBatchUnprivileged(t *testing.T) {
206 arr := createMap(t, Array, 4)
207 hash := createMap(t, Hash, 4)
208
209 keys := []uint32{0, 1}
210 values := []uint32{42, 4242}
211 qt.Assert(t, qt.IsNil(hash.Update(keys[0], values[0], UpdateAny)))
212 qt.Assert(t, qt.IsNil(hash.Update(keys[1], values[1], UpdateAny)))
213
214 testutils.WithCapabilities(t, nil, func() {
215 tmp := make([]uint32, 2)
216
217 var cursor MapBatchCursor
218 _, err := arr.BatchLookup(&cursor, tmp, tmp, nil)
219 testutils.SkipIfNotSupported(t, err)
220 qt.Assert(t, qt.IsNil(err))
221
222 count, err := arr.BatchUpdate(keys, values, nil)
223 testutils.SkipIfNotSupported(t, err)
224 qt.Assert(t, qt.IsNil(err))
225 qt.Assert(t, qt.Equals(count, len(keys)))
226
227 count, err = hash.BatchDelete(keys, nil)
228 testutils.SkipIfNotSupported(t, err)
229 qt.Assert(t, qt.IsNil(err))
230 qt.Assert(t, qt.Equals(count, len(keys)))
231 })
232 }
233
234 func TestMapBatchCursorReuse(t *testing.T) {
235 arr1 := createMap(t, Array, 4)
236 arr2 := createMap(t, Array, 4)
237
238 tmp := make([]uint32, 2)
239
240 var cursor MapBatchCursor
241 _, err := arr1.BatchLookup(&cursor, tmp, tmp, nil)
242 testutils.SkipIfNotSupported(t, err)
243 qt.Assert(t, qt.IsNil(err))
244
245 _, err = arr2.BatchLookup(&cursor, tmp, tmp, nil)
246 qt.Assert(t, qt.IsNotNil(err))
247 }
248
249 func TestMapLookupKeyTooSmall(t *testing.T) {
250 m := createMap(t, Array, 2)
251 defer m.Close()
252
253 var small uint16
254 qt.Assert(t, qt.IsNil(m.Put(uint32(0), uint32(1234))))
255 qt.Assert(t, qt.IsNotNil(m.Lookup(uint32(0), &small)))
256 }
257
258 func TestMapLookupKeyNotFoundAllocations(t *testing.T) {
259 m := createMap(t, Array, 2)
260 defer m.Close()
261 var key, out uint32 = 3, 0
262 var err error
263
264 allocs := testing.AllocsPerRun(5, func() {
265 err = m.Lookup(&key, &out)
266 })
267 qt.Assert(t, qt.ErrorIs(err, ErrKeyNotExist))
268 qt.Assert(t, qt.Equals(allocs, float64(0)))
269 }
270
271 func TestBatchAPIMapDelete(t *testing.T) {
272 if err := haveBatchAPI(); err != nil {
273 t.Skipf("batch api not available: %v", err)
274 }
275
276 m := createMap(t, Hash, 10)
277
278 var (
279 keys = []uint32{0, 1}
280 values = []uint32{42, 4242}
281 )
282
283 count, err := m.BatchUpdate(keys, values, nil)
284 if err != nil {
285 t.Fatalf("BatchUpdate: %v", err)
286 }
287 if count != len(keys) {
288 t.Fatalf("BatchUpdate: expected count, %d, to be %d", count, len(keys))
289 }
290
291 var v uint32
292 if err := m.Lookup(uint32(0), &v); err != nil {
293 t.Fatal("Can't lookup 0:", err)
294 }
295 if v != 42 {
296 t.Error("Want value 42, got", v)
297 }
298
299 count, err = m.BatchDelete(keys, nil)
300 if err != nil {
301 t.Fatalf("BatchDelete: %v", err)
302 }
303 if count != len(keys) {
304 t.Fatalf("BatchDelete: expected %d deletions got %d", len(keys), count)
305 }
306
307 if err := m.Lookup(uint32(0), &v); !errors.Is(err, ErrKeyNotExist) {
308 t.Fatalf("Lookup should have failed with error, %v, instead error is %v", ErrKeyNotExist, err)
309 }
310 }
311
312 func TestMapClose(t *testing.T) {
313 m := createMap(t, Array, 2)
314
315 if err := m.Close(); err != nil {
316 t.Fatal("Can't close map:", err)
317 }
318
319 if err := m.Put(uint32(0), uint32(42)); !errors.Is(err, sys.ErrClosedFd) {
320 t.Fatal("Put doesn't check for closed fd", err)
321 }
322
323 if _, err := m.LookupBytes(uint32(0)); !errors.Is(err, sys.ErrClosedFd) {
324 t.Fatal("Get doesn't check for closed fd", err)
325 }
326 }
327
328 func TestBatchMapWithLock(t *testing.T) {
329 testutils.SkipOnOldKernel(t, "5.13", "MAP BATCH BPF_F_LOCK")
330
331 spec, err := LoadCollectionSpec(testutils.NativeFile(t, "testdata/map_spin_lock-%s.elf"))
332 qt.Assert(t, qt.IsNil(err))
333
334 coll := mustNewCollection(t, spec, nil)
335
336 type spinLockValue struct {
337 Cnt uint32
338 Padding uint32
339 }
340
341 m, ok := coll.Maps["spin_lock_map"]
342 if !ok {
343 t.Fatal(err)
344 }
345
346 keys := []uint32{0, 1}
347 values := []spinLockValue{{Cnt: 42}, {Cnt: 4242}}
348 count, err := m.BatchUpdate(keys, values, &BatchOptions{ElemFlags: uint64(UpdateLock)})
349 testutils.SkipIfNotSupportedOnOS(t, err)
350 if err != nil {
351 t.Fatalf("BatchUpdate: %v", err)
352 }
353 if count != len(keys) {
354 t.Fatalf("BatchUpdate: expected count, %d, to be %d", count, len(keys))
355 }
356
357 var cursor MapBatchCursor
358 lookupKeys := make([]uint32, 2)
359 lookupValues := make([]spinLockValue, 2)
360 count, err = m.BatchLookup(&cursor, lookupKeys, lookupValues, &BatchOptions{ElemFlags: uint64(LookupLock)})
361 if !errors.Is(err, ErrKeyNotExist) {
362 t.Fatalf("BatchLookup: %v", err)
363 }
364 if count != 2 {
365 t.Fatalf("BatchLookup: expected two keys, got %d", count)
366 }
367
368 cursor = MapBatchCursor{}
369 deleteKeys := []uint32{0, 1}
370 deleteValues := make([]spinLockValue, 2)
371 count, err = m.BatchLookupAndDelete(&cursor, deleteKeys, deleteValues, nil)
372 if !errors.Is(err, ErrKeyNotExist) {
373 t.Fatalf("BatchLookupAndDelete: %v", err)
374 }
375 if count != 2 {
376 t.Fatalf("BatchLookupAndDelete: expected two keys, got %d", count)
377 }
378 }
379
380 func TestMapWithLock(t *testing.T) {
381 testutils.SkipOnOldKernel(t, "5.13", "MAP BPF_F_LOCK")
382
383 spec, err := LoadCollectionSpec(testutils.NativeFile(t, "testdata/map_spin_lock-%s.elf"))
384 qt.Assert(t, qt.IsNil(err))
385
386 coll := mustNewCollection(t, spec, nil)
387
388 type spinLockValue struct {
389 Cnt uint32
390 Padding uint32
391 }
392
393 m, ok := coll.Maps["spin_lock_map"]
394 if !ok {
395 t.Fatal(err)
396 }
397
398 key := uint32(1)
399 value := spinLockValue{Cnt: 5}
400 err = m.Update(key, value, UpdateLock)
401 if platform.IsWindows && errors.Is(err, unix.EINVAL) {
402 t.Skip("Windows doesn't support UpdateLock")
403 }
404 if err != nil {
405 t.Fatal(err)
406 }
407
408 value.Cnt = 0
409 err = m.LookupWithFlags(&key, &value, LookupLock)
410 if err != nil {
411 t.Fatal(err)
412 }
413 if value.Cnt != 5 {
414 t.Fatalf("Want value 5, got %d", value.Cnt)
415 }
416
417 t.Run("LookupAndDelete", func(t *testing.T) {
418 testutils.SkipOnOldKernel(t, "5.14", "LOOKUP_AND_DELETE flags")
419
420 value.Cnt = 0
421 err = m.LookupAndDeleteWithFlags(&key, &value, LookupLock)
422 if err != nil {
423 t.Fatal(err)
424 }
425 if value.Cnt != 5 {
426 t.Fatalf("Want value 5, got %d", value.Cnt)
427 }
428
429 err = m.LookupWithFlags(&key, &value, LookupLock)
430 if err != nil && !errors.Is(err, ErrKeyNotExist) {
431 t.Fatal(err)
432 }
433 })
434 }
435
436 func TestMapCloneNil(t *testing.T) {
437 m, err := (*Map)(nil).Clone()
438 if err != nil {
439 t.Fatal(err)
440 }
441
442 if m != nil {
443 t.Fatal("Cloning a nil map doesn't return nil")
444 }
445 }
446
447 func TestMapPin(t *testing.T) {
448 m := createMap(t, Array, 2)
449
450 if err := m.Put(uint32(0), uint32(42)); err != nil {
451 t.Fatal("Can't put:", err)
452 }
453
454 tmp := testutils.TempBPFFS(t)
455 path := filepath.Join(tmp, "map")
456
457 if err := m.Pin(path); err != nil {
458 testutils.SkipIfNotSupported(t, err)
459 t.Fatal(err)
460 }
461
462 pinned := m.IsPinned()
463 qt.Assert(t, qt.IsTrue(pinned))
464
465 m.Close()
466
467 m, err := LoadPinnedMap(path, nil)
468 testutils.SkipIfNotSupported(t, err)
469 if err != nil {
470 t.Fatal(err)
471 }
472 defer m.Close()
473
474 var v uint32
475 if err := m.Lookup(uint32(0), &v); err != nil {
476 t.Fatal("Can't lookup 0:", err)
477 }
478 if v != 42 {
479 t.Error("Want value 42, got", v)
480 }
481 }
482
483 func TestNestedMapPin(t *testing.T) {
484 m := createMapInMap(t, ArrayOfMaps, Array)
485
486 tmp := testutils.TempBPFFS(t)
487
488 path := filepath.Join(tmp, "nested")
489 if err := m.Pin(path); err != nil {
490 t.Fatal(err)
491 }
492 m.Close()
493
494 m, err := LoadPinnedMap(path, nil)
495 testutils.SkipIfNotSupported(t, err)
496 if err != nil {
497 t.Fatal(err)
498 }
499 defer m.Close()
500 }
501
502 func TestNestedMapPinNested(t *testing.T) {
503 if _, err := newMap(t, &MapSpec{
504 Type: ArrayOfMaps,
505 KeySize: 4,
506 ValueSize: 4,
507 MaxEntries: 2,
508 InnerMap: &MapSpec{
509 Name: "inner",
510 Type: Array,
511 KeySize: 4,
512 ValueSize: 4,
513 MaxEntries: 1,
514 Pinning: PinByName,
515 },
516 }, nil); err == nil {
517 t.Error("Inner maps should not be pinnable")
518 }
519 }
520
521 func TestMapPinMultiple(t *testing.T) {
522 testutils.SkipOnOldKernel(t, "4.9", "atomic re-pinning was introduced in 4.9 series")
523
524 tmp := testutils.TempBPFFS(t)
525
526 spec := spec1.Copy()
527
528 m1 := mustNewMap(t, spec, &MapOptions{PinPath: tmp})
529 pinned := m1.IsPinned()
530 qt.Assert(t, qt.IsTrue(pinned))
531
532 newPath := filepath.Join(tmp, "bar")
533 err := m1.Pin(newPath)
534 testutils.SkipIfNotSupported(t, err)
535 qt.Assert(t, qt.IsNil(err))
536 oldPath := filepath.Join(tmp, spec.Name)
537 if _, err := os.Stat(oldPath); err == nil {
538 t.Fatal("Previous pinned map path still exists:", err)
539 }
540 m2, err := LoadPinnedMap(newPath, nil)
541 qt.Assert(t, qt.IsNil(err))
542 pinned = m2.IsPinned()
543 qt.Assert(t, qt.IsTrue(pinned))
544 defer m2.Close()
545 }
546
547 func TestMapPinWithEmptyPath(t *testing.T) {
548 m := createMap(t, Array, 2)
549
550 err := m.Pin("")
551
552 qt.Assert(t, qt.Not(qt.IsNil(err)))
553 }
554
555 func TestMapPinFailReplace(t *testing.T) {
556 tmp := testutils.TempBPFFS(t)
557 spec := spec1.Copy()
558 spec2 := spec1.Copy()
559 spec2.Name = spec1.Name + "bar"
560
561 m := mustNewMap(t, spec, &MapOptions{PinPath: tmp})
562 _ = mustNewMap(t, spec2, &MapOptions{PinPath: tmp})
563
564 qt.Assert(t, qt.IsTrue(m.IsPinned()))
565 newPath := filepath.Join(tmp, spec2.Name)
566
567 qt.Assert(t, qt.Not(qt.IsNil(m.Pin(newPath))), qt.Commentf("Pin didn't"+
568 " fail new path from replacing an existing path"))
569 }
570
571 func TestMapUnpin(t *testing.T) {
572 tmp := testutils.TempBPFFS(t)
573 spec := spec1.Copy()
574
575 m := mustNewMap(t, spec, &MapOptions{PinPath: tmp})
576
577 pinned := m.IsPinned()
578 qt.Assert(t, qt.IsTrue(pinned))
579 path := filepath.Join(tmp, spec.Name)
580 m2, err := LoadPinnedMap(path, nil)
581 testutils.SkipIfNotSupported(t, err)
582 qt.Assert(t, qt.IsNil(err))
583 defer m2.Close()
584
585 if err = m.Unpin(); err != nil {
586 t.Fatal("Failed to unpin map:", err)
587 }
588 if _, err := os.Stat(path); err == nil {
589 t.Fatal("Pinned map path still exists after unpinning:", err)
590 }
591 }
592
593 func TestMapLoadPinned(t *testing.T) {
594 tmp := testutils.TempBPFFS(t)
595
596 spec := spec1.Copy()
597
598 m1 := mustNewMap(t, spec, &MapOptions{PinPath: tmp})
599 pinned := m1.IsPinned()
600 qt.Assert(t, qt.IsTrue(pinned))
601
602 path := filepath.Join(tmp, spec.Name)
603 m2, err := LoadPinnedMap(path, nil)
604 testutils.SkipIfNotSupported(t, err)
605 qt.Assert(t, qt.IsNil(err))
606 defer m2.Close()
607 pinned = m2.IsPinned()
608 qt.Assert(t, qt.IsTrue(pinned))
609 }
610
611 func TestMapLoadReusePinned(t *testing.T) {
612 for _, typ := range []MapType{Array, Hash, DevMap, DevMapHash} {
613 t.Run(typ.String(), func(t *testing.T) {
614 if typ == DevMap {
615 testutils.SkipOnOldKernel(t, "4.14", "devmap")
616 }
617 if typ == DevMapHash {
618 testutils.SkipOnOldKernel(t, "5.4", "devmap_hash")
619 }
620 tmp := testutils.TempBPFFS(t)
621 spec := &MapSpec{
622 Name: "pinmap",
623 Type: typ,
624 KeySize: 4,
625 ValueSize: 4,
626 MaxEntries: 1,
627 Pinning: PinByName,
628 }
629
630 _ = mustNewMap(t, spec, &MapOptions{PinPath: tmp})
631 _ = mustNewMap(t, spec, &MapOptions{PinPath: tmp})
632 })
633 }
634 }
635
636 func TestMapLoadPinnedUnpin(t *testing.T) {
637 tmp := testutils.TempBPFFS(t)
638
639 spec := spec1.Copy()
640
641 m1 := mustNewMap(t, spec, &MapOptions{PinPath: tmp})
642 pinned := m1.IsPinned()
643 qt.Assert(t, qt.IsTrue(pinned))
644
645 path := filepath.Join(tmp, spec.Name)
646 m2, err := LoadPinnedMap(path, nil)
647 testutils.SkipIfNotSupported(t, err)
648 qt.Assert(t, qt.IsNil(err))
649 defer m2.Close()
650 err = m1.Unpin()
651 qt.Assert(t, qt.IsNil(err))
652 err = m2.Unpin()
653 qt.Assert(t, qt.IsNil(err))
654 }
655
656 func TestMapLoadPinnedWithOptions(t *testing.T) {
657 // Introduced in commit 6e71b04a8224.
658 testutils.SkipOnOldKernel(t, "4.15", "file_flags in BPF_OBJ_GET")
659
660 array := createMap(t, Array, 2)
661
662 tmp := testutils.TempBPFFS(t)
663
664 path := filepath.Join(tmp, "map")
665 if err := array.Pin(path); err != nil {
666 t.Fatal(err)
667 }
668 if err := array.Put(uint32(0), uint32(123)); err != nil {
669 t.Fatal(err)
670 }
671 array.Close()
672
673 t.Run("read-only", func(t *testing.T) {
674 array, err := LoadPinnedMap(path, &LoadPinOptions{
675 ReadOnly: true,
676 })
677 if platform.IsWindows && errors.Is(err, unix.EINVAL) {
678 t.Skip("Windows doesn't support file_flags in OBJ_GET")
679 }
680 testutils.SkipIfNotSupported(t, err)
681 if err != nil {
682 t.Fatal("Can't load map:", err)
683 }
684 defer array.Close()
685
686 if err := array.Put(uint32(0), uint32(1)); !errors.Is(err, unix.EPERM) {
687 t.Fatal("Expected EPERM from Put, got", err)
688 }
689 })
690
691 t.Run("write-only", func(t *testing.T) {
692 array, err := LoadPinnedMap(path, &LoadPinOptions{
693 WriteOnly: true,
694 })
695 if platform.IsWindows && errors.Is(err, unix.EINVAL) {
696 t.Skip("Windows doesn't support file_flags in OBJ_GET")
697 }
698 testutils.SkipIfNotSupported(t, err)
699 if err != nil {
700 t.Fatal("Can't load map:", err)
701 }
702 defer array.Close()
703
704 var value uint32
705 if err := array.Lookup(uint32(0), &value); !errors.Is(err, unix.EPERM) {
706 t.Fatal("Expected EPERM from Lookup, got", err)
707 }
708 })
709 }
710
711 func TestMapPinFlags(t *testing.T) {
712 tmp := testutils.TempBPFFS(t)
713
714 spec := &MapSpec{
715 Name: "map",
716 Type: Array,
717 KeySize: 4,
718 ValueSize: 4,
719 MaxEntries: 1,
720 Pinning: PinByName,
721 }
722
723 _ = mustNewMap(t, spec, &MapOptions{PinPath: tmp})
724
725 _, err := newMap(t, spec, &MapOptions{
726 PinPath: tmp,
727 LoadPinOptions: LoadPinOptions{
728 Flags: math.MaxUint32,
729 },
730 })
731 if !errors.Is(err, unix.EINVAL) {
732 t.Fatal("Invalid flags should trigger EINVAL:", err)
733 }
734 }
735
736 func TestMapQueue(t *testing.T) {
737 testutils.SkipOnOldKernel(t, "4.20", "map type queue")
738
739 m := mustNewMap(t, &MapSpec{
740 Type: Queue,
741 ValueSize: 4,
742 MaxEntries: 2,
743 }, nil)
744
745 for _, v := range []uint32{42, 4242} {
746 if err := m.Put(nil, v); err != nil {
747 t.Fatalf("Can't put %d: %s", v, err)
748 }
749 }
750
751 var v uint32
752 if err := m.Lookup(nil, &v); err != nil {
753 t.Fatal("Lookup (Peek) on Queue:", err)
754 }
755 if v != 42 {
756 t.Error("Want value 42, got", v)
757 }
758 v = 0
759
760 if err := m.LookupAndDelete(nil, &v); err != nil {
761 t.Fatal("Can't lookup and delete element:", err)
762 }
763 if v != 42 {
764 t.Error("Want value 42, got", v)
765 }
766
767 v = 0
768 if err := m.LookupAndDelete(nil, unsafe.Pointer(&v)); err != nil {
769 t.Fatal("Can't lookup and delete element using unsafe.Pointer:", err)
770 }
771 if v != 4242 {
772 t.Error("Want value 4242, got", v)
773 }
774
775 if err := m.LookupAndDelete(nil, &v); !errors.Is(err, ErrKeyNotExist) {
776 t.Fatal("Lookup and delete on empty Queue:", err)
777 }
778
779 if err := m.Lookup(nil, &v); !errors.Is(err, ErrKeyNotExist) {
780 t.Fatal("Lookup (Peek) on empty Queue:", err)
781 }
782 }
783
784 func TestMapInMap(t *testing.T) {
785 for _, typ := range []MapType{ArrayOfMaps, HashOfMaps} {
786 t.Run(typ.String(), func(t *testing.T) {
787 inner := createMap(t, Array, 2)
788 if err := inner.Put(uint32(1), uint32(4242)); err != nil {
789 t.Fatal(err)
790 }
791
792 outer := createMapInMap(t, typ, Array)
793 if err := outer.Put(uint32(0), inner); err != nil {
794 t.Fatal("Can't put inner map:", err)
795 }
796
797 if err := outer.Put(uint32(0), (*Map)(nil)); err == nil {
798 t.Fatal("Put accepted a nil Map")
799 }
800
801 var inner2 *Map
802 if err := outer.Lookup(uint32(0), &inner2); err != nil {
803 t.Fatal("Can't lookup 0:", err)
804 }
805 defer inner2.Close()
806
807 var v uint32
808 if err := inner2.Lookup(uint32(1), &v); err != nil {
809 t.Fatal("Can't lookup 1 in inner2:", err)
810 }
811
812 if v != 4242 {
813 t.Error("Expected value 4242, got", v)
814 }
815
816 inner2.Close()
817
818 // Make sure we can still access the original map
819 if err := inner.Lookup(uint32(1), &v); err != nil {
820 t.Fatal("Can't lookup 1 in inner:", err)
821 }
822
823 if v != 4242 {
824 t.Error("Expected value 4242, got", v)
825 }
826 })
827 }
828 }
829
830 func TestNewMapInMapFromFD(t *testing.T) {
831 nested := createMapInMap(t, ArrayOfMaps, Array)
832
833 // Do not copy this, use Clone instead.
834 another, err := NewMapFromFD(testutils.DupFD(t, nested.FD()))
835 testutils.SkipIfNotSupportedOnOS(t, err)
836 qt.Assert(t, qt.IsNil(err))
837 another.Close()
838 }
839
840 func TestPerfEventArray(t *testing.T) {
841 specs := []*MapSpec{
842 {Type: PerfEventArray},
843 {Type: PerfEventArray, KeySize: 4},
844 {Type: PerfEventArray, ValueSize: 4},
845 }
846
847 for _, spec := range specs {
848 _ = mustNewMap(t, spec, nil)
849 }
850 }
851
852 func TestCPUMap(t *testing.T) {
853 testutils.SkipOnOldKernel(t, "4.15", "cpu map")
854
855 m := mustNewMap(t, &MapSpec{Type: CPUMap, KeySize: 4, ValueSize: 4}, nil)
856 qt.Assert(t, qt.Equals(m.MaxEntries(), uint32(MustPossibleCPU())))
857 }
858
859 func TestMapInMapValueSize(t *testing.T) {
860 spec := &MapSpec{
861 Type: ArrayOfMaps,
862 KeySize: 4,
863 ValueSize: 0,
864 MaxEntries: 2,
865 InnerMap: &MapSpec{
866 Type: Array,
867 KeySize: 4,
868 ValueSize: 4,
869 MaxEntries: 2,
870 },
871 }
872
873 _ = mustNewMap(t, spec, nil)
874
875 spec.ValueSize = 4
876 _ = mustNewMap(t, spec, nil)
877
878 spec.ValueSize = 1
879 _, err := newMap(t, spec, nil)
880 qt.Assert(t, qt.IsNotNil(err))
881 }
882
883 func TestIterateEmptyMap(t *testing.T) {
884 makeMap := func(t *testing.T, mapType MapType) *Map {
885 m, err := newMap(t, &MapSpec{
886 Type: mapType,
887 KeySize: 4,
888 ValueSize: 8,
889 MaxEntries: 2,
890 }, nil)
891 if errors.Is(err, unix.EINVAL) {
892 t.Skip(mapType, "is not supported")
893 }
894 qt.Assert(t, qt.IsNil(err))
895 return m
896 }
897
898 for _, mapType := range []MapType{
899 Hash,
900 SockHash,
901 } {
902 t.Run(mapType.String(), func(t *testing.T) {
903 m := makeMap(t, mapType)
904 entries := m.Iterate()
905
906 var key string
907 var value uint64
908 if entries.Next(&key, &value) {
909 t.Error("Empty hash should not be iterable")
910 }
911 if err := entries.Err(); err != nil {
912 t.Error("Empty hash shouldn't return an error:", err)
913 }
914 })
915 }
916
917 for _, mapType := range []MapType{
918 Array,
919 SockMap,
920 } {
921 t.Run(mapType.String(), func(t *testing.T) {
922 m := makeMap(t, mapType)
923 entries := m.Iterate()
924 var key string
925 var value uint64
926 for entries.Next(&key, &value) {
927 // Some empty arrays like sockmap don't return any keys.
928 }
929 if err := entries.Err(); err != nil {
930 t.Error("Empty array shouldn't return an error:", err)
931 }
932 })
933 }
934 }
935
936 func TestMapIterate(t *testing.T) {
937 hash := createMap(t, Hash, 2)
938
939 data := []string{"test", "more"}
940 slices.Sort(data)
941 for i, k := range data {
942 if err := hash.Put(k, uint32(i)); err != nil {
943 t.Fatal(err)
944 }
945 }
946
947 var key string
948 var value uint32
949 var keys []string
950
951 entries := hash.Iterate()
952 for entries.Next(&key, &value) {
953 keys = append(keys, key)
954 }
955 qt.Assert(t, qt.IsNil(entries.Err()))
956
957 sort.Strings(keys)
958 qt.Assert(t, qt.DeepEquals(keys, data))
959 }
960
961 func TestIterateWrongMap(t *testing.T) {
962 testutils.SkipOnOldKernel(t, "4.20", "map type queue")
963
964 m := mustNewMap(t, &MapSpec{
965 Type: Queue,
966 ValueSize: 4,
967 MaxEntries: 2,
968 Contents: []MapKV{
969 {nil, uint32(0)},
970 {nil, uint32(1)},
971 },
972 }, nil)
973
974 var value uint32
975 entries := m.Iterate()
976
977 qt.Assert(t, qt.IsFalse(entries.Next(nil, &value)))
978 qt.Assert(t, qt.IsNotNil(entries.Err()))
979 }
980
981 func TestMapIteratorAllocations(t *testing.T) {
982 arr := createMap(t, Array, 10)
983
984 var k, v uint32
985 iter := arr.Iterate()
986
987 // AllocsPerRun warms up the function for us.
988 allocs := testing.AllocsPerRun(int(arr.MaxEntries()-1), func() {
989 if !iter.Next(&k, &v) {
990 t.Fatal("Next failed while iterating: %w", iter.Err())
991 }
992 })
993
994 qt.Assert(t, qt.Equals(allocs, float64(0)))
995 }
996
997 func TestMapBatchLookupAllocations(t *testing.T) {
998 testutils.SkipIfNotSupported(t, haveBatchAPI())
999
1000 for _, typ := range []MapType{Array, PerCPUArray} {
1001 if typ == PerCPUArray {
1002 // https://lore.kernel.org/bpf/[email protected]/
1003 testutils.SkipOnOldKernel(t, "5.13", "batched ops support for percpu array")
1004 }
1005
1006 t.Run(typ.String(), func(t *testing.T) {
1007 m := mustNewMap(t, &MapSpec{
1008 Name: "test",
1009 Type: typ,
1010 KeySize: 4,
1011 ValueSize: 8, // PerCPU values must be 8 byte aligned.
1012 MaxEntries: 10,
1013 }, nil)
1014
1015 possibleCPU := 1
1016 if m.Type().hasPerCPUValue() {
1017 possibleCPU = MustPossibleCPU()
1018 }
1019
1020 var cursor MapBatchCursor
1021 keys := any(make([]uint32, 2))
1022 values := any(make([]uint64, 2*possibleCPU))
1023
1024 // AllocsPerRun warms up the function for us.
1025 allocs := testing.AllocsPerRun(1, func() {
1026 _, err := m.BatchLookup(&cursor, keys, values, nil)
1027 if err != nil {
1028 t.Fatal(err)
1029 }
1030 })
1031
1032 qt.Assert(t, qt.Equals(allocs, 0))
1033 })
1034 }
1035 }
1036
1037 type customTestUnmarshaler []uint8
1038
1039 func (c customTestUnmarshaler) UnmarshalBinary(data []byte) error {
1040 chunkSize := len(data) / len(c)
1041
1042 for i := range len(data) / chunkSize {
1043 c[i] = data[i*chunkSize]
1044 }
1045
1046 return nil
1047 }
1048
1049 func TestMapBatchLookupCustomUnmarshaler(t *testing.T) {
1050 testutils.SkipIfNotSupported(t, haveBatchAPI())
1051
1052 m := mustNewMap(t, &MapSpec{
1053 Type: Array,
1054 MaxEntries: 3,
1055 KeySize: 4,
1056 ValueSize: 4,
1057 Contents: []MapKV{
1058 {uint32(0), uint32(3)},
1059 {uint32(1), uint32(4)},
1060 {uint32(2), uint32(5)},
1061 },
1062 }, nil)
1063
1064 var (
1065 cursor MapBatchCursor
1066 // Use data structures that result in different memory size than the
1067 // map keys and values. Otherwise their memory is used as backing
1068 // memory for the syscall directly and Unmarshal is a no-op.
1069 // Use batch size that results in partial second lookup.
1070 batchKeys = make(customTestUnmarshaler, 2)
1071 batchValues = make(customTestUnmarshaler, 2)
1072 keys []uint8
1073 values []uint8
1074 )
1075
1076 _, err := m.BatchLookup(&cursor, batchKeys, batchValues, nil)
1077 if err != nil {
1078 t.Fatal("Full batch lookup failed:", err)
1079 }
1080
1081 keys = append(keys, batchKeys...)
1082 values = append(values, batchValues...)
1083
1084 _, err = m.BatchLookup(&cursor, batchKeys, batchValues, nil)
1085 if !errors.Is(err, ErrKeyNotExist) {
1086 t.Fatal("Partial batch lookup doesn't return ErrKeyNotExist:", err)
1087 }
1088
1089 keys = append(keys, batchKeys[0])
1090 values = append(values, batchValues[0])
1091
1092 qt.Assert(t, qt.DeepEquals(keys, []uint8{0, 1, 2}))
1093 qt.Assert(t, qt.DeepEquals(values, []uint8{3, 4, 5}))
1094 }
1095
1096 func TestMapIterateHashKeyOneByteFull(t *testing.T) {
1097 hash := mustNewMap(t, &MapSpec{
1098 Type: Hash,
1099 KeySize: 1,
1100 ValueSize: 1,
1101 MaxEntries: 256,
1102 }, nil)
1103
1104 for i := 0; i < int(hash.MaxEntries()); i++ {
1105 if err := hash.Put(uint8(i), uint8(i)); err != nil {
1106 t.Fatal(err)
1107 }
1108 }
1109 var key uint8
1110 var value uint8
1111 var keys int
1112
1113 entries := hash.Iterate()
1114 for entries.Next(&key, &value) {
1115 if key != value {
1116 t.Fatalf("Expected key == value, got key %v value %v", key, value)
1117 }
1118 keys++
1119 }
1120
1121 if err := entries.Err(); err != nil {
1122 t.Fatal(err)
1123 }
1124
1125 if keys != int(hash.MaxEntries()) {
1126 t.Fatalf("Expected to get %d keys, have %d", hash.MaxEntries(), keys)
1127 }
1128 }
1129
1130 func TestMapGuessNonExistentKey(t *testing.T) {
1131 if !platform.IsLinux {
1132 t.Skip("No need to test linux quirk on", runtime.GOOS)
1133 }
1134
1135 tests := []struct {
1136 name string
1137 mapType MapType
1138 keys []uint32
1139 }{
1140 {
1141 "empty", Hash, []uint32{},
1142 },
1143 {
1144 "all zero key", Hash, []uint32{0},
1145 },
1146 {
1147 "all ones key", Hash, []uint32{math.MaxUint32},
1148 },
1149 {
1150 "alternating bits key", Hash, []uint32{0x5555_5555},
1151 },
1152 {
1153 "all special patterns", Hash, []uint32{0, math.MaxUint32, 0x5555_5555},
1154 },
1155 {
1156 "empty", Array, []uint32{},
1157 },
1158 {
1159 "all zero key", Array, []uint32{0},
1160 },
1161 {
1162 "full", Array, []uint32{0, 1},
1163 },
1164 }
1165
1166 for _, tt := range tests {
1167 t.Run(fmt.Sprintf("%s: %s", tt.mapType, tt.name), func(t *testing.T) {
1168 maxEntries := uint32(len(tt.keys))
1169 if maxEntries == 0 {
1170 maxEntries = 1
1171 }
1172
1173 m := mustNewMap(t, &MapSpec{
1174 Type: tt.mapType,
1175 KeySize: 4,
1176 ValueSize: 4,
1177 MaxEntries: maxEntries,
1178 }, nil)
1179
1180 for _, key := range tt.keys {
1181 if err := m.Put(key, key); err != nil {
1182 t.Fatal(err)
1183 }
1184 }
1185
1186 guess, err := m.guessNonExistentKey()
1187 if err != nil {
1188 t.Fatal(err)
1189 }
1190
1191 if len(guess) != int(m.keySize) {
1192 t.Fatal("Guessed key has wrong size")
1193 }
1194
1195 var value uint32
1196 if err := m.Lookup(guess, &value); !errors.Is(err, unix.ENOENT) {
1197 t.Fatal("Doesn't return ENOENT:", err)
1198 }
1199 })
1200 }
1201
1202 t.Run("Hash: full", func(t *testing.T) {
1203 const n = math.MaxUint8 + 1
1204
1205 hash := mustNewMap(t, &MapSpec{
1206 Type: Hash,
1207 KeySize: 1,
1208 ValueSize: 1,
1209 MaxEntries: n,
1210 }, nil)
1211
1212 for i := range n {
1213 if err := hash.Put(uint8(i), uint8(i)); err != nil {
1214 t.Fatal(err)
1215 }
1216 }
1217
1218 _, err := hash.guessNonExistentKey()
1219 if err == nil {
1220 t.Fatal("guessNonExistentKey doesn't return error on full hash table")
1221 }
1222 })
1223 }
1224
1225 func TestNotExist(t *testing.T) {
1226 hash := createMap(t, Hash, 10)
1227
1228 var tmp uint32
1229 err := hash.Lookup("test", &tmp)
1230 if !errors.Is(err, ErrKeyNotExist) {
1231 t.Error("Lookup doesn't return ErrKeyNotExist")
1232 }
1233
1234 buf, err := hash.LookupBytes("test")
1235 if err != nil {
1236 t.Error("Looking up non-existent key return an error:", err)
1237 }
1238 if buf != nil {
1239 t.Error("LookupBytes returns non-nil buffer for non-existent key")
1240 }
1241
1242 if err := hash.Delete("test"); !errors.Is(err, ErrKeyNotExist) {
1243 t.Error("Deleting unknown key doesn't return ErrKeyNotExist", err)
1244 }
1245
1246 var k = []byte{1, 2, 3, 4}
1247 if err := hash.NextKey(&k, &tmp); !errors.Is(err, ErrKeyNotExist) {
1248 t.Error("Looking up next key in empty map doesn't return a non-existing error", err)
1249 }
1250
1251 if err := hash.NextKey(nil, &tmp); !errors.Is(err, ErrKeyNotExist) {
1252 t.Error("Looking up next key in empty map doesn't return a non-existing error", err)
1253 }
1254 }
1255
1256 func TestExist(t *testing.T) {
1257 hash := createMap(t, Hash, 10)
1258
1259 if err := hash.Put("test", uint32(21)); err != nil {
1260 t.Errorf("Failed to put key/value pair into hash: %v", err)
1261 }
1262
1263 if err := hash.Update("test", uint32(42), UpdateNoExist); !errors.Is(err, ErrKeyExist) {
1264 t.Error("Updating existing key doesn't return ErrKeyExist")
1265 }
1266 }
1267
1268 func TestIterateMapInMap(t *testing.T) {
1269 const idx = uint32(1)
1270
1271 parent := createMapInMap(t, ArrayOfMaps, Array)
1272 defer parent.Close()
1273
1274 a := createMap(t, Array, 2)
1275
1276 if err := parent.Put(idx, a); err != nil {
1277 t.Fatal(err)
1278 }
1279
1280 var (
1281 key uint32
1282 m *Map
1283 entries = parent.Iterate()
1284 )
1285
1286 if !entries.Next(&key, &m) {
1287 t.Fatal("Iterator encountered error:", entries.Err())
1288 }
1289 m.Close()
1290
1291 if key != 1 {
1292 t.Error("Iterator didn't skip first entry")
1293 }
1294
1295 if m == nil {
1296 t.Fatal("Map is nil")
1297 }
1298 }
1299
1300 func TestPerCPUMarshaling(t *testing.T) {
1301 for _, typ := range []MapType{PerCPUHash, PerCPUArray, LRUCPUHash} {
1302 t.Run(typ.String(), func(t *testing.T) {
1303 numCPU := MustPossibleCPU()
1304 if numCPU < 2 {
1305 t.Skip("Test requires at least two CPUs")
1306 }
1307 if typ == PerCPUHash || typ == PerCPUArray {
1308 testutils.SkipOnOldKernel(t, "4.6", "per-CPU hash and array")
1309 }
1310 if typ == LRUCPUHash {
1311 testutils.SkipOnOldKernel(t, "4.10", "LRU per-CPU hash")
1312 }
1313
1314 arr := createMap(t, typ, 1)
1315
1316 values := []*customEncoding{
1317 {"test"},
1318 {"more"},
1319 }
1320 if err := arr.Put(uint32(0), values); err != nil {
1321 t.Fatal(err)
1322 }
1323
1324 if err := arr.Lookup(uint32(0), nil); err == nil {
1325 t.Fatal("nil valueOut should generate error")
1326 }
1327
1328 // Make sure unmarshaling works on slices containing pointers
1329 retrievedVal := make([]*customEncoding, numCPU)
1330 if err := arr.Lookup(uint32(0), retrievedVal); err == nil {
1331 t.Fatal("Slices with nil values should generate error")
1332 }
1333 for i := range retrievedVal {
1334 retrievedVal[i] = &customEncoding{}
1335 }
1336 if err := arr.Lookup(uint32(0), retrievedVal); err != nil {
1337 t.Fatal("Can't retrieve key 0:", err)
1338 }
1339 var retrieved []*customEncoding
1340 if err := arr.Lookup(uint32(0), &retrieved); err != nil {
1341 t.Fatal("Can't retrieve key 0:", err)
1342 }
1343
1344 for i, want := range []string{"TEST", "MORE"} {
1345 if retrieved[i] == nil {
1346 t.Error("First item is nil")
1347 } else if have := retrieved[i].data; have != want {
1348 t.Errorf("Put doesn't use BinaryMarshaler, expected %s but got %s", want, have)
1349 }
1350 }
1351
1352 })
1353 }
1354 }
1355
1356 type bpfCgroupStorageKey struct {
1357 CgroupInodeId uint64
1358 AttachType AttachType
1359 _ [4]byte // Padding
1360 }
1361
1362 func TestCgroupPerCPUStorageMarshaling(t *testing.T) {
1363 numCPU := MustPossibleCPU()
1364 if numCPU < 2 {
1365 t.Skip("Test requires at least two CPUs")
1366 }
1367 testutils.SkipOnOldKernel(t, "5.9", "per-CPU CGoup storage with write from user space support")
1368
1369 arr := mustNewMap(t, &MapSpec{
1370 Type: PerCPUCGroupStorage,
1371 KeySize: uint32(unsafe.Sizeof(bpfCgroupStorageKey{})),
1372 ValueSize: uint32(unsafe.Sizeof(uint64(0))),
1373 }, nil)
1374
1375 prog := mustNewProgram(t, &ProgramSpec{
1376 Type: CGroupSKB,
1377 AttachType: AttachCGroupInetEgress,
1378 License: "MIT",
1379 Instructions: asm.Instructions{
1380 asm.LoadMapPtr(asm.R1, arr.FD()),
1381 asm.Mov.Imm(asm.R2, 0),
1382 asm.FnGetLocalStorage.Call(),
1383 asm.Mov.Imm(asm.R0, 0),
1384 asm.Return(),
1385 },
1386 }, nil)
1387
1388 cgroup := testutils.CreateCgroup(t)
1389
1390 progAttachAttrs := sys.ProgAttachAttr{
1391 TargetFdOrIfindex: uint32(cgroup.Fd()),
1392 AttachBpfFd: uint32(prog.FD()),
1393 AttachType: uint32(AttachCGroupInetEgress),
1394 AttachFlags: 0,
1395 ReplaceBpfFd: 0,
1396 }
1397 err := sys.ProgAttach(&progAttachAttrs)
1398 if err != nil {
1399 t.Fatal(err)
1400 }
1401 defer func() {
1402 attr := sys.ProgDetachAttr{
1403 TargetFdOrIfindex: uint32(cgroup.Fd()),
1404 AttachBpfFd: uint32(prog.FD()),
1405 AttachType: uint32(AttachCGroupInetEgress),
1406 }
1407 if err := sys.ProgDetach(&attr); err != nil {
1408 t.Fatal(err)
1409 }
1410 }()
1411
1412 var mapKey = &bpfCgroupStorageKey{
1413 CgroupInodeId: testutils.GetCgroupIno(t, cgroup),
1414 AttachType: AttachCGroupInetEgress,
1415 }
1416
1417 values := []uint64{1, 2}
1418 if err := arr.Put(mapKey, values); err != nil {
1419 t.Fatalf("Can't set cgroup %s storage: %s", cgroup.Name(), err)
1420 }
1421
1422 var retrieved []uint64
1423 if err := arr.Lookup(mapKey, &retrieved); err != nil {
1424 t.Fatalf("Can't retrieve cgroup %s storage: %s", cgroup.Name(), err)
1425 }
1426
1427 for i, want := range []uint64{1, 2} {
1428 if retrieved[i] == 0 {
1429 t.Errorf("Item %d is 0", i)
1430 } else if have := retrieved[i]; have != want {
1431 t.Errorf("PerCPUCGroupStorage map is not correctly unmarshaled, expected %d but got %d", want, have)
1432 }
1433 }
1434 }
1435
1436 func TestMapMarshalUnsafe(t *testing.T) {
1437 m := createMap(t, Hash, 1)
1438
1439 key := uint32(1)
1440 value := uint32(42)
1441
1442 if err := m.Put(unsafe.Pointer(&key), unsafe.Pointer(&value)); err != nil {
1443 t.Fatal(err)
1444 }
1445
1446 var res uint32
1447 if err := m.Lookup(unsafe.Pointer(&key), unsafe.Pointer(&res)); err != nil {
1448 t.Fatal("Can't get item:", err)
1449 }
1450
1451 var sum uint32
1452 iter := m.Iterate()
1453 for iter.Next(&key, unsafe.Pointer(&res)) {
1454 sum += res
1455 }
1456 if err := iter.Err(); err != nil {
1457 t.Fatal(err)
1458 }
1459
1460 if res != 42 {
1461 t.Fatalf("Expected 42, got %d", res)
1462 }
1463
1464 iter = m.Iterate()
1465 iter.Next(unsafe.Pointer(&key), &res)
1466 if err := iter.Err(); err != nil {
1467 t.Error(err)
1468 }
1469 if key != 1 {
1470 t.Errorf("Expected key 1, got %d", key)
1471 }
1472
1473 if err := m.Delete(unsafe.Pointer(&key)); err != nil {
1474 t.Fatal("Can't delete:", err)
1475 }
1476 }
1477
1478 func TestMapName(t *testing.T) {
1479 testutils.SkipIfNotSupported(t, haveObjName())
1480
1481 m := mustNewMap(t, &MapSpec{
1482 Name: "test!123",
1483 Type: Array,
1484 KeySize: 4,
1485 ValueSize: 4,
1486 MaxEntries: 1,
1487 }, nil)
1488
1489 var info sys.MapInfo
1490 if err := sys.ObjInfo(m.fd, &info); err != nil {
1491 t.Fatal(err)
1492 }
1493
1494 name := unix.ByteSliceToString(info.Name[:])
1495 qt.Assert(t, qt.Equals(name, "test123"))
1496 }
1497
1498 func TestMapFromFD(t *testing.T) {
1499 m := createMap(t, Array, 2)
1500
1501 if err := m.Put(uint32(0), uint32(123)); err != nil {
1502 t.Fatal(err)
1503 }
1504
1505 // If you're thinking about copying this, don't. Use
1506 // Clone() instead.
1507 m2, err := NewMapFromFD(testutils.DupFD(t, m.FD()))
1508 testutils.SkipIfNotSupported(t, err)
1509 if err != nil {
1510 t.Fatal(err)
1511 }
1512 defer m2.Close()
1513
1514 var val uint32
1515 if err := m2.Lookup(uint32(0), &val); err != nil {
1516 t.Fatal("Can't look up key:", err)
1517 }
1518
1519 if val != 123 {
1520 t.Error("Wrong value")
1521 }
1522 }
1523
1524 func TestMapContents(t *testing.T) {
1525 spec := &MapSpec{
1526 Type: Array,
1527 KeySize: 4,
1528 ValueSize: 4,
1529 MaxEntries: 2,
1530 Contents: []MapKV{
1531 {uint32(0), uint32(23)},
1532 {uint32(1), uint32(42)},
1533 },
1534 }
1535
1536 m := mustNewMap(t, spec, nil)
1537
1538 var value uint32
1539 if err := m.Lookup(uint32(0), &value); err != nil {
1540 t.Error("Can't look up key 0:", err)
1541 } else if value != 23 {
1542 t.Errorf("Incorrect value for key 0, expected 23, have %d", value)
1543 }
1544
1545 if err := m.Lookup(uint32(1), &value); err != nil {
1546 t.Error("Can't look up key 1:", err)
1547 } else if value != 42 {
1548 t.Errorf("Incorrect value for key 0, expected 23, have %d", value)
1549 }
1550
1551 spec.Contents = []MapKV{
1552 // Key is larger than MaxEntries
1553 {uint32(14), uint32(0)},
1554 }
1555
1556 // Invalid contents should be rejected
1557 _, err := newMap(t, spec, nil)
1558 qt.Assert(t, qt.IsNotNil(err))
1559 }
1560
1561 func TestMapFreeze(t *testing.T) {
1562 arr := createMap(t, Array, 2)
1563
1564 err := arr.Freeze()
1565 testutils.SkipIfNotSupported(t, err)
1566
1567 if err != nil {
1568 t.Fatal("Can't freeze map:", err)
1569 }
1570
1571 if err := arr.Put(uint32(0), uint32(1)); err == nil {
1572 t.Error("Freeze doesn't prevent modification from user space")
1573 }
1574
1575 info, err := arr.Info()
1576 qt.Assert(t, qt.IsNil(err))
1577 qt.Assert(t, qt.IsTrue(info.Frozen()))
1578 }
1579
1580 func TestMapGetNextID(t *testing.T) {
1581 testutils.SkipOnOldKernel(t, "4.13", "bpf_map_get_next_id")
1582 var next MapID
1583 var err error
1584
1585 // Ensure there is at least one map on the system.
1586 _ = createMap(t, Hash, 10)
1587
1588 if next, err = MapGetNextID(MapID(0)); err != nil {
1589 t.Fatal("Can't get next ID:", err)
1590 }
1591 if next == MapID(0) {
1592 t.Fatal("Expected next ID other than 0")
1593 }
1594
1595 // As there can be multiple eBPF maps, we loop over all of them and
1596 // make sure, the IDs increase and the last call will return ErrNotExist
1597 for {
1598 last := next
1599 if next, err = MapGetNextID(last); err != nil {
1600 if !errors.Is(err, os.ErrNotExist) {
1601 t.Fatal("Expected ErrNotExist, got:", err)
1602 }
1603 break
1604 }
1605 if next <= last {
1606 t.Fatalf("Expected next ID (%d) to be higher than the last ID (%d)", next, last)
1607 }
1608 }
1609 }
1610
1611 func TestNewMapFromID(t *testing.T) {
1612 hash := createMap(t, Hash, 10)
1613
1614 info, err := hash.Info()
1615 testutils.SkipIfNotSupported(t, err)
1616 if err != nil {
1617 t.Fatal("Couldn't get map info:", err)
1618 }
1619
1620 id, ok := info.ID()
1621 if !ok {
1622 t.Skip("Map ID not supported")
1623 }
1624
1625 hash2, err := NewMapFromID(id)
1626 if err != nil {
1627 t.Fatalf("Can't get map for ID %d: %v", id, err)
1628 }
1629 hash2.Close()
1630
1631 // As there can be multiple maps, we use max(uint32) as MapID to trigger an expected error.
1632 _, err = NewMapFromID(MapID(math.MaxUint32))
1633 if !errors.Is(err, os.ErrNotExist) {
1634 t.Fatal("Expected ErrNotExist, got:", err)
1635 }
1636 }
1637
1638 func TestMapPinning(t *testing.T) {
1639 tmp := testutils.TempBPFFS(t)
1640
1641 spec := &MapSpec{
1642 Name: "test",
1643 Type: Hash,
1644 KeySize: 4,
1645 ValueSize: 4,
1646 MaxEntries: 1,
1647 Pinning: PinByName,
1648 }
1649
1650 m1 := mustNewMap(t, spec, &MapOptions{PinPath: tmp})
1651 pinned := m1.IsPinned()
1652 qt.Assert(t, qt.IsTrue(pinned))
1653
1654 m1Info, err := m1.Info()
1655 qt.Assert(t, qt.IsNil(err))
1656
1657 if err := m1.Put(uint32(0), uint32(42)); err != nil {
1658 t.Fatal("Can't write value:", err)
1659 }
1660
1661 m2 := mustNewMap(t, spec, &MapOptions{PinPath: tmp})
1662
1663 m2Info, err := m2.Info()
1664 qt.Assert(t, qt.IsNil(err))
1665
1666 if m1ID, ok := m1Info.ID(); ok {
1667 m2ID, _ := m2Info.ID()
1668 qt.Assert(t, qt.Equals(m2ID, m1ID))
1669 }
1670
1671 var value uint32
1672 if err := m2.Lookup(uint32(0), &value); err != nil {
1673 t.Fatal("Can't read from map:", err)
1674 }
1675
1676 if value != 42 {
1677 t.Fatal("Pinning doesn't use pinned maps")
1678 }
1679
1680 spec.KeySize = 8
1681 spec.ValueSize = 8
1682 _, err = newMap(t, spec, &MapOptions{PinPath: tmp})
1683 if err == nil {
1684 t.Fatalf("Opening a pinned map with a mismatching spec did not fail")
1685 }
1686 if !errors.Is(err, ErrMapIncompatible) {
1687 t.Fatalf("Opening a pinned map with a mismatching spec failed with the wrong error")
1688 }
1689
1690 // Check if error string mentions both KeySize and ValueSize.
1691 qt.Assert(t, qt.StringContains(err.Error(), "KeySize"))
1692 qt.Assert(t, qt.StringContains(err.Error(), "ValueSize"))
1693 }
1694
1695 func TestMapHandle(t *testing.T) {
1696 kv := &btf.Int{Size: 4}
1697 m := mustNewMap(t, &MapSpec{
1698 Type: Hash,
1699 KeySize: kv.Size,
1700 ValueSize: kv.Size,
1701 Key: kv,
1702 Value: kv,
1703 MaxEntries: 1,
1704 }, nil)
1705
1706 h, err := m.Handle()
1707 testutils.SkipIfNotSupported(t, err)
1708 qt.Assert(t, qt.IsNil(err))
1709 qt.Assert(t, qt.IsNotNil(h))
1710 defer h.Close()
1711
1712 spec, err := h.Spec(nil)
1713 qt.Assert(t, qt.IsNil(err))
1714
1715 typ, err := spec.TypeByID(1)
1716 qt.Assert(t, qt.IsNil(err))
1717 qt.Assert(t, qt.ContentEquals(typ, btf.Type(kv)))
1718 }
1719
1720 func TestPerfEventArrayCompatible(t *testing.T) {
1721 ms := &MapSpec{
1722 Type: PerfEventArray,
1723 }
1724
1725 m := mustNewMap(t, ms, nil)
1726 qt.Assert(t, qt.IsNil(ms.Compatible(m)))
1727
1728 ms.MaxEntries = m.MaxEntries() - 1
1729 qt.Assert(t, qt.IsNotNil(ms.Compatible(m)))
1730 }
1731
1732 func TestLoadWrongPin(t *testing.T) {
1733 p := createBasicProgram(t)
1734 m := createMap(t, Hash, 10)
1735 tmp := testutils.TempBPFFS(t)
1736
1737 ppath := filepath.Join(tmp, "prog")
1738 mpath := filepath.Join(tmp, "map")
1739
1740 qt.Assert(t, qt.IsNil(m.Pin(mpath)))
1741 qt.Assert(t, qt.IsNil(p.Pin(ppath)))
1742
1743 t.Run("Program", func(t *testing.T) {
1744 lp, err := LoadPinnedProgram(ppath, nil)
1745 testutils.SkipIfNotSupported(t, err)
1746 qt.Assert(t, qt.IsNil(err))
1747 qt.Assert(t, qt.IsNil(lp.Close()))
1748
1749 _, err = LoadPinnedProgram(mpath, nil)
1750 qt.Assert(t, qt.IsNotNil(err))
1751 })
1752
1753 t.Run("Map", func(t *testing.T) {
1754 lm, err := LoadPinnedMap(mpath, nil)
1755 testutils.SkipIfNotSupported(t, err)
1756 qt.Assert(t, qt.IsNil(err))
1757 qt.Assert(t, qt.IsNil(lm.Close()))
1758
1759 _, err = LoadPinnedMap(ppath, nil)
1760 qt.Assert(t, qt.IsNotNil(err))
1761 })
1762 }
1763
1764 func TestMapWithToken(t *testing.T) {
1765 testutils.RunWithToken(t, "no-cmd", testutils.Delegated{
1766 Cmds: []sys.Cmd{},
1767 Maps: []sys.MapType{sys.BPF_MAP_TYPE_HASH},
1768 }, func(t *testing.T) {
1769 _, err := newMap(t, hashMapSpec, nil)
1770 qt.Assert(t, qt.ErrorIs(err, unix.EPERM))
1771 })
1772
1773 testutils.RunWithToken(t, "no-map", testutils.Delegated{
1774 Cmds: []sys.Cmd{sys.BPF_MAP_CREATE},
1775 Maps: []sys.MapType{},
1776 }, func(t *testing.T) {
1777 _, err := newMap(t, hashMapSpec, nil)
1778 qt.Assert(t, qt.ErrorIs(err, unix.EPERM))
1779 })
1780
1781 testutils.RunWithToken(t, "success", testutils.Delegated{
1782 Cmds: []sys.Cmd{sys.BPF_MAP_CREATE},
1783 Maps: []sys.MapType{sys.BPF_MAP_TYPE_HASH},
1784 }, func(t *testing.T) {
1785 _, err := newMap(t, hashMapSpec, nil)
1786 qt.Assert(t, qt.IsNil(err))
1787 })
1788 }
1789
1790 type benchValue struct {
1791 ID uint32
1792 Val16 uint16
1793 Val16_2 uint16
1794 Name [8]byte
1795 LID uint64
1796 }
1797
1798 type customBenchValue benchValue
1799
1800 func (cbv *customBenchValue) UnmarshalBinary(buf []byte) error {
1801 cbv.ID = internal.NativeEndian.Uint32(buf)
1802 cbv.Val16 = internal.NativeEndian.Uint16(buf[4:])
1803 cbv.Val16_2 = internal.NativeEndian.Uint16(buf[6:])
1804 copy(cbv.Name[:], buf[8:])
1805 cbv.LID = internal.NativeEndian.Uint64(buf[16:])
1806 return nil
1807 }
1808
1809 func (cbv *customBenchValue) MarshalBinary() ([]byte, error) {
1810 buf := make([]byte, 24)
1811 internal.NativeEndian.PutUint32(buf, cbv.ID)
1812 internal.NativeEndian.PutUint16(buf[4:], cbv.Val16)
1813 internal.NativeEndian.PutUint16(buf[6:], cbv.Val16_2)
1814 copy(buf[8:], cbv.Name[:])
1815 internal.NativeEndian.PutUint64(buf[16:], cbv.LID)
1816 return buf, nil
1817 }
1818
1819 type benchKey struct {
1820 id uint64
1821 }
1822
1823 func (bk *benchKey) MarshalBinary() ([]byte, error) {
1824 buf := make([]byte, 8)
1825 internal.NativeEndian.PutUint64(buf, bk.id)
1826 return buf, nil
1827 }
1828
1829 func BenchmarkMarshaling(b *testing.B) {
1830 newMap := func(valueSize uint32) *Map {
1831 return mustNewMap(b, &MapSpec{
1832 Type: Hash,
1833 KeySize: 8,
1834 ValueSize: valueSize,
1835 MaxEntries: 1,
1836 }, nil)
1837 }
1838
1839 key := uint64(0)
1840
1841 m := newMap(24)
1842 if err := m.Put(key, benchValue{}); err != nil {
1843 b.Fatal(err)
1844 }
1845 b.Cleanup(func() { m.Close() })
1846
1847 b.Run("ValueUnmarshalReflect", func(b *testing.B) {
1848 b.ReportAllocs()
1849
1850 var value benchValue
1851
1852 for b.Loop() {
1853 err := m.Lookup(unsafe.Pointer(&key), &value)
1854 if err != nil {
1855 b.Fatal("Can't get key:", err)
1856 }
1857 }
1858 })
1859
1860 b.Run("KeyMarshalReflect", func(b *testing.B) {
1861 b.ReportAllocs()
1862
1863 var value benchValue
1864
1865 for b.Loop() {
1866 err := m.Lookup(&key, unsafe.Pointer(&value))
1867 if err != nil {
1868 b.Fatal("Can't get key:", err)
1869 }
1870 }
1871 })
1872
1873 b.Run("ValueBinaryUnmarshaler", func(b *testing.B) {
1874 b.ReportAllocs()
1875
1876 var value customBenchValue
1877
1878 for b.Loop() {
1879 err := m.Lookup(unsafe.Pointer(&key), &value)
1880 if err != nil {
1881 b.Fatal("Can't get key:", err)
1882 }
1883 }
1884 })
1885
1886 b.Run("KeyBinaryMarshaler", func(b *testing.B) {
1887 b.ReportAllocs()
1888
1889 var key benchKey
1890 var value customBenchValue
1891
1892 for b.Loop() {
1893 err := m.Lookup(&key, unsafe.Pointer(&value))
1894 if err != nil {
1895 b.Fatal("Can't get key:", err)
1896 }
1897 }
1898 })
1899
1900 b.Run("KeyValueUnsafe", func(b *testing.B) {
1901 b.ReportAllocs()
1902
1903 var value benchValue
1904
1905 for b.Loop() {
1906 err := m.Lookup(unsafe.Pointer(&key), unsafe.Pointer(&value))
1907 if err != nil {
1908 b.Fatal("Can't get key:", err)
1909 }
1910 }
1911 })
1912 }
1913
1914 func BenchmarkPerCPUMarshalling(b *testing.B) {
1915 key := uint64(1)
1916 val := make([]uint64, MustPossibleCPU())
1917 for i := range val {
1918 val[i] = uint64(i)
1919 }
1920
1921 m := mustNewMap(b, &MapSpec{
1922 Type: PerCPUHash,
1923 KeySize: 8,
1924 ValueSize: 8,
1925 MaxEntries: 1,
1926 }, nil)
1927
1928 if err := m.Put(key, val[0:]); err != nil {
1929 b.Fatal(err)
1930 }
1931
1932 b.Run("reflection", func(b *testing.B) {
1933 b.ReportAllocs()
1934
1935 var value []uint64
1936
1937 for b.Loop() {
1938 err := m.Lookup(unsafe.Pointer(&key), &value)
1939 if err != nil {
1940 b.Fatal("Can't get key:", err)
1941 }
1942 }
1943 })
1944 }
1945
1946 func BenchmarkMap(b *testing.B) {
1947 m := createMap(b, Hash, 1)
1948
1949 if err := m.Put(uint32(0), uint32(42)); err != nil {
1950 b.Fatal(err)
1951 }
1952
1953 b.Run("Lookup", func(b *testing.B) {
1954 var key, value uint32
1955
1956 b.ReportAllocs()
1957
1958 for b.Loop() {
1959 err := m.Lookup(unsafe.Pointer(&key), unsafe.Pointer(&value))
1960 if err != nil {
1961 b.Fatal(err)
1962 }
1963 }
1964 })
1965
1966 b.Run("Update", func(b *testing.B) {
1967 var key, value uint32
1968
1969 b.ReportAllocs()
1970
1971 for b.Loop() {
1972 err := m.Update(unsafe.Pointer(&key), unsafe.Pointer(&value), UpdateAny)
1973 if err != nil {
1974 b.Fatal(err)
1975 }
1976 }
1977 })
1978
1979 b.Run("NextKey", func(b *testing.B) {
1980 var key uint32
1981
1982 b.ReportAllocs()
1983
1984 for b.Loop() {
1985 err := m.NextKey(nil, unsafe.Pointer(&key))
1986 if err != nil {
1987 b.Fatal(err)
1988 }
1989 }
1990 })
1991
1992 b.Run("Delete", func(b *testing.B) {
1993 var key uint32
1994
1995 b.ReportAllocs()
1996
1997 for b.Loop() {
1998 err := m.Delete(unsafe.Pointer(&key))
1999 if err != nil && !errors.Is(err, ErrKeyNotExist) {
2000 b.Fatal(err)
2001 }
2002 }
2003 })
2004 }
2005
2006 func BenchmarkIterate(b *testing.B) {
2007 for _, mt := range []MapType{Hash, PerCPUHash} {
2008 m := mustNewMap(b, &MapSpec{
2009 Type: mt,
2010 KeySize: 8,
2011 ValueSize: 8,
2012 MaxEntries: 1000,
2013 }, nil)
2014
2015 possibleCPU := 1
2016 if m.Type().hasPerCPUValue() {
2017 possibleCPU = MustPossibleCPU()
2018 }
2019 var (
2020 n = m.MaxEntries()
2021 keys = make([]uint64, n)
2022 values = make([]uint64, n*uint32(possibleCPU))
2023 )
2024
2025 for i := 0; uint32(i) < n; i++ {
2026 keys[i] = uint64(i)
2027 for j := 0; j < possibleCPU; j++ {
2028 values[i] = uint64((i * possibleCPU) + j)
2029 }
2030 }
2031
2032 _, err := m.BatchUpdate(keys, values, nil)
2033 testutils.SkipIfNotSupported(b, err)
2034 qt.Assert(b, qt.IsNil(err))
2035
2036 b.Run(m.Type().String(), func(b *testing.B) {
2037 b.Run("MapIterator", func(b *testing.B) {
2038 var k uint64
2039 v := make([]uint64, possibleCPU)
2040
2041 b.ReportAllocs()
2042
2043 for b.Loop() {
2044 iter := m.Iterate()
2045 for iter.Next(&k, v) {
2046 continue
2047 }
2048 if err := iter.Err(); err != nil {
2049 b.Fatal(err)
2050 }
2051 }
2052 })
2053
2054 b.Run("MapIteratorDelete", func(b *testing.B) {
2055 var k uint64
2056 v := make([]uint64, possibleCPU)
2057
2058 b.ReportAllocs()
2059
2060 for b.Loop() {
2061 b.StopTimer()
2062 if _, err := m.BatchUpdate(keys, values, nil); err != nil {
2063 b.Fatal(err)
2064 }
2065 b.StartTimer()
2066
2067 iter := m.Iterate()
2068 for iter.Next(&k, &v) {
2069 if err := m.Delete(&k); err != nil {
2070 b.Fatal(err)
2071 }
2072 }
2073 if err := iter.Err(); err != nil {
2074 b.Fatal(err)
2075 }
2076 }
2077 })
2078
2079 b.Run("BatchLookup", func(b *testing.B) {
2080 k := make([]uint64, m.MaxEntries())
2081 v := make([]uint64, m.MaxEntries()*uint32(possibleCPU))
2082
2083 b.ReportAllocs()
2084
2085 for b.Loop() {
2086 var cursor MapBatchCursor
2087 for {
2088 _, err := m.BatchLookup(&cursor, k, v, nil)
2089 if errors.Is(err, ErrKeyNotExist) {
2090 break
2091 }
2092 if err != nil {
2093 b.Fatal(err)
2094 }
2095 }
2096 }
2097 })
2098
2099 b.Run("BatchLookupAndDelete", func(b *testing.B) {
2100 k := make([]uint64, m.MaxEntries())
2101 v := make([]uint64, m.MaxEntries()*uint32(possibleCPU))
2102
2103 b.ReportAllocs()
2104
2105 for b.Loop() {
2106 b.StopTimer()
2107 if _, err := m.BatchUpdate(keys, values, nil); err != nil {
2108 b.Fatal(err)
2109 }
2110 b.StartTimer()
2111
2112 var cursor MapBatchCursor
2113 for {
2114 _, err := m.BatchLookupAndDelete(&cursor, k, v, nil)
2115 if errors.Is(err, ErrKeyNotExist) {
2116 break
2117 }
2118 if err != nil {
2119 b.Fatal(err)
2120 }
2121 }
2122 }
2123 })
2124
2125 b.Run("BatchDelete", func(b *testing.B) {
2126 b.ReportAllocs()
2127
2128 for b.Loop() {
2129 b.StopTimer()
2130 if _, err := m.BatchUpdate(keys, values, nil); err != nil {
2131 b.Fatal(err)
2132 }
2133 b.StartTimer()
2134
2135 if _, err := m.BatchDelete(keys, nil); err != nil {
2136 b.Fatal(err)
2137 }
2138 }
2139 })
2140 })
2141 }
2142 }
2143
2144 // Per CPU maps store a distinct value for each CPU. They are useful
2145 // to collect metrics.
2146 func ExampleMap_perCPU() {
2147 arr, err := NewMap(&MapSpec{
2148 Type: PerCPUArray,
2149 KeySize: 4,
2150 ValueSize: 4,
2151 MaxEntries: 2,
2152 })
2153 if err != nil {
2154 panic(err)
2155 }
2156 defer arr.Close()
2157
2158 possibleCPUs := MustPossibleCPU()
2159 perCPUValues := map[uint32]uint32{
2160 0: 4,
2161 1: 5,
2162 }
2163
2164 for k, v := range perCPUValues {
2165 // We set each perCPU slots to the same value.
2166 values := make([]uint32, possibleCPUs)
2167 for i := range values {
2168 values[i] = v
2169 }
2170 if err := arr.Put(k, values); err != nil {
2171 panic(err)
2172 }
2173 }
2174
2175 for k := range 2 {
2176 var values []uint32
2177 if err := arr.Lookup(uint32(k), &values); err != nil {
2178 panic(err)
2179 }
2180 // Note we will print an unexpected message if this is not true.
2181 fmt.Printf("Value of key %v on all CPUs: %v\n", k, values[0])
2182 }
2183 var (
2184 key uint32
2185 entries = arr.Iterate()
2186 )
2187
2188 var values []uint32
2189 for entries.Next(&key, &values) {
2190 expected, ok := perCPUValues[key]
2191 if !ok {
2192 fmt.Printf("Unexpected key %v\n", key)
2193 continue
2194 }
2195
2196 for i, n := range values {
2197 if n != expected {
2198 fmt.Printf("Key %v, Value for cpu %v is %v not %v\n",
2199 key, i, n, expected)
2200 }
2201 }
2202 }
2203
2204 if err := entries.Err(); err != nil {
2205 panic(err)
2206 }
2207 }
2208
2209 // It is possible to use unsafe.Pointer to avoid marshalling
2210 // and copy overhead. It is the responsibility of the caller to ensure
2211 // the correct size of unsafe.Pointers.
2212 //
2213 // Note that using unsafe.Pointer is only marginally faster than
2214 // implementing Marshaler on the type.
2215 func ExampleMap_zeroCopy() {
2216 hash, err := NewMap(&MapSpec{
2217 Type: Hash,
2218 KeySize: 5,
2219 ValueSize: 4,
2220 MaxEntries: 10,
2221 })
2222 if err != nil {
2223 panic(err)
2224 }
2225 defer hash.Close()
2226
2227 key := [5]byte{'h', 'e', 'l', 'l', 'o'}
2228 value := uint32(23)
2229
2230 if err := hash.Put(unsafe.Pointer(&key), unsafe.Pointer(&value)); err != nil {
2231 panic(err)
2232 }
2233
2234 value = 0
2235 if err := hash.Lookup(unsafe.Pointer(&key), unsafe.Pointer(&value)); err != nil {
2236 panic("can't get value:" + err.Error())
2237 }
2238
2239 fmt.Printf("The value is: %d\n", value)
2240 }
2241
2242 func ExampleMap_NextKey() {
2243 hash, err := NewMap(&MapSpec{
2244 Type: Hash,
2245 KeySize: 5,
2246 ValueSize: 4,
2247 MaxEntries: 10,
2248 Contents: []MapKV{
2249 {"hello", uint32(21)},
2250 {"world", uint32(42)},
2251 },
2252 })
2253 if err != nil {
2254 panic(err)
2255 }
2256 defer hash.Close()
2257
2258 var cur, next string
2259 var keys []string
2260
2261 for err = hash.NextKey(nil, &next); ; err = hash.NextKey(cur, &next) {
2262 if errors.Is(err, ErrKeyNotExist) {
2263 break
2264 }
2265 if err != nil {
2266 panic(err)
2267 }
2268 keys = append(keys, next)
2269 cur = next
2270 }
2271
2272 // Order of keys is non-deterministic due to randomized map seed
2273 sort.Strings(keys)
2274 fmt.Printf("Keys are %v\n", keys)
2275 }
2276
2277 // ExampleMap_Iterate demonstrates how to iterate over all entries
2278 // in a map.
2279 func ExampleMap_Iterate() {
2280 hash, err := NewMap(&MapSpec{
2281 Type: Hash,
2282 KeySize: 5,
2283 ValueSize: 4,
2284 MaxEntries: 10,
2285 Contents: []MapKV{
2286 {"hello", uint32(21)},
2287 {"world", uint32(42)},
2288 },
2289 })
2290 if err != nil {
2291 panic(err)
2292 }
2293 defer hash.Close()
2294
2295 var (
2296 key string
2297 value uint32
2298 entries = hash.Iterate()
2299 )
2300
2301 values := make(map[string]uint32)
2302 for entries.Next(&key, &value) {
2303 // Order of keys is non-deterministic due to randomized map seed
2304 values[key] = value
2305 }
2306
2307 if err := entries.Err(); err != nil {
2308 panic(fmt.Sprint("Iterator encountered an error:", err))
2309 }
2310
2311 for k, v := range values {
2312 fmt.Printf("key: %s, value: %d\n", k, v)
2313 }
2314 }
2315
2316 // It is possible to iterate nested maps and program arrays by
2317 // unmarshaling into a *Map or *Program.
2318 func ExampleMap_Iterate_nestedMapsAndProgramArrays() {
2319 inner := &MapSpec{
2320 Type: Array,
2321 KeySize: 4,
2322 ValueSize: 4,
2323 MaxEntries: 2,
2324 Contents: []MapKV{
2325 {uint32(0), uint32(1)},
2326 {uint32(1), uint32(2)},
2327 },
2328 }
2329 im, err := NewMap(inner)
2330 if err != nil {
2331 panic(err)
2332 }
2333 defer im.Close()
2334
2335 outer := &MapSpec{
2336 Type: ArrayOfMaps,
2337 InnerMap: inner,
2338 KeySize: 4,
2339 ValueSize: 4,
2340 MaxEntries: 10,
2341 Contents: []MapKV{
2342 {uint32(0), im},
2343 },
2344 }
2345 arrayOfMaps, err := NewMap(outer)
2346 if errors.Is(err, internal.ErrNotSupported) {
2347 // Fake the output if on very old kernel.
2348 fmt.Println("outerKey: 0")
2349 fmt.Println("\tinnerKey 0 innerValue 1")
2350 fmt.Println("\tinnerKey 1 innerValue 2")
2351 return
2352 }
2353 if err != nil {
2354 panic(err)
2355 }
2356 defer arrayOfMaps.Close()
2357
2358 var (
2359 key uint32
2360 m *Map
2361 entries = arrayOfMaps.Iterate()
2362 )
2363 for entries.Next(&key, &m) {
2364 // Make sure that the iterated map is closed after
2365 // we are done.
2366 defer m.Close()
2367
2368 // Order of keys is non-deterministic due to randomized map seed
2369 fmt.Printf("outerKey: %v\n", key)
2370
2371 var innerKey, innerValue uint32
2372 items := m.Iterate()
2373 for items.Next(&innerKey, &innerValue) {
2374 fmt.Printf("\tinnerKey %v innerValue %v\n", innerKey, innerValue)
2375 }
2376 if err := items.Err(); err != nil {
2377 panic(fmt.Sprint("Inner Iterator encountered an error:", err))
2378 }
2379 }
2380
2381 if err := entries.Err(); err != nil {
2382 panic(fmt.Sprint("Iterator encountered an error:", err))
2383 }
2384 }