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
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
//! One sample: pause the thread, copy its registers and stack, resume it; then unwind the
//! copy.
//!
//! Only fault-safe system calls run while the thread is paused: `QueryThreadCycleTime`,
//! `GetThreadContext` and `ReadProcessMemory`. Unwinding runs after the thread is resumed, in
//! safe Rust ([`crate::unwind_info`]) over the copied stack bytes. Each module the walk
//! enters is pinned with a counted `GetModuleHandleExW` reference for the rest of the walk,
//! and its headers, `.pdata`, unwind info and epilog bytes are read with `ReadProcessMemory`
//! inside the readable ranges its own PE header names, so neither an unloading image nor a
//! damaged frame can make the walk read memory it does not own.

use std::collections::HashMap;
use std::mem::zeroed;
use std::ptr::null_mut;

use windows_sys::Win32::Foundation::{FreeLibrary, HANDLE, HMODULE};
use windows_sys::Win32::System::Diagnostics::Debug::{
    CONTEXT, CONTEXT_CONTROL_AMD64, CONTEXT_INTEGER_AMD64, GetThreadContext,
};
use windows_sys::Win32::System::LibraryLoader::{
    GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, GetModuleHandleExW,
};
use windows_sys::Win32::System::Threading::{ResumeThread, SuspendThread};
use windows_sys::Win32::System::WindowsProgramming::QueryThreadCycleTime;

use super::sys;
use crate::MAX_FRAMES;
use crate::unwind_info::{
    Frame, Image, PeImage, RSP, Registers, RuntimeFunction, StackCopy, Stepped, UnwindPlan,
    load_plan, lookup, parse_pdata, read_pe, step,
};

/// The most stack copied per sample. Deeper stacks are cut there (counted as truncated).
pub(super) const STACK_COPY_BYTES: usize = 256 * 1024;
/// The largest exception directory loaded.
const MAX_PDATA_BYTES: u32 = 64 << 20;
/// Cached modules and decoded unwind infos per module, before the cache starts over.
const MAX_CACHED_MODULES: usize = 512;
const MAX_CACHED_PLANS: usize = 1 << 16;

/// A `CONTEXT` the system accepts: windows-sys declares it without the 16-byte alignment
/// `GetThreadContext` requires (a misaligned one fails with `ERROR_NOACCESS`).
#[repr(C, align(16))]
pub(super) struct AlignedContext(pub(super) CONTEXT);

/// What a thread was doing when paused, ready to unwind. Allocated once per sampler; nothing
/// in it is allocated while a thread is paused.
pub(super) struct Capture {
    context: Box<AlignedContext>,
    /// The copy of `[rsp, rsp + len)`.
    stack: Vec<u8>,
    /// Bytes copied (a multiple of 8).
    len: usize,
    /// The thread's stack pointer.
    rsp: u64,
    /// The thread's cycle counter, if read.
    pub(super) cycles: Option<u64>,
    /// The stack was deeper than [`STACK_COPY_BYTES`].
    pub(super) truncated: bool,
}

/// The stack bounds a capture checks the stack pointer against.
pub(super) struct StackInfo {
    pub(super) teb: Option<u64>,
    pub(super) bounds: Option<(u64, u64)>,
}

/// How a capture went.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Outcome {
    /// The thread could not be paused: it exited.
    Gone,
    /// The thread was paused but its registers could not be read.
    NoContext,
    /// Registers (and the stack, when its bounds are known) were copied.
    Captured,
}

/// Resumes the thread when dropped, so no path out of [`Capture::take`] leaves it paused.
struct Paused(HANDLE);

impl Drop for Paused {
    fn drop(&mut self) {
        // SAFETY: the handle has THREAD_SUSPEND_RESUME and this guard exists only after a
        // successful SuspendThread on it; this is the matching resume.
        unsafe { ResumeThread(self.0) };
    }
}

impl Capture {
    pub(super) fn new() -> Self {
        // SAFETY: all-zero is a valid CONTEXT (integers, arrays and a union of them).
        let context: AlignedContext = unsafe { zeroed() };
        Self {
            context: Box::new(context),
            stack: vec![0; STACK_COPY_BYTES],
            len: 0,
            rsp: 0,
            cycles: None,
            truncated: false,
        }
    }

    /// Pause the thread behind `handle`, copy what is needed to unwind it, resume it.
    ///
    /// Between `SuspendThread` and `ResumeThread` this allocates nothing, takes no lock and
    /// has no panicking operation (only checked arithmetic and fault-safe system calls). If a
    /// panic happened anyway, the guard would still resume the thread.
    pub(super) fn take(&mut self, handle: HANDLE, stack: &mut StackInfo) -> Outcome {
        self.len = 0;
        self.rsp = 0;
        self.cycles = None;
        self.truncated = false;
        // SAFETY: `handle` is an open thread handle with THREAD_SUSPEND_RESUME; `u32::MAX`
        // means the call failed and nothing was suspended.
        if unsafe { SuspendThread(handle) } == u32::MAX {
            return Outcome::Gone;
        }
        let _paused = Paused(handle);
        let mut cycles = 0_u64;
        // SAFETY: the handle has THREAD_QUERY_LIMITED_INFORMATION; `cycles` is writable.
        if unsafe { QueryThreadCycleTime(handle, &raw mut cycles) } != 0 {
            self.cycles = Some(cycles);
        }
        self.context.0.ContextFlags = CONTEXT_CONTROL_AMD64 | CONTEXT_INTEGER_AMD64;
        // SuspendThread is asynchronous; GetThreadContext returns only once the thread is
        // actually stopped, so the stack copy below sees a still stack.
        // SAFETY: the handle has THREAD_GET_CONTEXT; the context is writable and 16-byte
        // aligned (`AlignedContext`, boxed with its alignment).
        if unsafe { GetThreadContext(handle, &raw mut self.context.0) } == 0 {
            return Outcome::NoContext;
        }
        let rsp = self.context.0.Rsp;
        self.rsp = rsp;
        if rsp & 7 != 0 {
            return Outcome::Captured;
        }
        let inside =
            |bounds: Option<(u64, u64)>| bounds.is_some_and(|(low, high)| rsp >= low && rsp < high);
        if !inside(stack.bounds)
            && let Some(teb) = stack.teb
        {
            // A fiber switch or an alternate stack: read the bounds again (fault-safe reads).
            stack.bounds = sys::stack_bounds(teb);
        }
        let Some((_, high)) = stack.bounds.filter(|_| inside(stack.bounds)) else {
            return Outcome::Captured;
        };
        let wanted = high - rsp;
        let len = usize::try_from(wanted).map_or(STACK_COPY_BYTES, |w| w.min(STACK_COPY_BYTES));
        self.truncated = wanted > STACK_COPY_BYTES as u64;
        let len = len.min(self.stack.len());
        // SAFETY: `stack` holds STACK_COPY_BYTES writable bytes and `len` is at most that; the
        // source is this paused thread's stack, read by the kernel (a bad page fails cleanly).
        let read = unsafe { sys::read_into(rsp, self.stack.as_mut_ptr(), len) };
        self.len = read & !7;
        Outcome::Captured
    }

    fn registers(&self) -> Registers {
        let c = &self.context.0;
        Registers {
            rip: c.Rip,
            gpr: [
                c.Rax, c.Rcx, c.Rdx, c.Rbx, c.Rsp, c.Rbp, c.Rsi, c.Rdi, c.R8, c.R9, c.R10, c.R11,
                c.R12, c.R13, c.R14, c.R15,
            ],
        }
    }

    /// Unwind the captured thread (after it was resumed). Frames are function starts, leaf
    /// first. Returns the exact leaf address and the depth.
    pub(super) fn unwind(
        &self,
        unwinder: &mut Unwinder,
        frames: &mut [u64; MAX_FRAMES],
    ) -> (u64, usize) {
        let mut regs = self.registers();
        let leaf = regs.rip;
        let stack = StackCopy {
            base: self.rsp,
            bytes: self.stack.get(..self.len).unwrap_or_default(),
        };
        let depth = unwinder.walk(&mut regs, &stack, frames);
        unwinder.pins.clear();
        (leaf, depth)
    }
}

/// A counted reference to a module, given back when dropped.
struct ModuleRef(HMODULE);

impl Drop for ModuleRef {
    fn drop(&mut self) {
        // SAFETY: the reference was taken by a successful GetModuleHandleExW without
        // GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, and this is its one release. Nothing
        // read through it is still borrowed: every image read was a copy.
        unsafe { FreeLibrary(self.0) };
    }
}

/// A module held loaded for the rest of a walk, with the header it was read from.
struct Pinned {
    _reference: ModuleRef,
    base: u64,
    pe: PeImage,
}

impl Pinned {
    /// Pin the module holding `address`, if any.
    fn new(address: u64) -> Option<Self> {
        let mut module: HMODULE = null_mut();
        let name = std::ptr::without_provenance::<u16>(usize::try_from(address).ok()?);
        // SAFETY: with GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS the name argument is only an
        // address to look up and is never read; `module` is a writable out-pointer. On success
        // the module's reference count was raised, which `ModuleRef` gives back.
        let found = unsafe {
            GetModuleHandleExW(
                GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
                name,
                &raw mut module,
            )
        } != 0;
        if !found || module.is_null() {
            return None;
        }
        let reference = ModuleRef(module);
        let base = module.addr() as u64;
        // The header is sized from its own DOS and COFF fields, so a section table past the
        // first page is read whole.
        let pe = read_pe(|out| {
            // SAFETY: `out` is `out.len()` writable bytes; the source is read by the kernel.
            unsafe { sys::read_into(base, out.as_mut_ptr(), out.len()) }
        })?;
        if address.checked_sub(base)? >= u64::from(pe.size) {
            return None;
        }
        Some(Self {
            _reference: reference,
            base,
            pe,
        })
    }

    fn contains(&self, address: u64) -> bool {
        address
            .checked_sub(self.base)
            .is_some_and(|rva| rva < u64::from(self.pe.size))
    }

    fn key(&self) -> ModuleKey {
        ModuleKey {
            base: self.base,
            size: self.pe.size,
            stamp: self.pe.stamp,
            checksum: self.pe.checksum,
            exception: self.pe.exception,
        }
    }
}

/// Reads a pinned module's bytes, inside the readable ranges of its header, fault-safely.
struct PinnedImage<'a>(&'a Pinned);

impl Image for PinnedImage<'_> {
    fn read(&mut self, rva: u32, out: &mut [u8]) -> bool {
        if !self.0.pe.is_readable(rva, out.len()) {
            return false;
        }
        // SAFETY: `out` is `out.len()` writable bytes; the source is read by the kernel.
        let read =
            unsafe { sys::read_into(self.0.base + u64::from(rva), out.as_mut_ptr(), out.len()) };
        read == out.len()
    }
}

/// What tells one loaded image from another at the same address.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
struct ModuleKey {
    base: u64,
    size: u32,
    stamp: u32,
    checksum: u32,
    exception: (u32, u32),
}

#[derive(Default)]
struct ModuleData {
    table: Vec<RuntimeFunction>,
    plans: HashMap<u32, Option<UnwindPlan>>,
}

impl ModuleData {
    fn load(pinned: &Pinned) -> Self {
        let (rva, size) = pinned.pe.exception;
        let mut table = Vec::new();
        if size > 0 && size <= MAX_PDATA_BYTES {
            let mut bytes = vec![0_u8; size as usize];
            if PinnedImage(pinned).read(rva, &mut bytes) {
                table = parse_pdata(&bytes);
            }
        }
        Self {
            table,
            plans: HashMap::new(),
        }
    }
}

/// Unwinds captures, caching each module's function table and decoded unwind infos.
#[derive(Default)]
pub(super) struct Unwinder {
    modules: HashMap<ModuleKey, ModuleData>,
    /// Modules pinned during the current walk.
    pins: Vec<Pinned>,
}

impl Unwinder {
    /// The index in `pins` of the module holding `address`, pinning it if needed.
    fn pin(&mut self, address: u64) -> Option<usize> {
        if let Some(at) = self.pins.iter().position(|pin| pin.contains(address)) {
            return Some(at);
        }
        let pinned = Pinned::new(address)?;
        self.pins.push(pinned);
        Some(self.pins.len() - 1)
    }

    /// Walk from `regs` over `stack`, filling `frames`; returns the depth.
    fn walk(
        &mut self,
        regs: &mut Registers,
        stack: &StackCopy,
        frames: &mut [u64; MAX_FRAMES],
    ) -> usize {
        let mut depth = 0;
        let mut exact = true;
        while depth < MAX_FRAMES && regs.rip != 0 {
            let pc = regs.rip;
            // A return address may sit just past its function (a call that never returns),
            // so callers are looked up one byte back.
            let probe = if exact { pc } else { pc.wrapping_sub(1) };
            let Some(slot) = frames.get_mut(depth) else {
                break;
            };
            let found = self.pin(probe).and_then(|at| {
                let pinned = self.pins.get(at)?;
                let key = pinned.key();
                if !self.modules.contains_key(&key) && self.modules.len() >= MAX_CACHED_MODULES {
                    self.modules.clear();
                }
                let data = self
                    .modules
                    .entry(key)
                    .or_insert_with(|| ModuleData::load(pinned));
                let mut image = PinnedImage(pinned);
                let rva = u32::try_from(probe.checked_sub(pinned.base)?).ok()?;
                let entry = lookup(&data.table, rva, &mut image)?;
                let unwind = entry.function.unwind;
                if !data.plans.contains_key(&unwind) {
                    if data.plans.len() >= MAX_CACHED_PLANS {
                        data.plans.clear();
                    }
                    data.plans.insert(unwind, load_plan(unwind, &mut image));
                }
                Some((at, entry))
            });
            let Some((at, entry)) = found else {
                // No unwind data: JIT code, a bad pc, or a leaf function, whose return address
                // is on top of the stack. Only the leaf is stepped over.
                *slot = pc;
                depth += 1;
                let Some(return_address) = (depth == 1).then(|| stack.word(regs.rsp())).flatten()
                else {
                    break;
                };
                regs.rip = return_address;
                regs.gpr[RSP] = regs.rsp().wrapping_add(8);
                exact = false;
                continue;
            };
            let Some(pinned) = self.pins.get(at) else {
                break;
            };
            *slot = pinned.base + u64::from(entry.function.begin);
            depth += 1;
            // No copy (or a stack pointer outside it): only this frame is known.
            if stack.bytes.is_empty() || !stack.holds(regs.rsp()) {
                break;
            }
            let Some(data) = self.modules.get(&pinned.key()) else {
                break;
            };
            let Some(Some(plan)) = data.plans.get(&entry.function.unwind) else {
                break;
            };
            let Some(pc_rva) = pc
                .checked_sub(pinned.base)
                .and_then(|rva| u32::try_from(rva).ok())
            else {
                break;
            };
            let before = regs.rsp();
            let frame = Frame {
                entry,
                plan,
                pc: pc_rva,
                exact,
            };
            match step(&frame, regs, stack, &data.table, &mut PinnedImage(pinned)) {
                Some(stepped) => exact = stepped == Stepped::MachineFrame,
                None => break,
            }
            if regs.rsp() <= before {
                break;
            }
        }
        depth
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn context_alignment() {
        assert_eq!(std::mem::align_of::<AlignedContext>(), 16);
        let capture = Capture::new();
        assert_eq!((&raw const capture.context.0).addr() % 16, 0);
        assert_eq!(capture.stack.len(), STACK_COPY_BYTES);
    }

    #[test]
    fn pinning_finds_this_module_and_refuses_other_memory() {
        let here = pinning_finds_this_module_and_refuses_other_memory as fn() as usize as u64;
        let pinned = Pinned::new(here).unwrap();
        assert!(pinned.contains(here));
        assert!(pinned.pe.size > 0);
        assert_ne!(pinned.pe.exception, (0, 0), "an x64 image has .pdata");
        assert!(Pinned::new(0x10).is_none());
        let heap = Box::new(0_u64);
        assert!(Pinned::new((&raw const *heap).addr() as u64).is_none());
    }

    #[test]
    fn pinned_reads_stay_in_readable_ranges() {
        let here = pinned_reads_stay_in_readable_ranges as fn() as usize as u64;
        let pinned = Pinned::new(here).unwrap();
        let mut image = PinnedImage(&pinned);
        let mut mz = [0_u8; 2];
        assert!(image.read(0, &mut mz));
        assert_eq!(&mz, b"MZ");
        let mut past = [0_u8; 8];
        // The rest of the first page is mapped, so only the header's own ranges refuse it.
        let after_headers = pinned.pe.readable[0].1;
        assert!(after_headers < 0x1000, "{:x?}", pinned.pe.readable);
        assert!(!pinned.pe.is_readable(after_headers, past.len()));
        assert!(!image.read(after_headers, &mut past));
        assert!(!image.read(pinned.pe.size - 4, &mut past));
        assert!(!image.read(u32::MAX - 2, &mut past));
    }

    #[inline(never)]
    fn deeper(depth: u32, out: &mut Vec<u64>) {
        if depth == 0 {
            // Unwind this very thread: copy the live stack from here up and walk it.
            let mut capture = Capture::new();
            let mut context: AlignedContext =
                // SAFETY: all-zero is a valid CONTEXT.
                unsafe { zeroed() };
            context.0.ContextFlags = CONTEXT_CONTROL_AMD64 | CONTEXT_INTEGER_AMD64;
            // SAFETY: RtlCaptureContext fills the aligned, writable context of this thread.
            unsafe {
                windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureContext(
                    &raw mut context.0,
                );
            }
            let rsp = context.0.Rsp;
            let len = 64 * 1024;
            // SAFETY: the buffer holds STACK_COPY_BYTES >= len writable bytes.
            let read = unsafe { sys::read_into(rsp, capture.stack.as_mut_ptr(), len) };
            capture.len = read & !7;
            capture.rsp = rsp;
            *capture.context = context;
            let mut frames = [0_u64; MAX_FRAMES];
            let mut unwinder = Unwinder::default();
            let (_, depth) = capture.unwind(&mut unwinder, &mut frames);
            assert!(unwinder.pins.is_empty(), "pins are released after the walk");
            out.extend_from_slice(&frames[..depth]);
            return;
        }
        deeper(std::hint::black_box(depth - 1), out);
        std::hint::black_box(&out);
    }

    #[test]
    fn a_live_stack_unwinds_through_its_callers() {
        let mut frames = Vec::new();
        deeper(4, &mut frames);
        let start = deeper as fn(u32, &mut Vec<u64>) as usize as u64;
        let recursive = frames.iter().filter(|&&frame| frame == start).count();
        assert!(recursive >= 5, "{recursive} deeper frames in {frames:x?}");
        let test = a_live_stack_unwinds_through_its_callers as fn() as usize as u64;
        assert!(frames.contains(&test), "{frames:x?}");
    }

    #[test]
    fn a_capture_without_a_stack_records_only_the_leaf() {
        let mut capture = Capture::new();
        let here = a_capture_without_a_stack_records_only_the_leaf as fn() as usize as u64;
        capture.context.0.Rip = here + 1;
        capture.context.0.Rsp = 0x1000;
        capture.len = 0;
        let mut frames = [0_u64; MAX_FRAMES];
        let mut unwinder = Unwinder::default();
        let (leaf, depth) = capture.unwind(&mut unwinder, &mut frames);
        assert_eq!((leaf, depth), (here + 1, 1));
        assert_eq!(frames[0], here, "the leaf's function start");
        // Outside every module and without a stack: the bare pc.
        capture.context.0.Rip = 0x10;
        let (_, depth) = capture.unwind(&mut unwinder, &mut frames);
        assert_eq!((depth, frames[0]), (1, 0x10));
    }
}