dope-sys 0.77.0

Typed operating-system call contracts
Documentation
use std::{
    mem::MaybeUninit,
    os::fd::{self, AsRawFd as _, BorrowedFd, IntoRawFd as _, OwnedFd},
};

use crate::{Errno, io, kernel};
use kernel::errno;

pub(super) fn try_limit<S: errno::Source + ?Sized>() -> Result<(libc::rlim_t, libc::rlim_t), Errno>
{
    let mut limit = MaybeUninit::uninit();
    // SAFETY: getrlimit initializes both fields on success and leaves errno on failure.
    let limit = unsafe {
        let status = libc::getrlimit(libc::RLIMIT_NOFILE, limit.as_mut_ptr());
        kernel::raw::Status::new(status).try_zero::<S, Errno>()?;
        limit.assume_init()
    };
    Ok((limit.rlim_cur, limit.rlim_max))
}

pub(super) fn close<S: errno::Source + ?Sized, E: From<Errno>>(file: OwnedFd) -> Result<(), E> {
    // SAFETY: close takes this descriptor once and reports zero or -1 with errno.
    unsafe { kernel::raw::Status::new(libc::close(file.into_raw_fd())).try_zero::<S, E>() }
}

pub(super) fn duplicate<S: errno::Source + ?Sized, E: From<Errno>>(
    file: BorrowedFd<'_>,
) -> Result<OwnedFd, E> {
    // SAFETY: this command returns a fresh descriptor or -1 with errno.
    unsafe { OwnedFd::try_adopt::<S, E>(libc::fcntl(file.as_raw_fd(), libc::F_DUPFD_CLOEXEC, 0)) }
}

pub(super) fn read<'a, S: errno::Source + ?Sized, E: From<Errno>>(
    file: BorrowedFd<'_>,
    output: &'a mut [u8],
) -> Result<&'a mut [u8], E> {
    // SAFETY: read initializes at most this exclusive output extent or sets errno.
    unsafe {
        let raw = libc::read(file.as_raw_fd(), output.as_mut_ptr().cast(), output.len());
        io::raw::Buffer::try_native::<S, E>(output, raw)
    }
}

pub(super) fn try_write<'a, S: errno::Source + ?Sized, E: From<Errno>>(
    file: BorrowedFd<'_>,
    input: &'a [u8],
) -> Result<&'a [u8], E> {
    // SAFETY: write consumes at most this immutable input extent or sets errno.
    unsafe { io::raw::Buffer::try_native::<S, E>(input, write(file, input)) }
}

/// Fallible descriptor decoding preserving the standard ownership contract.
pub trait Adopt: fd::FromRawFd + Sized {
    /// # Safety
    /// `raw` is -1 or transfers one live descriptor; failure leaves this thread's
    /// positive errno unchanged for `S` to read.
    unsafe fn try_adopt<S: kernel::raw::Source + ?Sized, E: From<Errno>>(
        raw: fd::RawFd,
    ) -> Result<Self, E> {
        // SAFETY: the caller retains the native return and unchanged failure errno.
        let value = unsafe { kernel::raw::Status::new(raw).try_value::<S, E>() }?;
        // SAFETY: the nonnegative syscall result transfers this descriptor.
        Ok(unsafe { Self::from_raw_fd(value.get()) })
    }
}

impl<T: fd::FromRawFd> Adopt for T {}

pub(super) fn flags<
    S: errno::Source + ?Sized,
    F: super::Flags,
    const SET: bool,
    const RETRY: bool,
>(
    file: BorrowedFd<'_>,
    flags: libc::c_int,
) -> Result<libc::c_int, Errno> {
    const {
        assert!(matches!(
            (F::READ, F::WRITE),
            (libc::F_GETFD, libc::F_SETFD) | (libc::F_GETFL, libc::F_SETFL)
        ));
    }
    loop {
        // SAFETY: set returns zero, get returns a scalar; each failure leaves errno.
        let result = unsafe {
            if SET {
                let status = libc::fcntl(file.as_raw_fd(), F::WRITE, flags);
                kernel::raw::Status::new(status)
                    .try_zero::<S, Errno>()
                    .and(Ok(0))
            } else {
                let status = libc::fcntl(file.as_raw_fd(), F::READ);
                kernel::raw::Status::new(status)
                    .try_value::<S, Errno>()
                    .map(kernel::Value::get)
            }
        };
        match result {
            Err(error) if RETRY && error.is_intr() => continue,
            result => return result,
        }
    }
}

pub(crate) fn write(file: BorrowedFd<'_>, input: &[u8]) -> libc::ssize_t {
    // SAFETY: the borrowed descriptor and input remain live through this write.
    unsafe { libc::write(file.as_raw_fd(), input.as_ptr().cast(), input.len()) }
}