Skip to content
Myr

windows_timer.rs

This file

Path

src/timer/windows_timer.rs

126 lines · 4.8 KiB · Rust

Last changed by

Use windows-sys and fix feature flagClemens Wasserbefore adoptiond2fb7d4

History of this file

Take 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::util::units::Second;3132const HUNDRED_NS_PER_MS: i64 = 10;3334#[cfg(not(feature = "windows_process_extensions_main_thread_handle"))]35#[allow(non_upper_case_globals)]36static NtResumeProcess: Lazy<unsafe extern "system" fn(ProcessHandle: HANDLE) -> NTSTATUS> =37    Lazy::new(|| {38        // SAFETY: Getting the module handle for ntdll.dll is safe39        let ntdll = unsafe { GetModuleHandleW(w!("ntdll.dll")) };40        assert!(ntdll != 0, "GetModuleHandleW failed");4142        // SAFETY: The ntdll handle is valid43        let nt_resume_process = unsafe { GetProcAddress(ntdll, s!("NtResumeProcess")) };4445        // SAFETY: We transmute to the correct function signature46        unsafe { mem::transmute(nt_resume_process.unwrap()) }47    });4849pub struct CPUTimer {50    job_object: HANDLE,51}5253impl CPUTimer {54    pub unsafe fn start_suspended_process(child: &process::Child) -> Self {55        let child_handle = child.as_raw_handle() as HANDLE;5657        // SAFETY: Creating a new job object is safe58        let job_object = unsafe { CreateJobObjectW(ptr::null_mut(), ptr::null_mut()) };59        assert!(job_object != 0, "CreateJobObjectW failed");6061        // SAFETY: The job object handle is valid62        let ret = unsafe { AssignProcessToJobObject(job_object, child_handle) };63        assert!(ret != 0, "AssignProcessToJobObject failed");6465        #[cfg(feature = "windows_process_extensions_main_thread_handle")]66        {67            // SAFETY: The main thread handle is valid68            let ret = unsafe { ResumeThread(child.main_thread_handle().as_raw_handle() as HANDLE) };69            assert!(ret != u32::MAX, "ResumeThread failed");70        }7172        #[cfg(not(feature = "windows_process_extensions_main_thread_handle"))]73        {74            // Since we can't get the main thread handle on stable rust, we use75            // the undocumented but widely known `NtResumeProcess` function to76            // resume a process by it's handle.7778            // SAFETY: The process handle is valid79            let ret = unsafe { NtResumeProcess(child_handle) };80            assert!(ret == STATUS_SUCCESS, "NtResumeProcess failed");81        }8283        Self { job_object }84    }8586    pub fn stop(&self) -> (Second, Second) {87        let mut job_object_info =88            mem::MaybeUninit::<JOBOBJECT_BASIC_ACCOUNTING_INFORMATION>::uninit();8990        // SAFETY: A valid job object got created in `start_suspended_process`91        let res = unsafe {92            QueryInformationJobObject(93                self.job_object,94                JobObjectBasicAccountingInformation,95                job_object_info.as_mut_ptr().cast(),96                mem::size_of::<JOBOBJECT_BASIC_ACCOUNTING_INFORMATION>() as u32,97                ptr::null_mut(),98            )99        };100101        if res != 0 {102            // SAFETY: The job object info got correctly initialized103            let job_object_info = unsafe { job_object_info.assume_init() };104105            // The `TotalUserTime` is "The total amount of user-mode execution time for106            // all active processes associated with the job, as well as all terminated processes no107            // longer associated with the job, in 100-nanosecond ticks."108            let user: i64 = job_object_info.TotalUserTime / HUNDRED_NS_PER_MS;109110            // The `TotalKernelTime` is "The total amount of kernel-mode execution time111            // for all active processes associated with the job, as well as all terminated112            // processes no longer associated with the job, in 100-nanosecond ticks."113            let kernel: i64 = job_object_info.TotalKernelTime / HUNDRED_NS_PER_MS;114            (user as f64 * 1e-6, kernel as f64 * 1e-6)115        } else {116            (0.0, 0.0)117        }118    }119}120121impl Drop for CPUTimer {122    fn drop(&mut self) {123        // SAFETY: A valid job object got created in `start_suspended_process`124        unsafe { CloseHandle(self.job_object) };125    }126}