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
//! macOS: `libSystem`. The system call numbers and conventions below it are
//! private to Apple and change between releases.
//!
//! Every Rust program on macOS links `libSystem` already, so the functions
//! are simply declared, in `unsafe extern "C"` blocks next to their users.
//! Mind the x86_64 symbol variants: the functions that take or return a
//! `struct stat`, `dirent` or `statfs` must be linked as `name$INODE64` on
//! x86_64 (`#[cfg_attr(target_arch = "x86_64", link_name = "fstat$INODE64")]`),
//! or they use the legacy 32-bit inode layouts. aarch64 has only the new ones.

#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
compile_error!("oscall does not support this architecture on macOS");

pub mod errno;

pub(crate) mod event;
pub(crate) mod fs;
pub(crate) mod io;
pub(crate) mod mem;
pub(crate) mod net;
pub(crate) mod process;
pub(crate) mod rand;
pub(crate) mod sync;
pub(crate) mod thread;
pub(crate) mod time;

use core::ffi::c_int;

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

pub(crate) type RawHandle = i32;

unsafe extern "C" {
    fn __error() -> *mut c_int;
    #[link_name = "close$NOCANCEL"]
    fn close_nocancel(fd: c_int) -> c_int;
}

/// The calling thread's `errno`, as an [`Error`].
#[inline]
pub(crate) fn last_error() -> Error {
    // SAFETY: `__error` returns the address of the thread's errno.
    Error::from_raw_os_error(unsafe { *__error() })
}

/// Sets the calling thread's `errno`.
#[inline]
#[allow(dead_code)]
pub(crate) fn set_errno(value: c_int) {
    // SAFETY: `__error` returns the address of the thread's errno, which
    // only this thread reads and writes.
    unsafe { *__error() = value };
}

/// Converts the `-1` and `errno` convention to a `Result`.
#[inline]
#[allow(dead_code)]
pub(crate) fn cvt(ret: c_int) -> Result<c_int> {
    if ret == -1 {
        Err(last_error())
    } else {
        Ok(ret)
    }
}

/// As [`cvt`], for the functions that return a `ssize_t` or an `off_t`.
#[inline]
#[allow(dead_code)]
pub(crate) fn cvt_long(ret: i64) -> Result<i64> {
    if ret == -1 {
        Err(last_error())
    } else {
        Ok(ret)
    }
}

/// # Safety
///
/// `fd` must be an open descriptor that nothing uses afterwards.
pub(crate) unsafe fn close(fd: RawHandle) {
    // SAFETY: closing a descriptor the caller owns. The NOCANCEL variant
    // cannot leave the descriptor in an unknown state.
    unsafe { close_nocancel(fd) };
}

/// The generic I/O error.
pub(crate) const OTHER_ERROR: i32 = errno::EIO;

/// The classification of error codes. The first entry of a kind is the code
/// `Error::from(kind)` produces.
pub(crate) const ERRORS: &[(i32, ErrorKind)] = {
    use ErrorKind::*;
    use errno::*;
    &[
        (ENOENT, NotFound),
        (EACCES, PermissionDenied),
        (EPERM, PermissionDenied),
        (EEXIST, AlreadyExists),
        (EAGAIN, WouldBlock),
        (EINPROGRESS, InProgress),
        (EALREADY, InProgress),
        (EINTR, Interrupted),
        (EINVAL, InvalidInput),
        (ETIMEDOUT, TimedOut),
        (ENOTSUP, Unsupported),
        (ENOSYS, Unsupported),
        (EOPNOTSUPP, Unsupported),
        (EAFNOSUPPORT, Unsupported),
        (EPROTONOSUPPORT, Unsupported),
        (ENOMEM, OutOfMemory),
        (EBADF, BadHandle),
        (ENOTSOCK, BadHandle),
        (EPIPE, BrokenPipe),
        (ENOTDIR, NotADirectory),
        (EISDIR, IsADirectory),
        (ENOTEMPTY, DirectoryNotEmpty),
        (ENAMETOOLONG, InvalidFilename),
        (ERANGE, BufferTooSmall),
        (ELOOP, FilesystemLoop),
        (ENOSPC, StorageFull),
        (EDQUOT, QuotaExceeded),
        (EFBIG, FileTooLarge),
        (EROFS, ReadOnlyFilesystem),
        (EXDEV, CrossesDevices),
        (EMLINK, TooManyLinks),
        (EMFILE, TooManyOpenFiles),
        (ENFILE, TooManyOpenFiles),
        (EBUSY, ResourceBusy),
        (EDEADLK, Deadlock),
        (ESPIPE, NotSeekable),
        (ETXTBSY, ExecutableFileBusy),
        (ECONNREFUSED, ConnectionRefused),
        (ECONNRESET, ConnectionReset),
        (ECONNABORTED, ConnectionAborted),
        (ENOTCONN, NotConnected),
        (EISCONN, AlreadyConnected),
        (EADDRINUSE, AddrInUse),
        (EADDRNOTAVAIL, AddrNotAvailable),
        (ENETDOWN, NetworkDown),
        (ENETUNREACH, NetworkUnreachable),
        (EHOSTUNREACH, HostUnreachable),
        (EMSGSIZE, MessageTooLong),
        (ESRCH, NoSuchProcess),
    ]
};

#[cfg(test)]
mod tests {
    use super::*;

    unsafe extern "C" {
        fn getpid() -> c_int;
        fn close(fd: c_int) -> c_int;
    }

    #[test]
    fn calls() {
        // SAFETY: getpid takes nothing and cannot fail.
        let pid = unsafe { getpid() };
        assert!(pid > 0);
        #[cfg(feature = "std")]
        assert_eq!(pid as u32, std::process::id());

        // SAFETY: -1 is never an open descriptor.
        let err = cvt(unsafe { close(-1) }).unwrap_err();
        assert_eq!(err.raw_os_error(), errno::EBADF);
        assert_eq!(err.kind(), ErrorKind::BadHandle);
    }
}