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
//! `thread` on macOS: the `pthread` extensions, `sched_yield` and `sysctl`.

use core::ffi::{c_char, c_int, c_void};

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

/// `MAXTHREADNAMESIZE`: the size of a thread's name, with its NUL.
const NAME_SIZE: usize = 64;

pub(crate) const NAME_MAX: usize = NAME_SIZE - 1;

unsafe extern "C" {
    /// `pthread_t` is a pointer; null is the calling thread here.
    fn pthread_threadid_np(thread: *mut c_void, id: *mut u64) -> c_int;
    fn pthread_self() -> *mut c_void;
    /// Names the calling thread. Returns an error number.
    fn pthread_setname_np(name: *const c_char) -> c_int;
    /// Returns an error number.
    fn pthread_getname_np(thread: *mut c_void, name: *mut c_char, len: usize) -> c_int;
    fn sched_yield() -> c_int;
    fn sysctlbyname(
        name: *const c_char,
        old: *mut c_void,
        old_len: *mut usize,
        new: *mut c_void,
        new_len: usize,
    ) -> c_int;
}

/// `pthread_attr_t`: a signature and 56 opaque bytes, on both
/// architectures (`__PTHREAD_ATTR_SIZE__`).
#[repr(C)]
struct Attr {
    signature: core::ffi::c_long,
    opaque: [u8; 56],
}

/// `PTHREAD_STACK_MIN`, the larger of the two architectures' (arm64).
const STACK_MIN: usize = 16384;

unsafe extern "C" {
    fn pthread_attr_init(attr: *mut Attr) -> c_int;
    fn pthread_attr_destroy(attr: *mut Attr) -> c_int;
    fn pthread_attr_setstacksize(attr: *mut Attr, size: usize) -> c_int;
    fn pthread_create(
        thread: *mut *mut c_void,
        attr: *const Attr,
        start: unsafe extern "C" fn(*mut c_void) -> *mut c_void,
        arg: *mut c_void,
    ) -> c_int;
    fn pthread_join(thread: *mut c_void, value: *mut *mut c_void) -> c_int;
    fn pthread_detach(thread: *mut c_void) -> c_int;
    fn pthread_get_stackaddr_np(thread: *mut c_void) -> *mut c_void;
    fn pthread_get_stacksize_np(thread: *mut c_void) -> usize;
    fn pthread_set_qos_class_self_np(class: core::ffi::c_uint, relative: c_int) -> c_int;
    fn qos_class_self() -> core::ffi::c_uint;
}

/// The `pthread` functions return the error number.
fn check(code: c_int) -> Result<()> {
    match code {
        0 => Ok(()),
        code => Err(Error::from_raw_os_error(code)),
    }
}

/// A thread that was neither joined nor detached yet.
#[derive(Debug)]
pub(crate) struct Thread(*mut c_void);

// SAFETY: a `pthread_t` names a thread for any thread of the process.
unsafe impl Send for Thread {}
// SAFETY: as above; nothing is done through a shared reference.
unsafe impl Sync for Thread {}

unsafe extern "C" fn start(data: *mut c_void) -> *mut c_void {
    // SAFETY: `spawn` was given this pointer for this call.
    unsafe { crate::thread::spawn::thread_main(data) };
    core::ptr::null_mut()
}

/// # Safety
///
/// `data` is what `thread::spawn::thread_main` wants.
pub(crate) unsafe fn spawn(stack_size: usize, data: *mut c_void) -> Result<Thread> {
    let page = crate::sys::mem::page_size();
    let stack_size = stack_size
        .max(STACK_MIN)
        .checked_next_multiple_of(page)
        .ok_or(ErrorKind::InvalidInput)?;
    let mut attr = Attr {
        signature: 0,
        opaque: [0; 56],
    };
    let mut thread = core::ptr::null_mut();
    // SAFETY: the attributes are initialised before they are used and
    // destroyed after; the function writes the thread to `thread`, and
    // the caller answers for `data`.
    unsafe {
        check(pthread_attr_init(&raw mut attr))?;
        let result = check(pthread_attr_setstacksize(&raw mut attr, stack_size)).and_then(|()| {
            check(pthread_create(
                &raw mut thread,
                &raw const attr,
                start,
                data,
            ))
        });
        pthread_attr_destroy(&raw mut attr);
        result?;
    }
    Ok(Thread(thread))
}

impl Thread {
    pub(crate) fn join(self) -> Result<()> {
        let thread = self.0;
        core::mem::forget(self);
        // SAFETY: the thread was neither joined nor detached, and is not
        // named again.
        check(unsafe { pthread_join(thread, core::ptr::null_mut()) })
    }
}

impl Drop for Thread {
    fn drop(&mut self) {
        // SAFETY: the thread was neither joined nor detached, and is not
        // named again.
        unsafe { pthread_detach(self.0) };
    }
}

pub(crate) fn stack_bounds() -> core::ops::Range<usize> {
    // SAFETY: both functions read the structure of the calling thread.
    let (top, size) = unsafe {
        let thread = pthread_self();
        (
            pthread_get_stackaddr_np(thread) as usize,
            pthread_get_stacksize_np(thread),
        )
    };
    top.saturating_sub(size)..top
}

pub(crate) fn qos() -> u32 {
    // SAFETY: takes nothing and cannot fail.
    unsafe { qos_class_self() }
}

pub(crate) fn set_qos(class: u32) -> Result<()> {
    // SAFETY: takes two integers.
    check(unsafe { pthread_set_qos_class_self_np(class, 0) })
}

pub(crate) fn id() -> u64 {
    let mut id = 0;
    // SAFETY: the function writes one `u64`; it cannot fail for the calling
    // thread.
    unsafe { pthread_threadid_np(core::ptr::null_mut(), &raw mut id) };
    id
}

pub(crate) fn yield_now() {
    // SAFETY: sched_yield takes nothing.
    unsafe { sched_yield() };
}

pub(crate) fn available_parallelism() -> Result<usize> {
    let mut count: c_int = 0;
    let mut len = size_of::<c_int>();
    // SAFETY: the name is NUL-terminated, and the function writes at most
    // `len` bytes to `count`: the value is an `int`.
    cvt(unsafe {
        sysctlbyname(
            c"hw.activecpu".as_ptr(),
            (&raw mut count).cast(),
            &raw mut len,
            core::ptr::null_mut(),
            0,
        )
    })?;
    usize::try_from(count).map_err(|_| ErrorKind::Other.into())
}

pub(crate) fn set_name(name: &str) -> Result<()> {
    // A name of `NAME_MAX` bytes at most, which the caller cut it to: the
    // last byte of the buffer is never written, and is the NUL the function
    // reads up to if nothing else is.
    let mut buf = [0u8; NAME_SIZE];
    buf[..NAME_MAX]
        .get_mut(..name.len())
        .ok_or(ErrorKind::InvalidInput)?
        .copy_from_slice(name.as_bytes());
    // SAFETY: the function reads a NUL-terminated string, and `buf` ends
    // with a NUL whatever the name is.
    match unsafe { pthread_setname_np(buf.as_ptr().cast()) } {
        0 => Ok(()),
        code => Err(Error::from_raw_os_error(code)),
    }
}

pub(crate) fn name(buf: &mut [u8]) -> Result<usize> {
    let mut name = [0u8; NAME_SIZE];
    // SAFETY: the function writes at most `NAME_SIZE` bytes, NUL included,
    // for the calling thread.
    match unsafe { pthread_getname_np(pthread_self(), name.as_mut_ptr().cast(), NAME_SIZE) } {
        0 => {}
        code => return Err(Error::from_raw_os_error(code)),
    }
    let len = name.iter().position(|&b| b == 0).unwrap_or(NAME_SIZE);
    buf.get_mut(..len)
        .ok_or(ErrorKind::BufferTooSmall)?
        .copy_from_slice(&name[..len]);
    Ok(len)
}