Debian Codegraph @

map.go

raw symbols SCIP
1 package ebpf
2
3 import (
4 "bytes"
5 "errors"
6 "fmt"
7 "io"
8 "math/rand"
9 "os"
10 "path/filepath"
11 "reflect"
12 "slices"
13 "strings"
14 "sync"
15 "time"
16 "unsafe"
17
18 "github.com/cilium/ebpf/btf"
19 "github.com/cilium/ebpf/internal"
20 "github.com/cilium/ebpf/internal/platform"
21 "github.com/cilium/ebpf/internal/sys"
22 "github.com/cilium/ebpf/internal/sysenc"
23 "github.com/cilium/ebpf/internal/unix"
24 )
25
26 // Errors returned by Map and MapIterator methods.
27 var (
28 ErrKeyNotExist = errors.New("key does not exist")
29 ErrKeyExist = errors.New("key already exists")
30 ErrIterationAborted = errors.New("iteration aborted")
31 ErrMapIncompatible = errors.New("map spec is incompatible with existing map")
32
33 // pre-allocating these errors here since they may get called in hot code paths
34 // and cause unnecessary memory allocations
35 errMapLookupKeyNotExist = fmt.Errorf("lookup: %w", sysErrKeyNotExist)
36 )
37
38 // MapOptions control loading a map into the kernel.
39 type MapOptions struct {
40 // The base path to pin maps in if requested via PinByName.
41 // Existing maps will be re-used if they are compatible, otherwise an
42 // error is returned.
43 PinPath string
44 LoadPinOptions LoadPinOptions
45 }
46
47 // MapID represents the unique ID of an eBPF map
48 type MapID = sys.MapID
49
50 // MapSpec defines a Map.
51 type MapSpec struct {
52 // Name is passed to the kernel as a debug aid.
53 //
54 // Unsupported characters will be stripped.
55 Name string
56 Type MapType
57 KeySize uint32
58 ValueSize uint32
59 MaxEntries uint32
60
61 // Flags is passed to the kernel and specifies additional map
62 // creation attributes.
63 Flags uint32
64
65 // Automatically pin and load a map from MapOptions.PinPath.
66 // Generates an error if an existing pinned map is incompatible with the MapSpec.
67 Pinning PinType
68
69 // Specify numa node during map creation
70 // (effective only if sys.BPF_F_NUMA_NODE flag is set,
71 // which can be imported from golang.org/x/sys/unix)
72 NumaNode uint32
73
74 // The initial contents of the map. May be nil.
75 Contents []MapKV
76
77 // InnerMap is used as a template for ArrayOfMaps and HashOfMaps
78 InnerMap *MapSpec
79
80 // MapExtra is an opaque field whose meaning is map-specific.
81 //
82 // Available from 5.16.
83 MapExtra uint64
84
85 // Extra trailing bytes found in the ELF map definition when using structs
86 // larger than libbpf's bpf_map_def. nil if no trailing bytes were present.
87 // Must be nil or empty before instantiating the MapSpec into a Map.
88 Extra *bytes.Reader
89
90 // The key and value type of this map. May be nil.
91 Key, Value btf.Type
92
93 // Tags is a list of btf_decl_tag attributes set on the map definition.
94 //
95 // Decorate a map definition with `__attribute__((btf_decl_tag("foo")))`.
96 Tags []string
97 }
98
99 func (ms *MapSpec) String() string {
100 return fmt.Sprintf("%s(keySize=%d, valueSize=%d, maxEntries=%d, flags=%d)", ms.Type, ms.KeySize, ms.ValueSize, ms.MaxEntries, ms.Flags)
101 }
102
103 // Copy returns a copy of the spec.
104 //
105 // MapSpec.Contents is a shallow copy.
106 func (ms *MapSpec) Copy() *MapSpec {
107 if ms == nil {
108 return nil
109 }
110
111 cpy := *ms
112 cpy.Contents = slices.Clone(cpy.Contents)
113 cpy.Key = btf.Copy(cpy.Key)
114 cpy.Value = btf.Copy(cpy.Value)
115 cpy.Tags = slices.Clone(cpy.Tags)
116
117 if cpy.InnerMap == ms {
118 cpy.InnerMap = &cpy
119 } else {
120 cpy.InnerMap = ms.InnerMap.Copy()
121 }
122
123 if cpy.Extra != nil {
124 extra := *cpy.Extra
125 cpy.Extra = &extra
126 }
127
128 return &cpy
129 }
130
131 // fixupMagicFields fills fields of MapSpec which are usually
132 // left empty in ELF or which depend on runtime information.
133 //
134 // The method doesn't modify Spec, instead returning a copy.
135 // The copy is only performed if fixups are necessary, so callers mustn't mutate
136 // the returned spec.
137 func (spec *MapSpec) fixupMagicFields() (*MapSpec, error) {
138 switch {
139 case spec.Type.canStoreMap():
140 if spec.ValueSize != 0 && spec.ValueSize != 4 {
141 return nil, errors.New("ValueSize must be zero or four for map of map")
142 }
143
144 spec = spec.Copy()
145 spec.ValueSize = 4
146
147 case spec.Type == PerfEventArray:
148 if spec.KeySize != 0 && spec.KeySize != 4 {
149 return nil, errors.New("KeySize must be zero or four for perf event array")
150 }
151
152 if spec.ValueSize != 0 && spec.ValueSize != 4 {
153 return nil, errors.New("ValueSize must be zero or four for perf event array")
154 }
155
156 spec = spec.Copy()
157 spec.KeySize = 4
158 spec.ValueSize = 4
159
160 n, err := PossibleCPU()
161 if err != nil {
162 return nil, fmt.Errorf("fixup perf event array: %w", err)
163 }
164
165 if n := uint32(n); spec.MaxEntries == 0 || spec.MaxEntries > n {
166 // MaxEntries should be zero most of the time, but there is code
167 // out there which hardcodes large constants. Clamp the number
168 // of entries to the number of CPUs at most. Allow creating maps with
169 // less than n items since some kernel selftests relied on this
170 // behaviour in the past.
171 spec.MaxEntries = n
172 }
173
174 case spec.Type == CPUMap:
175 n, err := PossibleCPU()
176 if err != nil {
177 return nil, fmt.Errorf("fixup cpu map: %w", err)
178 }
179
180 if n := uint32(n); spec.MaxEntries == 0 || spec.MaxEntries > n {
181 // Perform clamping similar to PerfEventArray.
182 spec.MaxEntries = n
183 }
184 }
185
186 return spec, nil
187 }
188
189 // dataSection returns the contents of a datasec if the MapSpec represents one.
190 func (ms *MapSpec) dataSection() ([]byte, error) {
191 if n := len(ms.Contents); n != 1 {
192 return nil, fmt.Errorf("expected one key, found %d", n)
193 }
194
195 kv := ms.Contents[0]
196 if key, ok := ms.Contents[0].Key.(uint32); !ok || key != 0 {
197 return nil, fmt.Errorf("expected contents to have key 0")
198 }
199
200 value, ok := kv.Value.([]byte)
201 if !ok {
202 return nil, fmt.Errorf("value at first map key is %T, not []byte", kv.Value)
203 }
204
205 return value, nil
206 }
207
208 // updateDataSection copies the values of variables into MapSpec.Contents[0].Value.
209 //
210 // Only variables declared in sectionName will be updated.
211 func (ms *MapSpec) updateDataSection(vars map[string]*VariableSpec, sectionName string) error {
212 var specs []*VariableSpec
213 for _, vs := range vars {
214 if vs.SectionName != sectionName {
215 continue
216 }
217
218 specs = append(specs, vs)
219 }
220
221 if len(specs) == 0 {
222 return nil
223 }
224
225 data, err := ms.dataSection()
226 if err != nil {
227 return err
228 }
229
230 // Do not modify the original data slice, ms.Contents is a shallow copy.
231 data = slices.Clone(data)
232
233 slices.SortFunc(specs, func(a, b *VariableSpec) int {
234 return int(int64(a.Offset) - int64(b.Offset))
235 })
236
237 offset := uint32(0)
238 for _, v := range specs {
239 if v.Offset < offset {
240 return fmt.Errorf("variable %s (offset %d) overlaps with previous variable (offset %d)", v.Name, v.Offset, offset)
241 }
242
243 end := v.Offset + v.Size()
244 if int(end) > len(data) {
245 return fmt.Errorf("variable %s exceeds map size", v.Name)
246 }
247
248 copy(data[v.Offset:end], v.Value)
249 offset = end
250 }
251
252 ms.Contents = []MapKV{{Key: uint32(0), Value: data}}
253 return nil
254 }
255
256 func (ms *MapSpec) readOnly() bool {
257 return (ms.Flags & sys.BPF_F_RDONLY_PROG) > 0
258 }
259
260 func (ms *MapSpec) writeOnly() bool {
261 return (ms.Flags & sys.BPF_F_WRONLY_PROG) > 0
262 }
263
264 // MapKV is used to initialize the contents of a Map.
265 type MapKV struct {
266 Key any
267 Value any
268 }
269
270 // Compatible returns nil if an existing map may be used instead of creating
271 // one from the spec.
272 //
273 // Returns an error wrapping [ErrMapIncompatible] otherwise.
274 func (ms *MapSpec) Compatible(m *Map) error {
275 ms, err := ms.fixupMagicFields()
276 if err != nil {
277 return err
278 }
279
280 diffs := []string{}
281 if m.typ != ms.Type {
282 diffs = append(diffs, fmt.Sprintf("Type: %s changed to %s", m.typ, ms.Type))
283 }
284 if m.keySize != ms.KeySize {
285 diffs = append(diffs, fmt.Sprintf("KeySize: %d changed to %d", m.keySize, ms.KeySize))
286 }
287 if m.valueSize != ms.ValueSize {
288 diffs = append(diffs, fmt.Sprintf("ValueSize: %d changed to %d", m.valueSize, ms.ValueSize))
289 }
290 if m.maxEntries != ms.MaxEntries {
291 diffs = append(diffs, fmt.Sprintf("MaxEntries: %d changed to %d", m.maxEntries, ms.MaxEntries))
292 }
293
294 flags := ms.Flags
295 if ms.Type == DevMap || ms.Type == DevMapHash {
296 // As of 0cdbb4b09a06 ("devmap: Allow map lookups from eBPF")
297 // BPF_F_RDONLY_PROG is set unconditionally for devmaps. Explicitly
298 // allow this mismatch.
299 flags |= (m.flags & sys.BPF_F_RDONLY_PROG)
300 }
301
302 if m.flags != flags {
303 diffs = append(diffs, fmt.Sprintf("Flags: %d changed to %d", m.flags, flags))
304 }
305
306 if len(diffs) == 0 {
307 return nil
308 }
309
310 return fmt.Errorf("%s: %w", strings.Join(diffs, ", "), ErrMapIncompatible)
311 }
312
313 // Map represents a Map file descriptor.
314 //
315 // It is not safe to close a Map which is used by other goroutines.
316 //
317 // Map operations taking `any` arguments are encoded using [sysenc.Marshal],
318 // which is zero-copy for fixed-size types without padding as well as slices of
319 // bytes, but may involve allocations for other types. See its documentation for
320 // details.
321 //
322 // Implement encoding.BinaryMarshaler or encoding.BinaryUnmarshaler if you
323 // require custom encoding or decoding.
324 type Map struct {
325 name string
326 fd *sys.FD
327 typ MapType
328 keySize uint32
329 valueSize uint32
330 maxEntries uint32
331 flags uint32
332 pinnedPath string
333 // Per CPU maps return values larger than the size in the spec
334 fullValueSize int
335
336 memory *Memory
337 }
338
339 // NewMapFromFD creates a [Map] around a raw fd.
340 //
341 // You should not use fd after calling this function.
342 //
343 // Requires at least Linux 4.13.
344 func NewMapFromFD(fd int) (*Map, error) {
345 f, err := sys.NewFD(fd)
346 if err != nil {
347 return nil, err
348 }
349
350 return newMapFromFD(f)
351 }
352
353 func newMapFromFD(fd *sys.FD) (*Map, error) {
354 info, err := minimalMapInfoFromFd(fd)
355 if err != nil {
356 fd.Close()
357 return nil, fmt.Errorf("get map info: %w", err)
358 }
359
360 return newMapFromParts(fd, info.Name, info.Type, info.KeySize, info.ValueSize, info.MaxEntries, info.Flags)
361 }
362
363 // NewMap creates a new Map.
364 //
365 // It's equivalent to calling NewMapWithOptions with default options.
366 func NewMap(spec *MapSpec) (*Map, error) {
367 return NewMapWithOptions(spec, MapOptions{})
368 }
369
370 // NewMapWithOptions creates a new Map.
371 //
372 // Creating a map for the first time will perform feature detection
373 // by creating small, temporary maps.
374 //
375 // The caller is responsible for ensuring the process' rlimit is set
376 // sufficiently high for locking memory during map creation. This can be done
377 // by calling rlimit.RemoveMemlock() prior to calling NewMapWithOptions.
378 //
379 // May return an error wrapping ErrMapIncompatible.
380 func NewMapWithOptions(spec *MapSpec, opts MapOptions) (*Map, error) {
381 m, err := newMapWithOptions(spec, opts, btf.NewCache())
382 if err != nil {
383 return nil, fmt.Errorf("creating map: %w", err)
384 }
385
386 if err := m.finalize(spec); err != nil {
387 m.Close()
388 return nil, fmt.Errorf("populating map: %w", err)
389 }
390
391 return m, nil
392 }
393
394 func newMapWithOptions(spec *MapSpec, opts MapOptions, c *btf.Cache) (_ *Map, err error) {
395 closeOnError := func(c io.Closer) {
396 if err != nil {
397 c.Close()
398 }
399 }
400
401 switch spec.Pinning {
402 case PinByName:
403 if spec.Name == "" {
404 return nil, fmt.Errorf("pin by name: missing Name")
405 }
406
407 if opts.PinPath == "" {
408 return nil, fmt.Errorf("pin by name: missing MapOptions.PinPath")
409 }
410
411 path := filepath.Join(opts.PinPath, spec.Name)
412 m, err := LoadPinnedMap(path, &opts.LoadPinOptions)
413 if errors.Is(err, unix.ENOENT) {
414 break
415 }
416 if err != nil {
417 return nil, fmt.Errorf("load pinned map: %w", err)
418 }
419 defer closeOnError(m)
420
421 if err := spec.Compatible(m); err != nil {
422 return nil, fmt.Errorf("use pinned map %s: %w", spec.Name, err)
423 }
424
425 return m, nil
426
427 case PinNone:
428 // Nothing to do here
429
430 default:
431 return nil, fmt.Errorf("pin type %d: %w", int(spec.Pinning), ErrNotSupported)
432 }
433
434 var innerFd *sys.FD
435 if spec.Type.canStoreMap() {
436 if spec.InnerMap == nil {
437 return nil, fmt.Errorf("%s requires InnerMap", spec.Type)
438 }
439
440 if spec.InnerMap.Pinning != PinNone {
441 return nil, errors.New("inner maps cannot be pinned")
442 }
443
444 template, err := spec.InnerMap.createMap(nil, c)
445 if err != nil {
446 return nil, fmt.Errorf("inner map: %w", err)
447 }
448 defer template.Close()
449
450 // Intentionally skip populating and freezing (finalizing)
451 // the inner map template since it will be removed shortly.
452
453 innerFd = template.fd
454 }
455
456 m, err := spec.createMap(innerFd, c)
457 if err != nil {
458 return nil, err
459 }
460 defer closeOnError(m)
461
462 if spec.Pinning == PinByName {
463 path := filepath.Join(opts.PinPath, spec.Name)
464 if err := m.Pin(path); err != nil {
465 return nil, fmt.Errorf("pin map to %s: %w", path, err)
466 }
467 }
468
469 return m, nil
470 }
471
472 // Memory returns a memory-mapped region for the Map. The Map must have been
473 // created with the BPF_F_MMAPABLE flag. Repeated calls to Memory return the
474 // same mapping. Callers are responsible for coordinating access to Memory.
475 func (m *Map) Memory() (*Memory, error) {
476 if m.memory != nil {
477 return m.memory, nil
478 }
479
480 if m.flags&sys.BPF_F_MMAPABLE == 0 {
481 return nil, fmt.Errorf("Map was not created with the BPF_F_MMAPABLE flag: %w", ErrNotSupported)
482 }
483
484 size, err := m.memorySize()
485 if err != nil {
486 return nil, err
487 }
488
489 mm, err := newMemory(m.FD(), size)
490 if err != nil {
491 return nil, fmt.Errorf("creating new Memory: %w", err)
492 }
493
494 m.memory = mm
495
496 return mm, nil
497 }
498
499 // unsafeMemory returns a heap-mapped memory region for the Map. The Map must
500 // have been created with the BPF_F_MMAPABLE flag. Repeated calls to Memory
501 // return the same mapping. Callers are responsible for coordinating access to
502 // Memory.
503 func (m *Map) unsafeMemory() (*Memory, error) {
504 if m.memory != nil {
505 if !m.memory.heap {
506 return nil, errors.New("unsafeMemory would return existing non-heap memory")
507 }
508
509 return m.memory, nil
510 }
511
512 if m.flags&sys.BPF_F_MMAPABLE == 0 {
513 return nil, fmt.Errorf("Map was not created with the BPF_F_MMAPABLE flag: %w", ErrNotSupported)
514 }
515
516 size, err := m.memorySize()
517 if err != nil {
518 return nil, err
519 }
520
521 mm, err := newUnsafeMemory(m.FD(), size)
522 if err != nil {
523 return nil, fmt.Errorf("creating new Memory: %w", err)
524 }
525
526 m.memory = mm
527
528 return mm, nil
529 }
530
531 func (m *Map) memorySize() (int, error) {
532 switch m.Type() {
533 case Array:
534 // In Arrays, values are always laid out on 8-byte boundaries regardless of
535 // architecture. Multiply by MaxEntries and align the result to the host's
536 // page size.
537 size := int(internal.Align(m.ValueSize(), 8) * m.MaxEntries())
538 size = internal.Align(size, os.Getpagesize())
539 return size, nil
540 case Arena:
541 // For Arenas, MaxEntries denotes the maximum number of pages available to
542 // the arena.
543 return int(m.MaxEntries()) * os.Getpagesize(), nil
544 }
545
546 return 0, fmt.Errorf("determine memory size of map type %s: %w", m.Type(), ErrNotSupported)
547 }
548
549 // createMap validates the spec's properties and creates the map in the kernel
550 // using the given opts. It does not populate or freeze the map.
551 func (spec *MapSpec) createMap(inner *sys.FD, c *btf.Cache) (_ *Map, err error) {
552 closeOnError := func(closer io.Closer) {
553 if err != nil {
554 closer.Close()
555 }
556 }
557
558 // Kernels 4.13 through 5.4 used a struct bpf_map_def that contained
559 // additional 'inner_map_idx' and later 'numa_node' fields.
560 // In order to support loading these definitions, tolerate the presence of
561 // extra bytes, but require them to be zeroes.
562 if spec.Extra != nil {
563 if _, err := io.Copy(internal.DiscardZeroes{}, spec.Extra); err != nil {
564 return nil, errors.New("extra contains unhandled non-zero bytes, drain before creating map")
565 }
566 }
567
568 spec, err = spec.fixupMagicFields()
569 if err != nil {
570 return nil, err
571 }
572
573 p, sysMapType := platform.DecodeConstant(spec.Type)
574 if p != platform.Native {
575 return nil, fmt.Errorf("map type %s (%s): %w", spec.Type, p, internal.ErrNotSupportedOnOS)
576 }
577
578 attr := sys.MapCreateAttr{
579 MapName: maybeFillObjName(spec.Name),
580 MapType: sys.MapType(sysMapType),
581 KeySize: spec.KeySize,
582 ValueSize: spec.ValueSize,
583 MaxEntries: spec.MaxEntries,
584 MapFlags: spec.Flags,
585 NumaNode: spec.NumaNode,
586 MapExtra: spec.MapExtra,
587 }
588
589 if inner != nil {
590 attr.InnerMapFd = inner.Uint()
591 }
592
593 if spec.Key != nil || spec.Value != nil {
594 handle, keyTypeID, valueTypeID, err := btf.MarshalMapKV(spec.Key, spec.Value)
595 if err != nil && !errors.Is(err, btf.ErrNotSupported) {
596 return nil, fmt.Errorf("load BTF: %w", err)
597 }
598
599 if handle != nil {
600 defer handle.Close()
601
602 // Use BTF k/v during map creation.
603 attr.BtfFd = uint32(handle.FD())
604 attr.BtfKeyTypeId = keyTypeID
605 attr.BtfValueTypeId = valueTypeID
606 }
607
608 if spec.Type == StructOpsMap {
609 if handle == nil {
610 return nil, fmt.Errorf("struct_ops requires BTF")
611 }
612
613 localValue, ok := btf.As[*btf.Struct](spec.Value)
614 if !ok {
615 return nil, fmt.Errorf("struct_ops: value must be struct")
616 }
617
618 targetValue, targetID, module, err := structOpsFindTarget(localValue, c)
619 if err != nil {
620 return nil, fmt.Errorf("struct_ops: %w", err)
621 }
622 defer module.Close()
623
624 spec = spec.Copy()
625 spec.ValueSize = targetValue.Size
626
627 attr.ValueSize = targetValue.Size
628 attr.BtfVmlinuxValueTypeId = targetID
629
630 if module != nil {
631 // BPF_F_VTYPE_BTF_OBJ_FD is required if the type comes from a module
632 attr.MapFlags |= sys.BPF_F_VTYPE_BTF_OBJ_FD
633 // set FD for the kernel module
634 attr.ValueTypeBtfObjFd = int32(module.FD())
635 }
636
637 // StructOpsMap forbids passing BtfKeyTypeId or BtfValueTypeId, but
638 // requires BtfFd. Do the simple thing and just zero out the fields.
639 // See https://github.com/torvalds/linux/blob/9b332cece987ee1790b2ed4c989e28162fa47860/kernel/bpf/syscall.c#L1382-L1384
640 attr.BtfKeyTypeId = 0
641 attr.BtfValueTypeId = 0
642 }
643 }
644
645 fd, err := sys.MapCreate(&attr)
646
647 // Some map types don't support BTF k/v in earlier kernel versions.
648 // Remove BTF metadata and retry map creation.
649 if (errors.Is(err, sys.ENOTSUPP) || errors.Is(err, unix.EINVAL)) && attr.BtfFd != 0 {
650 attr.BtfFd, attr.BtfKeyTypeId, attr.BtfValueTypeId = 0, 0, 0
651 fd, err = sys.MapCreate(&attr)
652 }
653 if err != nil {
654 return nil, handleMapCreateError(attr, spec, err)
655 }
656
657 defer closeOnError(fd)
658 m, err := newMapFromParts(fd, spec.Name, spec.Type, spec.KeySize, spec.ValueSize, spec.MaxEntries, spec.Flags)
659 if err != nil {
660 return nil, fmt.Errorf("map create: %w", err)
661 }
662 return m, nil
663 }
664
665 func handleMapCreateError(attr sys.MapCreateAttr, spec *MapSpec, err error) error {
666 if platform.IsWindows {
667 if errors.Is(err, unix.EINVAL) && attr.MapFlags != 0 {
668 return fmt.Errorf("map create: flags: %w", internal.ErrNotSupportedOnOS)
669 }
670
671 return err
672 }
673
674 if errors.Is(err, sys.ErrTokenCapabilities) {
675 return fmt.Errorf("map create: %w", err)
676 }
677
678 if errors.Is(err, unix.EPERM) {
679 return fmt.Errorf("map create: %w (MEMLOCK may be too low, consider rlimit.RemoveMemlock)", err)
680 }
681
682 if errors.Is(err, unix.EINVAL) {
683 if spec.MaxEntries == 0 && !spec.Type.mustHaveZeroMaxEntries() {
684 return fmt.Errorf("map create: %w (MaxEntries may be incorrectly set to zero)", err)
685 }
686 if spec.Type == UnspecifiedMap {
687 return fmt.Errorf("map create: cannot use type %s", UnspecifiedMap)
688 }
689 if spec.Flags&sys.BPF_F_NO_PREALLOC != 0 && !spec.Type.mustHaveNoPrealloc() {
690 return fmt.Errorf("map create: %w (BPF_F_NO_PREALLOC flag may be incompatible with map type %s)", err, spec.Type)
691 }
692 if spec.Flags&sys.BPF_F_NO_PREALLOC == 0 && spec.Type.mustHaveNoPrealloc() {
693 return fmt.Errorf("map create: %w (BPF_F_NO_PREALLOC flag may need to be set for map type %s)", err, spec.Type)
694 }
695 }
696
697 if spec.Type.canStoreMap() {
698 if haveFeatErr := haveNestedMaps(); haveFeatErr != nil {
699 return fmt.Errorf("map create: %w", haveFeatErr)
700 }
701 }
702
703 if spec.readOnly() || spec.writeOnly() {
704 if haveFeatErr := haveMapMutabilityModifiers(); haveFeatErr != nil {
705 return fmt.Errorf("map create: %w", haveFeatErr)
706 }
707 }
708 if spec.Flags&sys.BPF_F_MMAPABLE > 0 {
709 if haveFeatErr := haveMmapableMaps(); haveFeatErr != nil {
710 return fmt.Errorf("map create: %w", haveFeatErr)
711 }
712 }
713 if spec.Flags&sys.BPF_F_INNER_MAP > 0 {
714 if haveFeatErr := haveInnerMaps(); haveFeatErr != nil {
715 return fmt.Errorf("map create: %w", haveFeatErr)
716 }
717 }
718 if spec.Flags&sys.BPF_F_NO_PREALLOC > 0 {
719 if haveFeatErr := haveNoPreallocMaps(); haveFeatErr != nil {
720 return fmt.Errorf("map create: %w", haveFeatErr)
721 }
722 }
723 // BPF_MAP_TYPE_RINGBUF's max_entries must be a power-of-2 multiple of kernel's page size.
724 if errors.Is(err, unix.EINVAL) &&
725 (attr.MapType == sys.BPF_MAP_TYPE_RINGBUF || attr.MapType == sys.BPF_MAP_TYPE_USER_RINGBUF) {
726 pageSize := uint32(os.Getpagesize())
727 maxEntries := attr.MaxEntries
728 if maxEntries%pageSize != 0 || !internal.IsPow(maxEntries) {
729 return fmt.Errorf("map create: %w (ring map size %d not a multiple of page size %d)", err, maxEntries, pageSize)
730 }
731 }
732
733 return fmt.Errorf("map create: %w", err)
734 }
735
736 // newMapFromParts allocates and returns a new Map structure.
737 // Sets the fullValueSize on per-CPU maps.
738 func newMapFromParts(fd *sys.FD, name string, typ MapType, keySize, valueSize, maxEntries, flags uint32) (*Map, error) {
739 m := &Map{
740 name,
741 fd,
742 typ,
743 keySize,
744 valueSize,
745 maxEntries,
746 flags,
747 "",
748 int(valueSize),
749 nil,
750 }
751
752 if !typ.hasPerCPUValue() {
753 return m, nil
754 }
755
756 possibleCPUs, err := PossibleCPU()
757 if err != nil {
758 return nil, err
759 }
760
761 m.fullValueSize = int(internal.Align(valueSize, 8)) * possibleCPUs
762 return m, nil
763 }
764
765 func (m *Map) String() string {
766 if m.name != "" {
767 return fmt.Sprintf("%s(%s)#%v", m.typ, m.name, m.fd)
768 }
769 return fmt.Sprintf("%s#%v", m.typ, m.fd)
770 }
771
772 // Type returns the underlying type of the map.
773 func (m *Map) Type() MapType {
774 return m.typ
775 }
776
777 // KeySize returns the size of the map key in bytes.
778 func (m *Map) KeySize() uint32 {
779 return m.keySize
780 }
781
782 // ValueSize returns the size of the map value in bytes.
783 func (m *Map) ValueSize() uint32 {
784 return m.valueSize
785 }
786
787 // MaxEntries returns the maximum number of elements the map can hold.
788 func (m *Map) MaxEntries() uint32 {
789 return m.maxEntries
790 }
791
792 // Flags returns the flags of the map.
793 func (m *Map) Flags() uint32 {
794 return m.flags
795 }
796
797 // Info returns metadata about the map. This was first introduced in Linux 4.5,
798 // but newer kernels support more MapInfo fields with the introduction of more
799 // features. See [MapInfo] and its methods for more details.
800 //
801 // Returns an error wrapping [ErrNotSupported] if the kernel supports neither
802 // BPF_OBJ_GET_INFO_BY_FD nor reading map information from /proc/self/fdinfo.
803 func (m *Map) Info() (*MapInfo, error) {
804 return newMapInfoFromFd(m.fd)
805 }
806
807 // Handle returns a reference to the Map's type information in the kernel.
808 //
809 // Returns [ErrNotSupported] if the kernel has no BTF support, or if there is no
810 // BTF associated with the Map.
811 func (m *Map) Handle() (*btf.Handle, error) {
812 info, err := m.Info()
813 if err != nil {
814 return nil, err
815 }
816
817 id, ok := info.BTFID()
818 if !ok {
819 return nil, fmt.Errorf("map %s: retrieve BTF ID: %w", m, ErrNotSupported)
820 }
821
822 return btf.NewHandleFromID(id)
823 }
824
825 // MapLookupFlags controls the behaviour of the map lookup calls.
826 type MapLookupFlags uint64
827
828 // LookupLock look up the value of a spin-locked map.
829 const LookupLock MapLookupFlags = sys.BPF_F_LOCK
830
831 // Lookup retrieves a value from a Map.
832 //
833 // Calls Close() on valueOut if it is of type **Map or **Program,
834 // and *valueOut is not nil.
835 //
836 // Returns an error if the key doesn't exist, see ErrKeyNotExist.
837 func (m *Map) Lookup(key, valueOut any) error {
838 return m.LookupWithFlags(key, valueOut, 0)
839 }
840
841 // LookupWithFlags retrieves a value from a Map with flags.
842 //
843 // Passing LookupLock flag will look up the value of a spin-locked
844 // map without returning the lock. This must be specified if the
845 // elements contain a spinlock.
846 //
847 // Calls Close() on valueOut if it is of type **Map or **Program,
848 // and *valueOut is not nil.
849 //
850 // Returns an error if the key doesn't exist, see ErrKeyNotExist.
851 func (m *Map) LookupWithFlags(key, valueOut any, flags MapLookupFlags) error {
852 if m.typ.hasPerCPUValue() {
853 return m.lookupPerCPU(key, valueOut, flags)
854 }
855
856 valueBytes := makeMapSyscallOutput(valueOut, m.fullValueSize)
857 if err := m.lookup(key, valueBytes.Pointer(), flags); err != nil {
858 return err
859 }
860
861 return m.unmarshalValue(valueOut, valueBytes)
862 }
863
864 // LookupAndDelete retrieves and deletes a value from a Map.
865 //
866 // Returns ErrKeyNotExist if the key doesn't exist.
867 func (m *Map) LookupAndDelete(key, valueOut any) error {
868 return m.LookupAndDeleteWithFlags(key, valueOut, 0)
869 }
870
871 // LookupAndDeleteWithFlags retrieves and deletes a value from a Map.
872 //
873 // Passing LookupLock flag will look up and delete the value of a spin-locked
874 // map without returning the lock. This must be specified if the elements
875 // contain a spinlock.
876 //
877 // Returns ErrKeyNotExist if the key doesn't exist.
878 func (m *Map) LookupAndDeleteWithFlags(key, valueOut any, flags MapLookupFlags) error {
879 if m.typ.hasPerCPUValue() {
880 return m.lookupAndDeletePerCPU(key, valueOut, flags)
881 }
882
883 valueBytes := makeMapSyscallOutput(valueOut, m.fullValueSize)
884 if err := m.lookupAndDelete(key, valueBytes.Pointer(), flags); err != nil {
885 return err
886 }
887 return m.unmarshalValue(valueOut, valueBytes)
888 }
889
890 // LookupBytes gets a value from Map.
891 //
892 // Returns a nil value if a key doesn't exist.
893 func (m *Map) LookupBytes(key any) ([]byte, error) {
894 valueBytes := make([]byte, m.fullValueSize)
895 valuePtr := sys.UnsafeSlicePointer(valueBytes)
896
897 err := m.lookup(key, valuePtr, 0)
898 if errors.Is(err, ErrKeyNotExist) {
899 return nil, nil
900 }
901
902 return valueBytes, err
903 }
904
905 func (m *Map) lookupPerCPU(key, valueOut any, flags MapLookupFlags) error {
906 slice, err := ensurePerCPUSlice(valueOut)
907 if err != nil {
908 return err
909 }
910 valueBytes := make([]byte, m.fullValueSize)
911 if err := m.lookup(key, sys.UnsafeSlicePointer(valueBytes), flags); err != nil {
912 return err
913 }
914 return unmarshalPerCPUValue(slice, int(m.valueSize), valueBytes)
915 }
916
917 func (m *Map) lookup(key any, valueOut sys.Pointer, flags MapLookupFlags) error {
918 keyPtr, err := m.marshalKey(key)
919 if err != nil {
920 return fmt.Errorf("can't marshal key: %w", err)
921 }
922
923 attr := sys.MapLookupElemAttr{
924 MapFd: m.fd.Uint(),
925 Key: keyPtr,
926 Value: valueOut,
927 Flags: uint64(flags),
928 }
929
930 if err = sys.MapLookupElem(&attr); err != nil {
931 if errors.Is(err, unix.ENOENT) {
932 return errMapLookupKeyNotExist
933 }
934 return fmt.Errorf("lookup: %w", wrapMapError(err))
935 }
936 return nil
937 }
938
939 func (m *Map) lookupAndDeletePerCPU(key, valueOut any, flags MapLookupFlags) error {
940 slice, err := ensurePerCPUSlice(valueOut)
941 if err != nil {
942 return err
943 }
944 valueBytes := make([]byte, m.fullValueSize)
945 if err := m.lookupAndDelete(key, sys.UnsafeSlicePointer(valueBytes), flags); err != nil {
946 return err
947 }
948 return unmarshalPerCPUValue(slice, int(m.valueSize), valueBytes)
949 }
950
951 // ensurePerCPUSlice allocates a slice for a per-CPU value if necessary.
952 func ensurePerCPUSlice(sliceOrPtr any) (any, error) {
953 if err := internal.IsNilPointer(sliceOrPtr); err != nil {
954 return nil, fmt.Errorf("per-cpu value: %w", err)
955 }
956
957 sliceOrPtrType := reflect.TypeOf(sliceOrPtr)
958 if sliceOrPtrType.Kind() == reflect.Slice {
959 // The target is a slice, the caller is responsible for ensuring that
960 // size is correct.
961 return sliceOrPtr, nil
962 }
963
964 slicePtrType := sliceOrPtrType
965 if slicePtrType.Kind() != reflect.Pointer || slicePtrType.Elem().Kind() != reflect.Slice {
966 return nil, fmt.Errorf("per-cpu value requires a slice or a pointer to slice")
967 }
968
969 possibleCPUs, err := PossibleCPU()
970 if err != nil {
971 return nil, err
972 }
973
974 sliceType := slicePtrType.Elem()
975 slice := reflect.MakeSlice(sliceType, possibleCPUs, possibleCPUs)
976
977 sliceElemType := sliceType.Elem()
978 sliceElemIsPointer := sliceElemType.Kind() == reflect.Pointer
979 reflect.ValueOf(sliceOrPtr).Elem().Set(slice)
980 if !sliceElemIsPointer {
981 return slice.Interface(), nil
982 }
983 sliceElemType = sliceElemType.Elem()
984
985 for i := range possibleCPUs {
986 newElem := reflect.New(sliceElemType)
987 slice.Index(i).Set(newElem)
988 }
989
990 return slice.Interface(), nil
991 }
992
993 func (m *Map) lookupAndDelete(key any, valuePtr sys.Pointer, flags MapLookupFlags) error {
994 keyPtr, err := m.marshalKey(key)
995 if err != nil {
996 return fmt.Errorf("can't marshal key: %w", err)
997 }
998
999 attr := sys.MapLookupAndDeleteElemAttr{
1000 MapFd: m.fd.Uint(),
1001 Key: keyPtr,
1002 Value: valuePtr,
1003 Flags: uint64(flags),
1004 }
1005
1006 if err := sys.MapLookupAndDeleteElem(&attr); err != nil {
1007 return fmt.Errorf("lookup and delete: %w", wrapMapError(err))
1008 }
1009
1010 return nil
1011 }
1012
1013 // MapUpdateFlags controls the behaviour of the Map.Update call.
1014 //
1015 // The exact semantics depend on the specific MapType.
1016 type MapUpdateFlags uint64
1017
1018 const (
1019 // UpdateAny creates a new element or update an existing one.
1020 UpdateAny MapUpdateFlags = iota
1021 // UpdateNoExist creates a new element.
1022 UpdateNoExist MapUpdateFlags = 1 << (iota - 1)
1023 // UpdateExist updates an existing element.
1024 UpdateExist
1025 // UpdateLock updates elements under bpf_spin_lock.
1026 UpdateLock
1027 )
1028
1029 // Put replaces or creates a value in map.
1030 //
1031 // It is equivalent to calling Update with UpdateAny.
1032 func (m *Map) Put(key, value any) error {
1033 return m.Update(key, value, UpdateAny)
1034 }
1035
1036 // Update changes the value of a key.
1037 func (m *Map) Update(key, value any, flags MapUpdateFlags) error {
1038 if m.typ.hasPerCPUValue() {
1039 return m.updatePerCPU(key, value, flags)
1040 }
1041
1042 valuePtr, err := m.marshalValue(value)
1043 if err != nil {
1044 return fmt.Errorf("marshal value: %w", err)
1045 }
1046
1047 return m.update(key, valuePtr, flags)
1048 }
1049
1050 func (m *Map) updatePerCPU(key, value any, flags MapUpdateFlags) error {
1051 valuePtr, err := marshalPerCPUValue(value, int(m.valueSize))
1052 if err != nil {
1053 return fmt.Errorf("marshal value: %w", err)
1054 }
1055
1056 return m.update(key, valuePtr, flags)
1057 }
1058
1059 func (m *Map) update(key any, valuePtr sys.Pointer, flags MapUpdateFlags) error {
1060 keyPtr, err := m.marshalKey(key)
1061 if err != nil {
1062 return fmt.Errorf("marshal key: %w", err)
1063 }
1064
1065 attr := sys.MapUpdateElemAttr{
1066 MapFd: m.fd.Uint(),
1067 Key: keyPtr,
1068 Value: valuePtr,
1069 Flags: uint64(flags),
1070 }
1071
1072 if err = sys.MapUpdateElem(&attr); err != nil {
1073 return fmt.Errorf("update: %w", wrapMapError(err))
1074 }
1075
1076 return nil
1077 }
1078
1079 // Delete removes a value.
1080 //
1081 // Returns ErrKeyNotExist if the key does not exist.
1082 func (m *Map) Delete(key any) error {
1083 keyPtr, err := m.marshalKey(key)
1084 if err != nil {
1085 return fmt.Errorf("can't marshal key: %w", err)
1086 }
1087
1088 attr := sys.MapDeleteElemAttr{
1089 MapFd: m.fd.Uint(),
1090 Key: keyPtr,
1091 }
1092
1093 if err = sys.MapDeleteElem(&attr); err != nil {
1094 return fmt.Errorf("delete: %w", wrapMapError(err))
1095 }
1096 return nil
1097 }
1098
1099 // NextKey finds the key following an initial key.
1100 //
1101 // See NextKeyBytes for details.
1102 //
1103 // Returns ErrKeyNotExist if there is no next key.
1104 func (m *Map) NextKey(key, nextKeyOut any) error {
1105 nextKeyBytes := makeMapSyscallOutput(nextKeyOut, int(m.keySize))
1106
1107 if err := m.nextKey(key, nextKeyBytes.Pointer()); err != nil {
1108 return err
1109 }
1110
1111 if err := nextKeyBytes.Unmarshal(nextKeyOut); err != nil {
1112 return fmt.Errorf("can't unmarshal next key: %w", err)
1113 }
1114 return nil
1115 }
1116
1117 // NextKeyBytes returns the key following an initial key as a byte slice.
1118 //
1119 // Passing nil will return the first key.
1120 //
1121 // Use Iterate if you want to traverse all entries in the map.
1122 //
1123 // Returns nil if there are no more keys.
1124 func (m *Map) NextKeyBytes(key any) ([]byte, error) {
1125 nextKey := make([]byte, m.keySize)
1126 nextKeyPtr := sys.UnsafeSlicePointer(nextKey)
1127
1128 err := m.nextKey(key, nextKeyPtr)
1129 if errors.Is(err, ErrKeyNotExist) {
1130 return nil, nil
1131 }
1132
1133 return nextKey, err
1134 }
1135
1136 func (m *Map) nextKey(key any, nextKeyOut sys.Pointer) error {
1137 var (
1138 keyPtr sys.Pointer
1139 err error
1140 )
1141
1142 if key != nil {
1143 keyPtr, err = m.marshalKey(key)
1144 if err != nil {
1145 return fmt.Errorf("can't marshal key: %w", err)
1146 }
1147 }
1148
1149 attr := sys.MapGetNextKeyAttr{
1150 MapFd: m.fd.Uint(),
1151 Key: keyPtr,
1152 NextKey: nextKeyOut,
1153 }
1154
1155 if err = sys.MapGetNextKey(&attr); err != nil {
1156 // Kernels 4.4.131 and earlier return EFAULT instead of a pointer to the
1157 // first map element when a nil key pointer is specified.
1158 if platform.IsLinux && key == nil && errors.Is(err, unix.EFAULT) {
1159 var guessKey []byte
1160 guessKey, err = m.guessNonExistentKey()
1161 if err != nil {
1162 return err
1163 }
1164
1165 // Retry the syscall with a valid non-existing key.
1166 attr.Key = sys.UnsafeSlicePointer(guessKey)
1167 if err = sys.MapGetNextKey(&attr); err == nil {
1168 return nil
1169 }
1170 }
1171
1172 return fmt.Errorf("next key: %w", wrapMapError(err))
1173 }
1174
1175 return nil
1176 }
1177
1178 var mmapProtectedPage = sync.OnceValues(func() ([]byte, error) {
1179 return unix.Mmap(-1, 0, os.Getpagesize(), unix.PROT_NONE, unix.MAP_ANON|unix.MAP_SHARED)
1180 })
1181
1182 // guessNonExistentKey attempts to perform a map lookup that returns ENOENT.
1183 // This is necessary on kernels before 4.4.132, since those don't support
1184 // iterating maps from the start by providing an invalid key pointer.
1185 func (m *Map) guessNonExistentKey() ([]byte, error) {
1186 // Map a protected page and use that as the value pointer. This saves some
1187 // work copying out the value, which we're not interested in.
1188 page, err := mmapProtectedPage()
1189 if err != nil {
1190 return nil, err
1191 }
1192 valuePtr := sys.UnsafeSlicePointer(page)
1193
1194 randKey := make([]byte, int(m.keySize))
1195
1196 for i := range 4 {
1197 switch i {
1198 // For hash maps, the 0 key is less likely to be occupied. They're often
1199 // used for storing data related to pointers, and their access pattern is
1200 // generally scattered across the keyspace.
1201 case 0:
1202 // An all-0xff key is guaranteed to be out of bounds of any array, since
1203 // those have a fixed key size of 4 bytes. The only corner case being
1204 // arrays with 2^32 max entries, but those are prohibitively expensive
1205 // in many environments.
1206 case 1:
1207 for r := range randKey {
1208 randKey[r] = 0xff
1209 }
1210 // Inspired by BCC, 0x55 is an alternating binary pattern (0101), so
1211 // is unlikely to be taken.
1212 case 2:
1213 for r := range randKey {
1214 randKey[r] = 0x55
1215 }
1216 // Last ditch effort, generate a random key.
1217 case 3:
1218 rand.New(rand.NewSource(time.Now().UnixNano())).Read(randKey)
1219 }
1220
1221 err := m.lookup(randKey, valuePtr, 0)
1222 if errors.Is(err, ErrKeyNotExist) {
1223 return randKey, nil
1224 }
1225 }
1226
1227 return nil, errors.New("couldn't find non-existing key")
1228 }
1229
1230 // BatchLookup looks up many elements in a map at once.
1231 //
1232 // "keysOut" and "valuesOut" must be of type slice, a pointer
1233 // to a slice or buffer will not work.
1234 // "cursor" is an pointer to an opaque handle. It must be non-nil. Pass
1235 // "cursor" to subsequent calls of this function to continue the batching
1236 // operation in the case of chunking.
1237 //
1238 // Warning: This API is not very safe to use as the kernel implementation for
1239 // batching relies on the user to be aware of subtle details with regarding to
1240 // different map type implementations.
1241 //
1242 // ErrKeyNotExist is returned when the batch lookup has reached
1243 // the end of all possible results, even when partial results
1244 // are returned. It should be used to evaluate when lookup is "done".
1245 func (m *Map) BatchLookup(cursor *MapBatchCursor, keysOut, valuesOut any, opts *BatchOptions) (int, error) {
1246 n, err := m.batchLookup(sys.BPF_MAP_LOOKUP_BATCH, cursor, keysOut, valuesOut, opts)
1247 if err != nil {
1248 return n, fmt.Errorf("map batch lookup: %w", err)
1249 }
1250 return n, nil
1251 }
1252
1253 // BatchLookupAndDelete looks up many elements in a map at once,
1254 //
1255 // It then deletes all those elements.
1256 // "keysOut" and "valuesOut" must be of type slice, a pointer
1257 // to a slice or buffer will not work.
1258 // "cursor" is an pointer to an opaque handle. It must be non-nil. Pass
1259 // "cursor" to subsequent calls of this function to continue the batching
1260 // operation in the case of chunking.
1261 //
1262 // Warning: This API is not very safe to use as the kernel implementation for
1263 // batching relies on the user to be aware of subtle details with regarding to
1264 // different map type implementations.
1265 //
1266 // ErrKeyNotExist is returned when the batch lookup has reached
1267 // the end of all possible results, even when partial results
1268 // are returned. It should be used to evaluate when lookup is "done".
1269 func (m *Map) BatchLookupAndDelete(cursor *MapBatchCursor, keysOut, valuesOut any, opts *BatchOptions) (int, error) {
1270 n, err := m.batchLookup(sys.BPF_MAP_LOOKUP_AND_DELETE_BATCH, cursor, keysOut, valuesOut, opts)
1271 if err != nil {
1272 return n, fmt.Errorf("map batch lookup and delete: %w", err)
1273 }
1274 return n, nil
1275 }
1276
1277 // MapBatchCursor represents a starting point for a batch operation.
1278 type MapBatchCursor struct {
1279 m *Map
1280 opaque []byte
1281 }
1282
1283 func (m *Map) batchLookup(cmd sys.Cmd, cursor *MapBatchCursor, keysOut, valuesOut any, opts *BatchOptions) (int, error) {
1284 if m.typ.hasPerCPUValue() {
1285 return m.batchLookupPerCPU(cmd, cursor, keysOut, valuesOut, opts)
1286 }
1287
1288 count, err := batchCount(keysOut, valuesOut)
1289 if err != nil {
1290 return 0, err
1291 }
1292
1293 valueBuf := sysenc.SyscallOutput(valuesOut, count*int(m.fullValueSize))
1294
1295 n, sysErr := m.batchLookupCmd(cmd, cursor, count, keysOut, valueBuf.Pointer(), opts)
1296 if errors.Is(sysErr, unix.ENOSPC) {
1297 // Hash tables return ENOSPC when the size of the batch is smaller than
1298 // any bucket.
1299 return n, fmt.Errorf("%w (batch size too small?)", sysErr)
1300 } else if sysErr != nil && !errors.Is(sysErr, unix.ENOENT) {
1301 return 0, sysErr
1302 }
1303
1304 err = valueBuf.Unmarshal(valuesOut)
1305 if err != nil {
1306 return 0, err
1307 }
1308
1309 return n, sysErr
1310 }
1311
1312 func (m *Map) batchLookupPerCPU(cmd sys.Cmd, cursor *MapBatchCursor, keysOut, valuesOut any, opts *BatchOptions) (int, error) {
1313 count, err := sliceLen(keysOut)
1314 if err != nil {
1315 return 0, fmt.Errorf("keys: %w", err)
1316 }
1317
1318 valueBuf := sysenc.SyscallOutput(valuesOut, count*int(m.fullValueSize))
1319
1320 n, sysErr := m.batchLookupCmd(cmd, cursor, count, keysOut, valueBuf.Pointer(), opts)
1321 if sysErr != nil && !errors.Is(sysErr, unix.ENOENT) {
1322 return 0, sysErr
1323 }
1324
1325 if bytesBuf := valueBuf.Bytes(); bytesBuf != nil {
1326 err = unmarshalBatchPerCPUValue(valuesOut, count, int(m.valueSize), bytesBuf)
1327 if err != nil {
1328 return 0, err
1329 }
1330 }
1331
1332 return n, sysErr
1333 }
1334
1335 func (m *Map) batchLookupCmd(cmd sys.Cmd, cursor *MapBatchCursor, count int, keysOut any, valuePtr sys.Pointer, opts *BatchOptions) (int, error) {
1336 // * generic_map_lookup_batch requires that batch_out is key_size bytes.
1337 // This is used by array and LPM maps.
1338 //
1339 // * __htab_map_lookup_and_delete_batch requires u32. This is used by the
1340 // various hash maps.
1341 //
1342 // Use a minimum of 4 bytes to avoid having to distinguish between the two.
1343 cursorLen := max(int(m.keySize), 4)
1344
1345 inBatch := cursor.opaque
1346 if inBatch == nil {
1347 // This is the first lookup, allocate a buffer to hold the cursor.
1348 cursor.opaque = make([]byte, cursorLen)
1349 cursor.m = m
1350 } else if cursor.m != m {
1351 // Prevent reuse of a cursor across maps. First, it's unlikely to work.
1352 // Second, the maps may require different cursorLen and cursor.opaque
1353 // may therefore be too short. This could lead to the kernel clobbering
1354 // user space memory.
1355 return 0, errors.New("a cursor may not be reused across maps")
1356 }
1357
1358 keyBuf := sysenc.SyscallOutput(keysOut, count*int(m.keySize))
1359
1360 attr := sys.MapLookupBatchAttr{
1361 MapFd: m.fd.Uint(),
1362 Keys: keyBuf.Pointer(),
1363 Values: valuePtr,
1364 Count: uint32(count),
1365 InBatch: sys.UnsafeSlicePointer(inBatch),
1366 OutBatch: sys.UnsafeSlicePointer(cursor.opaque),
1367 }
1368
1369 if opts != nil {
1370 attr.ElemFlags = opts.ElemFlags
1371 attr.Flags = opts.Flags
1372 }
1373
1374 _, sysErr := sys.BPF(cmd, unsafe.Pointer(&attr), unsafe.Sizeof(attr))
1375 sysErr = wrapMapError(sysErr)
1376 if sysErr != nil && !errors.Is(sysErr, unix.ENOENT) {
1377 if haveFeatErr := haveBatchAPI(); haveFeatErr != nil {
1378 return 0, haveFeatErr
1379 }
1380 return 0, sysErr
1381 }
1382
1383 if err := keyBuf.Unmarshal(keysOut); err != nil {
1384 return 0, err
1385 }
1386
1387 return int(attr.Count), sysErr
1388 }
1389
1390 // BatchUpdate updates the map with multiple keys and values
1391 // simultaneously.
1392 // "keys" and "values" must be of type slice, a pointer
1393 // to a slice or buffer will not work.
1394 func (m *Map) BatchUpdate(keys, values any, opts *BatchOptions) (int, error) {
1395 if m.typ.hasPerCPUValue() {
1396 return m.batchUpdatePerCPU(keys, values, opts)
1397 }
1398
1399 count, err := batchCount(keys, values)
1400 if err != nil {
1401 return 0, err
1402 }
1403
1404 valuePtr, err := marshalMapSyscallInput(values, count*int(m.valueSize))
1405 if err != nil {
1406 return 0, err
1407 }
1408
1409 return m.batchUpdate(count, keys, valuePtr, opts)
1410 }
1411
1412 func (m *Map) batchUpdate(count int, keys any, valuePtr sys.Pointer, opts *BatchOptions) (int, error) {
1413 keyPtr, err := marshalMapSyscallInput(keys, count*int(m.keySize))
1414 if err != nil {
1415 return 0, err
1416 }
1417
1418 attr := sys.MapUpdateBatchAttr{
1419 MapFd: m.fd.Uint(),
1420 Keys: keyPtr,
1421 Values: valuePtr,
1422 Count: uint32(count),
1423 }
1424 if opts != nil {
1425 attr.ElemFlags = opts.ElemFlags
1426 attr.Flags = opts.Flags
1427 }
1428
1429 err = sys.MapUpdateBatch(&attr)
1430 if err != nil {
1431 if haveFeatErr := haveBatchAPI(); haveFeatErr != nil {
1432 return 0, haveFeatErr
1433 }
1434 return int(attr.Count), fmt.Errorf("batch update: %w", wrapMapError(err))
1435 }
1436
1437 return int(attr.Count), nil
1438 }
1439
1440 func (m *Map) batchUpdatePerCPU(keys, values any, opts *BatchOptions) (int, error) {
1441 count, err := sliceLen(keys)
1442 if err != nil {
1443 return 0, fmt.Errorf("keys: %w", err)
1444 }
1445
1446 valueBuf, err := marshalBatchPerCPUValue(values, count, int(m.valueSize))
1447 if err != nil {
1448 return 0, err
1449 }
1450
1451 return m.batchUpdate(count, keys, sys.UnsafeSlicePointer(valueBuf), opts)
1452 }
1453
1454 // BatchDelete batch deletes entries in the map by keys.
1455 // "keys" must be of type slice, a pointer to a slice or buffer will not work.
1456 func (m *Map) BatchDelete(keys any, opts *BatchOptions) (int, error) {
1457 count, err := sliceLen(keys)
1458 if err != nil {
1459 return 0, fmt.Errorf("keys: %w", err)
1460 }
1461
1462 keyPtr, err := marshalMapSyscallInput(keys, count*int(m.keySize))
1463 if err != nil {
1464 return 0, fmt.Errorf("cannot marshal keys: %v", err)
1465 }
1466
1467 attr := sys.MapDeleteBatchAttr{
1468 MapFd: m.fd.Uint(),
1469 Keys: keyPtr,
1470 Count: uint32(count),
1471 }
1472
1473 if opts != nil {
1474 attr.ElemFlags = opts.ElemFlags
1475 attr.Flags = opts.Flags
1476 }
1477
1478 if err = sys.MapDeleteBatch(&attr); err != nil {
1479 if haveFeatErr := haveBatchAPI(); haveFeatErr != nil {
1480 return 0, haveFeatErr
1481 }
1482 return int(attr.Count), fmt.Errorf("batch delete: %w", wrapMapError(err))
1483 }
1484
1485 return int(attr.Count), nil
1486 }
1487
1488 func batchCount(keys, values any) (int, error) {
1489 keysLen, err := sliceLen(keys)
1490 if err != nil {
1491 return 0, fmt.Errorf("keys: %w", err)
1492 }
1493
1494 valuesLen, err := sliceLen(values)
1495 if err != nil {
1496 return 0, fmt.Errorf("values: %w", err)
1497 }
1498
1499 if keysLen != valuesLen {
1500 return 0, fmt.Errorf("keys and values must have the same length")
1501 }
1502
1503 return keysLen, nil
1504 }
1505
1506 // Iterate traverses a map.
1507 //
1508 // It's safe to create multiple iterators at the same time.
1509 //
1510 // It's not possible to guarantee that all keys in a map will be
1511 // returned if there are concurrent modifications to the map.
1512 func (m *Map) Iterate() *MapIterator {
1513 return newMapIterator(m)
1514 }
1515
1516 // Close the Map's underlying file descriptor, which could unload the
1517 // Map from the kernel if it is not pinned or in use by a loaded Program.
1518 func (m *Map) Close() error {
1519 if m == nil {
1520 // This makes it easier to clean up when iterating maps
1521 // of maps / programs.
1522 return nil
1523 }
1524
1525 return m.fd.Close()
1526 }
1527
1528 // FD gets the file descriptor of the Map.
1529 //
1530 // Calling this function is invalid after Close has been called.
1531 func (m *Map) FD() int {
1532 return m.fd.Int()
1533 }
1534
1535 // Clone creates a duplicate of the Map.
1536 //
1537 // Closing the duplicate does not affect the original, and vice versa.
1538 // Changes made to the map are reflected by both instances however.
1539 // If the original map was pinned, the cloned map will not be pinned by default.
1540 //
1541 // Cloning a nil Map returns nil.
1542 func (m *Map) Clone() (*Map, error) {
1543 if m == nil {
1544 return nil, nil
1545 }
1546
1547 dup, err := m.fd.Dup()
1548 if err != nil {
1549 return nil, fmt.Errorf("can't clone map: %w", err)
1550 }
1551
1552 return &Map{
1553 m.name,
1554 dup,
1555 m.typ,
1556 m.keySize,
1557 m.valueSize,
1558 m.maxEntries,
1559 m.flags,
1560 "",
1561 m.fullValueSize,
1562 nil,
1563 }, nil
1564 }
1565
1566 // Pin persists the map on the BPF virtual file system past the lifetime of
1567 // the process that created it .
1568 //
1569 // Calling Pin on a previously pinned map will overwrite the path, except when
1570 // the new path already exists. Re-pinning across filesystems is not supported.
1571 // You can Clone a map to pin it to a different path.
1572 //
1573 // This requires bpffs to be mounted above fileName.
1574 // See https://docs.cilium.io/en/stable/network/kubernetes/configuration/#mounting-bpffs-with-systemd
1575 func (m *Map) Pin(fileName string) error {
1576 if err := sys.Pin(m.pinnedPath, fileName, m.fd); err != nil {
1577 return err
1578 }
1579 m.pinnedPath = fileName
1580 return nil
1581 }
1582
1583 // Unpin removes the persisted state for the map from the BPF virtual filesystem.
1584 //
1585 // Failed calls to Unpin will not alter the state returned by IsPinned.
1586 //
1587 // Unpinning an unpinned Map returns nil.
1588 func (m *Map) Unpin() error {
1589 if err := sys.Unpin(m.pinnedPath); err != nil {
1590 return err
1591 }
1592 m.pinnedPath = ""
1593 return nil
1594 }
1595
1596 // IsPinned returns true if the map has a non-empty pinned path.
1597 func (m *Map) IsPinned() bool {
1598 return m.pinnedPath != ""
1599 }
1600
1601 // Freeze prevents a map to be modified from user space.
1602 //
1603 // It makes no changes to kernel-side restrictions.
1604 func (m *Map) Freeze() error {
1605 attr := sys.MapFreezeAttr{
1606 MapFd: m.fd.Uint(),
1607 }
1608
1609 if err := sys.MapFreeze(&attr); err != nil {
1610 if haveFeatErr := haveMapMutabilityModifiers(); haveFeatErr != nil {
1611 return fmt.Errorf("can't freeze map: %w", haveFeatErr)
1612 }
1613 return fmt.Errorf("can't freeze map: %w", err)
1614 }
1615 return nil
1616 }
1617
1618 // finalize populates the Map according to the Contents specified
1619 // in spec and freezes the Map if requested by spec.
1620 func (m *Map) finalize(spec *MapSpec) error {
1621 for _, kv := range spec.Contents {
1622 if err := m.Put(kv.Key, kv.Value); err != nil {
1623 return fmt.Errorf("putting value: key %v: %w", kv.Key, err)
1624 }
1625 }
1626
1627 if isConstantDataSection(spec.Name) || isKconfigSection(spec.Name) {
1628 if err := m.Freeze(); err != nil {
1629 return fmt.Errorf("freezing map: %w", err)
1630 }
1631 }
1632
1633 return nil
1634 }
1635
1636 func (m *Map) marshalKey(data any) (sys.Pointer, error) {
1637 if data == nil {
1638 if m.keySize == 0 {
1639 // Queues have a key length of zero, so passing nil here is valid.
1640 return sys.UnsafePointer(nil), nil
1641 }
1642 return sys.Pointer{}, errors.New("can't use nil as key of map")
1643 }
1644
1645 return marshalMapSyscallInput(data, int(m.keySize))
1646 }
1647
1648 func (m *Map) marshalValue(data any) (sys.Pointer, error) {
1649 var (
1650 buf []byte
1651 err error
1652 )
1653
1654 switch value := data.(type) {
1655 case *Map:
1656 if !m.typ.canStoreMap() {
1657 return sys.Pointer{}, fmt.Errorf("can't store map in %s", m.typ)
1658 }
1659 buf, err = marshalMap(value, int(m.valueSize))
1660
1661 case *Program:
1662 if !m.typ.canStoreProgram() {
1663 return sys.Pointer{}, fmt.Errorf("can't store program in %s", m.typ)
1664 }
1665 buf, err = marshalProgram(value, int(m.valueSize))
1666
1667 default:
1668 return marshalMapSyscallInput(data, int(m.valueSize))
1669 }
1670
1671 if err != nil {
1672 return sys.Pointer{}, err
1673 }
1674
1675 return sys.UnsafeSlicePointer(buf), nil
1676 }
1677
1678 func (m *Map) unmarshalValue(value any, buf sysenc.Buffer) error {
1679 switch value := value.(type) {
1680 case **Map:
1681 if !m.typ.canStoreMap() {
1682 return fmt.Errorf("can't read a map from %s", m.typ)
1683 }
1684
1685 other, err := unmarshalMap(buf)
1686 if err != nil {
1687 return err
1688 }
1689
1690 // The caller might close the map externally, so ignore errors.
1691 _ = (*value).Close()
1692
1693 *value = other
1694 return nil
1695
1696 case *Map:
1697 if !m.typ.canStoreMap() {
1698 return fmt.Errorf("can't read a map from %s", m.typ)
1699 }
1700 return errors.New("require pointer to *Map")
1701
1702 case **Program:
1703 if !m.typ.canStoreProgram() {
1704 return fmt.Errorf("can't read a program from %s", m.typ)
1705 }
1706
1707 other, err := unmarshalProgram(buf)
1708 if err != nil {
1709 return err
1710 }
1711
1712 // The caller might close the program externally, so ignore errors.
1713 _ = (*value).Close()
1714
1715 *value = other
1716 return nil
1717
1718 case *Program:
1719 if !m.typ.canStoreProgram() {
1720 return fmt.Errorf("can't read a program from %s", m.typ)
1721 }
1722 return errors.New("require pointer to *Program")
1723 }
1724
1725 return buf.Unmarshal(value)
1726 }
1727
1728 // LoadPinnedMap opens a Map from a pin (file) on the BPF virtual filesystem.
1729 //
1730 // Requires at least Linux 4.5.
1731 func LoadPinnedMap(fileName string, opts *LoadPinOptions) (*Map, error) {
1732 fd, typ, err := sys.ObjGetTyped(&sys.ObjGetAttr{
1733 Pathname: sys.NewStringPointer(fileName),
1734 FileFlags: opts.Marshal(),
1735 })
1736 if err != nil {
1737 return nil, err
1738 }
1739
1740 if typ != sys.BPF_TYPE_MAP {
1741 _ = fd.Close()
1742 return nil, fmt.Errorf("%s is not a Map", fileName)
1743 }
1744
1745 m, err := newMapFromFD(fd)
1746 if err == nil {
1747 m.pinnedPath = fileName
1748 }
1749
1750 return m, err
1751 }
1752
1753 // unmarshalMap creates a map from a map ID encoded in host endianness.
1754 func unmarshalMap(buf sysenc.Buffer) (*Map, error) {
1755 var id uint32
1756 if err := buf.Unmarshal(&id); err != nil {
1757 return nil, err
1758 }
1759 return NewMapFromID(MapID(id))
1760 }
1761
1762 // marshalMap marshals the fd of a map into a buffer in host endianness.
1763 func marshalMap(m *Map, length int) ([]byte, error) {
1764 if m == nil {
1765 return nil, errors.New("can't marshal a nil Map")
1766 }
1767
1768 if length != 4 {
1769 return nil, fmt.Errorf("can't marshal map to %d bytes", length)
1770 }
1771
1772 buf := make([]byte, 4)
1773 internal.NativeEndian.PutUint32(buf, m.fd.Uint())
1774 return buf, nil
1775 }
1776
1777 // MapIterator iterates a Map.
1778 //
1779 // See Map.Iterate.
1780 type MapIterator struct {
1781 target *Map
1782 // Temporary storage to avoid allocations in Next(). This is any instead
1783 // of []byte to avoid allocations.
1784 cursor any
1785 count, maxEntries uint32
1786 done bool
1787 err error
1788 }
1789
1790 func newMapIterator(target *Map) *MapIterator {
1791 return &MapIterator{
1792 target: target,
1793 maxEntries: target.maxEntries,
1794 }
1795 }
1796
1797 // Next decodes the next key and value.
1798 //
1799 // Iterating a hash map from which keys are being deleted is not
1800 // safe. You may see the same key multiple times. Iteration may
1801 // also abort with an error, see IsIterationAborted.
1802 //
1803 // Returns false if there are no more entries. You must check
1804 // the result of Err afterwards.
1805 //
1806 // See Map.Get for further caveats around valueOut.
1807 func (mi *MapIterator) Next(keyOut, valueOut any) bool {
1808 if mi.err != nil || mi.done {
1809 return false
1810 }
1811
1812 // For array-like maps NextKey returns nil only after maxEntries
1813 // iterations.
1814 for mi.count <= mi.maxEntries {
1815 if mi.cursor == nil {
1816 // Pass nil interface to NextKey to make sure the Map's first key
1817 // is returned. If we pass an uninitialized []byte instead, it'll see a
1818 // non-nil interface and try to marshal it.
1819 mi.cursor = make([]byte, mi.target.keySize)
1820 mi.err = mi.target.NextKey(nil, mi.cursor)
1821 } else {
1822 mi.err = mi.target.NextKey(mi.cursor, mi.cursor)
1823 }
1824
1825 if errors.Is(mi.err, ErrKeyNotExist) {
1826 mi.done = true
1827 mi.err = nil
1828 return false
1829 } else if mi.err != nil {
1830 mi.err = fmt.Errorf("get next key: %w", mi.err)
1831 return false
1832 }
1833
1834 mi.count++
1835 mi.err = mi.target.Lookup(mi.cursor, valueOut)
1836 if errors.Is(mi.err, ErrKeyNotExist) {
1837 // Even though the key should be valid, we couldn't look up
1838 // its value. If we're iterating a hash map this is probably
1839 // because a concurrent delete removed the value before we
1840 // could get it. This means that the next call to NextKeyBytes
1841 // is very likely to restart iteration.
1842 // If we're iterating one of the fd maps like
1843 // ProgramArray it means that a given slot doesn't have
1844 // a valid fd associated. It's OK to continue to the next slot.
1845 continue
1846 }
1847 if mi.err != nil {
1848 mi.err = fmt.Errorf("look up next key: %w", mi.err)
1849 return false
1850 }
1851
1852 buf := mi.cursor.([]byte)
1853 if ptr, ok := keyOut.(unsafe.Pointer); ok {
1854 copy(unsafe.Slice((*byte)(ptr), len(buf)), buf)
1855 } else {
1856 mi.err = sysenc.Unmarshal(keyOut, buf)
1857 }
1858
1859 return mi.err == nil
1860 }
1861
1862 mi.err = fmt.Errorf("%w", ErrIterationAborted)
1863 return false
1864 }
1865
1866 // Err returns any encountered error.
1867 //
1868 // The method must be called after Next returns nil.
1869 //
1870 // Returns ErrIterationAborted if it wasn't possible to do a full iteration.
1871 func (mi *MapIterator) Err() error {
1872 return mi.err
1873 }
1874
1875 // MapGetNextID returns the ID of the next eBPF map.
1876 //
1877 // Returns ErrNotExist, if there is no next eBPF map.
1878 func MapGetNextID(startID MapID) (MapID, error) {
1879 attr := &sys.MapGetNextIdAttr{Id: uint32(startID)}
1880 return MapID(attr.NextId), sys.MapGetNextId(attr)
1881 }
1882
1883 // NewMapFromID returns the [Map] for a given map id. Returns [ErrNotExist] if
1884 // there is no eBPF map with the given id.
1885 //
1886 // Requires at least Linux 4.13.
1887 func NewMapFromID(id MapID) (*Map, error) {
1888 fd, err := sys.MapGetFdById(&sys.MapGetFdByIdAttr{
1889 Id: uint32(id),
1890 })
1891 if err != nil {
1892 return nil, err
1893 }
1894
1895 return newMapFromFD(fd)
1896 }
1897
1898 // sliceLen returns the length if the value is a slice or an error otherwise.
1899 func sliceLen(slice any) (int, error) {
1900 sliceValue := reflect.ValueOf(slice)
1901 if sliceValue.Kind() != reflect.Slice {
1902 return 0, fmt.Errorf("%T is not a slice", slice)
1903 }
1904 return sliceValue.Len(), nil
1905 }