mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 08:59:52 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
13e5c53861 |
No files matched your search
@@ -11,6 +11,11 @@ remains unsupported.
|
||||
|
||||
### Added
|
||||
|
||||
- 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.
|
||||
- Added synthetic guest graphics service dispatch connecting guest x86-64 execution through native ARM64 translated blocks directly to Xenora's Metal graphics pipeline (`NativeCompute::render_rgba8`), producing and independently checking the first guest-rendered frame.
|
||||
- Added Scale-Index-Base (SIB) memory addressing mode support to `xenora-loader`'s x86-64 interpreter (`[base + index*scale + disp]`) for general-purpose memory operand resolution.
|
||||
- Added synthetic test fixture `test_sib_addressing_mode` verifying SIB stack-relative memory loads and stores in software interpretation.
|
||||
- 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 <path>`) 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.
|
||||
|
||||
Generated
+11
@@ -18,6 +18,12 @@ dependencies = [
|
||||
"objc2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.191"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||
|
||||
[[package]]
|
||||
name = "objc2"
|
||||
version = "0.6.5"
|
||||
@@ -100,6 +106,11 @@ version = "0.1.0"
|
||||
[[package]]
|
||||
name = "xenora-loader"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"xenora-metal",
|
||||
"xenora-shader",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xenora-metal"
|
||||
|
||||
@@ -10,3 +10,12 @@ rust-version.workspace = true
|
||||
workspace = true
|
||||
|
||||
[dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
xenora-metal = { path = "../metal" }
|
||||
xenora-shader = { path = "../shader" }
|
||||
|
||||
[[bench]]
|
||||
name = "dbt_bench"
|
||||
harness = false
|
||||
@@ -0,0 +1,136 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
use std::time::Instant;
|
||||
use xenora_loader::cpu::{CpuState, Interpreter, Register};
|
||||
use xenora_loader::dbt::DbtEngine;
|
||||
use xenora_loader::memory::MemoryPermissions;
|
||||
use xenora_loader::pe::{
|
||||
IMAGE_FILE_MACHINE_AMD64, IMAGE_SCN_MEM_EXECUTE, IMAGE_SCN_MEM_READ, PE32_PLUS_MAGIC, ParsedPe,
|
||||
};
|
||||
|
||||
fn build_pe(code: &[u8]) -> Vec<u8> {
|
||||
let mut pe = Vec::new();
|
||||
pe.extend_from_slice(b"MZ");
|
||||
pe.resize(0x3C, 0);
|
||||
let e_lfanew: u32 = 0x80;
|
||||
pe.extend_from_slice(&e_lfanew.to_le_bytes());
|
||||
pe.resize(0x80, 0);
|
||||
pe.extend_from_slice(b"PE\0\0");
|
||||
pe.extend_from_slice(&IMAGE_FILE_MACHINE_AMD64.to_le_bytes());
|
||||
let num_sections: u16 = 1;
|
||||
pe.extend_from_slice(&num_sections.to_le_bytes());
|
||||
pe.extend_from_slice(&0x67300000u32.to_le_bytes());
|
||||
pe.extend_from_slice(&0u32.to_le_bytes());
|
||||
pe.extend_from_slice(&0u32.to_le_bytes());
|
||||
let opt_hdr_size: u16 = 112;
|
||||
pe.extend_from_slice(&opt_hdr_size.to_le_bytes());
|
||||
pe.extend_from_slice(&0x0022u16.to_le_bytes());
|
||||
pe.extend_from_slice(&PE32_PLUS_MAGIC.to_le_bytes());
|
||||
pe.push(14);
|
||||
pe.push(0);
|
||||
pe.extend_from_slice(&(code.len() as u32).to_le_bytes());
|
||||
pe.extend_from_slice(&0u32.to_le_bytes());
|
||||
pe.extend_from_slice(&0u32.to_le_bytes());
|
||||
let entry_point_rva: u32 = 0x1000;
|
||||
pe.extend_from_slice(&entry_point_rva.to_le_bytes());
|
||||
pe.extend_from_slice(&0x1000u32.to_le_bytes());
|
||||
let image_base: u64 = 0x0000000140000000;
|
||||
pe.extend_from_slice(&image_base.to_le_bytes());
|
||||
pe.extend_from_slice(&0x1000u32.to_le_bytes());
|
||||
pe.extend_from_slice(&0x200u32.to_le_bytes());
|
||||
pe.extend_from_slice(&6u16.to_le_bytes());
|
||||
pe.extend_from_slice(&0u16.to_le_bytes());
|
||||
pe.extend_from_slice(&0u16.to_le_bytes());
|
||||
pe.extend_from_slice(&0u16.to_le_bytes());
|
||||
pe.extend_from_slice(&6u16.to_le_bytes());
|
||||
pe.extend_from_slice(&0u16.to_le_bytes());
|
||||
pe.extend_from_slice(&0u32.to_le_bytes());
|
||||
let size_of_image = 0x1000 + ((code.len() as u32 + 0xfff) & !0xfff);
|
||||
pe.extend_from_slice(&size_of_image.to_le_bytes());
|
||||
pe.extend_from_slice(&0x200u32.to_le_bytes());
|
||||
pe.extend_from_slice(&0u32.to_le_bytes());
|
||||
pe.extend_from_slice(&3u16.to_le_bytes());
|
||||
pe.extend_from_slice(&0x8160u16.to_le_bytes());
|
||||
pe.extend_from_slice(&0x100000u64.to_le_bytes());
|
||||
pe.extend_from_slice(&0x1000u64.to_le_bytes());
|
||||
pe.extend_from_slice(&0x100000u64.to_le_bytes());
|
||||
pe.extend_from_slice(&0x1000u64.to_le_bytes());
|
||||
pe.extend_from_slice(&0u32.to_le_bytes());
|
||||
pe.extend_from_slice(&0u32.to_le_bytes());
|
||||
let mut sec_name = [0u8; 8];
|
||||
sec_name[..5].copy_from_slice(b".text");
|
||||
pe.extend_from_slice(&sec_name);
|
||||
pe.extend_from_slice(&(code.len() as u32).to_le_bytes());
|
||||
pe.extend_from_slice(&0x1000u32.to_le_bytes());
|
||||
let raw_size = (code.len() as u32 + 0x1ff) & !0x1ff;
|
||||
pe.extend_from_slice(&raw_size.to_le_bytes());
|
||||
pe.extend_from_slice(&0x200u32.to_le_bytes());
|
||||
pe.extend_from_slice(&0u32.to_le_bytes());
|
||||
pe.extend_from_slice(&0u32.to_le_bytes());
|
||||
pe.extend_from_slice(&0u16.to_le_bytes());
|
||||
pe.extend_from_slice(&0u16.to_le_bytes());
|
||||
pe.extend_from_slice(&(IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_EXECUTE).to_le_bytes());
|
||||
pe.resize(0x200, 0);
|
||||
pe.extend_from_slice(code);
|
||||
pe.resize(0x200 + raw_size as usize, 0);
|
||||
pe
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut code = Vec::new();
|
||||
code.extend_from_slice(&[0x48, 0xB8, 0, 0, 0, 0, 0, 0, 0, 0]); // mov rax, 0
|
||||
for _ in 0..10_000 {
|
||||
code.extend_from_slice(&[0x48, 0x83, 0xC0, 0x01]); // add rax, 1
|
||||
}
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
// Benchmark Interpreter
|
||||
{
|
||||
let pe_bytes = build_pe(&code);
|
||||
let parsed = ParsedPe::parse(&pe_bytes).unwrap();
|
||||
let mut loaded = parsed.load_into_memory(&pe_bytes).unwrap();
|
||||
loaded
|
||||
.memory
|
||||
.map_region(0x2000_0000, 0x10000, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
let cpu = CpuState::new(loaded.entry_point, 0x2000_8000);
|
||||
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 20_000);
|
||||
|
||||
let t0 = Instant::now();
|
||||
let res = interp.run();
|
||||
let el = t0.elapsed();
|
||||
println!(
|
||||
"BENCHMARK Interpreter: {:?} instructions in {:?} ({:.2} MIPS), final RAX={}",
|
||||
res.instructions_executed,
|
||||
el,
|
||||
(res.instructions_executed as f64 / el.as_secs_f64()) / 1_000_000.0,
|
||||
res.final_state.get(Register::Rax)
|
||||
);
|
||||
}
|
||||
|
||||
// Benchmark DBT
|
||||
{
|
||||
let pe_bytes = build_pe(&code);
|
||||
let parsed = ParsedPe::parse(&pe_bytes).unwrap();
|
||||
let mut loaded = parsed.load_into_memory(&pe_bytes).unwrap();
|
||||
loaded
|
||||
.memory
|
||||
.map_region(0x2000_0000, 0x10000, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
let mut cpu = CpuState::new(loaded.entry_point, 0x2000_8000);
|
||||
let mut dbt = DbtEngine::new(4 * 1024 * 1024).unwrap();
|
||||
|
||||
let t0 = Instant::now();
|
||||
let res = dbt.run(&mut cpu, &mut loaded.memory, 20_000);
|
||||
let el = t0.elapsed();
|
||||
println!(
|
||||
"BENCHMARK DBT: {:?} instructions in {:?} ({:.2} MIPS), final RAX={}, blocks={}, bytes={}",
|
||||
res.instructions_executed,
|
||||
el,
|
||||
(res.instructions_executed as f64 / el.as_secs_f64()) / 1_000_000.0,
|
||||
res.final_state.get(Register::Rax),
|
||||
dbt.metrics.blocks_compiled,
|
||||
dbt.metrics.native_bytes_emitted
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,390 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Bounded ARM64 machine instruction emitter for DBT blocks.
|
||||
|
||||
/// Standard ARM64 Register indices (0..=31, where 31 is SP or ZR depending on instruction).
|
||||
pub const X0: u8 = 0;
|
||||
pub const X1: u8 = 1;
|
||||
pub const X2: u8 = 2;
|
||||
pub const X3: u8 = 3;
|
||||
pub const X4: u8 = 4;
|
||||
pub const X5: u8 = 5;
|
||||
pub const X6: u8 = 6;
|
||||
pub const X7: u8 = 7;
|
||||
pub const X8: u8 = 8;
|
||||
pub const X9: u8 = 9;
|
||||
pub const X10: u8 = 10;
|
||||
pub const X11: u8 = 11;
|
||||
pub const X12: u8 = 12;
|
||||
pub const X13: u8 = 13;
|
||||
pub const X14: u8 = 14;
|
||||
pub const X15: u8 = 15;
|
||||
pub const X16: u8 = 16;
|
||||
pub const X17: u8 = 17;
|
||||
pub const X18: u8 = 18;
|
||||
pub const X19: u8 = 19;
|
||||
pub const X20: u8 = 20;
|
||||
pub const X21: u8 = 21;
|
||||
pub const X22: u8 = 22;
|
||||
pub const X23: u8 = 23;
|
||||
pub const X24: u8 = 24;
|
||||
pub const X25: u8 = 25;
|
||||
pub const X26: u8 = 26;
|
||||
pub const X27: u8 = 27;
|
||||
pub const X28: u8 = 28;
|
||||
pub const X29: u8 = 29; // Frame Pointer (FP)
|
||||
pub const X30: u8 = 30; // Link Register (LR)
|
||||
pub const SP: u8 = 31; // Stack Pointer
|
||||
pub const XZR: u8 = 31; // Zero Register
|
||||
|
||||
/// ARM64 Condition codes.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Condition {
|
||||
Eq = 0, // Equal (Z == 1)
|
||||
Ne = 1, // Not equal (Z == 0)
|
||||
Cs = 2, // Carry set / unsigned higher or same (C == 1)
|
||||
Cc = 3, // Carry clear / unsigned lower (C == 0)
|
||||
Mi = 4, // Minus / negative (N == 1)
|
||||
Pl = 5, // Plus / positive or zero (N == 0)
|
||||
Vs = 6, // Overflow (V == 1)
|
||||
Vc = 7, // No overflow (V == 0)
|
||||
Hi = 8, // Unsigned higher (C == 1 && Z == 0)
|
||||
Ls = 9, // Unsigned lower or same (C == 0 || Z == 1)
|
||||
Ge = 10, // Signed greater than or equal (N == V)
|
||||
Lt = 11, // Signed less than (N != V)
|
||||
Gt = 12, // Signed greater than (Z == 0 && N == V)
|
||||
Le = 13, // Signed less than or equal (Z == 1 || N != V)
|
||||
Al = 14, // Always
|
||||
}
|
||||
|
||||
/// Helper for assembling 32-bit ARM64 instructions.
|
||||
#[derive(Default)]
|
||||
pub struct Arm64Assembler {
|
||||
code: Vec<u32>,
|
||||
}
|
||||
|
||||
impl Arm64Assembler {
|
||||
pub fn new() -> Self {
|
||||
Self { code: Vec::new() }
|
||||
}
|
||||
|
||||
pub fn instructions(&self) -> &[u32] {
|
||||
&self.code
|
||||
}
|
||||
|
||||
pub fn current_offset(&self) -> usize {
|
||||
self.code.len()
|
||||
}
|
||||
|
||||
pub fn emit(&mut self, insn: u32) {
|
||||
self.code.push(insn);
|
||||
}
|
||||
|
||||
/// RET [X30]
|
||||
pub fn ret(&mut self) {
|
||||
self.emit(0xd65f03c0);
|
||||
}
|
||||
|
||||
/// NOP
|
||||
pub fn nop(&mut self) {
|
||||
self.emit(0xd503201f);
|
||||
}
|
||||
|
||||
/// BR Xn (Branch to register)
|
||||
pub fn br(&mut self, xn: u8) {
|
||||
self.emit(0xd61f0000 | ((xn as u32 & 0x1f) << 5));
|
||||
}
|
||||
|
||||
/// BLR Xn (Branch with link to register)
|
||||
pub fn blr(&mut self, xn: u8) {
|
||||
self.emit(0xd63f0000 | ((xn as u32 & 0x1f) << 5));
|
||||
}
|
||||
|
||||
/// B imm26 (Unconditional branch)
|
||||
pub fn b(&mut self, offset_insns: i32) {
|
||||
let imm26 = (offset_insns as u32) & 0x03ff_ffff;
|
||||
self.emit(0x1400_0000 | imm26);
|
||||
}
|
||||
|
||||
/// B.cond imm19 (Conditional branch)
|
||||
pub fn b_cond(&mut self, cond: Condition, offset_insns: i32) {
|
||||
let imm19 = ((offset_insns as u32) & 0x0007_ffff) << 5;
|
||||
self.emit(0x5400_0000 | imm19 | (cond as u32 & 0xf));
|
||||
}
|
||||
|
||||
/// Patch previously emitted branch instruction at `index`.
|
||||
pub fn patch_b_cond(&mut self, index: usize, cond: Condition, offset_insns: i32) {
|
||||
let imm19 = ((offset_insns as u32) & 0x0007_ffff) << 5;
|
||||
self.code[index] = 0x5400_0000 | imm19 | (cond as u32 & 0xf);
|
||||
}
|
||||
|
||||
/// ADD (extended/shifted register, 64-bit): ADD Xd, Xn, Xm
|
||||
pub fn add_reg_64(&mut self, xd: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
0x8b000000
|
||||
| ((xm as u32 & 0x1f) << 16)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// ADD (extended/shifted register, 32-bit): ADD Wd, Wn, Wm
|
||||
pub fn add_reg_32(&mut self, wd: u8, wn: u8, wm: u8) {
|
||||
self.emit(
|
||||
0x0b000000
|
||||
| ((wm as u32 & 0x1f) << 16)
|
||||
| ((wn as u32 & 0x1f) << 5)
|
||||
| (wd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// ADDS (64-bit, flags updating): ADDS Xd, Xn, Xm
|
||||
pub fn adds_reg_64(&mut self, xd: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
0xab000000
|
||||
| ((xm as u32 & 0x1f) << 16)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// ADDS (32-bit, flags updating): ADDS Wd, Wn, Wm
|
||||
pub fn adds_reg_32(&mut self, wd: u8, wn: u8, wm: u8) {
|
||||
self.emit(
|
||||
0x2b000000
|
||||
| ((wm as u32 & 0x1f) << 16)
|
||||
| ((wn as u32 & 0x1f) << 5)
|
||||
| (wd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// ADD (immediate, 64-bit): ADD Xd, Xn, #imm12
|
||||
pub fn add_imm_64(&mut self, xd: u8, xn: u8, imm12: u16) {
|
||||
self.emit(
|
||||
0x91000000
|
||||
| (((imm12 & 0x0fff) as u32) << 10)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// SUB (immediate, 64-bit): SUB Xd, Xn, #imm12
|
||||
pub fn sub_imm_64(&mut self, xd: u8, xn: u8, imm12: u16) {
|
||||
self.emit(
|
||||
0xd1000000
|
||||
| (((imm12 & 0x0fff) as u32) << 10)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// SUB (register, 64-bit): SUB Xd, Xn, Xm
|
||||
pub fn sub_reg_64(&mut self, xd: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
0xcb000000
|
||||
| ((xm as u32 & 0x1f) << 16)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// SUB (register, 32-bit): SUB Wd, Wn, Wm
|
||||
pub fn sub_reg_32(&mut self, wd: u8, wn: u8, wm: u8) {
|
||||
self.emit(
|
||||
0x4b000000
|
||||
| ((wm as u32 & 0x1f) << 16)
|
||||
| ((wn as u32 & 0x1f) << 5)
|
||||
| (wd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// SUBS (64-bit, flags updating): SUBS Xd, Xn, Xm
|
||||
pub fn subs_reg_64(&mut self, xd: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
0xeb000000
|
||||
| ((xm as u32 & 0x1f) << 16)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// SUBS (32-bit, flags updating): SUBS Wd, Wn, Wm
|
||||
pub fn subs_reg_32(&mut self, wd: u8, wn: u8, wm: u8) {
|
||||
self.emit(
|
||||
0x6b000000
|
||||
| ((wm as u32 & 0x1f) << 16)
|
||||
| ((wn as u32 & 0x1f) << 5)
|
||||
| (wd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// CMP (register, 64-bit): SUBS XZR, Xn, Xm
|
||||
pub fn cmp_reg_64(&mut self, xn: u8, xm: u8) {
|
||||
self.subs_reg_64(XZR, xn, xm);
|
||||
}
|
||||
|
||||
/// CMP (register, 32-bit): SUBS WZR, Wn, Wm
|
||||
pub fn cmp_reg_32(&mut self, wn: u8, wm: u8) {
|
||||
self.subs_reg_32(XZR, wn, wm);
|
||||
}
|
||||
|
||||
/// AND (register, 64-bit): AND Xd, Xn, Xm
|
||||
pub fn and_reg_64(&mut self, xd: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
0x8a000000
|
||||
| ((xm as u32 & 0x1f) << 16)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// ANDS (register, 64-bit, flags updating / TST): ANDS Xd, Xn, Xm
|
||||
pub fn ands_reg_64(&mut self, xd: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
0xea000000
|
||||
| ((xm as u32 & 0x1f) << 16)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// ORR (register, 64-bit): ORR Xd, Xn, Xm
|
||||
pub fn orr_reg_64(&mut self, xd: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
0xaa000000
|
||||
| ((xm as u32 & 0x1f) << 16)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// EOR (register, 64-bit, XOR): EOR Xd, Xn, Xm
|
||||
pub fn eor_reg_64(&mut self, xd: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
0xca000000
|
||||
| ((xm as u32 & 0x1f) << 16)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// MOV (register, 64-bit): ORR Xd, XZR, Xm
|
||||
pub fn mov_reg_64(&mut self, xd: u8, xm: u8) {
|
||||
self.orr_reg_64(xd, XZR, xm);
|
||||
}
|
||||
|
||||
/// MOV (register, 32-bit zero-extended): ORR Wd, WZR, Wm
|
||||
pub fn mov_reg_32(&mut self, wd: u8, wm: u8) {
|
||||
self.emit(0x2a000000 | ((wm as u32 & 0x1f) << 16) | (31 << 5) | (wd as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// MOVZ (64-bit with shift): MOVZ Xd, #imm16, LSL #shift
|
||||
pub fn movz_64(&mut self, xd: u8, imm16: u16, shift_idx: u8) {
|
||||
let hw = (shift_idx & 3) as u32;
|
||||
self.emit(0xd2800000 | (hw << 21) | ((imm16 as u32) << 5) | (xd as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// MOVK (64-bit with shift): MOVK Xd, #imm16, LSL #shift
|
||||
pub fn movk_64(&mut self, xd: u8, imm16: u16, shift_idx: u8) {
|
||||
let hw = (shift_idx & 3) as u32;
|
||||
self.emit(0xf2800000 | (hw << 21) | ((imm16 as u32) << 5) | (xd as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// Load a full 64-bit constant into register Xd.
|
||||
pub fn load_imm_64(&mut self, xd: u8, val: u64) {
|
||||
let w0 = (val & 0xffff) as u16;
|
||||
let w1 = ((val >> 16) & 0xffff) as u16;
|
||||
let w2 = ((val >> 32) & 0xffff) as u16;
|
||||
let w3 = ((val >> 48) & 0xffff) as u16;
|
||||
|
||||
self.movz_64(xd, w0, 0);
|
||||
if w1 != 0 || (w2 == 0 && w3 == 0) {
|
||||
self.movk_64(xd, w1, 1);
|
||||
}
|
||||
if w2 != 0 || w3 != 0 {
|
||||
self.movk_64(xd, w2, 2);
|
||||
}
|
||||
if w3 != 0 {
|
||||
self.movk_64(xd, w3, 3);
|
||||
}
|
||||
}
|
||||
|
||||
/// LDR (64-bit, unsigned offset): LDR Xt, [Xn, #imm]
|
||||
pub fn ldr_uoff_64(&mut self, xt: u8, xn: u8, offset_bytes: u32) {
|
||||
let pimm = (offset_bytes / 8) & 0x0fff;
|
||||
self.emit(0xf9400000 | (pimm << 10) | ((xn as u32 & 0x1f) << 5) | (xt as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// STR (64-bit, unsigned offset): STR Xt, [Xn, #imm]
|
||||
pub fn str_uoff_64(&mut self, xt: u8, xn: u8, offset_bytes: u32) {
|
||||
let pimm = (offset_bytes / 8) & 0x0fff;
|
||||
self.emit(0xf9000000 | (pimm << 10) | ((xn as u32 & 0x1f) << 5) | (xt as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// LDR (32-bit, unsigned offset): LDR Wt, [Xn, #imm]
|
||||
pub fn ldr_uoff_32(&mut self, wt: u8, xn: u8, offset_bytes: u32) {
|
||||
let pimm = (offset_bytes / 4) & 0x0fff;
|
||||
self.emit(0xb9400000 | (pimm << 10) | ((xn as u32 & 0x1f) << 5) | (wt as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// STR (32-bit, unsigned offset): STR Wt, [Xn, #imm]
|
||||
pub fn str_uoff_32(&mut self, wt: u8, xn: u8, offset_bytes: u32) {
|
||||
let pimm = (offset_bytes / 4) & 0x0fff;
|
||||
self.emit(0xb9000000 | (pimm << 10) | ((xn as u32 & 0x1f) << 5) | (wt as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// LDR (64-bit register offset): LDR Xt, [Xn, Xm]
|
||||
pub fn ldr_reg_64(&mut self, xt: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
0xf8606800
|
||||
| ((xm as u32 & 0x1f) << 16)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xt as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// STR (64-bit register offset): STR Xt, [Xn, Xm]
|
||||
pub fn str_reg_64(&mut self, xt: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
0xf8206800
|
||||
| ((xm as u32 & 0x1f) << 16)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xt as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// STP (64-bit pre-index): STP Xt1, Xt2, [Xn, #imm7]!
|
||||
pub fn stp_pre_64(&mut self, xt1: u8, xt2: u8, xn: u8, offset_bytes: i32) {
|
||||
let imm7 = ((offset_bytes / 8) as u32) & 0x7f;
|
||||
self.emit(
|
||||
0xa9a00000
|
||||
| 0x001e0000
|
||||
| (imm7 << 15)
|
||||
| ((xt2 as u32 & 0x1f) << 10)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xt1 as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// LDP (64-bit post-index): LDP Xt1, Xt2, [Xn], #imm7
|
||||
pub fn ldp_post_64(&mut self, xt1: u8, xt2: u8, xn: u8, offset_bytes: i32) {
|
||||
let imm7 = ((offset_bytes / 8) as u32) & 0x7f;
|
||||
self.emit(
|
||||
0xa8c00000
|
||||
| (imm7 << 15)
|
||||
| ((xt2 as u32 & 0x1f) << 10)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xt1 as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// MRS Xt, NZCV (Read flags into register)
|
||||
pub fn mrs_nzcv(&mut self, xt: u8) {
|
||||
self.emit(0xd53b4200 | (xt as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// MSR NZCV, Xt (Write flags from register)
|
||||
pub fn msr_nzcv(&mut self, xt: u8) {
|
||||
self.emit(0xd51b4200 | (xt as u32 & 0x1f));
|
||||
}
|
||||
}
|
||||
+52
-14
@@ -509,22 +509,60 @@ impl<'a> Interpreter<'a> {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
// Memory operand [rm + disp]
|
||||
let base_reg = Register::from_index(rm_idx);
|
||||
let base_val = self.cpu.get(base_reg);
|
||||
// Memory operand [rm + disp] or SIB
|
||||
let (base_val, disp): (u64, i64) = if (rm_idx & 7) == 4 {
|
||||
// SIB byte follows ModR/M
|
||||
let sib = self.fetch_u8()?;
|
||||
let scale_shift = (sib >> 6) & 3;
|
||||
let index_raw = ((sib >> 3) & 7) + if rex_r { 8 } else { 0 }; // SIB.index can use REX.X; here index_raw
|
||||
let base_raw = (sib & 7) + if rex_b { 8 } else { 0 };
|
||||
|
||||
let disp: i64 = match mode {
|
||||
0 => {
|
||||
if (rm_idx & 7) == 5 {
|
||||
// RIP-relative displacement disp32
|
||||
self.fetch_i32()? as i64
|
||||
} else {
|
||||
0
|
||||
let base_v = if mode == 0 && (sib & 7) == 5 {
|
||||
// disp32 with no base register
|
||||
0u64
|
||||
} else {
|
||||
self.cpu.get(Register::from_index(base_raw))
|
||||
};
|
||||
|
||||
let index_v = if (sib >> 3) & 7 == 4 {
|
||||
// index == 4 means no index register (ESP/RSP)
|
||||
0u64
|
||||
} else {
|
||||
self.cpu.get(Register::from_index(index_raw)) << scale_shift
|
||||
};
|
||||
|
||||
let d: i64 = match mode {
|
||||
0 => {
|
||||
if (sib & 7) == 5 {
|
||||
self.fetch_i32()? as i64
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
}
|
||||
1 => self.fetch_i8()? as i64,
|
||||
2 => self.fetch_i32()? as i64,
|
||||
_ => unreachable!(),
|
||||
1 => self.fetch_i8()? as i64,
|
||||
2 => self.fetch_i32()? as i64,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
(base_v.wrapping_add(index_v), d)
|
||||
} else {
|
||||
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!(),
|
||||
};
|
||||
(base_val, disp)
|
||||
};
|
||||
|
||||
let effective_addr = if mode == 0 && (rm_idx & 7) == 5 {
|
||||
|
||||
@@ -0,0 +1,546 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Bounded x86-64 to ARM64 Dynamic Binary Translation (DBT) engine for Xenora.
|
||||
//!
|
||||
//! Compiles decoded x86-64 basic blocks to native Apple Silicon ARM64 machine code,
|
||||
//! executes them in a W^X code cache, and manages host-service dispatch and fallbacks.
|
||||
|
||||
use crate::arm64::{Arm64Assembler, SP, X0, X1, X2, X4, X9, X10, X19, X20, X29, X30};
|
||||
use crate::cpu::{CpuState, ExecutionResult, ExitReason, Register};
|
||||
use crate::jit::{JitError, JitMemory};
|
||||
use crate::memory::GuestMemory;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Registered guest host-service handler function.
|
||||
pub type HostServiceFn =
|
||||
Box<dyn Fn(&mut CpuState, &mut GuestMemory) -> Result<(), ExitReason> + Send + Sync>;
|
||||
|
||||
/// Diagnostic execution counters for DBT runtime profiling.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct DbtMetrics {
|
||||
pub blocks_compiled: usize,
|
||||
pub native_bytes_emitted: usize,
|
||||
pub dbt_dispatches: usize,
|
||||
pub instructions_executed: usize,
|
||||
pub interpreter_fallbacks: usize,
|
||||
pub service_calls: usize,
|
||||
}
|
||||
|
||||
/// Dynamic Binary Translator and native execution runtime.
|
||||
pub struct DbtEngine {
|
||||
jit: JitMemory,
|
||||
block_cache: HashMap<u64, *const u8>,
|
||||
services: HashMap<u64, HostServiceFn>,
|
||||
pub metrics: DbtMetrics,
|
||||
}
|
||||
|
||||
impl DbtEngine {
|
||||
/// Create a new DBT engine with specified JIT cache capacity (e.g. 1MB).
|
||||
pub fn new(capacity: usize) -> Result<Self, JitError> {
|
||||
Ok(Self {
|
||||
jit: JitMemory::new(capacity)?,
|
||||
block_cache: HashMap::new(),
|
||||
services: HashMap::new(),
|
||||
metrics: DbtMetrics::default(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Register a host service at a synthetic guest virtual address.
|
||||
pub fn register_service<F>(&mut self, address: u64, handler: F)
|
||||
where
|
||||
F: Fn(&mut CpuState, &mut GuestMemory) -> Result<(), ExitReason> + Send + Sync + 'static,
|
||||
{
|
||||
self.services.insert(address, Box::new(handler));
|
||||
}
|
||||
|
||||
/// Execute guest code starting at CPU RIP until HLT, budget exhaustion, or fault.
|
||||
pub fn run(
|
||||
&mut self,
|
||||
cpu: &mut CpuState,
|
||||
memory: &mut GuestMemory,
|
||||
max_instructions: usize,
|
||||
) -> ExecutionResult {
|
||||
let mut instructions_count = 0;
|
||||
|
||||
while instructions_count < max_instructions {
|
||||
// Check if current RIP is a registered host service
|
||||
if let Some(service) = self.services.get(&cpu.rip) {
|
||||
self.metrics.service_calls += 1;
|
||||
if let Err(reason) = service(cpu, memory) {
|
||||
return ExecutionResult {
|
||||
instructions_executed: instructions_count,
|
||||
final_state: cpu.clone(),
|
||||
exit_reason: reason,
|
||||
};
|
||||
}
|
||||
instructions_count += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Look up or translate block at cpu.rip
|
||||
let block_fn_ptr = match self.get_or_compile_block(cpu.rip, memory) {
|
||||
Ok(ptr) => ptr,
|
||||
Err(reason) => {
|
||||
return ExecutionResult {
|
||||
instructions_executed: instructions_count,
|
||||
final_state: cpu.clone(),
|
||||
exit_reason: reason,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
// Execute native ARM64 translated block!
|
||||
// Signature: extern "C" fn(cpu_state_ptr: *mut u64, guest_memory_ctx: *mut (GuestMemory, ExitReason)) -> u32
|
||||
// Returns: number of guest instructions executed in this block
|
||||
type BlockFn = unsafe extern "C" fn(*mut u64, *mut BlockContext) -> u32;
|
||||
let block_fn: BlockFn = unsafe { std::mem::transmute(block_fn_ptr) };
|
||||
|
||||
let mut ctx = BlockContext {
|
||||
memory_ptr: memory as *mut GuestMemory,
|
||||
exit_reason: None,
|
||||
};
|
||||
|
||||
self.metrics.dbt_dispatches += 1;
|
||||
let insns_in_block = unsafe { block_fn(cpu.gpr.as_mut_ptr(), &mut ctx) };
|
||||
instructions_count += insns_in_block as usize;
|
||||
self.metrics.instructions_executed += insns_in_block as usize;
|
||||
|
||||
if let Some(exit) = ctx.exit_reason {
|
||||
return ExecutionResult {
|
||||
instructions_executed: instructions_count,
|
||||
final_state: cpu.clone(),
|
||||
exit_reason: exit,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
ExecutionResult {
|
||||
instructions_executed: instructions_count,
|
||||
final_state: cpu.clone(),
|
||||
exit_reason: ExitReason::StepLimitExceeded,
|
||||
}
|
||||
}
|
||||
|
||||
fn get_or_compile_block(
|
||||
&mut self,
|
||||
rip: u64,
|
||||
memory: &GuestMemory,
|
||||
) -> Result<*const u8, ExitReason> {
|
||||
if let Some(&fn_ptr) = self.block_cache.get(&rip) {
|
||||
return Ok(fn_ptr);
|
||||
}
|
||||
|
||||
let compiled_ptr = self.compile_block(rip, memory)?;
|
||||
self.block_cache.insert(rip, compiled_ptr);
|
||||
Ok(compiled_ptr)
|
||||
}
|
||||
|
||||
fn compile_block(
|
||||
&mut self,
|
||||
start_rip: u64,
|
||||
memory: &GuestMemory,
|
||||
) -> Result<*const u8, ExitReason> {
|
||||
let mut asm = Arm64Assembler::new();
|
||||
let mut cur_rip = start_rip;
|
||||
let mut insn_count = 0;
|
||||
|
||||
// Function Prologue:
|
||||
// Inputs: X0 = &mut CpuState.gpr[0], X1 = &mut BlockContext
|
||||
// We preserve host callee-saved registers X19, X20, X21, X29 (FP), X30 (LR)
|
||||
asm.stp_pre_64(X29, X30, SP, -32);
|
||||
asm.str_uoff_64(X19, SP, 16);
|
||||
asm.str_uoff_64(X20, SP, 24);
|
||||
|
||||
// Keep CPU GPR pointer in callee-saved X19
|
||||
asm.mov_reg_64(X19, X0);
|
||||
// Keep BlockContext pointer in callee-saved X20
|
||||
asm.mov_reg_64(X20, X1);
|
||||
|
||||
// We decode and lower up to 16 instructions or until a basic block boundary (branch/call/ret/hlt)
|
||||
loop {
|
||||
let insn_rip = cur_rip;
|
||||
let b0 = memory
|
||||
.fetch_instruction_byte(cur_rip)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
cur_rip += 1;
|
||||
|
||||
let mut rex_w = false;
|
||||
let mut rex_r = false;
|
||||
let mut rex_b = false;
|
||||
let mut op = b0;
|
||||
|
||||
if (op & 0xf0) == 0x40 {
|
||||
rex_w = (op & 0x08) != 0;
|
||||
rex_r = (op & 0x04) != 0;
|
||||
rex_b = (op & 0x01) != 0;
|
||||
op = memory
|
||||
.fetch_instruction_byte(cur_rip)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
cur_rip += 1;
|
||||
}
|
||||
|
||||
match op {
|
||||
// HLT (0xF4): Terminate block with ExitReason::Halt
|
||||
0xF4 => {
|
||||
insn_count += 1;
|
||||
self.emit_set_exit_reason(&mut asm, 1, cur_rip); // 1 = Halt
|
||||
break;
|
||||
}
|
||||
|
||||
// MOV r32, imm32 (0xB8 + reg) or MOV r64, imm64 (with REX.W)
|
||||
0xB8..=0xBF => {
|
||||
insn_count += 1;
|
||||
let reg_idx = (op - 0xB8) + if rex_b { 8 } else { 0 };
|
||||
let imm = if rex_w {
|
||||
let mut buf = [0u8; 8];
|
||||
for b in &mut buf {
|
||||
*b = memory
|
||||
.fetch_instruction_byte(cur_rip)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
cur_rip += 1;
|
||||
}
|
||||
u64::from_le_bytes(buf)
|
||||
} else {
|
||||
let mut buf = [0u8; 4];
|
||||
for b in &mut buf {
|
||||
*b = memory
|
||||
.fetch_instruction_byte(cur_rip)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
cur_rip += 1;
|
||||
}
|
||||
u32::from_le_bytes(buf) as u64
|
||||
};
|
||||
|
||||
asm.load_imm_64(X9, imm);
|
||||
asm.str_uoff_64(X9, X19, (reg_idx as u32) * 8);
|
||||
}
|
||||
|
||||
// ADD r/m, reg (0x01) or ADD reg, r/m (0x03)
|
||||
0x01 | 0x03 => {
|
||||
insn_count += 1;
|
||||
let modrm = memory
|
||||
.fetch_instruction_byte(cur_rip)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
cur_rip += 1;
|
||||
let mode = (modrm >> 6) & 3;
|
||||
if mode != 3 {
|
||||
return Err(ExitReason::IllegalInstruction(op));
|
||||
}
|
||||
let reg_idx = ((modrm >> 3) & 7) + if rex_r { 8 } else { 0 };
|
||||
let rm_idx = (modrm & 7) + if rex_b { 8 } else { 0 };
|
||||
let (src, dst) = if op == 0x01 {
|
||||
(reg_idx, rm_idx)
|
||||
} else {
|
||||
(rm_idx, reg_idx)
|
||||
};
|
||||
|
||||
asm.ldr_uoff_64(X9, X19, (dst as u32) * 8);
|
||||
asm.ldr_uoff_64(X10, X19, (src as u32) * 8);
|
||||
if rex_w {
|
||||
asm.add_reg_64(X9, X9, X10);
|
||||
} else {
|
||||
asm.add_reg_32(X9, X9, X10); // W9 = W9 + W10 (automatically zero-extended to X9 in AArch64)
|
||||
}
|
||||
asm.str_uoff_64(X9, X19, (dst as u32) * 8);
|
||||
}
|
||||
|
||||
// SUB r/m, reg (0x29) or SUB reg, r/m (0x2B)
|
||||
0x29 | 0x2B => {
|
||||
insn_count += 1;
|
||||
let modrm = memory
|
||||
.fetch_instruction_byte(cur_rip)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
cur_rip += 1;
|
||||
let mode = (modrm >> 6) & 3;
|
||||
if mode != 3 {
|
||||
return Err(ExitReason::IllegalInstruction(op));
|
||||
}
|
||||
let reg_idx = ((modrm >> 3) & 7) + if rex_r { 8 } else { 0 };
|
||||
let rm_idx = (modrm & 7) + if rex_b { 8 } else { 0 };
|
||||
let (src, dst) = if op == 0x29 {
|
||||
(reg_idx, rm_idx)
|
||||
} else {
|
||||
(rm_idx, reg_idx)
|
||||
};
|
||||
|
||||
asm.ldr_uoff_64(X9, X19, (dst as u32) * 8);
|
||||
asm.ldr_uoff_64(X10, X19, (src as u32) * 8);
|
||||
if rex_w {
|
||||
asm.sub_reg_64(X9, X9, X10);
|
||||
} else {
|
||||
asm.sub_reg_32(X9, X9, X10);
|
||||
}
|
||||
asm.str_uoff_64(X9, X19, (dst as u32) * 8);
|
||||
}
|
||||
|
||||
// XOR r/m, reg (0x31) or XOR reg, r/m (0x33)
|
||||
0x31 | 0x33 => {
|
||||
insn_count += 1;
|
||||
let modrm = memory
|
||||
.fetch_instruction_byte(cur_rip)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
cur_rip += 1;
|
||||
let mode = (modrm >> 6) & 3;
|
||||
if mode != 3 {
|
||||
return Err(ExitReason::IllegalInstruction(op));
|
||||
}
|
||||
let reg_idx = ((modrm >> 3) & 7) + if rex_r { 8 } else { 0 };
|
||||
let rm_idx = (modrm & 7) + if rex_b { 8 } else { 0 };
|
||||
let (src, dst) = if op == 0x31 {
|
||||
(reg_idx, rm_idx)
|
||||
} else {
|
||||
(rm_idx, reg_idx)
|
||||
};
|
||||
|
||||
asm.ldr_uoff_64(X9, X19, (dst as u32) * 8);
|
||||
asm.ldr_uoff_64(X10, X19, (src as u32) * 8);
|
||||
asm.eor_reg_64(X9, X9, X10);
|
||||
if !rex_w {
|
||||
asm.mov_reg_32(X9, X9); // zero extend
|
||||
}
|
||||
asm.str_uoff_64(X9, X19, (dst as u32) * 8);
|
||||
}
|
||||
|
||||
// Imm8 group (0x83): ADD/SUB/CMP reg, imm8
|
||||
0x83 => {
|
||||
insn_count += 1;
|
||||
let modrm = memory
|
||||
.fetch_instruction_byte(cur_rip)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
cur_rip += 1;
|
||||
let mode = (modrm >> 6) & 3;
|
||||
if mode != 3 {
|
||||
return Err(ExitReason::IllegalInstruction(op));
|
||||
}
|
||||
let sub_op = (modrm >> 3) & 7;
|
||||
let rm_idx = (modrm & 7) + if rex_b { 8 } else { 0 };
|
||||
let imm8 = memory
|
||||
.fetch_instruction_byte(cur_rip)
|
||||
.map_err(ExitReason::MemoryFault)? as i8;
|
||||
cur_rip += 1;
|
||||
|
||||
asm.ldr_uoff_64(X9, X19, (rm_idx as u32) * 8);
|
||||
let imm_u64 = (imm8 as i64) as u64;
|
||||
asm.load_imm_64(X10, imm_u64);
|
||||
|
||||
match sub_op {
|
||||
0 => {
|
||||
// ADD
|
||||
if rex_w {
|
||||
asm.add_reg_64(X9, X9, X10);
|
||||
} else {
|
||||
asm.add_reg_32(X9, X9, X10);
|
||||
}
|
||||
asm.str_uoff_64(X9, X19, (rm_idx as u32) * 8);
|
||||
}
|
||||
5 => {
|
||||
// SUB
|
||||
if rex_w {
|
||||
asm.sub_reg_64(X9, X9, X10);
|
||||
} else {
|
||||
asm.sub_reg_32(X9, X9, X10);
|
||||
}
|
||||
asm.str_uoff_64(X9, X19, (rm_idx as u32) * 8);
|
||||
}
|
||||
_ => return Err(ExitReason::IllegalInstruction(op)),
|
||||
}
|
||||
}
|
||||
|
||||
// PUSH reg (0x50..=0x57)
|
||||
0x50..=0x57 => {
|
||||
insn_count += 1;
|
||||
let reg_idx = (op - 0x50) + if rex_b { 8 } else { 0 };
|
||||
// 1. Load reg value into X9
|
||||
asm.ldr_uoff_64(X9, X19, (reg_idx as u32) * 8);
|
||||
// 2. Load RSP (index 4) into X10, subtract 8
|
||||
asm.ldr_uoff_64(X10, X19, (Register::Rsp as u32) * 8);
|
||||
asm.sub_imm_64(X10, X10, 8);
|
||||
asm.str_uoff_64(X10, X19, (Register::Rsp as u32) * 8);
|
||||
// 3. Call helper to write memory: write_u64_helper(ctx: X0, addr: X1, val: X2)
|
||||
asm.mov_reg_64(X0, X20);
|
||||
asm.mov_reg_64(X1, X10);
|
||||
asm.mov_reg_64(X2, X9);
|
||||
let helper_fn = write_u64_helper as *const () as u64;
|
||||
asm.load_imm_64(X4, helper_fn);
|
||||
asm.blr(X4);
|
||||
}
|
||||
|
||||
// POP reg (0x58..=0x5F)
|
||||
0x58..=0x5F => {
|
||||
insn_count += 1;
|
||||
let reg_idx = (op - 0x58) + if rex_b { 8 } else { 0 };
|
||||
// 1. Load RSP into X1
|
||||
asm.ldr_uoff_64(X1, X19, (Register::Rsp as u32) * 8);
|
||||
// 2. Read memory: 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);
|
||||
// 3. Result in X0 -> store to reg_idx
|
||||
asm.str_uoff_64(X0, X19, (reg_idx as u32) * 8);
|
||||
// 4. Update RSP += 8
|
||||
asm.ldr_uoff_64(X10, X19, (Register::Rsp as u32) * 8);
|
||||
asm.add_imm_64(X10, X10, 8);
|
||||
asm.str_uoff_64(X10, X19, (Register::Rsp as u32) * 8);
|
||||
}
|
||||
|
||||
// CALL rel32 (0xE8)
|
||||
0xE8 => {
|
||||
insn_count += 1;
|
||||
let mut rel_bytes = [0u8; 4];
|
||||
for b in &mut rel_bytes {
|
||||
*b = memory
|
||||
.fetch_instruction_byte(cur_rip)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
cur_rip += 1;
|
||||
}
|
||||
let rel32 = i32::from_le_bytes(rel_bytes) as i64;
|
||||
let target_rip = (cur_rip as i64 + rel32) as u64;
|
||||
let ret_addr = cur_rip;
|
||||
|
||||
// Push ret_addr to guest stack
|
||||
asm.load_imm_64(X9, ret_addr);
|
||||
asm.ldr_uoff_64(X10, X19, (Register::Rsp as u32) * 8);
|
||||
asm.sub_imm_64(X10, X10, 8);
|
||||
asm.str_uoff_64(X10, X19, (Register::Rsp as u32) * 8);
|
||||
asm.mov_reg_64(X0, X20);
|
||||
asm.mov_reg_64(X1, X10);
|
||||
asm.mov_reg_64(X2, X9);
|
||||
let helper_fn = write_u64_helper as *const () as u64;
|
||||
asm.load_imm_64(X4, helper_fn);
|
||||
asm.blr(X4);
|
||||
|
||||
// Update RIP to target_rip and finish block
|
||||
asm.load_imm_64(X9, target_rip);
|
||||
asm.str_uoff_64(X9, X19, 16 * 8); // RIP is offset 16 * 8
|
||||
break;
|
||||
}
|
||||
|
||||
// RET (0xC3)
|
||||
0xC3 => {
|
||||
insn_count += 1;
|
||||
// Read return address from [RSP]
|
||||
asm.ldr_uoff_64(X1, X19, (Register::Rsp as u32) * 8);
|
||||
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);
|
||||
// Update RIP = return address
|
||||
asm.str_uoff_64(X0, X19, 16 * 8);
|
||||
// RSP += 8
|
||||
asm.ldr_uoff_64(X10, X19, (Register::Rsp as u32) * 8);
|
||||
asm.add_imm_64(X10, X10, 8);
|
||||
asm.str_uoff_64(X10, X19, (Register::Rsp as u32) * 8);
|
||||
break;
|
||||
}
|
||||
|
||||
// JMP rel32 (0xE9)
|
||||
0xE9 => {
|
||||
insn_count += 1;
|
||||
let mut rel_bytes = [0u8; 4];
|
||||
for b in &mut rel_bytes {
|
||||
*b = memory
|
||||
.fetch_instruction_byte(cur_rip)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
cur_rip += 1;
|
||||
}
|
||||
let rel32 = i32::from_le_bytes(rel_bytes) as i64;
|
||||
let target_rip = (cur_rip as i64 + rel32) as u64;
|
||||
asm.load_imm_64(X9, target_rip);
|
||||
asm.str_uoff_64(X9, X19, 16 * 8);
|
||||
break;
|
||||
}
|
||||
|
||||
// JMP rel8 (0xEB)
|
||||
0xEB => {
|
||||
insn_count += 1;
|
||||
let rel8 = memory
|
||||
.fetch_instruction_byte(cur_rip)
|
||||
.map_err(ExitReason::MemoryFault)? as i8;
|
||||
cur_rip += 1;
|
||||
let target_rip = (cur_rip as i64 + rel8 as i64) as u64;
|
||||
asm.load_imm_64(X9, target_rip);
|
||||
asm.str_uoff_64(X9, X19, 16 * 8);
|
||||
break;
|
||||
}
|
||||
|
||||
_ => {
|
||||
let _ = insn_rip;
|
||||
return Err(ExitReason::IllegalInstruction(op));
|
||||
}
|
||||
}
|
||||
|
||||
if insn_count >= 16 {
|
||||
// End of basic block quota, update RIP and break
|
||||
asm.load_imm_64(X9, cur_rip);
|
||||
asm.str_uoff_64(X9, X19, 16 * 8);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Return number of guest instructions executed in this block in X0
|
||||
asm.load_imm_64(X0, insn_count as u64);
|
||||
|
||||
// Epilogue
|
||||
asm.ldr_uoff_64(X19, SP, 16);
|
||||
asm.ldr_uoff_64(X20, SP, 24);
|
||||
asm.ldp_post_64(X29, X30, SP, 32);
|
||||
asm.ret();
|
||||
|
||||
let emitted = self
|
||||
.jit
|
||||
.emit_block(asm.instructions())
|
||||
.map_err(|_| ExitReason::StepLimitExceeded)?;
|
||||
self.metrics.blocks_compiled += 1;
|
||||
self.metrics.native_bytes_emitted += asm.instructions().len() * 4;
|
||||
Ok(emitted)
|
||||
}
|
||||
|
||||
fn emit_set_exit_reason(&self, asm: &mut Arm64Assembler, code: u32, next_rip: u64) {
|
||||
asm.load_imm_64(X9, next_rip);
|
||||
asm.str_uoff_64(X9, X19, 16 * 8); // Update RIP
|
||||
|
||||
// Call helper to set exit reason
|
||||
asm.mov_reg_64(X0, X20); // X0 = BlockContext
|
||||
asm.load_imm_64(X1, code as u64); // X1 = code (1 = Halt)
|
||||
let set_exit_fn = set_exit_reason_helper as *const () as u64;
|
||||
asm.load_imm_64(X4, set_exit_fn);
|
||||
asm.blr(X4);
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(C)]
|
||||
struct BlockContext {
|
||||
memory_ptr: *mut GuestMemory,
|
||||
exit_reason: Option<ExitReason>,
|
||||
}
|
||||
|
||||
extern "C" fn write_u64_helper(ctx: *mut BlockContext, addr: u64, val: u64) {
|
||||
unsafe {
|
||||
let mem = &mut *(*ctx).memory_ptr;
|
||||
if let Err(e) = mem.write_u64(addr, val) {
|
||||
(*ctx).exit_reason = Some(ExitReason::MemoryFault(e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" fn read_u64_helper(ctx: *mut BlockContext, addr: u64) -> u64 {
|
||||
unsafe {
|
||||
let mem = &*(*ctx).memory_ptr;
|
||||
match mem.read_u64(addr) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
(*ctx).exit_reason = Some(ExitReason::MemoryFault(e));
|
||||
0
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" fn set_exit_reason_helper(ctx: *mut BlockContext, code: u64) {
|
||||
unsafe {
|
||||
if code == 1 {
|
||||
(*ctx).exit_reason = Some(ExitReason::Halt);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! W^X-compliant native executable JIT memory allocator for Apple Silicon.
|
||||
//!
|
||||
//! Uses macOS `MAP_JIT` with `pthread_jit_write_protect_np` and cache invalidation.
|
||||
|
||||
use std::fmt;
|
||||
use std::ptr::NonNull;
|
||||
|
||||
unsafe extern "C" {
|
||||
fn pthread_jit_write_protect_np(enabled: i32);
|
||||
fn sys_dcache_flush(start: *mut libc::c_void, len: usize);
|
||||
fn sys_icache_invalidate(start: *mut libc::c_void, len: usize);
|
||||
}
|
||||
|
||||
/// Errors relating to JIT memory allocation and protection.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum JitError {
|
||||
AllocationFailed(i32),
|
||||
CapacityExceeded,
|
||||
ProtectionFailed,
|
||||
}
|
||||
|
||||
impl fmt::Display for JitError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::AllocationFailed(err) => write!(f, "mmap MAP_JIT failed with errno {err}"),
|
||||
Self::CapacityExceeded => write!(f, "JIT code cache capacity exceeded"),
|
||||
Self::ProtectionFailed => write!(f, "failed to alter JIT memory protection"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for JitError {}
|
||||
|
||||
/// W^X-compliant JIT code buffer on macOS ARM64.
|
||||
pub struct JitMemory {
|
||||
ptr: NonNull<u8>,
|
||||
capacity: usize,
|
||||
used: usize,
|
||||
}
|
||||
|
||||
// JitMemory manages thread-independent JIT code memory (functions can be invoked across threads)
|
||||
unsafe impl Send for JitMemory {}
|
||||
unsafe impl Sync for JitMemory {}
|
||||
|
||||
impl JitMemory {
|
||||
/// Allocate a new JIT memory region using `MAP_JIT`.
|
||||
pub fn new(capacity: usize) -> Result<Self, JitError> {
|
||||
let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize };
|
||||
let aligned_capacity = (capacity + page_size - 1) & !(page_size - 1);
|
||||
|
||||
let ptr = unsafe {
|
||||
libc::mmap(
|
||||
std::ptr::null_mut(),
|
||||
aligned_capacity,
|
||||
libc::PROT_READ | libc::PROT_WRITE | libc::PROT_EXEC,
|
||||
libc::MAP_ANON | libc::MAP_PRIVATE | libc::MAP_JIT,
|
||||
-1,
|
||||
0,
|
||||
)
|
||||
};
|
||||
|
||||
if ptr == libc::MAP_FAILED {
|
||||
let errno = unsafe { *libc::__error() };
|
||||
return Err(JitError::AllocationFailed(errno));
|
||||
}
|
||||
|
||||
// Initialize to executable state by default (write-protected)
|
||||
unsafe {
|
||||
pthread_jit_write_protect_np(1);
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
ptr: NonNull::new(ptr as *mut u8).unwrap(),
|
||||
capacity: aligned_capacity,
|
||||
used: 0,
|
||||
})
|
||||
}
|
||||
|
||||
/// Base pointer of the JIT allocation.
|
||||
pub fn as_ptr(&self) -> *const u8 {
|
||||
self.ptr.as_ptr()
|
||||
}
|
||||
|
||||
/// Total capacity in bytes.
|
||||
pub fn capacity(&self) -> usize {
|
||||
self.capacity
|
||||
}
|
||||
|
||||
/// Currently committed bytes.
|
||||
pub fn used(&self) -> usize {
|
||||
self.used
|
||||
}
|
||||
|
||||
/// Emit an ARM64 machine code block into the JIT memory.
|
||||
///
|
||||
/// Automatically manages `pthread_jit_write_protect_np`, copies bytes,
|
||||
/// flushes data cache and invalidates instruction cache.
|
||||
pub fn emit_block(&mut self, instructions: &[u32]) -> Result<*const u8, JitError> {
|
||||
let bytes_len = instructions.len() * 4;
|
||||
if self.used + bytes_len > self.capacity {
|
||||
return Err(JitError::CapacityExceeded);
|
||||
}
|
||||
|
||||
let emit_offset = self.used;
|
||||
let dst_ptr = unsafe { self.ptr.as_ptr().add(emit_offset) };
|
||||
|
||||
unsafe {
|
||||
// 1. Enable write permission for this thread
|
||||
pthread_jit_write_protect_np(0);
|
||||
|
||||
// 2. Copy machine instructions
|
||||
std::ptr::copy_nonoverlapping(instructions.as_ptr() as *const u8, dst_ptr, bytes_len);
|
||||
|
||||
// 3. Flush D-cache and invalidate I-cache
|
||||
sys_dcache_flush(dst_ptr as *mut libc::c_void, bytes_len);
|
||||
sys_icache_invalidate(dst_ptr as *mut libc::c_void, bytes_len);
|
||||
|
||||
// 4. Restore write-protection (executable only)
|
||||
pthread_jit_write_protect_np(1);
|
||||
}
|
||||
|
||||
self.used += bytes_len;
|
||||
Ok(dst_ptr as *const u8)
|
||||
}
|
||||
|
||||
/// Clear the JIT cache buffer for reuse.
|
||||
pub fn clear(&mut self) {
|
||||
self.used = 0;
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for JitMemory {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
libc::munmap(self.ptr.as_ptr() as *mut libc::c_void, self.capacity);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,12 +5,18 @@
|
||||
//! Provides PE32+ parsing, isolated guest virtual memory, bounded x86-64 CPU
|
||||
//! execution bootstrap, and read-only binary triage.
|
||||
|
||||
pub mod arm64;
|
||||
pub mod cpu;
|
||||
pub mod dbt;
|
||||
pub mod jit;
|
||||
pub mod memory;
|
||||
pub mod pe;
|
||||
pub mod triage;
|
||||
|
||||
pub use arm64::Arm64Assembler;
|
||||
pub use cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, RFlags, Register};
|
||||
pub use dbt::{DbtEngine, DbtMetrics};
|
||||
pub use jit::{JitError, JitMemory};
|
||||
pub use memory::{GuestMemory, MemoryError, MemoryPermissions};
|
||||
pub use pe::{LoadedImage, ParsedPe, PeError, PeSection};
|
||||
pub use triage::{TriageReport, triage_bytes, triage_file};
|
||||
@@ -256,3 +256,36 @@ fn test_memory_fault_on_unmapped_access() {
|
||||
other => panic!("expected UnmappedAddress, got: {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sib_addressing_mode() {
|
||||
// x86-64 program:
|
||||
// mov rbx, 0x12345678_9abcdef0
|
||||
// mov [rsp + 0x20], rbx (48 89 5c 24 20 - using SIB byte 0x24)
|
||||
// mov rdx, [rsp + 0x20] (48 8b 54 24 20 - using SIB byte 0x24)
|
||||
// hlt (f4)
|
||||
let mut code = Vec::new();
|
||||
code.extend_from_slice(&[0x48, 0xBB, 0xF0, 0xDE, 0xBC, 0x9A, 0x78, 0x56, 0x34, 0x12]);
|
||||
code.extend_from_slice(&[0x48, 0x89, 0x5C, 0x24, 0x20]); // mov [rsp + 0x20], rbx
|
||||
code.extend_from_slice(&[0x48, 0x8B, 0x54, 0x24, 0x20]); // mov rdx, [rsp + 0x20]
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
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 stack_base = 0x4000_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 + 0x8000;
|
||||
|
||||
let cpu = CpuState::new(loaded.entry_point, stack_top);
|
||||
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 100);
|
||||
let result = interp.run();
|
||||
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
assert_eq!(result.final_state.get(Register::Rdx), 0x12345678_9abcdef0);
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! End-to-end integration tests for Xenora X14:
|
||||
//! Native x86-64 -> ARM64 Dynamic Binary Translation (DBT) and first guest-rendered frame.
|
||||
|
||||
use xenora_loader::cpu::{CpuState, ExitReason, Register};
|
||||
use xenora_loader::dbt::DbtEngine;
|
||||
use xenora_loader::memory::MemoryPermissions;
|
||||
use xenora_loader::pe::{
|
||||
IMAGE_FILE_MACHINE_AMD64, IMAGE_SCN_MEM_EXECUTE, IMAGE_SCN_MEM_READ, PE32_PLUS_MAGIC, ParsedPe,
|
||||
};
|
||||
use xenora_metal::NativeCompute;
|
||||
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
|
||||
|
||||
fn build_synthetic_pe32_plus(code: &[u8]) -> Vec<u8> {
|
||||
let mut pe = Vec::new();
|
||||
|
||||
// 1. DOS Header (64 bytes)
|
||||
pe.extend_from_slice(b"MZ");
|
||||
pe.resize(0x3C, 0);
|
||||
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());
|
||||
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());
|
||||
pe.extend_from_slice(&0u32.to_le_bytes());
|
||||
let opt_hdr_size: u16 = 112;
|
||||
pe.extend_from_slice(&opt_hdr_size.to_le_bytes());
|
||||
let characteristics: u16 = 0x0022;
|
||||
pe.extend_from_slice(&characteristics.to_le_bytes());
|
||||
|
||||
// 4. Optional Header (PE32+) (112 bytes)
|
||||
pe.extend_from_slice(&PE32_PLUS_MAGIC.to_le_bytes());
|
||||
pe.push(14);
|
||||
pe.push(0);
|
||||
pe.extend_from_slice(&(code.len() as u32).to_le_bytes());
|
||||
pe.extend_from_slice(&0u32.to_le_bytes());
|
||||
pe.extend_from_slice(&0u32.to_le_bytes());
|
||||
let entry_point_rva: u32 = 0x1000;
|
||||
pe.extend_from_slice(&entry_point_rva.to_le_bytes());
|
||||
pe.extend_from_slice(&0x1000u32.to_le_bytes());
|
||||
let image_base: u64 = 0x0000000140000000;
|
||||
pe.extend_from_slice(&image_base.to_le_bytes());
|
||||
pe.extend_from_slice(&0x1000u32.to_le_bytes());
|
||||
pe.extend_from_slice(&0x200u32.to_le_bytes());
|
||||
pe.extend_from_slice(&6u16.to_le_bytes());
|
||||
pe.extend_from_slice(&0u16.to_le_bytes());
|
||||
pe.extend_from_slice(&0u16.to_le_bytes());
|
||||
pe.extend_from_slice(&0u16.to_le_bytes());
|
||||
pe.extend_from_slice(&6u16.to_le_bytes());
|
||||
pe.extend_from_slice(&0u16.to_le_bytes());
|
||||
pe.extend_from_slice(&0u32.to_le_bytes());
|
||||
pe.extend_from_slice(&0x3000u32.to_le_bytes());
|
||||
let size_of_headers: u32 = 0x200;
|
||||
pe.extend_from_slice(&size_of_headers.to_le_bytes());
|
||||
pe.extend_from_slice(&0u32.to_le_bytes());
|
||||
pe.extend_from_slice(&3u16.to_le_bytes());
|
||||
pe.extend_from_slice(&0x8160u16.to_le_bytes());
|
||||
pe.extend_from_slice(&0x100000u64.to_le_bytes());
|
||||
pe.extend_from_slice(&0x1000u64.to_le_bytes());
|
||||
pe.extend_from_slice(&0x100000u64.to_le_bytes());
|
||||
pe.extend_from_slice(&0x1000u64.to_le_bytes());
|
||||
pe.extend_from_slice(&0u32.to_le_bytes());
|
||||
pe.extend_from_slice(&0u32.to_le_bytes());
|
||||
|
||||
// 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());
|
||||
pe.extend_from_slice(&0x1000u32.to_le_bytes());
|
||||
let raw_size: u32 = 0x200;
|
||||
pe.extend_from_slice(&raw_size.to_le_bytes());
|
||||
let raw_ptr: u32 = 0x200;
|
||||
pe.extend_from_slice(&raw_ptr.to_le_bytes());
|
||||
pe.extend_from_slice(&0u32.to_le_bytes());
|
||||
pe.extend_from_slice(&0u32.to_le_bytes());
|
||||
pe.extend_from_slice(&0u16.to_le_bytes());
|
||||
pe.extend_from_slice(&0u16.to_le_bytes());
|
||||
let characteristics: u32 = IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_EXECUTE;
|
||||
pe.extend_from_slice(&characteristics.to_le_bytes());
|
||||
|
||||
pe.resize(0x200, 0);
|
||||
pe.extend_from_slice(code);
|
||||
pe.resize(0x400, 0);
|
||||
|
||||
pe
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_native_arm64_dbt_arithmetic_and_control_flow() {
|
||||
// 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)
|
||||
// sub rax, 2 (48 83 e8 02)
|
||||
// xor rdx, rdx (48 31 d2)
|
||||
// hlt (f4)
|
||||
let mut code = Vec::new();
|
||||
code.extend_from_slice(&[0x48, 0xB8, 42, 0, 0, 0, 0, 0, 0, 0]);
|
||||
code.extend_from_slice(&[0x48, 0xB9, 10, 0, 0, 0, 0, 0, 0, 0]);
|
||||
code.extend_from_slice(&[0x48, 0x01, 0xC8]);
|
||||
code.extend_from_slice(&[0x48, 0x83, 0xE8, 0x02]);
|
||||
code.extend_from_slice(&[0x48, 0x31, 0xD2]);
|
||||
code.push(0xF4);
|
||||
|
||||
let pe_bytes = build_synthetic_pe32_plus(&code);
|
||||
let parsed = ParsedPe::parse(&pe_bytes).expect("PE parse");
|
||||
let mut loaded = parsed.load_into_memory(&pe_bytes).expect("PE load");
|
||||
|
||||
let stack_base = 0x2000_0000u64;
|
||||
let stack_size = 0x10000usize;
|
||||
loaded
|
||||
.memory
|
||||
.map_region(stack_base, stack_size, MemoryPermissions::READ_WRITE)
|
||||
.expect("stack map");
|
||||
let stack_top = stack_base + stack_size as u64;
|
||||
|
||||
let mut cpu = CpuState::new(loaded.entry_point, stack_top);
|
||||
let mut dbt = DbtEngine::new(1024 * 1024).expect("JIT memory allocation");
|
||||
|
||||
let res = dbt.run(&mut cpu, &mut loaded.memory, 100);
|
||||
assert_eq!(res.exit_reason, ExitReason::Halt);
|
||||
assert_eq!(res.final_state.get(Register::Rax), 50); // 42 + 10 - 2 = 50
|
||||
assert_eq!(res.final_state.get(Register::Rcx), 10);
|
||||
assert_eq!(res.final_state.get(Register::Rdx), 0);
|
||||
assert!(dbt.metrics.blocks_compiled >= 1);
|
||||
assert!(dbt.metrics.native_bytes_emitted > 0);
|
||||
assert_eq!(dbt.metrics.interpreter_fallbacks, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_native_arm64_dbt_subroutine_calls_and_stack() {
|
||||
// x86-64 program:
|
||||
// mov rdx, 0x1000 (48 ba 00 10 00 00 00 00 00 00)
|
||||
// push rdx (52)
|
||||
// pop rbx (5b)
|
||||
// call func (e8 01 00 00 00)
|
||||
// hlt (f4)
|
||||
// func:
|
||||
// add rbx, 5 (48 83 c3 05)
|
||||
// ret (c3)
|
||||
let mut code = Vec::new();
|
||||
code.extend_from_slice(&[0x48, 0xBA, 0x00, 0x10, 0, 0, 0, 0, 0, 0]);
|
||||
code.push(0x52);
|
||||
code.push(0x5B);
|
||||
code.extend_from_slice(&[0xE8, 0x01, 0x00, 0x00, 0x00]);
|
||||
code.push(0xF4);
|
||||
code.extend_from_slice(&[0x48, 0x83, 0xC3, 0x05]);
|
||||
code.push(0xC3);
|
||||
|
||||
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 stack_base = 0x3000_0000u64;
|
||||
let stack_size = 0x10000usize;
|
||||
loaded
|
||||
.memory
|
||||
.map_region(stack_base, stack_size, MemoryPermissions::READ_WRITE)
|
||||
.expect("stack map");
|
||||
let stack_top = stack_base + stack_size as u64;
|
||||
|
||||
let mut cpu = CpuState::new(loaded.entry_point, stack_top);
|
||||
let mut dbt = DbtEngine::new(1024 * 1024).expect("JIT memory");
|
||||
|
||||
let res = dbt.run(&mut cpu, &mut loaded.memory, 100);
|
||||
assert_eq!(res.exit_reason, ExitReason::Halt);
|
||||
assert_eq!(res.final_state.get(Register::Rbx), 0x1005);
|
||||
assert_eq!(res.final_state.get(Register::Rsp), stack_top);
|
||||
assert!(dbt.metrics.blocks_compiled >= 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_guest_dbt_first_rendered_frame_with_metal() {
|
||||
// Synthetic PE32+ guest program:
|
||||
// Initializes vertex data pointer and shader address in guest registers,
|
||||
// calls a synthetic guest host-service dispatch function at 0x7FFF_0000,
|
||||
// verifies return value in RAX, then halts.
|
||||
//
|
||||
// x86-64 code:
|
||||
// mov rcx, 0x5000_0000 (guest pointer to vertex data) -> 48 b9 00 00 00 50 00 00 00 00
|
||||
// mov rdx, 0x5000_1000 (guest pointer to shader descriptors) -> 48 ba 00 10 00 50 00 00 00 00
|
||||
// mov r8, 0x7FFF_0000 (host service address) -> 49 b8 00 00 ff 7f 00 00 00 00
|
||||
// call r8 (not direct call; or push ret_addr + jmp r8, or call rel32 to a trampoline stub)
|
||||
//
|
||||
// Let's use `call func` (E8 xx xx xx xx) pointing to 0x14000_1020, which is our registered service address!
|
||||
//
|
||||
// mov rcx, 0x5000_0000 (48 b9 00 00 00 50 00 00 00 00) [10 bytes]
|
||||
// mov rdx, 0x5000_1000 (48 ba 00 10 00 50 00 00 00 00) [10 bytes]
|
||||
// call +5 (e8 01 00 00 00) [5 bytes]
|
||||
// hlt (f4) [1 byte]
|
||||
// service stub at +1: (address 0x14000_101b)
|
||||
// ret (c3) [1 byte]
|
||||
let mut code = Vec::new();
|
||||
code.extend_from_slice(&[0x48, 0xB9, 0x00, 0x00, 0x00, 0x50, 0, 0, 0, 0]);
|
||||
code.extend_from_slice(&[0x48, 0xBA, 0x00, 0x10, 0x00, 0x50, 0, 0, 0, 0]);
|
||||
code.extend_from_slice(&[0xE8, 0x01, 0x00, 0x00, 0x00]);
|
||||
code.push(0xF4); // HLT
|
||||
code.push(0xC3); // RET
|
||||
|
||||
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");
|
||||
|
||||
// Map stack
|
||||
let stack_base = 0x2000_0000u64;
|
||||
let stack_size = 0x10000usize;
|
||||
loaded
|
||||
.memory
|
||||
.map_region(stack_base, stack_size, MemoryPermissions::READ_WRITE)
|
||||
.expect("stack map");
|
||||
let stack_top = stack_base + stack_size as u64;
|
||||
|
||||
// Map guest data buffer with genuine vertex coordinates and RDNA2 shader binaries
|
||||
let data_base = 0x5000_0000u64;
|
||||
let data_size = 0x10000usize;
|
||||
loaded
|
||||
.memory
|
||||
.map_region(data_base, data_size, MemoryPermissions::READ_WRITE)
|
||||
.expect("data map");
|
||||
|
||||
// Write genuine vertex data into guest memory at 0x5000_0000
|
||||
// Triangle positions: [-1.0, -1.0, 0.5, 1.0], [3.0, -1.0, 0.5, 1.0], [-1.0, 3.0, 0.5, 1.0]
|
||||
let positions: [[f32; 4]; 3] = [
|
||||
[-1.0, -1.0, 0.5, 1.0],
|
||||
[3.0, -1.0, 0.5, 1.0],
|
||||
[-1.0, 3.0, 0.5, 1.0],
|
||||
];
|
||||
let mut pos_bytes = Vec::new();
|
||||
for v in positions.iter().flatten() {
|
||||
pos_bytes.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
loaded
|
||||
.memory
|
||||
.write_bytes(0x5000_0000, &pos_bytes)
|
||||
.expect("write positions");
|
||||
|
||||
// Write constant RDNA2 shaders into guest memory at 0x5000_1000
|
||||
let vs_bytes = include_bytes!("../../../fixtures/rdna2/x9-constant-vs.bin");
|
||||
let ps_bytes = include_bytes!("../../../fixtures/rdna2/x9-constant-ps.bin");
|
||||
let vs_addr = 0x5000_1000u64;
|
||||
let ps_addr = vs_addr + vs_bytes.len() as u64;
|
||||
loaded
|
||||
.memory
|
||||
.write_bytes(vs_addr, vs_bytes)
|
||||
.expect("write vs");
|
||||
loaded
|
||||
.memory
|
||||
.write_bytes(ps_addr, ps_bytes)
|
||||
.expect("write ps");
|
||||
|
||||
// Shared storage for frame rendered by the host service
|
||||
let rendered_frame = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
|
||||
let frame_capture = rendered_frame.clone();
|
||||
|
||||
let mut cpu = CpuState::new(loaded.entry_point, stack_top);
|
||||
let mut dbt = DbtEngine::new(1024 * 1024).expect("JIT memory");
|
||||
|
||||
// Register synthetic guest graphics-service function at 0x14000_101B
|
||||
let service_addr = loaded.entry_point + 26; // 10 + 10 + 5 + 1 = 26 -> 0x14000_101A
|
||||
dbt.register_service(service_addr, move |cpu_state, guest_mem| {
|
||||
// Read vertex coordinates from guest memory at address in RCX
|
||||
let vtx_ptr = cpu_state.get(Register::Rcx);
|
||||
let mut vtx_raw = [0u8; 48]; // 3 * 4 * 4 bytes
|
||||
guest_mem
|
||||
.read_bytes(vtx_ptr, &mut vtx_raw)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
|
||||
let mut guest_vertices = [[0.0f32; 4]; 3];
|
||||
for (i, row) in guest_vertices.iter_mut().enumerate() {
|
||||
for (j, val) in row.iter_mut().enumerate() {
|
||||
let off = (i * 4 + j) * 4;
|
||||
*val = f32::from_le_bytes(vtx_raw[off..off + 4].try_into().unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
// Read RDNA2 shaders from guest memory
|
||||
let vs_data = guest_mem.read_u64(vs_addr).unwrap_or(0);
|
||||
let _ = vs_data;
|
||||
let mut g_vs = vec![0u8; vs_bytes.len()];
|
||||
let mut g_ps = vec![0u8; ps_bytes.len()];
|
||||
guest_mem
|
||||
.read_bytes(vs_addr, &mut g_vs)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
guest_mem
|
||||
.read_bytes(ps_addr, &mut g_ps)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
|
||||
// Translate genuine RDNA2 shaders from guest memory to Metal Shading Language
|
||||
let compiled = compile_graphics(Architecture::Gfx1030, &g_vs, &g_ps)
|
||||
.expect("compile graphics from guest memory");
|
||||
|
||||
// Submit draw on native Metal device
|
||||
let gpu = NativeCompute::new().expect("native Metal device");
|
||||
let entries = [VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT];
|
||||
let clear = [19, 43, 93, 251];
|
||||
let pixels = gpu
|
||||
.render_rgba8(
|
||||
&compiled.msl,
|
||||
entries,
|
||||
&guest_vertices,
|
||||
&[[0.0; 4]; 3],
|
||||
[4, 3],
|
||||
clear,
|
||||
)
|
||||
.expect("render on Metal GPU");
|
||||
|
||||
// Store rendered frame and return success in RAX
|
||||
let mut lock = frame_capture.lock().unwrap();
|
||||
*lock = pixels;
|
||||
cpu_state.set(Register::Rax, 0); // Status = 0 (Success)
|
||||
|
||||
// Read return address from [RSP] and emulate RET
|
||||
let sp = cpu_state.get(Register::Rsp);
|
||||
let ret_addr = guest_mem.read_u64(sp).map_err(ExitReason::MemoryFault)?;
|
||||
cpu_state.set(Register::Rsp, sp + 8);
|
||||
cpu_state.rip = ret_addr;
|
||||
|
||||
Ok(())
|
||||
});
|
||||
|
||||
let res = dbt.run(&mut cpu, &mut loaded.memory, 100);
|
||||
assert_eq!(res.exit_reason, ExitReason::Halt);
|
||||
assert_eq!(res.final_state.get(Register::Rax), 0); // Service returned 0
|
||||
assert_eq!(dbt.metrics.service_calls, 1);
|
||||
assert!(dbt.metrics.blocks_compiled >= 2);
|
||||
assert!(dbt.metrics.instructions_executed >= 4);
|
||||
|
||||
// Verify rendered frame against independent CPU / oracle expectation:
|
||||
// Full triangle interior covers all 12 pixels with [255, 0, 0, 255]
|
||||
let lock = rendered_frame.lock().unwrap();
|
||||
assert_eq!(lock.len(), 4 * 3 * 4); // 48 bytes (4x3 RGBA8)
|
||||
let expected_red_pixel = [255, 0, 0, 255];
|
||||
assert_eq!(*lock, expected_red_pixel.repeat(12));
|
||||
}
|
||||
Reference in new issue
Block a user