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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
//! Counted stacks and the files written from them.

use std::collections::HashMap;
use std::ffi::OsStr;
use std::fmt::Write as _;
use std::path::{Component, Path, PathBuf};
use std::time::Duration;

use crate::{Error, MAX_DUMP_NAME, Placement};

/// Frames kept per stack.
pub const MAX_FRAMES: usize = 48;
/// Rows in each top list of the text report.
pub const TOP: usize = 30;

/// A loaded module.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Module {
    /// File name, as the frames show it (`app.exe`).
    pub name: String,
    /// Full path.
    pub path: String,
    /// Load address.
    pub base: u64,
    /// Image size in bytes.
    pub size: u64,
}

/// What sampling cost.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct Stats {
    /// Passes over the thread list.
    pub passes: u64,
    /// Samples taken (including those with no stack).
    pub samples: u64,
    /// Threads paused whose registers could not be read (the sample was dropped).
    pub failed: u64,
    /// Samples whose stack was deeper than the copy and was cut short.
    pub truncated: u64,
    /// Time the sampler ran.
    pub wall: Duration,
    /// Time threads spent paused, in all.
    pub paused: Duration,
    /// The longest single pause.
    pub longest_pause: Duration,
    /// Time spent finding threads and modules (no thread is paused then).
    pub scanning: Duration,
}

impl Stats {
    /// Mean pause per sample, in microseconds.
    #[must_use]
    pub fn mean_pause_us(&self) -> f64 {
        if self.samples == 0 {
            0.0
        } else {
            self.paused.as_secs_f64() * 1e6 / self.samples as f64
        }
    }
}

/// One distinct stack and how often it was seen.
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Stack {
    /// Index in [`Profile::threads`].
    pub thread: usize,
    /// Whether the thread was running (else waiting).
    pub on_cpu: bool,
    /// The exact instruction address of frame 0.
    pub leaf_pc: u64,
    /// Function start addresses, leaf first (the leaf's own function at 0).
    pub frames: Box<[u64]>,
    /// Samples of this stack.
    pub count: u64,
}

/// The samples of a run, or of part of one.
#[derive(Clone, Debug, Default)]
pub struct Profile {
    /// The spec that started the run, for the report.
    pub spec: String,
    /// Samples per second asked for.
    pub hz: u32,
    /// What sampling cost.
    pub stats: Stats,
    /// Placement readings, when they were asked for.
    pub placement: Option<Placement>,
    /// Dumps asked for without waiting that could not be written.
    pub dump_errors: Vec<String>,
    modules: Vec<Module>,
    threads: Vec<String>,
    stacks: Vec<Stack>,
    /// Stack hash to indexes in `stacks`.
    index: HashMap<u64, Vec<usize>>,
}

/// Names Windows maps to devices whatever the extension (`CON.txt` is the console).
const DEVICE_NAMES: [&str; 6] = ["CON", "PRN", "AUX", "NUL", "CONIN$", "CONOUT$"];

fn is_device_name(name: &str) -> bool {
    let stem = name.split('.').next().unwrap_or(name).trim_end();
    let upper = stem.to_uppercase();
    if DEVICE_NAMES.contains(&upper.as_str()) {
        return true;
    }
    // COM0 to COM9 and LPT0 to LPT9, with the superscript digits Windows also reserves.
    let mut chars = upper.chars();
    let prefix: String = chars.by_ref().take(3).collect();
    let rest: Vec<char> = chars.collect();
    (prefix == "COM" || prefix == "LPT")
        && matches!(rest.as_slice(), [digit] if digit.is_ascii_digit() || "¹²³".contains(*digit))
}

/// Check that `name` is a plain file name: one normal path component of at most
/// [`MAX_DUMP_NAME`] bytes, with no separator, drive, parent or current directory, control
/// character or device name, so that `<name>.folded` lands inside the directory it is joined
/// to. The message says what is wrong.
pub(crate) fn check_plain_name(name: &str) -> Result<(), String> {
    let mut components = Path::new(name).components();
    let one_normal = matches!(
        (components.next(), components.next()),
        (Some(Component::Normal(part)), None) if part == OsStr::new(name)
    );
    let plain = one_normal
        && name.len() <= MAX_DUMP_NAME
        && name != "."
        && name != ".."
        && !name
            .chars()
            .any(|c| matches!(c, '/' | '\\' | ':' | '\0') || c.is_control())
        && !is_device_name(name);
    if plain {
        Ok(())
    } else {
        Err(format!(
            "name {name:?}: use a plain file name of at most {MAX_DUMP_NAME} bytes"
        ))
    }
}

fn stack_hash(thread: usize, on_cpu: bool, leaf_pc: u64, frames: &[u64]) -> u64 {
    // FNV-1a over the words.
    let mut hash = 0xcbf2_9ce4_8422_2325_u64;
    let mut mix = |word: u64| {
        for byte in word.to_le_bytes() {
            hash ^= u64::from(byte);
            hash = hash.wrapping_mul(0x0100_0000_01b3);
        }
    };
    mix(thread as u64);
    mix(u64::from(on_cpu));
    mix(leaf_pc);
    for &frame in frames {
        mix(frame);
    }
    hash
}

impl Profile {
    /// An empty profile.
    #[must_use]
    pub fn new(spec: &str, hz: u32) -> Self {
        Self {
            spec: spec.to_owned(),
            hz,
            ..Self::default()
        }
    }

    /// The module list, sorted by base address.
    #[must_use]
    pub fn modules(&self) -> &[Module] {
        &self.modules
    }

    /// Replace the module list.
    pub fn set_modules(&mut self, mut modules: Vec<Module>) {
        modules.sort_by_key(|module| module.base);
        self.modules = modules;
    }

    /// Thread names, by index.
    #[must_use]
    pub fn threads(&self) -> &[String] {
        &self.threads
    }

    /// The distinct stacks, in the order first seen.
    pub fn stacks(&self) -> impl ExactSizeIterator<Item = &Stack> {
        self.stacks.iter()
    }

    /// The index of the thread called `name`, added if new.
    pub fn thread_id(&mut self, name: &str) -> usize {
        if let Some(found) = self.threads.iter().position(|known| known == name) {
            return found;
        }
        self.threads.push(name.to_owned());
        self.threads.len() - 1
    }

    /// Count a stack: `frames` are function starts, leaf first, and `leaf_pc` is the exact
    /// address inside `frames[0]`. Allocates only for a stack not seen before. `thread` should
    /// come from [`thread_id`](Self::thread_id).
    pub fn add(&mut self, thread: usize, on_cpu: bool, leaf_pc: u64, frames: &[u64], count: u64) {
        let hash = stack_hash(thread, on_cpu, leaf_pc, frames);
        let bucket = self.index.entry(hash).or_default();
        for &at in bucket.iter() {
            if let Some(stack) = self.stacks.get_mut(at)
                && stack.thread == thread
                && stack.on_cpu == on_cpu
                && stack.leaf_pc == leaf_pc
                && *stack.frames == *frames
            {
                stack.count = stack.count.saturating_add(count);
                return;
            }
        }
        bucket.push(self.stacks.len());
        self.stacks.push(Stack {
            thread,
            on_cpu,
            leaf_pc,
            frames: frames.into(),
            count,
        });
    }

    /// Samples counted in all.
    #[must_use]
    pub fn total(&self) -> u64 {
        self.stacks
            .iter()
            .fold(0_u64, |sum, stack| sum.saturating_add(stack.count))
    }

    /// The module holding `address` and the address's offset in it.
    #[must_use]
    pub fn locate(&self, address: u64) -> Option<(&Module, u64)> {
        let after = self
            .modules
            .partition_point(|module| module.base <= address);
        let module = self.modules.get(after.checked_sub(1)?)?;
        let rva = address - module.base;
        (rva < module.size).then_some((module, rva))
    }

    /// `module+0xRVA`, or `jit+0xADDRESS` outside every module.
    #[must_use]
    pub fn label(&self, address: u64) -> String {
        match self.locate(address) {
            Some((module, rva)) => format!("{}+{rva:#x}", module.name),
            None => format!("jit+{address:#x}"),
        }
    }

    fn thread_label(&self, stack: &Stack) -> String {
        let name = self.threads.get(stack.thread).map_or("?", String::as_str);
        if stack.on_cpu {
            name.to_owned()
        } else {
            format!("{name}#wait")
        }
    }

    /// The folded text: `thread;root;...;leaf count` per distinct stack, sorted. Callers are
    /// function starts; the leaf is the exact address. Waiting samples carry `#wait` after
    /// the thread name. Any flame graph tool that reads folded stacks takes it as is.
    #[must_use]
    pub fn folded(&self) -> String {
        let mut lines: Vec<String> = self
            .stacks
            .iter()
            .map(|stack| {
                let mut line = self.thread_label(stack);
                if stack.frames.is_empty() {
                    line.push_str(";(no-stack)");
                }
                for (depth, &frame) in stack.frames.iter().enumerate().rev() {
                    line.push(';');
                    line.push_str(&self.label(if depth == 0 { stack.leaf_pc } else { frame }));
                }
                format!("{line} {}", stack.count)
            })
            .collect();
        lines.sort_unstable();
        let mut text = lines.join("\n");
        if !text.is_empty() {
            text.push('\n');
        }
        text
    }

    /// The module list text: `base size path` per module.
    #[must_use]
    pub fn modules_text(&self) -> String {
        let mut text = String::from("# base size path\n");
        for module in &self.modules {
            let _ = writeln!(
                text,
                "{:#018x} {:#010x} {}",
                module.base, module.size, module.path
            );
        }
        text
    }

    /// The text report: the cost, the placement section, then per thread the top leaf
    /// addresses and top inclusive functions of the on-CPU samples and the top waiting leaves.
    #[must_use]
    pub fn report(&self) -> String {
        let mut text = String::new();
        let _ = writeln!(text, "mapsample: spec {:?}, {} Hz", self.spec, self.hz);
        let stats = &self.stats;
        let wall = stats.wall.as_secs_f64();
        let _ = writeln!(
            text,
            "{} samples in {} passes over {wall:.2} s ({} failed, {} cut short); mean pause {:.1} us, longest {:.1} us, paused {:.2}% of the wall time in all; {:.3} s spent finding threads and modules",
            stats.samples,
            stats.passes,
            stats.failed,
            stats.truncated,
            stats.mean_pause_us(),
            stats.longest_pause.as_secs_f64() * 1e6,
            if wall > 0.0 {
                stats.paused.as_secs_f64() * 100.0 / wall
            } else {
                0.0
            },
            stats.scanning.as_secs_f64(),
        );
        text.push_str("frames: leaf = exact address, callers = function start (unwind data)\n");
        for error in &self.dump_errors {
            let _ = writeln!(text, "dump not written: {error}");
        }
        text.push('\n');
        if let Some(placement) = &self.placement {
            text.push_str(&placement.report());
        }
        for (thread, name) in self.threads.iter().enumerate() {
            self.thread_report(thread, name, &mut text);
        }
        text
    }

    fn thread_report(&self, thread: usize, name: &str, text: &mut String) {
        let mut on_cpu = 0_u64;
        let mut waiting = 0_u64;
        let mut leaf: HashMap<u64, u64> = HashMap::new();
        let mut inclusive: HashMap<u64, u64> = HashMap::new();
        let mut wait_leaf: HashMap<u64, u64> = HashMap::new();
        for stack in self.stacks.iter().filter(|s| s.thread == thread) {
            let count = stack.count;
            let bump = |map: &mut HashMap<u64, u64>, key: u64| {
                let slot = map.entry(key).or_default();
                *slot = slot.saturating_add(count);
            };
            if stack.frames.is_empty() {
                if stack.on_cpu {
                    on_cpu = on_cpu.saturating_add(count);
                } else {
                    waiting = waiting.saturating_add(count);
                }
                continue;
            }
            if !stack.on_cpu {
                waiting = waiting.saturating_add(count);
                bump(&mut wait_leaf, stack.leaf_pc);
                continue;
            }
            on_cpu = on_cpu.saturating_add(count);
            bump(&mut leaf, stack.leaf_pc);
            for (at, &frame) in stack.frames.iter().enumerate() {
                // A function once per stack, however deep the recursion.
                if !stack
                    .frames
                    .iter()
                    .take(at)
                    .any(|&earlier| earlier == frame)
                {
                    bump(&mut inclusive, frame);
                }
            }
        }
        let _ = writeln!(
            text,
            "=== thread {name:?}: {} samples, {on_cpu} on-CPU, {waiting} waiting",
            on_cpu.saturating_add(waiting)
        );
        let rows = |title: &str,
                    counts: &HashMap<u64, u64>,
                    limit: usize,
                    whole: u64,
                    text: &mut String| {
            let _ = writeln!(text, "-- {title}");
            let mut sorted: Vec<(u64, u64)> = counts.iter().map(|(&a, &c)| (a, c)).collect();
            sorted.sort_unstable_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
            for (address, count) in sorted.into_iter().take(limit) {
                let percent = count as f64 * 100.0 / whole.max(1) as f64;
                let _ = writeln!(text, "{count:8} {percent:5.1}%  {}", self.label(address));
            }
        };
        rows(
            "top leaf addresses, on-CPU samples",
            &leaf,
            TOP,
            on_cpu,
            text,
        );
        rows(
            "top inclusive functions, on-CPU samples",
            &inclusive,
            TOP,
            on_cpu,
            text,
        );
        if waiting != 0 {
            rows(
                "top leaf addresses, waiting samples (10)",
                &wait_leaf,
                10,
                waiting,
                text,
            );
        }
        text.push('\n');
    }

    /// Add every stack of `other` to this profile; threads are matched by name.
    pub fn merge(&mut self, other: &Profile) {
        for stack in &other.stacks {
            let name = other.threads.get(stack.thread).map_or("?", String::as_str);
            let thread = self.thread_id(name);
            self.add(
                thread,
                stack.on_cpu,
                stack.leaf_pc,
                &stack.frames,
                stack.count,
            );
        }
    }

    /// Write `samples.folded`, `samples.txt` and `samples.modules.txt` into `dir`.
    pub fn write_to(&self, dir: &Path) -> Result<Vec<PathBuf>, Error> {
        self.write_named(dir, "samples")
    }

    /// Write `<name>.folded`, `<name>.txt` and `<name>.modules.txt` into `dir`, returning the
    /// paths written. `name` must be a plain file name (one path component: no separator,
    /// drive, `.`, `..` or device name, at most [`MAX_DUMP_NAME`] bytes); anything else is
    /// refused with [`Error::InvalidFileName`] before a file is written.
    pub fn write_named(&self, dir: &Path, name: &str) -> Result<Vec<PathBuf>, Error> {
        check_plain_name(name).map_err(Error::InvalidFileName)?;
        let files = [
            (format!("{name}.folded"), self.folded()),
            (format!("{name}.txt"), self.report()),
            (format!("{name}.modules.txt"), self.modules_text()),
        ];
        let mut written = Vec::with_capacity(files.len());
        for (file, text) in files {
            let path = dir.join(file);
            std::fs::write(&path, text).map_err(|source| Error::Io {
                path: path.clone(),
                source,
            })?;
            written.push(path);
        }
        Ok(written)
    }
}

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

    const APP: u64 = 0x7ff6_0000_0000;
    const NTDLL: u64 = 0x7ff8_0000_0000;

    fn module(name: &str, base: u64, size: u64) -> Module {
        Module {
            name: name.into(),
            path: format!("/opt/bin/{name}"),
            base,
            size,
        }
    }

    fn synthetic() -> Profile {
        let mut profile = Profile::new("worker", 1000);
        profile.set_modules(vec![
            module("ntdll.dll", NTDLL, 0x20_0000),
            module("app.exe", APP, 0x100_0000),
        ]);
        let worker = profile.thread_id("worker");
        // main (0x1000) -> run (0x2000) -> hot (0x3000), leaf inside hot at 0x3040.
        let stack = [APP + 0x3000, APP + 0x2000, APP + 0x1000];
        profile.add(worker, true, APP + 0x3040, &stack, 3);
        profile.add(worker, true, APP + 0x3044, &stack, 1);
        profile.add(worker, true, APP + 0x3040, &stack, 2);
        profile.add(worker, true, APP + 0x2010, &stack[1..], 4);
        profile.add(
            worker,
            false,
            NTDLL + 0x100,
            &[NTDLL + 0x100, APP + 0x1000],
            5,
        );
        profile.add(worker, true, 0x1234_5678, &[0x1234_5678], 1);
        profile.add(worker, true, 0, &[], 1);
        profile
    }

    #[test]
    fn identical_stacks_merge_and_distinct_ones_do_not() {
        let profile = synthetic();
        assert_eq!(profile.total(), 3 + 1 + 2 + 4 + 5 + 1 + 1);
        // 3 + 2 share a leaf address and merge; 0x3044 is its own.
        assert_eq!(profile.stacks().len(), 6);
        // The same frames on another thread or another state are distinct.
        let mut profile = profile;
        let other = profile.thread_id("other");
        let stack = [APP + 0x3000, APP + 0x2000, APP + 0x1000];
        profile.add(other, true, APP + 0x3040, &stack, 1);
        profile.add(0, false, APP + 0x3040, &stack, 1);
        assert_eq!(profile.stacks().len(), 8);
    }

    #[test]
    fn counts_saturate() {
        let mut profile = Profile::new("x", 1);
        let t = profile.thread_id("t");
        profile.add(t, true, 1, &[1], u64::MAX);
        profile.add(t, true, 1, &[1], 5);
        profile.add(t, true, 2, &[2], 5);
        assert_eq!(profile.total(), u64::MAX);
    }

    #[test]
    fn thread_ids_are_stable() {
        let mut profile = Profile::new("x", 1);
        assert_eq!(profile.thread_id("a"), 0);
        assert_eq!(profile.thread_id("b"), 1);
        assert_eq!(profile.thread_id("a"), 0);
        assert_eq!(profile.threads(), ["a", "b"]);
    }

    #[test]
    fn folded_is_root_first_with_module_rvas() {
        let folded = synthetic().folded();
        let lines: Vec<&str> = folded.lines().collect();
        assert!(lines.contains(&"worker;app.exe+0x1000;app.exe+0x2000;app.exe+0x3040 5"));
        assert!(lines.contains(&"worker;app.exe+0x1000;app.exe+0x2000;app.exe+0x3044 1"));
        // The leaf is the exact address, its callers are function starts.
        assert!(lines.contains(&"worker;app.exe+0x1000;app.exe+0x2010 4"));
        assert!(lines.contains(&"worker#wait;app.exe+0x1000;ntdll.dll+0x100 5"));
        assert!(lines.contains(&"worker;jit+0x12345678 1"));
        assert!(lines.contains(&"worker;(no-stack) 1"));
        assert!(folded.ends_with('\n'));
        let mut sorted = lines.clone();
        sorted.sort_unstable();
        assert_eq!(lines, sorted);
        assert_eq!(Profile::new("x", 1).folded(), "");
    }

    #[test]
    fn report_lists_leaf_and_inclusive_with_percentages() {
        let report = synthetic().report();
        assert!(
            report.starts_with("mapsample: spec \"worker\", 1000 Hz\n"),
            "{report}"
        );
        assert!(report.contains("=== thread \"worker\": 17 samples, 12 on-CPU, 5 waiting"));
        // 5 of 12 on-CPU samples sit at 0x3040.
        assert!(report.contains("5  41.7%  app.exe+0x3040"), "{report}");
        // main and run are on 10 of 12 on-CPU samples, hot on 6.
        assert!(report.contains("10  83.3%  app.exe+0x1000"), "{report}");
        assert!(report.contains("10  83.3%  app.exe+0x2000"), "{report}");
        assert!(report.contains("6  50.0%  app.exe+0x3000"), "{report}");
        assert!(report.contains("waiting samples"));
        assert!(report.contains("ntdll.dll+0x100"));
    }

    #[test]
    fn report_without_samples_has_no_nan() {
        let mut profile = Profile::new("x", 1);
        profile.thread_id("idle");
        let report = profile.report();
        assert!(
            report.contains("=== thread \"idle\": 0 samples"),
            "{report}"
        );
        assert!(!report.contains("NaN"), "{report}");
        assert!(!report.contains("waiting samples"));
    }

    #[test]
    fn report_top_lists_are_capped() {
        let mut profile = Profile::new("x", 1);
        let t = profile.thread_id("t");
        for leaf in 0..(TOP as u64 + 10) {
            profile.add(t, true, 0x1000 + leaf, &[0x1000 + leaf], leaf + 1);
        }
        let report = profile.report();
        let section: Vec<&str> = report
            .split("-- top leaf addresses, on-CPU samples\n")
            .nth(1)
            .unwrap()
            .split("-- ")
            .next()
            .unwrap()
            .lines()
            .collect();
        assert_eq!(section.len(), TOP);
    }

    #[test]
    fn recursion_counts_a_function_once_per_stack() {
        let mut profile = Profile::new("x", 10);
        profile.set_modules(vec![module("a.exe", 0x1000, 0x1000)]);
        let thread = profile.thread_id("t");
        profile.add(thread, true, 0x1010, &[0x1000, 0x1000, 0x1000], 4);
        let report = profile.report();
        assert!(report.contains("100.0%  a.exe+0x0\n"), "{report}");
        assert!(!report.contains("12 "), "{report}");
    }

    #[test]
    fn locate_respects_module_bounds() {
        let profile = synthetic();
        let at = |address| {
            profile
                .locate(address)
                .map(|(m, rva)| (m.name.as_str(), rva))
        };
        assert_eq!(at(APP), Some(("app.exe", 0)));
        assert_eq!(at(APP + 0xff_ffff), Some(("app.exe", 0xff_ffff)));
        assert!(at(APP + 0x100_0000).is_none());
        assert!(at(0x10).is_none());
        assert!(at(u64::MAX).is_none());
        assert_eq!(profile.label(NTDLL + 0x100), "ntdll.dll+0x100");
        assert_eq!(profile.label(5), "jit+0x5");
    }

    #[test]
    fn merge_matches_threads_by_name() {
        let mut a = Profile::new("x", 1);
        let ta = a.thread_id("one");
        a.add(ta, true, 1, &[1], 2);
        let mut b = Profile::new("x", 1);
        b.thread_id("zero");
        let tb = b.thread_id("one");
        b.add(tb, true, 1, &[1], 3);
        let tz = b.thread_id("zero");
        b.add(tz, false, 2, &[2], 1);
        a.merge(&b);
        assert_eq!(a.threads(), ["one", "zero"]);
        assert_eq!(a.total(), 6);
        assert_eq!(a.stacks().len(), 2);
    }

    #[test]
    fn modules_text_lists_base_size_path() {
        let text = synthetic().modules_text();
        assert!(text.starts_with("# base size path\n"));
        assert!(
            text.contains("0x00007ff600000000 0x01000000 /opt/bin/app.exe"),
            "{text}"
        );
        // Sorted by base: app.exe before ntdll.dll.
        let app = text.find("app.exe").unwrap();
        let ntdll = text.find("ntdll.dll").unwrap();
        assert!(app < ntdll);
    }

    #[test]
    fn files_are_written() {
        let dir = std::env::temp_dir().join(format!("mapsample-profile-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let written = synthetic().write_to(&dir).unwrap();
        assert_eq!(written.len(), 3);
        for name in ["samples.folded", "samples.txt", "samples.modules.txt"] {
            assert!(dir.join(name).is_file(), "{name}");
        }
        let named = synthetic().write_named(&dir, "stall-1").unwrap();
        assert!(named.iter().all(|path| path.is_file()));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn write_named_stays_inside_its_directory() {
        let root = std::env::temp_dir().join(format!("mapsample-escape-{}", std::process::id()));
        let dir = root.join("inner");
        std::fs::create_dir_all(&dir).unwrap();
        let absolute = std::env::temp_dir().join("mapsample-absolute");
        let absolute = absolute.to_str().unwrap();
        for bad in [
            "../escape",
            "..",
            ".",
            "",
            "sub/name",
            "sub\\name",
            absolute,
            "/etc/name",
            "c:name",
            "C:\\name",
            "\\\\server\\share",
            "nul\0",
            "CON",
            "con.txt",
            "Com1",
            "lpt9.log",
            "COM\u{b9}",
            &"x".repeat(MAX_DUMP_NAME + 1),
        ] {
            assert!(
                matches!(
                    synthetic().write_named(&dir, bad),
                    Err(Error::InvalidFileName(_))
                ),
                "{bad:?}"
            );
        }
        assert!(!root.join("escape.folded").exists());
        assert!(!dir.join("sub").exists());
        assert_eq!(
            std::fs::read_dir(&dir).unwrap().count(),
            0,
            "nothing written"
        );
        for good in [
            "stall-1",
            "a.b",
            "console",
            "COM10",
            "..x",
            &"x".repeat(MAX_DUMP_NAME),
        ] {
            assert!(check_plain_name(good).is_ok(), "{good:?}");
        }
        let _ = std::fs::remove_dir_all(&root);
    }

    #[test]
    fn report_counters_saturate() {
        let mut profile = Profile::new("x", 1);
        let t = profile.thread_id("t");
        profile.add(t, true, 1, &[1, 2, 1], u64::MAX);
        profile.add(t, true, 1, &[1, 3], u64::MAX);
        profile.add(t, false, 5, &[5], u64::MAX);
        profile.add(t, false, 6, &[], u64::MAX);
        profile.add(t, true, 7, &[], u64::MAX);
        let report = profile.report();
        let max = u64::MAX;
        assert!(
            report.contains(&format!("{max} samples, {max} on-CPU, {max} waiting")),
            "{report}"
        );
        assert!(
            report.contains(&format!("{max} 100.0%  jit+0x1")),
            "{report}"
        );
    }

    #[test]
    fn writing_to_a_missing_directory_names_the_file() {
        let dir = std::env::temp_dir()
            .join(format!("mapsample-missing-{}", std::process::id()))
            .join("nope");
        let error = synthetic().write_to(&dir).unwrap_err();
        assert!(
            matches!(&error, Error::Io { path, .. } if path.ends_with("samples.folded")),
            "{error}"
        );
    }
}