diff --git a/CHANGELOG.md b/CHANGELOG.md index 771b387c..16f0f6a7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,9 @@ remains unsupported. ### Added +- Added `xenora-loader` crate providing standalone PE32+ (64-bit Portable Executable) parsing, isolated guest virtual memory with strict page permissions (Read/Write/Execute), bounded software x86-64 instruction interpreter (`CpuState`, `Interpreter`, `RFlags`), and read-only diagnostic triage (`triage_file`, `triage_bytes`). +- Added CLI inspect command (`xenora inspect `) for read-only PE32+ header and section structure examination. +- Added comprehensive integration tests verifying synthetic PE32+ image mapping, register arithmetic, stack push/pop, subroutine calls/returns, deterministic unsupported opcode rejection, memory fault on unmapped access, and execution budget enforcement. - Added native Metal sampler abstraction (`MetalSampler`) supporting nearest-neighbor minification/magnification filtering, clamp-to-edge addressing, normalized coordinates, validated LOD bounds, and explicit `SamplerDesc` mapping. - Added native Metal RGBA8 2D texture allocation, mip upload validation (`MetalRgba8Texture`, `Rgba8MipLevel`, `Rgba8TextureDesc`), and texture/sampler pipeline binding definitions (`BoundSampledTexture`, `BindingSlot`) for future translated shader stages. - Added an independent pure-Rust CPU texture sampling reference for deterministic RGBA8 2D textures with nearest-neighbor filtering, normalized UV coordinates, clamp-to-edge addressing, explicit mip selection, and bounds validation. diff --git a/Cargo.lock b/Cargo.lock index 0a882e9e..7021d1ea 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -70,6 +70,7 @@ dependencies = [ name = "xenora" version = "0.1.0" dependencies = [ + "xenora-loader", "xenora-metal", "xenora-ref", "xenora-shader", @@ -96,6 +97,10 @@ dependencies = [ name = "xenora-isa" version = "0.1.0" +[[package]] +name = "xenora-loader" +version = "0.1.0" + [[package]] name = "xenora-metal" version = "0.1.0" @@ -103,6 +108,7 @@ dependencies = [ "objc2", "objc2-foundation", "objc2-metal", + "xenora-ref", "xenora-shader", "xenora-texture", ] diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index 05ec537f..93a6f1c2 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -12,3 +12,4 @@ workspace = true xenora-metal = { path = "../metal" } xenora-ref = { path = "../ref" } xenora-shader = { path = "../shader" } +xenora-loader = { path = "../loader" } diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index 22854a11..7befeb9b 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -14,6 +14,22 @@ fn main() -> ExitCode { ); ExitCode::SUCCESS } + Some("inspect") => { + let Some(file_path) = std::env::args().nth(2) else { + eprintln!("usage: xenora inspect "); + return ExitCode::from(2); + }; + match xenora_loader::triage_file(&file_path) { + Ok(report) => { + print!("{report}"); + ExitCode::SUCCESS + } + Err(err) => { + eprintln!("inspect failed: {err}"); + ExitCode::FAILURE + } + } + } Some("demo") => match demo::run() { Ok(()) => ExitCode::SUCCESS, Err(error) => { @@ -22,7 +38,7 @@ fn main() -> ExitCode { } }, _ => { - eprintln!("usage: xenora "); + eprintln!("usage: xenora "); ExitCode::from(2) } } diff --git a/crates/decoder/src/lib.rs b/crates/decoder/src/lib.rs index 2e411669..92a924ed 100644 --- a/crates/decoder/src/lib.rs +++ b/crates/decoder/src/lib.rs @@ -6,10 +6,10 @@ pub use xenora_isa::{ Architecture, ExportTarget, Instruction, InterpolationPhase, ScalarSource, VectorSource, }; use xenora_isa::{ - BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, S_BRANCH, S_CBRANCH_EXECZ, S_CBRANCH_SCC0, - S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, V_ADD_F32, - V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32, - V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32, + BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ, + S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, + V_ADD_F32, V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_INTERP_P1_F32, V_INTERP_P2_F32, + V_LSHLREV_B32, V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32, }; /// A successfully decoded instruction and its location in the input stream. @@ -205,6 +205,21 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco }; return Ok((Instruction::Export { target, sources }, len)); } + if IMAGE_SAMPLE_LZ.matches(first) { + let len = IMAGE_SAMPLE_LZ.byte_len(); + let second = word(bytes, len)?; + let (dst, coord, resource, sampler) = + image_sample_operands(first, second, "image_sample_lz")?; + return Ok(( + Instruction::ImageSampleLz { + dst, + coord, + resource, + sampler, + }, + len, + )); + } for (opcode, phase) in [ (V_INTERP_P1_F32, InterpolationPhase::First), (V_INTERP_P2_F32, InterpolationPhase::Second), @@ -410,6 +425,76 @@ fn vop2_registers(first: u32, mnemonic: &'static str) -> Result<(u8, u8, u8), De Ok(((first >> 17) as u8, first as u8, (first >> 9) as u8)) } +fn image_sample_operands( + first: u32, + second: u32, + mnemonic: &'static str, +) -> Result<(u8, u8, u8, u8), DecodeErrorKind> { + // In word 0: + // Bits 1..2: NSA (must be 0 for contiguous VADDR) + // Bits 3..5: DIM (1 = SQ_RSRC_IMG_2D) + // Bit 7: DLC (0) + // Bits 8..11: DMASK (0xf for RGBA 4-component return) + // Bit 12: UNORM (0) + // Bit 13: GLC (0) + // Bit 14: DA (0) + // Bit 15: R128 (0) + // Bit 16: TFE (0) + // Bit 25: SLC (0) + // Bit 0 & Bits 18..24: OP (0x27 / 39) + // Bits 26..31: ENCODING (0x3c) + // Mask off OP and ENCODING (bits 0, 18..24, 26..31). + // The expected variable bits for 2D RGBA8 sampling: + // dim = 1 (bits 3..5 = 1 << 3 = 0x8), dmask = 0xf (bits 8..11 = 0xf << 8 = 0xf00). + // All other modifier flags (NSA, DLC, UNORM, GLC, DA, R128, TFE, SLC) must be zero. + const MODIFIER_MASK: u32 = 0x0203_fffe; + const EXPECTED_2D_RGBA: u32 = 0x0000_0f08; + + if first & MODIFIER_MASK != EXPECTED_2D_RGBA { + return Err(unsupported( + mnemonic, + "expected dim:SQ_RSRC_IMG_2D and dmask:0xf with zero modifier flags", + )); + } + + // In word 1: + // Bits 0..7: VADDR (u8) + // Bits 8..15: VDATA (u8) + // Bits 16..20: SRSRC >> 2 (5 bits) + // Bits 21..25: SSAMP >> 2 (5 bits) + // Bits 26..29: reserved (must be 0) + // Bit 30: A16 (0) + // Bit 31: D16 (0) + if second & 0xfc00_0000 != 0 { + return Err(unsupported( + mnemonic, + "expected 32-bit float coordinates and data without A16/D16", + )); + } + + let coord = (second & 0xff) as u8; + let dst = ((second >> 8) & 0xff) as u8; + let resource = (((second >> 16) & 0x1f) * 4) as u8; + let sampler = (((second >> 21) & 0x1f) * 4) as u8; + + // RDNA 2 resource descriptor (T#) requires 8 SGPRs; sampler (S#) requires 4 SGPRs. + // SGPR range is 0..=105 for normal allocatable registers. + if resource > 98 { + return Err(unsupported( + mnemonic, + "resource descriptor must fit in normal SGPRs s[0:105]", + )); + } + if sampler > 102 { + return Err(unsupported( + mnemonic, + "sampler descriptor must fit in normal SGPRs s[0:105]", + )); + } + + Ok((dst, coord, resource, sampler)) +} + fn buffer_operands( first: u32, second: u32, diff --git a/crates/decoder/tests/gfx1030.rs b/crates/decoder/tests/gfx1030.rs index 14f68f2a..fcc8905c 100644 --- a/crates/decoder/tests/gfx1030.rs +++ b/crates/decoder/tests/gfx1030.rs @@ -138,6 +138,93 @@ fn rejects_other_opcodes_and_noncanonical_operands() { ); } +#[test] +fn decodes_image_sample_lz_and_rejects_malformed_variants() { + // image_sample_lz v[4:7], v[2:3], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + // bytes: [0x08, 0x0f, 0x9c, 0xf0, 0x02, 0x04, 0x40, 0x00] + let words = [0xf09c_0f08_u32, 0x0040_0402_u32]; + let bytes: Vec = words.iter().flat_map(|w| w.to_le_bytes()).collect(); + + let decoded = decode(Architecture::Gfx1030, &bytes).expect("decode image_sample_lz"); + assert_eq!(decoded.len(), 1); + assert_eq!( + decoded[0], + DecodedInstruction { + offset: 0, + byte_len: 8, + instruction: Instruction::ImageSampleLz { + dst: 4, + coord: 2, + resource: 0, + sampler: 8, + }, + } + ); + + // Negative tests: + // 1. Truncated (less than 8 bytes) + assert!(matches!( + decode(Architecture::Gfx1030, &bytes[..4]).unwrap_err().kind, + DecodeErrorKind::Truncated { + needed: 8, + available: 4 + } + )); + + // 2. Unsupported dim (dim != 1, e.g. dim = 0, bit 3 clear) + let bad_dim = [0xf09c_0f00_u32, 0x0040_0402_u32]; + let bad_dim_bytes: Vec = bad_dim.iter().flat_map(|w| w.to_le_bytes()).collect(); + assert!(matches!( + decode(Architecture::Gfx1030, &bad_dim_bytes) + .unwrap_err() + .kind, + DecodeErrorKind::UnsupportedForm { + mnemonic: "image_sample_lz", + .. + } + )); + + // 3. Unsupported dmask (dmask != 0xf, e.g. dmask = 0x1) + let bad_dmask = [0xf09c_0108_u32, 0x0040_0402_u32]; + let bad_dmask_bytes: Vec = bad_dmask.iter().flat_map(|w| w.to_le_bytes()).collect(); + assert!(matches!( + decode(Architecture::Gfx1030, &bad_dmask_bytes) + .unwrap_err() + .kind, + DecodeErrorKind::UnsupportedForm { + mnemonic: "image_sample_lz", + .. + } + )); + + // 4. Modifiers set (e.g. A16 bit 30 set in second word) + let bad_a16 = [0xf09c_0f08_u32, 0x4040_0402_u32]; + let bad_a16_bytes: Vec = bad_a16.iter().flat_map(|w| w.to_le_bytes()).collect(); + assert!(matches!( + decode(Architecture::Gfx1030, &bad_a16_bytes) + .unwrap_err() + .kind, + DecodeErrorKind::UnsupportedForm { + mnemonic: "image_sample_lz", + .. + } + )); + + // 5. Out of range SGPR for resource (resource > 98) + // 25 << 16 * 4 = 100 > 98 + let bad_res = [0xf09c_0f08_u32, 0x0059_0402_u32]; + let bad_res_bytes: Vec = bad_res.iter().flat_map(|w| w.to_le_bytes()).collect(); + assert!(matches!( + decode(Architecture::Gfx1030, &bad_res_bytes) + .unwrap_err() + .kind, + DecodeErrorKind::UnsupportedForm { + mnemonic: "image_sample_lz", + .. + } + )); +} + #[test] fn rejects_targets_at_eof_or_inside_a_literal() { for (words, target) in [ @@ -270,8 +357,10 @@ fn reference_op(instruction: Instruction) -> Op { Instruction::VectorMulF32 { dst, src0, src1 } => { Op::Vector(VectorAlu::FloatMultiply, dst, src0, src1) } - Instruction::Export { .. } | Instruction::Interpolate { .. } => { - panic!("compute reference matrix received a graphics instruction") + Instruction::Export { .. } + | Instruction::Interpolate { .. } + | Instruction::ImageSampleLz { .. } => { + panic!("compute reference matrix received a graphics/image instruction") } Instruction::EndProgram => Op::End, diff --git a/crates/isa/generate_rdna2.py b/crates/isa/generate_rdna2.py index a3d0ceff..5eb4f44b 100644 --- a/crates/isa/generate_rdna2.py +++ b/crates/isa/generate_rdna2.py @@ -33,6 +33,7 @@ VARIANTS = ( ("EXP", "ENC_EXP"), ("V_INTERP_P1_F32", "ENC_VINTRP"), ("V_INTERP_P2_F32", "ENC_VINTRP"), + ("IMAGE_SAMPLE_LZ", "ENC_MIMG"), ) @@ -40,10 +41,10 @@ def read_field(encoding, name): fields = encoding.findall("MicrocodeFormat/BitMap/Field") field = next(field for field in fields if field.findtext("FieldName") == name) ranges = field.findall("BitLayout/Range") - return sorted( + return [ (int(item.findtext("BitOffset")), int(item.findtext("BitCount"))) - for item in ranges - ) + for item in sorted(ranges, key=lambda x: int(x.attrib.get("Order", 0))) + ] def bits_to_word(value, ranges): diff --git a/crates/isa/src/lib.rs b/crates/isa/src/lib.rs index 787a97f5..ba93966b 100644 --- a/crates/isa/src/lib.rs +++ b/crates/isa/src/lib.rs @@ -4,10 +4,10 @@ use std::fmt; mod rdna2; pub use rdna2::{ - BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, S_BRANCH, S_CBRANCH_EXECZ, S_CBRANCH_SCC0, - S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, V_ADD_F32, - V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32, - V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32, + BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ, + S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, + V_ADD_F32, V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_INTERP_P1_F32, V_INTERP_P2_F32, + V_LSHLREV_B32, V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32, }; /// Selects the instruction encoding independently of the container and execution ABI. @@ -159,6 +159,17 @@ pub enum Instruction { attribute: u8, component: u8, }, + /// MIMG image_sample_lz 2D RGBA8 texture sample with level of detail zero. + ImageSampleLz { + /// Four contiguous destination VGPRs [dst..dst+3] receiving RGBA. + dst: u8, + /// Two contiguous coordinate VGPRs [coord..coord+1] containing (u, v). + coord: u8, + /// First SGPR of the eight-word resource descriptor s[resource..resource+7]. + resource: u8, + /// First SGPR of the four-word sampler descriptor s[sampler..sampler+3]. + sampler: u8, + }, /// Terminates the wave and waits for outstanding memory operations. EndProgram, } @@ -196,6 +207,7 @@ impl Instruction { phase: InterpolationPhase::Second, .. } => "v_interp_p2_f32_e32", + Self::ImageSampleLz { .. } => "image_sample_lz", Self::EndProgram => "s_endpgm", } } @@ -275,6 +287,21 @@ impl fmt::Display for Instruction { " v{dst}, v{coordinate}, attr{attribute}.{channel}" ) } + Self::ImageSampleLz { + dst, + coord, + resource, + sampler, + } => { + let last_dst = dst + 3; + let last_coord = coord + 1; + let last_res = resource + 7; + let last_samp = sampler + 3; + write!( + formatter, + " v[{dst}:{last_dst}], v[{coord}:{last_coord}], s[{resource}:{last_res}], s[{sampler}:{last_samp}] dmask:0xf dim:SQ_RSRC_IMG_2D" + ) + } Self::EndProgram => Ok(()), } } diff --git a/crates/isa/src/rdna2.rs b/crates/isa/src/rdna2.rs index 1baa2cef..8c5b4a8d 100644 --- a/crates/isa/src/rdna2.rs +++ b/crates/isa/src/rdna2.rs @@ -125,3 +125,8 @@ pub const V_INTERP_P2_F32: Opcode = Opcode { bits: 0xc8010000, bytes: 4, }; +pub const IMAGE_SAMPLE_LZ: Opcode = Opcode { + mask: 0xfdfc0001, + bits: 0xf09c0000, + bytes: 8, +}; diff --git a/crates/loader/Cargo.toml b/crates/loader/Cargo.toml new file mode 100644 index 00000000..be2b9840 --- /dev/null +++ b/crates/loader/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "xenora-loader" +description = "PE32+ loader, guest memory management, and x86-64 execution bootstrap for Xenora" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[lints] +workspace = true + +[dependencies] diff --git a/crates/loader/src/cpu.rs b/crates/loader/src/cpu.rs new file mode 100644 index 00000000..6405a2dc --- /dev/null +++ b/crates/loader/src/cpu.rs @@ -0,0 +1,612 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Minimal x86-64 guest CPU register state and bounded instruction interpreter. +//! +//! Executes real x86-64 opcodes in software against isolated `GuestMemory`. +//! Never executes guest x86-64 code natively on host ARM64. + +use crate::memory::{GuestMemory, MemoryError}; +use std::fmt; + +/// 64-bit General Purpose Register identifiers in x86-64. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Register { + Rax = 0, + Rcx = 1, + Rdx = 2, + Rbx = 3, + Rsp = 4, + Rbp = 5, + Rsi = 6, + Rdi = 7, + R8 = 8, + R9 = 9, + R10 = 10, + R11 = 11, + R12 = 12, + R13 = 13, + R14 = 14, + R15 = 15, +} + +impl Register { + pub fn from_index(index: u8) -> Self { + match index & 0xF { + 0 => Self::Rax, + 1 => Self::Rcx, + 2 => Self::Rdx, + 3 => Self::Rbx, + 4 => Self::Rsp, + 5 => Self::Rbp, + 6 => Self::Rsi, + 7 => Self::Rdi, + 8 => Self::R8, + 9 => Self::R9, + 10 => Self::R10, + 11 => Self::R11, + 12 => Self::R12, + 13 => Self::R13, + 14 => Self::R14, + 15 => Self::R15, + _ => unreachable!(), + } + } +} + +/// RFLAGS status bits tracked during guest execution. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct RFlags { + pub cf: bool, // Carry flag + pub zf: bool, // Zero flag + pub sf: bool, // Sign flag + pub of: bool, // Overflow flag +} + +/// x86-64 CPU state. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct CpuState { + pub gpr: [u64; 16], + pub rip: u64, + pub flags: RFlags, +} + +impl CpuState { + pub fn new(entry_point: u64, stack_pointer: u64) -> Self { + let mut gpr = [0u64; 16]; + gpr[Register::Rsp as usize] = stack_pointer; + Self { + gpr, + rip: entry_point, + flags: RFlags::default(), + } + } + + pub fn get(&self, reg: Register) -> u64 { + self.gpr[reg as usize] + } + + pub fn set(&mut self, reg: Register, val: u64) { + self.gpr[reg as usize] = val; + } +} + +/// Termination reason for guest execution. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ExitReason { + Halt, + Syscall(u64), + StepLimitExceeded, + MemoryFault(MemoryError), + IllegalInstruction(u8), + StackUnderflow, +} + +impl fmt::Display for ExitReason { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Halt => write!(f, "guest executed HLT"), + Self::Syscall(nr) => write!(f, "guest executed SYSCALL ({nr})"), + Self::StepLimitExceeded => write!(f, "execution step budget exhausted"), + Self::MemoryFault(e) => write!(f, "memory fault: {e}"), + Self::IllegalInstruction(op) => write!(f, "illegal or unsupported opcode: 0x{op:02x}"), + Self::StackUnderflow => write!(f, "stack underflow"), + } + } +} + +impl std::error::Error for ExitReason {} + +/// Result returned after running guest execution. +#[derive(Debug)] +pub struct ExecutionResult { + pub instructions_executed: usize, + pub final_state: CpuState, + pub exit_reason: ExitReason, +} + +/// Bounded software interpreter for x86-64 instructions. +pub struct Interpreter<'a> { + pub cpu: CpuState, + pub memory: &'a mut GuestMemory, + pub max_instructions: usize, + pub instructions_executed: usize, +} + +impl<'a> Interpreter<'a> { + pub fn new(cpu: CpuState, memory: &'a mut GuestMemory, max_instructions: usize) -> Self { + Self { + cpu, + memory, + max_instructions, + instructions_executed: 0, + } + } + + /// Run interpreter until halt, error, or instruction budget limit. + pub fn run(&mut self) -> ExecutionResult { + while self.instructions_executed < self.max_instructions { + match self.step() { + Ok(None) => { + self.instructions_executed += 1; + } + Ok(Some(reason)) => { + self.instructions_executed += 1; + return ExecutionResult { + instructions_executed: self.instructions_executed, + final_state: self.cpu.clone(), + exit_reason: reason, + }; + } + Err(reason) => { + return ExecutionResult { + instructions_executed: self.instructions_executed, + final_state: self.cpu.clone(), + exit_reason: reason, + }; + } + } + } + + ExecutionResult { + instructions_executed: self.instructions_executed, + final_state: self.cpu.clone(), + exit_reason: ExitReason::StepLimitExceeded, + } + } + + fn fetch_u8(&mut self) -> Result { + let b = self + .memory + .fetch_instruction_byte(self.cpu.rip) + .map_err(ExitReason::MemoryFault)?; + self.cpu.rip += 1; + Ok(b) + } + + fn fetch_u32(&mut self) -> Result { + let mut bytes = [0u8; 4]; + for b in &mut bytes { + *b = self.fetch_u8()?; + } + Ok(u32::from_le_bytes(bytes)) + } + + fn fetch_u64(&mut self) -> Result { + let mut bytes = [0u8; 8]; + for b in &mut bytes { + *b = self.fetch_u8()?; + } + Ok(u64::from_le_bytes(bytes)) + } + + fn fetch_i8(&mut self) -> Result { + Ok(self.fetch_u8()? as i8) + } + + fn fetch_i32(&mut self) -> Result { + Ok(self.fetch_u32()? as i32) + } + + /// Single-step execution. Returns Ok(Some(ExitReason)) on clean exit (HLT/SYSCALL). + pub fn step(&mut self) -> Result, ExitReason> { + let mut rex_w = false; + let mut rex_r = false; + let mut rex_b = false; + + let mut byte = self.fetch_u8()?; + + // Handle REX prefix (0x40 - 0x4F) + if (byte & 0xF0) == 0x40 { + rex_w = (byte & 0x08) != 0; + rex_r = (byte & 0x04) != 0; + rex_b = (byte & 0x01) != 0; + byte = self.fetch_u8()?; + } + + match byte { + // HLT: Halt execution + 0xF4 => Ok(Some(ExitReason::Halt)), + + // SYSCALL: 0x0F 0x05 + 0x0F => { + let second = self.fetch_u8()?; + if second == 0x05 { + let syscall_num = self.cpu.get(Register::Rax); + Ok(Some(ExitReason::Syscall(syscall_num))) + } else { + Err(ExitReason::IllegalInstruction(second)) + } + } + + // MOV r32, imm32 (0xB8 + reg) or MOV r64, imm64 with REX.W + 0xB8..=0xBF => { + let reg_idx = (byte - 0xB8) + if rex_b { 8 } else { 0 }; + let reg = Register::from_index(reg_idx); + if rex_w { + let imm = self.fetch_u64()?; + self.cpu.set(reg, imm); + } else { + let imm = self.fetch_u32()? as u64; // Zero-extended in x86-64 + self.cpu.set(reg, imm); + } + Ok(None) + } + + // XOR r/m, reg (0x31) or XOR reg, r/m (0x33) + 0x31 | 0x33 => { + let modrm = self.fetch_u8()?; + let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?; + let (src, dst) = if byte == 0x31 { (reg, rm) } else { (rm, reg) }; + let val1 = self.cpu.get(dst); + let val2 = self.cpu.get(src); + let res = if rex_w { + val1 ^ val2 + } else { + (val1 as u32 ^ val2 as u32) as u64 + }; + self.cpu.set(dst, res); + self.update_flags_logic(res, rex_w); + Ok(None) + } + + // ADD r/m, reg (0x01) or ADD reg, r/m (0x03) + 0x01 | 0x03 => { + let modrm = self.fetch_u8()?; + let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?; + let (src, dst) = if byte == 0x01 { (reg, rm) } else { (rm, reg) }; + let val1 = self.cpu.get(dst); + let val2 = self.cpu.get(src); + let (res, flags) = if rex_w { + add64(val1, val2) + } else { + let (r, f) = add32(val1 as u32, val2 as u32); + (r as u64, f) + }; + self.cpu.set(dst, res); + self.cpu.flags = flags; + Ok(None) + } + + // SUB r/m, reg (0x29) or SUB reg, r/m (0x2B) + 0x29 | 0x2B => { + let modrm = self.fetch_u8()?; + let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?; + let (src, dst) = if byte == 0x29 { (reg, rm) } else { (rm, reg) }; + let val1 = self.cpu.get(dst); + let val2 = self.cpu.get(src); + let (res, flags) = if rex_w { + sub64(val1, val2) + } else { + let (r, f) = sub32(val1 as u32, val2 as u32); + (r as u64, f) + }; + self.cpu.set(dst, res); + self.cpu.flags = flags; + Ok(None) + } + + // CMP reg, r/m (0x3B) or CMP r/m, reg (0x39) + 0x39 | 0x3B => { + let modrm = self.fetch_u8()?; + let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?; + let (v1, v2) = if byte == 0x39 { + (self.cpu.get(rm), self.cpu.get(reg)) + } else { + (self.cpu.get(reg), self.cpu.get(rm)) + }; + let (_, flags) = if rex_w { + sub64(v1, v2) + } else { + let (r, f) = sub32(v1 as u32, v2 as u32); + (r as u64, f) + }; + self.cpu.flags = flags; + Ok(None) + } + + // Immediate group 1: 0x83 /op reg, imm8 + 0x83 => { + let modrm = self.fetch_u8()?; + let op = (modrm >> 3) & 7; + let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?; + let imm8 = self.fetch_i8()? as i64; + let imm = imm8 as u64; + + let val = self.cpu.get(rm); + match op { + 0 => { + // ADD + let (res, flags) = if rex_w { + add64(val, imm) + } else { + let (r, f) = add32(val as u32, imm as u32); + (r as u64, f) + }; + self.cpu.set(rm, res); + self.cpu.flags = flags; + } + 5 => { + // SUB + let (res, flags) = if rex_w { + sub64(val, imm) + } else { + let (r, f) = sub32(val as u32, imm as u32); + (r as u64, f) + }; + self.cpu.set(rm, res); + self.cpu.flags = flags; + } + 7 => { + // CMP + let (_, flags) = if rex_w { + sub64(val, imm) + } else { + let (r, f) = sub32(val as u32, imm as u32); + (r as u64, f) + }; + self.cpu.flags = flags; + } + _ => return Err(ExitReason::IllegalInstruction(byte)), + } + let _ = reg; + Ok(None) + } + + // MOV r/m, reg (0x89) or MOV reg, r/m (0x8B) + 0x89 | 0x8B => { + let modrm = self.fetch_u8()?; + self.execute_mov_rm(modrm, rex_w, rex_r, rex_b, byte == 0x8B) + } + + // JMP rel8 (0xEB) + 0xEB => { + let offset = self.fetch_i8()? as i64; + self.cpu.rip = (self.cpu.rip as i64 + offset) as u64; + Ok(None) + } + + // JMP rel32 (0xE9) + 0xE9 => { + let offset = self.fetch_i32()? as i64; + self.cpu.rip = (self.cpu.rip as i64 + offset) as u64; + Ok(None) + } + + // JZ/JE rel8 (0x74) + 0x74 => { + let offset = self.fetch_i8()? as i64; + if self.cpu.flags.zf { + self.cpu.rip = (self.cpu.rip as i64 + offset) as u64; + } + Ok(None) + } + + // JNZ/JNE rel8 (0x75) + 0x75 => { + let offset = self.fetch_i8()? as i64; + if !self.cpu.flags.zf { + self.cpu.rip = (self.cpu.rip as i64 + offset) as u64; + } + Ok(None) + } + + // CALL rel32 (0xE8) + 0xE8 => { + let offset = self.fetch_i32()? as i64; + let target = (self.cpu.rip as i64 + offset) as u64; + let ret_addr = self.cpu.rip; + self.push_u64(ret_addr)?; + self.cpu.rip = target; + Ok(None) + } + + // RET (0xC3) + 0xC3 => { + let ret_addr = self.pop_u64()?; + self.cpu.rip = ret_addr; + Ok(None) + } + + // PUSH reg (0x50..=0x57) + 0x50..=0x57 => { + let reg_idx = (byte - 0x50) + if rex_b { 8 } else { 0 }; + let reg = Register::from_index(reg_idx); + let val = self.cpu.get(reg); + self.push_u64(val)?; + Ok(None) + } + + // POP reg (0x58..=0x5F) + 0x58..=0x5F => { + let reg_idx = (byte - 0x58) + if rex_b { 8 } else { 0 }; + let reg = Register::from_index(reg_idx); + let val = self.pop_u64()?; + self.cpu.set(reg, val); + Ok(None) + } + + _ => Err(ExitReason::IllegalInstruction(byte)), + } + } + + fn push_u64(&mut self, val: u64) -> Result<(), ExitReason> { + let sp = self.cpu.get(Register::Rsp); + let new_sp = sp.checked_sub(8).ok_or(ExitReason::StackUnderflow)?; + self.memory + .write_u64(new_sp, val) + .map_err(ExitReason::MemoryFault)?; + self.cpu.set(Register::Rsp, new_sp); + Ok(()) + } + + fn pop_u64(&mut self) -> Result { + let sp = self.cpu.get(Register::Rsp); + let val = self.memory.read_u64(sp).map_err(ExitReason::MemoryFault)?; + self.cpu.set(Register::Rsp, sp + 8); + Ok(val) + } + + fn decode_modrm_reg_reg( + &self, + modrm: u8, + rex_r: bool, + rex_b: bool, + ) -> Result<(Register, Register), ExitReason> { + let mode = (modrm >> 6) & 3; + if mode != 3 { + return Err(ExitReason::IllegalInstruction(modrm)); + } + let reg_idx = ((modrm >> 3) & 7) + if rex_r { 8 } else { 0 }; + let rm_idx = (modrm & 7) + if rex_b { 8 } else { 0 }; + Ok((Register::from_index(reg_idx), Register::from_index(rm_idx))) + } + + fn execute_mov_rm( + &mut self, + modrm: u8, + rex_w: bool, + rex_r: bool, + rex_b: bool, + is_load: bool, + ) -> Result, ExitReason> { + 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 }; + let reg = Register::from_index(reg_idx); + + if mode == 3 { + // Register-to-register move + let rm = Register::from_index(rm_idx); + if is_load { + let val = self.cpu.get(rm); + self.cpu + .set(reg, if rex_w { val } else { val as u32 as u64 }); + } else { + let val = self.cpu.get(reg); + self.cpu + .set(rm, if rex_w { val } else { val as u32 as u64 }); + } + return Ok(None); + } + + // Memory operand [rm + disp] + let base_reg = Register::from_index(rm_idx); + let base_val = self.cpu.get(base_reg); + + let disp: i64 = match mode { + 0 => { + if (rm_idx & 7) == 5 { + // RIP-relative displacement disp32 + self.fetch_i32()? as i64 + } else { + 0 + } + } + 1 => self.fetch_i8()? as i64, + 2 => self.fetch_i32()? as i64, + _ => unreachable!(), + }; + + let effective_addr = if mode == 0 && (rm_idx & 7) == 5 { + (self.cpu.rip as i64 + disp) as u64 + } else { + (base_val as i64 + disp) as u64 + }; + + if is_load { + // Load from memory to reg + if rex_w { + let val = self + .memory + .read_u64(effective_addr) + .map_err(ExitReason::MemoryFault)?; + self.cpu.set(reg, val); + } else { + let val = self + .memory + .read_u32(effective_addr) + .map_err(ExitReason::MemoryFault)?; + self.cpu.set(reg, val as u64); + } + } else { + // Store from reg to memory + let val = self.cpu.get(reg); + if rex_w { + self.memory + .write_u64(effective_addr, val) + .map_err(ExitReason::MemoryFault)?; + } else { + self.memory + .write_u32(effective_addr, val as u32) + .map_err(ExitReason::MemoryFault)?; + } + } + + Ok(None) + } + + fn update_flags_logic(&mut self, val: u64, is_64: bool) { + self.cpu.flags.cf = false; + self.cpu.flags.of = false; + if is_64 { + self.cpu.flags.zf = val == 0; + self.cpu.flags.sf = (val as i64) < 0; + } else { + let val32 = val as u32; + self.cpu.flags.zf = val32 == 0; + self.cpu.flags.sf = (val32 as i32) < 0; + } + } +} + +fn add64(a: u64, b: u64) -> (u64, RFlags) { + let (res, cf) = a.overflowing_add(b); + let of = ((a ^ res) & (b ^ res) & 0x8000_0000_0000_0000) != 0; + let sf = (res as i64) < 0; + let zf = res == 0; + (res, RFlags { cf, zf, sf, of }) +} + +fn add32(a: u32, b: u32) -> (u32, RFlags) { + let (res, cf) = a.overflowing_add(b); + let of = ((a ^ res) & (b ^ res) & 0x8000_0000) != 0; + let sf = (res as i32) < 0; + let zf = res == 0; + (res, RFlags { cf, zf, sf, of }) +} + +fn sub64(a: u64, b: u64) -> (u64, RFlags) { + let (res, cf) = a.overflowing_sub(b); + let of = ((a ^ b) & (a ^ res) & 0x8000_0000_0000_0000) != 0; + let sf = (res as i64) < 0; + let zf = res == 0; + (res, RFlags { cf, zf, sf, of }) +} + +fn sub32(a: u32, b: u32) -> (u32, RFlags) { + let (res, cf) = a.overflowing_sub(b); + let of = ((a ^ b) & (a ^ res) & 0x8000_0000) != 0; + let sf = (res as i32) < 0; + let zf = res == 0; + (res, RFlags { cf, zf, sf, of }) +} diff --git a/crates/loader/src/lib.rs b/crates/loader/src/lib.rs new file mode 100644 index 00000000..19b5a1f4 --- /dev/null +++ b/crates/loader/src/lib.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Xenora Loader crate. +//! +//! Provides PE32+ parsing, isolated guest virtual memory, bounded x86-64 CPU +//! execution bootstrap, and read-only binary triage. + +pub mod cpu; +pub mod memory; +pub mod pe; +pub mod triage; + +pub use cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, RFlags, Register}; +pub use memory::{GuestMemory, MemoryError, MemoryPermissions}; +pub use pe::{LoadedImage, ParsedPe, PeError, PeSection}; +pub use triage::{TriageReport, triage_bytes, triage_file}; diff --git a/crates/loader/src/memory.rs b/crates/loader/src/memory.rs new file mode 100644 index 00000000..98dfe890 --- /dev/null +++ b/crates/loader/src/memory.rs @@ -0,0 +1,256 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Guest virtual memory model for Xenora's x86-64 execution bootstrap. +//! +//! Provides isolated, page-aligned guest virtual memory with permission checking +//! (Read, Write, Execute) and bounds enforcement without host OS mapping tricks. + +use std::fmt; + +/// Permission flags for a mapped memory region. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct MemoryPermissions { + pub read: bool, + pub write: bool, + pub execute: bool, +} + +impl MemoryPermissions { + pub const READ_ONLY: Self = Self { + read: true, + write: false, + execute: false, + }; + pub const READ_WRITE: Self = Self { + read: true, + write: true, + execute: false, + }; + pub const READ_EXECUTE: Self = Self { + read: true, + write: false, + execute: true, + }; + pub const READ_WRITE_EXECUTE: Self = Self { + read: true, + write: true, + execute: true, + }; +} + +/// Errors occurring during guest memory operations. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MemoryError { + UnmappedAddress(u64), + PermissionViolation { + address: u64, + required: &'static str, + }, + OverlappingRegion { + base: u64, + size: u64, + }, + Overflow, + AllocationFailed, +} + +impl fmt::Display for MemoryError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::UnmappedAddress(addr) => write!(f, "unmapped guest address 0x{addr:016x}"), + Self::PermissionViolation { address, required } => { + write!( + f, + "permission violation at guest address 0x{address:016x}: requires {required}" + ) + } + Self::OverlappingRegion { base, size } => { + write!( + f, + "overlapping memory region: base 0x{base:016x}, size 0x{size:x}" + ) + } + Self::Overflow => write!(f, "guest memory address calculation overflow"), + Self::AllocationFailed => write!(f, "guest memory allocation exceeds allowed limit"), + } + } +} + +impl std::error::Error for MemoryError {} + +#[derive(Clone)] +struct MappedRegion { + base: u64, + data: Vec, + permissions: MemoryPermissions, +} + +impl MappedRegion { + fn contains(&self, address: u64, size: usize) -> bool { + let size_u64 = size as u64; + let Some(end) = address.checked_add(size_u64) else { + return false; + }; + let region_end = self.base + self.data.len() as u64; + address >= self.base && end <= region_end + } +} + +/// Guest virtual memory address space. +#[derive(Default, Clone)] +pub struct GuestMemory { + regions: Vec, +} + +impl GuestMemory { + /// Create a new empty guest address space. + pub fn new() -> Self { + Self { + regions: Vec::new(), + } + } + + /// Map a new region into guest virtual memory. + pub fn map_region( + &mut self, + base: u64, + size: usize, + permissions: MemoryPermissions, + ) -> Result<(), MemoryError> { + let size_u64 = size as u64; + let end = base.checked_add(size_u64).ok_or(MemoryError::Overflow)?; + + // Ensure no overlap with existing regions + for r in &self.regions { + let r_end = r.base + r.data.len() as u64; + if (base < r_end) && (r.base < end) { + return Err(MemoryError::OverlappingRegion { + base, + size: size_u64, + }); + } + } + + self.regions.push(MappedRegion { + base, + data: vec![0u8; size], + permissions, + }); + + // Keep sorted by base address + self.regions.sort_by_key(|r| r.base); + Ok(()) + } + + /// Map a new region and initialize it with initial data, bypassing runtime write permission checks. + pub fn map_region_with_data( + &mut self, + base: u64, + size: usize, + permissions: MemoryPermissions, + initial_data: &[u8], + ) -> Result<(), MemoryError> { + let size_u64 = size as u64; + let end = base.checked_add(size_u64).ok_or(MemoryError::Overflow)?; + + for r in &self.regions { + let r_end = r.base + r.data.len() as u64; + if (base < r_end) && (r.base < end) { + return Err(MemoryError::OverlappingRegion { + base, + size: size_u64, + }); + } + } + + let mut data = vec![0u8; size]; + let copy_len = std::cmp::min(size, initial_data.len()); + data[..copy_len].copy_from_slice(&initial_data[..copy_len]); + + self.regions.push(MappedRegion { + base, + data, + permissions, + }); + + self.regions.sort_by_key(|r| r.base); + Ok(()) + } + + /// Write raw bytes into guest memory at the specified address, checking permissions. + pub fn write_bytes(&mut self, address: u64, src: &[u8]) -> Result<(), MemoryError> { + for region in &mut self.regions { + if region.contains(address, src.len()) { + if !region.permissions.write { + return Err(MemoryError::PermissionViolation { + address, + required: "write", + }); + } + let offset = (address - region.base) as usize; + region.data[offset..offset + src.len()].copy_from_slice(src); + return Ok(()); + } + } + Err(MemoryError::UnmappedAddress(address)) + } + + /// Read raw bytes from guest memory at the specified address, checking permissions. + pub fn read_bytes(&self, address: u64, dst: &mut [u8]) -> Result<(), MemoryError> { + for region in &self.regions { + if region.contains(address, dst.len()) { + if !region.permissions.read { + return Err(MemoryError::PermissionViolation { + address, + required: "read", + }); + } + let offset = (address - region.base) as usize; + dst.copy_from_slice(®ion.data[offset..offset + dst.len()]); + return Ok(()); + } + } + Err(MemoryError::UnmappedAddress(address)) + } + + /// Read an instruction byte from guest memory, verifying execute permission. + pub fn fetch_instruction_byte(&self, address: u64) -> Result { + for region in &self.regions { + if region.contains(address, 1) { + if !region.permissions.execute { + return Err(MemoryError::PermissionViolation { + address, + required: "execute", + }); + } + let offset = (address - region.base) as usize; + return Ok(region.data[offset]); + } + } + Err(MemoryError::UnmappedAddress(address)) + } + + /// Read a 64-bit integer (little endian) from guest memory. + pub fn read_u64(&self, address: u64) -> Result { + let mut buf = [0u8; 8]; + self.read_bytes(address, &mut buf)?; + Ok(u64::from_le_bytes(buf)) + } + + /// 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()) + } + + /// Read a 32-bit integer (little endian) from guest memory. + pub fn read_u32(&self, address: u64) -> Result { + let mut buf = [0u8; 4]; + self.read_bytes(address, &mut buf)?; + Ok(u32::from_le_bytes(buf)) + } + + /// Write a 32-bit integer (little endian) to guest memory. + pub fn write_u32(&mut self, address: u64, value: u32) -> Result<(), MemoryError> { + self.write_bytes(address, &value.to_le_bytes()) + } +} diff --git a/crates/loader/src/pe.rs b/crates/loader/src/pe.rs new file mode 100644 index 00000000..34383fcf --- /dev/null +++ b/crates/loader/src/pe.rs @@ -0,0 +1,249 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! PE32+ (64-bit Portable Executable) format parser and section loader for Xenora. +//! +//! Parses standard PE32+ headers (DOS header, COFF header, Optional Header 64) +//! and loads valid section headers into `GuestMemory` with appropriate permissions. + +use crate::memory::{GuestMemory, MemoryError, MemoryPermissions}; +use std::fmt; + +/// Errors that can occur during PE32+ parsing and loading. +#[derive(Debug, PartialEq, Eq)] +pub enum PeError { + TooSmall, + InvalidDosSignature, + InvalidPeSignature, + UnsupportedMachine(u16), + InvalidMagic(u16), + InvalidSectionHeaders, + SectionMappingError(MemoryError), + InvalidEntryPoint, +} + +impl fmt::Display for PeError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::TooSmall => write!(f, "executable image is smaller than required headers"), + Self::InvalidDosSignature => write!(f, "invalid DOS signature (expected 'MZ')"), + Self::InvalidPeSignature => write!(f, "invalid PE signature (expected 'PE\\0\\0')"), + Self::UnsupportedMachine(m) => { + write!( + f, + "unsupported machine type 0x{m:04x} (expected AMD64 0x8664)" + ) + } + Self::InvalidMagic(magic) => { + write!( + f, + "invalid optional header magic 0x{magic:04x} (expected PE32+ 0x020b)" + ) + } + Self::InvalidSectionHeaders => write!(f, "invalid or corrupt section headers"), + Self::SectionMappingError(e) => write!(f, "failed to map section: {e}"), + Self::InvalidEntryPoint => write!(f, "entry point address is outside executable code"), + } + } +} + +impl std::error::Error for PeError {} + +/// An individual section extracted from a PE32+ header. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PeSection { + pub name: String, + pub virtual_address: u32, + pub virtual_size: u32, + pub raw_data_ptr: u32, + pub raw_data_size: u32, + pub characteristics: u32, + pub permissions: MemoryPermissions, +} + +/// Parsed metadata from a PE32+ executable. +#[derive(Clone, Debug)] +pub struct ParsedPe { + pub machine: u16, + pub number_of_sections: u16, + pub time_date_stamp: u32, + pub image_base: u64, + pub section_alignment: u32, + pub file_alignment: u32, + pub size_of_image: u32, + pub size_of_headers: u32, + pub entry_point_rva: u32, + pub sections: Vec, +} + +/// Result of loading a PE32+ image into guest memory. +pub struct LoadedImage { + pub pe: ParsedPe, + pub memory: GuestMemory, + pub entry_point: u64, +} + +// Windows PE Characteristic Constants +pub const IMAGE_SCN_MEM_EXECUTE: u32 = 0x20000000; +pub const IMAGE_SCN_MEM_READ: u32 = 0x40000000; +pub const IMAGE_SCN_MEM_WRITE: u32 = 0x80000000; + +// Standard Constants +pub const IMAGE_FILE_MACHINE_AMD64: u16 = 0x8664; +pub const PE32_PLUS_MAGIC: u16 = 0x020B; + +impl ParsedPe { + /// Parse PE32+ headers from an in-memory byte slice. + pub fn parse(bytes: &[u8]) -> Result { + if bytes.len() < 0x40 { + return Err(PeError::TooSmall); + } + + // 1. DOS Header + if &bytes[0..2] != b"MZ" { + return Err(PeError::InvalidDosSignature); + } + + let e_lfanew = u32::from_le_bytes(bytes[0x3C..0x40].try_into().unwrap()) as usize; + if bytes.len() < e_lfanew + 24 { + return Err(PeError::TooSmall); + } + + // 2. PE Signature + if &bytes[e_lfanew..e_lfanew + 4] != b"PE\0\0" { + return Err(PeError::InvalidPeSignature); + } + + // 3. COFF File Header + let coff_offset = e_lfanew + 4; + let machine = u16::from_le_bytes(bytes[coff_offset..coff_offset + 2].try_into().unwrap()); + if machine != IMAGE_FILE_MACHINE_AMD64 { + return Err(PeError::UnsupportedMachine(machine)); + } + + let number_of_sections = + u16::from_le_bytes(bytes[coff_offset + 2..coff_offset + 4].try_into().unwrap()); + let time_date_stamp = + u32::from_le_bytes(bytes[coff_offset + 4..coff_offset + 8].try_into().unwrap()); + let size_of_optional_header = u16::from_le_bytes( + bytes[coff_offset + 16..coff_offset + 18] + .try_into() + .unwrap(), + ) as usize; + + // 4. Optional Header (PE32+ is required) + let opt_offset = coff_offset + 20; + if bytes.len() < opt_offset + size_of_optional_header { + return Err(PeError::TooSmall); + } + + let magic = u16::from_le_bytes(bytes[opt_offset..opt_offset + 2].try_into().unwrap()); + if magic != PE32_PLUS_MAGIC { + return Err(PeError::InvalidMagic(magic)); + } + + let entry_point_rva = + u32::from_le_bytes(bytes[opt_offset + 16..opt_offset + 20].try_into().unwrap()); + let image_base = + u64::from_le_bytes(bytes[opt_offset + 24..opt_offset + 32].try_into().unwrap()); + let section_alignment = + u32::from_le_bytes(bytes[opt_offset + 32..opt_offset + 36].try_into().unwrap()); + let file_alignment = + u32::from_le_bytes(bytes[opt_offset + 36..opt_offset + 40].try_into().unwrap()); + let size_of_image = + u32::from_le_bytes(bytes[opt_offset + 56..opt_offset + 60].try_into().unwrap()); + let size_of_headers = + u32::from_le_bytes(bytes[opt_offset + 60..opt_offset + 64].try_into().unwrap()); + + // 5. Section Headers + let mut sections = Vec::with_capacity(number_of_sections as usize); + let section_table_offset = opt_offset + size_of_optional_header; + let section_header_size = 40; + + if bytes.len() < section_table_offset + (number_of_sections as usize * section_header_size) + { + return Err(PeError::InvalidSectionHeaders); + } + + for i in 0..number_of_sections as usize { + let offset = section_table_offset + i * section_header_size; + let sec_bytes = &bytes[offset..offset + section_header_size]; + + // Section name (up to 8 bytes UTF-8 or null-padded ASCII) + let name_raw = &sec_bytes[0..8]; + let name_len = name_raw.iter().position(|&b| b == 0).unwrap_or(8); + let name = String::from_utf8_lossy(&name_raw[..name_len]).into_owned(); + + let virtual_size = u32::from_le_bytes(sec_bytes[8..12].try_into().unwrap()); + let virtual_address = u32::from_le_bytes(sec_bytes[12..16].try_into().unwrap()); + let raw_data_size = u32::from_le_bytes(sec_bytes[16..20].try_into().unwrap()); + let raw_data_ptr = u32::from_le_bytes(sec_bytes[20..24].try_into().unwrap()); + let characteristics = u32::from_le_bytes(sec_bytes[36..40].try_into().unwrap()); + + let permissions = MemoryPermissions { + read: (characteristics & IMAGE_SCN_MEM_READ) != 0, + write: (characteristics & IMAGE_SCN_MEM_WRITE) != 0, + execute: (characteristics & IMAGE_SCN_MEM_EXECUTE) != 0, + }; + + sections.push(PeSection { + name, + virtual_address, + virtual_size, + raw_data_ptr, + raw_data_size, + characteristics, + permissions, + }); + } + + Ok(ParsedPe { + machine, + number_of_sections, + time_date_stamp, + image_base, + section_alignment, + file_alignment, + size_of_image, + size_of_headers, + entry_point_rva, + sections, + }) + } + + /// 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(); + + for sec in &self.sections { + let base_addr = self.image_base + sec.virtual_address as u64; + let map_size = std::cmp::max(sec.virtual_size, sec.raw_data_size) as usize; + if map_size == 0 { + continue; + } + + let initial_data = if sec.raw_data_size > 0 && sec.raw_data_ptr > 0 { + let start = sec.raw_data_ptr as usize; + let end = start + sec.raw_data_size as usize; + if end <= bytes.len() { + &bytes[start..end] + } else { + &[] + } + } else { + &[] + }; + + memory + .map_region_with_data(base_addr, map_size, sec.permissions, initial_data) + .map_err(PeError::SectionMappingError)?; + } + + let entry_point = self.image_base + self.entry_point_rva as u64; + + Ok(LoadedImage { + pe: self.clone(), + memory, + entry_point, + }) + } +} diff --git a/crates/loader/src/triage.rs b/crates/loader/src/triage.rs new file mode 100644 index 00000000..3f1fdf2c --- /dev/null +++ b/crates/loader/src/triage.rs @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Read-only PE32+ header and triage inspection. +//! +//! Provides diagnostic reports for executable binaries without loading or executing them. + +use crate::pe::{ParsedPe, PeError, PeSection}; +use std::fmt; +use std::fs; +use std::path::Path; + +/// High-level diagnostic report from inspecting a PE32+ binary. +#[derive(Clone, Debug)] +pub struct TriageReport { + pub file_size: usize, + pub machine: u16, + pub is_amd64: bool, + pub image_base: u64, + pub entry_point_rva: u32, + pub size_of_image: u32, + pub sections: Vec, +} + +impl fmt::Display for TriageReport { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + writeln!(f, "PE32+ Binary Triage Report:")?; + writeln!(f, " File Size: {} bytes", self.file_size)?; + writeln!( + f, + " Machine: 0x{:04x} (AMD64: {})", + self.machine, self.is_amd64 + )?; + writeln!(f, " Image Base: 0x{:016x}", self.image_base)?; + writeln!(f, " Entry Point RVA: 0x{:08x}", self.entry_point_rva)?; + writeln!(f, " Size of Image: 0x{:08x}", self.size_of_image)?; + writeln!(f, " Sections ({}):", self.sections.len())?; + for sec in &self.sections { + let perms = format!( + "{}{}{}", + if sec.permissions.read { "R" } else { "-" }, + if sec.permissions.write { "W" } else { "-" }, + if sec.permissions.execute { "X" } else { "-" } + ); + writeln!( + f, + " - {:<8} RVA: 0x{:08x} Size: 0x{:08x} Raw: 0x{:08x} Perms: [{}]", + sec.name, sec.virtual_address, sec.virtual_size, sec.raw_data_size, perms + )?; + } + Ok(()) + } +} + +/// Inspect a PE32+ binary file from disk in read-only mode. +pub fn triage_file>(path: P) -> Result { + let bytes = fs::read(path).map_err(|_| PeError::TooSmall)?; + triage_bytes(&bytes) +} + +/// Inspect in-memory PE32+ bytes in read-only mode. +pub fn triage_bytes(bytes: &[u8]) -> Result { + let pe = ParsedPe::parse(bytes)?; + Ok(TriageReport { + file_size: bytes.len(), + machine: pe.machine, + is_amd64: pe.machine == crate::pe::IMAGE_FILE_MACHINE_AMD64, + image_base: pe.image_base, + entry_point_rva: pe.entry_point_rva, + size_of_image: pe.size_of_image, + sections: pe.sections, + }) +} diff --git a/crates/loader/tests/bootstrap.rs b/crates/loader/tests/bootstrap.rs new file mode 100644 index 00000000..76ae64ab --- /dev/null +++ b/crates/loader/tests/bootstrap.rs @@ -0,0 +1,258 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! End-to-end integration tests for Xenora X12: PE32+ loading & x86-64 execution bootstrap. + +use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, Register}; +use xenora_loader::memory::{MemoryError, MemoryPermissions}; +use xenora_loader::pe::{ + IMAGE_FILE_MACHINE_AMD64, IMAGE_SCN_MEM_EXECUTE, IMAGE_SCN_MEM_READ, PE32_PLUS_MAGIC, ParsedPe, +}; +use xenora_loader::triage::triage_bytes; + +/// Helper to build a valid synthetic PE32+ executable with a single .text section. +fn build_synthetic_pe32_plus(code: &[u8]) -> Vec { + let mut pe = Vec::new(); + + // 1. DOS Header (64 bytes) + pe.extend_from_slice(b"MZ"); + pe.resize(0x3C, 0); + // e_lfanew at 0x3C points to 0x80 + let e_lfanew: u32 = 0x80; + pe.extend_from_slice(&e_lfanew.to_le_bytes()); + pe.resize(0x80, 0); + + // 2. PE Signature + pe.extend_from_slice(b"PE\0\0"); + + // 3. COFF File Header (20 bytes) + pe.extend_from_slice(&IMAGE_FILE_MACHINE_AMD64.to_le_bytes()); // Machine: 0x8664 + let num_sections: u16 = 1; + pe.extend_from_slice(&num_sections.to_le_bytes()); + let time_stamp: u32 = 0x67300000; + pe.extend_from_slice(&time_stamp.to_le_bytes()); + pe.extend_from_slice(&0u32.to_le_bytes()); // PointerToSymbolTable + pe.extend_from_slice(&0u32.to_le_bytes()); // NumberOfSymbols + let opt_hdr_size: u16 = 112; // Standard size without data directories + pe.extend_from_slice(&opt_hdr_size.to_le_bytes()); + let characteristics: u16 = 0x0022; // EXECUTABLE_IMAGE | LARGE_ADDRESS_AWARE + pe.extend_from_slice(&characteristics.to_le_bytes()); + + // 4. Optional Header (PE32+) (112 bytes) + pe.extend_from_slice(&PE32_PLUS_MAGIC.to_le_bytes()); // Magic: 0x020B + pe.push(14); // MajorLinkerVersion + pe.push(0); // MinorLinkerVersion + pe.extend_from_slice(&(code.len() as u32).to_le_bytes()); // SizeOfCode + pe.extend_from_slice(&0u32.to_le_bytes()); // SizeOfInitializedData + pe.extend_from_slice(&0u32.to_le_bytes()); // SizeOfUninitializedData + let entry_point_rva: u32 = 0x1000; + pe.extend_from_slice(&entry_point_rva.to_le_bytes()); // AddressOfEntryPoint + pe.extend_from_slice(&0x1000u32.to_le_bytes()); // BaseOfCode + let image_base: u64 = 0x0000000140000000; + pe.extend_from_slice(&image_base.to_le_bytes()); // ImageBase + pe.extend_from_slice(&0x1000u32.to_le_bytes()); // SectionAlignment + pe.extend_from_slice(&0x200u32.to_le_bytes()); // FileAlignment + pe.extend_from_slice(&6u16.to_le_bytes()); // MajorOSVersion + pe.extend_from_slice(&0u16.to_le_bytes()); // MinorOSVersion + pe.extend_from_slice(&0u16.to_le_bytes()); // MajorImageVersion + pe.extend_from_slice(&0u16.to_le_bytes()); // MinorImageVersion + pe.extend_from_slice(&6u16.to_le_bytes()); // MajorSubsystemVersion + pe.extend_from_slice(&0u16.to_le_bytes()); // MinorSubsystemVersion + pe.extend_from_slice(&0u32.to_le_bytes()); // Win32VersionValue + pe.extend_from_slice(&0x3000u32.to_le_bytes()); // SizeOfImage + let size_of_headers: u32 = 0x200; + pe.extend_from_slice(&size_of_headers.to_le_bytes()); // SizeOfHeaders + pe.extend_from_slice(&0u32.to_le_bytes()); // CheckSum + pe.extend_from_slice(&3u16.to_le_bytes()); // Subsystem: WINDOWS_CUI + pe.extend_from_slice(&0x8160u16.to_le_bytes()); // DllCharacteristics + pe.extend_from_slice(&0x100000u64.to_le_bytes()); // SizeOfStackReserve + pe.extend_from_slice(&0x1000u64.to_le_bytes()); // SizeOfStackCommit + pe.extend_from_slice(&0x100000u64.to_le_bytes()); // SizeOfHeapReserve + pe.extend_from_slice(&0x1000u64.to_le_bytes()); // SizeOfHeapCommit + pe.extend_from_slice(&0u32.to_le_bytes()); // LoaderFlags + pe.extend_from_slice(&0u32.to_le_bytes()); // NumberOfRvaAndSizes + + // 5. Section Table (1 section: .text, 40 bytes) + let mut sec_name = [0u8; 8]; + sec_name[..5].copy_from_slice(b".text"); + pe.extend_from_slice(&sec_name); + let virtual_size: u32 = code.len() as u32; + pe.extend_from_slice(&virtual_size.to_le_bytes()); // VirtualSize + pe.extend_from_slice(&0x1000u32.to_le_bytes()); // VirtualAddress + let raw_size: u32 = 0x200; + pe.extend_from_slice(&raw_size.to_le_bytes()); // SizeOfRawData + let raw_ptr: u32 = 0x200; + pe.extend_from_slice(&raw_ptr.to_le_bytes()); // PointerToRawData + pe.extend_from_slice(&0u32.to_le_bytes()); // PointerToRelocations + pe.extend_from_slice(&0u32.to_le_bytes()); // PointerToLinenumbers + pe.extend_from_slice(&0u16.to_le_bytes()); // NumberOfRelocations + pe.extend_from_slice(&0u16.to_le_bytes()); // NumberOfLinenumbers + let characteristics: u32 = IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_EXECUTE; // 0x60000020 + pe.extend_from_slice(&characteristics.to_le_bytes()); + + // Pad headers to FileAlignment (0x200) + pe.resize(0x200, 0); + + // Section raw data (.text) + pe.extend_from_slice(code); + pe.resize(0x400, 0); // Pad section to 0x200 raw size + + pe +} + +#[test] +fn test_pe_triage_and_parsing() { + let dummy_code = [0x90, 0xF4]; // NOP; HLT + let pe_bytes = build_synthetic_pe32_plus(&dummy_code); + + let triage = triage_bytes(&pe_bytes).expect("triage must succeed"); + assert!(triage.is_amd64); + assert_eq!(triage.image_base, 0x140000000); + assert_eq!(triage.entry_point_rva, 0x1000); + assert_eq!(triage.sections.len(), 1); + assert_eq!(triage.sections[0].name, ".text"); + assert!(triage.sections[0].permissions.execute); + assert!(triage.sections[0].permissions.read); + assert!(!triage.sections[0].permissions.write); +} + +#[test] +fn test_pe_loading_and_execution() { + // x86-64 program: + // mov rax, 42 -> 48 b8 2a 00 00 00 00 00 00 00 + // mov rcx, 10 -> 48 b9 0a 00 00 00 00 00 00 00 + // add rax, rcx -> 48 01 c8 + // hlt -> f4 + let mut code = Vec::new(); + // MOV RAX, 42 + code.extend_from_slice(&[0x48, 0xB8, 42, 0, 0, 0, 0, 0, 0, 0]); + // MOV RCX, 10 + code.extend_from_slice(&[0x48, 0xB9, 10, 0, 0, 0, 0, 0, 0, 0]); + // ADD RAX, RCX + code.extend_from_slice(&[0x48, 0x01, 0xC8]); + // HLT + code.push(0xF4); + + let pe_bytes = build_synthetic_pe32_plus(&code); + let parsed = ParsedPe::parse(&pe_bytes).expect("PE parse should succeed"); + let mut loaded = parsed + .load_into_memory(&pe_bytes) + .expect("PE load should succeed"); + + // Set up a guest stack region at 0x20000000 (RW) + let stack_base = 0x2000_0000u64; + let stack_size = 0x10000usize; + loaded + .memory + .map_region(stack_base, stack_size, MemoryPermissions::READ_WRITE) + .expect("stack mapping should succeed"); + let stack_top = stack_base + stack_size as u64; + + let cpu = CpuState::new(loaded.entry_point, stack_top); + let mut interp = Interpreter::new(cpu, &mut loaded.memory, 1000); + let result = interp.run(); + + assert_eq!(result.exit_reason, ExitReason::Halt); + assert_eq!(result.instructions_executed, 4); + assert_eq!(result.final_state.get(Register::Rax), 52); + assert_eq!(result.final_state.get(Register::Rcx), 10); + assert!(!result.final_state.flags.zf); +} + +#[test] +fn test_stack_operations_and_subroutine_call() { + // x86-64 program: + // mov rdx, 0x1234 (48 ba 34 12 00 00 00 00 00 00) + // push rdx (52) + // pop rbx (5b) + // call func (e8 05 00 00 00) + // hlt (f4) + // func: + // add rbx, 1 (48 83 c3 01) + // ret (c3) + let mut code = Vec::new(); + code.extend_from_slice(&[0x48, 0xBA, 0x34, 0x12, 0, 0, 0, 0, 0, 0]); // mov rdx, 0x1234 + code.push(0x52); // push rdx + code.push(0x5B); // pop rbx + code.extend_from_slice(&[0xE8, 0x01, 0x00, 0x00, 0x00]); // call +1 + code.push(0xF4); // hlt + code.extend_from_slice(&[0x48, 0x83, 0xC3, 0x01]); // add rbx, 1 + code.push(0xC3); // ret + + let pe_bytes = build_synthetic_pe32_plus(&code); + let parsed = ParsedPe::parse(&pe_bytes).expect("PE parse should succeed"); + let mut loaded = parsed + .load_into_memory(&pe_bytes) + .expect("PE load should succeed"); + + let stack_base = 0x3000_0000u64; + let stack_size = 0x10000usize; + loaded + .memory + .map_region(stack_base, stack_size, MemoryPermissions::READ_WRITE) + .expect("stack mapping should succeed"); + let stack_top = stack_base + stack_size as u64; + + let cpu = CpuState::new(loaded.entry_point, stack_top); + let mut interp = Interpreter::new(cpu, &mut loaded.memory, 1000); + let result = interp.run(); + + assert_eq!(result.exit_reason, ExitReason::Halt); + assert_eq!(result.final_state.get(Register::Rbx), 0x1235); + assert_eq!(result.final_state.get(Register::Rsp), stack_top); +} + +#[test] +fn test_step_budget_exhaustion() { + // Infinite loop: jmp -2 (EB FE) + let code = [0xEB, 0xFE]; + let pe_bytes = build_synthetic_pe32_plus(&code); + let parsed = ParsedPe::parse(&pe_bytes).expect("parse"); + let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load"); + + let cpu = CpuState::new(loaded.entry_point, 0x10000); + let mut interp = Interpreter::new(cpu, &mut loaded.memory, 50); + let result = interp.run(); + + assert_eq!(result.exit_reason, ExitReason::StepLimitExceeded); + assert_eq!(result.instructions_executed, 50); +} + +#[test] +fn test_unsupported_instruction_fails_deterministically() { + // Unsupported opcode: 0x0F 0x0B (UD2) + let code = [0x0F, 0x0B]; + let pe_bytes = build_synthetic_pe32_plus(&code); + let parsed = ParsedPe::parse(&pe_bytes).expect("parse"); + let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load"); + + let cpu = CpuState::new(loaded.entry_point, 0x10000); + let mut interp = Interpreter::new(cpu, &mut loaded.memory, 50); + let result = interp.run(); + + assert_eq!(result.exit_reason, ExitReason::IllegalInstruction(0x0B)); +} + +#[test] +fn test_memory_fault_on_unmapped_access() { + // MOV RAX, [0xDEADBEEF] -> 48 8B 04 25 EF BE AD DE (or simple reg-disp mov) + // Here: mov rax, 0xDEADBEEF; mov rbx, [rax] + // 48 b8 ef be ad de 00 00 00 00 + // 48 8b 18 (mov rbx, [rax]) + let code = [ + 0x48, 0xB8, 0xEF, 0xBE, 0xAD, 0xDE, 0x00, 0x00, 0x00, 0x00, 0x48, 0x8B, 0x18, + ]; + let pe_bytes = build_synthetic_pe32_plus(&code); + let parsed = ParsedPe::parse(&pe_bytes).expect("parse"); + let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load"); + + let cpu = CpuState::new(loaded.entry_point, 0x10000); + let mut interp = Interpreter::new(cpu, &mut loaded.memory, 50); + let result = interp.run(); + + match result.exit_reason { + ExitReason::MemoryFault(MemoryError::UnmappedAddress(addr)) => { + assert_eq!(addr, 0xDEADBEEF); + } + other => panic!("expected UnmappedAddress, got: {other:?}"), + } +} diff --git a/crates/metal/Cargo.toml b/crates/metal/Cargo.toml index 056a124d..107fe9d4 100644 --- a/crates/metal/Cargo.toml +++ b/crates/metal/Cargo.toml @@ -22,6 +22,7 @@ name = "sampler_texture" path = "tests/sampler_texture.rs" [dev-dependencies] +xenora-ref = { path = "../ref" } xenora-shader = { path = "../shader" } [target.'cfg(all(target_arch = "aarch64", target_os = "macos"))'.dependencies] diff --git a/crates/metal/src/render.rs b/crates/metal/src/render.rs index a8c7a472..1d815d9f 100644 --- a/crates/metal/src/render.rs +++ b/crates/metal/src/render.rs @@ -41,6 +41,40 @@ impl NativeCompute { colors: &[[f32; 4]; 3], [width, height]: [usize; 2], clear: [u8; 4], + ) -> Result, MetalError> { + self.render_rgba8_sampled( + source, + entries, + vertices, + colors, + [width, height], + clear, + None, + ) + } + + /// Draw one triangle with trusted MSL and optional bound sampled texture into a cleared RGBA8Unorm target. + /// + /// When `sampled` is provided, the texture is bound to fragment texture slot 0 and + /// the sampler to fragment sampler slot 0. + /// + /// # Errors + /// + /// Returns an error for non-finite inputs, invalid source or extent, or + /// Metal compilation, setup or completion failure. + #[allow(clippy::too_many_arguments)] + pub fn render_rgba8_sampled( + &self, + source: &str, + entries: [&str; 2], + vertices: &[[f32; 4]; 3], + colors: &[[f32; 4]; 3], + [width, height]: [usize; 2], + clear: [u8; 4], + sampled: Option<( + &crate::texture_pipeline::MetalRgba8Texture, + &crate::sampler::MetalSampler, + )>, ) -> Result, MetalError> { let pixels = width .checked_mul(height) @@ -149,6 +183,10 @@ impl NativeCompute { unsafe { encoder.setVertexBuffer_offset_atIndex(Some(&positions), 0, 0); encoder.setVertexBuffer_offset_atIndex(Some(&colors), 0, 1); + if let Some((tex, samp)) = sampled { + encoder.setFragmentTexture_atIndex(Some(tex.raw()), 0); + encoder.setFragmentSamplerState_atIndex(Some(samp.raw()), 0); + } encoder.drawPrimitives_vertexStart_vertexCount(MTLPrimitiveType::Triangle, 0, 3); } encoder.endEncoding(); diff --git a/crates/metal/tests/native/translated_render.rs b/crates/metal/tests/native/translated_render.rs index 5c537f90..5579098d 100644 --- a/crates/metal/tests/native/translated_render.rs +++ b/crates/metal/tests/native/translated_render.rs @@ -182,3 +182,118 @@ fn transformed_vertex_shader_draws_three_interior_pixels() { assert_eq!(passthrough_pixels, expected_passthrough.as_flattened()); println!("checked 3 covered pixels and 13 clear pixels from translated vertex arithmetic"); } + +#[test] +fn translated_image_sample_lz_pixel_shader_matches_cpu_reference() { + let gpu = context(); + + // 1. Prepare 2x2 RGBA8 texture with four distinct colors: + // (0, 0): Red [255, 0, 0, 255] + // (1, 0): Green [ 0, 255, 0, 255] + // (0, 1): Blue [ 0, 0, 255, 255] + // (1, 1): White [255, 255, 255, 255] + let texels_level0: [u8; 16] = [ + 255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255, + ]; + let tex_desc = xenora_metal::texture_pipeline::Rgba8TextureDesc::new(2, 2, 1) + .expect("valid 2x2 texture desc"); + let mip0 = xenora_metal::texture_pipeline::Rgba8MipLevel::new_packed(0, 2, 2, &texels_level0); + let texture = + xenora_metal::texture_pipeline::MetalRgba8Texture::upload(gpu.device(), tex_desc, &[mip0]) + .expect("upload RGBA8 2x2 texture to Metal"); + + // 2. Create native Metal sampler (nearest, clamp-to-edge) + let sampler_desc = xenora_texture::SamplerDesc::nearest_clamp(); + let sampler = xenora_metal::sampler::MetalSampler::new(gpu.device(), sampler_desc) + .expect("create native Metal sampler"); + + // 3. VS: x9-varying-vs.bin exports position from buffer(0) and UV from buffer(1) via param0 + let vs_bytes = include_bytes!("../../../../fixtures/rdna2/x9-varying-vs.bin"); + + // 4. PS: genuine gfx1030 machine-code instructions: + // v_interp_p1_f32_e32 v2, v0, attr0.x + // v_interp_p2_f32_e32 v2, v1, attr0.x + // v_interp_p1_f32_e32 v3, v0, attr0.y + // v_interp_p2_f32_e32 v3, v1, attr0.y + // image_sample_lz v[4:7], v[2:3], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + // exp mrt0, v4, v5, v6, v7 done vm + // s_endpgm + let mut ps_bytes = Vec::new(); + ps_bytes.extend_from_slice(&[0x00, 0x00, 0x08, 0xc8]); // v_interp_p1_f32_e32 v2, v0, attr0.x + ps_bytes.extend_from_slice(&[0x01, 0x00, 0x09, 0xc8]); // v_interp_p2_f32_e32 v2, v1, attr0.x + ps_bytes.extend_from_slice(&[0x00, 0x01, 0x0c, 0xc8]); // v_interp_p1_f32_e32 v3, v0, attr0.y + ps_bytes.extend_from_slice(&[0x01, 0x01, 0x0d, 0xc8]); // v_interp_p2_f32_e32 v3, v1, attr0.y + ps_bytes.extend_from_slice(&[0x08, 0x0f, 0x9c, 0xf0, 0x02, 0x04, 0x40, 0x00]); // image_sample_lz + ps_bytes.extend_from_slice(&[0x0f, 0x18, 0x00, 0xf8, 0x04, 0x05, 0x06, 0x07]); // exp mrt0 + ps_bytes.extend_from_slice(&[0x00, 0x00, 0x81, 0xbf]); // s_endpgm + + // 5. Compile through Xenora shader compiler pipeline: + // gfx1030 binary -> xenora-decoder -> xenora-shader IR -> MSL + let compiled = compile_graphics(Architecture::Gfx1030, vs_bytes, &ps_bytes) + .expect("compile translated image_sample_lz graphics shader"); + + assert!(compiled.ir.contains("sample_lz.2d.f32 tex0, samp0")); + assert!( + compiled + .msl + .contains("texture2d tex0 [[texture(0)]]") + ); + assert!(compiled.msl.contains("sampler samp0 [[sampler(0)]]")); + + // 6. Set up a fullscreen triangle covering a 2x2 render viewport: + // In Metal framebuffer layout, row 0 is at the top (NDC y = +1.0) and row 1 is at the bottom (NDC y = -1.0). + // Mapping UV coordinates so top row samples V in [0.0..0.5] and bottom row samples V in [0.5..1.0]: + // Vertex 0 (NDC [-1, -1], bottom-left) -> UV (0.0, 1.0) + // Vertex 1 (NDC [ 3, -1], bottom-right) -> UV (2.0, 1.0) + // Vertex 2 (NDC [-1, 3], top-left) -> UV (0.0, -1.0) + // In the 2x2 render target: + // Pixel (x=0, y=0, top-left row 0): center UV = (0.25, 0.25) -> Texel (0, 0) Red [255, 0, 0, 255] + // Pixel (x=1, y=0, top-right row 0): center UV = (0.75, 0.25) -> Texel (1, 0) Green [ 0, 255, 0, 255] + // Pixel (x=0, y=1, bottom-left row 1): center UV = (0.25, 0.75) -> Texel (0, 1) Blue [ 0, 0, 255, 255] + // Pixel (x=1, y=1, bottom-right row 1): center UV = (0.75, 0.75) -> Texel (1, 1) White [255, 255, 255, 255] + let uv_coords = [ + [0.0_f32, 1.0, 0.0, 1.0], + [2.0, 1.0, 0.0, 1.0], + [0.0, -1.0, 0.0, 1.0], + ]; + + let actual_pixels = gpu + .render_rgba8_sampled( + &compiled.msl, + ENTRIES, + &POSITIONS, + &uv_coords, + [2, 2], + CLEAR, + Some((&texture, &sampler)), + ) + .expect("draw translated texture sampling pipeline on Apple GPU"); + + // 7. Verify with independent CPU texture sampling reference + let ref_desc = xenora_ref::texture_sampling::Rgba8TextureDesc::new_packed(2, 2, 1) + .expect("valid CPU ref texture desc"); + let test_points = [ + [0.25_f32, 0.25], // pixel (0, 0) + [0.75, 0.25], // pixel (1, 0) + [0.25, 0.75], // pixel (0, 1) + [0.75, 0.75], // pixel (1, 1) + ]; + + let mut expected_pixels = Vec::new(); + for [u, v] in test_points { + let cpu_sample = + xenora_ref::texture_sampling::sample_rgba8_2d(&texels_level0, &ref_desc, 0, u, v) + .expect("CPU reference sampling"); + expected_pixels.extend_from_slice(&cpu_sample); + } + + assert_eq!( + actual_pixels, expected_pixels, + "GPU translated sampling output must bitwise match independent CPU sampling oracle" + ); + + println!( + "device={} verified translated RDNA2 image_sample_lz against independent CPU reference on Apple Silicon GPU", + gpu.device_name() + ); +} diff --git a/crates/shader/src/graphics.rs b/crates/shader/src/graphics.rs index 3e607a35..ce911663 100644 --- a/crates/shader/src/graphics.rs +++ b/crates/shader/src/graphics.rs @@ -40,6 +40,13 @@ enum Op { Constant(u32), Interpolate(u8), Binary(Binary, Value, Value), + SampleLodZero { + u: Value, + v: Value, + component: u8, + texture_index: u8, + sampler_index: u8, + }, } struct Export { @@ -106,6 +113,11 @@ pub fn compile_graphics( }); } + let has_sampling = pixel + .values + .iter() + .any(|(_, op)| matches!(op, Op::SampleLodZero { .. })); + let mut disassembly = String::new(); for (name, instructions) in [("vertex", vertex_decoded), ("pixel", pixel_decoded)] { let _ = writeln!(disassembly, "{name}:"); @@ -135,14 +147,25 @@ pub fn compile_graphics( msl.push_str( " return output;\n}\n\nstruct PixelOutput {\n float4 color [[color(0)]];\n};\n\n", ); - let parameter = if interpolates { - "VertexOutput input [[stage_in]]" + let mut params = Vec::new(); + if interpolates { + params.push("VertexOutput input [[stage_in]]".to_string()); + } + if has_sampling { + params.push("texture2d tex0 [[texture(0)]]".to_string()); + params.push("sampler samp0 [[sampler(0)]]".to_string()); + } + let param_str = params.join(",\n "); + let param_decl = if params.is_empty() { + String::new() + } else if params.len() == 1 { + param_str } else { - "" + format!("\n {param_str}") }; let _ = write!( msl, - "fragment PixelOutput {PIXEL_ENTRY_POINT}({parameter}) {{\n PixelOutput output;\n" + "fragment PixelOutput {PIXEL_ENTRY_POINT}({param_decl}) {{\n PixelOutput output;\n" ); ir.push_str("pixel:\n"); emit_values(&pixel, &mut ir, &mut msl); @@ -242,6 +265,36 @@ fn lift( registers[usize::from(dst)] = Some(ir.push(Some(offset), Op::Interpolate(component))); } + Instruction::ImageSampleLz { + dst, + coord, + resource, + sampler, + } if stage == Stage::Pixel && dst >= 2 && !exporting => { + // In synthetic binding ABI: + // resource s[0:7] maps to texture(0) + // sampler s[8:11] maps to sampler(0) + if (resource, sampler) != (0, 8) { + return Err(error( + "sampling outside synthetic resource binding ABI s[0:7] and s[8:11]", + )); + } + let u = read(coord)?; + let v = read(coord + 1)?; + for component in 0..4 { + let val = ir.push( + Some(offset), + Op::SampleLodZero { + u, + v, + component, + texture_index: 0, + sampler_index: 0, + }, + ); + registers[usize::from(dst + component)] = Some(val); + } + } Instruction::Export { target, sources: [a, b, c, d], @@ -320,6 +373,23 @@ fn emit_values(stage: &StageIr, ir: &mut String, msl: &mut String) { format!("interpolate.center_perspective.f32 attr0[{component}]"), format!("input.parameter[{component}]"), ), + Op::SampleLodZero { + u, + v, + component, + texture_index, + sampler_index, + } => { + let channel = ["r", "g", "b", "a"][usize::from(component)]; + ( + format!( + "sample_lz.2d.f32 tex{texture_index}, samp{sampler_index}, ({u}, {v})[{channel}]" + ), + format!( + "tex{texture_index}.sample(samp{sampler_index}, float2({u}, {v}), level(0.0f)).{channel}" + ), + ) + } }; if let Some(offset) = offset { let _ = write!(ir, "{offset:04x}: "); diff --git a/crates/shader/src/lib.rs b/crates/shader/src/lib.rs index 8135786c..5528cf3c 100644 --- a/crates/shader/src/lib.rs +++ b/crates/shader/src/lib.rs @@ -359,7 +359,9 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result "unsupported resource or buffer index", - Instruction::Export { .. } | Instruction::Interpolate { .. } => { + Instruction::Export { .. } + | Instruction::Interpolate { .. } + | Instruction::ImageSampleLz { .. } => { "graphics instruction is unsupported in a compute fixture" } Instruction::EndProgram if index + 1 != decoded.len() => { @@ -551,7 +553,9 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result { + Instruction::Export { .. } + | Instruction::Interpolate { .. } + | Instruction::ImageSampleLz { .. } => { return Err(error( "graphics instruction is unsupported in a compute fixture", )); diff --git a/crates/shader/tests/graphics.rs b/crates/shader/tests/graphics.rs index d7d995e5..dd1d4c28 100644 --- a/crates/shader/tests/graphics.rs +++ b/crates/shader/tests/graphics.rs @@ -9,6 +9,46 @@ const VARYING_PS: &[u8] = include_bytes!("../../../fixtures/rdna2/x9-varying-ps. const TRANSFORM_VS: &[u8] = include_bytes!("../../../fixtures/rdna2/x9-transform-vs.bin"); const END: &[u8] = &[0x00, 0x00, 0x81, 0xbf]; +#[test] +fn compiles_image_sample_lz_in_pixel_shader_and_emits_msl_texture_sampling() { + // VS: simple passthrough that exports pos0 from v[0:3] and param0 from v[4:7] + let vs_bytes = include_bytes!("../../../fixtures/rdna2/x9-varying-vs.bin"); + + // PS that samples a texture at (u, v) and exports color to mrt0: + // v_interp_p1_f32_e32 v2, v0, attr0.x + // v_interp_p2_f32_e32 v2, v1, attr0.x + // v_interp_p1_f32_e32 v3, v0, attr0.y + // v_interp_p2_f32_e32 v3, v1, attr0.y + // image_sample_lz v[4:7], v[2:3], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + // exp mrt0, v4, v5, v6, v7 done vm + // s_endpgm + let mut ps_bytes = Vec::new(); + // attr0.x interp p1 & p2 + ps_bytes.extend_from_slice(&[0x00, 0x00, 0x08, 0xc8]); // v_interp_p1_f32_e32 v2, v0, attr0.x + ps_bytes.extend_from_slice(&[0x01, 0x00, 0x09, 0xc8]); // v_interp_p2_f32_e32 v2, v1, attr0.x + // attr0.y interp p1 & p2 + ps_bytes.extend_from_slice(&[0x00, 0x01, 0x0c, 0xc8]); // v_interp_p1_f32_e32 v3, v0, attr0.y + ps_bytes.extend_from_slice(&[0x01, 0x01, 0x0d, 0xc8]); // v_interp_p2_f32_e32 v3, v1, attr0.y + // image_sample_lz v[4:7], v[2:3], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D + ps_bytes.extend_from_slice(&[0x08, 0x0f, 0x9c, 0xf0, 0x02, 0x04, 0x40, 0x00]); + // exp mrt0, v4, v5, v6, v7 done vm + ps_bytes.extend_from_slice(&[0x0f, 0x18, 0x00, 0xf8, 0x04, 0x05, 0x06, 0x07]); + // s_endpgm + ps_bytes.extend_from_slice(&[0x00, 0x00, 0x81, 0xbf]); + + let compiled = compile_graphics(Gfx1030, vs_bytes, &ps_bytes) + .expect("compile graphics with texture sampling"); + + assert!(compiled.ir.contains("sample_lz.2d.f32 tex0, samp0")); + assert!( + compiled + .msl + .contains("texture2d tex0 [[texture(0)]]") + ); + assert!(compiled.msl.contains("sampler samp0 [[sampler(0)]]")); + assert!(compiled.msl.contains("tex0.sample(samp0, float2(")); +} + #[test] fn links_constant_and_varying_graphics_fixtures() { let constant = compile_graphics(Gfx1030, CONSTANT_VS, CONSTANT_PS).unwrap();