Skip to content
peakoshiPublic

About

In-process Windows x64 stack sampler with rolling stall recorder, P/E-core placement, and MSVC /MAP symbolizer

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

mapsample

crates.io docs.rs CI

An in-process stack sampler for Windows x64, with a rolling stall recorder, processor placement readings, and an MSVC /MAP symbolizer that runs on any host.

  • Sampling. One thread pauses the matching threads of your own process up to 2,000 times a second, copies their stacks, resumes them, and unwinds the copies with the x64 unwind data the images already carry, using its own unwinder in safe Rust. It needs no administrator rights, no ETW session, no PDB files and no debug help library. Each sample is on-CPU or waiting (#wait), judged from the thread's cycle counter.
  • Stall recording. The last seconds of samples are always kept in a ring. When a frame hitches or a watchdog fires, Sampler::dump_recent or a DumpHandle writes the window that led up to it. A request accepted before Sampler::stop is written before stop returns.
  • Placement. On Windows 11 the sampler can also ask each thread which logical processor it runs on, with a special user-mode APC, to see time on efficiency cores, migrations between cores, and threads sharing a physical core. Each watched thread is read on its own, even when several share a name.
  • Symbolizing. Frames are recorded as module+0xRVA. The mapsample symbolize command (or mapsample::symbolize) names them from the linker map of the same build, demangling Rust names, on Linux, macOS or Windows.

The output is folded stacks (thread;root;...;leaf count), which every flame graph tool reads, plus a text report of the hottest leaves and functions per thread.

Usage

[dependencies]
mapsample = "0.1"
use mapsample::{Config, PlacementMode, Sampler, Window};
use std::path::Path;

fn main() -> Result<(), mapsample::Error> {
    // Threads whose names contain "worker" or "render", 1,000 samples a second.
    let config = Config::parse("worker,render:1000")?
        .with_window(Window::parse("2-30")?) // seconds 2 to 30 after start
        .with_placement(PlacementMode::WithSamples)
        .with_highlight_threads(["render"]);
    let sampler = Sampler::start(config)?;

    // A watchdog can keep a handle and ask for the last few seconds when a stall shows up.
    let watchdog = sampler.dump_handle();
    std::thread::spawn(move || {
        // ... on a stall:
        let _ = watchdog.request(Path::new("stalls"), "stall-1", 3.0);
    });

    // ... run the workload ...

    let profile = sampler.stop()?;
    // samples.folded, samples.txt, samples.modules.txt
    profile.write_to(Path::new("."))?;
    println!("{}", profile.report());
    Ok(())
}

Sampler::from_env() reads the configuration from the environment, so a build can carry the sampler and turn it on without a rebuild:

  • MAPSAMPLE: the spec, <name substring[,substring...] or *>[:hz], for example worker,render:1000 or *. Unset or blank leaves the sampler off.
  • MAPSAMPLE_WINDOW: <start>-<end> in seconds after start, for example 5-20.
  • MAPSAMPLE_PLACEMENT: 0 (off), 1 (readings and samples) or only (readings only, no thread is paused).
  • MAPSAMPLE_HIGHLIGHT: comma-separated thread name substrings always shown in the placement report.

Config::from_env_prefix("MYAPP") reads MYAPP, MYAPP_WINDOW and so on instead.

Command line

cargo install mapsample
mapsample symbolize samples.folded app.map --top 40

This writes samples.named.folded (feed it to a flame graph tool) and samples.flat.txt (self and inclusive time per function) next to the folded file. --module names the module the map describes when it is not <map stem>.exe. Link with /MAP (in Rust, -C link-arg=/MAP) to get the map.

Platforms

The library and the command build and run everywhere. Recording needs Windows on x86-64: elsewhere Sampler::start returns Error::UnsupportedPlatform, while profiles, rings, reports, /MAP parsing and symbolizing work as usual. Placement readings need QueueUserAPC2, which arrived in Windows 11; on older systems the placement section says why it is missing. Only one sampler runs per process.

Safety

The Windows backend uses unsafe for Win32 calls only, and every block states why it holds. The rules it follows:

  • While a thread is paused the sampler allocates nothing, takes no lock and cannot panic, since the paused thread may hold the heap lock or any other. A guard resumes it on every path.
  • The stack is copied under the pause with a fault-safe read (ReadProcessMemory). After the thread runs again the copy is unwound by an x64 unwinder written in safe Rust: it reads the stack only from the copied bytes, so a frame that would read outside them stops the walk. No system unwinder reads memory on its behalf.
  • Each module a walk enters is pinned with a counted GetModuleHandleExW reference until the walk ends, and the module handle that call returns is its loaded base. Its PE header is read first, from that base with ReadProcessMemory: one page, or as many bytes as its own DOS and COFF fields say the section table needs. Every later read (function table, unwind codes, epilog bytes) also goes through ReadProcessMemory and stays inside the size and readable ranges that header names, so a module unloading during a walk is never read after it is gone.
  • Every handle is owned and closed by a guard. A thread whose handle shows it exited is dropped even when Windows reuses its id, a thread id found by a system snapshot is checked to belong to this process before it is used, and no thread is skipped on the strength of its id alone.
  • Placement APCs write only to a static table of atomics. A slot is not reused while an APC aimed at it may still run, its thread handle is kept until the APC ran or the thread exited, and a slot forgets its last reading before another thread leases it, so stopping or dropping the sampler cannot leave an APC writing into freed memory or a reading credited to the wrong thread.
  • The module holding the APC routine and its table is pinned for the life of the process before the first APC is queued, so a queued APC can never run in an unloaded DLL. If the pin fails, no APC is queued and the placement section says why.

Sampling pauses the threads it watches for a few microseconds at a time, so expect some overhead at high rates. At 500 Hz and above the sampler thread keeps about one core busy to hold its pace.

Testing

cargo test

On Windows x64 this includes live tests that sample the test process itself.

License

Licensed under either of

at your option.

About

In-process Windows x64 stack sampler with rolling stall recorder, P/E-core placement, and MSVC /MAP symbolizer

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages