Skip to main content

vthread_stack/
stack.rs

1//! Guard-page-backed fixed stacks stamped with the identity of their allocation.
2
3use std::{io, num::NonZeroUsize, ptr::NonNull};
4
5use crate::stack_unix;
6
7/// Required stack pointer alignment at call boundaries on both supported targets.
8pub const STACK_ALIGNMENT: usize = 16;
9
10/// One private anonymous mapping whose lowest page is an inaccessible guard.
11///
12/// Stacks grow downward on both supported targets, so [`MappedStack::base`] is the
13/// initial stack pointer and the guard page catches overflow before it can reach a
14/// neighbouring mapping.
15#[derive(Debug)]
16pub struct MappedStack {
17    mapping: NonNull<u8>,
18    mapping_len: usize,
19    guard_len: usize,
20    base: NonZeroUsize,
21    identity: u64,
22}
23
24// SAFETY: the mapping is plain process memory owned exclusively by this value. Only
25// executing on it is carrier-affine, and that is enforced by the non-Send `Fiber`.
26unsafe impl Send for MappedStack {}
27// SAFETY: shared references expose only addresses and sizes, never the memory itself.
28unsafe impl Sync for MappedStack {}
29
30impl MappedStack {
31    /// Maps at least `usable` bytes above one guard page and stamps the allocation.
32    ///
33    /// The usable capacity rounds up to whole pages. The identity is assigned by the
34    /// allocating owner, normally a [`StackPool`](crate::StackPool), and never changes.
35    pub fn new(usable: usize, identity: u64) -> io::Result<Self> {
36        if usable == 0 {
37            return Err(io::Error::new(
38                io::ErrorKind::InvalidInput,
39                "stack capacity must be positive",
40            ));
41        }
42        let page = stack_unix::page_size()?;
43        let usable_len = usable
44            .checked_add(page - 1)
45            .map(|rounded| rounded & !(page - 1))
46            .ok_or_else(overflow)?;
47        let mapping_len = usable_len.checked_add(page).ok_or_else(overflow)?;
48        let mapping = stack_unix::reserve(mapping_len)?;
49        // Owning the mapping from here on releases it on every later failure path.
50        let mut stack = Self {
51            mapping,
52            mapping_len,
53            guard_len: page,
54            base: mapping.addr(),
55            identity,
56        };
57        stack.base = mapping
58            .addr()
59            .get()
60            .checked_add(mapping_len)
61            .and_then(NonZeroUsize::new)
62            .ok_or_else(overflow)?;
63        // SAFETY: the range starts one guard page above the reservation and ends at its
64        // top; both bounds are page aligned and inside the mapping `stack` now owns.
65        unsafe { stack_unix::enable(stack.usable_start(), usable_len) }?;
66        Ok(stack)
67    }
68
69    /// Highest usable address and initial stack pointer, aligned to [`STACK_ALIGNMENT`].
70    pub fn base(&self) -> NonZeroUsize {
71        self.base
72    }
73
74    /// Lowest address of the mapping, including the guard page.
75    pub fn limit(&self) -> NonZeroUsize {
76        self.mapping.addr()
77    }
78
79    /// Bytes of accessible stack above the guard page.
80    pub fn usable_len(&self) -> usize {
81        self.mapping_len - self.guard_len
82    }
83
84    /// Bytes in the inaccessible guard page.
85    pub fn guard_len(&self) -> usize {
86        self.guard_len
87    }
88
89    /// Identity stamped by the allocating owner.
90    pub fn identity(&self) -> u64 {
91        self.identity
92    }
93
94    fn usable_start(&self) -> NonNull<u8> {
95        // SAFETY: the guard page lies inside the mapping, so the offset stays in bounds.
96        unsafe { self.mapping.add(self.guard_len) }
97    }
98}
99
100fn overflow() -> io::Error {
101    io::Error::new(
102        io::ErrorKind::InvalidInput,
103        "stack mapping size overflows the address space",
104    )
105}
106
107impl Drop for MappedStack {
108    fn drop(&mut self) {
109        // SAFETY: this value exclusively owns the whole mapping and is being destroyed.
110        let released = unsafe { stack_unix::release(self.mapping, self.mapping_len) };
111        // A failed unmap cannot be handled or retried, and Drop must never unwind.
112        drop(released);
113    }
114}
115
116#[cfg(test)]
117#[path = "stack_test.rs"]
118mod stack_test;