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
|
|
@ -16,6 +16,12 @@
|
|||
//! - `tree-on-input`: reads one line from standard input first, then acts
|
||||
//! as `tree-plain`. A test adopts the helper in between, so the
|
||||
//! grandchild starts only after the helper is in its job.
|
||||
//! - `detached-plain`: starts the sleeping grandchild the way the `lutra`
|
||||
//! CLI did before C9 F1 (a [`std::process::Command`] with null stdio,
|
||||
//! detached in a new process group on Windows), `detached-proc`: through
|
||||
//! [`lutra_proc::spawn_detached`]. Then it prints the grandchild's id and
|
||||
//! exits. A test reading this output sees end of file at once unless the
|
||||
//! grandchild inherited the pipe.
|
||||
//!
|
||||
//! Any other argument exits with code 2.
|
||||
|
||||
|
|
@ -32,6 +38,7 @@ fn main() -> ExitCode {
|
|||
let role = std::env::args().nth(1).unwrap_or_default();
|
||||
match role.as_str() {
|
||||
"tree-plain" | "tree-proc" => tree(role == "tree-proc"),
|
||||
"detached-plain" | "detached-proc" => detached(role == "detached-proc"),
|
||||
"tree-on-input" => {
|
||||
let mut line = String::new();
|
||||
if std::io::stdin().lock().read_line(&mut line).is_err() {
|
||||
|
|
@ -72,6 +79,40 @@ fn tree(guarded: bool) -> ExitCode {
|
|||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
/// Starts the grandchild detached (through `lutra_proc` when `proc`),
|
||||
/// prints its id and returns.
|
||||
fn detached(proc: bool) -> ExitCode {
|
||||
let command = grandchild();
|
||||
let id = if proc {
|
||||
let args: Vec<&std::ffi::OsStr> = command.get_args().collect();
|
||||
let program = std::path::Path::new(command.get_program());
|
||||
match lutra_proc::spawn_detached(program, &args) {
|
||||
Ok(child) => child.id(),
|
||||
Err(_) => return ExitCode::from(4),
|
||||
}
|
||||
} else {
|
||||
let mut command = command;
|
||||
command
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null());
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
command.creation_flags(0x0000_0008 | 0x0000_0200);
|
||||
}
|
||||
match command.spawn() {
|
||||
Ok(child) => child.id(),
|
||||
Err(_) => return ExitCode::from(4),
|
||||
}
|
||||
};
|
||||
let mut out = std::io::stdout();
|
||||
if writeln!(out, "{id}").and_then(|()| out.flush()).is_err() {
|
||||
return ExitCode::from(5);
|
||||
}
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
|
||||
/// A system program that sleeps for [`SLEEP`] without output.
|
||||
fn grandchild() -> Command {
|
||||
let seconds = SLEEP.as_secs();
|
||||
|
|
|
|||
|
|
@ -37,9 +37,18 @@
|
|||
//! integrated terminal's ConPTY shell, into a kill-on-close job and returns
|
||||
//! a [`Guard`] that holds it. [`enable_ctrl_c`] (Windows) undoes an
|
||||
//! inherited "ignore Ctrl+C" flag before that shell starts.
|
||||
//!
|
||||
//! [`spawn_detached`] is the opposite of [`spawn`]: it starts a program that
|
||||
//! outlives the caller and holds none of its handles, as the `lutra` CLI
|
||||
//! starts the desktop app. On Windows the standard library makes every
|
||||
//! inheritable handle of the caller (such as the pipe a script reads the
|
||||
//! CLI's output from) inheritable by the child, so the script would wait
|
||||
//! until the app exits; `spawn_detached` passes no handles at all.
|
||||
|
||||
use std::ffi::OsStr;
|
||||
use std::io;
|
||||
use std::ops::{Deref, DerefMut};
|
||||
use std::path::Path;
|
||||
use std::process::{Command, ExitStatus};
|
||||
|
||||
#[cfg(unix)]
|
||||
|
|
@ -147,6 +156,78 @@ fn spawn_with(
|
|||
}
|
||||
}
|
||||
|
||||
/// A program started by [`spawn_detached`]. Dropping it leaves the program
|
||||
/// running.
|
||||
pub struct Detached {
|
||||
/// The process (Windows: its handle).
|
||||
#[cfg(windows)]
|
||||
inner: windows::DetachedProcess,
|
||||
/// The process.
|
||||
#[cfg(not(windows))]
|
||||
inner: std::process::Child,
|
||||
}
|
||||
|
||||
/// Starts `program` with `args` so that it outlives this process and holds
|
||||
/// none of its handles: standard input, output and error are closed (null),
|
||||
/// and it leaves this terminal's job control.
|
||||
///
|
||||
/// - **Windows:** a detached process in a new process group
|
||||
/// (`DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP`, so it has no console
|
||||
/// and a Ctrl+C in the caller's console does not reach it), created with
|
||||
/// `bInheritHandles = FALSE`, so no handle of the caller is inherited.
|
||||
/// - **Unix:** a new process group, so a Ctrl-C or hangup aimed at the
|
||||
/// terminal's foreground group does not reach it; the standard library
|
||||
/// opens its own descriptors close-on-exec.
|
||||
///
|
||||
/// The environment and working directory are this process's.
|
||||
///
|
||||
/// # Errors
|
||||
/// The OS error of starting the program.
|
||||
pub fn spawn_detached(program: &Path, args: &[&OsStr]) -> io::Result<Detached> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
windows::spawn_detached(program, args).map(|inner| Detached { inner })
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
let mut command = Command::new(program);
|
||||
command
|
||||
.args(args)
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null());
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
command.process_group(0);
|
||||
}
|
||||
command.spawn().map(|inner| Detached { inner })
|
||||
}
|
||||
}
|
||||
|
||||
impl Detached {
|
||||
/// The process id.
|
||||
pub fn id(&self) -> u32 {
|
||||
self.inner.id()
|
||||
}
|
||||
|
||||
/// The exit status if the program has exited, without waiting.
|
||||
///
|
||||
/// # Errors
|
||||
/// The OS error of asking for it.
|
||||
pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
|
||||
self.inner.try_wait()
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for Detached {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Detached")
|
||||
.field("id", &self.id())
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
/// A kill-on-close job for a process Lutra did not start through [`spawn`]
|
||||
/// (Windows only, see [`adopt`]). Dropping it kills the process and
|
||||
/// everything it started.
|
||||
|
|
|
|||
|
|
@ -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