artifactize-foundation 0.27.1

Native file, path and executable primitives for Artifactize.
Documentation
//! The pipe ends a child held before exec gives back.
//!
//! A forked child holds a copy of every descriptor its parent had open at the fork, including
//! the pipes of runs that were starting at the same time. Close-on-exec drops those copies only
//! at exec, and a gated child waits for its admission before it execs, so until then another
//! run's output pipe could not reach its end. The child therefore closes, before it waits, each
//! inherited pipe end whose other end it holds as well: such a pair is another run's pipe that
//! this child never uses. A lone write end is kept, because std reports a failed exec through
//! one whose read end only the parent holds.

use std::{io, os::fd::RawFd};

/// Reserve proportional headroom for other evals opening pipes concurrently.
#[cfg(not(target_os = "macos"))]
const DESCRIPTOR_HEADROOM_FACTOR: usize = 2;

/// Fixed room for bursts of descriptors opened between [`Inherited::reserve`] and the fork: the forked child cannot allocate, and a descriptor it has
/// no room for is only kept open until exec, as without this release.
#[cfg(not(target_os = "macos"))]
const SPARE_DESCRIPTORS: usize = 64;

/// One end of a pipe this process holds: which end it is, and which end it pairs with.
#[derive(Clone, Copy)]
struct PipeEnd {
    fd: RawFd,
    end: Key,
    peer: Key,
    #[cfg(target_os = "macos")]
    stat: EndIdentity,
}

/// Identifies one end of one pipe within this process: on Linux the pipe's inode and the end's
/// direction, on macOS the end's own handle.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[cfg(not(target_os = "macos"))]
struct Key(u64, Direction);

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[cfg(target_os = "macos")]
struct Key(u64);

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[cfg(not(target_os = "macos"))]
enum Direction {
    Read,
    Write,
}

#[cfg(not(target_os = "macos"))]
impl Direction {
    fn peer(self) -> Self {
        match self {
            Self::Read => Self::Write,
            Self::Write => Self::Read,
        }
    }
}

/// Memory or a native descriptor snapshot prepared before the fork.
pub(super) struct Inherited {
    ends: Vec<PipeEnd>,
}

impl Inherited {
    /// Keep Darwin's libproc calls on the parent side of fork. The child compares
    /// descriptor identities before using the snapshot, since other threads may close or
    /// reuse descriptors between the query and the fork.
    #[cfg(target_os = "macos")]
    pub(super) fn reserve() -> Self {
        Self {
            ends: snapshot().unwrap_or_default(),
        }
    }

    #[cfg(not(target_os = "macos"))]
    pub(super) fn reserve() -> Self {
        let capacity = open_descriptors()
            .unwrap_or(0)
            .saturating_mul(DESCRIPTOR_HEADROOM_FACTOR)
            .saturating_add(SPARE_DESCRIPTORS);
        Self {
            ends: Vec::with_capacity(capacity),
        }
    }

    /// In the forked child, before it waits for admission: close every inherited close-on-exec
    /// pipe end whose other end this child holds too, except `keep`.
    ///
    /// Only async-signal-safe system calls run here, on memory reserved before the fork.
    pub(super) fn release(&mut self, keep: RawFd) {
        #[cfg(not(target_os = "macos"))]
        {
            self.ends.clear();
            self.collect(keep);
        }
        #[cfg(target_os = "macos")]
        self.ends
            .retain(|end| inherited(end.fd, keep) && EndIdentity::read(end.fd) == Some(end.stat));
        self.ends.sort_unstable_by_key(|end| end.end);
        for end in &self.ends {
            if self
                .ends
                .binary_search_by_key(&end.peer, |other| other.end)
                .is_ok()
            {
                // SAFETY: `fd` was listed open in this single-threaded child and is not
                // `keep`; exec would close it anyway, as it is close-on-exec.
                unsafe { libc::close(end.fd) };
            }
        }
    }
}

#[cfg(not(target_os = "macos"))]
fn push(ends: &mut Vec<PipeEnd>, end: PipeEnd) {
    // Pushing past the reserved capacity would allocate in the forked child.
    if ends.len() < ends.capacity() {
        ends.push(end);
    }
}

/// Whether `fd` is one of artifactize's own: close-on-exec, above the standard streams.
fn inherited(fd: RawFd, keep: RawFd) -> bool {
    if fd <= libc::STDERR_FILENO || fd == keep {
        return false;
    }
    // SAFETY: F_GETFD only reads this process's descriptor flags.
    let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) };
    flags >= 0 && flags & libc::FD_CLOEXEC != 0
}

/// The descriptors open in this process.
#[cfg(not(target_os = "macos"))]
fn open_descriptors() -> io::Result<usize> {
    Ok(std::fs::read_dir("/proc/self/fd")?.count())
}

/// One `getdents64` batch of directory records, on the forked child's stack.
#[cfg(not(target_os = "macos"))]
const DIRECTORY_BUFFER_BYTES: usize = 4096;

#[cfg(not(target_os = "macos"))]
impl Inherited {
    /// RawDir uses getdents64 rather than readdir: it never allocates in the child.
    fn collect(&mut self, keep: RawFd) {
        use rustix::fs::{Mode, OFlags, RawDir, open};
        use std::{mem::MaybeUninit, os::fd::AsRawFd};

        let Ok(directory) = open(
            c"/proc/self/fd",
            OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
            Mode::empty(),
        ) else {
            return;
        };
        let directory_fd = directory.as_raw_fd();
        let mut buffer = [MaybeUninit::uninit(); DIRECTORY_BUFFER_BYTES];
        let mut entries = RawDir::new(directory, &mut buffer);
        while let Some(Ok(entry)) = entries.next() {
            if let Some(fd) = descriptor(entry.file_name().to_bytes())
                && fd != directory_fd
                && inherited(fd, keep)
                && let Some(end) = pipe_end(fd)
            {
                push(&mut self.ends, end);
            }
        }
    }
}

/// Leave only the Linux reaper's status socket open, without allocating after fork.
#[cfg(target_os = "linux")]
pub(super) fn close_except(keep: RawFd) -> io::Result<()> {
    use rustix::fs::{Mode, OFlags, RawDir, open};
    use std::{mem::MaybeUninit, os::fd::AsRawFd};

    // SAFETY: the reaper owns this fd table and neither range includes the socket.
    unsafe {
        let keep = keep as u32;
        if (keep == 0 || libc::syscall(libc::SYS_close_range, 0_u32, keep - 1, 0_u32) == 0)
            && libc::syscall(libc::SYS_close_range, keep + 1, u32::MAX, 0_u32) == 0
        {
            return Ok(());
        }
    }
    // Older kernels may support pidfds, but not close_range yet.
    let directory = open(
        c"/proc/self/fd",
        OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
        Mode::empty(),
    )?;
    let directory_fd = directory.as_raw_fd();
    let mut buffer = [MaybeUninit::uninit(); DIRECTORY_BUFFER_BYTES];
    let mut entries = RawDir::new(directory, &mut buffer);
    while let Some(entry) = entries.next() {
        if let Some(fd) = descriptor(entry?.file_name().to_bytes())
            && fd != directory_fd
            && fd != keep
        {
            // SAFETY: this is a listed open descriptor in the reaper's private fd table.
            unsafe { libc::close(fd) };
        }
    }
    Ok(())
}

/// The descriptor a `/proc/self/fd` entry names: its decimal digits.
#[cfg(not(target_os = "macos"))]
fn descriptor(name: &[u8]) -> Option<RawFd> {
    if name.is_empty() {
        return None;
    }
    name.iter().try_fold(0 as RawFd, |fd, &byte| {
        let digit = RawFd::from(byte.checked_sub(b'0').filter(|digit| *digit <= 9)?);
        fd.checked_mul(10)?.checked_add(digit)
    })
}

/// Both ends of a Linux pipe share its inode; the access mode tells them apart.
#[cfg(not(target_os = "macos"))]
fn pipe_end(fd: RawFd) -> Option<PipeEnd> {
    let mut stat = std::mem::MaybeUninit::<libc::stat>::uninit();
    // SAFETY: fstat writes a complete stat on success, which is checked before reading it.
    let stat = unsafe {
        if libc::fstat(fd, stat.as_mut_ptr()) != 0 {
            return None;
        }
        stat.assume_init()
    };
    if stat.st_mode & libc::S_IFMT != libc::S_IFIFO {
        return None;
    }
    // SAFETY: F_GETFL only reads this descriptor's status flags.
    let mode = unsafe { libc::fcntl(fd, libc::F_GETFL) };
    let direction = match mode {
        ..0 => return None,
        mode if mode & libc::O_ACCMODE == libc::O_RDONLY => Direction::Read,
        mode if mode & libc::O_ACCMODE == libc::O_WRONLY => Direction::Write,
        // A FIFO opened for both reading and writing is no pipe of a run.
        _ => return None,
    };
    let inode = stat.st_ino;
    Some(PipeEnd {
        fd,
        end: Key(inode, direction),
        peer: Key(inode, direction.peer()),
    })
}

/// Darwin sys/proc_info.h `struct proc_fileinfo`.
#[cfg(target_os = "macos")]
#[repr(C)]
struct ProcFileInfo {
    open_flags: u32,
    status: u32,
    offset: libc::off_t,
    kind: i32,
    guard_flags: u32,
}

/// Darwin sys/proc_info.h `struct pipe_info`: each end has its own handle and names its peer.
#[cfg(target_os = "macos")]
#[repr(C)]
struct PipeInfo {
    stat: libc::vinfo_stat,
    handle: u64,
    peer_handle: u64,
    status: i32,
    reserved: i32,
}

/// Darwin sys/proc_info.h `struct pipe_fdinfo`.
#[cfg(target_os = "macos")]
#[repr(C)]
struct PipeFdInfo {
    file: ProcFileInfo,
    pipe: PipeInfo,
}

/// Darwin sys/proc_info.h `PROC_PIDFDPIPEINFO`.
#[cfg(target_os = "macos")]
const PROC_PIDFDPIPEINFO: libc::c_int = 6;

#[cfg(target_os = "macos")]
fn snapshot() -> io::Result<Vec<PipeEnd>> {
    let pid = libc::pid_t::try_from(std::process::id()).map_err(io::Error::other)?;
    // SAFETY: asking libproc for the descriptor list capacity without a buffer.
    let bytes =
        unsafe { libc::proc_pidinfo(pid, libc::PROC_PIDLISTFDS, 0, std::ptr::null_mut(), 0) };
    if bytes <= 0 {
        return Err(io::Error::last_os_error());
    }
    let capacity = bytes as usize / std::mem::size_of::<libc::proc_fdinfo>();
    let mut descriptors = vec![
        libc::proc_fdinfo {
            proc_fd: 0,
            proc_fdtype: 0
        };
        capacity
    ];
    // SAFETY: the aligned slice holds the supplied number of complete records.
    let written = unsafe {
        libc::proc_pidinfo(
            pid,
            libc::PROC_PIDLISTFDS,
            0,
            descriptors.as_mut_ptr().cast(),
            std::mem::size_of_val(descriptors.as_slice()) as i32,
        )
    };
    if written < 0 {
        return Err(io::Error::last_os_error());
    }
    let count = written as usize / std::mem::size_of::<libc::proc_fdinfo>();
    Ok(descriptors
        .into_iter()
        .take(count)
        .filter(|entry| entry.proc_fdtype == libc::PROX_FDTYPE_PIPE as u32)
        .filter_map(|entry| pipe_end(pid, entry.proc_fd))
        .collect())
}

/// Darwin fstat gives each pipe end a different inode. Use it to validate an end
/// identified by libproc in the parent, not to infer a relationship between ends.
#[cfg(target_os = "macos")]
#[derive(Clone, Copy, PartialEq, Eq)]
struct EndIdentity {
    inode: libc::ino_t,
    birth: (libc::time_t, libc::c_long),
}

#[cfg(target_os = "macos")]
impl EndIdentity {
    fn read(fd: RawFd) -> Option<Self> {
        let mut stat = std::mem::MaybeUninit::<libc::stat>::uninit();
        // SAFETY: fstat is async-signal-safe and fills the record on success.
        let stat = unsafe {
            if libc::fstat(fd, stat.as_mut_ptr()) != 0 {
                return None;
            }
            stat.assume_init()
        };
        (stat.st_mode & libc::S_IFMT == libc::S_IFIFO).then_some(Self {
            inode: stat.st_ino,
            birth: (stat.st_birthtime, stat.st_birthtime_nsec),
        })
    }
}

#[cfg(target_os = "macos")]
fn pipe_end(pid: libc::pid_t, fd: RawFd) -> Option<PipeEnd> {
    let stat = EndIdentity::read(fd)?;
    let mut info = std::mem::MaybeUninit::<PipeFdInfo>::uninit();
    let size = libc::c_int::try_from(std::mem::size_of::<PipeFdInfo>()).ok()?;
    // SAFETY: libproc writes a complete record of exactly `size` bytes on success, which is
    // checked before reading it.
    let info = unsafe {
        if libc::proc_pidfdinfo(pid, fd, PROC_PIDFDPIPEINFO, info.as_mut_ptr().cast(), size) != size
        {
            return None;
        }
        info.assume_init()
    };
    // A pipe whose other end is closed everywhere names no peer.
    if info.pipe.peer_handle == 0 || EndIdentity::read(fd) != Some(stat) {
        return None;
    }
    Some(PipeEnd {
        fd,
        end: Key(info.pipe.handle),
        peer: Key(info.pipe.peer_handle),
        stat,
    })
}