oscall 0.0.1

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! `sync` on macOS: `os_sync_wait_on_address` and its family where the
//! system has them, the `ulock` system calls they are made of where it does
//! not.
//!
//! The documented calls (`<os/os_sync_wait_on_address.h>`) need macOS 14.4,
//! and the oldest version supported is 11: they are looked up when first
//! needed (`dlsym`), all four or none. Without them, the entry points
//! `libSystem` exports for libc++ and `libdispatch` are used, as Rust's
//! `std` does: `__ulock_wait2`, which takes its timeout in nanoseconds and
//! exists since macOS 11, and `__ulock_wake`. These are absent from the
//! SDK's headers, but they are what the documented calls are: the same
//! operation (`UL_COMPARE_AND_WAIT`) on the same address, so that either
//! family wakes the waiters of the other.

use core::ffi::{c_char, c_int, c_void};
use core::sync::atomic::{AtomicPtr, AtomicU8, AtomicU32, Ordering};
use core::time::Duration;

use crate::sys::errno;
use crate::{Error, Result};

// xnu: bsd/sys/ulock.h
/// Wait while the 32-bit value at the address is the given one.
const UL_COMPARE_AND_WAIT: u32 = 1;
/// Wake every waiter, not one.
const ULF_WAKE_ALL: u32 = 0x0000_0100;
/// Return errors as negative values instead of setting `errno`.
const ULF_NO_ERRNO: u32 = 0x0100_0000;

// <os/os_sync_wait_on_address.h>, <os/clock.h>
/// `OS_SYNC_WAIT_ON_ADDRESS_NONE`, `OS_SYNC_WAKE_BY_ADDRESS_NONE`: the
/// address is not in memory shared with another process.
const OS_SYNC_NONE: u32 = 0;
/// The only clock there is: the one `Clock::Monotonic` reads.
const OS_CLOCK_MACH_ABSOLUTE_TIME: u32 = 32;

/// `<dlfcn.h>`: every image of the process, in load order.
const RTLD_DEFAULT: *mut c_void = -2isize as *mut c_void;

/// The longest timeout given to the system: 292 years. The kernel adds the
/// timeout to its clock, and has not always checked that the sum fits in
/// 64 bits: a longer one could be over at once. Longer than this is
/// forever.
const MAX_TIMEOUT_NANOS: u64 = i64::MAX as u64;

unsafe extern "C" {
    /// `timeout` is in nanoseconds, 0 for none. Returns the number of other
    /// waiters, or a negative error number with `ULF_NO_ERRNO`.
    fn __ulock_wait2(
        operation: u32,
        addr: *mut c_void,
        value: u64,
        timeout: u64,
        value2: u64,
    ) -> c_int;
    fn __ulock_wake(operation: u32, addr: *mut c_void, wake_value: u64) -> c_int;
    fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
    /// The address of the thread's `errno`.
    fn __error() -> *mut c_int;
}

/// `os_sync_wait_on_address`: returns the number of other waiters, or -1
/// with the reason in `errno`.
type WaitFn = unsafe extern "C" fn(addr: *mut c_void, value: u64, size: usize, flags: u32) -> c_int;
/// `os_sync_wait_on_address_with_timeout`: likewise. A zero timeout is an
/// error.
type WaitTimeoutFn = unsafe extern "C" fn(
    addr: *mut c_void,
    value: u64,
    size: usize,
    flags: u32,
    clock_id: u32,
    timeout_ns: u64,
) -> c_int;
/// `os_sync_wake_by_address_any` and `os_sync_wake_by_address_all`: return
/// 0, or -1 with the reason in `errno`.
type WakeFn = unsafe extern "C" fn(addr: *mut c_void, size: usize, flags: u32) -> c_int;

/// The documented calls.
#[derive(Clone, Copy)]
struct OsSync {
    wait: WaitFn,
    wait_with_timeout: WaitTimeoutFn,
    wake_any: WakeFn,
    wake_all: WakeFn,
}

const UNRESOLVED: u8 = 0;
const DOCUMENTED: u8 = 1;
const ULOCK: u8 = 2;

/// Which calls the system has: a fact that does not change.
static FAMILY: AtomicU8 = AtomicU8::new(UNRESOLVED);
/// The addresses of the four documented calls, once `FAMILY` says
/// `DOCUMENTED`.
static SYMBOLS: [AtomicPtr<c_void>; 4] = [const { AtomicPtr::new(core::ptr::null_mut()) }; 4];

const NAMES: [&core::ffi::CStr; 4] = [
    c"os_sync_wait_on_address",
    c"os_sync_wait_on_address_with_timeout",
    c"os_sync_wake_by_address_any",
    c"os_sync_wake_by_address_all",
];

/// The documented calls, if the system has them.
fn os_sync() -> Option<OsSync> {
    let symbols = match FAMILY.load(Ordering::Acquire) {
        DOCUMENTED => SYMBOLS
            .each_ref()
            .map(|symbol| symbol.load(Ordering::Relaxed)),
        ULOCK => return None,
        _ => {
            // Threads that get here together find the same answer.
            // SAFETY: each name is a NUL-terminated string.
            let symbols = NAMES.map(|name| unsafe { dlsym(RTLD_DEFAULT, name.as_ptr()) });
            if symbols.iter().any(|symbol| symbol.is_null()) {
                FAMILY.store(ULOCK, Ordering::Release);
                return None;
            }
            for (cached, symbol) in SYMBOLS.iter().zip(symbols) {
                cached.store(symbol, Ordering::Relaxed);
            }
            FAMILY.store(DOCUMENTED, Ordering::Release);
            symbols
        }
    };
    // SAFETY: none is null, and each is the address of the function of that
    // name in `libSystem`, which has the type its header declares.
    Some(unsafe {
        OsSync {
            wait: core::mem::transmute::<*mut c_void, WaitFn>(symbols[0]),
            wait_with_timeout: core::mem::transmute::<*mut c_void, WaitTimeoutFn>(symbols[1]),
            wake_any: core::mem::transmute::<*mut c_void, WakeFn>(symbols[2]),
            wake_all: core::mem::transmute::<*mut c_void, WakeFn>(symbols[3]),
        }
    })
}

/// Makes one of the documented calls, and returns zero, or the error number
/// if it failed.
///
/// `errno` is left as it was. The calls report through it what is no
/// failure for the caller of this module (a timeout, no waiter to wake),
/// and the `ulock` calls do not touch it: waking must not change the
/// `errno` a program is about to read.
fn documented(call: impl FnOnce() -> c_int) -> c_int {
    // SAFETY: `__error` returns the address of the thread's `errno`, which
    // lives as long as the thread.
    let errno = unsafe { __error() };
    // SAFETY: as above.
    let saved = unsafe { *errno };
    if call() >= 0 {
        return 0;
    }
    // SAFETY: as above.
    unsafe {
        let code = *errno;
        *errno = saved;
        code
    }
}

/// Whether the wait ended otherwise than by its timeout.
pub(crate) fn wait(atomic: &AtomicU32, expected: u32, timeout: Option<Duration>) -> Result<bool> {
    // In nanoseconds, zero for none.
    let timeout = match timeout {
        None => 0,
        // The system takes 0 to mean no timeout, or refuses it: compare
        // here.
        Some(Duration::ZERO) => return Ok(atomic.load(Ordering::SeqCst) != expected),
        Some(timeout) => match u64::try_from(timeout.as_nanos()) {
            Ok(nanos) if nanos <= MAX_TIMEOUT_NANOS => nanos,
            // Nobody waits that long: no timeout.
            _ => 0,
        },
    };
    let addr = atomic.as_ptr().cast::<c_void>();
    let value = u64::from(expected);
    // Zero, or the error number.
    let code = match os_sync() {
        Some(os_sync) => {
            // SAFETY: the system reads the four bytes of the atomic, which
            // is borrowed.
            documented(|| unsafe {
                if timeout == 0 {
                    (os_sync.wait)(addr, value, size_of::<u32>(), OS_SYNC_NONE)
                } else {
                    (os_sync.wait_with_timeout)(
                        addr,
                        value,
                        size_of::<u32>(),
                        OS_SYNC_NONE,
                        OS_CLOCK_MACH_ABSOLUTE_TIME,
                        timeout,
                    )
                }
            })
        }
        None => {
            // SAFETY: the kernel reads the atomic, which is borrowed.
            let ret = unsafe {
                __ulock_wait2(UL_COMPARE_AND_WAIT | ULF_NO_ERRNO, addr, value, timeout, 0)
            };
            if ret >= 0 { 0 } else { -ret }
        }
    };
    match code {
        // Woken, or the value was not the expected one.
        0 => Ok(true),
        // A signal handler ran: a spurious wake-up. So is a value the
        // kernel could not read for now (it is short of memory: the address
        // is that of a borrowed atomic, and cannot be wrong).
        errno::EINTR | errno::EFAULT => Ok(true),
        errno::ETIMEDOUT => Ok(false),
        code => Err(Error::from_raw_os_error(code)),
    }
}

pub(crate) fn wake(atomic: &AtomicU32, all: bool) {
    let addr = atomic.as_ptr().cast::<c_void>();
    let os_sync = os_sync();
    loop {
        // Zero, or the error number.
        let code = match os_sync {
            Some(os_sync) => {
                let wake = if all {
                    os_sync.wake_all
                } else {
                    os_sync.wake_any
                };
                // SAFETY: the system only uses the address as a key.
                documented(|| unsafe { wake(addr, size_of::<u32>(), OS_SYNC_NONE) })
            }
            None => {
                let flags = if all { ULF_WAKE_ALL } else { 0 };
                // SAFETY: the kernel only uses the address as a key.
                let ret =
                    unsafe { __ulock_wake(UL_COMPARE_AND_WAIT | ULF_NO_ERRNO | flags, addr, 0) };
                if ret >= 0 { 0 } else { -ret }
            }
        };
        // The one loop: an interrupted wake has woken nobody, and the caller
        // has no error to act on (libc++ does the same). The other failure
        // is ENOENT: there was no waiter.
        if code != errno::EINTR {
            return;
        }
    }
}