windows_timer.rs
This file
Path
src/timer/windows_timer.rs
128 lines · 4.9 KiB · Rust
Last changed by
Merge pull request #964 from sharkdp/codex/windows-timer-precisionDavid Peterbefore adoption1c1be47
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 windows_sys::Win32::{7 Foundation::{CloseHandle, HANDLE},8 System::JobObjects::{9 AssignProcessToJobObject, CreateJobObjectW, JobObjectBasicAccountingInformation,10 QueryInformationJobObject, JOBOBJECT_BASIC_ACCOUNTING_INFORMATION,11 },12};1314#[cfg(feature = "windows_process_extensions_main_thread_handle")]15use std::os::windows::process::ChildExt;16#[cfg(feature = "windows_process_extensions_main_thread_handle")]17use windows_sys::Win32::System::Threading::ResumeThread;1819#[cfg(not(feature = "windows_process_extensions_main_thread_handle"))]20use once_cell::sync::Lazy;21#[cfg(not(feature = "windows_process_extensions_main_thread_handle"))]22use windows_sys::{23 s, w,24 Win32::{25 Foundation::{NTSTATUS, STATUS_SUCCESS},26 System::LibraryLoader::{GetModuleHandleW, GetProcAddress},27 },28};2930use crate::quantity::{nanosecond, Information, Time, Zero};3132#[cfg(not(feature = "windows_process_extensions_main_thread_handle"))]33#[allow(non_upper_case_globals)]34static NtResumeProcess: Lazy<unsafe extern "system" fn(ProcessHandle: HANDLE) -> NTSTATUS> =35 Lazy::new(|| {36 // SAFETY: Getting the module handle for ntdll.dll is safe37 let ntdll = unsafe { GetModuleHandleW(w!("ntdll.dll")) };38 assert!(ntdll != std::ptr::null_mut(), "GetModuleHandleW failed");3940 // SAFETY: The ntdll handle is valid41 let nt_resume_process = unsafe { GetProcAddress(ntdll, s!("NtResumeProcess")) };4243 // SAFETY: We transmute to the correct function signature44 unsafe { mem::transmute(nt_resume_process.unwrap()) }45 });4647pub struct CPUTimer {48 job_object: HANDLE,49}5051impl CPUTimer {52 pub unsafe fn start_suspended_process(child: &process::Child) -> Self {53 let child_handle = child.as_raw_handle() as HANDLE;5455 // SAFETY: Creating a new job object is safe56 let job_object = unsafe { CreateJobObjectW(ptr::null_mut(), ptr::null_mut()) };57 assert!(58 job_object != std::ptr::null_mut(),59 "CreateJobObjectW failed"60 );6162 // SAFETY: The job object handle is valid63 let ret = unsafe { AssignProcessToJobObject(job_object, child_handle) };64 assert!(ret != 0, "AssignProcessToJobObject failed");6566 #[cfg(feature = "windows_process_extensions_main_thread_handle")]67 {68 // SAFETY: The main thread handle is valid69 let ret = unsafe { ResumeThread(child.main_thread_handle().as_raw_handle() as HANDLE) };70 assert!(ret != u32::MAX, "ResumeThread failed");71 }7273 #[cfg(not(feature = "windows_process_extensions_main_thread_handle"))]74 {75 // Since we can't get the main thread handle on stable rust, we use76 // the undocumented but widely known `NtResumeProcess` function to77 // resume a process by it's handle.7879 // SAFETY: The process handle is valid80 let ret = unsafe { NtResumeProcess(child_handle) };81 assert!(ret == STATUS_SUCCESS, "NtResumeProcess failed");82 }8384 Self { job_object }85 }8687 pub fn stop(&self) -> (Time, Time, Information) {88 let mut job_object_info =89 mem::MaybeUninit::<JOBOBJECT_BASIC_ACCOUNTING_INFORMATION>::uninit();9091 // SAFETY: A valid job object got created in `start_suspended_process`92 let res = unsafe {93 QueryInformationJobObject(94 self.job_object,95 JobObjectBasicAccountingInformation,96 job_object_info.as_mut_ptr().cast(),97 mem::size_of::<JOBOBJECT_BASIC_ACCOUNTING_INFORMATION>() as u32,98 ptr::null_mut(),99 )100 };101102 if res != 0 {103 // SAFETY: The job object info got correctly initialized104 let job_object_info = unsafe { job_object_info.assume_init() };105106 // The `TotalUserTime` is "The total amount of user-mode execution time for107 // all active processes associated with the job, as well as all terminated processes no108 // longer associated with the job, in 100-nanosecond ticks."109 let user_time = Time::new::<nanosecond>((job_object_info.TotalUserTime as f64) * 100.0);110111 // The `TotalKernelTime` is "The total amount of kernel-mode execution time112 // for all active processes associated with the job, as well as all terminated113 // processes no longer associated with the job, in 100-nanosecond ticks."114 let system_time =115 Time::new::<nanosecond>((job_object_info.TotalKernelTime as f64) * 100.0);116 (user_time, system_time, Information::zero())117 } else {118 (Time::zero(), Time::zero(), Information::zero())119 }120 }121}122123impl Drop for CPUTimer {124 fn drop(&mut self) {125 // SAFETY: A valid job object got created in `start_suspended_process`126 unsafe { CloseHandle(self.job_object) };127 }128}