Skip to content

armgit / gecko

Public Imported from GitHub
0

A GameCube/Wii emulator and debugger written in Rust.

dsp tests

Layleceaddd9de240
diff --git a/.gitmodules b/.gitmodules
index 7122d95..501c542 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -4,3 +4,6 @@
[submodule "submodules/lilyskategc"]
path = submodules/lilyskategc
url = https://github.com/ioncodes/lilyskategc
+[submodule "submodules/gcwii-resources"]
+ path = submodules/gcwii-resources
+ url = https://codeberg.org/hazelwiss/gcwii-resources
diff --git a/Cargo.lock b/Cargo.lock
index 1ecfcd1..d98ea68 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3251,7 +3251,17 @@ dependencies = [
]
[[package]]
-name = "tinyemu"
+name = "tinystr"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869"
+dependencies = [
+ "displaydoc",
+ "zerovec",
+]
+
+[[package]]
+name = "tinytracer"
version = "0.1.0"
dependencies = [
"base64",
@@ -3264,16 +3274,6 @@ dependencies = [
"tracing-subscriber",
]
-[[package]]
-name = "tinystr"
-version = "0.8.2"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869"
-dependencies = [
- "displaydoc",
- "zerovec",
-]
-
[[package]]
name = "toml"
version = "1.1.0+spec-1.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index e14facf..39bed81 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -4,7 +4,7 @@ members = [
"crates/gctool",
"crates/disasm",
"crates/gecko",
- "crates/tinyemu",
+ "crates/tinytracer",
"crates/tinybench",
"crates/image",
"crates/tinyapp",
@@ -19,7 +19,7 @@ default-members = [
"crates/gctool",
"crates/disasm",
"crates/gecko",
- "crates/tinyemu",
+ "crates/tinytracer",
"crates/tinybench",
"crates/image",
"crates/tinyapp",
diff --git a/crates/dbglib/src/windows/dsp.rs b/crates/dbglib/src/windows/dsp.rs
index 90fabfb..ded8adf 100644
--- a/crates/dbglib/src/windows/dsp.rs
+++ b/crates/dbglib/src/windows/dsp.rs
@@ -137,7 +137,8 @@ pub fn show_dsp(ctx: &Context, open: &mut bool, dsp: &Dsp) {
.min_col_width(0.0)
.striped(true)
.show(ui, |ui| {
- let mut addr = dsp.registers.pc.saturating_sub(20);
+ let region_base = if dsp.registers.pc >= 0x8000 { 0x8000 } else { 0x0000 };
+ let mut addr = dsp.registers.pc.saturating_sub(20).max(region_base);
for _ in 0..40 {
let mem = imem_slice(dsp, addr);
let Some(mem) = mem else { break };
diff --git a/crates/gecko/src/cpu/interpreter/stubs.rs b/crates/gecko/src/cpu/interpreter/stubs.rs
index 721a058..d0278ed 100644
--- a/crates/gecko/src/cpu/interpreter/stubs.rs
+++ b/crates/gecko/src/cpu/interpreter/stubs.rs
@@ -16,7 +16,63 @@ macro_rules! stub {
stub! {
tw,
mtsrin, mcrxr,
- lswx, lswi, mfsrin,
- stswx, stswi,
+ lswi, mfsrin,
+ stswi,
eciwx, ecowx,
}
+
+#[inline(always)]
+pub fn lswx(ctx: &mut crate::gamecube::GameCube, instr: crate::cpu::instruction::Instruction) {
+ let ea = ctx
+ .cpu
+ .read_gpr_or_zero(instr.ra())
+ .wrapping_add(ctx.cpu.read_gpr(instr.rb()));
+ let mut n = ctx.cpu.spr.xer.byte_count() as u32;
+ if n == 0 {
+ return;
+ }
+ let mut r = (instr.rd() as u32).wrapping_sub(1) & 31;
+ let mut i = 0u32;
+ let mut addr = ea;
+ while n > 0 {
+ if i == 0 {
+ r = (r + 1) & 31;
+ ctx.cpu.write_gpr(r as u8, 0);
+ }
+ let byte = ctx.read_u8(addr) as u32;
+ let shift = 24 - i;
+ let val = ctx.cpu.read_gpr(r as u8) | (byte << shift);
+ ctx.cpu.write_gpr(r as u8, val);
+ i += 8;
+ if i == 32 {
+ i = 0;
+ }
+ addr = addr.wrapping_add(1);
+ n -= 1;
+ }
+}
+
+#[inline(always)]
+pub fn stswx(ctx: &mut crate::gamecube::GameCube, instr: crate::cpu::instruction::Instruction) {
+ let ea = ctx
+ .cpu
+ .read_gpr_or_zero(instr.ra())
+ .wrapping_add(ctx.cpu.read_gpr(instr.rb()));
+ let mut n = ctx.cpu.spr.xer.byte_count() as u32;
+ let mut r = (instr.rs() as u32).wrapping_sub(1) & 31;
+ let mut i = 0u32;
+ let mut addr = ea;
+ while n > 0 {
+ if i == 0 {
+ r = (r + 1) & 31;
+ }
+ let byte = (ctx.cpu.read_gpr(r as u8) >> (24 - i)) as u8;
+ ctx.write_u8(addr, byte);
+ i += 8;
+ if i == 32 {
+ i = 0;
+ }
+ addr = addr.wrapping_add(1);
+ n -= 1;
+ }
+}
diff --git a/crates/gecko/src/flipper/dsp.rs b/crates/gecko/src/flipper/dsp.rs
index e801a65..d1c1dce 100644
--- a/crates/gecko/src/flipper/dsp.rs
+++ b/crates/gecko/src/flipper/dsp.rs
@@ -15,6 +15,8 @@ use crate::mmio::Mmio;
use crate::mmio::constants::DSP_BASE;
use crate::mmio::traits::{MmioAccess, MmioRegister, MmioRw};
+pub const DSP_MAIL_SLICE: u32 = 72;
+
pub struct Dsp {
// Registers
pub registers: core::Registers,
@@ -230,13 +232,9 @@ impl Dsp {
/// Read a 16-bit word from IFX register space, with mailbox side-effects.
pub fn read_ifx(&mut self, addr: u16) -> u16 {
match addr {
- // CMBH (CPU Mailbox High): reading returns data + M bit;
- // clears M (busy) so the CPU sees the mailbox as free.
- 0xFFFE => {
- let val = self.mailbox_to_dsp_hi.raw();
- self.mailbox_to_dsp_hi.set_busy(false);
- val
- }
+ // CMBH (CPU Mailbox High): reading returns data + M bit.
+ // M is only cleared when CMBL is read (0xFFFF).
+ 0xFFFE => self.mailbox_to_dsp_hi.raw(),
// CMBL (CPU Mailbox Low): reading clears CMBH.M (busy)
0xFFFF => {
self.mailbox_to_dsp_hi.set_busy(false);
@@ -253,10 +251,10 @@ impl Dsp {
/// Write a 16-bit word to IFX register space, with mailbox side-effects.
pub fn write_ifx(&mut self, addr: u16, value: u16) {
match addr {
- // DMBH (DSP Mailbox High): store data bits (14:0), clear M bit
- // M will be set when DMBL is written (matching Dolphin behavior)
+ // DMBH (DSP Mailbox High): store data bits (14:0), busy is preserved
0xFFFC => {
- self.mailbox_to_cpu_hi = regs::MailboxToCpuHi::from_raw(value & 0x7FFF);
+ let busy = self.mailbox_to_cpu_hi.busy();
+ self.mailbox_to_cpu_hi = regs::MailboxToCpuHi::from_raw(value & 0x7FFF).with_busy(busy);
}
// DMBL (DSP Mailbox Low): writing sets DMBH.M
// Interrupt is NOT raised here; the ucode must explicitly write DIRQ (0xFFFB)
@@ -267,6 +265,7 @@ impl Dsp {
// DIRQ: DSP explicitly raises interrupt to CPU
0xFFFB => {
if value & 1 != 0 {
+ tracing::debug!("DSP DIRQ: requesting CPU interrupt");
self.csr.set_dsp_interrupt(true);
}
}
diff --git a/crates/gecko/src/flipper/dsp/core.rs b/crates/gecko/src/flipper/dsp/core.rs
index 088249e..9c0b8ed 100644
--- a/crates/gecko/src/flipper/dsp/core.rs
+++ b/crates/gecko/src/flipper/dsp/core.rs
@@ -195,15 +195,15 @@ impl Registers {
}
#[inline(always)]
- pub fn read<const ALLOW_SATURATION: bool>(&self, index: u8) -> u16 {
+ pub fn read<const ALLOW_SATURATION: bool>(&mut self, index: u8) -> u16 {
match index {
0..=3 => self.ar[index as usize],
4..=7 => self.ix[(index - 4) as usize],
8..=11 => self.wr[(index - 8) as usize],
- 12 => self.call_stack.top(),
- 13 => self.data_stack.top(),
- 14 => self.loop_addr.top(),
- 15 => self.loop_counter.top(),
+ 12 => self.call_stack.pop(),
+ 13 => self.data_stack.pop(),
+ 14 => self.loop_addr.pop(),
+ 15 => self.loop_counter.pop(),
16 => self.ac0_high,
17 => self.ac1_high,
18 => self.config,
@@ -250,10 +250,10 @@ impl Registers {
0..=3 => self.ar[index as usize] = value,
4..=7 => self.ix[(index - 4) as usize] = value,
8..=11 => self.wr[(index - 8) as usize] = value,
- 12 => self.call_stack.set_top(value),
- 13 => self.data_stack.set_top(value),
- 14 => self.loop_addr.set_top(value),
- 15 => self.loop_counter.set_top(value),
+ 12 => self.call_stack.push(value),
+ 13 => self.data_stack.push(value),
+ 14 => self.loop_addr.push(value),
+ 15 => self.loop_counter.push(value),
16 => self.ac0_high = value,
17 => self.ac1_high = value,
18 => self.config = value,
diff --git a/crates/gecko/src/flipper/dsp/regs.rs b/crates/gecko/src/flipper/dsp/regs.rs
index 09b35b6..04cba60 100644
--- a/crates/gecko/src/flipper/dsp/regs.rs
+++ b/crates/gecko/src/flipper/dsp/regs.rs
@@ -130,9 +130,8 @@ impl MmioAccess<Dsp> for MailboxToDspHi {
}
fn write(self, dsp: &mut Dsp) {
- // CPU writing CMBH sets data bits (14:0) and clears M bit
- // M will be set when CMBL is written
- dsp.mailbox_to_dsp_hi = self.with_busy(false);
+ // CPU writing CMBH sets data bits (14:0), busy is preserved
+ dsp.mailbox_to_dsp_hi = self.with_busy(dsp.mailbox_to_dsp_hi.busy());
}
}
diff --git a/crates/gecko/src/gamecube.rs b/crates/gecko/src/gamecube.rs
index f49191a..679f079 100644
--- a/crates/gecko/src/gamecube.rs
+++ b/crates/gecko/src/gamecube.rs
@@ -15,7 +15,7 @@ use crate::flipper::vi::VideoInterface;
#[cfg(feature = "idle-skip")]
use crate::idle::{IDLE_LOOP_MAX_INSTRS, IdleCheck, IdleDetector};
use crate::mmio::Mmio;
-use crate::scheduler::{CYCLES_PER_VSYNC, DSP_TICKS_PER_CPU_CYCLE, EventKind, Scheduler};
+use crate::scheduler::{CYCLES_PER_VSYNC, CPU_CYCLES_PER_DSP_TICK, EventKind, Scheduler};
#[cfg(feature = "scripting")]
use crate::scripting::{HookFlags, ScriptHookFilters, ScriptHookState, ScriptHost};
use image::Executable;
@@ -175,7 +175,7 @@ impl GameCube {
}
EventKind::DspTick => {
self.tick_dsp();
- self.scheduler.schedule_in(DSP_TICKS_PER_CPU_CYCLE, EventKind::DspTick);
+ self.scheduler.schedule_in(CPU_CYCLES_PER_DSP_TICK, EventKind::DspTick);
}
}
}
diff --git a/crates/gecko/src/scheduler.rs b/crates/gecko/src/scheduler.rs
index 8ed1a09..61d6d0d 100644
--- a/crates/gecko/src/scheduler.rs
+++ b/crates/gecko/src/scheduler.rs
@@ -3,7 +3,7 @@ use std::collections::BinaryHeap;
pub const CYCLES_PER_VSYNC: u64 = 486_000_000 / 60; // TODO: fix
pub const TIMEBASE_DIVISOR: u64 = 12;
-pub const DSP_TICKS_PER_CPU_CYCLE: u64 = 6; // ~486MHz CPU / ~81MHz DSP
+pub const CPU_CYCLES_PER_DSP_TICK: u64 = 6; // ~486MHz CPU / ~81MHz DSP
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum EventKind {
@@ -27,7 +27,7 @@ impl Scheduler {
events: BinaryHeap::new(),
};
s.schedule_at(CYCLES_PER_VSYNC, EventKind::VSync);
- s.schedule_at(DSP_TICKS_PER_CPU_CYCLE, EventKind::DspTick);
+ s.schedule_at(CPU_CYCLES_PER_DSP_TICK, EventKind::DspTick);
s
}
diff --git a/crates/tinyemu/Cargo.toml b/crates/tinytracer/Cargo.toml
similarity index 96%
rename from crates/tinyemu/Cargo.toml
rename to crates/tinytracer/Cargo.toml
index 14bc575..667f98b 100644
--- a/crates/tinyemu/Cargo.toml
+++ b/crates/tinytracer/Cargo.toml
@@ -1,5 +1,5 @@
[package]
-name = "tinyemu"
+name = "tinytracer"
version = "0.1.0"
edition = "2024"
diff --git a/crates/tinyemu/src/dump.rs b/crates/tinytracer/src/dump.rs
similarity index 100%
rename from crates/tinyemu/src/dump.rs
rename to crates/tinytracer/src/dump.rs
diff --git a/crates/tinyemu/src/fmt.rs b/crates/tinytracer/src/fmt.rs
similarity index 92%
rename from crates/tinyemu/src/fmt.rs
rename to crates/tinytracer/src/fmt.rs
index 723cf29..e400b04 100644
--- a/crates/tinyemu/src/fmt.rs
+++ b/crates/tinytracer/src/fmt.rs
@@ -21,7 +21,16 @@ pub fn colorize(tok: &AsmToken<'_>) -> String {
pub fn colorize_instr(instr: &disasm::gekko::GekkoInstruction) -> String {
let text = format!("{}", instr);
- let tokens = tokenizer::tokenize(&text);
+ colorize_asm(&text)
+}
+
+pub fn colorize_dsp_instr(instr: &disasm::dsp::GcDspInstruction) -> String {
+ let text = format!("{}", instr);
+ colorize_asm(&text)
+}
+
+fn colorize_asm(text: &str) -> String {
+ let tokens = tokenizer::tokenize(text);
tokens.into_iter().map(|t| colorize(&t)).collect::<Vec<_>>().join("")
}
diff --git a/crates/tinyemu/src/kitty.rs b/crates/tinytracer/src/kitty.rs
similarity index 100%
rename from crates/tinyemu/src/kitty.rs
rename to crates/tinytracer/src/kitty.rs
diff --git a/crates/tinyemu/src/main.rs b/crates/tinytracer/src/main.rs
similarity index 69%
rename from crates/tinyemu/src/main.rs
rename to crates/tinytracer/src/main.rs
index 970f7d7..9a1f4d8 100644
--- a/crates/tinyemu/src/main.rs
+++ b/crates/tinytracer/src/main.rs
@@ -3,11 +3,28 @@ mod fmt;
mod kitty;
mod snaptshot;
-use clap::Parser;
+use clap::{Parser, ValueEnum};
use colored::Colorize;
+use disasm::dsp::GcDspInstruction;
use disasm::gekko::GekkoInstruction;
use snaptshot::CpuSnapshot;
+#[derive(Clone, Copy, PartialEq, Eq, ValueEnum)]
+enum TraceMode {
+ Cpu,
+ Dsp,
+ Both,
+}
+
+impl TraceMode {
+ fn trace_cpu(self) -> bool {
+ matches!(self, TraceMode::Cpu | TraceMode::Both)
+ }
+ fn trace_dsp(self) -> bool {
+ matches!(self, TraceMode::Dsp | TraceMode::Both)
+ }
+}
+
#[derive(Parser)]
#[command(about = "GameCube emulator")]
struct Args {
@@ -27,6 +44,10 @@ struct Args {
#[arg(long)]
debug: bool,
+ /// Which processors to trace: cpu, dsp, or both
+ #[arg(long, default_value = "cpu")]
+ trace: TraceMode,
+
/// Stop emulation when PC reaches this address (hex, e.g. 0x80003A00)
#[arg(long, value_parser = parse_hex_addr)]
until: Option<u32>,
@@ -121,11 +142,15 @@ fn main() {
fn run_emulator(emulator: &mut gecko::gamecube::GameCube, args: &Args, symbols: Option<&image::symbols::SymbolTable>) {
let mut prev_snapshot = CpuSnapshot::from_cpu(&emulator.cpu);
let mut prev_pc = emulator.cpu.pc;
+ let mut prev_dsp_pc = emulator.dsp.registers.pc;
let mut in_busyloop = false;
let mut current_func: Option<String> = None;
+ let trace_cpu = args.trace.trace_cpu();
+ let trace_dsp = args.trace.trace_dsp();
+ let is_both = args.trace == TraceMode::Both;
loop {
- if !in_busyloop && !args.quiet {
+ if !in_busyloop && !args.quiet && trace_cpu {
if let Some(symbols) = symbols {
if let Some(sym) = symbols.lookup_exact(emulator.cpu.pc) {
if sym.kind == image::symbols::SymbolKind::Func {
@@ -138,25 +163,37 @@ fn run_emulator(emulator: &mut gecko::gamecube::GameCube, args: &Args, symbols:
}
}
}
- print_instruction(emulator, &prev_snapshot, args.debug);
+ print_cpu_instruction(emulator, &prev_snapshot, args.debug, is_both);
}
emulator.step();
+ // CPU trace
let curr_snapshot = CpuSnapshot::from_cpu(&emulator.cpu);
let curr_pc = emulator.cpu.pc;
- if curr_pc == prev_pc {
- if !in_busyloop && !args.quiet {
- println!("{}", "Busyloop detected!".bright_red().bold());
+ if trace_cpu {
+ if curr_pc == prev_pc {
+ if !in_busyloop && !args.quiet {
+ println!("{}", "Busyloop detected!".bright_red().bold());
+ }
+ in_busyloop = true;
+ } else {
+ in_busyloop = false;
+ }
+
+ if args.debug && !in_busyloop && !args.quiet {
+ dump::registers(&curr_snapshot, &prev_snapshot);
}
- in_busyloop = true;
- } else {
- in_busyloop = false;
}
- if args.debug && !in_busyloop && !args.quiet {
- dump::registers(&curr_snapshot, &prev_snapshot);
+ // DSP trace
+ if trace_dsp && !args.quiet {
+ let dsp_pc = emulator.dsp.registers.pc;
+ if dsp_pc != prev_dsp_pc {
+ print_dsp_instruction(emulator, prev_dsp_pc, is_both);
+ }
+ prev_dsp_pc = dsp_pc;
}
prev_pc = curr_pc;
@@ -168,7 +205,12 @@ fn run_emulator(emulator: &mut gecko::gamecube::GameCube, args: &Args, symbols:
}
}
-fn print_instruction(emulator: &gecko::gamecube::GameCube, prev_snapshot: &CpuSnapshot, debug: bool) {
+fn print_cpu_instruction(
+ emulator: &gecko::gamecube::GameCube,
+ prev_snapshot: &CpuSnapshot,
+ debug: bool,
+ prefix_tag: bool,
+) {
let instr = GekkoInstruction::decode(emulator.mmio.virt_slice(emulator.cpu.pc, 4))
.unwrap_or_else(|| {
dump::registers(prev_snapshot, prev_snapshot);
@@ -188,8 +230,14 @@ fn print_instruction(emulator: &gecko::gamecube::GameCube, prev_snapshot: &CpuSn
let refs = fmt::gpr_refs(&instr);
let fpr_refs = fmt::fpr_refs(&instr);
let comment = fmt::reg_comment(&prev_snapshot.gprs, &refs, &prev_snapshot.fprs, &fpr_refs);
+ let tag = if prefix_tag {
+ format!("{} ", "[cpu]".bold())
+ } else {
+ String::new()
+ };
let prefix = format!(
- "{}: {}",
+ "{}{}: {}",
+ tag,
format!("{:08X}", emulator.cpu.pc).bold(),
fmt::colorize_instr(&instr)
);
@@ -203,3 +251,24 @@ fn print_instruction(emulator: &gecko::gamecube::GameCube, prev_snapshot: &CpuSn
println!("{}{}{}", prefix, " ".repeat(pad), comment);
}
}
+
+fn print_dsp_instruction(emulator: &gecko::gamecube::GameCube, pc: u16, prefix_tag: bool) {
+ let w0 = emulator.dsp.read_imem(pc);
+ let w1 = emulator.dsp.read_imem(pc.wrapping_add(1));
+ let bytes = [(w0 >> 8) as u8, w0 as u8, (w1 >> 8) as u8, w1 as u8];
+ let tag = if prefix_tag {
+ format!("{} ", "[dsp]".bold().bright_blue())
+ } else {
+ String::new()
+ };
+ if let Some((insn, _)) = GcDspInstruction::decode(&bytes) {
+ println!(
+ "{}{}: {}",
+ tag,
+ format!("{:04X}", pc).bold(),
+ fmt::colorize_dsp_instr(&insn)
+ );
+ } else {
+ println!("{}{}: .word {w0:#06x}", tag, format!("{:04X}", pc).bold());
+ }
+}
diff --git a/crates/tinyemu/src/snaptshot.rs b/crates/tinytracer/src/snaptshot.rs
similarity index 100%
rename from crates/tinyemu/src/snaptshot.rs
rename to crates/tinytracer/src/snaptshot.rs
diff --git a/scripts/hazel.lua b/scripts/hazel.lua
index fba6d14..e57f5b2 100644
--- a/scripts/hazel.lua
+++ b/scripts/hazel.lua
@@ -1,27 +1,23 @@
--- toggle = false
--- local function hack(emu, virt_addr, phys_addr, size, value)
--- log(string.format("Toggling DSP busy bit: %s", toggle and "ON" or "OFF"))
--- log(string.format("Original DSP read value: %08X", value))
--- if toggle then
--- value = value | 0x8000
--- toggle = false
--- else
--- value = value & 0x7FFF
--- toggle = true
--- end
--- log(string.format("Modified DSP read value: %08X", value))
--- return value
--- end
+local stdout_buffer = ""
-local function ar_mode_hook(emu, virt_addr, phys_addr, size, value)
- log(string.format("Original AR mode value: %08X", value))
- return value | 1
+local function on_stdout_write(emu, virt_addr, phys_addr, size, value)
+ local ch = value & 0xFF
+ local done = (value & 0x100) ~= 0
+ if ch == 0x0A then
+ log("hazel says: " .. stdout_buffer)
+ stdout_buffer = ""
+ elseif ch ~= 0 then
+ stdout_buffer = stdout_buffer .. string.char(ch)
+ end
+ if done then
+ stdout_buffer = ""
+ end
end
traps = {
- bus_read_post = {
+ bus_write_post = {
virt = {
- [0xCC005016] = ar_mode_hook,
+ [0xCC007000] = on_stdout_write,
},
},
-}
\ No newline at end of file
+}
diff --git a/submodules/gcwii-resources b/submodules/gcwii-resources
new file mode 160000
index 0000000..b9266e6
--- /dev/null
+++ b/submodules/gcwii-resources
@@ -0,0 +1 @@
+Subproject commit b9266e6d36c527ba3d429603efa6bcd0a4fe6cbf