use std::io;
use std::mem::size_of;
use std::ops::ControlFlow;
use std::os::windows::io::{AsRawHandle as _, BorrowedHandle};
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,
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};
use crate::identity::ProcessId;
pub(crate) struct JobHandle {
raw: HANDLE,
}
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.raw.0).finish()
}
}
impl JobHandle {
fn new(handle: HANDLE) -> Self {
debug_assert!(!handle.0.is_null(), "job handle must not be null");
JobHandle { raw: handle }
}
pub(crate) fn handle(&self) -> BorrowedHandle<'_> {
unsafe { BorrowedHandle::borrow_raw(self.raw.0) }
}
pub(crate) fn hard_kill(&self) -> io::Result<()> {
#[cfg(test)]
{
fault::run_before_job_kill();
forced(fault::Step::JobKill, None).map_err(win32_io_error)?;
}
unsafe { TerminateJobObject(self.raw, 1) }.map_err(win32_io_error)
}
pub(crate) fn disarm(&self) -> io::Result<()> {
let info = JOBOBJECT_EXTENDED_LIMIT_INFORMATION::default();
unsafe {
SetInformationJobObject(
self.raw,
JobObjectExtendedLimitInformation,
std::ptr::addr_of!(info).cast(),
size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
)
}
.map_err(win32_io_error)
}
}
#[cfg(all(windows, test))]
impl JobHandle {
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::System::SystemServices::{JOB_OBJECT_QUERY, JOB_OBJECT_TERMINATE};
JobHandle::create_empty_for_test().duplicate_with_access_for_test(JOB_OBJECT_QUERY | JOB_OBJECT_TERMINATE)
}
pub(crate) fn duplicate_with_access_for_test(&self, access: u32) -> JobHandle {
use windows::Win32::Foundation::{DuplicateHandle, DUPLICATE_HANDLE_OPTIONS};
use windows::Win32::System::Threading::GetCurrentProcess;
let mut weak = HANDLE::default();
unsafe {
DuplicateHandle(
GetCurrentProcess(),
self.raw,
GetCurrentProcess(),
&mut weak,
access,
false,
DUPLICATE_HANDLE_OPTIONS(0),
)
}
.expect("DuplicateHandle with reduced access");
JobHandle::new(weak)
}
}
impl Drop for JobHandle {
fn drop(&mut self) {
unsafe {
if let Err(e) = CloseHandle(self.raw) {
log::warn!(
"closing the job handle failed ({report}); the tree may still be running",
report = crate::error::Report(&e)
);
}
}
}
}
impl JobHandle {
pub(crate) fn list_members(&self, root: Option<u32>) -> (Vec<ProcessId>, Vec<crate::error::Error>) {
use crate::containment::tree_kill::exit_unobserved;
use crate::error::Error;
let pids = match query_job_pid_list(self.raw) {
Ok(pids) => pids,
Err(e) => {
let why = Error::Unassessable {
detail: "the members of the job could not be listed before the kill, so their exit cannot be \
observed"
.to_owned(),
source: Some(Error::io_cause(e)),
};
return (Vec::new(), vec![why]);
}
};
let (mut members, mut unobserved) = (Vec::new(), Vec::new());
for pid in pids.into_iter().filter(|pid| Some(*pid) != root) {
let opened = unsafe { OpenProcess(PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, false, pid) };
match member_to_watch(opened, self.raw) {
Ok(Some(handle)) => {
let id = crate::identity::windows_identity_from_handle_result(handle, pid);
_ = unsafe { CloseHandle(handle) };
match id {
Ok(id) => members.push(id),
Err(e) => unobserved.push(exit_unobserved(
pid,
Error::Unassessable {
detail: "its start time could not be read".to_owned(),
source: Some(Error::io_cause(win32_io_error(e))),
},
)),
}
}
Ok(None) => {}
Err(e) => unobserved.push(exit_unobserved(pid, Error::Io(e))),
}
}
(members, unobserved)
}
}
impl crate::containment::Contains for JobHandle {
fn kill(&self, root: Option<&dyn crate::containment::Root>) -> crate::containment::TreeKill<'_> {
let (members, unobserved) = self.list_members(root.map(crate::containment::Root::pid));
let sent = crate::containment::Contains::send_kill(self, root);
crate::containment::TreeKill::listed(
sent,
members,
unobserved,
crate::containment::drain_edge::DrainEdge::Job(self),
)
}
fn send_kill(&self, _root: Option<&dyn crate::containment::Root>) -> crate::containment::dispatch::TreeKillOutcome {
use crate::containment::dispatch::{TreeKillOutcome, Unkilled};
TreeKillOutcome::Ran(
self.hard_kill()
.map_err(|e| crate::error::Error::Containment {
detail: "TerminateJobObject could not terminate the job".to_owned(),
source: Some(crate::error::Error::io_cause(e)),
})
.map_err(Unkilled::from),
)
}
fn send_terminate(
&self,
pid: u32,
_root: Option<&dyn crate::containment::Root>,
) -> crate::containment::TerminateOutcome {
crate::containment::TerminateOutcome::of(terminate(pid).map(Ok), Some("the SIGTERM"))
}
fn drain_edge(&self) -> Option<crate::containment::drain_edge::DrainEdge<'_>> {
Some(crate::containment::drain_edge::DrainEdge::Job(self))
}
fn kind(&self) -> crate::containment::Containment {
crate::containment::Containment::JobObject
}
fn disarm(&self) -> io::Result<()> {
JobHandle::disarm(self)
}
}
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 ({report}); cannot classify",
report = crate::error::Report(probe)
);
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 ({report})",
report = crate::error::Report(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, RefCell};
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))
}
thread_local! {
static BEFORE_JOB_KILL: crate::oneshot_hook::OneShotHook = const { crate::oneshot_hook::OneShotHook::new() };
}
pub(crate) fn set_before_job_kill(hook: impl FnOnce() + 'static) -> crate::oneshot_hook::Armed {
crate::oneshot_hook::arm(&BEFORE_JOB_KILL, hook)
}
pub(crate) fn run_before_job_kill() {
crate::oneshot_hook::fire(&BEFORE_JOB_KILL);
}
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,
JobKill,
}
enum ForcedPidLists {
Unarmed,
Armed(std::collections::VecDeque<Vec<u32>>),
}
thread_local! {
static JOB_PID_LIST: RefCell<ForcedPidLists> = const { RefCell::new(ForcedPidLists::Unarmed) };
static JOB_PID_LIST_QUERIES: Cell<u32> = const { Cell::new(0) };
}
pub(crate) fn force_job_pid_list(pids: Vec<u32>) -> ForcedList {
force_job_pid_lists([pids])
}
pub(crate) fn force_job_pid_lists(lists: impl IntoIterator<Item = Vec<u32>>) -> ForcedList {
JOB_PID_LIST.with(|f| {
let mut f = f.borrow_mut();
debug_assert!(
matches!(*f, ForcedPidLists::Unarmed),
"a pid list is forced and its guard is alive"
);
*f = ForcedPidLists::Armed(lists.into_iter().collect());
});
JOB_PID_LIST_QUERIES.with(|c| c.set(0));
ForcedList(())
}
pub(crate) fn take_forced_job_pid_list() -> Option<Vec<u32>> {
JOB_PID_LIST_QUERIES.with(|c| c.set(c.get() + 1));
JOB_PID_LIST.with(|f| {
let mut f = f.borrow_mut();
let ForcedPidLists::Armed(lists) = &mut *f else {
return None;
};
lists.pop_front()
})
}
pub(crate) fn job_pid_list_queries() -> u32 {
JOB_PID_LIST_QUERIES.with(|c| c.get())
}
#[must_use = "dropping this immediately disarms the forced pid list"]
pub(crate) struct ForcedList(());
impl Drop for ForcedList {
fn drop(&mut self) {
JOB_PID_LIST.with(|f| *f.borrow_mut() = ForcedPidLists::Unarmed);
JOB_PID_LIST_QUERIES.with(|c| c.set(0));
}
}
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>> {
#[cfg(test)]
if let Some(forced) = fault::take_forced_job_pid_list() {
return Ok(forced);
}
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>,
) -> Result<crate::containment::TreeDrain, crate::error::Error> {
wait_drained_raw(self.handle(), deadline)
}
#[cfg(feature = "tokio")]
pub(crate) fn drain_round(&self, last_round: bool) -> Result<Round, crate::error::Error> {
drain_round(HANDLE(self.handle().as_raw_handle()), last_round)
}
#[cfg(feature = "tokio")]
pub(crate) fn after_signalled(
&self,
watch: &Watch,
) -> Result<Option<crate::containment::TreeDrain>, crate::error::Error> {
after_signalled(HANDLE(self.handle().as_raw_handle()), watch)
}
}
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: BorrowedHandle<'_>,
deadline: Option<std::time::Instant>,
) -> Result<crate::containment::TreeDrain, crate::error::Error> {
use crate::containment::TreeDrain;
let job = HANDLE(job.as_raw_handle());
loop {
let last_round = deadline.is_some_and(|at| crate::wait::now() >= at);
let watch = match drain_round(job, last_round)? {
Round::Answer(drain) => return Ok(drain),
Round::List => continue,
Round::Watch(watch) => watch,
};
match watch.wait(deadline)? {
Ended::Deadline => return Ok(TreeDrain::MembersRemain),
Ended::Signalled => {
if let Some(drain) = after_signalled(job, &watch)? {
return Ok(drain);
}
}
}
}
}
pub(crate) enum Round {
Answer(crate::containment::TreeDrain),
List,
Watch(Watch),
}
pub(crate) struct Watch {
handles: Vec<std::os::windows::io::OwnedHandle>,
set: HandleSet,
last_round: bool,
}
struct HandleSet(Vec<HANDLE>);
unsafe impl Send for HandleSet {}
unsafe impl Sync for HandleSet {}
pub(crate) enum Ended {
Deadline,
Signalled,
}
impl Watch {
#[cfg(feature = "tokio")]
pub(crate) fn handles(&self) -> impl Iterator<Item = BorrowedHandle<'_>> + Clone {
use std::os::windows::io::AsHandle as _;
self.handles.iter().map(|h| h.as_handle())
}
fn wait(&self, deadline: Option<std::time::Instant>) -> Result<Ended, crate::error::Error> {
self.ended(crate::wait::wait_until(deadline, |ms| self.wait_for(ms)))
}
#[cfg(feature = "tokio")]
pub(crate) fn poll(&self) -> Result<Ended, crate::error::Error> {
self.ended(self.wait_for(0))
}
fn wait_for(&self, ms: u32) -> windows::Win32::Foundation::WAIT_EVENT {
unsafe { WaitForMultipleObjects(&self.set.0, false, ms) }
}
fn ended(&self, waited: windows::Win32::Foundation::WAIT_EVENT) -> Result<Ended, crate::error::Error> {
let wait_failed = (waited == WAIT_FAILED).then(io::Error::last_os_error);
if waited == WAIT_TIMEOUT {
return Ok(Ended::Deadline);
}
if let Some(e) = wait_failed {
return Err(crate::error::Error::Io(e));
}
let idx = waited.0.wrapping_sub(WAIT_OBJECT_0.0) as usize;
debug_assert!(
idx < self.handles.len(),
"unexpected WaitForMultipleObjects verdict: {waited:?}"
);
if idx >= self.handles.len() {
log::warn!(
"wait_tree: unexpected WaitForMultipleObjects verdict {waited:?} (index {idx} \
outside the {} handles waited on) - re-enumerating regardless",
self.handles.len()
);
}
Ok(Ended::Signalled)
}
}
fn after_signalled(job: HANDLE, watch: &Watch) -> Result<Option<crate::containment::TreeDrain>, crate::error::Error> {
if watch.last_round {
return final_listing(job).map(Some);
}
Ok(None)
}
fn drain_round(job: HANDLE, last_round: bool) -> Result<Round, crate::error::Error> {
use crate::error::Error;
let budget = MAXIMUM_WAIT_OBJECTS - 1;
let pids = match list_members_or_drained(job)? {
ControlFlow::Break(drained) => return Ok(Round::Answer(drained)),
ControlFlow::Continue(pids) => pids,
};
let mut handles: Vec<std::os::windows::io::OwnedHandle> = Vec::new();
let mut denied: Option<io::Error> = None;
for pid in &pids {
if handles.len() == budget {
break;
}
let opened = unsafe { OpenProcess(PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, false, *pid) };
match member_to_watch(opened, job) {
Ok(Some(h)) => handles.push(unsafe { std::os::windows::io::FromRawHandle::from_raw_handle(h.0) }),
Ok(None) => {}
Err(e) => denied = Some(e),
}
}
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 ({report})",
report = crate::error::Report(&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(Error::io_cause(e)),
});
}
if last_round {
return final_listing(job).map(Round::Answer);
}
return Ok(Round::List);
}
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: {report}",
report = crate::error::Report(e)
);
}
let set = HandleSet(handles.iter().map(|h| HANDLE(h.as_raw_handle())).collect());
Ok(Round::Watch(Watch {
handles,
set,
last_round,
}))
}
fn final_listing(job: HANDLE) -> Result<crate::containment::TreeDrain, crate::error::Error> {
use crate::containment::TreeDrain;
Ok(match list_members_or_drained(job)? {
ControlFlow::Break(drained) => drained,
ControlFlow::Continue(_) => TreeDrain::MembersRemain,
})
}
fn list_members_or_drained(
job: HANDLE,
) -> Result<ControlFlow<crate::containment::TreeDrain, Vec<u32>>, crate::error::Error> {
let pids = query_job_pid_list(job).map_err(crate::error::Error::Io)?;
Ok(if pids.is_empty() {
ControlFlow::Break(crate::containment::TreeDrain::AllMembersExited)
} else {
ControlFlow::Continue(pids)
})
}
#[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: {report}", report = crate::error::Report(&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): {report}",
report = crate::error::Report(&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,
) -> Result<Option<JobHandle>, crate::containment::dispatch::AttachFailure> {
let job_result = assign_held(proc_handle);
if let Err(resume_err) = resume_initial_threads(proc_handle, SuspendCount::Any) {
let cleanup = match job_result {
Ok(job) => job
.hard_kill()
.err()
.map(|e| crate::error::Error::io_cause(crate::error::io_context("terminating the job", e))),
Err(_) => None,
};
if let Some(failure) = &cleanup {
log::warn!(
"job kill after a failed resume also failed ({report}); the tree may still be running",
report = crate::error::Report(&**failure)
);
}
return Err(crate::containment::dispatch::AttachFailure {
cause: crate::error::Error::Containment {
detail: "the child's initial threads could not be resumed".to_owned(),
source: Some(crate::error::Error::io_cause(resume_err)),
},
cleanup: crate::error::Failures::collect(cleanup),
});
}
match job_result {
Ok(job) => Ok(Some(job)),
Err(_e) => {
Ok(None)
}
}
}
pub(crate) fn job_contains_pid(job: &JobHandle, pid: u32) -> bool {
use windows::Win32::System::JobObjects::IsProcessInJob;
use windows::Win32::System::Threading::{OpenProcess, PROCESS_QUERY_INFORMATION};
let process_handle = unsafe { OpenProcess(PROCESS_QUERY_INFORMATION, false, pid) }
.unwrap_or_else(|e| panic!("OpenProcess({pid}) failed: {e}"));
let mut in_job = windows::core::BOOL(0);
let queried = unsafe { IsProcessInJob(process_handle, Some(job.raw), &mut in_job) };
unsafe {
_ = CloseHandle(process_handle);
}
queried.unwrap_or_else(|e| panic!("IsProcessInJob({pid}) failed: {e}"));
in_job.as_bool()
}
pub(crate) fn job_limit_flags(
job: &JobHandle,
) -> 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();
unsafe {
QueryInformationJobObject(
Some(job.raw),
JobObjectBasicLimitInformation,
std::ptr::addr_of_mut!(info).cast(),
size_of::<JOBOBJECT_BASIC_LIMIT_INFORMATION>() as u32,
None,
)
}?;
Ok(info.LimitFlags)
}
pub(crate) fn job_kills_on_close(job: &JobHandle) -> bool {
let flags = job_limit_flags(job).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;