1use alloc::alloc::{alloc, dealloc, handle_alloc_error};
2use core::{alloc::Layout, ptr::NonNull};
3const GUARD: usize = 64;
4pub const DEFAULT_MIN_STACK_SIZE: usize = 4096;
6pub const MIN_STACK_SIZE: usize = 2048;
8const PAINT: u8 = 0xa5;
9
10pub type StackAllocateFn = unsafe fn(Layout) -> *mut u8;
15
16pub type StackDeallocateFn = unsafe fn(*mut u8, Layout);
19
20unsafe fn global_allocate(layout: Layout) -> *mut u8 {
21 unsafe { alloc(layout) }
23}
24
25unsafe fn global_deallocate(pointer: *mut u8, layout: Layout) {
26 unsafe { dealloc(pointer, layout) }
28}
29
30#[derive(Clone, Copy, Debug)]
38pub struct StackAllocator {
39 pub allocate: StackAllocateFn,
41 pub deallocate: StackDeallocateFn,
43}
44
45impl StackAllocator {
46 pub const fn new(allocate: StackAllocateFn, deallocate: StackDeallocateFn) -> Self {
48 Self {
49 allocate,
50 deallocate,
51 }
52 }
53
54 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
82pub 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
116pub struct Stack {
119 memory: NonNull<u8>,
120 layout: Layout,
121 deallocate: StackDeallocateFn,
122}
123impl Stack {
124 pub fn new(size: usize) -> Self {
127 Self::with_min_size(size, DEFAULT_MIN_STACK_SIZE)
128 }
129
130 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 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 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 unsafe { guard_intact_at(self.memory) }
175 }
176 pub(crate) fn guard(&self) -> NonNull<u8> {
178 self.memory
179 }
180}
181
182#[repr(transparent)]
185pub(crate) struct Backing(pub(crate) Stack);
186
187unsafe impl corosensei::stack::Stack for Backing {
198 fn base(&self) -> corosensei::stack::StackPointer {
199 unsafe { corosensei::stack::StackPointer::new_unchecked(self.0.top()) }
202 }
203 fn limit(&self) -> corosensei::stack::StackPointer {
204 unsafe { corosensei::stack::StackPointer::new_unchecked(self.0.guard().as_ptr() as usize) }
206 }
207}
208
209unsafe fn guard_intact_at(guard: NonNull<u8>) -> bool {
212 (0..GUARD).all(|i| unsafe { guard.as_ptr().add(i).read_volatile() == PAINT })
213}
214
215pub(crate) unsafe fn check_guard_at(guard: NonNull<u8>) {
220 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 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 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 unsafe { set_stack_allocator(allocator) };
255 Self { _lock: lock }
256 }
257 }
258
259 impl Drop for HookGuard<'_> {
260 fn drop(&mut self) {
261 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 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 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 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 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}