use std::ffi::c_void;
use std::io;
use std::mem::size_of;
use std::sync::RwLock;
use windows::Win32::Foundation::{
CloseHandle, SetHandleInformation, HANDLE, HANDLE_FLAGS, HANDLE_FLAG_INHERIT, WAIT_FAILED, WAIT_OBJECT_0,
WAIT_TIMEOUT,
};
use windows::Win32::System::Console::{GetStdHandle, STD_ERROR_HANDLE, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE};
use windows::Win32::System::JobObjects::{
AssignProcessToJobObject, CreateJobObjectW, JobObjectBasicProcessIdList, JobObjectExtendedLimitInformation,
QueryInformationJobObject, SetInformationJobObject, TerminateJobObject, JOBOBJECT_BASIC_PROCESS_ID_LIST,
JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
};
use windows::Win32::System::Threading::{
GetProcessId, GetProcessIdOfThread, OpenProcess, OpenThread, ResumeThread, WaitForMultipleObjects,
WaitForSingleObject, CREATE_NEW_PROCESS_GROUP, CREATE_SUSPENDED, PROCESS_QUERY_LIMITED_INFORMATION,
PROCESS_SYNCHRONIZE, THREAD_QUERY_LIMITED_INFORMATION, THREAD_SUSPEND_RESUME,
};
use crate::error::{io_context, win32_io_error};
fn null_ptr() -> *mut c_void {
std::ptr::null_mut()
}
pub(crate) struct JobHandle {
raw: RwLock<*mut c_void>,
}
unsafe impl Send for JobHandle {}
unsafe impl Sync for JobHandle {}
impl std::fmt::Debug for JobHandle {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("JobHandle").field("raw", &self.peek()).finish()
}
}
impl JobHandle {
fn new(handle: HANDLE) -> Self {
debug_assert!(!handle.0.is_null(), "job handle must not be null");
JobHandle {
raw: RwLock::new(handle.0),
}
}
fn peek(&self) -> *mut c_void {
*self.raw.read().unwrap_or_else(|e| e.into_inner())
}
pub(crate) fn with_handle<R>(&self, f: impl FnOnce(HANDLE) -> R) -> Option<R> {
let guard = self.raw.read().unwrap_or_else(|e| e.into_inner());
if guard.is_null() {
None
} else {
Some(f(HANDLE(*guard)))
}
}
fn take(&self) -> Option<HANDLE> {
let mut guard = self.raw.write().unwrap_or_else(|e| e.into_inner());
let p = std::mem::replace(&mut *guard, null_ptr());
if p.is_null() {
None
} else {
Some(HANDLE(p))
}
}
pub(crate) fn hard_kill(&self) -> io::Result<()> {
let Some(job) = self.take() else { return Ok(()) };
unsafe {
let terminated = TerminateJobObject(job, 1).map_err(win32_io_error);
if let Err(e) = CloseHandle(job) {
log::warn!("CloseHandle on the job failed ({e}); the handle is leaked");
}
terminated
}
}
pub(crate) fn disarm(&self) -> io::Result<()> {
self.with_handle(|job| {
let info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
unsafe {
SetInformationJobObject(
job,
JobObjectExtendedLimitInformation,
std::ptr::addr_of!(info).cast(),
size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
)
}
.map_err(win32_io_error)
})
.unwrap_or(Ok(()))
}
}
#[cfg(all(windows, test))]
impl JobHandle {
pub(crate) fn as_handle(&self) -> Option<HANDLE> {
let p = self.peek();
if p.is_null() {
None
} else {
Some(HANDLE(p))
}
}
pub(crate) fn create_empty_for_test() -> JobHandle {
let handle = unsafe { CreateJobObjectW(None, windows::core::PCWSTR::null()) }
.expect("CreateJobObjectW for test placeholder");
JobHandle::new(handle)
}
pub(crate) fn create_without_set_access_for_test() -> JobHandle {
use windows::Win32::Foundation::{DuplicateHandle, DUPLICATE_HANDLE_OPTIONS};
use windows::Win32::System::SystemServices::{JOB_OBJECT_QUERY, JOB_OBJECT_TERMINATE};
use windows::Win32::System::Threading::GetCurrentProcess;
let full = JobHandle::create_empty_for_test();
let mut weak = HANDLE::default();
full.with_handle(|job| {
unsafe {
DuplicateHandle(
GetCurrentProcess(),
job,
GetCurrentProcess(),
&mut weak,
JOB_OBJECT_QUERY | JOB_OBJECT_TERMINATE,
false,
DUPLICATE_HANDLE_OPTIONS(0),
)
}
})
.expect("the empty job is live")
.expect("DuplicateHandle with reduced access");
JobHandle::new(weak)
}
}
impl Drop for JobHandle {
fn drop(&mut self) {
if let Some(job) = self.take() {
unsafe {
if let Err(e) = CloseHandle(job) {
log::warn!("closing the job handle failed ({e}); the tree may still be running");
}
}
}
}
}
pub(crate) fn root_flags() -> u32 {
CREATE_SUSPENDED.0 | CREATE_NEW_PROCESS_GROUP.0
}
pub(crate) fn group_flags() -> u32 {
CREATE_NEW_PROCESS_GROUP.0
}
pub(crate) fn mechanism_from_flags(creation_flags: u32) -> crate::graceful::GracefulMechanism {
use crate::graceful::GracefulMechanism;
use windows::Win32::System::Threading::{CREATE_NEW_CONSOLE, CREATE_NO_WINDOW, DETACHED_PROCESS};
if creation_flags & CREATE_NEW_PROCESS_GROUP.0 == 0 {
return GracefulMechanism::None;
}
let out_of_console = DETACHED_PROCESS.0 | CREATE_NEW_CONSOLE.0 | CREATE_NO_WINDOW.0;
if creation_flags & out_of_console != 0 {
return GracefulMechanism::OtherConsoleGroup;
}
GracefulMechanism::ConsoleGroup
}
pub(crate) fn clear_std_handle_inheritance() {
for std_handle in [STD_INPUT_HANDLE, STD_OUTPUT_HANDLE, STD_ERROR_HANDLE] {
unsafe {
if let Ok(h) = GetStdHandle(std_handle) {
if !h.is_invalid() {
_ = SetHandleInformation(h, HANDLE_FLAG_INHERIT.0, HANDLE_FLAGS(0));
}
}
}
}
#[cfg(test)]
observe::record_inheritance_cleared();
}
pub(crate) fn caller_has_console() -> io::Result<bool> {
use windows::Win32::Foundation::{SetLastError, ERROR_INVALID_HANDLE, WIN32_ERROR};
use windows::Win32::System::Console::GetConsoleProcessList;
#[cfg(test)]
if fault::take_force_console_probe_error() {
return Err(io::Error::from_raw_os_error(
windows::Win32::Foundation::ERROR_INVALID_PARAMETER.0 as i32,
));
}
let mut list = [0u32; 1];
let n = unsafe {
SetLastError(WIN32_ERROR(0));
GetConsoleProcessList(&mut list)
};
if n != 0 {
return Ok(true);
}
let err = io::Error::last_os_error();
if err.raw_os_error() == Some(ERROR_INVALID_HANDLE.0 as i32) {
Ok(false)
} else {
Err(err)
}
}
pub(crate) fn classify_ctrl_event_failure(pid: u32, err: io::Error, console: io::Result<bool>) -> crate::error::Error {
use windows::Win32::Foundation::ERROR_INVALID_HANDLE;
let no_console = ERROR_INVALID_HANDLE.0 as i32;
if err.raw_os_error() == Some(no_console) && matches!(console, Ok(true)) {
log::warn!(
"CTRL_BREAK to group {pid} failed with ERROR_INVALID_HANDLE, but a console is \
attached; surfacing the raw error rather than claiming NoConsole"
);
return crate::error::Error::Io(err);
}
if err.raw_os_error() == Some(no_console) {
if let Err(probe) = &console {
log::warn!("CTRL_BREAK to group {pid}: the console probe failed ({probe}); cannot classify");
return crate::error::Error::Io(err);
}
return crate::error::Error::NoConsole {
detail: format!(
"cannot send CTRL_BREAK to process group {pid}: this process has no attached \
console. A GUI-subsystem binary, a service, or a detached spawn cannot deliver \
console control events — Windows delivers them only within the caller's \
console. Attach a console before spawning the tree, or use kill_tree() for a \
hard teardown."
),
};
}
if let Err(probe) = &console {
log::warn!("CTRL_BREAK to group {pid} failed, and the console probe also failed ({probe})");
}
crate::error::Error::Io(err)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum JobBreakaway {
NotInJob,
Permitted,
SilentBreakaway,
Forbidden,
Unknown,
}
pub(crate) fn probe_job_breakaway() -> JobBreakaway {
use windows::Win32::System::JobObjects::{
IsProcessInJob, JobObjectBasicLimitInformation, QueryInformationJobObject, JOBOBJECT_BASIC_LIMIT_INFORMATION,
JOB_OBJECT_LIMIT, JOB_OBJECT_LIMIT_BREAKAWAY_OK, JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK,
};
use windows::Win32::System::Threading::GetCurrentProcess;
#[cfg(test)]
if fault::take_force_job_probe_error() {
return JobBreakaway::Unknown;
}
let mut in_job = windows::core::BOOL(0);
if unsafe { IsProcessInJob(GetCurrentProcess(), None, &mut in_job) }.is_err() {
return JobBreakaway::Unknown;
}
if !in_job.as_bool() {
return JobBreakaway::NotInJob;
}
let mut info = JOBOBJECT_BASIC_LIMIT_INFORMATION::default();
let queried = unsafe {
QueryInformationJobObject(
None,
JobObjectBasicLimitInformation,
std::ptr::addr_of_mut!(info).cast(),
size_of::<JOBOBJECT_BASIC_LIMIT_INFORMATION>() as u32,
None,
)
};
if queried.is_err() {
return JobBreakaway::Unknown;
}
if info.LimitFlags & JOB_OBJECT_LIMIT_BREAKAWAY_OK != JOB_OBJECT_LIMIT(0) {
return JobBreakaway::Permitted;
}
if info.LimitFlags & JOB_OBJECT_LIMIT_SILENT_BREAKAWAY_OK != JOB_OBJECT_LIMIT(0) {
return JobBreakaway::SilentBreakaway;
}
JobBreakaway::Forbidden
}
pub(crate) fn terminate(pid: u32) -> Result<(), crate::error::Error> {
use windows::Win32::System::Console::{GenerateConsoleCtrlEvent, CTRL_BREAK_EVENT};
debug_assert!(
pid != 0,
"pid 0 addresses every process attached to the caller's console, including the caller"
);
terminate_with(
pid,
|| unsafe { GenerateConsoleCtrlEvent(CTRL_BREAK_EVENT, pid) },
caller_has_console,
)
}
fn terminate_with(
pid: u32,
send: impl FnOnce() -> windows::core::Result<()>,
console: impl FnOnce() -> io::Result<bool>,
) -> Result<(), crate::error::Error> {
match send() {
Ok(()) => {
#[cfg(test)]
observe::record_ctrl_break(pid);
Ok(())
}
Err(e) => Err(classify_ctrl_event_failure(pid, win32_io_error(e), console())),
}
}
#[cfg(test)]
pub(crate) mod observe {
use std::cell::{Cell, RefCell};
thread_local! {
static INHERITANCE_CLEARED: Cell<bool> = const { Cell::new(false) };
static CTRL_BREAKS: RefCell<Vec<u32>> = const { RefCell::new(Vec::new()) };
}
pub(crate) fn record_inheritance_cleared() {
INHERITANCE_CLEARED.with(|f| f.set(true));
}
pub(crate) fn take_inheritance_cleared() -> bool {
INHERITANCE_CLEARED.with(|f| f.replace(false))
}
pub(crate) fn record_ctrl_break(group: u32) {
CTRL_BREAKS.with(|b| b.borrow_mut().push(group));
}
pub(crate) fn take_ctrl_breaks() -> Vec<u32> {
CTRL_BREAKS.with(|b| std::mem::take(&mut *b.borrow_mut()))
}
}
#[cfg(test)]
pub(crate) mod fault {
use std::cell::Cell;
thread_local! {
static FORCE_CONSOLE_PROBE_ERROR: Cell<bool> = const { Cell::new(false) };
}
pub(crate) fn set_force_console_probe_error(on: bool) {
FORCE_CONSOLE_PROBE_ERROR.with(|f| f.set(on));
}
thread_local! {
static FORCE_JOB_PROBE_ERROR: Cell<bool> = const { Cell::new(false) };
}
pub(crate) fn set_force_job_probe_error(on: bool) {
FORCE_JOB_PROBE_ERROR.with(|f| f.set(on));
}
pub(crate) fn take_force_job_probe_error() -> bool {
FORCE_JOB_PROBE_ERROR.with(|f| f.replace(false))
}
pub(crate) fn take_force_console_probe_error() -> bool {
FORCE_CONSOLE_PROBE_ERROR.with(|f| f.replace(false))
}
pub(crate) fn armed() -> bool {
FORCE_CONSOLE_PROBE_ERROR.with(|f| f.get())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Step {
QueryOpen,
Owner,
ResumeOpen,
Resume,
CreationTime,
Assign,
}
thread_local! {
static INJECTED: Cell<Option<(u32, Option<u32>)>> = const { Cell::new(None) };
static INJECTED_VISIT: Cell<Option<Option<super::Visit>>> = const { Cell::new(None) };
static FORCED: Cell<Option<(Step, u32, Option<u32>)>> = const { Cell::new(None) };
static EQUAL_CREATION_TIMES: Cell<bool> = const { Cell::new(false) };
}
pub(crate) fn inject_snapshot_tid(tid: u32, owner: Option<u32>) -> Injected {
INJECTED.with(|f| {
debug_assert!(f.get().is_none(), "a snapshot tid is already injected");
f.set(Some((tid, owner)));
});
INJECTED_VISIT.with(|f| f.set(None));
Injected(())
}
pub(crate) fn injected_entry() -> Option<(u32, Option<u32>)> {
INJECTED.with(|f| f.get())
}
pub(crate) fn record_injected_visit(visit: Option<super::Visit>) {
INJECTED_VISIT.with(|f| f.set(Some(visit)));
}
pub(crate) fn take_injected_visit() -> Option<Option<super::Visit>> {
INJECTED_VISIT.with(|f| f.take())
}
pub(crate) fn force_next(step: Step, code: u32) -> Forced {
arm(step, code, None)
}
pub(crate) fn force_next_for_thread(step: Step, code: u32, tid: u32) -> Forced {
arm(step, code, Some(tid))
}
fn arm(step: Step, code: u32, tid: Option<u32>) -> Forced {
FORCED.with(|f| {
debug_assert!(f.get().is_none(), "a failure is already forced");
f.set(Some((step, code, tid)));
});
Forced(())
}
pub(crate) fn forced_is_armed() -> bool {
FORCED.with(|f| f.get().is_some())
}
pub(crate) fn take_forced(step: Step, tid: Option<u32>) -> Option<u32> {
FORCED.with(|f| match f.get() {
Some((armed, code, only)) if armed == step && (only.is_none() || only == tid) => {
f.set(None);
Some(code)
}
_ => None,
})
}
pub(crate) fn equal_creation_times() -> EqualTimes {
EQUAL_CREATION_TIMES.with(|f| f.set(true));
EqualTimes(())
}
pub(crate) fn creation_times_are_equal() -> bool {
EQUAL_CREATION_TIMES.with(|f| f.get())
}
#[must_use = "dropping this immediately restores the real clock"]
pub(crate) struct EqualTimes(());
impl Drop for EqualTimes {
fn drop(&mut self) {
EQUAL_CREATION_TIMES.with(|f| f.set(false));
}
}
#[must_use = "dropping this immediately removes the injected entry"]
pub(crate) struct Injected(());
impl Drop for Injected {
fn drop(&mut self) {
INJECTED.with(|f| f.set(None));
INJECTED_VISIT.with(|f| f.set(None));
}
}
#[must_use = "dropping this immediately disarms the forced failure"]
pub(crate) struct Forced(());
impl Drop for Forced {
fn drop(&mut self) {
FORCED.with(|f| f.set(None));
}
}
}
pub(crate) fn assign_to_kill_on_close_job(proc_handle: std::os::windows::io::RawHandle) -> io::Result<JobHandle> {
let raw_handle = HANDLE(proc_handle.cast());
let job = owned_job(unsafe { CreateJobObjectW(None, windows::core::PCWSTR::null()) })?;
set_kill_on_close_or_close(job)?;
assign_or_close(job, raw_handle)?;
Ok(JobHandle::new(job))
}
fn owned_job(created: windows::core::Result<HANDLE>) -> io::Result<HANDLE> {
created.map_err(win32_io_error)
}
fn set_kill_on_close_or_close(job: HANDLE) -> io::Result<()> {
let mut info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
let set = unsafe {
SetInformationJobObject(
job,
JobObjectExtendedLimitInformation,
std::ptr::addr_of!(info).cast(),
size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
)
};
if let Err(e) = set {
_ = unsafe { CloseHandle(job) };
return Err(win32_io_error(e));
}
Ok(())
}
fn assign_or_close(job: HANDLE, process: HANDLE) -> io::Result<()> {
if let Err(e) = unsafe { AssignProcessToJobObject(job, process) } {
_ = unsafe { CloseHandle(job) };
return Err(win32_io_error(e));
}
Ok(())
}
pub(crate) fn assign_held(proc_handle: std::os::windows::io::RawHandle) -> io::Result<JobHandle> {
#[cfg(test)]
forced(fault::Step::Assign, None).map_err(win32_io_error)?;
assign_to_kill_on_close_job(proc_handle)
}
pub(crate) fn query_job_pid_list(job: HANDLE) -> io::Result<Vec<u32>> {
let mut capacity: usize = 64;
loop {
let buf_len = size_of::<JOBOBJECT_BASIC_PROCESS_ID_LIST>() + capacity.saturating_sub(1) * size_of::<usize>();
let mut buf: Vec<usize> = vec![0usize; buf_len.div_ceil(size_of::<usize>())];
let mut returned = 0u32;
let header_ptr = buf.as_mut_ptr().cast::<JOBOBJECT_BASIC_PROCESS_ID_LIST>();
let result = unsafe {
QueryInformationJobObject(
Some(job),
JobObjectBasicProcessIdList,
header_ptr.cast(),
buf_len as u32,
Some(&mut returned),
)
};
let assigned = unsafe { std::ptr::addr_of!((*header_ptr).NumberOfAssignedProcesses).read_unaligned() } as usize;
if result.is_err() {
if assigned > capacity {
capacity = assigned;
continue;
}
return Err(io::Error::last_os_error());
}
let n = unsafe { std::ptr::addr_of!((*header_ptr).NumberOfProcessIdsInList).read_unaligned() } as usize;
debug_assert!(
n <= capacity,
"kernel reported more pids than the queried buffer could hold"
);
let list_ptr = unsafe { std::ptr::addr_of!((*header_ptr).ProcessIdList).cast::<usize>() };
let mut pids = Vec::with_capacity(n.min(capacity));
for i in 0..n.min(capacity) {
let raw = unsafe { list_ptr.add(i).read_unaligned() };
pids.push(raw as u32);
}
return Ok(pids);
}
}
const MAXIMUM_WAIT_OBJECTS: usize = 64;
impl JobHandle {
pub(crate) fn wait_drained(
&self,
deadline: Option<std::time::Instant>,
cancel: Option<HANDLE>,
) -> Result<crate::containment::TreeDrain, crate::error::Error> {
#[cfg(feature = "tokio")]
crate::bounded::assert_may_block("waiting for a job to drain");
let Some(dup) = self.with_handle(duplicate_job).transpose()? else {
return Err(consumed_job_handle_error());
};
let result = wait_drained_raw(dup, deadline, cancel);
unsafe {
_ = CloseHandle(dup);
}
result
}
}
pub(crate) fn consumed_job_handle_error() -> crate::error::Error {
crate::error::Error::Unassessable {
detail: "the job handle was already closed (kill_tree()/hard_kill(), or the owning \
Child/Job was dropped) before this drain check ran; whether every member has \
actually finished exiting can no longer be observed"
.into(),
source: None,
}
}
pub(crate) fn duplicate_job(handle: HANDLE) -> Result<HANDLE, crate::error::Error> {
use windows::Win32::Foundation::{DuplicateHandle, DUPLICATE_SAME_ACCESS};
use windows::Win32::System::Threading::GetCurrentProcess;
let mut dup = HANDLE::default();
unsafe {
DuplicateHandle(
GetCurrentProcess(),
handle,
GetCurrentProcess(),
&mut dup,
0,
false,
DUPLICATE_SAME_ACCESS,
)
}
.map_err(win32_io_error)?;
Ok(dup)
}
fn member_to_watch(opened: windows::core::Result<HANDLE>, job: HANDLE) -> io::Result<Option<HANDLE>> {
match opened {
Ok(h) => {
use windows::Win32::System::JobObjects::IsProcessInJob;
let mut in_job = windows::core::BOOL(0);
let confirmed = unsafe { IsProcessInJob(h, Some(job), &mut in_job) };
match confirmed {
Ok(()) if in_job.as_bool() => Ok(Some(h)),
Ok(()) => {
_ = unsafe { CloseHandle(h) };
Ok(None)
}
Err(e) => {
_ = unsafe { CloseHandle(h) };
Err(win32_io_error(e))
}
}
}
Err(e) if e.code() == windows::Win32::Foundation::ERROR_INVALID_PARAMETER.to_hresult() => Ok(None),
Err(e) => Err(win32_io_error(e)),
}
}
fn thread_snapshot(created: windows::core::Result<HANDLE>) -> io::Result<HANDLE> {
created.map_err(win32_io_error)
}
fn thread_entries_closing(
snap: HANDLE,
) -> io::Result<Vec<windows::Win32::System::Diagnostics::ToolHelp::THREADENTRY32>> {
use windows::Win32::Foundation::ERROR_NO_MORE_FILES;
use windows::Win32::System::Diagnostics::ToolHelp::{Thread32First, Thread32Next, THREADENTRY32};
let end_of_walk = windows::core::HRESULT::from_win32(ERROR_NO_MORE_FILES.0);
let mut entry = THREADENTRY32 {
dwSize: size_of::<THREADENTRY32>() as u32,
..Default::default()
};
let mut entries = Vec::new();
let mut step = unsafe { Thread32First(snap, &mut entry) };
let walked = loop {
match step {
Ok(()) => {}
Err(e) if e.code() == end_of_walk => break Ok(entries),
Err(e) => break Err(win32_io_error(e)),
}
entries.push(entry);
step = unsafe { Thread32Next(snap, &mut entry) };
};
_ = unsafe { CloseHandle(snap) };
walked
}
pub(crate) fn wait_drained_raw(
job: HANDLE,
deadline: Option<std::time::Instant>,
cancel: Option<HANDLE>,
) -> Result<crate::containment::TreeDrain, crate::error::Error> {
use crate::containment::TreeDrain;
use crate::error::Error;
#[cfg(feature = "tokio")]
crate::bounded::assert_may_block("waiting for a job to drain");
let budget = MAXIMUM_WAIT_OBJECTS - 1 - if cancel.is_some() { 1 } else { 0 };
loop {
if let Some(c) = cancel {
let cancel_state = unsafe { WaitForSingleObject(c, 0) };
if cancel_state == WAIT_OBJECT_0 {
return Ok(TreeDrain::MembersRemain);
}
}
let pids = query_job_pid_list(job).map_err(Error::Io)?;
if pids.is_empty() {
return Ok(TreeDrain::AllMembersExited);
}
let mut handles: Vec<HANDLE> = Vec::new();
let mut denied: Option<io::Error> = None;
for pid in pids.iter().take(budget) {
let opened = unsafe { OpenProcess(PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, false, *pid) };
match member_to_watch(opened, job) {
Ok(Some(h)) => handles.push(h),
Ok(None) => {}
Err(e) => denied = Some(e),
}
}
let remaining = crate::wait::remaining(deadline);
if handles.is_empty() {
if let Some(e) = denied {
log::warn!("wait_tree: could not open any live job member to watch for its exit ({e})");
return Err(Error::Unassessable {
detail: "could not open a handle to any live member of the contained tree \
to observe its exit"
.into(),
source: Some(e),
});
}
if remaining == Some(std::time::Duration::ZERO) {
return Ok(TreeDrain::MembersRemain);
}
continue;
}
if let Some(e) = &denied {
log::debug!(
"wait_tree: could not open one live job member to watch for its exit, but \
other members are still trackable this round: {e}"
);
}
let mut wait_set = handles.clone();
if let Some(c) = cancel {
wait_set.push(c);
}
let waited = crate::wait::wait_until(deadline, |ms| unsafe { WaitForMultipleObjects(&wait_set, false, ms) });
let wait_failed = (waited == WAIT_FAILED).then(io::Error::last_os_error);
for h in &handles {
unsafe {
_ = CloseHandle(*h);
}
}
if waited == WAIT_TIMEOUT {
return Ok(TreeDrain::MembersRemain);
}
if let Some(e) = wait_failed {
return Err(Error::Io(e));
}
let idx = waited.0.wrapping_sub(WAIT_OBJECT_0.0) as usize;
debug_assert!(
idx < wait_set.len(),
"unexpected WaitForMultipleObjects verdict: {waited:?}"
);
if idx >= wait_set.len() {
log::warn!(
"wait_tree: unexpected WaitForMultipleObjects verdict {waited:?} (index {idx} \
outside the {} handles waited on) - re-enumerating regardless",
wait_set.len()
);
}
if cancel.is_some() && idx == handles.len() {
return Ok(TreeDrain::MembersRemain);
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Visit {
Resumed,
Foreign {
owner: u32,
},
Gone,
Denied,
Failed,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub(crate) enum SuspendCount {
#[default]
Any,
ExactlyOne,
}
#[derive(Default)]
struct Walk {
expected: SuspendCount,
resumed: u32,
last_err: Option<io::Error>,
last_skip: Option<String>,
}
impl Walk {
fn skip(&mut self, reason: String) {
log::debug!("resume_initial_threads: {reason}; skipped");
self.last_skip = Some(reason);
}
fn fail_unidentified(&mut self, process_pid: u32, first: u32, second: u32) {
let msg = format!(
"the initial thread of pid {process_pid} cannot be identified: threads {first} and {second} have the same creation time"
);
log::warn!("resume_initial_threads: {msg}");
self.last_err.get_or_insert_with(|| io::Error::other(msg));
}
fn fail(&mut self, call: &str, tid: u32, process_pid: u32, cause: impl std::fmt::Display) -> Visit {
let msg = format!("{call} failed for thread {tid} of pid {process_pid}: {cause}");
log::warn!("resume_initial_threads: {msg}");
self.last_err.get_or_insert_with(|| io::Error::other(msg));
Visit::Failed
}
fn fail_win32(&mut self, call: &str, tid: u32, process_pid: u32, cause: windows::core::Error) -> Visit {
let context = format!("{call} failed for thread {tid} of pid {process_pid}");
let err = io_context(context, win32_io_error(cause));
log::warn!("resume_initial_threads: {err}");
self.last_err.get_or_insert(err);
Visit::Failed
}
}
struct ThreadHandle(HANDLE);
impl Drop for ThreadHandle {
fn drop(&mut self) {
unsafe { _ = CloseHandle(self.0) };
}
}
#[cfg(test)]
fn forced(step: fault::Step, tid: Option<u32>) -> windows::core::Result<()> {
match fault::take_forced(step, tid) {
Some(code) => Err(windows::core::Error::from_hresult(windows::core::HRESULT::from_win32(
code,
))),
None => Ok(()),
}
}
fn open_query(tid: u32) -> windows::core::Result<ThreadHandle> {
#[cfg(test)]
forced(fault::Step::QueryOpen, Some(tid))?;
unsafe { OpenThread(THREAD_QUERY_LIMITED_INFORMATION, false, tid) }.map(ThreadHandle)
}
fn open_for_resume(tid: u32) -> windows::core::Result<ThreadHandle> {
#[cfg(test)]
forced(fault::Step::ResumeOpen, Some(tid))?;
unsafe { OpenThread(THREAD_SUSPEND_RESUME | THREAD_QUERY_LIMITED_INFORMATION, false, tid) }.map(ThreadHandle)
}
fn owner_of(thread: &ThreadHandle) -> windows::core::Result<u32> {
#[cfg(test)]
forced(fault::Step::Owner, None)?;
match unsafe { GetProcessIdOfThread(thread.0) } {
0 => Err(windows::core::Error::from_thread()),
pid => Ok(pid),
}
}
fn resume_thread(thread: &ThreadHandle) -> windows::core::Result<u32> {
#[cfg(test)]
forced(fault::Step::Resume, None)?;
match unsafe { ResumeThread(thread.0) } {
u32::MAX => Err(windows::core::Error::from_thread()),
previous => Ok(previous),
}
}
fn visit_thread_entry(
entry: &windows::Win32::System::Diagnostics::ToolHelp::THREADENTRY32,
process_pid: u32,
walk: &mut Walk,
) -> Option<Visit> {
(entry.th32OwnerProcessID == process_pid).then(|| resume_if_owned(entry.th32ThreadID, process_pid, walk))
}
fn resume_if_owned(tid: u32, process_pid: u32, walk: &mut Walk) -> Visit {
use windows::Win32::Foundation::{ERROR_ACCESS_DENIED, ERROR_INVALID_PARAMETER};
let gone = windows::core::HRESULT::from_win32(ERROR_INVALID_PARAMETER.0);
let denied = windows::core::HRESULT::from_win32(ERROR_ACCESS_DENIED.0);
let query = match open_query(tid) {
Ok(h) => h,
Err(e) if e.code() == gone => {
walk.skip(format!("thread {tid} no longer exists"));
return Visit::Gone;
}
Err(e) if e.code() == denied => {
walk.skip(format!(
"thread {tid} cannot be opened for query (access denied), so it is not the child's"
));
return Visit::Denied;
}
Err(e) => return walk.fail_win32("OpenThread(query)", tid, process_pid, e),
};
match owner_of(&query) {
Ok(owner) if owner == process_pid => {}
Ok(owner) => {
walk.skip(format!("thread {tid} now belongs to pid {owner}"));
return Visit::Foreign { owner };
}
Err(e) => return walk.fail_win32("GetProcessIdOfThread", tid, process_pid, e),
}
let resume = match open_for_resume(tid) {
Ok(h) => h,
Err(e) => return walk.fail_win32("OpenThread(suspend/resume)", tid, process_pid, e),
};
match owner_of(&resume) {
Ok(again) if again == process_pid => {}
Ok(again) => {
return walk.fail(
"OpenThread(suspend/resume)",
tid,
process_pid,
format_args!("opened a thread of pid {again}, not the thread just checked"),
)
}
Err(e) => return walk.fail_win32("GetProcessIdOfThread", tid, process_pid, e),
}
match resume_thread(&resume) {
Ok(1) => {
walk.resumed += 1;
Visit::Resumed
}
Ok(_) if walk.expected == SuspendCount::Any => {
walk.resumed += 1;
Visit::Resumed
}
Ok(previous) => walk.fail(
"ResumeThread",
tid,
process_pid,
format_args!(
"the previous suspend count was {previous}, not 1: {}",
if previous > 1 {
"the thread is still suspended"
} else {
"the thread was not suspended, so the child had already run"
}
),
),
Err(e) => walk.fail_win32("ResumeThread", tid, process_pid, e),
}
}
fn creation_time_if_owned(tid: u32, process_pid: u32) -> Result<Option<u64>, (&'static str, windows::core::Error)> {
use windows::Win32::Foundation::{ERROR_ACCESS_DENIED, ERROR_INVALID_PARAMETER, FILETIME};
use windows::Win32::System::Threading::GetThreadTimes;
let gone = windows::core::HRESULT::from_win32(ERROR_INVALID_PARAMETER.0);
let denied = windows::core::HRESULT::from_win32(ERROR_ACCESS_DENIED.0);
let thread = match unsafe { OpenThread(THREAD_QUERY_LIMITED_INFORMATION, false, tid) } {
Ok(h) => ThreadHandle(h),
Err(e) if e.code() == gone || e.code() == denied => return Ok(None),
Err(e) => return Err(("OpenThread(query)", e)),
};
match owner_of(&thread) {
Ok(owner) if owner == process_pid => {}
Ok(_) => return Ok(None),
Err(e) => return Err(("GetProcessIdOfThread", e)),
}
let (mut created, mut exited, mut kernel, mut user) = (
FILETIME::default(),
FILETIME::default(),
FILETIME::default(),
FILETIME::default(),
);
#[cfg(test)]
forced(fault::Step::CreationTime, Some(tid)).map_err(|e| ("GetThreadTimes", e))?;
unsafe { GetThreadTimes(thread.0, &mut created, &mut exited, &mut kernel, &mut user) }
.map_err(|e| ("GetThreadTimes", e))?;
#[cfg(test)]
if fault::creation_times_are_equal() {
return Ok(Some(1));
}
Ok(Some(
(u64::from(created.dwHighDateTime) << 32) | u64::from(created.dwLowDateTime),
))
}
fn initial_thread_id(process_pid: u32, tids: &[u32], walk: &mut Walk) -> Option<u32> {
let mut times = Vec::with_capacity(tids.len());
for &tid in tids {
match creation_time_if_owned(tid, process_pid) {
Ok(Some(created)) => times.push((created, tid)),
Ok(None) => walk.skip(format!(
"thread {tid} is gone, is not pid {process_pid}'s, or cannot be opened by the child's creator"
)),
Err((call, e)) => {
walk.fail_win32(call, tid, process_pid, e);
return None;
}
}
}
match earliest_created(times) {
Earliest::NoThread => None,
Earliest::Unique(tid) => Some(tid),
Earliest::Tie(first, second) => {
walk.fail_unidentified(process_pid, first, second);
None
}
}
}
#[derive(Debug, PartialEq, Eq)]
enum Earliest {
NoThread,
Unique(u32),
Tie(u32, u32),
}
fn earliest_created(times: impl IntoIterator<Item = (u64, u32)>) -> Earliest {
let mut best: Option<(u64, u32)> = None;
let mut tied: Option<u32> = None;
for (created, tid) in times {
match best {
Some((time, _)) if created > time => {}
Some((time, _)) if created == time => {
tied.get_or_insert(tid);
}
_ => {
best = Some((created, tid));
tied = None;
}
}
}
match (best, tied) {
(None, _) => Earliest::NoThread,
(Some((_, tid)), None) => Earliest::Unique(tid),
(Some((_, first)), Some(second)) => Earliest::Tie(first, second),
}
}
fn process_pid_of(raw_handle: HANDLE) -> io::Result<u32> {
let pid = unsafe { GetProcessId(raw_handle) };
if pid == 0 {
return Err(io_context(
"GetProcessId failed on the child's handle",
io::Error::last_os_error(),
));
}
Ok(pid)
}
fn none_resumed_error(process_pid: u32, last_skip: Option<&str>) -> io::Error {
match last_skip {
Some(reason) => io::Error::other(format!(
"no suspended threads resumed: every thread the snapshot listed for pid {process_pid} was stale (last: {reason})"
)),
None => io::Error::other(format!(
"no suspended threads resumed: the snapshot listed no threads for pid {process_pid}"
)),
}
}
fn walk_verdict(process_pid: u32, walk: Walk) -> io::Result<()> {
let Walk {
resumed,
last_err,
last_skip,
..
} = walk;
if let Some(e) = last_err {
log::warn!(
"resume_initial_threads: failed to resume one or more of this child's initial threads \
({resumed} resumed successfully before the failure): {e}"
);
return Err(e);
}
if resumed == 0 {
return Err(none_resumed_error(process_pid, last_skip.as_deref()));
}
Ok(())
}
pub(crate) fn resume_initial_threads(
proc_handle: std::os::windows::io::RawHandle,
expected: SuspendCount,
) -> io::Result<()> {
use windows::Win32::System::Diagnostics::ToolHelp::{CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD};
let raw_handle = HANDLE(proc_handle.cast());
let mut walk = Walk {
expected,
..Walk::default()
};
let process_pid = process_pid_of(raw_handle);
debug_assert!(
process_pid.is_ok(),
"the caller must pass a live process handle: {process_pid:?}"
);
let process_pid = process_pid?;
unsafe {
let snap = thread_snapshot(CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0))?;
let entries = thread_entries_closing(snap)?;
if walk.expected == SuspendCount::ExactlyOne {
let own: Vec<u32> = entries
.iter()
.filter(|e| e.th32OwnerProcessID == process_pid)
.map(|e| e.th32ThreadID)
.collect();
if let Some(initial) = initial_thread_id(process_pid, &own, &mut walk) {
resume_if_owned(initial, process_pid, &mut walk);
}
} else {
for entry in &entries {
visit_thread_entry(entry, process_pid, &mut walk);
}
}
}
#[cfg(test)]
if let Some((tid, owner)) = fault::injected_entry() {
let entry = windows::Win32::System::Diagnostics::ToolHelp::THREADENTRY32 {
th32OwnerProcessID: owner.unwrap_or(process_pid),
th32ThreadID: tid,
..Default::default()
};
fault::record_injected_visit(visit_thread_entry(&entry, process_pid, &mut walk));
}
walk_verdict(process_pid, walk)
}
pub(crate) fn attach_job(proc_handle: std::os::windows::io::RawHandle) -> io::Result<Option<JobHandle>> {
let job_result = assign_held(proc_handle);
if let Err(resume_err) = resume_initial_threads(proc_handle, SuspendCount::Any) {
if let Ok(job) = job_result {
if let Err(e) = job.hard_kill() {
log::warn!("job kill after a failed resume also failed ({e}); the tree may still be running");
}
}
return Err(resume_err);
}
match job_result {
Ok(job) => Ok(Some(job)),
Err(_e) => {
Ok(None)
}
}
}
pub(crate) fn job_contains_pid(attached: &crate::containment::Attached, pid: u32) -> bool {
use windows::Win32::System::JobObjects::IsProcessInJob;
use windows::Win32::System::Threading::{OpenProcess, PROCESS_QUERY_INFORMATION};
let crate::containment::Attached::JobObject(job) = attached else {
return false;
};
let process_handle = unsafe {
match OpenProcess(PROCESS_QUERY_INFORMATION, false, pid) {
Ok(h) => h,
Err(_) => return false,
}
};
let mut in_job = windows::core::BOOL(0);
let queried = job.with_handle(|job_handle| {
unsafe { IsProcessInJob(process_handle, Some(job_handle), &mut in_job) }
});
unsafe {
_ = CloseHandle(process_handle);
}
matches!(queried, Some(Ok(()))) && in_job.as_bool()
}
pub(crate) fn job_limit_flags(
job: &JobHandle,
) -> Option<windows::core::Result<windows::Win32::System::JobObjects::JOB_OBJECT_LIMIT>> {
use windows::Win32::System::JobObjects::{JobObjectBasicLimitInformation, JOBOBJECT_BASIC_LIMIT_INFORMATION};
let mut info = JOBOBJECT_BASIC_LIMIT_INFORMATION::default();
let queried = job.with_handle(|handle| {
unsafe {
QueryInformationJobObject(
Some(handle),
JobObjectBasicLimitInformation,
std::ptr::addr_of_mut!(info).cast(),
size_of::<JOBOBJECT_BASIC_LIMIT_INFORMATION>() as u32,
None,
)
}
})?;
Some(queried.map(|()| info.LimitFlags))
}
pub(crate) fn job_kills_on_close(attached: &crate::containment::Attached) -> bool {
let crate::containment::Attached::JobObject(job) = attached else {
return false;
};
let flags = job_limit_flags(job)
.expect("the job handle is closed")
.unwrap_or_else(|e| panic!("querying the job's limits failed: {e}"));
flags.0 & JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE.0 != 0
}
#[cfg(test)]
#[path = "windows_tests.rs"]
mod windows_tests;