oscall 0.1.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! Creating threads where the system's own function makes one the whole
//! process accepts: macOS (`pthread_create`) and Windows (`CreateThread`).
//! Each re-exports this as part of its extension module.

use core::ffi::c_void;
use core::sync::atomic::{AtomicU32, Ordering};

use crate::sys;
use crate::{ErrorKind, Result};

/// The stack of a thread that asks for none: what `std` gives.
const DEFAULT_STACK_SIZE: usize = 2 << 20;

/// `started`: the thread has read its [`Start`], and is waking its creator.
const STARTED: u32 = 1;
/// `started`: the thread will not touch its [`Start`] again.
const DONE: u32 = 2;

/// What a new thread is given, on the stack of the one that creates it,
/// which waits until `started` says it has been read.
struct Start<'a> {
    f: fn(usize),
    arg: usize,
    name: Option<&'a str>,
    id: AtomicU32,
    id_high: AtomicU32,
    started: AtomicU32,
}

/// What every thread created here runs, called by the backend's own entry
/// point.
///
/// # Safety
///
/// `start` points to a [`Start`] whose owner waits for `started`.
pub(crate) unsafe fn thread_main(start: *mut c_void) {
    let (f, arg) = {
        // SAFETY: the caller's contract: the creator does not return, and
        // so keeps the structure, until `started` is set below.
        let start = unsafe { &*start.cast_const().cast::<Start<'_>>() };
        if let Some(name) = start.name {
            // A thread that could not be named runs all the same.
            let _ = crate::thread::set_name(name);
        }
        let id = crate::thread::id();
        start.id.store(id as u32, Ordering::Relaxed);
        start.id_high.store((id >> 32) as u32, Ordering::Relaxed);
        let call = (start.f, start.arg);
        start.started.store(STARTED, Ordering::Release);
        sys::sync::wake(&start.started, true);
        // The last use of the structure: the creator leaves once it reads
        // this, and its stack with it.
        start.started.store(DONE, Ordering::Release);
        call
    };
    f(arg);
}

/// The settings of a thread to create.
///
/// ```
/// # #[cfg(any(target_os = "macos", windows))] {
/// # #[cfg(target_os = "macos")] use oscall::thread::macos as system;
/// # #[cfg(windows)] use oscall::thread::windows as system;
/// use core::sync::atomic::{AtomicUsize, Ordering};
///
/// static SEEN: AtomicUsize = AtomicUsize::new(0);
///
/// let thread = system::Builder::new()
///     .name("worker")
///     .stack_size(256 * 1024)
///     .spawn_fn(|value| SEEN.store(value, Ordering::Release), 7)?;
/// thread.join()?;
/// assert_eq!(SEEN.load(Ordering::Acquire), 7);
/// # }
/// # Ok::<(), oscall::Error>(())
/// ```
#[derive(Clone, Debug, Default)]
#[must_use]
pub struct Builder<'a> {
    stack_size: usize,
    name: Option<&'a str>,
}

impl<'a> Builder<'a> {
    /// A thread with no name and a stack of 2 MiB.
    #[inline]
    pub const fn new() -> Self {
        Self {
            stack_size: 0,
            name: None,
        }
    }

    /// The size of the thread's stack, in bytes: 2 MiB unless set, which is
    /// also what `std` gives. The system rounds it up to whole pages, and
    /// to the least it accepts (16 KiB on macOS).
    ///
    /// The address space is reserved at once and the memory used as the
    /// stack grows.
    #[inline]
    pub const fn stack_size(mut self, size: usize) -> Self {
        self.stack_size = size;
        self
    }

    /// The name of the thread, as [`set_name`](crate::thread::set_name)
    /// sets it, which the thread does itself before it runs its function.
    /// A name the system refuses leaves the thread without one.
    #[inline]
    pub const fn name(mut self, name: &'a str) -> Self {
        self.name = Some(name);
        self
    }

    /// Creates a thread that calls `f(arg)`, and returns when the thread
    /// has started. Nothing is allocated.
    ///
    /// `arg` is whatever the function makes of it: a number, an index, or
    /// an address, which only `unsafe` code can turn back into a
    /// reference.
    ///
    /// Fails with [`InvalidInput`](ErrorKind::InvalidInput) if the name
    /// has a NUL character in it, and with what the system says when it
    /// cannot make a thread: [`WouldBlock`](ErrorKind::WouldBlock) for a
    /// limit on their number on macOS,
    /// [`OutOfMemory`](ErrorKind::OutOfMemory) for a stack that cannot be
    /// reserved.
    ///
    /// **A panic in `f` ends the process** (it aborts): there is no `std`
    /// here to catch it at the bottom of the thread, and it cannot unwind
    /// into the system.
    pub fn spawn_fn(self, f: fn(usize), arg: usize) -> Result<Thread> {
        if self.name.is_some_and(|name| name.as_bytes().contains(&0)) {
            return Err(ErrorKind::InvalidInput.into());
        }
        let stack_size = match self.stack_size {
            0 => DEFAULT_STACK_SIZE,
            size => size,
        };
        let start = Start {
            f,
            arg,
            name: self.name,
            id: AtomicU32::new(0),
            id_high: AtomicU32::new(0),
            started: AtomicU32::new(0),
        };
        // SAFETY: the thread is given a `Start`, and this function does
        // not return before the thread has said that it is done with it.
        let imp = unsafe { sys::thread::spawn(stack_size, (&raw const start).cast_mut().cast()) }?;
        while start.started.load(Ordering::Acquire) == 0 {
            // Whatever the wait says, the thread still reads `start`: only
            // the value ends this loop.
            let _ = sys::sync::wait(&start.started, 0, None);
        }
        // The thread is between two stores, with a wake-up in between
        // that must not outlive what it wakes on.
        while start.started.load(Ordering::Acquire) != DONE {
            sys::thread::yield_now();
        }
        let id = u64::from(start.id.load(Ordering::Relaxed))
            | u64::from(start.id_high.load(Ordering::Relaxed)) << 32;
        Ok(Thread { imp, id })
    }

    /// Creates a thread that calls `f`, and returns when the thread has
    /// started. What `f` returns is what [`JoinHandle::join`] returns.
    ///
    /// The errors are those of [`spawn_fn`](Self::spawn_fn), and so is the
    /// outcome of a panic: **the process aborts**, where a thread of `std`
    /// would hand the panic to whoever joins it.
    #[cfg(feature = "alloc")]
    pub fn spawn<F, T>(self, f: F) -> Result<JoinHandle<T>>
    where
        F: FnOnce() -> T + Send + 'static,
        T: Send + 'static,
    {
        use alloc::boxed::Box;
        use alloc::sync::Arc;

        fn run<F: FnOnce()>(main: usize) {
            // SAFETY: `main` is the box `spawn` leaked for this thread,
            // which runs once.
            let main = unsafe { Box::from_raw(main as *mut F) };
            main();
        }
        fn runner<F: FnOnce()>(_: &F) -> fn(usize) {
            run::<F>
        }

        let packet = Arc::new(Packet(core::cell::UnsafeCell::new(None)));
        let theirs = packet.clone();
        let main = move || {
            let value = f();
            // SAFETY: nothing reads the slot before the thread is joined,
            // and nothing else writes it.
            unsafe { *theirs.0.get() = Some(value) };
        };
        let run = runner(&main);
        let main = Box::into_raw(Box::new(main));
        match self.spawn_fn(run, main as usize) {
            Ok(thread) => Ok(JoinHandle { thread, packet }),
            Err(error) => {
                // SAFETY: no thread was created: the box is still ours.
                drop(unsafe { Box::from_raw(main) });
                Err(error)
            }
        }
    }
}

/// Creates a thread that calls `f(arg)`: [`Builder::spawn_fn`] with the
/// default settings.
pub fn spawn_fn(f: fn(usize), arg: usize) -> Result<Thread> {
    Builder::new().spawn_fn(f, arg)
}

/// Creates a thread that calls `f`: [`Builder::spawn`] with the default
/// settings.
///
/// ```
/// # #[cfg(any(target_os = "macos", windows))] {
/// # #[cfg(target_os = "macos")] use oscall::thread::macos as system;
/// # #[cfg(windows)] use oscall::thread::windows as system;
/// let numbers = vec![1, 2, 3];
/// let thread = system::spawn(move || numbers.iter().sum::<i32>())?;
/// assert_eq!(thread.join()?, 6);
/// # }
/// # Ok::<(), oscall::Error>(())
/// ```
#[cfg(feature = "alloc")]
pub fn spawn<F, T>(f: F) -> Result<JoinHandle<T>>
where
    F: FnOnce() -> T + Send + 'static,
    T: Send + 'static,
{
    Builder::new().spawn(f)
}

/// A thread created by [`spawn_fn`].
///
/// Dropping it detaches the thread, which then runs to its end on its
/// own; the process does not wait for it when it exits.
#[derive(Debug)]
pub struct Thread {
    imp: sys::thread::Thread,
    id: u64,
}

impl Thread {
    /// The identifier of the thread: what [`id`](crate::thread::id)
    /// returns in it. The system may give the number to another thread
    /// once this one has ended.
    #[inline]
    #[must_use]
    pub fn id(&self) -> u64 {
        self.id
    }

    /// Waits until the thread has ended.
    ///
    /// macOS: `pthread_join`. Windows: `WaitForSingleObject`.
    pub fn join(self) -> Result<()> {
        self.imp.join()
    }

    /// Lets the thread run on its own, which dropping the value does too.
    #[inline]
    pub fn detach(self) {}
}

/// Where a thread leaves what its function returned.
#[cfg(feature = "alloc")]
struct Packet<T>(core::cell::UnsafeCell<Option<T>>);

// SAFETY: the thread writes the value once, and the handle reads it once
// the thread has ended: never both at a time. The value itself crosses
// from one thread to the other, hence `Send`.
#[cfg(feature = "alloc")]
unsafe impl<T: Send> Sync for Packet<T> {}

/// A thread created by [`spawn`], and what its function will return.
///
/// Dropping it detaches the thread, as [`Thread`] does; the value it
/// returns is then dropped when it ends.
#[cfg(feature = "alloc")]
pub struct JoinHandle<T> {
    thread: Thread,
    packet: alloc::sync::Arc<Packet<T>>,
}

#[cfg(feature = "alloc")]
impl<T> JoinHandle<T> {
    /// The identifier of the thread: see [`Thread::id`].
    #[inline]
    #[must_use]
    pub fn id(&self) -> u64 {
        self.thread.id
    }

    /// Waits until the thread has ended, and returns what its function
    /// returned.
    pub fn join(self) -> Result<T> {
        self.thread.join()?;
        // SAFETY: the thread has ended: nothing else reaches the slot.
        let value = unsafe { (*self.packet.0.get()).take() };
        // A thread that ended without a value was ended by something else
        // than its function returning (`pthread_exit`, `ExitThread`).
        value.ok_or_else(|| ErrorKind::Other.into())
    }

    /// Lets the thread run on its own, which dropping the value does too.
    #[inline]
    pub fn detach(self) {}
}

#[cfg(feature = "alloc")]
impl<T> core::fmt::Debug for JoinHandle<T> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("JoinHandle")
            .field("thread", &self.thread)
            .finish_non_exhaustive()
    }
}