Compare commits

...
Author SHA1 Message Date
atharvranjan 4652eb08cb Integrate PR #267 with current native runtime
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:45:36 -06:00
atharvranjan d1bcd0249d Integrate PR #268 and clarify Win64 shadow-space expectations
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:44:49 -06:00
atharvranjan 097bb0b5b8 Merge commit '19f63a0' into integration/pr-284
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:43:15 -06:00
atharvranjan 2d77b35e56 Merge remote-tracking branch 'origin/main' into integration/pr-284
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 21:43:15 -06:00
atharvranjan 19f63a0985 Merge remote-tracking branch 'origin/main' into integration/pr-270
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:42:09 -06:00
atharvranjan 45322af82e Merge pull request #288 from MacosPorters/foc
Define BetterXen development phases and record migration repairs
2026-11-24 21:41:11 -06:00
atharvranjan aa9a961ef4 Remove README contributor avatar section
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:37:38 -06:00
atharvranjan 10347dc21b Document BetterXen development phases and migration check repairs
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:34:55 -06:00
atharvranjan 4d530392d1 Merge pull request #285 from MacosPorters/repo/add-codeowners
Add CODEOWNERS requiring maintainer review
2026-11-24 21:30:10 -06:00
atharvranjan f02eb2678e Add CODEOWNERS requiring maintainer review
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:21:45 -06:00
atharvranjan 19a905c30e Document migration archive refs as tags
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:01:27 -06:00
atharvranjan bfe0bbfaf7 Rename project and native applications to BetterXen
Update active repository links and coordination settings while retaining upstream history, notices, legacy library names and guest interfaces. Document the independent-copy migration and its limits.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 20:51:08 -06:00
Ranveer Soni 5442503d57 Merge pull request #421 from devil8blade/cursor/shader-cse-142
shader: opt-in IR common-subexpression elimination (#142)
2026-11-25 07:44:42 +05:30
devil8blade f0c61c7a91 loader: copy mid-size TLS templates into the zeroed block (#111)
Templates from 64 KiB up to 1 MiB were staged in a second buffer and
copied again into the thread block. Proving those bytes readable, then
copying them into the block that is already zeroed, avoids that buffer
and still maps nothing when the template cannot be read. Smaller
templates and templates of 1 MiB or more keep the single staged read,
which measured as fast or faster.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-24 21:01:31 -05:00
devil8blade 0caca18634 shader: opt-in IR common-subexpression elimination (#142)
Reuse the first equivalent pure vector unary or binary when
CompileOptions::eliminate_common_subexpressions is set. The flag defaults
off, so existing output stays byte-identical. Loads, stores, constant
definitions, lane masks, merges, branches and other side-effecting or
mask-dependent ops are not reused. Constant folding still runs first.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-24 20:49:19 -05:00
Ranveer Soni 2ea75603be Merge pull request #338 from LanaCodes-Boop/runtime/guest-clock-fixtures
loader: stop the mock clock wrapping and test time services against one clock (#204)
2026-11-25 06:56:35 +05:30
Ranveer Soni 6fc06dccff Merge branch 'main' into runtime/guest-clock-fixtures 2026-11-25 06:56:20 +05:30
Ranveer Soni a1295d5a48 Merge pull request #331 from zachdoxsee/task/329-gate-a1
loader: add process exit and the Gate A1 compiled C program (#329)
2026-11-25 06:55:50 +05:30
Ranveer Soni 20d7b9ece4 Merge pull request #376 from GDemay/perf/105-contiguous-data-access
loader: avoid resolver allocations in guest data access
2026-11-25 06:46:38 +05:30
zachdoxsee 0929d0214b Move the changelog entry down the list
Every merge to main adds its entry at the head of the Added list, and so did
this branch, so each of those merges put this branch in conflict over one
line. The entry is unchanged; it now sits lower down, in a place of its own.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:14:00 +01:00
zachdoxsee 66f7127553 Merge upstream main into task/329-gate-a1
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:10:46 +01:00
Ranveer Soni 714eaf49e2 Merge pull request #330 from devil8blade/cursor/shader-const-fold-141-5c9c
shader: opt-in IR constant folding with known-answer tests (#141)
2026-11-25 06:40:20 +05:30
devil8blade c93b505223 shader: opt-in IR constant folding with known-answer tests (#141)
Add CompileOptions::fold_constants and compile_with so pure vector unary
and binary ops between constants can fold after verification. Default
compile keeps the historical IR. Floating-point folding still uses the
exact positive-normal rules. Covered by hand-computed known-answer tests
and a fold-on versus fold-off check.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-25 01:05:13 +00:00
Ranveer Soni d8f7f2cb13 Merge pull request #380 from vedantdadhich21/fix/noncanonical-address-gp
fix(loader): raise GP for non-canonical data addresses (#379)
2026-11-25 06:34:40 +05:30
Ranveer Soni 042c08c855 Merge pull request #337 from zachdoxsee/task/333-pe-headers
loader: map the PE headers at the image base (#333)
2026-11-25 06:33:39 +05:30
Ranveer Soni 7e4ccd1e97 Merge pull request #316 from soggyramennoodle/feat/runtime-fuzz-bench
Runtime fuzzing, dispatch benchmarks, CRT string scans and MSVC name decoding
2026-11-25 06:32:53 +05:30
Ranveer Soni 96c772edc5 Merge pull request #398 from maridogolpeador/loader/121-shld-shrd
loader: add SHLD and SHRD, the double-precision shifts (#121)
2026-11-25 06:31:45 +05:30
zachdoxsee 9d94c0f40a Merge upstream main into task/329-gate-a1
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 01:56:40 +01:00
zachdoxsee 4e18000798 Merge upstream main into task/329-gate-a1
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 01:56:31 +01:00
maridogolpeador 67023d292b loader: add SHLD and SHRD, the double-precision shifts (#121)
Both engines refused SHLD and SHRD (0F A4/A5, 0F AC/AD) as illegal
instructions. They are now declared in the x86 registry and run on the
shared semantics for 16-, 32- and 64-bit register and memory
destinations, with the count in an 8-bit immediate or in CL.

- instructions.toml, x86_table.rs (generated), generate_x86.py,
  x86_decode.rs: the two operations and two operand encodings,
  rm_reg_imm and rm_reg_cl (ModRM destination, reg source, count).
- x86_exec.rs: the destination is shifted with the vacated bits filled
  from the source register. The count is masked to five bits (six for
  64-bit operands), a masked count of zero changes nothing, CF takes the
  last bit shifted out, ZF/SF/PF follow the result and OF is set only
  for a count of one. A 16-bit count above 16 is undefined in the SDM;
  the flags are kept and no test relies on the result.
- cpu_known_answers.rs: eight SDM-derived cases move from refused to
  verified.
- tests/x86: 72 assembled SHLD and SHRD instructions, with a
  bit-at-a-time reference in x86_integer.rs. A destination the
  reference marks undefined now skips the memory operand check too.
- docs/cpu/instruction-registry.md, CHANGELOG.md.

Nothing is lowered to ARM64.

Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com>
2026-11-24 20:47:45 -03:00
Adeeb Rahman 324eab08c3 Merge remote-tracking branch 'origin/main' into feat/runtime-fuzz-bench
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
2026-11-24 18:32:27 -05:00
Guillaume Demay 7d28fc89de loader: avoid resolver allocations for contiguous data access
Signed-off-by: Guillaume Demay <guillaumedemay@hotmail.fr>
2026-11-24 22:56:32 +01:00
Vedant Dadhich 9a29bd9c37 fix(loader): raise GP for non-canonical data addresses
Check canonical 48-bit address ranges in shared interpreter accesses, 16-byte SIMD paths, and every native DBT memory helper. Enable and expand the architectural known-answer group across operand widths, vector accesses, segment-base wrapping, boundary crossings, and valid canonical endpoints.

Signed-off-by: Vedant Dadhich <vedantdadhich21@gmail.com>
2026-11-25 03:21:14 +05:30
zachdoxsee e6fa931264 Merge upstream main into task/329-gate-a1
Any conflict was in CHANGELOG.md, where every entry is kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 22:24:13 +01:00
Arthur Lacoste af1b84ad75 loader: fix needless_range_loop in Win64 ABI tests (#201)
Address review feedback from zachdoxsee on PR #369: replace index-only XMM range loops with iterator-based loops so strict clippy passes on Rust 1.100.

Signed-off-by: Arthur Lacoste <arthurlacoste@users.noreply.github.com>
2026-11-24 22:14:29 +01:00
Arthur Lacoste cf438e25aa Merge remote-tracking branch 'origin/main' into runtime/win64-service-abi-201
# Conflicts:
#	CHANGELOG.md
2026-11-24 22:13:14 +01:00
zachdoxsee 04ee981103 Merge upstream main into task/329-gate-a1
Any conflict was in CHANGELOG.md, where every entry is kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 22:01:29 +01:00
zachdoxsee 35de41bd5f Merge upstream main into task/329-gate-a1
Conflict in CHANGELOG.md only: every entry is kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 21:43:49 +01:00
plokhi d35c278284 Clarify ARM64 encoding audit coverage
Signed-off-by: plokhi <37208555+Plokhi@users.noreply.github.com>
2026-11-24 21:33:37 +01:00
plokhi fbec436b89 Fix ARM64 variable shift register encoding
Signed-off-by: plokhi <37208555+Plokhi@users.noreply.github.com>
2026-11-24 21:19:38 +01:00
Arthur Lacoste 7246ab5ea6 loader: add Win64 service ABI preservation tests (#201)
Add dispatch and DBT-backed runtime service tests that verify Win64 callee entry alignment, caller-owned shadow space, return state, and preservation of nonvolatile GPRs/XMM registers across registered service calls.

AI-Assisted: Codex (GPT-5) helped draft the tests; I reviewed the diff and ran fmt/clippy(loader)/loader tests locally.
Signed-off-by: Arthur Lacoste <arthurlacoste@users.noreply.github.com>
2026-11-24 20:57:41 +01:00
zachdoxsee a0d4b7bf5d Merge upstream main into task/329-gate-a1
Conflict in CHANGELOG.md only: every entry is kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 20:21:39 +01:00
Swastickc 729e1b4cb1 loader: draw nothing for zero-instance flat draws and reject unsupported ones (#148)
Flat DrawInstanced ignored InstanceCount, StartInstanceLocation and
StartVertexLocation, so a zero-instance draw still drew and a changed
start vertex drew the first triangle. Zero instances or fewer than three
vertices now draw nothing; other unsupported parameters fail with
GraphicsError::Unsupported. Vertex reads use the range-checked
read_resource, so a view past its buffer or an overflowing guest address
fails with IndexOutOfRange.

Add tests/repeated_frames.rs: repeated reset, record, close and execute
frames with hand-derived pixels on the software reference backend.

Signed-off-by: Swastickc <28708247+Swastickc@users.noreply.github.com>
2026-11-25 00:34:19 +05:30
zachdoxsee 830f93ff14 loader: address review of process exit and the Gate A1 program (#329)
- An ExitProcess call in a TLS callback is a normal startup outcome with
  its status. The remaining callbacks and the entry point do not run.
- Exit closes Winsock sockets and task-queue handles as well as kernel
  objects, and open_handle_count counts all three tables.
- Startup reserves the page holding the entry-return and callback-return
  addresses, so an image mapped over them is refused and a guest
  allocation there fails.
- The Gate A1 program checks unequal memcmp results and compares the
  bytes it read back without memcmp.
- The gate test builds in a directory of its own per test process.
- The build script checks its tools and their libraries with file,
  lipo -archs and otool -L.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 19:55:20 +01:00
zachdoxsee 4962f054c8 Merge upstream main into task/329-gate-a1
Conflict in CHANGELOG.md only: both new entries are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 19:47:49 +01:00
zachdoxsee 48e1e5c8c1 Merge upstream main into task/329-gate-a1
Conflict in CHANGELOG.md only: both new entries are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 18:24:36 +01:00
LanaCodes-Boop 94732d90ca Merge remote-tracking branch 'upstream/main' into runtime/guest-clock-fixtures
Signed-off-by: LanaCodes-Boop <139008131+LanaCodes-Boop@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 14:22:11 -03:00
LanaCodes-Boop 1e8893a6bf loader: stop the mock clock wrapping and test time services against one clock (#204)
Signed-off-by: LanaCodes-Boop <139008131+LanaCodes-Boop@users.noreply.github.com>
2026-11-24 14:21:14 -03:00
zachdoxsee 47cb26ebdd loader: add process exit and the Gate A1 compiled C program (#329)
A guest can now end its process. kernel32.dll!ExitProcess stops execution
with the new ExitReason::ProcessExit(status), keeping all 32 bits of the
status, and never ends the host. A returning entry point does the same
with EAX: startup puts an exit address under the entry point. The exit
closes every guest handle, and the DbtEngine that ran the guest executes
no further guest instruction.

Gate A1 is an original C program with no C library linked. The test
builds it from source with clang and an LLD, runs it through
run_synthetic_startup, the standard services and the DBT at four
optimization levels, and checks its exit status, report, files and
memory against values recomputed in Rust. Three controls must fail in
the stated way. Gate A stays open until the hosted milestone, A2.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 17:42:09 +01:00
Adeeb RahmanandCursor eaeab25590 Record corrected runtime_services fuzz campaign evidence
Withdraw the unreachable-dispatch campaign counts and replace them with
the post-fix 300-second run (96,589 inputs, 4,008 coverage edges) plus
the XMemAlloc OOM that campaign found.

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

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

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

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

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

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

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

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
# Every change needs a review from the maintainers team.
* @MacosPorters/maintainers
+5 -6
View File
@@ -1,9 +1,8 @@
{
"lease_hours": 168,
"upstream": "ranveersoni98/Xenora",
"maintainers": ["ranveersoni98"],
"contributors": {
"ranveersoni98": ["cpu", "shared", "qa"],
"elforeign": ["gpu", "shared", "qa"]
}
"upstream": "MacosPorters/betterxen",
"maintainers": [
"Arths17"
],
"contributors": {}
}
+2 -2
View File
@@ -72,8 +72,8 @@ jobs:
LC_ALL=C PYTHONCOERCECLOCALE=0 PYTHONUTF8=0 scripts/audit/claims.sh
- name: Inspect native CLI
run: |
cargo build --locked -p xenora
binary=target/aarch64-apple-darwin/debug/xenora
cargo build --locked -p betterxen
binary=target/aarch64-apple-darwin/debug/betterxen
file "$binary"
test "$(lipo -archs "$binary")" = arm64
otool -L "$binary"
+6 -6
View File
@@ -1,4 +1,4 @@
# Xenora engineering rules
# BetterXen engineering rules
### Native Apple Silicon
@@ -7,7 +7,7 @@ Never introduce Rosetta 2, x86-64 host executables, MoltenVK, Vulkan runtime dep
- SPIR-V is permitted as a compiler intermediate representation. It does not justify a Vulkan runtime.
- All host executables and native dependencies must support ARM64. Verify with file, lipo -archs and otool -L.
- Never run Intel binaries through Rosetta, even temporarily. Never add a dependency that requires Rosetta to build or run. If a dependency cannot run natively, find an alternative or document the limitation.
- The guest architecture being decoded may be x86-64, but Xenora itself runs natively on ARM64.
- The guest architecture being decoded may be x86-64, but BetterXen itself runs natively on ARM64.
- Support M1 through M5 and future generations through runtime capability detection. Do not assume all Apple GPUs share capabilities.
- Use aarch64-apple-darwin as the Rust target.
@@ -20,7 +20,7 @@ Never introduce Rosetta 2, x86-64 host executables, MoltenVK, Vulkan runtime dep
- Never replace GPU tests with mocks and then claim GPU support.
- Unknown information is classified as unknown and becomes a documented research task.
- Every hardware claim carries an evidence class (section 9). Never present a lower-class claim as if it were a higher-class one.
- Never claim "verified on Xbox hardware". Xenora has no Xbox hardware access. Agreement with a spec-derived reference is not agreement with Xbox hardware, and docs must say so.
- Never claim "verified on Xbox hardware". BetterXen has no Xbox hardware access. Agreement with a spec-derived reference is not agreement with Xbox hardware, and docs must say so.
- Do not hide errors behind fallbacks. Do not translate unsupported instructions into silent no-ops. Do not weaken or delete tests to make them pass. Do not change mutation counting, tolerances or gate definitions to improve a score.
### Independence of verification
@@ -32,9 +32,9 @@ Never introduce Rosetta 2, x86-64 host executables, MoltenVK, Vulkan runtime dep
- Use only publicly accessible documentation and authorized materials. Never obtain or use leaked SDKs, confidential Xbox documentation, restricted console tools, firmware, encryption keys, or proprietary game binaries and shader collections. Do not attempt to bypass documentation access restrictions.
- Contributors who have seen leaked or confidential Xbox materials must not contribute. State this in CONTRIBUTING.md and require a DCO sign-off (Signed-off-by) on contributions.
- Include a plain statement in docs/legal.md: Xenora does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation. Add a note that this is not legal advice and that contributors should know their local laws, including anti-circumvention provisions such as DMCA section 1201.
- Include a plain statement in docs/legal.md: BetterXen does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation. Add a note that this is not legal advice and that contributors should know their local laws, including anti-circumvention provisions such as DMCA section 1201.
- Before copying or adapting any upstream code: verify the exact license of that file (not just the repo), check GPL-3.0-or-later compatibility, preserve copyright notices, record source repository and exact commit, document modifications, include required attribution. Never remove upstream copyright notices. If licensing is uncertain, stop using that code until resolved.
- Keep Xenora's emulator implementation original. Never copy, port, translate or adapt emulator source from Leonida, KyTx, AnyPS5 or similar projects.
- Keep BetterXen's emulator implementation original. Never copy, port, translate or adapt emulator source from Leonida, KyTx, AnyPS5 or similar projects.
- Validate the technical compatibility and safety of user-provided files. Do not ask for ownership receipts, accounts or acquisition provenance as part of file loading. Contributor provenance and licensing obligations still apply.
- Never place restricted material in the repository or its Git history.
- Do not push, publish, or change remote visibility without explicit user authorization. Prepare locally and report readiness.
@@ -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.
+27
View File
@@ -10,6 +10,13 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Changed
- TLS setup now copies templates from 64 KiB up to 1 MiB straight into the zeroed thread data block, after checking that every template byte is readable, instead of staging them in a second buffer (#111). The pointer array and data block layout, the TLS index write and the error for an unreadable template are unchanged, and nothing is mapped when the template cannot be read. On an Apple M2 Pro, median setup time for original synthetic templates over 31 interleaved samples fell by 21.7 % at 64 KiB, 19.0 % at 256 KiB and 14.2 % at 768 KiB. Smaller and larger templates keep the single staged read and showed no change beyond run-to-run variation.
- Removed the contributor avatar section from the README.
- Added `.github/CODEOWNERS` so pull requests request review from the `MacosPorters/maintainers` team. With the `main` branch rule that requires code-owner review, a maintainer must approve each change before it merges.
- Repaired destination issue links in 20 migrated PR descriptions while retaining the imported text, attribution and contributor certifications. Template and review requirements remain in place.
- Moved 163 unused migration PR refs from branches to verified archive tags, retaining the 22 open-PR branches. Historical refs no longer clutter the branch list or produce recent-push PR prompts.
- Renamed the project branding and native app and primary CLI package/binary to BetterXen (`betterxen`), and updated active repository links to `MacosPorters/betterxen`. Legacy `xenora-*` library packages and synthetic guest ABI names remain for compatibility. Upstream licenses, notices and historical evidence are retained.
- 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.
@@ -22,15 +29,23 @@ remains unsupported.
- Moved the six hand-written gfx1030 VOP2 logical and shift forms (`v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`, `v_ashrrev_i32`, AMD guide section 12.7) into the semantic registry under a new VGPR-only operand rule `vop2_vgpr2`, with no behaviour change: a sweep of 132,608 VOP2, VOP1 and SOP1 words decodes to the same text, length and error before and after, the MSL goldens are unchanged, and the runtime-region allowlist admits exactly the same six forms. The per-lane `VectorBinary` gained `And`, `Or`, `Xor` and the three shifts (count masked to S0[4:0]); 6 hand-written instruction variants and their decoder and lowering arms are gone (17 hand-written forms remain). Part of #215.
- Added non-blocking Metal compute submission through `submit_words` and `wait`, with completion-aware resource retirement and a sixteen-dispatch in-flight limit. Synchronous calls keep their existing behavior. The benchmark reports the host submission split and compares synchronous and pipelined batches.
- Reuse up to 16 native Metal compute pipelines per context for repeated shader source and entry points. Pending dispatches retain their pipelines through completion, including after eviction. Dispatch profiles report zero library and pipeline setup time when a cached pipeline is reused. Closes #132.
- Avoided resolver allocations for permitted guest data reads and writes contained in one mapping, preserving checked fallback for split spans and faults (#105).
- 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
- Added a Win64 ABI regression showing that a service may write the caller-allocated shadow space. Existing negative controls cover nonvolatile XMM-register corruption; the unchanged-home-slot test now describes its handler rather than implying an ABI preservation requirement.
- Added a BetterXen development phase plan based on current source, pending PRs and existing acceptance records, linked from both contributor entry points. It separates baseline reconciliation, hosted C execution, guest threading, translated rendering, application integration and measured optimization; no new runtime or compatibility acceptance is claimed.
- Added `tests/runtime_clock.rs`, which reads the performance counter, its frequency, both tick counts, the unbiased interrupt time and the system time from one injected clock and checks that they report the same elapsed time in their own units, after a host advance and after a guest `Sleep`, and that none of them decreases up to and past the end of the clock (#204). Expected values are worked out by hand from the documented units. Timed waits still return without consuming clock time.
- Added opt-in shader IR constant folding (`CompileOptions::fold_constants` / `compile_with`) for pure vector unary and binary ops whose operands are already constants (#141). Floating-point ops still use the exact positive-normal rules; loads, stores, lane masks, merges and branches are never folded. Default `compile` keeps the historical IR. Covered by hand-computed known-answer compiler tests (shifts by 32/33, ashr, min_i32 vs min_u32, mul_hi_i32_i24, ffbh_i32, exact float fold, load-derived float non-fold, and verify rejection of inexact constant float add) with a fold-on versus fold-off check, plus an MSL template drift check over every foldable op.
- Added opt-in shader IR common-subexpression elimination (`CompileOptions::eliminate_common_subexpressions` / `compile_with`) that reuses the first result of an equivalent pure vector unary or binary (#142). Equivalence is the same operation and the same operand values in the same order; constant operands match by bit pattern. Loads, stores, constant definitions, lane masks, merges, branches and other side-effecting or execution-mask-dependent ops are left in place. The pass runs after constant folding, so folded results stay constants and a later pure op on two equal folded constants can still be reused. Default `compile` keeps the historical IR. Covered by hand-derived known-answer compiler tests for reuse (and/xor, not, exact float add), for rejected loads, swapped subtracts, lane masks, lane merges and VCC selects, and for the four combinations with constant folding (1 + 2 = 3, and 1.0 + 2.0 = 3.0), and a check that the 13 golden fixtures, none of which repeats an expression, compile unchanged with the pass on. No speedup is claimed.
- The loader now maps an image's PE headers at its image base (#333): the first `SizeOfHeaders` bytes of the file, read-only, in whole 4 KiB pages that are zero past `SizeOfHeaders`. Programs read their own headers this way; the mingw-w64 C runtime does so before `main`, and until now that read faulted. When startup relocates an image it writes the load base into the mapped `ImageBase` field after the relocations, so an entry aimed at that field cannot move it twice; this is Xenora's policy and has not been compared with Windows. A load is refused with the new `PeError::InvalidHeaderSize` when `SizeOfHeaders` is zero, ends before the section table, runs past the file, or its pages would reach into a section, and when the bytes handed to the loader are not the PE32+ headers that were parsed. The page rule refuses images with sub-page section alignment whose first section starts inside the header page, which loaded before. The header pages count toward the 256 MiB mapping budget, which is checked before anything is mapped. `ParsedPe::parse` and the static probe are unchanged. `tests/pe_headers.rs` covers guest reads at the preferred and a relocated base, a relocation aimed at `ImageBase`, the write and execute faults and each refusal with original hand-built images; the image in `pe_mapping_limits.rs` now carries a valid `SizeOfHeaders`. Awaiting independent re-review.
- Added 35 known-answer cases for MOV with an immediate operand, opcodes C6 /0 and C7 /0 (#194), to `cpu_known_answers.rs`: byte, word, dword and qword stores through base, SIB, R12, R13, RSP and RBP addressing with 8-bit and 32-bit displacements; the imm32 sign extension of the 64-bit form; the register forms, including AH and a REX-selected SIL; unmapped and read-only store faults at each width; and #UD for reg field 1. Expected values come from the Intel SDM and were worked out by hand. The interpreter and the DBT already agreed with all of them, so this is new coverage and fixes no defect. The 16-bit forms covered are those that already run, and #118 stays open. Not compared with x86 hardware; awaiting independent review.
- Added Win64 service-call ABI tests in `crates/loader/tests/runtime_services.rs` for #201. A dispatch-level test and a DBT guest-call test verify 16-byte-aligned call entry (`RSP % 16 == 8`), caller-owned 32-byte shadow space accessibility/integrity, return-value/stack/RIP return state, and preservation of RBX/RBP/RDI/RSI/R12-R15 and XMM6-XMM15 across registered service calls. Expected values are derived from the Microsoft x64 calling convention, not from current implementation behavior.
- `dbt_bench` can also write its results as one JSON document when `XENORA_DBT_BENCH_JSON=<path>` is set (#112). The document records the host CPU, OS and architecture, the git revision and whether the tree had local changes, debug assertions, the workload and sample counts, the median, minimum, maximum, p95, p99, IQR and MIPS for the interpreter and for cold and warm DBT, and the cold DBT counters. Anything the benchmark cannot determine is `null`. The text output and the timed work are unchanged.
- Added synthetic guest handle-lifetime regression tests (#205) for capacity reuse, stale handles, duplicate rights and lifetime, wrong object types, thread pseudo handles and failed-output nonmutation. Runtime behavior is unchanged; independent acceptance is pending.
- Added a documented independent acceptance rule for promoting AMD RDNA2 desktop GPU (gfx1030) forms from local CPU and Metal results to `fixture verified`, including clean-commit evidence, reviewer independence, raw-log location, review-log summary, failure handling and status regeneration (#302).
@@ -45,6 +60,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.
@@ -82,6 +98,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.
@@ -90,6 +112,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.
@@ -215,9 +239,12 @@ remains unsupported.
native DBT.
### Fixed
- `MockClock::advance` no longer wraps the FILETIME. A large advance made the synthetic wall clock run backwards while the performance count beside it stopped at its maximum; both now stop at their maximum (#204).
- Fixed `DuplicateHandle` and `GetThreadId` naming the main thread from other guest threads, `OwningThread` in critical sections always holding the main thread's ID, the callback-depth limit being shared by all guest threads, and pending one-time initializations being unbounded.
- Fixed the address reported when a guest memory access faults part-way across a 4 KiB page boundary (#175). An access that starts in a mapped page and runs into an unmapped or forbidden one now reports the first byte it may not touch; it used to report the start of the access. An access whose first byte fails reports the same address as before, and a failed access still reads and writes nothing. Three Intel SDM page-fault cases in `cpu_known_answers.rs` moved from open defect to verified on both engines. `crates/loader/tests/memory_page_boundaries.rs` checks permissions, adjacent pages, address overflow and the fault address at every 4 KiB guest boundary across two host pages (16 KiB each on Apple Silicon). Guest memory is checked in software, so the host page size does not affect these results. Four #82 expectations and one CRT `memmove` expectation that pinned the start address were corrected. Not compared with x86 hardware; awaiting independent review.
- Fixed the native dependency audit reading Cargo JSON and inspection-tool output in the process locale encoding; it now reads and reports UTF-8 paths and diagnostics under an ASCII locale (#363).
- Fixed a latent ARM64 `LSLV` encoding bug that forced bit 1 of the shift-count register field (part of #131). The dynamic binary translator uses `X10` in its only call, which already has that bit set. `RBIT`, `CLZ` and `LSLV` now panic on out-of-range register numbers before emitting an instruction. Encoding tests use words checked against LLVM's assembler.
- Fixed flat (untextured) guest `DrawInstanced` draws in the synthetic D3D12-style graphics context (#148). A draw with zero instances or fewer than three vertices now draws nothing. A non-zero start vertex or start instance, more than one instance or more than three vertices now fails with `GraphicsError::Unsupported` instead of drawing the view's first triangle. Vertex reads stay inside the vertex buffer, so a view past its end, or one whose guest address would overflow, fails with `IndexOutOfRange` instead of reading neighbouring guest memory or panicking. `crates/loader/tests/repeated_frames.rs` runs these through repeated reset, record, close and execute frames on the software reference backend, with hand-derived pixels; no native Metal result is claimed.
- Made the static probe and the binder share one bounded import parser, after the truncated-name fix for #270. Truncated, unterminated, empty or non-ASCII names, reserved bits and endless tables are reported by the probe and refused by the binder.
- Fixed TLS callback metadata that was accepted or misread without an error (#78). A non-zero `AddressOfCallbacks` outside the image's sections, or 4 GiB or more above the image base, is now refused; it used to mean "no callbacks" or read the list from an unrelated place. The callback list must reach its null entry inside its section, where the section's zero-filled tail counts, and a list of more than 64 callbacks is refused where it used to be cut short. `execute_tls_callbacks` refuses a stack top that is not 16-byte aligned or cannot hold the entry frame, which used to overflow a subtraction, and a file cut inside the TLS data-directory entry no longer panics the parser. `TlsError` gains four variants for these cases. Twelve unit tests in `crates/loader/src/tls.rs` use original headers and code, and also check the argument registers, the stack pointer at entry and after return, callback order and the instruction budget. Expectations come from Microsoft's public PE Format and x64 calling convention pages; nothing ran on Windows, and independent review is pending.
- Fixed the thread's TLS pointer naming the TLS data itself (#76). Compiled code loads the pointer from the thread environment block, indexes it by the module's TLS index to get the address of the data block, and then adds a variable's offset; the loader had mapped the data where the pointer array belongs, so the first eight bytes of the template were used as the block address. `setup_tls` now maps a pointer array at the thread's TLS base and the data block one page above it, and stores the block address in the slot of the index it assigns. `crates/loader/tests/tls_layout.rs` follows that access sequence through guest memory for a template with zero fill, a rebased image and a zero-fill-only directory. The data block of the fixture harness can now be at most 60 KiB, down from 64 KiB, before it would meet the thread environment block. Alignment requests above 4 KiB and more than one module's TLS are not handled. The access sequence follows Microsoft's public PE Format page; nothing ran on Windows, and independent review is pending.
+2 -2
View File
@@ -1,6 +1,6 @@
# Code of Conduct
Xenora welcomes contributors with different backgrounds and experience levels. Discussions should be about the technical work and conducted with respect.
BetterXen welcomes contributors with different backgrounds and experience levels. Discussions should be about the technical work and conducted with respect.
## Expected behavior
@@ -19,4 +19,4 @@ If possible, use an available private contact channel for a repository maintaine
Maintainers may remove content, limit participation or block accounts when necessary to protect the community. Responses should be proportionate to the behavior and protect the privacy of affected people. Do not retaliate against anyone reporting a concern in good faith.
This policy applies to repository issues, pull requests, discussions and other spaces officially managed by Xenora.
This policy applies to repository issues, pull requests, discussions and other spaces officially managed by BetterXen.
+4 -4
View File
@@ -1,6 +1,6 @@
# Contributing to Xenora
# Contributing to BetterXen
Xenora is an experimental Xbox Series X|S recompilation framework for Apple Silicon. Its graphics subsystem, XenoMetal, targets native Metal execution. Contributions should improve verified behavior rather than expand untested claims.
BetterXen is an experimental Xbox Series X|S recompilation framework for Apple Silicon. Its graphics subsystem, XenoMetal, targets native Metal execution. Contributions should improve verified behavior rather than expand untested claims.
## Getting started
@@ -28,11 +28,11 @@ For a performance change, provide reproducible before-and-after results using eq
## Research and clean-room policy
Use publicly accessible specifications and authorized materials only. Do not submit leaked SDKs, confidential documentation, firmware, keys, proprietary game binaries or unauthorized shader dumps. Under Xenora's clean-room policy, anyone who has accessed leaked or confidential Xbox materials must not contribute. Do not post details of restricted material in issues or PRs.
Use publicly accessible specifications and authorized materials only. Do not submit leaked SDKs, confidential documentation, firmware, keys, proprietary game binaries or unauthorized shader dumps. Under BetterXen's clean-room policy, anyone who has accessed leaked or confidential Xbox materials must not contribute. Do not post details of restricted material in issues or PRs.
Distinguish desktop RDNA behavior from Xbox-specific behavior. Cite primary sources with exact applicable architectures and record uncertainties using the project's evidence classification when available. Tests on Apple GPUs do not establish verification on Xbox hardware.
Xenora implements its own Rust guest runtime, decoder, typed IR, shader
BetterXen implements its own Rust guest runtime, decoder, typed IR, shader
compiler and native Metal backend from public technical specifications
and independently derived tests. Contributions must not copy, port or
adapt code, decoder tables, internal metadata or implementation
Generated
+1 -1
View File
@@ -150,7 +150,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]]
name = "xenora"
name = "betterxen"
version = "0.1.0"
dependencies = [
"xenora-decoder",
+21 -23
View File
@@ -1,23 +1,25 @@
# Xenora
# BetterXen
BetterXen is a community-maintained continuation. Original Git history, licenses and contributor attribution are retained. See the [project history and migration notes](docs/migration.md) for source attribution and imported issue and pull-request records.
**Experimental Xbox Series X|S emulation research for Apple Silicon Macs.**
Xenora is an open-source project written primarily in Rust that builds and verifies a native, bounded execution environment on Apple Silicon: an independent x86-64 guest path, original PE32+ loading, AMD RDNA 2 shader translation, and a native Apple Metal graphics backend.
BetterXen is an open-source project written primarily in Rust that builds and verifies a native, bounded execution environment on Apple Silicon: an independent x86-64 guest path, original PE32+ loading, AMD RDNA 2 shader translation, and a native Apple Metal graphics backend.
**No Wine. No CrossOver. No Rosetta. No Vulkan runtime.**
Xenora is still experimental. Verified work is restricted to independently authored synthetic programs and shaders; authentic Xbox executable loading, system-service compatibility and commercial game execution remain unsupported. See the [current limitations](#current-limitations).
BetterXen is still experimental. Verified work is restricted to independently authored synthetic programs and shaders; authentic Xbox executable loading, system-service compatibility and commercial game execution remain unsupported. See the [current limitations](#current-limitations).
> [!CAUTION]
> **Xenora strictly opposes piracy.** Xenora is an independent, clean-room, general-purpose emulation research project that neither distributes copyrighted game files nor supports unauthorized content, DRM circumvention, or leaked materials. Use only legally obtained software. Xenora is not affiliated with Microsoft or any other publisher or platform holder.
> **BetterXen strictly opposes piracy.** BetterXen is an independent, clean-room, general-purpose emulation research project that neither distributes copyrighted game files nor supports unauthorized content, DRM circumvention, or leaked materials. Use only legally obtained software. BetterXen is not affiliated with Microsoft or any other publisher or platform holder.
[![Native Rust checks](https://github.com/ranveersoni98/Xenora/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/ranveersoni98/Xenora/actions/workflows/ci.yml)
[![Native Rust checks](https://github.com/MacosPorters/betterxen/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/MacosPorters/betterxen/actions/workflows/ci.yml)
---
## What works today?
Xenora has progressed from executing individual x86-64 instructions to running original PE32+ guest programs that interact with translated GPU workloads on Apple Silicon.
BetterXen has progressed from executing individual x86-64 instructions to running original PE32+ guest programs that interact with translated GPU workloads on Apple Silicon.
The latest verified milestones include **translated gfx1030 vertex and pixel shaders executing through native Apple Metal**, the native Metal **blend pass** (`NativeCompute::render_blend`) and **indexed triangle draws** (`NativeCompute::render_indexed`) into offscreen targets, with rendered pixels compared against independently calculated reference results.
@@ -51,13 +53,13 @@ The latest verified milestones include **translated gfx1030 vertex and pixel sha
| X24 — Gameplay and performance | Expand rendering correctness, input, audio, memory management, shader caching and execution performance | Long-term goal |
| X25 — Running games | Achieve reproducible, stable execution of compatible games on native Apple Silicon macOS using Metal | Long-term goal |
**Roadmap note:** X10–X25 are proposed engineering milestones, not completed implementations or a guaranteed sequence. Actual priorities will change as compatibility testing reveals new blockers. Successfully completing one milestone does not guarantee that a particular game will run.
**Roadmap note:** X10–X25 are proposed engineering milestones, not completed implementations or a guaranteed sequence. Follow the [BetterXen development phases](docs/development-phases.md) for the current work order and existing issue/PR dependencies. Actual priorities will change as compatibility testing reveals new blockers. Successfully completing one milestone does not guarantee that a particular game will run.
All existing verification refers to independently authored synthetic programs and shaders. Commercial-game compatibility remains unverified.
## Native graphics translation
Xenora's graphics pipeline translates a supported subset of AMD RDNA 2 instructions into Metal Shading Language.
BetterXen's graphics pipeline translates a supported subset of AMD RDNA 2 instructions into Metal Shading Language.
The translation process is:
@@ -164,7 +166,7 @@ The resource system remains experimental. Native GPU work already in flight duri
## Texture support
Xenora includes original texture upload, readback and block-compression paths.
BetterXen includes original texture upload, readback and block-compression paths.
Implemented and tested functionality includes:
@@ -183,7 +185,7 @@ Xbox-specific texture layouts and additional compression formats require further
## Architecture
Xenora is organized around three connected subsystems: guest execution, shader translation and native GPU execution.
BetterXen is organized around three connected subsystems: guest execution, shader translation and native GPU execution.
```mermaid
flowchart TD
@@ -230,7 +232,7 @@ flowchart TD
end
```
Xenora's host execution environment is native ARM64. The guest architecture being interpreted is x86-64.
BetterXen's host execution environment is native ARM64. The guest architecture being interpreted is x86-64.
The native graphics pipeline runs translated vertex and pixel stages, the indexed-draw and blend passes and the depth pass into offscreen Metal targets, with GPU readback compared against independent CPU references.
@@ -242,7 +244,7 @@ See [Interface Contracts](docs/interfaces.md) for the documented execution and r
## Current limitations
Xenora is an engineering research project, not a working commercial-game emulator.
BetterXen is an engineering research project, not a working commercial-game emulator.
The following remain unsupported or incomplete:
@@ -257,13 +259,13 @@ The following remain unsupported or incomplete:
| Performance | Production-scale workloads, CPU/GPU profiling and optimized execution |
| Game compatibility | No demonstrated execution of commercial Xbox titles |
Xenora's current shader fixtures target a bounded subset of desktop gfx1030 behavior. This is not equivalent to complete Xbox Series GPU compatibility.
BetterXen's current shader fixtures target a bounded subset of desktop gfx1030 behavior. This is not equivalent to complete Xbox Series GPU compatibility.
Progress is measured by reproducible tests rather than estimated game compatibility percentages.
---
## Building Xenora
## Building BetterXen
### Requirements
@@ -278,15 +280,15 @@ The recorded Apple M5 environment uses Rust 1.100.0 and Xcode 27.2.
### Clone
```sh
git clone https://github.com/ranveersoni98/Xenora.git
cd Xenora
git clone https://github.com/MacosPorters/betterxen.git
cd betterxen
```
### Build
```sh
scripts/bootstrap.sh
cargo build --locked -p xenora
cargo build --locked -p betterxen
```
### Run core tests
@@ -359,16 +361,12 @@ See the [roadmap table](#development-milestones) for proposed milestones, and th
---
### Contributors
[![Contributors](https://contrib.rocks/image?repo=ranveersoni98/Xenora)](https://github.com/ranveersoni98/Xenora/graphs/contributors)
## License
Xenora is licensed under the [GNU General Public License v3 or later](LICENSE).
BetterXen is licensed under the [GNU General Public License v3 or later](LICENSE).
See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for third-party attribution and [docs/legal.md](docs/legal.md) for the project's research and legal boundaries.
Xenora is an independent open-source project and is not affiliated with Microsoft, Xbox, Rockstar Games or Apple.
BetterXen is an independent open-source project and is not affiliated with Microsoft, Xbox, Rockstar Games or Apple.
---
+2 -2
View File
@@ -2,13 +2,13 @@
## Scope
Xenora is experimental and is not currently represented as a security-hardened runtime. Treat shaders, binary containers, caches and native library inputs as untrusted. Do not use it to process untrusted content in a sensitive environment.
BetterXen is experimental and is not currently represented as a security-hardened runtime. Treat shaders, binary containers, caches and native library inputs as untrusted. Do not use it to process untrusted content in a sensitive environment.
The project does not promise a fixed security support window at this stage. Report issues against a specific revision, preferably reproduced on current `main` where safe.
## Reporting vulnerabilities
Use [GitHub private vulnerability reporting](https://github.com/ranveersoni98/Xenora/security/advisories/new), if enabled. If it is unavailable, request a private reporting channel without disclosing exploit details publicly. Do not open a public issue containing sensitive vulnerability details, credentials, or private data.
Use [GitHub private vulnerability reporting](https://github.com/MacosPorters/betterxen/security/advisories/new), if enabled. If it is unavailable, request a private reporting channel without disclosing exploit details publicly. Do not open a public issue containing sensitive vulnerability details, credentials, or private data.
Include the affected commit, environment, affected component, expected and actual behavior, impact and a minimal, authorized reproduction. Use synthetic inputs wherever possible. Do not attach protected content, leaked SDK material or proprietary shaders.
+3 -3
View File
@@ -1,9 +1,9 @@
# Getting help
Start with the [README](README.md) and the relevant documentation in the repository, if available. Xenora is an experimental research project, not a commercial game compatibility service.
Start with the [README](README.md) and the relevant documentation in the repository, if available. BetterXen is an experimental research project, not a commercial game compatibility service.
- Use [GitHub Issues](https://github.com/ranveersoni98/Xenora/issues) for reproducible bugs, feature proposals, research findings and hardware verification reports.
- Use [GitHub Discussions](https://github.com/ranveersoni98/Xenora/discussions) for general questions if Discussions is enabled. Otherwise, search existing issues before filing a relevant question.
- Use [GitHub Issues](https://github.com/MacosPorters/betterxen/issues) for reproducible bugs, feature proposals, research findings and hardware verification reports.
- Use [GitHub Discussions](https://github.com/MacosPorters/betterxen/discussions) for general questions if Discussions is enabled. Otherwise, search existing issues before filing a relevant question.
- Follow [SECURITY.md](SECURITY.md) for security-sensitive reports.
Include the exact revision, host architecture, macOS version, relevant tool versions, steps to reproduce and sanitized output. Do not share personal paths, private account information, protected game assets, credentials or confidential material. If the reported feature is not yet implemented, identify it as a request rather than a regression.
+2 -2
View File
@@ -4,10 +4,10 @@
import PackageDescription
let package = Package(
name: "Xenora",
name: "BetterXen",
platforms: [.macOS(.v14)],
targets: [
.systemLibrary(name: "CXenora", path: "Sources/CXenora"),
.executableTarget(name: "Xenora", dependencies: ["CXenora"]),
.executableTarget(name: "BetterXen", dependencies: ["CXenora"], path: "Sources/Xenora"),
]
)
+3 -3
View File
@@ -834,13 +834,13 @@ struct ContentView: View {
}
}
struct XenoraApp: App {
struct BetterXenApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
let model = FrameModel()
let loop = FrameLoopModel()
var body: some Scene {
WindowGroup("Xenora") { ContentView(model: model, loop: loop) }
WindowGroup("BetterXen") { ContentView(model: model, loop: loop) }
}
}
@@ -1015,4 +1015,4 @@ if CommandLine.arguments.contains("--smoke") {
print(probe.summary)
exit(probe.connected ? 0 : 1)
}
XenoraApp.main()
BetterXenApp.main()
+1 -1
View File
@@ -1,5 +1,5 @@
[package]
name = "xenora"
name = "betterxen"
version.workspace = true
edition.workspace = true
license.workspace = true
+18 -17
View File
@@ -13,7 +13,7 @@ fn main() -> ExitCode {
match std::env::args().nth(1).as_deref() {
Some("info") => {
println!(
"Xenora {} ({})",
"BetterXen {} ({})",
env!("CARGO_PKG_VERSION"),
std::env::consts::ARCH
);
@@ -21,7 +21,7 @@ fn main() -> ExitCode {
}
Some("inspect") => {
let Some(file_path) = std::env::args().nth(2) else {
eprintln!("usage: xenora inspect <path-to-pe-binary>");
eprintln!("usage: betterxen inspect <path-to-pe-binary>");
return ExitCode::from(2);
};
match xenora_loader::triage_file(&file_path) {
@@ -90,7 +90,7 @@ fn main() -> ExitCode {
let Some(pe) = pe_path else {
eprintln!(
"usage: xenora probe --pe <path> [--mode <static>] [--report <output-dir>]"
"usage: betterxen probe --pe <path> [--mode <static>] [--report <output-dir>]"
);
return ExitCode::from(2);
};
@@ -111,7 +111,7 @@ fn main() -> ExitCode {
let config = xenora_loader::ProbeConfig::default();
match xenora_loader::run_probe_and_export(&bytes, &report_dir, &config) {
Ok(report) => {
println!("Xenora static PE probe complete.");
println!("BetterXen static PE probe complete.");
println!("Artifacts exported to: {report_dir}");
println!("Sections: {}", report.parsed.sections.len());
println!("Relocations: {}", report.relocations.total_entries);
@@ -137,19 +137,19 @@ fn main() -> ExitCode {
}
}
_ => {
eprintln!("usage: xenora <info|demo|inspect|probe|run|imports|shaders>");
eprintln!("usage: betterxen <info|demo|inspect|probe|run|imports|shaders>");
ExitCode::from(2)
}
}
}
/// `xenora imports sync [--report <dir>] [--check]`
/// `xenora imports generate --pe <path> [--out <dir>]`
/// `xenora imports metadata sync [--out <dir>]`
/// `xenora imports verify`
/// `betterxen imports sync [--report <dir>] [--check]`
/// `betterxen imports generate --pe <path> [--out <dir>]`
/// `betterxen imports metadata sync [--out <dir>]`
/// `betterxen imports verify`
fn imports_command(args: Vec<String>) -> ExitCode {
if args.is_empty() {
eprintln!("usage: xenora imports <sync|generate|metadata|verify> [options]");
eprintln!("usage: betterxen imports <sync|generate|metadata|verify> [options]");
return ExitCode::from(2);
}
@@ -160,7 +160,7 @@ fn imports_command(args: Vec<String>) -> ExitCode {
"verify" => run_imports_verify_cli(&args[1..]),
other => {
eprintln!("unknown imports subcommand: {other}");
eprintln!("usage: xenora imports <sync|generate|metadata|verify> [options]");
eprintln!("usage: betterxen imports <sync|generate|metadata|verify> [options]");
ExitCode::from(2)
}
}
@@ -331,7 +331,7 @@ fn run_imports_generate_cli(args: &[String]) -> ExitCode {
}
} else {
eprintln!(
"usage: xenora imports generate <--pe <executable> | --csv <missing_imports.csv>> [--out <dir>]"
"usage: betterxen imports generate <--pe <executable> | --csv <missing_imports.csv>> [--out <dir>]"
);
return ExitCode::from(2);
};
@@ -437,9 +437,10 @@ fn run_imports_sync(
let imports_csv_path = std::path::Path::new(report_dir).join("imports.csv");
if !imports_csv_path.exists() {
return Err(
format!("imports.csv not found in '{report_dir}'. Run `xenora probe` first.").into(),
);
return Err(format!(
"imports.csv not found in '{report_dir}'. Run `betterxen probe` first."
)
.into());
}
// Build the standard registry to get current implementation state.
@@ -525,11 +526,11 @@ fn run_imports_sync(
// Build the refreshed import_backlog.md.
let mut md = String::new();
let _ = writeln!(md, "# Xenora import compatibility backlog");
let _ = writeln!(md, "# BetterXen import compatibility backlog");
let _ = writeln!(md);
let _ = writeln!(
md,
"Generated by `xenora imports sync`. Do not edit manually."
"Generated by `betterxen imports sync`. Do not edit manually."
);
let _ = writeln!(
md,
+1 -1
View File
@@ -27,7 +27,7 @@ const TICKET: u64 = 17;
const DRAW_RESULT: u64 = 0x42;
const EXTENT: [usize; 2] = [4, 3];
const EXPECTED_PIXEL: [u8; 4] = [255, 0, 0, 255];
const USAGE: &str = "usage: xenora run --pe <trusted-fixture> --experimental [--trace] [--metal-hud] [--max-steps <1..=10000>]";
const USAGE: &str = "usage: betterxen run --pe <trusted-fixture> --experimental [--trace] [--metal-hud] [--max-steps <1..=10000>]";
struct Options {
path: PathBuf,
+3 -3
View File
@@ -1,11 +1,11 @@
//! `xenora shaders`: instruction inventory and stream inspection.
//! `betterxen shaders`: instruction inventory and stream inspection.
use std::process::ExitCode;
use xenora_decoder::{Architecture, SEMANTIC_FORMS, decode_at};
use xenora_isa::meta::{self, EncodingFamily, FORMS, identify};
const USAGE: &str = "usage: xenora shaders <coverage [--json] | inspect <gfx1030.bin>>";
const USAGE: &str = "usage: betterxen shaders <coverage [--json] | inspect <gfx1030.bin>>";
pub fn command(args: &[String]) -> ExitCode {
match args.first().map(String::as_str) {
@@ -109,7 +109,7 @@ fn inspect(path: &str) -> ExitCode {
ExitCode::SUCCESS
}
/// The printed rows of `xenora shaders inspect`, the number of rows that do
/// The printed rows of `betterxen shaders inspect`, the number of rows that do
/// not decode into executable instructions and the identification failure
/// that ended the stream early, if any.
struct Listing {
+2 -2
View File
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Default report folder of `xenora probe` and `xenora imports sync`.
//! Default report folder of `betterxen probe` and `betterxen imports sync`.
use std::process::Command;
@@ -13,7 +13,7 @@ fn probe_and_sync_use_the_same_default_folder() {
let folder = std::env::temp_dir().join(format!("xenora-default-{}", std::process::id()));
std::fs::create_dir(&folder).unwrap();
for arguments in [&["probe", "--pe", fixture][..], &["imports", "sync"]] {
let status = Command::new(env!("CARGO_BIN_EXE_xenora"))
let status = Command::new(env!("CARGO_BIN_EXE_betterxen"))
.args(arguments)
.current_dir(&folder)
.status()
+5 -5
View File
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! `xenora imports sync` over a probe report that lists delay-loaded imports.
//! `betterxen imports sync` over a probe report that lists delay-loaded imports.
use std::process::Command;
@@ -13,8 +13,8 @@ fn backlog_leaves_out_delay_loaded_imports() {
"/../../fixtures/pe/delay-imports.exe"
);
let report = std::env::temp_dir().join(format!("xenora-sync-delayed-{}", std::process::id()));
let xenora = |arguments: &[&str]| {
let status = Command::new(env!("CARGO_BIN_EXE_xenora"))
let betterxen = |arguments: &[&str]| {
let status = Command::new(env!("CARGO_BIN_EXE_betterxen"))
.args(arguments)
.arg("--report")
.arg(&report)
@@ -22,8 +22,8 @@ fn backlog_leaves_out_delay_loaded_imports() {
.unwrap();
assert!(status.success(), "{arguments:?}");
};
xenora(&["probe", "--pe", fixture]);
xenora(&["imports", "sync"]);
betterxen(&["probe", "--pe", fixture]);
betterxen(&["imports", "sync"]);
let listed = std::fs::read_to_string(report.join("imports.csv")).unwrap();
let backlog = std::fs::read_to_string(report.join("import_backlog.md")).unwrap();
std::fs::remove_dir_all(report).unwrap();
+529
View File
@@ -0,0 +1,529 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Decoding of Microsoft Visual C++ decorated names, for diagnostics.
//!
//! Written from the publicly described decoration scheme: a leading `?`,
//! `@`-terminated name fragments listed innermost first, single-digit name and
//! type back-references, an access and storage code, a calling convention,
//! the return type and the parameter list. Output follows the style of
//! Microsoft's `undname` tool. Anything outside the supported subset returns
//! `None` instead of a guess, so callers fall back to the decorated name.
const MAX_DEPTH: usize = 16;
/// The undecorated form of `symbol`, or `None` when it is not a decorated
/// C++ name or uses an unsupported construct.
pub fn demangle(symbol: &str) -> Option<String> {
let mut parser = Parser {
input: symbol.as_bytes(),
position: 0,
names: Vec::new(),
types: Vec::new(),
depth: 0,
};
let result = parser.symbol()?;
(parser.position == parser.input.len()).then_some(result)
}
/// A special name introduced by `?` and a code inside the qualified name.
enum Special {
Constructor,
Destructor,
Operator(&'static str),
Vftable,
}
struct Parser<'a> {
input: &'a [u8],
position: usize,
names: Vec<String>,
types: Vec<String>,
depth: usize,
}
impl Parser<'_> {
fn peek(&self) -> Option<u8> {
self.input.get(self.position).copied()
}
fn next(&mut self) -> Option<u8> {
let byte = self.peek()?;
self.position += 1;
Some(byte)
}
fn eat(&mut self, byte: u8) -> bool {
let found = self.peek() == Some(byte);
if found {
self.position += 1;
}
found
}
fn eat_str(&mut self, text: &str) -> bool {
let found = self.input[self.position..].starts_with(text.as_bytes());
if found {
self.position += text.len();
}
found
}
fn symbol(&mut self) -> Option<String> {
if !self.eat(b'?') {
return None;
}
let (name, special) = self.qualified_name(true)?;
match self.peek()? {
b'0'..=b'4' => self.variable(&name),
b'6' => {
self.next();
let qualifier = cv(self.next()?)?;
self.eat(b'@');
if !matches!(special, Some(Special::Vftable)) {
return None;
}
Some(format!("{} {name}", qualifier.trim()))
}
_ => self.function(&name, special.as_ref()),
}
}
fn variable(&mut self, name: &str) -> Option<String> {
let access = match self.next()? {
b'0' => "private: static ",
b'1' => "protected: static ",
b'2' => "public: static ",
_ => "",
};
let kind = self.data_type()?;
self.eat(b'E');
let qualifier = cv(self.next()?)?;
Some(format!("{access}{kind}{qualifier} {name}"))
}
fn function(&mut self, name: &str, special: Option<&Special>) -> Option<String> {
let (access, member) = match self.next()? {
b'A' | b'B' => ("private: ", true),
b'C' | b'D' => ("private: static ", false),
b'E' | b'F' => ("private: virtual ", true),
b'I' | b'J' => ("protected: ", true),
b'K' | b'L' => ("protected: static ", false),
b'M' | b'N' => ("protected: virtual ", true),
b'Q' | b'R' => ("public: ", true),
b'S' | b'T' => ("public: static ", false),
b'U' | b'V' => ("public: virtual ", true),
b'Y' | b'Z' => ("", false),
_ => return None,
};
let mut this = String::new();
if member {
let pointer64 = self.eat(b'E');
this.push_str(cv(self.next()?)?.trim_start());
if pointer64 {
this.push_str(" __ptr64");
}
}
let convention = match self.next()? {
b'A' | b'B' => "__cdecl",
b'C' | b'D' => "__pascal",
b'E' | b'F' => "__thiscall",
b'G' | b'H' => "__stdcall",
b'I' | b'J' => "__fastcall",
b'Q' => "__vectorcall",
_ => return None,
};
let returns = if self.eat(b'@') {
if !matches!(special, Some(Special::Constructor | Special::Destructor)) {
return None;
}
String::new()
} else {
if self.eat(b'?') {
cv(self.next()?)?;
}
format!("{} ", self.data_type()?)
};
let parameters = self.parameters()?;
if !self.eat(b'Z') {
return None;
}
Some(format!(
"{access}{returns}{convention} {name}({parameters}){this}"
))
}
fn parameters(&mut self) -> Option<String> {
if self.eat(b'X') {
return Some("void".to_owned());
}
let mut parameters = Vec::new();
loop {
match self.peek()? {
b'@' => {
self.next();
break;
}
b'Z' => {
self.next();
parameters.push("...".to_owned());
break;
}
_ => {
let start = self.position;
let kind = self.data_type()?;
if self.position - start > 1 && self.types.len() < 10 {
self.types.push(kind.clone());
}
parameters.push(kind);
}
}
}
Some(parameters.join(","))
}
/// Fragments up to `@`, joined outermost first.
fn qualified_name(&mut self, allow_special: bool) -> Option<(String, Option<Special>)> {
let mut special = None;
let mut fragments = Vec::new();
if allow_special
&& self.peek() == Some(b'?')
&& self.input.get(self.position + 1) != Some(&b'$')
{
self.next();
special = Some(self.special()?);
} else {
fragments.push(self.fragment()?);
}
while !self.eat(b'@') {
fragments.push(self.fragment()?);
}
fragments.reverse();
let scope = fragments.join("::");
let name = match &special {
None => scope,
Some(special) => {
let class = || Some(fragments.last()?.split('<').next()?.to_owned());
let leaf = match special {
Special::Constructor => class()?,
Special::Destructor => format!("~{}", class()?),
Special::Operator(name) => name.to_string(),
Special::Vftable => "`vftable'".to_owned(),
};
if scope.is_empty() {
leaf
} else {
format!("{scope}::{leaf}")
}
}
};
Some((name, special))
}
fn special(&mut self) -> Option<Special> {
Some(match self.next()? {
b'0' => Special::Constructor,
b'1' => Special::Destructor,
b'2' => Special::Operator("operator new"),
b'3' => Special::Operator("operator delete"),
b'4' => Special::Operator("operator="),
b'8' => Special::Operator("operator=="),
b'9' => Special::Operator("operator!="),
b'A' => Special::Operator("operator[]"),
b'R' => Special::Operator("operator()"),
b'_' => match self.next()? {
b'7' => Special::Vftable,
b'U' => Special::Operator("operator new[]"),
b'V' => Special::Operator("operator delete[]"),
_ => return None,
},
_ => return None,
})
}
fn fragment(&mut self) -> Option<String> {
if let Some(digit @ b'0'..=b'9') = self.peek() {
self.next();
return self.names.get(usize::from(digit - b'0')).cloned();
}
let fragment = if self.eat_str("?$") {
self.template()?
} else {
self.identifier()?
};
if self.names.len() < 10 && !self.names.contains(&fragment) {
self.names.push(fragment.clone());
}
Some(fragment)
}
fn identifier(&mut self) -> Option<String> {
let start = self.position;
while self.peek()? != b'@' {
let byte = self.next()?;
if !(byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$') {
return None;
}
}
let text = std::str::from_utf8(&self.input[start..self.position]).ok()?;
self.next();
(!text.is_empty()).then(|| text.to_owned())
}
/// `name@arguments@`, with back-references local to the argument list.
fn template(&mut self) -> Option<String> {
self.depth += 1;
if self.depth > MAX_DEPTH {
return None;
}
let outer_names = std::mem::take(&mut self.names);
let outer_types = std::mem::take(&mut self.types);
let name = self.identifier();
if let Some(name) = &name {
self.names.push(name.clone());
}
let mut arguments = Vec::new();
let result = (|| {
let name = name?;
while !self.eat(b'@') {
let start = self.position;
let argument = if self.eat(b'$') {
if !self.eat(b'0') {
return None;
}
self.number()?.to_string()
} else {
self.data_type()?
};
if self.position - start > 1 && self.types.len() < 10 {
self.types.push(argument.clone());
}
arguments.push(argument);
}
let joined = arguments.join(",");
let close = if joined.ends_with('>') { " >" } else { ">" };
Some(format!("{name}<{joined}{close}"))
})();
self.names = outer_names;
self.types = outer_types;
self.depth -= 1;
result
}
/// `0`–`9` encode 1–10; otherwise hexadecimal digits `A`–`P` end with `@`.
fn number(&mut self) -> Option<i64> {
let negative = self.eat(b'?');
let value = match self.next()? {
digit @ b'0'..=b'9' => i64::from(digit - b'0') + 1,
b'@' => 0,
mut digit => {
let mut value: i64 = 0;
loop {
if !(b'A'..=b'P').contains(&digit) {
return None;
}
value = value
.checked_mul(16)?
.checked_add(i64::from(digit - b'A'))?;
digit = self.next()?;
if digit == b'@' {
break value;
}
}
}
};
Some(if negative { -value } else { value })
}
fn data_type(&mut self) -> Option<String> {
self.depth += 1;
if self.depth > MAX_DEPTH {
return None;
}
let result = self.data_type_inner();
self.depth -= 1;
result
}
fn data_type_inner(&mut self) -> Option<String> {
let code = self.next()?;
let primitive = match code {
b'X' => "void",
b'C' => "signed char",
b'D' => "char",
b'E' => "unsigned char",
b'F' => "short",
b'G' => "unsigned short",
b'H' => "int",
b'I' => "unsigned int",
b'J' => "long",
b'K' => "unsigned long",
b'M' => "float",
b'N' => "double",
b'O' => "long double",
b'0'..=b'9' => return self.types.get(usize::from(code - b'0')).cloned(),
b'_' => match self.next()? {
b'J' => "__int64",
b'K' => "unsigned __int64",
b'N' => "bool",
b'W' => "wchar_t",
b'S' => "char16_t",
b'U' => "char32_t",
b'Q' => "char8_t",
_ => return None,
},
b'V' => return Some(format!("class {}", self.qualified_name(false)?.0)),
b'U' => return Some(format!("struct {}", self.qualified_name(false)?.0)),
b'T' => return Some(format!("union {}", self.qualified_name(false)?.0)),
b'W' => {
if !self.eat(b'4') {
return None;
}
return Some(format!("enum {}", self.qualified_name(false)?.0));
}
b'P' | b'Q' | b'R' | b'S' => return self.indirection("*", pointer_cv(code)),
b'A' => return self.indirection("&", ""),
b'B' => return self.indirection("&", " volatile"),
b'$' => {
if self.eat_str("$Q") {
return self.indirection("&&", "");
}
if self.eat_str("$T") {
return Some("std::nullptr_t".to_owned());
}
return None;
}
_ => return None,
};
Some(primitive.to_owned())
}
/// A pointer or reference: an optional `E` for `__ptr64`, the pointee's
/// qualifiers, then the pointee.
fn indirection(&mut self, symbol: &str, own: &str) -> Option<String> {
let pointer64 = self.eat(b'E');
let pointee_cv = cv(self.next()?)?;
let pointee = self.data_type()?;
let width = if pointer64 { " __ptr64" } else { "" };
Some(format!("{pointee}{pointee_cv} {symbol}{own}{width}"))
}
}
fn cv(code: u8) -> Option<&'static str> {
Some(match code {
b'A' => "",
b'B' => " const",
b'C' => " volatile",
b'D' => " const volatile",
_ => return None,
})
}
fn pointer_cv(code: u8) -> &'static str {
match code {
b'Q' => " const",
b'R' => " volatile",
b'S' => " const volatile",
_ => "",
}
}
#[cfg(test)]
mod tests {
use super::demangle;
#[test]
fn decodes_global_functions_and_operators() {
for (decorated, expected) in [
("?foo@@YAXXZ", "void __cdecl foo(void)"),
("?foo@@YAHH@Z", "int __cdecl foo(int)"),
("?f@@YAXPEBD@Z", "void __cdecl f(char const * __ptr64)"),
("?f@@YAXHZZ", "void __cdecl f(int,...)"),
(
"??2@YAPEAX_K@Z",
"void * __ptr64 __cdecl operator new(unsigned __int64)",
),
(
"??3@YAXPEAX@Z",
"void __cdecl operator delete(void * __ptr64)",
),
(
"??_U@YAPEAX_K@Z",
"void * __ptr64 __cdecl operator new[](unsigned __int64)",
),
(
"?_Xlength_error@std@@YAXPEBD@Z",
"void __cdecl std::_Xlength_error(char const * __ptr64)",
),
("?g@@YA_N_J0@Z", "bool __cdecl g(__int64,__int64)"),
] {
assert_eq!(
demangle(decorated).as_deref(),
Some(expected),
"{decorated}"
);
}
}
#[test]
fn decodes_members_constructors_and_data() {
for (decorated, expected) in [
(
"?bar@Foo@@QEAAXH@Z",
"public: void __cdecl Foo::bar(int) __ptr64",
),
(
"?get@Foo@@QEBAHXZ",
"public: int __cdecl Foo::get(void)const __ptr64",
),
("??0Foo@@QEAA@XZ", "public: __cdecl Foo::Foo(void) __ptr64"),
(
"??1Foo@@UEAA@XZ",
"public: virtual __cdecl Foo::~Foo(void) __ptr64",
),
(
"?make@Foo@@SAPEAV1@XZ",
"public: static class Foo * __ptr64 __cdecl Foo::make(void)",
),
("?x@ns@@3HA", "int ns::x"),
("?count@Foo@@2HB", "public: static int const Foo::count"),
("??_7type_info@@6B@", "const type_info::`vftable'"),
] {
assert_eq!(
demangle(decorated).as_deref(),
Some(expected),
"{decorated}"
);
}
}
#[test]
fn decodes_templates_and_back_references() {
assert_eq!(
demangle("?g@@YAXAEAV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z")
.as_deref(),
Some(
"void __cdecl g(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > & __ptr64)"
)
);
assert_eq!(
demangle("?h@@YAXV?$array@H$0BA@@std@@@Z").as_deref(),
Some("void __cdecl h(class std::array<int,16>)")
);
}
#[test]
fn rejects_undecorated_and_unsupported_names() {
for symbol in [
"malloc",
"",
"?",
"?foo@@",
"?foo@@YAXXZtrailing",
"??_R0?AVtype_info@@@8",
"?f@@YAXP6AXXZ@Z",
&format!("?f@@YAX{}@Z", "PEA".repeat(40) + "H"),
] {
assert_eq!(demangle(symbol), None, "{symbol}");
}
}
}
+2
View File
@@ -27,6 +27,7 @@
pub mod apiset;
pub mod classify;
pub mod codegen;
pub mod demangle;
pub mod ingest;
pub mod manifest;
pub mod metadata;
@@ -37,6 +38,7 @@ pub mod verify;
pub use apiset::{get_api_sets_for_canonical, resolve_api_set_canonical};
pub use classify::{Classification, SymbolDb};
pub use codegen::{GeneratedFiles, generate};
pub use demangle::demangle;
pub use ingest::{ingest_header_file, ingest_standard_system_headers};
pub use manifest::Manifest;
pub use metadata::{AbiType, CallingConvention, FunctionSignature, MetadataCatalog};
+7 -1
View File
@@ -166,7 +166,13 @@ impl Manifest {
if let Classification::Manual { reason } | Classification::Unsupported { reason } =
&e.classification
{
md.push_str(&format!("- `{}!{}` — {reason}\n", e.module, e.symbol));
match crate::demangle(&e.symbol) {
Some(name) => md.push_str(&format!(
"- `{}!{}` (`{name}`) — {reason}\n",
e.module, e.symbol
)),
None => md.push_str(&format!("- `{}!{}` — {reason}\n", e.module, e.symbol)),
}
}
}
md
+109
View File
@@ -0,0 +1,109 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Decorated names produced by an independent mangler: Apple clang 21 with
//! `-target x86_64-pc-windows-msvc -S` on the declarations quoted beside each
//! case. Expected strings restate those declarations in `undname` style; they
//! are not taken from the decoder.
use xenora_import_gen::demangle;
#[test]
fn clang_msvc_manglings_decode_to_their_declarations() {
for (decorated, expected) in [
// void foo();
("?foo@@YAXXZ", "void __cdecl foo(void)"),
// int foo2(int);
("?foo2@@YAHH@Z", "int __cdecl foo2(int)"),
// void f(const char*);
("?f@@YAXPEBD@Z", "void __cdecl f(char const * __ptr64)"),
// void fv(int, ...);
("?fv@@YAXHZZ", "void __cdecl fv(int,...)"),
// bool g(long long, long long);
("?g@@YA_N_J0@Z", "bool __cdecl g(__int64,__int64)"),
// namespace std { void _Xlength_error(const char*); }
(
"?_Xlength_error@std@@YAXPEBD@Z",
"void __cdecl std::_Xlength_error(char const * __ptr64)",
),
// struct Foo { void bar(int); };
(
"?bar@Foo@@QEAAXH@Z",
"public: void __cdecl Foo::bar(int) __ptr64",
),
// struct Foo { int get() const; };
(
"?get@Foo@@QEBAHXZ",
"public: int __cdecl Foo::get(void)const __ptr64",
),
// struct Foo { Foo(); };
("??0Foo@@QEAA@XZ", "public: __cdecl Foo::Foo(void) __ptr64"),
// struct Foo { static Foo* make(); };
(
"?make@Foo@@SAPEAU1@XZ",
"public: static struct Foo * __ptr64 __cdecl Foo::make(void)",
),
// void use(Foo&);
(
"?use@@YAXAEAUFoo@@@Z",
"void __cdecl use(struct Foo & __ptr64)",
),
// namespace ns { int x; }
("?x@ns@@3HA", "int ns::x"),
// Global operator new(size_t) and sized operator delete(void*, size_t).
(
"??2@YAPEAX_K@Z",
"void * __ptr64 __cdecl operator new(unsigned __int64)",
),
(
"??3@YAXPEAX_K@Z",
"void __cdecl operator delete(void * __ptr64,unsigned __int64)",
),
// void gs(std::basic_string<char, std::char_traits<char>, std::allocator<char>>&);
(
"?gs@@YAXAEAV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z",
"void __cdecl gs(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > & __ptr64)",
),
// void h(std::array<int, 16>);
(
"?h@@YAXV?$array@H$0BA@@std@@@Z",
"void __cdecl h(class std::array<int,16>)",
),
] {
assert_eq!(
demangle(decorated).as_deref(),
Some(expected),
"{decorated}"
);
}
}
#[test]
fn unsupported_clang_manglings_are_reported_rather_than_guessed() {
// void (*keep[])(): function pointer types are outside the supported subset.
assert_eq!(demangle("?keep@@3PAP6AXXZA"), None);
// A compiler-generated cleanup funclet nested in another function's scope.
assert_eq!(demangle("?dtor$2@?0??use@@YAXAEAUFoo@@@Z@4HA"), None);
}
#[test]
fn manifests_show_undecorated_names_for_unclassified_cxx_imports() {
use xenora_import_gen::{ImportRecord, Manifest, SymbolDb};
let record = |symbol: &str| ImportRecord {
module: "msvcp140.dll".to_owned(),
symbol: symbol.to_owned(),
ordinal: None,
iat_rva: 0x2000,
};
let manifest = Manifest::build(
&[
record("?_Xlength_error@std@@YAXPEBD@Z"),
record("?keep@@3PAP6AXXZA"),
],
&SymbolDb::builtin(),
);
let markdown = manifest.render_markdown();
assert!(markdown.contains(
"- `msvcp140.dll!?_Xlength_error@std@@YAXPEBD@Z` (`void __cdecl std::_Xlength_error(char const * __ptr64)`) —"
));
assert!(markdown.contains("- `msvcp140.dll!?keep@@3PAP6AXXZA` —"));
}
+4
View File
@@ -25,3 +25,7 @@ xenora-shader = { path = "../shader" }
[[bench]]
name = "dbt_bench"
harness = false
[[bench]]
name = "service_dispatch"
harness = false
+225
View File
@@ -0,0 +1,225 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Guest-to-host service dispatch cost, measured with original guest loops
//! that call standard services through a bound import table under the DBT.
//!
//! Every workload checks its result before timing. Each reported figure is
//! the per-iteration time of a loop of `ITERATIONS` calls: one warm-up batch,
//! then `BATCHES` measured batches. The empty loop is reported separately so
//! readers can subtract the loop and translation overhead themselves.
//!
//! Run with `cargo bench --locked -p xenora-loader --bench service_dispatch`.
#[path = "../tests/support/mod.rs"]
mod support;
use std::time::Instant;
use support::*;
use xenora_loader::cpu::{ExitReason, Register};
use xenora_loader::services::sysinfo::HostCapabilities;
const IMPORTS: &[(&str, &str)] = &[
("kernel32.dll", "GetLastError"),
("kernel32.dll", "CreateEventW"),
("kernel32.dll", "WaitForSingleObject"),
("ucrtbase.dll", "strlen"),
("kernel32.dll", "GetProcessHeap"),
("kernel32.dll", "HeapAlloc"),
("kernel32.dll", "HeapFree"),
("ucrtbase.dll", "qsort"),
];
const ITERATIONS: u32 = 10_000;
const BATCHES: usize = 10;
const CELL_EVENT: u64 = SCRATCH + 0x10;
const CELL_HEAP: u64 = SCRATCH + 0x18;
const STRING: u64 = SCRATCH + 0x100;
const ARRAY: u64 = SCRATCH + 0x200;
const ARRAY_LEN: u32 = 16;
const EMPTY: usize = 0;
const LAST_ERROR: usize = 1;
const WAIT: usize = 2;
const STRLEN: usize = 3;
const HEAP: usize = 4;
const QSORT: usize = 5;
const COMPARE: usize = 6;
/// A tiny x86-64 assembler for the routines below.
struct Asm {
base: u64,
code: Vec<u8>,
}
impl Asm {
fn new(routine_index: usize) -> Self {
Self {
base: routine(routine_index),
code: Vec::new(),
}
}
fn bytes(&mut self, bytes: &[u8]) -> &mut Self {
self.code.extend_from_slice(bytes);
self
}
fn imm64(&mut self, opcode: &[u8], value: u64) -> &mut Self {
self.bytes(opcode).bytes(&value.to_le_bytes())
}
fn imm32(&mut self, opcode: &[u8], value: u32) -> &mut Self {
self.bytes(opcode).bytes(&value.to_le_bytes())
}
/// `call qword ptr [rip + displacement]` through an import slot.
fn call_import(&mut self, symbol: &str) -> &mut Self {
let index = IMPORTS
.iter()
.position(|(_, name)| *name == symbol)
.unwrap();
let next = self.base + self.code.len() as u64 + 6;
let displacement = import_slot(IMPORTS, index).wrapping_sub(next) as u32;
self.imm32(&[0xFF, 0x15], displacement)
}
/// `mov ebx, ITERATIONS`, the loop body, `dec ebx; jnz body; hlt`.
fn counted(routine_index: usize, body: impl FnOnce(&mut Self)) -> Vec<u8> {
let mut asm = Self::new(routine_index);
asm.imm32(&[0xBB], ITERATIONS);
let start = asm.code.len();
body(&mut asm);
asm.bytes(&[0xFF, 0xCB]); // dec ebx
let back = start as i64 - (asm.code.len() as i64 + 2);
asm.bytes(&[0x75, i8::try_from(back).unwrap() as u8, 0xF4]);
asm.code
}
}
fn routines() -> Vec<Vec<u8>> {
let mut routines = vec![Vec::new(); 7];
routines[EMPTY] = Asm::counted(EMPTY, |_| {});
routines[LAST_ERROR] = Asm::counted(LAST_ERROR, |asm| {
asm.call_import("GetLastError");
});
routines[WAIT] = Asm::counted(WAIT, |asm| {
asm.imm64(&[0x48, 0xB8], CELL_EVENT) // mov rax, cell
.bytes(&[0x48, 0x8B, 0x08]) // mov rcx, [rax]
.bytes(&[0x31, 0xD2]) // xor edx, edx
.call_import("WaitForSingleObject");
});
routines[STRLEN] = Asm::counted(STRLEN, |asm| {
asm.imm64(&[0x48, 0xB9], STRING).call_import("strlen");
});
routines[HEAP] = Asm::counted(HEAP, |asm| {
asm.imm64(&[0x48, 0xB8], CELL_HEAP)
.bytes(&[0x48, 0x8B, 0x08]) // mov rcx, [rax]
.bytes(&[0x31, 0xD2])
.imm32(&[0x41, 0xB8], 64) // mov r8d, 64
.call_import("HeapAlloc")
.bytes(&[0x49, 0x89, 0xC0]) // mov r8, rax
.imm64(&[0x48, 0xB8], CELL_HEAP)
.bytes(&[0x48, 0x8B, 0x08])
.bytes(&[0x31, 0xD2])
.call_import("HeapFree");
});
routines[QSORT] = Asm::counted(QSORT, |asm| {
asm.imm64(&[0x48, 0xB9], ARRAY)
.imm32(&[0xBA], ARRAY_LEN) // mov edx, count
.imm32(&[0x41, 0xB8], 4) // mov r8d, width
.imm64(&[0x49, 0xB9], routine(COMPARE))
.call_import("qsort");
});
// int compare(const int *a, const int *b) { return *a - *b; }
routines[COMPARE] = vec![0x8B, 0x01, 0x2B, 0x02, 0xC3];
routines
}
fn median(samples: &mut [f64]) -> f64 {
samples.sort_by(f64::total_cmp);
samples[samples.len() / 2]
}
fn main() {
let mut guest = Guest::new(IMPORTS, &routines());
let event = guest.call("CreateEventW", &[0, 1, 1, 0]);
assert_ne!(event, 0);
guest.memory.write_u64(CELL_EVENT, event).unwrap();
let heap = guest.call("GetProcessHeap", &[]);
guest.memory.write_u64(CELL_HEAP, heap).unwrap();
guest.memory.write_bytes(STRING, &[b'a'; 63]).unwrap();
guest.memory.write_u8(STRING + 63, 0).unwrap();
let unsorted: Vec<i32> = (0..ARRAY_LEN as i32)
.map(|i| (i * 7919) % 31 - 15)
.collect();
let reset_array = |guest: &mut Guest| {
for (index, value) in unsorted.iter().enumerate() {
guest
.memory
.write_u32(ARRAY + 4 * index as u64, *value as u32)
.unwrap();
}
};
let host = HostCapabilities::detect();
let brand = std::process::Command::new("sysctl")
.args(["-n", "machdep.cpu.brand_string"])
.output()
.map(|output| String::from_utf8_lossy(&output.stdout).trim().to_owned())
.unwrap_or_default();
println!(
"host: {brand}, {} logical processors; profile: {}",
host.logical_processors.unwrap_or(0),
if cfg!(debug_assertions) {
"debug"
} else {
"release"
},
);
println!("{ITERATIONS} iterations per batch, 1 warm-up and {BATCHES} measured batches");
println!("workload,median_ns_per_iteration,min_ns,max_ns");
for (name, index, check) in [
("empty loop", EMPTY, None),
("GetLastError", LAST_ERROR, Some(0)),
(
"WaitForSingleObject (signaled manual-reset event)",
WAIT,
Some(0),
),
("strlen (63 bytes)", STRLEN, Some(63)),
("HeapAlloc + HeapFree (64 bytes)", HEAP, Some(1)),
("qsort (16 ints, guest comparator)", QSORT, Some(0)),
] {
let mut samples = Vec::with_capacity(BATCHES);
for batch in 0..=BATCHES {
if index == QSORT {
reset_array(&mut guest);
}
let start = Instant::now();
let (cpu, exit) = guest.execute(routine(index), usize::MAX);
let elapsed = start.elapsed();
assert_eq!(exit, ExitReason::Halt, "{name}");
assert_eq!(cpu.get(Register::Rbx), 0, "{name} loop count");
if let Some(expected) = check {
assert_eq!(cpu.get(Register::Rax), expected, "{name} result");
}
if index == QSORT {
let mut expected = unsorted.clone();
expected.sort();
let sorted: Vec<i32> = (0..ARRAY_LEN as u64)
.map(|i| guest.u32_at(ARRAY + 4 * i) as i32)
.collect();
assert_eq!(sorted, expected, "{name} ordering");
}
if batch > 0 {
samples.push(elapsed.as_nanos() as f64 / f64::from(ITERATIONS));
}
}
let (min, max) = samples.iter().fold((f64::MAX, 0f64), |(low, high), &s| {
(low.min(s), high.max(s))
});
println!("{name},{:.1},{min:.1},{max:.1}", median(&mut samples));
}
}
+3 -1
View File
@@ -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.
+49 -7
View File
@@ -307,23 +307,27 @@ impl Arm64Assembler {
}
/// RBIT Xd, Xn: reverse the bit order of the source.
/// Panics if a register number exceeds 31.
pub fn rbit_64(&mut self, xd: u8, xn: u8) {
self.emit(0xdac0_0000 | ((u32::from(xn) & 0x1f) << 5) | (u32::from(xd) & 0x1f));
assert!(xd <= XZR && xn <= XZR, "RBIT register must be in 0..=31");
self.emit(0xdac0_0000 | (u32::from(xn) << 5) | u32::from(xd));
}
/// CLZ Xd, Xn: count the leading zero bits of the source.
/// Panics if a register number exceeds 31.
pub fn clz_64(&mut self, xd: u8, xn: u8) {
self.emit(0xdac0_1000 | ((u32::from(xn) & 0x1f) << 5) | (u32::from(xd) & 0x1f));
assert!(xd <= XZR && xn <= XZR, "CLZ register must be in 0..=31");
self.emit(0xdac0_1000 | (u32::from(xn) << 5) | u32::from(xd));
}
/// LSLV Xd, Xn, Xm: shift the source left by the amount in Xm.
/// Panics if a register number exceeds 31.
pub fn lslv_64(&mut self, xd: u8, xn: u8, xm: u8) {
self.emit(
0x9ac2_2000
| ((u32::from(xm) & 0x1f) << 16)
| ((u32::from(xn) & 0x1f) << 5)
| (u32::from(xd) & 0x1f),
assert!(
xd <= XZR && xn <= XZR && xm <= XZR,
"LSLV register must be in 0..=31"
);
self.emit(0x9ac0_2000 | (u32::from(xm) << 16) | (u32::from(xn) << 5) | u32::from(xd));
}
/// LDR Qt, [Xn, #offset] (offset a multiple of 16)
@@ -831,6 +835,44 @@ mod tests {
assert_eq!(branch.instructions()[0], 0x14000005);
}
#[test]
fn rbit_clz_lslv_encodings_match_llvm() {
// A64 words from Apple Clang's integrated assembler and llvm-objdump.
let mut asm = Arm64Assembler::new();
asm.rbit_64(X10, X9); // rbit x10, x9
asm.rbit_64(X0, XZR); // rbit x0, xzr
asm.clz_64(X10, X10); // clz x10, x10
asm.clz_64(XZR, X30); // clz xzr, x30
asm.lslv_64(X11, X11, X10); // lslv x11, x11, x10
asm.lslv_64(X0, X1, X0); // lslv x0, x1, x0
asm.lslv_64(XZR, X30, XZR); // lslv xzr, x30, xzr
assert_eq!(
asm.instructions(),
[
0xdac0012a, 0xdac003e0, 0xdac0114a, 0xdac013df, 0x9aca216b, 0x9ac02020, 0x9adf23df,
]
);
}
#[test]
fn rbit_clz_lslv_reject_out_of_range_registers() {
let invalid_operands: [fn(&mut Arm64Assembler); 7] = [
|asm| asm.rbit_64(32, X0),
|asm| asm.rbit_64(X0, 32),
|asm| asm.clz_64(32, X0),
|asm| asm.clz_64(X0, 32),
|asm| asm.lslv_64(32, X0, X0),
|asm| asm.lslv_64(X0, 32, X0),
|asm| asm.lslv_64(X0, X0, 32),
];
for (index, emit) in invalid_operands.into_iter().enumerate() {
let mut asm = Arm64Assembler::new();
let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| emit(&mut asm)));
assert!(result.is_err(), "invalid operand case {index} was accepted");
assert!(asm.instructions().is_empty());
}
}
#[test]
fn unsigned_offset_stores_scale_by_access_size() {
let mut asm = Arm64Assembler::new();
+5 -1
View File
@@ -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")
}
+68
View File
@@ -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,
+24 -15
View File
@@ -120,10 +120,11 @@ pub enum GraphicsError {
/// An index buffer format other than DXGI `R16_UINT` (57) or `R32_UINT` (42).
InvalidIndexFormat(u32),
/// An indexed draw reads past its index buffer or fetches a vertex,
/// after applying the base vertex, outside its vertex buffer.
/// after applying the base vertex, outside its vertex buffer, or a flat
/// draw reads its vertices outside the vertex buffer.
IndexOutOfRange,
/// A descriptor heap, view, sampler, root signature or binding outside
/// the supported texture-binding subset. Nothing is drawn.
/// A descriptor heap, view, sampler, root signature, binding or draw
/// outside the supported subset. Nothing is drawn.
Unsupported(&'static str),
}
@@ -151,8 +152,8 @@ impl std::fmt::Display for GraphicsError {
Self::InvalidIndexFormat(format) => {
write!(f, "unsupported index buffer format {format}")
}
Self::IndexOutOfRange => write!(f, "indexed draw outside its index or vertex buffer"),
Self::Unsupported(what) => write!(f, "unsupported texture binding: {what}"),
Self::IndexOutOfRange => write!(f, "draw outside its index or vertex buffer"),
Self::Unsupported(what) => write!(f, "unsupported graphics operation: {what}"),
}
}
}
@@ -1673,9 +1674,22 @@ impl GraphicsContext {
rendered_output = Some(pixels);
continue;
}
if *vertex_count_per_instance < 3 {
// Zero instances, or fewer vertices than one triangle,
// draw nothing. The flat path draws only the first
// triangle of the view, once; anything else is rejected
// rather than drawn as a different triangle.
if *vertex_count_per_instance < 3 || *instance_count == 0 {
continue;
}
if *vertex_count_per_instance != 3
|| *instance_count != 1
|| *start_vertex_location != 0
|| *start_instance_location != 0
{
return Err(GraphicsError::Unsupported(
"flat draw other than one instance of the view's first three vertices",
));
}
draw_count += 1;
let v_res_handle =
vertex_resource.ok_or(GraphicsError::InvalidResourceHandle)?;
@@ -1684,15 +1698,10 @@ impl GraphicsContext {
.get(&v_res_handle)
.ok_or(GraphicsError::InvalidResourceHandle)?;
// Read vertices from guest memory backing or resource data
let mut raw_vtx = [0u8; 48]; // 3 * 4 * float32
if let Some(guest_addr) = v_res.guest_backing_addr {
memory.read_bytes(guest_addr + vertex_offset as u64, &mut raw_vtx)?;
} else if v_res.data.len() >= vertex_offset + 48 {
raw_vtx.copy_from_slice(&v_res.data[vertex_offset..vertex_offset + 48]);
} else {
return Err(GraphicsError::InvalidDescriptor);
}
// Three float4 positions, inside the resource whether it
// is backed by guest memory or by its own bytes.
let mut raw_vtx = [0u8; 48];
Self::read_resource(v_res, memory, vertex_offset, &mut raw_vtx)?;
let mut vertices = [[0.0f32; 4]; 3];
for (i, row) in vertices.iter_mut().enumerate() {
+26
View File
@@ -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
+613 -1
View File
@@ -5,7 +5,7 @@
//! Provides isolated, page-aligned guest virtual memory with permission checking
//! (Read, Write, Execute) and bounds enforcement without host OS mapping tricks.
use std::fmt;
use std::{fmt, ops::Range};
pub(crate) const ALLOCATION_GRANULARITY: u64 = 65_536;
@@ -520,14 +520,39 @@ impl GuestMemory {
/// Write raw bytes into guest memory at the specified address, checking permissions.
pub fn write_bytes(&mut self, address: u64, src: &[u8]) -> Result<(), MemoryError> {
if let Some((index, range)) = self.contiguous_region(address, src.len())
&& self.regions[index].permissions.write
{
self.regions[index].data[range].copy_from_slice(src);
return Ok(());
}
self.write_checked(address, src, Some("write"))
}
/// Read raw bytes from guest memory at the specified address, checking permissions.
pub fn read_bytes(&self, address: u64, dst: &mut [u8]) -> Result<(), MemoryError> {
if let Some((index, range)) = self.contiguous_region(address, dst.len())
&& self.regions[index].permissions.read
{
dst.copy_from_slice(&self.regions[index].data[range]);
return Ok(());
}
self.read_checked(address, dst, Some("read"))
}
// Only the first eligible mapping may supply the whole span. Otherwise
// the checked resolver must preserve split-access and overlap priority.
fn contiguous_region(&self, address: u64, len: usize) -> Option<(usize, Range<usize>)> {
let (index, region) = self
.regions
.iter()
.enumerate()
.find(|(_, region)| region.base + region.data.len() as u64 > address)?;
let offset = usize::try_from(address.checked_sub(region.base)?).ok()?;
let end = offset.checked_add(len)?;
(end <= region.data.len()).then_some((index, offset..end))
}
/// Read an instruction byte from guest memory, verifying execute permission.
pub fn fetch_instruction_byte(&self, address: u64) -> Result<u8, MemoryError> {
address.checked_add(1).ok_or(MemoryError::Overflow)?;
@@ -869,3 +894,590 @@ mod instruction_fetch_tests {
assert_eq!(m.fetch_instruction_byte(BASE + 3), Ok(0x44));
}
}
#[cfg(test)]
mod data_access_contract_tests {
use super::{MemoryPermissions as P, *};
const A: u64 = 0x10_0000;
#[test]
fn data_permissions_are_independent_and_failed_reads_leave_output_untouched() {
for bits in 0..8 {
let p = P {
read: bits & 1 != 0,
write: bits & 2 != 0,
execute: bits & 4 != 0,
};
let mut m = GuestMemory::new();
m.map_region_with_data(A, 4, p, &[1, 2, 3, 4]).unwrap();
let mut out = [0xee; 2];
let read = m.read_bytes(A + 1, &mut out);
assert_eq!(
read,
if p.read {
Ok(())
} else {
Err(MemoryError::PermissionViolation {
address: A + 1,
required: "read",
})
}
);
assert_eq!(out, if p.read { [2, 3] } else { [0xee; 2] });
let write = m.write_bytes(A + 1, &[0x55, 0x66]);
assert_eq!(
write,
if p.write {
Ok(())
} else {
Err(MemoryError::PermissionViolation {
address: A + 1,
required: "write",
})
}
);
let mut stored = [0; 4];
m.read_checked(A, &mut stored, None).unwrap();
assert_eq!(
stored,
if p.write {
[1, 0x55, 0x66, 4]
} else {
[1, 2, 3, 4]
}
);
}
}
#[test]
fn empty_data_spans_keep_inclusive_ends_and_ignore_permissions() {
let mut m = GuestMemory::new();
m.map_region(A, 0, P::NO_ACCESS).unwrap();
m.map_region(A + 16, 3, P::NO_ACCESS).unwrap();
m.map_region(u64::MAX, 0, P::NO_ACCESS).unwrap();
for at in [A, A + 16, A + 17, A + 19, u64::MAX] {
assert_eq!(m.read_bytes(at, &mut []), Ok(()));
assert_eq!(m.write_bytes(at, &[]), Ok(()));
}
for at in [A - 1, A + 1, A + 15, A + 20] {
assert_eq!(
m.read_bytes(at, &mut []),
Err(MemoryError::UnmappedAddress(at))
);
assert_eq!(
m.write_bytes(at, &[]),
Err(MemoryError::UnmappedAddress(at))
);
}
}
#[test]
fn data_address_overflow_precedes_permissions_and_preserves_output() {
let mut m = GuestMemory::new();
m.map_region(u64::MAX - 3, 3, P::NO_ACCESS).unwrap();
let mut out = [0xee; 2];
assert_eq!(
m.read_bytes(u64::MAX - 1, &mut out),
Err(MemoryError::Overflow)
);
assert_eq!(out, [0xee; 2]);
assert_eq!(
m.write_bytes(u64::MAX - 1, &[1, 2]),
Err(MemoryError::Overflow)
);
assert_eq!(
m.read_bytes(u64::MAX, &mut out[..1]),
Err(MemoryError::Overflow)
);
assert_eq!(m.write_bytes(u64::MAX, &[1]), Err(MemoryError::Overflow));
assert_eq!(m.read_u16(u64::MAX - 1), Err(MemoryError::Overflow));
}
#[test]
fn split_data_accesses_keep_exact_fallback_errors_and_atomicity() {
for (gap, right) in [
(0, P::READ_WRITE),
(0, P::READ_ONLY),
(0, P::NO_ACCESS),
(
0,
P {
read: false,
write: true,
execute: false,
},
),
(1, P::READ_WRITE),
] {
let mut m = GuestMemory::new();
m.map_region_with_data(A, 8, P::READ_WRITE, &[0, 1, 2, 3, 4, 5, 6, 7])
.unwrap();
let b = A + 8 + gap;
m.map_region_with_data(b, 8, right, &[8, 9, 10, 11, 12, 13, 14, 15])
.unwrap();
let mut expected = m.clone();
let mut actual_out = [0xee; 4];
let mut expected_out = [0xee; 4];
assert_eq!(
m.read_bytes(A + 6, &mut actual_out),
expected.read_checked(A + 6, &mut expected_out, Some("read"))
);
assert_eq!(actual_out, expected_out);
assert_eq!(
actual_out,
if gap == 0 && right.read {
[6, 7, 8, 9]
} else {
[0xee; 4]
}
);
let bytes = [0xa0, 0xa1, 0xa2, 0xa3];
assert_eq!(
m.write_bytes(A + 6, &bytes),
expected.write_checked(A + 6, &bytes, Some("write"))
);
let written = gap == 0 && right.write;
assert_eq!(
m.read_u64_bypass(A).unwrap().to_le_bytes(),
if written {
[0, 1, 2, 3, 4, 5, 0xa0, 0xa1]
} else {
[0, 1, 2, 3, 4, 5, 6, 7]
}
);
assert_eq!(
m.read_u64_bypass(b).unwrap().to_le_bytes(),
if written {
[0xa2, 0xa3, 10, 11, 12, 13, 14, 15]
} else {
[8, 9, 10, 11, 12, 13, 14, 15]
}
);
}
}
#[test]
fn data_accesses_keep_first_mapping_priority_for_partial_overlaps() {
const BASE: u64 = 0x0000_0003_0000_0000;
for first in [P::READ_WRITE, P::READ_ONLY] {
let mut m = GuestMemory::new();
m.map_region(0x1000, 1, P::NO_ACCESS).unwrap();
m.map_region_with_data(BASE, 4, first, &[1, 2, 3, 4])
.unwrap();
let empty = m.map_heap_allocation(PROCESS_HEAP, 0).unwrap();
assert_eq!(empty, BASE);
assert_eq!(
m.resize_heap_allocation(PROCESS_HEAP, empty, 8, true),
Ok(BASE)
);
let mut out = [0xee; 8];
assert_eq!(m.read_bytes(BASE, &mut out), Ok(()));
assert_eq!(out, [1, 2, 3, 4, 0, 0, 0, 0]);
assert_eq!(m.read_u16(BASE), Ok(0x0201));
let bytes = [0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7];
let mut expected = m.clone();
assert_eq!(
m.write_bytes(BASE, &bytes),
expected.write_checked(BASE, &bytes, Some("write"))
);
m.read_bytes(BASE, &mut out).unwrap();
assert_eq!(
out,
if first.write {
bytes
} else {
[1, 2, 3, 4, 0, 0, 0, 0]
}
);
}
}
#[test]
fn data_accesses_observe_writes_clones_release_and_remap() {
let mut m = GuestMemory::new();
m.map_region_with_data(A, 8, P::READ_WRITE, &[1; 8])
.unwrap();
let mut clone = m.clone();
m.write_u64(A, 0x1122_3344_5566_7788).unwrap();
clone.write_u32(A, 0xaabb_ccdd).unwrap();
assert_eq!(m.read_u64(A), Ok(0x1122_3344_5566_7788));
assert_eq!(clone.read_u64(A), Ok(0x0101_0101_aabb_ccdd));
let b = m.map_virtual_allocation(0x4000, 2, P::READ_WRITE).unwrap();
m.write_u16(b, 0x1234).unwrap();
assert_eq!(m.read_u16(b), Ok(0x1234));
assert!(m.release_virtual_allocation(b));
assert_eq!(m.read_u16(b), Err(MemoryError::UnmappedAddress(b)));
m.map_region_with_data(b, 2, P::READ_ONLY, &[0x56, 0x78])
.unwrap();
assert_eq!(m.read_u16(b), Ok(0x7856));
assert_eq!(
m.write_u8(b, 0),
Err(MemoryError::PermissionViolation {
address: b,
required: "write"
})
);
assert_eq!(clone.read_u16(b), Err(MemoryError::UnmappedAddress(b)));
}
}
#[cfg(test)]
mod data_memory_bench {
use super::{MemoryPermissions as P, *};
use crate::{CpuState, DbtEngine, ExitReason, Register};
use std::{hint::black_box, time::Instant};
const CODE: u64 = 0x1000;
const VALUE: u64 = 0xffff_ff00;
#[derive(Clone, Copy)]
enum Kind {
Registers,
Counter,
Sequential,
Split,
}
fn setting(name: &str, default: usize, maximum: usize) -> usize {
let value = std::env::var(name).map_or(default, |s| s.parse().expect(name));
assert!((1..=maximum).contains(&value), "invalid {name}");
value
}
fn quantile(sorted: &[f64], fraction: f64) -> f64 {
let rank = (sorted.len() - 1) as f64 * fraction;
let lo = rank.floor() as usize;
sorted[lo] + (sorted[rank.ceil() as usize] - sorted[lo]) * rank.fract()
}
fn guest(kind: Kind, iterations: usize, data: u64) -> (Vec<u8>, usize) {
// MOV RCX, iterations; MOV RDX, VALUE (control) or RSI, data; XOR EAX,EAX.
let registers = matches!(kind, Kind::Registers);
let sequential = matches!(kind, Kind::Sequential);
let mut code = vec![0x48, 0xb9];
code.extend_from_slice(&(iterations as u64).to_le_bytes());
code.extend_from_slice(&[0x48, if registers { 0xba } else { 0xbe }]);
let target = if registers { VALUE } else { data };
code.extend_from_slice(&target.to_le_bytes());
code.extend_from_slice(&[0x31, 0xc0]);
let per_iteration = if registers {
// ADD RAX,RDX; ADD RDX,1; DEC RCX; JNZ -12.
code.extend_from_slice(&[
0x48, 0x01, 0xd0, 0x48, 0x83, 0xc2, 0x01, 0x48, 0xff, 0xc9, 0x75, 0xf4,
]);
4
} else {
// MOV RDX,[RSI]; ADD RAX,RDX; ADD RDX,1; MOV [RSI],RDX.
code.extend_from_slice(&[
0x48, 0x8b, 0x16, 0x48, 0x01, 0xd0, 0x48, 0x83, 0xc2, 0x01, 0x48, 0x89, 0x16,
]);
if sequential {
code.extend_from_slice(&[0x48, 0x83, 0xc6, 0x08]); // ADD RSI,8.
}
// DEC RCX; JNZ -22 (sequential) or -18 (counter).
let back = if sequential { 0xea } else { 0xee };
code.extend_from_slice(&[0x48, 0xff, 0xc9, 0x75, back]);
6 + usize::from(sequential)
};
code.push(0xf4); // HLT; three setup instructions and one halt.
(code, iterations * per_iteration + 4)
}
// Run identical source on the baseline and candidate with the same release profile.
// Allocation counting is deliberately separate: instrumentation distorts these timings.
#[test]
#[ignore = "manual, correctness-gated warm DBT data-memory timing"]
fn warm_data_memory_benchmark() {
let samples = setting("XENORA_DATA_BENCH_SAMPLES", 31, 1001);
let counter = setting("XENORA_DATA_BENCH_ITERS", 32768, 65536);
let sequential = setting("XENORA_DATA_BENCH_STREAM_ITERS", 16384, 65536);
for (label, kind, regions, last) in [
("register-control", Kind::Registers, 4, false),
("counter-front", Kind::Counter, 4, false),
("counter-front-many", Kind::Counter, 64, false),
("counter-first", Kind::Counter, 4, false),
("counter-first-many", Kind::Counter, 64, false),
("counter-third-many", Kind::Counter, 64, false),
("counter-middle", Kind::Counter, 64, false),
("counter-last", Kind::Counter, 64, true),
("sequential-front", Kind::Sequential, 4, false),
("sequential-front-many", Kind::Sequential, 64, false),
("sequential-first", Kind::Sequential, 4, false),
("sequential-first-many", Kind::Sequential, 64, false),
("sequential-last", Kind::Sequential, 64, true),
("split-counter-control", Kind::Split, 4, false),
] {
let iterations = if matches!(kind, Kind::Sequential) {
sequential
} else {
counter
};
let code_address = if label.contains("-first") {
0x8000_0000
} else {
CODE
};
let data = if last {
0x4000_0000
} else if label.contains("-third") {
0x20_1000
} else if label.contains("-middle") {
0x23_f000
} else {
0x1_0000
};
let (code, expected_instructions) = guest(kind, iterations, data);
let words = if matches!(kind, Kind::Sequential) {
iterations
} else {
1
};
let initial: Vec<u8> = (0..words)
.flat_map(|i| (VALUE + i as u64).to_le_bytes())
.collect();
let increment = match kind {
Kind::Registers => 0,
Kind::Sequential => 1,
_ => iterations as u64,
};
let expected: Vec<u8> = (0..words)
.flat_map(|i| (VALUE + i as u64 + increment).to_le_bytes())
.collect();
let mut memory = GuestMemory::new();
memory
.map_region_with_data(code_address, 4096, P::READ_EXECUTE, &code)
.unwrap();
let pieces = if matches!(kind, Kind::Split) {
memory
.map_region_with_data(data, 4, P::READ_WRITE, &initial[..4])
.unwrap();
memory
.map_region_with_data(data + 4, 4, P::READ_WRITE, &initial[4..])
.unwrap();
2
} else {
memory
.map_region_with_data(data, initial.len(), P::READ_WRITE, &initial)
.unwrap();
1
};
for i in 0..regions - pieces - 1 {
memory
.map_region(0x20_0000 + i as u64 * 8192, 4096, P::READ_ONLY)
.unwrap();
}
let initial_cpu = CpuState::new(code_address, 0x8000_0000); // No stack instructions.
let mut dbt = DbtEngine::new(1024 * 1024).unwrap();
let mut readback = vec![0; initial.len()];
let n = iterations as u64;
let sum = n * VALUE + n * (n - 1) / 2;
let mut timings = Vec::with_capacity(samples);
let warmups = 5;
for sample in 0..samples + warmups {
memory.write_bytes(data, &initial).unwrap();
let mut cpu = initial_cpu.clone();
let before = dbt.metrics;
let started = Instant::now();
let result = black_box(dbt.run(&mut cpu, &mut memory, expected_instructions + 16));
let elapsed = started.elapsed();
assert_eq!(result.exit_reason, ExitReason::Halt, "{label}");
assert_eq!(
result.instructions_executed, expected_instructions,
"{label}"
);
let state = (
cpu.get(Register::Rax),
cpu.get(Register::Rdx),
cpu.get(Register::Rcx),
);
assert_eq!(state, (sum, VALUE + n, 0), "{label}");
memory.read_bytes(data, &mut readback).unwrap();
assert_eq!(readback, expected, "{label}");
assert_eq!(dbt.metrics.interpreter_fallbacks, 0, "{label}");
if sample > 0 {
let compiled = |m: crate::DbtMetrics| {
(m.blocks_compiled, m.native_bytes_emitted, m.cache_misses)
};
assert_eq!(compiled(dbt.metrics), compiled(before), "{label}");
if sample >= warmups {
timings.push(elapsed.as_nanos() as f64 / n as f64);
}
} else {
assert!(dbt.metrics.blocks_compiled > 0, "{label}");
}
}
timings.sort_by(f64::total_cmp);
println!(
"warm-data label={label} regions={regions} iterations={iterations} samples={samples} warmups={warmups} instructions={expected_instructions} median_ns_per_iteration={:.3} p10={:.3} p90={:.3}",
quantile(&timings, 0.5),
quantile(&timings, 0.1),
quantile(&timings, 0.9)
);
}
}
}
#[cfg(test)]
mod mapping_group_contract_tests {
use super::*;
#[test]
fn aliases_preserve_bytes_across_resize_relocation_and_release() {
const BASE: u64 = 0x0000_0003_0000_0000;
let mut memory = GuestMemory::new();
memory
.map_region(BASE - 16, 8, MemoryPermissions::READ_ONLY)
.unwrap();
memory
.map_region_with_data(BASE, 4, MemoryPermissions::READ_ONLY, &[1, 2, 3, 4])
.unwrap();
memory
.map_region(BASE + 16, 8, MemoryPermissions::READ_ONLY)
.unwrap();
let heap = memory.create_private_heap(0).unwrap();
assert_eq!(memory.map_heap_allocation(PROCESS_HEAP, 0), Ok(BASE));
assert_eq!(memory.map_heap_allocation(heap, 0), Ok(BASE));
assert_eq!(
memory.resize_heap_allocation(PROCESS_HEAP, BASE, 8, true),
Err(MemoryError::AllocationFailed)
);
assert_eq!(memory.resize_heap_allocation(heap, BASE, 8, true), Ok(BASE));
memory.write_bytes(BASE + 4, &[5, 6, 7, 8]).unwrap();
assert_eq!(memory.read_u64(BASE), Ok(0x0807_0605_0403_0201));
assert_eq!(
memory.resize_heap_allocation(heap, BASE, 32, true),
Err(MemoryError::AllocationFailed)
);
let moved = memory
.resize_heap_allocation(heap, BASE, 32, false)
.unwrap();
assert_ne!(moved, BASE);
let mut bytes = [0xff; 32];
memory.read_bytes(moved, &mut bytes).unwrap();
let mut expected = [0; 32];
expected[4..8].copy_from_slice(&[5, 6, 7, 8]);
assert_eq!(bytes, expected);
let mut failed = [0xff; 8];
assert_eq!(
memory.read_bytes(BASE, &mut failed),
Err(MemoryError::UnmappedAddress(BASE + 4))
);
assert_eq!(failed, [0xff; 8]);
assert_eq!(
memory.resize_heap_allocation(PROCESS_HEAP, BASE, 8, true),
Ok(BASE)
);
assert_eq!(memory.read_u64(BASE), Ok(0x0403_0201));
assert_eq!(
memory.resize_heap_allocation(PROCESS_HEAP, BASE, 2, true),
Ok(BASE)
);
assert_eq!(memory.read_u16(BASE + 2), Ok(0x0403));
assert!(memory.release_heap_allocation(PROCESS_HEAP, BASE));
assert_eq!(memory.read_u32(BASE), Ok(0x0403_0201));
assert_eq!(memory.read_u64(BASE - 16), Ok(0));
assert_eq!(memory.read_u64(BASE + 16), Ok(0));
}
}
#[cfg(test)]
mod bounds_access_contract_tests {
use super::*;
#[test]
fn permitted_empty_spans_and_high_addresses_keep_exact_bounds() {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(
u64::MAX - 8,
8,
MemoryPermissions::READ_WRITE,
&[1, 2, 3, 4, 5, 6, 7, 8],
)
.unwrap();
for at in [u64::MAX - 8, u64::MAX - 4, u64::MAX - 1, u64::MAX] {
assert_eq!(memory.read_bytes(at, &mut []), Ok(()));
assert_eq!(memory.write_bytes(at, &[]), Ok(()));
}
assert_eq!(memory.read_u64(u64::MAX - 8), Ok(0x0807_0605_0403_0201));
assert_eq!(memory.read_u8(u64::MAX - 1), Ok(8));
let mut failed = [0xee; 2];
assert_eq!(
memory.read_bytes(u64::MAX - 1, &mut failed),
Err(MemoryError::Overflow)
);
assert_eq!(failed, [0xee; 2]);
assert_eq!(
memory.write_u16(u64::MAX - 1, 0xffff),
Err(MemoryError::Overflow)
);
assert_eq!(memory.read_u64(u64::MAX - 7), Err(MemoryError::Overflow));
assert_eq!(
memory.write_u64(u64::MAX - 7, u64::MAX),
Err(MemoryError::Overflow)
);
memory.write_u8(u64::MAX - 1, 0x99).unwrap();
let mut actual = [0; 8];
memory.read_bytes(u64::MAX - 8, &mut actual).unwrap();
assert_eq!(actual, [1, 2, 3, 4, 5, 6, 7, 0x99]);
}
}
#[cfg(test)]
mod mapping_search_contract_tests {
use super::*;
#[test]
fn every_mapping_and_gap_keeps_its_bytes_across_table_sizes() {
const BASE: u64 = 0x40_0000;
for count in [0usize, 1, 2, 3, 4, 5, 7, 8, 9, 15, 16, 17, 31, 32, 33] {
let mut memory = GuestMemory::new();
for index in (0..count).rev() {
memory
.map_region_with_data(
BASE + index as u64 * 0x100,
8,
MemoryPermissions::READ_WRITE,
&[(index + 1) as u8; 8],
)
.unwrap();
}
assert_eq!(
memory.read_u8(BASE - 1),
Err(MemoryError::UnmappedAddress(BASE - 1))
);
if count == 0 {
assert_eq!(
memory.read_u8(BASE),
Err(MemoryError::UnmappedAddress(BASE))
);
assert_eq!(
memory.write_u8(BASE, 1),
Err(MemoryError::UnmappedAddress(BASE))
);
assert_eq!(
memory.read_bytes(BASE, &mut []),
Err(MemoryError::UnmappedAddress(BASE))
);
}
for index in 0..count {
let address = BASE + index as u64 * 0x100;
let mut actual = [0; 8];
memory.read_bytes(address, &mut actual).unwrap();
assert_eq!(actual, [(index + 1) as u8; 8]);
let replacement = [0x80 + index as u8; 8];
memory.write_bytes(address, &replacement).unwrap();
memory.read_bytes(address, &mut actual).unwrap();
assert_eq!(actual, replacement);
assert_eq!(memory.read_bytes(address + 8, &mut []), Ok(()));
assert_eq!(
memory.read_u8(address + 8),
Err(MemoryError::UnmappedAddress(address + 8))
);
let mut failed = [0xee; 2];
assert_eq!(
memory.read_bytes(address + 7, &mut failed),
Err(MemoryError::UnmappedAddress(address + 8))
);
assert_eq!(failed, [0xee; 2]);
}
}
}
}
+96 -11
View File
@@ -17,6 +17,7 @@ mod gdk_queue;
mod heap;
mod modules;
mod platform_fixture;
mod process;
mod synch;
pub mod sysinfo;
mod task_fixture;
@@ -93,8 +94,14 @@ impl MockClock {
}
}
/// Move both readings forward by `intervals` 100-nanosecond ticks. Each
/// stops at its maximum, so neither ever runs backwards.
pub fn advance(&self, intervals: u64) {
self.current.fetch_add(intervals, Ordering::SeqCst);
self.current
.try_update(Ordering::SeqCst, Ordering::SeqCst, |current| {
Some(current.saturating_add(intervals))
})
.expect("clock update always returns a value");
self.performance_count
.try_update(Ordering::SeqCst, Ordering::SeqCst, |count| {
Some(count.saturating_add(intervals).min(MAX_PERFORMANCE_COUNT))
@@ -198,6 +205,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 +232,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 +256,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 +543,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 +710,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
+30 -3
View File
@@ -45,11 +45,38 @@ fn string_length(
limit: u64,
unit: StringUnit,
) -> Result<u64, ExitReason> {
const BLOCK: u64 = 256;
let budget = SCAN_BUDGET / unit.width();
for offset in 0..limit.min(budget) {
if unit.read(memory, address, offset)? == 0 {
return Ok(offset);
let scan = limit.min(budget);
let mut buffer = [0u8; 2 * BLOCK as usize];
let mut offset = 0;
while offset < scan {
let count = BLOCK.min(scan - offset);
let bytes = &mut buffer[..(count * unit.width()) as usize];
// A block that crosses into unmapped or unreadable memory is scanned
// one unit at a time, so a terminator before the boundary still ends
// the scan and the fault reports the first inaccessible unit.
let block = address
.checked_add(offset * unit.width())
.filter(|_| address != 0)
.is_some_and(|start| memory.read_bytes(start, bytes).is_ok());
for index in 0..count {
let value = if block {
match unit {
StringUnit::Byte => u16::from(bytes[index as usize]),
StringUnit::Wide => {
let at = 2 * index as usize;
u16::from_le_bytes([bytes[at], bytes[at + 1]])
}
}
} else {
unit.read(memory, address, offset + index)?
};
if value == 0 {
return Ok(offset + index);
}
}
offset += count;
}
if limit <= budget {
return Ok(limit);
+12
View File
@@ -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>,
+23
View File
@@ -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);
}
+10
View File
@@ -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);
+52 -11
View File
@@ -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;
@@ -130,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)?;
@@ -139,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);
+440 -11
View File
@@ -233,6 +233,22 @@ fn read_callbacks(bytes: &[u8], pe: &ParsedPe, address: u64) -> Result<Vec<u64>,
/// Bytes reserved at `thread_tls_base` for the thread's TLS pointer array.
const TLS_ARRAY_SIZE: usize = 0x1000;
/// Bytes read per step when a template is checked and then copied into its
/// block.
const TEMPLATE_COPY_CHUNK: usize = 4096;
/// Smallest template copied into the zeroed block instead of a staging buffer.
///
/// Release timings of original synthetic templates on an Apple M2 Pro put the
/// point where a second buffer dominates at 64 KiB. Below that, one read into
/// a staging buffer is as fast or faster.
const DIRECT_TEMPLATE_MIN: usize = 64 * 1024;
/// Templates at least this big keep the single staged read. On the same
/// machine, proving the bytes readable and then copying them was no faster
/// than the staging buffer once the template reached 1 MiB.
const DIRECT_TEMPLATE_LIMIT: usize = 1024 * 1024;
/// Set up TLS runtime state in guest memory:
/// 1. Assign TLS index 0 at `index_address`.
/// 2. Map the thread's TLS pointer array at `thread_tls_base`.
@@ -244,6 +260,12 @@ const TLS_ARRAY_SIZE: usize = 0x1000;
/// TLS pointer. Compiled code loads that pointer, indexes it by the module's
/// TLS index to find the data block, and then adds a variable's offset, so the
/// array and the data are separate regions.
///
/// The block is the template followed by `SizeOfZeroFill` zero bytes. A
/// template of at least 64 KiB and below 1 MiB is proved readable and then
/// copied into a zeroed block. Every other size is read once into a staging
/// buffer that initializes the block. Either way, a template that cannot be
/// read leaves the pointer array unmapped.
pub fn setup_tls(
tls: &TlsDirectory,
loaded_base: u64,
@@ -278,11 +300,19 @@ pub fn setup_tls(
let total_size = template_size + (tls.size_of_zero_fill as usize);
if total_size > 0 {
// Read template bytes from image
let mut template_data = vec![0u8; template_size];
if template_size > 0 {
memory.read_bytes(actual_start, &mut template_data)?;
}
let direct = (DIRECT_TEMPLATE_MIN..DIRECT_TEMPLATE_LIMIT).contains(&template_size);
// The read happens before anything is mapped, so a missing or
// unreadable template does not leave a pointer array behind.
let staged = if direct {
prove_template_readable(memory, actual_start, template_size)?;
None
} else {
let mut staged = vec![0u8; template_size];
if template_size > 0 {
memory.read_bytes(actual_start, &mut staged)?;
}
Some(staged)
};
// Allocate the pointer array and the per-thread TLS block.
let block_base = thread_tls_base
@@ -295,12 +325,17 @@ pub fn setup_tls(
TLS_ARRAY_SIZE,
MemoryPermissions::READ_WRITE,
)?;
memory.map_region_with_data(
block_base,
map_size,
MemoryPermissions::READ_WRITE,
&template_data,
)?;
if let Some(staged) = staged.as_deref() {
memory.map_region_with_data(
block_base,
map_size,
MemoryPermissions::READ_WRITE,
staged,
)?;
} else {
memory.map_region(block_base, map_size, MemoryPermissions::READ_WRITE)?;
copy_template(memory, actual_start, block_base, template_size)?;
}
// Slot 0 belongs to the index assigned above.
memory.write_u64(thread_tls_base, block_base)?;
}
@@ -308,6 +343,44 @@ pub fn setup_tls(
Ok(())
}
/// Read every template byte, discarding the contents.
///
/// Failure here means the template is not available. Callers map the block
/// only after this returns.
fn prove_template_readable(memory: &GuestMemory, addr: u64, len: usize) -> Result<(), TlsError> {
let mut chunk = [0u8; TEMPLATE_COPY_CHUNK];
let mut offset = 0usize;
while offset < len {
let n = (len - offset).min(TEMPLATE_COPY_CHUNK);
let at = addr
.checked_add(offset as u64)
.ok_or(MemoryError::Overflow)?;
memory.read_bytes(at, &mut chunk[..n])?;
offset += n;
}
Ok(())
}
/// Copy `len` bytes from `src` to `dst`. `dst` is already zeroed, which is the
/// template's `SizeOfZeroFill` and the rounded tail of the block.
fn copy_template(memory: &mut GuestMemory, src: u64, dst: u64, len: usize) -> Result<(), TlsError> {
let mut chunk = [0u8; TEMPLATE_COPY_CHUNK];
let mut offset = 0usize;
while offset < len {
let n = (len - offset).min(TEMPLATE_COPY_CHUNK);
let from = src
.checked_add(offset as u64)
.ok_or(MemoryError::Overflow)?;
let to = dst
.checked_add(offset as u64)
.ok_or(MemoryError::Overflow)?;
memory.read_bytes(from, &mut chunk[..n])?;
memory.write_bytes(to, &chunk[..n])?;
offset += n;
}
Ok(())
}
/// Execute all registered TLS callbacks in sequence.
/// Signature: void (NTAPI *PIMAGE_TLS_CALLBACK)(PVOID DllHandle, DWORD Reason, PVOID Reserved);
/// - RCX = DllHandle (loaded_base)
@@ -392,6 +465,8 @@ mod tests {
use super::*;
use crate::pe::PeSection;
use std::hint::black_box;
use std::time::Instant;
const IMAGE_BASE: u64 = 0x1_4000_0000;
const SECTION_RVA: u32 = 0x1000;
@@ -680,4 +755,358 @@ mod tests {
assert_eq!(none, Ok(0));
}
}
/// Bytes that do not repeat every 256 or every 4096 bytes, so a chunk
/// copied from the wrong offset cannot match.
fn synthetic_template(len: usize) -> Vec<u8> {
(0..len)
.map(|index| {
let mixed = index ^ (index >> 8) ^ (index >> 16);
mixed.wrapping_mul(131).wrapping_add(17) as u8
})
.collect()
}
/// Image template at `template_at`, with `sentinel` 0xA5 bytes after it, and
/// a writable index that does not start at zero.
fn template_memory(
template_at: u64,
template: &[u8],
sentinel: usize,
index_at: u64,
) -> GuestMemory {
let mut image = template.to_vec();
image.extend(std::iter::repeat_n(0xA5, sentinel));
let map = (image.len() + 0xFFF) & !0xFFF;
image.resize(map, 0);
let mut memory = GuestMemory::new();
memory
.map_region_with_data(template_at, map, MemoryPermissions::READ_ONLY, &image)
.unwrap();
memory
.map_region_with_data(index_at, 0x1000, MemoryPermissions::READ_WRITE, &[0xFF; 8])
.unwrap();
memory
}
fn directory_at(
template_at: u64,
template_len: u64,
index_at: u64,
zero_fill: u32,
) -> TlsDirectory {
TlsDirectory {
raw_data_start_va: template_at,
raw_data_end_va: template_at + template_len,
index_address: index_at,
size_of_zero_fill: zero_fill,
..TlsDirectory::default()
}
}
fn assert_block(
memory: &GuestMemory,
thread: u64,
index: u64,
template: &[u8],
zero_fill: usize,
) {
assert_eq!(memory.read_u32(index).unwrap(), 0);
let block = memory.read_u64(thread).unwrap();
assert_eq!(block, thread + 0x1000, "the data block is the next page");
// The block is mapped up to the next page boundary and no further.
let mapped = (template.len() + zero_fill + 0xFFF) & !0xFFF;
let mut got = vec![0xEEu8; mapped];
memory.read_bytes(block, &mut got).unwrap();
assert_eq!(&got[..template.len()], template);
assert!(got[template.len()..].iter().all(|byte| *byte == 0));
let end = block + mapped as u64;
assert_eq!(memory.read_u8(end), Err(MemoryError::UnmappedAddress(end)));
}
const TEMPLATE_AT: u64 = 0x2_0020_0000;
const INDEX_AT: u64 = 0x2_0000_1000;
const THREAD_AT: u64 = 0x5_0000_0000;
#[test]
fn a_small_template_is_copied_and_zero_fill_does_not_take_the_following_bytes() {
let template = synthetic_template(48);
let mut memory = template_memory(TEMPLATE_AT, &template, 16, INDEX_AT);
setup_tls(
&directory_at(TEMPLATE_AT, template.len() as u64, INDEX_AT, 16),
IMAGE_BASE,
IMAGE_BASE,
&mut memory,
THREAD_AT,
)
.unwrap();
assert_block(&memory, THREAD_AT, INDEX_AT, &template, 16);
let mut tail = [0u8; 16];
memory
.read_bytes(TEMPLATE_AT + template.len() as u64, &mut tail)
.unwrap();
assert_eq!(tail, [0xA5; 16]);
let block = memory.read_u64(THREAD_AT).unwrap();
memory.write_u64(block + 8, 0x0102_0304_0506_0708).unwrap();
let mut image = [0u8; 8];
memory.read_bytes(TEMPLATE_AT + 8, &mut image).unwrap();
assert_eq!(image, template[8..16]);
}
#[test]
fn the_staged_and_direct_copy_boundaries_keep_every_template_byte() {
for len in [
DIRECT_TEMPLATE_MIN - 1,
DIRECT_TEMPLATE_MIN,
DIRECT_TEMPLATE_MIN + TEMPLATE_COPY_CHUNK + 100,
DIRECT_TEMPLATE_LIMIT - 1,
DIRECT_TEMPLATE_LIMIT,
] {
let template = synthetic_template(len);
let mut memory = template_memory(TEMPLATE_AT, &template, 24, INDEX_AT);
setup_tls(
&directory_at(TEMPLATE_AT, template.len() as u64, INDEX_AT, 24),
IMAGE_BASE,
IMAGE_BASE,
&mut memory,
THREAD_AT,
)
.unwrap();
assert_block(&memory, THREAD_AT, INDEX_AT, &template, 24);
let mut tail = [0u8; 24];
memory
.read_bytes(TEMPLATE_AT + template.len() as u64, &mut tail)
.unwrap();
assert_eq!(tail, [0xA5; 24], "len {len}");
}
}
#[test]
fn a_rebased_direct_copy_reads_the_loaded_image() {
let template = synthetic_template(DIRECT_TEMPLATE_MIN);
let preferred = 0x1_4000_0000u64;
let loaded = preferred + 0x80_0000;
let template_at = preferred + 0x20_0000;
let index_at = preferred + 0x1000;
let mut memory =
template_memory(template_at + 0x80_0000, &template, 0, index_at + 0x80_0000);
setup_tls(
&directory_at(template_at, template.len() as u64, index_at, 8),
loaded,
preferred,
&mut memory,
THREAD_AT,
)
.unwrap();
assert_block(&memory, THREAD_AT, index_at + 0x80_0000, &template, 8);
}
#[test]
fn an_unreadable_template_maps_no_pointer_array() {
for len in [32usize, DIRECT_TEMPLATE_MIN, DIRECT_TEMPLATE_MIN + 50] {
let mut missing = GuestMemory::new();
missing
.map_region_with_data(INDEX_AT, 0x1000, MemoryPermissions::READ_WRITE, &[0xFF; 8])
.unwrap();
let missing_result = setup_tls(
&directory_at(TEMPLATE_AT, len as u64, INDEX_AT, 0),
IMAGE_BASE,
IMAGE_BASE,
&mut missing,
THREAD_AT,
);
assert_eq!(
missing_result,
Err(TlsError::Memory(MemoryError::UnmappedAddress(TEMPLATE_AT))),
"{len}"
);
assert_eq!(missing.read_u32(INDEX_AT).unwrap(), 0);
assert!(matches!(
missing.read_u64(THREAD_AT),
Err(MemoryError::UnmappedAddress(_))
));
let mut denied = GuestMemory::new();
denied
.map_region(TEMPLATE_AT, len.max(0x1000), MemoryPermissions::NO_ACCESS)
.unwrap();
denied
.map_region_with_data(INDEX_AT, 0x1000, MemoryPermissions::READ_WRITE, &[0xFF; 8])
.unwrap();
let denied_result = setup_tls(
&directory_at(TEMPLATE_AT, len as u64, INDEX_AT, 0),
IMAGE_BASE,
IMAGE_BASE,
&mut denied,
THREAD_AT,
);
assert_eq!(
denied_result,
Err(TlsError::Memory(MemoryError::PermissionViolation {
address: TEMPLATE_AT,
required: "read",
})),
"{len}"
);
assert_eq!(denied.read_u32(INDEX_AT).unwrap(), 0);
assert!(matches!(
denied.read_u64(THREAD_AT),
Err(MemoryError::UnmappedAddress(_))
));
}
}
#[test]
fn a_direct_copy_template_that_runs_out_of_its_mapping_maps_nothing() {
let len = DIRECT_TEMPLATE_MIN + 100;
let mut memory = GuestMemory::new();
// Only the first chunk is mapped. The rest of the template is not.
memory
.map_region_with_data(
TEMPLATE_AT,
TEMPLATE_COPY_CHUNK,
MemoryPermissions::READ_ONLY,
&synthetic_template(TEMPLATE_COPY_CHUNK),
)
.unwrap();
memory
.map_region_with_data(INDEX_AT, 0x1000, MemoryPermissions::READ_WRITE, &[0xFF; 8])
.unwrap();
let result = setup_tls(
&directory_at(TEMPLATE_AT, len as u64, INDEX_AT, 0),
IMAGE_BASE,
IMAGE_BASE,
&mut memory,
THREAD_AT,
);
// The same first unreadable byte the single staged read reports.
assert_eq!(
result,
Err(TlsError::Memory(MemoryError::UnmappedAddress(
TEMPLATE_AT + TEMPLATE_COPY_CHUNK as u64
)))
);
assert_eq!(memory.read_u32(INDEX_AT).unwrap(), 0);
assert!(matches!(
memory.read_u64(THREAD_AT),
Err(MemoryError::UnmappedAddress(_))
));
}
#[test]
fn an_empty_template_and_zero_fill_only_assigns_the_index() {
let mut memory = template_memory(TEMPLATE_AT, &[], 0, INDEX_AT);
setup_tls(
&directory_at(TEMPLATE_AT, 0, INDEX_AT, 0),
IMAGE_BASE,
IMAGE_BASE,
&mut memory,
THREAD_AT,
)
.unwrap();
assert_eq!(memory.read_u32(INDEX_AT).unwrap(), 0);
assert!(matches!(
memory.read_u64(THREAD_AT),
Err(MemoryError::UnmappedAddress(_))
));
}
#[test]
fn a_zero_fill_only_block_is_zero_and_separate_from_the_array() {
let mut memory = template_memory(TEMPLATE_AT, &[], 0, INDEX_AT);
setup_tls(
&directory_at(TEMPLATE_AT, 0, INDEX_AT, 24),
IMAGE_BASE,
IMAGE_BASE,
&mut memory,
THREAD_AT,
)
.unwrap();
assert_block(&memory, THREAD_AT, INDEX_AT, &[], 24);
}
/// Byte pattern from the before/after timing runs. It is not the pattern
/// the correctness tests use to catch a chunk copied from the wrong offset.
fn timed_template(len: usize) -> Vec<u8> {
(0..len)
.map(|index| (index.wrapping_mul(131).wrapping_add(17)) as u8)
.collect()
}
fn timed_guest(template_len: usize, zero_fill: u32) -> (GuestMemory, TlsDirectory) {
let template = timed_template(template_len);
let mut memory = GuestMemory::new();
if template_len > 0 {
let map = (template_len + 0xFFF) & !0xFFF;
memory
.map_region_with_data(TEMPLATE_AT, map, MemoryPermissions::READ_ONLY, &template)
.unwrap();
}
memory
.map_region_with_data(INDEX_AT, 0x1000, MemoryPermissions::READ_WRITE, &[0xFF; 8])
.unwrap();
(
memory,
directory_at(TEMPLATE_AT, template_len as u64, INDEX_AT, zero_fill),
)
}
#[test]
#[ignore = "manual TLS template timing run; release build on an otherwise idle host"]
fn tls_template_initialization_profile() {
// Sizes, zero fill and batch counts from the interleaved before/after runs.
let cases = [
(64usize, 0u32, 80usize),
(4096, 0, 40),
(65535, 0, 20),
(65536, 128, 16),
(262144, 0, 6),
(786432, 0, 4),
(1048576, 0, 4),
(0, 1048576, 4),
];
for (template_len, zero_fill, batch) in cases {
let (mut memory, directory) = timed_guest(template_len, zero_fill);
setup_tls(&directory, IMAGE_BASE, IMAGE_BASE, &mut memory, THREAD_AT).unwrap();
if template_len > 0 {
let template = timed_template(template_len);
let block = memory.read_u64(THREAD_AT).unwrap();
let mut byte = [0u8; 1];
memory.read_bytes(block, &mut byte).unwrap();
assert_eq!(byte[0], template[0]);
memory
.read_bytes(block + template_len as u64 - 1, &mut byte)
.unwrap();
assert_eq!(byte[0], template[template_len - 1]);
}
let mut samples = Vec::new();
for run in 0..33 {
let mut guests: Vec<_> = (0..batch)
.map(|_| timed_guest(template_len, zero_fill))
.collect();
let start = Instant::now();
for (memory, directory) in &mut guests {
setup_tls(directory, IMAGE_BASE, IMAGE_BASE, memory, THREAD_AT).unwrap();
black_box(memory);
}
if run >= 2 {
let per_ns = start.elapsed().as_secs_f64() * 1e9 / batch as f64;
samples.push(per_ns);
}
}
samples.sort_by(f64::total_cmp);
let n = samples.len();
let mean = samples.iter().sum::<f64>() / n as f64;
let sample_variance = samples
.iter()
.map(|sample| (sample - mean).powi(2))
.sum::<f64>()
/ (n - 1) as f64;
println!(
"template={template_len} zero_fill={zero_fill} batch={batch} n={n} median_ns={:.1} sample_variance_ns2={sample_variance:.1}",
samples[n / 2]
);
}
}
}
+4
View File
@@ -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,
+91
View File
@@ -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) {
+9 -1
View File
@@ -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
View File
@@ -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,
+69 -18
View File
@@ -1688,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"
@@ -2817,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),
@@ -2915,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),
];
// ---------------------------------------------------------------------------
@@ -3614,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]
+302
View File
@@ -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);
}
+540
View File
@@ -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 = &registry
.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)
);
}
+325
View File
@@ -0,0 +1,325 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Repeated-frame regression for the guest graphics context (issue #148).
//!
//! One device, queue, allocator and command list are driven through the
//! per-frame loop a D3D12 guest uses: reset, record, close, execute. Each
//! frame changes the guest-backed vertex data, the clear colour or the draw
//! parameters. Expected pixels are written out by hand below for triangles
//! chosen so their coverage of a 4×3 viewport is obvious; they are not
//! computed by the rasterizer under test. These tests use the software
//! reference backend only; no native Metal result is claimed here.
use xenora_loader::graphics::{
CommandListType, GraphicsBackendId, GraphicsContext, GraphicsError, GraphicsHandle,
ResourceDesc, ResourceDimension, ResourceStates,
};
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
const WIDTH: usize = 4;
const HEIGHT: usize = 3;
const VERTICES: u64 = 0x0010_0000;
/// Two triangles of three float4 positions each.
const VERTEX_BYTES: usize = 96;
const RED: [u8; 4] = [255, 0, 0, 255];
/// Covers every pixel centre of the viewport.
const FULL: [[f32; 4]; 3] = [
[-1.0, -1.0, 0.0, 1.0],
[3.0, -1.0, 0.0, 1.0],
[-1.0, 3.0, 0.0, 1.0],
];
/// Its right edge is x = 0 in clip space, so it covers the two left columns
/// (centres at x = -0.75 and -0.25) and none of the two right ones.
const LEFT_HALF: [[f32; 4]; 3] = [
[0.0, 10.0, 0.0, 1.0],
[0.0, -10.0, 0.0, 1.0],
[-30.0, 0.0, 0.0, 1.0],
];
/// Lies wholly outside the viewport.
const OFFSCREEN: [[f32; 4]; 3] = [
[2.0, 2.0, 0.0, 1.0],
[3.0, 2.0, 0.0, 1.0],
[2.0, 3.0, 0.0, 1.0],
];
struct Rig {
ctx: GraphicsContext,
memory: GuestMemory,
queue: GraphicsHandle,
alloc: GraphicsHandle,
list: GraphicsHandle,
vertices: GraphicsHandle,
target: GraphicsHandle,
}
fn rig() -> Rig {
let mut ctx = GraphicsContext::new();
let device = ctx.create_device().unwrap();
let queue = ctx
.create_command_queue(device, CommandListType::Direct)
.unwrap();
let alloc = ctx
.create_command_allocator(device, CommandListType::Direct)
.unwrap();
let list = ctx
.create_command_list(device, alloc, CommandListType::Direct)
.unwrap();
// A new list starts open; close it so every frame begins with a reset.
ctx.close_command_list(list).unwrap();
let mut memory = GuestMemory::new();
memory
.map_region(VERTICES, 0x1000, MemoryPermissions::READ_WRITE)
.unwrap();
let buffer = ResourceDesc {
dimension: ResourceDimension::Buffer,
width: VERTEX_BYTES as u64,
height: 1,
depth_or_array_size: 1,
mip_levels: 1,
format_rgba8: false,
};
let vertices = ctx
.create_committed_resource(
device,
buffer,
ResourceStates::VERTEX_AND_CONSTANT_BUFFER,
Some(VERTICES),
)
.unwrap();
let texture = ResourceDesc {
dimension: ResourceDimension::Texture2D,
width: WIDTH as u64,
height: HEIGHT as u32,
depth_or_array_size: 1,
mip_levels: 1,
format_rgba8: true,
};
let target = ctx
.create_committed_resource(device, texture, ResourceStates::PRESENT, None)
.unwrap();
Rig {
ctx,
memory,
queue,
alloc,
list,
vertices,
target,
}
}
fn write_triangle(memory: &mut GuestMemory, slot: u64, triangle: [[f32; 4]; 3]) {
let bytes: Vec<u8> = triangle
.iter()
.flatten()
.flat_map(|value| value.to_le_bytes())
.collect();
memory.write_bytes(VERTICES + slot * 48, &bytes).unwrap();
}
/// Pixels with `columns` red from the left and the rest in `clear`.
fn expected(columns: usize, clear: [u8; 4]) -> Vec<u8> {
(0..WIDTH * HEIGHT)
.flat_map(|pixel| if pixel % WIDTH < columns { RED } else { clear })
.collect()
}
struct Draw {
clear: [u8; 4],
offset: usize,
vertex_count: u32,
instance_count: u32,
start_vertex: u32,
start_instance: u32,
}
impl Draw {
fn one(clear: [u8; 4]) -> Self {
Self {
clear,
offset: 0,
vertex_count: 3,
instance_count: 1,
start_vertex: 0,
start_instance: 0,
}
}
}
/// Record one frame: target to RENDER_TARGET, draw, back to PRESENT.
fn record(rig: &mut Rig, draw: &Draw) -> Result<(), GraphicsError> {
let ctx = &mut rig.ctx;
ctx.reset_command_list(rig.list, rig.alloc)?;
ctx.cmd_resource_barrier(
rig.list,
rig.target,
ResourceStates::PRESENT,
ResourceStates::RENDER_TARGET,
)?;
ctx.cmd_set_viewport(rig.list, WIDTH, HEIGHT)?;
ctx.cmd_set_render_targets(rig.list, Some(rig.target), draw.clear)?;
ctx.cmd_set_vertex_buffer(rig.list, rig.vertices, draw.offset, 48)?;
ctx.cmd_draw_instanced(
rig.list,
draw.vertex_count,
draw.instance_count,
draw.start_vertex,
draw.start_instance,
)?;
ctx.cmd_resource_barrier(
rig.list,
rig.target,
ResourceStates::RENDER_TARGET,
ResourceStates::PRESENT,
)?;
ctx.close_command_list(rig.list)
}
fn frame(rig: &mut Rig, draw: &Draw) -> Result<(Vec<u8>, usize), GraphicsError> {
record(rig, draw)?;
let outcome = rig
.ctx
.execute_command_list(rig.queue, rig.list, &rig.memory)?;
assert_eq!(outcome.backend, GraphicsBackendId::SoftwareReference);
assert_eq!((outcome.width, outcome.height), (WIDTH, HEIGHT));
Ok((outcome.pixels, outcome.draw_count))
}
fn frame_index(rig: &Rig) -> u64 {
rig.ctx.last_presentation.lock().unwrap().frame_index
}
#[test]
fn each_frame_reflects_its_own_guest_vertices_and_clear_colour() {
let mut rig = rig();
let frames = [
(LEFT_HALF, [0, 0, 64, 255], 2),
(FULL, [10, 20, 30, 255], WIDTH),
(OFFSCREEN, [1, 2, 3, 4], 0),
(LEFT_HALF, [9, 9, 9, 255], 2),
];
for (index, (triangle, clear, columns)) in frames.into_iter().enumerate() {
write_triangle(&mut rig.memory, 0, triangle);
let (pixels, draws) = frame(&mut rig, &Draw::one(clear)).unwrap();
let want = expected(columns, clear);
assert_eq!(pixels, want, "frame {index}");
assert_eq!(draws, 1, "frame {index}");
assert_eq!(frame_index(&rig), index as u64 + 1);
// The presentation holds this frame's pixels, not an earlier one's.
let presented = rig.ctx.last_presentation.lock().unwrap().pixels.clone();
assert_eq!(presented, want, "presented frame {index}");
}
}
#[test]
fn a_zero_instance_or_zero_vertex_frame_draws_nothing() {
let mut rig = rig();
write_triangle(&mut rig.memory, 0, FULL);
let clear = [5, 6, 7, 255];
for (vertices, instances) in [(3, 0), (0, 1), (2, 1)] {
let draw = Draw {
vertex_count: vertices,
instance_count: instances,
..Draw::one(clear)
};
let (pixels, draws) = frame(&mut rig, &draw).unwrap();
assert_eq!(pixels, expected(0, clear), "{vertices} x {instances}");
assert_eq!(draws, 0, "{vertices} x {instances}");
}
// The next ordinary frame still draws.
let (pixels, draws) = frame(&mut rig, &Draw::one(clear)).unwrap();
assert_eq!((pixels, draws), (expected(WIDTH, clear), 1));
}
#[test]
fn unsupported_draw_parameters_fail_and_the_next_frame_recovers() {
let mut rig = rig();
write_triangle(&mut rig.memory, 0, LEFT_HALF);
write_triangle(&mut rig.memory, 1, FULL);
let clear = [0, 0, 0, 255];
frame(&mut rig, &Draw::one(clear)).unwrap();
let rejected = [
Draw {
start_vertex: 3,
..Draw::one(clear)
},
Draw {
instance_count: 2,
..Draw::one(clear)
},
Draw {
start_instance: 1,
..Draw::one(clear)
},
Draw {
vertex_count: 6,
..Draw::one(clear)
},
];
for draw in &rejected {
// Only the draw is rejected. The barrier before it already ran, so
// the target is left in RENDER_TARGET, as a guest would see it.
let before = frame_index(&rig);
let result = frame(&mut rig, draw);
assert!(
matches!(result, Err(GraphicsError::Unsupported(_))),
"{result:?}"
);
assert_eq!(frame_index(&rig), before, "a failed frame is not presented");
rig.ctx.reset_command_list(rig.list, rig.alloc).unwrap();
rig.ctx
.cmd_resource_barrier(
rig.list,
rig.target,
ResourceStates::RENDER_TARGET,
ResourceStates::PRESENT,
)
.unwrap();
rig.ctx.close_command_list(rig.list).unwrap();
rig.ctx
.execute_command_list(rig.queue, rig.list, &rig.memory)
.unwrap();
}
// The second triangle is still reachable through the view offset.
let draw = Draw {
offset: 48,
..Draw::one(clear)
};
let (pixels, _) = frame(&mut rig, &draw).unwrap();
assert_eq!(pixels, expected(WIDTH, clear));
}
#[test]
fn a_vertex_view_outside_its_buffer_fails_without_reading_past_it() {
let mut rig = rig();
write_triangle(&mut rig.memory, 0, FULL);
write_triangle(&mut rig.memory, 1, FULL);
// Mapped guest memory continues past the buffer; the view must not.
write_triangle(&mut rig.memory, 2, FULL);
let clear = [0, 0, 0, 255];
for offset in [VERTEX_BYTES - 47, VERTEX_BYTES, usize::MAX - 100] {
let draw = Draw {
offset,
..Draw::one(clear)
};
assert_eq!(
frame(&mut rig, &draw),
Err(GraphicsError::IndexOutOfRange),
"offset {offset}"
);
rig.ctx.reset_command_list(rig.list, rig.alloc).unwrap();
rig.ctx
.cmd_resource_barrier(
rig.list,
rig.target,
ResourceStates::RENDER_TARGET,
ResourceStates::PRESENT,
)
.unwrap();
rig.ctx.close_command_list(rig.list).unwrap();
rig.ctx
.execute_command_list(rig.queue, rig.list, &rig.memory)
.unwrap();
}
}
+170
View File
@@ -0,0 +1,170 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! The injected guest clock read through every time service at once.
//!
//! Units come from the public Windows documentation: a FILETIME and the
//! unbiased interrupt time count 100-nanosecond intervals, the tick counts are
//! milliseconds, and a performance count divided by the reported frequency is
//! seconds. Expected values are worked out by hand from those units, not taken
//! from the service code.
mod support;
use std::sync::Arc;
use support::*;
use xenora_loader::services::{MockClock, ServicesState};
const KERNEL32: &str = "kernel32.dll";
const IMPORTS: &[(&str, &str)] = &[
(KERNEL32, "QueryPerformanceCounter"),
(KERNEL32, "QueryPerformanceFrequency"),
(KERNEL32, "GetTickCount"),
(KERNEL32, "GetTickCount64"),
(KERNEL32, "QueryUnbiasedInterruptTime"),
(KERNEL32, "GetSystemTimeAsFileTime"),
(KERNEL32, "Sleep"),
];
/// 2026-11-24 12:34:56 UTC as a FILETIME: 1,795,523,696 Unix seconds plus the
/// 11,644,473,600 seconds between 1601 and 1970, times ten million.
const START_FILETIME: u64 = 134_399_972_960_000_000;
/// Clock time that passes before the guest process starts.
const BEFORE_START: u64 = 1_234;
/// One reading of every time service.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Reading {
counter: u64,
frequency: u64,
tick: u64,
tick64: u64,
interrupt: u64,
filetime: u64,
}
fn guest() -> (Guest, Arc<MockClock>) {
let clock = Arc::new(MockClock::new(START_FILETIME));
clock.advance(BEFORE_START);
let guest = Guest::with_state(IMPORTS, &[], ServicesState::new(clock.clone()));
(guest, clock)
}
fn read(guest: &mut Guest) -> Reading {
let output = |guest: &mut Guest, symbol: &str| {
guest.memory.write_u64(SCRATCH, 0).unwrap();
guest.call(symbol, &[SCRATCH]);
guest.u64_at(SCRATCH)
};
Reading {
counter: output(guest, "QueryPerformanceCounter"),
frequency: output(guest, "QueryPerformanceFrequency"),
interrupt: output(guest, "QueryUnbiasedInterruptTime"),
filetime: output(guest, "GetSystemTimeAsFileTime"),
tick: guest.call("GetTickCount", &[]),
tick64: guest.call("GetTickCount64", &[]),
}
}
#[test]
fn every_time_service_reports_the_same_elapsed_time_in_its_own_unit() {
let (mut guest, clock) = guest();
// Uptime starts with the process; the counter and the calendar do not.
assert_eq!(
read(&mut guest),
Reading {
counter: 1_234,
frequency: 10_000_000,
tick: 0,
tick64: 0,
interrupt: 0,
filetime: 134_399_972_960_001_234,
}
);
// 3 s + 7 ms + 3 intervals.
clock.advance(30_070_003);
let after = read(&mut guest);
assert_eq!(
after,
Reading {
counter: 30_071_237,
frequency: 10_000_000,
tick: 3_007,
tick64: 3_007,
interrupt: 30_070_003,
filetime: 134_399_972_990_071_237,
}
);
assert_eq!((after.counter - 1_234) / after.frequency, 3);
// A guest sleep is the same time as a host advance: 250 ms.
assert_eq!(guest.call("Sleep", &[250]), 0);
assert_eq!(
read(&mut guest),
Reading {
counter: 32_571_237,
frequency: 10_000_000,
tick: 3_257,
tick64: 3_257,
interrupt: 32_570_003,
filetime: 134_399_972_992_571_237,
}
);
}
#[test]
fn no_reading_decreases_up_to_and_past_the_end_of_the_clock() {
let (mut guest, clock) = guest();
let mut last = read(&mut guest);
let steps = [
0,
1,
9_998,
1,
10_000_000,
1 << 40,
i64::MAX as u64 / 2,
i64::MAX as u64 / 2,
u64::MAX / 2,
u64::MAX,
1,
];
for step in steps {
clock.advance(step);
let now = read(&mut guest);
assert!(
now.counter >= last.counter,
"{step}: {now:?} after {last:?}"
);
assert!(now.tick64 >= last.tick64, "{step}: {now:?} after {last:?}");
assert!(
now.interrupt >= last.interrupt,
"{step}: {now:?} after {last:?}"
);
assert!(
now.filetime >= last.filetime,
"{step}: {now:?} after {last:?}"
);
// The 32-bit count is the low half of the 64-bit one and may wrap.
assert_eq!(now.tick, now.tick64 & 0xFFFF_FFFF, "{step}");
assert_eq!(now.frequency, 10_000_000, "{step}");
last = now;
}
// Both readings stop at their maximum; neither wraps.
let end = Reading {
counter: 0x7FFF_FFFF_FFFF_FFFF,
frequency: 10_000_000,
// (2^63 - 1 - 1,234) intervals, in whole milliseconds.
tick: 922_337_203_685_477 & 0xFFFF_FFFF,
tick64: 922_337_203_685_477,
interrupt: 0x7FFF_FFFF_FFFF_FFFF - 1_234,
filetime: u64::MAX,
};
assert_eq!(last, end);
// Sleeping at the end of the clock still returns and changes nothing.
assert_eq!(guest.call("Sleep", &[1]), 0);
assert_eq!(read(&mut guest), end);
}
+88
View File
@@ -0,0 +1,88 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Stable-toolchain replay of the `runtime_services` fuzz driver: seeded
//! pseudo-random call sequences against the standard service registry.
mod support;
use support::robustness::{ARG_REUSE_RESULT, ARG_ZERO, Driver};
/// xorshift64*, so every run uses the same inputs.
fn inputs(seed: u64, count: usize, length: usize) -> impl Iterator<Item = Vec<u8>> {
let mut state = seed;
(0..count).map(move |_| {
(0..length)
.map(|_| {
state ^= state >> 12;
state ^= state << 25;
state ^= state >> 27;
(state.wrapping_mul(0x2545_F491_4F6C_DD1D) >> 56) as u8
})
.collect()
})
}
#[test]
fn random_service_sequences_keep_memory_and_register_invariants() {
let driver = Driver::new();
assert!(driver.service_count() > 150, "{}", driver.service_count());
let mut total_calls = 0usize;
let mut max_distinct = 0usize;
for input in inputs(0x5EED_CAFE, 300, 1024) {
let stats = driver.run(&input);
total_calls += stats.calls;
max_distinct = max_distinct.max(stats.distinct_services);
}
// With memory init no longer consuming the corpus, 1 KiB inputs must
// reach the dispatch loop (each call needs 24 bytes plus a GS byte).
assert!(
total_calls >= 300 * 20,
"expected handlers to run; total_calls={total_calls}"
);
assert!(
max_distinct >= 8,
"expected multi-service coverage; max_distinct={max_distinct}"
);
assert_eq!(driver.run(&[]).calls, 0);
}
#[test]
fn encoded_sequences_invoke_handlers_and_reuse_handles() {
let driver = Driver::new();
let create = driver
.service_index("kernel32.dll", "CreateEventW")
.expect("CreateEventW");
let close = driver
.service_index("kernel32.dll", "CloseHandle")
.expect("CloseHandle");
let get_tick = driver
.service_index("kernel32.dll", "GetTickCount64")
.expect("GetTickCount64");
let query = driver
.service_index("kernel32.dll", "QueryPerformanceCounter")
.expect("QueryPerformanceCounter");
// CreateEventW(null, 0, 0, null) → CloseHandle(prior result) → GetTickCount64
// → QueryPerformanceCounter(writable via mode 2 is not used; zeros ok).
let zeros = [ARG_ZERO; 7];
let mut close_args = [ARG_ZERO; 7];
close_args[0] = ARG_REUSE_RESULT; // hObject from CreateEventW
let input = driver.encode_sequence(&[
(create, zeros),
(close, close_args),
(get_tick, zeros),
(query, zeros),
]);
let stats = driver.run(&input);
assert_eq!(stats.calls, 4);
assert_eq!(stats.distinct_services, 4);
}
#[test]
fn xmem_alloc_oom_artifact_fails_closed() {
// libFuzzer OOM from a ~3.7 GiB XMemAlloc before the virtual budget gated
// the mapping (fuzz/artifacts/runtime_services/oom-022d4084...).
let driver = Driver::new();
let stats = driver.run(&[242, 2, 24, 0, 248, 8, 9, 9, 8, 0, 0, 129, 191]);
assert!(stats.calls >= 1, "{stats:?}");
}
+187
View File
@@ -7,6 +7,7 @@
//! convention documentation, not from the registry or the handlers.
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
use xenora_loader::cpu::{CpuState, ExitReason, Register};
use xenora_loader::dbt::DbtEngine;
@@ -696,6 +697,76 @@ fn floating_arguments_and_results_use_xmm_registers() {
assert_eq!(float("fabsf", garbage | 0xBF80_0000) as u32, 0x3F80_0000); // -1
}
#[test]
fn guest_call_through_dbt_preserves_win64_abi_state() {
use Register::{R8, R9, R12, R13, R14, R15, Rax, Rbp, Rbx, Rcx, Rdi, Rdx, Rsi, Rsp};
let observed = Arc::new(Mutex::new(None::<(u64, u64, [u64; 4])>));
let seen = observed.clone();
let mut registry = ImportRegistry::new();
registry.register("t.dll", "F", move |_args, cpu, mem| {
let rsp = cpu.get(Rsp);
let shadow = [
mem.read_u64(rsp + 8).unwrap(),
mem.read_u64(rsp + 16).unwrap(),
mem.read_u64(rsp + 24).unwrap(),
mem.read_u64(rsp + 32).unwrap(),
];
*seen.lock().unwrap() = Some((rsp, cpu.rip, shadow));
cpu.set(Rcx, 0x11);
cpu.set(Rdx, 0x22);
cpu.set(R8, 0x33);
cpu.set(R9, 0x44);
for (reg, lane) in cpu.xmm[..6].iter_mut().enumerate() {
*lane = u128::from(0x55_u64 + reg as u64);
}
Ok(0x99AA_BBCC_DDEE_F001)
});
let image = build(&[("t.dll", Symbol::Name("F"))]);
let pe = ParsedPe::parse(&image.bytes).unwrap();
let mut memory = pe.load_into_memory(&image.bytes).unwrap().memory;
memory
.map_region(STACK, 0x1000, MemoryPermissions::READ_WRITE)
.unwrap();
registry
.bind_imports(&pe, &image.bytes, BASE, &mut memory)
.unwrap();
let mut engine = DbtEngine::new(256 * 1024).unwrap();
engine.set_import_registry(registry);
// Before CALL RSP is 16-byte aligned; CALL pushes return address so the
// callee sees RSP % 16 == 8. Shadow space is [entry_rsp+8, entry_rsp+40).
let initial_rsp = STACK_TOP;
assert_eq!(initial_rsp % 16, 0);
let entry_rsp_expected = initial_rsp - 8;
for slot in 0..4u64 {
memory
.write_u64(entry_rsp_expected + 8 + slot * 8, 0x7000 + slot)
.unwrap();
}
let mut cpu = CpuState::new(BASE + u64::from(CODE_RVA), initial_rsp);
let nonvolatile_gpr = [Rbx, Rbp, Rdi, Rsi, R12, R13, R14, R15];
for (index, register) in nonvolatile_gpr.into_iter().enumerate() {
cpu.set(register, 0x6100 + index as u64);
}
for (offset, lane) in cpu.xmm[6..16].iter_mut().enumerate() {
*lane = u128::from(0x6200_u64 + (offset + 6) as u64);
}
let result = engine.run(&mut cpu, &mut memory, 1000);
assert_eq!(result.exit_reason, ExitReason::Halt);
let (entry_rsp, _, shadow) = observed.lock().unwrap().expect("service ran");
assert_eq!(entry_rsp, entry_rsp_expected);
assert_eq!(entry_rsp % 16, 8);
assert_eq!(shadow, [0x7000, 0x7001, 0x7002, 0x7003]);
assert_eq!(cpu.get(Rax), 0x99AA_BBCC_DDEE_F001);
assert_eq!(cpu.get(Rsp), initial_rsp);
for (index, register) in nonvolatile_gpr.into_iter().enumerate() {
assert_eq!(cpu.get(register), 0x6100 + index as u64, "{register:?}");
}
for (offset, lane) in cpu.xmm[6..16].iter().enumerate() {
let index = offset + 6;
assert_eq!(*lane, u128::from(0x6200_u64 + index as u64), "xmm{index}");
}
}
#[test]
fn arguments_are_assigned_by_position_and_read_the_stack_after_the_fourth() {
let mut memory = GuestMemory::new();
@@ -957,6 +1028,122 @@ fn a_service_that_changes_a_nonvolatile_register_stops_the_guest() {
}
}
#[test]
fn service_may_write_its_caller_allocated_shadow_space() {
// Microsoft x64 calling convention: the caller reserves four home slots,
// but the callee may use them. Their contents are not nonvolatile state.
let (registry, mut memory, trampoline) = bound_service(|_, cpu, memory| {
for slot in 0..4u64 {
memory
.write_u64(cpu.get(Register::Rsp) + 8 + slot * 8, 0xA000 + slot)
.unwrap();
}
Ok(7)
});
let entry_rsp = STACK_TOP - 8;
memory.write_u64(entry_rsp, 0x1234).unwrap();
let mut cpu = CpuState::new(trampoline, entry_rsp);
assert_eq!(registry.dispatch(trampoline, &mut cpu, &mut memory), Ok(()));
assert_eq!(cpu.rip, 0x1234);
assert_eq!(cpu.get(Register::Rsp), entry_rsp + 8);
assert_eq!(cpu.get(Register::Rax), 7);
for slot in 0..4u64 {
assert_eq!(memory.read_u64(entry_rsp + 8 + slot * 8), Ok(0xA000 + slot));
}
}
#[test]
fn service_calls_preserve_win64_abi_state() {
// Microsoft x64 calling convention: at entry RSP % 16 == 8 (return address
// pushed by CALL). Callee preserves RBX,RBP,RDI,RSI,R12-R15 and XMM6-XMM15.
// Caller allocates 32-byte shadow/home space at [RSP+8, RSP+40), which
// the callee may use. This handler leaves it unchanged; the separate
// shadow-space test checks a handler that writes it. RAX carries the
// return value; RCX,RDX,R8,R9,R10,R11,XMM0-XMM5 are volatile.
use Register::{R8, R9, R10, R11, R12, R13, R14, R15, Rax, Rbp, Rbx, Rcx, Rdi, Rdx, Rsi, Rsp};
let observed = Arc::new(Mutex::new(None::<(u64, u64, [u64; 4], u64)>));
let seen = observed.clone();
let (registry, mut memory, trampoline) = bound_service(move |args, cpu, mem| {
let rsp = cpu.get(Rsp);
let shadow = [
mem.read_u64(rsp + 8).unwrap(),
mem.read_u64(rsp + 16).unwrap(),
mem.read_u64(rsp + 24).unwrap(),
mem.read_u64(rsp + 32).unwrap(),
];
*seen.lock().unwrap() = Some((rsp, cpu.rip, shadow, args.rcx));
// Clobber volatile registers; dispatcher must still return correctly and
// nonvolatile state must be preserved after return.
cpu.set(Rcx, 0xA1);
cpu.set(Rdx, 0xA2);
cpu.set(R8, 0xA3);
cpu.set(R9, 0xA4);
cpu.set(R10, 0xA5);
cpu.set(R11, 0xA6);
for (reg, lane) in cpu.xmm[..6].iter_mut().enumerate() {
*lane = u128::from(0xB0_u64 + reg as u64);
}
Ok(0x1122_3344_5566_7788)
});
// Win64: before CALL RSP is 16-byte aligned; CALL pushes return address,
// so callee entry sees RSP % 16 == 8.
let call_rsp = STACK_TOP - 8;
assert_eq!(call_rsp % 16, 8);
memory.write_u64(call_rsp, 0x1234).unwrap();
for slot in 0..4u64 {
memory
.write_u64(call_rsp + 8 + slot * 8, 0xC000 + slot)
.unwrap();
}
let mut cpu = CpuState::new(trampoline, call_rsp);
let nonvolatile_gpr = [Rbx, Rbp, Rdi, Rsi, R12, R13, R14, R15];
for (index, register) in nonvolatile_gpr.into_iter().enumerate() {
cpu.set(register, 0x5AA5_0000_0001_0000 + index as u64);
}
for (offset, lane) in cpu.xmm[6..16].iter_mut().enumerate() {
*lane = u128::from(0xD000_0000_0000_0000_u64 + (offset + 6) as u64);
}
cpu.set(Rcx, 0x1357_9BDF_2468_ACE0);
let result = registry.dispatch(trampoline, &mut cpu, &mut memory);
assert_eq!(result, Ok(()));
let (entry_rsp, entry_rip, shadow, entry_rcx) = observed.lock().unwrap().expect("service ran");
assert_eq!(entry_rip, trampoline);
assert_eq!(
entry_rsp, call_rsp,
"service sees caller RSP at return address"
);
assert_eq!(entry_rsp % 16, 8, "Win64 entry RSP must be 8 mod 16");
assert_eq!(entry_rcx, 0x1357_9BDF_2468_ACE0);
// Shadow/home space is caller-owned and must be addressable by the service.
assert_eq!(shadow, [0xC000, 0xC001, 0xC002, 0xC003]);
for slot in 0..4u64 {
assert_eq!(
memory.read_u64(call_rsp + 8 + slot * 8).unwrap(),
0xC000 + slot,
"this handler leaves its home slots untouched"
);
}
// Post-return ABI state.
assert_eq!(cpu.get(Rax), 0x1122_3344_5566_7788);
assert_eq!(cpu.get(Rsp), call_rsp + 8);
assert_eq!(cpu.rip, 0x1234);
for (index, register) in nonvolatile_gpr.into_iter().enumerate() {
assert_eq!(
cpu.get(register),
0x5AA5_0000_0001_0000 + index as u64,
"nonvolatile {register:?} must be preserved"
);
}
for (offset, lane) in cpu.xmm[6..16].iter().enumerate() {
let index = offset + 6;
assert_eq!(
*lane,
u128::from(0xD000_0000_0000_0000_u64 + index as u64),
"nonvolatile xmm{index} must be preserved"
);
}
}
#[test]
fn a_call_that_cannot_return_runs_no_service() {
let calls = Arc::new(AtomicUsize::new(0));
+275 -227
View File
@@ -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()
}
}
+241
View File
@@ -0,0 +1,241 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Drives sequences of standard runtime services with adversarial arguments.
//!
//! Shared by the `runtime_services` libFuzzer target and the stable-toolchain
//! regression test. Writable guest memory is filled from a deterministic
//! pattern, not from the fuzz input, so short corpora still reach the dispatch
//! loop. Each call takes its arguments from the remaining input: zero, all
//! ones, pointers into writable, read-only and unmapped memory, raw values,
//! small integers or an earlier result (so handles flow between calls). After
//! every call the driver checks that read-only and code memory are unchanged
//! and that the Win64 nonvolatile registers are preserved. A panic, a broken
//! invariant or a hang is a bug.
use std::collections::BTreeSet;
use std::sync::Arc;
use xenora_loader::cpu::{CpuState, Register};
use xenora_loader::imports::{ImportRegistry, Win64Args};
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
const WRITABLE: u64 = 0x5_0000;
const WRITABLE_LEN: usize = 0x1_0000;
const READ_ONLY: u64 = 0x7_0000;
const CODE: u64 = 0x7_8000;
const REGION_LEN: usize = 0x1000;
const STACK: u64 = 0x9_0000;
const STACK_LEN: usize = 0x2000;
const UNMAPPED: u64 = 0xDEAD_0000;
const MAX_CALLS: usize = 48;
/// Argument encoding mode that reuses an earlier handler result (handles).
#[allow(dead_code)] // used by the stable-toolchain regression test
pub const ARG_REUSE_RESULT: u8 = 8;
/// Argument encoding mode that supplies zero.
#[allow(dead_code)] // used by the stable-toolchain regression test
pub const ARG_ZERO: u8 = 0;
/// Services that wait on real time, run guest code or reach native Metal are
/// left out, so each input runs quickly and deterministically.
fn excluded(module: &str, symbol: &str) -> bool {
module.eq_ignore_ascii_case("xenora_fixture.dll")
|| matches!(symbol, "WSAPoll" | "XTaskQueueDispatch")
}
/// Outcome of one `Driver::run` against a single corpus input.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RunStats {
pub calls: usize,
pub distinct_services: usize,
}
pub struct Driver {
services: Vec<(String, String)>,
}
impl Default for Driver {
fn default() -> Self {
Self::new()
}
}
impl Driver {
pub fn new() -> Self {
let mut registry = ImportRegistry::new();
register_standard_services(
&mut registry,
Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))),
);
let mut services: Vec<(String, String)> = registry
.iter_registered()
.filter(|(module, symbol, _)| !excluded(module, symbol))
.map(|(module, symbol, _)| (module.to_owned(), symbol.to_owned()))
.collect();
services.sort();
Self { services }
}
#[allow(dead_code)] // used by the stable-toolchain regression test
pub fn service_count(&self) -> usize {
self.services.len()
}
/// Index of `module!symbol` in the driver's sorted service table.
#[allow(dead_code)] // used by the stable-toolchain regression test
pub fn service_index(&self, module: &str, symbol: &str) -> Option<usize> {
self.services
.iter()
.position(|(entry_module, entry_symbol)| {
entry_module.eq_ignore_ascii_case(module) && entry_symbol == symbol
})
}
/// Encode a deterministic multi-call corpus.
///
/// Each entry is `(service_index, [arg_mode; 7])`. Argument offsets are
/// zero; a trailing byte per call supplies the GS-base choice.
#[allow(dead_code)] // used by the stable-toolchain regression test
pub fn encode_sequence(&self, calls: &[(usize, [u8; 7])]) -> Vec<u8> {
let mut bytes = Vec::with_capacity(calls.len() * (2 + 7 * 3 + 1));
for &(index, modes) in calls {
bytes.extend_from_slice(&(index as u16).to_le_bytes());
for mode in modes {
bytes.extend_from_slice(&0u16.to_le_bytes());
bytes.push(mode);
}
bytes.push(0); // gs_base selector
}
bytes
}
/// Run one input against fresh service state and fresh guest memory.
pub fn run(&self, data: &[u8]) -> RunStats {
let mut registry = ImportRegistry::new();
let clock = Arc::new(MockClock::new(0x01DA_0000_0000_0000));
register_standard_services(&mut registry, Arc::new(ServicesState::new(clock)));
let mut input = Input(data);
let mut memory = GuestMemory::new();
memory
.map_region(WRITABLE, WRITABLE_LEN, MemoryPermissions::READ_WRITE)
.unwrap();
memory
.map_region(STACK, STACK_LEN, MemoryPermissions::READ_WRITE)
.unwrap();
// Deterministic fill: do not consume fuzz/corpus bytes here, or short
// inputs never reach the dispatch loop (WRITABLE_LEN is 65,536).
let fill: Vec<u8> = (0..WRITABLE_LEN)
.map(|i| (i.wrapping_mul(131).wrapping_add(17)) as u8)
.collect();
memory.write_bytes(WRITABLE, &fill).unwrap();
let read_only: Vec<u8> = (0..REGION_LEN).map(|i| (i * 7) as u8).collect();
memory
.map_region_with_data(
READ_ONLY,
REGION_LEN,
MemoryPermissions::READ_ONLY,
&read_only,
)
.unwrap();
memory
.map_region_with_data(
CODE,
REGION_LEN,
MemoryPermissions::READ_EXECUTE,
&[0xC3; REGION_LEN],
)
.unwrap();
let mut results = vec![0u64];
let mut seen = BTreeSet::new();
let mut calls = 0usize;
for _ in 0..MAX_CALLS {
let Some(selector) = input.u16() else { break };
let index = selector as usize % self.services.len();
let (module, symbol) = &self.services[index];
let mut args = [0u64; 7];
for arg in &mut args {
*arg = input.argument(&results);
}
let rsp = STACK + STACK_LEN as u64 / 2;
let mut cpu = CpuState::new(CODE, rsp);
cpu.gs_base = [0x7_F000, 0x7_F800][input.byte_or(0) as usize % 2];
for (register, value) in [Register::Rcx, Register::Rdx, Register::R8, Register::R9]
.into_iter()
.zip(args)
{
cpu.set(register, value);
}
for (slot, value) in args[4..].iter().enumerate() {
memory
.write_u64(rsp + 40 + 8 * slot as u64, *value)
.unwrap();
}
use Register::{R12, R13, R14, R15, Rbp, Rbx, Rdi, Rsi, Rsp};
let preserved = [Rbx, Rbp, Rdi, Rsi, Rsp, R12, R13, R14, R15];
let before = preserved.map(|register| cpu.get(register));
let service = registry
.binding(module, symbol)
.expect("registered service");
let outcome = (service.handler)(&Win64Args::new(&cpu), &mut cpu, &mut memory);
assert_eq!(
preserved.map(|register| cpu.get(register)),
before,
"{module}!{symbol} changed a nonvolatile register"
);
let mut check = vec![0; REGION_LEN];
memory.read_bytes(READ_ONLY, &mut check).unwrap();
assert_eq!(check, read_only, "{module}!{symbol} wrote read-only memory");
memory.read_bytes(CODE, &mut check).unwrap();
assert!(
check.iter().all(|&byte| byte == 0xC3),
"{module}!{symbol} wrote code memory"
);
calls += 1;
seen.insert((module.clone(), symbol.clone()));
if let Ok(value) = outcome {
results.push(value);
}
}
RunStats {
calls,
distinct_services: seen.len(),
}
}
}
struct Input<'a>(&'a [u8]);
impl Input<'_> {
fn take<const N: usize>(&mut self) -> Option<[u8; N]> {
let (head, rest) = self.0.split_first_chunk::<N>()?;
self.0 = rest;
Some(*head)
}
fn byte_or(&mut self, default: u8) -> u8 {
self.take::<1>().map_or(default, |[byte]| byte)
}
fn u16(&mut self) -> Option<u16> {
self.take::<2>().map(u16::from_le_bytes)
}
fn argument(&mut self, results: &[u64]) -> u64 {
let offset = u64::from(self.u16().unwrap_or(0));
match self.byte_or(0) % 9 {
0 => 0,
1 => u64::MAX,
2 => WRITABLE + offset % WRITABLE_LEN as u64,
3 => READ_ONLY + offset % REGION_LEN as u64,
4 => CODE + offset % REGION_LEN as u64,
5 => UNMAPPED + offset,
6 => self.take::<8>().map_or(offset, u64::from_le_bytes),
7 => offset % 512,
_ => results[offset as usize % results.len()],
}
}
}
+7
View File
@@ -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",
+72
View File
@@ -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
+54 -6
View File
@@ -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,
+34
View File
@@ -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]]
+362 -4
View File
@@ -2,6 +2,7 @@
//! Verified compilation for Xenora's synthetic compute and graphics ABIs.
use std::collections::HashMap;
use std::fmt::{self, Write};
mod graphics;
@@ -31,6 +32,26 @@ pub struct CompiledShader {
pub msl: String,
}
/// Optional translation passes applied after verification.
///
/// Default options preserve the historical IR shape: constants from scalar
/// evaluation and immediates remain, pure vector expressions between
/// constants are not rewritten, and duplicate pure expressions are not reused.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct CompileOptions {
/// Replace pure vector unary/binary ops whose operands are already
/// `const.u32` with a single constant. Floating-point ops fold only when
/// the existing exact positive-normal rules accept the result. Loads,
/// stores, lane masks, merges and branches are never folded.
pub fold_constants: bool,
/// Reuse the first result of an equivalent pure vector unary or binary
/// expression. Equivalence is the same operation and the same operand
/// values in the same order; constant operands compare by bit pattern.
/// Loads, stores, constants, lane masks, merges, branches and other
/// mask-dependent or side-effecting ops are never reused.
pub eliminate_common_subexpressions: bool,
}
#[derive(Debug)]
pub enum CompileError {
InvalidLength {
@@ -141,6 +162,9 @@ enum Op {
fallthrough: Value,
taken: Value,
},
/// The value is the earlier pure result `source`. The definition index stays
/// so later operands do not need renumbering.
Reuse(Value),
}
impl Op {
@@ -172,6 +196,7 @@ impl Op {
fallthrough,
taken,
} => vec![mask, fallthrough, taken],
Self::Reuse(source) => vec![source],
}
}
@@ -248,6 +273,7 @@ impl Op {
_ => unreachable!("not a VCC arithmetic operation"),
}
}
Self::Reuse(source) => name(source),
Self::Store(_)
| Self::ScalarBranch { .. }
| Self::CarryMask { .. }
@@ -289,7 +315,7 @@ fn compare_expression(op: VectorCompareOp, left: &str, right: &str) -> String {
}
}
#[derive(Clone, Copy)]
#[derive(Clone, Copy, PartialEq, Eq)]
enum Binary {
FloatAdd,
FloatMul,
@@ -475,10 +501,28 @@ fn exact_float_result(operator: Binary, left: KnownBits, right: KnownBits) -> Op
/// Compiles explicitly tagged raw machine code to a synthetic Metal compute kernel.
///
/// Bind equal-length disjoint input and output word buffers and dispatch one
/// invocation per word in a one-dimensional grid.
/// invocation per word in a one-dimensional grid. Equivalent to
/// [`compile_with`] using [`CompileOptions::default`].
pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShader, CompileError> {
compile_with(architecture, bytes, CompileOptions::default())
}
/// Compiles like [`compile`], with optional IR passes selected by `options`.
pub fn compile_with(
architecture: Architecture,
bytes: &[u8],
options: CompileOptions,
) -> Result<CompiledShader, CompileError> {
let decoded = decode_fixture(architecture, bytes)?;
let operations = lift(&decoded, bytes.len())?;
let mut operations = lift(&decoded, bytes.len())?;
if options.fold_constants {
fold_constant_ops(&mut operations);
}
// Fold first so a constant expression is `const.u32` before reuse. CSE does
// not fold, and it does not turn those constants back into arithmetic.
if options.eliminate_common_subexpressions {
eliminate_common_subexpressions(&mut operations);
}
let disassembly = decoded.iter().map(|line| format!("{line}\n")).collect();
let mut ir = String::new();
@@ -658,6 +702,10 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
format!("store.u32 output[index], {value}"),
format!("output[index] = {value};"),
),
Op::Reuse(source) => (
format!("{dest} = reuse.u32 {source}"),
format!("uint {dest} = {source};"),
),
};
// Writing to a String is infallible.
let _ = writeln!(ir, "{offset:04x}: {step}");
@@ -1462,6 +1510,265 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
})
}
/// Reuse the first equivalent pure vector unary or binary.
///
/// Equivalence is the operation plus its operand values in order. Constant
/// operands match by bit pattern, so two temps folded to the same `const.u32`
/// compare equal. That match only selects reuse: an op that is kept keeps
/// its own constant operands, so a shader with no repeat compiles unchanged.
/// Loads, stores, the constant definitions themselves, lane masks, merges,
/// branches and other mask-dependent or side-effecting ops are never
/// candidates. A reused definition stays at its index as `reuse.u32`.
fn eliminate_common_subexpressions(operations: &mut [(usize, Op)]) {
let mut expr_alias = vec![None; operations.len()];
let mut const_bits: HashMap<u32, usize> = HashMap::new();
let mut seen: Vec<(PureExpr, usize)> = Vec::new();
for index in 0..operations.len() {
let current = operations[index].1;
if let Op::Constant(bits) = current {
const_bits.entry(bits).or_insert(index);
continue;
}
let canonical = match current {
Op::Unary(operator, source) => Op::Unary(
operator,
equivalent_value(&expr_alias, &const_bits, operations, source),
),
Op::Binary(operator, left, right) => Op::Binary(
operator,
equivalent_value(&expr_alias, &const_bits, operations, left),
equivalent_value(&expr_alias, &const_bits, operations, right),
),
other => other,
};
let rewritten = map_uses(current, |value| reused_value(&expr_alias, value));
if let Some(key) = pure_expr(canonical) {
if let Some(&(_, first)) = seen.iter().find(|(seen_key, _)| *seen_key == key) {
expr_alias[index] = Some(first);
operations[index].1 = Op::Reuse(Value(first));
continue;
}
seen.push((key, index));
}
operations[index].1 = rewritten;
}
}
fn reused_value(expr_alias: &[Option<usize>], value: Value) -> Value {
match expr_alias.get(value.0).and_then(|slot| *slot) {
Some(index) => Value(index),
None => value,
}
}
/// SSA value to use when matching a pure expression. Follows a reuse edge, then
/// the earliest constant with the same bits.
fn equivalent_value(
expr_alias: &[Option<usize>],
const_bits: &HashMap<u32, usize>,
operations: &[(usize, Op)],
value: Value,
) -> Value {
let root = reused_value(expr_alias, value);
match operations.get(root.0).map(|(_, operation)| *operation) {
Some(Op::Constant(bits)) => const_bits.get(&bits).copied().map(Value).unwrap_or(root),
_ => root,
}
}
fn map_uses(operation: Op, map: impl Fn(Value) -> Value) -> Op {
match operation {
Op::Load | Op::Constant(_) | Op::ScalarBranch { .. } => operation,
Op::Binary(operator, left, right) => Op::Binary(operator, map(left), map(right)),
Op::Unary(operator, source) => Op::Unary(operator, map(source)),
Op::MergeLanes {
mask,
active,
inactive,
} => Op::MergeLanes {
mask,
active: map(active),
inactive: map(inactive),
},
Op::Store(value) => Op::Store(map(value)),
Op::VccArithmetic {
primitive,
left,
right,
mask,
flag,
} => Op::VccArithmetic {
primitive,
left: map(left),
right: map(right),
mask: map(mask),
flag,
},
Op::CarryMask { flag, exec } => Op::CarryMask {
flag: map(flag),
exec,
},
Op::LaneMask {
op,
name,
sdst,
src0,
src1,
high,
exec,
} => Op::LaneMask {
op,
name,
sdst,
src0: map(src0),
src1: map(src1),
high: high.map(|(left, right)| (map(left), map(right))),
exec,
},
Op::RuntimeBranch { mask, target } => Op::RuntimeBranch {
mask: map(mask),
target,
},
Op::JoinVccz {
mask,
fallthrough,
taken,
} => Op::JoinVccz {
mask: map(mask),
fallthrough: map(fallthrough),
taken: map(taken),
},
Op::Reuse(source) => Op::Reuse(map(source)),
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum PureExpr {
Unary(VectorUnary, usize),
Binary(Binary, usize, usize),
}
fn pure_expr(operation: Op) -> Option<PureExpr> {
match operation {
Op::Unary(operator, source) => Some(PureExpr::Unary(operator, source.0)),
Op::Binary(operator, left, right) => Some(PureExpr::Binary(operator, left.0, right.0)),
_ => None,
}
}
/// Replace pure constant expressions with `Op::Constant` in place.
///
/// Operands stay addressable by their original `Value` indices so later uses
/// need no rewrite. Side-effecting and mask-dependent ops are left unchanged.
fn fold_constant_ops(operations: &mut [(usize, Op)]) {
for index in 0..operations.len() {
let folded = match operations[index].1 {
Op::Unary(operator, source) => {
const_value(operations, source).and_then(|bits| eval_unary(operator, bits))
}
Op::Binary(operator, left, right) => {
match (
const_value(operations, left),
const_value(operations, right),
) {
(Some(left), Some(right)) => eval_binary(operator, left, right),
_ => None,
}
}
_ => None,
};
if let Some(bits) = folded {
operations[index].1 = Op::Constant(bits);
}
}
}
fn const_value(operations: &[(usize, Op)], value: Value) -> Option<u32> {
match operations.get(value.0).map(|(_, operation)| *operation)? {
Op::Constant(bits) => Some(bits),
_ => None,
}
}
fn concrete_bits(facts: KnownBits) -> Option<u32> {
if let Some([first, second]) = facts.values {
return (first == second).then_some(first);
}
if facts.zero | facts.one == u32::MAX {
Some(facts.one)
} else {
None
}
}
fn eval_unary(operator: VectorUnary, source: u32) -> Option<u32> {
Some(match operator {
VectorUnary::Not => !source,
VectorUnary::ReverseBits => source.reverse_bits(),
VectorUnary::FindHighUnsigned => {
if source == 0 {
0xffff_ffff
} else {
source.leading_zeros()
}
}
VectorUnary::FindLow => {
if source == 0 {
0xffff_ffff
} else {
source.trailing_zeros()
}
}
VectorUnary::FindHighSigned => {
if source == 0 || source == 0xffff_ffff {
0xffff_ffff
} else {
(source ^ (0u32.wrapping_sub(source >> 31))).leading_zeros()
}
}
})
}
fn eval_binary(operator: Binary, left: u32, right: u32) -> Option<u32> {
match operator {
Binary::FloatAdd | Binary::FloatMul => concrete_bits(exact_float_result(
operator,
KnownBits::constant(left),
KnownBits::constant(right),
)?),
Binary::Vector(operation) => Some(eval_vector_binary(operation, left, right)),
}
}
fn eval_vector_binary(operation: VectorBinary, left: u32, right: u32) -> u32 {
let i24 = |value: u32| ((value as i32) << 8) >> 8;
let u24 = |value: u32| value & 0x00ff_ffff;
match operation {
VectorBinary::Add => left.wrapping_add(right),
VectorBinary::Sub => left.wrapping_sub(right),
VectorBinary::Xnor => !(left ^ right),
VectorBinary::MinSigned => (left as i32).min(right as i32) as u32,
VectorBinary::MinUnsigned => left.min(right),
VectorBinary::MaxSigned => (left as i32).max(right as i32) as u32,
VectorBinary::MaxUnsigned => left.max(right),
VectorBinary::Mul24Signed => (i24(left) as u32).wrapping_mul(i24(right) as u32),
VectorBinary::Mul24Unsigned => u24(left).wrapping_mul(u24(right)),
VectorBinary::MulHi24Signed => {
((i64::from(i24(left)) * i64::from(i24(right))) >> 32) as u32
}
VectorBinary::MulHi24Unsigned => {
((u64::from(u24(left)) * u64::from(u24(right))) >> 32) as u32
}
VectorBinary::And => left & right,
VectorBinary::Or => left | right,
VectorBinary::Xor => left ^ right,
VectorBinary::ShiftLeft => left << (right & 31),
VectorBinary::ShiftRight => left >> (right & 31),
VectorBinary::ArithmeticShiftRight => ((left as i32) >> (right & 31)) as u32,
}
}
/// A wave-uniform constant operand at `offset`.
fn constant(
operations: &mut Vec<(usize, Op)>,
@@ -1510,7 +1817,58 @@ fn merge_lanes(
#[cfg(test)]
mod tests {
use super::{Binary, KnownBits, exact_float_result};
use super::{
Binary, KnownBits, Op, Value, VectorBinary, VectorUnary, eval_unary, eval_vector_binary,
exact_float_result, vector_expression,
};
/// Every foldable vector op must keep a matching MSL template and eval arm
/// so the fold table cannot drift from emission. Match arms in
/// `vector_expression` / `eval_vector_binary` / unary `expression` are
/// exhaustive; this test calls both sides for each variant.
#[test]
fn every_foldable_vector_op_has_matching_msl_template() {
for operation in [
VectorBinary::Add,
VectorBinary::Sub,
VectorBinary::Xnor,
VectorBinary::MinSigned,
VectorBinary::MinUnsigned,
VectorBinary::MaxSigned,
VectorBinary::MaxUnsigned,
VectorBinary::Mul24Signed,
VectorBinary::Mul24Unsigned,
VectorBinary::MulHi24Signed,
VectorBinary::MulHi24Unsigned,
VectorBinary::And,
VectorBinary::Or,
VectorBinary::Xor,
VectorBinary::ShiftLeft,
VectorBinary::ShiftRight,
VectorBinary::ArithmeticShiftRight,
] {
let expression = vector_expression(operation, "left", "right");
assert!(
!expression.is_empty(),
"missing MSL template for {operation:?}"
);
let _ = eval_vector_binary(operation, 0x11, 0x22);
}
for operation in [
VectorUnary::Not,
VectorUnary::ReverseBits,
VectorUnary::FindHighUnsigned,
VectorUnary::FindLow,
VectorUnary::FindHighSigned,
] {
let expression = Op::Unary(operation, Value(0)).expression(&|v| v.to_string(), "", "");
assert!(
!expression.is_empty(),
"missing MSL template for {operation:?}"
);
assert!(eval_unary(operation, 0x8000_0001).is_some());
}
}
#[test]
fn propagates_known_bits_through_integer_operators() {
+973 -1
View File
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use xenora_shader::{Architecture, CompileError, compile};
use xenora_shader::{Architecture, CompileError, CompileOptions, compile, compile_with};
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin");
@@ -551,3 +551,975 @@ fn vop1_integer_fixture_lowers_unary_and_masked_swap() {
include_str!("../../../fixtures/golden/vector-unary.metal")
);
}
// --- Opt-in constant folding: hand-computed known-answer fixtures -------------
// Instruction words are built by hand to match the existing RDNA2 fixture shape
// (load, wait, mov literals, op, store). Expected constants are derived from the
// RDNA2 guide / MSL templates in lib.rs, then checked against fold-on IR. Fold-off
// (and default compile) must leave the op mnemonic in the IR.
fn words(words: &[u32]) -> Vec<u8> {
words.iter().flat_map(|word| word.to_le_bytes()).collect()
}
fn mov_lit(dst: u32) -> u32 {
0x7e00_0000 | (dst << 17) | (1 << 9) | 255
}
fn vop2(op: u32, dst: u32, src0_vgpr: u32, src1_vgpr: u32) -> u32 {
(op << 25) | (dst << 17) | (src1_vgpr << 9) | (0x100 + src0_vgpr)
}
fn vop1(op: u32, dst: u32, src_vgpr: u32) -> u32 {
0x7e00_0000 | (dst << 17) | (op << 9) | (0x100 + src_vgpr)
}
/// load v1; mov v2,A; mov v3,B; VOP2 dst=v2 (or v4); store the result VGPR.
fn binary_const_fixture(op: u32, left: u32, right: u32, dst_is_v4: bool) -> Vec<u8> {
let (dst, store_hi) = if dst_is_v4 {
(4u32, 0x8001_0400u32)
} else {
(2, 0x8001_0200)
};
// For shift-rev forms the ISA encodes count in SRC0 and value in SRC1; the
// caller passes (count, value) already swapped into (src0, src1) via left/right
// naming below when needed. Non-rev forms use SRC0=v2, SRC1=v3.
let op_word = if dst_is_v4 {
// Shift-rev: v_l*rev dst, v3(count), v2(value) → SRC0=v3, SRC1=v2.
vop2(op, dst, 3, 2)
} else {
vop2(op, dst, 2, 3)
};
words(&[
0xe030_2000,
0x8000_0100, // buffer_load_dword v1
0xbf8c_3f70, // s_waitcnt vmcnt(0)
mov_lit(2),
left, // v_mov_b32 v2, left
mov_lit(3),
right, // v_mov_b32 v3, right
op_word,
0xe070_2000,
store_hi, // buffer_store_dword result
0xbbfd_0000, // s_waitcnt_vscnt
0xbf81_0000, // s_endpgm
])
}
fn unary_const_fixture(op: u32, source: u32) -> Vec<u8> {
words(&[
0xe030_2000,
0x8000_0100,
0xbf8c_3f70,
mov_lit(2),
source, // v_mov_b32 v2, source
vop1(op, 3, 2), // v_* v3, v2
0xe070_2000,
0x8001_0300, // buffer_store_dword v3
0xbbfd_0000,
0xbf81_0000,
])
}
/// load; mov v2,A; mov v3,B; and v2,v2,v3; xor v1,v1,v2; store.
/// Hand-computed: 0x12345678 & 0xff00ff00 == 0x12005600.
fn constant_and_fixture() -> Vec<u8> {
const A: u32 = 0x1234_5678;
const B: u32 = 0xff00_ff00;
words(&[
0xe030_2000,
0x8000_0100,
0xbf8c_3f70,
mov_lit(2),
A,
mov_lit(3),
B,
0x3604_0702, // v_and_b32 v2, v2, v3 (OP=27)
0x3a02_0501, // v_xor_b32 v1, v1, v2
0xe070_2000,
0x8001_0100,
0xbbfd_0000,
0xbf81_0000,
])
}
fn compile_fold_off(code: &[u8]) -> xenora_shader::CompiledShader {
compile_with(
Architecture::Gfx1030,
code,
CompileOptions {
fold_constants: false,
..CompileOptions::default()
},
)
.unwrap()
}
fn compile_fold_on(code: &[u8]) -> xenora_shader::CompiledShader {
compile_with(
Architecture::Gfx1030,
code,
CompileOptions {
fold_constants: true,
..CompileOptions::default()
},
)
.unwrap()
}
fn assert_folds_to(code: &[u8], mnemonic: &str, expected: u32) {
let plain = compile_fold_off(code);
let folded = compile_fold_on(code);
let default = compile(Architecture::Gfx1030, code).unwrap();
assert_eq!(
default.ir, plain.ir,
"default compile must match fold_constants: false"
);
assert!(
plain.ir.contains(mnemonic),
"fold-off IR must keep {mnemonic}: {}",
plain.ir
);
assert!(
!folded.ir.contains(mnemonic),
"fold-on IR must drop {mnemonic}: {}",
folded.ir
);
let const_ir = format!("const.u32 0x{expected:08x}");
assert!(
folded.ir.contains(&const_ir),
"fold-on IR must contain {const_ir}: {}",
folded.ir
);
let const_msl = format!("0x{expected:08x}u");
assert!(
folded.msl.contains(&const_msl),
"fold-on MSL must contain {const_msl}: {}",
folded.msl
);
}
#[test]
fn default_compile_matches_fold_constants_off() {
let code = constant_and_fixture();
let baseline = compile(Architecture::Gfx1030, &code).unwrap();
let explicit = compile_fold_off(&code);
assert_eq!(baseline.ir, explicit.ir);
assert_eq!(baseline.msl, explicit.msl);
assert!(baseline.ir.contains("and.b32"));
}
#[test]
fn folds_constant_and_b32_to_known_answer() {
// 0x12345678 & 0xff00ff00 = 0x12005600 (bitwise and of each bit).
assert_folds_to(&constant_and_fixture(), "and.b32", 0x1200_5600);
}
#[test]
fn folding_is_noop_on_add_fixture() {
let folded = compile_fold_on(FIXTURE);
let plain = compile(Architecture::Gfx1030, FIXTURE).unwrap();
// add.bin has no pure constant-constant vector op, so folding is a no-op.
assert_eq!(folded.ir, plain.ir);
assert_eq!(folded.msl, plain.msl);
assert_eq!(plain.ir, include_str!("../../../fixtures/golden/add.ir"));
}
#[test]
fn folds_lshl_by_32_as_shift_by_0() {
// Guide / MSL: count masked with S0[4:0] → 32 & 31 == 0, so 0xf0 << 0 == 0xf0.
// v_lshlrev_b32 OP=26; fixture stores into v4 (rev encoding).
let code = binary_const_fixture(26, 0x0000_00f0, 32, true);
assert_folds_to(&code, "lshl.b32", 0x0000_00f0);
}
#[test]
fn folds_lshl_by_33_as_shift_by_1() {
// 33 & 31 == 1, so 0xf0 << 1 == 0x1e0.
let code = binary_const_fixture(26, 0x0000_00f0, 33, true);
assert_folds_to(&code, "lshl.b32", 0x0000_01e0);
}
#[test]
fn folds_lshr_by_32_as_shift_by_0() {
// 32 & 31 == 0, so 0xf0 >> 0 == 0xf0. v_lshrrev_b32 OP=22.
let code = binary_const_fixture(22, 0x0000_00f0, 32, true);
assert_folds_to(&code, "lshr.b32", 0x0000_00f0);
}
#[test]
fn folds_lshr_by_33_as_shift_by_1() {
// 33 & 31 == 1, so 0xf0 >> 1 == 0x78.
let code = binary_const_fixture(22, 0x0000_00f0, 33, true);
assert_folds_to(&code, "lshr.b32", 0x0000_0078);
}
#[test]
fn folds_ashr_of_negative_value() {
// (-16 as i32) >> 4 == -1 → 0xffffffff. v_ashrrev_i32 OP=24.
let code = binary_const_fixture(24, 0xffff_fff0, 4, true);
assert_folds_to(&code, "ashr.i32", 0xffff_ffff);
}
#[test]
fn folds_min_i32_and_min_u32_differ_on_sign_bit() {
// min_i32(0x80000000, 1) = min(-2^31, 1) = 0x80000000.
// min_u32(0x80000000, 1) = min(2^31, 1) = 1.
// They must differ. OP MinI32=17, MinU32=19.
assert_folds_to(
&binary_const_fixture(17, 0x8000_0000, 1, false),
"min.i32",
0x8000_0000,
);
assert_folds_to(
&binary_const_fixture(19, 0x8000_0000, 1, false),
"min.u32",
1,
);
}
#[test]
fn folds_mul_hi_i32_i24_with_negative_input() {
// i24(0x00ffffff) = ((0x00ffffff << 8) >> 8) = -1; i24(2) = 2;
// (-1 * 2) as i64 >> 32 = -1 → 0xffffffff. v_mul_hi_i32_i24 OP=10.
let code = binary_const_fixture(10, 0x00ff_ffff, 2, false);
assert_folds_to(&code, "mulhi24.i32", 0xffff_ffff);
}
#[test]
fn folds_ffbh_i32_on_zero_all_ones_and_one() {
// RDNA2 / MSL: return 0xffffffff when every bit matches the sign bit (0 or -1);
// else clz(x ^ (0 - (x >> 31))). For 1: clz(1) = 31. v_ffbh_i32 OP=59.
assert_folds_to(&unary_const_fixture(59, 0), "ffbh.i32", 0xffff_ffff);
assert_folds_to(
&unary_const_fixture(59, 0xffff_ffff),
"ffbh.i32",
0xffff_ffff,
);
assert_folds_to(&unary_const_fixture(59, 1), "ffbh.i32", 31);
}
#[test]
fn folds_exact_positive_normal_float_add() {
// 1.0 + 2.0 = 3.0 exactly (positive normals). Bits: 0x3f800000 + 0x40000000
// → 0x40400000. VOP2 add_f32 OP=3.
let code = binary_const_fixture(3, 0x3f80_0000, 0x4000_0000, false);
assert_folds_to(&code, "add.f32", 0x4040_0000);
}
#[test]
fn float_add_from_load_stays_unfolded_with_fold_on() {
// float-exact.bin feeds add.f32 from a load-derived value (not a pure
// constant), so the op must remain even with fold_constants. Constant
// denormal / NaN / negative / inexact float pairs are rejected at verify
// (see rejects_inexact_float_add_of_constants_at_verify) and never reach
// the folder as stay-unfolded ops.
let plain = compile_fold_off(FLOAT);
let folded = compile_fold_on(FLOAT);
assert!(
plain.ir.contains("add.f32"),
"fold-off must keep add.f32: {}",
plain.ir
);
assert!(
folded.ir.contains("add.f32"),
"fold-on must not rewrite load-derived add.f32: {}",
folded.ir
);
assert!(
folded.ir.contains("mul.f32"),
"fold-on must not rewrite load-derived mul.f32: {}",
folded.ir
);
}
#[test]
fn rejects_inexact_float_add_of_constants_at_verify() {
// Both operands are positive normals, but 1.0 + 2^-24 is not representable
// in f32 (ulp of 1.0 is 2^-23), so exact_float_result refuses. Lift/verify
// rejects before fold_constant_ops runs; the op cannot "stay unfolded".
// Probed: fold_off and fold_on both return Verify at the add_f32 word.
let code = binary_const_fixture(3, 0x3f80_0000, 0x3380_0000, false);
let off = compile_with(
Architecture::Gfx1030,
&code,
CompileOptions {
fold_constants: false,
..CompileOptions::default()
},
);
let on = compile_with(
Architecture::Gfx1030,
&code,
CompileOptions {
fold_constants: true,
..CompileOptions::default()
},
);
assert!(
matches!(off, Err(CompileError::Verify { .. })),
"fold-off must reject inexact constant add.f32 at verify: {off:?}"
);
assert!(
matches!(on, Err(CompileError::Verify { .. })),
"fold-on must reject inexact constant add.f32 at verify: {on:?}"
);
// Folder unchanged: no stay-unfolded path exists for this pair.
}
// --- Opt-in common-subexpression elimination (#142) ---------------------------
// Expected IR is derived from the lifter's value order and the reuse rule
// (same unary/binary op, same operand values in order), not from the pass
// output. Constant bits cited below are computed by hand.
fn compile_options(code: &[u8], fold: bool, cse: bool) -> xenora_shader::CompiledShader {
compile_with(
Architecture::Gfx1030,
code,
CompileOptions {
fold_constants: fold,
eliminate_common_subexpressions: cse,
},
)
.unwrap()
}
fn vopc(op: u32, src0_vgpr: u32, src1_vgpr: u32) -> u32 {
// VOPC: encoding bits 0x7c00_0000, OP in bits 17-24, VSRC1 in bits 9-16,
// SRC0 in bits 0-8 (VGPR selector 256 + register).
0x7c00_0000 | (op << 17) | (src1_vgpr << 9) | (0x100 + src0_vgpr)
}
/// load; mov v2, 0xff00ff00; and v3 and v4 with v1, v2; xor each and with v2.
/// The two ands are the same pure op. The two xors become the same pure op
/// only after the second and is reused, so the second xor must reuse the first.
fn duplicate_and_xor_fixture() -> Vec<u8> {
words(&[
0xe030_2000,
0x8000_0100,
0xbf8c_3f70,
mov_lit(2),
0xff00_ff00,
vop2(27, 3, 1, 2), // v_and_b32 v3, v1, v2
vop2(27, 4, 1, 2), // v_and_b32 v4, v1, v2
vop2(29, 5, 3, 2), // v_xor_b32 v5, v3, v2
vop2(29, 6, 4, 2), // v_xor_b32 v6, v4, v2
0xe070_2000,
0x8001_0600, // buffer_store_dword v6
0xbbfd_0000,
0xbf81_0000,
])
}
const DUPLICATE_AND_OFF: &str = "\
0000: t0 = load.u32 input[index]
000c: t1 = const.u32 0xff00ff00
0014: t2 = and.b32 t0, t1
0018: t3 = and.b32 t0, t1
001c: t4 = xor.b32 t2, t1
0020: t5 = xor.b32 t3, t1
0024: store.u32 output[index], t5
";
const DUPLICATE_AND_ON: &str = "\
0000: t0 = load.u32 input[index]
000c: t1 = const.u32 0xff00ff00
0014: t2 = and.b32 t0, t1
0018: t3 = reuse.u32 t2
001c: t4 = xor.b32 t2, t1
0020: t5 = reuse.u32 t4
0024: store.u32 output[index], t4
";
const DUPLICATE_AND_MSL_OFF: &str = "\
#include <metal_stdlib>
using namespace metal;
kernel void xenora_compute(
device const uint* input [[buffer(0)]],
device uint* output [[buffer(1)]],
uint index [[thread_position_in_grid]]) {
uint t0 = input[index];
uint t1 = 0xff00ff00u;
uint t2 = t0 & t1;
uint t3 = t0 & t1;
uint t4 = t2 ^ t1;
uint t5 = t3 ^ t1;
output[index] = t5;
}
";
const DUPLICATE_AND_MSL_ON: &str = "\
#include <metal_stdlib>
using namespace metal;
kernel void xenora_compute(
device const uint* input [[buffer(0)]],
device uint* output [[buffer(1)]],
uint index [[thread_position_in_grid]]) {
uint t0 = input[index];
uint t1 = 0xff00ff00u;
uint t2 = t0 & t1;
uint t3 = t2;
uint t4 = t2 ^ t1;
uint t5 = t4;
output[index] = t4;
}
";
#[test]
fn default_compile_matches_cse_off() {
assert_eq!(
CompileOptions::default(),
CompileOptions {
fold_constants: false,
eliminate_common_subexpressions: false,
}
);
let code = duplicate_and_xor_fixture();
let baseline = compile(Architecture::Gfx1030, &code).unwrap();
let explicit = compile_options(&code, false, false);
assert_eq!(baseline.ir, explicit.ir);
assert_eq!(baseline.msl, explicit.msl);
assert_eq!(baseline.ir, DUPLICATE_AND_OFF);
assert_eq!(baseline.msl, DUPLICATE_AND_MSL_OFF);
// add.bin has no duplicate pure expression. CSE on must not touch it.
let add = compile(Architecture::Gfx1030, FIXTURE).unwrap();
let add_cse = compile_options(FIXTURE, false, true);
assert_eq!(add.ir, include_str!("../../../fixtures/golden/add.ir"));
assert_eq!(add_cse.ir, add.ir);
assert_eq!(add_cse.msl, add.msl);
}
#[test]
fn reuses_duplicate_and_and_the_xor_of_that_and() {
// Off: two and.b32 and two xor.b32. On: one of each, plus reuse.u32.
// The xor is not evaluated: xor of a value with a different operand stays
// xor.b32. (xor with itself is not what this fixture computes.)
let code = duplicate_and_xor_fixture();
let off = compile_options(&code, false, false);
let on = compile_options(&code, false, true);
assert_eq!(off.ir, DUPLICATE_AND_OFF);
assert_eq!(off.msl, DUPLICATE_AND_MSL_OFF);
assert_eq!(on.ir, DUPLICATE_AND_ON);
assert_eq!(on.msl, DUPLICATE_AND_MSL_ON);
assert_eq!(off.ir.matches("and.b32").count(), 2);
assert_eq!(on.ir.matches("and.b32").count(), 1);
assert_eq!(off.ir.matches("xor.b32").count(), 2);
assert_eq!(on.ir.matches("xor.b32").count(), 1);
assert_eq!(on.ir.matches("store.u32").count(), 1);
}
#[test]
fn reuses_duplicate_not() {
// v_not_b32 twice on the loaded word. ~x computed once.
let code = words(&[
0xe030_2000,
0x8000_0100,
0xbf8c_3f70,
vop1(55, 2, 1), // v_not_b32 v2, v1 (VOP1 opcode 55)
vop1(55, 3, 1), // v_not_b32 v3, v1
0xe070_2000,
0x8001_0300,
0xbbfd_0000,
0xbf81_0000,
]);
let off = "\
0000: t0 = load.u32 input[index]
000c: t1 = not.b32 t0
0010: t2 = not.b32 t0
0014: store.u32 output[index], t2
";
let on = "\
0000: t0 = load.u32 input[index]
000c: t1 = not.b32 t0
0010: t2 = reuse.u32 t1
0014: store.u32 output[index], t1
";
assert_eq!(compile_options(&code, false, false).ir, off);
assert_eq!(compile_options(&code, false, true).ir, on);
let msl = compile_options(&code, false, true).msl;
assert!(msl.contains("uint t1 = ~t0;"));
assert!(msl.contains("uint t2 = t1;"));
assert_eq!(msl.matches("~t0").count(), 1);
}
#[test]
fn does_not_reuse_swapped_subtract() {
// sub is not commutative: if the load is 0, v1 - 1 = 0xffffffff and
// 1 - v1 = 1. The third sub repeats the first and is reused.
let code = words(&[
0xe030_2000,
0x8000_0100,
0xbf8c_3f70,
mov_lit(2),
1,
vop2(38, 3, 1, 2), // v_sub_nc_u32 v3, v1, v2
vop2(38, 4, 2, 1), // v_sub_nc_u32 v4, v2, v1
vop2(38, 5, 1, 2), // v_sub_nc_u32 v5, v1, v2
0xe070_2000,
0x8001_0500,
0xbbfd_0000,
0xbf81_0000,
]);
let off = "\
0000: t0 = load.u32 input[index]
000c: t1 = const.u32 0x00000001
0014: t2 = sub.u32 t0, t1
0018: t3 = sub.u32 t1, t0
001c: t4 = sub.u32 t0, t1
0020: store.u32 output[index], t4
";
let on = "\
0000: t0 = load.u32 input[index]
000c: t1 = const.u32 0x00000001
0014: t2 = sub.u32 t0, t1
0018: t3 = sub.u32 t1, t0
001c: t4 = reuse.u32 t2
0020: store.u32 output[index], t2
";
assert_eq!(compile_options(&code, false, false).ir, off);
assert_eq!(compile_options(&code, false, true).ir, on);
assert_eq!(
compile_options(&code, false, true)
.ir
.matches("sub.u32")
.count(),
2
);
}
#[test]
fn does_not_reuse_a_different_opcode() {
// and vs or of the same bits differ. 0xff00ff00 & 0x0f0f0f0f = 0x0f000f00;
// 0xff00ff00 | 0x0f0f0f0f = 0xff0fff0f.
let code = words(&[
0xe030_2000,
0x8000_0100,
0xbf8c_3f70,
mov_lit(2),
0xff00_ff00,
vop2(27, 3, 1, 2), // v_and_b32
vop2(28, 4, 1, 2), // v_or_b32
0xe070_2000,
0x8001_0300,
0xbbfd_0000,
0xbf81_0000,
]);
let ir = "\
0000: t0 = load.u32 input[index]
000c: t1 = const.u32 0xff00ff00
0014: t2 = and.b32 t0, t1
0018: t3 = or.b32 t0, t1
001c: store.u32 output[index], t2
";
let off = compile_options(&code, false, false);
let on = compile_options(&code, false, true);
assert_eq!(off.ir, ir);
assert_eq!(on.ir, ir);
assert!(!on.ir.contains("reuse.u32"));
}
#[test]
fn does_not_merge_loads_or_duplicate_constant_definitions() {
// Two loads of input[index] stay two loads. Two movs of the same immediate
// stay two const.u32 definitions. The ands use different constant temps
// with equal bits, so the pure and is reused and the consts remain.
let code = words(&[
0xe030_2000,
0x8000_0100, // buffer_load_dword v1
0xbf8c_3f70,
0xe030_2000,
0x8000_0200, // buffer_load_dword v2
0xbf8c_3f70,
mov_lit(3),
0x1234_5678,
mov_lit(4),
0x1234_5678,
vop2(27, 5, 1, 3), // v_and_b32 v5, v1, v3
vop2(27, 6, 1, 4), // v_and_b32 v6, v1, v4
0xe070_2000,
0x8001_0600,
0xbbfd_0000,
0xbf81_0000,
]);
let off = "\
0000: t0 = load.u32 input[index]
000c: t1 = load.u32 input[index]
0018: t2 = const.u32 0x12345678
0020: t3 = const.u32 0x12345678
0028: t4 = and.b32 t0, t2
002c: t5 = and.b32 t0, t3
0030: store.u32 output[index], t5
";
// Constant temps compare by bits, so the second and reuses the first.
// The load temps differ, and neither load is removed.
let on = "\
0000: t0 = load.u32 input[index]
000c: t1 = load.u32 input[index]
0018: t2 = const.u32 0x12345678
0020: t3 = const.u32 0x12345678
0028: t4 = and.b32 t0, t2
002c: t5 = reuse.u32 t4
0030: store.u32 output[index], t4
";
assert_eq!(compile_options(&code, false, false).ir, off);
assert_eq!(compile_options(&code, false, true).ir, on);
assert_eq!(
compile_options(&code, false, true)
.ir
.matches("load.u32")
.count(),
2
);
assert_eq!(
compile_options(&code, false, true)
.ir
.matches("const.u32 0x12345678")
.count(),
2
);
}
#[test]
fn does_not_merge_lane_masks() {
// Two identical v_cmp_eq_u32_e32 (VOPC opcode 194) write the wave mask.
// The results are lane-mask values and are not reused.
let code = words(&[
mov_lit(1),
1,
mov_lit(2),
2,
vopc(194, 1, 2),
vopc(194, 1, 2),
mov_lit(3),
0,
0xe070_2000,
0x8001_0300,
0xbbfd_0000,
0xbf81_0000,
]);
let ir = "\
0000: t0 = const.u32 0x00000001
0008: t1 = const.u32 0x00000002
0010: t2 = wave.mask v_cmp_eq_u32_e32 t0, t1 exec=0xffffffff
0014: t3 = wave.mask v_cmp_eq_u32_e32 t0, t1 exec=0xffffffff
0018: t4 = const.u32 0x00000000
0020: store.u32 output[index], t4
";
let off = compile_options(&code, false, false);
let on = compile_options(&code, false, true);
assert_eq!(off.ir, ir);
assert_eq!(on.ir, ir);
assert_eq!(on.ir.matches("wave.mask").count(), 2);
assert!(!on.ir.contains("reuse.u32"));
}
#[test]
fn does_not_merge_lane_merges_under_partial_exec() {
// EXEC = 1 merges each and with that destination's previous value.
// The and itself is pure and is reused. The two merges see different
// inactive values (the two zero temps) and both remain.
let code = words(&[
0xe030_2000,
0x8000_0100,
0xbf8c_3f70,
mov_lit(2),
0xff00_ff00,
mov_lit(3),
0, // v3 initialized before the partial write
mov_lit(4),
0, // v4 initialized before the partial write
0xbefe_0381, // s_mov_b32 exec_lo, 1
vop2(27, 3, 1, 2), // v_and_b32 v3, v1, v2
vop2(27, 4, 1, 2), // v_and_b32 v4, v1, v2
0xbefe_03c1, // s_mov_b32 exec_lo, -1
0xe070_2000,
0x8001_0300, // buffer_store_dword v3
0xbbfd_0000,
0xbf81_0000,
]);
let off = "\
0000: t0 = load.u32 input[index]
000c: t1 = const.u32 0xff00ff00
0014: t2 = const.u32 0x00000000
001c: t3 = const.u32 0x00000000
0028: t4 = and.b32 t0, t1
0028: t5 = merge.lanes mask=0x00000001, t4, t2
002c: t6 = and.b32 t0, t1
002c: t7 = merge.lanes mask=0x00000001, t6, t3
0034: store.u32 output[index], t5
";
let on = "\
0000: t0 = load.u32 input[index]
000c: t1 = const.u32 0xff00ff00
0014: t2 = const.u32 0x00000000
001c: t3 = const.u32 0x00000000
0028: t4 = and.b32 t0, t1
0028: t5 = merge.lanes mask=0x00000001, t4, t2
002c: t6 = reuse.u32 t4
002c: t7 = merge.lanes mask=0x00000001, t4, t3
0034: store.u32 output[index], t5
";
assert_eq!(compile_options(&code, false, false).ir, off);
assert_eq!(compile_options(&code, false, true).ir, on);
assert_eq!(
compile_options(&code, false, true)
.ir
.matches("merge.lanes")
.count(),
2
);
}
#[test]
fn does_not_merge_vcc_select() {
// v_cndmask_b32 reads VCC. Two identical selects stay two vcc.Select ops.
let code = words(&[
0xe030_2000,
0x8000_0100,
0xbf8c_3f70,
mov_lit(2),
0x1111_1111,
0xbeea_0381, // s_mov_b32 vcc_lo, 1
vop2(1, 3, 1, 2), // v_cndmask_b32 v3, v1, v2
vop2(1, 4, 1, 2), // v_cndmask_b32 v4, v1, v2
0xe070_2000,
0x8001_0300,
0xbbfd_0000,
0xbf81_0000,
]);
let ir = "\
0000: t0 = load.u32 input[index]
000c: t1 = const.u32 0x11111111
0018: t2 = const.u32 0x00000001
0018: t3 = vcc.Select t0, t1, t2
001c: t4 = const.u32 0x00000001
001c: t5 = vcc.Select t0, t1, t4
0020: store.u32 output[index], t3
";
let off = compile_options(&code, false, false);
let on = compile_options(&code, false, true);
assert_eq!(off.ir, ir);
assert_eq!(on.ir, ir);
assert_eq!(on.ir.matches("vcc.Select").count(), 2);
assert!(!on.ir.contains("reuse.u32"));
}
#[test]
fn cse_leaves_branch_and_float_fixtures_unchanged() {
// No duplicate pure expression, so the pass is a no-op, including on the
// uniform branches and the load-derived float ops.
for (code, ir) in [
(
BRANCH,
include_str!("../../../fixtures/golden/bitwise-branch.ir"),
),
(
FLOAT,
include_str!("../../../fixtures/golden/float-exact.ir"),
),
] {
let plain = compile(Architecture::Gfx1030, code).unwrap();
let on = compile_options(code, false, true);
assert_eq!(plain.ir, ir);
assert_eq!(on.ir, plain.ir);
assert_eq!(on.msl, plain.msl);
}
}
#[test]
fn cse_leaves_every_golden_fixture_unchanged() {
// None of these fixtures repeats a pure op. Several use equal-bit
// constants in different ops whose operands must not be renamed.
macro_rules! golden {
($name:literal) => {{
let code = include_bytes!(concat!("../../../fixtures/rdna2/", $name, ".bin"));
let shader = compile_options(code, false, true);
assert_eq!(
shader.ir,
include_str!(concat!("../../../fixtures/golden/", $name, ".ir")),
"ir changed for {}",
$name
);
assert_eq!(
shader.msl,
include_str!(concat!("../../../fixtures/golden/", $name, ".metal")),
"msl changed for {}",
$name
);
}};
}
golden!("add");
golden!("bitwise-branch");
golden!("float-exact");
golden!("scalar-alu");
golden!("scalar-arith");
golden!("scalar-compare");
golden!("scalar-immediate");
golden!("scalar-logic");
golden!("scalar-unary");
golden!("vector-compare");
golden!("vector-compare-ft");
golden!("vector-integer");
golden!("vector-unary");
}
/// 1 + 2 = 3, and the same add twice, then and the load with each sum.
fn fold_and_cse_fixture() -> Vec<u8> {
words(&[
0xe030_2000,
0x8000_0100,
0xbf8c_3f70,
mov_lit(2),
1,
mov_lit(3),
2,
vop2(37, 4, 2, 3), // v_add_nc_u32 v4, v2, v3
vop2(37, 5, 2, 3), // v_add_nc_u32 v5, v2, v3
vop2(27, 6, 1, 4), // v_and_b32 v6, v1, v4
vop2(27, 7, 1, 5), // v_and_b32 v7, v1, v5
0xe070_2000,
0x8001_0700,
0xbbfd_0000,
0xbf81_0000,
])
}
#[test]
fn cse_interacts_with_constant_folding() {
// Hand-computed: 1 + 2 = 3 (0x00000003). Folding rewrites the adds and
// does not reuse the ands. CSE reuses both the add and the and, and does
// not invent the constant 3. Both passes: the adds are constants first,
// the two const 3 temps stay, and the ands reuse because those temps have
// the same bits.
let code = fold_and_cse_fixture();
let off = "\
0000: t0 = load.u32 input[index]
000c: t1 = const.u32 0x00000001
0014: t2 = const.u32 0x00000002
001c: t3 = add.u32 t1, t2
0020: t4 = add.u32 t1, t2
0024: t5 = and.b32 t0, t3
0028: t6 = and.b32 t0, t4
002c: store.u32 output[index], t6
";
let cse_only = "\
0000: t0 = load.u32 input[index]
000c: t1 = const.u32 0x00000001
0014: t2 = const.u32 0x00000002
001c: t3 = add.u32 t1, t2
0020: t4 = reuse.u32 t3
0024: t5 = and.b32 t0, t3
0028: t6 = reuse.u32 t5
002c: store.u32 output[index], t5
";
let fold_only = "\
0000: t0 = load.u32 input[index]
000c: t1 = const.u32 0x00000001
0014: t2 = const.u32 0x00000002
001c: t3 = const.u32 0x00000003
0020: t4 = const.u32 0x00000003
0024: t5 = and.b32 t0, t3
0028: t6 = and.b32 t0, t4
002c: store.u32 output[index], t6
";
let both = "\
0000: t0 = load.u32 input[index]
000c: t1 = const.u32 0x00000001
0014: t2 = const.u32 0x00000002
001c: t3 = const.u32 0x00000003
0020: t4 = const.u32 0x00000003
0024: t5 = and.b32 t0, t3
0028: t6 = reuse.u32 t5
002c: store.u32 output[index], t5
";
assert_eq!(compile_options(&code, false, false).ir, off);
assert_eq!(compile_options(&code, false, true).ir, cse_only);
assert_eq!(compile_options(&code, true, false).ir, fold_only);
assert_eq!(compile_options(&code, true, true).ir, both);
assert!(!cse_only.contains("0x00000003"));
assert_eq!(fold_only.matches("const.u32 0x00000003").count(), 2);
assert_eq!(both.matches("and.b32").count(), 1);
assert!(!both.contains("add.u32"));
}
#[test]
fn cse_does_not_fold_exact_float_add() {
// 1.0 + 2.0 = 3.0 exactly. Bits 0x3f800000 + 0x40000000 = 0x40400000.
// CSE reuses the add and leaves the operation. Folding replaces both
// adds with that constant. Enabling both matches folding alone: the adds
// are gone before reuse, and the two result constants are not merged.
let code = words(&[
mov_lit(2),
0x3f80_0000,
mov_lit(3),
0x4000_0000,
vop2(3, 4, 2, 3), // v_add_f32 v4, v2, v3
vop2(3, 5, 2, 3), // v_add_f32 v5, v2, v3
0xe070_2000,
0x8001_0500,
0xbbfd_0000,
0xbf81_0000,
]);
let cse_ir = "\
0000: t0 = const.u32 0x3f800000
0008: t1 = const.u32 0x40000000
0010: t2 = add.f32 t0, t1
0014: t3 = reuse.u32 t2
0018: store.u32 output[index], t2
";
let fold_ir = "\
0000: t0 = const.u32 0x3f800000
0008: t1 = const.u32 0x40000000
0010: t2 = const.u32 0x40400000
0014: t3 = const.u32 0x40400000
0018: store.u32 output[index], t3
";
let cse_msl = "\
#include <metal_stdlib>
using namespace metal;
kernel void xenora_compute(
device const uint* input [[buffer(0)]],
device uint* output [[buffer(1)]],
uint index [[thread_position_in_grid]]) {
#pragma clang fp contract(off)
#pragma clang fp reassociate(off)
uint t0 = 0x3f800000u;
uint t1 = 0x40000000u;
uint t2 = as_type<uint>(as_type<float>(t0) + as_type<float>(t1));
uint t3 = t2;
output[index] = t2;
}
";
let folded = compile_options(&code, true, false);
let both = compile_options(&code, true, true);
assert_eq!(compile_options(&code, false, true).ir, cse_ir);
assert_eq!(compile_options(&code, false, true).msl, cse_msl);
assert_eq!(folded.ir, fold_ir);
assert_eq!(both.ir, folded.ir);
assert_eq!(both.msl, folded.msl);
assert!(!cse_ir.contains("0x40400000"));
assert_eq!(fold_ir.matches("const.u32 0x40400000").count(), 2);
}
#[test]
fn cse_does_not_bypass_inexact_float_verification() {
// Same pair the folder refuses: 1.0 + 2^-24 is not an f32 value. Verify
// rejects it before either optional pass.
let code = binary_const_fixture(3, 0x3f80_0000, 0x3380_0000, false);
for fold in [false, true] {
for cse in [false, true] {
let result = compile_with(
Architecture::Gfx1030,
&code,
CompileOptions {
fold_constants: fold,
eliminate_common_subexpressions: cse,
},
);
assert!(
matches!(result, Err(CompileError::Verify { .. })),
"fold={fold} cse={cse} must reject at verify: {result:?}"
);
}
}
}
+9 -2
View File
@@ -1,4 +1,4 @@
# Xenora documentation
# BetterXen documentation
## Getting started
@@ -8,6 +8,10 @@ then read the [interface contracts](interfaces.md). Reproduce an
[independent validation suite](../tests/validation/README.md) before changing
either path. The [changelog](../CHANGELOG.md) records notable changes.
Use the [BetterXen development phases](development-phases.md) for current work
order, existing issue/PR dependencies and measurable completion criteria.
Historical phase checkpoints retain their original evidence scope.
## Architecture and technical design
- [Interface contracts](interfaces.md) — Translated shader stages, guest services, native command submission, and synthetic textures.
@@ -48,6 +52,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
@@ -62,7 +67,9 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
- [Legal scope](legal.md), [dependency licensing](licenses.md), and [third-party notices](../THIRD_PARTY_NOTICES.md) — Input policy, attribution, and redistribution findings.
- [Contribution guidelines](../CONTRIBUTING.md) — Original authorship, Developer Certificate of Origin sign-off, and evidence requirements.
- [Agent task queue](coordination/agent-tasks.md) — Areas, claiming, leases, upstream sync, verification and the security model for parallel contributors and coding agents.
- [CPU/runtime expansion campaign ledger](coordination/cpu-campaign-ledger.md) — Progress ledger for the Xenora native CPU and runtime compatibility campaign: starting/current commits, completed batches, new forms, verification evidence and the next implementation target.
- [CPU/runtime expansion campaign ledger](coordination/cpu-campaign-ledger.md) — Progress ledger for the BetterXen native CPU and runtime compatibility campaign: starting/current commits, completed batches, new forms, verification evidence and the next implementation target.
- [Infrastructure QA ownership](coordination/infrastructure-qa-ownership.md) — Non-overlapping paths for infrastructure and QA tooling.
- [Agent queue smoke evidence](coordination/agent-queue-smoke.md) — Live Actions results from the disposable smoke repository.
- [Infrastructure QA tooling](testing/infrastructure/README.md) — Advisory orchestration, PR validation, benchmark analysis and release checks.
- [Migration to BetterXen](migration.md): source attribution, imported history and compatibility names.
+1 -1
View File
@@ -1,5 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" width="530" height="185" viewBox="0 0 530 185" role="img" aria-labelledby="title description">
<title id="title">Xenora · recorded progress</title>
<title id="title">BetterXen · recorded progress</title>
<desc id="description">Decoded gfx1030 forms: 185 of 185. Accepted Metal forms · Apple M5: 18 of 185. Accepted guest milestones · X1–X4: 4 of 4</desc>
<rect x="1" y="1" width="528" height="183" rx="10" fill="#18212a" stroke="#516171"/>
<g font-family="system-ui,sans-serif" fill="#eaf0f5">

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

+2 -2
View File
@@ -95,7 +95,7 @@ CPUID (`0F A2`) returns a fixed table that never reads the host. It describes a
A feature bit is set only when every instruction of that feature is implemented. That is stricter than "some of it works", and it has consequences:
- SSE and SSE2 are not reported, although most of their instructions exist, because parts are still rejected: RSQRTPS and MASKMOVDQU, for example. BMI1 is not reported although TZCNT exists, because ANDN does not. The x87 FPU, MMX, FXSAVE, CMPXCHG8B, the time-stamp counter, LAHF and SYSRET are absent too.
- The table is therefore truthful about Xenora, not plausible as hardware: every real 64-bit processor reports the FPU and SSE2. A guest that tests a bit before using a feature avoids it; a guest that assumes SSE2 because it runs in 64-bit mode still gets every form that exists and an illegal-instruction exit for one that does not.
- The table is therefore truthful about BetterXen, not plausible as hardware: every real 64-bit processor reports the FPU and SSE2. A guest that tests a bit before using a feature avoids it; a guest that assumes SSE2 because it runs in 64-bit mode still gets every form that exists and an illegal-instruction exit for one that does not.
- A leaf that is not listed returns zeros, whatever the subleaf. Intel processors answer a leaf above the highest basic one with that leaf's data instead; software is expected to read the highest leaf first.
`xenora_loader::cpu::cpuid` is the one copy of the table. A runtime service that reports processor features should read it rather than keep its own list.
@@ -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.
+238
View File
@@ -0,0 +1,238 @@
# BetterXen development phases
This is BetterXen's working development plan. Each phase ends with a reproducible
application or engineering result. The plan is based on the current repository,
not on completing an inherited prompt or reaching a compatibility percentage.
No phase authorizes a release, publication, or commercial-game compatibility claim.
## Starting point
The source review used `19a905c30ea85166c05084da4fba67e356920912` on destination
`main`, with the local documentation work starting after the separate CODEOWNERS
commit `f02eb2678e76e91876be5706ce91dca25dcc3017`. The latter changes governance,
not runtime behavior. Open issues and PRs were inspected on November 24, 2026
(America/Chicago). Recheck their current heads and claims before taking work.
This task performed source inspection and read-only inventories. It did not
rerun the Rust, native GPU, application, fuzz, mutation, or performance suites.
Historical results below remain evidence for their recorded candidates only.
| Area | Present in the inspected source | Boundary for this plan |
| --- | --- | --- |
| Guest CPU | Generated x86-64 decoder, interpreter, ARM64 dynamic binary translator (DBT), integer and vector tests; inventory reports 491 declared forms and 206 operations | Declarations and lowering classifications do not establish independent acceptance or broad application compatibility. |
| Runtime | PE loading, import resolution, service handlers, process-exit tests and the compiled-C A1 fixture | The typed registry inventories only 20 services: 7 marked implemented and 13 partial. Many handwritten handlers are outside that inventory; 20 is not the total runtime service count. |
| Threads | Deterministic scheduler, guest thread contexts and guarded stacks, thread services and compiled-C thread tests | Guest threads execute serially on one host thread. Blocking synchronization, sleep behavior and thread lifecycle callbacks still have documented gaps. |
| Graphics | gfx1030 shader decoder/compiler/reference, native Metal execution paths, texture and draw tests | Synthetic desktop instruction fixtures do not establish Xbox behavior. Acceptance is tracked separately from local readback. |
| Native app | Swift app, Rust C interface, controller input and audio/virtual-filesystem fixtures | Existing fixtures do not establish one integrated threaded C++ 3D application. |
| Quality tools | CPU/runtime inventories, shader coverage reconciliation, task queue, PR checks and acceptance records | Some inventories and ledgers contain stale limitation text. A successful tool invocation does not prove every catalog entry is current. |
Sources: [CPU registry](cpu/instruction-registry.md),
[runtime registry](runtime/registry.md), [guest threads](runtime/threads.md),
[interfaces](interfaces.md), [shader coverage](shaders/semantic-coverage.md),
[Gate A](testing/gate-a.md), and [QA tooling](testing/infrastructure/README.md).
The read-only shader reconciliation reported zero mismatches during this task;
that result is inventory consistency, not new GPU verification.
## How previous phase names fit
Keep historical evidence and attribution intact. These records remain useful,
but their phase numbers are not the sequence for new BetterXen work.
| Existing record or name | Meaning | How to use it now |
| --- | --- | --- |
| [Phase 01 checkpoints and assurance](testing/phase01-assurance.md), [risk register](risk-register.md), [review log](testing/review-log.md) and [mutation record](testing/mutation.md) | Earlier bounded shader research and candidate-specific gates | Consult the original gate definitions and unresolved findings; do not relabel them as current acceptance. |
| [Phase 02 GPU/guest baseline](testing/phase-02-baseline.md) and [CPU feasibility](research/phase02-cpu-feasibility.md), [ecosystem](research/phase02-ecosystem.md), [collaboration](research/phase02-collaboration.md) research | Early graphics expansion and CPU feasibility work | Reuse documented public sources and evidence limits, checking them against current source. |
| [CPU/runtime campaign ledger](coordination/cpu-campaign-ledger.md) | Implementation batches and local evidence | Its older limitations are not a current feature inventory: scheduler, atomic and string work has since landed. |
| [Infrastructure Phase II/III tooling](testing/infrastructure/README.md) and [compatibility ledger](testing/infrastructure/phase3-compat-ledger.md) | A separate QA campaign | Tool code now includes compatibility-gap analysis and verification profiles beyond the ledger's early checkpoint. Coordinate with existing issue #219 rather than starting another QA framework. |
| [Gate A](testing/gate-a.md) | Compiled C execution, split into A1 and hosted-C A2 | A1 has a main-branch test. A2 is under review in PR #283; the document's “not started” description predates that PR. Neither is independently accepted by this plan. |
| Native app numbered gates in `crates/ffi` and `app` | Bounded session, graphics, audio and filesystem fixtures | Inspect their tests before proposing integration. Gate numbers are separate from shader acceptance gates. |
| README X1–X25 milestones | Broad capability map | Retain as a capability reference; use the phases below for the next work order. |
| Supplied Discord III, III-B, IV, V and VI excerpts | Broad runtime, graphics, application and performance objectives | Only excerpts were supplied. Their omitted requirements and completion status are unknown; they are not execution instructions. |
Bare issue numbers in historical documents may refer to the source repository.
All issue and PR links in the work sections below refer to **MacosPorters/betterxen**.
Use [migration records](migration.md) to resolve historical references.
## Phase 1 — Establish a trustworthy working baseline
**Outcome:** contributors can tell what exists on main, what is pending review,
and which checks actually ran on the candidate they are using.
1. Reconcile the current source with the CPU campaign ledger, Gate A document,
runtime inventory scope, and QA compatibility ledger. In particular, the QA
CPU inventory's intentional-rejection catalog still lists strings and
atomics/fences despite source and tests for supported subsets. Correct the
catalog through its existing owner; do not remove explicit unsupported forms.
2. Preserve all imported attribution. Repair destination links in migrated PRs
without recreating sign-offs or treating archived reviews as current approval.
3. Reproduce the applicable existing CPU, generator and repository checks for a
pinned candidate. Run GPU and app checks separately on an eligible native host.
Record errors, unavailable tools and skipped tests separately.
4. Review conflicting PR branches with their authors. Changing descriptions
cannot resolve source conflicts or provide missing ARM64 build checks.
5. Finish BetterXen's active branding where needed. Preserve copyright notices,
licenses and accurate historical records. Package names, C symbols, guest ABI
names and environment variables require a compatibility migration, not a
blanket search-and-replace. Do not rewrite authorship to imply new ownership.
Existing work: [migration checks #286](https://github.com/MacosPorters/betterxen/issues/286),
[QA scope #219](https://github.com/MacosPorters/betterxen/issues/219),
[app CI #248](https://github.com/MacosPorters/betterxen/issues/248).
**Exit criteria:** a candidate SHA, a current capability/blocker inventory,
links to retained logs for each executed gate, explicit pending reviews, and
usable PR descriptions. Independent acceptance remains a separate decision.
No release is required.
## Phase 2 — Finish a reproducible hosted C application
**Outcome:** an original hosted C program starts, uses the runtime, reports
results and exits through the guest path with checked cleanup.
Review and integrate existing work rather than creating a competing runtime:
| Prerequisite | Existing destination work |
| --- | --- |
| CRT startup calls | [issue #237](https://github.com/MacosPorters/betterxen/issues/237), [PR #273](https://github.com/MacosPorters/betterxen/pull/273) |
| Arguments and environment | [issue #242](https://github.com/MacosPorters/betterxen/issues/242), [PR #277](https://github.com/MacosPorters/betterxen/pull/277) |
| Normal termination and exit handlers | [issue #243](https://github.com/MacosPorters/betterxen/issues/243), [PR #280](https://github.com/MacosPorters/betterxen/pull/280) |
| Formatted standard output | [issue #245](https://github.com/MacosPorters/betterxen/issues/245), [PR #281](https://github.com/MacosPorters/betterxen/pull/281) |
| File streams | [issue #246](https://github.com/MacosPorters/betterxen/issues/246), [PR #282](https://github.com/MacosPorters/betterxen/pull/282) |
| Integrated hosted-C fixture | [issue #262](https://github.com/MacosPorters/betterxen/issues/262), [PR #283](https://github.com/MacosPorters/betterxen/pull/283) |
Check dependency order and stacked branches against their actual heads. Audit
the compiler and linked CRT's per-file licensing and native ARM64 build tools.
An x86-64 guest fixture is permitted; its compiler must run natively on ARM64.
**Exit criteria:** reproducible original fixture build; checked stdout/stderr,
arguments, file contents, exit status, callback order and cleanup; unresolved
imports and exhausted budgets fail explicitly. Existing A1 behavior still passes.
Independent reviewers derive expected results from public specifications and the
fixture contract. No general C++ or Xbox startup claim follows from this result.
## Phase 3 — Make threaded application behavior coherent
**Outcome:** an original worker-based application can block and resume without
stalling unrelated guest work or leaking per-thread state.
Extend the existing scheduler under [issue #228](https://github.com/MacosPorters/betterxen/issues/228).
Prioritize a small fixture that exposes a documented gap: guest sleep currently
delays all guest threads, and critical-section/SRW/condition-variable waits are
not fully connected to scheduling. Claim one gap and its paths before editing.
Then add the thread lifecycle behavior required by that workload, including
static thread-local storage (TLS), library attach/detach and fiber-local storage
(FLS) cleanup where supported. Keep unsupported callbacks explicit until their
semantics and safety are implemented. Preserve Win64 nonvolatile register checks
and coordinate with [issue #193 / PR #268](https://github.com/MacosPorters/betterxen/pull/268).
**Exit criteria:** deterministic results at several scheduling quanta; another
worker progresses while one waits; timeouts, cancellation, abandoned objects,
thread-local errors, stack bounds and cleanup have negative controls. Repeat
runs reclaim thread resources. Serial guest scheduling remains the execution
model unless a separately reviewed memory-ordering design replaces it.
## Phase 4 — Connect resource updates to translated rendering
**Outcome:** one original guest workload updates a texture and geometry, submits
translated rendering, waits for completion and produces an independently checked
frame through the existing native Metal backend.
Start with a bounded scene and its concrete missing features. Do not make all
RDNA2 instructions, mesh shaders or ray tracing prerequisites for a first scene.
Reuse the semantic registry and distinguish declared, decoded, lowered,
reference-tested, locally GPU-tested and independently accepted forms.
Coordinate [RDNA2 expansion #205](https://github.com/MacosPorters/betterxen/issues/205),
[mip footprints #241 / PR #278](https://github.com/MacosPorters/betterxen/pull/278),
[graphics fences #224](https://github.com/MacosPorters/betterxen/issues/224),
[shared resource lifetime #148](https://github.com/MacosPorters/betterxen/issues/148),
and [texture-update workload #147](https://github.com/MacosPorters/betterxen/issues/147).
Wave divergence, cross-lane operations and additional formats get separate
fixture contracts and claims when this workload needs them.
**Exit criteria:** actual Metal execution and frame readback against an
independently derived expectation; update/submission/retirement order is checked;
invalid descriptors, stale handles and unsupported shader forms fail explicitly.
Record host capability detection, hardware, validation settings and evidence
class. Test counts and tolerances retain their existing definitions. Results
remain synthetic desktop-gfx1030 evidence, never Xbox hardware verification.
## Phase 5 — Run one integrated interactive application reliably
**Outcome:** a small, original application joins guest execution, rendering,
input, bounded audio, filesystem access and lifecycle behavior in one session.
Start from [multi-module startup #256](https://github.com/MacosPorters/betterxen/issues/256)
and the existing app/FFI fixtures. First prove a compiled workload can reach a
checked frame. Add C++ language/runtime features only when an independently
authored failing fixture demonstrates the need. Audit any linked runtime first.
Do not treat the Swift audio/input demonstrations as guest integration evidence.
Coordinate [audio #227](https://github.com/MacosPorters/betterxen/issues/227),
[session errors #250](https://github.com/MacosPorters/betterxen/issues/250),
[report schema #254](https://github.com/MacosPorters/betterxen/issues/254),
[worker diagnostics #255](https://github.com/MacosPorters/betterxen/issues/255),
and [application quick start #247](https://github.com/MacosPorters/betterxen/issues/247).
Execution-admission changes remain owned by [issue #212](https://github.com/MacosPorters/betterxen/issues/212).
**Exit criteria:** scripted input and deterministic checkpoints; start, pause,
resume, stop and restart behavior; checked audio sample data before device
playback; bounded memory and handle use; sandbox escape attempts rejected;
useful failure reports and a repeatable soak protocol. Specify soak duration,
resource limits and acceptance conditions before measuring. A fixture worker
passing does not certify arbitrary files safe or commercial titles playable.
## Phase 6 — Improve measured bottlenecks
**Outcome:** faster or lower-resource execution of workloads whose correctness
is already checked, with measurements that another contributor can reproduce.
Performance analysis can begin earlier; changes must preserve the relevant
phase's correctness. Select bottlenecks from actual measurements rather than
assuming every shared-semantics call, allocation or cache miss needs replacement.
Potential work includes CPU helper lowering, bounded translation-cache policy,
Metal startup, texture transfers and frame-loop overhead.
Reuse [startup measurements #171 / PR #266](https://github.com/MacosPorters/betterxen/pull/266),
[TLS optimization #107 / PR #284](https://github.com/MacosPorters/betterxen/pull/284),
[DBT comparison #110 / PR #272](https://github.com/MacosPorters/betterxen/pull/272),
and [conditional cache prewarming #258](https://github.com/MacosPorters/betterxen/issues/258).
**Exit criteria:** correctness gates pass on the changed candidate; baseline and
candidate use equivalent inputs, toolchains, settings and hardware; idle-machine
samples include variance and separate cold/warm startup. Report regressions as
well as gains. Run validation-off benchmarks separately from validation-on GPU
correctness. Capability differences across Apple Silicon generations remain
unknown until measured; runtime detection controls optional paths.
## Taking the next task
Begin with Phase 1's evidence reconciliation and review Phase 2's existing PRs.
The phase-plan issue does not claim their implementation files. Read every
comment on a target issue and inspect linked PRs; never take a live claim.
Issue #219's QA paths and subsystem owners remain independent of this plan.
Each implementation task needs a bounded outcome, permitted files, dependencies,
public semantic sources, a failing fixture or other meaningful acceptance check,
and the required independent reviewers. Use original code and expectations;
never copy another emulator to satisfy a phase. Do not require a fixed number
of agents: use available resources only within the repository's LOW-reasoning
and independent-review rules.
Useful existing commands for the candidate record:
```sh
PYTHONPATH=scripts python3 -m qa cpu-inventory --compact
PYTHONPATH=scripts python3 -m qa runtime-inventory --compact
PYTHONPATH=scripts python3 -m qa rdna2 reconcile --compact
python3 scripts/audit/status.py --check
scripts/audit/claims.sh
scripts/audit/dependencies.sh
```
For implementation, run the applicable checkout commands in `AGENTS.md` and the
subsystem acceptance protocol. Keep logs under ignored `artifacts/`. Use at most
four Cargo jobs across two CPU-heavy jobs, one GPU job and one fuzz or mutation
campaign at a time. New verification must name the exact candidate; skipped
tests never count as GPU evidence. Passing a phase does not authorize a release.
+45 -7
View File
@@ -66,8 +66,34 @@ 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
@@ -78,7 +104,7 @@ 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
there. This is BetterXen'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
@@ -91,9 +117,9 @@ 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
`betterxen probe --mode static` inventories ordinary and delay-loaded PE imports
without guest execution. Without `--report` it writes to `diagnostics/probe`,
where `xenora imports sync` also looks. `missing_imports.csv` lists unresolved ordinary keys
where `betterxen imports sync` also looks. `missing_imports.csv` lists unresolved ordinary keys
with their import address table relative virtual addresses. The full inventory,
`imports.csv`, marks each entry `ordinary` or `delayed` in its `import_table`
column and records whether each key is registered, its implementation
@@ -112,7 +138,7 @@ ordinal, and slot in the delay import address table, after the ordinary rows.
Binding does not resolve them: the PE format leaves that to a delay-load helper
inside the image. The totals above and `missing_imports.csv` therefore cover
ordinary imports only, and the JSON report counts delayed slots and DLLs in
`delayed_imports` and `delayed_imported_dlls_count`. `xenora imports sync`
`delayed_imports` and `delayed_imported_dlls_count`. `betterxen imports sync`
leaves delayed rows out of its backlog for the same reason.
The probe reads only descriptors that lie wholly inside the directory's
@@ -124,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
@@ -437,7 +475,7 @@ four row-major Block Compression 1 (BC1) blocks, including slots beyond the
logical edge. The reader validates the full byte length, rejects padding
coordinates and can decode each logical block to sixteen RGBA8 texels.
The decoder uses bit replication to expand 5:6:5 endpoints and rounds integer
palette interpolation down. This layout is specific to Xenora fixtures. The block encoding follows the
palette interpolation down. This layout is specific to BetterXen fixtures. The block encoding follows the
[Direct3D BC1 description](https://learn.microsoft.com/en-us/windows/win32/direct3d10/d3d10-graphics-programming-guide-resources-block-compression).
`TiledBc1::linearize` strips the tile padding from one selected subresource
+3 -3
View File
@@ -1,14 +1,14 @@
# Clean-room scope
Xenora does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation.
BetterXen does not circumvent console security or DRM, does not load encrypted or protected content, and is a research project built from public documentation.
## User-provided game files
Users obtain and supply their own files. Xenora evaluates file structure,
Users obtain and supply their own files. BetterXen evaluates file structure,
supported features, compatibility and safe execution. Game import does
not check ownership, request receipts or account verification, investigate
acquisition, or block a technically supported file solely because its
origin is unknown. Xenora does not distribute or host commercial game
origin is unknown. BetterXen does not distribute or host commercial game
files or provide acquisition services.
## Project contributions and testing
+21
View File
@@ -0,0 +1,21 @@
# Migration to BetterXen
BetterXen is an independent copy of [XenoraOSS/Xenora](https://github.com/XenoraOSS/Xenora), hosted at [MacosPorters/betterxen](https://github.com/MacosPorters/betterxen). This is a copy, not a GitHub ownership transfer. The source repository remains unchanged.
## Preserved history
Original commits and authorship are retained. All 161 original pull-request heads and 24 available merge refs were copied. The 22 open PRs keep their `archive/pull/<original-number>/head` branches. The other 163 refs are preserved as tags named `archive/pull/<original-number>/head` or `archive/pull/<original-number>/merge`; their branch aliases were removed to avoid recent-push banners for historical work. Every tag was checked against its original commit before its branch alias was removed. The metadata archive also includes patches obtained through GitHub's API.
Issues are recreated with original-source links, author attribution and archived comment text. Original timestamps and authors cannot be assigned to recreated GitHub records. Destination issue and pull-request numbers differ. Historical `#number` references in upstream records refer to the original repository; consult the source link and number maps in the migration archive.
Open PRs are recreated against copied branches. Closed and merged PRs are retained as historical archive records, including descriptions, comments, reviews, changed-file metadata, commits and patches; they are not represented as newly merged work. Recreated PRs do not inherit approvals or check results.
The migration archive was uploaded with the `migration-archive-2026-11-24` release, but that release was no longer listed by GitHub during the branch cleanup. A verified local copy remains at `artifacts/repo-migration/xenora-to-betterxen-archive.zip`; `artifacts/` is ignored by Git. Git history also remains on GitHub through the active PR branches and archive tags. It includes JSON metadata, a readable issue/PR index, patches and original-to-destination number maps. It records the public state observed during migration, not an atomic snapshot. Linked external attachments and unavailable private data are not embedded unless explicitly listed in its manifest.
Stars, watchers, source organization membership, private settings, secrets, deploy keys, inaccessible project data, and Actions run history are not copied. The source wiki could not be cloned (GitHub reported that it was not found). No source releases were present during inventory. The one public discussion is archived and recreated with attribution. The destination was private at the initial inventory and later reported public visibility. The migration commands did not request a visibility change.
## Names and compatibility
The primary executable and Cargo package are `betterxen`. Existing `xenora-*` library package names, C interface symbols, the synthetic CPUID vendor string, environment-variable names and synthetic guest import names are retained for compatibility. Copyright notices, licenses, historical review evidence and upstream attribution retain their original names. Prior hardware and verification claims describe upstream evidence and do not certify this renamed copy.
The destination coordination configuration names `Arths17` as its maintainer. Source-specific contributor routing is cleared; destination maintainers can configure it for their own team.
+1 -1
View File
@@ -1,6 +1,6 @@
# Engineering progress
Xenora is an experimental research project. Verified work is restricted to
BetterXen is an experimental research project. Verified work is restricted to
independently authored synthetic programs and shaders; commercial game
execution and authentic Xbox startup are unsupported. Progress is measured by
reproducible tests, not by estimated game compatibility percentages.
+30
View File
@@ -96,3 +96,33 @@ correctness checks. The recorded 1-, 5- and 15-minute load averages were
individual compiler stages and cold/warm timing, tool and capability metadata,
and noise-based variability reporting. See the
[generated report](../../benchmarks/results/apple-m5/run-1795352394/report.md).
## Guest service dispatch
`cargo bench --locked -p xenora-loader --bench service_dispatch` measures
original guest loops that call standard runtime services through a bound
import table under the ARM64 dynamic binary translator. Before timing, each
workload checks its result: the loop count reaches zero, the service returns
its documented value, and `qsort` leaves the array in the order Rust's own sort
produces. The empty loop is reported separately, so readers can subtract the
loop and translation overhead. Each figure is the median per-iteration time of
10 measured batches of 10,000 iterations, after one warm-up batch.
Measured on Apple M2 Pro (12 logical processors), release profile, AC power,
on the working tree after `ed9b93c`. The 1-minute load average was 7.82, so the
machine was not idle and results are indicative only.
| Workload | Before (ns) | After the block `strlen` scan (ns) |
| --- | --- | --- |
| Empty loop | 21.5 | 20.1 |
| `GetLastError` | 181.8 | 188.4 |
| `WaitForSingleObject`, signaled manual-reset event | 281.0 | 284.6 |
| `strlen`, 63 bytes | 1,990.4 | 223.1 |
| `HeapAlloc` + `HeapFree`, 64 bytes | 475.0 | 493.3 |
| `qsort`, 16 ints with a guest comparator | 10,242.0 | 11,396.7 |
The `strlen` change scans 256-unit blocks with one checked read each. It falls
back to per-unit reads only when a block crosses unmapped or unreadable
memory, so the existing exact-fault tests still pass. The other rows differ by up to 11 percent between runs on this loaded
machine; that is run-to-run variation, not a measured change. Raw logs are kept locally under
`artifacts/system-runtime/bench/`. No comparison with native Windows is made.
+53
View File
@@ -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.
+6
View File
@@ -46,3 +46,9 @@ name = "reference"
path = "fuzz_targets/reference.rs"
test = false
doc = false
[[bin]]
name = "runtime_services"
path = "fuzz_targets/runtime_services.rs"
test = false
doc = false
+13
View File
@@ -0,0 +1,13 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#![no_main]
#[path = "../../crates/loader/tests/support/robustness.rs"]
mod robustness;
use libfuzzer_sys::fuzz_target;
use std::sync::OnceLock;
fuzz_target!(|data: &[u8]| {
static DRIVER: OnceLock<robustness::Driver> = OnceLock::new();
DRIVER.get_or_init(robustness::Driver::new).run(data);
});
+1 -1
View File
@@ -68,7 +68,7 @@ def render_progress(status):
]
svg = [
'<svg xmlns="http://www.w3.org/2000/svg" width="530" height="185" viewBox="0 0 530 185" role="img" aria-labelledby="title description">',
'<title id="title">Xenora · recorded progress</title>',
'<title id="title">BetterXen · recorded progress</title>',
'<desc id="description">' + escape(". ".join(f"{label}: {count} of {total}" for label, count, total in rows)) + '</desc>',
'<rect x="1" y="1" width="528" height="183" rx="10" fill="#18212a" stroke="#516171"/>',
'<g font-family="system-ui,sans-serif" fill="#eaf0f5">',
+7 -7
View File
@@ -1,6 +1,6 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
# Build Xenora.app (native ARM64) into build/Xenora.app and run its smoke check.
# Build BetterXen.app (native ARM64) into build/BetterXen.app and run its smoke check.
# Requires: macOS on Apple Silicon, Rust 1.100 (aarch64-apple-darwin), Swift 6 toolchain.
set -eu
cd "$(dirname "$0")/.."
@@ -19,18 +19,18 @@ MACOSX_DEPLOYMENT_TARGET=14.0 cargo build --locked --release -p xenora-ffi --tar
swift build --package-path app -c release --arch arm64 \
-Xlinker -L -Xlinker "$root/target/$target/release"
bundle="$root/build/Xenora.app"
bundle="$root/build/BetterXen.app"
rm -rf "$bundle"
mkdir -p "$bundle/Contents/MacOS"
cp "$(swift build --package-path app -c release --arch arm64 --show-bin-path)/Xenora" "$bundle/Contents/MacOS/Xenora"
cp "$(swift build --package-path app -c release --arch arm64 --show-bin-path)/BetterXen" "$bundle/Contents/MacOS/BetterXen"
cat > "$bundle/Contents/Info.plist" <<PLIST
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleExecutable</key><string>Xenora</string>
<key>CFBundleIdentifier</key><string>local.xenora.Xenora</string>
<key>CFBundleName</key><string>Xenora</string>
<key>CFBundleExecutable</key><string>BetterXen</string>
<key>CFBundleIdentifier</key><string>org.macosporters.betterxen</string>
<key>CFBundleName</key><string>BetterXen</string>
<key>CFBundlePackageType</key><string>APPL</string>
<key>CFBundleShortVersionString</key><string>0.1.0</string>
<key>LSMinimumSystemVersion</key><string>14.0</string>
@@ -52,7 +52,7 @@ PLIST
# this build executes no guest code, so it needs no JIT entitlement.
codesign --force --sign - "$bundle"
binary="$bundle/Contents/MacOS/Xenora"
binary="$bundle/Contents/MacOS/BetterXen"
[ "$(lipo -archs "$binary")" = arm64 ] || fail "executable is not arm64-only: $(lipo -archs "$binary")"
"$binary" --smoke
echo "build-app: built $bundle"
+2 -2
View File
@@ -9,5 +9,5 @@ export MTL_SHADER_VALIDATION_REPORT_TO_STDERR=1
export MTL_SHADER_VALIDATION_ABORT_ON_FAULT=1
export CARGO_BUILD_JOBS=${CARGO_BUILD_JOBS:-4}
cargo build --locked -p xenora
exec timeout 30s cargo run --locked -p xenora -- demo
cargo build --locked -p betterxen
exec timeout 30s cargo run --locked -p betterxen -- demo
+2 -2
View File
@@ -5,8 +5,8 @@ cd "$(dirname "$0")/.."
target=${1:-}
case "$target" in
instruction_stream|fixture|reference) ;;
*) printf '%s\n' 'usage: scripts/fuzz.sh <instruction_stream|fixture|reference> [seconds]' >&2; exit 2 ;;
instruction_stream|fixture|reference|runtime_services) ;;
*) printf '%s\n' 'usage: scripts/fuzz.sh <instruction_stream|fixture|reference|runtime_services> [seconds]' >&2; exit 2 ;;
esac
seconds=${2:-600}
case "$seconds" in
+1 -1
View File
@@ -33,7 +33,7 @@ def check_large_generated_paths(tracked_paths: Iterable[str], *, suspicious_pref
return HealthFinding("generated-paths", ok, detail)
def check_upstream_configured(remotes: Iterable[str], *, expected: str = "ranveersoni98/Xenora") -> HealthFinding:
def check_upstream_configured(remotes: Iterable[str], *, expected: str = "MacosPorters/betterxen") -> HealthFinding:
names = set(remotes)
# Accept either a remote named upstream or origin pointing at expected.
ok = "upstream" in names or "origin" in names
+1 -1
View File
@@ -132,7 +132,7 @@ class Cli(unittest.TestCase):
def test_shipped_config_parses(self):
r = self.run_cli("config-get", "upstream")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual(r.stdout.strip(), "ranveersoni98/Xenora")
self.assertEqual(r.stdout.strip(), "MacosPorters/betterxen")
def test_summary_accepts_now_after_subcommand(self):
# Actions passes --now after `summary`; parent-only --now used to reject that.
+44
View File
@@ -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 BetterXen
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.
+140
View File
@@ -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
+314
View File
@@ -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