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
//! Naming folded frames from an MSVC linker map (`link.exe /MAP`).
//!
//! A frame `app.exe+0x1a2b` is the RVA `0x1a2b` in `app.exe`; the map of the same build lists
//! every public and static symbol with its address. The nearest symbol at or below the RVA,
//! inside a code section, names the frame. No PDB, no debug help library and no network are
//! involved, so this works on any host.

use std::collections::{BTreeMap, HashMap};
use std::fmt::Write as _;

use crate::Error;

/// Rows in each list of the flat report by default.
pub const DEFAULT_TOP: usize = 60;

/// The code symbols of one linker map, by RVA.
#[derive(Clone, Debug, Default)]
pub struct SymbolMap {
    /// Sorted by RVA; one entry per address (the first name in the map wins).
    symbols: Vec<(u64, String)>,
    /// Code ranges `[start, end)` by RVA, sorted and disjoint. Empty when the map has no
    /// section table: then any RVA at or above a symbol resolves.
    code: Vec<(u64, u64)>,
}

impl SymbolMap {
    /// The symbol at or below `rva` in the same code range, and the distance to it.
    #[must_use]
    pub fn lookup(&self, rva: u64) -> Option<(&str, u64)> {
        let floor = if self.code.is_empty() {
            0
        } else {
            let after = self.code.partition_point(|&(start, _)| start <= rva);
            let &(start, end) = self.code.get(after.checked_sub(1)?)?;
            if rva >= end {
                return None;
            }
            start
        };
        let after = self.symbols.partition_point(|(start, _)| *start <= rva);
        let (start, name) = self.symbols.get(after.checked_sub(1)?)?;
        (*start >= floor).then(|| (name.as_str(), rva - start))
    }

    /// Code symbols held.
    #[must_use]
    pub fn len(&self) -> usize {
        self.symbols.len()
    }

    /// Whether no symbol is held.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.symbols.is_empty()
    }

    /// The code ranges `[start, end)` by RVA, from the map's section table.
    #[must_use]
    pub fn code_ranges(&self) -> &[(u64, u64)] {
        &self.code
    }
}

fn is_hex(text: &str, digits: usize) -> bool {
    text.len() == digits && text.bytes().all(|b| b.is_ascii_hexdigit())
}

/// `ssss:oooooooo`: a section number and an offset in it.
fn section_offset(token: &str) -> Option<(u16, u64)> {
    let (section, offset) = token.split_once(':')?;
    if !is_hex(section, 4) || !is_hex(offset, 8) {
        return None;
    }
    Some((
        u16::from_str_radix(section, 16).ok()?,
        u64::from_str_radix(offset, 16).ok()?,
    ))
}

/// Parse an MSVC link map.
///
/// The map gives the preferred load address (`Preferred load address is 0000000140000000`),
/// a section table (`0001:00000000 0086c220H .text$mn CODE`) and symbol lines
/// (`0001:00001000  name  0000000140001000 f  lib:object`). Symbols in sections the table
/// marks `CODE` are kept, by RVA (`Rva+Base` minus the preferred address); without a section
/// table, symbols of section 1 are kept. Other lines, and malformed ones, are skipped.
pub fn parse_map(text: &str) -> Result<SymbolMap, Error> {
    let mut preferred = None;
    // Section number to (offset, length) of its CODE groups.
    let mut code_groups: HashMap<u16, Vec<(u64, u64)>> = HashMap::new();
    let mut table_seen = false;
    let mut raw: Vec<(u16, u64, u64, String)> = Vec::new();
    for line in text.lines() {
        let trimmed = line.trim();
        if let Some(rest) = trimmed.strip_prefix("Preferred load address is ") {
            preferred = u64::from_str_radix(rest.trim(), 16).ok();
            continue;
        }
        let tokens: Vec<&str> = trimmed.split_whitespace().collect();
        let Some((section, offset)) = tokens.first().and_then(|t| section_offset(t)) else {
            continue;
        };
        // A section table line: `ssss:oooooooo LLLLLLLLH name class`.
        if let Some(length) = tokens
            .get(1)
            .and_then(|t| t.strip_suffix('H'))
            .filter(|t| is_hex(t, 8))
            .and_then(|t| u64::from_str_radix(t, 16).ok())
        {
            table_seen = true;
            if tokens.get(3).is_some_and(|class| *class == "CODE") {
                code_groups
                    .entry(section)
                    .or_default()
                    .push((offset, length));
            }
            continue;
        }
        // A symbol line: the first 16-digit hex token after the name is `Rva+Base`. The name
        // has no spaces in practice; join anyway.
        let Some(at) = tokens
            .iter()
            .skip(2)
            .position(|token| is_hex(token, 16))
            .map(|at| at + 2)
        else {
            continue;
        };
        let (Some(address), Some(name)) = (
            tokens.get(at).and_then(|t| u64::from_str_radix(t, 16).ok()),
            tokens.get(1..at).map(|parts| parts.join(" ")),
        ) else {
            continue;
        };
        raw.push((section, offset, address, name));
    }
    let preferred = preferred
        .ok_or_else(|| Error::InvalidMap("no \"Preferred load address\" line".to_owned()))?;
    let is_code = |section: u16| {
        if table_seen {
            code_groups.contains_key(&section)
        } else {
            section == 1
        }
    };
    let mut symbols: Vec<(u64, String)> = Vec::new();
    // Section number to its RVA, from the first symbol in it.
    let mut section_rva: HashMap<u16, u64> = HashMap::new();
    for (section, offset, address, name) in raw {
        if !is_code(section) {
            continue;
        }
        let Some(rva) = address.checked_sub(preferred) else {
            continue;
        };
        if let Some(base) = rva.checked_sub(offset) {
            section_rva.entry(section).or_insert(base);
        }
        symbols.push((rva, name));
    }
    if symbols.is_empty() {
        return Err(Error::InvalidMap(
            "no code symbols (is it an MSVC /MAP file?)".to_owned(),
        ));
    }
    // Stable: of several names at one address, the first in the map wins.
    symbols.sort_by_key(|(rva, _)| *rva);
    symbols.dedup_by_key(|(rva, _)| *rva);
    let mut code: Vec<(u64, u64)> = Vec::new();
    for (section, groups) in &code_groups {
        let Some(&base) = section_rva.get(section) else {
            continue;
        };
        for &(offset, length) in groups {
            if let Some(start) = base.checked_add(offset)
                && let Some(end) = start.checked_add(length)
                && end > start
            {
                code.push((start, end));
            }
        }
    }
    code.sort_unstable();
    let mut merged: Vec<(u64, u64)> = Vec::with_capacity(code.len());
    for (start, end) in code {
        match merged.last_mut() {
            Some(last) if start <= last.1 => last.1 = last.1.max(end),
            _ => merged.push((start, end)),
        }
    }
    Ok(SymbolMap {
        symbols,
        code: merged,
    })
}

/// The readable form of a linker symbol: Rust names (legacy and v0) demangled without the
/// hash; anything else (C, MSVC-decorated C++) as it is.
#[must_use]
pub fn demangle(raw: &str) -> String {
    format!("{:#}", rustc_demangle::demangle(raw))
}

/// A folded-file frame as a function name, if it is in `module` and the map names it.
fn name_frame(frame: &str, module: &str, map: &SymbolMap) -> Option<String> {
    let (name, offset) = frame.rsplit_once("+0x")?;
    if !name.eq_ignore_ascii_case(module) {
        return None;
    }
    let rva = u64::from_str_radix(offset, 16).ok()?;
    let (symbol, _) = map.lookup(rva)?;
    Some(demangle(symbol).replace(';', ","))
}

/// One folded line: the frames (thread first) and the count.
fn split_line(line: &str) -> Option<(Vec<&str>, u64)> {
    let (stack, count) = line.trim_end().rsplit_once(' ')?;
    let count = count.parse().ok()?;
    Some((stack.split(';').collect(), count))
}

/// The result of [`symbolize`].
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Symbolized {
    /// The folded text with named frames; stacks that became equal are merged.
    pub folded: String,
    /// Per thread label, the top self and inclusive functions.
    pub flat: String,
    /// Frame samples named.
    pub named: u64,
    /// Frame samples seen in the module.
    pub in_module: u64,
    /// Lines that were not `stack count`.
    pub skipped_lines: u64,
}

/// Name the frames of `module` in folded text `folded` from `map`; frames of other modules
/// stay as they are. `top` rows are kept in each list of the flat report.
#[must_use]
pub fn symbolize(folded: &str, map: &SymbolMap, module: &str, top: usize) -> Symbolized {
    // Per thread label: samples, self counts, inclusive counts.
    #[derive(Default)]
    struct Thread {
        samples: u64,
        own: HashMap<String, u64>,
        inclusive: HashMap<String, u64>,
    }
    let mut merged: BTreeMap<String, u64> = BTreeMap::new();
    let mut threads: BTreeMap<String, Thread> = BTreeMap::new();
    let mut result = Symbolized::default();
    for line in folded.lines().filter(|line| !line.trim().is_empty()) {
        let Some((frames, count)) = split_line(line) else {
            result.skipped_lines += 1;
            continue;
        };
        let Some((&thread, callers)) = frames.split_first() else {
            result.skipped_lines += 1;
            continue;
        };
        let mut names = Vec::with_capacity(callers.len());
        for &frame in callers {
            if frame
                .rsplit_once("+0x")
                .is_some_and(|(name, _)| name.eq_ignore_ascii_case(module))
            {
                result.in_module = result.in_module.saturating_add(count);
            }
            match name_frame(frame, module, map) {
                Some(name) => {
                    result.named = result.named.saturating_add(count);
                    names.push(name);
                }
                None => names.push(frame.to_owned()),
            }
        }
        let mut key = thread.to_owned();
        for name in &names {
            key.push(';');
            key.push_str(name);
        }
        let slot = merged.entry(key).or_default();
        *slot = slot.saturating_add(count);

        let entry = threads.entry(thread.to_owned()).or_default();
        entry.samples = entry.samples.saturating_add(count);
        if let Some(leaf) = names.last() {
            let own = entry.own.entry(leaf.clone()).or_default();
            *own = own.saturating_add(count);
        }
        for (at, name) in names.iter().enumerate() {
            if !names.iter().take(at).any(|earlier| earlier == name) {
                let inclusive = entry.inclusive.entry(name.clone()).or_default();
                *inclusive = inclusive.saturating_add(count);
            }
        }
    }
    for (stack, count) in &merged {
        let _ = writeln!(result.folded, "{stack} {count}");
    }
    for (thread, data) in &threads {
        let _ = writeln!(
            result.flat,
            "=== thread {thread:?}: {} samples",
            data.samples
        );
        for (title, counts) in [
            ("self (leaf function)", &data.own),
            ("inclusive (function on the stack)", &data.inclusive),
        ] {
            let _ = writeln!(result.flat, "-- {title}");
            let mut rows: Vec<(&String, &u64)> = counts.iter().collect();
            rows.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0)));
            for (name, count) in rows.into_iter().take(top) {
                let percent = *count as f64 * 100.0 / data.samples.max(1) as f64;
                let _ = writeln!(result.flat, "{count:8} {percent:5.1}%  {name}");
            }
        }
        result.flat.push('\n');
    }
    result
}

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

    const MAP: &str = " app

 Timestamp is 6af3f42e (Tue Nov 10 23:50:54 2026)

 Preferred load address is 0000000140000000

 Start         Length     Name                   Class
 0001:00000000 00003800H .text$mn                CODE
 0001:00003800 00000100H .text$x                 CODE
 0002:00000000 00001000H .rdata                  DATA

  Address         Publics by Value              Rva+Base               Lib:Object

 0000:00000000       __AbsoluteZero             0000000000000000     <absolute>
 0001:00000000       _ZN3app6render4draw17h0123456789abcdefE 0000000140001000 f   app.lib:render.o
 0001:00001000       _RNvCs15kBYyAo9fc_7mycrate7example 0000000140002000 f   mycrate.lib:x.o
 0001:00002000       memcpy                     0000000140003000 f   vcruntime.lib:memcpy.o
 0001:00002000       memmove_alias              0000000140003000 f   vcruntime.lib:memcpy.o
 0001:00002800       ?process@Worker@@QEAAXXZ   0000000140003800 f   worker.obj
 0001:000zzzzz       broken                     0000000140003900 f   x.obj
 0001:00002900       no_address_here            f   x.obj
 0002:00000010       ??_C@_05data               0000000140004010     app.obj
 0001:00002a00       before_base                0000000040000000 f   x.obj

 entry point at        0001:00000000

 Static symbols

 0001:00003800       app_static_helper          0000000140004800 f   app.obj
";

    #[test]
    fn map_parses_code_symbols_relative_to_the_preferred_base() {
        let map = parse_map(MAP).unwrap();
        // memmove_alias shares memcpy's address; the data symbol, the absolute one, the
        // broken lines and the address below the base are skipped.
        assert_eq!(map.len(), 5, "{map:?}");
        assert_eq!(
            map.lookup(0x1000),
            Some(("_ZN3app6render4draw17h0123456789abcdefE", 0))
        );
        assert_eq!(map.lookup(0x1fff).map(|s| s.1), Some(0xfff));
        assert_eq!(map.lookup(0x3010), Some(("memcpy", 0x10)));
        assert_eq!(
            map.lookup(0x3800).map(|s| s.0),
            Some("?process@Worker@@QEAAXXZ")
        );
        assert_eq!(map.lookup(0x4800).map(|s| s.0), Some("app_static_helper"));
        assert!(map.lookup(0x500).is_none(), "below the first symbol");
    }

    #[test]
    fn code_ranges_come_from_the_section_table() {
        let map = parse_map(MAP).unwrap();
        // Section 1 sits at RVA 0x1000 (its first symbol is at offset 0); its two CODE groups
        // touch and merge.
        assert_eq!(map.code_ranges(), &[(0x1000, 0x4900)]);
        assert!(map.lookup(0x48ff).is_some());
        // Past the code: data, not the last function.
        assert!(map.lookup(0x4900).is_none());
        assert!(map.lookup(0x9_0000).is_none());
        assert!(map.lookup(0xfff).is_none());
    }

    #[test]
    fn without_a_section_table_section_one_is_code() {
        let map = parse_map(
            " Preferred load address is 0000000140000000\n\
             0001:00000010 f1 0000000140001010 f a.obj\n\
             0002:00000000 d1 0000000140005000   a.obj\n",
        )
        .unwrap();
        assert_eq!(map.len(), 1);
        assert_eq!(map.code_ranges(), []);
        assert_eq!(map.lookup(0x9999), Some(("f1", 0x9999 - 0x1010)));
    }

    #[test]
    fn maps_without_base_or_symbols_are_refused() {
        assert!(matches!(parse_map("no map"), Err(Error::InvalidMap(_))));
        assert!(matches!(parse_map(""), Err(Error::InvalidMap(_))));
        let no_symbols =
            " Preferred load address is 0000000140000000\n 0001:00000000 00001000H .text CODE\n";
        assert!(matches!(parse_map(no_symbols), Err(Error::InvalidMap(_))));
        let bad_base =
            " Preferred load address is xyz\n 0001:00000000 f 0000000140000000 f a.obj\n";
        assert!(parse_map(bad_base).is_err());
    }

    #[test]
    fn crlf_maps_parse() {
        let map = parse_map(&MAP.replace('\n', "\r\n")).unwrap();
        assert_eq!(map.len(), 5);
    }

    #[test]
    fn rust_names_are_demangled_without_hash() {
        assert_eq!(
            demangle("_ZN3app6render4draw17h0123456789abcdefE"),
            "app::render::draw"
        );
        assert_eq!(
            demangle("_RNvCs15kBYyAo9fc_7mycrate7example"),
            "mycrate::example"
        );
        assert_eq!(demangle("memcpy"), "memcpy");
        assert_eq!(
            demangle("?process@Worker@@QEAAXXZ"),
            "?process@Worker@@QEAAXXZ"
        );
        assert_eq!(demangle(""), "");
    }

    #[test]
    fn frames_are_named_merged_and_profiled() {
        let map = parse_map(MAP).unwrap();
        let folded = "worker;app.exe+0x1000;app.exe+0x2004 3\n\
                      worker;app.exe+0x1008;app.exe+0x2010 2\n\
                      worker;APP.EXE+0x1000;ntdll.dll+0x100 1\n\
                      worker#wait;app.exe+0x3004 4\n\
                      worker;(no-stack) 1\n\
                      worker;jit+0x10 1\n\
                      worker;app.exe+0x9000 1\n";
        let result = symbolize(folded, &map, "app.exe", 10);
        // 0x1000 and 0x1008 are one function; 0x2004 and 0x2010 are one.
        assert!(
            result
                .folded
                .contains("worker;app::render::draw;mycrate::example 5\n"),
            "{}",
            result.folded
        );
        assert!(
            result
                .folded
                .contains("worker;app::render::draw;ntdll.dll+0x100 1\n")
        );
        assert!(result.folded.contains("worker#wait;memcpy 4\n"));
        assert!(result.folded.contains("worker;(no-stack) 1\n"));
        assert!(result.folded.contains("worker;jit+0x10 1\n"));
        // Outside the code ranges: left as it is.
        assert!(result.folded.contains("worker;app.exe+0x9000 1\n"));
        assert_eq!(result.in_module, 3 * 2 + 2 * 2 + 1 + 4 + 1);
        assert_eq!(result.named, 3 * 2 + 2 * 2 + 1 + 4);
        assert_eq!(result.skipped_lines, 0);
        assert!(
            result.flat.contains("=== thread \"worker\": 9 samples"),
            "{}",
            result.flat
        );
        // Self: mycrate::example 5 of 9; inclusive: draw on 6 of 9.
        assert!(
            result.flat.contains("       5  55.6%  mycrate::example"),
            "{}",
            result.flat
        );
        assert!(
            result.flat.contains("       6  66.7%  app::render::draw"),
            "{}",
            result.flat
        );
        assert!(
            result
                .flat
                .contains("=== thread \"worker#wait\": 4 samples")
        );
    }

    #[test]
    fn malformed_folded_lines_are_counted_and_skipped() {
        let map = parse_map(MAP).unwrap();
        let result = symbolize(
            "no count here\nworker;app.exe+0x1000 x\n\n  \nworker;app.exe+0x1000 2\n",
            &map,
            "app.exe",
            5,
        );
        assert_eq!(result.skipped_lines, 2);
        assert_eq!(result.folded, "worker;app::render::draw 2\n");
        let empty = symbolize("", &map, "app.exe", 5);
        assert_eq!(empty, Symbolized::default());
    }

    #[test]
    fn semicolons_in_names_do_not_split_frames() {
        let map = parse_map(
            " Preferred load address is 0000000140000000\n 0001:00000000 a;b 0000000140001000 f x.obj\n",
        )
        .unwrap();
        let result = symbolize("t;app.exe+0x1000 1\n", &map, "app.exe", 5);
        assert_eq!(result.folded, "t;a,b 1\n");
    }

    #[test]
    fn huge_counts_saturate() {
        let map = parse_map(MAP).unwrap();
        let max = u64::MAX;
        let folded = format!(
            "t;app.exe+0x1000;app.exe+0x2000 {max}\nt;app.exe+0x1000;app.exe+0x2000 {max}\n\
             t;app.exe+0x1000 {max}\n"
        );
        let result = symbolize(&folded, &map, "app.exe", 5);
        assert_eq!(result.named, max);
        assert_eq!(result.in_module, max);
        assert!(
            result.flat.contains(&format!("{max} samples")),
            "{}",
            result.flat
        );
        assert!(
            result
                .flat
                .contains(&format!("{max} 100.0%  app::render::draw")),
            "{}",
            result.flat
        );
        assert!(
            result.folded.contains(&format!(" {max}\n")),
            "{}",
            result.folded
        );
    }

    #[test]
    fn top_limits_the_flat_rows() {
        let map = parse_map(MAP).unwrap();
        let folded = "t;app.exe+0x1000 3\nt;app.exe+0x2000 2\nt;app.exe+0x3000 1\n";
        let flat = symbolize(folded, &map, "app.exe", 1).flat;
        assert_eq!(flat.matches('%').count(), 2, "{flat}");
        let none = symbolize(folded, &map, "app.exe", 0).flat;
        assert_eq!(none.matches('%').count(), 0, "{none}");
    }
}