Merge pull request #268 from MacosPorters/archive/pull/369/head

loader: add Win64 service ABI preservation tests (#201)
This commit is contained in:
atharvranjan authored and GitHub committed 2026-11-24 21:48:28 -06:00
commit f685b54e32
2 files changed
+189

No files matched your search

+2
View File
@@ -38,12 +38,14 @@ remains unsupported.
- Added a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status.
### Added
- Added a Win64 ABI regression showing that a service may write the caller-allocated shadow space. Existing negative controls cover nonvolatile XMM-register corruption; the unchanged-home-slot test now describes its handler rather than implying an ABI preservation requirement.
- Added a BetterXen development phase plan based on current source, pending PRs and existing acceptance records, linked from both contributor entry points. It separates baseline reconciliation, hosted C execution, guest threading, translated rendering, application integration and measured optimization; no new runtime or compatibility acceptance is claimed.
- Added `tests/runtime_clock.rs`, which reads the performance counter, its frequency, both tick counts, the unbiased interrupt time and the system time from one injected clock and checks that they report the same elapsed time in their own units, after a host advance and after a guest `Sleep`, and that none of them decreases up to and past the end of the clock (#204). Expected values are worked out by hand from the documented units. Timed waits still return without consuming clock time.
- Added opt-in shader IR constant folding (`CompileOptions::fold_constants` / `compile_with`) for pure vector unary and binary ops whose operands are already constants (#141). Floating-point ops still use the exact positive-normal rules; loads, stores, lane masks, merges and branches are never folded. Default `compile` keeps the historical IR. Covered by hand-computed known-answer compiler tests (shifts by 32/33, ashr, min_i32 vs min_u32, mul_hi_i32_i24, ffbh_i32, exact float fold, load-derived float non-fold, and verify rejection of inexact constant float add) with a fold-on versus fold-off check, plus an MSL template drift check over every foldable op.
- Added opt-in shader IR common-subexpression elimination (`CompileOptions::eliminate_common_subexpressions` / `compile_with`) that reuses the first result of an equivalent pure vector unary or binary (#142). Equivalence is the same operation and the same operand values in the same order; constant operands match by bit pattern. Loads, stores, constant definitions, lane masks, merges, branches and other side-effecting or execution-mask-dependent ops are left in place. The pass runs after constant folding, so folded results stay constants and a later pure op on two equal folded constants can still be reused. Default `compile` keeps the historical IR. Covered by hand-derived known-answer compiler tests for reuse (and/xor, not, exact float add), for rejected loads, swapped subtracts, lane masks, lane merges and VCC selects, and for the four combinations with constant folding (1 + 2 = 3, and 1.0 + 2.0 = 3.0), and a check that the 13 golden fixtures, none of which repeats an expression, compile unchanged with the pass on. No speedup is claimed.
- The loader now maps an image's PE headers at its image base (#333): the first `SizeOfHeaders` bytes of the file, read-only, in whole 4 KiB pages that are zero past `SizeOfHeaders`. Programs read their own headers this way; the mingw-w64 C runtime does so before `main`, and until now that read faulted. When startup relocates an image it writes the load base into the mapped `ImageBase` field after the relocations, so an entry aimed at that field cannot move it twice; this is Xenora's policy and has not been compared with Windows. A load is refused with the new `PeError::InvalidHeaderSize` when `SizeOfHeaders` is zero, ends before the section table, runs past the file, or its pages would reach into a section, and when the bytes handed to the loader are not the PE32+ headers that were parsed. The page rule refuses images with sub-page section alignment whose first section starts inside the header page, which loaded before. The header pages count toward the 256 MiB mapping budget, which is checked before anything is mapped. `ParsedPe::parse` and the static probe are unchanged. `tests/pe_headers.rs` covers guest reads at the preferred and a relocated base, a relocation aimed at `ImageBase`, the write and execute faults and each refusal with original hand-built images; the image in `pe_mapping_limits.rs` now carries a valid `SizeOfHeaders`. Awaiting independent re-review.
- Added 35 known-answer cases for MOV with an immediate operand, opcodes C6 /0 and C7 /0 (#194), to `cpu_known_answers.rs`: byte, word, dword and qword stores through base, SIB, R12, R13, RSP and RBP addressing with 8-bit and 32-bit displacements; the imm32 sign extension of the 64-bit form; the register forms, including AH and a REX-selected SIL; unmapped and read-only store faults at each width; and #UD for reg field 1. Expected values come from the Intel SDM and were worked out by hand. The interpreter and the DBT already agreed with all of them, so this is new coverage and fixes no defect. The 16-bit forms covered are those that already run, and #118 stays open. Not compared with x86 hardware; awaiting independent review.
- Added Win64 service-call ABI tests in `crates/loader/tests/runtime_services.rs` for #201. A dispatch-level test and a DBT guest-call test verify 16-byte-aligned call entry (`RSP % 16 == 8`), caller-owned 32-byte shadow space accessibility/integrity, return-value/stack/RIP return state, and preservation of RBX/RBP/RDI/RSI/R12-R15 and XMM6-XMM15 across registered service calls. Expected values are derived from the Microsoft x64 calling convention, not from current implementation behavior.
- `dbt_bench` can also write its results as one JSON document when `XENORA_DBT_BENCH_JSON=<path>` is set (#112). The document records the host CPU, OS and architecture, the git revision and whether the tree had local changes, debug assertions, the workload and sample counts, the median, minimum, maximum, p95, p99, IQR and MIPS for the interpreter and for cold and warm DBT, and the cold DBT counters. Anything the benchmark cannot determine is `null`. The text output and the timed work are unchanged.
- Added synthetic guest handle-lifetime regression tests (#205) for capacity reuse, stale handles, duplicate rights and lifetime, wrong object types, thread pseudo handles and failed-output nonmutation. Runtime behavior is unchanged; independent acceptance is pending.
- Added a documented independent acceptance rule for promoting AMD RDNA2 desktop GPU (gfx1030) forms from local CPU and Metal results to `fixture verified`, including clean-commit evidence, reviewer independence, raw-log location, review-log summary, failure handling and status regeneration (#302).
+187
View File
@@ -7,6 +7,7 @@
//! convention documentation, not from the registry or the handlers.
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
use xenora_loader::cpu::{CpuState, ExitReason, Register};
use xenora_loader::dbt::DbtEngine;
@@ -696,6 +697,76 @@ fn floating_arguments_and_results_use_xmm_registers() {
assert_eq!(float("fabsf", garbage | 0xBF80_0000) as u32, 0x3F80_0000); // -1
}
#[test]
fn guest_call_through_dbt_preserves_win64_abi_state() {
use Register::{R8, R9, R12, R13, R14, R15, Rax, Rbp, Rbx, Rcx, Rdi, Rdx, Rsi, Rsp};
let observed = Arc::new(Mutex::new(None::<(u64, u64, [u64; 4])>));
let seen = observed.clone();
let mut registry = ImportRegistry::new();
registry.register("t.dll", "F", move |_args, cpu, mem| {
let rsp = cpu.get(Rsp);
let shadow = [
mem.read_u64(rsp + 8).unwrap(),
mem.read_u64(rsp + 16).unwrap(),
mem.read_u64(rsp + 24).unwrap(),
mem.read_u64(rsp + 32).unwrap(),
];
*seen.lock().unwrap() = Some((rsp, cpu.rip, shadow));
cpu.set(Rcx, 0x11);
cpu.set(Rdx, 0x22);
cpu.set(R8, 0x33);
cpu.set(R9, 0x44);
for (reg, lane) in cpu.xmm[..6].iter_mut().enumerate() {
*lane = u128::from(0x55_u64 + reg as u64);
}
Ok(0x99AA_BBCC_DDEE_F001)
});
let image = build(&[("t.dll", Symbol::Name("F"))]);
let pe = ParsedPe::parse(&image.bytes).unwrap();
let mut memory = pe.load_into_memory(&image.bytes).unwrap().memory;
memory
.map_region(STACK, 0x1000, MemoryPermissions::READ_WRITE)
.unwrap();
registry
.bind_imports(&pe, &image.bytes, BASE, &mut memory)
.unwrap();
let mut engine = DbtEngine::new(256 * 1024).unwrap();
engine.set_import_registry(registry);
// Before CALL RSP is 16-byte aligned; CALL pushes return address so the
// callee sees RSP % 16 == 8. Shadow space is [entry_rsp+8, entry_rsp+40).
let initial_rsp = STACK_TOP;
assert_eq!(initial_rsp % 16, 0);
let entry_rsp_expected = initial_rsp - 8;
for slot in 0..4u64 {
memory
.write_u64(entry_rsp_expected + 8 + slot * 8, 0x7000 + slot)
.unwrap();
}
let mut cpu = CpuState::new(BASE + u64::from(CODE_RVA), initial_rsp);
let nonvolatile_gpr = [Rbx, Rbp, Rdi, Rsi, R12, R13, R14, R15];
for (index, register) in nonvolatile_gpr.into_iter().enumerate() {
cpu.set(register, 0x6100 + index as u64);
}
for (offset, lane) in cpu.xmm[6..16].iter_mut().enumerate() {
*lane = u128::from(0x6200_u64 + (offset + 6) as u64);
}
let result = engine.run(&mut cpu, &mut memory, 1000);
assert_eq!(result.exit_reason, ExitReason::Halt);
let (entry_rsp, _, shadow) = observed.lock().unwrap().expect("service ran");
assert_eq!(entry_rsp, entry_rsp_expected);
assert_eq!(entry_rsp % 16, 8);
assert_eq!(shadow, [0x7000, 0x7001, 0x7002, 0x7003]);
assert_eq!(cpu.get(Rax), 0x99AA_BBCC_DDEE_F001);
assert_eq!(cpu.get(Rsp), initial_rsp);
for (index, register) in nonvolatile_gpr.into_iter().enumerate() {
assert_eq!(cpu.get(register), 0x6100 + index as u64, "{register:?}");
}
for (offset, lane) in cpu.xmm[6..16].iter().enumerate() {
let index = offset + 6;
assert_eq!(*lane, u128::from(0x6200_u64 + index as u64), "xmm{index}");
}
}
#[test]
fn arguments_are_assigned_by_position_and_read_the_stack_after_the_fourth() {
let mut memory = GuestMemory::new();
@@ -957,6 +1028,122 @@ fn a_service_that_changes_a_nonvolatile_register_stops_the_guest() {
}
}
#[test]
fn service_may_write_its_caller_allocated_shadow_space() {
// Microsoft x64 calling convention: the caller reserves four home slots,
// but the callee may use them. Their contents are not nonvolatile state.
let (registry, mut memory, trampoline) = bound_service(|_, cpu, memory| {
for slot in 0..4u64 {
memory
.write_u64(cpu.get(Register::Rsp) + 8 + slot * 8, 0xA000 + slot)
.unwrap();
}
Ok(7)
});
let entry_rsp = STACK_TOP - 8;
memory.write_u64(entry_rsp, 0x1234).unwrap();
let mut cpu = CpuState::new(trampoline, entry_rsp);
assert_eq!(registry.dispatch(trampoline, &mut cpu, &mut memory), Ok(()));
assert_eq!(cpu.rip, 0x1234);
assert_eq!(cpu.get(Register::Rsp), entry_rsp + 8);
assert_eq!(cpu.get(Register::Rax), 7);
for slot in 0..4u64 {
assert_eq!(memory.read_u64(entry_rsp + 8 + slot * 8), Ok(0xA000 + slot));
}
}
#[test]
fn service_calls_preserve_win64_abi_state() {
// Microsoft x64 calling convention: at entry RSP % 16 == 8 (return address
// pushed by CALL). Callee preserves RBX,RBP,RDI,RSI,R12-R15 and XMM6-XMM15.
// Caller allocates 32-byte shadow/home space at [RSP+8, RSP+40), which
// the callee may use. This handler leaves it unchanged; the separate
// shadow-space test checks a handler that writes it. RAX carries the
// return value; RCX,RDX,R8,R9,R10,R11,XMM0-XMM5 are volatile.
use Register::{R8, R9, R10, R11, R12, R13, R14, R15, Rax, Rbp, Rbx, Rcx, Rdi, Rdx, Rsi, Rsp};
let observed = Arc::new(Mutex::new(None::<(u64, u64, [u64; 4], u64)>));
let seen = observed.clone();
let (registry, mut memory, trampoline) = bound_service(move |args, cpu, mem| {
let rsp = cpu.get(Rsp);
let shadow = [
mem.read_u64(rsp + 8).unwrap(),
mem.read_u64(rsp + 16).unwrap(),
mem.read_u64(rsp + 24).unwrap(),
mem.read_u64(rsp + 32).unwrap(),
];
*seen.lock().unwrap() = Some((rsp, cpu.rip, shadow, args.rcx));
// Clobber volatile registers; dispatcher must still return correctly and
// nonvolatile state must be preserved after return.
cpu.set(Rcx, 0xA1);
cpu.set(Rdx, 0xA2);
cpu.set(R8, 0xA3);
cpu.set(R9, 0xA4);
cpu.set(R10, 0xA5);
cpu.set(R11, 0xA6);
for (reg, lane) in cpu.xmm[..6].iter_mut().enumerate() {
*lane = u128::from(0xB0_u64 + reg as u64);
}
Ok(0x1122_3344_5566_7788)
});
// Win64: before CALL RSP is 16-byte aligned; CALL pushes return address,
// so callee entry sees RSP % 16 == 8.
let call_rsp = STACK_TOP - 8;
assert_eq!(call_rsp % 16, 8);
memory.write_u64(call_rsp, 0x1234).unwrap();
for slot in 0..4u64 {
memory
.write_u64(call_rsp + 8 + slot * 8, 0xC000 + slot)
.unwrap();
}
let mut cpu = CpuState::new(trampoline, call_rsp);
let nonvolatile_gpr = [Rbx, Rbp, Rdi, Rsi, R12, R13, R14, R15];
for (index, register) in nonvolatile_gpr.into_iter().enumerate() {
cpu.set(register, 0x5AA5_0000_0001_0000 + index as u64);
}
for (offset, lane) in cpu.xmm[6..16].iter_mut().enumerate() {
*lane = u128::from(0xD000_0000_0000_0000_u64 + (offset + 6) as u64);
}
cpu.set(Rcx, 0x1357_9BDF_2468_ACE0);
let result = registry.dispatch(trampoline, &mut cpu, &mut memory);
assert_eq!(result, Ok(()));
let (entry_rsp, entry_rip, shadow, entry_rcx) = observed.lock().unwrap().expect("service ran");
assert_eq!(entry_rip, trampoline);
assert_eq!(
entry_rsp, call_rsp,
"service sees caller RSP at return address"
);
assert_eq!(entry_rsp % 16, 8, "Win64 entry RSP must be 8 mod 16");
assert_eq!(entry_rcx, 0x1357_9BDF_2468_ACE0);
// Shadow/home space is caller-owned and must be addressable by the service.
assert_eq!(shadow, [0xC000, 0xC001, 0xC002, 0xC003]);
for slot in 0..4u64 {
assert_eq!(
memory.read_u64(call_rsp + 8 + slot * 8).unwrap(),
0xC000 + slot,
"this handler leaves its home slots untouched"
);
}
// Post-return ABI state.
assert_eq!(cpu.get(Rax), 0x1122_3344_5566_7788);
assert_eq!(cpu.get(Rsp), call_rsp + 8);
assert_eq!(cpu.rip, 0x1234);
for (index, register) in nonvolatile_gpr.into_iter().enumerate() {
assert_eq!(
cpu.get(register),
0x5AA5_0000_0001_0000 + index as u64,
"nonvolatile {register:?} must be preserved"
);
}
for (offset, lane) in cpu.xmm[6..16].iter().enumerate() {
let index = offset + 6;
assert_eq!(
*lane,
u128::from(0xD000_0000_0000_0000_u64 + index as u64),
"nonvolatile xmm{index} must be preserved"
);
}
}
#[test]
fn a_call_that_cannot_return_runs_no_service() {
let calls = Arc::new(AtomicUsize::new(0));