Skip to main content

vthread_stack/
scoped.rs

1//! Borrowed fibers whose executable state is revoked before their lexical scope exits.
2
3use crate::{
4    Fiber, FiberLease, MappedStack,
5    panic_payload::{self, CapturedPanic},
6};
7use std::{
8    cell::{Cell, RefCell},
9    io,
10    marker::PhantomData,
11    rc::Rc,
12};
13
14/// Lexical ownership for a bounded set of borrowed, non-Send stacks.
15pub struct FiberScope<'scope, 'env: 'scope> {
16    registry: Rc<Registry>,
17    scope: PhantomData<&'scope mut &'scope ()>,
18    env: PhantomData<&'env mut &'env ()>,
19}
20
21struct Registry {
22    fibers: RefCell<Vec<FiberLease>>,
23    capacity: usize,
24    closed: Cell<bool>,
25}
26
27struct ScopeGuard(Rc<Registry>);
28
29impl<'scope, 'env> FiberScope<'scope, 'env> {
30    /// Creates a local stack. The scope retains ownership even if its lease is forgotten.
31    pub fn spawn(
32        &'scope self,
33        stack: MappedStack,
34        entry: impl FnOnce() + 'scope,
35    ) -> io::Result<FiberLease> {
36        let mut fibers = self.registry.fibers.borrow_mut();
37        fibers.retain(FiberLease::live);
38        if self.registry.closed.get() || fibers.len() >= self.registry.capacity {
39            return Err(io::Error::other("borrowed fiber scope closed or full"));
40        }
41        // SAFETY: entry lives for scope; the non-forgettable outer scope owns a lease
42        // and revokes every stack before returning, including on unwind or leaked leases.
43        let fiber = unsafe { Fiber::borrowed(stack, entry) };
44        let lease = FiberLease::new(fiber);
45        fibers.push(lease.clone());
46        Ok(lease)
47    }
48}
49
50impl ScopeGuard {
51    fn drain(&self) -> Option<CapturedPanic> {
52        self.0.closed.set(true);
53        let fibers = self.0.fibers.take();
54        let mut failure = None;
55        for fiber in fibers {
56            for _ in 0..2 {
57                if !fiber.live() {
58                    break;
59                }
60                if let Err(payload) =
61                    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| fiber.reclaim()))
62                {
63                    panic_payload::retain(&mut failure, payload);
64                }
65            }
66            // A borrowed executable stack must never survive the lexical environment.
67            // A mount that fails twice has no safe recovery path; do not leak the fiber.
68            if fiber.live() {
69                std::process::abort();
70            }
71        }
72        failure
73    }
74}
75
76impl Drop for ScopeGuard {
77    fn drop(&mut self) {
78        self.drain();
79    }
80}
81
82/// Runs a lexical borrowed-stack owner; leaked leases are inert after this returns.
83pub fn fiber_scope<'env, R>(
84    capacity: usize,
85    body: impl for<'scope> FnOnce(&'scope FiberScope<'scope, 'env>) -> R,
86) -> R {
87    let registry = Rc::new(Registry {
88        fibers: RefCell::new(Vec::new()),
89        capacity,
90        closed: Cell::new(false),
91    });
92    let scope = FiberScope {
93        registry,
94        scope: PhantomData,
95        env: PhantomData,
96    };
97    // Declare the guard last: children may borrow the scope itself, so their
98    // reclamation must precede destruction of the scope value on every exit path.
99    let guard = ScopeGuard(Rc::clone(&scope.registry));
100    // Reclaim outside an active body unwind so a cleanup panic cannot double-unwind.
101    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| body(&scope)));
102    let cleanup = guard.drain();
103    match result {
104        Err(payload) => {
105            // The stack engine may be unwinding this scope with its private forced-unwind
106            // token. Preserve the payload exactly; cleanup payloads were captured above.
107            drop(cleanup);
108            std::panic::resume_unwind(payload)
109        }
110        Ok(value) => {
111            if let Some(failure) = cleanup {
112                std::panic::resume_unwind(Box::new(failure));
113            }
114            value
115        }
116    }
117}
118
119#[cfg(test)]
120#[path = "scoped_test.rs"]
121mod scoped_test;