use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
use std::time::{Duration, Instant};
use windows::Win32::Foundation::{CloseHandle, HANDLE, WAIT_FAILED, WAIT_OBJECT_0, WAIT_TIMEOUT};
use windows::Win32::System::Threading::{
CreateEventW, SetEvent, TerminateProcess, WaitForMultipleObjects, WaitForSingleObject, INFINITE,
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 ms: u32 = match crate::wait::remaining(deadline) {
None => INFINITE,
Some(d) => d.as_millis().min((INFINITE - 1) as u128) as u32,
};
let waited = 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))]
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))]
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(feature = "tokio"), allow(dead_code))] pub(crate) fn block_until_exit_or_cancel(
id: ProcessId,
grace: Option<Duration>,
cancel: &OwnedHandle,
) -> 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 ms = match grace {
None => INFINITE,
Some(d) => {
let clamped = d.as_millis().min((INFINITE - 1) as u128) as u32;
debug_assert!(
d.as_millis() <= (INFINITE - 1) as u128,
"Windows grace clamped to INFINITE-1 ms (~49.7 days): {}",
d.as_secs()
);
clamped
}
};
let handles = [handle, HANDLE(cancel.as_raw_handle())];
let waited = 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(),
})
}