Compare commits
3 Commits
aa3cc3df9b
...
adc333e6a6
Author | SHA1 | Date |
---|---|---|
|
adc333e6a6 | |
|
c223c80269 | |
|
7f9791c4c5 |
|
@ -1507,6 +1507,20 @@ dependencies = [
|
|||
"slab",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "fxprof-processed-profile"
|
||||
version = "0.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "25234f20a3ec0a962a61770cfe39ecf03cb529a6e474ad8cff025ed497eda557"
|
||||
dependencies = [
|
||||
"bitflags 2.9.1",
|
||||
"debugid",
|
||||
"rustc-hash 2.1.1",
|
||||
"serde",
|
||||
"serde_derive",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "gethostname"
|
||||
version = "0.4.3"
|
||||
|
@ -2140,10 +2154,12 @@ dependencies = [
|
|||
"egui_extras",
|
||||
"elf",
|
||||
"fixed",
|
||||
"fxprof-processed-profile",
|
||||
"gilrs",
|
||||
"hex",
|
||||
"image",
|
||||
"itertools 0.14.0",
|
||||
"normpath",
|
||||
"num-derive",
|
||||
"num-traits",
|
||||
"oneshot",
|
||||
|
@ -2569,6 +2585,15 @@ dependencies = [
|
|||
"minimal-lexical",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "normpath"
|
||||
version = "1.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c8911957c4b1549ac0dc74e30db9c8b0e66ddcd6d7acc33098f4c63a64a6d7ed"
|
||||
dependencies = [
|
||||
"windows-sys 0.59.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nu-ansi-term"
|
||||
version = "0.46.0"
|
||||
|
|
|
@ -22,11 +22,13 @@ egui-notify = "0.20"
|
|||
egui-winit = "0.32"
|
||||
egui-wgpu = { version = "0.32", features = ["winit"] }
|
||||
elf = "0.8"
|
||||
fxprof-processed-profile = "0.8"
|
||||
fixed = { version = "1.28", features = ["num-traits"] }
|
||||
gilrs = { version = "0.11", features = ["serde-serialize"] }
|
||||
hex = "0.4"
|
||||
image = { version = "0.25", default-features = false, features = ["png"] }
|
||||
itertools = "0.14"
|
||||
normpath = "1"
|
||||
num-derive = "0.4"
|
||||
num-traits = "0.2"
|
||||
oneshot = "0.1"
|
||||
|
|
10
src/app.rs
10
src/app.rs
|
@ -116,11 +116,6 @@ impl ApplicationHandler<UserEvent> for Application {
|
|||
server.launch(port);
|
||||
self.open(event_loop, Box::new(server));
|
||||
}
|
||||
if self.init_profiling {
|
||||
let mut profiler = ProfileWindow::new(SimId::Player1, self.client.clone());
|
||||
profiler.launch();
|
||||
self.open(event_loop, Box::new(profiler));
|
||||
}
|
||||
let app = GameWindow::new(
|
||||
self.client.clone(),
|
||||
self.proxy.clone(),
|
||||
|
@ -129,6 +124,11 @@ impl ApplicationHandler<UserEvent> for Application {
|
|||
SimId::Player1,
|
||||
);
|
||||
self.open(event_loop, Box::new(app));
|
||||
if self.init_profiling {
|
||||
let mut profiler = ProfileWindow::new(SimId::Player1, self.client.clone());
|
||||
profiler.launch();
|
||||
self.open(event_loop, Box::new(profiler));
|
||||
}
|
||||
}
|
||||
|
||||
fn window_event(
|
||||
|
|
|
@ -210,7 +210,7 @@ extern "C" fn on_execute(sim: *mut VB, address: u32, code: *const u16, length: c
|
|||
}
|
||||
}
|
||||
|
||||
let mut stopped = data.stop_reason.is_some();
|
||||
let mut stopped = data.stop_reason.is_some() || data.monitor.event.is_some();
|
||||
if data.step_from.is_some_and(|s| s != address) {
|
||||
data.step_from = None;
|
||||
data.stop_reason = Some(StopReason::Stepped);
|
||||
|
@ -247,7 +247,13 @@ extern "C" fn on_exception(sim: *mut VB, cause: *mut u16) -> c_int {
|
|||
// There is no way for the userdata to be null or otherwise invalid.
|
||||
let data: &mut VBState = unsafe { &mut *vb_get_user_data(sim).cast() };
|
||||
data.monitor.event = data.monitor.queued_event.take();
|
||||
data.monitor.queued_event = Some(SimEvent::Interrupt(unsafe { *cause }));
|
||||
let cause = unsafe { *cause };
|
||||
let pc = if cause == 0xff70 {
|
||||
0xffffff60
|
||||
} else {
|
||||
(cause & 0xfff0) as u32 | 0xffff0000
|
||||
};
|
||||
data.monitor.queued_event = Some(SimEvent::Interrupt(cause, pc));
|
||||
unsafe { vb_set_exception_callback(sim, None) };
|
||||
unsafe { vb_set_fetch_callback(sim, Some(on_fetch)) };
|
||||
if data.monitor.event.is_some() { 1 } else { 0 }
|
||||
|
@ -319,7 +325,8 @@ extern "C" fn on_write(
|
|||
pub enum SimEvent {
|
||||
Call(u32),
|
||||
Return,
|
||||
Interrupt(u16),
|
||||
Halt,
|
||||
Interrupt(u16, u32),
|
||||
Reti,
|
||||
}
|
||||
|
||||
|
@ -327,6 +334,7 @@ struct EventMonitor {
|
|||
enabled: bool,
|
||||
event: Option<SimEvent>,
|
||||
queued_event: Option<SimEvent>,
|
||||
just_halted: bool,
|
||||
}
|
||||
|
||||
impl EventMonitor {
|
||||
|
@ -335,6 +343,7 @@ impl EventMonitor {
|
|||
enabled: false,
|
||||
event: None,
|
||||
queued_event: None,
|
||||
just_halted: false,
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -343,7 +352,8 @@ impl EventMonitor {
|
|||
self.queued_event.is_some()
|
||||
}
|
||||
|
||||
fn do_detect_event(&self, sim: *mut VB, address: u32, code: &[u16]) -> Option<SimEvent> {
|
||||
fn do_detect_event(&mut self, sim: *mut VB, address: u32, code: &[u16]) -> Option<SimEvent> {
|
||||
const HALT_OPCODE: u16 = 0b011010;
|
||||
const JAL_OPCODE: u16 = 0b101011;
|
||||
const JMP_OPCODE: u16 = 0b000110;
|
||||
const RETI_OPCODE: u16 = 0b011001;
|
||||
|
@ -359,6 +369,18 @@ impl EventMonitor {
|
|||
|
||||
let opcode = code[0] >> 10;
|
||||
|
||||
if opcode == HALT_OPCODE {
|
||||
if !self.just_halted {
|
||||
self.just_halted = true;
|
||||
self.event = Some(SimEvent::Halt);
|
||||
} else {
|
||||
self.just_halted = false;
|
||||
}
|
||||
// Don't _return_ an event, we want to emit this right away.
|
||||
// If the CPU is halting, no other callbacks will run for a long time.
|
||||
return None;
|
||||
}
|
||||
|
||||
if opcode == JAL_OPCODE {
|
||||
let disp = format_iv_disp(code);
|
||||
if disp != 4 {
|
||||
|
|
267
src/profiler.rs
267
src/profiler.rs
|
@ -1,22 +1,25 @@
|
|||
use std::{
|
||||
collections::HashMap,
|
||||
path::PathBuf,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
sync::{Arc, Mutex},
|
||||
thread,
|
||||
};
|
||||
|
||||
use anyhow::Result;
|
||||
use tokio::{select, sync::mpsc};
|
||||
use wholesym::{SymbolManager, SymbolMap};
|
||||
|
||||
use crate::emulator::{EmulatorClient, EmulatorCommand, ProfileEvent, SimEvent, SimId};
|
||||
use recording::Recording;
|
||||
use state::ProgramState;
|
||||
|
||||
mod recording;
|
||||
mod state;
|
||||
mod symbols;
|
||||
|
||||
pub struct Profiler {
|
||||
sim_id: SimId,
|
||||
client: EmulatorClient,
|
||||
running: Arc<AtomicBool>,
|
||||
status: Arc<Mutex<ProfilerStatus>>,
|
||||
action: Option<mpsc::UnboundedSender<RecordingAction>>,
|
||||
killer: Option<oneshot::Sender<()>>,
|
||||
}
|
||||
|
||||
|
@ -25,21 +28,24 @@ impl Profiler {
|
|||
Self {
|
||||
sim_id,
|
||||
client,
|
||||
running: Arc::new(AtomicBool::new(false)),
|
||||
status: Arc::new(Mutex::new(ProfilerStatus::Disabled)),
|
||||
action: None,
|
||||
killer: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn started(&self) -> bool {
|
||||
self.running.load(Ordering::Relaxed)
|
||||
pub fn status(&self) -> ProfilerStatus {
|
||||
self.status.lock().unwrap().clone()
|
||||
}
|
||||
|
||||
pub fn start(&mut self) {
|
||||
pub fn enable(&mut self) {
|
||||
let sim_id = self.sim_id;
|
||||
let client = self.client.clone();
|
||||
let running = self.running.clone();
|
||||
let (tx, rx) = oneshot::channel();
|
||||
self.killer = Some(tx);
|
||||
let status = self.status.clone();
|
||||
let (action_tx, action_rx) = mpsc::unbounded_channel();
|
||||
self.action = Some(action_tx);
|
||||
let (killer_tx, killer_rx) = oneshot::channel();
|
||||
self.killer = Some(killer_tx);
|
||||
thread::spawn(move || {
|
||||
tokio::runtime::Builder::new_current_thread()
|
||||
.enable_all()
|
||||
|
@ -47,130 +53,183 @@ impl Profiler {
|
|||
.unwrap()
|
||||
.block_on(async move {
|
||||
select! {
|
||||
_ = run_profile(sim_id, client, running.clone()) => {}
|
||||
_ = rx => {
|
||||
running.store(false, Ordering::Relaxed);
|
||||
_ = run_profile(sim_id, client, status.clone(), action_rx) => {}
|
||||
_ = killer_rx => {
|
||||
*status.lock().unwrap() = ProfilerStatus::Disabled;
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
|
||||
pub fn stop(&mut self) {
|
||||
pub fn disable(&mut self) {
|
||||
if let Some(killer) = self.killer.take() {
|
||||
let _ = killer.send(());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start_recording(&mut self) {
|
||||
if let Some(action) = &self.action {
|
||||
let _ = action.send(RecordingAction::Start);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn finish_recording(&mut self) -> oneshot::Receiver<Vec<u8>> {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
if let Some(action) = &self.action {
|
||||
let _ = action.send(RecordingAction::Finish(tx));
|
||||
}
|
||||
rx
|
||||
}
|
||||
|
||||
pub fn cancel_recording(&mut self) {
|
||||
if let Some(action) = &self.action {
|
||||
let _ = action.send(RecordingAction::Cancel);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_profile(sim_id: SimId, client: EmulatorClient, running: Arc<AtomicBool>) {
|
||||
impl Drop for Profiler {
|
||||
fn drop(&mut self) {
|
||||
self.disable();
|
||||
}
|
||||
}
|
||||
|
||||
async fn run_profile(
|
||||
sim_id: SimId,
|
||||
client: EmulatorClient,
|
||||
status: Arc<Mutex<ProfilerStatus>>,
|
||||
mut action_source: mpsc::UnboundedReceiver<RecordingAction>,
|
||||
) {
|
||||
let (profile_sync, mut profile_source) = mpsc::unbounded_channel();
|
||||
client.send_command(EmulatorCommand::StartProfiling(sim_id, profile_sync));
|
||||
|
||||
running.store(true, Ordering::Relaxed);
|
||||
*status.lock().unwrap() = ProfilerStatus::Enabled;
|
||||
|
||||
let mut session = None;
|
||||
while let Some(event) = profile_source.recv().await {
|
||||
match event {
|
||||
ProfileEvent::Start { file_path } => {
|
||||
session = Some(ProfileSession::new(file_path).await);
|
||||
let mut session = ProfilerSession::new();
|
||||
loop {
|
||||
select! {
|
||||
maybe_event = profile_source.recv() => {
|
||||
let Some(event) = maybe_event else {
|
||||
break; // emulator thread disconnected
|
||||
};
|
||||
if let Err(error) = handle_event(event, &mut session).await {
|
||||
*status.lock().unwrap() = ProfilerStatus::Error(error.to_string());
|
||||
return;
|
||||
}
|
||||
}
|
||||
maybe_action = action_source.recv() => {
|
||||
let Some(action) = maybe_action else {
|
||||
break; // ui thread disconnected
|
||||
};
|
||||
handle_action(action, &mut session, &status);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
*status.lock().unwrap() = ProfilerStatus::Disabled;
|
||||
}
|
||||
|
||||
async fn handle_event(event: ProfileEvent, session: &mut ProfilerSession) -> Result<()> {
|
||||
match event {
|
||||
ProfileEvent::Start { file_path } => session.start_profiling(file_path).await,
|
||||
ProfileEvent::Update { cycles, event } => {
|
||||
if let Some(session) = &mut session {
|
||||
session.track_elapsed_cycles(cycles);
|
||||
session.track_elapsed_cycles(cycles)?;
|
||||
if let Some(event) = event {
|
||||
session.track_event(event);
|
||||
session.track_event(event)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
running.store(false, Ordering::Release);
|
||||
}
|
||||
|
||||
struct ProfileSession {
|
||||
symbol_map: SymbolMap,
|
||||
call_stacks: HashMap<u16, Vec<StackFrame>>,
|
||||
context_stack: Vec<u16>,
|
||||
fn handle_action(
|
||||
action: RecordingAction,
|
||||
session: &mut ProfilerSession,
|
||||
status: &Mutex<ProfilerStatus>,
|
||||
) {
|
||||
match action {
|
||||
RecordingAction::Start => {
|
||||
session.start_recording();
|
||||
*status.lock().unwrap() = ProfilerStatus::Recording;
|
||||
}
|
||||
RecordingAction::Finish(rx) => {
|
||||
if let Some(bytes) = session.finish_recording() {
|
||||
let _ = rx.send(bytes);
|
||||
}
|
||||
*status.lock().unwrap() = ProfilerStatus::Enabled;
|
||||
}
|
||||
RecordingAction::Cancel => {
|
||||
session.cancel_recording();
|
||||
*status.lock().unwrap() = ProfilerStatus::Enabled;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct StackFrame {
|
||||
#[expect(dead_code)]
|
||||
address: Option<u32>,
|
||||
cycles: u64,
|
||||
#[derive(Clone)]
|
||||
pub enum ProfilerStatus {
|
||||
Disabled,
|
||||
Enabled,
|
||||
Recording,
|
||||
Error(String),
|
||||
}
|
||||
|
||||
impl ProfileSession {
|
||||
async fn new(file_path: PathBuf) -> Self {
|
||||
let symbol_manager = SymbolManager::with_config(Default::default());
|
||||
let symbol_map = symbol_manager
|
||||
.load_symbol_map_for_binary_at_path(&file_path, None)
|
||||
.await
|
||||
.expect("cannae load symbols");
|
||||
let mut call_stacks = HashMap::new();
|
||||
call_stacks.insert(
|
||||
0,
|
||||
vec![StackFrame {
|
||||
address: None,
|
||||
cycles: 0,
|
||||
}],
|
||||
);
|
||||
impl ProfilerStatus {
|
||||
pub fn enabled(&self) -> bool {
|
||||
matches!(self, Self::Enabled | Self::Recording)
|
||||
}
|
||||
}
|
||||
|
||||
enum RecordingAction {
|
||||
Start,
|
||||
Finish(oneshot::Sender<Vec<u8>>),
|
||||
Cancel,
|
||||
}
|
||||
|
||||
struct ProfilerSession {
|
||||
program: Option<ProgramState>,
|
||||
recording: Option<Recording>,
|
||||
}
|
||||
|
||||
impl ProfilerSession {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
symbol_map,
|
||||
call_stacks,
|
||||
context_stack: vec![],
|
||||
program: None,
|
||||
recording: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn track_elapsed_cycles(&mut self, cycles: u32) {
|
||||
let code = self.context_stack.last().copied().unwrap_or(0);
|
||||
let Some(stack) = self.call_stacks.get_mut(&code) else {
|
||||
panic!("missing stack {code:04x}");
|
||||
};
|
||||
for frame in stack {
|
||||
frame.cycles += cycles as u64;
|
||||
async fn start_profiling(&mut self, file_path: PathBuf) -> Result<()> {
|
||||
self.program = Some(ProgramState::new(file_path).await?);
|
||||
self.recording = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn track_elapsed_cycles(&mut self, cycles: u32) -> Result<()> {
|
||||
if let (Some(state), Some(recording)) = (&self.program, &mut self.recording) {
|
||||
recording.track_elapsed_cycles(state, cycles);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn track_event(&mut self, event: SimEvent) -> Result<()> {
|
||||
if let Some(program) = &mut self.program {
|
||||
program.track_event(event)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn start_recording(&mut self) {
|
||||
if let Some(program) = &self.program {
|
||||
self.recording = Some(Recording::new(program));
|
||||
}
|
||||
}
|
||||
|
||||
fn track_event(&mut self, event: SimEvent) {
|
||||
match event {
|
||||
SimEvent::Interrupt(code) => {
|
||||
self.context_stack.push(code);
|
||||
if self.call_stacks.insert(code, vec![]).is_some() {
|
||||
panic!("{code:04x} fired twice");
|
||||
}
|
||||
}
|
||||
SimEvent::Reti => {
|
||||
let Some(code) = self.context_stack.pop() else {
|
||||
panic!("reti when not in interrupt");
|
||||
};
|
||||
if self.call_stacks.remove(&code).is_none() {
|
||||
panic!("{code:04x} popped but never called")
|
||||
}
|
||||
}
|
||||
SimEvent::Call(addr) => {
|
||||
let code = self.context_stack.last().copied().unwrap_or(0);
|
||||
let Some(stack) = self.call_stacks.get_mut(&code) else {
|
||||
panic!("missing stack {code:04x}");
|
||||
};
|
||||
let name = self
|
||||
.symbol_map
|
||||
.lookup_sync(wholesym::LookupAddress::Svma(addr as u64));
|
||||
println!("depth {}: {:?}", stack.len(), name);
|
||||
stack.push(StackFrame {
|
||||
address: Some(addr),
|
||||
cycles: 0,
|
||||
});
|
||||
}
|
||||
SimEvent::Return => {
|
||||
let code = self.context_stack.last().copied().unwrap_or(0);
|
||||
let Some(stack) = self.call_stacks.get_mut(&code) else {
|
||||
panic!("missing stack {code:04x}");
|
||||
};
|
||||
if stack.pop().is_none() {
|
||||
panic!("returned from {code:04x} but stack was empty");
|
||||
}
|
||||
}
|
||||
fn finish_recording(&mut self) -> Option<Vec<u8>> {
|
||||
self.recording.take().map(|r| r.finish())
|
||||
}
|
||||
|
||||
fn cancel_recording(&mut self) {
|
||||
self.recording.take();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,114 @@
|
|||
use std::collections::HashMap;
|
||||
|
||||
use fxprof_processed_profile::{
|
||||
CategoryHandle, CpuDelta, Frame, FrameFlags, FrameInfo, ProcessHandle, Profile,
|
||||
ReferenceTimestamp, SamplingInterval, StackHandle, ThreadHandle, Timestamp,
|
||||
};
|
||||
|
||||
use crate::profiler::state::{ProgramState, RESET_CODE, StackFrame};
|
||||
|
||||
pub struct Recording {
|
||||
profile: Profile,
|
||||
process: ProcessHandle,
|
||||
threads: HashMap<u16, ThreadHandle>,
|
||||
now: u64,
|
||||
}
|
||||
|
||||
impl Recording {
|
||||
pub fn new(state: &ProgramState) -> Self {
|
||||
let symbol_file = state.symbol_file();
|
||||
|
||||
let name = &symbol_file.name();
|
||||
let reference_timestamp = ReferenceTimestamp::from_millis_since_unix_epoch(0.0);
|
||||
let interval = SamplingInterval::from_hz(20_000_000.0);
|
||||
let mut profile = Profile::new(name, reference_timestamp, interval);
|
||||
|
||||
let process = profile.add_process(name, 1, Timestamp::from_nanos_since_reference(0));
|
||||
|
||||
let lib = profile.add_lib(symbol_file.library_info().clone());
|
||||
profile.add_lib_mapping(process, lib, 0x00000000, 0xffffffff, 0);
|
||||
|
||||
let mut me = Self {
|
||||
profile,
|
||||
process,
|
||||
threads: HashMap::new(),
|
||||
now: 0,
|
||||
};
|
||||
me.track_elapsed_cycles(state, 0);
|
||||
me
|
||||
}
|
||||
|
||||
pub fn track_elapsed_cycles(&mut self, state: &ProgramState, cycles: u32) {
|
||||
self.now += cycles as u64;
|
||||
let timestamp = Timestamp::from_nanos_since_reference(self.now * 50);
|
||||
let weight = 1;
|
||||
|
||||
let active_code = if let Some((code, frames)) = state.current_stack() {
|
||||
let thread = *self.threads.entry(code).or_insert_with(|| {
|
||||
let process = self.process;
|
||||
let tid = code as u32;
|
||||
let start_time = Timestamp::from_nanos_since_reference(self.now * 50);
|
||||
let is_main = code == RESET_CODE;
|
||||
let thread = self.profile.add_thread(process, tid, start_time, is_main);
|
||||
self.profile
|
||||
.set_thread_name(thread, &thread_name_for_code(code));
|
||||
thread
|
||||
});
|
||||
|
||||
let stack = self.handle_for_stack(thread, frames);
|
||||
let cpu_delta = CpuDelta::from_nanos((self.now - cycles as u64) * 50);
|
||||
self.profile
|
||||
.add_sample(thread, timestamp, stack, cpu_delta, weight);
|
||||
Some(code)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
for (code, thread) in &self.threads {
|
||||
if active_code == Some(*code) {
|
||||
continue;
|
||||
}
|
||||
self.profile
|
||||
.add_sample_same_stack_zero_cpu(*thread, timestamp, weight);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn finish(self) -> Vec<u8> {
|
||||
serde_json::to_vec(&self.profile).expect("could not serialize profile")
|
||||
}
|
||||
|
||||
fn handle_for_stack(
|
||||
&mut self,
|
||||
thread: ThreadHandle,
|
||||
frames: &[StackFrame],
|
||||
) -> Option<StackHandle> {
|
||||
self.profile.intern_stack_frames(
|
||||
thread,
|
||||
frames.iter().map(|f| FrameInfo {
|
||||
frame: Frame::InstructionPointer(f.address as u64),
|
||||
category_pair: CategoryHandle::OTHER.into(),
|
||||
flags: FrameFlags::empty(),
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
fn thread_name_for_code(code: u16) -> std::borrow::Cow<'static, str> {
|
||||
match code {
|
||||
RESET_CODE => "Main".into(),
|
||||
0xffd0 => "Duplexed exception".into(),
|
||||
0xfe40 => "VIP interrupt".into(),
|
||||
0xfe30 => "Communication interrupt".into(),
|
||||
0xfe20 => "Game pak interrupt".into(),
|
||||
0xfe10 => "Timer interrupt".into(),
|
||||
0xfe00 => "Game pad interrupt".into(),
|
||||
0xffc0 => "Address trap".into(),
|
||||
0xffa0..0xffc0 => format!("Trap (vector {})", code - 0xffa0).into(),
|
||||
0xff90 => "Illegal opcode exception".into(),
|
||||
0xff80 => "Zero division exception".into(),
|
||||
0xff60 => "Floating-point reserved operand exception".into(),
|
||||
0xff70 => "Floating-point invalid operation exception".into(),
|
||||
0xff68 => "Floating-point zero division exception".into(),
|
||||
0xff64 => "Floating-point overflow exception".into(),
|
||||
other => format!("Unrecognized handler (0x{other:04x})").into(),
|
||||
}
|
||||
}
|
|
@ -0,0 +1,104 @@
|
|||
use std::{collections::HashMap, path::PathBuf};
|
||||
|
||||
use anyhow::{Result, bail};
|
||||
|
||||
use crate::{emulator::SimEvent, profiler::symbols::SymbolFile};
|
||||
|
||||
pub struct ProgramState {
|
||||
symbol_file: SymbolFile,
|
||||
call_stacks: HashMap<u16, Vec<StackFrame>>,
|
||||
context_stack: Vec<u16>,
|
||||
}
|
||||
|
||||
pub struct StackFrame {
|
||||
pub address: u32,
|
||||
}
|
||||
|
||||
pub const RESET_CODE: u16 = 0xfff0;
|
||||
impl ProgramState {
|
||||
pub async fn new(file_path: PathBuf) -> Result<Self> {
|
||||
let symbol_file = SymbolFile::load(&file_path).await?;
|
||||
let mut call_stacks = HashMap::new();
|
||||
call_stacks.insert(
|
||||
RESET_CODE,
|
||||
vec![StackFrame {
|
||||
address: 0xfffffff0,
|
||||
}],
|
||||
);
|
||||
Ok(Self {
|
||||
symbol_file,
|
||||
call_stacks,
|
||||
context_stack: vec![RESET_CODE],
|
||||
})
|
||||
}
|
||||
|
||||
pub fn symbol_file(&self) -> &SymbolFile {
|
||||
&self.symbol_file
|
||||
}
|
||||
|
||||
pub fn current_stack(&self) -> Option<(u16, &[StackFrame])> {
|
||||
let code = self.context_stack.last()?;
|
||||
let call_stack = self.call_stacks.get(code)?;
|
||||
Some((*code, call_stack))
|
||||
}
|
||||
|
||||
pub fn track_event(&mut self, event: SimEvent) -> Result<()> {
|
||||
match event {
|
||||
SimEvent::Call(address) => {
|
||||
let Some(code) = self.context_stack.last() else {
|
||||
bail!("How did we call anything when we're halted?");
|
||||
};
|
||||
let Some(stack) = self.call_stacks.get_mut(code) else {
|
||||
bail!("missing stack {code:04x}");
|
||||
};
|
||||
stack.push(StackFrame { address });
|
||||
}
|
||||
SimEvent::Return => {
|
||||
let Some(code) = self.context_stack.last() else {
|
||||
bail!("how did we return when we're halted?");
|
||||
};
|
||||
let Some(stack) = self.call_stacks.get_mut(code) else {
|
||||
bail!("missing stack {code:04x}");
|
||||
};
|
||||
if stack.pop().is_none() {
|
||||
bail!("returned from {code:04x} but stack was empty");
|
||||
}
|
||||
if stack.is_empty() {
|
||||
bail!("returned to oblivion");
|
||||
}
|
||||
}
|
||||
SimEvent::Halt => {
|
||||
let Some(RESET_CODE) = self.context_stack.pop() else {
|
||||
bail!("halted when not in an interrupt");
|
||||
};
|
||||
}
|
||||
SimEvent::Interrupt(code, address) => {
|
||||
// if the CPU was halted before, wake it up now
|
||||
if self.context_stack.is_empty() {
|
||||
self.context_stack.push(RESET_CODE);
|
||||
}
|
||||
|
||||
self.context_stack.push(code);
|
||||
if self
|
||||
.call_stacks
|
||||
.insert(code, vec![StackFrame { address }])
|
||||
.is_some()
|
||||
{
|
||||
bail!("{code:04x} fired twice");
|
||||
}
|
||||
}
|
||||
SimEvent::Reti => {
|
||||
let Some(code) = self.context_stack.pop() else {
|
||||
bail!("RETI when halted");
|
||||
};
|
||||
if code == RESET_CODE {
|
||||
bail!("RETI when not in interrupt");
|
||||
}
|
||||
if self.call_stacks.remove(&code).is_none() {
|
||||
bail!("{code:04x} popped but never called");
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
|
@ -0,0 +1,67 @@
|
|||
use std::{path::Path, sync::Arc};
|
||||
|
||||
use anyhow::Result;
|
||||
use fxprof_processed_profile::{LibraryInfo, Symbol, SymbolTable};
|
||||
use wholesym::{SymbolManager, samply_symbols::demangle_any};
|
||||
|
||||
pub struct SymbolFile {
|
||||
library_info: LibraryInfo,
|
||||
}
|
||||
|
||||
impl SymbolFile {
|
||||
pub async fn load(file_path: &Path) -> Result<Self> {
|
||||
let normalized = normpath::PathExt::normalize(file_path)?;
|
||||
let library_info =
|
||||
SymbolManager::library_info_for_binary_at_path(normalized.as_path(), None).await?;
|
||||
|
||||
let symbol_manager = SymbolManager::with_config(Default::default());
|
||||
let symbol_map = symbol_manager
|
||||
.load_symbol_map_for_binary_at_path(normalized.as_path(), None)
|
||||
.await?;
|
||||
|
||||
let name = library_info
|
||||
.name
|
||||
.or_else(|| {
|
||||
normalized
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
})
|
||||
.unwrap_or("game".to_string());
|
||||
let debug_name = library_info.debug_name.unwrap_or_else(|| name.clone());
|
||||
let path = library_info
|
||||
.path
|
||||
.unwrap_or_else(|| normalized.into_os_string().to_string_lossy().into_owned());
|
||||
let debug_path = library_info.debug_path.unwrap_or_else(|| path.clone());
|
||||
let debug_id = library_info.debug_id.unwrap_or_default();
|
||||
let code_id = library_info.code_id.map(|id| id.to_string());
|
||||
let arch = library_info.arch;
|
||||
let symbols = symbol_map
|
||||
.iter_symbols()
|
||||
.map(|(address, name)| Symbol {
|
||||
address: address + 0x07000000,
|
||||
size: None,
|
||||
name: demangle_any(&name),
|
||||
})
|
||||
.collect();
|
||||
Ok(Self {
|
||||
library_info: LibraryInfo {
|
||||
name,
|
||||
debug_name,
|
||||
path,
|
||||
debug_path,
|
||||
debug_id,
|
||||
code_id,
|
||||
arch,
|
||||
symbol_table: Some(Arc::new(SymbolTable::new(symbols))),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
pub fn name(&self) -> &str {
|
||||
&self.library_info.name
|
||||
}
|
||||
|
||||
pub fn library_info(&self) -> &LibraryInfo {
|
||||
&self.library_info
|
||||
}
|
||||
}
|
|
@ -1,14 +1,19 @@
|
|||
use egui::{CentralPanel, ViewportBuilder, ViewportId};
|
||||
use std::{fs, time::Duration};
|
||||
|
||||
use anyhow::Result;
|
||||
use egui::{Button, CentralPanel, Checkbox, ViewportBuilder, ViewportId};
|
||||
use egui_notify::{Anchor, Toast, Toasts};
|
||||
|
||||
use crate::{
|
||||
emulator::{EmulatorClient, SimId},
|
||||
profiler::Profiler,
|
||||
profiler::{Profiler, ProfilerStatus},
|
||||
window::AppWindow,
|
||||
};
|
||||
|
||||
pub struct ProfileWindow {
|
||||
sim_id: SimId,
|
||||
profiler: Profiler,
|
||||
toasts: Toasts,
|
||||
}
|
||||
|
||||
impl ProfileWindow {
|
||||
|
@ -16,11 +21,47 @@ impl ProfileWindow {
|
|||
Self {
|
||||
sim_id,
|
||||
profiler: Profiler::new(sim_id, client),
|
||||
toasts: Toasts::new()
|
||||
.with_anchor(Anchor::BottomLeft)
|
||||
.with_margin((10.0, 10.0).into())
|
||||
.reverse(true),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn launch(&mut self) {
|
||||
self.profiler.start();
|
||||
self.profiler.enable();
|
||||
}
|
||||
|
||||
fn finish_recording(&mut self) {
|
||||
match self.try_finish_recording() {
|
||||
Ok(Some(path)) => {
|
||||
let mut toast = Toast::info(format!("Saved to {path}"));
|
||||
toast.duration(Some(Duration::from_secs(5)));
|
||||
self.toasts.add(toast);
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(error) => {
|
||||
let mut toast = Toast::error(format!("{error:#}"));
|
||||
toast.duration(Some(Duration::from_secs(5)));
|
||||
self.toasts.add(toast);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn try_finish_recording(&mut self) -> Result<Option<String>> {
|
||||
let bytes_receiver = self.profiler.finish_recording();
|
||||
let file = rfd::FileDialog::new()
|
||||
.add_filter("Profiler files", &["json"])
|
||||
.set_file_name("profile.json")
|
||||
.save_file();
|
||||
if let Some(path) = file {
|
||||
let bytes = pollster::block_on(bytes_receiver)?;
|
||||
fs::write(&path, bytes)?;
|
||||
Ok(Some(path.display().to_string()))
|
||||
} else {
|
||||
self.profiler.cancel_recording();
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -40,15 +81,46 @@ impl AppWindow for ProfileWindow {
|
|||
}
|
||||
|
||||
fn show(&mut self, ctx: &egui::Context) {
|
||||
let status = self.profiler.status();
|
||||
let recording = matches!(status, ProfilerStatus::Recording);
|
||||
CentralPanel::default().show(ctx, |ui| {
|
||||
let mut started = self.profiler.started();
|
||||
if ui.checkbox(&mut started, "Profiling enabled?").changed() {
|
||||
if started {
|
||||
self.profiler.start();
|
||||
let mut enabled = status.enabled();
|
||||
let enabled_checkbox = Checkbox::new(&mut enabled, "Profiling enabled?");
|
||||
if ui.add_enabled(!recording, enabled_checkbox).changed() {
|
||||
if enabled {
|
||||
self.profiler.enable();
|
||||
} else {
|
||||
self.profiler.stop();
|
||||
self.profiler.disable();
|
||||
}
|
||||
}
|
||||
|
||||
ui.horizontal(|ui| {
|
||||
if !recording {
|
||||
let record_button = Button::new("Record");
|
||||
let can_record = matches!(status, ProfilerStatus::Enabled);
|
||||
if ui.add_enabled(can_record, record_button).clicked() {
|
||||
self.profiler.start_recording();
|
||||
}
|
||||
} else {
|
||||
if ui.button("Finish recording").clicked() {
|
||||
self.finish_recording();
|
||||
}
|
||||
if ui.button("Cancel recording").clicked() {
|
||||
self.profiler.cancel_recording();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
match &status {
|
||||
ProfilerStatus::Recording => {
|
||||
ui.label("Recording...");
|
||||
}
|
||||
ProfilerStatus::Error(message) => {
|
||||
ui.label(message);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
});
|
||||
self.toasts.show(ctx);
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue