use std::os::windows::io::{AsHandle, AsRawHandle, FromRawHandle, OwnedHandle};
use windows::Win32::Foundation::{CloseHandle, HANDLE};
use windows::Win32::System::Threading::{
PROCESS_ACCESS_RIGHTS, PROCESS_ALL_ACCESS, PROCESS_SYNCHRONIZE, PROCESS_TERMINATE,
};
use super::child::{KillRefusal, OsChild, OsHandle, PeekOutcome, TryObserveOutcome};
use super::{Exit, OsProcess, WaitFor};
use crate::error::{win32_io_error, Error};
use crate::identity::{
windows_exit_look, windows_granted_access, windows_open_dropping_refused, windows_terminate_held, HandleIdentity,
Kernel, Liveness, Look, Opened, ProcessId, Termination,
};
use crate::signal::{Sent, Sig};
use crate::wait::exit_only::{self, Target};
#[cfg(feature = "tokio")]
pub(crate) mod registered_wait;
#[cfg(test)]
pub(crate) mod test_event;
pub(crate) const CREATE_PROCESS_ACCESS: PROCESS_ACCESS_RIGHTS = PROCESS_ALL_ACCESS;
pub(crate) struct WindowsProcess<K> {
kernel: K,
pid: Option<u32>,
handle: OwnedHandle,
granted: PROCESS_ACCESS_RIGHTS,
}
impl<K> std::fmt::Debug for WindowsProcess<K> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("WindowsProcess")
.field("pid", &self.pid)
.field("handle", &self.handle)
.field("granted", &self.granted)
.finish_non_exhaustive()
}
}
impl<K: Kernel + Send> WindowsProcess<K> {
pub(crate) fn open(kernel: K, id: ProcessId) -> Result<Option<Self>, Error> {
let Some((handle, granted)) = open_verified(id)? else {
return Ok(None);
};
#[cfg(test)]
crate::wait::read_probe::mark("identity verified");
Ok(Some(Self {
kernel,
pid: Some(id.pid()),
handle: unsafe { OwnedHandle::from_raw_handle(handle.0 as _) },
granted,
}))
}
pub(crate) fn for_child(kernel: K, handle: OwnedHandle, pid: u32) -> Self {
Self {
kernel,
pid: Some(pid),
handle,
granted: CREATE_PROCESS_ACCESS,
}
}
pub(crate) fn for_uac(kernel: K, handle: OwnedHandle, pid: Option<u32>) -> Self {
let granted = uac_access(HANDLE(handle.as_raw_handle()));
Self {
kernel,
pid,
handle,
granted,
}
}
fn raw(&self) -> HANDLE {
HANDLE(self.handle.as_raw_handle())
}
fn has_synchronize(&self) -> bool {
self.granted.0 & PROCESS_SYNCHRONIZE.0 != 0
}
}
fn uac_access(handle: HANDLE) -> PROCESS_ACCESS_RIGHTS {
access_of_uac_read(windows_granted_access(handle))
}
pub(crate) fn access_of_uac_read(read: Result<u32, impl std::error::Error + 'static>) -> PROCESS_ACCESS_RIGHTS {
let granted = match read {
Ok(access) => PROCESS_ACCESS_RIGHTS(access),
Err(e) => {
log::debug!(
"uac_access: the access granted to an elevated child's handle could not be read ({report})",
report = crate::error::Report(&e)
);
PROCESS_SYNCHRONIZE
}
};
if granted.0 & PROCESS_SYNCHRONIZE.0 == 0 {
log::warn!("uac_access: an elevated child's handle was not granted SYNCHRONIZE; it cannot be waited on");
debug_assert!(false, "an elevated child's handle holds SYNCHRONIZE");
}
granted
}
fn close(handle: HANDLE) {
let closed = unsafe { CloseHandle(handle) };
debug_assert!(closed.is_ok(), "CloseHandle of an owned process handle should not fail");
}
fn holds_process(handle: HANDLE, id: ProcessId) -> Result<bool, Error> {
match crate::identity::windows_handle_identity(handle, id) {
HandleIdentity::Same => Ok(true),
HandleIdentity::Different => {
close(handle);
Ok(false)
}
HandleIdentity::Unreadable(e) => {
close(handle);
Err(Error::Unassessable {
detail: format!("pid {} opened but its identity could not be verified", id.pid()),
source: Some(Error::io_cause(win32_io_error(e))),
})
}
}
}
pub(crate) fn open_verified(id: ProcessId) -> Result<Option<(HANDLE, PROCESS_ACCESS_RIGHTS)>, Error> {
let (opened, granted) = windows_open_dropping_refused(id.pid(), &[PROCESS_SYNCHRONIZE, PROCESS_TERMINATE]);
let handle = match opened {
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 => Err(Error::Unassessable {
detail: format!("pid {} could not be opened", id.pid()),
source: Some(Error::io_cause(win32_io_error(e))),
}),
}
}
};
if !holds_process(handle, id)? {
return Ok(None); }
Ok(Some((handle, granted)))
}
impl<K: Kernel + Send> OsProcess for WindowsProcess<K> {
fn signal(&self, sig: Sig) -> Result<Sent, Error> {
match sig {
Sig::Kill => match windows_terminate_held(&self.kernel, self.raw(), self.granted) {
Termination::Terminated => Ok(Sent::Delivered),
Termination::Exited => Ok(Sent::Gone),
Termination::Failed(e) => {
log::debug!(
"wait: TerminateProcess({}) failed ({report})",
super::child_named(self.pid),
report = crate::error::Report(&e)
);
Err(Error::Io(win32_io_error(e)))
}
},
}
}
fn exited(&self) -> Result<Exit<'_>, Error> {
match windows_exit_look(self.raw(), self.has_synchronize()) {
Ok(Look::Exited) => Ok(Exit::Exited),
Ok(Look::Running) => Ok(Exit::Running(WaitFor::Signalled(self.handle.as_handle()))),
Err(e) => Err(Error::Io(win32_io_error(e))),
}
}
fn os_handle(&self) -> OsHandle<'_> {
self.handle.as_handle()
}
}
impl<K: Kernel + Send> OsChild for WindowsProcess<K> {
fn pid(&self) -> Option<u32> {
self.pid
}
fn kernel(&self) -> &dyn Kernel {
&self.kernel
}
fn kill_refusal(&self) -> KillRefusal {
if self.granted.0 & PROCESS_TERMINATE.0 != 0 {
KillRefusal::Never
} else {
KillRefusal::Permission
}
}
fn peek(&self) -> Result<PeekOutcome, Error> {
debug_assert!(self.has_synchronize(), "a child's handle can be waited on");
exit_only::peek(&Target::Handle(self.handle.as_handle())).map_err(Error::Io)
}
fn try_observe(&self) -> Result<TryObserveOutcome<'_>, Error> {
debug_assert!(self.has_synchronize(), "a child's handle can be waited on");
let handle = self.handle.as_handle();
Ok(match exit_only::peek(&Target::Handle(handle)).map_err(Error::Io)? {
PeekOutcome::Exit(record) => TryObserveOutcome::Exited(record),
PeekOutcome::Running => TryObserveOutcome::Running(WaitFor::Signalled(handle)),
PeekOutcome::Foreign(foreign) => TryObserveOutcome::Foreign(foreign),
})
}
}
#[cfg(test)]
#[path = "windows_tests.rs"]
mod windows_tests;