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
//! `io` on WASI preview 1.

use crate::io::{IoSlice, IoSliceMut, SeekFrom};
use crate::sys::cvt;
use crate::{BorrowedHandle, ErrorKind, OwnedHandle, Result};

#[link(wasm_import_module = "wasi_snapshot_preview1")]
unsafe extern "C" {
    fn fd_read(fd: i32, iovs: *const RawIoSlice, count: usize, done: *mut usize) -> i32;
    fn fd_write(fd: i32, iovs: *const RawIoSlice, count: usize, done: *mut usize) -> i32;
    fn fd_pread(
        fd: i32,
        iovs: *const RawIoSlice,
        count: usize,
        offset: i64,
        done: *mut usize,
    ) -> i32;
    fn fd_pwrite(
        fd: i32,
        iovs: *const RawIoSlice,
        count: usize,
        offset: i64,
        done: *mut usize,
    ) -> i32;
    fn fd_seek(fd: i32, offset: i64, whence: i32, pos: *mut u64) -> i32;
    fn fd_fdstat_get(fd: i32, stat: *mut FdStat) -> i32;
    fn fd_fdstat_set_flags(fd: i32, flags: i32) -> i32;
}

/// More buffers than this are not passed to one call.
const IOV_MAX: usize = 1024;

/// `iovec` and `ciovec`, which have the same layout.
#[derive(Clone, Copy)]
#[repr(C)]
pub(crate) struct RawIoSlice {
    base: *mut u8,
    len: usize,
}

impl RawIoSlice {
    #[inline]
    pub(crate) fn new(base: *mut u8, len: usize) -> Self {
        Self { base, len }
    }

    #[inline]
    pub(crate) fn ptr(&self) -> *mut u8 {
        self.base
    }

    #[inline]
    pub(crate) fn len(&self) -> usize {
        self.len
    }
}

/// `fdstat`.
#[repr(C)]
pub(crate) struct FdStat {
    pub(crate) filetype: u8,
    pub(crate) flags: u16,
    pub(crate) rights_base: u64,
    pub(crate) rights_inheriting: u64,
}

const FILETYPE_CHARACTER_DEVICE: u8 = 2;
const RIGHTS_FD_SEEK: u64 = 1 << 2;
const RIGHTS_FD_TELL: u64 = 1 << 5;

fn unsupported<T>() -> Result<T> {
    Err(ErrorKind::Unsupported.into())
}

fn file_offset(offset: u64) -> Result<i64> {
    i64::try_from(offset).map_err(|_| ErrorKind::InvalidInput.into())
}

pub(crate) fn read(handle: BorrowedHandle<'_>, buf: &mut [u8]) -> Result<usize> {
    let iov = RawIoSlice::new(buf.as_mut_ptr(), buf.len());
    let mut done = 0;
    // SAFETY: one `iovec` that describes `buf`, writable for its length.
    cvt(unsafe { fd_read(handle.as_raw(), &raw const iov, 1, &raw mut done) })?;
    Ok(done)
}

pub(crate) fn write(handle: BorrowedHandle<'_>, buf: &[u8]) -> Result<usize> {
    let iov = RawIoSlice::new(buf.as_ptr().cast_mut(), buf.len());
    let mut done = 0;
    // SAFETY: one `ciovec` that describes `buf`, which is only read.
    cvt(unsafe { fd_write(handle.as_raw(), &raw const iov, 1, &raw mut done) })?;
    Ok(done)
}

pub(crate) fn read_at(handle: BorrowedHandle<'_>, buf: &mut [u8], offset: u64) -> Result<usize> {
    let iov = RawIoSlice::new(buf.as_mut_ptr(), buf.len());
    let offset = file_offset(offset)?;
    let mut done = 0;
    // SAFETY: one `iovec` that describes `buf`, writable for its length.
    cvt(unsafe { fd_pread(handle.as_raw(), &raw const iov, 1, offset, &raw mut done) })?;
    Ok(done)
}

pub(crate) fn write_at(handle: BorrowedHandle<'_>, buf: &[u8], offset: u64) -> Result<usize> {
    let iov = RawIoSlice::new(buf.as_ptr().cast_mut(), buf.len());
    let offset = file_offset(offset)?;
    let mut done = 0;
    // SAFETY: one `ciovec` that describes `buf`, which is only read.
    cvt(unsafe { fd_pwrite(handle.as_raw(), &raw const iov, 1, offset, &raw mut done) })?;
    Ok(done)
}

pub(crate) fn read_vectored(
    handle: BorrowedHandle<'_>,
    bufs: &mut [IoSliceMut<'_>],
) -> Result<usize> {
    let count = bufs.len().min(IOV_MAX);
    let mut done = 0;
    // SAFETY: `IoSliceMut` is a transparent `iovec` over a writable buffer.
    cvt(unsafe { fd_read(handle.as_raw(), bufs.as_ptr().cast(), count, &raw mut done) })?;
    Ok(done)
}

pub(crate) fn write_vectored(handle: BorrowedHandle<'_>, bufs: &[IoSlice<'_>]) -> Result<usize> {
    let count = bufs.len().min(IOV_MAX);
    let mut done = 0;
    // SAFETY: `IoSlice` is a transparent `ciovec` over a readable buffer.
    cvt(unsafe { fd_write(handle.as_raw(), bufs.as_ptr().cast(), count, &raw mut done) })?;
    Ok(done)
}

pub(crate) fn seek(handle: BorrowedHandle<'_>, pos: SeekFrom) -> Result<u64> {
    let (offset, whence) = match pos {
        SeekFrom::Start(offset) => (offset as i64, 0),
        SeekFrom::Current(offset) => (offset, 1),
        SeekFrom::End(offset) => (offset, 2),
    };
    let mut pos = 0;
    // SAFETY: `pos` is the `filesize` the call writes.
    cvt(unsafe { fd_seek(handle.as_raw(), offset, whence, &raw mut pos) })?;
    Ok(pos)
}

pub(crate) fn pipe() -> Result<(OwnedHandle, OwnedHandle)> {
    unsupported()
}

pub(crate) fn duplicate(_: BorrowedHandle<'_>) -> Result<OwnedHandle> {
    unsupported()
}

fn std_handle(fd: i32) -> Option<BorrowedHandle<'static>> {
    // SAFETY: nothing is done to the descriptor here; if it is closed, the
    // calls made with it fail.
    Some(unsafe { BorrowedHandle::borrow_raw(fd) })
}

pub(crate) fn stdin() -> Option<BorrowedHandle<'static>> {
    std_handle(0)
}

pub(crate) fn stdout() -> Option<BorrowedHandle<'static>> {
    std_handle(1)
}

pub(crate) fn stderr() -> Option<BorrowedHandle<'static>> {
    std_handle(2)
}

pub(crate) fn is_terminal(handle: BorrowedHandle<'_>) -> bool {
    let mut stat = FdStat {
        filetype: 0,
        flags: 0,
        rights_base: 0,
        rights_inheriting: 0,
    };
    // SAFETY: `stat` is the `fdstat` the call writes.
    if cvt(unsafe { fd_fdstat_get(handle.as_raw(), &raw mut stat) }).is_err() {
        return false;
    }
    // As wasi-libc's `isatty`: a character device that cannot seek. (A
    // character device that can is something like `/dev/null`.)
    stat.filetype == FILETYPE_CHARACTER_DEVICE
        && stat.rights_base & (RIGHTS_FD_SEEK | RIGHTS_FD_TELL) == 0
}

pub(crate) fn set_inheritable(_: BorrowedHandle<'_>, _: bool) -> Result<()> {
    unsupported()
}

pub(crate) fn is_inheritable(_: BorrowedHandle<'_>) -> Result<bool> {
    unsupported()
}

/// `FDFLAGS_NONBLOCK`.
const FDFLAGS_NONBLOCK: u16 = 1 << 2;

pub(crate) fn set_nonblocking(handle: BorrowedHandle<'_>, nonblocking: bool) -> Result<()> {
    let mut stat = FdStat {
        filetype: 0,
        flags: 0,
        rights_base: 0,
        rights_inheriting: 0,
    };
    // SAFETY: `stat` is the structure the call fills.
    cvt(unsafe { fd_fdstat_get(handle.as_raw(), &raw mut stat) })?;
    // The flags are set as a whole: keep the others.
    let new = if nonblocking {
        stat.flags | FDFLAGS_NONBLOCK
    } else {
        stat.flags & !FDFLAGS_NONBLOCK
    };
    // SAFETY: no memory is involved.
    cvt(unsafe { fd_fdstat_set_flags(handle.as_raw(), new as i32) })
}