Benchmark guest service dispatch and scan CRT strings in blocks

Add correctness-gated guest loops that time services through the
import table. Scan string lengths 256 units at a time, falling back to
single units at mapping boundaries to keep exact faults.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
(cherry picked from commit b9f6afb20c7541c69464e2e771396269961a8a49)
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
This commit is contained in:
Adeeb Rahman committed 2026-11-24 10:33:26 -05:00
1 parent b3a6a57a8e
commit e0a6dae554
6 files changed
+540 -232

No files matched your search

+3
View File
@@ -10,6 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Changed
- Guest `strlen`, `strnlen`, `wcslen` and `wcsnlen` scan memory in 256-unit blocks, falling back to single units at mapping boundaries so faults still report the first inaccessible unit. On Apple M2 Pro the 63-byte `strlen` workload went from 1,990 ns to 223 ns per call (median of 10 batches, on a machine that was not idle).
- Moved the six hand-written gfx1030 VOP2 logical and shift forms (`v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`, `v_ashrrev_i32`, AMD guide section 12.7) into the semantic registry under a new VGPR-only operand rule `vop2_vgpr2`, with no behaviour change: a sweep of 132,608 VOP2, VOP1 and SOP1 words decodes to the same text, length and error before and after, the MSL goldens are unchanged, and the runtime-region allowlist admits exactly the same six forms. The per-lane `VectorBinary` gained `And`, `Or`, `Xor` and the three shifts (count masked to S0[4:0]); 6 hand-written instruction variants and their decoder and lowering arms are gone (17 hand-written forms remain). Part of #215.
- Added non-blocking Metal compute submission through `submit_words` and `wait`, with completion-aware resource retirement and a sixteen-dispatch in-flight limit. Synchronous calls keep their existing behavior. The benchmark reports the host submission split and compares synchronous and pipelined batches.
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
@@ -43,6 +44,8 @@ remains unsupported.
- Added guest mutexes, critical sections, SRW locks, condition variables, synchronous one-time initialization, interlocked SLists, and TLS and FLS slots. Ownership is per guest thread (TEB). Calls that would have to block stop the guest with an explicit runtime-limit fault, because there is no guest scheduler yet. An original PE32+ fixture calls every service through its import table, using two guest TEBs. See `docs/interfaces.md`.
- Added a guest service dispatch benchmark (`cargo bench -p xenora-loader --bench service_dispatch`). It runs correctness-gated guest loops that call services through the import table under the DBT; see `docs/testing/benchmarks.md`.
- Added a `runtime_services` fuzz target (`scripts/fuzz.sh runtime_services`) and a stable-toolchain replay test sharing the same driver. Both call random sequences of the standard guest services with zero, all-ones, writable, read-only, executable, unmapped, raw and earlier-result arguments, and check after every call that read-only and code memory are unchanged and nonvolatile registers are preserved. A local 300-second campaign on Apple M2 Pro ran 131,744 inputs (1,573 coverage edges) without a crash. Services that wait on real time or reach native Metal are excluded.
- Added guest system information, memory status, calendar time conversion, interrupt time and sleeping. The guest sees a configurable simulated machine (`GuestSystemProfile`, one processor by default), kept separate from the detected host hardware (`HostCapabilities`). Sleeping goes through the injectable clock, so tests advance time deterministically. An original PE32+ fixture verifies `SYSTEM_INFO`, `MEMORYSTATUSEX` and `SYSTEMTIME` layouts and leap-year handling against dates computed independently.
+4
View File
@@ -24,3 +24,7 @@ xenora-shader = { path = "../shader" }
[[bench]]
name = "dbt_bench"
harness = false
[[bench]]
name = "service_dispatch"
harness = false
+225
View File
@@ -0,0 +1,225 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Guest-to-host service dispatch cost, measured with original guest loops
//! that call standard services through a bound import table under the DBT.
//!
//! Every workload checks its result before timing. Each reported figure is
//! the per-iteration time of a loop of `ITERATIONS` calls: one warm-up batch,
//! then `BATCHES` measured batches. The empty loop is reported separately so
//! readers can subtract the loop and translation overhead themselves.
//!
//! Run with `cargo bench --locked -p xenora-loader --bench service_dispatch`.
#[path = "../tests/support/mod.rs"]
mod support;
use std::time::Instant;
use support::*;
use xenora_loader::cpu::{ExitReason, Register};
use xenora_loader::services::sysinfo::HostCapabilities;
const IMPORTS: &[(&str, &str)] = &[
("kernel32.dll", "GetLastError"),
("kernel32.dll", "CreateEventW"),
("kernel32.dll", "WaitForSingleObject"),
("ucrtbase.dll", "strlen"),
("kernel32.dll", "GetProcessHeap"),
("kernel32.dll", "HeapAlloc"),
("kernel32.dll", "HeapFree"),
("ucrtbase.dll", "qsort"),
];
const ITERATIONS: u32 = 10_000;
const BATCHES: usize = 10;
const CELL_EVENT: u64 = SCRATCH + 0x10;
const CELL_HEAP: u64 = SCRATCH + 0x18;
const STRING: u64 = SCRATCH + 0x100;
const ARRAY: u64 = SCRATCH + 0x200;
const ARRAY_LEN: u32 = 16;
const EMPTY: usize = 0;
const LAST_ERROR: usize = 1;
const WAIT: usize = 2;
const STRLEN: usize = 3;
const HEAP: usize = 4;
const QSORT: usize = 5;
const COMPARE: usize = 6;
/// A tiny x86-64 assembler for the routines below.
struct Asm {
base: u64,
code: Vec<u8>,
}
impl Asm {
fn new(routine_index: usize) -> Self {
Self {
base: routine(routine_index),
code: Vec::new(),
}
}
fn bytes(&mut self, bytes: &[u8]) -> &mut Self {
self.code.extend_from_slice(bytes);
self
}
fn imm64(&mut self, opcode: &[u8], value: u64) -> &mut Self {
self.bytes(opcode).bytes(&value.to_le_bytes())
}
fn imm32(&mut self, opcode: &[u8], value: u32) -> &mut Self {
self.bytes(opcode).bytes(&value.to_le_bytes())
}
/// `call qword ptr [rip + displacement]` through an import slot.
fn call_import(&mut self, symbol: &str) -> &mut Self {
let index = IMPORTS
.iter()
.position(|(_, name)| *name == symbol)
.unwrap();
let next = self.base + self.code.len() as u64 + 6;
let displacement = import_slot(IMPORTS, index).wrapping_sub(next) as u32;
self.imm32(&[0xFF, 0x15], displacement)
}
/// `mov ebx, ITERATIONS`, the loop body, `dec ebx; jnz body; hlt`.
fn counted(routine_index: usize, body: impl FnOnce(&mut Self)) -> Vec<u8> {
let mut asm = Self::new(routine_index);
asm.imm32(&[0xBB], ITERATIONS);
let start = asm.code.len();
body(&mut asm);
asm.bytes(&[0xFF, 0xCB]); // dec ebx
let back = start as i64 - (asm.code.len() as i64 + 2);
asm.bytes(&[0x75, i8::try_from(back).unwrap() as u8, 0xF4]);
asm.code
}
}
fn routines() -> Vec<Vec<u8>> {
let mut routines = vec![Vec::new(); 7];
routines[EMPTY] = Asm::counted(EMPTY, |_| {});
routines[LAST_ERROR] = Asm::counted(LAST_ERROR, |asm| {
asm.call_import("GetLastError");
});
routines[WAIT] = Asm::counted(WAIT, |asm| {
asm.imm64(&[0x48, 0xB8], CELL_EVENT) // mov rax, cell
.bytes(&[0x48, 0x8B, 0x08]) // mov rcx, [rax]
.bytes(&[0x31, 0xD2]) // xor edx, edx
.call_import("WaitForSingleObject");
});
routines[STRLEN] = Asm::counted(STRLEN, |asm| {
asm.imm64(&[0x48, 0xB9], STRING).call_import("strlen");
});
routines[HEAP] = Asm::counted(HEAP, |asm| {
asm.imm64(&[0x48, 0xB8], CELL_HEAP)
.bytes(&[0x48, 0x8B, 0x08]) // mov rcx, [rax]
.bytes(&[0x31, 0xD2])
.imm32(&[0x41, 0xB8], 64) // mov r8d, 64
.call_import("HeapAlloc")
.bytes(&[0x49, 0x89, 0xC0]) // mov r8, rax
.imm64(&[0x48, 0xB8], CELL_HEAP)
.bytes(&[0x48, 0x8B, 0x08])
.bytes(&[0x31, 0xD2])
.call_import("HeapFree");
});
routines[QSORT] = Asm::counted(QSORT, |asm| {
asm.imm64(&[0x48, 0xB9], ARRAY)
.imm32(&[0xBA], ARRAY_LEN) // mov edx, count
.imm32(&[0x41, 0xB8], 4) // mov r8d, width
.imm64(&[0x49, 0xB9], routine(COMPARE))
.call_import("qsort");
});
// int compare(const int *a, const int *b) { return *a - *b; }
routines[COMPARE] = vec![0x8B, 0x01, 0x2B, 0x02, 0xC3];
routines
}
fn median(samples: &mut [f64]) -> f64 {
samples.sort_by(f64::total_cmp);
samples[samples.len() / 2]
}
fn main() {
let mut guest = Guest::new(IMPORTS, &routines());
let event = guest.call("CreateEventW", &[0, 1, 1, 0]);
assert_ne!(event, 0);
guest.memory.write_u64(CELL_EVENT, event).unwrap();
let heap = guest.call("GetProcessHeap", &[]);
guest.memory.write_u64(CELL_HEAP, heap).unwrap();
guest.memory.write_bytes(STRING, &[b'a'; 63]).unwrap();
guest.memory.write_u8(STRING + 63, 0).unwrap();
let unsorted: Vec<i32> = (0..ARRAY_LEN as i32)
.map(|i| (i * 7919) % 31 - 15)
.collect();
let reset_array = |guest: &mut Guest| {
for (index, value) in unsorted.iter().enumerate() {
guest
.memory
.write_u32(ARRAY + 4 * index as u64, *value as u32)
.unwrap();
}
};
let host = HostCapabilities::detect();
let brand = std::process::Command::new("sysctl")
.args(["-n", "machdep.cpu.brand_string"])
.output()
.map(|output| String::from_utf8_lossy(&output.stdout).trim().to_owned())
.unwrap_or_default();
println!(
"host: {brand}, {} logical processors; profile: {}",
host.logical_processors.unwrap_or(0),
if cfg!(debug_assertions) {
"debug"
} else {
"release"
},
);
println!("{ITERATIONS} iterations per batch, 1 warm-up and {BATCHES} measured batches");
println!("workload,median_ns_per_iteration,min_ns,max_ns");
for (name, index, check) in [
("empty loop", EMPTY, None),
("GetLastError", LAST_ERROR, Some(0)),
(
"WaitForSingleObject (signaled manual-reset event)",
WAIT,
Some(0),
),
("strlen (63 bytes)", STRLEN, Some(63)),
("HeapAlloc + HeapFree (64 bytes)", HEAP, Some(1)),
("qsort (16 ints, guest comparator)", QSORT, Some(0)),
] {
let mut samples = Vec::with_capacity(BATCHES);
for batch in 0..=BATCHES {
if index == QSORT {
reset_array(&mut guest);
}
let start = Instant::now();
let (cpu, exit) = guest.execute(routine(index), usize::MAX);
let elapsed = start.elapsed();
assert_eq!(exit, ExitReason::Halt, "{name}");
assert_eq!(cpu.get(Register::Rbx), 0, "{name} loop count");
if let Some(expected) = check {
assert_eq!(cpu.get(Register::Rax), expected, "{name} result");
}
if index == QSORT {
let mut expected = unsorted.clone();
expected.sort();
let sorted: Vec<i32> = (0..ARRAY_LEN as u64)
.map(|i| guest.u32_at(ARRAY + 4 * i) as i32)
.collect();
assert_eq!(sorted, expected, "{name} ordering");
}
if batch > 0 {
samples.push(elapsed.as_nanos() as f64 / f64::from(ITERATIONS));
}
}
let (min, max) = samples.iter().fold((f64::MAX, 0f64), |(low, high), &s| {
(low.min(s), high.max(s))
});
println!("{name},{:.1},{min:.1},{max:.1}", median(&mut samples));
}
}
+30 -3
View File
@@ -45,11 +45,38 @@ fn string_length(
limit: u64,
unit: StringUnit,
) -> Result<u64, ExitReason> {
const BLOCK: u64 = 256;
let budget = SCAN_BUDGET / unit.width();
for offset in 0..limit.min(budget) {
if unit.read(memory, address, offset)? == 0 {
return Ok(offset);
let scan = limit.min(budget);
let mut buffer = [0u8; 2 * BLOCK as usize];
let mut offset = 0;
while offset < scan {
let count = BLOCK.min(scan - offset);
let bytes = &mut buffer[..(count * unit.width()) as usize];
// A block that crosses into unmapped or unreadable memory is scanned
// one unit at a time, so a terminator before the boundary still ends
// the scan and the fault reports the first inaccessible unit.
let block = address
.checked_add(offset * unit.width())
.filter(|_| address != 0)
.is_some_and(|start| memory.read_bytes(start, bytes).is_ok());
for index in 0..count {
let value = if block {
match unit {
StringUnit::Byte => u16::from(bytes[index as usize]),
StringUnit::Wide => {
let at = 2 * index as usize;
u16::from_le_bytes([bytes[at], bytes[at + 1]])
}
}
} else {
unit.read(memory, address, offset + index)?
};
if value == 0 {
return Ok(offset + index);
}
}
offset += count;
}
if limit <= budget {
return Ok(limit);
+248 -229
View File
@@ -1,229 +1,248 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Shared harness for runtime service tests: an original PE32+ image whose
//! imports are bound to the standard service registry and called from
//! translated guest code.
#![allow(dead_code)]
pub mod robustness;
use std::sync::Arc;
use xenora_loader::cpu::{CpuState, ExitReason, Register};
use xenora_loader::dbt::DbtEngine;
use xenora_loader::imports::ImportRegistry;
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
use xenora_loader::pe::ParsedPe;
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
pub const BASE: u64 = 0x1_4000_0000;
pub const CODE_RVA: u32 = 0x1000;
const IDATA_RVA: u32 = 0x10000;
const IDATA_RAW: usize = 0x2200;
const IDATA_LEN: usize = 0x4000;
pub const SCRATCH: u64 = 0x5_0000;
pub const SCRATCH_LEN: u64 = 0x1000;
pub const STACK: u64 = 0x8_0000;
pub const STACK_TOP: u64 = STACK + 0x800;
pub const THREAD_A: u64 = 0x7_0000;
pub const THREAD_B: u64 = 0x7_2000;
/// Guest routines start at this RVA in the text section, 32 bytes apart.
pub const ROUTINES_RVA: u32 = 0x1800;
pub const RUNTIME_LIMIT: ExitReason = ExitReason::IllegalInstruction(0xFE);
/// Guest address of routine `index`.
pub fn routine(index: usize) -> u64 {
BASE + u64::from(ROUTINES_RVA) + 32 * index as u64
}
/// The code for import `n`, at RVA 0x1000 + 16n, is `call [its slot]; hlt`.
/// Each import has its own descriptor.
fn build(imports: &[(&str, &str)], routines: &[Vec<u8>]) -> Vec<u8> {
let mut pe = vec![0u8; IDATA_RAW + IDATA_LEN];
fn put(pe: &mut [u8], at: usize, bytes: &[u8]) {
pe[at..at + bytes.len()].copy_from_slice(bytes);
}
put(&mut pe, 0, b"MZ");
put(&mut pe, 0x3C, &0x80u32.to_le_bytes());
put(&mut pe, 0x80, b"PE\0\0");
put(&mut pe, 0x84, &0x8664u16.to_le_bytes());
put(&mut pe, 0x86, &2u16.to_le_bytes());
put(&mut pe, 0x94, &240u16.to_le_bytes());
let optional = 0x98;
put(&mut pe, optional, &0x20Bu16.to_le_bytes());
put(&mut pe, optional + 16, &CODE_RVA.to_le_bytes());
put(&mut pe, optional + 24, &BASE.to_le_bytes());
put(&mut pe, optional + 32, &0x1000u32.to_le_bytes());
put(&mut pe, optional + 36, &0x200u32.to_le_bytes());
put(&mut pe, optional + 56, &0x20000u32.to_le_bytes());
put(&mut pe, optional + 60, &0x200u32.to_le_bytes());
put(&mut pe, optional + 108, &16u32.to_le_bytes());
put(&mut pe, optional + 120, &IDATA_RVA.to_le_bytes());
put(&mut pe, optional + 124, &0x100u32.to_le_bytes());
for (index, (name, rva, raw, len, flags)) in [
(b".text", CODE_RVA, 0x200, 0x2000, 0x6000_0020u32),
(b".idat", IDATA_RVA, IDATA_RAW, IDATA_LEN, 0xC000_0040),
]
.into_iter()
.enumerate()
{
let section = optional + 240 + 40 * index;
put(&mut pe, section, name);
put(&mut pe, section + 8, &(len as u32).to_le_bytes());
put(&mut pe, section + 12, &rva.to_le_bytes());
put(&mut pe, section + 16, &(len as u32).to_le_bytes());
put(&mut pe, section + 20, &(raw as u32).to_le_bytes());
put(&mut pe, section + 36, &flags.to_le_bytes());
}
assert!(16 * imports.len() <= (ROUTINES_RVA - CODE_RVA) as usize);
let file = |rva: u32| IDATA_RAW + (rva - IDATA_RVA) as usize;
let mut next = IDATA_RVA + 20 * (imports.len() as u32 + 1);
let mut take = |len: usize| {
let rva = next;
next = (next + len as u32 + 7) & !7;
rva
};
for (index, (module, symbol)) in imports.iter().enumerate() {
let module_rva = take(module.len() + 1);
put(&mut pe, file(module_rva), module.as_bytes());
let hint = take(symbol.len() + 3);
put(&mut pe, file(hint) + 2, symbol.as_bytes());
let (lookup, slot) = (take(16), take(16));
put(&mut pe, file(lookup), &u64::from(hint).to_le_bytes());
put(&mut pe, file(slot), &u64::from(hint).to_le_bytes());
let descriptor = file(IDATA_RVA) + 20 * index;
put(&mut pe, descriptor, &lookup.to_le_bytes());
put(&mut pe, descriptor + 12, &module_rva.to_le_bytes());
put(&mut pe, descriptor + 16, &slot.to_le_bytes());
let code_rva = CODE_RVA + 16 * index as u32;
let displacement = slot.wrapping_sub(code_rva + 6);
let at = 0x200 + 16 * index;
put(&mut pe, at, &[0xFF, 0x15]); // call qword ptr [rip + displacement]
put(&mut pe, at + 2, &displacement.to_le_bytes());
put(&mut pe, at + 6, &[0xF4]); // hlt
}
for (index, code) in routines.iter().enumerate() {
assert!(code.len() <= 32);
let at = 0x200 + (ROUTINES_RVA - CODE_RVA) as usize + 32 * index;
put(&mut pe, at, code);
}
pe
}
pub struct Guest {
engine: DbtEngine,
pub memory: GuestMemory,
pub state: Arc<ServicesState>,
imports: &'static [(&'static str, &'static str)],
teb: u64,
}
impl Guest {
pub fn new(imports: &'static [(&'static str, &'static str)], routines: &[Vec<u8>]) -> Self {
let state = ServicesState::new(Arc::new(MockClock::new(0)));
Self::with_state(imports, routines, state)
}
pub fn with_state(
imports: &'static [(&'static str, &'static str)],
routines: &[Vec<u8>],
state: ServicesState,
) -> Self {
let bytes = build(imports, routines);
let pe = ParsedPe::parse(&bytes).unwrap();
let mut memory = pe.load_into_memory(&bytes).unwrap().memory;
memory
.map_region(SCRATCH, SCRATCH_LEN as usize, MemoryPermissions::READ_WRITE)
.unwrap();
memory
.map_region(STACK, 0x1000, MemoryPermissions::READ_WRITE)
.unwrap();
let state = Arc::new(state);
let mut registry = ImportRegistry::new();
register_standard_services(&mut registry, Arc::clone(&state));
let bound = registry
.bind_imports(&pe, &bytes, BASE, &mut memory)
.unwrap();
assert_eq!(bound, imports.len());
let mut engine = DbtEngine::new(256 * 1024).unwrap();
engine.set_import_registry(registry);
Self {
engine,
memory,
state,
imports,
teb: THREAD_A,
}
}
pub fn on(&mut self, teb: u64) -> &mut Self {
self.teb = teb;
self
}
/// Call an import with Win64 arguments. Arguments after the fourth go on
/// the stack after the return address and the home area.
pub fn run(&mut self, symbol: &str, args: &[u64]) -> (u64, ExitReason) {
let index = self
.imports
.iter()
.position(|(_, name)| *name == symbol)
.unwrap_or_else(|| panic!("{symbol} is not imported"));
let mut cpu = CpuState::new(BASE + u64::from(CODE_RVA) + 16 * index as u64, STACK_TOP);
cpu.gs_base = self.teb;
for (register, value) in [Register::Rcx, Register::Rdx, Register::R8, Register::R9]
.into_iter()
.zip(args)
{
cpu.set(register, *value);
}
for (slot, value) in args.iter().skip(4).enumerate() {
let address = STACK_TOP + 32 + 8 * slot as u64;
self.memory.write_u64(address, *value).unwrap();
}
use Register::{R12, R13, R14, R15, Rbp, Rbx, Rdi, Rsi};
let nonvolatile = [Rbx, Rbp, Rdi, Rsi, R12, R13, R14, R15];
for (index, register) in nonvolatile.into_iter().enumerate() {
cpu.set(register, 0x5EED_0000 + index as u64);
}
let result = self.engine.run(&mut cpu, &mut self.memory, 100_000);
if result.exit_reason == ExitReason::Halt {
// The service returned to the instruction after its CALL.
assert_eq!(cpu.get(Register::Rsp), STACK_TOP, "{symbol}");
for (index, register) in nonvolatile.into_iter().enumerate() {
assert_eq!(cpu.get(register), 0x5EED_0000 + index as u64, "{symbol}");
}
}
(cpu.get(Register::Rax), result.exit_reason)
}
pub fn call(&mut self, symbol: &str, args: &[u64]) -> u64 {
let (rax, exit) = self.run(symbol, args);
assert_eq!(exit, ExitReason::Halt, "{symbol}");
rax
}
pub fn fails(&mut self, symbol: &str, args: &[u64]) -> ExitReason {
let (_, exit) = self.run(symbol, args);
assert_ne!(exit, ExitReason::Halt, "{symbol} should stop the guest");
exit
}
pub fn error(&mut self) -> u64 {
self.call("GetLastError", &[])
}
pub fn u16_at(&self, address: u64) -> u16 {
self.memory.read_u16(address).unwrap()
}
pub fn u32_at(&self, address: u64) -> u32 {
self.memory.read_u32(address).unwrap()
}
pub fn u64_at(&self, address: u64) -> u64 {
self.memory.read_u64(address).unwrap()
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
//! Shared harness for runtime service tests: an original PE32+ image whose
//! imports are bound to the standard service registry and called from
//! translated guest code.
#![allow(dead_code)]
pub mod robustness;
use std::sync::Arc;
use xenora_loader::cpu::{CpuState, ExitReason, Register};
use xenora_loader::dbt::DbtEngine;
use xenora_loader::imports::ImportRegistry;
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
use xenora_loader::pe::ParsedPe;
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
pub const BASE: u64 = 0x1_4000_0000;
pub const CODE_RVA: u32 = 0x1000;
const IDATA_RVA: u32 = 0x10000;
const IDATA_RAW: usize = 0x2200;
const IDATA_LEN: usize = 0x4000;
pub const SCRATCH: u64 = 0x5_0000;
pub const SCRATCH_LEN: u64 = 0x1000;
pub const STACK: u64 = 0x8_0000;
pub const STACK_TOP: u64 = STACK + 0x800;
pub const THREAD_A: u64 = 0x7_0000;
pub const THREAD_B: u64 = 0x7_2000;
/// Guest routines start at this RVA in the text section, 64 bytes apart.
pub const ROUTINES_RVA: u32 = 0x1800;
pub const ROUTINE_SIZE: usize = 64;
pub const RUNTIME_LIMIT: ExitReason = ExitReason::IllegalInstruction(0xFE);
/// Guest address of routine `index`.
pub fn routine(index: usize) -> u64 {
BASE + u64::from(ROUTINES_RVA) + (ROUTINE_SIZE * index) as u64
}
/// Guest address of the import address table slot for `imports[index]`, as
/// laid out by the image builder.
pub fn import_slot(imports: &[(&str, &str)], index: usize) -> u64 {
BASE + u64::from(build_image(imports, &[]).1[index])
}
/// The code for import `n`, at RVA 0x1000 + 16n, is `call [its slot]; hlt`.
/// Each import has its own descriptor.
fn build_image(imports: &[(&str, &str)], routines: &[Vec<u8>]) -> (Vec<u8>, Vec<u32>) {
let mut pe = vec![0u8; IDATA_RAW + IDATA_LEN];
fn put(pe: &mut [u8], at: usize, bytes: &[u8]) {
pe[at..at + bytes.len()].copy_from_slice(bytes);
}
put(&mut pe, 0, b"MZ");
put(&mut pe, 0x3C, &0x80u32.to_le_bytes());
put(&mut pe, 0x80, b"PE\0\0");
put(&mut pe, 0x84, &0x8664u16.to_le_bytes());
put(&mut pe, 0x86, &2u16.to_le_bytes());
put(&mut pe, 0x94, &240u16.to_le_bytes());
let optional = 0x98;
put(&mut pe, optional, &0x20Bu16.to_le_bytes());
put(&mut pe, optional + 16, &CODE_RVA.to_le_bytes());
put(&mut pe, optional + 24, &BASE.to_le_bytes());
put(&mut pe, optional + 32, &0x1000u32.to_le_bytes());
put(&mut pe, optional + 36, &0x200u32.to_le_bytes());
put(&mut pe, optional + 56, &0x20000u32.to_le_bytes());
put(&mut pe, optional + 60, &0x200u32.to_le_bytes());
put(&mut pe, optional + 108, &16u32.to_le_bytes());
put(&mut pe, optional + 120, &IDATA_RVA.to_le_bytes());
put(&mut pe, optional + 124, &0x100u32.to_le_bytes());
for (index, (name, rva, raw, len, flags)) in [
(b".text", CODE_RVA, 0x200, 0x2000, 0x6000_0020u32),
(b".idat", IDATA_RVA, IDATA_RAW, IDATA_LEN, 0xC000_0040),
]
.into_iter()
.enumerate()
{
let section = optional + 240 + 40 * index;
put(&mut pe, section, name);
put(&mut pe, section + 8, &(len as u32).to_le_bytes());
put(&mut pe, section + 12, &rva.to_le_bytes());
put(&mut pe, section + 16, &(len as u32).to_le_bytes());
put(&mut pe, section + 20, &(raw as u32).to_le_bytes());
put(&mut pe, section + 36, &flags.to_le_bytes());
}
assert!(16 * imports.len() <= (ROUTINES_RVA - CODE_RVA) as usize);
let file = |rva: u32| IDATA_RAW + (rva - IDATA_RVA) as usize;
let mut next = IDATA_RVA + 20 * (imports.len() as u32 + 1);
let mut take = |len: usize| {
let rva = next;
next = (next + len as u32 + 7) & !7;
rva
};
let mut slots = Vec::with_capacity(imports.len());
for (index, (module, symbol)) in imports.iter().enumerate() {
let module_rva = take(module.len() + 1);
put(&mut pe, file(module_rva), module.as_bytes());
let hint = take(symbol.len() + 3);
put(&mut pe, file(hint) + 2, symbol.as_bytes());
let (lookup, slot) = (take(16), take(16));
put(&mut pe, file(lookup), &u64::from(hint).to_le_bytes());
put(&mut pe, file(slot), &u64::from(hint).to_le_bytes());
let descriptor = file(IDATA_RVA) + 20 * index;
put(&mut pe, descriptor, &lookup.to_le_bytes());
put(&mut pe, descriptor + 12, &module_rva.to_le_bytes());
put(&mut pe, descriptor + 16, &slot.to_le_bytes());
slots.push(slot);
let code_rva = CODE_RVA + 16 * index as u32;
let displacement = slot.wrapping_sub(code_rva + 6);
let at = 0x200 + 16 * index;
put(&mut pe, at, &[0xFF, 0x15]); // call qword ptr [rip + displacement]
put(&mut pe, at + 2, &displacement.to_le_bytes());
put(&mut pe, at + 6, &[0xF4]); // hlt
}
for (index, code) in routines.iter().enumerate() {
assert!(code.len() <= ROUTINE_SIZE);
let at = 0x200 + (ROUTINES_RVA - CODE_RVA) as usize + ROUTINE_SIZE * index;
put(&mut pe, at, code);
}
(pe, slots)
}
pub struct Guest {
engine: DbtEngine,
pub memory: GuestMemory,
pub state: Arc<ServicesState>,
imports: &'static [(&'static str, &'static str)],
teb: u64,
}
impl Guest {
pub fn new(imports: &'static [(&'static str, &'static str)], routines: &[Vec<u8>]) -> Self {
let state = ServicesState::new(Arc::new(MockClock::new(0)));
Self::with_state(imports, routines, state)
}
pub fn with_state(
imports: &'static [(&'static str, &'static str)],
routines: &[Vec<u8>],
state: ServicesState,
) -> Self {
let (bytes, _) = build_image(imports, routines);
let pe = ParsedPe::parse(&bytes).unwrap();
let mut memory = pe.load_into_memory(&bytes).unwrap().memory;
memory
.map_region(SCRATCH, SCRATCH_LEN as usize, MemoryPermissions::READ_WRITE)
.unwrap();
memory
.map_region(STACK, 0x1000, MemoryPermissions::READ_WRITE)
.unwrap();
let state = Arc::new(state);
let mut registry = ImportRegistry::new();
register_standard_services(&mut registry, Arc::clone(&state));
let bound = registry
.bind_imports(&pe, &bytes, BASE, &mut memory)
.unwrap();
assert_eq!(bound, imports.len());
let mut engine = DbtEngine::new(256 * 1024).unwrap();
engine.set_import_registry(registry);
Self {
engine,
memory,
state,
imports,
teb: THREAD_A,
}
}
pub fn on(&mut self, teb: u64) -> &mut Self {
self.teb = teb;
self
}
/// Call an import with Win64 arguments. Arguments after the fourth go on
/// the stack after the return address and the home area.
pub fn run(&mut self, symbol: &str, args: &[u64]) -> (u64, ExitReason) {
let index = self
.imports
.iter()
.position(|(_, name)| *name == symbol)
.unwrap_or_else(|| panic!("{symbol} is not imported"));
let mut cpu = CpuState::new(BASE + u64::from(CODE_RVA) + 16 * index as u64, STACK_TOP);
cpu.gs_base = self.teb;
for (register, value) in [Register::Rcx, Register::Rdx, Register::R8, Register::R9]
.into_iter()
.zip(args)
{
cpu.set(register, *value);
}
for (slot, value) in args.iter().skip(4).enumerate() {
let address = STACK_TOP + 32 + 8 * slot as u64;
self.memory.write_u64(address, *value).unwrap();
}
use Register::{R12, R13, R14, R15, Rbp, Rbx, Rdi, Rsi};
let nonvolatile = [Rbx, Rbp, Rdi, Rsi, R12, R13, R14, R15];
for (index, register) in nonvolatile.into_iter().enumerate() {
cpu.set(register, 0x5EED_0000 + index as u64);
}
let result = self.engine.run(&mut cpu, &mut self.memory, 100_000);
if result.exit_reason == ExitReason::Halt {
// The service returned to the instruction after its CALL.
assert_eq!(cpu.get(Register::Rsp), STACK_TOP, "{symbol}");
for (index, register) in nonvolatile.into_iter().enumerate() {
assert_eq!(cpu.get(register), 0x5EED_0000 + index as u64, "{symbol}");
}
}
(cpu.get(Register::Rax), result.exit_reason)
}
/// Run guest code from `entry` on the calling thread's TEB until it stops.
pub fn execute(&mut self, entry: u64, max_instructions: usize) -> (CpuState, ExitReason) {
let mut cpu = CpuState::new(entry, STACK_TOP);
cpu.gs_base = self.teb;
let result = self
.engine
.run(&mut cpu, &mut self.memory, max_instructions);
(cpu, result.exit_reason)
}
pub fn call(&mut self, symbol: &str, args: &[u64]) -> u64 {
let (rax, exit) = self.run(symbol, args);
assert_eq!(exit, ExitReason::Halt, "{symbol}");
rax
}
pub fn fails(&mut self, symbol: &str, args: &[u64]) -> ExitReason {
let (_, exit) = self.run(symbol, args);
assert_ne!(exit, ExitReason::Halt, "{symbol} should stop the guest");
exit
}
pub fn error(&mut self) -> u64 {
self.call("GetLastError", &[])
}
pub fn u16_at(&self, address: u64) -> u16 {
self.memory.read_u16(address).unwrap()
}
pub fn u32_at(&self, address: u64) -> u32 {
self.memory.read_u32(address).unwrap()
}
pub fn u64_at(&self, address: u64) -> u64 {
self.memory.read_u64(address).unwrap()
}
}
+30
View File
@@ -96,3 +96,33 @@ correctness checks. The recorded 1-, 5- and 15-minute load averages were
individual compiler stages and cold/warm timing, tool and capability metadata,
and noise-based variability reporting. See the
[generated report](../../benchmarks/results/apple-m5/run-1795352394/report.md).
## Guest service dispatch
`cargo bench --locked -p xenora-loader --bench service_dispatch` measures
original guest loops that call standard runtime services through a bound
import table under the ARM64 dynamic binary translator. Before timing, each
workload checks its result: the loop count reaches zero, the service returns
its documented value, and `qsort` leaves the array in the order Rust's own sort
produces. The empty loop is reported separately, so readers can subtract the
loop and translation overhead. Each figure is the median per-iteration time of
10 measured batches of 10,000 iterations, after one warm-up batch.
Measured on Apple M2 Pro (12 logical processors), release profile, AC power,
on the working tree after `ed9b93c`. The 1-minute load average was 7.82, so the
machine was not idle and results are indicative only.
| Workload | Before (ns) | After the block `strlen` scan (ns) |
| --- | --- | --- |
| Empty loop | 21.5 | 20.1 |
| `GetLastError` | 181.8 | 188.4 |
| `WaitForSingleObject`, signaled manual-reset event | 281.0 | 284.6 |
| `strlen`, 63 bytes | 1,990.4 | 223.1 |
| `HeapAlloc` + `HeapFree`, 64 bytes | 475.0 | 493.3 |
| `qsort`, 16 ints with a guest comparator | 10,242.0 | 11,396.7 |
The `strlen` change scans 256-unit blocks with one checked read each. It falls
back to per-unit reads only when a block crosses unmapped or unreadable
memory, so the existing exact-fault tests still pass. The other rows differ by up to 11 percent between runs on this loaded
machine; that is run-to-run variation, not a measured change. Raw logs are kept locally under
`artifacts/system-runtime/bench/`. No comparison with native Windows is made.