use std::time::{Duration, SystemTime};
use windows::Wdk::Foundation::{NtQueryObject, ObjectBasicInformation};
use windows::Wdk::System::Threading::{NtQueryInformationProcess, ProcessBasicInformation, PROCESSINFOCLASS};
use windows::Win32::Foundation::{
CloseHandle, RtlNtStatusToDosError, ERROR_INVALID_PARAMETER, FILETIME, HANDLE, NTSTATUS, STILL_ACTIVE, WAIT_FAILED,
WAIT_OBJECT_0, WAIT_TIMEOUT,
};
use windows::Win32::System::Threading::{
GetCurrentProcess, GetExitCodeProcess, GetProcessTimes, OpenProcess, TerminateProcess, WaitForSingleObject,
PROCESS_ACCESS_RIGHTS, PROCESS_BASIC_INFORMATION, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE,
PROCESS_TERMINATE,
};
use windows::Win32::System::WindowsProgramming::PUBLIC_OBJECT_BASIC_INFORMATION;
use super::{Key, Liveness, OrderKey, OrderedRead, ParentRead, RawPid, Resolved, UnknownCause};
const EPOCH_DIFF_100NS: u64 = 116_444_736_000_000_000;
pub(crate) const ERROR_INVALID_PARAMETER_HRESULT: windows::core::HRESULT =
windows::core::HRESULT::from_win32(ERROR_INVALID_PARAMETER.0);
pub(crate) enum Opened {
Found(HANDLE),
Gone,
Denied(windows::core::Error),
}
pub(crate) fn open_classified(pid: RawPid, mask: PROCESS_ACCESS_RIGHTS) -> Opened {
match unsafe { OpenProcess(mask, false, pid) } {
Ok(h) => Opened::Found(h),
Err(e) if e.code() == ERROR_INVALID_PARAMETER_HRESULT => Opened::Gone,
Err(e) => {
log::debug!("OpenProcess({pid}, {mask:?}) failed: {e} — reporting Unknown, not absence");
Opened::Denied(e)
}
}
}
pub(crate) fn open_dropping_refused(
pid: RawPid,
optional: &[PROCESS_ACCESS_RIGHTS],
) -> (Opened, PROCESS_ACCESS_RIGHTS) {
debug_assert!(optional.len() < 32, "a subset of the optional rights is a u32 mask");
let mut subsets: Vec<u32> = (0..1u32 << optional.len()).collect();
subsets.sort_by_key(|subset| (std::cmp::Reverse(subset.count_ones()), *subset));
let mut denied = None;
for subset in subsets {
let rights = optional
.iter()
.enumerate()
.filter(|(i, _)| subset >> i & 1 == 1)
.fold(PROCESS_QUERY_LIMITED_INFORMATION, |rights, (_, right)| rights | *right);
match open_classified(pid, rights) {
Opened::Denied(e) if is_access_denied(&e) => denied = Some((e, rights)),
opened => return (opened, rights),
}
}
let (e, rights) = denied.expect("the empty subset is always tried");
(Opened::Denied(e), rights)
}
pub(crate) fn close(handle: HANDLE) {
if let Err(e) = unsafe { CloseHandle(handle) } {
log::warn!("CloseHandle of an owned process handle failed: {e}");
debug_assert!(false, "CloseHandle of an owned process handle should not fail: {e}");
}
}
pub(crate) enum Termination {
Terminated,
Exited,
Failed(windows::core::Error),
}
pub(crate) fn is_access_denied(e: &windows::core::Error) -> bool {
e.code() == windows::core::HRESULT::from_win32(windows::Win32::Foundation::ERROR_ACCESS_DENIED.0)
}
pub(crate) fn terminate_held(handle: HANDLE, granted: PROCESS_ACCESS_RIGHTS) -> Termination {
let refusal = match terminate_process(handle) {
Ok(()) => return Termination::Terminated,
Err(e) if !is_access_denied(&e) => return Termination::Failed(e),
Err(e) => e,
};
if granted.0 & PROCESS_TERMINATE.0 != 0 {
return Termination::Exited;
}
match exit_look(handle, granted.0 & PROCESS_SYNCHRONIZE.0 != 0) {
Ok(Look::Exited) => Termination::Exited,
Ok(Look::Running) => Termination::Failed(refusal),
Err(e) => {
log::debug!("terminate_held: a handle without PROCESS_TERMINATE could not prove an exit: {e}");
Termination::Failed(refusal)
}
}
}
pub(crate) enum Look {
Exited,
Running,
}
pub(crate) fn exit_look(handle: HANDLE, has_synchronize: bool) -> windows::core::Result<Look> {
if has_synchronize {
return match unsafe { WaitForSingleObject(handle, 0) } {
WAIT_OBJECT_0 => Ok(Look::Exited),
WAIT_TIMEOUT => Ok(Look::Running),
WAIT_FAILED => Err(windows::core::Error::from_thread()),
other => {
debug_assert!(false, "WaitForSingleObject returned {other:?}");
Err(windows::core::Error::new(
windows::Win32::Foundation::E_UNEXPECTED,
format!("WaitForSingleObject returned {other:?}"),
))
}
};
}
let mut code = 0u32;
unsafe { GetExitCodeProcess(handle, &mut code) }?;
if code != STILL_ACTIVE.0 as u32 {
return Ok(Look::Exited);
}
Err(windows::core::Error::from_hresult(windows::core::HRESULT::from_win32(
windows::Win32::Foundation::ERROR_ACCESS_DENIED.0,
)))
}
pub(crate) fn granted_access(handle: HANDLE) -> windows::core::Result<u32> {
let mut info = PUBLIC_OBJECT_BASIC_INFORMATION::default();
let status = unsafe {
NtQueryObject(
Some(handle),
ObjectBasicInformation,
Some(std::ptr::from_mut(&mut info).cast()),
std::mem::size_of::<PUBLIC_OBJECT_BASIC_INFORMATION>() as u32,
None,
)
};
if status.is_ok() {
return Ok(info.GrantedAccess);
}
let code = unsafe { RtlNtStatusToDosError(status) };
Err(windows::core::Error::from_hresult(windows::core::HRESULT::from_win32(
code,
)))
}
pub(crate) const TERMINATE_EXIT_CODE: u32 = 1;
fn terminate_process(handle: HANDLE) -> windows::core::Result<()> {
#[cfg(test)]
if fault::fire_exiting_refusal() {
return Err(windows::core::Error::from_hresult(windows::core::HRESULT::from_win32(
windows::Win32::Foundation::ERROR_ACCESS_DENIED.0,
)));
}
unsafe { TerminateProcess(handle, TERMINATE_EXIT_CODE) }
}
#[cfg(test)]
pub(crate) mod fault {
use crate::oneshot_hook::{self, Armed, OneShotHook};
thread_local! {
static EXITING: OneShotHook = const { OneShotHook::new() };
}
pub(crate) fn refuse_next_terminate_as_exiting() -> Armed {
oneshot_hook::arm(&EXITING, || {})
}
pub(super) fn fire_exiting_refusal() -> bool {
oneshot_hook::fire_with(&EXITING, ()).is_some()
}
}
pub(crate) fn creation_token_result(handle: HANDLE) -> windows::core::Result<Key> {
let mut creation = FILETIME::default();
let mut exit = FILETIME::default();
let mut kernel = FILETIME::default();
let mut user = FILETIME::default();
unsafe { GetProcessTimes(handle, &mut creation, &mut exit, &mut kernel, &mut user) }?;
let ft = ((creation.dwHighDateTime as u64) << 32) | creation.dwLowDateTime as u64;
Ok(Key::from_raw(ft))
}
pub(super) fn creation_token(handle: HANDLE) -> Option<Key> {
creation_token_result(handle).ok()
}
const PROCESS_SEQUENCE_NUMBER: PROCESSINFOCLASS = PROCESSINFOCLASS(92);
unsafe fn query<T>(handle: HANDLE, class: PROCESSINFOCLASS, out: &mut T) -> Result<(), NTSTATUS> {
let status = unsafe {
NtQueryInformationProcess(
handle,
class,
std::ptr::from_mut(out).cast(),
std::mem::size_of::<T>() as u32,
std::ptr::null_mut(),
)
};
if status.is_ok() {
Ok(())
} else {
Err(status)
}
}
fn sequence_number(handle: HANDLE) -> Result<u64, NTSTATUS> {
let mut sequence = 0u64;
unsafe { query(handle, PROCESS_SEQUENCE_NUMBER, &mut sequence) }?;
Ok(sequence)
}
fn creator_pid(handle: HANDLE) -> Result<usize, NTSTATUS> {
let mut info = PROCESS_BASIC_INFORMATION::default();
unsafe { query(handle, ProcessBasicInformation, &mut info) }?;
Ok(info.InheritedFromUniqueProcessId)
}
pub(super) fn ordered_read(pid: RawPid, expected: Option<Key>, ask_parent: bool) -> OrderedRead {
let (read, parent, cause) = open_and_read(pid, expected, ask_parent);
OrderedRead {
read: read.map(|(key, order)| (key, Some(order))),
parent,
cause,
}
}
fn open_and_read(
pid: RawPid,
expected: Option<Key>,
ask_parent: bool,
) -> (Resolved<(Key, OrderKey)>, ParentRead, UnknownCause) {
let handle = match open_for_query(pid) {
Ok(handle) => handle,
Err(read) => return (read, ParentRead::not_read(ask_parent), UnknownCause::default()),
};
let (read, cause) = combine(pid, expected, creation_token_result(handle), sequence_number(handle));
let (parent, cause) = if ask_parent {
creator_read(pid, creator_pid(handle), cause)
} else {
(ParentRead::NotAsked, cause)
};
close(handle);
(read, parent, cause)
}
fn open_for_query<T>(pid: RawPid) -> Result<HANDLE, Resolved<T>> {
match open_classified(pid, PROCESS_QUERY_LIMITED_INFORMATION) {
Opened::Found(handle) => Ok(handle),
Opened::Gone => Err(Resolved::Gone),
Opened::Denied(_) => Err(Resolved::Unknown),
}
}
fn creator_read(pid: RawPid, creator: Result<usize, NTSTATUS>, cause: UnknownCause) -> (ParentRead, UnknownCause) {
match creator {
Ok(creator) => match RawPid::try_from(creator) {
Ok(creator) => (ParentRead::Is(creator), cause),
Err(_) => {
log::warn!("the creator pid {creator:#x} of pid {pid} is wider than a DWORD");
debug_assert!(false, "the creator pid {creator:#x} of pid {pid} is wider than a DWORD");
(ParentRead::Unreadable, cause)
}
},
Err(status) => {
log::debug!(
"NtQueryInformationProcess(ProcessBasicInformation) failed on an opened handle for pid {pid}: \
NTSTATUS {:#010x}",
status.0 as u32
);
(ParentRead::Unreadable, cause.with_creator_status(status))
}
}
}
fn combine(
pid: RawPid,
expected: Option<Key>,
key: windows::core::Result<Key>,
sequence: Result<u64, NTSTATUS>,
) -> (Resolved<(Key, OrderKey)>, UnknownCause) {
match (key, sequence) {
(Ok(now), _) if expected.is_some_and(|expected| expected != now) => (Resolved::Gone, UnknownCause::default()),
(Ok(key), Ok(sequence)) => (Resolved::Found((key, OrderKey(sequence))), UnknownCause::default()),
(Ok(_), Err(status)) => {
log::debug!(
"NtQueryInformationProcess(ProcessSequenceNumber) failed on an opened handle for pid {pid}: \
NTSTATUS {:#010x}",
status.0 as u32
);
(Resolved::Unknown, UnknownCause::of_sequence_status(status))
}
(Err(e), sequence) => {
log::debug!("GetProcessTimes failed on an opened handle for pid {pid}: {e}");
let cause = sequence
.err()
.map_or_else(UnknownCause::default, UnknownCause::of_sequence_status);
(Resolved::Unknown, cause)
}
}
}
pub(super) fn order_key(pid: RawPid, key: Key) -> (Resolved<OrderKey>, UnknownCause) {
let (read, _, cause) = open_and_read(pid, Some(key), false);
(read.map(|(_, order)| order), cause)
}
pub(crate) fn windows_identity_from_handle(handle: HANDLE, pid: RawPid) -> Option<crate::identity::ProcessId> {
let start = creation_token(handle)?;
Some(crate::identity::ProcessId { pid, key: start })
}
pub(super) fn current_token() -> Resolved<Key> {
match creation_token(unsafe { GetCurrentProcess() }) {
Some(t) => Resolved::Found(t),
None => Resolved::Unknown,
}
}
pub(super) fn start_token(pid: RawPid) -> Resolved<Key> {
let handle = match open_for_query(pid) {
Ok(handle) => handle,
Err(read) => return read,
};
let token = creation_token_result(handle);
close(handle);
match token {
Ok(t) => Resolved::Found(t),
Err(e) => {
log::debug!("GetProcessTimes failed on an opened handle for pid {pid}: {e}");
Resolved::Unknown
}
}
}
pub(super) fn created_at(start: Key) -> Option<SystemTime> {
let unix_100ns = start.raw().checked_sub(EPOCH_DIFF_100NS)?;
let secs = unix_100ns / 10_000_000;
let nanos = (unix_100ns % 10_000_000) * 100;
Some(SystemTime::UNIX_EPOCH + Duration::new(secs, nanos as u32))
}
pub(super) fn is_running(pid: RawPid, start: Key) -> Liveness {
let (opened, granted) = open_dropping_refused(pid, &[PROCESS_SYNCHRONIZE]);
let handle = match opened {
Opened::Found(h) => h,
Opened::Gone => return Liveness::Dead,
Opened::Denied(_) => return Liveness::Unknown,
};
let verdict = match creation_token_result(handle) {
Ok(t) if t == start => match exit_look(handle, granted.0 & PROCESS_SYNCHRONIZE.0 != 0) {
Ok(Look::Running) => Liveness::Alive,
Ok(Look::Exited) => Liveness::Dead,
Err(e) => {
log::debug!("exit look at pid {pid} failed: {e}");
Liveness::Unknown
}
},
Ok(_) => Liveness::Dead, Err(e) => {
log::debug!("GetProcessTimes failed on an opened handle for pid {pid}: {e}");
Liveness::Unknown
}
};
close(handle);
verdict
}
#[cfg(test)]
#[path = "windows_tests.rs"]
mod windows_tests;
pub(super) fn session_scope() -> Result<super::persist::Scope, super::persist::ScopeReadError> {
Ok(super::persist::Scope::none())
}