F1: lutra starts the desktop without passing on any handle
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>
This commit is contained in:
parent
8a05f508c8
commit
f4dbc9188e
7 changed files with 340 additions and 33 deletions
|
|
@ -19,21 +19,29 @@
|
|||
//! (`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 and console APIs are only reachable through FFI. Every call gets
|
||||
//! Tool Help, thread, process and console 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.
|
||||
//! `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;
|
||||
use std::process::Command;
|
||||
use std::os::windows::process::{CommandExt, ExitStatusExt};
|
||||
use std::path::Path;
|
||||
use std::process::{Command, ExitStatus};
|
||||
|
||||
use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE;
|
||||
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,
|
||||
|
|
@ -44,7 +52,9 @@ use windows_sys::Win32::System::JobObjects::{
|
|||
SetInformationJobObject, TerminateJobObject,
|
||||
};
|
||||
use windows_sys::Win32::System::Threading::{
|
||||
CREATE_NO_WINDOW, CREATE_SUSPENDED, OpenThread, ResumeThread, THREAD_SUSPEND_RESUME,
|
||||
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.
|
||||
|
|
@ -201,3 +211,148 @@ fn resume_thread(tid: u32) -> io::Result<()> {
|
|||
}
|
||||
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""#);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue