//! A sampling profiler for md-bench's workload, for a machine where `perf` is not //! allowed (`perf_event_paranoid` 4). Needs the `profile` feature and frame pointers: //! //! ```text //! RUSTFLAGS="-C force-frame-pointers=yes" cargo build --release --features profile \ //! --bin md-profile --target-dir target/profile //! md-profile CART [md-bench's options] --samples FILE //! scripts/profile.py target/profile/release/md-profile FILE //! ``` //! //! `ITIMER_PROF` raises SIGPROF every 250 µs of CPU time; the handler records the //! interrupted instruction and the return addresses up the frame-pointer chain (within //! this thread's stack), as offsets into the executable. `scripts/profile.py` turns //! them into functions with `addr2line`, inlined frames included. use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::Instant; use megadrive_rust::cartridge::{load_image, Cartridge}; use megadrive_rust::io::Device; use megadrive_rust::machine::machine; use megadrive_rust::trace::Run; use megadrive_rust::System; const DEPTH: usize = 24; const CAPACITY: usize = 1 << 18; static mut SAMPLES: [[usize; DEPTH]; CAPACITY] = [[0; DEPTH]; CAPACITY]; static TAKEN: AtomicUsize = AtomicUsize::new(0); static mut STACK: (usize, usize) = (0, 0); extern "C" fn on_sample(_: libc::c_int, _: *mut libc::siginfo_t, context: *mut libc::c_void) { let index = TAKEN.fetch_add(1, Ordering::Relaxed); if index >= CAPACITY { return; } // SAFETY: the handler runs on the one thread that was interrupted, and each sample // has its own slot; the stack bounds were set before the timer started. unsafe { let context = &*(context as *const libc::ucontext_t); let rip = context.uc_mcontext.gregs[libc::REG_RIP as usize] as usize; let mut rbp = context.uc_mcontext.gregs[libc::REG_RBP as usize] as usize; let slot = &mut *std::ptr::addr_of_mut!(SAMPLES[index]); slot[0] = rip; let (low, high) = STACK; let mut depth = 1; while depth < DEPTH && rbp >= low && rbp + 16 <= high && rbp % 8 == 0 { let next = *(rbp as *const usize); slot[depth] = *((rbp + 8) as *const usize); depth += 1; if next <= rbp { break; } rbp = next; } } } fn main() -> Result<(), String> { let mut args = std::env::args().skip(1); let mut run: Option = None; let mut options: Vec<(String, Option)> = Vec::new(); let mut out = String::from("samples.txt"); while let Some(arg) = args.next() { if arg == "--samples" { out = args.next().ok_or("--samples needs a value")?; } else if arg == "--no-fm" { options.push((arg, None)); } else if arg.starts_with("--") { let value = args.next().ok_or(format!("{arg} needs a value"))?; options.push((arg, Some(value))); } else if run.is_none() { run = Some(Run::new(arg)); } else { return Err(format!("unknown argument {arg}")); } } let mut run = run.ok_or("md-profile CART [options] --samples FILE")?; for (name, value) in options { let mut value = value.into_iter(); run.option(&name, &mut || { value.next().ok_or(format!("{name} needs a value")) })?; } let machine = machine(&run.machine).ok_or("unknown machine")?; let pads = [ Device::by_name(&run.pads[0])?, Device::by_name(&run.pads[1])?, ]; let image = load_image(&run.cartridge)?; let mut system = System::new( machine, Some(Cartridge::from_image(image)), Some(pads), None, ); if run.no_fm { system.board().dev.fm.enabled = false; } // SAFETY: plain libc calls on this thread's own attributes and the signal table. unsafe { let mut attr: libc::pthread_attr_t = std::mem::zeroed(); libc::pthread_getattr_np(libc::pthread_self(), &mut attr); let (mut base, mut size) = (std::ptr::null_mut(), 0usize); libc::pthread_attr_getstack(&attr, &mut base, &mut size); STACK = (base as usize, base as usize + size); let mut action: libc::sigaction = std::mem::zeroed(); action.sa_sigaction = on_sample as *const () as usize; action.sa_flags = libc::SA_SIGINFO | libc::SA_RESTART; libc::sigaction(libc::SIGPROF, &action, std::ptr::null_mut()); let tick = libc::timeval { tv_sec: 0, tv_usec: 250, }; let timer = libc::itimerval { it_interval: tick, it_value: tick, }; libc::setitimer(libc::ITIMER_PROF, &timer, std::ptr::null_mut()); } let started = Instant::now(); for frame in 0..run.frames { let held = run .presses .iter() .filter(|p| p.from <= frame && frame < p.to) .fold(0, |held, p| held | p.buttons); if let Some(device) = &mut system.board().dev.io.ports[0].device { device.set_pressed(held); } system .run_frame() .map_err(|l| format!("frame {frame}: {l}"))?; std::hint::black_box(system.take_audio()); let vdp = &system.board().vdp; std::hint::black_box(vdp.renderer.frame_rgb(&vdp.s)); } let seconds = started.elapsed().as_secs_f64(); // SAFETY: stops the timer before the samples are read. unsafe { let zero = libc::timeval { tv_sec: 0, tv_usec: 0, }; let timer = libc::itimerval { it_interval: zero, it_value: zero, }; libc::setitimer(libc::ITIMER_PROF, &timer, std::ptr::null_mut()); } // The executable's load address, to make the addresses offsets addr2line can read. let exe = std::fs::read_link("/proc/self/exe").map_err(|e| e.to_string())?; let maps = std::fs::read_to_string("/proc/self/maps").map_err(|e| e.to_string())?; let base = maps .lines() .find(|l| l.ends_with(exe.to_str().unwrap_or("?"))) .and_then(|l| l.split('-').next()) .and_then(|a| usize::from_str_radix(a, 16).ok()) .ok_or("no load address")?; let taken = TAKEN.load(Ordering::Relaxed).min(CAPACITY); let mut text = String::new(); // By index: each slot is read through a raw pointer to the static. #[allow(clippy::needless_range_loop)] for index in 0..taken { // SAFETY: the timer is stopped; nothing writes the samples any more. let slot = unsafe { &*std::ptr::addr_of!(SAMPLES[index]) }; let frames: Vec = slot .iter() .take_while(|&&a| a != 0) .map(|&a| format!("{:x}", a.wrapping_sub(base))) .collect(); text.push_str(&frames.join(" ")); text.push('\n'); } std::fs::write(&out, text).map_err(|e| e.to_string())?; eprintln!( "{taken} samples in {seconds:.2} s ({} frames) to {out}", run.frames ); Ok(()) }