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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
//! The Windows x64 backend: finding threads and modules, the sampling loop, pacing.

#![allow(unsafe_code)]

mod apc;
mod capture;
mod sys;

use std::collections::HashSet;
use std::mem::size_of;
use std::os::windows::io::OwnedHandle;
use std::ptr::{null, null_mut};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};

use windows_sys::Win32::Foundation::{HANDLE, WAIT_OBJECT_0};
use windows_sys::Win32::System::Diagnostics::ToolHelp::{
    CreateToolhelp32Snapshot, MODULEENTRY32W, Module32FirstW, Module32NextW, TH32CS_SNAPMODULE,
    TH32CS_SNAPMODULE32, TH32CS_SNAPTHREAD, THREADENTRY32, Thread32First, Thread32Next,
};
use windows_sys::Win32::System::Threading::{
    CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, CreateWaitableTimerExW, GetCurrentProcess,
    GetCurrentProcessId, GetCurrentThread, GetCurrentThreadId, GetProcessIdOfThread, GetThreadId,
    OpenThread, SetThreadPriority, SetWaitableTimer, THREAD_GET_CONTEXT,
    THREAD_PRIORITY_ABOVE_NORMAL, THREAD_QUERY_INFORMATION, THREAD_QUERY_LIMITED_INFORMATION,
    THREAD_SET_CONTEXT, THREAD_SUSPEND_RESUME, THREAD_SYNCHRONIZE, TIMER_ALL_ACCESS,
    WaitForSingleObject,
};

use capture::{Capture, Outcome, StackInfo, Unwinder};

use crate::sampler::{DumpRequest, Shared, serve_dumps};
use crate::{Config, MAX_FRAMES, Module, Placement, PlacementMode, Profile, Ring, Stats};

/// How often the thread and module lists are refreshed.
const RESCAN: Duration = Duration::from_millis(250);
/// A sample is on-CPU when the cycle rate since the previous sample reached this part of the
/// best rate seen.
const BUSY_FRACTION: f64 = 0.5;
/// Pauses shorter than this say nothing about the rate.
const MIN_RATE_WINDOW: Duration = Duration::from_micros(200);

/// A thread being watched.
pub(super) struct Target {
    tid: u32,
    /// The thread's label in the profile.
    name: String,
    /// Always `Some` until the target drops (then it may move to a placement slot).
    handle: Option<OwnedHandle>,
    /// The raw value of `handle`.
    raw: HANDLE,
    /// Index in the profile's thread list.
    thread: usize,
    stack: StackInfo,
    /// The cycle counter and time of the previous sample.
    last: Option<(u64, Instant)>,
    dead: bool,
    /// Placement: the leased slot, the sequence number last read, the cycle counter at the
    /// previous placement pass.
    slot: Option<usize>,
    seen: u64,
    place_cycles: Option<u64>,
    /// Index in the placement's thread list, once read: one per thread lifetime, so threads
    /// sharing a name are told apart.
    placed: Option<usize>,
}

impl Drop for Target {
    fn drop(&mut self) {
        if let (Some(index), Some(handle)) = (self.slot.take(), self.handle.take()) {
            apc::release(index, handle);
        }
        // Otherwise the OwnedHandle closes itself.
    }
}

/// Handles to every thread of this process (opened with `access`), with their ids.
fn open_threads(access: u32) -> Vec<(u32, OwnedHandle)> {
    /// `ntdll!NtGetNextThread`.
    type GetNextThread =
        unsafe extern "system" fn(HANDLE, HANDLE, u32, u32, u32, *mut HANDLE) -> i32;
    let mut threads: Vec<(u32, OwnedHandle)> = Vec::new();
    if let Some(address) = sys::export("ntdll.dll", c"NtGetNextThread") {
        // SAFETY: ntdll exports NtGetNextThread(process, previous thread, access, attributes,
        // flags, out handle) -> NTSTATUS with the system calling convention (since Windows
        // Vista); function pointers have one size.
        let next_thread = unsafe {
            std::mem::transmute::<unsafe extern "system" fn() -> isize, GetNextThread>(address)
        };
        let mut previous: HANDLE = null_mut();
        loop {
            let mut next: HANDLE = null_mut();
            // SAFETY: the current-process pseudo-handle; `previous` is null or a handle this
            // loop got and still owns (in `threads`); `next` is a writable out-pointer.
            let status =
                unsafe { next_thread(GetCurrentProcess(), previous, access, 0, 0, &raw mut next) };
            // SAFETY: on success `next` is a new handle the caller owns.
            let Some(handle) = (status >= 0).then(|| unsafe { sys::owned(next) }).flatten() else {
                break;
            };
            previous = sys::raw(&handle);
            // SAFETY: a valid thread handle.
            let tid = unsafe { GetThreadId(previous) };
            threads.push((tid, handle));
        }
        return threads;
    }
    // SAFETY: no arguments.
    let pid = unsafe { GetCurrentProcessId() };
    for tid in snapshot_thread_ids() {
        // SAFETY: opens a thread by id; null on failure, else a handle we own.
        let Some(handle) = (unsafe { sys::owned(OpenThread(access, 0, tid)) }) else {
            continue;
        };
        // The id may have been reused by a thread of another process since the snapshot.
        // SAFETY: a valid thread handle with THREAD_QUERY_LIMITED_INFORMATION.
        if unsafe { GetProcessIdOfThread(sys::raw(&handle)) } == pid {
            threads.push((tid, handle));
        }
    }
    threads
}

/// The ids of this process's threads from a Toolhelp snapshot of the whole system (tens of
/// milliseconds on a busy machine: the fallback).
fn snapshot_thread_ids() -> Vec<u32> {
    let mut ids = Vec::new();
    // SAFETY: a thread snapshot of the whole system; INVALID_HANDLE_VALUE on failure, else a
    // handle we own.
    let Some(snapshot) = (unsafe { sys::owned(CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0)) })
    else {
        return ids;
    };
    // SAFETY: all-zero is a valid THREADENTRY32 (integers only).
    let mut entry: THREADENTRY32 = unsafe { std::mem::zeroed() };
    entry.dwSize = u32::try_from(size_of::<THREADENTRY32>()).unwrap_or(0);
    // SAFETY: no arguments.
    let pid = unsafe { GetCurrentProcessId() };
    // SAFETY: a valid snapshot handle and a writable entry with `dwSize` set.
    let mut more = unsafe { Thread32First(sys::raw(&snapshot), &raw mut entry) } != 0;
    while more {
        if entry.th32OwnerProcessID == pid {
            ids.push(entry.th32ThreadID);
        }
        // SAFETY: as above.
        more = unsafe { Thread32Next(sys::raw(&snapshot), &raw mut entry) } != 0;
    }
    ids
}

fn wide_to_string(wide: &[u16]) -> String {
    let end = wide
        .iter()
        .position(|&unit| unit == 0)
        .unwrap_or(wide.len());
    String::from_utf16_lossy(wide.get(..end).unwrap_or_default())
}

/// The modules loaded now (empty if the snapshot keeps failing).
fn modules() -> Vec<Module> {
    let mut found = Vec::new();
    for _ in 0..5 {
        // SAFETY: a module snapshot of this process (id 0); INVALID_HANDLE_VALUE on failure
        // (ERROR_BAD_LENGTH while modules load), else a handle we own.
        let Some(snapshot) = (unsafe {
            sys::owned(CreateToolhelp32Snapshot(
                TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32,
                0,
            ))
        }) else {
            std::thread::sleep(Duration::from_millis(5));
            continue;
        };
        // SAFETY: all-zero is a valid MODULEENTRY32W (integers, arrays, a null pointer).
        let mut entry: MODULEENTRY32W = unsafe { std::mem::zeroed() };
        entry.dwSize = u32::try_from(size_of::<MODULEENTRY32W>()).unwrap_or(0);
        // SAFETY: a valid snapshot handle and a writable entry with `dwSize` set.
        let mut more = unsafe { Module32FirstW(sys::raw(&snapshot), &raw mut entry) } != 0;
        while more {
            found.push(Module {
                name: wide_to_string(&entry.szModule),
                path: wide_to_string(&entry.szExePath),
                base: entry.modBaseAddr as u64,
                size: u64::from(entry.modBaseSize),
            });
            // SAFETY: as above.
            more = unsafe { Module32NextW(sys::raw(&snapshot), &raw mut entry) } != 0;
        }
        break;
    }
    found
}

/// Add the new threads that match, drop the ones that left.
///
/// Every thread that is not a target has its name read again on each scan (a name may be set
/// or changed late, and an id may be reused by a new thread); no verdict is cached by id. A
/// target whose own handle shows it exited is dropped even if its id was reused.
fn refresh(
    config: &Config,
    access: u32,
    profile: &mut Profile,
    targets: &mut Vec<Target>,
    own: u32,
) {
    let threads = open_threads(access);
    let alive: HashSet<u32> = threads.iter().map(|(tid, _)| *tid).collect();
    targets.retain(|target| {
        !target.dead && alive.contains(&target.tid) && !sys::has_exited(target.raw)
    });
    for (tid, handle) in threads {
        if tid == own || targets.iter().any(|t| t.tid == tid) {
            continue;
        }
        let raw = sys::raw(&handle);
        let name = sys::thread_name(raw);
        if !config.matches(&name) {
            continue;
        }
        let label = if name.is_empty() {
            format!("tid{tid}")
        } else {
            name
        };
        let teb = sys::teb(raw);
        targets.push(Target {
            tid,
            thread: profile.thread_id(&label),
            name: label,
            handle: Some(handle),
            raw,
            stack: StackInfo {
                teb,
                bounds: teb.and_then(sys::stack_bounds),
            },
            last: None,
            dead: false,
            slot: None,
            seen: 0,
            place_cycles: None,
            placed: None,
        });
    }
}

/// Merge `found` into `known` (a module that unloaded stays known, for labels).
fn merge_modules(known: &mut Vec<Module>, found: &[Module]) {
    for module in found {
        if !known.iter().any(|old| {
            old.base == module.base && old.size == module.size && old.name == module.name
        }) {
            known.push(module.clone());
        }
    }
    known.sort_by_key(|module| module.base);
}

/// A high-resolution waitable timer, or none (then the sampler sleeps).
struct Pacer(Option<OwnedHandle>);

impl Pacer {
    fn new() -> Self {
        // SAFETY: no security attributes and no name; null on failure, else a handle we own.
        Self(unsafe {
            sys::owned(CreateWaitableTimerExW(
                null(),
                null(),
                CREATE_WAITABLE_TIMER_HIGH_RESOLUTION,
                TIMER_ALL_ACCESS,
            ))
        })
    }

    /// Wait until `deadline` or `stop`: the timer in slices of at most 50 ms, then a spin for
    /// the last 2 ms (a timer wakes 0.5 to 1 ms late, too coarse for 1 kHz; at 500 Hz and
    /// above the sampler thread therefore keeps about one core busy).
    fn wait_until(&self, deadline: Instant, stop: &AtomicBool) {
        const SPIN: Duration = Duration::from_millis(2);
        loop {
            let now = Instant::now();
            if now >= deadline || stop.load(Ordering::Acquire) {
                return;
            }
            let remaining = deadline - now;
            if remaining <= SPIN {
                std::thread::yield_now();
                continue;
            }
            let slice = remaining
                .saturating_sub(SPIN)
                .min(Duration::from_millis(50));
            let Some(timer) = &self.0 else {
                std::thread::sleep(slice);
                continue;
            };
            // Relative due time in 100 ns units, negative.
            let due = -i64::try_from(slice.as_nanos() / 100)
                .unwrap_or(i64::MAX)
                .max(1);
            // SAFETY: a valid timer handle; `due` outlives the call; no completion routine and
            // no resume of a suspended system.
            let armed =
                unsafe { SetWaitableTimer(sys::raw(timer), &raw const due, 0, None, null(), 0) }
                    != 0;
            // SAFETY: a valid handle; the wait is bounded (the timer fires within `slice`).
            if !armed || unsafe { WaitForSingleObject(sys::raw(timer), 100) } != WAIT_OBJECT_0 {
                std::thread::sleep(slice);
            }
        }
    }
}

/// Classify a sample as on-CPU from the thread's cycle counter.
fn on_cpu(target: &mut Target, cycles: Option<u64>, at: Instant, best_rate: &mut f64) -> bool {
    let mut running = true;
    if let Some(cycles) = cycles {
        if let Some((last_cycles, last_time)) = target.last {
            let window = at.saturating_duration_since(last_time);
            if window >= MIN_RATE_WINDOW {
                let rate = cycles.saturating_sub(last_cycles) as f64 / window.as_secs_f64();
                *best_rate = best_rate.max(rate);
                running = rate >= *best_rate * BUSY_FRACTION;
            }
        }
        target.last = Some((cycles, at));
    }
    running
}

/// Write the dumps `requests` ask for from `ring` (second `now` is the current one).
fn serve(
    requests: Vec<DumpRequest>,
    ring: &Ring,
    now: u64,
    stats: Stats,
    known: &[Module],
    profile: &mut Profile,
) {
    if requests.is_empty() {
        return;
    }
    let mut template = Profile::new(&profile.spec, profile.hz);
    template.stats = stats;
    template.set_modules(known.to_vec());
    serve_dumps(requests, ring, now, &template, &mut profile.dump_errors);
}

/// The sampler thread's body.
pub(crate) fn run(config: &Config, shared: &Shared) -> Profile {
    let mut profile = Profile::new(config.spec(), config.hz());
    // SAFETY: the pseudo-handle of the current thread; a higher priority keeps the pacing
    // steady on a busy machine.
    unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL) };
    // SAFETY: no arguments.
    let own = unsafe { GetCurrentThreadId() };
    let sampling = config.placement() != PlacementMode::Only;
    let mut access =
        THREAD_QUERY_INFORMATION | THREAD_QUERY_LIMITED_INFORMATION | THREAD_SYNCHRONIZE;
    if sampling {
        access |= THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT;
    }
    if config.placement() != PlacementMode::Off {
        access |= THREAD_SET_CONTEXT;
    }
    let period = Duration::from_secs_f64(1.0 / f64::from(config.hz().max(1)));
    let timer = Pacer::new();
    let started = Instant::now();
    let mut targets: Vec<Target> = Vec::new();
    let mut known = Vec::new();
    merge_modules(&mut known, &modules());
    let mut next_scan = started;
    let mut deadline = started;
    let mut best_rate = 0.0_f64;
    let mut stats = Stats::default();
    let mut ring = Ring::new(config.ring_seconds());
    let mut capture = Capture::new();
    let mut unwinder = Unwinder::default();
    let mut frames = [0_u64; MAX_FRAMES];
    let mut placer = None;
    let mut unavailable = None;
    if config.placement() != PlacementMode::Off {
        match apc::Placer::new(config) {
            Ok(new) => placer = Some(new),
            Err(reason) => unavailable = Some(reason),
        }
    }
    while !shared.stopping() {
        let now = Instant::now();
        if now >= next_scan {
            refresh(config, access, &mut profile, &mut targets, own);
            merge_modules(&mut known, &modules());
            if let Some(placer) = placer.as_mut() {
                placer.assign(&mut targets);
            }
            stats.scanning += now.elapsed();
            next_scan = now + RESCAN;
        }
        let elapsed = started.elapsed().as_secs_f64();
        // Seconds since the start; a run would need 584 billion years to overflow.
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        let second = elapsed as u64;
        let inside = config
            .window()
            .is_none_or(|window| window.contains(elapsed));
        if inside && let Some(placer) = placer.as_mut() {
            placer.pass(stats.passes, &mut targets);
        }
        for target in targets.iter_mut().filter(|_| inside && sampling) {
            let before = Instant::now();
            let outcome = capture.take(target.raw, &mut target.stack);
            let after = Instant::now();
            match outcome {
                Outcome::Gone => {
                    target.dead = true;
                    continue;
                }
                Outcome::NoContext => {
                    stats.failed += 1;
                    continue;
                }
                Outcome::Captured => {}
            }
            let pause = after - before;
            stats.paused += pause;
            stats.longest_pause = stats.longest_pause.max(pause);
            stats.samples += 1;
            if capture.truncated {
                stats.truncated += 1;
            }
            let running = on_cpu(target, capture.cycles, before, &mut best_rate);
            let (leaf, depth) = capture.unwind(&mut unwinder, &mut frames);
            let stack = frames.get(..depth).unwrap_or_default();
            profile.add(target.thread, running, leaf, stack, 1);
            let name = profile
                .threads()
                .get(target.thread)
                .map_or("?", String::as_str);
            ring.add(second, name, running, leaf, stack);
        }
        let requests = shared.take_requests();
        if !requests.is_empty() {
            let now = Stats {
                wall: started.elapsed(),
                ..stats
            };
            serve(requests, &ring, second, now, &known, &mut profile);
        }
        targets.retain(|target| !target.dead);
        stats.passes += 1;
        deadline += period;
        let now = Instant::now();
        if deadline < now {
            // Late: do not burst to catch up.
            deadline = now;
        }
        timer.wait_until(deadline, shared.stop_flag());
    }
    // The stop closed admission first, so this serves every request accepted before it.
    stats.wall = started.elapsed();
    serve(
        shared.drain_requests(),
        &ring,
        stats.wall.as_secs(),
        stats,
        &known,
        &mut profile,
    );
    profile.stats = stats;
    profile.placement = match (placer, unavailable) {
        (Some(placer), _) => Some(placer.finish(&mut targets)),
        (None, Some(reason)) => Some(Placement {
            unavailable: Some(reason),
            ..Placement::default()
        }),
        (None, None) => None,
    };
    drop(targets);
    merge_modules(&mut known, &modules());
    profile.set_modules(known);
    profile
}