#![cfg(windows)]
#![warn(unsafe_op_in_unsafe_fn)]
use std::process::{self, Child, ExitStatus};
use std::{mem, os::windows::io::AsRawHandle, ptr};
use anyhow::Result;
use windows_sys::Win32::{
Foundation::{CloseHandle, HANDLE},
System::JobObjects::{
AssignProcessToJobObject, CreateJobObjectW, JobObjectBasicAccountingInformation,
QueryInformationJobObject, JOBOBJECT_BASIC_ACCOUNTING_INFORMATION,
},
};
#[cfg(feature = "windows_process_extensions_main_thread_handle")]
use std::os::windows::process::ChildExt;
#[cfg(feature = "windows_process_extensions_main_thread_handle")]
use windows_sys::Win32::System::Threading::ResumeThread;
#[cfg(not(feature = "windows_process_extensions_main_thread_handle"))]
use once_cell::sync::Lazy;
#[cfg(not(feature = "windows_process_extensions_main_thread_handle"))]
use windows_sys::{
s, w,
Win32::{
Foundation::{NTSTATUS, STATUS_SUCCESS},
System::LibraryLoader::{GetModuleHandleW, GetProcAddress},
},
};
use crate::quantity::{nanosecond, Information, Time, Zero};
#[cfg(not(feature = "windows_process_extensions_main_thread_handle"))]
#[allow(non_upper_case_globals)]
static NtResumeProcess: Lazy<unsafe extern "system" fn(process_handle: HANDLE) -> NTSTATUS> =
Lazy::new(|| {
let ntdll = unsafe { GetModuleHandleW(w!("ntdll.dll")) };
assert!(!ntdll.is_null(), "GetModuleHandleW failed");
let nt_resume_process = unsafe { GetProcAddress(ntdll, s!("NtResumeProcess")) };
unsafe { mem::transmute(nt_resume_process.unwrap()) }
});
pub struct CPUTimer {
job_object: HANDLE,
}
impl CPUTimer {
pub unsafe fn start_suspended_process(child: &process::Child) -> Self {
let child_handle = child.as_raw_handle() as HANDLE;
let job_object = unsafe { CreateJobObjectW(ptr::null_mut(), ptr::null_mut()) };
assert!(!job_object.is_null(), "CreateJobObjectW failed");
let ret = unsafe { AssignProcessToJobObject(job_object, child_handle) };
assert!(ret != 0, "AssignProcessToJobObject failed");
#[cfg(feature = "windows_process_extensions_main_thread_handle")]
{
let ret = unsafe { ResumeThread(child.main_thread_handle().as_raw_handle() as HANDLE) };
assert!(ret != u32::MAX, "ResumeThread failed");
}
#[cfg(not(feature = "windows_process_extensions_main_thread_handle"))]
{
let ret = unsafe { NtResumeProcess(child_handle) };
assert!(ret == STATUS_SUCCESS, "NtResumeProcess failed");
}
Self { job_object }
}
pub fn stop(&self, mut child: Child) -> Result<(Time, Time, Option<Information>, ExitStatus)> {
let status = child.wait()?;
let mut job_object_info =
mem::MaybeUninit::<JOBOBJECT_BASIC_ACCOUNTING_INFORMATION>::uninit();
let res = unsafe {
QueryInformationJobObject(
self.job_object,
JobObjectBasicAccountingInformation,
job_object_info.as_mut_ptr().cast(),
mem::size_of::<JOBOBJECT_BASIC_ACCOUNTING_INFORMATION>() as u32,
ptr::null_mut(),
)
};
if res != 0 {
let job_object_info = unsafe { job_object_info.assume_init() };
let user_time = Time::new::<nanosecond>((job_object_info.TotalUserTime as f64) * 100.0);
let system_time =
Time::new::<nanosecond>((job_object_info.TotalKernelTime as f64) * 100.0);
Ok((user_time, system_time, None, status))
} else {
Ok((Time::zero(), Time::zero(), None, status))
}
}
}
impl Drop for CPUTimer {
fn drop(&mut self) {
unsafe { CloseHandle(self.job_object) };
}
}