dope-sys 0.76.0

Typed operating-system call contracts
Documentation
use std::{mem, num::NonZero, ptr};

use o3::base::marker::ThreadBound;

use crate::{Errno, kernel};

pub(super) fn entropy<S: kernel::raw::Source + ?Sized, const N: usize>(
    bytes: &mut mem::MaybeUninit<[u8; N]>,
) -> Result<&mut [u8; N], Errno> {
    const { assert!(N <= 256) };
    // SAFETY: bytes provides N writable bytes, within getentropy's 256-byte limit.
    let result = unsafe { libc::getentropy(bytes.as_mut_ptr().cast(), N) };
    // SAFETY: getentropy handles interruptions internally and returns zero or -1
    // with unchanged native errno; success initializes the complete requested extent.
    unsafe { kernel::raw::Status::new(result).try_zero::<S, Errno>() }?;
    // SAFETY: success initializes all N bytes, including the empty array.
    Ok(unsafe { bytes.assume_init_mut() })
}

/// # Safety
/// Implementors access only their admitted context and resources, with the promised thread exclusivity.
pub unsafe trait Task: Sized {
    /// # Safety
    /// The context and all resources it uses must retain their admitted access rights through this execution.
    unsafe fn run(context: ptr::NonNull<Self>);
}

/// Native thread attributes carrying one validated stack extent.
pub struct Attrs(libc::pthread_attr_t);

impl Attrs {
    /// Initializes attributes for a thread with the exact requested stack.
    pub fn with_stack(stack: NonZero<usize>) -> Result<Self, Errno> {
        let mut raw = mem::MaybeUninit::uninit();
        // SAFETY: raw has the native attribute size and is initialized on success.
        let result = unsafe { libc::pthread_attr_init(raw.as_mut_ptr()) };
        // SAFETY: pthread_attr_init returns zero or a positive error code directly.
        unsafe { kernel::raw::Status::new(result).try_pthread() }?;
        // SAFETY: pthread_attr_init completed, so this value is initialized and
        // owned here until its Drop destroys it.
        let mut attr = Self(unsafe { raw.assume_init() });
        let result = unsafe { libc::pthread_attr_setstacksize(&mut attr.0, stack.get()) };
        // SAFETY: pthread_attr_setstacksize returns zero or a positive error code.
        unsafe { kernel::raw::Status::new(result).try_pthread() }?;
        Ok(attr)
    }

    /// # Safety
    /// Retain the initialized context and its borrowed resources at stable addresses through creation
    /// failure or successful join. Preserve T's exclusive access even if the handle is forgotten.
    pub unsafe fn spawn<T: Task>(&self, context: ptr::NonNull<T>) -> Result<Handle, Errno> {
        let mut thread = mem::MaybeUninit::uninit();
        // SAFETY: attrs and the writable handle outlive this call. The caller retains
        // T's context and access rights through join. pthread_create returns the exact errno.
        unsafe {
            kernel::raw::Status::new(libc::pthread_create(
                thread.as_mut_ptr(),
                &self.0,
                run::<T>,
                context.as_ptr().cast(),
            ))
            .try_pthread()
        }?;
        // SAFETY: pthread_create wrote the handle before returning success.
        Ok(Handle(unsafe { thread.assume_init() }, ThreadBound::NEW))
    }
}

/// Destroys the uniquely owned attributes; no caller can invalidate them first.
impl Drop for Attrs {
    fn drop(&mut self) {
        // SAFETY: these initialized attributes are exclusively owned and destroyed
        // once. Only stack size was changed, so no work-interval port is retained;
        // destruction returns exactly zero on the admitted native implementations.
        unsafe { libc::pthread_attr_destroy(&mut self.0) };
    }
}

/// One joinable native thread, joined on drop by its creating thread.
#[repr(transparent)]
pub struct Handle(libc::pthread_t, ThreadBound);

impl Drop for Handle {
    fn drop(&mut self) {
        // SAFETY: successful spawn created this unique joinable handle, retained
        // by its creating thread. pthread_join returns zero or a positive error
        // code, which is checked before the owner can reclaim worker storage.
        if let Err(cause) = unsafe {
            kernel::raw::Status::new(libc::pthread_join(self.0, ptr::null_mut())).try_pthread()
        } {
            kernel::Fatal::Join(cause).terminate()
        }
    }
}

extern "C" fn run<T: Task>(context: *mut std::ffi::c_void) -> *mut std::ffi::c_void {
    // SAFETY: spawn passes this admitted nonnull T context exactly once.
    unsafe { T::run(ptr::NonNull::new_unchecked(context.cast())) };
    ptr::null_mut()
}