Compare commits

..
Author SHA1 Message Date
Adeeb Rahman 324eab08c3 Merge remote-tracking branch 'origin/main' into feat/runtime-fuzz-bench
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 18:32:27 -05:00
Adeeb RahmanandCursor eaeab25590 Record corrected runtime_services fuzz campaign evidence
Withdraw the unreachable-dispatch campaign counts and replace them with
the post-fix 300-second run (96,589 inputs, 4,008 coverage edges) plus
the XMemAlloc OOM that campaign found.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-24 11:28:48 -05:00
Adeeb RahmanandCursor 8d19006c32 Bound XMemAlloc through the virtual memory budget
The fixed fuzz harness reached service handlers and immediately found a
libFuzzer OOM: XMemAlloc mapped unbounded ImageOrStatic regions, so a
~3.7 GiB request tried to malloc host storage. Overflowing sizes still
fail closed, and successful sizes use map_virtual_allocation.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-24 11:23:12 -05:00
Adeeb RahmanandCursor 84221ac715 Fail closed on overflowing XMemAlloc sizes
The fuzz harness now reaches service handlers; a u64::MAX-sized request
panicked in debug builds while aligning to a page. Treat unrepresentable
sizes as allocation failure.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-24 11:20:11 -05:00
Adeeb RahmanandCursor 673e2a4556 Merge origin/main into feat/runtime-fuzz-bench
Sync with main after #215/#198/#130 landings. Keep the guest string-scan
changelog entry alongside the upstream SOP1 registry note, and correct the
runtime_services fuzz harness so corpus bytes drive dispatch instead of the
65,536-byte writable fill (withdrawing the earlier campaign counts).

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-24 11:20:11 -05:00
Adeeb Rahman b49d50e34e Decode MSVC decorated names for import diagnostics
Add a clean-room decoder for the common decoration grammar, show its
output in generator manifests, and test it against names clang mangles
for x86_64-pc-windows-msvc.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
(cherry picked from commit 506e09c909e75c92ef8a0050df67fc79f787028a)
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 10:33:26 -05:00
Adeeb Rahman e0a6dae554 Benchmark guest service dispatch and scan CRT strings in blocks
Add correctness-gated guest loops that time services through the
import table. Scan string lengths 256 units at a time, falling back to
single units at mapping boundaries to keep exact faults.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
(cherry picked from commit b9f6afb20c7541c69464e2e771396269961a8a49)
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 10:33:26 -05:00
Adeeb Rahman b3a6a57a8e Fuzz the standard guest service registry
Drive random service call sequences with adversarial arguments and
check memory and register invariants after every call. The libFuzzer
target and a stable replay test share one driver.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
(cherry picked from commit 3027b9eb06904793c464b80490aa3903bfe7e173)
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 10:33:26 -05:00
19 changed files with 1571 additions and 1023 deletions

No files matched your search

+1 -1
View File
@@ -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 CPU-only parser at a time: `scripts/fuzz.sh <instruction_stream|fixture|reference>` (600 seconds by default).
- 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.
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.
+7 -1
View File
@@ -10,6 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Changed
- Guest `strlen`, `strnlen`, `wcslen` and `wcsnlen` scan memory in 256-unit blocks, falling back to single units at mapping boundaries so faults still report the first inaccessible unit. On Apple M2 Pro the 63-byte `strlen` workload went from 1,990 ns to 223 ns per call (median of 10 batches, on a machine that was not idle).
- 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.
@@ -29,7 +30,6 @@ remains unsupported.
- Added a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status.
### Added
- `dbt_bench` can compare two of its JSON documents when `XENORA_DBT_BENCH_COMPARE=<baseline.json>,<candidate.json>` is set (#114). It prints each median with its change and whether the change exceeds the larger recorded IQR, and lists changed DBT counters. It refuses, with exit status 1 and the differing field named, to compare runs from different CPUs, operating systems or architectures, with unknown host fields, or with different workloads, sample counts, debug assertions or build labels. A new optional `XENORA_DBT_BENCH_BUILD_LABEL` records build settings the benchmark cannot see, such as LTO. No benchmark runs in this mode.
- `dbt_bench` can also write its results as one JSON document when `XENORA_DBT_BENCH_JSON=<path>` is set (#112). The document records the host CPU, OS and architecture, the git revision and whether the tree had local changes, debug assertions, the workload and sample counts, the median, minimum, maximum, p95, p99, IQR and MIPS for the interpreter and for cold and warm DBT, and the cold DBT counters. Anything the benchmark cannot determine is `null`. The text output and the timed work are unchanged.
- Added synthetic guest handle-lifetime regression tests (#205) for capacity reuse, stale handles, duplicate rights and lifetime, wrong object types, thread pseudo handles and failed-output nonmutation. Runtime behavior is unchanged; independent acceptance is pending.
- Added a documented independent acceptance rule for promoting AMD RDNA2 desktop GPU (gfx1030) forms from local CPU and Metal results to `fixture verified`, including clean-commit evidence, reviewer independence, raw-log location, review-log summary, failure handling and status regeneration (#302).
@@ -80,6 +80,12 @@ 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.
+529
View File
@@ -0,0 +1,529 @@
// 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}");
}
}
}
+2
View File
@@ -27,6 +27,7 @@
pub mod apiset;
pub mod classify;
pub mod codegen;
pub mod demangle;
pub mod ingest;
pub mod manifest;
pub mod metadata;
@@ -37,6 +38,7 @@ 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};
+7 -1
View File
@@ -166,7 +166,13 @@ impl Manifest {
if let Classification::Manual { reason } | Classification::Unsupported { reason } =
&e.classification
{
md.push_str(&format!("- `{}!{}` — {reason}\n", e.module, e.symbol));
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
+109
View File
@@ -0,0 +1,109 @@
// 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` —"));
}
+4
View File
@@ -25,3 +25,7 @@ xenora-shader = { path = "../shader" }
[[bench]]
name = "dbt_bench"
harness = false
[[bench]]
name = "service_dispatch"
harness = false
+3 -778
View File
@@ -5,14 +5,7 @@
//! Set `XENORA_DBT_BENCH_JSON=<path>` to also write the results as one JSON
//! document (format version 1). The text output does not change. Values the
//! benchmark cannot determine, such as the git revision outside a checkout,
//! are written as `null`. The benchmark cannot see build settings such as LTO,
//! so `XENORA_DBT_BENCH_BUILD_LABEL=<text>` records a label of your choosing
//! for them.
//!
//! Set `XENORA_DBT_BENCH_COMPARE=<baseline.json>,<candidate.json>` to compare
//! two such documents instead of running the benchmark. The comparison is
//! refused, with exit status 1, unless both runs used the same host, workload,
//! build settings and sample counts.
//! are written as `null`.
//!
//! The benchmark target disables Cargo's test harness. To run the percentile
//! unit tests, build with
@@ -161,7 +154,6 @@ struct RunInfo {
revision: Option<String>,
dirty: Option<bool>,
debug_assertions: bool,
build_label: Option<String>,
guest_code_bytes: usize,
warmup: usize,
}
@@ -195,7 +187,6 @@ fn run_info(guest_code_bytes: usize, warmup: usize) -> RunInfo {
dirty: command_output("git", &["status", "--porcelain", "--untracked-files=no"])
.map(|status| !status.is_empty()),
debug_assertions: cfg!(debug_assertions),
build_label: non_empty(std::env::var("XENORA_DBT_BENCH_BUILD_LABEL").ok()),
guest_code_bytes,
warmup,
}
@@ -283,10 +274,7 @@ fn json_document(
),
(
"build",
json_object(&[
("debug_assertions", info.debug_assertions.to_string()),
("label", json_option(info.build_label.as_ref(), string)),
]),
json_object(&[("debug_assertions", info.debug_assertions.to_string())]),
),
(
"workload",
@@ -331,471 +319,7 @@ fn json_document(
])
}
/// A parsed JSON value. Numbers keep their source text, so integers compare exactly.
#[derive(Clone, Debug, PartialEq)]
enum Json {
Null,
Bool(bool),
Number(String),
String(String),
Array(Vec<Json>),
Object(Vec<(String, Json)>),
}
impl Json {
/// The value at a dotted path such as `host.cpu`, if every step is an object key.
fn get(&self, path: &str) -> Option<&Json> {
path.split('.').try_fold(self, |value, key| match value {
Json::Object(fields) => fields.iter().find(|(k, _)| k == key).map(|(_, v)| v),
_ => None,
})
}
}
const MAX_JSON_DEPTH: usize = 32;
/// Reads one JSON document (RFC 8259) and rejects anything after it.
fn parse_json(text: &str) -> Result<Json, String> {
let mut reader = JsonReader {
bytes: text.as_bytes(),
pos: 0,
};
let value = reader.value(0)?;
reader.skip_whitespace();
if reader.pos != reader.bytes.len() {
return reader.error("unexpected data after the document");
}
Ok(value)
}
struct JsonReader<'a> {
bytes: &'a [u8],
pos: usize,
}
impl JsonReader<'_> {
fn error<T>(&self, what: &str) -> Result<T, String> {
Err(format!("{what} at byte {}", self.pos))
}
fn peek(&self) -> Option<u8> {
self.bytes.get(self.pos).copied()
}
fn skip_whitespace(&mut self) {
while matches!(self.peek(), Some(b' ' | b'\t' | b'\n' | b'\r')) {
self.pos += 1;
}
}
fn expect(&mut self, byte: u8) -> Result<(), String> {
if self.peek() == Some(byte) {
self.pos += 1;
Ok(())
} else {
self.error(&format!("expected '{}'", byte as char))
}
}
fn value(&mut self, depth: usize) -> Result<Json, String> {
if depth > MAX_JSON_DEPTH {
return self.error("nesting too deep");
}
self.skip_whitespace();
match self.peek() {
None => self.error("unexpected end of input"),
Some(b'n') => self.literal("null", Json::Null),
Some(b't') => self.literal("true", Json::Bool(true)),
Some(b'f') => self.literal("false", Json::Bool(false)),
Some(b'"') => Ok(Json::String(self.string()?)),
Some(b'[') => self.array(depth),
Some(b'{') => self.object(depth),
Some(b'-' | b'0'..=b'9') => self.number(),
Some(_) => self.error("unexpected character"),
}
}
fn literal(&mut self, word: &str, value: Json) -> Result<Json, String> {
if self.bytes[self.pos..].starts_with(word.as_bytes()) {
self.pos += word.len();
Ok(value)
} else {
self.error("invalid literal")
}
}
fn array(&mut self, depth: usize) -> Result<Json, String> {
self.expect(b'[')?;
let mut items = Vec::new();
self.skip_whitespace();
if self.peek() == Some(b']') {
self.pos += 1;
return Ok(Json::Array(items));
}
loop {
items.push(self.value(depth + 1)?);
self.skip_whitespace();
match self.peek() {
Some(b',') => self.pos += 1,
Some(b']') => {
self.pos += 1;
return Ok(Json::Array(items));
}
_ => return self.error("expected ',' or ']'"),
}
}
}
fn object(&mut self, depth: usize) -> Result<Json, String> {
self.expect(b'{')?;
let mut fields: Vec<(String, Json)> = Vec::new();
self.skip_whitespace();
if self.peek() == Some(b'}') {
self.pos += 1;
return Ok(Json::Object(fields));
}
loop {
self.skip_whitespace();
let key = self.string()?;
if fields.iter().any(|(k, _)| *k == key) {
return self.error(&format!("duplicate key `{key}`"));
}
self.skip_whitespace();
self.expect(b':')?;
let value = self.value(depth + 1)?;
fields.push((key, value));
self.skip_whitespace();
match self.peek() {
Some(b',') => self.pos += 1,
Some(b'}') => {
self.pos += 1;
return Ok(Json::Object(fields));
}
_ => return self.error("expected ',' or '}'"),
}
}
}
fn digits(&mut self) -> usize {
let start = self.pos;
while matches!(self.peek(), Some(b'0'..=b'9')) {
self.pos += 1;
}
self.pos - start
}
fn number(&mut self) -> Result<Json, String> {
let start = self.pos;
if self.peek() == Some(b'-') {
self.pos += 1;
}
match self.peek() {
Some(b'0') => self.pos += 1,
Some(b'1'..=b'9') => {
self.digits();
}
_ => return self.error("invalid number"),
}
if self.peek() == Some(b'.') {
self.pos += 1;
if self.digits() == 0 {
return self.error("invalid number");
}
}
if matches!(self.peek(), Some(b'e' | b'E')) {
self.pos += 1;
if matches!(self.peek(), Some(b'+' | b'-')) {
self.pos += 1;
}
if self.digits() == 0 {
return self.error("invalid number");
}
}
// Only ASCII digits and signs were consumed.
Ok(Json::Number(
String::from_utf8_lossy(&self.bytes[start..self.pos]).into_owned(),
))
}
fn hex4(&mut self) -> Result<u32, String> {
let digits = self.bytes.get(self.pos..self.pos + 4);
let value = digits
.and_then(|d| std::str::from_utf8(d).ok())
.and_then(|d| u32::from_str_radix(d, 16).ok());
match value {
Some(value) if digits.is_some_and(|d| d.iter().all(u8::is_ascii_hexdigit)) => {
self.pos += 4;
Ok(value)
}
_ => self.error("invalid \\u escape"),
}
}
fn unicode_escape(&mut self) -> Result<char, String> {
let first = self.hex4()?;
let code = match first {
0xD800..=0xDBFF => {
if !self.bytes[self.pos..].starts_with(b"\\u") {
return self.error("unpaired surrogate");
}
self.pos += 2;
let second = self.hex4()?;
if !(0xDC00..=0xDFFF).contains(&second) {
return self.error("unpaired surrogate");
}
0x10000 + ((first - 0xD800) << 10) + (second - 0xDC00)
}
0xDC00..=0xDFFF => return self.error("unpaired surrogate"),
code => code,
};
char::from_u32(code).map_or_else(|| self.error("invalid code point"), Ok)
}
fn string(&mut self) -> Result<String, String> {
self.expect(b'"')?;
let mut out = String::new();
loop {
// Copy the run up to the next quote, backslash or control byte. Those
// are ASCII, so the run never ends inside a multi-byte character.
let start = self.pos;
while matches!(self.peek(), Some(b) if b != b'"' && b != b'\\' && b >= 0x20) {
self.pos += 1;
}
match std::str::from_utf8(&self.bytes[start..self.pos]) {
Ok(run) => out.push_str(run),
Err(_) => return self.error("invalid UTF-8"),
}
match self.peek() {
Some(b'"') => {
self.pos += 1;
return Ok(out);
}
Some(b'\\') => {
self.pos += 1;
let escaped = self.peek();
self.pos += 1;
out.push(match escaped {
Some(b'"') => '"',
Some(b'\\') => '\\',
Some(b'/') => '/',
Some(b'b') => '\u{8}',
Some(b'f') => '\u{c}',
Some(b'n') => '\n',
Some(b'r') => '\r',
Some(b't') => '\t',
Some(b'u') => self.unicode_escape()?,
_ => {
self.pos -= 1;
return self.error("invalid escape");
}
});
}
Some(_) => return self.error("control character in string"),
None => return self.error("unterminated string"),
}
}
}
}
/// Fields that must be equal for two runs to be compared. A field listed in
/// `OPTIONAL_FIELDS` counts as `null` when a document does not have it.
const MATCHING_FIELDS: [&str; 15] = [
"format_version",
"benchmark",
"host.cpu",
"host.os",
"host.arch",
"build.debug_assertions",
"build.label",
"workload.name",
"workload.guest_instructions",
"workload.guest_code_bytes",
"workload.instruction_budget",
"workload.warmup_rounds",
"timings.interpreter.samples",
"timings.cold_dbt.samples",
"timings.warm_dbt.samples",
];
/// Older version 1 documents predate the build label.
const OPTIONAL_FIELDS: [&str; 1] = ["build.label"];
/// Host fields that must be known: two unknown CPUs are not the same CPU.
const KNOWN_FIELDS: [&str; 3] = ["host.cpu", "host.os", "host.arch"];
const SERIES: [(&str, &str); 3] = [
("interpreter", "Interpreter"),
("cold_dbt", "Cold DBT"),
("warm_dbt", "Warm DBT"),
];
const COUNTERS: [&str; 8] = [
"blocks_compiled",
"cache_hits",
"cache_misses",
"native_bytes_emitted",
"dbt_dispatches",
"instructions_executed",
"interpreter_fallbacks",
"service_calls",
];
fn field<'a>(doc: &'a Json, path: &str) -> Result<&'a Json, String> {
match doc.get(path) {
Some(value) => Ok(value),
None if OPTIONAL_FIELDS.contains(&path) => Ok(&Json::Null),
None => Err(format!("missing field `{path}`")),
}
}
fn integer(doc: &Json, path: &str) -> Result<u128, String> {
match field(doc, path)? {
Json::Number(text) => text
.parse()
.map_err(|_| format!("`{path}` is not a non-negative integer")),
_ => Err(format!("`{path}` is not a number")),
}
}
fn text(doc: &Json, path: &str) -> String {
match doc.get(path) {
Some(Json::String(value)) => value.clone(),
Some(Json::Bool(value)) => value.to_string(),
Some(Json::Number(value)) => value.clone(),
// The build label is optional, so its absence is not an unknown value.
_ if OPTIONAL_FIELDS.contains(&path) => "none".to_owned(),
_ => "unknown".to_owned(),
}
}
fn duration(ns: u128) -> Duration {
Duration::from_nanos(u64::try_from(ns).unwrap_or(u64::MAX))
}
fn change(before: u128, after: u128) -> String {
if before == 0 {
return "n/a".to_owned();
}
format!(
"{:+.2}%",
(after as f64 - before as f64) / before as f64 * 100.0
)
}
fn source(doc: &Json) -> String {
let dirty = match doc.get("source.dirty") {
Some(Json::Bool(true)) => " with local changes",
Some(Json::Bool(false)) => "",
_ => ", local changes unknown",
};
format!("{}{dirty}", text(doc, "source.revision"))
}
/// Compares two exported documents. Returns the report lines, or why the runs
/// cannot be compared.
fn compare_documents(baseline: &Json, candidate: &Json) -> Result<Vec<String>, String> {
for doc in [baseline, candidate] {
if field(doc, "format_version")? != &Json::Number("1".to_owned()) {
return Err("only format version 1 is supported".to_owned());
}
}
for path in KNOWN_FIELDS {
for (name, doc) in [("baseline", baseline), ("candidate", candidate)] {
if field(doc, path)? == &Json::Null {
return Err(format!(
"`{path}` is unknown in the {name}, so the hosts cannot be shown to match"
));
}
}
}
for path in MATCHING_FIELDS {
if field(baseline, path)? != field(candidate, path)? {
return Err(format!(
"`{path}` differs: baseline {}, candidate {}",
text(baseline, path),
text(candidate, path)
));
}
}
let mut lines = vec![
format!("Baseline: {}", source(baseline)),
format!("Candidate: {}", source(candidate)),
format!(
"Host: {}, {} {}; debug assertions {}; build label {}",
text(baseline, "host.cpu"),
text(baseline, "host.os"),
text(baseline, "host.arch"),
text(baseline, "build.debug_assertions"),
text(baseline, "build.label"),
),
];
if field(baseline, "host.os_version")? != field(candidate, "host.os_version")? {
lines.push(format!(
"Note: OS version differs: baseline {}, candidate {}",
text(baseline, "host.os_version"),
text(candidate, "host.os_version")
));
}
for (key, label) in SERIES {
let path = |stat: &str| format!("timings.{key}.{stat}");
let before = integer(baseline, &path("median_ns"))?;
let after = integer(candidate, &path("median_ns"))?;
let spread = integer(baseline, &path("iqr_ns"))?.max(integer(candidate, &path("iqr_ns"))?);
let verdict = if before.abs_diff(after) > spread {
"larger than"
} else {
"within"
};
lines.push(format!(
"{label}: median {:?} -> {:?} ({}), {verdict} the larger IQR {:?}",
duration(before),
duration(after),
change(before, after),
duration(spread)
));
}
let mut counters_changed = false;
for counter in COUNTERS {
let path = format!("cold_dbt_metrics.{counter}");
let (before, after) = (integer(baseline, &path)?, integer(candidate, &path)?);
if before != after {
counters_changed = true;
lines.push(format!(
"Cold DBT {counter}: {before} -> {after} ({})",
change(before, after)
));
}
}
if !counters_changed {
lines.push("Cold DBT counters are identical".to_owned());
}
Ok(lines)
}
fn compare_files(spec: &str) -> Result<Vec<String>, String> {
let (baseline, candidate) = spec
.split_once(',')
.ok_or("expected <baseline.json>,<candidate.json>")?;
let read = |path: &str| {
let text = std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?;
parse_json(&text).map_err(|e| format!("{path}: {e}"))
};
compare_documents(&read(baseline)?, &read(candidate)?)
}
fn main() {
if let Ok(spec) = std::env::var("XENORA_DBT_BENCH_COMPARE") {
match compare_files(&spec) {
Ok(lines) => lines.iter().for_each(|line| println!("{line}")),
Err(reason) => {
eprintln!("dbt_bench: cannot compare: {reason}");
std::process::exit(1);
}
}
return;
}
let sample_count = std::env::var("XENORA_DBT_BENCH_SAMPLES")
.map_or(101, |value| value.parse::<usize>().expect("sample count"));
assert!(sample_count > 0);
@@ -970,7 +494,6 @@ mod tests {
revision: Some("0123abcd".to_owned()),
dirty: Some(false),
debug_assertions: false,
build_label: Some("fat-lto".to_owned()),
guest_code_bytes: 40_011,
warmup: 10,
}
@@ -1005,7 +528,7 @@ mod tests {
r#"{{"format_version":1,"benchmark":"dbt_bench","unix_time":1700000000,"#,
r#""host":{{"cpu":"Test \"CPU\"\\1","os":"macos","os_version":null,"arch":"aarch64"}},"#,
r#""source":{{"revision":"0123abcd","dirty":false}},"#,
r#""build":{{"debug_assertions":false,"label":"fat-lto"}},"#,
r#""build":{{"debug_assertions":false}},"#,
r#""workload":{{"name":"add_rax_chain","guest_instructions":{},"guest_code_bytes":40011,"instruction_budget":20000,"warmup_rounds":10}},"#,
r#""timings":{{"interpreter":{},"cold_dbt":{},"warm_dbt":{}}},"#,
r#""cold_dbt_metrics":{{"blocks_compiled":626,"cache_hits":0,"cache_misses":626,"native_bytes_emitted":245168,"dbt_dispatches":626,"instructions_executed":10002,"interpreter_fallbacks":1,"service_calls":0}}}}"#,
@@ -1057,302 +580,4 @@ mod tests {
assert_eq!(s.iqr, Duration::from_micros(30));
assert_eq!(s.mips, INSTRUCTIONS as f64 / 25e-6 / 1e6);
}
// `cargo bench` builds this target with `--cfg test` but without `--test`,
// so this module is compiled with its #[test] functions removed and shared
// helpers look unused there.
#[allow(dead_code)]
fn comparable_document() -> super::Json {
super::parse_json(concat!(
r#"{"format_version":1,"benchmark":"dbt_bench","unix_time":1,"#,
r#""host":{"cpu":"Apple M5","os":"macos","os_version":"27.2.1","arch":"aarch64"},"#,
r#""source":{"revision":"aaaa","dirty":false},"#,
r#""build":{"debug_assertions":false,"label":null},"#,
r#""workload":{"name":"add_rax_chain","guest_instructions":10002,"guest_code_bytes":40011,"instruction_budget":20000,"warmup_rounds":10},"#,
r#""timings":{"#,
r#""interpreter":{"samples":101,"median_ns":900000,"min_ns":1,"max_ns":2,"p95_ns":1,"p99_ns":1,"iqr_ns":20000,"median_mips":11.1},"#,
r#""cold_dbt":{"samples":101,"median_ns":1100000,"min_ns":1,"max_ns":2,"p95_ns":1,"p99_ns":1,"iqr_ns":40000,"median_mips":9.1},"#,
r#""warm_dbt":{"samples":101,"median_ns":22000,"min_ns":1,"max_ns":2,"p95_ns":1,"p99_ns":1,"iqr_ns":500,"median_mips":454.6}},"#,
r#""cold_dbt_metrics":{"blocks_compiled":626,"cache_hits":0,"cache_misses":626,"native_bytes_emitted":245168,"dbt_dispatches":626,"instructions_executed":10002,"interpreter_fallbacks":0,"service_calls":0}}"#,
))
.expect("fixture parses")
}
/// Replaces the value at a dotted path, which must exist except for its last key.
#[allow(dead_code)]
fn set(doc: &mut super::Json, path: &str, value: super::Json) {
let (parent, key) = path.rsplit_once('.').map_or(("", path), |(p, k)| (p, k));
let mut node = doc;
for step in parent.split('.').filter(|s| !s.is_empty()) {
let super::Json::Object(fields) = node else {
panic!("{step} is not in an object")
};
node = &mut fields.iter_mut().find(|(k, _)| k == step).expect(step).1;
}
let super::Json::Object(fields) = node else {
panic!("{path} has no parent object")
};
match fields.iter_mut().find(|(k, _)| k == key) {
Some(entry) => entry.1 = value,
None => fields.push((key.to_owned(), value)),
}
}
#[test]
fn reader_accepts_json_values() {
use super::{Json, parse_json};
let doc = parse_json(
r#" { "a" : [1, -0.5, 2e3, 3E-2, true, false, null, {}, []], "s": "q\"b\\s\/n\n\té😀 Zażółć" } "#,
)
.unwrap();
assert_eq!(
doc.get("a"),
Some(&Json::Array(vec![
Json::Number("1".to_owned()),
Json::Number("-0.5".to_owned()),
Json::Number("2e3".to_owned()),
Json::Number("3E-2".to_owned()),
Json::Bool(true),
Json::Bool(false),
Json::Null,
Json::Object(vec![]),
Json::Array(vec![]),
]))
);
assert_eq!(
doc.get("s"),
Some(&Json::String("q\"b\\s/n\n\té😀 Zażółć".to_owned()))
);
assert_eq!(doc.get("a.b"), None);
assert_eq!(doc.get("missing"), None);
}
#[test]
fn reader_rejects_malformed_json() {
use super::parse_json;
let deep = "[".repeat(40) + &"]".repeat(40);
for bad in [
"",
"{",
r#"{"a":1,}"#,
r#"{"a" 1}"#,
r#"{"a":1,"a":2}"#,
"[1 2]",
"01",
"1.",
"-",
"1e",
"+1",
"tru",
r#""open"#,
"\"tab\tinside\"",
r#""\x""#,
r#""\u12g4""#,
r#""\u+123""#,
r#""\ud83d""#,
r#""\ude00""#,
r#""\ud83dA""#,
"{} {}",
deep.as_str(),
] {
assert!(parse_json(bad).is_err(), "accepted {bad:?}");
}
}
#[test]
fn exported_document_reads_back() {
use super::{DbtMetrics, Duration, Json, RunInfo, Summary, json_document, parse_json};
let summary = Summary {
samples: 7,
median: Duration::from_nanos(1_234_567),
min: Duration::from_nanos(1),
max: Duration::from_nanos(9),
p95: Duration::from_nanos(8),
p99: Duration::from_nanos(9),
iqr: Duration::from_nanos(3),
mips: 8.25,
};
let info = RunInfo {
unix_time: None,
cpu: Some("CPU \"x\" \\ \u{1}".to_owned()),
os: "macos",
os_version: None,
arch: "aarch64",
revision: None,
dirty: Some(true),
debug_assertions: true,
build_label: Some("é label".to_owned()),
guest_code_bytes: 5,
warmup: 2,
};
let metrics = DbtMetrics {
native_bytes_emitted: 42,
..DbtMetrics::default()
};
let doc = parse_json(&json_document(
&info, &summary, &summary, &summary, &metrics,
))
.unwrap();
let string = |s: &str| Some(Json::String(s.to_owned()));
assert_eq!(doc.get("host.cpu").cloned(), string("CPU \"x\" \\ \u{1}"));
assert_eq!(doc.get("build.label").cloned(), string("é label"));
assert_eq!(doc.get("host.os_version"), Some(&Json::Null));
assert_eq!(doc.get("source.dirty"), Some(&Json::Bool(true)));
assert_eq!(
doc.get("timings.cold_dbt.median_ns"),
Some(&Json::Number("1234567".to_owned()))
);
assert_eq!(
doc.get("cold_dbt_metrics.native_bytes_emitted"),
Some(&Json::Number("42".to_owned()))
);
}
#[test]
fn comparison_reports_changes_against_the_spread() {
use super::{Json, compare_documents};
let baseline = comparable_document();
let mut candidate = comparable_document();
set(
&mut candidate,
"source.revision",
Json::String("bbbb".to_owned()),
);
set(&mut candidate, "source.dirty", Json::Bool(true));
// 900 µs -> 846 µs is 54 µs, beyond the larger IQR of 20 µs.
set(
&mut candidate,
"timings.interpreter.median_ns",
Json::Number("846000".to_owned()),
);
// 1.1 ms -> 1.12 ms is 20 µs, within the larger IQR of 45 µs.
set(
&mut candidate,
"timings.cold_dbt.median_ns",
Json::Number("1120000".to_owned()),
);
set(
&mut candidate,
"timings.cold_dbt.iqr_ns",
Json::Number("45000".to_owned()),
);
set(
&mut candidate,
"cold_dbt_metrics.native_bytes_emitted",
Json::Number("290184".to_owned()),
);
set(
&mut candidate,
"host.os_version",
Json::String("27.3".to_owned()),
);
let lines = compare_documents(&baseline, &candidate).unwrap();
assert_eq!(
lines,
[
"Baseline: aaaa",
"Candidate: bbbb with local changes",
"Host: Apple M5, macos aarch64; debug assertions false; build label none",
"Note: OS version differs: baseline 27.2.1, candidate 27.3",
"Interpreter: median 900µs -> 846µs (-6.00%), larger than the larger IQR 20µs",
"Cold DBT: median 1.1ms -> 1.12ms (+1.82%), within the larger IQR 45µs",
"Warm DBT: median 22µs -> 22µs (+0.00%), within the larger IQR 500ns",
"Cold DBT native_bytes_emitted: 245168 -> 290184 (+18.36%)",
]
);
let same = compare_documents(&baseline, &baseline).unwrap();
assert_eq!(same.last().unwrap(), "Cold DBT counters are identical");
}
#[test]
fn comparison_rejects_every_mismatching_field() {
use super::{Json, compare_documents};
// Written out independently of MATCHING_FIELDS, so dropping a field
// there fails this test.
for path in [
"format_version",
"benchmark",
"host.cpu",
"host.os",
"host.arch",
"build.debug_assertions",
"build.label",
"workload.name",
"workload.guest_instructions",
"workload.guest_code_bytes",
"workload.instruction_budget",
"workload.warmup_rounds",
"timings.interpreter.samples",
"timings.cold_dbt.samples",
"timings.warm_dbt.samples",
] {
let mut candidate = comparable_document();
let other = match path {
"build.debug_assertions" => Json::Bool(true),
"build.label" => Json::String("fat-lto".to_owned()),
// A valid but different version is refused as unsupported first.
"format_version" => Json::Number("2".to_owned()),
p if p.contains("samples")
|| p.starts_with("workload.") && p != "workload.name" =>
{
Json::Number("7".to_owned())
}
_ => Json::String("other".to_owned()),
};
set(&mut candidate, path, other);
let error = compare_documents(&comparable_document(), &candidate).expect_err(path);
assert!(
error.contains(path) || path == "format_version" && error.contains("version"),
"{path}: {error}"
);
}
}
#[test]
fn comparison_needs_known_hosts_and_matching_labels() {
use super::{Json, compare_documents};
for path in ["host.cpu", "host.os", "host.arch"] {
let mut unknown = comparable_document();
set(&mut unknown, path, Json::Null);
let error = compare_documents(&unknown, &unknown).expect_err(path);
assert!(error.contains("unknown in the baseline"), "{error}");
}
// A document written before the label existed counts as having no label.
let mut old = comparable_document();
let Json::Object(fields) = &mut old else {
unreachable!()
};
let build = &mut fields.iter_mut().find(|(k, _)| k == "build").unwrap().1;
let Json::Object(build) = build else {
unreachable!()
};
build.retain(|(k, _)| k != "label");
assert!(compare_documents(&old, &comparable_document()).is_ok());
let mut labelled = comparable_document();
set(
&mut labelled,
"build.label",
Json::String("fat-lto".to_owned()),
);
assert!(compare_documents(&old, &labelled).is_err());
assert!(compare_documents(&labelled, &labelled).is_ok());
let mut missing = comparable_document();
let Json::Object(fields) = &mut missing else {
unreachable!()
};
fields.retain(|(k, _)| k != "workload");
let error = compare_documents(&comparable_document(), &missing).unwrap_err();
assert!(error.contains("missing field `workload.name`"), "{error}");
}
}
+225
View File
@@ -0,0 +1,225 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Guest-to-host service dispatch cost, measured with original guest loops
//! that call standard services through a bound import table under the DBT.
//!
//! Every workload checks its result before timing. Each reported figure is
//! the per-iteration time of a loop of `ITERATIONS` calls: one warm-up batch,
//! then `BATCHES` measured batches. The empty loop is reported separately so
//! readers can subtract the loop and translation overhead themselves.
//!
//! Run with `cargo bench --locked -p xenora-loader --bench service_dispatch`.
#[path = "../tests/support/mod.rs"]
mod support;
use std::time::Instant;
use support::*;
use xenora_loader::cpu::{ExitReason, Register};
use xenora_loader::services::sysinfo::HostCapabilities;
const IMPORTS: &[(&str, &str)] = &[
("kernel32.dll", "GetLastError"),
("kernel32.dll", "CreateEventW"),
("kernel32.dll", "WaitForSingleObject"),
("ucrtbase.dll", "strlen"),
("kernel32.dll", "GetProcessHeap"),
("kernel32.dll", "HeapAlloc"),
("kernel32.dll", "HeapFree"),
("ucrtbase.dll", "qsort"),
];
const ITERATIONS: u32 = 10_000;
const BATCHES: usize = 10;
const CELL_EVENT: u64 = SCRATCH + 0x10;
const CELL_HEAP: u64 = SCRATCH + 0x18;
const STRING: u64 = SCRATCH + 0x100;
const ARRAY: u64 = SCRATCH + 0x200;
const ARRAY_LEN: u32 = 16;
const EMPTY: usize = 0;
const LAST_ERROR: usize = 1;
const WAIT: usize = 2;
const STRLEN: usize = 3;
const HEAP: usize = 4;
const QSORT: usize = 5;
const COMPARE: usize = 6;
/// A tiny x86-64 assembler for the routines below.
struct Asm {
base: u64,
code: Vec<u8>,
}
impl Asm {
fn new(routine_index: usize) -> Self {
Self {
base: routine(routine_index),
code: Vec::new(),
}
}
fn bytes(&mut self, bytes: &[u8]) -> &mut Self {
self.code.extend_from_slice(bytes);
self
}
fn imm64(&mut self, opcode: &[u8], value: u64) -> &mut Self {
self.bytes(opcode).bytes(&value.to_le_bytes())
}
fn imm32(&mut self, opcode: &[u8], value: u32) -> &mut Self {
self.bytes(opcode).bytes(&value.to_le_bytes())
}
/// `call qword ptr [rip + displacement]` through an import slot.
fn call_import(&mut self, symbol: &str) -> &mut Self {
let index = IMPORTS
.iter()
.position(|(_, name)| *name == symbol)
.unwrap();
let next = self.base + self.code.len() as u64 + 6;
let displacement = import_slot(IMPORTS, index).wrapping_sub(next) as u32;
self.imm32(&[0xFF, 0x15], displacement)
}
/// `mov ebx, ITERATIONS`, the loop body, `dec ebx; jnz body; hlt`.
fn counted(routine_index: usize, body: impl FnOnce(&mut Self)) -> Vec<u8> {
let mut asm = Self::new(routine_index);
asm.imm32(&[0xBB], ITERATIONS);
let start = asm.code.len();
body(&mut asm);
asm.bytes(&[0xFF, 0xCB]); // dec ebx
let back = start as i64 - (asm.code.len() as i64 + 2);
asm.bytes(&[0x75, i8::try_from(back).unwrap() as u8, 0xF4]);
asm.code
}
}
fn routines() -> Vec<Vec<u8>> {
let mut routines = vec![Vec::new(); 7];
routines[EMPTY] = Asm::counted(EMPTY, |_| {});
routines[LAST_ERROR] = Asm::counted(LAST_ERROR, |asm| {
asm.call_import("GetLastError");
});
routines[WAIT] = Asm::counted(WAIT, |asm| {
asm.imm64(&[0x48, 0xB8], CELL_EVENT) // mov rax, cell
.bytes(&[0x48, 0x8B, 0x08]) // mov rcx, [rax]
.bytes(&[0x31, 0xD2]) // xor edx, edx
.call_import("WaitForSingleObject");
});
routines[STRLEN] = Asm::counted(STRLEN, |asm| {
asm.imm64(&[0x48, 0xB9], STRING).call_import("strlen");
});
routines[HEAP] = Asm::counted(HEAP, |asm| {
asm.imm64(&[0x48, 0xB8], CELL_HEAP)
.bytes(&[0x48, 0x8B, 0x08]) // mov rcx, [rax]
.bytes(&[0x31, 0xD2])
.imm32(&[0x41, 0xB8], 64) // mov r8d, 64
.call_import("HeapAlloc")
.bytes(&[0x49, 0x89, 0xC0]) // mov r8, rax
.imm64(&[0x48, 0xB8], CELL_HEAP)
.bytes(&[0x48, 0x8B, 0x08])
.bytes(&[0x31, 0xD2])
.call_import("HeapFree");
});
routines[QSORT] = Asm::counted(QSORT, |asm| {
asm.imm64(&[0x48, 0xB9], ARRAY)
.imm32(&[0xBA], ARRAY_LEN) // mov edx, count
.imm32(&[0x41, 0xB8], 4) // mov r8d, width
.imm64(&[0x49, 0xB9], routine(COMPARE))
.call_import("qsort");
});
// int compare(const int *a, const int *b) { return *a - *b; }
routines[COMPARE] = vec![0x8B, 0x01, 0x2B, 0x02, 0xC3];
routines
}
fn median(samples: &mut [f64]) -> f64 {
samples.sort_by(f64::total_cmp);
samples[samples.len() / 2]
}
fn main() {
let mut guest = Guest::new(IMPORTS, &routines());
let event = guest.call("CreateEventW", &[0, 1, 1, 0]);
assert_ne!(event, 0);
guest.memory.write_u64(CELL_EVENT, event).unwrap();
let heap = guest.call("GetProcessHeap", &[]);
guest.memory.write_u64(CELL_HEAP, heap).unwrap();
guest.memory.write_bytes(STRING, &[b'a'; 63]).unwrap();
guest.memory.write_u8(STRING + 63, 0).unwrap();
let unsorted: Vec<i32> = (0..ARRAY_LEN as i32)
.map(|i| (i * 7919) % 31 - 15)
.collect();
let reset_array = |guest: &mut Guest| {
for (index, value) in unsorted.iter().enumerate() {
guest
.memory
.write_u32(ARRAY + 4 * index as u64, *value as u32)
.unwrap();
}
};
let host = HostCapabilities::detect();
let brand = std::process::Command::new("sysctl")
.args(["-n", "machdep.cpu.brand_string"])
.output()
.map(|output| String::from_utf8_lossy(&output.stdout).trim().to_owned())
.unwrap_or_default();
println!(
"host: {brand}, {} logical processors; profile: {}",
host.logical_processors.unwrap_or(0),
if cfg!(debug_assertions) {
"debug"
} else {
"release"
},
);
println!("{ITERATIONS} iterations per batch, 1 warm-up and {BATCHES} measured batches");
println!("workload,median_ns_per_iteration,min_ns,max_ns");
for (name, index, check) in [
("empty loop", EMPTY, None),
("GetLastError", LAST_ERROR, Some(0)),
(
"WaitForSingleObject (signaled manual-reset event)",
WAIT,
Some(0),
),
("strlen (63 bytes)", STRLEN, Some(63)),
("HeapAlloc + HeapFree (64 bytes)", HEAP, Some(1)),
("qsort (16 ints, guest comparator)", QSORT, Some(0)),
] {
let mut samples = Vec::with_capacity(BATCHES);
for batch in 0..=BATCHES {
if index == QSORT {
reset_array(&mut guest);
}
let start = Instant::now();
let (cpu, exit) = guest.execute(routine(index), usize::MAX);
let elapsed = start.elapsed();
assert_eq!(exit, ExitReason::Halt, "{name}");
assert_eq!(cpu.get(Register::Rbx), 0, "{name} loop count");
if let Some(expected) = check {
assert_eq!(cpu.get(Register::Rax), expected, "{name} result");
}
if index == QSORT {
let mut expected = unsorted.clone();
expected.sort();
let sorted: Vec<i32> = (0..ARRAY_LEN as u64)
.map(|i| guest.u32_at(ARRAY + 4 * i) as i32)
.collect();
assert_eq!(sorted, expected, "{name} ordering");
}
if batch > 0 {
samples.push(elapsed.as_nanos() as f64 / f64::from(ITERATIONS));
}
}
let (min, max) = samples.iter().fold((f64::MAX, 0f64), |(low, high), &s| {
(low.min(s), high.max(s))
});
println!("{name},{:.1},{min:.1},{max:.1}", median(&mut samples));
}
}
+14 -10
View File
@@ -439,20 +439,24 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc<Serv
return Ok(0);
}
let page_size = 4096;
let aligned_size = (size + page_size - 1) & !(page_size - 1);
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 alloc_addr = s
.next_alloc_addr
.fetch_add(aligned_size as u64, Ordering::SeqCst);
if mem
.map_region(alloc_addr, aligned_size, MemoryPermissions::READ_WRITE)
.is_err()
{
return Ok(0);
}
Ok(alloc_addr)
Ok(mem
.map_virtual_allocation(alloc_addr, aligned_size, MemoryPermissions::READ_WRITE)
.unwrap_or(0))
};
registry.register("xmem.dll", "XMemAlloc", handler);
registry.set_status("xmem.dll", "XMemAlloc", ServiceStatus::Partial);
+30 -3
View File
@@ -45,11 +45,38 @@ fn string_length(
limit: u64,
unit: StringUnit,
) -> Result<u64, ExitReason> {
const BLOCK: u64 = 256;
let budget = SCAN_BUDGET / unit.width();
for offset in 0..limit.min(budget) {
if unit.read(memory, address, offset)? == 0 {
return Ok(offset);
let scan = limit.min(budget);
let mut buffer = [0u8; 2 * BLOCK as usize];
let mut offset = 0;
while offset < scan {
let count = BLOCK.min(scan - offset);
let bytes = &mut buffer[..(count * unit.width()) as usize];
// A block that crosses into unmapped or unreadable memory is scanned
// one unit at a time, so a terminator before the boundary still ends
// the scan and the fault reports the first inaccessible unit.
let block = address
.checked_add(offset * unit.width())
.filter(|_| address != 0)
.is_some_and(|start| memory.read_bytes(start, bytes).is_ok());
for index in 0..count {
let value = if block {
match unit {
StringUnit::Byte => u16::from(bytes[index as usize]),
StringUnit::Wide => {
let at = 2 * index as usize;
u16::from_le_bytes([bytes[at], bytes[at + 1]])
}
}
} else {
unit.read(memory, address, offset + index)?
};
if value == 0 {
return Ok(offset + index);
}
}
offset += count;
}
if limit <= budget {
return Ok(limit);
+88
View File
@@ -0,0 +1,88 @@
// 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:?}");
}
+248 -227
View File
@@ -1,227 +1,248 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Shared harness for runtime service tests: an original PE32+ image whose
//! imports are bound to the standard service registry and called from
//! translated guest code.
#![allow(dead_code)]
use std::sync::Arc;
use xenora_loader::cpu::{CpuState, ExitReason, Register};
use xenora_loader::dbt::DbtEngine;
use xenora_loader::imports::ImportRegistry;
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
use xenora_loader::pe::ParsedPe;
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
pub const BASE: u64 = 0x1_4000_0000;
pub const CODE_RVA: u32 = 0x1000;
const IDATA_RVA: u32 = 0x10000;
const IDATA_RAW: usize = 0x2200;
const IDATA_LEN: usize = 0x4000;
pub const SCRATCH: u64 = 0x5_0000;
pub const SCRATCH_LEN: u64 = 0x1000;
pub const STACK: u64 = 0x8_0000;
pub const STACK_TOP: u64 = STACK + 0x800;
pub const THREAD_A: u64 = 0x7_0000;
pub const THREAD_B: u64 = 0x7_2000;
/// Guest routines start at this RVA in the text section, 32 bytes apart.
pub const ROUTINES_RVA: u32 = 0x1800;
pub const RUNTIME_LIMIT: ExitReason = ExitReason::IllegalInstruction(0xFE);
/// Guest address of routine `index`.
pub fn routine(index: usize) -> u64 {
BASE + u64::from(ROUTINES_RVA) + 32 * index as u64
}
/// The code for import `n`, at RVA 0x1000 + 16n, is `call [its slot]; hlt`.
/// Each import has its own descriptor.
fn build(imports: &[(&str, &str)], routines: &[Vec<u8>]) -> Vec<u8> {
let mut pe = vec![0u8; IDATA_RAW + IDATA_LEN];
fn put(pe: &mut [u8], at: usize, bytes: &[u8]) {
pe[at..at + bytes.len()].copy_from_slice(bytes);
}
put(&mut pe, 0, b"MZ");
put(&mut pe, 0x3C, &0x80u32.to_le_bytes());
put(&mut pe, 0x80, b"PE\0\0");
put(&mut pe, 0x84, &0x8664u16.to_le_bytes());
put(&mut pe, 0x86, &2u16.to_le_bytes());
put(&mut pe, 0x94, &240u16.to_le_bytes());
let optional = 0x98;
put(&mut pe, optional, &0x20Bu16.to_le_bytes());
put(&mut pe, optional + 16, &CODE_RVA.to_le_bytes());
put(&mut pe, optional + 24, &BASE.to_le_bytes());
put(&mut pe, optional + 32, &0x1000u32.to_le_bytes());
put(&mut pe, optional + 36, &0x200u32.to_le_bytes());
put(&mut pe, optional + 56, &0x20000u32.to_le_bytes());
put(&mut pe, optional + 60, &0x200u32.to_le_bytes());
put(&mut pe, optional + 108, &16u32.to_le_bytes());
put(&mut pe, optional + 120, &IDATA_RVA.to_le_bytes());
put(&mut pe, optional + 124, &0x100u32.to_le_bytes());
for (index, (name, rva, raw, len, flags)) in [
(b".text", CODE_RVA, 0x200, 0x2000, 0x6000_0020u32),
(b".idat", IDATA_RVA, IDATA_RAW, IDATA_LEN, 0xC000_0040),
]
.into_iter()
.enumerate()
{
let section = optional + 240 + 40 * index;
put(&mut pe, section, name);
put(&mut pe, section + 8, &(len as u32).to_le_bytes());
put(&mut pe, section + 12, &rva.to_le_bytes());
put(&mut pe, section + 16, &(len as u32).to_le_bytes());
put(&mut pe, section + 20, &(raw as u32).to_le_bytes());
put(&mut pe, section + 36, &flags.to_le_bytes());
}
assert!(16 * imports.len() <= (ROUTINES_RVA - CODE_RVA) as usize);
let file = |rva: u32| IDATA_RAW + (rva - IDATA_RVA) as usize;
let mut next = IDATA_RVA + 20 * (imports.len() as u32 + 1);
let mut take = |len: usize| {
let rva = next;
next = (next + len as u32 + 7) & !7;
rva
};
for (index, (module, symbol)) in imports.iter().enumerate() {
let module_rva = take(module.len() + 1);
put(&mut pe, file(module_rva), module.as_bytes());
let hint = take(symbol.len() + 3);
put(&mut pe, file(hint) + 2, symbol.as_bytes());
let (lookup, slot) = (take(16), take(16));
put(&mut pe, file(lookup), &u64::from(hint).to_le_bytes());
put(&mut pe, file(slot), &u64::from(hint).to_le_bytes());
let descriptor = file(IDATA_RVA) + 20 * index;
put(&mut pe, descriptor, &lookup.to_le_bytes());
put(&mut pe, descriptor + 12, &module_rva.to_le_bytes());
put(&mut pe, descriptor + 16, &slot.to_le_bytes());
let code_rva = CODE_RVA + 16 * index as u32;
let displacement = slot.wrapping_sub(code_rva + 6);
let at = 0x200 + 16 * index;
put(&mut pe, at, &[0xFF, 0x15]); // call qword ptr [rip + displacement]
put(&mut pe, at + 2, &displacement.to_le_bytes());
put(&mut pe, at + 6, &[0xF4]); // hlt
}
for (index, code) in routines.iter().enumerate() {
assert!(code.len() <= 32);
let at = 0x200 + (ROUTINES_RVA - CODE_RVA) as usize + 32 * index;
put(&mut pe, at, code);
}
pe
}
pub struct Guest {
engine: DbtEngine,
pub memory: GuestMemory,
pub state: Arc<ServicesState>,
imports: &'static [(&'static str, &'static str)],
teb: u64,
}
impl Guest {
pub fn new(imports: &'static [(&'static str, &'static str)], routines: &[Vec<u8>]) -> Self {
let state = ServicesState::new(Arc::new(MockClock::new(0)));
Self::with_state(imports, routines, state)
}
pub fn with_state(
imports: &'static [(&'static str, &'static str)],
routines: &[Vec<u8>],
state: ServicesState,
) -> Self {
let bytes = build(imports, routines);
let pe = ParsedPe::parse(&bytes).unwrap();
let mut memory = pe.load_into_memory(&bytes).unwrap().memory;
memory
.map_region(SCRATCH, SCRATCH_LEN as usize, MemoryPermissions::READ_WRITE)
.unwrap();
memory
.map_region(STACK, 0x1000, MemoryPermissions::READ_WRITE)
.unwrap();
let state = Arc::new(state);
let mut registry = ImportRegistry::new();
register_standard_services(&mut registry, Arc::clone(&state));
let bound = registry
.bind_imports(&pe, &bytes, BASE, &mut memory)
.unwrap();
assert_eq!(bound, imports.len());
let mut engine = DbtEngine::new(256 * 1024).unwrap();
engine.set_import_registry(registry);
Self {
engine,
memory,
state,
imports,
teb: THREAD_A,
}
}
pub fn on(&mut self, teb: u64) -> &mut Self {
self.teb = teb;
self
}
/// Call an import with Win64 arguments. Arguments after the fourth go on
/// the stack after the return address and the home area.
pub fn run(&mut self, symbol: &str, args: &[u64]) -> (u64, ExitReason) {
let index = self
.imports
.iter()
.position(|(_, name)| *name == symbol)
.unwrap_or_else(|| panic!("{symbol} is not imported"));
let mut cpu = CpuState::new(BASE + u64::from(CODE_RVA) + 16 * index as u64, STACK_TOP);
cpu.gs_base = self.teb;
for (register, value) in [Register::Rcx, Register::Rdx, Register::R8, Register::R9]
.into_iter()
.zip(args)
{
cpu.set(register, *value);
}
for (slot, value) in args.iter().skip(4).enumerate() {
let address = STACK_TOP + 32 + 8 * slot as u64;
self.memory.write_u64(address, *value).unwrap();
}
use Register::{R12, R13, R14, R15, Rbp, Rbx, Rdi, Rsi};
let nonvolatile = [Rbx, Rbp, Rdi, Rsi, R12, R13, R14, R15];
for (index, register) in nonvolatile.into_iter().enumerate() {
cpu.set(register, 0x5EED_0000 + index as u64);
}
let result = self.engine.run(&mut cpu, &mut self.memory, 100_000);
if result.exit_reason == ExitReason::Halt {
// The service returned to the instruction after its CALL.
assert_eq!(cpu.get(Register::Rsp), STACK_TOP, "{symbol}");
for (index, register) in nonvolatile.into_iter().enumerate() {
assert_eq!(cpu.get(register), 0x5EED_0000 + index as u64, "{symbol}");
}
}
(cpu.get(Register::Rax), result.exit_reason)
}
pub fn call(&mut self, symbol: &str, args: &[u64]) -> u64 {
let (rax, exit) = self.run(symbol, args);
assert_eq!(exit, ExitReason::Halt, "{symbol}");
rax
}
pub fn fails(&mut self, symbol: &str, args: &[u64]) -> ExitReason {
let (_, exit) = self.run(symbol, args);
assert_ne!(exit, ExitReason::Halt, "{symbol} should stop the guest");
exit
}
pub fn error(&mut self) -> u64 {
self.call("GetLastError", &[])
}
pub fn u16_at(&self, address: u64) -> u16 {
self.memory.read_u16(address).unwrap()
}
pub fn u32_at(&self, address: u64) -> u32 {
self.memory.read_u32(address).unwrap()
}
pub fn u64_at(&self, address: u64) -> u64 {
self.memory.read_u64(address).unwrap()
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
//! Shared harness for runtime service tests: an original PE32+ image whose
//! imports are bound to the standard service registry and called from
//! translated guest code.
#![allow(dead_code)]
pub mod robustness;
use std::sync::Arc;
use xenora_loader::cpu::{CpuState, ExitReason, Register};
use xenora_loader::dbt::DbtEngine;
use xenora_loader::imports::ImportRegistry;
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
use xenora_loader::pe::ParsedPe;
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
pub const BASE: u64 = 0x1_4000_0000;
pub const CODE_RVA: u32 = 0x1000;
const IDATA_RVA: u32 = 0x10000;
const IDATA_RAW: usize = 0x2200;
const IDATA_LEN: usize = 0x4000;
pub const SCRATCH: u64 = 0x5_0000;
pub const SCRATCH_LEN: u64 = 0x1000;
pub const STACK: u64 = 0x8_0000;
pub const STACK_TOP: u64 = STACK + 0x800;
pub const THREAD_A: u64 = 0x7_0000;
pub const THREAD_B: u64 = 0x7_2000;
/// Guest routines start at this RVA in the text section, 64 bytes apart.
pub const ROUTINES_RVA: u32 = 0x1800;
pub const ROUTINE_SIZE: usize = 64;
pub const RUNTIME_LIMIT: ExitReason = ExitReason::IllegalInstruction(0xFE);
/// Guest address of routine `index`.
pub fn routine(index: usize) -> u64 {
BASE + u64::from(ROUTINES_RVA) + (ROUTINE_SIZE * index) as u64
}
/// Guest address of the import address table slot for `imports[index]`, as
/// laid out by the image builder.
pub fn import_slot(imports: &[(&str, &str)], index: usize) -> u64 {
BASE + u64::from(build_image(imports, &[]).1[index])
}
/// The code for import `n`, at RVA 0x1000 + 16n, is `call [its slot]; hlt`.
/// Each import has its own descriptor.
fn build_image(imports: &[(&str, &str)], routines: &[Vec<u8>]) -> (Vec<u8>, Vec<u32>) {
let mut pe = vec![0u8; IDATA_RAW + IDATA_LEN];
fn put(pe: &mut [u8], at: usize, bytes: &[u8]) {
pe[at..at + bytes.len()].copy_from_slice(bytes);
}
put(&mut pe, 0, b"MZ");
put(&mut pe, 0x3C, &0x80u32.to_le_bytes());
put(&mut pe, 0x80, b"PE\0\0");
put(&mut pe, 0x84, &0x8664u16.to_le_bytes());
put(&mut pe, 0x86, &2u16.to_le_bytes());
put(&mut pe, 0x94, &240u16.to_le_bytes());
let optional = 0x98;
put(&mut pe, optional, &0x20Bu16.to_le_bytes());
put(&mut pe, optional + 16, &CODE_RVA.to_le_bytes());
put(&mut pe, optional + 24, &BASE.to_le_bytes());
put(&mut pe, optional + 32, &0x1000u32.to_le_bytes());
put(&mut pe, optional + 36, &0x200u32.to_le_bytes());
put(&mut pe, optional + 56, &0x20000u32.to_le_bytes());
put(&mut pe, optional + 60, &0x200u32.to_le_bytes());
put(&mut pe, optional + 108, &16u32.to_le_bytes());
put(&mut pe, optional + 120, &IDATA_RVA.to_le_bytes());
put(&mut pe, optional + 124, &0x100u32.to_le_bytes());
for (index, (name, rva, raw, len, flags)) in [
(b".text", CODE_RVA, 0x200, 0x2000, 0x6000_0020u32),
(b".idat", IDATA_RVA, IDATA_RAW, IDATA_LEN, 0xC000_0040),
]
.into_iter()
.enumerate()
{
let section = optional + 240 + 40 * index;
put(&mut pe, section, name);
put(&mut pe, section + 8, &(len as u32).to_le_bytes());
put(&mut pe, section + 12, &rva.to_le_bytes());
put(&mut pe, section + 16, &(len as u32).to_le_bytes());
put(&mut pe, section + 20, &(raw as u32).to_le_bytes());
put(&mut pe, section + 36, &flags.to_le_bytes());
}
assert!(16 * imports.len() <= (ROUTINES_RVA - CODE_RVA) as usize);
let file = |rva: u32| IDATA_RAW + (rva - IDATA_RVA) as usize;
let mut next = IDATA_RVA + 20 * (imports.len() as u32 + 1);
let mut take = |len: usize| {
let rva = next;
next = (next + len as u32 + 7) & !7;
rva
};
let mut slots = Vec::with_capacity(imports.len());
for (index, (module, symbol)) in imports.iter().enumerate() {
let module_rva = take(module.len() + 1);
put(&mut pe, file(module_rva), module.as_bytes());
let hint = take(symbol.len() + 3);
put(&mut pe, file(hint) + 2, symbol.as_bytes());
let (lookup, slot) = (take(16), take(16));
put(&mut pe, file(lookup), &u64::from(hint).to_le_bytes());
put(&mut pe, file(slot), &u64::from(hint).to_le_bytes());
let descriptor = file(IDATA_RVA) + 20 * index;
put(&mut pe, descriptor, &lookup.to_le_bytes());
put(&mut pe, descriptor + 12, &module_rva.to_le_bytes());
put(&mut pe, descriptor + 16, &slot.to_le_bytes());
slots.push(slot);
let code_rva = CODE_RVA + 16 * index as u32;
let displacement = slot.wrapping_sub(code_rva + 6);
let at = 0x200 + 16 * index;
put(&mut pe, at, &[0xFF, 0x15]); // call qword ptr [rip + displacement]
put(&mut pe, at + 2, &displacement.to_le_bytes());
put(&mut pe, at + 6, &[0xF4]); // hlt
}
for (index, code) in routines.iter().enumerate() {
assert!(code.len() <= ROUTINE_SIZE);
let at = 0x200 + (ROUTINES_RVA - CODE_RVA) as usize + ROUTINE_SIZE * index;
put(&mut pe, at, code);
}
(pe, slots)
}
pub struct Guest {
engine: DbtEngine,
pub memory: GuestMemory,
pub state: Arc<ServicesState>,
imports: &'static [(&'static str, &'static str)],
teb: u64,
}
impl Guest {
pub fn new(imports: &'static [(&'static str, &'static str)], routines: &[Vec<u8>]) -> Self {
let state = ServicesState::new(Arc::new(MockClock::new(0)));
Self::with_state(imports, routines, state)
}
pub fn with_state(
imports: &'static [(&'static str, &'static str)],
routines: &[Vec<u8>],
state: ServicesState,
) -> Self {
let (bytes, _) = build_image(imports, routines);
let pe = ParsedPe::parse(&bytes).unwrap();
let mut memory = pe.load_into_memory(&bytes).unwrap().memory;
memory
.map_region(SCRATCH, SCRATCH_LEN as usize, MemoryPermissions::READ_WRITE)
.unwrap();
memory
.map_region(STACK, 0x1000, MemoryPermissions::READ_WRITE)
.unwrap();
let state = Arc::new(state);
let mut registry = ImportRegistry::new();
register_standard_services(&mut registry, Arc::clone(&state));
let bound = registry
.bind_imports(&pe, &bytes, BASE, &mut memory)
.unwrap();
assert_eq!(bound, imports.len());
let mut engine = DbtEngine::new(256 * 1024).unwrap();
engine.set_import_registry(registry);
Self {
engine,
memory,
state,
imports,
teb: THREAD_A,
}
}
pub fn on(&mut self, teb: u64) -> &mut Self {
self.teb = teb;
self
}
/// Call an import with Win64 arguments. Arguments after the fourth go on
/// the stack after the return address and the home area.
pub fn run(&mut self, symbol: &str, args: &[u64]) -> (u64, ExitReason) {
let index = self
.imports
.iter()
.position(|(_, name)| *name == symbol)
.unwrap_or_else(|| panic!("{symbol} is not imported"));
let mut cpu = CpuState::new(BASE + u64::from(CODE_RVA) + 16 * index as u64, STACK_TOP);
cpu.gs_base = self.teb;
for (register, value) in [Register::Rcx, Register::Rdx, Register::R8, Register::R9]
.into_iter()
.zip(args)
{
cpu.set(register, *value);
}
for (slot, value) in args.iter().skip(4).enumerate() {
let address = STACK_TOP + 32 + 8 * slot as u64;
self.memory.write_u64(address, *value).unwrap();
}
use Register::{R12, R13, R14, R15, Rbp, Rbx, Rdi, Rsi};
let nonvolatile = [Rbx, Rbp, Rdi, Rsi, R12, R13, R14, R15];
for (index, register) in nonvolatile.into_iter().enumerate() {
cpu.set(register, 0x5EED_0000 + index as u64);
}
let result = self.engine.run(&mut cpu, &mut self.memory, 100_000);
if result.exit_reason == ExitReason::Halt {
// The service returned to the instruction after its CALL.
assert_eq!(cpu.get(Register::Rsp), STACK_TOP, "{symbol}");
for (index, register) in nonvolatile.into_iter().enumerate() {
assert_eq!(cpu.get(register), 0x5EED_0000 + index as u64, "{symbol}");
}
}
(cpu.get(Register::Rax), result.exit_reason)
}
/// Run guest code from `entry` on the calling thread's TEB until it stops.
pub fn execute(&mut self, entry: u64, max_instructions: usize) -> (CpuState, ExitReason) {
let mut cpu = CpuState::new(entry, STACK_TOP);
cpu.gs_base = self.teb;
let result = self
.engine
.run(&mut cpu, &mut self.memory, max_instructions);
(cpu, result.exit_reason)
}
pub fn call(&mut self, symbol: &str, args: &[u64]) -> u64 {
let (rax, exit) = self.run(symbol, args);
assert_eq!(exit, ExitReason::Halt, "{symbol}");
rax
}
pub fn fails(&mut self, symbol: &str, args: &[u64]) -> ExitReason {
let (_, exit) = self.run(symbol, args);
assert_ne!(exit, ExitReason::Halt, "{symbol} should stop the guest");
exit
}
pub fn error(&mut self) -> u64 {
self.call("GetLastError", &[])
}
pub fn u16_at(&self, address: u64) -> u16 {
self.memory.read_u16(address).unwrap()
}
pub fn u32_at(&self, address: u64) -> u32 {
self.memory.read_u32(address).unwrap()
}
pub fn u64_at(&self, address: u64) -> u64 {
self.memory.read_u64(address).unwrap()
}
}
+241
View File
@@ -0,0 +1,241 @@
// 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()],
}
}
}
+12
View File
@@ -102,6 +102,18 @@ 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
+30
View File
@@ -96,3 +96,33 @@ correctness checks. The recorded 1-, 5- and 15-minute load averages were
individual compiler stages and cold/warm timing, tool and capability metadata,
and noise-based variability reporting. See the
[generated report](../../benchmarks/results/apple-m5/run-1795352394/report.md).
## Guest service dispatch
`cargo bench --locked -p xenora-loader --bench service_dispatch` measures
original guest loops that call standard runtime services through a bound
import table under the ARM64 dynamic binary translator. Before timing, each
workload checks its result: the loop count reaches zero, the service returns
its documented value, and `qsort` leaves the array in the order Rust's own sort
produces. The empty loop is reported separately, so readers can subtract the
loop and translation overhead. Each figure is the median per-iteration time of
10 measured batches of 10,000 iterations, after one warm-up batch.
Measured on Apple M2 Pro (12 logical processors), release profile, AC power,
on the working tree after `ed9b93c`. The 1-minute load average was 7.82, so the
machine was not idle and results are indicative only.
| Workload | Before (ns) | After the block `strlen` scan (ns) |
| --- | --- | --- |
| Empty loop | 21.5 | 20.1 |
| `GetLastError` | 181.8 | 188.4 |
| `WaitForSingleObject`, signaled manual-reset event | 281.0 | 284.6 |
| `strlen`, 63 bytes | 1,990.4 | 223.1 |
| `HeapAlloc` + `HeapFree`, 64 bytes | 475.0 | 493.3 |
| `qsort`, 16 ints with a guest comparator | 10,242.0 | 11,396.7 |
The `strlen` change scans 256-unit blocks with one checked read each. It falls
back to per-unit reads only when a block crosses unmapped or unreadable
memory, so the existing exact-fault tests still pass. The other rows differ by up to 11 percent between runs on this loaded
machine; that is run-to-run variation, not a measured change. Raw logs are kept locally under
`artifacts/system-runtime/bench/`. No comparison with native Windows is made.
+6
View File
@@ -46,3 +46,9 @@ 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
+13
View File
@@ -0,0 +1,13 @@
// 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
View File
@@ -5,8 +5,8 @@ cd "$(dirname "$0")/.."
target=${1:-}
case "$target" in
instruction_stream|fixture|reference) ;;
*) printf '%s\n' 'usage: scripts/fuzz.sh <instruction_stream|fixture|reference> [seconds]' >&2; exit 2 ;;
instruction_stream|fixture|reference|runtime_services) ;;
*) printf '%s\n' 'usage: scripts/fuzz.sh <instruction_stream|fixture|reference|runtime_services> [seconds]' >&2; exit 2 ;;
esac
seconds=${2:-600}
case "$seconds" in