Debian Codegraph @

memory.go

raw symbols SCIP
1 package ebpf
2
3 import (
4 "errors"
5 "fmt"
6 "io"
7 "runtime"
8
9 "github.com/cilium/ebpf/internal/unix"
10 )
11
12 // Memory is the building block for accessing the memory of specific bpf map
13 // types (Array and Arena at the time of writing) without going through the bpf
14 // syscall interface.
15 //
16 // Given the fd of a bpf map created with the BPF_F_MMAPABLE flag, a shared
17 // 'file'-based memory-mapped region can be allocated in the process' address
18 // space, exposing the bpf map's memory by simply accessing a memory location.
19
20 var ErrReadOnly = errors.New("resource is read-only")
21
22 // Memory implements accessing a Map's memory without making any syscalls.
23 // Pay attention to the difference between Go and C struct alignment rules. Use
24 // [structs.HostLayout] on supported Go versions to help with alignment.
25 //
26 // Note on memory coherence: avoid using packed structs in memory shared between
27 // user space and eBPF C programs. This drops a struct's memory alignment to 1,
28 // forcing the compiler to use single-byte loads and stores for field accesses.
29 // This may lead to partially-written data to be observed from user space.
30 //
31 // On most architectures, the memmove implementation used by Go's copy() will
32 // access data in word-sized chunks. If paired with a matching access pattern on
33 // the eBPF C side (and if using default memory alignment), accessing shared
34 // memory without atomics or other synchronization primitives should be sound
35 // for individual values. For accesses beyond a single value, the usual
36 // concurrent programming rules apply.
37 type Memory struct {
38 b []byte
39 ro bool
40 heap bool
41
42 cleanup runtime.Cleanup
43 }
44
45 func newMemory(fd, size int) (*Memory, error) {
46 // Typically, maps created with BPF_F_RDONLY_PROG remain writable from user
47 // space until frozen. As a security precaution, the kernel doesn't allow
48 // mapping bpf map memory as read-write into user space if the bpf map was
49 // frozen, or if it was created using the RDONLY_PROG flag.
50 //
51 // The user would be able to write to the map after freezing (since the kernel
52 // can't change the protection mode of an already-mapped page), while the
53 // verifier assumes the contents to be immutable.
54 b, err := unix.Mmap(fd, 0, size, unix.PROT_READ|unix.PROT_WRITE, unix.MAP_SHARED)
55
56 // If the map is frozen when an rw mapping is requested, expect EPERM. If the
57 // map was created with BPF_F_RDONLY_PROG, expect EACCES.
58 var ro bool
59 if errors.Is(err, unix.EPERM) || errors.Is(err, unix.EACCES) {
60 ro = true
61 b, err = unix.Mmap(fd, 0, size, unix.PROT_READ, unix.MAP_SHARED)
62 }
63 if err != nil {
64 return nil, fmt.Errorf("setting up memory-mapped region: %w", err)
65 }
66
67 mm := &Memory{b: b, ro: ro, heap: false}
68 mm.cleanup = runtime.AddCleanup(mm, memoryCleanupFunc(), b)
69
70 return mm, nil
71 }
72
73 func memoryCleanupFunc() func([]byte) {
74 return func(b []byte) {
75 if err := unix.Munmap(b); err != nil {
76 panic(fmt.Errorf("unmapping memory: %w", err))
77 }
78 }
79 }
80
81 func (mm *Memory) close() {
82 mm.cleanup.Stop()
83 memoryCleanupFunc()(mm.b)
84 mm.b = nil
85 }
86
87 // Size returns the size of the memory-mapped region in bytes.
88 func (mm *Memory) Size() uint32 {
89 return uint32(len(mm.b))
90 }
91
92 // ReadOnly returns true if the memory-mapped region is read-only.
93 func (mm *Memory) ReadOnly() bool {
94 return mm.ro
95 }
96
97 // bounds returns true if an access at off of the given size is within bounds.
98 func (mm *Memory) bounds(off, size uint32) bool {
99 if off+size < off {
100 return false
101 }
102 return off+size <= uint32(len(mm.b))
103 }
104
105 // ReadAt implements [io.ReaderAt]. Useful for creating a new [io.OffsetWriter].
106 //
107 // See [Memory] for details around memory coherence.
108 func (mm *Memory) ReadAt(p []byte, off int64) (int, error) {
109 if mm.b == nil {
110 return 0, fmt.Errorf("memory-mapped region closed")
111 }
112
113 if p == nil {
114 return 0, fmt.Errorf("input buffer p is nil")
115 }
116
117 if off < 0 || off >= int64(len(mm.b)) {
118 return 0, fmt.Errorf("read offset out of range")
119 }
120
121 n := copy(p, mm.b[off:])
122 if n < len(p) {
123 return n, io.EOF
124 }
125
126 return n, nil
127 }
128
129 // WriteAt implements [io.WriterAt]. Useful for creating a new
130 // [io.SectionReader].
131 //
132 // See [Memory] for details around memory coherence.
133 func (mm *Memory) WriteAt(p []byte, off int64) (int, error) {
134 if mm.b == nil {
135 return 0, fmt.Errorf("memory-mapped region closed")
136 }
137 if mm.ro {
138 return 0, fmt.Errorf("memory-mapped region not writable: %w", ErrReadOnly)
139 }
140
141 if p == nil {
142 return 0, fmt.Errorf("output buffer p is nil")
143 }
144
145 if off < 0 || off >= int64(len(mm.b)) {
146 return 0, fmt.Errorf("write offset out of range")
147 }
148
149 n := copy(mm.b[off:], p)
150 if n < len(p) {
151 return n, io.EOF
152 }
153
154 return n, nil
155 }