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};
pub const MAX_FRAMES: usize = 48;
pub const TOP: usize = 30;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Module {
pub name: String,
pub path: String,
pub base: u64,
pub size: u64,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct Stats {
pub passes: u64,
pub samples: u64,
pub failed: u64,
pub truncated: u64,
pub wall: Duration,
pub paused: Duration,
pub longest_pause: Duration,
pub scanning: Duration,
}
impl Stats {
#[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
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Stack {
pub thread: usize,
pub on_cpu: bool,
pub leaf_pc: u64,
pub frames: Box<[u64]>,
pub count: u64,
}
#[derive(Clone, Debug, Default)]
pub struct Profile {
pub spec: String,
pub hz: u32,
pub stats: Stats,
pub placement: Option<Placement>,
pub dump_errors: Vec<String>,
modules: Vec<Module>,
threads: Vec<String>,
stacks: Vec<Stack>,
index: HashMap<u64, Vec<usize>>,
}
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;
}
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))
}
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 {
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 {
#[must_use]
pub fn new(spec: &str, hz: u32) -> Self {
Self {
spec: spec.to_owned(),
hz,
..Self::default()
}
}
#[must_use]
pub fn modules(&self) -> &[Module] {
&self.modules
}
pub fn set_modules(&mut self, mut modules: Vec<Module>) {
modules.sort_by_key(|module| module.base);
self.modules = modules;
}
#[must_use]
pub fn threads(&self) -> &[String] {
&self.threads
}
pub fn stacks(&self) -> impl ExactSizeIterator<Item = &Stack> {
self.stacks.iter()
}
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
}
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,
});
}
#[must_use]
pub fn total(&self) -> u64 {
self.stacks
.iter()
.fold(0_u64, |sum, stack| sum.saturating_add(stack.count))
}
#[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))
}
#[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")
}
}
#[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
}
#[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
}
#[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() {
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');
}
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,
);
}
}
pub fn write_to(&self, dir: &Path) -> Result<Vec<PathBuf>, Error> {
self.write_named(dir, "samples")
}
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");
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);
assert_eq!(profile.stacks().len(), 6);
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"));
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"));
assert!(report.contains("5 41.7% app.exe+0x3040"), "{report}");
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}"
);
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}"
);
}
}