Skip to main content

stackful/
runtime.rs

1#[path = "fp.rs"]
2mod fp;
3#[path = "stack.rs"]
4mod stack;
5use stack::{Backing, check_guard_at};
6pub use stack::{
7    DEFAULT_MIN_STACK_SIZE, MIN_STACK_SIZE, Stack, StackAllocateFn, StackAllocator,
8    StackDeallocateFn, set_stack_allocator,
9};
10
11use alloc::rc::Rc;
12use core::{
13    cell::{Cell, RefCell, UnsafeCell},
14    future::Future,
15    pin::Pin,
16    ptr::NonNull,
17    task::{Context, Poll, Waker},
18};
19
20type Native = corosensei::Coroutine<(), (), (), Backing>;
21type Yielder = corosensei::Yielder<(), ()>;
22
23/// Bytes corosensei reserves at the top of the stack, beyond the entry, on every target.
24const INITIAL_FRAME: usize = 128;
25/// Usable bytes that must remain for the entry's own frames.
26const MIN_ENTRY_STACK: usize = 1024;
27
28/// Number of coroutine-local storage slots stored inline in each coroutine control block.
29pub const TLS_SLOTS: usize = 4;
30
31/// Failure accessing coroutine-local storage.
32#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33pub enum TlsError {
34    /// Called outside a running coroutine.
35    NotInCoroutine,
36    /// Requested slot index is greater than or equal to [`TLS_SLOTS`].
37    InvalidSlot,
38}
39
40type ErasedFuture = *mut (dyn Future<Output = ()> + 'static);
41#[derive(Clone, Copy)]
42struct Pending {
43    future: ErasedFuture,
44    cancel: bool,
45}
46struct Control {
47    /// Owns the stack and the entry. Only the driver touches it, around each switch.
48    native: UnsafeCell<Native>,
49    /// The stack's painted guard, which `native` owns.
50    guard: NonNull<u8>,
51    #[cfg(all(feature = "crash", target_arch = "xtensa"))]
52    stack_bounds: StackBounds,
53    /// Set when the entry starts; stays valid, on the coroutine stack, until it ends.
54    yielder: Cell<*const Yielder>,
55    pending: Cell<Option<Pending>>,
56    started: Cell<bool>,
57    result: Cell<Option<Result<i32, Cancelled>>>,
58    waker: RefCell<Option<Waker>>,
59    tls: [Cell<usize>; TLS_SLOTS],
60    native_context: Cell<*const ()>,
61}
62/// Maximum number of bare-metal CPU cores tracked by the per-core current-coroutine table.
63pub const MAX_CORES: usize = 8;
64
65/// Platform hook returning the calling CPU core's index in `0..MAX_CORES`.
66pub type CoreIdProvider = fn() -> usize;
67
68#[cfg(any(not(target_os = "linux"), test))]
69fn single_core_id() -> usize {
70    0
71}
72
73#[cfg(any(not(target_os = "linux"), test))]
74struct PerCoreCurrent {
75    provider: Cell<CoreIdProvider>,
76    slots: [Cell<usize>; MAX_CORES],
77}
78
79#[cfg(any(not(target_os = "linux"), test))]
80impl PerCoreCurrent {
81    const fn new() -> Self {
82        Self {
83            provider: Cell::new(single_core_id),
84            slots: [const { Cell::new(0) }; MAX_CORES],
85        }
86    }
87
88    fn core_index(&self) -> usize {
89        let core = (self.provider.get())();
90        assert!(
91            core < MAX_CORES,
92            "stackful core id {core} exceeds MAX_CORES ({MAX_CORES})"
93        );
94        core
95    }
96
97    fn get(&self) -> *const Control {
98        let core = self.core_index();
99        self.slots[core].get() as *const Control
100    }
101
102    fn set(&self, value: *const Control) {
103        let core = self.core_index();
104        self.slots[core].set(value as usize);
105        #[cfg(all(feature = "crash", target_arch = "xtensa"))]
106        {
107            // SAFETY: A non-null current control block belongs to this core.
108            let bounds = unsafe { value.as_ref() }.map(|control| control.stack_bounds);
109            if let Some(slot) = PUBLISHED_STACKS.get(core) {
110                slot.set(bounds);
111            }
112        }
113    }
114
115    fn set_provider(&self, provider: CoreIdProvider) {
116        assert!(
117            self.slots.iter().all(|slot| slot.get() == 0),
118            "cannot change stackful core id provider while a coroutine is active"
119        );
120        self.provider.set(provider);
121    }
122}
123
124#[cfg(target_os = "linux")]
125std::thread_local! { static CURRENT: Cell<*const Control> = const { Cell::new(core::ptr::null()) }; }
126#[cfg(target_os = "linux")]
127fn current() -> *const Control {
128    CURRENT.with(Cell::get)
129}
130#[cfg(target_os = "linux")]
131fn set_current(value: *const Control) {
132    CURRENT.with(|c| c.set(value));
133}
134
135#[cfg(not(target_os = "linux"))]
136static CURRENT: critical_section::Mutex<PerCoreCurrent> =
137    critical_section::Mutex::new(PerCoreCurrent::new());
138#[cfg(not(target_os = "linux"))]
139fn current() -> *const Control {
140    critical_section::with(|cs| CURRENT.borrow(cs).get())
141}
142#[cfg(not(target_os = "linux"))]
143fn set_current(value: *const Control) {
144    critical_section::with(|cs| CURRENT.borrow(cs).set(value));
145}
146
147/// Address bounds of the usable coroutine stack.
148#[cfg(all(feature = "crash", target_arch = "xtensa"))]
149#[derive(Clone, Copy)]
150pub struct StackBounds {
151    pub start: usize,
152    pub end: usize,
153}
154
155#[cfg(all(feature = "crash", target_arch = "xtensa"))]
156use core::sync::atomic::{AtomicUsize, Ordering};
157
158#[cfg(all(feature = "crash", target_arch = "xtensa"))]
159struct PublishedStack {
160    start: AtomicUsize,
161    end: AtomicUsize,
162}
163
164#[cfg(all(feature = "crash", target_arch = "xtensa"))]
165impl PublishedStack {
166    fn set(&self, bounds: Option<StackBounds>) {
167        self.end.store(0, Ordering::SeqCst);
168        if let Some(bounds) = bounds {
169            self.start.store(bounds.start, Ordering::Relaxed);
170            self.end.store(bounds.end, Ordering::SeqCst);
171        }
172    }
173}
174
175#[cfg(all(feature = "crash", target_arch = "xtensa"))]
176static PUBLISHED_STACKS: [PublishedStack; 2] = [const {
177    PublishedStack {
178        start: AtomicUsize::new(0),
179        end: AtomicUsize::new(0),
180    }
181}; 2];
182
183/// Get the bounds published by the calling core without taking a lock.
184/// Use the captured stack pointer to check whether the switch already occurred.
185#[cfg(all(feature = "crash", target_arch = "xtensa"))]
186pub fn current_stack_bounds(core: usize) -> Option<StackBounds> {
187    let slot = PUBLISHED_STACKS.get(core)?;
188    let end = slot.end.load(Ordering::SeqCst);
189    (end != 0).then(|| StackBounds {
190        start: slot.start.load(Ordering::Relaxed),
191        end,
192    })
193}
194
195/// Register the platform hook that identifies the calling CPU core on bare metal.
196///
197/// By default, bare-metal targets assume a single core (index `0`). Multi-core bare-metal
198/// firmware (such as dual-core ESP32-S3 or ESP32-P4) must register a provider once at
199/// start-up before any coroutine runs on a secondary core.
200///
201/// On Linux each OS thread already has its own thread-local current-coroutine pointer, so
202/// this function is a no-op there.
203///
204/// Panics on bare metal if any coroutine is currently active when called.
205///
206/// # Safety
207/// `provider` must return a unique index in `0..MAX_CORES` for each physical CPU core that
208/// can execute concurrently, and must be safe to call inside a `critical_section` without
209/// blocking, allocating, or panicking on valid cores.
210pub unsafe fn set_core_id_provider(provider: CoreIdProvider) {
211    #[cfg(not(target_os = "linux"))]
212    critical_section::with(|cs| CURRENT.borrow(cs).set_provider(provider));
213    #[cfg(target_os = "linux")]
214    let _ = provider;
215}
216
217/// A native coroutine. Neither Send nor Sync: poll it on its creating executor thread.
218pub struct Coroutine {
219    control: Rc<Control>,
220}
221/// The driver was dropped before completion: the coroutine was cancelled, and its suspended
222/// frames were discarded without running anything on them.
223#[derive(Clone, Copy, Debug, PartialEq, Eq)]
224pub struct Cancelled;
225/// One completion observer, sharing the coroutine's control allocation.
226pub struct JoinHandle {
227    control: Rc<Control>,
228}
229
230impl Coroutine {
231    /// Create a coroutine, allocating only its shared control block.
232    ///
233    /// # Safety
234    /// The stack must accommodate the entry and all callees, including interrupt frames
235    /// if the platform uses the same SP. Canary checks cannot prevent memory corruption.
236    /// Entry must never unwind. On bare metal, all coroutines must run on a single core
237    /// and must never be entered or suspended from an interrupt. Do not migrate a live
238    /// coroutine or its handles to another OS thread, including via foreign code.
239    ///
240    /// Dropping the coroutine after it started and before it finished cancels it: the
241    /// suspended frames are discarded and the stack is freed, without running a destructor
242    /// on them (see [`Cancelled`]). The entry and everything it calls must therefore not
243    /// leave an object that owns a resource (an open file, an allocation, a lock guard)
244    /// only in a frame across a suspension, because nothing would ever release it: keep
245    /// it in a place the host owns and releases itself. A future passed to
246    /// [`suspend_on`] counts as such a place only if it is passed to
247    /// [`suspend_on_cancellable`], which the cancellation drops in place. Nothing outside
248    /// the coroutine may keep a pointer into its stack beyond the call that is suspended:
249    /// the stack is freed and reused once the coroutine is dropped.
250    ///
251    /// On bare metal, the default current-coroutine slot assumes a single core (`0`).
252    /// Multi-core firmware must register a per-core ID hook with [`set_core_id_provider`]
253    /// before starting coroutines on secondary cores; without one, another core calling
254    /// an API that reaches [`suspend_on`] (the native application ABI or synchronous VFS
255    /// files and directories) while a coroutine is live would see that coroutine as its
256    /// own and switch onto its stack.
257    pub unsafe fn new<F: FnOnce() -> i32 + 'static>(stack: Stack, entry: F) -> Self {
258        // The entry and corosensei's initial frame sit at the top of the stack.
259        assert!(
260            stack.usable_size()
261                >= size_of::<F>() + align_of::<F>() + INITIAL_FRAME + MIN_ENTRY_STACK,
262            "entry leaves too little stack"
263        );
264        let guard = stack.guard();
265        #[cfg(all(feature = "crash", target_arch = "xtensa"))]
266        let stack_bounds = StackBounds {
267            start: stack.top() - stack.usable_size(),
268            end: stack.top(),
269        };
270        let native = Native::with_stack(Backing(stack), move |yielder, ()| {
271            // SAFETY: the driver set the current coroutine before entering.
272            let control = unsafe { &*current() };
273            control.yielder.set(yielder);
274            fp::Environment::INITIAL.write();
275            let status = entry();
276            // SAFETY: this is the running coroutine's control block.
277            unsafe { finish(control, status) }
278        });
279        Self {
280            control: Rc::new(Control {
281                native: UnsafeCell::new(native),
282                guard,
283                #[cfg(all(feature = "crash", target_arch = "xtensa"))]
284                stack_bounds,
285                yielder: Cell::new(core::ptr::null()),
286                pending: Cell::new(None),
287                started: Cell::new(false),
288                result: Cell::new(None),
289                waker: RefCell::new(None),
290                tls: [const { Cell::new(0) }; TLS_SLOTS],
291                native_context: Cell::new(core::ptr::null()),
292            }),
293        }
294    }
295    /// Install the native ABI's private context for this coroutine.
296    /// # Safety
297    /// A non-null value must identify a live native ABI context for each poll.
298    pub unsafe fn set_native_context(&mut self, value: *const ()) {
299        self.control.native_context.set(value);
300    }
301
302    /// Create the sole join observer. Multiple observers are rejected to bound waker storage.
303    pub fn join_handle(&self) -> JoinHandle {
304        // Rc count also includes an earlier observer, if any.
305        assert_eq!(
306            Rc::strong_count(&self.control),
307            1,
308            "join handle already exists"
309        );
310        JoinHandle {
311            control: self.control.clone(),
312        }
313    }
314    /// Poll the suspended operation with the executor's real waker, then resume native code.
315    /// A coroutine that was [stopped](Self::stop) stays pending for good.
316    pub fn resume(&mut self, cx: &mut Context<'_>) -> Poll<i32> {
317        let c = Rc::as_ptr(&self.control);
318        loop {
319            match self.control.result.get() {
320                Some(Ok(result)) => return Poll::Ready(result),
321                Some(Err(Cancelled)) => return Poll::Pending,
322                None => {}
323            }
324            if let Some(Pending { future, .. }) = self.control.pending.get() {
325                // SAFETY: the future remains pinned on the suspended native stack. No
326                // coroutine runs while the driver polls it; it is cleared before resume.
327                if unsafe { Pin::new_unchecked(&mut *future) }
328                    .poll(cx)
329                    .is_pending()
330                {
331                    return Poll::Pending;
332                }
333                self.control.pending.set(None);
334            }
335            self.control.check_guard();
336            let previous = current();
337            set_current(c);
338            self.control.started.set(true);
339            let environment = fp::Environment::read();
340            // SAFETY: the driver has exclusive access to `native`: the coroutine side
341            // reaches only the other fields of the control block, through `current`.
342            unsafe {
343                let native = &mut *self.control.native.get();
344                native.resume(());
345                if matches!(self.control.result.get(), Some(Ok(_))) {
346                    // `finish` left the coroutine suspended for good, abandoning
347                    // its frames as `exit` documents. Nothing on them is dropped.
348                    native.force_reset();
349                }
350            }
351            environment.write();
352            set_current(previous);
353            self.control.check_guard();
354        }
355    }
356}
357impl Future for Coroutine {
358    type Output = i32;
359    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<i32> {
360        self.resume(cx)
361    }
362}
363impl Coroutine {
364    /// Cancel a suspended coroutine for good, but keep its stack until it is dropped.
365    ///
366    /// This does what dropping it would do to its pending operation: an operation passed to
367    /// [`suspend_on_cancellable`] is dropped in place, so it gives back what it holds (a
368    /// lock, a file), and the join observer sees [`Cancelled`]. The frames stay where they
369    /// are and are never resumed: [`Self::resume`] stays pending from now on. A host that
370    /// must let other code run before it can drop the coroutine (another coroutine of the
371    /// same program that still reads its stack, say) stops it first.
372    ///
373    /// Stopping never suspends, even when called from another coroutine: the operation's
374    /// destructor runs as if no coroutine were running, so a wait inside it (closing a file
375    /// it opened, say) blocks the caller as [`task::block_on`] does, and runs to its end.
376    /// Nothing can therefore cancel the caller halfway through a destructor and leave what
377    /// the operation held, or this coroutine, behind.
378    ///
379    /// Stopping a coroutine that has not started, has finished or is already stopped does
380    /// nothing. Do not call it from the coroutine itself.
381    pub fn stop(&mut self) {
382        if !self.control.started.get() || self.control.result.get().is_some() {
383            return;
384        }
385        self.control.result.set(Some(Err(Cancelled)));
386        if let Some(w) = self.control.waker.borrow_mut().take() {
387            w.wake();
388        }
389        // The last suspension checked the guard on the way out, but an overflow in the
390        // frames that suspended can only be seen now: stop before running a destructor on
391        // a stack that may be damaged, as `resume` does.
392        self.control.check_guard();
393        // Opted-in bridge futures can release their state on cancellation, while the stack
394        // they are pinned on is intact.
395        if let Some(Pending {
396            future,
397            cancel: true,
398        }) = self.control.pending.take()
399        {
400            /// Restores the running coroutine, if any, once the destructor has run.
401            struct Restore(*const Control);
402            impl Drop for Restore {
403                fn drop(&mut self) {
404                    set_current(self.0);
405                }
406            }
407            let _restore = Restore(current());
408            set_current(core::ptr::null());
409            // SAFETY: the wrapper is initialized and pinned on the suspended stack. The
410            // coroutine will never resume, so it cannot drop the wrapper again.
411            unsafe { core::ptr::drop_in_place(future) };
412        }
413    }
414}
415impl Drop for Coroutine {
416    fn drop(&mut self) {
417        self.control.native_context.set(core::ptr::null());
418        if self.control.started.get() && !matches!(self.control.result.get(), Some(Ok(_))) {
419            // Cancels it now, or did when it was stopped.
420            self.stop();
421            // SAFETY: the driver is the only user of `native`, and it is being dropped,
422            // so nothing resumes the coroutine again. The frames are discarded, never
423            // unwound: `Coroutine::new` makes the caller keep every owner of a resource
424            // out of them and every pointer to them out of the rest of the system. This
425            // keeps corosensei's own drop, which would try to unwind a suspended
426            // coroutine and abort without its `unwind` feature, from running on them.
427            unsafe { (*self.control.native.get()).force_reset() };
428        }
429    }
430}
431impl Future for JoinHandle {
432    type Output = Result<i32, Cancelled>;
433    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
434        if let Some(result) = self.control.result.get() {
435            Poll::Ready(result)
436        } else {
437            let mut w = self.control.waker.borrow_mut();
438            if w.as_ref().is_none_or(|w| !w.will_wake(cx.waker())) {
439                *w = Some(cx.waker().clone());
440            }
441            Poll::Pending
442        }
443    }
444}
445/// Drive a coroutine as a normal local Embassy future.
446pub async fn drive(coroutine: Coroutine) -> i32 {
447    coroutine.await
448}
449
450/// Whether execution is currently on a native coroutine stack.
451pub fn is_in_coroutine() -> bool {
452    !current().is_null()
453}
454
455/// Await from native code. Outside a coroutine this preserves task::block_on behavior.
456/// No heap allocation occurs here. The future and output stay on the native stack.
457/// Do not call this from a future's poll method: poll methods must return Pending.
458/// Do not call it while holding a critical section: the interrupt mask is not
459/// switched with the stack, so the executor would run with interrupts masked.
460pub fn suspend_on<F: Future>(future: F) -> F::Output {
461    suspend(future, false)
462}
463
464/// Like [`suspend_on`], but drops this future in place if the driver cancels
465/// the coroutine. The future's destructor runs on the executor's stack.
466pub fn suspend_on_cancellable<F: Future>(future: F) -> F::Output {
467    suspend(future, true)
468}
469
470fn suspend<F: Future>(future: F, cancel: bool) -> F::Output {
471    let c = current();
472    if c.is_null() {
473        return task::block_on(future);
474    }
475    let mut output = None;
476    {
477        let mut wrapper = core::pin::pin!(async {
478            output = Some(future.await);
479        });
480        // SAFETY: erased lifetime is bounded by the suspended call frame; resume only
481        // occurs once polling completes. Dropping the driver discards the stack, and runs
482        // this future's destructor only if it was opted in with `suspend_on_cancellable`.
483        let erased: ErasedFuture = unsafe {
484            core::mem::transmute::<*mut dyn Future<Output = ()>, ErasedFuture>(
485                wrapper.as_mut().get_unchecked_mut(),
486            )
487        };
488        unsafe {
489            suspend_pending(
490                c,
491                Pending {
492                    future: erased,
493                    cancel,
494                },
495            )
496        };
497        // End the future's mutable borrow before reading its result.
498    }
499    output.expect("coroutine resumed before future completed")
500}
501
502#[inline(never)]
503unsafe fn suspend_pending(control: *const Control, pending: Pending) {
504    // SAFETY: the caller is on this control's coroutine stack and the pending
505    // future remains pinned until completion or cancellation of that stack.
506    unsafe {
507        (*control).check_guard();
508        (*control).pending.set(Some(pending));
509        let environment = fp::Environment::read();
510        (*(*control).yielder.get()).suspend(());
511        environment.write();
512        (*control).check_guard();
513    }
514}
515
516/// Pointer privately installed by the native ABI; null on other coroutines.
517pub fn native_context() -> *const () {
518    unsafe { current().as_ref() }.map_or(core::ptr::null(), |control| control.native_context.get())
519}
520
521/// Install the native ABI's private context on the running coroutine.
522/// # Safety
523/// Must be in a coroutine. A non-null value must remain a live native ABI
524/// context while execution can access it.
525pub unsafe fn set_native_context(value: *const ()) {
526    if let Some(control) = unsafe { current().as_ref() } {
527        control.native_context.set(value);
528    }
529}
530
531/// Read a coroutine-local storage slot for the currently running coroutine.
532/// Slots start at `0`. No heap allocation occurs.
533/// Returns [`TlsError::InvalidSlot`] if `slot >= TLS_SLOTS`, or
534/// [`TlsError::NotInCoroutine`] outside a running coroutine.
535pub fn tls_get(slot: usize) -> Result<usize, TlsError> {
536    if slot >= TLS_SLOTS {
537        return Err(TlsError::InvalidSlot);
538    }
539    let c = current();
540    if c.is_null() {
541        return Err(TlsError::NotInCoroutine);
542    }
543    // SAFETY: `c` points to the live control block of the currently executing coroutine.
544    let tls = unsafe { &(*c).tls };
545    Ok(tls[slot].get())
546}
547
548/// Write a coroutine-local storage slot for the currently running coroutine.
549/// No heap allocation occurs.
550/// Returns [`TlsError::InvalidSlot`] if `slot >= TLS_SLOTS`, or
551/// [`TlsError::NotInCoroutine`] outside a running coroutine.
552pub fn tls_set(slot: usize, value: usize) -> Result<(), TlsError> {
553    if slot >= TLS_SLOTS {
554        return Err(TlsError::InvalidSlot);
555    }
556    let c = current();
557    if c.is_null() {
558        return Err(TlsError::NotInCoroutine);
559    }
560    // SAFETY: `c` points to the live control block of the currently executing coroutine.
561    let tls = unsafe { &(*c).tls };
562    tls[slot].set(value);
563    Ok(())
564}
565
566impl Control {
567    fn check_guard(&self) {
568        // SAFETY: `native` owns the stack containing the guard for our lifetime.
569        unsafe { check_guard_at(self.guard) };
570    }
571}
572
573/// Publish `status`, wake the join observer and leave the coroutine for good.
574///
575/// # Safety
576/// `c` must be the control block of the running coroutine. Nothing may resume it.
577unsafe fn finish(c: *const Control, status: i32) -> ! {
578    unsafe {
579        (*c).native_context.set(core::ptr::null());
580        (*c).result.set(Some(Ok(status)));
581        let waker = (*c).waker.borrow_mut().take();
582        if let Some(w) = waker {
583            w.wake();
584        }
585        (*c).check_guard();
586        // The driver discards the abandoned coroutine with `force_reset`.
587        (*(*c).yielder.get()).suspend(());
588    }
589    panic!("completed coroutine resumed");
590}
591
592/// End the running coroutine at once with `status`, as if its entry had returned it.
593///
594/// The frames between this call and the entry are abandoned: no destructor runs and
595/// nothing unwinds, like a `longjmp` that never returns. The driver then observes
596/// `status`, and the stack and control block are released as for a normal return.
597/// Panics outside a coroutine.
598///
599/// # Safety
600/// Every object that owns a resource (an allocation, an open file, a lock guard) and
601/// is live in an abandoned frame is leaked. The caller must have released or must
602/// not need such resources, including the entry closure's own captures: move owned
603/// data out of the coroutine stack, or free it before calling. Frames that
604/// borrowed data from the caller's executor side stay valid, as the stack is only
605/// dropped by the driver after this call.
606pub unsafe fn exit(status: i32) -> ! {
607    let c = current();
608    assert!(!c.is_null(), "exit outside a coroutine");
609    unsafe { finish(c, status) }
610}
611
612/// Spawn on the calling task's executor, preserving stack/thread affinity.
613/// The manager additionally allocates its existing task pool, metadata and join signal.
614///
615/// # Safety
616/// Same contract as [`Coroutine::new`]. The manager must map the current task to
617/// its actual executor; registering or moving local Spawners across threads is invalid.
618pub async unsafe fn spawn<F: FnOnce() -> i32 + 'static>(
619    manager: &'static task::Manager,
620    parent: task::TaskIdentifier,
621    name: &str,
622    stack: Stack,
623    entry: F,
624) -> task::Result<(task::JoinHandle<i32>, task::TaskIdentifier)> {
625    unsafe { spawn_with_result(manager, parent, name, stack, entry, core::convert::identity).await }
626}
627
628/// Like [`spawn`], converting the exit status before signaling the task join handle.
629///
630/// # Safety
631/// Same contract as [`spawn`].
632pub async unsafe fn spawn_with_result<F, Map, T>(
633    manager: &'static task::Manager,
634    parent: task::TaskIdentifier,
635    name: &str,
636    stack: Stack,
637    entry: F,
638    map: Map,
639) -> task::Result<(task::JoinHandle<T>, task::TaskIdentifier)>
640where
641    F: FnOnce() -> i32 + 'static,
642    Map: FnOnce(i32) -> T + 'static,
643    T: 'static,
644{
645    unsafe { spawn_with_driver(manager, parent, name, stack, entry, drive, map).await }
646}
647
648/// Like [`spawn_with_result`], with a local future that drives the entry coroutine.
649/// # Safety
650/// Same contract as [`spawn`]. The driver must keep all native execution on the task's
651/// executor and stop it before releasing the resources borrowed by the entry.
652pub async unsafe fn spawn_with_driver<F, Driver, Run, Map, T>(
653    manager: &'static task::Manager,
654    parent: task::TaskIdentifier,
655    name: &str,
656    stack: Stack,
657    entry: F,
658    driver: Run,
659    map: Map,
660) -> task::Result<(task::JoinHandle<T>, task::TaskIdentifier)>
661where
662    F: FnOnce() -> i32 + 'static,
663    Driver: Future<Output = i32> + 'static,
664    Run: FnOnce(Coroutine) -> Driver + 'static,
665    Map: FnOnce(i32) -> T + 'static,
666    T: 'static,
667{
668    let caller = manager.get_current_task_identifier().await;
669    let spawner = manager.get_spawner(caller).await?;
670    let coroutine = unsafe { Coroutine::new(stack, entry) };
671    manager
672        .spawn(parent, name, Some(spawner), move |_| async move {
673            map(driver(coroutine).await)
674        })
675        .await
676}
677
678/// Bytes in the shared control allocation, including the two Rc reference counts.
679pub const fn control_allocation_size() -> usize {
680    core::mem::size_of::<Control>() + 2 * core::mem::size_of::<usize>()
681}
682
683#[cfg(test)]
684mod per_core_tests {
685    use super::*;
686
687    std::thread_local! {
688        static SIMULATED_CORE: Cell<usize> = const { Cell::new(0) };
689    }
690
691    fn simulated_core_id() -> usize {
692        SIMULATED_CORE.with(Cell::get)
693    }
694
695    fn out_of_range_core_id() -> usize {
696        MAX_CORES
697    }
698
699    #[test]
700    fn default_provider_uses_core_zero() {
701        let table = PerCoreCurrent::new();
702        assert!(table.get().is_null());
703        let sentinel = 0x1000usize as *const Control;
704        table.set(sentinel);
705        assert_eq!(table.get(), sentinel);
706        table.set(core::ptr::null());
707        assert!(table.get().is_null());
708    }
709
710    #[test]
711    fn isolates_current_pointer_per_core() {
712        let table = PerCoreCurrent::new();
713        table.set_provider(simulated_core_id);
714
715        let core0_ptr = 0x2000usize as *const Control;
716        let core1_ptr = 0x3000usize as *const Control;
717        let last_core_ptr = 0x4000usize as *const Control;
718
719        SIMULATED_CORE.with(|c| c.set(0));
720        table.set(core0_ptr);
721
722        SIMULATED_CORE.with(|c| c.set(1));
723        assert!(table.get().is_null());
724        table.set(core1_ptr);
725
726        SIMULATED_CORE.with(|c| c.set(MAX_CORES - 1));
727        assert!(table.get().is_null());
728        table.set(last_core_ptr);
729
730        SIMULATED_CORE.with(|c| c.set(0));
731        assert_eq!(table.get(), core0_ptr);
732        SIMULATED_CORE.with(|c| c.set(1));
733        assert_eq!(table.get(), core1_ptr);
734        SIMULATED_CORE.with(|c| c.set(MAX_CORES - 1));
735        assert_eq!(table.get(), last_core_ptr);
736
737        // Clearing all slots allows changing the provider again.
738        table.set(core::ptr::null());
739        SIMULATED_CORE.with(|c| c.set(1));
740        table.set(core::ptr::null());
741        SIMULATED_CORE.with(|c| c.set(0));
742        table.set(core::ptr::null());
743        table.set_provider(single_core_id);
744    }
745
746    #[test]
747    #[should_panic(expected = "while a coroutine is active")]
748    fn rejects_provider_change_while_coroutine_active() {
749        let table = PerCoreCurrent::new();
750        table.set(0x5000usize as *const Control);
751        table.set_provider(simulated_core_id);
752    }
753
754    #[test]
755    #[should_panic(expected = "exceeds MAX_CORES")]
756    fn rejects_out_of_range_core_id() {
757        let table = PerCoreCurrent::new();
758        table.set_provider(out_of_range_core_id);
759        let _ = table.get();
760    }
761}