mapsample 0.1.0

In-process Windows x64 stack sampler with a rolling stall recorder, P/E-core placement readings, and an MSVC /MAP symbolizer
Documentation
//! Small Win32 helpers: owned handles, fault-safe memory reads, thread names and stacks.

use std::ffi::c_void;
use std::mem::size_of;
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
use std::ptr::null_mut;

use windows_sys::Wdk::System::Threading::NtQueryInformationThread;
use windows_sys::Win32::Foundation::{HANDLE, INVALID_HANDLE_VALUE, LocalFree, WAIT_OBJECT_0};
use windows_sys::Win32::System::Diagnostics::Debug::ReadProcessMemory;
use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleW, GetProcAddress};
use windows_sys::Win32::System::Threading::{
    GetCurrentProcess, GetThreadDescription, WaitForSingleObject,
};

/// `TEB.NtTib.StackBase`, `TEB.NtTib.StackLimit` and `TEB.DeallocationStack` (x64).
const TEB_STACK_BASE: u64 = 0x08;
const TEB_STACK_LIMIT: u64 = 0x10;
const TEB_DEALLOCATION_STACK: u64 = 0x1478;

/// Take ownership of a handle an API just returned; `None` for null and
/// `INVALID_HANDLE_VALUE`.
///
/// # Safety
/// `raw` must be null, `INVALID_HANDLE_VALUE`, or an open handle that the caller owns and
/// that nothing else will close.
pub(super) unsafe fn owned(raw: HANDLE) -> Option<OwnedHandle> {
    if raw.is_null() || raw == INVALID_HANDLE_VALUE {
        return None;
    }
    // SAFETY: the caller hands over an open, owned handle (checked not null or invalid).
    Some(unsafe { OwnedHandle::from_raw_handle(raw) })
}

/// The raw value of an owned handle, valid while `handle` lives.
pub(super) fn raw(handle: &OwnedHandle) -> HANDLE {
    handle.as_raw_handle()
}

/// Whether the thread behind `handle` (opened with `SYNCHRONIZE`) has exited. An exited
/// thread runs no more user-mode code, APCs included.
pub(super) fn has_exited(handle: HANDLE) -> bool {
    // SAFETY: a zero timeout only polls the object; an invalid handle makes the call fail.
    unsafe { WaitForSingleObject(handle, 0) == WAIT_OBJECT_0 }
}

/// Copy up to `len` bytes of this process at `address` into `dst`, returning how many were
/// read. A fault-safe system call: a bad address fails instead of faulting. Allocation-free,
/// lock-free (in user mode) and panic-free, so it may run while a thread is paused.
///
/// # Safety
/// `dst` must be valid for writes of `len` bytes.
pub(super) unsafe fn read_into(address: u64, dst: *mut u8, len: usize) -> usize {
    let mut read = 0_usize;
    // SAFETY: the caller guarantees `dst` holds `len` writable bytes; the source is only
    // read by the kernel, which checks it; the current-process pseudo-handle is always valid.
    let ok = unsafe {
        ReadProcessMemory(
            GetCurrentProcess(),
            address as *const c_void,
            dst.cast::<c_void>(),
            len,
            &raw mut read,
        )
    };
    // A partial copy fails with ERROR_PARTIAL_COPY but still reports what it read.
    if ok == 0 { read.min(len) } else { len }
}

/// Eight bytes of this process at `address`, if readable. Fault-safe (see [`read_into`]).
pub(super) fn read_u64(address: u64) -> Option<u64> {
    let mut value = 0_u64;
    // SAFETY: `value` is 8 writable bytes.
    let read = unsafe { read_into(address, (&raw mut value).cast::<u8>(), size_of::<u64>()) };
    (read == size_of::<u64>()).then_some(value)
}

/// `THREAD_BASIC_INFORMATION`, class 0 of `NtQueryInformationThread`.
#[repr(C)]
struct ThreadBasicInformation {
    exit_status: i32,
    teb: *mut c_void,
    process: usize,
    thread: usize,
    affinity: usize,
    priority: i32,
    base_priority: i32,
}

/// The address of a thread's TEB.
pub(super) fn teb(handle: HANDLE) -> Option<u64> {
    let mut info = ThreadBasicInformation {
        exit_status: 0,
        teb: null_mut(),
        process: 0,
        thread: 0,
        affinity: 0,
        priority: 0,
        base_priority: 0,
    };
    let size = u32::try_from(size_of::<ThreadBasicInformation>()).ok()?;
    // SAFETY: `info` is writable and its exact size is passed; class 0 is
    // ThreadBasicInformation, whose layout `ThreadBasicInformation` mirrors; `handle` is a
    // thread handle with query rights (a bad one fails the call).
    let status = unsafe {
        NtQueryInformationThread(
            handle,
            0,
            (&raw mut info).cast::<c_void>(),
            size,
            null_mut(),
        )
    };
    (status >= 0 && !info.teb.is_null()).then_some(info.teb as u64)
}

/// The bounds `[low, high)` of a thread's stack, read from its TEB with fault-safe reads.
/// Allocation-, lock- and panic-free, so it may run while the thread is paused (a fiber
/// switch moves the bounds, so they are read again when the stack pointer leaves them).
pub(super) fn stack_bounds(teb: u64) -> Option<(u64, u64)> {
    let high = read_u64(teb.checked_add(TEB_STACK_BASE)?)?;
    let committed = read_u64(teb.checked_add(TEB_STACK_LIMIT)?)?;
    let reserved = read_u64(teb.checked_add(TEB_DEALLOCATION_STACK)?)?;
    // The committed limit moves as the stack grows; the allocation base does not.
    let low = if reserved != 0 && reserved < high {
        reserved
    } else {
        committed
    };
    (low != 0 && low < high && high.trailing_zeros() >= 3).then_some((low, high))
}

/// Frees a `GetThreadDescription` string on every path.
struct LocalString(*mut u16);

impl Drop for LocalString {
    fn drop(&mut self) {
        // SAFETY: the pointer came from `GetThreadDescription`, which documents `LocalFree`,
        // and is freed once.
        unsafe { LocalFree(self.0.cast::<c_void>()) };
    }
}

/// A thread's description (the name Rust's `thread::Builder` sets); empty if none.
pub(super) fn thread_name(handle: HANDLE) -> String {
    let mut wide: *mut u16 = null_mut();
    // SAFETY: `handle` has THREAD_QUERY_LIMITED_INFORMATION and `wide` is a writable
    // out-pointer; on success it receives a NUL-terminated string the caller frees.
    let result = unsafe { GetThreadDescription(handle, &raw mut wide) };
    if result < 0 || wide.is_null() {
        return String::new();
    }
    let owner = LocalString(wide);
    let mut length = 0_usize;
    // SAFETY: the string is NUL-terminated, so every unit up to and including the NUL is
    // readable; the scan stops at the NUL or after 4,096 units.
    while length < 4096 && unsafe { *owner.0.add(length) } != 0 {
        length += 1;
    }
    // SAFETY: the `length` units before the NUL are initialized and live until `owner` drops.
    let units = unsafe { std::slice::from_raw_parts(owner.0, length) };
    String::from_utf16_lossy(units)
}

/// An export of a module that is always loaded (`kernel32.dll`, `ntdll.dll`).
pub(super) fn export(
    module: &str,
    name: &std::ffi::CStr,
) -> Option<unsafe extern "system" fn() -> isize> {
    let wide: Vec<u16> = module.encode_utf16().chain(Some(0)).collect();
    // SAFETY: a NUL-terminated wide string; no reference count is taken.
    let handle = unsafe { GetModuleHandleW(wide.as_ptr()) };
    if handle.is_null() {
        return None;
    }
    // SAFETY: `handle` is a loaded module and `name` is NUL-terminated.
    unsafe { GetProcAddress(handle, name.as_ptr().cast()) }
}