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
//! The arguments and the environment on Linux: the kernel's copy of them.
//!
//! Both sit above the initial stack, and without a libc nothing in the
//! process has a pointer to them (see `auxv`). The kernel reads that
//! memory for whoever reads `/proc/self/cmdline` and `/proc/self/environ`:
//! strings that each end with a NUL, which is the form the portable layer
//! wants.

use core::ffi::CStr;

use crate::sys::syscall;
use crate::{ErrorKind, Result};

const AT_FDCWD: i32 = -100;
const O_RDONLY: usize = 0;
/// The same on every architecture oscall supports.
const O_CLOEXEC: usize = 0o2000000;

/// Reads the whole of a file of `/proc` into `buf`.
fn read_all(path: &CStr, buf: &mut [u8]) -> Result<usize> {
    // SAFETY: the path is NUL-terminated, and opening a file for reading
    // has no effect on the process but the descriptor returned.
    let fd = unsafe { syscall!(OPENAT, AT_FDCWD, path.as_ptr(), O_RDONLY | O_CLOEXEC, 0) }?;
    let mut filled = 0;
    let result = loop {
        // One byte more than the buffer holds tells a file that fits
        // exactly from one that does not.
        let mut extra = 0u8;
        let (to, room) = match buf.get_mut(filled..) {
            Some(rest) if !rest.is_empty() => (rest.as_mut_ptr(), rest.len()),
            _ => (&raw mut extra, 1),
        };
        // SAFETY: the destination is writable for the length given.
        match unsafe { syscall!(READ, fd, to, room) } {
            Ok(0) => break Ok(filled),
            Ok(_) if filled == buf.len() => break Err(ErrorKind::BufferTooSmall.into()),
            Ok(n) => filled += n,
            Err(error) => break Err(error),
        }
    };
    // SAFETY: `fd` was opened above and is used by nothing else.
    unsafe { crate::sys::close(fd as i32) };
    result
}

pub(crate) fn args(buf: &mut [u8]) -> Result<usize> {
    read_all(c"/proc/self/cmdline", buf)
}

pub(crate) fn vars(buf: &mut [u8]) -> Result<usize> {
    read_all(c"/proc/self/environ", buf)
}