A GameCube/Wii emulator and debugger written in Rust.
cursed branching
Laylebda3481cca98
diff --git a/Cargo.lock b/Cargo.lockindex 3f4531c..dbe4caf 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2,6 +2,15 @@# It is not intended for manual editing.version = 4+[[package]]+name = "aho-corasick"+version = "1.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"+dependencies = [+ "memchr",+]+[[package]]name = "anstream"version = "0.6.21"@@ -52,6 +61,12 @@ dependencies = ["windows-sys",]+[[package]]+name = "cfg-if"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"+[[package]]name = "chipi"version = "0.4.0"@@ -133,6 +148,7 @@ name = "gekko"version = "0.1.0"dependencies = ["chipi",+ "tracing",][[package]]@@ -147,12 +163,60 @@ version = "1.70.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"+[[package]]+name = "lazy_static"+version = "1.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"++[[package]]+name = "log"+version = "0.4.29"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"++[[package]]+name = "matchers"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"+dependencies = [+ "regex-automata",+]++[[package]]+name = "memchr"+version = "2.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"++[[package]]+name = "nu-ansi-term"+version = "0.50.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"+dependencies = [+ "windows-sys",+]++[[package]]+name = "once_cell"+version = "1.21.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"+[[package]]name = "once_cell_polyfill"version = "1.70.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"+[[package]]+name = "pin-project-lite"+version = "0.2.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b"+[[package]]name = "proc-macro2"version = "1.0.106"@@ -171,6 +235,38 @@ dependencies = ["proc-macro2",]+[[package]]+name = "regex-automata"+version = "0.4.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5276caf25ac86c8d810222b3dbb938e512c55c6831a10f3e6ed1c93b84041f1c"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-syntax",+]++[[package]]+name = "regex-syntax"+version = "0.8.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7a2d987857b319362043e95f5353c0535c1f58eec5336fdfcf626430af7def58"++[[package]]+name = "sharded-slab"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"+dependencies = [+ "lazy_static",+]++[[package]]+name = "smallvec"+version = "1.15.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"+[[package]]name = "strsim"version = "0.11.1"@@ -188,6 +284,15 @@ dependencies = ["unicode-ident",]+[[package]]+name = "thread_local"+version = "1.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185"+dependencies = [+ "cfg-if",+]+[[package]]name = "tinyemu"version = "0.1.0"@@ -195,6 +300,69 @@ dependencies = ["colored","disasm","gekko",+ "tracing",+ "tracing-subscriber",+]++[[package]]+name = "tracing"+version = "0.1.44"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"+dependencies = [+ "pin-project-lite",+ "tracing-attributes",+ "tracing-core",+]++[[package]]+name = "tracing-attributes"+version = "0.1.31"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"+dependencies = [+ "proc-macro2",+ "quote",+ "syn",+]++[[package]]+name = "tracing-core"+version = "0.1.36"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"+dependencies = [+ "once_cell",+ "valuable",+]++[[package]]+name = "tracing-log"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"+dependencies = [+ "log",+ "once_cell",+ "tracing-core",+]++[[package]]+name = "tracing-subscriber"+version = "0.3.22"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2f30143827ddab0d256fd843b7a66d164e9f271cfa0dde49142c5ca0ca291f1e"+dependencies = [+ "matchers",+ "nu-ansi-term",+ "once_cell",+ "regex-automata",+ "sharded-slab",+ "smallvec",+ "thread_local",+ "tracing",+ "tracing-core",+ "tracing-log",][[package]]@@ -209,6 +377,12 @@ version = "0.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"+[[package]]+name = "valuable"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"+[[package]]name = "windows-link"version = "0.2.1"diff --git a/crates/gekko/Cargo.toml b/crates/gekko/Cargo.tomlindex bd4329f..1625bbb 100644--- a/crates/gekko/Cargo.toml+++ b/crates/gekko/Cargo.toml@@ -5,3 +5,6 @@ edition = "2024"[build-dependencies]chipi = "0.4.0"++[dependencies]+tracing = "0.1.44"diff --git a/crates/gekko/build.rs b/crates/gekko/build.rsindex e710c96..493c73a 100644--- a/crates/gekko/build.rs+++ b/crates/gekko/build.rs@@ -10,7 +10,7 @@ fn main() {.handler_mod("crate::cpu::interpreter").ctx_type("crate::gekko::Gekko").instr_type("crate::cpu::semantics::Instruction")- .group("branch", ["bx", "bclrx"])+ .group("branch", ["bx", "bcx", "bclrx"]).group("alu", ["ori", "addi", "addis"]).group("msr", ["mtmsr", "mfmsr"]).group("spr", ["mtspr", "mfspr"])diff --git a/crates/gekko/src/cpu.rs b/crates/gekko/src/cpu.rsindex 0a95824..9413934 100644--- a/crates/gekko/src/cpu.rs+++ b/crates/gekko/src/cpu.rs@@ -1,5 +1,6 @@pub mod interpreter;pub mod semantics;+pub mod branch;#[allow(dead_code, unused_variables, non_upper_case_globals, clippy::all)]pub mod lut {diff --git a/crates/gekko/src/cpu/branch.rs b/crates/gekko/src/cpu/branch.rsnew file mode 100644index 0000000..3892a8c--- /dev/null+++ b/crates/gekko/src/cpu/branch.rs@@ -0,0 +1,57 @@+#[derive(Debug)]+pub enum BranchControl {+ BranchIfConditionTrue,+ BranchIfConditionFalse,+ BranchAlways,+ DecrementBranchIfNotZeroAndConditionFalse,+ DecrementBranchIfZeroAndConditionFalse,+ DecrementBranchIfNotZeroAndConditionTrue,+ DecrementBranchIfZeroAndConditionTrue,+ DecrementBranchIfNotZero,+ DecrementBranchIfZero,+}++impl BranchControl {+ pub fn from_bo(value: u8) -> Self {+ let branch_hint = value & 0b1 == 0;+ tracing::trace!("Branch hint: {branch_hint}");++ match value & 0b11110 {+ 0b00000 => Self::DecrementBranchIfNotZeroAndConditionFalse,+ 0b00010 => Self::DecrementBranchIfZeroAndConditionFalse,+ 0b00100 | 0b00110 => Self::BranchIfConditionFalse,+ 0b01000 => Self::DecrementBranchIfNotZeroAndConditionTrue,+ 0b01010 => Self::DecrementBranchIfZeroAndConditionTrue,+ 0b01100 | 0b01110 => Self::BranchIfConditionTrue,+ 0b10000 | 0b11000 => Self::DecrementBranchIfNotZero,+ 0b10010 | 0b11010 => Self::DecrementBranchIfZero,+ _ => Self::BranchAlways,+ }+ }++ pub fn should_branch(&self, ctr: u32, condition: bool) -> bool {+ match self {+ Self::BranchIfConditionTrue => condition,+ Self::BranchIfConditionFalse => !condition,+ Self::BranchAlways => true,+ Self::DecrementBranchIfNotZeroAndConditionFalse => ctr != 0 && !condition,+ Self::DecrementBranchIfZeroAndConditionFalse => ctr == 0 && !condition,+ Self::DecrementBranchIfNotZeroAndConditionTrue => ctr != 0 && condition,+ Self::DecrementBranchIfZeroAndConditionTrue => ctr == 0 && condition,+ Self::DecrementBranchIfNotZero => ctr != 0,+ Self::DecrementBranchIfZero => ctr == 0,+ }+ }++ pub fn should_decrement_ctr(&self) -> bool {+ matches!(+ self,+ Self::DecrementBranchIfNotZeroAndConditionFalse+ | Self::DecrementBranchIfZeroAndConditionFalse+ | Self::DecrementBranchIfNotZeroAndConditionTrue+ | Self::DecrementBranchIfZeroAndConditionTrue+ | Self::DecrementBranchIfNotZero+ | Self::DecrementBranchIfZero+ )+ }+}diff --git a/crates/gekko/src/cpu/interpreter.rs b/crates/gekko/src/cpu/interpreter.rsindex ea900f9..048b8e2 100644--- a/crates/gekko/src/cpu/interpreter.rs+++ b/crates/gekko/src/cpu/interpreter.rs@@ -1,3 +1,5 @@+use crate::cpu::branch::BranchControl;+pub fn branch<const OP: u32>(ctx: &mut crate::gekko::Gekko,instr: crate::cpu::semantics::Instruction,@@ -6,18 +8,45 @@ pub fn branch<const OP: u32>(ctx.cpu.lr = ctx.cpu.cia.wrapping_add(4);}- let target = match OP {+ match OP {crate::cpu::lut::OP_BX => {- if instr.aa() {+ ctx.cpu.nia = if instr.aa() {instr.li() as u32} else {ctx.cpu.cia.wrapping_add_signed(instr.li())}}- crate::cpu::lut::OP_BCLRX => ctx.cpu.lr,+ crate::cpu::lut::OP_BCLRX | crate::cpu::lut::OP_BCX => {+ let ctrl = BranchControl::from_bo(instr.bo());+ tracing::trace!("Branch control: {ctrl:?}");++ if ctrl.should_decrement_ctr() {+ ctx.cpu.ctr = ctx.cpu.ctr.wrapping_sub(1);+ }++ // TODO: cond missing+ if !ctrl.should_branch(ctx.cpu.ctr, true) {+ return;+ }++ match OP {+ crate::cpu::lut::OP_BCLRX => {+ ctx.cpu.nia = ctx.cpu.lr;+ }+ crate::cpu::lut::OP_BCX => {+ ctx.cpu.nia = if instr.aa() {+ instr.bd() as u32+ } else {+ ctx.cpu.cia.wrapping_add_signed(instr.bd())+ }+ }+ _ => {+ tracing::error!("missing OP = {OP:#x}");+ }+ }+ }_ => todo!("branch instruction with OP = {OP:#x}"),};- ctx.cpu.nia = target;}pub fn alu<const OP: u32>(@@ -57,10 +86,10 @@ pub fn msr<const OP: u32>() {match OP {crate::cpu::lut::OP_MTMSR => {- println!("OP_MTMSR!!");+ tracing::error!("OP_MTMSR!!");}crate::cpu::lut::OP_MFMSR => {- println!("OP_MFMSR!!");+ tracing::error!("OP_MFMSR!!");}_ => todo!("MSR instruction with OP = {OP:#x}"),}@@ -71,9 +100,12 @@ pub fn spr<const OP: u32>(instr: crate::cpu::semantics::Instruction,) {match OP {- crate::cpu::lut::OP_MTSPR => {- println!("OP_MTSPR!! {}", instr.spr());- }+ crate::cpu::lut::OP_MTSPR => match instr.spr() {+ 1 => ctx.cpu.xer = ctx.cpu.gprs[instr.rs()],+ 8 => ctx.cpu.lr = ctx.cpu.gprs[instr.rs()],+ 9 => ctx.cpu.ctr = ctx.cpu.gprs[instr.rs()],+ _ => todo!("unimplemented SPR number {}", instr.spr()),+ },crate::cpu::lut::OP_MFSPR => match instr.spr() {1 => ctx.cpu.gprs[instr.rd()] = ctx.cpu.xer,8 => ctx.cpu.gprs[instr.rd()] = ctx.cpu.lr,diff --git a/crates/gekko/src/cpu/semantics.rs b/crates/gekko/src/cpu/semantics.rsindex 6272051..2c49c55 100644--- a/crates/gekko/src/cpu/semantics.rs+++ b/crates/gekko/src/cpu/semantics.rs@@ -32,6 +32,6 @@ impl Instruction {#[inline] pub fn spr(&self) -> u32 { let raw = (self.0 >> 11) & 0x3ff; (raw >> 5) | ((raw & 0x1f) << 5) }- #[inline] pub fn bo(&self) -> u32 { (self.0 >> 21) & 0x1f }- #[inline] pub fn bi(&self) -> u32 { (self.0 >> 16) & 0x1f }+ #[inline] pub fn bo(&self) -> u8 { ((self.0 >> 21) & 0x1f) as u8 }+ #[inline] pub fn bi(&self) -> u8 { ((self.0 >> 16) & 0x1f) as u8 }}diff --git a/crates/gekko/src/mmu.rs b/crates/gekko/src/mmu.rsindex 80625a4..057e2b8 100644--- a/crates/gekko/src/mmu.rs+++ b/crates/gekko/src/mmu.rs@@ -21,24 +21,32 @@ impl Mmu {/// Resolve a physical address to a `(backing_slice, offset)` pair/// This is the one place that maps physical addresses to memory regions+ #[tracing::instrument(skip(self), level = "trace")]fn resolve(&self, phys: u32) -> (&[u8], usize) {match phys {RAM_BASE..=RAM_END => (&self.ram, phys as usize),EFB_BASE..=EFB_END => (&self.efb, (phys - EFB_BASE) as usize),HW_REG_BASE..=HW_REG_END => (&self.hwr, (phys - HW_REG_BASE) as usize),- _ => panic!("unmapped physical read at {phys:#010X}"),+ _ => {+ tracing::error!("unmapped physical read at {:08X}", phys);+ (&self.ram, 0)+ }}}/// Resolve a physical address to a `(backing_slice, offset)` pair/// This is the one place that maps physical addresses to memory regions/// Returns a mutable slice for write operations+ #[tracing::instrument(skip(self), level = "trace")]fn resolve_mut(&mut self, phys: u32) -> (&mut [u8], usize) {match phys {RAM_BASE..=RAM_END => (&mut self.ram, phys as usize),EFB_BASE..=EFB_END => (&mut self.efb, (phys - EFB_BASE) as usize),HW_REG_BASE..=HW_REG_END => (&mut self.hwr, (phys - HW_REG_BASE) as usize),- _ => panic!("unmapped physical write at {phys:#010X}"),+ _ => {+ tracing::error!("unmapped physical write at {:08X}", phys);+ (&mut self.ram, 0)+ }}}diff --git a/crates/tinyemu/Cargo.toml b/crates/tinyemu/Cargo.tomlindex 5a715c7..8f71890 100644--- a/crates/tinyemu/Cargo.toml+++ b/crates/tinyemu/Cargo.toml@@ -6,4 +6,6 @@ edition = "2024"[dependencies]gekko = { path = "../gekko" }colored = "3.1.1"-disasm = { path = "../disasm" }\ No newline at end of file+disasm = { path = "../disasm" }+tracing = "0.1"+tracing-subscriber = { version = "0.3.22", features = ["env-filter"] }diff --git a/crates/tinyemu/src/fmt.rs b/crates/tinyemu/src/fmt.rsindex 9d780e2..0c7fc9d 100644--- a/crates/tinyemu/src/fmt.rs+++ b/crates/tinyemu/src/fmt.rs@@ -27,3 +27,48 @@ pub fn colorize_instr(instr: &disasm::gekko::GekkoInstruction) -> String {.collect::<Vec<_>>().join("")}++pub fn gpr_refs(instr: &disasm::gekko::GekkoInstruction) -> Vec<u8> {+ let text = format!("{}", instr);+ let tokens = tokenizer::tokenize(&text);+ let mut seen = [false; 32];+ let mut refs = Vec::new();+ for tok in tokens {+ if let AsmToken::Gpr(n) = tok {+ let n = n as usize;+ if !seen[n] {+ seen[n] = true;+ refs.push(n as u8);+ }+ }+ }+ refs+}++pub fn reg_comment(gprs: &[u32; 32], refs: &[u8]) -> String {+ if refs.is_empty() {+ return String::new();+ }+ let parts: Vec<String> = refs+ .iter()+ .map(|&n| format!("r{}={:08X}", n, gprs[n as usize]))+ .collect();+ format!("; {}", parts.join(", ")).dimmed().to_string()+}++pub fn visible_len(s: &str) -> usize {+ let mut len = 0;+ let mut chars = s.chars();+ while let Some(c) = chars.next() {+ if c == '\x1b' {+ for c2 in chars.by_ref() {+ if c2 == 'm' {+ break;+ }+ }+ } else {+ len += 1;+ }+ }+ len+}diff --git a/crates/tinyemu/src/main.rs b/crates/tinyemu/src/main.rsindex 7f33077..76b2c3f 100644--- a/crates/tinyemu/src/main.rs+++ b/crates/tinyemu/src/main.rs@@ -11,6 +11,14 @@ fn main() {.expect("Usage: debugger <path_to_rom>");let is_debug = std::env::args().any(|arg| arg == "--debug");+ tracing_subscriber::fmt()+ .without_time()+ .with_env_filter(+ tracing_subscriber::EnvFilter::try_from_default_env()+ .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("warn")),+ )+ .init();+let mut gekko = gekko::gekko::Gekko::new(&path);let mut prev_snapshot = CpuSnapshot::from_cpu(&gekko.cpu);@@ -23,11 +31,22 @@ fn main() {dbg!(&instr);}- println!(+ let refs = fmt::gpr_refs(&instr);+ let comment = fmt::reg_comment(&prev_snapshot.gprs, &refs);++ let prefix = format!("{}: {}",format!("{:08X}", gekko.cpu.pc).bold(),fmt::colorize_instr(&instr));+ const COMMENT_COL: usize = 50;+ let pad = COMMENT_COL.saturating_sub(fmt::visible_len(&prefix));++ if comment.is_empty() {+ println!("{}", prefix);+ } else {+ println!("{}{}{}", prefix, " ".repeat(pad), comment);+ }gekko.run_until_event();let curr_snapshot = CpuSnapshot::from_cpu(&gekko.cpu);