Compare commits

..
Author SHA1 Message Date
Arthur Lacoste ba26ba75a7 Merge af1b84ad75 into bbc84c0da0 2026-11-24 21:14:36 +00:00
Arthur Lacoste af1b84ad75 loader: fix needless_range_loop in Win64 ABI tests (#201)
Address review feedback from zachdoxsee on PR #369: replace index-only XMM range loops with iterator-based loops so strict clippy passes on Rust 1.100.

Signed-off-by: Arthur Lacoste <arthurlacoste@users.noreply.github.com>
2026-11-24 22:14:29 +01:00
Arthur Lacoste cf438e25aa Merge remote-tracking branch 'origin/main' into runtime/win64-service-abi-201
# Conflicts:
#	CHANGELOG.md
2026-11-24 22:13:14 +01:00
Zach Doxsee bbc84c0da0 Merge pull request #373 from 1Bartosz/bench/112-json-export
bench: export dbt_bench results as JSON (#112)
2026-11-24 21:57:25 +01:00
Bartosz Szczepański 061c28b405 bench: export dbt_bench results as JSON (#112)
dbt_bench printed its results only as text. With
XENORA_DBT_BENCH_JSON=<path> set it now also writes one JSON document:
host CPU, OS and architecture, git revision and dirty state, debug
assertions, the workload and sample counts, median, min, max, p95, p99,
IQR and MIPS for the interpreter and cold and warm DBT, and the cold
DBT counters. Values the benchmark cannot determine are null.

The statistics are computed once in a Summary that feeds both the text
line and the JSON, so the two cannot disagree. The text output and the
timed work are unchanged, and no dependency is added.

Unit tests cover string escaping, null handling, the whole document for
fixed inputs and the text line format.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-24 21:22:58 +01:00
Arthur Lacoste 7246ab5ea6 loader: add Win64 service ABI preservation tests (#201)
Add dispatch and DBT-backed runtime service tests that verify Win64 callee entry alignment, caller-owned shadow space, return state, and preservation of nonvolatile GPRs/XMM registers across registered service calls.

AI-Assisted: Codex (GPT-5) helped draft the tests; I reviewed the diff and ran fmt/clippy(loader)/loader tests locally.
Signed-off-by: Arthur Lacoste <arthurlacoste@users.noreply.github.com>
2026-11-24 20:57:41 +01:00
7 changed files with 526 additions and 503 deletions

No files matched your search

+2 -1
View File
@@ -10,7 +10,6 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Changed
- The native ARM64 DBT now runs the 32- and 64-bit register and immediate forms of ADC and SBB itself instead of falling back to the shared interpreter (#195). The guest CF is moved into the host carry before ADCS or SBCS, inverted for SBB because SBCS subtracts NOT C while SBB subtracts CF. Memory forms and 8- and 16-bit forms still use the shared semantics. `tests/x86_carry_chain.rs` runs 256-bit add and subtract chains of 64- and 32-bit limbs, in one block and split one block per limb, against widening `u128`/`i128` reference arithmetic in both engines, plus immediate 128-bit increments and decrements and the `sbb reg, reg` carry mask. Locally verified on Apple M5 only.
- Removed the temporary region-list allocation from each instruction-byte fetch while preserving lookup order, execute-permission checks and error behavior (part of #104).
- Release and bench builds now use fat link-time optimization with one codegen unit (#116). On a local Apple M5, `dbt_bench` medians over five alternating runs dropped by about 6 % for the interpreter (903 to 845 µs) and about 9 % for cold DBT (1.155 to 1.046 ms), while warm DBT (cache hits) became about 2 % slower (21.83-22.08 to 22.29-22.54 µs over four further runs). The `xenora` binary shrank from 2.73 to 2.11 MB. A clean release build of the workspace takes about 14 s instead of 6 s. Debug and test builds are unchanged.
- The ARM64 assembler loads 64-bit constants with the fewest MOVZ or MOVN plus MOVK instructions (#92). It no longer emits MOVK for zero halfwords and starts from MOVN when more halfwords are 0xFFFF than zero, so small negative values take one instruction instead of four. On Apple M5 the DBT benchmark emits 245,168 instead of 290,184 native bytes for its 626 blocks (-15.5%) and the 1,048 integer fixture instructions 128,724 instead of 145,732 (-11.7%); benchmark run times did not change measurably. New tests check the sequences against LLVM encodings and execute 1,056 of them on the host through the JIT.
@@ -27,6 +26,8 @@ remains unsupported.
- Made the native semantic-review timeout in `scripts/test-gpu.sh` configurable with `XENORA_SEMANTIC_TIMEOUT` and raised its default from 120 to 300 seconds, so cold Apple Silicon runs do not fail while the expanded Metal known-answer suite is still progressing.
### Added
- 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).
- Added the VOP3A (`_e64`) encodings of eleven gfx1030 VOP2 integer forms (`v_mul_{i32_i24,hi_i32_i24,u32_u24,hi_u32_u24}`, `v_{min,max}_{i32,u32}`, `v_xnor_b32`, `v_sub_nc_u32`, `v_subrev_nc_u32`) and of the sixteen Wave32 integer compares (explicit SGPR mask destination, `s_cbranch_vccz` through `vcc_lo`, a translation error for reads of runtime-only SGPR results) as semantic-registry encoding variants, with VGPR sources only. New fixtures `vop3-integer` and `vop3-compare` with IR and MSL goldens, and an independent guide-derived oracle (`tests/validation/tests/vop3_{integer,compare}.rs`) that agrees on both reference interpreters and on native Metal. Part of #215.
+362 -15
View File
@@ -2,6 +2,11 @@
//! Synthetic interpreter and DBT timings.
//!
//! Set `XENORA_DBT_BENCH_JSON=<path>` to also write the results as one JSON
//! document (format version 1). The text output does not change. Values the
//! benchmark cannot determine, such as the git revision outside a checkout,
//! are written as `null`.
//!
//! The benchmark target disables Cargo's test harness. To run the percentile
//! unit tests, build with
//! `cargo rustc --locked -p xenora-loader --bench dbt_bench --message-format=json -- --test`
@@ -10,7 +15,7 @@
use std::hint::black_box;
use std::time::{Duration, Instant};
use xenora_loader::cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, Register};
use xenora_loader::dbt::DbtEngine;
use xenora_loader::dbt::{DbtEngine, DbtMetrics};
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,
@@ -103,19 +108,215 @@ fn percentile(sorted: &[Duration], fraction: f64) -> Duration {
lower + (upper - lower).mul_f64(rank.fract())
}
fn report(label: &str, samples: &mut [Duration]) {
/// Order statistics of one timing series, shared by the text and JSON reports.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Summary {
samples: usize,
median: Duration,
min: Duration,
max: Duration,
p95: Duration,
p99: Duration,
iqr: Duration,
mips: f64,
}
fn summarize(samples: &mut [Duration]) -> Summary {
samples.sort_unstable();
let median = percentile(samples, 0.50);
let p95 = percentile(samples, 0.95);
let p99 = percentile(samples, 0.99);
let iqr = percentile(samples, 0.75) - percentile(samples, 0.25);
let min = samples[0];
let max = samples[samples.len() - 1];
let mips = INSTRUCTIONS as f64 / median.as_secs_f64() / 1_000_000.0;
println!(
"{label}: {} samples, median {median:?}, min {min:?}, max {max:?}, p95 {p95:?}, p99 {p99:?}, IQR {iqr:?}, median {mips:.2} MIPS",
samples.len()
);
Summary {
samples: samples.len(),
median,
min: samples[0],
max: samples[samples.len() - 1],
p95: percentile(samples, 0.95),
p99: percentile(samples, 0.99),
iqr: percentile(samples, 0.75) - percentile(samples, 0.25),
mips: INSTRUCTIONS as f64 / median.as_secs_f64() / 1_000_000.0,
}
}
fn report_line(label: &str, s: &Summary) -> String {
format!(
"{label}: {} samples, median {:?}, min {:?}, max {:?}, p95 {:?}, p99 {:?}, IQR {:?}, median {:.2} MIPS",
s.samples, s.median, s.min, s.max, s.p95, s.p99, s.iqr, s.mips
)
}
/// Facts about the run that are not timings. `None` means the benchmark could not
/// determine the value.
struct RunInfo {
unix_time: Option<u64>,
cpu: Option<String>,
os: &'static str,
os_version: Option<String>,
arch: &'static str,
revision: Option<String>,
dirty: Option<bool>,
debug_assertions: bool,
guest_code_bytes: usize,
warmup: usize,
}
fn command_output(program: &str, args: &[&str]) -> Option<String> {
let output = std::process::Command::new(program)
.args(args)
.output()
.ok()?;
if !output.status.success() {
return None;
}
Some(String::from_utf8(output.stdout).ok()?.trim().to_owned())
}
fn run_info(guest_code_bytes: usize, warmup: usize) -> RunInfo {
let non_empty = |value: Option<String>| value.filter(|v| !v.is_empty());
RunInfo {
unix_time: std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.ok()
.map(|d| d.as_secs()),
cpu: non_empty(command_output(
"sysctl",
&["-n", "machdep.cpu.brand_string"],
)),
os: std::env::consts::OS,
os_version: non_empty(command_output("sw_vers", &["-productVersion"])),
arch: std::env::consts::ARCH,
revision: non_empty(command_output("git", &["rev-parse", "HEAD"])),
dirty: command_output("git", &["status", "--porcelain", "--untracked-files=no"])
.map(|status| !status.is_empty()),
debug_assertions: cfg!(debug_assertions),
guest_code_bytes,
warmup,
}
}
fn json_string(value: &str) -> String {
let mut out = String::with_capacity(value.len() + 2);
out.push('"');
for c in value.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
out
}
fn json_option<T>(value: Option<T>, render: impl FnOnce(T) -> String) -> String {
value.map_or_else(|| "null".to_owned(), render)
}
/// JSON has no infinity or NaN, so a non-finite rate (a zero median) is `null`.
fn json_f64(value: f64) -> String {
if value.is_finite() {
format!("{value}")
} else {
"null".to_owned()
}
}
fn json_object(fields: &[(&str, String)]) -> String {
let body: Vec<String> = fields
.iter()
.map(|(key, value)| format!("{}:{value}", json_string(key)))
.collect();
format!("{{{}}}", body.join(","))
}
fn json_summary(s: &Summary) -> String {
json_object(&[
("samples", s.samples.to_string()),
("median_ns", s.median.as_nanos().to_string()),
("min_ns", s.min.as_nanos().to_string()),
("max_ns", s.max.as_nanos().to_string()),
("p95_ns", s.p95.as_nanos().to_string()),
("p99_ns", s.p99.as_nanos().to_string()),
("iqr_ns", s.iqr.as_nanos().to_string()),
("median_mips", json_f64(s.mips)),
])
}
fn json_document(
info: &RunInfo,
interpreter: &Summary,
cold: &Summary,
warm: &Summary,
metrics: &DbtMetrics,
) -> String {
let string = |value: &String| json_string(value);
json_object(&[
("format_version", "1".to_owned()),
("benchmark", json_string("dbt_bench")),
("unix_time", json_option(info.unix_time, |t| t.to_string())),
(
"host",
json_object(&[
("cpu", json_option(info.cpu.as_ref(), string)),
("os", json_string(info.os)),
("os_version", json_option(info.os_version.as_ref(), string)),
("arch", json_string(info.arch)),
]),
),
(
"source",
json_object(&[
("revision", json_option(info.revision.as_ref(), string)),
("dirty", json_option(info.dirty, |d| d.to_string())),
]),
),
(
"build",
json_object(&[("debug_assertions", info.debug_assertions.to_string())]),
),
(
"workload",
json_object(&[
("name", json_string("add_rax_chain")),
("guest_instructions", INSTRUCTIONS.to_string()),
("guest_code_bytes", info.guest_code_bytes.to_string()),
("instruction_budget", BUDGET.to_string()),
("warmup_rounds", info.warmup.to_string()),
]),
),
(
"timings",
json_object(&[
("interpreter", json_summary(interpreter)),
("cold_dbt", json_summary(cold)),
("warm_dbt", json_summary(warm)),
]),
),
(
"cold_dbt_metrics",
json_object(&[
("blocks_compiled", metrics.blocks_compiled.to_string()),
("cache_hits", metrics.cache_hits.to_string()),
("cache_misses", metrics.cache_misses.to_string()),
(
"native_bytes_emitted",
metrics.native_bytes_emitted.to_string(),
),
("dbt_dispatches", metrics.dbt_dispatches.to_string()),
(
"instructions_executed",
metrics.instructions_executed.to_string(),
),
(
"interpreter_fallbacks",
metrics.interpreter_fallbacks.to_string(),
),
("service_calls", metrics.service_calls.to_string()),
]),
),
])
}
fn main() {
@@ -190,14 +391,24 @@ fn main() {
"Percentiles describe this synthetic workload on this host; tail estimates vary with sample count."
);
println!("Even sample counts use the midpoint of the two middle values for the median.");
report("Interpreter", &mut interpreter);
report("Cold DBT", &mut cold);
report("Warm DBT", &mut warm);
let interpreter = summarize(&mut interpreter);
let cold = summarize(&mut cold);
let warm = summarize(&mut warm);
println!("{}", report_line("Interpreter", &interpreter));
println!("{}", report_line("Cold DBT", &cold));
println!("{}", report_line("Warm DBT", &warm));
let metrics = cold_metrics.unwrap();
println!(
"Cold DBT compiled {} blocks and emitted {} native bytes in {} dispatches",
metrics.blocks_compiled, metrics.native_bytes_emitted, metrics.dbt_dispatches
);
if let Some(path) = std::env::var_os("XENORA_DBT_BENCH_JSON") {
let info = run_info(code.len(), warmup_count);
let document = json_document(&info, &interpreter, &cold, &warm, &metrics);
std::fs::write(&path, document + "\n").expect("write XENORA_DBT_BENCH_JSON");
println!("JSON results written to {}", path.to_string_lossy());
}
}
#[cfg(test)]
@@ -233,4 +444,140 @@ mod tests {
let samples = [10, 20, 100].map(Duration::from_micros);
assert_eq!(percentile(&samples, 0.50), Duration::from_micros(20));
}
#[test]
fn json_strings_escape_quotes_backslashes_and_controls() {
use super::json_string;
assert_eq!(json_string("plain"), r#""plain""#);
assert_eq!(json_string(r#"a"b\c"#), r#""a\"b\\c""#);
assert_eq!(json_string("l1\nl2\r\t"), r#""l1\nl2\r\t""#);
assert_eq!(json_string("\u{1}\u{1f}"), r#""\u0001\u001f""#);
// Non-ASCII text needs no escape in UTF-8 JSON.
assert_eq!(json_string("Zażółć"), "\"Zażółć\"");
}
#[test]
fn unknown_values_and_non_finite_rates_are_null() {
use super::{json_f64, json_option};
assert_eq!(json_option(None::<u64>, |v| v.to_string()), "null");
assert_eq!(json_option(Some(7_u64), |v| v.to_string()), "7");
assert_eq!(json_f64(f64::INFINITY), "null");
assert_eq!(json_f64(f64::NAN), "null");
assert_eq!(json_f64(12.5), "12.5");
}
#[test]
fn document_has_every_field_with_the_summary_values() {
fn fixed_summary(median_us: u64) -> super::Summary {
use super::Duration;
super::Summary {
samples: 3,
median: Duration::from_micros(median_us),
min: Duration::from_micros(10),
max: Duration::from_micros(100),
p95: Duration::from_nanos(92_000),
p99: Duration::from_nanos(98_400),
iqr: Duration::from_micros(45),
mips: 500.25,
}
}
fn fixed_info() -> super::RunInfo {
super::RunInfo {
unix_time: Some(1_700_000_000),
cpu: Some("Test \"CPU\"\\1".to_owned()),
os: "macos",
os_version: None,
arch: "aarch64",
revision: Some("0123abcd".to_owned()),
dirty: Some(false),
debug_assertions: false,
guest_code_bytes: 40_011,
warmup: 10,
}
}
use super::{DbtMetrics, INSTRUCTIONS, json_document};
let metrics = DbtMetrics {
blocks_compiled: 626,
cache_hits: 0,
cache_misses: 626,
native_bytes_emitted: 245_168,
dbt_dispatches: 626,
instructions_executed: 10_002,
interpreter_fallbacks: 1,
service_calls: 0,
};
let document = json_document(
&fixed_info(),
&fixed_summary(20),
&fixed_summary(30),
&fixed_summary(40),
&metrics,
);
let summary = |median: &str| {
format!(
r#"{{"samples":3,"median_ns":{median},"min_ns":10000,"max_ns":100000,"p95_ns":92000,"p99_ns":98400,"iqr_ns":45000,"median_mips":500.25}}"#
)
};
let expected = format!(
concat!(
r#"{{"format_version":1,"benchmark":"dbt_bench","unix_time":1700000000,"#,
r#""host":{{"cpu":"Test \"CPU\"\\1","os":"macos","os_version":null,"arch":"aarch64"}},"#,
r#""source":{{"revision":"0123abcd","dirty":false}},"#,
r#""build":{{"debug_assertions":false}},"#,
r#""workload":{{"name":"add_rax_chain","guest_instructions":{},"guest_code_bytes":40011,"instruction_budget":20000,"warmup_rounds":10}},"#,
r#""timings":{{"interpreter":{},"cold_dbt":{},"warm_dbt":{}}},"#,
r#""cold_dbt_metrics":{{"blocks_compiled":626,"cache_hits":0,"cache_misses":626,"native_bytes_emitted":245168,"dbt_dispatches":626,"instructions_executed":10002,"interpreter_fallbacks":1,"service_calls":0}}}}"#,
),
INSTRUCTIONS,
summary("20000"),
summary("30000"),
summary("40000"),
);
assert_eq!(document, expected);
}
#[test]
fn text_report_keeps_its_format() {
fn fixed_summary(median_us: u64) -> super::Summary {
use super::Duration;
super::Summary {
samples: 3,
median: Duration::from_micros(median_us),
min: Duration::from_micros(10),
max: Duration::from_micros(100),
p95: Duration::from_nanos(92_000),
p99: Duration::from_nanos(98_400),
iqr: Duration::from_micros(45),
mips: 500.25,
}
}
use super::report_line;
assert_eq!(
report_line("Cold DBT", &fixed_summary(20)),
"Cold DBT: 3 samples, median 20µs, min 10µs, max 100µs, p95 92µs, p99 98.4µs, IQR 45µs, median 500.25 MIPS"
);
}
#[test]
fn summary_matches_the_percentile_helper() {
use super::{Duration, INSTRUCTIONS, summarize};
let mut samples = [100, 10, 30, 20].map(Duration::from_micros);
let s = summarize(&mut samples);
assert_eq!(s.samples, 4);
assert_eq!(s.median, Duration::from_micros(25));
assert_eq!(s.min, Duration::from_micros(10));
assert_eq!(s.max, Duration::from_micros(100));
assert_eq!(s.p95, Duration::from_nanos(89_500));
assert_eq!(s.p99, Duration::from_nanos(97_900));
assert_eq!(s.iqr, Duration::from_micros(30));
assert_eq!(s.mips, INSTRUCTIONS as f64 / 25e-6 / 1e6);
}
}
-40
View File
@@ -430,46 +430,6 @@ impl Arm64Assembler {
);
}
/// ADCS (64-bit, flags updating): ADCS Xd, Xn, Xm computes Xn + Xm + C.
pub fn adcs_reg_64(&mut self, xd: u8, xn: u8, xm: u8) {
self.emit(
0xba000000
| ((xm as u32 & 0x1f) << 16)
| ((xn as u32 & 0x1f) << 5)
| (xd as u32 & 0x1f),
);
}
/// ADCS (32-bit, flags updating): ADCS Wd, Wn, Wm computes Wn + Wm + C.
pub fn adcs_reg_32(&mut self, wd: u8, wn: u8, wm: u8) {
self.emit(
0x3a000000
| ((wm as u32 & 0x1f) << 16)
| ((wn as u32 & 0x1f) << 5)
| (wd as u32 & 0x1f),
);
}
/// SBCS (64-bit, flags updating): SBCS Xd, Xn, Xm computes Xn - Xm - !C.
pub fn sbcs_reg_64(&mut self, xd: u8, xn: u8, xm: u8) {
self.emit(
0xfa000000
| ((xm as u32 & 0x1f) << 16)
| ((xn as u32 & 0x1f) << 5)
| (xd as u32 & 0x1f),
);
}
/// SBCS (32-bit, flags updating): SBCS Wd, Wn, Wm computes Wn - Wm - !C.
pub fn sbcs_reg_32(&mut self, wd: u8, wn: u8, wm: u8) {
self.emit(
0x7a000000
| ((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(
+1 -21
View File
@@ -335,9 +335,6 @@ pub fn is_native(insn: &Insn) -> bool {
let scanned = matches!(insn.size, 2 | 4 | 8);
match insn.op {
Op::Add | Op::Sub | Op::Cmp | Op::And | Op::Or | Op::Xor | Op::Test => wide,
// Register and immediate forms only; a memory destination would have
// to restore the guest carry again after the store helper call.
Op::Adc | Op::Sbb => wide && insn.memory().is_none(),
Op::Inc | Op::Dec | Op::Neg | Op::Not => wide,
Op::Cmov => wide,
Op::Bsf | Op::Bsr => scanned,
@@ -590,26 +587,9 @@ impl Emitter<'_> {
}
/// X11 = X9 op X10, setting host NZCV only for the arithmetic operations.
/// ADC and SBB also read the guest CF and clobber X12 and X13.
fn compute(&mut self, op: Op, wide: bool) {
let asm = &mut *self.asm;
if matches!(op, Op::Adc | Op::Sbb) {
// ADCS adds the host C, so C must equal the guest CF. SBCS
// subtracts NOT C, while x86 SBB subtracts the borrow CF, so there
// C must be its inverse. A compare sets C when it does not borrow.
asm.ldrb_uoff(X12, X19, CF);
if op == Op::Adc {
asm.load_imm_64(X13, 1);
asm.cmp_reg_32(X12, X13); // C = CF >= 1
} else {
asm.cmp_reg_32(XZR, X12); // C = 0 >= CF
}
}
match (op, wide) {
(Op::Adc, true) => asm.adcs_reg_64(X11, X9, X10),
(Op::Adc, false) => asm.adcs_reg_32(X11, X9, X10),
(Op::Sbb, true) => asm.sbcs_reg_64(X11, X9, X10),
(Op::Sbb, false) => asm.sbcs_reg_32(X11, X9, X10),
(Op::Add | Op::Inc, true) => asm.adds_reg_64(X11, X9, X10),
(Op::Add | Op::Inc, false) => asm.adds_reg_32(X11, X9, X10),
(Op::And | Op::Test, true) => asm.ands_reg_64(X11, X9, X10),
@@ -643,7 +623,7 @@ impl Emitter<'_> {
match op {
// INC and DEC leave CF unchanged.
Op::Inc | Op::Dec => {}
Op::Add | Op::Adc => {
Op::Add => {
asm.cset_32(X12, Condition::Cs);
asm.strb_uoff(X12, X19, CF);
}
-42
View File
@@ -164,45 +164,3 @@ fn vector_operations_match_llvm() {
assert_eq!(assembler.instructions(), [*word], "{text}");
}
}
#[test]
fn carry_arithmetic_matches_llvm() {
// `llvm-mc -triple=aarch64-apple-macos -show-encoding`.
let cases: &[(&str, Emit, u32)] = &[
(
"adcs x11, x9, x10",
|a| a.adcs_reg_64(11, 9, 10),
0xba0a012b,
),
(
"adcs w11, w9, w10",
|a| a.adcs_reg_32(11, 9, 10),
0x3a0a012b,
),
(
"adcs x0, x30, x17",
|a| a.adcs_reg_64(0, 30, 17),
0xba1103c0,
),
(
"sbcs x11, x9, x10",
|a| a.sbcs_reg_64(11, 9, 10),
0xfa0a012b,
),
(
"sbcs w11, w9, w10",
|a| a.sbcs_reg_32(11, 9, 10),
0x7a0a012b,
),
(
"sbcs w0, w30, w17",
|a| a.sbcs_reg_32(0, 30, 17),
0x7a1103c0,
),
];
for (text, emit, word) in cases {
let mut assembler = Arm64Assembler::new();
emit(&mut assembler);
assert_eq!(assembler.instructions(), [*word], "{text}");
}
}
+161
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,96 @@ fn a_service_that_changes_a_nonvolatile_register_stops_the_guest() {
}
}
#[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 owns 32-byte shadow/home space at [RSP+8, RSP+40). 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,
"service call must not mutate caller shadow space"
);
}
// 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));
-384
View File
@@ -1,384 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Multiword ADC and SBB carry chains through the interpreter and the native
//! DBT.
//!
//! Encodings were assembled with LLVM (`llvm-mc -triple=x86_64`, Intel syntax).
//! Expected values come from widening `u128` and `i128` arithmetic over the
//! limbs, following the ADC and SBB operation sections of the Intel SDM Vol. 2:
//! DEST = DEST + SRC + CF and DEST = DEST - (SRC + CF). They never read the
//! production semantics. Both engines must also agree on the complete state,
//! including PF and AF, which the reference does not model.
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter};
use xenora_loader::dbt::{DbtEngine, is_native};
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
use xenora_loader::x86_decode::decode;
use xenora_loader::x86_table::Op;
const ENTRY: u64 = 0x1000;
/// `jmp +0`: ends the translated block, so the next instruction reads CF from
/// the guest state stored by the previous block.
const JMP: [u8; 2] = [0xEB, 0x00];
const HLT: u8 = 0xF4;
/// Limb registers: A in RAX, RBX, RCX, RDX and B in R8 to R11.
const A: [usize; 4] = [0, 3, 1, 2];
const B: [usize; 4] = [8, 9, 10, 11];
// add rax, r8; adc rbx, r9; adc rcx, r10; adc rdx, r11 (and the SUB/SBB and
// 32-bit equivalents).
const ADD64: [&[u8]; 4] = [
&[0x4C, 0x01, 0xC0],
&[0x4C, 0x11, 0xCB],
&[0x4C, 0x11, 0xD1],
&[0x4C, 0x11, 0xDA],
];
const SUB64: [&[u8]; 4] = [
&[0x4C, 0x29, 0xC0],
&[0x4C, 0x19, 0xCB],
&[0x4C, 0x19, 0xD1],
&[0x4C, 0x19, 0xDA],
];
const ADD32: [&[u8]; 4] = [
&[0x44, 0x01, 0xC0],
&[0x44, 0x11, 0xCB],
&[0x44, 0x11, 0xD1],
&[0x44, 0x11, 0xDA],
];
const SUB32: [&[u8]; 4] = [
&[0x44, 0x29, 0xC0],
&[0x44, 0x19, 0xCB],
&[0x44, 0x19, 0xD1],
&[0x44, 0x19, 0xDA],
];
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Chain {
Add,
Sub,
}
/// Expected limbs and CF, ZF, SF, OF of the last limb.
#[derive(PartialEq, Eq, Debug)]
struct Expected {
limbs: [u64; 4],
cf: bool,
zf: bool,
sf: bool,
of: bool,
}
fn reference(chain: Chain, bits: u32, a: [u64; 4], b: [u64; 4]) -> Expected {
let mask = if bits == 64 {
u64::MAX
} else {
(1u64 << bits) - 1
};
let modulus = 1u128 << bits;
let signed = |value: u64| -> i128 {
let value = i128::from(value & mask);
if value >= (1i128 << (bits - 1)) {
value - (1i128 << bits)
} else {
value
}
};
let mut limbs = [0; 4];
let mut carry = 0u128;
let mut of = false;
for i in 0..4 {
let (x, y) = (u128::from(a[i] & mask), u128::from(b[i] & mask));
let wide = match chain {
Chain::Add => x + y + carry,
Chain::Sub => x + modulus - y - carry,
};
limbs[i] = (wide % modulus) as u64;
let exact = match chain {
Chain::Add => signed(a[i]) + signed(b[i]) + carry as i128,
Chain::Sub => signed(a[i]) - signed(b[i]) - carry as i128,
};
of = exact != signed(limbs[i]);
carry = match chain {
Chain::Add => u128::from(wide >= modulus),
Chain::Sub => u128::from(y + carry > x),
};
}
Expected {
limbs,
cf: carry != 0,
zf: limbs[3] == 0,
sf: limbs[3] >> (bits - 1) & 1 != 0,
of,
}
}
fn program(parts: &[&[u8]], split: bool) -> Vec<u8> {
let mut code = Vec::new();
for (i, part) in parts.iter().enumerate() {
if split && i > 0 {
code.extend_from_slice(&JMP);
}
code.extend_from_slice(part);
}
code.push(HLT);
code
}
fn load(code: &[u8], gpr: [u64; 16], cf: bool) -> (CpuState, GuestMemory) {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, code)
.unwrap();
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr = gpr;
cpu.flags.cf = cf;
(cpu, memory)
}
/// Run `code` to its HLT in both engines, check they agree on the whole state
/// and that the DBT never left native code, and return the final state.
fn run_both(code: &[u8], gpr: [u64; 16], cf: bool, context: &str) -> CpuState {
let (cpu, mut memory) = load(code, gpr, cf);
let interpreted = Interpreter::new(cpu, &mut memory, 64).run();
let (mut cpu, mut memory) = load(code, gpr, cf);
let mut engine = DbtEngine::new(16 * 1024).unwrap();
let translated = engine.run(&mut cpu, &mut memory, 64);
assert_eq!(interpreted.exit_reason, ExitReason::Halt, "{context}");
assert_eq!(translated.exit_reason, ExitReason::Halt, "{context}");
assert_eq!(translated.final_state, interpreted.final_state, "{context}");
assert_eq!(engine.metrics.interpreter_fallbacks, 0, "{context}");
interpreted.final_state
}
struct Random(u64);
impl Random {
fn next(&mut self) -> u64 {
self.0 ^= self.0 >> 12;
self.0 ^= self.0 << 25;
self.0 ^= self.0 >> 27;
self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
}
}
/// Limb values at the carry and overflow boundaries of a `bits`-wide limb.
fn edges(bits: u32) -> [u64; 6] {
let max = if bits == 64 {
u64::MAX
} else {
(1u64 << bits) - 1
};
let sign = 1u64 << (bits - 1);
[0, 1, max - 1, max, sign, sign - 1]
}
fn operand_sets(bits: u32) -> Vec<([u64; 4], [u64; 4])> {
let edges = edges(bits);
let mut sets = Vec::new();
for &x in &edges {
for &y in &edges {
sets.push(([x; 4], [y; 4]));
sets.push(([x, y, x, y], [y, x, y, x]));
}
}
let mut random = Random(0x0195_ADC5_BB00_0001);
for _ in 0..256 {
let mut pick = || {
let raw = random.next();
if raw & 3 == 0 {
edges[(raw >> 8) as usize % edges.len()] | raw & !edges[3]
} else {
raw
}
};
let a = [pick(), pick(), pick(), pick()];
let b = [pick(), pick(), pick(), pick()];
sets.push((a, b));
}
sets
}
fn check_chain(chain: Chain, bits: u32, parts: [&[u8]; 4]) {
for part in &parts[1..] {
let insn = decode(ENTRY, |address| {
part.get((address - ENTRY) as usize).copied().ok_or(())
})
.unwrap();
assert!(matches!(insn.op, Op::Adc | Op::Sbb));
assert!(is_native(&insn), "{:?}", insn.op);
}
let mut random = Random(u64::from(bits) << 8 | chain as u64);
for (a, b) in operand_sets(bits) {
let expected = reference(chain, bits, a, b);
for split in [false, true] {
let code = program(&parts, split);
let mut gpr: [u64; 16] = std::array::from_fn(|_| random.next());
for i in 0..4 {
gpr[A[i]] = a[i];
gpr[B[i]] = b[i];
}
// The leading ADD or SUB must ignore the incoming carry.
for cf in [false, true] {
let context = format!("{chain:?}{bits} split={split} cf={cf} a={a:x?} b={b:x?}");
let state = run_both(&code, gpr, cf, &context);
let limbs = A.map(|index| state.gpr[index]);
// A 32-bit destination clears bits 63:32.
assert_eq!(limbs, expected.limbs, "{context}");
assert_eq!(B.map(|index| state.gpr[index]), b, "{context}");
let flags = (
state.flags.cf,
state.flags.zf,
state.flags.sf,
state.flags.of,
);
let wanted = (expected.cf, expected.zf, expected.sf, expected.of);
assert_eq!(flags, wanted, "{context}");
}
}
}
}
#[test]
fn reference_matches_native_wide_arithmetic() {
// 128-bit sanity checks of the reference itself on the low two limbs.
let cases = [
(u128::MAX, 1u128),
(0, 1),
(1u128 << 64, 1),
(0x8000_0000_0000_0000_0000_0000_0000_0000, 1),
];
for (x, y) in cases {
let a = [x as u64, (x >> 64) as u64, 0, 0];
let b = [y as u64, (y >> 64) as u64, 0, 0];
let sum = reference(Chain::Add, 64, a, b);
let expected = x.wrapping_add(y);
assert_eq!(sum.limbs[0], expected as u64);
assert_eq!(sum.limbs[1], (expected >> 64) as u64);
let difference = reference(Chain::Sub, 64, a, b);
let expected = x.wrapping_sub(y);
assert_eq!(difference.limbs[0], expected as u64);
assert_eq!(difference.limbs[1], (expected >> 64) as u64);
// The upper limbs are zero, so the 256-bit borrow is the 128-bit one.
assert_eq!(difference.cf, y > x);
}
}
#[test]
fn add_adc_chains_of_64_bit_limbs_carry_across_blocks() {
check_chain(Chain::Add, 64, ADD64);
}
#[test]
fn sub_sbb_chains_of_64_bit_limbs_borrow_across_blocks() {
check_chain(Chain::Sub, 64, SUB64);
}
#[test]
fn add_adc_chains_of_32_bit_limbs_carry_across_blocks() {
check_chain(Chain::Add, 32, ADD32);
}
#[test]
fn sub_sbb_chains_of_32_bit_limbs_borrow_across_blocks() {
check_chain(Chain::Sub, 32, SUB32);
}
#[test]
fn split_chains_run_one_block_per_limb() {
let code = program(&ADD64, true);
let (mut cpu, mut memory) = load(&code, [0; 16], false);
let mut engine = DbtEngine::new(16 * 1024).unwrap();
let result = engine.run(&mut cpu, &mut memory, 64);
assert_eq!(result.exit_reason, ExitReason::Halt);
assert_eq!(engine.metrics.blocks_compiled, 4);
assert_eq!(engine.metrics.interpreter_fallbacks, 0);
}
#[test]
fn immediate_forms_increment_and_decrement_a_128_bit_value() {
// add rax, 1; adc rbx, 0 and sub rax, 1; sbb rbx, 0.
let increment: [&[u8]; 2] = [&[0x48, 0x83, 0xC0, 0x01], &[0x48, 0x83, 0xD3, 0x00]];
let decrement: [&[u8]; 2] = [&[0x48, 0x83, 0xE8, 0x01], &[0x48, 0x83, 0xDB, 0x00]];
let values = [
0u128,
1,
u64::MAX as u128,
1u128 << 64,
u128::MAX,
u128::MAX - 1,
1u128 << 127,
(1u128 << 127) - 1,
];
for value in values {
for split in [false, true] {
for (parts, expected, carry, overflow) in [
(
&increment,
value.wrapping_add(1),
value == u128::MAX,
value == (1u128 << 127) - 1,
),
(
&decrement,
value.wrapping_sub(1),
value == 0,
value == 1u128 << 127,
),
] {
let code = program(parts, split);
let mut gpr = [0x5A5A_5A5A_5A5A_5A5A; 16];
gpr[0] = value as u64;
gpr[3] = (value >> 64) as u64;
let context = format!("{value:#x} split={split} {:x?}", parts[0]);
let state = run_both(&code, gpr, true, &context);
assert_eq!(state.gpr[0], expected as u64, "{context}");
assert_eq!(state.gpr[3], (expected >> 64) as u64, "{context}");
assert_eq!(state.flags.cf, carry, "{context}");
assert_eq!(state.flags.of, overflow, "{context}");
assert_eq!(state.flags.zf, (expected >> 64) == 0, "{context}");
assert_eq!(state.flags.sf, expected >> 127 != 0, "{context}");
}
}
}
}
#[test]
fn sbb_of_a_register_with_itself_materializes_the_carry_mask() {
// sbb esi, esi and sbb rsi, rsi give -CF and borrow exactly when CF was
// set; adc edi, 0 adds CF to 0x89ABCDEF without a carry out. The 32-bit
// forms clear bits 63:32.
// (code, destination register, value from CF, CF out from CF in)
type Case = (&'static [u8], usize, fn(bool) -> u64, fn(bool) -> bool);
let cases: [Case; 3] = [
(
&[0x19, 0xF6],
6,
|cf| if cf { 0xFFFF_FFFF } else { 0 },
|cf| cf,
),
(
&[0x48, 0x19, 0xF6],
6,
|cf| if cf { u64::MAX } else { 0 },
|cf| cf,
),
(
&[0x83, 0xD7, 0x00],
7,
|cf| u64::from(cf) + 0x89AB_CDEF,
|_| false,
),
];
for (code, register, value, carry) in cases {
for cf in [false, true] {
let mut gpr = [0x0123_4567_89AB_CDEF; 16];
gpr[6] = 0xDEAD_BEEF_0000_0001;
let program = [code, &[HLT]].concat();
let context = format!("{code:x?} cf={cf}");
let state = run_both(&program, gpr, cf, &context);
assert_eq!(state.gpr[register], value(cf), "{context}");
assert_eq!(state.flags.cf, carry(cf), "{context}");
}
}
}