use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{RecvTimeoutError, SyncSender, sync_channel};
use std::sync::{Arc, Mutex, MutexGuard};
use std::thread::JoinHandle;
use std::time::Duration;
use crate::profile::check_plain_name;
use crate::{Config, Error, Profile, Ring};
pub const DUMP_WAIT: Duration = Duration::from_secs(10);
pub const MAX_DUMP_NAME: usize = 128;
static ACTIVE: AtomicBool = AtomicBool::new(false);
#[derive(Debug)]
struct ActiveClaim;
impl ActiveClaim {
fn claim() -> Result<Self, Error> {
ACTIVE
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
.map(|_| Self)
.map_err(|_| Error::AlreadyRunning)
}
}
impl Drop for ActiveClaim {
fn drop(&mut self) {
ACTIVE.store(false, Ordering::Release);
}
}
#[derive(Debug)]
pub(crate) struct DumpRequest {
dir: PathBuf,
name: String,
seconds: f64,
reply: Option<SyncSender<Result<Vec<PathBuf>, Error>>>,
}
#[derive(Debug, Default)]
struct Queue {
open: bool,
asked: usize,
requests: Vec<DumpRequest>,
}
#[derive(Debug)]
pub(crate) struct Shared {
stop: AtomicBool,
pending: AtomicBool,
queue: Mutex<Queue>,
max_dumps: usize,
}
impl Shared {
fn new(max_dumps: usize) -> Self {
Self {
stop: AtomicBool::new(false),
pending: AtomicBool::new(false),
queue: Mutex::new(Queue {
open: true,
..Queue::default()
}),
max_dumps,
}
}
fn lock(&self) -> MutexGuard<'_, Queue> {
self.queue
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
#[cfg_attr(not(all(windows, target_arch = "x86_64")), allow(dead_code))]
pub(crate) fn stopping(&self) -> bool {
self.stop.load(Ordering::Acquire)
}
#[cfg_attr(not(all(windows, target_arch = "x86_64")), allow(dead_code))]
pub(crate) fn stop_flag(&self) -> &AtomicBool {
&self.stop
}
fn request(
&self,
dir: &Path,
name: &str,
seconds: f64,
reply: Option<SyncSender<Result<Vec<PathBuf>, Error>>>,
) -> Result<(), Error> {
validate_dump(name, seconds)?;
let mut queue = self.lock();
if !queue.open || self.stopping() {
return Err(Error::NotRunning);
}
if queue.asked >= self.max_dumps {
return Err(Error::DumpLimit {
max: self.max_dumps,
});
}
queue.asked += 1;
queue.requests.push(DumpRequest {
dir: dir.to_owned(),
name: name.to_owned(),
seconds,
reply,
});
self.pending.store(true, Ordering::Release);
Ok(())
}
#[cfg_attr(not(all(windows, target_arch = "x86_64")), allow(dead_code))]
pub(crate) fn take_requests(&self) -> Vec<DumpRequest> {
if !self.pending.swap(false, Ordering::AcqRel) {
return Vec::new();
}
std::mem::take(&mut self.lock().requests)
}
#[cfg_attr(not(all(windows, target_arch = "x86_64")), allow(dead_code))]
pub(crate) fn drain_requests(&self) -> Vec<DumpRequest> {
let mut queue = self.lock();
self.pending.store(false, Ordering::Release);
std::mem::take(&mut queue.requests)
}
fn begin_stop(&self) {
let mut queue = self.lock();
queue.open = false;
self.stop.store(true, Ordering::Release);
}
fn close(&self) {
let mut queue = self.lock();
queue.open = false;
queue.requests.clear();
self.pending.store(false, Ordering::Release);
}
}
fn validate_dump(name: &str, seconds: f64) -> Result<(), Error> {
check_plain_name(name).map_err(Error::InvalidDump)?;
if !(seconds.is_finite() && seconds > 0.0) {
return Err(Error::InvalidDump(format!(
"duration {seconds}: expected a positive number of seconds"
)));
}
Ok(())
}
#[cfg_attr(not(all(windows, target_arch = "x86_64")), allow(dead_code))]
pub(crate) fn serve_dumps(
requests: Vec<DumpRequest>,
ring: &Ring,
now: u64,
template: &Profile,
errors: &mut Vec<String>,
) {
for request in requests {
let mut profile = ring.recent(now, request.seconds, &template.spec, template.hz);
profile.stats = template.stats;
profile.set_modules(template.modules().to_vec());
let result = profile.write_named(&request.dir, &request.name);
match request.reply {
Some(reply) => {
let _ = reply.try_send(result);
}
None => {
if let Err(error) = result {
errors.push(format!("{}: {error}", request.name));
}
}
}
}
}
#[derive(Debug)]
struct WorkerGuard {
shared: Arc<Shared>,
_claim: ActiveClaim,
}
impl Drop for WorkerGuard {
fn drop(&mut self) {
self.shared.close();
}
}
#[derive(Debug)]
pub struct Sampler {
shared: Arc<Shared>,
thread: Option<JoinHandle<Profile>>,
}
#[derive(Clone, Debug)]
pub struct DumpHandle {
shared: Arc<Shared>,
}
impl DumpHandle {
pub fn request(&self, dir: &Path, name: &str, seconds: f64) -> Result<(), Error> {
self.shared.request(dir, name, seconds, None)
}
}
impl Sampler {
pub fn start(config: Config) -> Result<Self, Error> {
#[cfg(all(windows, target_arch = "x86_64"))]
{
let max_dumps = config.max_dumps();
Self::launch(
max_dumps,
move |shared| crate::win64::run(&config, shared),
|job| {
std::thread::Builder::new()
.name("mapsample".into())
.spawn(job)
},
)
}
#[cfg(not(all(windows, target_arch = "x86_64")))]
{
drop(config);
Err(Error::UnsupportedPlatform)
}
}
pub fn from_env() -> Result<Option<Self>, Error> {
Config::from_env()?.map(Self::start).transpose()
}
#[cfg_attr(not(all(windows, target_arch = "x86_64")), allow(dead_code))]
fn launch(
max_dumps: usize,
run: impl FnOnce(&Shared) -> Profile + Send + 'static,
spawn: impl FnOnce(Box<dyn FnOnce() -> Profile + Send>) -> std::io::Result<JoinHandle<Profile>>,
) -> Result<Self, Error> {
let claim = ActiveClaim::claim()?;
let shared = Arc::new(Shared::new(max_dumps));
let guard = WorkerGuard {
shared: Arc::clone(&shared),
_claim: claim,
};
let thread = spawn(Box::new(move || {
let guard = guard;
let mut profile = run(&guard.shared);
for request in guard.shared.drain_requests() {
match request.reply {
Some(reply) => {
let _ = reply.try_send(Err(Error::NotRunning));
}
None => profile.dump_errors.push(format!(
"{}: the sampler stopped before writing it",
request.name
)),
}
}
profile
}))
.map_err(Error::Spawn)?;
Ok(Self {
shared,
thread: Some(thread),
})
}
#[must_use]
pub fn dump_handle(&self) -> DumpHandle {
DumpHandle {
shared: Arc::clone(&self.shared),
}
}
pub fn dump_recent(&self, dir: &Path, name: &str, seconds: f64) -> Result<Vec<PathBuf>, Error> {
let (reply, result) = sync_channel(1);
self.shared.request(dir, name, seconds, Some(reply))?;
match result.recv_timeout(DUMP_WAIT) {
Ok(written) => written,
Err(RecvTimeoutError::Timeout) => Err(Error::DumpTimeout),
Err(RecvTimeoutError::Disconnected) => Err(Error::NotRunning),
}
}
pub fn stop(mut self) -> Result<Profile, Error> {
self.shared.begin_stop();
match self.thread.take() {
Some(thread) => thread.join().map_err(|_| Error::WorkerPanicked),
None => Err(Error::NotRunning),
}
}
}
impl Drop for Sampler {
fn drop(&mut self) {
self.shared.begin_stop();
if let Some(thread) = self.thread.take() {
let _ = thread.join();
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Module, Stats};
static ONE_AT_A_TIME: Mutex<()> = Mutex::new(());
fn one_at_a_time() -> MutexGuard<'static, ()> {
ONE_AT_A_TIME
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
#[allow(clippy::unnecessary_wraps)]
fn spawn_thread(
job: Box<dyn FnOnce() -> Profile + Send>,
) -> std::io::Result<JoinHandle<Profile>> {
Ok(std::thread::spawn(job))
}
fn fake_run(shared: &Shared) -> Profile {
serving_run(shared, true)
}
fn serving_run(shared: &Shared, in_passes: bool) -> Profile {
let mut ring = Ring::new(10);
for second in 0..5 {
ring.add(second, "worker", true, 0x1000 + second, &[0x1000]);
}
let mut profile = Profile::new("fake", 100);
profile.set_modules(vec![Module {
name: "app.exe".into(),
path: "app.exe".into(),
base: 0x1000,
size: 0x1000,
}]);
let serve = |requests: Vec<DumpRequest>, profile: &mut Profile| {
if !requests.is_empty() {
let mut errors = std::mem::take(&mut profile.dump_errors);
serve_dumps(requests, &ring, 4, profile, &mut errors);
profile.dump_errors = errors;
}
};
while !shared.stopping() {
if in_passes {
serve(shared.take_requests(), &mut profile);
}
std::thread::sleep(Duration::from_millis(1));
}
serve(shared.drain_requests(), &mut profile);
profile.stats = Stats::default();
profile
}
#[test]
fn dumps_accepted_before_stop_are_written() {
let _one = one_at_a_time();
let dir = temp_dir("before-stop");
let sampler =
Sampler::launch(8, |shared| serving_run(shared, false), spawn_thread).unwrap();
let handle = sampler.dump_handle();
for name in ["a", "b", "c"] {
handle.request(&dir, name, 1.0).unwrap();
}
let profile = sampler.stop().unwrap();
assert!(profile.dump_errors.is_empty(), "{:?}", profile.dump_errors);
for name in ["a", "b", "c"] {
assert!(dir.join(format!("{name}.folded")).is_file(), "{name}");
}
assert!(matches!(
handle.request(&dir, "late", 1.0),
Err(Error::NotRunning)
));
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_body_that_drops_accepted_dumps_is_reported() {
let _one = one_at_a_time();
let sampler = Sampler::launch(
4,
|shared| {
while !shared.stopping() {
std::thread::sleep(Duration::from_millis(1));
}
Profile::default()
},
spawn_thread,
)
.unwrap();
sampler
.dump_handle()
.request(Path::new("."), "lost", 1.0)
.unwrap();
let profile = sampler.stop().unwrap();
assert_eq!(
profile.dump_errors,
["lost: the sampler stopped before writing it"]
);
}
#[test]
fn stopping_closes_admission_under_the_lock() {
let shared = Shared::new(4);
shared.request(Path::new("."), "queued", 1.0, None).unwrap();
shared.begin_stop();
assert!(shared.stopping());
assert!(matches!(
shared.request(Path::new("."), "after", 1.0, None),
Err(Error::NotRunning)
));
let drained = shared.drain_requests();
assert_eq!(drained.len(), 1);
assert_eq!(drained[0].name, "queued");
assert!(shared.drain_requests().is_empty());
}
#[test]
fn dump_names_share_the_profile_rules() {
let shared = Shared::new(8);
for bad in ["../up", "sub/x", "CON", "lpt1.txt", "/abs"] {
assert!(
matches!(
shared.request(Path::new("."), bad, 1.0, None),
Err(Error::InvalidDump(_))
),
"{bad:?}"
);
}
}
fn temp_dir(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("mapsample-{tag}-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
dir
}
#[test]
fn one_sampler_per_process() {
let _one = one_at_a_time();
let first = Sampler::launch(4, fake_run, spawn_thread).unwrap();
assert!(matches!(
Sampler::launch(4, fake_run, spawn_thread),
Err(Error::AlreadyRunning)
));
first.stop().unwrap();
Sampler::launch(4, fake_run, spawn_thread)
.unwrap()
.stop()
.unwrap();
}
#[test]
fn failed_spawn_releases_the_claim() {
let _one = one_at_a_time();
let failed = Sampler::launch(4, fake_run, |_| Err(std::io::Error::other("no threads")));
assert!(matches!(failed, Err(Error::Spawn(_))));
assert!(!ACTIVE.load(Ordering::Acquire));
Sampler::launch(4, fake_run, spawn_thread)
.unwrap()
.stop()
.unwrap();
}
#[test]
fn a_panicking_worker_reports_and_releases() {
let _one = one_at_a_time();
let sampler = Sampler::launch(
4,
|_| -> Profile { std::panic::panic_any("boom") },
spawn_thread,
)
.unwrap();
assert!(matches!(sampler.stop(), Err(Error::WorkerPanicked)));
assert!(!ACTIVE.load(Ordering::Acquire));
}
#[test]
fn blocking_dump_writes_files() {
let _one = one_at_a_time();
let dir = temp_dir("dump");
let sampler = Sampler::launch(4, fake_run, spawn_thread).unwrap();
let written = sampler.dump_recent(&dir, "stall-1", 2.0).unwrap();
assert_eq!(written.len(), 3);
let folded = std::fs::read_to_string(dir.join("stall-1.folded")).unwrap();
assert_eq!(folded.lines().count(), 3, "{folded}");
assert!(dir.join("stall-1.txt").is_file());
let modules = std::fs::read_to_string(dir.join("stall-1.modules.txt")).unwrap();
assert!(modules.contains("app.exe"), "{modules}");
sampler.stop().unwrap();
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn dump_budget_and_validation() {
let _one = one_at_a_time();
let dir = temp_dir("budget");
let sampler = Sampler::launch(2, fake_run, spawn_thread).unwrap();
let handle = sampler.dump_handle();
for bad in ["", ".", "..", "a/b", "a\\b", "c:x", "nul\0", "line\nbreak"] {
assert!(
matches!(handle.request(&dir, bad, 1.0), Err(Error::InvalidDump(_))),
"{bad:?}"
);
}
let long = "x".repeat(MAX_DUMP_NAME + 1);
assert!(handle.request(&dir, &long, 1.0).is_err());
for seconds in [0.0, -1.0, f64::NAN, f64::INFINITY] {
assert!(handle.request(&dir, "ok", seconds).is_err(), "{seconds}");
}
handle.request(&dir, "one", 1.0).unwrap();
sampler.dump_recent(&dir, "two", 1.0).unwrap();
assert!(matches!(
handle.request(&dir, "three", 1.0),
Err(Error::DumpLimit { max: 2 })
));
let profile = sampler.stop().unwrap();
assert!(profile.dump_errors.is_empty(), "{:?}", profile.dump_errors);
assert!(dir.join("one.folded").is_file());
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn failed_fire_and_forget_dumps_are_recorded() {
let _one = one_at_a_time();
let missing = temp_dir("missing").join("does-not-exist");
let sampler = Sampler::launch(4, fake_run, spawn_thread).unwrap();
sampler
.dump_handle()
.request(&missing, "lost", 1.0)
.unwrap();
assert!(matches!(
sampler.dump_recent(&missing, "also-lost", 1.0),
Err(Error::Io { .. })
));
let profile = sampler.stop().unwrap();
assert_eq!(profile.dump_errors.len(), 1, "{:?}", profile.dump_errors);
assert!(profile.dump_errors[0].starts_with("lost: "));
}
#[test]
fn handles_outliving_the_sampler_are_refused() {
let _one = one_at_a_time();
let sampler = Sampler::launch(4, fake_run, spawn_thread).unwrap();
let handle = sampler.dump_handle();
let clone = handle.clone();
drop(sampler);
assert!(matches!(
handle.request(Path::new("."), "late", 1.0),
Err(Error::NotRunning)
));
assert!(clone.request(Path::new("."), "late", 1.0).is_err());
}
#[test]
fn a_waiter_sees_a_sampler_that_never_serves() {
let _one = one_at_a_time();
let sampler = Sampler::launch(4, |_| Profile::default(), spawn_thread).unwrap();
std::thread::sleep(Duration::from_millis(20));
let result = sampler.dump_recent(Path::new("."), "never", 1.0);
assert!(matches!(result, Err(Error::NotRunning)), "{result:?}");
sampler.stop().unwrap();
}
#[test]
fn stopping_wakes_pending_waiters() {
let _one = one_at_a_time();
let shared = Shared::new(4);
let (reply, result) = sync_channel(1);
shared
.request(Path::new("."), "queued", 1.0, Some(reply))
.unwrap();
shared.close();
assert!(matches!(
result.recv_timeout(Duration::from_secs(1)),
Err(RecvTimeoutError::Disconnected)
));
assert!(shared.take_requests().is_empty());
assert!(matches!(
shared.request(Path::new("."), "x", 1.0, None),
Err(Error::NotRunning)
));
}
#[test]
fn handles_are_send_and_sync() {
fn check<T: Send + Sync>() {}
check::<DumpHandle>();
check::<Sampler>();
}
#[cfg(not(all(windows, target_arch = "x86_64")))]
#[test]
fn other_platforms_refuse_cleanly() {
let config = Config::parse("*").unwrap();
assert!(matches!(
Sampler::start(config),
Err(Error::UnsupportedPlatform)
));
}
}