oscall 0.0.2

Low-level cross-platform interface to operating system services: files, memory mapping, networking and more, with no libc on Linux
Documentation
//! `io` on macOS.

use core::ffi::{c_int, c_void};

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

/// `IOV_MAX`: more buffers than this make `readv` fail.
const IOV_MAX: usize = 1024;
/// The kernel refuses to read or write more than `INT_MAX` bytes at once.
const MAX_LEN: usize = c_int::MAX as usize - 1;

const F_GETFD: c_int = 1;
const F_GETFL: c_int = 3;
const F_SETFL: c_int = 4;
const O_NONBLOCK: c_int = 0x4;
const F_SETFD: c_int = 2;
const F_DUPFD_CLOEXEC: c_int = 67;
const FD_CLOEXEC: c_int = 1;

unsafe extern "C" {
    #[link_name = "read"]
    fn c_read(fd: c_int, buf: *mut c_void, len: usize) -> isize;
    #[link_name = "write"]
    fn c_write(fd: c_int, buf: *const c_void, len: usize) -> isize;
    fn pread(fd: c_int, buf: *mut c_void, len: usize, offset: i64) -> isize;
    fn pwrite(fd: c_int, buf: *const c_void, len: usize, offset: i64) -> isize;
    fn readv(fd: c_int, iov: *const RawIoSlice, count: c_int) -> isize;
    fn writev(fd: c_int, iov: *const RawIoSlice, count: c_int) -> isize;
    fn lseek(fd: c_int, offset: i64, whence: c_int) -> i64;
    #[link_name = "pipe"]
    fn c_pipe(fds: *mut c_int) -> c_int;
    pub(crate) fn fcntl(fd: c_int, cmd: c_int, ...) -> c_int;
    fn isatty(fd: c_int) -> c_int;
}

/// `struct iovec`.
#[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
    }
}

fn cvt_len(ret: isize) -> Result<usize> {
    cvt_long(ret as i64).map(|n| n as usize)
}

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 len = buf.len().min(MAX_LEN);
    // SAFETY: `buf` is writable for `len` bytes.
    cvt_len(unsafe { c_read(handle.as_raw(), buf.as_mut_ptr().cast(), len) })
}

pub(crate) fn write(handle: BorrowedHandle<'_>, buf: &[u8]) -> Result<usize> {
    let len = buf.len().min(MAX_LEN);
    // SAFETY: `buf` is readable for `len` bytes.
    cvt_len(unsafe { c_write(handle.as_raw(), buf.as_ptr().cast(), len) })
}

pub(crate) fn read_at(handle: BorrowedHandle<'_>, buf: &mut [u8], offset: u64) -> Result<usize> {
    let len = buf.len().min(MAX_LEN);
    let offset = file_offset(offset)?;
    // SAFETY: `buf` is writable for `len` bytes.
    cvt_len(unsafe { pread(handle.as_raw(), buf.as_mut_ptr().cast(), len, offset) })
}

pub(crate) fn write_at(handle: BorrowedHandle<'_>, buf: &[u8], offset: u64) -> Result<usize> {
    let len = buf.len().min(MAX_LEN);
    let offset = file_offset(offset)?;
    // SAFETY: `buf` is readable for `len` bytes.
    cvt_len(unsafe { pwrite(handle.as_raw(), buf.as_ptr().cast(), len, offset) })
}

pub(crate) fn read_vectored(
    handle: BorrowedHandle<'_>,
    bufs: &mut [IoSliceMut<'_>],
) -> Result<usize> {
    // No buffer at all is an invalid argument here, and a read of nothing
    // elsewhere.
    if bufs.is_empty() {
        return read(handle, &mut []);
    }
    let count = bufs.len().min(IOV_MAX) as c_int;
    // SAFETY: `IoSliceMut` is a transparent `iovec` over a writable buffer.
    cvt_len(unsafe { readv(handle.as_raw(), bufs.as_ptr().cast(), count) })
}

pub(crate) fn write_vectored(handle: BorrowedHandle<'_>, bufs: &[IoSlice<'_>]) -> Result<usize> {
    // No buffer at all is an invalid argument here, and a write of nothing
    // elsewhere.
    if bufs.is_empty() {
        return write(handle, &[]);
    }
    let count = bufs.len().min(IOV_MAX) as c_int;
    // SAFETY: `IoSlice` is a transparent `iovec` over a readable buffer.
    cvt_len(unsafe { writev(handle.as_raw(), bufs.as_ptr().cast(), count) })
}

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),
    };
    // SAFETY: no memory is involved.
    cvt_long(unsafe { lseek(handle.as_raw(), offset, whence) }).map(|pos| pos as u64)
}

pub(crate) fn pipe() -> Result<(OwnedHandle, OwnedHandle)> {
    let mut fds: [c_int; 2] = [0; 2];
    // SAFETY: `fds` is the two descriptors the call writes.
    cvt(unsafe { c_pipe(fds.as_mut_ptr()) })?;
    // SAFETY: both descriptors were just created and are owned by nobody.
    let pair = unsafe { (OwnedHandle::from_raw(fds[0]), OwnedHandle::from_raw(fds[1])) };
    // macOS has no pipe2: the flag cannot be set atomically.
    set_inheritable(pair.0.as_handle(), false)?;
    set_inheritable(pair.1.as_handle(), false)?;
    Ok(pair)
}

pub(crate) fn duplicate(handle: BorrowedHandle<'_>) -> Result<OwnedHandle> {
    let min: c_int = 0;
    // SAFETY: the command takes an `int`, passed as the variadic argument.
    let fd = cvt(unsafe { fcntl(handle.as_raw(), F_DUPFD_CLOEXEC, min) })?;
    // SAFETY: the descriptor was just created.
    Ok(unsafe { OwnedHandle::from_raw(fd) })
}

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 {
    // SAFETY: no memory is involved.
    unsafe { isatty(handle.as_raw()) == 1 }
}

pub(crate) fn set_inheritable(handle: BorrowedHandle<'_>, inheritable: bool) -> Result<()> {
    // FD_CLOEXEC is the only descriptor flag there is.
    let flags = if inheritable { 0 } else { FD_CLOEXEC };
    // SAFETY: the command takes an `int`, passed as the variadic argument.
    cvt(unsafe { fcntl(handle.as_raw(), F_SETFD, flags) })?;
    Ok(())
}

pub(crate) fn is_inheritable(handle: BorrowedHandle<'_>) -> Result<bool> {
    // SAFETY: the command takes no argument.
    let flags = cvt(unsafe { fcntl(handle.as_raw(), F_GETFD) })?;
    Ok(flags & FD_CLOEXEC == 0)
}

pub(crate) fn set_nonblocking(handle: BorrowedHandle<'_>, nonblocking: bool) -> Result<()> {
    // The flags are set as a whole: keep the others.
    // SAFETY: the command takes no argument.
    let flags = cvt(unsafe { fcntl(handle.as_raw(), F_GETFL) })?;
    let new = if nonblocking {
        flags | O_NONBLOCK
    } else {
        flags & !O_NONBLOCK
    };
    if new != flags {
        // SAFETY: the command takes an `int`, passed as the variadic
        // argument.
        cvt(unsafe { fcntl(handle.as_raw(), F_SETFL, new) })?;
    }
    Ok(())
}