A GameCube/Wii emulator and debugger written in Rust.
logging for apploader and FF crystal bearers
Layle8504acafe1ed
diff --git a/crates/debugger/src/main.rs b/crates/debugger/src/main.rsindex 65e5e25..e3fd3fc 100644--- a/crates/debugger/src/main.rs+++ b/crates/debugger/src/main.rs@@ -273,7 +273,7 @@ fn main() {let dvd = image::load_dvd(dvd_data);if dvd.header().is_wii() {eprintln!("Detected Wii disc, booting via apploader HLE");- EmulatorVariant::Wii(Wii::with_apploader_hle(dvd))+ EmulatorVariant::Wii(Wii::apploader_hle(dvd).build())} else {eprintln!("Detected GameCube disc, booting via IPL HLE");EmulatorVariant::Gc(GameCube::with_ipl_hle(dvd))diff --git a/crates/gecko/src/system.rs b/crates/gecko/src/system.rsindex 12894cb..197530c 100644--- a/crates/gecko/src/system.rs+++ b/crates/gecko/src/system.rs@@ -284,6 +284,16 @@ impl<const SYSTEM: SystemId> System<SYSTEM> {self.hook_host = Some(host);}+ #[cfg(feature = "hooks")]+ pub fn has_hook_host(&self) -> bool {+ self.hook_host.is_some()+ }++ #[cfg(not(feature = "hooks"))]+ pub fn has_hook_host(&self) -> bool {+ false+ }+#[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 {diff --git a/crates/gecko/src/wii.rs b/crates/gecko/src/wii.rsindex 0115bbe..cd0c17f 100644--- a/crates/gecko/src/wii.rs+++ b/crates/gecko/src/wii.rs@@ -34,7 +34,18 @@ impl Wii {Self::with_scheduler(entrypoint, Scheduler::new_wii())}- pub fn with_apploader_hle(dvd: Box<dyn image::Dvd>) -> Self {+ pub fn apploader_hle(dvd: Box<dyn image::Dvd>) -> ApploaderHleBuilder {+ ApploaderHleBuilder {+ dvd,+ #[cfg(feature = "hooks")]+ host: None,+ }+ }++ fn apploader_hle_run(+ dvd: Box<dyn image::Dvd>,+ #[cfg(feature = "hooks")] host: Option<Box<dyn crate::hooks::Host<{ WII }> + Send>>,+ ) -> Self {assert!(dvd.header().is_wii(), "apploader HLE only supports Wii discs");let game_name = String::from_utf8_lossy(&dvd.header().game_name);@@ -74,6 +85,11 @@ impl Wii {emu.gekko.gprs[1] = APPLOADER_STACK;+ #[cfg(feature = "hooks")]+ if let Some(host) = host {+ emu.set_hook_host(host);+ }+Self::run_apploader(&mut emu, dvd.as_ref(), apploader_entry);emu.insert_dvd(dvd);@@ -294,3 +310,25 @@ impl Wii {);}}++pub struct ApploaderHleBuilder {+ dvd: Box<dyn image::Dvd>,+ #[cfg(feature = "hooks")]+ host: Option<Box<dyn crate::hooks::Host<{ WII }> + Send>>,+}++impl ApploaderHleBuilder {+ #[cfg(feature = "hooks")]+ pub fn lua_host(mut self, host: Box<dyn crate::hooks::Host<{ WII }> + Send>) -> Self {+ self.host = Some(host);+ self+ }++ pub fn build(self) -> Wii {+ Wii::apploader_hle_run(+ self.dvd,+ #[cfg(feature = "hooks")]+ self.host,+ )+ }+}diff --git a/crates/scripting/src/lib.rs b/crates/scripting/src/lib.rsindex 2fffce7..47146c2 100644--- a/crates/scripting/src/lib.rs+++ b/crates/scripting/src/lib.rs@@ -1,9 +1,8 @@use std::collections::HashMap;+use std::path::PathBuf;#[cfg(feature = "hooks-mut-traps")]-use std::sync::{- Arc,- atomic::{AtomicBool, Ordering},-};+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Arc, Mutex};use gecko::hooks::{AddressFilter, BusAddressFilter, HookFilters, HookFlags, HookState, Host};use gecko::system::{System, SystemId};@@ -164,6 +163,31 @@ impl LuaHost {})?;lua.globals().set("log", log_fn)?;+ let script_dirs: Arc<Mutex<Vec<PathBuf>>> = Arc::new(Mutex::new(Vec::new()));+ if let Some(parent) = std::path::Path::new(name).parent() {+ script_dirs.lock().unwrap().push(parent.to_path_buf());+ }+ let include_dirs = Arc::clone(&script_dirs);+ let include_fn = lua.create_function(move |lua, path: String| {+ let resolved = {+ let stack = include_dirs.lock().unwrap();+ let base = stack.last().cloned().unwrap_or_default();+ base.join(&path)+ };+ let source = std::fs::read_to_string(&resolved)+ .map_err(|e| mlua::Error::runtime(format!("include {resolved:?}: {e}")))?;+ let pushed = resolved.parent().map(|p| p.to_path_buf());+ if let Some(ref d) = pushed {+ include_dirs.lock().unwrap().push(d.clone());+ }+ let result = lua.load(&source).set_name(resolved.to_string_lossy().as_ref()).exec();+ if pushed.is_some() {+ include_dirs.lock().unwrap().pop();+ }+ result+ })?;+ lua.globals().set("include", include_fn)?;+#[cfg(feature = "hooks-mut-traps")]{let refresh_requested_fn = refresh_requested.clone();diff --git a/crates/tinyapp/src/main.rs b/crates/tinyapp/src/main.rsindex 0580fa9..75a6d12 100644--- a/crates/tinyapp/src/main.rs+++ b/crates/tinyapp/src/main.rs@@ -90,7 +90,15 @@ fn main() {let dvd = image::load_dvd(dvd_data);if dvd.header().is_wii() {println!("Detected Wii disc, booting via apploader HLE");- let mut emulator = Wii::with_apploader_hle(dvd);+ let builder = Wii::apploader_hle(dvd);+ #[cfg(feature = "scripting")]+ let builder = if let Some(ref path) = args.script {+ let host = scripting::LuaHost::from_file(path).expect("failed to load script");+ builder.lua_host(Box::new(host))+ } else {+ builder+ };+ let mut emulator = builder.build();configure(&mut emulator, &args);run(emulator, present_mode);} else {@@ -112,8 +120,12 @@ fn configure<const SYSTEM: SystemId>(emulator: &mut System<SYSTEM>, args: &Args)#[cfg(feature = "scripting")]if let Some(ref path) = args.script {- let host = scripting::LuaHost::from_file(path).expect("failed to load script");- emulator.set_hook_host(Box::new(host));+ // Already attached for Wii apploader HLE; only attach here for other+ // boot paths.+ if !emulator.has_hook_host() {+ let host = scripting::LuaHost::from_file(path).expect("failed to load script");+ emulator.set_hook_host(Box::new(host));+ }}emulator.add_primary_controller(PadStatus {diff --git a/scripts/apploader_osreport.lua b/scripts/apploader_osreport.luanew file mode 100644index 0000000..c84d248--- /dev/null+++ b/scripts/apploader_osreport.lua@@ -0,0 +1,87 @@+local OSREPORT_STUB = 0x81300000++function read_cstring(emu, addr)+ local chars = {}+ for i = 0, 1023 do+ local b = emu:read_u8(addr + i)+ if b == 0 then break end+ chars[#chars + 1] = string.char(b)+ end+ return table.concat(chars)+end++function printf(emu, fmt, args)+ local out = {}+ local i = 1+ local arg_idx = 1+ local function next_arg()+ local v = args[arg_idx] or 0+ arg_idx = arg_idx + 1+ return v+ end++ while i <= #fmt do+ local c = fmt:sub(i, i)+ if c ~= "%" then+ out[#out + 1] = c+ i = i + 1+ else+ i = i + 1+ local spec = "%"+ if fmt:sub(i, i) == "0" then+ spec = spec .. "0"+ i = i + 1+ end+ while fmt:sub(i, i):match("%d") do+ spec = spec .. fmt:sub(i, i)+ i = i + 1+ end+ local kind = fmt:sub(i, i)+ i = i + 1+ if kind == "%" then+ out[#out + 1] = "%"+ elseif kind == "d" or kind == "i" then+ local v = next_arg()+ if v >= 0x80000000 then v = v - 0x100000000 end+ out[#out + 1] = string.format(spec .. "d", v)+ elseif kind == "u" then+ out[#out + 1] = string.format(spec .. "u", next_arg())+ elseif kind == "x" then+ out[#out + 1] = string.format(spec .. "x", next_arg())+ elseif kind == "X" then+ out[#out + 1] = string.format(spec .. "X", next_arg())+ elseif kind == "s" then+ out[#out + 1] = read_cstring(emu, next_arg())+ elseif kind == "c" then+ out[#out + 1] = string.char(next_arg() % 256)+ else+ out[#out + 1] = spec .. kind+ end+ end+ end+ return table.concat(out)+end++function emit(prefix, msg)+ msg = msg:gsub("[\r\n]+$", "")+ for line in (msg .. "\n"):gmatch("([^\n]*)\n") do+ if #line > 0 then+ log(prefix .. line)+ end+ end+end++function dispatch_printf(prefix)+ return function(emu)+ local fmt = read_cstring(emu, emu:gpr(3))+ local args = {+ emu:gpr(4), emu:gpr(5), emu:gpr(6), emu:gpr(7),+ emu:gpr(8), emu:gpr(9), emu:gpr(10),+ }+ emit(prefix, printf(emu, fmt, args))+ end+end++traps = traps or {}+traps.cpu_pre = traps.cpu_pre or {}+traps.cpu_pre[OSREPORT_STUB] = dispatch_printf("[apploader] ")diff --git a/scripts/ff_logger.lua b/scripts/ff_logger.luanew file mode 100644index 0000000..7588b54--- /dev/null+++ b/scripts/ff_logger.lua@@ -0,0 +1,29 @@+-- Hooks OSReport / OSReportLn / OSPanic in Final Fantasy Crystal Chronicles: The Crystal Bearers+-- It also includes the Apploader logs.+--+-- Addresses are from the FF main.dol:+-- OSReport @ 0x803756F0 - OSReport(fmt, ...)+-- OSReportLn @ 0x80378D40 - OSReportLn(fmt, ...)+-- OSPanic @ 0x80378DC0 - OSPanic(file, line, fmt, ...) [no return]++include("apploader_osreport.lua")++local OS_REPORT = 0x803756F0+local OS_REPORT_LN = 0x80378D40+local OS_PANIC = 0x80378DC0++local function on_panic(emu)+ local file = read_cstring(emu, emu:gpr(3))+ local line = emu:gpr(4)+ local fmt = read_cstring(emu, emu:gpr(5))+ local args = {+ emu:gpr(6), emu:gpr(7), emu:gpr(8),+ emu:gpr(9), emu:gpr(10),+ }+ emit("[OSPanic] ", printf(emu, fmt, args))+ log(string.format("[OSPanic] at %s:%d", file, line))+end++traps.cpu_pre[OS_REPORT] = dispatch_printf("[OSReport] ")+traps.cpu_pre[OS_REPORT_LN] = dispatch_printf("[OSReportLn] ")+traps.cpu_pre[OS_PANIC] = on_panic