fix(process-daemon): put Store app processes that leave the job back in one

This commit is contained in:
Filip Hejmowski 2026-11-20 11:31:41 +01:00
parent ded5ad9304
commit ab3c3d8b29
6 changed files with 1053 additions and 79 deletions

View file

@ -32,6 +32,7 @@ windows-sys = { version = "0.61.2", features = [
"Win32_Security",
"Win32_Security_Authorization",
"Win32_Storage_FileSystem",
"Win32_System_Diagnostics_ToolHelp",
"Win32_System_IO",
"Win32_System_JobObjects",
"Win32_System_Pipes",

View file

@ -147,9 +147,15 @@ starts a pipe process: any command without a terminal. Both return
mask across exec). On Windows it is created with `CREATE_NO_WINDOW` (no
console) inside a kill-on-close job. When the program is a Store app (such
as Store PowerShell 7), the processes it starts stay inside its package, and
so in the job, instead of breaking away. A Store app started by another
process in the job, such as `cmd.exe`, still breaks away with everything it
starts. For a bare executable name,
so in the job, instead of breaking away. Windows still lets two kinds of
process leave the job: a Store app started further down the tree (Store
PowerShell, `wsl.exe` or `winget.exe` run by `cmd.exe`, say) moves to its
package's own job, and the children of such a Store app break away from
every job. About once a second the daemon finds them by their parent and
puts them back: one in no job joins the command's job, and a Store app gets
a kill-on-close job of its own inside its package's job. A signal or a
failed exit reaches them even before that; only one that left less than a
second before the daemon dies can survive it. For a bare executable name,
`CreateProcessW` searches the directory containing the daemon executable,
the daemon's current directory, the 32-bit and then 16-bit Windows system
directories, the Windows directory, and finally the directories in the
@ -189,8 +195,9 @@ starts a pipe process: any command without a terminal. Both return
On Unix a non-zero exit code sends SIGTERM to the process group before the
waiter reaps the leader, then SIGKILL after three seconds if the group
survives. A signal death has no numeric exit code and does not trigger this
cleanup. On Windows a non-zero exit terminates the job immediately. The
waiter clears kill-on-close and releases the job and process handles at exit.
cleanup. On Windows a non-zero exit terminates the job, and the jobs of
Store apps that left it, immediately. The waiter clears kill-on-close on
every job and releases the jobs and process handles at exit.
- The finished record (including exit status, output path and metadata) stays
listed until `terminate`. Its PID is historical metadata. `terminate` kills
a running tree and removes its record; after exit it only removes the record.

View file

@ -5,8 +5,11 @@
//! with overlapped I/O. The child is created suspended and joins a
//! kill-on-close job before it runs, so
//! `TerminateJobObject` reaches every descendant and a daemon crash takes the
//! tree with it. No console signals are used: every `signal` is a hard kill of
//! the tree, and the exit reports the signal the daemon sent.
//! tree with it. Processes that Windows lets leave the job are put back by the
//! watcher in [`tree`]. No console signals are used: every `signal` is a hard
//! kill of the tree, and the exit reports the signal the daemon sent.
mod tree;
use std::cmp::Ordering;
use std::collections::HashMap;
@ -41,7 +44,7 @@ use windows_sys::Win32::System::IO::{CancelIoEx, GetOverlappedResult, OVERLAPPED
use windows_sys::Win32::System::JobObjects::{
AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
JOBOBJECT_BASIC_LIMIT_INFORMATION, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
JobObjectExtendedLimitInformation, SetInformationJobObject, TerminateJobObject,
JobObjectExtendedLimitInformation, SetInformationJobObject,
};
use windows_sys::Win32::System::Pipes::{
CreateNamedPipeW, PIPE_READMODE_BYTE, PIPE_REJECT_REMOTE_CLIENTS, PIPE_TYPE_BYTE, PIPE_WAIT,
@ -59,6 +62,7 @@ use super::{DRAIN_AFTER_EXIT, Exit, OutputSink, exit_message, start_pipe};
use crate::service::{CreatePipe, ProcessSignal, TerminalHandle, TerminalId};
use crate::transport::retained::Retained;
use crate::transport::windows::{event, owned_handle, security::PrivateSecurity, wide};
use tree::Tree;
/// Cancel is first so a pipe that is always readable cannot starve it.
const CANCEL_READY: u32 = WAIT_OBJECT_0;
@ -109,8 +113,9 @@ impl TerminalHandle {
}
}
/// A pipe child on Windows: the process object, the job that owns its tree
/// (unless one could not be used), and the signal the daemon sent, if any.
/// A pipe child on Windows: the process object, the tree of jobs that owns its
/// descendants (unless no job could be used), and the signal the daemon sent,
/// if any.
#[derive(Debug)]
pub(in crate::service) struct Process {
pid: u32,
@ -128,7 +133,7 @@ struct State {
#[derive(Debug)]
struct Handles {
process: Arc<OwnedHandle>,
job: Option<Job>,
tree: Option<Tree>,
}
impl Process {
@ -192,23 +197,18 @@ fn record_kill<'a>(state: &'a mut State, name: &'static str) -> Option<&'a Handl
/// Terminates the whole tree.
fn terminate(handles: &Handles) -> io::Result<()> {
// SAFETY: the handles stay open while they are borrowed here.
let terminated = unsafe {
match &handles.job {
Some(job) => TerminateJobObject(job.handle(), 1),
None => TerminateProcess(handles.process.as_raw_handle(), 1),
}
let result = match &handles.tree {
Some(tree) => tree.terminate(),
// SAFETY: the process handle stays open while it is borrowed here.
None if unsafe { TerminateProcess(handles.process.as_raw_handle(), 1) } != 0 => Ok(()),
None => Err(io::Error::last_os_error()),
};
if terminated != 0 {
return Ok(());
match result {
// A process that has already exited refuses termination; signalling
// an empty Unix process group is not an error either.
Err(error) if error.raw_os_error() == Some(ERROR_ACCESS_DENIED as i32) => Ok(()),
result => result,
}
let error = io::Error::last_os_error();
// A process that has already exited refuses termination; signalling an
// empty Unix process group is not an error either.
if error.raw_os_error() == Some(ERROR_ACCESS_DENIED as i32) {
return Ok(());
}
Err(error)
}
/// Returns the process and job handles for a spawned tree.
@ -227,8 +227,8 @@ fn spawn(
// anything. PROC_THREAD_ATTRIBUTE_JOB_LIST would be atomic, but Windows
// then refuses to add a Store app (Store PowerShell 7) to its package's
// container job while another process of that package is running.
let job = job.and_then(|job| match job.assign(created.process()) {
Ok(()) => Some(job),
let tree = job.and_then(|job| match job.assign(created.process()) {
Ok(()) => Some(Tree::watch(id, job, created.pid)),
Err(error) => {
// An outer job with UI restrictions refuses new members. Run the
// command anyway; only the main process can be killed then.
@ -246,7 +246,7 @@ fn spawn(
state: Mutex::new(State {
handles: Some(Handles {
process: Arc::new(process),
job,
tree,
}),
killed: None,
}),
@ -367,8 +367,8 @@ fn wait_exit(process: &Process) -> io::Result<Exit> {
if unsafe { GetExitCodeProcess(handle.as_raw_handle(), &mut code) } == 0 {
return Err(io::Error::last_os_error());
}
if let Some(job) = handles.and_then(|handles| handles.job)
&& let Err(error) = job.finish(code != 0 && state.killed.is_none())
if let Some(tree) = handles.and_then(|handles| handles.tree)
&& let Err(error) = tree.finish(code != 0 && state.killed.is_none())
{
eprintln!("pipe process {}: job cleanup failed: {error}", process.pid);
}
@ -746,16 +746,6 @@ impl Job {
}
Ok(())
}
fn finish(self, failed: bool) -> io::Result<()> {
// No console and no SIGTERM grace. If termination fails, closing the
// still-armed job is the fallback. For a successful command disarm
// kill-on-close before releasing the handle.
if failed && unsafe { TerminateJobObject(self.handle(), 1) } == 0 {
return Err(io::Error::last_os_error());
}
self.set_limits(0)
}
}
fn warn_no_job(id: TerminalId, error: &io::Error) {
@ -949,9 +939,9 @@ fn compare_keys(a: &[u16], b: &[u16]) -> Ordering {
/// PROCESS_CREATION_DESKTOP_APP_BREAKAWAY_DISABLE_PROCESS_TREE, which
/// windows-sys does not define. By default a Store app such as Store
/// PowerShell 7 starts its children outside its package, and so outside every
/// job; with this policy they stay in the job. It only helps when the Store app
/// is the program itself: one started further down the tree, e.g. by cmd.exe,
/// still breaks away with its children.
/// job; with this policy they stay in the job. It only reaches the program's
/// own children: a Store app started further down the tree leaves the job, and
/// so do its children, until the watcher in [`tree`] puts them back.
static KEEP_DESKTOP_APP_CHILDREN: u32 = 0x02;
/// An initialized process-attribute list and the buffer it points into, freed
@ -1046,7 +1036,7 @@ mod tests {
String::from_utf16(value).unwrap()
}
fn test_request(program: &str, args: &[&str]) -> CreatePipe {
pub(super) fn test_request(program: &str, args: &[&str]) -> CreatePipe {
CreatePipe {
program: program.into(),
args: args.iter().map(|arg| arg.to_string()).collect(),
@ -1256,7 +1246,7 @@ mod tests {
.lock()
.handles
.as_ref()
.is_some_and(|handles| handles.job.is_some())
.is_some_and(|handles| handles.tree.is_some())
};
let running = start(3, "Start-Sleep 30");

View file

@ -0,0 +1,636 @@
//! The process tree of a pipe command, including processes that leave its job.
//!
//! A command runs in a kill-on-close job, but Windows lets two kinds of
//! process leave it. A Store app (an app execution alias such as Store
//! PowerShell 7, `wsl.exe` or `winget.exe`) started by a process in the job
//! moves to its package's own job, which ours cannot hold. And the children of
//! a Store app break away from every job, unless the app is the command itself
//! and so got the daemon's desktop-app policy. Nothing stops either, so a
//! watcher thread finds them afterwards.
//!
//! The watcher records every process that enters one of the tree's jobs, from
//! the jobs' completion-port messages, and keeps it open so its PID cannot be
//! reused. Every [`POLL_INTERVAL`] it walks a process snapshot for children of
//! recorded processes that are in none of the tree's jobs. One in no job joins
//! the command's job; one in another job (a Store app in its package's job)
//! gets a kill-on-close job of its own, nested inside that one. Killing the
//! tree terminates every job, then kills what escaped since the last poll.
use std::collections::HashMap;
use std::io;
use std::mem::{size_of, size_of_val};
use std::os::windows::io::{AsRawHandle, OwnedHandle};
use std::ptr::{null, null_mut};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError};
use std::time::{Duration, Instant};
use windows_sys::Win32::Foundation::{FILETIME, INVALID_HANDLE_VALUE, WAIT_TIMEOUT};
use windows_sys::Win32::System::Diagnostics::ToolHelp::{
CreateToolhelp32Snapshot, PROCESSENTRY32W, Process32FirstW, Process32NextW, TH32CS_SNAPPROCESS,
};
use windows_sys::Win32::System::IO::{
CreateIoCompletionPort, GetQueuedCompletionStatus, OVERLAPPED, PostQueuedCompletionStatus,
};
use windows_sys::Win32::System::JobObjects::{
IsProcessInJob, JOBOBJECT_ASSOCIATE_COMPLETION_PORT,
JobObjectAssociateCompletionPortInformation, SetInformationJobObject, TerminateJobObject,
};
use windows_sys::Win32::System::Threading::{
GetProcessTimes, INFINITE, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SET_QUOTA,
PROCESS_SYNCHRONIZE, PROCESS_TERMINATE, TerminateProcess,
};
use super::{Job, is_signalled};
use crate::service::TerminalId;
use crate::transport::windows::owned_handle;
/// How long a process that left the tree's jobs can run before it is put back
/// in one, which only matters if the daemon dies: killing the tree finds it
/// anyway. A snapshot takes a few milliseconds, so polling more often costs
/// noticeable CPU while commands run.
const POLL_INTERVAL: Duration = Duration::from_secs(1);
/// Snapshots taken when killing the tree, while each still finds a process.
const KILL_SWEEPS: usize = 3;
/// The completion key that only wakes the watcher.
const WAKE: usize = 0;
/// winnt.h's job message for a process joining the job, which windows-sys
/// only exports with its SystemServices feature.
const JOB_OBJECT_MSG_NEW_PROCESS: u32 = 6;
/// A command's jobs and the processes known to be in its tree.
#[derive(Debug)]
pub(super) struct Tree {
key: usize,
state: Arc<Mutex<State>>,
}
#[derive(Debug)]
struct State {
id: TerminalId,
key: usize,
/// The command's job first, then one per Store app that left it.
jobs: Vec<Job>,
members: HashMap<u32, Member>,
killed: bool,
}
#[derive(Debug)]
struct Member {
process: OwnedHandle,
created: u64,
}
impl Tree {
/// Watches the tree of `root`, which is in `job` and has not started yet.
pub(super) fn watch(id: TerminalId, job: Job, root: u32) -> Self {
let watcher = watcher();
let key = watcher.map_or(WAKE, |watcher| {
watcher.next_key.fetch_add(1, Ordering::Relaxed)
});
if let Some(watcher) = watcher
&& let Err(error) = watcher.notify(&job, key)
{
eprintln!("pipe process {id}: job notifications are unavailable: {error}");
}
let mut state = State {
id,
key,
jobs: vec![job],
members: HashMap::new(),
killed: false,
};
state.record(root);
let state = Arc::new(Mutex::new(state));
if let Some(watcher) = watcher {
watcher.trees().insert(key, Arc::clone(&state));
watcher.wake();
}
Self { key, state }
}
/// Kills every process of the tree.
pub(super) fn terminate(&self) -> io::Result<()> {
self.lock().terminate()
}
/// Kills the tree first when the command failed. Otherwise what it left
/// running keeps running: kill-on-close is cleared on every job. If the
/// kill fails, dropping the still-armed jobs is the fallback.
pub(super) fn finish(self, failed: bool) -> io::Result<()> {
let mut state = self.lock();
if failed {
state.terminate()?;
}
state.jobs.iter().try_for_each(|job| job.set_limits(0))
}
#[cfg(test)]
pub(super) fn job(&self) -> windows_sys::Win32::Foundation::HANDLE {
self.lock().jobs[0].handle()
}
fn lock(&self) -> MutexGuard<'_, State> {
lock(&self.state)
}
}
impl Drop for Tree {
fn drop(&mut self) {
if self.key != WAKE
&& let Some(watcher) = watcher()
{
watcher.trees().remove(&self.key);
}
}
}
impl State {
/// Records a process that entered one of the tree's jobs. A late message
/// can name a PID that already belongs to another process: only a process
/// still in one of the jobs is ours.
fn record(&mut self, pid: u32) {
if self.members.contains_key(&pid) {
return;
}
if let Some(process) = open(pid)
&& self.jobs.iter().any(|job| in_job(&process, job))
&& let Some(created) = created(&process)
{
self.members.insert(pid, Member { process, created });
}
}
fn terminate(&mut self) -> io::Result<()> {
self.killed = true;
let mut result = Ok(());
for job in &self.jobs {
// SAFETY: the job handle stays open through the call.
if unsafe { TerminateJobObject(job.handle(), 1) } == 0 && result.is_ok() {
result = Err(io::Error::last_os_error());
}
}
for _ in 0..KILL_SWEEPS {
let Ok(processes) = snapshot() else {
break;
};
if self.adopt(&processes) == 0 {
break;
}
}
result
}
/// Takes in every process in `processes` whose parent is a member, until
/// none is left. Returns how many it took.
fn adopt(&mut self, processes: &[Entry]) -> usize {
let mut total = 0;
loop {
let mut taken = 0;
for entry in processes {
if self.members.contains_key(&entry.pid) {
continue;
}
let Some(parent) = self.members.get(&entry.parent) else {
continue;
};
let parent_created = parent.created;
let Some(process) = open(entry.pid) else {
continue;
};
// Members are held open, so their PIDs are not reused; a
// process older than its parent got that parent PID from an
// earlier process.
let Some(created) = created(&process).filter(|created| *created >= parent_created)
else {
continue;
};
self.take(&process);
self.members.insert(entry.pid, Member { process, created });
taken += 1;
}
if taken == 0 {
return total;
}
total += taken;
}
}
/// Puts a process of the tree back in one of its jobs, or kills it once
/// the tree has been killed.
fn take(&mut self, process: &OwnedHandle) {
if self.killed {
// SAFETY: the process handle stays open through the call.
unsafe { TerminateProcess(process.as_raw_handle(), 1) };
return;
}
if self.jobs.iter().any(|job| in_job(process, job))
|| self.jobs.iter().any(|job| job.assign(process).is_ok())
{
return;
}
// A job we cannot join, such as a Store app's package job, can still
// hold a job of ours.
let Some(job) = Job::new(self.id) else {
return;
};
if job.assign(process).is_err() {
return;
}
if self.key != WAKE
&& let Some(watcher) = watcher()
{
let _ = watcher.notify(&job, self.key);
}
self.jobs.push(job);
}
/// Members that had exited before a snapshot cannot add to it, so they
/// are dropped once it has been walked.
fn exited(&self) -> Vec<u32> {
self.members
.iter()
.filter(|(_, member)| is_signalled(&member.process))
.map(|(pid, _)| *pid)
.collect()
}
}
/// The one thread that watches every tree.
struct Watcher {
port: OwnedHandle,
trees: Mutex<HashMap<usize, Arc<Mutex<State>>>>,
next_key: AtomicUsize,
}
static WATCHER: OnceLock<Option<Watcher>> = OnceLock::new();
/// Starts the watcher on first use. Without it a tree is only its job.
fn watcher() -> Option<&'static Watcher> {
WATCHER
.get_or_init(|| {
Watcher::new()
.and_then(|watcher| {
std::thread::Builder::new()
.name("opencode-pty-job-watcher".into())
.spawn(|| {
if let Some(watcher) = WATCHER.wait() {
watcher.run();
}
})?;
Ok(watcher)
})
.inspect_err(|error| {
eprintln!(
"pipe processes: cannot watch for processes leaving their job: {error}"
)
})
.ok()
})
.as_ref()
}
impl Watcher {
fn new() -> io::Result<Self> {
// SAFETY: a new completion port not associated with any file.
let port = owned_handle(unsafe {
CreateIoCompletionPort(INVALID_HANDLE_VALUE, null_mut(), 0, 1)
})?;
Ok(Self {
port,
trees: Mutex::new(HashMap::new()),
next_key: AtomicUsize::new(WAKE + 1),
})
}
fn trees(&self) -> MutexGuard<'_, HashMap<usize, Arc<Mutex<State>>>> {
self.trees.lock().unwrap_or_else(PoisonError::into_inner)
}
/// Sends the job's messages to the watcher, tagged with the tree's key.
fn notify(&self, job: &Job, key: usize) -> io::Result<()> {
let port = JOBOBJECT_ASSOCIATE_COMPLETION_PORT {
CompletionKey: key as *mut _,
CompletionPort: self.port.as_raw_handle(),
};
// SAFETY: the job and port stay open through the call, and the value
// matches the information class.
if unsafe {
SetInformationJobObject(
job.handle(),
JobObjectAssociateCompletionPortInformation,
(&raw const port).cast(),
size_of_val(&port) as u32,
)
} == 0
{
return Err(io::Error::last_os_error());
}
Ok(())
}
fn wake(&self) {
// SAFETY: the port stays open; the packet carries no overlapped data.
unsafe { PostQueuedCompletionStatus(self.port.as_raw_handle(), 0, WAKE, null()) };
}
fn run(&self) {
let mut next_poll = Instant::now() + POLL_INTERVAL;
loop {
let timeout = if self.trees().is_empty() {
INFINITE
} else {
next_poll
.saturating_duration_since(Instant::now())
.as_millis() as u32
};
let mut message = 0;
let mut key = 0;
let mut overlapped: *mut OVERLAPPED = null_mut();
// SAFETY: the port stays open and every out-pointer is valid.
let received = unsafe {
GetQueuedCompletionStatus(
self.port.as_raw_handle(),
&mut message,
&mut key,
&mut overlapped,
timeout,
)
} != 0;
if !received {
let error = io::Error::last_os_error();
if error.raw_os_error() != Some(WAIT_TIMEOUT as i32) {
eprintln!(
"pipe processes: stopped watching for processes leaving their job: {error}"
);
return;
}
}
// For job messages the overlapped pointer carries the PID.
if received && message == JOB_OBJECT_MSG_NEW_PROCESS {
let tree = self.trees().get(&key).cloned();
if let Some(tree) = tree {
lock(&tree).record(overlapped as usize as u32);
}
}
if Instant::now() >= next_poll {
self.poll();
next_poll = Instant::now() + POLL_INTERVAL;
}
}
}
fn poll(&self) {
let trees: Vec<_> = self.trees().values().cloned().collect();
if trees.is_empty() {
return;
}
let exited: Vec<_> = trees.iter().map(|tree| lock(tree).exited()).collect();
let Ok(processes) = snapshot() else {
return;
};
for (tree, exited) in trees.iter().zip(exited) {
let mut state = lock(tree);
state.adopt(&processes);
for pid in exited {
state.members.remove(&pid);
}
}
}
}
fn lock(state: &Mutex<State>) -> MutexGuard<'_, State> {
state.lock().unwrap_or_else(PoisonError::into_inner)
}
struct Entry {
pid: u32,
parent: u32,
}
/// Every running process with its parent's PID.
fn snapshot() -> io::Result<Vec<Entry>> {
// SAFETY: a new process snapshot, adopted on success.
let snapshot = owned_handle(unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) })?;
let mut entry = PROCESSENTRY32W {
dwSize: size_of::<PROCESSENTRY32W>() as u32,
..Default::default()
};
let mut processes = Vec::new();
// SAFETY: the snapshot stays open and the entry's size is set.
let mut more = unsafe { Process32FirstW(snapshot.as_raw_handle(), &mut entry) } != 0;
while more {
processes.push(Entry {
pid: entry.th32ProcessID,
parent: entry.th32ParentProcessID,
});
// SAFETY: as above.
more = unsafe { Process32NextW(snapshot.as_raw_handle(), &mut entry) } != 0;
}
Ok(processes)
}
/// Opens a process with the access the tree needs, if it is ours to open.
fn open(pid: u32) -> Option<OwnedHandle> {
// SAFETY: a new, non-inheritable handle, adopted on success.
owned_handle(unsafe {
OpenProcess(
PROCESS_QUERY_LIMITED_INFORMATION
| PROCESS_SET_QUOTA
| PROCESS_SYNCHRONIZE
| PROCESS_TERMINATE,
0,
pid,
)
})
.ok()
}
fn created(process: &OwnedHandle) -> Option<u64> {
let mut created = FILETIME::default();
let mut exited = FILETIME::default();
let mut kernel = FILETIME::default();
let mut user = FILETIME::default();
// SAFETY: the process handle stays open and every out-pointer is valid.
if unsafe {
GetProcessTimes(
process.as_raw_handle(),
&mut created,
&mut exited,
&mut kernel,
&mut user,
)
} == 0
{
return None;
}
Some(u64::from(created.dwHighDateTime) << 32 | u64::from(created.dwLowDateTime))
}
fn in_job(process: &OwnedHandle, job: &Job) -> bool {
let mut result = 0;
// SAFETY: both handles stay open through the call.
let queried = unsafe { IsProcessInJob(process.as_raw_handle(), job.handle(), &mut result) };
queried != 0 && result != 0
}
#[cfg(test)]
mod tests {
use std::os::windows::io::FromRawHandle;
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE};
use windows_sys::Win32::System::Threading::{
CREATE_NO_WINDOW, CreateProcessW, DeleteProcThreadAttributeList,
EXTENDED_STARTUPINFO_PRESENT, InitializeProcThreadAttributeList,
PROC_THREAD_ATTRIBUTE_PARENT_PROCESS, PROCESS_INFORMATION, STARTUPINFOEXW,
UpdateProcThreadAttribute, WaitForSingleObject,
};
use super::super::tests::test_request;
use super::super::{OutputPipe, Spawned, create_process, output_pipe};
use super::*;
/// A suspended `ping` that will be the tree's root, and a child of it
/// created outside its job, the way a Store app's children leave it.
fn root_with_escaped_child() -> (Spawned, OwnedHandle) {
let request = test_request("ping.exe", &["-n", "30", "127.0.0.1"]);
let OutputPipe { client, .. } = output_pipe().unwrap();
let root = create_process(&request, &client).unwrap();
let child = child_of(root.process());
(root, child)
}
fn child_of(parent: &OwnedHandle) -> OwnedHandle {
let mut bytes = 0;
// SAFETY: the first call only reports the required size.
unsafe { InitializeProcThreadAttributeList(null_mut(), 1, 0, &mut bytes) };
let mut buffer = vec![0_usize; bytes.div_ceil(size_of::<usize>())];
let list = buffer.as_mut_ptr().cast();
let raw: HANDLE = parent.as_raw_handle();
let mut command: Vec<u16> = "ping.exe -n 30 127.0.0.1\0".encode_utf16().collect();
let mut info = PROCESS_INFORMATION::default();
// SAFETY: the buffer is large enough and outlives the list, the parent
// handle outlives the call, and the list is deleted before return.
unsafe {
assert_ne!(InitializeProcThreadAttributeList(list, 1, 0, &mut bytes), 0);
assert_ne!(
UpdateProcThreadAttribute(
list,
0,
PROC_THREAD_ATTRIBUTE_PARENT_PROCESS as usize,
(&raw const raw).cast(),
size_of::<HANDLE>(),
null_mut(),
null(),
),
0
);
let mut startup = STARTUPINFOEXW::default();
startup.StartupInfo.cb = size_of::<STARTUPINFOEXW>() as u32;
startup.lpAttributeList = list;
let created = CreateProcessW(
null(),
command.as_mut_ptr(),
null(),
null(),
0,
CREATE_NO_WINDOW | EXTENDED_STARTUPINFO_PRESENT,
null(),
null(),
(&raw const startup).cast(),
&mut info,
);
DeleteProcThreadAttributeList(list);
assert_ne!(created, 0, "{}", io::Error::last_os_error());
CloseHandle(info.hThread);
OwnedHandle::from_raw_handle(info.hProcess)
}
}
fn in_raw_job(process: &OwnedHandle, job: HANDLE) -> bool {
let mut result = 0;
// SAFETY: both handles stay open through the call.
let queried = unsafe { IsProcessInJob(process.as_raw_handle(), job, &mut result) };
queried != 0 && result != 0
}
fn wait_until(what: &str, mut done: impl FnMut() -> bool) {
let deadline = Instant::now() + Duration::from_secs(10);
while !done() {
assert!(Instant::now() < deadline, "{what}");
std::thread::sleep(Duration::from_millis(10));
}
}
struct KillOnDrop(OwnedHandle);
impl Drop for KillOnDrop {
fn drop(&mut self) {
// SAFETY: the handle is this test's own child.
unsafe { TerminateProcess(self.0.as_raw_handle(), 1) };
}
}
#[test]
fn the_watcher_puts_an_escaped_child_back_in_the_job() {
let (root, child) = root_with_escaped_child();
let child = KillOnDrop(child);
let job = Job::new(1).unwrap();
job.assign(root.process()).unwrap();
let tree = Tree::watch(1, job, root.pid);
let (_, root) = root.resume().unwrap();
let _root = KillOnDrop(root);
assert!(!in_raw_job(&child.0, tree.job()));
wait_until("the child did not join the job", || {
in_raw_job(&child.0, tree.job())
});
tree.terminate().unwrap();
wait_until("the child survived the kill", || is_signalled(&child.0));
}
#[test]
fn killing_the_tree_kills_an_escaped_child_the_watcher_has_not_seen() {
let (root, child) = root_with_escaped_child();
let child = KillOnDrop(child);
let job = Job::new(2).unwrap();
job.assign(root.process()).unwrap();
// Not registered with the watcher: only the kill's own sweep finds it.
let mut state = State {
id: 2,
key: WAKE,
jobs: vec![job],
members: HashMap::new(),
killed: false,
};
state.record(root.pid);
let (_, root) = root.resume().unwrap();
let root = KillOnDrop(root);
state.terminate().unwrap();
wait_until("the root survived the kill", || is_signalled(&root.0));
// SAFETY: the child handle stays open through the wait.
assert_eq!(
unsafe { WaitForSingleObject(child.0.as_raw_handle(), 5000) },
0
);
}
#[test]
fn a_successful_command_leaves_an_adopted_child_running() {
let (root, child) = root_with_escaped_child();
let child = KillOnDrop(child);
let job = Job::new(3).unwrap();
job.assign(root.process()).unwrap();
let tree = Tree::watch(3, job, root.pid);
let (_, root) = root.resume().unwrap();
let _root = KillOnDrop(root);
wait_until("the child did not join the job", || {
in_raw_job(&child.0, tree.job())
});
tree.finish(false).unwrap();
std::thread::sleep(Duration::from_millis(300));
assert!(
!is_signalled(&child.0),
"closing a disarmed job killed the child"
);
}
}

View file

@ -13,6 +13,7 @@ use std::env;
use std::fs;
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
use std::path::{Path, PathBuf};
use std::ptr::null_mut;
use std::time::{Duration, Instant};
use opencode_pty::service::{
@ -20,8 +21,10 @@ use opencode_pty::service::{
ProcessSignal, TerminalId, TerminalLifecycle, TerminalService,
};
use windows_sys::Win32::Foundation::{ERROR_PRIVILEGE_NOT_HELD, WAIT_OBJECT_0};
use windows_sys::Win32::System::JobObjects::IsProcessInJob;
use windows_sys::Win32::System::Threading::{
OpenProcess, PROCESS_SYNCHRONIZE, PROCESS_TERMINATE, TerminateProcess, WaitForSingleObject,
OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE, PROCESS_TERMINATE,
TerminateProcess, WaitForSingleObject,
};
/// A unique temporary path, removed when dropped even if a test fails.
@ -578,51 +581,255 @@ fn signal_reaches_a_grandchild_in_the_job() {
service.terminate(info.id).unwrap();
}
#[test]
fn signal_reaches_a_grandchild_of_store_powershell() {
// Only where PowerShell 7 is installed from the Microsoft Store.
let Some(alias) = env::var_os("LOCALAPPDATA")
/// Store PowerShell 7's app execution alias, where it is installed from the
/// Microsoft Store.
fn store_powershell() -> Option<PathBuf> {
env::var_os("LOCALAPPDATA")
.map(|dir| Path::new(&dir).join(r"Microsoft\WindowsApps\pwsh.exe"))
.filter(|alias| alias.exists())
else {
}
/// A script for Store PowerShell that starts `ping` and writes its own PID
/// and the ping's.
struct StoreScript {
script: TempPath,
pids: TempPath,
}
impl StoreScript {
fn new(name: &str) -> Self {
let pids = TempPath::new(&format!("{name}-pids"));
let script = TempPath::script(name, "ps1");
fs::write(
&script.0,
format!(
r#"
$child = [System.Diagnostics.Process]::Start('ping.exe', '-n 60 127.0.0.1')
[System.IO.File]::WriteAllText('{}', "$PID $($child.Id)")
Start-Sleep -Seconds 60
"#,
ps_path(&pids.0)
),
)
.unwrap();
Self { script, pids }
}
/// The arguments that run the script.
fn args(&self) -> Vec<String> {
[
"-NoProfile",
"-NonInteractive",
"-ExecutionPolicy",
"Bypass",
"-File",
]
.into_iter()
.map(String::from)
.chain([self.script.0.display().to_string()])
.collect()
}
/// The Store PowerShell running the script and its `ping`, killed when
/// dropped.
fn processes(&self) -> (KillOnDrop, KillOnDrop) {
let deadline = Instant::now() + Duration::from_secs(10);
loop {
if let Ok(text) = fs::read_to_string(&self.pids.0)
&& let Some((powershell, ping)) = text.trim().split_once(' ')
{
return (
KillOnDrop(powershell.parse().unwrap()),
KillOnDrop(ping.parse().unwrap()),
);
}
assert!(
Instant::now() < deadline,
"the script did not write its PIDs"
);
std::thread::sleep(Duration::from_millis(20));
}
}
}
/// A batch file that runs `program` with `args`, so the program is started
/// by `cmd.exe` rather than by the daemon.
fn batch_running(name: &str, program: &Path, args: &[String]) -> TempPath {
let args = args
.iter()
.map(|arg| format!("\"{arg}\""))
.collect::<Vec<_>>()
.join(" ");
batch(
name,
&[
"@echo off".to_string(),
format!("\"{}\" {args}", program.display()),
],
)
}
/// For a command that starts a Store app through the Windows shell, as
/// `start` and PowerShell's `&` do: the shell writes its caches under
/// %SystemDrive%, so without it they land in the working directory.
fn shell_env() -> HashMap<String, String> {
let mut env = base_env();
env.extend(env::var("SystemDrive").map(|drive| ("SystemDrive".to_string(), drive)));
env
}
fn in_a_job(pid: u32) -> bool {
// SAFETY: a successful handle is adopted immediately; it is only queried.
let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
assert!(!handle.is_null(), "process {pid} is gone");
// SAFETY: OpenProcess returned a new, uniquely owned handle.
let handle = unsafe { OwnedHandle::from_raw_handle(handle) };
let mut result = 0;
// SAFETY: the handle stays valid through the call.
unsafe { IsProcessInJob(handle.as_raw_handle(), null_mut(), &mut result) };
result != 0
}
fn kill_and_wait(service: &TerminalService, id: TerminalId) {
service.signal(id, ProcessSignal::Kill).unwrap();
let exit = service.wait(id).unwrap().recv().unwrap();
assert_eq!(exit.signal.as_deref(), Some("SIGKILL"));
}
#[test]
fn signal_reaches_a_grandchild_of_store_powershell() {
let Some(alias) = store_powershell() else {
return;
};
let service = TerminalService::default();
let pid_file = TempPath::new("store-grandchild-pid");
let script = TempPath::script("store-grandchild", "ps1");
fs::write(
&script.0,
format!(
r#"
$child = [System.Diagnostics.Process]::Start('ping.exe', '-n 60 127.0.0.1')
[System.IO.File]::WriteAllText('{}', "$($child.Id)")
Start-Sleep -Seconds 60
"#,
ps_path(&pid_file.0)
),
)
.unwrap();
let script = StoreScript::new("store-grandchild");
let (info, _file) = start(&service, |file| {
pipe(alias.to_str().unwrap(), script.args(), file, base_env())
});
let (_, grandchild) = script.processes();
assert!(alive(grandchild.0));
kill_and_wait(&service, info.id);
wait_dead(grandchild.0);
service.terminate(info.id).unwrap();
}
#[test]
fn signal_reaches_a_store_app_started_by_another_program() {
let Some(alias) = store_powershell() else {
return;
};
let service = TerminalService::default();
let script = StoreScript::new("store-nested");
let outer = batch_running("store-nested-outer", &alias, &script.args());
let (info, _file) = start(&service, |file| cmd(&outer.0.display().to_string(), file));
// Store PowerShell left the job for its package's job, and its ping left
// every job.
let (powershell, ping) = script.processes();
kill_and_wait(&service, info.id);
wait_dead(powershell.0);
wait_dead(ping.0);
service.terminate(info.id).unwrap();
}
#[test]
fn signal_reaches_the_children_of_store_powershell_started_by_store_powershell() {
let Some(alias) = store_powershell() else {
return;
};
let service = TerminalService::default();
let script = StoreScript::new("store-in-store");
// PowerShell does not wait for an app execution alias it starts.
let command = format!(
"& '{}' {}; Start-Sleep -Seconds 60",
ps_path(&alias),
script
.args()
.iter()
.map(|arg| format!("'{}'", arg.replace('\'', "''")))
.collect::<Vec<_>>()
.join(" ")
);
let (info, _file) = start(&service, |file| {
pipe(
alias.to_str().unwrap(),
vec![
"-NoProfile".into(),
"-NonInteractive".into(),
"-ExecutionPolicy".into(),
"Bypass".into(),
"-File".into(),
script.0.display().to_string(),
"-Command".into(),
command,
],
file,
base_env(),
shell_env(),
)
});
let grandchild = KillOnDrop(read_pid(&pid_file.0));
assert!(alive(grandchild.0));
service.signal(info.id, ProcessSignal::Kill).unwrap();
let exit = service.wait(info.id).unwrap().recv().unwrap();
assert_eq!(exit.signal.as_deref(), Some("SIGKILL"));
wait_dead(grandchild.0);
// The inner PowerShell stays in the job, but nothing gave it the
// desktop-app policy, so its ping left every job.
let (powershell, ping) = script.processes();
kill_and_wait(&service, info.id);
wait_dead(powershell.0);
wait_dead(ping.0);
service.terminate(info.id).unwrap();
}
#[test]
fn processes_that_leave_the_job_are_put_back_in_one() {
let Some(alias) = store_powershell() else {
return;
};
let service = TerminalService::default();
let script = StoreScript::new("store-adopted");
let outer = batch_running("store-adopted-outer", &alias, &script.args());
let (info, _file) = start(&service, |file| cmd(&outer.0.display().to_string(), file));
let (_powershell, ping) = script.processes();
// In a job again, a daemon crash takes it down too.
let deadline = Instant::now() + Duration::from_secs(5);
while !in_a_job(ping.0) {
assert!(
Instant::now() < deadline,
"the ping was not put back in a job"
);
std::thread::sleep(Duration::from_millis(20));
}
service.terminate(info.id).unwrap();
wait_dead(ping.0);
}
#[test]
fn a_failed_exit_terminates_a_store_app_it_started() {
let Some(alias) = store_powershell() else {
return;
};
let service = TerminalService::default();
let script = StoreScript::new("store-failed");
let args = script
.args()
.iter()
.map(|arg| format!("\"{arg}\""))
.collect::<Vec<_>>()
.join(" ");
let outer = batch(
"store-failed-outer",
&[
"@echo off".to_string(),
format!("start /b \"\" \"{}\" {args}", alias.display()),
":wait".to_string(),
format!("if exist \"{}\" exit /b 1", script.pids.0.display()),
"ping -n 2 127.0.0.1 >nul".to_string(),
"goto wait".to_string(),
],
);
let (info, file) = start(&service, |file| {
pipe(
"cmd.exe",
vec!["/d".into(), "/c".into(), outer.0.display().to_string()],
file,
shell_env(),
)
});
let (powershell, ping) = script.processes();
assert_eq!(run(&service, info.id, &file).exit.exit_code, Some(1));
wait_dead(powershell.0);
wait_dead(ping.0);
service.terminate(info.id).unwrap();
}

View file

@ -18,12 +18,13 @@ use opencode_pty::protocol::{
AttachmentRole, Envelope, Request, Response, SubscriptionEvent, read_frame,
read_subscription_event, write_frame,
};
use opencode_pty::service::{CreatePty, ProcessInfo, ProcessMode, TerminalLifecycle};
use opencode_pty::service::{CreatePty, PipeMetadata, ProcessInfo, ProcessMode, TerminalLifecycle};
use terminal_fixture::{Command as FixtureCommand, Deadline, Fixture, TempDir};
use windows_sys::Win32::Foundation::WAIT_OBJECT_0;
use windows_sys::Win32::System::JobObjects::IsProcessInJob;
use windows_sys::Win32::System::Threading::{
GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE,
WaitForSingleObject,
PROCESS_TERMINATE, TerminateProcess, WaitForSingleObject,
};
struct Daemon {
@ -701,3 +702,135 @@ fn observer_disconnect_and_control_input_preserve_independent_terminals() {
drop(owner);
daemon.wait();
}
/// A directory removed when dropped.
struct TempFiles(PathBuf);
impl Drop for TempFiles {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// Kills a test process even when an assertion fails first.
struct Killed(OwnedHandle);
impl Killed {
fn open(pid: u32) -> Self {
// SAFETY: a successful handle is adopted immediately.
let handle = unsafe {
OpenProcess(
PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_SYNCHRONIZE | PROCESS_TERMINATE,
0,
pid,
)
};
assert!(!handle.is_null(), "process {pid} is gone");
// SAFETY: OpenProcess returned a new, uniquely owned handle.
Self(unsafe { OwnedHandle::from_raw_handle(handle) })
}
fn in_a_job(&self) -> bool {
let mut result = 0;
// SAFETY: the handle stays open through the call.
unsafe { IsProcessInJob(self.0.as_raw_handle(), std::ptr::null_mut(), &mut result) };
result != 0
}
fn dies(&self) -> bool {
// SAFETY: the handle stays open through the wait.
unsafe { WaitForSingleObject(self.0.as_raw_handle(), 10_000) == WAIT_OBJECT_0 }
}
}
impl Drop for Killed {
fn drop(&mut self) {
// SAFETY: the handle has PROCESS_TERMINATE access and is still open.
unsafe { TerminateProcess(self.0.as_raw_handle(), 1) };
}
}
#[test]
fn a_daemon_crash_kills_store_processes_that_left_the_job() {
// Only where PowerShell 7 is installed from the Microsoft Store.
let Some(alias) = std::env::var_os("LOCALAPPDATA")
.map(|dir| Path::new(&dir).join(r"Microsoft\WindowsApps\pwsh.exe"))
.filter(|alias| alias.exists())
else {
return;
};
let _deadline = Deadline::new();
let mut daemon = Daemon::start();
let (_owner, response) = daemon.own(None);
assert!(matches!(response, Response::Owned));
// cmd.exe reads a batch file in the console code page, so these paths stay
// ASCII rather than living in the fixture's Unicode directory.
let root = TempFiles(std::env::temp_dir().join(format!(
"opencode-pty-store-crash-{:016x}",
rand::random::<u64>()
)));
std::fs::create_dir(&root.0).unwrap();
let root = &root.0;
let pids = root.join("store-pids");
let script = root.join("store.ps1");
std::fs::write(
&script,
format!(
"$child = [System.Diagnostics.Process]::Start('ping.exe', '-n 60 127.0.0.1')\n[System.IO.File]::WriteAllText('{}', \"$PID $($child.Id)\")\nStart-Sleep -Seconds 60\n",
pids.display().to_string().replace('\'', "''")
),
)
.unwrap();
// Started by cmd.exe, Store PowerShell leaves the job for its package's
// job, and its ping leaves every job.
let outer = root.join("outer.cmd");
std::fs::write(
&outer,
format!(
"@echo off\r\n\"{}\" -NoProfile -NonInteractive -ExecutionPolicy Bypass -File \"{}\"\r\n",
alias.display(),
script.display()
),
)
.unwrap();
let response = daemon.request(Request::CreatePipe {
program: "cmd.exe".into(),
args: vec!["/d".into(), "/c".into(), outer.display().to_string()],
cwd: root.clone(),
env: ["PATH", "SystemRoot", "TEMP"]
.into_iter()
.filter_map(|name| Some((name.to_string(), std::env::var(name).ok()?)))
.collect(),
group_id: "store".into(),
output_path: root.join("out"),
metadata: PipeMetadata::new(),
});
assert!(matches!(response, Response::Created { .. }), "{response:?}");
let deadline = Instant::now() + Duration::from_secs(10);
let (powershell, ping) = loop {
if let Ok(text) = std::fs::read_to_string(&pids)
&& let Some((powershell, ping)) = text.trim().split_once(' ')
{
break (
Killed::open(powershell.parse().unwrap()),
Killed::open(ping.parse().unwrap()),
);
}
assert!(
Instant::now() < deadline,
"the script did not write its PIDs"
);
thread::sleep(Duration::from_millis(20));
};
while !ping.in_a_job() {
assert!(
Instant::now() < deadline,
"the ping was not put back in a job"
);
thread::sleep(Duration::from_millis(20));
}
daemon.child.kill().unwrap();
daemon.child.wait().unwrap();
assert!(powershell.dies(), "Store PowerShell survived the daemon");
assert!(ping.dies(), "its ping survived the daemon");
}