job-limits 0.1.0

Memory limits for child processes, and a guard that cleans up the whole process tree (same API on unix and Windows)
Documentation
#![allow(unsafe_code)]

use std::ffi::c_void;
use std::io;
use std::os::windows::io::{AsRawHandle, RawHandle};
use std::process::{Child, Command};

use windows_sys::Win32::Foundation::{CloseHandle, HANDLE};
use windows_sys::Win32::System::JobObjects::{
    AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
    JOB_OBJECT_LIMIT_PROCESS_MEMORY, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
    JobObjectExtendedLimitInformation, SetInformationJobObject,
};

use crate::Limits;

pub(crate) type Raw = RawHandle;

pub(crate) fn raw(child: &Child) -> Raw {
    child.as_raw_handle()
}

#[cfg(feature = "tokio")]
pub(crate) fn raw_tokio(child: &tokio::process::Child) -> io::Result<Raw> {
    child
        .raw_handle()
        .ok_or_else(|| io::Error::other("the child process has already ended"))
}

/// Nothing to do before the child starts on Windows (it is put into the Job after it starts).
pub(crate) fn prepare(_: &Limits, _: &mut Command) {}

/// A Job Object that ends every process in it when it is closed.
#[derive(Debug)]
pub(crate) struct Guard(HANDLE);

// SAFETY: a Job Object handle can be used and closed from any thread.
unsafe impl Send for Guard {}
unsafe impl Sync for Guard {}

impl Drop for Guard {
    fn drop(&mut self) {
        // SAFETY: `self.0` is a handle that `attach` created and only this `Drop` closes.
        unsafe {
            CloseHandle(self.0);
        }
    }
}

fn check(ok: i32) -> io::Result<()> {
    if ok == 0 {
        Err(io::Error::last_os_error())
    } else {
        Ok(())
    }
}

pub(crate) fn attach(limits: &Limits, _pid: u32, process: Raw) -> io::Result<Guard> {
    let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
    info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
    if let Some(bytes) = limits.process_memory {
        info.BasicLimitInformation.LimitFlags |= JOB_OBJECT_LIMIT_PROCESS_MEMORY;
        info.ProcessMemoryLimit = usize::try_from(bytes).map_err(|_| {
            io::Error::new(
                io::ErrorKind::InvalidInput,
                "the memory limit does not fit in the address space of this platform",
            )
        })?;
    }

    // SAFETY: all arguments are valid (null for the attributes and the name).
    let job = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
    if job.is_null() {
        return Err(io::Error::last_os_error());
    }
    // From here on, `Drop` closes the Job if a later step fails
    let guard = Guard(job);

    // SAFETY: `info` is the structure for `JobObjectExtendedLimitInformation`, with the right size.
    check(unsafe {
        SetInformationJobObject(
            job,
            JobObjectExtendedLimitInformation,
            (&raw const info).cast::<c_void>(),
            size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
        )
    })?;
    // SAFETY: `process` is the handle of a live child process, owned by the caller.
    check(unsafe { AssignProcessToJobObject(job, process as HANDLE) })?;
    Ok(guard)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::process::Stdio;
    use std::time::{Duration, Instant};
    use windows_sys::Win32::System::JobObjects::QueryInformationJobObject;

    fn sleeper() -> Child {
        Command::new("ping")
            .args(["-n", "30", "127.0.0.1"])
            .stdout(Stdio::null())
            .spawn()
            .unwrap()
    }

    #[test]
    fn limit_and_kill_on_close_are_set_in_the_job() {
        let mut child = sleeper();
        let limits = Limits::new().process_memory(1 << 30);
        let guard = attach(&limits, child.id(), child.as_raw_handle()).unwrap();

        let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
        // SAFETY: `info` matches the information class being queried, with the right size.
        check(unsafe {
            QueryInformationJobObject(
                guard.0,
                JobObjectExtendedLimitInformation,
                (&raw mut info).cast::<c_void>(),
                size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
                std::ptr::null_mut(),
            )
        })
        .unwrap();
        let flags = info.BasicLimitInformation.LimitFlags;
        assert_ne!(flags & JOB_OBJECT_LIMIT_PROCESS_MEMORY, 0);
        assert_ne!(flags & JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, 0);
        assert_eq!(info.ProcessMemoryLimit, 1 << 30);

        drop(guard);
        let _ = child.wait();
    }

    #[test]
    fn dropping_the_guard_ends_the_child() {
        let mut child = sleeper();
        let guard = attach(&Limits::new(), child.id(), child.as_raw_handle()).unwrap();
        let started = Instant::now();
        drop(guard);
        // The exit code is not checked (a process ended by a closing Job exits with 0).
        // `ping -n 30` takes about 30 seconds, so returning early shows the Guard cleaned up
        child.wait().unwrap();
        assert!(started.elapsed() < Duration::from_secs(10));
    }
}