dope-sys 0.77.0

Typed operating-system call contracts
Documentation
use std::{
    mem::MaybeUninit,
    os::fd::{AsRawFd, BorrowedFd, OwnedFd, RawFd},
    slice,
};

use o3::{
    base::num::bounded,
    buffer::bytes::{self, bounded::MAX},
};

use crate::{Errno, io, kernel};
use io::{
    fd,
    file::{self, metadata::Metadata, watch},
};
use kernel::errno;

/// # Safety
/// Descriptors stay fixed until owner drop; names retain exclusive storage through borrowing.
/// Watches retain registration; events borrow only admitted records.
pub unsafe trait Directory: kernel::raw::Source {
    type Stream;
    type Watch;
    type Events<'a>: Iterator<Item = watch::Event<'a>>;

    /// # Safety
    /// Bytes contain complete initialized native records for this watch,
    /// including nonzero event masks.
    unsafe fn watch_events<'a>(watch: &Self::Watch, bytes: &'a [u8]) -> Self::Events<'a>;

    fn open_dir<E: From<Errno>>(path: &std::ffi::CStr) -> Result<Self::Stream, file::OpenError<E>>
    where
        Self: file::File,
    {
        let file = Self::open(
            path,
            file::Open::DIRECTORY | file::Open::CLOSE_ON_EXEC,
            file::Mode::new(0),
        )
        .map_err(file::OpenError::Syscall)?;
        Self::from_fd(file)
    }

    fn from_fd<E: From<Errno>>(file: OwnedFd) -> Result<Self::Stream, file::OpenError<E>>;
    fn descriptor(stream: &Self::Stream) -> kernel::raw::Descriptor;
    fn next(stream: &mut Self::Stream) -> Result<Option<file::Entry<'_>>, Errno>;
}

/// # Safety
/// Each decoded success retains the uniquely transferred descriptor until
/// delivery or reclamation.
pub unsafe trait Completion {
    type Outcome;
    type Invalid;

    /// # Safety
    /// A successful outcome transfers one live descriptor from a completed
    /// open operation. Its descriptor has not been decoded or reclaimed before.
    unsafe fn open(outcome: Self::Outcome) -> Result<Result<OwnedFd, Errno>, Self::Invalid>;
}

pub(super) fn parent(dir: Option<BorrowedFd<'_>>) -> RawFd {
    dir.as_ref().map_or(libc::AT_FDCWD, AsRawFd::as_raw_fd)
}

unsafe fn completed<S: kernel::raw::Source + ?Sized, E: From<Errno>>(
    result: libc::c_int,
    output: &MaybeUninit<libc::stat>,
) -> Result<Metadata, E> {
    // SAFETY: the caller pairs one stat call's unchanged status with its destination.
    unsafe {
        io::raw::status::<S, E>(result)?;
        Ok(Metadata::new(output.assume_init_ref()))
    }
}

pub(super) fn unlink_at<S: kernel::raw::Source + ?Sized, E: From<Errno>>(
    dir: Option<BorrowedFd<'_>>,
    path: &std::ffi::CStr,
    flags: libc::c_int,
) -> Result<(), E> {
    // SAFETY: both calls borrow the terminated path and any supplied parent through their status.
    unsafe {
        let result = match (dir, flags) {
            (None, 0) => libc::unlink(path.as_ptr()),
            (dir, flags) => libc::unlinkat(parent(dir), path.as_ptr(), flags),
        };
        io::raw::status::<S, E>(result)
    }
}

pub(super) fn entries<S: Directory>(
    stream: &mut S::Stream,
) -> (BorrowedFd<'_>, file::Entries<'_, S>) {
    let fd = S::descriptor(stream);
    // SAFETY: the descriptor is fixed until stream drop; this loan keeps its owner live.
    (
        unsafe { BorrowedFd::borrow_raw(fd.get()) },
        file::Entries(stream),
    )
}

pub(super) fn open<S: errno::Source + ?Sized, E: From<Errno>>(
    parent: Option<BorrowedFd<'_>>,
    path: &std::ffi::CStr,
    flags: file::Open,
    mode: file::Mode,
) -> Result<OwnedFd, E> {
    let flags = flags.raw();
    let mode = mode.raw() as libc::mode_t as libc::c_uint;
    // SAFETY: the terminated path and optional parent stay borrowed; success transfers the new descriptor.
    unsafe {
        let result = match parent {
            Some(dir) => libc::openat(dir.as_raw_fd(), path.as_ptr(), flags, mode),
            None => libc::open(path.as_ptr(), flags, mode),
        };
        <OwnedFd as fd::raw::Adopt>::try_adopt::<S, E>(result)
    }
}

pub(super) fn stat<S: errno::Source + ?Sized, E: From<Errno>, const NO_FOLLOW: bool>(
    dir: Option<BorrowedFd<'_>>,
    path: &std::ffi::CStr,
) -> Result<Metadata, E> {
    let mut output = MaybeUninit::uninit();
    // SAFETY: each call borrows the path and initializes this output only on success.
    unsafe {
        let result = if NO_FOLLOW {
            libc::fstatat(
                parent(dir),
                path.as_ptr(),
                output.as_mut_ptr(),
                libc::AT_SYMLINK_NOFOLLOW,
            )
        } else {
            libc::stat(path.as_ptr(), output.as_mut_ptr())
        };
        completed::<S, E>(result, &output)
    }
}

pub(super) fn rename<S: errno::Source + ?Sized, E: From<Errno>>(
    dir: Option<BorrowedFd<'_>>,
    old: &std::ffi::CStr,
    new: &std::ffi::CStr,
) -> Result<(), E> {
    // SAFETY: both terminated names and the common parent, when present, outlive the call.
    unsafe {
        let result = match dir {
            Some(dir) => {
                libc::renameat(dir.as_raw_fd(), old.as_ptr(), dir.as_raw_fd(), new.as_ptr())
            }
            None => libc::rename(old.as_ptr(), new.as_ptr()),
        };
        io::raw::status::<S, E>(result)
    }
}

pub(super) fn read<'a, S: kernel::raw::Source + ?Sized, E: From<Errno>>(
    file: BorrowedFd<'_>,
    output: &'a mut [MaybeUninit<u8>],
    offset: file::Offset,
) -> Result<&'a mut [u8], E> {
    // SAFETY: pread initializes the returned prefix only, retains the descriptor and accepts this off_t.
    unsafe {
        let count = libc::pread(
            file.as_raw_fd(),
            output.as_mut_ptr().cast(),
            output.len(),
            offset.get() as libc::off_t,
        );
        Ok(io::raw::Buffer::try_native::<S, E>(output, count)?.assume_init_mut())
    }
}

pub(super) fn metadata<S: errno::Source + ?Sized, E: From<Errno>>(
    file: BorrowedFd<'_>,
) -> Result<Metadata, E> {
    let mut output = MaybeUninit::uninit();
    // SAFETY: only a successful fstat initializes this destination.
    unsafe {
        let result = libc::fstat(file.as_raw_fd(), output.as_mut_ptr());
        completed::<S, E>(result, &output)
    }
}

pub(super) fn mkdir<S: errno::Source + ?Sized, E: From<Errno>>(
    path: &std::ffi::CStr,
    mode: file::Mode,
) -> Result<(), E> {
    // SAFETY: the path is terminated and remains borrowed through the native result.
    unsafe { io::raw::status::<S, E>(libc::mkdir(path.as_ptr(), mode.raw() as libc::mode_t)) }
}

pub(super) fn try_lock<S: errno::Source + ?Sized, E: From<Errno>>(
    file: BorrowedFd<'_>,
) -> Result<(), E> {
    // SAFETY: this nonblocking exclusive admission borrows the descriptor and captures the exact errno.
    unsafe { io::raw::status::<S, E>(libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB)) }
}

pub(super) fn sync<S: errno::Source + ?Sized, E: From<Errno>>(
    file: BorrowedFd<'_>,
) -> Result<(), E> {
    // SAFETY: fsync borrows the descriptor and returns zero or -1 with errno.
    unsafe { io::raw::status::<S, E>(libc::fsync(file.as_raw_fd())) }
}

pub(super) fn truncate<S: errno::Source + ?Sized, E: From<Errno>>(
    file: BorrowedFd<'_>,
    len: i64,
) -> Result<(), E> {
    // SAFETY: ftruncate borrows the descriptor and returns zero or -1 with errno.
    unsafe { io::raw::status::<S, E>(libc::ftruncate(file.as_raw_fd(), len)) }
}

pub(super) fn read_at<'a, S: errno::Source + ?Sized, E: From<Errno>>(
    file: BorrowedFd<'_>,
    output: &'a mut [u8],
    offset: file::Offset,
) -> Result<&'a mut [u8], E> {
    // SAFETY: pread writes only initialized bytes and cannot invalidate the rest of the original slice.
    let output = unsafe { slice::from_raw_parts_mut(output.as_mut_ptr().cast(), output.len()) };
    read::<S, E>(file, output, offset)
}

pub(super) fn write_at<S: errno::Source + ?Sized, E: From<Errno>>(
    file: BorrowedFd<'_>,
    input: bytes::Prefix<'_, MAX>,
    offset: file::Offset,
) -> Result<bounded::raw::U32<0, { MAX as u32 }>, E> {
    let input = input.as_slice();
    // SAFETY: the admitted input bounds a completed write to i32::MAX and the offset fits off_t.
    unsafe {
        let count = libc::pwrite(
            file.as_raw_fd(),
            input.as_ptr().cast(),
            input.len(),
            offset.get() as libc::off_t,
        );
        Ok(kernel::raw::Status::from_count(count)
            .try_count::<S, E>()?
            .bounded())
    }
}