Skip to content

armgit / gecko

Public Imported from GitHub
0

A GameCube/Wii emulator and debugger written in Rust.

ipl decoder/encoder in gctool

Layleac6f7e7d36ab
diff --git a/Cargo.lock b/Cargo.lock
index a2a838b..c956f59 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -96,9 +96,9 @@ dependencies = [
[[package]]
name = "anstream"
-version = "0.6.21"
+version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "43d5b281e737544384e969a5ccad3f1cdd24b48086a0fc1b2a5262a26b8f4f4a"
+checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
dependencies = [
"anstyle",
"anstyle-parse",
@@ -117,9 +117,9 @@ checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78"
[[package]]
name = "anstyle-parse"
-version = "0.2.7"
+version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4e7644824f0aa2c7b9384579234ef10eb7efb6a0deb83f9630a49594dd9c15c2"
+checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
dependencies = [
"utf8parse",
]
@@ -405,9 +405,9 @@ checksum = "a7d2ab3ac8eccf8652db81b52914ee4822e03efb764d16e72791a46366071032"
[[package]]
name = "clap"
-version = "4.5.60"
+version = "4.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2797f34da339ce31042b27d23607e051786132987f595b02ba4f6a6dffb7030a"
+checksum = "b193af5b67834b676abd72466a96c1024e6a6ad978a1f484bd90b85c94041351"
dependencies = [
"clap_builder",
"clap_derive",
@@ -415,9 +415,9 @@ dependencies = [
[[package]]
name = "clap_builder"
-version = "4.5.60"
+version = "4.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "24a241312cea5059b13574bb9b3861cabf758b879c15190b37b6d6fd63ab6876"
+checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f"
dependencies = [
"anstream",
"anstyle",
@@ -427,9 +427,9 @@ dependencies = [
[[package]]
name = "clap_derive"
-version = "4.5.55"
+version = "4.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a92793da1a46a5f2a02a6f4c46c6496b28c43638adea8306fcb0caa1634f24e5"
+checksum = "1110bd8a634a1ab8cb04345d8d878267d57c3cf1b38d91b71af6686408bbca6a"
dependencies = [
"heck",
"proc-macro2",
@@ -484,7 +484,7 @@ version = "3.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34"
dependencies = [
- "windows-sys 0.61.2",
+ "windows-sys 0.52.0",
]
[[package]]
@@ -633,7 +633,6 @@ name = "debugger"
version = "0.1.0"
dependencies = [
"backend-wgpu",
- "bytemuck",
"disasm",
"egui",
"egui-wgpu",
@@ -840,7 +839,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
- "windows-sys 0.61.2",
+ "windows-sys 0.52.0",
]
[[package]]
@@ -1630,7 +1629,7 @@ version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [
- "windows-sys 0.61.2",
+ "windows-sys 0.59.0",
]
[[package]]
@@ -1955,9 +1954,9 @@ dependencies = [
[[package]]
name = "once_cell"
-version = "1.21.3"
+version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "once_cell_polyfill"
@@ -2318,7 +2317,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys 0.12.1",
- "windows-sys 0.61.2",
+ "windows-sys 0.52.0",
]
[[package]]
@@ -2700,7 +2699,6 @@ name = "tinyapp"
version = "0.1.0"
dependencies = [
"backend-wgpu",
- "bytemuck",
"egui",
"egui-wgpu",
"egui-winit",
@@ -2723,7 +2721,6 @@ dependencies = [
"disasm",
"gekko",
"image 0.1.0",
- "tracing",
"tracing-subscriber",
]
@@ -2813,9 +2810,9 @@ dependencies = [
[[package]]
name = "tracing-subscriber"
-version = "0.3.22"
+version = "0.3.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2f30143827ddab0d256fd843b7a66d164e9f271cfa0dde49142c5ca0ca291f1e"
+checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319"
dependencies = [
"matchers",
"nu-ansi-term",
@@ -3351,7 +3348,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
- "windows-sys 0.61.2",
+ "windows-sys 0.52.0",
]
[[package]]
diff --git a/Cargo.toml b/Cargo.toml
index 96220f7..bca3626 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -21,7 +21,9 @@ egui-winit = { git = "https://github.com/ioncodes/egui.git" }
[profile.release]
lto = "fat"
-#debug = true
+codegen-units = 1
+debug = false
+opt-level = 3
[profile.dev]
opt-level = 3
diff --git a/crates/debugger/Cargo.toml b/crates/debugger/Cargo.toml
index a713f0e..beac018 100644
--- a/crates/debugger/Cargo.toml
+++ b/crates/debugger/Cargo.toml
@@ -14,5 +14,4 @@ pollster = "0.4"
egui = "0.33"
egui-wgpu = "0.33"
egui-winit = { version = "0.33", features = ["wayland", "x11"] }
-bytemuck = { version = "1", features = ["derive"] }
egui_material_icons = "0.5.0"
diff --git a/crates/gctool/Cargo.toml b/crates/gctool/Cargo.toml
index 8b41294..f3cad16 100644
--- a/crates/gctool/Cargo.toml
+++ b/crates/gctool/Cargo.toml
@@ -4,7 +4,7 @@ version = "0.1.0"
edition = "2024"
[dependencies]
-clap = { version = "4", features = ["derive"] }
+clap = { version = "4.6.0", features = ["derive"] }
disasm = { path = "../disasm" }
image = { path = "../image" }
comfy-table = "7.2.2"
\ No newline at end of file
diff --git a/crates/gctool/src/cli.rs b/crates/gctool/src/cli.rs
new file mode 100644
index 0000000..ede06f7
--- /dev/null
+++ b/crates/gctool/src/cli.rs
@@ -0,0 +1,58 @@
+use clap::{Parser, Subcommand, ValueEnum};
+
+pub fn parse_offset(s: &str) -> Result<usize, String> {
+ if let Some(hex) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
+ usize::from_str_radix(hex, 16).map_err(|e| e.to_string())
+ } else {
+ s.parse().map_err(|e: std::num::ParseIntError| e.to_string())
+ }
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
+pub enum DisasmArch {
+ Ppc,
+ Dsp,
+}
+
+#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
+pub enum IplAction {
+ Decode,
+ Encode,
+}
+
+#[derive(Subcommand)]
+pub enum Command {
+ /// Show file header information
+ Info {
+ /// Input DOL file
+ file: String,
+ },
+ /// Disassemble binary code
+ Disasm {
+ /// Target architecture
+ #[arg(long, value_enum, default_value_t = DisasmArch::Ppc)]
+ arch: DisasmArch,
+ /// Start offset (hex or decimal)
+ #[arg(long, value_parser = parse_offset)]
+ offset: Option<usize>,
+ /// Input file
+ file: String,
+ },
+ /// Decode or encode a GameCube IPL
+ Ipl {
+ /// IPL transformation to apply
+ #[arg(long, value_enum, default_value_t = IplAction::Decode)]
+ action: IplAction,
+ /// Input IPL file
+ file: String,
+ /// Output file path (defaults to <name>.encoded.bin or <name>.decoded.bin)
+ output: Option<String>,
+ },
+}
+
+#[derive(Parser)]
+#[command(about = "GameCube multi-tool", long_about = None)]
+pub struct Args {
+ #[command(subcommand)]
+ pub command: Command,
+}
diff --git a/crates/gctool/src/disassembly.rs b/crates/gctool/src/disassembly.rs
new file mode 100644
index 0000000..f96d594
--- /dev/null
+++ b/crates/gctool/src/disassembly.rs
@@ -0,0 +1,40 @@
+use disasm::dsp::DspInstruction;
+use disasm::gekko::GekkoInstruction;
+
+pub fn disassemble_ppc(data: &[u8], start: usize) {
+ let mut offset = start;
+ while offset + 4 <= data.len() {
+ let word = u32::from_be_bytes(data[offset..offset + 4].try_into().unwrap());
+ let addr = offset as u32;
+
+ match GekkoInstruction::decode(&data[offset..]) {
+ Some((instr, _)) => println!("{:08X} {:08X} {}", addr, word, instr),
+ None => println!("{:08X} {:08X} .long {:#010x}", addr, word, word),
+ }
+
+ offset += 4;
+ }
+}
+
+pub fn disassemble_dsp(data: &[u8], start: usize) {
+ let mut offset = start;
+ while offset + 2 <= data.len() {
+ let word = u16::from_be_bytes(data[offset..offset + 2].try_into().unwrap());
+ let addr = (offset / 2) as u32;
+
+ match DspInstruction::decode(&data[offset..]) {
+ Some((instr, bytes_consumed)) => {
+ let hex_parts: Vec<_> = data[offset..offset + bytes_consumed]
+ .chunks_exact(2)
+ .map(|c| format!("{:04x}", u16::from_be_bytes(c.try_into().unwrap())))
+ .collect();
+ println!("{:04x} {:9} {}", addr, hex_parts.join(" "), instr);
+ offset += bytes_consumed;
+ }
+ None => {
+ println!("{:04x} {:04x} .word {:#06x}", addr, word, word);
+ offset += 2;
+ }
+ }
+ }
+}
diff --git a/crates/gctool/src/dol.rs b/crates/gctool/src/dol.rs
new file mode 100644
index 0000000..66dab12
--- /dev/null
+++ b/crates/gctool/src/dol.rs
@@ -0,0 +1,37 @@
+use comfy_table::{Table, presets::ASCII_MARKDOWN};
+use image::{Dol, Executable};
+
+fn section_table(sections: &[image::Section]) -> Table {
+ let mut table = Table::new();
+ table.load_preset(ASCII_MARKDOWN);
+ table.set_header(vec!["idx", "offset", "vaddr", "size", "end"]);
+ for (i, s) in sections.iter().enumerate() {
+ table.add_row(vec![
+ format!("{i}"),
+ format!("0x{:08X}", s.offset),
+ format!("0x{:08X}", s.vaddr),
+ format!("0x{:08X}", s.size),
+ format!("0x{:08X}", s.vaddr + s.size),
+ ]);
+ }
+ table
+}
+
+pub fn info(data: Vec<u8>) {
+ let dol = Dol::parse(data);
+
+ println!("Text Sections ({}):", dol.text_sections().len());
+ println!("{}\n", section_table(dol.text_sections()));
+
+ println!("Data Sections ({}):", dol.data_sections().len());
+ println!("{}\n", section_table(dol.data_sections()));
+
+ let (bss_start, bss_size) = dol.bss();
+ println!("Entry point: 0x{:08X}\n", dol.entry_point());
+ println!(
+ "BSS: 0x{:08X} - 0x{:08X} (size: 0x{:08X})",
+ bss_start,
+ bss_start + bss_size,
+ bss_size
+ );
+}
diff --git a/crates/gctool/src/ipl.rs b/crates/gctool/src/ipl.rs
new file mode 100644
index 0000000..f2d5a82
--- /dev/null
+++ b/crates/gctool/src/ipl.rs
@@ -0,0 +1,122 @@
+use crate::cli::IplAction;
+
+use std::fs;
+use std::path::Path;
+use std::process;
+
+const IPL_ROM_SIZE: usize = 0x200000;
+const SCRAMBLE_START: usize = 0x100;
+const SCRAMBLE_SIZE: usize = 0x1AFE00;
+
+fn decode(data: &mut [u8]) {
+ let region = &mut data[SCRAMBLE_START..SCRAMBLE_START + SCRAMBLE_SIZE];
+
+ let mut acc: u8 = 0;
+ let mut nacc: u8 = 0;
+
+ let mut t: u16 = 0x2953;
+ let mut u: u16 = 0xD9C2;
+ let mut v: u16 = 0x3FF1;
+
+ let mut x: u8 = 1;
+
+ let mut it = 0;
+ while it < region.len() {
+ let t0 = (t & 1) as u8;
+ let t1 = ((t >> 1) & 1) as u8;
+ let u0 = (u & 1) as u8;
+ let u1 = ((u >> 1) & 1) as u8;
+ let v0 = (v & 1) as u8;
+
+ x ^= t1 ^ v0;
+ x ^= u0 | u1;
+ x ^= (t0 ^ u1 ^ v0) & (t0 ^ u0);
+
+ if t0 == u0 {
+ v >>= 1;
+ if v0 != 0 {
+ v ^= 0xB3D0;
+ }
+ }
+
+ if t0 == 0 {
+ u >>= 1;
+ if u0 != 0 {
+ u ^= 0xFB10;
+ }
+ }
+
+ t >>= 1;
+ if t0 != 0 {
+ t ^= 0xA740;
+ }
+
+ nacc += 1;
+ acc = acc.wrapping_shl(1) + x;
+ if nacc == 8 {
+ region[it] ^= acc;
+ nacc = 0;
+ it += 1;
+ }
+ }
+}
+
+fn is_encoded(data: &[u8]) -> bool {
+ if data.len() < 0x104 {
+ return true;
+ }
+ let w = u32::from_be_bytes(data[0x100..0x104].try_into().unwrap());
+ // Decoded BS1 starts with `lis r4, 0x0011`
+ w != 0x3C800011
+}
+
+pub fn process_ipl(file: &str, output: Option<&str>, action: IplAction) {
+ let mut data = fs::read(file).unwrap_or_else(|e| {
+ eprintln!("failed to read {}: {}", file, e);
+ process::exit(1);
+ });
+ assert_eq!(data.len(), IPL_ROM_SIZE);
+
+ let encoded = is_encoded(&data);
+
+ match action {
+ IplAction::Encode if encoded => eprintln!("warning: ROM appears already encoded"),
+ IplAction::Decode if !encoded => eprintln!("warning: ROM appears already decoded"),
+ _ => {}
+ }
+
+ let copyright = String::from_utf8_lossy(&data[..0x56]);
+ let action_label = match action {
+ IplAction::Decode => "Decoding",
+ IplAction::Encode => "Encoding",
+ };
+ println!("{action_label}: {file}");
+ println!(" {copyright}");
+
+ decode(&mut data);
+
+ let out_path = match output {
+ Some(p) => p.to_string(),
+ None => {
+ let p = Path::new(file);
+ let stem = p.file_stem().unwrap_or_default().to_string_lossy();
+ let ext = p
+ .extension()
+ .map(|e| format!(".{}", e.to_string_lossy()))
+ .unwrap_or_default();
+ let suffix = match action {
+ IplAction::Encode => ".encoded",
+ IplAction::Decode => ".decoded",
+ };
+ format!("{}{}{}", stem, suffix, ext)
+ }
+ };
+
+ fs::write(&out_path, &data).unwrap_or_else(|e| {
+ eprintln!("failed to write {}: {}", out_path, e);
+ process::exit(1);
+ });
+
+ let state = if is_encoded(&data) { "encoded" } else { "decoded" };
+ eprintln!(" output ({state}): {out_path}");
+}
diff --git a/crates/gctool/src/main.rs b/crates/gctool/src/main.rs
index 4f25c25..6c5db7c 100644
--- a/crates/gctool/src/main.rs
+++ b/crates/gctool/src/main.rs
@@ -1,143 +1,51 @@
-use disasm::dsp::DspInstruction;
-use disasm::gekko::GekkoInstruction;
-use image::{Dol, Executable};
+mod cli;
+mod disassembly;
+mod dol;
+mod ipl;
-use clap::{Parser, ValueEnum};
-use comfy_table::{Table, presets::ASCII_MARKDOWN};
+use crate::cli::{Args, Command, DisasmArch};
+use crate::disassembly::{disassemble_dsp, disassemble_ppc};
+use crate::dol::info;
+use crate::ipl::process_ipl;
+
+use clap::Parser;
use std::fs;
use std::process;
-#[derive(Debug, Clone, Copy, ValueEnum)]
-enum Mode {
- Dol,
- Dsp,
-}
-
-fn parse_offset(s: &str) -> Result<usize, String> {
- if let Some(hex) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
- usize::from_str_radix(hex, 16).map_err(|e| e.to_string())
- } else {
- s.parse().map_err(|e: std::num::ParseIntError| e.to_string())
- }
-}
-
-#[derive(Parser)]
-#[command(about = "GameCube multi-tool", long_about = None)]
-struct Args {
- #[arg(short, long, value_enum, default_value_t = Mode::Dol)]
- mode: Mode,
- /// Inspect file headers instead of disassembling
- #[arg(short, long)]
- inspect: bool,
- file: String,
- #[arg(value_parser = parse_offset, default_value_t = 0)]
- offset: usize,
-}
-
-fn disassemble_dol(data: &[u8], start: usize) {
- let mut offset = start;
- while offset + 4 <= data.len() {
- let word = u32::from_be_bytes(data[offset..offset + 4].try_into().unwrap());
- let addr = offset as u32;
-
- match GekkoInstruction::decode(&data[offset..]) {
- Some((instr, _)) => println!("{:08X} {:08X} {}", addr, word, instr),
- None => println!("{:08X} {:08X} .long {:#010x}", addr, word, word),
- }
-
- offset += 4;
- }
-}
-
-fn disassemble_dsp(data: &[u8], start: usize) {
- let mut offset = start;
- while offset + 2 <= data.len() {
- let word = u16::from_be_bytes(data[offset..offset + 2].try_into().unwrap());
- let addr = (offset / 2) as u32;
-
- match DspInstruction::decode(&data[offset..]) {
- Some((instr, bytes_consumed)) => {
- let hex_parts: Vec<_> = data[offset..offset + bytes_consumed]
- .chunks_exact(2)
- .map(|c| format!("{:04x}", u16::from_be_bytes(c.try_into().unwrap())))
- .collect();
- println!("{:04x} {:9} {}", addr, hex_parts.join(" "), instr);
- offset += bytes_consumed;
- }
- None => {
- println!("{:04x} {:04x} .word {:#06x}", addr, word, word);
- offset += 2;
- }
- }
- }
-}
-
-fn section_table(sections: &[image::Section]) -> Table {
- let mut table = Table::new();
- table.load_preset(ASCII_MARKDOWN);
- table.set_header(vec!["idx", "offset", "vaddr", "size", "end"]);
- for (i, s) in sections.iter().enumerate() {
- table.add_row(vec![
- format!("{i}"),
- format!("0x{:08X}", s.offset),
- format!("0x{:08X}", s.vaddr),
- format!("0x{:08X}", s.size),
- format!("0x{:08X}", s.vaddr + s.size),
- ]);
- }
- table
-}
-
-fn inspect_dol(data: Vec<u8>) {
- let dol = Dol::parse(data);
-
- println!("Text Sections ({}):", dol.text_sections().len());
- println!("{}\n", section_table(dol.text_sections()));
-
- println!("Data Sections ({}):", dol.data_sections().len());
- println!("{}\n", section_table(dol.data_sections()));
-
- let (bss_start, bss_size) = dol.bss();
- println!("Entry point: 0x{:08X}\n", dol.entry_point());
- println!(
- "BSS: 0x{:08X} - 0x{:08X} (size: 0x{:08X})",
- bss_start,
- bss_start + bss_size,
- bss_size
- );
+fn read_file_or_exit(file: &str) -> Vec<u8> {
+ fs::read(file).unwrap_or_else(|e| {
+ eprintln!("failed to read {}: {}", file, e);
+ process::exit(1);
+ })
}
fn main() {
let args = Args::parse();
- let data = fs::read(&args.file).unwrap_or_else(|e| {
- eprintln!("failed to read {}: {}", args.file, e);
- process::exit(1);
- });
-
- if args.inspect {
- match args.mode {
- Mode::Dol => inspect_dol(data),
- Mode::Dsp => {
- eprintln!("inspect is only supported for DOL files");
+ match &args.command {
+ Command::Info { file } => {
+ info(read_file_or_exit(file));
+ }
+ Command::Disasm { arch, offset, file } => {
+ let data = read_file_or_exit(file);
+
+ let start = offset.unwrap_or(0);
+ let min_size = match arch {
+ DisasmArch::Dsp => 2,
+ DisasmArch::Ppc => 4,
+ };
+ if data.len() < start + min_size {
+ eprintln!("file too small for offset {:#x}", start);
process::exit(1);
}
- }
- return;
- }
-
- let min_size = match args.mode {
- Mode::Dol => 4,
- Mode::Dsp => 2,
- };
-
- if data.len() < args.offset + min_size {
- eprintln!("file too small for offset {:#x}", args.offset);
- process::exit(1);
- }
- match args.mode {
- Mode::Dol => disassemble_dol(&data, args.offset),
- Mode::Dsp => disassemble_dsp(&data, args.offset),
+ match arch {
+ DisasmArch::Dsp => disassemble_dsp(&data, start),
+ DisasmArch::Ppc => disassemble_ppc(&data, start),
+ }
+ }
+ Command::Ipl { action, file, output } => {
+ process_ipl(file, output.as_deref(), *action);
+ }
}
}
diff --git a/crates/tinyapp/Cargo.toml b/crates/tinyapp/Cargo.toml
index 3ab762c..2f7de19 100644
--- a/crates/tinyapp/Cargo.toml
+++ b/crates/tinyapp/Cargo.toml
@@ -14,5 +14,4 @@ egui = "0.33"
egui-wgpu = "0.33"
egui-winit = { version = "0.33", features = ["wayland", "x11"] }
egui_plot = "0.34"
-bytemuck = { version = "1", features = ["derive"] }
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
diff --git a/crates/tinyemu/Cargo.toml b/crates/tinyemu/Cargo.toml
index d689bf9..138eefc 100644
--- a/crates/tinyemu/Cargo.toml
+++ b/crates/tinyemu/Cargo.toml
@@ -8,7 +8,6 @@ gekko = { path = "../gekko" }
image = { path = "../image" }
colored = "3.1.1"
disasm = { path = "../disasm" }
-tracing = "0.1"
-tracing-subscriber = { version = "0.3.22", features = ["env-filter"] }
+tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
base64 = "0.22"
-clap = { version = "4.5.60", features = ["derive"] }
+clap = { version = "4.6.0", features = ["derive"] }