windows_timer.rs
This file
Path
src/timer/windows_timer.rs
122 lines · 4.7 KiB · Rust
Last changed by
Cleanup Windows CPUTimerClemens Wasserbefore adoption7db6178
History of this fileTake it
1#![cfg(windows)]2#![warn(unsafe_op_in_unsafe_fn)]34use std::{mem, os::windows::io::AsRawHandle, process, ptr};56use winapi::{7 shared::{ntdef::NTSTATUS, ntstatus::STATUS_SUCCESS},8 um::{9 handleapi::CloseHandle,10 jobapi2::{AssignProcessToJobObject, CreateJobObjectW, QueryInformationJobObject},11 libloaderapi::{GetModuleHandleA, GetProcAddress},12 winnt::{13 JobObjectBasicAccountingInformation, HANDLE, JOBOBJECT_BASIC_ACCOUNTING_INFORMATION,14 },15 },16};1718#[cfg(windows_process_extensions_main_thread_handle)]19use winapi::shared::minwindef::DWORD;2021#[cfg(not(windows_process_extensions_main_thread_handle))]22use once_cell::sync::Lazy;2324use crate::util::units::Second;2526const HUNDRED_NS_PER_MS: i64 = 10;2728#[cfg(not(windows_process_extensions_main_thread_handle))]29#[allow(non_upper_case_globals)]30static NtResumeProcess: Lazy<unsafe extern "system" fn(ProcessHandle: HANDLE) -> NTSTATUS> =31 Lazy::new(|| {32 // SAFETY: Getting the module handle for ntdll.dll is safe33 let ntdll = unsafe { GetModuleHandleA(b"ntdll.dll\0".as_ptr().cast()) };34 assert!(!ntdll.is_null(), "GetModuleHandleA failed");3536 // SAFETY: The ntdll handle is valid37 let nt_resume_process =38 unsafe { GetProcAddress(ntdll, b"NtResumeProcess\0".as_ptr().cast()) };39 assert!(!nt_resume_process.is_null(), "GetProcAddress failed");4041 // SAFETY: We transmute to the correct function signature42 unsafe { mem::transmute(nt_resume_process) }43 });4445pub struct CPUTimer {46 job_object: HANDLE,47}4849impl CPUTimer {50 pub unsafe fn start_suspended_process(child: &process::Child) -> Self {51 // SAFETY: Creating a new job object is safe52 let job_object = unsafe { CreateJobObjectW(ptr::null_mut(), ptr::null_mut()) };53 assert!(!job_object.is_null(), "CreateJobObjectW failed");5455 // SAFETY: The job object handle is valid56 let ret = unsafe { AssignProcessToJobObject(job_object, child.as_raw_handle()) };57 assert!(ret != 0, "AssignProcessToJobObject failed");5859 #[cfg(windows_process_extensions_main_thread_handle)]60 {61 // SAFETY: The main thread handle is valid62 let ret = unsafe { ResumeThread(child.main_thread_handle().as_raw_handle()) };63 assert!(ret != -1 as DWORD, "ResumeThread failed");64 }6566 #[cfg(not(windows_process_extensions_main_thread_handle))]67 {68 // Since we can't get the main thread handle on stable rust, we use69 // the undocumented but widely known `NtResumeProcess` function to70 // resume a process by it's handle.7172 // SAFETY: The process handle is valid73 let ret = unsafe { NtResumeProcess(child.as_raw_handle()) };74 assert!(ret == STATUS_SUCCESS, "NtResumeProcess failed");75 }7677 Self { job_object }78 }7980 pub fn stop(&self) -> (Second, Second) {81 let mut job_object_info =82 mem::MaybeUninit::<JOBOBJECT_BASIC_ACCOUNTING_INFORMATION>::uninit();8384 // SAFETY: A valid job object got created in `start_suspended_process`85 let res = unsafe {86 QueryInformationJobObject(87 self.job_object,88 JobObjectBasicAccountingInformation,89 job_object_info.as_mut_ptr().cast(),90 mem::size_of::<JOBOBJECT_BASIC_ACCOUNTING_INFORMATION>() as u32,91 ptr::null_mut(),92 )93 };9495 if res != 0 {96 // SAFETY: The job object info got correctly initialized97 let job_object_info = unsafe { job_object_info.assume_init() };9899 // SAFETY: The `TotalUserTime` is "The total amount of user-mode execution time for100 // all active processes associated with the job, as well as all terminated processes no101 // longer associated with the job, in 100-nanosecond ticks." and is safe to extract102 let user: i64 = unsafe { job_object_info.TotalUserTime.QuadPart() } / HUNDRED_NS_PER_MS;103104 // SAFETY: The `TotalKernelTime` is "The total amount of kernel-mode execution time105 // for all active processes associated with the job, as well as all terminated106 // processes no longer associated with the job, in 100-nanosecond ticks." and is safe107 // to extract108 let kernel: i64 =109 unsafe { job_object_info.TotalKernelTime.QuadPart() } / HUNDRED_NS_PER_MS;110 (user as f64 * 1e-6, kernel as f64 * 1e-6)111 } else {112 (0.0, 0.0)113 }114 }115}116117impl Drop for CPUTimer {118 fn drop(self: &mut Self) {119 // SAFETY: A valid job object got created in `start_suspended_process`120 unsafe { CloseHandle(self.job_object) };121 }122}