mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-28 04:11:20 +00:00
Compare commits
199
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d1bcd0249d | ||
|
|
097bb0b5b8 | ||
|
|
2d77b35e56 | ||
|
|
19f63a0985 | ||
|
|
45322af82e | ||
|
|
aa9a961ef4 | ||
|
|
10347dc21b | ||
|
|
4d530392d1 | ||
|
|
f02eb2678e | ||
|
|
19a905c30e | ||
|
|
bfe0bbfaf7 | ||
|
|
5442503d57 | ||
|
|
f0c61c7a91 | ||
|
|
0caca18634 | ||
|
|
2ea75603be | ||
|
|
6fc06dccff | ||
|
|
a1295d5a48 | ||
|
|
20d7b9ece4 | ||
|
|
0929d0214b | ||
|
|
66f7127553 | ||
|
|
714eaf49e2 | ||
|
|
c93b505223 | ||
|
|
d8f7f2cb13 | ||
|
|
042c08c855 | ||
|
|
7e4ccd1e97 | ||
|
|
96c772edc5 | ||
|
|
496938aef4 | ||
|
|
9d94c0f40a | ||
|
|
4e18000798 | ||
|
|
8c188b04c9 | ||
|
|
9eb75522f0 | ||
|
|
3f41f7406b | ||
|
|
67023d292b | ||
|
|
324eab08c3 | ||
|
|
7d28fc89de | ||
|
|
9a29bd9c37 | ||
|
|
38359969cd | ||
|
|
652c6ae02f | ||
|
|
0529c62226 | ||
|
|
e6fa931264 | ||
|
|
3b47c21bb0 | ||
|
|
9a62d86a89 | ||
|
|
4b32c532fe | ||
|
|
af1b84ad75 | ||
|
|
cf438e25aa | ||
|
|
bd46504a97 | ||
|
|
cc4dd092cf | ||
|
|
04ee981103 | ||
|
|
bbc84c0da0 | ||
|
|
d2f77cdea3 | ||
|
|
3a36379db4 | ||
|
|
147e2a9f1a | ||
|
|
a7fa8b0d65 | ||
|
|
fd0e73bc28 | ||
|
|
35de41bd5f | ||
|
|
e6b657a2e9 | ||
|
|
c05e631c6d | ||
|
|
6bac25f099 | ||
|
|
d35c278284 | ||
|
|
34a583b101 | ||
|
|
061c28b405 | ||
|
|
3b52215a30 | ||
|
|
0214a7bab5 | ||
|
|
fbec436b89 | ||
|
|
47b526fba9 | ||
|
|
c68e3ccb4c | ||
|
|
fb6282ceb2 | ||
|
|
bb6a9f6912 | ||
|
|
a7e3e1e42c | ||
|
|
9c76bf16f0 | ||
|
|
2f28a5adbb | ||
|
|
788de1e83b | ||
|
|
7dd1329866 | ||
|
|
4b579af70d | ||
|
|
b4f45573cf | ||
|
|
0766307acc | ||
|
|
9dfdfd1134 | ||
|
|
ce8d16e367 | ||
|
|
8df13ae976 | ||
|
|
36c4fbd520 | ||
|
|
3c8b6bad97 | ||
|
|
d4c29cd7dd | ||
|
|
7246ab5ea6 | ||
|
|
938cbd3028 | ||
|
|
c9505e53e2 | ||
|
|
02eb8046a1 | ||
|
|
4a0b5d4ded | ||
|
|
00eb6971e9 | ||
|
|
c3b0025977 | ||
|
|
1013746e17 | ||
|
|
7c88e5d655 | ||
|
|
bb318ed2ba | ||
|
|
b1b57cf16a | ||
|
|
cdcc55c33e | ||
|
|
0730f4dbbf | ||
|
|
6f27da3ccc | ||
|
|
6236996f41 | ||
|
|
05f2526d27 | ||
|
|
e5aca73c55 | ||
|
|
281d92bfb5 | ||
|
|
5131de9cd6 | ||
|
|
fec13fa27a | ||
|
|
68503a674c | ||
|
|
82cb66e80f | ||
|
|
06dbe2946d | ||
|
|
685217e61b | ||
|
|
a0d4b7bf5d | ||
|
|
14d5083f0f | ||
|
|
0115af5c04 | ||
|
|
9ddb708cdf | ||
|
|
5b7ffec90a | ||
|
|
48c5d20aa9 | ||
|
|
8049c36f51 | ||
|
|
94783fa603 | ||
|
|
c91036f879 | ||
|
|
c1cea65e17 | ||
|
|
974d1fc62c | ||
|
|
6f1ac2a906 | ||
|
|
223a754eb7 | ||
|
|
3d19c756e2 | ||
|
|
d195978903 | ||
|
|
830f93ff14 | ||
|
|
4962f054c8 | ||
|
|
67dfb18166 | ||
|
|
782c49167c | ||
|
|
6106c37912 | ||
|
|
d2491dee07 | ||
|
|
823a5812a0 | ||
|
|
c1ca4ea140 | ||
|
|
710a2e1e73 | ||
|
|
de92766b29 | ||
|
|
4d44765363 | ||
|
|
6de750b152 | ||
|
|
c95e175210 | ||
|
|
adf10db015 | ||
|
|
4e4a6b36be | ||
|
|
403a67747f | ||
|
|
509811aad0 | ||
|
|
dc3b02b62f | ||
|
|
d847d7ea6e | ||
|
|
b9372408c8 | ||
|
|
8b67479526 | ||
|
|
0fdb995892 | ||
|
|
b55a4c24ef | ||
|
|
48e1e5c8c1 | ||
|
|
6947fe7ff6 | ||
|
|
94732d90ca | ||
|
|
1e8893a6bf | ||
|
|
d7f7d586d3 | ||
|
|
b8fbdf35b9 | ||
|
|
d01627b3de | ||
|
|
291c9807ee | ||
|
|
84866956b9 | ||
|
|
47cb26ebdd | ||
|
|
1d363c3c34 | ||
|
|
eaeab25590 | ||
|
|
e74ebbe30b | ||
|
|
26eba92b87 | ||
|
|
05143d6295 | ||
|
|
d6a65b2940 | ||
|
|
1cc7f01fec | ||
|
|
8d19006c32 | ||
|
|
6a4fc7cce1 | ||
|
|
b5b24347e9 | ||
|
|
f8eb976102 | ||
|
|
84221ac715 | ||
|
|
673e2a4556 | ||
|
|
bbb59324c0 | ||
|
|
34b16ca65c | ||
|
|
fd0e427c7b | ||
|
|
314d1f5874 | ||
|
|
7adb978683 | ||
|
|
9d5de05055 | ||
|
|
3348d34e6f | ||
|
|
8e9ec8b9d1 | ||
|
|
b54f5ef0aa | ||
|
|
4d5207afd8 | ||
|
|
27daa701c1 | ||
|
|
c985c3fa17 | ||
|
|
6ad1602a3d | ||
|
|
82cafe9664 | ||
|
|
bf2c279dc7 | ||
|
|
3521dca45b | ||
|
|
131c8669cf | ||
|
|
2c8c63cf65 | ||
|
|
da16b36499 | ||
|
|
061568a6ee | ||
|
|
a03188315d | ||
|
|
95f6b52d9f | ||
|
|
7499d6f6c3 | ||
|
|
3a3f0c52af | ||
|
|
989bb79d6c | ||
|
|
d157f802d3 | ||
|
|
fb0544652b | ||
|
|
61943d23b6 | ||
|
|
947d6e4eaf | ||
|
|
b49d50e34e | ||
|
|
e0a6dae554 | ||
|
|
b3a6a57a8e |
No files matched your search
@@ -0,0 +1,2 @@
|
||||
# Every change needs a review from the maintainers team.
|
||||
* @MacosPorters/maintainers
|
||||
@@ -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": {}
|
||||
}
|
||||
@@ -41,6 +41,8 @@ jobs:
|
||||
python3 crates/isa/generate_semantics.py --check
|
||||
python3 scripts/audit/semantic_coverage.py --check
|
||||
python3 scripts/audit/status.py --check
|
||||
# The generated status check must not depend on the host locale encoding.
|
||||
LC_ALL=C PYTHONCOERCECLOCALE=0 PYTHONUTF8=0 python3 scripts/audit/status.py --check
|
||||
for fixture in x2 x3 x4; do
|
||||
python3 "experiments/x1/fixtures/$fixture.py" --check || exit 1
|
||||
done
|
||||
@@ -50,6 +52,8 @@ jobs:
|
||||
sh -n scripts/agent-queue.sh scripts/agent-sync.sh
|
||||
- name: Test pull request template check
|
||||
run: PYTHONPATH=scripts python3 -m unittest discover -s tests/pr_template
|
||||
- name: Test native audit JSON decoding
|
||||
run: python3 -m unittest discover -s tests/audit
|
||||
- name: Test semantic registry generator and coverage report
|
||||
run: |
|
||||
python3 -m unittest discover -s tests/semantics_generator
|
||||
@@ -65,11 +69,11 @@ jobs:
|
||||
cargo test --locked --workspace
|
||||
cargo test --locked --manifest-path experiments/x1/Cargo.toml
|
||||
scripts/audit/dependencies.sh
|
||||
scripts/audit/claims.sh
|
||||
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"
|
||||
@@ -35,6 +35,7 @@
|
||||
|
||||
__pycache__/
|
||||
*.pyc
|
||||
/diagnostics/probe/
|
||||
/diagnostics/gta6-candidate-*/
|
||||
/diagnostics/gta6-check/
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
+73
-1
@@ -10,15 +10,69 @@ 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.
|
||||
- The ARM64 assembler loads 64-bit constants with the fewest MOVZ or MOVN plus MOVK instructions (#92). It no longer emits MOVK for zero halfwords and starts from MOVN when more halfwords are 0xFFFF than zero, so small negative values take one instruction instead of four. On Apple M5 the DBT benchmark emits 245,168 instead of 290,184 native bytes for its 626 blocks (-15.5%) and the 1,048 integer fixture instructions 128,724 instead of 145,732 (-11.7%); benchmark run times did not change measurably. New tests check the sequences against LLVM encodings and execute 1,056 of them on the host through the JIT.
|
||||
- Resolve the tiled BC1 mip and array layer once per linearization and copy contiguous block runs within each tile row. Partial edge blocks are retained and padding slots are skipped. Closes #349.
|
||||
- Changed the default report folder of `xenora probe` and `xenora imports sync` to `diagnostics/probe`, which Git ignores (#364). Anyone relying on the earlier default has to pass `--report`.
|
||||
- Relocation reports now build their type histogram once per image, avoiding a tree lookup for every entry. Target checks and fixup order are unchanged; synthetic regressions and an opt-in relocation timing test cover the change (#109).
|
||||
- Moved the six supported gfx1030 SOPP compute control forms into the semantic registry, preserving instruction decoding and shader lowering. Part of #215.
|
||||
- Moved gfx1030 `s_mov_b32` (SOP1) into the semantic registry, preserving its existing decode domain and shader output. The move operand rule retains explicit VCC and EXEC half destinations. Part of #215.
|
||||
- Moved the six hand-written gfx1030 VOP2 logical and shift forms (`v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`, `v_ashrrev_i32`, AMD guide section 12.7) into the semantic registry under a new VGPR-only operand rule `vop2_vgpr2`, with no behaviour change: a sweep of 132,608 VOP2, VOP1 and SOP1 words decodes to the same text, length and error before and after, the MSL goldens are unchanged, and the runtime-region allowlist admits exactly the same six forms. The per-lane `VectorBinary` gained `And`, `Or`, `Xor` and the three shifts (count masked to S0[4:0]); 6 hand-written instruction variants and their decoder and lowering arms are gone (17 hand-written forms remain). Part of #215.
|
||||
- Added non-blocking Metal compute submission through `submit_words` and `wait`, with completion-aware resource retirement and a sixteen-dispatch in-flight limit. Synchronous calls keep their existing behavior. The benchmark reports the host submission split and compares synchronous and pipelined batches.
|
||||
- Reuse up to 16 native Metal compute pipelines per context for repeated shader source and entry points. Pending dispatches retain their pipelines through completion, including after eviction. Dispatch profiles report zero library and pipeline setup time when a cached pipeline is reused. Closes #132.
|
||||
- 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).
|
||||
- Added the VOP3A (`_e64`) encodings of eleven gfx1030 VOP2 integer forms (`v_mul_{i32_i24,hi_i32_i24,u32_u24,hi_u32_u24}`, `v_{min,max}_{i32,u32}`, `v_xnor_b32`, `v_sub_nc_u32`, `v_subrev_nc_u32`) and of the sixteen Wave32 integer compares (explicit SGPR mask destination, `s_cbranch_vccz` through `vcc_lo`, a translation error for reads of runtime-only SGPR results) as semantic-registry encoding variants, with VGPR sources only. New fixtures `vop3-integer` and `vop3-compare` with IR and MSL goldens, and an independent guide-derived oracle (`tests/validation/tests/vop3_{integer,compare}.rs`) that agrees on both reference interpreters and on native Metal. Part of #215.
|
||||
- Added `scripts/cpu-tests.sh`, which lists the default-feature workspace test targets and runs
|
||||
deterministic shards of them (`--shard K/N`), with `--check N` showing every target lands in
|
||||
exactly one shard. It does not replace `cargo test --locked --workspace` or
|
||||
`scripts/test-gpu.sh`. `docs/testing/cpu-coverage.md` records local CPU gate timings on one
|
||||
Apple M4 host (about 40 s wall time; one loader target takes about 19 s) and shows that the 2- and
|
||||
3-shard unions match the full gate's 681 passed and 34 ignored tests (#159).
|
||||
- Added guest texture binding through D3D12-style descriptor tables (#303): shader-visible CBV_SRV_UAV and sampler heaps, `CreateShaderResourceView` for one-level RGBA8 and BC1 2D textures, a point/clamp `CreateSampler`, a root signature with one pixel-stage SRV table and one sampler table, and `SetDescriptorHeaps`/`SetGraphicsRootDescriptorTable` in `crates/loader/src/graphics.rs`, plus `NativeCompute::render_rgba8_sampled_bc1`. Verified locally on an Apple M5 Pro under Metal validation: a guest draw with the translated `image_sample_lz` pixel stage matches the software reference and hand-derived images on 16 of 16 pixels for two RGBA8 textures and 64 of 64 for an 8×8 BC1 texture. A wrong descriptor slot changes the image, off-centre and out-of-range coordinates point-sample with clamping, and a rejected binding, draw shape or resource state never reaches the backend. The software reference samples BC1 with the spec-exact decoder, while Apple's hardware rounds BC1's interpolated palette entries differently (171/84 against 170/85), so the BC1 fixtures use only endpoint colours. Not yet reachable from guest imports. Not yet independently accepted.
|
||||
- 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.
|
||||
- Added MOVS and STOS for 8- to 64-bit elements, with and without REP, and the direction flag with CLD and STD (#129). A REP form runs one element per step and stays on the instruction until RCX is zero, so every element counts against the step budget, a repeat can stop part-way and resume, a zero count touches nothing, and a fault keeps the elements already done with RSI, RDI and RCX at the one that faulted. An FS or GS override applies to the MOVS source only. Both engines run these on the shared semantics with no bulk-copy path, so large copies are slow. LODS, CMPS, SCAS, REPE, REPNE and the address-size override stay rejected. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and `tests/cpu_rep.rs` adds a byte-array model over every form, direction and count; not compared with x86 hardware and awaiting independent review.
|
||||
- Added a deterministic guest thread scheduler (first part of #323): independent CPU contexts, guarded stacks and TEBs on one host thread, with bounded turns, `CreateThread`, `ExitThread`, `TerminateThread`, `GetExitCodeThread`, `SuspendThread`, `ResumeThread` and `SwitchToThread`. With a scheduler attached, `WaitForSingleObject` and `WaitForMultipleObjects` block only the calling guest thread, with timeouts, on threads, events, semaphores and mutexes; abandoned mutexes, deadlocks and per-thread faults are reported. Guest threads never run concurrently. Critical sections, SRW locks, condition variables and `Sleep` do not block per thread yet. See `docs/runtime/threads.md`.
|
||||
- Added decoding and Metal shader translation for the sixteen Wave32 VOPC 64-bit integer compares (#215). They read VGPR pairs, known even-aligned SGPR pairs or sign-extended inline integers and write the Wave32 VCC mask. The guide-derived oracle passes on native Metal (4,640 cases in 3,818 programs on a local Apple M5 under API and shader validation); acceptance is pending.
|
||||
- Added XADD and CMPXCHG for 8- to 64-bit register and memory destinations, and the LOCK prefix on their memory forms (#198). LOCK anywhere else, CMPXCHG8B and CMPXCHG16B stay rejected. Both engines run the new forms on the shared semantics, one instruction at a time, so a locked instruction is indivisible today and LOCK changes no result; `docs/cpu/instruction-registry.md` states the ordering, alignment, compare-failure and fault rules a guest scheduler must preserve. A failed compare still writes the destination, so it faults on memory that cannot be written. Nothing is lowered to ARM64 atomic instructions, and no multi-thread behaviour is established. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, with 62 LLVM-assembled fixtures and five new tests in `x86_atomic.rs`; not compared with x86 hardware and awaiting independent review.
|
||||
- Added CPUID with a fixed, host-independent guest contract (#130). It reports a synthetic processor with the vendor string `Xenora guest` and sets a feature bit only when every instruction of that feature is implemented: CMOV, POPCNT, LZCNT and long mode today. SSE and SSE2 are not reported while parts of them, such as RSQRTPS and MFENCE, are still rejected, so the table is truthful about Xenora and not a plausible hardware model. Unlisted leaves return zeros. `tests/cpu_features.rs` pins every leaf in both engines, requires each reported feature's instructions among the executed fixtures, and holds a refused witness instruction for 31 unreported features. `docs/cpu/instruction-registry.md` gives the table and the rule for reporting a new feature. Not compared with a processor; awaiting independent review.
|
||||
- Added six Wave32 gfx1030 VOP1 integer forms through the semantic registry, including bit scans and a two-register swap under EXEC (AMD RDNA 2 ISA guide section 12.8, #215). The compiler accepts 752 guide-derived cases and rejects 610 programs at the oracle’s expected offsets. Native Metal verification and independent acceptance are pending.
|
||||
- Added delay-loaded imports to the static PE probe (#244). `xenora probe --mode static` now reads the PE32+ delay-load directory and lists each delay-loaded import in `imports.csv` with its DLL, symbol or ordinal, and delay import address table slot. A new `import_table` column, inserted after `iat_rva`, marks every row `ordinary` or `delayed`; `import_kind` stays the last column. The existing totals and `missing_imports.csv` still cover ordinary imports only, and the JSON report adds `delayed_imports`, `delayed_imported_dlls_count` and `delay_import_error`. The table is bounded by the directory's declared size, which must hold the empty descriptor that ends it, and each descriptor's DLL name, import address table and import name table must be present and start in section data. A table that breaks these rules, is truncated, sets a reserved attribute bit or uses the earlier virtual-address descriptor form is reported with the entries read before the problem. `xenora imports sync` leaves delayed rows out of its backlog. Inspection stays static: nothing is bound or executed. Covered by an original fixture (`fixtures/pe/delay-imports.exe`, generated by `fixtures/pe/delay-imports.py`) whose imports were cross-checked locally with `llvm-readobj --coff-imports` from LLVM 23.1.6; awaiting independent review.
|
||||
- Added the sixteen gfx1030 SOPK integer forms through the semantic registry: `s_movk_i32`, `s_cmovk_i32`, `s_cmpk_{eq,lg,gt,ge,lt,le}_{i32,u32}`, `s_addk_i32` and `s_mulk_i32` (AMD guide sections 12.2 and 13.1.2), with SDST s0-s105 only and SIMM16 sign-extended (zero-extended for the unsigned compares). The registry gained the operand rules `sopk_sgpr` and `sopk_compare` and the operations `mov` and `cmov`; the decoder and the scalar translation fold them like SOP2 and SOPC. An independent guide-derived oracle (`tests/validation/tests/sopk.rs`, 4,184 cases and 398 rejections on both CPU interpreters and native Metal), an LLVM-assembled fixture `scalar-immediate.s` with IR and MSL goldens, and the LLVM three-way decoder check cover them (part of #215).
|
||||
- Added an independent guide-derived oracle for the Wave32 16-bit (`v_cmp_{lt..ge}_{i16,u16}_e32`) and 64-bit (`v_cmp_{f..t}_{i64,u64}_e32`) integer compares in the reference and the second interpreter (6,212 lane cases, 1,208 rejections; contract in `docs/shaders/vector-compare.md` section 2a). The decoder and translator still reject these forms, and native Metal agreement is not yet shown. Part of #215.
|
||||
- Added an independent guide-derived oracle for the Wave32 16-bit (`v_cmp_{lt..ge}_{i16,u16}_e32`) and 64-bit (`v_cmp_{f..t}_{i64,u64}_e32`) integer compares in the reference and the second interpreter (6,212 lane cases, 1,208 rejections; contract in `docs/shaders/vector-compare.md` section 2a). Part of #215.
|
||||
- Added `python3 -m qa rdna2 rank` to the read-only RDNA2 planner: it groups undeclared gfx1030 forms by the piece of work that would unlock them (an encoding variant of a declared form, a new operand rule, or a new primitive, from XML identity and operand shape only) and ranks the groups by forms per estimated cost, excluding claimed scopes, with `--no-float` to leave out floating-point groups until the FP contract exists (part of #215).
|
||||
- Added authoritative read-only x86-64 CPU inventory CLI (`python3 -m qa cpu-inventory`) over `crates/loader/x86/instructions.toml` via `generate_x86.load`, with opcode-map/prefix/operand summaries, native vs shared-semantic operation partitions from `dbt.rs`, fixture mnemonic evidence and a separate unsupported catalog. Does not count candidates as implemented. Covered by `tests/qa/test_cpu_inventory.py`.
|
||||
- Added typed runtime inventory CLI (`python3 -m qa runtime-inventory`) over `crates/loader/runtime/services.txt`, reporting implemented/partial/stub services separately from API-set aliases and leaving independently-verified empty unless recorded. Covered by `tests/qa/test_runtime_inventory.py`.
|
||||
@@ -44,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.
|
||||
@@ -52,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.
|
||||
@@ -177,7 +239,16 @@ 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.
|
||||
- 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.
|
||||
- Fixed the MXCSR flags of an unmasked floating-point overflow whose result is exact before the exponent is bounded, such as the largest binary32 value times two (#128). Only the overflow flag is set; the precision flag used to be set as well although nothing was rounded. A masked overflow still sets both flags and delivers infinity or the largest finite value, and an unmasked overflow that is also inexact still sets both. Five Intel SDM cases in `cpu_known_answers.rs` moved from open defect to verified on both engines, with three more for the other rounding modes, and the scalar and conversion sweeps now compare the precision flag in this case as well. Not compared with x86 hardware; awaiting independent review.
|
||||
- Fixed the decoder refusing an instruction whose REX prefix is followed by a legacy prefix (#69). Such a REX is ignored, as the Intel SDM (Vol. 2A, 2.2.1) specifies, so `48 66 01 D8` now runs as `add ax, bx`; it used to stop the guest with an illegal-instruction exit. The ignored byte still counts toward the instruction's length, and a REX that directly precedes the opcode behaves as before. The interpreter, the DBT and the static probe share the decoder. One SDM-derived case in `cpu_known_answers.rs` moved from refused to verified and three were added, for an ignored REX.B, an ignored REX.W before a segment prefix, and a later REX that does apply. Two REX bytes in a row and the address-size prefix stay rejected. Not compared with x86 hardware; awaiting independent review.
|
||||
- Fixed import binding writing some slots before finding an unresolved import, and service calls taking effect before an unreadable return address was noticed. A service that changes a nonvolatile register, including XMM6 to XMM15, now stops the guest (part of #201).
|
||||
- Fixed older import-generator templates that reported success for unimplemented wrappers, used a nonexistent exit reason, and read floating-point arguments from integer registers.
|
||||
- Fixed guest flags in the native DBT (#64, #70). They lived only in host NZCV, so they were lost across helper calls and block boundaries and register ADD, SUB and XOR set none. JB, JAE, JBE and JA used ARM carry polarity, which is inverted for subtraction. Flags are now stored in the guest state.
|
||||
@@ -186,6 +257,7 @@ remains unsupported.
|
||||
- Fixed 32-bit guest stores and loads in the native DBT (MOV 89/8B and C7 /0), which accessed eight bytes: stores overwrote the next four guest bytes and accesses at the end of a mapping faulted. RIP-relative operands of byte moves and extensions, which were read as RBP-relative, and LEA with a segment prefix, which added the segment base, are fixed too.
|
||||
- Fixed an x86 prefix-length test that read an untracked fuzz artifact and so failed on every fresh checkout; its input is now inline.
|
||||
- Fixed agent-queue `apply_actions` crashing on comment-only decisions (claim refusals) by skipping no-op `gh issue edit` calls; accept `summary --now` after the subcommand; grant the audit job `pull-requests: read` so live audits can list open PRs (issue #180).
|
||||
- Fixed `scripts/audit/status.py` and the Python embedded in `scripts/audit/claims.sh` reading and writing tracked files in the process locale encoding instead of UTF-8: under an ASCII or cp1252 locale the status check crashed on `docs/claims.toml` or reported a spurious `xenora-progress.svg` difference. Both scripts now pass `encoding="utf-8"`, as the rest of `scripts/` does, the two write sites also pin `newline="\n"` so a Windows host cannot turn tracked LF files into CRLF when it regenerates them, and CI runs the two checks again under a non-UTF-8 locale so the requirement stays enforced.
|
||||
|
||||
- Generated CRT adapters now report unsupported calls when the required guest ABI or runtime behavior is missing.
|
||||
|
||||
|
||||
+2
-2
@@ -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
@@ -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
+2
-1
@@ -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",
|
||||
@@ -204,6 +204,7 @@ dependencies = [
|
||||
"sha2",
|
||||
"xenora-metal",
|
||||
"xenora-shader",
|
||||
"xenora-texture",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -10,3 +10,10 @@ rust-version = "1.100"
|
||||
|
||||
[workspace.lints.rust]
|
||||
unsafe_op_in_unsafe_fn = "deny"
|
||||
|
||||
# Whole-program optimization for release and bench builds (#116). On an Apple M5 the
|
||||
# interpreter ran about 6 % and cold DBT about 9 % faster in `dbt_bench`, at the cost of
|
||||
# slower release builds. Debug and test builds are unaffected.
|
||||
[profile.release]
|
||||
lto = "fat"
|
||||
codegen-units = 1
|
||||
@@ -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.
|
||||
|
||||
[](https://github.com/ranveersoni98/Xenora/actions/workflows/ci.yml)
|
||||
[](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
|
||||
@@ -309,7 +311,7 @@ These require a Metal-capable Apple Silicon Mac.
|
||||
scripts/test-gpu.sh
|
||||
```
|
||||
|
||||
The native test suite enables Metal API and shader validation and tests the supported compute, rendering and texture paths.
|
||||
The native test suite enables Metal API and shader validation and tests the supported compute, rendering and texture paths. The full semantic-review batch defaults to a 300-second timeout; set `XENORA_SEMANTIC_TIMEOUT` to raise or lower it for a slower or faster host. On macOS, the script uses a Python 3 fallback when GNU `timeout` is unavailable.
|
||||
|
||||
### Verify guest execution
|
||||
|
||||
@@ -359,16 +361,12 @@ See the [roadmap table](#development-milestones) for proposed milestones, and th
|
||||
|
||||
---
|
||||
|
||||
### Contributors
|
||||
|
||||
[](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
@@ -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
@@ -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
@@ -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"),
|
||||
]
|
||||
)
|
||||
@@ -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,5 +1,5 @@
|
||||
[package]
|
||||
name = "xenora"
|
||||
name = "betterxen"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
+23
-19
@@ -6,11 +6,14 @@ mod shaders;
|
||||
|
||||
use std::process::ExitCode;
|
||||
|
||||
/// Where `probe` writes and `imports sync` reads without `--report`.
|
||||
const DEFAULT_REPORT_DIR: &str = "diagnostics/probe";
|
||||
|
||||
fn main() -> ExitCode {
|
||||
match std::env::args().nth(1).as_deref() {
|
||||
Some("info") => {
|
||||
println!(
|
||||
"Xenora {} ({})",
|
||||
"BetterXen {} ({})",
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
std::env::consts::ARCH
|
||||
);
|
||||
@@ -18,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) {
|
||||
@@ -46,7 +49,7 @@ fn main() -> ExitCode {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let mut pe_path: Option<String> = None;
|
||||
let mut mode = "static".to_string();
|
||||
let mut report_dir = "diagnostics/gta6-candidate-e95020b2".to_string();
|
||||
let mut report_dir = DEFAULT_REPORT_DIR.to_string();
|
||||
|
||||
let mut i = 2;
|
||||
while i < args.len() {
|
||||
@@ -87,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);
|
||||
};
|
||||
@@ -108,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);
|
||||
@@ -134,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);
|
||||
}
|
||||
|
||||
@@ -157,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)
|
||||
}
|
||||
}
|
||||
@@ -328,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);
|
||||
};
|
||||
@@ -373,7 +376,7 @@ fn run_imports_generate_cli(args: &[String]) -> ExitCode {
|
||||
}
|
||||
|
||||
fn run_imports_sync_cli(args: &[String]) -> ExitCode {
|
||||
let mut report_dir = "diagnostics/gta6-candidate-e95020b2".to_string();
|
||||
let mut report_dir = DEFAULT_REPORT_DIR.to_string();
|
||||
let mut check_mode = false;
|
||||
|
||||
let mut i = 0;
|
||||
@@ -434,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.
|
||||
@@ -522,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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Default report folder of `betterxen probe` and `betterxen imports sync`.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
#[test]
|
||||
fn probe_and_sync_use_the_same_default_folder() {
|
||||
let fixture = concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/../../fixtures/pe/delay-imports.exe"
|
||||
);
|
||||
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_betterxen"))
|
||||
.args(arguments)
|
||||
.current_dir(&folder)
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success(), "{arguments:?}");
|
||||
}
|
||||
let written = ["imports.csv", "import_backlog.md"]
|
||||
.map(|name| folder.join("diagnostics/probe").join(name).is_file());
|
||||
std::fs::remove_dir_all(folder).unwrap();
|
||||
assert_eq!(written, [true, true]);
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
+99
-69
@@ -5,17 +5,17 @@ use std::fmt;
|
||||
pub use xenora_isa::{
|
||||
Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp,
|
||||
ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, ScalarSource, ScalarUnaryOp,
|
||||
VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorSource,
|
||||
SoppControlOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorCompareVop3Op,
|
||||
VectorSource, VectorSwapOp, VectorUnaryOp,
|
||||
};
|
||||
use xenora_isa::{
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ,
|
||||
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_ENDPGM, S_WAITCNT, S_WAITCNT_VSCNT, V_ADD_F32,
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_WAITCNT_VSCNT, V_ADD_F32,
|
||||
V_INTERP_P1_F32, V_INTERP_P2_F32, V_MOV_B32, V_MUL_F32, VCC_LO,
|
||||
};
|
||||
|
||||
use xenora_isa::meta::EncodingFamily;
|
||||
pub use xenora_isa::semantics::VectorBinary;
|
||||
use xenora_isa::semantics::{FORM_IDS, OperandRule};
|
||||
pub use xenora_isa::semantics::{VectorBinary, VectorLowering, VectorUnary, VectorVcc};
|
||||
|
||||
/// Metadata forms that [`decode`] turns into an [`Instruction`] for at least one
|
||||
/// operand combination: the hand-written forms below followed by every form of
|
||||
@@ -40,17 +40,11 @@ const fn concat_forms<const N: usize>() -> [(&'static str, EncodingFamily); N] {
|
||||
}
|
||||
|
||||
/// Decoded forms not yet described by the semantic registry.
|
||||
const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 16] = [
|
||||
const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 10] = [
|
||||
("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf),
|
||||
("BUFFER_STORE_DWORD", EncodingFamily::Mubuf),
|
||||
("EXP", EncodingFamily::Exp),
|
||||
("IMAGE_SAMPLE_LZ", EncodingFamily::Mimg),
|
||||
("S_BRANCH", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_EXECZ", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_SCC0", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_VCCZ", EncodingFamily::Sopp),
|
||||
("S_ENDPGM", EncodingFamily::Sopp),
|
||||
("S_WAITCNT", EncodingFamily::Sopp),
|
||||
("S_WAITCNT_VSCNT", EncodingFamily::Sopk),
|
||||
("V_ADD_F32", EncodingFamily::Vop2),
|
||||
("V_INTERP_P1_F32", EncodingFamily::Vintrp),
|
||||
@@ -316,9 +310,46 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
if V_MOV_B32.matches(first) {
|
||||
return move_b32(first, bytes);
|
||||
}
|
||||
// AMD RDNA 2 ISA guide 13.3.2: VDST occupies bits 17–24 and SRC0 bits 0–8.
|
||||
if let Some(op) = VectorUnaryOp::from_word(first) {
|
||||
let dst = (first >> 17) as u8;
|
||||
let (src, len) = vector_src0(first, bytes, op.assembly_name())?;
|
||||
return Ok((Instruction::VectorUnary { op, dst, src }, len));
|
||||
}
|
||||
if let Some(op) = VectorSwapOp::from_word(first) {
|
||||
if first & 0x100 == 0 {
|
||||
return Err(unsupported(
|
||||
op.assembly_name(),
|
||||
"expected a VGPR SRC0 for writeback",
|
||||
));
|
||||
}
|
||||
let dst = (first >> 17) as u8;
|
||||
let src = first as u8;
|
||||
return Ok((Instruction::VectorSwap { op, dst, src }, 4));
|
||||
}
|
||||
if let Some(op) = VectorCompareOp::from_word(first) {
|
||||
return vector_compare(op, first, bytes);
|
||||
}
|
||||
if let Some(op) = VectorCompareVop3Op::from_word(first) {
|
||||
let second = word(bytes, 8)?;
|
||||
let sdst = first as u8;
|
||||
if sdst > VCC_LO {
|
||||
return Err(unsupported(
|
||||
op.assembly_name(),
|
||||
"expected a destination of s0-s105 or vcc_lo",
|
||||
));
|
||||
}
|
||||
let (src0, src1) = vop3_vgpr2_sources(op.assembly_name(), first, second)?;
|
||||
return Ok((
|
||||
Instruction::VectorCompareVop3 {
|
||||
op,
|
||||
sdst,
|
||||
src0,
|
||||
src1,
|
||||
},
|
||||
8,
|
||||
));
|
||||
}
|
||||
if let Some(op) = VectorAluVop3Op::from_word(first) {
|
||||
let second = word(bytes, 8)?;
|
||||
return Ok((vop3_vgpr2(op, first, second)?, 8));
|
||||
@@ -379,34 +410,25 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
let simm16 = first as u16;
|
||||
return Ok((Instruction::ScalarImmediateCompare { op, src, simm16 }, 4));
|
||||
}
|
||||
if S_BRANCH.matches(first) {
|
||||
let target = branch_target(first, offset, "s_branch")?;
|
||||
return Ok((Instruction::Branch { target }, S_BRANCH.byte_len()));
|
||||
if let Some(op) = SoppControlOp::from_word(first) {
|
||||
let immediate = first as u16;
|
||||
if op
|
||||
.required_immediate()
|
||||
.is_some_and(|exact| immediate != exact)
|
||||
{
|
||||
let detail = if op == SoppControlOp::EndProgram {
|
||||
"expected zero immediate"
|
||||
} else {
|
||||
"expected vmcnt(0) alone"
|
||||
};
|
||||
return Err(unsupported(op.mnemonic(), detail));
|
||||
}
|
||||
let instruction = op.decode(|| branch_target(immediate, offset, op.mnemonic()))?;
|
||||
return Ok((instruction, 4));
|
||||
}
|
||||
if let Some(op) = ScalarAluOp::from_word(first) {
|
||||
return scalar_alu(op, first, bytes);
|
||||
}
|
||||
if S_CBRANCH_SCC0.matches(first) {
|
||||
let target = branch_target(first, offset, "s_cbranch_scc0")?;
|
||||
return Ok((
|
||||
Instruction::BranchSccZero { target },
|
||||
S_CBRANCH_SCC0.byte_len(),
|
||||
));
|
||||
}
|
||||
if S_CBRANCH_EXECZ.matches(first) {
|
||||
let target = branch_target(first, offset, "s_cbranch_execz")?;
|
||||
return Ok((
|
||||
Instruction::BranchExecZero { target },
|
||||
S_CBRANCH_EXECZ.byte_len(),
|
||||
));
|
||||
}
|
||||
if S_CBRANCH_VCCZ.matches(first) {
|
||||
let target = branch_target(first, offset, "s_cbranch_vccz")?;
|
||||
return Ok((
|
||||
Instruction::BranchVccZero { target },
|
||||
S_CBRANCH_VCCZ.byte_len(),
|
||||
));
|
||||
}
|
||||
if let Some(op) = VectorAluOp::from_word(first) {
|
||||
// VOP2: SRC0 in bits 0-8, VSRC1 in bits 9-16, VDST in bits 17-24.
|
||||
let dst = ((first >> 17) & 0xff) as u8;
|
||||
@@ -417,7 +439,10 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
let (_, src0, _) = vop2_registers(first, op.assembly_name())?;
|
||||
(VectorSource::Register(src0), 4)
|
||||
}
|
||||
_ => vector_src0(first, bytes, op.assembly_name())?,
|
||||
OperandRule::Vop2Vgpr | OperandRule::Vop2Vcc => {
|
||||
vector_src0(first, bytes, op.assembly_name())?
|
||||
}
|
||||
_ => unreachable!("non-VOP2 operand rule for VOP2 instruction"),
|
||||
};
|
||||
return Ok((
|
||||
Instruction::VectorAlu {
|
||||
@@ -443,15 +468,6 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
V_MUL_F32.byte_len(),
|
||||
));
|
||||
}
|
||||
if S_WAITCNT.matches(first) {
|
||||
return scalar_form(
|
||||
first,
|
||||
S_WAITCNT.byte_len(),
|
||||
0xbf8c_3f70,
|
||||
Instruction::WaitLoad,
|
||||
"expected vmcnt(0) alone",
|
||||
);
|
||||
}
|
||||
if S_WAITCNT_VSCNT.matches(first) {
|
||||
return scalar_form(
|
||||
first,
|
||||
@@ -461,15 +477,6 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
"expected null, 0",
|
||||
);
|
||||
}
|
||||
if S_ENDPGM.matches(first) {
|
||||
return scalar_form(
|
||||
first,
|
||||
S_ENDPGM.byte_len(),
|
||||
0xbf81_0000,
|
||||
Instruction::EndProgram,
|
||||
"expected zero immediate",
|
||||
);
|
||||
}
|
||||
|
||||
Err(DecodeErrorKind::UnsupportedOpcode { word: first })
|
||||
}
|
||||
@@ -526,11 +533,11 @@ fn scalar_source(
|
||||
}
|
||||
|
||||
fn branch_target(
|
||||
first: u32,
|
||||
immediate: u16,
|
||||
offset: usize,
|
||||
mnemonic: &'static str,
|
||||
) -> Result<usize, DecodeErrorKind> {
|
||||
let displacement = first as u16 as i16;
|
||||
let displacement = immediate as i16;
|
||||
let words = usize::try_from(displacement)
|
||||
.map_err(|_| unsupported(mnemonic, "expected a forward branch"))?;
|
||||
offset
|
||||
@@ -657,11 +664,26 @@ fn vector_compare(
|
||||
bytes: &[u8],
|
||||
) -> Result<(Instruction, u8), DecodeErrorKind> {
|
||||
let src1 = ((first >> 9) & 0xff) as u8;
|
||||
let (src0, len) = vector_src0(first, bytes, op.assembly_name())?;
|
||||
let mnemonic = op.assembly_name();
|
||||
if op.semantics().width == 64 {
|
||||
// Guide §3.6.3 requires even SGPR bases. Reject invalid selectors
|
||||
// before reading a literal word or considering the execution mask.
|
||||
let source = first & 0x1ff;
|
||||
if src1 == 255
|
||||
|| !matches!(source, 0..=104 | 128..=208 | 256..=510)
|
||||
|| (source <= 104 && !source.is_multiple_of(2))
|
||||
{
|
||||
return Err(unsupported(mnemonic, "invalid 64-bit compare source"));
|
||||
}
|
||||
}
|
||||
if op.semantics().width == 16 && first & 0x1ff == 255 {
|
||||
return Err(unsupported(mnemonic, "literal in 16-bit compare"));
|
||||
}
|
||||
let (src0, len) = vector_src0(first, bytes, mnemonic)?;
|
||||
Ok((Instruction::VectorCompare { op, src0, src1 }, len))
|
||||
}
|
||||
|
||||
/// The 9-bit SRC0 of a VOPC or VOP2 word: a VGPR, `s0-s105`, `vcc_lo`, an
|
||||
/// The 9-bit SRC0 of a VOP1, VOP2 or VOPC word: a VGPR, `s0-s105`, `vcc_lo`, an
|
||||
/// inline integer -16..64 or a literal word; everything else is unsupported.
|
||||
fn vector_src0(
|
||||
first: u32,
|
||||
@@ -721,29 +743,37 @@ fn move_b32(first: u32, bytes: &[u8]) -> Result<(Instruction, u8), DecodeErrorKi
|
||||
Ok((Instruction::MoveB32 { dst, src }, len))
|
||||
}
|
||||
|
||||
/// Operand rule `vop3_vgpr2`: VDST in bits 0-7 of the first word, SRC0 and SRC1
|
||||
/// in bits 0-8 and 9-17 of the second (RDNA 2 ISA section 13.3.4, VOP3A). Both sources
|
||||
/// are VGPRs, ABS, OP_SEL, CLAMP, OMOD and NEG are clear, and the unused SRC2 is
|
||||
/// the gfx1030 assembler's inline-zero operand encoding.
|
||||
fn vop3_vgpr2(
|
||||
op: VectorAluVop3Op,
|
||||
first: u32,
|
||||
second: u32,
|
||||
) -> Result<Instruction, DecodeErrorKind> {
|
||||
let (src0, src1) = vop3_vgpr2_sources(op.assembly_name(), first, second)?;
|
||||
Ok(Instruction::VectorAluVop3 {
|
||||
op,
|
||||
dst: first as u8,
|
||||
src0,
|
||||
src1,
|
||||
})
|
||||
}
|
||||
|
||||
/// Common VOP3A source and modifier checks (RDNA 2 ISA section 13.3.4).
|
||||
/// SRC0 and SRC1 are VGPRs, the unused SRC2 is inline zero, and ABS, OP_SEL,
|
||||
/// CLAMP, OMOD and NEG are clear.
|
||||
fn vop3_vgpr2_sources(
|
||||
mnemonic: &'static str,
|
||||
first: u32,
|
||||
second: u32,
|
||||
) -> Result<(u8, u8), DecodeErrorKind> {
|
||||
let src0 = second & 0x1ff;
|
||||
let src1 = (second >> 9) & 0x1ff;
|
||||
if first & 0xff00 != 0 || second >> 18 != 128 || src0 < 256 || src1 < 256 {
|
||||
return Err(unsupported(
|
||||
op.assembly_name(),
|
||||
mnemonic,
|
||||
"expected two VGPR sources and no modifiers",
|
||||
));
|
||||
}
|
||||
Ok(Instruction::VectorAluVop3 {
|
||||
op,
|
||||
dst: first as u8,
|
||||
src0: src0 as u8,
|
||||
src1: src1 as u8,
|
||||
})
|
||||
Ok((src0 as u8, src1 as u8))
|
||||
}
|
||||
|
||||
fn scalar_form(
|
||||
|
||||
+338
-41
@@ -5,12 +5,12 @@ use std::process::{Command, Stdio};
|
||||
use xenora_decoder::{
|
||||
Architecture, CompareRelation, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction,
|
||||
ScalarAluOp, ScalarImmediateOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op,
|
||||
VectorSource, decode, decode_at,
|
||||
VectorCompareOp, VectorCompareVop3Op, VectorSource, VectorUnaryOp, decode, decode_at,
|
||||
};
|
||||
use xenora_isa::semantics::Signedness;
|
||||
use xenora_ref::{
|
||||
BranchCondition, CompareSource, Comparison, Op, ScalarAlu, ScalarImmediate, ScalarUnary,
|
||||
Source, VectorAlu, VectorInteger,
|
||||
BranchCondition, CompareSource, CompareWidth, Comparison, Op, ScalarAlu, ScalarImmediate,
|
||||
ScalarUnary, Source, VectorAlu, VectorInteger, VectorUnary,
|
||||
};
|
||||
|
||||
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin");
|
||||
@@ -71,6 +71,127 @@ fn decodes_each_fixture_instruction_with_offset_and_length() {
|
||||
assert_eq!(instructions, wanted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_wave32_vop3_compares_from_llvm_words() {
|
||||
use VectorCompareVop3Op::*;
|
||||
|
||||
// llvm-mc -triple=amdgcn -mcpu=gfx1030 -mattr=+wavefrontsize32 -show-encoding
|
||||
let cases: [(u32, VectorCompareVop3Op, u8); 19] = [
|
||||
// v_cmp_lt_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x81,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd481_0004, CmpLtI32, 4),
|
||||
// v_cmp_eq_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x82,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd482_0004, CmpEqI32, 4),
|
||||
// v_cmp_le_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x83,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd483_0004, CmpLeI32, 4),
|
||||
// v_cmp_gt_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x84,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd484_0004, CmpGtI32, 4),
|
||||
// v_cmp_ne_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x85,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd485_0004, CmpNeI32, 4),
|
||||
// v_cmp_ge_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x86,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd486_0004, CmpGeI32, 4),
|
||||
// v_cmp_lt_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc1,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c1_0004, CmpLtU32, 4),
|
||||
// v_cmp_eq_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc2,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c2_0004, CmpEqU32, 4),
|
||||
// v_cmp_le_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc3,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c3_0004, CmpLeU32, 4),
|
||||
// v_cmp_gt_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc4,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c4_0004, CmpGtU32, 4),
|
||||
// v_cmp_ne_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc5,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c5_0004, CmpNeU32, 4),
|
||||
// v_cmp_ge_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc6,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c6_0004, CmpGeU32, 4),
|
||||
// v_cmp_f_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x80,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd480_0004, CmpFI32, 4),
|
||||
// v_cmp_t_i32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0x87,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd487_0004, CmpTI32, 4),
|
||||
// v_cmp_f_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc0,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c0_0004, CmpFU32, 4),
|
||||
// v_cmp_t_u32_e64 s4, v1, v2 ; encoding: [0x04,0x00,0xc7,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c7_0004, CmpTU32, 4),
|
||||
// v_cmp_eq_u32_e64 s0, v1, v2 ; encoding: [0x00,0x00,0xc2,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c2_0000, CmpEqU32, 0),
|
||||
// v_cmp_eq_u32_e64 s105, v1, v2 ; encoding: [0x69,0x00,0xc2,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c2_0069, CmpEqU32, 105),
|
||||
// v_cmp_eq_u32_e64 vcc_lo, v1, v2 ; encoding: [0x6a,0x00,0xc2,0xd4,0x01,0x05,0x02,0x02]
|
||||
(0xd4c2_006a, CmpEqU32, 106),
|
||||
];
|
||||
for (first, op, sdst) in cases {
|
||||
let code: Vec<_> = [first, 0x0202_0501]
|
||||
.into_iter()
|
||||
.flat_map(u32::to_le_bytes)
|
||||
.collect();
|
||||
let decoded = decode(Architecture::Gfx1030, &code).unwrap();
|
||||
let dst = if sdst == 106 {
|
||||
"vcc_lo".to_owned()
|
||||
} else {
|
||||
format!("s{sdst}")
|
||||
};
|
||||
assert_eq!(
|
||||
decoded,
|
||||
[DecodedInstruction {
|
||||
offset: 0,
|
||||
byte_len: 8,
|
||||
instruction: Instruction::VectorCompareVop3 {
|
||||
op,
|
||||
sdst,
|
||||
src0: 1,
|
||||
src1: 2
|
||||
},
|
||||
}],
|
||||
);
|
||||
assert_eq!(
|
||||
decoded[0].instruction.to_string(),
|
||||
format!("{} {dst}, v1, v2", op.assembly_name())
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_noncanonical_wave32_vop3_compare_operands() {
|
||||
// v_cmp_eq_u32_e64 s4, v1, v2
|
||||
let first = 0xd4c2_0004;
|
||||
let second = 0x0202_0501;
|
||||
let rejects = |first, second| {
|
||||
let code: Vec<_> = [first, second]
|
||||
.into_iter()
|
||||
.flat_map(u32::to_le_bytes)
|
||||
.collect();
|
||||
let error = decode(Architecture::Gfx1030, &code).unwrap_err();
|
||||
assert_eq!(error.offset, 0);
|
||||
assert!(
|
||||
matches!(
|
||||
error.kind,
|
||||
DecodeErrorKind::UnsupportedForm {
|
||||
mnemonic: "v_cmp_eq_u32_e64",
|
||||
..
|
||||
}
|
||||
),
|
||||
"{first:#010x} {second:#010x}: {error}"
|
||||
);
|
||||
};
|
||||
|
||||
// Includes vcc_hi (107), TTMPs (108-123), null (124), m0 (125) and EXEC (126-127).
|
||||
for sdst in 107..=255 {
|
||||
rejects((first & !0xff) | sdst, second);
|
||||
}
|
||||
for bit in 8..=15 {
|
||||
// ABS, OP_SEL and CLAMP.
|
||||
rejects(first | (1 << bit), second);
|
||||
}
|
||||
for bit in 27..=31 {
|
||||
// OMOD and NEG.
|
||||
rejects(first, second | (1 << bit));
|
||||
}
|
||||
rejects(first, second ^ (1 << 18)); // SRC2 = 129 instead of 128.
|
||||
for shift in [0, 9] {
|
||||
for selector in [4, 106, 128, 240, 255] {
|
||||
// SGPR, VCC_LO, inline integer/float, literal.
|
||||
rejects(first, (second & !(0x1ff << shift)) | (selector << shift));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_non_boundary_prefix_reports_the_incomplete_instruction() {
|
||||
let lengths = [8, 4, 8, 8, 8, 4, 4];
|
||||
@@ -303,6 +424,44 @@ fn reference_scalar(scalar: ScalarSource) -> Source {
|
||||
}
|
||||
}
|
||||
|
||||
fn reference_comparison(op: VectorCompareOp) -> Comparison {
|
||||
Comparison {
|
||||
offset: match op.relation() {
|
||||
CompareRelation::Less => 1,
|
||||
CompareRelation::Equal => 2,
|
||||
CompareRelation::LessOrEqual => 3,
|
||||
CompareRelation::Greater => 4,
|
||||
CompareRelation::NotEqual => 5,
|
||||
CompareRelation::GreaterOrEqual => 6,
|
||||
CompareRelation::False => 0,
|
||||
CompareRelation::True => 7,
|
||||
},
|
||||
signed: op.signed(),
|
||||
}
|
||||
}
|
||||
|
||||
fn reference_vector_integer(op: VectorAluOp) -> VectorInteger {
|
||||
match op {
|
||||
VectorAluOp::CndmaskB32 => VectorInteger::Select,
|
||||
VectorAluOp::AddCoCiU32 => VectorInteger::AddCarry,
|
||||
VectorAluOp::SubCoCiU32 => VectorInteger::SubtractBorrow { reversed: false },
|
||||
VectorAluOp::SubrevCoCiU32 => VectorInteger::SubtractBorrow { reversed: true },
|
||||
VectorAluOp::MulI32I24 => VectorInteger::Multiply24 { signed: true },
|
||||
VectorAluOp::MulHiI32I24 => VectorInteger::MultiplyHigh24 { signed: true },
|
||||
VectorAluOp::MulU32U24 => VectorInteger::Multiply24 { signed: false },
|
||||
VectorAluOp::MulHiU32U24 => VectorInteger::MultiplyHigh24 { signed: false },
|
||||
VectorAluOp::MinI32 => VectorInteger::Minimum { signed: true },
|
||||
VectorAluOp::MaxI32 => VectorInteger::Maximum { signed: true },
|
||||
VectorAluOp::MinU32 => VectorInteger::Minimum { signed: false },
|
||||
VectorAluOp::MaxU32 => VectorInteger::Maximum { signed: false },
|
||||
VectorAluOp::XnorB32 => VectorInteger::Xnor,
|
||||
VectorAluOp::AddNcU32 => VectorInteger::Add,
|
||||
VectorAluOp::SubNcU32 => VectorInteger::Subtract,
|
||||
VectorAluOp::SubrevNcU32 => VectorInteger::SubtractReverse,
|
||||
_ => panic!("{op:?} decodes only with a VGPR SRC0 (operand rule vop2_vgpr2)"),
|
||||
}
|
||||
}
|
||||
|
||||
fn reference_op(instruction: Instruction) -> Op {
|
||||
match instruction {
|
||||
Instruction::BufferLoadDword {
|
||||
@@ -330,6 +489,22 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
src: VectorSource::Scalar(src),
|
||||
} => Op::MoveScalar(dst, src),
|
||||
Instruction::MoveB32 { dst, src } => Op::Move(dst, reference_source(src)),
|
||||
Instruction::VectorUnary { op, dst, src } => Op::VectorUnary(
|
||||
match op {
|
||||
VectorUnaryOp::NotB32 => VectorUnary::Not,
|
||||
VectorUnaryOp::BfrevB32 => VectorUnary::ReverseBits,
|
||||
VectorUnaryOp::FfbhU32 => VectorUnary::FindFirstOneFromMsb,
|
||||
VectorUnaryOp::FfblB32 => VectorUnary::FindFirstOneFromLsb,
|
||||
VectorUnaryOp::FfbhI32 => VectorUnary::FindSignChange,
|
||||
},
|
||||
dst,
|
||||
match src {
|
||||
VectorSource::Register(reg) => CompareSource::Vector(reg),
|
||||
VectorSource::Scalar(reg) => CompareSource::Scalar(reg),
|
||||
VectorSource::Immediate(bits) => CompareSource::Immediate(bits),
|
||||
},
|
||||
),
|
||||
Instruction::VectorSwap { dst, src, .. } => Op::Swap(dst, src),
|
||||
Instruction::ScalarAlu {
|
||||
op,
|
||||
dst,
|
||||
@@ -375,13 +550,23 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
reference_scalar(src0),
|
||||
reference_scalar(src1),
|
||||
),
|
||||
// The reference's VOP3 add; it is the only VOP3 variant so far.
|
||||
Instruction::VectorAluVop3 {
|
||||
op: VectorAluVop3Op::AddNcU32,
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
} => Op::Add(dst, src0, src1),
|
||||
Instruction::VectorAluVop3 {
|
||||
op,
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
} => Op::VectorInteger(
|
||||
reference_vector_integer(op.base()),
|
||||
dst,
|
||||
CompareSource::Vector(src0),
|
||||
src1,
|
||||
),
|
||||
Instruction::ScalarUnary { op, dst, src } => {
|
||||
let src = reference_scalar(src);
|
||||
let unary = match op {
|
||||
@@ -489,25 +674,29 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
panic!("compute reference matrix received a graphics/image instruction")
|
||||
}
|
||||
|
||||
Instruction::VectorCompare { op, src0, src1 } => Op::Compare(
|
||||
Comparison {
|
||||
offset: match op.relation() {
|
||||
CompareRelation::Less => 1,
|
||||
CompareRelation::Equal => 2,
|
||||
CompareRelation::LessOrEqual => 3,
|
||||
CompareRelation::Greater => 4,
|
||||
CompareRelation::NotEqual => 5,
|
||||
CompareRelation::GreaterOrEqual => 6,
|
||||
CompareRelation::False => 0,
|
||||
CompareRelation::True => 7,
|
||||
},
|
||||
signed: op.signed(),
|
||||
},
|
||||
match src0 {
|
||||
Instruction::VectorCompare { op, src0, src1 } => {
|
||||
let comparison = reference_comparison(op);
|
||||
let src0 = match src0 {
|
||||
VectorSource::Register(reg) => CompareSource::Vector(reg),
|
||||
VectorSource::Scalar(reg) => CompareSource::Scalar(reg),
|
||||
VectorSource::Immediate(bits) => CompareSource::Immediate(bits),
|
||||
},
|
||||
};
|
||||
match op.semantics().width {
|
||||
16 => Op::WideCompare(comparison, CompareWidth::Half, src0, src1),
|
||||
32 => Op::Compare(comparison, src0, src1),
|
||||
64 => Op::WideCompare(comparison, CompareWidth::Double, src0, src1),
|
||||
width => panic!("unexpected VOPC operand width {width}"),
|
||||
}
|
||||
}
|
||||
Instruction::VectorCompareVop3 {
|
||||
op,
|
||||
sdst,
|
||||
src0,
|
||||
src1,
|
||||
} => Op::CompareVop3(
|
||||
sdst,
|
||||
reference_comparison(op.base()),
|
||||
CompareSource::Vector(src0),
|
||||
src1,
|
||||
),
|
||||
Instruction::VectorAlu {
|
||||
@@ -516,21 +705,7 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
src0,
|
||||
src1,
|
||||
} => Op::VectorInteger(
|
||||
match op {
|
||||
VectorAluOp::MulI32I24 => VectorInteger::Multiply24 { signed: true },
|
||||
VectorAluOp::MulHiI32I24 => VectorInteger::MultiplyHigh24 { signed: true },
|
||||
VectorAluOp::MulU32U24 => VectorInteger::Multiply24 { signed: false },
|
||||
VectorAluOp::MulHiU32U24 => VectorInteger::MultiplyHigh24 { signed: false },
|
||||
VectorAluOp::MinI32 => VectorInteger::Minimum { signed: true },
|
||||
VectorAluOp::MaxI32 => VectorInteger::Maximum { signed: true },
|
||||
VectorAluOp::MinU32 => VectorInteger::Minimum { signed: false },
|
||||
VectorAluOp::MaxU32 => VectorInteger::Maximum { signed: false },
|
||||
VectorAluOp::XnorB32 => VectorInteger::Xnor,
|
||||
VectorAluOp::AddNcU32 => VectorInteger::Add,
|
||||
VectorAluOp::SubNcU32 => VectorInteger::Subtract,
|
||||
VectorAluOp::SubrevNcU32 => VectorInteger::SubtractReverse,
|
||||
_ => panic!("{op:?} decodes only with a VGPR SRC0 (operand rule vop2_vgpr2)"),
|
||||
},
|
||||
reference_vector_integer(op),
|
||||
dst,
|
||||
match src0 {
|
||||
VectorSource::Register(reg) => CompareSource::Vector(reg),
|
||||
@@ -566,14 +741,19 @@ fn compares_fixture_instructions_against_llvm() {
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-arith.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-immediate.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-integer.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-vcc.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-compare.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-compare-ft.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-unary.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-compare-16.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vop3-integer.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vop3-compare.bin"),
|
||||
high_registers,
|
||||
&matrix,
|
||||
] {
|
||||
count += compare_against_llvm(fixture, &mut forms);
|
||||
}
|
||||
assert_eq!(forms.len(), 120, "forms compared: {forms:?}");
|
||||
assert_eq!(forms.len(), 169, "forms compared: {forms:?}");
|
||||
eprintln!(
|
||||
"{count} three-way instruction comparisons across {} forms",
|
||||
forms.len()
|
||||
@@ -801,7 +981,7 @@ fn distinguishes_llvm_invalid_encodings_from_xenora_subset_rejections() {
|
||||
let outside_subset: &[&[u32]] = &[
|
||||
&[0x7e04_026b], // VOP1 VCC_HI source
|
||||
&[0x7da2_0501], // v_cmpx_eq_u32_e32
|
||||
&[0xd482_006a, 0x0002_0501], // v_cmp_lt_i32_e64
|
||||
&[0xd482_006a, 0x0002_0501], // v_cmp_eq_i32_e64 with SRC2 = 0
|
||||
&[0x8788_0908], // s_and_b64
|
||||
&[0x8008_ffff, 0x1234_5678], // SOP2 with two literal sources
|
||||
&[0x806c_0908], // SOP2 TTMP destination
|
||||
@@ -870,7 +1050,7 @@ fn normalize_llvm_assembly(assembly: &str, next_offset: usize) -> String {
|
||||
let target = next_offset + displacement * 4;
|
||||
format!("{mnemonic} -> 0x{target:04x}")
|
||||
}
|
||||
// VOPC and the registry VOP2 forms print SRC0 (the second operand) as bits.
|
||||
// VOPC and registry VOP2 forms print SRC0 as bits.
|
||||
mnemonic
|
||||
if mnemonic.starts_with("v_cmp_")
|
||||
|| VectorAluOp::ALL
|
||||
@@ -878,10 +1058,11 @@ fn normalize_llvm_assembly(assembly: &str, next_offset: usize) -> String {
|
||||
.any(|op| op.assembly_name() == mnemonic) =>
|
||||
{
|
||||
let mut parts: Vec<String> = operands.split(", ").map(str::to_owned).collect();
|
||||
parts[1] = match literal_bits(&parts[1]) {
|
||||
let src = if parts.len() == 5 { 2 } else { 1 };
|
||||
parts[src] = match literal_bits(&parts[src]) {
|
||||
Some(bits) => format!("0x{bits:x}"),
|
||||
None => parts[1].parse::<i32>().map_or_else(
|
||||
|_| parts[1].clone(),
|
||||
None => parts[src].parse::<i32>().map_or_else(
|
||||
|_| parts[src].clone(),
|
||||
|value| format!("0x{:x}", value as u32),
|
||||
),
|
||||
};
|
||||
@@ -1090,6 +1271,122 @@ fn decode_at_resolves_branch_targets_from_the_stream_offset() {
|
||||
);
|
||||
}
|
||||
|
||||
// llvm-mc -triple=amdgcn -mcpu=gfx1030 -show-encoding
|
||||
const VOP3_INTEGER_ENCODINGS: [(VectorAluVop3Op, u32); 11] = [
|
||||
// v_mul_i32_i24_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x09,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MulI32I24, 0xd50900ff),
|
||||
// v_mul_hi_i32_i24_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x0a,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MulHiI32I24, 0xd50a00ff),
|
||||
// v_mul_u32_u24_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x0b,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MulU32U24, 0xd50b00ff),
|
||||
// v_mul_hi_u32_u24_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x0c,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MulHiU32U24, 0xd50c00ff),
|
||||
// v_min_i32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x11,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MinI32, 0xd51100ff),
|
||||
// v_max_i32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x12,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MaxI32, 0xd51200ff),
|
||||
// v_min_u32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x13,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MinU32, 0xd51300ff),
|
||||
// v_max_u32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x14,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::MaxU32, 0xd51400ff),
|
||||
// v_xnor_b32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x1e,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::XnorB32, 0xd51e00ff),
|
||||
// v_sub_nc_u32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x26,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::SubNcU32, 0xd52600ff),
|
||||
// v_subrev_nc_u32_e64 v255, v0, v127 ; encoding: [0xff,0x00,0x27,0xd5,0x00,0xff,0x02,0x02]
|
||||
(VectorAluVop3Op::SubrevNcU32, 0xd52700ff),
|
||||
];
|
||||
const VOP3_INTEGER_SOURCE_WORD: u32 = 0x0202_ff00;
|
||||
|
||||
#[test]
|
||||
fn decodes_registry_vop3_integer_encodings() {
|
||||
for (op, first) in VOP3_INTEGER_ENCODINGS {
|
||||
let bytes = [first.to_le_bytes(), VOP3_INTEGER_SOURCE_WORD.to_le_bytes()].concat();
|
||||
let decoded = decode(Architecture::Gfx1030, &bytes).unwrap();
|
||||
assert_eq!(decoded.len(), 1);
|
||||
assert_eq!(decoded[0].byte_len, 8);
|
||||
assert_eq!(
|
||||
decoded[0].instruction,
|
||||
Instruction::VectorAluVop3 {
|
||||
op,
|
||||
dst: 255,
|
||||
src0: 0,
|
||||
src1: 127,
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_vop3_integer_fixture() {
|
||||
use VectorAluVop3Op::*;
|
||||
|
||||
let code = include_bytes!("../../../fixtures/rdna2/vop3-integer.bin");
|
||||
let decoded = decode(Architecture::Gfx1030, code).unwrap();
|
||||
let expected = [
|
||||
(MulI32I24, 2, 1, 1),
|
||||
(MulHiI32I24, 3, 2, 1),
|
||||
(MulU32U24, 4, 2, 1),
|
||||
(MulHiU32U24, 255, 4, 1),
|
||||
(MinI32, 6, 1, 2),
|
||||
(MaxI32, 7, 1, 4),
|
||||
(MinU32, 8, 3, 1),
|
||||
(MaxU32, 9, 255, 2),
|
||||
(XnorB32, 10, 1, 255),
|
||||
(SubNcU32, 11, 6, 10),
|
||||
(SubrevNcU32, 1, 1, 9),
|
||||
];
|
||||
let actual: Vec<_> = decoded
|
||||
.iter()
|
||||
.filter_map(|decoded| match decoded.instruction {
|
||||
Instruction::VectorAluVop3 {
|
||||
op,
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
} => Some((decoded.offset, decoded.byte_len, op, dst, src0, src1)),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let expected: Vec<_> = expected
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, (op, dst, src0, src1))| (12 + 8 * index, 8, op, dst, src0, src1))
|
||||
.collect();
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_registry_vop3_integer_modifiers_and_other_sources() {
|
||||
for (op, first) in VOP3_INTEGER_ENCODINGS {
|
||||
let second = VOP3_INTEGER_SOURCE_WORD;
|
||||
let reject = |first: u32, second: u32| {
|
||||
let bytes = [first.to_le_bytes(), second.to_le_bytes()].concat();
|
||||
let error = decode(Architecture::Gfx1030, &bytes)
|
||||
.expect_err(&format!("{op:?} accepted {first:#010x} {second:#010x}"));
|
||||
assert_eq!(error.offset, 0);
|
||||
assert!(matches!(
|
||||
error.kind,
|
||||
DecodeErrorKind::UnsupportedForm { mnemonic, .. }
|
||||
if mnemonic == op.assembly_name()
|
||||
));
|
||||
};
|
||||
|
||||
// First word: ABS[10:8], OP_SEL[14:11], CLAMP[15].
|
||||
for bit in 8..=15 {
|
||||
reject(first | (1 << bit), second);
|
||||
}
|
||||
// Second word: OMOD[28:27], NEG[31:29].
|
||||
for bit in 27..=31 {
|
||||
reject(first, second | (1 << bit));
|
||||
}
|
||||
|
||||
reject(first, second & !0x1ff); // SRC0 = s0
|
||||
reject(first, (second & !(0x1ff << 9)) | (128 << 9)); // SRC1 = inline zero
|
||||
reject(first, second | (1 << 18)); // SRC2 = inline one
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_sopk_immediates_and_rejects_non_sgpr_operands() {
|
||||
use xenora_decoder::ScalarImmediateCompareOp;
|
||||
|
||||
@@ -0,0 +1,529 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Decoding of Microsoft Visual C++ decorated names, for diagnostics.
|
||||
//!
|
||||
//! Written from the publicly described decoration scheme: a leading `?`,
|
||||
//! `@`-terminated name fragments listed innermost first, single-digit name and
|
||||
//! type back-references, an access and storage code, a calling convention,
|
||||
//! the return type and the parameter list. Output follows the style of
|
||||
//! Microsoft's `undname` tool. Anything outside the supported subset returns
|
||||
//! `None` instead of a guess, so callers fall back to the decorated name.
|
||||
|
||||
const MAX_DEPTH: usize = 16;
|
||||
|
||||
/// The undecorated form of `symbol`, or `None` when it is not a decorated
|
||||
/// C++ name or uses an unsupported construct.
|
||||
pub fn demangle(symbol: &str) -> Option<String> {
|
||||
let mut parser = Parser {
|
||||
input: symbol.as_bytes(),
|
||||
position: 0,
|
||||
names: Vec::new(),
|
||||
types: Vec::new(),
|
||||
depth: 0,
|
||||
};
|
||||
let result = parser.symbol()?;
|
||||
(parser.position == parser.input.len()).then_some(result)
|
||||
}
|
||||
|
||||
/// A special name introduced by `?` and a code inside the qualified name.
|
||||
enum Special {
|
||||
Constructor,
|
||||
Destructor,
|
||||
Operator(&'static str),
|
||||
Vftable,
|
||||
}
|
||||
|
||||
struct Parser<'a> {
|
||||
input: &'a [u8],
|
||||
position: usize,
|
||||
names: Vec<String>,
|
||||
types: Vec<String>,
|
||||
depth: usize,
|
||||
}
|
||||
|
||||
impl Parser<'_> {
|
||||
fn peek(&self) -> Option<u8> {
|
||||
self.input.get(self.position).copied()
|
||||
}
|
||||
|
||||
fn next(&mut self) -> Option<u8> {
|
||||
let byte = self.peek()?;
|
||||
self.position += 1;
|
||||
Some(byte)
|
||||
}
|
||||
|
||||
fn eat(&mut self, byte: u8) -> bool {
|
||||
let found = self.peek() == Some(byte);
|
||||
if found {
|
||||
self.position += 1;
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
fn eat_str(&mut self, text: &str) -> bool {
|
||||
let found = self.input[self.position..].starts_with(text.as_bytes());
|
||||
if found {
|
||||
self.position += text.len();
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
fn symbol(&mut self) -> Option<String> {
|
||||
if !self.eat(b'?') {
|
||||
return None;
|
||||
}
|
||||
let (name, special) = self.qualified_name(true)?;
|
||||
match self.peek()? {
|
||||
b'0'..=b'4' => self.variable(&name),
|
||||
b'6' => {
|
||||
self.next();
|
||||
let qualifier = cv(self.next()?)?;
|
||||
self.eat(b'@');
|
||||
if !matches!(special, Some(Special::Vftable)) {
|
||||
return None;
|
||||
}
|
||||
Some(format!("{} {name}", qualifier.trim()))
|
||||
}
|
||||
_ => self.function(&name, special.as_ref()),
|
||||
}
|
||||
}
|
||||
|
||||
fn variable(&mut self, name: &str) -> Option<String> {
|
||||
let access = match self.next()? {
|
||||
b'0' => "private: static ",
|
||||
b'1' => "protected: static ",
|
||||
b'2' => "public: static ",
|
||||
_ => "",
|
||||
};
|
||||
let kind = self.data_type()?;
|
||||
self.eat(b'E');
|
||||
let qualifier = cv(self.next()?)?;
|
||||
Some(format!("{access}{kind}{qualifier} {name}"))
|
||||
}
|
||||
|
||||
fn function(&mut self, name: &str, special: Option<&Special>) -> Option<String> {
|
||||
let (access, member) = match self.next()? {
|
||||
b'A' | b'B' => ("private: ", true),
|
||||
b'C' | b'D' => ("private: static ", false),
|
||||
b'E' | b'F' => ("private: virtual ", true),
|
||||
b'I' | b'J' => ("protected: ", true),
|
||||
b'K' | b'L' => ("protected: static ", false),
|
||||
b'M' | b'N' => ("protected: virtual ", true),
|
||||
b'Q' | b'R' => ("public: ", true),
|
||||
b'S' | b'T' => ("public: static ", false),
|
||||
b'U' | b'V' => ("public: virtual ", true),
|
||||
b'Y' | b'Z' => ("", false),
|
||||
_ => return None,
|
||||
};
|
||||
let mut this = String::new();
|
||||
if member {
|
||||
let pointer64 = self.eat(b'E');
|
||||
this.push_str(cv(self.next()?)?.trim_start());
|
||||
if pointer64 {
|
||||
this.push_str(" __ptr64");
|
||||
}
|
||||
}
|
||||
let convention = match self.next()? {
|
||||
b'A' | b'B' => "__cdecl",
|
||||
b'C' | b'D' => "__pascal",
|
||||
b'E' | b'F' => "__thiscall",
|
||||
b'G' | b'H' => "__stdcall",
|
||||
b'I' | b'J' => "__fastcall",
|
||||
b'Q' => "__vectorcall",
|
||||
_ => return None,
|
||||
};
|
||||
let returns = if self.eat(b'@') {
|
||||
if !matches!(special, Some(Special::Constructor | Special::Destructor)) {
|
||||
return None;
|
||||
}
|
||||
String::new()
|
||||
} else {
|
||||
if self.eat(b'?') {
|
||||
cv(self.next()?)?;
|
||||
}
|
||||
format!("{} ", self.data_type()?)
|
||||
};
|
||||
let parameters = self.parameters()?;
|
||||
if !self.eat(b'Z') {
|
||||
return None;
|
||||
}
|
||||
Some(format!(
|
||||
"{access}{returns}{convention} {name}({parameters}){this}"
|
||||
))
|
||||
}
|
||||
|
||||
fn parameters(&mut self) -> Option<String> {
|
||||
if self.eat(b'X') {
|
||||
return Some("void".to_owned());
|
||||
}
|
||||
let mut parameters = Vec::new();
|
||||
loop {
|
||||
match self.peek()? {
|
||||
b'@' => {
|
||||
self.next();
|
||||
break;
|
||||
}
|
||||
b'Z' => {
|
||||
self.next();
|
||||
parameters.push("...".to_owned());
|
||||
break;
|
||||
}
|
||||
_ => {
|
||||
let start = self.position;
|
||||
let kind = self.data_type()?;
|
||||
if self.position - start > 1 && self.types.len() < 10 {
|
||||
self.types.push(kind.clone());
|
||||
}
|
||||
parameters.push(kind);
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(parameters.join(","))
|
||||
}
|
||||
|
||||
/// Fragments up to `@`, joined outermost first.
|
||||
fn qualified_name(&mut self, allow_special: bool) -> Option<(String, Option<Special>)> {
|
||||
let mut special = None;
|
||||
let mut fragments = Vec::new();
|
||||
if allow_special
|
||||
&& self.peek() == Some(b'?')
|
||||
&& self.input.get(self.position + 1) != Some(&b'$')
|
||||
{
|
||||
self.next();
|
||||
special = Some(self.special()?);
|
||||
} else {
|
||||
fragments.push(self.fragment()?);
|
||||
}
|
||||
while !self.eat(b'@') {
|
||||
fragments.push(self.fragment()?);
|
||||
}
|
||||
fragments.reverse();
|
||||
let scope = fragments.join("::");
|
||||
let name = match &special {
|
||||
None => scope,
|
||||
Some(special) => {
|
||||
let class = || Some(fragments.last()?.split('<').next()?.to_owned());
|
||||
let leaf = match special {
|
||||
Special::Constructor => class()?,
|
||||
Special::Destructor => format!("~{}", class()?),
|
||||
Special::Operator(name) => name.to_string(),
|
||||
Special::Vftable => "`vftable'".to_owned(),
|
||||
};
|
||||
if scope.is_empty() {
|
||||
leaf
|
||||
} else {
|
||||
format!("{scope}::{leaf}")
|
||||
}
|
||||
}
|
||||
};
|
||||
Some((name, special))
|
||||
}
|
||||
|
||||
fn special(&mut self) -> Option<Special> {
|
||||
Some(match self.next()? {
|
||||
b'0' => Special::Constructor,
|
||||
b'1' => Special::Destructor,
|
||||
b'2' => Special::Operator("operator new"),
|
||||
b'3' => Special::Operator("operator delete"),
|
||||
b'4' => Special::Operator("operator="),
|
||||
b'8' => Special::Operator("operator=="),
|
||||
b'9' => Special::Operator("operator!="),
|
||||
b'A' => Special::Operator("operator[]"),
|
||||
b'R' => Special::Operator("operator()"),
|
||||
b'_' => match self.next()? {
|
||||
b'7' => Special::Vftable,
|
||||
b'U' => Special::Operator("operator new[]"),
|
||||
b'V' => Special::Operator("operator delete[]"),
|
||||
_ => return None,
|
||||
},
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn fragment(&mut self) -> Option<String> {
|
||||
if let Some(digit @ b'0'..=b'9') = self.peek() {
|
||||
self.next();
|
||||
return self.names.get(usize::from(digit - b'0')).cloned();
|
||||
}
|
||||
let fragment = if self.eat_str("?$") {
|
||||
self.template()?
|
||||
} else {
|
||||
self.identifier()?
|
||||
};
|
||||
if self.names.len() < 10 && !self.names.contains(&fragment) {
|
||||
self.names.push(fragment.clone());
|
||||
}
|
||||
Some(fragment)
|
||||
}
|
||||
|
||||
fn identifier(&mut self) -> Option<String> {
|
||||
let start = self.position;
|
||||
while self.peek()? != b'@' {
|
||||
let byte = self.next()?;
|
||||
if !(byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'$') {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
let text = std::str::from_utf8(&self.input[start..self.position]).ok()?;
|
||||
self.next();
|
||||
(!text.is_empty()).then(|| text.to_owned())
|
||||
}
|
||||
|
||||
/// `name@arguments@`, with back-references local to the argument list.
|
||||
fn template(&mut self) -> Option<String> {
|
||||
self.depth += 1;
|
||||
if self.depth > MAX_DEPTH {
|
||||
return None;
|
||||
}
|
||||
let outer_names = std::mem::take(&mut self.names);
|
||||
let outer_types = std::mem::take(&mut self.types);
|
||||
let name = self.identifier();
|
||||
if let Some(name) = &name {
|
||||
self.names.push(name.clone());
|
||||
}
|
||||
let mut arguments = Vec::new();
|
||||
let result = (|| {
|
||||
let name = name?;
|
||||
while !self.eat(b'@') {
|
||||
let start = self.position;
|
||||
let argument = if self.eat(b'$') {
|
||||
if !self.eat(b'0') {
|
||||
return None;
|
||||
}
|
||||
self.number()?.to_string()
|
||||
} else {
|
||||
self.data_type()?
|
||||
};
|
||||
if self.position - start > 1 && self.types.len() < 10 {
|
||||
self.types.push(argument.clone());
|
||||
}
|
||||
arguments.push(argument);
|
||||
}
|
||||
let joined = arguments.join(",");
|
||||
let close = if joined.ends_with('>') { " >" } else { ">" };
|
||||
Some(format!("{name}<{joined}{close}"))
|
||||
})();
|
||||
self.names = outer_names;
|
||||
self.types = outer_types;
|
||||
self.depth -= 1;
|
||||
result
|
||||
}
|
||||
|
||||
/// `0`–`9` encode 1–10; otherwise hexadecimal digits `A`–`P` end with `@`.
|
||||
fn number(&mut self) -> Option<i64> {
|
||||
let negative = self.eat(b'?');
|
||||
let value = match self.next()? {
|
||||
digit @ b'0'..=b'9' => i64::from(digit - b'0') + 1,
|
||||
b'@' => 0,
|
||||
mut digit => {
|
||||
let mut value: i64 = 0;
|
||||
loop {
|
||||
if !(b'A'..=b'P').contains(&digit) {
|
||||
return None;
|
||||
}
|
||||
value = value
|
||||
.checked_mul(16)?
|
||||
.checked_add(i64::from(digit - b'A'))?;
|
||||
digit = self.next()?;
|
||||
if digit == b'@' {
|
||||
break value;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
Some(if negative { -value } else { value })
|
||||
}
|
||||
|
||||
fn data_type(&mut self) -> Option<String> {
|
||||
self.depth += 1;
|
||||
if self.depth > MAX_DEPTH {
|
||||
return None;
|
||||
}
|
||||
let result = self.data_type_inner();
|
||||
self.depth -= 1;
|
||||
result
|
||||
}
|
||||
|
||||
fn data_type_inner(&mut self) -> Option<String> {
|
||||
let code = self.next()?;
|
||||
let primitive = match code {
|
||||
b'X' => "void",
|
||||
b'C' => "signed char",
|
||||
b'D' => "char",
|
||||
b'E' => "unsigned char",
|
||||
b'F' => "short",
|
||||
b'G' => "unsigned short",
|
||||
b'H' => "int",
|
||||
b'I' => "unsigned int",
|
||||
b'J' => "long",
|
||||
b'K' => "unsigned long",
|
||||
b'M' => "float",
|
||||
b'N' => "double",
|
||||
b'O' => "long double",
|
||||
b'0'..=b'9' => return self.types.get(usize::from(code - b'0')).cloned(),
|
||||
b'_' => match self.next()? {
|
||||
b'J' => "__int64",
|
||||
b'K' => "unsigned __int64",
|
||||
b'N' => "bool",
|
||||
b'W' => "wchar_t",
|
||||
b'S' => "char16_t",
|
||||
b'U' => "char32_t",
|
||||
b'Q' => "char8_t",
|
||||
_ => return None,
|
||||
},
|
||||
b'V' => return Some(format!("class {}", self.qualified_name(false)?.0)),
|
||||
b'U' => return Some(format!("struct {}", self.qualified_name(false)?.0)),
|
||||
b'T' => return Some(format!("union {}", self.qualified_name(false)?.0)),
|
||||
b'W' => {
|
||||
if !self.eat(b'4') {
|
||||
return None;
|
||||
}
|
||||
return Some(format!("enum {}", self.qualified_name(false)?.0));
|
||||
}
|
||||
b'P' | b'Q' | b'R' | b'S' => return self.indirection("*", pointer_cv(code)),
|
||||
b'A' => return self.indirection("&", ""),
|
||||
b'B' => return self.indirection("&", " volatile"),
|
||||
b'$' => {
|
||||
if self.eat_str("$Q") {
|
||||
return self.indirection("&&", "");
|
||||
}
|
||||
if self.eat_str("$T") {
|
||||
return Some("std::nullptr_t".to_owned());
|
||||
}
|
||||
return None;
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
Some(primitive.to_owned())
|
||||
}
|
||||
|
||||
/// A pointer or reference: an optional `E` for `__ptr64`, the pointee's
|
||||
/// qualifiers, then the pointee.
|
||||
fn indirection(&mut self, symbol: &str, own: &str) -> Option<String> {
|
||||
let pointer64 = self.eat(b'E');
|
||||
let pointee_cv = cv(self.next()?)?;
|
||||
let pointee = self.data_type()?;
|
||||
let width = if pointer64 { " __ptr64" } else { "" };
|
||||
Some(format!("{pointee}{pointee_cv} {symbol}{own}{width}"))
|
||||
}
|
||||
}
|
||||
|
||||
fn cv(code: u8) -> Option<&'static str> {
|
||||
Some(match code {
|
||||
b'A' => "",
|
||||
b'B' => " const",
|
||||
b'C' => " volatile",
|
||||
b'D' => " const volatile",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn pointer_cv(code: u8) -> &'static str {
|
||||
match code {
|
||||
b'Q' => " const",
|
||||
b'R' => " volatile",
|
||||
b'S' => " const volatile",
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::demangle;
|
||||
|
||||
#[test]
|
||||
fn decodes_global_functions_and_operators() {
|
||||
for (decorated, expected) in [
|
||||
("?foo@@YAXXZ", "void __cdecl foo(void)"),
|
||||
("?foo@@YAHH@Z", "int __cdecl foo(int)"),
|
||||
("?f@@YAXPEBD@Z", "void __cdecl f(char const * __ptr64)"),
|
||||
("?f@@YAXHZZ", "void __cdecl f(int,...)"),
|
||||
(
|
||||
"??2@YAPEAX_K@Z",
|
||||
"void * __ptr64 __cdecl operator new(unsigned __int64)",
|
||||
),
|
||||
(
|
||||
"??3@YAXPEAX@Z",
|
||||
"void __cdecl operator delete(void * __ptr64)",
|
||||
),
|
||||
(
|
||||
"??_U@YAPEAX_K@Z",
|
||||
"void * __ptr64 __cdecl operator new[](unsigned __int64)",
|
||||
),
|
||||
(
|
||||
"?_Xlength_error@std@@YAXPEBD@Z",
|
||||
"void __cdecl std::_Xlength_error(char const * __ptr64)",
|
||||
),
|
||||
("?g@@YA_N_J0@Z", "bool __cdecl g(__int64,__int64)"),
|
||||
] {
|
||||
assert_eq!(
|
||||
demangle(decorated).as_deref(),
|
||||
Some(expected),
|
||||
"{decorated}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_members_constructors_and_data() {
|
||||
for (decorated, expected) in [
|
||||
(
|
||||
"?bar@Foo@@QEAAXH@Z",
|
||||
"public: void __cdecl Foo::bar(int) __ptr64",
|
||||
),
|
||||
(
|
||||
"?get@Foo@@QEBAHXZ",
|
||||
"public: int __cdecl Foo::get(void)const __ptr64",
|
||||
),
|
||||
("??0Foo@@QEAA@XZ", "public: __cdecl Foo::Foo(void) __ptr64"),
|
||||
(
|
||||
"??1Foo@@UEAA@XZ",
|
||||
"public: virtual __cdecl Foo::~Foo(void) __ptr64",
|
||||
),
|
||||
(
|
||||
"?make@Foo@@SAPEAV1@XZ",
|
||||
"public: static class Foo * __ptr64 __cdecl Foo::make(void)",
|
||||
),
|
||||
("?x@ns@@3HA", "int ns::x"),
|
||||
("?count@Foo@@2HB", "public: static int const Foo::count"),
|
||||
("??_7type_info@@6B@", "const type_info::`vftable'"),
|
||||
] {
|
||||
assert_eq!(
|
||||
demangle(decorated).as_deref(),
|
||||
Some(expected),
|
||||
"{decorated}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_templates_and_back_references() {
|
||||
assert_eq!(
|
||||
demangle("?g@@YAXAEAV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z")
|
||||
.as_deref(),
|
||||
Some(
|
||||
"void __cdecl g(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > & __ptr64)"
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
demangle("?h@@YAXV?$array@H$0BA@@std@@@Z").as_deref(),
|
||||
Some("void __cdecl h(class std::array<int,16>)")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_undecorated_and_unsupported_names() {
|
||||
for symbol in [
|
||||
"malloc",
|
||||
"",
|
||||
"?",
|
||||
"?foo@@",
|
||||
"?foo@@YAXXZtrailing",
|
||||
"??_R0?AVtype_info@@@8",
|
||||
"?f@@YAXP6AXXZ@Z",
|
||||
&format!("?f@@YAX{}@Z", "PEA".repeat(40) + "H"),
|
||||
] {
|
||||
assert_eq!(demangle(symbol), None, "{symbol}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,7 @@
|
||||
pub mod apiset;
|
||||
pub mod classify;
|
||||
pub mod codegen;
|
||||
pub mod demangle;
|
||||
pub mod ingest;
|
||||
pub mod manifest;
|
||||
pub mod metadata;
|
||||
@@ -37,6 +38,7 @@ pub mod verify;
|
||||
pub use apiset::{get_api_sets_for_canonical, resolve_api_set_canonical};
|
||||
pub use classify::{Classification, SymbolDb};
|
||||
pub use codegen::{GeneratedFiles, generate};
|
||||
pub use demangle::demangle;
|
||||
pub use ingest::{ingest_header_file, ingest_standard_system_headers};
|
||||
pub use manifest::Manifest;
|
||||
pub use metadata::{AbiType, CallingConvention, FunctionSignature, MetadataCatalog};
|
||||
|
||||
@@ -166,7 +166,13 @@ impl Manifest {
|
||||
if let Classification::Manual { reason } | Classification::Unsupported { reason } =
|
||||
&e.classification
|
||||
{
|
||||
md.push_str(&format!("- `{}!{}` — {reason}\n", e.module, e.symbol));
|
||||
match crate::demangle(&e.symbol) {
|
||||
Some(name) => md.push_str(&format!(
|
||||
"- `{}!{}` (`{name}`) — {reason}\n",
|
||||
e.module, e.symbol
|
||||
)),
|
||||
None => md.push_str(&format!("- `{}!{}` — {reason}\n", e.module, e.symbol)),
|
||||
}
|
||||
}
|
||||
}
|
||||
md
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Decorated names produced by an independent mangler: Apple clang 21 with
|
||||
//! `-target x86_64-pc-windows-msvc -S` on the declarations quoted beside each
|
||||
//! case. Expected strings restate those declarations in `undname` style; they
|
||||
//! are not taken from the decoder.
|
||||
|
||||
use xenora_import_gen::demangle;
|
||||
|
||||
#[test]
|
||||
fn clang_msvc_manglings_decode_to_their_declarations() {
|
||||
for (decorated, expected) in [
|
||||
// void foo();
|
||||
("?foo@@YAXXZ", "void __cdecl foo(void)"),
|
||||
// int foo2(int);
|
||||
("?foo2@@YAHH@Z", "int __cdecl foo2(int)"),
|
||||
// void f(const char*);
|
||||
("?f@@YAXPEBD@Z", "void __cdecl f(char const * __ptr64)"),
|
||||
// void fv(int, ...);
|
||||
("?fv@@YAXHZZ", "void __cdecl fv(int,...)"),
|
||||
// bool g(long long, long long);
|
||||
("?g@@YA_N_J0@Z", "bool __cdecl g(__int64,__int64)"),
|
||||
// namespace std { void _Xlength_error(const char*); }
|
||||
(
|
||||
"?_Xlength_error@std@@YAXPEBD@Z",
|
||||
"void __cdecl std::_Xlength_error(char const * __ptr64)",
|
||||
),
|
||||
// struct Foo { void bar(int); };
|
||||
(
|
||||
"?bar@Foo@@QEAAXH@Z",
|
||||
"public: void __cdecl Foo::bar(int) __ptr64",
|
||||
),
|
||||
// struct Foo { int get() const; };
|
||||
(
|
||||
"?get@Foo@@QEBAHXZ",
|
||||
"public: int __cdecl Foo::get(void)const __ptr64",
|
||||
),
|
||||
// struct Foo { Foo(); };
|
||||
("??0Foo@@QEAA@XZ", "public: __cdecl Foo::Foo(void) __ptr64"),
|
||||
// struct Foo { static Foo* make(); };
|
||||
(
|
||||
"?make@Foo@@SAPEAU1@XZ",
|
||||
"public: static struct Foo * __ptr64 __cdecl Foo::make(void)",
|
||||
),
|
||||
// void use(Foo&);
|
||||
(
|
||||
"?use@@YAXAEAUFoo@@@Z",
|
||||
"void __cdecl use(struct Foo & __ptr64)",
|
||||
),
|
||||
// namespace ns { int x; }
|
||||
("?x@ns@@3HA", "int ns::x"),
|
||||
// Global operator new(size_t) and sized operator delete(void*, size_t).
|
||||
(
|
||||
"??2@YAPEAX_K@Z",
|
||||
"void * __ptr64 __cdecl operator new(unsigned __int64)",
|
||||
),
|
||||
(
|
||||
"??3@YAXPEAX_K@Z",
|
||||
"void __cdecl operator delete(void * __ptr64,unsigned __int64)",
|
||||
),
|
||||
// void gs(std::basic_string<char, std::char_traits<char>, std::allocator<char>>&);
|
||||
(
|
||||
"?gs@@YAXAEAV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@@Z",
|
||||
"void __cdecl gs(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > & __ptr64)",
|
||||
),
|
||||
// void h(std::array<int, 16>);
|
||||
(
|
||||
"?h@@YAXV?$array@H$0BA@@std@@@Z",
|
||||
"void __cdecl h(class std::array<int,16>)",
|
||||
),
|
||||
] {
|
||||
assert_eq!(
|
||||
demangle(decorated).as_deref(),
|
||||
Some(expected),
|
||||
"{decorated}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_clang_manglings_are_reported_rather_than_guessed() {
|
||||
// void (*keep[])(): function pointer types are outside the supported subset.
|
||||
assert_eq!(demangle("?keep@@3PAP6AXXZA"), None);
|
||||
// A compiler-generated cleanup funclet nested in another function's scope.
|
||||
assert_eq!(demangle("?dtor$2@?0??use@@YAXAEAUFoo@@@Z@4HA"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manifests_show_undecorated_names_for_unclassified_cxx_imports() {
|
||||
use xenora_import_gen::{ImportRecord, Manifest, SymbolDb};
|
||||
let record = |symbol: &str| ImportRecord {
|
||||
module: "msvcp140.dll".to_owned(),
|
||||
symbol: symbol.to_owned(),
|
||||
ordinal: None,
|
||||
iat_rva: 0x2000,
|
||||
};
|
||||
let manifest = Manifest::build(
|
||||
&[
|
||||
record("?_Xlength_error@std@@YAXPEBD@Z"),
|
||||
record("?keep@@3PAP6AXXZA"),
|
||||
],
|
||||
&SymbolDb::builtin(),
|
||||
);
|
||||
let markdown = manifest.render_markdown();
|
||||
assert!(markdown.contains(
|
||||
"- `msvcp140.dll!?_Xlength_error@std@@YAXPEBD@Z` (`void __cdecl std::_Xlength_error(char const * __ptr64)`) —"
|
||||
));
|
||||
assert!(markdown.contains("- `msvcp140.dll!?keep@@3PAP6AXXZA` —"));
|
||||
}
|
||||
@@ -44,12 +44,25 @@ TOP_KEYS = {
|
||||
# An encoding variant is another encoding of a form already in the registry (for
|
||||
# example the VOP3 `_e64` encoding of a VOP2 form): pure data that names the base
|
||||
# form, the encoding family, its opcode there and the operand rule of that
|
||||
# encoding. It inherits the base form's operation, signedness and effects.
|
||||
# encoding. The rule may redirect the base form's mask to an explicit destination.
|
||||
VARIANT_KEYS = {"of", "family", "opcode", "operands", "spec", "verify"}
|
||||
# The assembler suffix LLVM prints for a variant's encoding family.
|
||||
ASSEMBLY_SUFFIX = {"VOP3": "_e64"}
|
||||
|
||||
# Control effects select an existing typed instruction and its operand contract.
|
||||
# The XML records SCC as a separate implicit input. VCC and EXEC predicates
|
||||
# have fieldless mask inputs instead.
|
||||
CONTROL_OPERATIONS = {
|
||||
"end_program": ("EndProgram", "sopp_end", None),
|
||||
"branch": ("Branch", "sopp_branch", None),
|
||||
"branch_scc_zero": ("BranchSccZero", "sopp_branch", None),
|
||||
"branch_vcc_zero": ("BranchVccZero", "sopp_branch", "OPR_VCC"),
|
||||
"branch_exec_zero": ("BranchExecZero", "sopp_branch", "OPR_SDST_EXEC"),
|
||||
"wait_load": ("WaitLoad", "sopp_wait", None),
|
||||
}
|
||||
|
||||
OPERATIONS = {
|
||||
**{name: variant for name, (variant, _, _) in CONTROL_OPERATIONS.items()},
|
||||
"add": "Add", "sub": "Sub", "and": "And", "or": "Or", "xor": "Xor",
|
||||
"andn2": "AndNot", "orn2": "OrNot", "nand": "Nand", "nor": "Nor", "xnor": "Xnor",
|
||||
"lshl": "ShiftLeft", "lshr": "LogicalShiftRight", "ashr": "ArithmeticShiftRight",
|
||||
@@ -61,7 +74,7 @@ OPERATIONS = {
|
||||
"mul": "Multiply", "mul_hi": "MultiplyHigh", "bfe": "BitfieldExtract",
|
||||
"absdiff": "AbsoluteDifference", "lshl_add": "ShiftLeftAdd",
|
||||
"mul24": "Multiply24", "mul_hi24": "MultiplyHigh24",
|
||||
"mov": "Move", "cmov": "ConditionalMove",
|
||||
"mov": "Move", "cmov": "ConditionalMove", "swap": "Swap",
|
||||
}
|
||||
# Unary operations read one source; they need an operand rule of the unary kind.
|
||||
UNARY = {"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "flbit", "sext", "abs"}
|
||||
@@ -76,10 +89,13 @@ RELATIONS = {
|
||||
}
|
||||
# F and T exist only as VOPC compares (guide Table 59 offsets 0 and 7).
|
||||
VECTOR_ONLY_RELATIONS = {"f", "t"}
|
||||
# Guide 12.9 Table 59 and Table 61: a 32-bit integer VOPC compare's opcode is
|
||||
# its group base (128 for _I32, 192 for _U32) plus its relation's offset. This
|
||||
# is the guide's opcode layout, not a reading of the mnemonic.
|
||||
VOPC_INTEGER_BASES = {"signed": 128, "unsigned": 192}
|
||||
# Guide 12.9 Tables 59 and 61: integer VOPC opcodes are the group base
|
||||
# for the operand width and signedness plus the relation offset.
|
||||
VOPC_INTEGER_BASES = {
|
||||
16: {"signed": 136, "unsigned": 168},
|
||||
32: {"signed": 128, "unsigned": 192},
|
||||
64: {"signed": 160, "unsigned": 224},
|
||||
}
|
||||
VOPC_RELATION_OFFSETS = {"f": 0, "lt": 1, "eq": 2, "le": 3, "gt": 4, "lg": 5, "ge": 6, "t": 7}
|
||||
# (relation, signedness) -> primitive. Equality does not depend on signedness,
|
||||
# so both declared signednesses of EQ and LG share one primitive.
|
||||
@@ -97,7 +113,7 @@ COMPARE_PRIMITIVES = {
|
||||
# the signedness their primitive names, and their S1 is an unsigned count.
|
||||
LOGICAL = {
|
||||
"and", "or", "xor", "andn2", "orn2", "nand", "nor", "xnor",
|
||||
"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "cselect", "bfm",
|
||||
"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "cselect", "bfm", "swap",
|
||||
}
|
||||
ARITHMETIC = {
|
||||
"add", "sub", "min", "max", "mul", "mul_hi", "bfe", "absdiff", "lshl_add", "mul24", "mul_hi24",
|
||||
@@ -124,7 +140,7 @@ SHIFT_AMOUNTS = {1, 2, 3, 4}
|
||||
SOURCE_ORDER_KEY = "source_order"
|
||||
SOURCE_ORDERS = {"reversed"}
|
||||
SIGNEDNESS = {"unsigned": "Unsigned", "signed": "Signed", "bitwise": "Bitwise"}
|
||||
CARRY_IN = {"none": "None", "scc": "Scc"}
|
||||
CARRY_IN = {"none": "None", "scc": "Scc", "vcc": "Vcc"}
|
||||
SCC = {
|
||||
"unchanged": "Unchanged",
|
||||
"carry_out": "CarryOut",
|
||||
@@ -134,16 +150,19 @@ SCC = {
|
||||
"relation": "Relation",
|
||||
"selected_src0": "SelectedSrc0",
|
||||
}
|
||||
# lane_mask: the Wave32 VOPC result written to VCC_LO (vcc only; EXEC writes
|
||||
# such as v_cmpx have no contract yet, so exec must stay unchanged).
|
||||
MASK = {"unchanged": "Unchanged", "lane_mask": "LaneMask"}
|
||||
# lane_mask: the Wave32 compare or carry result written to VCC_LO.
|
||||
# sdst_lane_mask: the Wave32 compare result written to explicit VOP3A SDST.
|
||||
# EXEC writes such as v_cmpx have no contract, so exec must stay unchanged.
|
||||
MASK = {"unchanged": "Unchanged", "lane_mask": "LaneMask", "sdst_lane_mask": "SdstLaneMask"}
|
||||
WAVE = {"any": "Any", "wave32": "Wave32"}
|
||||
# Which wave declaration each operand-rule kind must make. The decoder has no
|
||||
# wave-size input, so "wave32" is only true where the caller's ABI fixes the
|
||||
# wave size: the lane-mask compares, whose one entry point is the Wave32
|
||||
# compute fixture ABI (docs/shaders/vector-compare.md section 2). Every other
|
||||
# kind must be "any".
|
||||
WAVE_BY_KIND = {"vector_compare": "wave32"}
|
||||
# The synthetic compute fixture ABI fixes the wave size for these operand-rule
|
||||
# kinds and for the VCC-reading VOP2 rule. Other forms declare "any".
|
||||
WAVE_BY_KIND = {"control": "wave32", "vector_compare": "wave32", "vector_unary": "wave32", "vector_swap": "wave32"}
|
||||
VCC_VECTOR_PRIMITIVES = {
|
||||
("cselect", "bitwise"): "Select",
|
||||
("add", "unsigned"): "AddCarry",
|
||||
("sub", "unsigned"): "SubtractBorrow",
|
||||
}
|
||||
EVIDENCE = {
|
||||
"reference": "Reference",
|
||||
"independent": "Independent",
|
||||
@@ -164,7 +183,6 @@ PINNED_DOCUMENTS = {
|
||||
"file": "amdgpu_isa_rdna2.xml",
|
||||
},
|
||||
}
|
||||
WIDTHS = {32}
|
||||
|
||||
# (operation, signedness) -> (required SCC effect, primitive, takes carry-in).
|
||||
# A form whose declaration is not a row here has no primitive and is rejected.
|
||||
@@ -258,8 +276,73 @@ UNSUPPORTED_COMBOS = {
|
||||
# which SOP2 groups under src_vcc and src_special).
|
||||
# VOP3 rules also name source classes and encoding fields they refuse.
|
||||
VOP3_COMBOS = {"src_sgpr", "src_inline", "src_literal", "modifiers", "src2"}
|
||||
ALL_COMBOS = UNSUPPORTED_COMBOS | {"src_vcc_hi", "src_null"} | VOP3_COMBOS
|
||||
ALL_COMBOS = UNSUPPORTED_COMBOS | {"src_vcc_hi", "src_null", "dst_vcc_hi"} | VOP3_COMBOS
|
||||
VOP3_VGPR2_UNSUPPORTED = {
|
||||
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
|
||||
"src_float_inline", "src_special", "src_literal", "modifiers", "src2",
|
||||
}
|
||||
|
||||
VECTOR_UNARY_PRIMITIVES = {
|
||||
("not", "bitwise"): "Not",
|
||||
("brev", "bitwise"): "ReverseBits",
|
||||
("flbit", "unsigned"): "FindHighUnsigned",
|
||||
("ff1", "bitwise"): "FindLow",
|
||||
("flbit", "signed"): "FindHighSigned",
|
||||
}
|
||||
|
||||
OPERAND_RULES = {
|
||||
"sopp_end": {
|
||||
"rust": "SoppEnd",
|
||||
"enum": "SoppControlOp",
|
||||
"shape": {"family": "SOPP", "src": [], "max_literals": 0, "immediate": 0},
|
||||
"unsupported": set(),
|
||||
"kind": "control",
|
||||
},
|
||||
"sopp_branch": {
|
||||
"rust": "SoppBranch",
|
||||
"enum": "SoppControlOp",
|
||||
"shape": {"family": "SOPP", "src": [{"field": "SIMM16", "class": "label"}], "max_literals": 0},
|
||||
"unsupported": set(),
|
||||
"kind": "control",
|
||||
},
|
||||
"sopp_wait": {
|
||||
"rust": "SoppWait",
|
||||
"enum": "SoppControlOp",
|
||||
"shape": {"family": "SOPP", "src": [{"field": "SIMM16", "class": "waitcnt"}],
|
||||
"max_literals": 0, "immediate": 0x3f70},
|
||||
"unsupported": set(),
|
||||
"kind": "control",
|
||||
},
|
||||
"vop1_vgpr": {
|
||||
"rust": "Vop1Vgpr",
|
||||
"enum": "VectorUnaryOp",
|
||||
"shape": {
|
||||
"family": "VOP1",
|
||||
"dst": {"field": "VDST", "class": "vgpr", "min": 0, "max": 255},
|
||||
"src": [{"field": "SRC0", "class": "vector_source"}],
|
||||
"max_literals": 1,
|
||||
},
|
||||
"unsupported": {
|
||||
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline",
|
||||
"src_special",
|
||||
},
|
||||
"kind": "vector_unary",
|
||||
},
|
||||
"vop1_swap": {
|
||||
"rust": "Vop1Swap",
|
||||
"enum": "VectorSwapOp",
|
||||
"shape": {
|
||||
"family": "VOP1",
|
||||
"dst": {"field": "VDST", "class": "vgpr", "min": 0, "max": 255},
|
||||
"src": [{"field": "SRC0", "class": "vgpr"}],
|
||||
"max_literals": 0,
|
||||
},
|
||||
"unsupported": {
|
||||
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
|
||||
"src_float_inline", "src_special", "src_literal",
|
||||
},
|
||||
"kind": "vector_swap",
|
||||
},
|
||||
"sop2_sgpr": {
|
||||
"rust": "Sop2Sgpr",
|
||||
"enum": "ScalarAluOp",
|
||||
@@ -363,6 +446,44 @@ OPERAND_RULES = {
|
||||
},
|
||||
"kind": "vector_compare",
|
||||
},
|
||||
"vopc_vcc_half": {
|
||||
"rust": "VopcVccHalf",
|
||||
"enum": "VectorCompareOp",
|
||||
"shape": {
|
||||
"family": "VOPC",
|
||||
"src": [
|
||||
{"field": "SRC0", "class": "vector_source"},
|
||||
{"field": "VSRC1", "class": "vgpr"},
|
||||
],
|
||||
"max_literals": 0,
|
||||
},
|
||||
# The destination is implicitly vcc_lo; the decoder rejects these SRC0
|
||||
# selectors (the same vector_source as VOP2).
|
||||
"unsupported": {
|
||||
"src_literal", "src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline",
|
||||
"src_special",
|
||||
},
|
||||
"kind": "vector_compare",
|
||||
"width": 16,
|
||||
},
|
||||
"vopc_vcc_pair": {
|
||||
"rust": "VopcVccPair",
|
||||
"enum": "VectorCompareOp",
|
||||
"shape": {
|
||||
"family": "VOPC",
|
||||
"src": [
|
||||
{"field": "SRC0", "class": "vector_pair_or_inline_integer"},
|
||||
{"field": "VSRC1", "class": "vgpr_pair"},
|
||||
],
|
||||
"max_literals": 0,
|
||||
},
|
||||
"unsupported": {
|
||||
"src_vcc", "src_literal", "src_exec", "src_m0", "src_ttmp", "src_null",
|
||||
"src_float_inline", "src_special",
|
||||
},
|
||||
"kind": "vector_compare",
|
||||
"width": 64,
|
||||
},
|
||||
"vop3_vgpr2": {
|
||||
"rust": "Vop3Vgpr2",
|
||||
"enum": "VectorAluOp",
|
||||
@@ -380,16 +501,34 @@ OPERAND_RULES = {
|
||||
},
|
||||
# Two VGPR sources only, with ABS, OP_SEL, CLAMP, OMOD and NEG clear and
|
||||
# SRC2 the assembler's unused inline zero; the decoder rejects the rest.
|
||||
"unsupported": {
|
||||
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
|
||||
"src_float_inline", "src_special", "src_literal", "modifiers", "src2",
|
||||
},
|
||||
"unsupported": VOP3_VGPR2_UNSUPPORTED,
|
||||
"kind": "vector_vop3",
|
||||
# Only encoding variants of forms whose rule has this kind may use it.
|
||||
"variant_of": "vector",
|
||||
# The generated enum of this rule's variants; base() maps to "enum".
|
||||
"variant_enum": "VectorAluVop3Op",
|
||||
},
|
||||
"vop3_cmp_vgpr2": {
|
||||
"rust": "Vop3CmpVgpr2",
|
||||
"enum": "VectorCompareOp",
|
||||
"shape": {
|
||||
"family": "VOP3",
|
||||
"dst": {"field": "VDST", "class": "sgpr", "min": 0, "max": 106},
|
||||
"src": [
|
||||
{"field": "SRC0", "class": "vgpr"},
|
||||
{"field": "SRC1", "class": "vgpr"},
|
||||
],
|
||||
"max_literals": 0,
|
||||
"variant_only": True,
|
||||
},
|
||||
"unsupported": VOP3_VGPR2_UNSUPPORTED | {
|
||||
"dst_vcc_hi", "dst_exec", "dst_ttmp", "dst_m0", "dst_null",
|
||||
},
|
||||
"kind": "vector_compare_vop3",
|
||||
"variant_of": "vector_compare",
|
||||
"variant_enum": "VectorCompareVop3Op",
|
||||
"vcc_transition": ("lane_mask", "sdst_lane_mask"),
|
||||
},
|
||||
"vop2_vgpr": {
|
||||
"rust": "Vop2Vgpr",
|
||||
"enum": "VectorAluOp",
|
||||
@@ -410,6 +549,24 @@ OPERAND_RULES = {
|
||||
},
|
||||
"kind": "vector",
|
||||
},
|
||||
"vop2_vcc": {
|
||||
"rust": "Vop2Vcc",
|
||||
"enum": "VectorAluOp",
|
||||
"shape": {
|
||||
"family": "VOP2",
|
||||
"dst": {"field": "VDST", "class": "vgpr", "min": 0, "max": 255},
|
||||
"src": [
|
||||
{"field": "SRC0", "class": "vector_source"},
|
||||
{"field": "VSRC1", "class": "vgpr"},
|
||||
],
|
||||
"max_literals": 1,
|
||||
},
|
||||
"unsupported": {
|
||||
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline",
|
||||
"src_special",
|
||||
},
|
||||
"kind": "vector",
|
||||
},
|
||||
"vop2_vgpr2": {
|
||||
"rust": "Vop2Vgpr2",
|
||||
"enum": "VectorAluOp",
|
||||
@@ -599,24 +756,35 @@ def _check_xml(form, rule, snapshot, errors):
|
||||
operands = {}
|
||||
scc_in = scc_out = False
|
||||
implicit = set()
|
||||
vcc_writes = []
|
||||
for field, data_format, kind, size, is_input, is_output, _implicit, _encoded in variant["operands"]:
|
||||
vcc_operands = []
|
||||
control_mask = CONTROL_OPERATIONS.get(form["operation"], (None, None, None))[2]
|
||||
mask_inputs = 0
|
||||
for field, data_format, kind, size, is_input, is_output, is_implicit, encoded in variant["operands"]:
|
||||
if kind == "OPR_SSRC_SPECIAL_SCC":
|
||||
scc_in |= is_input
|
||||
scc_out |= is_output
|
||||
elif control_mask and (field, kind, data_format, size, is_input, is_output, is_implicit, encoded) == (
|
||||
"", control_mask, "FMT_NUM_M64", 64, True, False, True, True
|
||||
):
|
||||
mask_inputs += 1
|
||||
elif field:
|
||||
operands[field] = (data_format, size, is_input, is_output)
|
||||
operands[field] = (data_format, kind, size, is_input, is_output)
|
||||
elif kind == "OPR_VCC":
|
||||
vcc_operands.append((data_format, size, is_input, is_output))
|
||||
else:
|
||||
implicit.add(kind)
|
||||
if kind == "OPR_VCC":
|
||||
vcc_writes.append((is_input, is_output))
|
||||
# The vocabulary states SCC effects and a lane-mask VCC write; any other
|
||||
# implicit XML operand (such as an EXEC write) is undeclared.
|
||||
if form["carry_in"] == "vcc":
|
||||
if vcc_operands.count(("FMT_NUM_M64", 64, True, False)) != 1:
|
||||
errors.append(f"{label}: carry_in vcc requires one implicit XML VCC input")
|
||||
if ("FMT_NUM_M64", 64, True, False) in vcc_operands:
|
||||
vcc_operands.remove(("FMT_NUM_M64", 64, True, False))
|
||||
if form["vcc"] == "lane_mask":
|
||||
# Exactly one fieldless VCC operand, written and not read.
|
||||
if vcc_writes != [(False, True)]:
|
||||
if vcc_operands != [("FMT_NUM_M64", 64, False, True)]:
|
||||
errors.append(f"{label}: vcc lane_mask but the XML has no implicit VCC output")
|
||||
implicit.discard("OPR_VCC")
|
||||
elif vcc_operands:
|
||||
implicit.add("OPR_VCC")
|
||||
if control_mask and mask_inputs != 1:
|
||||
errors.append(f"{label}: expected one implicit {control_mask} input in the XML")
|
||||
if implicit:
|
||||
errors.append(f"{label}: XML implicit operands {sorted(implicit)} are not declared")
|
||||
if scc_in != (form["carry_in"] == "scc"):
|
||||
@@ -636,7 +804,15 @@ def _check_xml(form, rule, snapshot, errors):
|
||||
if field not in operands:
|
||||
errors.append(f"{label}: XML has no operand {field}")
|
||||
continue
|
||||
data_format, size, is_input, is_output = operands[field]
|
||||
data_format, kind, size, is_input, is_output = operands[field]
|
||||
if field == "SIMM16" and _rule_kind(form) == "control":
|
||||
expected_kind, expected_format = (
|
||||
("OPR_LABEL", "FMT_NUM_I16") if form["operands"] == "sopp_branch"
|
||||
else ("OPR_WAITCNT", "FMT_NUM_B16")
|
||||
)
|
||||
if [field, expected_format, expected_kind, 16, True, False, False, True] not in variant["operands"]:
|
||||
errors.append(f"{label}: SIMM16 is not an encoded {expected_kind} input")
|
||||
continue
|
||||
if field == "SIMM16":
|
||||
# The 16-bit immediate: signed forms read it as FMT_NUM_I16 (sign
|
||||
# extended), unsigned compares as FMT_NUM_U16 (zero extended).
|
||||
@@ -648,9 +824,17 @@ def _check_xml(form, rule, snapshot, errors):
|
||||
continue
|
||||
bits = form.get(SOURCE_BITS_KEY) if is_source else None
|
||||
expected = bits if type(bits) is int else form["width"]
|
||||
if not is_source and form["vcc"] == "sdst_lane_mask":
|
||||
# The XML describes the Wave64 pair. The Wave32 ABI writes one SGPR.
|
||||
expected = 64
|
||||
if (kind, data_format) != ("OPR_SREG", "FMT_NUM_M64"):
|
||||
errors.append(f"{label}: {field} is not a scalar mask destination in the XML")
|
||||
if size != expected:
|
||||
errors.append(f"{label}: {field} is {size} bits in the XML, declared {expected}")
|
||||
if (is_input, is_output) != (is_source, not is_source):
|
||||
# The XML marks both swap operands as outputs. Guide 12.8 also
|
||||
# reads both old values before assigning either result.
|
||||
direction = (False, True) if _rule_kind(form) == "vector_swap" else (is_source, not is_source)
|
||||
if (is_input, is_output) != direction:
|
||||
errors.append(f"{label}: {field} direction disagrees with the XML")
|
||||
if field == count_field:
|
||||
if data_format != "FMT_NUM_U32":
|
||||
@@ -660,7 +844,11 @@ def _check_xml(form, rule, snapshot, errors):
|
||||
elif type(bits) is int:
|
||||
if data_format != f"FMT_NUM_I{bits}":
|
||||
errors.append(f"{label}: {field} has XML format {data_format}, not FMT_NUM_I{bits}")
|
||||
elif is_source and data_format not in SOURCE_FORMATS.get(form["signedness"], ()):
|
||||
elif is_source and data_format not in (
|
||||
{f"FMT_NUM_{'I' if form['signedness'] == 'signed' else 'U'}{form['width']}"}
|
||||
if form["operands"] in ("vopc_vcc_half", "vopc_vcc_pair")
|
||||
else SOURCE_FORMATS.get(form["signedness"], ())
|
||||
):
|
||||
errors.append(
|
||||
f"{label}: signedness {form['signedness']} contradicts XML format {data_format}"
|
||||
)
|
||||
@@ -730,18 +918,23 @@ def validate(registry, snapshot):
|
||||
errors.append(f"{label}: variant {form['variant']!r} is reserved")
|
||||
if type(form["opcode"]) is not int or not 0 <= form["opcode"] <= U16_MAX:
|
||||
errors.append(f"{label}: invalid opcode")
|
||||
wave = WAVE_BY_KIND.get(_rule_kind(form), "any")
|
||||
reads_vcc = form["operands"] == "vop2_vcc"
|
||||
wave = "wave32" if reads_vcc else WAVE_BY_KIND.get(_rule_kind(form), "any")
|
||||
if (form["carry_in"] == "vcc") != reads_vcc:
|
||||
errors.append(f"{label}: implicit VCC input requires the vop2_vcc rule")
|
||||
if form["wave"] in WAVE and form["wave"] != wave:
|
||||
errors.append(f"{label}: wave {form['wave']} is not enforced for this rule (requires {wave})")
|
||||
lane_mask = _rule_kind(form) == "vector_compare"
|
||||
if form["vcc"] in MASK and (form["vcc"] == "lane_mask") != lane_mask:
|
||||
lane_mask = _rule_kind(form) == "vector_compare" or (reads_vcc and form["operation"] != "cselect")
|
||||
vcc = "lane_mask" if lane_mask else "unchanged"
|
||||
if form["vcc"] in MASK and form["vcc"] != vcc:
|
||||
errors.append(
|
||||
f"{label}: vcc {form['vcc']} contradicts rule {form['operands']} "
|
||||
f"(requires {'lane_mask' if lane_mask else 'unchanged'})"
|
||||
f"(requires {vcc})"
|
||||
)
|
||||
if form["exec"] != "unchanged":
|
||||
errors.append(f"{label}: exec {form['exec']} has no contract (requires unchanged)")
|
||||
if type(form["width"]) is not int or form["width"] not in WIDTHS:
|
||||
expected_width = (_implemented_rule(form) or {}).get("width", 32)
|
||||
if type(form["width"]) is not int or form["width"] != expected_width:
|
||||
errors.append(f"{label}: width {form['width']} is not supported")
|
||||
for key, value in (
|
||||
("name", form["name"]),
|
||||
@@ -781,7 +974,7 @@ def validate(registry, snapshot):
|
||||
errors.append(f"{label}: unknown {SOURCE_ORDER_KEY} {order!r}")
|
||||
elif _rule_kind(form) != "vector":
|
||||
errors.append(f"{label}: {SOURCE_ORDER_KEY} on a non-vector form")
|
||||
if form["operation"] in SCC_READERS and form["carry_in"] != "scc":
|
||||
if not reads_vcc and form["operation"] in SCC_READERS and form["carry_in"] != "scc":
|
||||
errors.append(f"{label}: operation {form['operation']} reads SCC (requires carry_in scc)")
|
||||
if form["operation"] == "sext":
|
||||
bits = form.get(SOURCE_BITS_KEY)
|
||||
@@ -807,7 +1000,7 @@ def validate(registry, snapshot):
|
||||
f"{expected} (guide 13.1.2), not {form['opcode']}"
|
||||
)
|
||||
elif _rule_kind(form) == "vector_compare":
|
||||
base = VOPC_INTEGER_BASES.get(form["signedness"])
|
||||
base = VOPC_INTEGER_BASES.get(expected_width, {}).get(form["signedness"])
|
||||
expected = None if base is None else base + VOPC_RELATION_OFFSETS[relation]
|
||||
if form["opcode"] != expected:
|
||||
errors.append(
|
||||
@@ -821,10 +1014,24 @@ def validate(registry, snapshot):
|
||||
if form["carry_in"] != "none":
|
||||
errors.append(f"{label}: carry_in {form['carry_in']} contradicts compare")
|
||||
primitive = (scc, None, False)
|
||||
elif _rule_kind(form) == "vector":
|
||||
elif form["operation"] in CONTROL_OPERATIONS:
|
||||
variant, operand_rule, _ = CONTROL_OPERATIONS[form["operation"]]
|
||||
signedness = "signed" if operand_rule == "sopp_branch" else "bitwise"
|
||||
if (form["variant"], form["operands"], form["signedness"]) != (variant, operand_rule, signedness):
|
||||
errors.append(f"{label}: control operation requires {variant}, {operand_rule}, {signedness}")
|
||||
if RELATION_KEY in form or form["width"] != 32:
|
||||
errors.append(f"{label}: control operation requires width 32 and no relation")
|
||||
primitive = ("unchanged", None, form["operation"] == "branch_scc_zero")
|
||||
elif _rule_kind(form) in ("vector", "vector_unary", "vector_swap"):
|
||||
if RELATION_KEY in form:
|
||||
errors.append(f"{label}: {RELATION_KEY} on a non-compare operation")
|
||||
lowering = VECTOR_PRIMITIVES.get((form["operation"], form["signedness"]))
|
||||
key = (form["operation"], form["signedness"])
|
||||
table = {
|
||||
"vector": VCC_VECTOR_PRIMITIVES if reads_vcc else VECTOR_PRIMITIVES,
|
||||
"vector_unary": VECTOR_UNARY_PRIMITIVES,
|
||||
"vector_swap": {("swap", "bitwise"): "Swap"},
|
||||
}[_rule_kind(form)]
|
||||
lowering = table.get(key)
|
||||
primitive = None if lowering is None else ("unchanged", lowering, False)
|
||||
else:
|
||||
if RELATION_KEY in form:
|
||||
@@ -852,10 +1059,13 @@ def validate(registry, snapshot):
|
||||
elif form["operands"] in OPERAND_RULES and OPERAND_RULES[form["operands"]]["kind"] != (
|
||||
(_rule_kind(form) if _rule_kind(form) in ("vector_compare", "immediate_compare") else "compare")
|
||||
if form["operation"] == "compare"
|
||||
else "vector_swap" if form["operation"] == "swap"
|
||||
else "vector_unary" if _rule_kind(form) == "vector_unary" and form["operation"] in UNARY
|
||||
else "unary" if form["operation"] in UNARY or (
|
||||
form["operation"] == "mov" and form["family"] == "SOP1"
|
||||
)
|
||||
else "vector" if _rule_kind(form) == "vector" and form["operation"] not in UNARY
|
||||
else "control" if form["operation"] in CONTROL_OPERATIONS
|
||||
else "immediate" if _rule_kind(form) == "immediate"
|
||||
else "alu"
|
||||
):
|
||||
@@ -890,9 +1100,10 @@ def variant_row(registry, variant, base=None):
|
||||
"""The base form re-encoded: its declaration with the variant's identity."""
|
||||
if base is None:
|
||||
base = next(form for form in registry["form"] if form.get("name") == variant["of"])
|
||||
_, vcc = OPERAND_RULES[variant["operands"]].get("vcc_transition", ("unchanged", "unchanged"))
|
||||
return dict(
|
||||
base, family=variant["family"], opcode=variant["opcode"], operands=variant["operands"],
|
||||
spec=variant["spec"], verify=variant["verify"],
|
||||
vcc=vcc, spec=variant["spec"], verify=variant["verify"],
|
||||
)
|
||||
|
||||
|
||||
@@ -962,24 +1173,32 @@ def _check_variants(registry, rules, documents, snapshot, seen, errors):
|
||||
if FORM_KEYS - set(base):
|
||||
errors.append(f"{label}: not checked, its form {variant['of']} is incomplete")
|
||||
continue
|
||||
base_vcc, _ = implemented.get("vcc_transition", ("unchanged", "unchanged"))
|
||||
if base["vcc"] != base_vcc:
|
||||
errors.append(
|
||||
f"{label}: operand rule {variant['operands']} requires a base "
|
||||
f"destination contract of {base_vcc}, got {base['vcc']}"
|
||||
)
|
||||
# The same base row as the completeness check above (with duplicate
|
||||
# declarations, the dict keeps the last one).
|
||||
_check_xml(variant_row(registry, variant, base), rule, snapshot, errors)
|
||||
# Every explicit operand, destination included, has the base encoding's
|
||||
# data format, in the same order (VSRC1 of VOP2 is SRC1 of VOP3).
|
||||
# Explicit destinations and sources keep the base encoding's data format
|
||||
# in the same role. The implicit-to-explicit mask transition is checked
|
||||
# above and in _check_xml for each encoding.
|
||||
base_xml = snapshot["variants"].get((base["name"], _family_encoding(base["family"])))
|
||||
own_xml = snapshot["variants"].get((variant["of"], _family_encoding(variant["family"])))
|
||||
base_rule = rules.get(base.get("operands"))
|
||||
if base_xml and own_xml and _well_formed(base_rule) and _well_formed(rule):
|
||||
# Operands correspond by role, in rule order: the destination, then
|
||||
# each source (VSRC1 of VOP2 is SRC1 of VOP3).
|
||||
def roles(rule, record):
|
||||
def roles(rule, record, explicit_dst):
|
||||
by_field = {row[0]: row[1] for row in record["operands"] if row[0]}
|
||||
fields = ([rule["dst"]["field"]] if "dst" in rule else [])
|
||||
fields = [rule["dst"]["field"]] if explicit_dst else []
|
||||
fields += [src["field"] for src in rule.get("src", [])]
|
||||
return [(field, by_field.get(field)) for field in fields]
|
||||
|
||||
pairs = list(zip(roles(base_rule, base_xml), roles(rule, own_xml)))
|
||||
explicit_dst = "dst" in base_rule and "dst" in rule
|
||||
pairs = zip(roles(base_rule, base_xml, explicit_dst), roles(rule, own_xml, explicit_dst))
|
||||
for (base_field, base_format), (field, data_format) in pairs:
|
||||
if base_format != data_format:
|
||||
errors.append(
|
||||
@@ -1042,7 +1261,7 @@ def render(registry, snapshot):
|
||||
"use crate::primitive;",
|
||||
"use crate::semantics::{",
|
||||
" CarryIn, Document, Evidence, FormSemantics, MaskEffect, Operation, OperandRule, SccEffect,",
|
||||
" Signedness, SpecRef, VectorBinary, Wave,",
|
||||
" Signedness, SpecRef, VectorBinary, VectorLowering, VectorUnary, VectorVcc, Wave,",
|
||||
"};",
|
||||
"use crate::CompareRelation;",
|
||||
"",
|
||||
@@ -1232,7 +1451,7 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
f"pub enum {enum} {{",
|
||||
]
|
||||
for form in forms:
|
||||
carry = " plus SCC" if form["carry_in"] == "scc" else ""
|
||||
carry = {"scc": " plus SCC", "vcc": " with VCC input"}.get(form["carry_in"], "")
|
||||
what = f"compare {form[RELATION_KEY]}" if RELATION_KEY in form else form["operation"]
|
||||
effect = f"VCC = {form['vcc']}" if form["vcc"] != "unchanged" else f"SCC = {form['scc']}"
|
||||
out += [
|
||||
@@ -1289,6 +1508,67 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
" }]",
|
||||
" }",
|
||||
]
|
||||
if kind == "control":
|
||||
out += [
|
||||
"",
|
||||
" /// Exact SIMM16 required by the fixture, or None for a displacement.",
|
||||
" pub const fn required_immediate(self) -> Option<u16> {",
|
||||
" match self {",
|
||||
]
|
||||
for form in forms:
|
||||
exact = OPERAND_RULES[form["operands"]]["shape"].get("immediate")
|
||||
value = "None" if exact is None else f"Some({exact:#x})"
|
||||
out.append(f" Self::{form['variant']} => {value},")
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// Constructs the existing decoded instruction, resolving a target only for a branch.",
|
||||
" pub fn decode<E>(",
|
||||
" self,",
|
||||
" target: impl FnOnce() -> Result<usize, E>,",
|
||||
" ) -> Result<crate::Instruction, E> {",
|
||||
" Ok(match self {",
|
||||
]
|
||||
for form in forms:
|
||||
variant = form["variant"]
|
||||
fields = " { target: target()? }" if form["operands"] == "sopp_branch" else ""
|
||||
out.append(f" Self::{variant} => crate::Instruction::{variant}{fields},")
|
||||
out += [" })", " }", "}", "", "impl crate::Instruction {",
|
||||
" /// The registry operation corresponding to a decoded SOPP control.",
|
||||
f" pub const fn sopp_control(self) -> Option<{enum}> {{",
|
||||
" match self {"]
|
||||
for form in forms:
|
||||
variant = form["variant"]
|
||||
fields = " { .. }" if form["operands"] == "sopp_branch" else ""
|
||||
out.append(f" Self::{variant}{fields} => Some({enum}::{variant}),")
|
||||
out += [" _ => None,", " }", " }", "}"]
|
||||
return out
|
||||
if kind in ("vector_unary", "vector_swap"):
|
||||
out += [
|
||||
"",
|
||||
" /// Assembler name of the 32-bit VOP1 encoding.",
|
||||
" pub const fn assembly_name(self) -> &'static str {",
|
||||
" match self {",
|
||||
]
|
||||
suffix = "_e32" if kind == "vector_unary" else ""
|
||||
out += [f" Self::{form['variant']} => \"{form['name'].lower()}{suffix}\"," for form in forms]
|
||||
out += [" }", " }"]
|
||||
if kind == "vector_swap":
|
||||
return out + ["}"]
|
||||
if kind == "vector_unary":
|
||||
out += [
|
||||
"",
|
||||
" /// Per-lane integer operation selected by the registry.",
|
||||
" pub const fn lowering(self) -> VectorUnary {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => "
|
||||
f"VectorUnary::{VECTOR_UNARY_PRIMITIVES[(form['operation'], form['signedness'])]},"
|
||||
for form in forms
|
||||
]
|
||||
return out + [" }", " }", "}"]
|
||||
if kind == "immediate":
|
||||
out += [
|
||||
"",
|
||||
@@ -1431,14 +1711,16 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
" }",
|
||||
"",
|
||||
" /// The per-lane operation its MSL lowering uses.",
|
||||
" pub const fn lowering(self) -> VectorBinary {",
|
||||
" pub const fn lowering(self) -> VectorLowering {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => "
|
||||
f"VectorBinary::{VECTOR_PRIMITIVES[(form['operation'], form['signedness'])]},"
|
||||
for form in forms
|
||||
]
|
||||
for form in forms:
|
||||
key = (form["operation"], form["signedness"])
|
||||
if form["operands"] == "vop2_vcc":
|
||||
lowering = f"Vcc(VectorVcc::{VCC_VECTOR_PRIMITIVES[key]})"
|
||||
else:
|
||||
lowering = f"Binary(VectorBinary::{VECTOR_PRIMITIVES[key]})"
|
||||
out.append(f" Self::{form['variant']} => VectorLowering::{lowering},")
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
@@ -1488,6 +1770,7 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
out += [" }", " }"]
|
||||
if kind in ("compare", "vector_compare"):
|
||||
result = "SCC" if kind == "compare" else "per-lane result"
|
||||
has_pairs = any(form["width"] == 64 for form in forms)
|
||||
out += [
|
||||
"",
|
||||
" /// The relation tested, with S0 on the left.",
|
||||
@@ -1504,11 +1787,32 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
"",
|
||||
f" /// The {result}: whether the relation holds for S0 and S1.",
|
||||
" pub const fn test(self, src0: u32, src1: u32) -> bool {",
|
||||
" match self {",
|
||||
]
|
||||
if has_pairs:
|
||||
out += [
|
||||
" self.test_bits(src0 as u64, src1 as u64)",
|
||||
" }",
|
||||
"",
|
||||
" /// Test raw operand bits at the width declared by this VOPC form.",
|
||||
" pub const fn test_bits(self, src0: u64, src1: u64) -> bool {",
|
||||
]
|
||||
out += [" match self {"]
|
||||
for form in forms:
|
||||
function = COMPARE_PRIMITIVES[(form[RELATION_KEY], form["signedness"])]
|
||||
out.append(f" Self::{form['variant']} => primitive::{function}(src0, src1),")
|
||||
relation = form[RELATION_KEY]
|
||||
if form["width"] in (16, 64) and relation not in VECTOR_ONLY_RELATIONS:
|
||||
symbol = {"lt": "<", "eq": "==", "le": "<=", "gt": ">", "lg": "!=", "ge": ">="}[relation]
|
||||
width = form["width"]
|
||||
if width == 64 and form["signedness"] == "unsigned":
|
||||
left, right = "src0", "src1"
|
||||
else:
|
||||
cast = f"{'i' if form['signedness'] == 'signed' else 'u'}{width}"
|
||||
left, right = f"(src0 as {cast})", f"(src1 as {cast})"
|
||||
expression = f"{left} {symbol} {right}"
|
||||
else:
|
||||
function = COMPARE_PRIMITIVES[(relation, form["signedness"])]
|
||||
args = "src0 as u32, src1 as u32" if has_pairs else "src0, src1"
|
||||
expression = f"primitive::{function}({args})"
|
||||
out.append(f" Self::{form['variant']} => {expression},")
|
||||
out += [" }", " }", "}"]
|
||||
return out
|
||||
out += [
|
||||
|
||||
@@ -21,9 +21,11 @@ include = [
|
||||
"rdna2/sopc.toml",
|
||||
"rdna2/sopk.toml",
|
||||
"rdna2/sop1.toml",
|
||||
"rdna2/vop1.toml",
|
||||
"rdna2/vop2.toml",
|
||||
"rdna2/vopc.toml",
|
||||
"rdna2/vop3.toml",
|
||||
"rdna2/sopp.toml",
|
||||
]
|
||||
|
||||
# Named public documents that spec references point at.
|
||||
@@ -43,11 +45,12 @@ file = "amdgpu_isa_rdna2.xml"
|
||||
# variant Rust enum variant of the typed op
|
||||
# operation primitive (closed vocabulary in generate_semantics.py OPERATIONS)
|
||||
# signedness unsigned | signed | bitwise (bitwise iff a logical operation)
|
||||
# carry_in none | scc (scc for unsigned add/sub carry and the cselect condition)
|
||||
# carry_in none | scc | vcc (implicit scalar or per-lane condition or carry)
|
||||
# width operand and result width in bits
|
||||
# scc unchanged | carry_out | borrow | signed_overflow | nonzero | relation | selected_src0
|
||||
# vcc, exec unchanged (stated, not implied) | lane_mask (vcc of a Wave32 VOPC compare)
|
||||
# wave any | wave32 (wave32 exactly for the VOPC lane-mask compares)
|
||||
# vcc, exec unchanged (stated, not implied) | lane_mask (Wave32 VOPC compare or VOP2 carry output)
|
||||
# VOP3A compare variant rows derive sdst_lane_mask from their operand rule.
|
||||
# wave any | wave32 (wave32 for VOPC compares, VOP1 integer forms and VCC-reading VOP2 forms)
|
||||
# operands a key of [operand_rules]
|
||||
# spec references; at least one guide section with a page
|
||||
# verify evidence required before the form counts as verified
|
||||
@@ -0,0 +1,123 @@
|
||||
# Existing gfx1030 compute controls, AMD RDNA 2 ISA guide §12.5.
|
||||
|
||||
[operand_rules.sopp_end]
|
||||
family = "SOPP"
|
||||
src = []
|
||||
max_literals = 0
|
||||
unsupported = []
|
||||
immediate = 0
|
||||
|
||||
[operand_rules.sopp_branch]
|
||||
family = "SOPP"
|
||||
src = [{ field = "SIMM16", class = "label" }]
|
||||
max_literals = 0
|
||||
unsupported = []
|
||||
|
||||
[operand_rules.sopp_wait]
|
||||
family = "SOPP"
|
||||
src = [{ field = "SIMM16", class = "waitcnt" }]
|
||||
max_literals = 0
|
||||
unsupported = []
|
||||
immediate = 0x3f70
|
||||
|
||||
[[form]]
|
||||
name = "S_ENDPGM"
|
||||
family = "SOPP"
|
||||
opcode = 1
|
||||
variant = "EndProgram"
|
||||
operation = "end_program"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "sopp_end"
|
||||
spec = [{ document = "guide", section = "12.5", page = 124 }, { document = "guide", section = "13.1.5", page = 245 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_BRANCH"
|
||||
family = "SOPP"
|
||||
opcode = 2
|
||||
variant = "Branch"
|
||||
operation = "branch"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "sopp_branch"
|
||||
spec = [{ document = "guide", section = "12.5", page = 124 }, { document = "guide", section = "13.1.5", page = 245 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CBRANCH_SCC0"
|
||||
family = "SOPP"
|
||||
opcode = 4
|
||||
variant = "BranchSccZero"
|
||||
operation = "branch_scc_zero"
|
||||
signedness = "signed"
|
||||
carry_in = "scc"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "sopp_branch"
|
||||
spec = [{ document = "guide", section = "12.5", page = 124 }, { document = "guide", section = "13.1.5", page = 245 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CBRANCH_VCCZ"
|
||||
family = "SOPP"
|
||||
opcode = 6
|
||||
variant = "BranchVccZero"
|
||||
operation = "branch_vcc_zero"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "sopp_branch"
|
||||
spec = [{ document = "guide", section = "12.5", page = 124 }, { document = "guide", section = "13.1.5", page = 245 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CBRANCH_EXECZ"
|
||||
family = "SOPP"
|
||||
opcode = 8
|
||||
variant = "BranchExecZero"
|
||||
operation = "branch_exec_zero"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "sopp_branch"
|
||||
spec = [{ document = "guide", section = "12.5", page = 125 }, { document = "guide", section = "13.1.5", page = 245 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_WAITCNT"
|
||||
family = "SOPP"
|
||||
opcode = 12
|
||||
variant = "WaitLoad"
|
||||
operation = "wait_load"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "sopp_wait"
|
||||
spec = [{ document = "guide", section = "12.5", page = 125 }, { document = "guide", section = "13.1.5", page = 245 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
@@ -0,0 +1,123 @@
|
||||
# Wave32 VOP1 integer forms, AMD RDNA 2 ISA guide 12.8.
|
||||
|
||||
[operand_rules.vop1_vgpr]
|
||||
family = "VOP1"
|
||||
dst = { field = "VDST", class = "vgpr", min = 0, max = 255 }
|
||||
src = [{ field = "SRC0", class = "vector_source" }]
|
||||
max_literals = 1
|
||||
unsupported = [
|
||||
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special",
|
||||
]
|
||||
|
||||
# Both operands are read and written by swap; SRC0 must select a VGPR.
|
||||
[operand_rules.vop1_swap]
|
||||
family = "VOP1"
|
||||
dst = { field = "VDST", class = "vgpr", min = 0, max = 255 }
|
||||
src = [{ field = "SRC0", class = "vgpr" }]
|
||||
max_literals = 0
|
||||
unsupported = [
|
||||
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
|
||||
"src_float_inline", "src_special", "src_literal",
|
||||
]
|
||||
|
||||
[[form]]
|
||||
name = "V_NOT_B32"
|
||||
family = "VOP1"
|
||||
opcode = 55
|
||||
variant = "NotB32"
|
||||
operation = "not"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop1_vgpr"
|
||||
spec = [{ document = "guide", section = "12.8", page = 143 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_BFREV_B32"
|
||||
family = "VOP1"
|
||||
opcode = 56
|
||||
variant = "BfrevB32"
|
||||
operation = "brev"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop1_vgpr"
|
||||
spec = [{ document = "guide", section = "12.8", page = 143 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_FFBH_U32"
|
||||
family = "VOP1"
|
||||
opcode = 57
|
||||
variant = "FfbhU32"
|
||||
operation = "flbit"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop1_vgpr"
|
||||
spec = [{ document = "guide", section = "12.8", page = 143 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_FFBL_B32"
|
||||
family = "VOP1"
|
||||
opcode = 58
|
||||
variant = "FfblB32"
|
||||
operation = "ff1"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop1_vgpr"
|
||||
spec = [{ document = "guide", section = "12.8", page = 143 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_FFBH_I32"
|
||||
family = "VOP1"
|
||||
opcode = 59
|
||||
variant = "FfbhI32"
|
||||
operation = "flbit"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop1_vgpr"
|
||||
spec = [{ document = "guide", section = "12.8", page = 144 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_SWAP_B32"
|
||||
family = "VOP1"
|
||||
opcode = 101
|
||||
variant = "SwapB32"
|
||||
operation = "swap"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop1_swap"
|
||||
spec = [{ document = "guide", section = "12.8", page = 149 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
@@ -348,3 +348,85 @@ wave = "any"
|
||||
operands = "vop2_vgpr2"
|
||||
spec = [{ document = "guide", section = "12.7", page = 133 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[operand_rules.vop2_vcc]
|
||||
family = "VOP2"
|
||||
dst = { field = "VDST", class = "vgpr", min = 0, max = 255 }
|
||||
src = [
|
||||
{ field = "SRC0", class = "vector_source" },
|
||||
{ field = "VSRC1", class = "vgpr" },
|
||||
]
|
||||
# vector_source = VGPR, normal SGPR s0-s105, vcc_lo, inline integer -16..64, or a literal word.
|
||||
max_literals = 1
|
||||
unsupported = [
|
||||
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special",
|
||||
]
|
||||
|
||||
[[form]]
|
||||
name = "V_CNDMASK_B32"
|
||||
family = "VOP2"
|
||||
opcode = 1
|
||||
variant = "CndmaskB32"
|
||||
operation = "cselect"
|
||||
signedness = "bitwise"
|
||||
carry_in = "vcc"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop2_vcc"
|
||||
spec = [{ document = "guide", section = "12.7", page = 131 }, { document = "guide", section = "3.9", page = 20 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_ADD_CO_CI_U32"
|
||||
family = "VOP2"
|
||||
opcode = 40
|
||||
variant = "AddCoCiU32"
|
||||
operation = "add"
|
||||
signedness = "unsigned"
|
||||
carry_in = "vcc"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop2_vcc"
|
||||
spec = [{ document = "guide", section = "12.7", page = 134 }, { document = "guide", section = "3.9", page = 20 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_SUB_CO_CI_U32"
|
||||
family = "VOP2"
|
||||
opcode = 41
|
||||
variant = "SubCoCiU32"
|
||||
operation = "sub"
|
||||
signedness = "unsigned"
|
||||
carry_in = "vcc"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop2_vcc"
|
||||
spec = [{ document = "guide", section = "12.7", page = 134 }, { document = "guide", section = "3.9", page = 20 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_SUBREV_CO_CI_U32"
|
||||
family = "VOP2"
|
||||
opcode = 42
|
||||
variant = "SubrevCoCiU32"
|
||||
operation = "sub"
|
||||
signedness = "unsigned"
|
||||
carry_in = "vcc"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vop2_vcc"
|
||||
source_order = "reversed"
|
||||
spec = [{ document = "guide", section = "12.7", page = 134 }, { document = "guide", section = "3.9", page = 20 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
@@ -1,6 +1,202 @@
|
||||
# VOP3 encodings of the gfx1030 semantic registry; included by ../rdna2.toml.
|
||||
# Data only; see the root file for the field meanings.
|
||||
|
||||
# ---- Wave32 VOPC compares in VOP3A (#215) ----
|
||||
|
||||
# VDST encodes the scalar lane-mask destination, including vcc_lo (selector 106).
|
||||
# The two sources are VGPRs. Modifiers are clear and SRC2 is inline zero.
|
||||
[operand_rules.vop3_cmp_vgpr2]
|
||||
family = "VOP3"
|
||||
dst = { field = "VDST", class = "sgpr", min = 0, max = 106 }
|
||||
src = [
|
||||
{ field = "SRC0", class = "vgpr" },
|
||||
{ field = "SRC1", class = "vgpr" },
|
||||
]
|
||||
max_literals = 0
|
||||
variant_only = true
|
||||
unsupported = [
|
||||
"dst_vcc_hi", "dst_exec", "dst_ttmp", "dst_m0", "dst_null",
|
||||
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
|
||||
"src_float_inline", "src_special", "src_literal", "modifiers", "src2",
|
||||
]
|
||||
|
||||
# Opcodes come from the pinned XML's default ENC_VOP3 records.
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_LT_I32"
|
||||
family = "VOP3"
|
||||
opcode = 129
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_EQ_I32"
|
||||
family = "VOP3"
|
||||
opcode = 130
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_LE_I32"
|
||||
family = "VOP3"
|
||||
opcode = 131
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_GT_I32"
|
||||
family = "VOP3"
|
||||
opcode = 132
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_NE_I32"
|
||||
family = "VOP3"
|
||||
opcode = 133
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_GE_I32"
|
||||
family = "VOP3"
|
||||
opcode = 134
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_LT_U32"
|
||||
family = "VOP3"
|
||||
opcode = 193
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_EQ_U32"
|
||||
family = "VOP3"
|
||||
opcode = 194
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_LE_U32"
|
||||
family = "VOP3"
|
||||
opcode = 195
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_GT_U32"
|
||||
family = "VOP3"
|
||||
opcode = 196
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_NE_U32"
|
||||
family = "VOP3"
|
||||
opcode = 197
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_GE_U32"
|
||||
family = "VOP3"
|
||||
opcode = 198
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_F_I32"
|
||||
family = "VOP3"
|
||||
opcode = 128
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_T_I32"
|
||||
family = "VOP3"
|
||||
opcode = 135
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_F_U32"
|
||||
family = "VOP3"
|
||||
opcode = 192
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_CMP_T_U32"
|
||||
family = "VOP3"
|
||||
opcode = 199
|
||||
operands = "vop3_cmp_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
{ document = "guide", section = "13.3.4", page = 257 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
# ---- VOP3 encoding variants of registry forms (#215) ----
|
||||
# An [[encoding_variant]] re-encodes a form declared in another family file: it
|
||||
# names the form (`of`), this family, the XML opcode here and the operand rule
|
||||
@@ -37,3 +233,130 @@ spec = [
|
||||
{ document = "guide", section = "12.7", page = 134 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
# ABS and NEG apply to floating-point inputs (guide 6.2.1) and OMOD
|
||||
# applies to floating-point results (6.2.2). These integer forms use neither.
|
||||
# OP_SEL selects 16-bit halves (13.3.4). CLAMP saturates integer results
|
||||
# (6.5), which these registry forms do not declare. SGPR, inline and literal
|
||||
# sources remain outside this operand rule.
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MUL_I32_I24"
|
||||
family = "VOP3"
|
||||
opcode = 265
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 131 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MUL_HI_I32_I24"
|
||||
family = "VOP3"
|
||||
opcode = 266
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 132 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MUL_U32_U24"
|
||||
family = "VOP3"
|
||||
opcode = 267
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 132 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MUL_HI_U32_U24"
|
||||
family = "VOP3"
|
||||
opcode = 268
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 132 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MIN_I32"
|
||||
family = "VOP3"
|
||||
opcode = 273
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 133 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MAX_I32"
|
||||
family = "VOP3"
|
||||
opcode = 274
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 133 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MIN_U32"
|
||||
family = "VOP3"
|
||||
opcode = 275
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 133 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_MAX_U32"
|
||||
family = "VOP3"
|
||||
opcode = 276
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 133 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_XNOR_B32"
|
||||
family = "VOP3"
|
||||
opcode = 286
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 134 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_SUB_NC_U32"
|
||||
family = "VOP3"
|
||||
opcode = 294
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 134 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[encoding_variant]]
|
||||
of = "V_SUBREV_NC_U32"
|
||||
family = "VOP3"
|
||||
opcode = 295
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ document = "guide", section = "12.7", page = 134 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
@@ -358,3 +358,617 @@ spec = [
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
# Wave32 64-bit integer compares (guide 3.6.3, 6.2 Table 20 and 12.9).
|
||||
[operand_rules.vopc_vcc_pair]
|
||||
family = "VOPC"
|
||||
src = [
|
||||
{ field = "SRC0", class = "vector_pair_or_inline_integer" },
|
||||
{ field = "VSRC1", class = "vgpr_pair" },
|
||||
]
|
||||
max_literals = 0
|
||||
unsupported = [
|
||||
"src_vcc", "src_literal", "src_exec", "src_m0", "src_ttmp", "src_null",
|
||||
"src_float_inline", "src_special",
|
||||
]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LT_I64"
|
||||
family = "VOPC"
|
||||
opcode = 161
|
||||
variant = "CmpLtI64"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_EQ_I64"
|
||||
family = "VOPC"
|
||||
opcode = 162
|
||||
variant = "CmpEqI64"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LE_I64"
|
||||
family = "VOPC"
|
||||
opcode = 163
|
||||
variant = "CmpLeI64"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GT_I64"
|
||||
family = "VOPC"
|
||||
opcode = 164
|
||||
variant = "CmpGtI64"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_NE_I64"
|
||||
family = "VOPC"
|
||||
opcode = 165
|
||||
variant = "CmpNeI64"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GE_I64"
|
||||
family = "VOPC"
|
||||
opcode = 166
|
||||
variant = "CmpGeI64"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LT_U64"
|
||||
family = "VOPC"
|
||||
opcode = 225
|
||||
variant = "CmpLtU64"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_EQ_U64"
|
||||
family = "VOPC"
|
||||
opcode = 226
|
||||
variant = "CmpEqU64"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LE_U64"
|
||||
family = "VOPC"
|
||||
opcode = 227
|
||||
variant = "CmpLeU64"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GT_U64"
|
||||
family = "VOPC"
|
||||
opcode = 228
|
||||
variant = "CmpGtU64"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_NE_U64"
|
||||
family = "VOPC"
|
||||
opcode = 229
|
||||
variant = "CmpNeU64"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GE_U64"
|
||||
family = "VOPC"
|
||||
opcode = 230
|
||||
variant = "CmpGeU64"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_F_I64"
|
||||
family = "VOPC"
|
||||
opcode = 160
|
||||
variant = "CmpFI64"
|
||||
operation = "compare"
|
||||
relation = "f"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_T_I64"
|
||||
family = "VOPC"
|
||||
opcode = 167
|
||||
variant = "CmpTI64"
|
||||
operation = "compare"
|
||||
relation = "t"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_F_U64"
|
||||
family = "VOPC"
|
||||
opcode = 224
|
||||
variant = "CmpFU64"
|
||||
operation = "compare"
|
||||
relation = "f"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_T_U64"
|
||||
family = "VOPC"
|
||||
opcode = 231
|
||||
variant = "CmpTU64"
|
||||
operation = "compare"
|
||||
relation = "t"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 64
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_pair"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal"]
|
||||
|
||||
# Wave32 16-bit integer compares (guide 12.9, Tables 59 and 61).
|
||||
[operand_rules.vopc_vcc_half]
|
||||
family = "VOPC"
|
||||
src = [
|
||||
{ field = "SRC0", class = "vector_source" },
|
||||
{ field = "VSRC1", class = "vgpr" },
|
||||
]
|
||||
# Guide 6.2, 6.2.5 and 6.8: read the low half of each source.
|
||||
max_literals = 0
|
||||
unsupported = [
|
||||
"src_literal", "src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special",
|
||||
]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LT_I16"
|
||||
family = "VOPC"
|
||||
opcode = 137
|
||||
variant = "CmpLtI16"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_EQ_I16"
|
||||
family = "VOPC"
|
||||
opcode = 138
|
||||
variant = "CmpEqI16"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LE_I16"
|
||||
family = "VOPC"
|
||||
opcode = 139
|
||||
variant = "CmpLeI16"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GT_I16"
|
||||
family = "VOPC"
|
||||
opcode = 140
|
||||
variant = "CmpGtI16"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_NE_I16"
|
||||
family = "VOPC"
|
||||
opcode = 141
|
||||
variant = "CmpNeI16"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GE_I16"
|
||||
family = "VOPC"
|
||||
opcode = 142
|
||||
variant = "CmpGeI16"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LT_U16"
|
||||
family = "VOPC"
|
||||
opcode = 169
|
||||
variant = "CmpLtU16"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_EQ_U16"
|
||||
family = "VOPC"
|
||||
opcode = 170
|
||||
variant = "CmpEqU16"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LE_U16"
|
||||
family = "VOPC"
|
||||
opcode = 171
|
||||
variant = "CmpLeU16"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GT_U16"
|
||||
family = "VOPC"
|
||||
opcode = 172
|
||||
variant = "CmpGtU16"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_NE_U16"
|
||||
family = "VOPC"
|
||||
opcode = 173
|
||||
variant = "CmpNeU16"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_GE_U16"
|
||||
family = "VOPC"
|
||||
opcode = 174
|
||||
variant = "CmpGeU16"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 16
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc_half"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
+69
-6
@@ -20,9 +20,22 @@ pub use rdna2::{
|
||||
};
|
||||
pub use semantics_gen::{
|
||||
ScalarAluOp, ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, ScalarUnaryOp,
|
||||
VectorAluOp, VectorAluVop3Op, VectorCompareOp,
|
||||
SoppControlOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorCompareVop3Op,
|
||||
VectorSwapOp, VectorUnaryOp,
|
||||
};
|
||||
|
||||
impl VectorAluOp {
|
||||
/// Whether this encoding takes a per-lane VCC_LO bit.
|
||||
pub fn reads_vcc(self) -> bool {
|
||||
self.semantics().carry_in == semantics::CarryIn::Vcc
|
||||
}
|
||||
|
||||
/// Whether this encoding replaces the Wave32 VCC_LO mask.
|
||||
pub fn writes_vcc(self) -> bool {
|
||||
self.semantics().vcc == semantics::MaskEffect::LaneMask
|
||||
}
|
||||
}
|
||||
|
||||
/// SGPR index of `vcc_lo`, the Wave32 vector condition code.
|
||||
pub const VCC_LO: u8 = 106;
|
||||
|
||||
@@ -155,6 +168,14 @@ pub enum Instruction {
|
||||
WaitStore,
|
||||
/// VOP1 unmodified 32-bit vector move.
|
||||
MoveB32 { dst: u8, src: VectorSource },
|
||||
/// VOP1 unary integer operation with a single VGPR result.
|
||||
VectorUnary {
|
||||
op: VectorUnaryOp,
|
||||
dst: u8,
|
||||
src: VectorSource,
|
||||
},
|
||||
/// VOP1 register swap. Both operands are inputs and outputs.
|
||||
VectorSwap { op: VectorSwapOp, dst: u8, src: u8 },
|
||||
/// VOP3 encoding of a registry VOP2 integer operation (operand rule
|
||||
/// `vop3_vgpr2`): two VGPR sources and no input or output modifiers.
|
||||
VectorAluVop3 {
|
||||
@@ -199,13 +220,22 @@ pub enum Instruction {
|
||||
src: u8,
|
||||
simm16: u16,
|
||||
},
|
||||
/// VOPC 32-bit integer compare writing a Wave32 mask to `vcc_lo`.
|
||||
/// `src0` is a VGPR, `s0-s105`, `vcc_lo`, an inline integer or a literal.
|
||||
/// VOPC integer compare writing a Wave32 mask to `vcc_lo`.
|
||||
/// For 64-bit forms register operands name pair bases and the immediate
|
||||
/// contains the low word of a sign-extended inline integer.
|
||||
VectorCompare {
|
||||
op: VectorCompareOp,
|
||||
src0: VectorSource,
|
||||
src1: u8,
|
||||
},
|
||||
/// VOP3A 32-bit integer compare writing a Wave32 mask to s0-s105 or `vcc_lo`.
|
||||
/// Both sources are VGPR indices.
|
||||
VectorCompareVop3 {
|
||||
op: VectorCompareVop3Op,
|
||||
sdst: u8,
|
||||
src0: u8,
|
||||
src1: u8,
|
||||
},
|
||||
/// VOP2 32-bit per-lane integer operation from the semantic registry.
|
||||
/// `src0` is a VGPR, `s0-s105`, `vcc_lo`, an inline integer or a literal;
|
||||
/// `src1` is a VGPR. Inactive lanes keep `dst`.
|
||||
@@ -279,6 +309,8 @@ impl Instruction {
|
||||
Self::WaitLoad => "s_waitcnt",
|
||||
Self::WaitStore => "s_waitcnt_vscnt",
|
||||
Self::MoveB32 { .. } => "v_mov_b32_e32",
|
||||
Self::VectorUnary { op, .. } => op.assembly_name(),
|
||||
Self::VectorSwap { op, .. } => op.assembly_name(),
|
||||
Self::VectorAluVop3 { op, .. } => op.assembly_name(),
|
||||
Self::ScalarUnary { op, .. } => op.mnemonic(),
|
||||
Self::ScalarAlu { op, .. } => op.mnemonic(),
|
||||
@@ -286,6 +318,7 @@ impl Instruction {
|
||||
Self::ScalarImmediate { op, .. } => op.mnemonic(),
|
||||
Self::ScalarImmediateCompare { op, .. } => op.mnemonic(),
|
||||
Self::VectorCompare { op, .. } => op.assembly_name(),
|
||||
Self::VectorCompareVop3 { op, .. } => op.assembly_name(),
|
||||
Self::VectorAlu { op, .. } => op.assembly_name(),
|
||||
Self::BranchSccZero { .. } => "s_cbranch_scc0",
|
||||
Self::BranchExecZero { .. } => "s_cbranch_execz",
|
||||
@@ -330,7 +363,10 @@ impl fmt::Display for Instruction {
|
||||
}
|
||||
Self::WaitLoad => formatter.write_str(" vmcnt(0)"),
|
||||
Self::WaitStore => formatter.write_str(" null, 0"),
|
||||
Self::MoveB32 { dst, src } => write!(formatter, " v{dst}, {src}"),
|
||||
Self::MoveB32 { dst, src } | Self::VectorUnary { dst, src, .. } => {
|
||||
write!(formatter, " v{dst}, {src}")
|
||||
}
|
||||
Self::VectorSwap { dst, src, .. } => write!(formatter, " v{dst}, v{src}"),
|
||||
Self::VectorAluVop3 {
|
||||
dst, src0, src1, ..
|
||||
}
|
||||
@@ -351,13 +387,40 @@ impl fmt::Display for Instruction {
|
||||
Self::ScalarImmediateCompare { src, simm16, .. } => {
|
||||
write!(formatter, " s{src}, {simm16:#x}")
|
||||
}
|
||||
Self::VectorCompare { op, src0, src1 } if op.semantics().width == 64 => {
|
||||
formatter.write_str(" vcc_lo, ")?;
|
||||
match src0 {
|
||||
VectorSource::Register(base) => {
|
||||
write!(formatter, "v[{base}:{}]", u16::from(base) + 1)?;
|
||||
}
|
||||
VectorSource::Scalar(base) => {
|
||||
write!(formatter, "s[{base}:{}]", u16::from(base) + 1)?;
|
||||
}
|
||||
VectorSource::Immediate(bits) => write!(formatter, "{}", bits as i32)?,
|
||||
}
|
||||
write!(formatter, ", v[{src1}:{}]", u16::from(src1) + 1)
|
||||
}
|
||||
Self::VectorCompare { src0, src1, .. } => {
|
||||
write!(formatter, " vcc_lo, {src0}, v{src1}")
|
||||
}
|
||||
Self::VectorCompareVop3 {
|
||||
sdst, src0, src1, ..
|
||||
} => write!(formatter, " {}, v{src0}, v{src1}", ScalarDestination(sdst)),
|
||||
Self::VectorAlu {
|
||||
dst, src0, src1, ..
|
||||
op,
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
} => {
|
||||
write!(formatter, " v{dst}, {src0}, v{src1}")
|
||||
write!(formatter, " v{dst}, ")?;
|
||||
if op.writes_vcc() {
|
||||
write!(formatter, "vcc_lo, ")?;
|
||||
}
|
||||
write!(formatter, "{src0}, v{src1}")?;
|
||||
if op.reads_vcc() {
|
||||
write!(formatter, ", vcc_lo")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Self::Branch { target }
|
||||
| Self::BranchSccZero { target }
|
||||
|
||||
@@ -47,7 +47,7 @@ pub enum Operation {
|
||||
LogicalShiftRight,
|
||||
/// Shift S0 right by the masked count in S1, filling with its sign bit.
|
||||
ArithmeticShiftRight,
|
||||
/// Compare S0 with S1 under the form's relation; writes only SCC.
|
||||
/// Compare S0 with S1 under the form's relation, producing SCC or a lane mask.
|
||||
Compare,
|
||||
/// Bitwise complement of S0.
|
||||
Not,
|
||||
@@ -94,6 +94,35 @@ pub enum Operation {
|
||||
Move,
|
||||
/// SOPK: SDST receives the sign-extended SIMM16 when SCC is set.
|
||||
ConditionalMove,
|
||||
/// Terminate the program.
|
||||
EndProgram,
|
||||
/// Unconditional PC-relative branch.
|
||||
Branch,
|
||||
/// Branch when SCC is clear.
|
||||
BranchSccZero,
|
||||
/// Branch when VCC is zero.
|
||||
BranchVccZero,
|
||||
/// Branch when EXEC is zero.
|
||||
BranchExecZero,
|
||||
/// Complete an outstanding vector load.
|
||||
WaitLoad,
|
||||
/// Swap the two old per-lane VGPR values (guide 12.8).
|
||||
Swap,
|
||||
}
|
||||
|
||||
/// Per-lane integer operation with one input and one result.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum VectorUnary {
|
||||
/// Bitwise complement.
|
||||
Not,
|
||||
/// Reverse bit order.
|
||||
ReverseBits,
|
||||
/// Count leading zeros, or return all ones for zero.
|
||||
FindHighUnsigned,
|
||||
/// Count trailing zeros, or return all ones for zero.
|
||||
FindLow,
|
||||
/// Count leading sign bits, or return all ones if every bit matches.
|
||||
FindHighSigned,
|
||||
}
|
||||
|
||||
/// The per-lane integer operation a vector form lowers to. One reusable MSL
|
||||
@@ -148,13 +177,35 @@ pub enum Signedness {
|
||||
Bitwise,
|
||||
}
|
||||
|
||||
/// Whether the operation reads SCC.
|
||||
/// Per-lane VOP2 operation selected by the semantic registry.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum VectorLowering {
|
||||
/// Two explicit operands, with no implicit lane input.
|
||||
Binary(VectorBinary),
|
||||
/// Two explicit operands and the lane's VCC bit.
|
||||
Vcc(VectorVcc),
|
||||
}
|
||||
|
||||
/// VOP2 primitives with an implicit per-lane VCC input.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum VectorVcc {
|
||||
/// Choose S1 when the VCC bit is set, otherwise S0.
|
||||
Select,
|
||||
/// Unsigned addition with carry-in and carry-out.
|
||||
AddCarry,
|
||||
/// Unsigned subtraction with borrow-in and borrow-out.
|
||||
SubtractBorrow,
|
||||
}
|
||||
|
||||
/// Implicit condition or carry input.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum CarryIn {
|
||||
/// SCC is not read.
|
||||
/// No implicit condition or carry input.
|
||||
None,
|
||||
/// SCC as carry-in (add), borrow-in (sub) or the select condition (select).
|
||||
Scc,
|
||||
/// Per-lane Wave32 VCC_LO bit.
|
||||
Vcc,
|
||||
}
|
||||
|
||||
/// What a form writes to SCC.
|
||||
@@ -176,7 +227,7 @@ pub enum SccEffect {
|
||||
SelectedSrc0,
|
||||
}
|
||||
|
||||
/// What a form writes to VCC or EXEC.
|
||||
/// Where a form writes its lane mask, if any.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum MaskEffect {
|
||||
/// Not written.
|
||||
@@ -185,6 +236,8 @@ pub enum MaskEffect {
|
||||
/// exists) & test(lane n), fully written; `VCC_HI` has no known value after
|
||||
/// it (docs/shaders/vector-compare.md section 3).
|
||||
LaneMask,
|
||||
/// Wave32 VOP3A compare mask written to SDST, which may be `vcc_lo`.
|
||||
SdstLaneMask,
|
||||
}
|
||||
|
||||
/// Wave-size restriction.
|
||||
@@ -218,21 +271,41 @@ pub enum OperandRule {
|
||||
/// SOPK integer compare: SDST (s0-s105) is the left operand, SIMM16 the right
|
||||
/// (sign-extended for `_i32`, zero-extended for `_u32`); only SCC is written.
|
||||
SopkCompare,
|
||||
/// SOPP termination with zero in the reserved immediate field.
|
||||
SoppEnd,
|
||||
/// SOPP branch with a signed dword displacement from the next instruction.
|
||||
SoppBranch,
|
||||
/// SOPP wait with exactly vmcnt(0) and the other counters disabled.
|
||||
SoppWait,
|
||||
/// VOPC vector compare: the destination is `vcc_lo` (Wave32); SRC0 is a VGPR,
|
||||
/// s0-s105, `vcc_lo`, an inline integer -16..64 or a literal word; VSRC1 is a
|
||||
/// VGPR. Everything else is rejected as unsupported.
|
||||
VopcVcc,
|
||||
/// Wave32 VOPC with a VGPR pair, even normal SGPR pair or inline integer
|
||||
/// as SRC0 and a VGPR pair as VSRC1. The destination is `vcc_lo`.
|
||||
VopcVccPair,
|
||||
/// VOPC with low-half operands and no literal selector.
|
||||
VopcVccHalf,
|
||||
/// VOP3 encoding of a VOP2 vector form: VDST is v0-v255, SRC0 and SRC1 are
|
||||
/// VGPRs, no input or output modifiers, SRC2 unused. Everything else is
|
||||
/// rejected as unsupported.
|
||||
Vop3Vgpr2,
|
||||
/// VOP3A compare: VDST encodes s0-s105 or `vcc_lo`; SRC0 and SRC1 are
|
||||
/// VGPRs, SRC2 is unused and all modifiers are clear.
|
||||
Vop3CmpVgpr2,
|
||||
/// VOP2 vector: VDST is v0-v255; SRC0 is a VGPR, s0-s105, `vcc_lo`, an inline
|
||||
/// integer -16..64 or a literal word; VSRC1 is a VGPR. Everything else is
|
||||
/// rejected as unsupported.
|
||||
Vop2Vgpr,
|
||||
/// VOP2 general SRC0 and VGPR VSRC1 with an implicit VCC_LO input.
|
||||
Vop2Vcc,
|
||||
/// VOP2 vector, VGPR sources only: VDST is v0-v255; SRC0 and VSRC1 are VGPRs.
|
||||
/// Everything else (SGPR, inline, literal SRC0) is rejected as unsupported.
|
||||
Vop2Vgpr2,
|
||||
/// VOP1 unary: VGPR VDST and the same SRC0 domain as VOP2.
|
||||
Vop1Vgpr,
|
||||
/// VOP1 swap: VDST and SRC0 each read and write a VGPR.
|
||||
Vop1Swap,
|
||||
}
|
||||
|
||||
/// Evidence a form needs before it counts as verified.
|
||||
@@ -297,7 +370,7 @@ pub struct FormSemantics {
|
||||
pub relation: Option<CompareRelation>,
|
||||
/// SCC write.
|
||||
pub scc: SccEffect,
|
||||
/// VCC write.
|
||||
/// Implicit VCC write or explicit scalar destination for a compare mask.
|
||||
pub vcc: MaskEffect,
|
||||
/// EXEC write.
|
||||
pub exec: MaskEffect,
|
||||
|
||||
+3080
-116
File diff suppressed because it is too large.
Load diff
@@ -2,11 +2,12 @@
|
||||
|
||||
use xenora_isa::meta::{EncodingFamily, FORMS as META_FORMS};
|
||||
use xenora_isa::semantics::{
|
||||
CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, MaskEffect, SCHEMA, SccEffect, Signedness, Wave,
|
||||
CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, MaskEffect, OperandRule, SCHEMA, SccEffect,
|
||||
Signedness, Wave,
|
||||
};
|
||||
use xenora_isa::{
|
||||
CompareRelation, ScalarAluOp, ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp,
|
||||
ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp,
|
||||
ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorCompareVop3Op,
|
||||
};
|
||||
|
||||
#[test]
|
||||
@@ -168,7 +169,16 @@ fn vector_alu_dispatch_selects_exactly_the_registry_vop2_forms() {
|
||||
|
||||
#[test]
|
||||
fn vector_compare_dispatch_selects_exactly_the_registry_vopc_forms() {
|
||||
const OPERANDS: [u32; 6] = [0, 1, 0x7fff_ffff, 0x8000_0000, 0xffff_fffe, 0xffff_ffff];
|
||||
const OPERANDS16: [u64; 6] = [
|
||||
0xaaaa_0000,
|
||||
0x5555_0001,
|
||||
0xdead_7fff,
|
||||
0x8000,
|
||||
0xfffe,
|
||||
0xffff,
|
||||
];
|
||||
const OPERANDS32: [u64; 6] = [0, 1, 0x7fff_ffff, 0x8000_0000, 0xffff_fffe, 0xffff_ffff];
|
||||
const OPERANDS64: [u64; 6] = [0, 1, u64::MAX >> 1, 1 << 63, u64::MAX - 1, u64::MAX];
|
||||
for op in VectorCompareOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Vopc);
|
||||
@@ -187,9 +197,22 @@ fn vector_compare_dispatch_selects_exactly_the_registry_vopc_forms() {
|
||||
);
|
||||
// The per-lane test is the declared relation over the declared
|
||||
// signedness, with SRC0 on the left.
|
||||
for src0 in OPERANDS {
|
||||
for src1 in OPERANDS {
|
||||
let ordering = if op.signed() {
|
||||
let operands = match row.width {
|
||||
16 => OPERANDS16,
|
||||
64 => OPERANDS64,
|
||||
_ => OPERANDS32,
|
||||
};
|
||||
for src0 in operands {
|
||||
for src1 in operands {
|
||||
let ordering = if row.width == 16 {
|
||||
if op.signed() {
|
||||
(src0 as i16).cmp(&(src1 as i16))
|
||||
} else {
|
||||
(src0 as u16).cmp(&(src1 as u16))
|
||||
}
|
||||
} else if op.signed() && row.width == 64 {
|
||||
(src0 as i64).cmp(&(src1 as i64))
|
||||
} else if op.signed() {
|
||||
(src0 as i32).cmp(&(src1 as i32))
|
||||
} else {
|
||||
src0.cmp(&src1)
|
||||
@@ -205,7 +228,7 @@ fn vector_compare_dispatch_selects_exactly_the_registry_vopc_forms() {
|
||||
CompareRelation::True => true,
|
||||
};
|
||||
assert_eq!(
|
||||
op.test(src0, src1),
|
||||
op.test_bits(src0, src1),
|
||||
expected,
|
||||
"{} {src0:#x} {src1:#x}",
|
||||
row.name
|
||||
@@ -213,7 +236,7 @@ fn vector_compare_dispatch_selects_exactly_the_registry_vopc_forms() {
|
||||
}
|
||||
}
|
||||
}
|
||||
// v_cmpx and the 16-, 64-bit and float compares must not be dispatched.
|
||||
// v_cmpx and the float compares must not be dispatched.
|
||||
dispatch_selects_exactly(EncodingFamily::Vopc, |word| {
|
||||
VectorCompareOp::from_word(word).map(|op| op.semantics().name)
|
||||
});
|
||||
@@ -239,8 +262,38 @@ fn vop3_variant_dispatch_selects_exactly_the_registry_vop3_rows() {
|
||||
assert_eq!(row.swap_sources, base.swap_sources);
|
||||
assert_eq!(op.assembly_name(), format!("{}_e64", op.base().mnemonic()));
|
||||
}
|
||||
for base_op in VectorCompareOp::ALL {
|
||||
let base = base_op.semantics();
|
||||
let mut variants = VectorCompareVop3Op::ALL
|
||||
.into_iter()
|
||||
.filter(|op| op.base() == base_op);
|
||||
if base.width != 32 {
|
||||
assert_eq!(variants.next(), None, "{}", base.name);
|
||||
continue;
|
||||
}
|
||||
let op = variants
|
||||
.next()
|
||||
.expect("32-bit VOPC form must have a VOP3A encoding");
|
||||
assert_eq!(variants.next(), None);
|
||||
let row = op.semantics();
|
||||
assert_eq!((row.name, row.family), (base.name, EncodingFamily::Vop3));
|
||||
assert_eq!(row.operation, base.operation);
|
||||
assert_eq!(row.signedness, base.signedness);
|
||||
assert_eq!(row.relation, base.relation);
|
||||
assert_eq!(row.scc, SccEffect::Unchanged);
|
||||
assert_eq!(row.exec, MaskEffect::Unchanged);
|
||||
assert_eq!(row.wave, Wave::Wave32);
|
||||
assert_eq!(row.width, 32);
|
||||
assert_eq!(row.vcc, MaskEffect::SdstLaneMask);
|
||||
assert_eq!(row.operands, OperandRule::Vop3CmpVgpr2);
|
||||
assert_eq!(op.assembly_name(), format!("{}_e64", base_op.mnemonic()));
|
||||
}
|
||||
dispatch_selects_exactly(EncodingFamily::Vop3, |word| {
|
||||
VectorAluVop3Op::from_word(word).map(|op| op.semantics().name)
|
||||
let alu = VectorAluVop3Op::from_word(word);
|
||||
let compare = VectorCompareVop3Op::from_word(word);
|
||||
assert!(alu.is_none() || compare.is_none(), "{word:#x}");
|
||||
alu.map(|op| op.semantics().name)
|
||||
.or_else(|| compare.map(|op| op.semantics().name))
|
||||
});
|
||||
// No first word of the other 64-bit families (VOP3B shares VOP3's
|
||||
// encoding bits) selects a variant.
|
||||
@@ -254,5 +307,11 @@ fn vop3_variant_dispatch_selects_exactly_the_registry_vop3_rows() {
|
||||
"{}",
|
||||
meta.name
|
||||
);
|
||||
assert_eq!(
|
||||
VectorCompareVop3Op::from_word(meta.bits as u32),
|
||||
None,
|
||||
"{}",
|
||||
meta.name
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ gpu-tests = []
|
||||
[dependencies]
|
||||
libc = "0.2"
|
||||
sha2 = "0.10"
|
||||
xenora-texture = { path = "../texture" }
|
||||
|
||||
[dev-dependencies]
|
||||
xenora-metal = { path = "../metal" }
|
||||
@@ -24,3 +25,7 @@ xenora-shader = { path = "../shader" }
|
||||
[[bench]]
|
||||
name = "dbt_bench"
|
||||
harness = false
|
||||
|
||||
[[bench]]
|
||||
name = "service_dispatch"
|
||||
harness = false
|
||||
@@ -1,9 +1,21 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Synthetic interpreter and DBT timings.
|
||||
//!
|
||||
//! Set `XENORA_DBT_BENCH_JSON=<path>` to also write the results as one JSON
|
||||
//! document (format version 1). The text output does not change. Values the
|
||||
//! benchmark cannot determine, such as the git revision outside a checkout,
|
||||
//! are written as `null`.
|
||||
//!
|
||||
//! The benchmark target disables Cargo's test harness. To run the percentile
|
||||
//! unit tests, build with
|
||||
//! `cargo rustc --locked -p xenora-loader --bench dbt_bench --message-format=json -- --test`
|
||||
//! and run the executable named by the benchmark's compiler-artifact message.
|
||||
|
||||
use std::hint::black_box;
|
||||
use std::time::{Duration, Instant};
|
||||
use xenora_loader::cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, Register};
|
||||
use xenora_loader::dbt::DbtEngine;
|
||||
use xenora_loader::dbt::{DbtEngine, DbtMetrics};
|
||||
use xenora_loader::memory::MemoryPermissions;
|
||||
use xenora_loader::pe::{
|
||||
IMAGE_FILE_MACHINE_AMD64, IMAGE_SCN_MEM_EXECUTE, IMAGE_SCN_MEM_READ, PE32_PLUS_MAGIC, ParsedPe,
|
||||
@@ -88,22 +100,231 @@ fn check(result: ExecutionResult) {
|
||||
assert_eq!(result.final_state.get(Register::Rax), ADDS as u64);
|
||||
}
|
||||
|
||||
fn report(label: &str, samples: &mut [Duration]) {
|
||||
fn percentile(sorted: &[Duration], fraction: f64) -> Duration {
|
||||
// Interpolate between adjacent values at rank (n - 1) * fraction.
|
||||
let rank = (sorted.len() - 1) as f64 * fraction;
|
||||
let lower = sorted[rank.floor() as usize];
|
||||
let upper = sorted[rank.ceil() as usize];
|
||||
lower + (upper - lower).mul_f64(rank.fract())
|
||||
}
|
||||
|
||||
/// Order statistics of one timing series, shared by the text and JSON reports.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
struct Summary {
|
||||
samples: usize,
|
||||
median: Duration,
|
||||
min: Duration,
|
||||
max: Duration,
|
||||
p95: Duration,
|
||||
p99: Duration,
|
||||
iqr: Duration,
|
||||
mips: f64,
|
||||
}
|
||||
|
||||
fn summarize(samples: &mut [Duration]) -> Summary {
|
||||
samples.sort_unstable();
|
||||
let median = samples[samples.len() / 2];
|
||||
let min = samples[0];
|
||||
let max = samples[samples.len() - 1];
|
||||
let mips = INSTRUCTIONS as f64 / median.as_secs_f64() / 1_000_000.0;
|
||||
println!(
|
||||
"{label}: {} samples, median {median:?}, min {min:?}, max {max:?}, median {mips:.2} MIPS",
|
||||
samples.len()
|
||||
);
|
||||
let median = percentile(samples, 0.50);
|
||||
Summary {
|
||||
samples: samples.len(),
|
||||
median,
|
||||
min: samples[0],
|
||||
max: samples[samples.len() - 1],
|
||||
p95: percentile(samples, 0.95),
|
||||
p99: percentile(samples, 0.99),
|
||||
iqr: percentile(samples, 0.75) - percentile(samples, 0.25),
|
||||
mips: INSTRUCTIONS as f64 / median.as_secs_f64() / 1_000_000.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn report_line(label: &str, s: &Summary) -> String {
|
||||
format!(
|
||||
"{label}: {} samples, median {:?}, min {:?}, max {:?}, p95 {:?}, p99 {:?}, IQR {:?}, median {:.2} MIPS",
|
||||
s.samples, s.median, s.min, s.max, s.p95, s.p99, s.iqr, s.mips
|
||||
)
|
||||
}
|
||||
|
||||
/// Facts about the run that are not timings. `None` means the benchmark could not
|
||||
/// determine the value.
|
||||
struct RunInfo {
|
||||
unix_time: Option<u64>,
|
||||
cpu: Option<String>,
|
||||
os: &'static str,
|
||||
os_version: Option<String>,
|
||||
arch: &'static str,
|
||||
revision: Option<String>,
|
||||
dirty: Option<bool>,
|
||||
debug_assertions: bool,
|
||||
guest_code_bytes: usize,
|
||||
warmup: usize,
|
||||
}
|
||||
|
||||
fn command_output(program: &str, args: &[&str]) -> Option<String> {
|
||||
let output = std::process::Command::new(program)
|
||||
.args(args)
|
||||
.output()
|
||||
.ok()?;
|
||||
if !output.status.success() {
|
||||
return None;
|
||||
}
|
||||
Some(String::from_utf8(output.stdout).ok()?.trim().to_owned())
|
||||
}
|
||||
|
||||
fn run_info(guest_code_bytes: usize, warmup: usize) -> RunInfo {
|
||||
let non_empty = |value: Option<String>| value.filter(|v| !v.is_empty());
|
||||
RunInfo {
|
||||
unix_time: std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.ok()
|
||||
.map(|d| d.as_secs()),
|
||||
cpu: non_empty(command_output(
|
||||
"sysctl",
|
||||
&["-n", "machdep.cpu.brand_string"],
|
||||
)),
|
||||
os: std::env::consts::OS,
|
||||
os_version: non_empty(command_output("sw_vers", &["-productVersion"])),
|
||||
arch: std::env::consts::ARCH,
|
||||
revision: non_empty(command_output("git", &["rev-parse", "HEAD"])),
|
||||
dirty: command_output("git", &["status", "--porcelain", "--untracked-files=no"])
|
||||
.map(|status| !status.is_empty()),
|
||||
debug_assertions: cfg!(debug_assertions),
|
||||
guest_code_bytes,
|
||||
warmup,
|
||||
}
|
||||
}
|
||||
|
||||
fn json_string(value: &str) -> String {
|
||||
let mut out = String::with_capacity(value.len() + 2);
|
||||
out.push('"');
|
||||
for c in value.chars() {
|
||||
match c {
|
||||
'"' => out.push_str("\\\""),
|
||||
'\\' => out.push_str("\\\\"),
|
||||
'\n' => out.push_str("\\n"),
|
||||
'\r' => out.push_str("\\r"),
|
||||
'\t' => out.push_str("\\t"),
|
||||
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out.push('"');
|
||||
out
|
||||
}
|
||||
|
||||
fn json_option<T>(value: Option<T>, render: impl FnOnce(T) -> String) -> String {
|
||||
value.map_or_else(|| "null".to_owned(), render)
|
||||
}
|
||||
|
||||
/// JSON has no infinity or NaN, so a non-finite rate (a zero median) is `null`.
|
||||
fn json_f64(value: f64) -> String {
|
||||
if value.is_finite() {
|
||||
format!("{value}")
|
||||
} else {
|
||||
"null".to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
fn json_object(fields: &[(&str, String)]) -> String {
|
||||
let body: Vec<String> = fields
|
||||
.iter()
|
||||
.map(|(key, value)| format!("{}:{value}", json_string(key)))
|
||||
.collect();
|
||||
format!("{{{}}}", body.join(","))
|
||||
}
|
||||
|
||||
fn json_summary(s: &Summary) -> String {
|
||||
json_object(&[
|
||||
("samples", s.samples.to_string()),
|
||||
("median_ns", s.median.as_nanos().to_string()),
|
||||
("min_ns", s.min.as_nanos().to_string()),
|
||||
("max_ns", s.max.as_nanos().to_string()),
|
||||
("p95_ns", s.p95.as_nanos().to_string()),
|
||||
("p99_ns", s.p99.as_nanos().to_string()),
|
||||
("iqr_ns", s.iqr.as_nanos().to_string()),
|
||||
("median_mips", json_f64(s.mips)),
|
||||
])
|
||||
}
|
||||
|
||||
fn json_document(
|
||||
info: &RunInfo,
|
||||
interpreter: &Summary,
|
||||
cold: &Summary,
|
||||
warm: &Summary,
|
||||
metrics: &DbtMetrics,
|
||||
) -> String {
|
||||
let string = |value: &String| json_string(value);
|
||||
json_object(&[
|
||||
("format_version", "1".to_owned()),
|
||||
("benchmark", json_string("dbt_bench")),
|
||||
("unix_time", json_option(info.unix_time, |t| t.to_string())),
|
||||
(
|
||||
"host",
|
||||
json_object(&[
|
||||
("cpu", json_option(info.cpu.as_ref(), string)),
|
||||
("os", json_string(info.os)),
|
||||
("os_version", json_option(info.os_version.as_ref(), string)),
|
||||
("arch", json_string(info.arch)),
|
||||
]),
|
||||
),
|
||||
(
|
||||
"source",
|
||||
json_object(&[
|
||||
("revision", json_option(info.revision.as_ref(), string)),
|
||||
("dirty", json_option(info.dirty, |d| d.to_string())),
|
||||
]),
|
||||
),
|
||||
(
|
||||
"build",
|
||||
json_object(&[("debug_assertions", info.debug_assertions.to_string())]),
|
||||
),
|
||||
(
|
||||
"workload",
|
||||
json_object(&[
|
||||
("name", json_string("add_rax_chain")),
|
||||
("guest_instructions", INSTRUCTIONS.to_string()),
|
||||
("guest_code_bytes", info.guest_code_bytes.to_string()),
|
||||
("instruction_budget", BUDGET.to_string()),
|
||||
("warmup_rounds", info.warmup.to_string()),
|
||||
]),
|
||||
),
|
||||
(
|
||||
"timings",
|
||||
json_object(&[
|
||||
("interpreter", json_summary(interpreter)),
|
||||
("cold_dbt", json_summary(cold)),
|
||||
("warm_dbt", json_summary(warm)),
|
||||
]),
|
||||
),
|
||||
(
|
||||
"cold_dbt_metrics",
|
||||
json_object(&[
|
||||
("blocks_compiled", metrics.blocks_compiled.to_string()),
|
||||
("cache_hits", metrics.cache_hits.to_string()),
|
||||
("cache_misses", metrics.cache_misses.to_string()),
|
||||
(
|
||||
"native_bytes_emitted",
|
||||
metrics.native_bytes_emitted.to_string(),
|
||||
),
|
||||
("dbt_dispatches", metrics.dbt_dispatches.to_string()),
|
||||
(
|
||||
"instructions_executed",
|
||||
metrics.instructions_executed.to_string(),
|
||||
),
|
||||
(
|
||||
"interpreter_fallbacks",
|
||||
metrics.interpreter_fallbacks.to_string(),
|
||||
),
|
||||
("service_calls", metrics.service_calls.to_string()),
|
||||
]),
|
||||
),
|
||||
])
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let sample_count = std::env::var("XENORA_DBT_BENCH_SAMPLES")
|
||||
.map_or(101, |value| value.parse::<usize>().expect("sample count"));
|
||||
assert!(sample_count > 0);
|
||||
let warmup_count = std::env::var("XENORA_DBT_BENCH_WARMUP")
|
||||
.map_or(10, |value| value.parse::<usize>().expect("warmup count"));
|
||||
|
||||
let mut code = vec![0x48, 0xB8, 0, 0, 0, 0, 0, 0, 0, 0]; // mov rax, 0
|
||||
for _ in 0..ADDS {
|
||||
@@ -124,44 +345,239 @@ fn main() {
|
||||
let mut warm = Vec::with_capacity(sample_count);
|
||||
let mut cold_metrics = None;
|
||||
|
||||
for _ in 0..sample_count {
|
||||
for record in
|
||||
std::iter::repeat_n(false, warmup_count).chain(std::iter::repeat_n(true, sample_count))
|
||||
{
|
||||
let mut interp = Interpreter::new(initial_cpu.clone(), &mut loaded.memory, BUDGET);
|
||||
let start = Instant::now();
|
||||
let result = black_box(interp.run());
|
||||
interpreter.push(start.elapsed());
|
||||
let interpreter_time = start.elapsed();
|
||||
check(result);
|
||||
|
||||
let mut dbt = DbtEngine::new(4 * 1024 * 1024).unwrap();
|
||||
let mut cpu = initial_cpu.clone();
|
||||
let start = Instant::now();
|
||||
let result = black_box(dbt.run(&mut cpu, &mut loaded.memory, BUDGET));
|
||||
cold.push(start.elapsed());
|
||||
let cold_time = start.elapsed();
|
||||
check(result);
|
||||
assert!(dbt.metrics.blocks_compiled > 0);
|
||||
assert_eq!(dbt.metrics.cache_hits, 0);
|
||||
assert_eq!(dbt.metrics.cache_misses, dbt.metrics.blocks_compiled);
|
||||
cold_metrics = Some(dbt.metrics);
|
||||
let metrics = dbt.metrics;
|
||||
|
||||
let mut cpu = initial_cpu.clone();
|
||||
let start = Instant::now();
|
||||
let result = black_box(dbt.run(&mut cpu, &mut loaded.memory, BUDGET));
|
||||
warm.push(start.elapsed());
|
||||
let warm_time = start.elapsed();
|
||||
check(result);
|
||||
assert_eq!(
|
||||
Some(dbt.metrics.blocks_compiled),
|
||||
cold_metrics.map(|m| m.blocks_compiled)
|
||||
);
|
||||
assert_eq!(dbt.metrics.blocks_compiled, metrics.blocks_compiled);
|
||||
assert_eq!(dbt.metrics.cache_hits, dbt.metrics.blocks_compiled);
|
||||
assert_eq!(dbt.metrics.cache_misses, dbt.metrics.blocks_compiled);
|
||||
|
||||
if record {
|
||||
interpreter.push(interpreter_time);
|
||||
cold.push(cold_time);
|
||||
warm.push(warm_time);
|
||||
cold_metrics = Some(metrics);
|
||||
}
|
||||
}
|
||||
|
||||
println!("{INSTRUCTIONS} guest instructions per sample, final RAX={ADDS}");
|
||||
report("Interpreter", &mut interpreter);
|
||||
report("Cold DBT", &mut cold);
|
||||
report("Warm DBT", &mut warm);
|
||||
println!("{warmup_count} warmup rounds excluded (XENORA_DBT_BENCH_WARMUP, default 10)");
|
||||
println!(
|
||||
"Cold DBT includes translation with a fresh engine; warm DBT reuses that engine's cache."
|
||||
);
|
||||
println!(
|
||||
"Percentiles describe this synthetic workload on this host; tail estimates vary with sample count."
|
||||
);
|
||||
println!("Even sample counts use the midpoint of the two middle values for the median.");
|
||||
let interpreter = summarize(&mut interpreter);
|
||||
let cold = summarize(&mut cold);
|
||||
let warm = summarize(&mut warm);
|
||||
println!("{}", report_line("Interpreter", &interpreter));
|
||||
println!("{}", report_line("Cold DBT", &cold));
|
||||
println!("{}", report_line("Warm DBT", &warm));
|
||||
let metrics = cold_metrics.unwrap();
|
||||
println!(
|
||||
"Cold DBT compiled {} blocks and emitted {} native bytes in {} dispatches",
|
||||
metrics.blocks_compiled, metrics.native_bytes_emitted, metrics.dbt_dispatches
|
||||
);
|
||||
|
||||
if let Some(path) = std::env::var_os("XENORA_DBT_BENCH_JSON") {
|
||||
let info = run_info(code.len(), warmup_count);
|
||||
let document = json_document(&info, &interpreter, &cold, &warm, &metrics);
|
||||
std::fs::write(&path, document + "\n").expect("write XENORA_DBT_BENCH_JSON");
|
||||
println!("JSON results written to {}", path.to_string_lossy());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn single_sample_has_no_spread() {
|
||||
use super::{Duration, percentile};
|
||||
|
||||
let samples = [Duration::from_micros(50)];
|
||||
for fraction in [0.25, 0.50, 0.75, 0.95, 0.99] {
|
||||
assert_eq!(percentile(&samples, fraction), samples[0]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn percentiles_interpolate_across_even_samples() {
|
||||
use super::{Duration, percentile};
|
||||
|
||||
let samples = [10, 20, 30, 100].map(Duration::from_micros);
|
||||
assert_eq!(percentile(&samples, 0.50), Duration::from_micros(25));
|
||||
assert_eq!(percentile(&samples, 0.95), Duration::from_nanos(89_500));
|
||||
assert_eq!(percentile(&samples, 0.99), Duration::from_nanos(97_900));
|
||||
assert_eq!(
|
||||
percentile(&samples, 0.75) - percentile(&samples, 0.25),
|
||||
Duration::from_nanos(30_000)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn median_uses_the_middle_of_odd_samples() {
|
||||
use super::{Duration, percentile};
|
||||
|
||||
let samples = [10, 20, 100].map(Duration::from_micros);
|
||||
assert_eq!(percentile(&samples, 0.50), Duration::from_micros(20));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_strings_escape_quotes_backslashes_and_controls() {
|
||||
use super::json_string;
|
||||
|
||||
assert_eq!(json_string("plain"), r#""plain""#);
|
||||
assert_eq!(json_string(r#"a"b\c"#), r#""a\"b\\c""#);
|
||||
assert_eq!(json_string("l1\nl2\r\t"), r#""l1\nl2\r\t""#);
|
||||
assert_eq!(json_string("\u{1}\u{1f}"), r#""\u0001\u001f""#);
|
||||
// Non-ASCII text needs no escape in UTF-8 JSON.
|
||||
assert_eq!(json_string("Zażółć"), "\"Zażółć\"");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_values_and_non_finite_rates_are_null() {
|
||||
use super::{json_f64, json_option};
|
||||
|
||||
assert_eq!(json_option(None::<u64>, |v| v.to_string()), "null");
|
||||
assert_eq!(json_option(Some(7_u64), |v| v.to_string()), "7");
|
||||
assert_eq!(json_f64(f64::INFINITY), "null");
|
||||
assert_eq!(json_f64(f64::NAN), "null");
|
||||
assert_eq!(json_f64(12.5), "12.5");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn document_has_every_field_with_the_summary_values() {
|
||||
fn fixed_summary(median_us: u64) -> super::Summary {
|
||||
use super::Duration;
|
||||
super::Summary {
|
||||
samples: 3,
|
||||
median: Duration::from_micros(median_us),
|
||||
min: Duration::from_micros(10),
|
||||
max: Duration::from_micros(100),
|
||||
p95: Duration::from_nanos(92_000),
|
||||
p99: Duration::from_nanos(98_400),
|
||||
iqr: Duration::from_micros(45),
|
||||
mips: 500.25,
|
||||
}
|
||||
}
|
||||
|
||||
fn fixed_info() -> super::RunInfo {
|
||||
super::RunInfo {
|
||||
unix_time: Some(1_700_000_000),
|
||||
cpu: Some("Test \"CPU\"\\1".to_owned()),
|
||||
os: "macos",
|
||||
os_version: None,
|
||||
arch: "aarch64",
|
||||
revision: Some("0123abcd".to_owned()),
|
||||
dirty: Some(false),
|
||||
debug_assertions: false,
|
||||
guest_code_bytes: 40_011,
|
||||
warmup: 10,
|
||||
}
|
||||
}
|
||||
|
||||
use super::{DbtMetrics, INSTRUCTIONS, json_document};
|
||||
|
||||
let metrics = DbtMetrics {
|
||||
blocks_compiled: 626,
|
||||
cache_hits: 0,
|
||||
cache_misses: 626,
|
||||
native_bytes_emitted: 245_168,
|
||||
dbt_dispatches: 626,
|
||||
instructions_executed: 10_002,
|
||||
interpreter_fallbacks: 1,
|
||||
service_calls: 0,
|
||||
};
|
||||
let document = json_document(
|
||||
&fixed_info(),
|
||||
&fixed_summary(20),
|
||||
&fixed_summary(30),
|
||||
&fixed_summary(40),
|
||||
&metrics,
|
||||
);
|
||||
let summary = |median: &str| {
|
||||
format!(
|
||||
r#"{{"samples":3,"median_ns":{median},"min_ns":10000,"max_ns":100000,"p95_ns":92000,"p99_ns":98400,"iqr_ns":45000,"median_mips":500.25}}"#
|
||||
)
|
||||
};
|
||||
let expected = format!(
|
||||
concat!(
|
||||
r#"{{"format_version":1,"benchmark":"dbt_bench","unix_time":1700000000,"#,
|
||||
r#""host":{{"cpu":"Test \"CPU\"\\1","os":"macos","os_version":null,"arch":"aarch64"}},"#,
|
||||
r#""source":{{"revision":"0123abcd","dirty":false}},"#,
|
||||
r#""build":{{"debug_assertions":false}},"#,
|
||||
r#""workload":{{"name":"add_rax_chain","guest_instructions":{},"guest_code_bytes":40011,"instruction_budget":20000,"warmup_rounds":10}},"#,
|
||||
r#""timings":{{"interpreter":{},"cold_dbt":{},"warm_dbt":{}}},"#,
|
||||
r#""cold_dbt_metrics":{{"blocks_compiled":626,"cache_hits":0,"cache_misses":626,"native_bytes_emitted":245168,"dbt_dispatches":626,"instructions_executed":10002,"interpreter_fallbacks":1,"service_calls":0}}}}"#,
|
||||
),
|
||||
INSTRUCTIONS,
|
||||
summary("20000"),
|
||||
summary("30000"),
|
||||
summary("40000"),
|
||||
);
|
||||
assert_eq!(document, expected);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_report_keeps_its_format() {
|
||||
fn fixed_summary(median_us: u64) -> super::Summary {
|
||||
use super::Duration;
|
||||
super::Summary {
|
||||
samples: 3,
|
||||
median: Duration::from_micros(median_us),
|
||||
min: Duration::from_micros(10),
|
||||
max: Duration::from_micros(100),
|
||||
p95: Duration::from_nanos(92_000),
|
||||
p99: Duration::from_nanos(98_400),
|
||||
iqr: Duration::from_micros(45),
|
||||
mips: 500.25,
|
||||
}
|
||||
}
|
||||
|
||||
use super::report_line;
|
||||
|
||||
assert_eq!(
|
||||
report_line("Cold DBT", &fixed_summary(20)),
|
||||
"Cold DBT: 3 samples, median 20µs, min 10µs, max 100µs, p95 92µs, p99 98.4µs, IQR 45µs, median 500.25 MIPS"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn summary_matches_the_percentile_helper() {
|
||||
use super::{Duration, INSTRUCTIONS, summarize};
|
||||
|
||||
let mut samples = [100, 10, 30, 20].map(Duration::from_micros);
|
||||
let s = summarize(&mut samples);
|
||||
assert_eq!(s.samples, 4);
|
||||
assert_eq!(s.median, Duration::from_micros(25));
|
||||
assert_eq!(s.min, Duration::from_micros(10));
|
||||
assert_eq!(s.max, Duration::from_micros(100));
|
||||
assert_eq!(s.p95, Duration::from_nanos(89_500));
|
||||
assert_eq!(s.p99, Duration::from_nanos(97_900));
|
||||
assert_eq!(s.iqr, Duration::from_micros(30));
|
||||
assert_eq!(s.mips, INSTRUCTIONS as f64 / 25e-6 / 1e6);
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,9 @@
|
||||
differs. Never writes.
|
||||
|
||||
Rejects unknown keys and vocabulary, overlapping encodings, digit and plain
|
||||
forms sharing an opcode, operand constraints that contradict each other, and
|
||||
flags declared both written and undefined. Standard library only (Python 3.11+).
|
||||
forms sharing an opcode, operand constraints that contradict each other, LOCK
|
||||
on a form that cannot write memory, and flags declared both written and
|
||||
undefined. Standard library only (Python 3.11+).
|
||||
"""
|
||||
|
||||
import sys
|
||||
@@ -26,7 +27,7 @@ RUST = HERE / "src/x86_table.rs"
|
||||
TOP_KEYS = {"schema", "architecture", "documents", "operation", "alu", "form", "group"}
|
||||
OPERATION_KEYS = {"reads", "writes", "undefined", "conditional", "terminator", "faults", "ref"}
|
||||
FORM_KEYS = {"op", "map", "prefix", "opcode", "count", "digit", "enc", "size", "imm", "src",
|
||||
"memory_only", "register_only", "no_rex_b", "unaligned"}
|
||||
"memory_only", "register_only", "no_rex_b", "unaligned", "lock"}
|
||||
GROUP_KEYS = {"map", "opcodes", "digits"}
|
||||
FLAGS = ["cf", "zf", "sf", "of", "pf", "af"]
|
||||
MAPS = {"1": "ONE_BYTE", "0f": "TWO_BYTE"}
|
||||
@@ -39,6 +40,7 @@ SRCS = {"": 0, "b": 1, "w": 2, "d": 4, "q": 8, "x": 16}
|
||||
# encoding -> (Rust variant, has ModRM, required immediates)
|
||||
ENCS = {
|
||||
"none": ("None", False, {""}),
|
||||
"string": ("String", False, {""}),
|
||||
"rm_reg": ("RmReg", True, {""}),
|
||||
"reg_rm": ("RegRm", True, {""}),
|
||||
"reg_rm_imm": ("RegRmImm", True, {"ib", "iz"}),
|
||||
@@ -48,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"}),
|
||||
@@ -63,6 +67,8 @@ ENCS = {
|
||||
"reg_xmm": ("RegXmm", True, {""}),
|
||||
"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_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.
|
||||
@@ -171,6 +177,8 @@ def load(text):
|
||||
if (form["size"] == "x") != (form["enc"] in XMM_RM - {"reg_xmm", "reg_xmm_imm"}
|
||||
or form["enc"] == "xmm_gpr_imm"):
|
||||
fail(f"{where}: XMM size does not match the encoding")
|
||||
if form.get("lock") and (form["enc"] not in RM_DESTINATIONS or form.get("register_only")):
|
||||
fail(f"{where}: LOCK needs a memory destination")
|
||||
if form.get("unaligned") and form["src"] != "x":
|
||||
fail(f"{where}: alignment applies only to 16-byte operands")
|
||||
if form["prefix"] and form["map"] != "0f":
|
||||
@@ -266,7 +274,8 @@ def generate(operations, forms):
|
||||
f"memory_only: {str(bool(form.get('memory_only'))).lower()}, "
|
||||
f"register_only: {str(bool(form.get('register_only'))).lower()}, "
|
||||
f"no_rex_b: {str(bool(form.get('no_rex_b'))).lower()}, "
|
||||
f"unaligned: {str(bool(form.get('unaligned'))).lower()} }},")
|
||||
f"unaligned: {str(bool(form.get('unaligned'))).lower()}, "
|
||||
f"lockable: {str(bool(form.get('lock'))).lower()} }},")
|
||||
out += ["];", ""]
|
||||
|
||||
groups = []
|
||||
|
||||
+217
-21
@@ -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)
|
||||
@@ -430,6 +434,46 @@ impl Arm64Assembler {
|
||||
);
|
||||
}
|
||||
|
||||
/// ADCS (64-bit, flags updating): ADCS Xd, Xn, Xm computes Xn + Xm + C.
|
||||
pub fn adcs_reg_64(&mut self, xd: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
0xba000000
|
||||
| ((xm as u32 & 0x1f) << 16)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// ADCS (32-bit, flags updating): ADCS Wd, Wn, Wm computes Wn + Wm + C.
|
||||
pub fn adcs_reg_32(&mut self, wd: u8, wn: u8, wm: u8) {
|
||||
self.emit(
|
||||
0x3a000000
|
||||
| ((wm as u32 & 0x1f) << 16)
|
||||
| ((wn as u32 & 0x1f) << 5)
|
||||
| (wd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// SBCS (64-bit, flags updating): SBCS Xd, Xn, Xm computes Xn - Xm - !C.
|
||||
pub fn sbcs_reg_64(&mut self, xd: u8, xn: u8, xm: u8) {
|
||||
self.emit(
|
||||
0xfa000000
|
||||
| ((xm as u32 & 0x1f) << 16)
|
||||
| ((xn as u32 & 0x1f) << 5)
|
||||
| (xd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// SBCS (32-bit, flags updating): SBCS Wd, Wn, Wm computes Wn - Wm - !C.
|
||||
pub fn sbcs_reg_32(&mut self, wd: u8, wn: u8, wm: u8) {
|
||||
self.emit(
|
||||
0x7a000000
|
||||
| ((wm as u32 & 0x1f) << 16)
|
||||
| ((wn as u32 & 0x1f) << 5)
|
||||
| (wd as u32 & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// ADD (immediate, 64-bit): ADD Xd, Xn, #imm12
|
||||
pub fn add_imm_64(&mut self, xd: u8, xn: u8, imm12: u16) {
|
||||
self.emit(
|
||||
@@ -582,22 +626,35 @@ impl Arm64Assembler {
|
||||
self.emit(0xf2800000 | (hw << 21) | ((imm16 as u32) << 5) | (xd as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// Load a full 64-bit constant into register Xd.
|
||||
pub fn load_imm_64(&mut self, xd: u8, val: u64) {
|
||||
let w0 = (val & 0xffff) as u16;
|
||||
let w1 = ((val >> 16) & 0xffff) as u16;
|
||||
let w2 = ((val >> 32) & 0xffff) as u16;
|
||||
let w3 = ((val >> 48) & 0xffff) as u16;
|
||||
/// MOVN (64-bit with shift): MOVN Xd, #imm16, LSL #shift writes
|
||||
/// NOT (imm16 << shift), so every other halfword becomes 0xFFFF.
|
||||
pub fn movn_64(&mut self, xd: u8, imm16: u16, shift_idx: u8) {
|
||||
let hw = (shift_idx & 3) as u32;
|
||||
self.emit(0x92800000 | (hw << 21) | ((imm16 as u32) << 5) | (xd as u32 & 0x1f));
|
||||
}
|
||||
|
||||
self.movz_64(xd, w0, 0);
|
||||
if w1 != 0 || (w2 == 0 && w3 == 0) {
|
||||
self.movk_64(xd, w1, 1);
|
||||
/// Load a full 64-bit constant into register Xd with the fewest MOVZ or
|
||||
/// MOVN plus MOVK instructions: one for each halfword that differs from
|
||||
/// the background the first instruction leaves, and always at least one.
|
||||
/// MOVZ leaves zero halfwords and MOVN leaves 0xFFFF ones, so MOVN is used
|
||||
/// when more halfwords are 0xFFFF than zero.
|
||||
pub fn load_imm_64(&mut self, xd: u8, val: u64) {
|
||||
let halves: [u16; 4] = std::array::from_fn(|i| (val >> (16 * i)) as u16);
|
||||
let zeros = halves.iter().filter(|&&h| h == 0).count();
|
||||
let ones = halves.iter().filter(|&&h| h == 0xffff).count();
|
||||
let background = if ones > zeros { 0xffff } else { 0 };
|
||||
// The first halfword that differs from the background, or halfword 0
|
||||
// when none does (val is 0 or all ones).
|
||||
let first = halves.iter().position(|&h| h != background).unwrap_or(0);
|
||||
if background == 0 {
|
||||
self.movz_64(xd, halves[first], first as u8);
|
||||
} else {
|
||||
self.movn_64(xd, !halves[first], first as u8);
|
||||
}
|
||||
if w2 != 0 || w3 != 0 {
|
||||
self.movk_64(xd, w2, 2);
|
||||
}
|
||||
if w3 != 0 {
|
||||
self.movk_64(xd, w3, 3);
|
||||
for (index, &half) in halves.iter().enumerate().skip(first + 1) {
|
||||
if half != background {
|
||||
self.movk_64(xd, half, index as u8);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -778,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();
|
||||
@@ -786,4 +881,105 @@ mod tests {
|
||||
asm.str_uoff_32(X0, X19, 136);
|
||||
assert_eq!(asm.instructions(), &[0xf90013f5, 0xf9404269, 0xb9008a60]);
|
||||
}
|
||||
|
||||
/// Constants at the halfword boundaries the MOVZ/MOVN choice depends on.
|
||||
const IMMEDIATE_EDGES: [u64; 16] = [
|
||||
0,
|
||||
1,
|
||||
0xffff,
|
||||
0x1_0000,
|
||||
0x8000_0000,
|
||||
0xffff_ffff,
|
||||
0x1_0000_0000,
|
||||
0x1234_0000_0000_0000,
|
||||
0x0000_0001_0000_0005,
|
||||
0x1234_5678_9abc_def0,
|
||||
0x7fff_ffff_ffff_ffff,
|
||||
0x8000_0000_0000_0000,
|
||||
0xffff_0000_ffff_ffff,
|
||||
0xffff_ffff_edcc_5678,
|
||||
0xffff_ffff_ffff_1234,
|
||||
u64::MAX,
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn immediate_sequences_match_llvm_encodings() {
|
||||
// llvm-mc -triple=aarch64-apple-macos -show-encoding.
|
||||
let cases: &[(u64, &[u32])] = &[
|
||||
(0, &[0xd2800000]), // movz x0, #0
|
||||
(u64::MAX, &[0x92800000]), // movn x0, #0
|
||||
(0xffff_ffff_ffff_1234, &[0x929db960]), // movn x0, #0xedcb
|
||||
(0x1234_0000_0000_0000, &[0xd2e24680]), // movz x0, #0x1234, lsl #48
|
||||
(0xffff_0000_ffff_ffff, &[0x92dfffe0]), // movn x0, #0xffff, lsl #32
|
||||
(0x0000_0001_0000_0005, &[0xd28000a0, 0xf2c00020]), // movz #5; movk #1, lsl #32
|
||||
// movn x0, #0xa987; movk x0, #0xedcc, lsl #16
|
||||
(0xffff_ffff_edcc_5678, &[0x929530e0, 0xf2bdb980]),
|
||||
];
|
||||
for &(value, expected) in cases {
|
||||
let mut asm = Arm64Assembler::new();
|
||||
asm.load_imm_64(X0, value);
|
||||
assert_eq!(asm.instructions(), expected, "{value:#x}");
|
||||
}
|
||||
// movz x9, #0xdef0; movk x9, #0x9abc, lsl #16; #0x5678, lsl #32;
|
||||
// #0x1234, lsl #48
|
||||
let mut asm = Arm64Assembler::new();
|
||||
asm.load_imm_64(X9, 0x1234_5678_9abc_def0);
|
||||
assert_eq!(
|
||||
asm.instructions(),
|
||||
&[0xd29bde09, 0xf2b35789, 0xf2cacf09, 0xf2e24689]
|
||||
);
|
||||
}
|
||||
|
||||
/// Fewest MOVZ/MOVN/MOVK instructions for `value`: every halfword that is
|
||||
/// neither zero (after MOVZ) nor 0xFFFF (after MOVN), and at least one.
|
||||
fn shortest_wide_move(value: u64) -> usize {
|
||||
let halves = (0..4).map(|i| (value >> (16 * i)) & 0xffff);
|
||||
let not_zero = halves.clone().filter(|&h| h != 0).count();
|
||||
let not_ones = halves.filter(|&h| h != 0xffff).count();
|
||||
not_zero.min(not_ones).max(1)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn immediates_run_on_the_host_and_use_the_fewest_wide_moves() {
|
||||
let mut values = IMMEDIATE_EDGES.to_vec();
|
||||
let mut state = 0x9e37_79b9_7f4a_7c15u64;
|
||||
for _ in 0..512 {
|
||||
state ^= state >> 12;
|
||||
state ^= state << 25;
|
||||
state ^= state >> 27;
|
||||
let raw = state.wrapping_mul(0x2545_f491_4f6c_dd1d);
|
||||
// Force some halfwords to zero or all ones so both MOVZ and MOVN
|
||||
// sequences of every length occur.
|
||||
let mut value = raw;
|
||||
for half in 0..4 {
|
||||
match (raw >> (60 - 2 * half)) & 3 {
|
||||
0 => value &= !(0xffff << (16 * half)),
|
||||
1 => value |= 0xffff << (16 * half),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
values.push(value);
|
||||
}
|
||||
let mut jit = crate::jit::JitMemory::new(64 * 1024).unwrap();
|
||||
for value in values {
|
||||
for register in [X0, X9] {
|
||||
let mut asm = Arm64Assembler::new();
|
||||
asm.load_imm_64(register, value);
|
||||
assert_eq!(
|
||||
asm.instructions().len(),
|
||||
shortest_wide_move(value),
|
||||
"{value:#x}"
|
||||
);
|
||||
if register != X0 {
|
||||
asm.mov_reg_64(X0, register);
|
||||
}
|
||||
asm.ret();
|
||||
let entry = jit.emit_block(asm.instructions()).unwrap();
|
||||
// SAFETY: the block is a complete AAPCS64 leaf function that
|
||||
// writes only X0 (and X9, a caller-saved register) and returns.
|
||||
let function: extern "C" fn() -> u64 = unsafe { std::mem::transmute(entry) };
|
||||
assert_eq!(function(), value, "{value:#x} in x{register}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -97,6 +97,8 @@ pub struct CpuState {
|
||||
/// XMM0-XMM15, lane 0 in the low bits.
|
||||
pub xmm: [u128; 16],
|
||||
pub mxcsr: Mxcsr,
|
||||
/// Direction flag: string instructions step RSI and RDI down when set.
|
||||
pub df: bool,
|
||||
}
|
||||
|
||||
impl CpuState {
|
||||
@@ -111,6 +113,7 @@ impl CpuState {
|
||||
fs_base: 0,
|
||||
xmm: [0; 16],
|
||||
mxcsr: Mxcsr::default(),
|
||||
df: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -123,6 +126,35 @@ impl CpuState {
|
||||
}
|
||||
}
|
||||
|
||||
/// CPUID leaf 1, EDX: CMOVcc.
|
||||
pub const CPUID_CMOV: u32 = 1 << 15;
|
||||
/// CPUID leaf 1, ECX: POPCNT.
|
||||
pub const CPUID_POPCNT: u32 = 1 << 23;
|
||||
/// CPUID leaf 0x8000_0001, ECX: LZCNT.
|
||||
pub const CPUID_LZCNT: u32 = 1 << 5;
|
||||
/// CPUID leaf 0x8000_0001, EDX: 64-bit mode.
|
||||
pub const CPUID_LONG_MODE: u32 = 1 << 29;
|
||||
|
||||
/// What the guest's CPUID returns in EAX, EBX, ECX and EDX.
|
||||
///
|
||||
/// The table is fixed and never reads the host. It names a synthetic
|
||||
/// processor, not an Intel or AMD product, and sets a feature bit only when
|
||||
/// every instruction of that feature is implemented. A leaf that is not
|
||||
/// listed returns zeros.
|
||||
pub fn cpuid(leaf: u32, _subleaf: u32) -> [u32; 4] {
|
||||
let word = |text: &[u8; 4]| u32::from_le_bytes(*text);
|
||||
match leaf {
|
||||
// Highest basic leaf, then "Xenora guest" in EBX, EDX, ECX.
|
||||
0 => [1, word(b"Xeno"), word(b"uest"), word(b"ra g")],
|
||||
// No family, model or stepping: this is no shipped processor.
|
||||
1 => [0, 0, CPUID_POPCNT, CPUID_CMOV],
|
||||
// Highest extended leaf.
|
||||
0x8000_0000 => [0x8000_0001, 0, 0, 0],
|
||||
0x8000_0001 => [0, 0, CPUID_LZCNT, CPUID_LONG_MODE],
|
||||
_ => [0; 4],
|
||||
}
|
||||
}
|
||||
|
||||
/// Termination reason for guest execution.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ExitReason {
|
||||
@@ -135,12 +167,21 @@ 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.
|
||||
GuestYield,
|
||||
/// The running guest thread ended itself.
|
||||
GuestThreadExited,
|
||||
}
|
||||
|
||||
impl fmt::Display for ExitReason {
|
||||
@@ -156,9 +197,13 @@ 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")
|
||||
}
|
||||
Self::GuestBlocked => write!(f, "guest thread is waiting"),
|
||||
Self::GuestYield => write!(f, "guest thread gave up its turn"),
|
||||
Self::GuestThreadExited => write!(f, "guest thread exited"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+320
-2
@@ -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,11 +82,61 @@ 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,
|
||||
memory: &mut GuestMemory,
|
||||
max_instructions: usize,
|
||||
) -> ExecutionResult {
|
||||
self.run_bounded(cpu, memory, max_instructions, true)
|
||||
}
|
||||
|
||||
/// As [`Self::run`], but stop at the first block boundary that reaches the
|
||||
/// budget. Repeated slices reuse whole blocks instead of compiling a
|
||||
/// shortened one at every cutoff. The budget may be exceeded by less than
|
||||
/// one block.
|
||||
pub(crate) fn run_slice(
|
||||
&mut self,
|
||||
cpu: &mut CpuState,
|
||||
memory: &mut GuestMemory,
|
||||
max_instructions: usize,
|
||||
) -> ExecutionResult {
|
||||
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;
|
||||
|
||||
@@ -119,7 +172,11 @@ impl DbtEngine {
|
||||
}
|
||||
|
||||
// Look up or translate block at cpu.rip
|
||||
let block_limit = (max_instructions - instructions_count).min(MAX_BLOCK_INSTRUCTIONS);
|
||||
let block_limit = if exact {
|
||||
(max_instructions - instructions_count).min(MAX_BLOCK_INSTRUCTIONS)
|
||||
} else {
|
||||
MAX_BLOCK_INSTRUCTIONS
|
||||
};
|
||||
let mut block = self.get_or_compile_block(cpu.rip, memory, block_limit);
|
||||
// A decode failure can belong to a later instruction in the block.
|
||||
// Execute the current instruction alone so earlier effects retire
|
||||
@@ -335,6 +392,9 @@ pub fn is_native(insn: &Insn) -> bool {
|
||||
let scanned = matches!(insn.size, 2 | 4 | 8);
|
||||
match insn.op {
|
||||
Op::Add | Op::Sub | Op::Cmp | Op::And | Op::Or | Op::Xor | Op::Test => wide,
|
||||
// Register and immediate forms only; a memory destination would have
|
||||
// to restore the guest carry again after the store helper call.
|
||||
Op::Adc | Op::Sbb => wide && insn.memory().is_none(),
|
||||
Op::Inc | Op::Dec | Op::Neg | Op::Not => wide,
|
||||
Op::Cmov => wide,
|
||||
Op::Bsf | Op::Bsr => scanned,
|
||||
@@ -587,9 +647,26 @@ impl Emitter<'_> {
|
||||
}
|
||||
|
||||
/// X11 = X9 op X10, setting host NZCV only for the arithmetic operations.
|
||||
/// ADC and SBB also read the guest CF and clobber X12 and X13.
|
||||
fn compute(&mut self, op: Op, wide: bool) {
|
||||
let asm = &mut *self.asm;
|
||||
if matches!(op, Op::Adc | Op::Sbb) {
|
||||
// ADCS adds the host C, so C must equal the guest CF. SBCS
|
||||
// subtracts NOT C, while x86 SBB subtracts the borrow CF, so there
|
||||
// C must be its inverse. A compare sets C when it does not borrow.
|
||||
asm.ldrb_uoff(X12, X19, CF);
|
||||
if op == Op::Adc {
|
||||
asm.load_imm_64(X13, 1);
|
||||
asm.cmp_reg_32(X12, X13); // C = CF >= 1
|
||||
} else {
|
||||
asm.cmp_reg_32(XZR, X12); // C = 0 >= CF
|
||||
}
|
||||
}
|
||||
match (op, wide) {
|
||||
(Op::Adc, true) => asm.adcs_reg_64(X11, X9, X10),
|
||||
(Op::Adc, false) => asm.adcs_reg_32(X11, X9, X10),
|
||||
(Op::Sbb, true) => asm.sbcs_reg_64(X11, X9, X10),
|
||||
(Op::Sbb, false) => asm.sbcs_reg_32(X11, X9, X10),
|
||||
(Op::Add | Op::Inc, true) => asm.adds_reg_64(X11, X9, X10),
|
||||
(Op::Add | Op::Inc, false) => asm.adds_reg_32(X11, X9, X10),
|
||||
(Op::And | Op::Test, true) => asm.ands_reg_64(X11, X9, X10),
|
||||
@@ -623,7 +700,7 @@ impl Emitter<'_> {
|
||||
match op {
|
||||
// INC and DEC leave CF unchanged.
|
||||
Op::Inc | Op::Dec => {}
|
||||
Op::Add => {
|
||||
Op::Add | Op::Adc => {
|
||||
asm.cset_32(X12, Condition::Cs);
|
||||
asm.strb_uoff(X12, X19, CF);
|
||||
}
|
||||
@@ -1214,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;
|
||||
@@ -1232,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,
|
||||
@@ -1275,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) {
|
||||
@@ -1293,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));
|
||||
@@ -1340,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;
|
||||
@@ -1353,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;
|
||||
@@ -1366,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),
|
||||
@@ -1383,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;
|
||||
@@ -1396,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,
|
||||
@@ -1413,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,
|
||||
@@ -2267,4 +2382,207 @@ mod tests {
|
||||
ExitReason::MemoryFault(MemoryError::UnmappedAddress(FS_BASE + 8))
|
||||
);
|
||||
}
|
||||
|
||||
/// Intel SDM Volume 1, section 3.4.3.1: for `SUB` and `CMP`, `CF` is the
|
||||
/// borrow out of the most significant bit. `JB` is `CF = 1`, `JAE` is
|
||||
/// `CF = 0`, `JBE` is `CF = 1 or ZF = 1` and `JA` is `CF = 0 and ZF = 0`.
|
||||
///
|
||||
/// ARM64 reports the inverse: `SUBS` sets `C` when the subtraction does
|
||||
/// *not* borrow, and its `HI`/`LS` conditions are defined on that same
|
||||
/// inverted carry. These four x86 conditions therefore cannot be taken
|
||||
/// from an ARM64 condition code without translating the borrow first,
|
||||
/// which makes them the ones to pin at the boundaries.
|
||||
/// One unsigned condition: the low nibble pair as encoded in the `0x70`
|
||||
/// block, and the rule that decides it from CF and ZF.
|
||||
type UnsignedCondition = (u8, fn(bool, bool) -> bool);
|
||||
|
||||
const UNSIGNED_CONDITIONS: [UnsignedCondition; 4] = [
|
||||
(0x72, |cf, _zf| cf), // JB, JC, JNAE
|
||||
(0x73, |cf, _zf| !cf), // JAE, JNB, JNC
|
||||
(0x76, |cf, zf| cf || zf), // JBE, JNA
|
||||
(0x77, |cf, zf| !cf && !zf), // JA, JNBE
|
||||
];
|
||||
|
||||
/// Build `<op> eax, ebx` (or `rax, rbx`) followed by the short or near form
|
||||
/// of `condition`. The not-taken path writes 1 to `ECX` and halts, the
|
||||
/// taken path writes 2. A near branch targets offset 140, which a `disp8`
|
||||
/// cannot reach, so the two encodings are exercised separately.
|
||||
fn unsigned_branch_program(op: [u8; 2], condition: u8, wide: bool, near: bool) -> Vec<u8> {
|
||||
let mut code = Vec::new();
|
||||
if wide {
|
||||
code.push(0x48); // REX.W
|
||||
}
|
||||
code.extend_from_slice(&op); // cmp/sub eax, ebx
|
||||
let jcc = code.len();
|
||||
if near {
|
||||
// The near form is `0F 8x`, where x is the low nibble of the
|
||||
// short form's opcode.
|
||||
code.extend_from_slice(&[0x0F, 0x80 | (condition & 0x0F), 0, 0, 0, 0]);
|
||||
} else {
|
||||
code.extend_from_slice(&[condition, 0]);
|
||||
}
|
||||
code.extend_from_slice(&[0xB9, 1, 0, 0, 0]); // mov ecx, 1
|
||||
code.push(0xF4); // hlt
|
||||
let target = if near { 140 } else { code.len() };
|
||||
while code.len() < target {
|
||||
code.push(0x90); // nop
|
||||
}
|
||||
code.extend_from_slice(&[0xB9, 2, 0, 0, 0]); // mov ecx, 2
|
||||
code.push(0xF4); // hlt
|
||||
let next = jcc + if near { 6 } else { 2 };
|
||||
let displacement = target as i64 - next as i64;
|
||||
if near {
|
||||
code[jcc + 2..jcc + 6].copy_from_slice(&(displacement as i32).to_le_bytes());
|
||||
} else {
|
||||
code[jcc + 1] = displacement as i8 as u8;
|
||||
}
|
||||
code
|
||||
}
|
||||
|
||||
/// Run one branch program and return `(ecx, cf, zf)`.
|
||||
fn run_unsigned_branch(code: &[u8], left: u64, right: u64) -> (u64, bool, bool) {
|
||||
let (mut engine, mut cpu, mut memory) = fixture(code);
|
||||
cpu.set(Register::Rax, left);
|
||||
cpu.set(Register::Rbx, right);
|
||||
let result = engine.run(&mut cpu, &mut memory, 32);
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
// Either the two-instruction taken path or the two-instruction
|
||||
// not-taken path runs after the compare and the branch.
|
||||
assert_eq!(result.instructions_executed, 4);
|
||||
// The compare, the branch and the halting move all run as translated
|
||||
// ARM64, not through the shared interpreter.
|
||||
assert_eq!(engine.metrics.interpreter_fallbacks, 0);
|
||||
(cpu.get(Register::Rcx), cpu.flags.cf, cpu.flags.zf)
|
||||
}
|
||||
|
||||
/// The four unsigned conditions, at both ends of the 32-bit and 64-bit
|
||||
/// ranges, in the short and the near encoding. Expected flags and
|
||||
/// outcomes come from the SDM rules above, not from the lowering.
|
||||
#[test]
|
||||
fn unsigned_branch_conditions_follow_the_borrow_at_every_boundary() {
|
||||
const CMP: [u8; 2] = [0x39, 0xD8];
|
||||
let cases: &[(bool, u64, u64)] = &[
|
||||
// 32-bit: zero, one, equal operands, both ends of the range, and
|
||||
// the pair where the sign bit flips but the unsigned order holds.
|
||||
(false, 0, 0),
|
||||
(false, 0, 1),
|
||||
(false, 1, 0),
|
||||
(false, 0xFFFF_FFFF, 0xFFFF_FFFF),
|
||||
(false, 0xFFFF_FFFF, 0),
|
||||
(false, 0, 0xFFFF_FFFF),
|
||||
(false, 0x7FFF_FFFF, 0x8000_0000),
|
||||
(false, 0x8000_0000, 0x7FFF_FFFF),
|
||||
// The same boundaries at 64 bits, plus a subtraction that clears
|
||||
// the sign bit without borrowing.
|
||||
(true, 0, 0),
|
||||
(true, 0, 1),
|
||||
(true, 1, 0),
|
||||
(true, u64::MAX, u64::MAX),
|
||||
(true, u64::MAX, 0),
|
||||
(true, 0, u64::MAX),
|
||||
(true, 0x7FFF_FFFF_FFFF_FFFF, 0x8000_0000_0000_0000),
|
||||
(true, 0x8000_0000_0000_0000, 0x7FFF_FFFF_FFFF_FFFF),
|
||||
(true, 0x8000_0000_0000_0000, 1),
|
||||
];
|
||||
|
||||
for &(wide, left, right) in cases {
|
||||
let mask = if wide { u64::MAX } else { u64::from(u32::MAX) };
|
||||
let (left, right) = (left & mask, right & mask);
|
||||
// SDM: CF is the borrow out of the most significant bit, ZF is a
|
||||
// zero result. Both follow from the operands alone.
|
||||
let (cf, zf) = (left < right, left == right);
|
||||
for &(condition, holds) in &UNSIGNED_CONDITIONS {
|
||||
let taken = holds(cf, zf);
|
||||
for &near in &[false, true] {
|
||||
let code = unsigned_branch_program(CMP, condition, wide, near);
|
||||
let (ecx, got_cf, got_zf) = run_unsigned_branch(&code, left, right);
|
||||
let case = format!(
|
||||
"{condition:#04x} {:#x} {:#x} {}",
|
||||
left,
|
||||
right,
|
||||
if near { "near" } else { "short" }
|
||||
);
|
||||
assert_eq!(got_cf, cf, "{case}: CF");
|
||||
assert_eq!(got_zf, zf, "{case}: ZF");
|
||||
assert_eq!(ecx, if taken { 2 } else { 1 }, "{case}: branch outcome");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `SUB` is the other producer of the carry these conditions read, and the
|
||||
/// one where the ARM64 carry is inverted: `0 - 1` borrows, while
|
||||
/// `0x8000_0000_0000_0000 - 1` does not borrow even though it clears the
|
||||
/// sign bit.
|
||||
#[test]
|
||||
fn subtract_borrow_into_and_out_of_the_high_bit_feeds_the_unsigned_branches() {
|
||||
const SUB: [u8; 2] = [0x29, 0xD8];
|
||||
let cases: &[(bool, u64, u64)] = &[
|
||||
(false, 0, 1),
|
||||
(false, 0x8000_0000, 1),
|
||||
(true, 0, 1),
|
||||
(true, 0x8000_0000_0000_0000, 1),
|
||||
];
|
||||
|
||||
for &(wide, left, right) in cases {
|
||||
let mask = if wide { u64::MAX } else { u64::from(u32::MAX) };
|
||||
let (left, right) = (left & mask, right & mask);
|
||||
let (cf, zf) = (left < right, left == right);
|
||||
for &(condition, holds) in &UNSIGNED_CONDITIONS {
|
||||
let taken = holds(cf, zf);
|
||||
for &near in &[false, true] {
|
||||
let code = unsigned_branch_program(SUB, condition, wide, near);
|
||||
let (ecx, got_cf, got_zf) = run_unsigned_branch(&code, left, right);
|
||||
let case = format!(
|
||||
"{condition:#04x} {:#x} {:#x} {}",
|
||||
left,
|
||||
right,
|
||||
if near { "near" } else { "short" }
|
||||
);
|
||||
assert_eq!(got_cf, cf, "{case}: CF");
|
||||
assert_eq!(got_zf, zf, "{case}: ZF");
|
||||
assert_eq!(ecx, if taken { 2 } else { 1 }, "{case}: branch outcome");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The carry these conditions read is produced in one translated block and
|
||||
/// consumed in the next. A lowering that left it in the host's condition
|
||||
/// flags would pass the single-block cases above and fail here.
|
||||
#[test]
|
||||
fn unsigned_branch_reads_flags_stored_by_a_previous_block() {
|
||||
const CMP: [u8; 2] = [0x39, 0xD8];
|
||||
let cases: &[(bool, u64, u64)] = &[
|
||||
(false, 0, 0), // CF = 0, ZF = 1
|
||||
(false, 0, 1), // CF = 1, ZF = 0
|
||||
(false, 0xFFFF_FFFF, 0), // CF = 0, ZF = 0
|
||||
(true, 0x8000_0000_0000_0000, 1), // CF = 0 although the sign bit clears
|
||||
];
|
||||
|
||||
for &(wide, left, right) in cases {
|
||||
let (cf, zf) = (left < right, left == right);
|
||||
for &(condition, holds) in &UNSIGNED_CONDITIONS {
|
||||
let taken = holds(cf, zf);
|
||||
let code = unsigned_branch_program(CMP, condition, wide, false);
|
||||
let (mut engine, mut cpu, mut memory) = fixture(&code);
|
||||
cpu.set(Register::Rax, left);
|
||||
cpu.set(Register::Rbx, right);
|
||||
|
||||
// One instruction per run: the compare is translated as a
|
||||
// one-instruction block, so the branch is compiled separately
|
||||
// and can only read the flags the first block stored.
|
||||
let first = engine.run(&mut cpu, &mut memory, 1);
|
||||
assert_eq!(first.exit_reason, ExitReason::StepLimitExceeded);
|
||||
assert_eq!(cpu.rip, ENTRY + if wide { 3 } else { 2 });
|
||||
assert_eq!((cpu.flags.cf, cpu.flags.zf), (cf, zf));
|
||||
|
||||
let second = engine.run(&mut cpu, &mut memory, 8);
|
||||
assert_eq!(second.exit_reason, ExitReason::Halt);
|
||||
assert_eq!(second.instructions_executed, 3);
|
||||
assert_eq!(cpu.get(Register::Rcx), if taken { 2 } else { 1 });
|
||||
assert_eq!(engine.metrics.interpreter_fallbacks, 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+1030
-2
File diff suppressed because it is too large.
Load diff
@@ -196,8 +196,25 @@ 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;
|
||||
|
||||
fn callback_depth(memory: &GuestMemory, teb: u64) -> usize {
|
||||
memory
|
||||
.callback_frames
|
||||
.range((teb, 0)..=(teb, u64::MAX))
|
||||
.count()
|
||||
}
|
||||
|
||||
pub(crate) struct GuestCallback {
|
||||
pub(crate) entry: u64,
|
||||
pub(crate) context: u64,
|
||||
@@ -264,6 +281,8 @@ pub(crate) struct CallbackFrame {
|
||||
|
||||
/// Registry for resolving and binding import symbols to guest trampoline VAs.
|
||||
pub struct ImportRegistry {
|
||||
/// Set by the standard services so a call can end the caller's turn.
|
||||
pub(crate) hooks: Option<Arc<crate::services::threads::SchedulerHooks>>,
|
||||
// (lower-case module, name) -> service index. Symbol names keep their case.
|
||||
services: HashMap<(String, ImportName), usize>,
|
||||
handlers: Vec<ServiceDescriptor>,
|
||||
@@ -282,6 +301,7 @@ impl Default for ImportRegistry {
|
||||
impl ImportRegistry {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
hooks: None,
|
||||
services: HashMap::new(),
|
||||
handlers: Vec::new(),
|
||||
callback_dispatchers: HashMap::new(),
|
||||
@@ -609,7 +629,7 @@ impl ImportRegistry {
|
||||
args: [u64; 4],
|
||||
) -> Result<(), ExitReason> {
|
||||
let key = (cpu.gs_base, slot + 8);
|
||||
if memory.callback_frames.len() >= MAX_CALLBACK_DEPTH
|
||||
if callback_depth(memory, cpu.gs_base) >= MAX_CALLBACK_DEPTH
|
||||
|| memory.callback_frames.contains_key(&key)
|
||||
{
|
||||
return Err(ExitReason::ServiceAbiViolation);
|
||||
@@ -635,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()
|
||||
}
|
||||
@@ -646,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
|
||||
@@ -725,7 +762,7 @@ impl ImportRegistry {
|
||||
}
|
||||
if let Some(dispatcher) = self.callback_dispatchers.get(&service_idx) {
|
||||
let key = (cpu.gs_base, after);
|
||||
if memory.callback_frames.len() >= MAX_CALLBACK_DEPTH
|
||||
if callback_depth(memory, cpu.gs_base) >= MAX_CALLBACK_DEPTH
|
||||
|| memory.callback_frames.contains_key(&key)
|
||||
{
|
||||
return Err(ExitReason::ServiceAbiViolation);
|
||||
@@ -766,6 +803,9 @@ impl ImportRegistry {
|
||||
cpu.set(Register::Rax, value);
|
||||
cpu.set(Register::Rsp, after);
|
||||
cpu.rip = ret_addr;
|
||||
if self.hooks.as_ref().is_some_and(|h| h.switch_requested()) {
|
||||
return Err(ExitReason::GuestYield);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ pub mod reloc;
|
||||
pub mod runtime;
|
||||
#[rustfmt::skip]
|
||||
pub mod runtime_table;
|
||||
pub mod scheduler;
|
||||
pub mod services;
|
||||
pub mod softfloat;
|
||||
pub mod startup;
|
||||
|
||||
+860
-6
@@ -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;
|
||||
|
||||
@@ -95,6 +95,8 @@ enum AllocationKind {
|
||||
ImageOrStatic,
|
||||
Virtual,
|
||||
Heap(u64),
|
||||
/// Stack, guard or TEB of a guest thread; only the scheduler frees it.
|
||||
Thread,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -382,6 +384,19 @@ impl GuestMemory {
|
||||
Ok(destination)
|
||||
}
|
||||
|
||||
pub(crate) fn map_thread_region(
|
||||
&mut self,
|
||||
base: u64,
|
||||
size: usize,
|
||||
permissions: MemoryPermissions,
|
||||
) -> Result<u64, MemoryError> {
|
||||
self.map_dynamic_allocation(base, size, permissions, AllocationKind::Thread)
|
||||
}
|
||||
|
||||
pub(crate) fn release_thread_region(&mut self, base: u64) -> bool {
|
||||
self.release_dynamic_allocation(base, AllocationKind::Thread)
|
||||
}
|
||||
|
||||
pub(crate) fn release_virtual_allocation(&mut self, base: u64) -> bool {
|
||||
self.release_dynamic_allocation(base, AllocationKind::Virtual)
|
||||
}
|
||||
@@ -419,6 +434,12 @@ impl GuestMemory {
|
||||
/// byte must be mapped and every region must grant `required` (`None` bypasses
|
||||
/// permission checks for the loader). The whole range is checked before any byte
|
||||
/// is copied, so a failed access never partially reads or writes.
|
||||
///
|
||||
/// A failed access reports the lowest address it may not touch, which is the
|
||||
/// start of the access only when its first byte fails. An access that begins in
|
||||
/// a mapped page and runs into an unmapped or forbidden one therefore reports
|
||||
/// the first byte of that page, as an x86 page fault reports the linear address
|
||||
/// that could not be translated or accessed.
|
||||
fn resolve(
|
||||
&self,
|
||||
address: u64,
|
||||
@@ -452,7 +473,10 @@ impl GuestMemory {
|
||||
Some(_) => region.permissions.execute,
|
||||
};
|
||||
if let (false, Some(required)) = (permitted, required) {
|
||||
return Err(MemoryError::PermissionViolation { address, required });
|
||||
return Err(MemoryError::PermissionViolation {
|
||||
address: cursor,
|
||||
required,
|
||||
});
|
||||
}
|
||||
let take = (end.min(region_end) - cursor) as usize;
|
||||
pieces.push((index, (cursor - region.base) as usize, take));
|
||||
@@ -461,7 +485,7 @@ impl GuestMemory {
|
||||
return Ok(pieces);
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
Err(MemoryError::UnmappedAddress(cursor))
|
||||
}
|
||||
|
||||
fn read_checked(
|
||||
@@ -496,19 +520,55 @@ 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> {
|
||||
let mut buf = [0u8; 1];
|
||||
self.read_checked(address, &mut buf, Some("execute"))?;
|
||||
Ok(buf[0])
|
||||
address.checked_add(1).ok_or(MemoryError::Overflow)?;
|
||||
let region = self
|
||||
.regions
|
||||
.iter()
|
||||
.find(|region| region.base + region.data.len() as u64 > address)
|
||||
.filter(|region| region.base <= address)
|
||||
.ok_or(MemoryError::UnmappedAddress(address))?;
|
||||
if !region.permissions.execute {
|
||||
return Err(MemoryError::PermissionViolation {
|
||||
address,
|
||||
required: "execute",
|
||||
});
|
||||
}
|
||||
Ok(region.data[(address - region.base) as usize])
|
||||
}
|
||||
|
||||
/// Read a 64-bit integer (little endian) from guest memory.
|
||||
@@ -627,3 +687,797 @@ mod tests {
|
||||
assert_eq!(memory.heap_allocation_size(PROCESS_HEAP, moved), Some(1));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod instruction_fetch_tests {
|
||||
use super::{MemoryPermissions as P, *};
|
||||
|
||||
fn denied(address: u64) -> Result<u8, MemoryError> {
|
||||
Err(MemoryError::PermissionViolation {
|
||||
address,
|
||||
required: "execute",
|
||||
})
|
||||
}
|
||||
fn missing(address: u64) -> Result<u8, MemoryError> {
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_reports_overflow_before_lookup() {
|
||||
let m = GuestMemory::new();
|
||||
for at in [0, 1, 0x1000, u64::MAX - 1] {
|
||||
assert_eq!(m.fetch_instruction_byte(at), missing(at));
|
||||
}
|
||||
assert_eq!(
|
||||
m.fetch_instruction_byte(u64::MAX),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region(u64::MAX, 0, P::NO_ACCESS).unwrap();
|
||||
assert_eq!(
|
||||
m.fetch_instruction_byte(u64::MAX),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_checks_execute_permission_for_every_byte_value() {
|
||||
let bytes: Vec<u8> = (0..=255).collect();
|
||||
for flags in 0..8 {
|
||||
let permission = P {
|
||||
read: flags & 1 != 0,
|
||||
write: flags & 2 != 0,
|
||||
execute: flags & 4 != 0,
|
||||
};
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(0x1000, bytes.len(), permission, &bytes)
|
||||
.unwrap();
|
||||
for (offset, byte) in bytes.iter().enumerate() {
|
||||
let at = 0x1000 + offset as u64;
|
||||
assert_eq!(
|
||||
m.fetch_instruction_byte(at),
|
||||
if flags & 4 != 0 {
|
||||
Ok(*byte)
|
||||
} else {
|
||||
denied(at)
|
||||
},
|
||||
"flags={flags}, at={at:x}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_handles_sparse_and_out_of_order_mappings() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(0x3000, 2, P::READ_EXECUTE, &[0xc1, 0xc2])
|
||||
.unwrap();
|
||||
m.map_region_with_data(0, 2, P::READ_EXECUTE, &[0x01, 0x02])
|
||||
.unwrap();
|
||||
m.map_region_with_data(0x2000, 1, P::READ_ONLY, &[0xb1])
|
||||
.unwrap();
|
||||
m.map_region_with_data(0x1000, 2, P::READ_EXECUTE, &[0xa1, 0xa2])
|
||||
.unwrap();
|
||||
for (at, byte) in [
|
||||
(0, 1),
|
||||
(1, 2),
|
||||
(0x1000, 0xa1),
|
||||
(0x1001, 0xa2),
|
||||
(0x3000, 0xc1),
|
||||
(0x3001, 0xc2),
|
||||
] {
|
||||
assert_eq!(m.fetch_instruction_byte(at), Ok(byte));
|
||||
}
|
||||
assert_eq!(m.fetch_instruction_byte(0x2000), denied(0x2000));
|
||||
for at in [2, 0xfff, 0x1002, 0x2001, 0x2fff, 0x3002] {
|
||||
assert_eq!(m.fetch_instruction_byte(at), missing(at));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_ignores_empty_mappings_at_shared_boundaries() {
|
||||
for zero_first in [false, true] {
|
||||
for execute in [false, true] {
|
||||
let mut m = GuestMemory::new();
|
||||
let permission = P {
|
||||
read: false,
|
||||
write: false,
|
||||
execute,
|
||||
};
|
||||
if zero_first {
|
||||
for _ in 0..7 {
|
||||
m.map_region(0x1000, 0, P::READ_WRITE_EXECUTE).unwrap();
|
||||
}
|
||||
}
|
||||
m.map_region_with_data(0x1000, 2, permission, &[0x34, 0x56])
|
||||
.unwrap();
|
||||
for _ in 0..7 {
|
||||
m.map_region(0x1000, 0, P::NO_ACCESS).unwrap();
|
||||
}
|
||||
for _ in 0..7 {
|
||||
m.map_region(0x1002, 0, P::READ_WRITE_EXECUTE).unwrap();
|
||||
}
|
||||
for (at, byte) in [(0x1000, 0x34), (0x1001, 0x56)] {
|
||||
assert_eq!(
|
||||
m.fetch_instruction_byte(at),
|
||||
if execute { Ok(byte) } else { denied(at) }
|
||||
);
|
||||
}
|
||||
assert_eq!(m.fetch_instruction_byte(0x1002), missing(0x1002));
|
||||
}
|
||||
}
|
||||
let mut m = GuestMemory::new();
|
||||
for at in [1, 1, 2, 0x1000] {
|
||||
m.map_region(at, 0, P::READ_WRITE_EXECUTE).unwrap();
|
||||
}
|
||||
for at in [0, 1, 2, 3, 0x1000] {
|
||||
assert_eq!(m.fetch_instruction_byte(at), missing(at));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_checks_adjacent_mapping_permissions() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(0x1000, 1, P::READ_EXECUTE, &[0xa5])
|
||||
.unwrap();
|
||||
m.map_region_with_data(0x1001, 1, P::READ_WRITE, &[0x5a])
|
||||
.unwrap();
|
||||
m.map_region(0x1001, 0, P::READ_EXECUTE).unwrap();
|
||||
m.map_region_with_data(0x1002, 1, P::READ_EXECUTE, &[0xc3])
|
||||
.unwrap();
|
||||
assert_eq!(m.fetch_instruction_byte(0x1000), Ok(0xa5));
|
||||
assert_eq!(m.fetch_instruction_byte(0x1001), denied(0x1001));
|
||||
assert_eq!(m.fetch_instruction_byte(0x1002), Ok(0xc3));
|
||||
assert_eq!(m.fetch_instruction_byte(0x1003), missing(0x1003));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_handles_the_highest_region_end() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(u64::MAX - 2, 2, P::READ_EXECUTE, &[0x12, 0x34])
|
||||
.unwrap();
|
||||
m.map_region(u64::MAX, 0, P::READ_EXECUTE).unwrap();
|
||||
assert_eq!(
|
||||
m.fetch_instruction_byte(u64::MAX - 3),
|
||||
missing(u64::MAX - 3)
|
||||
);
|
||||
assert_eq!(m.fetch_instruction_byte(u64::MAX - 2), Ok(0x12));
|
||||
assert_eq!(m.fetch_instruction_byte(u64::MAX - 1), Ok(0x34));
|
||||
assert_eq!(
|
||||
m.fetch_instruction_byte(u64::MAX),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_observes_writes_clones_and_mapping_changes() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(0x1000, 1, P::READ_WRITE_EXECUTE, &[0x11])
|
||||
.unwrap();
|
||||
let mut clone = m.clone();
|
||||
m.write_u8(0x1000, 0x22).unwrap();
|
||||
clone.write_u8(0x1000, 0x33).unwrap();
|
||||
assert_eq!(m.fetch_instruction_byte(0x1000), Ok(0x22));
|
||||
assert_eq!(clone.fetch_instruction_byte(0x1000), Ok(0x33));
|
||||
let base = m
|
||||
.map_virtual_allocation(0x4000, 1, P::READ_WRITE_EXECUTE)
|
||||
.unwrap();
|
||||
m.write_u8(base, 0x44).unwrap();
|
||||
assert_eq!(m.fetch_instruction_byte(base), Ok(0x44));
|
||||
assert!(m.release_virtual_allocation(base));
|
||||
assert_eq!(m.fetch_instruction_byte(base), missing(base));
|
||||
m.map_region_with_data(base, 1, P::READ_ONLY, &[0x55])
|
||||
.unwrap();
|
||||
assert_eq!(m.fetch_instruction_byte(base), denied(base));
|
||||
assert_eq!(clone.fetch_instruction_byte(base), missing(base));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fetch_keeps_first_mapping_priority_after_empty_heap_growth() {
|
||||
// Existing private allocation methods can grow a zero allocation onto an
|
||||
// earlier mapping at its base. The fetch-only patch must preserve the
|
||||
// original mapping's priority even for this already-representable state.
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(0x1000, 1, P::READ_EXECUTE, &[0x90])
|
||||
.unwrap();
|
||||
const BASE: u64 = 0x0000_0003_0000_0000;
|
||||
m.map_region_with_data(BASE, 4, P::READ_EXECUTE, &[0x11, 0x22, 0x33, 0x44])
|
||||
.unwrap();
|
||||
let empty = m.map_heap_allocation(PROCESS_HEAP, 0).unwrap();
|
||||
assert_eq!(empty, BASE);
|
||||
assert_eq!(
|
||||
m.resize_heap_allocation(PROCESS_HEAP, empty, 2, true),
|
||||
Ok(BASE)
|
||||
);
|
||||
assert_eq!(m.fetch_instruction_byte(BASE), Ok(0x11));
|
||||
assert_eq!(m.fetch_instruction_byte(BASE + 1), Ok(0x22));
|
||||
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]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+95
-8
@@ -3,7 +3,8 @@
|
||||
//! PE32+ (64-bit Portable Executable) format parser and section loader for Xenora.
|
||||
//!
|
||||
//! Parses standard PE32+ headers (DOS header, COFF header, Optional Header 64)
|
||||
//! and loads valid section headers into `GuestMemory` with appropriate permissions.
|
||||
//! and loads the headers and each section into `GuestMemory` with appropriate
|
||||
//! permissions.
|
||||
|
||||
use crate::memory::{GuestMemory, MemoryError, MemoryPermissions};
|
||||
use std::fmt;
|
||||
@@ -19,6 +20,11 @@ pub enum PeError {
|
||||
InvalidSectionHeaders,
|
||||
SectionMappingError(MemoryError),
|
||||
InvalidEntryPoint,
|
||||
/// The headers cannot be mapped at the image base: `SizeOfHeaders` is
|
||||
/// zero, ends before the section table does, runs past the end of the
|
||||
/// file, or its pages reach into a section; or the bytes given to the
|
||||
/// loader do not hold the PE32+ headers that were parsed.
|
||||
InvalidHeaderSize,
|
||||
}
|
||||
|
||||
impl fmt::Display for PeError {
|
||||
@@ -42,6 +48,12 @@ impl fmt::Display for PeError {
|
||||
Self::InvalidSectionHeaders => write!(f, "invalid or corrupt section headers"),
|
||||
Self::SectionMappingError(e) => write!(f, "failed to map section: {e}"),
|
||||
Self::InvalidEntryPoint => write!(f, "entry point address is outside executable code"),
|
||||
Self::InvalidHeaderSize => write!(
|
||||
f,
|
||||
"the PE headers cannot be mapped: SizeOfHeaders is zero, shorter than the section \
|
||||
table, longer than the file or reaches into a section, or the bytes do not match \
|
||||
the parsed headers"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -80,6 +92,9 @@ pub struct LoadedImage {
|
||||
pub pe: ParsedPe,
|
||||
pub memory: GuestMemory,
|
||||
pub entry_point: u64,
|
||||
/// Guest address of the `ImageBase` field in the mapped optional header.
|
||||
/// Startup writes the load base there once relocations have been applied.
|
||||
pub(crate) image_base_field: u64,
|
||||
}
|
||||
|
||||
// Windows PE Characteristic Constants
|
||||
@@ -94,9 +109,14 @@ pub const PE32_PLUS_MAGIC: u16 = 0x020B;
|
||||
/// PE32+ optional header length up to and including NumberOfRvaAndSizes.
|
||||
const PE32_PLUS_MIN_OPTIONAL_HEADER: usize = 112;
|
||||
const SECTION_HEADER_SIZE: usize = 40;
|
||||
/// Host memory budget for all mapped sections of one image. This is a loader policy
|
||||
/// limit, not a property of the PE format.
|
||||
/// Host memory budget for the mapped headers and sections of one image. This is a
|
||||
/// loader policy limit, not a property of the PE format.
|
||||
const MAX_MAPPED_IMAGE_BYTES: u64 = 256 * 1024 * 1024;
|
||||
/// The mapped headers end on a guest page boundary.
|
||||
const HEADER_PAGE: u64 = 0x1000;
|
||||
/// `ImageBase` and `SizeOfHeaders` within the PE32+ optional header.
|
||||
const OPTIONAL_IMAGE_BASE: usize = 24;
|
||||
const OPTIONAL_SIZE_OF_HEADERS: usize = 60;
|
||||
|
||||
fn read_u16(bytes: &[u8], at: usize) -> u16 {
|
||||
u16::from_le_bytes([bytes[at], bytes[at + 1]])
|
||||
@@ -270,25 +290,91 @@ impl ParsedPe {
|
||||
None
|
||||
}
|
||||
|
||||
/// Load this parsed PE into a fresh `GuestMemory` instance, mapping all sections.
|
||||
/// Where the headers are and how much to map for them: the file length of
|
||||
/// the headers, the page-rounded length of the mapping, and the file offset
|
||||
/// of the optional header's `ImageBase` field. Nothing is copied or
|
||||
/// allocated here.
|
||||
///
|
||||
/// A caller may pass bytes other than the ones parsed, so the header
|
||||
/// layout is read again from `bytes` with every access checked, and must
|
||||
/// be a PE32+ optional header that agrees with the parsed metadata.
|
||||
fn headers_for(&self, bytes: &[u8]) -> Result<(usize, u64, usize), PeError> {
|
||||
let field = |at: usize, len: usize| at.checked_add(len).and_then(|end| bytes.get(at..end));
|
||||
let u16_at = |at: usize| Some(u16::from_le_bytes(field(at, 2)?.try_into().ok()?));
|
||||
let u32_at = |at: usize| Some(u32::from_le_bytes(field(at, 4)?.try_into().ok()?));
|
||||
let layout = || {
|
||||
let coff = (u32_at(0x3C)? as usize).checked_add(4)?;
|
||||
let sections = u16_at(coff.checked_add(2)?)?;
|
||||
let optional_size = usize::from(u16_at(coff.checked_add(16)?)?);
|
||||
let optional = coff.checked_add(20)?;
|
||||
let image_base = optional.checked_add(OPTIONAL_IMAGE_BASE)?;
|
||||
let agrees = u16_at(optional)? == PE32_PLUS_MAGIC
|
||||
&& optional_size >= PE32_PLUS_MIN_OPTIONAL_HEADER
|
||||
&& sections == self.number_of_sections
|
||||
&& u64::from_le_bytes(field(image_base, 8)?.try_into().ok()?) == self.image_base
|
||||
&& u32_at(optional.checked_add(OPTIONAL_SIZE_OF_HEADERS)?)? == self.size_of_headers;
|
||||
let table_end = optional
|
||||
.checked_add(optional_size)?
|
||||
.checked_add(usize::from(sections).checked_mul(SECTION_HEADER_SIZE)?)?;
|
||||
agrees.then_some((image_base, table_end))
|
||||
};
|
||||
let (image_base, table_end) = layout().ok_or(PeError::InvalidHeaderSize)?;
|
||||
|
||||
// A size of zero is shorter than any section table.
|
||||
let len = self.size_of_headers as usize;
|
||||
if len < table_end || len > bytes.len() {
|
||||
return Err(PeError::InvalidHeaderSize);
|
||||
}
|
||||
let mapped = u64::from(self.size_of_headers).next_multiple_of(HEADER_PAGE);
|
||||
let reaches_a_section = self.sections.iter().any(|sec| {
|
||||
sec.virtual_size.max(sec.raw_data_size) > 0 && u64::from(sec.virtual_address) < mapped
|
||||
});
|
||||
if reaches_a_section {
|
||||
return Err(PeError::InvalidHeaderSize);
|
||||
}
|
||||
Ok((len, mapped, image_base))
|
||||
}
|
||||
|
||||
/// Load this parsed PE into a fresh `GuestMemory` instance, mapping the
|
||||
/// headers and all sections.
|
||||
pub fn load_into_memory(&self, bytes: &[u8]) -> Result<LoadedImage, PeError> {
|
||||
self.load_at_base(bytes, self.image_base)
|
||||
}
|
||||
|
||||
pub(crate) fn load_at_base(&self, bytes: &[u8], base: u64) -> Result<LoadedImage, PeError> {
|
||||
// Each section becomes a zero-filled host allocation, so bound the total before
|
||||
// allocating anything. Sections may not overlap, so the sum is the mapped size.
|
||||
let mapped: u64 = self
|
||||
let (headers_len, headers_mapped, image_base_field) = self.headers_for(bytes)?;
|
||||
|
||||
// The headers and each section become zero-filled host allocations, so bound
|
||||
// the total before allocating anything. Sections may not overlap, so the sum
|
||||
// is the mapped size.
|
||||
let mapped = self
|
||||
.sections
|
||||
.iter()
|
||||
.map(|sec| u64::from(sec.virtual_size.max(sec.raw_data_size)))
|
||||
.sum();
|
||||
.sum::<u64>()
|
||||
+ headers_mapped;
|
||||
if mapped > MAX_MAPPED_IMAGE_BYTES {
|
||||
return Err(PeError::SectionMappingError(MemoryError::AllocationFailed));
|
||||
}
|
||||
|
||||
let mut memory = GuestMemory::new();
|
||||
|
||||
// Windows maps the headers read-only at the image base, and programs read
|
||||
// them: a C runtime finds its own sections this way before `main`. The
|
||||
// budget above is checked first, and the file bytes are the initial data
|
||||
// of the mapping, so nothing else is copied.
|
||||
memory
|
||||
.map_region_with_data(
|
||||
base,
|
||||
headers_mapped as usize,
|
||||
MemoryPermissions::READ_ONLY,
|
||||
&bytes[..headers_len],
|
||||
)
|
||||
.map_err(PeError::SectionMappingError)?;
|
||||
let image_base_field = base
|
||||
.checked_add(image_base_field as u64)
|
||||
.ok_or(PeError::InvalidHeaderSize)?;
|
||||
|
||||
for sec in &self.sections {
|
||||
let base_addr = base
|
||||
.checked_add(u64::from(sec.virtual_address))
|
||||
@@ -323,6 +409,7 @@ impl ParsedPe {
|
||||
pe: self.clone(),
|
||||
memory,
|
||||
entry_point,
|
||||
image_base_field,
|
||||
})
|
||||
}
|
||||
}
|
||||
+234
-1
@@ -163,7 +163,6 @@ pub fn apply_relocations(
|
||||
let reloc_type = (entry_val >> 12) as u8;
|
||||
let offset_in_page = (entry_val & 0x0FFF) as u32;
|
||||
|
||||
*report.type_counts.entry(reloc_type).or_insert(0) += 1;
|
||||
report.total_entries += 1;
|
||||
|
||||
match reloc_type {
|
||||
@@ -221,6 +220,17 @@ pub fn apply_relocations(
|
||||
read_bytes += block_size as usize;
|
||||
}
|
||||
|
||||
// Only these two types can reach a successful return. Build the public
|
||||
// histogram once instead of searching its tree for every relocation.
|
||||
for (kind, count) in [
|
||||
(IMAGE_REL_BASED_ABSOLUTE, report.skipped_absolute),
|
||||
(IMAGE_REL_BASED_DIR64, report.applied_dir64),
|
||||
] {
|
||||
if count != 0 {
|
||||
report.type_counts.insert(kind, count);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
@@ -274,3 +284,226 @@ fn find_reloc_directory(
|
||||
Ok(Some((reloc_rva, reloc_size)))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::memory::MemoryPermissions;
|
||||
use crate::pe::PeSection;
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
|
||||
const PREFERRED: u64 = 0x140000000;
|
||||
const LOADED: u64 = PREFERRED + 0x200000;
|
||||
const DATA_RVA: u32 = 0x1000;
|
||||
const DIRECTORY_RVA: u32 = 0x10000000;
|
||||
const DIRECTORY_OFFSET: usize = 0x200;
|
||||
|
||||
// Original synthetic directory, laid out from Microsoft's PE Format,
|
||||
// .reloc section: eight-byte block headers and two-byte type/offset words.
|
||||
// https://learn.microsoft.com/windows/win32/debug/pe-format#the-reloc-section-image-only
|
||||
// Header fields and metadata are supplied directly: PE parsing is not timed.
|
||||
fn fixture(blocks: &[(u32, Vec<u16>)], data: &[u8]) -> (ParsedPe, Vec<u8>, GuestMemory) {
|
||||
let mut bytes = vec![0u8; DIRECTORY_OFFSET];
|
||||
bytes[0x3c..0x40].copy_from_slice(&0x80u32.to_le_bytes());
|
||||
bytes[0x94..0x96].copy_from_slice(&240u16.to_le_bytes());
|
||||
bytes[0x104..0x108].copy_from_slice(&16u32.to_le_bytes());
|
||||
bytes[0x130..0x134].copy_from_slice(&DIRECTORY_RVA.to_le_bytes());
|
||||
for (page, entries) in blocks {
|
||||
bytes.extend_from_slice(&page.to_le_bytes());
|
||||
bytes.extend_from_slice(&(8u32 + entries.len() as u32 * 2).to_le_bytes());
|
||||
for entry in entries {
|
||||
bytes.extend_from_slice(&entry.to_le_bytes());
|
||||
}
|
||||
}
|
||||
let size = (bytes.len() - DIRECTORY_OFFSET) as u32;
|
||||
bytes[0x134..0x138].copy_from_slice(&size.to_le_bytes());
|
||||
let pe = ParsedPe {
|
||||
machine: 0x8664,
|
||||
number_of_sections: 1,
|
||||
time_date_stamp: 0,
|
||||
image_base: PREFERRED,
|
||||
section_alignment: 4096,
|
||||
file_alignment: 512,
|
||||
size_of_image: DIRECTORY_RVA + size.max(4096),
|
||||
size_of_headers: 512,
|
||||
entry_point_rva: 0,
|
||||
sections: vec![PeSection {
|
||||
name: ".reloc".into(),
|
||||
virtual_address: DIRECTORY_RVA,
|
||||
virtual_size: size,
|
||||
raw_data_ptr: DIRECTORY_OFFSET as u32,
|
||||
raw_data_size: size,
|
||||
characteristics: 0x40000040,
|
||||
permissions: MemoryPermissions::READ_ONLY,
|
||||
}],
|
||||
};
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
LOADED + u64::from(DATA_RVA),
|
||||
data.len(),
|
||||
MemoryPermissions::READ_ONLY,
|
||||
data,
|
||||
)
|
||||
.unwrap();
|
||||
(pe, bytes, memory)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn counts_padding_and_rebases_read_only_targets() {
|
||||
for (preferred, initial, expected) in [
|
||||
(PREFERRED, 0x140001234, 0x140201234),
|
||||
(LOADED + 0x200000, 0x140001234, 0x13fe01234),
|
||||
(LOADED - 8, u64::MAX - 3, 4),
|
||||
(LOADED + 8, 3, u64::MAX - 4),
|
||||
] {
|
||||
let (mut pe, bytes, mut memory) =
|
||||
fixture(&[(DATA_RVA, vec![0x0fff, 0xa000])], &initial.to_le_bytes());
|
||||
pe.image_base = preferred;
|
||||
let report = apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
|
||||
assert_eq!(memory.read_u64(LOADED + 0x1000).unwrap(), expected);
|
||||
assert_eq!(report.total_entries, 2);
|
||||
assert_eq!(report.applied_dir64, 1);
|
||||
assert_eq!(report.skipped_absolute, 1);
|
||||
assert_eq!(report.type_counts, BTreeMap::from([(0, 1), (10, 1)]));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn histogram_omits_types_that_did_not_occur() {
|
||||
for (entries, counts) in [
|
||||
(vec![], BTreeMap::new()),
|
||||
(vec![0x0fff, 0x0000], BTreeMap::from([(0, 2)])),
|
||||
(vec![0xa000, 0xa008], BTreeMap::from([(10, 2)])),
|
||||
] {
|
||||
let (pe, bytes, mut memory) = fixture(&[(DATA_RVA, entries)], &[0; 16]);
|
||||
let report = apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
|
||||
assert_eq!(report.type_counts, counts);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_duplicate_and_overlapping_entry_order() {
|
||||
let (pe, bytes, mut memory) = fixture(
|
||||
&[(DATA_RVA, vec![0xa000, 0xa000, 0xa004, 0x0000])],
|
||||
&[0; 16],
|
||||
);
|
||||
let report = apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
|
||||
// Two additions of 0x200000 at offset zero, then one at offset four.
|
||||
let mut actual = [0; 16];
|
||||
memory.read_bytes(LOADED + 0x1000, &mut actual).unwrap();
|
||||
assert_eq!(
|
||||
actual,
|
||||
[0, 0, 0x40, 0, 0, 0, 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0]
|
||||
);
|
||||
assert_eq!(report.type_counts, BTreeMap::from([(0, 1), (10, 3)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_fields_observe_prior_carries_in_directory_order() {
|
||||
let initial = [255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0];
|
||||
for (entries, expected) in [
|
||||
(vec![0xa000, 0xa004], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]),
|
||||
(vec![0xa004, 0xa000], [0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]),
|
||||
] {
|
||||
let (mut pe, bytes, mut memory) = fixture(&[(DATA_RVA, entries)], &initial);
|
||||
pe.image_base = LOADED - 1;
|
||||
apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
|
||||
let mut actual = [0; 12];
|
||||
memory.read_bytes(LOADED + 0x1000, &mut actual).unwrap();
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_prior_writes_and_rejects_unsupported_types() {
|
||||
let (pe, bytes, mut memory) = fixture(&[(DATA_RVA, vec![0xa000, 0xf008])], &[0; 16]);
|
||||
assert_eq!(
|
||||
apply_relocations(&pe, &bytes, LOADED, &mut memory),
|
||||
Err(RelocationError::UnsupportedRelocationType(15))
|
||||
);
|
||||
assert_eq!(memory.read_u64(LOADED + 0x1000).unwrap(), 0x200000);
|
||||
assert_eq!(memory.read_u64(LOADED + 0x1008).unwrap(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_delta_keeps_the_empty_report_without_parsing() {
|
||||
let (mut pe, _, mut memory) = fixture(&[], &[0; 8]);
|
||||
pe.image_base = LOADED;
|
||||
assert_eq!(
|
||||
apply_relocations(&pe, &[], LOADED, &mut memory).unwrap(),
|
||||
RelocationReport::default()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "manual relocation timing run; release build on an otherwise idle host"]
|
||||
fn relocation_profile() {
|
||||
for pages in [1u32, 128] {
|
||||
for padding_every in [0usize, 2, 1] {
|
||||
let blocks: Vec<_> = (0..pages)
|
||||
.map(|page| {
|
||||
let entries = (0..512)
|
||||
.map(|slot| {
|
||||
let padding = padding_every != 0 && slot % padding_every == 0;
|
||||
(if padding { 0 } else { 0xa000 }) | (slot as u16 * 8)
|
||||
})
|
||||
.collect();
|
||||
(DATA_RVA + page * 4096, entries)
|
||||
})
|
||||
.collect();
|
||||
let (pe, bytes, initial) = fixture(&blocks, &vec![0; pages as usize * 4096]);
|
||||
let mut samples = Vec::new();
|
||||
for run in 0..36 {
|
||||
let mut memory = initial.clone();
|
||||
let start = Instant::now();
|
||||
let report = black_box(
|
||||
apply_relocations(
|
||||
black_box(&pe),
|
||||
black_box(&bytes),
|
||||
LOADED,
|
||||
black_box(&mut memory),
|
||||
)
|
||||
.unwrap(),
|
||||
);
|
||||
let elapsed = start.elapsed().as_secs_f64() * 1e6;
|
||||
assert_eq!(report.total_entries, pages as usize * 512);
|
||||
let padding = match padding_every {
|
||||
0 => 0,
|
||||
2 => report.total_entries / 2,
|
||||
_ => report.total_entries,
|
||||
};
|
||||
assert_eq!(report.skipped_absolute, padding);
|
||||
assert_eq!(report.applied_dir64, report.total_entries - padding);
|
||||
// Check every output against the fixture's independently specified pattern.
|
||||
for slot in 0..pages as usize * 512 {
|
||||
let expected = if padding_every != 0 && slot % padding_every == 0 {
|
||||
0
|
||||
} else {
|
||||
0x200000
|
||||
};
|
||||
assert_eq!(
|
||||
memory.read_u64(LOADED + 0x1000 + slot as u64 * 8).unwrap(),
|
||||
expected
|
||||
);
|
||||
}
|
||||
if run >= 5 {
|
||||
samples.push(elapsed);
|
||||
}
|
||||
}
|
||||
samples.sort_by(f64::total_cmp);
|
||||
let mean = samples.iter().sum::<f64>() / samples.len() as f64;
|
||||
let variance =
|
||||
samples.iter().map(|s| (s - mean).powi(2)).sum::<f64>() / samples.len() as f64;
|
||||
println!(
|
||||
"pages={pages} padding_every={padding_every} n={} median_us={:.3} variance_us2={variance:.3} min_us={:.3} max_us={:.3}",
|
||||
samples.len(),
|
||||
samples[samples.len() / 2],
|
||||
samples[0],
|
||||
samples[samples.len() - 1]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Deterministic cooperative scheduler for guest threads.
|
||||
//!
|
||||
//! One host thread runs one guest thread at a time, in first-in, first-out
|
||||
//! order, for a bounded number of instructions. The same program, quantum and
|
||||
//! clock always interleave the same way. Guest threads never run concurrently,
|
||||
//! so nothing here relies on a guest memory-ordering model.
|
||||
//!
|
||||
//! A service that has to wait returns [`ExitReason::GuestBlocked`] without any
|
||||
//! effect and with RIP still on its trampoline. The scheduler runs that call
|
||||
//! again when something it may wait for has changed, oldest waiter first.
|
||||
|
||||
use crate::cpu::{CpuState, ExitReason};
|
||||
use crate::dbt::DbtEngine;
|
||||
use crate::memory::GuestMemory;
|
||||
use crate::services::ServicesState;
|
||||
use crate::services::threads::{RunState, THREAD_RETURN};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Default instructions a thread runs before the next one gets a turn.
|
||||
pub const DEFAULT_QUANTUM: usize = 1024;
|
||||
|
||||
/// Why scheduling stopped.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum Outcome {
|
||||
/// The main thread executed HLT, the synthetic process exit.
|
||||
Halted,
|
||||
/// Every thread ended.
|
||||
AllThreadsExited,
|
||||
/// No thread can run and no wait has a deadline.
|
||||
Deadlock {
|
||||
blocked: Vec<u32>,
|
||||
suspended: Vec<u32>,
|
||||
},
|
||||
BudgetExhausted,
|
||||
/// A thread stopped for a reason the guest cannot handle.
|
||||
Fault {
|
||||
thread: u32,
|
||||
reason: ExitReason,
|
||||
rip: u64,
|
||||
},
|
||||
}
|
||||
|
||||
/// Result of one scheduled run.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ScheduleReport {
|
||||
pub outcome: Outcome,
|
||||
/// Guest instructions and service calls, including repeated waits.
|
||||
pub instructions: usize,
|
||||
/// Turns given to threads.
|
||||
pub turns: usize,
|
||||
/// Largest number of guest threads alive at once.
|
||||
pub peak_threads: usize,
|
||||
/// Main thread state when it last stopped.
|
||||
pub main: CpuState,
|
||||
}
|
||||
|
||||
pub struct Scheduler {
|
||||
state: Arc<ServicesState>,
|
||||
quantum: usize,
|
||||
}
|
||||
|
||||
enum Turn {
|
||||
Continue,
|
||||
Stop(Outcome),
|
||||
}
|
||||
|
||||
impl Scheduler {
|
||||
/// `quantum` is at least one instruction; a turn ends at the first block
|
||||
/// boundary that reaches it.
|
||||
pub fn new(state: Arc<ServicesState>, quantum: usize) -> Self {
|
||||
Self {
|
||||
state,
|
||||
quantum: quantum.max(1),
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `main` and every thread it creates. Only one scheduler may be
|
||||
/// attached to a service state at a time. Created threads still alive at
|
||||
/// the end are terminated with code 0 and reclaimed, so a run that had any
|
||||
/// cannot be continued.
|
||||
pub fn run(
|
||||
&self,
|
||||
engine: &mut DbtEngine,
|
||||
memory: &mut GuestMemory,
|
||||
main: &CpuState,
|
||||
budget: usize,
|
||||
) -> Result<ScheduleReport, ExitReason> {
|
||||
let main_id = self.state.attach_scheduler(main)?;
|
||||
let mut report = ScheduleReport {
|
||||
outcome: Outcome::BudgetExhausted,
|
||||
instructions: 0,
|
||||
turns: 0,
|
||||
peak_threads: 1,
|
||||
main: main.clone(),
|
||||
};
|
||||
while report.instructions < budget {
|
||||
match self.turn(engine, memory, main_id, budget, &mut report) {
|
||||
Turn::Continue => {}
|
||||
Turn::Stop(outcome) => {
|
||||
report.outcome = outcome;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if report.outcome == Outcome::BudgetExhausted && self.all_ended() {
|
||||
report.outcome = Outcome::AllThreadsExited;
|
||||
}
|
||||
let continues = report.outcome == Outcome::BudgetExhausted;
|
||||
self.state
|
||||
.detach_scheduler(memory, continues.then_some(&report.main));
|
||||
Ok(report)
|
||||
}
|
||||
|
||||
fn turn(
|
||||
&self,
|
||||
engine: &mut DbtEngine,
|
||||
memory: &mut GuestMemory,
|
||||
main_id: u32,
|
||||
budget: usize,
|
||||
report: &mut ScheduleReport,
|
||||
) -> Turn {
|
||||
if let Some(outcome) = self.wake(engine, memory, main_id, budget, report) {
|
||||
return Turn::Stop(outcome);
|
||||
}
|
||||
let Some(id) = self.next_ready() else {
|
||||
// A spent budget may have left waiters untried, and must not sleep.
|
||||
if report.instructions >= budget {
|
||||
return Turn::Continue;
|
||||
}
|
||||
return self.idle();
|
||||
};
|
||||
report.turns += 1;
|
||||
let turn = self.take_credit(id).unwrap_or(self.quantum);
|
||||
let limit = turn.min(budget.saturating_sub(report.instructions));
|
||||
if limit == 0 {
|
||||
self.requeue(id);
|
||||
return Turn::Continue;
|
||||
}
|
||||
let before = report.instructions;
|
||||
let stop = self.run_thread(engine, memory, id, main_id, limit, report);
|
||||
match stop {
|
||||
Stop::Outcome(outcome) => Turn::Stop(outcome),
|
||||
Stop::Ended => Turn::Continue,
|
||||
Stop::Blocked => {
|
||||
let mut table = self.state.threads.lock().expect("guest thread table");
|
||||
table.sequence += 1;
|
||||
let sequence = table.sequence;
|
||||
if let Some(thread) = table.threads.get_mut(&id) {
|
||||
thread.run = RunState::Blocked(sequence);
|
||||
}
|
||||
Turn::Continue
|
||||
}
|
||||
Stop::Preempted { front } => {
|
||||
// Signaling keeps the caller's turn, but never renews it.
|
||||
let left = turn.saturating_sub(report.instructions - before);
|
||||
let mut table = self.state.threads.lock().expect("guest thread table");
|
||||
if let Some(thread) = table.threads.get_mut(&id) {
|
||||
if front && left > 0 {
|
||||
thread.credit = Some(left);
|
||||
table.queue.push_front(id);
|
||||
} else {
|
||||
table.queue.push_back(id);
|
||||
}
|
||||
}
|
||||
Turn::Continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn all_ended(&self) -> bool {
|
||||
let table = self.state.threads.lock().expect("guest thread table");
|
||||
table.threads.is_empty()
|
||||
}
|
||||
|
||||
/// Put back a thread that got no turn.
|
||||
fn requeue(&self, id: u32) {
|
||||
let mut table = self.state.threads.lock().expect("guest thread table");
|
||||
table.queue.push_front(id);
|
||||
}
|
||||
|
||||
fn take_credit(&self, id: u32) -> Option<usize> {
|
||||
let mut table = self.state.threads.lock().expect("guest thread table");
|
||||
table.threads.get_mut(&id)?.credit.take()
|
||||
}
|
||||
|
||||
/// Remove and return the first thread that can run.
|
||||
fn next_ready(&self) -> Option<u32> {
|
||||
let mut table = self.state.threads.lock().expect("guest thread table");
|
||||
let position = table
|
||||
.queue
|
||||
.iter()
|
||||
.position(|id| table.threads.get(id).is_some_and(|t| t.suspend == 0))?;
|
||||
table.queue.remove(position)
|
||||
}
|
||||
|
||||
/// Run the pending call of every blocked thread, oldest first. A thread that
|
||||
/// ends with its call may be what an older one waits for, so that repeats
|
||||
/// the pass.
|
||||
fn wake(
|
||||
&self,
|
||||
engine: &mut DbtEngine,
|
||||
memory: &mut GuestMemory,
|
||||
main_id: u32,
|
||||
budget: usize,
|
||||
report: &mut ScheduleReport,
|
||||
) -> Option<Outcome> {
|
||||
loop {
|
||||
let mut ended = false;
|
||||
for id in self.blocked(report) {
|
||||
if report.instructions >= budget {
|
||||
return None;
|
||||
}
|
||||
match self.run_thread(engine, memory, id, main_id, 1, report) {
|
||||
Stop::Outcome(outcome) => return Some(outcome),
|
||||
Stop::Blocked => {}
|
||||
Stop::Ended => ended = true,
|
||||
Stop::Preempted { .. } => {
|
||||
let mut table = self.state.threads.lock().expect("guest thread table");
|
||||
if let Some(thread) = table.threads.get_mut(&id) {
|
||||
thread.run = RunState::Ready;
|
||||
table.queue.push_back(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if !ended {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Blocked threads that are not suspended, oldest first.
|
||||
fn blocked(&self, report: &mut ScheduleReport) -> Vec<u32> {
|
||||
let table = self.state.threads.lock().expect("guest thread table");
|
||||
report.peak_threads = report.peak_threads.max(table.threads.len());
|
||||
let mut blocked: Vec<(u64, u32)> = table
|
||||
.threads
|
||||
.iter()
|
||||
.filter(|(_, thread)| thread.suspend == 0)
|
||||
.filter_map(|(&id, thread)| match thread.run {
|
||||
RunState::Blocked(sequence) => Some((sequence, id)),
|
||||
RunState::Ready => None,
|
||||
})
|
||||
.collect();
|
||||
blocked.sort_unstable();
|
||||
blocked.into_iter().map(|(_, id)| id).collect()
|
||||
}
|
||||
|
||||
/// Nothing can run: advance to the next deadline or stop.
|
||||
fn idle(&self) -> Turn {
|
||||
let table = self.state.threads.lock().expect("guest thread table");
|
||||
if table.threads.is_empty() {
|
||||
return Turn::Stop(Outcome::AllThreadsExited);
|
||||
}
|
||||
if let Some(deadline) = table.next_deadline() {
|
||||
drop(table);
|
||||
let now = self.state.clock.performance_count();
|
||||
self.state.clock.sleep(deadline.saturating_sub(now));
|
||||
return Turn::Continue;
|
||||
}
|
||||
let mut blocked = Vec::new();
|
||||
let mut suspended = Vec::new();
|
||||
for (&id, thread) in &table.threads {
|
||||
if thread.suspend > 0 {
|
||||
suspended.push(id);
|
||||
} else {
|
||||
blocked.push(id);
|
||||
}
|
||||
}
|
||||
Turn::Stop(Outcome::Deadlock { blocked, suspended })
|
||||
}
|
||||
|
||||
fn run_thread(
|
||||
&self,
|
||||
engine: &mut DbtEngine,
|
||||
memory: &mut GuestMemory,
|
||||
id: u32,
|
||||
main_id: u32,
|
||||
limit: usize,
|
||||
report: &mut ScheduleReport,
|
||||
) -> Stop {
|
||||
let cpu = {
|
||||
let mut table = self.state.threads.lock().expect("guest thread table");
|
||||
table.threads.get_mut(&id).and_then(|t| t.cpu.take())
|
||||
};
|
||||
let Some(mut cpu) = cpu else {
|
||||
return Stop::Ended;
|
||||
};
|
||||
self.state.hooks.take_switch();
|
||||
let result = engine.run_slice(&mut cpu, memory, limit);
|
||||
// The engine does not count a call that stops it.
|
||||
let stopped = matches!(
|
||||
result.exit_reason,
|
||||
ExitReason::GuestYield | ExitReason::GuestBlocked | ExitReason::GuestThreadExited
|
||||
);
|
||||
report.instructions += result.instructions_executed + usize::from(stopped);
|
||||
let rip = cpu.rip;
|
||||
let returned = (rip == THREAD_RETURN && id != main_id)
|
||||
.then(|| cpu.get(crate::cpu::Register::Rax) as u32);
|
||||
if id == main_id {
|
||||
report.main = cpu.clone();
|
||||
}
|
||||
let exit = {
|
||||
let mut table = self.state.threads.lock().expect("guest thread table");
|
||||
let Some(thread) = table.threads.get_mut(&id) else {
|
||||
return Stop::Ended;
|
||||
};
|
||||
thread.cpu = Some(cpu);
|
||||
thread.exit
|
||||
};
|
||||
if let Some(code) = exit.or(returned) {
|
||||
self.state.end_thread(id, code, memory);
|
||||
return Stop::Ended;
|
||||
}
|
||||
match result.exit_reason {
|
||||
ExitReason::StepLimitExceeded => Stop::Preempted { front: false },
|
||||
ExitReason::GuestYield => Stop::Preempted {
|
||||
front: !self.state.hooks.take_switch(),
|
||||
},
|
||||
ExitReason::GuestBlocked => Stop::Blocked,
|
||||
ExitReason::Halt if id == main_id => Stop::Outcome(Outcome::Halted),
|
||||
reason => Stop::Outcome(Outcome::Fault {
|
||||
thread: id,
|
||||
reason,
|
||||
rip,
|
||||
}),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum Stop {
|
||||
Blocked,
|
||||
Ended,
|
||||
Preempted { front: bool },
|
||||
Outcome(Outcome),
|
||||
}
|
||||
+149
-16
@@ -17,9 +17,11 @@ mod gdk_queue;
|
||||
mod heap;
|
||||
mod modules;
|
||||
mod platform_fixture;
|
||||
mod process;
|
||||
mod synch;
|
||||
pub mod sysinfo;
|
||||
mod task_fixture;
|
||||
pub(crate) mod threads;
|
||||
mod winsock;
|
||||
|
||||
use crate::runtime::HResult;
|
||||
@@ -92,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))
|
||||
@@ -193,8 +201,12 @@ pub struct ServicesState {
|
||||
objects: Mutex<ObjectState>,
|
||||
last_errors: Mutex<BTreeMap<u64, u32>>,
|
||||
synch: Mutex<synch::Synch>,
|
||||
pub(crate) threads: Mutex<threads::ThreadTable>,
|
||||
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>,
|
||||
@@ -217,7 +229,10 @@ impl ServicesState {
|
||||
objects: Mutex::new(ObjectState::default()),
|
||||
last_errors: Mutex::default(),
|
||||
synch: Mutex::default(),
|
||||
threads: Mutex::default(),
|
||||
hooks: Arc::default(),
|
||||
atexit: Mutex::default(),
|
||||
exit_status: Mutex::default(),
|
||||
winsock: Mutex::default(),
|
||||
task_fixture: Mutex::default(),
|
||||
platform_fixture: Mutex::default(),
|
||||
@@ -241,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
|
||||
@@ -294,11 +379,26 @@ impl ServicesState {
|
||||
/// hand-written fixture services.
|
||||
pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc<ServicesState>) {
|
||||
crate::runtime_table::register(registry, &state);
|
||||
registry.hooks = Some(Arc::clone(&state.hooks));
|
||||
threads::register(registry, &state);
|
||||
|
||||
let s = state.clone();
|
||||
registry.register(KERNEL32, "GetThreadId", move |args, cpu, mem| {
|
||||
let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
if handle == CURRENT_THREAD {
|
||||
return Ok(u64::from(s.thread_id_of(cpu.gs_base)));
|
||||
}
|
||||
let thread = s.objects.lock().expect("guest object state");
|
||||
if let Some(GuestObject::Waitable { state, access }) = thread.handles.get(&handle)
|
||||
&& let events::Waitable::Thread { id, .. } =
|
||||
&*state.lock().expect("guest waitable state")
|
||||
{
|
||||
return if access & THREAD_QUERY_RIGHTS == 0 {
|
||||
s.fail(cpu.gs_base, ERROR_ACCESS_DENIED, 0)
|
||||
} else {
|
||||
Ok(u64::from(*id))
|
||||
};
|
||||
}
|
||||
if let Err(error) = thread.check_access(handle, THREAD_QUERY_RIGHTS) {
|
||||
return s.fail(cpu.gs_base, error, 0);
|
||||
}
|
||||
@@ -324,8 +424,12 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc<Serv
|
||||
if inherit != 0 || options & !DUPLICATE_SAME_ACCESS != 0 || source == CURRENT_PROCESS {
|
||||
return s.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
let worker = s.current_worker(cpu.gs_base);
|
||||
let mut thread = s.objects.lock().expect("guest object state");
|
||||
let (granted, mut object) = if source == CURRENT_THREAD {
|
||||
let (granted, mut object) = if let (CURRENT_THREAD, Some(state)) = (source, worker) {
|
||||
let access = threads::THREAD_ALL_ACCESS;
|
||||
(access, GuestObject::Waitable { state, access })
|
||||
} else if source == CURRENT_THREAD {
|
||||
(
|
||||
THREAD_SUPPORTED_RIGHTS,
|
||||
GuestObject::Thread(THREAD_SUPPORTED_RIGHTS),
|
||||
@@ -439,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);
|
||||
@@ -602,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
|
||||
@@ -664,7 +773,7 @@ pub(crate) mod handlers {
|
||||
}
|
||||
|
||||
pub fn get_current_thread_id(context: &mut ServiceContext<'_>) -> Outcome<u32> {
|
||||
Ok(context.state.thread_id)
|
||||
Ok(context.state.thread_id_of(context.teb))
|
||||
}
|
||||
|
||||
pub fn open_thread(
|
||||
@@ -674,21 +783,41 @@ pub(crate) mod handlers {
|
||||
id: u32,
|
||||
) -> Outcome<u64> {
|
||||
let state = context.state;
|
||||
if id != state.thread_id {
|
||||
let worker = state.worker_object(id);
|
||||
let main = id == state.thread_id && state.main_thread_alive();
|
||||
if !main && worker.is_none() {
|
||||
return state.fail(context.teb, ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
if inherit || access & !THREAD_SUPPORTED_RIGHTS != 0 {
|
||||
let supported = THREAD_SUPPORTED_RIGHTS
|
||||
| if worker.is_some() {
|
||||
threads::WORKER_RIGHTS
|
||||
} else {
|
||||
0
|
||||
};
|
||||
if inherit || access & !supported != 0 {
|
||||
return state.fail(context.teb, ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
let mut thread = state.objects.lock().expect("guest object state");
|
||||
let Some(handle) = thread.next_handle() else {
|
||||
return state.fail(context.teb, ERROR_NOT_ENOUGH_MEMORY, 0);
|
||||
};
|
||||
thread.insert_handle(handle, GuestObject::Thread(access));
|
||||
let object = match worker {
|
||||
Some(state) => GuestObject::Waitable { state, access },
|
||||
None => GuestObject::Thread(access),
|
||||
};
|
||||
thread.insert_handle(handle, object);
|
||||
Ok(handle)
|
||||
}
|
||||
|
||||
pub fn get_thread_priority(context: &mut ServiceContext<'_>, handle: u64) -> Outcome<i32> {
|
||||
// Only the main thread has a priority; a worker must not change it.
|
||||
if handle == CURRENT_THREAD && context.state.current_worker(context.teb).is_some() {
|
||||
return context.state.fail(
|
||||
context.teb,
|
||||
ERROR_NOT_SUPPORTED,
|
||||
THREAD_PRIORITY_ERROR_RETURN as i32,
|
||||
);
|
||||
}
|
||||
let thread = context.state.objects.lock().expect("guest object state");
|
||||
if let Err(error) = thread.check_access(handle, THREAD_QUERY_RIGHTS) {
|
||||
return context
|
||||
@@ -703,6 +832,10 @@ pub(crate) mod handlers {
|
||||
handle: u64,
|
||||
priority: i32,
|
||||
) -> Outcome<bool> {
|
||||
// Only the main thread has a priority; a worker must not change it.
|
||||
if handle == CURRENT_THREAD && context.state.current_worker(context.teb).is_some() {
|
||||
return context.state.fail(context.teb, ERROR_NOT_SUPPORTED, false);
|
||||
}
|
||||
let state = context.state;
|
||||
let mut thread = state.objects.lock().expect("guest object state");
|
||||
if let Err(error) = thread.check_access(handle, THREAD_SET_RIGHTS) {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Unnamed event, semaphore and mutex objects and waits that can resolve without a guest scheduler.
|
||||
//! Unnamed event, semaphore and mutex objects and waits. A wait that cannot
|
||||
//! resolve at once blocks the guest thread if a scheduler is attached, and is
|
||||
//! unsupported otherwise.
|
||||
|
||||
use super::threads::PendingWait;
|
||||
use super::{
|
||||
ERROR_ACCESS_DENIED, ERROR_INVALID_HANDLE, ERROR_INVALID_PARAMETER, ERROR_NOACCESS,
|
||||
ERROR_NOT_ENOUGH_MEMORY, ERROR_NOT_SUPPORTED, GuestObject, KERNEL32, ServicesState,
|
||||
@@ -13,11 +16,14 @@ use std::sync::{Arc, Mutex};
|
||||
|
||||
const SYNCH_API: &str = "api-ms-win-core-synch-l1-1-0.dll";
|
||||
const EVENT_MODIFY_STATE: u32 = 0x0002;
|
||||
const SYNCHRONIZE: u32 = 0x0010_0000;
|
||||
pub(super) const SYNCHRONIZE: u32 = 0x0010_0000;
|
||||
const EVENT_ALL_ACCESS: u32 = 0x001f_0003;
|
||||
const WAIT_OBJECT_0: u64 = 0;
|
||||
const INFINITE: u32 = u32::MAX;
|
||||
const TICKS_PER_MILLI: u64 = 10_000;
|
||||
const WAIT_TIMEOUT: u64 = 258;
|
||||
const WAIT_FAILED: u64 = u32::MAX as u64;
|
||||
const WAIT_ABANDONED_0: u64 = 0x80;
|
||||
|
||||
const SEMAPHORE_ALL_ACCESS: u32 = 0x001f_0003;
|
||||
const SEMAPHORE_MODIFY_STATE: u32 = 2;
|
||||
@@ -40,6 +46,13 @@ pub(super) enum Waitable {
|
||||
Mutex {
|
||||
owner: Option<u64>,
|
||||
recursion: u32,
|
||||
/// The owner ended without releasing it.
|
||||
abandoned: bool,
|
||||
},
|
||||
/// Signaled for good once the guest thread has ended.
|
||||
Thread {
|
||||
id: u32,
|
||||
exit_code: Option<u32>,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -49,21 +62,30 @@ impl Waitable {
|
||||
Self::Event { signaled, .. } => *signaled,
|
||||
Self::Semaphore { count, .. } => *count > 0,
|
||||
Self::Mutex { owner, .. } => owner.is_none_or(|owner| owner == teb),
|
||||
Self::Thread { exit_code, .. } => exit_code.is_some(),
|
||||
}
|
||||
}
|
||||
|
||||
fn consume(&mut self, teb: u64) {
|
||||
/// Take the signal; true if it was an abandoned mutex.
|
||||
fn consume(&mut self, teb: u64) -> bool {
|
||||
match self {
|
||||
Self::Event {
|
||||
manual_reset,
|
||||
signaled,
|
||||
} => *signaled = *manual_reset,
|
||||
Self::Semaphore { count, .. } => *count -= 1,
|
||||
Self::Mutex { owner, recursion } => {
|
||||
Self::Mutex {
|
||||
owner,
|
||||
recursion,
|
||||
abandoned,
|
||||
} => {
|
||||
*owner = Some(teb);
|
||||
*recursion += 1;
|
||||
return std::mem::take(abandoned);
|
||||
}
|
||||
Self::Thread { .. } => {}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn at_recursion_limit(&self) -> bool {
|
||||
@@ -100,6 +122,7 @@ fn insert_mutex(
|
||||
let object = Waitable::Mutex {
|
||||
owner: initial_owner.then_some(teb),
|
||||
recursion: u32::from(initial_owner),
|
||||
abandoned: false,
|
||||
};
|
||||
insert_waitable(state, teb, object, access)
|
||||
}
|
||||
@@ -150,6 +173,9 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
|
||||
return state.fail(cpu.gs_base, ERROR_ACCESS_DENIED, 0);
|
||||
}
|
||||
*current = signaled;
|
||||
if signaled {
|
||||
state.hooks.signal();
|
||||
}
|
||||
Ok(1)
|
||||
});
|
||||
}
|
||||
@@ -202,6 +228,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
|
||||
return release.fail(cpu.gs_base, ERROR_NOACCESS, 0);
|
||||
}
|
||||
*count += amount;
|
||||
release.hooks.signal();
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
@@ -244,7 +271,10 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
|
||||
return release.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0);
|
||||
};
|
||||
let mut state = state.lock().expect("guest waitable state");
|
||||
let Waitable::Mutex { owner, recursion } = &mut *state else {
|
||||
let Waitable::Mutex {
|
||||
owner, recursion, ..
|
||||
} = &mut *state
|
||||
else {
|
||||
return release.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0);
|
||||
};
|
||||
if *owner != Some(cpu.gs_base) {
|
||||
@@ -253,6 +283,7 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
|
||||
*recursion -= 1;
|
||||
if *recursion == 0 {
|
||||
*owner = None;
|
||||
release.hooks.signal();
|
||||
}
|
||||
Ok(1)
|
||||
});
|
||||
@@ -263,6 +294,9 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
|
||||
] {
|
||||
let single = Arc::clone(state);
|
||||
registry.register(KERNEL32, symbol, move |args, cpu, mem| {
|
||||
if let Some(result) = resume_wait(&single, cpu.gs_base) {
|
||||
return result;
|
||||
}
|
||||
let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
let timeout = args.get(1, mem).map_err(ExitReason::MemoryFault)? as u32;
|
||||
if extended && args.get(2, mem).map_err(ExitReason::MemoryFault)? as u32 != 0 {
|
||||
@@ -277,6 +311,9 @@ pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>
|
||||
] {
|
||||
let multiple = Arc::clone(state);
|
||||
registry.register(KERNEL32, symbol, move |args, cpu, mem| {
|
||||
if let Some(result) = resume_wait(&multiple, cpu.gs_base) {
|
||||
return result;
|
||||
}
|
||||
let count = args.get(0, mem).map_err(ExitReason::MemoryFault)? as u32;
|
||||
let address = args.get(1, mem).map_err(ExitReason::MemoryFault)?;
|
||||
let all = args.get(2, mem).map_err(ExitReason::MemoryFault)? as u32 != 0;
|
||||
@@ -363,21 +400,75 @@ fn wait_for_objects(
|
||||
None => return state.fail(teb, ERROR_INVALID_HANDLE, WAIT_FAILED),
|
||||
}
|
||||
}
|
||||
let mut ready = Vec::with_capacity(handles.len());
|
||||
for (index, event) in waitables.into_iter().enumerate() {
|
||||
if event.lock().expect("guest waitable state").is_ready(teb) {
|
||||
ready.push((index, event));
|
||||
if let Some(result) = try_satisfy(&waitables, all, teb) {
|
||||
return result;
|
||||
}
|
||||
if timeout == 0 {
|
||||
return Ok(WAIT_TIMEOUT);
|
||||
}
|
||||
if !state.hooks.is_attached() {
|
||||
return state.fail(teb, ERROR_NOT_SUPPORTED, WAIT_FAILED);
|
||||
}
|
||||
// Keep the objects themselves: closing a handle or changing the guest's
|
||||
// handle array does not change a wait already in progress.
|
||||
let deadline = (timeout != INFINITE).then(|| {
|
||||
state
|
||||
.clock
|
||||
.performance_count()
|
||||
.saturating_add(u64::from(timeout) * TICKS_PER_MILLI)
|
||||
});
|
||||
let pending = PendingWait {
|
||||
objects: waitables.into_iter().map(Arc::clone).collect(),
|
||||
all,
|
||||
deadline,
|
||||
};
|
||||
state
|
||||
.threads
|
||||
.lock()
|
||||
.expect("guest thread table")
|
||||
.waits
|
||||
.insert(teb, pending);
|
||||
Err(ExitReason::GuestBlocked)
|
||||
}
|
||||
|
||||
/// Continue the wait this thread is blocked in, if any. Waiters are retried
|
||||
/// directly after a signal, so an object found signaled once the deadline has
|
||||
/// passed was signaled too late and is left alone.
|
||||
fn resume_wait(state: &ServicesState, teb: u64) -> Option<Result<u64, ExitReason>> {
|
||||
let mut table = state.threads.lock().expect("guest thread table");
|
||||
let pending = table.waits.get(&teb)?;
|
||||
let expired = pending
|
||||
.deadline
|
||||
.is_some_and(|deadline| state.clock.performance_count() >= deadline);
|
||||
let result = if expired {
|
||||
Some(Ok(WAIT_TIMEOUT))
|
||||
} else {
|
||||
let objects: Vec<&Arc<Mutex<Waitable>>> = pending.objects.iter().collect();
|
||||
try_satisfy(&objects, pending.all, teb)
|
||||
};
|
||||
if result.is_some() {
|
||||
table.waits.remove(&teb);
|
||||
}
|
||||
Some(result.unwrap_or(Err(ExitReason::GuestBlocked)))
|
||||
}
|
||||
|
||||
/// Consume the objects if the wait is satisfied now.
|
||||
fn try_satisfy(
|
||||
waitables: &[&Arc<Mutex<Waitable>>],
|
||||
all: bool,
|
||||
teb: u64,
|
||||
) -> Option<Result<u64, ExitReason>> {
|
||||
let mut ready = Vec::with_capacity(waitables.len());
|
||||
for (index, object) in waitables.iter().enumerate() {
|
||||
if object.lock().expect("guest waitable state").is_ready(teb) {
|
||||
ready.push((index, object));
|
||||
if !all {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ready.is_empty() || (all && ready.len() != handles.len()) {
|
||||
return if timeout == 0 {
|
||||
Ok(WAIT_TIMEOUT)
|
||||
} else {
|
||||
state.fail(teb, ERROR_NOT_SUPPORTED, WAIT_FAILED)
|
||||
};
|
||||
if ready.is_empty() || (all && ready.len() != waitables.len()) {
|
||||
return None;
|
||||
}
|
||||
if ready.iter().any(|(_, object)| {
|
||||
object
|
||||
@@ -386,11 +477,42 @@ fn wait_for_objects(
|
||||
.at_recursion_limit()
|
||||
}) {
|
||||
// Windows raises STATUS_MUTANT_LIMIT_EXCEEDED; exceptions are unsupported.
|
||||
return Err(ExitReason::IllegalInstruction(0xFE));
|
||||
return Some(Err(ExitReason::IllegalInstruction(0xFE)));
|
||||
}
|
||||
let first = ready[0].0;
|
||||
for (_, event) in ready {
|
||||
event.lock().expect("guest waitable state").consume(teb);
|
||||
let first = ready[0].0 as u64;
|
||||
let mut abandoned = None;
|
||||
for (index, object) in ready {
|
||||
if object.lock().expect("guest waitable state").consume(teb) {
|
||||
abandoned.get_or_insert(index as u64);
|
||||
}
|
||||
}
|
||||
Some(Ok(match abandoned {
|
||||
Some(index) => WAIT_ABANDONED_0 + index,
|
||||
None => WAIT_OBJECT_0 + first,
|
||||
}))
|
||||
}
|
||||
|
||||
impl ServicesState {
|
||||
/// Release every mutex owned by a guest thread that has ended.
|
||||
pub(super) fn abandon_mutexes(&self, teb: u64) {
|
||||
let objects = self.objects.lock().expect("guest object state");
|
||||
let table = self.threads.lock().expect("guest thread table");
|
||||
let handles = objects.handles.values().filter_map(|object| match object {
|
||||
GuestObject::Waitable { state, .. } => Some(state),
|
||||
_ => None,
|
||||
});
|
||||
// A waiter keeps an object alive after its last handle is closed.
|
||||
let waiting = table.waits.values().flat_map(|wait| &wait.objects);
|
||||
for object in handles.chain(waiting) {
|
||||
if let Waitable::Mutex {
|
||||
owner,
|
||||
recursion,
|
||||
abandoned,
|
||||
} = &mut *object.lock().expect("guest waitable state")
|
||||
&& *owner == Some(teb)
|
||||
{
|
||||
(*owner, *recursion, *abandoned) = (None, 0, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(WAIT_OBJECT_0 + first as u64)
|
||||
}
|
||||
@@ -41,6 +41,18 @@ struct ScheduledCallback {
|
||||
}
|
||||
|
||||
impl QueueHandles {
|
||||
/// Task-queue handles the guest has open.
|
||||
pub(super) fn open_count(&self) -> usize {
|
||||
self.queues.len()
|
||||
}
|
||||
|
||||
/// Process exit: every handle is closed and nothing stays scheduled.
|
||||
pub(super) fn close_all(&mut self) {
|
||||
self.queues.clear();
|
||||
self.terminated.clear();
|
||||
self.pending.clear();
|
||||
}
|
||||
|
||||
fn open(
|
||||
&mut self,
|
||||
duplicate: Option<Queue>,
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Process termination.
|
||||
|
||||
use super::{KERNEL32, ServicesState};
|
||||
use crate::cpu::ExitReason;
|
||||
use crate::imports::{ImportRegistry, ServiceStatus};
|
||||
use std::sync::Arc;
|
||||
|
||||
const PROCESS_THREADS_API: &str = "api-ms-win-core-processthreads-l1-1-0.dll";
|
||||
|
||||
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
// ExitProcess does not return (processthreadsapi.h). It stops the guest
|
||||
// with its status and never ends the host. It is partial: there are no
|
||||
// other threads or loaded DLLs to notify.
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "ExitProcess", move |args, _, _| {
|
||||
// The status is a UINT, the low half of the first argument.
|
||||
Err(ExitReason::ProcessExit(s.exit_process(args.rcx as u32)))
|
||||
});
|
||||
registry.alias(PROCESS_THREADS_API, KERNEL32, "ExitProcess");
|
||||
registry.set_status(KERNEL32, "ExitProcess", ServiceStatus::Partial);
|
||||
}
|
||||
@@ -3,9 +3,10 @@
|
||||
//! Critical sections, slim reader/writer locks, condition variables, one-time
|
||||
//! initialization, interlocked singly linked lists and thread-local storage.
|
||||
//!
|
||||
//! Ownership is keyed by the calling guest TEB. No guest scheduler exists yet,
|
||||
//! so an operation that would have to block another guest thread stops the
|
||||
//! guest with the runtime-limit fault instead of pretending to synchronize.
|
||||
//! Ownership is keyed by the calling guest TEB. These objects do not block
|
||||
//! through the guest scheduler yet, so an operation that would have to wait for
|
||||
//! another guest thread stops the guest with the runtime-limit fault instead of
|
||||
//! pretending to synchronize.
|
||||
|
||||
use super::{
|
||||
ERROR_INVALID_PARAMETER, ERROR_NOT_ENOUGH_MEMORY, ERROR_NOT_SUPPORTED, KERNEL32, ServicesState,
|
||||
@@ -37,6 +38,9 @@ const CRITICAL_SECTION_NO_DEBUG_INFO: u32 = 0x0100_0000;
|
||||
const MAX_CRITICAL_SECTIONS: usize = 4096;
|
||||
|
||||
const MAX_SRW_LOCKS: usize = 4096;
|
||||
const MAX_PENDING_INIT_ONCE: usize = 4096;
|
||||
/// Owner of a lock whose thread ended while holding it. Never a TEB address.
|
||||
const ENDED_THREAD: u64 = u64::MAX;
|
||||
const CONDITION_VARIABLE_LOCKMODE_SHARED: u32 = 1;
|
||||
|
||||
const INIT_ONCE_CHECK_ONLY: u32 = 1;
|
||||
@@ -161,6 +165,33 @@ pub(super) struct Synch {
|
||||
}
|
||||
|
||||
impl Synch {
|
||||
/// Drop the thread-local values of a guest thread that has ended, without
|
||||
/// running FLS callbacks. Locks it held stay held: its TEB address may be
|
||||
/// reused, and the next thread there must not own them.
|
||||
pub(super) fn retire_thread(&mut self, teb: u64) {
|
||||
self.tls_values.retain(|&(owner, _), _| owner != teb);
|
||||
self.fls_values.retain(|&(owner, _), _| owner != teb);
|
||||
for section in self.sections.values_mut() {
|
||||
if section.owner == Some(teb) {
|
||||
section.owner = Some(ENDED_THREAD);
|
||||
}
|
||||
}
|
||||
for lock in self.srw.values_mut() {
|
||||
if lock.exclusive == Some(teb) {
|
||||
lock.exclusive = Some(ENDED_THREAD);
|
||||
}
|
||||
if let Some(count) = lock.shared.remove(&teb) {
|
||||
let held = lock.shared.entry(ENDED_THREAD).or_default();
|
||||
*held = held.saturating_add(count);
|
||||
}
|
||||
}
|
||||
for owner in self.init_once_pending.values_mut() {
|
||||
if *owner == teb {
|
||||
*owner = ENDED_THREAD;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn section(&mut self, address: u64) -> Result<&mut CriticalSection, ExitReason> {
|
||||
// Using an uninitialized critical section is undefined; report it.
|
||||
self.sections.get_mut(&address).map_or_else(unsupported, Ok)
|
||||
@@ -228,6 +259,7 @@ fn enter_section(
|
||||
address: u64,
|
||||
teb: u64,
|
||||
) -> Result<bool, ExitReason> {
|
||||
let thread_id = state.thread_id_of(teb);
|
||||
let mut synch = state.synch.lock().expect("guest synchronization state");
|
||||
let section = synch.section(address)?;
|
||||
match section.owner {
|
||||
@@ -237,7 +269,7 @@ fn enter_section(
|
||||
}
|
||||
section.owner = Some(teb);
|
||||
section.recursion += 1;
|
||||
mirror_section(memory, address, section, state.thread_id)?;
|
||||
mirror_section(memory, address, section, thread_id)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
@@ -247,6 +279,7 @@ fn leave_section(
|
||||
address: u64,
|
||||
teb: u64,
|
||||
) -> Result<(), ExitReason> {
|
||||
let thread_id = state.thread_id_of(teb);
|
||||
let mut synch = state.synch.lock().expect("guest synchronization state");
|
||||
let section = synch.section(address)?;
|
||||
if section.owner != Some(teb) {
|
||||
@@ -256,7 +289,7 @@ fn leave_section(
|
||||
if section.recursion == 0 {
|
||||
section.owner = None;
|
||||
}
|
||||
mirror_section(memory, address, section, state.thread_id)
|
||||
mirror_section(memory, address, section, thread_id)
|
||||
}
|
||||
|
||||
/// Check that a pointer-sized synchronization object is readable and writable.
|
||||
@@ -611,8 +644,9 @@ fn register_srw_and_conditions(registry: &mut ImportRegistry, state: &Arc<Servic
|
||||
}
|
||||
}
|
||||
|
||||
/// A zero timeout releases and reacquires the lock, which no other guest
|
||||
/// thread can observe, then reports the timeout. Longer sleeps would block.
|
||||
/// A zero timeout releases and reacquires the lock within one service call, so
|
||||
/// no other guest thread can observe it, then reports the timeout. Longer sleeps
|
||||
/// would block.
|
||||
fn sleep_result(state: &ServicesState, teb: u64, timeout: u32) -> Result<u64, ExitReason> {
|
||||
if timeout == 0 {
|
||||
state.fail(teb, ERROR_TIMEOUT, 0)
|
||||
@@ -666,6 +700,9 @@ fn register_init_once(registry: &mut ImportRegistry, state: &Arc<ServicesState>)
|
||||
s.fail(teb, ERROR_GEN_FAILURE, 0)
|
||||
}
|
||||
0 if value == 0 => {
|
||||
if synch.init_once_pending.len() >= MAX_PENDING_INIT_ONCE {
|
||||
return unsupported();
|
||||
}
|
||||
mem.write_u32(pending, 1).map_err(fault)?;
|
||||
mem.write_u64(once, INIT_ONCE_PENDING).map_err(fault)?;
|
||||
synch.init_once_pending.insert(once, teb);
|
||||
@@ -727,6 +764,9 @@ fn register_init_once(registry: &mut ImportRegistry, state: &Arc<ServicesState>)
|
||||
return unsupported();
|
||||
}
|
||||
let mut synch = s.synch.lock().expect("guest synchronization state");
|
||||
if synch.init_once_pending.len() >= MAX_PENDING_INIT_ONCE {
|
||||
return unsupported();
|
||||
}
|
||||
mem.write_u64(scratch, 0).map_err(fault)?;
|
||||
mem.write_u64(once, INIT_ONCE_PENDING).map_err(fault)?;
|
||||
synch.init_once_pending.insert(once, teb);
|
||||
|
||||
@@ -0,0 +1,590 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Guest thread table and the thread services.
|
||||
//!
|
||||
//! A guest thread is a CPU context, a guarded stack and a TEB. It is not a host
|
||||
//! thread: [`crate::scheduler`] runs one guest thread at a time on one host
|
||||
//! thread. Without an attached scheduler `CreateThread` reports
|
||||
//! `ERROR_NOT_SUPPORTED`, no thread object exists, and waits behave as they do
|
||||
//! for a single thread.
|
||||
|
||||
use super::events::{SYNCHRONIZE, Waitable};
|
||||
use super::{
|
||||
CURRENT_THREAD, ERROR_ACCESS_DENIED, ERROR_INVALID_HANDLE, ERROR_INVALID_PARAMETER,
|
||||
ERROR_NOACCESS, ERROR_NOT_ENOUGH_MEMORY, ERROR_NOT_SUPPORTED, GuestObject, KERNEL32, PAGE_SIZE,
|
||||
PROCESS_THREADS_V1, ServicesState, THREAD_QUERY_RIGHTS,
|
||||
};
|
||||
use crate::cpu::{CpuState, ExitReason, Register};
|
||||
use crate::imports::{ImportRegistry, ServiceStatus};
|
||||
use crate::memory::{ALLOCATION_GRANULARITY, GuestMemory, MemoryError, MemoryPermissions};
|
||||
use std::collections::{BTreeMap, BTreeSet, VecDeque};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
/// Most guest threads alive at once, the main thread included.
|
||||
pub const MAX_THREADS: usize = 64;
|
||||
/// Stack of a thread created with a zero size.
|
||||
pub const DEFAULT_STACK: u64 = 256 * 1024;
|
||||
const MAX_STACK: u64 = 8 * 1024 * 1024;
|
||||
/// Highest suspend count (MAXIMUM_SUSPEND_COUNT).
|
||||
const MAX_SUSPEND: u32 = 127;
|
||||
/// GetExitCodeThread result while the thread runs.
|
||||
const STILL_ACTIVE: u32 = 259;
|
||||
const CREATE_SUSPENDED: u32 = 4;
|
||||
const STACK_SIZE_PARAM_IS_A_RESERVATION: u32 = 0x0001_0000;
|
||||
pub(super) const THREAD_ALL_ACCESS: u32 = 0x001F_FFFF;
|
||||
const THREAD_TERMINATE: u32 = 1;
|
||||
const THREAD_SUSPEND_RESUME: u32 = 2;
|
||||
/// Rights that exist only on worker thread objects.
|
||||
pub(super) const WORKER_RIGHTS: u32 = THREAD_TERMINATE | THREAD_SUSPEND_RESUME;
|
||||
const ERROR_SIGNAL_REFUSED: u32 = 156;
|
||||
|
||||
/// Each thread slot holds a guard page, the stack, a guard page and the TEB.
|
||||
const THREAD_AREA: u64 = 0x0000_0006_0000_0000;
|
||||
const THREAD_STRIDE: u64 = 0x0100_0000;
|
||||
const TEB_OFFSET: u64 = 0x00F0_0000;
|
||||
const TEB_SIZE: u64 = 0x2000;
|
||||
const TEB_STACK_BASE: u64 = 0x08;
|
||||
const TEB_STACK_LIMIT: u64 = 0x10;
|
||||
const TEB_SELF: u64 = 0x30;
|
||||
|
||||
/// Return address of a thread's start routine. Nothing is mapped there.
|
||||
pub(crate) const THREAD_RETURN: u64 = 0xFFFF_FFFF_FFFE_0000;
|
||||
|
||||
/// How a service asked the scheduler to act after it completed.
|
||||
const SWITCH_NONE: u8 = 0;
|
||||
const SWITCH_SIGNAL: u8 = 1;
|
||||
const SWITCH_YIELD: u8 = 2;
|
||||
|
||||
/// Shared between the services, the import dispatcher and the scheduler.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct SchedulerHooks {
|
||||
attached: AtomicBool,
|
||||
switch: AtomicU8,
|
||||
}
|
||||
|
||||
impl SchedulerHooks {
|
||||
pub(crate) fn is_attached(&self) -> bool {
|
||||
self.attached.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// An object other threads may wait for changed.
|
||||
pub(super) fn signal(&self) {
|
||||
if self.is_attached() {
|
||||
self.switch.fetch_max(SWITCH_SIGNAL, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
fn yield_turn(&self) {
|
||||
self.switch.store(SWITCH_YIELD, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// Whether the dispatcher should stop the current thread after the call.
|
||||
pub(crate) fn switch_requested(&self) -> bool {
|
||||
self.switch.load(Ordering::SeqCst) != SWITCH_NONE
|
||||
}
|
||||
|
||||
/// Take the request; true if the thread gives up its turn.
|
||||
pub(crate) fn take_switch(&self) -> bool {
|
||||
self.switch.swap(SWITCH_NONE, Ordering::SeqCst) == SWITCH_YIELD
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum RunState {
|
||||
Ready,
|
||||
/// Waiting in a service; the sequence number orders waiters.
|
||||
Blocked(u64),
|
||||
}
|
||||
|
||||
pub(crate) struct GuestThread {
|
||||
teb: u64,
|
||||
/// Taken by the scheduler while the thread runs.
|
||||
pub(crate) cpu: Option<CpuState>,
|
||||
pub(crate) run: RunState,
|
||||
pub(crate) suspend: u32,
|
||||
/// What is left of a turn the thread interrupted by signaling.
|
||||
pub(crate) credit: Option<usize>,
|
||||
object: Arc<Mutex<Waitable>>,
|
||||
slot: Option<u64>,
|
||||
allocations: Vec<u64>,
|
||||
/// Set by ExitThread and TerminateThread.
|
||||
pub(crate) exit: Option<u32>,
|
||||
}
|
||||
|
||||
/// Objects a blocked thread waits for, captured when it first blocked.
|
||||
pub(super) struct PendingWait {
|
||||
pub(super) objects: Vec<Arc<Mutex<Waitable>>>,
|
||||
pub(super) all: bool,
|
||||
pub(super) deadline: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct ThreadTable {
|
||||
pub(crate) threads: BTreeMap<u32, GuestThread>,
|
||||
/// Ready threads in the order they run.
|
||||
pub(crate) queue: VecDeque<u32>,
|
||||
pub(super) waits: BTreeMap<u64, PendingWait>,
|
||||
/// Main thread wait of a run that stopped on its budget, and the context
|
||||
/// that continues it.
|
||||
continued: Option<(CpuState, PendingWait)>,
|
||||
slots: BTreeSet<u64>,
|
||||
last_id: u32,
|
||||
pub(crate) sequence: u64,
|
||||
}
|
||||
|
||||
impl ThreadTable {
|
||||
fn id_of(&self, teb: u64) -> Option<u32> {
|
||||
self.threads
|
||||
.iter()
|
||||
.find(|(_, thread)| thread.teb == teb)
|
||||
.map(|(&id, _)| id)
|
||||
}
|
||||
|
||||
fn by_object(&mut self, object: &Arc<Mutex<Waitable>>) -> Option<&mut GuestThread> {
|
||||
self.threads
|
||||
.values_mut()
|
||||
.find(|thread| Arc::ptr_eq(&thread.object, object))
|
||||
}
|
||||
|
||||
/// Earliest deadline of any wait that is not suspended away.
|
||||
pub(crate) fn next_deadline(&self) -> Option<u64> {
|
||||
self.threads
|
||||
.values()
|
||||
.filter(|thread| thread.suspend == 0 && thread.run != RunState::Ready)
|
||||
.filter_map(|thread| self.waits.get(&thread.teb)?.deadline)
|
||||
.min()
|
||||
}
|
||||
}
|
||||
|
||||
/// Arguments of CreateThread.
|
||||
struct ThreadRequest {
|
||||
stack: u64,
|
||||
start: u64,
|
||||
parameter: u64,
|
||||
suspended: bool,
|
||||
/// `stack` is the reservation rather than the initial commitment.
|
||||
reservation: bool,
|
||||
id_output: u64,
|
||||
}
|
||||
|
||||
fn map_thread(
|
||||
memory: &mut GuestMemory,
|
||||
base: u64,
|
||||
stack: u64,
|
||||
allocations: &mut Vec<u64>,
|
||||
) -> Result<(), MemoryError> {
|
||||
let low = base + PAGE_SIZE;
|
||||
let top = low + stack;
|
||||
let teb = base + TEB_OFFSET;
|
||||
for (address, size, permissions) in [
|
||||
(base, PAGE_SIZE, MemoryPermissions::NO_ACCESS),
|
||||
(low, stack, MemoryPermissions::READ_WRITE),
|
||||
(top, PAGE_SIZE, MemoryPermissions::NO_ACCESS),
|
||||
(teb, TEB_SIZE, MemoryPermissions::READ_WRITE),
|
||||
] {
|
||||
allocations.push(memory.map_thread_region(address, size as usize, permissions)?);
|
||||
}
|
||||
// A recycled TEB address must not inherit the previous thread's errno.
|
||||
let errno = memory.crt_errno_address(teb)?;
|
||||
memory.write_u32_bypass(errno, 0)?;
|
||||
memory.write_u64_bypass(teb + TEB_STACK_BASE, top)?;
|
||||
memory.write_u64_bypass(teb + TEB_STACK_LIMIT, low)?;
|
||||
memory.write_u64_bypass(teb + TEB_SELF, teb)
|
||||
}
|
||||
|
||||
impl ServicesState {
|
||||
/// Adopt the calling context as the main guest thread.
|
||||
pub(crate) fn attach_scheduler(&self, main: &CpuState) -> Result<u32, ExitReason> {
|
||||
let mut table = self.threads.lock().expect("guest thread table");
|
||||
if self.hooks.attached.swap(true, Ordering::SeqCst) {
|
||||
return Err(ExitReason::ServiceAbiViolation);
|
||||
}
|
||||
// IDs are never reused, even by a later run.
|
||||
table.last_id = table.last_id.max(self.thread_id);
|
||||
table.threads.insert(
|
||||
self.thread_id,
|
||||
GuestThread {
|
||||
teb: main.gs_base,
|
||||
cpu: Some(main.clone()),
|
||||
run: RunState::Ready,
|
||||
suspend: 0,
|
||||
credit: None,
|
||||
object: Arc::new(Mutex::new(Waitable::Thread {
|
||||
id: self.thread_id,
|
||||
exit_code: None,
|
||||
})),
|
||||
slot: None,
|
||||
allocations: Vec::new(),
|
||||
exit: None,
|
||||
},
|
||||
);
|
||||
table.queue.push_back(self.thread_id);
|
||||
if let Some((context, wait)) = table.continued.take()
|
||||
&& context == *main
|
||||
{
|
||||
table.waits.insert(main.gs_base, wait);
|
||||
}
|
||||
Ok(self.thread_id)
|
||||
}
|
||||
|
||||
/// Reclaim every created thread. The main thread keeps its per-thread state.
|
||||
/// `continues` is its context if the run stopped on its budget; its pending
|
||||
/// wait is then kept for that context.
|
||||
pub(crate) fn detach_scheduler(&self, memory: &mut GuestMemory, continues: Option<&CpuState>) {
|
||||
let workers: Vec<u32> = {
|
||||
let table = self.threads.lock().expect("guest thread table");
|
||||
let worker = |(&id, thread): (&u32, &GuestThread)| thread.slot.map(|_| id);
|
||||
table.threads.iter().filter_map(worker).collect()
|
||||
};
|
||||
for id in workers {
|
||||
self.end_thread(id, 0, memory);
|
||||
}
|
||||
let mut table = self.threads.lock().expect("guest thread table");
|
||||
if let Some(context) = continues {
|
||||
let wait = table.waits.remove(&context.gs_base);
|
||||
table.continued = wait.map(|wait| (context.clone(), wait));
|
||||
}
|
||||
table.threads.clear();
|
||||
table.queue.clear();
|
||||
table.waits.clear();
|
||||
drop(table);
|
||||
self.hooks.switch.store(SWITCH_NONE, Ordering::SeqCst);
|
||||
self.hooks.attached.store(false, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// Record a thread's exit code, signal its object and reclaim its state.
|
||||
pub(crate) fn end_thread(&self, id: u32, code: u32, memory: &mut GuestMemory) {
|
||||
let thread = {
|
||||
let mut table = self.threads.lock().expect("guest thread table");
|
||||
let Some(thread) = table.threads.remove(&id) else {
|
||||
return;
|
||||
};
|
||||
table.queue.retain(|&queued| queued != id);
|
||||
table.waits.remove(&thread.teb);
|
||||
if let Some(slot) = thread.slot {
|
||||
table.slots.remove(&slot);
|
||||
}
|
||||
thread
|
||||
};
|
||||
if let Waitable::Thread { exit_code, .. } =
|
||||
&mut *thread.object.lock().expect("guest waitable state")
|
||||
{
|
||||
*exit_code = Some(code);
|
||||
}
|
||||
self.abandon_mutexes(thread.teb);
|
||||
self.retire_thread_last_error(thread.teb);
|
||||
self.synch
|
||||
.lock()
|
||||
.expect("guest synchronization state")
|
||||
.retire_thread(thread.teb);
|
||||
memory
|
||||
.callback_frames
|
||||
.retain(|&(teb, _), _| teb != thread.teb);
|
||||
for base in thread.allocations {
|
||||
memory.release_thread_region(base);
|
||||
}
|
||||
self.hooks.signal();
|
||||
}
|
||||
|
||||
/// ID of the guest thread whose TEB is `teb`.
|
||||
pub(super) fn thread_id_of(&self, teb: u64) -> u32 {
|
||||
self.threads
|
||||
.lock()
|
||||
.expect("guest thread table")
|
||||
.id_of(teb)
|
||||
.unwrap_or(self.thread_id)
|
||||
}
|
||||
|
||||
/// Whether the main thread can still be named by its ID.
|
||||
pub(super) fn main_thread_alive(&self) -> bool {
|
||||
let table = self.threads.lock().expect("guest thread table");
|
||||
!self.hooks.is_attached() || table.threads.contains_key(&self.thread_id)
|
||||
}
|
||||
|
||||
/// Thread object for an ID, if that thread is alive and not the main thread.
|
||||
pub(super) fn worker_object(&self, id: u32) -> Option<Arc<Mutex<Waitable>>> {
|
||||
let table = self.threads.lock().expect("guest thread table");
|
||||
table
|
||||
.threads
|
||||
.get(&id)
|
||||
.filter(|thread| thread.slot.is_some())
|
||||
.map(|thread| Arc::clone(&thread.object))
|
||||
}
|
||||
|
||||
/// Thread object of the calling worker, or `None` in the main thread.
|
||||
pub(super) fn current_worker(&self, teb: u64) -> Option<Arc<Mutex<Waitable>>> {
|
||||
let table = self.threads.lock().expect("guest thread table");
|
||||
let thread = table.threads.get(&table.id_of(teb)?)?;
|
||||
thread.slot.map(|_| Arc::clone(&thread.object))
|
||||
}
|
||||
|
||||
fn create_thread(
|
||||
&self,
|
||||
teb: u64,
|
||||
memory: &mut GuestMemory,
|
||||
request: &ThreadRequest,
|
||||
) -> Result<u64, ExitReason> {
|
||||
if request.id_output != 0 && memory.check_write(request.id_output, 4).is_err() {
|
||||
return self.fail(teb, ERROR_NOACCESS, 0);
|
||||
}
|
||||
// Without the reservation flag the size is an initial commitment, and
|
||||
// the reservation is at least the default.
|
||||
let stack = if request.stack == 0 || !request.reservation {
|
||||
request.stack.max(DEFAULT_STACK)
|
||||
} else {
|
||||
request.stack
|
||||
};
|
||||
let Some(stack) = stack
|
||||
.checked_next_multiple_of(ALLOCATION_GRANULARITY)
|
||||
.filter(|&size| size <= MAX_STACK)
|
||||
else {
|
||||
return self.fail(teb, ERROR_NOT_ENOUGH_MEMORY, 0);
|
||||
};
|
||||
let mut objects = self.objects.lock().expect("guest object state");
|
||||
let mut table = self.threads.lock().expect("guest thread table");
|
||||
let handle = objects.next_handle();
|
||||
let id = table.last_id.checked_add(4);
|
||||
let (Some(handle), Some(id), true) = (handle, id, table.threads.len() < MAX_THREADS) else {
|
||||
return self.fail(teb, ERROR_NOT_ENOUGH_MEMORY, 0);
|
||||
};
|
||||
// A slot the guest has mapped something into is skipped.
|
||||
let mut prepared = None;
|
||||
for slot in (0..2 * MAX_THREADS as u64).filter(|slot| !table.slots.contains(slot)) {
|
||||
let base = THREAD_AREA + slot * THREAD_STRIDE;
|
||||
let mut allocations = Vec::new();
|
||||
// The start routine is entered as if called: RSP is 8 modulo 16,
|
||||
// and above it are the return address and a 32-byte home area.
|
||||
let rsp = base + PAGE_SIZE + stack - 40;
|
||||
let mapped = map_thread(memory, base, stack, &mut allocations)
|
||||
.and_then(|()| memory.write_u64(rsp, THREAD_RETURN));
|
||||
if mapped.is_ok() {
|
||||
prepared = Some((slot, base, rsp, allocations));
|
||||
break;
|
||||
}
|
||||
for base in allocations {
|
||||
memory.release_thread_region(base);
|
||||
}
|
||||
if !matches!(mapped, Err(MemoryError::OverlappingRegion { .. })) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let Some((slot, base, rsp, allocations)) = prepared else {
|
||||
return self.fail(teb, ERROR_NOT_ENOUGH_MEMORY, 0);
|
||||
};
|
||||
if request.id_output != 0 {
|
||||
memory
|
||||
.write_u32(request.id_output, id)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
}
|
||||
let mut cpu = CpuState::new(request.start, rsp);
|
||||
cpu.gs_base = base + TEB_OFFSET;
|
||||
cpu.set(Register::Rcx, request.parameter);
|
||||
let object = Arc::new(Mutex::new(Waitable::Thread {
|
||||
id,
|
||||
exit_code: None,
|
||||
}));
|
||||
objects.insert_handle(
|
||||
handle,
|
||||
GuestObject::Waitable {
|
||||
state: Arc::clone(&object),
|
||||
access: THREAD_ALL_ACCESS,
|
||||
},
|
||||
);
|
||||
table.slots.insert(slot);
|
||||
table.last_id = id;
|
||||
table.threads.insert(
|
||||
id,
|
||||
GuestThread {
|
||||
teb: base + TEB_OFFSET,
|
||||
cpu: Some(cpu),
|
||||
run: RunState::Ready,
|
||||
suspend: u32::from(request.suspended),
|
||||
credit: None,
|
||||
object,
|
||||
slot: Some(slot),
|
||||
allocations,
|
||||
exit: None,
|
||||
},
|
||||
);
|
||||
table.queue.push_back(id);
|
||||
Ok(handle)
|
||||
}
|
||||
|
||||
/// Thread object and granted rights behind a handle.
|
||||
fn thread_handle(&self, teb: u64, handle: u64) -> Result<(Arc<Mutex<Waitable>>, u32), u32> {
|
||||
if handle == CURRENT_THREAD {
|
||||
let mut table = self.threads.lock().expect("guest thread table");
|
||||
let id = table.id_of(teb).ok_or(ERROR_INVALID_HANDLE)?;
|
||||
let thread = table.threads.get_mut(&id).ok_or(ERROR_INVALID_HANDLE)?;
|
||||
return Ok((Arc::clone(&thread.object), THREAD_ALL_ACCESS));
|
||||
}
|
||||
let objects = self.objects.lock().expect("guest object state");
|
||||
match objects.handles.get(&handle) {
|
||||
Some(GuestObject::Waitable { state, access })
|
||||
if matches!(
|
||||
*state.lock().expect("guest waitable state"),
|
||||
Waitable::Thread { .. }
|
||||
) =>
|
||||
{
|
||||
Ok((Arc::clone(state), *access))
|
||||
}
|
||||
// Handles to the main thread from OpenThread name no object.
|
||||
Some(GuestObject::Thread(_)) => Err(ERROR_NOT_SUPPORTED),
|
||||
_ => Err(ERROR_INVALID_HANDLE),
|
||||
}
|
||||
}
|
||||
|
||||
/// Change another thread's suspend count and return the previous one.
|
||||
fn change_suspend(&self, teb: u64, handle: u64, resume: bool) -> Result<u64, ExitReason> {
|
||||
const FAILED: u64 = u32::MAX as u64;
|
||||
let (object, access) = match self.thread_handle(teb, handle) {
|
||||
Ok(found) => found,
|
||||
Err(error) => return self.fail(teb, error, FAILED),
|
||||
};
|
||||
if access & THREAD_SUSPEND_RESUME == 0 {
|
||||
return self.fail(teb, ERROR_ACCESS_DENIED, FAILED);
|
||||
}
|
||||
let mut table = self.threads.lock().expect("guest thread table");
|
||||
let Some(thread) = table.by_object(&object) else {
|
||||
return self.fail(teb, ERROR_ACCESS_DENIED, FAILED); // terminated
|
||||
};
|
||||
let previous = thread.suspend;
|
||||
if resume {
|
||||
thread.suspend = previous.saturating_sub(1);
|
||||
} else if previous >= MAX_SUSPEND {
|
||||
return self.fail(teb, ERROR_SIGNAL_REFUSED, FAILED);
|
||||
} else {
|
||||
thread.suspend = previous + 1;
|
||||
}
|
||||
drop(table);
|
||||
self.hooks.signal();
|
||||
Ok(u64::from(previous))
|
||||
}
|
||||
|
||||
fn terminate(
|
||||
&self,
|
||||
teb: u64,
|
||||
handle: u64,
|
||||
code: u32,
|
||||
memory: &mut GuestMemory,
|
||||
) -> Result<u64, ExitReason> {
|
||||
let (object, access) = match self.thread_handle(teb, handle) {
|
||||
Ok(found) => found,
|
||||
Err(error) => return self.fail(teb, error, 0),
|
||||
};
|
||||
if access & THREAD_TERMINATE == 0 {
|
||||
return self.fail(teb, ERROR_ACCESS_DENIED, 0);
|
||||
}
|
||||
let mut table = self.threads.lock().expect("guest thread table");
|
||||
let Some(id) = table
|
||||
.threads
|
||||
.iter()
|
||||
.find(|(_, thread)| Arc::ptr_eq(&thread.object, &object))
|
||||
.map(|(&id, _)| id)
|
||||
else {
|
||||
return self.fail(teb, ERROR_ACCESS_DENIED, 0); // already terminated
|
||||
};
|
||||
let thread = table.threads.get_mut(&id).expect("thread found above");
|
||||
if thread.teb == teb {
|
||||
thread.exit = Some(code);
|
||||
return Err(ExitReason::GuestThreadExited);
|
||||
}
|
||||
drop(table);
|
||||
self.end_thread(id, code, memory);
|
||||
Ok(1)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "CreateThread", move |args, cpu, memory| {
|
||||
let arg = |index| args.get(index, memory).map_err(ExitReason::MemoryFault);
|
||||
let attributes = arg(0)?;
|
||||
let flags = arg(4)? as u32;
|
||||
let request = ThreadRequest {
|
||||
stack: arg(1)?,
|
||||
start: arg(2)?,
|
||||
parameter: arg(3)?,
|
||||
suspended: flags & CREATE_SUSPENDED != 0,
|
||||
reservation: flags & STACK_SIZE_PARAM_IS_A_RESERVATION != 0,
|
||||
id_output: arg(5)?,
|
||||
};
|
||||
if !s.hooks.is_attached() || attributes != 0 {
|
||||
return s.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
if flags & !(CREATE_SUSPENDED | STACK_SIZE_PARAM_IS_A_RESERVATION) != 0 {
|
||||
return s.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
s.create_thread(cpu.gs_base, memory, &request)
|
||||
});
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "ExitThread", move |args, cpu, _| {
|
||||
let mut table = s.threads.lock().expect("guest thread table");
|
||||
let Some(id) = table.id_of(cpu.gs_base) else {
|
||||
return Err(ExitReason::IllegalInstruction(0xFE));
|
||||
};
|
||||
table.threads.get_mut(&id).expect("thread found above").exit = Some(args.rcx as u32);
|
||||
Err(ExitReason::GuestThreadExited)
|
||||
});
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "TerminateThread", move |args, cpu, memory| {
|
||||
s.terminate(cpu.gs_base, args.rcx, args.rdx as u32, memory)
|
||||
});
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "GetExitCodeThread", move |args, cpu, memory| {
|
||||
let (object, access) = match s.thread_handle(cpu.gs_base, args.rcx) {
|
||||
Ok(found) => found,
|
||||
Err(error) => return s.fail(cpu.gs_base, error, 0),
|
||||
};
|
||||
if access & THREAD_QUERY_RIGHTS == 0 {
|
||||
return s.fail(cpu.gs_base, ERROR_ACCESS_DENIED, 0);
|
||||
}
|
||||
let code = match &*object.lock().expect("guest waitable state") {
|
||||
Waitable::Thread { exit_code, .. } => exit_code.unwrap_or(STILL_ACTIVE),
|
||||
_ => return s.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0),
|
||||
};
|
||||
if memory.write_u32(args.rdx, code).is_err() {
|
||||
return s.fail(cpu.gs_base, ERROR_NOACCESS, 0);
|
||||
}
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
for (symbol, resume) in [("SuspendThread", false), ("ResumeThread", true)] {
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, symbol, move |args, cpu, _| {
|
||||
s.change_suspend(cpu.gs_base, args.rcx, resume)
|
||||
});
|
||||
}
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "SwitchToThread", move |_, cpu, _| {
|
||||
let table = s.threads.lock().expect("guest thread table");
|
||||
let current = table.id_of(cpu.gs_base);
|
||||
let other = table.threads.iter().any(|(&id, thread)| {
|
||||
Some(id) != current && thread.run == RunState::Ready && thread.suspend == 0
|
||||
});
|
||||
drop(table);
|
||||
if other {
|
||||
s.hooks.yield_turn();
|
||||
}
|
||||
Ok(u64::from(other))
|
||||
});
|
||||
|
||||
for symbol in [
|
||||
"CreateThread",
|
||||
"ExitThread",
|
||||
"TerminateThread",
|
||||
"GetExitCodeThread",
|
||||
"SuspendThread",
|
||||
"ResumeThread",
|
||||
"SwitchToThread",
|
||||
] {
|
||||
registry.alias(PROCESS_THREADS_V1, KERNEL32, symbol);
|
||||
registry.set_status(KERNEL32, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
const _: () = assert!(THREAD_ALL_ACCESS & SYNCHRONIZE != 0);
|
||||
}
|
||||
@@ -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);
|
||||
|
||||
@@ -35,6 +35,7 @@ pub struct Control {
|
||||
pub rounding: Rounding,
|
||||
pub denormals_are_zero: bool,
|
||||
pub flush_to_zero: bool,
|
||||
pub overflow_masked: bool,
|
||||
pub underflow_masked: bool,
|
||||
}
|
||||
|
||||
@@ -49,6 +50,7 @@ impl Control {
|
||||
},
|
||||
denormals_are_zero: mxcsr & 1 << 6 != 0,
|
||||
flush_to_zero: mxcsr & 1 << 15 != 0,
|
||||
overflow_masked: mxcsr & 1 << 10 != 0,
|
||||
underflow_masked: mxcsr & 1 << 11 != 0,
|
||||
}
|
||||
}
|
||||
@@ -263,6 +265,14 @@ fn round(
|
||||
flags |= PRECISION;
|
||||
}
|
||||
if leading > format.bias() {
|
||||
if !control.overflow_masked {
|
||||
// No result is delivered. Precision is reported only if rounding
|
||||
// with an unbounded exponent was inexact.
|
||||
return Outcome {
|
||||
bits: 0,
|
||||
flags: OVERFLOW | if inexact { PRECISION } else { 0 },
|
||||
};
|
||||
}
|
||||
let to_infinity = match control.rounding {
|
||||
Rounding::Nearest => true,
|
||||
Rounding::Down => sign,
|
||||
|
||||
@@ -3,14 +3,16 @@
|
||||
//! Process startup for trusted, original PE32+ fixtures.
|
||||
|
||||
use crate::dbt::DbtMetrics;
|
||||
use crate::tls::TlsError;
|
||||
use crate::{
|
||||
CpuState, DbtEngine, ExecutionResult, ImportRegistry, LoadedImage, MemoryError,
|
||||
CpuState, DbtEngine, ExecutionResult, ExitReason, ImportRegistry, LoadedImage, MemoryError,
|
||||
MemoryPermissions, ParsedPe, PeError, RelocationReport, apply_relocations,
|
||||
execute_tls_callbacks, parse_tls_directory, setup_tls,
|
||||
};
|
||||
|
||||
const STACK_SIZE: usize = 64 * 1024;
|
||||
const JIT_CAPACITY: usize = 1024 * 1024;
|
||||
const RETURN_SENTINEL_PAGE_SIZE: usize = 0x1000;
|
||||
/// The TEB is placed this far above the TLS base and spans two 4 KiB pages.
|
||||
const TEB_OFFSET: u64 = 0x10000;
|
||||
const TEB_SIZE: usize = 0x2000;
|
||||
@@ -95,6 +97,7 @@ pub fn run_synthetic_startup_with_observer(
|
||||
entry_rva: pe.entry_point_rva,
|
||||
});
|
||||
let mut image = pe.load_at_base(bytes, layout.image_base)?;
|
||||
let image_base_field = image.image_base_field;
|
||||
let memory = &mut image.memory;
|
||||
memory
|
||||
.fetch_instruction_byte(image.entry_point)
|
||||
@@ -104,6 +107,12 @@ pub fn run_synthetic_startup_with_observer(
|
||||
});
|
||||
|
||||
let relocations = apply_relocations(&pe, bytes, layout.image_base, memory)?;
|
||||
// The mapped optional header names the base the image is loaded at. This
|
||||
// is written after the relocations so that an entry aimed at the field
|
||||
// itself cannot leave it holding anything else.
|
||||
memory
|
||||
.write_u64_bypass(image_base_field, layout.image_base)
|
||||
.map_err(PeError::SectionMappingError)?;
|
||||
observe(StartupEvent::Relocated {
|
||||
applied_dir64: relocations.applied_dir64,
|
||||
});
|
||||
@@ -123,6 +132,14 @@ pub fn run_synthetic_startup_with_observer(
|
||||
}
|
||||
|
||||
memory.map_region(stack_base, STACK_SIZE, MemoryPermissions::READ_WRITE)?;
|
||||
// Keep guest code and data out of the page that holds the return
|
||||
// addresses the engine intercepts. An image or layout that already covers
|
||||
// it is refused here, and a later guest allocation there fails.
|
||||
memory.map_region(
|
||||
crate::imports::RETURN_SENTINEL_PAGE,
|
||||
RETURN_SENTINEL_PAGE_SIZE,
|
||||
MemoryPermissions::NO_ACCESS,
|
||||
)?;
|
||||
|
||||
map_teb(memory, teb_base, &layout, stack_base)?;
|
||||
|
||||
@@ -132,28 +149,59 @@ pub fn run_synthetic_startup_with_observer(
|
||||
let mut tls_cpu = CpuState::new(image.entry_point, layout.stack_top);
|
||||
tls_cpu.gs_base = teb_base;
|
||||
let mut tls_callbacks = 0;
|
||||
let mut exited_in_tls = None;
|
||||
if let Some(tls) = &tls {
|
||||
tls_callbacks = execute_tls_callbacks(
|
||||
&tls.callbacks,
|
||||
layout.image_base,
|
||||
pe.image_base,
|
||||
layout.stack_top,
|
||||
&mut tls_cpu,
|
||||
memory,
|
||||
&mut engine,
|
||||
)?;
|
||||
// One callback at a time, so that a callback which ends the process
|
||||
// is seen as an exit and not as a fault, and the callbacks that
|
||||
// finished before it are counted.
|
||||
for callback in &tls.callbacks {
|
||||
match execute_tls_callbacks(
|
||||
std::slice::from_ref(callback),
|
||||
layout.image_base,
|
||||
pe.image_base,
|
||||
layout.stack_top,
|
||||
&mut tls_cpu,
|
||||
memory,
|
||||
&mut engine,
|
||||
) {
|
||||
Ok(_) => tls_callbacks += 1,
|
||||
Err(TlsError::CallbackExecutionFault(ExitReason::ProcessExit(status))) => {
|
||||
exited_in_tls = Some(status);
|
||||
break;
|
||||
}
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
observe(StartupEvent::TlsCompleted {
|
||||
callbacks: tls_callbacks,
|
||||
native_steps: engine.metrics.instructions_executed,
|
||||
});
|
||||
if let Some(status) = exited_in_tls {
|
||||
// The process ended before its entry point: the remaining callbacks
|
||||
// and the entry point do not run, and this is an ordinary outcome.
|
||||
return Ok(StartupResult {
|
||||
image,
|
||||
relocations,
|
||||
bound_imports,
|
||||
tls_callbacks,
|
||||
execution: ExecutionResult {
|
||||
instructions_executed: 0,
|
||||
final_state: tls_cpu,
|
||||
exit_reason: ExitReason::ProcessExit(status),
|
||||
},
|
||||
dbt_metrics: engine.metrics,
|
||||
});
|
||||
}
|
||||
observe(StartupEvent::Entering {
|
||||
step_limit: entry_budget,
|
||||
});
|
||||
|
||||
// Model function entry with the Win64 32-byte home area and return slot.
|
||||
// The synthetic entry point terminates with HLT.
|
||||
// An entry point may end with HLT, call ExitProcess, or return: the
|
||||
// return slot holds the address that ends the process with EAX.
|
||||
memory.write_u64_bypass(layout.stack_top - 40, crate::imports::ENTRY_RETURN)?;
|
||||
let mut entry_cpu = CpuState::new(image.entry_point, layout.stack_top - 40);
|
||||
entry_cpu.gs_base = teb_base;
|
||||
let execution = engine.run(&mut entry_cpu, memory, entry_budget);
|
||||
|
||||
+882
-33
@@ -11,11 +11,39 @@ use crate::memory::{GuestMemory, MemoryError, MemoryPermissions};
|
||||
use crate::pe::ParsedPe;
|
||||
use std::fmt;
|
||||
|
||||
/// Most callbacks one TLS directory may list.
|
||||
pub const MAX_TLS_CALLBACKS: usize = 64;
|
||||
|
||||
/// Bytes below the stack top that a callback is entered with: the return
|
||||
/// address and the 32-byte home space the Win64 convention gives every callee.
|
||||
const CALLBACK_FRAME: u64 = 40;
|
||||
|
||||
/// Errors arising during TLS setup or callback invocation.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum TlsError {
|
||||
DirectoryOutOfBounds { rva: u32 },
|
||||
InvalidTemplateRange { start: u64, end: u64 },
|
||||
DirectoryOutOfBounds {
|
||||
rva: u32,
|
||||
},
|
||||
InvalidTemplateRange {
|
||||
start: u64,
|
||||
end: u64,
|
||||
},
|
||||
/// `AddressOfCallbacks` is not zero and not inside a section of the image.
|
||||
CallbackArrayOutOfBounds {
|
||||
address: u64,
|
||||
},
|
||||
/// The callback array leaves its section before a null entry.
|
||||
CallbackArrayUnterminated {
|
||||
address: u64,
|
||||
},
|
||||
/// The callback array lists more than [`MAX_TLS_CALLBACKS`] entries.
|
||||
TooManyCallbacks {
|
||||
limit: usize,
|
||||
},
|
||||
/// The stack cannot hold a callback's entry frame or is not 16-byte aligned.
|
||||
InvalidCallbackStack {
|
||||
stack_top: u64,
|
||||
},
|
||||
CallbackExecutionFault(ExitReason),
|
||||
Memory(MemoryError),
|
||||
}
|
||||
@@ -32,6 +60,27 @@ impl fmt::Display for TlsError {
|
||||
"invalid TLS template range: 0x{start:016x}..0x{end:016x}"
|
||||
)
|
||||
}
|
||||
Self::CallbackArrayOutOfBounds { address } => {
|
||||
write!(
|
||||
f,
|
||||
"TLS callback array at 0x{address:016x} is outside the image"
|
||||
)
|
||||
}
|
||||
Self::CallbackArrayUnterminated { address } => {
|
||||
write!(
|
||||
f,
|
||||
"TLS callback array at 0x{address:016x} has no null entry in its section"
|
||||
)
|
||||
}
|
||||
Self::TooManyCallbacks { limit } => {
|
||||
write!(f, "TLS callback array lists more than {limit} callbacks")
|
||||
}
|
||||
Self::InvalidCallbackStack { stack_top } => {
|
||||
write!(
|
||||
f,
|
||||
"stack top 0x{stack_top:016x} cannot hold an aligned TLS callback frame"
|
||||
)
|
||||
}
|
||||
Self::CallbackExecutionFault(e) => {
|
||||
write!(f, "fault during TLS callback execution: {e}")
|
||||
}
|
||||
@@ -78,7 +127,7 @@ pub fn parse_tls_directory(bytes: &[u8], pe: &ParsedPe) -> Result<Option<TlsDire
|
||||
) as usize;
|
||||
|
||||
// TLS directory is directory index 9 (offset 112 + 9 * 8 = 184 in Optional Header)
|
||||
if size_of_opt < 192 || bytes.len() < opt_offset + 188 {
|
||||
if size_of_opt < 192 || bytes.len() < opt_offset + 192 {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
@@ -114,24 +163,7 @@ pub fn parse_tls_directory(bytes: &[u8], pe: &ParsedPe) -> Result<Option<TlsDire
|
||||
u32::from_le_bytes(bytes[tls_off + 32..tls_off + 36].try_into().unwrap());
|
||||
let characteristics = u32::from_le_bytes(bytes[tls_off + 36..tls_off + 40].try_into().unwrap());
|
||||
|
||||
let mut callbacks = Vec::new();
|
||||
if callbacks_address >= pe.image_base {
|
||||
let cb_rva = (callbacks_address - pe.image_base) as u32;
|
||||
if let Some(cb_off) = pe.rva_to_file_offset(cb_rva) {
|
||||
let mut curr = cb_off;
|
||||
while curr + 8 <= bytes.len() {
|
||||
let target = u64::from_le_bytes(bytes[curr..curr + 8].try_into().unwrap());
|
||||
if target == 0 {
|
||||
break;
|
||||
}
|
||||
callbacks.push(target);
|
||||
curr += 8;
|
||||
if callbacks.len() >= 64 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let callbacks = read_callbacks(bytes, pe, callbacks_address)?;
|
||||
|
||||
Ok(Some(TlsDirectory {
|
||||
raw_data_start_va,
|
||||
@@ -144,9 +176,96 @@ pub fn parse_tls_directory(bytes: &[u8], pe: &ParsedPe) -> Result<Option<TlsDire
|
||||
}))
|
||||
}
|
||||
|
||||
/// Read the null-terminated callback array that `address` names.
|
||||
///
|
||||
/// A null `address` means the image has no callbacks. Any other value must be a
|
||||
/// virtual address inside one section, and the array must reach its null entry
|
||||
/// inside that section. Bytes past the section's file data, up to its virtual
|
||||
/// size, are zero in the loaded image and are read as zero here.
|
||||
fn read_callbacks(bytes: &[u8], pe: &ParsedPe, address: u64) -> Result<Vec<u64>, TlsError> {
|
||||
if address == 0 {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let (section, start) = address
|
||||
.checked_sub(pe.image_base)
|
||||
.and_then(|rva| u32::try_from(rva).ok())
|
||||
.and_then(|rva| {
|
||||
pe.sections.iter().find_map(|section| {
|
||||
let offset = rva.checked_sub(section.virtual_address)?;
|
||||
let extent = section.virtual_size.max(section.raw_data_size);
|
||||
(offset < extent).then_some((section, u64::from(offset)))
|
||||
})
|
||||
})
|
||||
.ok_or(TlsError::CallbackArrayOutOfBounds { address })?;
|
||||
let extent = u64::from(section.virtual_size.max(section.raw_data_size));
|
||||
let byte_at = |offset: u64| -> Option<u8> {
|
||||
if offset >= extent {
|
||||
None
|
||||
} else if offset >= u64::from(section.raw_data_size) {
|
||||
Some(0)
|
||||
} else {
|
||||
let file = u64::from(section.raw_data_ptr) + offset;
|
||||
bytes.get(usize::try_from(file).ok()?).copied()
|
||||
}
|
||||
};
|
||||
|
||||
let mut callbacks = Vec::new();
|
||||
let mut offset = start;
|
||||
loop {
|
||||
let mut entry = [0u8; 8];
|
||||
for byte in &mut entry {
|
||||
*byte = byte_at(offset).ok_or(TlsError::CallbackArrayUnterminated { address })?;
|
||||
offset += 1;
|
||||
}
|
||||
let target = u64::from_le_bytes(entry);
|
||||
if target == 0 {
|
||||
return Ok(callbacks);
|
||||
}
|
||||
if callbacks.len() == MAX_TLS_CALLBACKS {
|
||||
return Err(TlsError::TooManyCallbacks {
|
||||
limit: MAX_TLS_CALLBACKS,
|
||||
});
|
||||
}
|
||||
callbacks.push(target);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 (e.g. 0) at `index_address`.
|
||||
/// 2. Allocate and initialize per-thread TLS storage from the template.
|
||||
/// 1. Assign TLS index 0 at `index_address`.
|
||||
/// 2. Map the thread's TLS pointer array at `thread_tls_base`.
|
||||
/// 3. Map the thread's data block one page above it, initialized from the
|
||||
/// template and zero fill, and store its address in the array slot of the
|
||||
/// index.
|
||||
///
|
||||
/// `thread_tls_base` is the value the thread environment block holds as its
|
||||
/// 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,
|
||||
@@ -181,31 +300,97 @@ 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 per-thread TLS block
|
||||
// Allocate the pointer array and the per-thread TLS block.
|
||||
let block_base = thread_tls_base
|
||||
.checked_add(TLS_ARRAY_SIZE as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
let page_size = 4096;
|
||||
let map_size = (total_size + page_size - 1) & !(page_size - 1);
|
||||
memory.map_region_with_data(
|
||||
memory.map_region(
|
||||
thread_tls_base,
|
||||
map_size,
|
||||
TLS_ARRAY_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)?;
|
||||
}
|
||||
|
||||
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)
|
||||
/// - RDX = Reason (DLL_PROCESS_ATTACH = 1)
|
||||
/// - R8 = Reserved (0)
|
||||
///
|
||||
/// Each callback is entered as after a CALL from a 16-byte aligned stack: RSP
|
||||
/// is `stack_top - 40`, holding the return address below 32 bytes of home
|
||||
/// space. A `stack_top` that is not 16-byte aligned or cannot hold that frame
|
||||
/// is rejected before any callback runs.
|
||||
pub fn execute_tls_callbacks(
|
||||
callbacks: &[u64],
|
||||
loaded_base: u64,
|
||||
@@ -215,6 +400,12 @@ pub fn execute_tls_callbacks(
|
||||
memory: &mut GuestMemory,
|
||||
dbt: &mut DbtEngine,
|
||||
) -> Result<usize, TlsError> {
|
||||
if callbacks.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
if stack_top < CALLBACK_FRAME || !stack_top.is_multiple_of(16) {
|
||||
return Err(TlsError::InvalidCallbackStack { stack_top });
|
||||
}
|
||||
let delta = (loaded_base as i128) - (preferred_base as i128);
|
||||
let mut executed_count = 0;
|
||||
|
||||
@@ -224,7 +415,7 @@ pub fn execute_tls_callbacks(
|
||||
// Reset CPU state for callback execution adhering to Win64 ABI
|
||||
cpu.rip = actual_cb_va;
|
||||
// Stack pointer aligned with 32-byte shadow space + return address
|
||||
let rsp = stack_top - 40;
|
||||
let rsp = stack_top - CALLBACK_FRAME;
|
||||
cpu.set(Register::Rsp, rsp);
|
||||
// Write synthetic magic return address (0xFFFF_FFFF_FFFF_0000) into [RSP]
|
||||
let magic_ret = 0xFFFF_FFFF_FFFF_0000u64;
|
||||
@@ -261,3 +452,661 @@ pub fn execute_tls_callbacks(
|
||||
|
||||
Ok(executed_count)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
//! Expectations come from Microsoft's public PE Format page (the TLS
|
||||
//! directory: `AddressOfCallbacks` is a virtual address of a null-terminated
|
||||
//! array, and a callback is `void cb(PVOID DllHandle, DWORD Reason, PVOID
|
||||
//! Reserved)`) and its x64 calling convention page (the stack is 16-byte
|
||||
//! aligned before a call, the caller provides 32 bytes of home space, and
|
||||
//! the first three integer arguments are in RCX, RDX and R8). The headers
|
||||
//! and code bytes below are original. Nothing here ran on Windows.
|
||||
|
||||
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;
|
||||
const SECTION_FILE: usize = 0x400;
|
||||
const SECTION_SIZE: u32 = 0x400;
|
||||
/// Offset of the optional header: `e_lfanew` (0x80), signature, COFF header.
|
||||
const OPTIONAL_HEADER: usize = 0x80 + 24;
|
||||
|
||||
fn parsed(virtual_size: u32) -> ParsedPe {
|
||||
ParsedPe {
|
||||
machine: 0x8664,
|
||||
number_of_sections: 1,
|
||||
time_date_stamp: 0,
|
||||
image_base: IMAGE_BASE,
|
||||
section_alignment: 0x1000,
|
||||
file_alignment: 0x200,
|
||||
size_of_image: 0x3000,
|
||||
size_of_headers: 0x400,
|
||||
entry_point_rva: 0,
|
||||
sections: vec![PeSection {
|
||||
name: ".rdata".into(),
|
||||
virtual_address: SECTION_RVA,
|
||||
virtual_size,
|
||||
raw_data_ptr: SECTION_FILE as u32,
|
||||
raw_data_size: SECTION_SIZE,
|
||||
characteristics: crate::pe::IMAGE_SCN_MEM_READ,
|
||||
permissions: MemoryPermissions::READ_ONLY,
|
||||
}],
|
||||
}
|
||||
}
|
||||
|
||||
/// A file with one section holding a TLS directory at its start and the
|
||||
/// callback `entries` at `array_rva`. The directory names `callbacks_address`.
|
||||
/// Every byte after the section's file data is 0xCC.
|
||||
fn file(callbacks_address: u64, array_rva: u32, entries: &[u64]) -> Vec<u8> {
|
||||
let section_end = SECTION_FILE + SECTION_SIZE as usize;
|
||||
let mut bytes = vec![0u8; section_end];
|
||||
bytes.resize(section_end + 0x200, 0xCC);
|
||||
bytes[0x3C..0x40].copy_from_slice(&0x80u32.to_le_bytes());
|
||||
// SizeOfOptionalHeader: a PE32+ optional header with 16 data directories.
|
||||
bytes[0x94..0x96].copy_from_slice(&240u16.to_le_bytes());
|
||||
// Data directory 9 (TLS): RVA and size.
|
||||
let entry = OPTIONAL_HEADER + 112 + 9 * 8;
|
||||
bytes[entry..entry + 4].copy_from_slice(&SECTION_RVA.to_le_bytes());
|
||||
bytes[entry + 4..entry + 8].copy_from_slice(&40u32.to_le_bytes());
|
||||
// IMAGE_TLS_DIRECTORY64.AddressOfCallBacks is its fourth 8-byte field.
|
||||
bytes[SECTION_FILE + 24..SECTION_FILE + 32]
|
||||
.copy_from_slice(&callbacks_address.to_le_bytes());
|
||||
let mut at = SECTION_FILE + (array_rva - SECTION_RVA) as usize;
|
||||
for entry in entries {
|
||||
bytes[at..at + 8].copy_from_slice(&entry.to_le_bytes());
|
||||
at += 8;
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
fn callbacks_of(bytes: &[u8], pe: &ParsedPe) -> Result<Vec<u64>, TlsError> {
|
||||
parse_tls_directory(bytes, pe).map(|tls| tls.expect("a TLS directory").callbacks)
|
||||
}
|
||||
|
||||
const ARRAY_RVA: u32 = 0x1100;
|
||||
const ARRAY: u64 = IMAGE_BASE + ARRAY_RVA as u64;
|
||||
const FIRST: u64 = IMAGE_BASE + 0x2000;
|
||||
const SECOND: u64 = IMAGE_BASE + 0x2010;
|
||||
|
||||
#[test]
|
||||
fn callbacks_are_read_in_order_up_to_the_null_entry() {
|
||||
let bytes = file(ARRAY, ARRAY_RVA, &[FIRST, SECOND, 0, IMAGE_BASE + 0x2020]);
|
||||
assert_eq!(
|
||||
callbacks_of(&bytes, &parsed(SECTION_SIZE)),
|
||||
Ok(vec![FIRST, SECOND])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_null_callbacks_address_means_no_callbacks() {
|
||||
let bytes = file(0, ARRAY_RVA, &[FIRST, 0]);
|
||||
assert_eq!(callbacks_of(&bytes, &parsed(SECTION_SIZE)), Ok(vec![]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_callback_array_outside_the_image_is_rejected() {
|
||||
for address in [8, IMAGE_BASE - 8, IMAGE_BASE + 0x800, IMAGE_BASE + 0x5000] {
|
||||
let bytes = file(address, ARRAY_RVA, &[FIRST, 0]);
|
||||
assert_eq!(
|
||||
callbacks_of(&bytes, &parsed(SECTION_SIZE)),
|
||||
Err(TlsError::CallbackArrayOutOfBounds { address }),
|
||||
"{address:#x}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_callback_array_address_is_not_truncated_to_32_bits() {
|
||||
// The low 32 bits of the offset name the real array.
|
||||
let address = ARRAY + (1 << 32);
|
||||
let bytes = file(address, ARRAY_RVA, &[FIRST, 0]);
|
||||
assert_eq!(
|
||||
callbacks_of(&bytes, &parsed(SECTION_SIZE)),
|
||||
Err(TlsError::CallbackArrayOutOfBounds { address })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_callback_array_must_end_inside_its_section() {
|
||||
// Two entries fill the last 16 bytes of the section; the file goes on.
|
||||
let rva = SECTION_RVA + SECTION_SIZE - 16;
|
||||
let address = IMAGE_BASE + u64::from(rva);
|
||||
let bytes = file(address, rva, &[FIRST, SECOND]);
|
||||
assert_eq!(
|
||||
callbacks_of(&bytes, &parsed(SECTION_SIZE)),
|
||||
Err(TlsError::CallbackArrayUnterminated { address })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_fill_after_the_section_file_data_ends_the_array() {
|
||||
// The section is larger in memory than in the file, so the bytes after
|
||||
// its file data are zero when loaded, whatever follows in the file.
|
||||
let rva = SECTION_RVA + SECTION_SIZE - 16;
|
||||
let address = IMAGE_BASE + u64::from(rva);
|
||||
let bytes = file(address, rva, &[FIRST, SECOND]);
|
||||
assert_eq!(
|
||||
callbacks_of(&bytes, &parsed(SECTION_SIZE + 0x100)),
|
||||
Ok(vec![FIRST, SECOND])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_callback_array_over_the_limit_is_rejected() {
|
||||
let entries: Vec<u64> = (0..65).map(|index| FIRST + index * 16).collect();
|
||||
let mut at_limit = entries[..MAX_TLS_CALLBACKS].to_vec();
|
||||
at_limit.push(0);
|
||||
let bytes = file(ARRAY, ARRAY_RVA, &at_limit);
|
||||
assert_eq!(
|
||||
callbacks_of(&bytes, &parsed(SECTION_SIZE)),
|
||||
Ok(entries[..64].to_vec())
|
||||
);
|
||||
|
||||
let mut over = entries.clone();
|
||||
over.push(0);
|
||||
let bytes = file(ARRAY, ARRAY_RVA, &over);
|
||||
assert_eq!(
|
||||
callbacks_of(&bytes, &parsed(SECTION_SIZE)),
|
||||
Err(TlsError::TooManyCallbacks { limit: 64 })
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_cut_inside_the_tls_data_directory_has_no_tls_directory() {
|
||||
let bytes = file(ARRAY, ARRAY_RVA, &[FIRST, 0]);
|
||||
let entry = OPTIONAL_HEADER + 112 + 9 * 8;
|
||||
for length in entry..entry + 8 {
|
||||
let directory = parse_tls_directory(&bytes[..length], &parsed(SECTION_SIZE));
|
||||
assert!(matches!(directory, Ok(None)), "length {length:#x}");
|
||||
}
|
||||
}
|
||||
|
||||
const CODE: u64 = 0x40_0000;
|
||||
const STACK_TOP: u64 = 0x80_0000;
|
||||
const SENTINEL: u64 = 0xFFFF_FFFF_FFFF_0000;
|
||||
|
||||
/// Code at `CODE`, a 4 KiB stack below `STACK_TOP` and a fresh translator.
|
||||
fn guest(code: &[u8]) -> (CpuState, GuestMemory, DbtEngine) {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(CODE, 0x1000, MemoryPermissions::READ_EXECUTE, code)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region(STACK_TOP - 0x1000, 0x1000, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
(
|
||||
CpuState::new(0, 0),
|
||||
memory,
|
||||
DbtEngine::new(64 * 1024).unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Two callbacks 16 bytes apart. Each shifts RAX left by four bits and sets
|
||||
/// its own number in the low bits, so RAX records the order they ran in.
|
||||
const TAGGING: [u8; 25] = [
|
||||
0x48, 0xC1, 0xE0, 0x04, // shl rax, 4
|
||||
0x48, 0x83, 0xC8, 0x01, // or rax, 1
|
||||
0xC3, // ret
|
||||
0, 0, 0, 0, 0, 0, 0, // padding
|
||||
0x48, 0xC1, 0xE0, 0x04, // shl rax, 4
|
||||
0x48, 0x83, 0xC8, 0x02, // or rax, 2
|
||||
0xC3, // ret
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn a_callback_is_entered_with_the_win64_arguments_and_frame() {
|
||||
let code = [0x48, 0x89, 0xE0, 0xC3]; // mov rax, rsp; ret
|
||||
let (mut cpu, mut memory, mut dbt) = guest(&code);
|
||||
// Loaded 64 KiB above the preferred base: the listed address is rebased.
|
||||
let loaded = IMAGE_BASE + 0x1_0000;
|
||||
let listed = [CODE - 0x1_0000];
|
||||
let ran = execute_tls_callbacks(
|
||||
&listed,
|
||||
loaded,
|
||||
IMAGE_BASE,
|
||||
STACK_TOP,
|
||||
&mut cpu,
|
||||
&mut memory,
|
||||
&mut dbt,
|
||||
);
|
||||
assert_eq!(ran, Ok(1));
|
||||
let entry_rsp = cpu.get(Register::Rax);
|
||||
assert_eq!(entry_rsp, STACK_TOP - 40);
|
||||
// A callee is entered 8 bytes off 16-byte alignment, as after a CALL.
|
||||
assert_eq!(entry_rsp % 16, 8);
|
||||
assert_eq!(memory.read_u64(entry_rsp), Ok(SENTINEL));
|
||||
assert_eq!(cpu.get(Register::Rcx), loaded);
|
||||
assert_eq!(cpu.get(Register::Rdx), 1); // DLL_PROCESS_ATTACH
|
||||
assert_eq!(cpu.get(Register::R8), 0);
|
||||
// RET popped the return address and nothing else.
|
||||
assert_eq!(cpu.get(Register::Rsp), entry_rsp + 8);
|
||||
assert_eq!(cpu.rip, SENTINEL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn callbacks_run_in_array_order() {
|
||||
for (order, recorded) in [([CODE, CODE + 16], 0x12), ([CODE + 16, CODE], 0x21)] {
|
||||
let (mut cpu, mut memory, mut dbt) = guest(&TAGGING);
|
||||
let ran = execute_tls_callbacks(
|
||||
&order,
|
||||
IMAGE_BASE,
|
||||
IMAGE_BASE,
|
||||
STACK_TOP,
|
||||
&mut cpu,
|
||||
&mut memory,
|
||||
&mut dbt,
|
||||
);
|
||||
assert_eq!(ran, Ok(2));
|
||||
assert_eq!(cpu.get(Register::Rax), recorded);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_callback_over_the_instruction_budget_stops_the_sequence() {
|
||||
let mut code = TAGGING.to_vec();
|
||||
code.resize(32, 0);
|
||||
code.extend([0xEB, 0xFE]); // jmp to itself
|
||||
let (mut cpu, mut memory, mut dbt) = guest(&code);
|
||||
let ran = execute_tls_callbacks(
|
||||
&[CODE, CODE + 32, CODE + 16],
|
||||
IMAGE_BASE,
|
||||
IMAGE_BASE,
|
||||
STACK_TOP,
|
||||
&mut cpu,
|
||||
&mut memory,
|
||||
&mut dbt,
|
||||
);
|
||||
assert_eq!(
|
||||
ran,
|
||||
Err(TlsError::CallbackExecutionFault(
|
||||
ExitReason::StepLimitExceeded
|
||||
))
|
||||
);
|
||||
// The first callback ran; the one after the endless one did not.
|
||||
assert_eq!(cpu.get(Register::Rax), 0x1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unusable_callback_stack_is_rejected_before_anything_runs() {
|
||||
for stack_top in [0, 32, STACK_TOP - 8, STACK_TOP - 1] {
|
||||
let (mut cpu, mut memory, mut dbt) = guest(&TAGGING);
|
||||
let ran = execute_tls_callbacks(
|
||||
&[CODE],
|
||||
IMAGE_BASE,
|
||||
IMAGE_BASE,
|
||||
stack_top,
|
||||
&mut cpu,
|
||||
&mut memory,
|
||||
&mut dbt,
|
||||
);
|
||||
assert_eq!(
|
||||
ran,
|
||||
Err(TlsError::InvalidCallbackStack { stack_top }),
|
||||
"{stack_top:#x}"
|
||||
);
|
||||
assert_eq!(cpu, CpuState::new(0, 0));
|
||||
assert_eq!(memory.read_u64(STACK_TOP - 48), Ok(0));
|
||||
// No callback, no frame: the stack is not looked at.
|
||||
let none = execute_tls_callbacks(&[], 0, 0, stack_top, &mut cpu, &mut memory, &mut dbt);
|
||||
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]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,8 @@ pub struct Form {
|
||||
pub no_rex_b: bool,
|
||||
/// A 16-byte memory operand may have any alignment.
|
||||
pub unaligned: bool,
|
||||
/// The LOCK prefix is accepted when the ModRM operand is memory.
|
||||
pub lockable: bool,
|
||||
}
|
||||
|
||||
/// Opcode table entry.
|
||||
@@ -64,6 +66,8 @@ pub enum Entry {
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Encoding {
|
||||
None,
|
||||
/// A string instruction: source `[RSI]`, destination `[RDI]`, REP allowed.
|
||||
String,
|
||||
RmReg,
|
||||
RegRm,
|
||||
RegRmImm,
|
||||
@@ -72,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,
|
||||
@@ -167,6 +175,11 @@ pub struct Insn {
|
||||
pub imm: u64,
|
||||
/// Condition code for Jcc, CMOVcc and SETcc.
|
||||
pub condition: u8,
|
||||
/// Carries a LOCK prefix. Set only for a lockable form with a memory
|
||||
/// destination.
|
||||
pub lock: bool,
|
||||
/// A string instruction carrying a REP prefix.
|
||||
pub rep: bool,
|
||||
}
|
||||
|
||||
impl Insn {
|
||||
@@ -228,11 +241,21 @@ impl<E, F: FnMut(u64) -> Result<u8, E>> Cursor<F> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `byte` is a legacy prefix: an operand-size, address-size, segment,
|
||||
/// LOCK or repeat prefix (Intel SDM Vol. 2A, 2.1.1).
|
||||
fn is_legacy_prefix(byte: u8) -> bool {
|
||||
matches!(
|
||||
byte,
|
||||
0x26 | 0x2E | 0x36 | 0x3E | 0x64 | 0x65 | 0x66 | 0x67 | 0xF0 | 0xF2 | 0xF3
|
||||
)
|
||||
}
|
||||
|
||||
/// Decode one instruction at `rip`. `fetch` supplies the byte at an address and
|
||||
/// is called only for bytes that belong to the instruction, in order.
|
||||
///
|
||||
/// Forms the registry does not declare, LOCK, address-size overrides and an
|
||||
/// ignored segment override after FS or GS are rejected rather than approximated.
|
||||
/// Forms the registry does not declare, LOCK anywhere but on a lockable form
|
||||
/// with a memory destination, address-size overrides and an ignored segment
|
||||
/// override after FS or GS are rejected rather than approximated.
|
||||
pub fn decode<E>(
|
||||
rip: u64,
|
||||
fetch: impl FnMut(u64) -> Result<u8, E>,
|
||||
@@ -246,10 +269,24 @@ pub fn decode<E>(
|
||||
let mut operand_size = false;
|
||||
let mut rep = false;
|
||||
let mut repne = false;
|
||||
let mut lock = false;
|
||||
let mut segment = None;
|
||||
let mut rex = 0;
|
||||
let mut byte = cursor.u8()?;
|
||||
loop {
|
||||
let selected = match byte {
|
||||
// REX applies only immediately before the opcode. One that is
|
||||
// followed by a legacy prefix is ignored (Intel SDM Vol. 2A, 2.2.1).
|
||||
0x40..=0x4F => {
|
||||
let next = cursor.u8()?;
|
||||
if !is_legacy_prefix(next) {
|
||||
rex = byte;
|
||||
byte = next;
|
||||
break;
|
||||
}
|
||||
byte = next;
|
||||
continue;
|
||||
}
|
||||
0x64 => Segment::Fs,
|
||||
0x65 => Segment::Gs,
|
||||
0x66 => {
|
||||
@@ -267,6 +304,11 @@ pub fn decode<E>(
|
||||
byte = cursor.u8()?;
|
||||
continue;
|
||||
}
|
||||
0xF0 => {
|
||||
lock = true;
|
||||
byte = cursor.u8()?;
|
||||
continue;
|
||||
}
|
||||
// CS, DS, ES and SS overrides have no effect in 64-bit mode. After
|
||||
// FS or GS their meaning is not relied on, so it is rejected.
|
||||
0x26 | 0x2E | 0x36 | 0x3E if segment.is_none() => {
|
||||
@@ -283,10 +325,6 @@ pub fn decode<E>(
|
||||
byte = cursor.u8()?;
|
||||
}
|
||||
|
||||
let rex = if byte & 0xF0 == 0x40 { byte } else { 0 };
|
||||
if rex != 0 {
|
||||
byte = cursor.u8()?;
|
||||
}
|
||||
let (rex_w, rex_r, rex_x, rex_b) =
|
||||
(rex & 8 != 0, (rex & 4) << 1, (rex & 2) << 2, (rex & 1) << 3);
|
||||
|
||||
@@ -298,8 +336,12 @@ pub fn decode<E>(
|
||||
let opcode = if two_byte { cursor.u8()? } else { byte };
|
||||
let slot = usize::from(opcode);
|
||||
let table = if !two_byte {
|
||||
// Only PAUSE (F3 90) has a meaning here for F3 on a one-byte opcode.
|
||||
if repne || (rep && opcode != 0x90) {
|
||||
// On a one-byte opcode F3 is PAUSE (F3 90) or REP on a string form.
|
||||
let string = matches!(
|
||||
ONE_BYTE[slot],
|
||||
Entry::Form(index) if FORMS[usize::from(index)].encoding == Encoding::String
|
||||
);
|
||||
if repne || (rep && opcode != 0x90 && !string) {
|
||||
return Err(DecodeError::Unsupported(if rep { 0xF3 } else { 0xF2 }));
|
||||
}
|
||||
&ONE_BYTE
|
||||
@@ -325,9 +367,24 @@ pub fn decode<E>(
|
||||
GROUPS[usize::from(index)][usize::from((modrm >> 3) & 7)]
|
||||
}
|
||||
};
|
||||
let form = FORMS
|
||||
let mut form = FORMS
|
||||
.get(usize::from(form_index))
|
||||
.ok_or(DecodeError::Unsupported(opcode))?;
|
||||
let mut form_index = form_index;
|
||||
if form.no_rex_b && rex_b != 0 {
|
||||
// 90 is NOP only without REX.B. With it the byte exchanges r8 with the
|
||||
// accumulator, as the first register of the 91..97 row would (Intel
|
||||
// SDM Vol. 2B, "NOP" and "XCHG").
|
||||
match ONE_BYTE[slot + 1] {
|
||||
Entry::Form(index)
|
||||
if !two_byte && !rep && FORMS[usize::from(index)].encoding == Encoding::OpReg =>
|
||||
{
|
||||
form_index = index;
|
||||
form = &FORMS[usize::from(index)];
|
||||
}
|
||||
_ => return Err(DecodeError::Unsupported(opcode)),
|
||||
}
|
||||
}
|
||||
if form.has_modrm && matches!(entry, Entry::Form(_)) {
|
||||
modrm = cursor.u8()?;
|
||||
}
|
||||
@@ -348,10 +405,6 @@ pub fn decode<E>(
|
||||
if operand_size && !takes_operand_size && !overridden {
|
||||
return Err(DecodeError::Unsupported(0x66));
|
||||
}
|
||||
if form.no_rex_b && rex_b != 0 {
|
||||
return Err(DecodeError::Unsupported(opcode));
|
||||
}
|
||||
|
||||
let rm_size = if form.source != 0 { form.source } else { size };
|
||||
let register = |field: u8, extension: u8, width: u8| {
|
||||
if width == 1 && rex == 0 && field >= 4 {
|
||||
@@ -412,6 +465,20 @@ pub fn decode<E>(
|
||||
}
|
||||
} else if matches!(form.encoding, Encoding::OpReg | Encoding::OpRegImm) {
|
||||
reg = register(opcode & 7, rex_b, size);
|
||||
} else if form.encoding == Encoding::String {
|
||||
// The source is DS:[RSI], which FS or GS may override. The destination
|
||||
// ES:[RDI] takes no override.
|
||||
rm = Some(RmOperand::Mem(MemOperand {
|
||||
base: Some(6),
|
||||
index: None,
|
||||
disp: 0,
|
||||
segment,
|
||||
}));
|
||||
}
|
||||
// LOCK is an invalid opcode unless the instruction is lockable and its
|
||||
// destination is memory (Intel SDM Vol. 2, "LOCK").
|
||||
if lock && !(form.lockable && matches!(rm, Some(RmOperand::Mem(_)))) {
|
||||
return Err(DecodeError::Unsupported(0xF0));
|
||||
}
|
||||
|
||||
let mut imm = match form.immediate {
|
||||
@@ -449,6 +516,8 @@ pub fn decode<E>(
|
||||
reg,
|
||||
imm,
|
||||
condition: opcode & 0xF,
|
||||
lock,
|
||||
rep: rep && form.encoding == Encoding::String,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
//! the state unchanged. Flags that the architecture leaves undefined keep their
|
||||
//! previous value, which is permitted but not something guests may rely on.
|
||||
|
||||
use crate::cpu::{CpuState, ExitReason, RFlags, Register};
|
||||
use crate::cpu::{CpuState, ExitReason, RFlags, Register, cpuid};
|
||||
use crate::memory::GuestMemory;
|
||||
use crate::x86_decode::{Encoding, Insn, MemOperand, RegOperand, RmOperand, Segment};
|
||||
use crate::x86_simd;
|
||||
@@ -19,8 +19,11 @@ use crate::x86_table::Op;
|
||||
const RAX: usize = Register::Rax as usize;
|
||||
const RCX: usize = Register::Rcx as usize;
|
||||
const RDX: usize = Register::Rdx as usize;
|
||||
const RBX: usize = Register::Rbx as usize;
|
||||
const RSP: usize = Register::Rsp as usize;
|
||||
const RBP: usize = Register::Rbp as usize;
|
||||
const RSI: usize = Register::Rsi as usize;
|
||||
const RDI: usize = Register::Rdi as usize;
|
||||
|
||||
/// Value mask of an operand of `size` bytes.
|
||||
fn mask(size: u8) -> u64 {
|
||||
@@ -46,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)]);
|
||||
@@ -75,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),
|
||||
@@ -90,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),
|
||||
@@ -238,6 +267,25 @@ fn shift(op: Op, value: u64, count: u64, size: u8, old: RFlags) -> Option<(u64,
|
||||
flags.cf = signed >> (count - 1) & 1 != 0;
|
||||
(signed >> count) as u64
|
||||
}
|
||||
Op::Rcl | Op::Rcr => {
|
||||
// The carry flag is one more bit above the operand, so the rotation
|
||||
// is over `bits + 1` positions and the count is reduced modulo that.
|
||||
let width = bits + 1;
|
||||
let ring = wide | u128::from(old.cf) << bits;
|
||||
let by = count % width;
|
||||
let left = if op == Op::Rcl {
|
||||
by
|
||||
} else {
|
||||
(width - by) % width
|
||||
};
|
||||
let rotated = if left == 0 {
|
||||
ring
|
||||
} else {
|
||||
ring << left | ring >> (width - left)
|
||||
};
|
||||
flags.cf = rotated >> bits & 1 != 0;
|
||||
rotated as u64
|
||||
}
|
||||
_ => {
|
||||
let by = count % bits;
|
||||
let left = if op == Op::Rol {
|
||||
@@ -265,7 +313,7 @@ fn shift(op: Op, value: u64, count: u64, size: u8, old: RFlags) -> Option<(u64,
|
||||
// OF is defined only for a count of one.
|
||||
if count == 1 {
|
||||
flags.of = match op {
|
||||
Op::Shl | Op::Rol => (result & top != 0) != flags.cf,
|
||||
Op::Shl | Op::Rol | Op::Rcl => (result & top != 0) != flags.cf,
|
||||
Op::Shr => value & top != 0,
|
||||
Op::Sar => false,
|
||||
_ => (result & top != 0) != (result & (top >> 1) != 0),
|
||||
@@ -274,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)
|
||||
@@ -351,6 +447,8 @@ pub fn execute(
|
||||
Encoding::OpRegImm => write_reg(cpu, insn.reg, size, insn.imm),
|
||||
_ => write_rm(cpu, memory, insn, insn.imm & mask(size))?,
|
||||
},
|
||||
// A non-temporal store is an ordinary store: there is no cache to bypass.
|
||||
Op::Movnti => write_rm(cpu, memory, insn, read_reg(cpu, insn.reg, size))?,
|
||||
Op::Movzx => {
|
||||
let value = read_rm(cpu, memory, insn)?;
|
||||
write_reg(cpu, insn.reg, size, value);
|
||||
@@ -364,11 +462,48 @@ pub fn execute(
|
||||
write_reg(cpu, insn.reg, size, offset(cpu, &operand));
|
||||
}
|
||||
}
|
||||
Op::Xchg if insn.encoding == Encoding::OpReg => {
|
||||
// The accumulator with the register in the opcode, never itself:
|
||||
// 90 without REX.B is NOP.
|
||||
let rax = accumulator(RAX);
|
||||
let (a, b) = (read_reg(cpu, rax, size), read_reg(cpu, insn.reg, size));
|
||||
write_reg(cpu, rax, size, b);
|
||||
write_reg(cpu, insn.reg, size, a);
|
||||
}
|
||||
Op::Xchg => {
|
||||
let (a, b) = operands(cpu, memory, insn)?;
|
||||
write_rm(cpu, memory, insn, b)?;
|
||||
write_reg(cpu, insn.reg, size, a);
|
||||
}
|
||||
Op::Xadd => {
|
||||
let (a, b) = operands(cpu, memory, insn)?;
|
||||
let (value, flags) = add(a, b, false, size);
|
||||
write_rm(cpu, memory, insn, value)?;
|
||||
// The source is loaded before the destination is stored, so a
|
||||
// register added to itself keeps the sum.
|
||||
if insn.rm != Some(RmOperand::Reg(insn.reg)) {
|
||||
write_reg(cpu, insn.reg, size, a);
|
||||
}
|
||||
cpu.flags = flags;
|
||||
}
|
||||
Op::Cmpxchg => {
|
||||
let (destination, source) = operands(cpu, memory, insn)?;
|
||||
let expected = cpu.gpr[RAX] & mask(size);
|
||||
let (_, flags) = sub(expected, destination, false, size);
|
||||
// The destination is written whether or not the values match, so a
|
||||
// mismatch on memory that cannot be written still faults.
|
||||
let matched = expected == destination;
|
||||
write_rm(
|
||||
cpu,
|
||||
memory,
|
||||
insn,
|
||||
if matched { source } else { destination },
|
||||
)?;
|
||||
if !matched {
|
||||
write_reg(cpu, accumulator(RAX), size, destination);
|
||||
}
|
||||
cpu.flags = flags;
|
||||
}
|
||||
Op::Bswap => {
|
||||
let value = read_reg(cpu, insn.reg, size).swap_bytes() >> (64 - 8 * u32::from(size));
|
||||
write_reg(cpu, insn.reg, size, value);
|
||||
@@ -387,7 +522,24 @@ pub fn execute(
|
||||
if negative { mask(size) } else { 0 },
|
||||
);
|
||||
}
|
||||
Op::Rol | Op::Ror | Op::Shl | Op::Shr | Op::Sar => {
|
||||
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) {
|
||||
Some((value, flags)) => {
|
||||
@@ -544,6 +696,49 @@ pub fn execute(
|
||||
cpu.gpr[RSP] = sp.wrapping_add(8).wrapping_add(insn.imm);
|
||||
}
|
||||
Op::Nop => {}
|
||||
// Every load and store of an instruction completes before the next
|
||||
// instruction starts, on one host thread, so guest accesses are already
|
||||
// totally ordered and a fence has nothing further to enforce.
|
||||
Op::Lfence | Op::Mfence | Op::Sfence => {}
|
||||
Op::Cpuid => {
|
||||
// The leaf is EAX and the subleaf ECX. Each result is a 32-bit
|
||||
// register write, so the upper halves are cleared.
|
||||
let values = cpuid(cpu.gpr[RAX] as u32, cpu.gpr[RCX] as u32);
|
||||
for (register, value) in [RAX, RBX, RCX, RDX].into_iter().zip(values) {
|
||||
cpu.gpr[register] = u64::from(value);
|
||||
}
|
||||
}
|
||||
Op::Movs | Op::Stos => {
|
||||
// One element per execution. A REP form with elements left keeps
|
||||
// RIP on itself, so every element is a step of its own: it counts
|
||||
// against the step budget, and a fault keeps the elements already
|
||||
// done, with RSI, RDI and RCX at the element that faulted.
|
||||
if !(insn.rep && cpu.gpr[RCX] == 0) {
|
||||
let value = if insn.op == Op::Movs {
|
||||
read_rm(cpu, memory, insn)?
|
||||
} else {
|
||||
cpu.gpr[RAX] & mask(size)
|
||||
};
|
||||
write_mem(memory, cpu.gpr[RDI], size, value)?;
|
||||
let step = if cpu.df {
|
||||
u64::from(size).wrapping_neg()
|
||||
} else {
|
||||
u64::from(size)
|
||||
};
|
||||
if insn.op == Op::Movs {
|
||||
cpu.gpr[RSI] = cpu.gpr[RSI].wrapping_add(step);
|
||||
}
|
||||
cpu.gpr[RDI] = cpu.gpr[RDI].wrapping_add(step);
|
||||
if insn.rep {
|
||||
cpu.gpr[RCX] -= 1;
|
||||
if cpu.gpr[RCX] != 0 {
|
||||
next = insn.rip;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Op::Cld => cpu.df = false,
|
||||
Op::Std => cpu.df = true,
|
||||
Op::Clc => cpu.flags.cf = false,
|
||||
Op::Stc => cpu.flags.cf = true,
|
||||
Op::Cmc => cpu.flags.cf = !cpu.flags.cf,
|
||||
|
||||
@@ -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)
|
||||
|
||||
+659
-486
File diff suppressed because it is too large.
Load diff
@@ -164,3 +164,45 @@ fn vector_operations_match_llvm() {
|
||||
assert_eq!(assembler.instructions(), [*word], "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn carry_arithmetic_matches_llvm() {
|
||||
// `llvm-mc -triple=aarch64-apple-macos -show-encoding`.
|
||||
let cases: &[(&str, Emit, u32)] = &[
|
||||
(
|
||||
"adcs x11, x9, x10",
|
||||
|a| a.adcs_reg_64(11, 9, 10),
|
||||
0xba0a012b,
|
||||
),
|
||||
(
|
||||
"adcs w11, w9, w10",
|
||||
|a| a.adcs_reg_32(11, 9, 10),
|
||||
0x3a0a012b,
|
||||
),
|
||||
(
|
||||
"adcs x0, x30, x17",
|
||||
|a| a.adcs_reg_64(0, 30, 17),
|
||||
0xba1103c0,
|
||||
),
|
||||
(
|
||||
"sbcs x11, x9, x10",
|
||||
|a| a.sbcs_reg_64(11, 9, 10),
|
||||
0xfa0a012b,
|
||||
),
|
||||
(
|
||||
"sbcs w11, w9, w10",
|
||||
|a| a.sbcs_reg_32(11, 9, 10),
|
||||
0x7a0a012b,
|
||||
),
|
||||
(
|
||||
"sbcs w0, w30, w17",
|
||||
|a| a.sbcs_reg_32(0, 30, 17),
|
||||
0x7a1103c0,
|
||||
),
|
||||
];
|
||||
for (text, emit, word) in cases {
|
||||
let mut assembler = Arm64Assembler::new();
|
||||
emit(&mut assembler);
|
||||
assert_eq!(assembler.instructions(), [*word], "{text}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,644 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Seeded sequences of original x86-64 instructions for issue #74.
|
||||
//!
|
||||
//! Expected states follow the Intel SDM (Vol. 1, §§3.4.1 and 3.4.3,
|
||||
//! Vol. 2, ADD, SUB, CMP, XOR, MOV, Jcc, CALL, RET, DEC, MOVDQU, PADDB,
|
||||
//! PSUBW and PXOR, and Vol. 3A, §7.15, Page-Fault Exception). The oracles work from arithmetic operands, branch
|
||||
//! predicates, array indices and vector lanes. They never decode the emitted
|
||||
//! bytes or use Xenora's instruction or flag helpers.
|
||||
//!
|
||||
//! <https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html>
|
||||
//!
|
||||
//! The x86 bytes run as guest code through a synthetic memory map and end at
|
||||
//! Xenora's HLT sentinel. To replay a failure, use the printed test name and
|
||||
//! XENORA_CPU_DIFFERENTIAL_CASE index. For example:
|
||||
//!
|
||||
//! ```sh
|
||||
//! XENORA_CPU_DIFFERENTIAL_CASE=0 cargo test --locked -p xenora-loader \
|
||||
//! --test cpu_differential seeded_register_sequences -- --exact
|
||||
//! ```
|
||||
//!
|
||||
//! The seed and bytes are printed for reproducing the program outside this
|
||||
//! harness as well.
|
||||
|
||||
use xenora_loader::cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, RFlags, Register};
|
||||
use xenora_loader::dbt::DbtEngine;
|
||||
use xenora_loader::memory::{GuestMemory, MemoryError, MemoryPermissions};
|
||||
|
||||
const CODE: u64 = 0x40_0000;
|
||||
const DATA: u64 = 0x50_0000;
|
||||
const DATA_LEN: usize = 192;
|
||||
const STACK_TOP: u64 = DATA + DATA_LEN as u64;
|
||||
const BUDGET: usize = 128;
|
||||
const TEST_SEED: u64 = 0x74_da7a_c0de_ba5e;
|
||||
|
||||
// SplitMix64 with a fresh stream per case. Changing the corpus order does not
|
||||
// affect replay of an existing index.
|
||||
struct Random(u64);
|
||||
|
||||
impl Random {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15);
|
||||
let mut word = self.0;
|
||||
word = (word ^ (word >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
|
||||
word = (word ^ (word >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
|
||||
word ^ (word >> 31)
|
||||
}
|
||||
|
||||
fn below(&mut self, end: usize) -> usize {
|
||||
(self.next() % end as u64) as usize
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct State {
|
||||
cpu: CpuState,
|
||||
data: [u8; DATA_LEN],
|
||||
af_defined: bool,
|
||||
}
|
||||
|
||||
impl State {
|
||||
fn seeded(random: &mut Random) -> Self {
|
||||
let mut cpu = CpuState::new(CODE, STACK_TOP);
|
||||
cpu.gpr = std::array::from_fn(|_| random.next());
|
||||
cpu.set(Register::Rsp, STACK_TOP);
|
||||
cpu.xmm =
|
||||
std::array::from_fn(|_| (u128::from(random.next()) << 64) | u128::from(random.next()));
|
||||
let flags = random.next();
|
||||
cpu.flags = RFlags {
|
||||
cf: flags & 1 != 0,
|
||||
pf: flags & 2 != 0,
|
||||
af: flags & 4 != 0,
|
||||
zf: flags & 8 != 0,
|
||||
sf: flags & 16 != 0,
|
||||
of: flags & 32 != 0,
|
||||
};
|
||||
cpu.df = flags & 64 != 0;
|
||||
cpu.fs_base = DATA;
|
||||
cpu.gs_base = DATA + 64;
|
||||
Self {
|
||||
cpu,
|
||||
data: std::array::from_fn(|_| random.next() as u8),
|
||||
af_defined: true,
|
||||
}
|
||||
}
|
||||
|
||||
fn checkpoint(&mut self, trace: &mut Vec<Self>, offset: usize) {
|
||||
self.cpu.rip = CODE + offset as u64;
|
||||
trace.push(self.clone());
|
||||
}
|
||||
|
||||
fn word(&self, offset: usize) -> u64 {
|
||||
u64::from_le_bytes(self.data[offset..offset + 8].try_into().unwrap())
|
||||
}
|
||||
|
||||
fn put_word(&mut self, offset: usize, value: u64) {
|
||||
self.data[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
struct Case {
|
||||
code: Vec<u8>,
|
||||
initial: State,
|
||||
// State after each attempted instruction, including the terminal instruction.
|
||||
trace: Vec<State>,
|
||||
native_only: bool,
|
||||
exit: ExitReason,
|
||||
}
|
||||
|
||||
impl Case {
|
||||
fn memory(&self) -> GuestMemory {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
CODE,
|
||||
self.code.len(),
|
||||
MemoryPermissions::READ_EXECUTE,
|
||||
&self.code,
|
||||
)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
DATA,
|
||||
DATA_LEN,
|
||||
MemoryPermissions::READ_WRITE,
|
||||
&self.initial.data,
|
||||
)
|
||||
.unwrap();
|
||||
memory
|
||||
}
|
||||
|
||||
fn verify(&self, id: &str) {
|
||||
let steps = self.trace.len();
|
||||
assert!(steps < BUDGET);
|
||||
let compare = |engine: &str,
|
||||
result: ExecutionResult,
|
||||
memory: &GuestMemory,
|
||||
budget: usize,
|
||||
offset: usize| {
|
||||
let steps = (steps - offset).min(budget);
|
||||
let expected = &self.trace[offset + steps - 1];
|
||||
let label = || {
|
||||
let start_rip = if offset == 0 {
|
||||
self.initial.cpu.rip
|
||||
} else {
|
||||
self.trace[offset - 1].cpu.rip
|
||||
};
|
||||
format!(
|
||||
"{id} {engine} from {start_rip:#x}, after {} guest steps, bytes {:02x?}",
|
||||
offset + steps,
|
||||
self.code
|
||||
)
|
||||
};
|
||||
let finished = offset + steps == self.trace.len();
|
||||
let exit = if finished {
|
||||
self.exit
|
||||
} else {
|
||||
ExitReason::StepLimitExceeded
|
||||
};
|
||||
let retired = steps - usize::from(finished && self.exit != ExitReason::Halt);
|
||||
assert_eq!(result.exit_reason, exit, "{}", label());
|
||||
assert_eq!(result.instructions_executed, retired, "{}", label());
|
||||
let mut actual = result.final_state;
|
||||
if !expected.af_defined {
|
||||
actual.flags.af = expected.cpu.flags.af;
|
||||
}
|
||||
assert_eq!(actual, expected.cpu, "{}", label());
|
||||
let mut data = [0; DATA_LEN];
|
||||
memory.read_bytes(DATA, &mut data).unwrap();
|
||||
if let Some(index) = data.iter().zip(expected.data).position(|(&a, b)| a != b) {
|
||||
panic!(
|
||||
"{}: guest byte at {:#x}: got {:#04x}, expected {:#04x}",
|
||||
label(),
|
||||
DATA + index as u64,
|
||||
data[index],
|
||||
expected.data[index]
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
let mut stepped = DbtEngine::new(128 * 1024).unwrap();
|
||||
let mut interpreted_memory = self.memory();
|
||||
let mut translated_memory = self.memory();
|
||||
let mut interpreted_cpu = self.initial.cpu.clone();
|
||||
let mut translated_cpu = self.initial.cpu.clone();
|
||||
// Check the first divergent retired instruction before testing full
|
||||
// blocks. Each engine continues from its own state at every step.
|
||||
for offset in 0..steps {
|
||||
let result = Interpreter::new(interpreted_cpu, &mut interpreted_memory, 1).run();
|
||||
interpreted_cpu = result.final_state.clone();
|
||||
compare(
|
||||
"interpreter (1 step)",
|
||||
result,
|
||||
&interpreted_memory,
|
||||
1,
|
||||
offset,
|
||||
);
|
||||
|
||||
let result = stepped.run(&mut translated_cpu, &mut translated_memory, 1);
|
||||
compare("DBT (1 step)", result, &translated_memory, 1, offset);
|
||||
}
|
||||
|
||||
// Exercise native block lowering and then reuse those blocks with a
|
||||
// fresh copy of the guest input and memory at the same addresses.
|
||||
let mut dbt = DbtEngine::new(128 * 1024).unwrap();
|
||||
let mut memory = self.memory();
|
||||
let result = Interpreter::new(self.initial.cpu.clone(), &mut memory, BUDGET).run();
|
||||
compare("interpreter", result, &memory, BUDGET, 0);
|
||||
let mut run_full = |engine| {
|
||||
let mut memory = self.memory();
|
||||
let result = dbt.run(&mut self.initial.cpu.clone(), &mut memory, BUDGET);
|
||||
compare(engine, result, &memory, BUDGET, 0);
|
||||
dbt.metrics
|
||||
};
|
||||
let cold = run_full("DBT (cold)");
|
||||
let cached = run_full("DBT (cached)");
|
||||
assert!(cold.blocks_compiled > 0, "{id}");
|
||||
assert_eq!(cold.blocks_compiled, cached.blocks_compiled, "{id}");
|
||||
assert!(cached.cache_hits > cold.cache_hits, "{id}");
|
||||
assert!(cached.dbt_dispatches > cold.dbt_dispatches, "{id}");
|
||||
|
||||
// These budgets cut the longer programs around a 16-instruction
|
||||
// native block boundary, including a resume from the truncated block.
|
||||
for budget in [15, 16, 17].into_iter().filter(|&budget| budget < steps) {
|
||||
let mut memory = self.memory();
|
||||
let mut cpu = self.initial.cpu.clone();
|
||||
let result = dbt.run(&mut cpu, &mut memory, budget);
|
||||
compare("DBT (limited)", result, &memory, budget, 0);
|
||||
let result = dbt.run(&mut cpu, &mut memory, BUDGET);
|
||||
compare("DBT (resumed)", result, &memory, BUDGET, budget);
|
||||
}
|
||||
|
||||
if self.native_only {
|
||||
assert_eq!(dbt.metrics.interpreter_fallbacks, 0, "{id}");
|
||||
assert_eq!(stepped.metrics.interpreter_fallbacks, 0, "{id}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum Alu {
|
||||
Add,
|
||||
Sub,
|
||||
Compare,
|
||||
Xor,
|
||||
Move,
|
||||
}
|
||||
|
||||
impl Alu {
|
||||
const OPS: [Self; 5] = [Self::Add, Self::Sub, Self::Compare, Self::Xor, Self::Move];
|
||||
|
||||
// SDM Vol. 2, §2.1 and the r/m,reg forms for each instruction. A bare
|
||||
// REX prefix selects SPL/BPL/SIL/DIL instead of the high byte registers.
|
||||
fn encode(self, code: &mut Vec<u8>, bits: u32, dst: usize, src: usize) {
|
||||
if bits == 16 {
|
||||
code.push(0x66);
|
||||
}
|
||||
let rex = 0x40 | (u8::from(bits == 64) << 3) | ((src as u8 >> 3) << 2) | (dst as u8 >> 3);
|
||||
if rex != 0x40 || (bits == 8 && (src >= 4 || dst >= 4)) {
|
||||
code.push(rex);
|
||||
}
|
||||
let byte_opcode = match self {
|
||||
Self::Add => 0x00,
|
||||
Self::Sub => 0x28,
|
||||
Self::Compare => 0x38,
|
||||
Self::Xor => 0x30,
|
||||
Self::Move => 0x88,
|
||||
};
|
||||
code.extend([
|
||||
byte_opcode | u8::from(bits != 8),
|
||||
0xc0 | ((src as u8 & 7) << 3) | (dst as u8 & 7),
|
||||
]);
|
||||
}
|
||||
|
||||
fn expect(self, state: &mut State, bits: u32, dst: usize, src: usize) {
|
||||
let mask = u64::MAX >> (64 - bits);
|
||||
let left = state.cpu.gpr[dst] & mask;
|
||||
let right = state.cpu.gpr[src] & mask;
|
||||
let result = match self {
|
||||
Self::Move => right,
|
||||
Self::Xor => {
|
||||
let result = left ^ right;
|
||||
state.cpu.flags = result_flags(result, bits);
|
||||
state.af_defined = false;
|
||||
result
|
||||
}
|
||||
Self::Add | Self::Compare | Self::Sub => {
|
||||
let (result, flags) = arithmetic(left, right, bits, matches!(self, Self::Add));
|
||||
state.cpu.flags = flags;
|
||||
state.af_defined = true;
|
||||
result
|
||||
}
|
||||
};
|
||||
if !matches!(self, Self::Compare) {
|
||||
state.cpu.gpr[dst] = if bits >= 32 {
|
||||
result
|
||||
} else {
|
||||
(state.cpu.gpr[dst] & !mask) | result
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn result_flags(result: u64, bits: u32) -> RFlags {
|
||||
RFlags {
|
||||
zf: result == 0,
|
||||
sf: result >> (bits - 1) == 1,
|
||||
pf: (result as u8).count_ones().is_multiple_of(2),
|
||||
..RFlags::default()
|
||||
}
|
||||
}
|
||||
|
||||
// Carry, auxiliary carry and signed overflow are derived by separate
|
||||
// widened calculations. The exact signed result determines overflow.
|
||||
fn arithmetic(left: u64, right: u64, bits: u32, add: bool) -> (u64, RFlags) {
|
||||
let modulus = 1i128 << bits;
|
||||
let signed = |word: u64| {
|
||||
let word = i128::from(word);
|
||||
if word >= modulus / 2 {
|
||||
word - modulus
|
||||
} else {
|
||||
word
|
||||
}
|
||||
};
|
||||
let operation = |a: i128, b: i128| if add { a + b } else { a - b };
|
||||
let wide = operation(i128::from(left), i128::from(right));
|
||||
let result = wide.rem_euclid(modulus) as u64;
|
||||
let mut flags = result_flags(result, bits);
|
||||
flags.cf = !(0..modulus).contains(&wide);
|
||||
let nibble = operation(i128::from(left & 15), i128::from(right & 15));
|
||||
flags.af = !(0..16).contains(&nibble);
|
||||
let signed_result = operation(signed(left), signed(right));
|
||||
flags.of = !(-modulus / 2..modulus / 2).contains(&signed_result);
|
||||
(result, flags)
|
||||
}
|
||||
|
||||
fn seeded_cases(
|
||||
test: &str,
|
||||
family: u64,
|
||||
count: usize,
|
||||
make_case: impl Fn(usize, &mut Random) -> Case,
|
||||
) {
|
||||
let selected = std::env::var("XENORA_CPU_DIFFERENTIAL_CASE")
|
||||
.ok()
|
||||
.map(|text| {
|
||||
let index = text
|
||||
.parse::<usize>()
|
||||
.expect("XENORA_CPU_DIFFERENTIAL_CASE must be a decimal case index");
|
||||
assert!(index < count, "{test} has case indices 0..{count}");
|
||||
index
|
||||
});
|
||||
for index in selected.map_or(0..count, |index| index..index + 1) {
|
||||
let seed = TEST_SEED ^ (family << 48) ^ index as u64;
|
||||
let case = make_case(index, &mut Random(seed));
|
||||
case.verify(&format!(
|
||||
"{test}: XENORA_CPU_DIFFERENTIAL_CASE={index} (seed {seed:#018x})"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeded_register_sequences() {
|
||||
const WIDTHS: [u32; 4] = [8, 16, 32, 64];
|
||||
seeded_cases("seeded_register_sequences", 1, 240, |index, random| {
|
||||
let mixed_widths = index >= 160;
|
||||
let bits = WIDTHS[index % 4];
|
||||
let edges = [
|
||||
0,
|
||||
1,
|
||||
15,
|
||||
16,
|
||||
(1u64 << (bits - 1)) - 1,
|
||||
1 << (bits - 1),
|
||||
u64::MAX,
|
||||
];
|
||||
let mut initial = State::seeded(random);
|
||||
// Keep random high bits when the operand is narrower than the GPR.
|
||||
let mask = u64::MAX >> (64 - bits);
|
||||
for reg in [0, 1, 2, 3, 8, 9, 10, 11] {
|
||||
let edge = edges[random.below(edges.len())];
|
||||
initial.cpu.gpr[reg] = (initial.cpu.gpr[reg] & !mask) | (edge & mask);
|
||||
}
|
||||
let mut state = initial.clone();
|
||||
let mut code = Vec::new();
|
||||
let mut trace = Vec::new();
|
||||
for step in 0..24 {
|
||||
let bits = if mixed_widths {
|
||||
WIDTHS[(index + step) % WIDTHS.len()]
|
||||
} else {
|
||||
bits
|
||||
};
|
||||
let op = Alu::OPS[random.below(Alu::OPS.len())];
|
||||
let dst = random.below(16);
|
||||
let src = random.below(16);
|
||||
op.encode(&mut code, bits, dst, src);
|
||||
op.expect(&mut state, bits, dst, src);
|
||||
state.checkpoint(&mut trace, code.len());
|
||||
}
|
||||
code.push(0xf4);
|
||||
state.checkpoint(&mut trace, code.len());
|
||||
Case {
|
||||
code,
|
||||
initial,
|
||||
trace,
|
||||
native_only: !mixed_widths && bits >= 32,
|
||||
exit: ExitReason::Halt,
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn branch_predicate(condition: usize, flags: RFlags) -> bool {
|
||||
let base = [
|
||||
flags.of,
|
||||
flags.cf,
|
||||
flags.zf,
|
||||
flags.cf || flags.zf,
|
||||
flags.sf,
|
||||
flags.pf,
|
||||
flags.sf != flags.of,
|
||||
flags.zf || flags.sf != flags.of,
|
||||
][condition / 2];
|
||||
base ^ !condition.is_multiple_of(2)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeded_compare_branch_pairs() {
|
||||
seeded_cases("seeded_compare_branch_pairs", 2, 128, |index, random| {
|
||||
let condition = index % 16;
|
||||
let taken = index / 16 % 2 != 0;
|
||||
let bits = [32, 64][index / 32 % 2];
|
||||
let near = index >= 64;
|
||||
let sign = 1u64 << (bits - 1);
|
||||
let boundary = [0, 1, 2, sign - 1, sign, sign | 1, (sign - 1) | sign];
|
||||
let pairs = boundary
|
||||
.into_iter()
|
||||
.flat_map(|left| boundary.map(|right| (left, right)));
|
||||
let eligible: Vec<_> = pairs
|
||||
.filter(|&(left, right)| {
|
||||
branch_predicate(condition, arithmetic(left, right, bits, false).1) == taken
|
||||
})
|
||||
.collect();
|
||||
let (left, right) = eligible[random.below(eligible.len())];
|
||||
let mut initial = State::seeded(random);
|
||||
let mask = u64::MAX >> (64 - bits);
|
||||
initial.cpu.gpr[0] = (initial.cpu.gpr[0] & !mask) | left;
|
||||
initial.cpu.gpr[8] = (initial.cpu.gpr[8] & !mask) | right;
|
||||
let mut state = initial.clone();
|
||||
let mut code = Vec::new();
|
||||
let mut trace = Vec::new();
|
||||
Alu::Compare.encode(&mut code, bits, 0, 8);
|
||||
Alu::Compare.expect(&mut state, bits, 0, 8);
|
||||
let branch = code.len();
|
||||
state.checkpoint(&mut trace, branch);
|
||||
if near {
|
||||
code.extend([0x0f, 0x80 + condition as u8, 3, 0, 0, 0]);
|
||||
} else {
|
||||
code.extend([0x70 + condition as u8, 3]);
|
||||
}
|
||||
// The two arms set distinct low bytes of RDX, then stop.
|
||||
let fallthrough = code.len();
|
||||
code.extend([0xb2, 0x31, 0xf4, 0xb2, 0x73, 0xf4]);
|
||||
let arm = fallthrough + if taken { 3 } else { 0 };
|
||||
state.checkpoint(&mut trace, arm);
|
||||
state.cpu.gpr[2] = (state.cpu.gpr[2] & !255) | if taken { 0x73 } else { 0x31 };
|
||||
state.checkpoint(&mut trace, arm + 2);
|
||||
state.checkpoint(&mut trace, arm + 3);
|
||||
Case {
|
||||
code,
|
||||
initial,
|
||||
trace,
|
||||
native_only: true,
|
||||
exit: ExitReason::Halt,
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeded_memory_loop_with_calls() {
|
||||
seeded_cases("seeded_memory_loop_with_calls", 3, 64, |_, random| {
|
||||
let count = random.below(8) + 1;
|
||||
let input = random.below(8);
|
||||
let output = 80 + random.below(8);
|
||||
let mut initial = State::seeded(random);
|
||||
initial.cpu.set(Register::Rcx, count as u64);
|
||||
initial.cpu.set(Register::Rsi, DATA + input as u64);
|
||||
initial.cpu.set(Register::Rdi, DATA + output as u64);
|
||||
let code = vec![
|
||||
0xe8, 10, 0, 0, 0, // 0: call sum
|
||||
0x48, 0x89, 0x44, 0xcf, 0xf8, // 5: mov [rdi + rcx*8 - 8], rax
|
||||
0xff, 0xc9, // 10: dec ecx
|
||||
0x75, 0xf2, // 12: jnz start
|
||||
0xf4, // 14: hlt
|
||||
0x48, 0x03, 0x44, 0xce, 0xf8, // 15: sum: add rax, [rsi + rcx*8 - 8]
|
||||
0xc3, // 20: ret
|
||||
];
|
||||
let mut state = initial.clone();
|
||||
let mut trace = Vec::new();
|
||||
let mut sum = state.cpu.get(Register::Rax);
|
||||
for remaining in (1..=count).rev() {
|
||||
state.put_word(DATA_LEN - 8, CODE + 5);
|
||||
state.cpu.set(Register::Rsp, STACK_TOP - 8);
|
||||
state.checkpoint(&mut trace, 15);
|
||||
|
||||
let index = (remaining - 1) * 8;
|
||||
let (next, flags) = arithmetic(sum, initial.word(input + index), 64, true);
|
||||
sum = next;
|
||||
state.cpu.set(Register::Rax, sum);
|
||||
state.cpu.flags = flags;
|
||||
state.checkpoint(&mut trace, 20);
|
||||
|
||||
state.cpu.set(Register::Rsp, STACK_TOP);
|
||||
state.checkpoint(&mut trace, 5);
|
||||
state.put_word(output + index, sum);
|
||||
state.checkpoint(&mut trace, 10);
|
||||
|
||||
let (counter, mut flags) = arithmetic(remaining as u64, 1, 32, false);
|
||||
flags.cf = state.cpu.flags.cf; // DEC leaves carry intact.
|
||||
state.cpu.set(Register::Rcx, counter);
|
||||
state.cpu.flags = flags;
|
||||
state.checkpoint(&mut trace, 12);
|
||||
state.checkpoint(&mut trace, if counter == 0 { 14 } else { 0 });
|
||||
}
|
||||
state.checkpoint(&mut trace, 15);
|
||||
Case {
|
||||
code,
|
||||
initial,
|
||||
trace,
|
||||
native_only: true,
|
||||
exit: ExitReason::Halt,
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeded_vector_load_arithmetic_store() {
|
||||
seeded_cases("seeded_vector_load_arithmetic_store", 4, 64, |_, random| {
|
||||
let mut initial = State::seeded(random);
|
||||
let input = random.below(16);
|
||||
let output = 64 + random.below(16);
|
||||
initial.cpu.set(Register::Rsi, DATA + input as u64);
|
||||
initial.cpu.set(Register::Rdi, DATA + output as u64);
|
||||
let code = vec![
|
||||
0xf3, 0x44, 0x0f, 0x6f, 0x0e, // 0: movdqu xmm9, [rsi]
|
||||
0x66, 0x44, 0x0f, 0xfc, 0xca, // 5: paddb xmm9, xmm2
|
||||
0x66, 0x45, 0x0f, 0xf9, 0xcf, // 10: psubw xmm9, xmm15
|
||||
0x66, 0x44, 0x0f, 0xef, 0xc8, // 15: pxor xmm9, xmm0
|
||||
0xf3, 0x44, 0x0f, 0x7f, 0x0f, // 20: movdqu [rdi], xmm9
|
||||
0xf4,
|
||||
];
|
||||
let mut state = initial.clone();
|
||||
let mut trace = Vec::new();
|
||||
let mut lanes: [u8; 16] = initial.data[input..input + 16].try_into().unwrap();
|
||||
state.cpu.xmm[9] = u128::from_le_bytes(lanes);
|
||||
state.checkpoint(&mut trace, 5);
|
||||
|
||||
for (lane, addend) in lanes.iter_mut().zip(initial.cpu.xmm[2].to_le_bytes()) {
|
||||
*lane = lane.wrapping_add(addend);
|
||||
}
|
||||
state.cpu.xmm[9] = u128::from_le_bytes(lanes);
|
||||
state.checkpoint(&mut trace, 10);
|
||||
|
||||
let subtrahend = initial.cpu.xmm[15].to_le_bytes();
|
||||
let (words, _) = lanes.as_chunks_mut::<2>();
|
||||
let (subtrahends, _) = subtrahend.as_chunks::<2>();
|
||||
for (word, &rhs) in words.iter_mut().zip(subtrahends) {
|
||||
let left = u16::from_le_bytes(*word);
|
||||
let right = u16::from_le_bytes(rhs);
|
||||
*word = left.wrapping_sub(right).to_le_bytes();
|
||||
}
|
||||
state.cpu.xmm[9] = u128::from_le_bytes(lanes);
|
||||
state.checkpoint(&mut trace, 15);
|
||||
|
||||
state.cpu.xmm[9] ^= initial.cpu.xmm[0];
|
||||
state.checkpoint(&mut trace, 20);
|
||||
state.data[output..output + 16].copy_from_slice(&state.cpu.xmm[9].to_le_bytes());
|
||||
state.checkpoint(&mut trace, 25);
|
||||
state.checkpoint(&mut trace, 26);
|
||||
Case {
|
||||
code,
|
||||
initial,
|
||||
trace,
|
||||
native_only: true,
|
||||
exit: ExitReason::Halt,
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeded_precise_memory_faults() {
|
||||
seeded_cases("seeded_precise_memory_faults", 5, 28, |index, random| {
|
||||
// Both branch outcomes and both operand directions at each of the
|
||||
// seven possible byte splits of an eight-byte operand.
|
||||
let store = index.is_multiple_of(2);
|
||||
let taken = (index / 2).is_multiple_of(2);
|
||||
let split = index / 4 + 1;
|
||||
let mut initial = State::seeded(random);
|
||||
let output = random.below(32);
|
||||
let value = initial.cpu.get(Register::Rax);
|
||||
let rhs = if taken { value } else { value ^ (1 << 63) };
|
||||
initial.cpu.set(Register::R8, rhs);
|
||||
initial.cpu.set(Register::Rdi, DATA + output as u64);
|
||||
initial.cpu.set(Register::Rsi, STACK_TOP - split as u64);
|
||||
let code = vec![
|
||||
0x48,
|
||||
0x89,
|
||||
0x07, // 0: mov [rdi], rax
|
||||
0x4c,
|
||||
0x39,
|
||||
0xc0, // 3: cmp rax, r8
|
||||
0x74,
|
||||
0x03, // 6: je faulting_move
|
||||
0x4d,
|
||||
0x89,
|
||||
0xd1, // 8: mov r9, r10
|
||||
0x48,
|
||||
if store { 0x89 } else { 0x8b },
|
||||
0x06, // 11: mov [rsi], rax or mov rax, [rsi]
|
||||
0xf4,
|
||||
];
|
||||
let mut state = initial.clone();
|
||||
let mut trace = Vec::new();
|
||||
state.put_word(output, value);
|
||||
state.checkpoint(&mut trace, 3);
|
||||
state.cpu.flags = arithmetic(value, rhs, 64, false).1;
|
||||
state.checkpoint(&mut trace, 6);
|
||||
if taken {
|
||||
state.checkpoint(&mut trace, 11);
|
||||
} else {
|
||||
state.checkpoint(&mut trace, 8);
|
||||
state.cpu.set(Register::R9, initial.cpu.get(Register::R10));
|
||||
state.checkpoint(&mut trace, 11);
|
||||
}
|
||||
// The faulting instruction leaves RIP, registers and all mapped bytes
|
||||
// intact. The preceding store and optional register move stay retired.
|
||||
state.checkpoint(&mut trace, 11);
|
||||
Case {
|
||||
code,
|
||||
initial,
|
||||
trace,
|
||||
native_only: true,
|
||||
exit: ExitReason::MemoryFault(MemoryError::UnmappedAddress(STACK_TOP)),
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! The guest CPUID contract (issue #130).
|
||||
//!
|
||||
//! CPUID reports a fixed synthetic processor. A feature bit is set only when
|
||||
//! every instruction of that feature is implemented, so each bit that is set
|
||||
//! is checked against instructions that run, and each bit software commonly
|
||||
//! tests that is clear has a witness instruction of that feature which both
|
||||
//! engines refuse. The witness must be removed before its bit can be set.
|
||||
//!
|
||||
//! Bit positions and the feature each instruction belongs to are from the
|
||||
//! Intel SDM Vol. 2, CPUID and the instruction entries. Encodings were
|
||||
//! assembled with `clang -target x86_64-apple-macos` and read with `objdump`.
|
||||
|
||||
use xenora_loader::cpu::{
|
||||
CPUID_CMOV, CPUID_LONG_MODE, CPUID_LZCNT, CPUID_POPCNT, CpuState, ExitReason, Interpreter,
|
||||
RFlags, cpuid,
|
||||
};
|
||||
use xenora_loader::dbt::DbtEngine;
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
use xenora_loader::x86_decode::decode;
|
||||
|
||||
const ENTRY: u64 = 0x1000;
|
||||
const RAX: usize = 0;
|
||||
const RCX: usize = 1;
|
||||
const RDX: usize = 2;
|
||||
const RBX: usize = 3;
|
||||
const RSI: usize = 6;
|
||||
|
||||
/// Index of a CPUID result, which come in the order EAX, EBX, ECX, EDX.
|
||||
const EBX: usize = 1;
|
||||
const ECX: usize = 2;
|
||||
const EDX: usize = 3;
|
||||
|
||||
fn image(code: &[u8]) -> GuestMemory {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, code)
|
||||
.unwrap();
|
||||
memory
|
||||
}
|
||||
|
||||
/// Final state and exit reason from the interpreter, then from the DBT.
|
||||
fn both(cpu: &CpuState, code: &[u8], budget: usize) -> [(&'static str, CpuState, ExitReason); 2] {
|
||||
let mut memory = image(code);
|
||||
let interpreted = Interpreter::new(cpu.clone(), &mut memory, budget).run();
|
||||
let mut memory = image(code);
|
||||
let mut state = cpu.clone();
|
||||
let translated = DbtEngine::new(64 * 1024)
|
||||
.unwrap()
|
||||
.run(&mut state, &mut memory, budget);
|
||||
[
|
||||
(
|
||||
"interpreter",
|
||||
interpreted.final_state,
|
||||
interpreted.exit_reason,
|
||||
),
|
||||
("DBT", translated.final_state, translated.exit_reason),
|
||||
]
|
||||
}
|
||||
|
||||
const SET: RFlags = RFlags {
|
||||
cf: true,
|
||||
zf: true,
|
||||
sf: true,
|
||||
of: true,
|
||||
pf: true,
|
||||
af: true,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn every_leaf_returns_its_documented_values() {
|
||||
// (leaf, subleaf, [EAX, EBX, ECX, EDX])
|
||||
let leaves: &[(u32, u32, [u32; 4])] = &[
|
||||
// Highest basic leaf 1, and "Xeno", "uest", "ra g" as little-endian text.
|
||||
(0, 0, [1, 0x6F6E_6558, 0x7473_6575, 0x6720_6172]),
|
||||
// POPCNT is ECX bit 23 and CMOV is EDX bit 15. No signature.
|
||||
(1, 0, [0, 0, 0x0080_0000, 0x0000_8000]),
|
||||
(1, 0xFFFF_FFFF, [0, 0, 0x0080_0000, 0x0000_8000]),
|
||||
// Highest extended leaf.
|
||||
(0x8000_0000, 0, [0x8000_0001, 0, 0, 0]),
|
||||
// LZCNT is ECX bit 5 and long mode is EDX bit 29.
|
||||
(0x8000_0001, 0, [0, 0, 0x0000_0020, 0x2000_0000]),
|
||||
(0x8000_0001, 7, [0, 0, 0x0000_0020, 0x2000_0000]),
|
||||
// Everything else, above or between the highest leaves, is zeros.
|
||||
(2, 0, [0; 4]),
|
||||
(4, 0, [0; 4]),
|
||||
(6, 0, [0; 4]),
|
||||
(7, 0, [0; 4]),
|
||||
(7, 1, [0; 4]),
|
||||
(0xB, 0, [0; 4]),
|
||||
(0xD, 1, [0; 4]),
|
||||
(0x16, 0, [0; 4]),
|
||||
(0x4000_0000, 0, [0; 4]),
|
||||
(0x7FFF_FFFF, 0, [0; 4]),
|
||||
(0x8000_0002, 0, [0; 4]),
|
||||
(0x8000_0008, 0, [0; 4]),
|
||||
(0xFFFF_FFFF, 0, [0; 4]),
|
||||
];
|
||||
for &(leaf, subleaf, wanted) in leaves {
|
||||
// Only EAX and ECX select the leaf: the upper halves are noise.
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
for (index, register) in cpu.gpr.iter_mut().enumerate() {
|
||||
*register = 0xA5A5_0000_1111_0000 + index as u64;
|
||||
}
|
||||
cpu.gpr[RAX] = 0xDEAD_BEEF_0000_0000 | u64::from(leaf);
|
||||
cpu.gpr[RCX] = 0xFEED_FACE_0000_0000 | u64::from(subleaf);
|
||||
cpu.flags = SET;
|
||||
// Each result is a 32-bit register write, so it clears the upper half.
|
||||
// CPUID changes no flag and no other register.
|
||||
let mut expected = cpu.clone();
|
||||
expected.rip = ENTRY + 2;
|
||||
for (register, value) in [RAX, RBX, RCX, RDX].into_iter().zip(wanted) {
|
||||
expected.gpr[register] = u64::from(value);
|
||||
}
|
||||
for (engine, state, exit) in both(&cpu, &[0x0F, 0xA2], 1) {
|
||||
let what = format!("leaf {leaf:#x} subleaf {subleaf:#x} on the {engine}");
|
||||
assert_eq!(exit, ExitReason::StepLimitExceeded, "{what}");
|
||||
assert_eq!(state, expected, "{what}");
|
||||
}
|
||||
// The function a runtime service would read agrees with the instruction.
|
||||
assert_eq!(cpuid(leaf, subleaf), wanted, "leaf {leaf:#x}");
|
||||
}
|
||||
|
||||
let [_, ebx, ecx, edx] = cpuid(0, 0);
|
||||
let vendor: Vec<u8> = [ebx, edx, ecx]
|
||||
.into_iter()
|
||||
.flat_map(u32::to_le_bytes)
|
||||
.collect();
|
||||
assert_eq!(vendor, b"Xenora guest");
|
||||
assert_eq!(
|
||||
(CPUID_POPCNT, CPUID_CMOV, CPUID_LZCNT, CPUID_LONG_MODE),
|
||||
(1 << 23, 1 << 15, 1 << 5, 1 << 29)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reported_features_have_all_their_instructions_in_the_fixtures() {
|
||||
// `tests/x86_integer.rs` runs every line of this file through both engines
|
||||
// against an independent reference. Here each reported feature must have
|
||||
// its whole instruction set among those lines.
|
||||
let fixture = include_str!("x86/integer.txt");
|
||||
let decodable = |text: &str| {
|
||||
let line = fixture
|
||||
.lines()
|
||||
.find(|line| line.split_once(" | ").is_some_and(|(_, asm)| asm == text))
|
||||
.unwrap_or_else(|| panic!("no fixture for {text}"));
|
||||
let code: Vec<u8> = line
|
||||
.split_once(" | ")
|
||||
.unwrap()
|
||||
.0
|
||||
.split(' ')
|
||||
.map(|byte| u8::from_str_radix(byte, 16).unwrap())
|
||||
.collect();
|
||||
decode(ENTRY, |at| {
|
||||
code.get((at - ENTRY) as usize).copied().ok_or(())
|
||||
})
|
||||
.unwrap_or_else(|error| panic!("{text}: {error:?}"));
|
||||
};
|
||||
let memory = |bits: u32| {
|
||||
let width = match bits {
|
||||
16 => "word",
|
||||
32 => "dword",
|
||||
_ => "qword",
|
||||
};
|
||||
format!("{width} ptr [rsi + 4*rdi + 16]")
|
||||
};
|
||||
// 16-, 32- and 64-bit destinations (RBX and R10) from a register and from memory.
|
||||
let sizes = [
|
||||
(16, "bx", "r9w", "r10w"),
|
||||
(32, "ebx", "r9d", "r10d"),
|
||||
(64, "rbx", "r9", "r10"),
|
||||
];
|
||||
|
||||
assert_ne!(cpuid(1, 0)[EDX] & CPUID_CMOV, 0);
|
||||
for condition in "o no b ae e ne be a s ns p np l ge le g".split(' ') {
|
||||
for (bits, low, source, high) in sizes {
|
||||
decodable(&format!("cmov{condition} {low}, {source}"));
|
||||
decodable(&format!("cmov{condition} {high}, {}", memory(bits)));
|
||||
}
|
||||
}
|
||||
for (feature, bit, name) in [
|
||||
(cpuid(1, 0)[ECX], CPUID_POPCNT, "popcnt"),
|
||||
(cpuid(0x8000_0001, 0)[ECX], CPUID_LZCNT, "lzcnt"),
|
||||
] {
|
||||
assert_ne!(feature & bit, 0, "{name}");
|
||||
for (bits, low, source, high) in sizes {
|
||||
decodable(&format!("{name} {low}, {source}"));
|
||||
decodable(&format!("{name} {high}, {}", memory(bits)));
|
||||
}
|
||||
}
|
||||
// Long mode: 64-bit operands and the registers only it has.
|
||||
assert_ne!(cpuid(0x8000_0001, 0)[EDX] & CPUID_LONG_MODE, 0);
|
||||
decodable("add r9, r12");
|
||||
decodable("movabs r15, 0x8877665544332211");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unreported_features_each_have_an_instruction_that_is_refused() {
|
||||
// (feature, leaf, result register, bit, an instruction of that feature)
|
||||
let witnesses: &[(&str, u32, usize, u32, &[u8])] = &[
|
||||
("FPU", 1, EDX, 0, &[0xD9, 0xE8]), // fld1
|
||||
("TSC", 1, EDX, 4, &[0x0F, 0x31]), // rdtsc
|
||||
("CX8", 1, EDX, 8, &[0x0F, 0xC7, 0x0E]), // cmpxchg8b [rsi]
|
||||
("CLFSH", 1, EDX, 19, &[0x0F, 0xAE, 0x3E]), // clflush [rsi]
|
||||
("MMX", 1, EDX, 23, &[0x0F, 0x77]), // emms
|
||||
("FXSR", 1, EDX, 24, &[0x0F, 0xAE, 0x06]), // fxsave [rsi]
|
||||
("SSE", 1, EDX, 25, &[0x0F, 0x52, 0xC1]), // rsqrtps xmm0, xmm1
|
||||
("SSE2", 1, EDX, 26, &[0x66, 0x0F, 0xF7, 0xC1]), // maskmovdqu xmm0, xmm1
|
||||
("SSE3", 1, ECX, 0, &[0xF2, 0x0F, 0x7C, 0xC1]), // haddps xmm0, xmm1
|
||||
(
|
||||
"PCLMULQDQ",
|
||||
1,
|
||||
ECX,
|
||||
1,
|
||||
&[0x66, 0x0F, 0x3A, 0x44, 0xC1, 0x00],
|
||||
), // pclmulqdq xmm0, xmm1, 0
|
||||
("SSSE3", 1, ECX, 9, &[0x66, 0x0F, 0x38, 0x00, 0xC1]), // pshufb xmm0, xmm1
|
||||
("FMA", 1, ECX, 12, &[0xC4, 0xE2, 0x71, 0x98, 0xC2]), // vfmadd132ps xmm0, xmm1, xmm2
|
||||
("CMPXCHG16B", 1, ECX, 13, &[0x48, 0x0F, 0xC7, 0x0E]), // cmpxchg16b [rsi]
|
||||
("SSE4.1", 1, ECX, 19, &[0x66, 0x0F, 0x38, 0x40, 0xC1]), // pmulld xmm0, xmm1
|
||||
("SSE4.2", 1, ECX, 20, &[0xF2, 0x0F, 0x38, 0xF1, 0xC1]), // crc32 eax, ecx
|
||||
("MOVBE", 1, ECX, 22, &[0x0F, 0x38, 0xF0, 0x06]), // movbe eax, [rsi]
|
||||
("AESNI", 1, ECX, 25, &[0x66, 0x0F, 0x38, 0xDC, 0xC1]), // aesenc xmm0, xmm1
|
||||
("XSAVE", 1, ECX, 26, &[0x0F, 0x01, 0xD0]), // xgetbv
|
||||
("AVX", 1, ECX, 28, &[0xC5, 0xF4, 0x58, 0xC2]), // vaddps ymm0, ymm1, ymm2
|
||||
("F16C", 1, ECX, 29, &[0xC4, 0xE2, 0x79, 0x13, 0xC1]), // vcvtph2ps xmm0, xmm1
|
||||
("RDRAND", 1, ECX, 30, &[0x0F, 0xC7, 0xF0]), // rdrand eax
|
||||
("BMI1", 7, EBX, 3, &[0xC4, 0xE2, 0x70, 0xF2, 0xC2]), // andn eax, ecx, edx
|
||||
("AVX2", 7, EBX, 5, &[0xC5, 0xF5, 0xFE, 0xC2]), // vpaddd ymm0, ymm1, ymm2
|
||||
("BMI2", 7, EBX, 8, &[0xC4, 0xE2, 0x73, 0xF6, 0xC2]), // mulx eax, ecx, edx
|
||||
("RDSEED", 7, EBX, 18, &[0x0F, 0xC7, 0xF8]), // rdseed eax
|
||||
("ADX", 7, EBX, 19, &[0x66, 0x0F, 0x38, 0xF6, 0xC1]), // adcx eax, ecx
|
||||
("SHA", 7, EBX, 29, &[0x0F, 0x38, 0xC9, 0xC1]), // sha1msg1 xmm0, xmm1
|
||||
("LAHF/SAHF", 0x8000_0001, ECX, 0, &[0x9F]), // lahf
|
||||
("PREFETCHW", 0x8000_0001, ECX, 8, &[0x0F, 0x0D, 0x0E]), // prefetchw [rsi]
|
||||
("SYSCALL/SYSRET", 0x8000_0001, EDX, 11, &[0x48, 0x0F, 0x07]), // sysretq
|
||||
("RDTSCP", 0x8000_0001, EDX, 27, &[0x0F, 0x01, 0xF9]), // rdtscp
|
||||
];
|
||||
for &(feature, leaf, register, bit, code) in witnesses {
|
||||
assert_eq!(
|
||||
cpuid(leaf, 0)[register] >> bit & 1,
|
||||
0,
|
||||
"{feature} is reported"
|
||||
);
|
||||
let mut padded = code.to_vec();
|
||||
padded.extend([0x90; 8]);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RSI] = ENTRY;
|
||||
for (engine, state, exit) in both(&cpu, &padded, 1) {
|
||||
assert!(
|
||||
matches!(exit, ExitReason::IllegalInstruction(_)),
|
||||
"{feature}: {code:02X?} ran on the {engine} ({exit:?}); report the feature only \
|
||||
once all of it is implemented"
|
||||
);
|
||||
assert_eq!(state, cpu, "{feature} on the {engine}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_guest_can_use_an_instruction_after_testing_its_feature_bit() {
|
||||
// mov eax, 1
|
||||
// cpuid
|
||||
// bt ecx, 23 ; POPCNT
|
||||
// jnc done
|
||||
// popcnt rax, rsi
|
||||
// done: hlt
|
||||
let code = [
|
||||
0xB8, 0x01, 0x00, 0x00, 0x00, 0x0F, 0xA2, 0x0F, 0xBA, 0xE1, 0x17, 0x73, 0x05, 0xF3, 0x48,
|
||||
0x0F, 0xB8, 0xC6, 0xF4,
|
||||
];
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RSI] = 0xF0F0_0000_0000_0001;
|
||||
for (engine, state, exit) in both(&cpu, &code, 16) {
|
||||
assert_eq!(exit, ExitReason::Halt, "{engine}");
|
||||
// Nine bits are set in RSI. Leaf 1 leaves EAX zero, so a skipped
|
||||
// POPCNT would show as 0.
|
||||
assert_eq!(state.gpr[RAX], 9, "{engine}");
|
||||
assert_eq!(state.rip, ENTRY + code.len() as u64, "{engine}");
|
||||
}
|
||||
}
|
||||
@@ -1294,6 +1294,147 @@ gs_xadd_without_lock: rbx=8 rcx=5 gs8=03000000 => rcx=3 gs8=08000000 f=cpazso
|
||||
fs_rep_movsb_overrides_source_only_df_clear: rsi=8 rdi=D rcx=2 fs8=a1a2 m0=0000 => rsi=a rdi=D+2 rcx=0 m0=a1a2 f=*
|
||||
";
|
||||
|
||||
/// MOV r/m, imm (opcodes C6 /0 and C7 /0), issue #194.
|
||||
///
|
||||
/// Memory-form encodings came from Apple clang's assembler. The register forms
|
||||
/// of C6/C7 are the long alternatives to B0+r and B8+r, which that assembler
|
||||
/// never emits, so they were written by hand from the opcode map (ModRM
|
||||
/// `11 000 rm`). Expected values follow SDM 2B MOV, where the imm32 of the
|
||||
/// 64-bit form is sign-extended, and were computed by hand before the first run,
|
||||
/// without reading how the interpreter or the DBT execute C6 and C7. The author is
|
||||
/// an AI model, as for the rest of this file. Both engines already agreed with
|
||||
/// every case, so this group closes a coverage gap and fixes no defect.
|
||||
const IMMEDIATE_STORES: &str = r"
|
||||
@ mov byte ptr [rdi], 0x80
|
||||
c60780
|
||||
SDM 2B MOV (C6 /0)
|
||||
store_byte_base: rdi=D m0=aaaaaaaa => m0=80aaaaaa f=*
|
||||
@ mov word ptr [rdi], 0x8001
|
||||
66c7070180
|
||||
SDM 2B MOV (C7 /0, 66 prefix)
|
||||
store_word_base: rdi=D m0=aaaaaaaa => m0=0180aaaa f=*
|
||||
@ mov dword ptr [rdi], 0x80000001
|
||||
c70701000080
|
||||
SDM 2B MOV (C7 /0)
|
||||
store_dword_base_is_not_sign_extended: rdi=D m0=aaaaaaaaaaaaaaaa => m0=01000080aaaaaaaa f=*
|
||||
@ mov qword ptr [rdi], -0x7fffffff
|
||||
48c70701000080
|
||||
SDM 2B MOV (REX.W C7 /0, imm32 sign-extended to 64 bits)
|
||||
store_qword_negative_immediate_sign_extends: rdi=D m0=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa => m0=01000080ffffffffaaaaaaaaaaaaaaaa f=*
|
||||
@ mov qword ptr [rdi], 1
|
||||
48c70701000000
|
||||
SDM 2B MOV (REX.W C7 /0)
|
||||
store_qword_positive_immediate_clears_upper_half: rdi=D m0=ffffffffffffffffaaaaaaaaaaaaaaaa => m0=0100000000000000aaaaaaaaaaaaaaaa f=*
|
||||
@ mov qword ptr [rdi+rcx*8+0x10], -2
|
||||
48c744cf10feffffff
|
||||
SDM 2B MOV; 2A 2.1.5 (SIB, disp8)
|
||||
store_qword_sib_scale_8_disp8: rdi=D rcx=2 m20=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa => m20=feffffffffffffffaaaaaaaaaaaaaaaa f=*
|
||||
@ mov dword ptr [rdi+0x7f], 0x11223344
|
||||
c7477f44332211
|
||||
SDM 2B MOV; 2A 2.1.5 (disp8, largest positive)
|
||||
store_dword_disp8_positive_limit: rdi=D m7e=aaaaaaaaaaaaaaaaaaaa => m7e=aa44332211aaaaaaaaaa f=*
|
||||
@ mov dword ptr [rdi-0x80], 0x11223344
|
||||
c7478044332211
|
||||
SDM 2B MOV; 2A 2.1.5 (disp8 is sign-extended)
|
||||
store_dword_disp8_negative_limit: rdi=D+80 m0=aaaaaaaaaaaaaaaa => m0=44332211aaaaaaaa f=*
|
||||
@ mov dword ptr [rdi+0x100], 0x11223344
|
||||
c7870001000044332211
|
||||
SDM 2B MOV; 2A 2.1.5 (disp32)
|
||||
store_dword_disp32: rdi=D m100=aaaaaaaaaaaaaaaa => m100=44332211aaaaaaaa f=*
|
||||
@ mov byte ptr [r9+r10*2+1], 7
|
||||
43c644510107
|
||||
SDM 2B MOV; 2A 2.1.5 (REX.X and REX.B)
|
||||
store_byte_rex_base_and_index: r9=D+10 r10=8 m20=aaaaaaaa => m20=aa07aaaa f=*
|
||||
@ mov qword ptr [r12], 5
|
||||
49c7042405000000
|
||||
SDM 2B MOV; 2A 2.1.5 (R12 needs a SIB byte)
|
||||
store_qword_r12_base: r12=D+30 m30=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa => m30=0500000000000000aaaaaaaaaaaaaaaa f=*
|
||||
@ mov qword ptr [r13], 5
|
||||
49c7450005000000
|
||||
SDM 2B MOV; 2A 2.1.5 (R13 with mod 00 would be RIP-relative, so disp8 0)
|
||||
store_qword_r13_base: r13=D+40 m40=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa => m40=0500000000000000aaaaaaaaaaaaaaaa f=*
|
||||
@ mov word ptr [rsp+8], 0x1234
|
||||
66c74424083412
|
||||
SDM 2B MOV; 2A 2.1.5 (RSP needs a SIB byte)
|
||||
store_word_rsp_base: rsp=D+58 m60=aaaaaaaa => m60=3412aaaa f=*
|
||||
@ mov byte ptr [rbp+2], 0x7f
|
||||
c645027f
|
||||
SDM 2B MOV
|
||||
store_byte_rbp_disp8: rbp=D+70 m72=aaaa => m72=7faa f=*
|
||||
@ mov byte ptr [rdi+rcx], -1
|
||||
c6040fff
|
||||
SDM 2B MOV
|
||||
store_byte_base_plus_index: rdi=D+80 rcx=5 m84=aaaaaaaa => m84=aaffaaaa f=*
|
||||
@ mov word ptr [r8+r9*4+0x20], 0x7ffe
|
||||
6643c7448820fe7f
|
||||
SDM 2B MOV; 2A 2.1.5
|
||||
store_word_r8_r9_scaled: r8=D r9=10 m60=aaaaaaaa => m60=fe7faaaa f=*
|
||||
@ mov eax, 0x80000001
|
||||
c7c001000080
|
||||
SDM 2B MOV (C7 /0, register form); 1 3.4.1.1
|
||||
register_dword_zero_extends: rax=ffffffffffffffff => rax=0000000080000001 f=*
|
||||
@ mov ax, 0x8001
|
||||
66c7c00180
|
||||
SDM 2B MOV; 1 3.4.1.1
|
||||
register_word_keeps_upper_bits: rax=1122334455667788 => rax=1122334455668001 f=*
|
||||
@ mov rax, -2
|
||||
48c7c0feffffff
|
||||
SDM 2B MOV (REX.W C7 /0, register form)
|
||||
register_qword_sign_extends: rax=0 => rax=fffffffffffffffe f=*
|
||||
@ mov r10, 0x7fffffff
|
||||
49c7c2ffffff7f
|
||||
SDM 2B MOV
|
||||
register_qword_rex_b_positive: r10=ffffffffffffffff => r10=000000007fffffff f=*
|
||||
@ mov r8d, -1
|
||||
41c7c0ffffffff
|
||||
SDM 2B MOV; 1 3.4.1.1
|
||||
register_dword_rex_b_zero_extends: r8=1122334455667788 => r8=00000000ffffffff f=*
|
||||
@ mov al, 0x80
|
||||
c6c080
|
||||
SDM 2B MOV (C6 /0, register form)
|
||||
register_byte_al: rax=1122334455667788 => rax=1122334455667780 f=*
|
||||
@ mov ah, 5
|
||||
c6c405
|
||||
SDM 2B MOV; 1 3.4.1.1 (no REX: ModRM 4 is AH)
|
||||
register_byte_ah: rax=1122334455667788 => rax=1122334455660588 f=*
|
||||
@ mov sil, 3
|
||||
40c6c603
|
||||
SDM 2B MOV; 1 3.4.1.1 (a REX prefix makes ModRM 6 SIL)
|
||||
register_byte_sil: rsi=1122334455667788 => rsi=1122334455667703 f=*
|
||||
@ mov r9b, 4
|
||||
41c6c104
|
||||
SDM 2B MOV
|
||||
register_byte_r9b: r9=1122334455667788 => r9=1122334455667704 f=*
|
||||
@ mov byte ptr [rdi], 0x80
|
||||
!c60780
|
||||
SDM 3A 7.15 Interrupt 14
|
||||
store_byte_unmapped: rdi=U => ! PFW U
|
||||
store_byte_readonly: rdi=R+8 => ! PFW R+8
|
||||
@ mov word ptr [rdi], 0x8001
|
||||
!66c7070180
|
||||
SDM 3A 7.15 Interrupt 14
|
||||
store_word_unmapped: rdi=U => ! PFW U
|
||||
store_word_readonly: rdi=R+8 => ! PFW R+8
|
||||
@ mov dword ptr [rdi], 0x80000001
|
||||
!c70701000080
|
||||
SDM 3A 7.15 Interrupt 14
|
||||
store_dword_unmapped: rdi=U => ! PFW U
|
||||
store_dword_readonly: rdi=R+8 => ! PFW R+8
|
||||
@ mov qword ptr [rdi], -0x7fffffff
|
||||
!48c70701000080
|
||||
SDM 3A 7.15 Interrupt 14
|
||||
store_qword_unmapped: rdi=U => ! PFW U
|
||||
store_qword_readonly: rdi=R+8 => ! PFW R+8
|
||||
@ C6 with ModRM reg field 1 (no such instruction)
|
||||
!c60f01
|
||||
SDM 2B MOV (C6 is defined only as /0); 3A 7.15 Interrupt 6
|
||||
c6_reg_field_1_is_ud: rdi=D m0=aaaaaaaa => ! UD
|
||||
@ C7 with ModRM reg field 1 (no such instruction)
|
||||
!c70f01000000
|
||||
SDM 2B MOV (C7 is defined only as /0); 3A 7.15 Interrupt 6
|
||||
c7_reg_field_1_is_ud: rdi=D m0=aaaaaaaa => ! UD
|
||||
";
|
||||
|
||||
const DECODING: &str = r"
|
||||
@ mov eax, [ebx]
|
||||
678b03
|
||||
@@ -1307,6 +1448,18 @@ addr32_sum_wraps_at_32_bits: rbx=ffff0000 rcx=10000+D rax=0 m0=44332211 => rax=1
|
||||
486601d8
|
||||
SDM 2A 2.2.1
|
||||
rex_not_adjacent_to_opcode_is_ignored: rax=112233445566ffff rbx=1 => rax=1122334455660000 f=CPAZso
|
||||
@ .byte 0x41,0x66,0x01,0xd8
|
||||
416601d8
|
||||
SDM 2A 2.2.1
|
||||
ignored_rex_b_does_not_select_r8: rax=112233445566ffff rbx=1 r8=5 => rax=1122334455660000 f=CPAZso
|
||||
@ .byte 0x48,0x64,0x8b,0x03
|
||||
48648b03
|
||||
SDM 2A 2.2.1; 1 3.4.1.1
|
||||
ignored_rex_w_before_segment_prefix_loads_32_bits: rax=ffffffffffffffff rbx=8 fs8=1122334455667788 => rax=44332211 f=*
|
||||
@ .byte 0x41,0x66,0x41,0x01,0xd8
|
||||
41664101d8
|
||||
SDM 2A 2.2.1
|
||||
rex_after_ignored_rex_applies: rax=7 rbx=1 r8=112233445566ffff => r8=1122334455660000 f=CPAZso
|
||||
@ .byte 0x66,0x48,0x01,0xd8
|
||||
664801d8
|
||||
SDM 2A 2.2.1.2
|
||||
@@ -1353,6 +1506,33 @@ mov_moffs8_store: rax=77 m0=00000000 => m0=00000077 f=*
|
||||
thirteen_byte_fs_add_imm32: rax=10 rbx=8 fs120=0000000000000000 => fs120=4433221100000000 f=cPazso
|
||||
";
|
||||
|
||||
/// Single-thread baseline for the fences (#199). Each engine completes every
|
||||
/// load and store of an instruction before the next instruction starts, so the
|
||||
/// cases only require that a fence changes nothing and that accesses on either
|
||||
/// side of it happen in program order. Nothing here involves a second thread.
|
||||
const FENCES: &str = r"
|
||||
@ mov [rdi], rax; mfence; mov rbx, [rdi]
|
||||
488907 0faef0 488b1f
|
||||
SDM 2B MFENCE
|
||||
mfence_store_is_visible_to_a_later_load: rdi=D rax=1122334455667788 m0=0000000000000000 => rbx=1122334455667788 m0=8877665544332211 f=*
|
||||
@ mov [rdi], rax; sfence; mov rbx, [rdi+8]
|
||||
488907 0faef8 488b5f08
|
||||
SDM 2B SFENCE
|
||||
sfence_after_a_store_keeps_other_memory: rdi=D rax=1 m0=0000000000000000 m8=aabbccddeeff0011 => rbx=1100ffeeddccbbaa m0=0100000000000000 f=*
|
||||
@ mov rbx, [rdi]; lfence; mov [rdi], rax
|
||||
488b1f 0faee8 488907
|
||||
SDM 2B LFENCE
|
||||
lfence_load_precedes_a_later_store: rdi=D rax=5 m0=0200000000000000 => rbx=2 m0=0500000000000000 f=*
|
||||
@ mfence; lfence; sfence
|
||||
0faef0 0faee8 0faef8
|
||||
SDM 2B MFENCE; 2B LFENCE; 2B SFENCE
|
||||
fences_change_no_register_or_flag: rax=1122334455667788 rbx=99aabbccddeeff00 => f=*
|
||||
@ .byte 0x0f,0xae,0xf5; .byte 0x0f,0xae,0xeb; .byte 0x0f,0xae,0xff
|
||||
0faef5 0faeeb 0faeff
|
||||
SDM 2B MFENCE; 2B LFENCE; 2B SFENCE (the r/m field is ignored)
|
||||
fences_ignore_the_rm_field: rax=1122334455667788 => f=*
|
||||
";
|
||||
|
||||
const MEMORY_FAULTS: &str = r"
|
||||
@ mov r8d, 1; add al, bl; mov rcx, [rsi]; mov r9d, 2
|
||||
41b801000000 00d8 !488b0e 41b902000000
|
||||
@@ -1493,7 +1673,7 @@ jump_to_unmapped_faults_at_target: rbx=U => rax=1 rip=U f=* ! PFX U
|
||||
jump_to_data_page_faults_at_target: rbx=D+40 => rip=D+40 f=* ! PFX D+40
|
||||
";
|
||||
|
||||
const DEFECT_STRADDLING_FAULT_ADDRESS: &str = r"
|
||||
const STRADDLING_FAULT_ADDRESS: &str = r"
|
||||
@ mov rcx, [rsi-4]
|
||||
!488b4efc
|
||||
SDM 3A 5.7 (the address with no translation); 3A 7.15 Interrupt 14
|
||||
@@ -1508,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"
|
||||
@@ -2596,12 +2836,15 @@ add_memory_crosses_contiguous_pages: rdi=D+1000 mffd=ffffffffffffffff => mffd=00
|
||||
push_pop_cross_contiguous_pages: rsp=D+1004 rax=1122334455667788 => rbx=1122334455667788 mffc=8877665544332211 f=*
|
||||
";
|
||||
|
||||
const DEFECT_EXACT_UNMASKED_OVERFLOW: &str = r"
|
||||
const EXACT_UNMASKED_OVERFLOW: &str = r"
|
||||
@ mulss xmm1, xmm2
|
||||
!f30f59ca
|
||||
SDM 1 D.4.2.3 Table D-16 (PE only if inexact); APM 1 4.10.2.8
|
||||
unmasked_overflow_exact_sets_only_oe: x1=s:7f7fffff x2=s:40000000 mx=1b80 => mx=1b88 f=* ! XM
|
||||
unmasked_negative_overflow_exact_sets_only_oe: x1=s:ff7fffff x2=s:40000000 mx=1b80 => mx=1b88 f=* ! XM
|
||||
unmasked_overflow_exact_sets_only_oe_down: x1=s:7f7fffff x2=s:40000000 mx=3b80 => mx=3b88 f=* ! XM
|
||||
unmasked_overflow_exact_sets_only_oe_up: x1=s:7f7fffff x2=s:40000000 mx=5b80 => mx=5b88 f=* ! XM
|
||||
unmasked_overflow_exact_sets_only_oe_zero: x1=s:7f7fffff x2=s:40000000 mx=7b80 => mx=7b88 f=* ! XM
|
||||
@ addsd xmm1, xmm2
|
||||
!f20f58ca
|
||||
SDM 1 D.4.2.3 Table D-16 (PE only if inexact); APM 1 4.10.2.8
|
||||
@@ -2631,12 +2874,10 @@ const GROUPS: &[(&str, &str)] = &[
|
||||
("strings", STRINGS),
|
||||
("fs_gs", FS_GS),
|
||||
("decoding", DECODING),
|
||||
("fences", FENCES),
|
||||
("memory_faults", MEMORY_FAULTS),
|
||||
(
|
||||
"defect_straddling_fault_address",
|
||||
DEFECT_STRADDLING_FAULT_ADDRESS,
|
||||
),
|
||||
("defect_noncanonical_address", DEFECT_NONCANONICAL_ADDRESS),
|
||||
("straddling_fault_address", STRADDLING_FAULT_ADDRESS),
|
||||
("noncanonical_address", NONCANONICAL_ADDRESS),
|
||||
("packed_integer_sse2", PACKED_INTEGER_SSE2),
|
||||
("packed_integer_beyond_sse2", PACKED_INTEGER_BEYOND_SSE2),
|
||||
("fp_rounding", FP_ROUNDING),
|
||||
@@ -2649,10 +2890,7 @@ const GROUPS: &[(&str, &str)] = &[
|
||||
("fp_mxcsr_and_unmasked", FP_MXCSR_AND_UNMASKED),
|
||||
("fp_beyond_sse2", FP_BEYOND_SSE2),
|
||||
("defect_overlong_instruction", DEFECT_OVERLONG_INSTRUCTION),
|
||||
(
|
||||
"defect_exact_unmasked_overflow",
|
||||
DEFECT_EXACT_UNMASKED_OVERFLOW,
|
||||
),
|
||||
("exact_unmasked_overflow", EXACT_UNMASKED_OVERFLOW),
|
||||
("page_crossing", PAGE_CROSSING),
|
||||
];
|
||||
|
||||
@@ -2666,31 +2904,21 @@ const UNSUPPORTED: &[(&str, usize)] = &[
|
||||
("bt_memory_register_offset_can_fault", 0),
|
||||
("btr16_memory_negative_16bit_offset", 0),
|
||||
("bts_memory_negative_offset", 0),
|
||||
("cmpsb_is_rsi_minus_rdi", 0),
|
||||
("cmpsb_is_rsi_minus_rdi", 1),
|
||||
("cmpxchg16b_equal", 0),
|
||||
("cmpxchg16b_equal_without_lock", 0),
|
||||
("cmpxchg16b_not_equal", 0),
|
||||
("cmpxchg16b_unaligned_is_gp", 0),
|
||||
("cmpxchg16b_unaligned_without_lock_is_gp", 0),
|
||||
("cmpxchg32_equal", 0),
|
||||
("cmpxchg64_memory_equal_without_lock", 0),
|
||||
("cmpxchg64_memory_not_equal", 0),
|
||||
("cmpxchg64_memory_not_equal_without_lock", 0),
|
||||
("cmpxchg8_not_equal_loads_al", 0),
|
||||
("cmpxchg8b_equal", 0),
|
||||
("cmpxchg8b_equal_without_lock", 0),
|
||||
("cmpxchg8b_not_equal", 0),
|
||||
("cmpxchg_mismatch_still_writes", 0),
|
||||
("crc32c_byte_and_qword_forms_agree", 0),
|
||||
("crc32c_check_string", 0),
|
||||
("dpps_mask", 0),
|
||||
("enter_leave_round_trip", 0),
|
||||
("fifteen_byte_instruction_executes", 0),
|
||||
("fs_addr32_truncates_before_adding_base", 0),
|
||||
("fs_rep_movsb_overrides_source_only", 0),
|
||||
("fs_rep_movsb_overrides_source_only_df_clear", 0),
|
||||
("gs_lock_xadd", 0),
|
||||
("gs_xadd_without_lock", 0),
|
||||
("haddps_hsubpd_addsubps", 0),
|
||||
("insertps_zero_mask", 0),
|
||||
("jecxz_tests_low_32_bits", 1),
|
||||
@@ -2699,17 +2927,15 @@ const UNSUPPORTED: &[(&str, usize)] = &[
|
||||
("lahf_zero", 0),
|
||||
("lea64_addr32_truncates_effective_address", 0),
|
||||
("lock_btc_memory", 0),
|
||||
("lodsd_zero_extends", 0),
|
||||
("lodsd_zero_extends", 1),
|
||||
("lodsd_zero_extends_df_clear", 0),
|
||||
("lodsw_preserves_upper48", 0),
|
||||
("lodsw_preserves_upper48", 1),
|
||||
("loop_decrements_rcx_without_flags", 1),
|
||||
("loopne_stops_on_zero_flag", 1),
|
||||
("maskmovdqu_selects_bytes", 0),
|
||||
("mov_moffs64_load", 0),
|
||||
("mov_moffs8_store", 0),
|
||||
("movddup_movsldup_movshdup", 0),
|
||||
("movdqa_movaps_aligned_store_and_load", 3),
|
||||
("movsb_forward", 0),
|
||||
("mpsadbw", 0),
|
||||
("pabs_min_is_unchanged", 0),
|
||||
("packusdw", 0),
|
||||
@@ -2731,67 +2957,24 @@ const UNSUPPORTED: &[(&str, usize)] = &[
|
||||
("ptest_flags", 0),
|
||||
("push16_moves_rsp_by_two", 0),
|
||||
("pushfq_popfq_status_round_trip", 0),
|
||||
("rcl16_by16", 0),
|
||||
("rcl16_by17_is_identity", 0),
|
||||
("rcl32_by31", 0),
|
||||
("rcl32_cl32_affects_nothing_but_extension", 0),
|
||||
("rcl64_by63", 0),
|
||||
("rcl8_by1_clear_carry_in", 0),
|
||||
("rcl8_by1_set_carry_in_preserves_szap", 0),
|
||||
("rcl8_by8", 0),
|
||||
("rcl8_by9_is_identity", 0),
|
||||
("rcpps_special_values", 0),
|
||||
("rcpss_relative_error_bound", 0),
|
||||
("rcpss_rsqrtss_signal_nothing", 0),
|
||||
("rcr64_by1", 0),
|
||||
("rcr8_by10_is_by_one_mod_9", 0),
|
||||
("rcr8_by1_clear_carry_in", 0),
|
||||
("rcr8_by1_set_carry_in", 0),
|
||||
("rep_lodsb_source_fault", 0),
|
||||
("rep_movs_zero_count_touches_nothing", 0),
|
||||
("rep_movsb_addr32_uses_32bit_registers", 0),
|
||||
("rep_movsb_fault_df_clear", 0),
|
||||
("rep_movsb_fault_stops_at_failing_iteration", 0),
|
||||
("rep_movsb_overlap_propagates_df_clear", 0),
|
||||
("rep_movsq_overlap_propagates", 0),
|
||||
("rep_movsq_zero_count_df_clear", 0),
|
||||
("rep_movsw_backward", 0),
|
||||
("rep_stosd_df_clear", 0),
|
||||
("rep_stosd_forward", 0),
|
||||
("rep_stosq_fault_df_clear", 0),
|
||||
("rep_stosq_fault_stops_at_failing_iteration", 0),
|
||||
("repe_cmpsb_fault_restores_flags", 0),
|
||||
("rep_lodsb_source_fault", 1),
|
||||
("rep_movsb_addr32_uses_32bit_registers", 1),
|
||||
("repe_cmpsb_fault_restores_flags", 1),
|
||||
("repe_cmpsb_fault_restores_flags_df_clear", 0),
|
||||
("repe_cmpsb_stops_at_difference", 0),
|
||||
("repe_cmpsb_stops_at_difference", 1),
|
||||
("repe_cmpsb_stops_at_difference_df_clear", 0),
|
||||
("repe_cmpsb_zero_count_keeps_flags", 0),
|
||||
("repne_scasb_finds_byte", 0),
|
||||
("repe_cmpsb_zero_count_keeps_flags", 1),
|
||||
("repne_scasb_finds_byte", 1),
|
||||
("repne_scasb_finds_byte_df_clear", 0),
|
||||
("repne_scasd_exhausts_count", 0),
|
||||
("rex_not_adjacent_to_opcode_is_ignored", 0),
|
||||
("repne_scasd_exhausts_count", 1),
|
||||
("roundps_uses_mxcsr_rc", 0),
|
||||
("roundsd_suppress_precision", 0),
|
||||
("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),
|
||||
("shr_rcr_128bit_right_shift", 1),
|
||||
("shrd32_by8", 0),
|
||||
("shrd64_by1_sign_change", 0),
|
||||
("shrd64_cl64_is_count_zero", 0),
|
||||
("xadd32_reg_reg", 0),
|
||||
("xadd64_memory", 0),
|
||||
("xadd64_memory_without_lock", 0),
|
||||
("xadd64_same_register_doubles", 0),
|
||||
("xadd8_al_ah", 0),
|
||||
("xadd_readonly_page_keeps_register", 0),
|
||||
("xchg_ax_r9w_preserves_both_uppers", 0),
|
||||
("xchg_eax_ebx_clears_both_uppers", 0),
|
||||
("xchg_rax_r8_is_not_nop", 0),
|
||||
];
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -3417,6 +3600,11 @@ fn exchange() {
|
||||
check_group(EXCHANGE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn immediate_stores() {
|
||||
check_group(IMMEDIATE_STORES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flag_moves() {
|
||||
check_group(FLAG_MOVES);
|
||||
@@ -3462,21 +3650,24 @@ fn decoding() {
|
||||
check_group(DECODING);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fences() {
|
||||
check_group(FENCES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memory_faults() {
|
||||
check_group(MEMORY_FAULTS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "known defect (#155): a page-crossing fault reports the start of the access"]
|
||||
fn defect_straddling_fault_address() {
|
||||
check_group(DEFECT_STRADDLING_FAULT_ADDRESS);
|
||||
fn straddling_fault_address() {
|
||||
check_group(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]
|
||||
@@ -3541,9 +3732,8 @@ fn defect_overlong_instruction() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "known defect (#155): an exact unmasked overflow sets PE as well as OE"]
|
||||
fn defect_exact_unmasked_overflow() {
|
||||
check_group(DEFECT_EXACT_UNMASKED_OVERFLOW);
|
||||
fn exact_unmasked_overflow() {
|
||||
check_group(EXACT_UNMASKED_OVERFLOW);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -3627,6 +3817,7 @@ fn dbt_route_of_every_case_is_recorded() {
|
||||
let memory = start.image.load(&case.code);
|
||||
let text: Vec<&str> = case.asm.split(';').map(str::trim).collect();
|
||||
let mut routes = Vec::new();
|
||||
let mut repeats = false;
|
||||
for (index, &offset) in case.offsets.iter().enumerate() {
|
||||
let Ok(insn) = decode(CODE + offset as u64, |at| memory.fetch_instruction_byte(at))
|
||||
else {
|
||||
@@ -3634,6 +3825,7 @@ fn dbt_route_of_every_case_is_recorded() {
|
||||
};
|
||||
let name = text.get(index).copied().unwrap_or(case.asm);
|
||||
routes.push(is_native(&insn));
|
||||
repeats |= insn.rep;
|
||||
if is_native(&insn) {
|
||||
native.insert(name);
|
||||
} else {
|
||||
@@ -3648,13 +3840,13 @@ fn dbt_route_of_every_case_is_recorded() {
|
||||
};
|
||||
counts.entry(group).or_default()[kind] += 1;
|
||||
// Straight-line cases run each instruction once, so the counter must equal
|
||||
// the number of helper instructions.
|
||||
// the number of helper instructions. A REP form runs once per element.
|
||||
let labelled = text.iter().any(|piece| {
|
||||
piece
|
||||
.split_once(':')
|
||||
.is_some_and(|(label, _)| label.parse::<u8>().is_ok())
|
||||
});
|
||||
if !labelled && case.fault.is_empty() && routes.len() == case.offsets.len() {
|
||||
if !labelled && !repeats && case.fault.is_empty() && routes.len() == case.offsets.len() {
|
||||
let mut dbt = new_dbt();
|
||||
let mut memory = memory.clone();
|
||||
run_dbt(&mut dbt, &start.cpu, &mut memory, BUDGET);
|
||||
@@ -4070,11 +4262,7 @@ fn shift_and_rotate_sweep_matches_operation_pseudocode() {
|
||||
runs += bench.runs;
|
||||
}
|
||||
}
|
||||
let wanted: Vec<String> = ["rcl", "rcr"]
|
||||
.iter()
|
||||
.flat_map(|op| WIDTHS.map(|bits| format!("{op}{bits}")))
|
||||
.collect();
|
||||
assert_eq!(refused, wanted, "unsupported shift forms changed");
|
||||
assert_eq!(refused, Vec::<String>::new(), "a shift form is refused");
|
||||
println!("{runs} engine runs");
|
||||
}
|
||||
|
||||
@@ -4764,12 +4952,7 @@ fn deliver(
|
||||
}
|
||||
if lowest + precision - 1 > format.max_exponent() {
|
||||
if mxcsr & OM == 0 {
|
||||
// PE of an exact overflow is `defect_exact_unmasked_overflow`; this
|
||||
// sweep compares every other bit.
|
||||
return Outcome {
|
||||
open: if unbounded_exact { PE } else { 0 },
|
||||
..outcome(0, OE | unbounded_inexact)
|
||||
};
|
||||
return outcome(0, OE | unbounded_inexact);
|
||||
}
|
||||
let to_infinity = match mode {
|
||||
0 => true,
|
||||
|
||||
@@ -0,0 +1,500 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! MOVS, STOS, REP and the direction flag (issue #129).
|
||||
//!
|
||||
//! Expected results come from a byte-array model written from the operation
|
||||
//! sections of the Intel SDM Vol. 2 for MOVS, STOS, REP, CLD and STD. The
|
||||
//! model never decodes or calls the production semantics. Encodings were
|
||||
//! assembled with `clang -target x86_64-apple-macos` and read with `objdump`.
|
||||
//! Nothing was compared with x86 hardware.
|
||||
//!
|
||||
//! A REP form runs one element per step and stays on the instruction until RCX
|
||||
//! is zero. The tests check that rule through the step counts, so a repeat can
|
||||
//! never outrun the step budget.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use xenora_loader::cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, RFlags};
|
||||
use xenora_loader::dbt::{DbtEngine, is_native};
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
use xenora_loader::x86_decode::decode;
|
||||
use xenora_loader::x86_table::{FORMS, Op};
|
||||
|
||||
const ENTRY: u64 = 0x1000;
|
||||
/// One writable page with nothing mapped on either side.
|
||||
const DATA: u64 = 0x8000;
|
||||
const PAGE: usize = 0x1000;
|
||||
const END: u64 = DATA + PAGE as u64;
|
||||
|
||||
const RAX: usize = 0;
|
||||
const RCX: usize = 1;
|
||||
const RSI: usize = 6;
|
||||
const RDI: usize = 7;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
enum Kind {
|
||||
Movs,
|
||||
Stos,
|
||||
}
|
||||
|
||||
/// `[rep] movs/stos` for an element of `size` bytes, in the assembler's order.
|
||||
fn encode(kind: Kind, size: u64, rep: bool) -> Vec<u8> {
|
||||
let mut code = Vec::new();
|
||||
if rep {
|
||||
code.push(0xF3);
|
||||
}
|
||||
match size {
|
||||
2 => code.push(0x66),
|
||||
8 => code.push(0x48),
|
||||
_ => {}
|
||||
}
|
||||
code.push(match (kind, size) {
|
||||
(Kind::Movs, 1) => 0xA4,
|
||||
(Kind::Movs, _) => 0xA5,
|
||||
(Kind::Stos, 1) => 0xAA,
|
||||
(Kind::Stos, _) => 0xAB,
|
||||
});
|
||||
code
|
||||
}
|
||||
|
||||
fn image(code: &[u8], data: &[u8]) -> GuestMemory {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, code)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region_with_data(DATA, PAGE, MemoryPermissions::READ_WRITE, data)
|
||||
.unwrap();
|
||||
memory
|
||||
}
|
||||
|
||||
fn bytes(memory: &GuestMemory) -> Vec<u8> {
|
||||
let mut out = vec![0; PAGE];
|
||||
memory.read_bytes(DATA, &mut out).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
struct Run {
|
||||
name: &'static str,
|
||||
result: ExecutionResult,
|
||||
memory: GuestMemory,
|
||||
/// Instructions the DBT ran on the shared semantics.
|
||||
helpers: usize,
|
||||
}
|
||||
|
||||
/// The interpreter and the DBT, each from its own copy of the state.
|
||||
fn both(cpu: &CpuState, memory: &GuestMemory, budget: usize) -> [Run; 2] {
|
||||
let mut interpreted = memory.clone();
|
||||
let result = Interpreter::new(cpu.clone(), &mut interpreted, budget).run();
|
||||
let mut translated = memory.clone();
|
||||
let mut engine = DbtEngine::new(64 * 1024).unwrap();
|
||||
let mut state = cpu.clone();
|
||||
let native = engine.run(&mut state, &mut translated, budget);
|
||||
[
|
||||
Run {
|
||||
name: "interpreter",
|
||||
result,
|
||||
memory: interpreted,
|
||||
helpers: 0,
|
||||
},
|
||||
Run {
|
||||
name: "DBT",
|
||||
result: native,
|
||||
memory: translated,
|
||||
helpers: engine.metrics.interpreter_fallbacks,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
/// Deterministic generator (xorshift64*).
|
||||
struct Random(u64);
|
||||
|
||||
impl Random {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 >> 12;
|
||||
self.0 ^= self.0 << 25;
|
||||
self.0 ^= self.0 >> 27;
|
||||
self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
|
||||
}
|
||||
}
|
||||
|
||||
/// The architectural effect of `count` elements on a byte array: each element
|
||||
/// is read whole, then written, then the pointers move by its size.
|
||||
fn model(
|
||||
kind: Kind,
|
||||
size: u64,
|
||||
backward: bool,
|
||||
count: u64,
|
||||
data: &mut [u8],
|
||||
rax: u64,
|
||||
(mut rsi, mut rdi): (u64, u64),
|
||||
) -> (u64, u64) {
|
||||
let size_bytes = size as usize;
|
||||
for _ in 0..count {
|
||||
let element: Vec<u8> = match kind {
|
||||
Kind::Movs => {
|
||||
let from = (rsi - DATA) as usize;
|
||||
data[from..from + size_bytes].to_vec()
|
||||
}
|
||||
Kind::Stos => rax.to_le_bytes()[..size_bytes].to_vec(),
|
||||
};
|
||||
let to = (rdi - DATA) as usize;
|
||||
data[to..to + size_bytes].copy_from_slice(&element);
|
||||
if kind == Kind::Movs {
|
||||
rsi = if backward { rsi - size } else { rsi + size };
|
||||
}
|
||||
rdi = if backward { rdi - size } else { rdi + size };
|
||||
}
|
||||
(rsi, rdi)
|
||||
}
|
||||
|
||||
const FLAGS: RFlags = RFlags {
|
||||
cf: true,
|
||||
zf: false,
|
||||
sf: true,
|
||||
of: false,
|
||||
pf: true,
|
||||
af: false,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn every_form_matches_a_byte_array_model_and_counts_one_step_per_element() {
|
||||
let mut random = Random(0x1234_5678_9ABC_DEF1);
|
||||
for kind in [Kind::Movs, Kind::Stos] {
|
||||
for size in [1, 2, 4, 8] {
|
||||
for rep in [false, true] {
|
||||
for backward in [false, true] {
|
||||
for round in 0..40 {
|
||||
// Counts 0 to 9. Source and destination start within 24
|
||||
// bytes of each other, so the ranges often overlap.
|
||||
let count = round % 10;
|
||||
let rsi = DATA + 0x400 + random.next() % 0x100;
|
||||
let rdi = rsi + random.next() % 49 - 24;
|
||||
let rax = random.next();
|
||||
let data: Vec<u8> = (0..PAGE).map(|_| random.next() as u8).collect();
|
||||
|
||||
let mut code = encode(kind, size, rep);
|
||||
code.push(0xF4); // hlt
|
||||
let memory = image(&code, &data);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
for register in &mut cpu.gpr {
|
||||
*register = random.next();
|
||||
}
|
||||
cpu.gpr[RAX] = rax;
|
||||
cpu.gpr[RCX] = count;
|
||||
cpu.gpr[RSI] = rsi;
|
||||
cpu.gpr[RDI] = rdi;
|
||||
cpu.df = backward;
|
||||
cpu.flags = FLAGS;
|
||||
|
||||
// Without REP exactly one element moves and RCX is not
|
||||
// read or written.
|
||||
let elements = if rep { count } else { 1 };
|
||||
let mut wanted_data = data.clone();
|
||||
let (wanted_rsi, wanted_rdi) = model(
|
||||
kind,
|
||||
size,
|
||||
backward,
|
||||
elements,
|
||||
&mut wanted_data,
|
||||
rax,
|
||||
(rsi, rdi),
|
||||
);
|
||||
let mut wanted = cpu.clone();
|
||||
wanted.rip = ENTRY + code.len() as u64;
|
||||
wanted.gpr[RSI] = wanted_rsi;
|
||||
wanted.gpr[RDI] = wanted_rdi;
|
||||
if rep {
|
||||
wanted.gpr[RCX] = 0;
|
||||
}
|
||||
// One step per element, one for a REP with a zero
|
||||
// count, and one for the HLT.
|
||||
let steps = elements.max(1) as usize + 1;
|
||||
|
||||
for run in both(&cpu, &memory, 64) {
|
||||
let what = format!(
|
||||
"{kind:?} size {size} rep={rep} backward={backward} count={count} \
|
||||
on the {}",
|
||||
run.name
|
||||
);
|
||||
assert_eq!(run.result.exit_reason, ExitReason::Halt, "{what}");
|
||||
assert_eq!(run.result.final_state, wanted, "{what}");
|
||||
assert!(bytes(&run.memory) == wanted_data, "{what}: memory");
|
||||
assert_eq!(run.result.instructions_executed, steps, "{what}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn step_budget_stops_a_repeat_part_way_and_it_resumes() {
|
||||
// rep stosb; hlt
|
||||
let code = [0xF3, 0xAA, 0xF4];
|
||||
let memory = image(&code, &[0; PAGE]);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RAX] = 0x5A;
|
||||
cpu.gpr[RCX] = 100;
|
||||
cpu.gpr[RDI] = DATA + 0x200;
|
||||
for run in both(&cpu, &memory, 10) {
|
||||
// Ten steps store ten bytes and leave RIP on the instruction.
|
||||
assert_eq!(
|
||||
run.result.exit_reason,
|
||||
ExitReason::StepLimitExceeded,
|
||||
"{}",
|
||||
run.name
|
||||
);
|
||||
assert_eq!(run.result.instructions_executed, 10, "{}", run.name);
|
||||
let state = &run.result.final_state;
|
||||
assert_eq!(
|
||||
(state.rip, state.gpr[RCX], state.gpr[RDI]),
|
||||
(ENTRY, 90, DATA + 0x20A),
|
||||
"{}",
|
||||
run.name
|
||||
);
|
||||
let written = bytes(&run.memory);
|
||||
assert_eq!(written[0x200..0x20A], [0x5A; 10], "{}", run.name);
|
||||
assert_eq!(written[0x20A..0x264], [0; 90], "{}", run.name);
|
||||
if run.name == "DBT" {
|
||||
assert_eq!(run.helpers, 10);
|
||||
}
|
||||
|
||||
// Resuming from that state finishes the remaining ninety and halts.
|
||||
let [rest, _] = both(state, &run.memory, 1000);
|
||||
assert_eq!(rest.result.exit_reason, ExitReason::Halt, "{}", run.name);
|
||||
assert_eq!(rest.result.instructions_executed, 91, "{}", run.name);
|
||||
assert_eq!(rest.result.final_state.gpr[RCX], 0, "{}", run.name);
|
||||
assert_eq!(
|
||||
bytes(&rest.memory)[0x200..0x264],
|
||||
[0x5A; 100],
|
||||
"{}",
|
||||
run.name
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_count_is_all_of_rcx() {
|
||||
// rep stosb with a count above 32 bits: two steps take exactly two off it.
|
||||
let memory = image(&[0xF3, 0xAA, 0xF4], &[0; PAGE]);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RCX] = 0x0000_0001_0000_0001;
|
||||
cpu.gpr[RDI] = DATA;
|
||||
for run in both(&cpu, &memory, 2) {
|
||||
assert_eq!(
|
||||
run.result.exit_reason,
|
||||
ExitReason::StepLimitExceeded,
|
||||
"{}",
|
||||
run.name
|
||||
);
|
||||
assert_eq!(
|
||||
run.result.final_state.gpr[RCX], 0x0000_0000_FFFF_FFFF,
|
||||
"{}",
|
||||
run.name
|
||||
);
|
||||
assert_eq!(run.result.final_state.rip, ENTRY, "{}", run.name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fault_keeps_the_elements_already_done() {
|
||||
// (code, RSI, RDI, backward, elements that complete before the fault)
|
||||
let cases: &[(&[u8], u64, u64, bool, u64)] = &[
|
||||
// rep movsq up to the end of the page: 19 bytes hold two elements, and
|
||||
// the third would end past the page.
|
||||
(&[0xF3, 0x48, 0xA5], DATA, END - 19, false, 2),
|
||||
// rep stosd down to the start of the page: elements at offsets 5 and 1
|
||||
// fit, the next would start before the page.
|
||||
(&[0xF3, 0xAB], 0, DATA + 5, true, 2),
|
||||
// rep movsw from a source that ends: three elements can be read.
|
||||
(&[0xF3, 0x66, 0xA5], END - 6, DATA + 0x100, false, 3),
|
||||
// rep movsb with no readable source at all.
|
||||
(&[0xF3, 0xA4], END, DATA + 0x100, false, 0),
|
||||
];
|
||||
let mut random = Random(77);
|
||||
for &(code, rsi, rdi, backward, done) in cases {
|
||||
let data: Vec<u8> = (0..PAGE).map(|_| random.next() as u8).collect();
|
||||
let memory = image(code, &data);
|
||||
let insn = decode(ENTRY, |at| {
|
||||
code.get((at - ENTRY) as usize).copied().ok_or(())
|
||||
})
|
||||
.unwrap();
|
||||
let (kind, size) = (
|
||||
if insn.op == Op::Movs {
|
||||
Kind::Movs
|
||||
} else {
|
||||
Kind::Stos
|
||||
},
|
||||
u64::from(insn.size),
|
||||
);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RAX] = 0x1122_3344_5566_7788;
|
||||
cpu.gpr[RCX] = 9;
|
||||
cpu.gpr[RSI] = rsi;
|
||||
cpu.gpr[RDI] = rdi;
|
||||
cpu.df = backward;
|
||||
cpu.flags = FLAGS;
|
||||
|
||||
// The completed elements took effect. The faulting one changed
|
||||
// nothing, and RIP stays on the instruction so it can be restarted.
|
||||
let mut wanted_data = data.clone();
|
||||
let (wanted_rsi, wanted_rdi) = model(
|
||||
kind,
|
||||
size,
|
||||
backward,
|
||||
done,
|
||||
&mut wanted_data,
|
||||
cpu.gpr[RAX],
|
||||
(rsi, rdi),
|
||||
);
|
||||
let mut wanted = cpu.clone();
|
||||
wanted.gpr[RCX] = 9 - done;
|
||||
wanted.gpr[RSI] = wanted_rsi;
|
||||
wanted.gpr[RDI] = wanted_rdi;
|
||||
|
||||
for run in both(&cpu, &memory, 64) {
|
||||
let what = format!("{code:02X?} on the {}", run.name);
|
||||
assert!(
|
||||
matches!(run.result.exit_reason, ExitReason::MemoryFault(_)),
|
||||
"{what}: {:?}",
|
||||
run.result.exit_reason
|
||||
);
|
||||
assert_eq!(run.result.final_state, wanted, "{what}");
|
||||
assert!(bytes(&run.memory) == wanted_data, "{what}: memory");
|
||||
assert_eq!(run.result.instructions_executed, done as usize, "{what}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direction_flag_is_set_by_std_and_cleared_by_cld() {
|
||||
// std; stosb; cld; stosb; hlt
|
||||
let code = [0xFD, 0xAA, 0xFC, 0xAA, 0xF4];
|
||||
let memory = image(&code, &[0; PAGE]);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RAX] = 0xC3;
|
||||
cpu.gpr[RDI] = DATA + 0x80;
|
||||
cpu.flags = FLAGS;
|
||||
for run in both(&cpu, &memory, 16) {
|
||||
assert_eq!(run.result.exit_reason, ExitReason::Halt, "{}", run.name);
|
||||
// The first store steps down to 0x7F, the second back up to 0x80.
|
||||
assert_eq!(run.result.final_state.gpr[RDI], DATA + 0x80, "{}", run.name);
|
||||
let written = bytes(&run.memory);
|
||||
assert_eq!(written[0x7F..0x81], [0xC3, 0xC3], "{}", run.name);
|
||||
assert!(!run.result.final_state.df, "{}", run.name);
|
||||
// Neither instruction touches a status flag.
|
||||
assert_eq!(run.result.final_state.flags, FLAGS, "{}", run.name);
|
||||
}
|
||||
// The flag outlives the run that set it.
|
||||
for run in both(&cpu, &image(&[0xFD, 0xF4], &[0; PAGE]), 4) {
|
||||
assert!(run.result.final_state.df, "{}", run.name);
|
||||
assert_eq!(run.result.final_state.flags, FLAGS, "{}", run.name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_segment_override_moves_the_source_only() {
|
||||
const BASE: u64 = 0x300;
|
||||
let mut data = vec![0u8; PAGE];
|
||||
data[0x10] = 0x11; // DATA + 0x10, what [RSI] names without a base
|
||||
data[0x310] = 0x22; // DATA + 0x10 + BASE, the same RSI under the FS or GS base
|
||||
for (code, uses_base) in [
|
||||
(&[0xA4][..], false), // movsb
|
||||
(&[0x64, 0xA4][..], true), // movsb with the source under FS
|
||||
(&[0x65, 0xA4][..], true), // movsb with the source under GS
|
||||
] {
|
||||
let memory = image(code, &data);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.fs_base = BASE;
|
||||
cpu.gs_base = BASE;
|
||||
cpu.gpr[RSI] = DATA + 0x10;
|
||||
cpu.gpr[RDI] = DATA + 0x800;
|
||||
for run in both(&cpu, &memory, 1) {
|
||||
let what = format!("{code:02X?} on the {}", run.name);
|
||||
// The destination is [RDI] with no base either way.
|
||||
let wanted = if uses_base { 0x22 } else { 0x11 };
|
||||
assert_eq!(bytes(&run.memory)[0x800], wanted, "{what}");
|
||||
assert_eq!(
|
||||
run.result.final_state.gpr[RSI],
|
||||
DATA + 0x11,
|
||||
"{what}: RSI moves by the element, not by the base"
|
||||
);
|
||||
}
|
||||
}
|
||||
// STOS has no source, and its destination takes no override.
|
||||
let memory = image(&[0x64, 0xAA], &data);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.fs_base = BASE;
|
||||
cpu.gpr[RAX] = 0x77;
|
||||
cpu.gpr[RDI] = DATA + 0x800;
|
||||
for run in both(&cpu, &memory, 1) {
|
||||
let written = bytes(&run.memory);
|
||||
assert_eq!((written[0x800], written[0xB00]), (0x77, 0), "{}", run.name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exactly_the_declared_string_forms_decode() {
|
||||
let decode_bytes = |code: &[u8]| {
|
||||
decode(ENTRY, |at| {
|
||||
code.get((at - ENTRY) as usize).copied().ok_or(())
|
||||
})
|
||||
};
|
||||
let mut seen = BTreeSet::new();
|
||||
for kind in [Kind::Movs, Kind::Stos] {
|
||||
for size in [1, 2, 4, 8] {
|
||||
for rep in [false, true] {
|
||||
let code = encode(kind, size, rep);
|
||||
let insn =
|
||||
decode_bytes(&code).unwrap_or_else(|error| panic!("{code:02X?}: {error:?}"));
|
||||
assert_eq!(usize::from(insn.len), code.len(), "{code:02X?}");
|
||||
assert_eq!((u64::from(insn.size), insn.rep), (size, rep), "{code:02X?}");
|
||||
assert!(!is_native(&insn), "{code:02X?}");
|
||||
seen.insert(usize::from(insn.form));
|
||||
}
|
||||
}
|
||||
}
|
||||
for code in [[0xFC], [0xFD]] {
|
||||
seen.insert(usize::from(decode_bytes(&code).unwrap().form));
|
||||
}
|
||||
// Every declared form of these operations was reached above.
|
||||
for (index, form) in FORMS.iter().enumerate() {
|
||||
if matches!(form.op, Op::Movs | Op::Stos | Op::Cld | Op::Std) {
|
||||
assert!(seen.contains(&index), "{:?} {:?}", form.op, form.size);
|
||||
}
|
||||
}
|
||||
|
||||
let rejected: &[&[u8]] = &[
|
||||
&[0xF2, 0xA4], // repne movsb
|
||||
&[0xF2, 0xAB], // repne stosd
|
||||
&[0xF3, 0xF2, 0xA4], // both repeat prefixes
|
||||
&[0x67, 0xF3, 0xA4], // rep movsb with 32-bit addresses
|
||||
&[0xF0, 0xF3, 0xAA], // lock rep stosb
|
||||
&[0xF3, 0xFC], // rep cld
|
||||
&[0xA6], // cmpsb
|
||||
&[0xF3, 0xA6], // repe cmpsb
|
||||
&[0xAC], // lodsb
|
||||
&[0xAE], // scasb
|
||||
&[0xF2, 0xAE], // repne scasb
|
||||
];
|
||||
for code in rejected {
|
||||
let mut padded = code.to_vec();
|
||||
padded.extend([0x90; 8]);
|
||||
let memory = image(&padded, &[0; PAGE]);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RCX] = 3;
|
||||
cpu.gpr[RSI] = DATA;
|
||||
cpu.gpr[RDI] = DATA + 0x100;
|
||||
for run in both(&cpu, &memory, 1) {
|
||||
assert!(
|
||||
matches!(run.result.exit_reason, ExitReason::IllegalInstruction(_)),
|
||||
"{code:02X?} on the {}: {:?}",
|
||||
run.name,
|
||||
run.result.exit_reason
|
||||
);
|
||||
assert_eq!(run.result.final_state, cpu, "{code:02X?}");
|
||||
assert!(bytes(&run.memory) == vec![0; PAGE], "{code:02X?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -96,10 +96,11 @@ fn crt_handlers_validate_memory_boundaries() {
|
||||
0x1008
|
||||
)))
|
||||
);
|
||||
// The destination 0x1005..0x1009 is mapped up to 0x1008.
|
||||
assert_eq!(
|
||||
call("memmove", 0x1005, 0x1000, 4, &mut memory),
|
||||
Err(ExitReason::MemoryFault(MemoryError::UnmappedAddress(
|
||||
0x1005
|
||||
0x1008
|
||||
)))
|
||||
);
|
||||
let mut bytes = [0; 8];
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,274 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Guest 4 KiB page boundaries on a host with larger pages (#175).
|
||||
//!
|
||||
//! Apple Silicon uses 16 KiB host pages, so four guest pages share one host
|
||||
//! page and host page protection cannot separate them. Guest memory is checked
|
||||
//! in software, byte by byte, and is never mapped with host protections. These
|
||||
//! tests lay 4 KiB guest pages across two spans of the detected host page size
|
||||
//! and require the same results at every guest page boundary, whether or not it
|
||||
//! is also a host page boundary.
|
||||
//!
|
||||
//! The expected fault address is the first byte, in address order, that the
|
||||
//! access may not touch: the linear address with no translation or without the
|
||||
//! needed right. This is the reading of the Intel SDM used by the page-fault
|
||||
//! cases in `cpu_known_answers.rs` (Volume 3A, Sections 5.7 and 7.15, Interrupt
|
||||
//! 14). Every expectation below is a literal address or a table written from
|
||||
//! that rule, not a value read back from the memory model. Nothing here was
|
||||
//! compared with x86 hardware.
|
||||
|
||||
use xenora_loader::services::sysinfo::HostCapabilities;
|
||||
use xenora_loader::{GuestMemory, MemoryError, MemoryPermissions as P};
|
||||
|
||||
const GUEST_PAGE: u64 = 0x1000;
|
||||
/// Aligned to every host page size up to 1 GiB.
|
||||
const BASE: u64 = 0x4000_0000;
|
||||
|
||||
fn host_page() -> u64 {
|
||||
let size = HostCapabilities::detect()
|
||||
.page_size
|
||||
.expect("the host reports a page size");
|
||||
assert_eq!(size % GUEST_PAGE, 0, "host page size {size:#x}");
|
||||
size
|
||||
}
|
||||
|
||||
/// Guest page boundaries strictly inside two host pages starting at `BASE`.
|
||||
/// On a 16 KiB host that is seven boundaries, one of them a host page boundary.
|
||||
fn boundaries() -> Vec<u64> {
|
||||
let pages = 2 * host_page() / GUEST_PAGE;
|
||||
(1..pages).map(|page| BASE + page * GUEST_PAGE).collect()
|
||||
}
|
||||
|
||||
fn unmapped(address: u64) -> MemoryError {
|
||||
MemoryError::UnmappedAddress(address)
|
||||
}
|
||||
|
||||
fn violation(address: u64, required: &'static str) -> MemoryError {
|
||||
MemoryError::PermissionViolation { address, required }
|
||||
}
|
||||
|
||||
/// The page below `boundary`, filled with 0x5a, and optionally the page above
|
||||
/// it, filled with 0xa5.
|
||||
fn pages_around(boundary: u64, below: P, above: Option<P>) -> GuestMemory {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(boundary - GUEST_PAGE, 0x1000, below, &[0x5a; 0x1000])
|
||||
.unwrap();
|
||||
if let Some(above) = above {
|
||||
memory
|
||||
.map_region_with_data(boundary, 0x1000, above, &[0xa5; 0x1000])
|
||||
.unwrap();
|
||||
}
|
||||
memory
|
||||
}
|
||||
|
||||
/// The 16 bytes centred on `boundary`, read without permission checks.
|
||||
fn bytes_around(memory: &GuestMemory, boundary: u64) -> (u64, u64) {
|
||||
(
|
||||
memory.read_u64_bypass(boundary - 8).unwrap(),
|
||||
memory.read_u64_bypass(boundary).unwrap(),
|
||||
)
|
||||
}
|
||||
|
||||
const BELOW: u64 = 0x5a5a_5a5a_5a5a_5a5a;
|
||||
const ABOVE: u64 = 0xa5a5_a5a5_a5a5_a5a5;
|
||||
|
||||
#[test]
|
||||
fn apple_silicon_host_pages_hold_four_guest_pages() {
|
||||
let size = host_page();
|
||||
if cfg!(all(target_os = "macos", target_arch = "aarch64")) {
|
||||
assert_eq!(size, 0x4000);
|
||||
assert_eq!(boundaries().len(), 7);
|
||||
assert!(boundaries().contains(&(BASE + 0x4000)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_guest_page_in_a_host_page_keeps_its_own_permissions() {
|
||||
// (permissions, read allowed, write allowed, execute allowed)
|
||||
let kinds = [
|
||||
(P::READ_WRITE, true, true, false),
|
||||
(P::READ_ONLY, true, false, false),
|
||||
(P::NO_ACCESS, false, false, false),
|
||||
(P::READ_EXECUTE, true, false, true),
|
||||
];
|
||||
let pages = 2 * host_page() / GUEST_PAGE;
|
||||
let mut memory = GuestMemory::new();
|
||||
for page in 0..pages {
|
||||
let fill = [page as u8 + 1; 0x1000];
|
||||
let kind = kinds[page as usize % kinds.len()].0;
|
||||
memory
|
||||
.map_region_with_data(BASE + page * GUEST_PAGE, 0x1000, kind, &fill)
|
||||
.unwrap();
|
||||
}
|
||||
for page in 0..pages {
|
||||
let (_, read, write, execute) = kinds[page as usize % kinds.len()];
|
||||
let fill = page as u8 + 1;
|
||||
let first = BASE + page * GUEST_PAGE;
|
||||
for address in [first, first + 0xFFF] {
|
||||
let expected = |allowed, required| {
|
||||
if allowed {
|
||||
Ok(fill)
|
||||
} else {
|
||||
Err(violation(address, required))
|
||||
}
|
||||
};
|
||||
assert_eq!(memory.read_u8(address), expected(read, "read"));
|
||||
assert_eq!(
|
||||
memory.fetch_instruction_byte(address),
|
||||
expected(execute, "execute")
|
||||
);
|
||||
assert_eq!(
|
||||
memory.write_u8(address, fill),
|
||||
expected(write, "write").map(|_| ())
|
||||
);
|
||||
}
|
||||
}
|
||||
assert_eq!(memory.read_u8(BASE - 1), Err(unmapped(BASE - 1)));
|
||||
let end = BASE + pages * GUEST_PAGE;
|
||||
assert_eq!(memory.read_u8(end), Err(unmapped(end)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn access_across_adjacent_guest_pages_lands_in_both() {
|
||||
for boundary in boundaries() {
|
||||
let mut memory = pages_around(boundary, P::READ_WRITE, Some(P::READ_WRITE));
|
||||
memory
|
||||
.write_u64(boundary - 3, 0x8877_6655_4433_2211)
|
||||
.unwrap();
|
||||
assert_eq!(memory.read_u64(boundary - 3), Ok(0x8877_6655_4433_2211));
|
||||
// Little endian: three bytes below the boundary, five above it.
|
||||
assert_eq!(
|
||||
bytes_around(&memory, boundary),
|
||||
(0x3322_115a_5a5a_5a5a, 0xa5a5_a588_7766_5544),
|
||||
"boundary {boundary:#x}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crossing_into_an_unmapped_page_faults_at_its_first_byte() {
|
||||
for boundary in boundaries() {
|
||||
let mut memory = pages_around(boundary, P::READ_WRITE, None);
|
||||
let fault = Err(unmapped(boundary));
|
||||
for back in 1..8u64 {
|
||||
let start = boundary - back;
|
||||
let context = format!("boundary {boundary:#x}, start -{back}");
|
||||
assert_eq!(memory.read_u64(start).map(|_| ()), fault, "{context}");
|
||||
assert_eq!(memory.write_u64(start, 0), fault, "{context}");
|
||||
assert_eq!(memory.write_u64_bypass(start, 0), fault, "{context}");
|
||||
assert_eq!(memory.read_u64_bypass(start).map(|_| ()), fault);
|
||||
}
|
||||
for (back, width) in [(1u64, 2usize), (3, 4), (15, 16), (1, 0x1001)] {
|
||||
let mut buffer = vec![0u8; width];
|
||||
assert_eq!(memory.read_bytes(boundary - back, &mut buffer), fault);
|
||||
assert_eq!(memory.write_bytes(boundary - back, &buffer), fault);
|
||||
}
|
||||
// The failed stores wrote nothing below the boundary, and the last
|
||||
// access that fits still succeeds.
|
||||
assert_eq!(memory.read_u64(boundary - 8), Ok(BELOW));
|
||||
// An access that does not touch the mapped page faults at its own
|
||||
// first byte.
|
||||
assert_eq!(memory.read_u64(boundary).map(|_| ()), fault);
|
||||
assert_eq!(
|
||||
memory.read_u64(boundary + 5).map(|_| ()),
|
||||
Err(unmapped(boundary + 5))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn starting_in_an_unmapped_page_faults_at_the_access_start() {
|
||||
for boundary in boundaries() {
|
||||
// Only the page above the boundary exists.
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(boundary, 0x1000, P::READ_WRITE, &[0xa5; 0x1000])
|
||||
.unwrap();
|
||||
for back in 1..8u64 {
|
||||
let start = boundary - back;
|
||||
assert_eq!(memory.read_u64(start).map(|_| ()), Err(unmapped(start)));
|
||||
assert_eq!(memory.write_u64(start, 0), Err(unmapped(start)));
|
||||
}
|
||||
assert_eq!(memory.read_u64(boundary), Ok(ABOVE));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crossing_into_a_page_without_the_right_faults_at_its_first_byte() {
|
||||
for boundary in boundaries() {
|
||||
// A store into a read-only page.
|
||||
let mut memory = pages_around(boundary, P::READ_WRITE, Some(P::READ_ONLY));
|
||||
for back in 1..8u64 {
|
||||
assert_eq!(
|
||||
memory.write_u64(boundary - back, 0),
|
||||
Err(violation(boundary, "write")),
|
||||
"boundary {boundary:#x}, start -{back}"
|
||||
);
|
||||
assert!(memory.read_u64(boundary - back).is_ok());
|
||||
}
|
||||
assert_eq!(bytes_around(&memory, boundary), (BELOW, ABOVE));
|
||||
|
||||
// A load from a page with no access.
|
||||
let memory = pages_around(boundary, P::READ_ONLY, Some(P::NO_ACCESS));
|
||||
for back in 1..8u64 {
|
||||
assert_eq!(
|
||||
memory.read_u64(boundary - back).map(|_| ()),
|
||||
Err(violation(boundary, "read")),
|
||||
"boundary {boundary:#x}, start -{back}"
|
||||
);
|
||||
}
|
||||
assert_eq!(memory.read_u64(boundary - 8), Ok(BELOW));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_lowest_failing_byte_decides_the_fault() {
|
||||
for boundary in boundaries() {
|
||||
// Forbidden first page, unmapped second page: the first byte fails.
|
||||
let mut memory = pages_around(boundary, P::READ_ONLY, None);
|
||||
assert_eq!(
|
||||
memory.write_u64(boundary - 4, 0),
|
||||
Err(violation(boundary - 4, "write"))
|
||||
);
|
||||
assert_eq!(
|
||||
memory.read_u64(boundary - 4).map(|_| ()),
|
||||
Err(unmapped(boundary))
|
||||
);
|
||||
|
||||
// Writable, then read-only, then unmapped: a store over all three
|
||||
// stops at the read-only page, a load at the unmapped one.
|
||||
let mut memory = pages_around(boundary, P::READ_WRITE, Some(P::READ_ONLY));
|
||||
let mut buffer = vec![0u8; 0x1008];
|
||||
assert_eq!(
|
||||
memory.write_bytes(boundary - 4, &buffer),
|
||||
Err(violation(boundary, "write"))
|
||||
);
|
||||
assert_eq!(
|
||||
memory.read_bytes(boundary - 4, &mut buffer),
|
||||
Err(unmapped(boundary + GUEST_PAGE))
|
||||
);
|
||||
assert_eq!(bytes_around(&memory, boundary), (BELOW, ABOVE));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_highest_guest_page_boundaries_do_not_wrap() {
|
||||
// The last page that can be mapped ends one page below 2^64.
|
||||
let top = u64::MAX - 0xFFF; // 0xffff_ffff_ffff_f000
|
||||
let mut memory = pages_around(top, P::READ_WRITE, None);
|
||||
assert_eq!(
|
||||
memory.map_region(top, 0x1000, P::READ_WRITE),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
assert_eq!(memory.read_u64(top - 8), Ok(BELOW));
|
||||
assert_eq!(memory.read_u64(top - 4).map(|_| ()), Err(unmapped(top)));
|
||||
assert_eq!(memory.write_u64(top - 4, 0), Err(unmapped(top)));
|
||||
// An access whose end passes 2^64 is an overflow wherever it starts.
|
||||
assert_eq!(memory.read_u64(u64::MAX - 6), Err(MemoryError::Overflow));
|
||||
assert_eq!(
|
||||
memory.write_u64(u64::MAX - 6, 0),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
assert_eq!(memory.read_u64(top - 8), Ok(BELOW));
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
//! Expected behavior follows x86-64 data access rules: an access is valid when
|
||||
//! every byte it touches is mapped with the required permission, whether or not
|
||||
//! it is aligned or crosses into an adjacent mapping. A faulting access changes
|
||||
//! nothing.
|
||||
//! nothing and reports the lowest address it may not touch (#175).
|
||||
|
||||
use xenora_loader::{GuestMemory, MemoryError, MemoryPermissions as P};
|
||||
|
||||
@@ -56,7 +56,7 @@ fn region_end_is_exclusive() {
|
||||
lone.map_region(A, 0x1000, P::READ_ONLY).unwrap();
|
||||
assert_eq!(
|
||||
lone.read_u32(A + 0xFFD),
|
||||
Err(MemoryError::UnmappedAddress(A + 0xFFD))
|
||||
Err(MemoryError::UnmappedAddress(A + 0x1000))
|
||||
);
|
||||
assert_eq!(
|
||||
lone.read_u8(A - 1),
|
||||
@@ -90,7 +90,7 @@ fn spanning_into_a_gap_fails_without_partial_write() {
|
||||
m.map_region(A + 0x2000, 0x1000, P::READ_WRITE).unwrap();
|
||||
assert_eq!(
|
||||
m.write_u64(A + 0xFFC, u64::MAX),
|
||||
Err(MemoryError::UnmappedAddress(A + 0xFFC))
|
||||
Err(MemoryError::UnmappedAddress(A + 0x1000))
|
||||
);
|
||||
assert_eq!(m.read_u32(A + 0xFFC), Ok(0x1111_1111));
|
||||
}
|
||||
@@ -101,7 +101,7 @@ fn spanning_into_a_forbidden_region_fails_atomically() {
|
||||
assert_eq!(
|
||||
m.write_u64(A + 0xFFC, u64::MAX),
|
||||
Err(MemoryError::PermissionViolation {
|
||||
address: A + 0xFFC,
|
||||
address: A + 0x1000,
|
||||
required: "write"
|
||||
})
|
||||
);
|
||||
@@ -123,7 +123,7 @@ fn loader_bypass_ignores_permissions_but_not_mapping() {
|
||||
assert_eq!(m.read_u32(A), Ok(7));
|
||||
assert_eq!(
|
||||
m.write_u64_bypass(A + 0x1FFC, 0),
|
||||
Err(MemoryError::UnmappedAddress(A + 0x1FFC))
|
||||
Err(MemoryError::UnmappedAddress(A + 0x2000))
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,430 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! The PE headers are mapped read-only at the image base (#333).
|
||||
//!
|
||||
//! Windows maps the first `SizeOfHeaders` bytes of an image at its base, and
|
||||
//! programs read them: a C runtime walks its own section table before `main`.
|
||||
//!
|
||||
//! Every image here is original and built byte by byte in this file. Expected
|
||||
//! values are the bytes the builder wrote, never values read back from a run.
|
||||
|
||||
use xenora_loader::cpu::{ExitReason, Register};
|
||||
use xenora_loader::imports::ImportRegistry;
|
||||
use xenora_loader::startup::{StartupLayout, StartupResult, run_synthetic_startup};
|
||||
use xenora_loader::{MemoryError, ParsedPe, PeError};
|
||||
|
||||
const PREFERRED_BASE: u64 = 0x1_4000_0000;
|
||||
const OTHER_BASE: u64 = 0x2_5000_0000;
|
||||
/// Deliberately not the usual 0x40 or 0x80, so a read of it is distinctive.
|
||||
const E_LFANEW: u32 = 0x90;
|
||||
const OPTIONAL: usize = E_LFANEW as usize + 4 + 20;
|
||||
const OPTIONAL_SIZE: usize = 240;
|
||||
const SECTIONS: u16 = 2;
|
||||
/// The first byte after the section table.
|
||||
const TABLE_END: u32 = (OPTIONAL + OPTIONAL_SIZE) as u32 + 40 * SECTIONS as u32;
|
||||
|
||||
/// One image: `.text` holding `code` and an uninitialized `.data`.
|
||||
struct Image {
|
||||
size_of_headers: u32,
|
||||
text_rva: u32,
|
||||
data_rva: u32,
|
||||
data_size: u32,
|
||||
/// File offset of the code, and so the length of the file before it.
|
||||
text_offset: u32,
|
||||
code: Vec<u8>,
|
||||
/// Base relocation blocks, placed in `.text` 0x100 bytes after the code.
|
||||
relocations: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Image {
|
||||
fn new(code: &[u8]) -> Self {
|
||||
Self {
|
||||
size_of_headers: 0x400,
|
||||
text_rva: 0x2000,
|
||||
data_rva: 0x3000,
|
||||
data_size: 0x100,
|
||||
text_offset: 0x400,
|
||||
code: code.to_vec(),
|
||||
relocations: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn build(&self) -> Vec<u8> {
|
||||
let mut pe = vec![0u8; self.text_offset as usize + 0x200];
|
||||
pe[0..2].copy_from_slice(b"MZ");
|
||||
pe[0x3C..0x40].copy_from_slice(&E_LFANEW.to_le_bytes());
|
||||
// A recognisable pattern where a DOS stub would be, and in the padding
|
||||
// after the section table.
|
||||
for (i, byte) in pe[0x40..E_LFANEW as usize].iter_mut().enumerate() {
|
||||
*byte = (i * 7 + 3) as u8;
|
||||
}
|
||||
// The pattern stops after two pages so that a very large header stays cheap.
|
||||
let padding_end = (self.text_offset as usize).min(0x2000);
|
||||
for (i, byte) in pe[TABLE_END as usize..padding_end].iter_mut().enumerate() {
|
||||
*byte = (i * 5 + 1) as u8;
|
||||
}
|
||||
let pe_at = E_LFANEW as usize;
|
||||
pe[pe_at..pe_at + 4].copy_from_slice(b"PE\0\0");
|
||||
let coff = pe_at + 4;
|
||||
pe[coff..coff + 2].copy_from_slice(&0x8664u16.to_le_bytes());
|
||||
pe[coff + 2..coff + 4].copy_from_slice(&SECTIONS.to_le_bytes());
|
||||
pe[coff + 16..coff + 18].copy_from_slice(&(OPTIONAL_SIZE as u16).to_le_bytes());
|
||||
pe[coff + 18..coff + 20].copy_from_slice(&0x0022u16.to_le_bytes());
|
||||
let opt = OPTIONAL;
|
||||
pe[opt..opt + 2].copy_from_slice(&0x020Bu16.to_le_bytes());
|
||||
pe[opt + 16..opt + 20].copy_from_slice(&self.text_rva.to_le_bytes());
|
||||
pe[opt + 24..opt + 32].copy_from_slice(&PREFERRED_BASE.to_le_bytes());
|
||||
pe[opt + 32..opt + 36].copy_from_slice(&0x1000u32.to_le_bytes());
|
||||
pe[opt + 36..opt + 40].copy_from_slice(&0x200u32.to_le_bytes());
|
||||
pe[opt + 56..opt + 60].copy_from_slice(&0x4000u32.to_le_bytes());
|
||||
pe[opt + 60..opt + 64].copy_from_slice(&self.size_of_headers.to_le_bytes());
|
||||
pe[opt + 108..opt + 112].copy_from_slice(&16u32.to_le_bytes());
|
||||
|
||||
let mut section = |i: usize, name: &[u8], rva: u32, size: u32, raw: u32, flags: u32| {
|
||||
let h = opt + OPTIONAL_SIZE + i * 40;
|
||||
pe[h..h + name.len()].copy_from_slice(name);
|
||||
pe[h + 8..h + 12].copy_from_slice(&size.to_le_bytes());
|
||||
pe[h + 12..h + 16].copy_from_slice(&rva.to_le_bytes());
|
||||
pe[h + 16..h + 20]
|
||||
.copy_from_slice(&(if raw == 0 { 0 } else { 0x200u32 }).to_le_bytes());
|
||||
pe[h + 20..h + 24].copy_from_slice(&raw.to_le_bytes());
|
||||
pe[h + 36..h + 40].copy_from_slice(&flags.to_le_bytes());
|
||||
};
|
||||
section(
|
||||
0,
|
||||
b".text",
|
||||
self.text_rva,
|
||||
0x200,
|
||||
self.text_offset,
|
||||
0x6000_0020,
|
||||
);
|
||||
section(1, b".data", self.data_rva, self.data_size, 0, 0xC000_0080);
|
||||
|
||||
let at = self.text_offset as usize;
|
||||
pe[at..at + self.code.len()].copy_from_slice(&self.code);
|
||||
if !self.relocations.is_empty() {
|
||||
// Data directory 5 is the base relocation table.
|
||||
let directory = OPTIONAL + 112 + 5 * 8;
|
||||
pe[directory..directory + 4].copy_from_slice(&(self.text_rva + 0x100).to_le_bytes());
|
||||
pe[directory + 4..directory + 8]
|
||||
.copy_from_slice(&(self.relocations.len() as u32).to_le_bytes());
|
||||
pe[at + 0x100..at + 0x100 + self.relocations.len()].copy_from_slice(&self.relocations);
|
||||
}
|
||||
pe
|
||||
}
|
||||
}
|
||||
|
||||
/// `lea rbx, [rip - (text_rva + 7)]`: the image base, wherever it was loaded.
|
||||
fn base_into_rbx(text_rva: u32) -> Vec<u8> {
|
||||
let mut code = vec![0x48, 0x8D, 0x1D];
|
||||
code.extend((-(text_rva as i32 + 7)).to_le_bytes());
|
||||
code
|
||||
}
|
||||
|
||||
fn run(bytes: &[u8], base: u64) -> StartupResult {
|
||||
let layout = StartupLayout {
|
||||
image_base: base,
|
||||
stack_top: 0x2_0001_0000,
|
||||
tls_base: 0x3_0000_0000,
|
||||
};
|
||||
run_synthetic_startup(bytes, layout, ImportRegistry::new(), 1_000).expect("startup")
|
||||
}
|
||||
|
||||
fn load_error(image: &Image) -> Option<PeError> {
|
||||
let bytes = image.build();
|
||||
let pe = ParsedPe::parse(&bytes).expect("the parser does not judge SizeOfHeaders");
|
||||
pe.load_into_memory(&bytes).err()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_guest_reads_its_own_headers_at_the_preferred_and_at_a_relocated_base() {
|
||||
let mut code = base_into_rbx(0x2000);
|
||||
code.extend([
|
||||
0x0F, 0xB7, 0x03, // movzx eax, word [rbx] DOS signature
|
||||
0x8B, 0x4B, 0x3C, // mov ecx, [rbx + 0x3C] e_lfanew
|
||||
0x8B, 0x14, 0x0B, // mov edx, [rbx + rcx] PE signature
|
||||
0x0F, 0xB7, 0x74, 0x0B, 0x06, // movzx esi, word [rbx + rcx + 6] NumberOfSections
|
||||
0x48, 0x8B, 0x7C, 0x0B, 0x30, // mov rdi, [rbx + rcx + 0x30] ImageBase
|
||||
0xF4, // hlt
|
||||
]);
|
||||
let bytes = Image::new(&code).build();
|
||||
for base in [PREFERRED_BASE, OTHER_BASE] {
|
||||
let result = run(&bytes, base);
|
||||
let cpu = &result.execution.final_state;
|
||||
assert_eq!(result.execution.exit_reason, ExitReason::Halt, "{base:#x}");
|
||||
assert_eq!(cpu.get(Register::Rbx), base, "{base:#x}");
|
||||
assert_eq!(cpu.get(Register::Rax), 0x5A4D, "{base:#x}");
|
||||
assert_eq!(cpu.get(Register::Rcx), u64::from(E_LFANEW), "{base:#x}");
|
||||
assert_eq!(cpu.get(Register::Rdx), 0x0000_4550, "{base:#x}");
|
||||
assert_eq!(cpu.get(Register::Rsi), u64::from(SECTIONS), "{base:#x}");
|
||||
// The mapped header names the base the image is at, not the preferred one.
|
||||
assert_eq!(cpu.get(Register::Rdi), base, "{base:#x}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_mapping_is_the_file_headers_then_zeros_to_the_end_of_the_page() {
|
||||
let mut code = base_into_rbx(0x2000);
|
||||
code.push(0xF4);
|
||||
let bytes = Image::new(&code).build();
|
||||
for base in [PREFERRED_BASE, OTHER_BASE] {
|
||||
let result = run(&bytes, base);
|
||||
let memory = &result.image.memory;
|
||||
let mut page = [0u8; 0x1000];
|
||||
memory.read_bytes(base, &mut page).unwrap();
|
||||
|
||||
let mut wanted = bytes[..0x400].to_vec();
|
||||
wanted[OPTIONAL + 24..OPTIONAL + 32].copy_from_slice(&base.to_le_bytes());
|
||||
assert_eq!(&page[..0x400], wanted.as_slice(), "{base:#x}");
|
||||
assert!(page[0x400..].iter().all(|&byte| byte == 0), "{base:#x}");
|
||||
|
||||
// One page and no more: `.text` starts a page later.
|
||||
assert_eq!(
|
||||
memory.read_u8(base + 0x1000),
|
||||
Err(MemoryError::UnmappedAddress(base + 0x1000)),
|
||||
"{base:#x}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_guest_write_to_the_headers_faults_and_changes_nothing() {
|
||||
let mut code = base_into_rbx(0x2000);
|
||||
code.extend([0xC6, 0x03, 0x00, 0xF4]); // mov byte [rbx], 0; hlt
|
||||
let result = run(&Image::new(&code).build(), OTHER_BASE);
|
||||
assert_eq!(
|
||||
result.execution.exit_reason,
|
||||
ExitReason::MemoryFault(MemoryError::PermissionViolation {
|
||||
address: OTHER_BASE,
|
||||
required: "write",
|
||||
})
|
||||
);
|
||||
assert_eq!(result.image.memory.read_u8(OTHER_BASE), Ok(b'M'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_headers_cannot_be_executed() {
|
||||
let mut code = base_into_rbx(0x2000);
|
||||
code.extend([0xFF, 0xE3]); // jmp rbx
|
||||
let result = run(&Image::new(&code).build(), OTHER_BASE);
|
||||
assert_eq!(
|
||||
result.execution.exit_reason,
|
||||
ExitReason::MemoryFault(MemoryError::PermissionViolation {
|
||||
address: OTHER_BASE,
|
||||
required: "execute",
|
||||
})
|
||||
);
|
||||
assert_eq!(result.execution.final_state.rip, OTHER_BASE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headers_longer_than_a_page_take_whole_pages() {
|
||||
// 0x1001 bytes of headers need two pages, so `.text` must start at 0x2000.
|
||||
let mut image = Image::new(&[0xF4]);
|
||||
image.size_of_headers = 0x1001;
|
||||
image.text_offset = 0x1200;
|
||||
let bytes = image.build();
|
||||
let Ok(loaded) = ParsedPe::parse(&bytes).unwrap().load_into_memory(&bytes) else {
|
||||
panic!("two pages of headers below a section at 0x2000 must load");
|
||||
};
|
||||
let memory = &loaded.memory;
|
||||
assert_eq!(memory.read_u8(PREFERRED_BASE + 0x1000), Ok(bytes[0x1000]));
|
||||
assert_eq!(memory.read_u8(PREFERRED_BASE + 0x1001), Ok(0));
|
||||
assert_eq!(memory.read_u8(PREFERRED_BASE + 0x1FFF), Ok(0));
|
||||
assert_eq!(memory.read_u8(PREFERRED_BASE + 0x2000), Ok(0xF4));
|
||||
|
||||
// With `.text` a page earlier the headers would reach into it.
|
||||
image.text_rva = 0x1000;
|
||||
assert_eq!(load_error(&image), Some(PeError::InvalidHeaderSize));
|
||||
|
||||
// Exactly one page of headers ends where that section starts.
|
||||
image.size_of_headers = 0x1000;
|
||||
assert_eq!(load_error(&image), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_size_that_cannot_be_mapped_is_refused() {
|
||||
let mut image = Image::new(&[0xF4]);
|
||||
image.size_of_headers = 0;
|
||||
assert_eq!(load_error(&image), Some(PeError::InvalidHeaderSize));
|
||||
|
||||
// One byte short of the section table, then exactly the section table.
|
||||
image.size_of_headers = TABLE_END - 1;
|
||||
assert_eq!(load_error(&image), Some(PeError::InvalidHeaderSize));
|
||||
image.size_of_headers = TABLE_END;
|
||||
assert_eq!(load_error(&image), None);
|
||||
|
||||
// The file is 0x600 bytes: exactly that, then one byte more.
|
||||
image.size_of_headers = 0x600;
|
||||
assert_eq!(load_error(&image), None);
|
||||
image.size_of_headers = 0x601;
|
||||
assert_eq!(load_error(&image), Some(PeError::InvalidHeaderSize));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_section_inside_the_header_page_is_not_an_overlap() {
|
||||
// A section that maps nothing has no range to collide with.
|
||||
let mut image = Image::new(&[0xF4]);
|
||||
image.data_rva = 0x200;
|
||||
image.data_size = 0;
|
||||
assert_eq!(load_error(&image), None);
|
||||
|
||||
image.data_size = 1;
|
||||
assert_eq!(load_error(&image), Some(PeError::InvalidHeaderSize));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loading_with_bytes_shorter_than_the_headers_is_an_error_not_a_panic() {
|
||||
let bytes = Image::new(&[0xF4]).build();
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
for len in [0, 0x3F, OPTIONAL, TABLE_END as usize, 0x3FF] {
|
||||
assert_eq!(
|
||||
pe.load_into_memory(&bytes[..len]).err(),
|
||||
Some(PeError::InvalidHeaderSize),
|
||||
"{len:#x}"
|
||||
);
|
||||
}
|
||||
|
||||
// Other bytes of the right length, whose own headers leave no room for the
|
||||
// `ImageBase` field inside the size that was parsed.
|
||||
let mut image = Image::new(&[0xF4]);
|
||||
image.size_of_headers = OPTIONAL as u32 + 8;
|
||||
let bytes = image.build();
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
let mut other = bytes.clone();
|
||||
let coff = E_LFANEW as usize + 4;
|
||||
other[coff + 2..coff + 4].copy_from_slice(&0u16.to_le_bytes());
|
||||
other[coff + 16..coff + 18].copy_from_slice(&0u16.to_le_bytes());
|
||||
assert_eq!(
|
||||
pe.load_into_memory(&other).err(),
|
||||
Some(PeError::InvalidHeaderSize)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn startup_reports_the_refusal() {
|
||||
let mut image = Image::new(&[0xF4]);
|
||||
image.size_of_headers = 0;
|
||||
let layout = StartupLayout {
|
||||
image_base: OTHER_BASE,
|
||||
stack_top: 0x2_0001_0000,
|
||||
tls_base: 0x3_0000_0000,
|
||||
};
|
||||
let error = run_synthetic_startup(&image.build(), layout, ImportRegistry::new(), 1_000)
|
||||
.err()
|
||||
.expect("refused");
|
||||
assert_eq!(error.to_string(), PeError::InvalidHeaderSize.to_string());
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"the PE headers cannot be mapped: SizeOfHeaders is zero, shorter than the section table, \
|
||||
longer than the file or reaches into a section, or the bytes do not match the parsed \
|
||||
headers"
|
||||
);
|
||||
}
|
||||
|
||||
/// One base relocation block: `IMAGE_REL_BASED_DIR64` entries for the given
|
||||
/// offsets in the page at `page_rva`, padded to a multiple of four bytes.
|
||||
fn dir64_block(page_rva: u32, offsets: &[u16]) -> Vec<u8> {
|
||||
let mut entries: Vec<u16> = offsets.iter().map(|offset| 0xA000 | offset).collect();
|
||||
if entries.len() % 2 == 1 {
|
||||
entries.push(0); // IMAGE_REL_BASED_ABSOLUTE padding
|
||||
}
|
||||
let mut block = page_rva.to_le_bytes().to_vec();
|
||||
block.extend((8 + 2 * entries.len() as u32).to_le_bytes());
|
||||
for entry in entries {
|
||||
block.extend(entry.to_le_bytes());
|
||||
}
|
||||
block
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_relocation_aimed_at_image_base_does_not_move_it_twice() {
|
||||
// The image carries two DIR64 entries: one for the `ImageBase` field in the
|
||||
// headers, and one for a pointer in `.text` so the table is seen to apply.
|
||||
let mut code = base_into_rbx(0x2000);
|
||||
code.extend([
|
||||
0x8B, 0x4B, 0x3C, // mov ecx, [rbx + 0x3C]
|
||||
0x48, 0x8B, 0x7C, 0x0B, 0x30, // mov rdi, [rbx + rcx + 0x30] ImageBase
|
||||
// mov rax, [rip + 0x2A]: the pointer at 0x2040
|
||||
0x48, 0x8B, 0x05, 0x2A, 0x00, 0x00, 0x00, 0xF4, // hlt
|
||||
]);
|
||||
// The load ends 0x16 bytes into the code, and 0x16 + 0x2A is 0x40.
|
||||
assert_eq!(code.len(), 0x17);
|
||||
code.resize(0x40, 0x90);
|
||||
code.extend((PREFERRED_BASE + 0x2040).to_le_bytes());
|
||||
let mut image = Image::new(&code);
|
||||
image.relocations = dir64_block(0, &[OPTIONAL as u16 + 24]);
|
||||
image.relocations.extend(dir64_block(0x2000, &[0x40]));
|
||||
let bytes = image.build();
|
||||
|
||||
for base in [PREFERRED_BASE, OTHER_BASE] {
|
||||
let result = run(&bytes, base);
|
||||
assert_eq!(result.execution.exit_reason, ExitReason::Halt, "{base:#x}");
|
||||
// Nothing is applied when the image is already at its preferred base.
|
||||
let applied = if base == PREFERRED_BASE { 0 } else { 2 };
|
||||
assert_eq!(result.relocations.applied_dir64, applied, "{base:#x}");
|
||||
let cpu = &result.execution.final_state;
|
||||
assert_eq!(cpu.get(Register::Rax), base + 0x2040, "{base:#x}");
|
||||
// Not the preferred base, and not the load base plus the delta again.
|
||||
assert_eq!(cpu.get(Register::Rdi), base, "{base:#x}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bytes_that_are_not_the_parsed_headers_are_refused() {
|
||||
let bytes = Image::new(&[0xF4]).build();
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
let coff = E_LFANEW as usize + 4;
|
||||
let refused = |change: &dyn Fn(&mut Vec<u8>)| {
|
||||
let mut other = bytes.clone();
|
||||
change(&mut other);
|
||||
pe.load_into_memory(&other).err()
|
||||
};
|
||||
assert_eq!(refused(&|_| {}), None);
|
||||
|
||||
// An optional header declared empty: the section table would start where
|
||||
// the optional header is, and `ImageBase` would be patched inside it.
|
||||
assert_eq!(
|
||||
refused(&|b| b[coff + 16..coff + 18].copy_from_slice(&0u16.to_le_bytes())),
|
||||
Some(PeError::InvalidHeaderSize)
|
||||
);
|
||||
// One byte short of the PE32+ fields the loader relies on.
|
||||
assert_eq!(
|
||||
refused(&|b| b[coff + 16..coff + 18].copy_from_slice(&111u16.to_le_bytes())),
|
||||
Some(PeError::InvalidHeaderSize)
|
||||
);
|
||||
// Not a PE32+ optional header.
|
||||
assert_eq!(
|
||||
refused(&|b| b[OPTIONAL..OPTIONAL + 2].copy_from_slice(&0x010Bu16.to_le_bytes())),
|
||||
Some(PeError::InvalidHeaderSize)
|
||||
);
|
||||
// A different section count, preferred base or header size.
|
||||
assert_eq!(
|
||||
refused(&|b| b[coff + 2..coff + 4].copy_from_slice(&1u16.to_le_bytes())),
|
||||
Some(PeError::InvalidHeaderSize)
|
||||
);
|
||||
assert_eq!(
|
||||
refused(&|b| b[OPTIONAL + 24] ^= 1),
|
||||
Some(PeError::InvalidHeaderSize)
|
||||
);
|
||||
assert_eq!(
|
||||
refused(&|b| b[OPTIONAL + 60..OPTIONAL + 64].copy_from_slice(&0x200u32.to_le_bytes())),
|
||||
Some(PeError::InvalidHeaderSize)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headers_over_the_mapping_budget_are_refused() {
|
||||
// 256 MiB of headers and one more page. The file really is that long, so
|
||||
// only the budget stands between this image and a mapping of that size.
|
||||
const BUDGET: u32 = 256 * 1024 * 1024;
|
||||
let mut image = Image::new(&[0xF4]);
|
||||
image.size_of_headers = BUDGET + 0x1000;
|
||||
image.text_offset = BUDGET + 0x1000;
|
||||
image.text_rva = BUDGET + 0x1000;
|
||||
image.data_rva = BUDGET + 0x2000;
|
||||
assert_eq!(
|
||||
load_error(&image),
|
||||
Some(PeError::SectionMappingError(MemoryError::AllocationFailed))
|
||||
);
|
||||
}
|
||||
@@ -4,11 +4,14 @@
|
||||
//!
|
||||
//! A section's mapped size is max(VirtualSize, SizeOfRawData) and the loader
|
||||
//! backs it with zero-filled host memory, so a small file can request a large
|
||||
//! allocation. The loader's documented budget is 256 MiB per image.
|
||||
//! allocation. The loader's documented budget is 256 MiB per image, and the
|
||||
//! page of headers mapped at the image base (#333) counts toward it.
|
||||
|
||||
use xenora_loader::{MemoryError, ParsedPe, PeError};
|
||||
|
||||
const BUDGET: u32 = 256 * 1024 * 1024;
|
||||
/// The image's 0x200 bytes of headers are mapped as one 4 KiB page.
|
||||
const HEADERS: u32 = 0x1000;
|
||||
|
||||
/// An original synthetic image: one 0x200-byte code section at RVA 0x1000 followed by
|
||||
/// uninitialized sections (no raw data) of the given virtual sizes, packed back to back.
|
||||
@@ -25,6 +28,8 @@ fn build(bss_sizes: &[u32]) -> Vec<u8> {
|
||||
pe[opt..opt + 2].copy_from_slice(&0x020Bu16.to_le_bytes());
|
||||
pe[opt + 16..opt + 20].copy_from_slice(&0x1000u32.to_le_bytes());
|
||||
pe[opt + 24..opt + 32].copy_from_slice(&0x1_4000_0000u64.to_le_bytes());
|
||||
// SizeOfHeaders: everything before the code's raw data.
|
||||
pe[opt + 60..opt + 64].copy_from_slice(&0x200u32.to_le_bytes());
|
||||
|
||||
let mut section = |i: usize, va: u32, vsize: u32, raw: u32, flags: u32| {
|
||||
let h = opt + 112 + i * 40;
|
||||
@@ -56,14 +61,14 @@ fn small_image_loads() {
|
||||
|
||||
#[test]
|
||||
fn image_exactly_at_budget_loads() {
|
||||
let bytes = build(&[BUDGET - 0x200]);
|
||||
let bytes = build(&[BUDGET - HEADERS - 0x200]);
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
assert!(pe.load_into_memory(&bytes).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_byte_over_budget_is_rejected() {
|
||||
let bytes = build(&[BUDGET - 0x1FF]);
|
||||
let bytes = build(&[BUDGET - HEADERS - 0x1FF]);
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
|
||||
}
|
||||
|
||||
@@ -158,7 +158,7 @@ fn probe_distinguishes_aliases_from_unavailable_services() {
|
||||
|
||||
for (index, (rva, name)) in [
|
||||
(0x1180u64, "GetCurrentProcess"),
|
||||
(0x11a0u64, "CreateThread"),
|
||||
(0x11a0u64, "TerminateProcess"),
|
||||
(0x11c0u64, "getcurrentprocess"),
|
||||
]
|
||||
.into_iter()
|
||||
|
||||
@@ -0,0 +1,540 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Process exit (issue #329): `ExitProcess`, a returning entry point, and the
|
||||
//! rule that an exited guest runs nothing further.
|
||||
//!
|
||||
//! Expected behaviour is from the public Win32 documentation for
|
||||
//! `ExitProcess` (processthreadsapi.h): it does not return, the status is a
|
||||
//! `UINT`, and the process's handles are closed. The guest code is original.
|
||||
|
||||
mod support;
|
||||
|
||||
use std::sync::Arc;
|
||||
use support::*;
|
||||
use xenora_loader::cpu::{CpuState, ExitReason};
|
||||
use xenora_loader::import_table::ImportName;
|
||||
use xenora_loader::imports::{ENTRY_RETURN, ImportRegistry, RETURN_SENTINEL_PAGE, Win64Args};
|
||||
use xenora_loader::memory::{GuestMemory, MemoryError, MemoryPermissions};
|
||||
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
|
||||
use xenora_loader::startup::{StartupLayout, run_synthetic_startup};
|
||||
|
||||
const KERNEL32: &str = "kernel32.dll";
|
||||
const THREADS: &str = "api-ms-win-core-processthreads-l1-1-0.dll";
|
||||
const UCRT: &str = "ucrtbase.dll";
|
||||
|
||||
const IMPORTS: &[(&str, &str)] = &[
|
||||
(KERNEL32, "ExitProcess"),
|
||||
(KERNEL32, "SetLastError"),
|
||||
(KERNEL32, "CreateFileW"),
|
||||
(KERNEL32, "CreateEventW"),
|
||||
(UCRT, "qsort"),
|
||||
("ws2_32.dll", "WSAStartup"),
|
||||
("ws2_32.dll", "socket"),
|
||||
("xgameruntime.dll", "XTaskQueueCreate"),
|
||||
];
|
||||
const ALIAS: &[(&str, &str)] = &[(THREADS, "ExitProcess")];
|
||||
|
||||
/// Guest address of the stub `call [slot]; hlt` for import `index`.
|
||||
fn stub(index: usize) -> u64 {
|
||||
BASE + u64::from(CODE_RVA) + 16 * index as u64
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_process_stops_the_guest_with_its_whole_status() {
|
||||
// The status is a 32-bit UINT: values above 255 survive, and the upper
|
||||
// half of RCX is not part of it.
|
||||
for (argument, status) in [
|
||||
(0, 0),
|
||||
(1, 1),
|
||||
(150, 150),
|
||||
(0x1234_5678, 0x1234_5678),
|
||||
(0xFFFF_FFFF, 0xFFFF_FFFF),
|
||||
(0xAAAA_BBBB_0000_002A, 0x2A),
|
||||
] {
|
||||
for imports in [IMPORTS, ALIAS] {
|
||||
let mut guest = Guest::new(imports, &[]);
|
||||
assert_eq!(guest.state.exit_status(), None);
|
||||
// The stub is `call [ExitProcess]; hlt`. A service that returned
|
||||
// would reach the HLT and report Halt.
|
||||
let (_, exit) = guest.run("ExitProcess", &[argument]);
|
||||
assert_eq!(exit, ExitReason::ProcessExit(status), "{argument:#x}");
|
||||
assert_eq!(guest.state.exit_status(), Some(status), "{argument:#x}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exited_guest_runs_nothing_further() {
|
||||
let mut guest = Guest::new(IMPORTS, &[]);
|
||||
assert_eq!(guest.run("ExitProcess", &[3]).1, ExitReason::ProcessExit(3));
|
||||
// Neither another service nor a second exit takes effect: the engine
|
||||
// reports the first exit again without executing anything.
|
||||
for (symbol, argument) in [("SetLastError", 5), ("ExitProcess", 9)] {
|
||||
let (_, exit) = guest.run(symbol, &[argument]);
|
||||
assert_eq!(exit, ExitReason::ProcessExit(3), "{symbol}");
|
||||
}
|
||||
assert_eq!(guest.state.last_error(THREAD_A), 0);
|
||||
assert_eq!(guest.state.exit_status(), Some(3));
|
||||
}
|
||||
|
||||
/// Under the guest thread scheduler the engine runs in slices. A process exit
|
||||
/// from the scheduled main thread stops the schedule with that exit as its
|
||||
/// reason, and sets the engine's exit latch through the sliced entry point, so
|
||||
/// nothing runs afterwards. The scheduler has no outcome of its own for a
|
||||
/// process exit and reports it as the reason of a `Fault`.
|
||||
#[test]
|
||||
fn exit_process_under_the_scheduler_ends_the_run() {
|
||||
use xenora_loader::scheduler::Outcome;
|
||||
for quantum in [1, 64, 1_000_000] {
|
||||
let mut guest = Guest::new(IMPORTS, &[]);
|
||||
assert_ne!(guest.call("CreateEventW", &[0, 1, 0, 0]), 0);
|
||||
let report = guest.scheduled("ExitProcess", &[0xAAAA_BBBB_0000_0015], quantum, 10_000);
|
||||
assert!(
|
||||
matches!(
|
||||
report.outcome,
|
||||
Outcome::Fault {
|
||||
reason: ExitReason::ProcessExit(0x15),
|
||||
..
|
||||
}
|
||||
),
|
||||
"quantum {quantum}: {:?}",
|
||||
report.outcome
|
||||
);
|
||||
assert_eq!(guest.state.exit_status(), Some(0x15));
|
||||
assert_eq!(guest.state.open_handle_count(), 0);
|
||||
// The engine is latched: an unsliced run executes nothing either.
|
||||
let (_, exit) = guest.run("SetLastError", &[5]);
|
||||
assert_eq!(exit, ExitReason::ProcessExit(0x15), "quantum {quantum}");
|
||||
assert_eq!(guest.state.last_error(THREAD_A), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_exit_decides_the_status() {
|
||||
// Two calls of the service itself, with no engine in between to stop the
|
||||
// second one.
|
||||
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0))));
|
||||
let mut registry = ImportRegistry::new();
|
||||
register_standard_services(&mut registry, Arc::clone(&state));
|
||||
let exit = ®istry
|
||||
.resolve(KERNEL32, &ImportName::Name("ExitProcess".into()))
|
||||
.expect("ExitProcess is registered")
|
||||
.handler;
|
||||
let mut cpu = CpuState::new(0, 0);
|
||||
let mut memory = GuestMemory::new();
|
||||
for status in [41, 42] {
|
||||
let mut args = Win64Args::new(&cpu);
|
||||
args.rcx = status;
|
||||
assert_eq!(
|
||||
exit(&args, &mut cpu, &mut memory),
|
||||
Err(ExitReason::ProcessExit(41))
|
||||
);
|
||||
}
|
||||
assert_eq!(state.exit_status(), Some(41));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_from_inside_a_service_callback_ends_the_process() {
|
||||
// A comparator for qsort that exits instead of comparing:
|
||||
// sub rsp, 0x28
|
||||
// mov ecx, 9
|
||||
// call <ExitProcess stub>
|
||||
// mov byte ptr [SCRATCH], 1 ; must never run
|
||||
// add rsp, 0x28
|
||||
// ret
|
||||
let call_end = routine(0) + 14;
|
||||
let displacement = (stub(0).wrapping_sub(call_end) as u32).to_le_bytes();
|
||||
let mut comparator = vec![0x48, 0x83, 0xEC, 0x28, 0xB9, 9, 0, 0, 0, 0xE8];
|
||||
comparator.extend(displacement);
|
||||
comparator.extend([0xC6, 0x04, 0x25]);
|
||||
comparator.extend((SCRATCH as u32).to_le_bytes());
|
||||
comparator.extend([0x01, 0x48, 0x83, 0xC4, 0x28, 0xC3]);
|
||||
|
||||
let mut guest = Guest::new(IMPORTS, &[comparator]);
|
||||
let items = SCRATCH + 0x100;
|
||||
guest.memory.write_u64(items, 2).unwrap();
|
||||
guest.memory.write_u64(items + 8, 1).unwrap();
|
||||
let (_, exit) = guest.run("qsort", &[items, 2, 8, routine(0)]);
|
||||
assert_eq!(exit, ExitReason::ProcessExit(9));
|
||||
assert_eq!(guest.memory.read_u8(SCRATCH).unwrap(), 0);
|
||||
// The sort never resumed, so the items are as the guest left them.
|
||||
assert_eq!((guest.u64_at(items), guest.u64_at(items + 8)), (2, 1));
|
||||
assert_eq!(guest.state.exit_status(), Some(9));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_closes_every_handle_and_keeps_the_files() {
|
||||
let mut guest = Guest::new(IMPORTS, &[]);
|
||||
let name: Vec<u8> = "C:\\exit.bin\0"
|
||||
.encode_utf16()
|
||||
.flat_map(u16::to_le_bytes)
|
||||
.collect();
|
||||
guest.memory.write_bytes(SCRATCH, &name).unwrap();
|
||||
// CreateFileW(name, GENERIC_READ | GENERIC_WRITE, no sharing, null,
|
||||
// CREATE_ALWAYS, 0, null) and an unnamed event.
|
||||
let file = guest.call("CreateFileW", &[SCRATCH, 0xC000_0000, 0, 0, 2, 0, 0]);
|
||||
assert_ne!(file, u64::MAX);
|
||||
assert_ne!(guest.call("CreateEventW", &[0, 1, 0, 0]), 0);
|
||||
assert_eq!(guest.state.open_handle_count(), 2);
|
||||
|
||||
// Sockets and task queues live in tables of their own. WSAStartup(2.2),
|
||||
// two UDP sockets, and XTaskQueueCreate(manual, manual, &handle).
|
||||
assert_eq!(guest.call("WSAStartup", &[0x0202, SCRATCH + 0x200]), 0);
|
||||
let first = guest.call("socket", &[2, 2, 17]);
|
||||
let second = guest.call("socket", &[2, 2, 17]);
|
||||
assert!(first != u64::MAX && second != u64::MAX && first != second);
|
||||
assert_eq!(guest.state.open_handle_count(), 4);
|
||||
assert_eq!(guest.call("XTaskQueueCreate", &[0, 0, SCRATCH + 0x400]), 0);
|
||||
assert_ne!(guest.u64_at(SCRATCH + 0x400), 0);
|
||||
assert_eq!(guest.state.open_handle_count(), 5);
|
||||
|
||||
assert_eq!(guest.run("ExitProcess", &[0]).1, ExitReason::ProcessExit(0));
|
||||
assert_eq!(guest.state.open_handle_count(), 0);
|
||||
// The drive is not the process: the file it created is still there.
|
||||
assert_eq!(guest.state.file_contents("C:\\exit.bin"), Some(Vec::new()));
|
||||
assert_eq!(guest.state.file_contents("C:\\absent.bin"), None);
|
||||
}
|
||||
|
||||
/// A PE32+ image with one executable section and no imports whose entry
|
||||
/// point is `mov eax, status; ret`.
|
||||
fn returning_image(status: u32) -> Vec<u8> {
|
||||
let mut pe = vec![0u8; 0x400];
|
||||
let mut put = |at: usize, bytes: &[u8]| pe[at..at + bytes.len()].copy_from_slice(bytes);
|
||||
put(0, b"MZ");
|
||||
put(0x3C, &0x80u32.to_le_bytes());
|
||||
put(0x80, b"PE\0\0");
|
||||
put(0x84, &0x8664u16.to_le_bytes()); // AMD64
|
||||
put(0x86, &1u16.to_le_bytes()); // one section
|
||||
put(0x94, &240u16.to_le_bytes()); // optional header size
|
||||
put(0x96, &0x0022u16.to_le_bytes()); // executable, large-address-aware
|
||||
let optional = 0x98;
|
||||
put(optional, &0x20Bu16.to_le_bytes()); // PE32+
|
||||
put(optional + 16, &0x1000u32.to_le_bytes()); // entry point
|
||||
put(optional + 24, &0x1_4000_0000u64.to_le_bytes()); // image base
|
||||
put(optional + 32, &0x1000u32.to_le_bytes()); // section alignment
|
||||
put(optional + 36, &0x200u32.to_le_bytes()); // file alignment
|
||||
put(optional + 56, &0x2000u32.to_le_bytes()); // size of image
|
||||
put(optional + 60, &0x200u32.to_le_bytes()); // size of headers
|
||||
put(optional + 108, &16u32.to_le_bytes()); // data directories
|
||||
let section = optional + 240;
|
||||
put(section, b".text");
|
||||
put(section + 8, &0x200u32.to_le_bytes()); // virtual size
|
||||
put(section + 12, &0x1000u32.to_le_bytes()); // RVA
|
||||
put(section + 16, &0x200u32.to_le_bytes()); // raw size
|
||||
put(section + 20, &0x200u32.to_le_bytes()); // raw offset
|
||||
put(section + 36, &0x6000_0020u32.to_le_bytes()); // code, execute, read
|
||||
put(0x200, &[0xB8]);
|
||||
put(0x201, &status.to_le_bytes());
|
||||
put(0x205, &[0xC3]);
|
||||
pe
|
||||
}
|
||||
|
||||
fn layout() -> StartupLayout {
|
||||
StartupLayout {
|
||||
image_base: 0x1_4000_0000,
|
||||
stack_top: 0x2_0001_0000,
|
||||
tls_base: 0x3_0000_0000,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_returning_entry_point_exits_with_eax() {
|
||||
// With no ExitProcess registered the return still ends the process.
|
||||
let bare = run_synthetic_startup(
|
||||
&returning_image(0x1234_5678),
|
||||
layout(),
|
||||
ImportRegistry::new(),
|
||||
100,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
bare.execution.exit_reason,
|
||||
ExitReason::ProcessExit(0x1234_5678)
|
||||
);
|
||||
// `mov eax, imm32` and `ret`, then nothing.
|
||||
assert_eq!(bare.execution.instructions_executed, 2);
|
||||
|
||||
// With the standard services it goes through ExitProcess, so the status
|
||||
// is recorded where a host can read it.
|
||||
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0))));
|
||||
let mut registry = ImportRegistry::new();
|
||||
register_standard_services(&mut registry, Arc::clone(&state));
|
||||
let standard = run_synthetic_startup(&returning_image(77), layout(), registry, 100).unwrap();
|
||||
assert_eq!(standard.execution.exit_reason, ExitReason::ProcessExit(77));
|
||||
assert_eq!(state.exit_status(), Some(77));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Exit before the entry point, and the reserved return addresses
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const IMAGE_BASE: u64 = 0x1_4000_0000;
|
||||
const ENTRY_RVA: u32 = 0x1000;
|
||||
/// TLS callback `n` is at this RVA plus 0x20 for each one before it.
|
||||
const CALLBACK_RVA: u32 = 0x1040;
|
||||
const IAT_RVA: u32 = 0x2070;
|
||||
/// One byte per marker: a routine that ran sets its own to 1.
|
||||
const MARKER_RVA: u32 = 0x2100;
|
||||
|
||||
/// A PE32+ image that imports one kernel32 function. `entry` is its entry
|
||||
/// point and each of `callbacks` is a TLS callback.
|
||||
fn image(symbol: &str, entry: &[u8], callbacks: &[Vec<u8>]) -> Vec<u8> {
|
||||
assert!(entry.len() <= 0x40 && callbacks.len() <= 4);
|
||||
let mut pe = vec![0u8; 0x600];
|
||||
let mut put = |at: usize, bytes: &[u8]| pe[at..at + bytes.len()].copy_from_slice(bytes);
|
||||
put(0, b"MZ");
|
||||
put(0x3C, &0x80u32.to_le_bytes());
|
||||
put(0x80, b"PE\0\0");
|
||||
put(0x84, &0x8664u16.to_le_bytes());
|
||||
put(0x86, &2u16.to_le_bytes());
|
||||
put(0x94, &240u16.to_le_bytes());
|
||||
put(0x96, &0x0022u16.to_le_bytes());
|
||||
let optional = 0x98;
|
||||
put(optional, &0x20Bu16.to_le_bytes());
|
||||
put(optional + 16, &ENTRY_RVA.to_le_bytes());
|
||||
put(optional + 24, &IMAGE_BASE.to_le_bytes());
|
||||
put(optional + 32, &0x1000u32.to_le_bytes());
|
||||
put(optional + 36, &0x200u32.to_le_bytes());
|
||||
put(optional + 56, &0x3000u32.to_le_bytes());
|
||||
put(optional + 60, &0x200u32.to_le_bytes());
|
||||
put(optional + 108, &16u32.to_le_bytes());
|
||||
// Data directory 1: imports. Data directory 9: TLS.
|
||||
put(optional + 120, &0x2000u32.to_le_bytes());
|
||||
put(optional + 124, &0x28u32.to_le_bytes());
|
||||
if !callbacks.is_empty() {
|
||||
put(optional + 184, &0x2080u32.to_le_bytes());
|
||||
put(optional + 188, &40u32.to_le_bytes());
|
||||
}
|
||||
for (index, (name, rva, raw, flags)) in [
|
||||
(b".text", 0x1000u32, 0x200u32, 0x6000_0020u32),
|
||||
(b".data", 0x2000, 0x400, 0xC000_0040),
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let section = optional + 240 + 40 * index;
|
||||
put(section, name);
|
||||
put(section + 8, &0x200u32.to_le_bytes());
|
||||
put(section + 12, &rva.to_le_bytes());
|
||||
put(section + 16, &0x200u32.to_le_bytes());
|
||||
put(section + 20, &raw.to_le_bytes());
|
||||
put(section + 36, &flags.to_le_bytes());
|
||||
}
|
||||
// `.data`, at file offset 0x400: the import descriptor, its strings, the
|
||||
// lookup table and the address table.
|
||||
let data = |rva: u32| 0x400 + (rva - 0x2000) as usize;
|
||||
put(data(0x2000), &0x2060u32.to_le_bytes()); // lookup table
|
||||
put(data(0x200C), &0x2040u32.to_le_bytes()); // DLL name
|
||||
put(data(0x2010), &IAT_RVA.to_le_bytes());
|
||||
put(data(0x2040), KERNEL32.as_bytes());
|
||||
put(data(0x2052), symbol.as_bytes());
|
||||
put(data(0x2060), &0x2050u64.to_le_bytes());
|
||||
put(data(IAT_RVA), &0x2050u64.to_le_bytes());
|
||||
if !callbacks.is_empty() {
|
||||
// The TLS directory: no template, an index slot, and the callbacks.
|
||||
put(data(0x2080) + 16, &(IMAGE_BASE + 0x20C0).to_le_bytes());
|
||||
put(data(0x2080) + 24, &(IMAGE_BASE + 0x20D0).to_le_bytes());
|
||||
}
|
||||
for (index, code) in callbacks.iter().enumerate() {
|
||||
assert!(code.len() <= 0x20);
|
||||
let rva = CALLBACK_RVA + 0x20 * index as u32;
|
||||
put(
|
||||
data(0x20D0) + 8 * index,
|
||||
&(IMAGE_BASE + u64::from(rva)).to_le_bytes(),
|
||||
);
|
||||
put(0x200 + (rva - 0x1000) as usize, code);
|
||||
}
|
||||
put(0x200, entry);
|
||||
pe
|
||||
}
|
||||
|
||||
/// `mov byte [marker], 1`, for code that starts at `rva`.
|
||||
fn set_marker(rva: u32, marker: u32) -> Vec<u8> {
|
||||
let mut code = vec![0xC6, 0x05];
|
||||
code.extend((MARKER_RVA + marker - (rva + 7)).to_le_bytes());
|
||||
code.push(1);
|
||||
code
|
||||
}
|
||||
|
||||
/// `mov ecx, status; call [import]; hlt`, for code that starts at `rva`.
|
||||
fn call_import_with(rva: u32, status: u32) -> Vec<u8> {
|
||||
let mut code = vec![0xB9];
|
||||
code.extend(status.to_le_bytes());
|
||||
code.extend([0xFF, 0x15]);
|
||||
code.extend((IAT_RVA - (rva + 11)).to_le_bytes());
|
||||
code.push(0xF4);
|
||||
code
|
||||
}
|
||||
|
||||
fn then(mut code: Vec<u8>, last: u8) -> Vec<u8> {
|
||||
code.push(last);
|
||||
code
|
||||
}
|
||||
|
||||
const RET: u8 = 0xC3;
|
||||
const HLT: u8 = 0xF4;
|
||||
|
||||
struct Started {
|
||||
result: xenora_loader::startup::StartupResult,
|
||||
state: Arc<ServicesState>,
|
||||
}
|
||||
|
||||
impl Started {
|
||||
fn markers(&self) -> [u8; 3] {
|
||||
let mut markers = [0; 3];
|
||||
self.result
|
||||
.image
|
||||
.memory
|
||||
.read_bytes(IMAGE_BASE + u64::from(MARKER_RVA), &mut markers)
|
||||
.unwrap();
|
||||
markers
|
||||
}
|
||||
}
|
||||
|
||||
fn start(bytes: &[u8]) -> Result<Started, String> {
|
||||
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0))));
|
||||
let mut registry = ImportRegistry::new();
|
||||
register_standard_services(&mut registry, Arc::clone(&state));
|
||||
run_synthetic_startup(bytes, layout(), registry, 1_000)
|
||||
.map(|result| Started { result, state })
|
||||
.map_err(|error| error.to_string())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_in_a_tls_callback_is_an_exit_and_nothing_after_it_runs() {
|
||||
// Markers: 0 and 1 for the two callbacks, 2 for the entry point.
|
||||
let entry = then(set_marker(ENTRY_RVA, 2), HLT);
|
||||
let first = CALLBACK_RVA;
|
||||
let second = CALLBACK_RVA + 0x20;
|
||||
|
||||
// Control: no callback exits. Both run, then the entry point.
|
||||
let quiet = start(&image(
|
||||
"ExitProcess",
|
||||
&entry,
|
||||
&[
|
||||
then(set_marker(first, 0), RET),
|
||||
then(set_marker(second, 1), RET),
|
||||
],
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(quiet.result.execution.exit_reason, ExitReason::Halt);
|
||||
assert_eq!(quiet.result.tls_callbacks, 2);
|
||||
assert_eq!(quiet.markers(), [1, 1, 1]);
|
||||
assert_eq!(quiet.state.exit_status(), None);
|
||||
|
||||
// The first callback exits: the second and the entry point never run.
|
||||
let early = start(&image(
|
||||
"ExitProcess",
|
||||
&entry,
|
||||
&[
|
||||
call_import_with(first, 77),
|
||||
then(set_marker(second, 1), RET),
|
||||
],
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
early.result.execution.exit_reason,
|
||||
ExitReason::ProcessExit(77)
|
||||
);
|
||||
assert_eq!(early.result.execution.instructions_executed, 0);
|
||||
assert_eq!(early.result.tls_callbacks, 0);
|
||||
assert_eq!(early.markers(), [0, 0, 0]);
|
||||
assert_eq!(early.state.exit_status(), Some(77));
|
||||
|
||||
// The second callback exits: the first finished, the entry point never runs.
|
||||
let late = start(&image(
|
||||
"ExitProcess",
|
||||
&entry,
|
||||
&[
|
||||
then(set_marker(first, 0), RET),
|
||||
call_import_with(second, 0x1_0002),
|
||||
],
|
||||
))
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
late.result.execution.exit_reason,
|
||||
ExitReason::ProcessExit(0x1_0002)
|
||||
);
|
||||
assert_eq!(late.result.tls_callbacks, 1);
|
||||
assert_eq!(late.markers(), [1, 0, 0]);
|
||||
assert_eq!(late.state.exit_status(), Some(0x1_0002));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fault_in_a_tls_callback_is_still_a_startup_error() {
|
||||
let entry = then(set_marker(ENTRY_RVA, 2), HLT);
|
||||
let error = start(&image("ExitProcess", &entry, &[vec![HLT]]))
|
||||
.err()
|
||||
.expect("a callback that halts is a fault");
|
||||
assert_eq!(
|
||||
error,
|
||||
"fault during TLS callback execution: guest executed HLT"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_image_over_the_reserved_return_addresses_is_refused() {
|
||||
// The entry point of this image would be exactly the address that means
|
||||
// "the entry point returned". Unreserved, the engine would report an exit
|
||||
// with status 0 before running one instruction of it.
|
||||
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0))));
|
||||
let mut registry = ImportRegistry::new();
|
||||
register_standard_services(&mut registry, Arc::clone(&state));
|
||||
let over = StartupLayout {
|
||||
image_base: ENTRY_RETURN - u64::from(ENTRY_RVA),
|
||||
..layout()
|
||||
};
|
||||
let error = run_synthetic_startup(&returning_image(5), over, registry, 100)
|
||||
.err()
|
||||
.expect("refused")
|
||||
.to_string();
|
||||
assert_eq!(
|
||||
error,
|
||||
format!("overlapping memory region: base 0x{RETURN_SENTINEL_PAGE:016x}, size 0x1000")
|
||||
);
|
||||
assert_eq!(state.exit_status(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_guest_cannot_map_the_reserved_return_addresses() {
|
||||
// The page is there after startup, and nothing can read, write or run it.
|
||||
let mut started = start(&image("ExitProcess", &[HLT], &[])).unwrap();
|
||||
let memory = &mut started.result.image.memory;
|
||||
assert!(matches!(
|
||||
memory.read_u8(ENTRY_RETURN),
|
||||
Err(MemoryError::PermissionViolation { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
memory.map_region(RETURN_SENTINEL_PAGE, 0x1000, MemoryPermissions::READ_WRITE),
|
||||
Err(MemoryError::OverlappingRegion { .. })
|
||||
));
|
||||
|
||||
// The entry point calls VirtualAlloc(address, 0x1000, MEM_COMMIT |
|
||||
// MEM_RESERVE, PAGE_READWRITE) and returns 1 if it got a null pointer.
|
||||
let allocate_at = |address: u64| {
|
||||
let mut code = vec![0x48, 0xB9]; // mov rcx, address
|
||||
code.extend(address.to_le_bytes());
|
||||
code.extend([0xBA, 0x00, 0x10, 0x00, 0x00]); // mov edx, 0x1000
|
||||
code.extend([0x41, 0xB8, 0x00, 0x30, 0x00, 0x00]); // mov r8d, 0x3000
|
||||
code.extend([0x41, 0xB9, 0x04, 0x00, 0x00, 0x00]); // mov r9d, 4
|
||||
code.extend([0x48, 0x83, 0xEC, 0x28]); // sub rsp, 0x28
|
||||
code.extend([0xFF, 0x15]); // call [VirtualAlloc]
|
||||
code.extend((IAT_RVA - (ENTRY_RVA + code.len() as u32 + 4)).to_le_bytes());
|
||||
code.extend([0x48, 0x83, 0xC4, 0x28]); // add rsp, 0x28
|
||||
code.extend([0x48, 0x85, 0xC0]); // test rax, rax
|
||||
code.extend([0x0F, 0x94, 0xC0]); // setz al
|
||||
code.extend([0x0F, 0xB6, 0xC0]); // movzx eax, al
|
||||
code.push(RET);
|
||||
start(&image("VirtualAlloc", &code, &[]))
|
||||
.unwrap()
|
||||
.result
|
||||
.execution
|
||||
.exit_reason
|
||||
};
|
||||
// Control: a free address is allocated.
|
||||
assert_eq!(allocate_at(0x6_0000_0000), ExitReason::ProcessExit(0));
|
||||
assert_eq!(
|
||||
allocate_at(RETURN_SENTINEL_PAGE),
|
||||
ExitReason::ProcessExit(1)
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,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);
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Synthetic guest calls through the standard import registry. Expectations use
|
||||
//! Microsoft's public CloseHandle, DuplicateHandle and synchronization contracts:
|
||||
//! https://learn.microsoft.com/windows/win32/api/handleapi/nf-handleapi-closehandle
|
||||
//! https://learn.microsoft.com/windows/win32/api/handleapi/nf-handleapi-duplicatehandle
|
||||
//! https://learn.microsoft.com/windows/win32/sync/synchronization-object-security-and-access-rights
|
||||
//!
|
||||
//! Capacity, rejected rights escalation and failed-output nonmutation are Xenora
|
||||
//! subset policies, not claims about every Windows handle implementation. The
|
||||
//! current runtime avoids stale aliases with increasing IDs, not generations.
|
||||
|
||||
mod support;
|
||||
|
||||
use support::{Guest, SCRATCH, SCRATCH_LEN};
|
||||
use xenora_loader::memory::MemoryPermissions;
|
||||
|
||||
const IMPORTS: &[(&str, &str)] = &[
|
||||
("kernel32.dll", "GetLastError"),
|
||||
("kernel32.dll", "CreateEventW"),
|
||||
("kernel32.dll", "CreateSemaphoreW"),
|
||||
("kernel32.dll", "SetEvent"),
|
||||
("kernel32.dll", "ReleaseSemaphore"),
|
||||
("kernel32.dll", "WaitForSingleObject"),
|
||||
("kernel32.dll", "CloseHandle"),
|
||||
("kernel32.dll", "DuplicateHandle"),
|
||||
("kernel32.dll", "GetCurrentThread"),
|
||||
("kernel32.dll", "GetCurrentThreadId"),
|
||||
("kernel32.dll", "GetThreadId"),
|
||||
];
|
||||
|
||||
const CURRENT_PROCESS: u64 = u64::MAX;
|
||||
const SAME_ACCESS: u64 = 2;
|
||||
const MODIFY: u64 = 2;
|
||||
const SYNCHRONIZE: u64 = 0x0010_0000;
|
||||
const WAIT_TIMEOUT: u64 = 258;
|
||||
const WAIT_FAILED: u64 = u32::MAX as u64;
|
||||
const INVALID_HANDLE: u64 = 6;
|
||||
const ACCESS_DENIED: u64 = 5;
|
||||
const NOACCESS: u64 = 998;
|
||||
const SENTINEL: u64 = 0xABCD_1234_5678_90EF;
|
||||
// Xenora's bounded object table, not a Windows limit.
|
||||
const CAPACITY: usize = 1024;
|
||||
|
||||
fn event(guest: &mut Guest) -> u64 {
|
||||
let handle = guest.call("CreateEventW", &[0, 0, 0, 0]);
|
||||
assert_ne!(handle, 0);
|
||||
handle
|
||||
}
|
||||
|
||||
fn duplicate(guest: &mut Guest, source: u64, output: u64, rights: u64, options: u64) -> u64 {
|
||||
guest.call(
|
||||
"DuplicateHandle",
|
||||
&[
|
||||
CURRENT_PROCESS,
|
||||
source,
|
||||
CURRENT_PROCESS,
|
||||
output,
|
||||
rights,
|
||||
0,
|
||||
options,
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
fn copy(guest: &mut Guest, source: u64, rights: u64, options: u64) -> u64 {
|
||||
guest.memory.write_u64(SCRATCH, SENTINEL).unwrap();
|
||||
assert_eq!(duplicate(guest, source, SCRATCH, rights, options), 1);
|
||||
let handle = guest.u64_at(SCRATCH);
|
||||
assert_ne!(handle, 0);
|
||||
assert_ne!(handle, source);
|
||||
assert_ne!(handle, SENTINEL);
|
||||
handle
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reclaimed_capacity_never_revives_closed_handles() {
|
||||
let mut guest = Guest::new(IMPORTS, &[]);
|
||||
let handles: Vec<_> = (0..CAPACITY).map(|_| event(&mut guest)).collect();
|
||||
assert_eq!(guest.call("CreateEventW", &[0, 0, 0, 0]), 0);
|
||||
assert_eq!(guest.error(), 8); // ERROR_NOT_ENOUGH_MEMORY
|
||||
|
||||
// Release one slot at a time while the table stays otherwise full.
|
||||
for old in handles {
|
||||
assert_eq!(guest.call("CloseHandle", &[old]), 1);
|
||||
let replacement = event(&mut guest);
|
||||
assert_ne!(replacement, old);
|
||||
assert_eq!(guest.call("SetEvent", &[old]), 0);
|
||||
assert_eq!(guest.error(), INVALID_HANDLE);
|
||||
assert_eq!(guest.call("CloseHandle", &[old]), 0);
|
||||
assert_eq!(guest.error(), INVALID_HANDLE);
|
||||
// Neither stale operation may signal or destroy the replacement.
|
||||
assert_eq!(
|
||||
guest.call("WaitForSingleObject", &[replacement, 0]),
|
||||
WAIT_TIMEOUT
|
||||
);
|
||||
assert_eq!(guest.call("SetEvent", &[replacement]), 1);
|
||||
assert_eq!(guest.call("WaitForSingleObject", &[replacement, 0]), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicates_share_signal_state_but_keep_independent_rights_and_lifetimes() {
|
||||
let mut guest = Guest::new(IMPORTS, &[]);
|
||||
let source = event(&mut guest);
|
||||
let waiter = copy(&mut guest, source, SYNCHRONIZE, 0);
|
||||
let setter = copy(&mut guest, source, MODIFY, 0);
|
||||
|
||||
assert_eq!(guest.call("SetEvent", &[waiter]), 0);
|
||||
assert_eq!(guest.error(), ACCESS_DENIED);
|
||||
assert_eq!(
|
||||
guest.call("WaitForSingleObject", &[source, 0]),
|
||||
WAIT_TIMEOUT
|
||||
);
|
||||
assert_eq!(guest.call("SetEvent", &[setter]), 1);
|
||||
assert_eq!(guest.call("WaitForSingleObject", &[setter, 0]), WAIT_FAILED);
|
||||
assert_eq!(guest.error(), ACCESS_DENIED);
|
||||
// A denied wait must not consume the auto-reset event's signal.
|
||||
assert_eq!(guest.call("WaitForSingleObject", &[waiter, 0]), 0);
|
||||
assert_eq!(
|
||||
guest.call("WaitForSingleObject", &[source, 0]),
|
||||
WAIT_TIMEOUT
|
||||
);
|
||||
|
||||
assert_eq!(guest.call("CloseHandle", &[source]), 1);
|
||||
assert_eq!(guest.call("SetEvent", &[setter]), 1);
|
||||
assert_eq!(guest.call("WaitForSingleObject", &[waiter, 0]), 0);
|
||||
// SAME_ACCESS ignores desired access, and must retain the reduced rights.
|
||||
let second_waiter = copy(&mut guest, waiter, u64::MAX, SAME_ACCESS);
|
||||
assert_eq!(guest.call("CloseHandle", &[waiter]), 1);
|
||||
assert_eq!(guest.call("SetEvent", &[second_waiter]), 0);
|
||||
assert_eq!(guest.error(), ACCESS_DENIED);
|
||||
assert_eq!(guest.call("SetEvent", &[setter]), 1);
|
||||
assert_eq!(guest.call("CloseHandle", &[setter]), 1);
|
||||
assert_eq!(guest.call("WaitForSingleObject", &[second_waiter, 0]), 0);
|
||||
assert_eq!(
|
||||
guest.call("WaitForSingleObject", &[second_waiter, 0]),
|
||||
WAIT_TIMEOUT
|
||||
);
|
||||
assert_eq!(guest.call("CloseHandle", &[second_waiter]), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_duplicate_outputs_leave_memory_source_and_capacity_unchanged() {
|
||||
let mut guest = Guest::new(IMPORTS, &[]);
|
||||
let source = event(&mut guest);
|
||||
let readonly = 0x6_0000;
|
||||
guest
|
||||
.memory
|
||||
.map_region(readonly, 8, MemoryPermissions::READ_ONLY)
|
||||
.unwrap();
|
||||
guest
|
||||
.memory
|
||||
.write_u64(SCRATCH + SCRATCH_LEN - 8, SENTINEL)
|
||||
.unwrap();
|
||||
assert_eq!(guest.call("SetEvent", &[source]), 1);
|
||||
|
||||
for output in [0, readonly, 0xDEAD_0000, SCRATCH + SCRATCH_LEN - 4] {
|
||||
// Repeated failures must not fill the table with unreachable duplicates.
|
||||
for _ in 0..CAPACITY {
|
||||
assert_eq!(duplicate(&mut guest, source, output, 0, SAME_ACCESS), 0);
|
||||
assert_eq!(guest.error(), NOACCESS);
|
||||
}
|
||||
}
|
||||
assert_eq!(guest.u64_at(readonly), 0);
|
||||
assert_eq!(guest.u64_at(SCRATCH + SCRATCH_LEN - 8), SENTINEL);
|
||||
assert_eq!(guest.call("WaitForSingleObject", &[source, 0]), 0);
|
||||
assert_eq!(
|
||||
guest.call("WaitForSingleObject", &[source, 0]),
|
||||
WAIT_TIMEOUT
|
||||
);
|
||||
// All remaining slots must still be available after the failed calls.
|
||||
for _ in 1..CAPACITY {
|
||||
event(&mut guest);
|
||||
}
|
||||
assert_eq!(guest.call("CreateEventW", &[0, 0, 0, 0]), 0);
|
||||
assert_eq!(guest.error(), 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_types_and_rights_escalation_preserve_objects_and_output() {
|
||||
let mut guest = Guest::new(IMPORTS, &[]);
|
||||
let source = event(&mut guest);
|
||||
let semaphore = guest.call("CreateSemaphoreW", &[0, 1, 2, 0]);
|
||||
assert_ne!(semaphore, 0);
|
||||
assert_eq!(guest.call("SetEvent", &[semaphore]), 0);
|
||||
assert_eq!(guest.error(), INVALID_HANDLE);
|
||||
assert_eq!(guest.call("ReleaseSemaphore", &[source, 1, 0]), 0);
|
||||
assert_eq!(guest.error(), INVALID_HANDLE);
|
||||
for handle in [source, semaphore] {
|
||||
assert_eq!(guest.call("GetThreadId", &[handle]), 0);
|
||||
assert_eq!(guest.error(), INVALID_HANDLE);
|
||||
}
|
||||
assert_eq!(guest.call("WaitForSingleObject", &[semaphore, 0]), 0);
|
||||
assert_eq!(
|
||||
guest.call("WaitForSingleObject", &[semaphore, 0]),
|
||||
WAIT_TIMEOUT
|
||||
);
|
||||
assert_eq!(
|
||||
guest.call("WaitForSingleObject", &[source, 0]),
|
||||
WAIT_TIMEOUT
|
||||
);
|
||||
|
||||
let waiter = copy(&mut guest, source, SYNCHRONIZE, 0);
|
||||
guest.memory.write_u64(SCRATCH, SENTINEL).unwrap();
|
||||
assert_eq!(duplicate(&mut guest, waiter, SCRATCH, MODIFY, 0), 0);
|
||||
assert_eq!(guest.error(), ACCESS_DENIED);
|
||||
assert_eq!(guest.u64_at(SCRATCH), SENTINEL);
|
||||
assert_eq!(guest.call("SetEvent", &[source]), 1);
|
||||
assert_eq!(guest.call("WaitForSingleObject", &[waiter, 0]), 0);
|
||||
assert_eq!(guest.call("CloseHandle", &[waiter]), 1);
|
||||
assert_eq!(duplicate(&mut guest, waiter, SCRATCH, 0, SAME_ACCESS), 0);
|
||||
assert_eq!(guest.error(), INVALID_HANDLE);
|
||||
assert_eq!(guest.u64_at(SCRATCH), SENTINEL);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_pseudo_handle_survives_real_duplicate_closure() {
|
||||
let mut guest = Guest::new(IMPORTS, &[]);
|
||||
let pseudo = guest.call("GetCurrentThread", &[]);
|
||||
let id = guest.call("GetCurrentThreadId", &[]);
|
||||
let first = copy(&mut guest, pseudo, 0x0800, 0); // THREAD_QUERY_LIMITED_INFORMATION
|
||||
assert_eq!(guest.call("GetThreadId", &[first]), id);
|
||||
assert_eq!(guest.call("CloseHandle", &[first]), 1);
|
||||
let second = copy(&mut guest, pseudo, 0x0800, 0);
|
||||
assert_ne!(first, second);
|
||||
assert_eq!(guest.call("GetThreadId", &[first]), 0);
|
||||
assert_eq!(guest.error(), INVALID_HANDLE);
|
||||
assert_eq!(guest.call("GetThreadId", &[second]), id);
|
||||
assert_eq!(guest.call("GetThreadId", &[pseudo]), id);
|
||||
assert_eq!(guest.call("CloseHandle", &[second]), 1);
|
||||
assert_eq!(guest.call("GetThreadId", &[pseudo]), id);
|
||||
}
|
||||
@@ -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:?}");
|
||||
}
|
||||
@@ -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));
|
||||
|
||||
@@ -0,0 +1,933 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Guest thread scheduler tests.
|
||||
//!
|
||||
//! The workloads are original C programs compiled for x86-64 Windows (see
|
||||
//! `threads/compile.py`), bound through a real import table and executed as
|
||||
//! translated guest code. Expected values are computed here or stated by the
|
||||
//! public Win32 documentation, not taken from the scheduler.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
use xenora_loader::cpu::{CpuState, ExitReason, Register};
|
||||
use xenora_loader::dbt::{DbtEngine, DbtMetrics};
|
||||
use xenora_loader::imports::ImportRegistry;
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
use xenora_loader::pe::ParsedPe;
|
||||
use xenora_loader::scheduler::{DEFAULT_QUANTUM, Outcome, ScheduleReport, Scheduler};
|
||||
use xenora_loader::services::{Clock, MockClock, ServicesState, register_standard_services};
|
||||
|
||||
const BASE: u64 = 0x1_4000_0000;
|
||||
const TEXT_RVA: u32 = 0x1000;
|
||||
const TEXT_RAW: usize = 0x200;
|
||||
const TEXT_LEN: usize = 0x4000;
|
||||
const IDATA_RVA: u32 = 0x8000;
|
||||
const IDATA_RAW: usize = TEXT_RAW + TEXT_LEN;
|
||||
const IDATA_LEN: usize = 0x2000;
|
||||
const STACK: u64 = 0x8_0000;
|
||||
const STACK_LEN: usize = 0x1_0000;
|
||||
const TEB: u64 = 0x7_0000;
|
||||
const SHARED: u64 = 0x5_0000;
|
||||
const COUNTER: u64 = SHARED + 256;
|
||||
/// First guest thread slot: guard page, stack, guard page, TEB.
|
||||
const FIRST_SLOT: u64 = 0x6_0000_0000;
|
||||
const BUDGET: usize = 20_000_000;
|
||||
const MAIN_ID: u32 = 0x4104;
|
||||
/// Host services of the test programs: advance the clock by RCX milliseconds,
|
||||
/// and try to run a second scheduler.
|
||||
const ADVANCE: u64 = 0x6_0000;
|
||||
const NESTED: u64 = 0x6_0010;
|
||||
|
||||
fn return_to_guest(cpu: &mut CpuState, memory: &mut GuestMemory) -> Result<(), ExitReason> {
|
||||
let rsp = cpu.get(Register::Rsp);
|
||||
cpu.rip = memory.read_u64(rsp).map_err(ExitReason::MemoryFault)?;
|
||||
cpu.set(Register::Rsp, rsp + 8);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct Program {
|
||||
code: Vec<u8>,
|
||||
entries: BTreeMap<&'static str, usize>,
|
||||
imports: Vec<(&'static str, usize)>,
|
||||
}
|
||||
|
||||
fn program() -> Program {
|
||||
let mut program = Program {
|
||||
code: Vec::new(),
|
||||
entries: BTreeMap::new(),
|
||||
imports: Vec::new(),
|
||||
};
|
||||
for line in include_str!("threads/program.txt").lines() {
|
||||
let parts: Vec<&str> = line.split(' ').collect();
|
||||
match parts[0] {
|
||||
"entry" => {
|
||||
program.entries.insert(parts[1], parts[2].parse().unwrap());
|
||||
}
|
||||
"import" => program.imports.push((parts[1], parts[2].parse().unwrap())),
|
||||
_ => program.code.extend(
|
||||
(0..parts[1].len())
|
||||
.step_by(2)
|
||||
.map(|at| u8::from_str_radix(&parts[1][at..at + 2], 16).unwrap()),
|
||||
),
|
||||
}
|
||||
}
|
||||
program
|
||||
}
|
||||
|
||||
/// Build a PE image whose entry point is `call main; hlt`.
|
||||
fn image(main: &str) -> Vec<u8> {
|
||||
let program = program();
|
||||
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);
|
||||
}
|
||||
let start = program.code.len().next_multiple_of(16);
|
||||
assert!(start + 16 <= TEXT_LEN);
|
||||
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,
|
||||
&(TEXT_RVA + start as u32).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, &0x10000u32.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", TEXT_RVA, TEXT_RAW, TEXT_LEN, 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());
|
||||
}
|
||||
put(&mut pe, TEXT_RAW, &program.code);
|
||||
let displacement = program.entries[main] as i32 - (start as i32 + 5);
|
||||
put(&mut pe, TEXT_RAW + start, &[0xE8]);
|
||||
put(&mut pe, TEXT_RAW + start + 1, &displacement.to_le_bytes());
|
||||
put(&mut pe, TEXT_RAW + start + 5, &[0xF4]);
|
||||
|
||||
let file = |rva: u32| IDATA_RAW + (rva - IDATA_RVA) as usize;
|
||||
let mut names: Vec<&str> = program.imports.iter().map(|import| import.0).collect();
|
||||
names.sort_unstable();
|
||||
names.dedup();
|
||||
let mut next = IDATA_RVA + 20 * (names.len() as u32 + 1);
|
||||
let mut take = |len: usize| {
|
||||
let rva = next;
|
||||
next = (next + len as u32 + 7) & !7;
|
||||
rva
|
||||
};
|
||||
let mut slots = BTreeMap::new();
|
||||
for (index, name) in names.iter().enumerate() {
|
||||
let module: &[u8] = if *name == "_errno" {
|
||||
b"api-ms-win-crt-runtime-l1-1-0.dll"
|
||||
} else {
|
||||
b"KERNEL32.dll"
|
||||
};
|
||||
let module_rva = take(module.len() + 1);
|
||||
put(&mut pe, file(module_rva), module);
|
||||
let hint = take(name.len() + 3);
|
||||
put(&mut pe, file(hint) + 2, name.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.insert(*name, slot);
|
||||
}
|
||||
for (name, offset) in &program.imports {
|
||||
let displacement = slots[name].wrapping_sub(TEXT_RVA + *offset as u32 + 4);
|
||||
put(&mut pe, TEXT_RAW + offset, &displacement.to_le_bytes());
|
||||
}
|
||||
pe
|
||||
}
|
||||
|
||||
struct Run {
|
||||
report: ScheduleReport,
|
||||
memory: GuestMemory,
|
||||
clock: Arc<MockClock>,
|
||||
metrics: DbtMetrics,
|
||||
state: Arc<ServicesState>,
|
||||
}
|
||||
|
||||
impl Run {
|
||||
fn out(&self, index: u64) -> u64 {
|
||||
self.memory.read_u64(SHARED + 8 * index).unwrap()
|
||||
}
|
||||
|
||||
fn outs(&self, count: u64) -> Vec<u64> {
|
||||
(0..count).map(|index| self.out(index)).collect()
|
||||
}
|
||||
|
||||
fn halted(self) -> Self {
|
||||
assert_eq!(self.report.outcome, Outcome::Halted);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
struct Guest {
|
||||
memory: GuestMemory,
|
||||
engine: DbtEngine,
|
||||
cpu: CpuState,
|
||||
state: Arc<ServicesState>,
|
||||
clock: Arc<MockClock>,
|
||||
}
|
||||
|
||||
fn guest(main: &str) -> Guest {
|
||||
let bytes = image(main);
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
let mut loaded = pe.load_into_memory(&bytes).unwrap();
|
||||
let memory = &mut loaded.memory;
|
||||
for (base, len) in [(SHARED, 0x1000), (STACK, STACK_LEN), (TEB, 0x2000)] {
|
||||
memory
|
||||
.map_region(base, len, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
}
|
||||
let clock = Arc::new(MockClock::new(1_000_000));
|
||||
let state = Arc::new(ServicesState::new(clock.clone()));
|
||||
let mut registry = ImportRegistry::new();
|
||||
register_standard_services(&mut registry, Arc::clone(&state));
|
||||
registry.bind_imports(&pe, &bytes, BASE, memory).unwrap();
|
||||
let mut engine = DbtEngine::new(1024 * 1024).unwrap();
|
||||
engine.set_import_registry(registry);
|
||||
let time = clock.clone();
|
||||
engine.register_service(ADVANCE, move |cpu, memory| {
|
||||
time.advance(cpu.get(Register::Rcx) * 10_000);
|
||||
return_to_guest(cpu, memory)
|
||||
});
|
||||
let mut cpu = CpuState::new(loaded.entry_point, STACK + STACK_LEN as u64 - 0x100);
|
||||
cpu.gs_base = TEB;
|
||||
Guest {
|
||||
memory: loaded.memory,
|
||||
engine,
|
||||
cpu,
|
||||
state,
|
||||
clock,
|
||||
}
|
||||
}
|
||||
|
||||
fn run_with(main: &str, quantum: usize, budget: usize) -> Run {
|
||||
let mut guest = guest(main);
|
||||
let report = Scheduler::new(Arc::clone(&guest.state), quantum)
|
||||
.run(&mut guest.engine, &mut guest.memory, &guest.cpu, budget)
|
||||
.unwrap();
|
||||
Run {
|
||||
report,
|
||||
memory: guest.memory,
|
||||
clock: guest.clock,
|
||||
metrics: guest.engine.metrics,
|
||||
state: guest.state,
|
||||
}
|
||||
}
|
||||
|
||||
fn run(main: &str) -> Run {
|
||||
run_with(main, DEFAULT_QUANTUM, BUDGET)
|
||||
}
|
||||
|
||||
const QUANTA: [usize; 6] = [1, 2, 7, 64, 1024, 1_000_000];
|
||||
const FAILED: u64 = u32::MAX as u64;
|
||||
|
||||
fn fibonacci(n: u32) -> u64 {
|
||||
(0..n)
|
||||
.fold((0u64, 1u64), |(a, b), _| (b, a.wrapping_add(b)))
|
||||
.0
|
||||
}
|
||||
|
||||
fn collatz_steps(mut value: u64) -> u64 {
|
||||
let mut steps = 0;
|
||||
while value != 1 {
|
||||
value = if value % 2 == 1 {
|
||||
3 * value + 1
|
||||
} else {
|
||||
value / 2
|
||||
};
|
||||
steps += 1;
|
||||
}
|
||||
steps
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threads_run_independent_functions_and_report_exit_codes() {
|
||||
for quantum in QUANTA {
|
||||
let run = run_with("main_independent", quantum, BUDGET).halted();
|
||||
assert_eq!(
|
||||
run.outs(7),
|
||||
[fibonacci(80), collatz_steps(97), 0, 11, 22, 1, 1],
|
||||
"quantum {quantum}"
|
||||
);
|
||||
assert_eq!(run.report.peak_threads, 3);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn atomic_and_locked_counters_lose_no_update() {
|
||||
for quantum in QUANTA {
|
||||
for main in ["main_atomic", "main_mutex"] {
|
||||
let run = run_with(main, quantum, BUDGET).halted();
|
||||
assert_eq!(run.outs(2), [0, 800], "{main} quantum {quantum}");
|
||||
assert_eq!(run.report.peak_threads, 5);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsynchronized_counters_do_lose_updates() {
|
||||
// Shows that the threads really interleave: the locked version above has
|
||||
// the same read, yield, write sequence.
|
||||
let run = run("main_racy").halted();
|
||||
assert!(run.out(1) < 800, "{}", run.out(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_blocked_thread_resumes_when_it_is_signaled() {
|
||||
let expected = (1..=50u64).fold(0u64, |sum, value| sum.wrapping_mul(31).wrapping_add(value));
|
||||
for quantum in QUANTA {
|
||||
let run = run_with("main_producer", quantum, BUDGET).halted();
|
||||
assert_eq!(run.outs(2), [expected, 1], "quantum {quantum}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_signal_releases_the_oldest_waiter_only() {
|
||||
for quantum in [64, 1024, 1_000_000] {
|
||||
let run = run_with("main_fifo", quantum, BUDGET).halted();
|
||||
// Nobody ran before the signal; the setter cannot take it back.
|
||||
assert_eq!(
|
||||
[run.out(8), run.out(9), run.out(10)],
|
||||
[0, 258, 1],
|
||||
"quantum {quantum}"
|
||||
);
|
||||
assert_eq!(run.outs(4), [10, 11, 12, 13], "quantum {quantum}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn timeouts_follow_the_clock_exactly() {
|
||||
let run = run("main_timeout").halted();
|
||||
assert_eq!(run.outs(3), [258, 258, 0]);
|
||||
// 250 ms in 100 ns units, and no further sleep.
|
||||
assert_eq!(run.clock.performance_count(), 2_500_000);
|
||||
let run = run_with("main_signal_before_timeout", 1024, BUDGET).halted();
|
||||
assert_eq!(run.outs(2), [0, 258]);
|
||||
assert_eq!(run.clock.performance_count(), 400_000 + 1_000_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_local_state_is_isolated() {
|
||||
for quantum in QUANTA {
|
||||
let run = run_with("main_isolated", quantum, BUDGET).halted();
|
||||
assert_eq!(
|
||||
run.outs(7),
|
||||
[1, 1, 1, 1, 1234, 0xAAAA, 1],
|
||||
"quantum {quantum}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_and_termination_follow_the_documented_results() {
|
||||
let run = run("main_lifecycle").halted();
|
||||
assert_eq!(
|
||||
run.outs(16),
|
||||
[
|
||||
0, 0xC0DE, // ExitThread
|
||||
259, 258, // STILL_ACTIVE, WAIT_TIMEOUT
|
||||
1, 0, 77, // TerminateThread, signaled, its code
|
||||
0, 5, 77, // already terminated: ERROR_ACCESS_DENIED, code kept
|
||||
1, FAILED, 6, // closed: WAIT_FAILED, ERROR_INVALID_HANDLE
|
||||
0, 0, 0, // OpenThread fails; nothing ran after ExitThread
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn suspended_threads_do_not_run() {
|
||||
let run = run("main_suspend");
|
||||
// The program ends by suspending itself, with nobody left to resume it.
|
||||
assert_eq!(
|
||||
run.report.outcome,
|
||||
Outcome::Deadlock {
|
||||
blocked: vec![],
|
||||
suspended: vec![MAIN_ID]
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
run.outs(15),
|
||||
[
|
||||
0, 1, 2, // created suspended, then suspended again, then resumed once
|
||||
258, 1, 0, 1, // still suspended; resumed; ended; ran
|
||||
FAILED, 5, // an ended thread cannot be suspended
|
||||
1, 0, // resumed and joined through an opened handle
|
||||
0, 5, 0, // which may not query or terminate
|
||||
0, // main never resumed itself
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hundreds_of_threads_leave_nothing_behind() {
|
||||
for quantum in [7, 1024] {
|
||||
let run = run_with("main_churn", quantum, BUDGET).halted();
|
||||
assert_eq!(run.outs(2), [600, 600], "quantum {quantum}");
|
||||
assert_eq!(run.report.peak_threads, 2, "one slot is reused");
|
||||
for offset in [0, 0x1000, 0x2_0000, 0xF0_0000] {
|
||||
assert!(
|
||||
run.memory.read_u8(FIRST_SLOT + offset).is_err(),
|
||||
"{offset:#x} is still mapped"
|
||||
);
|
||||
assert!(
|
||||
run.memory
|
||||
.read_u8(FIRST_SLOT + 0x100_0000 + offset)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
assert_eq!(run.state.last_error(FIRST_SLOT + 0xF0_0000), 0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_creation_is_bounded_and_validated() {
|
||||
let run = run("main_limit");
|
||||
// The main thread counts towards the limit of 64. The waiters never end.
|
||||
assert_eq!(run.outs(5), [63, 8, 0, 0, 87]);
|
||||
assert_eq!(run.report.outcome, Outcome::Halted);
|
||||
assert!(
|
||||
run.memory.read_u8(FIRST_SLOT + 0x1000).is_err(),
|
||||
"reclaimed at exit"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_deadlock_is_reported_with_its_threads() {
|
||||
let run = run("main_deadlock");
|
||||
assert_eq!(
|
||||
run.report.outcome,
|
||||
Outcome::Deadlock {
|
||||
blocked: vec![MAIN_ID, MAIN_ID + 4],
|
||||
suspended: vec![]
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mutex_owned_by_an_ended_thread_is_reported_abandoned_once() {
|
||||
let run = run("main_abandoned").halted();
|
||||
// WAIT_ABANDONED_0 + 1, released, then an ordinary acquisition.
|
||||
assert_eq!(run.outs(3), [0x81, 1, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stack_overflow_faults_in_the_guard_page_of_that_thread() {
|
||||
let run = run("main_overflow");
|
||||
let Outcome::Fault {
|
||||
thread,
|
||||
reason,
|
||||
rip,
|
||||
} = run.report.outcome
|
||||
else {
|
||||
panic!("{:?}", run.report.outcome);
|
||||
};
|
||||
assert_eq!(thread, MAIN_ID + 4);
|
||||
assert!((BASE..BASE + 0x8000).contains(&rip));
|
||||
let ExitReason::MemoryFault(error) = reason else {
|
||||
panic!("{reason:?}")
|
||||
};
|
||||
let text = format!("{error:?}");
|
||||
assert!(text.contains("PermissionViolation"), "{text}");
|
||||
// A 256 KiB stack with frames of at least 512 bytes.
|
||||
assert!((100..512).contains(&run.out(0)), "{}", run.out(0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wait_keeps_the_objects_it_was_given() {
|
||||
for quantum in QUANTA {
|
||||
let run = run_with("main_captured", quantum, BUDGET).halted();
|
||||
// Object 1, the semaphore, whose only permit the wait consumed.
|
||||
assert_eq!(run.outs(2), [1, 258], "quantum {quantum}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_process_ends_with_its_main_thread_but_not_with_exit_thread() {
|
||||
let run = run("main_outlived").halted();
|
||||
assert!(
|
||||
run.memory.read_u8(FIRST_SLOT + 0x1000).is_err(),
|
||||
"the spinning thread is gone"
|
||||
);
|
||||
let run = run_with("main_exits_first", 1024, BUDGET);
|
||||
assert_eq!(run.report.outcome, Outcome::AllThreadsExited);
|
||||
assert_eq!(run.outs(2), [258, 1]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scheduling_is_deterministic_and_bounded() {
|
||||
for main in ["main_racy", "main_mutex", "main_isolated", "main_churn"] {
|
||||
for quantum in [1, 64, 1024] {
|
||||
let (first, second) = (
|
||||
run_with(main, quantum, BUDGET),
|
||||
run_with(main, quantum, BUDGET),
|
||||
);
|
||||
assert_eq!(first.report, second.report, "{main} quantum {quantum}");
|
||||
assert_eq!(first.outs(32), second.outs(32), "{main} quantum {quantum}");
|
||||
}
|
||||
}
|
||||
for budget in [0, 1, 100, 5000] {
|
||||
let run = run_with("main_atomic", 64, budget);
|
||||
assert_eq!(run.report.outcome, Outcome::BudgetExhausted);
|
||||
assert!(
|
||||
run.report.instructions <= budget + 64,
|
||||
"{}",
|
||||
run.report.instructions
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_quanta_do_not_fill_the_code_cache() {
|
||||
// Compiled code must not depend on where turns happened to end.
|
||||
let blocks = |quantum| {
|
||||
run_with("main_independent", quantum, BUDGET)
|
||||
.metrics
|
||||
.blocks_compiled
|
||||
};
|
||||
let whole = blocks(1_000_000);
|
||||
for quantum in [1, 2, 3, 5, 7, 11, 13, 64] {
|
||||
assert_eq!(blocks(quantum), whole, "quantum {quantum}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_scheduler_nothing_pretends_to_create_threads() {
|
||||
let mut guest = guest("main_independent");
|
||||
let result = guest.engine.run(&mut guest.cpu, &mut guest.memory, BUDGET);
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
assert_eq!(
|
||||
guest.memory.read_u64(SHARED + 392).unwrap(),
|
||||
0,
|
||||
"CreateThread returned null"
|
||||
);
|
||||
assert_eq!(
|
||||
guest.memory.read_u64(SHARED + 16).unwrap(),
|
||||
FAILED,
|
||||
"the wait failed"
|
||||
);
|
||||
assert_eq!(guest.state.last_error(TEB), 6);
|
||||
|
||||
let mut waiting = self::guest("main_timeout");
|
||||
waiting
|
||||
.engine
|
||||
.run(&mut waiting.cpu, &mut waiting.memory, BUDGET);
|
||||
assert_eq!(waiting.memory.read_u64(SHARED).unwrap(), FAILED);
|
||||
assert_eq!(waiting.clock.performance_count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_finished_run_detaches_its_scheduler() {
|
||||
let mut guest = guest("main_timeout");
|
||||
for _ in 0..2 {
|
||||
let scheduler = Scheduler::new(Arc::clone(&guest.state), 1024);
|
||||
let report = scheduler
|
||||
.run(&mut guest.engine, &mut guest.memory, &guest.cpu, BUDGET)
|
||||
.unwrap();
|
||||
assert_eq!(report.outcome, Outcome::Halted);
|
||||
assert_ne!(report.main.get(Register::Rsp), 0);
|
||||
}
|
||||
assert_eq!(guest.memory.read_u64(COUNTER).unwrap(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_scheduler_cannot_attach_while_one_runs() {
|
||||
let mut guest = guest("main_nested");
|
||||
let state = Arc::clone(&guest.state);
|
||||
guest.engine.register_service(NESTED, move |cpu, memory| {
|
||||
let mut engine = DbtEngine::new(1024 * 1024).unwrap();
|
||||
let nested = Scheduler::new(Arc::clone(&state), 1024).run(&mut engine, memory, cpu, BUDGET);
|
||||
assert_eq!(nested.err(), Some(ExitReason::ServiceAbiViolation));
|
||||
memory
|
||||
.write_u64(SHARED, 1)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
return_to_guest(cpu, memory)
|
||||
});
|
||||
let report = Scheduler::new(Arc::clone(&guest.state), 1024)
|
||||
.run(&mut guest.engine, &mut guest.memory, &guest.cpu, BUDGET)
|
||||
.unwrap();
|
||||
// The refused attempt leaves the running scheduler attached.
|
||||
assert_eq!(report.outcome, Outcome::Halted);
|
||||
assert_eq!(guest.memory.read_u64(SHARED).unwrap(), 1);
|
||||
assert_eq!(guest.memory.read_u64(SHARED + 8).unwrap(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_signal_after_the_deadline_is_not_taken_by_the_expired_wait() {
|
||||
for quantum in QUANTA {
|
||||
let run = run_with("main_expired_wait", quantum, BUDGET).halted();
|
||||
// WAIT_TIMEOUT, the signaling thread ends, and the auto-reset signal is
|
||||
// still there once.
|
||||
assert_eq!(run.outs(4), [258, 0, 0, 258], "quantum {quantum}");
|
||||
assert_eq!(run.clock.performance_count(), 1_000_000);
|
||||
}
|
||||
}
|
||||
|
||||
/// Run `main_continued_wait` until `budget` is spent.
|
||||
fn first_part(budget: usize) -> (Guest, ScheduleReport) {
|
||||
let mut guest = guest("main_continued_wait");
|
||||
let report = Scheduler::new(Arc::clone(&guest.state), 1024)
|
||||
.run(&mut guest.engine, &mut guest.memory, &guest.cpu, budget)
|
||||
.unwrap();
|
||||
(guest, report)
|
||||
}
|
||||
|
||||
/// Smallest budget with which the wait has been called.
|
||||
fn budget_that_blocks() -> usize {
|
||||
(1..200)
|
||||
.find(|&budget| first_part(budget).0.engine.metrics.service_calls >= 2)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_continued_run_keeps_the_pending_wait() {
|
||||
let blocks = budget_that_blocks();
|
||||
for budget in [blocks, blocks + 1] {
|
||||
let (mut guest, report) = first_part(budget);
|
||||
assert_eq!(report.outcome, Outcome::BudgetExhausted);
|
||||
guest.clock.advance(6_000_000);
|
||||
// Neither the timeout nor the objects are taken again.
|
||||
guest.memory.write_u64(SHARED + 8 * 49, 0xBAD).unwrap();
|
||||
let report = Scheduler::new(Arc::clone(&guest.state), 1024)
|
||||
.run(&mut guest.engine, &mut guest.memory, &report.main, BUDGET)
|
||||
.unwrap();
|
||||
assert_eq!(report.outcome, Outcome::Halted);
|
||||
assert_eq!(guest.memory.read_u64(SHARED).unwrap(), 258);
|
||||
assert_eq!(guest.clock.performance_count(), 10_000_000);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_from_another_context_does_not_inherit_a_pending_wait() {
|
||||
let (mut guest, _) = first_part(budget_that_blocks());
|
||||
let report = Scheduler::new(Arc::clone(&guest.state), 1024)
|
||||
.run(&mut guest.engine, &mut guest.memory, &guest.cpu, BUDGET)
|
||||
.unwrap();
|
||||
assert_eq!(report.outcome, Outcome::Halted);
|
||||
guest.clock.advance(6_000_000);
|
||||
let begun = guest.clock.performance_count();
|
||||
Scheduler::new(Arc::clone(&guest.state), 1024)
|
||||
.run(&mut guest.engine, &mut guest.memory, &guest.cpu, BUDGET)
|
||||
.unwrap();
|
||||
assert_eq!(guest.clock.performance_count(), begun + 10_000_000);
|
||||
|
||||
let (mut guest, _) = first_part(budget_that_blocks());
|
||||
guest.clock.advance(6_000_000);
|
||||
Scheduler::new(Arc::clone(&guest.state), 1024)
|
||||
.run(&mut guest.engine, &mut guest.memory, &guest.cpu, BUDGET)
|
||||
.unwrap();
|
||||
assert_eq!(guest.clock.performance_count(), 16_000_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exhausted_run_neither_sleeps_nor_reports_a_deadlock() {
|
||||
let blocks = budget_that_blocks();
|
||||
for budget in 1..=blocks + 1 {
|
||||
let (guest, report) = first_part(budget);
|
||||
assert_eq!(report.outcome, Outcome::BudgetExhausted, "{budget}");
|
||||
assert_eq!(guest.clock.performance_count(), 0, "{budget}");
|
||||
}
|
||||
// One retry more: there is budget left for the result of the sleep.
|
||||
assert_eq!(
|
||||
first_part(blocks + 2).0.clock.performance_count(),
|
||||
10_000_000
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_thread_that_ends_with_its_wait_is_noticed_at_once() {
|
||||
for quantum in QUANTA {
|
||||
// Neither a deadlock nor the longer timeout of the thread waiting for it.
|
||||
let run = run_with("main_ends_in_a_wait", quantum, BUDGET).halted();
|
||||
assert_eq!(run.outs(3), [0, 0, 258], "quantum {quantum}");
|
||||
assert_eq!(run.clock.performance_count(), 1_000_000);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_thread_that_ended_cannot_be_opened_by_its_id() {
|
||||
for quantum in QUANTA {
|
||||
let run = run_with("main_reopened", quantum, BUDGET);
|
||||
assert_eq!(run.report.outcome, Outcome::AllThreadsExited);
|
||||
// ERROR_INVALID_PARAMETER.
|
||||
assert_eq!(run.outs(4), [1, 1, 0, 87], "quantum {quantum}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_signaled_object_goes_to_the_waiting_thread() {
|
||||
for quantum in [256, 1024, 1_000_000] {
|
||||
let run = run_with("main_handoff", quantum, BUDGET).halted();
|
||||
// Not available again, and the waiter has not run when the call
|
||||
// returns: for a mutex, a semaphore and an event.
|
||||
assert_eq!(
|
||||
run.outs(11),
|
||||
[258, 0, 1, 258, 1, 2, 258, 2, 3, 0, 1],
|
||||
"quantum {quantum}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_suspended_waiter_takes_nothing() {
|
||||
for quantum in QUANTA {
|
||||
let run = run_with("main_suspended_waiter", quantum, BUDGET).halted();
|
||||
assert_eq!(run.outs(4), [0, 0, 0, 1], "quantum {quantum}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opened_handles_carry_only_their_rights() {
|
||||
let run = run("main_rights").halted();
|
||||
assert_eq!(
|
||||
run.outs(13),
|
||||
[
|
||||
FAILED, 5, 0, 5, 1, 259, // query only
|
||||
0, 1, 0, FAILED, 5, 0, // suspend only
|
||||
1,
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_privileged_halt_in_a_worker_is_a_fault_not_a_process_exit() {
|
||||
let run = run("main_worker_halts");
|
||||
assert!(
|
||||
matches!(
|
||||
run.report.outcome,
|
||||
Outcome::Fault { thread, reason: ExitReason::Halt, .. } if thread == MAIN_ID + 4
|
||||
),
|
||||
"{:?}",
|
||||
run.report.outcome
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_stacks_are_reused() {
|
||||
let run = run("main_reuse").halted();
|
||||
assert_eq!(run.memory.read_u64(COUNTER).unwrap(), 50);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_signals_do_not_starve_ready_threads() {
|
||||
for quantum in [1, 7, 64, 1024, 10_000] {
|
||||
let run = run_with("main_starve", quantum, 1_000_000).halted();
|
||||
assert_eq!(run.out(0), 1, "quantum {quantum}");
|
||||
// The main thread gave up its turn after about one quantum.
|
||||
assert!(run.out(1) <= quantum as u64, "{} at {quantum}", run.out(1));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locks_of_an_ended_thread_are_not_inherited() {
|
||||
for quantum in QUANTA {
|
||||
let run = run_with("main_orphaned_locks", quantum, BUDGET);
|
||||
// The second worker runs in the first one's slot. It owns nothing, and
|
||||
// completing an initialization it did not begin fails.
|
||||
assert_eq!(run.outs(5), [1, 1, 0, 0, 0], "quantum {quantum}");
|
||||
assert_eq!(run.out(7), 0);
|
||||
match run.report.outcome {
|
||||
Outcome::Halted => assert_eq!(run.out(5), 0),
|
||||
Outcome::Fault { thread, .. } => assert_eq!(thread, MAIN_ID + 8),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reader_writer_lock_of_an_ended_thread_cannot_be_released_by_another() {
|
||||
for main in ["main_orphaned_exclusive", "main_orphaned_shared"] {
|
||||
let run = run(main);
|
||||
assert!(
|
||||
matches!(run.report.outcome, Outcome::Fault { thread, .. } if thread == MAIN_ID + 8),
|
||||
"{main}: {:?}",
|
||||
run.report.outcome
|
||||
);
|
||||
assert_eq!(run.memory.read_u32(SHARED + 548).unwrap(), 0, "{main}");
|
||||
}
|
||||
assert_eq!(run("main_orphaned_shared").outs(2), [1, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_initializations_are_bounded() {
|
||||
let run = run_with("main_pending_bound", 1024, 200_000_000);
|
||||
assert!(
|
||||
matches!(run.report.outcome, Outcome::Fault { .. }),
|
||||
"{:?}",
|
||||
run.report.outcome
|
||||
);
|
||||
assert_eq!(run.memory.read_u64(COUNTER).unwrap(), 4096);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_worker_can_duplicate_its_own_pseudo_handle() {
|
||||
let run = run("main_duplicate").halted();
|
||||
assert_eq!(
|
||||
run.outs(9),
|
||||
[
|
||||
1, 1, 258, 1, // a real handle to the worker itself
|
||||
0, 50, // it has no priority to set
|
||||
0, 44, // signaled, with its exit code
|
||||
0, // the main thread's priority is unchanged
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_small_commitment_keeps_the_default_reservation() {
|
||||
let run = run("main_small_commit").halted();
|
||||
assert_eq!(run.out(0), (1..=200).sum::<u64>());
|
||||
let slot = |index: u64| run.memory.read_u64(SHARED + 264 + 8 * index).unwrap();
|
||||
assert!(
|
||||
slot(0) - slot(1) > 100_000,
|
||||
"the recursion really used the stack"
|
||||
);
|
||||
// With the flag the size is the reservation, rounded up to 64 KiB.
|
||||
let run = self::run("main_small_reservation");
|
||||
assert!(
|
||||
matches!(run.report.outcome, Outcome::Fault { .. }),
|
||||
"{:?}",
|
||||
run.report.outcome
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guest_allocations_cannot_block_or_free_thread_memory() {
|
||||
let run = run("main_area_taken").halted();
|
||||
assert_eq!(run.outs(3), [FIRST_SLOT, 1, 1]);
|
||||
let run = self::run("main_free_stack").halted();
|
||||
assert_eq!(run.outs(2), [0, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn threads_can_be_ended_in_every_state() {
|
||||
for quantum in [256, 1024, 1_000_000] {
|
||||
let run = run_with("main_terminations", quantum, BUDGET).halted();
|
||||
assert_eq!(
|
||||
run.outs(11),
|
||||
[
|
||||
1, 60, 0, // blocked: ended, and its wait consumed nothing
|
||||
1, 0, 61, 0, // suspended, then by itself; neither ran on
|
||||
0x80, 0, // both mutexes abandoned under wait-all, then normal
|
||||
FAILED, 156, // the 128th suspension is refused
|
||||
],
|
||||
"quantum {quantum}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_small_budget_stops_cleanly() {
|
||||
for main in ["main_limit", "main_mutex", "main_fifo"] {
|
||||
for quantum in [1, 64, 1024] {
|
||||
for budget in (1..1500).step_by(29) {
|
||||
let run = run_with(main, quantum, budget);
|
||||
assert!(!matches!(run.report.outcome, Outcome::Deadlock { .. }));
|
||||
// One block and one pass of retries may follow the limit.
|
||||
assert!(
|
||||
run.report.instructions < budget + 32,
|
||||
"{main} {quantum} {budget}: {}",
|
||||
run.report.instructions
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retrying_many_waiters_stays_within_the_budget() {
|
||||
// Up to 63 threads wait at once; a pass over all of them must stop.
|
||||
for budget in (1500..12_000).step_by(211) {
|
||||
let run = run_with("main_limit", 64, budget);
|
||||
assert!(!matches!(run.report.outcome, Outcome::Deadlock { .. }));
|
||||
assert!(
|
||||
run.report.instructions < budget + 32,
|
||||
"{budget}: {}",
|
||||
run.report.instructions
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_that_stopped_on_its_budget_keeps_main_thread_state() {
|
||||
let mut guest = guest("main_keeps_state");
|
||||
let mut cpu = guest.cpu.clone();
|
||||
let mut runs = 0;
|
||||
loop {
|
||||
let report = Scheduler::new(Arc::clone(&guest.state), 64)
|
||||
.run(&mut guest.engine, &mut guest.memory, &cpu, 500)
|
||||
.unwrap();
|
||||
runs += 1;
|
||||
if report.outcome == Outcome::Halted {
|
||||
break;
|
||||
}
|
||||
assert_eq!(report.outcome, Outcome::BudgetExhausted);
|
||||
cpu = report.main;
|
||||
}
|
||||
assert!(runs > 10, "{runs}");
|
||||
assert_eq!(guest.memory.read_u64(SHARED).unwrap(), 88);
|
||||
assert_eq!(guest.memory.read_u64(SHARED + 8).unwrap(), 77);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_ids_are_not_reused_by_a_later_run() {
|
||||
let mut first = guest("main_worker_halts");
|
||||
let mut threads = Vec::new();
|
||||
for _ in 0..3 {
|
||||
let report = Scheduler::new(Arc::clone(&first.state), 1024)
|
||||
.run(&mut first.engine, &mut first.memory, &first.cpu, BUDGET)
|
||||
.unwrap();
|
||||
let Outcome::Fault { thread, .. } = report.outcome else {
|
||||
panic!("{:?}", report.outcome);
|
||||
};
|
||||
threads.push(thread);
|
||||
}
|
||||
assert_eq!(threads, [MAIN_ID + 4, MAIN_ID + 8, MAIN_ID + 12]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn service_calls_that_end_a_turn_are_counted() {
|
||||
for (main, calls) in [
|
||||
("main_signals", 1000),
|
||||
("main_independent", 5),
|
||||
("main_mutex", 100),
|
||||
("main_fifo", 10),
|
||||
("main_churn", 100),
|
||||
("main_exits_first", 3),
|
||||
] {
|
||||
for quantum in QUANTA {
|
||||
let run = run_with(main, quantum, BUDGET);
|
||||
assert!(run.metrics.service_calls >= calls, "{main} {quantum}");
|
||||
assert_eq!(
|
||||
run.report.instructions,
|
||||
run.metrics.instructions_executed + run.metrics.service_calls,
|
||||
"{main} quantum {quantum}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+275
-227
@@ -1,227 +1,275 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Shared harness for runtime service tests: an original PE32+ image whose
|
||||
//! imports are bound to the standard service registry and called from
|
||||
//! translated guest code.
|
||||
|
||||
#![allow(dead_code)]
|
||||
|
||||
use std::sync::Arc;
|
||||
use xenora_loader::cpu::{CpuState, ExitReason, Register};
|
||||
use xenora_loader::dbt::DbtEngine;
|
||||
use xenora_loader::imports::ImportRegistry;
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
use xenora_loader::pe::ParsedPe;
|
||||
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
|
||||
|
||||
pub const BASE: u64 = 0x1_4000_0000;
|
||||
pub const CODE_RVA: u32 = 0x1000;
|
||||
const IDATA_RVA: u32 = 0x10000;
|
||||
const IDATA_RAW: usize = 0x2200;
|
||||
const IDATA_LEN: usize = 0x4000;
|
||||
pub const SCRATCH: u64 = 0x5_0000;
|
||||
pub const SCRATCH_LEN: u64 = 0x1000;
|
||||
pub const STACK: u64 = 0x8_0000;
|
||||
pub const STACK_TOP: u64 = STACK + 0x800;
|
||||
pub const THREAD_A: u64 = 0x7_0000;
|
||||
pub const THREAD_B: u64 = 0x7_2000;
|
||||
/// Guest routines start at this RVA in the text section, 32 bytes apart.
|
||||
pub const ROUTINES_RVA: u32 = 0x1800;
|
||||
pub const RUNTIME_LIMIT: ExitReason = ExitReason::IllegalInstruction(0xFE);
|
||||
|
||||
/// Guest address of routine `index`.
|
||||
pub fn routine(index: usize) -> u64 {
|
||||
BASE + u64::from(ROUTINES_RVA) + 32 * index as u64
|
||||
}
|
||||
|
||||
/// The code for import `n`, at RVA 0x1000 + 16n, is `call [its slot]; hlt`.
|
||||
/// Each import has its own descriptor.
|
||||
fn build(imports: &[(&str, &str)], routines: &[Vec<u8>]) -> Vec<u8> {
|
||||
let mut pe = vec![0u8; IDATA_RAW + IDATA_LEN];
|
||||
fn put(pe: &mut [u8], at: usize, bytes: &[u8]) {
|
||||
pe[at..at + bytes.len()].copy_from_slice(bytes);
|
||||
}
|
||||
put(&mut pe, 0, b"MZ");
|
||||
put(&mut pe, 0x3C, &0x80u32.to_le_bytes());
|
||||
put(&mut pe, 0x80, b"PE\0\0");
|
||||
put(&mut pe, 0x84, &0x8664u16.to_le_bytes());
|
||||
put(&mut pe, 0x86, &2u16.to_le_bytes());
|
||||
put(&mut pe, 0x94, &240u16.to_le_bytes());
|
||||
let optional = 0x98;
|
||||
put(&mut pe, optional, &0x20Bu16.to_le_bytes());
|
||||
put(&mut pe, optional + 16, &CODE_RVA.to_le_bytes());
|
||||
put(&mut pe, optional + 24, &BASE.to_le_bytes());
|
||||
put(&mut pe, optional + 32, &0x1000u32.to_le_bytes());
|
||||
put(&mut pe, optional + 36, &0x200u32.to_le_bytes());
|
||||
put(&mut pe, optional + 56, &0x20000u32.to_le_bytes());
|
||||
put(&mut pe, optional + 60, &0x200u32.to_le_bytes());
|
||||
put(&mut pe, optional + 108, &16u32.to_le_bytes());
|
||||
put(&mut pe, optional + 120, &IDATA_RVA.to_le_bytes());
|
||||
put(&mut pe, optional + 124, &0x100u32.to_le_bytes());
|
||||
for (index, (name, rva, raw, len, flags)) in [
|
||||
(b".text", CODE_RVA, 0x200, 0x2000, 0x6000_0020u32),
|
||||
(b".idat", IDATA_RVA, IDATA_RAW, IDATA_LEN, 0xC000_0040),
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let section = optional + 240 + 40 * index;
|
||||
put(&mut pe, section, name);
|
||||
put(&mut pe, section + 8, &(len as u32).to_le_bytes());
|
||||
put(&mut pe, section + 12, &rva.to_le_bytes());
|
||||
put(&mut pe, section + 16, &(len as u32).to_le_bytes());
|
||||
put(&mut pe, section + 20, &(raw as u32).to_le_bytes());
|
||||
put(&mut pe, section + 36, &flags.to_le_bytes());
|
||||
}
|
||||
|
||||
assert!(16 * imports.len() <= (ROUTINES_RVA - CODE_RVA) as usize);
|
||||
let file = |rva: u32| IDATA_RAW + (rva - IDATA_RVA) as usize;
|
||||
let mut next = IDATA_RVA + 20 * (imports.len() as u32 + 1);
|
||||
let mut take = |len: usize| {
|
||||
let rva = next;
|
||||
next = (next + len as u32 + 7) & !7;
|
||||
rva
|
||||
};
|
||||
for (index, (module, symbol)) in imports.iter().enumerate() {
|
||||
let module_rva = take(module.len() + 1);
|
||||
put(&mut pe, file(module_rva), module.as_bytes());
|
||||
let hint = take(symbol.len() + 3);
|
||||
put(&mut pe, file(hint) + 2, symbol.as_bytes());
|
||||
let (lookup, slot) = (take(16), take(16));
|
||||
put(&mut pe, file(lookup), &u64::from(hint).to_le_bytes());
|
||||
put(&mut pe, file(slot), &u64::from(hint).to_le_bytes());
|
||||
let descriptor = file(IDATA_RVA) + 20 * index;
|
||||
put(&mut pe, descriptor, &lookup.to_le_bytes());
|
||||
put(&mut pe, descriptor + 12, &module_rva.to_le_bytes());
|
||||
put(&mut pe, descriptor + 16, &slot.to_le_bytes());
|
||||
|
||||
let code_rva = CODE_RVA + 16 * index as u32;
|
||||
let displacement = slot.wrapping_sub(code_rva + 6);
|
||||
let at = 0x200 + 16 * index;
|
||||
put(&mut pe, at, &[0xFF, 0x15]); // call qword ptr [rip + displacement]
|
||||
put(&mut pe, at + 2, &displacement.to_le_bytes());
|
||||
put(&mut pe, at + 6, &[0xF4]); // hlt
|
||||
}
|
||||
for (index, code) in routines.iter().enumerate() {
|
||||
assert!(code.len() <= 32);
|
||||
let at = 0x200 + (ROUTINES_RVA - CODE_RVA) as usize + 32 * index;
|
||||
put(&mut pe, at, code);
|
||||
}
|
||||
pe
|
||||
}
|
||||
|
||||
pub struct Guest {
|
||||
engine: DbtEngine,
|
||||
pub memory: GuestMemory,
|
||||
pub state: Arc<ServicesState>,
|
||||
imports: &'static [(&'static str, &'static str)],
|
||||
teb: u64,
|
||||
}
|
||||
|
||||
impl Guest {
|
||||
pub fn new(imports: &'static [(&'static str, &'static str)], routines: &[Vec<u8>]) -> Self {
|
||||
let state = ServicesState::new(Arc::new(MockClock::new(0)));
|
||||
Self::with_state(imports, routines, state)
|
||||
}
|
||||
|
||||
pub fn with_state(
|
||||
imports: &'static [(&'static str, &'static str)],
|
||||
routines: &[Vec<u8>],
|
||||
state: ServicesState,
|
||||
) -> Self {
|
||||
let bytes = build(imports, routines);
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
let mut memory = pe.load_into_memory(&bytes).unwrap().memory;
|
||||
memory
|
||||
.map_region(SCRATCH, SCRATCH_LEN as usize, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region(STACK, 0x1000, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
let state = Arc::new(state);
|
||||
let mut registry = ImportRegistry::new();
|
||||
register_standard_services(&mut registry, Arc::clone(&state));
|
||||
let bound = registry
|
||||
.bind_imports(&pe, &bytes, BASE, &mut memory)
|
||||
.unwrap();
|
||||
assert_eq!(bound, imports.len());
|
||||
let mut engine = DbtEngine::new(256 * 1024).unwrap();
|
||||
engine.set_import_registry(registry);
|
||||
Self {
|
||||
engine,
|
||||
memory,
|
||||
state,
|
||||
imports,
|
||||
teb: THREAD_A,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn on(&mut self, teb: u64) -> &mut Self {
|
||||
self.teb = teb;
|
||||
self
|
||||
}
|
||||
|
||||
/// Call an import with Win64 arguments. Arguments after the fourth go on
|
||||
/// the stack after the return address and the home area.
|
||||
pub fn run(&mut self, symbol: &str, args: &[u64]) -> (u64, ExitReason) {
|
||||
let index = self
|
||||
.imports
|
||||
.iter()
|
||||
.position(|(_, name)| *name == symbol)
|
||||
.unwrap_or_else(|| panic!("{symbol} is not imported"));
|
||||
let mut cpu = CpuState::new(BASE + u64::from(CODE_RVA) + 16 * index as u64, STACK_TOP);
|
||||
cpu.gs_base = self.teb;
|
||||
for (register, value) in [Register::Rcx, Register::Rdx, Register::R8, Register::R9]
|
||||
.into_iter()
|
||||
.zip(args)
|
||||
{
|
||||
cpu.set(register, *value);
|
||||
}
|
||||
for (slot, value) in args.iter().skip(4).enumerate() {
|
||||
let address = STACK_TOP + 32 + 8 * slot as u64;
|
||||
self.memory.write_u64(address, *value).unwrap();
|
||||
}
|
||||
use Register::{R12, R13, R14, R15, Rbp, Rbx, Rdi, Rsi};
|
||||
let nonvolatile = [Rbx, Rbp, Rdi, Rsi, R12, R13, R14, R15];
|
||||
for (index, register) in nonvolatile.into_iter().enumerate() {
|
||||
cpu.set(register, 0x5EED_0000 + index as u64);
|
||||
}
|
||||
let result = self.engine.run(&mut cpu, &mut self.memory, 100_000);
|
||||
if result.exit_reason == ExitReason::Halt {
|
||||
// The service returned to the instruction after its CALL.
|
||||
assert_eq!(cpu.get(Register::Rsp), STACK_TOP, "{symbol}");
|
||||
for (index, register) in nonvolatile.into_iter().enumerate() {
|
||||
assert_eq!(cpu.get(register), 0x5EED_0000 + index as u64, "{symbol}");
|
||||
}
|
||||
}
|
||||
(cpu.get(Register::Rax), result.exit_reason)
|
||||
}
|
||||
|
||||
pub fn call(&mut self, symbol: &str, args: &[u64]) -> u64 {
|
||||
let (rax, exit) = self.run(symbol, args);
|
||||
assert_eq!(exit, ExitReason::Halt, "{symbol}");
|
||||
rax
|
||||
}
|
||||
|
||||
pub fn fails(&mut self, symbol: &str, args: &[u64]) -> ExitReason {
|
||||
let (_, exit) = self.run(symbol, args);
|
||||
assert_ne!(exit, ExitReason::Halt, "{symbol} should stop the guest");
|
||||
exit
|
||||
}
|
||||
|
||||
pub fn error(&mut self) -> u64 {
|
||||
self.call("GetLastError", &[])
|
||||
}
|
||||
|
||||
pub fn u16_at(&self, address: u64) -> u16 {
|
||||
self.memory.read_u16(address).unwrap()
|
||||
}
|
||||
|
||||
pub fn u32_at(&self, address: u64) -> u32 {
|
||||
self.memory.read_u32(address).unwrap()
|
||||
}
|
||||
|
||||
pub fn u64_at(&self, address: u64) -> u64 {
|
||||
self.memory.read_u64(address).unwrap()
|
||||
}
|
||||
}
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Shared harness for runtime service tests: an original PE32+ image whose
|
||||
//! imports are bound to the standard service registry and called from
|
||||
//! translated guest code.
|
||||
|
||||
#![allow(dead_code)]
|
||||
|
||||
pub mod robustness;
|
||||
|
||||
use std::sync::Arc;
|
||||
use xenora_loader::cpu::{CpuState, ExitReason, Register};
|
||||
use xenora_loader::dbt::DbtEngine;
|
||||
use xenora_loader::imports::ImportRegistry;
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
use xenora_loader::pe::ParsedPe;
|
||||
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
|
||||
|
||||
pub const BASE: u64 = 0x1_4000_0000;
|
||||
pub const CODE_RVA: u32 = 0x1000;
|
||||
const IDATA_RVA: u32 = 0x10000;
|
||||
const IDATA_RAW: usize = 0x2200;
|
||||
const IDATA_LEN: usize = 0x4000;
|
||||
pub const SCRATCH: u64 = 0x5_0000;
|
||||
pub const SCRATCH_LEN: u64 = 0x1000;
|
||||
pub const STACK: u64 = 0x8_0000;
|
||||
pub const STACK_TOP: u64 = STACK + 0x800;
|
||||
pub const THREAD_A: u64 = 0x7_0000;
|
||||
pub const THREAD_B: u64 = 0x7_2000;
|
||||
/// Guest routines start at this RVA in the text section, 64 bytes apart.
|
||||
pub const ROUTINES_RVA: u32 = 0x1800;
|
||||
pub const ROUTINE_SIZE: usize = 64;
|
||||
pub const RUNTIME_LIMIT: ExitReason = ExitReason::IllegalInstruction(0xFE);
|
||||
|
||||
/// Guest address of routine `index`.
|
||||
pub fn routine(index: usize) -> u64 {
|
||||
BASE + u64::from(ROUTINES_RVA) + (ROUTINE_SIZE * index) as u64
|
||||
}
|
||||
|
||||
/// Guest address of the import address table slot for `imports[index]`, as
|
||||
/// laid out by the image builder.
|
||||
pub fn import_slot(imports: &[(&str, &str)], index: usize) -> u64 {
|
||||
BASE + u64::from(build_image(imports, &[]).1[index])
|
||||
}
|
||||
|
||||
/// The code for import `n`, at RVA 0x1000 + 16n, is `call [its slot]; hlt`.
|
||||
/// Each import has its own descriptor.
|
||||
fn build_image(imports: &[(&str, &str)], routines: &[Vec<u8>]) -> (Vec<u8>, Vec<u32>) {
|
||||
let mut pe = vec![0u8; IDATA_RAW + IDATA_LEN];
|
||||
fn put(pe: &mut [u8], at: usize, bytes: &[u8]) {
|
||||
pe[at..at + bytes.len()].copy_from_slice(bytes);
|
||||
}
|
||||
put(&mut pe, 0, b"MZ");
|
||||
put(&mut pe, 0x3C, &0x80u32.to_le_bytes());
|
||||
put(&mut pe, 0x80, b"PE\0\0");
|
||||
put(&mut pe, 0x84, &0x8664u16.to_le_bytes());
|
||||
put(&mut pe, 0x86, &2u16.to_le_bytes());
|
||||
put(&mut pe, 0x94, &240u16.to_le_bytes());
|
||||
let optional = 0x98;
|
||||
put(&mut pe, optional, &0x20Bu16.to_le_bytes());
|
||||
put(&mut pe, optional + 16, &CODE_RVA.to_le_bytes());
|
||||
put(&mut pe, optional + 24, &BASE.to_le_bytes());
|
||||
put(&mut pe, optional + 32, &0x1000u32.to_le_bytes());
|
||||
put(&mut pe, optional + 36, &0x200u32.to_le_bytes());
|
||||
put(&mut pe, optional + 56, &0x20000u32.to_le_bytes());
|
||||
put(&mut pe, optional + 60, &0x200u32.to_le_bytes());
|
||||
put(&mut pe, optional + 108, &16u32.to_le_bytes());
|
||||
put(&mut pe, optional + 120, &IDATA_RVA.to_le_bytes());
|
||||
put(&mut pe, optional + 124, &0x100u32.to_le_bytes());
|
||||
for (index, (name, rva, raw, len, flags)) in [
|
||||
(b".text", CODE_RVA, 0x200, 0x2000, 0x6000_0020u32),
|
||||
(b".idat", IDATA_RVA, IDATA_RAW, IDATA_LEN, 0xC000_0040),
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let section = optional + 240 + 40 * index;
|
||||
put(&mut pe, section, name);
|
||||
put(&mut pe, section + 8, &(len as u32).to_le_bytes());
|
||||
put(&mut pe, section + 12, &rva.to_le_bytes());
|
||||
put(&mut pe, section + 16, &(len as u32).to_le_bytes());
|
||||
put(&mut pe, section + 20, &(raw as u32).to_le_bytes());
|
||||
put(&mut pe, section + 36, &flags.to_le_bytes());
|
||||
}
|
||||
|
||||
assert!(16 * imports.len() <= (ROUTINES_RVA - CODE_RVA) as usize);
|
||||
let file = |rva: u32| IDATA_RAW + (rva - IDATA_RVA) as usize;
|
||||
let mut next = IDATA_RVA + 20 * (imports.len() as u32 + 1);
|
||||
let mut take = |len: usize| {
|
||||
let rva = next;
|
||||
next = (next + len as u32 + 7) & !7;
|
||||
rva
|
||||
};
|
||||
let mut slots = Vec::with_capacity(imports.len());
|
||||
for (index, (module, symbol)) in imports.iter().enumerate() {
|
||||
let module_rva = take(module.len() + 1);
|
||||
put(&mut pe, file(module_rva), module.as_bytes());
|
||||
let hint = take(symbol.len() + 3);
|
||||
put(&mut pe, file(hint) + 2, symbol.as_bytes());
|
||||
let (lookup, slot) = (take(16), take(16));
|
||||
put(&mut pe, file(lookup), &u64::from(hint).to_le_bytes());
|
||||
put(&mut pe, file(slot), &u64::from(hint).to_le_bytes());
|
||||
let descriptor = file(IDATA_RVA) + 20 * index;
|
||||
put(&mut pe, descriptor, &lookup.to_le_bytes());
|
||||
put(&mut pe, descriptor + 12, &module_rva.to_le_bytes());
|
||||
put(&mut pe, descriptor + 16, &slot.to_le_bytes());
|
||||
slots.push(slot);
|
||||
|
||||
let code_rva = CODE_RVA + 16 * index as u32;
|
||||
let displacement = slot.wrapping_sub(code_rva + 6);
|
||||
let at = 0x200 + 16 * index;
|
||||
put(&mut pe, at, &[0xFF, 0x15]); // call qword ptr [rip + displacement]
|
||||
put(&mut pe, at + 2, &displacement.to_le_bytes());
|
||||
put(&mut pe, at + 6, &[0xF4]); // hlt
|
||||
}
|
||||
for (index, code) in routines.iter().enumerate() {
|
||||
assert!(code.len() <= ROUTINE_SIZE);
|
||||
let at = 0x200 + (ROUTINES_RVA - CODE_RVA) as usize + ROUTINE_SIZE * index;
|
||||
put(&mut pe, at, code);
|
||||
}
|
||||
(pe, slots)
|
||||
}
|
||||
|
||||
pub struct Guest {
|
||||
engine: DbtEngine,
|
||||
pub memory: GuestMemory,
|
||||
pub state: Arc<ServicesState>,
|
||||
imports: &'static [(&'static str, &'static str)],
|
||||
teb: u64,
|
||||
}
|
||||
|
||||
impl Guest {
|
||||
pub fn new(imports: &'static [(&'static str, &'static str)], routines: &[Vec<u8>]) -> Self {
|
||||
let state = ServicesState::new(Arc::new(MockClock::new(0)));
|
||||
Self::with_state(imports, routines, state)
|
||||
}
|
||||
|
||||
pub fn with_state(
|
||||
imports: &'static [(&'static str, &'static str)],
|
||||
routines: &[Vec<u8>],
|
||||
state: ServicesState,
|
||||
) -> Self {
|
||||
let (bytes, _) = build_image(imports, routines);
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
let mut memory = pe.load_into_memory(&bytes).unwrap().memory;
|
||||
memory
|
||||
.map_region(SCRATCH, SCRATCH_LEN as usize, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region(STACK, 0x1000, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
let state = Arc::new(state);
|
||||
let mut registry = ImportRegistry::new();
|
||||
register_standard_services(&mut registry, Arc::clone(&state));
|
||||
let bound = registry
|
||||
.bind_imports(&pe, &bytes, BASE, &mut memory)
|
||||
.unwrap();
|
||||
assert_eq!(bound, imports.len());
|
||||
let mut engine = DbtEngine::new(256 * 1024).unwrap();
|
||||
engine.set_import_registry(registry);
|
||||
Self {
|
||||
engine,
|
||||
memory,
|
||||
state,
|
||||
imports,
|
||||
teb: THREAD_A,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn on(&mut self, teb: u64) -> &mut Self {
|
||||
self.teb = teb;
|
||||
self
|
||||
}
|
||||
|
||||
/// Call an import with Win64 arguments. Arguments after the fourth go on
|
||||
/// the stack after the return address and the home area.
|
||||
pub fn run(&mut self, symbol: &str, args: &[u64]) -> (u64, ExitReason) {
|
||||
let index = self
|
||||
.imports
|
||||
.iter()
|
||||
.position(|(_, name)| *name == symbol)
|
||||
.unwrap_or_else(|| panic!("{symbol} is not imported"));
|
||||
let mut cpu = CpuState::new(BASE + u64::from(CODE_RVA) + 16 * index as u64, STACK_TOP);
|
||||
cpu.gs_base = self.teb;
|
||||
for (register, value) in [Register::Rcx, Register::Rdx, Register::R8, Register::R9]
|
||||
.into_iter()
|
||||
.zip(args)
|
||||
{
|
||||
cpu.set(register, *value);
|
||||
}
|
||||
for (slot, value) in args.iter().skip(4).enumerate() {
|
||||
let address = STACK_TOP + 32 + 8 * slot as u64;
|
||||
self.memory.write_u64(address, *value).unwrap();
|
||||
}
|
||||
use Register::{R12, R13, R14, R15, Rbp, Rbx, Rdi, Rsi};
|
||||
let nonvolatile = [Rbx, Rbp, Rdi, Rsi, R12, R13, R14, R15];
|
||||
for (index, register) in nonvolatile.into_iter().enumerate() {
|
||||
cpu.set(register, 0x5EED_0000 + index as u64);
|
||||
}
|
||||
let result = self.engine.run(&mut cpu, &mut self.memory, 100_000);
|
||||
if result.exit_reason == ExitReason::Halt {
|
||||
// The service returned to the instruction after its CALL.
|
||||
assert_eq!(cpu.get(Register::Rsp), STACK_TOP, "{symbol}");
|
||||
for (index, register) in nonvolatile.into_iter().enumerate() {
|
||||
assert_eq!(cpu.get(register), 0x5EED_0000 + index as u64, "{symbol}");
|
||||
}
|
||||
}
|
||||
(cpu.get(Register::Rax), result.exit_reason)
|
||||
}
|
||||
|
||||
/// Call an import as the main thread of a scheduled run: the engine runs
|
||||
/// in slices of `quantum` instructions under the guest thread scheduler.
|
||||
pub fn scheduled(
|
||||
&mut self,
|
||||
symbol: &str,
|
||||
args: &[u64],
|
||||
quantum: usize,
|
||||
budget: usize,
|
||||
) -> xenora_loader::scheduler::ScheduleReport {
|
||||
let index = self
|
||||
.imports
|
||||
.iter()
|
||||
.position(|(_, name)| *name == symbol)
|
||||
.unwrap_or_else(|| panic!("{symbol} is not imported"));
|
||||
let mut cpu = CpuState::new(BASE + u64::from(CODE_RVA) + 16 * index as u64, STACK_TOP);
|
||||
cpu.gs_base = self.teb;
|
||||
for (register, value) in [Register::Rcx, Register::Rdx, Register::R8, Register::R9]
|
||||
.into_iter()
|
||||
.zip(args)
|
||||
{
|
||||
cpu.set(register, *value);
|
||||
}
|
||||
xenora_loader::scheduler::Scheduler::new(Arc::clone(&self.state), quantum)
|
||||
.run(&mut self.engine, &mut self.memory, &cpu, budget)
|
||||
.expect("the scheduler attaches")
|
||||
}
|
||||
|
||||
/// Run guest code from `entry` on the calling thread's TEB until it stops.
|
||||
pub fn execute(&mut self, entry: u64, max_instructions: usize) -> (CpuState, ExitReason) {
|
||||
let mut cpu = CpuState::new(entry, STACK_TOP);
|
||||
cpu.gs_base = self.teb;
|
||||
let result = self
|
||||
.engine
|
||||
.run(&mut cpu, &mut self.memory, max_instructions);
|
||||
(cpu, result.exit_reason)
|
||||
}
|
||||
|
||||
pub fn call(&mut self, symbol: &str, args: &[u64]) -> u64 {
|
||||
let (rax, exit) = self.run(symbol, args);
|
||||
assert_eq!(exit, ExitReason::Halt, "{symbol}");
|
||||
rax
|
||||
}
|
||||
|
||||
pub fn fails(&mut self, symbol: &str, args: &[u64]) -> ExitReason {
|
||||
let (_, exit) = self.run(symbol, args);
|
||||
assert_ne!(exit, ExitReason::Halt, "{symbol} should stop the guest");
|
||||
exit
|
||||
}
|
||||
|
||||
pub fn error(&mut self) -> u64 {
|
||||
self.call("GetLastError", &[])
|
||||
}
|
||||
|
||||
pub fn u16_at(&self, address: u64) -> u16 {
|
||||
self.memory.read_u16(address).unwrap()
|
||||
}
|
||||
|
||||
pub fn u32_at(&self, address: u64) -> u32 {
|
||||
self.memory.read_u32(address).unwrap()
|
||||
}
|
||||
|
||||
pub fn u64_at(&self, address: u64) -> u64 {
|
||||
self.memory.read_u64(address).unwrap()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Drives sequences of standard runtime services with adversarial arguments.
|
||||
//!
|
||||
//! Shared by the `runtime_services` libFuzzer target and the stable-toolchain
|
||||
//! regression test. Writable guest memory is filled from a deterministic
|
||||
//! pattern, not from the fuzz input, so short corpora still reach the dispatch
|
||||
//! loop. Each call takes its arguments from the remaining input: zero, all
|
||||
//! ones, pointers into writable, read-only and unmapped memory, raw values,
|
||||
//! small integers or an earlier result (so handles flow between calls). After
|
||||
//! every call the driver checks that read-only and code memory are unchanged
|
||||
//! and that the Win64 nonvolatile registers are preserved. A panic, a broken
|
||||
//! invariant or a hang is a bug.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::Arc;
|
||||
use xenora_loader::cpu::{CpuState, Register};
|
||||
use xenora_loader::imports::{ImportRegistry, Win64Args};
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
|
||||
|
||||
const WRITABLE: u64 = 0x5_0000;
|
||||
const WRITABLE_LEN: usize = 0x1_0000;
|
||||
const READ_ONLY: u64 = 0x7_0000;
|
||||
const CODE: u64 = 0x7_8000;
|
||||
const REGION_LEN: usize = 0x1000;
|
||||
const STACK: u64 = 0x9_0000;
|
||||
const STACK_LEN: usize = 0x2000;
|
||||
const UNMAPPED: u64 = 0xDEAD_0000;
|
||||
const MAX_CALLS: usize = 48;
|
||||
|
||||
/// Argument encoding mode that reuses an earlier handler result (handles).
|
||||
#[allow(dead_code)] // used by the stable-toolchain regression test
|
||||
pub const ARG_REUSE_RESULT: u8 = 8;
|
||||
/// Argument encoding mode that supplies zero.
|
||||
#[allow(dead_code)] // used by the stable-toolchain regression test
|
||||
pub const ARG_ZERO: u8 = 0;
|
||||
|
||||
/// Services that wait on real time, run guest code or reach native Metal are
|
||||
/// left out, so each input runs quickly and deterministically.
|
||||
fn excluded(module: &str, symbol: &str) -> bool {
|
||||
module.eq_ignore_ascii_case("xenora_fixture.dll")
|
||||
|| matches!(symbol, "WSAPoll" | "XTaskQueueDispatch")
|
||||
}
|
||||
|
||||
/// Outcome of one `Driver::run` against a single corpus input.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct RunStats {
|
||||
pub calls: usize,
|
||||
pub distinct_services: usize,
|
||||
}
|
||||
|
||||
pub struct Driver {
|
||||
services: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
impl Default for Driver {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl Driver {
|
||||
pub fn new() -> Self {
|
||||
let mut registry = ImportRegistry::new();
|
||||
register_standard_services(
|
||||
&mut registry,
|
||||
Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))),
|
||||
);
|
||||
let mut services: Vec<(String, String)> = registry
|
||||
.iter_registered()
|
||||
.filter(|(module, symbol, _)| !excluded(module, symbol))
|
||||
.map(|(module, symbol, _)| (module.to_owned(), symbol.to_owned()))
|
||||
.collect();
|
||||
services.sort();
|
||||
Self { services }
|
||||
}
|
||||
|
||||
#[allow(dead_code)] // used by the stable-toolchain regression test
|
||||
pub fn service_count(&self) -> usize {
|
||||
self.services.len()
|
||||
}
|
||||
|
||||
/// Index of `module!symbol` in the driver's sorted service table.
|
||||
#[allow(dead_code)] // used by the stable-toolchain regression test
|
||||
pub fn service_index(&self, module: &str, symbol: &str) -> Option<usize> {
|
||||
self.services
|
||||
.iter()
|
||||
.position(|(entry_module, entry_symbol)| {
|
||||
entry_module.eq_ignore_ascii_case(module) && entry_symbol == symbol
|
||||
})
|
||||
}
|
||||
|
||||
/// Encode a deterministic multi-call corpus.
|
||||
///
|
||||
/// Each entry is `(service_index, [arg_mode; 7])`. Argument offsets are
|
||||
/// zero; a trailing byte per call supplies the GS-base choice.
|
||||
#[allow(dead_code)] // used by the stable-toolchain regression test
|
||||
pub fn encode_sequence(&self, calls: &[(usize, [u8; 7])]) -> Vec<u8> {
|
||||
let mut bytes = Vec::with_capacity(calls.len() * (2 + 7 * 3 + 1));
|
||||
for &(index, modes) in calls {
|
||||
bytes.extend_from_slice(&(index as u16).to_le_bytes());
|
||||
for mode in modes {
|
||||
bytes.extend_from_slice(&0u16.to_le_bytes());
|
||||
bytes.push(mode);
|
||||
}
|
||||
bytes.push(0); // gs_base selector
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
/// Run one input against fresh service state and fresh guest memory.
|
||||
pub fn run(&self, data: &[u8]) -> RunStats {
|
||||
let mut registry = ImportRegistry::new();
|
||||
let clock = Arc::new(MockClock::new(0x01DA_0000_0000_0000));
|
||||
register_standard_services(&mut registry, Arc::new(ServicesState::new(clock)));
|
||||
|
||||
let mut input = Input(data);
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region(WRITABLE, WRITABLE_LEN, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region(STACK, STACK_LEN, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
// Deterministic fill: do not consume fuzz/corpus bytes here, or short
|
||||
// inputs never reach the dispatch loop (WRITABLE_LEN is 65,536).
|
||||
let fill: Vec<u8> = (0..WRITABLE_LEN)
|
||||
.map(|i| (i.wrapping_mul(131).wrapping_add(17)) as u8)
|
||||
.collect();
|
||||
memory.write_bytes(WRITABLE, &fill).unwrap();
|
||||
let read_only: Vec<u8> = (0..REGION_LEN).map(|i| (i * 7) as u8).collect();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
READ_ONLY,
|
||||
REGION_LEN,
|
||||
MemoryPermissions::READ_ONLY,
|
||||
&read_only,
|
||||
)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
CODE,
|
||||
REGION_LEN,
|
||||
MemoryPermissions::READ_EXECUTE,
|
||||
&[0xC3; REGION_LEN],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let mut results = vec![0u64];
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut calls = 0usize;
|
||||
for _ in 0..MAX_CALLS {
|
||||
let Some(selector) = input.u16() else { break };
|
||||
let index = selector as usize % self.services.len();
|
||||
let (module, symbol) = &self.services[index];
|
||||
let mut args = [0u64; 7];
|
||||
for arg in &mut args {
|
||||
*arg = input.argument(&results);
|
||||
}
|
||||
let rsp = STACK + STACK_LEN as u64 / 2;
|
||||
let mut cpu = CpuState::new(CODE, rsp);
|
||||
cpu.gs_base = [0x7_F000, 0x7_F800][input.byte_or(0) as usize % 2];
|
||||
for (register, value) in [Register::Rcx, Register::Rdx, Register::R8, Register::R9]
|
||||
.into_iter()
|
||||
.zip(args)
|
||||
{
|
||||
cpu.set(register, value);
|
||||
}
|
||||
for (slot, value) in args[4..].iter().enumerate() {
|
||||
memory
|
||||
.write_u64(rsp + 40 + 8 * slot as u64, *value)
|
||||
.unwrap();
|
||||
}
|
||||
use Register::{R12, R13, R14, R15, Rbp, Rbx, Rdi, Rsi, Rsp};
|
||||
let preserved = [Rbx, Rbp, Rdi, Rsi, Rsp, R12, R13, R14, R15];
|
||||
let before = preserved.map(|register| cpu.get(register));
|
||||
|
||||
let service = registry
|
||||
.binding(module, symbol)
|
||||
.expect("registered service");
|
||||
let outcome = (service.handler)(&Win64Args::new(&cpu), &mut cpu, &mut memory);
|
||||
|
||||
assert_eq!(
|
||||
preserved.map(|register| cpu.get(register)),
|
||||
before,
|
||||
"{module}!{symbol} changed a nonvolatile register"
|
||||
);
|
||||
let mut check = vec![0; REGION_LEN];
|
||||
memory.read_bytes(READ_ONLY, &mut check).unwrap();
|
||||
assert_eq!(check, read_only, "{module}!{symbol} wrote read-only memory");
|
||||
memory.read_bytes(CODE, &mut check).unwrap();
|
||||
assert!(
|
||||
check.iter().all(|&byte| byte == 0xC3),
|
||||
"{module}!{symbol} wrote code memory"
|
||||
);
|
||||
calls += 1;
|
||||
seen.insert((module.clone(), symbol.clone()));
|
||||
if let Ok(value) = outcome {
|
||||
results.push(value);
|
||||
}
|
||||
}
|
||||
RunStats {
|
||||
calls,
|
||||
distinct_services: seen.len(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Input<'a>(&'a [u8]);
|
||||
|
||||
impl Input<'_> {
|
||||
fn take<const N: usize>(&mut self) -> Option<[u8; N]> {
|
||||
let (head, rest) = self.0.split_first_chunk::<N>()?;
|
||||
self.0 = rest;
|
||||
Some(*head)
|
||||
}
|
||||
|
||||
fn byte_or(&mut self, default: u8) -> u8 {
|
||||
self.take::<1>().map_or(default, |[byte]| byte)
|
||||
}
|
||||
|
||||
fn u16(&mut self) -> Option<u16> {
|
||||
self.take::<2>().map(u16::from_le_bytes)
|
||||
}
|
||||
|
||||
fn argument(&mut self, results: &[u64]) -> u64 {
|
||||
let offset = u64::from(self.u16().unwrap_or(0));
|
||||
match self.byte_or(0) % 9 {
|
||||
0 => 0,
|
||||
1 => u64::MAX,
|
||||
2 => WRITABLE + offset % WRITABLE_LEN as u64,
|
||||
3 => READ_ONLY + offset % REGION_LEN as u64,
|
||||
4 => CODE + offset % REGION_LEN as u64,
|
||||
5 => UNMAPPED + offset,
|
||||
6 => self.take::<8>().map_or(offset, u64::from_le_bytes),
|
||||
7 => offset % 512,
|
||||
_ => results[offset as usize % results.len()],
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compile the guest thread programs with clang and list their code.
|
||||
|
||||
generate write program.txt next to this file
|
||||
--check recompile in memory and fail if the committed listing differs
|
||||
|
||||
program.txt holds one line per item: `code <hex>`, `entry <name> <offset>` and
|
||||
`import <name> <offset>` for each 32-bit RIP-relative reference to an import
|
||||
slot. Nothing is executed and no linker is needed: the test places the code and
|
||||
fills in the references. Only clang and the Python standard library are used.
|
||||
"""
|
||||
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
OUT = HERE / "program.txt"
|
||||
FLAGS = ["-target", "x86_64-pc-windows-msvc", "-O1", "-ffreestanding", "-fno-builtin", "-nostdinc",
|
||||
"-fno-stack-protector", "-fno-asynchronous-unwind-tables", "-mno-implicit-float",
|
||||
"-fno-jump-tables", "-fno-optimize-sibling-calls", "-fno-ident", "-Wno-infinite-recursion"]
|
||||
REL32 = range(4, 10) # IMAGE_REL_AMD64_REL32 to REL32_5
|
||||
|
||||
|
||||
def listing():
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
obj = Path(directory, "program.obj")
|
||||
subprocess.run(["clang", *FLAGS, "-c", HERE / "program.c", "-o", obj], check=True)
|
||||
data = obj.read_bytes()
|
||||
machine, sections, _, symbols_at, symbol_count, optional, _ = struct.unpack_from("<HHIIIHH", data)
|
||||
assert machine == 0x8664
|
||||
strings = symbols_at + 18 * symbol_count
|
||||
|
||||
def name_at(raw):
|
||||
if raw[:4] == b"\0\0\0\0":
|
||||
start = strings + struct.unpack_from("<I", raw, 4)[0]
|
||||
return data[start:data.index(b"\0", start)].decode()
|
||||
return raw.rstrip(b"\0").decode()
|
||||
|
||||
symbols, index = {}, 0
|
||||
while index < symbol_count:
|
||||
raw = data[symbols_at + 18 * index:symbols_at + 18 * (index + 1)]
|
||||
value, section, _, storage, extra = struct.unpack_from("<IhHBB", raw, 8)
|
||||
symbols[index] = (name_at(raw[:8]), value, section, storage)
|
||||
index += 1 + extra
|
||||
text = None
|
||||
for number in range(sections):
|
||||
fields = struct.unpack_from("<8sIIIIIIHHI", data, 20 + optional + 40 * number)
|
||||
name, size = fields[0].rstrip(b"\0").decode(), fields[3]
|
||||
if name == ".text":
|
||||
text = (number + 1, size, fields[4], fields[5], fields[7])
|
||||
elif size and name in (".data", ".rdata", ".bss"):
|
||||
sys.exit(f"unexpected {name} of {size} bytes")
|
||||
number, size, at, relocations_at, count = text
|
||||
code = bytearray(data[at:at + size])
|
||||
imports = []
|
||||
for index in range(count):
|
||||
offset, symbol, kind = struct.unpack_from("<IIH", data, relocations_at + 10 * index)
|
||||
target, value, section, _ = symbols[symbol]
|
||||
if kind not in REL32:
|
||||
sys.exit(f"relocation type {kind} against {target}")
|
||||
trailing = kind - 4
|
||||
if section == number:
|
||||
addend = struct.unpack_from("<i", code, offset)[0]
|
||||
struct.pack_into("<i", code, offset, value + addend - (offset + 4 + trailing))
|
||||
elif target.startswith("__imp_") and trailing == 0:
|
||||
imports.append((target[6:], offset))
|
||||
else:
|
||||
sys.exit(f"unresolved reference to {target}")
|
||||
lines = [f"entry {name} {value}" for name, value, section, storage in sorted(symbols.values())
|
||||
if section == number and storage == 2 and name.startswith("main_")]
|
||||
lines += [f"import {name} {offset}" for name, offset in imports]
|
||||
lines += [f"code {code[i:i + 32].hex()}" for i in range(0, len(code), 32)]
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) != 2 or argv[1] not in ("generate", "--check"):
|
||||
sys.exit("usage: compile.py generate|--check")
|
||||
text = listing()
|
||||
if argv[1] == "generate":
|
||||
OUT.write_text(text)
|
||||
elif OUT.read_text() != text:
|
||||
sys.exit("program.txt differs from the compiler output")
|
||||
print(f"{text.count('entry ')} programs, {text.count('import ')} import references, {32 * text.count('code ')} bytes")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv)
|
||||
@@ -0,0 +1,806 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//
|
||||
// Original guest programs for the thread scheduler tests. Each `main_*`
|
||||
// function is run as the main guest thread and stores what it observed in the
|
||||
// shared block, which the test maps at a fixed address.
|
||||
|
||||
typedef unsigned long long u64;
|
||||
typedef unsigned int u32;
|
||||
typedef void *HANDLE;
|
||||
typedef u32 (*START)(void *);
|
||||
|
||||
#define IMPORT __declspec(dllimport)
|
||||
IMPORT HANDLE CreateThread(void *, u64, START, void *, u32, u32 *);
|
||||
IMPORT void ExitThread(u32);
|
||||
IMPORT int TerminateThread(HANDLE, u32);
|
||||
IMPORT int GetExitCodeThread(HANDLE, u32 *);
|
||||
IMPORT u32 SuspendThread(HANDLE);
|
||||
IMPORT u32 ResumeThread(HANDLE);
|
||||
IMPORT int SwitchToThread(void);
|
||||
IMPORT u32 GetCurrentThreadId(void);
|
||||
IMPORT u32 GetThreadId(HANDLE);
|
||||
IMPORT HANDLE OpenThread(u32, int, u32);
|
||||
IMPORT u32 WaitForSingleObject(HANDLE, u32);
|
||||
IMPORT u32 WaitForMultipleObjects(u32, const HANDLE *, int, u32);
|
||||
IMPORT HANDLE CreateEventA(void *, int, int, const char *);
|
||||
IMPORT int SetEvent(HANDLE);
|
||||
IMPORT HANDLE CreateMutexA(void *, int, const char *);
|
||||
IMPORT int ReleaseMutex(HANDLE);
|
||||
IMPORT HANDLE CreateSemaphoreA(void *, int, int, const char *);
|
||||
IMPORT int ReleaseSemaphore(HANDLE, int, int *);
|
||||
IMPORT int CloseHandle(HANDLE);
|
||||
IMPORT u32 GetLastError(void);
|
||||
IMPORT void SetLastError(u32);
|
||||
IMPORT u32 TlsAlloc(void);
|
||||
IMPORT void *TlsGetValue(u32);
|
||||
IMPORT int TlsSetValue(u32, void *);
|
||||
IMPORT int *_errno(void);
|
||||
IMPORT void InitializeCriticalSection(void *);
|
||||
IMPORT void EnterCriticalSection(void *);
|
||||
IMPORT int TryEnterCriticalSection(void *);
|
||||
IMPORT void LeaveCriticalSection(void *);
|
||||
IMPORT void AcquireSRWLockExclusive(void *);
|
||||
IMPORT void AcquireSRWLockShared(void *);
|
||||
IMPORT void ReleaseSRWLockExclusive(void *);
|
||||
IMPORT void ReleaseSRWLockShared(void *);
|
||||
IMPORT u32 TryAcquireSRWLockExclusive(void *);
|
||||
IMPORT u32 TryAcquireSRWLockShared(void *);
|
||||
IMPORT int InitOnceBeginInitialize(void *, u32, int *, void **);
|
||||
IMPORT int InitOnceComplete(void *, u32, void *);
|
||||
IMPORT int DuplicateHandle(HANDLE, HANDLE, HANDLE, HANDLE *, u32, int, u32);
|
||||
IMPORT int SetThreadPriority(HANDLE, int);
|
||||
IMPORT int GetThreadPriority(HANDLE);
|
||||
IMPORT void *VirtualAlloc(void *, u64, u32, u32);
|
||||
IMPORT int VirtualFree(void *, u64, u32);
|
||||
|
||||
#define INFINITE 0xFFFFFFFFu
|
||||
#define THREAD(n) ((void *)(u64)(n))
|
||||
struct shared {
|
||||
volatile u64 out[32];
|
||||
volatile u64 counter;
|
||||
volatile u64 slots[16];
|
||||
HANDLE handles[16];
|
||||
HANDLE a, b, c;
|
||||
volatile u32 tls;
|
||||
volatile u32 flag;
|
||||
u64 section[5], srw, once;
|
||||
};
|
||||
#define S ((struct shared *)0x50000)
|
||||
|
||||
static HANDLE spawn(START start, u64 parameter) {
|
||||
return CreateThread(0, 0, start, THREAD(parameter), 0, 0);
|
||||
}
|
||||
|
||||
static void join(HANDLE thread) {
|
||||
WaitForSingleObject(thread, INFINITE);
|
||||
CloseHandle(thread);
|
||||
}
|
||||
|
||||
// --- independent functions and exit codes --------------------------------
|
||||
static u32 fibonacci(void *n) {
|
||||
u64 a = 0, b = 1;
|
||||
for (u64 i = 0; i < (u64)n; i++) {
|
||||
u64 next = a + b;
|
||||
a = b;
|
||||
b = next;
|
||||
}
|
||||
S->out[0] = a;
|
||||
return 11;
|
||||
}
|
||||
|
||||
static u32 collatz(void *n) {
|
||||
u64 value = (u64)n, steps = 0;
|
||||
while (value != 1) {
|
||||
value = value & 1 ? 3 * value + 1 : value >> 1;
|
||||
steps++;
|
||||
}
|
||||
S->out[1] = steps;
|
||||
return 22;
|
||||
}
|
||||
|
||||
void main_independent(void) {
|
||||
u32 id = 0, code = 0;
|
||||
S->handles[0] = CreateThread(0, 0, fibonacci, THREAD(80), 0, &id);
|
||||
S->handles[1] = spawn(collatz, 97);
|
||||
S->out[2] = WaitForMultipleObjects(2, S->handles, 1, INFINITE);
|
||||
GetExitCodeThread(S->handles[0], &code);
|
||||
S->out[3] = code;
|
||||
GetExitCodeThread(S->handles[1], &code);
|
||||
S->out[4] = code;
|
||||
S->out[5] = id == GetThreadId(S->handles[0]);
|
||||
S->out[6] = id != GetCurrentThreadId();
|
||||
}
|
||||
|
||||
// --- shared counters -------------------------------------------------------
|
||||
#define ROUNDS 200
|
||||
// Uses the previous value, so the compiler emits LOCK XADD.
|
||||
static u32 atomic_worker(void *unused) {
|
||||
u64 seen = 0;
|
||||
for (int i = 0; i < ROUNDS; i++) {
|
||||
seen |= __atomic_fetch_add(&S->counter, 1, __ATOMIC_SEQ_CST);
|
||||
if ((i & 7) == 0) SwitchToThread();
|
||||
}
|
||||
return (u32)seen;
|
||||
}
|
||||
|
||||
static u32 racy_worker(void *unused) {
|
||||
for (int i = 0; i < ROUNDS; i++) {
|
||||
u64 value = S->counter;
|
||||
SwitchToThread();
|
||||
S->counter = value + 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static u32 mutex_worker(void *unused) {
|
||||
for (int i = 0; i < ROUNDS; i++) {
|
||||
WaitForSingleObject(S->a, INFINITE);
|
||||
u64 value = S->counter;
|
||||
SwitchToThread();
|
||||
S->counter = value + 1;
|
||||
ReleaseMutex(S->a);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void run_four(START start) {
|
||||
for (int i = 0; i < 4; i++) S->handles[i] = spawn(start, i);
|
||||
S->out[0] = WaitForMultipleObjects(4, S->handles, 1, INFINITE);
|
||||
S->out[1] = S->counter;
|
||||
}
|
||||
void main_atomic(void) { run_four(atomic_worker); }
|
||||
void main_racy(void) { run_four(racy_worker); }
|
||||
void main_mutex(void) {
|
||||
S->a = CreateMutexA(0, 0, 0);
|
||||
run_four(mutex_worker);
|
||||
}
|
||||
|
||||
// --- blocking and resuming -------------------------------------------------
|
||||
static u32 consumer(void *unused) {
|
||||
u64 sum = 0;
|
||||
for (int i = 0; i < 50; i++) {
|
||||
WaitForSingleObject(S->a, INFINITE);
|
||||
sum = sum * 31 + S->slots[0];
|
||||
SetEvent(S->b);
|
||||
}
|
||||
S->out[0] = sum;
|
||||
return 0;
|
||||
}
|
||||
|
||||
void main_producer(void) {
|
||||
S->a = CreateEventA(0, 0, 0, 0);
|
||||
S->b = CreateEventA(0, 0, 0, 0);
|
||||
HANDLE thread = spawn(consumer, 0);
|
||||
for (int i = 0; i < 50; i++) {
|
||||
S->slots[0] = i + 1;
|
||||
SetEvent(S->a);
|
||||
WaitForSingleObject(S->b, INFINITE);
|
||||
}
|
||||
join(thread);
|
||||
S->out[1] = 1;
|
||||
}
|
||||
|
||||
static u32 ordered_waiter(void *index) {
|
||||
WaitForSingleObject(S->a, INFINITE);
|
||||
u64 position = __atomic_fetch_add(&S->counter, 1, __ATOMIC_SEQ_CST);
|
||||
S->out[position] = (u64)index;
|
||||
return 0;
|
||||
}
|
||||
|
||||
// One auto-reset signal releases exactly one waiter, and the setter cannot
|
||||
// take it back from a thread that was already waiting.
|
||||
void main_fifo(void) {
|
||||
S->a = CreateEventA(0, 0, 0, 0);
|
||||
for (int i = 0; i < 4; i++) S->handles[i] = spawn(ordered_waiter, 10 + i);
|
||||
for (int i = 0; i < 20; i++) SwitchToThread();
|
||||
S->out[8] = S->counter;
|
||||
SetEvent(S->a);
|
||||
S->out[9] = WaitForSingleObject(S->a, 0);
|
||||
for (int i = 0; i < 20; i++) SwitchToThread();
|
||||
S->out[10] = S->counter;
|
||||
for (int i = 0; i < 3; i++) SetEvent(S->a);
|
||||
WaitForMultipleObjects(4, S->handles, 1, INFINITE);
|
||||
}
|
||||
|
||||
void main_timeout(void) {
|
||||
S->a = CreateEventA(0, 1, 0, 0);
|
||||
S->out[0] = WaitForSingleObject(S->a, 250);
|
||||
S->out[1] = WaitForSingleObject(S->a, 0);
|
||||
SetEvent(S->a);
|
||||
S->out[2] = WaitForSingleObject(S->a, 250);
|
||||
}
|
||||
|
||||
static u32 late_signal(void *unused) {
|
||||
WaitForSingleObject(S->b, 40);
|
||||
SetEvent(S->a);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void main_signal_before_timeout(void) {
|
||||
S->a = CreateEventA(0, 0, 0, 0);
|
||||
S->b = CreateEventA(0, 0, 0, 0);
|
||||
HANDLE thread = spawn(late_signal, 0);
|
||||
S->out[0] = WaitForSingleObject(S->a, 100);
|
||||
S->out[1] = WaitForSingleObject(S->a, 100);
|
||||
join(thread);
|
||||
}
|
||||
|
||||
// --- per-thread state ------------------------------------------------------
|
||||
static u32 isolated(void *index) {
|
||||
u64 n = (u64)index;
|
||||
u32 clean = GetLastError() == 0 && TlsGetValue(S->tls) == 0 && *_errno() == 0;
|
||||
TlsSetValue(S->tls, THREAD(n * 1000 + 7));
|
||||
*_errno() = (int)n + 40;
|
||||
SetLastError((u32)n + 500);
|
||||
u32 id = GetCurrentThreadId();
|
||||
for (int i = 0; i < 10; i++) SwitchToThread();
|
||||
u32 error = GetLastError();
|
||||
u32 good = clean && error == n + 500 && TlsGetValue(S->tls) == THREAD(n * 1000 + 7)
|
||||
&& *_errno() == (int)n + 40 && id == GetCurrentThreadId();
|
||||
S->slots[n] = id;
|
||||
return good;
|
||||
}
|
||||
|
||||
void main_isolated(void) {
|
||||
S->tls = TlsAlloc();
|
||||
TlsSetValue(S->tls, THREAD(0xAAAA));
|
||||
SetLastError(1234);
|
||||
u32 ids = 1;
|
||||
for (int i = 0; i < 4; i++) S->handles[i] = spawn(isolated, i);
|
||||
WaitForMultipleObjects(4, S->handles, 1, INFINITE);
|
||||
for (int i = 0; i < 4; i++) {
|
||||
u32 code = 0;
|
||||
GetExitCodeThread(S->handles[i], &code);
|
||||
S->out[i] = code;
|
||||
ids &= S->slots[i] == GetThreadId(S->handles[i]);
|
||||
for (int j = 0; j < i; j++) ids &= S->slots[i] != S->slots[j];
|
||||
}
|
||||
S->out[4] = GetLastError();
|
||||
S->out[5] = (u64)TlsGetValue(S->tls);
|
||||
S->out[6] = ids;
|
||||
}
|
||||
|
||||
// --- lifecycle -------------------------------------------------------------
|
||||
static u32 exits(void *code) {
|
||||
ExitThread((u32)(u64)code);
|
||||
S->out[15] = 1; // never reached
|
||||
return 99;
|
||||
}
|
||||
|
||||
static u32 spins(void *unused) {
|
||||
for (;;) S->counter++;
|
||||
}
|
||||
|
||||
void main_lifecycle(void) {
|
||||
u32 code = 0;
|
||||
S->a = CreateEventA(0, 1, 0, 0);
|
||||
HANDLE ended = spawn(exits, 0xC0DE);
|
||||
S->out[0] = WaitForSingleObject(ended, INFINITE);
|
||||
GetExitCodeThread(ended, &code);
|
||||
S->out[1] = code;
|
||||
HANDLE spinning = spawn(spins, 0);
|
||||
SwitchToThread();
|
||||
GetExitCodeThread(spinning, &code);
|
||||
S->out[2] = code; // STILL_ACTIVE
|
||||
S->out[3] = WaitForSingleObject(spinning, 0);
|
||||
S->out[4] = TerminateThread(spinning, 77);
|
||||
S->out[5] = WaitForSingleObject(spinning, INFINITE);
|
||||
GetExitCodeThread(spinning, &code);
|
||||
S->out[6] = code;
|
||||
S->out[7] = TerminateThread(spinning, 78);
|
||||
S->out[8] = GetLastError();
|
||||
GetExitCodeThread(spinning, &code);
|
||||
S->out[9] = code;
|
||||
S->out[10] = CloseHandle(spinning);
|
||||
S->out[11] = WaitForSingleObject(spinning, 0);
|
||||
S->out[12] = GetLastError();
|
||||
HANDLE opened = OpenThread(0x00100040, 0, GetThreadId(ended));
|
||||
S->out[13] = (u64)opened; // an ended thread has no ID
|
||||
}
|
||||
|
||||
static u32 marks(void *unused) {
|
||||
S->flag = 1;
|
||||
return 5;
|
||||
}
|
||||
|
||||
void main_suspend(void) {
|
||||
HANDLE thread = CreateThread(0, 0x20000, marks, 0, 4, 0);
|
||||
for (int i = 0; i < 10; i++) SwitchToThread();
|
||||
S->out[0] = S->flag;
|
||||
S->out[1] = SuspendThread(thread);
|
||||
S->out[2] = ResumeThread(thread);
|
||||
S->out[3] = WaitForSingleObject(thread, 10);
|
||||
S->out[4] = ResumeThread(thread);
|
||||
S->out[5] = WaitForSingleObject(thread, INFINITE);
|
||||
S->out[6] = S->flag;
|
||||
S->out[7] = SuspendThread(thread);
|
||||
S->out[8] = GetLastError();
|
||||
u32 id = GetThreadId(thread);
|
||||
HANDLE other = CreateThread(0, 0, marks, 0, 4, &id);
|
||||
HANDLE opened = OpenThread(0x00100002, 0, id);
|
||||
S->out[9] = ResumeThread(opened);
|
||||
S->out[10] = WaitForSingleObject(opened, INFINITE);
|
||||
u32 code = 0;
|
||||
S->out[11] = GetExitCodeThread(opened, &code);
|
||||
S->out[12] = GetLastError(); // the handle has no query right
|
||||
S->out[13] = TerminateThread(opened, 1);
|
||||
for (int i = 0; i < 200; i++) {
|
||||
if (SuspendThread(THREAD(-2)) == 0xFFFFFFFF) break;
|
||||
S->out[14]++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
#define CYCLES 600
|
||||
static u32 short_lived(void *index) {
|
||||
u32 clean = GetLastError() == 0 && TlsGetValue(S->tls) == 0 && *_errno() == 0;
|
||||
SetLastError(9);
|
||||
TlsSetValue(S->tls, index);
|
||||
*_errno() = 33;
|
||||
S->counter += clean;
|
||||
return (u32)(u64)index;
|
||||
}
|
||||
|
||||
void main_churn(void) {
|
||||
S->tls = TlsAlloc();
|
||||
u64 right = 0;
|
||||
for (u64 i = 1; i <= CYCLES; i++) {
|
||||
u32 code = 0;
|
||||
HANDLE thread = spawn(short_lived, i);
|
||||
WaitForSingleObject(thread, INFINITE);
|
||||
GetExitCodeThread(thread, &code);
|
||||
right += code == i;
|
||||
CloseHandle(thread);
|
||||
}
|
||||
S->out[0] = right;
|
||||
S->out[1] = S->counter;
|
||||
}
|
||||
|
||||
void main_limit(void) {
|
||||
u64 made = 0;
|
||||
S->a = CreateEventA(0, 1, 0, 0);
|
||||
for (int i = 0; i < 100; i++) {
|
||||
HANDLE thread = CreateThread(0, 0x10000, ordered_waiter, 0, 0, 0);
|
||||
if (!thread) break;
|
||||
made++;
|
||||
CloseHandle(thread);
|
||||
}
|
||||
S->out[0] = made;
|
||||
S->out[1] = GetLastError();
|
||||
S->out[2] = (u64)CreateThread(0, 0x10000000, marks, 0, 0, 0);
|
||||
S->out[3] = (u64)CreateThread(0, 0, marks, 0, 0x80, 0);
|
||||
S->out[4] = GetLastError();
|
||||
}
|
||||
|
||||
// --- failures --------------------------------------------------------------
|
||||
static u32 locks_b_then_a(void *unused) {
|
||||
WaitForSingleObject(S->b, INFINITE);
|
||||
SetEvent(S->c);
|
||||
WaitForSingleObject(S->a, INFINITE);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void main_deadlock(void) {
|
||||
S->a = CreateMutexA(0, 1, 0);
|
||||
S->b = CreateMutexA(0, 0, 0);
|
||||
S->c = CreateEventA(0, 0, 0, 0);
|
||||
spawn(locks_b_then_a, 0);
|
||||
WaitForSingleObject(S->c, INFINITE);
|
||||
WaitForSingleObject(S->b, INFINITE);
|
||||
}
|
||||
|
||||
static u32 abandons(void *unused) {
|
||||
WaitForSingleObject(S->a, INFINITE);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void main_abandoned(void) {
|
||||
S->a = CreateMutexA(0, 0, 0);
|
||||
S->handles[0] = CreateEventA(0, 1, 0, 0);
|
||||
S->handles[1] = S->a;
|
||||
join(spawn(abandons, 0));
|
||||
S->out[0] = WaitForMultipleObjects(2, S->handles, 0, INFINITE);
|
||||
S->out[1] = ReleaseMutex(S->a);
|
||||
S->out[2] = WaitForSingleObject(S->a, INFINITE);
|
||||
}
|
||||
|
||||
static u64 recurse(volatile u64 *previous) {
|
||||
volatile u64 frame[64];
|
||||
frame[0] = (u64)previous;
|
||||
S->out[0]++;
|
||||
return recurse(frame) + frame[0];
|
||||
}
|
||||
static u32 overflows(void *unused) { return (u32)recurse(0); }
|
||||
void main_overflow(void) { join(spawn(overflows, 0)); }
|
||||
|
||||
static u32 changes_the_wait(void *unused) {
|
||||
for (int i = 0; i < 100; i++) SwitchToThread(); // main blocks first
|
||||
CloseHandle(S->a);
|
||||
S->handles[0] = S->handles[1] = S->c;
|
||||
ReleaseSemaphore(S->b, 1, 0);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// The wait keeps the objects it was given.
|
||||
void main_captured(void) {
|
||||
S->a = CreateEventA(0, 1, 0, 0);
|
||||
S->b = CreateSemaphoreA(0, 0, 5, 0);
|
||||
S->c = CreateEventA(0, 1, 1, 0);
|
||||
S->handles[0] = S->a;
|
||||
S->handles[1] = S->b;
|
||||
HANDLE thread = spawn(changes_the_wait, 0);
|
||||
S->out[0] = WaitForMultipleObjects(2, S->handles, 0, INFINITE);
|
||||
join(thread);
|
||||
S->out[1] = WaitForSingleObject(S->b, 0);
|
||||
}
|
||||
|
||||
void main_outlived(void) {
|
||||
spawn(spins, 0);
|
||||
SwitchToThread();
|
||||
}
|
||||
|
||||
static u32 last_one(void *unused) {
|
||||
S->out[0] = WaitForSingleObject(S->a, 30);
|
||||
S->out[1] = 1;
|
||||
return 0;
|
||||
}
|
||||
void main_exits_first(void) {
|
||||
S->a = CreateEventA(0, 0, 0, 0);
|
||||
spawn(last_one, 0);
|
||||
ExitThread(3);
|
||||
}
|
||||
|
||||
// --- hand-off and rights ---------------------------------------------------
|
||||
static u32 takes(void *unused) {
|
||||
WaitForSingleObject(S->a, INFINITE);
|
||||
S->counter++;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void settle(void) {
|
||||
for (int i = 0; i < 30; i++) SwitchToThread();
|
||||
}
|
||||
|
||||
// An object signaled while a thread waits belongs to that thread, which has
|
||||
// not run yet when the signaling call returns.
|
||||
void main_handoff(void) {
|
||||
S->a = CreateMutexA(0, 1, 0);
|
||||
spawn(takes, 0);
|
||||
settle();
|
||||
ReleaseMutex(S->a);
|
||||
S->out[0] = WaitForSingleObject(S->a, 0);
|
||||
S->out[1] = S->counter;
|
||||
settle();
|
||||
S->out[2] = S->counter;
|
||||
|
||||
S->a = CreateSemaphoreA(0, 0, 5, 0);
|
||||
spawn(takes, 0);
|
||||
settle();
|
||||
ReleaseSemaphore(S->a, 1, 0);
|
||||
S->out[3] = WaitForSingleObject(S->a, 0);
|
||||
S->out[4] = S->counter;
|
||||
settle();
|
||||
S->out[5] = S->counter;
|
||||
|
||||
S->a = CreateEventA(0, 0, 0, 0);
|
||||
spawn(takes, 0);
|
||||
settle();
|
||||
SetEvent(S->a);
|
||||
S->out[6] = WaitForSingleObject(S->a, 0);
|
||||
S->out[7] = S->counter;
|
||||
settle();
|
||||
S->out[8] = S->counter;
|
||||
|
||||
// Signaling does not cost the caller its turn.
|
||||
spawn(marks, 0);
|
||||
SetEvent(S->a);
|
||||
S->out[9] = S->flag;
|
||||
settle();
|
||||
S->out[10] = S->flag;
|
||||
}
|
||||
|
||||
// A suspended thread does not take what it waits for.
|
||||
void main_suspended_waiter(void) {
|
||||
S->a = CreateSemaphoreA(0, 0, 5, 0);
|
||||
HANDLE thread = spawn(takes, 0);
|
||||
settle();
|
||||
S->out[0] = SuspendThread(thread);
|
||||
ReleaseSemaphore(S->a, 1, 0);
|
||||
settle();
|
||||
S->out[1] = WaitForSingleObject(S->a, 0);
|
||||
S->out[2] = S->counter;
|
||||
ReleaseSemaphore(S->a, 1, 0);
|
||||
ResumeThread(thread);
|
||||
join(thread);
|
||||
S->out[3] = S->counter;
|
||||
}
|
||||
|
||||
void main_rights(void) {
|
||||
S->a = CreateEventA(0, 1, 0, 0);
|
||||
HANDLE thread = spawn(takes, 0);
|
||||
u32 id = GetThreadId(thread), code = 0;
|
||||
HANDLE query = OpenThread(0x00100040, 0, id);
|
||||
HANDLE suspend = OpenThread(0x00000002, 0, id);
|
||||
S->out[0] = SuspendThread(query);
|
||||
S->out[1] = GetLastError();
|
||||
S->out[2] = TerminateThread(query, 1);
|
||||
S->out[3] = GetLastError();
|
||||
S->out[4] = GetExitCodeThread(query, &code);
|
||||
S->out[5] = code;
|
||||
S->out[6] = SuspendThread(suspend);
|
||||
S->out[7] = ResumeThread(suspend);
|
||||
S->out[8] = GetExitCodeThread(suspend, &code);
|
||||
S->out[9] = WaitForSingleObject(suspend, 0);
|
||||
S->out[10] = GetLastError();
|
||||
S->out[11] = GetThreadId(suspend);
|
||||
SetEvent(S->a);
|
||||
join(thread);
|
||||
S->out[12] = GetThreadId(query) == id; // the object outlives the thread
|
||||
}
|
||||
|
||||
static u32 halts(void *unused) {
|
||||
__asm__ volatile("hlt");
|
||||
return 0;
|
||||
}
|
||||
void main_worker_halts(void) { join(spawn(halts, 0)); }
|
||||
|
||||
static u32 reports_stack(void *unused) {
|
||||
volatile u64 local = 0;
|
||||
if (!S->slots[0]) S->slots[0] = (u64)&local;
|
||||
S->counter += S->slots[0] == (u64)&local;
|
||||
return 0;
|
||||
}
|
||||
void main_reuse(void) {
|
||||
for (int i = 0; i < 50; i++) join(spawn(reports_stack, 0));
|
||||
}
|
||||
|
||||
// Signaling over and over must not starve a thread that is ready to run.
|
||||
void main_starve(void) {
|
||||
S->a = CreateEventA(0, 0, 0, 0);
|
||||
spawn(marks, 0);
|
||||
u64 signals = 0;
|
||||
while (!S->flag) {
|
||||
SetEvent(S->a);
|
||||
signals++;
|
||||
}
|
||||
S->out[0] = S->flag;
|
||||
S->out[1] = signals;
|
||||
}
|
||||
|
||||
// --- locks of an ended thread ----------------------------------------------
|
||||
static u32 takes_locks(void *unused) {
|
||||
int pending = 0;
|
||||
EnterCriticalSection(S->section);
|
||||
S->out[0] = S->section[2] == GetCurrentThreadId(); // OwningThread
|
||||
AcquireSRWLockExclusive(&S->srw);
|
||||
S->out[1] = InitOnceBeginInitialize(&S->once, 0, &pending, 0) && pending;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static u32 inherits_locks(void *unused) {
|
||||
u32 local = 0;
|
||||
S->out[2] = TryEnterCriticalSection(S->section);
|
||||
S->out[3] = TryAcquireSRWLockExclusive(&S->srw) & 0xFF;
|
||||
S->out[4] = TryAcquireSRWLockShared(&S->srw) & 0xFF;
|
||||
S->out[5] = InitOnceComplete(&S->once, 0, 0);
|
||||
S->out[6] = (u64)&local;
|
||||
return 0;
|
||||
}
|
||||
|
||||
void main_orphaned_locks(void) {
|
||||
InitializeCriticalSection(S->section);
|
||||
join(spawn(takes_locks, 0));
|
||||
S->out[7] = TryEnterCriticalSection(S->section);
|
||||
join(spawn(inherits_locks, 0));
|
||||
}
|
||||
|
||||
static u32 begins_once(void *where) {
|
||||
int pending = 0;
|
||||
InitOnceBeginInitialize(where, 0, &pending, 0);
|
||||
return 0;
|
||||
}
|
||||
void main_pending_bound(void) {
|
||||
char *block = VirtualAlloc(0, 0x10000, 0x3000, 4);
|
||||
for (u64 i = 0; i < 5000; i++) {
|
||||
join(spawn(begins_once, (u64)block + 8 * i));
|
||||
S->counter++;
|
||||
}
|
||||
}
|
||||
|
||||
// --- identity --------------------------------------------------------------
|
||||
static u32 duplicates_itself(void *unused) {
|
||||
HANDLE copy = 0;
|
||||
u32 code = 0;
|
||||
S->out[0] = DuplicateHandle(THREAD(-1), THREAD(-2), THREAD(-1), ©, 0, 0, 2);
|
||||
S->out[1] = GetThreadId(copy) == GetCurrentThreadId();
|
||||
S->out[2] = WaitForSingleObject(copy, 0);
|
||||
S->out[3] = GetExitCodeThread(copy, &code) && code == 259;
|
||||
S->out[4] = SetThreadPriority(THREAD(-2), 2);
|
||||
S->out[5] = GetLastError();
|
||||
S->handles[0] = copy;
|
||||
return 44;
|
||||
}
|
||||
|
||||
void main_duplicate(void) {
|
||||
u32 code = 0;
|
||||
join(spawn(duplicates_itself, 0));
|
||||
S->out[6] = WaitForSingleObject(S->handles[0], 0);
|
||||
GetExitCodeThread(S->handles[0], &code);
|
||||
S->out[7] = code;
|
||||
S->out[8] = (u64)GetThreadPriority(THREAD(-2));
|
||||
}
|
||||
|
||||
// --- stacks ----------------------------------------------------------------
|
||||
// Every frame's address is used by its callee, so this stays recursive.
|
||||
static u64 deep(u64 n, volatile u64 *caller) {
|
||||
volatile u64 frame[64];
|
||||
frame[0] = n;
|
||||
frame[1] = (u64)caller;
|
||||
return n ? deep(n - 1, frame) + frame[0] : (S->slots[1] = (u64)frame, 0);
|
||||
}
|
||||
static u32 recurses(void *n) {
|
||||
volatile u64 top = 0;
|
||||
S->slots[0] = (u64)⊤
|
||||
S->out[0] = deep((u64)n, &top);
|
||||
return 1;
|
||||
}
|
||||
// 200 frames of over 512 bytes need more than 100 KB.
|
||||
void main_small_commit(void) { join(CreateThread(0, 4096, recurses, THREAD(200), 0, 0)); }
|
||||
void main_small_reservation(void) { join(CreateThread(0, 4096, recurses, THREAD(200), 0x10000, 0)); }
|
||||
|
||||
void main_area_taken(void) {
|
||||
S->out[0] = (u64)VirtualAlloc(THREAD(0x600000000), 0x10000, 0x3000, 4);
|
||||
HANDLE thread = spawn(marks, 0);
|
||||
S->out[1] = thread != 0;
|
||||
join(thread);
|
||||
S->out[2] = S->flag;
|
||||
}
|
||||
|
||||
static u32 frees_itself(void *unused) {
|
||||
u64 local = 0;
|
||||
S->out[0] = VirtualFree(THREAD(((u64)&local & ~0xFFFFFFull) + 0x1000), 0, 0x8000);
|
||||
S->out[1] = VirtualFree(THREAD(((u64)&local & ~0xFFFFFFull) + 0xF00000), 0, 0x8000);
|
||||
return 0;
|
||||
}
|
||||
void main_free_stack(void) { join(spawn(frees_itself, 0)); }
|
||||
|
||||
// --- ending threads in every state -------------------------------------------
|
||||
static u32 waits_forever(void *unused) {
|
||||
WaitForSingleObject(S->a, INFINITE);
|
||||
S->flag = 9;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static u32 terminates_itself(void *unused) {
|
||||
TerminateThread(THREAD(-2), 61);
|
||||
S->flag = 9;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static u32 owns_both(void *unused) {
|
||||
WaitForMultipleObjects(2, S->handles, 1, INFINITE);
|
||||
return 0;
|
||||
}
|
||||
|
||||
void main_terminations(void) {
|
||||
u32 code = 0;
|
||||
S->a = CreateEventA(0, 0, 0, 0);
|
||||
HANDLE blocked = spawn(waits_forever, 0);
|
||||
settle();
|
||||
S->out[0] = TerminateThread(blocked, 60);
|
||||
GetExitCodeThread(blocked, &code);
|
||||
S->out[1] = code;
|
||||
SetEvent(S->a); // nobody is left to consume it
|
||||
S->out[2] = WaitForSingleObject(S->a, 0);
|
||||
HANDLE suspended = CreateThread(0, 0, waits_forever, 0, 4, 0);
|
||||
S->out[3] = TerminateThread(suspended, 62);
|
||||
S->out[4] = WaitForSingleObject(suspended, INFINITE);
|
||||
HANDLE itself = spawn(terminates_itself, 0);
|
||||
WaitForSingleObject(itself, INFINITE);
|
||||
GetExitCodeThread(itself, &code);
|
||||
S->out[5] = code;
|
||||
S->out[6] = S->flag;
|
||||
S->handles[0] = CreateMutexA(0, 0, 0);
|
||||
S->handles[1] = CreateMutexA(0, 0, 0);
|
||||
join(spawn(owns_both, 0));
|
||||
S->out[7] = WaitForMultipleObjects(2, S->handles, 1, INFINITE);
|
||||
ReleaseMutex(S->handles[0]);
|
||||
ReleaseMutex(S->handles[1]);
|
||||
S->out[8] = WaitForMultipleObjects(2, S->handles, 1, INFINITE);
|
||||
HANDLE limit = CreateThread(0, 0, marks, 0, 4, 0);
|
||||
for (int i = 0; i < 126; i++) SuspendThread(limit);
|
||||
S->out[9] = SuspendThread(limit);
|
||||
S->out[10] = GetLastError();
|
||||
TerminateThread(limit, 0);
|
||||
}
|
||||
|
||||
void main_keeps_state(void) {
|
||||
S->tls = TlsAlloc();
|
||||
TlsSetValue(S->tls, THREAD(77));
|
||||
SetLastError(88);
|
||||
for (volatile u64 i = 0; i < 3000; i++) {}
|
||||
S->out[0] = GetLastError();
|
||||
S->out[1] = (u64)TlsGetValue(S->tls);
|
||||
}
|
||||
|
||||
void main_signals(void) {
|
||||
S->a = CreateEventA(0, 1, 0, 0);
|
||||
for (volatile u64 i = 0; i < 1000; i++) SetEvent(S->a);
|
||||
}
|
||||
|
||||
static u32 holds_exclusive(void *unused) { AcquireSRWLockExclusive(&S->srw); return 0; }
|
||||
static u32 holds_shared(void *unused) { AcquireSRWLockShared(&S->srw); return 0; }
|
||||
static u32 releases_exclusive(void *unused) { ReleaseSRWLockExclusive(&S->srw); return S->flag = 1; }
|
||||
static u32 releases_shared(void *unused) { ReleaseSRWLockShared(&S->srw); return S->flag = 1; }
|
||||
void main_orphaned_exclusive(void) {
|
||||
join(spawn(holds_exclusive, 0));
|
||||
join(spawn(releases_exclusive, 0));
|
||||
}
|
||||
void main_orphaned_shared(void) {
|
||||
join(spawn(holds_shared, 0));
|
||||
S->out[0] = TryAcquireSRWLockShared(&S->srw) & 0xFF; // sharing is still possible
|
||||
S->out[1] = TryAcquireSRWLockExclusive(&S->srw) & 0xFF;
|
||||
join(spawn(releases_shared, 0));
|
||||
}
|
||||
|
||||
// Host services the test registers at fixed addresses.
|
||||
#define ADVANCE ((void (*)(u64))0x60000)
|
||||
#define NESTED ((void (*)(void))0x60010)
|
||||
|
||||
// --- a signal after the deadline belongs to nobody -------------------------
|
||||
static u32 signals_too_late(void *unused) {
|
||||
while (!S->flag) SwitchToThread();
|
||||
settle();
|
||||
ADVANCE(100);
|
||||
SetEvent(S->a);
|
||||
return 0;
|
||||
}
|
||||
void main_expired_wait(void) {
|
||||
S->a = CreateEventA(0, 0, 0, 0);
|
||||
HANDLE late = spawn(signals_too_late, 0);
|
||||
S->flag = 1;
|
||||
S->out[0] = WaitForSingleObject(S->a, 50);
|
||||
S->out[1] = WaitForSingleObject(late, INFINITE);
|
||||
S->out[2] = WaitForSingleObject(S->a, 0);
|
||||
S->out[3] = WaitForSingleObject(S->a, 0);
|
||||
}
|
||||
|
||||
void main_continued_wait(void) {
|
||||
S->a = CreateEventA(0, 1, 0, 0);
|
||||
S->handles[0] = S->a;
|
||||
S->out[0] = WaitForMultipleObjects(1, S->handles, 1, 1000);
|
||||
S->out[1] = 1;
|
||||
}
|
||||
|
||||
static u32 reopens(void *id) {
|
||||
settle();
|
||||
S->out[2] = (u64)OpenThread(0x40, 0, (u32)(u64)id);
|
||||
S->out[3] = GetLastError();
|
||||
return 0;
|
||||
}
|
||||
void main_reopened(void) {
|
||||
u32 id = GetCurrentThreadId();
|
||||
S->out[0] = OpenThread(0x40, 0, id) != 0;
|
||||
S->out[1] = spawn(reopens, id) != 0;
|
||||
ExitThread(3);
|
||||
}
|
||||
|
||||
// A tail call: the wait returns straight to the end of the thread.
|
||||
static u32 ends_in_a_wait(HANDLE event, u32 unused) {
|
||||
__attribute__((musttail)) return WaitForSingleObject(event, 50);
|
||||
}
|
||||
void main_ends_in_a_wait(void) {
|
||||
u32 code = 0;
|
||||
S->a = CreateEventA(0, 1, 0, 0);
|
||||
S->handles[0] = spawn((START)(void *)ends_in_a_wait, (u64)S->a);
|
||||
S->out[0] = WaitForSingleObject(S->handles[0], INFINITE);
|
||||
S->handles[1] = spawn((START)(void *)ends_in_a_wait, (u64)S->a);
|
||||
S->out[1] = WaitForSingleObject(S->handles[1], 1000);
|
||||
GetExitCodeThread(S->handles[1], &code);
|
||||
S->out[2] = code;
|
||||
}
|
||||
|
||||
void main_nested(void) {
|
||||
NESTED();
|
||||
S->out[1] = WaitForSingleObject(spawn(collatz, 97), INFINITE);
|
||||
}
|
||||
@@ -0,0 +1,700 @@
|
||||
entry main_abandoned 4784
|
||||
entry main_area_taken 8960
|
||||
entry main_atomic 432
|
||||
entry main_captured 5152
|
||||
entry main_churn 3936
|
||||
entry main_continued_wait 11232
|
||||
entry main_deadlock 4560
|
||||
entry main_duplicate 8288
|
||||
entry main_ends_in_a_wait 11552
|
||||
entry main_exits_first 5584
|
||||
entry main_expired_wait 10928
|
||||
entry main_fifo 1520
|
||||
entry main_free_stack 9120
|
||||
entry main_handoff 5744
|
||||
entry main_independent 0
|
||||
entry main_isolated 2256
|
||||
entry main_keeps_state 10176
|
||||
entry main_lifecycle 2896
|
||||
entry main_limit 4272
|
||||
entry main_mutex 896
|
||||
entry main_nested 11792
|
||||
entry main_orphaned_exclusive 10432
|
||||
entry main_orphaned_locks 7632
|
||||
entry main_orphaned_shared 10656
|
||||
entry main_outlived 5520
|
||||
entry main_overflow 5056
|
||||
entry main_pending_bound 8064
|
||||
entry main_producer 1184
|
||||
entry main_racy 672
|
||||
entry main_reopened 11328
|
||||
entry main_reuse 7280
|
||||
entry main_rights 6720
|
||||
entry main_signal_before_timeout 2032
|
||||
entry main_signals 10320
|
||||
entry main_small_commit 8736
|
||||
entry main_small_reservation 8880
|
||||
entry main_starve 7472
|
||||
entry main_suspend 3424
|
||||
entry main_suspended_waiter 6432
|
||||
entry main_terminations 9312
|
||||
entry main_timeout 1904
|
||||
entry main_worker_halts 7184
|
||||
import CreateThread 50
|
||||
import WaitForMultipleObjects 142
|
||||
import GetExitCodeThread 167
|
||||
import GetThreadId 232
|
||||
import GetCurrentThreadId 257
|
||||
import CreateThread 451
|
||||
import WaitForMultipleObjects 534
|
||||
import SwitchToThread 590
|
||||
import CreateThread 691
|
||||
import WaitForMultipleObjects 774
|
||||
import SwitchToThread 831
|
||||
import CreateMutexA 914
|
||||
import CreateThread 936
|
||||
import WaitForMultipleObjects 1014
|
||||
import WaitForSingleObject 1075
|
||||
import SwitchToThread 1082
|
||||
import ReleaseMutex 1089
|
||||
import CreateEventA 1196
|
||||
import CreateThread 1273
|
||||
import SetEvent 1288
|
||||
import WaitForSingleObject 1295
|
||||
import WaitForSingleObject 1365
|
||||
import CloseHandle 1374
|
||||
import WaitForSingleObject 1427
|
||||
import SetEvent 1434
|
||||
import CreateEventA 1539
|
||||
import CreateThread 1566
|
||||
import SwitchToThread 1638
|
||||
import SetEvent 1680
|
||||
import WaitForSingleObject 1696
|
||||
import SetEvent 1758
|
||||
import WaitForMultipleObjects 1814
|
||||
import WaitForSingleObject 1863
|
||||
import CreateEventA 1924
|
||||
import WaitForSingleObject 1939
|
||||
import SetEvent 1995
|
||||
import CreateEventA 2041
|
||||
import CreateThread 2118
|
||||
import WaitForSingleObject 2136
|
||||
import CloseHandle 2197
|
||||
import WaitForSingleObject 2227
|
||||
import SetEvent 2241
|
||||
import TlsAlloc 2279
|
||||
import TlsSetValue 2304
|
||||
import SetLastError 2315
|
||||
import CreateThread 2331
|
||||
import WaitForMultipleObjects 2412
|
||||
import GetExitCodeThread 2422
|
||||
import GetThreadId 2429
|
||||
import GetLastError 2568
|
||||
import TlsGetValue 2591
|
||||
import GetLastError 2659
|
||||
import TlsGetValue 2676
|
||||
import TlsSetValue 2715
|
||||
import _errno 2725
|
||||
import SetLastError 2740
|
||||
import GetCurrentThreadId 2751
|
||||
import SwitchToThread 2760
|
||||
import GetLastError 2777
|
||||
import TlsGetValue 2812
|
||||
import _errno 2823
|
||||
import GetCurrentThreadId 2834
|
||||
import _errno 2875
|
||||
import CreateEventA 2932
|
||||
import CreateThread 2971
|
||||
import WaitForSingleObject 2993
|
||||
import GetExitCodeThread 3021
|
||||
import SwitchToThread 3089
|
||||
import TerminateThread 3135
|
||||
import GetLastError 3226
|
||||
import CloseHandle 3269
|
||||
import GetThreadId 3319
|
||||
import OpenThread 3335
|
||||
import ExitThread 3382
|
||||
import CreateThread 3471
|
||||
import SwitchToThread 3486
|
||||
import SuspendThread 3528
|
||||
import ResumeThread 3550
|
||||
import WaitForSingleObject 3572
|
||||
import GetLastError 3666
|
||||
import GetThreadId 3688
|
||||
import CreateThread 3730
|
||||
import OpenThread 3748
|
||||
import GetExitCodeThread 3809
|
||||
import TerminateThread 3846
|
||||
import TlsAlloc 3954
|
||||
import CreateThread 3976
|
||||
import WaitForSingleObject 3983
|
||||
import GetExitCodeThread 3995
|
||||
import CloseHandle 4002
|
||||
import GetLastError 4171
|
||||
import TlsGetValue 4188
|
||||
import SetLastError 4206
|
||||
import TlsSetValue 4222
|
||||
import _errno 4228
|
||||
import _errno 4257
|
||||
import CreateEventA 4302
|
||||
import CreateThread 4329
|
||||
import CloseHandle 4336
|
||||
import GetLastError 4427
|
||||
import CreateMutexA 4568
|
||||
import CreateEventA 4621
|
||||
import CreateThread 4666
|
||||
import WaitForSingleObject 4681
|
||||
import WaitForSingleObject 4736
|
||||
import SetEvent 4757
|
||||
import CreateMutexA 4799
|
||||
import CreateEventA 4826
|
||||
import CreateThread 4887
|
||||
import WaitForSingleObject 4897
|
||||
import CloseHandle 4916
|
||||
import WaitForMultipleObjects 4941
|
||||
import ReleaseMutex 4965
|
||||
import WaitForSingleObject 5043
|
||||
import CreateThread 5094
|
||||
import WaitForSingleObject 5111
|
||||
import CloseHandle 5120
|
||||
import CreateEventA 5161
|
||||
import CreateSemaphoreA 5203
|
||||
import CreateThread 5306
|
||||
import WaitForMultipleObjects 5334
|
||||
import WaitForSingleObject 5351
|
||||
import CloseHandle 5370
|
||||
import SwitchToThread 5422
|
||||
import CloseHandle 5456
|
||||
import ReleaseSemaphore 5502
|
||||
import CreateThread 5557
|
||||
import SwitchToThread 5563
|
||||
import CreateEventA 5600
|
||||
import CreateThread 5645
|
||||
import ExitThread 5656
|
||||
import WaitForSingleObject 5699
|
||||
import CreateMutexA 5762
|
||||
import CreateThread 5807
|
||||
import SwitchToThread 5819
|
||||
import ReleaseMutex 5840
|
||||
import WaitForSingleObject 5856
|
||||
import CreateSemaphoreA 5941
|
||||
import CreateThread 5986
|
||||
import ReleaseSemaphore 6024
|
||||
import WaitForSingleObject 6040
|
||||
import CreateEventA 6114
|
||||
import CreateThread 6159
|
||||
import SetEvent 6192
|
||||
import WaitForSingleObject 6208
|
||||
import CreateThread 6311
|
||||
import SetEvent 6325
|
||||
import WaitForSingleObject 6403
|
||||
import CreateSemaphoreA 6454
|
||||
import CreateThread 6499
|
||||
import SwitchToThread 6514
|
||||
import SuspendThread 6539
|
||||
import ReleaseSemaphore 6571
|
||||
import WaitForSingleObject 6609
|
||||
import ReleaseSemaphore 6661
|
||||
import ResumeThread 6670
|
||||
import CloseHandle 6689
|
||||
import CreateEventA 6751
|
||||
import CreateThread 6796
|
||||
import GetThreadId 6808
|
||||
import OpenThread 6825
|
||||
import SuspendThread 6864
|
||||
import GetLastError 6886
|
||||
import TerminateThread 6913
|
||||
import GetExitCodeThread 6943
|
||||
import ResumeThread 7003
|
||||
import WaitForSingleObject 7039
|
||||
import GetThreadId 7080
|
||||
import SetEvent 7107
|
||||
import CloseHandle 7127
|
||||
import CreateThread 7222
|
||||
import WaitForSingleObject 7239
|
||||
import CloseHandle 7248
|
||||
import CreateThread 7308
|
||||
import WaitForSingleObject 7315
|
||||
import CloseHandle 7322
|
||||
import CreateEventA 7492
|
||||
import CreateThread 7537
|
||||
import SetEvent 7556
|
||||
import InitializeCriticalSection 7648
|
||||
import CreateThread 7679
|
||||
import WaitForSingleObject 7698
|
||||
import CloseHandle 7715
|
||||
import TryEnterCriticalSection 7732
|
||||
import EnterCriticalSection 7828
|
||||
import GetCurrentThreadId 7842
|
||||
import AcquireSRWLockExclusive 7871
|
||||
import InitOnceBeginInitialize 7892
|
||||
import TryEnterCriticalSection 7955
|
||||
import TryAcquireSRWLockExclusive 7976
|
||||
import TryAcquireSRWLockShared 7998
|
||||
import InitOnceComplete 8025
|
||||
import VirtualAlloc 8103
|
||||
import CreateThread 8120
|
||||
import WaitForSingleObject 8127
|
||||
import CloseHandle 8134
|
||||
import InitOnceBeginInitialize 8264
|
||||
import CreateThread 8335
|
||||
import WaitForSingleObject 8345
|
||||
import CloseHandle 8364
|
||||
import GetExitCodeThread 8405
|
||||
import GetThreadPriority 8430
|
||||
import DuplicateHandle 8538
|
||||
import GetThreadId 8559
|
||||
import GetCurrentThreadId 8567
|
||||
import WaitForSingleObject 8595
|
||||
import GetExitCodeThread 8621
|
||||
import SetThreadPriority 8668
|
||||
import GetLastError 8684
|
||||
import CreateThread 8780
|
||||
import WaitForSingleObject 8797
|
||||
import CloseHandle 8806
|
||||
import CreateThread 8924
|
||||
import WaitForSingleObject 8941
|
||||
import CloseHandle 8950
|
||||
import VirtualAlloc 8994
|
||||
import CreateThread 9039
|
||||
import WaitForSingleObject 9072
|
||||
import CloseHandle 9081
|
||||
import CreateThread 9158
|
||||
import WaitForSingleObject 9175
|
||||
import CloseHandle 9184
|
||||
import VirtualFree 9237
|
||||
import CreateEventA 9345
|
||||
import CreateThread 9390
|
||||
import SwitchToThread 9405
|
||||
import TerminateThread 9433
|
||||
import GetExitCodeThread 9461
|
||||
import SetEvent 9501
|
||||
import WaitForSingleObject 9516
|
||||
import CreateThread 9562
|
||||
import CreateMutexA 9706
|
||||
import CloseHandle 9796
|
||||
import WaitForMultipleObjects 9803
|
||||
import ReleaseMutex 9852
|
||||
import SuspendThread 9946
|
||||
import SuspendThread 9966
|
||||
import GetLastError 9982
|
||||
import TerminateThread 10003
|
||||
import WaitForSingleObject 10051
|
||||
import TerminateThread 10098
|
||||
import WaitForMultipleObjects 10156
|
||||
import TlsAlloc 10182
|
||||
import TlsSetValue 10207
|
||||
import SetLastError 10218
|
||||
import GetLastError 10276
|
||||
import TlsGetValue 10299
|
||||
import CreateEventA 10340
|
||||
import SetEvent 10377
|
||||
import CreateThread 10468
|
||||
import WaitForSingleObject 10487
|
||||
import CloseHandle 10504
|
||||
import AcquireSRWLockExclusive 10587
|
||||
import ReleaseSRWLockExclusive 10619
|
||||
import CreateThread 10692
|
||||
import WaitForSingleObject 10711
|
||||
import CloseHandle 10728
|
||||
import TryAcquireSRWLockShared 10745
|
||||
import TryAcquireSRWLockExclusive 10767
|
||||
import AcquireSRWLockShared 10859
|
||||
import ReleaseSRWLockShared 10891
|
||||
import CreateEventA 10946
|
||||
import CreateThread 10991
|
||||
import WaitForSingleObject 11020
|
||||
import SwitchToThread 11139
|
||||
import SwitchToThread 11172
|
||||
import SetEvent 11212
|
||||
import CreateEventA 11251
|
||||
import WaitForMultipleObjects 11295
|
||||
import GetCurrentThreadId 11335
|
||||
import OpenThread 11353
|
||||
import CreateThread 11406
|
||||
import ExitThread 11433
|
||||
import SwitchToThread 11474
|
||||
import OpenThread 11506
|
||||
import GetLastError 11520
|
||||
import CreateEventA 11582
|
||||
import CreateThread 11621
|
||||
import WaitForSingleObject 11648
|
||||
import GetExitCodeThread 11749
|
||||
import WaitForSingleObject 11784
|
||||
import CreateThread 11839
|
||||
import WaitForSingleObject 11853
|
||||
code 56574883ec38c744243400000000c744243000000000488d4424344889442428
|
||||
code c7442420000000004c8d05f1000000488b350000000041b95000000031c931d2
|
||||
code ffd6488904258801050048c744242800000000c7442420000000004c8d050e01
|
||||
code 000041b96100000031c931d2ffd64889042590010500ba88010500b902000000
|
||||
code 41b80100000041b9ffffffffff150000000089c04889042510000500488b0c25
|
||||
code 88010500488b3d00000000488d7424304889f2ffd78b44243048890425180005
|
||||
code 00488b0c25900105004889f2ffd78b44243048890425200005008b742434488b
|
||||
code 0c2588010500ff150000000031c939c60f94c148890c25280005008b742434ff
|
||||
code 150000000031c939c60f95c148890c25300005004883c4385f5ec30f1f440000
|
||||
code 4885c974314883f9014883d100b80100000031d26666662e0f1f840000000000
|
||||
code 4989d14901c14989c04889c24c89c848ffc975eceb034531c04c890425000005
|
||||
code 00b80b000000c3660f1f84000000000031c04883f90174254889ca0f1f440000
|
||||
code 4c8d044949ffc048d1eaf6c101490f45d048ffc04889d14883fa0175e3488904
|
||||
code 2508000500b816000000c30f1f4400005657534883ec3031f6488d3d80000000
|
||||
code 488b1d00000000660f1f84000000000048c744242800000000c7442420000000
|
||||
code 0031c931d24989f84989f1ffd3488904f58801050048ffc64883fe0475d2ba88
|
||||
code 010500b90400000041b80100000041b9ffffffffff150000000089c048890425
|
||||
code 00000500488b04250001050048890425080005004883c4305b5f5ec30f1f4000
|
||||
code 41565657534883ec2831f6488b3d0000000031dbeb17662e0f1f840000000000
|
||||
code 4c09f6ffc381fbc8000000741941be01000000f04c0fc1342500010500f6c307
|
||||
code 75deffd7ebda89f04883c4285b5f5e415ec366666666662e0f1f840000000000
|
||||
code 5657534883ec3031f6488d3d80000000488b1d00000000660f1f840000000000
|
||||
code 48c744242800000000c74424200000000031c931d24989f84989f1ffd3488904
|
||||
code f58801050048ffc64883fe0475d2ba88010500b90400000041b80100000041b9
|
||||
code ffffffffff150000000089c04889042500000500488b04250001050048890425
|
||||
code 080005004883c4305b5f5ec30f1f40005657534883ec20bec8000000488b3d00
|
||||
code 000000666666662e0f1f840000000000488b1c2500010500ffd748ffc348891c
|
||||
code 2500010500ffce75e731c04883c4205b5f5ec3666666662e0f1f840000000000
|
||||
code 5657534883ec3031f631c931d24531c0ff15000000004889042508020500488d
|
||||
code 3d7b000000488b1d000000000f1f400048c744242800000000c7442420000000
|
||||
code 0031c931d24989f84989f1ffd3488904f58801050048ffc64883fe0475d2ba88
|
||||
code 010500b90400000041b80100000041b9ffffffffff150000000089c048890425
|
||||
code 00000500488b04250001050048890425080005004883c4305b5f5ec30f1f4000
|
||||
code 415741565657534883ec20bec8000000488b3d00000000488b1d000000004c8b
|
||||
code 350000000066662e0f1f840000000000488b0c2508020500baffffffffffd74c
|
||||
code 8b3c2500010500ffd349ffc74c893c2500010500488b0c250802050041ffd6ff
|
||||
code ce75cd31c04883c4205b5f5e415e415fc36666666666662e0f1f840000000000
|
||||
code 41565657534883ec38488b350000000031c931d24531c04531c9ffd648890425
|
||||
code 0802050031c931d24531c04531c9ffd6488904251002050048c7442428000000
|
||||
code 00c7442420000000004c8d059000000031c931d24531c9ff15000000004889c6
|
||||
code bf01000000488b1d000000004c8b3500000000666666662e0f1f840000000000
|
||||
code 48893c2508010500488b0c2508020500ffd3488b0c2510020500baffffffff41
|
||||
code ffd648ffc74883ff3375d54889f1baffffffffff15000000004889f1ff150000
|
||||
code 000048c7042508000500010000004883c4385b5f5e415ec30f1f840000000000
|
||||
code 41565657534883ec28be3200000031ff488b1d000000004c8b35000000006690
|
||||
code 488b0c2508020500baffffffffffd34889f848c1e0054829f84889c748033c25
|
||||
code 08010500488b0c251002050041ffd6ffce75cd48893c250000050031c04883c4
|
||||
code 285b5f5e415ec3660f1f8400000000005657534883ec3031c931d24531c04531
|
||||
code c9ff15000000004889042508020500be0a000000488d3d15010000488b1d0000
|
||||
code 000066666666662e0f1f84000000000048c744242800000000c7442420000000
|
||||
code 0031c931d24989f84989f1ffd3488904f53801050048ffc64883fe0e75d2bf14
|
||||
code 000000488b3500000000660f1f440000ffd6ffcf75fa488b0425000105004889
|
||||
code 042540000500488b0c2508020500ff1500000000488b0c250802050031d2ff15
|
||||
code 0000000089c04889042548000500bf14000000666666662e0f1f840000000000
|
||||
code ffd6ffcf75fa488b0425000105004889042550000500be03000000488b3d0000
|
||||
code 000066666666662e0f1f840000000000488b0c2508020500ffd7ffce75f2ba88
|
||||
code 010500b90400000041b80100000041b9ffffffffff15000000004883c4305b5f
|
||||
code 5ec366666666662e0f1f840000000000564883ec204889ce488b0c2508020500
|
||||
code baffffffffff1500000000b801000000f0480fc1042500010500488934c50000
|
||||
code 050031c04883c4205ec3660f1f440000564883ec2031c9ba010000004531c045
|
||||
code 31c9ff15000000004889042508020500488b35000000004889c1bafa000000ff
|
||||
code d689c04889042500000500488b0c250802050031d2ffd689c048890425080005
|
||||
code 00488b0c2508020500ff1500000000488b0c2508020500bafa000000ffd689c0
|
||||
code 48890425100005004883c4205ec3669056574883ec38488b350000000031c931
|
||||
code d24531c04531c9ffd6488904250802050031c931d24531c04531c9ffd6488904
|
||||
code 251002050048c744242800000000c7442420000000004c8d056300000031c931
|
||||
code d24531c9ff15000000004889c6488b0c2508020500488b3d00000000ba640000
|
||||
code 00ffd789c04889042500000500488b0c2508020500ba64000000ffd789c04889
|
||||
code 0425080005004889f1baffffffffffd74889f1ff15000000004883c4385f5ec3
|
||||
code 4883ec28488b0c2510020500ba28000000ff1500000000488b0c2508020500ff
|
||||
code 150000000031c04883c428c30f1f40004157415641554154565755534883ec38
|
||||
code bb08010500ff1500000000890425200205008b0c2520020500baaaaa0000ff15
|
||||
code 00000000b9d2040000ff150000000031f6488d3d380100004c8b350000000090
|
||||
code 48c744242800000000c74424200000000031c931d24989f84989f141ffd64889
|
||||
code 84f38000000048ffc64883fe0475d1bf01000000ba88010500b90400000041b8
|
||||
code 0100000041b9ffffffffff15000000004531f64c8b3d000000004c8b25000000
|
||||
code 004531edeb13662e0f1f84000000000049ffc54983fd04746d89fdc744243400
|
||||
code 0000004a8b8ceb80000000488d54243441ffd78b4424344a8984ebf8feffff4a
|
||||
code 8b34eb4a8b8ceb8000000041ffd489c031ff4839c6400f94c721ef4d85ed74b0
|
||||
code 31c066666666662e0f1f8400000000004a8b0ceb483b0cc3410f44fe48ffc049
|
||||
code 39c575eceb8aff150000000089c048890425200005008b0c2520020500ff1500
|
||||
code 000000488904252800050089f848890425300005004883c4385b5d5f5e415c41
|
||||
code 5d415e415fc3662e0f1f840000000000415741564154565755534883ec204889
|
||||
code ceff150000000085c075168b0c2520020500ff15000000004885c00f84b80000
|
||||
code 004531f64869dee80300004883cb078b0c25200205004889daff150000000044
|
||||
code 8d7e28ff15000000004489388d8ef4010000ff1500000000bd0a000000ff1500
|
||||
code 00000089c74c8b25000000000f1f400041ffd4ffcd75f9ff150000000089c048
|
||||
code 8d8ef40100004839c10f94c031ed4184c6742b8b0c2520020500ff1500000000
|
||||
code 4839d87519ff1500000000443938750eff150000000031ed39c7400f94c589f8
|
||||
code 488904f50801050089e84883c4205b5d5f5e415c415e415fc3ff150000000083
|
||||
code 3800410f94c6e939ffffff0f1f4400004157415641545657534883ec38c74424
|
||||
code 340000000031c9ba010000004531c04531c9ff15000000004889042508020500
|
||||
code 48c744242800000000c7442420000000004c8d0598010000488b1d0000000041
|
||||
code b9dec0000031c931d2ffd34889c64c8b35000000004889c1baffffffff41ffd6
|
||||
code 89c048890425000005004c8b3d00000000488d7c24344889f14889fa41ffd78b
|
||||
code 442434488904250800050048c744242800000000c7442420000000004c8d054d
|
||||
code 01000031c931d24531c9ffd34889c3ff15000000004889d94889fa41ffd78b44
|
||||
code 243448890425100005004889d931d241ffd689c048890425180005004c8b2500
|
||||
code 0000004889d9ba4d00000041ffd4489848890425200005004889d9baffffffff
|
||||
code 41ffd689c048890425280005004889d94889fa41ffd78b442434488904253000
|
||||
code 05004889d9ba4e00000041ffd4489848890425380005004c8b250000000041ff
|
||||
code d489c048890425400005004889d94889fa41ffd78b4424344889042548000500
|
||||
code 4889d9ff1500000000489848890425500005004889d931d241ffd689c0488904
|
||||
code 255800050041ffd489c048890425600005004889f1ff1500000000b940001000
|
||||
code 31d24189c0ff150000000048890425680005004883c4385b5f5e415c415e415f
|
||||
code c36666666666662e0f1f8400000000004883ec28ff150000000048c704257800
|
||||
code 050001000000b8630000004883c428c348ff042500010500ebf6660f1f440000
|
||||
code 415741565657534883ec4048c744242800000000c7442420040000004c8d05bd
|
||||
code 010000ba0000020031c94531c9ff15000000004889c6bf0a000000488b1d0000
|
||||
code 000066666666662e0f1f840000000000ffd3ffcf75fa8b042524020500488904
|
||||
code 2500000500488b3d000000004889f1ffd789c04889042508000500488b1d0000
|
||||
code 00004889f1ffd389c048890425100005004c8b35000000004889f1ba0a000000
|
||||
code 41ffd689c048890425180005004889f1ffd389c048890425200005004889f1ba
|
||||
code ffffffff41ffd689c048890425280005008b0425240205004889042530000500
|
||||
code 4889f1ffd789c048890425380005004c8b3d0000000041ffd789c04889042540
|
||||
code 0005004889f1ff150000000089442438488d4424384889442428c74424200400
|
||||
code 00004c8d05b700000031c931d24531c9ff1500000000448b442438b902001000
|
||||
code 31d2ff15000000004889c64889c1ffd389c048890425480005004889f1baffff
|
||||
code ffff41ffd689c04889042550000500c744243c00000000488d54243c4889f1ff
|
||||
code 15000000004898488904255800050041ffd789c048890425600005004889f1ba
|
||||
code 01000000ff15000000004898488904256800050048c7c1feffffffffd783f8ff
|
||||
code 740848ff0425700005004883c4405b5f5e415e415fc3662e0f1f840000000000
|
||||
code c704252402050001000000b805000000c36666666666662e0f1f840000000000
|
||||
code 4157415641554154565755534883ec38ff150000000089042520020500be0100
|
||||
code 00004531ff4c8b25000000004c8b2d00000000488d5c2434488b2d0000000048
|
||||
code 8b3d00000000662e0f1f840000000000c74424340000000048c7442428000000
|
||||
code 00c74424200000000031c931d24c8d056c0000004989f141ffd44989c64889c1
|
||||
code baffffffff41ffd54c89f14889daffd58b44243431c94839c60f94c14901cf4c
|
||||
code 89f1ffd748ffc64881fe5902000075a04c893c2500000500488b042500010500
|
||||
code 48890425080005004883c4385b5d5f5e415c415d415e415fc30f1f8000000000
|
||||
code 56574883ec284889ceff150000000085c075128b0c2520020500ff1500000000
|
||||
code 4885c0743a31ffb909000000ff15000000008b0c25200205004889f2ff150000
|
||||
code 0000ff1500000000c7002100000048013c250001050089f04883c4285f5ec3ff
|
||||
code 150000000031ff833800400f94c7ebb741574156565755534883ec384531f631
|
||||
code c9ba010000004531c04531c9ff15000000004889042508020500bd6300000048
|
||||
code 8d354af6ffff488b1d000000004c8b3d000000006666662e0f1f840000000000
|
||||
code 48c744242800000000c744242000000000ba0000010031c94989f04531c9ffd3
|
||||
code 4889c74885c0740949ffc64889f941ffd783ed010f92c04885ff740484c074c0
|
||||
code 4c89342500000500488b3d00000000ffd789c0488904250800050048c7442428
|
||||
code 00000000c744242000000000488d35cdfdffffba0000001031c94989f04531c9
|
||||
code ffd3488904251000050048c744242800000000c74424208000000031c931d249
|
||||
code 89f04531c9ffd34889042518000500ffd789c048890425200005004883c4385b
|
||||
code 5d5f5e415e415fc30f1f840000000000564883ec30488b350000000031c9ba01
|
||||
code 0000004531c0ffd6488904250802050031c931d24531c0ffd648890425100205
|
||||
code 0031c931d24531c04531c9ff1500000000488904251802050048c74424280000
|
||||
code 0000c7442420000000004c8d053f00000031c931d24531c9ff1500000000488b
|
||||
code 0c2518020500488b3500000000baffffffffffd6488b0c2510020500baffffff
|
||||
code ffffd64883c4305ec30f1f8000000000564883ec20488b0c2510020500488b35
|
||||
code 00000000baffffffffffd6488b0c2518020500ff1500000000488b0c25080205
|
||||
code 00baffffffffffd631c04883c4205ec356574883ec3831c931d24531c0ff1500
|
||||
code 000000488904250802050031c9ba010000004531c04531c9ff15000000004889
|
||||
code 042588010500488b042508020500488904259001050048c744242800000000c7
|
||||
code 442420000000004c8d059200000031c931d24531c9ff15000000004889c6488b
|
||||
code 3d000000004889c1baffffffffffd74889f1ff1500000000ba88010500b90200
|
||||
code 00004531c041b9ffffffffff150000000089c04889042500000500488b0c2508
|
||||
code 020500ff150000000048984889042508000500488b0c2508020500baffffffff
|
||||
code ffd789c048890425100005004883c4385f5ec3666666662e0f1f840000000000
|
||||
code 4883ec28488b0c2508020500baffffffffff150000000031c04883c428c36690
|
||||
code 564883ec3048c744242800000000c7442420000000004c8d053300000031c931
|
||||
code d24531c9ff15000000004889c64889c1baffffffffff15000000004889f1ff15
|
||||
code 000000004883c4305ec3660f1f4400004883ec2831c9e8451a00004883c428c3
|
||||
code 56574883ec38488b350000000031c9ba010000004531c04531c9ffd648890425
|
||||
code 0802050031c931d241b8050000004531c9ff1500000000488904251002050031
|
||||
code c9ba0100000041b8010000004531c9ffd64889042518020500488b0425080205
|
||||
code 004889042588010500488b042510020500488904259001050048c74424280000
|
||||
code 0000c7442420000000004c8d056f00000031c931d24531c9ff15000000004889
|
||||
code c6ba88010500b9020000004531c041b9ffffffffff150000000089c048890425
|
||||
code 00000500488b3d000000004889f1baffffffffffd74889f1ff1500000000488b
|
||||
code 0c251002050031d2ffd789c048890425080005004883c4385f5ec30f1f440000
|
||||
code 56574883ec28be64000000488b3d0000000066666666662e0f1f840000000000
|
||||
code ffd7ffce75fa488b0c2508020500ff1500000000488b04251802050048890425
|
||||
code 900105004889042588010500488b0c2510020500ba010000004531c0ff150000
|
||||
code 000031c04883c4285f5ec30f1f4400004883ec3848c744242800000000c74424
|
||||
code 20000000004c8d05a4f7ffff31c931d24531c9ff1500000000ff150000000048
|
||||
code 83c438c36666662e0f1f8400000000004883ec3831c931d24531c04531c9ff15
|
||||
code 00000000488904250802050048c744242800000000c7442420000000004c8d05
|
||||
code 2c00000031c931d24531c9ff1500000000b903000000ff15000000004883c438
|
||||
code c36666666666662e0f1f8400000000004883ec28488b0c2508020500ba1e0000
|
||||
code 00ff150000000089c0488904250000050048c70425080005000100000031c048
|
||||
code 83c428c36666662e0f1f84000000000056574883ec3831c9ba010000004531c0
|
||||
code ff1500000000488904250802050048c744242800000000c7442420000000004c
|
||||
code 8d054a02000031c931d24531c9ff1500000000bf1e000000488b350000000090
|
||||
code ffd6ffcf75fa488b0c2508020500ff1500000000488b0c250802050031d2ff15
|
||||
code 0000000089c04889042500000500488b0425000105004889042508000500bf1e
|
||||
code 000000666666662e0f1f840000000000ffd6ffcf75fa488b0425000105004889
|
||||
code 04251000050031c931d241b8050000004531c9ff150000000048890425080205
|
||||
code 0048c744242800000000c7442420000000004c8d059701000031c931d24531c9
|
||||
code ff1500000000bf1e0000000f1f440000ffd6ffcf75fa488b0c2508020500ba01
|
||||
code 0000004531c0ff1500000000488b0c250802050031d2ff150000000089c04889
|
||||
code 042518000500488b0425000105004889042520000500bf1e0000000f1f440000
|
||||
code ffd6ffcf75fa488b042500010500488904252800050031c931d24531c04531c9
|
||||
code ff1500000000488904250802050048c744242800000000c7442420000000004c
|
||||
code 8d05ea00000031c931d24531c9ff1500000000bf1e0000000f1f840000000000
|
||||
code ffd6ffcf75fa488b0c2508020500ff1500000000488b0c250802050031d2ff15
|
||||
code 0000000089c04889042530000500488b0425000105004889042538000500bf1e
|
||||
code 000000666666662e0f1f840000000000ffd6ffcf75fa488b0425000105004889
|
||||
code 04254000050048c744242800000000c7442420000000004c8d05a2f6ffff31c9
|
||||
code 31d24531c9ff1500000000488b0c2508020500ff15000000008b042524020500
|
||||
code 4889042548000500bf1e0000000f1f00ffd6ffcf75fa8b042524020500488904
|
||||
code 25500005004883c4385f5ec30f1f40004883ec28488b0c2508020500baffffff
|
||||
code ffff150000000048ff04250001050031c04883c428c3662e0f1f840000000000
|
||||
code 5657534883ec3031c931d241b8050000004531c9ff1500000000488904250802
|
||||
code 050048c744242800000000c7442420000000004c8d0596ffffff31c931d24531
|
||||
code c9ff15000000004889c6bb1e000000488b3d00000000662e0f1f840000000000
|
||||
code ffd7ffcb75fa4889f1ff150000000089c04889042500000500488b0c25080205
|
||||
code 00ba010000004531c0ff1500000000bb1e0000006666662e0f1f840000000000
|
||||
code ffd7ffcb75fa488b0c2508020500488b3d0000000031d2ffd789c04889042508
|
||||
code 000500488b0425000105004889042510000500488b0c2508020500ba01000000
|
||||
code 4531c0ff15000000004889f1ff15000000004889f1baffffffffffd74889f1ff
|
||||
code 1500000000488b04250001050048890425180005004883c4305b5f5ec30f1f00
|
||||
code 4157415641554154565755534883ec3831c9ba010000004531c04531c9ff1500
|
||||
code 000000488904250802050048c744242800000000c7442420000000004c8d056d
|
||||
code feffff31c931d24531c9ff15000000004889c74889c1ff150000000089c6c744
|
||||
code 2434000000004c8b3500000000b94000100031d24189c041ffd64889c3b90200
|
||||
code 000031d24189f041ffd64989c6488b2d000000004889d9ffd589c04889042500
|
||||
code 0005004c8b2d0000000041ffd589c048890425080005004889d9ba01000000ff
|
||||
code 15000000004898488904251000050041ffd589c048890425180005004c8b2500
|
||||
code 0000004c8d7c24344889d94c89fa41ffd4489848890425200005008b44243448
|
||||
code 890425280005004c89f1ffd589c048890425300005004c89f1ff150000000089
|
||||
code c048890425380005004c89f14c89fa41ffd4489848890425400005004c8b3d00
|
||||
code 0000004c89f131d241ffd789c0488904254800050041ffd589c0488904255000
|
||||
code 05004c89f14c8b350000000041ffd689c04889042558000500488b0c25080205
|
||||
code 00ff15000000004889f9baffffffff41ffd74889f9ff15000000004889d941ff
|
||||
code d631c939f00f94c148890c25600005004883c4385b5d5f5e415c415d415e415f
|
||||
code c36666666666662e0f1f840000000000564883ec3048c744242800000000c744
|
||||
code 2420000000004c8d053300000031c931d24531c9ff15000000004889c64889c1
|
||||
code baffffffffff15000000004889f1ff15000000004883c4305ec3660f1f440000
|
||||
code f431c0c36666662e0f1f8400000000004157415641545657534883ec38bb3200
|
||||
code 0000488d35670000004c8b35000000004c8b3d000000004c8b25000000006690
|
||||
code 48c744242800000000c74424200000000031c931d24989f04531c941ffd64889
|
||||
code c74889c1baffffffff41ffd74889f941ffd4ffcb75ca4883c4385b5f5e415c41
|
||||
code 5e415fc36666662e0f1f8400000000005048c704240000000048833c25080105
|
||||
code 00004889e075084889042508010500488b0c250801050031d24839c10f94c248
|
||||
code 0114250001050031c059c30f1f44000056574883ec3831f631c931d24531c045
|
||||
code 31c9ff1500000000488904250802050048c744242800000000c7442420000000
|
||||
code 004c8d05d8f1ffff31c931d24531c9ff1500000000833c252402050000752831
|
||||
code f6488b3d000000000f1f840000000000488b0c2508020500ffd748ffc6833c25
|
||||
code 240205000074e98b042524020500488904250000050048893425080005004883
|
||||
code c4385f5ec366662e0f1f84000000000041565657534883ec38b928020500ff15
|
||||
code 0000000048c744242800000000c7442420000000004c8d0584000000488b3d00
|
||||
code 00000031c931d24531c9ffd74889c6488b1d000000004889c1baffffffffffd3
|
||||
code 4c8b35000000004889f141ffd6b928020500ff15000000004898488904253800
|
||||
code 050048c744242800000000c7442420000000004c8d05a600000031c931d24531
|
||||
code c9ffd74889c64889c1baffffffffffd34889f141ffd64883c4385b5f5e415ec3
|
||||
code 564883ec30c744242c00000000b928020500ff1500000000488b342538020500
|
||||
code ff150000000089c031c94839c60f94c148890c2500000500b950020500ff1500
|
||||
code 0000004c8d44242cb95802050031d24531c9ff150000000085c00f95c0837c24
|
||||
code 2c000f95c120c10fb6c1488904250800050031c04883c4305ec3660f1f440000
|
||||
code 4883ec28c744242400000000b928020500ff1500000000489848890425100005
|
||||
code 00b950020500ff15000000000fb6c04889042518000500b950020500ff150000
|
||||
code 00000fb6c04889042520000500b95802050031d24531c0ff1500000000489848
|
||||
code 89042528000500488d442424488904253000050031c04883c428c30f1f440000
|
||||
code 41574156415541545657534883ec304531f6ba0000010031c941b80030000041
|
||||
code b904000000ff15000000004889c6488d3d7b0000004c8b3d000000004c8b2500
|
||||
code 0000004c8b2d00000000660f1f4400004e8d0c3648c744242800000000c74424
|
||||
code 200000000031c931d24989f841ffd74889c34889c1baffffffff41ffd44889d9
|
||||
code 41ffd548ff0425000105004983c6084981fe409c000075b84883c4305b5f5e41
|
||||
code 5c415d415e415fc30f1f8400000000004883ec28c7442424000000004c8d4424
|
||||
code 2431d24531c9ff150000000031c04883c428c3666666662e0f1f840000000000
|
||||
code 56574883ec38c74424340000000048c744242800000000c7442420000000004c
|
||||
code 8d058a00000031c931d24531c9ff15000000004889c6488b3d000000004889c1
|
||||
code baffffffffffd74889f1ff1500000000488b0c258801050031d2ffd789c04889
|
||||
code 042530000500488b0c2588010500488d542434ff15000000008b442434488904
|
||||
code 253800050048c7c1feffffffff1500000000489848890425400005004883c438
|
||||
code 5f5ec3666666662e0f1f840000000000564883ec5048c744244000000000c744
|
||||
code 244c00000000c744243002000000c744242800000000c7442420000000004c8d
|
||||
code 4c244048c7c1ffffffff48c7c2feffffff49c7c0ffffffffff15000000004898
|
||||
code 4889042500000500488b4c2440ff150000000089c6ff150000000031c939c60f
|
||||
code 94c148890c2508000500488b4c244031d2ff150000000089c048890425100005
|
||||
code 00488b4c2440488d54244cff150000000085c00f95c0817c244c030100000f94
|
||||
code c120c10fb6c1488904251800050048c7c1feffffffba02000000ff1500000000
|
||||
code 48984889042520000500ff150000000089c04889042528000500488b44244048
|
||||
code 89042588010500b82c0000004883c4505ec366666666662e0f1f840000000000
|
||||
code 564883ec3048c744242800000000c7442420000000004c8d0533000000ba0010
|
||||
code 000041b9c800000031c9ff15000000004889c64889c1baffffffffff15000000
|
||||
code 004889f1ff15000000004883c4305ec34883ec2848c744242000000000488d54
|
||||
code 24204889142508010500e8010c00004889042500000500b8010000004883c428
|
||||
code c36666666666662e0f1f840000000000564883ec3048c744242800000000c744
|
||||
code 2420000001004c8d05a3ffffffba0010000041b9c800000031c9ff1500000000
|
||||
code 4889c64889c1baffffffffff15000000004889f1ff15000000004883c4305ec3
|
||||
code 564883ec3048b90000000006000000ba0000010041b80030000041b904000000
|
||||
code ff1500000000488904250000050048c744242800000000c7442420000000004c
|
||||
code 8d05faebffff31c931d24531c9ff15000000004889c631c04885f60f95c04889
|
||||
code 0425080005004889f1baffffffffff15000000004889f1ff15000000008b0425
|
||||
code 2402050048890425100005004883c4305ec366666666662e0f1f840000000000
|
||||
code 564883ec3048c744242800000000c7442420000000004c8d053300000031c931
|
||||
code d24531c9ff15000000004889c64889c1baffffffffff15000000004889f1ff15
|
||||
code 000000004883c4305ec3660f1f44000056574883ec2848c74424200000000048
|
||||
code 8d7424204881e6000000ff488d8e00100000488b3d0000000031d241b8008000
|
||||
code 00ffd7489848890425000005004881ce0000f0004889f131d241b800800000ff
|
||||
code d74898488904250800050031c04883c4285f5ec36666662e0f1f840000000000
|
||||
code 4157415641545657534883ec38c74424340000000031c931d24531c04531c9ff
|
||||
code 1500000000488904250802050048c744242800000000c7442420000000004c8d
|
||||
code 058b02000031c931d24531c9ff15000000004889c7be1e000000488b1d000000
|
||||
code 006666666666662e0f1f840000000000ffd3ffce75fa4c8b25000000004889f9
|
||||
code ba3c00000041ffd4489848890425000005004c8b3d00000000488d7424344889
|
||||
code f94889f241ffd78b4424344889042508000500488b0c2508020500ff15000000
|
||||
code 00488b0c25080205004c8b350000000031d241ffd689c0488904251000050048
|
||||
code c744242800000000c7442420040000004c8d05d9010000488b1d0000000031c9
|
||||
code 31d24531c9ffd34889c74889c1ba3e00000041ffd44898488904251800050048
|
||||
code 89f9baffffffff41ffd689c0488904252000050048c744242800000000c74424
|
||||
code 20000000004c8d05b401000031c931d24531c9ffd34889c74889c1baffffffff
|
||||
code 41ffd64889f94889f241ffd78b44243448890425280005008b04252402050048
|
||||
code 89042530000500488b350000000031c931d24531c0ffd6488904258801050031
|
||||
code c931d24531c0ffd6488904259001050048c744242800000000c7442420000000
|
||||
code 004c8d056801000031c931d24531c9ffd34889c64889c1baffffffff41ffd648
|
||||
code 89f1ff1500000000488b3500000000ba88010500b90200000041b80100000041
|
||||
code b9ffffffffffd689c04889042538000500488b0c2588010500488b3d00000000
|
||||
code ffd7488b0c2590010500ffd7ba88010500b90200000041b80100000041b9ffff
|
||||
code ffffffd689c0488904254000050048c744242800000000c7442420040000004c
|
||||
code 8d057ae8ffff31c931d24531c9ffd34889c6bf7e000000488b1d000000006690
|
||||
code 4889f1ffd3ffcf75f74889f1ff150000000089c04889042548000500ff150000
|
||||
code 000089c048890425500005004889f131d2ff15000000004883c4385b5f5e415c
|
||||
code 415e415fc366662e0f1f8400000000004883ec28488b0c2508020500baffffff
|
||||
code ffff1500000000c70425240205000900000031c04883c428c30f1f8000000000
|
||||
code 4883ec2848c7c1feffffffba3d000000ff1500000000c7042524020500090000
|
||||
code 0031c04883c428c30f1f8400000000004883ec28ba88010500b90200000041b8
|
||||
code 0100000041b9ffffffffff150000000031c04883c428c3660f1f840000000000
|
||||
code 4883ec28ff1500000000890425200205008b0c2520020500ba4d000000ff1500
|
||||
code 000000b958000000ff150000000048c744242000000000488b442420483db70b
|
||||
code 0000771e6666662e0f1f84000000000048ff442420488b442420483db80b0000
|
||||
code 72eeff150000000089c048890425000005008b0c2520020500ff150000000048
|
||||
code 890425080005004883c428c30f1f4000564883ec3031c9ba010000004531c045
|
||||
code 31c9ff1500000000488904250802050048c744242800000000488b442428483d
|
||||
code e70300007726488b35000000000f1f00488b0c2508020500ffd648ff44242848
|
||||
code 8b442428483de803000072e44883c4305ec366666666662e0f1f840000000000
|
||||
code 41565657534883ec3848c744242800000000c7442420000000004c8d056f0000
|
||||
code 00488b3d0000000031c931d24531c9ffd74889c6488b1d000000004889c1baff
|
||||
code ffffffffd34c8b35000000004889f141ffd648c744242800000000c744242000
|
||||
code 0000004c8d054600000031c931d24531c9ffd74889c64889c1baffffffffffd3
|
||||
code 4889f141ffd64883c4385b5f5e415ec34883ec28b950020500ff150000000031
|
||||
code c04883c428c3662e0f1f8400000000004883ec28b950020500ff1500000000c7
|
||||
code 04252402050001000000b8010000004883c428c36666662e0f1f840000000000
|
||||
code 41565657534883ec3848c744242800000000c7442420000000004c8d059f0000
|
||||
code 00488b3d0000000031c931d24531c9ffd74889c6488b1d000000004889c1baff
|
||||
code ffffffffd34c8b35000000004889f141ffd6b950020500ff15000000000fb6c0
|
||||
code 4889042500000500b950020500ff15000000000fb6c0488904250800050048c7
|
||||
code 44242800000000c7442420000000004c8d054a00000031c931d24531c9ffd748
|
||||
code 89c64889c1baffffffffffd34889f141ffd64883c4385b5f5e415ec30f1f4000
|
||||
code 4883ec28b950020500ff150000000031c04883c428c3662e0f1f840000000000
|
||||
code 4883ec28b950020500ff1500000000c704252402050001000000b80100000048
|
||||
code 83c428c36666662e0f1f84000000000056574883ec3831c931d24531c04531c9
|
||||
code ff1500000000488904250802050048c744242800000000c7442420000000004c
|
||||
code 8d058a00000031c931d24531c9ff15000000004889c6c7042524020500010000
|
||||
code 00488b0c2508020500488b3d00000000ba32000000ffd789c048890425000005
|
||||
code 004889f1baffffffffffd789c04889042508000500488b0c250802050031d2ff
|
||||
code d789c04889042510000500488b0c250802050031d2ffd789c048890425180005
|
||||
code 004883c4385f5ec30f1f84000000000056574883ec28833c252402050000751c
|
||||
code 488b3500000000660f1f840000000000ffd6833c25240205000074f4be1e0000
|
||||
code 00488b3d000000000f1f840000000000ffd7ffce75fab800000600b964000000
|
||||
code ffd0488b0c2508020500ff150000000031c04883c4285f5ec30f1f8000000000
|
||||
code 4883ec2831c9ba010000004531c04531c9ff1500000000488904250802050048
|
||||
code 89042588010500ba88010500b90100000041b80100000041b9e8030000ff1500
|
||||
code 00000089c0488904250000050048c7042508000500010000004883c428c36690
|
||||
code 564883ec30ff150000000089c6b94000000031d24189c0ff150000000031c948
|
||||
code 85c00f95c148890c25000005004189f148c744242800000000c7442420000000
|
||||
code 004c8d053800000031c931d2ff150000000031c94885c00f95c148890c250800
|
||||
code 0500b903000000ff15000000004883c4305ec3666666662e0f1f840000000000
|
||||
code 5657534883ec204889cebf1e000000488b1d00000000662e0f1f840000000000
|
||||
code ffd3ffcf75fab94000000031d24189f0ff15000000004889042510000500ff15
|
||||
code 0000000089c0488904251800050031c04883c4205b5f5ec30f1f840000000000
|
||||
code 5657534883ec40c744243c0000000031c9ba010000004531c04531c9ff150000
|
||||
code 0000488904250802050048c744242800000000c744242000000000488d359e00
|
||||
code 0000488b3d0000000031c931d24989f04989c1ffd74889042588010500488b1d
|
||||
code 000000004889c1baffffffffffd389c048890425000005004c8b0c2508020500
|
||||
code 48c744242800000000c74424200000000031c931d24989f0ffd7488904259001
|
||||
code 05004889c1bae8030000ffd389c04889042508000500488b0c2590010500488d
|
||||
code 54243cff15000000008b44243c48890425100005004883c4405b5f5ec30f1f00
|
||||
code ba3200000048ff25000000000f1f40004883ec38b810000600ffd048c7442428
|
||||
code 00000000c7442420000000004c8d053dd3ffff41b96100000031c931d2ff1500
|
||||
code 0000004889c1baffffffffff150000000089c048890425080005004883c438c3
|
||||
code 4881ec2802000048894c242048ff042500000500488d4c2420e8e2ffffff4803
|
||||
code 4424204881c428020000c30f1f4400004881ec2802000048894c242048895424
|
||||
code 284885c9741a48ffc9488d542420e8ddffffff48034424204881c428020000c3
|
||||
code 488d442420488904251001050031c04881c428020000c3
|
||||
@@ -0,0 +1,130 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Thread-local storage layout as compiled code reads it (#76).
|
||||
//!
|
||||
//! Microsoft's public PE Format page ("The .tls Section") describes the
|
||||
//! access: load the address of the thread's TLS array from the thread
|
||||
//! environment block, load the module's TLS index from the address the TLS
|
||||
//! directory names, use the index times the pointer size as an offset into
|
||||
//! the array to get the address of the module's data block, then add the
|
||||
//! variable's offset in the template. The block starts as a copy of the
|
||||
//! template followed by `SizeOfZeroFill` zero bytes.
|
||||
//!
|
||||
//! The startup harness stores the `thread_tls_base` it passes to `setup_tls`
|
||||
//! in the TEB's TLS pointer field, so these tests start from that value and
|
||||
//! follow the same steps through guest memory. The directory and template are
|
||||
//! original. Nothing here ran on Windows.
|
||||
|
||||
use xenora_loader::{GuestMemory, MemoryError, MemoryPermissions as P, TlsDirectory, setup_tls};
|
||||
|
||||
const IMAGE: u64 = 0x1_4000_0000;
|
||||
const TEMPLATE: u64 = IMAGE + 0x3000;
|
||||
const INDEX: u64 = IMAGE + 0x4000;
|
||||
const THREAD_TLS: u64 = 0x3_0000_0000;
|
||||
/// Read as a pointer, the first eight bytes are the template's own address, so
|
||||
/// a layout that takes the data for the array still finds readable memory.
|
||||
const TEMPLATE_BYTES: [u8; 20] = [
|
||||
0x00, 0x30, 0x00, 0x40, 0x01, 0x00, 0x00, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88,
|
||||
0xA1, 0xB2, 0xC3, 0xD4,
|
||||
];
|
||||
|
||||
fn directory(template_len: u64, zero_fill: u32) -> TlsDirectory {
|
||||
TlsDirectory {
|
||||
raw_data_start_va: TEMPLATE,
|
||||
raw_data_end_va: TEMPLATE + template_len,
|
||||
index_address: INDEX,
|
||||
size_of_zero_fill: zero_fill,
|
||||
..TlsDirectory::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// An image with the template in read-only data and a writable index that
|
||||
/// does not start at zero.
|
||||
fn image(base: u64) -> GuestMemory {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
TEMPLATE - IMAGE + base,
|
||||
0x1000,
|
||||
P::READ_ONLY,
|
||||
&TEMPLATE_BYTES,
|
||||
)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region_with_data(INDEX - IMAGE + base, 0x1000, P::READ_WRITE, &[0xFF; 8])
|
||||
.unwrap();
|
||||
memory
|
||||
}
|
||||
|
||||
/// The address of the module's data block, found the way compiled code does.
|
||||
fn block_address(memory: &GuestMemory, teb_tls_pointer: u64, index_address: u64) -> u64 {
|
||||
let index = u64::from(memory.read_u32(index_address).unwrap());
|
||||
memory.read_u64(teb_tls_pointer + index * 8).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tls_array_slot_leads_to_a_copy_of_the_template() {
|
||||
let mut memory = image(IMAGE);
|
||||
setup_tls(&directory(20, 12), IMAGE, IMAGE, &mut memory, THREAD_TLS).unwrap();
|
||||
|
||||
assert_eq!(memory.read_u32(INDEX), Ok(0));
|
||||
let block = block_address(&memory, THREAD_TLS, INDEX);
|
||||
assert_ne!(block, THREAD_TLS, "the array is not the data block");
|
||||
assert_ne!(block, TEMPLATE, "the block is the thread's own copy");
|
||||
let mut data = [0xEEu8; 32];
|
||||
memory.read_bytes(block, &mut data).unwrap();
|
||||
assert_eq!(data[..20], TEMPLATE_BYTES);
|
||||
assert_eq!(data[20..], [0u8; 12]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_thread_block_is_writable_and_separate_from_the_template() {
|
||||
let mut memory = image(IMAGE);
|
||||
setup_tls(&directory(20, 12), IMAGE, IMAGE, &mut memory, THREAD_TLS).unwrap();
|
||||
let block = block_address(&memory, THREAD_TLS, INDEX);
|
||||
|
||||
memory.write_u64(block + 8, 0x0102_0304_0506_0708).unwrap();
|
||||
assert_eq!(memory.read_u64(block + 8), Ok(0x0102_0304_0506_0708));
|
||||
// The image's template is the initial value for later threads.
|
||||
let mut template = [0u8; 20];
|
||||
memory.read_bytes(TEMPLATE, &mut template).unwrap();
|
||||
assert_eq!(template, TEMPLATE_BYTES);
|
||||
// The array slot still names the block after the block is written.
|
||||
assert_eq!(block_address(&memory, THREAD_TLS, INDEX), block);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rebased_image_uses_its_loaded_addresses() {
|
||||
let loaded = IMAGE + 0x20_0000;
|
||||
let mut memory = image(loaded);
|
||||
setup_tls(&directory(20, 0), loaded, IMAGE, &mut memory, THREAD_TLS).unwrap();
|
||||
|
||||
let index_address = INDEX - IMAGE + loaded;
|
||||
assert_eq!(memory.read_u32(index_address), Ok(0));
|
||||
let block = block_address(&memory, THREAD_TLS, index_address);
|
||||
let mut data = [0u8; 20];
|
||||
memory.read_bytes(block, &mut data).unwrap();
|
||||
assert_eq!(data, TEMPLATE_BYTES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zero_fill_only_directory_gets_a_zeroed_block() {
|
||||
let mut memory = image(IMAGE);
|
||||
setup_tls(&directory(0, 24), IMAGE, IMAGE, &mut memory, THREAD_TLS).unwrap();
|
||||
let block = block_address(&memory, THREAD_TLS, INDEX);
|
||||
let mut data = [0xEEu8; 24];
|
||||
memory.read_bytes(block, &mut data).unwrap();
|
||||
assert_eq!(data, [0u8; 24]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inverted_template_range_is_rejected_before_anything_is_mapped() {
|
||||
let mut memory = image(IMAGE);
|
||||
let mut inverted = directory(20, 0);
|
||||
inverted.raw_data_end_va = TEMPLATE - 1;
|
||||
assert!(setup_tls(&inverted, IMAGE, IMAGE, &mut memory, THREAD_TLS).is_err());
|
||||
assert_eq!(
|
||||
memory.read_u64(THREAD_TLS),
|
||||
Err(MemoryError::UnmappedAddress(THREAD_TLS))
|
||||
);
|
||||
}
|
||||
@@ -54,11 +54,18 @@ def cases():
|
||||
for bits in (8, 16, 32, 64):
|
||||
out += [f"{op} {reg(1, bits)}", f"{op} {reg(9, bits)}", f"{op} {mem(bits)}"]
|
||||
out.append(f"{op} ch")
|
||||
for op in "rol ror shl shr sar".split():
|
||||
for op in "rol ror rcl rcr shl shr sar".split():
|
||||
for bits in (8, 16, 32, 64):
|
||||
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",
|
||||
@@ -84,11 +91,27 @@ def cases():
|
||||
f"mov {mem(bits)}, {reg(2, bits)}", f"mov {reg(14, bits)}, 0x5a",
|
||||
f"mov {mem(bits)}, 0x5a", f"xchg {reg(3, bits)}, {reg(9, bits)}",
|
||||
f"xchg {mem(bits)}, {reg(2, bits)}"]
|
||||
for op in ("xadd", "cmpxchg"):
|
||||
for bits in (8, 16, 32, 64):
|
||||
# Destination RAX always matches the accumulator; a register with
|
||||
# itself keeps the sum. LOCK is valid only with a memory destination.
|
||||
out += [f"{op} {reg(3, bits)}, {reg(1, bits)}", f"{op} {reg(9, bits)}, {reg(12, bits)}",
|
||||
f"{op} {reg(0, bits)}, {reg(2, bits)}", f"{op} {reg(3, bits)}, {reg(3, bits)}",
|
||||
f"{op} {mem(bits)}, {reg(2, bits)}", f"lock {op} {mem(bits)}, {reg(2, bits)}",
|
||||
f"lock {op} {mem(bits)}, {reg(0, bits)}"]
|
||||
out += [f"{op} ah, bl", f"{op} cl, dh", f"{op} {mem(8)}, ch"]
|
||||
out += ["mov ah, bl", "mov dl, ch", "mov bh, 0x21", "xchg ah, bl", "mov sil, dil",
|
||||
"movabs r15, 0x8877665544332211", "mov rcx, -2", "bswap ebx", "bswap r9",
|
||||
"cbw", "cwde", "cdqe", "cwd", "cdq", "cqo", "clc", "stc", "cmc", "nop",
|
||||
"nop dword ptr [rax + 8]", "pause", "push r9", "push rbx", "push -5", "push 0x12345678",
|
||||
"cbw", "cwde", "cdqe", "cwd", "cdq", "cqo", "clc", "stc", "cmc", "nop", "cpuid",
|
||||
"nop dword ptr [rax + 8]", "pause", "lfence", "mfence", "sfence",
|
||||
f"movnti {mem(32)}, ebx", f"movnti {mem(64)}, rbx",
|
||||
f"movnti {mem(32)}, r9d", f"movnti {mem(64)}, r14", "push r9", "push rbx", "push -5", "push 0x12345678",
|
||||
f"push {mem(64)}", "pop rbx", "pop r12", f"pop {mem(64)}", "leave"]
|
||||
# The accumulator short form of XCHG: 91..97, and 90 with REX.B.
|
||||
for index in range(1, 16):
|
||||
bits = (16, 32, 64)[index % 3]
|
||||
out.append(f"xchg {reg(0, bits)}, {reg(index, bits)}")
|
||||
out += ["xchg r8w, ax", "xchg r8, rax", "xchg r8d, eax", "xchg ecx, eax", "xchg r15w, ax"]
|
||||
return list(dict.fromkeys(out))
|
||||
|
||||
|
||||
@@ -163,7 +186,13 @@ def assemble(lines):
|
||||
subprocess.run(["clang", "-target", "x86_64-apple-macos", "-c", source, "-o", obj], check=True)
|
||||
# One line per instruction: objdump never wraps its raw bytes.
|
||||
listing = subprocess.run(["objdump", "-d", obj], check=True, capture_output=True, text=True).stdout
|
||||
rows = [m.group(1).split() for m in re.finditer(r"^\s*[0-9a-f]+:\s((?:[0-9a-f]{2}\s)+)", listing, re.M)]
|
||||
rows, prefix = [], []
|
||||
for match in re.finditer(r"^\s*[0-9a-f]+:\s((?:[0-9a-f]{2}\s)+)(.*)$", listing, re.M):
|
||||
row = prefix + match.group(1).split()
|
||||
# objdump lists a leading LOCK prefix on a row of its own.
|
||||
prefix = row if match.group(2).strip() == "lock" else []
|
||||
if not prefix:
|
||||
rows.append(row)
|
||||
if len(rows) != len(lines):
|
||||
sys.exit(f"{len(lines)} instructions assembled to {len(rows)} rows")
|
||||
return "".join(f"{' '.join(row)} | {line}\n" for row, line in zip(rows, lines))
|
||||
|
||||
@@ -547,6 +547,86 @@ d3 4c be 10 | ror dword ptr [rsi + 4*rdi + 16], cl
|
||||
48 d3 4c be 10 | ror qword ptr [rsi + 4*rdi + 16], cl
|
||||
49 c1 cd 3f | ror r13, 63
|
||||
49 c1 cd 00 | ror r13, 0
|
||||
d0 d3 | rcl bl, 1
|
||||
d0 54 be 10 | rcl byte ptr [rsi + 4*rdi + 16], 1
|
||||
c0 d3 03 | rcl bl, 3
|
||||
c0 54 be 10 03 | rcl byte ptr [rsi + 4*rdi + 16], 3
|
||||
c0 d3 07 | rcl bl, 7
|
||||
c0 54 be 10 07 | rcl byte ptr [rsi + 4*rdi + 16], 7
|
||||
d2 d3 | rcl bl, cl
|
||||
d2 54 be 10 | rcl byte ptr [rsi + 4*rdi + 16], cl
|
||||
41 c0 d5 07 | rcl r13b, 7
|
||||
41 c0 d5 00 | rcl r13b, 0
|
||||
66 d1 d3 | rcl bx, 1
|
||||
66 d1 54 be 10 | rcl word ptr [rsi + 4*rdi + 16], 1
|
||||
66 c1 d3 03 | rcl bx, 3
|
||||
66 c1 54 be 10 03 | rcl word ptr [rsi + 4*rdi + 16], 3
|
||||
66 c1 d3 07 | rcl bx, 7
|
||||
66 c1 54 be 10 07 | rcl word ptr [rsi + 4*rdi + 16], 7
|
||||
66 d3 d3 | rcl bx, cl
|
||||
66 d3 54 be 10 | rcl word ptr [rsi + 4*rdi + 16], cl
|
||||
66 41 c1 d5 0f | rcl r13w, 15
|
||||
66 41 c1 d5 00 | rcl r13w, 0
|
||||
d1 d3 | rcl ebx, 1
|
||||
d1 54 be 10 | rcl dword ptr [rsi + 4*rdi + 16], 1
|
||||
c1 d3 03 | rcl ebx, 3
|
||||
c1 54 be 10 03 | rcl dword ptr [rsi + 4*rdi + 16], 3
|
||||
c1 d3 07 | rcl ebx, 7
|
||||
c1 54 be 10 07 | rcl dword ptr [rsi + 4*rdi + 16], 7
|
||||
d3 d3 | rcl ebx, cl
|
||||
d3 54 be 10 | rcl dword ptr [rsi + 4*rdi + 16], cl
|
||||
41 c1 d5 1f | rcl r13d, 31
|
||||
41 c1 d5 00 | rcl r13d, 0
|
||||
48 d1 d3 | rcl rbx, 1
|
||||
48 d1 54 be 10 | rcl qword ptr [rsi + 4*rdi + 16], 1
|
||||
48 c1 d3 03 | rcl rbx, 3
|
||||
48 c1 54 be 10 03 | rcl qword ptr [rsi + 4*rdi + 16], 3
|
||||
48 c1 d3 07 | rcl rbx, 7
|
||||
48 c1 54 be 10 07 | rcl qword ptr [rsi + 4*rdi + 16], 7
|
||||
48 d3 d3 | rcl rbx, cl
|
||||
48 d3 54 be 10 | rcl qword ptr [rsi + 4*rdi + 16], cl
|
||||
49 c1 d5 3f | rcl r13, 63
|
||||
49 c1 d5 00 | rcl r13, 0
|
||||
d0 db | rcr bl, 1
|
||||
d0 5c be 10 | rcr byte ptr [rsi + 4*rdi + 16], 1
|
||||
c0 db 03 | rcr bl, 3
|
||||
c0 5c be 10 03 | rcr byte ptr [rsi + 4*rdi + 16], 3
|
||||
c0 db 07 | rcr bl, 7
|
||||
c0 5c be 10 07 | rcr byte ptr [rsi + 4*rdi + 16], 7
|
||||
d2 db | rcr bl, cl
|
||||
d2 5c be 10 | rcr byte ptr [rsi + 4*rdi + 16], cl
|
||||
41 c0 dd 07 | rcr r13b, 7
|
||||
41 c0 dd 00 | rcr r13b, 0
|
||||
66 d1 db | rcr bx, 1
|
||||
66 d1 5c be 10 | rcr word ptr [rsi + 4*rdi + 16], 1
|
||||
66 c1 db 03 | rcr bx, 3
|
||||
66 c1 5c be 10 03 | rcr word ptr [rsi + 4*rdi + 16], 3
|
||||
66 c1 db 07 | rcr bx, 7
|
||||
66 c1 5c be 10 07 | rcr word ptr [rsi + 4*rdi + 16], 7
|
||||
66 d3 db | rcr bx, cl
|
||||
66 d3 5c be 10 | rcr word ptr [rsi + 4*rdi + 16], cl
|
||||
66 41 c1 dd 0f | rcr r13w, 15
|
||||
66 41 c1 dd 00 | rcr r13w, 0
|
||||
d1 db | rcr ebx, 1
|
||||
d1 5c be 10 | rcr dword ptr [rsi + 4*rdi + 16], 1
|
||||
c1 db 03 | rcr ebx, 3
|
||||
c1 5c be 10 03 | rcr dword ptr [rsi + 4*rdi + 16], 3
|
||||
c1 db 07 | rcr ebx, 7
|
||||
c1 5c be 10 07 | rcr dword ptr [rsi + 4*rdi + 16], 7
|
||||
d3 db | rcr ebx, cl
|
||||
d3 5c be 10 | rcr dword ptr [rsi + 4*rdi + 16], cl
|
||||
41 c1 dd 1f | rcr r13d, 31
|
||||
41 c1 dd 00 | rcr r13d, 0
|
||||
48 d1 db | rcr rbx, 1
|
||||
48 d1 5c be 10 | rcr qword ptr [rsi + 4*rdi + 16], 1
|
||||
48 c1 db 03 | rcr rbx, 3
|
||||
48 c1 5c be 10 03 | rcr qword ptr [rsi + 4*rdi + 16], 3
|
||||
48 c1 db 07 | rcr rbx, 7
|
||||
48 c1 5c be 10 07 | rcr qword ptr [rsi + 4*rdi + 16], 7
|
||||
48 d3 db | rcr rbx, cl
|
||||
48 d3 5c be 10 | rcr qword ptr [rsi + 4*rdi + 16], cl
|
||||
49 c1 dd 3f | rcr r13, 63
|
||||
49 c1 dd 00 | rcr r13, 0
|
||||
d0 e3 | shl bl, 1
|
||||
d0 64 be 10 | shl byte ptr [rsi + 4*rdi + 16], 1
|
||||
c0 e3 03 | shl bl, 3
|
||||
@@ -667,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
|
||||
@@ -953,6 +1105,68 @@ c7 44 be 10 5a 00 00 00 | mov dword ptr [rsi + 4*rdi + 16], 0x5a
|
||||
48 c7 44 be 10 5a 00 00 00 | mov qword ptr [rsi + 4*rdi + 16], 0x5a
|
||||
49 87 d9 | xchg rbx, r9
|
||||
48 87 54 be 10 | xchg qword ptr [rsi + 4*rdi + 16], rdx
|
||||
0f c0 cb | xadd bl, cl
|
||||
45 0f c0 e1 | xadd r9b, r12b
|
||||
0f c0 d0 | xadd al, dl
|
||||
0f c0 db | xadd bl, bl
|
||||
0f c0 54 be 10 | xadd byte ptr [rsi + 4*rdi + 16], dl
|
||||
f0 0f c0 54 be 10 | lock xadd byte ptr [rsi + 4*rdi + 16], dl
|
||||
f0 0f c0 44 be 10 | lock xadd byte ptr [rsi + 4*rdi + 16], al
|
||||
66 0f c1 cb | xadd bx, cx
|
||||
66 45 0f c1 e1 | xadd r9w, r12w
|
||||
66 0f c1 d0 | xadd ax, dx
|
||||
66 0f c1 db | xadd bx, bx
|
||||
66 0f c1 54 be 10 | xadd word ptr [rsi + 4*rdi + 16], dx
|
||||
66 f0 0f c1 54 be 10 | lock xadd word ptr [rsi + 4*rdi + 16], dx
|
||||
66 f0 0f c1 44 be 10 | lock xadd word ptr [rsi + 4*rdi + 16], ax
|
||||
0f c1 cb | xadd ebx, ecx
|
||||
45 0f c1 e1 | xadd r9d, r12d
|
||||
0f c1 d0 | xadd eax, edx
|
||||
0f c1 db | xadd ebx, ebx
|
||||
0f c1 54 be 10 | xadd dword ptr [rsi + 4*rdi + 16], edx
|
||||
f0 0f c1 54 be 10 | lock xadd dword ptr [rsi + 4*rdi + 16], edx
|
||||
f0 0f c1 44 be 10 | lock xadd dword ptr [rsi + 4*rdi + 16], eax
|
||||
48 0f c1 cb | xadd rbx, rcx
|
||||
4d 0f c1 e1 | xadd r9, r12
|
||||
48 0f c1 d0 | xadd rax, rdx
|
||||
48 0f c1 db | xadd rbx, rbx
|
||||
48 0f c1 54 be 10 | xadd qword ptr [rsi + 4*rdi + 16], rdx
|
||||
f0 48 0f c1 54 be 10 | lock xadd qword ptr [rsi + 4*rdi + 16], rdx
|
||||
f0 48 0f c1 44 be 10 | lock xadd qword ptr [rsi + 4*rdi + 16], rax
|
||||
0f c0 dc | xadd ah, bl
|
||||
0f c0 f1 | xadd cl, dh
|
||||
0f c0 6c be 10 | xadd byte ptr [rsi + 4*rdi + 16], ch
|
||||
0f b0 cb | cmpxchg bl, cl
|
||||
45 0f b0 e1 | cmpxchg r9b, r12b
|
||||
0f b0 d0 | cmpxchg al, dl
|
||||
0f b0 db | cmpxchg bl, bl
|
||||
0f b0 54 be 10 | cmpxchg byte ptr [rsi + 4*rdi + 16], dl
|
||||
f0 0f b0 54 be 10 | lock cmpxchg byte ptr [rsi + 4*rdi + 16], dl
|
||||
f0 0f b0 44 be 10 | lock cmpxchg byte ptr [rsi + 4*rdi + 16], al
|
||||
66 0f b1 cb | cmpxchg bx, cx
|
||||
66 45 0f b1 e1 | cmpxchg r9w, r12w
|
||||
66 0f b1 d0 | cmpxchg ax, dx
|
||||
66 0f b1 db | cmpxchg bx, bx
|
||||
66 0f b1 54 be 10 | cmpxchg word ptr [rsi + 4*rdi + 16], dx
|
||||
66 f0 0f b1 54 be 10 | lock cmpxchg word ptr [rsi + 4*rdi + 16], dx
|
||||
66 f0 0f b1 44 be 10 | lock cmpxchg word ptr [rsi + 4*rdi + 16], ax
|
||||
0f b1 cb | cmpxchg ebx, ecx
|
||||
45 0f b1 e1 | cmpxchg r9d, r12d
|
||||
0f b1 d0 | cmpxchg eax, edx
|
||||
0f b1 db | cmpxchg ebx, ebx
|
||||
0f b1 54 be 10 | cmpxchg dword ptr [rsi + 4*rdi + 16], edx
|
||||
f0 0f b1 54 be 10 | lock cmpxchg dword ptr [rsi + 4*rdi + 16], edx
|
||||
f0 0f b1 44 be 10 | lock cmpxchg dword ptr [rsi + 4*rdi + 16], eax
|
||||
48 0f b1 cb | cmpxchg rbx, rcx
|
||||
4d 0f b1 e1 | cmpxchg r9, r12
|
||||
48 0f b1 d0 | cmpxchg rax, rdx
|
||||
48 0f b1 db | cmpxchg rbx, rbx
|
||||
48 0f b1 54 be 10 | cmpxchg qword ptr [rsi + 4*rdi + 16], rdx
|
||||
f0 48 0f b1 54 be 10 | lock cmpxchg qword ptr [rsi + 4*rdi + 16], rdx
|
||||
f0 48 0f b1 44 be 10 | lock cmpxchg qword ptr [rsi + 4*rdi + 16], rax
|
||||
0f b0 dc | cmpxchg ah, bl
|
||||
0f b0 f1 | cmpxchg cl, dh
|
||||
0f b0 6c be 10 | cmpxchg byte ptr [rsi + 4*rdi + 16], ch
|
||||
88 dc | mov ah, bl
|
||||
88 ea | mov dl, ch
|
||||
b7 21 | mov bh, 0x21
|
||||
@@ -972,8 +1186,16 @@ f8 | clc
|
||||
f9 | stc
|
||||
f5 | cmc
|
||||
90 | nop
|
||||
0f a2 | cpuid
|
||||
0f 1f 40 08 | nop dword ptr [rax + 8]
|
||||
f3 90 | pause
|
||||
0f ae e8 | lfence
|
||||
0f ae f0 | mfence
|
||||
0f ae f8 | sfence
|
||||
0f c3 5c be 10 | movnti dword ptr [rsi + 4*rdi + 16], ebx
|
||||
48 0f c3 5c be 10 | movnti qword ptr [rsi + 4*rdi + 16], rbx
|
||||
44 0f c3 4c be 10 | movnti dword ptr [rsi + 4*rdi + 16], r9d
|
||||
4c 0f c3 74 be 10 | movnti qword ptr [rsi + 4*rdi + 16], r14
|
||||
41 51 | push r9
|
||||
53 | push rbx
|
||||
6a fb | push -5
|
||||
@@ -983,3 +1205,23 @@ ff 74 be 10 | push qword ptr [rsi + 4*rdi + 16]
|
||||
41 5c | pop r12
|
||||
8f 44 be 10 | pop qword ptr [rsi + 4*rdi + 16]
|
||||
c9 | leave
|
||||
91 | xchg eax, ecx
|
||||
48 92 | xchg rax, rdx
|
||||
66 93 | xchg ax, bx
|
||||
94 | xchg eax, esp
|
||||
48 95 | xchg rax, rbp
|
||||
66 96 | xchg ax, si
|
||||
97 | xchg eax, edi
|
||||
49 90 | xchg rax, r8
|
||||
66 41 91 | xchg ax, r9w
|
||||
41 92 | xchg eax, r10d
|
||||
49 93 | xchg rax, r11
|
||||
66 41 94 | xchg ax, r12w
|
||||
41 95 | xchg eax, r13d
|
||||
49 96 | xchg rax, r14
|
||||
66 41 97 | xchg ax, r15w
|
||||
66 41 90 | xchg r8w, ax
|
||||
49 90 | xchg r8, rax
|
||||
41 90 | xchg r8d, eax
|
||||
91 | xchg ecx, eax
|
||||
66 41 97 | xchg r15w, ax
|
||||
@@ -0,0 +1,376 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! XADD, CMPXCHG and the LOCK prefix (issue #198).
|
||||
//!
|
||||
//! Expected values follow the operation sections of the Intel SDM Vol. 2 for
|
||||
//! XADD, CMPXCHG and LOCK, stated here as literal results. Encodings were
|
||||
//! assembled with `clang -target x86_64-apple-macos` and read with `objdump`.
|
||||
//! Nothing was compared with x86 hardware.
|
||||
//!
|
||||
//! Both engines run one guest instruction at a time on one host thread, so
|
||||
//! these tests establish the single-thread results that any later guest
|
||||
//! scheduler has to preserve. They say nothing about concurrent execution.
|
||||
|
||||
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, RFlags};
|
||||
use xenora_loader::dbt::{DbtEngine, is_native};
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
use xenora_loader::x86_decode::decode;
|
||||
|
||||
const ENTRY: u64 = 0x1000;
|
||||
/// Two writable pages. Nothing is mapped after them unless a test says so.
|
||||
const DATA: u64 = 0x4000;
|
||||
const PAGE: u64 = 0x1000;
|
||||
const END: u64 = DATA + 2 * PAGE;
|
||||
|
||||
const RAX: usize = 0;
|
||||
const RCX: usize = 1;
|
||||
const RDX: usize = 2;
|
||||
const RBX: usize = 3;
|
||||
const RSI: usize = 6;
|
||||
|
||||
fn image(code: &[u8]) -> GuestMemory {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, code)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region(DATA, 2 * PAGE as usize, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
memory
|
||||
}
|
||||
|
||||
fn data(memory: &GuestMemory) -> Vec<u8> {
|
||||
let mut out = vec![0; 2 * PAGE as usize];
|
||||
memory.read_bytes(DATA, &mut out).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
struct Run {
|
||||
name: &'static str,
|
||||
cpu: CpuState,
|
||||
exit: ExitReason,
|
||||
memory: GuestMemory,
|
||||
/// Instructions the DBT ran on the shared semantics.
|
||||
helpers: usize,
|
||||
}
|
||||
|
||||
/// The interpreter and the DBT, each from its own copy of `cpu` and `memory`.
|
||||
fn both(cpu: &CpuState, memory: &GuestMemory, budget: usize) -> [Run; 2] {
|
||||
let mut interpreted = memory.clone();
|
||||
let result = Interpreter::new(cpu.clone(), &mut interpreted, budget).run();
|
||||
let mut translated = memory.clone();
|
||||
let mut engine = DbtEngine::new(64 * 1024).unwrap();
|
||||
let mut state = cpu.clone();
|
||||
let native = engine.run(&mut state, &mut translated, budget);
|
||||
[
|
||||
Run {
|
||||
name: "interpreter",
|
||||
cpu: result.final_state,
|
||||
exit: result.exit_reason,
|
||||
memory: interpreted,
|
||||
helpers: 0,
|
||||
},
|
||||
Run {
|
||||
name: "DBT",
|
||||
cpu: native.final_state,
|
||||
exit: native.exit_reason,
|
||||
memory: translated,
|
||||
helpers: engine.metrics.interpreter_fallbacks,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn flags(cf: bool, zf: bool, sf: bool, of: bool, pf: bool, af: bool) -> RFlags {
|
||||
RFlags {
|
||||
cf,
|
||||
zf,
|
||||
sf,
|
||||
of,
|
||||
pf,
|
||||
af,
|
||||
}
|
||||
}
|
||||
|
||||
fn low(bits: u32) -> u64 {
|
||||
u64::MAX >> (64 - bits)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lock_is_accepted_only_on_xadd_and_cmpxchg_with_a_memory_destination() {
|
||||
let accepted: &[&[u8]] = &[
|
||||
&[0xF0, 0x0F, 0xC1, 0x0E], // lock xadd [rsi], ecx
|
||||
&[0xF0, 0x0F, 0xB1, 0x0E], // lock cmpxchg [rsi], ecx
|
||||
&[0x66, 0xF0, 0x0F, 0xC1, 0x0E], // lock xadd [rsi], cx, in LLVM's prefix order
|
||||
&[0xF0, 0x66, 0x0F, 0xC1, 0x0E], // the same with LOCK first
|
||||
&[0x65, 0xF0, 0x0F, 0xB0, 0x0E], // lock cmpxchg gs:[rsi], cl
|
||||
&[0xF0, 0x48, 0x0F, 0xC1, 0x0E], // lock xadd [rsi], rcx
|
||||
];
|
||||
for code in accepted {
|
||||
let lock = code.iter().position(|byte| *byte == 0xF0).unwrap();
|
||||
let mut unlocked = code.to_vec();
|
||||
unlocked.remove(lock);
|
||||
let insn = decode(ENTRY, |at| {
|
||||
code.get((at - ENTRY) as usize).copied().ok_or(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(insn.lock && !is_native(&insn), "{code:02X?}");
|
||||
assert_eq!(usize::from(insn.len), code.len(), "{code:02X?}");
|
||||
|
||||
// The accumulator matches the operand, so each exchange stores RCX.
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RAX] = 0x2122_2324_2526_2728;
|
||||
cpu.gpr[RCX] = 0x1112_1314_1516_1718;
|
||||
cpu.gpr[RSI] = DATA + 0x40;
|
||||
let mut memory = image(code);
|
||||
memory
|
||||
.write_u64(DATA + 0x40, 0x2122_2324_2526_2728)
|
||||
.unwrap();
|
||||
let mut plain = image(&unlocked);
|
||||
plain.write_u64(DATA + 0x40, 0x2122_2324_2526_2728).unwrap();
|
||||
|
||||
// LOCK changes no result here: only the instruction is a byte longer.
|
||||
for (locked, wanted) in both(&cpu, &memory, 1).iter().zip(both(&cpu, &plain, 1)) {
|
||||
assert_eq!(locked.exit, ExitReason::StepLimitExceeded, "{code:02X?}");
|
||||
assert_eq!(locked.cpu.rip, ENTRY + code.len() as u64, "{code:02X?}");
|
||||
let mut shifted = wanted.cpu.clone();
|
||||
shifted.rip += 1;
|
||||
assert_eq!(locked.cpu, shifted, "{code:02X?} on the {}", locked.name);
|
||||
assert_eq!(data(&locked.memory), data(&wanted.memory), "{code:02X?}");
|
||||
assert_ne!(data(&locked.memory), data(&memory), "{code:02X?}");
|
||||
}
|
||||
}
|
||||
|
||||
let rejected: &[&[u8]] = &[
|
||||
&[0xF0, 0x0F, 0xC1, 0xC8], // lock xadd eax, ecx: register destination
|
||||
&[0xF0, 0x0F, 0xB1, 0xCB], // lock cmpxchg ebx, ecx: register destination
|
||||
&[0xF0, 0x01, 0x0E], // lock add [rsi], ecx: outside the locked subset
|
||||
&[0xF0, 0x87, 0x0E], // lock xchg [rsi], ecx: outside the locked subset
|
||||
&[0xF0, 0x0F, 0xC7, 0x0E], // lock cmpxchg8b [rsi]: not implemented
|
||||
&[0xF0, 0x8B, 0x06], // lock mov eax, [rsi]: never lockable
|
||||
&[0xF0, 0x90], // lock nop
|
||||
];
|
||||
for code in rejected {
|
||||
let mut padded = code.to_vec();
|
||||
padded.extend([0x90; 8]);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RSI] = DATA;
|
||||
let memory = image(&padded);
|
||||
for run in both(&cpu, &memory, 1) {
|
||||
assert!(
|
||||
matches!(run.exit, ExitReason::IllegalInstruction(_)),
|
||||
"{code:02X?} on the {}: {:?}",
|
||||
run.name,
|
||||
run.exit
|
||||
);
|
||||
assert_eq!(run.cpu, cpu, "{code:02X?}");
|
||||
assert_eq!(data(&run.memory), data(&memory), "{code:02X?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_and_exchange_takes_each_branch_at_every_width() {
|
||||
// Destination [rsi] or RBX, source RCX, accumulator RAX.
|
||||
let forms: &[(&[u8], u32, bool)] = &[
|
||||
(&[0xF0, 0x0F, 0xB0, 0x0E], 8, true), // lock cmpxchg [rsi], cl
|
||||
(&[0x66, 0xF0, 0x0F, 0xB1, 0x0E], 16, true), // lock cmpxchg [rsi], cx
|
||||
(&[0xF0, 0x0F, 0xB1, 0x0E], 32, true), // lock cmpxchg [rsi], ecx
|
||||
(&[0xF0, 0x48, 0x0F, 0xB1, 0x0E], 64, true), // lock cmpxchg [rsi], rcx
|
||||
(&[0x0F, 0xB0, 0xCB], 8, false), // cmpxchg bl, cl
|
||||
(&[0x66, 0x0F, 0xB1, 0xCB], 16, false), // cmpxchg bx, cx
|
||||
(&[0x0F, 0xB1, 0xCB], 32, false), // cmpxchg ebx, ecx
|
||||
(&[0x48, 0x0F, 0xB1, 0xCB], 64, false), // cmpxchg rbx, rcx
|
||||
];
|
||||
const ACCUMULATOR: u64 = 0x1111_2222_3333_4444;
|
||||
const SOURCE: u64 = 0xAAAA_BBBB_CCCC_DDDD;
|
||||
const ABOVE: u64 = 0x5555_6666_7777_8888;
|
||||
for &(code, bits, in_memory) in forms {
|
||||
let mask = low(bits);
|
||||
for matches in [true, false] {
|
||||
// The destination holds the accumulator's low bits, or differs in
|
||||
// bit 0, under bits the operation must not read.
|
||||
let old = (ABOVE & !mask) | ((ACCUMULATOR ^ u64::from(!matches)) & mask);
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RAX] = ACCUMULATOR;
|
||||
cpu.gpr[RCX] = SOURCE;
|
||||
cpu.gpr[RBX] = old;
|
||||
cpu.gpr[RSI] = DATA + 0x80;
|
||||
// accumulator - destination is 0, or -1 when the destination is
|
||||
// one more. Start from the opposite flags so each must be written.
|
||||
let after = if matches {
|
||||
flags(false, true, false, false, true, false)
|
||||
} else {
|
||||
flags(true, false, true, false, true, true)
|
||||
};
|
||||
cpu.flags = flags(
|
||||
!after.cf, !after.zf, !after.sf, !after.of, !after.pf, !after.af,
|
||||
);
|
||||
let mut memory = image(code);
|
||||
memory.write_u64(DATA + 0x80, old).unwrap();
|
||||
|
||||
// A match stores the source. A mismatch stores the old value back
|
||||
// and loads it into the accumulator. An 8- or 16-bit register write
|
||||
// keeps the bits above it, a 32-bit one clears them, and a memory
|
||||
// write touches only its own bytes.
|
||||
let stored = if matches { SOURCE & mask } else { old & mask };
|
||||
let merged = |before: u64, value: u64| match bits {
|
||||
32 => value,
|
||||
_ => (before & !mask) | value,
|
||||
};
|
||||
let mut wanted = cpu.clone();
|
||||
wanted.rip = ENTRY + code.len() as u64;
|
||||
wanted.flags = after;
|
||||
if !matches {
|
||||
wanted.gpr[RAX] = merged(ACCUMULATOR, old & mask);
|
||||
}
|
||||
let wanted_memory = if in_memory {
|
||||
(old & !mask) | stored
|
||||
} else {
|
||||
wanted.gpr[RBX] = merged(old, stored);
|
||||
old
|
||||
};
|
||||
|
||||
for run in both(&cpu, &memory, 1) {
|
||||
let what = format!("{code:02X?} matches={matches} on the {}", run.name);
|
||||
assert_eq!(run.exit, ExitReason::StepLimitExceeded, "{what}");
|
||||
assert_eq!(run.cpu, wanted, "{what}");
|
||||
assert_eq!(
|
||||
run.memory.read_u64(DATA + 0x80).unwrap(),
|
||||
wanted_memory,
|
||||
"{what}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn locked_operands_may_be_unaligned_and_span_two_regions() {
|
||||
// No alignment is required of a locked operand (SDM Vol. 2, "LOCK"). The
|
||||
// last address straddles the data and a second writable region after it.
|
||||
let spanning = |code: &[u8]| {
|
||||
let mut memory = image(code);
|
||||
memory
|
||||
.map_region(END, PAGE as usize, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
memory
|
||||
};
|
||||
for at in [DATA + 1, DATA + 0x33, DATA + PAGE - 3, END - 8, END - 3] {
|
||||
// lock xadd [rsi], rcx
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RCX] = 0x0000_0001_0000_0003;
|
||||
cpu.gpr[RSI] = at;
|
||||
let mut memory = spanning(&[0xF0, 0x48, 0x0F, 0xC1, 0x0E]);
|
||||
memory.write_u64(at, 0xFFFF_FFFF_FFFF_FFFE).unwrap();
|
||||
for run in both(&cpu, &memory, 1) {
|
||||
assert_eq!(run.exit, ExitReason::StepLimitExceeded, "{at:#x}");
|
||||
assert_eq!(run.cpu.gpr[RCX], 0xFFFF_FFFF_FFFF_FFFE, "{at:#x}");
|
||||
assert_eq!(
|
||||
run.memory.read_u64(at).unwrap(),
|
||||
0x0000_0001_0000_0001,
|
||||
"{at:#x}"
|
||||
);
|
||||
// 0xFFFF_FFFF_FFFF_FFFE + 0x0000_0001_0000_0003 carries out of bit
|
||||
// 63 and bit 3; the sum is positive, nonzero and ends in 0x01.
|
||||
assert_eq!(
|
||||
run.cpu.flags,
|
||||
flags(true, false, false, false, false, true),
|
||||
"{at:#x}"
|
||||
);
|
||||
}
|
||||
|
||||
// lock cmpxchg [rsi], rcx, with a matching accumulator
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RAX] = 0x8877_6655_4433_2211;
|
||||
cpu.gpr[RCX] = 0x0102_0304_0506_0708;
|
||||
cpu.gpr[RSI] = at;
|
||||
let mut memory = spanning(&[0xF0, 0x48, 0x0F, 0xB1, 0x0E]);
|
||||
memory.write_u64(at, 0x8877_6655_4433_2211).unwrap();
|
||||
for run in both(&cpu, &memory, 1) {
|
||||
assert_eq!(run.exit, ExitReason::StepLimitExceeded, "{at:#x}");
|
||||
assert_eq!(run.cpu.gpr[RAX], 0x8877_6655_4433_2211, "{at:#x}");
|
||||
assert_eq!(
|
||||
run.memory.read_u64(at).unwrap(),
|
||||
0x0102_0304_0506_0708,
|
||||
"{at:#x}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fault_on_any_byte_of_the_operand_changes_nothing() {
|
||||
let xadd: &[u8] = &[0xF0, 0x48, 0x0F, 0xC1, 0x0E]; // lock xadd [rsi], rcx
|
||||
let cmpxchg: &[u8] = &[0xF0, 0x48, 0x0F, 0xB1, 0x0E]; // lock cmpxchg [rsi], rcx
|
||||
// The last three bytes of writable memory, then five bytes that are
|
||||
// unmapped or read-only.
|
||||
let at = END - 3;
|
||||
for code in [xadd, cmpxchg] {
|
||||
for read_only_tail in [false, true] {
|
||||
// Accumulators that match and that do not match the operand's
|
||||
// writable bytes: a failed compare needs the write access too.
|
||||
for accumulator in [0x0000_0000_00CC_BBAA_u64, 7] {
|
||||
let mut memory = image(code);
|
||||
memory.write_bytes(at, &[0xAA, 0xBB, 0xCC]).unwrap();
|
||||
if read_only_tail {
|
||||
memory
|
||||
.map_region(END, PAGE as usize, MemoryPermissions::READ_ONLY)
|
||||
.unwrap();
|
||||
}
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[RAX] = accumulator;
|
||||
cpu.gpr[RCX] = 0x1122_3344_5566_7788;
|
||||
cpu.gpr[RSI] = at;
|
||||
cpu.flags = flags(true, false, true, false, true, false);
|
||||
for run in both(&cpu, &memory, 1) {
|
||||
let what = format!(
|
||||
"{code:02X?} tail read-only={read_only_tail} rax={accumulator:#x} on the {}",
|
||||
run.name
|
||||
);
|
||||
assert!(
|
||||
matches!(run.exit, ExitReason::MemoryFault(_)),
|
||||
"{what}: {:?}",
|
||||
run.exit
|
||||
);
|
||||
assert_eq!(run.cpu, cpu, "{what}");
|
||||
assert_eq!(data(&run.memory), data(&memory), "{what}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compare_and_swap_loop_retries_then_fetch_and_add_follows() {
|
||||
// retry: lea rcx, [rax + 1]
|
||||
// lock cmpxchg [rsi], rcx
|
||||
// jne retry
|
||||
// mov edx, 5
|
||||
// lock xadd [rsi], rdx
|
||||
// hlt
|
||||
let code = [
|
||||
0x48, 0x8D, 0x48, 0x01, 0xF0, 0x48, 0x0F, 0xB1, 0x0E, 0x75, 0xF5, 0xBA, 0x05, 0x00, 0x00,
|
||||
0x00, 0xF0, 0x48, 0x0F, 0xC1, 0x16, 0xF4,
|
||||
];
|
||||
const COUNTER: u64 = DATA + 0x100;
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
// A stale expectation: the first exchange fails and reloads RAX, the
|
||||
// second succeeds.
|
||||
cpu.gpr[RAX] = 0xDEAD;
|
||||
cpu.gpr[RSI] = COUNTER;
|
||||
let mut memory = image(&code);
|
||||
memory.write_u64(COUNTER, 41).unwrap();
|
||||
for run in both(&cpu, &memory, 64) {
|
||||
assert_eq!(run.exit, ExitReason::Halt, "{}", run.name);
|
||||
assert_eq!(run.cpu.gpr[RAX], 41, "{}", run.name);
|
||||
assert_eq!(run.cpu.gpr[RCX], 42, "{}", run.name);
|
||||
// XADD returns the value before its addition.
|
||||
assert_eq!(run.cpu.gpr[RDX], 42, "{}", run.name);
|
||||
assert_eq!(run.memory.read_u64(COUNTER).unwrap(), 47, "{}", run.name);
|
||||
assert_eq!(run.cpu.rip, ENTRY + code.len() as u64, "{}", run.name);
|
||||
// Two exchanges and one addition, none lowered to ARM64 yet.
|
||||
if run.name == "DBT" {
|
||||
assert_eq!(run.helpers, 3);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Multiword ADC and SBB carry chains through the interpreter and the native
|
||||
//! DBT.
|
||||
//!
|
||||
//! Encodings were assembled with LLVM (`llvm-mc -triple=x86_64`, Intel syntax).
|
||||
//! Expected values come from widening `u128` and `i128` arithmetic over the
|
||||
//! limbs, following the ADC and SBB operation sections of the Intel SDM Vol. 2:
|
||||
//! DEST = DEST + SRC + CF and DEST = DEST - (SRC + CF). They never read the
|
||||
//! production semantics. Both engines must also agree on the complete state,
|
||||
//! including PF and AF, which the reference does not model.
|
||||
|
||||
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter};
|
||||
use xenora_loader::dbt::{DbtEngine, is_native};
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
use xenora_loader::x86_decode::decode;
|
||||
use xenora_loader::x86_table::Op;
|
||||
|
||||
const ENTRY: u64 = 0x1000;
|
||||
/// `jmp +0`: ends the translated block, so the next instruction reads CF from
|
||||
/// the guest state stored by the previous block.
|
||||
const JMP: [u8; 2] = [0xEB, 0x00];
|
||||
const HLT: u8 = 0xF4;
|
||||
|
||||
/// Limb registers: A in RAX, RBX, RCX, RDX and B in R8 to R11.
|
||||
const A: [usize; 4] = [0, 3, 1, 2];
|
||||
const B: [usize; 4] = [8, 9, 10, 11];
|
||||
|
||||
// add rax, r8; adc rbx, r9; adc rcx, r10; adc rdx, r11 (and the SUB/SBB and
|
||||
// 32-bit equivalents).
|
||||
const ADD64: [&[u8]; 4] = [
|
||||
&[0x4C, 0x01, 0xC0],
|
||||
&[0x4C, 0x11, 0xCB],
|
||||
&[0x4C, 0x11, 0xD1],
|
||||
&[0x4C, 0x11, 0xDA],
|
||||
];
|
||||
const SUB64: [&[u8]; 4] = [
|
||||
&[0x4C, 0x29, 0xC0],
|
||||
&[0x4C, 0x19, 0xCB],
|
||||
&[0x4C, 0x19, 0xD1],
|
||||
&[0x4C, 0x19, 0xDA],
|
||||
];
|
||||
const ADD32: [&[u8]; 4] = [
|
||||
&[0x44, 0x01, 0xC0],
|
||||
&[0x44, 0x11, 0xCB],
|
||||
&[0x44, 0x11, 0xD1],
|
||||
&[0x44, 0x11, 0xDA],
|
||||
];
|
||||
const SUB32: [&[u8]; 4] = [
|
||||
&[0x44, 0x29, 0xC0],
|
||||
&[0x44, 0x19, 0xCB],
|
||||
&[0x44, 0x19, 0xD1],
|
||||
&[0x44, 0x19, 0xDA],
|
||||
];
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
enum Chain {
|
||||
Add,
|
||||
Sub,
|
||||
}
|
||||
|
||||
/// Expected limbs and CF, ZF, SF, OF of the last limb.
|
||||
#[derive(PartialEq, Eq, Debug)]
|
||||
struct Expected {
|
||||
limbs: [u64; 4],
|
||||
cf: bool,
|
||||
zf: bool,
|
||||
sf: bool,
|
||||
of: bool,
|
||||
}
|
||||
|
||||
fn reference(chain: Chain, bits: u32, a: [u64; 4], b: [u64; 4]) -> Expected {
|
||||
let mask = if bits == 64 {
|
||||
u64::MAX
|
||||
} else {
|
||||
(1u64 << bits) - 1
|
||||
};
|
||||
let modulus = 1u128 << bits;
|
||||
let signed = |value: u64| -> i128 {
|
||||
let value = i128::from(value & mask);
|
||||
if value >= (1i128 << (bits - 1)) {
|
||||
value - (1i128 << bits)
|
||||
} else {
|
||||
value
|
||||
}
|
||||
};
|
||||
let mut limbs = [0; 4];
|
||||
let mut carry = 0u128;
|
||||
let mut of = false;
|
||||
for i in 0..4 {
|
||||
let (x, y) = (u128::from(a[i] & mask), u128::from(b[i] & mask));
|
||||
let wide = match chain {
|
||||
Chain::Add => x + y + carry,
|
||||
Chain::Sub => x + modulus - y - carry,
|
||||
};
|
||||
limbs[i] = (wide % modulus) as u64;
|
||||
let exact = match chain {
|
||||
Chain::Add => signed(a[i]) + signed(b[i]) + carry as i128,
|
||||
Chain::Sub => signed(a[i]) - signed(b[i]) - carry as i128,
|
||||
};
|
||||
of = exact != signed(limbs[i]);
|
||||
carry = match chain {
|
||||
Chain::Add => u128::from(wide >= modulus),
|
||||
Chain::Sub => u128::from(y + carry > x),
|
||||
};
|
||||
}
|
||||
Expected {
|
||||
limbs,
|
||||
cf: carry != 0,
|
||||
zf: limbs[3] == 0,
|
||||
sf: limbs[3] >> (bits - 1) & 1 != 0,
|
||||
of,
|
||||
}
|
||||
}
|
||||
|
||||
fn program(parts: &[&[u8]], split: bool) -> Vec<u8> {
|
||||
let mut code = Vec::new();
|
||||
for (i, part) in parts.iter().enumerate() {
|
||||
if split && i > 0 {
|
||||
code.extend_from_slice(&JMP);
|
||||
}
|
||||
code.extend_from_slice(part);
|
||||
}
|
||||
code.push(HLT);
|
||||
code
|
||||
}
|
||||
|
||||
fn load(code: &[u8], gpr: [u64; 16], cf: bool) -> (CpuState, GuestMemory) {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, code)
|
||||
.unwrap();
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr = gpr;
|
||||
cpu.flags.cf = cf;
|
||||
(cpu, memory)
|
||||
}
|
||||
|
||||
/// Run `code` to its HLT in both engines, check they agree on the whole state
|
||||
/// and that the DBT never left native code, and return the final state.
|
||||
fn run_both(code: &[u8], gpr: [u64; 16], cf: bool, context: &str) -> CpuState {
|
||||
let (cpu, mut memory) = load(code, gpr, cf);
|
||||
let interpreted = Interpreter::new(cpu, &mut memory, 64).run();
|
||||
let (mut cpu, mut memory) = load(code, gpr, cf);
|
||||
let mut engine = DbtEngine::new(16 * 1024).unwrap();
|
||||
let translated = engine.run(&mut cpu, &mut memory, 64);
|
||||
assert_eq!(interpreted.exit_reason, ExitReason::Halt, "{context}");
|
||||
assert_eq!(translated.exit_reason, ExitReason::Halt, "{context}");
|
||||
assert_eq!(translated.final_state, interpreted.final_state, "{context}");
|
||||
assert_eq!(engine.metrics.interpreter_fallbacks, 0, "{context}");
|
||||
interpreted.final_state
|
||||
}
|
||||
|
||||
struct Random(u64);
|
||||
|
||||
impl Random {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 >> 12;
|
||||
self.0 ^= self.0 << 25;
|
||||
self.0 ^= self.0 >> 27;
|
||||
self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
|
||||
}
|
||||
}
|
||||
|
||||
/// Limb values at the carry and overflow boundaries of a `bits`-wide limb.
|
||||
fn edges(bits: u32) -> [u64; 6] {
|
||||
let max = if bits == 64 {
|
||||
u64::MAX
|
||||
} else {
|
||||
(1u64 << bits) - 1
|
||||
};
|
||||
let sign = 1u64 << (bits - 1);
|
||||
[0, 1, max - 1, max, sign, sign - 1]
|
||||
}
|
||||
|
||||
fn operand_sets(bits: u32) -> Vec<([u64; 4], [u64; 4])> {
|
||||
let edges = edges(bits);
|
||||
let mut sets = Vec::new();
|
||||
for &x in &edges {
|
||||
for &y in &edges {
|
||||
sets.push(([x; 4], [y; 4]));
|
||||
sets.push(([x, y, x, y], [y, x, y, x]));
|
||||
}
|
||||
}
|
||||
let mut random = Random(0x0195_ADC5_BB00_0001);
|
||||
for _ in 0..256 {
|
||||
let mut pick = || {
|
||||
let raw = random.next();
|
||||
if raw & 3 == 0 {
|
||||
edges[(raw >> 8) as usize % edges.len()] | raw & !edges[3]
|
||||
} else {
|
||||
raw
|
||||
}
|
||||
};
|
||||
let a = [pick(), pick(), pick(), pick()];
|
||||
let b = [pick(), pick(), pick(), pick()];
|
||||
sets.push((a, b));
|
||||
}
|
||||
sets
|
||||
}
|
||||
|
||||
fn check_chain(chain: Chain, bits: u32, parts: [&[u8]; 4]) {
|
||||
for part in &parts[1..] {
|
||||
let insn = decode(ENTRY, |address| {
|
||||
part.get((address - ENTRY) as usize).copied().ok_or(())
|
||||
})
|
||||
.unwrap();
|
||||
assert!(matches!(insn.op, Op::Adc | Op::Sbb));
|
||||
assert!(is_native(&insn), "{:?}", insn.op);
|
||||
}
|
||||
let mut random = Random(u64::from(bits) << 8 | chain as u64);
|
||||
for (a, b) in operand_sets(bits) {
|
||||
let expected = reference(chain, bits, a, b);
|
||||
for split in [false, true] {
|
||||
let code = program(&parts, split);
|
||||
let mut gpr: [u64; 16] = std::array::from_fn(|_| random.next());
|
||||
for i in 0..4 {
|
||||
gpr[A[i]] = a[i];
|
||||
gpr[B[i]] = b[i];
|
||||
}
|
||||
// The leading ADD or SUB must ignore the incoming carry.
|
||||
for cf in [false, true] {
|
||||
let context = format!("{chain:?}{bits} split={split} cf={cf} a={a:x?} b={b:x?}");
|
||||
let state = run_both(&code, gpr, cf, &context);
|
||||
let limbs = A.map(|index| state.gpr[index]);
|
||||
// A 32-bit destination clears bits 63:32.
|
||||
assert_eq!(limbs, expected.limbs, "{context}");
|
||||
assert_eq!(B.map(|index| state.gpr[index]), b, "{context}");
|
||||
let flags = (
|
||||
state.flags.cf,
|
||||
state.flags.zf,
|
||||
state.flags.sf,
|
||||
state.flags.of,
|
||||
);
|
||||
let wanted = (expected.cf, expected.zf, expected.sf, expected.of);
|
||||
assert_eq!(flags, wanted, "{context}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_matches_native_wide_arithmetic() {
|
||||
// 128-bit sanity checks of the reference itself on the low two limbs.
|
||||
let cases = [
|
||||
(u128::MAX, 1u128),
|
||||
(0, 1),
|
||||
(1u128 << 64, 1),
|
||||
(0x8000_0000_0000_0000_0000_0000_0000_0000, 1),
|
||||
];
|
||||
for (x, y) in cases {
|
||||
let a = [x as u64, (x >> 64) as u64, 0, 0];
|
||||
let b = [y as u64, (y >> 64) as u64, 0, 0];
|
||||
let sum = reference(Chain::Add, 64, a, b);
|
||||
let expected = x.wrapping_add(y);
|
||||
assert_eq!(sum.limbs[0], expected as u64);
|
||||
assert_eq!(sum.limbs[1], (expected >> 64) as u64);
|
||||
let difference = reference(Chain::Sub, 64, a, b);
|
||||
let expected = x.wrapping_sub(y);
|
||||
assert_eq!(difference.limbs[0], expected as u64);
|
||||
assert_eq!(difference.limbs[1], (expected >> 64) as u64);
|
||||
// The upper limbs are zero, so the 256-bit borrow is the 128-bit one.
|
||||
assert_eq!(difference.cf, y > x);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_adc_chains_of_64_bit_limbs_carry_across_blocks() {
|
||||
check_chain(Chain::Add, 64, ADD64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sub_sbb_chains_of_64_bit_limbs_borrow_across_blocks() {
|
||||
check_chain(Chain::Sub, 64, SUB64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_adc_chains_of_32_bit_limbs_carry_across_blocks() {
|
||||
check_chain(Chain::Add, 32, ADD32);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sub_sbb_chains_of_32_bit_limbs_borrow_across_blocks() {
|
||||
check_chain(Chain::Sub, 32, SUB32);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_chains_run_one_block_per_limb() {
|
||||
let code = program(&ADD64, true);
|
||||
let (mut cpu, mut memory) = load(&code, [0; 16], false);
|
||||
let mut engine = DbtEngine::new(16 * 1024).unwrap();
|
||||
let result = engine.run(&mut cpu, &mut memory, 64);
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
assert_eq!(engine.metrics.blocks_compiled, 4);
|
||||
assert_eq!(engine.metrics.interpreter_fallbacks, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn immediate_forms_increment_and_decrement_a_128_bit_value() {
|
||||
// add rax, 1; adc rbx, 0 and sub rax, 1; sbb rbx, 0.
|
||||
let increment: [&[u8]; 2] = [&[0x48, 0x83, 0xC0, 0x01], &[0x48, 0x83, 0xD3, 0x00]];
|
||||
let decrement: [&[u8]; 2] = [&[0x48, 0x83, 0xE8, 0x01], &[0x48, 0x83, 0xDB, 0x00]];
|
||||
let values = [
|
||||
0u128,
|
||||
1,
|
||||
u64::MAX as u128,
|
||||
1u128 << 64,
|
||||
u128::MAX,
|
||||
u128::MAX - 1,
|
||||
1u128 << 127,
|
||||
(1u128 << 127) - 1,
|
||||
];
|
||||
for value in values {
|
||||
for split in [false, true] {
|
||||
for (parts, expected, carry, overflow) in [
|
||||
(
|
||||
&increment,
|
||||
value.wrapping_add(1),
|
||||
value == u128::MAX,
|
||||
value == (1u128 << 127) - 1,
|
||||
),
|
||||
(
|
||||
&decrement,
|
||||
value.wrapping_sub(1),
|
||||
value == 0,
|
||||
value == 1u128 << 127,
|
||||
),
|
||||
] {
|
||||
let code = program(parts, split);
|
||||
let mut gpr = [0x5A5A_5A5A_5A5A_5A5A; 16];
|
||||
gpr[0] = value as u64;
|
||||
gpr[3] = (value >> 64) as u64;
|
||||
let context = format!("{value:#x} split={split} {:x?}", parts[0]);
|
||||
let state = run_both(&code, gpr, true, &context);
|
||||
assert_eq!(state.gpr[0], expected as u64, "{context}");
|
||||
assert_eq!(state.gpr[3], (expected >> 64) as u64, "{context}");
|
||||
assert_eq!(state.flags.cf, carry, "{context}");
|
||||
assert_eq!(state.flags.of, overflow, "{context}");
|
||||
assert_eq!(state.flags.zf, (expected >> 64) == 0, "{context}");
|
||||
assert_eq!(state.flags.sf, expected >> 127 != 0, "{context}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sbb_of_a_register_with_itself_materializes_the_carry_mask() {
|
||||
// sbb esi, esi and sbb rsi, rsi give -CF and borrow exactly when CF was
|
||||
// set; adc edi, 0 adds CF to 0x89ABCDEF without a carry out. The 32-bit
|
||||
// forms clear bits 63:32.
|
||||
// (code, destination register, value from CF, CF out from CF in)
|
||||
type Case = (&'static [u8], usize, fn(bool) -> u64, fn(bool) -> bool);
|
||||
let cases: [Case; 3] = [
|
||||
(
|
||||
&[0x19, 0xF6],
|
||||
6,
|
||||
|cf| if cf { 0xFFFF_FFFF } else { 0 },
|
||||
|cf| cf,
|
||||
),
|
||||
(
|
||||
&[0x48, 0x19, 0xF6],
|
||||
6,
|
||||
|cf| if cf { u64::MAX } else { 0 },
|
||||
|cf| cf,
|
||||
),
|
||||
(
|
||||
&[0x83, 0xD7, 0x00],
|
||||
7,
|
||||
|cf| u64::from(cf) + 0x89AB_CDEF,
|
||||
|_| false,
|
||||
),
|
||||
];
|
||||
for (code, register, value, carry) in cases {
|
||||
for cf in [false, true] {
|
||||
let mut gpr = [0x0123_4567_89AB_CDEF; 16];
|
||||
gpr[6] = 0xDEAD_BEEF_0000_0001;
|
||||
let program = [code, &[HLT]].concat();
|
||||
let context = format!("{code:x?} cf={cf}");
|
||||
let state = run_both(&program, gpr, cf, &context);
|
||||
assert_eq!(state.gpr[register], value(cf), "{context}");
|
||||
assert_eq!(state.flags.cf, carry(cf), "{context}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
@@ -305,6 +306,8 @@ enum Outcome {
|
||||
}
|
||||
|
||||
fn reference(m: &mut Machine, text: &str) -> Outcome {
|
||||
// LOCK changes no result on a machine that runs one instruction at a time.
|
||||
let text = text.strip_prefix("lock ").unwrap_or(text);
|
||||
let (name, rest) = text.split_once(' ').unwrap_or((text, ""));
|
||||
let places: Vec<Place> = if rest.is_empty() || name == "lea" || name == "nop" {
|
||||
Vec::new()
|
||||
@@ -395,7 +398,7 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
|
||||
write(m, places[0], (1u128 << bits) - 1 - a);
|
||||
Outcome::Done(none)
|
||||
}
|
||||
"shl" | "shr" | "sar" | "rol" | "ror" => {
|
||||
"shl" | "shr" | "sar" | "rol" | "ror" | "rcl" | "rcr" => {
|
||||
let count = match rest.split(", ").nth(1) {
|
||||
Some("cl") => u32::from(m.gpr[1] as u8),
|
||||
_ => read(m, places[1], 8) as u32,
|
||||
@@ -403,13 +406,22 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
|
||||
let start = read(m, places[0], bits);
|
||||
let mut value = start;
|
||||
let top = 1u128 << (bits - 1);
|
||||
let mut carry = m.flags.cf;
|
||||
for _ in 0..count {
|
||||
let carry_in = m.flags.cf;
|
||||
let mut carry = carry_in;
|
||||
// RCL and RCR rotate through CF, so `bits + 1` steps come round again.
|
||||
let steps = if matches!(name, "rcl" | "rcr") {
|
||||
count % (bits + 1)
|
||||
} else {
|
||||
count
|
||||
};
|
||||
for _ in 0..steps {
|
||||
// One step at a time, as the SDM loop does.
|
||||
let (high, low) = (bit(value, bits - 1), bit(value, 0));
|
||||
(value, carry) = match name {
|
||||
"shl" => (truncate(value * 2, bits), high),
|
||||
"rol" => (truncate(value * 2, bits) + u128::from(high), high),
|
||||
"rcl" => (truncate(value * 2, bits) + u128::from(carry), high),
|
||||
"rcr" => (value / 2 + if carry { top } else { 0 }, low),
|
||||
"shr" => (value / 2, low),
|
||||
"sar" => (value / 2 + if high { top } else { 0 }, low),
|
||||
_ => (value / 2 + if low { top } else { 0 }, low),
|
||||
@@ -422,7 +434,8 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
|
||||
let (msb, next) = (bit(value, bits - 1), bit(value, bits - 2));
|
||||
if count == 1 {
|
||||
m.flags.of = match name {
|
||||
"shl" | "rol" => msb != carry,
|
||||
"shl" | "rol" | "rcl" => msb != carry,
|
||||
"rcr" => bit(start, bits - 1) != carry_in,
|
||||
"shr" => bit(start, bits - 1),
|
||||
"sar" => false,
|
||||
_ => msb != next,
|
||||
@@ -438,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,
|
||||
@@ -625,7 +685,8 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
|
||||
..none
|
||||
})
|
||||
}
|
||||
"mov" | "movabs" => {
|
||||
// MOVNTI stores like MOV; the non-temporal hint changes no result.
|
||||
"mov" | "movabs" | "movnti" => {
|
||||
let value = read(m, places[1], bits);
|
||||
write(m, places[0], value);
|
||||
Outcome::Done(none)
|
||||
@@ -659,6 +720,28 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
|
||||
write(m, places[1], a);
|
||||
Outcome::Done(none)
|
||||
}
|
||||
"xadd" => {
|
||||
// TEMP := SRC + DEST; SRC := DEST; DEST := TEMP.
|
||||
let (a, b) = (read(m, places[0], bits), read(m, places[1], bits));
|
||||
let sum = arithmetic(m, a, b, false, false, bits);
|
||||
write(m, places[1], a);
|
||||
write(m, places[0], sum);
|
||||
Outcome::Done(none)
|
||||
}
|
||||
"cmpxchg" => {
|
||||
// The accumulator is compared with DEST as CMP would. On a match
|
||||
// DEST := SRC; otherwise accumulator := DEST and DEST := DEST.
|
||||
let accumulator = read(m, rax(bits), bits);
|
||||
let (destination, source) = (read(m, places[0], bits), read(m, places[1], bits));
|
||||
arithmetic(m, accumulator, destination, true, false, bits);
|
||||
if accumulator == destination {
|
||||
write(m, places[0], source);
|
||||
} else {
|
||||
write(m, rax(bits), destination);
|
||||
write(m, places[0], destination);
|
||||
}
|
||||
Outcome::Done(none)
|
||||
}
|
||||
"bswap" => {
|
||||
let value = read(m, places[0], bits);
|
||||
let bytes = bits / 8;
|
||||
@@ -704,7 +787,26 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
|
||||
m.flags.cf = !m.flags.cf;
|
||||
Outcome::Done(none)
|
||||
}
|
||||
"nop" | "pause" => Outcome::Done(none),
|
||||
// The fences order memory accesses and compute nothing.
|
||||
"nop" | "pause" | "lfence" | "mfence" | "sfence" => Outcome::Done(none),
|
||||
"cpuid" => {
|
||||
// Xenora's guest CPUID contract, restated: the vendor "Xenora guest"
|
||||
// and the four features whose every instruction exists, CMOV and
|
||||
// POPCNT in leaf 1, LZCNT and long mode in leaf 0x8000_0001.
|
||||
let word = |text: &[u8; 4]| u32::from_le_bytes(*text);
|
||||
let values = match m.gpr[RAX] as u32 {
|
||||
0 => [1, word(b"Xeno"), word(b"uest"), word(b"ra g")],
|
||||
1 => [0, 0, 1 << 23, 1 << 15],
|
||||
0x8000_0000 => [0x8000_0001, 0, 0, 0],
|
||||
0x8000_0001 => [0, 0, 1 << 5, 1 << 29],
|
||||
_ => [0; 4],
|
||||
};
|
||||
// EAX, EBX, ECX and EDX, each zero-extended.
|
||||
for (index, value) in [0, 3, 1, 2].into_iter().zip(values) {
|
||||
m.gpr[index] = u64::from(value);
|
||||
}
|
||||
Outcome::Done(none)
|
||||
}
|
||||
"push" => {
|
||||
m.pushed = read(m, places[0], 64) as u64;
|
||||
m.gpr[4] -= 8;
|
||||
@@ -884,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,
|
||||
@@ -935,7 +1037,9 @@ fn every_declared_form_is_executed_by_a_fixture() {
|
||||
.unwrap_or_else(|error| panic!("{line}: {error:?}"));
|
||||
seen.insert(usize::from(insn.form));
|
||||
}
|
||||
// Control flow and exits are covered by the tests below.
|
||||
// Control flow and exits are covered by the tests below. String
|
||||
// instructions and the direction flag need their own memory layout and
|
||||
// are covered form by form in `tests/cpu_rep.rs`.
|
||||
let separate = [
|
||||
Op::Ldmxcsr,
|
||||
Op::Jcc,
|
||||
@@ -944,6 +1048,10 @@ fn every_declared_form_is_executed_by_a_fixture() {
|
||||
Op::Ret,
|
||||
Op::Hlt,
|
||||
Op::Syscall,
|
||||
Op::Movs,
|
||||
Op::Stos,
|
||||
Op::Cld,
|
||||
Op::Std,
|
||||
];
|
||||
let mut missing: BTreeMap<&str, Vec<String>> = BTreeMap::new();
|
||||
for (index, form) in FORMS.iter().enumerate() {
|
||||
@@ -1166,17 +1274,21 @@ fn undeclared_and_ambiguous_encodings_are_rejected() {
|
||||
&[0xF0, 0x01, 0x0E], // lock add [rsi], ecx
|
||||
&[0xF2, 0x90], // repne nop
|
||||
&[0xF3, 0xC3], // rep ret
|
||||
&[0xF3, 0xA4], // rep movsb
|
||||
&[0xF2, 0xA4], // repne movsb
|
||||
&[0xF3, 0xA6], // repe cmpsb
|
||||
&[0x67, 0x8B, 0x06], // address-size override
|
||||
&[0x64, 0x2E, 0x8B, 0x06], // CS after FS
|
||||
&[0x66, 0x50], // push ax
|
||||
&[0x66, 0xE8, 0, 0], // call rel16
|
||||
&[0x66, 0x0F, 0xC9], // bswap cx (undefined)
|
||||
&[0x66, 0x63, 0xC1], // 16-bit movsxd
|
||||
&[0x41, 0x90], // xchg r8, rax
|
||||
&[0xF3, 0x41, 0x90], // F3 on xchg r8, rax
|
||||
&[0x8D, 0xC0], // lea with a register operand
|
||||
&[0x0F, 0xAE, 0x2E], // 0F AE /5 with a memory operand
|
||||
&[0x0F, 0xAE, 0x36], // 0F AE /6 with a memory operand
|
||||
&[0x0F, 0xC3, 0xC1], // movnti with a register destination
|
||||
&[0x66, 0x0F, 0xC3, 0x06], // 66 with movnti
|
||||
&[0x0F, 0xA3, 0x06], // bt [rsi], eax
|
||||
&[0xC0, 0xD0, 0x01], // rcl al, 1
|
||||
&[0xC6, 0xC8, 0x01], // C6 /1
|
||||
&[0xFF, 0xF8], // FF /7
|
||||
&[0xFE, 0xD0], // FE /2
|
||||
|
||||
@@ -10,6 +10,12 @@
|
||||
# decodable; a form counts as implemented only once its operation has semantics
|
||||
# and independent tests. Forms not listed here are rejected.
|
||||
#
|
||||
# enc = "string" is a string instruction: its source is [RSI], which FS or GS
|
||||
# may override, its destination is [RDI], and it accepts the REP prefix (F3).
|
||||
#
|
||||
# lock = true accepts the LOCK prefix (F0) when the ModRM operand is memory.
|
||||
# Every other use of LOCK is rejected, as the architecture's #UD.
|
||||
#
|
||||
# prefix is a mandatory prefix: "66", "f3" or "f2". SSE forms use size x (XMM)
|
||||
# and give the ModRM operand width in src: x = 16 bytes, q = 8, d = 4, w = 2.
|
||||
# A 16-byte memory operand must be aligned unless unaligned = true.
|
||||
@@ -48,14 +54,20 @@ movsx = { ref = "sdm MOVSX/MOVSXD" }
|
||||
movsxd = { ref = "sdm MOVSX/MOVSXD" }
|
||||
lea = { ref = "sdm LEA" }
|
||||
xchg = { ref = "sdm XCHG" }
|
||||
xadd = { writes = "cf zf sf of pf af", ref = "sdm XADD" }
|
||||
cmpxchg = { writes = "cf zf sf of pf af", ref = "sdm CMPXCHG" }
|
||||
bswap = { ref = "sdm BSWAP" }
|
||||
cwde = { ref = "sdm CBW/CWDE/CDQE" }
|
||||
cdq = { ref = "sdm CWD/CDQ/CQO" }
|
||||
rol = { writes = "cf of", conditional = true, ref = "sdm RCL/RCR/ROL/ROR" }
|
||||
ror = { writes = "cf of", conditional = true, ref = "sdm RCL/RCR/ROL/ROR" }
|
||||
rcl = { reads = "cf", writes = "cf of", conditional = true, ref = "sdm RCL/RCR/ROL/ROR" }
|
||||
rcr = { reads = "cf", writes = "cf of", conditional = true, ref = "sdm RCL/RCR/ROL/ROR" }
|
||||
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" }
|
||||
@@ -85,6 +97,12 @@ syscall = { terminator = true, ref = "sdm SYSCALL" }
|
||||
clc = { writes = "cf", ref = "sdm CLC" }
|
||||
stc = { writes = "cf", ref = "sdm STC" }
|
||||
cmc = { reads = "cf", writes = "cf", ref = "sdm CMC" }
|
||||
cpuid = { ref = "sdm CPUID" }
|
||||
cld = { ref = "sdm CLD" }
|
||||
std = { ref = "sdm STD" }
|
||||
# A REP form repeats by leaving RIP on itself, so these end a translated block.
|
||||
movs = { terminator = true, ref = "sdm MOVS/MOVSB/MOVSW/MOVSD/MOVSQ" }
|
||||
stos = { terminator = true, ref = "sdm STOS/STOSB/STOSW/STOSD/STOSQ" }
|
||||
|
||||
# SSE and SSE2 moves and packed integer operations. None reads or writes RFLAGS.
|
||||
movaps = { ref = "sdm MOVAPS" }
|
||||
@@ -92,6 +110,7 @@ movups = { ref = "sdm MOVUPS" }
|
||||
movdqa = { ref = "sdm MOVDQA" }
|
||||
movdqu = { ref = "sdm MOVDQU" }
|
||||
movntdq = { ref = "sdm MOVNTDQ" }
|
||||
movnti = { ref = "sdm MOVNTI" }
|
||||
movntps = { ref = "sdm MOVNTPS/MOVNTPD" }
|
||||
movss = { ref = "sdm MOVSS" }
|
||||
movsd = { ref = "sdm MOVSD (scalar double)" }
|
||||
@@ -169,6 +188,9 @@ shufpd = { ref = "sdm SHUFPD" }
|
||||
pinsrw = { ref = "sdm PINSRW" }
|
||||
pextrw = { ref = "sdm PEXTRW" }
|
||||
ldmxcsr = { ref = "sdm LDMXCSR" }
|
||||
lfence = { ref = "sdm LFENCE" }
|
||||
mfence = { ref = "sdm MFENCE" }
|
||||
sfence = { ref = "sdm SFENCE" }
|
||||
stmxcsr = { ref = "sdm STMXCSR" }
|
||||
|
||||
# Floating point. Every form can raise a SIMD floating-point exception.
|
||||
@@ -387,6 +409,51 @@ opcode = 0x87
|
||||
enc = "rm_reg"
|
||||
size = "v"
|
||||
|
||||
# The accumulator with the register in the opcode. Opcode 0x90 is NOP; with
|
||||
# REX.B the decoder reads it as 0x91 with register 0, which is then r8. A row
|
||||
# of eight would have to start at 0x90, so each opcode is its own form.
|
||||
[[form]]
|
||||
op = "xchg"
|
||||
opcode = 0x91
|
||||
enc = "op_reg"
|
||||
size = "v"
|
||||
|
||||
[[form]]
|
||||
op = "xchg"
|
||||
opcode = 0x92
|
||||
enc = "op_reg"
|
||||
size = "v"
|
||||
|
||||
[[form]]
|
||||
op = "xchg"
|
||||
opcode = 0x93
|
||||
enc = "op_reg"
|
||||
size = "v"
|
||||
|
||||
[[form]]
|
||||
op = "xchg"
|
||||
opcode = 0x94
|
||||
enc = "op_reg"
|
||||
size = "v"
|
||||
|
||||
[[form]]
|
||||
op = "xchg"
|
||||
opcode = 0x95
|
||||
enc = "op_reg"
|
||||
size = "v"
|
||||
|
||||
[[form]]
|
||||
op = "xchg"
|
||||
opcode = 0x96
|
||||
enc = "op_reg"
|
||||
size = "v"
|
||||
|
||||
[[form]]
|
||||
op = "xchg"
|
||||
opcode = 0x97
|
||||
enc = "op_reg"
|
||||
size = "v"
|
||||
|
||||
[[form]]
|
||||
op = "mov"
|
||||
opcode = 0x88
|
||||
@@ -562,6 +629,49 @@ opcode = 0x05
|
||||
enc = "none"
|
||||
size = "n"
|
||||
|
||||
[[form]]
|
||||
op = "cpuid"
|
||||
map = "0f"
|
||||
opcode = 0xA2
|
||||
enc = "none"
|
||||
size = "n"
|
||||
|
||||
[[form]]
|
||||
op = "movs"
|
||||
opcode = 0xA4
|
||||
enc = "string"
|
||||
size = "b"
|
||||
|
||||
[[form]]
|
||||
op = "movs"
|
||||
opcode = 0xA5
|
||||
enc = "string"
|
||||
size = "v"
|
||||
|
||||
[[form]]
|
||||
op = "stos"
|
||||
opcode = 0xAA
|
||||
enc = "string"
|
||||
size = "b"
|
||||
|
||||
[[form]]
|
||||
op = "stos"
|
||||
opcode = 0xAB
|
||||
enc = "string"
|
||||
size = "v"
|
||||
|
||||
[[form]]
|
||||
op = "cld"
|
||||
opcode = 0xFC
|
||||
enc = "none"
|
||||
size = "n"
|
||||
|
||||
[[form]]
|
||||
op = "std"
|
||||
opcode = 0xFD
|
||||
enc = "none"
|
||||
size = "n"
|
||||
|
||||
[[form]]
|
||||
op = "movzx"
|
||||
map = "0f"
|
||||
@@ -674,6 +784,38 @@ enc = "rm_reg"
|
||||
size = "v"
|
||||
register_only = true
|
||||
|
||||
[[form]]
|
||||
op = "cmpxchg"
|
||||
map = "0f"
|
||||
opcode = 0xB0
|
||||
enc = "rm_reg"
|
||||
size = "b"
|
||||
lock = true
|
||||
|
||||
[[form]]
|
||||
op = "cmpxchg"
|
||||
map = "0f"
|
||||
opcode = 0xB1
|
||||
enc = "rm_reg"
|
||||
size = "v"
|
||||
lock = true
|
||||
|
||||
[[form]]
|
||||
op = "xadd"
|
||||
map = "0f"
|
||||
opcode = 0xC0
|
||||
enc = "rm_reg"
|
||||
size = "b"
|
||||
lock = true
|
||||
|
||||
[[form]]
|
||||
op = "xadd"
|
||||
map = "0f"
|
||||
opcode = 0xC1
|
||||
enc = "rm_reg"
|
||||
size = "v"
|
||||
lock = true
|
||||
|
||||
# Groups whose digits select an operation: [opcode, size, immediate, encoding].
|
||||
[[group]]
|
||||
map = "0f"
|
||||
@@ -690,7 +832,39 @@ digits = { 0 = "inc", 1 = "dec" }
|
||||
|
||||
[[group]]
|
||||
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", 4 = "shl", 5 = "shr", 7 = "sar" }
|
||||
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.
|
||||
|
||||
@@ -814,6 +988,14 @@ size = "x"
|
||||
src = "x"
|
||||
memory_only = true
|
||||
|
||||
[[form]]
|
||||
op = "movnti"
|
||||
map = "0f"
|
||||
opcode = 0xC3
|
||||
enc = "rm_reg"
|
||||
size = "y"
|
||||
memory_only = true
|
||||
|
||||
[[form]]
|
||||
op = "movntps"
|
||||
map = "0f"
|
||||
@@ -1831,6 +2013,36 @@ size = "n"
|
||||
src = "d"
|
||||
memory_only = true
|
||||
|
||||
# The fences are the register forms of digits 5 to 7; the r/m field is ignored.
|
||||
# The memory forms of those digits (the XSAVE family and CLFLUSH) are not
|
||||
# declared.
|
||||
[[form]]
|
||||
op = "lfence"
|
||||
map = "0f"
|
||||
opcode = 0xAE
|
||||
digit = 5
|
||||
enc = "rm_unread"
|
||||
size = "n"
|
||||
register_only = true
|
||||
|
||||
[[form]]
|
||||
op = "mfence"
|
||||
map = "0f"
|
||||
opcode = 0xAE
|
||||
digit = 6
|
||||
enc = "rm_unread"
|
||||
size = "n"
|
||||
register_only = true
|
||||
|
||||
[[form]]
|
||||
op = "sfence"
|
||||
map = "0f"
|
||||
opcode = 0xAE
|
||||
digit = 7
|
||||
enc = "rm_unread"
|
||||
size = "n"
|
||||
register_only = true
|
||||
|
||||
# SSE and SSE2 floating-point forms. RCP and RSQRT approximations are not
|
||||
# architecturally exact and are left out.
|
||||
|
||||
|
||||
+76
-27
@@ -1,4 +1,4 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, VecDeque};
|
||||
use std::ffi::c_void;
|
||||
use std::fmt;
|
||||
use std::mem::size_of_val;
|
||||
@@ -37,6 +37,16 @@ const MAX_GROUPS: usize = 64;
|
||||
const MAX_GRID_WORDS: usize = MAX_GROUPS * MAX_THREADS_PER_GROUP;
|
||||
const MAX_SOURCE_BYTES: usize = 64 * 1024;
|
||||
const MAX_IN_FLIGHT: usize = 16;
|
||||
const MAX_CACHED_PIPELINES: usize = 16;
|
||||
|
||||
type ComputePipeline = Retained<ProtocolObject<dyn MTLComputePipelineState>>;
|
||||
|
||||
struct CachedPipeline {
|
||||
source: Box<str>,
|
||||
entry: Box<str>,
|
||||
shader_validation: bool,
|
||||
pipeline: ComputePipeline,
|
||||
}
|
||||
|
||||
const BC_READBACK: &str = r"
|
||||
#include <metal_stdlib>
|
||||
@@ -148,7 +158,9 @@ impl std::error::Error for MetalError {}
|
||||
/// measure a single submission and are not a benchmark distribution.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct RunProfile {
|
||||
/// Host library compilation time, or zero when reusing a compute pipeline.
|
||||
pub library_seconds: f64,
|
||||
/// Host pipeline creation time, or zero when reusing a compute pipeline.
|
||||
pub pipeline_seconds: f64,
|
||||
pub gpu_seconds: f64,
|
||||
/// Host wall time from the start of setup until wait observes completion.
|
||||
@@ -171,6 +183,8 @@ pub struct NativeCompute {
|
||||
device: Retained<ProtocolObject<dyn MTLDevice>>,
|
||||
queue: Retained<ProtocolObject<dyn MTLCommandQueue>>,
|
||||
submissions: Mutex<SubmissionTable>,
|
||||
// Least recently used first. In-flight submissions retain their own reference.
|
||||
compute_pipelines: Mutex<VecDeque<CachedPipeline>>,
|
||||
}
|
||||
|
||||
/// A submitted dispatch whose result can be collected by its issuing context.
|
||||
@@ -247,7 +261,7 @@ struct SubmissionEntry {
|
||||
/// Metal reports Completed or Error.
|
||||
struct InFlightResources {
|
||||
command: Retained<ProtocolObject<dyn MTLCommandBuffer>>,
|
||||
_pipeline: Retained<ProtocolObject<dyn MTLComputePipelineState>>,
|
||||
_pipeline: ComputePipeline,
|
||||
_input: Option<Retained<ProtocolObject<dyn MTLBuffer>>>,
|
||||
output: Retained<ProtocolObject<dyn MTLBuffer>>,
|
||||
_texture: Option<Retained<ProtocolObject<dyn MTLTexture>>>,
|
||||
@@ -348,6 +362,7 @@ impl NativeCompute {
|
||||
device,
|
||||
queue,
|
||||
submissions: Mutex::default(),
|
||||
compute_pipelines: Mutex::default(),
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -901,7 +916,7 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
self.run_profiled_words(source, entry, input, Some(width))
|
||||
}
|
||||
|
||||
/// Compile the kernel and report the smaller of the device and pipeline width limits.
|
||||
/// Find or compile the kernel and report the smaller of the device and pipeline width limits.
|
||||
///
|
||||
/// Input size and threadgroup count are checked separately at dispatch.
|
||||
///
|
||||
@@ -911,11 +926,7 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
pub fn max_group_width(&self, source: &str, entry: &str) -> Result<usize, MetalError> {
|
||||
validate_source(source, &[entry])?;
|
||||
autoreleasepool(|_| {
|
||||
let options = compile_options()?;
|
||||
let library = self.compile_library(source, &options)?;
|
||||
let function = find_function(&library, entry)?;
|
||||
let pipeline = self.compute_pipeline(&function)?;
|
||||
verify_shader_validation(&pipeline)?;
|
||||
let (pipeline, _, _) = self.prepare_compute_pipeline(source, entry)?;
|
||||
Ok(self.pipeline_group_width_limit(&pipeline))
|
||||
})
|
||||
}
|
||||
@@ -963,15 +974,8 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
host_start: Instant,
|
||||
) -> Result<Submission<'_>, MetalError> {
|
||||
self.submissions().check_capacity()?;
|
||||
let options = compile_options()?;
|
||||
let library_start = Instant::now();
|
||||
let library = self.compile_library(source, &options)?;
|
||||
let library_seconds = library_start.elapsed().as_secs_f64();
|
||||
let function = find_function(&library, entry)?;
|
||||
let pipeline_start = Instant::now();
|
||||
let pipeline = self.compute_pipeline(&function)?;
|
||||
let pipeline_seconds = pipeline_start.elapsed().as_secs_f64();
|
||||
verify_shader_validation(&pipeline)?;
|
||||
let (pipeline, library_seconds, pipeline_seconds) =
|
||||
self.prepare_compute_pipeline(source, entry)?;
|
||||
|
||||
let limit = self.pipeline_group_width_limit(&pipeline);
|
||||
let width = match group_width {
|
||||
@@ -1108,18 +1112,67 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
})
|
||||
}
|
||||
|
||||
fn compute_pipeline(
|
||||
fn prepare_compute_pipeline(
|
||||
&self,
|
||||
function: &ProtocolObject<dyn MTLFunction>,
|
||||
) -> Result<Retained<ProtocolObject<dyn MTLComputePipelineState>>, MetalError> {
|
||||
self.device
|
||||
.newComputePipelineStateWithFunction_error(function)
|
||||
source: &str,
|
||||
entry: &str,
|
||||
) -> Result<(ComputePipeline, f64, f64), MetalError> {
|
||||
let shader_validation = std::env::var("MTL_SHADER_VALIDATION").as_deref() == Ok("1");
|
||||
// Device identity is fixed by this context. All misses use the same
|
||||
// compile options (safe math, precise functions, default language,
|
||||
// no macros) and unspecialized functions. Any configurable options
|
||||
// must become part of the key before they are used here.
|
||||
let mut cache = self
|
||||
.compute_pipelines
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(index) = cache.iter().position(|cached| {
|
||||
cached.source.as_ref() == source
|
||||
&& cached.entry.as_ref() == entry
|
||||
&& cached.shader_validation == shader_validation
|
||||
}) {
|
||||
let cached = cache.remove(index).expect("position in the locked cache");
|
||||
let pipeline = cached.pipeline.clone();
|
||||
cache.push_back(cached);
|
||||
return Ok((pipeline, 0.0, 0.0));
|
||||
}
|
||||
|
||||
// Serialize cache misses in this context so concurrent requests for
|
||||
// one key share the same build. The submission table is unlocked here.
|
||||
let options = compile_options()?;
|
||||
let library_start = Instant::now();
|
||||
let library = self.compile_library(source, &options)?;
|
||||
let library_seconds = library_start.elapsed().as_secs_f64();
|
||||
let function = find_function(&library, entry)?;
|
||||
let pipeline_start = Instant::now();
|
||||
let pipeline = self
|
||||
.device
|
||||
.newComputePipelineStateWithFunction_error(&function)
|
||||
.map_err(|error| {
|
||||
MetalError::new(
|
||||
"newComputePipelineStateWithFunction",
|
||||
error.localizedDescription().to_string(),
|
||||
)
|
||||
})
|
||||
})?;
|
||||
let pipeline_seconds = pipeline_start.elapsed().as_secs_f64();
|
||||
if shader_validation {
|
||||
verify_shader_validation(&pipeline)?;
|
||||
}
|
||||
|
||||
// Bound owned key text to 1 MiB. A valid oversized key can run
|
||||
// uncached, so this budget does not alter source or entry validation.
|
||||
if entry.len() <= MAX_SOURCE_BYTES.saturating_sub(source.len()) {
|
||||
if cache.len() == MAX_CACHED_PIPELINES {
|
||||
cache.pop_front();
|
||||
}
|
||||
cache.push_back(CachedPipeline {
|
||||
source: source.into(),
|
||||
entry: entry.into(),
|
||||
shader_validation,
|
||||
pipeline: pipeline.clone(),
|
||||
});
|
||||
}
|
||||
Ok((pipeline, library_seconds, pipeline_seconds))
|
||||
}
|
||||
|
||||
fn pipeline_group_width_limit(
|
||||
@@ -1232,10 +1285,6 @@ fn check_command_status(
|
||||
fn verify_shader_validation(
|
||||
pipeline: &ProtocolObject<dyn MTLComputePipelineState>,
|
||||
) -> Result<(), MetalError> {
|
||||
if std::env::var("MTL_SHADER_VALIDATION").as_deref() != Ok("1") {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if !pipeline.respondsToSelector(sel!(shaderValidation)) {
|
||||
return Err(MetalError::new(
|
||||
"shaderValidation",
|
||||
|
||||
@@ -101,7 +101,43 @@ impl NativeCompute {
|
||||
colors,
|
||||
[width, height],
|
||||
clear,
|
||||
sampled,
|
||||
sampled.map(|(texture, sampler)| (texture.raw(), sampler)),
|
||||
)
|
||||
.map(|(pixels, _)| pixels)
|
||||
}
|
||||
|
||||
/// As [`Self::render_rgba8_sampled`], with level 0 of a BC1 upload bound
|
||||
/// natively as a `BC1_RGBA` texture to fragment texture slot 0 and the
|
||||
/// sampler to fragment sampler slot 0.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// As [`Self::render_rgba8_sampled`], and for an invalid BC1 level.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn render_rgba8_sampled_bc1(
|
||||
&self,
|
||||
source: &str,
|
||||
entries: [&str; 2],
|
||||
vertices: &[[f32; 4]; 3],
|
||||
colors: &[[f32; 4]; 3],
|
||||
extent: [usize; 2],
|
||||
clear: [u8; 4],
|
||||
texture: &Bc1Upload<'_>,
|
||||
sampler: &crate::sampler::MetalSampler,
|
||||
) -> Result<Vec<u8>, MetalError> {
|
||||
let level = texture
|
||||
.subresource(0, 0)
|
||||
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
|
||||
self.validate_bc_extent(level.width, level.height, "BC1")?;
|
||||
let bc1 = self.new_bc1_texture(&level)?;
|
||||
self.render_rgba8_internal(
|
||||
source,
|
||||
entries,
|
||||
vertices,
|
||||
colors,
|
||||
extent,
|
||||
clear,
|
||||
Some((&bc1, sampler)),
|
||||
)
|
||||
.map(|(pixels, _)| pixels)
|
||||
}
|
||||
@@ -116,7 +152,7 @@ impl NativeCompute {
|
||||
[width, height]: [usize; 2],
|
||||
clear: [u8; 4],
|
||||
sampled: Option<(
|
||||
&crate::texture_pipeline::MetalRgba8Texture,
|
||||
&ProtocolObject<dyn MTLTexture>,
|
||||
&crate::sampler::MetalSampler,
|
||||
)>,
|
||||
) -> Result<(Vec<u8>, Option<f64>), MetalError> {
|
||||
@@ -228,7 +264,7 @@ impl NativeCompute {
|
||||
encoder.setVertexBuffer_offset_atIndex(Some(&positions), 0, 0);
|
||||
encoder.setVertexBuffer_offset_atIndex(Some(&colors), 0, 1);
|
||||
if let Some((tex, samp)) = sampled {
|
||||
encoder.setFragmentTexture_atIndex(Some(tex.raw()), 0);
|
||||
encoder.setFragmentTexture_atIndex(Some(tex), 0);
|
||||
encoder.setFragmentSamplerState_atIndex(Some(samp.raw()), 0);
|
||||
}
|
||||
encoder.drawPrimitives_vertexStart_vertexCount(MTLPrimitiveType::Triangle, 0, 3);
|
||||
|
||||
Loaded 100 of 175 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user