lutra_proc::spawn_detached starts a program through CreateProcessW with bInheritHandles = FALSE and null standard handles (DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP as before), so lutra's output pipe closes when lutra exits. launch.rs uses it. Helper roles detached-plain/-proc show the standard library keeping the pipe open and spawn_detached not. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
358 lines
14 KiB
Rust
358 lines
14 KiB
Rust
//! Windows: one job object per child with `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`
|
|
//! (<https://learn.microsoft.com/windows/win32/procthread/job-objects>).
|
|
//!
|
|
//! 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.
|
|
//!
|
|
//! [`enable_ctrl_c`] undoes an inherited "ignore Ctrl+C" flag
|
|
//! (`SetConsoleCtrlHandler(NULL, FALSE)`), so the terminal's shells pass
|
|
//! Ctrl+C on to the programs they run.
|
|
//!
|
|
//! [`spawn_detached`] starts a program through `CreateProcessW` directly,
|
|
//! with `bInheritHandles = FALSE`, which the standard library cannot do.
|
|
//!
|
|
//! This is the one module in Lutra that allows `unsafe`: the job object,
|
|
//! Tool Help, thread, process and console APIs are only reachable through FFI. Every call gets
|
|
//! valid arguments by construction: handles come from `CreateJobObjectW`,
|
|
//! `CreateToolhelp32Snapshot`, `OpenThread` or `CreateProcessW` (owned by an [`OwnedHandle`]
|
|
//! right away) or from a live [`std::process::Child`], strings passed in are
|
|
//! NUL-terminated UTF-16 buffers that outlive the call, and the limit,
|
|
//! thread entry, startup and process information structures are plain C
|
|
//! structs that are valid when zeroed.
|
|
|
|
#![allow(unsafe_code)]
|
|
|
|
use std::ffi::OsStr;
|
|
use std::io;
|
|
use std::os::windows::ffi::OsStrExt;
|
|
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle, RawHandle};
|
|
use std::os::windows::process::{CommandExt, ExitStatusExt};
|
|
use std::path::Path;
|
|
use std::process::{Command, ExitStatus};
|
|
|
|
use windows_sys::Win32::Foundation::{INVALID_HANDLE_VALUE, WAIT_OBJECT_0, WAIT_TIMEOUT};
|
|
use windows_sys::Win32::System::Console::SetConsoleCtrlHandler;
|
|
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_NEW_PROCESS_GROUP, CREATE_NO_WINDOW, CREATE_SUSPENDED, CreateProcessW, DETACHED_PROCESS,
|
|
GetExitCodeProcess, OpenThread, PROCESS_INFORMATION, ResumeThread, STARTF_USESTDHANDLES,
|
|
STARTUPINFOW, THREAD_SUSPEND_RESUME, WaitForSingleObject,
|
|
};
|
|
|
|
/// The exit code a process killed with its job reports.
|
|
const KILLED_EXIT_CODE: u32 = 1;
|
|
|
|
/// Lets this process, and the console programs it starts from now on,
|
|
/// handle Ctrl+C again: `SetConsoleCtrlHandler(NULL, FALSE)`.
|
|
///
|
|
/// A process started with `CREATE_NEW_PROCESS_GROUP` (the `lutra` CLI
|
|
/// starts Lutra that way) ignores Ctrl+C, and its children inherit that.
|
|
///
|
|
/// # Errors
|
|
/// The OS error of `SetConsoleCtrlHandler`.
|
|
pub(crate) fn enable_ctrl_c() -> io::Result<()> {
|
|
let ok = unsafe { SetConsoleCtrlHandler(None, 0) };
|
|
if ok == 0 {
|
|
return Err(io::Error::last_os_error());
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// 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> {
|
|
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<Self> {
|
|
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<Self> {
|
|
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::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>())
|
|
.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::<THREADENTRY32>()).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(())
|
|
}
|
|
|
|
/// A program started by [`spawn_detached`]: its process handle and id.
|
|
pub(crate) struct DetachedProcess {
|
|
/// The process handle from `CreateProcessW`.
|
|
process: OwnedHandle,
|
|
/// The process id.
|
|
id: u32,
|
|
}
|
|
|
|
/// Starts `program` with `args` as a detached process in a new process
|
|
/// group (`DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP`) that inherits no
|
|
/// handle at all (`bInheritHandles = FALSE`) and has no standard handles
|
|
/// (`STARTF_USESTDHANDLES` with null handles). The standard library always
|
|
/// passes `TRUE`, so every inheritable handle of the caller, such as the
|
|
/// pipe a script reads its output from, would stay open in the program.
|
|
/// `program` is found the way `CreateProcessW` finds the first word of a
|
|
/// command line (`.exe` added, `PATH` searched), as the standard library
|
|
/// does for a bare name.
|
|
///
|
|
/// # Errors
|
|
/// The OS error of `CreateProcessW`.
|
|
pub(crate) fn spawn_detached(program: &Path, args: &[&OsStr]) -> io::Result<DetachedProcess> {
|
|
let mut line = quote(program.as_os_str());
|
|
for arg in args {
|
|
line.push(SPACE);
|
|
line.extend(quote(arg));
|
|
}
|
|
line.push(0);
|
|
let mut startup: STARTUPINFOW = unsafe { std::mem::zeroed() };
|
|
startup.cb = u32::try_from(std::mem::size_of::<STARTUPINFOW>()).unwrap_or(u32::MAX);
|
|
startup.dwFlags = STARTF_USESTDHANDLES;
|
|
let mut info: PROCESS_INFORMATION = unsafe { std::mem::zeroed() };
|
|
let ok = unsafe {
|
|
CreateProcessW(
|
|
std::ptr::null(),
|
|
line.as_mut_ptr(),
|
|
std::ptr::null(),
|
|
std::ptr::null(),
|
|
0,
|
|
DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP,
|
|
std::ptr::null(),
|
|
std::ptr::null(),
|
|
&raw const startup,
|
|
&raw mut info,
|
|
)
|
|
};
|
|
if ok == 0 {
|
|
return Err(io::Error::last_os_error());
|
|
}
|
|
let process = unsafe { OwnedHandle::from_raw_handle(info.hProcess) };
|
|
drop(unsafe { OwnedHandle::from_raw_handle(info.hThread) });
|
|
Ok(DetachedProcess {
|
|
process,
|
|
id: info.dwProcessId,
|
|
})
|
|
}
|
|
|
|
impl DetachedProcess {
|
|
/// The process id.
|
|
pub(crate) fn id(&self) -> u32 {
|
|
self.id
|
|
}
|
|
|
|
/// The exit status if the process has exited, without waiting.
|
|
///
|
|
/// # Errors
|
|
/// The OS error of `WaitForSingleObject` or `GetExitCodeProcess`.
|
|
pub(crate) fn try_wait(&self) -> io::Result<Option<ExitStatus>> {
|
|
let handle = self.process.as_raw_handle();
|
|
match unsafe { WaitForSingleObject(handle, 0) } {
|
|
WAIT_TIMEOUT => Ok(None),
|
|
WAIT_OBJECT_0 => {
|
|
let mut code = 0u32;
|
|
if unsafe { GetExitCodeProcess(handle, &raw mut code) } == 0 {
|
|
return Err(io::Error::last_os_error());
|
|
}
|
|
Ok(Some(ExitStatus::from_raw(code)))
|
|
}
|
|
_ => Err(io::Error::last_os_error()),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// A backslash in UTF-16.
|
|
const BACKSLASH: u16 = 0x5c;
|
|
|
|
/// A double quote in UTF-16.
|
|
const QUOTE: u16 = 0x22;
|
|
|
|
/// A space in UTF-16.
|
|
const SPACE: u16 = 0x20;
|
|
|
|
/// A tab in UTF-16.
|
|
const TAB: u16 = 0x09;
|
|
|
|
/// One argument quoted for a Windows command line as the C runtime and
|
|
/// `CommandLineToArgvW` split it: wrapped in quotes when empty or when it
|
|
/// has spaces, tabs or quotes; quotes and the backslashes before them (or
|
|
/// before the closing quote) are escaped.
|
|
fn quote(arg: &OsStr) -> Vec<u16> {
|
|
let units: Vec<u16> = arg.encode_wide().collect();
|
|
let needs = units.is_empty() || units.iter().any(|&u| u == SPACE || u == TAB || u == QUOTE);
|
|
if !needs {
|
|
return units;
|
|
}
|
|
let mut out = vec![QUOTE];
|
|
let mut backslashes = 0usize;
|
|
for &unit in &units {
|
|
if unit == BACKSLASH {
|
|
backslashes += 1;
|
|
continue;
|
|
}
|
|
let escaped = if unit == QUOTE {
|
|
backslashes * 2 + 1
|
|
} else {
|
|
backslashes
|
|
};
|
|
out.extend(std::iter::repeat_n(BACKSLASH, escaped));
|
|
out.push(unit);
|
|
backslashes = 0;
|
|
}
|
|
out.extend(std::iter::repeat_n(BACKSLASH, backslashes * 2));
|
|
out.push(QUOTE);
|
|
out
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn quoted(arg: &str) -> String {
|
|
String::from_utf16("e(OsStr::new(arg))).unwrap()
|
|
}
|
|
|
|
#[test]
|
|
fn arguments_are_quoted_as_the_c_runtime_splits_them() {
|
|
assert_eq!(quoted("-n"), "-n");
|
|
assert_eq!(quoted(r"C:\a\b"), r"C:\a\b");
|
|
assert_eq!(quoted(""), r#""""#);
|
|
assert_eq!(quoted(r"C:\Program Files\x"), r#""C:\Program Files\x""#);
|
|
assert_eq!(quoted(r#"say "hi""#), r#""say \"hi\"""#);
|
|
assert_eq!(quoted(r"dir with space\"), r#""dir with space\\""#);
|
|
assert_eq!(quoted(r#"a\"b"#), r#""a\\\"b""#);
|
|
}
|
|
}
|