use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
use std::time::Instant;
use windows::Win32::Foundation::{CloseHandle, HANDLE, WAIT_FAILED, WAIT_OBJECT_0, WAIT_TIMEOUT};
use windows::Win32::System::Threading::{
CreateEventW, SetEvent, TerminateProcess, WaitForMultipleObjects, WaitForSingleObject,
PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE, PROCESS_TERMINATE,
};
use crate::error::Error;
use crate::identity::{HandleIdentity, Liveness, Opened, ProcessId};
fn close(handle: HANDLE) {
let closed = unsafe { CloseHandle(handle) };
debug_assert!(closed.is_ok(), "CloseHandle of an owned process handle should not fail");
}
pub(crate) fn block_until_exit(id: ProcessId, deadline: Option<Option<Instant>>) -> Result<bool, Error> {
let handle = match crate::identity::windows_open_classified(
id.pid(),
PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION,
) {
Opened::Found(h) => h,
Opened::Gone => return Ok(true), Opened::Denied(e) => {
return match id.is_alive() {
Liveness::Dead => Ok(true),
Liveness::Alive | Liveness::Unknown => {
log::warn!(
"wait: pid {} could not be opened to watch for its exit ({e}) - reporting an error, not an exit",
id.pid()
);
Err(Error::Unassessable {
detail: format!("pid {} could not be opened to watch for its exit", id.pid()),
source: Some(e.into()),
})
}
}
}
};
match crate::identity::windows_handle_identity(handle, id) {
HandleIdentity::Same => {}
HandleIdentity::Different => {
close(handle);
return Ok(true); }
HandleIdentity::Unreadable(e) => {
log::warn!(
"wait: pid {} opened but its identity could not be verified ({e})",
id.pid()
);
close(handle);
return Err(Error::Unassessable {
detail: format!("pid {} opened but its identity could not be verified", id.pid()),
source: Some(e.into()),
});
}
}
let waited = crate::wait::wait_until(deadline, |ms| unsafe { WaitForSingleObject(handle, ms) });
let wait_err = (waited != WAIT_OBJECT_0 && waited != WAIT_TIMEOUT).then(std::io::Error::last_os_error);
close(handle);
match wait_err {
None => Ok(waited == WAIT_OBJECT_0), Some(e) => Err(Error::Io(e)),
}
}
#[cfg_attr(
not(feature = "tokio"),
allow(
dead_code,
reason = "only consumer is tokio::wait::grace_wait and the async raw backend, behind the tokio feature"
)
)]
pub(crate) fn new_cancel_event() -> Result<OwnedHandle, Error> {
let h = unsafe { CreateEventW(None, true, false, None) }.map_err(|e| Error::Io(e.into()))?;
Ok(unsafe { OwnedHandle::from_raw_handle(h.0 as _) })
}
#[cfg_attr(
not(feature = "tokio"),
allow(
dead_code,
reason = "only consumer is tokio::wait::grace_wait and the async raw backend, behind the tokio feature"
)
)]
pub(crate) fn signal_cancel(event: &OwnedHandle) {
let set = unsafe { SetEvent(HANDLE(event.as_raw_handle())) };
debug_assert!(set.is_ok(), "SetEvent on an owned event handle failed: {set:?}");
if !std::thread::panicking() {
assert!(set.is_ok(), "SetEvent on an owned event handle failed: {set:?}");
} else if let Err(e) = &set {
log::error!("SetEvent failed during unwind ({e}); a parked watcher may not release");
}
}
#[cfg_attr(
not(any(feature = "tokio", test)),
allow(
dead_code,
reason = "only consumers are block_until_exit_or_cancel's (behind the tokio feature) and the unit-test fixtures"
)
)]
pub(crate) fn open_verified(id: ProcessId) -> Result<Option<HANDLE>, Error> {
let handle = match crate::identity::windows_open_classified(
id.pid(),
PROCESS_SYNCHRONIZE | PROCESS_QUERY_LIMITED_INFORMATION,
) {
Opened::Found(h) => h,
Opened::Gone => return Ok(None), Opened::Denied(e) => {
return match id.is_alive() {
Liveness::Dead => Ok(None),
Liveness::Alive | Liveness::Unknown => {
log::warn!(
"wait: pid {} could not be opened to watch for its exit ({e}) - reporting an error, not an exit",
id.pid()
);
Err(Error::Unassessable {
detail: format!("pid {} could not be opened to watch for its exit", id.pid()),
source: Some(e.into()),
})
}
}
}
};
match crate::identity::windows_handle_identity(handle, id) {
HandleIdentity::Same => {}
HandleIdentity::Different => {
close(handle);
return Ok(None); }
HandleIdentity::Unreadable(e) => {
log::warn!(
"wait: pid {} opened but its identity could not be verified ({e})",
id.pid()
);
close(handle);
return Err(Error::Unassessable {
detail: format!("pid {} opened but its identity could not be verified", id.pid()),
source: Some(e.into()),
});
}
}
Ok(Some(handle))
}
#[cfg_attr(
not(feature = "tokio"),
allow(
dead_code,
reason = "only consumer is tokio::wait::grace_wait and the async raw backend, behind the tokio feature"
)
)]
pub(crate) fn block_until_exit_or_cancel(
id: ProcessId,
deadline: Option<Instant>,
cancel: &OwnedHandle,
) -> Result<bool, Error> {
#[cfg(feature = "tokio")]
crate::bounded::assert_may_block("waiting for a process to exit or be cancelled");
let Some(handle) = open_verified(id)? else {
return Ok(true); };
#[cfg(test)]
crate::wait::read_probe::mark("identity verified");
#[cfg(test)]
if armed_probe::is_armed() {
let already = unsafe { WaitForSingleObject(handle, 0) };
if already == WAIT_FAILED {
let e = std::io::Error::last_os_error();
debug_assert!(
false,
"armed_probe: non-blocking poll of an identity-verified handle failed: {e}"
);
} else if already != WAIT_OBJECT_0 {
armed_probe::notify_armed_unsignalled();
signal_cancel(cancel);
}
}
let handles = [handle, HANDLE(cancel.as_raw_handle())];
let waited = crate::wait::wait_until(deadline.map(Some), |ms| unsafe {
WaitForMultipleObjects(&handles, false, ms)
});
let wait_failed = (waited == WAIT_FAILED).then(std::io::Error::last_os_error);
close(handle);
if waited == WAIT_OBJECT_0 {
Ok(true) } else if waited.0 == WAIT_OBJECT_0.0 + 1 || waited == WAIT_TIMEOUT {
Ok(false) } else if let Some(e) = wait_failed {
Err(Error::Io(e))
} else {
debug_assert!(false, "unexpected WaitForMultipleObjects verdict: {waited:?}");
Err(Error::Io(std::io::Error::other(format!(
"unexpected WaitForMultipleObjects result: {waited:?}"
))))
}
}
pub(crate) fn kill(id: ProcessId) -> Result<(), Error> {
let handle =
match crate::identity::windows_open_classified(id.pid(), PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION)
{
Opened::Found(h) => h,
Opened::Gone => return Ok(()), Opened::Denied(e) => {
return if id.is_alive() == Liveness::Dead {
Ok(())
} else {
log::warn!(
"wait: pid {} could not be opened to terminate it ({e}) - reporting an error, not a kill",
id.pid()
);
Err(Error::Unassessable {
detail: format!("pid {} could not be opened to terminate it", id.pid()),
source: Some(e.into()),
})
}
}
};
match crate::identity::windows_handle_identity(handle, id) {
HandleIdentity::Same => {}
HandleIdentity::Different => {
close(handle);
return Ok(()); }
HandleIdentity::Unreadable(e) => {
log::warn!(
"wait: pid {} opened but its identity could not be verified ({e})",
id.pid()
);
close(handle);
return Err(Error::Unassessable {
detail: format!("pid {} opened but its identity could not be verified", id.pid()),
source: Some(e.into()),
});
}
}
let res = unsafe { TerminateProcess(handle, 1) };
let verdict = res.is_err().then(|| id.is_alive());
close(handle);
match res {
Ok(()) => Ok(()),
Err(_) if verdict == Some(Liveness::Dead) => Ok(()),
Err(e) => {
log::warn!(
"wait: TerminateProcess(pid {}) failed and the target is not provably dead ({e})",
id.pid()
);
Err(Error::Io(e.into()))
}
}
}
pub(crate) fn terminate(id: ProcessId) -> Result<(), Error> {
let _ = id;
Err(Error::Unsupported {
op: "graceful terminate (SIGTERM-equivalent)".into(),
platform: "windows",
detail: "Windows has no per-process graceful-termination signal; for a contained \
child use graceful_shutdown_tree (CTRL_BREAK to the group)"
.into(),
})
}
#[cfg(test)]
pub(crate) mod armed_probe {
use crate::relayed_probe::{self, Probe};
use std::sync::mpsc::Sender;
pub(crate) struct Armed;
impl Probe for Armed {
type Event = ();
}
pub(crate) type Guard = relayed_probe::Guard<Armed>;
#[cfg_attr(
not(feature = "tokio"),
allow(
dead_code,
reason = "only consumer is tokio::wait::grace_wait and the async raw backend, behind the tokio feature"
)
)]
pub(crate) fn install(tx: Sender<()>) -> Guard {
relayed_probe::install(tx)
}
pub(crate) fn is_armed() -> bool {
relayed_probe::is_installed::<Armed>()
}
pub(crate) fn notify_armed_unsignalled() {
relayed_probe::notify::<Armed>(());
}
}
#[cfg(test)]
#[path = "windows_tests.rs"]
mod windows_tests;