A GameCube/Wii emulator and debugger written in Rust.
experimental shit
Layleab754191e45e
diff --git a/crates/dbglib/src/lib.rs b/crates/dbglib/src/lib.rsindex 967b0d1..1b43f10 100644--- a/crates/dbglib/src/lib.rs+++ b/crates/dbglib/src/lib.rs@@ -6,11 +6,14 @@ use std::io::Write;use gecko::gamecube::GameCube;use gecko::scheduler::{CPU_CYCLES_PER_DSP_TICK, DSP_BATCH_SIZE, ScheduledFn, dsp_batch_handler};+use gecko::system::GC;++type GameCubeScheduledFn = ScheduledFn<{ GC }>;/// Identify the DSP batch handler so the debugger can intercept it for per-instruction tracing.#[inline(always)]-fn is_dsp_batch(f: ScheduledFn) -> bool {- (f as usize) == (dsp_batch_handler as ScheduledFn as usize)+fn is_dsp_batch(f: GameCubeScheduledFn) -> bool {+ (f as usize) == (dsp_batch_handler as GameCubeScheduledFn as usize)}#[derive(Debug, PartialEq, Eq, Clone, Copy)]diff --git a/crates/gecko/src/gamecube.rs b/crates/gecko/src/gamecube.rsindex f9744bb..b481fc4 100644--- a/crates/gecko/src/gamecube.rs+++ b/crates/gecko/src/gamecube.rs@@ -1,141 +1,25 @@use crate::cpu::instruction::Instruction;-use crate::cpu::{self, Cpu, IPL_RESET_VECTOR};-use crate::dvd::DvdInterface;-use crate::flipper::ai::AudioInterface;-use crate::flipper::cp::CommandProcessor;-use crate::flipper::dsp::Dsp;-use crate::flipper::exi::ExternalInterface;+use crate::cpu::{self, IPL_RESET_VECTOR};use crate::flipper::exi::macronix::ExiMacronix;-use crate::flipper::gx::GraphicsProcessor;-use crate::flipper::mi::MemoryInterface;-use crate::flipper::pe::PixelEngine;-use crate::flipper::pi::ProcessorInterface;-use crate::flipper::si::{SerialInterface, pad};-use crate::flipper::vi::VideoInterface;#[cfg(feature = "hooks")]-use crate::hooks::{HookFilters, HookFlags, HookState, Host};-use crate::host::{EmptyRenderSink, RenderSink};+use crate::hooks::HookFlags;#[cfg(feature = "idle-skip")]-use crate::idle::{IDLE_LOOP_MAX_INSTRS, IdleCheck, IdleDetector};+use crate::idle::{IDLE_LOOP_MAX_INSTRS, IdleCheck};use crate::ipl::IPL_HLE;-use crate::mmio::Mmio;use crate::scheduler::Scheduler;+use crate::system::{GC, System};use image::Executable;-pub struct GameCube {- pub vsync_pending: bool,- pub cpu: Cpu,- pub scheduler: Scheduler,- pub mmio: Mmio,- pub vi: VideoInterface,- pub pe: PixelEngine,- pub pi: ProcessorInterface,- pub dsp: Dsp,- pub exi: ExternalInterface,- pub gx: GraphicsProcessor,- pub cp: CommandProcessor,- pub di: DvdInterface,- pub si: SerialInterface,- pub ai: AudioInterface,- pub mi: MemoryInterface,-- /// GX dispatches actions here.- pub render_sink: Box<dyn RenderSink>,-- #[cfg(feature = "idle-skip")]- idle: IdleDetector,-- #[cfg(feature = "hooks")]- pub hook_host: Option<Box<dyn Host + Send>>,- #[cfg(feature = "hooks")]- pub hook_flags: HookFlags,- #[cfg(feature = "hooks")]- pub hook_filters: HookFilters,-}+pub type GameCube = System<{ GC }>;impl GameCube {- #[cfg(feature = "hooks")]- #[inline(always)]- pub fn apply_hook_state(&mut self, state: HookState) {- self.hook_flags = state.flags;- self.hook_filters = state.filters;- }-- #[cfg(feature = "hooks")]- #[inline(always)]- pub fn sync_pending_hook_state(&mut self, host: &mut dyn Host) {- #[cfg(feature = "hooks-mut-traps")]- match host.take_pending_hook_state() {- Ok(Some(state)) => self.apply_hook_state(state),- Ok(None) => {}- Err(err) => tracing::error!(target: "script", error = %err, "failed to refresh script traps"),- }-- #[cfg(not(feature = "hooks-mut-traps"))]- let _ = host;- }-pub fn new(entrypoint: u32) -> Self {- GameCube {- vsync_pending: false,- cpu: Cpu::new(entrypoint),- scheduler: Scheduler::new(),- mmio: Mmio::new(),- vi: VideoInterface::new(),- pe: PixelEngine::new(),- pi: ProcessorInterface::new(),- dsp: Dsp::new(),- exi: ExternalInterface::dummy(),- gx: GraphicsProcessor::new(),- cp: CommandProcessor::new(),- di: DvdInterface::new(),- si: SerialInterface::new(),- ai: AudioInterface::new(),- mi: MemoryInterface::new(),-- render_sink: Box::new(EmptyRenderSink),-- #[cfg(feature = "idle-skip")]- idle: IdleDetector::new(),-- #[cfg(feature = "hooks")]- hook_host: None,- #[cfg(feature = "hooks")]- hook_flags: HookFlags::empty(),- #[cfg(feature = "hooks")]- hook_filters: HookFilters::default(),- }+ Self::with_scheduler(entrypoint, Scheduler::new_gamecube())}pub fn with_image(exe: &impl Executable) -> Self {let mut emulator = GameCube::new(exe.entry_point());- let data = exe.data();-- // Copy TEXT sections to memory- for section in exe.text_sections() {- for i in 0..section.size {- let addr = section.vaddr + i;- let value = data[(section.offset + i) as usize];- emulator.mmio.virt_write_u8(addr, value);- }- }-- // Copy DATA sections to memory- for section in exe.data_sections() {- for i in 0..section.size {- let addr = section.vaddr + i;- let value = data[(section.offset + i) as usize];- emulator.mmio.virt_write_u8(addr, value);- }- }-- // Zero out the BSS section- let (bss_start, bss_size) = exe.bss();- for i in 0..bss_size {- let addr = bss_start + i;- emulator.mmio.virt_write_u8(addr, 0);- }-+ emulator.load_image(exe);emulator}@@ -301,17 +185,13 @@ impl GameCube {#[cfg(feature = "idle-skip")]match self.idle.check(self.cpu.cia, self.cpu.nia) {IdleCheck::Skip => {- if let Some(deadline) = self.scheduler.next_deadline() {- self.scheduler.cycles = deadline;- }+ self.scheduler.cycles = self.scheduler.next_deadline();}IdleCheck::Validate { start, end } => {let safe = self.is_polling_loop(start, end);self.idle.set_validated(safe);if safe {- if let Some(deadline) = self.scheduler.next_deadline() {- self.scheduler.cycles = deadline;- }+ self.scheduler.cycles = self.scheduler.next_deadline();}}IdleCheck::Continue => {}@@ -323,16 +203,13 @@ impl GameCube {/// Drain pending scheduler events, then execute one CPU instruction.#[inline(always)]pub fn step(&mut self) {- while let Some(f) = self.scheduler.poll() {- f(self);- }+ self.drain_events();self.step_cpu();}#[inline(always)]pub fn prepare_frame(&mut self) {- self.vsync_pending = false;- self.si.update_polling();+ self.begin_frame();crate::flipper::si::refresh_interrupts(self);}@@ -345,9 +222,7 @@ impl GameCube {self.step_cpu();}// Drain all events that are now due- while let Some(f) = self.scheduler.poll() {- f(self);- }+ self.drain_events();}}@@ -363,43 +238,4 @@ impl GameCube {}crate::idle::validate_polling_loop(&buf[..count.min(buf.len())], &self.cpu.gprs)}-- #[cfg(feature = "hooks")]- pub fn set_hook_host(&mut self, host: Box<dyn Host + Send>) {- self.apply_hook_state(host.hook_state());- self.hook_host = Some(host);- }-- #[cfg(all(feature = "hooks", feature = "hooks-mut-traps"))]- pub fn refresh_hook_traps(&mut self) -> Result<(), String> {- let Some(mut host) = self.hook_host.take() else {- return Ok(());- };-- let refresh_result = host.force_refresh_traps();- match refresh_result {- Ok(state) => {- self.apply_hook_state(state);- self.hook_host = Some(host);- Ok(())- }- Err(err) => {- self.hook_host = Some(host);- Err(err)- }- }- }-- pub fn frame_size(&self) -> (usize, usize) {- let fmt = self.vi.dcr.video_format();- (fmt.columns(), fmt.lines())- }-- pub fn add_primary_controller(&mut self, input: pad::PadStatus) {- self.si.pad_state[0] = input;- }-- pub fn primary_controller_mut(&mut self) -> &mut pad::PadStatus {- &mut self.si.pad_state[0]- }}diff --git a/crates/gecko/src/lib.rs b/crates/gecko/src/lib.rsindex bf434ee..09e2c97 100644--- a/crates/gecko/src/lib.rs+++ b/crates/gecko/src/lib.rs@@ -8,6 +8,11 @@ pub mod idle;pub mod ipl;pub mod mmio;pub mod scheduler;+pub mod system;+pub mod wii;++pub use gamecube::GameCube;+pub use wii::Wii;#[cfg(feature = "hooks")]pub mod hooks;diff --git a/crates/gecko/src/scheduler.rs b/crates/gecko/src/scheduler.rsindex 5adb083..1afe4f9 100644--- a/crates/gecko/src/scheduler.rs+++ b/crates/gecko/src/scheduler.rs@@ -1,43 +1,35 @@use std::collections::VecDeque;use crate::flipper::vi::regs::RefreshRate;-use crate::gamecube::GameCube;+use crate::system::{GC, System, SystemId};pub const TIMEBASE_DIVISOR: u64 = 12;pub const CPU_CYCLES_PER_DSP_TICK: u64 = 6; // ~486MHz CPU / ~81MHz DSPpub const DSP_BATCH_SIZE: u64 = 1024;-pub type ScheduledFn = fn(&mut GameCube);+pub type ScheduledFn<const SYSTEM: SystemId> = fn(&mut System<SYSTEM>);#[derive(Clone, Copy)]-struct ScheduledEvent {+struct ScheduledEvent<const SYSTEM: SystemId> {deadline: u64,- f: ScheduledFn,+ f: ScheduledFn<SYSTEM>,}-pub struct Scheduler {+pub struct Scheduler<const SYSTEM: SystemId> {pub cycles: u64,next_deadline: u64,timebase_offset: i64,- events: VecDeque<ScheduledEvent>,+ events: VecDeque<ScheduledEvent<SYSTEM>>,}-impl Scheduler {- pub fn new() -> Self {- let mut s = Scheduler {+impl<const SYSTEM: SystemId> Scheduler<SYSTEM> {+ pub fn empty() -> Self {+ Scheduler {cycles: 0,next_deadline: u64::MAX,timebase_offset: 0,events: VecDeque::with_capacity(8),- };- let initial_refresh_rate = RefreshRate::Hz60; // TODO: Detect IPL and schedule accordingly- s.schedule_at(initial_refresh_rate.cycles_per_frame(), self::vsync_handler);- s.schedule_at(CPU_CYCLES_PER_DSP_TICK * DSP_BATCH_SIZE, self::dsp_batch_handler);- s.schedule_at(- crate::cpu::dec::cycles_until_underflow(u32::MAX),- crate::cpu::dec::underflow_handler,- );- s+ }}#[inline(always)]@@ -70,24 +62,24 @@ impl Scheduler {}/// Insert an event keeping the deque sorted by deadline (earliest first).- pub fn schedule_at(&mut self, deadline: u64, f: ScheduledFn) {+ pub fn schedule_at(&mut self, deadline: u64, f: ScheduledFn<SYSTEM>) {let pos = self.events.partition_point(|e| e.deadline <= deadline);self.events.insert(pos, ScheduledEvent { deadline, f });self.next_deadline = self.next_deadline.min(deadline);}- pub fn cancel(&mut self, f: ScheduledFn) {+ pub fn cancel(&mut self, f: ScheduledFn<SYSTEM>) {self.events.retain(|e| !std::ptr::fn_addr_eq(e.f, f));self.refresh_deadline();}- pub fn schedule_in(&mut self, delay: u64, f: ScheduledFn) {+ pub fn schedule_in(&mut self, delay: u64, f: ScheduledFn<SYSTEM>) {let deadline = self.cycles + delay;self.schedule_at(deadline, f);}#[inline(always)]- pub fn poll(&mut self) -> Option<ScheduledFn> {+ pub fn poll(&mut self) -> Option<ScheduledFn<SYSTEM>> {let front = self.events.front()?;if self.cycles >= front.deadline {let f = self.events.pop_front().unwrap().f;@@ -104,15 +96,29 @@ impl Scheduler {}}+impl Scheduler<{ GC }> {+ pub fn new_gamecube() -> Self {+ let mut s = Self::empty();+ let initial_refresh_rate = RefreshRate::Hz60; // TODO: Detect IPL and schedule accordingly+ s.schedule_at(initial_refresh_rate.cycles_per_frame(), self::vsync_handler);+ s.schedule_at(CPU_CYCLES_PER_DSP_TICK * DSP_BATCH_SIZE, self::dsp_batch_handler);+ s.schedule_at(+ crate::cpu::dec::cycles_until_underflow(u32::MAX),+ crate::cpu::dec::underflow_handler,+ );+ s+ }+}+/// Reschedules itself every frame.-pub fn vsync_handler(gc: &mut GameCube) {+pub fn vsync_handler(gc: &mut System<{ GC }>) {gc.vsync_pending = true;let rate = gc.vi.dcr.video_format().refresh_rate();gc.scheduler.schedule_in(rate.cycles_per_frame(), self::vsync_handler);}/// Reschedules itself every DSP batch.-pub fn dsp_batch_handler(gc: &mut GameCube) {+pub fn dsp_batch_handler(gc: &mut System<{ GC }>) {gc.execute_dsp_batch();gc.scheduler.schedule_in(self::CPU_CYCLES_PER_DSP_TICK * self::DSP_BATCH_SIZE,diff --git a/crates/gecko/src/system.rs b/crates/gecko/src/system.rsnew file mode 100644index 0000000..6ee1724--- /dev/null+++ b/crates/gecko/src/system.rs@@ -0,0 +1,194 @@+use crate::cpu::Cpu;+use crate::dvd::DvdInterface;+use crate::flipper::ai::AudioInterface;+use crate::flipper::cp::CommandProcessor;+use crate::flipper::dsp::Dsp;+use crate::flipper::exi::ExternalInterface;+use crate::flipper::gx::GraphicsProcessor;+use crate::flipper::mi::MemoryInterface;+use crate::flipper::pe::PixelEngine;+use crate::flipper::pi::ProcessorInterface;+use crate::flipper::si::{SerialInterface, pad};+use crate::flipper::vi::VideoInterface;+#[cfg(feature = "hooks")]+use crate::hooks::{HookFilters, HookFlags, HookState, Host};+use crate::host::{EmptyRenderSink, RenderSink};+#[cfg(feature = "idle-skip")]+use crate::idle::IdleDetector;+use crate::mmio::Mmio;+use crate::scheduler::Scheduler;+use image::Executable;++pub type SystemId = u8;++pub const GC: SystemId = 0;+pub const WII: SystemId = 1;++pub struct System<const SYSTEM: SystemId> {+ pub vsync_pending: bool,+ pub cpu: Cpu,+ pub scheduler: Scheduler<SYSTEM>,+ pub mmio: Mmio,+ pub vi: VideoInterface,+ pub pe: PixelEngine,+ pub pi: ProcessorInterface,+ pub dsp: Dsp,+ pub exi: ExternalInterface,+ pub gx: GraphicsProcessor,+ pub cp: CommandProcessor,+ pub di: DvdInterface,+ pub si: SerialInterface,+ pub ai: AudioInterface,+ pub mi: MemoryInterface,++ /// GX dispatches actions here.+ pub render_sink: Box<dyn RenderSink>,++ #[cfg(feature = "idle-skip")]+ pub(crate) idle: IdleDetector,++ #[cfg(feature = "hooks")]+ pub hook_host: Option<Box<dyn Host + Send>>,+ #[cfg(feature = "hooks")]+ pub hook_flags: HookFlags,+ #[cfg(feature = "hooks")]+ pub hook_filters: HookFilters,+}++impl<const SYSTEM: SystemId> System<SYSTEM> {+ pub const SYSTEM: SystemId = SYSTEM;++ pub(crate) fn with_scheduler(entrypoint: u32, scheduler: Scheduler<SYSTEM>) -> Self {+ System {+ vsync_pending: false,+ cpu: Cpu::new(entrypoint),+ scheduler,+ mmio: Mmio::new(),+ vi: VideoInterface::new(),+ pe: PixelEngine::new(),+ pi: ProcessorInterface::new(),+ dsp: Dsp::new(),+ exi: ExternalInterface::dummy(),+ gx: GraphicsProcessor::new(),+ cp: CommandProcessor::new(),+ di: DvdInterface::new(),+ si: SerialInterface::new(),+ ai: AudioInterface::new(),+ mi: MemoryInterface::new(),++ render_sink: Box::new(EmptyRenderSink),++ #[cfg(feature = "idle-skip")]+ idle: IdleDetector::new(),++ #[cfg(feature = "hooks")]+ hook_host: None,+ #[cfg(feature = "hooks")]+ hook_flags: HookFlags::empty(),+ #[cfg(feature = "hooks")]+ hook_filters: HookFilters::default(),+ }+ }++ pub fn frame_size(&self) -> (usize, usize) {+ let fmt = self.vi.dcr.video_format();+ (fmt.columns(), fmt.lines())+ }++ pub fn add_primary_controller(&mut self, input: pad::PadStatus) {+ self.si.pad_state[0] = input;+ }++ pub fn primary_controller_mut(&mut self) -> &mut pad::PadStatus {+ &mut self.si.pad_state[0]+ }++ #[inline(always)]+ pub fn begin_frame(&mut self) {+ self.vsync_pending = false;+ self.si.update_polling();+ }++ #[inline(always)]+ pub fn drain_events(&mut self) {+ while let Some(f) = self.scheduler.poll() {+ f(self);+ }+ }++ pub fn load_image(&mut self, exe: &impl Executable) {+ let data = exe.data();++ // Copy TEXT sections to memory+ for section in exe.text_sections() {+ for i in 0..section.size {+ let addr = section.vaddr + i;+ let value = data[(section.offset + i) as usize];+ self.mmio.virt_write_u8(addr, value);+ }+ }++ // Copy DATA sections to memory+ for section in exe.data_sections() {+ for i in 0..section.size {+ let addr = section.vaddr + i;+ let value = data[(section.offset + i) as usize];+ self.mmio.virt_write_u8(addr, value);+ }+ }++ // Zero out the BSS section+ let (bss_start, bss_size) = exe.bss();+ for i in 0..bss_size {+ let addr = bss_start + i;+ self.mmio.virt_write_u8(addr, 0);+ }+ }++ #[cfg(feature = "hooks")]+ #[inline(always)]+ pub fn apply_hook_state(&mut self, state: HookState) {+ self.hook_flags = state.flags;+ self.hook_filters = state.filters;+ }++ #[cfg(feature = "hooks")]+ #[inline(always)]+ pub fn sync_pending_hook_state(&mut self, host: &mut dyn Host) {+ #[cfg(feature = "hooks-mut-traps")]+ match host.take_pending_hook_state() {+ Ok(Some(state)) => self.apply_hook_state(state),+ Ok(None) => {}+ Err(err) => tracing::error!(target: "script", error = %err, "failed to refresh script traps"),+ }++ #[cfg(not(feature = "hooks-mut-traps"))]+ let _ = host;+ }++ #[cfg(feature = "hooks")]+ pub fn set_hook_host(&mut self, host: Box<dyn Host + Send>) {+ self.apply_hook_state(host.hook_state());+ self.hook_host = Some(host);+ }++ #[cfg(all(feature = "hooks", feature = "hooks-mut-traps"))]+ pub fn refresh_hook_traps(&mut self) -> Result<(), String> {+ let Some(mut host) = self.hook_host.take() else {+ return Ok(());+ };++ let refresh_result = host.force_refresh_traps();+ match refresh_result {+ Ok(state) => {+ self.apply_hook_state(state);+ self.hook_host = Some(host);+ Ok(())+ }+ Err(err) => {+ self.hook_host = Some(host);+ Err(err)+ }+ }+ }+}diff --git a/crates/gecko/src/wii.rs b/crates/gecko/src/wii.rsnew file mode 100644index 0000000..2ac30b7--- /dev/null+++ b/crates/gecko/src/wii.rs@@ -0,0 +1,11 @@+use crate::scheduler::Scheduler;+use crate::system::{System, WII};++pub type Wii = System<{ WII }>;+++impl Wii {+ pub fn new(entrypoint: u32) -> Self {+ Self::with_scheduler(entrypoint, Scheduler::empty())+ }+}