Terminate Windows process trees with job objects (#34624)

## Why

Terminating a Windows execution session must also stop child processes, while a
normal root-process exit must continue to allow background descendants to run.

## What changed

- Assign Windows pipe, ConPTY, and sandbox processes to job objects and terminate
  the job when a session is cancelled, times out, or is explicitly stopped.
- Preserve descendants when the root process exits normally.
- Attach ConPTY and sandbox processes to their jobs atomically at creation; keep
  root-process termination as a fallback where job setup is unavailable.

## Testing

Added Windows coverage for descendant termination and preservation across pipe,
ConPTY, capture, cancellation, and legacy sandbox execution paths.

GitOrigin-RevId: 8f831f2fc4caaa7b79ce842a3ed7192bd02dd3b4
This commit is contained in:
iceweasel-oai authored and copyberry committed 2026-07-21 22:07:09 +00:00
1 parent ded4eacdbd
commit 9b33613db6
16 files changed
+946 -241

No files matched your search

+122
View File
@@ -0,0 +1,122 @@
use filedescriptor::OwnedHandle;
use std::io;
use std::os::windows::io::AsRawHandle;
use std::os::windows::io::FromRawHandle;
use std::os::windows::io::RawHandle;
use std::sync::Mutex;
use winapi::um::jobapi2::AssignProcessToJobObject;
use winapi::um::jobapi2::CreateJobObjectW;
use winapi::um::jobapi2::SetInformationJobObject;
use winapi::um::jobapi2::TerminateJobObject;
use winapi::um::winnt::JOB_OBJECT_LIMIT_BREAKAWAY_OK;
use winapi::um::winnt::JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
use winapi::um::winnt::JOBOBJECT_EXTENDED_LIMIT_INFORMATION;
use winapi::um::winnt::JobObjectExtendedLimitInformation;
/// Owns a Windows Job Object used to terminate a spawned process tree.
#[derive(Debug)]
pub struct JobObject {
handle: OwnedHandle,
// A mutex makes the state check, Job Object API call, and state update
// atomic with respect to concurrent preserve and terminate requests.
preserve_descendants: Mutex<bool>,
}
impl JobObject {
/// Creates a Job Object configured to terminate all members when its last handle closes.
pub fn create() -> io::Result<Self> {
let handle = unsafe { CreateJobObjectW(std::ptr::null_mut(), std::ptr::null()) };
if handle.is_null() {
return Err(io::Error::last_os_error());
}
let handle = unsafe { OwnedHandle::from_raw_handle(handle.cast()) };
Self::set_limit_flags(
&handle,
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE | JOB_OBJECT_LIMIT_BREAKAWAY_OK,
)?;
Ok(Self {
handle,
preserve_descendants: Mutex::new(false),
})
}
fn set_limit_flags(handle: &OwnedHandle, flags: u32) -> io::Result<()> {
let mut limits: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { std::mem::zeroed() };
limits.BasicLimitInformation.LimitFlags = flags;
let configured = unsafe {
SetInformationJobObject(
handle.as_raw_handle().cast(),
JobObjectExtendedLimitInformation,
std::ptr::addr_of_mut!(limits).cast(),
std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
)
};
if configured == 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
/// Assigns a running process to this job.
///
/// Assignment is not retroactive: descendants created before this call
/// completes are not guaranteed to become members of the job.
pub(crate) fn assign_process(&self, process_handle: RawHandle) -> io::Result<()> {
let assigned = unsafe {
AssignProcessToJobObject(self.handle.as_raw_handle().cast(), process_handle.cast())
};
if assigned == 0 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
/// Allows contained descendants to keep running after the root exits normally.
///
/// This disables both explicit job termination and kill-on-close for this
/// object. Calls race safely with [`Self::terminate`]: whichever operation
/// acquires the state lock first determines whether the process tree is
/// preserved or terminated.
pub fn preserve_descendants(&self) -> io::Result<()> {
let mut preserve_descendants = self
.preserve_descendants
.lock()
.map_err(|_| io::Error::other("job state lock poisoned"))?;
if *preserve_descendants {
return Ok(());
}
Self::set_limit_flags(&self.handle, JOB_OBJECT_LIMIT_BREAKAWAY_OK)?;
*preserve_descendants = true;
Ok(())
}
/// Terminates every process currently assigned to the job.
pub fn terminate(&self) -> io::Result<()> {
let preserve_descendants = self
.preserve_descendants
.lock()
.map_err(|_| io::Error::other("job state lock poisoned"))?;
if *preserve_descendants {
return Ok(());
}
let terminated = unsafe {
TerminateJobObject(self.handle.as_raw_handle().cast(), /*uExitCode*/ 1)
};
if terminated == 0 {
Err(io::Error::last_os_error())
} else {
Ok(())
}
}
}
impl AsRawHandle for JobObject {
fn as_raw_handle(&self) -> RawHandle {
self.handle.as_raw_handle()
}
}
+32 -26
View File
@@ -19,12 +19,8 @@
// SOFTWARE.
// Local modifications:
// - Fix Codex bug #13945 in the Windows PTY kill path. The vendored code treated
// `TerminateProcess`'s nonzero success return as failure and `0` as success,
// which inverts kill outcomes for both `WinChild::do_kill` and
// `WinChildKiller::kill`.
// - This bug still exists in the original WezTerm source as of 2026-03-08, so
// this is an intentional divergence from upstream.
// - Place spawned processes in a Job Object so kill operations terminate the
// full process tree, while normal root exit preserves background descendants.
use anyhow::Context as _;
use filedescriptor::OwnedHandle;
@@ -35,6 +31,7 @@ use std::io::Error as IoError;
use std::io::Result as IoResult;
use std::os::windows::io::AsRawHandle;
use std::pin::Pin;
use std::sync::Arc;
use std::sync::Mutex;
use std::task::Context;
use std::task::Poll;
@@ -45,19 +42,29 @@ use winapi::um::synchapi::WaitForSingleObject;
use winapi::um::winbase::INFINITE;
pub(crate) mod conpty;
mod job;
mod procthreadattr;
mod psuedocon;
pub use conpty::ConPtySystem;
pub use job::JobObject;
pub use psuedocon::PsuedoCon;
pub use psuedocon::conpty_supported;
#[derive(Debug)]
pub struct WinChild {
proc: Mutex<OwnedHandle>,
job: Arc<JobObject>,
}
impl WinChild {
pub(crate) fn new(proc: OwnedHandle, job: Arc<JobObject>) -> Self {
Self {
proc: Mutex::new(proc),
job,
}
}
fn is_complete(&mut self) -> IoResult<Option<ExitStatus>> {
let mut status: DWORD = 0;
let proc = self.proc.lock().unwrap().try_clone().unwrap();
@@ -66,6 +73,7 @@ impl WinChild {
if status == STILL_ACTIVE {
Ok(None)
} else {
self.preserve_descendants();
Ok(Some(ExitStatus::with_exit_code(status)))
}
} else {
@@ -74,48 +82,45 @@ impl WinChild {
}
fn do_kill(&mut self) -> IoResult<()> {
let proc = self.proc.lock().unwrap().try_clone().unwrap();
let res = unsafe { TerminateProcess(proc.as_raw_handle() as _, 1) };
// Codex bug #13945: Win32 returns nonzero on success, so only `0` is an error.
if res == 0 {
Err(IoError::last_os_error())
} else {
Ok(())
self.job.terminate()
}
fn preserve_descendants(&self) {
if let Err(err) = self.job.preserve_descendants() {
log::warn!("ConPTY failed to preserve descendants after root exit: {err}");
}
}
}
impl ChildKiller for WinChild {
fn kill(&mut self) -> IoResult<()> {
self.do_kill().ok();
if let Err(err) = self.do_kill() {
log::warn!("ConPTY failed to terminate process tree: {err}");
}
Ok(())
}
fn clone_killer(&self) -> Box<dyn ChildKiller + Send + Sync> {
let proc = self.proc.lock().unwrap().try_clone().unwrap();
Box::new(WinChildKiller { proc })
Box::new(WinChildKiller {
job: Arc::clone(&self.job),
})
}
}
#[derive(Debug)]
pub struct WinChildKiller {
proc: OwnedHandle,
job: Arc<JobObject>,
}
impl ChildKiller for WinChildKiller {
fn kill(&mut self) -> IoResult<()> {
let res = unsafe { TerminateProcess(self.proc.as_raw_handle() as _, 1) };
// Codex bug #13945: Win32 returns nonzero on success, so only `0` is an error.
if res == 0 {
Err(IoError::last_os_error())
} else {
Ok(())
}
self.job.terminate()
}
fn clone_killer(&self) -> Box<dyn ChildKiller + Send + Sync> {
let proc = self.proc.try_clone().unwrap();
Box::new(WinChildKiller { proc })
Box::new(WinChildKiller {
job: Arc::clone(&self.job),
})
}
}
@@ -135,6 +140,7 @@ impl Child for WinChild {
let mut status: DWORD = 0;
let res = unsafe { GetExitCodeProcess(proc.as_raw_handle() as _, &mut status) };
if res != 0 {
self.preserve_descendants();
Ok(ExitStatus::with_exit_code(status))
} else {
Err(IoError::last_os_error())
+40 -4
View File
@@ -21,16 +21,20 @@
use super::psuedocon::HPCON;
use anyhow::Error;
use anyhow::ensure;
use std::ffi::c_void;
use std::io::Error as IoError;
use std::mem;
use std::ptr;
use winapi::shared::minwindef::DWORD;
use winapi::um::processthreadsapi::*;
use winapi::um::winnt::HANDLE;
const PROC_THREAD_ATTRIBUTE_JOB_LIST: usize = 0x0002000D;
const PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE: usize = 0x00020016;
pub struct ProcThreadAttributeList {
data: Vec<u8>,
job_list: Vec<HANDLE>,
}
impl ProcThreadAttributeList {
@@ -56,7 +60,10 @@ impl ProcThreadAttributeList {
"InitializeProcThreadAttributeList failed: {}",
IoError::last_os_error()
);
Ok(Self { data })
Ok(Self {
data,
job_list: Vec::new(),
})
}
pub fn as_mut_ptr(&mut self) -> LPPROC_THREAD_ATTRIBUTE_LIST {
@@ -64,13 +71,42 @@ impl ProcThreadAttributeList {
}
pub fn set_pty(&mut self, con: HPCON) -> Result<(), Error> {
// SAFETY: `con` is the Windows-defined value and size for this attribute.
unsafe {
self.update(
PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE,
con,
mem::size_of::<HPCON>(),
)
}
}
pub fn set_job(&mut self, job: HANDLE) -> Result<(), Error> {
// Atomic job attachment is intentionally required for native ConPTY
// spawns. If Windows cannot honor the job list (for example, because a
// parent job forbids nesting), fail the spawn rather than briefly run
// an uncontained process tree.
self.job_list = vec![job];
let value = self.job_list.as_mut_ptr().cast();
let size = std::mem::size_of_val(self.job_list.as_slice());
// SAFETY: `value` points to `self.job_list`, which remains alive while
// the attribute list can reference it, and `size` covers that slice.
unsafe { self.update(PROC_THREAD_ATTRIBUTE_JOB_LIST, value, size) }
}
unsafe fn update(
&mut self,
attribute: usize,
value: *mut c_void,
size: usize,
) -> Result<(), Error> {
let res = unsafe {
UpdateProcThreadAttribute(
self.as_mut_ptr(),
0,
PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE,
con,
mem::size_of::<HPCON>(),
attribute,
value,
size,
ptr::null_mut(),
ptr::null_mut(),
)
+6 -5
View File
@@ -20,6 +20,7 @@
// SOFTWARE.
use super::WinChild;
use crate::win::job::JobObject;
use crate::win::procthreadattr::ProcThreadAttributeList;
use anyhow::Error;
use anyhow::bail;
@@ -40,7 +41,7 @@ use std::os::windows::io::AsRawHandle;
use std::os::windows::io::FromRawHandle;
use std::path::Path;
use std::ptr;
use std::sync::Mutex;
use std::sync::Arc;
use winapi::shared::minwindef::DWORD;
use winapi::shared::ntdef::NTSTATUS;
use winapi::shared::ntstatus::STATUS_SUCCESS;
@@ -173,6 +174,7 @@ impl PsuedoCon {
}
pub fn spawn_command(&self, cmd: CommandBuilder) -> anyhow::Result<WinChild> {
let job = Arc::new(JobObject::create()?);
let mut si: STARTUPINFOEXW = unsafe { mem::zeroed() };
si.StartupInfo.cb = mem::size_of::<STARTUPINFOEXW>() as u32;
si.StartupInfo.dwFlags = STARTF_USESTDHANDLES;
@@ -180,8 +182,9 @@ impl PsuedoCon {
si.StartupInfo.hStdOutput = INVALID_HANDLE_VALUE;
si.StartupInfo.hStdError = INVALID_HANDLE_VALUE;
let mut attrs = ProcThreadAttributeList::with_capacity(/*num_attributes*/ 1)?;
let mut attrs = ProcThreadAttributeList::with_capacity(/*num_attributes*/ 2)?;
attrs.set_pty(self.con)?;
attrs.set_job(job.as_raw_handle().cast())?;
si.lpAttributeList = attrs.as_mut_ptr();
let mut pi: PROCESS_INFORMATION = unsafe { mem::zeroed() };
@@ -221,9 +224,7 @@ impl PsuedoCon {
let _main_thread = unsafe { OwnedHandle::from_raw_handle(pi.hThread as _) };
let proc = unsafe { OwnedHandle::from_raw_handle(pi.hProcess as _) };
Ok(WinChild {
proc: Mutex::new(proc),
})
Ok(WinChild::new(proc, job))
}
}