A GameCube/Wii emulator and debugger written in Rust.
extract symbols from elf
Layle4f6655c9adee
diff --git a/Cargo.lock b/Cargo.lockindex 34b2d32..09e22d5 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -214,10 +214,6 @@ dependencies = ["litrs",]-[[package]]-name = "dol"-version = "0.1.0"-[[package]]name = "errno"version = "0.3.14"@@ -235,7 +231,7 @@ dependencies = ["clap","comfy-table","disasm",- "dol",+ "image",][[package]]@@ -244,7 +240,7 @@ version = "0.1.0"dependencies = ["chapa","chipi 0.5.1",- "dol",+ "image","tracing",]@@ -254,6 +250,13 @@ version = "0.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"+[[package]]+name = "image"+version = "0.1.0"+dependencies = [+ "object",+]+[[package]]name = "is_terminal_polyfill"version = "1.70.2"@@ -323,6 +326,15 @@ dependencies = ["windows-sys",]+[[package]]+name = "object"+version = "0.36.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "62948e14d923ea95ea2c7c86c71013138b66525b86bdc08d2dcc262bdb497b87"+dependencies = [+ "memchr",+]+[[package]]name = "once_cell"version = "1.21.3"@@ -477,6 +489,7 @@ dependencies = ["colored","disasm","gekko",+ "image","tracing","tracing-subscriber",]diff --git a/Cargo.toml b/Cargo.tomlindex fe84a82..4cae363 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -1,6 +1,6 @@[workspace]resolver = "3"-members = ["crates/gctool", "crates/disasm", "crates/gekko", "crates/tinyemu", "crates/dol"]+members = ["crates/gctool", "crates/disasm", "crates/gekko", "crates/tinyemu", "crates/image"][profile.release]lto = "fat"diff --git a/crates/dol/Cargo.toml b/crates/dol/Cargo.tomldeleted file mode 100644index aa35fbc..0000000--- a/crates/dol/Cargo.toml+++ /dev/null@@ -1,6 +0,0 @@-[package]-name = "dol"-version = "0.1.0"-edition = "2024"--[dependencies]diff --git a/crates/dol/src/lib.rs b/crates/dol/src/lib.rsdeleted file mode 100644index e7a3c02..0000000--- a/crates/dol/src/lib.rs+++ /dev/null@@ -1,52 +0,0 @@-pub struct Section {- pub offset: u32,- pub vaddr: u32,- pub size: u32,-}--pub struct Dol {- pub text_sections: Vec<Section>,- pub data_sections: Vec<Section>,- pub bss_start: u32,- pub bss_size: u32,- pub entry_point: u32,-}--impl Dol {- pub fn parse(data: &[u8]) -> Self {- let mut text_sections = Vec::new();- let mut data_sections = Vec::new();-- for i in 0..=6 {- let offset = u32::from_be_bytes(data[0x00 + (i * 4)..0x00 + (i * 4) + 4].try_into().unwrap());- let vaddr = u32::from_be_bytes(data[0x48 + (i * 4)..0x48 + (i * 4) + 4].try_into().unwrap());- let size = u32::from_be_bytes(data[0x90 + (i * 4)..0x90 + (i * 4) + 4].try_into().unwrap());-- if size > 0 {- text_sections.push(Section { offset, vaddr, size });- }- }-- for i in 0..=10 {- let offset = u32::from_be_bytes(data[0x1C + (i * 4)..0x1C + (i * 4) + 4].try_into().unwrap());- let vaddr = u32::from_be_bytes(data[0x64 + (i * 4)..0x64 + (i * 4) + 4].try_into().unwrap());- let size = u32::from_be_bytes(data[0xAC + (i * 4)..0xAC + (i * 4) + 4].try_into().unwrap());-- if size > 0 {- data_sections.push(Section { offset, vaddr, size });- }- }-- let bss_start = u32::from_be_bytes(data[0xD8..0xDC].try_into().unwrap());- let bss_size = u32::from_be_bytes(data[0xDC..0xE0].try_into().unwrap());- let entry_point = u32::from_be_bytes(data[0xE0..0xE4].try_into().unwrap());-- Dol {- text_sections,- data_sections,- bss_start,- bss_size,- entry_point,- }- }-}\ No newline at end of filediff --git a/crates/gctool/Cargo.toml b/crates/gctool/Cargo.tomlindex 5e30595..8b41294 100644--- a/crates/gctool/Cargo.toml+++ b/crates/gctool/Cargo.toml@@ -6,5 +6,5 @@ edition = "2024"[dependencies]clap = { version = "4", features = ["derive"] }disasm = { path = "../disasm" }-dol = { path = "../dol" }+image = { path = "../image" }comfy-table = "7.2.2"\ No newline at end of filediff --git a/crates/gctool/src/main.rs b/crates/gctool/src/main.rsindex d76cdca..68d9444 100644--- a/crates/gctool/src/main.rs+++ b/crates/gctool/src/main.rs@@ -1,6 +1,6 @@use disasm::dsp::DspInstruction;use disasm::gekko::GekkoInstruction;-use dol::Dol;+use image::{Dol, Executable};use clap::{Parser, ValueEnum};use comfy_table::{Table, presets::ASCII_MARKDOWN};@@ -73,7 +73,7 @@ fn disassemble_dsp(data: &[u8], start: usize) {}}-fn section_table(sections: &[dol::Section]) -> Table {+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"]);@@ -89,21 +89,22 @@ fn section_table(sections: &[dol::Section]) -> Table {table}-fn inspect_dol(data: &[u8]) {+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!("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));+ println!("Data Sections ({}):", dol.data_sections().len());+ println!("{}\n", section_table(dol.data_sections()));- println!("Entry point: 0x{:08X}\n", dol.entry_point);+ 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})",- dol.bss_start,- dol.bss_start + dol.bss_size,- dol.bss_size+ bss_start,+ bss_start + bss_size,+ bss_size);}@@ -117,7 +118,7 @@ fn main() {if args.inspect {match args.mode {- Mode::Dol => inspect_dol(&data),+ Mode::Dol => inspect_dol(data),Mode::Dsp => {eprintln!("inspect is only supported for DOL files");process::exit(1);diff --git a/crates/gekko/Cargo.toml b/crates/gekko/Cargo.tomlindex 39e1a25..2e4b877 100644--- a/crates/gekko/Cargo.toml+++ b/crates/gekko/Cargo.toml@@ -9,4 +9,4 @@ chipi = "0.5.1"[dependencies]chapa = { git = "http://github.com/ioncodes/chapa" }tracing = "0.1.44"-dol = { path = "../dol" }\ No newline at end of file+image = { path = "../image" }\ No newline at end of filediff --git a/crates/gekko/src/gekko.rs b/crates/gekko/src/gekko.rsindex e1bef45..82f22d9 100644--- a/crates/gekko/src/gekko.rs+++ b/crates/gekko/src/gekko.rs@@ -4,7 +4,7 @@ use crate::{scheduler::Scheduler,vi::Vi,};-use dol::Dol;+use image::Executable;pub struct Gekko {pub cpu: Cpu,@@ -14,13 +14,12 @@ pub struct Gekko {}impl Gekko {- pub fn new(path: &str) -> Self {+ pub fn new(exe: &impl Executable) -> Self {let mut mmio = Mmio::new();- let data = std::fs::read(path).expect("failed to read ROM");- let dol = Dol::parse(&data);+ let data = exe.data();// Copy TEXT sections to memory- for section in &dol.text_sections {+ 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];@@ -29,7 +28,7 @@ impl Gekko {}// Copy DATA sections to memory- for section in &dol.data_sections {+ 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];@@ -38,13 +37,14 @@ impl Gekko {}// Zero out the BSS section- for i in 0..dol.bss_size {- let addr = dol.bss_start + i;+ let (bss_start, bss_size) = exe.bss();+ for i in 0..bss_size {+ let addr = bss_start + i;mmio.virt_write_u8(addr, 0);}Gekko {- cpu: Cpu::new(dol.entry_point),+ cpu: Cpu::new(exe.entry_point()),scheduler: Scheduler { cycles: 0 },mmio,vi: Vi::new(),diff --git a/crates/image/Cargo.toml b/crates/image/Cargo.tomlnew file mode 100644index 0000000..c6a99e5--- /dev/null+++ b/crates/image/Cargo.toml@@ -0,0 +1,7 @@+[package]+name = "image"+version = "0.1.0"+edition = "2024"++[dependencies]+object = { version = "0.36", default-features = false, features = ["elf", "read"] }diff --git a/crates/image/src/elf.rs b/crates/image/src/elf.rsnew file mode 100644index 0000000..b77c6f8--- /dev/null+++ b/crates/image/src/elf.rs@@ -0,0 +1,46 @@+use crate::symbols::{Symbol, SymbolKind, SymbolTable};+use object::read::elf::ElfFile32;+use object::{Endianness, Object, ObjectSymbol};++#[derive(Debug)]+pub enum ElfError {+ Parse(String),+}++impl std::fmt::Display for ElfError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ ElfError::Parse(msg) => write!(f, "ELF parse error: {msg}"),+ }+ }+}++impl std::error::Error for ElfError {}++pub fn parse_elf_symbols(data: &[u8]) -> Result<SymbolTable, ElfError> {+ let elf = ElfFile32::<Endianness>::parse(data).map_err(|e| ElfError::Parse(e.to_string()))?;++ let mut symbols = Vec::new();++ for sym in elf.symbols() {+ let name = sym.name().unwrap_or_default();+ if name.is_empty() || sym.address() == 0 {+ continue;+ }++ let kind = match sym.kind() {+ object::SymbolKind::Text => SymbolKind::Func,+ object::SymbolKind::Data => SymbolKind::Object,+ _ => SymbolKind::Other,+ };++ symbols.push(Symbol {+ name: name.to_string(),+ addr: sym.address() as u32,+ size: sym.size() as u32,+ kind,+ });+ }++ Ok(SymbolTable::new(symbols))+}diff --git a/crates/image/src/lib.rs b/crates/image/src/lib.rsnew file mode 100644index 0000000..433fbd8--- /dev/null+++ b/crates/image/src/lib.rs@@ -0,0 +1,101 @@+pub mod elf;+pub mod symbols;++pub struct Section {+ pub offset: u32,+ pub vaddr: u32,+ pub size: u32,+}++pub trait Executable {+ fn text_sections(&self) -> &[Section];+ fn data_sections(&self) -> &[Section];+ fn bss(&self) -> (u32, u32);+ fn entry_point(&self) -> u32;+ fn data(&self) -> &[u8];+}++pub struct Dol {+ raw: Vec<u8>,+ text_sections: Vec<Section>,+ data_sections: Vec<Section>,+ bss_start: u32,+ bss_size: u32,+ entry_point: u32,+}++impl Dol {+ pub fn parse(data: Vec<u8>) -> Self {+ let mut text_sections = Vec::new();+ let mut data_sections = Vec::new();++ for i in 0..=6 {+ let offset =+ u32::from_be_bytes(data[0x00 + (i * 4)..0x00 + (i * 4) + 4].try_into().unwrap());+ let vaddr =+ u32::from_be_bytes(data[0x48 + (i * 4)..0x48 + (i * 4) + 4].try_into().unwrap());+ let size =+ u32::from_be_bytes(data[0x90 + (i * 4)..0x90 + (i * 4) + 4].try_into().unwrap());++ if size > 0 {+ text_sections.push(Section {+ offset,+ vaddr,+ size,+ });+ }+ }++ for i in 0..=10 {+ let offset =+ u32::from_be_bytes(data[0x1C + (i * 4)..0x1C + (i * 4) + 4].try_into().unwrap());+ let vaddr =+ u32::from_be_bytes(data[0x64 + (i * 4)..0x64 + (i * 4) + 4].try_into().unwrap());+ let size =+ u32::from_be_bytes(data[0xAC + (i * 4)..0xAC + (i * 4) + 4].try_into().unwrap());++ if size > 0 {+ data_sections.push(Section {+ offset,+ vaddr,+ size,+ });+ }+ }++ let bss_start = u32::from_be_bytes(data[0xD8..0xDC].try_into().unwrap());+ let bss_size = u32::from_be_bytes(data[0xDC..0xE0].try_into().unwrap());+ let entry_point = u32::from_be_bytes(data[0xE0..0xE4].try_into().unwrap());++ Dol {+ raw: data,+ text_sections,+ data_sections,+ bss_start,+ bss_size,+ entry_point,+ }+ }+}++impl Executable for Dol {+ fn text_sections(&self) -> &[Section] {+ &self.text_sections+ }++ fn data_sections(&self) -> &[Section] {+ &self.data_sections+ }++ fn bss(&self) -> (u32, u32) {+ (self.bss_start, self.bss_size)+ }++ fn entry_point(&self) -> u32 {+ self.entry_point+ }++ fn data(&self) -> &[u8] {+ &self.raw+ }+}diff --git a/crates/image/src/symbols.rs b/crates/image/src/symbols.rsnew file mode 100644index 0000000..9030a25--- /dev/null+++ b/crates/image/src/symbols.rs@@ -0,0 +1,51 @@+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum SymbolKind {+ Func,+ Object,+ Other,+}++#[derive(Debug, Clone)]+pub struct Symbol {+ pub name: String,+ pub addr: u32,+ pub size: u32,+ pub kind: SymbolKind,+}++pub struct SymbolTable {+ symbols: Vec<Symbol>,+}++impl SymbolTable {+ pub fn new(mut symbols: Vec<Symbol>) -> Self {+ symbols.sort_by_key(|s| s.addr);+ Self { symbols }+ }++ /// Find the symbol containing `addr` (i.e. `sym.addr <= addr < sym.addr + sym.size`)+ pub fn lookup(&self, addr: u32) -> Option<&Symbol> {+ let idx = self+ .symbols+ .partition_point(|s| s.addr <= addr)+ .checked_sub(1)?;+ let sym = &self.symbols[idx];+ if addr < sym.addr.wrapping_add(sym.size) {+ Some(sym)+ } else {+ None+ }+ }++ /// Find a symbol whose start address is exactly `addr`+ pub fn lookup_exact(&self, addr: u32) -> Option<&Symbol> {+ let idx = self.symbols.partition_point(|s| s.addr < addr);+ self.symbols.get(idx).filter(|s| s.addr == addr)+ }++ /// Returns `true` if `addr` is the entry point of a function symbol+ pub fn is_function_entry(&self, addr: u32) -> bool {+ self.lookup_exact(addr)+ .is_some_and(|s| s.kind == SymbolKind::Func)+ }+}diff --git a/crates/tinyemu/Cargo.toml b/crates/tinyemu/Cargo.tomlindex 06f810c..d689bf9 100644--- a/crates/tinyemu/Cargo.toml+++ b/crates/tinyemu/Cargo.toml@@ -5,6 +5,7 @@ edition = "2024"[dependencies]gekko = { path = "../gekko" }+image = { path = "../image" }colored = "3.1.1"disasm = { path = "../disasm" }tracing = "0.1"diff --git a/crates/tinyemu/src/main.rs b/crates/tinyemu/src/main.rsindex 8a6cf42..9867513 100644--- a/crates/tinyemu/src/main.rs+++ b/crates/tinyemu/src/main.rs@@ -21,6 +21,10 @@ struct Args {#[arg(long, value_parser = parse_hex_addr)]until: Option<u32>,+ /// Path to a companion ELF file for symbol names+ #[arg(long)]+ elf: Option<String>,+/// Suppress all stdout output (tracing is unaffected)#[arg(long)]quiet: bool,@@ -42,8 +46,16 @@ fn main() {).init();- let mut gekko = gekko::gekko::Gekko::new(&args.rom);- run_emulator(&mut gekko, &args);+ let rom_data = std::fs::read(&args.rom).expect("failed to read ROM");+ let dol = image::Dol::parse(rom_data);+ let mut gekko = gekko::gekko::Gekko::new(&dol);++ let symbols = args.elf.as_ref().map(|path| {+ let elf_data = std::fs::read(path).expect("failed to read ELF file");+ image::elf::parse_elf_symbols(&elf_data).expect("failed to parse ELF symbols")+ });++ run_emulator(&mut gekko, &args, symbols.as_ref());if !args.quiet {dump_mmio(&gekko.vi);@@ -55,13 +67,30 @@ fn main() {render_kitty(&pixels, video_format.columns(), video_format.lines());}-fn run_emulator(gekko: &mut gekko::gekko::Gekko, args: &Args) {+fn run_emulator(+ gekko: &mut gekko::gekko::Gekko,+ args: &Args,+ symbols: Option<&image::symbols::SymbolTable>,+) {let mut prev_snapshot = CpuSnapshot::from_cpu(&gekko.cpu);let mut prev_pc = gekko.cpu.pc;let mut in_busyloop = false;+ let mut current_func: Option<String> = None;loop {if !in_busyloop && !args.quiet {+ if let Some(symbols) = symbols {+ if let Some(sym) = symbols.lookup_exact(gekko.cpu.pc) {+ if sym.kind == image::symbols::SymbolKind::Func {+ let name = &sym.name;+ let changed = current_func.as_ref() != Some(name);+ if changed {+ println!("{}", format!("{name}:").green().bold());+ current_func = Some(name.clone());+ }+ }+ }+ }print_instruction(gekko, &prev_snapshot, args.debug);}