Skip to content
Myr

windows_timer.rs

This file

Path

src/timer/windows_timer.rs

131 lines · 5.0 KiB · Rust

Last changed by

Merge pull request #790 from sharkdp/new-metricsDavid Peterbefore adoptionf26c015

History of this file

Take it

1#![cfg(windows)]2#![warn(unsafe_op_in_unsafe_fn)]34use std::process::{self, Child, ExitStatus};5use std::{mem, os::windows::io::AsRawHandle, ptr};67use anyhow::Result;89use windows_sys::Win32::{10    Foundation::{CloseHandle, HANDLE},11    System::JobObjects::{12        AssignProcessToJobObject, CreateJobObjectW, JobObjectBasicAccountingInformation,13        QueryInformationJobObject, JOBOBJECT_BASIC_ACCOUNTING_INFORMATION,14    },15};1617#[cfg(feature = "windows_process_extensions_main_thread_handle")]18use std::os::windows::process::ChildExt;19#[cfg(feature = "windows_process_extensions_main_thread_handle")]20use windows_sys::Win32::System::Threading::ResumeThread;2122#[cfg(not(feature = "windows_process_extensions_main_thread_handle"))]23use once_cell::sync::Lazy;24#[cfg(not(feature = "windows_process_extensions_main_thread_handle"))]25use windows_sys::{26    s, w,27    Win32::{28        Foundation::{NTSTATUS, STATUS_SUCCESS},29        System::LibraryLoader::{GetModuleHandleW, GetProcAddress},30    },31};3233use crate::quantity::{nanosecond, Information, Time, Zero};3435#[cfg(not(feature = "windows_process_extensions_main_thread_handle"))]36#[allow(non_upper_case_globals)]37static NtResumeProcess: Lazy<unsafe extern "system" fn(process_handle: HANDLE) -> NTSTATUS> =38    Lazy::new(|| {39        // SAFETY: Getting the module handle for ntdll.dll is safe40        let ntdll = unsafe { GetModuleHandleW(w!("ntdll.dll")) };41        assert!(!ntdll.is_null(), "GetModuleHandleW failed");4243        // SAFETY: The ntdll handle is valid44        let nt_resume_process = unsafe { GetProcAddress(ntdll, s!("NtResumeProcess")) };4546        // SAFETY: We transmute to the correct function signature47        unsafe { mem::transmute(nt_resume_process.unwrap()) }48    });4950pub struct CPUTimer {51    job_object: HANDLE,52}5354impl CPUTimer {55    pub unsafe fn start_suspended_process(child: &process::Child) -> Self {56        let child_handle = child.as_raw_handle() as HANDLE;5758        // SAFETY: Creating a new job object is safe59        let job_object = unsafe { CreateJobObjectW(ptr::null_mut(), ptr::null_mut()) };60        assert!(!job_object.is_null(), "CreateJobObjectW failed");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, mut child: Child) -> Result<(Time, Time, Option<Information>, ExitStatus)> {88        let status = child.wait()?;8990        let mut job_object_info =91            mem::MaybeUninit::<JOBOBJECT_BASIC_ACCOUNTING_INFORMATION>::uninit();9293        // SAFETY: A valid job object got created in `start_suspended_process`94        let res = unsafe {95            QueryInformationJobObject(96                self.job_object,97                JobObjectBasicAccountingInformation,98                job_object_info.as_mut_ptr().cast(),99                mem::size_of::<JOBOBJECT_BASIC_ACCOUNTING_INFORMATION>() as u32,100                ptr::null_mut(),101            )102        };103104        if res != 0 {105            // SAFETY: The job object info got correctly initialized106            let job_object_info = unsafe { job_object_info.assume_init() };107108            // The `TotalUserTime` is "The total amount of user-mode execution time for109            // all active processes associated with the job, as well as all terminated processes no110            // longer associated with the job, in 100-nanosecond ticks."111            let user_time = Time::new::<nanosecond>((job_object_info.TotalUserTime as f64) * 100.0);112113            // The `TotalKernelTime` is "The total amount of kernel-mode execution time114            // for all active processes associated with the job, as well as all terminated115            // processes no longer associated with the job, in 100-nanosecond ticks."116            let system_time =117                Time::new::<nanosecond>((job_object_info.TotalKernelTime as f64) * 100.0);118119            Ok((user_time, system_time, None, status))120        } else {121            Ok((Time::zero(), Time::zero(), None, status))122        }123    }124}125126impl Drop for CPUTimer {127    fn drop(&mut self) {128        // SAFETY: A valid job object got created in `start_suspended_process`129        unsafe { CloseHandle(self.job_object) };130    }131}