mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 13:30:43 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bd46504a97 |
No files matched your search
@@ -91,7 +91,7 @@ A coding agent claims in the name of the person it works for and follows the sam
|
||||
- Run source mutation on decoder/shader/ref: `scripts/mutation.sh` (R2 owns triage)
|
||||
- Check generated status tables: `python3 scripts/audit/status.py --check`.
|
||||
- Check claims and dependency direction: `scripts/audit/claims.sh` and `scripts/audit/dependencies.sh`
|
||||
- Fuzz one target at a time: `scripts/fuzz.sh <instruction_stream|fixture|reference|runtime_services>` (600 seconds by default). `runtime_services` drives the standard guest service registry.
|
||||
- Fuzz one CPU-only parser at a time: `scripts/fuzz.sh <instruction_stream|fixture|reference>` (600 seconds by default).
|
||||
|
||||
Keep generated and gate logs under ignored `artifacts/`. Use at most four Cargo build jobs across two simultaneous CPU-heavy jobs, with one GPU job and one fuzz or mutation campaign at a time.
|
||||
|
||||
|
||||
@@ -10,8 +10,6 @@ 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).
|
||||
- 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.
|
||||
@@ -22,12 +20,10 @@ remains unsupported.
|
||||
- Moved gfx1030 `s_mov_b32` (SOP1) into the semantic registry, preserving its existing decode domain and shader output. The move operand rule retains explicit VCC and EXEC half destinations. Part of #215.
|
||||
- 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.
|
||||
- Reuse up to 16 native Metal compute pipelines per context for repeated shader source and entry points. Pending dispatches retain their pipelines through completion, including after eviction. Dispatch profiles report zero library and pipeline setup time when a cached pipeline is reused. Closes #132.
|
||||
- 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.
|
||||
|
||||
### Fixed
|
||||
- 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 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
|
||||
- `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.
|
||||
@@ -80,12 +76,6 @@ 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 an MSVC decorated-name decoder (`xenora_import_gen::demangle`), and import manifests now show undecorated names for C++ imports that need manual engineering. Unsupported constructs return no result rather than a guess. Tests decode names mangled independently by clang for `x86_64-pc-windows-msvc`.
|
||||
|
||||
- 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. Writable guest memory is filled from a deterministic pattern so corpus bytes are reserved for dispatch. An earlier 300-second campaign's input and edge counts are withdrawn: that run exhausted each input while filling the 65,536-byte writable region and never reached the dispatch loop. After the harness fix, a local 300-second campaign on Apple Silicon (`scripts/fuzz.sh runtime_services 300`) ran 96,589 inputs (4,008 coverage edges, 9,940 features) without a crash; the first minutes also found a ~3.7 GiB `XMemAlloc` host OOM, which is now fixed by failing closed on overflowing sizes and routing mappings through the virtual allocation budget. 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.
|
||||
|
||||
- Added services that call guest code and continue when it returns. The import dispatcher can run a sequence of guest callbacks on a checked stack frame, verifying the Win64 nonvolatile registers after each one. The CRT uses this for `qsort`, `qsort_s`, `bsearch`, `bsearch_s`, `_initterm`, `_initterm_e`, onexit tables, `atexit` and `_cexit`. Kernel32 uses it for `InitOnceExecuteOnce` and `FlsFree` cleanup callbacks. Original guest comparators and initializers in a PE32+ fixture verify ordering, stop-on-failure and register preservation.
|
||||
|
||||
@@ -309,7 +309,7 @@ These require a Metal-capable Apple Silicon Mac.
|
||||
scripts/test-gpu.sh
|
||||
```
|
||||
|
||||
The native test suite enables Metal API and shader validation and tests the supported compute, rendering and texture paths. The full semantic-review batch defaults to a 300-second timeout; set `XENORA_SEMANTIC_TIMEOUT` to raise or lower it for a slower or faster host. On macOS, the script uses a Python 3 fallback when GNU `timeout` is unavailable.
|
||||
The native test suite enables Metal API and shader validation and tests the supported compute, rendering and texture paths. The full semantic-review batch defaults to a 300-second timeout; set `XENORA_SEMANTIC_TIMEOUT` to raise or lower it for a slower or faster host.
|
||||
|
||||
### Verify guest execution
|
||||
|
||||
|
||||
@@ -1,529 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Decoding of Microsoft Visual C++ decorated names, for diagnostics.
|
||||
//!
|
||||
//! Written from the publicly described decoration scheme: a leading `?`,
|
||||
//! `@`-terminated name fragments listed innermost first, single-digit name and
|
||||
//! type back-references, an access and storage code, a calling convention,
|
||||
//! the return type and the parameter list. Output follows the style of
|
||||
//! Microsoft's `undname` tool. Anything outside the supported subset returns
|
||||
//! `None` instead of a guess, so callers fall back to the decorated name.
|
||||
|
||||
const MAX_DEPTH: usize = 16;
|
||||
|
||||
/// The undecorated form of `symbol`, or `None` when it is not a decorated
|
||||
/// C++ name or uses an unsupported construct.
|
||||
pub fn demangle(symbol: &str) -> Option<String> {
|
||||
let mut parser = Parser {
|
||||
input: symbol.as_bytes(),
|
||||
position: 0,
|
||||
names: Vec::new(),
|
||||
types: Vec::new(),
|
||||
depth: 0,
|
||||
};
|
||||
let result = parser.symbol()?;
|
||||
(parser.position == parser.input.len()).then_some(result)
|
||||
}
|
||||
|
||||
/// A special name introduced by `?` and a code inside the qualified name.
|
||||
enum Special {
|
||||
Constructor,
|
||||
Destructor,
|
||||
Operator(&'static str),
|
||||
Vftable,
|
||||
}
|
||||
|
||||
struct Parser<'a> {
|
||||
input: &'a [u8],
|
||||
position: usize,
|
||||
names: Vec<String>,
|
||||
types: Vec<String>,
|
||||
depth: usize,
|
||||
}
|
||||
|
||||
impl Parser<'_> {
|
||||
fn peek(&self) -> Option<u8> {
|
||||
self.input.get(self.position).copied()
|
||||
}
|
||||
|
||||
fn next(&mut self) -> Option<u8> {
|
||||
let byte = self.peek()?;
|
||||
self.position += 1;
|
||||
Some(byte)
|
||||
}
|
||||
|
||||
fn eat(&mut self, byte: u8) -> bool {
|
||||
let found = self.peek() == Some(byte);
|
||||
if found {
|
||||
self.position += 1;
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
fn eat_str(&mut self, text: &str) -> bool {
|
||||
let found = self.input[self.position..].starts_with(text.as_bytes());
|
||||
if found {
|
||||
self.position += text.len();
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
fn symbol(&mut self) -> Option<String> {
|
||||
if !self.eat(b'?') {
|
||||
return None;
|
||||
}
|
||||
let (name, special) = self.qualified_name(true)?;
|
||||
match self.peek()? {
|
||||
b'0'..=b'4' => self.variable(&name),
|
||||
b'6' => {
|
||||
self.next();
|
||||
let qualifier = cv(self.next()?)?;
|
||||
self.eat(b'@');
|
||||
if !matches!(special, Some(Special::Vftable)) {
|
||||
return None;
|
||||
}
|
||||
Some(format!("{} {name}", qualifier.trim()))
|
||||
}
|
||||
_ => self.function(&name, special.as_ref()),
|
||||
}
|
||||
}
|
||||
|
||||
fn variable(&mut self, name: &str) -> Option<String> {
|
||||
let access = match self.next()? {
|
||||
b'0' => "private: static ",
|
||||
b'1' => "protected: static ",
|
||||
b'2' => "public: static ",
|
||||
_ => "",
|
||||
};
|
||||
let kind = self.data_type()?;
|
||||
self.eat(b'E');
|
||||
let qualifier = cv(self.next()?)?;
|
||||
Some(format!("{access}{kind}{qualifier} {name}"))
|
||||
}
|
||||
|
||||
fn function(&mut self, name: &str, special: Option<&Special>) -> Option<String> {
|
||||
let (access, member) = match self.next()? {
|
||||
b'A' | b'B' => ("private: ", true),
|
||||
b'C' | b'D' => ("private: static ", false),
|
||||
b'E' | b'F' => ("private: virtual ", true),
|
||||
b'I' | b'J' => ("protected: ", true),
|
||||
b'K' | b'L' => ("protected: static ", false),
|
||||
b'M' | b'N' => ("protected: virtual ", true),
|
||||
b'Q' | b'R' => ("public: ", true),
|
||||
b'S' | b'T' => ("public: static ", false),
|
||||
b'U' | b'V' => ("public: virtual ", true),
|
||||
b'Y' | b'Z' => ("", false),
|
||||
_ => return None,
|
||||
};
|
||||
let mut this = String::new();
|
||||
if member {
|
||||
let pointer64 = self.eat(b'E');
|
||||
this.push_str(cv(self.next()?)?.trim_start());
|
||||
if pointer64 {
|
||||
this.push_str(" __ptr64");
|
||||
}
|
||||
}
|
||||
let convention = match self.next()? {
|
||||
b'A' | b'B' => "__cdecl",
|
||||
b'C' | b'D' => "__pascal",
|
||||
b'E' | b'F' => "__thiscall",
|
||||
b'G' | b'H' => "__stdcall",
|
||||
b'I' | b'J' => "__fastcall",
|
||||
b'Q' => "__vectorcall",
|
||||
_ => return None,
|
||||
};
|
||||
let returns = if self.eat(b'@') {
|
||||
if !matches!(special, Some(Special::Constructor | Special::Destructor)) {
|
||||
return None;
|
||||
}
|
||||
String::new()
|
||||
} else {
|
||||
if self.eat(b'?') {
|
||||
cv(self.next()?)?;
|
||||
}
|
||||
format!("{} ", self.data_type()?)
|
||||
};
|
||||
let parameters = self.parameters()?;
|
||||
if !self.eat(b'Z') {
|
||||
return None;
|
||||
}
|
||||
Some(format!(
|
||||
"{access}{returns}{convention} {name}({parameters}){this}"
|
||||
))
|
||||
}
|
||||
|
||||
fn parameters(&mut self) -> Option<String> {
|
||||
if self.eat(b'X') {
|
||||
return Some("void".to_owned());
|
||||
}
|
||||
let mut parameters = Vec::new();
|
||||
loop {
|
||||
match self.peek()? {
|
||||
b'@' => {
|
||||
self.next();
|
||||
break;
|
||||
}
|
||||
b'Z' => {
|
||||
self.next();
|
||||
parameters.push("...".to_owned());
|
||||
break;
|
||||
}
|
||||
_ => {
|
||||
let start = self.position;
|
||||
let kind = self.data_type()?;
|
||||
if self.position - start > 1 && self.types.len() < 10 {
|
||||
self.types.push(kind.clone());
|
||||
}
|
||||
parameters.push(kind);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(parameters.join(","))
|
||||
}
|
||||
|
||||
/// Fragments up to `@`, joined outermost first.
|
||||
fn qualified_name(&mut self, allow_special: bool) -> Option<(String, Option<Special>)> {
|
||||
let mut special = None;
|
||||
let mut fragments = Vec::new();
|
||||
if allow_special
|
||||
&& self.peek() == Some(b'?')
|
||||
&& self.input.get(self.position + 1) != Some(&b'$')
|
||||
{
|
||||
self.next();
|
||||
special = Some(self.special()?);
|
||||
} else {
|
||||
fragments.push(self.fragment()?);
|
||||
}
|
||||
while !self.eat(b'@') {
|
||||
fragments.push(self.fragment()?);
|
||||
}
|
||||
fragments.reverse();
|
||||
let scope = fragments.join("::");
|
||||
let name = match &special {
|
||||
None => scope,
|
||||
Some(special) => {
|
||||
let class = || Some(fragments.last()?.split('<').next()?.to_owned());
|
||||
let leaf = match special {
|
||||
Special::Constructor => class()?,
|
||||
Special::Destructor => format!("~{}", class()?),
|
||||
Special::Operator(name) => name.to_string(),
|
||||
Special::Vftable => "`vftable'".to_owned(),
|
||||
};
|
||||
if scope.is_empty() {
|
||||
leaf
|
||||
} else {
|
||||
format!("{scope}::{leaf}")
|
||||
}
|
||||
}
|
||||
};
|
||||
Some((name, special))
|
||||
}
|
||||
|
||||
fn special(&mut self) -> Option<Special> {
|
||||
Some(match self.next()? {
|
||||
b'0' => Special::Constructor,
|
||||
b'1' => Special::Destructor,
|
||||
b'2' => Special::Operator("operator new"),
|
||||
b'3' => Special::Operator("operator delete"),
|
||||
b'4' => Special::Operator("operator="),
|
||||
b'8' => Special::Operator("operator=="),
|
||||
b'9' => Special::Operator("operator!="),
|
||||
b'A' => Special::Operator("operator[]"),
|
||||
b'R' => Special::Operator("operator()"),
|
||||
b'_' => match self.next()? {
|
||||
b'7' => Special::Vftable,
|
||||
b'U' => Special::Operator("operator new[]"),
|
||||
b'V' => Special::Operator("operator delete[]"),
|
||||
_ => return None,
|
||||
},
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn fragment(&mut self) -> Option<String> {
|
||||
if let Some(digit @ b'0'..=b'9') = self.peek() {
|
||||
self.next();
|
||||
return self.names.get(usize::from(digit - b'0')).cloned();
|
||||
}
|
||||
let fragment = if self.eat_str("?$") {
|
||||
self.template()?
|
||||
} else {
|
||||
self.identifier()?
|
||||
};
|
||||
if self.names.len() < 10 && !self.names.contains(&fragment) {
|
||||
self.names.push(fragment.clone());
|
||||
}
|
||||
Some(fragment)
|
||||
}
|
||||
|
||||
fn identifier(&mut self) -> Option<String> {
|
||||
let start = self.position;
|
||||
while self.peek()? != b'@' {
|
||||
let byte = self.next()?;
|
||||
if !(byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$') {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let text = std::str::from_utf8(&self.input[start..self.position]).ok()?;
|
||||
self.next();
|
||||
(!text.is_empty()).then(|| text.to_owned())
|
||||
}
|
||||
|
||||
/// `name@arguments@`, with back-references local to the argument list.
|
||||
fn template(&mut self) -> Option<String> {
|
||||
self.depth += 1;
|
||||
if self.depth > MAX_DEPTH {
|
||||
return None;
|
||||
}
|
||||
let outer_names = std::mem::take(&mut self.names);
|
||||
let outer_types = std::mem::take(&mut self.types);
|
||||
let name = self.identifier();
|
||||
if let Some(name) = &name {
|
||||
self.names.push(name.clone());
|
||||
}
|
||||
let mut arguments = Vec::new();
|
||||
let result = (|| {
|
||||
let name = name?;
|
||||
while !self.eat(b'@') {
|
||||
let start = self.position;
|
||||
let argument = if self.eat(b'$') {
|
||||
if !self.eat(b'0') {
|
||||
return None;
|
||||
}
|
||||
self.number()?.to_string()
|
||||
} else {
|
||||
self.data_type()?
|
||||
};
|
||||
if self.position - start > 1 && self.types.len() < 10 {
|
||||
self.types.push(argument.clone());
|
||||
}
|
||||
arguments.push(argument);
|
||||
}
|
||||
let joined = arguments.join(",");
|
||||
let close = if joined.ends_with('>') { " >" } else { ">" };
|
||||
Some(format!("{name}<{joined}{close}"))
|
||||
})();
|
||||
self.names = outer_names;
|
||||
self.types = outer_types;
|
||||
self.depth -= 1;
|
||||
result
|
||||
}
|
||||
|
||||
/// `0`–`9` encode 1–10; otherwise hexadecimal digits `A`–`P` end with `@`.
|
||||
fn number(&mut self) -> Option<i64> {
|
||||
let negative = self.eat(b'?');
|
||||
let value = match self.next()? {
|
||||
digit @ b'0'..=b'9' => i64::from(digit - b'0') + 1,
|
||||
b'@' => 0,
|
||||
mut digit => {
|
||||
let mut value: i64 = 0;
|
||||
loop {
|
||||
if !(b'A'..=b'P').contains(&digit) {
|
||||
return None;
|
||||
}
|
||||
value = value
|
||||
.checked_mul(16)?
|
||||
.checked_add(i64::from(digit - b'A'))?;
|
||||
digit = self.next()?;
|
||||
if digit == b'@' {
|
||||
break value;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
Some(if negative { -value } else { value })
|
||||
}
|
||||
|
||||
fn data_type(&mut self) -> Option<String> {
|
||||
self.depth += 1;
|
||||
if self.depth > MAX_DEPTH {
|
||||
return None;
|
||||
}
|
||||
let result = self.data_type_inner();
|
||||
self.depth -= 1;
|
||||
result
|
||||
}
|
||||
|
||||
fn data_type_inner(&mut self) -> Option<String> {
|
||||
let code = self.next()?;
|
||||
let primitive = match code {
|
||||
b'X' => "void",
|
||||
b'C' => "signed char",
|
||||
b'D' => "char",
|
||||
b'E' => "unsigned char",
|
||||
b'F' => "short",
|
||||
b'G' => "unsigned short",
|
||||
b'H' => "int",
|
||||
b'I' => "unsigned int",
|
||||
b'J' => "long",
|
||||
b'K' => "unsigned long",
|
||||
b'M' => "float",
|
||||
b'N' => "double",
|
||||
b'O' => "long double",
|
||||
b'0'..=b'9' => return self.types.get(usize::from(code - b'0')).cloned(),
|
||||
b'_' => match self.next()? {
|
||||
b'J' => "__int64",
|
||||
b'K' => "unsigned __int64",
|
||||
b'N' => "bool",
|
||||
b'W' => "wchar_t",
|
||||
b'S' => "char16_t",
|
||||
b'U' => "char32_t",
|
||||
b'Q' => "char8_t",
|
||||
_ => return None,
|
||||
},
|
||||
b'V' => return Some(format!("class {}", self.qualified_name(false)?.0)),
|
||||
b'U' => return Some(format!("struct {}", self.qualified_name(false)?.0)),
|
||||
b'T' => return Some(format!("union {}", self.qualified_name(false)?.0)),
|
||||
b'W' => {
|
||||
if !self.eat(b'4') {
|
||||
return None;
|
||||
}
|
||||
return Some(format!("enum {}", self.qualified_name(false)?.0));
|
||||
}
|
||||
b'P' | b'Q' | b'R' | b'S' => return self.indirection("*", pointer_cv(code)),
|
||||
b'A' => return self.indirection("&", ""),
|
||||
b'B' => return self.indirection("&", " volatile"),
|
||||
b'$' => {
|
||||
if self.eat_str("$Q") {
|
||||
return self.indirection("&&", "");
|
||||
}
|
||||
if self.eat_str("$T") {
|
||||
return Some("std::nullptr_t".to_owned());
|
||||
}
|
||||
return None;
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
Some(primitive.to_owned())
|
||||
}
|
||||
|
||||
/// A pointer or reference: an optional `E` for `__ptr64`, the pointee's
|
||||
/// qualifiers, then the pointee.
|
||||
fn indirection(&mut self, symbol: &str, own: &str) -> Option<String> {
|
||||
let pointer64 = self.eat(b'E');
|
||||
let pointee_cv = cv(self.next()?)?;
|
||||
let pointee = self.data_type()?;
|
||||
let width = if pointer64 { " __ptr64" } else { "" };
|
||||
Some(format!("{pointee}{pointee_cv} {symbol}{own}{width}"))
|
||||
}
|
||||
}
|
||||
|
||||
fn cv(code: u8) -> Option<&'static str> {
|
||||
Some(match code {
|
||||
b'A' => "",
|
||||
b'B' => " const",
|
||||
b'C' => " volatile",
|
||||
b'D' => " const volatile",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn pointer_cv(code: u8) -> &'static str {
|
||||
match code {
|
||||
b'Q' => " const",
|
||||
b'R' => " volatile",
|
||||
b'S' => " const volatile",
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::demangle;
|
||||
|
||||
#[test]
|
||||
fn decodes_global_functions_and_operators() {
|
||||
for (decorated, expected) in [
|
||||
("?foo@@YAXXZ", "void __cdecl foo(void)"),
|
||||
("?foo@@YAHH@Z", "int __cdecl foo(int)"),
|
||||
("?f@@YAXPEBD@Z", "void __cdecl f(char const * __ptr64)"),
|
||||
("?f@@YAXHZZ", "void __cdecl f(int,...)"),
|
||||
(
|
||||
"??2@YAPEAX_K@Z",
|
||||
"void * __ptr64 __cdecl operator new(unsigned __int64)",
|
||||
),
|
||||
(
|
||||
"??3@YAXPEAX@Z",
|
||||
"void __cdecl operator delete(void * __ptr64)",
|
||||
),
|
||||
(
|
||||
"??_U@YAPEAX_K@Z",
|
||||
"void * __ptr64 __cdecl operator new[](unsigned __int64)",
|
||||
),
|
||||
(
|
||||
"?_Xlength_error@std@@YAXPEBD@Z",
|
||||
"void __cdecl std::_Xlength_error(char const * __ptr64)",
|
||||
),
|
||||
("?g@@YA_N_J0@Z", "bool __cdecl g(__int64,__int64)"),
|
||||
] {
|
||||
assert_eq!(
|
||||
demangle(decorated).as_deref(),
|
||||
Some(expected),
|
||||
"{decorated}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_members_constructors_and_data() {
|
||||
for (decorated, expected) in [
|
||||
(
|
||||
"?bar@Foo@@QEAAXH@Z",
|
||||
"public: void __cdecl Foo::bar(int) __ptr64",
|
||||
),
|
||||
(
|
||||
"?get@Foo@@QEBAHXZ",
|
||||
"public: int __cdecl Foo::get(void)const __ptr64",
|
||||
),
|
||||
("??0Foo@@QEAA@XZ", "public: __cdecl Foo::Foo(void) __ptr64"),
|
||||
(
|
||||
"??1Foo@@UEAA@XZ",
|
||||
"public: virtual __cdecl Foo::~Foo(void) __ptr64",
|
||||
),
|
||||
(
|
||||
"?make@Foo@@SAPEAV1@XZ",
|
||||
"public: static class Foo * __ptr64 __cdecl Foo::make(void)",
|
||||
),
|
||||
("?x@ns@@3HA", "int ns::x"),
|
||||
("?count@Foo@@2HB", "public: static int const Foo::count"),
|
||||
("??_7type_info@@6B@", "const type_info::`vftable'"),
|
||||
] {
|
||||
assert_eq!(
|
||||
demangle(decorated).as_deref(),
|
||||
Some(expected),
|
||||
"{decorated}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_templates_and_back_references() {
|
||||
assert_eq!(
|
||||
demangle("?g@@YAXAEAV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z")
|
||||
.as_deref(),
|
||||
Some(
|
||||
"void __cdecl g(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > & __ptr64)"
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
demangle("?h@@YAXV?$array@H$0BA@@std@@@Z").as_deref(),
|
||||
Some("void __cdecl h(class std::array<int,16>)")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_undecorated_and_unsupported_names() {
|
||||
for symbol in [
|
||||
"malloc",
|
||||
"",
|
||||
"?",
|
||||
"?foo@@",
|
||||
"?foo@@YAXXZtrailing",
|
||||
"??_R0?AVtype_info@@@8",
|
||||
"?f@@YAXP6AXXZ@Z",
|
||||
&format!("?f@@YAX{}@Z", "PEA".repeat(40) + "H"),
|
||||
] {
|
||||
assert_eq!(demangle(symbol), None, "{symbol}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,6 @@
|
||||
pub mod apiset;
|
||||
pub mod classify;
|
||||
pub mod codegen;
|
||||
pub mod demangle;
|
||||
pub mod ingest;
|
||||
pub mod manifest;
|
||||
pub mod metadata;
|
||||
@@ -38,7 +37,6 @@ pub mod verify;
|
||||
pub use apiset::{get_api_sets_for_canonical, resolve_api_set_canonical};
|
||||
pub use classify::{Classification, SymbolDb};
|
||||
pub use codegen::{GeneratedFiles, generate};
|
||||
pub use demangle::demangle;
|
||||
pub use ingest::{ingest_header_file, ingest_standard_system_headers};
|
||||
pub use manifest::Manifest;
|
||||
pub use metadata::{AbiType, CallingConvention, FunctionSignature, MetadataCatalog};
|
||||
|
||||
@@ -166,13 +166,7 @@ impl Manifest {
|
||||
if let Classification::Manual { reason } | Classification::Unsupported { reason } =
|
||||
&e.classification
|
||||
{
|
||||
match crate::demangle(&e.symbol) {
|
||||
Some(name) => md.push_str(&format!(
|
||||
"- `{}!{}` (`{name}`) — {reason}\n",
|
||||
e.module, e.symbol
|
||||
)),
|
||||
None => md.push_str(&format!("- `{}!{}` — {reason}\n", e.module, e.symbol)),
|
||||
}
|
||||
md.push_str(&format!("- `{}!{}` — {reason}\n", e.module, e.symbol));
|
||||
}
|
||||
}
|
||||
md
|
||||
|
||||
@@ -1,109 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Decorated names produced by an independent mangler: Apple clang 21 with
|
||||
//! `-target x86_64-pc-windows-msvc -S` on the declarations quoted beside each
|
||||
//! case. Expected strings restate those declarations in `undname` style; they
|
||||
//! are not taken from the decoder.
|
||||
|
||||
use xenora_import_gen::demangle;
|
||||
|
||||
#[test]
|
||||
fn clang_msvc_manglings_decode_to_their_declarations() {
|
||||
for (decorated, expected) in [
|
||||
// void foo();
|
||||
("?foo@@YAXXZ", "void __cdecl foo(void)"),
|
||||
// int foo2(int);
|
||||
("?foo2@@YAHH@Z", "int __cdecl foo2(int)"),
|
||||
// void f(const char*);
|
||||
("?f@@YAXPEBD@Z", "void __cdecl f(char const * __ptr64)"),
|
||||
// void fv(int, ...);
|
||||
("?fv@@YAXHZZ", "void __cdecl fv(int,...)"),
|
||||
// bool g(long long, long long);
|
||||
("?g@@YA_N_J0@Z", "bool __cdecl g(__int64,__int64)"),
|
||||
// namespace std { void _Xlength_error(const char*); }
|
||||
(
|
||||
"?_Xlength_error@std@@YAXPEBD@Z",
|
||||
"void __cdecl std::_Xlength_error(char const * __ptr64)",
|
||||
),
|
||||
// struct Foo { void bar(int); };
|
||||
(
|
||||
"?bar@Foo@@QEAAXH@Z",
|
||||
"public: void __cdecl Foo::bar(int) __ptr64",
|
||||
),
|
||||
// struct Foo { int get() const; };
|
||||
(
|
||||
"?get@Foo@@QEBAHXZ",
|
||||
"public: int __cdecl Foo::get(void)const __ptr64",
|
||||
),
|
||||
// struct Foo { Foo(); };
|
||||
("??0Foo@@QEAA@XZ", "public: __cdecl Foo::Foo(void) __ptr64"),
|
||||
// struct Foo { static Foo* make(); };
|
||||
(
|
||||
"?make@Foo@@SAPEAU1@XZ",
|
||||
"public: static struct Foo * __ptr64 __cdecl Foo::make(void)",
|
||||
),
|
||||
// void use(Foo&);
|
||||
(
|
||||
"?use@@YAXAEAUFoo@@@Z",
|
||||
"void __cdecl use(struct Foo & __ptr64)",
|
||||
),
|
||||
// namespace ns { int x; }
|
||||
("?x@ns@@3HA", "int ns::x"),
|
||||
// Global operator new(size_t) and sized operator delete(void*, size_t).
|
||||
(
|
||||
"??2@YAPEAX_K@Z",
|
||||
"void * __ptr64 __cdecl operator new(unsigned __int64)",
|
||||
),
|
||||
(
|
||||
"??3@YAXPEAX_K@Z",
|
||||
"void __cdecl operator delete(void * __ptr64,unsigned __int64)",
|
||||
),
|
||||
// void gs(std::basic_string<char, std::char_traits<char>, std::allocator<char>>&);
|
||||
(
|
||||
"?gs@@YAXAEAV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z",
|
||||
"void __cdecl gs(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > & __ptr64)",
|
||||
),
|
||||
// void h(std::array<int, 16>);
|
||||
(
|
||||
"?h@@YAXV?$array@H$0BA@@std@@@Z",
|
||||
"void __cdecl h(class std::array<int,16>)",
|
||||
),
|
||||
] {
|
||||
assert_eq!(
|
||||
demangle(decorated).as_deref(),
|
||||
Some(expected),
|
||||
"{decorated}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_clang_manglings_are_reported_rather_than_guessed() {
|
||||
// void (*keep[])(): function pointer types are outside the supported subset.
|
||||
assert_eq!(demangle("?keep@@3PAP6AXXZA"), None);
|
||||
// A compiler-generated cleanup funclet nested in another function's scope.
|
||||
assert_eq!(demangle("?dtor$2@?0??use@@YAXAEAUFoo@@@Z@4HA"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manifests_show_undecorated_names_for_unclassified_cxx_imports() {
|
||||
use xenora_import_gen::{ImportRecord, Manifest, SymbolDb};
|
||||
let record = |symbol: &str| ImportRecord {
|
||||
module: "msvcp140.dll".to_owned(),
|
||||
symbol: symbol.to_owned(),
|
||||
ordinal: None,
|
||||
iat_rva: 0x2000,
|
||||
};
|
||||
let manifest = Manifest::build(
|
||||
&[
|
||||
record("?_Xlength_error@std@@YAXPEBD@Z"),
|
||||
record("?keep@@3PAP6AXXZA"),
|
||||
],
|
||||
&SymbolDb::builtin(),
|
||||
);
|
||||
let markdown = manifest.render_markdown();
|
||||
assert!(markdown.contains(
|
||||
"- `msvcp140.dll!?_Xlength_error@std@@YAXPEBD@Z` (`void __cdecl std::_Xlength_error(char const * __ptr64)`) —"
|
||||
));
|
||||
assert!(markdown.contains("- `msvcp140.dll!?keep@@3PAP6AXXZA` —"));
|
||||
}
|
||||
@@ -25,7 +25,3 @@ xenora-shader = { path = "../shader" }
|
||||
[[bench]]
|
||||
name = "dbt_bench"
|
||||
harness = false
|
||||
|
||||
[[bench]]
|
||||
name = "service_dispatch"
|
||||
harness = false
|
||||
@@ -1,225 +0,0 @@
|
||||
// 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));
|
||||
}
|
||||
}
|
||||
@@ -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(
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -439,24 +439,20 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc<Serv
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let page_size = 4096usize;
|
||||
// Huge or overflowing sizes fail closed. Unbounded map_region would
|
||||
// try to malloc multi-gigabyte host buffers (libFuzzer OOM on
|
||||
// ~3.7 GiB); route through the virtual budget instead.
|
||||
let Some(aligned_size) = size
|
||||
.checked_add(page_size - 1)
|
||||
.map(|rounded| rounded & !(page_size - 1))
|
||||
.filter(|&aligned| aligned != 0)
|
||||
else {
|
||||
return Ok(0);
|
||||
};
|
||||
let page_size = 4096;
|
||||
let aligned_size = (size + page_size - 1) & !(page_size - 1);
|
||||
let alloc_addr = s
|
||||
.next_alloc_addr
|
||||
.fetch_add(aligned_size as u64, Ordering::SeqCst);
|
||||
|
||||
Ok(mem
|
||||
.map_virtual_allocation(alloc_addr, aligned_size, MemoryPermissions::READ_WRITE)
|
||||
.unwrap_or(0))
|
||||
if mem
|
||||
.map_region(alloc_addr, aligned_size, MemoryPermissions::READ_WRITE)
|
||||
.is_err()
|
||||
{
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
Ok(alloc_addr)
|
||||
};
|
||||
registry.register("xmem.dll", "XMemAlloc", handler);
|
||||
registry.set_status("xmem.dll", "XMemAlloc", ServiceStatus::Partial);
|
||||
|
||||
@@ -45,38 +45,11 @@ fn string_length(
|
||||
limit: u64,
|
||||
unit: StringUnit,
|
||||
) -> Result<u64, ExitReason> {
|
||||
const BLOCK: u64 = 256;
|
||||
let budget = SCAN_BUDGET / unit.width();
|
||||
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);
|
||||
}
|
||||
for offset in 0..limit.min(budget) {
|
||||
if unit.read(memory, address, offset)? == 0 {
|
||||
return Ok(offset);
|
||||
}
|
||||
offset += count;
|
||||
}
|
||||
if limit <= budget {
|
||||
return Ok(limit);
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,644 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Seeded sequences of original x86-64 instructions for issue #74.
|
||||
//!
|
||||
//! Expected states follow the Intel SDM (Vol. 1, §§3.4.1 and 3.4.3,
|
||||
//! Vol. 2, ADD, SUB, CMP, XOR, MOV, Jcc, CALL, RET, DEC, MOVDQU, PADDB,
|
||||
//! PSUBW and PXOR, and Vol. 3A, §7.15, Page-Fault Exception). The oracles work from arithmetic operands, branch
|
||||
//! predicates, array indices and vector lanes. They never decode the emitted
|
||||
//! bytes or use Xenora's instruction or flag helpers.
|
||||
//!
|
||||
//! <https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html>
|
||||
//!
|
||||
//! The x86 bytes run as guest code through a synthetic memory map and end at
|
||||
//! Xenora's HLT sentinel. To replay a failure, use the printed test name and
|
||||
//! XENORA_CPU_DIFFERENTIAL_CASE index. For example:
|
||||
//!
|
||||
//! ```sh
|
||||
//! XENORA_CPU_DIFFERENTIAL_CASE=0 cargo test --locked -p xenora-loader \
|
||||
//! --test cpu_differential seeded_register_sequences -- --exact
|
||||
//! ```
|
||||
//!
|
||||
//! The seed and bytes are printed for reproducing the program outside this
|
||||
//! harness as well.
|
||||
|
||||
use xenora_loader::cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, RFlags, Register};
|
||||
use xenora_loader::dbt::DbtEngine;
|
||||
use xenora_loader::memory::{GuestMemory, MemoryError, MemoryPermissions};
|
||||
|
||||
const CODE: u64 = 0x40_0000;
|
||||
const DATA: u64 = 0x50_0000;
|
||||
const DATA_LEN: usize = 192;
|
||||
const STACK_TOP: u64 = DATA + DATA_LEN as u64;
|
||||
const BUDGET: usize = 128;
|
||||
const TEST_SEED: u64 = 0x74_da7a_c0de_ba5e;
|
||||
|
||||
// SplitMix64 with a fresh stream per case. Changing the corpus order does not
|
||||
// affect replay of an existing index.
|
||||
struct Random(u64);
|
||||
|
||||
impl Random {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15);
|
||||
let mut word = self.0;
|
||||
word = (word ^ (word >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
|
||||
word = (word ^ (word >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
|
||||
word ^ (word >> 31)
|
||||
}
|
||||
|
||||
fn below(&mut self, end: usize) -> usize {
|
||||
(self.next() % end as u64) as usize
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct State {
|
||||
cpu: CpuState,
|
||||
data: [u8; DATA_LEN],
|
||||
af_defined: bool,
|
||||
}
|
||||
|
||||
impl State {
|
||||
fn seeded(random: &mut Random) -> Self {
|
||||
let mut cpu = CpuState::new(CODE, STACK_TOP);
|
||||
cpu.gpr = std::array::from_fn(|_| random.next());
|
||||
cpu.set(Register::Rsp, STACK_TOP);
|
||||
cpu.xmm =
|
||||
std::array::from_fn(|_| (u128::from(random.next()) << 64) | u128::from(random.next()));
|
||||
let flags = random.next();
|
||||
cpu.flags = RFlags {
|
||||
cf: flags & 1 != 0,
|
||||
pf: flags & 2 != 0,
|
||||
af: flags & 4 != 0,
|
||||
zf: flags & 8 != 0,
|
||||
sf: flags & 16 != 0,
|
||||
of: flags & 32 != 0,
|
||||
};
|
||||
cpu.df = flags & 64 != 0;
|
||||
cpu.fs_base = DATA;
|
||||
cpu.gs_base = DATA + 64;
|
||||
Self {
|
||||
cpu,
|
||||
data: std::array::from_fn(|_| random.next() as u8),
|
||||
af_defined: true,
|
||||
}
|
||||
}
|
||||
|
||||
fn checkpoint(&mut self, trace: &mut Vec<Self>, offset: usize) {
|
||||
self.cpu.rip = CODE + offset as u64;
|
||||
trace.push(self.clone());
|
||||
}
|
||||
|
||||
fn word(&self, offset: usize) -> u64 {
|
||||
u64::from_le_bytes(self.data[offset..offset + 8].try_into().unwrap())
|
||||
}
|
||||
|
||||
fn put_word(&mut self, offset: usize, value: u64) {
|
||||
self.data[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
struct Case {
|
||||
code: Vec<u8>,
|
||||
initial: State,
|
||||
// State after each attempted instruction, including the terminal instruction.
|
||||
trace: Vec<State>,
|
||||
native_only: bool,
|
||||
exit: ExitReason,
|
||||
}
|
||||
|
||||
impl Case {
|
||||
fn memory(&self) -> GuestMemory {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
CODE,
|
||||
self.code.len(),
|
||||
MemoryPermissions::READ_EXECUTE,
|
||||
&self.code,
|
||||
)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
DATA,
|
||||
DATA_LEN,
|
||||
MemoryPermissions::READ_WRITE,
|
||||
&self.initial.data,
|
||||
)
|
||||
.unwrap();
|
||||
memory
|
||||
}
|
||||
|
||||
fn verify(&self, id: &str) {
|
||||
let steps = self.trace.len();
|
||||
assert!(steps < BUDGET);
|
||||
let compare = |engine: &str,
|
||||
result: ExecutionResult,
|
||||
memory: &GuestMemory,
|
||||
budget: usize,
|
||||
offset: usize| {
|
||||
let steps = (steps - offset).min(budget);
|
||||
let expected = &self.trace[offset + steps - 1];
|
||||
let label = || {
|
||||
let start_rip = if offset == 0 {
|
||||
self.initial.cpu.rip
|
||||
} else {
|
||||
self.trace[offset - 1].cpu.rip
|
||||
};
|
||||
format!(
|
||||
"{id} {engine} from {start_rip:#x}, after {} guest steps, bytes {:02x?}",
|
||||
offset + steps,
|
||||
self.code
|
||||
)
|
||||
};
|
||||
let finished = offset + steps == self.trace.len();
|
||||
let exit = if finished {
|
||||
self.exit
|
||||
} else {
|
||||
ExitReason::StepLimitExceeded
|
||||
};
|
||||
let retired = steps - usize::from(finished && self.exit != ExitReason::Halt);
|
||||
assert_eq!(result.exit_reason, exit, "{}", label());
|
||||
assert_eq!(result.instructions_executed, retired, "{}", label());
|
||||
let mut actual = result.final_state;
|
||||
if !expected.af_defined {
|
||||
actual.flags.af = expected.cpu.flags.af;
|
||||
}
|
||||
assert_eq!(actual, expected.cpu, "{}", label());
|
||||
let mut data = [0; DATA_LEN];
|
||||
memory.read_bytes(DATA, &mut data).unwrap();
|
||||
if let Some(index) = data.iter().zip(expected.data).position(|(&a, b)| a != b) {
|
||||
panic!(
|
||||
"{}: guest byte at {:#x}: got {:#04x}, expected {:#04x}",
|
||||
label(),
|
||||
DATA + index as u64,
|
||||
data[index],
|
||||
expected.data[index]
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
let mut stepped = DbtEngine::new(128 * 1024).unwrap();
|
||||
let mut interpreted_memory = self.memory();
|
||||
let mut translated_memory = self.memory();
|
||||
let mut interpreted_cpu = self.initial.cpu.clone();
|
||||
let mut translated_cpu = self.initial.cpu.clone();
|
||||
// Check the first divergent retired instruction before testing full
|
||||
// blocks. Each engine continues from its own state at every step.
|
||||
for offset in 0..steps {
|
||||
let result = Interpreter::new(interpreted_cpu, &mut interpreted_memory, 1).run();
|
||||
interpreted_cpu = result.final_state.clone();
|
||||
compare(
|
||||
"interpreter (1 step)",
|
||||
result,
|
||||
&interpreted_memory,
|
||||
1,
|
||||
offset,
|
||||
);
|
||||
|
||||
let result = stepped.run(&mut translated_cpu, &mut translated_memory, 1);
|
||||
compare("DBT (1 step)", result, &translated_memory, 1, offset);
|
||||
}
|
||||
|
||||
// Exercise native block lowering and then reuse those blocks with a
|
||||
// fresh copy of the guest input and memory at the same addresses.
|
||||
let mut dbt = DbtEngine::new(128 * 1024).unwrap();
|
||||
let mut memory = self.memory();
|
||||
let result = Interpreter::new(self.initial.cpu.clone(), &mut memory, BUDGET).run();
|
||||
compare("interpreter", result, &memory, BUDGET, 0);
|
||||
let mut run_full = |engine| {
|
||||
let mut memory = self.memory();
|
||||
let result = dbt.run(&mut self.initial.cpu.clone(), &mut memory, BUDGET);
|
||||
compare(engine, result, &memory, BUDGET, 0);
|
||||
dbt.metrics
|
||||
};
|
||||
let cold = run_full("DBT (cold)");
|
||||
let cached = run_full("DBT (cached)");
|
||||
assert!(cold.blocks_compiled > 0, "{id}");
|
||||
assert_eq!(cold.blocks_compiled, cached.blocks_compiled, "{id}");
|
||||
assert!(cached.cache_hits > cold.cache_hits, "{id}");
|
||||
assert!(cached.dbt_dispatches > cold.dbt_dispatches, "{id}");
|
||||
|
||||
// These budgets cut the longer programs around a 16-instruction
|
||||
// native block boundary, including a resume from the truncated block.
|
||||
for budget in [15, 16, 17].into_iter().filter(|&budget| budget < steps) {
|
||||
let mut memory = self.memory();
|
||||
let mut cpu = self.initial.cpu.clone();
|
||||
let result = dbt.run(&mut cpu, &mut memory, budget);
|
||||
compare("DBT (limited)", result, &memory, budget, 0);
|
||||
let result = dbt.run(&mut cpu, &mut memory, BUDGET);
|
||||
compare("DBT (resumed)", result, &memory, BUDGET, budget);
|
||||
}
|
||||
|
||||
if self.native_only {
|
||||
assert_eq!(dbt.metrics.interpreter_fallbacks, 0, "{id}");
|
||||
assert_eq!(stepped.metrics.interpreter_fallbacks, 0, "{id}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Alu {
|
||||
Add,
|
||||
Sub,
|
||||
Compare,
|
||||
Xor,
|
||||
Move,
|
||||
}
|
||||
|
||||
impl Alu {
|
||||
const OPS: [Self; 5] = [Self::Add, Self::Sub, Self::Compare, Self::Xor, Self::Move];
|
||||
|
||||
// SDM Vol. 2, §2.1 and the r/m,reg forms for each instruction. A bare
|
||||
// REX prefix selects SPL/BPL/SIL/DIL instead of the high byte registers.
|
||||
fn encode(self, code: &mut Vec<u8>, bits: u32, dst: usize, src: usize) {
|
||||
if bits == 16 {
|
||||
code.push(0x66);
|
||||
}
|
||||
let rex = 0x40 | (u8::from(bits == 64) << 3) | ((src as u8 >> 3) << 2) | (dst as u8 >> 3);
|
||||
if rex != 0x40 || (bits == 8 && (src >= 4 || dst >= 4)) {
|
||||
code.push(rex);
|
||||
}
|
||||
let byte_opcode = match self {
|
||||
Self::Add => 0x00,
|
||||
Self::Sub => 0x28,
|
||||
Self::Compare => 0x38,
|
||||
Self::Xor => 0x30,
|
||||
Self::Move => 0x88,
|
||||
};
|
||||
code.extend([
|
||||
byte_opcode | u8::from(bits != 8),
|
||||
0xc0 | ((src as u8 & 7) << 3) | (dst as u8 & 7),
|
||||
]);
|
||||
}
|
||||
|
||||
fn expect(self, state: &mut State, bits: u32, dst: usize, src: usize) {
|
||||
let mask = u64::MAX >> (64 - bits);
|
||||
let left = state.cpu.gpr[dst] & mask;
|
||||
let right = state.cpu.gpr[src] & mask;
|
||||
let result = match self {
|
||||
Self::Move => right,
|
||||
Self::Xor => {
|
||||
let result = left ^ right;
|
||||
state.cpu.flags = result_flags(result, bits);
|
||||
state.af_defined = false;
|
||||
result
|
||||
}
|
||||
Self::Add | Self::Compare | Self::Sub => {
|
||||
let (result, flags) = arithmetic(left, right, bits, matches!(self, Self::Add));
|
||||
state.cpu.flags = flags;
|
||||
state.af_defined = true;
|
||||
result
|
||||
}
|
||||
};
|
||||
if !matches!(self, Self::Compare) {
|
||||
state.cpu.gpr[dst] = if bits >= 32 {
|
||||
result
|
||||
} else {
|
||||
(state.cpu.gpr[dst] & !mask) | result
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn result_flags(result: u64, bits: u32) -> RFlags {
|
||||
RFlags {
|
||||
zf: result == 0,
|
||||
sf: result >> (bits - 1) == 1,
|
||||
pf: (result as u8).count_ones().is_multiple_of(2),
|
||||
..RFlags::default()
|
||||
}
|
||||
}
|
||||
|
||||
// Carry, auxiliary carry and signed overflow are derived by separate
|
||||
// widened calculations. The exact signed result determines overflow.
|
||||
fn arithmetic(left: u64, right: u64, bits: u32, add: bool) -> (u64, RFlags) {
|
||||
let modulus = 1i128 << bits;
|
||||
let signed = |word: u64| {
|
||||
let word = i128::from(word);
|
||||
if word >= modulus / 2 {
|
||||
word - modulus
|
||||
} else {
|
||||
word
|
||||
}
|
||||
};
|
||||
let operation = |a: i128, b: i128| if add { a + b } else { a - b };
|
||||
let wide = operation(i128::from(left), i128::from(right));
|
||||
let result = wide.rem_euclid(modulus) as u64;
|
||||
let mut flags = result_flags(result, bits);
|
||||
flags.cf = !(0..modulus).contains(&wide);
|
||||
let nibble = operation(i128::from(left & 15), i128::from(right & 15));
|
||||
flags.af = !(0..16).contains(&nibble);
|
||||
let signed_result = operation(signed(left), signed(right));
|
||||
flags.of = !(-modulus / 2..modulus / 2).contains(&signed_result);
|
||||
(result, flags)
|
||||
}
|
||||
|
||||
fn seeded_cases(
|
||||
test: &str,
|
||||
family: u64,
|
||||
count: usize,
|
||||
make_case: impl Fn(usize, &mut Random) -> Case,
|
||||
) {
|
||||
let selected = std::env::var("XENORA_CPU_DIFFERENTIAL_CASE")
|
||||
.ok()
|
||||
.map(|text| {
|
||||
let index = text
|
||||
.parse::<usize>()
|
||||
.expect("XENORA_CPU_DIFFERENTIAL_CASE must be a decimal case index");
|
||||
assert!(index < count, "{test} has case indices 0..{count}");
|
||||
index
|
||||
});
|
||||
for index in selected.map_or(0..count, |index| index..index + 1) {
|
||||
let seed = TEST_SEED ^ (family << 48) ^ index as u64;
|
||||
let case = make_case(index, &mut Random(seed));
|
||||
case.verify(&format!(
|
||||
"{test}: XENORA_CPU_DIFFERENTIAL_CASE={index} (seed {seed:#018x})"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeded_register_sequences() {
|
||||
const WIDTHS: [u32; 4] = [8, 16, 32, 64];
|
||||
seeded_cases("seeded_register_sequences", 1, 240, |index, random| {
|
||||
let mixed_widths = index >= 160;
|
||||
let bits = WIDTHS[index % 4];
|
||||
let edges = [
|
||||
0,
|
||||
1,
|
||||
15,
|
||||
16,
|
||||
(1u64 << (bits - 1)) - 1,
|
||||
1 << (bits - 1),
|
||||
u64::MAX,
|
||||
];
|
||||
let mut initial = State::seeded(random);
|
||||
// Keep random high bits when the operand is narrower than the GPR.
|
||||
let mask = u64::MAX >> (64 - bits);
|
||||
for reg in [0, 1, 2, 3, 8, 9, 10, 11] {
|
||||
let edge = edges[random.below(edges.len())];
|
||||
initial.cpu.gpr[reg] = (initial.cpu.gpr[reg] & !mask) | (edge & mask);
|
||||
}
|
||||
let mut state = initial.clone();
|
||||
let mut code = Vec::new();
|
||||
let mut trace = Vec::new();
|
||||
for step in 0..24 {
|
||||
let bits = if mixed_widths {
|
||||
WIDTHS[(index + step) % WIDTHS.len()]
|
||||
} else {
|
||||
bits
|
||||
};
|
||||
let op = Alu::OPS[random.below(Alu::OPS.len())];
|
||||
let dst = random.below(16);
|
||||
let src = random.below(16);
|
||||
op.encode(&mut code, bits, dst, src);
|
||||
op.expect(&mut state, bits, dst, src);
|
||||
state.checkpoint(&mut trace, code.len());
|
||||
}
|
||||
code.push(0xf4);
|
||||
state.checkpoint(&mut trace, code.len());
|
||||
Case {
|
||||
code,
|
||||
initial,
|
||||
trace,
|
||||
native_only: !mixed_widths && bits >= 32,
|
||||
exit: ExitReason::Halt,
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn branch_predicate(condition: usize, flags: RFlags) -> bool {
|
||||
let base = [
|
||||
flags.of,
|
||||
flags.cf,
|
||||
flags.zf,
|
||||
flags.cf || flags.zf,
|
||||
flags.sf,
|
||||
flags.pf,
|
||||
flags.sf != flags.of,
|
||||
flags.zf || flags.sf != flags.of,
|
||||
][condition / 2];
|
||||
base ^ !condition.is_multiple_of(2)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeded_compare_branch_pairs() {
|
||||
seeded_cases("seeded_compare_branch_pairs", 2, 128, |index, random| {
|
||||
let condition = index % 16;
|
||||
let taken = index / 16 % 2 != 0;
|
||||
let bits = [32, 64][index / 32 % 2];
|
||||
let near = index >= 64;
|
||||
let sign = 1u64 << (bits - 1);
|
||||
let boundary = [0, 1, 2, sign - 1, sign, sign | 1, (sign - 1) | sign];
|
||||
let pairs = boundary
|
||||
.into_iter()
|
||||
.flat_map(|left| boundary.map(|right| (left, right)));
|
||||
let eligible: Vec<_> = pairs
|
||||
.filter(|&(left, right)| {
|
||||
branch_predicate(condition, arithmetic(left, right, bits, false).1) == taken
|
||||
})
|
||||
.collect();
|
||||
let (left, right) = eligible[random.below(eligible.len())];
|
||||
let mut initial = State::seeded(random);
|
||||
let mask = u64::MAX >> (64 - bits);
|
||||
initial.cpu.gpr[0] = (initial.cpu.gpr[0] & !mask) | left;
|
||||
initial.cpu.gpr[8] = (initial.cpu.gpr[8] & !mask) | right;
|
||||
let mut state = initial.clone();
|
||||
let mut code = Vec::new();
|
||||
let mut trace = Vec::new();
|
||||
Alu::Compare.encode(&mut code, bits, 0, 8);
|
||||
Alu::Compare.expect(&mut state, bits, 0, 8);
|
||||
let branch = code.len();
|
||||
state.checkpoint(&mut trace, branch);
|
||||
if near {
|
||||
code.extend([0x0f, 0x80 + condition as u8, 3, 0, 0, 0]);
|
||||
} else {
|
||||
code.extend([0x70 + condition as u8, 3]);
|
||||
}
|
||||
// The two arms set distinct low bytes of RDX, then stop.
|
||||
let fallthrough = code.len();
|
||||
code.extend([0xb2, 0x31, 0xf4, 0xb2, 0x73, 0xf4]);
|
||||
let arm = fallthrough + if taken { 3 } else { 0 };
|
||||
state.checkpoint(&mut trace, arm);
|
||||
state.cpu.gpr[2] = (state.cpu.gpr[2] & !255) | if taken { 0x73 } else { 0x31 };
|
||||
state.checkpoint(&mut trace, arm + 2);
|
||||
state.checkpoint(&mut trace, arm + 3);
|
||||
Case {
|
||||
code,
|
||||
initial,
|
||||
trace,
|
||||
native_only: true,
|
||||
exit: ExitReason::Halt,
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeded_memory_loop_with_calls() {
|
||||
seeded_cases("seeded_memory_loop_with_calls", 3, 64, |_, random| {
|
||||
let count = random.below(8) + 1;
|
||||
let input = random.below(8);
|
||||
let output = 80 + random.below(8);
|
||||
let mut initial = State::seeded(random);
|
||||
initial.cpu.set(Register::Rcx, count as u64);
|
||||
initial.cpu.set(Register::Rsi, DATA + input as u64);
|
||||
initial.cpu.set(Register::Rdi, DATA + output as u64);
|
||||
let code = vec![
|
||||
0xe8, 10, 0, 0, 0, // 0: call sum
|
||||
0x48, 0x89, 0x44, 0xcf, 0xf8, // 5: mov [rdi + rcx*8 - 8], rax
|
||||
0xff, 0xc9, // 10: dec ecx
|
||||
0x75, 0xf2, // 12: jnz start
|
||||
0xf4, // 14: hlt
|
||||
0x48, 0x03, 0x44, 0xce, 0xf8, // 15: sum: add rax, [rsi + rcx*8 - 8]
|
||||
0xc3, // 20: ret
|
||||
];
|
||||
let mut state = initial.clone();
|
||||
let mut trace = Vec::new();
|
||||
let mut sum = state.cpu.get(Register::Rax);
|
||||
for remaining in (1..=count).rev() {
|
||||
state.put_word(DATA_LEN - 8, CODE + 5);
|
||||
state.cpu.set(Register::Rsp, STACK_TOP - 8);
|
||||
state.checkpoint(&mut trace, 15);
|
||||
|
||||
let index = (remaining - 1) * 8;
|
||||
let (next, flags) = arithmetic(sum, initial.word(input + index), 64, true);
|
||||
sum = next;
|
||||
state.cpu.set(Register::Rax, sum);
|
||||
state.cpu.flags = flags;
|
||||
state.checkpoint(&mut trace, 20);
|
||||
|
||||
state.cpu.set(Register::Rsp, STACK_TOP);
|
||||
state.checkpoint(&mut trace, 5);
|
||||
state.put_word(output + index, sum);
|
||||
state.checkpoint(&mut trace, 10);
|
||||
|
||||
let (counter, mut flags) = arithmetic(remaining as u64, 1, 32, false);
|
||||
flags.cf = state.cpu.flags.cf; // DEC leaves carry intact.
|
||||
state.cpu.set(Register::Rcx, counter);
|
||||
state.cpu.flags = flags;
|
||||
state.checkpoint(&mut trace, 12);
|
||||
state.checkpoint(&mut trace, if counter == 0 { 14 } else { 0 });
|
||||
}
|
||||
state.checkpoint(&mut trace, 15);
|
||||
Case {
|
||||
code,
|
||||
initial,
|
||||
trace,
|
||||
native_only: true,
|
||||
exit: ExitReason::Halt,
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeded_vector_load_arithmetic_store() {
|
||||
seeded_cases("seeded_vector_load_arithmetic_store", 4, 64, |_, random| {
|
||||
let mut initial = State::seeded(random);
|
||||
let input = random.below(16);
|
||||
let output = 64 + random.below(16);
|
||||
initial.cpu.set(Register::Rsi, DATA + input as u64);
|
||||
initial.cpu.set(Register::Rdi, DATA + output as u64);
|
||||
let code = vec![
|
||||
0xf3, 0x44, 0x0f, 0x6f, 0x0e, // 0: movdqu xmm9, [rsi]
|
||||
0x66, 0x44, 0x0f, 0xfc, 0xca, // 5: paddb xmm9, xmm2
|
||||
0x66, 0x45, 0x0f, 0xf9, 0xcf, // 10: psubw xmm9, xmm15
|
||||
0x66, 0x44, 0x0f, 0xef, 0xc8, // 15: pxor xmm9, xmm0
|
||||
0xf3, 0x44, 0x0f, 0x7f, 0x0f, // 20: movdqu [rdi], xmm9
|
||||
0xf4,
|
||||
];
|
||||
let mut state = initial.clone();
|
||||
let mut trace = Vec::new();
|
||||
let mut lanes: [u8; 16] = initial.data[input..input + 16].try_into().unwrap();
|
||||
state.cpu.xmm[9] = u128::from_le_bytes(lanes);
|
||||
state.checkpoint(&mut trace, 5);
|
||||
|
||||
for (lane, addend) in lanes.iter_mut().zip(initial.cpu.xmm[2].to_le_bytes()) {
|
||||
*lane = lane.wrapping_add(addend);
|
||||
}
|
||||
state.cpu.xmm[9] = u128::from_le_bytes(lanes);
|
||||
state.checkpoint(&mut trace, 10);
|
||||
|
||||
let subtrahend = initial.cpu.xmm[15].to_le_bytes();
|
||||
let (words, _) = lanes.as_chunks_mut::<2>();
|
||||
let (subtrahends, _) = subtrahend.as_chunks::<2>();
|
||||
for (word, &rhs) in words.iter_mut().zip(subtrahends) {
|
||||
let left = u16::from_le_bytes(*word);
|
||||
let right = u16::from_le_bytes(rhs);
|
||||
*word = left.wrapping_sub(right).to_le_bytes();
|
||||
}
|
||||
state.cpu.xmm[9] = u128::from_le_bytes(lanes);
|
||||
state.checkpoint(&mut trace, 15);
|
||||
|
||||
state.cpu.xmm[9] ^= initial.cpu.xmm[0];
|
||||
state.checkpoint(&mut trace, 20);
|
||||
state.data[output..output + 16].copy_from_slice(&state.cpu.xmm[9].to_le_bytes());
|
||||
state.checkpoint(&mut trace, 25);
|
||||
state.checkpoint(&mut trace, 26);
|
||||
Case {
|
||||
code,
|
||||
initial,
|
||||
trace,
|
||||
native_only: true,
|
||||
exit: ExitReason::Halt,
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeded_precise_memory_faults() {
|
||||
seeded_cases("seeded_precise_memory_faults", 5, 28, |index, random| {
|
||||
// Both branch outcomes and both operand directions at each of the
|
||||
// seven possible byte splits of an eight-byte operand.
|
||||
let store = index.is_multiple_of(2);
|
||||
let taken = (index / 2).is_multiple_of(2);
|
||||
let split = index / 4 + 1;
|
||||
let mut initial = State::seeded(random);
|
||||
let output = random.below(32);
|
||||
let value = initial.cpu.get(Register::Rax);
|
||||
let rhs = if taken { value } else { value ^ (1 << 63) };
|
||||
initial.cpu.set(Register::R8, rhs);
|
||||
initial.cpu.set(Register::Rdi, DATA + output as u64);
|
||||
initial.cpu.set(Register::Rsi, STACK_TOP - split as u64);
|
||||
let code = vec![
|
||||
0x48,
|
||||
0x89,
|
||||
0x07, // 0: mov [rdi], rax
|
||||
0x4c,
|
||||
0x39,
|
||||
0xc0, // 3: cmp rax, r8
|
||||
0x74,
|
||||
0x03, // 6: je faulting_move
|
||||
0x4d,
|
||||
0x89,
|
||||
0xd1, // 8: mov r9, r10
|
||||
0x48,
|
||||
if store { 0x89 } else { 0x8b },
|
||||
0x06, // 11: mov [rsi], rax or mov rax, [rsi]
|
||||
0xf4,
|
||||
];
|
||||
let mut state = initial.clone();
|
||||
let mut trace = Vec::new();
|
||||
state.put_word(output, value);
|
||||
state.checkpoint(&mut trace, 3);
|
||||
state.cpu.flags = arithmetic(value, rhs, 64, false).1;
|
||||
state.checkpoint(&mut trace, 6);
|
||||
if taken {
|
||||
state.checkpoint(&mut trace, 11);
|
||||
} else {
|
||||
state.checkpoint(&mut trace, 8);
|
||||
state.cpu.set(Register::R9, initial.cpu.get(Register::R10));
|
||||
state.checkpoint(&mut trace, 11);
|
||||
}
|
||||
// The faulting instruction leaves RIP, registers and all mapped bytes
|
||||
// intact. The preceding store and optional register move stay retired.
|
||||
state.checkpoint(&mut trace, 11);
|
||||
Case {
|
||||
code,
|
||||
initial,
|
||||
trace,
|
||||
native_only: true,
|
||||
exit: ExitReason::MemoryFault(MemoryError::UnmappedAddress(STACK_TOP)),
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Stable-toolchain replay of the `runtime_services` fuzz driver: seeded
|
||||
//! pseudo-random call sequences against the standard service registry.
|
||||
|
||||
mod support;
|
||||
|
||||
use support::robustness::{ARG_REUSE_RESULT, ARG_ZERO, Driver};
|
||||
|
||||
/// xorshift64*, so every run uses the same inputs.
|
||||
fn inputs(seed: u64, count: usize, length: usize) -> impl Iterator<Item = Vec<u8>> {
|
||||
let mut state = seed;
|
||||
(0..count).map(move |_| {
|
||||
(0..length)
|
||||
.map(|_| {
|
||||
state ^= state >> 12;
|
||||
state ^= state << 25;
|
||||
state ^= state >> 27;
|
||||
(state.wrapping_mul(0x2545_F491_4F6C_DD1D) >> 56) as u8
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_service_sequences_keep_memory_and_register_invariants() {
|
||||
let driver = Driver::new();
|
||||
assert!(driver.service_count() > 150, "{}", driver.service_count());
|
||||
let mut total_calls = 0usize;
|
||||
let mut max_distinct = 0usize;
|
||||
for input in inputs(0x5EED_CAFE, 300, 1024) {
|
||||
let stats = driver.run(&input);
|
||||
total_calls += stats.calls;
|
||||
max_distinct = max_distinct.max(stats.distinct_services);
|
||||
}
|
||||
// With memory init no longer consuming the corpus, 1 KiB inputs must
|
||||
// reach the dispatch loop (each call needs 24 bytes plus a GS byte).
|
||||
assert!(
|
||||
total_calls >= 300 * 20,
|
||||
"expected handlers to run; total_calls={total_calls}"
|
||||
);
|
||||
assert!(
|
||||
max_distinct >= 8,
|
||||
"expected multi-service coverage; max_distinct={max_distinct}"
|
||||
);
|
||||
assert_eq!(driver.run(&[]).calls, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoded_sequences_invoke_handlers_and_reuse_handles() {
|
||||
let driver = Driver::new();
|
||||
let create = driver
|
||||
.service_index("kernel32.dll", "CreateEventW")
|
||||
.expect("CreateEventW");
|
||||
let close = driver
|
||||
.service_index("kernel32.dll", "CloseHandle")
|
||||
.expect("CloseHandle");
|
||||
let get_tick = driver
|
||||
.service_index("kernel32.dll", "GetTickCount64")
|
||||
.expect("GetTickCount64");
|
||||
let query = driver
|
||||
.service_index("kernel32.dll", "QueryPerformanceCounter")
|
||||
.expect("QueryPerformanceCounter");
|
||||
|
||||
// CreateEventW(null, 0, 0, null) → CloseHandle(prior result) → GetTickCount64
|
||||
// → QueryPerformanceCounter(writable via mode 2 is not used; zeros ok).
|
||||
let zeros = [ARG_ZERO; 7];
|
||||
let mut close_args = [ARG_ZERO; 7];
|
||||
close_args[0] = ARG_REUSE_RESULT; // hObject from CreateEventW
|
||||
let input = driver.encode_sequence(&[
|
||||
(create, zeros),
|
||||
(close, close_args),
|
||||
(get_tick, zeros),
|
||||
(query, zeros),
|
||||
]);
|
||||
let stats = driver.run(&input);
|
||||
assert_eq!(stats.calls, 4);
|
||||
assert_eq!(stats.distinct_services, 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xmem_alloc_oom_artifact_fails_closed() {
|
||||
// libFuzzer OOM from a ~3.7 GiB XMemAlloc before the virtual budget gated
|
||||
// the mapping (fuzz/artifacts/runtime_services/oom-022d4084...).
|
||||
let driver = Driver::new();
|
||||
let stats = driver.run(&[242, 2, 24, 0, 248, 8, 9, 9, 8, 0, 0, 129, 191]);
|
||||
assert!(stats.calls >= 1, "{stats:?}");
|
||||
}
|
||||
+227
-248
@@ -1,248 +1,227 @@
|
||||
// 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()
|
||||
}
|
||||
}
|
||||
// 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)]
|
||||
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -1,241 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Drives sequences of standard runtime services with adversarial arguments.
|
||||
//!
|
||||
//! Shared by the `runtime_services` libFuzzer target and the stable-toolchain
|
||||
//! regression test. Writable guest memory is filled from a deterministic
|
||||
//! pattern, not from the fuzz input, so short corpora still reach the dispatch
|
||||
//! loop. Each call takes its arguments from the remaining input: zero, all
|
||||
//! ones, pointers into writable, read-only and unmapped memory, raw values,
|
||||
//! small integers or an earlier result (so handles flow between calls). After
|
||||
//! every call the driver checks that read-only and code memory are unchanged
|
||||
//! and that the Win64 nonvolatile registers are preserved. A panic, a broken
|
||||
//! invariant or a hang is a bug.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::Arc;
|
||||
use xenora_loader::cpu::{CpuState, Register};
|
||||
use xenora_loader::imports::{ImportRegistry, Win64Args};
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
|
||||
|
||||
const WRITABLE: u64 = 0x5_0000;
|
||||
const WRITABLE_LEN: usize = 0x1_0000;
|
||||
const READ_ONLY: u64 = 0x7_0000;
|
||||
const CODE: u64 = 0x7_8000;
|
||||
const REGION_LEN: usize = 0x1000;
|
||||
const STACK: u64 = 0x9_0000;
|
||||
const STACK_LEN: usize = 0x2000;
|
||||
const UNMAPPED: u64 = 0xDEAD_0000;
|
||||
const MAX_CALLS: usize = 48;
|
||||
|
||||
/// Argument encoding mode that reuses an earlier handler result (handles).
|
||||
#[allow(dead_code)] // used by the stable-toolchain regression test
|
||||
pub const ARG_REUSE_RESULT: u8 = 8;
|
||||
/// Argument encoding mode that supplies zero.
|
||||
#[allow(dead_code)] // used by the stable-toolchain regression test
|
||||
pub const ARG_ZERO: u8 = 0;
|
||||
|
||||
/// Services that wait on real time, run guest code or reach native Metal are
|
||||
/// left out, so each input runs quickly and deterministically.
|
||||
fn excluded(module: &str, symbol: &str) -> bool {
|
||||
module.eq_ignore_ascii_case("xenora_fixture.dll")
|
||||
|| matches!(symbol, "WSAPoll" | "XTaskQueueDispatch")
|
||||
}
|
||||
|
||||
/// Outcome of one `Driver::run` against a single corpus input.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct RunStats {
|
||||
pub calls: usize,
|
||||
pub distinct_services: usize,
|
||||
}
|
||||
|
||||
pub struct Driver {
|
||||
services: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
impl Default for Driver {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Driver {
|
||||
pub fn new() -> Self {
|
||||
let mut registry = ImportRegistry::new();
|
||||
register_standard_services(
|
||||
&mut registry,
|
||||
Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))),
|
||||
);
|
||||
let mut services: Vec<(String, String)> = registry
|
||||
.iter_registered()
|
||||
.filter(|(module, symbol, _)| !excluded(module, symbol))
|
||||
.map(|(module, symbol, _)| (module.to_owned(), symbol.to_owned()))
|
||||
.collect();
|
||||
services.sort();
|
||||
Self { services }
|
||||
}
|
||||
|
||||
#[allow(dead_code)] // used by the stable-toolchain regression test
|
||||
pub fn service_count(&self) -> usize {
|
||||
self.services.len()
|
||||
}
|
||||
|
||||
/// Index of `module!symbol` in the driver's sorted service table.
|
||||
#[allow(dead_code)] // used by the stable-toolchain regression test
|
||||
pub fn service_index(&self, module: &str, symbol: &str) -> Option<usize> {
|
||||
self.services
|
||||
.iter()
|
||||
.position(|(entry_module, entry_symbol)| {
|
||||
entry_module.eq_ignore_ascii_case(module) && entry_symbol == symbol
|
||||
})
|
||||
}
|
||||
|
||||
/// Encode a deterministic multi-call corpus.
|
||||
///
|
||||
/// Each entry is `(service_index, [arg_mode; 7])`. Argument offsets are
|
||||
/// zero; a trailing byte per call supplies the GS-base choice.
|
||||
#[allow(dead_code)] // used by the stable-toolchain regression test
|
||||
pub fn encode_sequence(&self, calls: &[(usize, [u8; 7])]) -> Vec<u8> {
|
||||
let mut bytes = Vec::with_capacity(calls.len() * (2 + 7 * 3 + 1));
|
||||
for &(index, modes) in calls {
|
||||
bytes.extend_from_slice(&(index as u16).to_le_bytes());
|
||||
for mode in modes {
|
||||
bytes.extend_from_slice(&0u16.to_le_bytes());
|
||||
bytes.push(mode);
|
||||
}
|
||||
bytes.push(0); // gs_base selector
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
/// Run one input against fresh service state and fresh guest memory.
|
||||
pub fn run(&self, data: &[u8]) -> RunStats {
|
||||
let mut registry = ImportRegistry::new();
|
||||
let clock = Arc::new(MockClock::new(0x01DA_0000_0000_0000));
|
||||
register_standard_services(&mut registry, Arc::new(ServicesState::new(clock)));
|
||||
|
||||
let mut input = Input(data);
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region(WRITABLE, WRITABLE_LEN, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region(STACK, STACK_LEN, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
// Deterministic fill: do not consume fuzz/corpus bytes here, or short
|
||||
// inputs never reach the dispatch loop (WRITABLE_LEN is 65,536).
|
||||
let fill: Vec<u8> = (0..WRITABLE_LEN)
|
||||
.map(|i| (i.wrapping_mul(131).wrapping_add(17)) as u8)
|
||||
.collect();
|
||||
memory.write_bytes(WRITABLE, &fill).unwrap();
|
||||
let read_only: Vec<u8> = (0..REGION_LEN).map(|i| (i * 7) as u8).collect();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
READ_ONLY,
|
||||
REGION_LEN,
|
||||
MemoryPermissions::READ_ONLY,
|
||||
&read_only,
|
||||
)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
CODE,
|
||||
REGION_LEN,
|
||||
MemoryPermissions::READ_EXECUTE,
|
||||
&[0xC3; REGION_LEN],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let mut results = vec![0u64];
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut calls = 0usize;
|
||||
for _ in 0..MAX_CALLS {
|
||||
let Some(selector) = input.u16() else { break };
|
||||
let index = selector as usize % self.services.len();
|
||||
let (module, symbol) = &self.services[index];
|
||||
let mut args = [0u64; 7];
|
||||
for arg in &mut args {
|
||||
*arg = input.argument(&results);
|
||||
}
|
||||
let rsp = STACK + STACK_LEN as u64 / 2;
|
||||
let mut cpu = CpuState::new(CODE, rsp);
|
||||
cpu.gs_base = [0x7_F000, 0x7_F800][input.byte_or(0) as usize % 2];
|
||||
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[4..].iter().enumerate() {
|
||||
memory
|
||||
.write_u64(rsp + 40 + 8 * slot as u64, *value)
|
||||
.unwrap();
|
||||
}
|
||||
use Register::{R12, R13, R14, R15, Rbp, Rbx, Rdi, Rsi, Rsp};
|
||||
let preserved = [Rbx, Rbp, Rdi, Rsi, Rsp, R12, R13, R14, R15];
|
||||
let before = preserved.map(|register| cpu.get(register));
|
||||
|
||||
let service = registry
|
||||
.binding(module, symbol)
|
||||
.expect("registered service");
|
||||
let outcome = (service.handler)(&Win64Args::new(&cpu), &mut cpu, &mut memory);
|
||||
|
||||
assert_eq!(
|
||||
preserved.map(|register| cpu.get(register)),
|
||||
before,
|
||||
"{module}!{symbol} changed a nonvolatile register"
|
||||
);
|
||||
let mut check = vec![0; REGION_LEN];
|
||||
memory.read_bytes(READ_ONLY, &mut check).unwrap();
|
||||
assert_eq!(check, read_only, "{module}!{symbol} wrote read-only memory");
|
||||
memory.read_bytes(CODE, &mut check).unwrap();
|
||||
assert!(
|
||||
check.iter().all(|&byte| byte == 0xC3),
|
||||
"{module}!{symbol} wrote code memory"
|
||||
);
|
||||
calls += 1;
|
||||
seen.insert((module.clone(), symbol.clone()));
|
||||
if let Ok(value) = outcome {
|
||||
results.push(value);
|
||||
}
|
||||
}
|
||||
RunStats {
|
||||
calls,
|
||||
distinct_services: seen.len(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Input<'a>(&'a [u8]);
|
||||
|
||||
impl Input<'_> {
|
||||
fn take<const N: usize>(&mut self) -> Option<[u8; N]> {
|
||||
let (head, rest) = self.0.split_first_chunk::<N>()?;
|
||||
self.0 = rest;
|
||||
Some(*head)
|
||||
}
|
||||
|
||||
fn byte_or(&mut self, default: u8) -> u8 {
|
||||
self.take::<1>().map_or(default, |[byte]| byte)
|
||||
}
|
||||
|
||||
fn u16(&mut self) -> Option<u16> {
|
||||
self.take::<2>().map(u16::from_le_bytes)
|
||||
}
|
||||
|
||||
fn argument(&mut self, results: &[u64]) -> u64 {
|
||||
let offset = u64::from(self.u16().unwrap_or(0));
|
||||
match self.byte_or(0) % 9 {
|
||||
0 => 0,
|
||||
1 => u64::MAX,
|
||||
2 => WRITABLE + offset % WRITABLE_LEN as u64,
|
||||
3 => READ_ONLY + offset % REGION_LEN as u64,
|
||||
4 => CODE + offset % REGION_LEN as u64,
|
||||
5 => UNMAPPED + offset,
|
||||
6 => self.take::<8>().map_or(offset, u64::from_le_bytes),
|
||||
7 => offset % 512,
|
||||
_ => results[offset as usize % results.len()],
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
+27
-76
@@ -1,4 +1,4 @@
|
||||
use std::collections::{BTreeMap, VecDeque};
|
||||
use std::collections::BTreeMap;
|
||||
use std::ffi::c_void;
|
||||
use std::fmt;
|
||||
use std::mem::size_of_val;
|
||||
@@ -37,16 +37,6 @@ const MAX_GROUPS: usize = 64;
|
||||
const MAX_GRID_WORDS: usize = MAX_GROUPS * MAX_THREADS_PER_GROUP;
|
||||
const MAX_SOURCE_BYTES: usize = 64 * 1024;
|
||||
const MAX_IN_FLIGHT: usize = 16;
|
||||
const MAX_CACHED_PIPELINES: usize = 16;
|
||||
|
||||
type ComputePipeline = Retained<ProtocolObject<dyn MTLComputePipelineState>>;
|
||||
|
||||
struct CachedPipeline {
|
||||
source: Box<str>,
|
||||
entry: Box<str>,
|
||||
shader_validation: bool,
|
||||
pipeline: ComputePipeline,
|
||||
}
|
||||
|
||||
const BC_READBACK: &str = r"
|
||||
#include <metal_stdlib>
|
||||
@@ -158,9 +148,7 @@ impl std::error::Error for MetalError {}
|
||||
/// measure a single submission and are not a benchmark distribution.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RunProfile {
|
||||
/// Host library compilation time, or zero when reusing a compute pipeline.
|
||||
pub library_seconds: f64,
|
||||
/// Host pipeline creation time, or zero when reusing a compute pipeline.
|
||||
pub pipeline_seconds: f64,
|
||||
pub gpu_seconds: f64,
|
||||
/// Host wall time from the start of setup until wait observes completion.
|
||||
@@ -183,8 +171,6 @@ pub struct NativeCompute {
|
||||
device: Retained<ProtocolObject<dyn MTLDevice>>,
|
||||
queue: Retained<ProtocolObject<dyn MTLCommandQueue>>,
|
||||
submissions: Mutex<SubmissionTable>,
|
||||
// Least recently used first. In-flight submissions retain their own reference.
|
||||
compute_pipelines: Mutex<VecDeque<CachedPipeline>>,
|
||||
}
|
||||
|
||||
/// A submitted dispatch whose result can be collected by its issuing context.
|
||||
@@ -261,7 +247,7 @@ struct SubmissionEntry {
|
||||
/// Metal reports Completed or Error.
|
||||
struct InFlightResources {
|
||||
command: Retained<ProtocolObject<dyn MTLCommandBuffer>>,
|
||||
_pipeline: ComputePipeline,
|
||||
_pipeline: Retained<ProtocolObject<dyn MTLComputePipelineState>>,
|
||||
_input: Option<Retained<ProtocolObject<dyn MTLBuffer>>>,
|
||||
output: Retained<ProtocolObject<dyn MTLBuffer>>,
|
||||
_texture: Option<Retained<ProtocolObject<dyn MTLTexture>>>,
|
||||
@@ -362,7 +348,6 @@ impl NativeCompute {
|
||||
device,
|
||||
queue,
|
||||
submissions: Mutex::default(),
|
||||
compute_pipelines: Mutex::default(),
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -916,7 +901,7 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
self.run_profiled_words(source, entry, input, Some(width))
|
||||
}
|
||||
|
||||
/// Find or compile the kernel and report the smaller of the device and pipeline width limits.
|
||||
/// Compile the kernel and report the smaller of the device and pipeline width limits.
|
||||
///
|
||||
/// Input size and threadgroup count are checked separately at dispatch.
|
||||
///
|
||||
@@ -926,7 +911,11 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
pub fn max_group_width(&self, source: &str, entry: &str) -> Result<usize, MetalError> {
|
||||
validate_source(source, &[entry])?;
|
||||
autoreleasepool(|_| {
|
||||
let (pipeline, _, _) = self.prepare_compute_pipeline(source, entry)?;
|
||||
let options = compile_options()?;
|
||||
let library = self.compile_library(source, &options)?;
|
||||
let function = find_function(&library, entry)?;
|
||||
let pipeline = self.compute_pipeline(&function)?;
|
||||
verify_shader_validation(&pipeline)?;
|
||||
Ok(self.pipeline_group_width_limit(&pipeline))
|
||||
})
|
||||
}
|
||||
@@ -974,8 +963,15 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
host_start: Instant,
|
||||
) -> Result<Submission<'_>, MetalError> {
|
||||
self.submissions().check_capacity()?;
|
||||
let (pipeline, library_seconds, pipeline_seconds) =
|
||||
self.prepare_compute_pipeline(source, entry)?;
|
||||
let options = compile_options()?;
|
||||
let library_start = Instant::now();
|
||||
let library = self.compile_library(source, &options)?;
|
||||
let library_seconds = library_start.elapsed().as_secs_f64();
|
||||
let function = find_function(&library, entry)?;
|
||||
let pipeline_start = Instant::now();
|
||||
let pipeline = self.compute_pipeline(&function)?;
|
||||
let pipeline_seconds = pipeline_start.elapsed().as_secs_f64();
|
||||
verify_shader_validation(&pipeline)?;
|
||||
|
||||
let limit = self.pipeline_group_width_limit(&pipeline);
|
||||
let width = match group_width {
|
||||
@@ -1112,67 +1108,18 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
})
|
||||
}
|
||||
|
||||
fn prepare_compute_pipeline(
|
||||
fn compute_pipeline(
|
||||
&self,
|
||||
source: &str,
|
||||
entry: &str,
|
||||
) -> Result<(ComputePipeline, f64, f64), MetalError> {
|
||||
let shader_validation = std::env::var("MTL_SHADER_VALIDATION").as_deref() == Ok("1");
|
||||
// Device identity is fixed by this context. All misses use the same
|
||||
// compile options (safe math, precise functions, default language,
|
||||
// no macros) and unspecialized functions. Any configurable options
|
||||
// must become part of the key before they are used here.
|
||||
let mut cache = self
|
||||
.compute_pipelines
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(index) = cache.iter().position(|cached| {
|
||||
cached.source.as_ref() == source
|
||||
&& cached.entry.as_ref() == entry
|
||||
&& cached.shader_validation == shader_validation
|
||||
}) {
|
||||
let cached = cache.remove(index).expect("position in the locked cache");
|
||||
let pipeline = cached.pipeline.clone();
|
||||
cache.push_back(cached);
|
||||
return Ok((pipeline, 0.0, 0.0));
|
||||
}
|
||||
|
||||
// Serialize cache misses in this context so concurrent requests for
|
||||
// one key share the same build. The submission table is unlocked here.
|
||||
let options = compile_options()?;
|
||||
let library_start = Instant::now();
|
||||
let library = self.compile_library(source, &options)?;
|
||||
let library_seconds = library_start.elapsed().as_secs_f64();
|
||||
let function = find_function(&library, entry)?;
|
||||
let pipeline_start = Instant::now();
|
||||
let pipeline = self
|
||||
.device
|
||||
.newComputePipelineStateWithFunction_error(&function)
|
||||
function: &ProtocolObject<dyn MTLFunction>,
|
||||
) -> Result<Retained<ProtocolObject<dyn MTLComputePipelineState>>, MetalError> {
|
||||
self.device
|
||||
.newComputePipelineStateWithFunction_error(function)
|
||||
.map_err(|error| {
|
||||
MetalError::new(
|
||||
"newComputePipelineStateWithFunction",
|
||||
error.localizedDescription().to_string(),
|
||||
)
|
||||
})?;
|
||||
let pipeline_seconds = pipeline_start.elapsed().as_secs_f64();
|
||||
if shader_validation {
|
||||
verify_shader_validation(&pipeline)?;
|
||||
}
|
||||
|
||||
// Bound owned key text to 1 MiB. A valid oversized key can run
|
||||
// uncached, so this budget does not alter source or entry validation.
|
||||
if entry.len() <= MAX_SOURCE_BYTES.saturating_sub(source.len()) {
|
||||
if cache.len() == MAX_CACHED_PIPELINES {
|
||||
cache.pop_front();
|
||||
}
|
||||
cache.push_back(CachedPipeline {
|
||||
source: source.into(),
|
||||
entry: entry.into(),
|
||||
shader_validation,
|
||||
pipeline: pipeline.clone(),
|
||||
});
|
||||
}
|
||||
Ok((pipeline, library_seconds, pipeline_seconds))
|
||||
})
|
||||
}
|
||||
|
||||
fn pipeline_group_width_limit(
|
||||
@@ -1285,6 +1232,10 @@ fn check_command_status(
|
||||
fn verify_shader_validation(
|
||||
pipeline: &ProtocolObject<dyn MTLComputePipelineState>,
|
||||
) -> Result<(), MetalError> {
|
||||
if std::env::var("MTL_SHADER_VALIDATION").as_deref() != Ok("1") {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if !pipeline.respondsToSelector(sel!(shaderValidation)) {
|
||||
return Err(MetalError::new(
|
||||
"shaderValidation",
|
||||
|
||||
@@ -356,131 +356,6 @@ fn multiple_submissions() {
|
||||
assert_eq!(second, [5, 5, 1, 5]);
|
||||
}
|
||||
|
||||
fn pipeline_was_reused(profile: &xenora_metal::RunProfile) -> bool {
|
||||
profile.library_seconds == 0.0 && profile.pipeline_seconds == 0.0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_pipeline_cache_distinguishes_source_entry_and_context() {
|
||||
let context = context();
|
||||
let source = fixture("output[id] = input[id] + 1u;");
|
||||
let second_entry =
|
||||
fixture("output[id] = input[id] * 2u;").replace("void fixture(", "void other(");
|
||||
let source = format!("{source}\n{second_entry}");
|
||||
let changed = source.replace("input[id] + 1u", "input[id] - 1u");
|
||||
let input = [0, 11, u32::MAX];
|
||||
|
||||
for (msl, entry, expected) in [
|
||||
(source.as_str(), "fixture", [1, 12, 0]),
|
||||
(source.as_str(), "other", [0, 22, u32::MAX - 1]),
|
||||
(changed.as_str(), "fixture", [u32::MAX, 10, u32::MAX - 1]),
|
||||
] {
|
||||
let cold = native(context.run_words_profiled(msl, entry, &input));
|
||||
let warm = native(context.run_words_profiled(msl, entry, &input));
|
||||
assert!(!pipeline_was_reused(&cold), "{entry}");
|
||||
assert!(pipeline_was_reused(&warm), "{entry}");
|
||||
assert_eq!(cold.output, expected, "{entry}");
|
||||
assert_eq!(warm.output, expected, "{entry}");
|
||||
}
|
||||
let separate = native(NativeCompute::new());
|
||||
let fresh = native(separate.run_words_profiled(&source, "fixture", &input));
|
||||
assert!(!pipeline_was_reused(&fresh));
|
||||
assert_eq!(fresh.output, [1, 12, 0]);
|
||||
|
||||
for _ in 0..2 {
|
||||
for (msl, entry, operation) in [
|
||||
(source.as_str(), "missing", "newFunctionWithName"),
|
||||
("not valid MSL", "fixture", "newLibraryWithSource"),
|
||||
] {
|
||||
let error = context
|
||||
.run_words_profiled(msl, entry, &input)
|
||||
.expect_err("invalid pipeline must still fail after warming the cache");
|
||||
assert_eq!(error.operation, operation);
|
||||
}
|
||||
}
|
||||
let error = context
|
||||
.run_words_with_group_width(&source, "fixture", &input, 0)
|
||||
.expect_err("cached pipeline must still check dispatch width");
|
||||
assert_eq!(error.operation, "threadgroup width");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_pipeline_cache_bounds_key_bytes_without_rejecting_maximum_source() {
|
||||
const SOURCE_LIMIT: usize = 64 * 1024;
|
||||
let context = context();
|
||||
let mut source = fixture("output[id] = input[id] ^ 1u;");
|
||||
source.push_str("\n// ");
|
||||
source.push_str(&" ".repeat(SOURCE_LIMIT - source.len()));
|
||||
|
||||
for _ in 0..2 {
|
||||
let profile = native(context.run_words_profiled(&source, "fixture", &[8]));
|
||||
assert_eq!(profile.output, [9]);
|
||||
assert!(!pipeline_was_reused(&profile));
|
||||
}
|
||||
source.push(' ');
|
||||
let error = context
|
||||
.run_words_profiled(&source, "fixture", &[8])
|
||||
.expect_err("source above 64 KiB must fail before pipeline lookup");
|
||||
assert_eq!(error.operation, "source bounds");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compute_pipeline_cache_evicts_oldest_unused_key_and_keeps_pending_work_alive() {
|
||||
let context = context();
|
||||
// Seventeen entries in one source fit in Metal's input limit and exceed
|
||||
// Xenora's 16-pipeline cache. Each kernel writes a distinct result.
|
||||
let source: String = (0..=16)
|
||||
.map(|id| {
|
||||
fixture(&format!("output[id] = input[id] + {id}u;"))
|
||||
.replace("void fixture(", &format!("void entry{id}("))
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
native(context.max_group_width(&source, "entry0"));
|
||||
let (pending, gate) = native(context.submit_words_gated(&source, "entry1", &[7]));
|
||||
for id in 2..16 {
|
||||
native(context.max_group_width(&source, &format!("entry{id}")));
|
||||
}
|
||||
native(context.max_group_width(&source, "entry0"));
|
||||
native(context.max_group_width(&source, "entry16"));
|
||||
gate.open();
|
||||
let finished = native(context.wait(pending));
|
||||
assert_eq!(finished.output, [8]);
|
||||
|
||||
let recent = native(context.run_words_profiled(&source, "entry0", &[29]));
|
||||
assert!(pipeline_was_reused(&recent));
|
||||
assert_eq!(recent.output, [29]);
|
||||
let rebuilt = native(context.run_words_profiled(&source, "entry1", &[17]));
|
||||
assert!(!pipeline_was_reused(&rebuilt));
|
||||
assert_eq!(rebuilt.output, [18]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn simultaneous_compute_submissions_share_one_pipeline_build() {
|
||||
let context = context();
|
||||
let source = fixture("output[id] = input[id] ^ 5u;");
|
||||
let start = std::sync::Barrier::new(4);
|
||||
std::thread::scope(|scope| {
|
||||
let workers: Vec<_> = (0..4)
|
||||
.map(|input| {
|
||||
let (context, source, start) = (&context, &source, &start);
|
||||
scope.spawn(move || {
|
||||
start.wait();
|
||||
let token = native(context.submit_words(source, "fixture", &[input]));
|
||||
let result = native(context.wait(token));
|
||||
assert_eq!(result.output, [input ^ 5]);
|
||||
usize::from(!pipeline_was_reused(&result))
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let builds: usize = workers
|
||||
.into_iter()
|
||||
.map(|worker| worker.join().unwrap())
|
||||
.sum();
|
||||
assert_eq!(builds, 1);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn errors_propagate() {
|
||||
let context = context();
|
||||
@@ -538,52 +413,3 @@ kernel void fixture(device const uint *input [[buffer(0)]],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "manual GPU timing run"]
|
||||
fn compute_pipeline_reuse_benchmark() {
|
||||
const WARMUPS: usize = 10;
|
||||
const SAMPLES: usize = 101;
|
||||
let warm_context = context();
|
||||
let device = warm_context.device_name();
|
||||
let source = fixture("output[id] = input[id] * 7u + 3u;");
|
||||
let input = mixing_input(131);
|
||||
let expected: Vec<_> = input
|
||||
.iter()
|
||||
.map(|word| word.wrapping_mul(7).wrapping_add(3))
|
||||
.collect();
|
||||
let mut timings = [[[0.0; SAMPLES]; 4]; 2];
|
||||
|
||||
for round in 0..WARMUPS + SAMPLES {
|
||||
let cold_context = context();
|
||||
// Alternate order so neither measurement always follows the other.
|
||||
let contexts = [&cold_context, &warm_context];
|
||||
for index in [round % 2, (round + 1) % 2] {
|
||||
let profile = native(contexts[index].run_words_profiled(&source, "fixture", &input));
|
||||
assert_eq!(profile.output, expected, "context={index} round={round}");
|
||||
if round >= WARMUPS {
|
||||
for (samples, seconds) in timings[index].iter_mut().zip([
|
||||
profile.library_seconds,
|
||||
profile.pipeline_seconds,
|
||||
profile.host_seconds,
|
||||
profile.gpu_seconds,
|
||||
]) {
|
||||
samples[round - WARMUPS] = seconds;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for (label, [mut library, mut pipeline, mut host, mut gpu]) in
|
||||
["fresh context", "repeated context"]
|
||||
.into_iter()
|
||||
.zip(timings)
|
||||
{
|
||||
println!(
|
||||
"device={device} {label} samples={SAMPLES} library_us[{}] pipeline_us[{}] host_us[{}] gpu_us[{}]",
|
||||
timing_summary(&mut library),
|
||||
timing_summary(&mut pipeline),
|
||||
timing_summary(&mut host),
|
||||
timing_summary(&mut gpu),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -102,18 +102,6 @@ attribute bit, is truncated, or uses the earlier virtual-address descriptor form
|
||||
is reported in `delay_import_error` and in the Markdown report, together with
|
||||
the entries read before it.
|
||||
|
||||
`xenora_import_gen::demangle` decodes Microsoft Visual C++ decorated names
|
||||
for diagnostics, in the style of Microsoft's `undname`. It covers functions,
|
||||
data, member access and storage, `this` qualifiers, calling conventions,
|
||||
constructors, destructors, common operators, `vftable` names, classes,
|
||||
structs, unions, enums, pointers, references, primitive types, templates
|
||||
with type and integer arguments, and name and type back-references. Function
|
||||
pointer types, RTTI descriptors, nested function scopes and other constructs
|
||||
return `None`, so callers show the decorated name instead of a guess. The
|
||||
generator manifest's list of imports that need manual engineering shows the
|
||||
undecorated form beside each decorated C++ import. Tests check names mangled
|
||||
by clang for `x86_64-pc-windows-msvc` against their source declarations.
|
||||
|
||||
The synthetic process registry supports the current-process pseudo handle and
|
||||
its process ID. The priority boost setter and getter record and query a guest
|
||||
policy. They are partial until a guest scheduler applies the policy. The process
|
||||
|
||||
@@ -96,33 +96,3 @@ 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.
|
||||
@@ -46,9 +46,3 @@ name = "reference"
|
||||
path = "fuzz_targets/reference.rs"
|
||||
test = false
|
||||
doc = false
|
||||
|
||||
[[bin]]
|
||||
name = "runtime_services"
|
||||
path = "fuzz_targets/runtime_services.rs"
|
||||
test = false
|
||||
doc = false
|
||||
@@ -1,13 +0,0 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#![no_main]
|
||||
|
||||
#[path = "../../crates/loader/tests/support/robustness.rs"]
|
||||
mod robustness;
|
||||
|
||||
use libfuzzer_sys::fuzz_target;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
fuzz_target!(|data: &[u8]| {
|
||||
static DRIVER: OnceLock<robustness::Driver> = OnceLock::new();
|
||||
DRIVER.get_or_init(robustness::Driver::new).run(data);
|
||||
});
|
||||
+2
-2
@@ -5,8 +5,8 @@ cd "$(dirname "$0")/.."
|
||||
|
||||
target=${1:-}
|
||||
case "$target" in
|
||||
instruction_stream|fixture|reference|runtime_services) ;;
|
||||
*) printf '%s\n' 'usage: scripts/fuzz.sh <instruction_stream|fixture|reference|runtime_services> [seconds]' >&2; exit 2 ;;
|
||||
instruction_stream|fixture|reference) ;;
|
||||
*) printf '%s\n' 'usage: scripts/fuzz.sh <instruction_stream|fixture|reference> [seconds]' >&2; exit 2 ;;
|
||||
esac
|
||||
seconds=${2:-600}
|
||||
case "$seconds" in
|
||||
|
||||
@@ -13,43 +13,6 @@ export CARGO_BUILD_JOBS=${CARGO_BUILD_JOBS:-4}
|
||||
# allow slower hosts to raise it without editing the script.
|
||||
export XENORA_SEMANTIC_TIMEOUT=${XENORA_SEMANTIC_TIMEOUT:-300s}
|
||||
|
||||
# macOS does not ship GNU timeout. Python 3 is already a project requirement,
|
||||
# so use a small POSIX-compatible fallback rather than making coreutils a
|
||||
# prerequisite for the native suite.
|
||||
if ! command -v timeout >/dev/null 2>&1; then
|
||||
timeout() {
|
||||
duration=$1
|
||||
shift
|
||||
python3 - "$duration" "$@" <<'PY'
|
||||
import os
|
||||
import re
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
text = sys.argv[1]
|
||||
match = re.fullmatch(r"(\d+(?:\.\d+)?)([smh]?)", text)
|
||||
if match is None:
|
||||
print(f"timeout: invalid duration {text!r}", file=sys.stderr)
|
||||
raise SystemExit(2)
|
||||
seconds = float(match.group(1)) * {"": 1, "s": 1, "m": 60, "h": 3600}[match.group(2)]
|
||||
try:
|
||||
process = subprocess.Popen(sys.argv[2:], start_new_session=True)
|
||||
except FileNotFoundError as error:
|
||||
print(f"timeout: {error}", file=sys.stderr)
|
||||
raise SystemExit(127)
|
||||
try:
|
||||
code = process.wait(timeout=seconds)
|
||||
except subprocess.TimeoutExpired:
|
||||
os.killpg(process.pid, signal.SIGKILL)
|
||||
process.wait()
|
||||
print(f"timeout: command exceeded {seconds:g} seconds", file=sys.stderr)
|
||||
raise SystemExit(124)
|
||||
raise SystemExit(code)
|
||||
PY
|
||||
}
|
||||
fi
|
||||
|
||||
cargo test --locked -p xenora-metal --features gpu-tests --test native_compute --no-run
|
||||
timeout 30s cargo test --locked -p xenora-metal --features gpu-tests --test native_compute -- \
|
||||
--nocapture --test-threads=1
|
||||
|
||||
Reference in new issue
Block a user