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, TryReapOutcome};
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,
Liveness, Look, Opened, ProcessId, Termination,
};
use crate::signal::{Sent, Sig};
use crate::wait::exit_only::{self, Reap, Target};
pub(crate) mod cancel;
pub(crate) const CREATE_PROCESS_ACCESS: PROCESS_ACCESS_RIGHTS = PROCESS_ALL_ACCESS;
#[derive(Debug)]
pub(crate) struct WindowsProcess {
pid: u32,
handle: OwnedHandle,
granted: PROCESS_ACCESS_RIGHTS,
}
impl WindowsProcess {
pub(crate) fn open(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 {
pid: id.pid(),
handle: unsafe { OwnedHandle::from_raw_handle(handle.0 as _) },
granted,
}))
}
pub(crate) fn for_child(handle: OwnedHandle, pid: u32) -> Self {
Self {
pid,
handle,
granted: CREATE_PROCESS_ACCESS,
}
}
pub(crate) fn for_uac(handle: OwnedHandle, pid: u32, granted: PROCESS_ACCESS_RIGHTS) -> Self {
Self { 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
}
}
pub(crate) 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::fmt::Display>) -> 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 ({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) => {
log::warn!(
"wait: pid {} opened but its identity could not be verified ({e})",
id.pid()
);
close(handle);
Err(Error::Unassessable {
detail: format!("pid {} opened but its identity could not be verified", id.pid()),
source: Some(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 => {
log::warn!(
"wait: pid {} could not be opened ({e}) - reporting an error, not an exit or a kill",
id.pid()
);
Err(Error::Unassessable {
detail: format!("pid {} could not be opened", id.pid()),
source: Some(win32_io_error(e)),
})
}
}
}
};
if !holds_process(handle, id)? {
return Ok(None); }
Ok(Some((handle, granted)))
}
impl OsProcess for WindowsProcess {
fn signal(&self, sig: Sig) -> Result<Sent, Error> {
match sig {
Sig::Kill => match windows_terminate_held(self.raw(), self.granted) {
Termination::Terminated => Ok(Sent::Delivered),
Termination::Exited => Ok(Sent::Gone),
Termination::Failed(e) => {
log::debug!("wait: TerminateProcess(pid {}) failed ({e})", self.pid);
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 OsChild for WindowsProcess {
fn pid(&self) -> Option<u32> {
Some(self.pid)
}
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_reap(&self) -> Result<TryReapOutcome<'_>, Error> {
debug_assert!(self.has_synchronize(), "a child's handle can be waited on");
let handle = self.handle.as_handle();
Ok(match exit_only::try_reap(&Target::Handle(handle)).map_err(Error::Io)? {
Reap::Reaped(record) => TryReapOutcome::Reaped(record),
Reap::Running => TryReapOutcome::Running(WaitFor::Signalled(handle)),
Reap::Foreign(foreign) => TryReapOutcome::Foreign(foreign),
})
}
}
#[cfg(test)]
#[path = "windows_tests.rs"]
mod windows_tests;