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 WASI: `args_get` and
//! `environ_get`, which write the strings, each with its NUL, and a pointer
//! to each.

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

#[link(wasm_import_module = "wasi_snapshot_preview1")]
unsafe extern "C" {
    fn args_sizes_get(count: *mut usize, size: *mut usize) -> i32;
    fn args_get(argv: *mut *mut u8, buf: *mut u8) -> i32;
    fn environ_sizes_get(count: *mut usize, size: *mut usize) -> i32;
    fn environ_get(environ: *mut *mut u8, buf: *mut u8) -> i32;
}

type Sizes = unsafe extern "C" fn(*mut usize, *mut usize) -> i32;
type Get = unsafe extern "C" fn(*mut *mut u8, *mut u8) -> i32;

/// The strings go at the start of `buf`, where the caller wants them, and
/// the pointers the host insists on writing after them, where nothing
/// reads them.
fn get(sizes: Sizes, get: Get, buf: &mut [u8]) -> Result<usize> {
    let (mut count, mut size) = (0usize, 0usize);
    // SAFETY: the function writes two numbers.
    cvt(unsafe { sizes(&raw mut count, &raw mut size) })?;
    if count == 0 {
        return Ok(0);
    }
    let (strings, rest) = buf
        .split_at_mut_checked(size)
        .ok_or(ErrorKind::BufferTooSmall)?;
    // SAFETY: any bytes are valid pointers to write over.
    let (_, pointers, _) = unsafe { rest.align_to_mut::<*mut u8>() };
    if pointers.len() < count {
        return Err(ErrorKind::BufferTooSmall.into());
    }
    // SAFETY: the function writes `count` pointers and `size` bytes, as it
    // just said, and both destinations are at least that large.
    cvt(unsafe { get(pointers.as_mut_ptr(), strings.as_mut_ptr()) })?;
    Ok(size)
}

pub(crate) fn args(buf: &mut [u8]) -> Result<usize> {
    get(args_sizes_get, args_get, buf)
}

pub(crate) fn vars(buf: &mut [u8]) -> Result<usize> {
    get(environ_sizes_get, environ_get, buf)
}