| 1 | package ebpf |
| 2 | |
| 3 | import ( |
| 4 | "errors" |
| 5 | "fmt" |
| 6 | "os" |
| 7 | "reflect" |
| 8 | "runtime" |
| 9 | "unsafe" |
| 10 | |
| 11 | "github.com/cilium/ebpf/internal" |
| 12 | "github.com/cilium/ebpf/internal/unix" |
| 13 | ) |
| 14 | |
| 15 | // This file contains an experimental, unsafe implementation of Memory that |
| 16 | // allows taking a Go pointer to a memory-mapped region. This currently does not |
| 17 | // have first-class support from the Go runtime, so it may break in future Go |
| 18 | // versions. The Go proposal for the runtime to track off-heap pointers is here: |
| 19 | // https://github.com/golang/go/issues/70224. |
| 20 | // |
| 21 | // In Go, the programmer should not have to worry about freeing memory. Since |
| 22 | // this API synthesizes Go variables around global variables declared in a BPF |
| 23 | // C program, we want to lean on the runtime for making sure accessing them is |
| 24 | // safe at all times. Unfortunately, Go (as of 1.24) does not have the ability |
| 25 | // of automatically managing memory that was not allocated by the runtime. |
| 26 | // |
| 27 | // This led to a solution that requests regular Go heap memory by allocating a |
| 28 | // slice (making the runtime track pointers into the slice's backing array) and |
| 29 | // memory-mapping the bpf map's memory over it. Then, before returning the |
| 30 | // Memory to the caller, a finalizer is set on the backing array, making sure |
| 31 | // the bpf map's memory is unmapped from the heap before releasing the backing |
| 32 | // array to the runtime for reallocation. |
| 33 | // |
| 34 | // This obviates the need to maintain a reference to the *Memory at all times, |
| 35 | // which is difficult for the caller to achieve if the variable access is done |
| 36 | // through another object (like a sync.Atomic) that can potentially be passed |
| 37 | // around the Go application. Accidentally losing the reference to the *Memory |
| 38 | // would result in hard-to-debug segfaults, which are always unexpected in Go. |
| 39 | |
| 40 | //go:linkname heapObjectsCanMove runtime.heapObjectsCanMove |
| 41 | func heapObjectsCanMove() bool |
| 42 | |
| 43 | // Set from a file behind the ebpf_unsafe_memory_experiment build tag to enable |
| 44 | // features that require mapping bpf map memory over the Go heap. |
| 45 | var unsafeMemory = false |
| 46 | |
| 47 | // ErrInvalidType is returned when the given type cannot be used as a Memory or |
| 48 | // Variable pointer. |
| 49 | var ErrInvalidType = errors.New("invalid type") |
| 50 | |
| 51 | func newUnsafeMemory(fd, size int) (*Memory, error) { |
| 52 | // Some architectures need the size to be page-aligned to work with MAP_FIXED. |
| 53 | if size%os.Getpagesize() != 0 { |
| 54 | return nil, fmt.Errorf("memory: must be a multiple of page size (requested %d bytes)", size) |
| 55 | } |
| 56 | |
| 57 | // Allocate a page-aligned span of memory on the Go heap. |
| 58 | alloc, err := allocate(size) |
| 59 | if err != nil { |
| 60 | return nil, fmt.Errorf("allocating memory: %w", err) |
| 61 | } |
| 62 | |
| 63 | // Typically, maps created with BPF_F_RDONLY_PROG remain writable from user |
| 64 | // space until frozen. As a security precaution, the kernel doesn't allow |
| 65 | // mapping bpf map memory as read-write into user space if the bpf map was |
| 66 | // frozen, or if it was created using the RDONLY_PROG flag. |
| 67 | // |
| 68 | // The user would be able to write to the map after freezing (since the kernel |
| 69 | // can't change the protection mode of an already-mapped page), while the |
| 70 | // verifier assumes the contents to be immutable. |
| 71 | // |
| 72 | // Map the bpf map memory over a page-aligned allocation on the Go heap. |
| 73 | err = mapmap(fd, alloc, size, unix.PROT_READ|unix.PROT_WRITE) |
| 74 | |
| 75 | // If the map is frozen when an rw mapping is requested, expect EPERM. If the |
| 76 | // map was created with BPF_F_RDONLY_PROG, expect EACCES. |
| 77 | var ro bool |
| 78 | if errors.Is(err, unix.EPERM) || errors.Is(err, unix.EACCES) { |
| 79 | ro = true |
| 80 | err = mapmap(fd, alloc, size, unix.PROT_READ) |
| 81 | } |
| 82 | if err != nil { |
| 83 | return nil, fmt.Errorf("setting up memory-mapped region: %w", err) |
| 84 | } |
| 85 | |
| 86 | mm := &Memory{ |
| 87 | unsafe.Slice((*byte)(alloc), size), |
| 88 | ro, |
| 89 | true, |
| 90 | runtime.Cleanup{}, |
| 91 | } |
| 92 | |
| 93 | return mm, nil |
| 94 | } |
| 95 | |
| 96 | // allocate returns a pointer to a page-aligned section of memory on the Go |
| 97 | // heap, managed by the runtime. |
| 98 | // |
| 99 | //go:nocheckptr |
| 100 | func allocate(size int) (unsafe.Pointer, error) { |
| 101 | // Memory-mapping over a piece of the Go heap is unsafe when the GC can |
| 102 | // randomly decide to move objects around, in which case the mapped region |
| 103 | // will not move along with it. |
| 104 | if heapObjectsCanMove() { |
| 105 | return nil, errors.New("this Go runtime has a moving garbage collector") |
| 106 | } |
| 107 | |
| 108 | if size == 0 { |
| 109 | return nil, errors.New("size must be greater than 0") |
| 110 | } |
| 111 | |
| 112 | // Request at least two pages of memory from the runtime to ensure we can |
| 113 | // align the requested allocation to a page boundary. This is needed for |
| 114 | // MAP_FIXED and makes sure we don't mmap over some other allocation on the Go |
| 115 | // heap. |
| 116 | size = internal.Align(size+os.Getpagesize(), os.Getpagesize()) |
| 117 | |
| 118 | // Allocate a new slice and store a pointer to its backing array. |
| 119 | alloc := unsafe.Pointer(unsafe.SliceData(make([]byte, size))) |
| 120 | |
| 121 | // Align the pointer to a page boundary within the allocation. This may alias |
| 122 | // the initial pointer if it was already page-aligned. |
| 123 | aligned := internal.Align(uintptr(alloc), uintptr(os.Getpagesize())) |
| 124 | alloc = unsafe.Add(alloc, aligned-uintptr(alloc)) |
| 125 | |
| 126 | // Return an aligned pointer into the backing array, losing the original |
| 127 | // reference. The runtime.SetFinalizer docs specify that its argument 'must be |
| 128 | // a pointer to an object, complit or local var', but this is still somewhat |
| 129 | // vague and not enforced by the current implementation. |
| 130 | // |
| 131 | // Currently, finalizers can be set and triggered from any address within a |
| 132 | // heap allocation, even individual struct fields or arbitrary offsets within |
| 133 | // a slice. In this case, finalizers set on struct fields or slice offsets |
| 134 | // will only run when the whole struct or backing array are collected. The |
| 135 | // accepted runtime.AddCleanup proposal makes this behaviour more explicit and |
| 136 | // is set to deprecate runtime.SetFinalizer. |
| 137 | // |
| 138 | // Alternatively, we'd have to track the original allocation and the aligned |
| 139 | // pointer separately, which severely complicates finalizer setup and makes it |
| 140 | // prone to human error. For now, just bump the pointer and treat it as the |
| 141 | // new and only reference to the backing array. |
| 142 | return alloc, nil |
| 143 | } |
| 144 | |
| 145 | // mapmap memory-maps the given file descriptor at the given address and sets a |
| 146 | // finalizer on addr to unmap it when it's no longer reachable. |
| 147 | func mapmap(fd int, addr unsafe.Pointer, size, flags int) error { |
| 148 | // Map the bpf map memory over the Go heap. This will result in the following |
| 149 | // mmap layout in the process' address space (0xc000000000 is a span of Go |
| 150 | // heap), visualized using pmap: |
| 151 | // |
| 152 | // Address Kbytes RSS Dirty Mode Mapping |
| 153 | // 000000c000000000 1824 864 864 rw--- [ anon ] |
| 154 | // 000000c0001c8000 4 4 4 rw-s- [ anon ] |
| 155 | // 000000c0001c9000 2268 16 16 rw--- [ anon ] |
| 156 | // |
| 157 | // This will break up the Go heap, but as long as the runtime doesn't try to |
| 158 | // move our allocation around, this is safe for as long as we hold a reference |
| 159 | // to our allocated object. |
| 160 | // |
| 161 | // Use MAP_SHARED to make sure the kernel sees any writes we do, and MAP_FIXED |
| 162 | // to ensure the mapping starts exactly at the address we requested. If alloc |
| 163 | // isn't page-aligned, the mapping operation will fail. |
| 164 | if _, err := unix.MmapPtr(fd, 0, addr, uintptr(size), |
| 165 | flags, unix.MAP_SHARED|unix.MAP_FIXED); err != nil { |
| 166 | return fmt.Errorf("setting up memory-mapped region: %w", err) |
| 167 | } |
| 168 | |
| 169 | // Set a finalizer on the heap allocation to undo the mapping before the span |
| 170 | // is collected and reused by the runtime. This has a few reasons: |
| 171 | // |
| 172 | // - Avoid leaking memory/mappings. |
| 173 | // - Future writes to this memory should never clobber a bpf map's contents. |
| 174 | // - Some bpf maps are mapped read-only, causing a segfault if the runtime |
| 175 | // reallocates and zeroes the span later. |
| 176 | runtime.SetFinalizer((*byte)(addr), unmap(size)) |
| 177 | |
| 178 | return nil |
| 179 | } |
| 180 | |
| 181 | // unmap returns a function that takes a pointer to a memory-mapped region on |
| 182 | // the Go heap. The function undoes any mappings and discards the span's |
| 183 | // contents. |
| 184 | // |
| 185 | // Used as a finalizer in [newMemory], split off into a separate function for |
| 186 | // testing and to avoid accidentally closing over the unsafe.Pointer to the |
| 187 | // memory region, which would cause a cyclical reference. |
| 188 | // |
| 189 | // The resulting function panics if the mmap operation returns an error, since |
| 190 | // it would mean the integrity of the Go heap is compromised. |
| 191 | func unmap(size int) func(*byte) { |
| 192 | return func(a *byte) { |
| 193 | // Create another mapping at the same address to undo the original mapping. |
| 194 | // This will cause the kernel to repair the slab since we're using the same |
| 195 | // protection mode and flags as the original mapping for the Go heap. |
| 196 | // |
| 197 | // Address Kbytes RSS Dirty Mode Mapping |
| 198 | // 000000c000000000 4096 884 884 rw--- [ anon ] |
| 199 | // |
| 200 | // Using munmap here would leave an unmapped hole in the heap, compromising |
| 201 | // its integrity. |
| 202 | // |
| 203 | // MmapPtr allocates another unsafe.Pointer at the same address. Even though |
| 204 | // we discard it here, it may temporarily resurrect the backing array and |
| 205 | // delay its collection to the next GC cycle. |
| 206 | _, err := unix.MmapPtr(-1, 0, unsafe.Pointer(a), uintptr(size), |
| 207 | unix.PROT_READ|unix.PROT_WRITE, |
| 208 | unix.MAP_PRIVATE|unix.MAP_FIXED|unix.MAP_ANON) |
| 209 | if err != nil { |
| 210 | panic(fmt.Errorf("undoing bpf map memory mapping: %w", err)) |
| 211 | } |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | // checkUnsafeMemory ensures value T can be accessed in mm at offset off. |
| 216 | // |
| 217 | // The comparable constraint narrows down the set of eligible types to exclude |
| 218 | // slices, maps and functions. These complex types cannot be mapped to memory |
| 219 | // directly. |
| 220 | func checkUnsafeMemory[T comparable](mm *Memory, off uint32) error { |
| 221 | if mm.b == nil { |
| 222 | return fmt.Errorf("memory-mapped region is nil") |
| 223 | } |
| 224 | if mm.ro { |
| 225 | return ErrReadOnly |
| 226 | } |
| 227 | if !mm.heap { |
| 228 | return fmt.Errorf("memory region is not heap-mapped, build with '-tags ebpf_unsafe_memory_experiment' to enable: %w", ErrNotSupported) |
| 229 | } |
| 230 | |
| 231 | t := reflect.TypeFor[T]() |
| 232 | if err := checkType(t.String(), t); err != nil { |
| 233 | return err |
| 234 | } |
| 235 | |
| 236 | size := t.Size() |
| 237 | if size == 0 { |
| 238 | return fmt.Errorf("zero-sized type %s: %w", t, ErrInvalidType) |
| 239 | } |
| 240 | |
| 241 | if off%uint32(t.Align()) != 0 { |
| 242 | return fmt.Errorf("unaligned access of memory-mapped region: %d-byte aligned read at offset %d", t.Align(), off) |
| 243 | } |
| 244 | |
| 245 | vs, bs := uint32(size), uint32(len(mm.b)) |
| 246 | if !mm.bounds(off, vs) { |
| 247 | return fmt.Errorf("%d-byte value at offset %d exceeds mmap size of %d bytes", vs, off, bs) |
| 248 | } |
| 249 | |
| 250 | return nil |
| 251 | } |
| 252 | |
| 253 | // checkType recursively checks if the given type is supported for memory |
| 254 | // mapping. Only fixed-size, non-Go-pointer types are supported: bools, floats, |
| 255 | // (u)int[8-64], arrays, and structs containing them. As an exception, uintptr |
| 256 | // is allowed since the backing memory is expected to contain 32-bit pointers on |
| 257 | // 32-bit systems despite BPF always allocating 64 bits for pointers in a data |
| 258 | // section. |
| 259 | // |
| 260 | // Doesn't check for loops since it rejects pointers. Should that ever change, a |
| 261 | // visited set would be needed. |
| 262 | func checkType(name string, t reflect.Type) error { |
| 263 | // Special-case atomic types to allow them to be used as root types as well as |
| 264 | // struct fields. Notably, omit atomic.Value and atomic.Pointer since those |
| 265 | // are pointer types. Also, atomic.Value embeds an interface value, which |
| 266 | // doesn't make sense to share with C land. |
| 267 | if t.PkgPath() == "sync/atomic" { |
| 268 | switch t.Name() { |
| 269 | case "Bool", "Int32", "Int64", "Uint32", "Uint64", "Uintptr": |
| 270 | return nil |
| 271 | } |
| 272 | } |
| 273 | |
| 274 | switch t.Kind() { |
| 275 | case reflect.Uintptr, reflect.Bool, reflect.Float32, reflect.Float64, |
| 276 | reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, |
| 277 | reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: |
| 278 | return nil |
| 279 | |
| 280 | case reflect.Array: |
| 281 | at := t.Elem() |
| 282 | if err := checkType(fmt.Sprintf("%s.%s", name, at.String()), at); err != nil { |
| 283 | return err |
| 284 | } |
| 285 | |
| 286 | case reflect.Struct: |
| 287 | var hasHostLayout bool |
| 288 | for i := range t.NumField() { |
| 289 | at := t.Field(i).Type |
| 290 | |
| 291 | // Require [structs.HostLayout] to be embedded in all structs. Check the |
| 292 | // full package path to reject a user-defined HostLayout type. |
| 293 | if at.PkgPath() == "structs" && at.Name() == "HostLayout" { |
| 294 | hasHostLayout = true |
| 295 | continue |
| 296 | } |
| 297 | |
| 298 | if err := checkType(fmt.Sprintf("%s.%s", name, at.String()), at); err != nil { |
| 299 | return err |
| 300 | } |
| 301 | } |
| 302 | |
| 303 | if !hasHostLayout { |
| 304 | return fmt.Errorf("struct %s must embed structs.HostLayout: %w", name, ErrInvalidType) |
| 305 | } |
| 306 | |
| 307 | default: |
| 308 | // For basic types like int and bool, the kind name is the same as the type |
| 309 | // name, so the fallthrough case would print 'int type int not supported'. |
| 310 | // Omit the kind name if it matches the type name. |
| 311 | if t.String() == t.Kind().String() { |
| 312 | // Output: type int not supported |
| 313 | return fmt.Errorf("type %s not supported: %w", name, ErrInvalidType) |
| 314 | } |
| 315 | |
| 316 | // Output: interface value io.Reader not supported |
| 317 | return fmt.Errorf("%s type %s not supported: %w", t.Kind(), name, ErrInvalidType) |
| 318 | } |
| 319 | |
| 320 | return nil |
| 321 | } |
| 322 | |
| 323 | // memoryPointer returns a pointer to a value of type T at offset off in mm. |
| 324 | // Taking a pointer to a read-only Memory or to a Memory that is not heap-mapped |
| 325 | // is not supported. |
| 326 | // |
| 327 | // T must contain only fixed-size, non-Go-pointer types: bools, floats, |
| 328 | // (u)int[8-64], arrays, and structs containing them. Structs must embed |
| 329 | // [structs.HostLayout]. [ErrInvalidType] is returned if T is not a valid type. |
| 330 | // |
| 331 | // Memory must be writable, off must be aligned to the size of T, and the value |
| 332 | // must be within bounds of the Memory. |
| 333 | // |
| 334 | // To access read-only memory, use [Memory.ReadAt]. |
| 335 | func memoryPointer[T comparable](mm *Memory, off uint32) (*T, error) { |
| 336 | if err := checkUnsafeMemory[T](mm, off); err != nil { |
| 337 | return nil, fmt.Errorf("memory pointer: %w", err) |
| 338 | } |
| 339 | return (*T)(unsafe.Pointer(&mm.b[off])), nil |
| 340 | } |