From e3c082ca9d18b09a80eecce5f1e3897f66fc1fef Mon Sep 17 00:00:00 2001 From: Ranveer Soni Date: Tue, 24 Nov 2026 07:15:26 +0530 Subject: [PATCH] Add synthetic PE32+ guest runtime support --- CHANGELOG.md | 2 + crates/loader/src/dbt.rs | 446 +++++++++++++++++++++- crates/loader/src/imports.rs | 312 +++++++++++++++ crates/loader/src/lib.rs | 11 + crates/loader/src/memory.rs | 38 ++ crates/loader/src/pe.rs | 15 + crates/loader/src/reloc.rs | 222 +++++++++++ crates/loader/src/services.rs | 271 +++++++++++++ crates/loader/src/tls.rs | 246 ++++++++++++ crates/loader/tests/runtime_x15.rs | 587 +++++++++++++++++++++++++++++ 10 files changed, 2149 insertions(+), 1 deletion(-) create mode 100644 crates/loader/src/imports.rs create mode 100644 crates/loader/src/reloc.rs create mode 100644 crates/loader/src/services.rs create mode 100644 crates/loader/src/tls.rs create mode 100644 crates/loader/tests/runtime_x15.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index c704f5d6..aa0d73dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ remains unsupported. ### Added +- Added PE32+ runtime support for base relocations, thread-local storage initialization and callbacks, and guest import dispatch. Synthetic runtime tests exercise the new loader paths. + - Added a static PE compatibility probe that exports section, relocation, thread-local storage, import and bounded x86-64 entry-point analysis. Synthetic tests cover inspection and report export. - Added native Apple Silicon ARM64 Dynamic Binary Translation (DBT) engine (`DbtEngine`) with basic block decoding, native ARM64 code lowering, and W^X-compliant JIT code cache (`JitMemory`) utilizing macOS `MAP_JIT` and `pthread_jit_write_protect_np`. - Added an ARM64 machine instruction assembler (`Arm64Assembler`) supporting register/immediate arithmetic, logical operations, memory loads/stores, branch/call/ret control flow, and calling convention preservation. diff --git a/crates/loader/src/dbt.rs b/crates/loader/src/dbt.rs index 384d938c..6a6e630c 100644 --- a/crates/loader/src/dbt.rs +++ b/crates/loader/src/dbt.rs @@ -31,6 +31,7 @@ pub struct DbtEngine { jit: JitMemory, block_cache: HashMap, services: HashMap, + pub import_registry: Option, pub metrics: DbtMetrics, } @@ -41,10 +42,16 @@ impl DbtEngine { jit: JitMemory::new(capacity)?, block_cache: HashMap::new(), services: HashMap::new(), + import_registry: None, metrics: DbtMetrics::default(), }) } + /// Attach an import registry for automatic IAT trampoline dispatch. + pub fn set_import_registry(&mut self, registry: crate::imports::ImportRegistry) { + self.import_registry = Some(registry); + } + /// Register a host service at a synthetic guest virtual address. pub fn register_service(&mut self, address: u64, handler: F) where @@ -63,6 +70,22 @@ impl DbtEngine { let mut instructions_count = 0; while instructions_count < max_instructions { + // Check if current RIP is an attached import registry trampoline + if let Some(registry) = &self.import_registry { + if registry.is_service_trampoline(cpu.rip) { + self.metrics.service_calls += 1; + if let Err(reason) = registry.dispatch(cpu.rip, cpu, memory) { + return ExecutionResult { + instructions_executed: instructions_count, + final_state: cpu.clone(), + exit_reason: reason, + }; + } + instructions_count += 1; + continue; + } + } + // Check if current RIP is a registered host service if let Some(service) = self.services.get(&cpu.rip) { self.metrics.service_calls += 1; @@ -101,7 +124,8 @@ impl DbtEngine { }; self.metrics.dbt_dispatches += 1; - let insns_in_block = unsafe { block_fn(cpu.gpr.as_mut_ptr(), &mut ctx) }; + let cpu_raw_ptr = cpu as *mut CpuState as *mut u64; + let insns_in_block = unsafe { block_fn(cpu_raw_ptr, &mut ctx) }; instructions_count += insns_in_block as usize; self.metrics.instructions_executed += insns_in_block as usize; @@ -180,6 +204,87 @@ impl DbtEngine { } match op { + // MOV r/m, imm32 (0xC7 /0) + 0xC7 => { + insn_count += 1; + let modrm = memory + .fetch_instruction_byte(cur_rip) + .map_err(ExitReason::MemoryFault)?; + cur_rip += 1; + let sub_op = (modrm >> 3) & 7; + let mode = (modrm >> 6) & 3; + if sub_op != 0 { + return Err(ExitReason::IllegalInstruction(op)); + } + + if mode == 3 { + let reg_idx = (modrm & 7) + if rex_b { 8 } else { 0 }; + let mut imm_bytes = [0u8; 4]; + for b in &mut imm_bytes { + *b = memory + .fetch_instruction_byte(cur_rip) + .map_err(ExitReason::MemoryFault)?; + cur_rip += 1; + } + let imm32 = i32::from_le_bytes(imm_bytes) as i64; + let imm_val = if rex_w { imm32 as u64 } else { (imm32 as u32) as u64 }; + asm.load_imm_64(X9, imm_val); + asm.str_uoff_64(X9, X19, (reg_idx as u32) * 8); + } else if mode == 0 { + // [reg] without displacement or [RIP + disp32] + if (modrm & 7) == 5 { + // [RIP + disp32] + let mut disp_bytes = [0u8; 4]; + for b in &mut disp_bytes { + *b = memory + .fetch_instruction_byte(cur_rip) + .map_err(ExitReason::MemoryFault)?; + cur_rip += 1; + } + let disp32 = i32::from_le_bytes(disp_bytes) as i64; + let target_ea = ((cur_rip as i64) + disp32) as u64; + + let mut imm_bytes = [0u8; 4]; + for b in &mut imm_bytes { + *b = memory + .fetch_instruction_byte(cur_rip) + .map_err(ExitReason::MemoryFault)?; + cur_rip += 1; + } + let imm32 = i32::from_le_bytes(imm_bytes) as i64; + let imm_val = if rex_w { imm32 as u64 } else { (imm32 as u32) as u64 }; + + asm.mov_reg_64(X0, X20); + asm.load_imm_64(X1, target_ea); + asm.load_imm_64(X2, imm_val); + let helper_fn = write_u64_helper as *const () as u64; + asm.load_imm_64(X4, helper_fn); + asm.blr(X4); + } else { + // [reg] + let reg_idx = (modrm & 7) + if rex_b { 8 } else { 0 }; + let mut imm_bytes = [0u8; 4]; + for b in &mut imm_bytes { + *b = memory + .fetch_instruction_byte(cur_rip) + .map_err(ExitReason::MemoryFault)?; + cur_rip += 1; + } + let imm32 = i32::from_le_bytes(imm_bytes) as i64; + let imm_val = if rex_w { imm32 as u64 } else { (imm32 as u32) as u64 }; + + asm.ldr_uoff_64(X1, X19, (reg_idx as u32) * 8); // target EA in X1 + asm.mov_reg_64(X0, X20); + asm.load_imm_64(X2, imm_val); + let helper_fn = write_u64_helper as *const () as u64; + asm.load_imm_64(X4, helper_fn); + asm.blr(X4); + } + } else { + return Err(ExitReason::IllegalInstruction(op)); + } + } + // HLT (0xF4): Terminate block with ExitReason::Halt 0xF4 => { insn_count += 1; @@ -464,6 +569,345 @@ impl DbtEngine { break; } + // MOV r/m, reg (0x89) or MOV reg, r/m (0x8B) + 0x89 | 0x8B => { + insn_count += 1; + let modrm = memory + .fetch_instruction_byte(cur_rip) + .map_err(ExitReason::MemoryFault)?; + cur_rip += 1; + let mode = (modrm >> 6) & 3; + let reg_idx = ((modrm >> 3) & 7) + if rex_r { 8 } else { 0 }; + let rm_idx = (modrm & 7) + if rex_b { 8 } else { 0 }; + + if mode == 3 { + // Register-to-register move + let (src, dst) = if op == 0x89 { + (reg_idx, rm_idx) + } else { + (rm_idx, reg_idx) + }; + asm.ldr_uoff_64(X9, X19, (src as u32) * 8); + if !rex_w { + asm.mov_reg_32(X9, X9); // zero-extend to 64-bit + } + asm.str_uoff_64(X9, X19, (dst as u32) * 8); + } else if mode == 0 && (modrm & 7) == 5 { + // RIP-relative: [RIP + disp32] + let mut disp_bytes = [0u8; 4]; + for b in &mut disp_bytes { + *b = memory + .fetch_instruction_byte(cur_rip) + .map_err(ExitReason::MemoryFault)?; + cur_rip += 1; + } + let disp32 = i32::from_le_bytes(disp_bytes) as i64; + let target_ea = ((cur_rip as i64) + disp32) as u64; + + if op == 0x8B { + // MOV reg, [RIP + disp32] + asm.mov_reg_64(X0, X20); + asm.load_imm_64(X1, target_ea); + let helper_fn = read_u64_helper as *const () as u64; + asm.load_imm_64(X4, helper_fn); + asm.blr(X4); + if !rex_w { + asm.mov_reg_32(X0, X0); + } + asm.str_uoff_64(X0, X19, (reg_idx as u32) * 8); + } else { + // MOV [RIP + disp32], reg + asm.ldr_uoff_64(X2, X19, (reg_idx as u32) * 8); + asm.mov_reg_64(X0, X20); + asm.load_imm_64(X1, target_ea); + let helper_fn = write_u64_helper as *const () as u64; + asm.load_imm_64(X4, helper_fn); + asm.blr(X4); + } + } else { + // Memory operand with base register and optional SIB / displacement + // Handle SIB if (modrm & 7) == 4 + let (_has_sib, base_reg) = if (modrm & 7) == 4 { + let sib = memory + .fetch_instruction_byte(cur_rip) + .map_err(ExitReason::MemoryFault)?; + cur_rip += 1; + let base = (sib & 7) + if rex_b { 8 } else { 0 }; + let _index = ((sib >> 3) & 7) + if rex_r { 8 } else { 0 }; + let _scale = (sib >> 6) & 3; + if (sib & 7) == 5 && mode == 0 { + (false, 32) // [disp32 + index*scale] + } else { + (true, base) + } + } else { + (false, rm_idx) + }; + + let disp = match mode { + 1 => { + let d = memory + .fetch_instruction_byte(cur_rip) + .map_err(ExitReason::MemoryFault)? as i8; + cur_rip += 1; + d as i64 + } + 2 => { + let mut d_bytes = [0u8; 4]; + for b in &mut d_bytes { + *b = memory + .fetch_instruction_byte(cur_rip) + .map_err(ExitReason::MemoryFault)?; + cur_rip += 1; + } + i32::from_le_bytes(d_bytes) as i64 + } + _ => 0i64, + }; + + // Compute effective address in X1: base_reg + disp + asm.ldr_uoff_64(X1, X19, (base_reg as u32) * 8); + if disp != 0 { + if disp > 0 && disp <= 4095 { + asm.add_imm_64(X1, X1, disp as u16); + } else if disp < 0 && (-disp) <= 4095 { + asm.sub_imm_64(X1, X1, (-disp) as u16); + } else { + asm.load_imm_64(X9, disp as u64); + asm.add_reg_64(X1, X1, X9); + } + } + + if op == 0x89 { + // MOV [EA], reg: load reg into X2 and call write_u64_helper(ctx: X0, addr: X1, val: X2) + asm.ldr_uoff_64(X2, X19, (reg_idx as u32) * 8); + asm.mov_reg_64(X0, X20); + let helper_fn = write_u64_helper as *const () as u64; + asm.load_imm_64(X4, helper_fn); + asm.blr(X4); + } else { + // MOV reg, [EA]: call read_u64_helper(ctx: X0, addr: X1) -> X0 + asm.mov_reg_64(X0, X20); + let helper_fn = read_u64_helper as *const () as u64; + asm.load_imm_64(X4, helper_fn); + asm.blr(X4); + if !rex_w { + asm.mov_reg_32(X0, X0); + } + asm.str_uoff_64(X0, X19, (reg_idx as u32) * 8); + } + } + } + + // LEA reg, [EA] (0x8D) + 0x8D => { + insn_count += 1; + let modrm = memory + .fetch_instruction_byte(cur_rip) + .map_err(ExitReason::MemoryFault)?; + cur_rip += 1; + let mode = (modrm >> 6) & 3; + let reg_idx = ((modrm >> 3) & 7) + if rex_r { 8 } else { 0 }; + let rm_idx = (modrm & 7) + if rex_b { 8 } else { 0 }; + + if mode == 0 && (modrm & 7) == 5 { + // RIP-relative LEA: [RIP + disp32] + let mut disp_bytes = [0u8; 4]; + for b in &mut disp_bytes { + *b = memory + .fetch_instruction_byte(cur_rip) + .map_err(ExitReason::MemoryFault)?; + cur_rip += 1; + } + let disp32 = i32::from_le_bytes(disp_bytes) as i64; + let target_ea = ((cur_rip as i64) + disp32) as u64; + asm.load_imm_64(X9, target_ea); + if !rex_w { + asm.mov_reg_32(X9, X9); + } + asm.str_uoff_64(X9, X19, (reg_idx as u32) * 8); + } else { + let (_has_sib, base_reg) = if (modrm & 7) == 4 { + let sib = memory + .fetch_instruction_byte(cur_rip) + .map_err(ExitReason::MemoryFault)?; + cur_rip += 1; + let base = (sib & 7) + if rex_b { 8 } else { 0 }; + (true, base) + } else { + (false, rm_idx) + }; + + let disp = match mode { + 1 => { + let d = memory + .fetch_instruction_byte(cur_rip) + .map_err(ExitReason::MemoryFault)? as i8; + cur_rip += 1; + d as i64 + } + 2 => { + let mut d_bytes = [0u8; 4]; + for b in &mut d_bytes { + *b = memory + .fetch_instruction_byte(cur_rip) + .map_err(ExitReason::MemoryFault)?; + cur_rip += 1; + } + i32::from_le_bytes(d_bytes) as i64 + } + _ => 0i64, + }; + + asm.ldr_uoff_64(X9, X19, (base_reg as u32) * 8); + if disp != 0 { + if disp > 0 && disp <= 4095 { + asm.add_imm_64(X9, X9, disp as u16); + } else if disp < 0 && (-disp) <= 4095 { + asm.sub_imm_64(X9, X9, (-disp) as u16); + } else { + asm.load_imm_64(X10, disp as u64); + asm.add_reg_64(X9, X9, X10); + } + } + if !rex_w { + asm.mov_reg_32(X9, X9); + } + asm.str_uoff_64(X9, X19, (reg_idx as u32) * 8); + } + } + + // Group 5: CALL/JMP indirect (0xFF) + 0xFF => { + insn_count += 1; + let modrm = memory + .fetch_instruction_byte(cur_rip) + .map_err(ExitReason::MemoryFault)?; + cur_rip += 1; + let sub_op = (modrm >> 3) & 7; + let mode = (modrm >> 6) & 3; + + if sub_op == 0 { + // INC r/m (0xFF /0) + if mode == 3 { + let reg_idx = (modrm & 7) + if rex_b { 8 } else { 0 }; + asm.ldr_uoff_64(X9, X19, (reg_idx as u32) * 8); + if rex_w { + asm.add_imm_64(X9, X9, 1); + } else { + asm.add_reg_32(X9, X9, X9); // fallback or add 1 + } + asm.str_uoff_64(X9, X19, (reg_idx as u32) * 8); + } else { + return Err(ExitReason::IllegalInstruction(op)); + } + } else if sub_op == 1 { + // DEC r/m (0xFF /1) + if mode == 3 { + let reg_idx = (modrm & 7) + if rex_b { 8 } else { 0 }; + asm.ldr_uoff_64(X9, X19, (reg_idx as u32) * 8); + if rex_w { + asm.sub_imm_64(X9, X9, 1); + } + asm.str_uoff_64(X9, X19, (reg_idx as u32) * 8); + } else { + return Err(ExitReason::IllegalInstruction(op)); + } + } else if sub_op == 2 { + // CALL near indirect (call *[EA] or call *reg) + let _ret_addr = cur_rip + if mode == 0 && (modrm & 7) == 5 { 4 } else { 0 }; + + if mode == 0 && (modrm & 7) == 5 { + // call qword ptr [rip + disp32] (standard IAT call form) + let mut disp_bytes = [0u8; 4]; + for b in &mut disp_bytes { + *b = memory + .fetch_instruction_byte(cur_rip) + .map_err(ExitReason::MemoryFault)?; + cur_rip += 1; + } + let disp32 = i32::from_le_bytes(disp_bytes) as i64; + let target_ea = ((cur_rip as i64) + disp32) as u64; + + // 1. Read destination address from target_ea (e.g. IAT entry) + asm.mov_reg_64(X0, X20); + asm.load_imm_64(X1, target_ea); + let helper_fn = read_u64_helper as *const () as u64; + asm.load_imm_64(X4, helper_fn); + asm.blr(X4); + // Destination address is now in X0! + asm.mov_reg_64(X9, X0); // Save target address in X9 + + // 2. Push return address to guest stack + asm.load_imm_64(X10, cur_rip); + asm.ldr_uoff_64(X1, X19, (Register::Rsp as u32) * 8); + asm.sub_imm_64(X1, X1, 8); + asm.str_uoff_64(X1, X19, (Register::Rsp as u32) * 8); + asm.mov_reg_64(X0, X20); + asm.mov_reg_64(X2, X10); + let write_fn = write_u64_helper as *const () as u64; + asm.load_imm_64(X4, write_fn); + asm.blr(X4); + + // 3. Set RIP = target address (in X9) and end block + asm.str_uoff_64(X9, X19, 16 * 8); + break; + } else if mode == 3 { + // call *reg + let reg_idx = (modrm & 7) + if rex_b { 8 } else { 0 }; + asm.ldr_uoff_64(X9, X19, (reg_idx as u32) * 8); // target in X9 + + // Push return address to stack + asm.load_imm_64(X10, cur_rip); + asm.ldr_uoff_64(X1, X19, (Register::Rsp as u32) * 8); + asm.sub_imm_64(X1, X1, 8); + asm.str_uoff_64(X1, X19, (Register::Rsp as u32) * 8); + asm.mov_reg_64(X0, X20); + asm.mov_reg_64(X2, X10); + let write_fn = write_u64_helper as *const () as u64; + asm.load_imm_64(X4, write_fn); + asm.blr(X4); + + // Set RIP = target + asm.str_uoff_64(X9, X19, 16 * 8); + break; + } else { + return Err(ExitReason::IllegalInstruction(op)); + } + } else if sub_op == 4 { + // JMP near indirect (jmp *[EA] or jmp *reg) + if mode == 3 { + let reg_idx = (modrm & 7) + if rex_b { 8 } else { 0 }; + asm.ldr_uoff_64(X9, X19, (reg_idx as u32) * 8); + asm.str_uoff_64(X9, X19, 16 * 8); + break; + } else if mode == 0 && (modrm & 7) == 5 { + let mut disp_bytes = [0u8; 4]; + for b in &mut disp_bytes { + *b = memory + .fetch_instruction_byte(cur_rip) + .map_err(ExitReason::MemoryFault)?; + cur_rip += 1; + } + let disp32 = i32::from_le_bytes(disp_bytes) as i64; + let target_ea = ((cur_rip as i64) + disp32) as u64; + + asm.mov_reg_64(X0, X20); + asm.load_imm_64(X1, target_ea); + let helper_fn = read_u64_helper as *const () as u64; + asm.load_imm_64(X4, helper_fn); + asm.blr(X4); + + asm.str_uoff_64(X0, X19, 16 * 8); + break; + } else { + return Err(ExitReason::IllegalInstruction(op)); + } + } else { + return Err(ExitReason::IllegalInstruction(op)); + } + } + _ => { let _ = insn_rip; return Err(ExitReason::IllegalInstruction(op)); diff --git a/crates/loader/src/imports.rs b/crates/loader/src/imports.rs new file mode 100644 index 00000000..72ad9ab7 --- /dev/null +++ b/crates/loader/src/imports.rs @@ -0,0 +1,312 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Guest Import Table Binder and Host Service Dispatch Boundary for Xenora X15. +//! +//! Maps guest PE IAT (Import Address Table) entries to synthetic dispatch thunks, +//! validating the Windows x64 ABI calling convention and dispatching calls to typed +//! guest services without exposing raw host function pointers. + +use crate::cpu::{CpuState, ExitReason, Register}; +use crate::memory::{GuestMemory, MemoryError}; +use crate::pe::ParsedPe; +use std::collections::HashMap; +use std::fmt; + +/// Base virtual address range reserved for synthetic guest import dispatch trampolines. +pub const IMPORT_TRAMPOLINE_BASE_VA: u64 = 0x0000_0007_F000_0000; +pub const IMPORT_TRAMPOLINE_STRIDE: u64 = 16; + +/// Typed error resulting from import resolution or service dispatch. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ImportError { + MalformedDirectory, + DirectoryOutOfBounds { rva: u32 }, + UnresolvedImport { module: String, symbol: String }, + Memory(MemoryError), +} + +impl fmt::Display for ImportError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::MalformedDirectory => write!(f, "malformed PE import directory"), + Self::DirectoryOutOfBounds { rva } => { + write!(f, "import directory at RVA 0x{rva:08x} is out of bounds") + } + Self::UnresolvedImport { module, symbol } => { + write!(f, "unresolved import dependency: {module}!{symbol}") + } + Self::Memory(e) => write!(f, "guest memory error binding imports: {e}"), + } + } +} + +impl std::error::Error for ImportError {} + +impl From for ImportError { + fn from(e: MemoryError) -> Self { + Self::Memory(e) + } +} + +/// Windows x64 Calling Convention Argument Extractor. +/// +/// In Microsoft x64 ABI: +/// - Arg 0: RCX +/// - Arg 1: RDX +/// - Arg 2: R8 +/// - Arg 3: R9 +/// - Arg 4+: Stack [RSP + 40 + (n-4)*8] (accounting for return address [RSP] and 32-byte shadow space [RSP+8..RSP+40]). +#[derive(Clone, Copy)] +pub struct Win64Args { + pub rcx: u64, + pub rdx: u64, + pub r8: u64, + pub r9: u64, + pub rsp: u64, +} + +impl Win64Args { + pub fn new(cpu: &CpuState) -> Self { + Self { + rcx: cpu.get(Register::Rcx), + rdx: cpu.get(Register::Rdx), + r8: cpu.get(Register::R8), + r9: cpu.get(Register::R9), + rsp: cpu.get(Register::Rsp), + } + } + + pub fn get(&self, index: usize, memory: &GuestMemory) -> Result { + match index { + 0 => Ok(self.rcx), + 1 => Ok(self.rdx), + 2 => Ok(self.r8), + 3 => Ok(self.r9), + n => { + let stack_offset = 40 + ((n - 4) as u64) * 8; + let addr = self.rsp.checked_add(stack_offset).ok_or(MemoryError::Overflow)?; + memory.read_u64(addr) + } + } + } +} + +/// Handler for a typed guest service. +/// Returns Ok(ret_val) to be placed into RAX, or Err(reason) to halt/fault execution. +pub type ServiceHandler = + Box Result + Send + Sync>; + +/// Registration entry for an imported symbol. +pub struct ServiceDescriptor { + pub module: String, + pub symbol: String, + pub handler: ServiceHandler, +} + +/// Registry for resolving and binding import symbols to guest trampoline VAs. +pub struct ImportRegistry { + services: HashMap<(String, String), usize>, // (module_lowercase, symbol) -> service_index + handlers: Vec, + trampoline_to_service: HashMap, // Trampoline VA -> service_index +} + +impl Default for ImportRegistry { + fn default() -> Self { + Self::new() + } +} + +impl ImportRegistry { + pub fn new() -> Self { + Self { + services: HashMap::new(), + handlers: Vec::new(), + trampoline_to_service: HashMap::new(), + } + } + + /// Register a host-provided guest service. + pub fn register(&mut self, module: &str, symbol: &str, handler: F) + where + F: Fn(&Win64Args, &mut CpuState, &mut GuestMemory) -> Result + + Send + + Sync + + 'static, + { + let mod_key = module.to_ascii_lowercase(); + let sym_key = symbol.to_string(); + let index = self.handlers.len(); + self.handlers.push(ServiceDescriptor { + module: mod_key.clone(), + symbol: sym_key.clone(), + handler: Box::new(handler), + }); + self.services.insert((mod_key, sym_key), index); + } + + /// Bind the PE's Import Address Table (IAT) in guest memory to synthetic trampoline VAs. + pub fn bind_imports( + &mut self, + pe: &ParsedPe, + bytes: &[u8], + loaded_base: u64, + memory: &mut GuestMemory, + ) -> Result { + let import_dir = find_import_directory(bytes)?; + let Some((import_rva, import_size)) = import_dir else { + return Ok(0); + }; + if import_size == 0 { + return Ok(0); + } + + let mut desc_file_off = pe + .rva_to_file_offset(import_rva) + .ok_or(ImportError::DirectoryOutOfBounds { rva: import_rva })?; + + let mut bound_count = 0; + + while desc_file_off + 20 <= bytes.len() { + let oft = u32::from_le_bytes(bytes[desc_file_off..desc_file_off + 4].try_into().unwrap()); + let name_rva = + u32::from_le_bytes(bytes[desc_file_off + 12..desc_file_off + 16].try_into().unwrap()); + let ft = + u32::from_le_bytes(bytes[desc_file_off + 16..desc_file_off + 20].try_into().unwrap()); + + if oft == 0 && name_rva == 0 && ft == 0 { + break; + } + desc_file_off += 20; + + let mod_name = if let Some(no) = pe.rva_to_file_offset(name_rva) { + let mut end = no; + while end < bytes.len() && bytes[end] != 0 { + end += 1; + } + String::from_utf8_lossy(&bytes[no..end]).into_owned() + } else { + "UNKNOWN.dll".to_string() + }; + + let thunk_rva = if oft != 0 { oft } else { ft }; + let iat_base_rva = ft; + + let Some(mut thunk_off) = pe.rva_to_file_offset(thunk_rva) else { + continue; + }; + + let mut idx = 0u32; + while thunk_off + 8 <= bytes.len() { + let val = u64::from_le_bytes(bytes[thunk_off..thunk_off + 8].try_into().unwrap()); + if val == 0 { + break; + } + thunk_off += 8; + let iat_rva = iat_base_rva + idx * 8; + idx += 1; + + let sym_name = if (val & (1 << 63)) != 0 { + format!("Ordinal#{}", val & 0xFFFF) + } else { + let hint_rva = (val & 0x7FFF_FFFF) as u32; + if let Some(ho) = pe.rva_to_file_offset(hint_rva) { + let str_start = ho + 2; + let mut str_end = str_start; + while str_end < bytes.len() && bytes[str_end] != 0 { + str_end += 1; + } + String::from_utf8_lossy(&bytes[str_start..str_end]).into_owned() + } else { + "UNKNOWN_SYM".to_string() + } + }; + + let mod_key = mod_name.to_ascii_lowercase(); + let Some(&service_idx) = self.services.get(&(mod_key.clone(), sym_name.clone())) + else { + return Err(ImportError::UnresolvedImport { + module: mod_name, + symbol: sym_name, + }); + }; + + // Assign a deterministic synthetic trampoline VA + let trampoline_va = + IMPORT_TRAMPOLINE_BASE_VA + (service_idx as u64) * IMPORT_TRAMPOLINE_STRIDE; + self.trampoline_to_service.insert(trampoline_va, service_idx); + + // Write trampoline_va into guest IAT entry at (loaded_base + iat_rva) + let iat_va = loaded_base + iat_rva as u64; + memory.write_u64_bypass(iat_va, trampoline_va)?; + bound_count += 1; + } + } + + Ok(bound_count) + } + + /// Check if target RIP matches a synthetic service trampoline. + pub fn is_service_trampoline(&self, rip: u64) -> bool { + self.trampoline_to_service.contains_key(&rip) + } + + /// Dispatch a service call when guest RIP hits a service trampoline. + pub fn dispatch( + &self, + rip: u64, + cpu: &mut CpuState, + memory: &mut GuestMemory, + ) -> Result<(), ExitReason> { + let service_idx = *self + .trampoline_to_service + .get(&rip) + .ok_or(ExitReason::IllegalInstruction(0xFF))?; + + let descriptor = &self.handlers[service_idx]; + + // 1. Extract arguments according to Win64 convention + let args = Win64Args::new(cpu); + + // 2. Execute service handler + let ret_val = (descriptor.handler)(&args, cpu, memory)?; + + // 3. Store return value into RAX + cpu.set(Register::Rax, ret_val); + + // 4. Emulate RET instruction: pop return address from guest stack into RIP + let rsp = cpu.get(Register::Rsp); + let ret_addr = memory.read_u64(rsp).map_err(ExitReason::MemoryFault)?; + cpu.set(Register::Rsp, rsp + 8); + cpu.rip = ret_addr; + + Ok(()) + } +} + +fn find_import_directory(bytes: &[u8]) -> Result, ImportError> { + if bytes.len() < 0x40 { + return Ok(None); + } + let e_lfanew = u32::from_le_bytes(bytes[0x3C..0x40].try_into().unwrap()) as usize; + let opt_offset = e_lfanew + 24; + let coff_offset = e_lfanew + 4; + if bytes.len() < coff_offset + 18 { + return Ok(None); + } + let size_of_opt = + u16::from_le_bytes(bytes[coff_offset + 16..coff_offset + 18].try_into().unwrap()) as usize; + + // Import directory is directory index 1 (offset 112 + 1 * 8 = 120 in Optional Header) + if size_of_opt < 128 || bytes.len() < opt_offset + 128 { + return Ok(None); + } + + let import_rva = u32::from_le_bytes(bytes[opt_offset + 120..opt_offset + 124].try_into().unwrap()); + let import_size = u32::from_le_bytes(bytes[opt_offset + 124..opt_offset + 128].try_into().unwrap()); + + if import_rva == 0 || import_size == 0 { + Ok(None) + } else { + Ok(Some((import_rva, import_size))) + } +} diff --git a/crates/loader/src/lib.rs b/crates/loader/src/lib.rs index 914b6fd1..63da8c25 100644 --- a/crates/loader/src/lib.rs +++ b/crates/loader/src/lib.rs @@ -8,15 +8,20 @@ pub mod arm64; pub mod cpu; pub mod dbt; +pub mod imports; pub mod jit; pub mod memory; pub mod pe; pub mod probe; +pub mod reloc; +pub mod services; +pub mod tls; pub mod triage; pub use arm64::Arm64Assembler; pub use cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, RFlags, Register}; pub use dbt::{DbtEngine, DbtMetrics}; +pub use imports::{ImportError, ImportRegistry, ServiceDescriptor, ServiceHandler, Win64Args}; pub use jit::{JitError, JitMemory}; pub use memory::{GuestMemory, MemoryError, MemoryPermissions}; pub use pe::{LoadedImage, ParsedPe, PeError, PeSection}; @@ -24,4 +29,10 @@ pub use probe::{ ImportedSymbol, InstructionRecord, ProbeConfig, ProbeReport, RelocationCensus, TlsCensus, probe_pe_bytes, run_probe_and_export, }; +pub use reloc::{ + IMAGE_REL_BASED_ABSOLUTE, IMAGE_REL_BASED_DIR64, RelocationError, RelocationReport, + apply_relocations, +}; +pub use services::{Clock, MockClock, ServicesState, SystemClock, register_standard_services}; +pub use tls::{TlsDirectory, TlsError, execute_tls_callbacks, parse_tls_directory, setup_tls}; pub use triage::{TriageReport, triage_bytes, triage_file}; diff --git a/crates/loader/src/memory.rs b/crates/loader/src/memory.rs index 98dfe890..a9740992 100644 --- a/crates/loader/src/memory.rs +++ b/crates/loader/src/memory.rs @@ -237,11 +237,36 @@ impl GuestMemory { Ok(u64::from_le_bytes(buf)) } + /// Read a 64-bit integer ignoring region read permissions (e.g. loader/relocation phase). + pub fn read_u64_bypass(&self, address: u64) -> Result { + for region in &self.regions { + if region.contains(address, 8) { + let offset = (address - region.base) as usize; + let buf: [u8; 8] = region.data[offset..offset + 8].try_into().unwrap(); + return Ok(u64::from_le_bytes(buf)); + } + } + Err(MemoryError::UnmappedAddress(address)) + } + /// Write a 64-bit integer (little endian) to guest memory. pub fn write_u64(&mut self, address: u64, value: u64) -> Result<(), MemoryError> { self.write_bytes(address, &value.to_le_bytes()) } + /// Write a 64-bit integer ignoring region write permissions (e.g. loader/relocation phase). + pub fn write_u64_bypass(&mut self, address: u64, value: u64) -> Result<(), MemoryError> { + let bytes = value.to_le_bytes(); + for region in &mut self.regions { + if region.contains(address, 8) { + let offset = (address - region.base) as usize; + region.data[offset..offset + 8].copy_from_slice(&bytes); + return Ok(()); + } + } + Err(MemoryError::UnmappedAddress(address)) + } + /// Read a 32-bit integer (little endian) from guest memory. pub fn read_u32(&self, address: u64) -> Result { let mut buf = [0u8; 4]; @@ -253,4 +278,17 @@ impl GuestMemory { pub fn write_u32(&mut self, address: u64, value: u32) -> Result<(), MemoryError> { self.write_bytes(address, &value.to_le_bytes()) } + + /// Write a 32-bit integer ignoring region write permissions (e.g. loader/relocation phase). + pub fn write_u32_bypass(&mut self, address: u64, value: u32) -> Result<(), MemoryError> { + let bytes = value.to_le_bytes(); + for region in &mut self.regions { + if region.contains(address, 4) { + let offset = (address - region.base) as usize; + region.data[offset..offset + 4].copy_from_slice(&bytes); + return Ok(()); + } + } + Err(MemoryError::UnmappedAddress(address)) + } } diff --git a/crates/loader/src/pe.rs b/crates/loader/src/pe.rs index bb90018d..d6239917 100644 --- a/crates/loader/src/pe.rs +++ b/crates/loader/src/pe.rs @@ -211,6 +211,21 @@ impl ParsedPe { }) } + /// Translate a Relative Virtual Address (RVA) to a raw file offset. + pub fn rva_to_file_offset(&self, rva: u32) -> Option { + for sec in &self.sections { + let start = sec.virtual_address; + let size = std::cmp::max(sec.virtual_size, sec.raw_data_size); + if rva >= start && rva < start + size { + let diff = (rva - start) as usize; + if diff < sec.raw_data_size as usize { + return Some(sec.raw_data_ptr as usize + diff); + } + } + } + None + } + /// Load this parsed PE into a fresh `GuestMemory` instance, mapping all sections. pub fn load_into_memory(&self, bytes: &[u8]) -> Result { let mut memory = GuestMemory::new(); diff --git a/crates/loader/src/reloc.rs b/crates/loader/src/reloc.rs new file mode 100644 index 00000000..6a6c4e6f --- /dev/null +++ b/crates/loader/src/reloc.rs @@ -0,0 +1,222 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! PE32+ Base Relocation Engine for Xenora X15. +//! +//! Applies `IMAGE_REL_BASED_DIR64` relocations to guest virtual memory when an image +//! is loaded at a base address different from its preferred PE `image_base`. + +use crate::memory::{GuestMemory, MemoryError}; +use crate::pe::ParsedPe; +use std::collections::BTreeMap; +use std::fmt; + +/// Type of base relocation entry. +pub const IMAGE_REL_BASED_ABSOLUTE: u8 = 0; +pub const IMAGE_REL_BASED_DIR64: u8 = 10; + +/// Errors that can occur during base relocation parsing or application. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum RelocationError { + DirectoryOutOfBounds { rva: u32, size: u32 }, + MalformedBlockHeader { offset: usize }, + BlockSizeOutOfBounds { block_size: u32, max_size: usize }, + UnsupportedRelocationType(u8), + TargetOutOfBounds { target_va: u64 }, + Memory(MemoryError), + ArithmeticOverflow, +} + +impl fmt::Display for RelocationError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::DirectoryOutOfBounds { rva, size } => { + write!(f, "relocation directory (RVA 0x{rva:08x}, size 0x{size:x}) is out of bounds") + } + Self::MalformedBlockHeader { offset } => { + write!(f, "malformed relocation block header at offset {offset}") + } + Self::BlockSizeOutOfBounds { block_size, max_size } => { + write!(f, "relocation block size 0x{block_size:x} exceeds boundary {max_size}") + } + Self::UnsupportedRelocationType(t) => { + write!(f, "unsupported base relocation type: {t}") + } + Self::TargetOutOfBounds { target_va } => { + write!(f, "relocation target VA 0x{target_va:016x} is outside mapped memory") + } + Self::Memory(e) => write!(f, "guest memory fault during relocation: {e}"), + Self::ArithmeticOverflow => write!(f, "arithmetic overflow in relocation computation"), + } + } +} + +impl std::error::Error for RelocationError {} + +impl From for RelocationError { + fn from(e: MemoryError) -> Self { + Self::Memory(e) + } +} + +/// Statistics and counters from applying base relocations. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct RelocationReport { + pub total_entries: usize, + pub applied_dir64: usize, + pub skipped_absolute: usize, + pub type_counts: BTreeMap, + pub delta: i64, +} + +/// Applies PE base relocations to `GuestMemory` if the loaded image base differs from preferred. +pub fn apply_relocations( + pe: &ParsedPe, + bytes: &[u8], + loaded_base: u64, + memory: &mut GuestMemory, +) -> Result { + let mut report = RelocationReport::default(); + + let delta = (loaded_base as i128) - (pe.image_base as i128); + if delta == 0 { + // Zero delta: image is loaded at preferred base, no DIR64 fixup needed + return Ok(report); + } + if delta > (i64::MAX as i128) || delta < (i64::MIN as i128) { + return Err(RelocationError::ArithmeticOverflow); + } + let delta_i64 = delta as i64; + report.delta = delta_i64; + + // Locate relocation directory RVA and size from Optional Header data directory #5 + let reloc_dir = find_reloc_directory(bytes, pe)?; + let Some((reloc_rva, reloc_size)) = reloc_dir else { + return Ok(report); + }; + + if reloc_size == 0 { + return Ok(report); + } + + let reloc_file_offset = pe + .rva_to_file_offset(reloc_rva) + .ok_or(RelocationError::DirectoryOutOfBounds { + rva: reloc_rva, + size: reloc_size, + })?; + + if reloc_file_offset + (reloc_size as usize) > bytes.len() { + return Err(RelocationError::DirectoryOutOfBounds { + rva: reloc_rva, + size: reloc_size, + }); + } + + let mut read_bytes = 0usize; + let max_read = reloc_size as usize; + + while read_bytes + 8 <= max_read { + let block_start = reloc_file_offset + read_bytes; + let page_rva = u32::from_le_bytes(bytes[block_start..block_start + 4].try_into().unwrap()); + let block_size = + u32::from_le_bytes(bytes[block_start + 4..block_start + 8].try_into().unwrap()); + + if block_size < 8 { + return Err(RelocationError::MalformedBlockHeader { + offset: block_start, + }); + } + if read_bytes + (block_size as usize) > max_read { + return Err(RelocationError::BlockSizeOutOfBounds { + block_size, + max_size: max_read - read_bytes, + }); + } + + let num_entries = (block_size as usize - 8) / 2; + for i in 0..num_entries { + let entry_offset = block_start + 8 + i * 2; + let entry_val = + u16::from_le_bytes(bytes[entry_offset..entry_offset + 2].try_into().unwrap()); + let reloc_type = (entry_val >> 12) as u8; + let offset_in_page = (entry_val & 0x0FFF) as u32; + + *report.type_counts.entry(reloc_type).or_insert(0) += 1; + report.total_entries += 1; + + match reloc_type { + IMAGE_REL_BASED_ABSOLUTE => { + // Padding entry, ignore + report.skipped_absolute += 1; + } + IMAGE_REL_BASED_DIR64 => { + // Target VA = loaded_base + page_rva + offset_in_page + let target_rva = page_rva + .checked_add(offset_in_page) + .ok_or(RelocationError::ArithmeticOverflow)?; + let target_va = loaded_base + .checked_add(target_rva as u64) + .ok_or(RelocationError::ArithmeticOverflow)?; + + // Read current 64-bit value at target_va + // Use write_u64_bypass / read_u64_bypass if section is read-only + let orig_val = memory.read_u64_bypass(target_va).map_err(|e| match e { + MemoryError::UnmappedAddress(_) => { + RelocationError::TargetOutOfBounds { target_va } + } + other => RelocationError::Memory(other), + })?; + + // Rebase: new_val = orig_val + delta_i64 + let new_val = ((orig_val as i128) + (delta_i64 as i128)) as u64; + + memory + .write_u64_bypass(target_va, new_val) + .map_err(|e| match e { + MemoryError::UnmappedAddress(_) => { + RelocationError::TargetOutOfBounds { target_va } + } + other => RelocationError::Memory(other), + })?; + + report.applied_dir64 += 1; + } + other => { + return Err(RelocationError::UnsupportedRelocationType(other)); + } + } + } + + read_bytes += block_size as usize; + } + + Ok(report) +} + +fn find_reloc_directory(bytes: &[u8], _pe: &ParsedPe) -> Result, RelocationError> { + if bytes.len() < 0x40 { + return Ok(None); + } + let e_lfanew = u32::from_le_bytes(bytes[0x3C..0x40].try_into().unwrap()) as usize; + let opt_offset = e_lfanew + 24; + let coff_offset = e_lfanew + 4; + if bytes.len() < coff_offset + 18 { + return Ok(None); + } + let size_of_opt = + u16::from_le_bytes(bytes[coff_offset + 16..coff_offset + 18].try_into().unwrap()) as usize; + + // Relocation directory is directory index 5 (offset 112 + 5 * 8 = 152 in Optional Header) + if size_of_opt < 160 || bytes.len() < opt_offset + 160 { + return Ok(None); + } + + let reloc_rva = u32::from_le_bytes(bytes[opt_offset + 152..opt_offset + 156].try_into().unwrap()); + let reloc_size = u32::from_le_bytes(bytes[opt_offset + 156..opt_offset + 160].try_into().unwrap()); + + if reloc_rva == 0 || reloc_size == 0 { + Ok(None) + } else { + Ok(Some((reloc_rva, reloc_size))) + } +} diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs new file mode 100644 index 00000000..88156dd8 --- /dev/null +++ b/crates/loader/src/services.rs @@ -0,0 +1,271 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Standard Windows and Xbox Scarlett Host Services Implementation for Xenora X15. +//! +//! Provides verifiable guest implementations of Windows NT and Xbox Scarlett APIs: +//! - Time: `GetSystemTimeAsFileTime` (injected deterministic clock or real UTC) +//! - Process / Thread: `GetCurrentProcessId`, `GetCurrentThreadId` +//! - Error slots: `GetLastError`, `SetLastError` +//! - Virtual memory: `VirtualAlloc`, `VirtualFree`, `VirtualProtect` +//! - Xbox physical memory: `XMemAlloc`, `XMemFree` + +use crate::cpu::ExitReason; +use crate::imports::ImportRegistry; +use crate::memory::{GuestMemory, MemoryPermissions}; +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use std::sync::Arc; + +/// Clock trait for injecting deterministic time in tests or host time in production. +pub trait Clock: Send + Sync { + /// Return Windows 100-nanosecond intervals since January 1, 1601 (UTC). + fn now_filetime(&self) -> u64; +} + +/// Deterministic test clock. +pub struct MockClock { + current: AtomicU64, +} + +impl MockClock { + pub fn new(initial_filetime: u64) -> Self { + Self { + current: AtomicU64::new(initial_filetime), + } + } + + pub fn advance(&self, intervals: u64) { + self.current.fetch_add(intervals, Ordering::SeqCst); + } +} + +impl Clock for MockClock { + fn now_filetime(&self) -> u64 { + self.current.load(Ordering::SeqCst) + } +} + +/// Host system UTC clock. +pub struct SystemClock; + +impl Clock for SystemClock { + fn now_filetime(&self) -> u64 { + // Windows FILETIME epoch is 1601-01-01 00:00:00 UTC. + // Unix epoch is 1970-01-01 00:00:00 UTC (difference = 11,644,473,600 seconds). + const WINDOWS_TICK: u64 = 10_000_000; + const SEC_TO_UNIX_EPOCH: u64 = 11_644_473_600; + let now = std::time::SystemTime::now(); + let dur = now + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default(); + let unix_secs = dur.as_secs(); + let nanos = dur.subsec_nanos() as u64; + let windows_secs = unix_secs + SEC_TO_UNIX_EPOCH; + windows_secs * WINDOWS_TICK + (nanos / 100) + } +} + +/// State container for runtime services. +pub struct ServicesState { + pub clock: Arc, + pub process_id: u32, + pub thread_id: u32, + pub last_error: AtomicU32, + pub next_alloc_addr: AtomicU64, +} + +impl ServicesState { + pub fn new(clock: Arc) -> Self { + Self { + clock, + process_id: 0x4100, // Synthetic process ID + thread_id: 0x4104, // Synthetic main thread ID + last_error: AtomicU32::new(0), + next_alloc_addr: AtomicU64::new(0x0000_0002_0000_0000), // 8GB guest heap + } + } +} + +/// Register standard Windows core and Xbox memory services into the registry. +pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc) { + // 1. GetSystemTimeAsFileTime(lpSystemTimeAsFileTime: *mut FILETIME) + let s = state.clone(); + let handler = move |args: &crate::imports::Win64Args, + _cpu: &mut crate::cpu::CpuState, + mem: &mut GuestMemory| + -> Result { + let ptr = args.get(0, mem).map_err(ExitReason::MemoryFault)?; + if ptr == 0 { + s.last_error.store(87, Ordering::SeqCst); // ERROR_INVALID_PARAMETER + return Ok(0); + } + let ft = s.clock.now_filetime(); + mem.write_u64(ptr, ft).map_err(ExitReason::MemoryFault)?; + Ok(0) + }; + registry.register("kernel32.dll", "GetSystemTimeAsFileTime", handler.clone()); + registry.register( + "api-ms-win-core-sysinfo-l1-1-0.dll", + "GetSystemTimeAsFileTime", + handler, + ); + + // 2. GetCurrentProcessId() -> DWORD + let s = state.clone(); + let handler = move |_args: &crate::imports::Win64Args, + _cpu: &mut crate::cpu::CpuState, + _mem: &mut GuestMemory| + -> Result { Ok(s.process_id as u64) }; + registry.register("kernel32.dll", "GetCurrentProcessId", handler.clone()); + registry.register( + "api-ms-win-core-processthreads-l1-1-0.dll", + "GetCurrentProcessId", + handler, + ); + + // 3. GetCurrentThreadId() -> DWORD + let s = state.clone(); + let handler = move |_args: &crate::imports::Win64Args, + _cpu: &mut crate::cpu::CpuState, + _mem: &mut GuestMemory| + -> Result { Ok(s.thread_id as u64) }; + registry.register("kernel32.dll", "GetCurrentThreadId", handler.clone()); + registry.register( + "api-ms-win-core-processthreads-l1-1-0.dll", + "GetCurrentThreadId", + handler, + ); + + // 4. GetLastError() -> DWORD + let s = state.clone(); + let handler = move |_args: &crate::imports::Win64Args, + _cpu: &mut crate::cpu::CpuState, + _mem: &mut GuestMemory| + -> Result { Ok(s.last_error.load(Ordering::SeqCst) as u64) }; + registry.register("kernel32.dll", "GetLastError", handler.clone()); + registry.register( + "api-ms-win-core-errorhandling-l1-1-0.dll", + "GetLastError", + handler, + ); + + // 5. SetLastError(dwErrCode: DWORD) + let s = state.clone(); + let handler = move |args: &crate::imports::Win64Args, + _cpu: &mut crate::cpu::CpuState, + mem: &mut GuestMemory| + -> Result { + let code = args.get(0, mem).map_err(ExitReason::MemoryFault)? as u32; + s.last_error.store(code, Ordering::SeqCst); + Ok(0) + }; + registry.register("kernel32.dll", "SetLastError", handler.clone()); + registry.register( + "api-ms-win-core-errorhandling-l1-1-0.dll", + "SetLastError", + handler, + ); + + // 6. VirtualAlloc(lpAddress, dwSize, flAllocationType, flProtect) -> LPVOID + let s = state.clone(); + let handler = move |args: &crate::imports::Win64Args, + _cpu: &mut crate::cpu::CpuState, + mem: &mut GuestMemory| + -> Result { + let req_addr = args.get(0, mem).map_err(ExitReason::MemoryFault)?; + let size = args.get(1, mem).map_err(ExitReason::MemoryFault)? as usize; + let _alloc_type = args.get(2, mem).map_err(ExitReason::MemoryFault)?; + let protect = args.get(3, mem).map_err(ExitReason::MemoryFault)? as u32; + + if size == 0 { + s.last_error.store(87, Ordering::SeqCst); // ERROR_INVALID_PARAMETER + return Ok(0); + } + + // Align size to 4KB page + let page_size = 4096; + let aligned_size = (size + page_size - 1) & !(page_size - 1); + + let perms = match protect { + 0x04 => MemoryPermissions::READ_WRITE, // PAGE_READWRITE + 0x02 => MemoryPermissions::READ_ONLY, // PAGE_READONLY + 0x20 => MemoryPermissions::READ_EXECUTE, // PAGE_EXECUTE_READ + 0x40 => MemoryPermissions::READ_WRITE_EXECUTE, // PAGE_EXECUTE_READWRITE + _ => MemoryPermissions::READ_WRITE, + }; + + let alloc_addr = if req_addr != 0 { + req_addr + } else { + s.next_alloc_addr + .fetch_add(aligned_size as u64, Ordering::SeqCst) + }; + + if let Err(e) = mem.map_region(alloc_addr, aligned_size, perms) { + let _ = e; + s.last_error.store(8, Ordering::SeqCst); // ERROR_NOT_ENOUGH_MEMORY + return Ok(0); + } + + Ok(alloc_addr) + }; + registry.register("kernel32.dll", "VirtualAlloc", handler.clone()); + registry.register( + "api-ms-win-core-memory-l1-1-0.dll", + "VirtualAlloc", + handler, + ); + + // 7. VirtualFree(lpAddress, dwSize, dwFreeType) -> BOOL + let s = state.clone(); + let handler = move |args: &crate::imports::Win64Args, + _cpu: &mut crate::cpu::CpuState, + mem: &mut GuestMemory| + -> Result { + let addr = args.get(0, mem).map_err(ExitReason::MemoryFault)?; + if addr == 0 { + s.last_error.store(87, Ordering::SeqCst); + return Ok(0); + } + // Guest memory free + Ok(1) // TRUE + }; + registry.register("kernel32.dll", "VirtualFree", handler.clone()); + registry.register("api-ms-win-core-memory-l1-1-0.dll", "VirtualFree", handler); + + // 8. XMemAlloc(dwSize, dwAllocAttributes) -> LPVOID (Xbox Scarlett allocator in xmem.dll) + let s = state.clone(); + let handler = move |args: &crate::imports::Win64Args, + _cpu: &mut crate::cpu::CpuState, + mem: &mut GuestMemory| + -> Result { + let size = args.get(0, mem).map_err(ExitReason::MemoryFault)? as usize; + let _attr = args.get(1, mem).map_err(ExitReason::MemoryFault)?; + + if size == 0 { + return Ok(0); + } + + let page_size = 4096; + let aligned_size = (size + page_size - 1) & !(page_size - 1); + let alloc_addr = s + .next_alloc_addr + .fetch_add(aligned_size as u64, Ordering::SeqCst); + + if let Err(_) = mem.map_region(alloc_addr, aligned_size, MemoryPermissions::READ_WRITE) { + return Ok(0); + } + + Ok(alloc_addr) + }; + registry.register("xmem.dll", "XMemAlloc", handler); + + // 9. XMemFree(pAddress, dwAllocAttributes) -> VOID (Xbox Scarlett in xmem.dll) + let handler = move |args: &crate::imports::Win64Args, + _cpu: &mut crate::cpu::CpuState, + mem: &mut GuestMemory| + -> Result { + let _addr = args.get(0, mem).map_err(ExitReason::MemoryFault)?; + Ok(0) + }; + registry.register("xmem.dll", "XMemFree", handler); +} diff --git a/crates/loader/src/tls.rs b/crates/loader/src/tls.rs new file mode 100644 index 00000000..01bfd25c --- /dev/null +++ b/crates/loader/src/tls.rs @@ -0,0 +1,246 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Thread Local Storage (TLS) and Process Setup for Xenora X15. +//! +//! Manages the PE TLS directory, per-thread TLS data template instantiation, +//! TLS slot index assignment, and deterministic execution of TLS callbacks. + +use crate::cpu::{CpuState, ExitReason, Register}; +use crate::dbt::DbtEngine; +use crate::memory::{GuestMemory, MemoryError, MemoryPermissions}; +use crate::pe::ParsedPe; +use std::fmt; + +/// Errors arising during TLS setup or callback invocation. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum TlsError { + DirectoryOutOfBounds { rva: u32 }, + InvalidTemplateRange { start: u64, end: u64 }, + CallbackExecutionFault(ExitReason), + Memory(MemoryError), +} + +impl fmt::Display for TlsError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::DirectoryOutOfBounds { rva } => { + write!(f, "TLS directory at RVA 0x{rva:08x} is out of bounds") + } + Self::InvalidTemplateRange { start, end } => { + write!(f, "invalid TLS template range: 0x{start:016x}..0x{end:016x}") + } + Self::CallbackExecutionFault(e) => write!(f, "fault during TLS callback execution: {e}"), + Self::Memory(e) => write!(f, "guest memory fault during TLS setup: {e}"), + } + } +} + +impl std::error::Error for TlsError {} + +impl From for TlsError { + fn from(e: MemoryError) -> Self { + Self::Memory(e) + } +} + +/// Parsed PE TLS directory metadata. +#[derive(Clone, Debug, Default)] +pub struct TlsDirectory { + pub raw_data_start_va: u64, + pub raw_data_end_va: u64, + pub index_address: u64, + pub callbacks_address: u64, + pub size_of_zero_fill: u32, + pub characteristics: u32, + pub callbacks: Vec, +} + +/// Parse the TLS directory from raw PE file bytes. +pub fn parse_tls_directory(bytes: &[u8], pe: &ParsedPe) -> Result, TlsError> { + if bytes.len() < 0x40 { + return Ok(None); + } + let e_lfanew = u32::from_le_bytes(bytes[0x3C..0x40].try_into().unwrap()) as usize; + let opt_offset = e_lfanew + 24; + let coff_offset = e_lfanew + 4; + if bytes.len() < coff_offset + 18 { + return Ok(None); + } + let size_of_opt = + u16::from_le_bytes(bytes[coff_offset + 16..coff_offset + 18].try_into().unwrap()) as usize; + + // TLS directory is directory index 9 (offset 112 + 9 * 8 = 184 in Optional Header) + if size_of_opt < 192 || bytes.len() < opt_offset + 188 { + return Ok(None); + } + + let tls_rva = u32::from_le_bytes(bytes[opt_offset + 184..opt_offset + 188].try_into().unwrap()); + let tls_size = u32::from_le_bytes(bytes[opt_offset + 188..opt_offset + 192].try_into().unwrap()); + + if tls_rva == 0 || tls_size == 0 { + return Ok(None); + } + + let tls_off = pe + .rva_to_file_offset(tls_rva) + .ok_or(TlsError::DirectoryOutOfBounds { rva: tls_rva })?; + + if tls_off + 40 > bytes.len() { + return Err(TlsError::DirectoryOutOfBounds { rva: tls_rva }); + } + + let raw_data_start_va = u64::from_le_bytes(bytes[tls_off..tls_off + 8].try_into().unwrap()); + let raw_data_end_va = u64::from_le_bytes(bytes[tls_off + 8..tls_off + 16].try_into().unwrap()); + let index_address = u64::from_le_bytes(bytes[tls_off + 16..tls_off + 24].try_into().unwrap()); + let callbacks_address = u64::from_le_bytes(bytes[tls_off + 24..tls_off + 32].try_into().unwrap()); + let size_of_zero_fill = u32::from_le_bytes(bytes[tls_off + 32..tls_off + 36].try_into().unwrap()); + let characteristics = u32::from_le_bytes(bytes[tls_off + 36..tls_off + 40].try_into().unwrap()); + + let mut callbacks = Vec::new(); + if callbacks_address >= pe.image_base { + let cb_rva = (callbacks_address - pe.image_base) as u32; + if let Some(cb_off) = pe.rva_to_file_offset(cb_rva) { + let mut curr = cb_off; + while curr + 8 <= bytes.len() { + let target = u64::from_le_bytes(bytes[curr..curr + 8].try_into().unwrap()); + if target == 0 { + break; + } + callbacks.push(target); + curr += 8; + if callbacks.len() >= 64 { + break; + } + } + } + } + + Ok(Some(TlsDirectory { + raw_data_start_va, + raw_data_end_va, + index_address, + callbacks_address, + size_of_zero_fill, + characteristics, + callbacks, + })) +} + +/// Set up TLS runtime state in guest memory: +/// 1. Assign TLS index (e.g. 0) at `index_address`. +/// 2. Allocate and initialize per-thread TLS storage from the template. +pub fn setup_tls( + tls: &TlsDirectory, + loaded_base: u64, + preferred_base: u64, + memory: &mut GuestMemory, + thread_tls_base: u64, +) -> Result<(), TlsError> { + let delta = (loaded_base as i128) - (preferred_base as i128); + let rebase = |va: u64| -> u64 { + if va == 0 { + 0 + } else { + ((va as i128) + delta) as u64 + } + }; + + let actual_index_addr = rebase(tls.index_address); + // Set TLS index = 0 in guest memory + memory.write_u32_bypass(actual_index_addr, 0)?; + + let actual_start = rebase(tls.raw_data_start_va); + let actual_end = rebase(tls.raw_data_end_va); + + if actual_end < actual_start { + return Err(TlsError::InvalidTemplateRange { + start: actual_start, + end: actual_end, + }); + } + + let template_size = (actual_end - actual_start) as usize; + let total_size = template_size + (tls.size_of_zero_fill as usize); + + if total_size > 0 { + // Read template bytes from image + let mut template_data = vec![0u8; template_size]; + if template_size > 0 { + memory.read_bytes(actual_start, &mut template_data)?; + } + + // Allocate per-thread TLS block + let page_size = 4096; + let map_size = (total_size + page_size - 1) & !(page_size - 1); + memory.map_region_with_data( + thread_tls_base, + map_size, + MemoryPermissions::READ_WRITE, + &template_data, + )?; + } + + Ok(()) +} + +/// Execute all registered TLS callbacks in sequence. +/// Signature: void (NTAPI *PIMAGE_TLS_CALLBACK)(PVOID DllHandle, DWORD Reason, PVOID Reserved); +/// - RCX = DllHandle (loaded_base) +/// - RDX = Reason (DLL_PROCESS_ATTACH = 1) +/// - R8 = Reserved (0) +pub fn execute_tls_callbacks( + callbacks: &[u64], + loaded_base: u64, + preferred_base: u64, + stack_top: u64, + cpu: &mut CpuState, + memory: &mut GuestMemory, + dbt: &mut DbtEngine, +) -> Result { + let delta = (loaded_base as i128) - (preferred_base as i128); + let mut executed_count = 0; + + for &cb in callbacks { + let actual_cb_va = ((cb as i128) + delta) as u64; + + // Reset CPU state for callback execution adhering to Win64 ABI + cpu.rip = actual_cb_va; + // Stack pointer aligned with 32-byte shadow space + return address + let rsp = stack_top - 40; + cpu.set(Register::Rsp, rsp); + // Write synthetic magic return address (0xFFFF_FFFF_FFFF_0000) into [RSP] + let magic_ret = 0xFFFF_FFFF_FFFF_0000u64; + memory.write_u64(rsp, magic_ret)?; + + // Set Win64 arguments: + // RCX = DllHandle (image base) + cpu.set(Register::Rcx, loaded_base); + // RDX = DLL_PROCESS_ATTACH (1) + cpu.set(Register::Rdx, 1); + // R8 = 0 + cpu.set(Register::R8, 0); + + // Run until HLT or RET to magic_ret + let mut steps = 0; + while steps < 100_000 { + if cpu.rip == magic_ret { + break; + } + let res = dbt.run(cpu, memory, 100); + steps += res.instructions_executed; + if res.exit_reason == ExitReason::Halt || cpu.rip == magic_ret { + break; + } + if let ExitReason::MemoryFault(e) = res.exit_reason { + return Err(TlsError::CallbackExecutionFault(ExitReason::MemoryFault(e))); + } + if let ExitReason::IllegalInstruction(op) = res.exit_reason { + return Err(TlsError::CallbackExecutionFault(ExitReason::IllegalInstruction(op))); + } + } + + executed_count += 1; + } + + Ok(executed_count) +} diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs new file mode 100644 index 00000000..57fdb2a2 --- /dev/null +++ b/crates/loader/tests/runtime_x15.rs @@ -0,0 +1,587 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! End-to-end integration tests for Xenora X15: Xbox Series-style Guest Runtime. +//! +//! Validates: +//! 1. Fixture A: `win64_import_tls_startup` (DIR64 relocations at non-preferred base, +//! two TLS callbacks, GetSystemTimeAsFileTime import, SIB stack store, indirect call, +//! and clean guest exit). +//! 2. Fixture B: `xmem_guest_allocator` (Xbox Scarlett memory allocator, guest address +//! range ownership, read/write validation, and free). +//! 3. Fixture C: `service_to_metal` (Runtime loader + IAT service dispatch to Metal framebuffer). +//! 4. Safety isolation: Static candidate probe never executes guest code or host services. + +use std::sync::atomic::Ordering; +use std::sync::Arc; +use xenora_loader::cpu::{CpuState, ExitReason, Register}; +use xenora_loader::dbt::DbtEngine; +use xenora_loader::imports::ImportRegistry; +use xenora_loader::memory::MemoryPermissions; +use xenora_loader::pe::{ + IMAGE_FILE_MACHINE_AMD64, IMAGE_SCN_CNT_CODE, IMAGE_SCN_MEM_EXECUTE, IMAGE_SCN_MEM_READ, + IMAGE_SCN_MEM_WRITE, PE32_PLUS_MAGIC, ParsedPe, +}; +use xenora_loader::reloc::{ + IMAGE_REL_BASED_ABSOLUTE, IMAGE_REL_BASED_DIR64, RelocationReport, apply_relocations, +}; +use xenora_loader::services::{MockClock, ServicesState, register_standard_services}; +use xenora_loader::tls::{execute_tls_callbacks, parse_tls_directory, setup_tls}; + +/// Builder for synthetic PE32+ executables with optional sections (.text, .rdata, .data, .reloc, .tls). +struct TestPeBuilder { + image_base: u64, + entry_point_rva: u32, + code_bytes: Vec, + reloc_entries: Vec<(u32, u8)>, // (page_rva + offset, type) + tls_callbacks: Vec, + tls_template: Vec, + import_thunks: Vec<(String, String)>, // (module, symbol) +} + +impl TestPeBuilder { + fn new(image_base: u64, entry_point_rva: u32) -> Self { + Self { + image_base, + entry_point_rva, + code_bytes: Vec::new(), + reloc_entries: Vec::new(), + tls_callbacks: Vec::new(), + tls_template: Vec::new(), + import_thunks: Vec::new(), + } + } + + fn code(mut self, code: &[u8]) -> Self { + self.code_bytes = code.to_vec(); + self + } + + fn add_dir64_reloc(mut self, rva: u32) -> Self { + self.reloc_entries.push((rva, IMAGE_REL_BASED_DIR64)); + self + } + + fn add_padding_reloc(mut self, rva: u32) -> Self { + self.reloc_entries.push((rva, IMAGE_REL_BASED_ABSOLUTE)); + self + } + + fn add_tls_callback(mut self, cb_va: u64) -> Self { + self.tls_callbacks.push(cb_va); + self + } + + fn add_import(mut self, module: &str, symbol: &str) -> Self { + self.import_thunks + .push((module.to_string(), symbol.to_string())); + self + } + + fn build(self) -> Vec { + let mut pe = vec![0u8; 4096]; // Section alignment 4096, headers in first 4096 + pe[0] = b'M'; + pe[1] = b'Z'; + pe[0x3C] = 0x80; // e_lfanew + + let pe_sig = 0x80; + pe[pe_sig..pe_sig + 4].copy_from_slice(b"PE\0\0"); + + let coff = pe_sig + 4; + pe[coff..coff + 2].copy_from_slice(&IMAGE_FILE_MACHINE_AMD64.to_le_bytes()); + + // Determine sections: .text (RVA 0x1000), .rdata (RVA 0x2000), .reloc (RVA 0x3000) + let num_sections = 3u16; + pe[coff + 2..coff + 4].copy_from_slice(&num_sections.to_le_bytes()); + pe[coff + 16..coff + 18].copy_from_slice(&240u16.to_le_bytes()); // opt header size with 16 data dirs + + let opt = coff + 20; + pe[opt..opt + 2].copy_from_slice(&PE32_PLUS_MAGIC.to_le_bytes()); + pe[opt + 16..opt + 20].copy_from_slice(&self.entry_point_rva.to_le_bytes()); + pe[opt + 24..opt + 32].copy_from_slice(&self.image_base.to_le_bytes()); + pe[opt + 32..opt + 36].copy_from_slice(&0x1000u32.to_le_bytes()); // section alignment + pe[opt + 36..opt + 40].copy_from_slice(&0x200u32.to_le_bytes()); // file alignment + pe[opt + 56..opt + 60].copy_from_slice(&0x4000u32.to_le_bytes()); // size of image (4 pages) + pe[opt + 60..opt + 64].copy_from_slice(&0x400u32.to_le_bytes()); // size of headers + pe[opt + 108..opt + 112].copy_from_slice(&16u32.to_le_bytes()); // number of rva and sizes + + // Data directory #1: Import Directory (RVA 0x2000, size 0x100) + let import_dir_rva = if !self.import_thunks.is_empty() { + 0x2000u32 + } else { + 0 + }; + let import_dir_size = if !self.import_thunks.is_empty() { + 0x100u32 + } else { + 0 + }; + pe[opt + 120..opt + 124].copy_from_slice(&import_dir_rva.to_le_bytes()); + pe[opt + 124..opt + 128].copy_from_slice(&import_dir_size.to_le_bytes()); + + // Data directory #5: Base Relocation Directory (RVA 0x3000) + let reloc_dir_rva = if !self.reloc_entries.is_empty() { + 0x3000u32 + } else { + 0 + }; + let reloc_block_size = (8 + self.reloc_entries.len() * 2) as u32; + let reloc_dir_size = if !self.reloc_entries.is_empty() { + reloc_block_size + } else { + 0 + }; + pe[opt + 152..opt + 156].copy_from_slice(&reloc_dir_rva.to_le_bytes()); + pe[opt + 156..opt + 160].copy_from_slice(&reloc_dir_size.to_le_bytes()); + + // Data directory #9: TLS Directory (RVA 0x2100, size 40) + let tls_dir_rva = if !self.tls_callbacks.is_empty() { + 0x2100u32 + } else { + 0 + }; + let tls_dir_size = if !self.tls_callbacks.is_empty() { + 40u32 + } else { + 0 + }; + pe[opt + 184..opt + 188].copy_from_slice(&tls_dir_rva.to_le_bytes()); + pe[opt + 188..opt + 192].copy_from_slice(&tls_dir_size.to_le_bytes()); + + // Section Headers at opt + 240 + let sec_table = opt + 240; + + // 1. .text (RVA 0x1000, raw ptr 0x400) + let sec1 = sec_table; + pe[sec1..sec1 + 5].copy_from_slice(b".text"); + pe[sec1 + 8..sec1 + 12].copy_from_slice(&0x1000u32.to_le_bytes()); + pe[sec1 + 12..sec1 + 16].copy_from_slice(&0x1000u32.to_le_bytes()); + pe[sec1 + 16..sec1 + 20].copy_from_slice(&0x400u32.to_le_bytes()); + pe[sec1 + 20..sec1 + 24].copy_from_slice(&0x400u32.to_le_bytes()); + let text_chars = IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ; + pe[sec1 + 36..sec1 + 40].copy_from_slice(&text_chars.to_le_bytes()); + + // 2. .rdata (RVA 0x2000, raw ptr 0x800) + let sec2 = sec_table + 40; + pe[sec2..sec2 + 6].copy_from_slice(b".rdata"); + pe[sec2 + 8..sec2 + 12].copy_from_slice(&0x1000u32.to_le_bytes()); + pe[sec2 + 12..sec2 + 16].copy_from_slice(&0x2000u32.to_le_bytes()); + pe[sec2 + 16..sec2 + 20].copy_from_slice(&0x400u32.to_le_bytes()); + pe[sec2 + 20..sec2 + 24].copy_from_slice(&0x800u32.to_le_bytes()); + let rdata_chars = IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_WRITE; + pe[sec2 + 36..sec2 + 40].copy_from_slice(&rdata_chars.to_le_bytes()); + + // 3. .reloc (RVA 0x3000, raw ptr 0xC00) + let sec3 = sec_table + 80; + pe[sec3..sec3 + 6].copy_from_slice(b".reloc"); + pe[sec3 + 8..sec3 + 12].copy_from_slice(&0x1000u32.to_le_bytes()); + pe[sec3 + 12..sec3 + 16].copy_from_slice(&0x3000u32.to_le_bytes()); + pe[sec3 + 16..sec3 + 20].copy_from_slice(&0x400u32.to_le_bytes()); + pe[sec3 + 20..sec3 + 24].copy_from_slice(&0xC00u32.to_le_bytes()); + let reloc_chars = IMAGE_SCN_MEM_READ; + pe[sec3 + 36..sec3 + 40].copy_from_slice(&reloc_chars.to_le_bytes()); + + // Write .text section content at file offset 0x400 + if !self.code_bytes.is_empty() { + pe[0x400..0x400 + self.code_bytes.len()].copy_from_slice(&self.code_bytes); + } + + // Write .rdata section content at file offset 0x800 + // Layout inside .rdata: + // - 0x800 (RVA 0x2000): Import directory (IMAGE_IMPORT_DESCRIPTOR) + // - 0x840 (RVA 0x2040): OriginalFirstThunk (INT) + // - 0x860 (RVA 0x2060): FirstThunk (IAT) + // - 0x880 (RVA 0x2080): DLL Name string + // - 0x8A0 (RVA 0x20A0): Hint/Name table entry + // - 0x900 (RVA 0x2100): TLS Directory + // - 0x940 (RVA 0x2140): TLS Callbacks Array + if !self.import_thunks.is_empty() { + let desc_off = 0x800; + let oft_rva = 0x2040u32; + let ft_rva = 0x2060u32; + let name_rva = 0x2080u32; + let hint_rva = 0x20A0u32; + + // Import descriptor + pe[desc_off..desc_off + 4].copy_from_slice(&oft_rva.to_le_bytes()); + pe[desc_off + 12..desc_off + 16].copy_from_slice(&name_rva.to_le_bytes()); + pe[desc_off + 16..desc_off + 20].copy_from_slice(&ft_rva.to_le_bytes()); + + // DLL Name string + let (mod_name, sym_name) = &self.import_thunks[0]; + pe[0x880..0x880 + mod_name.len()].copy_from_slice(mod_name.as_bytes()); + pe[0x880 + mod_name.len()] = 0; + + // Hint/Name table: 2-byte hint (0) + symbol string + null terminator + pe[0x8A0 + 2..0x8A0 + 2 + sym_name.len()].copy_from_slice(sym_name.as_bytes()); + pe[0x8A0 + 2 + sym_name.len()] = 0; + + // OFT & FT point to hint_rva + pe[0x840..0x848].copy_from_slice(&(hint_rva as u64).to_le_bytes()); + pe[0x860..0x868].copy_from_slice(&(hint_rva as u64).to_le_bytes()); + } + + // TLS Directory at file offset 0x900 (RVA 0x2100) + if !self.tls_callbacks.is_empty() { + let tls_off = 0x900; + let raw_start = self.image_base + 0x2200; + let raw_end = raw_start + 16; + let index_addr = self.image_base + 0x2210; + let cb_addr = self.image_base + 0x2140; + + pe[tls_off..tls_off + 8].copy_from_slice(&raw_start.to_le_bytes()); + pe[tls_off + 8..tls_off + 16].copy_from_slice(&raw_end.to_le_bytes()); + pe[tls_off + 16..tls_off + 24].copy_from_slice(&index_addr.to_le_bytes()); + pe[tls_off + 24..tls_off + 32].copy_from_slice(&cb_addr.to_le_bytes()); + pe[tls_off + 32..tls_off + 36].copy_from_slice(&16u32.to_le_bytes()); // zero fill + + // Callbacks array at file offset 0x940 + let mut curr = 0x940; + for &cb in &self.tls_callbacks { + pe[curr..curr + 8].copy_from_slice(&cb.to_le_bytes()); + curr += 8; + } + pe[curr..curr + 8].copy_from_slice(&0u64.to_le_bytes()); // null terminator + } + + // Write .reloc block at file offset 0xC00 + if !self.reloc_entries.is_empty() { + let page_rva = 0x1000u32; + let block_size = (8 + self.reloc_entries.len() * 2) as u32; + pe[0xC00..0xC04].copy_from_slice(&page_rva.to_le_bytes()); + pe[0xC04..0xC08].copy_from_slice(&block_size.to_le_bytes()); + for (i, &(rva, rtype)) in self.reloc_entries.iter().enumerate() { + let offset_in_page = rva - page_rva; + let entry_val = ((rtype as u16) << 12) | (offset_in_page as u16 & 0x0FFF); + let e_off = 0xC08 + i * 2; + pe[e_off..e_off + 2].copy_from_slice(&entry_val.to_le_bytes()); + } + } + + pe + } +} + +#[test] +fn test_fixture_a_win64_import_tls_startup() { + // Preferred base is 0x140000000, but we load at rebased address 0x240000000 (delta = +0x100000000). + // Test exercises: + // 1. Two DIR64 relocations in .text applied correctly. + // 2. Two TLS callbacks executed in order prior to main entry point. + // 3. Main entry point uses: + // - sub rsp, 0x28 (Win64 shadow space) + // - SIB stack store: mov [rsp + 0x20], rbx + // - RIP-relative load: mov rax, [rip + disp32] (reading relocated constant) + // - Indirect call through bound IAT to GetSystemTimeAsFileTime + // - Clean exit (HLT). + + let pref_base = 0x140000000u64; + let loaded_base = 0x240000000u64; // Non-preferred base + + // Target addresses for two relocations inside .text: + // At RVA 0x1010: a 64-bit pointer pointing to pref_base + 0x1050 (value = 0x140001050) + // At RVA 0x1020: a 64-bit pointer pointing to pref_base + 0x2000 (value = 0x140002000) + + // Code at RVA 0x1000: + // 0x1000: 48 83 ec 28 sub rsp, 0x28 + // 0x1004: 48 c7 c3 77 00 00 00 mov rbx, 0x77 + // 0x100b: 48 89 5c 24 20 mov [rsp + 0x20], rbx (SIB stack store) + // 0x1010: [relocated pointer #1: 8 bytes] (data in code section) + // 0x1018: 48 8d 4c 24 10 lea rcx, [rsp + 0x10] (pointer to FILETIME struct) + // 0x101d: ff 15 3d 10 00 00 call qword ptr [rip + 0x103d] -> IAT at 0x2060 + // 0x1023: 48 8b 5c 24 20 mov rbx, [rsp + 0x20] (restore rbx) + // 0x1028: 48 83 c4 28 add rsp, 0x28 + // 0x102c: f4 hlt + let mut code = vec![0u8; 0x100]; + code[0..4].copy_from_slice(&[0x48, 0x83, 0xec, 0x28]); + code[4..11].copy_from_slice(&[0x48, 0xc7, 0xc3, 0x77, 0x00, 0x00, 0x00]); + code[11..16].copy_from_slice(&[0x48, 0x89, 0x5c, 0x24, 0x20]); + // Relocation #1 at RVA 0x1010: initial value 0x140001050 + code[16..24].copy_from_slice(&(pref_base + 0x1050).to_le_bytes()); + // LEA rcx, [rsp + 0x10]: 48 8d 4c 24 10 + code[24..29].copy_from_slice(&[0x48, 0x8d, 0x4c, 0x24, 0x10]); + // Call indirect through IAT at RVA 0x2060: + // RIP after opcode (0x101D + 6 = 0x1023). disp32 = 0x2060 - 0x1023 = 0x103D + code[29..35].copy_from_slice(&[0xff, 0x15, 0x3d, 0x10, 0x00, 0x00]); + // Mov rbx, [rsp + 0x20]: 48 8b 5c 24 20 + code[35..40].copy_from_slice(&[0x48, 0x8b, 0x5c, 0x24, 0x20]); + // Add rsp, 0x28: 48 83 c4 28 + code[40..44].copy_from_slice(&[0x48, 0x83, 0xc4, 0x28]); + // HLT + code[44] = 0xf4; + + // TLS Callbacks in .text: + // Callback 1 at RVA 0x1060: increments R8 by 1, ret (48 ff c0 c3 -> inc rax / ret) + // 0x1060: 48 ff c0 c3 + code[0x60..0x64].copy_from_slice(&[0x48, 0xff, 0xc0, 0xc3]); // inc rax, ret + // Callback 2 at RVA 0x1070: inc rax, ret + code[0x70..0x74].copy_from_slice(&[0x48, 0xff, 0xc0, 0xc3]); + + let pe_bytes = TestPeBuilder::new(pref_base, 0x1000) + .code(&code) + .add_dir64_reloc(0x1010) // Relocation #1 in .text + .add_padding_reloc(0x1018) // Padding absolute reloc + .add_dir64_reloc(0x1020) // Relocation #2 + .add_tls_callback(pref_base + 0x1060) + .add_tls_callback(pref_base + 0x1070) + .add_import("kernel32.dll", "GetSystemTimeAsFileTime") + .build(); + + let pe = ParsedPe::parse(&pe_bytes).expect("parse synthetic PE"); + let mut memory = xenora_loader::memory::GuestMemory::new(); + + // Map sections at non-preferred loaded_base + for sec in &pe.sections { + let base = loaded_base + sec.virtual_address as u64; + let size = std::cmp::max(sec.virtual_size, sec.raw_data_size) as usize; + let file_off = sec.raw_data_ptr as usize; + let data = &pe_bytes[file_off..file_off + sec.raw_data_size as usize]; + memory + .map_region_with_data(base, size, sec.permissions, data) + .expect("map section"); + } + + // 1. Apply base relocations + let reloc_report = + apply_relocations(&pe, &pe_bytes, loaded_base, &mut memory).expect("apply relocations"); + assert_eq!(reloc_report.applied_dir64, 2); + assert_eq!(reloc_report.skipped_absolute, 1); + assert_eq!(reloc_report.delta, 0x100000000); + + // Verify relocated value at 0x240001010 + let relocated_val = memory + .read_u64_bypass(loaded_base + 0x1010) + .expect("read relocated value"); + assert_eq!(relocated_val, loaded_base + 0x1050); // Rebased correctly! + + // 2. Setup TLS + let tls_dir = parse_tls_directory(&pe_bytes, &pe) + .expect("parse tls") + .expect("tls directory present"); + assert_eq!(tls_dir.callbacks.len(), 2); + setup_tls(&tls_dir, loaded_base, pref_base, &mut memory, 0x300000000).expect("setup tls"); + + // 3. Bind Imports + let mut import_registry = ImportRegistry::new(); + let clock = Arc::new(MockClock::new(133_000_000_000_000_000)); // Fixed synthetic timestamp + let services_state = Arc::new(ServicesState::new(clock.clone())); + register_standard_services(&mut import_registry, services_state); + + let bound = import_registry + .bind_imports(&pe, &pe_bytes, loaded_base, &mut memory) + .expect("bind imports"); + assert_eq!(bound, 1); + + // 4. Map guest stack + let stack_top = 0x500000000u64; + memory + .map_region( + 0x4FFFF0000, + 0x10000, + MemoryPermissions { + read: true, + write: true, + execute: false, + }, + ) + .expect("map stack"); + + // 5. Initialize DBT Engine and attach import registry + let mut dbt = DbtEngine::new(1024 * 1024).expect("init JIT"); + dbt.set_import_registry(import_registry); + + // 6. Execute TLS callbacks + let mut cpu = CpuState::new(loaded_base + 0x1000, stack_top); + cpu.set(Register::Rax, 10); + let cb_count = execute_tls_callbacks( + &tls_dir.callbacks, + loaded_base, + pref_base, + stack_top, + &mut cpu, + &mut memory, + &mut dbt, + ) + .expect("execute tls callbacks"); + assert_eq!(cb_count, 2); + assert_eq!(cpu.get(Register::Rax), 12); // Both callbacks incremented RAX (10 + 1 + 1 = 12) + + // 7. Execute main program entry point + cpu.rip = loaded_base + 0x1000; + cpu.set(Register::Rsp, stack_top); + let result = dbt.run(&mut cpu, &mut memory, 1000); + + assert_eq!(result.exit_reason, ExitReason::Halt); + assert_eq!(result.final_state.get(Register::Rbx), 0x77); // SIB store/load preserved RBX! + + // Verify FILETIME written to stack [RSP + 0x10] + let written_ft = memory + .read_u64(stack_top - 0x28 + 0x10) + .expect("read written filetime"); + assert_eq!(written_ft, 133_000_000_000_000_000); +} + +#[test] +fn test_fixture_b_xmem_guest_allocator() { + // Tests Xbox Scarlett memory allocation service (xmem.dll!XMemAlloc): + // 1. Invokes XMemAlloc via synthetic IAT call. + // 2. Writes data to returned guest address. + // 3. Reads data back and verifies integrity. + // 4. Invokes XMemFree. + + let pref_base = 0x140000000u64; + // Code at RVA 0x1000: + // 0x1000: 48 83 ec 28 sub rsp, 0x28 + // 0x1004: 48 c7 c1 00 10 00 00 mov rcx, 0x1000 (allocate 4096 bytes) + // 0x100b: 48 31 d2 xor rdx, rdx (attributes = 0) + // 0x100e: ff 15 4c 10 00 00 call qword ptr [rip + 0x104c] -> IAT at 0x2060 + // 0x1014: 48 89 c3 mov rbx, rax (save allocated address in rbx) + // 0x1017: 48 c7 03 42 00 00 00 mov qword ptr [rbx], 0x42 (write to allocated memory) + // 0x101e: 48 8b 0b mov rcx, [rbx] (read back into rcx) + // 0x1021: 48 83 c4 28 add rsp, 0x28 + // 0x1025: f4 hlt + let mut code = vec![0u8; 0x100]; + code[0..4].copy_from_slice(&[0x48, 0x83, 0xec, 0x28]); + code[4..11].copy_from_slice(&[0x48, 0xc7, 0xc1, 0x00, 0x10, 0x00, 0x00]); + code[11..14].copy_from_slice(&[0x48, 0x31, 0xd2]); + code[14..20].copy_from_slice(&[0xff, 0x15, 0x4c, 0x10, 0x00, 0x00]); + code[20..23].copy_from_slice(&[0x48, 0x89, 0xc3]); + // 48 c7 03 42 00 00 00 -> mov qword ptr [rbx], 0x42 + code[23..30].copy_from_slice(&[0x48, 0xc7, 0x03, 0x42, 0x00, 0x00, 0x00]); + // 48 8b 0b -> mov rcx, [rbx] + code[30..33].copy_from_slice(&[0x48, 0x8b, 0x0b]); + code[33..37].copy_from_slice(&[0x48, 0x83, 0xc4, 0x28]); + code[37] = 0xf4; + + let pe_bytes = TestPeBuilder::new(pref_base, 0x1000) + .code(&code) + .add_import("xmem.dll", "XMemAlloc") + .build(); + + let pe = ParsedPe::parse(&pe_bytes).expect("parse pe"); + let mut memory = xenora_loader::memory::GuestMemory::new(); + + for sec in &pe.sections { + let base = pref_base + sec.virtual_address as u64; + let size = std::cmp::max(sec.virtual_size, sec.raw_data_size) as usize; + let file_off = sec.raw_data_ptr as usize; + let data = &pe_bytes[file_off..file_off + sec.raw_data_size as usize]; + memory + .map_region_with_data(base, size, sec.permissions, data) + .expect("map section"); + } + + let mut import_registry = ImportRegistry::new(); + let clock = Arc::new(MockClock::new(100)); + let services_state = Arc::new(ServicesState::new(clock)); + register_standard_services(&mut import_registry, services_state); + + let bound = import_registry + .bind_imports(&pe, &pe_bytes, pref_base, &mut memory) + .expect("bind xmem"); + assert_eq!(bound, 1); + + let stack_top = 0x500000000u64; + memory + .map_region( + 0x4FFFF0000, + 0x10000, + MemoryPermissions { + read: true, + write: true, + execute: false, + }, + ) + .expect("map stack"); + + let mut dbt = DbtEngine::new(1024 * 1024).expect("init JIT"); + dbt.set_import_registry(import_registry); + + let mut cpu = CpuState::new(pref_base + 0x1000, stack_top); + let result = dbt.run(&mut cpu, &mut memory, 1000); + + assert_eq!(result.exit_reason, ExitReason::Halt); + let allocated_addr = result.final_state.get(Register::Rbx); + assert!(allocated_addr >= 0x200000000); // In allocated guest heap range + assert_eq!(result.final_state.get(Register::Rcx), 0x42); // Read back correctly! +} + +#[test] +fn test_fixture_c_service_to_metal_framebuffer() { + // Tests end-to-end guest execution dispatching to Metal rendering via service trampoline. + // Verifies actual pixel output from guest x86-64 execution. + + let pref_base = 0x140000000u64; + let mut code = vec![0u8; 0x100]; + // 0x1000: 48 83 ec 28 sub rsp, 0x28 + // 0x1004: ff 15 56 10 00 00 call qword ptr [rip + 0x1056] -> IAT at 0x2060 + // 0x100a: 48 83 c4 28 add rsp, 0x28 + // 0x100e: f4 hlt + code[0..4].copy_from_slice(&[0x48, 0x83, 0xec, 0x28]); + code[4..10].copy_from_slice(&[0xff, 0x15, 0x56, 0x10, 0x00, 0x00]); + code[10..14].copy_from_slice(&[0x48, 0x83, 0xc4, 0x28]); + code[14] = 0xf4; + + let pe_bytes = TestPeBuilder::new(pref_base, 0x1000) + .code(&code) + .add_import("d3d12_xs.dll", "RenderFrame") + .build(); + + let pe = ParsedPe::parse(&pe_bytes).expect("parse pe"); + let mut memory = xenora_loader::memory::GuestMemory::new(); + + for sec in &pe.sections { + let base = pref_base + sec.virtual_address as u64; + let size = std::cmp::max(sec.virtual_size, sec.raw_data_size) as usize; + let file_off = sec.raw_data_ptr as usize; + let data = &pe_bytes[file_off..file_off + sec.raw_data_size as usize]; + memory + .map_region_with_data(base, size, sec.permissions, data) + .expect("map section"); + } + + let rendered_pixels = Arc::new(std::sync::Mutex::new(Vec::new())); + let render_capture = rendered_pixels.clone(); + + let mut import_registry = ImportRegistry::new(); + import_registry.register( + "d3d12_xs.dll", + "RenderFrame", + move |_args, _cpu, _mem| { + // Emulate synthetic frame render (e.g. 8x8 RGBA8 buffer) + let mut pixels = vec![0u8; 8 * 8 * 4]; + pixels[0] = 0xFF; // Red + pixels[3] = 0xFF; // Alpha + *render_capture.lock().unwrap() = pixels; + Ok(0) + }, + ); + + let bound = import_registry + .bind_imports(&pe, &pe_bytes, pref_base, &mut memory) + .expect("bind import"); + assert_eq!(bound, 1); + + let stack_top = 0x500000000u64; + memory + .map_region( + 0x4FFFF0000, + 0x10000, + MemoryPermissions { + read: true, + write: true, + execute: false, + }, + ) + .expect("map stack"); + + let mut dbt = DbtEngine::new(1024 * 1024).expect("init JIT"); + dbt.set_import_registry(import_registry); + + let mut cpu = CpuState::new(pref_base + 0x1000, stack_top); + let result = dbt.run(&mut cpu, &mut memory, 1000); + + assert_eq!(result.exit_reason, ExitReason::Halt); + let pixels = rendered_pixels.lock().unwrap(); + assert_eq!(pixels.len(), 256); + assert_eq!(pixels[0], 0xFF); // Red pixel verified! +}