//! Windows: one job object per child with `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE` //! (). //! //! A child started with [`Group::prepare`] runs before it joins its job (a //! window of microseconds). [`Group::prepare_suspended`] closes that window: //! the child is created suspended (`CREATE_SUSPENDED`), put into its job and //! only then resumed. The standard library keeps the primary thread's handle //! to itself, so the thread is found through a Tool Help snapshot of the //! system's threads (`CreateToolhelp32Snapshot`, `Thread32First` / //! `Thread32Next`) and resumed with `OpenThread` + `ResumeThread`. The //! snapshot covers every thread on the machine and costs about 60 ms //! (measured 2026-10-27: 43 → 107 ms per `cmd /c exit`), which is why only //! long-lived children pay for it. //! //! [`Group::adopt`] puts a process someone else started (the terminal's //! ConPTY shell) into a new job by its handle. //! //! This is the one module in Lutra that allows `unsafe`: the job object, //! Tool Help and thread APIs are only reachable through FFI. Every call gets //! valid arguments by construction: handles come from `CreateJobObjectW`, //! `CreateToolhelp32Snapshot` or `OpenThread` (owned by an [`OwnedHandle`] //! right away) or from a live [`std::process::Child`], and the limit and //! thread entry structures are plain C structs that are valid when zeroed. #![allow(unsafe_code)] use std::io; use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle, RawHandle}; use std::os::windows::process::CommandExt; use std::process::Command; use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; use windows_sys::Win32::System::Diagnostics::ToolHelp::{ CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next, }; use windows_sys::Win32::System::JobObjects::{ AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JobObjectExtendedLimitInformation, SetInformationJobObject, TerminateJobObject, }; use windows_sys::Win32::System::Threading::{ CREATE_NO_WINDOW, CREATE_SUSPENDED, OpenThread, ResumeThread, THREAD_SUSPEND_RESUME, }; /// The exit code a process killed with its job reports. const KILLED_EXIT_CODE: u32 = 1; /// The job a child runs in. Lutra holds the only handle; closing it (on /// drop, or when Lutra's process ends) kills every process in the job. pub(crate) struct Group { /// The job object. job: OwnedHandle, } impl Group { /// Nothing to set on the command: the process joins its job right /// after it starts. pub(crate) fn prepare(_command: &mut Command) {} /// Creates a kill-on-close job and puts `child` into it. /// /// # Errors /// The OS error of `CreateJobObjectW`, `SetInformationJobObject` or /// `AssignProcessToJobObject`. pub(crate) fn attach(child: &std::process::Child) -> io::Result { Self::adopt(child.as_raw_handle()) } /// Makes the process start suspended and without a console window /// (`CREATE_SUSPENDED | CREATE_NO_WINDOW`). These replace any creation /// flags set on `command` before: the standard library cannot read them /// back, and every tool Lutra runs is a console program whose window /// must stay hidden. pub(crate) fn prepare_suspended(command: &mut Command) { command.creation_flags(CREATE_SUSPENDED | CREATE_NO_WINDOW); } /// Creates a kill-on-close job, puts the suspended `child` into it and /// resumes it. /// /// # Errors /// The errors of [`Group::attach`] and of resuming the child (see /// [`resume`]). The job is closed on error, which kills the child once /// it is in the job. pub(crate) fn attach_suspended(child: &std::process::Child) -> io::Result { let group = Self::attach(child)?; resume(child.id())?; Ok(group) } /// Creates a kill-on-close job and puts the process behind `process` /// into it. The handle needs `PROCESS_SET_QUOTA | PROCESS_TERMINATE` /// access (a handle from `CreateProcess` has all access) and stays owned /// by the caller. /// /// # Errors /// The OS error of `CreateJobObjectW`, `SetInformationJobObject` or /// `AssignProcessToJobObject`. pub(crate) fn adopt(process: RawHandle) -> io::Result { let raw = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) }; if raw.is_null() { return Err(io::Error::last_os_error()); } let job = unsafe { OwnedHandle::from_raw_handle(raw) }; let mut limits: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { std::mem::zeroed() }; limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; let size = u32::try_from(std::mem::size_of::()) .map_err(io::Error::other)?; let set = unsafe { SetInformationJobObject( job.as_raw_handle(), JobObjectExtendedLimitInformation, std::ptr::from_ref(&limits).cast(), size, ) }; if set == 0 { return Err(io::Error::last_os_error()); } let assigned = unsafe { AssignProcessToJobObject(job.as_raw_handle(), process) }; if assigned == 0 { return Err(io::Error::last_os_error()); } Ok(Self { job }) } /// Terminates every process in the job. The result is ignored on /// purpose: the job may be empty already, and closing the handle on /// drop kills whatever is left anyway. pub(crate) fn kill(&mut self) { let _ = unsafe { TerminateJobObject(self.job.as_raw_handle(), KILLED_EXIT_CODE) }; } } /// Resumes every thread of the suspended process `pid`. A process created /// with `CREATE_SUSPENDED` has exactly one thread, its primary thread, with /// a suspend count of one. /// /// # Errors /// The OS error of `CreateToolhelp32Snapshot`, `OpenThread` or /// `ResumeThread`, or `NotFound` when the snapshot holds no thread of `pid`. fn resume(pid: u32) -> io::Result<()> { let raw = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) }; if raw == INVALID_HANDLE_VALUE || raw.is_null() { return Err(io::Error::last_os_error()); } let snapshot = unsafe { OwnedHandle::from_raw_handle(raw) }; let mut entry: THREADENTRY32 = unsafe { std::mem::zeroed() }; entry.dwSize = u32::try_from(std::mem::size_of::()).map_err(io::Error::other)?; let mut resumed = 0usize; let mut more = unsafe { Thread32First(snapshot.as_raw_handle(), &raw mut entry) } != 0; while more { if entry.th32OwnerProcessID == pid { resume_thread(entry.th32ThreadID)?; resumed += 1; } more = unsafe { Thread32Next(snapshot.as_raw_handle(), &raw mut entry) } != 0; } if resumed == 0 { return Err(io::Error::new( io::ErrorKind::NotFound, format!("no thread of process {pid} to resume"), )); } Ok(()) } /// Opens thread `tid` and decrements its suspend count once. /// /// # Errors /// The OS error of `OpenThread` or `ResumeThread`. fn resume_thread(tid: u32) -> io::Result<()> { let raw = unsafe { OpenThread(THREAD_SUSPEND_RESUME, 0, tid) }; if raw.is_null() { return Err(io::Error::last_os_error()); } let thread = unsafe { OwnedHandle::from_raw_handle(raw) }; if unsafe { ResumeThread(thread.as_raw_handle()) } == u32::MAX { return Err(io::Error::last_os_error()); } Ok(()) }