Skip to main content

abi_application/threads/
runtime.rs

1use super::*;
2use crate::{Process, Status, XilaStartup, registry::Registry, suspend_dynamic};
3use alloc::{alloc::alloc, boxed::Box, vec::Vec};
4use core::{
5    alloc::Layout,
6    cell::{Cell, RefCell, UnsafeCell},
7    future::poll_fn,
8    pin::pin,
9    ptr::{self, NonNull},
10    task::{Poll, Waker},
11};
12use stackful::{Coroutine, Stack};
13
14mod sync;
15pub use sync::*;
16
17const MAIN_THREAD: usize = 1;
18
19struct Local<'group> {
20    group: &'group Group,
21    id: usize,
22    libc: UnsafeCell<ThreadLibc>,
23    values: [Cell<(usize, *mut c_void)>; XILA_THREAD_KEYS_MAX],
24}
25
26impl<'group> Local<'group> {
27    const fn new(group: &'group Group, id: usize) -> Self {
28        Self {
29            group,
30            id,
31            libc: UnsafeCell::new(ThreadLibc {
32                error: 0,
33                strtok_next: ptr::null_mut(),
34                random_state: 1,
35            }),
36            values: [const { Cell::new((0, ptr::null_mut())) }; XILA_THREAD_KEYS_MAX],
37        }
38    }
39
40    /// Allocate a worker's `Local` on the heap, or fail with `OutOfMemory`.
41    fn try_boxed(group: &'group Group, id: usize) -> Result<Box<Self>, Status> {
42        let layout = Layout::new::<Self>();
43        // SAFETY: `Local` is not zero-sized.
44        let memory =
45            NonNull::new(unsafe { alloc(layout) }.cast::<Self>()).ok_or(Status::OutOfMemory)?;
46        // SAFETY: the global allocator returned this block for the layout of `Local`, which
47        // `Box` frees with the same layout.
48        unsafe {
49            memory.write(Self::new(group, id));
50            Ok(Box::from_raw(memory.as_ptr()))
51        }
52    }
53}
54
55struct Worker {
56    id: usize,
57    creator: usize,
58    coroutine: Option<Coroutine>,
59    /// The worker's identifier, TLS values and libc storage, which its native context points
60    /// to. They live in this record, on the heap, and never on the worker's own coroutine
61    /// stack: an overflow there must not reach what `xila_process_exit` relies on (#778).
62    /// Boxed so that its address, which `xila_thread_libc` hands out, survives the
63    /// reallocation of the worker list. Declared after `coroutine`, so a suspended
64    /// coroutine is discarded before it.
65    local: Box<Local<'static>>,
66    result: Option<*mut c_void>,
67    detached: bool,
68    joining: bool,
69}
70
71struct Group {
72    process: Cell<*const Process>,
73    /// The handles the process opened: the host state's registry.
74    registry: Cell<*const Registry>,
75    /// The startup block of the process, for `__xila_current_startup`. One pointer for the
76    /// whole process: main and its workers read the same one.
77    startup: Cell<*const XilaStartup>,
78    workers: RefCell<Vec<Option<Worker>>>,
79    /// Main's coroutine, out of here while it runs. Declared after `workers`, so a
80    /// cancellation drops the workers first, as `shut_down` stops them first.
81    main: RefCell<Option<Coroutine>>,
82    next_thread: Cell<usize>,
83    keys: [Cell<usize>; XILA_THREAD_KEYS_MAX],
84    next_key: Cell<usize>,
85    repoll: Cell<bool>,
86    shutdown_thread: Cell<usize>,
87}
88
89impl Group {
90    const fn new() -> Self {
91        Self {
92            process: Cell::new(ptr::null()),
93            registry: Cell::new(ptr::null()),
94            startup: Cell::new(ptr::null()),
95            workers: RefCell::new(Vec::new()),
96            main: RefCell::new(None),
97            next_thread: Cell::new(MAIN_THREAD + 1),
98            keys: [const { Cell::new(0) }; XILA_THREAD_KEYS_MAX],
99            next_key: Cell::new(XILA_THREAD_KEYS_MAX),
100            repoll: Cell::new(false),
101            shutdown_thread: Cell::new(0),
102        }
103    }
104
105    fn notify(&self) {
106        self.repoll.set(true);
107    }
108
109    fn with_worker<R>(
110        &self,
111        id: usize,
112        f: impl FnOnce(&mut Option<Worker>) -> Result<R, Status>,
113    ) -> Result<R, Status> {
114        let mut workers = self.workers.borrow_mut();
115        let slot = workers
116            .iter_mut()
117            .find(|slot| slot.as_ref().is_some_and(|worker| worker.id == id))
118            .ok_or(Status::NoSuchTask)?;
119        f(slot)
120    }
121
122    /// Only one executor poll drives the group. Use its real waker for each
123    /// child future, including Embassy timers which require an Embassy waker.
124    /// A wake polls the group again. No future wakes just because it is pending.
125    fn poll_workers(&self, waker: &Waker) -> Poll<i32> {
126        let count = self.workers.borrow().len();
127        for index in 0..count {
128            // Release the borrow before resuming arbitrary C (which can spawn).
129            let shutdown_thread = self.shutdown_thread.get();
130            let Some((mut coroutine, local)) = self.workers.borrow_mut()[index]
131                .as_mut()
132                .filter(|worker| shutdown_thread == 0 || shutdown_thread == worker.id)
133                .and_then(|worker| {
134                    let local = ptr::from_ref::<Local<'static>>(&worker.local);
135                    worker.coroutine.take().map(|coroutine| (coroutine, local))
136                })
137            else {
138                continue;
139            };
140            // The record, and so its boxed Local, stays in the list until the worker has
141            // stored its result, which is the last thing it does before it finishes.
142            unsafe { coroutine.set_native_context(local.cast()) };
143            let result = coroutine.resume(&mut core::task::Context::from_waker(waker));
144            unsafe { coroutine.set_native_context(ptr::null()) };
145            let mut workers = self.workers.borrow_mut();
146            let slot = &mut workers[index];
147            if let Some(worker) = slot {
148                if result.is_pending() {
149                    worker.coroutine = Some(coroutine);
150                    continue;
151                }
152                let id = worker.id;
153                if self.shutdown_thread.get() == id {
154                    return result;
155                }
156                if worker.detached {
157                    *slot = None;
158                }
159                // A finished creator can never join its children. Detach them,
160                // and reap any that have already returned.
161                for slot in &mut *workers {
162                    if let Some(child) = slot
163                        && child.creator == id
164                    {
165                        child.detached = true;
166                        if child.result.is_some() {
167                            *slot = None;
168                        }
169                    }
170                }
171                self.notify();
172            }
173        }
174        Poll::Pending
175    }
176
177    /// Begin terminal cleanup on behalf of `caller`: from now on only it runs, and every
178    /// other thread, main included, is stopped (see [`Coroutine::stop`]). A stopped thread's
179    /// cancellable wait is dropped here, so whatever it held, such as the VFS namespace
180    /// lock a path call holds while it waits, is free before the caller's cleanup needs
181    /// it. The stacks stay until the driver drops the coroutines, because the caller may
182    /// still read them (a stream buffer on main's stack, say).
183    ///
184    /// Each coroutine is stopped where it is, in the group: stopping never suspends, so
185    /// nothing runs, and no cancellation can land, while the group is borrowed, and a
186    /// stopped thread stays reachable for the driver, and for a host that drops it, the
187    /// whole time.
188    fn shut_down(&self, caller: usize) {
189        self.shutdown_thread.set(caller);
190        for coroutine in self
191            .workers
192            .borrow_mut()
193            .iter_mut()
194            .flatten()
195            .filter_map(|worker| worker.coroutine.as_mut())
196        {
197            coroutine.stop();
198        }
199        // Main's coroutine is out of the group while main runs, so main never stops itself.
200        if let Some(main) = self.main.borrow_mut().as_mut() {
201            main.stop();
202        }
203    }
204
205    fn key(&self, key: usize) -> Result<&Cell<usize>, Status> {
206        let slot = &self.keys[key % XILA_THREAD_KEYS_MAX];
207        if key == 0 || slot.get() != key {
208            return Err(Status::InvalidArgument);
209        }
210        Ok(slot)
211    }
212}
213
214fn current() -> Result<(&'static Group, &'static Local<'static>), Status> {
215    // The pinned driver owns the Group for the lifetime of every runnable
216    // coroutine. The driver installs the Local of the coroutine it resumes around
217    // that resume: main's in the driver future, a worker's in its record. Neither
218    // is on a coroutine stack. The erased lifetime lets ABI calls suspend, but
219    // references must never escape this group.
220    let local = unsafe { stackful::native_context().cast::<Local<'static>>().as_ref() }
221        .ok_or(Status::Unsupported)?;
222    Ok((local.group, local))
223}
224
225pub(crate) fn bind_process(process: *const Process) {
226    if let Ok((group, _)) = current() {
227        group.process.set(process);
228    }
229}
230
231/// Record where the calling process's handles are registered, for every thread of it.
232pub(crate) fn bind_registry(registry: *const Registry) {
233    if let Ok((group, _)) = current() {
234        group.registry.set(registry);
235    }
236}
237
238/// Record the startup block of the calling thread's process, or clear it with null, and
239/// return the one it replaces. Without a process group, which is the case outside a driven
240/// coroutine, it does nothing and returns null.
241pub(crate) fn bind_startup(startup: *const XilaStartup) -> *const XilaStartup {
242    current().map_or(ptr::null(), |(group, _)| group.startup.replace(startup))
243}
244
245/// The startup block of the calling thread's process, or null outside a bound process.
246/// Concurrent processes on one executor each see their own, because the pointer lives in
247/// the process's group, which the driver installs around every resume.
248pub(crate) fn current_startup() -> *const XilaStartup {
249    current().map_or(ptr::null(), |(group, _)| group.startup.get())
250}
251
252/// The registry of the calling thread's process, once its entry has started.
253///
254/// # Safety
255/// The reference must not be used after the process's host state is released.
256pub(crate) unsafe fn registry<'a>() -> Option<&'a Registry> {
257    let (group, _) = current().ok()?;
258    // SAFETY: the host state outlives every coroutine of the process, as the caller assures.
259    unsafe { group.registry.get().as_ref() }
260}
261
262pub(crate) fn stop_workers() {
263    if let Ok((group, local)) = current() {
264        group.shut_down(local.id);
265    }
266}
267
268/// Begin terminal process cleanup. Only the calling thread may run after
269/// this call, even if cleanup suspends. Spawning new workers is disabled.
270///
271/// The other threads are stopped at once: a cancellable wait one of them is suspended
272/// in (a path call holding the VFS namespace lock, a socket being connected) is dropped
273/// now, so cleanup never waits for what it held. Their stacks stay until the process ends.
274///
275/// A stopped thread that was waiting on a mutex or a condition variable stays in its
276/// queue. Terminal cleanup must therefore only try-lock (`XILA_MUTEX_TRY`): an unlock that
277/// finds a queued waiter hands the mutex to a thread that never runs again, and a blocking
278/// lock behind a stopped owner or waiter never returns, so exit would hang.
279/// # Safety
280/// The caller must complete process exit without waiting for stopped peers.
281/// Stopped coroutines and their pending operations are never resumed.
282pub unsafe extern "C" fn xila_thread_stop_others(process: *const Process) -> Status {
283    status((|| {
284        let (group, local) = current()?;
285        if process.is_null() || group.process.get() != process {
286            return Err(Status::InvalidArgument);
287        }
288        group.shut_down(local.id);
289        Ok(())
290    })())
291}
292
293/// Finish the calling worker with a pointer-sized result. Main must use
294/// process exit or return. The worker's native frames are abandoned.
295/// # Safety
296/// The caller must release resources that would otherwise be leaked when its
297/// frames are abandoned. The result is opaque and must survive worker exit.
298pub unsafe extern "C" fn xila_thread_exit(result: *mut c_void) -> Status {
299    status((|| {
300        let (group, local) = current()?;
301        if local.id == MAIN_THREAD || group.shutdown_thread.get() != 0 {
302            return Err(Status::InvalidState);
303        }
304        group.with_worker(local.id, |slot| {
305            slot.as_mut().ok_or(Status::NoSuchTask)?.result = Some(result);
306            Ok(())
307        })?;
308        crate::exit_coroutine(0);
309    })())
310}
311
312pub(crate) fn prepare_exit(process: *const Process) -> Result<(), Status> {
313    if let Ok((group, local)) = current() {
314        if group.process.get() != process {
315            return Err(Status::InvalidArgument);
316        }
317        group.shut_down(local.id);
318    }
319    Ok(())
320}
321
322/// Drive the process entry and all its workers on the same executor task.
323/// The group and its workers are dropped before this future returns. A suspended
324/// coroutine, main or worker, is cancelled: its frames are discarded and its stack freed.
325/// What the process owns lives in the host state, which the caller releases afterwards.
326pub async fn drive_process(main: Coroutine) -> i32 {
327    let group = Group::new();
328    *group.main.borrow_mut() = Some(main);
329    let local = Local::new(&group, MAIN_THREAD);
330    poll_fn(|cx| {
331        group.repoll.set(false);
332
333        match group.shutdown_thread.get() {
334            0 | MAIN_THREAD => {
335                // Taken out while it runs, like a worker's, and put back if it suspends.
336                let main = group.main.borrow_mut().take();
337                if let Some(mut main) = main {
338                    // Both locals are borrowed by this pinned future.
339                    unsafe { main.set_native_context(ptr::from_ref(&local).cast()) };
340                    let result = main.resume(cx);
341                    unsafe { main.set_native_context(ptr::null()) };
342                    if result.is_ready() {
343                        return result;
344                    }
345                    *group.main.borrow_mut() = Some(main);
346                }
347            }
348            _ => {}
349        }
350        if group.shutdown_thread.get() != MAIN_THREAD {
351            let result = group.poll_workers(cx.waker());
352            if result.is_ready() {
353                return result;
354            }
355        }
356        if group.repoll.get() {
357            cx.waker().wake_by_ref();
358        }
359        Poll::Pending
360    })
361    .await
362}
363
364fn status(result: Result<(), Status>) -> Status {
365    result.map_or_else(|error| error, |()| Status::Ok)
366}
367
368/// Start a coroutine on the current process's executor. Zero stack size uses
369/// 4 KiB on bare metal or 64 KiB on Linux.
370/// # Safety
371/// The process and output must be live. The entry must never unwind or exceed
372/// the requested stack and the argument must remain valid until entry ends.
373pub unsafe extern "C" fn xila_thread_spawn(
374    process: *const Process,
375    stack_size: usize,
376    entry: ThreadEntry,
377    argument: *mut c_void,
378    thread: *mut usize,
379) -> Status {
380    status((|| {
381        let (group, local) = current()?;
382        let entry = entry.ok_or(Status::InvalidArgument)?;
383        if process.is_null() || group.process.get() != process || thread.is_null() {
384            return Err(Status::InvalidArgument);
385        }
386        if group.shutdown_thread.get() != 0 {
387            return Err(Status::InvalidState);
388        }
389        let stack_size = match stack_size {
390            0 if cfg!(target_os = "linux") => XILA_THREAD_STACK_MAX,
391            0 => stackful::DEFAULT_MIN_STACK_SIZE,
392            XILA_THREAD_STACK_MIN..=XILA_THREAD_STACK_MAX => stack_size,
393            _ => return Err(Status::InvalidArgument),
394        };
395
396        let id = group.next_thread.get();
397        let next = id.checked_add(1).ok_or(Status::Overflow)?;
398        let stack = Stack::try_with_min_size(stack_size, XILA_THREAD_STACK_MIN)
399            .ok_or(Status::OutOfMemory)?;
400        let worker_local = Local::try_boxed(group, id)?;
401        let mut workers = group.workers.borrow_mut();
402        let index = if let Some(index) = workers.iter().position(Option::is_none) {
403            index
404        } else {
405            workers.try_reserve(1).map_err(|_| Status::OutOfMemory)?;
406            workers.push(None);
407            workers.len() - 1
408        };
409        // The entry captures only what the program needs to start. The driver installs the
410        // worker's Local, from its record, around each resume.
411        let coroutine = unsafe {
412            Coroutine::new(stack, move || {
413                let result = entry(argument);
414                if let Ok((group, local)) = current() {
415                    let _ = group.with_worker(local.id, |slot| {
416                        slot.as_mut().ok_or(Status::NoSuchTask)?.result = Some(result);
417                        Ok(())
418                    });
419                }
420                0
421            })
422        };
423        workers[index] = Some(Worker {
424            id,
425            creator: local.id,
426            coroutine: Some(coroutine),
427            local: worker_local,
428            result: None,
429            detached: false,
430            joining: false,
431        });
432        group.next_thread.set(next);
433        group.notify();
434        unsafe { thread.write(id) };
435        Ok(())
436    })())
437}
438
439/// Wait for one worker, then reap its result. Joining oneself fails with Deadlock.
440/// # Safety
441/// A non-null result must be writable after the wait.
442pub unsafe extern "C" fn xila_thread_join(thread: usize, result: *mut *mut c_void) -> Status {
443    status((|| {
444        let (group, local) = current()?;
445        if thread == local.id {
446            return Err(Status::Deadlock);
447        }
448        group.with_worker(thread, |slot| {
449            let worker = slot.as_mut().ok_or(Status::NoSuchTask)?;
450            if worker.creator != local.id {
451                return Err(Status::NoChild);
452            }
453            if worker.detached || worker.joining {
454                return Err(Status::InvalidArgument);
455            }
456            worker.joining = true;
457            Ok(())
458        })?;
459        let mut value = Err(Status::NoSuchTask);
460        suspend_dynamic(pin!(poll_fn(|_| {
461            let response = group.with_worker(thread, |slot| {
462                let result = slot.as_ref().and_then(|worker| worker.result);
463                if result.is_some() {
464                    *slot = None;
465                }
466                Ok(result)
467            });
468            if matches!(response, Ok(None)) {
469                Poll::Pending
470            } else {
471                value = response.and_then(|value| value.ok_or(Status::NoSuchTask));
472                Poll::Ready(())
473            }
474        })));
475        let value = value?;
476        if !result.is_null() {
477            unsafe { result.write(value) };
478        }
479        Ok(())
480    })())
481}
482
483/// Detach a worker. Its result is discarded, and it is reaped on return.
484pub extern "C" fn xila_thread_detach(thread: usize) -> Status {
485    status((|| {
486        let (group, _) = current()?;
487        group.with_worker(thread, |slot| {
488            let worker = slot.as_mut().ok_or(Status::NoSuchTask)?;
489            if worker.detached || worker.joining {
490                return Err(Status::InvalidArgument);
491            }
492            worker.detached = true;
493            if worker.result.is_some() {
494                *slot = None;
495            }
496            Ok(())
497        })
498    })())
499}
500
501/// Yield once to the other coroutines on the executor.
502pub extern "C" fn xila_thread_yield() -> Status {
503    if let Err(error) = current() {
504        return error;
505    }
506    crate::yield_once();
507    Status::Ok
508}
509
510/// Read the calling thread's process-local identifier.
511/// # Safety
512/// Output must be aligned and writable.
513pub unsafe extern "C" fn xila_thread_current(thread: *mut usize) -> Status {
514    status((|| {
515        let (_, local) = current()?;
516        if thread.is_null() {
517            return Err(Status::InvalidArgument);
518        }
519        unsafe { thread.write(local.id) };
520        Ok(())
521    })())
522}
523
524/// Report whether the process still has live workers. Finished workers whose
525/// results have not been joined do not count.
526/// # Safety
527/// Output must be aligned and writable.
528pub unsafe extern "C" fn xila_thread_has_workers(live: *mut bool) -> Status {
529    status((|| {
530        let (group, _) = current()?;
531        if live.is_null() {
532            return Err(Status::InvalidArgument);
533        }
534        let workers = group.workers.borrow();
535        let has_workers = workers
536            .iter()
537            .flatten()
538            .any(|worker| worker.result.is_none());
539        unsafe { live.write(has_workers) };
540        Ok(())
541    })())
542}
543
544/// Allocate a process-local TLS key. New keys read as null in all threads.
545/// # Safety
546/// Output must be aligned and writable.
547pub unsafe extern "C" fn xila_thread_key_create(key: *mut usize) -> Status {
548    status((|| {
549        let (group, _) = current()?;
550        if key.is_null() {
551            return Err(Status::InvalidArgument);
552        }
553        let (index, slot) = group
554            .keys
555            .iter()
556            .enumerate()
557            .find(|(_, slot)| slot.get() == 0)
558            .ok_or(Status::OutOfMemory)?;
559        let base = group.next_key.get();
560        group.next_key.set(
561            base.checked_add(XILA_THREAD_KEYS_MAX)
562                .ok_or(Status::Overflow)?,
563        );
564        let value = base + index;
565        slot.set(value);
566        unsafe { key.write(value) };
567        Ok(())
568    })())
569}
570
571/// Invalidate a process-local TLS key without calling destructors.
572pub extern "C" fn xila_thread_key_delete(key: usize) -> Status {
573    status((|| {
574        let (group, _) = current()?;
575        group.key(key)?.set(0);
576        Ok(())
577    })())
578}
579
580/// Read a TLS value from the current coroutine.
581/// # Safety
582/// Output must be aligned and writable.
583pub unsafe extern "C" fn xila_thread_tls_get(key: usize, value: *mut *mut c_void) -> Status {
584    status((|| {
585        let (group, local) = current()?;
586        group.key(key)?;
587        if value.is_null() {
588            return Err(Status::InvalidArgument);
589        }
590        let (stored_key, stored_value) = local.values[key % XILA_THREAD_KEYS_MAX].get();
591        unsafe {
592            value.write(if stored_key == key {
593                stored_value
594            } else {
595                ptr::null_mut()
596            })
597        };
598        Ok(())
599    })())
600}
601
602/// Write a pointer-sized value in the current coroutine. The host never
603/// dereferences or frees it.
604pub extern "C" fn xila_thread_tls_set(key: usize, value: *mut c_void) -> Status {
605    status((|| {
606        let (group, local) = current()?;
607        group.key(key)?;
608        local.values[key % XILA_THREAD_KEYS_MAX].set((key, value));
609        Ok(())
610    })())
611}
612
613/// Read the address of the current coroutine's libc storage.
614/// # Safety
615/// Output must be aligned and writable. The returned pointer is borrowed until
616/// the calling coroutine ends and must only be used by that coroutine.
617pub unsafe extern "C" fn xila_thread_libc(location: *mut *mut ThreadLibc) -> Status {
618    status((|| {
619        let (_, local) = current()?;
620        if location.is_null() {
621            return Err(Status::InvalidArgument);
622        }
623        unsafe { location.write(local.libc.get()) };
624        Ok(())
625    })())
626}
627
628#[cfg(all(test, target_os = "linux"))]
629mod tests {
630    use super::*;
631    use core::{future::Future, task::Context};
632
633    #[test]
634    fn coroutine_tls_survives_yield_and_key_reuse_starts_empty() {
635        let mut id = 99;
636        assert_eq!(unsafe { xila_thread_current(&mut id) }, Status::Unsupported);
637        assert_eq!(id, 99);
638
639        let main = unsafe {
640            Coroutine::new(Stack::new(64 * 1024), || {
641                let mut keys = [0; XILA_THREAD_KEYS_MAX];
642                for key in &mut keys {
643                    assert_eq!(xila_thread_key_create(key), Status::Ok);
644                }
645                let mut extra = 0;
646                assert_eq!(xila_thread_key_create(&mut extra), Status::OutOfMemory);
647                assert_eq!(extra, 0);
648
649                let value = ptr::dangling_mut();
650                assert_eq!(xila_thread_tls_set(keys[0], value), Status::Ok);
651                assert_eq!(xila_thread_yield(), Status::Ok);
652                let mut stored = ptr::null_mut();
653                assert_eq!(xila_thread_tls_get(keys[0], &mut stored), Status::Ok);
654                assert_eq!(stored, value);
655
656                assert_eq!(xila_thread_key_delete(keys[0]), Status::Ok);
657                assert_eq!(xila_thread_key_create(&mut extra), Status::Ok);
658                assert_ne!(extra, keys[0]);
659                assert_eq!(xila_thread_tls_get(extra, &mut stored), Status::Ok);
660                assert!(stored.is_null());
661                17
662            })
663        };
664        let mut driver = pin!(drive_process(main));
665        let mut cx = Context::from_waker(Waker::noop());
666        assert_eq!(driver.as_mut().poll(&mut cx), Poll::Pending);
667        assert_eq!(driver.as_mut().poll(&mut cx), Poll::Ready(17));
668    }
669
670    // Keep the probes bounded so a missed wake is a test failure.
671    fn run_probe(main: impl FnOnce() -> i32 + 'static) -> i32 {
672        let main = unsafe { Coroutine::new(Stack::new(64 * 1024), main) };
673        let mut driver = pin!(drive_process(main));
674        let mut cx = Context::from_waker(Waker::noop());
675        for _ in 0..200 {
676            if let Poll::Ready(status) = driver.as_mut().poll(&mut cx) {
677                return status;
678            }
679        }
680        panic!("process did not finish");
681    }
682
683    struct BroadcastProbe {
684        mutex: Mutex,
685        condition: Condition,
686        woken: usize,
687    }
688
689    unsafe extern "C" fn probe_waiter(argument: *mut c_void) -> *mut c_void {
690        let probe = argument.cast::<BroadcastProbe>();
691        unsafe {
692            let mutex = &raw mut (*probe).mutex;
693            let condition = &raw mut (*probe).condition;
694            assert_eq!(xila_mutex_lock(mutex, 0), Status::Ok);
695            assert_eq!(
696                xila_condition_wait(condition, mutex, 0, ptr::null()),
697                Status::Ok
698            );
699            (*probe).woken += 1;
700            assert_eq!(xila_mutex_unlock(mutex), Status::Ok);
701        }
702        ptr::null_mut()
703    }
704
705    #[test]
706    fn probe_destroy_after_broadcast() {
707        for reinit in [false, true] {
708            let result = run_probe(move || unsafe {
709                let process = ptr::dangling::<Process>();
710                bind_process(process);
711                let mut probe = BroadcastProbe {
712                    mutex: core::mem::zeroed(),
713                    condition: core::mem::zeroed(),
714                    woken: 0,
715                };
716                let probe = &raw mut probe;
717                let mutex = &raw mut (*probe).mutex;
718                let condition = &raw mut (*probe).condition;
719                let mut ids = [0; 3];
720                for id in &mut ids {
721                    assert_eq!(
722                        xila_thread_spawn(process, 0, Some(probe_waiter), probe.cast(), id),
723                        Status::Ok
724                    );
725                }
726                assert_eq!(xila_thread_yield(), Status::Ok);
727                assert_eq!(xila_mutex_lock(mutex, 0), Status::Ok);
728                assert_eq!(xila_condition_notify(condition, true), Status::Ok);
729                assert_eq!(xila_mutex_unlock(mutex), Status::Ok);
730                assert_eq!(xila_condition_destroy(condition), Status::Ok);
731                assert_eq!((*probe).woken, 0);
732                if reinit {
733                    assert_eq!(xila_condition_init(condition), Status::Ok);
734                }
735                for id in ids {
736                    assert_eq!(xila_thread_join(id, ptr::null_mut()), Status::Ok);
737                }
738                (*probe).woken as i32
739            });
740            assert_eq!(result, 3);
741        }
742    }
743
744    struct StarvationProbe {
745        mutex: Mutex,
746        iterations: usize,
747    }
748
749    unsafe extern "C" fn hog(argument: *mut c_void) -> *mut c_void {
750        let probe = argument.cast::<StarvationProbe>();
751        unsafe {
752            let mutex = &raw mut (*probe).mutex;
753            for _ in 0..50 {
754                assert_eq!(xila_mutex_lock(mutex, 0), Status::Ok);
755                // Suspend while holding the mutex, as stdio can during a write.
756                assert_eq!(xila_thread_yield(), Status::Ok);
757                (*probe).iterations += 1;
758                assert_eq!(xila_mutex_unlock(mutex), Status::Ok);
759            }
760        }
761        ptr::null_mut()
762    }
763
764    #[test]
765    fn probe_mutex_starvation() {
766        let seen = run_probe(|| unsafe {
767            let process = ptr::dangling::<Process>();
768            bind_process(process);
769            let mut probe = StarvationProbe {
770                mutex: core::mem::zeroed(),
771                iterations: 0,
772            };
773            let probe = &raw mut probe;
774            let mutex = &raw mut (*probe).mutex;
775            let mut id = 0;
776            assert_eq!(
777                xila_thread_spawn(process, 0, Some(hog), probe.cast(), &mut id),
778                Status::Ok
779            );
780            assert_eq!(xila_thread_yield(), Status::Ok);
781            assert_eq!(xila_mutex_lock(mutex, 0), Status::Ok);
782            let seen = (*probe).iterations;
783            assert_eq!(xila_mutex_unlock(mutex), Status::Ok);
784            assert_eq!(xila_thread_join(id, ptr::null_mut()), Status::Ok);
785            seen as i32
786        });
787        assert!(
788            (1..=2).contains(&seen),
789            "main acquired after {seen} iterations"
790        );
791    }
792
793    /// Whether the calling worker's native context, and the libc storage it hands out, are
794    /// the `Local` its record owns, rather than something on its own coroutine stack.
795    fn context_in_record() -> bool {
796        let context = stackful::native_context();
797        let Ok((group, local)) = current() else {
798            return false;
799        };
800        let mut libc = ptr::null_mut();
801        if unsafe { xila_thread_libc(&mut libc) } != Status::Ok {
802            return false;
803        }
804        group
805            .with_worker(local.id, |slot| {
806                let worker = slot.as_ref().ok_or(Status::NoSuchTask)?;
807                let record = ptr::from_ref::<Local<'static>>(&worker.local);
808                Ok(ptr::eq(record.cast(), context)
809                    && ptr::eq(local, record)
810                    && ptr::eq(libc, local.libc.get()))
811            })
812            .unwrap_or(false)
813    }
814
815    unsafe extern "C" fn local_probe(_: *mut c_void) -> *mut c_void {
816        let mut libc = ptr::null_mut();
817        assert_eq!(unsafe { xila_thread_libc(&mut libc) }, Status::Ok);
818        let before = context_in_record();
819        // Main fills the worker list while this worker is suspended, which moves the
820        // records: the Local, and the libc storage handed out above, must not move.
821        assert_eq!(xila_thread_yield(), Status::Ok);
822        let mut moved = ptr::null_mut();
823        assert_eq!(unsafe { xila_thread_libc(&mut moved) }, Status::Ok);
824        let after = context_in_record() && ptr::eq(libc, moved);
825        ptr::without_provenance_mut(usize::from(before) | usize::from(after) << 1)
826    }
827
828    unsafe extern "C" fn idle(_: *mut c_void) -> *mut c_void {
829        ptr::null_mut()
830    }
831
832    /// A worker's Local lives in the record its group owns, not on the worker's coroutine
833    /// stack, so an overflow there cannot reach what `xila_process_exit` reads through the
834    /// native context (#778).
835    #[test]
836    fn worker_local_stays_off_the_worker_stack() {
837        let result = run_probe(|| unsafe {
838            let process = ptr::dangling::<Process>();
839            bind_process(process);
840            let mut probe = 0;
841            assert_eq!(
842                xila_thread_spawn(process, 0, Some(local_probe), ptr::null_mut(), &mut probe),
843                Status::Ok
844            );
845            // Let the probe run up to its yield.
846            assert_eq!(xila_thread_yield(), Status::Ok);
847            let mut fillers = [0; 8];
848            for id in &mut fillers {
849                assert_eq!(
850                    xila_thread_spawn(process, 0, Some(idle), ptr::null_mut(), id),
851                    Status::Ok
852                );
853            }
854            let mut checks = ptr::null_mut();
855            assert_eq!(xila_thread_join(probe, &mut checks), Status::Ok);
856            for id in fillers {
857                assert_eq!(xila_thread_join(id, ptr::null_mut()), Status::Ok);
858            }
859            checks.addr() as i32
860        });
861        assert_eq!(result, 3);
862    }
863
864    unsafe extern "C" fn stop_from_worker(argument: *mut c_void) -> *mut c_void {
865        assert_eq!(
866            unsafe { xila_thread_stop_others(argument.cast()) },
867            Status::Ok
868        );
869        // The sole cleanup thread must resume even if its flush suspends.
870        assert_eq!(xila_thread_yield(), Status::Ok);
871        crate::exit_coroutine(37);
872    }
873
874    unsafe extern "C" fn stopped_worker(_: *mut c_void) -> *mut c_void {
875        panic!("stopped worker resumed");
876    }
877
878    #[test]
879    fn only_shutdown_caller_can_resume() {
880        let result = run_probe(|| unsafe {
881            let process = ptr::dangling_mut::<Process>();
882            bind_process(process);
883            let mut id = 0;
884            assert_eq!(
885                xila_thread_spawn(process, 0, Some(stop_from_worker), process.cast(), &mut id),
886                Status::Ok
887            );
888            assert_eq!(
889                xila_thread_spawn(process, 0, Some(stopped_worker), ptr::null_mut(), &mut id),
890                Status::Ok
891            );
892            assert_eq!(xila_thread_yield(), Status::Ok);
893            panic!("main resumed after a worker started shutdown");
894        });
895        assert_eq!(result, 37);
896    }
897}