mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-27 18:20:28 +00:00
Compare commits
41
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0929d0214b | ||
|
|
66f7127553 | ||
|
|
d8f7f2cb13 | ||
|
|
042c08c855 | ||
|
|
7e4ccd1e97 | ||
|
|
96c772edc5 | ||
|
|
496938aef4 | ||
|
|
9d94c0f40a | ||
|
|
4e18000798 | ||
|
|
8c188b04c9 | ||
|
|
9eb75522f0 | ||
|
|
3f41f7406b | ||
|
|
67023d292b | ||
|
|
324eab08c3 | ||
|
|
9a29bd9c37 | ||
|
|
652c6ae02f | ||
|
|
0529c62226 | ||
|
|
e6fa931264 | ||
|
|
bd46504a97 | ||
|
|
cc4dd092cf | ||
|
|
04ee981103 | ||
|
|
fd0e73bc28 | ||
|
|
35de41bd5f | ||
|
|
6bac25f099 | ||
|
|
685217e61b | ||
|
|
a0d4b7bf5d | ||
|
|
830f93ff14 | ||
|
|
4962f054c8 | ||
|
|
67dfb18166 | ||
|
|
d2491dee07 | ||
|
|
48e1e5c8c1 | ||
|
|
6947fe7ff6 | ||
|
|
b8fbdf35b9 | ||
|
|
47cb26ebdd | ||
|
|
eaeab25590 | ||
|
|
8d19006c32 | ||
|
|
84221ac715 | ||
|
|
673e2a4556 | ||
|
|
b49d50e34e | ||
|
|
e0a6dae554 | ||
|
|
b3a6a57a8e |
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 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.
|
||||
|
||||
|
||||
@@ -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.
|
||||
@@ -25,10 +26,13 @@ remains unsupported.
|
||||
- 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
|
||||
- Non-canonical 64-bit guest data addresses now raise `#GP` instead of a memory fault in both the interpreter and native DBT, including accesses that cross the canonical-address boundary. The synthetic architectural test is enabled again.
|
||||
- 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
|
||||
- The loader now maps an image's PE headers at its image base (#333): the first `SizeOfHeaders` bytes of the file, read-only, in whole 4 KiB pages that are zero past `SizeOfHeaders`. Programs read their own headers this way; the mingw-w64 C runtime does so before `main`, and until now that read faulted. When startup relocates an image it writes the load base into the mapped `ImageBase` field after the relocations, so an entry aimed at that field cannot move it twice; this is Xenora's policy and has not been compared with Windows. A load is refused with the new `PeError::InvalidHeaderSize` when `SizeOfHeaders` is zero, ends before the section table, runs past the file, or its pages would reach into a section, and when the bytes handed to the loader are not the PE32+ headers that were parsed. The page rule refuses images with sub-page section alignment whose first section starts inside the header page, which loaded before. The header pages count toward the 256 MiB mapping budget, which is checked before anything is mapped. `ParsedPe::parse` and the static probe are unchanged. `tests/pe_headers.rs` covers guest reads at the preferred and a relocated base, a relocation aimed at `ImageBase`, the write and execute faults and each refusal with original hand-built images; the image in `pe_mapping_limits.rs` now carries a valid `SizeOfHeaders`. Awaiting independent re-review.
|
||||
- Added 35 known-answer cases for MOV with an immediate operand, opcodes C6 /0 and C7 /0 (#194), to `cpu_known_answers.rs`: byte, word, dword and qword stores through base, SIB, R12, R13, RSP and RBP addressing with 8-bit and 32-bit displacements; the imm32 sign extension of the 64-bit form; the register forms, including AH and a REX-selected SIL; unmapped and read-only store faults at each width; and #UD for reg field 1. Expected values come from the Intel SDM and were worked out by hand. The interpreter and the DBT already agreed with all of them, so this is new coverage and fixes no defect. The 16-bit forms covered are those that already run, and #118 stays open. Not compared with x86 hardware; awaiting independent review.
|
||||
- `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).
|
||||
@@ -43,6 +47,7 @@ remains unsupported.
|
||||
- Added MOVNTI, the SSE2 non-temporal store of a 32- or 64-bit general register to memory (part of #125). Both engines used to stop on it with an illegal-instruction exit. It is an ordinary store, as the other non-temporal stores already are; the register form and the 66 prefix stay rejected, and a destination that cannot be written faults without changing state. The SDM-derived case `movdqa_movaps_aligned_store_and_load` in `cpu_known_answers.rs`, which ends in a MOVNTI, moved from refused to verified, and `tests/x86/integer.txt` gains four assembled instructions checked by the text-only reference in `x86_integer.rs`. MASKMOVDQU stays rejected and SSE2 stays unreported by CPUID. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added MFENCE, LFENCE and SFENCE and documented the ordering of guest memory accesses (part of #199). Both engines used to stop on a fence with an illegal-instruction exit. Each engine runs one guest instruction at a time on one host thread and completes its loads and stores before the next, so accesses are already totally ordered and the fences change nothing; `docs/cpu/instruction-registry.md` states this and that it holds only while guest threads do not run on several host threads. Five single-thread cases in `cpu_known_answers.rs` and three assembled fixtures cover them, and the memory forms that share the opcode stay rejected. SSE2 is still not reported by CPUID because other SSE2 instructions are rejected; the refused SSE2 instruction that `cpu_features.rs` holds is now MASKMOVDQU. No multi-thread behaviour is established, and nothing was compared with x86 hardware; awaiting independent review.
|
||||
- Added the accumulator short form of XCHG, opcodes 91 to 97 and 90 with REX.B, at 16, 32 and 64 bits (part of #118). Assemblers choose this form whenever one operand is the accumulator, and both engines used to stop on it with an illegal-instruction exit. A 16-bit exchange keeps the upper 48 bits of both registers, a 32-bit one clears both upper halves, and `49 90` exchanges RAX with R8 while plain `90` stays NOP. Both engines run the shared semantics; nothing is lowered to ARM64. Three SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and `tests/x86/integer.txt` gains 20 assembled instructions checked by the text-only reference in `x86_integer.rs`. F3 before this form, 16-bit PUSH and POP and LODSW stay rejected. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added SHLD and SHRD, the double-precision shifts (`0F A4`/`0F A5` and `0F AC`/`0F AD`), for 16-, 32- and 64-bit register and memory destinations with the count in an 8-bit immediate or in CL (part of #121). The count is masked to five bits (six for 64-bit operands); a masked count of zero changes nothing, the vacated bits are filled from the source register, CF receives the last bit shifted out of the destination, ZF, SF and PF follow the result, OF is set only for a count of one (a sign change) and AF is undefined. A 16-bit count above 16 leaves the result and flags undefined in the Intel SDM; Xenora keeps every flag and writes the bits of the 32-bit concatenation, and no test relies on that. The registry gained the operand encodings `rm_reg_imm` and `rm_reg_cl`. Both engines run the shared semantics; nothing is lowered to ARM64. Eight SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and `tests/x86/integer.txt` gains 72 assembled SHLD and SHRD instructions, checked by a bit-at-a-time reference in `x86_integer.rs` and by the faulting read-modify-write test. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added RCL and RCR, the rotates through the carry flag, for 8-, 16-, 32- and 64-bit register and memory operands with a count of one, CL or an immediate (part of #121). The count is masked to five bits (six for 64-bit operands) and then reduced modulo 9 or 17 for 8- and 16-bit operands; a masked count of zero changes nothing, CF receives the last bit rotated out, and OF is set only for a count of one. Both engines run the shared semantics; nothing is lowered to ARM64. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and its shift sweep now runs both instructions at every width, count and carry against its bit-loop model. `tests/x86/integer.txt` gains 80 assembled RCL and RCR instructions, checked by the single-step reference in `x86_integer.rs`. SHLD and SHRD stay rejected. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added four Wave32 gfx1030 VOP2 select and carry forms through the semantic registry. Conditional select, add with carry and both subtract orders with borrow use a per-lane VCC bit and have a guide-derived oracle that passes on both CPU interpreters and on native Metal (local Apple M5, API and shader validation); independent acceptance is pending. Part of #215.
|
||||
- Added decoding and Metal shader translation for twelve Wave32 VOPC 16-bit integer compares (#215). The signed and unsigned forms compare the low 16 bits of each source and write the Wave32 VCC mask. CPU verification covers 1,572 compiler acceptance cases and 408 rejections from the guide-derived oracle, which also passes on native Metal (1,572 cases in 1,420 programs on a local Apple M5 under API and shader validation); acceptance is pending.
|
||||
@@ -80,6 +85,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.
|
||||
@@ -88,6 +99,8 @@ remains unsupported.
|
||||
|
||||
- Added guest module lookup and named symbol resolution for built-in Kernel32 and UCRT services.
|
||||
|
||||
- Added process exit and the first Gate A milestone, A1 (#329). `kernel32.dll!ExitProcess` stops the guest with the new `ExitReason::ProcessExit(status)`, carrying all 32 bits of the status, and never ends the host; a returning entry point does the same with EAX. The exit closes every guest handle, including Winsock sockets and task-queue handles, and the engine that ran the guest executes nothing further. A TLS callback that exits ends startup with that exit as its outcome, and the remaining callbacks and the entry point do not run. Startup reserves the page holding the return addresses the engine intercepts, so an image mapped over them is refused. `atexit` functions are not run. A1 is an original C program with no C library linked (`tests/compat_fixtures/gate_a1.c`): `crates/loader/tests/gate_a1.rs` builds it from source with clang and an LLD on every run, executes it through the loader, the standard services and the DBT at `-O0`, `-O1`, `-O2` and `-Os`, and checks its exit status, its report, its files and its memory against values recomputed in Rust. `docs/testing/gate-a.md` records what A1 shows and that Gate A stays open until the hosted milestone, A2, passes. Verified locally with two compilers; awaiting independent review.
|
||||
|
||||
- Added same-process guest file handle duplication with a shared file position.
|
||||
|
||||
- Added guest file and directory enumeration with typed search handles.
|
||||
|
||||
@@ -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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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};
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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` —"));
|
||||
}
|
||||
@@ -25,3 +25,7 @@ xenora-shader = { path = "../shader" }
|
||||
[[bench]]
|
||||
name = "dbt_bench"
|
||||
harness = false
|
||||
|
||||
[[bench]]
|
||||
name = "service_dispatch"
|
||||
harness = false
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,8 @@ ENCS = {
|
||||
"rm_imm": ("RmImm", True, {"ib", "iz"}),
|
||||
"rm_one": ("RmOne", True, {""}),
|
||||
"rm_cl": ("RmCl", True, {""}),
|
||||
"rm_reg_imm": ("RmRegImm", True, {"ub"}),
|
||||
"rm_reg_cl": ("RmRegCl", True, {""}),
|
||||
"acc_imm": ("AccImm", False, {"ib", "iz"}),
|
||||
"op_reg": ("OpReg", False, {""}),
|
||||
"op_reg_imm": ("OpRegImm", False, {"ib", "iv"}),
|
||||
@@ -66,7 +68,7 @@ ENCS = {
|
||||
"reg_xmm_imm": ("RegXmmImm", True, {"ub"}),
|
||||
}
|
||||
# Encodings whose ModRM operand is the destination, so LOCK can apply to it.
|
||||
RM_DESTINATIONS = {"rm_reg", "rm", "rm_imm", "rm_one", "rm_cl"}
|
||||
RM_DESTINATIONS = {"rm_reg", "rm", "rm_imm", "rm_one", "rm_cl", "rm_reg_imm", "rm_reg_cl"}
|
||||
# Encodings whose ModRM operand is an XMM register or memory of the source width.
|
||||
XMM_RM = {"xmm_rm", "rm_xmm", "xmm_rm_imm", "rm_imm_xmm", "reg_xmm", "reg_xmm_imm"}
|
||||
# One-byte opcodes that are prefixes or the two-byte escape, never instructions.
|
||||
|
||||
@@ -167,12 +167,15 @@ pub enum ExitReason {
|
||||
StackUnderflow,
|
||||
/// Division by zero or a quotient too large for its destination (#DE).
|
||||
DivideError,
|
||||
/// A misaligned 16-byte operand or a reserved MXCSR bit (#GP).
|
||||
/// A non-canonical data address, misaligned 16-byte operand or reserved MXCSR bit (#GP).
|
||||
GeneralProtection,
|
||||
/// An unmasked SSE floating-point exception (#XM); MXCSR holds its flags.
|
||||
SimdException,
|
||||
/// A host service changed a register the Win64 ABI requires it to preserve.
|
||||
ServiceAbiViolation,
|
||||
/// The guest ended its own process with this exit status. Only the guest
|
||||
/// stops; the host keeps running.
|
||||
ProcessExit(u32),
|
||||
/// A service has to wait; it had no effect and runs again later.
|
||||
GuestBlocked,
|
||||
/// A service completed and asked the scheduler for a turn.
|
||||
@@ -194,6 +197,7 @@ impl fmt::Display for ExitReason {
|
||||
Self::DivideError => write!(f, "guest divide error"),
|
||||
Self::GeneralProtection => write!(f, "guest general-protection fault"),
|
||||
Self::SimdException => write!(f, "guest SIMD floating-point exception"),
|
||||
Self::ProcessExit(status) => write!(f, "guest process exited with status {status}"),
|
||||
Self::ServiceAbiViolation => {
|
||||
write!(f, "host service changed a nonvolatile guest register")
|
||||
}
|
||||
|
||||
@@ -48,6 +48,8 @@ pub struct DbtEngine {
|
||||
services: HashMap<u64, HostServiceFn>,
|
||||
pub import_registry: Option<crate::imports::ImportRegistry>,
|
||||
pub metrics: DbtMetrics,
|
||||
/// Exit status of a guest that ended its process on this engine.
|
||||
exited: Option<u32>,
|
||||
}
|
||||
|
||||
impl DbtEngine {
|
||||
@@ -62,6 +64,7 @@ impl DbtEngine {
|
||||
services: HashMap::new(),
|
||||
import_registry: None,
|
||||
metrics: DbtMetrics::default(),
|
||||
exited: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -79,6 +82,9 @@ impl DbtEngine {
|
||||
}
|
||||
|
||||
/// Execute guest code starting at CPU RIP until HLT, budget exhaustion, or fault.
|
||||
///
|
||||
/// Once the guest has ended its process, this engine executes nothing
|
||||
/// further: every later call reports the same exit.
|
||||
pub fn run(
|
||||
&mut self,
|
||||
cpu: &mut CpuState,
|
||||
@@ -101,12 +107,36 @@ impl DbtEngine {
|
||||
self.run_bounded(cpu, memory, max_instructions, false)
|
||||
}
|
||||
|
||||
/// Both entry points go through the process-exit latch: once the guest
|
||||
/// process has exited, no guest instruction runs again, whichever guest
|
||||
/// thread the caller tries to run.
|
||||
fn run_bounded(
|
||||
&mut self,
|
||||
cpu: &mut CpuState,
|
||||
memory: &mut GuestMemory,
|
||||
max_instructions: usize,
|
||||
exact: bool,
|
||||
) -> ExecutionResult {
|
||||
if let Some(status) = self.exited {
|
||||
return ExecutionResult {
|
||||
instructions_executed: 0,
|
||||
final_state: cpu.clone(),
|
||||
exit_reason: ExitReason::ProcessExit(status),
|
||||
};
|
||||
}
|
||||
let result = self.execute(cpu, memory, max_instructions, exact);
|
||||
if let ExitReason::ProcessExit(status) = result.exit_reason {
|
||||
self.exited = Some(status);
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn execute(
|
||||
&mut self,
|
||||
cpu: &mut CpuState,
|
||||
memory: &mut GuestMemory,
|
||||
max_instructions: usize,
|
||||
exact: bool,
|
||||
) -> ExecutionResult {
|
||||
let mut instructions_count = 0;
|
||||
|
||||
@@ -1261,11 +1291,22 @@ struct BlockContext {
|
||||
const BLOCK_CTX_FAULTED_OFFSET: u32 = 8;
|
||||
const _: () = assert!(std::mem::offset_of!(BlockContext, faulted) == 8);
|
||||
|
||||
fn check_guest_address(ctx: *mut BlockContext, address: u64, size: u8) -> bool {
|
||||
if x86_exec::canonical_access(address, size) {
|
||||
return true;
|
||||
}
|
||||
fault(ctx, ExitReason::GeneralProtection);
|
||||
false
|
||||
}
|
||||
|
||||
extern "C" fn write_u64_helper(ctx: *mut BlockContext, addr: u64, val: u64) {
|
||||
unsafe {
|
||||
if (*ctx).exit_reason.is_some() {
|
||||
return;
|
||||
}
|
||||
if !check_guest_address(ctx, addr, 8) {
|
||||
return;
|
||||
}
|
||||
let mem = &mut *(*ctx).memory_ptr;
|
||||
if let Err(e) = mem.write_u64(addr, val) {
|
||||
(*ctx).faulted = 1;
|
||||
@@ -1279,6 +1320,9 @@ extern "C" fn read_u64_helper(ctx: *mut BlockContext, addr: u64) -> u64 {
|
||||
if (*ctx).exit_reason.is_some() {
|
||||
return 0;
|
||||
}
|
||||
if !check_guest_address(ctx, addr, 8) {
|
||||
return 0;
|
||||
}
|
||||
let mem = &*(*ctx).memory_ptr;
|
||||
match mem.read_u64(addr) {
|
||||
Ok(v) => v,
|
||||
@@ -1322,6 +1366,9 @@ fn fault(ctx: *mut BlockContext, reason: ExitReason) {
|
||||
|
||||
/// Read 16 bytes at any alignment; returned in X0 (low) and X1 (high).
|
||||
extern "C" fn read_u128_helper(ctx: *mut BlockContext, addr: u64) -> u128 {
|
||||
if !check_guest_address(ctx, addr, 16) {
|
||||
return 0;
|
||||
}
|
||||
let memory = unsafe { &*(*ctx).memory_ptr };
|
||||
let mut bytes = [0; 16];
|
||||
if let Err(error) = memory.read_bytes(addr, &mut bytes) {
|
||||
@@ -1340,6 +1387,9 @@ extern "C" fn read_aligned_u128_helper(ctx: *mut BlockContext, addr: u64) -> u12
|
||||
|
||||
/// Write 16 bytes at any alignment; `value` arrives in X2 (low) and X3 (high).
|
||||
extern "C" fn write_u128_helper(ctx: *mut BlockContext, addr: u64, value: u128) {
|
||||
if !check_guest_address(ctx, addr, 16) {
|
||||
return;
|
||||
}
|
||||
let memory = unsafe { &mut *(*ctx).memory_ptr };
|
||||
if let Err(error) = memory.write_bytes(addr, &value.to_le_bytes()) {
|
||||
fault(ctx, ExitReason::MemoryFault(error));
|
||||
@@ -1387,6 +1437,9 @@ extern "C" fn write_u16_helper(ctx: *mut BlockContext, addr: u64, val: u64) {
|
||||
if (*ctx).exit_reason.is_some() {
|
||||
return;
|
||||
}
|
||||
if !check_guest_address(ctx, addr, 2) {
|
||||
return;
|
||||
}
|
||||
let mem = &mut *(*ctx).memory_ptr;
|
||||
if let Err(e) = mem.write_u16(addr, val as u16) {
|
||||
(*ctx).faulted = 1;
|
||||
@@ -1400,6 +1453,9 @@ extern "C" fn write_u32_helper(ctx: *mut BlockContext, addr: u64, val: u64) {
|
||||
if (*ctx).exit_reason.is_some() {
|
||||
return;
|
||||
}
|
||||
if !check_guest_address(ctx, addr, 4) {
|
||||
return;
|
||||
}
|
||||
let mem = &mut *(*ctx).memory_ptr;
|
||||
if let Err(e) = mem.write_u32(addr, val as u32) {
|
||||
(*ctx).faulted = 1;
|
||||
@@ -1413,6 +1469,9 @@ extern "C" fn read_u32_helper(ctx: *mut BlockContext, addr: u64) -> u64 {
|
||||
if (*ctx).exit_reason.is_some() {
|
||||
return 0;
|
||||
}
|
||||
if !check_guest_address(ctx, addr, 4) {
|
||||
return 0;
|
||||
}
|
||||
let mem = &*(*ctx).memory_ptr;
|
||||
match mem.read_u32(addr) {
|
||||
Ok(v) => u64::from(v),
|
||||
@@ -1430,6 +1489,9 @@ extern "C" fn write_u8_helper(ctx: *mut BlockContext, addr: u64, val: u64) {
|
||||
if (*ctx).exit_reason.is_some() {
|
||||
return;
|
||||
}
|
||||
if !check_guest_address(ctx, addr, 1) {
|
||||
return;
|
||||
}
|
||||
let mem = &mut *(*ctx).memory_ptr;
|
||||
if let Err(e) = mem.write_u8(addr, val as u8) {
|
||||
(*ctx).faulted = 1;
|
||||
@@ -1443,6 +1505,9 @@ extern "C" fn read_u8_helper(ctx: *mut BlockContext, addr: u64) -> u64 {
|
||||
if (*ctx).exit_reason.is_some() {
|
||||
return 0;
|
||||
}
|
||||
if !check_guest_address(ctx, addr, 1) {
|
||||
return 0;
|
||||
}
|
||||
let mem = &*(*ctx).memory_ptr;
|
||||
match mem.read_u8(addr) {
|
||||
Ok(v) => v as u64,
|
||||
@@ -1460,6 +1525,9 @@ extern "C" fn read_u16_helper(ctx: *mut BlockContext, addr: u64) -> u64 {
|
||||
if (*ctx).exit_reason.is_some() {
|
||||
return 0;
|
||||
}
|
||||
if !check_guest_address(ctx, addr, 2) {
|
||||
return 0;
|
||||
}
|
||||
let mem = &*(*ctx).memory_ptr;
|
||||
match mem.read_u16(addr) {
|
||||
Ok(v) => v as u64,
|
||||
|
||||
@@ -196,6 +196,15 @@ fn trampoline_address(index: usize) -> u64 {
|
||||
}
|
||||
|
||||
const CALLBACK_RETURN: u64 = IMPORT_TRAMPOLINE_BASE_VA - IMPORT_TRAMPOLINE_STRIDE;
|
||||
/// Return address placed under a process entry point. Reaching it ends the
|
||||
/// process with EAX as its exit status.
|
||||
pub const ENTRY_RETURN: u64 = CALLBACK_RETURN - IMPORT_TRAMPOLINE_STRIDE;
|
||||
/// The 4 KiB page that holds [`ENTRY_RETURN`] and the callback return
|
||||
/// address. The engine intercepts those two addresses before it executes
|
||||
/// anything there, so startup reserves the page: guest code mapped over it
|
||||
/// would never run.
|
||||
pub const RETURN_SENTINEL_PAGE: u64 = ENTRY_RETURN & !0xFFF;
|
||||
const _: () = assert!(CALLBACK_RETURN & !0xFFF == RETURN_SENTINEL_PAGE);
|
||||
/// Nested guest callbacks allowed in one guest thread.
|
||||
const MAX_CALLBACK_DEPTH: usize = 32;
|
||||
|
||||
@@ -646,6 +655,7 @@ impl ImportRegistry {
|
||||
/// Check if target RIP matches a synthetic service trampoline.
|
||||
pub fn is_service_trampoline(&self, rip: u64) -> bool {
|
||||
rip == CALLBACK_RETURN
|
||||
|| rip == ENTRY_RETURN
|
||||
|| self.trampoline_to_service.contains_key(&rip)
|
||||
|| self.dynamic_trampolines.get(rip).is_some()
|
||||
}
|
||||
@@ -657,6 +667,22 @@ impl ImportRegistry {
|
||||
cpu: &mut CpuState,
|
||||
memory: &mut GuestMemory,
|
||||
) -> Result<(), ExitReason> {
|
||||
if rip == ENTRY_RETURN {
|
||||
// The entry point returned. Its result is the exit status, and it
|
||||
// goes through ExitProcess when that is registered so both ways of
|
||||
// ending do the same cleanup.
|
||||
let status = cpu.get(Register::Rax) as u32;
|
||||
let exit = ExitReason::ProcessExit(status);
|
||||
let Some(index) = self.index("kernel32.dll", &ImportName::Name("ExitProcess".into()))
|
||||
else {
|
||||
return Err(exit);
|
||||
};
|
||||
let mut args = Win64Args::new(cpu);
|
||||
args.rcx = u64::from(status);
|
||||
return Err((self.handlers[index].handler)(&args, cpu, memory)
|
||||
.err()
|
||||
.unwrap_or(exit));
|
||||
}
|
||||
if rip == CALLBACK_RETURN {
|
||||
let key = (cpu.gs_base, cpu.get(Register::Rsp));
|
||||
let frame = memory
|
||||
|
||||
+95
-8
@@ -3,7 +3,8 @@
|
||||
//! PE32+ (64-bit Portable Executable) format parser and section loader for Xenora.
|
||||
//!
|
||||
//! Parses standard PE32+ headers (DOS header, COFF header, Optional Header 64)
|
||||
//! and loads valid section headers into `GuestMemory` with appropriate permissions.
|
||||
//! and loads the headers and each section into `GuestMemory` with appropriate
|
||||
//! permissions.
|
||||
|
||||
use crate::memory::{GuestMemory, MemoryError, MemoryPermissions};
|
||||
use std::fmt;
|
||||
@@ -19,6 +20,11 @@ pub enum PeError {
|
||||
InvalidSectionHeaders,
|
||||
SectionMappingError(MemoryError),
|
||||
InvalidEntryPoint,
|
||||
/// The headers cannot be mapped at the image base: `SizeOfHeaders` is
|
||||
/// zero, ends before the section table does, runs past the end of the
|
||||
/// file, or its pages reach into a section; or the bytes given to the
|
||||
/// loader do not hold the PE32+ headers that were parsed.
|
||||
InvalidHeaderSize,
|
||||
}
|
||||
|
||||
impl fmt::Display for PeError {
|
||||
@@ -42,6 +48,12 @@ impl fmt::Display for PeError {
|
||||
Self::InvalidSectionHeaders => write!(f, "invalid or corrupt section headers"),
|
||||
Self::SectionMappingError(e) => write!(f, "failed to map section: {e}"),
|
||||
Self::InvalidEntryPoint => write!(f, "entry point address is outside executable code"),
|
||||
Self::InvalidHeaderSize => write!(
|
||||
f,
|
||||
"the PE headers cannot be mapped: SizeOfHeaders is zero, shorter than the section \
|
||||
table, longer than the file or reaches into a section, or the bytes do not match \
|
||||
the parsed headers"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -80,6 +92,9 @@ pub struct LoadedImage {
|
||||
pub pe: ParsedPe,
|
||||
pub memory: GuestMemory,
|
||||
pub entry_point: u64,
|
||||
/// Guest address of the `ImageBase` field in the mapped optional header.
|
||||
/// Startup writes the load base there once relocations have been applied.
|
||||
pub(crate) image_base_field: u64,
|
||||
}
|
||||
|
||||
// Windows PE Characteristic Constants
|
||||
@@ -94,9 +109,14 @@ pub const PE32_PLUS_MAGIC: u16 = 0x020B;
|
||||
/// PE32+ optional header length up to and including NumberOfRvaAndSizes.
|
||||
const PE32_PLUS_MIN_OPTIONAL_HEADER: usize = 112;
|
||||
const SECTION_HEADER_SIZE: usize = 40;
|
||||
/// Host memory budget for all mapped sections of one image. This is a loader policy
|
||||
/// limit, not a property of the PE format.
|
||||
/// Host memory budget for the mapped headers and sections of one image. This is a
|
||||
/// loader policy limit, not a property of the PE format.
|
||||
const MAX_MAPPED_IMAGE_BYTES: u64 = 256 * 1024 * 1024;
|
||||
/// The mapped headers end on a guest page boundary.
|
||||
const HEADER_PAGE: u64 = 0x1000;
|
||||
/// `ImageBase` and `SizeOfHeaders` within the PE32+ optional header.
|
||||
const OPTIONAL_IMAGE_BASE: usize = 24;
|
||||
const OPTIONAL_SIZE_OF_HEADERS: usize = 60;
|
||||
|
||||
fn read_u16(bytes: &[u8], at: usize) -> u16 {
|
||||
u16::from_le_bytes([bytes[at], bytes[at + 1]])
|
||||
@@ -270,25 +290,91 @@ impl ParsedPe {
|
||||
None
|
||||
}
|
||||
|
||||
/// Load this parsed PE into a fresh `GuestMemory` instance, mapping all sections.
|
||||
/// Where the headers are and how much to map for them: the file length of
|
||||
/// the headers, the page-rounded length of the mapping, and the file offset
|
||||
/// of the optional header's `ImageBase` field. Nothing is copied or
|
||||
/// allocated here.
|
||||
///
|
||||
/// A caller may pass bytes other than the ones parsed, so the header
|
||||
/// layout is read again from `bytes` with every access checked, and must
|
||||
/// be a PE32+ optional header that agrees with the parsed metadata.
|
||||
fn headers_for(&self, bytes: &[u8]) -> Result<(usize, u64, usize), PeError> {
|
||||
let field = |at: usize, len: usize| at.checked_add(len).and_then(|end| bytes.get(at..end));
|
||||
let u16_at = |at: usize| Some(u16::from_le_bytes(field(at, 2)?.try_into().ok()?));
|
||||
let u32_at = |at: usize| Some(u32::from_le_bytes(field(at, 4)?.try_into().ok()?));
|
||||
let layout = || {
|
||||
let coff = (u32_at(0x3C)? as usize).checked_add(4)?;
|
||||
let sections = u16_at(coff.checked_add(2)?)?;
|
||||
let optional_size = usize::from(u16_at(coff.checked_add(16)?)?);
|
||||
let optional = coff.checked_add(20)?;
|
||||
let image_base = optional.checked_add(OPTIONAL_IMAGE_BASE)?;
|
||||
let agrees = u16_at(optional)? == PE32_PLUS_MAGIC
|
||||
&& optional_size >= PE32_PLUS_MIN_OPTIONAL_HEADER
|
||||
&& sections == self.number_of_sections
|
||||
&& u64::from_le_bytes(field(image_base, 8)?.try_into().ok()?) == self.image_base
|
||||
&& u32_at(optional.checked_add(OPTIONAL_SIZE_OF_HEADERS)?)? == self.size_of_headers;
|
||||
let table_end = optional
|
||||
.checked_add(optional_size)?
|
||||
.checked_add(usize::from(sections).checked_mul(SECTION_HEADER_SIZE)?)?;
|
||||
agrees.then_some((image_base, table_end))
|
||||
};
|
||||
let (image_base, table_end) = layout().ok_or(PeError::InvalidHeaderSize)?;
|
||||
|
||||
// A size of zero is shorter than any section table.
|
||||
let len = self.size_of_headers as usize;
|
||||
if len < table_end || len > bytes.len() {
|
||||
return Err(PeError::InvalidHeaderSize);
|
||||
}
|
||||
let mapped = u64::from(self.size_of_headers).next_multiple_of(HEADER_PAGE);
|
||||
let reaches_a_section = self.sections.iter().any(|sec| {
|
||||
sec.virtual_size.max(sec.raw_data_size) > 0 && u64::from(sec.virtual_address) < mapped
|
||||
});
|
||||
if reaches_a_section {
|
||||
return Err(PeError::InvalidHeaderSize);
|
||||
}
|
||||
Ok((len, mapped, image_base))
|
||||
}
|
||||
|
||||
/// Load this parsed PE into a fresh `GuestMemory` instance, mapping the
|
||||
/// headers and all sections.
|
||||
pub fn load_into_memory(&self, bytes: &[u8]) -> Result<LoadedImage, PeError> {
|
||||
self.load_at_base(bytes, self.image_base)
|
||||
}
|
||||
|
||||
pub(crate) fn load_at_base(&self, bytes: &[u8], base: u64) -> Result<LoadedImage, PeError> {
|
||||
// Each section becomes a zero-filled host allocation, so bound the total before
|
||||
// allocating anything. Sections may not overlap, so the sum is the mapped size.
|
||||
let mapped: u64 = self
|
||||
let (headers_len, headers_mapped, image_base_field) = self.headers_for(bytes)?;
|
||||
|
||||
// The headers and each section become zero-filled host allocations, so bound
|
||||
// the total before allocating anything. Sections may not overlap, so the sum
|
||||
// is the mapped size.
|
||||
let mapped = self
|
||||
.sections
|
||||
.iter()
|
||||
.map(|sec| u64::from(sec.virtual_size.max(sec.raw_data_size)))
|
||||
.sum();
|
||||
.sum::<u64>()
|
||||
+ headers_mapped;
|
||||
if mapped > MAX_MAPPED_IMAGE_BYTES {
|
||||
return Err(PeError::SectionMappingError(MemoryError::AllocationFailed));
|
||||
}
|
||||
|
||||
let mut memory = GuestMemory::new();
|
||||
|
||||
// Windows maps the headers read-only at the image base, and programs read
|
||||
// them: a C runtime finds its own sections this way before `main`. The
|
||||
// budget above is checked first, and the file bytes are the initial data
|
||||
// of the mapping, so nothing else is copied.
|
||||
memory
|
||||
.map_region_with_data(
|
||||
base,
|
||||
headers_mapped as usize,
|
||||
MemoryPermissions::READ_ONLY,
|
||||
&bytes[..headers_len],
|
||||
)
|
||||
.map_err(PeError::SectionMappingError)?;
|
||||
let image_base_field = base
|
||||
.checked_add(image_base_field as u64)
|
||||
.ok_or(PeError::InvalidHeaderSize)?;
|
||||
|
||||
for sec in &self.sections {
|
||||
let base_addr = base
|
||||
.checked_add(u64::from(sec.virtual_address))
|
||||
@@ -323,6 +409,7 @@ impl ParsedPe {
|
||||
pe: self.clone(),
|
||||
memory,
|
||||
entry_point,
|
||||
image_base_field,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ mod gdk_queue;
|
||||
mod heap;
|
||||
mod modules;
|
||||
mod platform_fixture;
|
||||
mod process;
|
||||
mod synch;
|
||||
pub mod sysinfo;
|
||||
mod task_fixture;
|
||||
@@ -198,6 +199,8 @@ pub struct ServicesState {
|
||||
pub(crate) hooks: Arc<threads::SchedulerHooks>,
|
||||
/// Functions registered with `atexit`, run in reverse order by `_cexit`.
|
||||
atexit: Mutex<Vec<u64>>,
|
||||
/// The status the guest process exited with. Set once.
|
||||
exit_status: Mutex<Option<u32>>,
|
||||
winsock: Mutex<winsock::Winsock>,
|
||||
task_fixture: Mutex<task_fixture::TaskFixture>,
|
||||
platform_fixture: Mutex<platform_fixture::PlatformFixture>,
|
||||
@@ -223,6 +226,7 @@ impl ServicesState {
|
||||
threads: Mutex::default(),
|
||||
hooks: Arc::default(),
|
||||
atexit: Mutex::default(),
|
||||
exit_status: Mutex::default(),
|
||||
winsock: Mutex::default(),
|
||||
task_fixture: Mutex::default(),
|
||||
platform_fixture: Mutex::default(),
|
||||
@@ -246,6 +250,76 @@ impl ServicesState {
|
||||
self.priority_boost_disabled.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// The status the guest process exited with, once it has exited.
|
||||
pub fn exit_status(&self) -> Option<u32> {
|
||||
*self.exit_status.lock().expect("guest exit status")
|
||||
}
|
||||
|
||||
/// How many guest handles are open: kernel objects, sockets and task
|
||||
/// queues, which are kept in three separate tables.
|
||||
pub fn open_handle_count(&self) -> usize {
|
||||
let objects = self
|
||||
.objects
|
||||
.lock()
|
||||
.expect("guest object state")
|
||||
.handles
|
||||
.len();
|
||||
let sockets = self
|
||||
.winsock
|
||||
.lock()
|
||||
.expect("guest Winsock state")
|
||||
.open_count();
|
||||
let queues = self
|
||||
.gdk_queues
|
||||
.lock()
|
||||
.expect("GDK queue handle table")
|
||||
.open_count();
|
||||
objects + sockets + queues
|
||||
}
|
||||
|
||||
/// A file on the synthetic `C:` drive, named as the guest names it.
|
||||
pub fn file_contents(&self, path: &str) -> Option<Vec<u8>> {
|
||||
let path = path.replace('/', "\\").to_ascii_lowercase();
|
||||
let name = path.strip_prefix("c:\\").unwrap_or(&path);
|
||||
self.objects
|
||||
.lock()
|
||||
.expect("guest object state")
|
||||
.files
|
||||
.get(name)
|
||||
.cloned()
|
||||
}
|
||||
|
||||
/// End the guest process. The first exit decides the status; a later one
|
||||
/// reports it again and changes nothing.
|
||||
///
|
||||
/// Every guest handle is closed: kernel objects, sockets and task queues.
|
||||
/// Files stay on the synthetic drive, guest memory stays mapped for the
|
||||
/// host to inspect, and `atexit` functions are not run.
|
||||
fn exit_process(&self, status: u32) -> u32 {
|
||||
let mut exited = self.exit_status.lock().expect("guest exit status");
|
||||
if let Some(first) = *exited {
|
||||
return first;
|
||||
}
|
||||
*exited = Some(status);
|
||||
// The three table locks are taken one at a time, never nested.
|
||||
self.objects
|
||||
.lock()
|
||||
.expect("guest object state")
|
||||
.handles
|
||||
.clear();
|
||||
self.winsock
|
||||
.lock()
|
||||
.expect("guest Winsock state")
|
||||
.close_all();
|
||||
self.winsock_changed.notify_all();
|
||||
self.gdk_queues
|
||||
.lock()
|
||||
.expect("GDK queue handle table")
|
||||
.close_all();
|
||||
self.gdk_queue_changed.notify_all();
|
||||
status
|
||||
}
|
||||
|
||||
/// Read the last-error value for a guest thread's TEB.
|
||||
pub fn last_error(&self, teb: u64) -> u32 {
|
||||
self.last_errors
|
||||
@@ -463,20 +537,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);
|
||||
@@ -626,6 +704,7 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc<Serv
|
||||
platform_fixture::register(registry, &state);
|
||||
gdk_queue::register(registry, &state);
|
||||
modules::register(registry, &state);
|
||||
process::register(registry, &state);
|
||||
}
|
||||
|
||||
/// Implementations behind the generated adapters. A failure the guest can
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -41,6 +41,18 @@ struct ScheduledCallback {
|
||||
}
|
||||
|
||||
impl QueueHandles {
|
||||
/// Task-queue handles the guest has open.
|
||||
pub(super) fn open_count(&self) -> usize {
|
||||
self.queues.len()
|
||||
}
|
||||
|
||||
/// Process exit: every handle is closed and nothing stays scheduled.
|
||||
pub(super) fn close_all(&mut self) {
|
||||
self.queues.clear();
|
||||
self.terminated.clear();
|
||||
self.pending.clear();
|
||||
}
|
||||
|
||||
fn open(
|
||||
&mut self,
|
||||
duplicate: Option<Queue>,
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Process termination.
|
||||
|
||||
use super::{KERNEL32, ServicesState};
|
||||
use crate::cpu::ExitReason;
|
||||
use crate::imports::{ImportRegistry, ServiceStatus};
|
||||
use std::sync::Arc;
|
||||
|
||||
const PROCESS_THREADS_API: &str = "api-ms-win-core-processthreads-l1-1-0.dll";
|
||||
|
||||
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
// ExitProcess does not return (processthreadsapi.h). It stops the guest
|
||||
// with its status and never ends the host. It is partial: there are no
|
||||
// other threads or loaded DLLs to notify.
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "ExitProcess", move |args, _, _| {
|
||||
// The status is a UINT, the low half of the first argument.
|
||||
Err(ExitReason::ProcessExit(s.exit_process(args.rcx as u32)))
|
||||
});
|
||||
registry.alias(PROCESS_THREADS_API, KERNEL32, "ExitProcess");
|
||||
registry.set_status(KERNEL32, "ExitProcess", ServiceStatus::Partial);
|
||||
}
|
||||
@@ -54,6 +54,16 @@ struct Socket {
|
||||
}
|
||||
|
||||
impl Winsock {
|
||||
/// Sockets the guest has open.
|
||||
pub(super) fn open_count(&self) -> usize {
|
||||
self.sockets.len()
|
||||
}
|
||||
|
||||
/// Process exit: every socket is closed.
|
||||
pub(super) fn close_all(&mut self) {
|
||||
self.sockets.clear();
|
||||
}
|
||||
|
||||
fn socket(&self, handle: u64) -> Result<&Socket, u32> {
|
||||
if self.refs == 0 {
|
||||
return Err(WSANOTINITIALISED);
|
||||
|
||||
@@ -3,14 +3,16 @@
|
||||
//! Process startup for trusted, original PE32+ fixtures.
|
||||
|
||||
use crate::dbt::DbtMetrics;
|
||||
use crate::tls::TlsError;
|
||||
use crate::{
|
||||
CpuState, DbtEngine, ExecutionResult, ImportRegistry, LoadedImage, MemoryError,
|
||||
CpuState, DbtEngine, ExecutionResult, ExitReason, ImportRegistry, LoadedImage, MemoryError,
|
||||
MemoryPermissions, ParsedPe, PeError, RelocationReport, apply_relocations,
|
||||
execute_tls_callbacks, parse_tls_directory, setup_tls,
|
||||
};
|
||||
|
||||
const STACK_SIZE: usize = 64 * 1024;
|
||||
const JIT_CAPACITY: usize = 1024 * 1024;
|
||||
const RETURN_SENTINEL_PAGE_SIZE: usize = 0x1000;
|
||||
/// The TEB is placed this far above the TLS base and spans two 4 KiB pages.
|
||||
const TEB_OFFSET: u64 = 0x10000;
|
||||
const TEB_SIZE: usize = 0x2000;
|
||||
@@ -95,6 +97,7 @@ pub fn run_synthetic_startup_with_observer(
|
||||
entry_rva: pe.entry_point_rva,
|
||||
});
|
||||
let mut image = pe.load_at_base(bytes, layout.image_base)?;
|
||||
let image_base_field = image.image_base_field;
|
||||
let memory = &mut image.memory;
|
||||
memory
|
||||
.fetch_instruction_byte(image.entry_point)
|
||||
@@ -104,6 +107,12 @@ pub fn run_synthetic_startup_with_observer(
|
||||
});
|
||||
|
||||
let relocations = apply_relocations(&pe, bytes, layout.image_base, memory)?;
|
||||
// The mapped optional header names the base the image is loaded at. This
|
||||
// is written after the relocations so that an entry aimed at the field
|
||||
// itself cannot leave it holding anything else.
|
||||
memory
|
||||
.write_u64_bypass(image_base_field, layout.image_base)
|
||||
.map_err(PeError::SectionMappingError)?;
|
||||
observe(StartupEvent::Relocated {
|
||||
applied_dir64: relocations.applied_dir64,
|
||||
});
|
||||
@@ -123,6 +132,14 @@ pub fn run_synthetic_startup_with_observer(
|
||||
}
|
||||
|
||||
memory.map_region(stack_base, STACK_SIZE, MemoryPermissions::READ_WRITE)?;
|
||||
// Keep guest code and data out of the page that holds the return
|
||||
// addresses the engine intercepts. An image or layout that already covers
|
||||
// it is refused here, and a later guest allocation there fails.
|
||||
memory.map_region(
|
||||
crate::imports::RETURN_SENTINEL_PAGE,
|
||||
RETURN_SENTINEL_PAGE_SIZE,
|
||||
MemoryPermissions::NO_ACCESS,
|
||||
)?;
|
||||
|
||||
map_teb(memory, teb_base, &layout, stack_base)?;
|
||||
|
||||
@@ -132,28 +149,59 @@ pub fn run_synthetic_startup_with_observer(
|
||||
let mut tls_cpu = CpuState::new(image.entry_point, layout.stack_top);
|
||||
tls_cpu.gs_base = teb_base;
|
||||
let mut tls_callbacks = 0;
|
||||
let mut exited_in_tls = None;
|
||||
if let Some(tls) = &tls {
|
||||
tls_callbacks = execute_tls_callbacks(
|
||||
&tls.callbacks,
|
||||
layout.image_base,
|
||||
pe.image_base,
|
||||
layout.stack_top,
|
||||
&mut tls_cpu,
|
||||
memory,
|
||||
&mut engine,
|
||||
)?;
|
||||
// One callback at a time, so that a callback which ends the process
|
||||
// is seen as an exit and not as a fault, and the callbacks that
|
||||
// finished before it are counted.
|
||||
for callback in &tls.callbacks {
|
||||
match execute_tls_callbacks(
|
||||
std::slice::from_ref(callback),
|
||||
layout.image_base,
|
||||
pe.image_base,
|
||||
layout.stack_top,
|
||||
&mut tls_cpu,
|
||||
memory,
|
||||
&mut engine,
|
||||
) {
|
||||
Ok(_) => tls_callbacks += 1,
|
||||
Err(TlsError::CallbackExecutionFault(ExitReason::ProcessExit(status))) => {
|
||||
exited_in_tls = Some(status);
|
||||
break;
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
observe(StartupEvent::TlsCompleted {
|
||||
callbacks: tls_callbacks,
|
||||
native_steps: engine.metrics.instructions_executed,
|
||||
});
|
||||
if let Some(status) = exited_in_tls {
|
||||
// The process ended before its entry point: the remaining callbacks
|
||||
// and the entry point do not run, and this is an ordinary outcome.
|
||||
return Ok(StartupResult {
|
||||
image,
|
||||
relocations,
|
||||
bound_imports,
|
||||
tls_callbacks,
|
||||
execution: ExecutionResult {
|
||||
instructions_executed: 0,
|
||||
final_state: tls_cpu,
|
||||
exit_reason: ExitReason::ProcessExit(status),
|
||||
},
|
||||
dbt_metrics: engine.metrics,
|
||||
});
|
||||
}
|
||||
observe(StartupEvent::Entering {
|
||||
step_limit: entry_budget,
|
||||
});
|
||||
|
||||
// Model function entry with the Win64 32-byte home area and return slot.
|
||||
// The synthetic entry point terminates with HLT.
|
||||
// An entry point may end with HLT, call ExitProcess, or return: the
|
||||
// return slot holds the address that ends the process with EAX.
|
||||
memory.write_u64_bypass(layout.stack_top - 40, crate::imports::ENTRY_RETURN)?;
|
||||
let mut entry_cpu = CpuState::new(image.entry_point, layout.stack_top - 40);
|
||||
entry_cpu.gs_base = teb_base;
|
||||
let execution = engine.run(&mut entry_cpu, memory, entry_budget);
|
||||
|
||||
@@ -76,6 +76,10 @@ pub enum Encoding {
|
||||
RmImm,
|
||||
RmOne,
|
||||
RmCl,
|
||||
/// `rm` from `rm` and `reg`, with an 8-bit count (SHLD, SHRD).
|
||||
RmRegImm,
|
||||
/// `rm` from `rm` and `reg`, with the count in CL (SHLD, SHRD).
|
||||
RmRegCl,
|
||||
AccImm,
|
||||
OpReg,
|
||||
OpRegImm,
|
||||
|
||||
@@ -49,6 +49,26 @@ pub fn address(cpu: &CpuState, operand: &MemOperand) -> u64 {
|
||||
base.wrapping_add(offset(cpu, operand))
|
||||
}
|
||||
|
||||
/// Whether a 64-bit guest address is canonical under the x86-64 48-bit
|
||||
/// virtual-address rule (Intel SDM Vol. 1, section 3.3.7.1).
|
||||
pub(crate) fn is_canonical(address: u64) -> bool {
|
||||
matches!(address >> 47, 0 | 0x1_ffff)
|
||||
}
|
||||
|
||||
/// Whether every byte of a data access has a canonical address. An overflowing
|
||||
/// range is left to [`GuestMemory`] so it keeps its existing overflow fault.
|
||||
pub(crate) fn canonical_access(address: u64, size: u8) -> bool {
|
||||
if !is_canonical(address) {
|
||||
return false;
|
||||
}
|
||||
if size <= 1 {
|
||||
return true;
|
||||
}
|
||||
address
|
||||
.checked_add(u64::from(size) - 1)
|
||||
.is_none_or(is_canonical)
|
||||
}
|
||||
|
||||
/// Effective address without a segment base, as LEA computes it.
|
||||
fn offset(cpu: &CpuState, operand: &MemOperand) -> u64 {
|
||||
let base = operand.base.map_or(0, |index| cpu.gpr[usize::from(index)]);
|
||||
@@ -78,6 +98,9 @@ pub(crate) fn write_reg(cpu: &mut CpuState, reg: RegOperand, size: u8, value: u6
|
||||
}
|
||||
|
||||
pub(crate) fn read_mem(memory: &GuestMemory, address: u64, size: u8) -> Result<u64, ExitReason> {
|
||||
if !canonical_access(address, size) {
|
||||
return Err(ExitReason::GeneralProtection);
|
||||
}
|
||||
match size {
|
||||
1 => memory.read_u8(address).map(u64::from),
|
||||
2 => memory.read_u16(address).map(u64::from),
|
||||
@@ -93,6 +116,9 @@ pub(crate) fn write_mem(
|
||||
size: u8,
|
||||
value: u64,
|
||||
) -> Result<(), ExitReason> {
|
||||
if !canonical_access(address, size) {
|
||||
return Err(ExitReason::GeneralProtection);
|
||||
}
|
||||
match size {
|
||||
1 => memory.write_u8(address, value as u8),
|
||||
2 => memory.write_u16(address, value as u16),
|
||||
@@ -296,6 +322,54 @@ fn shift(op: Op, value: u64, count: u64, size: u8, old: RFlags) -> Option<(u64,
|
||||
Some((result, flags))
|
||||
}
|
||||
|
||||
/// SHLD and SHRD (Intel SDM Vol. 2B, "SHLD" and "SHRD"): `dst` is shifted by
|
||||
/// `count` and the vacated bits are filled from `src`, which is unchanged.
|
||||
/// `None` means a masked count of zero, which changes neither the destination
|
||||
/// nor the flags.
|
||||
///
|
||||
/// A count above the operand size is possible only for 16-bit operands and
|
||||
/// leaves the result and flags undefined. Xenora then returns the bits the
|
||||
/// 32-bit concatenation gives and keeps every flag; no test relies on that.
|
||||
fn double_shift(
|
||||
op: Op,
|
||||
dst: u64,
|
||||
src: u64,
|
||||
count: u64,
|
||||
size: u8,
|
||||
old: RFlags,
|
||||
) -> Option<(u64, RFlags)> {
|
||||
let count = (count & if size == 8 { 0x3F } else { 0x1F }) as u32;
|
||||
if count == 0 {
|
||||
return None;
|
||||
}
|
||||
let bits = 8 * u32::from(size);
|
||||
let (dst, src) = (u128::from(dst), u128::from(src));
|
||||
// SHLD shifts `dst:src` left and keeps the high half; SHRD shifts
|
||||
// `src:dst` right and keeps the low half. CF is the last bit shifted out
|
||||
// of the destination.
|
||||
let (result, cf) = if op == Op::Shld {
|
||||
let pair = dst << bits | src;
|
||||
let shifted = pair << count;
|
||||
(shifted >> bits, pair >> (2 * bits - count) & 1 != 0)
|
||||
} else {
|
||||
let pair = src << bits | dst;
|
||||
(pair >> count, pair >> (count - 1) & 1 != 0)
|
||||
};
|
||||
let result = result as u64 & mask(size);
|
||||
let mut flags = old;
|
||||
if count > bits {
|
||||
return Some((result, flags));
|
||||
}
|
||||
flags.cf = cf;
|
||||
result_flags(&mut flags, result, size);
|
||||
// OF is defined only for a count of one: set when the sign changed.
|
||||
if count == 1 {
|
||||
let top = u128::from(sign_bit(size));
|
||||
flags.of = (u128::from(result) & top != 0) != (dst & top != 0);
|
||||
}
|
||||
Some((result, flags))
|
||||
}
|
||||
|
||||
fn push(cpu: &mut CpuState, memory: &mut GuestMemory, value: u64) -> Result<(), ExitReason> {
|
||||
let sp = cpu.gpr[RSP]
|
||||
.checked_sub(8)
|
||||
@@ -448,6 +522,23 @@ pub fn execute(
|
||||
if negative { mask(size) } else { 0 },
|
||||
);
|
||||
}
|
||||
Op::Shld | Op::Shrd => {
|
||||
let dst = read_rm(cpu, memory, insn)?;
|
||||
let src = read_reg(cpu, insn.reg, size);
|
||||
let count = match insn.encoding {
|
||||
Encoding::RmRegCl => cpu.gpr[RCX] & 0xFF,
|
||||
_ => insn.imm & 0xFF,
|
||||
};
|
||||
match double_shift(insn.op, dst, src, count, size, cpu.flags) {
|
||||
Some((value, flags)) => {
|
||||
write_rm(cpu, memory, insn, value)?;
|
||||
cpu.flags = flags;
|
||||
}
|
||||
// As for the other shifts, a zero count still performs the
|
||||
// write's permission check and the 32-bit zero-extension.
|
||||
None => write_rm(cpu, memory, insn, dst)?,
|
||||
}
|
||||
}
|
||||
Op::Rol | Op::Ror | Op::Rcl | Op::Rcr | Op::Shl | Op::Shr | Op::Sar => {
|
||||
let (a, count) = operands(cpu, memory, insn)?;
|
||||
match shift(insn.op, a, count, size, cpu.flags) {
|
||||
|
||||
@@ -8,7 +8,9 @@
|
||||
use crate::cpu::{CpuState, ExitReason, Mxcsr};
|
||||
use crate::memory::GuestMemory;
|
||||
use crate::x86_decode::{Encoding, Insn, RegOperand, RmOperand};
|
||||
use crate::x86_exec::{address, read_mem, read_reg, rm_operand, write_mem, write_reg};
|
||||
use crate::x86_exec::{
|
||||
address, canonical_access, read_mem, read_reg, rm_operand, write_mem, write_reg,
|
||||
};
|
||||
use crate::x86_float;
|
||||
use crate::x86_table::{FORMS, Op};
|
||||
|
||||
@@ -216,6 +218,9 @@ fn read_vector(memory: &GuestMemory, address: u64, size: u8) -> Result<u128, Exi
|
||||
if size < 16 {
|
||||
return read_mem(memory, address, size).map(u128::from);
|
||||
}
|
||||
if !canonical_access(address, size) {
|
||||
return Err(ExitReason::GeneralProtection);
|
||||
}
|
||||
let mut bytes = [0; 16];
|
||||
memory
|
||||
.read_bytes(address, &mut bytes)
|
||||
@@ -232,6 +237,9 @@ fn write_vector(
|
||||
if size < 16 {
|
||||
return write_mem(memory, address, size, value as u64);
|
||||
}
|
||||
if !canonical_access(address, size) {
|
||||
return Err(ExitReason::GeneralProtection);
|
||||
}
|
||||
memory
|
||||
.write_bytes(address, &value.to_le_bytes())
|
||||
.map_err(ExitReason::MemoryFault)
|
||||
|
||||
+156
-134
@@ -39,6 +39,8 @@ pub enum Op {
|
||||
Shl,
|
||||
Shr,
|
||||
Sar,
|
||||
Shld,
|
||||
Shrd,
|
||||
Mul,
|
||||
Imul,
|
||||
Imul2,
|
||||
@@ -215,7 +217,7 @@ pub enum Op {
|
||||
}
|
||||
|
||||
impl Op {
|
||||
pub const ALL: &[Op] = &[Op::Add, Op::Or, Op::Adc, Op::Sbb, Op::And, Op::Sub, Op::Xor, Op::Cmp, Op::Test, Op::Inc, Op::Dec, Op::Neg, Op::Not, Op::Mov, Op::Movzx, Op::Movsx, Op::Movsxd, Op::Lea, Op::Xchg, Op::Xadd, Op::Cmpxchg, Op::Bswap, Op::Cwde, Op::Cdq, Op::Rol, Op::Ror, Op::Rcl, Op::Rcr, Op::Shl, Op::Shr, Op::Sar, Op::Mul, Op::Imul, Op::Imul2, Op::Div, Op::Idiv, Op::Cmov, Op::Setcc, Op::Bt, Op::Bts, Op::Btr, Op::Btc, Op::Bsf, Op::Bsr, Op::Popcnt, Op::Tzcnt, Op::Lzcnt, Op::Push, Op::Pop, Op::Leave, Op::Call, Op::Jmp, Op::Jcc, Op::Ret, Op::Nop, Op::Hlt, Op::Syscall, Op::Clc, Op::Stc, Op::Cmc, Op::Cpuid, Op::Cld, Op::Std, Op::Movs, Op::Stos, Op::Movaps, Op::Movups, Op::Movdqa, Op::Movdqu, Op::Movntdq, Op::Movnti, Op::Movntps, Op::Movss, Op::Movsd, Op::Movq, Op::Movd, Op::Movlps, Op::Movhps, Op::Movmskps, Op::Movmskpd, Op::Pmovmskb, Op::Pand, Op::Pandn, Op::Por, Op::Pxor, Op::Punpcklbw, Op::Punpcklwd, Op::Punpckldq, Op::Packsswb, Op::Pcmpgtb, Op::Pcmpgtw, Op::Pcmpgtd, Op::Packuswb, Op::Punpckhbw, Op::Punpckhwd, Op::Punpckhdq, Op::Packssdw, Op::Punpcklqdq, Op::Punpckhqdq, Op::Pcmpeqb, Op::Pcmpeqw, Op::Pcmpeqd, Op::Paddq, Op::Pmullw, Op::Psubusb, Op::Psubusw, Op::Pminub, Op::Paddusb, Op::Paddusw, Op::Pmaxub, Op::Pavgb, Op::Pavgw, Op::Pmulhuw, Op::Pmulhw, Op::Psubsb, Op::Psubsw, Op::Pminsw, Op::Paddsb, Op::Paddsw, Op::Pmaxsw, Op::Pmuludq, Op::Pmaddwd, Op::Psadbw, Op::Psubb, Op::Psubw, Op::Psubd, Op::Psubq, Op::Paddb, Op::Paddw, Op::Paddd, Op::Psrlw, Op::Psraw, Op::Psllw, Op::Psrld, Op::Psrad, Op::Pslld, Op::Psrlq, Op::Psllq, Op::Psrldq, Op::Pslldq, Op::Pshufd, Op::Pshufhw, Op::Pshuflw, Op::Shufps, Op::Shufpd, Op::Pinsrw, Op::Pextrw, Op::Ldmxcsr, Op::Lfence, Op::Mfence, Op::Sfence, Op::Stmxcsr, Op::Sqrtps, Op::Sqrtpd, Op::Sqrtss, Op::Sqrtsd, Op::Addps, Op::Addpd, Op::Addss, Op::Addsd, Op::Mulps, Op::Mulpd, Op::Mulss, Op::Mulsd, Op::Subps, Op::Subpd, Op::Subss, Op::Subsd, Op::Minps, Op::Minpd, Op::Minss, Op::Minsd, Op::Divps, Op::Divpd, Op::Divss, Op::Divsd, Op::Maxps, Op::Maxpd, Op::Maxss, Op::Maxsd, Op::Cmpps, Op::Cmppd, Op::Cmpss, Op::Cmpsd, Op::Ucomiss, Op::Comiss, Op::Ucomisd, Op::Comisd, Op::Cvtps2pd, Op::Cvtpd2ps, Op::Cvtss2sd, Op::Cvtsd2ss, Op::Cvtdq2ps, Op::Cvtps2dq, Op::Cvttps2dq, Op::Cvttpd2dq, Op::Cvtdq2pd, Op::Cvtpd2dq, Op::Cvtsi2ss, Op::Cvttss2si, Op::Cvtss2si, Op::Cvtsi2sd, Op::Cvttsd2si, Op::Cvtsd2si];
|
||||
pub const ALL: &[Op] = &[Op::Add, Op::Or, Op::Adc, Op::Sbb, Op::And, Op::Sub, Op::Xor, Op::Cmp, Op::Test, Op::Inc, Op::Dec, Op::Neg, Op::Not, Op::Mov, Op::Movzx, Op::Movsx, Op::Movsxd, Op::Lea, Op::Xchg, Op::Xadd, Op::Cmpxchg, Op::Bswap, Op::Cwde, Op::Cdq, Op::Rol, Op::Ror, Op::Rcl, Op::Rcr, Op::Shl, Op::Shr, Op::Sar, Op::Shld, Op::Shrd, Op::Mul, Op::Imul, Op::Imul2, Op::Div, Op::Idiv, Op::Cmov, Op::Setcc, Op::Bt, Op::Bts, Op::Btr, Op::Btc, Op::Bsf, Op::Bsr, Op::Popcnt, Op::Tzcnt, Op::Lzcnt, Op::Push, Op::Pop, Op::Leave, Op::Call, Op::Jmp, Op::Jcc, Op::Ret, Op::Nop, Op::Hlt, Op::Syscall, Op::Clc, Op::Stc, Op::Cmc, Op::Cpuid, Op::Cld, Op::Std, Op::Movs, Op::Stos, Op::Movaps, Op::Movups, Op::Movdqa, Op::Movdqu, Op::Movntdq, Op::Movnti, Op::Movntps, Op::Movss, Op::Movsd, Op::Movq, Op::Movd, Op::Movlps, Op::Movhps, Op::Movmskps, Op::Movmskpd, Op::Pmovmskb, Op::Pand, Op::Pandn, Op::Por, Op::Pxor, Op::Punpcklbw, Op::Punpcklwd, Op::Punpckldq, Op::Packsswb, Op::Pcmpgtb, Op::Pcmpgtw, Op::Pcmpgtd, Op::Packuswb, Op::Punpckhbw, Op::Punpckhwd, Op::Punpckhdq, Op::Packssdw, Op::Punpcklqdq, Op::Punpckhqdq, Op::Pcmpeqb, Op::Pcmpeqw, Op::Pcmpeqd, Op::Paddq, Op::Pmullw, Op::Psubusb, Op::Psubusw, Op::Pminub, Op::Paddusb, Op::Paddusw, Op::Pmaxub, Op::Pavgb, Op::Pavgw, Op::Pmulhuw, Op::Pmulhw, Op::Psubsb, Op::Psubsw, Op::Pminsw, Op::Paddsb, Op::Paddsw, Op::Pmaxsw, Op::Pmuludq, Op::Pmaddwd, Op::Psadbw, Op::Psubb, Op::Psubw, Op::Psubd, Op::Psubq, Op::Paddb, Op::Paddw, Op::Paddd, Op::Psrlw, Op::Psraw, Op::Psllw, Op::Psrld, Op::Psrad, Op::Pslld, Op::Psrlq, Op::Psllq, Op::Psrldq, Op::Pslldq, Op::Pshufd, Op::Pshufhw, Op::Pshuflw, Op::Shufps, Op::Shufpd, Op::Pinsrw, Op::Pextrw, Op::Ldmxcsr, Op::Lfence, Op::Mfence, Op::Sfence, Op::Stmxcsr, Op::Sqrtps, Op::Sqrtpd, Op::Sqrtss, Op::Sqrtsd, Op::Addps, Op::Addpd, Op::Addss, Op::Addsd, Op::Mulps, Op::Mulpd, Op::Mulss, Op::Mulsd, Op::Subps, Op::Subpd, Op::Subss, Op::Subsd, Op::Minps, Op::Minpd, Op::Minss, Op::Minsd, Op::Divps, Op::Divpd, Op::Divss, Op::Divsd, Op::Maxps, Op::Maxpd, Op::Maxss, Op::Maxsd, Op::Cmpps, Op::Cmppd, Op::Cmpss, Op::Cmpsd, Op::Ucomiss, Op::Comiss, Op::Ucomisd, Op::Comisd, Op::Cvtps2pd, Op::Cvtpd2ps, Op::Cvtss2sd, Op::Cvtsd2ss, Op::Cvtdq2ps, Op::Cvtps2dq, Op::Cvttps2dq, Op::Cvttpd2dq, Op::Cvtdq2pd, Op::Cvtpd2dq, Op::Cvtsi2ss, Op::Cvttss2si, Op::Cvtss2si, Op::Cvtsi2sd, Op::Cvttsd2si, Op::Cvtsd2si];
|
||||
|
||||
/// Lower-case mnemonic stem.
|
||||
pub const fn name(self) -> &'static str {
|
||||
@@ -251,6 +253,8 @@ impl Op {
|
||||
Op::Shl => "shl",
|
||||
Op::Shr => "shr",
|
||||
Op::Sar => "sar",
|
||||
Op::Shld => "shld",
|
||||
Op::Shrd => "shrd",
|
||||
Op::Mul => "mul",
|
||||
Op::Imul => "imul",
|
||||
Op::Imul2 => "imul2",
|
||||
@@ -461,6 +465,8 @@ impl Op {
|
||||
Op::Shl => 0,
|
||||
Op::Shr => 0,
|
||||
Op::Sar => 0,
|
||||
Op::Shld => 0,
|
||||
Op::Shrd => 0,
|
||||
Op::Mul => 0,
|
||||
Op::Imul => 0,
|
||||
Op::Imul2 => 0,
|
||||
@@ -671,6 +677,8 @@ impl Op {
|
||||
Op::Shl => 0,
|
||||
Op::Shr => 0,
|
||||
Op::Sar => 0,
|
||||
Op::Shld => 0,
|
||||
Op::Shrd => 0,
|
||||
Op::Mul => 9,
|
||||
Op::Imul => 9,
|
||||
Op::Imul2 => 9,
|
||||
@@ -881,6 +889,8 @@ impl Op {
|
||||
Op::Shl => 31,
|
||||
Op::Shr => 31,
|
||||
Op::Sar => 31,
|
||||
Op::Shld => 31,
|
||||
Op::Shrd => 31,
|
||||
Op::Mul => 9,
|
||||
Op::Imul => 9,
|
||||
Op::Imul2 => 9,
|
||||
@@ -1091,6 +1101,8 @@ impl Op {
|
||||
Op::Shl => 32,
|
||||
Op::Shr => 32,
|
||||
Op::Sar => 32,
|
||||
Op::Shld => 32,
|
||||
Op::Shrd => 32,
|
||||
Op::Mul => 54,
|
||||
Op::Imul => 54,
|
||||
Op::Imul2 => 54,
|
||||
@@ -1301,6 +1313,8 @@ impl Op {
|
||||
Op::Shl => false,
|
||||
Op::Shr => false,
|
||||
Op::Sar => false,
|
||||
Op::Shld => false,
|
||||
Op::Shrd => false,
|
||||
Op::Mul => false,
|
||||
Op::Imul => false,
|
||||
Op::Imul2 => false,
|
||||
@@ -1511,6 +1525,8 @@ impl Op {
|
||||
Op::Shl => false,
|
||||
Op::Shr => false,
|
||||
Op::Sar => false,
|
||||
Op::Shld => false,
|
||||
Op::Shrd => false,
|
||||
Op::Mul => false,
|
||||
Op::Imul => false,
|
||||
Op::Imul2 => false,
|
||||
@@ -1721,6 +1737,8 @@ impl Op {
|
||||
Op::Shl => false,
|
||||
Op::Shr => false,
|
||||
Op::Sar => false,
|
||||
Op::Shld => false,
|
||||
Op::Shrd => false,
|
||||
Op::Mul => false,
|
||||
Op::Imul => false,
|
||||
Op::Imul2 => false,
|
||||
@@ -1898,7 +1916,7 @@ impl Op {
|
||||
}
|
||||
}
|
||||
|
||||
pub static FORMS: [Form; 392] = [
|
||||
pub static FORMS: [Form; 396] = [
|
||||
Form { op: Op::Movsxd, encoding: Encoding::RegRm, size: OperandSize::Wide, immediate: Immediate::None, source: 4, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Push, encoding: Encoding::OpReg, size: OperandSize::Quad, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Pop, encoding: Encoding::OpReg, size: OperandSize::Quad, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
@@ -1979,6 +1997,10 @@ pub static FORMS: [Form; 392] = [
|
||||
Form { op: Op::Cmpxchg, encoding: Encoding::RmReg, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: true },
|
||||
Form { op: Op::Xadd, encoding: Encoding::RmReg, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: true },
|
||||
Form { op: Op::Xadd, encoding: Encoding::RmReg, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: true },
|
||||
Form { op: Op::Shld, encoding: Encoding::RmRegImm, size: OperandSize::Variable, immediate: Immediate::Byte, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Shld, encoding: Encoding::RmRegCl, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Shrd, encoding: Encoding::RmRegImm, size: OperandSize::Variable, immediate: Immediate::Byte, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Shrd, encoding: Encoding::RmRegCl, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Movaps, encoding: Encoding::XmmRm, size: OperandSize::Xmm, immediate: Immediate::None, source: 16, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Movaps, encoding: Encoding::RmXmm, size: OperandSize::Xmm, immediate: Immediate::None, source: 16, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
Form { op: Op::Movaps, encoding: Encoding::XmmRm, size: OperandSize::Xmm, immediate: Immediate::None, source: 16, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
|
||||
@@ -2295,47 +2317,47 @@ pub static FORMS: [Form; 392] = [
|
||||
|
||||
/// Form per ModRM digit; 65535 marks an unsupported digit.
|
||||
pub static GROUPS: [[u16; 8]; 22] = [
|
||||
[264, 273, 282, 291, 300, 309, 318, 327],
|
||||
[265, 274, 283, 292, 301, 310, 319, 328],
|
||||
[266, 275, 284, 293, 302, 311, 320, 329],
|
||||
[268, 277, 286, 295, 304, 313, 322, 331],
|
||||
[269, 278, 287, 296, 305, 314, 323, 332],
|
||||
[270, 279, 288, 297, 306, 315, 324, 333],
|
||||
[6, 65535, 65535, 65535, 65535, 65535, 65535, 65535],
|
||||
[350, 351, 352, 353, 354, 355, 65535, 356],
|
||||
[357, 358, 359, 360, 361, 362, 65535, 363],
|
||||
[354, 355, 356, 357, 358, 359, 65535, 360],
|
||||
[361, 362, 363, 364, 365, 366, 65535, 367],
|
||||
[40, 65535, 65535, 65535, 65535, 65535, 65535, 65535],
|
||||
[41, 65535, 65535, 65535, 65535, 65535, 65535, 65535],
|
||||
[364, 365, 366, 367, 368, 369, 65535, 370],
|
||||
[371, 372, 373, 374, 375, 376, 65535, 377],
|
||||
[378, 379, 380, 381, 382, 383, 65535, 384],
|
||||
[385, 386, 387, 388, 389, 390, 65535, 391],
|
||||
[18, 65535, 334, 335, 336, 337, 338, 339],
|
||||
[19, 65535, 340, 341, 342, 343, 344, 345],
|
||||
[346, 347, 65535, 65535, 65535, 65535, 65535, 65535],
|
||||
[348, 349, 48, 65535, 49, 65535, 5, 65535],
|
||||
[368, 369, 370, 371, 372, 373, 65535, 374],
|
||||
[375, 376, 377, 378, 379, 380, 65535, 381],
|
||||
[382, 383, 384, 385, 386, 387, 65535, 388],
|
||||
[389, 390, 391, 392, 393, 394, 65535, 395],
|
||||
[18, 65535, 338, 339, 340, 341, 342, 343],
|
||||
[19, 65535, 344, 345, 346, 347, 348, 349],
|
||||
[350, 351, 65535, 65535, 65535, 65535, 65535, 65535],
|
||||
[352, 353, 48, 65535, 49, 65535, 5, 65535],
|
||||
[35, 65535, 65535, 65535, 65535, 65535, 65535, 65535],
|
||||
[65535, 65535, 201, 202, 65535, 203, 204, 205],
|
||||
[65535, 65535, 65535, 65535, 330, 331, 332, 333],
|
||||
[65535, 65535, 173, 65535, 175, 65535, 177, 65535],
|
||||
[65535, 65535, 179, 65535, 181, 65535, 183, 65535],
|
||||
[65535, 65535, 185, 188, 65535, 65535, 187, 189],
|
||||
[65535, 65535, 205, 206, 65535, 207, 208, 209],
|
||||
[65535, 65535, 65535, 65535, 334, 335, 336, 337],
|
||||
[65535, 65535, 177, 65535, 179, 65535, 181, 65535],
|
||||
[65535, 65535, 183, 65535, 185, 65535, 187, 65535],
|
||||
[65535, 65535, 189, 192, 65535, 65535, 191, 193],
|
||||
];
|
||||
|
||||
pub static ONE_BYTE: [Entry; 256] = [
|
||||
Entry::Form(258), Entry::Form(259), Entry::Form(260), Entry::Form(261),
|
||||
Entry::Form(262), Entry::Form(263), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(267), Entry::Form(268), Entry::Form(269), Entry::Form(270),
|
||||
Entry::Form(271), Entry::Form(272), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(276), Entry::Form(277), Entry::Form(278), Entry::Form(279),
|
||||
Entry::Form(280), Entry::Form(281), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(285), Entry::Form(286), Entry::Form(287), Entry::Form(288),
|
||||
Entry::Form(289), Entry::Form(290), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(294), Entry::Form(295), Entry::Form(296), Entry::Form(297),
|
||||
Entry::Form(298), Entry::Form(299), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(303), Entry::Form(304), Entry::Form(305), Entry::Form(306),
|
||||
Entry::Form(307), Entry::Form(308), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(312), Entry::Form(313), Entry::Form(314), Entry::Form(315),
|
||||
Entry::Form(316), Entry::Form(317), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(321), Entry::Form(322), Entry::Form(323), Entry::Form(324),
|
||||
Entry::Form(325), Entry::Form(326), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(262), Entry::Form(263), Entry::Form(264), Entry::Form(265),
|
||||
Entry::Form(266), Entry::Form(267), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(271), Entry::Form(272), Entry::Form(273), Entry::Form(274),
|
||||
Entry::Form(275), Entry::Form(276), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(280), Entry::Form(281), Entry::Form(282), Entry::Form(283),
|
||||
Entry::Form(284), Entry::Form(285), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(289), Entry::Form(290), Entry::Form(291), Entry::Form(292),
|
||||
Entry::Form(293), Entry::Form(294), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(298), Entry::Form(299), Entry::Form(300), Entry::Form(301),
|
||||
Entry::Form(302), Entry::Form(303), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(307), Entry::Form(308), Entry::Form(309), Entry::Form(310),
|
||||
Entry::Form(311), Entry::Form(312), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(316), Entry::Form(317), Entry::Form(318), Entry::Form(319),
|
||||
Entry::Form(320), Entry::Form(321), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(325), Entry::Form(326), Entry::Form(327), Entry::Form(328),
|
||||
Entry::Form(329), Entry::Form(330), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2391,14 +2413,14 @@ pub static TWO_BYTE: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Form(54), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(84), Entry::Form(85), Entry::Form(104), Entry::Form(106),
|
||||
Entry::Form(195), Entry::Form(197), Entry::Form(108), Entry::Form(110),
|
||||
Entry::Form(88), Entry::Form(89), Entry::Form(108), Entry::Form(110),
|
||||
Entry::Form(199), Entry::Form(201), Entry::Form(112), Entry::Form(114),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Group(16),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(80), Entry::Form(81), Entry::Unsupported, Entry::Form(94),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(238), Entry::Form(239),
|
||||
Entry::Form(84), Entry::Form(85), Entry::Unsupported, Entry::Form(98),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(242), Entry::Form(243),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2407,10 +2429,10 @@ pub static TWO_BYTE: [Entry; 256] = [
|
||||
Entry::Form(12), Entry::Form(12), Entry::Form(12), Entry::Form(12),
|
||||
Entry::Form(12), Entry::Form(12), Entry::Form(12), Entry::Form(12),
|
||||
Entry::Form(12), Entry::Form(12), Entry::Form(12), Entry::Form(12),
|
||||
Entry::Form(112), Entry::Form(206), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(116), Entry::Form(119), Entry::Form(122), Entry::Form(125),
|
||||
Entry::Form(210), Entry::Form(214), Entry::Form(242), Entry::Form(246),
|
||||
Entry::Form(218), Entry::Form(222), Entry::Form(226), Entry::Form(230),
|
||||
Entry::Form(116), Entry::Form(210), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(120), Entry::Form(123), Entry::Form(126), Entry::Form(129),
|
||||
Entry::Form(214), Entry::Form(218), Entry::Form(246), Entry::Form(250),
|
||||
Entry::Form(222), Entry::Form(226), Entry::Form(230), Entry::Form(234),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2428,15 +2450,15 @@ pub static TWO_BYTE: [Entry; 256] = [
|
||||
Entry::Form(13), Entry::Form(13), Entry::Form(13), Entry::Form(13),
|
||||
Entry::Form(13), Entry::Form(13), Entry::Form(13), Entry::Form(13),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(55), Entry::Form(72),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(80), Entry::Form(81), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Form(73),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Group(17), Entry::Form(9),
|
||||
Entry::Form(82), Entry::Form(83), Entry::Group(17), Entry::Form(9),
|
||||
Entry::Form(76), Entry::Form(77), Entry::Unsupported, Entry::Form(74),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(62), Entry::Form(63),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Group(18), Entry::Form(75),
|
||||
Entry::Form(67), Entry::Form(68), Entry::Form(64), Entry::Form(65),
|
||||
Entry::Form(78), Entry::Form(79), Entry::Form(234), Entry::Form(93),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(193), Entry::Unsupported,
|
||||
Entry::Form(78), Entry::Form(79), Entry::Form(238), Entry::Form(97),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(197), Entry::Unsupported,
|
||||
Entry::Form(66), Entry::Form(66), Entry::Form(66), Entry::Form(66),
|
||||
Entry::Form(66), Entry::Form(66), Entry::Form(66), Entry::Form(66),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2458,14 +2480,14 @@ pub static TWO_BYTE_66: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(86), Entry::Form(87), Entry::Form(105), Entry::Form(107),
|
||||
Entry::Form(196), Entry::Form(198), Entry::Form(109), Entry::Form(111),
|
||||
Entry::Form(90), Entry::Form(91), Entry::Form(109), Entry::Form(111),
|
||||
Entry::Form(200), Entry::Form(202), Entry::Form(113), Entry::Form(115),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(82), Entry::Form(83), Entry::Unsupported, Entry::Form(95),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(240), Entry::Form(241),
|
||||
Entry::Form(86), Entry::Form(87), Entry::Unsupported, Entry::Form(99),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(244), Entry::Form(245),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2474,18 +2496,18 @@ pub static TWO_BYTE_66: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(113), Entry::Form(207), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(117), Entry::Form(120), Entry::Form(123), Entry::Form(126),
|
||||
Entry::Form(211), Entry::Form(215), Entry::Form(243), Entry::Form(247),
|
||||
Entry::Form(219), Entry::Form(223), Entry::Form(227), Entry::Form(231),
|
||||
Entry::Form(127), Entry::Form(128), Entry::Form(129), Entry::Form(130),
|
||||
Entry::Form(117), Entry::Form(211), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(121), Entry::Form(124), Entry::Form(127), Entry::Form(130),
|
||||
Entry::Form(215), Entry::Form(219), Entry::Form(247), Entry::Form(251),
|
||||
Entry::Form(223), Entry::Form(227), Entry::Form(231), Entry::Form(235),
|
||||
Entry::Form(131), Entry::Form(132), Entry::Form(133), Entry::Form(134),
|
||||
Entry::Form(135), Entry::Form(136), Entry::Form(137), Entry::Form(138),
|
||||
Entry::Form(139), Entry::Form(140), Entry::Form(102), Entry::Form(88),
|
||||
Entry::Form(190), Entry::Group(19), Entry::Group(20), Entry::Group(21),
|
||||
Entry::Form(141), Entry::Form(142), Entry::Form(143), Entry::Unsupported,
|
||||
Entry::Form(139), Entry::Form(140), Entry::Form(141), Entry::Form(142),
|
||||
Entry::Form(143), Entry::Form(144), Entry::Form(106), Entry::Form(92),
|
||||
Entry::Form(194), Entry::Group(19), Entry::Group(20), Entry::Group(21),
|
||||
Entry::Form(145), Entry::Form(146), Entry::Form(147), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(103), Entry::Form(89),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(107), Entry::Form(93),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2502,22 +2524,22 @@ pub static TWO_BYTE_66: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(235), Entry::Unsupported,
|
||||
Entry::Form(199), Entry::Form(200), Entry::Form(194), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(239), Entry::Unsupported,
|
||||
Entry::Form(203), Entry::Form(204), Entry::Form(198), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Form(172), Entry::Form(178), Entry::Form(184),
|
||||
Entry::Form(144), Entry::Form(145), Entry::Form(101), Entry::Form(114),
|
||||
Entry::Form(146), Entry::Form(147), Entry::Form(148), Entry::Form(115),
|
||||
Entry::Form(149), Entry::Form(150), Entry::Form(151), Entry::Form(118),
|
||||
Entry::Form(152), Entry::Form(174), Entry::Form(180), Entry::Form(153),
|
||||
Entry::Form(154), Entry::Form(155), Entry::Form(249), Entry::Form(92),
|
||||
Entry::Form(156), Entry::Form(157), Entry::Form(158), Entry::Form(121),
|
||||
Entry::Form(159), Entry::Form(160), Entry::Form(161), Entry::Form(124),
|
||||
Entry::Unsupported, Entry::Form(176), Entry::Form(182), Entry::Form(186),
|
||||
Entry::Form(162), Entry::Form(163), Entry::Form(164), Entry::Unsupported,
|
||||
Entry::Form(165), Entry::Form(166), Entry::Form(167), Entry::Form(168),
|
||||
Entry::Form(169), Entry::Form(170), Entry::Form(171), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Form(176), Entry::Form(182), Entry::Form(188),
|
||||
Entry::Form(148), Entry::Form(149), Entry::Form(105), Entry::Form(118),
|
||||
Entry::Form(150), Entry::Form(151), Entry::Form(152), Entry::Form(119),
|
||||
Entry::Form(153), Entry::Form(154), Entry::Form(155), Entry::Form(122),
|
||||
Entry::Form(156), Entry::Form(178), Entry::Form(184), Entry::Form(157),
|
||||
Entry::Form(158), Entry::Form(159), Entry::Form(253), Entry::Form(96),
|
||||
Entry::Form(160), Entry::Form(161), Entry::Form(162), Entry::Form(125),
|
||||
Entry::Form(163), Entry::Form(164), Entry::Form(165), Entry::Form(128),
|
||||
Entry::Unsupported, Entry::Form(180), Entry::Form(186), Entry::Form(190),
|
||||
Entry::Form(166), Entry::Form(167), Entry::Form(168), Entry::Unsupported,
|
||||
Entry::Form(169), Entry::Form(170), Entry::Form(171), Entry::Form(172),
|
||||
Entry::Form(173), Entry::Form(174), Entry::Form(175), Entry::Unsupported,
|
||||
];
|
||||
|
||||
pub static TWO_BYTE_F3: [Entry; 256] = [
|
||||
@@ -2525,14 +2547,14 @@ pub static TWO_BYTE_F3: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(96), Entry::Form(97), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(100), Entry::Form(101), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(252), Entry::Unsupported,
|
||||
Entry::Form(253), Entry::Form(254), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(256), Entry::Unsupported,
|
||||
Entry::Form(257), Entry::Form(258), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2541,18 +2563,18 @@ pub static TWO_BYTE_F3: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Form(208), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Form(212), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(212), Entry::Form(216), Entry::Form(244), Entry::Form(248),
|
||||
Entry::Form(220), Entry::Form(224), Entry::Form(228), Entry::Form(232),
|
||||
Entry::Form(216), Entry::Form(220), Entry::Form(248), Entry::Form(252),
|
||||
Entry::Form(224), Entry::Form(228), Entry::Form(232), Entry::Form(236),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Form(90),
|
||||
Entry::Form(191), Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Form(94),
|
||||
Entry::Form(195), Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(100), Entry::Form(91),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(104), Entry::Form(95),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2569,7 +2591,7 @@ pub static TWO_BYTE_F3: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(69), Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(70), Entry::Form(71), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(236), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(240), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2578,7 +2600,7 @@ pub static TWO_BYTE_F3: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(250), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(254), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
@@ -2592,60 +2614,60 @@ pub static TWO_BYTE_F2: [Entry; 256] = [
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(98), Entry::Form(99), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(102), Entry::Form(103), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(259), Entry::Unsupported,
|
||||
Entry::Form(260), Entry::Form(261), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Form(213), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(217), Entry::Form(221), Entry::Form(249), Entry::Unsupported,
|
||||
Entry::Form(225), Entry::Form(229), Entry::Form(233), Entry::Form(237),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(196), Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(241), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(255), Entry::Unsupported,
|
||||
Entry::Form(256), Entry::Form(257), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Form(209), Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(213), Entry::Form(217), Entry::Form(245), Entry::Unsupported,
|
||||
Entry::Form(221), Entry::Form(225), Entry::Form(229), Entry::Form(233),
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Form(192), Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(237), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Form(251), Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
|
||||
|
||||
@@ -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)),
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1294,6 +1294,147 @@ gs_xadd_without_lock: rbx=8 rcx=5 gs8=03000000 => rcx=3 gs8=08000000 f=cpazso
|
||||
fs_rep_movsb_overrides_source_only_df_clear: rsi=8 rdi=D rcx=2 fs8=a1a2 m0=0000 => rsi=a rdi=D+2 rcx=0 m0=a1a2 f=*
|
||||
";
|
||||
|
||||
/// MOV r/m, imm (opcodes C6 /0 and C7 /0), issue #194.
|
||||
///
|
||||
/// Memory-form encodings came from Apple clang's assembler. The register forms
|
||||
/// of C6/C7 are the long alternatives to B0+r and B8+r, which that assembler
|
||||
/// never emits, so they were written by hand from the opcode map (ModRM
|
||||
/// `11 000 rm`). Expected values follow SDM 2B MOV, where the imm32 of the
|
||||
/// 64-bit form is sign-extended, and were computed by hand before the first run,
|
||||
/// without reading how the interpreter or the DBT execute C6 and C7. The author is
|
||||
/// an AI model, as for the rest of this file. Both engines already agreed with
|
||||
/// every case, so this group closes a coverage gap and fixes no defect.
|
||||
const IMMEDIATE_STORES: &str = r"
|
||||
@ mov byte ptr [rdi], 0x80
|
||||
c60780
|
||||
SDM 2B MOV (C6 /0)
|
||||
store_byte_base: rdi=D m0=aaaaaaaa => m0=80aaaaaa f=*
|
||||
@ mov word ptr [rdi], 0x8001
|
||||
66c7070180
|
||||
SDM 2B MOV (C7 /0, 66 prefix)
|
||||
store_word_base: rdi=D m0=aaaaaaaa => m0=0180aaaa f=*
|
||||
@ mov dword ptr [rdi], 0x80000001
|
||||
c70701000080
|
||||
SDM 2B MOV (C7 /0)
|
||||
store_dword_base_is_not_sign_extended: rdi=D m0=aaaaaaaaaaaaaaaa => m0=01000080aaaaaaaa f=*
|
||||
@ mov qword ptr [rdi], -0x7fffffff
|
||||
48c70701000080
|
||||
SDM 2B MOV (REX.W C7 /0, imm32 sign-extended to 64 bits)
|
||||
store_qword_negative_immediate_sign_extends: rdi=D m0=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa => m0=01000080ffffffffaaaaaaaaaaaaaaaa f=*
|
||||
@ mov qword ptr [rdi], 1
|
||||
48c70701000000
|
||||
SDM 2B MOV (REX.W C7 /0)
|
||||
store_qword_positive_immediate_clears_upper_half: rdi=D m0=ffffffffffffffffaaaaaaaaaaaaaaaa => m0=0100000000000000aaaaaaaaaaaaaaaa f=*
|
||||
@ mov qword ptr [rdi+rcx*8+0x10], -2
|
||||
48c744cf10feffffff
|
||||
SDM 2B MOV; 2A 2.1.5 (SIB, disp8)
|
||||
store_qword_sib_scale_8_disp8: rdi=D rcx=2 m20=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa => m20=feffffffffffffffaaaaaaaaaaaaaaaa f=*
|
||||
@ mov dword ptr [rdi+0x7f], 0x11223344
|
||||
c7477f44332211
|
||||
SDM 2B MOV; 2A 2.1.5 (disp8, largest positive)
|
||||
store_dword_disp8_positive_limit: rdi=D m7e=aaaaaaaaaaaaaaaaaaaa => m7e=aa44332211aaaaaaaaaa f=*
|
||||
@ mov dword ptr [rdi-0x80], 0x11223344
|
||||
c7478044332211
|
||||
SDM 2B MOV; 2A 2.1.5 (disp8 is sign-extended)
|
||||
store_dword_disp8_negative_limit: rdi=D+80 m0=aaaaaaaaaaaaaaaa => m0=44332211aaaaaaaa f=*
|
||||
@ mov dword ptr [rdi+0x100], 0x11223344
|
||||
c7870001000044332211
|
||||
SDM 2B MOV; 2A 2.1.5 (disp32)
|
||||
store_dword_disp32: rdi=D m100=aaaaaaaaaaaaaaaa => m100=44332211aaaaaaaa f=*
|
||||
@ mov byte ptr [r9+r10*2+1], 7
|
||||
43c644510107
|
||||
SDM 2B MOV; 2A 2.1.5 (REX.X and REX.B)
|
||||
store_byte_rex_base_and_index: r9=D+10 r10=8 m20=aaaaaaaa => m20=aa07aaaa f=*
|
||||
@ mov qword ptr [r12], 5
|
||||
49c7042405000000
|
||||
SDM 2B MOV; 2A 2.1.5 (R12 needs a SIB byte)
|
||||
store_qword_r12_base: r12=D+30 m30=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa => m30=0500000000000000aaaaaaaaaaaaaaaa f=*
|
||||
@ mov qword ptr [r13], 5
|
||||
49c7450005000000
|
||||
SDM 2B MOV; 2A 2.1.5 (R13 with mod 00 would be RIP-relative, so disp8 0)
|
||||
store_qword_r13_base: r13=D+40 m40=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa => m40=0500000000000000aaaaaaaaaaaaaaaa f=*
|
||||
@ mov word ptr [rsp+8], 0x1234
|
||||
66c74424083412
|
||||
SDM 2B MOV; 2A 2.1.5 (RSP needs a SIB byte)
|
||||
store_word_rsp_base: rsp=D+58 m60=aaaaaaaa => m60=3412aaaa f=*
|
||||
@ mov byte ptr [rbp+2], 0x7f
|
||||
c645027f
|
||||
SDM 2B MOV
|
||||
store_byte_rbp_disp8: rbp=D+70 m72=aaaa => m72=7faa f=*
|
||||
@ mov byte ptr [rdi+rcx], -1
|
||||
c6040fff
|
||||
SDM 2B MOV
|
||||
store_byte_base_plus_index: rdi=D+80 rcx=5 m84=aaaaaaaa => m84=aaffaaaa f=*
|
||||
@ mov word ptr [r8+r9*4+0x20], 0x7ffe
|
||||
6643c7448820fe7f
|
||||
SDM 2B MOV; 2A 2.1.5
|
||||
store_word_r8_r9_scaled: r8=D r9=10 m60=aaaaaaaa => m60=fe7faaaa f=*
|
||||
@ mov eax, 0x80000001
|
||||
c7c001000080
|
||||
SDM 2B MOV (C7 /0, register form); 1 3.4.1.1
|
||||
register_dword_zero_extends: rax=ffffffffffffffff => rax=0000000080000001 f=*
|
||||
@ mov ax, 0x8001
|
||||
66c7c00180
|
||||
SDM 2B MOV; 1 3.4.1.1
|
||||
register_word_keeps_upper_bits: rax=1122334455667788 => rax=1122334455668001 f=*
|
||||
@ mov rax, -2
|
||||
48c7c0feffffff
|
||||
SDM 2B MOV (REX.W C7 /0, register form)
|
||||
register_qword_sign_extends: rax=0 => rax=fffffffffffffffe f=*
|
||||
@ mov r10, 0x7fffffff
|
||||
49c7c2ffffff7f
|
||||
SDM 2B MOV
|
||||
register_qword_rex_b_positive: r10=ffffffffffffffff => r10=000000007fffffff f=*
|
||||
@ mov r8d, -1
|
||||
41c7c0ffffffff
|
||||
SDM 2B MOV; 1 3.4.1.1
|
||||
register_dword_rex_b_zero_extends: r8=1122334455667788 => r8=00000000ffffffff f=*
|
||||
@ mov al, 0x80
|
||||
c6c080
|
||||
SDM 2B MOV (C6 /0, register form)
|
||||
register_byte_al: rax=1122334455667788 => rax=1122334455667780 f=*
|
||||
@ mov ah, 5
|
||||
c6c405
|
||||
SDM 2B MOV; 1 3.4.1.1 (no REX: ModRM 4 is AH)
|
||||
register_byte_ah: rax=1122334455667788 => rax=1122334455660588 f=*
|
||||
@ mov sil, 3
|
||||
40c6c603
|
||||
SDM 2B MOV; 1 3.4.1.1 (a REX prefix makes ModRM 6 SIL)
|
||||
register_byte_sil: rsi=1122334455667788 => rsi=1122334455667703 f=*
|
||||
@ mov r9b, 4
|
||||
41c6c104
|
||||
SDM 2B MOV
|
||||
register_byte_r9b: r9=1122334455667788 => r9=1122334455667704 f=*
|
||||
@ mov byte ptr [rdi], 0x80
|
||||
!c60780
|
||||
SDM 3A 7.15 Interrupt 14
|
||||
store_byte_unmapped: rdi=U => ! PFW U
|
||||
store_byte_readonly: rdi=R+8 => ! PFW R+8
|
||||
@ mov word ptr [rdi], 0x8001
|
||||
!66c7070180
|
||||
SDM 3A 7.15 Interrupt 14
|
||||
store_word_unmapped: rdi=U => ! PFW U
|
||||
store_word_readonly: rdi=R+8 => ! PFW R+8
|
||||
@ mov dword ptr [rdi], 0x80000001
|
||||
!c70701000080
|
||||
SDM 3A 7.15 Interrupt 14
|
||||
store_dword_unmapped: rdi=U => ! PFW U
|
||||
store_dword_readonly: rdi=R+8 => ! PFW R+8
|
||||
@ mov qword ptr [rdi], -0x7fffffff
|
||||
!48c70701000080
|
||||
SDM 3A 7.15 Interrupt 14
|
||||
store_qword_unmapped: rdi=U => ! PFW U
|
||||
store_qword_readonly: rdi=R+8 => ! PFW R+8
|
||||
@ C6 with ModRM reg field 1 (no such instruction)
|
||||
!c60f01
|
||||
SDM 2B MOV (C6 is defined only as /0); 3A 7.15 Interrupt 6
|
||||
c6_reg_field_1_is_ud: rdi=D m0=aaaaaaaa => ! UD
|
||||
@ C7 with ModRM reg field 1 (no such instruction)
|
||||
!c70f01000000
|
||||
SDM 2B MOV (C7 is defined only as /0); 3A 7.15 Interrupt 6
|
||||
c7_reg_field_1_is_ud: rdi=D m0=aaaaaaaa => ! UD
|
||||
";
|
||||
|
||||
const DECODING: &str = r"
|
||||
@ mov eax, [ebx]
|
||||
678b03
|
||||
@@ -1547,15 +1688,75 @@ store8_crossing_into_unmapped_page_writes_nothing: rdi=U rax=1122334455667788 =>
|
||||
movups_load_crossing_into_unmapped: rsi=U => ! PFR U
|
||||
";
|
||||
|
||||
const DEFECT_NONCANONICAL_ADDRESS: &str = r"
|
||||
const NONCANONICAL_ADDRESS: &str = r"
|
||||
@ movzx eax, byte ptr [rsi]
|
||||
!0fb606
|
||||
SDM 1 3.3.7.1; 2A MOVZX
|
||||
noncanonical_byte_load_faults: rsi=0000800000000000 => ! GP
|
||||
@ mov ax, [rsi]
|
||||
!668b06
|
||||
SDM 1 3.3.7.1; 2A MOV
|
||||
noncanonical_word_load_faults: rsi=0000800000000000 => ! GP
|
||||
@ mov eax, [rsi]
|
||||
!8b06
|
||||
SDM 1 3.3.7.1; 2A MOV
|
||||
noncanonical_dword_load_faults: rsi=0000800000000000 => ! GP
|
||||
@ mov rax, [rsi]
|
||||
!488b06
|
||||
SDM 1 3.3.7.1; 3A 7.15 Interrupt 13
|
||||
noncanonical_load_faults: rsi=100000000000000 => ! GP
|
||||
@ mov [rdi], rax
|
||||
SDM 1 3.3.7.1; 2A MOV
|
||||
noncanonical_qword_load_faults: rsi=0000800000000000 => ! GP
|
||||
@ mov byte ptr [rdi], al
|
||||
!8807
|
||||
SDM 1 3.3.7.1; 2A MOV
|
||||
noncanonical_byte_store_faults: rdi=ffff7fffffffffff => ! GP
|
||||
@ mov word ptr [rdi], ax
|
||||
!668907
|
||||
SDM 1 3.3.7.1; 2A MOV
|
||||
noncanonical_word_store_faults: rdi=ffff7fffffffffff => ! GP
|
||||
@ mov dword ptr [rdi], eax
|
||||
!8907
|
||||
SDM 1 3.3.7.1; 2A MOV
|
||||
noncanonical_dword_store_faults: rdi=ffff7fffffffffff => ! GP
|
||||
@ mov qword ptr [rdi], rax
|
||||
!488907
|
||||
SDM 1 3.3.7.1; 3A 7.15 Interrupt 13
|
||||
noncanonical_store_faults: rdi=7fffffffffffffff => ! GP
|
||||
SDM 1 3.3.7.1; 2A MOV
|
||||
noncanonical_qword_store_faults: rdi=ffff7fffffffffff => ! GP
|
||||
@ mov rax, [rsi]
|
||||
!488b06
|
||||
SDM 1 3.3.7.1; 2A MOV
|
||||
qword_crossing_into_lower_hole_faults: rsi=00007fffffffffff => ! GP
|
||||
qword_ending_at_last_lower_canonical_byte_is_unmapped: rsi=00007ffffffffff8 => ! PFR 00007ffffffffff8
|
||||
@ movzx eax, byte ptr [rsi]
|
||||
!0fb606
|
||||
SDM 1 3.3.7.1; 2A MOVZX
|
||||
last_lower_canonical_byte_is_unmapped: rsi=00007fffffffffff => ! PFR 00007fffffffffff
|
||||
first_upper_canonical_byte_is_unmapped: rsi=ffff800000000000 => ! PFR ffff800000000000
|
||||
@ movups xmm0, [rsi]
|
||||
!0f1006
|
||||
SDM 1 3.3.7.1; 2B MOVUPS
|
||||
noncanonical_vector_load_faults: rsi=0000800000000000 => ! GP
|
||||
vector_crossing_into_lower_hole_faults: rsi=00007fffffffffff => ! GP
|
||||
vector_ending_at_last_lower_canonical_byte_is_unmapped: rsi=00007ffffffffff0 => ! PFR 00007ffffffffff0
|
||||
@ movups [rdi], xmm0
|
||||
!0f1107
|
||||
SDM 1 3.3.7.1; 2B MOVUPS
|
||||
noncanonical_vector_store_faults: rdi=ffff7fffffffffff => ! GP
|
||||
vector_store_at_first_upper_canonical_byte_is_unmapped: rdi=ffff800000000000 => ! PFR ffff800000000000
|
||||
@ movdqu xmm0, [rsi]
|
||||
!f30f6f06
|
||||
SDM 1 3.3.7.1; 2B MOVDQU
|
||||
movdqu_crossing_into_lower_hole_faults: rsi=00007fffffffffff => ! GP
|
||||
movdqu_at_first_upper_canonical_byte_is_unmapped: rsi=ffff800000000000 => ! PFR ffff800000000000
|
||||
@ movdqu [rdi], xmm0
|
||||
!f30f7f07
|
||||
SDM 1 3.3.7.1; 2B MOVDQU
|
||||
movdqu_store_crossing_into_lower_hole_faults: rdi=00007fffffffffff => ! GP
|
||||
@ mov rax, gs:[rsi]
|
||||
!65488b06
|
||||
SDM 1 3.3.7.1, 3A 4.2; 2A MOV
|
||||
wrapped_segment_address_is_checked: gsbase=0000800000000000 rsi=ffffffffffffffff => ! GP
|
||||
noncanonical_segment_base_faults: gsbase=0000800000000000 rsi=0 => ! GP
|
||||
canonical_upper_segment_base_is_unmapped: gsbase=ffff800000000000 rsi=0 => ! PFR ffff800000000000
|
||||
";
|
||||
|
||||
const PACKED_INTEGER_SSE2: &str = r"
|
||||
@@ -2676,7 +2877,7 @@ const GROUPS: &[(&str, &str)] = &[
|
||||
("fences", FENCES),
|
||||
("memory_faults", MEMORY_FAULTS),
|
||||
("straddling_fault_address", STRADDLING_FAULT_ADDRESS),
|
||||
("defect_noncanonical_address", DEFECT_NONCANONICAL_ADDRESS),
|
||||
("noncanonical_address", NONCANONICAL_ADDRESS),
|
||||
("packed_integer_sse2", PACKED_INTEGER_SSE2),
|
||||
("packed_integer_beyond_sse2", PACKED_INTEGER_BEYOND_SSE2),
|
||||
("fp_rounding", FP_ROUNDING),
|
||||
@@ -2774,14 +2975,6 @@ const UNSUPPORTED: &[(&str, usize)] = &[
|
||||
("roundss_imm_modes", 0),
|
||||
("sahf_clear_keeps_of", 0),
|
||||
("sahf_ignores_bits_1_3_5", 0),
|
||||
("shld16_by16_takes_source", 0),
|
||||
("shld32_by1_sign_change", 0),
|
||||
("shld32_by4", 0),
|
||||
("shld32_cl32_is_count_zero", 0),
|
||||
("shld64_by63", 0),
|
||||
("shrd32_by8", 0),
|
||||
("shrd64_by1_sign_change", 0),
|
||||
("shrd64_cl64_is_count_zero", 0),
|
||||
];
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -3407,6 +3600,11 @@ fn exchange() {
|
||||
check_group(EXCHANGE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn immediate_stores() {
|
||||
check_group(IMMEDIATE_STORES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flag_moves() {
|
||||
check_group(FLAG_MOVES);
|
||||
@@ -3468,9 +3666,8 @@ fn straddling_fault_address() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "known defect (#155): a non-canonical address is a memory fault, not #GP"]
|
||||
fn defect_noncanonical_address() {
|
||||
check_group(DEFECT_NONCANONICAL_ADDRESS);
|
||||
fn noncanonical_address() {
|
||||
check_group(NONCANONICAL_ADDRESS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,302 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Gate A1 (issue #329): an original C program with no C library linked,
|
||||
//! built from source by this test and run through the loader, the standard
|
||||
//! services and the ARM64 DBT.
|
||||
//!
|
||||
//! `tests/compat_fixtures/build-gate-a1.sh` compiles
|
||||
//! `tests/compat_fixtures/gate_a1.c` with clang and links it with an LLD, so
|
||||
//! the test needs both on the host. It fails, and does not skip, when they
|
||||
//! are missing.
|
||||
//!
|
||||
//! Every expected value is recomputed here, in Rust, from the description of
|
||||
//! the program: nothing is read back from a run and asserted. The host
|
||||
//! arithmetic and the guest arithmetic share no code.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use xenora_loader::cpu::ExitReason;
|
||||
use xenora_loader::imports::ImportRegistry;
|
||||
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
|
||||
use xenora_loader::startup::{StartupLayout, StartupResult, run_synthetic_startup};
|
||||
|
||||
/// The status of a run in which every check passed.
|
||||
const STATUS: u32 = 0x00A1_A1A1;
|
||||
const RECORDS: u32 = 64;
|
||||
/// Checks the program counts on a complete run, and the one that the
|
||||
/// `GATE_BREAK` variant fails: three for allocation, 63 for the sort order,
|
||||
/// then the Fibonacci check.
|
||||
const CHECKS: u32 = 92;
|
||||
const BROKEN_CHECK: u32 = 67;
|
||||
/// Twelve from ucrtbase.dll and eight from kernel32.dll.
|
||||
const IMPORTS: usize = 20;
|
||||
/// The six entries of the program's table of function pointers.
|
||||
const RELOCATIONS: usize = 6;
|
||||
|
||||
/// Build every variant once and return the output directory.
|
||||
fn built() -> &'static Path {
|
||||
static OUT: OnceLock<PathBuf> = OnceLock::new();
|
||||
OUT.get_or_init(|| {
|
||||
// One directory per test process: two `cargo test` runs that share a
|
||||
// target directory must not write and read the same files.
|
||||
let out = PathBuf::from(env!("CARGO_TARGET_TMPDIR"))
|
||||
.join(format!("gate-a1-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&out);
|
||||
let script = concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/../../tests/compat_fixtures/build-gate-a1.sh"
|
||||
);
|
||||
let build = Command::new("sh")
|
||||
.arg(script)
|
||||
.arg(&out)
|
||||
.output()
|
||||
.expect("run tests/compat_fixtures/build-gate-a1.sh");
|
||||
assert!(
|
||||
build.status.success(),
|
||||
"the Gate A1 program did not build; it needs clang and an LLD:\n{}{}",
|
||||
String::from_utf8_lossy(&build.stdout),
|
||||
String::from_utf8_lossy(&build.stderr)
|
||||
);
|
||||
let toolchain = std::fs::read_to_string(out.join("toolchain.txt")).unwrap();
|
||||
println!("Gate A1 built with:\n{toolchain}");
|
||||
out
|
||||
})
|
||||
}
|
||||
|
||||
struct Outcome {
|
||||
result: StartupResult,
|
||||
state: Arc<ServicesState>,
|
||||
}
|
||||
|
||||
/// Run one built variant through the real startup path with the standard
|
||||
/// services, loaded away from its preferred base so its relocations matter.
|
||||
fn run(name: &str, budget: usize) -> Result<Outcome, String> {
|
||||
let bytes = std::fs::read(built().join(format!("{name}.exe"))).unwrap();
|
||||
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0))));
|
||||
let mut registry = ImportRegistry::new();
|
||||
register_standard_services(&mut registry, Arc::clone(&state));
|
||||
let layout = StartupLayout {
|
||||
image_base: 0x2_5000_0000,
|
||||
stack_top: 0x2_0001_0000,
|
||||
tls_base: 0x3_0000_0000,
|
||||
};
|
||||
match run_synthetic_startup(&bytes, layout, registry, budget) {
|
||||
Ok(result) => Ok(Outcome { result, state }),
|
||||
Err(error) => {
|
||||
// Nothing may have run or been left behind.
|
||||
assert_eq!(state.exit_status(), None, "{name}");
|
||||
assert_eq!(state.open_handle_count(), 0, "{name}");
|
||||
assert_eq!(state.file_contents("C:\\gate-a1.txt"), None, "{name}");
|
||||
Err(error.to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// What the program computes, restated independently
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// One of six steps chosen by the round number.
|
||||
fn mix(value: u64, round: u32) -> u64 {
|
||||
match round % 6 {
|
||||
0 => value
|
||||
.wrapping_mul(6_364_136_223_846_793_005)
|
||||
.wrapping_add(1_442_695_040_888_963_407),
|
||||
1 => value.rotate_left(13),
|
||||
2 => value / 7 + value % 1_000_003,
|
||||
3 => value ^ (value >> 29),
|
||||
// C division of a signed 64-bit value truncates toward zero.
|
||||
4 => (value as i64 / -3) as u64,
|
||||
_ => value.wrapping_sub(u64::from(round)),
|
||||
}
|
||||
}
|
||||
|
||||
struct Expected {
|
||||
report: String,
|
||||
/// The sorted records as the program stores them: key, weight, ratio.
|
||||
data: Vec<u8>,
|
||||
key_checksum: u64,
|
||||
}
|
||||
|
||||
fn expected() -> Expected {
|
||||
let mut state = 0x243F_6A88_85A3_08D3_u64;
|
||||
let mut records = Vec::new();
|
||||
let mut weighted = 0u64;
|
||||
for index in 0..RECORDS {
|
||||
state = mix(state, index);
|
||||
let fraction = state & 0xFFFF;
|
||||
// The program sums fraction / 65536 * index in doubles. Every term
|
||||
// and the sum are exact, so the scaled total is this integer.
|
||||
weighted += fraction * u64::from(index);
|
||||
// The index in the low six bits makes every key different.
|
||||
let key = (((state >> 20) as u32) << 6) | index;
|
||||
records.push((key, index, fraction as f64 / 65536.0));
|
||||
}
|
||||
records.sort_by_key(|record| record.0);
|
||||
assert!(records.windows(2).all(|pair| pair[0].0 != pair[1].0));
|
||||
|
||||
// FNV-1a over each key, least significant byte first.
|
||||
let mut key_checksum = 0xCBF2_9CE4_8422_2325_u64;
|
||||
let mut data = Vec::new();
|
||||
for (key, weight, ratio) in &records {
|
||||
for byte in key.to_le_bytes() {
|
||||
key_checksum = (key_checksum ^ u64::from(byte)).wrapping_mul(0x0100_0000_01B3);
|
||||
}
|
||||
data.extend(key.to_le_bytes());
|
||||
data.extend(weight.to_le_bytes());
|
||||
data.extend(ratio.to_le_bytes());
|
||||
}
|
||||
let wide = (state % 1_000_000_007) as i64 * -977 / 13;
|
||||
// Fibonacci(12) is 144. The text is 16 characters; its hexadecimal and
|
||||
// decimal fields are 0x7b and -42. A missing file is error 2
|
||||
// (ERROR_FILE_NOT_FOUND) and an impossible allocation sets errno to 12
|
||||
// (ENOMEM). The data file holds 64 records of 16 bytes.
|
||||
let report = format!(
|
||||
"gate a1\nrecords {RECORDS}\nkeys {key_checksum}\nweighted {weighted}\nfibonacci 144\n\
|
||||
wide {wide}\nstrings 16 123 -42\nerrors 2 12\nfile {}\n",
|
||||
data.len()
|
||||
);
|
||||
Expected {
|
||||
report,
|
||||
data,
|
||||
key_checksum,
|
||||
}
|
||||
}
|
||||
|
||||
/// The program's result block, which it keeps in a section named `.gate`:
|
||||
/// magic, check count, key checksum, kept pointer, freed pointer.
|
||||
fn result_block(outcome: &Outcome) -> (u32, u32, u64, u64, u64) {
|
||||
let image = &outcome.result.image;
|
||||
let section = image
|
||||
.pe
|
||||
.sections
|
||||
.iter()
|
||||
.find(|section| section.name == ".gate")
|
||||
.expect("a .gate section");
|
||||
let at = 0x2_5000_0000 + u64::from(section.virtual_address);
|
||||
let memory = &image.memory;
|
||||
(
|
||||
memory.read_u32(at).unwrap(),
|
||||
memory.read_u32(at + 4).unwrap(),
|
||||
memory.read_u64(at + 8).unwrap(),
|
||||
memory.read_u64(at + 16).unwrap(),
|
||||
memory.read_u64(at + 24).unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// The gate
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[test]
|
||||
fn the_program_runs_to_its_exit_at_every_optimization_level() {
|
||||
let wanted = expected();
|
||||
for name in ["gate-a1-O0", "gate-a1-O1", "gate-a1-O2", "gate-a1-Os"] {
|
||||
let outcome = run(name, 2_000_000).unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||
let result = &outcome.result;
|
||||
let state = &outcome.state;
|
||||
|
||||
// It was loaded, relocated and bound by the real startup path.
|
||||
assert_eq!(result.bound_imports, IMPORTS, "{name}");
|
||||
assert_eq!(result.relocations.applied_dir64, RELOCATIONS, "{name}");
|
||||
|
||||
// It ended itself, with all 32 bits of its status.
|
||||
assert_eq!(
|
||||
result.execution.exit_reason,
|
||||
ExitReason::ProcessExit(STATUS),
|
||||
"{name}"
|
||||
);
|
||||
assert_eq!(state.exit_status(), Some(STATUS), "{name}");
|
||||
|
||||
// It ran as translated ARM64 code.
|
||||
let metrics = &result.dbt_metrics;
|
||||
assert!(
|
||||
metrics.blocks_compiled > 0 && metrics.native_bytes_emitted > 0,
|
||||
"{name}"
|
||||
);
|
||||
assert!(metrics.instructions_executed > 1_000, "{name}");
|
||||
assert!(metrics.service_calls > 20, "{name}");
|
||||
println!(
|
||||
"{name}: {} guest instructions, {} of them through the shared semantics, {} service \
|
||||
calls",
|
||||
metrics.instructions_executed, metrics.interpreter_fallbacks, metrics.service_calls
|
||||
);
|
||||
|
||||
// Output: the report it wrote.
|
||||
let report = state.file_contents("C:\\gate-a1.txt").expect("a report");
|
||||
assert_eq!(String::from_utf8(report).unwrap(), wanted.report, "{name}");
|
||||
|
||||
// Filesystem: the data file holds the sorted records, the file it
|
||||
// looked for was not created, and the report handle it left open was
|
||||
// closed by the exit.
|
||||
assert_eq!(
|
||||
state.file_contents("C:\\gate-a1.bin").as_deref(),
|
||||
Some(wanted.data.as_slice()),
|
||||
"{name}"
|
||||
);
|
||||
assert_eq!(state.file_contents("C:\\none.bin"), None, "{name}");
|
||||
assert_eq!(state.open_handle_count(), 0, "{name}");
|
||||
|
||||
// Memory: the result block, a block it kept and a block it freed.
|
||||
let (magic, checks, key_checksum, kept, freed) = result_block(&outcome);
|
||||
assert_eq!((magic, checks), (0x3141_5926, CHECKS), "{name}");
|
||||
assert_eq!(key_checksum, wanted.key_checksum, "{name}");
|
||||
let memory = &result.image.memory;
|
||||
let mut text = [0u8; 16];
|
||||
memory.read_bytes(kept, &mut text).unwrap();
|
||||
assert_eq!(&text, b"kept by gate a1\0", "{name}");
|
||||
assert!(
|
||||
memory.read_u8(freed).is_err(),
|
||||
"{name}: freed block is still mapped"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_returning_entry_point_gives_the_same_result() {
|
||||
let outcome = run("gate-a1-return", 2_000_000).unwrap();
|
||||
assert_eq!(
|
||||
outcome.result.execution.exit_reason,
|
||||
ExitReason::ProcessExit(STATUS)
|
||||
);
|
||||
assert_eq!(outcome.state.exit_status(), Some(STATUS));
|
||||
assert_eq!(outcome.state.open_handle_count(), 0);
|
||||
let report = outcome.state.file_contents("C:\\gate-a1.txt").unwrap();
|
||||
assert_eq!(String::from_utf8(report).unwrap(), expected().report);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wrong_expectation_exits_with_the_number_of_the_failed_check() {
|
||||
// The variant expects Fibonacci(12) to be 145. Everything before that
|
||||
// check passes, and nothing after it runs.
|
||||
let outcome = run("gate-a1-break", 2_000_000).unwrap();
|
||||
assert_eq!(
|
||||
outcome.result.execution.exit_reason,
|
||||
ExitReason::ProcessExit(BROKEN_CHECK)
|
||||
);
|
||||
assert_eq!(outcome.state.exit_status(), Some(BROKEN_CHECK));
|
||||
assert_eq!(result_block(&outcome).1, BROKEN_CHECK);
|
||||
assert_eq!(outcome.state.file_contents("C:\\gate-a1.bin"), None);
|
||||
assert_eq!(outcome.state.file_contents("C:\\gate-a1.txt"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_import_nobody_provides_is_refused_before_entry() {
|
||||
let error = run("gate-a1-missing", 2_000_000).err().expect("refusal");
|
||||
assert_eq!(
|
||||
error,
|
||||
"unresolved import dependency: kernel32.dll!GateMissingService"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_step_budget_that_is_too_small_is_not_an_exit() {
|
||||
let outcome = run("gate-a1-O1", 500).unwrap();
|
||||
assert_eq!(
|
||||
outcome.result.execution.exit_reason,
|
||||
ExitReason::StepLimitExceeded
|
||||
);
|
||||
assert_eq!(outcome.state.exit_status(), None);
|
||||
assert_eq!(outcome.state.file_contents("C:\\gate-a1.txt"), None);
|
||||
}
|
||||
@@ -0,0 +1,430 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! The PE headers are mapped read-only at the image base (#333).
|
||||
//!
|
||||
//! Windows maps the first `SizeOfHeaders` bytes of an image at its base, and
|
||||
//! programs read them: a C runtime walks its own section table before `main`.
|
||||
//!
|
||||
//! Every image here is original and built byte by byte in this file. Expected
|
||||
//! values are the bytes the builder wrote, never values read back from a run.
|
||||
|
||||
use xenora_loader::cpu::{ExitReason, Register};
|
||||
use xenora_loader::imports::ImportRegistry;
|
||||
use xenora_loader::startup::{StartupLayout, StartupResult, run_synthetic_startup};
|
||||
use xenora_loader::{MemoryError, ParsedPe, PeError};
|
||||
|
||||
const PREFERRED_BASE: u64 = 0x1_4000_0000;
|
||||
const OTHER_BASE: u64 = 0x2_5000_0000;
|
||||
/// Deliberately not the usual 0x40 or 0x80, so a read of it is distinctive.
|
||||
const E_LFANEW: u32 = 0x90;
|
||||
const OPTIONAL: usize = E_LFANEW as usize + 4 + 20;
|
||||
const OPTIONAL_SIZE: usize = 240;
|
||||
const SECTIONS: u16 = 2;
|
||||
/// The first byte after the section table.
|
||||
const TABLE_END: u32 = (OPTIONAL + OPTIONAL_SIZE) as u32 + 40 * SECTIONS as u32;
|
||||
|
||||
/// One image: `.text` holding `code` and an uninitialized `.data`.
|
||||
struct Image {
|
||||
size_of_headers: u32,
|
||||
text_rva: u32,
|
||||
data_rva: u32,
|
||||
data_size: u32,
|
||||
/// File offset of the code, and so the length of the file before it.
|
||||
text_offset: u32,
|
||||
code: Vec<u8>,
|
||||
/// Base relocation blocks, placed in `.text` 0x100 bytes after the code.
|
||||
relocations: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Image {
|
||||
fn new(code: &[u8]) -> Self {
|
||||
Self {
|
||||
size_of_headers: 0x400,
|
||||
text_rva: 0x2000,
|
||||
data_rva: 0x3000,
|
||||
data_size: 0x100,
|
||||
text_offset: 0x400,
|
||||
code: code.to_vec(),
|
||||
relocations: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn build(&self) -> Vec<u8> {
|
||||
let mut pe = vec![0u8; self.text_offset as usize + 0x200];
|
||||
pe[0..2].copy_from_slice(b"MZ");
|
||||
pe[0x3C..0x40].copy_from_slice(&E_LFANEW.to_le_bytes());
|
||||
// A recognisable pattern where a DOS stub would be, and in the padding
|
||||
// after the section table.
|
||||
for (i, byte) in pe[0x40..E_LFANEW as usize].iter_mut().enumerate() {
|
||||
*byte = (i * 7 + 3) as u8;
|
||||
}
|
||||
// The pattern stops after two pages so that a very large header stays cheap.
|
||||
let padding_end = (self.text_offset as usize).min(0x2000);
|
||||
for (i, byte) in pe[TABLE_END as usize..padding_end].iter_mut().enumerate() {
|
||||
*byte = (i * 5 + 1) as u8;
|
||||
}
|
||||
let pe_at = E_LFANEW as usize;
|
||||
pe[pe_at..pe_at + 4].copy_from_slice(b"PE\0\0");
|
||||
let coff = pe_at + 4;
|
||||
pe[coff..coff + 2].copy_from_slice(&0x8664u16.to_le_bytes());
|
||||
pe[coff + 2..coff + 4].copy_from_slice(&SECTIONS.to_le_bytes());
|
||||
pe[coff + 16..coff + 18].copy_from_slice(&(OPTIONAL_SIZE as u16).to_le_bytes());
|
||||
pe[coff + 18..coff + 20].copy_from_slice(&0x0022u16.to_le_bytes());
|
||||
let opt = OPTIONAL;
|
||||
pe[opt..opt + 2].copy_from_slice(&0x020Bu16.to_le_bytes());
|
||||
pe[opt + 16..opt + 20].copy_from_slice(&self.text_rva.to_le_bytes());
|
||||
pe[opt + 24..opt + 32].copy_from_slice(&PREFERRED_BASE.to_le_bytes());
|
||||
pe[opt + 32..opt + 36].copy_from_slice(&0x1000u32.to_le_bytes());
|
||||
pe[opt + 36..opt + 40].copy_from_slice(&0x200u32.to_le_bytes());
|
||||
pe[opt + 56..opt + 60].copy_from_slice(&0x4000u32.to_le_bytes());
|
||||
pe[opt + 60..opt + 64].copy_from_slice(&self.size_of_headers.to_le_bytes());
|
||||
pe[opt + 108..opt + 112].copy_from_slice(&16u32.to_le_bytes());
|
||||
|
||||
let mut section = |i: usize, name: &[u8], rva: u32, size: u32, raw: u32, flags: u32| {
|
||||
let h = opt + OPTIONAL_SIZE + i * 40;
|
||||
pe[h..h + name.len()].copy_from_slice(name);
|
||||
pe[h + 8..h + 12].copy_from_slice(&size.to_le_bytes());
|
||||
pe[h + 12..h + 16].copy_from_slice(&rva.to_le_bytes());
|
||||
pe[h + 16..h + 20]
|
||||
.copy_from_slice(&(if raw == 0 { 0 } else { 0x200u32 }).to_le_bytes());
|
||||
pe[h + 20..h + 24].copy_from_slice(&raw.to_le_bytes());
|
||||
pe[h + 36..h + 40].copy_from_slice(&flags.to_le_bytes());
|
||||
};
|
||||
section(
|
||||
0,
|
||||
b".text",
|
||||
self.text_rva,
|
||||
0x200,
|
||||
self.text_offset,
|
||||
0x6000_0020,
|
||||
);
|
||||
section(1, b".data", self.data_rva, self.data_size, 0, 0xC000_0080);
|
||||
|
||||
let at = self.text_offset as usize;
|
||||
pe[at..at + self.code.len()].copy_from_slice(&self.code);
|
||||
if !self.relocations.is_empty() {
|
||||
// Data directory 5 is the base relocation table.
|
||||
let directory = OPTIONAL + 112 + 5 * 8;
|
||||
pe[directory..directory + 4].copy_from_slice(&(self.text_rva + 0x100).to_le_bytes());
|
||||
pe[directory + 4..directory + 8]
|
||||
.copy_from_slice(&(self.relocations.len() as u32).to_le_bytes());
|
||||
pe[at + 0x100..at + 0x100 + self.relocations.len()].copy_from_slice(&self.relocations);
|
||||
}
|
||||
pe
|
||||
}
|
||||
}
|
||||
|
||||
/// `lea rbx, [rip - (text_rva + 7)]`: the image base, wherever it was loaded.
|
||||
fn base_into_rbx(text_rva: u32) -> Vec<u8> {
|
||||
let mut code = vec![0x48, 0x8D, 0x1D];
|
||||
code.extend((-(text_rva as i32 + 7)).to_le_bytes());
|
||||
code
|
||||
}
|
||||
|
||||
fn run(bytes: &[u8], base: u64) -> StartupResult {
|
||||
let layout = StartupLayout {
|
||||
image_base: base,
|
||||
stack_top: 0x2_0001_0000,
|
||||
tls_base: 0x3_0000_0000,
|
||||
};
|
||||
run_synthetic_startup(bytes, layout, ImportRegistry::new(), 1_000).expect("startup")
|
||||
}
|
||||
|
||||
fn load_error(image: &Image) -> Option<PeError> {
|
||||
let bytes = image.build();
|
||||
let pe = ParsedPe::parse(&bytes).expect("the parser does not judge SizeOfHeaders");
|
||||
pe.load_into_memory(&bytes).err()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_guest_reads_its_own_headers_at_the_preferred_and_at_a_relocated_base() {
|
||||
let mut code = base_into_rbx(0x2000);
|
||||
code.extend([
|
||||
0x0F, 0xB7, 0x03, // movzx eax, word [rbx] DOS signature
|
||||
0x8B, 0x4B, 0x3C, // mov ecx, [rbx + 0x3C] e_lfanew
|
||||
0x8B, 0x14, 0x0B, // mov edx, [rbx + rcx] PE signature
|
||||
0x0F, 0xB7, 0x74, 0x0B, 0x06, // movzx esi, word [rbx + rcx + 6] NumberOfSections
|
||||
0x48, 0x8B, 0x7C, 0x0B, 0x30, // mov rdi, [rbx + rcx + 0x30] ImageBase
|
||||
0xF4, // hlt
|
||||
]);
|
||||
let bytes = Image::new(&code).build();
|
||||
for base in [PREFERRED_BASE, OTHER_BASE] {
|
||||
let result = run(&bytes, base);
|
||||
let cpu = &result.execution.final_state;
|
||||
assert_eq!(result.execution.exit_reason, ExitReason::Halt, "{base:#x}");
|
||||
assert_eq!(cpu.get(Register::Rbx), base, "{base:#x}");
|
||||
assert_eq!(cpu.get(Register::Rax), 0x5A4D, "{base:#x}");
|
||||
assert_eq!(cpu.get(Register::Rcx), u64::from(E_LFANEW), "{base:#x}");
|
||||
assert_eq!(cpu.get(Register::Rdx), 0x0000_4550, "{base:#x}");
|
||||
assert_eq!(cpu.get(Register::Rsi), u64::from(SECTIONS), "{base:#x}");
|
||||
// The mapped header names the base the image is at, not the preferred one.
|
||||
assert_eq!(cpu.get(Register::Rdi), base, "{base:#x}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_mapping_is_the_file_headers_then_zeros_to_the_end_of_the_page() {
|
||||
let mut code = base_into_rbx(0x2000);
|
||||
code.push(0xF4);
|
||||
let bytes = Image::new(&code).build();
|
||||
for base in [PREFERRED_BASE, OTHER_BASE] {
|
||||
let result = run(&bytes, base);
|
||||
let memory = &result.image.memory;
|
||||
let mut page = [0u8; 0x1000];
|
||||
memory.read_bytes(base, &mut page).unwrap();
|
||||
|
||||
let mut wanted = bytes[..0x400].to_vec();
|
||||
wanted[OPTIONAL + 24..OPTIONAL + 32].copy_from_slice(&base.to_le_bytes());
|
||||
assert_eq!(&page[..0x400], wanted.as_slice(), "{base:#x}");
|
||||
assert!(page[0x400..].iter().all(|&byte| byte == 0), "{base:#x}");
|
||||
|
||||
// One page and no more: `.text` starts a page later.
|
||||
assert_eq!(
|
||||
memory.read_u8(base + 0x1000),
|
||||
Err(MemoryError::UnmappedAddress(base + 0x1000)),
|
||||
"{base:#x}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_guest_write_to_the_headers_faults_and_changes_nothing() {
|
||||
let mut code = base_into_rbx(0x2000);
|
||||
code.extend([0xC6, 0x03, 0x00, 0xF4]); // mov byte [rbx], 0; hlt
|
||||
let result = run(&Image::new(&code).build(), OTHER_BASE);
|
||||
assert_eq!(
|
||||
result.execution.exit_reason,
|
||||
ExitReason::MemoryFault(MemoryError::PermissionViolation {
|
||||
address: OTHER_BASE,
|
||||
required: "write",
|
||||
})
|
||||
);
|
||||
assert_eq!(result.image.memory.read_u8(OTHER_BASE), Ok(b'M'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_headers_cannot_be_executed() {
|
||||
let mut code = base_into_rbx(0x2000);
|
||||
code.extend([0xFF, 0xE3]); // jmp rbx
|
||||
let result = run(&Image::new(&code).build(), OTHER_BASE);
|
||||
assert_eq!(
|
||||
result.execution.exit_reason,
|
||||
ExitReason::MemoryFault(MemoryError::PermissionViolation {
|
||||
address: OTHER_BASE,
|
||||
required: "execute",
|
||||
})
|
||||
);
|
||||
assert_eq!(result.execution.final_state.rip, OTHER_BASE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headers_longer_than_a_page_take_whole_pages() {
|
||||
// 0x1001 bytes of headers need two pages, so `.text` must start at 0x2000.
|
||||
let mut image = Image::new(&[0xF4]);
|
||||
image.size_of_headers = 0x1001;
|
||||
image.text_offset = 0x1200;
|
||||
let bytes = image.build();
|
||||
let Ok(loaded) = ParsedPe::parse(&bytes).unwrap().load_into_memory(&bytes) else {
|
||||
panic!("two pages of headers below a section at 0x2000 must load");
|
||||
};
|
||||
let memory = &loaded.memory;
|
||||
assert_eq!(memory.read_u8(PREFERRED_BASE + 0x1000), Ok(bytes[0x1000]));
|
||||
assert_eq!(memory.read_u8(PREFERRED_BASE + 0x1001), Ok(0));
|
||||
assert_eq!(memory.read_u8(PREFERRED_BASE + 0x1FFF), Ok(0));
|
||||
assert_eq!(memory.read_u8(PREFERRED_BASE + 0x2000), Ok(0xF4));
|
||||
|
||||
// With `.text` a page earlier the headers would reach into it.
|
||||
image.text_rva = 0x1000;
|
||||
assert_eq!(load_error(&image), Some(PeError::InvalidHeaderSize));
|
||||
|
||||
// Exactly one page of headers ends where that section starts.
|
||||
image.size_of_headers = 0x1000;
|
||||
assert_eq!(load_error(&image), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_size_that_cannot_be_mapped_is_refused() {
|
||||
let mut image = Image::new(&[0xF4]);
|
||||
image.size_of_headers = 0;
|
||||
assert_eq!(load_error(&image), Some(PeError::InvalidHeaderSize));
|
||||
|
||||
// One byte short of the section table, then exactly the section table.
|
||||
image.size_of_headers = TABLE_END - 1;
|
||||
assert_eq!(load_error(&image), Some(PeError::InvalidHeaderSize));
|
||||
image.size_of_headers = TABLE_END;
|
||||
assert_eq!(load_error(&image), None);
|
||||
|
||||
// The file is 0x600 bytes: exactly that, then one byte more.
|
||||
image.size_of_headers = 0x600;
|
||||
assert_eq!(load_error(&image), None);
|
||||
image.size_of_headers = 0x601;
|
||||
assert_eq!(load_error(&image), Some(PeError::InvalidHeaderSize));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_section_inside_the_header_page_is_not_an_overlap() {
|
||||
// A section that maps nothing has no range to collide with.
|
||||
let mut image = Image::new(&[0xF4]);
|
||||
image.data_rva = 0x200;
|
||||
image.data_size = 0;
|
||||
assert_eq!(load_error(&image), None);
|
||||
|
||||
image.data_size = 1;
|
||||
assert_eq!(load_error(&image), Some(PeError::InvalidHeaderSize));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loading_with_bytes_shorter_than_the_headers_is_an_error_not_a_panic() {
|
||||
let bytes = Image::new(&[0xF4]).build();
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
for len in [0, 0x3F, OPTIONAL, TABLE_END as usize, 0x3FF] {
|
||||
assert_eq!(
|
||||
pe.load_into_memory(&bytes[..len]).err(),
|
||||
Some(PeError::InvalidHeaderSize),
|
||||
"{len:#x}"
|
||||
);
|
||||
}
|
||||
|
||||
// Other bytes of the right length, whose own headers leave no room for the
|
||||
// `ImageBase` field inside the size that was parsed.
|
||||
let mut image = Image::new(&[0xF4]);
|
||||
image.size_of_headers = OPTIONAL as u32 + 8;
|
||||
let bytes = image.build();
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
let mut other = bytes.clone();
|
||||
let coff = E_LFANEW as usize + 4;
|
||||
other[coff + 2..coff + 4].copy_from_slice(&0u16.to_le_bytes());
|
||||
other[coff + 16..coff + 18].copy_from_slice(&0u16.to_le_bytes());
|
||||
assert_eq!(
|
||||
pe.load_into_memory(&other).err(),
|
||||
Some(PeError::InvalidHeaderSize)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_reports_the_refusal() {
|
||||
let mut image = Image::new(&[0xF4]);
|
||||
image.size_of_headers = 0;
|
||||
let layout = StartupLayout {
|
||||
image_base: OTHER_BASE,
|
||||
stack_top: 0x2_0001_0000,
|
||||
tls_base: 0x3_0000_0000,
|
||||
};
|
||||
let error = run_synthetic_startup(&image.build(), layout, ImportRegistry::new(), 1_000)
|
||||
.err()
|
||||
.expect("refused");
|
||||
assert_eq!(error.to_string(), PeError::InvalidHeaderSize.to_string());
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"the PE headers cannot be mapped: SizeOfHeaders is zero, shorter than the section table, \
|
||||
longer than the file or reaches into a section, or the bytes do not match the parsed \
|
||||
headers"
|
||||
);
|
||||
}
|
||||
|
||||
/// One base relocation block: `IMAGE_REL_BASED_DIR64` entries for the given
|
||||
/// offsets in the page at `page_rva`, padded to a multiple of four bytes.
|
||||
fn dir64_block(page_rva: u32, offsets: &[u16]) -> Vec<u8> {
|
||||
let mut entries: Vec<u16> = offsets.iter().map(|offset| 0xA000 | offset).collect();
|
||||
if entries.len() % 2 == 1 {
|
||||
entries.push(0); // IMAGE_REL_BASED_ABSOLUTE padding
|
||||
}
|
||||
let mut block = page_rva.to_le_bytes().to_vec();
|
||||
block.extend((8 + 2 * entries.len() as u32).to_le_bytes());
|
||||
for entry in entries {
|
||||
block.extend(entry.to_le_bytes());
|
||||
}
|
||||
block
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_relocation_aimed_at_image_base_does_not_move_it_twice() {
|
||||
// The image carries two DIR64 entries: one for the `ImageBase` field in the
|
||||
// headers, and one for a pointer in `.text` so the table is seen to apply.
|
||||
let mut code = base_into_rbx(0x2000);
|
||||
code.extend([
|
||||
0x8B, 0x4B, 0x3C, // mov ecx, [rbx + 0x3C]
|
||||
0x48, 0x8B, 0x7C, 0x0B, 0x30, // mov rdi, [rbx + rcx + 0x30] ImageBase
|
||||
// mov rax, [rip + 0x2A]: the pointer at 0x2040
|
||||
0x48, 0x8B, 0x05, 0x2A, 0x00, 0x00, 0x00, 0xF4, // hlt
|
||||
]);
|
||||
// The load ends 0x16 bytes into the code, and 0x16 + 0x2A is 0x40.
|
||||
assert_eq!(code.len(), 0x17);
|
||||
code.resize(0x40, 0x90);
|
||||
code.extend((PREFERRED_BASE + 0x2040).to_le_bytes());
|
||||
let mut image = Image::new(&code);
|
||||
image.relocations = dir64_block(0, &[OPTIONAL as u16 + 24]);
|
||||
image.relocations.extend(dir64_block(0x2000, &[0x40]));
|
||||
let bytes = image.build();
|
||||
|
||||
for base in [PREFERRED_BASE, OTHER_BASE] {
|
||||
let result = run(&bytes, base);
|
||||
assert_eq!(result.execution.exit_reason, ExitReason::Halt, "{base:#x}");
|
||||
// Nothing is applied when the image is already at its preferred base.
|
||||
let applied = if base == PREFERRED_BASE { 0 } else { 2 };
|
||||
assert_eq!(result.relocations.applied_dir64, applied, "{base:#x}");
|
||||
let cpu = &result.execution.final_state;
|
||||
assert_eq!(cpu.get(Register::Rax), base + 0x2040, "{base:#x}");
|
||||
// Not the preferred base, and not the load base plus the delta again.
|
||||
assert_eq!(cpu.get(Register::Rdi), base, "{base:#x}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bytes_that_are_not_the_parsed_headers_are_refused() {
|
||||
let bytes = Image::new(&[0xF4]).build();
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
let coff = E_LFANEW as usize + 4;
|
||||
let refused = |change: &dyn Fn(&mut Vec<u8>)| {
|
||||
let mut other = bytes.clone();
|
||||
change(&mut other);
|
||||
pe.load_into_memory(&other).err()
|
||||
};
|
||||
assert_eq!(refused(&|_| {}), None);
|
||||
|
||||
// An optional header declared empty: the section table would start where
|
||||
// the optional header is, and `ImageBase` would be patched inside it.
|
||||
assert_eq!(
|
||||
refused(&|b| b[coff + 16..coff + 18].copy_from_slice(&0u16.to_le_bytes())),
|
||||
Some(PeError::InvalidHeaderSize)
|
||||
);
|
||||
// One byte short of the PE32+ fields the loader relies on.
|
||||
assert_eq!(
|
||||
refused(&|b| b[coff + 16..coff + 18].copy_from_slice(&111u16.to_le_bytes())),
|
||||
Some(PeError::InvalidHeaderSize)
|
||||
);
|
||||
// Not a PE32+ optional header.
|
||||
assert_eq!(
|
||||
refused(&|b| b[OPTIONAL..OPTIONAL + 2].copy_from_slice(&0x010Bu16.to_le_bytes())),
|
||||
Some(PeError::InvalidHeaderSize)
|
||||
);
|
||||
// A different section count, preferred base or header size.
|
||||
assert_eq!(
|
||||
refused(&|b| b[coff + 2..coff + 4].copy_from_slice(&1u16.to_le_bytes())),
|
||||
Some(PeError::InvalidHeaderSize)
|
||||
);
|
||||
assert_eq!(
|
||||
refused(&|b| b[OPTIONAL + 24] ^= 1),
|
||||
Some(PeError::InvalidHeaderSize)
|
||||
);
|
||||
assert_eq!(
|
||||
refused(&|b| b[OPTIONAL + 60..OPTIONAL + 64].copy_from_slice(&0x200u32.to_le_bytes())),
|
||||
Some(PeError::InvalidHeaderSize)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headers_over_the_mapping_budget_are_refused() {
|
||||
// 256 MiB of headers and one more page. The file really is that long, so
|
||||
// only the budget stands between this image and a mapping of that size.
|
||||
const BUDGET: u32 = 256 * 1024 * 1024;
|
||||
let mut image = Image::new(&[0xF4]);
|
||||
image.size_of_headers = BUDGET + 0x1000;
|
||||
image.text_offset = BUDGET + 0x1000;
|
||||
image.text_rva = BUDGET + 0x1000;
|
||||
image.data_rva = BUDGET + 0x2000;
|
||||
assert_eq!(
|
||||
load_error(&image),
|
||||
Some(PeError::SectionMappingError(MemoryError::AllocationFailed))
|
||||
);
|
||||
}
|
||||
@@ -4,11 +4,14 @@
|
||||
//!
|
||||
//! A section's mapped size is max(VirtualSize, SizeOfRawData) and the loader
|
||||
//! backs it with zero-filled host memory, so a small file can request a large
|
||||
//! allocation. The loader's documented budget is 256 MiB per image.
|
||||
//! allocation. The loader's documented budget is 256 MiB per image, and the
|
||||
//! page of headers mapped at the image base (#333) counts toward it.
|
||||
|
||||
use xenora_loader::{MemoryError, ParsedPe, PeError};
|
||||
|
||||
const BUDGET: u32 = 256 * 1024 * 1024;
|
||||
/// The image's 0x200 bytes of headers are mapped as one 4 KiB page.
|
||||
const HEADERS: u32 = 0x1000;
|
||||
|
||||
/// An original synthetic image: one 0x200-byte code section at RVA 0x1000 followed by
|
||||
/// uninitialized sections (no raw data) of the given virtual sizes, packed back to back.
|
||||
@@ -25,6 +28,8 @@ fn build(bss_sizes: &[u32]) -> Vec<u8> {
|
||||
pe[opt..opt + 2].copy_from_slice(&0x020Bu16.to_le_bytes());
|
||||
pe[opt + 16..opt + 20].copy_from_slice(&0x1000u32.to_le_bytes());
|
||||
pe[opt + 24..opt + 32].copy_from_slice(&0x1_4000_0000u64.to_le_bytes());
|
||||
// SizeOfHeaders: everything before the code's raw data.
|
||||
pe[opt + 60..opt + 64].copy_from_slice(&0x200u32.to_le_bytes());
|
||||
|
||||
let mut section = |i: usize, va: u32, vsize: u32, raw: u32, flags: u32| {
|
||||
let h = opt + 112 + i * 40;
|
||||
@@ -56,14 +61,14 @@ fn small_image_loads() {
|
||||
|
||||
#[test]
|
||||
fn image_exactly_at_budget_loads() {
|
||||
let bytes = build(&[BUDGET - 0x200]);
|
||||
let bytes = build(&[BUDGET - HEADERS - 0x200]);
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
assert!(pe.load_into_memory(&bytes).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_byte_over_budget_is_rejected() {
|
||||
let bytes = build(&[BUDGET - 0x1FF]);
|
||||
let bytes = build(&[BUDGET - HEADERS - 0x1FF]);
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,540 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Process exit (issue #329): `ExitProcess`, a returning entry point, and the
|
||||
//! rule that an exited guest runs nothing further.
|
||||
//!
|
||||
//! Expected behaviour is from the public Win32 documentation for
|
||||
//! `ExitProcess` (processthreadsapi.h): it does not return, the status is a
|
||||
//! `UINT`, and the process's handles are closed. The guest code is original.
|
||||
|
||||
mod support;
|
||||
|
||||
use std::sync::Arc;
|
||||
use support::*;
|
||||
use xenora_loader::cpu::{CpuState, ExitReason};
|
||||
use xenora_loader::import_table::ImportName;
|
||||
use xenora_loader::imports::{ENTRY_RETURN, ImportRegistry, RETURN_SENTINEL_PAGE, Win64Args};
|
||||
use xenora_loader::memory::{GuestMemory, MemoryError, MemoryPermissions};
|
||||
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
|
||||
use xenora_loader::startup::{StartupLayout, run_synthetic_startup};
|
||||
|
||||
const KERNEL32: &str = "kernel32.dll";
|
||||
const THREADS: &str = "api-ms-win-core-processthreads-l1-1-0.dll";
|
||||
const UCRT: &str = "ucrtbase.dll";
|
||||
|
||||
const IMPORTS: &[(&str, &str)] = &[
|
||||
(KERNEL32, "ExitProcess"),
|
||||
(KERNEL32, "SetLastError"),
|
||||
(KERNEL32, "CreateFileW"),
|
||||
(KERNEL32, "CreateEventW"),
|
||||
(UCRT, "qsort"),
|
||||
("ws2_32.dll", "WSAStartup"),
|
||||
("ws2_32.dll", "socket"),
|
||||
("xgameruntime.dll", "XTaskQueueCreate"),
|
||||
];
|
||||
const ALIAS: &[(&str, &str)] = &[(THREADS, "ExitProcess")];
|
||||
|
||||
/// Guest address of the stub `call [slot]; hlt` for import `index`.
|
||||
fn stub(index: usize) -> u64 {
|
||||
BASE + u64::from(CODE_RVA) + 16 * index as u64
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_process_stops_the_guest_with_its_whole_status() {
|
||||
// The status is a 32-bit UINT: values above 255 survive, and the upper
|
||||
// half of RCX is not part of it.
|
||||
for (argument, status) in [
|
||||
(0, 0),
|
||||
(1, 1),
|
||||
(150, 150),
|
||||
(0x1234_5678, 0x1234_5678),
|
||||
(0xFFFF_FFFF, 0xFFFF_FFFF),
|
||||
(0xAAAA_BBBB_0000_002A, 0x2A),
|
||||
] {
|
||||
for imports in [IMPORTS, ALIAS] {
|
||||
let mut guest = Guest::new(imports, &[]);
|
||||
assert_eq!(guest.state.exit_status(), None);
|
||||
// The stub is `call [ExitProcess]; hlt`. A service that returned
|
||||
// would reach the HLT and report Halt.
|
||||
let (_, exit) = guest.run("ExitProcess", &[argument]);
|
||||
assert_eq!(exit, ExitReason::ProcessExit(status), "{argument:#x}");
|
||||
assert_eq!(guest.state.exit_status(), Some(status), "{argument:#x}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exited_guest_runs_nothing_further() {
|
||||
let mut guest = Guest::new(IMPORTS, &[]);
|
||||
assert_eq!(guest.run("ExitProcess", &[3]).1, ExitReason::ProcessExit(3));
|
||||
// Neither another service nor a second exit takes effect: the engine
|
||||
// reports the first exit again without executing anything.
|
||||
for (symbol, argument) in [("SetLastError", 5), ("ExitProcess", 9)] {
|
||||
let (_, exit) = guest.run(symbol, &[argument]);
|
||||
assert_eq!(exit, ExitReason::ProcessExit(3), "{symbol}");
|
||||
}
|
||||
assert_eq!(guest.state.last_error(THREAD_A), 0);
|
||||
assert_eq!(guest.state.exit_status(), Some(3));
|
||||
}
|
||||
|
||||
/// Under the guest thread scheduler the engine runs in slices. A process exit
|
||||
/// from the scheduled main thread stops the schedule with that exit as its
|
||||
/// reason, and sets the engine's exit latch through the sliced entry point, so
|
||||
/// nothing runs afterwards. The scheduler has no outcome of its own for a
|
||||
/// process exit and reports it as the reason of a `Fault`.
|
||||
#[test]
|
||||
fn exit_process_under_the_scheduler_ends_the_run() {
|
||||
use xenora_loader::scheduler::Outcome;
|
||||
for quantum in [1, 64, 1_000_000] {
|
||||
let mut guest = Guest::new(IMPORTS, &[]);
|
||||
assert_ne!(guest.call("CreateEventW", &[0, 1, 0, 0]), 0);
|
||||
let report = guest.scheduled("ExitProcess", &[0xAAAA_BBBB_0000_0015], quantum, 10_000);
|
||||
assert!(
|
||||
matches!(
|
||||
report.outcome,
|
||||
Outcome::Fault {
|
||||
reason: ExitReason::ProcessExit(0x15),
|
||||
..
|
||||
}
|
||||
),
|
||||
"quantum {quantum}: {:?}",
|
||||
report.outcome
|
||||
);
|
||||
assert_eq!(guest.state.exit_status(), Some(0x15));
|
||||
assert_eq!(guest.state.open_handle_count(), 0);
|
||||
// The engine is latched: an unsliced run executes nothing either.
|
||||
let (_, exit) = guest.run("SetLastError", &[5]);
|
||||
assert_eq!(exit, ExitReason::ProcessExit(0x15), "quantum {quantum}");
|
||||
assert_eq!(guest.state.last_error(THREAD_A), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_exit_decides_the_status() {
|
||||
// Two calls of the service itself, with no engine in between to stop the
|
||||
// second one.
|
||||
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0))));
|
||||
let mut registry = ImportRegistry::new();
|
||||
register_standard_services(&mut registry, Arc::clone(&state));
|
||||
let exit = ®istry
|
||||
.resolve(KERNEL32, &ImportName::Name("ExitProcess".into()))
|
||||
.expect("ExitProcess is registered")
|
||||
.handler;
|
||||
let mut cpu = CpuState::new(0, 0);
|
||||
let mut memory = GuestMemory::new();
|
||||
for status in [41, 42] {
|
||||
let mut args = Win64Args::new(&cpu);
|
||||
args.rcx = status;
|
||||
assert_eq!(
|
||||
exit(&args, &mut cpu, &mut memory),
|
||||
Err(ExitReason::ProcessExit(41))
|
||||
);
|
||||
}
|
||||
assert_eq!(state.exit_status(), Some(41));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_from_inside_a_service_callback_ends_the_process() {
|
||||
// A comparator for qsort that exits instead of comparing:
|
||||
// sub rsp, 0x28
|
||||
// mov ecx, 9
|
||||
// call <ExitProcess stub>
|
||||
// mov byte ptr [SCRATCH], 1 ; must never run
|
||||
// add rsp, 0x28
|
||||
// ret
|
||||
let call_end = routine(0) + 14;
|
||||
let displacement = (stub(0).wrapping_sub(call_end) as u32).to_le_bytes();
|
||||
let mut comparator = vec![0x48, 0x83, 0xEC, 0x28, 0xB9, 9, 0, 0, 0, 0xE8];
|
||||
comparator.extend(displacement);
|
||||
comparator.extend([0xC6, 0x04, 0x25]);
|
||||
comparator.extend((SCRATCH as u32).to_le_bytes());
|
||||
comparator.extend([0x01, 0x48, 0x83, 0xC4, 0x28, 0xC3]);
|
||||
|
||||
let mut guest = Guest::new(IMPORTS, &[comparator]);
|
||||
let items = SCRATCH + 0x100;
|
||||
guest.memory.write_u64(items, 2).unwrap();
|
||||
guest.memory.write_u64(items + 8, 1).unwrap();
|
||||
let (_, exit) = guest.run("qsort", &[items, 2, 8, routine(0)]);
|
||||
assert_eq!(exit, ExitReason::ProcessExit(9));
|
||||
assert_eq!(guest.memory.read_u8(SCRATCH).unwrap(), 0);
|
||||
// The sort never resumed, so the items are as the guest left them.
|
||||
assert_eq!((guest.u64_at(items), guest.u64_at(items + 8)), (2, 1));
|
||||
assert_eq!(guest.state.exit_status(), Some(9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_closes_every_handle_and_keeps_the_files() {
|
||||
let mut guest = Guest::new(IMPORTS, &[]);
|
||||
let name: Vec<u8> = "C:\\exit.bin\0"
|
||||
.encode_utf16()
|
||||
.flat_map(u16::to_le_bytes)
|
||||
.collect();
|
||||
guest.memory.write_bytes(SCRATCH, &name).unwrap();
|
||||
// CreateFileW(name, GENERIC_READ | GENERIC_WRITE, no sharing, null,
|
||||
// CREATE_ALWAYS, 0, null) and an unnamed event.
|
||||
let file = guest.call("CreateFileW", &[SCRATCH, 0xC000_0000, 0, 0, 2, 0, 0]);
|
||||
assert_ne!(file, u64::MAX);
|
||||
assert_ne!(guest.call("CreateEventW", &[0, 1, 0, 0]), 0);
|
||||
assert_eq!(guest.state.open_handle_count(), 2);
|
||||
|
||||
// Sockets and task queues live in tables of their own. WSAStartup(2.2),
|
||||
// two UDP sockets, and XTaskQueueCreate(manual, manual, &handle).
|
||||
assert_eq!(guest.call("WSAStartup", &[0x0202, SCRATCH + 0x200]), 0);
|
||||
let first = guest.call("socket", &[2, 2, 17]);
|
||||
let second = guest.call("socket", &[2, 2, 17]);
|
||||
assert!(first != u64::MAX && second != u64::MAX && first != second);
|
||||
assert_eq!(guest.state.open_handle_count(), 4);
|
||||
assert_eq!(guest.call("XTaskQueueCreate", &[0, 0, SCRATCH + 0x400]), 0);
|
||||
assert_ne!(guest.u64_at(SCRATCH + 0x400), 0);
|
||||
assert_eq!(guest.state.open_handle_count(), 5);
|
||||
|
||||
assert_eq!(guest.run("ExitProcess", &[0]).1, ExitReason::ProcessExit(0));
|
||||
assert_eq!(guest.state.open_handle_count(), 0);
|
||||
// The drive is not the process: the file it created is still there.
|
||||
assert_eq!(guest.state.file_contents("C:\\exit.bin"), Some(Vec::new()));
|
||||
assert_eq!(guest.state.file_contents("C:\\absent.bin"), None);
|
||||
}
|
||||
|
||||
/// A PE32+ image with one executable section and no imports whose entry
|
||||
/// point is `mov eax, status; ret`.
|
||||
fn returning_image(status: u32) -> Vec<u8> {
|
||||
let mut pe = vec![0u8; 0x400];
|
||||
let mut put = |at: usize, bytes: &[u8]| pe[at..at + bytes.len()].copy_from_slice(bytes);
|
||||
put(0, b"MZ");
|
||||
put(0x3C, &0x80u32.to_le_bytes());
|
||||
put(0x80, b"PE\0\0");
|
||||
put(0x84, &0x8664u16.to_le_bytes()); // AMD64
|
||||
put(0x86, &1u16.to_le_bytes()); // one section
|
||||
put(0x94, &240u16.to_le_bytes()); // optional header size
|
||||
put(0x96, &0x0022u16.to_le_bytes()); // executable, large-address-aware
|
||||
let optional = 0x98;
|
||||
put(optional, &0x20Bu16.to_le_bytes()); // PE32+
|
||||
put(optional + 16, &0x1000u32.to_le_bytes()); // entry point
|
||||
put(optional + 24, &0x1_4000_0000u64.to_le_bytes()); // image base
|
||||
put(optional + 32, &0x1000u32.to_le_bytes()); // section alignment
|
||||
put(optional + 36, &0x200u32.to_le_bytes()); // file alignment
|
||||
put(optional + 56, &0x2000u32.to_le_bytes()); // size of image
|
||||
put(optional + 60, &0x200u32.to_le_bytes()); // size of headers
|
||||
put(optional + 108, &16u32.to_le_bytes()); // data directories
|
||||
let section = optional + 240;
|
||||
put(section, b".text");
|
||||
put(section + 8, &0x200u32.to_le_bytes()); // virtual size
|
||||
put(section + 12, &0x1000u32.to_le_bytes()); // RVA
|
||||
put(section + 16, &0x200u32.to_le_bytes()); // raw size
|
||||
put(section + 20, &0x200u32.to_le_bytes()); // raw offset
|
||||
put(section + 36, &0x6000_0020u32.to_le_bytes()); // code, execute, read
|
||||
put(0x200, &[0xB8]);
|
||||
put(0x201, &status.to_le_bytes());
|
||||
put(0x205, &[0xC3]);
|
||||
pe
|
||||
}
|
||||
|
||||
fn layout() -> StartupLayout {
|
||||
StartupLayout {
|
||||
image_base: 0x1_4000_0000,
|
||||
stack_top: 0x2_0001_0000,
|
||||
tls_base: 0x3_0000_0000,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_returning_entry_point_exits_with_eax() {
|
||||
// With no ExitProcess registered the return still ends the process.
|
||||
let bare = run_synthetic_startup(
|
||||
&returning_image(0x1234_5678),
|
||||
layout(),
|
||||
ImportRegistry::new(),
|
||||
100,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
bare.execution.exit_reason,
|
||||
ExitReason::ProcessExit(0x1234_5678)
|
||||
);
|
||||
// `mov eax, imm32` and `ret`, then nothing.
|
||||
assert_eq!(bare.execution.instructions_executed, 2);
|
||||
|
||||
// With the standard services it goes through ExitProcess, so the status
|
||||
// is recorded where a host can read it.
|
||||
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0))));
|
||||
let mut registry = ImportRegistry::new();
|
||||
register_standard_services(&mut registry, Arc::clone(&state));
|
||||
let standard = run_synthetic_startup(&returning_image(77), layout(), registry, 100).unwrap();
|
||||
assert_eq!(standard.execution.exit_reason, ExitReason::ProcessExit(77));
|
||||
assert_eq!(state.exit_status(), Some(77));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Exit before the entry point, and the reserved return addresses
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const IMAGE_BASE: u64 = 0x1_4000_0000;
|
||||
const ENTRY_RVA: u32 = 0x1000;
|
||||
/// TLS callback `n` is at this RVA plus 0x20 for each one before it.
|
||||
const CALLBACK_RVA: u32 = 0x1040;
|
||||
const IAT_RVA: u32 = 0x2070;
|
||||
/// One byte per marker: a routine that ran sets its own to 1.
|
||||
const MARKER_RVA: u32 = 0x2100;
|
||||
|
||||
/// A PE32+ image that imports one kernel32 function. `entry` is its entry
|
||||
/// point and each of `callbacks` is a TLS callback.
|
||||
fn image(symbol: &str, entry: &[u8], callbacks: &[Vec<u8>]) -> Vec<u8> {
|
||||
assert!(entry.len() <= 0x40 && callbacks.len() <= 4);
|
||||
let mut pe = vec![0u8; 0x600];
|
||||
let mut put = |at: usize, bytes: &[u8]| pe[at..at + bytes.len()].copy_from_slice(bytes);
|
||||
put(0, b"MZ");
|
||||
put(0x3C, &0x80u32.to_le_bytes());
|
||||
put(0x80, b"PE\0\0");
|
||||
put(0x84, &0x8664u16.to_le_bytes());
|
||||
put(0x86, &2u16.to_le_bytes());
|
||||
put(0x94, &240u16.to_le_bytes());
|
||||
put(0x96, &0x0022u16.to_le_bytes());
|
||||
let optional = 0x98;
|
||||
put(optional, &0x20Bu16.to_le_bytes());
|
||||
put(optional + 16, &ENTRY_RVA.to_le_bytes());
|
||||
put(optional + 24, &IMAGE_BASE.to_le_bytes());
|
||||
put(optional + 32, &0x1000u32.to_le_bytes());
|
||||
put(optional + 36, &0x200u32.to_le_bytes());
|
||||
put(optional + 56, &0x3000u32.to_le_bytes());
|
||||
put(optional + 60, &0x200u32.to_le_bytes());
|
||||
put(optional + 108, &16u32.to_le_bytes());
|
||||
// Data directory 1: imports. Data directory 9: TLS.
|
||||
put(optional + 120, &0x2000u32.to_le_bytes());
|
||||
put(optional + 124, &0x28u32.to_le_bytes());
|
||||
if !callbacks.is_empty() {
|
||||
put(optional + 184, &0x2080u32.to_le_bytes());
|
||||
put(optional + 188, &40u32.to_le_bytes());
|
||||
}
|
||||
for (index, (name, rva, raw, flags)) in [
|
||||
(b".text", 0x1000u32, 0x200u32, 0x6000_0020u32),
|
||||
(b".data", 0x2000, 0x400, 0xC000_0040),
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let section = optional + 240 + 40 * index;
|
||||
put(section, name);
|
||||
put(section + 8, &0x200u32.to_le_bytes());
|
||||
put(section + 12, &rva.to_le_bytes());
|
||||
put(section + 16, &0x200u32.to_le_bytes());
|
||||
put(section + 20, &raw.to_le_bytes());
|
||||
put(section + 36, &flags.to_le_bytes());
|
||||
}
|
||||
// `.data`, at file offset 0x400: the import descriptor, its strings, the
|
||||
// lookup table and the address table.
|
||||
let data = |rva: u32| 0x400 + (rva - 0x2000) as usize;
|
||||
put(data(0x2000), &0x2060u32.to_le_bytes()); // lookup table
|
||||
put(data(0x200C), &0x2040u32.to_le_bytes()); // DLL name
|
||||
put(data(0x2010), &IAT_RVA.to_le_bytes());
|
||||
put(data(0x2040), KERNEL32.as_bytes());
|
||||
put(data(0x2052), symbol.as_bytes());
|
||||
put(data(0x2060), &0x2050u64.to_le_bytes());
|
||||
put(data(IAT_RVA), &0x2050u64.to_le_bytes());
|
||||
if !callbacks.is_empty() {
|
||||
// The TLS directory: no template, an index slot, and the callbacks.
|
||||
put(data(0x2080) + 16, &(IMAGE_BASE + 0x20C0).to_le_bytes());
|
||||
put(data(0x2080) + 24, &(IMAGE_BASE + 0x20D0).to_le_bytes());
|
||||
}
|
||||
for (index, code) in callbacks.iter().enumerate() {
|
||||
assert!(code.len() <= 0x20);
|
||||
let rva = CALLBACK_RVA + 0x20 * index as u32;
|
||||
put(
|
||||
data(0x20D0) + 8 * index,
|
||||
&(IMAGE_BASE + u64::from(rva)).to_le_bytes(),
|
||||
);
|
||||
put(0x200 + (rva - 0x1000) as usize, code);
|
||||
}
|
||||
put(0x200, entry);
|
||||
pe
|
||||
}
|
||||
|
||||
/// `mov byte [marker], 1`, for code that starts at `rva`.
|
||||
fn set_marker(rva: u32, marker: u32) -> Vec<u8> {
|
||||
let mut code = vec![0xC6, 0x05];
|
||||
code.extend((MARKER_RVA + marker - (rva + 7)).to_le_bytes());
|
||||
code.push(1);
|
||||
code
|
||||
}
|
||||
|
||||
/// `mov ecx, status; call [import]; hlt`, for code that starts at `rva`.
|
||||
fn call_import_with(rva: u32, status: u32) -> Vec<u8> {
|
||||
let mut code = vec![0xB9];
|
||||
code.extend(status.to_le_bytes());
|
||||
code.extend([0xFF, 0x15]);
|
||||
code.extend((IAT_RVA - (rva + 11)).to_le_bytes());
|
||||
code.push(0xF4);
|
||||
code
|
||||
}
|
||||
|
||||
fn then(mut code: Vec<u8>, last: u8) -> Vec<u8> {
|
||||
code.push(last);
|
||||
code
|
||||
}
|
||||
|
||||
const RET: u8 = 0xC3;
|
||||
const HLT: u8 = 0xF4;
|
||||
|
||||
struct Started {
|
||||
result: xenora_loader::startup::StartupResult,
|
||||
state: Arc<ServicesState>,
|
||||
}
|
||||
|
||||
impl Started {
|
||||
fn markers(&self) -> [u8; 3] {
|
||||
let mut markers = [0; 3];
|
||||
self.result
|
||||
.image
|
||||
.memory
|
||||
.read_bytes(IMAGE_BASE + u64::from(MARKER_RVA), &mut markers)
|
||||
.unwrap();
|
||||
markers
|
||||
}
|
||||
}
|
||||
|
||||
fn start(bytes: &[u8]) -> Result<Started, String> {
|
||||
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0))));
|
||||
let mut registry = ImportRegistry::new();
|
||||
register_standard_services(&mut registry, Arc::clone(&state));
|
||||
run_synthetic_startup(bytes, layout(), registry, 1_000)
|
||||
.map(|result| Started { result, state })
|
||||
.map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_in_a_tls_callback_is_an_exit_and_nothing_after_it_runs() {
|
||||
// Markers: 0 and 1 for the two callbacks, 2 for the entry point.
|
||||
let entry = then(set_marker(ENTRY_RVA, 2), HLT);
|
||||
let first = CALLBACK_RVA;
|
||||
let second = CALLBACK_RVA + 0x20;
|
||||
|
||||
// Control: no callback exits. Both run, then the entry point.
|
||||
let quiet = start(&image(
|
||||
"ExitProcess",
|
||||
&entry,
|
||||
&[
|
||||
then(set_marker(first, 0), RET),
|
||||
then(set_marker(second, 1), RET),
|
||||
],
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(quiet.result.execution.exit_reason, ExitReason::Halt);
|
||||
assert_eq!(quiet.result.tls_callbacks, 2);
|
||||
assert_eq!(quiet.markers(), [1, 1, 1]);
|
||||
assert_eq!(quiet.state.exit_status(), None);
|
||||
|
||||
// The first callback exits: the second and the entry point never run.
|
||||
let early = start(&image(
|
||||
"ExitProcess",
|
||||
&entry,
|
||||
&[
|
||||
call_import_with(first, 77),
|
||||
then(set_marker(second, 1), RET),
|
||||
],
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
early.result.execution.exit_reason,
|
||||
ExitReason::ProcessExit(77)
|
||||
);
|
||||
assert_eq!(early.result.execution.instructions_executed, 0);
|
||||
assert_eq!(early.result.tls_callbacks, 0);
|
||||
assert_eq!(early.markers(), [0, 0, 0]);
|
||||
assert_eq!(early.state.exit_status(), Some(77));
|
||||
|
||||
// The second callback exits: the first finished, the entry point never runs.
|
||||
let late = start(&image(
|
||||
"ExitProcess",
|
||||
&entry,
|
||||
&[
|
||||
then(set_marker(first, 0), RET),
|
||||
call_import_with(second, 0x1_0002),
|
||||
],
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
late.result.execution.exit_reason,
|
||||
ExitReason::ProcessExit(0x1_0002)
|
||||
);
|
||||
assert_eq!(late.result.tls_callbacks, 1);
|
||||
assert_eq!(late.markers(), [1, 0, 0]);
|
||||
assert_eq!(late.state.exit_status(), Some(0x1_0002));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fault_in_a_tls_callback_is_still_a_startup_error() {
|
||||
let entry = then(set_marker(ENTRY_RVA, 2), HLT);
|
||||
let error = start(&image("ExitProcess", &entry, &[vec![HLT]]))
|
||||
.err()
|
||||
.expect("a callback that halts is a fault");
|
||||
assert_eq!(
|
||||
error,
|
||||
"fault during TLS callback execution: guest executed HLT"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_over_the_reserved_return_addresses_is_refused() {
|
||||
// The entry point of this image would be exactly the address that means
|
||||
// "the entry point returned". Unreserved, the engine would report an exit
|
||||
// with status 0 before running one instruction of it.
|
||||
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0))));
|
||||
let mut registry = ImportRegistry::new();
|
||||
register_standard_services(&mut registry, Arc::clone(&state));
|
||||
let over = StartupLayout {
|
||||
image_base: ENTRY_RETURN - u64::from(ENTRY_RVA),
|
||||
..layout()
|
||||
};
|
||||
let error = run_synthetic_startup(&returning_image(5), over, registry, 100)
|
||||
.err()
|
||||
.expect("refused")
|
||||
.to_string();
|
||||
assert_eq!(
|
||||
error,
|
||||
format!("overlapping memory region: base 0x{RETURN_SENTINEL_PAGE:016x}, size 0x1000")
|
||||
);
|
||||
assert_eq!(state.exit_status(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_guest_cannot_map_the_reserved_return_addresses() {
|
||||
// The page is there after startup, and nothing can read, write or run it.
|
||||
let mut started = start(&image("ExitProcess", &[HLT], &[])).unwrap();
|
||||
let memory = &mut started.result.image.memory;
|
||||
assert!(matches!(
|
||||
memory.read_u8(ENTRY_RETURN),
|
||||
Err(MemoryError::PermissionViolation { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
memory.map_region(RETURN_SENTINEL_PAGE, 0x1000, MemoryPermissions::READ_WRITE),
|
||||
Err(MemoryError::OverlappingRegion { .. })
|
||||
));
|
||||
|
||||
// The entry point calls VirtualAlloc(address, 0x1000, MEM_COMMIT |
|
||||
// MEM_RESERVE, PAGE_READWRITE) and returns 1 if it got a null pointer.
|
||||
let allocate_at = |address: u64| {
|
||||
let mut code = vec![0x48, 0xB9]; // mov rcx, address
|
||||
code.extend(address.to_le_bytes());
|
||||
code.extend([0xBA, 0x00, 0x10, 0x00, 0x00]); // mov edx, 0x1000
|
||||
code.extend([0x41, 0xB8, 0x00, 0x30, 0x00, 0x00]); // mov r8d, 0x3000
|
||||
code.extend([0x41, 0xB9, 0x04, 0x00, 0x00, 0x00]); // mov r9d, 4
|
||||
code.extend([0x48, 0x83, 0xEC, 0x28]); // sub rsp, 0x28
|
||||
code.extend([0xFF, 0x15]); // call [VirtualAlloc]
|
||||
code.extend((IAT_RVA - (ENTRY_RVA + code.len() as u32 + 4)).to_le_bytes());
|
||||
code.extend([0x48, 0x83, 0xC4, 0x28]); // add rsp, 0x28
|
||||
code.extend([0x48, 0x85, 0xC0]); // test rax, rax
|
||||
code.extend([0x0F, 0x94, 0xC0]); // setz al
|
||||
code.extend([0x0F, 0xB6, 0xC0]); // movzx eax, al
|
||||
code.push(RET);
|
||||
start(&image("VirtualAlloc", &code, &[]))
|
||||
.unwrap()
|
||||
.result
|
||||
.execution
|
||||
.exit_reason
|
||||
};
|
||||
// Control: a free address is allocated.
|
||||
assert_eq!(allocate_at(0x6_0000_0000), ExitReason::ProcessExit(0));
|
||||
assert_eq!(
|
||||
allocate_at(RETURN_SENTINEL_PAGE),
|
||||
ExitReason::ProcessExit(1)
|
||||
);
|
||||
}
|
||||
@@ -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:?}");
|
||||
}
|
||||
+275
-227
@@ -1,227 +1,275 @@
|
||||
// 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)
|
||||
}
|
||||
|
||||
/// Call an import as the main thread of a scheduled run: the engine runs
|
||||
/// in slices of `quantum` instructions under the guest thread scheduler.
|
||||
pub fn scheduled(
|
||||
&mut self,
|
||||
symbol: &str,
|
||||
args: &[u64],
|
||||
quantum: usize,
|
||||
budget: usize,
|
||||
) -> xenora_loader::scheduler::ScheduleReport {
|
||||
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);
|
||||
}
|
||||
xenora_loader::scheduler::Scheduler::new(Arc::clone(&self.state), quantum)
|
||||
.run(&mut self.engine, &mut self.memory, &cpu, budget)
|
||||
.expect("the scheduler attaches")
|
||||
}
|
||||
|
||||
/// 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()
|
||||
}
|
||||
}
|
||||
@@ -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()],
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -59,6 +59,13 @@ def cases():
|
||||
for count in ("1", "3", "7", "cl"):
|
||||
out += [f"{op} {reg(3, bits)}, {count}", f"{op} {mem(bits)}, {count}"]
|
||||
out += [f"{op} {reg(13, bits)}, {bits - 1}", f"{op} {reg(13, bits)}, 0"]
|
||||
for op in ("shld", "shrd"):
|
||||
for bits in (16, 32, 64):
|
||||
for count in ("1", "3", "7", "cl"):
|
||||
out += [f"{op} {reg(3, bits)}, {reg(9, bits)}, {count}",
|
||||
f"{op} {mem(bits)}, {reg(2, bits)}, {count}"]
|
||||
out += [f"{op} {reg(13, bits)}, {reg(0, bits)}, {bits - 1}", f"{op} {reg(13, bits)}, {reg(1, bits)}, 0",
|
||||
f"{op} {reg(3, bits)}, {reg(3, bits)}, 5", f"{op} {reg(12, bits)}, {reg(10, bits)}, {bits}"]
|
||||
for bits in (16, 32, 64):
|
||||
out += [f"imul {reg(3, bits)}, {reg(9, bits)}", f"imul {reg(3, bits)}, {mem(bits)}",
|
||||
f"imul {reg(8, bits)}, {reg(1, bits)}, -7", f"imul {reg(8, bits)}, {reg(1, bits)}, 0x1234",
|
||||
|
||||
@@ -747,6 +747,78 @@ d3 7c be 10 | sar dword ptr [rsi + 4*rdi + 16], cl
|
||||
48 d3 7c be 10 | sar qword ptr [rsi + 4*rdi + 16], cl
|
||||
49 c1 fd 3f | sar r13, 63
|
||||
49 c1 fd 00 | sar r13, 0
|
||||
66 44 0f a4 cb 01 | shld bx, r9w, 1
|
||||
66 0f a4 54 be 10 01 | shld word ptr [rsi + 4*rdi + 16], dx, 1
|
||||
66 44 0f a4 cb 03 | shld bx, r9w, 3
|
||||
66 0f a4 54 be 10 03 | shld word ptr [rsi + 4*rdi + 16], dx, 3
|
||||
66 44 0f a4 cb 07 | shld bx, r9w, 7
|
||||
66 0f a4 54 be 10 07 | shld word ptr [rsi + 4*rdi + 16], dx, 7
|
||||
66 44 0f a5 cb | shld bx, r9w, cl
|
||||
66 0f a5 54 be 10 | shld word ptr [rsi + 4*rdi + 16], dx, cl
|
||||
66 41 0f a4 c5 0f | shld r13w, ax, 15
|
||||
66 41 0f a4 cd 00 | shld r13w, cx, 0
|
||||
66 0f a4 db 05 | shld bx, bx, 5
|
||||
66 45 0f a4 d4 10 | shld r12w, r10w, 16
|
||||
44 0f a4 cb 01 | shld ebx, r9d, 1
|
||||
0f a4 54 be 10 01 | shld dword ptr [rsi + 4*rdi + 16], edx, 1
|
||||
44 0f a4 cb 03 | shld ebx, r9d, 3
|
||||
0f a4 54 be 10 03 | shld dword ptr [rsi + 4*rdi + 16], edx, 3
|
||||
44 0f a4 cb 07 | shld ebx, r9d, 7
|
||||
0f a4 54 be 10 07 | shld dword ptr [rsi + 4*rdi + 16], edx, 7
|
||||
44 0f a5 cb | shld ebx, r9d, cl
|
||||
0f a5 54 be 10 | shld dword ptr [rsi + 4*rdi + 16], edx, cl
|
||||
41 0f a4 c5 1f | shld r13d, eax, 31
|
||||
41 0f a4 cd 00 | shld r13d, ecx, 0
|
||||
0f a4 db 05 | shld ebx, ebx, 5
|
||||
45 0f a4 d4 20 | shld r12d, r10d, 32
|
||||
4c 0f a4 cb 01 | shld rbx, r9, 1
|
||||
48 0f a4 54 be 10 01 | shld qword ptr [rsi + 4*rdi + 16], rdx, 1
|
||||
4c 0f a4 cb 03 | shld rbx, r9, 3
|
||||
48 0f a4 54 be 10 03 | shld qword ptr [rsi + 4*rdi + 16], rdx, 3
|
||||
4c 0f a4 cb 07 | shld rbx, r9, 7
|
||||
48 0f a4 54 be 10 07 | shld qword ptr [rsi + 4*rdi + 16], rdx, 7
|
||||
4c 0f a5 cb | shld rbx, r9, cl
|
||||
48 0f a5 54 be 10 | shld qword ptr [rsi + 4*rdi + 16], rdx, cl
|
||||
49 0f a4 c5 3f | shld r13, rax, 63
|
||||
49 0f a4 cd 00 | shld r13, rcx, 0
|
||||
48 0f a4 db 05 | shld rbx, rbx, 5
|
||||
4d 0f a4 d4 40 | shld r12, r10, 64
|
||||
66 44 0f ac cb 01 | shrd bx, r9w, 1
|
||||
66 0f ac 54 be 10 01 | shrd word ptr [rsi + 4*rdi + 16], dx, 1
|
||||
66 44 0f ac cb 03 | shrd bx, r9w, 3
|
||||
66 0f ac 54 be 10 03 | shrd word ptr [rsi + 4*rdi + 16], dx, 3
|
||||
66 44 0f ac cb 07 | shrd bx, r9w, 7
|
||||
66 0f ac 54 be 10 07 | shrd word ptr [rsi + 4*rdi + 16], dx, 7
|
||||
66 44 0f ad cb | shrd bx, r9w, cl
|
||||
66 0f ad 54 be 10 | shrd word ptr [rsi + 4*rdi + 16], dx, cl
|
||||
66 41 0f ac c5 0f | shrd r13w, ax, 15
|
||||
66 41 0f ac cd 00 | shrd r13w, cx, 0
|
||||
66 0f ac db 05 | shrd bx, bx, 5
|
||||
66 45 0f ac d4 10 | shrd r12w, r10w, 16
|
||||
44 0f ac cb 01 | shrd ebx, r9d, 1
|
||||
0f ac 54 be 10 01 | shrd dword ptr [rsi + 4*rdi + 16], edx, 1
|
||||
44 0f ac cb 03 | shrd ebx, r9d, 3
|
||||
0f ac 54 be 10 03 | shrd dword ptr [rsi + 4*rdi + 16], edx, 3
|
||||
44 0f ac cb 07 | shrd ebx, r9d, 7
|
||||
0f ac 54 be 10 07 | shrd dword ptr [rsi + 4*rdi + 16], edx, 7
|
||||
44 0f ad cb | shrd ebx, r9d, cl
|
||||
0f ad 54 be 10 | shrd dword ptr [rsi + 4*rdi + 16], edx, cl
|
||||
41 0f ac c5 1f | shrd r13d, eax, 31
|
||||
41 0f ac cd 00 | shrd r13d, ecx, 0
|
||||
0f ac db 05 | shrd ebx, ebx, 5
|
||||
45 0f ac d4 20 | shrd r12d, r10d, 32
|
||||
4c 0f ac cb 01 | shrd rbx, r9, 1
|
||||
48 0f ac 54 be 10 01 | shrd qword ptr [rsi + 4*rdi + 16], rdx, 1
|
||||
4c 0f ac cb 03 | shrd rbx, r9, 3
|
||||
48 0f ac 54 be 10 03 | shrd qword ptr [rsi + 4*rdi + 16], rdx, 3
|
||||
4c 0f ac cb 07 | shrd rbx, r9, 7
|
||||
48 0f ac 54 be 10 07 | shrd qword ptr [rsi + 4*rdi + 16], rdx, 7
|
||||
4c 0f ad cb | shrd rbx, r9, cl
|
||||
48 0f ad 54 be 10 | shrd qword ptr [rsi + 4*rdi + 16], rdx, cl
|
||||
49 0f ac c5 3f | shrd r13, rax, 63
|
||||
49 0f ac cd 00 | shrd r13, rcx, 0
|
||||
48 0f ac db 05 | shrd rbx, rbx, 5
|
||||
4d 0f ac d4 40 | shrd r12, r10, 64
|
||||
66 41 0f af d9 | imul bx, r9w
|
||||
66 0f af 5c be 10 | imul bx, word ptr [rsi + 4*rdi + 16]
|
||||
66 44 6b c1 f9 | imul r8w, cx, -7
|
||||
|
||||
@@ -274,7 +274,8 @@ struct Undefined {
|
||||
of: bool,
|
||||
pf: bool,
|
||||
af: bool,
|
||||
/// The destination itself is undefined (BSF/BSR of zero).
|
||||
/// The destination itself is undefined (BSF/BSR of zero, or a 16-bit
|
||||
/// SHLD/SHRD count above 16).
|
||||
destination: bool,
|
||||
}
|
||||
|
||||
@@ -450,6 +451,53 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
|
||||
}
|
||||
Outcome::Done(undefined)
|
||||
}
|
||||
"shld" | "shrd" => {
|
||||
// Intel SDM Vol. 2B, SHLD and SHRD: the count is masked to 5 bits
|
||||
// (6 for 64-bit operands); a count above the operand size leaves
|
||||
// the destination and the flags undefined.
|
||||
let count = read(m, places[2], 8) as u32 % if bits == 64 { 64 } else { 32 };
|
||||
let start = read(m, places[0], bits);
|
||||
let mut fill = read(m, places[1], bits);
|
||||
if count > bits {
|
||||
return Outcome::Done(Undefined {
|
||||
cf: true,
|
||||
zf: true,
|
||||
sf: true,
|
||||
of: true,
|
||||
pf: true,
|
||||
af: true,
|
||||
destination: true,
|
||||
});
|
||||
}
|
||||
let mut value = start;
|
||||
let mut carry = m.flags.cf;
|
||||
for _ in 0..count {
|
||||
// One bit at a time: the bit leaving the destination goes to
|
||||
// CF and the next bit of the source enters from the other end.
|
||||
if name == "shld" {
|
||||
carry = bit(value, bits - 1);
|
||||
value = truncate(value * 2, bits) + u128::from(bit(fill, bits - 1));
|
||||
fill = truncate(fill * 2, bits);
|
||||
} else {
|
||||
carry = bit(value, 0);
|
||||
value = value / 2 + if bit(fill, 0) { 1u128 << (bits - 1) } else { 0 };
|
||||
fill /= 2;
|
||||
}
|
||||
}
|
||||
write(m, places[0], value);
|
||||
let mut undefined = none;
|
||||
if count != 0 {
|
||||
m.flags.cf = carry;
|
||||
set_result(&mut m.flags, value, bits);
|
||||
undefined.af = true;
|
||||
if count == 1 {
|
||||
m.flags.of = bit(value, bits - 1) != bit(start, bits - 1);
|
||||
} else {
|
||||
undefined.of = true;
|
||||
}
|
||||
}
|
||||
Outcome::Done(undefined)
|
||||
}
|
||||
"mul" | "imul" => {
|
||||
let undefined = Undefined {
|
||||
zf: true,
|
||||
@@ -938,12 +986,12 @@ fn every_fixture_instruction_matches_the_reference_in_both_engines() {
|
||||
assert_eq!(state.rip, ENTRY + case.code.len() as u64, "{text}");
|
||||
if !undefined.destination {
|
||||
assert_eq!(state.gpr, expected.gpr, "{text} from {cpu:x?}");
|
||||
assert_eq!(
|
||||
memory.read_u64(OPERAND).unwrap(),
|
||||
expected.operand,
|
||||
"{text} from {cpu:x?}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
memory.read_u64(OPERAND).unwrap(),
|
||||
expected.operand,
|
||||
"{text} from {cpu:x?}"
|
||||
);
|
||||
assert_eq!(
|
||||
memory.read_u64(STACK_TOP - 8).unwrap(),
|
||||
expected.pushed,
|
||||
|
||||
@@ -66,6 +66,8 @@ rcr = { reads = "cf", writes = "cf of", conditional = true, ref = "sdm RCL/RCR/R
|
||||
shl = { writes = "cf zf sf of pf", undefined = "af", conditional = true, ref = "sdm SAL/SAR/SHL/SHR" }
|
||||
shr = { writes = "cf zf sf of pf", undefined = "af", conditional = true, ref = "sdm SAL/SAR/SHL/SHR" }
|
||||
sar = { writes = "cf zf sf of pf", undefined = "af", conditional = true, ref = "sdm SAL/SAR/SHL/SHR" }
|
||||
shld = { writes = "cf zf sf of pf", undefined = "af", conditional = true, ref = "sdm SHLD" }
|
||||
shrd = { writes = "cf zf sf of pf", undefined = "af", conditional = true, ref = "sdm SHRD" }
|
||||
mul = { writes = "cf of", undefined = "zf sf pf af", ref = "sdm MUL" }
|
||||
imul = { writes = "cf of", undefined = "zf sf pf af", ref = "sdm IMUL" }
|
||||
imul2 = { writes = "cf of", undefined = "zf sf pf af", ref = "sdm IMUL" }
|
||||
@@ -832,6 +834,38 @@ digits = { 0 = "inc", 1 = "dec" }
|
||||
opcodes = [[0xC0, "b", "ib", "rm_imm"], [0xC1, "v", "ib", "rm_imm"], [0xD0, "b", "", "rm_one"], [0xD1, "v", "", "rm_one"], [0xD2, "b", "", "rm_cl"], [0xD3, "v", "", "rm_cl"]]
|
||||
digits = { 0 = "rol", 1 = "ror", 2 = "rcl", 3 = "rcr", 4 = "shl", 5 = "shr", 7 = "sar" }
|
||||
|
||||
# Double-precision shifts: the ModRM operand is shifted and filled from the
|
||||
# reg operand, by an 8-bit immediate or by CL.
|
||||
[[form]]
|
||||
op = "shld"
|
||||
map = "0f"
|
||||
opcode = 0xA4
|
||||
enc = "rm_reg_imm"
|
||||
size = "v"
|
||||
imm = "ub"
|
||||
|
||||
[[form]]
|
||||
op = "shld"
|
||||
map = "0f"
|
||||
opcode = 0xA5
|
||||
enc = "rm_reg_cl"
|
||||
size = "v"
|
||||
|
||||
[[form]]
|
||||
op = "shrd"
|
||||
map = "0f"
|
||||
opcode = 0xAC
|
||||
enc = "rm_reg_imm"
|
||||
size = "v"
|
||||
imm = "ub"
|
||||
|
||||
[[form]]
|
||||
op = "shrd"
|
||||
map = "0f"
|
||||
opcode = 0xAD
|
||||
enc = "rm_reg_cl"
|
||||
size = "v"
|
||||
|
||||
# SSE and SSE2 moves and packed integer forms.
|
||||
|
||||
[[form]]
|
||||
|
||||
@@ -48,6 +48,7 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
|
||||
- [Test inventory comparison](testing/test-inventory.md) — Detect missing or newly ignored Cargo tests across commits.
|
||||
- [Persistent resource and translated rendering acceptance](testing/x9-acceptance.md) — Pinned upstream tests, native ARM64 results and unsupported cases.
|
||||
- [Baseline acceptance](testing/phase-02-baseline.md), [Phase 01 assurance](testing/phase01-assurance.md), and [independent reviews](testing/review-log.md) — Candidate-specific results and release findings.
|
||||
- [Gate A: a compiled C program](testing/gate-a.md) — The two milestones, what the A1 test checks and what it does not show.
|
||||
- [Mutation testing](testing/mutation.md) and [benchmark protocol](testing/benchmarks.md) — Test sensitivity, benchmark inputs, and timing requirements.
|
||||
|
||||
## Research and engineering decisions
|
||||
|
||||
@@ -104,4 +104,4 @@ A feature bit is set only when every instruction of that feature is implemented.
|
||||
|
||||
## Rejected on purpose
|
||||
|
||||
LOCK except as described above, F2 or F3 where it is neither PAUSE nor part of a declared form, F2 combined with F3, address-size overrides, an ignored segment override after FS or GS, 16-bit stack and branch forms, 16-bit BSWAP and MOVSXD, bit tests of memory by a register index, SHLD, SHRD, LODS, CMPS, SCAS, REPE and REPNE, MMX, the RCP and RSQRT approximations, SSE3 and later, VEX, CMPXCHG8B and CMPXCHG16B. The DBT also refuses raw SYSCALL.
|
||||
LOCK except as described above, F2 or F3 where it is neither PAUSE nor part of a declared form, F2 combined with F3, address-size overrides, an ignored segment override after FS or GS, 16-bit stack and branch forms, 16-bit BSWAP and MOVSXD, bit tests of memory by a register index, LODS, CMPS, SCAS, REPE and REPNE, MMX, the RCP and RSQRT approximations, SSE3 and later, VEX, CMPXCHG8B and CMPXCHG16B. The DBT also refuses raw SYSCALL.
|
||||
+62
-2
@@ -66,8 +66,56 @@ returns owned words after command completion or a stage-specific error.
|
||||
fixture, guest memory addresses, a service registry and an entry instruction
|
||||
budget. It maps and rebases the image, binds imports, initializes thread-local
|
||||
storage, invokes its callbacks and runs the entry point. The fixture entry point
|
||||
uses a Win64-aligned stack and terminates with HLT. The result includes the loaded
|
||||
guest memory and the entry execution outcome.
|
||||
uses a Win64-aligned stack. It may end with HLT, call `ExitProcess`, or return.
|
||||
The result includes the loaded guest memory and the entry execution outcome.
|
||||
|
||||
A guest ends its process through `kernel32.dll!ExitProcess`, also reachable as
|
||||
`api-ms-win-core-processthreads-l1-1-0.dll!ExitProcess`. Execution stops with
|
||||
`ExitReason::ProcessExit(status)`, where the status is the full 32-bit value
|
||||
the guest passed. Only the guest stops: the host process is not ended. A
|
||||
returning entry point does the same with EAX as the status, which matches
|
||||
Windows while the process has one thread. The exit closes every guest handle:
|
||||
kernel objects, Winsock sockets and task-queue handles, which
|
||||
`ServicesState::open_handle_count` counts together. Files stay on the synthetic `C:` drive, guest memory stays mapped so the host
|
||||
can inspect it, and `atexit` functions are not run: that belongs to the C
|
||||
runtime's `exit`, which is not implemented. `ServicesState::exit_status`
|
||||
reports the status. After an exit the `DbtEngine` that ran the guest executes
|
||||
no further guest instruction and answers every later `run` with the same
|
||||
`ProcessExit`. A service callback that was in progress is never resumed.
|
||||
|
||||
A TLS callback may end the process too. Startup then reports the exit as its
|
||||
outcome, with the status, and runs neither the remaining callbacks nor the
|
||||
entry point; `StartupResult::tls_callbacks` counts the callbacks that finished.
|
||||
Any other stop inside a TLS callback is still a startup error.
|
||||
|
||||
The engine recognises two return addresses, one under the entry point and one
|
||||
under a guest callback, before it executes anything at them. Both are in the
|
||||
4 KiB page at `imports::RETURN_SENTINEL_PAGE`, which startup reserves with no
|
||||
access. An image or layout that covers that page is refused, and a guest
|
||||
allocation there fails. The import trampolines above that page are intercepted
|
||||
in the same way and are not reserved.
|
||||
|
||||
Loading an image maps its headers as well as its sections. The first
|
||||
`SizeOfHeaders` bytes of the file are mapped read-only at the image base, in
|
||||
whole 4 KiB pages. Everything in those pages past `SizeOfHeaders` is zero, even
|
||||
where the file holds more bytes there. A guest can read its own DOS header,
|
||||
section table and data directories; it cannot write or execute them.
|
||||
|
||||
When startup loads an image away from its preferred base, it writes the load
|
||||
base into the mapped optional header's `ImageBase` field after the relocations
|
||||
have been applied, so an entry aimed at that field cannot leave any other value
|
||||
there. This is Xenora's policy: the PE specification defines `ImageBase` as the
|
||||
preferred base, and the behaviour has not been compared with Windows.
|
||||
|
||||
The load is refused with `PeError::InvalidHeaderSize` when `SizeOfHeaders` is
|
||||
zero, ends before the section table does, runs past the end of the file, or its
|
||||
pages would reach into a section, and when the bytes given to the loader are not
|
||||
the PE32+ headers that were parsed. The page rule is stricter than the loader
|
||||
was before: an image whose section alignment is below 4 KiB, with a section
|
||||
that starts inside the header page, used to load and is now refused. The header
|
||||
pages count toward the 256 MiB mapping budget of one image, which is checked
|
||||
before anything is mapped. `ParsedPe::parse` does not make these checks, so
|
||||
static inspection of a file is unchanged.
|
||||
|
||||
`xenora probe --mode static` inventories ordinary and delay-loaded PE imports
|
||||
without guest execution. Without `--report` it writes to `diagnostics/probe`,
|
||||
@@ -102,6 +150,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
|
||||
|
||||
@@ -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.
|
||||
@@ -0,0 +1,53 @@
|
||||
# Gate A: a compiled C program
|
||||
|
||||
Gate A asks for an independently compiled C program, exercising allocation,
|
||||
file operations, arithmetic, function calls and error handling, to run through
|
||||
Xenora. The maintainer split it into two milestones. Gate A is complete only
|
||||
when both pass.
|
||||
|
||||
| Milestone | What it is | Status |
|
||||
| --- | --- | --- |
|
||||
| A1 | An original C program with no C library linked, importing documented `kernel32.dll` and `ucrtbase.dll` functions, run through the loader and the ARM64 DBT with proper process exit | Passes locally; awaiting independent review |
|
||||
| A2 | A hosted C program: a real C runtime startup, the standard C library, `argc` and `argv`, stdio and formatted output, normal exit and runtime cleanup | Not started |
|
||||
|
||||
## A1
|
||||
|
||||
The program is [`tests/compat_fixtures/gate_a1.c`](../../tests/compat_fixtures/gate_a1.c).
|
||||
Its build configuration and provenance are in
|
||||
[`tests/compat_fixtures/README.md`](../../tests/compat_fixtures/README.md#gate-a1-a-c-program-with-no-c-library).
|
||||
The gate is `crates/loader/tests/gate_a1.rs`:
|
||||
|
||||
```sh
|
||||
cargo test --locked -p xenora-loader --test gate_a1 -- --nocapture
|
||||
```
|
||||
|
||||
The test builds the program from source, then runs each build through
|
||||
`run_synthetic_startup` with `register_standard_services`, loaded away from its
|
||||
preferred base. It checks, at `-O0`, `-O1`, `-O2` and `-Os`:
|
||||
|
||||
- the 20 imports are bound and the 6 base relocations applied;
|
||||
- the guest ends with `ExitReason::ProcessExit(0x00A1A1A1)`, all 32 bits;
|
||||
- it ran as translated code, with service calls;
|
||||
- the text report it wrote matches a report recomputed in Rust;
|
||||
- the data file holds the 64 sorted records, the file it looked for does not exist, and the handle it left open was closed by the exit;
|
||||
- its result block in guest memory holds the expected values, the block it kept is readable and the block it freed is unmapped.
|
||||
|
||||
Three controls must fail in the stated way: a wrong expectation exits with the
|
||||
number of the failed check, an import that no service provides is refused
|
||||
before entry, and a step budget that is too small is not an exit. A variant
|
||||
whose entry point returns its status gives the same result as `ExitProcess`.
|
||||
|
||||
### What A1 does not show
|
||||
|
||||
- It is one program. Local runs used Homebrew clang 23.1.6 and Apple clang 17.0.0, each with LLD 23.1.5. Another compiler or a larger program can need instructions and services this one does not.
|
||||
- Most services it calls are marked partial in the registry. They did what this program needs.
|
||||
- It runs in the DBT only. The interpreter has no import dispatch.
|
||||
- It reaches the guest through a test, not through `xenora run`, which accepts only two built-in fixtures.
|
||||
- Nothing here concerns a commercial game or an Xbox launch environment.
|
||||
|
||||
## A2
|
||||
|
||||
Not started. It needs at least the C standard I/O functions, `exit` with
|
||||
`atexit` handlers, command-line and environment access, and a decision on
|
||||
which C runtime startup code may be linked and under what licence. None of
|
||||
those are registered today.
|
||||
@@ -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
|
||||
@@ -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
@@ -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
|
||||
|
||||
@@ -66,3 +66,47 @@ enabled.
|
||||
The runner prints the guest's exit value and returns a nonzero host status
|
||||
for load or interpreter faults. The gate compares both outcomes. These
|
||||
fixtures exercise synthetic commands and local Apple Silicon readback.
|
||||
|
||||
## Gate A1: a C program with no C library
|
||||
|
||||
`gate_a1.c` is an original C program that links no C library. It imports
|
||||
twelve functions from `ucrtbase.dll` and eight from `kernel32.dll` by name,
|
||||
with prototypes written from the public Windows SDK and C standard
|
||||
declarations. It allocates and frees memory, sorts with a callback, does
|
||||
64-bit and double arithmetic, uses the C string functions, writes and reads
|
||||
files on the synthetic `C:` drive, checks two error paths, writes a text
|
||||
report and ends with `ExitProcess`.
|
||||
|
||||
`build-gate-a1.sh [output directory]` builds it. `cargo test -p xenora-loader
|
||||
--test gate_a1` runs that script and then runs the result through
|
||||
`run_synthetic_startup`, the standard services and the DBT. No built
|
||||
executable is committed: the test builds from source every time, in CI too.
|
||||
|
||||
Compiler configuration:
|
||||
|
||||
| Step | Command |
|
||||
| --- | --- |
|
||||
| Compile | `clang --target=x86_64-pc-windows-msvc -O<level> -ffreestanding -fno-stack-protector -Wall -Wextra -Werror` |
|
||||
| Import libraries | `lld-link /lib /machine:x64 /def:<kernel32 or ucrtbase>.def` from the name lists in the script |
|
||||
| Link | `lld-link /entry:gate_entry /subsystem:console /nodefaultlib /timestamp:0` |
|
||||
|
||||
It is built at `-O0`, `-O1`, `-O2` and `-Os`, and three more times at `-O1` as
|
||||
controls: `GATE_BREAK` (one wrong expectation), `GATE_RETURN` (the entry point
|
||||
returns its status) and `GATE_MISSING` (an import no service provides).
|
||||
|
||||
Tools. `CLANG` defaults to Homebrew LLVM when it is installed and otherwise to
|
||||
the `clang` on `PATH`. `LLD_LINK` defaults to Homebrew `lld` when it is
|
||||
installed and otherwise to the `rust-lld` inside the active Rust toolchain,
|
||||
which is an LLD. On macOS the script requires both, and every library they
|
||||
load that is a file on disk, to be ARM64: it checks each tool with `file` and
|
||||
`lipo -archs`, and each library `otool -L` lists with `lipo -archs`, following
|
||||
the tool's own run paths. The script writes the versions it used to
|
||||
`toolchain.txt`, which the test prints, and what the native checks looked at to
|
||||
`toolchain-native.txt`. The test builds into a directory of its own for each
|
||||
test process under the Cargo target directory, so two runs that share a target
|
||||
directory do not overwrite each other's files; `cargo clean` removes them.
|
||||
|
||||
Provenance. The source, the name lists and the script were written for Xenora
|
||||
and are GPL-3.0-or-later. Nothing from a Windows SDK, a C runtime or another
|
||||
project is compiled or linked. The compiler and linker are LLVM projects
|
||||
under the Apache License 2.0 with LLVM exceptions; they are tools, not inputs.
|
||||
Executable
+140
@@ -0,0 +1,140 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
#
|
||||
# Build the Gate A1 program, tests/compat_fixtures/gate_a1.c, as x86-64 PE32+
|
||||
# executables with no C library linked.
|
||||
#
|
||||
# build-gate-a1.sh [output directory] default: artifacts/gate-a1
|
||||
#
|
||||
# Tools, all native to the host:
|
||||
# CLANG a clang that accepts --target=x86_64-pc-windows-msvc. Default:
|
||||
# Homebrew LLVM if installed, otherwise the clang on PATH.
|
||||
# LLD_LINK an lld-link. Default: Homebrew lld if installed, otherwise the
|
||||
# rust-lld that ships in the active Rust toolchain.
|
||||
#
|
||||
# The linker also makes the two import libraries, from the definition files
|
||||
# written below, so nothing from a Windows SDK or another C runtime is used.
|
||||
set -eu
|
||||
cd "$(dirname "$0")/../.."
|
||||
root=$PWD
|
||||
src="$root/tests/compat_fixtures/gate_a1.c"
|
||||
out=${1:-"$root/artifacts/gate-a1"}
|
||||
|
||||
clang=${CLANG:-}
|
||||
if [ -z "$clang" ]; then
|
||||
clang=/opt/homebrew/opt/llvm/bin/clang
|
||||
[ -x "$clang" ] || clang=$(command -v clang)
|
||||
fi
|
||||
flavor=
|
||||
linker=${LLD_LINK:-}
|
||||
if [ -z "$linker" ]; then
|
||||
linker=/opt/homebrew/opt/lld/bin/lld-link
|
||||
if [ ! -x "$linker" ]; then
|
||||
host=$(rustc -vV | sed -n 's/^host: //p')
|
||||
linker="$(rustc --print sysroot)/lib/rustlib/$host/bin/rust-lld"
|
||||
flavor="-flavor link"
|
||||
fi
|
||||
fi
|
||||
for tool in "$clang" "$linker"; do
|
||||
[ -x "$tool" ] || { echo "missing tool: $tool" >&2; exit 1; }
|
||||
done
|
||||
# AGENTS.md: host tools and what they load must be ARM64, checked with file,
|
||||
# lipo -archs and otool -L. An @rpath library is looked up through the tool's
|
||||
# own run paths. A library that is still not a file on disk is in the system's
|
||||
# shared cache, and is listed only.
|
||||
native=
|
||||
if [ "$(uname -s)" = Darwin ]; then
|
||||
for tool in "$clang" "$linker"; do
|
||||
case "$(file -bL "$tool")" in
|
||||
*arm64*) ;;
|
||||
*) echo "ARM64 tool required (file): $tool" >&2; exit 1 ;;
|
||||
esac
|
||||
case "$(lipo -archs "$tool")" in
|
||||
*arm64*) ;;
|
||||
*) echo "ARM64 tool required (lipo): $tool" >&2; exit 1 ;;
|
||||
esac
|
||||
here=$(dirname "$tool")
|
||||
runpaths=$(otool -l "$tool" | awk '/LC_RPATH/ { getline; getline; print $2 }' |
|
||||
sed "s|@loader_path|$here|; s|@executable_path|$here|")
|
||||
for library in $(otool -L "$tool" | awk 'NR > 1 { print $1 }'); do
|
||||
case "$library" in
|
||||
@rpath/*)
|
||||
for runpath in $runpaths; do
|
||||
if [ -f "$runpath/${library#@rpath/}" ]; then
|
||||
library="$runpath/${library#@rpath/}"
|
||||
break
|
||||
fi
|
||||
done ;;
|
||||
esac
|
||||
[ -f "$library" ] || continue
|
||||
case "$(lipo -archs "$library")" in
|
||||
*arm64*) ;;
|
||||
*) echo "ARM64 library required by $tool: $library" >&2; exit 1 ;;
|
||||
esac
|
||||
native="$native $library: $(lipo -archs "$library")
|
||||
"
|
||||
done
|
||||
native="$native$(file -bL "$tool")
|
||||
$(otool -L "$tool")
|
||||
"
|
||||
done
|
||||
fi
|
||||
# $flavor is empty or two words on purpose.
|
||||
# shellcheck disable=SC2086
|
||||
link() { "$linker" $flavor "$@"; }
|
||||
|
||||
mkdir -p "$out"
|
||||
cd "$out"
|
||||
{
|
||||
"$clang" --version | head -1
|
||||
link --version | head -1
|
||||
} > toolchain.txt
|
||||
# What the native checks above looked at.
|
||||
printf '%s' "$native" > toolchain-native.txt
|
||||
|
||||
cat > kernel32.def <<'DEF'
|
||||
LIBRARY kernel32.dll
|
||||
EXPORTS
|
||||
CloseHandle
|
||||
CreateFileW
|
||||
ExitProcess
|
||||
GateMissingService
|
||||
GetFileSizeEx
|
||||
GetLastError
|
||||
ReadFile
|
||||
SetFilePointerEx
|
||||
WriteFile
|
||||
DEF
|
||||
cat > ucrtbase.def <<'DEF'
|
||||
LIBRARY ucrtbase.dll
|
||||
EXPORTS
|
||||
_errno
|
||||
free
|
||||
malloc
|
||||
memcmp
|
||||
memcpy
|
||||
memset
|
||||
qsort
|
||||
realloc
|
||||
strcmp
|
||||
strlen
|
||||
strncmp
|
||||
strtol
|
||||
DEF
|
||||
link /lib /machine:x64 /def:kernel32.def /out:kernel32.lib
|
||||
link /lib /machine:x64 /def:ucrtbase.def /out:ucrtbase.lib
|
||||
|
||||
# name, optimization level, extra definition
|
||||
build() {
|
||||
"$clang" --target=x86_64-pc-windows-msvc "-$2" -ffreestanding -fno-stack-protector \
|
||||
-Wall -Wextra -Werror ${3:+"-D$3"} -c "$src" -o "$1.obj"
|
||||
link /entry:gate_entry /subsystem:console /nodefaultlib /timestamp:0 \
|
||||
"/out:$1.exe" "$1.obj" kernel32.lib ucrtbase.lib
|
||||
}
|
||||
for level in O0 O1 O2 Os; do
|
||||
build "gate-a1-$level" "$level" ""
|
||||
done
|
||||
# Controls: a wrong expectation, a returning entry point, an import nobody provides.
|
||||
build gate-a1-break O1 GATE_BREAK
|
||||
build gate-a1-return O1 GATE_RETURN
|
||||
build gate-a1-missing O1 GATE_MISSING
|
||||
@@ -0,0 +1,314 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//
|
||||
// Gate A1: an original C program with no C library linked.
|
||||
//
|
||||
// It allocates and frees memory, sorts with a callback, does 64-bit and
|
||||
// double arithmetic, uses the C string functions, reads and writes files on
|
||||
// the synthetic C: drive, checks two error paths, writes a text report and
|
||||
// ends its process with a status. Every outside function is imported by name
|
||||
// from kernel32.dll or ucrtbase.dll; the prototypes below follow the public
|
||||
// Windows SDK and C standard declarations. Nothing else is linked.
|
||||
//
|
||||
// Build with tests/compat_fixtures/build-gate-a1.sh. The test that runs it,
|
||||
// crates/loader/tests/gate_a1.rs, recomputes every number in the report.
|
||||
|
||||
typedef unsigned long long u64;
|
||||
typedef long long i64;
|
||||
typedef unsigned int u32;
|
||||
typedef unsigned short wchar;
|
||||
typedef unsigned char u8;
|
||||
|
||||
#define IMPORT __declspec(dllimport)
|
||||
|
||||
// ucrtbase.dll
|
||||
IMPORT void *malloc(u64 size);
|
||||
IMPORT void *realloc(void *block, u64 size);
|
||||
IMPORT void free(void *block);
|
||||
IMPORT int *_errno(void);
|
||||
IMPORT u64 strlen(const char *text);
|
||||
IMPORT int strcmp(const char *left, const char *right);
|
||||
IMPORT int strncmp(const char *left, const char *right, u64 count);
|
||||
IMPORT long strtol(const char *text, char **end, int base);
|
||||
IMPORT void *memcpy(void *to, const void *from, u64 count);
|
||||
IMPORT void *memset(void *to, int value, u64 count);
|
||||
IMPORT int memcmp(const void *left, const void *right, u64 count);
|
||||
IMPORT void qsort(void *base, u64 count, u64 size, int (*compare)(const void *, const void *));
|
||||
|
||||
// kernel32.dll
|
||||
IMPORT void *CreateFileW(const wchar *name, u32 access, u32 share, void *security,
|
||||
u32 disposition, u32 flags, void *template_file);
|
||||
IMPORT int WriteFile(void *file, const void *data, u32 size, u32 *written, void *overlapped);
|
||||
IMPORT int ReadFile(void *file, void *data, u32 size, u32 *read, void *overlapped);
|
||||
IMPORT int SetFilePointerEx(void *file, i64 distance, i64 *position, u32 method);
|
||||
IMPORT int GetFileSizeEx(void *file, i64 *size);
|
||||
IMPORT int CloseHandle(void *object);
|
||||
IMPORT u32 GetLastError(void);
|
||||
IMPORT void ExitProcess(u32 status);
|
||||
#ifdef GATE_MISSING
|
||||
// Negative control: a name no service provides.
|
||||
IMPORT void GateMissingService(void);
|
||||
#endif
|
||||
|
||||
#define INVALID_HANDLE ((void *)-1)
|
||||
#define GENERIC_READ 0x80000000u
|
||||
#define GENERIC_WRITE 0x40000000u
|
||||
#define CREATE_ALWAYS 2
|
||||
#define OPEN_EXISTING 3
|
||||
#define ERROR_FILE_NOT_FOUND 2
|
||||
#define ENOMEM 12
|
||||
|
||||
// The status of a run in which every check passed. It is wider than a byte so
|
||||
// the test can tell that all 32 bits arrive.
|
||||
#define GATE_A1_STATUS 0x00A1A1A1u
|
||||
#define RECORDS 64
|
||||
|
||||
// The compiler refers to this when a program uses floating point.
|
||||
int _fltused = 0x9875;
|
||||
|
||||
struct record {
|
||||
u32 key;
|
||||
u32 weight;
|
||||
double ratio;
|
||||
};
|
||||
|
||||
// What the host reads from guest memory afterwards, in a section of its own
|
||||
// so the test can find it by name.
|
||||
struct gate_result {
|
||||
u32 magic;
|
||||
u32 checks;
|
||||
u64 key_checksum;
|
||||
void *kept;
|
||||
void *freed;
|
||||
};
|
||||
#pragma section(".gate", read, write)
|
||||
__declspec(allocate(".gate")) struct gate_result gate_result = {0x31415926u, 0, 0, 0, 0};
|
||||
|
||||
// Six steps reached through a table of pointers, which gives the image base
|
||||
// relocations. The table is volatile so that an optimizer keeps it.
|
||||
static u64 step_multiply(u64 value, u32 round) {
|
||||
(void)round;
|
||||
return value * 6364136223846793005ULL + 1442695040888963407ULL;
|
||||
}
|
||||
static u64 step_rotate(u64 value, u32 round) {
|
||||
(void)round;
|
||||
return (value << 13) | (value >> 51);
|
||||
}
|
||||
static u64 step_divide(u64 value, u32 round) {
|
||||
(void)round;
|
||||
return value / 7 + value % 1000003;
|
||||
}
|
||||
static u64 step_fold(u64 value, u32 round) {
|
||||
(void)round;
|
||||
return value ^ (value >> 29);
|
||||
}
|
||||
static u64 step_signed(u64 value, u32 round) {
|
||||
(void)round;
|
||||
return (u64)((i64)value / -3);
|
||||
}
|
||||
static u64 step_subtract(u64 value, u32 round) { return value - round; }
|
||||
|
||||
static u64 (*volatile steps[6])(u64, u32) = {step_multiply, step_rotate, step_divide,
|
||||
step_fold, step_signed, step_subtract};
|
||||
|
||||
static u64 mix(u64 value, u32 round) { return steps[round % 6](value, round); }
|
||||
|
||||
static int by_key(const void *left, const void *right) {
|
||||
const struct record *a = left, *b = right;
|
||||
return a->key < b->key ? -1 : a->key > b->key;
|
||||
}
|
||||
|
||||
static u32 fibonacci(u32 n) { return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); }
|
||||
|
||||
// FNV-1a over the keys, least significant byte first.
|
||||
static u64 checksum_keys(const struct record *records, u32 count) {
|
||||
u64 sum = 0xCBF29CE484222325ULL;
|
||||
for (u32 index = 0; index < count; index++)
|
||||
for (u32 byte = 0; byte < 4; byte++)
|
||||
sum = (sum ^ ((records[index].key >> (8 * byte)) & 0xFF)) * 0x100000001B3ULL;
|
||||
return sum;
|
||||
}
|
||||
|
||||
// A small text writer, since no formatted output function is linked.
|
||||
struct text {
|
||||
char *bytes;
|
||||
u32 used;
|
||||
};
|
||||
static void put_text(struct text *out, const char *text) {
|
||||
u64 length = strlen(text);
|
||||
memcpy(out->bytes + out->used, text, length);
|
||||
out->used += (u32)length;
|
||||
}
|
||||
static void put_unsigned(struct text *out, u64 value) {
|
||||
char digits[20];
|
||||
u32 count = 0;
|
||||
do {
|
||||
digits[count++] = (char)('0' + value % 10);
|
||||
value /= 10;
|
||||
} while (value);
|
||||
while (count)
|
||||
out->bytes[out->used++] = digits[--count];
|
||||
}
|
||||
static void put_signed(struct text *out, i64 value) {
|
||||
if (value < 0) {
|
||||
out->bytes[out->used++] = '-';
|
||||
put_unsigned(out, (u64)0 - (u64)value);
|
||||
} else {
|
||||
put_unsigned(out, (u64)value);
|
||||
}
|
||||
}
|
||||
|
||||
// A failed check ends the process with the number of that check.
|
||||
#define CHECK(condition) \
|
||||
do { \
|
||||
gate_result.checks++; \
|
||||
if (!(condition)) \
|
||||
return gate_result.checks; \
|
||||
} while (0)
|
||||
|
||||
static u32 run(void) {
|
||||
// Allocation: fill a block, grow it, and keep what it held.
|
||||
struct record *records = malloc(RECORDS * sizeof *records);
|
||||
CHECK(records != 0);
|
||||
u64 state = 0x243F6A8885A308D3ULL;
|
||||
for (u32 index = 0; index < RECORDS; index++) {
|
||||
state = mix(state, index);
|
||||
// The index in the low six bits makes every key different, so the
|
||||
// sorted order does not depend on how the sort treats equal keys.
|
||||
records[index].key = ((u32)(state >> 20) << 6) | index;
|
||||
records[index].weight = index;
|
||||
records[index].ratio = (double)(state & 0xFFFF) / 65536.0;
|
||||
}
|
||||
u32 first_key = records[0].key;
|
||||
struct record *grown = realloc(records, 2 * RECORDS * sizeof *records);
|
||||
CHECK(grown != 0);
|
||||
records = grown;
|
||||
CHECK(records[0].key == first_key && records[RECORDS - 1].weight == RECORDS - 1);
|
||||
|
||||
// Computation. Each product below is an exact double, and so is their sum,
|
||||
// so the scaled total is an integer the host can recompute.
|
||||
double total = 0;
|
||||
for (u32 index = 0; index < RECORDS; index++)
|
||||
total += records[index].ratio * records[index].weight;
|
||||
u64 weighted = (u64)(total * 65536.0);
|
||||
qsort(records, RECORDS, sizeof *records, by_key);
|
||||
for (u32 index = 1; index < RECORDS; index++)
|
||||
CHECK(records[index - 1].key <= records[index].key);
|
||||
gate_result.key_checksum = checksum_keys(records, RECORDS);
|
||||
#ifdef GATE_BREAK
|
||||
// Negative control: one expectation is wrong, so this check fails.
|
||||
CHECK(fibonacci(12) == 145);
|
||||
#else
|
||||
CHECK(fibonacci(12) == 144);
|
||||
#endif
|
||||
i64 wide = (i64)(state % 1000000007ULL) * -977 / 13;
|
||||
|
||||
// Strings.
|
||||
static const char line[] = "gate-a1:0x7b:-42";
|
||||
char scratch[32];
|
||||
char *end = 0;
|
||||
CHECK(strlen(line) == 16);
|
||||
CHECK(strcmp(line, "gate-a1:0x7b:-42") == 0 && strcmp("gate", "gave") < 0);
|
||||
CHECK(strncmp(line, "gate-b9", 5) == 0 && strncmp(line, "gate-b9", 6) != 0);
|
||||
long hex = strtol(line + 8, &end, 16);
|
||||
CHECK(hex == 123 && end == line + 12);
|
||||
long negative = strtol(line + 13, &end, 10);
|
||||
CHECK(negative == -42 && *end == 0);
|
||||
memset(scratch, '.', sizeof scratch);
|
||||
memcpy(scratch, line, 7);
|
||||
CHECK(memcmp(scratch, "gate-a1.", 8) == 0 && scratch[31] == '.');
|
||||
// Unequal blocks, in both orders: a memcmp that always says "equal" fails here.
|
||||
CHECK(memcmp(scratch, "gate-a2.", 8) < 0 && memcmp("gate-b", scratch, 6) > 0);
|
||||
|
||||
// Errors: a file that does not exist and an allocation that cannot succeed.
|
||||
static const wchar none[] = {'C', ':', '\\', 'n', 'o', 'n', 'e', '.', 'b', 'i', 'n', 0};
|
||||
CHECK(CreateFileW(none, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0) == INVALID_HANDLE);
|
||||
u32 missing = GetLastError();
|
||||
CHECK(missing == ERROR_FILE_NOT_FOUND);
|
||||
*_errno() = 0;
|
||||
CHECK(malloc(~0ULL) == 0);
|
||||
int exhausted = *_errno();
|
||||
CHECK(exhausted == ENOMEM);
|
||||
|
||||
// Files: write the sorted records, then read them back through the same
|
||||
// handle and compare.
|
||||
static const wchar data_name[] = {'C', ':', '\\', 'g', 'a', 't', 'e', '-', 'a',
|
||||
'1', '.', 'b', 'i', 'n', 0};
|
||||
u32 bytes = RECORDS * (u32)sizeof *records;
|
||||
u32 moved = 0;
|
||||
i64 size = 0;
|
||||
void *file = CreateFileW(data_name, GENERIC_READ | GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, 0);
|
||||
CHECK(file != INVALID_HANDLE);
|
||||
CHECK(WriteFile(file, records, bytes, &moved, 0) && moved == bytes);
|
||||
CHECK(GetFileSizeEx(file, &size) && size == bytes);
|
||||
CHECK(SetFilePointerEx(file, 0, 0, 0));
|
||||
u8 *copy = malloc(bytes);
|
||||
CHECK(copy != 0);
|
||||
CHECK(ReadFile(file, copy, bytes, &moved, 0) && moved == bytes);
|
||||
CHECK(memcmp(copy, records, bytes) == 0);
|
||||
// The same comparison without memcmp, and a one-bit difference in the
|
||||
// last byte that memcmp has to see.
|
||||
u32 same = 0;
|
||||
for (u32 i = 0; i < bytes; i++) same += copy[i] == ((const u8 *)records)[i];
|
||||
CHECK(same == bytes);
|
||||
copy[bytes - 1] ^= 1;
|
||||
CHECK(memcmp(copy, records, bytes) != 0);
|
||||
copy[bytes - 1] ^= 1;
|
||||
CHECK(CloseHandle(file));
|
||||
|
||||
// Memory the host inspects afterwards: one block freed, one kept.
|
||||
static const char kept_text[] = "kept by gate a1";
|
||||
char *kept = malloc(sizeof kept_text);
|
||||
CHECK(kept != 0);
|
||||
memcpy(kept, kept_text, sizeof kept_text);
|
||||
gate_result.kept = kept;
|
||||
gate_result.freed = copy;
|
||||
free(copy);
|
||||
free(records);
|
||||
|
||||
// The report. Its handle is left open on purpose: ending the process has
|
||||
// to close it.
|
||||
static const wchar report_name[] = {'C', ':', '\\', 'g', 'a', 't', 'e', '-', 'a',
|
||||
'1', '.', 't', 'x', 't', 0};
|
||||
struct text report = {malloc(256), 0};
|
||||
CHECK(report.bytes != 0);
|
||||
put_text(&report, "gate a1\nrecords ");
|
||||
put_unsigned(&report, RECORDS);
|
||||
put_text(&report, "\nkeys ");
|
||||
put_unsigned(&report, gate_result.key_checksum);
|
||||
put_text(&report, "\nweighted ");
|
||||
put_unsigned(&report, weighted);
|
||||
put_text(&report, "\nfibonacci ");
|
||||
put_unsigned(&report, fibonacci(12));
|
||||
put_text(&report, "\nwide ");
|
||||
put_signed(&report, wide);
|
||||
put_text(&report, "\nstrings ");
|
||||
put_unsigned(&report, strlen(line));
|
||||
put_text(&report, " ");
|
||||
put_signed(&report, hex);
|
||||
put_text(&report, " ");
|
||||
put_signed(&report, negative);
|
||||
put_text(&report, "\nerrors ");
|
||||
put_unsigned(&report, missing);
|
||||
put_text(&report, " ");
|
||||
put_signed(&report, exhausted);
|
||||
put_text(&report, "\nfile ");
|
||||
put_unsigned(&report, bytes);
|
||||
put_text(&report, "\n");
|
||||
void *log = CreateFileW(report_name, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, 0);
|
||||
CHECK(log != INVALID_HANDLE);
|
||||
CHECK(WriteFile(log, report.bytes, report.used, &moved, 0) && moved == report.used);
|
||||
return GATE_A1_STATUS;
|
||||
}
|
||||
|
||||
#ifdef GATE_RETURN
|
||||
// Variant: the entry point returns its status instead of calling ExitProcess.
|
||||
u32 gate_entry(void) { return run(); }
|
||||
#else
|
||||
void gate_entry(void) {
|
||||
#ifdef GATE_MISSING
|
||||
if (!gate_result.magic)
|
||||
GateMissingService();
|
||||
#endif
|
||||
ExitProcess(run());
|
||||
}
|
||||
#endif
|
||||
Reference in new issue
Block a user