#![cfg(all(windows, target_arch = "x86_64"))]
#![allow(unsafe_code, clippy::unwrap_used, clippy::panic)]
use std::hint::black_box;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};
use mapsample::{Config, Placement, PlacementMode, Profile, Sampler};
use windows_sys::Win32::System::LibraryLoader::{GetModuleHandleW, GetProcAddress};
use windows_sys::Win32::System::Threading::{GetCurrentProcess, GetProcessHandleCount};
static SERIAL: Mutex<()> = Mutex::new(());
fn serial() -> std::sync::MutexGuard<'static, ()> {
SERIAL
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
#[inline(never)]
fn busy_spin(stop: &AtomicBool) -> u64 {
let mut x = 0x9e37_79b9_7f4a_7c15_u64;
while !stop.load(Ordering::Relaxed) {
for _ in 0..1000 {
x = black_box(x.rotate_left(7) ^ x.wrapping_mul(31));
}
}
x
}
struct Workload {
stop: Arc<AtomicBool>,
threads: Vec<JoinHandle<()>>,
}
impl Workload {
fn start(busy: &[&str], sleeping: &[&str]) -> Self {
let stop = Arc::new(AtomicBool::new(false));
let mut threads = Vec::new();
for name in busy {
let stop = Arc::clone(&stop);
threads.push(
thread::Builder::new()
.name((*name).to_owned())
.spawn(move || {
black_box(busy_spin(&stop));
})
.unwrap(),
);
}
for name in sleeping {
let stop = Arc::clone(&stop);
threads.push(
thread::Builder::new()
.name((*name).to_owned())
.spawn(move || {
while !stop.load(Ordering::Relaxed) {
thread::sleep(Duration::from_millis(20));
}
})
.unwrap(),
);
}
thread::sleep(Duration::from_millis(30));
Self { stop, threads }
}
fn finish(self) {
self.stop.store(true, Ordering::Relaxed);
for thread in self.threads {
thread.join().unwrap();
}
}
}
fn thread_index(profile: &Profile, name: &str) -> usize {
profile
.threads()
.iter()
.position(|thread| thread == name)
.unwrap_or_else(|| panic!("{name} was not sampled: {:?}", profile.threads()))
}
fn split(profile: &Profile, thread: usize) -> (u64, u64) {
let mut counts = (0, 0);
for stack in profile.stacks().filter(|stack| stack.thread == thread) {
if stack.on_cpu {
counts.0 += stack.count;
} else {
counts.1 += stack.count;
}
}
counts
}
fn handle_count() -> u32 {
let mut count = 0_u32;
let ok = unsafe { GetProcessHandleCount(GetCurrentProcess(), &raw mut count) };
assert_ne!(ok, 0);
count
}
fn scratch(test: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("mapsample-{test}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn busy_threads_are_on_cpu_and_sleeping_threads_wait() {
let _turn = serial();
let work = Workload::start(&["mstest-busy"], &["mstest-sleep"]);
let sampler = Sampler::start(Config::parse("mstest-:500").unwrap()).unwrap();
thread::sleep(Duration::from_millis(1200));
let profile = sampler.stop().unwrap();
work.finish();
let busy = thread_index(&profile, "mstest-busy");
let sleep = thread_index(&profile, "mstest-sleep");
assert!(
profile
.threads()
.iter()
.all(|name| name.starts_with("mstest-"))
);
let (busy_on, busy_wait) = split(&profile, busy);
let (sleep_on, sleep_wait) = split(&profile, sleep);
assert!(busy_on > 200, "busy: {busy_on} on-CPU, {busy_wait} waiting");
assert!(
busy_on > 4 * busy_wait,
"busy: {busy_on} on-CPU, {busy_wait} waiting"
);
assert!(
sleep_wait > 200,
"sleep: {sleep_on} on-CPU, {sleep_wait} waiting"
);
assert!(
sleep_wait > 4 * sleep_on,
"sleep: {sleep_on} on-CPU, {sleep_wait} waiting"
);
assert!(profile.stats.samples >= busy_on + busy_wait + sleep_on + sleep_wait);
eprintln!(
"longest pause {:?}, mean {:.1} us",
profile.stats.longest_pause,
profile.stats.mean_pause_us()
);
let exe = std::env::current_exe().unwrap();
let exe_name = exe.file_name().unwrap().to_string_lossy().to_lowercase();
let mut deep = 0;
let mut in_spin = 0;
for stack in profile
.stacks()
.filter(|stack| stack.thread == busy && stack.on_cpu)
{
assert!(!stack.frames.is_empty());
let (module, _) = profile.locate(stack.leaf_pc).unwrap();
if module.name.to_lowercase() == exe_name && stack.frames.len() >= 3 {
deep += stack.count;
}
if stack.frames[0] <= stack.leaf_pc && stack.leaf_pc - stack.frames[0] < 4096 {
in_spin += stack.count;
}
assert!(stack.frames.iter().all(|&frame| frame != 0));
}
assert!(
deep * 2 > busy_on,
"{deep} of {busy_on} busy samples unwound into the test binary"
);
assert!(
in_spin * 2 > busy_on,
"{in_spin} of {busy_on} leaves near their function start"
);
let spin_start = busy_spin as fn(&AtomicBool) -> u64 as usize as u64;
let reached = profile
.stacks()
.filter(|stack| stack.thread == busy)
.any(|stack| stack.frames.contains(&spin_start));
assert!(reached, "busy_spin at {spin_start:#x} is on no busy stack");
let folded = profile.folded();
assert!(folded.lines().any(|line| line.starts_with("mstest-busy;")));
assert!(
folded
.lines()
.any(|line| line.starts_with("mstest-sleep#wait;"))
);
assert!(
profile
.report()
.starts_with("mapsample: spec \"mstest-:500\"")
);
}
#[test]
fn a_ring_dump_writes_the_three_files() {
let _turn = serial();
let dir = scratch("dump");
let work = Workload::start(&["mstest-dump"], &[]);
let sampler = Sampler::start(Config::parse("mstest-dump").unwrap()).unwrap();
thread::sleep(Duration::from_millis(1500));
let paths = sampler.dump_recent(&dir, "stall", 2.0).unwrap();
let handle = sampler.dump_handle();
let profile = sampler.stop().unwrap();
work.finish();
assert!(handle.request(&dir, "late", 1.0).is_err());
assert_eq!(profile.dump_errors, [] as [String; 0]);
let names: Vec<String> = paths
.iter()
.map(|path| path.file_name().unwrap().to_string_lossy().into_owned())
.collect();
assert_eq!(names, ["stall.folded", "stall.txt", "stall.modules.txt"]);
let folded = std::fs::read_to_string(&paths[0]).unwrap();
assert_ne!(folded, "");
for line in folded.lines() {
let (stack, count) = line.rsplit_once(' ').unwrap();
assert!(count.parse::<u64>().unwrap() > 0, "{line}");
let mut frames = stack.split(';');
let thread = frames.next().unwrap();
assert!(
thread == "mstest-dump" || thread == "mstest-dump#wait",
"{line}"
);
assert!(
frames.all(|frame| frame.contains("+0x") || frame == "(no-stack)"),
"{line}"
);
}
let text = std::fs::read_to_string(&paths[1]).unwrap();
assert!(
text.starts_with("mapsample: spec \"mstest-dump\""),
"{text}"
);
let modules = std::fs::read_to_string(&paths[2]).unwrap();
assert!(modules.starts_with("# base size path\n"));
assert!(modules.to_lowercase().contains("ntdll.dll"));
let exe = std::env::current_exe().unwrap();
assert!(modules.contains(&*exe.to_string_lossy()), "{modules}");
std::fs::remove_dir_all(&dir).unwrap();
}
fn placement_supported() -> bool {
let kernel32: Vec<u16> = "kernel32.dll".encode_utf16().chain(Some(0)).collect();
let module = unsafe { GetModuleHandleW(kernel32.as_ptr()) };
!module.is_null()
&& unsafe { GetProcAddress(module, c"QueueUserAPC2".as_ptr().cast()) }.is_some()
}
fn available(profile: &Profile) -> Option<&Placement> {
let placement = profile.placement.as_ref().unwrap();
if !placement_supported() {
let reason = placement.unavailable.as_deref().unwrap_or_default();
assert!(reason.contains("QueueUserAPC2"), "{reason:?}");
assert_eq!(placement.readings, []);
assert!(profile.report().contains("no readings: "));
return None;
}
assert!(
placement.unavailable.is_none(),
"{:?}",
placement.unavailable
);
Some(placement)
}
fn placed_index(placement: &Placement, name: &str) -> usize {
let found: Vec<usize> = (0..placement.threads.len())
.filter(|&index| placement.threads[index].name == name)
.collect();
assert_eq!(found.len(), 1, "{name}: {:?}", placement.threads);
found[0]
}
fn placed(mode: PlacementMode, run: Duration) -> Profile {
let work = Workload::start(&["mstest-place-busy"], &["mstest-place-idle"]);
let config = Config::parse("mstest-place")
.unwrap()
.with_placement(mode)
.with_highlight_threads(["place-idle"]);
let sampler = Sampler::start(config).unwrap();
thread::sleep(run);
let profile = sampler.stop().unwrap();
work.finish();
profile
}
#[test]
fn placement_only_takes_no_samples() {
let _turn = serial();
let profile = placed(PlacementMode::Only, Duration::from_millis(800));
assert_eq!(profile.stats.samples, 0);
let Some(placement) = available(&profile) else {
return;
};
assert_ne!(placement.cpus.len(), 0);
let busy = placed_index(placement, "mstest-place-busy");
let idle = placed_index(placement, "mstest-place-idle");
let count = |thread| {
placement
.readings
.iter()
.filter(|r| r.thread == thread)
.count()
};
assert!(count(busy) > 20, "{} busy readings", count(busy));
assert!(count(idle) > 0, "{} idle readings", count(idle));
assert!(
placement
.readings
.iter()
.all(|r| placement.cpus.iter().any(|cpu| cpu.index == r.cpu))
);
assert_eq!(placement.highlight_threads, ["place-idle"]);
let report = profile.report();
assert!(report.contains("=== placement"), "{report}");
assert!(report.contains("mstest-place-idle"), "{report}");
}
#[test]
fn placement_with_samples_does_both() {
let _turn = serial();
let profile = placed(PlacementMode::WithSamples, Duration::from_millis(800));
assert!(profile.stats.samples > 100);
let busy = thread_index(&profile, "mstest-place-busy");
assert!(split(&profile, busy).0 > 100);
let Some(placement) = available(&profile) else {
return;
};
let placed_busy = placed_index(placement, "mstest-place-busy");
assert!(
placement
.readings
.iter()
.filter(|r| r.thread == placed_busy)
.count()
> 20
);
}
#[test]
fn same_named_threads_are_read_apart() {
let _turn = serial();
let work = Workload::start(&["mstest-twin", "mstest-twin"], &[]);
let config = Config::parse("mstest-twin")
.unwrap()
.with_placement(PlacementMode::Only);
let sampler = Sampler::start(config).unwrap();
thread::sleep(Duration::from_millis(600));
let profile = sampler.stop().unwrap();
work.finish();
assert_eq!(profile.threads(), ["mstest-twin"]);
let Some(placement) = available(&profile) else {
return;
};
let twins: Vec<usize> = (0..placement.threads.len())
.filter(|&index| placement.threads[index].name == "mstest-twin")
.collect();
assert_eq!(twins.len(), 2, "{:?}", placement.threads);
assert_ne!(
placement.threads[twins[0]].tid,
placement.threads[twins[1]].tid
);
for &index in &twins {
let count = placement
.readings
.iter()
.filter(|r| r.thread == index)
.count();
assert!(count > 10, "twin {index}: {count} readings");
}
let report = profile.report();
assert!(report.contains("mstest-twin #1 (tid "), "{report}");
assert!(report.contains("mstest-twin #2 (tid "), "{report}");
}
#[test]
fn a_dump_asked_for_just_before_stop_is_written() {
let _turn = serial();
let dir = scratch("last-dump");
let work = Workload::start(&["mstest-last"], &[]);
let sampler = Sampler::start(Config::parse("mstest-last").unwrap()).unwrap();
thread::sleep(Duration::from_millis(300));
let handle = sampler.dump_handle();
handle.request(&dir, "last", 1.0).unwrap();
let profile = sampler.stop().unwrap();
work.finish();
assert_eq!(profile.dump_errors, [] as [String; 0]);
assert!(dir.join("last.folded").is_file());
assert!(handle.request(&dir, "after", 1.0).is_err());
std::fs::remove_dir_all(&dir).unwrap();
}
#[test]
fn rapid_start_and_stop_leak_nothing() {
let _turn = serial();
placed(PlacementMode::WithSamples, Duration::from_millis(50));
let before = handle_count();
let started = Instant::now();
for round in 0..30 {
let mode = match round % 3 {
0 => PlacementMode::Off,
1 => PlacementMode::WithSamples,
_ => PlacementMode::Only,
};
let profile = placed(mode, Duration::from_millis(5 + (round % 4) * 10));
assert_eq!(profile.dump_errors, [] as [String; 0]);
if mode != PlacementMode::Off {
assert!(profile.placement.is_some());
}
}
let first = Sampler::start(Config::parse("*").unwrap()).unwrap();
assert!(matches!(
Sampler::start(Config::parse("*").unwrap()),
Err(mapsample::Error::AlreadyRunning)
));
drop(first);
Sampler::start(Config::parse("*:100").unwrap())
.unwrap()
.stop()
.unwrap();
let after = handle_count();
assert!(
after <= before + 8,
"handles: {before} before, {after} after 30 runs ({:?})",
started.elapsed()
);
}