use std::io;
use std::mem::size_of;
use std::ops::ControlFlow;
use std::os::windows::io::{AsRawHandle as _, BorrowedHandle};
use std::sync::atomic::{AtomicU32, Ordering};
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, JobObjectBasicAccountingInformation, JobObjectBasicProcessIdList,
JobObjectExtendedLimitInformation, QueryInformationJobObject, SetInformationJobObject, TerminateJobObject,
JOBOBJECT_BASIC_ACCOUNTING_INFORMATION, 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::containment::tree_kill::{Settled, Unnamed};
use crate::error::{io_context, win32_io_error};
use crate::identity::ProcessId;
pub(crate) struct JobHandle {
raw: HANDLE,
confirmed: AtomicU32,
}
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,
confirmed: AtomicU32::new(0),
}
}
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 assign_for_test(&self, process: std::os::windows::io::RawHandle) -> io::Result<()> {
unsafe { AssignProcessToJobObject(self.raw, HANDLE(process.cast())) }.map_err(win32_io_error)
}
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<Unnamed>) {
use crate::error::Error;
let pids = match query_job_pid_list(self.raw) {
Ok(pids) => pids,
Err(e) => {
let detail =
"the members of the job could not be listed before the kill, so their exit cannot be observed";
return (Vec::new(), vec![unlisted(detail, e)]);
}
};
let mut found = Listed::default();
for pid in pids.into_iter().filter(|pid| Some(*pid) != root) {
found.look(self.raw, pid, false);
}
let unproved = std::mem::take(&mut found.unproved);
if unproved.is_empty() {
return (found.members, found.unobserved);
}
match settle_unproved(self.raw, &unproved) {
Err(e) => {
let detail = "the members of the job were listed, but the listing that settles the pids whose \
membership could not be established failed, so whether those exited cannot be observed";
found.unobserved.push(unlisted(detail, e));
found
.unobserved
.extend(unproved.into_iter().map(|(pid, e)| Unnamed::member(pid, Error::Io(e))));
}
Ok(ControlFlow::Break(())) => {}
Ok(ControlFlow::Continue(named)) => {
for pid in named {
found.look(self.raw, pid, true);
}
}
}
(found.members, found.unobserved)
}
}
#[derive(Default)]
struct Listed {
members: Vec<ProcessId>,
unobserved: Vec<Unnamed>,
unproved: Vec<(u32, io::Error)>,
}
impl Listed {
fn look(&mut self, job: HANDLE, pid: u32, settling: bool) {
use crate::error::Error;
match member_identity(job, pid, open_for_membership(pid)) {
Ok(Some(id)) => self.members.push(id),
Ok(None) => {}
Err(NotNamed::Membership(e)) if settling => self.unobserved.push(Unnamed::member(pid, Error::Io(e))),
Err(NotNamed::Membership(e)) => self.unproved.push((pid, e)),
Err(NotNamed::Identity(cause)) => self.unobserved.push(Unnamed::member(pid, cause)),
}
}
}
fn unlisted(detail: &str, cause: io::Error) -> Unnamed {
Unnamed::nameless(crate::error::Error::Unassessable {
detail: detail.to_owned(),
source: Some(crate::error::Error::io_cause(cause)),
})
}
fn open_for_membership(pid: u32) -> windows::core::Result<HANDLE> {
unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) }
}
fn open_for_wait(pid: u32) -> windows::core::Result<HANDLE> {
#[cfg(test)]
forced(fault::Step::WaitOpen, Some(pid))?;
unsafe { OpenProcess(PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION, false, pid) }
}
enum NotNamed {
Membership(io::Error),
Identity(crate::error::Error),
}
fn member_identity(
job: HANDLE,
pid: u32,
opened: windows::core::Result<HANDLE>,
) -> Result<Option<ProcessId>, NotNamed> {
use crate::error::Error;
#[cfg(test)]
if let Err(e) = forced(fault::Step::Membership, Some(pid)) {
if let Ok(handle) = opened {
_ = unsafe { CloseHandle(handle) };
}
return Err(NotNamed::Membership(win32_io_error(e)));
}
let handle = match member_to_watch(opened, job) {
Standing::Member(handle) => handle,
Standing::NotMember => return Ok(None),
Standing::Unproved(e) => return Err(NotNamed::Membership(e)),
};
let id = crate::identity::windows_identity_from_handle_result(handle, pid);
#[cfg(test)]
let id = forced(fault::Step::Identity, Some(pid)).and(id);
_ = unsafe { CloseHandle(handle) };
id.map(Some).map_err(|e| {
NotNamed::Identity(Error::Unassessable {
detail: "its start time could not be read".to_owned(),
source: Some(Error::io_cause(win32_io_error(e))),
})
})
}
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,
Option<crate::containment::treewalk::Listing>,
) {
let sent = crate::containment::TerminateOutcome::of(terminate(pid).map(Ok), Some("the SIGTERM"));
(sent, None)
}
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,
LoaderRead,
JobKill,
Membership,
WaitOpen,
Identity,
}
enum ForcedPidLists {
Unarmed,
Armed {
lists: std::collections::VecDeque<Vec<u32>>,
then_fail: Option<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 {
arm_job_pid_lists(lists, None)
}
pub(crate) fn force_job_pid_lists_then_failure(lists: impl IntoIterator<Item = Vec<u32>>, code: u32) -> ForcedList {
arm_job_pid_lists(lists, Some(code))
}
fn arm_job_pid_lists(lists: impl IntoIterator<Item = Vec<u32>>, then_fail: Option<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: lists.into_iter().collect(),
then_fail,
};
});
JOB_PID_LIST_QUERIES.with(|c| c.set(0));
ForcedList(())
}
pub(crate) fn take_forced_job_pid_list() -> Option<std::io::Result<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, then_fail } = &mut *f else {
return None;
};
lists.pop_front().map(Ok).or_else(|| {
then_fail
.take()
.map(|code| Err(std::io::Error::from_raw_os_error(code as i32)))
})
})
}
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: RefCell<Vec<(Step, u32, Option<u32>)>> = const { RefCell::new(Vec::new()) };
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| {
let mut f = f.borrow_mut();
debug_assert!(f.iter().all(|(armed, ..)| *armed != step), "{step:?} is already forced");
f.push((step, code, tid));
});
Forced(())
}
pub(crate) fn forced_is_armed() -> bool {
FORCED.with(|f| !f.borrow().is_empty())
}
pub(crate) fn take_forced(step: Step, tid: Option<u32>) -> Option<u32> {
FORCED.with(|f| {
let mut f = f.borrow_mut();
let at = f
.iter()
.position(|&(armed, _, only)| armed == step && (only.is_none() || only == tid))?;
Some(f.remove(at).1)
})
}
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.borrow_mut().clear());
}
}
}
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 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, deadline)
}
pub(crate) fn wait_drained_past(
&self,
deadline: Option<std::time::Instant>,
settled: &Settled,
) -> Result<crate::containment::TreeDrain, crate::error::Error> {
wait_drained_past(self, deadline, settled)
}
pub(crate) fn count_to_confirm(&self) -> Result<Option<u32>, crate::error::Error> {
let count = total_processes(self.raw).map_err(|e| crate::error::Error::Unassessable {
detail: "the number of processes the job has had could not be read, so its drain cannot be confirmed"
.to_owned(),
source: Some(crate::error::Error::io_cause(e)),
})?;
Ok((count != self.confirmed.load(Ordering::Relaxed)).then_some(count))
}
pub(crate) fn confirmed_at(&self, count: u32) {
self.confirmed.store(count, Ordering::Relaxed);
}
#[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<Round, crate::error::Error> {
after_signalled(HANDLE(self.handle().as_raw_handle()), watch)
}
}
#[cfg(feature = "tokio")]
pub(crate) fn unsignalled_members_of(job: BorrowedHandle<'_>) -> Result<Vec<Found>, crate::error::Error> {
unsignalled_members(HANDLE(job.as_raw_handle()))
}
#[derive(Debug)]
enum Standing {
Member(HANDLE),
NotMember,
Unproved(io::Error),
}
fn member_to_watch(opened: windows::core::Result<HANDLE>, job: HANDLE) -> Standing {
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() => Standing::Member(h),
Ok(()) => {
_ = unsafe { CloseHandle(h) };
Standing::NotMember
}
Err(e) => {
_ = unsafe { CloseHandle(h) };
Standing::Unproved(win32_io_error(e))
}
}
}
Err(e) if e.code() == windows::Win32::Foundation::ERROR_INVALID_PARAMETER.to_hresult() => Standing::NotMember,
Err(e) => Standing::Unproved(win32_io_error(e)),
}
}
fn member_to_watch_for_wait(pid: u32, job: HANDLE) -> io::Result<Standing> {
#[cfg(test)]
if let Err(e) = forced(fault::Step::Membership, Some(pid)) {
return Ok(Standing::Unproved(win32_io_error(e)));
}
match open_for_wait(pid) {
Err(refused) if refused.code() != windows::Win32::Foundation::ERROR_INVALID_PARAMETER.to_hresult() => {
match member_to_watch(open_for_membership(pid), job) {
Standing::Member(proof) => {
let retried = open_for_wait(pid);
_ = unsafe { CloseHandle(proof) };
retried.map(Standing::Member).map_err(win32_io_error)
}
other => Ok(other),
}
}
opened => Ok(member_to_watch(opened, job)),
}
}
fn settle_unproved(job: HANDLE, unproved: &[(u32, io::Error)]) -> io::Result<ControlFlow<(), Vec<u32>>> {
let again = match list_members_or_drained(job)? {
ControlFlow::Break(()) => return Ok(ControlFlow::Break(())),
ControlFlow::Continue(again) => again,
};
let listed: std::collections::HashSet<u32> = again.into_iter().collect();
let mut named = Vec::new();
for (pid, cause) in unproved {
if listed.contains(pid) {
named.push(*pid);
} else {
log::debug!(
"the job's list named pid {pid}, whose membership could not be established ({report}), and the \
listing after it does not: a deleted member's pid; dropped",
report = crate::error::Report(cause)
);
}
}
Ok(ControlFlow::Continue(named))
}
fn thread_snapshot(created: windows::core::Result<HANDLE>) -> io::Result<HANDLE> {
created.map_err(win32_io_error)
}
fn thread_entries() -> io::Result<Vec<windows::Win32::System::Diagnostics::ToolHelp::THREADENTRY32>> {
use windows::Win32::System::Diagnostics::ToolHelp::{CreateToolhelp32Snapshot, TH32CS_SNAPTHREAD};
let snap = thread_snapshot(unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0) })?;
thread_entries_closing(snap)
}
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: &JobHandle,
deadline: Option<std::time::Instant>,
) -> Result<crate::containment::TreeDrain, crate::error::Error> {
wait_drained_past(job, deadline, &Settled::default())
}
pub(crate) fn wait_drained_past(
job_handle: &JobHandle,
deadline: Option<std::time::Instant>,
settled: &Settled,
) -> Result<crate::containment::TreeDrain, crate::error::Error> {
use crate::containment::TreeDrain;
let job = HANDLE(job_handle.handle().as_raw_handle());
loop {
let last_round = deadline.is_some_and(|at| crate::wait::now() >= at);
let round = match drain_round(job, last_round)? {
Round::Watch(watch) => match watch.wait(deadline)? {
Ended::Deadline => return Ok(TreeDrain::MembersRemain),
Ended::Signalled => after_signalled(job, &watch)?,
},
round => round,
};
match round {
Round::Answer(drain) => return Ok(drain),
Round::Confirm => return confirm_drained(job_handle, deadline, settled),
Round::List | Round::Watch(_) => {}
}
}
}
pub(crate) enum Round {
Answer(crate::containment::TreeDrain),
List,
Watch(Watch),
Confirm,
}
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| {
#[cfg(test)]
crate::wait::block_probe::blocking(
(ms != u32::MAX).then(|| std::time::Duration::from_millis(ms.into())),
crate::wait::block_probe::WaitObject::Handles,
);
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<Round, crate::error::Error> {
if watch.last_round {
return final_listing(job);
}
Ok(Round::List)
}
fn confirm_drained(
job: &JobHandle,
deadline: Option<std::time::Instant>,
settled: &Settled,
) -> Result<crate::containment::TreeDrain, crate::error::Error> {
use crate::containment::TreeDrain;
let Some(count) = job.count_to_confirm()? else {
return Ok(TreeDrain::AllMembersExited);
};
walk_confirm(
ConfirmWalk::new(job, count, unsignalled_members(job.raw), settled),
deadline,
)
}
fn walk_confirm(
mut walk: ConfirmWalk<'_>,
deadline: Option<std::time::Instant>,
) -> Result<crate::containment::TreeDrain, crate::error::Error> {
use crate::containment::tree_kill::wait_for_member;
use crate::identity::HostKernel;
loop {
match walk.next() {
ConfirmStep::Wait(id) => walk.waited(id, wait_for_member(&HostKernel, id, deadline)),
ConfirmStep::Done(answer) => return answer,
}
}
}
pub(crate) type Found = Result<ProcessId, (u32, crate::error::Error)>;
pub(crate) enum ConfirmStep {
Wait(ProcessId),
Done(Result<crate::containment::TreeDrain, crate::error::Error>),
}
pub(crate) struct ConfirmWalk<'a> {
job: &'a JobHandle,
count: u32,
queue: std::collections::VecDeque<ProcessId>,
failures: Vec<crate::error::Error>,
remain: bool,
left_out: bool,
done: bool,
}
impl<'a> ConfirmWalk<'a> {
pub(crate) fn new(
job: &'a JobHandle,
count: u32,
snapshot: Result<Vec<Found>, crate::error::Error>,
settled: &Settled,
) -> ConfirmWalk<'a> {
let mut walk = ConfirmWalk {
job,
count,
queue: std::collections::VecDeque::new(),
failures: Vec::new(),
remain: false,
left_out: false,
done: false,
};
match snapshot {
Err(failed) => walk.failures.push(failed),
Ok(found) => {
for member in found {
match member {
Ok(id) if settled.covers_identity(id) => walk.left_out = true,
Ok(id) => walk.queue.push_back(id),
Err((pid, _)) if settled.covers_unreadable(pid) => walk.left_out = true,
Err((pid, cause)) => walk.failures.push(member_unobserved(pid, cause)),
}
}
}
}
walk
}
pub(crate) fn next(&mut self) -> ConfirmStep {
debug_assert!(!self.done, "a confirmation walk was asked for a step after its answer");
match self.queue.pop_front() {
Some(id) => ConfirmStep::Wait(id),
None => {
self.done = true;
ConfirmStep::Done(self.answer())
}
}
}
pub(crate) fn waited(&mut self, id: ProcessId, outcome: Result<bool, crate::error::Error>) {
match outcome {
Ok(true) => {}
Ok(false) => self.remain = true,
Err(cause) => self.failures.push(member_unobserved(id.pid(), cause)),
}
}
fn answer(&mut self) -> Result<crate::containment::TreeDrain, crate::error::Error> {
use crate::containment::TreeDrain;
let mut failures = std::mem::take(&mut self.failures).into_iter();
if let Some(first) = failures.next() {
return Err(first.with_peers(failures.map(std::sync::Arc::new)));
}
if self.remain {
return Ok(TreeDrain::MembersRemain);
}
if !self.left_out {
self.job.confirmed_at(self.count);
}
Ok(TreeDrain::AllMembersExited)
}
}
fn unsignalled_members(job: HANDLE) -> Result<Vec<Found>, crate::error::Error> {
use crate::identity::HostKernel;
let mut members = Vec::new();
for (pid, _parent) in crate::containment::enumerate::process_parents(&HostKernel)? {
let Ok(handle) = open_for_membership(pid) else {
continue;
};
match member_identity(job, pid, Ok(handle)) {
Ok(Some(id)) => members.push(Ok(id)),
Ok(None) => {}
Err(NotNamed::Membership(e)) => log::debug!(
"the drain's snapshot names pid {pid}, whose membership of the job cannot be established ({report}); \
it is not waited for",
report = crate::error::Report(&e)
),
Err(NotNamed::Identity(cause)) => members.push(Err((pid, cause))),
}
}
Ok(members)
}
fn total_processes(job: HANDLE) -> io::Result<u32> {
let mut info = JOBOBJECT_BASIC_ACCOUNTING_INFORMATION::default();
unsafe {
QueryInformationJobObject(
Some(job),
JobObjectBasicAccountingInformation,
std::ptr::addr_of_mut!(info).cast(),
size_of::<JOBOBJECT_BASIC_ACCOUNTING_INFORMATION>() as u32,
None,
)
}
.map_err(win32_io_error)?;
Ok(info.TotalProcesses)
}
fn member_unobserved(pid: u32, cause: crate::error::Error) -> crate::error::Error {
crate::error::Error::Unassessable {
detail: format!("a member of the job, pid {pid}, could not be waited for"),
source: Some(std::sync::Arc::new(cause)),
}
}
fn drain_round(job: HANDLE, last_round: bool) -> Result<Round, crate::error::Error> {
use crate::error::Error;
let pids = match list_members_or_drained(job)? {
ControlFlow::Break(()) => return Ok(Round::Confirm),
ControlFlow::Continue(pids) => pids,
};
let mut looks = Looks {
job,
last_round,
handles: Vec::new(),
denied: None,
unproved: Vec::new(),
};
looks.look(&pids, false)?;
if looks.handles.is_empty() {
if let Some((pid, e)) = looks.denied.take() {
log::warn!(
"wait_tree: could not open any live job member to watch for its exit ({report})",
report = crate::error::Report(&e)
);
return Err(member_unobserved(pid, Error::Io(e)));
}
if looks.unproved.is_empty() {
if last_round {
return final_listing(job);
}
return Ok(Round::List);
}
match settle_unproved(job, &looks.unproved)? {
ControlFlow::Break(()) => return Ok(Round::Confirm),
ControlFlow::Continue(named) => looks.look(&named, true)?,
}
if last_round {
return Ok(Round::Answer(crate::containment::TreeDrain::MembersRemain));
}
if looks.handles.is_empty() {
return Ok(Round::List);
}
}
let Looks { handles, denied, .. } = looks;
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,
}))
}
struct Looks {
job: HANDLE,
last_round: bool,
handles: Vec<std::os::windows::io::OwnedHandle>,
denied: Option<(u32, io::Error)>,
unproved: Vec<(u32, io::Error)>,
}
impl Looks {
fn look(&mut self, pids: &[u32], settling: bool) -> Result<(), crate::error::Error> {
use crate::error::Error;
let budget = MAXIMUM_WAIT_OBJECTS - 1;
for &pid in pids {
if self.handles.len() == budget {
break;
}
let holds = !(settling && self.last_round);
match member_to_watch_for_wait(pid, self.job) {
Ok(Standing::Member(h)) if holds => {
self.handles
.push(unsafe { std::os::windows::io::FromRawHandle::from_raw_handle(h.0) });
}
Ok(Standing::Member(h)) => {
_ = unsafe { CloseHandle(h) };
}
Ok(Standing::NotMember) => {}
Ok(Standing::Unproved(cause)) | Err(cause) if settling => {
return Err(member_unobserved(pid, Error::Io(cause)))
}
Ok(Standing::Unproved(cause)) => self.unproved.push((pid, cause)),
Err(e) => self.denied = Some((pid, e)),
}
}
Ok(())
}
}
fn final_listing(job: HANDLE) -> Result<Round, crate::error::Error> {
use crate::containment::TreeDrain;
Ok(match list_members_or_drained(job)? {
ControlFlow::Break(()) => Round::Confirm,
ControlFlow::Continue(_) => Round::Answer(TreeDrain::MembersRemain),
})
}
fn list_members_or_drained(job: HANDLE) -> io::Result<ControlFlow<(), Vec<u32>>> {
let pids = query_job_pid_list(job)?;
Ok(if pids.is_empty() {
ControlFlow::Break(())
} 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
}
}
#[derive(Debug)]
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 suspend_thread(thread: &ThreadHandle) -> windows::core::Result<u32> {
match unsafe { windows::Win32::System::Threading::SuspendThread(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
}
}
}
fn initial_thread_among(
entries: &[windows::Win32::System::Diagnostics::ToolHelp::THREADENTRY32],
process_pid: u32,
walk: &mut Walk,
) -> Option<u32> {
let own: Vec<u32> = entries
.iter()
.filter(|e| e.th32OwnerProcessID == process_pid)
.map(|e| e.th32ThreadID)
.collect();
initial_thread_id(process_pid, &own, walk)
}
#[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<()> {
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?;
let entries = thread_entries()?;
if walk.expected == SuspendCount::ExactlyOne {
if let Some(initial) = initial_thread_among(&entries, process_pid, &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,
strict: bool,
) -> Result<Option<JobHandle>, crate::containment::dispatch::AttachFailure> {
let job_result = match assign_held(proc_handle) {
Err(e) if strict => {
let proven = match not_started::prove_not_started(proc_handle) {
Ok(proven) => Some(Box::new(proven)),
Err(why) => {
log::warn!(
"the child may have run, so its failed Job assignment is not a not-started failure: {why}"
);
None
}
};
let detail = "the child could not be put in its Job Object";
return Err(crate::containment::dispatch::AttachFailure {
cause: crate::error::Error::Containment {
detail: if proven.is_some() {
format!("{detail}, so the program did not run")
} else {
detail.to_owned()
},
source: Some(crate::error::Error::io_cause(e)),
},
cleanup: None,
not_started: proven.is_some(),
proven,
});
}
other => other,
};
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),
not_started: false,
proven: None,
});
}
match job_result {
Ok(job) => Ok(Some(job)),
Err(e) => {
let child = process_pid_of(HANDLE(proc_handle.cast()))
.map_or_else(|_| "the child".to_owned(), |pid| format!("pid {pid}"));
log::warn!(
"Job Object containment: {child} could not be put in its Job Object ({report}); falling back to a process-tree walk",
report = crate::error::Report(&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
}
#[path = "windows/not_started.rs"]
mod not_started;
pub(crate) use not_started::ProvenRoot;
#[cfg(test)]
#[path = "windows_tests.rs"]
mod windows_tests;
#[cfg(test)]
#[path = "windows_confirm_tests.rs"]
mod windows_confirm_tests;