|
| 1 | +//! Lock-free, async-signal-safe global allocator for the fspy preload library. |
| 2 | +//! |
| 3 | +//! The preload library interposes libc functions that POSIX declares |
| 4 | +//! async-signal-safe (`open`, `stat`, `execve`, ...). Programs may call these |
| 5 | +//! from signal handlers, and — more commonly — from the child of `fork()` in a |
| 6 | +//! multithreaded process, where only async-signal-safe calls are permitted: |
| 7 | +//! the libc allocator's locks may be held forever by threads that no longer |
| 8 | +//! exist after the fork. Routing the preload's Rust allocations through this |
| 9 | +//! allocator keeps them safe in both contexts: |
| 10 | +//! |
| 11 | +//! - **No locks.** Every state transition is a lock-free compare-and-swap |
| 12 | +//! loop: an attempt only retries because another running thread completed |
| 13 | +//! its operation, so nothing ever waits on state that a thread which |
| 14 | +//! vanished at `fork()` — or sits suspended under a signal handler — would |
| 15 | +//! have to release. (Lock-free, not wait-free: an individual operation has |
| 16 | +//! no fixed retry bound under active contention.) |
| 17 | +//! - **No thread-locals.** TLS first-touch allocates through libc malloc on |
| 18 | +//! some platforms (macOS thread-local variables), which would reintroduce |
| 19 | +//! the hazard this crate exists to remove. |
| 20 | +//! - **mmap-backed.** Memory comes straight from the kernel. On Linux the |
| 21 | +//! allocator relies on nothing from libc: mapping syscalls are issued |
| 22 | +//! directly (rustix's raw backend) and even the page size is discovered by |
| 23 | +//! probing with raw syscalls. On macOS, which has no stable raw-syscall |
| 24 | +//! ABI, calls go through the thin libSystem stubs. libc malloc is never |
| 25 | +//! called anywhere. |
| 26 | +//! |
| 27 | +//! Design: power-of-two size classes (16 B ..= 64 KiB) carve blocks out of |
| 28 | +//! 1 MiB slabs; freed blocks recycle through a per-class Treiber free list |
| 29 | +//! made ABA-safe by a generation tag. Requests larger than the biggest class |
| 30 | +//! (or over-aligned beyond 4 KiB) map and unmap directly. See the `pool` |
| 31 | +//! module for the details. |
| 32 | +//! |
| 33 | +//! Because the allocator is a `const`-initialized static with no lazy setup, |
| 34 | +//! it works from the very first allocation in the process — even before the |
| 35 | +//! preload library's constructor runs. |
| 36 | +
|
| 37 | +#![cfg_attr(not(test), no_std)] |
| 38 | + |
| 39 | +// Compile as an empty crate on non-unix targets: the allocator backs the unix |
| 40 | +// preload library. A Windows backend can be added alongside `sys::Mmap` if |
| 41 | +// the Windows preload ever needs one. |
| 42 | + |
| 43 | +#[cfg(unix)] |
| 44 | +mod class; |
| 45 | +#[cfg(unix)] |
| 46 | +mod mapping; |
| 47 | +#[cfg(unix)] |
| 48 | +mod mmap; |
| 49 | +#[cfg(unix)] |
| 50 | +mod pool; |
| 51 | +#[cfg(unix)] |
| 52 | +mod slab; |
| 53 | +#[cfg(unix)] |
| 54 | +mod sys; |
| 55 | + |
| 56 | +#[cfg(unix)] |
| 57 | +use core::{ |
| 58 | + alloc::{GlobalAlloc, Layout}, |
| 59 | + ptr::{self, NonNull}, |
| 60 | +}; |
| 61 | + |
| 62 | +#[cfg(unix)] |
| 63 | +use crate::{mmap::Mmap, pool::Pool}; |
| 64 | + |
| 65 | +/// A lock-free, async-signal-safe, fork-safe [`GlobalAlloc`] implementation. |
| 66 | +/// |
| 67 | +/// Intended to be installed as the `#[global_allocator]` of the fspy preload |
| 68 | +/// library. All memory comes from anonymous mappings; libc malloc is never |
| 69 | +/// called, no locks are taken, and no thread-local state is used. |
| 70 | +/// |
| 71 | +/// Capacity is bounded by design: each size class can hold at most 256 slabs |
| 72 | +/// of 1 MiB (roughly 200 MiB per class). Requests beyond that — far outside |
| 73 | +/// anything the preload library does — fail like any other out-of-memory |
| 74 | +/// condition (`alloc` returns null). |
| 75 | +#[cfg(unix)] |
| 76 | +pub struct FspyAlloc { |
| 77 | + pool: Pool<Mmap>, |
| 78 | +} |
| 79 | + |
| 80 | +#[cfg(unix)] |
| 81 | +impl FspyAlloc { |
| 82 | + /// Creates the allocator. `const` so it can back a `static` with no |
| 83 | + /// runtime initialization. |
| 84 | + #[must_use] |
| 85 | + pub const fn new() -> Self { |
| 86 | + Self { pool: Pool::new() } |
| 87 | + } |
| 88 | +} |
| 89 | + |
| 90 | +#[cfg(unix)] |
| 91 | +impl Default for FspyAlloc { |
| 92 | + fn default() -> Self { |
| 93 | + Self::new() |
| 94 | + } |
| 95 | +} |
| 96 | + |
| 97 | +// SAFETY: `Pool` hands out blocks that are non-null, at least `layout.size()` |
| 98 | +// bytes large, aligned to at least `layout.align()`, and exclusively owned |
| 99 | +// until returned via `dealloc`. Allocation failure is reported as null, and |
| 100 | +// none of the methods unwind. |
| 101 | +#[cfg(unix)] |
| 102 | +unsafe impl GlobalAlloc for FspyAlloc { |
| 103 | + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { |
| 104 | + self.pool.alloc(layout).map_or(ptr::null_mut(), NonNull::as_ptr) |
| 105 | + } |
| 106 | + |
| 107 | + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { |
| 108 | + let Some(ptr) = NonNull::new(ptr) else { return }; |
| 109 | + // SAFETY: per the GlobalAlloc contract, `ptr` was returned by this |
| 110 | + // allocator for this `layout`. |
| 111 | + unsafe { self.pool.dealloc(ptr, layout) } |
| 112 | + } |
| 113 | + |
| 114 | + unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 { |
| 115 | + self.pool.alloc_zeroed(layout).map_or(ptr::null_mut(), NonNull::as_ptr) |
| 116 | + } |
| 117 | + |
| 118 | + unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 { |
| 119 | + let Some(ptr) = NonNull::new(ptr) else { return ptr::null_mut() }; |
| 120 | + // SAFETY: per the GlobalAlloc contract, `ptr` was returned by this |
| 121 | + // allocator for this `layout`, and `new_size` is non-zero. |
| 122 | + unsafe { self.pool.realloc(ptr, layout, new_size) }.map_or(ptr::null_mut(), NonNull::as_ptr) |
| 123 | + } |
| 124 | +} |
0 commit comments