// SPDX-License-Identifier: MIT //! sega32x-rust-fast: megadrive-rust-fast's md-profile for s32x-bench's workload. //! //! A sampling profiler for s32x-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 s32x-profile --target-dir target/profile //! s32x-profile CART --bios-dir DIR [s32x-bench's options] --samples FILE //! scripts/profile.py target/profile/release/s32x-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::trace::Press; use sega32x_rust::trace::Run; 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 = Run { cartridge: std::path::PathBuf::new(), bios_dir: std::path::PathBuf::new(), machine: "genesis".into(), frames: 900, presses: Vec::new(), resets: Vec::new(), no_fm: false, bus_frames: 0, steps: None, saves: Vec::new(), }; let mut out = String::from("samples.txt"); let mut cartridge = None; while let Some(arg) = args.next() { let mut value = || args.next().ok_or(format!("{arg} needs a value")); match arg.as_str() { "--samples" => out = value()?, "--no-fm" => run.no_fm = true, "--bios-dir" => run.bios_dir = value()?.into(), "--machine" => run.machine = value()?, "--frames" => run.frames = value()?.parse().map_err(|_| "bad --frames")?, "--press" => run.presses.push(Press::parse(&value()?)?), _ if arg.starts_with("--") => return Err(format!("unknown argument {arg}")), _ if cartridge.is_none() => cartridge = Some(std::path::PathBuf::from(&arg)), _ => return Err(format!("unknown argument {arg}")), } } run.cartridge = cartridge.ok_or("s32x-profile CART --bios-dir DIR [options] --samples FILE")?; let (_digest, mut system, _device) = run.build()?; // 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(()) }