Skip to content
Myr

windows_timer.rs

This file

Path

src/timer/windows_timer.rs

124 lines · 4.7 KiB · Rust

Last changed by

Fix winapi type definition changeClemens Wasserbefore adoptionccda6c4

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 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        let child_handle = child.as_raw_handle().cast();5253        // SAFETY: Creating a new job object is safe54        let job_object = unsafe { CreateJobObjectW(ptr::null_mut(), ptr::null_mut()) };55        assert!(!job_object.is_null(), "CreateJobObjectW failed");5657        // SAFETY: The job object handle is valid58        let ret = unsafe { AssignProcessToJobObject(job_object, child_handle) };59        assert!(ret != 0, "AssignProcessToJobObject failed");6061        #[cfg(windows_process_extensions_main_thread_handle)]62        {63            // SAFETY: The main thread handle is valid64            let ret = unsafe { ResumeThread(child.main_thread_handle().as_raw_handle()) };65            assert!(ret != -1 as DWORD, "ResumeThread failed");66        }6768        #[cfg(not(windows_process_extensions_main_thread_handle))]69        {70            // Since we can't get the main thread handle on stable rust, we use71            // the undocumented but widely known `NtResumeProcess` function to72            // resume a process by it's handle.7374            // SAFETY: The process handle is valid75            let ret = unsafe { NtResumeProcess(child_handle) };76            assert!(ret == STATUS_SUCCESS, "NtResumeProcess failed");77        }7879        Self { job_object }80    }8182    pub fn stop(&self) -> (Second, Second) {83        let mut job_object_info =84            mem::MaybeUninit::<JOBOBJECT_BASIC_ACCOUNTING_INFORMATION>::uninit();8586        // SAFETY: A valid job object got created in `start_suspended_process`87        let res = unsafe {88            QueryInformationJobObject(89                self.job_object,90                JobObjectBasicAccountingInformation,91                job_object_info.as_mut_ptr().cast(),92                mem::size_of::<JOBOBJECT_BASIC_ACCOUNTING_INFORMATION>() as u32,93                ptr::null_mut(),94            )95        };9697        if res != 0 {98            // SAFETY: The job object info got correctly initialized99            let job_object_info = unsafe { job_object_info.assume_init() };100101            // SAFETY: The `TotalUserTime` is "The total amount of user-mode execution time for102            // all active processes associated with the job, as well as all terminated processes no103            // longer associated with the job, in 100-nanosecond ticks." and is safe to extract104            let user: i64 = unsafe { job_object_info.TotalUserTime.QuadPart() } / HUNDRED_NS_PER_MS;105106            // SAFETY: The `TotalKernelTime` is "The total amount of kernel-mode execution time107            // for all active processes associated with the job, as well as all terminated108            // processes no longer associated with the job, in 100-nanosecond ticks." and is safe109            // to extract110            let kernel: i64 =111                unsafe { job_object_info.TotalKernelTime.QuadPart() } / HUNDRED_NS_PER_MS;112            (user as f64 * 1e-6, kernel as f64 * 1e-6)113        } else {114            (0.0, 0.0)115        }116    }117}118119impl Drop for CPUTimer {120    fn drop(self: &mut Self) {121        // SAFETY: A valid job object got created in `start_suspended_process`122        unsafe { CloseHandle(self.job_object) };123    }124}