oscall 0.1.0

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

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

/// `O_CLOEXEC`, the same on every architecture.
const O_CLOEXEC: usize = 0o2000000;
/// `IOV_MAX`: more buffers than this make `readv` fail.
const IOV_MAX: usize = 1024;

const F_GETFD: usize = 1;
const F_GETFL: usize = 3;
const F_SETFL: usize = 4;
/// The same on every architecture oscall has (asm-generic/fcntl.h).
const O_NONBLOCK: usize = 0o4000;
const F_SETFD: usize = 2;
const F_DUPFD_CLOEXEC: usize = 1030;
const FD_CLOEXEC: usize = 1;

const TIOCGWINSZ: usize = 0x5413;

const SEEK_SET: usize = 0;
const SEEK_CUR: usize = 1;
const SEEK_END: usize = 2;

/// `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
    }
}

/// `fcntl`, by the name it has on the target: 32-bit architectures only
/// have, or should use, `fcntl64`.
///
/// # Safety
///
/// As the command requires.
pub(crate) unsafe fn fcntl(fd: i32, cmd: usize, arg: usize) -> Result<usize> {
    #[cfg(target_pointer_width = "32")]
    // SAFETY: the caller upholds what the command requires.
    return unsafe { syscall!(FCNTL64, fd, cmd, arg) };
    #[cfg(target_pointer_width = "64")]
    // SAFETY: the caller upholds what the command requires.
    return unsafe { syscall!(FCNTL, fd, cmd, arg) };
}

/// The two halves of a file offset, as `preadv` and `pwritev` take them:
/// the low `long` first, then the high one, which a 64-bit kernel ignores.
#[inline]
fn halves(offset: u64) -> (usize, usize) {
    #[cfg(target_pointer_width = "32")]
    return (offset as usize, (offset >> 32) as usize);
    #[cfg(target_pointer_width = "64")]
    return (offset as usize, 0);
}

pub(crate) fn read(handle: BorrowedHandle<'_>, buf: &mut [u8]) -> Result<usize> {
    // SAFETY: `buf` is writable for its length.
    unsafe { syscall!(READ, handle.as_raw(), buf.as_mut_ptr(), buf.len()) }
}

pub(crate) fn write(handle: BorrowedHandle<'_>, buf: &[u8]) -> Result<usize> {
    // SAFETY: `buf` is readable for its length.
    unsafe { syscall!(WRITE, handle.as_raw(), buf.as_ptr(), buf.len()) }
}

// Positional I/O goes through `preadv` and `pwritev`, which take the offset
// as two `long`s on every architecture: `pread64` takes a 64-bit argument,
// whose registers differ between the 32-bit architectures.

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 (low, high) = halves(offset);
    // SAFETY: one `iovec` that describes `buf`, writable for its length.
    unsafe { syscall!(PREADV, handle.as_raw(), &raw const iov, 1, low, high) }
}

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 (low, high) = halves(offset);
    // SAFETY: one `iovec` that describes `buf`, which is only read.
    unsafe { syscall!(PWRITEV, handle.as_raw(), &raw const iov, 1, low, high) }
}

pub(crate) fn read_vectored(
    handle: BorrowedHandle<'_>,
    bufs: &mut [IoSliceMut<'_>],
) -> Result<usize> {
    let count = bufs.len().min(IOV_MAX);
    // SAFETY: `IoSliceMut` is a transparent `iovec` over a writable buffer.
    unsafe { syscall!(READV, handle.as_raw(), bufs.as_mut_ptr(), count) }
}

pub(crate) fn write_vectored(handle: BorrowedHandle<'_>, bufs: &[IoSlice<'_>]) -> Result<usize> {
    let count = bufs.len().min(IOV_MAX);
    // SAFETY: `IoSlice` is a transparent `iovec` over a readable buffer.
    unsafe { syscall!(WRITEV, handle.as_raw(), bufs.as_ptr(), count) }
}

pub(crate) fn seek(handle: BorrowedHandle<'_>, pos: SeekFrom) -> Result<u64> {
    let (offset, whence) = match pos {
        SeekFrom::Start(offset) => (offset as i64, SEEK_SET),
        SeekFrom::Current(offset) => (offset, SEEK_CUR),
        SeekFrom::End(offset) => (offset, SEEK_END),
    };
    #[cfg(target_pointer_width = "64")]
    // SAFETY: no memory is involved.
    return unsafe { syscall!(LSEEK, handle.as_raw(), offset, whence) }.map(|pos| pos as u64);
    #[cfg(target_pointer_width = "32")]
    {
        let mut result = 0u64;
        let high = (offset >> 32) as usize;
        let low = offset as usize;
        // riscv32 names the same call without the underscore.
        #[cfg(not(target_arch = "riscv32"))]
        // SAFETY: `result` is a writable `loff_t`.
        unsafe { syscall!(_LLSEEK, handle.as_raw(), high, low, &raw mut result, whence) }?;
        #[cfg(target_arch = "riscv32")]
        // SAFETY: `result` is a writable `loff_t`.
        unsafe { syscall!(LLSEEK, handle.as_raw(), high, low, &raw mut result, whence) }?;
        Ok(result)
    }
}

pub(crate) fn pipe() -> Result<(OwnedHandle, OwnedHandle)> {
    let mut fds = [0i32; 2];
    // SAFETY: `fds` is the two descriptors the call writes.
    unsafe { syscall!(PIPE2, fds.as_mut_ptr(), O_CLOEXEC) }?;
    // SAFETY: both descriptors were just created and are owned by nobody.
    Ok(unsafe { (OwnedHandle::from_raw(fds[0]), OwnedHandle::from_raw(fds[1])) })
}

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

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 {
    // `struct winsize`: four `unsigned short`. Only terminals answer.
    let mut size = [0u16; 4];
    // SAFETY: the request writes a `struct winsize`.
    unsafe { syscall!(IOCTL, handle.as_raw(), TIOCGWINSZ, size.as_mut_ptr()) }.is_ok()
}

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 integer.
    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 = unsafe { fcntl(handle.as_raw(), F_GETFD, 0) }?;
    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 = unsafe { fcntl(handle.as_raw(), F_GETFL, 0) }?;
    let new = if nonblocking {
        flags | O_NONBLOCK
    } else {
        flags & !O_NONBLOCK
    };
    if new != flags {
        // SAFETY: the command takes an integer.
        unsafe { fcntl(handle.as_raw(), F_SETFL, new) }?;
    }
    Ok(())
}