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
//! Linux and fullrust: raw system calls, with or without a libc in the process.

#[cfg(not(any(
    target_arch = "x86",
    target_arch = "x86_64",
    target_arch = "arm",
    target_arch = "aarch64",
    target_arch = "riscv32",
    target_arch = "riscv64",
)))]
compile_error!("oscall does not support this architecture on Linux");

// 64-bit values are split into register pairs low half first, and structures
// are laid out, for little-endian targets only.
#[cfg(target_endian = "big")]
compile_error!("oscall does not support big-endian Linux targets");

#[cfg_attr(target_arch = "x86", path = "arch/x86.rs")]
#[cfg_attr(target_arch = "x86_64", path = "arch/x86_64.rs")]
#[cfg_attr(target_arch = "arm", path = "arch/arm.rs")]
#[cfg_attr(target_arch = "aarch64", path = "arch/aarch64.rs")]
#[cfg_attr(
    any(target_arch = "riscv32", target_arch = "riscv64"),
    path = "arch/riscv.rs"
)]
#[allow(dead_code)]
pub(crate) mod arch;

/// The system call numbers of the target architecture. They differ between
/// architectures in value and in which calls exist at all (for instance
/// `OPEN`, `MMAP` against `MMAP2`, `CLOCK_GETTIME` against
/// `CLOCK_GETTIME64`).
#[cfg_attr(target_arch = "x86", path = "nr/x86.rs")]
#[cfg_attr(target_arch = "x86_64", path = "nr/x86_64.rs")]
#[cfg_attr(target_arch = "arm", path = "nr/arm.rs")]
#[cfg_attr(target_arch = "aarch64", path = "nr/aarch64.rs")]
#[cfg_attr(target_arch = "riscv32", path = "nr/riscv32.rs")]
#[cfg_attr(target_arch = "riscv64", path = "nr/riscv64.rs")]
#[allow(dead_code)]
#[rustfmt::skip]
pub mod nr;

pub mod errno;

pub(crate) mod auxv;
pub(crate) mod vdso;

pub(crate) mod env;
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 resolve;
pub(crate) mod sync;
pub(crate) mod thread;
pub(crate) mod time;
pub(crate) mod uring;

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

pub(crate) type RawHandle = i32;

/// Makes a system call and returns its raw result, as a `Result<usize>`:
/// `syscall!(OPENAT, dirfd, path.as_ptr(), flags, mode)`. The first argument
/// names a constant of [`nr`]; the others are cast with `as usize` (so a
/// negative `i32` sign-extends, a negative literal needs its type spelled out
/// (`-1i32`), and a 64-bit value on a 32-bit target must be
/// split by the caller, the way that system call expects).
///
/// The expansion is an `unsafe` call: use it in an `unsafe` block, and
/// uphold whatever the system call requires of its arguments.
macro_rules! syscall {
    ($nr:ident) => {
        $crate::sys::check($crate::sys::arch::syscall0($crate::sys::nr::$nr))
    };
    ($nr:ident, $a:expr) => {
        $crate::sys::check($crate::sys::arch::syscall1($crate::sys::nr::$nr, $a as usize))
    };
    ($nr:ident, $a:expr, $b:expr) => {
        $crate::sys::check($crate::sys::arch::syscall2(
            $crate::sys::nr::$nr,
            $a as usize,
            $b as usize,
        ))
    };
    ($nr:ident, $a:expr, $b:expr, $c:expr) => {
        $crate::sys::check($crate::sys::arch::syscall3(
            $crate::sys::nr::$nr,
            $a as usize,
            $b as usize,
            $c as usize,
        ))
    };
    ($nr:ident, $a:expr, $b:expr, $c:expr, $d:expr) => {
        $crate::sys::check($crate::sys::arch::syscall4(
            $crate::sys::nr::$nr,
            $a as usize,
            $b as usize,
            $c as usize,
            $d as usize,
        ))
    };
    ($nr:ident, $a:expr, $b:expr, $c:expr, $d:expr, $e:expr) => {
        $crate::sys::check($crate::sys::arch::syscall5(
            $crate::sys::nr::$nr,
            $a as usize,
            $b as usize,
            $c as usize,
            $d as usize,
            $e as usize,
        ))
    };
    ($nr:ident, $a:expr, $b:expr, $c:expr, $d:expr, $e:expr, $f:expr) => {
        $crate::sys::check($crate::sys::arch::syscall6(
            $crate::sys::nr::$nr,
            $a as usize,
            $b as usize,
            $c as usize,
            $d as usize,
            $e as usize,
            $f as usize,
        ))
    };
}
#[allow(unused_imports)]
pub(crate) use syscall;

/// Splits a system call's return value: the kernel reports an error as
/// `-errno`, in the last 4095 values of the address space.
#[inline]
pub(crate) fn check(ret: usize) -> Result<usize> {
    if ret > -4096isize as usize {
        Err(Error::from_raw_os_error(
            (ret as isize).wrapping_neg() as i32
        ))
    } 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.
    let _ = unsafe { syscall!(CLOSE, 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),
        (ETIME, TimedOut),
        (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),
        (ECANCELED, Canceled),
    ]
};

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

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

        // Six arguments, the most a system call takes, and one that travels
        // in every argument register: an anonymous mapping.
        #[cfg(target_pointer_width = "32")]
        // SAFETY: a fresh private mapping; MMAP2 takes its offset in pages.
        let map = unsafe { syscall!(MMAP2, 0, 8192, 3, 0x22, -1i32, 0) };
        #[cfg(target_pointer_width = "64")]
        // SAFETY: a fresh private mapping.
        let map = unsafe { syscall!(MMAP, 0, 8192, 3, 0x22, -1i32, 0) };
        let addr = map.unwrap();
        assert_eq!(addr % 4096, 0);
        // SAFETY: the mapping is two readable and writable pages.
        unsafe {
            let p = addr as *mut u8;
            p.add(8191).write(7);
            assert_eq!(p.add(8191).read(), 7);
            assert_eq!(p.read(), 0);
        }
        // SAFETY: unmapping the mapping made above.
        unsafe { syscall!(MUNMAP, addr, 8192) }.unwrap();

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