artifactize-foundation 0.27.1

Native file, path and executable primitives for Artifactize.
Documentation
use std::{
    io, mem,
    os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle},
    ptr,
    time::{Duration, Instant},
};
use windows_sys::Win32::{
    Foundation::{
        ERROR_INVALID_PARAMETER, ERROR_MORE_DATA, WAIT_FAILED, WAIT_OBJECT_0, WAIT_TIMEOUT,
    },
    System::{
        JobObjects::{
            AssignProcessToJobObject, CreateJobObjectW, IsProcessInJob,
            JOB_OBJECT_LIMIT_ACTIVE_PROCESS, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
            JOBOBJECT_BASIC_ACCOUNTING_INFORMATION, JOBOBJECT_BASIC_LIMIT_INFORMATION,
            JOBOBJECT_BASIC_PROCESS_ID_LIST, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
            JobObjectBasicAccountingInformation, JobObjectBasicProcessIdList,
            JobObjectExtendedLimitInformation, QueryInformationJobObject, SetInformationJobObject,
            TerminateJobObject,
        },
        Threading::{
            OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE,
            WaitForSingleObject,
        },
    },
};

// A killed process must not look like it exited successfully.
const FORCED_TERMINATION_EXIT_CODE: u32 = 1;

/// A job whose processes all die when its last handle closes, artifactize's included.
pub(super) struct Job(OwnedHandle);

impl Job {
    pub(super) fn new() -> io::Result<Self> {
        // SAFETY: no attributes and no name create a private, non-inheritable job.
        let handle = unsafe { CreateJobObjectW(ptr::null(), ptr::null()) };
        if handle.is_null() {
            return Err(io::Error::last_os_error());
        }
        // SAFETY: CreateJobObjectW returned a new handle that nothing else owns.
        let job = Self(unsafe { OwnedHandle::from_raw_handle(handle) });
        job.limit(JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE)?;
        Ok(job)
    }

    /// Set the job's limits to exactly `flags`.
    fn limit(&self, flags: u32) -> io::Result<()> {
        let limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION {
            BasicLimitInformation: JOBOBJECT_BASIC_LIMIT_INFORMATION {
                LimitFlags: flags,
                ActiveProcessLimit: 0,
                ..Default::default()
            },
            ..Default::default()
        };
        // SAFETY: the information class matches the structure and its size.
        let ok = unsafe {
            SetInformationJobObject(
                self.0.as_raw_handle(),
                JobObjectExtendedLimitInformation,
                (&raw const limits).cast(),
                mem::size_of_val(&limits) as u32,
            )
        };
        if ok == 0 {
            return Err(io::Error::last_os_error());
        }
        Ok(())
    }

    /// Closing the job no longer kills its processes.
    pub(super) fn keep_on_close(&self) -> io::Result<()> {
        self.limit(0)
    }

    pub(super) fn assign(&self, child: &tokio::process::Child) -> io::Result<()> {
        let process = child
            .raw_handle()
            .expect("a newly spawned child has a process handle");
        // SAFETY: both handles are open.
        if unsafe { AssignProcessToJobObject(self.0.as_raw_handle(), process) } == 0 {
            return Err(io::Error::last_os_error());
        }
        Ok(())
    }

    pub(super) fn active_processes(&self) -> io::Result<u32> {
        let mut info = JOBOBJECT_BASIC_ACCOUNTING_INFORMATION::default();
        // SAFETY: the open Job handle and information-class-matching writable
        // buffer remain valid for the exact supplied buffer size.
        if unsafe {
            QueryInformationJobObject(
                self.0.as_raw_handle(),
                JobObjectBasicAccountingInformation,
                (&raw mut info).cast(),
                mem::size_of_val(&info) as u32,
                ptr::null_mut(),
            )
        } == 0
        {
            return Err(io::Error::last_os_error());
        }
        Ok(info.ActiveProcesses)
    }

    pub(super) fn processes_for_cleanup(&self) -> io::Result<Vec<OwnedHandle>> {
        // Stop new assignments (including children trying to spawn) before taking the
        // snapshot. Unlike a zero active count, these handles also observe native rundown.
        self.limit(JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_ACTIVE_PROCESS)?;
        let (buffer, count) = self.process_list()?;
        buffer[PROCESS_LIST_HEADER..][..count]
            .iter()
            .filter_map(|&pid| self.open_member(pid as u32).transpose())
            .collect()
    }

    fn process_list(&self) -> io::Result<(Vec<usize>, usize)> {
        // Avoid a second native query for the usual small process tree.
        const INITIAL_CAPACITY: usize = 16;
        let mut buffer = vec![0usize; PROCESS_LIST_HEADER + INITIAL_CAPACITY];
        loop {
            let size = u32::try_from(mem::size_of_val(buffer.as_slice()))
                .map_err(|_| io::ErrorKind::InvalidData)?;
            let data = buffer
                .as_mut_ptr()
                .cast::<JOBOBJECT_BASIC_PROCESS_ID_LIST>();
            // SAFETY: the buffer is initialized, aligned to the pointer-sized items and
            // large enough for the header and all the entries we told Windows it can write.
            let result = unsafe {
                QueryInformationJobObject(
                    self.0.as_raw_handle(),
                    JobObjectBasicProcessIdList,
                    data.cast(),
                    size,
                    ptr::null_mut(),
                )
            };
            // SAFETY: the aligned buffer contains at least the whole declared structure.
            let header = unsafe { &*data };
            let available = buffer.len() - PROCESS_LIST_HEADER;
            if result != 0 {
                let count = header.NumberOfProcessIdsInList as usize;
                if count > available {
                    return Err(io::ErrorKind::InvalidData.into());
                }
                return Ok((buffer, count));
            }
            let error = io::Error::last_os_error();
            let needed = header.NumberOfAssignedProcesses as usize;
            if error.raw_os_error() != Some(ERROR_MORE_DATA as i32) || needed <= available {
                return Err(error);
            }
            // Only still-assigned processes remain; the zero limit blocks new ones.
            buffer.resize(PROCESS_LIST_HEADER + needed, 0);
        }
    }

    fn open_member(&self, pid: u32) -> io::Result<Option<OwnedHandle>> {
        // SAFETY: only queries and synchronization, and success gives an owned handle.
        let handle = unsafe {
            OpenProcess(
                PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_SYNCHRONIZE,
                0,
                pid,
            )
        };
        if handle.is_null() {
            let error = io::Error::last_os_error();
            return if error.raw_os_error() == Some(ERROR_INVALID_PARAMETER as i32) {
                Ok(None)
            } else {
                Err(error)
            };
        }
        // SAFETY: OpenProcess returned a new, non-inheritable process handle.
        let handle = unsafe { OwnedHandle::from_raw_handle(handle) };
        let mut member = 0;
        // SAFETY: both handles are live and the out pointer points to a writable BOOL.
        if unsafe { IsProcessInJob(handle.as_raw_handle(), self.0.as_raw_handle(), &mut member) }
            == 0
        {
            return Err(io::Error::last_os_error());
        }
        // The snapshot PID might have belonged to a member that exited and been reused.
        Ok((member != 0).then_some(handle))
    }

    pub(super) fn terminate(&self) -> io::Result<()> {
        // SAFETY: the job handle is open.
        if unsafe { TerminateJobObject(self.0.as_raw_handle(), FORCED_TERMINATION_EXIT_CODE) } == 0
        {
            return Err(io::Error::last_os_error());
        }
        Ok(())
    }
}

const PROCESS_LIST_HEADER: usize =
    mem::offset_of!(JOBOBJECT_BASIC_PROCESS_ID_LIST, ProcessIdList) / mem::size_of::<usize>();

pub(super) fn wait_for_exit(processes: &[OwnedHandle]) -> io::Result<()> {
    const CLEANUP_TIMEOUT: Duration = Duration::from_secs(30);
    let deadline = Instant::now() + CLEANUP_TIMEOUT;
    for process in processes {
        let remaining = deadline.saturating_duration_since(Instant::now());
        // SAFETY: each process handle is live and grants synchronization. The timeout
        // fits in a u32 because the common deadline is at most CLEANUP_TIMEOUT away.
        match unsafe { WaitForSingleObject(process.as_raw_handle(), remaining.as_millis() as u32) }
        {
            WAIT_OBJECT_0 => {}
            WAIT_FAILED => return Err(io::Error::last_os_error()),
            WAIT_TIMEOUT => {
                return Err(io::Error::new(
                    io::ErrorKind::TimedOut,
                    "Job descendants did not terminate",
                ));
            }
            _ => return Err(io::Error::other("Unexpected Job process wait result")),
        }
    }
    Ok(())
}