//! A sampling profiler for the board, since `perf` is not allowed here: //! SIGPROF 1,000 times a second of CPU time, the interrupted instruction's //! address recorded, then `scripts/profile.py` maps the addresses to source //! lines (inlined frames included) with `addr2line`. //! //! cargo run --release --features profile --bin gameboy-profile -- [MACHINE:]ROM [--slices N] [--out FILE] //! //! (a2600-rust-fast's profiler, adapted.) The run is gameboy-bench's: skip-boot, the gate's //! input script, audio capture on. use std::path::Path; use std::sync::atomic::{AtomicUsize, Ordering}; use gameboy_rust::boot::read_image; use gameboy_rust::{load_cartridge, machine, Clock, GameBoy}; const SLICE_T: u64 = 70224; const BUTTONS: [&str; 8] = ["a", "b", "select", "start", "right", "left", "up", "down"]; const CAPACITY: usize = 1 << 20; static mut SAMPLES: [usize; CAPACITY] = [0; CAPACITY]; static COUNT: AtomicUsize = AtomicUsize::new(0); extern "C" fn on_prof(_: libc::c_int, _: *mut libc::siginfo_t, context: *mut libc::c_void) { // SAFETY: the kernel passes a ucontext_t; only the RIP is read, and each // slot is written once, by this handler, on this thread. unsafe { let ucontext = &*(context as *const libc::ucontext_t); let rip = ucontext.uc_mcontext.gregs[libc::REG_RIP as usize] as usize; let n = COUNT.fetch_add(1, Ordering::Relaxed); if n < CAPACITY { let samples = &raw mut SAMPLES; (*samples)[n] = rip; } } } fn main() { let mut slices = 1200u64; let mut out = "external/profile.txt".to_owned(); let mut game = None; let mut args = std::env::args().skip(1); while let Some(arg) = args.next() { match arg.as_str() { "--slices" => slices = args.next().expect("N").parse().expect("a number"), "--out" => out = args.next().expect("FILE"), _ => game = Some(arg), } } let game = game.expect("usage: gameboy-profile [MACHINE:]ROM [--slices N] [--out FILE]"); let (key, rom) = match game.split_once(':') { Some((k, r)) if machine(k).is_some() => (k.to_owned(), r.to_owned()), _ => ("dmg".to_owned(), game.clone()), }; let data = read_image(Path::new(&rom)).unwrap_or_else(|e| panic!("{e}")); let cart = load_cartridge(&data, Clock::Board).expect("cartridge"); let mut gb = GameBoy::new(cart, machine(&key).unwrap(), None).expect("board"); gb.hw.apu.capture = true; let script = std::fs::read_to_string(concat!( env!("CARGO_MANIFEST_DIR"), "/scripts/inputs/poke.txt" )) .unwrap(); let mut inputs = std::collections::HashMap::new(); for line in script.lines() { let words: Vec<&str> = line .split('#') .next() .unwrap_or("") .split_whitespace() .collect(); if let Some(first) = words.first() { inputs.insert( first.parse::().unwrap(), words[1..] .iter() .filter(|w| **w != "-") .map(|w| w.to_string()) .collect::>(), ); } } // SAFETY: installing a handler and an interval timer for this process. unsafe { let mut action: libc::sigaction = std::mem::zeroed(); action.sa_sigaction = on_prof 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: 1000, }; let timer = libc::itimerval { it_interval: tick, it_value: tick, }; libc::setitimer(libc::ITIMER_PROF, &timer, std::ptr::null_mut()); } let mut pressed: Vec = Vec::new(); for index in 0..slices { if let Some(wanted) = inputs.get(&index) { for name in BUTTONS { let (was, is) = ( pressed.iter().any(|p| p == name), wanted.iter().any(|w| w == name), ); if was != is { gb.set_pressed(name, is); } } pressed = wanted.clone(); } while gb.hw.t < (index + 1) * SLICE_T { gb.step(); } gb.hw.apu.take_samples(); } // SAFETY: stop the timer before reading the samples. 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()); } let maps = std::fs::read_to_string("/proc/self/maps").unwrap(); let exe = std::fs::read_link("/proc/self/exe").unwrap(); let base = maps .lines() .find(|line| line.ends_with(exe.to_str().unwrap())) .and_then(|line| usize::from_str_radix(line.split('-').next().unwrap(), 16).ok()) .expect("the executable's mapping"); let n = COUNT.load(Ordering::Relaxed).min(CAPACITY); let mut text = format!("{}\n", exe.display()); let samples = &raw const SAMPLES; for i in 0..n { // SAFETY: the timer is stopped, nothing writes SAMPLES any more. let rip = unsafe { (*samples)[i] }; text.push_str(&format!("{:x}\n", rip.wrapping_sub(base))); } std::fs::write(&out, text).unwrap(); eprintln!("{n} samples to {out}"); }