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 macOS: what the C runtime keeps,
//! through the accessors of `crt_externs.h`.

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

use crate::Result;
use crate::process::env::Writer;

unsafe extern "C" {
    fn _NSGetArgc() -> *mut c_int;
    fn _NSGetArgv() -> *mut *const *const c_char;
    fn _NSGetEnviron() -> *mut *const *const c_char;
}

/// Copies the strings of a list that a null pointer ends, `limit` of them
/// at most.
///
/// # Safety
///
/// `list` is null or points to pointers to NUL-terminated strings, the
/// last of which is followed by a null pointer or is the `limit`th, and
/// nothing writes any of it meanwhile.
unsafe fn copy(list: *const *const c_char, limit: usize, buf: &mut [u8]) -> Result<usize> {
    let mut out = Writer::new(buf);
    if list.is_null() {
        return Ok(0);
    }
    for i in 0..limit {
        // SAFETY: the caller's contract: the list goes on until a null
        // pointer or `limit`.
        let string = unsafe { list.add(i).read() };
        if string.is_null() {
            break;
        }
        // SAFETY: the caller's contract: a NUL-terminated string.
        out.push(unsafe { CStr::from_ptr(string) }.to_bytes())?;
        out.end()?;
    }
    Ok(out.len())
}

pub(crate) fn args(buf: &mut [u8]) -> Result<usize> {
    // SAFETY: the accessors return the addresses of the runtime's `argc`
    // and `argv`, which it set before any code of the program ran and
    // which a program does not change; `argv` has `argc` strings.
    unsafe {
        let count = usize::try_from(_NSGetArgc().read()).unwrap_or(0);
        copy(_NSGetArgv().read(), count, buf)
    }
}

pub(crate) fn vars(buf: &mut [u8]) -> Result<usize> {
    // SAFETY: the accessor returns the address of `environ`, a list a null
    // pointer ends. `setenv` and `putenv` change it, and nothing keeps
    // them from doing so now: the contract of every function that changes
    // the environment (`std::env::set_var` is `unsafe` for it) is that no
    // other thread reads it meanwhile.
    unsafe { copy(_NSGetEnviron().read(), usize::MAX, buf) }
}