Skip to main content

stackful/
stack.rs

1use alloc::alloc::{alloc, dealloc, handle_alloc_error};
2use core::{alloc::Layout, ptr::NonNull};
3const GUARD: usize = 64;
4/// Default minimum usable stack size in bytes applied by [`Stack::new`].
5pub const DEFAULT_MIN_STACK_SIZE: usize = 4096;
6/// Smallest usable stack size in bytes permitted by [`Stack::with_min_size`].
7pub const MIN_STACK_SIZE: usize = 2048;
8const PAINT: u8 = 0xa5;
9
10/// Function that allocates backing memory for a coroutine [`Stack`] with the requested [`Layout`].
11///
12/// Must return either a null pointer on failure or a pointer to at least `layout.size()`
13/// writable bytes aligned to `layout.align()`.
14pub type StackAllocateFn = unsafe fn(Layout) -> *mut u8;
15
16/// Function that releases backing memory previously returned by its paired [`StackAllocateFn`]
17/// with the exact same [`Layout`].
18pub type StackDeallocateFn = unsafe fn(*mut u8, Layout);
19
20unsafe fn global_allocate(layout: Layout) -> *mut u8 {
21    // SAFETY: forwarded to the global allocator with the caller's non-zero layout.
22    unsafe { alloc(layout) }
23}
24
25unsafe fn global_deallocate(pointer: *mut u8, layout: Layout) {
26    // SAFETY: `pointer` was returned by `global_allocate` with `layout`.
27    unsafe { dealloc(pointer, layout) }
28}
29
30/// Allocator hooks used to obtain and release coroutine [`Stack`] backing memory.
31///
32/// By default, [`Stack`] uses [`StackAllocator::GLOBAL`], which forwards to
33/// [`alloc::alloc::alloc`] and [`alloc::alloc::dealloc`]. Platforms whose global heap
34/// places large allocations in memory that cannot safely back stacks (such as PSRAM on
35/// Espressif boards, which becomes inaccessible during flash writes) can install an
36/// allocator backed by always-accessible internal SRAM via [`set_stack_allocator`].
37#[derive(Clone, Copy, Debug)]
38pub struct StackAllocator {
39    /// Allocate backing memory for a stack with the requested [`Layout`].
40    pub allocate: StackAllocateFn,
41    /// Release backing memory previously returned by [`Self::allocate`] with the same [`Layout`].
42    pub deallocate: StackDeallocateFn,
43}
44
45impl StackAllocator {
46    /// Create a stack allocator from an `allocate`/`deallocate` function-pointer pair.
47    pub const fn new(allocate: StackAllocateFn, deallocate: StackDeallocateFn) -> Self {
48        Self {
49            allocate,
50            deallocate,
51        }
52    }
53
54    /// The default stack allocator backed by [`alloc::alloc::alloc`] and [`alloc::alloc::dealloc`].
55    pub const GLOBAL: Self = Self {
56        allocate: global_allocate,
57        deallocate: global_deallocate,
58    };
59}
60
61#[cfg(target_os = "linux")]
62static STACK_ALLOCATOR: std::sync::Mutex<StackAllocator> =
63    std::sync::Mutex::new(StackAllocator::GLOBAL);
64
65#[cfg(not(target_os = "linux"))]
66static STACK_ALLOCATOR: critical_section::Mutex<core::cell::Cell<StackAllocator>> =
67    critical_section::Mutex::new(core::cell::Cell::new(StackAllocator::GLOBAL));
68
69fn current_stack_allocator() -> StackAllocator {
70    #[cfg(target_os = "linux")]
71    {
72        *STACK_ALLOCATOR
73            .lock()
74            .unwrap_or_else(|poisoned| poisoned.into_inner())
75    }
76    #[cfg(not(target_os = "linux"))]
77    {
78        critical_section::with(|cs| STACK_ALLOCATOR.borrow(cs).get())
79    }
80}
81
82/// Register the allocator used for subsequent coroutine [`Stack`] allocations.
83///
84/// Platforms whose global allocator places large allocations in external memory that cannot
85/// safely back stacks (such as PSRAM on Espressif boards, which is unreachable while writing
86/// flash) should call this once during start-up before launching coroutines.
87///
88/// Each [`Stack`] stores the `deallocate` function from the allocator that created it, so
89/// already-live stacks are always released through their matching deallocator even if the
90/// hook is replaced afterwards. Pass [`StackAllocator::GLOBAL`] to restore the default
91/// global allocator.
92///
93/// # Safety
94/// - `allocator.allocate` must return either a null pointer or a non-null pointer to an
95///   exclusive, writable memory block of at least `layout.size()` bytes aligned to
96///   `layout.align()`.
97/// - Any returned memory must remain valid and accessible (including across interrupts and
98///   flash writes on bare-metal targets) until released via `allocator.deallocate`.
99/// - `allocator.deallocate` must safely release any non-null pointer returned by
100///   `allocator.allocate` when passed the exact matching `layout`.
101/// - Both functions must be safe to call from any thread or core that creates or drops a
102///   [`Stack`], without requiring the caller to hold a critical section.
103pub unsafe fn set_stack_allocator(allocator: StackAllocator) {
104    #[cfg(target_os = "linux")]
105    {
106        *STACK_ALLOCATOR
107            .lock()
108            .unwrap_or_else(|poisoned| poisoned.into_inner()) = allocator;
109    }
110    #[cfg(not(target_os = "linux"))]
111    {
112        critical_section::with(|cs| STACK_ALLOCATOR.borrow(cs).set(allocator));
113    }
114}
115
116/// Single heap allocation, aligned to 16 bytes, with a 64-byte painted lower guard.
117/// This detects damage at boundaries; it does not provide memory protection.
118pub struct Stack {
119    memory: NonNull<u8>,
120    layout: Layout,
121    deallocate: StackDeallocateFn,
122}
123impl Stack {
124    /// Allocate a stack with at least [`DEFAULT_MIN_STACK_SIZE`] (4 KiB) usable bytes,
125    /// rounded up to 16 bytes, plus a 64-byte painted lower guard.
126    pub fn new(size: usize) -> Self {
127        Self::with_min_size(size, DEFAULT_MIN_STACK_SIZE)
128    }
129
130    /// Allocate a stack with a caller-chosen minimum usable size, floored at
131    /// [`MIN_STACK_SIZE`] (2 KiB), rounded up to 16 bytes, plus the same 64-byte
132    /// painted lower guard as [`Stack::new`].
133    ///
134    /// Lowering the minimum below 4 KiB saves RAM on constrained MCUs (e.g. 256 KiB
135    /// SRAM), at the cost of tighter headroom for call depth, debug frames,
136    /// suspended futures pinned on the native stack, and shared interrupt frames.
137    /// Audit worst-case stack usage before choosing a 2 KiB stack.
138    pub fn with_min_size(size: usize, min_usable: usize) -> Self {
139        let layout = Self::layout(size, min_usable).expect("stack too large");
140        Self::allocate(layout).unwrap_or_else(|| handle_alloc_error(layout))
141    }
142
143    /// Like [`Stack::with_min_size`], but returns `None` instead of panicking or
144    /// aborting when the size is unrepresentable or the allocator is out of memory.
145    pub fn try_with_min_size(size: usize, min_usable: usize) -> Option<Self> {
146        Self::allocate(Self::layout(size, min_usable)?)
147    }
148
149    fn layout(size: usize, min_usable: usize) -> Option<Layout> {
150        let size = size.max(min_usable.max(MIN_STACK_SIZE));
151        Layout::from_size_align(size.checked_add(GUARD + 15)? & !15, 16).ok()
152    }
153
154    fn allocate(layout: Layout) -> Option<Self> {
155        let allocator = current_stack_allocator();
156        // SAFETY: `layout` has non-zero size (at least MIN_STACK_SIZE + GUARD) and valid
157        // 16-byte alignment; `allocator` satisfies the `set_stack_allocator` contract.
158        let memory = NonNull::new(unsafe { (allocator.allocate)(layout) })?;
159        unsafe { memory.as_ptr().write_bytes(PAINT, layout.size()) };
160        Some(Self {
161            memory,
162            layout,
163            deallocate: allocator.deallocate,
164        })
165    }
166    pub(crate) fn top(&self) -> usize {
167        self.memory.as_ptr() as usize + self.layout.size()
168    }
169    pub fn usable_size(&self) -> usize {
170        self.layout.size() - GUARD
171    }
172    pub fn guard_intact(&self) -> bool {
173        // SAFETY: this Stack still owns the allocation containing the guard.
174        unsafe { guard_intact_at(self.memory) }
175    }
176    /// The painted guard at the lower end, for checks while a coroutine owns the stack.
177    pub(crate) fn guard(&self) -> NonNull<u8> {
178        self.memory
179    }
180}
181
182/// The corosensei view of a [`Stack`]. A private type, so only `Coroutine::new` can
183/// hand a painted stack, which has no protected guard, to corosensei.
184#[repr(transparent)]
185pub(crate) struct Backing(pub(crate) Stack);
186
187// SAFETY: the allocation is 16-byte aligned and stable for the lifetime of the value.
188// It deviates from two documented requirements of corosensei's `Stack` trait, neither of
189// which corosensei checks for a custom stack (only its built-in stacks use them):
190// - No guard page. Microcontrollers have no MMU to provide one, and on hosts the heap
191//   block has none either. The painted guard only detects an overflow at the next switch.
192// - At least 2 KiB of usable memory instead of corosensei's `MIN_STACK_SIZE` (4 KiB).
193// Both are covered by the caller of the unsafe `Coroutine::new`, which must size the
194// stack for all native stack use: the entry, its callees and interrupt frames (on
195// Xtensa, `xtensa-lx-rt` pushes 256 bytes per interrupt level on the coroutine stack).
196// Revisit this if a corosensei feature that relies on either requirement is enabled.
197unsafe impl corosensei::stack::Stack for Backing {
198    fn base(&self) -> corosensei::stack::StackPointer {
199        // SAFETY: both addresses lie in a live allocation, so they are not zero. The
200        // unchecked constructor avoids a panic site on every target.
201        unsafe { corosensei::stack::StackPointer::new_unchecked(self.0.top()) }
202    }
203    fn limit(&self) -> corosensei::stack::StackPointer {
204        // SAFETY: as in `base`.
205        unsafe { corosensei::stack::StackPointer::new_unchecked(self.0.guard().as_ptr() as usize) }
206    }
207}
208
209/// # Safety
210/// The allocation holding the guard must be alive.
211unsafe fn guard_intact_at(guard: NonNull<u8>) -> bool {
212    (0..GUARD).all(|i| unsafe { guard.as_ptr().add(i).read_volatile() == PAINT })
213}
214
215/// Terminate the program if the painted guard was damaged.
216///
217/// # Safety
218/// The allocation holding the guard must be alive.
219pub(crate) unsafe fn check_guard_at(guard: NonNull<u8>) {
220    // C ABI ensures fatal termination instead of unwinding over a damaged stack.
221    extern "C" fn overflow() -> ! {
222        panic!("stackful stack guard corrupted");
223    }
224    if !unsafe { guard_intact_at(guard) } {
225        overflow();
226    }
227}
228impl Drop for Stack {
229    fn drop(&mut self) {
230        // SAFETY: `self.memory` was allocated by the allocator paired with `self.deallocate`
231        // using `self.layout`, and this `Stack` owns it exclusively until dropped.
232        unsafe { (self.deallocate)(self.memory.as_ptr(), self.layout) };
233    }
234}
235#[cfg(test)]
236mod tests {
237    use super::*;
238    use std::sync::{Mutex, RwLock};
239
240    /// Serializes tests that mutate the global stack allocator hook against tests
241    /// that rely on the default global allocator.
242    static ALLOCATOR_TEST_LOCK: RwLock<()> = RwLock::new(());
243
244    struct HookGuard<'a> {
245        _lock: std::sync::RwLockWriteGuard<'a, ()>,
246    }
247
248    impl<'a> HookGuard<'a> {
249        fn install(allocator: StackAllocator) -> Self {
250            let lock = ALLOCATOR_TEST_LOCK
251                .write()
252                .unwrap_or_else(|poisoned| poisoned.into_inner());
253            // SAFETY: test hooks satisfy the `StackAllocator` contract.
254            unsafe { set_stack_allocator(allocator) };
255            Self { _lock: lock }
256        }
257    }
258
259    impl Drop for HookGuard<'_> {
260        fn drop(&mut self) {
261            // SAFETY: restoring the built-in global allocator is always valid.
262            unsafe { set_stack_allocator(StackAllocator::GLOBAL) };
263        }
264    }
265
266    #[derive(Default)]
267    struct RecordedCalls {
268        alloc_layouts: std::vec::Vec<(usize, Layout)>,
269        dealloc_calls: std::vec::Vec<(usize, Layout)>,
270    }
271
272    static CUSTOM_A_STATE: Mutex<RecordedCalls> = Mutex::new(RecordedCalls {
273        alloc_layouts: std::vec::Vec::new(),
274        dealloc_calls: std::vec::Vec::new(),
275    });
276
277    static CUSTOM_B_STATE: Mutex<RecordedCalls> = Mutex::new(RecordedCalls {
278        alloc_layouts: std::vec::Vec::new(),
279        dealloc_calls: std::vec::Vec::new(),
280    });
281
282    static NULL_ALLOC_STATE: Mutex<(usize, usize)> = Mutex::new((0, 0));
283
284    unsafe fn custom_a_allocate(layout: Layout) -> *mut u8 {
285        let pointer = unsafe { alloc(layout) };
286        if !pointer.is_null() {
287            CUSTOM_A_STATE
288                .lock()
289                .unwrap()
290                .alloc_layouts
291                .push((pointer as usize, layout));
292        }
293        pointer
294    }
295
296    unsafe fn custom_a_deallocate(pointer: *mut u8, layout: Layout) {
297        CUSTOM_A_STATE
298            .lock()
299            .unwrap()
300            .dealloc_calls
301            .push((pointer as usize, layout));
302        unsafe { dealloc(pointer, layout) };
303    }
304
305    unsafe fn custom_b_allocate(layout: Layout) -> *mut u8 {
306        let pointer = unsafe { alloc(layout) };
307        if !pointer.is_null() {
308            CUSTOM_B_STATE
309                .lock()
310                .unwrap()
311                .alloc_layouts
312                .push((pointer as usize, layout));
313        }
314        pointer
315    }
316
317    unsafe fn custom_b_deallocate(pointer: *mut u8, layout: Layout) {
318        CUSTOM_B_STATE
319            .lock()
320            .unwrap()
321            .dealloc_calls
322            .push((pointer as usize, layout));
323        unsafe { dealloc(pointer, layout) };
324    }
325
326    unsafe fn null_allocate(_layout: Layout) -> *mut u8 {
327        NULL_ALLOC_STATE.lock().unwrap().0 += 1;
328        core::ptr::null_mut()
329    }
330
331    unsafe fn null_deallocate(_pointer: *mut u8, _layout: Layout) {
332        NULL_ALLOC_STATE.lock().unwrap().1 += 1;
333    }
334
335    #[test]
336    fn detects_guard_damage() {
337        let _guard = ALLOCATOR_TEST_LOCK
338            .read()
339            .unwrap_or_else(|poisoned| poisoned.into_inner());
340        for stack in [
341            Stack::new(DEFAULT_MIN_STACK_SIZE),
342            Stack::with_min_size(MIN_STACK_SIZE, MIN_STACK_SIZE),
343        ] {
344            assert!(stack.guard_intact());
345            unsafe { stack.memory.as_ptr().add(GUARD - 1).write(0) };
346            assert!(!stack.guard_intact());
347        }
348    }
349
350    #[test]
351    fn respects_default_and_configurable_minimum_sizes() {
352        let _guard = ALLOCATOR_TEST_LOCK
353            .read()
354            .unwrap_or_else(|poisoned| poisoned.into_inner());
355        assert_eq!(Stack::new(0).usable_size(), DEFAULT_MIN_STACK_SIZE);
356        assert_eq!(
357            Stack::new(MIN_STACK_SIZE).usable_size(),
358            DEFAULT_MIN_STACK_SIZE
359        );
360        assert_eq!(
361            Stack::with_min_size(MIN_STACK_SIZE, MIN_STACK_SIZE).usable_size(),
362            MIN_STACK_SIZE
363        );
364        assert_eq!(Stack::with_min_size(512, 512).usable_size(), MIN_STACK_SIZE);
365        assert_eq!(Stack::with_min_size(1024, 3072).usable_size(), 3072);
366        assert_eq!(
367            Stack::with_min_size(MIN_STACK_SIZE + 1, MIN_STACK_SIZE).usable_size(),
368            MIN_STACK_SIZE + 16
369        );
370    }
371
372    #[test]
373    fn try_with_min_size_reports_failure_instead_of_aborting() {
374        let _guard = ALLOCATOR_TEST_LOCK
375            .read()
376            .unwrap_or_else(|poisoned| poisoned.into_inner());
377        let stack = Stack::try_with_min_size(MIN_STACK_SIZE + 1, MIN_STACK_SIZE).unwrap();
378        assert_eq!(stack.usable_size(), MIN_STACK_SIZE + 16);
379        assert!(stack.guard_intact());
380        // Unrepresentable and unobtainable sizes.
381        assert!(Stack::try_with_min_size(usize::MAX, MIN_STACK_SIZE).is_none());
382        assert!(Stack::try_with_min_size(isize::MAX as usize - 80, MIN_STACK_SIZE).is_none());
383    }
384
385    #[test]
386    fn custom_allocator_allocates_and_matches_deallocator_across_hook_changes() {
387        let _hook = HookGuard::install(StackAllocator::new(custom_a_allocate, custom_a_deallocate));
388        {
389            let mut a = CUSTOM_A_STATE.lock().unwrap();
390            a.alloc_layouts.clear();
391            a.dealloc_calls.clear();
392            let mut b = CUSTOM_B_STATE.lock().unwrap();
393            b.alloc_layouts.clear();
394            b.dealloc_calls.clear();
395        }
396
397        let stack_a = Stack::try_with_min_size(MIN_STACK_SIZE + 1, MIN_STACK_SIZE).unwrap();
398        assert_eq!(stack_a.usable_size(), MIN_STACK_SIZE + 16);
399        assert!(stack_a.guard_intact());
400        let expected_layout_a = Layout::from_size_align(MIN_STACK_SIZE + 16 + GUARD, 16).unwrap();
401        let ptr_a = stack_a.memory.as_ptr() as usize;
402
403        // Swap to a second custom allocator while `stack_a` is still live.
404        unsafe { set_stack_allocator(StackAllocator::new(custom_b_allocate, custom_b_deallocate)) };
405        let stack_b = Stack::new(DEFAULT_MIN_STACK_SIZE);
406        let expected_layout_b =
407            Layout::from_size_align(DEFAULT_MIN_STACK_SIZE + GUARD, 16).unwrap();
408        let ptr_b = stack_b.memory.as_ptr() as usize;
409
410        // Dropping `stack_a` must still invoke `custom_a_deallocate` with the exact pointer and layout.
411        drop(stack_a);
412        {
413            let a = CUSTOM_A_STATE.lock().unwrap();
414            assert_eq!(a.alloc_layouts, [(ptr_a, expected_layout_a)]);
415            assert_eq!(a.dealloc_calls, [(ptr_a, expected_layout_a)]);
416            let b = CUSTOM_B_STATE.lock().unwrap();
417            assert_eq!(b.alloc_layouts, [(ptr_b, expected_layout_b)]);
418            assert!(b.dealloc_calls.is_empty());
419        }
420
421        // Dropping `stack_b` invokes `custom_b_deallocate` with its exact pointer and layout.
422        drop(stack_b);
423        {
424            let b = CUSTOM_B_STATE.lock().unwrap();
425            assert_eq!(b.dealloc_calls, [(ptr_b, expected_layout_b)]);
426        }
427    }
428
429    #[test]
430    fn custom_allocator_returning_null_yields_none_without_deallocating() {
431        let _hook = HookGuard::install(StackAllocator::new(null_allocate, null_deallocate));
432        *NULL_ALLOC_STATE.lock().unwrap() = (0, 0);
433
434        assert!(Stack::try_with_min_size(DEFAULT_MIN_STACK_SIZE, MIN_STACK_SIZE).is_none());
435        let (alloc_calls, dealloc_calls) = *NULL_ALLOC_STATE.lock().unwrap();
436        assert_eq!(alloc_calls, 1);
437        assert_eq!(dealloc_calls, 0);
438    }
439
440    #[test]
441    fn default_allocator_fallback_works_after_reset() {
442        let _hook = HookGuard::install(StackAllocator::new(null_allocate, null_deallocate));
443        *NULL_ALLOC_STATE.lock().unwrap() = (0, 0);
444
445        unsafe { set_stack_allocator(StackAllocator::GLOBAL) };
446        let stack = Stack::try_with_min_size(DEFAULT_MIN_STACK_SIZE, MIN_STACK_SIZE).unwrap();
447        assert_eq!(stack.usable_size(), DEFAULT_MIN_STACK_SIZE);
448        assert!(stack.guard_intact());
449        drop(stack);
450
451        assert_eq!(*NULL_ALLOC_STATE.lock().unwrap(), (0, 0));
452    }
453}