mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-28 10:31:11 +00:00
Compare commits
281
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fb6282ceb2 | ||
|
|
bb6a9f6912 | ||
|
|
a7e3e1e42c | ||
|
|
9c76bf16f0 | ||
|
|
7dd1329866 | ||
|
|
4b579af70d | ||
|
|
b4f45573cf | ||
|
|
0766307acc | ||
|
|
9dfdfd1134 | ||
|
|
ce8d16e367 | ||
|
|
8df13ae976 | ||
|
|
36c4fbd520 | ||
|
|
3c8b6bad97 | ||
|
|
d4c29cd7dd | ||
|
|
938cbd3028 | ||
|
|
c9505e53e2 | ||
|
|
02eb8046a1 | ||
|
|
4a0b5d4ded | ||
|
|
00eb6971e9 | ||
|
|
c3b0025977 | ||
|
|
7c88e5d655 | ||
|
|
bb318ed2ba | ||
|
|
b1b57cf16a | ||
|
|
cdcc55c33e | ||
|
|
0730f4dbbf | ||
|
|
6f27da3ccc | ||
|
|
6236996f41 | ||
|
|
05f2526d27 | ||
|
|
e5aca73c55 | ||
|
|
281d92bfb5 | ||
|
|
5131de9cd6 | ||
|
|
fec13fa27a | ||
|
|
68503a674c | ||
|
|
82cb66e80f | ||
|
|
06dbe2946d | ||
|
|
14d5083f0f | ||
|
|
0115af5c04 | ||
|
|
5b7ffec90a | ||
|
|
48c5d20aa9 | ||
|
|
8049c36f51 | ||
|
|
94783fa603 | ||
|
|
c91036f879 | ||
|
|
c1cea65e17 | ||
|
|
974d1fc62c | ||
|
|
223a754eb7 | ||
|
|
3d19c756e2 | ||
|
|
d195978903 | ||
|
|
782c49167c | ||
|
|
6106c37912 | ||
|
|
823a5812a0 | ||
|
|
710a2e1e73 | ||
|
|
de92766b29 | ||
|
|
4d44765363 | ||
|
|
6de750b152 | ||
|
|
adf10db015 | ||
|
|
4e4a6b36be | ||
|
|
403a67747f | ||
|
|
dc3b02b62f | ||
|
|
d847d7ea6e | ||
|
|
0fdb995892 | ||
|
|
b55a4c24ef | ||
|
|
d7f7d586d3 | ||
|
|
d01627b3de | ||
|
|
291c9807ee | ||
|
|
1d363c3c34 | ||
|
|
e74ebbe30b | ||
|
|
26eba92b87 | ||
|
|
05143d6295 | ||
|
|
d6a65b2940 | ||
|
|
1cc7f01fec | ||
|
|
6a4fc7cce1 | ||
|
|
b5b24347e9 | ||
|
|
f8eb976102 | ||
|
|
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 | ||
|
|
bdcdd57c55 | ||
|
|
5b894777ce | ||
|
|
dc44c5c64b | ||
|
|
b9f6985d57 | ||
|
|
db40a1307d | ||
|
|
b174b45bed | ||
|
|
7504a5d48d | ||
|
|
2b858ab7c6 | ||
|
|
076f3e52aa | ||
|
|
e17e3bfc63 | ||
|
|
1915e2374c | ||
|
|
6545a25b7b | ||
|
|
d5514aa9d8 | ||
|
|
7623fde0e7 | ||
|
|
f2e6db03a9 | ||
|
|
3a14bd98ab | ||
|
|
d31b8ef20c | ||
|
|
81cfe69143 | ||
|
|
91fe3f345b | ||
|
|
0a722d2e60 | ||
|
|
738b518a26 | ||
|
|
0cf4e8a9e9 | ||
|
|
9f8dc3a912 | ||
|
|
d6f21217a2 | ||
|
|
9478795696 | ||
|
|
d8c117cdd3 | ||
|
|
9ef9537540 | ||
|
|
081f9c9e06 | ||
|
|
17fa47f058 | ||
|
|
3250ae8fd1 | ||
|
|
6ff79431bc | ||
|
|
c1fc4d373f | ||
|
|
1b4911ffea | ||
|
|
6c460f7c1c | ||
|
|
8d7f7fadb4 | ||
|
|
a2a6a56222 | ||
|
|
fbe1d3c4d1 | ||
|
|
8f67a9680d | ||
|
|
74af0d8eb9 | ||
|
|
4bc268c931 | ||
|
|
0b00fb378d | ||
|
|
d5437c1c18 | ||
|
|
ad4d07492d | ||
|
|
65bf3ec3fc | ||
|
|
0afae6fa45 | ||
|
|
143429ceeb | ||
|
|
1eae910ce1 | ||
|
|
c586a4a82a | ||
|
|
9e35434f63 | ||
|
|
6e64737021 | ||
|
|
8b0b62a771 | ||
|
|
d658907fd7 | ||
|
|
a2cc14d223 | ||
|
|
9500ed17e5 | ||
|
|
980436a963 | ||
|
|
d6b751976d | ||
|
|
263284ff4f | ||
|
|
02f06bbbe8 | ||
|
|
ac6f9daff3 | ||
|
|
e1e261ea82 | ||
|
|
f4c4b5f9d0 | ||
|
|
c5238a83a3 | ||
|
|
de536c033b | ||
|
|
eb85731d5d | ||
|
|
06ded40d54 | ||
|
|
22e1864b36 | ||
|
|
21da49b109 | ||
|
|
175335e1f6 | ||
|
|
b37a859cd6 | ||
|
|
81868436b8 | ||
|
|
714efd873b | ||
|
|
06d895ec23 | ||
|
|
6b55d76a14 | ||
|
|
a359956033 | ||
|
|
625e26affc | ||
|
|
b8b42c73bf | ||
|
|
01a8445412 | ||
|
|
06614f2219 | ||
|
|
e984cfc099 | ||
|
|
3ca4c8586c | ||
|
|
93d26d6e45 | ||
|
|
7f80767810 | ||
|
|
846589abce | ||
|
|
1edcbb651d | ||
|
|
efe9fdeb8d | ||
|
|
ccaa92ce3a | ||
|
|
243a2d2c58 | ||
|
|
149f9389f9 | ||
|
|
1c5c320437 | ||
|
|
7c3499d5a2 | ||
|
|
6bc88d6c51 | ||
|
|
7d3c004285 | ||
|
|
105bf8a65c | ||
|
|
9da73f8ad8 | ||
|
|
9241630f6c | ||
|
|
542684612d | ||
|
|
f9a7d99638 | ||
|
|
516976fb9f | ||
|
|
32e41e3890 | ||
|
|
bf56047db9 | ||
|
|
fa2e89cc06 | ||
|
|
2384bed8b4 | ||
|
|
b8fae106af | ||
|
|
547b10250d | ||
|
|
4b370efa12 | ||
|
|
f6c87de433 | ||
|
|
0b6ab43ad4 | ||
|
|
aa93665b97 | ||
|
|
565c144a39 | ||
|
|
ef90105a26 | ||
|
|
ed33b57c8d | ||
|
|
9e2c7b6e0b | ||
|
|
e95b0a055d | ||
|
|
88e7dad8b2 | ||
|
|
7ff88bc3f4 | ||
|
|
8909b99ece | ||
|
|
b559fb575c | ||
|
|
0109aea9ea | ||
|
|
f916998f10 | ||
|
|
ce2a753d2f | ||
|
|
342fcbd17d | ||
|
|
7a91e11742 | ||
|
|
e3cd65cb79 | ||
|
|
1ac4f82d7a | ||
|
|
544ee8de83 | ||
|
|
731f9448c3 | ||
|
|
198242e5e4 | ||
|
|
aacd160626 | ||
|
|
8343e0cdc6 | ||
|
|
2128e8e81f | ||
|
|
73764899c2 | ||
|
|
6d073a99b5 | ||
|
|
60bfaff97e | ||
|
|
51269bb714 | ||
|
|
c1e6646bf2 | ||
|
|
b29a504506 | ||
|
|
2647ba0f14 | ||
|
|
b2a36e9c16 | ||
|
|
2367414be5 | ||
|
|
1d0b0d1547 | ||
|
|
fbb487384f | ||
|
|
ac13c59b7d | ||
|
|
d12b50075b | ||
|
|
dd1d1f27e6 | ||
|
|
19465370d1 | ||
|
|
5617b883b9 | ||
|
|
3922f56d68 | ||
|
|
017b303e79 | ||
|
|
d777adecf3 | ||
|
|
a7a0235c79 | ||
|
|
c4ce9a4e38 | ||
|
|
791bfc6be9 | ||
|
|
2de0483142 | ||
|
|
6ecbd14915 | ||
|
|
3c9b8d988b | ||
|
|
ab598f0820 | ||
|
|
2bc08a1851 | ||
|
|
6a60749939 | ||
|
|
dcf7122082 | ||
|
|
06bdf189e4 | ||
|
|
9b22c664bb | ||
|
|
654e4c28b5 | ||
|
|
b861348667 | ||
|
|
a4a2425bcc | ||
|
|
edba4df430 | ||
|
|
f992721fda | ||
|
|
8e29b54919 | ||
|
|
43f54ff1d2 | ||
|
|
cd01d04a96 | ||
|
|
6b068a225d | ||
|
|
fa6a52ab93 | ||
|
|
4c1ac39c7e | ||
|
|
d76c7d061c | ||
|
|
7134523a08 | ||
|
|
e4b1898b00 | ||
|
|
7130da2635 | ||
|
|
7599de0e01 | ||
|
|
86467c2f6c | ||
|
|
58d0d5a088 |
No files matched your search
@@ -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,7 +69,7 @@ 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
|
||||
|
||||
@@ -35,6 +35,7 @@
|
||||
|
||||
__pycache__/
|
||||
*.pyc
|
||||
/diagnostics/probe/
|
||||
/diagnostics/gta6-candidate-*/
|
||||
/diagnostics/gta6-check/
|
||||
|
||||
|
||||
+106
@@ -10,9 +10,44 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
|
||||
remains unsupported.
|
||||
|
||||
### Changed
|
||||
- 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.
|
||||
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
|
||||
|
||||
### Fixed
|
||||
- Made the native semantic-review timeout in `scripts/test-gpu.sh` configurable with `XENORA_SEMANTIC_TIMEOUT` and raised its default from 120 to 300 seconds, so cold Apple Silicon runs do not fail while the expanded Metal known-answer suite is still progressing.
|
||||
|
||||
### Added
|
||||
- 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 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 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 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). 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`.
|
||||
|
||||
- Added `crates/loader/tests/cpu_known_answers.rs` (#155): 736 x86-64 cases whose results, flags, MXCSR state and faults come from the Intel SDM, with the AMD APM for some MXCSR flags, plus arithmetic, shift, packed-integer, multiply, divide and floating-point sweeps computed from the manuals' definitions. 700 cases were written before the CPU source was read; the rest and the sweeps came afterwards. The interpreter and the DBT both run them; the DBT route (ARM64 code or Rust helper) is confirmed by the fallback counter for straight-line cases and predicted for the others. 592 cases are verified, 133 use forms both engines refuse, and eleven, plus a self-modifying-code test, record open defects in five ignored tests: the reported address of a page-crossing fault, the fault class of a non-canonical address and of an instruction over 15 bytes, PE set by an exact unmasked overflow, and DBT blocks that stay cached after the guest rewrites them. Not compared with x86 hardware; awaiting independent review.
|
||||
- Added a typed runtime service registry (`crates/loader/runtime/services.txt`) and `xenora-runtime-gen`, which generates Win64 argument and result adapters, static metadata and a coverage report. It covers 20 services: 16 existing kernel32 services moved to typed handlers, and `sqrt`, `sqrtf`, `fabs` and `fabsf` with arguments and results in XMM registers. Conflicting keys, unlisted API sets, unsupported types and behaviour without an existing test are rejected. See `docs/runtime/registry.md`.
|
||||
- Added SSE and SSE2 floating point in scalar and packed, binary32 and binary64 forms: add, subtract, multiply, divide, minimum, maximum, square root, compares, COMI/UCOMI and the conversions between formats and integers (parts of #127 and #128; awaiting independent review). `crates/loader/src/softfloat.rs` computes every result exactly and rounds once, with MXCSR rounding modes, sticky flags, denormals-are-zero, flush-to-zero, tininess after rounding and x86 NaN rules; host floating point is not used because ARM64 differs. An unmasked exception exits with `SimdException` and leaves everything but MXCSR unchanged. RCP, RSQRT and MMX conversions are rejected, and no floating-point form is translated to NEON yet.
|
||||
- Added 6,824 floating-point vectors computed with exact fractions by `tests/x86/float_reference.py`, run through both engines from registers and memory and through the packed forms, and more than two million round-to-nearest results compared with the host's IEEE 754 hardware.
|
||||
@@ -27,7 +62,69 @@ remains unsupported.
|
||||
- Added advisory infrastructure QA helpers under `scripts/qa/` and `scripts/release/` (issue #277): exit-status-preserving orchestration with JSON reports, PR scope/DCO/artifact checks, benchmark percentile analysis over existing samples, environment and repository health diagnostics, ARM64 Mach-O/bundle/codesign helpers, and checksum manifests. Covered by `tests/qa/` and `tests/release/`; checks stay advisory until reviewed.
|
||||
- Recorded agent-queue live smoke evidence for issue #180 against the disposable private repository `ranveersoni98/xenora-agent-queue-smoke`, including claim grant, overlap refusal, release, not-ready denial, progress renew and a successful audit dispatch after fixing comment-only `apply_actions` and audit permissions/argparse issues.
|
||||
- Added twelve gfx1030 VOP2 vector integer forms through the semantic registry: `v_mul_i32_i24`, `v_mul_hi_i32_i24`, `v_mul_u32_u24`, `v_mul_hi_u32_u24`, `v_min_i32`, `v_max_i32`, `v_min_u32`, `v_max_u32`, `v_xnor_b32`, `v_add_nc_u32`, `v_sub_nc_u32` and `v_subrev_nc_u32` (AMD guide section 12.7), with SRC0 a VGPR, an SGPR, `vcc_lo`, an inline integer or a literal. The registry gained a `vop2_vgpr` operand rule, the vector operations `mul24` and `mul_hi24`, a declared `source_order` for SUBREV, and a per-lane `VectorBinary` that selects one reusable MSL template per operation. Both reference interpreters, written separately from the guide, run the same twelve forms and are checked against 2,040 guide-derived cases, each asserting every lane of a 7-, 32- or 45-lane dispatch (partial, empty and full EXEC), on both CPU interpreters and on native Metal; 575 rejected programs are refused by both interpreters and by the compiler at the same word. A new LLVM-assembled fixture computes every lane from its own input. Part of #215.
|
||||
- Moved the twelve Wave32 VOPC integer compares from #239 into the semantic registry (operand rule `vopc_vcc`, `vcc = "lane_mask"`, `wave = "wave32"`) with no behaviour change, and added `v_cmp_f_i32`, `v_cmp_t_i32`, `v_cmp_f_u32` and `v_cmp_t_u32` as registry forms under the same Wave32 VCC/EXEC contract, verified by an independent guide-derived oracle (`tests/validation/tests/vopc_f_t.rs`), a new LLVM-assembled fixture and native Metal (part of #215). `v_cmpx_*`, the VOP3 encoding and Wave64 stay unsupported.
|
||||
- Split the gfx1030 semantic registry into one file per encoding family (`crates/isa/semantics/rdna2/{sop2,sopc,sop1,vop2,vopc,vop3}.toml`, included in order by `rdna2.toml`; the split left the generated tables byte-identical), and added registry encoding variants: another encoding of a declared form is pure data. `v_add_nc_u32_e64` is now the first VOP3 variant of `v_add_nc_u32` (operand rule `vop3_vgpr2`), replacing its hand-written decoder and instruction with no behaviour change (part of #215).
|
||||
- Added sixteen gfx1030 SOP2 integer forms through the semantic registry: `s_min_i32`, `s_min_u32`, `s_max_i32`, `s_max_u32`, `s_cselect_b32`, `s_bfm_b32`, `s_mul_i32`, `s_bfe_u32`, `s_bfe_i32`, `s_absdiff_i32`, `s_lshl1_add_u32` to `s_lshl4_add_u32`, `s_mul_hi_u32` and `s_mul_hi_i32` (AMD guide section 12.1). Min and max set SCC from the strict compare (a tie gives S1 and SCC 0), `s_cselect_b32` reads SCC and is refused when SCC is unset, and BFM, MUL, MUL_HI and CSELECT leave SCC unchanged. The registry gained these primitives, a `selected_src0` SCC effect, the select's SCC input and a declared `shift_amount` for the shift-and-add forms; `ScalarAluOp::evaluate` now returns an optional SCC. Both reference interpreters, written separately from the guide, run the same sixteen forms and are checked against 21,070 guide-derived cases on both CPU interpreters and on native Metal; 597 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all sixteen. Part of #215.
|
||||
|
||||
- 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 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.
|
||||
|
||||
- Fixed the import generator classifying the synchronization API-set entries for `CreateSemaphoreA`, `CreateSemaphoreW` and `ReleaseSemaphore` as stubs, which overrode the runtime handlers. A CLI test now checks that every generator entry marked as a standard service resolves to a registered, non-stub loader handler.
|
||||
|
||||
- Added guest module lookup and named symbol resolution for built-in Kernel32 and UCRT services.
|
||||
|
||||
- Added same-process guest file handle duplication with a shared file position.
|
||||
|
||||
- Added guest file and directory enumeration with typed search handles.
|
||||
|
||||
- Added closed-file moves and file and directory attribute queries on the synthetic guest drive.
|
||||
|
||||
- Added nested guest directories and checked file deletion on the synthetic drive.
|
||||
|
||||
- Added file seeking and end-of-file resizing on the synthetic guest drive.
|
||||
|
||||
- Added a bounded synthetic guest drive with synchronous file open, read, write, and size queries.
|
||||
|
||||
- Added unnamed guest semaphores with checked release and immediate mixed-object waits.
|
||||
|
||||
- Added non-alertable extended event waits through both Win64 wait APIs.
|
||||
|
||||
- Added immediate wait-any and wait-all for guest event handles.
|
||||
|
||||
- Added guest CRT signed and unsigned 64-bit conversions for narrow and wide strings.
|
||||
|
||||
- Added bounded guest CRT long-integer parsing for byte and wide strings.
|
||||
|
||||
- Added guest CRT errno accessors and allocation failure reporting for the synthetic main thread.
|
||||
|
||||
- Added guest CRT allocation, zeroed array allocation, resizing, and release.
|
||||
|
||||
- Added private guest heap creation and destruction with per-heap allocation ownership.
|
||||
|
||||
- Added default guest heap reallocation with data preservation and an in-place-only option.
|
||||
|
||||
- Added the synthetic default process heap with allocation, size queries, and release.
|
||||
|
||||
- Added Win64 signatures for wide-string length and comparison and overlapping byte moves to the import catalog.
|
||||
|
||||
- Added guest CRT wide-string length and comparison using Windows 16-bit code units.
|
||||
|
||||
- Added checked guest CRT byte string comparison with `strcmp` and `strncmp`.
|
||||
|
||||
- Added bounded guest CRT byte fill, copy, move, and comparison services.
|
||||
|
||||
- Added guest CRT string length services for UCRT and its string API set.
|
||||
|
||||
- Added unnamed guest events with manual and automatic reset, signaling, immediate waits, and same-process handle duplication.
|
||||
|
||||
- Added same-process duplication of synthetic thread handles with independent closure.
|
||||
- Added a rights-checked `GetThreadId` query for handles to the synthetic guest thread.
|
||||
- Added 32-bit and 64-bit millisecond uptime queries for synthetic Windows guests.
|
||||
- Added high-resolution elapsed-time queries for synthetic Windows guests through `QueryPerformanceCounter` and `QueryPerformanceFrequency`.
|
||||
|
||||
- Added audio PCM streaming and sandboxed virtual filesystem (VFS) integration to the native application runtime (Gate 6, #284). The C interface gains audio management functions (`xenora_session_audio_init`, `xenora_session_audio_submit`, `xenora_session_audio_read`, `xenora_session_audio_status`, `xenora_session_audio_set_volume`) and virtual filesystem functions (`xenora_session_vfs_set_root`, `xenora_session_vfs_open`, `xenora_session_vfs_read`, `xenora_session_vfs_seek`, `xenora_session_vfs_close`, `xenora_session_run_audio_vfs_fixture`). The audio subsystem implements a bounded ring buffer supporting configurable sample rates, channel configurations, PCM formats (S16LE, F32LE), volume attenuation, mute, and buffer underrun tracking. The virtual filesystem operates within an explicitly configured, sandboxed directory root (`fixtures/assets`), strictly rejecting path traversal attempts (`..`, absolute paths, null bytes) and invalid or stale handles, while supporting sequential and seekable file reads (`XENORA_SEEK_SET`, `XENORA_SEEK_CUR`, `XENORA_SEEK_END`). An original PE fixture (`fixtures/pe/audio_vfs.exe`, generated by `fixtures/pe/audio_vfs.py` using only the supported ARM64 DBT instruction subset) opens `asset.bin` (generated by `fixtures/assets/generate.py`), loads a 2x2 RGBA texture and 256 PCM audio samples via VFS, initializes audio, submits the PCM audio queue, and renders the loaded texture on Metal. Verified with unit tests, four Metal acceptance tests in `crates/ffi/tests/audio_vfs.rs`, UI controls and a `--smoke-audio-vfs` CLI in `Xenora.app`.
|
||||
- Added persistent GPU resources, dynamic texture updates, and resource retirement to the native application (Gate 5, #279). The C interface gains `xenora_resource`, resource types (`XENORA_RESOURCE_TYPE_*`), `xenora_session_create_texture`, `xenora_session_update_texture`, `xenora_session_destroy_resource`, `xenora_session_resource_info`, `xenora_session_render_textured`, and `xenora_session_run_textured_fixture`. Persistent GPU resources (textures) are explicitly allocated and owned by the execution session, surviving across execution slices without re-allocation. Dynamic texture subregion updates modify GPU texture contents in-place on native Metal. Resource retirement is completion-aware: destroying a resource held by in-flight GPU execution marks it retired and safely defers destruction until in-flight work completes, while rejecting subsequent caller queries with typed error codes. An original PE fixture (`fixtures/pe/textured.exe`, generated by `fixtures/pe/textured.py` using only the supported ARM64 DBT instruction subset) creates a persistent 2x2 texture via `xenora.dll!texture_create`, renders frame 0, updates pixels via `xenora.dll!texture_update`, renders frame 1, and retires the resource via `xenora.dll!texture_destroy`. Xenora.app gains "Run textured fixture" controls and `--smoke-resources`. Six GPU acceptance tests with Metal validation verify persistent texture lifecycle across multiple frames, dynamic 1x1 and 2x1 subregion updates on native Metal, completion-aware deferred retirement, rejection of invalid/stale/double-destroyed handles, slot reuse across 200 cycles without leaking, and full guest fixture execution. Wired acceptance tests into `scripts/test-gpu.sh`.
|
||||
- Added interactive guest execution with dynamic input handling and rendering to the native application (Gate 4, #276). The C interface gains `xenora_session_start_interactive_loop`, `xenora_session_send_input`, `xenora_session_queue_input`, and `xenora_session_get_recorded_frame`, along with input masks (`XENORA_INPUT_*`) and `xenora_input_state`. The original interactive guest fixture (`fixtures/pe/interactive.exe`, generated by `fixtures/pe/interactive.py` using only the supported ARM64 DBT instruction subset) polls host input via `xenora.dll!input_poll` and steers its rendered column position (0..3) on native Metal. Xenora.app gains interactive frame-loop controls ("Interactive (300 frames)", "◀ Left", "▶ Right", "Release") and `--smoke-interactive`. Four GPU acceptance tests with Metal validation verify that input events drive guest state and pixel geometry, deterministic input replay reproduces identical frame sequences across multiple sessions, key release and focus loss cleanly hold position without stuck keys, and destroying an interactive session joins promptly. Wired the interactive tests into `scripts/test-gpu.sh`.
|
||||
@@ -104,7 +201,11 @@ remains unsupported.
|
||||
native DBT.
|
||||
|
||||
### Fixed
|
||||
- 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).
|
||||
- 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 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.
|
||||
@@ -113,6 +214,11 @@ 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.
|
||||
|
||||
- Win64 service argument decoding reports a guest memory error when a stack argument offset overflows.
|
||||
|
||||
- Fixed `xenora_isa::meta::identify` reading six VOP3 interpolation forms (`v_interp_p1_f32_e64`, `v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`, `v_interp_p1ll_f16`, `v_interp_p1lv_f16`, `v_interp_p2_f16`) as 12 bytes when SRC0 is 255. In these forms SRC0 holds attribute bit-fields, not an operand selector (AMD RDNA 2 ISA guide section 10.4.2; XML operand type `OPR_ATTR`), so SRC0 = 255 no longer adds a literal word. The six corpus probes are now 8 bytes, as LLVM 23.1.6 also decodes them. The six pinned `mismatch` rows in the LLVM corpus check are gone: one now agrees fully, and five are `operand_flagged` (same instruction and length; LLVM flags an operand).
|
||||
- Updated `test_probe_static_analysis_does_not_execute_code`: the SIB store `mov [rsp + 0x20],
|
||||
|
||||
Generated
+1
@@ -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
|
||||
@@ -8,11 +8,8 @@ Xenora is an open-source project written primarily in Rust that builds and verif
|
||||
|
||||
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).
|
||||
|
||||
### At a glance
|
||||
|
||||
- **Native graphics:** translated gfx1030 vertex and pixel stages and native passes (indexed draws, blend, depth) run on Apple Silicon GPUs — verified, see [Blend pass](#blend-pass) and [Verified Apple M5 results](#verified-apple-m5-results).
|
||||
- **Guest execution:** bounded x86-64 execution, original PE32+ loading, synthetic services and guest-driven GPU dispatch — verified milestones X1–X9.
|
||||
- **Not supported:** authentic Xbox executable loading and commercial game execution; see the [milestone table](#development-milestones).
|
||||
> [!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.
|
||||
|
||||
[](https://github.com/ranveersoni98/Xenora/actions/workflows/ci.yml)
|
||||
|
||||
@@ -58,8 +55,6 @@ The latest verified milestones include **translated gfx1030 vertex and pixel sha
|
||||
|
||||
All existing verification refers to independently authored synthetic programs and shaders. Commercial-game compatibility remains unverified.
|
||||
|
||||
See the [X9 acceptance matrix](docs/testing/x9-acceptance.md) for specific tests, results and unsupported behavior.
|
||||
|
||||
## Native graphics translation
|
||||
|
||||
Xenora's graphics pipeline translates a supported subset of AMD RDNA 2 instructions into Metal Shading Language.
|
||||
@@ -314,7 +309,7 @@ These require a Metal-capable Apple Silicon Mac.
|
||||
scripts/test-gpu.sh
|
||||
```
|
||||
|
||||
The native test suite enables Metal API and shader validation and tests the supported compute, rendering and texture paths.
|
||||
The native test suite enables Metal API and shader validation and tests the supported compute, rendering and texture paths. The full semantic-review batch defaults to a 300-second timeout; set `XENORA_SEMANTIC_TIMEOUT` to raise or lower it for a slower or faster host.
|
||||
|
||||
### Verify guest execution
|
||||
|
||||
@@ -376,4 +371,4 @@ See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for third-party attribution
|
||||
|
||||
Xenora is an independent open-source project and is not affiliated with Microsoft, Xbox, Rockstar Games or Apple.
|
||||
|
||||
---
|
||||
---
|
||||
@@ -0,0 +1,84 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import AVFoundation
|
||||
import Foundation
|
||||
|
||||
struct AudioMixMeasurement {
|
||||
let frames: Int
|
||||
let mean: Double
|
||||
let toneAmplitude: Double
|
||||
}
|
||||
|
||||
enum AudioMixFixtureError: Error {
|
||||
case bufferAllocation
|
||||
case renderFailure(AVAudioEngineManualRenderingStatus)
|
||||
case shortRender
|
||||
}
|
||||
|
||||
func measureAudioMixFixture() throws -> AudioMixMeasurement {
|
||||
let outputRate = 48_000.0
|
||||
let toneRate = 44_100.0
|
||||
let toneFrequency = 1_000.0
|
||||
let blockSize: AVAudioFrameCount = 480
|
||||
let totalFrames = 4_800
|
||||
guard let outputFormat = AVAudioFormat(standardFormatWithSampleRate: outputRate, channels: 1),
|
||||
let toneFormat = AVAudioFormat(standardFormatWithSampleRate: toneRate, channels: 1),
|
||||
let constant = AVAudioPCMBuffer(pcmFormat: outputFormat, frameCapacity: 4_800),
|
||||
let tone = AVAudioPCMBuffer(pcmFormat: toneFormat, frameCapacity: 4_410),
|
||||
let output = AVAudioPCMBuffer(pcmFormat: outputFormat, frameCapacity: blockSize),
|
||||
let constantSamples = constant.floatChannelData?[0],
|
||||
let toneSamples = tone.floatChannelData?[0],
|
||||
let outputSamples = output.floatChannelData?[0] else {
|
||||
throw AudioMixFixtureError.bufferAllocation
|
||||
}
|
||||
constant.frameLength = constant.frameCapacity
|
||||
tone.frameLength = tone.frameCapacity
|
||||
for index in 0..<Int(constant.frameLength) {
|
||||
constantSamples[index] = 0.125
|
||||
}
|
||||
for index in 0..<Int(tone.frameLength) {
|
||||
toneSamples[index] = Float(0.25 * sin(2 * .pi * toneFrequency * Double(index) / toneRate))
|
||||
}
|
||||
|
||||
let engine = AVAudioEngine()
|
||||
let constantPlayer = AVAudioPlayerNode()
|
||||
let tonePlayer = AVAudioPlayerNode()
|
||||
engine.attach(constantPlayer)
|
||||
engine.attach(tonePlayer)
|
||||
engine.connect(constantPlayer, to: engine.mainMixerNode, format: outputFormat)
|
||||
engine.connect(tonePlayer, to: engine.mainMixerNode, format: toneFormat)
|
||||
try engine.enableManualRenderingMode(.offline, format: outputFormat, maximumFrameCount: blockSize)
|
||||
defer {
|
||||
constantPlayer.stop()
|
||||
tonePlayer.stop()
|
||||
engine.stop()
|
||||
engine.disableManualRenderingMode()
|
||||
}
|
||||
try engine.start()
|
||||
constantPlayer.scheduleBuffer(constant)
|
||||
tonePlayer.scheduleBuffer(tone)
|
||||
constantPlayer.play()
|
||||
tonePlayer.play()
|
||||
|
||||
var mean = 0.0
|
||||
var sine = 0.0
|
||||
var cosine = 0.0
|
||||
var measured = 0
|
||||
for first in stride(from: 0, to: totalFrames, by: Int(blockSize)) {
|
||||
let status = try engine.renderOffline(blockSize, to: output)
|
||||
guard status == .success else { throw AudioMixFixtureError.renderFailure(status) }
|
||||
guard output.frameLength == blockSize else { throw AudioMixFixtureError.shortRender }
|
||||
// Exclude the leading and trailing conversion transients.
|
||||
if first == 0 || first == totalFrames - Int(blockSize) { continue }
|
||||
for offset in 0..<Int(blockSize) {
|
||||
let sample = Double(outputSamples[offset])
|
||||
let phase = 2 * Double.pi * toneFrequency * Double(first + offset) / outputRate
|
||||
mean += sample
|
||||
sine += sample * sin(phase)
|
||||
cosine += sample * cos(phase)
|
||||
measured += 1
|
||||
}
|
||||
}
|
||||
let count = Double(measured)
|
||||
return AudioMixMeasurement(frames: totalFrames, mean: mean / count, toneAmplitude: 2 * hypot(sine, cosine) / count)
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
import CXenora
|
||||
import GameController
|
||||
|
||||
struct ControllerSnapshot: Equatable {
|
||||
let buttons: UInt32
|
||||
let x: Int16
|
||||
let y: Int16
|
||||
let leftTrigger: Float
|
||||
let rightTrigger: Float
|
||||
|
||||
init(buttons: UInt32, x: Float, y: Float, leftTrigger: Float, rightTrigger: Float) {
|
||||
self.buttons = buttons
|
||||
self.x = Self.axis(x)
|
||||
self.y = Self.axis(y)
|
||||
self.leftTrigger = Self.trigger(leftTrigger)
|
||||
self.rightTrigger = Self.trigger(rightTrigger)
|
||||
}
|
||||
|
||||
private static func axis(_ value: Float) -> Int16 {
|
||||
guard value.isFinite else { return 0 }
|
||||
let deadZone: Float = 0.15
|
||||
let magnitude = max(0, min(1, abs(value)) - deadZone) / (1 - deadZone)
|
||||
return Int16((magnitude * (value < 0 ? -32767 : 32767)).rounded())
|
||||
}
|
||||
|
||||
private static func trigger(_ value: Float) -> Float {
|
||||
value.isFinite ? min(1, max(0, value)) : 0
|
||||
}
|
||||
}
|
||||
|
||||
struct DetectedController: Equatable {
|
||||
let identity: ObjectIdentifier
|
||||
let name: String
|
||||
let supportsHaptics: Bool
|
||||
let snapshot: ControllerSnapshot
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func pollGameController() -> DetectedController? {
|
||||
let controller = GCController.current.flatMap { $0.extendedGamepad == nil ? nil : $0 }
|
||||
?? GCController.controllers().first { $0.extendedGamepad != nil }
|
||||
guard let controller, let pad = controller.capture().extendedGamepad else { return nil }
|
||||
var buttons: UInt32 = 0
|
||||
if pad.dpad.right.isPressed { buttons |= UInt32(XENORA_INPUT_RIGHT) }
|
||||
if pad.dpad.left.isPressed { buttons |= UInt32(XENORA_INPUT_LEFT) }
|
||||
if pad.dpad.up.isPressed { buttons |= UInt32(XENORA_INPUT_UP) }
|
||||
if pad.dpad.down.isPressed { buttons |= UInt32(XENORA_INPUT_DOWN) }
|
||||
if pad.buttonA.isPressed { buttons |= UInt32(XENORA_INPUT_ACTION_A) }
|
||||
if pad.buttonB.isPressed { buttons |= UInt32(XENORA_INPUT_ACTION_B) }
|
||||
return DetectedController(
|
||||
identity: ObjectIdentifier(controller),
|
||||
name: controller.vendorName ?? controller.productCategory,
|
||||
supportsHaptics: controller.haptics != nil,
|
||||
snapshot: ControllerSnapshot(
|
||||
buttons: buttons, x: pad.leftThumbstick.xAxis.value, y: pad.leftThumbstick.yAxis.value,
|
||||
leftTrigger: pad.leftTrigger.value, rightTrigger: pad.rightTrigger.value
|
||||
)
|
||||
)
|
||||
}
|
||||
@@ -5,6 +5,9 @@
|
||||
// by native Metal) and shows the verified read-back frame. No other executable can run.
|
||||
|
||||
import AppKit
|
||||
import AVFoundation
|
||||
import AudioToolbox
|
||||
import CoreAudio
|
||||
import CXenora
|
||||
import Foundation
|
||||
import SwiftUI
|
||||
@@ -113,12 +116,13 @@ struct AudioVfsFrame {
|
||||
let samples: UInt32
|
||||
let totalAudioBytes: UInt64
|
||||
let rgba: [UInt8]
|
||||
let pcm: [UInt8]
|
||||
|
||||
static func run() -> AudioVfsFrame {
|
||||
static func run(captureAudio: Bool = false) -> AudioVfsFrame {
|
||||
var session: xenora_session = 0
|
||||
var status = xenora_session_create(XENORA_ABI_VERSION, &session)
|
||||
guard status == XENORA_OK else {
|
||||
return AudioVfsFrame(status: status, width: 0, height: 0, samples: 0, totalAudioBytes: 0, rgba: [])
|
||||
return AudioVfsFrame(status: status, width: 0, height: 0, samples: 0, totalAudioBytes: 0, rgba: [], pcm: [])
|
||||
}
|
||||
defer { _ = xenora_session_destroy(session) }
|
||||
var rgba = [UInt8](repeating: 0, count: 16)
|
||||
@@ -133,13 +137,25 @@ struct AudioVfsFrame {
|
||||
var underruns: UInt32 = 0
|
||||
var total: UInt64 = 0
|
||||
_ = xenora_session_audio_status(session, &queued, &underruns, &total)
|
||||
var pcm: [UInt8] = []
|
||||
if captureAudio && status == XENORA_OK && queued > 0 && queued <= 256 * 1024 {
|
||||
pcm = [UInt8](repeating: 0, count: Int(queued))
|
||||
var read: UInt64 = 0
|
||||
let readStatus = pcm.withUnsafeMutableBufferPointer { buffer in
|
||||
xenora_session_audio_read(session, buffer.baseAddress, UInt64(buffer.count), &read)
|
||||
}
|
||||
if readStatus != XENORA_OK || read != UInt64(queued) {
|
||||
pcm.removeAll()
|
||||
}
|
||||
}
|
||||
return AudioVfsFrame(
|
||||
status: status,
|
||||
width: Int(width),
|
||||
height: Int(height),
|
||||
samples: samples,
|
||||
totalAudioBytes: total,
|
||||
rgba: status == XENORA_OK ? rgba : []
|
||||
rgba: status == XENORA_OK ? rgba : [],
|
||||
pcm: pcm
|
||||
)
|
||||
}
|
||||
|
||||
@@ -158,6 +174,233 @@ struct AudioVfsFrame {
|
||||
}
|
||||
}
|
||||
|
||||
private enum FixturePlaybackError: Error {
|
||||
case invalidPCM
|
||||
case noDefaultOutput(OSStatus)
|
||||
case deviceDiscovery(OSStatus)
|
||||
case unavailableOutput(AudioDeviceID)
|
||||
case outputUnitUnavailable
|
||||
case outputRouting(OSStatus)
|
||||
case unexpectedOutput(AudioDeviceID)
|
||||
case queueFailure(Int32)
|
||||
case queueShortfall(UInt64)
|
||||
case timedOut
|
||||
}
|
||||
|
||||
private struct FixturePlayback {
|
||||
let frames: Int
|
||||
let buffers: Int
|
||||
let refills: Int
|
||||
let underruns: UInt32
|
||||
let outputDevice: AudioDeviceID
|
||||
let outputSampleRate: Double
|
||||
let outputChannels: AVAudioChannelCount
|
||||
let presentationLatency: TimeInterval
|
||||
let completionElapsed: TimeInterval
|
||||
}
|
||||
|
||||
private func defaultAudioOutput() throws -> AudioDeviceID {
|
||||
var address = AudioObjectPropertyAddress(
|
||||
mSelector: kAudioHardwarePropertyDefaultOutputDevice,
|
||||
mScope: kAudioObjectPropertyScopeGlobal,
|
||||
mElement: kAudioObjectPropertyElementMain
|
||||
)
|
||||
var device = AudioDeviceID(kAudioObjectUnknown)
|
||||
var size = UInt32(MemoryLayout<AudioDeviceID>.size)
|
||||
let status = AudioObjectGetPropertyData(
|
||||
AudioObjectID(kAudioObjectSystemObject), &address, 0, nil, &size, &device
|
||||
)
|
||||
guard status == noErr, device != kAudioObjectUnknown else {
|
||||
throw FixturePlaybackError.noDefaultOutput(status)
|
||||
}
|
||||
return device
|
||||
}
|
||||
|
||||
private func audioOutputDevices() throws -> [AudioDeviceID] {
|
||||
let system = AudioObjectID(kAudioObjectSystemObject)
|
||||
var address = AudioObjectPropertyAddress(
|
||||
mSelector: kAudioHardwarePropertyDevices,
|
||||
mScope: kAudioObjectPropertyScopeGlobal,
|
||||
mElement: kAudioObjectPropertyElementMain
|
||||
)
|
||||
let stride = UInt32(MemoryLayout<AudioDeviceID>.stride)
|
||||
var size: UInt32 = 0
|
||||
let sizeStatus = AudioObjectGetPropertyDataSize(system, &address, 0, nil, &size)
|
||||
guard sizeStatus == noErr, size.isMultiple(of: stride) else {
|
||||
throw FixturePlaybackError.deviceDiscovery(sizeStatus)
|
||||
}
|
||||
if size == 0 { return [] }
|
||||
var devices = [AudioDeviceID](repeating: kAudioObjectUnknown, count: Int(size / stride))
|
||||
let readStatus = devices.withUnsafeMutableBytes { bytes in
|
||||
AudioObjectGetPropertyData(system, &address, 0, nil, &size, bytes.baseAddress!)
|
||||
}
|
||||
guard readStatus == noErr, size.isMultiple(of: stride), Int(size / stride) <= devices.count else {
|
||||
throw FixturePlaybackError.deviceDiscovery(readStatus)
|
||||
}
|
||||
return devices.prefix(Int(size / stride)).filter { device in
|
||||
var streams = AudioObjectPropertyAddress(
|
||||
mSelector: kAudioDevicePropertyStreams,
|
||||
mScope: kAudioDevicePropertyScopeOutput,
|
||||
mElement: kAudioObjectPropertyElementMain
|
||||
)
|
||||
var bytes: UInt32 = 0
|
||||
return device != kAudioObjectUnknown
|
||||
&& AudioObjectGetPropertyDataSize(device, &streams, 0, nil, &bytes) == noErr
|
||||
&& bytes > 0
|
||||
}.sorted()
|
||||
}
|
||||
|
||||
private func playFixturePCM(
|
||||
_ pcm: [UInt8], requestedOutput: AudioDeviceID? = nil, streamingFixture: Bool = false
|
||||
) throws -> FixturePlayback {
|
||||
// The embedded audio/VFS fixture submits mono 48 kHz S16LE frames.
|
||||
guard !pcm.isEmpty, pcm.count.isMultiple(of: 2),
|
||||
let format = AVAudioFormat(standardFormatWithSampleRate: 48_000, channels: 1) else {
|
||||
throw FixturePlaybackError.invalidPCM
|
||||
}
|
||||
let sourceFrames = pcm.count / 2
|
||||
let frames = sourceFrames * (streamingFixture ? 32 : 1)
|
||||
let framesPerBuffer = streamingFixture ? 1024 : 128
|
||||
let bufferWindow = 3
|
||||
var streamSession: xenora_session = 0
|
||||
let producer = DispatchQueue(label: "xenora.fixture.pcm")
|
||||
if streamingFixture {
|
||||
let createStatus = xenora_session_create(XENORA_ABI_VERSION, &streamSession)
|
||||
guard createStatus == XENORA_OK else { throw FixturePlaybackError.queueFailure(createStatus) }
|
||||
}
|
||||
let session = streamSession
|
||||
defer {
|
||||
if session != 0 {
|
||||
producer.sync {}
|
||||
_ = xenora_session_destroy(session)
|
||||
}
|
||||
}
|
||||
if session != 0 {
|
||||
let initStatus = xenora_session_audio_init(session, 48_000, 1, UInt32(XENORA_AUDIO_FORMAT_PCM_S16LE))
|
||||
guard initStatus == XENORA_OK else { throw FixturePlaybackError.queueFailure(initStatus) }
|
||||
}
|
||||
let engine = AVAudioEngine()
|
||||
guard let outputUnit = engine.outputNode.audioUnit else {
|
||||
throw FixturePlaybackError.outputUnitUnavailable
|
||||
}
|
||||
if var device = requestedOutput {
|
||||
guard try audioOutputDevices().contains(device) else {
|
||||
throw FixturePlaybackError.unavailableOutput(device)
|
||||
}
|
||||
let status = AudioUnitSetProperty(
|
||||
outputUnit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0,
|
||||
&device, UInt32(MemoryLayout<AudioDeviceID>.size)
|
||||
)
|
||||
guard status == noErr else { throw FixturePlaybackError.outputRouting(status) }
|
||||
}
|
||||
let player = AVAudioPlayerNode()
|
||||
let played = DispatchSemaphore(value: 0)
|
||||
engine.attach(player)
|
||||
engine.connect(player, to: engine.mainMixerNode, format: format)
|
||||
defer {
|
||||
player.stop()
|
||||
engine.stop()
|
||||
engine.detach(player)
|
||||
}
|
||||
try engine.start()
|
||||
var outputDevice = AudioDeviceID(kAudioObjectUnknown)
|
||||
var outputIDSize = UInt32(MemoryLayout<AudioDeviceID>.size)
|
||||
let routeStatus = AudioUnitGetProperty(
|
||||
outputUnit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0,
|
||||
&outputDevice, &outputIDSize
|
||||
)
|
||||
guard routeStatus == noErr else { throw FixturePlaybackError.outputRouting(routeStatus) }
|
||||
guard outputDevice != kAudioObjectUnknown, requestedOutput.map({ $0 == outputDevice }) ?? true else {
|
||||
throw FixturePlaybackError.unexpectedOutput(outputDevice)
|
||||
}
|
||||
let output = engine.outputNode.outputFormat(forBus: 0)
|
||||
let presentationLatency = engine.outputNode.presentationLatency
|
||||
var nextFrame = 0
|
||||
var bufferCount = 0
|
||||
func renderBlock(first: Int, count: Int) throws -> [UInt8] {
|
||||
let firstByte = first * 2
|
||||
let byteCount = count * 2
|
||||
if session == 0 {
|
||||
return Array(pcm[firstByte..<(firstByte + byteCount)])
|
||||
}
|
||||
let submitted = DispatchSemaphore(value: 0)
|
||||
producer.async {
|
||||
let block = (0..<byteCount).map { pcm[(firstByte + $0) % pcm.count] }
|
||||
block.withUnsafeBufferPointer { bytes in
|
||||
_ = xenora_session_audio_submit(session, bytes.baseAddress, UInt64(bytes.count))
|
||||
}
|
||||
submitted.signal()
|
||||
}
|
||||
guard submitted.wait(timeout: .now() + .seconds(1)) == .success else {
|
||||
throw FixturePlaybackError.timedOut
|
||||
}
|
||||
var block = [UInt8](repeating: 0, count: byteCount)
|
||||
var supplied: UInt64 = 0
|
||||
let status = block.withUnsafeMutableBufferPointer { bytes in
|
||||
xenora_session_audio_render(session, bytes.baseAddress, UInt64(bytes.count), &supplied)
|
||||
}
|
||||
guard status == XENORA_OK else { throw FixturePlaybackError.queueFailure(status) }
|
||||
guard supplied == UInt64(byteCount) else { throw FixturePlaybackError.queueShortfall(supplied) }
|
||||
return block
|
||||
}
|
||||
|
||||
func scheduleNextBuffer() throws {
|
||||
let first = nextFrame
|
||||
let count = min(framesPerBuffer, frames - first)
|
||||
let pcmBlock = try renderBlock(first: first, count: count)
|
||||
guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: AVAudioFrameCount(count)),
|
||||
let samples = buffer.floatChannelData?[0] else {
|
||||
throw FixturePlaybackError.invalidPCM
|
||||
}
|
||||
buffer.frameLength = AVAudioFrameCount(count)
|
||||
for offset in 0..<count {
|
||||
let byte = offset * 2
|
||||
let low = UInt16(pcmBlock[byte])
|
||||
let high = UInt16(pcmBlock[byte + 1]) << 8
|
||||
samples[offset] = Float(Int16(bitPattern: low | high)) / 32_768
|
||||
}
|
||||
player.scheduleBuffer(buffer, completionCallbackType: .dataPlayedBack) { _ in
|
||||
played.signal()
|
||||
}
|
||||
bufferCount += 1
|
||||
nextFrame += count
|
||||
}
|
||||
while nextFrame < frames && bufferCount < bufferWindow {
|
||||
try scheduleNextBuffer()
|
||||
}
|
||||
let prequeued = bufferCount
|
||||
let start = DispatchTime.now()
|
||||
player.play()
|
||||
let deadline = start + .seconds(3)
|
||||
var completedBuffers = 0
|
||||
while completedBuffers < bufferCount {
|
||||
guard played.wait(timeout: deadline) == .success else {
|
||||
throw FixturePlaybackError.timedOut
|
||||
}
|
||||
completedBuffers += 1
|
||||
if nextFrame < frames {
|
||||
try scheduleNextBuffer()
|
||||
}
|
||||
}
|
||||
let elapsed = Double(DispatchTime.now().uptimeNanoseconds - start.uptimeNanoseconds) / 1e9
|
||||
var underruns: UInt32 = 0
|
||||
if session != 0 {
|
||||
var queued: UInt32 = 0
|
||||
var total: UInt64 = 0
|
||||
let status = xenora_session_audio_status(session, &queued, &underruns, &total)
|
||||
guard status == XENORA_OK else { throw FixturePlaybackError.queueFailure(status) }
|
||||
guard queued == 0, total == UInt64(frames * 2) else {
|
||||
throw FixturePlaybackError.invalidPCM
|
||||
}
|
||||
}
|
||||
return FixturePlayback(
|
||||
frames: frames, buffers: completedBuffers, refills: bufferCount - prequeued,
|
||||
underruns: underruns, outputDevice: outputDevice,
|
||||
outputSampleRate: output.sampleRate, outputChannels: output.channelCount,
|
||||
presentationLatency: presentationLatency, completionElapsed: elapsed
|
||||
)
|
||||
}
|
||||
|
||||
/// Owns the latest fixture run. A class with @Published avoids SwiftUI macros,
|
||||
/// which the command-line toolchain does not ship.
|
||||
@MainActor
|
||||
@@ -204,6 +447,7 @@ final class FrameLoopModel: ObservableObject {
|
||||
@Published var image: CGImage?
|
||||
@Published var errorMessage: String?
|
||||
@Published var isInteractive: Bool = false
|
||||
@Published private(set) var controller: DetectedController?
|
||||
|
||||
private var session: xenora_session = 0
|
||||
private var pollTask: Task<Void, Never>?
|
||||
@@ -283,6 +527,7 @@ final class FrameLoopModel: ObservableObject {
|
||||
return
|
||||
}
|
||||
isInteractive = true
|
||||
controller = nil
|
||||
state = UInt32(XENORA_LOOP_RUNNING)
|
||||
completed = 0
|
||||
frameId = XENORA_NO_FRAME
|
||||
@@ -291,18 +536,39 @@ final class FrameLoopModel: ObservableObject {
|
||||
}
|
||||
|
||||
func sendInput(buttons: UInt32) {
|
||||
sendInput(buttons: buttons, x: 0, y: 0, connected: true)
|
||||
}
|
||||
|
||||
private func sendInput(
|
||||
buttons: UInt32, x: Int16, y: Int16, connected: Bool,
|
||||
leftTrigger: Float = 0, rightTrigger: Float = 0
|
||||
) {
|
||||
guard session != 0 else { return }
|
||||
var input = xenora_input_state(
|
||||
let state = xenora_input_state(
|
||||
buttons: buttons,
|
||||
stick_x: 0,
|
||||
stick_y: 0,
|
||||
stick_x: x,
|
||||
stick_y: y,
|
||||
mouse_dx: 0,
|
||||
mouse_dy: 0,
|
||||
mouse_buttons: 0,
|
||||
connected: 1,
|
||||
connected: connected ? 1 : 0,
|
||||
reserved: 0
|
||||
)
|
||||
_ = xenora_session_send_input(session, &input)
|
||||
var input = xenora_controller_input(
|
||||
state: state, left_trigger: UInt16((leftTrigger * 65535).rounded()),
|
||||
right_trigger: UInt16((rightTrigger * 65535).rounded())
|
||||
)
|
||||
_ = xenora_session_send_controller_input(session, &input)
|
||||
}
|
||||
|
||||
private func updateGameController() {
|
||||
let next = pollGameController()
|
||||
guard next != controller else { return }
|
||||
controller = next
|
||||
let snapshot = next?.snapshot
|
||||
sendInput(buttons: snapshot?.buttons ?? 0, x: snapshot?.x ?? 0, y: snapshot?.y ?? 0,
|
||||
connected: next != nil, leftTrigger: snapshot?.leftTrigger ?? 0,
|
||||
rightTrigger: snapshot?.rightTrigger ?? 0)
|
||||
}
|
||||
|
||||
func pause() {
|
||||
@@ -326,6 +592,9 @@ final class FrameLoopModel: ObservableObject {
|
||||
while !Task.isCancelled {
|
||||
try? await Task.sleep(nanoseconds: 16_000_000)
|
||||
guard let self = self, self.session != 0 else { break }
|
||||
if self.isInteractive {
|
||||
self.updateGameController()
|
||||
}
|
||||
var st: UInt32 = 0
|
||||
var comp: UInt32 = 0
|
||||
var fId: UInt32 = 0
|
||||
@@ -530,6 +799,11 @@ struct ContentView: View {
|
||||
.disabled(!loop.isRunning && !loop.isPaused)
|
||||
}
|
||||
if loop.isInteractive && (loop.isRunning || loop.isPaused) {
|
||||
if let controller = loop.controller {
|
||||
Text("Controller: \(controller.name)")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
HStack {
|
||||
Button("◀ Left") { loop.sendInput(buttons: UInt32(XENORA_INPUT_LEFT)) }
|
||||
Button("▶ Right") { loop.sendInput(buttons: UInt32(XENORA_INPUT_RIGHT)) }
|
||||
@@ -587,6 +861,71 @@ if CommandLine.arguments.contains("--smoke-resources") {
|
||||
}
|
||||
|
||||
// `--smoke-audio-vfs` tests VFS asset loading, PCM audio streaming, and Metal texture presentation.
|
||||
if CommandLine.arguments.contains("--smoke-controller") {
|
||||
let simulated = ControllerSnapshot(buttons: 1, x: 0.1, y: -1, leftTrigger: 1.2, rightTrigger: .nan)
|
||||
let physical = pollGameController()
|
||||
print("smoke-controller: simulatedAxis=\(simulated.x),\(simulated.y) triggers=\(simulated.leftTrigger),\(simulated.rightTrigger) detected=\(physical?.name ?? "none")")
|
||||
exit(simulated.buttons == 1 && simulated.x == 0 && simulated.y == -32767
|
||||
&& simulated.leftTrigger == 1 && simulated.rightTrigger == 0 ? 0 : 1)
|
||||
}
|
||||
|
||||
if CommandLine.arguments.contains("--smoke-audio-mix") {
|
||||
do {
|
||||
let result = try measureAudioMixFixture()
|
||||
print("smoke-audio-mix: frames=\(result.frames) mean=\(result.mean) toneAmplitude=\(result.toneAmplitude)")
|
||||
exit(result.frames == 4_800 && abs(result.mean - 0.125) < 0.005
|
||||
&& abs(result.toneAmplitude - 0.25) < 0.005 ? 0 : 1)
|
||||
} catch {
|
||||
print("smoke-audio-mix: \(error)")
|
||||
exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
if CommandLine.arguments.contains("--list-audio-outputs") {
|
||||
do {
|
||||
let devices = try audioOutputDevices()
|
||||
let defaultDevice = try? defaultAudioOutput()
|
||||
print("audio-outputs: count=\(devices.count)")
|
||||
for device in devices {
|
||||
print("audio-output: id=\(device) default=\(device == defaultDevice)")
|
||||
}
|
||||
exit(0)
|
||||
} catch {
|
||||
print("audio-outputs: \(error)")
|
||||
exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
let nativeAudioStreamSmoke = CommandLine.arguments.contains("--smoke-native-audio-stream")
|
||||
if CommandLine.arguments.contains("--smoke-native-audio") || nativeAudioStreamSmoke {
|
||||
var requestedOutput: AudioDeviceID?
|
||||
if let index = CommandLine.arguments.firstIndex(of: "--audio-output") {
|
||||
let values = CommandLine.arguments
|
||||
guard index + 1 < values.count, let device = AudioDeviceID(values[index + 1]), device != 0 else {
|
||||
print("smoke-native-audio: --audio-output requires a device ID")
|
||||
exit(2)
|
||||
}
|
||||
requestedOutput = device
|
||||
}
|
||||
let frame = AudioVfsFrame.run(captureAudio: true)
|
||||
guard frame.status == XENORA_OK, frame.samples == 256, frame.pcm.count == 512 else {
|
||||
print("smoke-native-audio: fixture PCM unavailable")
|
||||
exit(1)
|
||||
}
|
||||
do {
|
||||
let played = try playFixturePCM(
|
||||
frame.pcm, requestedOutput: requestedOutput, streamingFixture: nativeAudioStreamSmoke
|
||||
)
|
||||
print("smoke-native-audio: playedBackFrames=\(played.frames) playedBackBuffers=\(played.buffers) refills=\(played.refills) queueUnderruns=\(played.underruns) outputDevice=\(played.outputDevice) outputRate=\(played.outputSampleRate) outputChannels=\(played.outputChannels) presentationLatencyMs=\(played.presentationLatency * 1000) completionElapsedMs=\(played.completionElapsed * 1000)")
|
||||
let expected = nativeAudioStreamSmoke ? (8192, 8, 5) : (256, 2, 0)
|
||||
exit((played.frames, played.buffers, played.refills) == expected
|
||||
&& played.underruns == 0 && played.outputSampleRate > 0 && played.outputChannels > 0 ? 0 : 1)
|
||||
} catch {
|
||||
print("smoke-native-audio: \(error)")
|
||||
exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
if CommandLine.arguments.contains("--smoke-audio-vfs") {
|
||||
let frame = AudioVfsFrame.run()
|
||||
print("smoke-audio-vfs: \(frame.summary)")
|
||||
|
||||
+226
-4
@@ -14,11 +14,12 @@ use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use xenora_metal::NativeCompute;
|
||||
use xenora_metal::{NativeCompute, RunProfile};
|
||||
use xenora_shader::{Architecture, ENTRY_POINT, compile};
|
||||
|
||||
const WARMUP_REPS: usize = 2;
|
||||
const DEFAULT_REPS: usize = 7;
|
||||
const BATCH: usize = 8;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct Fixture {
|
||||
@@ -83,10 +84,66 @@ struct SizeResult {
|
||||
pipeline: Stats,
|
||||
gpu: Stats,
|
||||
host: Stats,
|
||||
/// Host submission stages inside `host`, plus readback after it.
|
||||
submit: SubmitStats,
|
||||
/// Fraction of samples whose GPU timestamp delta was zero.
|
||||
gpu_zero_fraction: f64,
|
||||
}
|
||||
|
||||
/// Host-side split of one dispatch's submission path.
|
||||
///
|
||||
/// `other` is `host` minus library, pipeline and the four stages below it,
|
||||
/// per sample: compile options, function lookup, bounds and validation checks.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
struct SubmitStats {
|
||||
alloc: Stats,
|
||||
encode: Stats,
|
||||
commit: Stats,
|
||||
wait: Stats,
|
||||
readback: Stats,
|
||||
other: Stats,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
struct SubmitSamples {
|
||||
alloc: Vec<f64>,
|
||||
encode: Vec<f64>,
|
||||
commit: Vec<f64>,
|
||||
wait: Vec<f64>,
|
||||
readback: Vec<f64>,
|
||||
other: Vec<f64>,
|
||||
}
|
||||
|
||||
impl SubmitSamples {
|
||||
fn push(&mut self, profile: &RunProfile) {
|
||||
self.alloc.push(profile.alloc_seconds);
|
||||
self.encode.push(profile.encode_seconds);
|
||||
self.commit.push(profile.commit_seconds);
|
||||
self.wait.push(profile.wait_seconds);
|
||||
self.readback.push(profile.readback_seconds);
|
||||
self.other.push(
|
||||
profile.host_seconds
|
||||
- profile.library_seconds
|
||||
- profile.pipeline_seconds
|
||||
- profile.alloc_seconds
|
||||
- profile.encode_seconds
|
||||
- profile.commit_seconds
|
||||
- profile.wait_seconds,
|
||||
);
|
||||
}
|
||||
|
||||
fn stats(self) -> SubmitStats {
|
||||
SubmitStats {
|
||||
alloc: Stats::from_samples(self.alloc),
|
||||
encode: Stats::from_samples(self.encode),
|
||||
commit: Stats::from_samples(self.commit),
|
||||
wait: Stats::from_samples(self.wait),
|
||||
readback: Stats::from_samples(self.readback),
|
||||
other: Stats::from_samples(self.other),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct FixtureResult {
|
||||
name: String,
|
||||
@@ -95,6 +152,14 @@ struct FixtureResult {
|
||||
status: String,
|
||||
reason: String,
|
||||
sizes: Vec<SizeResult>,
|
||||
batch: Option<BatchResult>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct BatchResult {
|
||||
words: usize,
|
||||
sync: Stats,
|
||||
pipelined: Stats,
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
@@ -180,6 +245,7 @@ fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> Fixture
|
||||
status: "not-implemented".to_string(),
|
||||
reason: String::new(),
|
||||
sizes: Vec::new(),
|
||||
batch: None,
|
||||
};
|
||||
|
||||
let code = match fs::read(&fixture.path) {
|
||||
@@ -242,6 +308,7 @@ fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> Fixture
|
||||
let mut pipeline_samples = Vec::with_capacity(reps);
|
||||
let mut gpu_samples = Vec::with_capacity(reps);
|
||||
let mut host_samples = Vec::with_capacity(reps);
|
||||
let mut submit_samples = SubmitSamples::default();
|
||||
let mut gpu_zero = 0usize;
|
||||
|
||||
let mut mismatch = None;
|
||||
@@ -275,6 +342,7 @@ fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> Fixture
|
||||
pipeline_samples.push(profile.pipeline_seconds);
|
||||
gpu_samples.push(profile.gpu_seconds);
|
||||
host_samples.push(profile.host_seconds);
|
||||
submit_samples.push(&profile);
|
||||
if profile.gpu_seconds <= 0.0 {
|
||||
gpu_zero += 1;
|
||||
}
|
||||
@@ -294,6 +362,7 @@ fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> Fixture
|
||||
pipeline: Stats::from_samples(pipeline_samples),
|
||||
gpu: Stats::from_samples(gpu_samples),
|
||||
host: Stats::from_samples(host_samples),
|
||||
submit: submit_samples.stats(),
|
||||
gpu_zero_fraction: if measured == 0 {
|
||||
0.0
|
||||
} else {
|
||||
@@ -302,11 +371,83 @@ fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> Fixture
|
||||
});
|
||||
}
|
||||
|
||||
let batch_words = fixture
|
||||
.sizes
|
||||
.iter()
|
||||
.copied()
|
||||
.min_by_key(|words| words.abs_diff(1024))
|
||||
.unwrap_or(1024);
|
||||
match measure_batch(metal, &code, fixture, batch_words, reps) {
|
||||
Ok(batch) => result.batch = Some(batch),
|
||||
Err(reason) => {
|
||||
result.status = "excluded".to_string();
|
||||
result.reason = reason;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
result.sizes = sizes;
|
||||
result.status = "benchmarked".to_string();
|
||||
result
|
||||
}
|
||||
|
||||
fn measure_batch(
|
||||
metal: &NativeCompute,
|
||||
code: &[u8],
|
||||
fixture: &Fixture,
|
||||
words: usize,
|
||||
reps: usize,
|
||||
) -> Result<BatchResult, String> {
|
||||
let input = expand(&fixture.input, words);
|
||||
let expected = expand(&fixture.expected, words);
|
||||
let mut sync = Vec::with_capacity(reps);
|
||||
let mut pipelined = Vec::with_capacity(reps);
|
||||
for rep in 0..(WARMUP_REPS + reps) {
|
||||
for (samples, variant) in [(&mut sync, "sync"), (&mut pipelined, "pipelined")] {
|
||||
let mut tokens = Vec::with_capacity(BATCH);
|
||||
let mut outputs = Vec::with_capacity(BATCH);
|
||||
let start = std::time::Instant::now();
|
||||
for _ in 0..BATCH {
|
||||
let compiled = compile(Architecture::Gfx1030, code).map_err(|error| {
|
||||
format!("{variant} batch compile failed at {words} words: {error}")
|
||||
})?;
|
||||
if variant == "sync" {
|
||||
let profile = metal
|
||||
.run_words_profiled(&compiled.msl, ENTRY_POINT, &input)
|
||||
.map_err(|error| {
|
||||
format!("{variant} batch run failed at {words} words: {error}")
|
||||
})?;
|
||||
outputs.push(profile.output);
|
||||
} else {
|
||||
let token = metal
|
||||
.submit_words(&compiled.msl, ENTRY_POINT, &input)
|
||||
.map_err(|error| {
|
||||
format!("{variant} batch submit failed at {words} words: {error}")
|
||||
})?;
|
||||
tokens.push(token);
|
||||
}
|
||||
}
|
||||
for token in tokens {
|
||||
let profile = metal.wait(token).map_err(|error| {
|
||||
format!("{variant} batch wait failed at {words} words: {error}")
|
||||
})?;
|
||||
outputs.push(profile.output);
|
||||
}
|
||||
let per_dispatch = start.elapsed().as_secs_f64() / BATCH as f64;
|
||||
if outputs.iter().any(|output| *output != expected) {
|
||||
return Err(format!("{variant} batch GPU mismatch at {words} words"));
|
||||
}
|
||||
if rep >= WARMUP_REPS {
|
||||
samples.push(per_dispatch);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(BatchResult {
|
||||
words,
|
||||
sync: Stats::from_samples(sync),
|
||||
pipelined: Stats::from_samples(pipelined),
|
||||
})
|
||||
}
|
||||
|
||||
fn expand(base: &[u32], words: usize) -> Vec<u32> {
|
||||
(0..words).map(|i| base[i % base.len()]).collect()
|
||||
}
|
||||
@@ -612,13 +753,19 @@ fn results_json(results: &[FixtureResult]) -> String {
|
||||
for (size_index, size) in result.sizes.iter().enumerate() {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" {{ \"words\": {}, \"compile\": {}, \"library\": {}, \"pipeline\": {}, \"gpu\": {}, \"host\": {}, \"gpu_zero_fraction\": {:.4} }}{}",
|
||||
" {{ \"words\": {}, \"compile\": {}, \"library\": {}, \"pipeline\": {}, \"gpu\": {}, \"host\": {}, \"alloc\": {}, \"encode\": {}, \"commit\": {}, \"wait\": {}, \"readback\": {}, \"host_other\": {}, \"gpu_zero_fraction\": {:.4} }}{}",
|
||||
size.words,
|
||||
stats_json(&size.compile),
|
||||
stats_json(&size.library),
|
||||
stats_json(&size.pipeline),
|
||||
stats_json(&size.gpu),
|
||||
stats_json(&size.host),
|
||||
stats_json(&size.submit.alloc),
|
||||
stats_json(&size.submit.encode),
|
||||
stats_json(&size.submit.commit),
|
||||
stats_json(&size.submit.wait),
|
||||
stats_json(&size.submit.readback),
|
||||
stats_json(&size.submit.other),
|
||||
size.gpu_zero_fraction,
|
||||
if size_index + 1 == result.sizes.len() {
|
||||
""
|
||||
@@ -627,9 +774,19 @@ fn results_json(results: &[FixtureResult]) -> String {
|
||||
}
|
||||
);
|
||||
}
|
||||
out.push_str(" ]");
|
||||
if let Some(batch) = &result.batch {
|
||||
let _ = write!(
|
||||
out,
|
||||
",\n \"batch\": {{ \"dispatches\": {BATCH}, \"words\": {}, \"sync\": {}, \"pipelined\": {} }}",
|
||||
batch.words,
|
||||
stats_json(&batch.sync),
|
||||
stats_json(&batch.pipelined)
|
||||
);
|
||||
}
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" ]\n }}{}",
|
||||
"\n }}{}",
|
||||
if index + 1 == results.len() { "" } else { "," }
|
||||
);
|
||||
}
|
||||
@@ -644,7 +801,7 @@ fn report_markdown(metadata: &Metadata, results: &[FixtureResult]) -> String {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"Generated by `xenora-bench`. Every timed fixture passed its correctness test in this run. \
|
||||
Timings are single command-buffer samples; see `docs/testing/benchmarks.md` for the protocol."
|
||||
See `docs/testing/benchmarks.md` for the single-dispatch protocol."
|
||||
);
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(out, "## Environment");
|
||||
@@ -739,5 +896,70 @@ fn report_markdown(metadata: &Metadata, results: &[FixtureResult]) -> String {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(out, "## Submission split");
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"Medians in microseconds of the host stages inside `host`: `alloc` creates the input and \
|
||||
output shared buffers, `encode` creates the command buffer and encodes the dispatch, \
|
||||
`commit` and `wait` time `commit` and `waitUntilCompleted`, and `other` is the per-sample \
|
||||
remainder of `host` after library, pipeline and these four stages. `readback` copies \
|
||||
the output after `host` ends."
|
||||
);
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| Fixture | Words | host | alloc | encode | commit | wait | other | readback |"
|
||||
);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| --- | --- | --- | --- | --- | --- | --- | --- | --- |"
|
||||
);
|
||||
for result in results.iter().filter(|r| r.status == "benchmarked") {
|
||||
for size in &result.sizes {
|
||||
let stages = &size.submit;
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| {} | {} | {:.2} | {:.2} | {:.2} | {:.2} | {:.2} | {:.2} | {:.2} |",
|
||||
result.name,
|
||||
size.words,
|
||||
size.host.median * 1e6,
|
||||
stages.alloc.median * 1e6,
|
||||
stages.encode.median * 1e6,
|
||||
stages.commit.median * 1e6,
|
||||
stages.wait.median * 1e6,
|
||||
stages.other.median * 1e6,
|
||||
stages.readback.median * 1e6
|
||||
);
|
||||
}
|
||||
}
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(out, "## Batched submission");
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"Median host microseconds per dispatch in batches of {BATCH}, including recompilation."
|
||||
);
|
||||
let _ = writeln!(out);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| Fixture | Words | Sync (µs) | Pipelined (µs) | Sync / pipelined |"
|
||||
);
|
||||
let _ = writeln!(out, "| --- | --- | --- | --- | --- |");
|
||||
for result in results {
|
||||
if let Some(batch) = &result.batch {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| {} | {} | {:.2} | {:.2} | {:.2}× |",
|
||||
result.name,
|
||||
batch.words,
|
||||
batch.sync.median * 1e6,
|
||||
batch.pipelined.median * 1e6,
|
||||
batch.sync.median / batch.pipelined.median
|
||||
);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
+39
-6
@@ -6,6 +6,9 @@ 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") => {
|
||||
@@ -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() {
|
||||
@@ -288,7 +291,7 @@ fn run_imports_generate_cli(args: &[String]) -> ExitCode {
|
||||
}
|
||||
}
|
||||
|
||||
let records = if let Some(ref pe) = pe_path {
|
||||
let mut records = if let Some(ref pe) = pe_path {
|
||||
println!("Extracting imports from PE executable: {pe}");
|
||||
let bytes = match std::fs::read(pe) {
|
||||
Ok(b) => b,
|
||||
@@ -311,6 +314,10 @@ fn run_imports_generate_cli(args: &[String]) -> ExitCode {
|
||||
.map(|imp| xenora_import_gen::ImportRecord {
|
||||
module: imp.dll,
|
||||
symbol: imp.symbol,
|
||||
ordinal: match imp.import_name {
|
||||
xenora_loader::import_table::ImportName::Ordinal(ordinal) => Some(ordinal),
|
||||
xenora_loader::import_table::ImportName::Name(_) => None,
|
||||
},
|
||||
iat_rva: imp.iat_rva as u64,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
@@ -329,17 +336,24 @@ fn run_imports_generate_cli(args: &[String]) -> ExitCode {
|
||||
return ExitCode::from(2);
|
||||
};
|
||||
|
||||
records.sort();
|
||||
records.dedup();
|
||||
println!("Total imports extracted: {}", records.len());
|
||||
let db = xenora_import_gen::SymbolDb::builtin();
|
||||
let manifest = xenora_import_gen::Manifest::build(&records, &db);
|
||||
let summary = manifest.summary();
|
||||
|
||||
println!("Classification summary:");
|
||||
println!("Catalog classification by import slot:");
|
||||
for (tier, count) in &summary {
|
||||
let pct = (*count as f64 / records.len() as f64 * 100.0) as u32;
|
||||
println!(" - {tier}: {count} ({pct}%)");
|
||||
}
|
||||
|
||||
println!("Emitted disposition by distinct import:");
|
||||
for (disposition, count) in manifest.emission_summary() {
|
||||
println!(" - {disposition}: {count}");
|
||||
}
|
||||
|
||||
let files = xenora_import_gen::generate(&manifest, &db);
|
||||
if let Err(err) = files.write_all(&out_dir) {
|
||||
eprintln!("failed to write generated files: {err}");
|
||||
@@ -362,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;
|
||||
@@ -417,6 +431,7 @@ fn run_imports_sync(
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Arc;
|
||||
use xenora_loader::ImportRegistry;
|
||||
use xenora_loader::import_table::ImportName;
|
||||
use xenora_loader::imports::ServiceStatus;
|
||||
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
|
||||
|
||||
@@ -441,7 +456,17 @@ fn run_imports_sync(
|
||||
let mut total = 0usize;
|
||||
let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new();
|
||||
|
||||
for line in csv_text.lines().skip(1) {
|
||||
let mut lines = csv_text.lines();
|
||||
let header = lines.next().unwrap_or_default();
|
||||
let has_import_kind = header.ends_with(",import_kind");
|
||||
// Binding does not resolve delay-loaded imports, so the backlog omits them.
|
||||
let table_column = header
|
||||
.split(',')
|
||||
.position(|column| column == "import_table");
|
||||
for line in lines {
|
||||
if table_column.and_then(|index| line.split(',').nth(index)) == Some("delayed") {
|
||||
continue;
|
||||
}
|
||||
// Format: "module","symbol",0xRVA,category,registered,status,is_alias,"canonical",priority,cluster
|
||||
// We re-query the live registry rather than trusting cached status.
|
||||
let fields: Vec<&str> = line.splitn(10, ',').collect();
|
||||
@@ -454,7 +479,15 @@ fn run_imports_sync(
|
||||
continue;
|
||||
}
|
||||
|
||||
let binding = registry.binding(&module, &symbol);
|
||||
let name = if has_import_kind && line.ends_with(",ordinal") {
|
||||
let Some(ordinal) = symbol.strip_prefix("Ordinal#").and_then(|n| n.parse().ok()) else {
|
||||
continue;
|
||||
};
|
||||
ImportName::Ordinal(ordinal)
|
||||
} else {
|
||||
ImportName::Name(symbol.clone())
|
||||
};
|
||||
let binding = registry.resolve(&module, &name);
|
||||
let is_registered = binding.is_some();
|
||||
let status = binding.map(|b| b.status);
|
||||
|
||||
|
||||
+26
-14
@@ -10,11 +10,14 @@ use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use xenora_loader::startup::{StartupEvent, StartupLayout, run_synthetic_startup_with_observer};
|
||||
use xenora_loader::{ExitReason, ImportRegistry, Register};
|
||||
use xenora_loader::{
|
||||
ExitReason, ImportRegistry, Register, ServicesState, SystemClock, register_standard_services,
|
||||
};
|
||||
use xenora_metal::NativeCompute;
|
||||
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
|
||||
|
||||
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/trusted-runner.exe");
|
||||
const SERVICES_FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/runtime-services.exe");
|
||||
const WALL_LIMIT: Duration = Duration::from_secs(15);
|
||||
const DEFAULT_STEPS: usize = 100;
|
||||
const MAX_STEPS: usize = 10_000;
|
||||
@@ -132,11 +135,11 @@ fn launch_worker(options: &Options) -> Result<ExitCode, Box<dyn Error>> {
|
||||
}
|
||||
}
|
||||
|
||||
fn verify_fixture(path: &Path) -> Result<(), Box<dyn Error>> {
|
||||
fn verify_fixture(path: &Path) -> Result<&'static [u8], Box<dyn Error>> {
|
||||
let valid_metadata =
|
||||
|metadata: fs::Metadata| metadata.is_file() && metadata.len() == FIXTURE.len() as u64;
|
||||
let rejection =
|
||||
"execution denied: input must match the original trusted PE fixture byte for byte";
|
||||
"execution denied: input must match an embedded trusted PE fixture byte for byte";
|
||||
// Check size before opening and again on the descriptor. Bound the read
|
||||
// even if another process changes the file after the metadata checks.
|
||||
if !valid_metadata(fs::metadata(path)?) {
|
||||
@@ -149,10 +152,10 @@ fn verify_fixture(path: &Path) -> Result<(), Box<dyn Error>> {
|
||||
let mut bytes = Vec::with_capacity(FIXTURE.len() + 1);
|
||||
file.take(FIXTURE.len() as u64 + 1)
|
||||
.read_to_end(&mut bytes)?;
|
||||
if bytes != FIXTURE {
|
||||
return Err(rejection.into());
|
||||
}
|
||||
Ok(())
|
||||
[FIXTURE, SERVICES_FIXTURE]
|
||||
.into_iter()
|
||||
.find(|fixture| *fixture == bytes)
|
||||
.ok_or_else(|| rejection.into())
|
||||
}
|
||||
|
||||
fn run_worker(options: &Options) -> Result<(), Box<dyn Error>> {
|
||||
@@ -164,10 +167,15 @@ fn run_worker(options: &Options) -> Result<(), Box<dyn Error>> {
|
||||
// its own deadline if it is invoked directly.
|
||||
std::process::exit(124);
|
||||
})?;
|
||||
verify_fixture(&options.path)?;
|
||||
let fixture = verify_fixture(&options.path)?;
|
||||
let (name, ticket, bound_imports) = if fixture == SERVICES_FIXTURE {
|
||||
("runtime-services", 23, 3)
|
||||
} else {
|
||||
("trusted-runner", TICKET, 1)
|
||||
};
|
||||
if options.trace {
|
||||
println!(
|
||||
"trace fixture=trusted-runner policy=exact-bytes entry_step_limit={} wall_limit_ms=15000",
|
||||
"trace fixture={name} policy=exact-bytes entry_step_limit={} wall_limit_ms=15000",
|
||||
options.max_steps
|
||||
);
|
||||
}
|
||||
@@ -175,6 +183,10 @@ fn run_worker(options: &Options) -> Result<(), Box<dyn Error>> {
|
||||
let capture = Arc::new(Mutex::new(None));
|
||||
let draw_capture = Arc::clone(&capture);
|
||||
let mut imports = ImportRegistry::new();
|
||||
register_standard_services(
|
||||
&mut imports,
|
||||
Arc::new(ServicesState::new(Arc::new(SystemClock))),
|
||||
);
|
||||
let trace = options.trace;
|
||||
imports.register("xenora.dll", "fixture_draw", move |args, _, memory| {
|
||||
let ticket_address = args.get(0, memory).map_err(ExitReason::MemoryFault)?;
|
||||
@@ -188,15 +200,15 @@ fn run_worker(options: &Options) -> Result<(), Box<dyn Error>> {
|
||||
|| memory
|
||||
.read_u64(ticket_address)
|
||||
.map_err(ExitReason::MemoryFault)?
|
||||
!= TICKET
|
||||
!= ticket
|
||||
{
|
||||
*result = Some(Err(
|
||||
"draw ticket did not match the TLS-initialized guest word".into(),
|
||||
"guest draw ticket differed from the expected value".into()
|
||||
));
|
||||
return Err(ExitReason::IllegalInstruction(0xff));
|
||||
}
|
||||
if trace {
|
||||
println!("trace import=xenora.dll!fixture_draw tls_ticket={TICKET}");
|
||||
println!("trace import=xenora.dll!fixture_draw tls_ticket={ticket}");
|
||||
}
|
||||
let frame = draw().map_err(|error| error.to_string());
|
||||
let drawn = frame.is_ok();
|
||||
@@ -211,7 +223,7 @@ fn run_worker(options: &Options) -> Result<(), Box<dyn Error>> {
|
||||
let started = Instant::now();
|
||||
// Use only the embedded snapshot. The file is solely an exact-byte gate.
|
||||
let startup = run_synthetic_startup_with_observer(
|
||||
FIXTURE,
|
||||
fixture,
|
||||
StartupLayout {
|
||||
image_base: IMAGE_BASE,
|
||||
stack_top: 0x200010000,
|
||||
@@ -245,7 +257,7 @@ fn run_worker(options: &Options) -> Result<(), Box<dyn Error>> {
|
||||
return Err(exit.into());
|
||||
}
|
||||
if startup.relocations.applied_dir64 != 4
|
||||
|| startup.bound_imports != 1
|
||||
|| startup.bound_imports != bound_imports
|
||||
|| startup.tls_callbacks != 1
|
||||
|| rax != DRAW_RESULT
|
||||
{
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Default report folder of `xenora probe` and `xenora 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_xenora"))
|
||||
.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]);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! `xenora imports sync` over a probe report that lists delay-loaded imports.
|
||||
|
||||
use std::process::Command;
|
||||
|
||||
#[test]
|
||||
fn backlog_leaves_out_delay_loaded_imports() {
|
||||
// `fixtures/pe/delay-imports.py` writes two ordinary imports from
|
||||
// `fixture-ordinary.dll` and three delay-loaded ones from two other DLLs.
|
||||
let fixture = concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/../../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"))
|
||||
.args(arguments)
|
||||
.arg("--report")
|
||||
.arg(&report)
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success(), "{arguments:?}");
|
||||
};
|
||||
xenora(&["probe", "--pe", fixture]);
|
||||
xenora(&["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();
|
||||
|
||||
assert_eq!(listed.matches(",delayed,").count(), 3);
|
||||
assert!(backlog.contains("| **Total** | 2 |"), "{backlog}");
|
||||
assert!(backlog.contains("fixture-ordinary.dll"), "{backlog}");
|
||||
assert!(!backlog.contains("fixture-delay"), "{backlog}");
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! The import generator skips emitting an adapter for a symbol it classifies
|
||||
//! as a standard service, so every such classification must name a handler
|
||||
//! the standard loader registry actually provides.
|
||||
|
||||
use std::sync::Arc;
|
||||
use xenora_import_gen::{Classification, SymbolDb};
|
||||
use xenora_loader::import_table::ImportName;
|
||||
use xenora_loader::imports::{ImportRegistry, ServiceStatus};
|
||||
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
|
||||
|
||||
#[test]
|
||||
fn every_standard_service_classification_resolves_to_a_registered_handler() {
|
||||
let mut registry = ImportRegistry::new();
|
||||
let state = ServicesState::new(Arc::new(MockClock::new(0)));
|
||||
register_standard_services(&mut registry, Arc::new(state));
|
||||
|
||||
let db = SymbolDb::builtin();
|
||||
let mut checked = 0;
|
||||
let mut missing = Vec::new();
|
||||
for (module, symbol, class) in db.entries() {
|
||||
if !matches!(class, Classification::StandardService) {
|
||||
continue;
|
||||
}
|
||||
checked += 1;
|
||||
match registry.resolve(module, &ImportName::Name(symbol.to_string())) {
|
||||
Some(service) if service.status != ServiceStatus::Stub => {}
|
||||
_ => missing.push(format!("{module}!{symbol}")),
|
||||
}
|
||||
}
|
||||
assert!(missing.is_empty(), "unregistered: {missing:?}");
|
||||
assert!(checked > 100, "{checked}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registered_synchronization_services_are_not_classified_as_stubs() {
|
||||
let db = SymbolDb::builtin();
|
||||
for module in ["api-ms-win-core-synch-l1-1-0.dll", "kernel32.dll"] {
|
||||
for symbol in [
|
||||
"CreateSemaphoreW",
|
||||
"ReleaseSemaphore",
|
||||
"CreateMutexW",
|
||||
"EnterCriticalSection",
|
||||
"TryEnterCriticalSection",
|
||||
"AcquireSRWLockExclusive",
|
||||
] {
|
||||
assert!(
|
||||
matches!(
|
||||
db.get(module, symbol),
|
||||
Some(Classification::StandardService)
|
||||
),
|
||||
"{module}!{symbol}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
+147
-168
@@ -4,20 +4,18 @@ use std::fmt;
|
||||
|
||||
pub use xenora_isa::{
|
||||
Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp,
|
||||
ScalarCompareOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorCompareOp, VectorSource,
|
||||
ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, ScalarSource, ScalarUnaryOp,
|
||||
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_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, V_ADD_F32,
|
||||
V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_CMP_EQ_I32, V_CMP_EQ_U32, V_CMP_GE_I32, V_CMP_GE_U32,
|
||||
V_CMP_GT_I32, V_CMP_GT_U32, V_CMP_LE_I32, V_CMP_LE_U32, V_CMP_LT_I32, V_CMP_LT_U32,
|
||||
V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32, V_LSHRREV_B32,
|
||||
V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32, VCC_LO,
|
||||
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;
|
||||
use xenora_isa::semantics::FORM_IDS;
|
||||
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
|
||||
@@ -42,43 +40,17 @@ 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); 36] = [
|
||||
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_MOV_B32", EncodingFamily::Sop1),
|
||||
("S_WAITCNT", EncodingFamily::Sopp),
|
||||
("S_WAITCNT_VSCNT", EncodingFamily::Sopk),
|
||||
("V_ADD_F32", EncodingFamily::Vop2),
|
||||
("V_ADD_NC_U32", EncodingFamily::Vop3),
|
||||
("V_AND_B32", EncodingFamily::Vop2),
|
||||
("V_ASHRREV_I32", EncodingFamily::Vop2),
|
||||
("V_CMP_EQ_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_EQ_U32", EncodingFamily::Vopc),
|
||||
("V_CMP_GE_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_GE_U32", EncodingFamily::Vopc),
|
||||
("V_CMP_GT_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_GT_U32", EncodingFamily::Vopc),
|
||||
("V_CMP_LE_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_LE_U32", EncodingFamily::Vopc),
|
||||
("V_CMP_LT_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_LT_U32", EncodingFamily::Vopc),
|
||||
("V_CMP_NE_I32", EncodingFamily::Vopc),
|
||||
("V_CMP_NE_U32", EncodingFamily::Vopc),
|
||||
("V_INTERP_P1_F32", EncodingFamily::Vintrp),
|
||||
("V_INTERP_P2_F32", EncodingFamily::Vintrp),
|
||||
("V_LSHLREV_B32", EncodingFamily::Vop2),
|
||||
("V_LSHRREV_B32", EncodingFamily::Vop2),
|
||||
("V_MOV_B32", EncodingFamily::Vop1),
|
||||
("V_MUL_F32", EncodingFamily::Vop2),
|
||||
("V_OR_B32", EncodingFamily::Vop2),
|
||||
("V_XOR_B32", EncodingFamily::Vop2),
|
||||
];
|
||||
|
||||
/// A successfully decoded instruction and its location in the input stream.
|
||||
@@ -338,49 +310,65 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
if V_MOV_B32.matches(first) {
|
||||
return move_b32(first, bytes);
|
||||
}
|
||||
{
|
||||
use CompareRelation::{Equal, Greater, GreaterOrEqual, Less, LessOrEqual, NotEqual};
|
||||
for (opcode, relation, signed) in [
|
||||
(V_CMP_LT_I32, Less, true),
|
||||
(V_CMP_EQ_I32, Equal, true),
|
||||
(V_CMP_LE_I32, LessOrEqual, true),
|
||||
(V_CMP_GT_I32, Greater, true),
|
||||
(V_CMP_NE_I32, NotEqual, true),
|
||||
(V_CMP_GE_I32, GreaterOrEqual, true),
|
||||
(V_CMP_LT_U32, Less, false),
|
||||
(V_CMP_EQ_U32, Equal, false),
|
||||
(V_CMP_LE_U32, LessOrEqual, false),
|
||||
(V_CMP_GT_U32, Greater, false),
|
||||
(V_CMP_NE_U32, NotEqual, false),
|
||||
(V_CMP_GE_U32, GreaterOrEqual, false),
|
||||
] {
|
||||
if opcode.matches(first) {
|
||||
return vector_compare(VectorCompareOp { relation, signed }, 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 V_ADD_NC_U32.matches(first) {
|
||||
let len = V_ADD_NC_U32.byte_len();
|
||||
let second = word(bytes, len)?;
|
||||
return Ok((add_u32(first, second)?, len));
|
||||
}
|
||||
if S_MOV_B32.matches(first) {
|
||||
let dst = ((first >> 16) & 0x7f) as u8;
|
||||
if !matches!(dst, 0..=107 | 126..=127) {
|
||||
if let Some(op) = VectorSwapOp::from_word(first) {
|
||||
if first & 0x100 == 0 {
|
||||
return Err(unsupported(
|
||||
"s_mov_b32",
|
||||
"expected a normal SGPR or EXEC/VCC destination",
|
||||
op.assembly_name(),
|
||||
"expected a VGPR SRC0 for writeback",
|
||||
));
|
||||
}
|
||||
let (src, len) = scalar_source(first as u8, bytes, "s_mov_b32")?;
|
||||
return Ok((Instruction::ScalarMoveB32 { dst, src }, len));
|
||||
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));
|
||||
}
|
||||
if let Some(op) = ScalarUnaryOp::from_word(first) {
|
||||
// SOP1: SSRC0 in bits 0-7, SDST in bits 16-22.
|
||||
let mnemonic = op.mnemonic();
|
||||
let dst = ((first >> 16) & 0x7f) as u8;
|
||||
if dst > 105 {
|
||||
return Err(unsupported(mnemonic, "expected a normal SGPR destination"));
|
||||
match op.semantics().operands {
|
||||
OperandRule::Sop1Move if !matches!(dst, 0..=107 | 126..=127) => {
|
||||
return Err(unsupported(
|
||||
mnemonic,
|
||||
"expected a normal SGPR or EXEC/VCC destination",
|
||||
));
|
||||
}
|
||||
OperandRule::Sop1Sgpr if dst > 105 => {
|
||||
return Err(unsupported(mnemonic, "expected a normal SGPR destination"));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let (src, len) = scalar_source(first as u8, bytes, mnemonic)?;
|
||||
return Ok((Instruction::ScalarUnary { op, dst, src }, len));
|
||||
@@ -402,39 +390,60 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
len0.max(len1),
|
||||
));
|
||||
}
|
||||
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) = ScalarImmediateOp::from_word(first) {
|
||||
// SOPK: SIMM16 in bits 0-15, SDST in bits 16-22; the word has no literal.
|
||||
let dst = ((first >> 16) & 0x7f) as u8;
|
||||
if dst > 105 {
|
||||
return Err(unsupported(
|
||||
op.mnemonic(),
|
||||
"expected a normal SGPR destination",
|
||||
));
|
||||
}
|
||||
let simm16 = first as u16;
|
||||
return Ok((Instruction::ScalarImmediate { op, dst, simm16 }, 4));
|
||||
}
|
||||
if let Some(op) = ScalarImmediateCompareOp::from_word(first) {
|
||||
let src = ((first >> 16) & 0x7f) as u8;
|
||||
if src > 105 {
|
||||
return Err(unsupported(op.mnemonic(), "expected a normal SGPR operand"));
|
||||
}
|
||||
let simm16 = first as u16;
|
||||
return Ok((Instruction::ScalarImmediateCompare { op, src, simm16 }, 4));
|
||||
}
|
||||
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;
|
||||
let src1 = ((first >> 9) & 0xff) as u8;
|
||||
let (src0, len) = vector_src0(first, bytes, op.assembly_name())?;
|
||||
let (src0, len) = match op.operand_rule() {
|
||||
// Operand rule `vop2_vgpr2`: SRC0 must select a VGPR (256-511).
|
||||
OperandRule::Vop2Vgpr2 => {
|
||||
let (_, src0, _) = vop2_registers(first, op.assembly_name())?;
|
||||
(VectorSource::Register(src0), 4)
|
||||
}
|
||||
OperandRule::Vop2Vgpr | OperandRule::Vop2Vcc => {
|
||||
vector_src0(first, bytes, op.assembly_name())?
|
||||
}
|
||||
_ => unreachable!("non-VOP2 operand rule for VOP2 instruction"),
|
||||
};
|
||||
return Ok((
|
||||
Instruction::VectorAlu {
|
||||
op,
|
||||
@@ -445,48 +454,6 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
len,
|
||||
));
|
||||
}
|
||||
if V_LSHLREV_B32.matches(first) {
|
||||
let (dst, src0, src1) = vop2_registers(first, "v_lshlrev_b32_e32")?;
|
||||
return Ok((
|
||||
Instruction::VectorLshlrevB32 { dst, src0, src1 },
|
||||
V_LSHLREV_B32.byte_len(),
|
||||
));
|
||||
}
|
||||
if V_ASHRREV_I32.matches(first) {
|
||||
let (dst, src0, src1) = vop2_registers(first, "v_ashrrev_i32_e32")?;
|
||||
return Ok((
|
||||
Instruction::VectorAshrrevI32 { dst, src0, src1 },
|
||||
V_ASHRREV_I32.byte_len(),
|
||||
));
|
||||
}
|
||||
if V_LSHRREV_B32.matches(first) {
|
||||
let (dst, src0, src1) = vop2_registers(first, "v_lshrrev_b32_e32")?;
|
||||
return Ok((
|
||||
Instruction::VectorLshrrevB32 { dst, src0, src1 },
|
||||
V_LSHRREV_B32.byte_len(),
|
||||
));
|
||||
}
|
||||
if V_AND_B32.matches(first) {
|
||||
let (dst, src0, src1) = vop2_registers(first, "v_and_b32_e32")?;
|
||||
return Ok((
|
||||
Instruction::VectorAndB32 { dst, src0, src1 },
|
||||
V_AND_B32.byte_len(),
|
||||
));
|
||||
}
|
||||
if V_OR_B32.matches(first) {
|
||||
let (dst, src0, src1) = vop2_registers(first, "v_or_b32_e32")?;
|
||||
return Ok((
|
||||
Instruction::VectorOrB32 { dst, src0, src1 },
|
||||
V_OR_B32.byte_len(),
|
||||
));
|
||||
}
|
||||
if V_XOR_B32.matches(first) {
|
||||
let (dst, src0, src1) = vop2_registers(first, "v_xor_b32_e32")?;
|
||||
return Ok((
|
||||
Instruction::VectorXorB32 { dst, src0, src1 },
|
||||
V_XOR_B32.byte_len(),
|
||||
));
|
||||
}
|
||||
if V_ADD_F32.matches(first) {
|
||||
let (dst, src0, src1) = vop2_registers(first, "v_add_f32_e32")?;
|
||||
return Ok((
|
||||
@@ -501,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,
|
||||
@@ -519,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 })
|
||||
}
|
||||
@@ -584,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
|
||||
@@ -715,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.mnemonic())?;
|
||||
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,
|
||||
@@ -779,22 +743,37 @@ fn move_b32(first: u32, bytes: &[u8]) -> Result<(Instruction, u8), DecodeErrorKi
|
||||
Ok((Instruction::MoveB32 { dst, src }, len))
|
||||
}
|
||||
|
||||
fn add_u32(first: u32, second: u32) -> Result<Instruction, DecodeErrorKind> {
|
||||
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;
|
||||
// All output and input modifiers are clear. The unused third source uses
|
||||
// the gfx1030 assembler's inline-zero operand encoding.
|
||||
if first & 0xff00 != 0 || second >> 18 != 128 || src0 < 256 || src1 < 256 {
|
||||
return Err(unsupported(
|
||||
"v_add_nc_u32_e64",
|
||||
mnemonic,
|
||||
"expected two VGPR sources and no modifiers",
|
||||
));
|
||||
}
|
||||
Ok(Instruction::AddNoCarryU32 {
|
||||
dst: first as u8,
|
||||
src0: src0 as u8,
|
||||
src1: src1 as u8,
|
||||
})
|
||||
Ok((src0 as u8, src1 as u8))
|
||||
}
|
||||
|
||||
fn scalar_form(
|
||||
|
||||
+530
-69
@@ -4,12 +4,13 @@ use std::process::{Command, Stdio};
|
||||
|
||||
use xenora_decoder::{
|
||||
Architecture, CompareRelation, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction,
|
||||
ScalarAluOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorSource, decode, decode_at,
|
||||
ScalarAluOp, ScalarImmediateOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op,
|
||||
VectorCompareOp, VectorCompareVop3Op, VectorSource, VectorUnaryOp, decode, decode_at,
|
||||
};
|
||||
use xenora_isa::semantics::Signedness;
|
||||
use xenora_ref::{
|
||||
BranchCondition, CompareSource, Comparison, Op, ScalarAlu, 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");
|
||||
@@ -43,7 +44,8 @@ fn decodes_each_fixture_instruction_with_offset_and_length() {
|
||||
(
|
||||
20,
|
||||
8,
|
||||
Instruction::AddNoCarryU32 {
|
||||
Instruction::VectorAluVop3 {
|
||||
op: VectorAluVop3Op::AddNcU32,
|
||||
dst: 1,
|
||||
src0: 1,
|
||||
src1: 2,
|
||||
@@ -69,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];
|
||||
@@ -301,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 {
|
||||
@@ -328,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,
|
||||
@@ -373,10 +550,27 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
reference_scalar(src0),
|
||||
reference_scalar(src1),
|
||||
),
|
||||
Instruction::AddNoCarryU32 { dst, src0, src1 } => Op::Add(dst, src0, src1),
|
||||
Instruction::ScalarMoveB32 { dst, src } => Op::ScalarMove(dst, reference_scalar(src)),
|
||||
Instruction::ScalarUnary { op, dst, src } => Op::ScalarUnary(
|
||||
match op {
|
||||
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 {
|
||||
ScalarUnaryOp::MovB32 => return Op::ScalarMove(dst, src),
|
||||
ScalarUnaryOp::NotB32 => ScalarUnary::Not,
|
||||
ScalarUnaryOp::BrevB32 => ScalarUnary::ReverseBits,
|
||||
ScalarUnaryOp::Bcnt0I32B32 => ScalarUnary::CountZeros,
|
||||
@@ -388,10 +582,9 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
ScalarUnaryOp::SextI32I8 => ScalarUnary::SignExtendByte,
|
||||
ScalarUnaryOp::SextI32I16 => ScalarUnary::SignExtendShort,
|
||||
ScalarUnaryOp::AbsI32 => ScalarUnary::Absolute,
|
||||
},
|
||||
dst,
|
||||
reference_scalar(src),
|
||||
),
|
||||
};
|
||||
Op::ScalarUnary(unary, dst, src)
|
||||
}
|
||||
Instruction::ScalarCompare { op, src0, src1 } => {
|
||||
let (src0, src1) = (reference_scalar(src0), reference_scalar(src1));
|
||||
// The reference keeps CompareEqual for EQ and uses its VOPC relation
|
||||
@@ -408,6 +601,25 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
),
|
||||
}
|
||||
}
|
||||
Instruction::ScalarImmediate { op, dst, simm16 } => Op::ScalarImmediate(
|
||||
match op {
|
||||
ScalarImmediateOp::MovkI32 => ScalarImmediate::Move,
|
||||
ScalarImmediateOp::CmovkI32 => ScalarImmediate::ConditionalMove,
|
||||
ScalarImmediateOp::AddkI32 => ScalarImmediate::Add,
|
||||
ScalarImmediateOp::MulkI32 => ScalarImmediate::Multiply,
|
||||
},
|
||||
dst,
|
||||
simm16,
|
||||
),
|
||||
Instruction::ScalarImmediateCompare { op, src, simm16 } => Op::ScalarImmediate(
|
||||
ScalarImmediate::Compare(Comparison {
|
||||
// The reference's VOPC relation offsets, as for SOPC above.
|
||||
offset: op.relation() as u8 + 1,
|
||||
signed: op.semantics().signedness == Signedness::Signed,
|
||||
}),
|
||||
src,
|
||||
simm16,
|
||||
),
|
||||
Instruction::BranchSccZero { target } => Op::Branch {
|
||||
target,
|
||||
condition: BranchCondition::SccZero,
|
||||
@@ -424,22 +636,32 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
target,
|
||||
condition: BranchCondition::Always,
|
||||
},
|
||||
Instruction::VectorAndB32 { dst, src0, src1 } => {
|
||||
Op::Vector(VectorAlu::And, dst, src0, src1)
|
||||
}
|
||||
Instruction::VectorLshlrevB32 { dst, src0, src1 } => {
|
||||
Op::Vector(VectorAlu::ShiftLeft, dst, src0, src1)
|
||||
}
|
||||
Instruction::VectorAshrrevI32 { dst, src0, src1 } => {
|
||||
Op::Vector(VectorAlu::ArithmeticShiftRight, dst, src0, src1)
|
||||
}
|
||||
Instruction::VectorLshrrevB32 { dst, src0, src1 } => {
|
||||
Op::Vector(VectorAlu::ShiftRight, dst, src0, src1)
|
||||
}
|
||||
Instruction::VectorOrB32 { dst, src0, src1 } => Op::Vector(VectorAlu::Or, dst, src0, src1),
|
||||
Instruction::VectorXorB32 { dst, src0, src1 } => {
|
||||
Op::Vector(VectorAlu::Xor, dst, src0, src1)
|
||||
}
|
||||
// The six logical and shift forms migrated from hand-written code
|
||||
// (#215 M27) keep the reference's VGPR-only VectorAlu ops.
|
||||
Instruction::VectorAlu {
|
||||
op:
|
||||
op @ (VectorAluOp::AndB32
|
||||
| VectorAluOp::OrB32
|
||||
| VectorAluOp::XorB32
|
||||
| VectorAluOp::LshlrevB32
|
||||
| VectorAluOp::LshrrevB32
|
||||
| VectorAluOp::AshrrevI32),
|
||||
dst,
|
||||
src0: VectorSource::Register(src0),
|
||||
src1,
|
||||
} => Op::Vector(
|
||||
match op {
|
||||
VectorAluOp::AndB32 => VectorAlu::And,
|
||||
VectorAluOp::OrB32 => VectorAlu::Or,
|
||||
VectorAluOp::XorB32 => VectorAlu::Xor,
|
||||
VectorAluOp::LshlrevB32 => VectorAlu::ShiftLeft,
|
||||
VectorAluOp::LshrrevB32 => VectorAlu::ShiftRight,
|
||||
_ => VectorAlu::ArithmeticShiftRight,
|
||||
},
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
),
|
||||
Instruction::VectorAddF32 { dst, src0, src1 } => {
|
||||
Op::Vector(VectorAlu::FloatAdd, dst, src0, src1)
|
||||
}
|
||||
@@ -452,23 +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,
|
||||
},
|
||||
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 {
|
||||
@@ -477,20 +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,
|
||||
},
|
||||
reference_vector_integer(op),
|
||||
dst,
|
||||
match src0 {
|
||||
VectorSource::Register(reg) => CompareSource::Vector(reg),
|
||||
@@ -524,14 +739,21 @@ fn compares_fixture_instructions_against_llvm() {
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-compare.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-unary.bin"),
|
||||
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(), 100, "forms compared: {forms:?}");
|
||||
assert_eq!(forms.len(), 169, "forms compared: {forms:?}");
|
||||
eprintln!(
|
||||
"{count} three-way instruction comparisons across {} forms",
|
||||
forms.len()
|
||||
@@ -589,6 +811,12 @@ fn assemble_matrix() -> Vec<u8> {
|
||||
s_or_b32 s103, s3, 0x80000000
|
||||
s_xor_b32 s102, s104, -16
|
||||
s_xor_b32 s7, s7, lit(0x1)
|
||||
s_movk_i32 s105, 0xffff
|
||||
s_movk_i32 s8, 0
|
||||
s_cmovk_i32 s105, 0x8000
|
||||
s_addk_i32 s9, 0x7fff
|
||||
s_addk_i32 s105, 0xffff
|
||||
s_mulk_i32 s8, 0x8001
|
||||
v_mov_b32_e32 v255, s105
|
||||
v_mov_b32_e32 v0, s0
|
||||
v_mov_b32_e32 v128, vcc_lo
|
||||
@@ -596,7 +824,7 @@ fn assemble_matrix() -> Vec<u8> {
|
||||
);
|
||||
// Every supported VOPC form with each source class: VGPR, SGPR, vcc_lo,
|
||||
// inline integers at both ends, inline zero and a literal.
|
||||
for relation in ["lt", "eq", "le", "gt", "ne", "ge"] {
|
||||
for relation in ["f", "lt", "eq", "le", "gt", "ne", "ge", "t"] {
|
||||
for kind in ["i32", "u32"] {
|
||||
for src0 in [
|
||||
"v255",
|
||||
@@ -614,6 +842,15 @@ fn assemble_matrix() -> Vec<u8> {
|
||||
writeln!(assembly, "v_cmp_{relation}_{kind}_e32 vcc_lo, v1, v255").unwrap();
|
||||
}
|
||||
}
|
||||
// Every SOPK compare on the lowest and highest readable SGPR.
|
||||
for relation in ["eq", "lg", "gt", "ge", "lt", "le"] {
|
||||
for kind in ["i32", "u32"] {
|
||||
for register in ["s0", "s7", "s8", "s105"] {
|
||||
writeln!(assembly, "s_cmpk_{relation}_{kind} {register}, 0x8000").unwrap();
|
||||
}
|
||||
writeln!(assembly, "s_cmpk_{relation}_{kind} s9, 0").unwrap();
|
||||
}
|
||||
}
|
||||
for value in -16..=64 {
|
||||
writeln!(assembly, "v_mov_b32_e32 v255, {value}").unwrap();
|
||||
writeln!(assembly, "s_mov_b32 s105, {value}").unwrap();
|
||||
@@ -744,9 +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
|
||||
&[0x7d00_0501], // v_cmp_f_i32_e32
|
||||
&[0x7d0e_0501], // v_cmp_t_i32_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
|
||||
@@ -815,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
|
||||
@@ -823,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),
|
||||
),
|
||||
};
|
||||
@@ -936,14 +1172,16 @@ fn decodes_inline_negative_and_register_sources() {
|
||||
let decoded = decode(Architecture::Gfx1030, &bytes).unwrap();
|
||||
assert_eq!(
|
||||
decoded[0].instruction,
|
||||
Instruction::ScalarMoveB32 {
|
||||
Instruction::ScalarUnary {
|
||||
op: ScalarUnaryOp::MovB32,
|
||||
dst: 10,
|
||||
src: ScalarSource::Immediate(5)
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
decoded[1].instruction,
|
||||
Instruction::ScalarMoveB32 {
|
||||
Instruction::ScalarUnary {
|
||||
op: ScalarUnaryOp::MovB32,
|
||||
dst: 11,
|
||||
src: ScalarSource::Immediate(0xffff_fffd)
|
||||
}
|
||||
@@ -977,7 +1215,8 @@ fn accepts_scalar_destination_105_and_vgpr_zero_add_sources() {
|
||||
let valid = 0xbee9_0380u32.to_le_bytes();
|
||||
assert_eq!(
|
||||
decode(Architecture::Gfx1030, &valid).unwrap()[0].instruction,
|
||||
Instruction::ScalarMoveB32 {
|
||||
Instruction::ScalarUnary {
|
||||
op: ScalarUnaryOp::MovB32,
|
||||
dst: 105,
|
||||
src: ScalarSource::Immediate(0)
|
||||
}
|
||||
@@ -997,7 +1236,8 @@ fn accepts_scalar_destination_105_and_vgpr_zero_add_sources() {
|
||||
let bytes: Vec<_> = words.iter().flat_map(|word| word.to_le_bytes()).collect();
|
||||
assert_eq!(
|
||||
decode(Architecture::Gfx1030, &bytes).unwrap()[0].instruction,
|
||||
Instruction::AddNoCarryU32 {
|
||||
Instruction::VectorAluVop3 {
|
||||
op: VectorAluVop3Op::AddNcU32,
|
||||
dst: 1,
|
||||
src0: 0,
|
||||
src1: 0
|
||||
@@ -1030,3 +1270,224 @@ 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;
|
||||
let decode_word = |word: u32| decode(Architecture::Gfx1030, &word.to_le_bytes());
|
||||
// Words assembled by LLVM for gfx1030 (llvm-mc --show-encoding).
|
||||
// s_movk_i32 s8, 0x8000
|
||||
let decoded = decode_word(0xb008_8000).unwrap();
|
||||
assert_eq!(decoded[0].byte_len, 4);
|
||||
assert_eq!(
|
||||
decoded[0].instruction,
|
||||
Instruction::ScalarImmediate {
|
||||
op: ScalarImmediateOp::MovkI32,
|
||||
dst: 8,
|
||||
simm16: 0x8000
|
||||
}
|
||||
);
|
||||
// s_cmovk_i32 s105, 0xffff keeps the full 16 bits: the sign extension is
|
||||
// the translator's job, not the decoder's.
|
||||
assert_eq!(
|
||||
decode_word(0xb169_ffff).unwrap()[0].instruction,
|
||||
Instruction::ScalarImmediate {
|
||||
op: ScalarImmediateOp::CmovkI32,
|
||||
dst: 105,
|
||||
simm16: 0xffff
|
||||
}
|
||||
);
|
||||
// s_cmpk_gt_u32 s0, 0x1234 and s_cmpk_le_i32 s7, 0xffff read SDST s0-s7.
|
||||
assert_eq!(
|
||||
decode_word(0xb580_1234).unwrap()[0].instruction,
|
||||
Instruction::ScalarImmediateCompare {
|
||||
op: ScalarImmediateCompareOp::CmpkGtU32,
|
||||
src: 0,
|
||||
simm16: 0x1234
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
decode_word(0xb407_ffff).unwrap()[0].instruction,
|
||||
Instruction::ScalarImmediateCompare {
|
||||
op: ScalarImmediateCompareOp::CmpkLeI32,
|
||||
src: 7,
|
||||
simm16: 0xffff
|
||||
}
|
||||
);
|
||||
// s_addk_i32 s9, 0x7fff and s_mulk_i32 s105, 0
|
||||
assert_eq!(
|
||||
decode_word(0xb789_7fff).unwrap()[0].instruction,
|
||||
Instruction::ScalarImmediate {
|
||||
op: ScalarImmediateOp::AddkI32,
|
||||
dst: 9,
|
||||
simm16: 0x7fff
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
decode_word(0xb869_0000).unwrap()[0].instruction,
|
||||
Instruction::ScalarImmediate {
|
||||
op: ScalarImmediateOp::MulkI32,
|
||||
dst: 105,
|
||||
simm16: 0
|
||||
}
|
||||
);
|
||||
// vcc_lo, exec_lo, null and ttmp0 as SDST, and s_cmpk_eq_i32 m0: refused.
|
||||
for (word, mnemonic, detail) in [
|
||||
(
|
||||
0xb06a_0001,
|
||||
"s_movk_i32",
|
||||
"expected a normal SGPR destination",
|
||||
),
|
||||
(
|
||||
0xb07e_0001,
|
||||
"s_movk_i32",
|
||||
"expected a normal SGPR destination",
|
||||
),
|
||||
(
|
||||
0xb07d_0001,
|
||||
"s_movk_i32",
|
||||
"expected a normal SGPR destination",
|
||||
),
|
||||
(
|
||||
0xb06c_0001,
|
||||
"s_movk_i32",
|
||||
"expected a normal SGPR destination",
|
||||
),
|
||||
(
|
||||
0xb1fc_0001,
|
||||
"s_cmpk_eq_i32",
|
||||
"expected a normal SGPR operand",
|
||||
),
|
||||
] {
|
||||
assert_eq!(
|
||||
decode_word(word).unwrap_err().kind,
|
||||
DecodeErrorKind::UnsupportedForm { mnemonic, detail },
|
||||
"{word:#010x}"
|
||||
);
|
||||
}
|
||||
// Other SOPK opcodes (opcode 1 s_version, 17 s_getreg_b32) stay unsupported.
|
||||
for word in [0xb080_0000u32, 0xb888_0000] {
|
||||
assert!(decode_word(word).is_err(), "{word:#010x}");
|
||||
}
|
||||
// The fixed store fence is still the one decoded SOPK word outside the registry.
|
||||
assert_eq!(
|
||||
decode_word(0xbbfd_0000).unwrap()[0].instruction,
|
||||
Instruction::WaitStore
|
||||
);
|
||||
}
|
||||
@@ -28,6 +28,9 @@ enum {
|
||||
XENORA_BUFFER_TOO_SMALL = 7,
|
||||
XENORA_EXECUTION_FAILED = 8,
|
||||
XENORA_INVALID_STATE = 9,
|
||||
XENORA_FILE_NOT_FOUND = 10,
|
||||
XENORA_ACCESS_DENIED = 11,
|
||||
XENORA_IO_ERROR = 12,
|
||||
};
|
||||
|
||||
/* Frame-loop states reported by xenora_session_frame_loop_status. */
|
||||
@@ -56,6 +59,13 @@ typedef struct {
|
||||
uint16_t reserved;
|
||||
} xenora_input_state;
|
||||
|
||||
/* Extended controller snapshot. Trigger values span 0 to 65535. */
|
||||
typedef struct {
|
||||
xenora_input_state state;
|
||||
uint16_t left_trigger;
|
||||
uint16_t right_trigger;
|
||||
} xenora_controller_input;
|
||||
|
||||
#define XENORA_INPUT_NONE 0u
|
||||
#define XENORA_INPUT_RIGHT (1u << 0)
|
||||
#define XENORA_INPUT_LEFT (1u << 1)
|
||||
@@ -113,6 +123,7 @@ xenora_status xenora_session_run_trusted_fixture(
|
||||
xenora_status xenora_session_start_frame_loop(xenora_session session, uint32_t frame_count);
|
||||
xenora_status xenora_session_start_interactive_loop(xenora_session session, uint32_t frame_count);
|
||||
xenora_status xenora_session_send_input(xenora_session session, const xenora_input_state *input);
|
||||
xenora_status xenora_session_send_controller_input(xenora_session session, const xenora_controller_input *input);
|
||||
xenora_status xenora_session_queue_input(xenora_session session, const xenora_input_state *input);
|
||||
xenora_status xenora_session_pause_frame_loop(xenora_session session);
|
||||
xenora_status xenora_session_resume_frame_loop(xenora_session session);
|
||||
@@ -244,6 +255,7 @@ xenora_status xenora_session_audio_init(
|
||||
|
||||
/*
|
||||
* Submit PCM audio bytes into the session audio queue.
|
||||
* byte_count must contain a whole number of interleaved sample frames.
|
||||
*/
|
||||
xenora_status xenora_session_audio_submit(
|
||||
xenora_session session,
|
||||
@@ -253,6 +265,7 @@ xenora_status xenora_session_audio_submit(
|
||||
|
||||
/*
|
||||
* Read PCM audio bytes from the session audio queue.
|
||||
* Only whole frames are returned. Any remaining output bytes are untouched.
|
||||
*/
|
||||
xenora_status xenora_session_audio_read(
|
||||
xenora_session session,
|
||||
@@ -262,7 +275,18 @@ xenora_status xenora_session_audio_read(
|
||||
);
|
||||
|
||||
/*
|
||||
* Query current audio queue status: queued bytes, underruns, total submitted.
|
||||
* Fill one playback block with whole frames, padding a shortfall with silence.
|
||||
* out_source_bytes reports how much PCM was supplied before padding.
|
||||
*/
|
||||
xenora_status xenora_session_audio_render(
|
||||
xenora_session session,
|
||||
uint8_t *out_pcm,
|
||||
uint64_t byte_count,
|
||||
uint64_t *out_source_bytes
|
||||
);
|
||||
|
||||
/*
|
||||
* Query queued bytes, render calls that ran short, and total bytes submitted.
|
||||
*/
|
||||
xenora_status xenora_session_audio_status(
|
||||
xenora_session session,
|
||||
@@ -300,6 +324,8 @@ xenora_status xenora_session_vfs_set_root(
|
||||
|
||||
/*
|
||||
* Open a file within the virtual filesystem sandboxed root.
|
||||
* Missing files return XENORA_FILE_NOT_FOUND. Host permission failures return
|
||||
* XENORA_ACCESS_DENIED. Other host I/O failures return XENORA_IO_ERROR.
|
||||
*/
|
||||
xenora_status xenora_session_vfs_open(
|
||||
xenora_session session,
|
||||
|
||||
@@ -50,6 +50,34 @@ pub struct InputState {
|
||||
pub reserved: u16,
|
||||
}
|
||||
|
||||
#[derive(Default, Copy, Clone)]
|
||||
#[repr(C)]
|
||||
pub struct ControllerInput {
|
||||
pub state: InputState,
|
||||
pub left_trigger: u16,
|
||||
pub right_trigger: u16,
|
||||
}
|
||||
|
||||
impl ControllerInput {
|
||||
fn guest_bytes(self) -> [u8; 20] {
|
||||
let mut bytes = [0; 20];
|
||||
bytes[..4].copy_from_slice(&self.state.buttons.to_le_bytes());
|
||||
for (slot, value) in bytes[4..12].as_chunks_mut::<2>().0.iter_mut().zip([
|
||||
self.state.stick_x,
|
||||
self.state.stick_y,
|
||||
self.state.mouse_dx,
|
||||
self.state.mouse_dy,
|
||||
]) {
|
||||
*slot = value.to_le_bytes();
|
||||
}
|
||||
bytes[12] = self.state.mouse_buttons;
|
||||
bytes[13] = self.state.connected;
|
||||
bytes[16..18].copy_from_slice(&self.left_trigger.to_le_bytes());
|
||||
bytes[18..20].copy_from_slice(&self.right_trigger.to_le_bytes());
|
||||
bytes
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
status: u32,
|
||||
@@ -58,7 +86,7 @@ struct State {
|
||||
interactive: bool,
|
||||
limit: u32,
|
||||
completed: u32,
|
||||
input: InputState,
|
||||
input: ControllerInput,
|
||||
input_queue: std::collections::VecDeque<InputState>,
|
||||
recorded_frames: Vec<(u32, Vec<u8>)>,
|
||||
/// Every `frame_submit` call the guest made, including the one answered with 0.
|
||||
@@ -131,6 +159,13 @@ impl FrameLoop {
|
||||
}
|
||||
|
||||
pub fn send_input(&self, input: InputState) {
|
||||
self.send_controller_input(ControllerInput {
|
||||
state: input,
|
||||
..ControllerInput::default()
|
||||
});
|
||||
}
|
||||
|
||||
pub fn send_controller_input(&self, input: ControllerInput) {
|
||||
let mut state = self.lock();
|
||||
state.input = input;
|
||||
}
|
||||
@@ -187,7 +222,7 @@ impl FrameLoop {
|
||||
let shared_poll = Arc::clone(self);
|
||||
imports.register("xenora.dll", "input_poll", move |_args, _, _memory| {
|
||||
let mut state = shared_poll.lock();
|
||||
let input = state.input_queue.pop_front().unwrap_or(state.input);
|
||||
let input = state.input_queue.pop_front().unwrap_or(state.input.state);
|
||||
let cmd = if input.buttons & crate::XENORA_INPUT_RIGHT != 0 {
|
||||
1u64
|
||||
} else if input.buttons & crate::XENORA_INPUT_LEFT != 0 {
|
||||
@@ -197,6 +232,18 @@ impl FrameLoop {
|
||||
};
|
||||
Ok(cmd)
|
||||
});
|
||||
let snapshot = Arc::clone(self);
|
||||
imports.register(
|
||||
"xenora.dll",
|
||||
"input_poll_snapshot",
|
||||
move |args, _, memory| {
|
||||
let input = snapshot.lock().input;
|
||||
memory
|
||||
.write_bytes(args.rcx, &input.guest_bytes())
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
Ok(1)
|
||||
},
|
||||
);
|
||||
}
|
||||
let limit = self.lock().limit as usize;
|
||||
let is_interactive = self.lock().interactive;
|
||||
@@ -330,3 +377,31 @@ pub fn expected(index: u32) -> Vec<u8> {
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn extended_controller_snapshot_retains_trigger_bytes_and_legacy_input_resets_them() {
|
||||
let running = FrameLoop::default();
|
||||
running.send_controller_input(ControllerInput {
|
||||
state: InputState {
|
||||
buttons: 0x10,
|
||||
stick_x: -32767,
|
||||
stick_y: 9,
|
||||
connected: 1,
|
||||
reserved: u16::MAX,
|
||||
..InputState::default()
|
||||
},
|
||||
left_trigger: 0x1234,
|
||||
right_trigger: u16::MAX,
|
||||
});
|
||||
let bytes = running.lock().input.guest_bytes();
|
||||
assert_eq!(std::mem::size_of::<ControllerInput>(), 20);
|
||||
assert_eq!(
|
||||
bytes,
|
||||
[
|
||||
16, 0, 0, 0, 1, 128, 9, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0x34, 0x12, 255, 255
|
||||
]
|
||||
);
|
||||
running.send_input(InputState::default());
|
||||
assert_eq!(running.lock().input.guest_bytes(), [0; 20]);
|
||||
}
|
||||
+233
-23
@@ -29,6 +29,9 @@ pub const XENORA_LIMIT_EXCEEDED: i32 = 6;
|
||||
pub const XENORA_BUFFER_TOO_SMALL: i32 = 7;
|
||||
pub const XENORA_EXECUTION_FAILED: i32 = 8;
|
||||
pub const XENORA_INVALID_STATE: i32 = 9;
|
||||
pub const XENORA_FILE_NOT_FOUND: i32 = 10;
|
||||
pub const XENORA_ACCESS_DENIED: i32 = 11;
|
||||
pub const XENORA_IO_ERROR: i32 = 12;
|
||||
|
||||
pub const XENORA_LOOP_NONE: u32 = 0;
|
||||
pub const XENORA_LOOP_RUNNING: u32 = frame_loop::RUNNING;
|
||||
@@ -47,6 +50,7 @@ pub const XENORA_INPUT_DOWN: u32 = 1 << 3;
|
||||
pub const XENORA_INPUT_ACTION_A: u32 = 1 << 4;
|
||||
pub const XENORA_INPUT_ACTION_B: u32 = 1 << 5;
|
||||
|
||||
pub use frame_loop::ControllerInput as xenora_controller_input;
|
||||
pub use frame_loop::InputState as xenora_input_state;
|
||||
|
||||
pub const XENORA_FIXTURE_FRAME_WIDTH: u32 = 4;
|
||||
@@ -95,46 +99,73 @@ impl Default for AudioSubsystem {
|
||||
}
|
||||
|
||||
impl AudioSubsystem {
|
||||
fn frame_bytes(&self) -> usize {
|
||||
let sample_bytes = if self.format == XENORA_AUDIO_FORMAT_PCM_F32LE {
|
||||
4
|
||||
} else {
|
||||
2
|
||||
};
|
||||
sample_bytes * self.channels as usize
|
||||
}
|
||||
|
||||
pub fn submit(&mut self, bytes: &[u8]) {
|
||||
self.total_submitted_bytes = self
|
||||
.total_submitted_bytes
|
||||
.saturating_add(bytes.len() as u64);
|
||||
let processed_bytes: Vec<u8> =
|
||||
if self.format == XENORA_AUDIO_FORMAT_PCM_S16LE && bytes.len().is_multiple_of(2) {
|
||||
let mut out = bytes.to_vec();
|
||||
for chunk in out.as_chunks_mut::<2>().0 {
|
||||
let sample = i16::from_le_bytes([chunk[0], chunk[1]]);
|
||||
let attenuated = if self.muted {
|
||||
0i16
|
||||
} else {
|
||||
let scaled = (sample as f32) * self.volume;
|
||||
scaled.clamp(-32768.0, 32767.0) as i16
|
||||
};
|
||||
let res_bytes = attenuated.to_le_bytes();
|
||||
chunk[0] = res_bytes[0];
|
||||
chunk[1] = res_bytes[1];
|
||||
}
|
||||
out
|
||||
} else {
|
||||
bytes.to_vec()
|
||||
};
|
||||
let processed_bytes: Vec<u8> = if self.format == XENORA_AUDIO_FORMAT_PCM_S16LE {
|
||||
let mut out = bytes.to_vec();
|
||||
for chunk in out.as_chunks_mut::<2>().0 {
|
||||
let sample = i16::from_le_bytes([chunk[0], chunk[1]]);
|
||||
let attenuated = if self.muted {
|
||||
0i16
|
||||
} else {
|
||||
let scaled = (sample as f32) * self.volume;
|
||||
scaled.clamp(-32768.0, 32767.0) as i16
|
||||
};
|
||||
let res_bytes = attenuated.to_le_bytes();
|
||||
chunk[0] = res_bytes[0];
|
||||
chunk[1] = res_bytes[1];
|
||||
}
|
||||
out
|
||||
} else {
|
||||
let mut out = bytes.to_vec();
|
||||
for chunk in out.as_chunks_mut::<4>().0 {
|
||||
let sample = f32::from_le_bytes(*chunk);
|
||||
let scaled = if self.muted || !sample.is_finite() {
|
||||
0.0
|
||||
} else {
|
||||
(sample * self.volume).clamp(-1.0, 1.0)
|
||||
};
|
||||
*chunk = scaled.to_le_bytes();
|
||||
}
|
||||
out
|
||||
};
|
||||
|
||||
for b in processed_bytes {
|
||||
if self.queue.len() >= self.max_capacity_bytes {
|
||||
self.queue.pop_front();
|
||||
self.underruns = self.underruns.saturating_add(1);
|
||||
}
|
||||
self.queue.push_back(b);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn read(&mut self, out: &mut [u8]) -> usize {
|
||||
let count = out.len().min(self.queue.len());
|
||||
let usable = out.len().min(self.queue.len());
|
||||
let count = usable - usable % self.frame_bytes();
|
||||
for b in out.iter_mut().take(count) {
|
||||
*b = self.queue.pop_front().unwrap_or(0);
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
fn render(&mut self, out: &mut [u8]) -> usize {
|
||||
let supplied = self.read(out);
|
||||
if supplied < out.len() {
|
||||
out[supplied..].fill(0);
|
||||
self.underruns = self.underruns.saturating_add(1);
|
||||
}
|
||||
supplied
|
||||
}
|
||||
}
|
||||
|
||||
pub const XENORA_NO_FILE: u64 = 0;
|
||||
@@ -401,6 +432,29 @@ pub unsafe extern "C" fn xenora_session_send_input(
|
||||
})
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `input` must be a valid pointer to an initialized `xenora_controller_input`.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn xenora_session_send_controller_input(
|
||||
session: u64,
|
||||
input: *const frame_loop::ControllerInput,
|
||||
) -> i32 {
|
||||
guarded(|| {
|
||||
if input.is_null() {
|
||||
return XENORA_INVALID_ARGUMENT;
|
||||
}
|
||||
let input = unsafe { *input };
|
||||
match session_loop(session) {
|
||||
Ok(Some(running)) => {
|
||||
running.send_controller_input(input);
|
||||
XENORA_OK
|
||||
}
|
||||
Ok(None) => XENORA_INVALID_STATE,
|
||||
Err(status) => status,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `input` must be a valid pointer to an initialized `xenora_input_state`.
|
||||
#[unsafe(no_mangle)]
|
||||
@@ -1334,6 +1388,9 @@ pub unsafe extern "C" fn xenora_session_audio_submit(
|
||||
return XENORA_INVALID_HANDLE;
|
||||
}
|
||||
let slot = &mut slots[split(session).0];
|
||||
if !(byte_count as usize).is_multiple_of(slot.audio.frame_bytes()) {
|
||||
return XENORA_INVALID_ARGUMENT;
|
||||
}
|
||||
// SAFETY: checked non-null and bounded above.
|
||||
let bytes = unsafe { std::slice::from_raw_parts(pcm_bytes, byte_count as usize) };
|
||||
slot.audio.submit(bytes);
|
||||
@@ -1352,7 +1409,7 @@ pub unsafe extern "C" fn xenora_session_audio_read(
|
||||
out_bytes_read: *mut u64,
|
||||
) -> i32 {
|
||||
guarded(|| {
|
||||
if out_pcm.is_null() || out_bytes_read.is_null() {
|
||||
if out_pcm.is_null() || out_bytes_read.is_null() || capacity > isize::MAX as u64 {
|
||||
return XENORA_INVALID_ARGUMENT;
|
||||
}
|
||||
let Ok(mut slots) = SESSIONS.lock() else {
|
||||
@@ -1370,6 +1427,42 @@ pub unsafe extern "C" fn xenora_session_audio_read(
|
||||
})
|
||||
}
|
||||
|
||||
/// Fill an aligned PCM playback block. Missing frames are replaced with silence.
|
||||
///
|
||||
/// # Safety
|
||||
/// `out_pcm` must point to `byte_count` writable bytes and `out_source_bytes`
|
||||
/// must be valid for one aligned `u64` write.
|
||||
#[unsafe(no_mangle)]
|
||||
pub unsafe extern "C" fn xenora_session_audio_render(
|
||||
session: u64,
|
||||
out_pcm: *mut u8,
|
||||
byte_count: u64,
|
||||
out_source_bytes: *mut u64,
|
||||
) -> i32 {
|
||||
guarded(|| {
|
||||
if out_pcm.is_null()
|
||||
|| out_source_bytes.is_null()
|
||||
|| !(1..=256 * 1024).contains(&byte_count)
|
||||
{
|
||||
return XENORA_INVALID_ARGUMENT;
|
||||
}
|
||||
let Ok(mut slots) = SESSIONS.lock() else {
|
||||
return XENORA_INTERNAL_ERROR;
|
||||
};
|
||||
if !is_live(&slots, session) {
|
||||
return XENORA_INVALID_HANDLE;
|
||||
}
|
||||
let audio = &mut slots[split(session).0].audio;
|
||||
if !(byte_count as usize).is_multiple_of(audio.frame_bytes()) {
|
||||
return XENORA_INVALID_ARGUMENT;
|
||||
}
|
||||
let output = unsafe { std::slice::from_raw_parts_mut(out_pcm, byte_count as usize) };
|
||||
let supplied = audio.render(output);
|
||||
unsafe { out_source_bytes.write(supplied as u64) };
|
||||
XENORA_OK
|
||||
})
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// Each output pointer must be non-null and valid for one aligned write.
|
||||
#[unsafe(no_mangle)]
|
||||
@@ -1449,6 +1542,17 @@ pub unsafe extern "C" fn xenora_session_vfs_set_root(
|
||||
})
|
||||
}
|
||||
|
||||
fn vfs_read_status(kind: std::io::ErrorKind) -> i32 {
|
||||
use std::io::ErrorKind;
|
||||
match kind {
|
||||
ErrorKind::NotFound | ErrorKind::NotADirectory => XENORA_FILE_NOT_FOUND,
|
||||
ErrorKind::PermissionDenied => XENORA_ACCESS_DENIED,
|
||||
ErrorKind::InvalidInput | ErrorKind::IsADirectory => XENORA_INVALID_ARGUMENT,
|
||||
ErrorKind::OutOfMemory => XENORA_LIMIT_EXCEEDED,
|
||||
_ => XENORA_IO_ERROR,
|
||||
}
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// `rel_path` must be non-null and point to a valid NUL-terminated C string;
|
||||
/// `out_file` must be non-null and valid for one aligned `u64` write.
|
||||
@@ -1483,7 +1587,7 @@ pub unsafe extern "C" fn xenora_session_vfs_open(
|
||||
|
||||
let data = match std::fs::read(&full_path) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(_) => return XENORA_INVALID_ARGUMENT,
|
||||
Err(error) => return vfs_read_status(error.kind()),
|
||||
};
|
||||
|
||||
let file_idx = match slot.vfs.files.iter().position(|f| f.generation % 2 == 0) {
|
||||
@@ -1976,6 +2080,21 @@ mod tests {
|
||||
(status, sections, entry)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_vfs_read_errors_have_stable_statuses() {
|
||||
use std::io::ErrorKind;
|
||||
for (kind, expected) in [
|
||||
(ErrorKind::NotFound, XENORA_FILE_NOT_FOUND),
|
||||
(ErrorKind::NotADirectory, XENORA_FILE_NOT_FOUND),
|
||||
(ErrorKind::PermissionDenied, XENORA_ACCESS_DENIED),
|
||||
(ErrorKind::IsADirectory, XENORA_INVALID_ARGUMENT),
|
||||
(ErrorKind::OutOfMemory, XENORA_LIMIT_EXCEEDED),
|
||||
(ErrorKind::UnexpectedEof, XENORA_IO_ERROR),
|
||||
] {
|
||||
assert_eq!(vfs_read_status(kind), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_and_rust_constants_agree() {
|
||||
let header = include_str!("../include/xenora.h");
|
||||
@@ -1991,6 +2110,9 @@ mod tests {
|
||||
("XENORA_BUFFER_TOO_SMALL", XENORA_BUFFER_TOO_SMALL),
|
||||
("XENORA_EXECUTION_FAILED", XENORA_EXECUTION_FAILED),
|
||||
("XENORA_INVALID_STATE", XENORA_INVALID_STATE),
|
||||
("XENORA_FILE_NOT_FOUND", XENORA_FILE_NOT_FOUND),
|
||||
("XENORA_ACCESS_DENIED", XENORA_ACCESS_DENIED),
|
||||
("XENORA_IO_ERROR", XENORA_IO_ERROR),
|
||||
("XENORA_LOOP_NONE", XENORA_LOOP_NONE as i32),
|
||||
("XENORA_LOOP_RUNNING", XENORA_LOOP_RUNNING as i32),
|
||||
("XENORA_LOOP_PAUSED", XENORA_LOOP_PAUSED as i32),
|
||||
@@ -2485,6 +2607,94 @@ mod tests {
|
||||
xenora_session_destroy(session);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_render_pads_missing_frames_and_counts_only_render_shortfalls() {
|
||||
let _guard = serial();
|
||||
let session = create();
|
||||
assert_eq!(
|
||||
xenora_session_audio_init(session, 48000, 2, XENORA_AUDIO_FORMAT_PCM_S16LE),
|
||||
XENORA_OK
|
||||
);
|
||||
let frame = [1, 2, 3, 4];
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_audio_submit(session, frame.as_ptr(), 4) },
|
||||
XENORA_OK
|
||||
);
|
||||
let mut output = [0xaa; 8];
|
||||
let mut supplied = 99;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_audio_render(session, output.as_mut_ptr(), 7, &mut supplied) },
|
||||
XENORA_INVALID_ARGUMENT
|
||||
);
|
||||
assert_eq!(output, [0xaa; 8]);
|
||||
assert_eq!(supplied, 99);
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_audio_render(session, output.as_mut_ptr(), 8, &mut supplied) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(supplied, 4);
|
||||
assert_eq!(output, [1, 2, 3, 4, 0, 0, 0, 0]);
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_audio_render(session, output.as_mut_ptr(), 8, &mut supplied) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(supplied, 0);
|
||||
assert_eq!(output, [0; 8]);
|
||||
let overflow = vec![0; 256 * 1024 + 4];
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_audio_submit(session, overflow.as_ptr(), overflow.len() as u64)
|
||||
},
|
||||
XENORA_OK
|
||||
);
|
||||
let (mut queued, mut underruns, mut total) = (0, 0, 0);
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_audio_status(session, &mut queued, &mut underruns, &mut total)
|
||||
},
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(queued, 256 * 1024);
|
||||
assert_eq!(underruns, 2);
|
||||
xenora_session_destroy(session);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn float_pcm_applies_gain_and_preserves_stereo_frame_boundaries() {
|
||||
let _guard = serial();
|
||||
let session = create();
|
||||
assert_eq!(
|
||||
xenora_session_audio_init(session, 48000, 2, XENORA_AUDIO_FORMAT_PCM_F32LE),
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(xenora_session_audio_set_volume(session, 0.5, 0), XENORA_OK);
|
||||
let input: Vec<u8> = [1.0_f32, -0.5, f32::NAN, 4.0]
|
||||
.into_iter()
|
||||
.flat_map(f32::to_le_bytes)
|
||||
.collect();
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_audio_submit(session, input.as_ptr(), 4) },
|
||||
XENORA_INVALID_ARGUMENT
|
||||
);
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_audio_submit(session, input.as_ptr(), 16) },
|
||||
XENORA_OK
|
||||
);
|
||||
let mut output = [0xaa; 9];
|
||||
let mut count = 0;
|
||||
for expected in [[0.5_f32, -0.25], [0.0, 1.0]] {
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_audio_read(session, output.as_mut_ptr(), 9, &mut count) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(count, 8);
|
||||
assert_eq!(&output[..4], &expected[0].to_le_bytes());
|
||||
assert_eq!(&output[4..8], &expected[1].to_le_bytes());
|
||||
assert_eq!(output[8], 0xaa);
|
||||
}
|
||||
xenora_session_destroy(session);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_audio_subsystem_lifecycle_and_volume() {
|
||||
let _guard = serial();
|
||||
|
||||
@@ -180,11 +180,9 @@ fn virtual_filesystem_sandboxing_and_traversal_rejection() {
|
||||
"../../etc/passwd",
|
||||
"/etc/passwd",
|
||||
"sub/../../secret",
|
||||
"asset.bin\0extra",
|
||||
"",
|
||||
] {
|
||||
let bad_c = std::ffi::CString::new(*bad)
|
||||
.unwrap_or_else(|_| std::ffi::CString::new("fallback_bad").unwrap());
|
||||
let bad_c = std::ffi::CString::new(*bad).unwrap();
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_vfs_open(sess, bad_c.as_ptr(), 0, &mut file) },
|
||||
XENORA_INVALID_ARGUMENT,
|
||||
@@ -193,6 +191,13 @@ fn virtual_filesystem_sandboxing_and_traversal_rejection() {
|
||||
);
|
||||
}
|
||||
|
||||
let missing = std::ffi::CString::new("missing-xenora-test-asset.bin").unwrap();
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_vfs_open(sess, missing.as_ptr(), 0, &mut file) },
|
||||
XENORA_FILE_NOT_FOUND
|
||||
);
|
||||
assert_eq!(file, XENORA_NO_FILE);
|
||||
|
||||
// Open existing valid asset
|
||||
let good = std::ffi::CString::new("asset.bin").unwrap();
|
||||
assert_eq!(
|
||||
|
||||
@@ -53,8 +53,10 @@ pub fn get_api_sets_for_canonical(canonical: &str) -> &'static [&'static str] {
|
||||
"api-ms-win-core-debug-l1-1-0.dll",
|
||||
"api-ms-win-core-handle-l1-1-0.dll",
|
||||
"api-ms-win-core-interlocked-l1-1-0.dll",
|
||||
"api-ms-win-core-fibers-l1-1-0.dll",
|
||||
"api-ms-win-core-datetime-l1-1-1.dll",
|
||||
"api-ms-win-core-timezone-l1-1-0.dll",
|
||||
"api-ms-win-core-realtime-l1-1-0.dll",
|
||||
"api-ms-win-core-memory-l1-1-0.dll",
|
||||
],
|
||||
"ucrtbase.dll" => &[
|
||||
|
||||
+254
-231
@@ -33,6 +33,8 @@ pub enum Classification {
|
||||
/// Brief description for the stub comment.
|
||||
note: &'static str,
|
||||
},
|
||||
/// Service supplied by the loader standard registry.
|
||||
StandardService,
|
||||
/// Compiler intrinsic or SEH helper; stub that traps gracefully.
|
||||
RuntimeHelper { note: &'static str },
|
||||
/// Proprietary, platform-only, or requires significant manual engineering.
|
||||
@@ -47,6 +49,7 @@ impl Classification {
|
||||
Self::CrtNative { .. } => "crt-native",
|
||||
Self::CrtWrapper { .. } => "crt-wrapper",
|
||||
Self::Win32Stub { .. } => "win32-stub",
|
||||
Self::StandardService => "standard-service",
|
||||
Self::RuntimeHelper { .. } => "runtime-helper",
|
||||
Self::Manual { .. } => "manual",
|
||||
Self::Unsupported { .. } => "unsupported",
|
||||
@@ -54,7 +57,10 @@ impl Classification {
|
||||
}
|
||||
|
||||
pub fn is_generatable(&self) -> bool {
|
||||
!matches!(self, Self::Manual { .. } | Self::Unsupported { .. })
|
||||
!matches!(
|
||||
self,
|
||||
Self::StandardService | Self::Manual { .. } | Self::Unsupported { .. }
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,6 +77,17 @@ impl SymbolDb {
|
||||
self.entries.get(&key)
|
||||
}
|
||||
|
||||
/// Every classified `(module, symbol)` pair, sorted, with modules in lowercase.
|
||||
pub fn entries(&self) -> Vec<(&str, &str, &Classification)> {
|
||||
let mut entries: Vec<_> = self
|
||||
.entries
|
||||
.iter()
|
||||
.map(|((module, symbol), class)| (module.as_str(), symbol.as_str(), class))
|
||||
.collect();
|
||||
entries.sort_by(|a, b| (a.0, a.1).cmp(&(b.0, b.1)));
|
||||
entries
|
||||
}
|
||||
|
||||
/// Build the built-in database. Every entry here is derived exclusively from
|
||||
/// public Microsoft documentation and ISO/POSIX standards.
|
||||
pub fn builtin() -> Self {
|
||||
@@ -111,10 +128,6 @@ impl SymbolDb {
|
||||
self.ins(module, sym, Classification::Win32Stub { return_zero, note });
|
||||
}
|
||||
|
||||
fn manual(&mut self, module: &str, sym: &str, reason: &'static str) {
|
||||
self.ins(module, sym, Classification::Manual { reason });
|
||||
}
|
||||
|
||||
fn runtime_helper(&mut self, module: &str, sym: &str, note: &'static str) {
|
||||
self.ins(module, sym, Classification::RuntimeHelper { note });
|
||||
}
|
||||
@@ -127,6 +140,11 @@ impl SymbolDb {
|
||||
|
||||
fn populate_crt_math(&mut self) {
|
||||
let m = "api-ms-win-crt-math-l1-1-0.dll";
|
||||
for module in [m, "ucrtbase.dll"] {
|
||||
for symbol in ["sqrt", "sqrtf", "fabs", "fabsf"] {
|
||||
self.ins(module, symbol, Classification::StandardService);
|
||||
}
|
||||
}
|
||||
for (sym, libc) in &[
|
||||
("acos", "acos"),
|
||||
("acosf", "acosf"),
|
||||
@@ -145,8 +163,6 @@ impl SymbolDb {
|
||||
("exp2", "exp2"),
|
||||
("exp2f", "exp2f"),
|
||||
("expf", "expf"),
|
||||
("fabs", "fabs"),
|
||||
("fabsf", "fabsf"),
|
||||
("floor", "floor"),
|
||||
("floorf", "floorf"),
|
||||
("fma", "fma"),
|
||||
@@ -170,8 +186,6 @@ impl SymbolDb {
|
||||
("roundf", "roundf"),
|
||||
("sin", "sin"),
|
||||
("sinf", "sinf"),
|
||||
("sqrt", "sqrt"),
|
||||
("sqrtf", "sqrtf"),
|
||||
("tan", "tan"),
|
||||
("tanf", "tanf"),
|
||||
("trunc", "trunc"),
|
||||
@@ -198,6 +212,14 @@ impl SymbolDb {
|
||||
|
||||
fn populate_crt_string(&mut self) {
|
||||
let m = "api-ms-win-crt-string-l1-1-0.dll";
|
||||
for module in [m, "ucrtbase.dll"] {
|
||||
for symbol in [
|
||||
"strlen", "strnlen", "strcmp", "strncmp", "wcslen", "wcsnlen", "wcscmp", "wcsncmp",
|
||||
"memset", "memcpy", "memmove", "memcmp",
|
||||
] {
|
||||
self.ins(module, symbol, Classification::StandardService);
|
||||
}
|
||||
}
|
||||
for (sym, libc) in &[
|
||||
("isalnum", "isalnum"),
|
||||
("isalpha", "isalpha"),
|
||||
@@ -212,27 +234,17 @@ impl SymbolDb {
|
||||
("tolower", "tolower"),
|
||||
("toupper", "toupper"),
|
||||
("memchr", "memchr"),
|
||||
("memcmp", "memcmp"),
|
||||
("memcpy", "memcpy"),
|
||||
("memmove", "memmove"),
|
||||
("memset", "memset"),
|
||||
("strcat", "strcat"),
|
||||
("strcmp", "strcmp"),
|
||||
("strcpy", "strcpy"),
|
||||
("strcspn", "strcspn"),
|
||||
("strlen", "strlen"),
|
||||
("strncat", "strncat"),
|
||||
("strncmp", "strncmp"),
|
||||
("strncpy", "strncpy"),
|
||||
("strpbrk", "strpbrk"),
|
||||
("strspn", "strspn"),
|
||||
("strstr", "strstr"),
|
||||
("strtok", "strtok"),
|
||||
("wcslen", "wcslen"),
|
||||
("wcscat", "wcscat"),
|
||||
("wcscmp", "wcscmp"),
|
||||
("wcscpy", "wcscpy"),
|
||||
("wcsncmp", "wcsncmp"),
|
||||
("wcsncpy", "wcsncpy"),
|
||||
("wcsstr", "wcsstr"),
|
||||
("wcstok", "wcstok"),
|
||||
@@ -369,9 +381,6 @@ impl SymbolDb {
|
||||
("abort", "abort"),
|
||||
("exit", "exit"),
|
||||
("_exit", "_exit"),
|
||||
("atexit", "atexit"),
|
||||
("bsearch", "bsearch"),
|
||||
("qsort", "qsort"),
|
||||
("rand", "rand"),
|
||||
("srand", "srand"),
|
||||
("atoi", "atoi"),
|
||||
@@ -380,14 +389,11 @@ impl SymbolDb {
|
||||
] {
|
||||
self.crt_native(m, sym, libc, "ISO C runtime — identical ABI on macOS");
|
||||
}
|
||||
self.win32_stub(
|
||||
m,
|
||||
"_errno",
|
||||
false,
|
||||
"Windows errno accessor — returns pointer to thread errno",
|
||||
);
|
||||
self.win32_stub(m, "_get_errno", false, "Windows get_errno");
|
||||
self.win32_stub(m, "_set_errno", false, "Windows set_errno");
|
||||
for module in [m, "ucrtbase.dll"] {
|
||||
for symbol in ["_errno", "_get_errno", "_set_errno"] {
|
||||
self.ins(module, symbol, Classification::StandardService);
|
||||
}
|
||||
}
|
||||
self.win32_stub(m, "_set_app_type", false, "CRT app-type hint — no-op");
|
||||
self.win32_stub(m, "_set_fmode", false, "CRT file mode hint — no-op");
|
||||
self.win32_stub(m, "_set_new_mode", false, "CRT new-mode hint — no-op");
|
||||
@@ -416,31 +422,21 @@ impl SymbolDb {
|
||||
"CRT invalid param abort",
|
||||
);
|
||||
self.win32_stub(m, "_purecall", false, "pure virtual call trap");
|
||||
self.win32_stub(
|
||||
m,
|
||||
"_initterm",
|
||||
false,
|
||||
"CRT ctor table init — no-op for guest image",
|
||||
);
|
||||
self.win32_stub(
|
||||
m,
|
||||
"_initterm_e",
|
||||
false,
|
||||
"CRT ctor table init with error — no-op",
|
||||
);
|
||||
self.win32_stub(
|
||||
m,
|
||||
"_initialize_onexit_table",
|
||||
false,
|
||||
"CRT onexit table init — no-op",
|
||||
);
|
||||
self.win32_stub(
|
||||
m,
|
||||
"_register_onexit_function",
|
||||
false,
|
||||
"CRT onexit register — no-op",
|
||||
);
|
||||
self.win32_stub(m, "_crt_atexit", false, "CRT atexit variant — no-op");
|
||||
// Initializer and exit functions are guest code.
|
||||
for module in [m, "ucrtbase.dll"] {
|
||||
for symbol in [
|
||||
"_initterm",
|
||||
"_initterm_e",
|
||||
"_initialize_onexit_table",
|
||||
"_register_onexit_function",
|
||||
"_execute_onexit_table",
|
||||
"atexit",
|
||||
"_crt_atexit",
|
||||
"_cexit",
|
||||
] {
|
||||
self.ins(module, symbol, Classification::StandardService);
|
||||
}
|
||||
}
|
||||
self.win32_stub(
|
||||
m,
|
||||
"_register_thread_local_exe_atexit_callback",
|
||||
@@ -498,9 +494,10 @@ impl SymbolDb {
|
||||
|
||||
fn populate_crt_heap(&mut self) {
|
||||
let m = "api-ms-win-crt-heap-l1-1-0.dll";
|
||||
// These map to guest VirtualAlloc, not host malloc — Manual
|
||||
for sym in &["malloc", "free", "calloc", "realloc"] {
|
||||
self.manual(m, sym, "Must use guest VirtualAlloc, not host malloc");
|
||||
for module in [m, "ucrtbase.dll"] {
|
||||
for symbol in ["malloc", "free", "calloc", "realloc"] {
|
||||
self.ins(module, symbol, Classification::StandardService);
|
||||
}
|
||||
}
|
||||
self.win32_stub(m, "_set_new_handler", false, "new handler — stub");
|
||||
}
|
||||
@@ -524,35 +521,35 @@ impl SymbolDb {
|
||||
|
||||
fn populate_crt_convert(&mut self) {
|
||||
let m = "api-ms-win-crt-convert-l1-1-0.dll";
|
||||
for module in [m, "ucrtbase.dll"] {
|
||||
for symbol in [
|
||||
"strtol",
|
||||
"strtoul",
|
||||
"wcstol",
|
||||
"wcstoul",
|
||||
"strtoll",
|
||||
"strtoull",
|
||||
"wcstoll",
|
||||
"wcstoull",
|
||||
"_strtoi64",
|
||||
"_strtoui64",
|
||||
"_wcstoi64",
|
||||
"_wcstoui64",
|
||||
] {
|
||||
self.ins(module, symbol, Classification::StandardService);
|
||||
}
|
||||
}
|
||||
for (sym, libc) in &[
|
||||
("strtod", "strtod"),
|
||||
("strtof", "strtof"),
|
||||
("strtol", "strtol"),
|
||||
("strtoul", "strtoul"),
|
||||
("strtoll", "strtoll"),
|
||||
("strtoull", "strtoull"),
|
||||
("mbstowcs", "mbstowcs"),
|
||||
("wcstombs", "wcstombs"),
|
||||
("wcstod", "wcstod"),
|
||||
("wcstol", "wcstol"),
|
||||
("wcstoul", "wcstoul"),
|
||||
("wctob", "wctob"),
|
||||
("btowc", "btowc"),
|
||||
] {
|
||||
self.crt_native(m, sym, libc, "ISO C conversion — identical ABI on macOS");
|
||||
}
|
||||
self.win32_stub(
|
||||
m,
|
||||
"_strtoi64",
|
||||
false,
|
||||
"Windows 64-bit strtoi64 — same as strtoll",
|
||||
);
|
||||
self.win32_stub(
|
||||
m,
|
||||
"_strtoui64",
|
||||
false,
|
||||
"Windows 64-bit strtoui64 — same as strtoull",
|
||||
);
|
||||
self.win32_stub(m, "_itoa", false, "Windows itoa — integer to ASCII");
|
||||
self.win32_stub(m, "_itoa_s", false, "Windows itoa_s — safe variant");
|
||||
self.win32_stub(m, "_wtoi", false, "Wide char to int");
|
||||
@@ -572,8 +569,12 @@ impl SymbolDb {
|
||||
self.crt_native(m, "div", "div", "ISO C div");
|
||||
self.crt_native(m, "ldiv", "ldiv", "ISO C ldiv");
|
||||
self.crt_native(m, "lldiv", "lldiv", "ISO C lldiv");
|
||||
self.crt_native(m, "bsearch", "bsearch", "ISO C bsearch");
|
||||
self.crt_native(m, "qsort", "qsort", "ISO C qsort");
|
||||
// The comparators are guest code, so these cannot use host libc.
|
||||
for module in [m, "ucrtbase.dll"] {
|
||||
for symbol in ["qsort", "qsort_s", "bsearch", "bsearch_s"] {
|
||||
self.ins(module, symbol, Classification::StandardService);
|
||||
}
|
||||
}
|
||||
self.crt_native(m, "rand", "rand", "ISO C rand");
|
||||
self.crt_native(m, "srand", "srand", "ISO C srand");
|
||||
}
|
||||
@@ -673,8 +674,27 @@ impl SymbolDb {
|
||||
// ---- Win32 kernel / process --------------------------------------------
|
||||
|
||||
fn populate_win32_kernel(&mut self) {
|
||||
for module in ["kernel32.dll", "api-ms-win-core-heap-l1-1-0.dll"] {
|
||||
for symbol in [
|
||||
"GetProcessHeap",
|
||||
"HeapAlloc",
|
||||
"HeapReAlloc",
|
||||
"HeapSize",
|
||||
"HeapFree",
|
||||
"HeapCreate",
|
||||
"HeapDestroy",
|
||||
] {
|
||||
self.ins(module, symbol, Classification::StandardService);
|
||||
}
|
||||
}
|
||||
let p1 = "api-ms-win-core-processthreads-l1-1-0.dll";
|
||||
let p2 = "api-ms-win-core-processthreads-l1-1-2.dll";
|
||||
for module in [p1, "kernel32.dll"] {
|
||||
self.ins(module, "GetThreadId", Classification::StandardService);
|
||||
}
|
||||
for module in ["kernel32.dll", "api-ms-win-core-handle-l1-1-0.dll"] {
|
||||
self.ins(module, "DuplicateHandle", Classification::StandardService);
|
||||
}
|
||||
for m in &[p1, p2, "kernel32.dll"] {
|
||||
self.win32_stub(
|
||||
m,
|
||||
@@ -753,75 +773,80 @@ impl SymbolDb {
|
||||
|
||||
fn populate_win32_synch(&mut self) {
|
||||
let m = "api-ms-win-core-synch-l1-1-0.dll";
|
||||
self.win32_stub(
|
||||
m,
|
||||
"WaitForSingleObject",
|
||||
false,
|
||||
"WaitForSingleObject — stub returning WAIT_OBJECT_0",
|
||||
);
|
||||
self.win32_stub(
|
||||
m,
|
||||
"WaitForSingleObjectEx",
|
||||
false,
|
||||
"WaitForSingleObjectEx — stub",
|
||||
);
|
||||
self.win32_stub(
|
||||
m,
|
||||
"CreateEventA",
|
||||
true,
|
||||
"CreateEvent — stub returning fake handle",
|
||||
);
|
||||
self.win32_stub(
|
||||
m,
|
||||
"CreateEventW",
|
||||
true,
|
||||
"CreateEvent wide — stub returning fake handle",
|
||||
);
|
||||
self.win32_stub(m, "SetEvent", false, "SetEvent — no-op stub");
|
||||
self.win32_stub(m, "ResetEvent", false, "ResetEvent — no-op stub");
|
||||
self.win32_stub(m, "CreateMutexA", true, "CreateMutex — stub");
|
||||
self.win32_stub(m, "CreateMutexW", true, "CreateMutex wide — stub");
|
||||
self.win32_stub(m, "ReleaseMutex", false, "ReleaseMutex — stub");
|
||||
for module in [m, "kernel32.dll"] {
|
||||
for symbol in [
|
||||
"CreateEventA",
|
||||
"CreateEventW",
|
||||
"SetEvent",
|
||||
"ResetEvent",
|
||||
"CreateSemaphoreA",
|
||||
"CreateSemaphoreW",
|
||||
"ReleaseSemaphore",
|
||||
"WaitForSingleObject",
|
||||
"WaitForSingleObjectEx",
|
||||
"WaitForMultipleObjects",
|
||||
"WaitForMultipleObjectsEx",
|
||||
"CreateMutexA",
|
||||
"CreateMutexW",
|
||||
"CreateMutexExA",
|
||||
"CreateMutexExW",
|
||||
"ReleaseMutex",
|
||||
"InitializeCriticalSection",
|
||||
"InitializeCriticalSectionAndSpinCount",
|
||||
"InitializeCriticalSectionEx",
|
||||
"EnterCriticalSection",
|
||||
"TryEnterCriticalSection",
|
||||
"LeaveCriticalSection",
|
||||
"DeleteCriticalSection",
|
||||
"SetCriticalSectionSpinCount",
|
||||
"InitializeSRWLock",
|
||||
"AcquireSRWLockExclusive",
|
||||
"AcquireSRWLockShared",
|
||||
"TryAcquireSRWLockExclusive",
|
||||
"TryAcquireSRWLockShared",
|
||||
"ReleaseSRWLockExclusive",
|
||||
"ReleaseSRWLockShared",
|
||||
] {
|
||||
self.ins(module, symbol, Classification::StandardService);
|
||||
}
|
||||
}
|
||||
for module in ["api-ms-win-core-synch-l1-2-0.dll", "kernel32.dll"] {
|
||||
for symbol in [
|
||||
"InitializeConditionVariable",
|
||||
"WakeConditionVariable",
|
||||
"WakeAllConditionVariable",
|
||||
"SleepConditionVariableCS",
|
||||
"SleepConditionVariableSRW",
|
||||
"InitOnceInitialize",
|
||||
"InitOnceBeginInitialize",
|
||||
"InitOnceComplete",
|
||||
"InitOnceExecuteOnce",
|
||||
] {
|
||||
self.ins(module, symbol, Classification::StandardService);
|
||||
}
|
||||
}
|
||||
for module in ["api-ms-win-core-interlocked-l1-1-0.dll", "kernel32.dll"] {
|
||||
for symbol in [
|
||||
"InitializeSListHead",
|
||||
"InterlockedPushEntrySList",
|
||||
"InterlockedPopEntrySList",
|
||||
"InterlockedFlushSList",
|
||||
"QueryDepthSList",
|
||||
] {
|
||||
self.ins(module, symbol, Classification::StandardService);
|
||||
}
|
||||
}
|
||||
for module in ["api-ms-win-core-processthreads-l1-1-0.dll", "kernel32.dll"] {
|
||||
for symbol in ["TlsAlloc", "TlsFree", "TlsGetValue", "TlsSetValue"] {
|
||||
self.ins(module, symbol, Classification::StandardService);
|
||||
}
|
||||
}
|
||||
for module in ["api-ms-win-core-fibers-l1-1-0.dll", "kernel32.dll"] {
|
||||
for symbol in ["FlsAlloc", "FlsFree", "FlsGetValue", "FlsSetValue"] {
|
||||
self.ins(module, symbol, Classification::StandardService);
|
||||
}
|
||||
}
|
||||
self.win32_stub(m, "CloseHandle", false, "CloseHandle — no-op stub");
|
||||
self.win32_stub(
|
||||
m,
|
||||
"InitializeCriticalSection",
|
||||
false,
|
||||
"InitializeCriticalSection — no-op",
|
||||
);
|
||||
self.win32_stub(
|
||||
m,
|
||||
"InitializeCriticalSectionAndSpinCount",
|
||||
false,
|
||||
"CRIT_SECTION with spin — no-op",
|
||||
);
|
||||
self.win32_stub(
|
||||
m,
|
||||
"EnterCriticalSection",
|
||||
false,
|
||||
"EnterCriticalSection — no-op",
|
||||
);
|
||||
self.win32_stub(
|
||||
m,
|
||||
"LeaveCriticalSection",
|
||||
false,
|
||||
"LeaveCriticalSection — no-op",
|
||||
);
|
||||
self.win32_stub(
|
||||
m,
|
||||
"DeleteCriticalSection",
|
||||
false,
|
||||
"DeleteCriticalSection — no-op",
|
||||
);
|
||||
self.win32_stub(
|
||||
m,
|
||||
"TryEnterCriticalSection",
|
||||
false,
|
||||
"TryEnterCriticalSection — returns TRUE",
|
||||
);
|
||||
self.win32_stub(m, "CreateSemaphoreA", true, "CreateSemaphore — stub");
|
||||
self.win32_stub(m, "CreateSemaphoreW", true, "CreateSemaphore wide — stub");
|
||||
self.win32_stub(m, "ReleaseSemaphore", false, "ReleaseSemaphore — stub");
|
||||
self.win32_stub(
|
||||
m,
|
||||
"InterlockedIncrement",
|
||||
@@ -848,25 +873,11 @@ impl SymbolDb {
|
||||
);
|
||||
|
||||
let m2 = "api-ms-win-core-synch-l1-2-1.dll";
|
||||
self.win32_stub(
|
||||
self.ins(
|
||||
m2,
|
||||
"WaitForMultipleObjects",
|
||||
false,
|
||||
"WaitForMultipleObjects — stub returning 0",
|
||||
Classification::StandardService,
|
||||
);
|
||||
self.win32_stub(
|
||||
m2,
|
||||
"WaitForMultipleObjectsEx",
|
||||
false,
|
||||
"WaitForMultipleObjectsEx — stub",
|
||||
);
|
||||
self.win32_stub(
|
||||
m2,
|
||||
"InitOnceExecuteOnce",
|
||||
false,
|
||||
"InitOnce — executes callback directly",
|
||||
);
|
||||
self.win32_stub(m2, "InitOnceInitialize", false, "InitOnce init — no-op");
|
||||
}
|
||||
|
||||
// ---- Win32 library loader ----------------------------------------------
|
||||
@@ -886,19 +897,11 @@ impl SymbolDb {
|
||||
"LoadLibraryW — stub returning null",
|
||||
);
|
||||
self.win32_stub(m, "FreeLibrary", false, "FreeLibrary — no-op stub");
|
||||
self.win32_stub(
|
||||
m,
|
||||
"GetModuleHandleA",
|
||||
false,
|
||||
"GetModuleHandle — stub returning synthetic base",
|
||||
);
|
||||
self.win32_stub(m, "GetModuleHandleW", false, "GetModuleHandleW — stub");
|
||||
self.win32_stub(
|
||||
m,
|
||||
"GetProcAddress",
|
||||
false,
|
||||
"GetProcAddress — stub returning null",
|
||||
);
|
||||
for module in [m, "kernel32.dll"] {
|
||||
for symbol in ["GetModuleHandleA", "GetModuleHandleW", "GetProcAddress"] {
|
||||
self.ins(module, symbol, Classification::StandardService);
|
||||
}
|
||||
}
|
||||
self.win32_stub(
|
||||
m,
|
||||
"GetModuleFileNameA",
|
||||
@@ -916,46 +919,68 @@ impl SymbolDb {
|
||||
// ---- Win32 performance -------------------------------------------------
|
||||
|
||||
fn populate_win32_profile(&mut self) {
|
||||
let m = "api-ms-win-core-profile-l1-1-0.dll";
|
||||
self.win32_stub(
|
||||
m,
|
||||
"QueryPerformanceCounter",
|
||||
false,
|
||||
"QPC — returns host mach_absolute_time",
|
||||
);
|
||||
self.win32_stub(
|
||||
m,
|
||||
"QueryPerformanceFrequency",
|
||||
false,
|
||||
"QPF — returns 10 MHz",
|
||||
);
|
||||
for module in ["kernel32.dll", "api-ms-win-core-profile-l1-1-0.dll"] {
|
||||
for symbol in ["QueryPerformanceCounter", "QueryPerformanceFrequency"] {
|
||||
self.ins(module, symbol, Classification::StandardService);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Win32 system info -------------------------------------------------
|
||||
|
||||
fn populate_win32_sysinfo(&mut self) {
|
||||
let m = "api-ms-win-core-sysinfo-l1-1-0.dll";
|
||||
self.win32_stub(
|
||||
m,
|
||||
"GetSystemTimeAsFileTime",
|
||||
false,
|
||||
"returns current UTC as FILETIME",
|
||||
);
|
||||
self.win32_stub(m, "GetTickCount64", false, "returns uptime in ms as u64");
|
||||
self.win32_stub(m, "GetTickCount", false, "returns uptime in ms as u32");
|
||||
self.win32_stub(
|
||||
m,
|
||||
"GetSystemInfo",
|
||||
false,
|
||||
"fills SYSTEM_INFO with synthetic values",
|
||||
);
|
||||
self.win32_stub(
|
||||
m,
|
||||
"GetLocalTime",
|
||||
false,
|
||||
"fills SYSTEMTIME with host local time",
|
||||
);
|
||||
self.win32_stub(m, "GetSystemTime", false, "fills SYSTEMTIME with host UTC");
|
||||
for (module, symbols) in [
|
||||
(
|
||||
m,
|
||||
&[
|
||||
"GetSystemTimeAsFileTime",
|
||||
"GetTickCount",
|
||||
"GetTickCount64",
|
||||
"GetSystemInfo",
|
||||
"GlobalMemoryStatusEx",
|
||||
"GetSystemTime",
|
||||
"GetLocalTime",
|
||||
][..],
|
||||
),
|
||||
(
|
||||
"api-ms-win-core-sysinfo-l1-2-0.dll",
|
||||
&["GetNativeSystemInfo", "GetSystemTimePreciseAsFileTime"],
|
||||
),
|
||||
(
|
||||
"api-ms-win-core-timezone-l1-1-0.dll",
|
||||
&["FileTimeToSystemTime", "SystemTimeToFileTime"],
|
||||
),
|
||||
(
|
||||
"api-ms-win-core-realtime-l1-1-0.dll",
|
||||
&["QueryUnbiasedInterruptTime"],
|
||||
),
|
||||
("api-ms-win-core-synch-l1-2-0.dll", &["Sleep"]),
|
||||
("api-ms-win-core-synch-l1-1-0.dll", &["SleepEx"]),
|
||||
(
|
||||
"kernel32.dll",
|
||||
&[
|
||||
"GetSystemTimeAsFileTime",
|
||||
"GetTickCount",
|
||||
"GetTickCount64",
|
||||
"GetSystemInfo",
|
||||
"GetNativeSystemInfo",
|
||||
"GlobalMemoryStatusEx",
|
||||
"GetSystemTime",
|
||||
"GetLocalTime",
|
||||
"GetSystemTimePreciseAsFileTime",
|
||||
"FileTimeToSystemTime",
|
||||
"SystemTimeToFileTime",
|
||||
"QueryUnbiasedInterruptTime",
|
||||
"Sleep",
|
||||
"SleepEx",
|
||||
],
|
||||
),
|
||||
] {
|
||||
for symbol in symbols {
|
||||
self.ins(module, symbol, Classification::StandardService);
|
||||
}
|
||||
}
|
||||
self.win32_stub(
|
||||
m,
|
||||
"GetProcessorCount",
|
||||
@@ -974,37 +999,35 @@ impl SymbolDb {
|
||||
false,
|
||||
"CreateFile — stub returning INVALID_HANDLE_VALUE",
|
||||
);
|
||||
self.win32_stub(
|
||||
m,
|
||||
"CreateFileW",
|
||||
false,
|
||||
"CreateFileW — stub returning INVALID_HANDLE_VALUE",
|
||||
);
|
||||
self.win32_stub(m, "ReadFile", false, "ReadFile — stub returning FALSE");
|
||||
self.win32_stub(m, "WriteFile", false, "WriteFile — stub returning FALSE");
|
||||
for module in [m, "kernel32.dll"] {
|
||||
for symbol in [
|
||||
"CreateFileW",
|
||||
"ReadFile",
|
||||
"WriteFile",
|
||||
"GetFileSizeEx",
|
||||
"SetFilePointerEx",
|
||||
"SetEndOfFile",
|
||||
"CreateDirectoryW",
|
||||
"RemoveDirectoryW",
|
||||
"DeleteFileW",
|
||||
"GetFileAttributesW",
|
||||
"MoveFileW",
|
||||
"FindFirstFileW",
|
||||
"FindNextFileW",
|
||||
"FindClose",
|
||||
] {
|
||||
self.ins(module, symbol, Classification::StandardService);
|
||||
}
|
||||
}
|
||||
self.win32_stub(m, "CloseHandle", false, "CloseHandle — no-op stub");
|
||||
self.win32_stub(m, "GetFileSize", false, "GetFileSize — stub returning 0");
|
||||
self.win32_stub(
|
||||
m,
|
||||
"GetFileSizeEx",
|
||||
false,
|
||||
"GetFileSizeEx — stub returning 0",
|
||||
);
|
||||
self.win32_stub(m, "SetFilePointerEx", false, "SetFilePointerEx — stub");
|
||||
self.win32_stub(
|
||||
m,
|
||||
"GetFileAttributesA",
|
||||
false,
|
||||
"GetFileAttributes — stub returning INVALID",
|
||||
);
|
||||
self.win32_stub(m, "GetFileAttributesW", false, "GetFileAttributesW — stub");
|
||||
self.win32_stub(m, "DeleteFileA", false, "DeleteFile — stub returning FALSE");
|
||||
self.win32_stub(
|
||||
m,
|
||||
"DeleteFileW",
|
||||
false,
|
||||
"DeleteFileW — stub returning FALSE",
|
||||
);
|
||||
self.win32_stub(
|
||||
m,
|
||||
"FlushFileBuffers",
|
||||
|
||||
@@ -40,6 +40,14 @@ fn write_file(dir: &str, name: &str, content: &str) -> Result<(), String> {
|
||||
std::fs::write(&path, content).map_err(|e| format!("write {path}: {e}"))
|
||||
}
|
||||
|
||||
fn unique_entries(manifest: &Manifest) -> impl Iterator<Item = &crate::manifest::ManifestEntry> {
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
manifest
|
||||
.entries
|
||||
.iter()
|
||||
.filter(move |entry| seen.insert(entry.key()))
|
||||
}
|
||||
|
||||
/// Generate all files from the manifest.
|
||||
pub fn generate(manifest: &Manifest, _db: &SymbolDb) -> GeneratedFiles {
|
||||
let crt_rs = gen_crt(manifest);
|
||||
@@ -81,7 +89,7 @@ pub fn register_generated_crt_services(registry: &mut ImportRegistry) {
|
||||
"#,
|
||||
);
|
||||
|
||||
for entry in manifest.entries.iter() {
|
||||
for entry in unique_entries(manifest) {
|
||||
match &entry.classification {
|
||||
Classification::CrtNative { libc_sym, note } => {
|
||||
out.push_str(&gen_crt_native_registration(
|
||||
@@ -119,9 +127,15 @@ pub fn register_generated_crt_services(registry: &mut ImportRegistry) {
|
||||
|
||||
/// Generate a registration block for a CrtNative symbol.
|
||||
/// These use a simple `Win64Args` → libc dispatch pattern.
|
||||
fn gen_crt_native_registration(module: &str, symbol: &str, libc_sym: &str, note: &str) -> String {
|
||||
fn gen_crt_native_registration(module: &str, symbol: &str, _libc_sym: &str, note: &str) -> String {
|
||||
// Determine the calling pattern based on symbol name
|
||||
let dispatch = crt_dispatch_expr(symbol, libc_sym);
|
||||
let (status, dispatch) = match crt_dispatch_expr(symbol) {
|
||||
Some(dispatch) => ("Partial", dispatch),
|
||||
None => (
|
||||
"Stub",
|
||||
"Err(ExitReason::IllegalInstruction(0xFE))".to_owned(),
|
||||
),
|
||||
};
|
||||
|
||||
format!(
|
||||
r#"
|
||||
@@ -129,8 +143,8 @@ fn gen_crt_native_registration(module: &str, symbol: &str, libc_sym: &str, note:
|
||||
// Source: ISO C / POSIX public specification.
|
||||
registry.register_with_status(
|
||||
"{module}", "{symbol}",
|
||||
ServiceStatus::Partial, // upgraded to Implemented when conformance test passes
|
||||
|args: &Win64Args, cpu: &mut CpuState, mem: &mut GuestMemory| -> Result<u64, ExitReason> {{
|
||||
ServiceStatus::{status},
|
||||
|args: &Win64Args, _cpu: &mut CpuState, mem: &mut GuestMemory| -> Result<u64, ExitReason> {{
|
||||
{dispatch}
|
||||
}},
|
||||
);
|
||||
@@ -151,8 +165,7 @@ fn gen_crt_wrapper_registration(module: &str, symbol: &str, _libc_sym: &str, not
|
||||
"{module}", "{symbol}",
|
||||
ServiceStatus::Stub,
|
||||
|args: &Win64Args, _cpu: &mut CpuState, mem: &mut GuestMemory| -> Result<u64, ExitReason> {{
|
||||
// Not implemented: fails explicitly instead of reporting success.
|
||||
Err(ExitReason::IllegalInstruction(0xFE)) // 0xFE = Unsupported Host Service Call
|
||||
Err(ExitReason::IllegalInstruction(0xFE))
|
||||
}},
|
||||
);
|
||||
"#,
|
||||
@@ -199,7 +212,7 @@ pub fn register_generated_stubs(registry: &mut ImportRegistry) {
|
||||
"#,
|
||||
);
|
||||
|
||||
for entry in manifest.entries.iter() {
|
||||
for entry in unique_entries(manifest) {
|
||||
if let Classification::Win32Stub { note, .. } = &entry.classification {
|
||||
out.push_str(&format!(
|
||||
r#"
|
||||
@@ -232,71 +245,65 @@ fn gen_tests(manifest: &Manifest) -> String {
|
||||
let mut out = file_header("generated_tests.rs");
|
||||
out.push_str(
|
||||
r#"
|
||||
//! Auto-generated conformance tests for CRT bindings.
|
||||
//! Each test verifies that the generated service handler returns a correct value
|
||||
//! for a canonical input against a known-good expected output.
|
||||
//! Do not edit manually — regenerate with `xenora imports generate`.
|
||||
//!
|
||||
//! Run with: cargo test -p xenora-loader --test generated
|
||||
//! Conformance tests for emitted service registrations.
|
||||
//! Place this file and the two generated registration files together as
|
||||
//! an integration test in a Cargo package that depends on xenora-loader.
|
||||
|
||||
use xenora_loader::imports::{ImportRegistry, Win64Args};
|
||||
use xenora_loader::cpu::CpuState;
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
use xenora_loader::services::register_standard_services;
|
||||
pub use xenora_loader::{cpu, imports, memory};
|
||||
|
||||
/// Build a minimal test registry with generated bindings loaded.
|
||||
fn test_registry() -> ImportRegistry {
|
||||
let mut reg = ImportRegistry::new();
|
||||
let clock = std::sync::Arc::new(xenora_loader::services::SystemClock);
|
||||
let state = std::sync::Arc::new(xenora_loader::services::ServicesState::new(clock));
|
||||
register_standard_services(&mut reg, state);
|
||||
// Generated registrations would be loaded here in integration.
|
||||
reg
|
||||
#[path = "generated_crt.rs"]
|
||||
mod generated_crt;
|
||||
#[path = "generated_stubs.rs"]
|
||||
mod generated_stubs;
|
||||
|
||||
use cpu::{CpuState, ExitReason};
|
||||
use imports::{ImportRegistry, ServiceStatus, Win64Args};
|
||||
use memory::GuestMemory;
|
||||
|
||||
fn check(module: &str, symbol: &str, input: u64, status: ServiceStatus, expected: Result<u64, ExitReason>) {
|
||||
let mut registry = ImportRegistry::new();
|
||||
generated_crt::register_generated_crt_services(&mut registry);
|
||||
generated_stubs::register_generated_stubs(&mut registry);
|
||||
let service = registry.binding(module, symbol).expect("generated binding");
|
||||
assert_eq!(service.status, status);
|
||||
let args = Win64Args { rcx: input, rdx: 0, r8: 0, r9: 0, rsp: 0x8000 };
|
||||
let mut cpu = CpuState::new(0x1000, 0x8000);
|
||||
let mut memory = GuestMemory::new();
|
||||
assert_eq!((service.handler)(&args, &mut cpu, &mut memory), expected);
|
||||
}
|
||||
|
||||
fn fresh_state() -> (CpuState, GuestMemory) {
|
||||
let cpu = CpuState::new(0x1000, 0x8000);
|
||||
let mut mem = GuestMemory::new();
|
||||
mem.map_region(0x1000, 0x20000, MemoryPermissions::READ_WRITE_EXECUTE)
|
||||
.expect("map test region");
|
||||
(cpu, mem)
|
||||
}
|
||||
|
||||
"#,
|
||||
);
|
||||
|
||||
// Generate a test per CrtNative entry that has a testable canonical case
|
||||
for entry in manifest.entries.iter() {
|
||||
if let Classification::CrtNative { libc_sym, .. } = &entry.classification
|
||||
&& let Some(test) = canonical_test(&entry.symbol, libc_sym)
|
||||
{
|
||||
out.push_str(&format!(
|
||||
r#"
|
||||
for (index, entry) in unique_entries(manifest).enumerate() {
|
||||
let (input, status, expected) = match &entry.classification {
|
||||
Classification::CrtNative { .. } if crt_dispatch_expr(&entry.symbol).is_some() => {
|
||||
let Some((input, expected)) = canonical_integer_case(&entry.symbol) else {
|
||||
continue;
|
||||
};
|
||||
(input, "Partial", format!("Ok({expected})"))
|
||||
}
|
||||
Classification::CrtNative { .. }
|
||||
| Classification::CrtWrapper { .. }
|
||||
| Classification::RuntimeHelper { .. }
|
||||
| Classification::Win32Stub { .. } => (
|
||||
0,
|
||||
"Stub",
|
||||
"Err(ExitReason::IllegalInstruction(0xFE))".to_owned(),
|
||||
),
|
||||
_ => continue,
|
||||
};
|
||||
out.push_str(&format!(
|
||||
r#"
|
||||
#[test]
|
||||
fn generated_test_{fn_name}() {{
|
||||
{test}
|
||||
fn generated_test_{name}_{index}() {{
|
||||
check({module:?}, {symbol:?}, {input}, ServiceStatus::{status}, {expected});
|
||||
}}
|
||||
"#,
|
||||
fn_name = symbol_to_ident_lower(&entry.symbol),
|
||||
test = test,
|
||||
));
|
||||
}
|
||||
name = symbol_to_ident_lower(&entry.symbol),
|
||||
module = entry.module,
|
||||
symbol = entry.symbol,
|
||||
));
|
||||
}
|
||||
|
||||
// Test that every generated stub is registered and returns without error
|
||||
out.push_str(
|
||||
r#"
|
||||
#[test]
|
||||
fn generated_stubs_are_all_registered() {
|
||||
// Verify that the manifest-driven registration functions compile and
|
||||
// that every generated stub returns Ok without panicking.
|
||||
// This test validates the generated source compiles; individual stubs
|
||||
// are tested separately when they have known-good canonical inputs.
|
||||
let _ = test_registry();
|
||||
}
|
||||
"#,
|
||||
);
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
@@ -331,151 +338,9 @@ fn symbol_to_ident_lower(sym: &str) -> String {
|
||||
symbol_to_ident(sym).to_ascii_lowercase()
|
||||
}
|
||||
|
||||
/// Returns the Rust dispatch expression body for a CRT native call.
|
||||
/// We call libc via `unsafe` FFI. Guest pointers are read as raw u64 addresses;
|
||||
/// we do NOT dereference them in the generated code — that is left to the
|
||||
/// existing memory-safe service dispatch infrastructure.
|
||||
fn crt_dispatch_expr(symbol: &str, libc_sym: &str) -> String {
|
||||
// Categorise by calling pattern
|
||||
match symbol {
|
||||
// Math f64 → f64, single arg
|
||||
"acos" | "asin" | "atan" | "cos" | "sin" | "tan" | "exp" | "log" | "log10" | "log2"
|
||||
| "sqrt" | "fabs" | "floor" | "ceil" | "round" | "trunc" | "exp2" => {
|
||||
format!(
|
||||
r#"let x = f64::from_bits(cpu.xmm[0] as u64);
|
||||
extern "C" {{ fn {libc_sym}(x: f64) -> f64; }}
|
||||
let r = unsafe {{ {libc_sym}(x) }};
|
||||
cpu.xmm[0] = u128::from(r.to_bits());
|
||||
Ok(0)"#,
|
||||
libc_sym = libc_sym,
|
||||
)
|
||||
}
|
||||
// Math f32 → f32, single arg
|
||||
"acosf" | "asinf" | "atanf" | "cosf" | "sinf" | "tanf" | "expf" | "logf" | "log10f"
|
||||
| "log2f" | "sqrtf" | "fabsf" | "floorf" | "ceilf" | "roundf" | "truncf" | "cbrtf"
|
||||
| "erff" | "exp2f" => {
|
||||
format!(
|
||||
r#"let x = f32::from_bits(cpu.xmm[0] as u32);
|
||||
extern "C" {{ fn {libc_sym}(x: f32) -> f32; }}
|
||||
let r = unsafe {{ {libc_sym}(x) }};
|
||||
cpu.xmm[0] = u128::from(r.to_bits());
|
||||
Ok(0)"#,
|
||||
libc_sym = libc_sym,
|
||||
)
|
||||
}
|
||||
// Math f64 × f64 → f64, two args
|
||||
"atan2" | "pow" | "fmod" | "hypot" | "fmax" | "fmin" | "copysign" => {
|
||||
format!(
|
||||
r#"let x = f64::from_bits(cpu.xmm[0] as u64);
|
||||
let y = f64::from_bits(cpu.xmm[1] as u64);
|
||||
extern "C" {{ fn {libc_sym}(x: f64, y: f64) -> f64; }}
|
||||
let r = unsafe {{ {libc_sym}(x, y) }};
|
||||
cpu.xmm[0] = u128::from(r.to_bits());
|
||||
Ok(0)"#,
|
||||
libc_sym = libc_sym,
|
||||
)
|
||||
}
|
||||
// Math f32 × f32 → f32
|
||||
"atan2f" | "powf" | "fmodf" | "hypotf" | "fmaxf" | "fminf" | "copysignf" => {
|
||||
format!(
|
||||
r#"let x = f32::from_bits(cpu.xmm[0] as u32);
|
||||
let y = f32::from_bits(cpu.xmm[1] as u32);
|
||||
extern "C" {{ fn {libc_sym}(x: f32, y: f32) -> f32; }}
|
||||
let r = unsafe {{ {libc_sym}(x, y) }};
|
||||
cpu.xmm[0] = u128::from(r.to_bits());
|
||||
Ok(0)"#,
|
||||
libc_sym = libc_sym,
|
||||
)
|
||||
}
|
||||
// Math f64 × f64 × f64 → f64 (fma)
|
||||
"fma" => r#"let x = f64::from_bits(cpu.xmm[0] as u64);
|
||||
let y = f64::from_bits(cpu.xmm[1] as u64);
|
||||
let z = f64::from_bits(cpu.xmm[2] as u64);
|
||||
extern "C" { fn fma(x: f64, y: f64, z: f64) -> f64; }
|
||||
let r = unsafe { fma(x, y, z) };
|
||||
cpu.xmm[0] = u128::from(r.to_bits());
|
||||
Ok(0)"#
|
||||
.to_string(),
|
||||
"fmaf" => r#"let x = f32::from_bits(cpu.xmm[0] as u32);
|
||||
let y = f32::from_bits(cpu.xmm[1] as u32);
|
||||
let z = f32::from_bits(cpu.xmm[2] as u32);
|
||||
extern "C" { fn fmaf(x: f32, y: f32, z: f32) -> f32; }
|
||||
let r = unsafe { fmaf(x, y, z) };
|
||||
cpu.xmm[0] = u128::from(r.to_bits());
|
||||
Ok(0)"#
|
||||
.to_string(),
|
||||
// strlen(ptr) -> size_t
|
||||
"strlen" => r#"// strlen: RCX = guest pointer to null-terminated string
|
||||
let ptr = args.rcx;
|
||||
if ptr == 0 { return Ok(0); }
|
||||
let mut len: u64 = 0;
|
||||
loop {
|
||||
let b = mem.read_u8(ptr + len).map_err(ExitReason::MemoryFault)?;
|
||||
if b == 0 { break; }
|
||||
len += 1;
|
||||
if len > 1_048_576 { break; } // safety cap 1 MiB
|
||||
}
|
||||
Ok(len)"#
|
||||
.to_string(),
|
||||
// memset(dst, val, count) -> dst
|
||||
"memset" => r#"let dst = args.rcx;
|
||||
let val = (args.rdx & 0xFF) as u8;
|
||||
let count = args.r8 as usize;
|
||||
for i in 0..count as u64 {
|
||||
mem.write_u8(dst + i, val).map_err(ExitReason::MemoryFault)?;
|
||||
}
|
||||
Ok(dst)"#
|
||||
.to_string(),
|
||||
// memcpy(dst, src, n) -> dst
|
||||
"memcpy" | "memmove" => r#"let dst = args.rcx;
|
||||
let src = args.rdx;
|
||||
let n = args.r8 as usize;
|
||||
let mut buf = vec![0u8; n];
|
||||
for (i, slot) in buf.iter_mut().enumerate() {
|
||||
*slot = mem.read_u8(src + i as u64).map_err(ExitReason::MemoryFault)?;
|
||||
}
|
||||
for (i, &b) in buf.iter().enumerate() {
|
||||
mem.write_u8(dst + i as u64, b).map_err(ExitReason::MemoryFault)?;
|
||||
}
|
||||
Ok(dst)"#
|
||||
.to_string(),
|
||||
// memcmp(a, b, n) -> int
|
||||
"memcmp" => r#"let a = args.rcx;
|
||||
let b = args.rdx;
|
||||
let n = args.r8 as usize;
|
||||
for i in 0..n as u64 {
|
||||
let ba = mem.read_u8(a + i).map_err(ExitReason::MemoryFault)?;
|
||||
let bb = mem.read_u8(b + i).map_err(ExitReason::MemoryFault)?;
|
||||
if ba != bb {
|
||||
return Ok((ba as i64 - bb as i64) as u64);
|
||||
}
|
||||
}
|
||||
Ok(0)"#
|
||||
.to_string(),
|
||||
// strcmp(a, b) -> int
|
||||
"strcmp" => r#"let a = args.rcx;
|
||||
let b = args.rdx;
|
||||
let mut i = 0u64;
|
||||
loop {
|
||||
let ca = mem.read_u8(a + i).map_err(ExitReason::MemoryFault)?;
|
||||
let cb = mem.read_u8(b + i).map_err(ExitReason::MemoryFault)?;
|
||||
if ca != cb { return Ok((ca as i64 - cb as i64) as u64); }
|
||||
if ca == 0 { return Ok(0); }
|
||||
i += 1;
|
||||
}"#
|
||||
.to_string(),
|
||||
// strncmp(a, b, n) -> int
|
||||
"strncmp" => r#"let a = args.rcx;
|
||||
let b = args.rdx;
|
||||
let n = args.r8 as usize;
|
||||
for i in 0..n as u64 {
|
||||
let ca = mem.read_u8(a + i).map_err(ExitReason::MemoryFault)?;
|
||||
let cb = mem.read_u8(b + i).map_err(ExitReason::MemoryFault)?;
|
||||
if ca != cb { return Ok((ca as i64 - cb as i64) as u64); }
|
||||
if ca == 0 { return Ok(0); }
|
||||
}
|
||||
Ok(0)"#
|
||||
.to_string(),
|
||||
/// Returns a dispatch body for CRT calls with a compatible guest ABI adapter.
|
||||
pub(crate) fn crt_dispatch_expr(symbol: &str) -> Option<String> {
|
||||
Some(match symbol {
|
||||
// abs(int) -> int
|
||||
"abs" | "labs" => r#"let x = args.rcx as i32;
|
||||
Ok(x.abs() as u64)"#
|
||||
@@ -511,240 +376,24 @@ fn crt_dispatch_expr(symbol: &str, libc_sym: &str) -> String {
|
||||
"toupper" => r#"let c = (args.rcx & 0xFF) as u8;
|
||||
Ok(c.to_ascii_uppercase() as u64)"#
|
||||
.to_string(),
|
||||
// localeconv — return NULL (no locale support in guest)
|
||||
"localeconv" => "Ok(0)".to_string(),
|
||||
// strftime — stub returning 0
|
||||
"strftime" => "Ok(0)".to_string(),
|
||||
// Generic: return 0 as a safe default
|
||||
_ => format!(
|
||||
"// No specific dispatch for '{symbol}' — safe default\n Ok(0)",
|
||||
symbol = symbol,
|
||||
),
|
||||
}
|
||||
// Floating-point CRT calls also land here until XMM state is available.
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns a Rust test body for symbols where we can derive a known-good expected value.
|
||||
fn canonical_test(symbol: &str, _libc_sym: &str) -> Option<String> {
|
||||
match symbol {
|
||||
"strlen" => Some(
|
||||
r#"
|
||||
let (_cpu, mut mem) = fresh_state();
|
||||
// Write "hello\0" at 0x2000 (already mapped by fresh_state)
|
||||
for (i, b) in b"hello\0".iter().enumerate() {
|
||||
mem.write_u8(0x2000 + i as u64, *b).unwrap();
|
||||
}
|
||||
let _args = Win64Args { rcx: 0x2000, rdx: 0, r8: 0, r9: 0, rsp: 0x8000 };
|
||||
// strlen should return 5
|
||||
// (This test validates the generated dispatch body compiles and executes correctly.)
|
||||
let result = {
|
||||
let mut len: u64 = 0;
|
||||
loop {
|
||||
let b = mem.read_u8(0x2000 + len).unwrap();
|
||||
if b == 0 { break; }
|
||||
len += 1;
|
||||
}
|
||||
len
|
||||
};
|
||||
assert_eq!(result, 5, "strlen('hello') == 5");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"memset" => Some(
|
||||
r#"
|
||||
let (_cpu, mut mem) = fresh_state();
|
||||
for i in 0..8u64 {
|
||||
mem.write_u8(0x3000 + i, 0xAA).unwrap();
|
||||
}
|
||||
// memset(0x3000, 0xBB, 4)
|
||||
let val: u8 = 0xBB;
|
||||
for i in 0..4u64 {
|
||||
mem.write_u8(0x3000 + i, val).unwrap();
|
||||
}
|
||||
for i in 0..4u64 {
|
||||
assert_eq!(mem.read_u8(0x3000 + i).unwrap(), 0xBB, "memset byte {i}");
|
||||
}
|
||||
// bytes 4..8 should still be 0xAA
|
||||
for i in 4..8u64 {
|
||||
assert_eq!(mem.read_u8(0x3000 + i).unwrap(), 0xAA, "memset preserved byte {i}");
|
||||
}
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"memcmp" => Some(
|
||||
r#"
|
||||
let (_cpu, mut mem) = fresh_state();
|
||||
for (i, b) in b"ABCDE".iter().enumerate() {
|
||||
mem.write_u8(0x4000 + i as u64, *b).unwrap();
|
||||
mem.write_u8(0x4100 + i as u64, *b).unwrap();
|
||||
}
|
||||
// memcmp equal regions
|
||||
let mut result = 0i64;
|
||||
for i in 0..5u64 {
|
||||
let ba = mem.read_u8(0x4000 + i).unwrap();
|
||||
let bb = mem.read_u8(0x4100 + i).unwrap();
|
||||
if ba != bb { result = ba as i64 - bb as i64; break; }
|
||||
}
|
||||
assert_eq!(result, 0, "memcmp equal regions");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"strcmp" => Some(
|
||||
r#"
|
||||
let (_cpu, mut mem) = fresh_state();
|
||||
for (i, b) in b"hello\0".iter().enumerate() {
|
||||
mem.write_u8(0x5000 + i as u64, *b).unwrap();
|
||||
mem.write_u8(0x5100 + i as u64, *b).unwrap();
|
||||
}
|
||||
let mut i = 0u64;
|
||||
let result = loop {
|
||||
let ca = mem.read_u8(0x5000 + i).unwrap();
|
||||
let cb = mem.read_u8(0x5100 + i).unwrap();
|
||||
if ca != cb { break (ca as i64 - cb as i64) as u64; }
|
||||
if ca == 0 { break 0; }
|
||||
i += 1;
|
||||
};
|
||||
assert_eq!(result, 0, "strcmp equal strings");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
// Math tests using known values
|
||||
"sqrt" => Some(
|
||||
r#"
|
||||
// sqrt(4.0) == 2.0 — basic sanity check
|
||||
let x: f64 = 4.0;
|
||||
let result = x.sqrt();
|
||||
assert!((result - 2.0).abs() < 1e-10, "sqrt(4.0) = {result}");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"sqrtf" => Some(
|
||||
r#"
|
||||
let x: f32 = 9.0;
|
||||
let result = x.sqrt();
|
||||
assert!((result - 3.0).abs() < 1e-6, "sqrtf(9.0) = {result}");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"fabs" => Some(
|
||||
r#"
|
||||
let x: f64 = -3.14;
|
||||
let result = x.abs();
|
||||
assert!((result - 3.14).abs() < 1e-10, "fabs(-3.14) = {result}");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"fabsf" => Some(
|
||||
r#"
|
||||
let x: f32 = -2.5;
|
||||
let result = x.abs();
|
||||
assert!((result - 2.5f32).abs() < 1e-6, "fabsf(-2.5) = {result}");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"isalpha" => Some(
|
||||
r#"
|
||||
let result_a = b'A'.is_ascii_alphabetic();
|
||||
let result_1 = b'1'.is_ascii_alphabetic();
|
||||
assert!(result_a, "isalpha('A') should be true");
|
||||
assert!(!result_1, "isalpha('1') should be false");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"isdigit" => Some(
|
||||
r#"
|
||||
assert!(b'5'.is_ascii_digit(), "isdigit('5') should be true");
|
||||
assert!(!b'x'.is_ascii_digit(), "isdigit('x') should be false");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"abs" => Some(
|
||||
r#"
|
||||
let x: i32 = -42;
|
||||
assert_eq!(x.abs(), 42, "abs(-42) == 42");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"llabs" => Some(
|
||||
r#"
|
||||
let x: i64 = -9_000_000_000;
|
||||
assert_eq!(x.unsigned_abs(), 9_000_000_000u64, "llabs(-9e9) == 9e9");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"cos" => Some(
|
||||
r#"
|
||||
let result = (0.0f64).cos();
|
||||
assert!((result - 1.0).abs() < 1e-10, "cos(0.0) = {result}");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"cosf" => Some(
|
||||
r#"
|
||||
let result = (0.0f32).cos();
|
||||
assert!((result - 1.0).abs() < 1e-6, "cosf(0.0) = {result}");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"sin" => Some(
|
||||
r#"
|
||||
let result = (0.0f64).sin();
|
||||
assert!(result.abs() < 1e-10, "sin(0.0) = {result}");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"sinf" => Some(
|
||||
r#"
|
||||
let result = (0.0f32).sin();
|
||||
assert!(result.abs() < 1e-6, "sinf(0.0) = {result}");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"floor" => Some(
|
||||
r#"
|
||||
let result = (3.7f64).floor();
|
||||
assert_eq!(result, 3.0, "floor(3.7) = {result}");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"ceil" => Some(
|
||||
r#"
|
||||
let result = (3.2f64).ceil();
|
||||
assert_eq!(result, 4.0, "ceil(3.2) = {result}");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"strncmp" => Some(
|
||||
r#"
|
||||
let (_cpu, mut mem) = fresh_state();
|
||||
for (i, b) in b"hello world\0".iter().enumerate() {
|
||||
mem.write_u8(0x6000 + i as u64, *b).unwrap();
|
||||
mem.write_u8(0x6100 + i as u64, *b).unwrap();
|
||||
}
|
||||
let n = 5usize;
|
||||
let mut diff = 0i64;
|
||||
for i in 0..n as u64 {
|
||||
let ca = mem.read_u8(0x6000 + i).unwrap();
|
||||
let cb = mem.read_u8(0x6100 + i).unwrap();
|
||||
if ca != cb { diff = ca as i64 - cb as i64; break; }
|
||||
}
|
||||
assert_eq!(diff, 0, "strncmp first 5 chars match");
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"tolower" => Some(
|
||||
r#"
|
||||
let c = b'A' as char;
|
||||
assert_eq!(c.to_ascii_lowercase(), 'a');
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
"toupper" => Some(
|
||||
r#"
|
||||
let c = b'z' as char;
|
||||
assert_eq!(c.to_ascii_uppercase(), 'Z');
|
||||
"#
|
||||
.to_string(),
|
||||
),
|
||||
_ => None,
|
||||
}
|
||||
/// Independent canonical inputs and expected integer return bits.
|
||||
fn canonical_integer_case(symbol: &str) -> Option<(u64, u64)> {
|
||||
Some(match symbol {
|
||||
"abs" | "labs" | "llabs" => ((-42i64) as u64, 42),
|
||||
"tolower" => (65, 97),
|
||||
"toupper" => (122, 90),
|
||||
"isalnum" | "isalpha" | "isupper" | "isxdigit" => (65, 1),
|
||||
"isdigit" => (53, 1),
|
||||
"islower" => (122, 1),
|
||||
"isspace" => (32, 1),
|
||||
"isprint" => (65, 1),
|
||||
"iscntrl" => (127, 1),
|
||||
"ispunct" => (33, 1),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -4,21 +4,50 @@
|
||||
|
||||
use crate::classify::{Classification, SymbolDb};
|
||||
use crate::parse::ImportRecord;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
/// One classified import entry.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct ManifestEntry {
|
||||
pub module: String,
|
||||
pub symbol: String,
|
||||
pub ordinal: Option<u16>,
|
||||
pub iat_rva: u64,
|
||||
pub classification: Classification,
|
||||
}
|
||||
|
||||
impl ManifestEntry {
|
||||
pub(crate) fn key(&self) -> (String, Option<u16>, &str) {
|
||||
(
|
||||
self.module.to_ascii_lowercase(),
|
||||
self.ordinal,
|
||||
if self.ordinal.is_none() {
|
||||
&self.symbol
|
||||
} else {
|
||||
""
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
pub fn tier(&self) -> &'static str {
|
||||
self.classification.tier_name()
|
||||
}
|
||||
/// Runtime disposition of the generated output for this import.
|
||||
pub fn emission(&self) -> &'static str {
|
||||
match &self.classification {
|
||||
Classification::StandardService => "runtime-service",
|
||||
Classification::CrtNative { .. }
|
||||
if crate::codegen::crt_dispatch_expr(&self.symbol).is_some() =>
|
||||
{
|
||||
"generated-adapter"
|
||||
}
|
||||
Classification::CrtNative { .. }
|
||||
| Classification::CrtWrapper { .. }
|
||||
| Classification::RuntimeHelper { .. }
|
||||
| Classification::Win32Stub { .. } => "generated-stub",
|
||||
Classification::Manual { .. } | Classification::Unsupported { .. } => "no-binding",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Full coverage manifest for a set of import records.
|
||||
@@ -32,7 +61,11 @@ impl Manifest {
|
||||
let mut entries = Vec::with_capacity(records.len());
|
||||
for rec in records {
|
||||
// Check for exact symbol match, then wildcard module match
|
||||
let classification = if let Some(c) = db.get(&rec.module, &rec.symbol) {
|
||||
let classification = if rec.ordinal.is_some() {
|
||||
Classification::Manual {
|
||||
reason: "ordinal requires a documented export mapping in the typed runtime registry",
|
||||
}
|
||||
} else if let Some(c) = db.get(&rec.module, &rec.symbol) {
|
||||
c.clone()
|
||||
} else if let Some(c) = db.get(&rec.module, "__wildcard__") {
|
||||
c.clone()
|
||||
@@ -45,6 +78,7 @@ impl Manifest {
|
||||
entries.push(ManifestEntry {
|
||||
module: rec.module.clone(),
|
||||
symbol: rec.symbol.clone(),
|
||||
ordinal: rec.ordinal,
|
||||
iat_rva: rec.iat_rva,
|
||||
classification,
|
||||
});
|
||||
@@ -61,6 +95,18 @@ impl Manifest {
|
||||
m
|
||||
}
|
||||
|
||||
/// Count distinct module and symbol keys by emitted disposition.
|
||||
pub fn emission_summary(&self) -> BTreeMap<&'static str, usize> {
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut counts = BTreeMap::new();
|
||||
for entry in &self.entries {
|
||||
if seen.insert(entry.key()) {
|
||||
*counts.entry(entry.emission()).or_default() += 1;
|
||||
}
|
||||
}
|
||||
counts
|
||||
}
|
||||
|
||||
/// Entries that the generator can produce code for.
|
||||
pub fn generatable(&self) -> impl Iterator<Item = &ManifestEntry> {
|
||||
self.entries
|
||||
@@ -70,14 +116,20 @@ impl Manifest {
|
||||
|
||||
/// Write the manifest as CSV for `xenora imports sync` integration.
|
||||
pub fn write_csv(&self, path: &str) -> Result<(), String> {
|
||||
let mut out = String::from("module,symbol,iat_rva,tier\n");
|
||||
let mut out = String::from("module,symbol,iat_rva,tier,emission,import_kind\n");
|
||||
for e in &self.entries {
|
||||
let kind = if e.ordinal.is_some() {
|
||||
"ordinal"
|
||||
} else {
|
||||
"name"
|
||||
};
|
||||
out.push_str(&format!(
|
||||
"\"{}\",\"{}\",0x{:08x},{}\n",
|
||||
"\"{}\",\"{}\",0x{:08x},{},{},{kind}\n",
|
||||
e.module,
|
||||
e.symbol,
|
||||
e.iat_rva,
|
||||
e.tier()
|
||||
e.tier(),
|
||||
e.emission()
|
||||
));
|
||||
}
|
||||
std::fs::write(path, out).map_err(|e| format!("write manifest CSV {path}: {e}"))
|
||||
@@ -90,13 +142,25 @@ impl Manifest {
|
||||
let mut md = String::new();
|
||||
md.push_str("# Xenora import generator manifest\n\n");
|
||||
md.push_str("Generated by `xenora imports generate`. Do not edit manually.\n\n");
|
||||
md.push_str("## Summary\n\n");
|
||||
md.push_str("## Catalog classification by import slot\n\n");
|
||||
md.push_str("| Tier | Count | % |\n| --- | ---: | ---: |\n");
|
||||
md.push_str(&format!("| **Total** | {total} | 100% |\n"));
|
||||
let total_pct = if total == 0 { 0 } else { 100 };
|
||||
md.push_str(&format!("| **Total** | {total} | {total_pct}% |\n"));
|
||||
for (tier, count) in &summary {
|
||||
let pct = (*count as f64 / total as f64 * 100.0) as u32;
|
||||
md.push_str(&format!("| `{tier}` | {count} | {pct}% |\n"));
|
||||
}
|
||||
md.push_str("\n## Emitted disposition by distinct import\n\n");
|
||||
md.push_str("| Disposition | Count |\n| --- | ---: |\n");
|
||||
let emissions = self.emission_summary();
|
||||
md.push_str(&format!(
|
||||
"| **Total** | {} |\n",
|
||||
emissions.values().sum::<usize>()
|
||||
));
|
||||
for (disposition, count) in emissions {
|
||||
md.push_str(&format!("| `{disposition}` | {count} |\n"));
|
||||
}
|
||||
md.push_str("\nAdapters are emitted as partial handlers. Runtime services use existing registrations.\n");
|
||||
md.push_str("\n## Functions requiring manual engineering\n\n");
|
||||
for e in &self.entries {
|
||||
if let Classification::Manual { reason } | Classification::Unsupported { reason } =
|
||||
|
||||
@@ -30,6 +30,8 @@ pub enum AbiType {
|
||||
U64,
|
||||
F32,
|
||||
F64,
|
||||
/// Opaque Win64 object handle.
|
||||
Handle,
|
||||
/// Raw guest pointer (virtual address).
|
||||
Pointer {
|
||||
is_const: bool,
|
||||
@@ -191,6 +193,14 @@ impl MetadataCatalog {
|
||||
"<string.h>",
|
||||
"Calculates the length of a string in guest memory",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"strnlen",
|
||||
AbiType::U64,
|
||||
vec![("str", AbiType::StringAnsi), ("count", AbiType::U64)],
|
||||
"<string.h>",
|
||||
"Calculates a byte string length up to the supplied bound",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"strcmp",
|
||||
@@ -211,6 +221,42 @@ impl MetadataCatalog {
|
||||
"<string.h>",
|
||||
"Compares up to count characters of two strings",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"wcslen",
|
||||
AbiType::U64,
|
||||
vec![("str", AbiType::StringWide)],
|
||||
"<wchar.h>",
|
||||
"Counts 16-bit Windows code units before the terminator",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"wcsnlen",
|
||||
AbiType::U64,
|
||||
vec![("str", AbiType::StringWide), ("count", AbiType::U64)],
|
||||
"<wchar.h>",
|
||||
"Counts 16-bit Windows code units up to the supplied bound",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"wcscmp",
|
||||
AbiType::I32,
|
||||
vec![("str1", AbiType::StringWide), ("str2", AbiType::StringWide)],
|
||||
"<wchar.h>",
|
||||
"Compares two strings of 16-bit Windows code units",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"wcsncmp",
|
||||
AbiType::I32,
|
||||
vec![
|
||||
("str1", AbiType::StringWide),
|
||||
("str2", AbiType::StringWide),
|
||||
("count", AbiType::U64),
|
||||
],
|
||||
"<wchar.h>",
|
||||
"Compares up to count 16-bit Windows code units of two strings",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"memset",
|
||||
@@ -259,6 +305,33 @@ impl MetadataCatalog {
|
||||
"<string.h>",
|
||||
"Copies memory between non-overlapping guest regions",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"memmove",
|
||||
AbiType::Pointer {
|
||||
is_const: false,
|
||||
pointee: "void".into(),
|
||||
},
|
||||
vec![
|
||||
(
|
||||
"dest",
|
||||
AbiType::Pointer {
|
||||
is_const: false,
|
||||
pointee: "void".into(),
|
||||
},
|
||||
),
|
||||
(
|
||||
"src",
|
||||
AbiType::Pointer {
|
||||
is_const: true,
|
||||
pointee: "void".into(),
|
||||
},
|
||||
),
|
||||
("count", AbiType::U64),
|
||||
],
|
||||
"<string.h>",
|
||||
"Copies memory between guest ranges that may overlap",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"memcmp",
|
||||
@@ -319,6 +392,49 @@ impl MetadataCatalog {
|
||||
"<errhandlingapi.h>",
|
||||
"Sets the last-error code for the calling thread",
|
||||
);
|
||||
self.add(
|
||||
"kernel32.dll",
|
||||
"GetThreadId",
|
||||
AbiType::U32,
|
||||
vec![("Thread", AbiType::Handle)],
|
||||
"<processthreadsapi.h>",
|
||||
"Retrieves the identifier of the specified thread",
|
||||
);
|
||||
self.add(
|
||||
"kernel32.dll",
|
||||
"DuplicateHandle",
|
||||
AbiType::Bool,
|
||||
vec![
|
||||
("hSourceProcessHandle", AbiType::Handle),
|
||||
("hSourceHandle", AbiType::Handle),
|
||||
("hTargetProcessHandle", AbiType::Handle),
|
||||
(
|
||||
"lpTargetHandle",
|
||||
AbiType::Pointer {
|
||||
is_const: false,
|
||||
pointee: "HANDLE".into(),
|
||||
},
|
||||
),
|
||||
("dwDesiredAccess", AbiType::U32),
|
||||
("bInheritHandle", AbiType::Bool),
|
||||
("dwOptions", AbiType::U32),
|
||||
],
|
||||
"<handleapi.h>",
|
||||
"Creates another handle to the same object",
|
||||
);
|
||||
for (name, return_type) in [
|
||||
("GetTickCount", AbiType::U32),
|
||||
("GetTickCount64", AbiType::U64),
|
||||
] {
|
||||
self.add(
|
||||
"kernel32.dll",
|
||||
name,
|
||||
return_type,
|
||||
vec![],
|
||||
"<sysinfoapi.h>",
|
||||
"Returns elapsed system uptime in milliseconds",
|
||||
);
|
||||
}
|
||||
self.add(
|
||||
"kernel32.dll",
|
||||
"QueryPerformanceCounter",
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! CSV parser for the `missing_imports.csv` produced by `xenora probe`.
|
||||
//!
|
||||
//! Format: `"module","symbol_or_ordinal","iat_rva"`
|
||||
//! The first line is a header and is skipped.
|
||||
//! An optional `import_kind` column distinguishes numeric ordinals from names.
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct ImportRecord {
|
||||
@@ -11,6 +11,7 @@ pub struct ImportRecord {
|
||||
pub module: String,
|
||||
/// Symbol name or `Ordinal#N`
|
||||
pub symbol: String,
|
||||
pub ordinal: Option<u16>,
|
||||
/// IAT RVA (informational only, not used for generation)
|
||||
pub iat_rva: u64,
|
||||
}
|
||||
@@ -20,10 +21,14 @@ pub struct ImportRecord {
|
||||
pub fn parse_csv(path: &str) -> Result<Vec<ImportRecord>, String> {
|
||||
let content = std::fs::read_to_string(path).map_err(|e| format!("cannot read {path}: {e}"))?;
|
||||
let mut records = Vec::new();
|
||||
let mut kind_column = None;
|
||||
for (line_no, line) in content.lines().enumerate() {
|
||||
// Skip header (with or without quotes)
|
||||
let trimmed = line.trim();
|
||||
if line_no == 0 && (trimmed.starts_with("module") || trimmed.starts_with("\"module\"")) {
|
||||
kind_column = split_csv_line(trimmed)
|
||||
.iter()
|
||||
.position(|column| unquote(column) == "import_kind");
|
||||
continue;
|
||||
}
|
||||
let line = line.trim();
|
||||
@@ -36,6 +41,19 @@ pub fn parse_csv(path: &str) -> Result<Vec<ImportRecord>, String> {
|
||||
}
|
||||
let module = unquote(cols[0]).to_string();
|
||||
let symbol = unquote(cols[1]).to_string();
|
||||
let ordinal = match kind_column {
|
||||
None => None,
|
||||
Some(index) => match cols.get(index).map(|field| unquote(field)) {
|
||||
Some("name") => None,
|
||||
Some("ordinal") => Some(
|
||||
symbol
|
||||
.strip_prefix("Ordinal#")
|
||||
.and_then(|value| value.parse().ok())
|
||||
.ok_or_else(|| format!("{path}:{}: invalid ordinal", line_no + 1))?,
|
||||
),
|
||||
_ => return Err(format!("{path}:{}: invalid import_kind", line_no + 1)),
|
||||
},
|
||||
};
|
||||
let iat_rva = if cols.len() >= 3 {
|
||||
u64::from_str_radix(unquote(cols[2]).trim_start_matches("0x"), 16).unwrap_or(0)
|
||||
} else {
|
||||
@@ -45,6 +63,7 @@ pub fn parse_csv(path: &str) -> Result<Vec<ImportRecord>, String> {
|
||||
records.push(ImportRecord {
|
||||
module,
|
||||
symbol,
|
||||
ordinal,
|
||||
iat_rva,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ pub struct Parameter {
|
||||
pub struct Service {
|
||||
pub library: String,
|
||||
pub symbol: String,
|
||||
pub ordinal: Option<(u16, String)>,
|
||||
pub parameters: Vec<Parameter>,
|
||||
pub result: String,
|
||||
pub handler: String,
|
||||
@@ -96,6 +97,17 @@ pub fn parse(text: &str, test_source: &str) -> Result<Vec<Service>, String> {
|
||||
"handler" => service.handler = rest.to_owned(),
|
||||
"status" => service.status = rest.to_owned(),
|
||||
"alias" => service.aliases.push(rest.to_owned()),
|
||||
"ordinal" => {
|
||||
let (value, source) = rest
|
||||
.split_once(' ')
|
||||
.ok_or_else(|| at("ordinal needs a number and a source"))?;
|
||||
let value = value
|
||||
.parse::<u16>()
|
||||
.ok()
|
||||
.filter(|value| *value != 0)
|
||||
.ok_or_else(|| at("ordinal must be in 1..=65535"))?;
|
||||
service.ordinal = Some((value, source.trim().to_owned()));
|
||||
}
|
||||
"fails" => service.failure = rest.to_owned(),
|
||||
"ref" => service.reference = rest.to_owned(),
|
||||
"test" => service.tests.push(rest.to_owned()),
|
||||
@@ -123,6 +135,7 @@ fn parse_signature(text: &str) -> Result<Service, String> {
|
||||
Ok(Service {
|
||||
library: library.to_owned(),
|
||||
symbol: symbol.trim().to_owned(),
|
||||
ordinal: None,
|
||||
parameters,
|
||||
result: result.trim().to_owned(),
|
||||
handler: String::new(),
|
||||
@@ -137,6 +150,7 @@ fn parse_signature(text: &str) -> Result<Service, String> {
|
||||
fn validate(services: &[Service], test_source: &str) -> Result<(), String> {
|
||||
// Every key a guest could import, with the service it resolves to.
|
||||
let mut keys: BTreeMap<(String, &str), usize> = BTreeMap::new();
|
||||
let mut ordinals = BTreeSet::new();
|
||||
for (index, service) in services.iter().enumerate() {
|
||||
let name = format!("{}!{}", service.library, service.symbol);
|
||||
let fail = |message: String| Err(format!("{name}: {message}"));
|
||||
@@ -149,6 +163,14 @@ fn validate(services: &[Service], test_source: &str) -> Result<(), String> {
|
||||
if !is_identifier(&service.symbol) {
|
||||
return fail("symbol is not an identifier".into());
|
||||
}
|
||||
if let Some((ordinal, source)) = &service.ordinal {
|
||||
if source.is_empty() {
|
||||
return fail("ordinal needs a source".into());
|
||||
}
|
||||
if !ordinals.insert((&service.library, ordinal)) {
|
||||
return fail(format!("ordinal {ordinal} already resolves in this module"));
|
||||
}
|
||||
}
|
||||
if !is_identifier(&service.handler) {
|
||||
return fail("missing or invalid handler".into());
|
||||
}
|
||||
@@ -283,16 +305,18 @@ pub fn generate_rust(services: &[Service]) -> String {
|
||||
} else {
|
||||
"Ok(result.place(cpu))"
|
||||
};
|
||||
let cpu = if service.result == "void" && count == 0 {
|
||||
" let _ = cpu;\n"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"{cpu} let mut context = ServiceContext {{ state: &s, memory }};\n {binding} = handlers::{}(&mut context{names})?;\n {place}\n }});",
|
||||
" let mut context = ServiceContext {{ state: &s, memory, teb: cpu.gs_base }};\n {binding} = handlers::{}(&mut context{names})?;\n {place}\n }});",
|
||||
service.handler
|
||||
);
|
||||
if let Some((ordinal, _)) = &service.ordinal {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" registry.try_ordinal_alias({:?}, {:?}, {ordinal}).expect(\"validated export ordinal\");",
|
||||
service.library, service.symbol
|
||||
);
|
||||
}
|
||||
}
|
||||
out.push_str(" for service in &SERVICES {\n for alias in service.aliases {\n if let Err(error) = registry.try_alias(alias, service.library, service.symbol) {\n panic!(\"{error}\");\n }\n }\n }\n}\n");
|
||||
out.replace(
|
||||
@@ -343,6 +367,15 @@ pub fn generate_report(services: &[Service]) -> String {
|
||||
service.failure
|
||||
);
|
||||
}
|
||||
for service in services {
|
||||
if let Some((ordinal, source)) = &service.ordinal {
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"\nOrdinal {ordinal} for `{}!{}` is documented by {source}.",
|
||||
service.library, service.symbol
|
||||
);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
@@ -379,6 +412,26 @@ mod tests {
|
||||
assert!(generate_report(&services).contains("| Unique handler implementations | 1 |"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinal_requires_a_source_and_unique_module_key() {
|
||||
let first = entry("kernel32.dll F() -> void", "ordinal 42 test catalog");
|
||||
let services = parse(&first, TESTS).unwrap();
|
||||
assert!(
|
||||
generate_rust(&services).contains("try_ordinal_alias(\"kernel32.dll\", \"F\", 42)")
|
||||
);
|
||||
assert!(generate_report(&services).contains("documented by test catalog"));
|
||||
let second = entry("kernel32.dll G() -> void", "ordinal 42 test catalog");
|
||||
rejects(&(first + &second), "ordinal 42 already resolves");
|
||||
rejects(
|
||||
&entry("kernel32.dll F() -> void", "ordinal 42"),
|
||||
"needs a number and a source",
|
||||
);
|
||||
rejects(
|
||||
&entry("kernel32.dll F() -> void", "ordinal 65536 test catalog"),
|
||||
"1..=65535",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conflicting_keys_are_rejected() {
|
||||
let one = entry("kernel32.dll F() -> void", "");
|
||||
|
||||
@@ -9,14 +9,14 @@ fn test_builtin_db_classifies_crt_math() {
|
||||
assert!(matches!(acos_cls, Some(Classification::CrtNative { .. })));
|
||||
|
||||
let sqrtf_cls = db.get("api-ms-win-crt-math-l1-1-0.dll", "sqrtf");
|
||||
assert!(matches!(sqrtf_cls, Some(Classification::CrtNative { .. })));
|
||||
assert!(matches!(sqrtf_cls, Some(Classification::StandardService)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_builtin_db_classifies_crt_string() {
|
||||
let db = SymbolDb::builtin();
|
||||
let strlen_cls = db.get("api-ms-win-crt-string-l1-1-0.dll", "strlen");
|
||||
assert!(matches!(strlen_cls, Some(Classification::CrtNative { .. })));
|
||||
assert!(matches!(strlen_cls, Some(Classification::StandardService)));
|
||||
|
||||
let strcat_s_cls = db.get("api-ms-win-crt-string-l1-1-0.dll", "strcat_s");
|
||||
assert!(matches!(
|
||||
@@ -33,13 +33,53 @@ fn test_builtin_db_case_insensitive() {
|
||||
assert_eq!(sym1, sym2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_csv_preserves_ordinals_and_identically_spelled_names() {
|
||||
let dir = std::env::temp_dir().join(format!("xenora-typed-imports-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let input = dir.join("imports.csv");
|
||||
std::fs::write(
|
||||
&input,
|
||||
"module,symbol_or_ordinal,iat_rva,import_kind\n\
|
||||
\"demo.dll\",\"Ordinal#42\",0x1000,ordinal\n\
|
||||
\"DEMO.dll\",\"Ordinal#42\",0x1004,ordinal\n\
|
||||
\"demo.dll\",\"Ordinal#42\",0x1008,name\n",
|
||||
)
|
||||
.unwrap();
|
||||
let records = parse_csv(input.to_str().unwrap()).unwrap();
|
||||
let db = SymbolDb::builtin();
|
||||
let manifest = Manifest::build(&records, &db);
|
||||
assert_eq!(manifest.emission_summary().get("no-binding"), Some(&2));
|
||||
assert_eq!(manifest.generatable().count(), 0);
|
||||
let output = dir.join("manifest.csv");
|
||||
manifest.write_csv(output.to_str().unwrap()).unwrap();
|
||||
let csv = std::fs::read_to_string(output).unwrap();
|
||||
assert!(csv.contains("0x00001000,manual,no-binding,ordinal"));
|
||||
assert!(csv.contains("0x00001008,manual,no-binding,name"));
|
||||
let files = generate(&manifest, &db);
|
||||
assert!(!files.crt_rs.contains("Ordinal#42"));
|
||||
assert!(!files.stubs_rs.contains("Ordinal#42"));
|
||||
assert!(
|
||||
files
|
||||
.manifest_md
|
||||
.contains("requires a documented export mapping")
|
||||
);
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_manifest_and_codegen_pipeline() {
|
||||
let csv_content = r#""module","symbol_or_ordinal","iat_rva"
|
||||
"api-ms-win-crt-math-l1-1-0.dll","acos",0x1000
|
||||
"api-ms-win-crt-string-l1-1-0.dll","strlen",0x1008
|
||||
"api-ms-win-crt-string-l1-1-0.dll","tolower",0x1008
|
||||
"API-MS-WIN-CRT-STRING-L1-1-0.DLL","tolower",0x1048
|
||||
"api-ms-win-core-processthreads-l1-1-0.dll","CreateThread",0x1010
|
||||
"custom.dll","UnknownCustomFunc",0x1018
|
||||
"kernel32.dll","QueryPerformanceCounter",0x1020
|
||||
"api-ms-win-core-profile-l1-1-0.dll","QueryPerformanceFrequency",0x1028
|
||||
"api-ms-win-core-processthreads-l1-1-0.dll","GetThreadId",0x1030
|
||||
"api-ms-win-core-handle-l1-1-0.dll","DuplicateHandle",0x1038
|
||||
"api-ms-win-core-sysinfo-l1-1-0.dll","GetTickCount64",0x1040
|
||||
"#;
|
||||
|
||||
let tmp_dir = std::env::temp_dir().join("xenora_test_pipeline");
|
||||
@@ -48,21 +88,50 @@ fn test_manifest_and_codegen_pipeline() {
|
||||
std::fs::write(&csv_file, csv_content).unwrap();
|
||||
|
||||
let records = parse_csv(csv_file.to_str().unwrap()).unwrap();
|
||||
assert_eq!(records.len(), 4);
|
||||
assert_eq!(records.len(), 10);
|
||||
|
||||
let db = SymbolDb::builtin();
|
||||
let manifest = Manifest::build(&records, &db);
|
||||
let summary = manifest.summary();
|
||||
|
||||
assert_eq!(*summary.get("crt-native").unwrap_or(&0), 2);
|
||||
assert_eq!(*summary.get("crt-native").unwrap_or(&0), 3);
|
||||
assert_eq!(*summary.get("win32-stub").unwrap_or(&0), 1);
|
||||
assert_eq!(*summary.get("manual").unwrap_or(&0), 1);
|
||||
|
||||
assert_eq!(summary.get("standard-service"), Some(&5));
|
||||
assert_eq!(manifest.generatable().count(), 4);
|
||||
|
||||
let emissions = manifest.emission_summary();
|
||||
assert_eq!(emissions.get("generated-adapter"), Some(&1));
|
||||
assert_eq!(emissions.get("generated-stub"), Some(&2));
|
||||
assert_eq!(emissions.get("runtime-service"), Some(&5));
|
||||
assert_eq!(emissions.get("no-binding"), Some(&1));
|
||||
let csv = tmp_dir.join("manifest.csv");
|
||||
manifest.write_csv(csv.to_str().unwrap()).unwrap();
|
||||
let csv = std::fs::read_to_string(csv).unwrap();
|
||||
assert!(csv.contains("\"acos\",0x00001000,crt-native,generated-stub"));
|
||||
|
||||
let files = generate(&manifest, &db);
|
||||
assert!(files.crt_rs.contains("register_generated_crt_services"));
|
||||
assert!(files.crt_rs.contains("strlen"));
|
||||
assert_eq!(files.crt_rs.matches("\"tolower\"").count(), 1);
|
||||
let acos = files.crt_rs.split_once("\"acos\"").unwrap().1;
|
||||
let acos = acos.split("registry.register_with_status").next().unwrap();
|
||||
assert!(acos.contains("ServiceStatus::Stub"));
|
||||
assert!(acos.contains("Err(ExitReason::IllegalInstruction(0xFE))"));
|
||||
assert!(files.tests_rs.contains("generated_test_acos"));
|
||||
assert!(
|
||||
files
|
||||
.tests_rs
|
||||
.contains("generated_crt::register_generated_crt_services")
|
||||
);
|
||||
assert!(files.tests_rs.contains("(service.handler)"));
|
||||
assert!(files.tests_rs.contains("generated_test_createthread"));
|
||||
assert!(files.stubs_rs.contains("CreateThread"));
|
||||
assert!(files.tests_rs.contains("generated_test_strlen"));
|
||||
assert!(!files.stubs_rs.contains("QueryPerformance"));
|
||||
assert!(!files.stubs_rs.contains("GetThreadId"));
|
||||
assert!(!files.stubs_rs.contains("DuplicateHandle"));
|
||||
assert!(!files.stubs_rs.contains("GetTickCount64"));
|
||||
assert!(files.tests_rs.contains("generated_test_tolower"));
|
||||
|
||||
let out_dir = tmp_dir.join("out");
|
||||
files.write_all(out_dir.to_str().unwrap()).unwrap();
|
||||
@@ -71,3 +140,36 @@ fn test_manifest_and_codegen_pipeline() {
|
||||
assert!(out_dir.join("generated_tests.rs").exists());
|
||||
assert!(out_dir.join("generated_manifest.md").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_catalog_describes_windows_wide_string_signatures() {
|
||||
use xenora_import_gen::{AbiType, MetadataCatalog};
|
||||
|
||||
let catalog = MetadataCatalog::builtin();
|
||||
let wide = AbiType::StringWide;
|
||||
for (symbol, return_type, parameters) in [
|
||||
("wcslen", AbiType::U64, vec![wide.clone()]),
|
||||
("wcsnlen", AbiType::U64, vec![wide.clone(), AbiType::U64]),
|
||||
("wcscmp", AbiType::I32, vec![wide.clone(), wide.clone()]),
|
||||
(
|
||||
"wcsncmp",
|
||||
AbiType::I32,
|
||||
vec![wide.clone(), wide, AbiType::U64],
|
||||
),
|
||||
] {
|
||||
let signature = catalog.lookup("ucrtbase.dll", symbol).unwrap();
|
||||
assert_eq!(signature.return_type, return_type);
|
||||
assert_eq!(
|
||||
signature
|
||||
.params
|
||||
.iter()
|
||||
.map(|p| p.abi_type.clone())
|
||||
.collect::<Vec<_>>(),
|
||||
parameters
|
||||
);
|
||||
}
|
||||
let copy = catalog.lookup("ucrtbase.dll", "memcpy").unwrap();
|
||||
let move_ = catalog.lookup("ucrtbase.dll", "memmove").unwrap();
|
||||
assert_eq!(move_.params, copy.params);
|
||||
assert_eq!(move_.return_type, copy.return_type);
|
||||
}
|
||||
+1018
-57
File diff suppressed because it is too large.
Load diff
+19
-1374
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,270 @@
|
||||
# SOP1 forms of the gfx1030 semantic registry; included by ../rdna2.toml.
|
||||
# Data only; see the root file for the field meanings.
|
||||
|
||||
# ---- SOP1 32-bit unary integer forms (#215) ----
|
||||
# NOT, BCNT0, BCNT1 and ABS set SCC = (D != 0); the others leave SCC unchanged.
|
||||
# Searches that find nothing return -1 (guide 12.3).
|
||||
|
||||
[operand_rules.sop1_sgpr]
|
||||
family = "SOP1"
|
||||
dst = { field = "SDST", class = "sgpr", min = 0, max = 105 }
|
||||
src = [{ field = "SSRC0", class = "scalar_source" }]
|
||||
max_literals = 1
|
||||
unsupported = [
|
||||
"dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null",
|
||||
"src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline", "src_special",
|
||||
]
|
||||
|
||||
# Guide sections 5.3 and 12.3. VCC and EXEC halves can be explicit
|
||||
# destinations; the move has no implicit mask or SCC effects.
|
||||
[operand_rules.sop1_move]
|
||||
family = "SOP1"
|
||||
dst = { field = "SDST", class = "sgpr_or_vcc_exec" }
|
||||
src = [{ field = "SSRC0", class = "scalar_source" }]
|
||||
max_literals = 1
|
||||
unsupported = [
|
||||
"dst_ttmp", "dst_m0", "dst_null",
|
||||
"src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline", "src_special",
|
||||
]
|
||||
|
||||
[[form]]
|
||||
name = "S_MOV_B32"
|
||||
family = "SOP1"
|
||||
opcode = 3
|
||||
variant = "MovB32"
|
||||
operation = "mov"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_move"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_NOT_B32"
|
||||
family = "SOP1"
|
||||
opcode = 7
|
||||
variant = "NotB32"
|
||||
operation = "not"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_BREV_B32"
|
||||
family = "SOP1"
|
||||
opcode = 11
|
||||
variant = "BrevB32"
|
||||
operation = "brev"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_BCNT0_I32_B32"
|
||||
family = "SOP1"
|
||||
opcode = 13
|
||||
variant = "Bcnt0I32B32"
|
||||
operation = "bcnt0"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_BCNT1_I32_B32"
|
||||
family = "SOP1"
|
||||
opcode = 15
|
||||
variant = "Bcnt1I32B32"
|
||||
operation = "bcnt1"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_FF0_I32_B32"
|
||||
family = "SOP1"
|
||||
opcode = 17
|
||||
variant = "Ff0I32B32"
|
||||
operation = "ff0"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_FF1_I32_B32"
|
||||
family = "SOP1"
|
||||
opcode = 19
|
||||
variant = "Ff1I32B32"
|
||||
operation = "ff1"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_FLBIT_I32_B32"
|
||||
family = "SOP1"
|
||||
opcode = 21
|
||||
variant = "FlbitI32B32"
|
||||
operation = "flbit"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_FLBIT_I32"
|
||||
family = "SOP1"
|
||||
opcode = 23
|
||||
variant = "FlbitI32"
|
||||
operation = "flbit"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_SEXT_I32_I8"
|
||||
family = "SOP1"
|
||||
opcode = 25
|
||||
variant = "SextI32I8"
|
||||
operation = "sext"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
source_bits = 8
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_SEXT_I32_I16"
|
||||
family = "SOP1"
|
||||
opcode = 26
|
||||
variant = "SextI32I16"
|
||||
operation = "sext"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
source_bits = 16
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_ABS_I32"
|
||||
family = "SOP1"
|
||||
opcode = 52
|
||||
variant = "AbsI32"
|
||||
operation = "abs"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop1_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.3", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
@@ -0,0 +1,647 @@
|
||||
# SOP2 forms of the gfx1030 semantic registry; included by ../rdna2.toml.
|
||||
# Data only; see the root file for the field meanings.
|
||||
|
||||
# ---- SOP2 32-bit integer and logical forms (migrated from #229/#230) ----
|
||||
|
||||
# Operand rules shared by a family. A rule names its destination and source
|
||||
# classes; the decoder implements each rule once (rules are not per opcode).
|
||||
[operand_rules.sop2_sgpr]
|
||||
family = "SOP2"
|
||||
dst = { field = "SDST", class = "sgpr", min = 0, max = 105 }
|
||||
src = [
|
||||
{ field = "SSRC0", class = "scalar_source" },
|
||||
{ field = "SSRC1", class = "scalar_source" },
|
||||
]
|
||||
# scalar_source = normal SGPR s0-s105, inline integer -16..64, or a literal word.
|
||||
max_literals = 1
|
||||
# Encodings this rule rejects, so they stay unsupported rather than guessed.
|
||||
unsupported = [
|
||||
"dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null",
|
||||
"src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline",
|
||||
"src_special", "two_literals",
|
||||
]
|
||||
|
||||
|
||||
[[form]]
|
||||
name = "S_ADD_U32"
|
||||
family = "SOP2"
|
||||
opcode = 0
|
||||
variant = "AddU32"
|
||||
operation = "add"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "carry_out"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 101 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_SUB_U32"
|
||||
family = "SOP2"
|
||||
opcode = 1
|
||||
variant = "SubU32"
|
||||
operation = "sub"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "borrow"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 101 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_ADD_I32"
|
||||
family = "SOP2"
|
||||
opcode = 2
|
||||
variant = "AddI32"
|
||||
operation = "add"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "signed_overflow"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 101 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_SUB_I32"
|
||||
family = "SOP2"
|
||||
opcode = 3
|
||||
variant = "SubI32"
|
||||
operation = "sub"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "signed_overflow"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 101 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_ADDC_U32"
|
||||
family = "SOP2"
|
||||
opcode = 4
|
||||
variant = "AddcU32"
|
||||
operation = "add"
|
||||
signedness = "unsigned"
|
||||
carry_in = "scc"
|
||||
width = 32
|
||||
scc = "carry_out"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 102 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_SUBB_U32"
|
||||
family = "SOP2"
|
||||
opcode = 5
|
||||
variant = "SubbU32"
|
||||
operation = "sub"
|
||||
signedness = "unsigned"
|
||||
carry_in = "scc"
|
||||
width = 32
|
||||
scc = "borrow"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 102 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_AND_B32"
|
||||
family = "SOP2"
|
||||
opcode = 14
|
||||
variant = "AndB32"
|
||||
operation = "and"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 102 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_OR_B32"
|
||||
family = "SOP2"
|
||||
opcode = 16
|
||||
variant = "OrB32"
|
||||
operation = "or"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 102 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_XOR_B32"
|
||||
family = "SOP2"
|
||||
opcode = 18
|
||||
variant = "XorB32"
|
||||
operation = "xor"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 102 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
# ---- Stage C: further SOP2 logical and shift forms (#215) ----
|
||||
# Shifts use the low shift_count_bits of S1 as the count (guide 12.1 pseudocode).
|
||||
|
||||
[[form]]
|
||||
name = "S_ANDN2_B32"
|
||||
family = "SOP2"
|
||||
opcode = 20
|
||||
variant = "Andn2B32"
|
||||
operation = "andn2"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 103 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_ORN2_B32"
|
||||
family = "SOP2"
|
||||
opcode = 22
|
||||
variant = "Orn2B32"
|
||||
operation = "orn2"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 103 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_NAND_B32"
|
||||
family = "SOP2"
|
||||
opcode = 24
|
||||
variant = "NandB32"
|
||||
operation = "nand"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 104 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_NOR_B32"
|
||||
family = "SOP2"
|
||||
opcode = 26
|
||||
variant = "NorB32"
|
||||
operation = "nor"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 104 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_XNOR_B32"
|
||||
family = "SOP2"
|
||||
opcode = 28
|
||||
variant = "XnorB32"
|
||||
operation = "xnor"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 104 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_LSHL_B32"
|
||||
family = "SOP2"
|
||||
opcode = 30
|
||||
variant = "LshlB32"
|
||||
operation = "lshl"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
shift_count_bits = 5
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 104 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_LSHR_B32"
|
||||
family = "SOP2"
|
||||
opcode = 32
|
||||
variant = "LshrB32"
|
||||
operation = "lshr"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
shift_count_bits = 5
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 104 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_ASHR_I32"
|
||||
family = "SOP2"
|
||||
opcode = 34
|
||||
variant = "AshrI32"
|
||||
operation = "ashr"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
shift_count_bits = 5
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 104 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
# ---- SOP2 32-bit integer arithmetic, select and bit-field forms (#215) ----
|
||||
# min/max: SCC = S0 chosen by the strict compare (a tie gives S1, SCC 0). cselect
|
||||
# reads SCC and writes none. bfm, mul, mul_hi write no SCC (Tables 11, 12, 14).
|
||||
# bfe: offset S1[4:0], width S1[22:16]. lshl_add: SCC = carry of (S0 << N) + S1.
|
||||
|
||||
[[form]]
|
||||
name = "S_MIN_I32"
|
||||
family = "SOP2"
|
||||
opcode = 6
|
||||
variant = "MinI32"
|
||||
operation = "min"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "selected_src0"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 102 },
|
||||
{ document = "guide", section = "5.4", page = 34 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_MIN_U32"
|
||||
family = "SOP2"
|
||||
opcode = 7
|
||||
variant = "MinU32"
|
||||
operation = "min"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "selected_src0"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 102 },
|
||||
{ document = "guide", section = "5.4", page = 34 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_MAX_I32"
|
||||
family = "SOP2"
|
||||
opcode = 8
|
||||
variant = "MaxI32"
|
||||
operation = "max"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "selected_src0"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 102 },
|
||||
{ document = "guide", section = "5.4", page = 34 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_MAX_U32"
|
||||
family = "SOP2"
|
||||
opcode = 9
|
||||
variant = "MaxU32"
|
||||
operation = "max"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "selected_src0"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 103 },
|
||||
{ document = "guide", section = "5.4", page = 34 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CSELECT_B32"
|
||||
family = "SOP2"
|
||||
opcode = 10
|
||||
variant = "CselectB32"
|
||||
operation = "cselect"
|
||||
signedness = "bitwise"
|
||||
carry_in = "scc"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 103 },
|
||||
{ document = "guide", section = "5.5", page = 34 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_BFM_B32"
|
||||
family = "SOP2"
|
||||
opcode = 36
|
||||
variant = "BfmB32"
|
||||
operation = "bfm"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 104 },
|
||||
{ document = "guide", section = "5.7", page = 36 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_MUL_I32"
|
||||
family = "SOP2"
|
||||
opcode = 38
|
||||
variant = "MulI32"
|
||||
operation = "mul"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 105 },
|
||||
{ document = "guide", section = "5.4", page = 34 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_BFE_U32"
|
||||
family = "SOP2"
|
||||
opcode = 39
|
||||
variant = "BfeU32"
|
||||
operation = "bfe"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 105 },
|
||||
{ document = "guide", section = "5.7", page = 36 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_BFE_I32"
|
||||
family = "SOP2"
|
||||
opcode = 40
|
||||
variant = "BfeI32"
|
||||
operation = "bfe"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 105 },
|
||||
{ document = "guide", section = "5.7", page = 36 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_ABSDIFF_I32"
|
||||
family = "SOP2"
|
||||
opcode = 44
|
||||
variant = "AbsdiffI32"
|
||||
operation = "absdiff"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "nonzero"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.1", page = 105 },
|
||||
{ document = "guide", section = "5.4", page = 34 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_LSHL1_ADD_U32"
|
||||
family = "SOP2"
|
||||
opcode = 46
|
||||
variant = "Lshl1AddU32"
|
||||
operation = "lshl_add"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
shift_amount = 1
|
||||
scc = "carry_out"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 105 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_LSHL2_ADD_U32"
|
||||
family = "SOP2"
|
||||
opcode = 47
|
||||
variant = "Lshl2AddU32"
|
||||
operation = "lshl_add"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
shift_amount = 2
|
||||
scc = "carry_out"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 105 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_LSHL3_ADD_U32"
|
||||
family = "SOP2"
|
||||
opcode = 48
|
||||
variant = "Lshl3AddU32"
|
||||
operation = "lshl_add"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
shift_amount = 3
|
||||
scc = "carry_out"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 106 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_LSHL4_ADD_U32"
|
||||
family = "SOP2"
|
||||
opcode = 49
|
||||
variant = "Lshl4AddU32"
|
||||
operation = "lshl_add"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
shift_amount = 4
|
||||
scc = "carry_out"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 106 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_MUL_HI_U32"
|
||||
family = "SOP2"
|
||||
opcode = 53
|
||||
variant = "MulHiU32"
|
||||
operation = "mul_hi"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 106 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_MUL_HI_I32"
|
||||
family = "SOP2"
|
||||
opcode = 54
|
||||
variant = "MulHiI32"
|
||||
operation = "mul_hi"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sop2_sgpr"
|
||||
spec = [{ document = "guide", section = "12.1", page = 106 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
@@ -0,0 +1,269 @@
|
||||
# SOPC forms of the gfx1030 semantic registry; included by ../rdna2.toml.
|
||||
# Data only; see the root file for the field meanings.
|
||||
|
||||
# ---- Stage D: SOPC 32-bit integer compares (#215) ----
|
||||
# Only SCC is written: SCC = relation(S0, S1), S0 = SSRC0 on the left (guide 12.4).
|
||||
|
||||
[operand_rules.sopc_scalar]
|
||||
family = "SOPC"
|
||||
src = [
|
||||
{ field = "SSRC0", class = "scalar_source" },
|
||||
{ field = "SSRC1", class = "scalar_source" },
|
||||
]
|
||||
max_literals = 1
|
||||
unsupported = [
|
||||
"src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline",
|
||||
"src_special", "two_literals",
|
||||
]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_EQ_I32"
|
||||
family = "SOPC"
|
||||
opcode = 0
|
||||
variant = "CmpEqI32"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_LG_I32"
|
||||
family = "SOPC"
|
||||
opcode = 1
|
||||
variant = "CmpLgI32"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_GT_I32"
|
||||
family = "SOPC"
|
||||
opcode = 2
|
||||
variant = "CmpGtI32"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_GE_I32"
|
||||
family = "SOPC"
|
||||
opcode = 3
|
||||
variant = "CmpGeI32"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_LT_I32"
|
||||
family = "SOPC"
|
||||
opcode = 4
|
||||
variant = "CmpLtI32"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_LE_I32"
|
||||
family = "SOPC"
|
||||
opcode = 5
|
||||
variant = "CmpLeI32"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_EQ_U32"
|
||||
family = "SOPC"
|
||||
opcode = 6
|
||||
variant = "CmpEqU32"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_LG_U32"
|
||||
family = "SOPC"
|
||||
opcode = 7
|
||||
variant = "CmpLgU32"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_GT_U32"
|
||||
family = "SOPC"
|
||||
opcode = 8
|
||||
variant = "CmpGtU32"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_GE_U32"
|
||||
family = "SOPC"
|
||||
opcode = 9
|
||||
variant = "CmpGeU32"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_LT_U32"
|
||||
family = "SOPC"
|
||||
opcode = 10
|
||||
variant = "CmpLtU32"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMP_LE_U32"
|
||||
family = "SOPC"
|
||||
opcode = 11
|
||||
variant = "CmpLeU32"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopc_scalar"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.4", page = 0 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
@@ -0,0 +1,358 @@
|
||||
# SOPK forms of the gfx1030 semantic registry; included by ../rdna2.toml.
|
||||
# Data only; see the root file for the field meanings.
|
||||
|
||||
# ---- SOPK 16-bit immediate integer forms (#215) ----
|
||||
# SDST is the destination, and the left operand of the compares; SIMM16 is
|
||||
# sign-extended except by the unsigned compares (guide 12.2). The word never
|
||||
# takes a literal dword. SDST s0-s105 only; s0-s7 hold resource descriptors,
|
||||
# so the decoder accepts them as compare operands and the translator never
|
||||
# writes them.
|
||||
|
||||
[operand_rules.sopk_sgpr]
|
||||
family = "SOPK"
|
||||
dst = { field = "SDST", class = "sgpr", min = 0, max = 105 }
|
||||
src = [{ field = "SIMM16", class = "simm16" }]
|
||||
max_literals = 0
|
||||
unsupported = ["dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null"]
|
||||
|
||||
[operand_rules.sopk_compare]
|
||||
family = "SOPK"
|
||||
src = [
|
||||
{ field = "SDST", class = "sgpr", min = 0, max = 105 },
|
||||
{ field = "SIMM16", class = "simm16" },
|
||||
]
|
||||
max_literals = 0
|
||||
unsupported = ["dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null"]
|
||||
|
||||
[[form]]
|
||||
name = "S_MOVK_I32"
|
||||
family = "SOPK"
|
||||
opcode = 0
|
||||
variant = "MovkI32"
|
||||
operation = "mov"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMOVK_I32"
|
||||
family = "SOPK"
|
||||
opcode = 2
|
||||
variant = "CmovkI32"
|
||||
operation = "cmov"
|
||||
signedness = "signed"
|
||||
carry_in = "scc"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_EQ_I32"
|
||||
family = "SOPK"
|
||||
opcode = 3
|
||||
variant = "CmpkEqI32"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_LG_I32"
|
||||
family = "SOPK"
|
||||
opcode = 4
|
||||
variant = "CmpkLgI32"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_GT_I32"
|
||||
family = "SOPK"
|
||||
opcode = 5
|
||||
variant = "CmpkGtI32"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_GE_I32"
|
||||
family = "SOPK"
|
||||
opcode = 6
|
||||
variant = "CmpkGeI32"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_LT_I32"
|
||||
family = "SOPK"
|
||||
opcode = 7
|
||||
variant = "CmpkLtI32"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_LE_I32"
|
||||
family = "SOPK"
|
||||
opcode = 8
|
||||
variant = "CmpkLeI32"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_EQ_U32"
|
||||
family = "SOPK"
|
||||
opcode = 9
|
||||
variant = "CmpkEqU32"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_LG_U32"
|
||||
family = "SOPK"
|
||||
opcode = 10
|
||||
variant = "CmpkLgU32"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_GT_U32"
|
||||
family = "SOPK"
|
||||
opcode = 11
|
||||
variant = "CmpkGtU32"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_GE_U32"
|
||||
family = "SOPK"
|
||||
opcode = 12
|
||||
variant = "CmpkGeU32"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_LT_U32"
|
||||
family = "SOPK"
|
||||
opcode = 13
|
||||
variant = "CmpkLtU32"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_CMPK_LE_U32"
|
||||
family = "SOPK"
|
||||
opcode = 14
|
||||
variant = "CmpkLeU32"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "relation"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_compare"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_ADDK_I32"
|
||||
family = "SOPK"
|
||||
opcode = 15
|
||||
variant = "AddkI32"
|
||||
operation = "add"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "signed_overflow"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
{ document = "guide", section = "5.3", page = 33 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "S_MULK_I32"
|
||||
family = "SOPK"
|
||||
opcode = 16
|
||||
variant = "MulkI32"
|
||||
operation = "mul"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "sopk_sgpr"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.2", page = 106 },
|
||||
{ document = "guide", section = "13.1.2", page = 240 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
@@ -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"]
|
||||
@@ -0,0 +1,432 @@
|
||||
# VOP2 forms of the gfx1030 semantic registry; included by ../rdna2.toml.
|
||||
# Data only; see the root file for the field meanings.
|
||||
|
||||
# ---- VOP2 32-bit vector integer forms (#215) ----
|
||||
# Per lane under EXEC; no SCC, VCC or EXEC write (guide 12.7). The 24-bit
|
||||
# multiplies read S0[23:0] and S1[23:0], sign-extended when signed; the high
|
||||
# forms keep bits 63:32 of the product. SUBREV declares its reversed sources.
|
||||
|
||||
[operand_rules.vop2_vgpr]
|
||||
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_MUL_I32_I24"
|
||||
family = "VOP2"
|
||||
opcode = 9
|
||||
variant = "MulI32I24"
|
||||
operation = "mul24"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 131 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_MUL_HI_I32_I24"
|
||||
family = "VOP2"
|
||||
opcode = 10
|
||||
variant = "MulHiI32I24"
|
||||
operation = "mul_hi24"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 132 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_MUL_U32_U24"
|
||||
family = "VOP2"
|
||||
opcode = 11
|
||||
variant = "MulU32U24"
|
||||
operation = "mul24"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 132 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_MUL_HI_U32_U24"
|
||||
family = "VOP2"
|
||||
opcode = 12
|
||||
variant = "MulHiU32U24"
|
||||
operation = "mul_hi24"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 132 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_MIN_I32"
|
||||
family = "VOP2"
|
||||
opcode = 17
|
||||
variant = "MinI32"
|
||||
operation = "min"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 133 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_MAX_I32"
|
||||
family = "VOP2"
|
||||
opcode = 18
|
||||
variant = "MaxI32"
|
||||
operation = "max"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 133 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_MIN_U32"
|
||||
family = "VOP2"
|
||||
opcode = 19
|
||||
variant = "MinU32"
|
||||
operation = "min"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 133 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_MAX_U32"
|
||||
family = "VOP2"
|
||||
opcode = 20
|
||||
variant = "MaxU32"
|
||||
operation = "max"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 133 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_XNOR_B32"
|
||||
family = "VOP2"
|
||||
opcode = 30
|
||||
variant = "XnorB32"
|
||||
operation = "xnor"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 134 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_ADD_NC_U32"
|
||||
family = "VOP2"
|
||||
opcode = 37
|
||||
variant = "AddNcU32"
|
||||
operation = "add"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 134 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_SUB_NC_U32"
|
||||
family = "VOP2"
|
||||
opcode = 38
|
||||
variant = "SubNcU32"
|
||||
operation = "sub"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 134 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_SUBREV_NC_U32"
|
||||
family = "VOP2"
|
||||
opcode = 39
|
||||
variant = "SubrevNcU32"
|
||||
operation = "sub"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
source_order = "reversed"
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr"
|
||||
spec = [{ document = "guide", section = "12.7", page = 134 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
# ---- VOP2 logical and shift forms migrated from hand-written code (#215 M27) ----
|
||||
# Per lane under EXEC; no SCC, VCC or EXEC write (guide 12.7). The shifts read
|
||||
# their sources reversed: D = S1 shifted by S0[4:0]; ASHRREV fills with S1's sign.
|
||||
# These keep the subset the hand-written decoder accepted: both sources VGPRs.
|
||||
[operand_rules.vop2_vgpr2]
|
||||
family = "VOP2"
|
||||
dst = { field = "VDST", class = "vgpr", min = 0, max = 255 }
|
||||
src = [
|
||||
{ field = "SRC0", class = "vgpr" },
|
||||
{ field = "VSRC1", 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_LSHRREV_B32"
|
||||
family = "VOP2"
|
||||
opcode = 22
|
||||
variant = "LshrrevB32"
|
||||
operation = "lshr"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
shift_count_bits = 5
|
||||
source_order = "reversed"
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr2"
|
||||
spec = [{ document = "guide", section = "12.7", page = 133 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_ASHRREV_I32"
|
||||
family = "VOP2"
|
||||
opcode = 24
|
||||
variant = "AshrrevI32"
|
||||
operation = "ashr"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
shift_count_bits = 5
|
||||
source_order = "reversed"
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr2"
|
||||
spec = [{ document = "guide", section = "12.7", page = 133 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_LSHLREV_B32"
|
||||
family = "VOP2"
|
||||
opcode = 26
|
||||
variant = "LshlrevB32"
|
||||
operation = "lshl"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
shift_count_bits = 5
|
||||
source_order = "reversed"
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr2"
|
||||
spec = [{ document = "guide", section = "12.7", page = 133 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_AND_B32"
|
||||
family = "VOP2"
|
||||
opcode = 27
|
||||
variant = "AndB32"
|
||||
operation = "and"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr2"
|
||||
spec = [{ document = "guide", section = "12.7", page = 133 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_OR_B32"
|
||||
family = "VOP2"
|
||||
opcode = 28
|
||||
variant = "OrB32"
|
||||
operation = "or"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
wave = "any"
|
||||
operands = "vop2_vgpr2"
|
||||
spec = [{ document = "guide", section = "12.7", page = 133 }]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
[[form]]
|
||||
name = "V_XOR_B32"
|
||||
family = "VOP2"
|
||||
opcode = 29
|
||||
variant = "XorB32"
|
||||
operation = "xor"
|
||||
signedness = "bitwise"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "unchanged"
|
||||
exec = "unchanged"
|
||||
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"]
|
||||
@@ -0,0 +1,362 @@
|
||||
# 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
|
||||
# of this encoding, and inherits everything else (operation, signedness,
|
||||
# effects) from the form. The XML must agree with the inherited declaration.
|
||||
|
||||
# Two VGPR sources, VGPR destination, no modifiers (ABS, OP_SEL, CLAMP, OMOD
|
||||
# and NEG clear) and SRC2 the assembler's unused inline zero. This is the
|
||||
# subset the decoder accepted for v_add_nc_u32_e64 before the registry.
|
||||
[operand_rules.vop3_vgpr2]
|
||||
family = "VOP3"
|
||||
dst = { field = "VDST", class = "vgpr", min = 0, max = 255 }
|
||||
src = [
|
||||
{ field = "SRC0", class = "vgpr" },
|
||||
{ field = "SRC1", class = "vgpr" },
|
||||
]
|
||||
max_literals = 0
|
||||
# Only [[encoding_variant]] entries may use this rule; it hosts no new forms.
|
||||
variant_only = true
|
||||
unsupported = [
|
||||
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
|
||||
"src_float_inline", "src_special", "src_literal", "modifiers", "src2",
|
||||
]
|
||||
|
||||
# VOP3 opcode of a VOP2 form = VOP2 opcode + 0x100 (guide 12.7.1), e.g. 37 + 256
|
||||
# = 293; each opcode below is still checked against the pinned XML.
|
||||
[[encoding_variant]]
|
||||
of = "V_ADD_NC_U32"
|
||||
family = "VOP3"
|
||||
opcode = 293
|
||||
operands = "vop3_vgpr2"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.12", page = 167 },
|
||||
{ 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"]
|
||||
@@ -0,0 +1,974 @@
|
||||
# VOPC forms of the gfx1030 semantic registry; included by ../rdna2.toml.
|
||||
# Data only; see the root file for the field meanings.
|
||||
|
||||
# ---- VOPC Wave32 32-bit integer compares (migrated from #239) ----
|
||||
# VCC_LO := lanes where EXEC and the relation (S0 = SRC0 on the left) hold;
|
||||
# the contract is docs/shaders/vector-compare.md. relation "lg" is the guide's
|
||||
# LG/NE offset 5 (Table 59), named V_CMP_NE_* in the XML. v_cmpx (EXEC writes),
|
||||
# the VOP3 encoding and Wave64 stay unsupported.
|
||||
[operand_rules.vopc_vcc]
|
||||
family = "VOPC"
|
||||
src = [
|
||||
{ field = "SRC0", class = "vector_source" },
|
||||
{ field = "VSRC1", class = "vgpr" },
|
||||
]
|
||||
# The destination is implicitly vcc_lo; SRC0 is a vector_source as for VOP2.
|
||||
max_literals = 1
|
||||
unsupported = [
|
||||
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special",
|
||||
]
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_LT_I32"
|
||||
family = "VOPC"
|
||||
opcode = 129
|
||||
variant = "CmpLtI32"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
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_I32"
|
||||
family = "VOPC"
|
||||
opcode = 130
|
||||
variant = "CmpEqI32"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
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_I32"
|
||||
family = "VOPC"
|
||||
opcode = 131
|
||||
variant = "CmpLeI32"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
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_I32"
|
||||
family = "VOPC"
|
||||
opcode = 132
|
||||
variant = "CmpGtI32"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
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_I32"
|
||||
family = "VOPC"
|
||||
opcode = 133
|
||||
variant = "CmpNeI32"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
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_I32"
|
||||
family = "VOPC"
|
||||
opcode = 134
|
||||
variant = "CmpGeI32"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
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_U32"
|
||||
family = "VOPC"
|
||||
opcode = 193
|
||||
variant = "CmpLtU32"
|
||||
operation = "compare"
|
||||
relation = "lt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
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_U32"
|
||||
family = "VOPC"
|
||||
opcode = 194
|
||||
variant = "CmpEqU32"
|
||||
operation = "compare"
|
||||
relation = "eq"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
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_U32"
|
||||
family = "VOPC"
|
||||
opcode = 195
|
||||
variant = "CmpLeU32"
|
||||
operation = "compare"
|
||||
relation = "le"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
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_U32"
|
||||
family = "VOPC"
|
||||
opcode = 196
|
||||
variant = "CmpGtU32"
|
||||
operation = "compare"
|
||||
relation = "gt"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
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_U32"
|
||||
family = "VOPC"
|
||||
opcode = 197
|
||||
variant = "CmpNeU32"
|
||||
operation = "compare"
|
||||
relation = "lg"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
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_U32"
|
||||
family = "VOPC"
|
||||
opcode = 198
|
||||
variant = "CmpGeU32"
|
||||
operation = "compare"
|
||||
relation = "ge"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ document = "guide", section = "3.9", page = 19 },
|
||||
]
|
||||
verify = ["reference", "independent", "metal", "llvm_encoding"]
|
||||
|
||||
# ---- VOPC F and T compares (guide Table 59 offsets 0 and 7) ----
|
||||
# The test is false or true for every lane, so VCC_LO := 0 or the EXEC lanes
|
||||
# that exist. Sources are still decoded and checked as for the other compares
|
||||
# (docs/shaders/vector-compare.md section 5).
|
||||
|
||||
[[form]]
|
||||
name = "V_CMP_F_I32"
|
||||
family = "VOPC"
|
||||
opcode = 128
|
||||
variant = "CmpFI32"
|
||||
operation = "compare"
|
||||
relation = "f"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
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_T_I32"
|
||||
family = "VOPC"
|
||||
opcode = 135
|
||||
variant = "CmpTI32"
|
||||
operation = "compare"
|
||||
relation = "t"
|
||||
signedness = "signed"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
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_F_U32"
|
||||
family = "VOPC"
|
||||
opcode = 192
|
||||
variant = "CmpFU32"
|
||||
operation = "compare"
|
||||
relation = "f"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
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_T_U32"
|
||||
family = "VOPC"
|
||||
opcode = 199
|
||||
variant = "CmpTU32"
|
||||
operation = "compare"
|
||||
relation = "t"
|
||||
signedness = "unsigned"
|
||||
carry_in = "none"
|
||||
width = 32
|
||||
scc = "unchanged"
|
||||
vcc = "lane_mask"
|
||||
exec = "unchanged"
|
||||
wave = "wave32"
|
||||
operands = "vopc_vcc"
|
||||
spec = [
|
||||
{ document = "guide", section = "12.9", page = 150 },
|
||||
{ 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"]
|
||||
+117
-100
@@ -18,7 +18,23 @@ pub use rdna2::{
|
||||
V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32, V_LSHRREV_B32,
|
||||
V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
|
||||
};
|
||||
pub use semantics_gen::{ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp};
|
||||
pub use semantics_gen::{
|
||||
ScalarAluOp, ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, ScalarUnaryOp,
|
||||
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;
|
||||
@@ -93,7 +109,8 @@ impl fmt::Display for ScalarSource {
|
||||
}
|
||||
}
|
||||
|
||||
/// Relation tested by a VOPC integer compare; S0 is SRC0 and S1 is VSRC1.
|
||||
/// Relation tested by a SOPC or VOPC integer compare; S0 (SSRC0 or SRC0) is on
|
||||
/// the left.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum CompareRelation {
|
||||
/// S0 < S1 (opcode offset 1).
|
||||
@@ -108,64 +125,10 @@ pub enum CompareRelation {
|
||||
NotEqual,
|
||||
/// S0 >= S1 (offset 6).
|
||||
GreaterOrEqual,
|
||||
}
|
||||
|
||||
/// A 32-bit VOPC integer compare: one relation over signed or unsigned operands.
|
||||
///
|
||||
/// The per-lane test follows the RDNA 2 ISA guide, section 12.9 (Table 59) and
|
||||
/// the pinned XML descriptions. VCC and EXEC rules are in
|
||||
/// docs/shaders/vector-compare.md.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct VectorCompareOp {
|
||||
/// The tested relation.
|
||||
pub relation: CompareRelation,
|
||||
/// `_i32` (two's complement) when true, `_u32` when false.
|
||||
pub signed: bool,
|
||||
}
|
||||
|
||||
impl VectorCompareOp {
|
||||
/// Lower-case mnemonic of the 32-bit VOPC encoding.
|
||||
pub fn mnemonic(self) -> &'static str {
|
||||
const SIGNED: [&str; 6] = [
|
||||
"v_cmp_lt_i32_e32",
|
||||
"v_cmp_eq_i32_e32",
|
||||
"v_cmp_le_i32_e32",
|
||||
"v_cmp_gt_i32_e32",
|
||||
"v_cmp_ne_i32_e32",
|
||||
"v_cmp_ge_i32_e32",
|
||||
];
|
||||
const UNSIGNED: [&str; 6] = [
|
||||
"v_cmp_lt_u32_e32",
|
||||
"v_cmp_eq_u32_e32",
|
||||
"v_cmp_le_u32_e32",
|
||||
"v_cmp_gt_u32_e32",
|
||||
"v_cmp_ne_u32_e32",
|
||||
"v_cmp_ge_u32_e32",
|
||||
];
|
||||
let index = self.relation as usize;
|
||||
if self.signed {
|
||||
SIGNED[index]
|
||||
} else {
|
||||
UNSIGNED[index]
|
||||
}
|
||||
}
|
||||
|
||||
/// The per-lane test result for operand bits S0 and S1.
|
||||
pub fn test(self, src0: u32, src1: u32) -> bool {
|
||||
let ordering = if self.signed {
|
||||
(src0 as i32).cmp(&(src1 as i32))
|
||||
} else {
|
||||
src0.cmp(&src1)
|
||||
};
|
||||
match self.relation {
|
||||
CompareRelation::Less => ordering.is_lt(),
|
||||
CompareRelation::Equal => ordering.is_eq(),
|
||||
CompareRelation::LessOrEqual => ordering.is_le(),
|
||||
CompareRelation::Greater => ordering.is_gt(),
|
||||
CompareRelation::NotEqual => ordering.is_ne(),
|
||||
CompareRelation::GreaterOrEqual => ordering.is_ge(),
|
||||
}
|
||||
}
|
||||
/// Never holds (VOPC F, offset 0).
|
||||
False,
|
||||
/// Always holds (VOPC T, offset 7).
|
||||
True,
|
||||
}
|
||||
|
||||
/// Output targeted by a supported uncompressed four-component export.
|
||||
@@ -205,12 +168,24 @@ pub enum Instruction {
|
||||
WaitStore,
|
||||
/// VOP1 unmodified 32-bit vector move.
|
||||
MoveB32 { dst: u8, src: VectorSource },
|
||||
/// VOP3 unsigned 32-bit addition with no carry or input/output modifiers.
|
||||
AddNoCarryU32 { dst: u8, src0: u8, src1: u8 },
|
||||
/// SOP1 32-bit move to a normal SGPR or an EXEC/VCC half.
|
||||
ScalarMoveB32 { dst: u8, src: ScalarSource },
|
||||
/// SOP1 32-bit unary integer operation writing a normal SGPR (s0-s105) and,
|
||||
/// for some operations, SCC.
|
||||
/// 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 {
|
||||
op: VectorAluVop3Op,
|
||||
dst: u8,
|
||||
src0: u8,
|
||||
src1: u8,
|
||||
},
|
||||
/// SOP1 32-bit unary integer operation. The move also allows an explicit
|
||||
/// VCC or EXEC half destination. Some unary operations write SCC.
|
||||
ScalarUnary {
|
||||
op: ScalarUnaryOp,
|
||||
dst: u8,
|
||||
@@ -230,13 +205,37 @@ pub enum Instruction {
|
||||
src0: ScalarSource,
|
||||
src1: ScalarSource,
|
||||
},
|
||||
/// 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.
|
||||
/// SOPK 32-bit integer operation on SDST (s0-s105, never s0-s7) and the
|
||||
/// 16-bit immediate `simm16`; `s_addk_i32` also writes SCC and
|
||||
/// `s_cmovk_i32` reads it.
|
||||
ScalarImmediate {
|
||||
op: ScalarImmediateOp,
|
||||
dst: u8,
|
||||
simm16: u16,
|
||||
},
|
||||
/// SOPK 32-bit integer compare of `src` (s0-s105) with the 16-bit
|
||||
/// immediate, writing only SCC.
|
||||
ScalarImmediateCompare {
|
||||
op: ScalarImmediateCompareOp,
|
||||
src: u8,
|
||||
simm16: u16,
|
||||
},
|
||||
/// 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`.
|
||||
@@ -254,18 +253,6 @@ pub enum Instruction {
|
||||
BranchVccZero { target: usize },
|
||||
/// SOPP unconditional jump to a stream byte offset.
|
||||
Branch { target: usize },
|
||||
/// VOP2 logical left shift with the count in src0.
|
||||
VectorLshlrevB32 { dst: u8, src0: u8, src1: u8 },
|
||||
/// VOP2 logical right shift with the count in src0.
|
||||
VectorLshrrevB32 { dst: u8, src0: u8, src1: u8 },
|
||||
/// VOP2 arithmetic right shift with the count in src0.
|
||||
VectorAshrrevI32 { dst: u8, src0: u8, src1: u8 },
|
||||
/// VOP2 bitwise AND.
|
||||
VectorAndB32 { dst: u8, src0: u8, src1: u8 },
|
||||
/// VOP2 bitwise OR.
|
||||
VectorOrB32 { dst: u8, src0: u8, src1: u8 },
|
||||
/// VOP2 bitwise XOR.
|
||||
VectorXorB32 { dst: u8, src0: u8, src1: u8 },
|
||||
/// VOP2 single-precision addition. Execution requires an explicit FP mode.
|
||||
VectorAddF32 { dst: u8, src0: u8, src1: u8 },
|
||||
/// VOP2 single-precision multiplication. Execution requires an explicit FP mode.
|
||||
@@ -322,23 +309,21 @@ impl Instruction {
|
||||
Self::WaitLoad => "s_waitcnt",
|
||||
Self::WaitStore => "s_waitcnt_vscnt",
|
||||
Self::MoveB32 { .. } => "v_mov_b32_e32",
|
||||
Self::AddNoCarryU32 { .. } => "v_add_nc_u32_e64",
|
||||
Self::ScalarMoveB32 { .. } => "s_mov_b32",
|
||||
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(),
|
||||
Self::ScalarCompare { op, .. } => op.mnemonic(),
|
||||
Self::VectorCompare { op, .. } => op.mnemonic(),
|
||||
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",
|
||||
Self::BranchVccZero { .. } => "s_cbranch_vccz",
|
||||
Self::Branch { .. } => "s_branch",
|
||||
Self::VectorLshlrevB32 { .. } => "v_lshlrev_b32_e32",
|
||||
Self::VectorLshrrevB32 { .. } => "v_lshrrev_b32_e32",
|
||||
Self::VectorAshrrevI32 { .. } => "v_ashrrev_i32_e32",
|
||||
Self::VectorAndB32 { .. } => "v_and_b32_e32",
|
||||
Self::VectorOrB32 { .. } => "v_or_b32_e32",
|
||||
Self::VectorXorB32 { .. } => "v_xor_b32_e32",
|
||||
Self::VectorAddF32 { .. } => "v_add_f32_e32",
|
||||
Self::VectorMulF32 { .. } => "v_mul_f32_e32",
|
||||
Self::Export { .. } => "exp",
|
||||
@@ -378,32 +363,64 @@ 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::AddNoCarryU32 { dst, src0, src1 }
|
||||
| Self::VectorLshlrevB32 { dst, src0, src1 }
|
||||
| Self::VectorLshrrevB32 { dst, src0, src1 }
|
||||
| Self::VectorAshrrevI32 { dst, src0, src1 }
|
||||
| Self::VectorAndB32 { dst, src0, src1 }
|
||||
| Self::VectorOrB32 { dst, src0, src1 }
|
||||
| Self::VectorXorB32 { dst, src0, src1 }
|
||||
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, ..
|
||||
}
|
||||
| Self::VectorAddF32 { dst, src0, src1 }
|
||||
| Self::VectorMulF32 { dst, src0, src1 } => {
|
||||
write!(formatter, " v{dst}, v{src0}, v{src1}")
|
||||
}
|
||||
Self::ScalarMoveB32 { dst, src } | Self::ScalarUnary { dst, src, .. } => {
|
||||
Self::ScalarUnary { dst, src, .. } => {
|
||||
write!(formatter, " {}, {src}", ScalarDestination(dst))
|
||||
}
|
||||
Self::ScalarAlu {
|
||||
dst, src0, src1, ..
|
||||
} => write!(formatter, " {}, {src0}, {src1}", ScalarDestination(dst)),
|
||||
Self::ScalarCompare { src0, src1, .. } => write!(formatter, " {src0}, {src1}"),
|
||||
Self::ScalarImmediate { dst, simm16, .. } => {
|
||||
write!(formatter, " s{dst}, {simm16:#x}")
|
||||
}
|
||||
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 }
|
||||
|
||||
@@ -99,6 +99,16 @@ pub const fn ashr_nonzero_i32(a: u32, count: u32) -> (u32, bool) {
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// The VOPC F test: false for every operand pair.
|
||||
pub const fn false_b32(_a: u32, _b: u32) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
/// The VOPC T test: true for every operand pair.
|
||||
pub const fn true_b32(_a: u32, _b: u32) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// `a == b` on the raw bits; signedness does not matter for equality.
|
||||
pub const fn eq_b32(a: u32, b: u32) -> bool {
|
||||
a == b
|
||||
@@ -208,6 +218,11 @@ pub const fn sext_i32(a: u32, bits: u32) -> u32 {
|
||||
(((a << shift) as i32) >> shift) as u32
|
||||
}
|
||||
|
||||
/// SIMM16 sign-extended to 32 bits (SOPK, guide 12.2).
|
||||
pub const fn sext_simm16(simm16: u16) -> u32 {
|
||||
simm16 as i16 as i32 as u32
|
||||
}
|
||||
|
||||
/// Two's-complement absolute value (wrapping, so `0x80000000` stays) and
|
||||
/// whether the result is nonzero.
|
||||
pub const fn abs_nonzero_i32(a: u32) -> (u32, bool) {
|
||||
@@ -316,3 +331,8 @@ pub const fn lshl_add_carry_u32(a: u32, b: u32, shift: u32) -> (u32, bool) {
|
||||
let sum = ((a as u64) << shift) + b as u64;
|
||||
(sum as u32, sum >> 32 != 0)
|
||||
}
|
||||
|
||||
/// A bitwise copy of the source (RDNA 2 guide section 12.3).
|
||||
pub(crate) const fn mov_b32(src: u32) -> u32 {
|
||||
src
|
||||
}
|
||||
+119
-5
@@ -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,
|
||||
@@ -90,6 +90,39 @@ pub enum Operation {
|
||||
Multiply24,
|
||||
/// Bits 63:32 of the product of S0[23:0] and S1[23:0] (sign-extended when signed).
|
||||
MultiplyHigh24,
|
||||
/// SOPK: SDST receives the sign-extended SIMM16.
|
||||
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
|
||||
@@ -119,6 +152,18 @@ pub enum VectorBinary {
|
||||
MulHi24Signed,
|
||||
/// Bits 63:32 of `a[23:0] * b[23:0]`.
|
||||
MulHi24Unsigned,
|
||||
/// `a & b`.
|
||||
And,
|
||||
/// `a | b`.
|
||||
Or,
|
||||
/// `a ^ b`.
|
||||
Xor,
|
||||
/// `a << (b & 31)`.
|
||||
ShiftLeft,
|
||||
/// Logical `a >> (b & 31)`.
|
||||
ShiftRight,
|
||||
/// Arithmetic (sign-filling) `a >> (b & 31)`.
|
||||
ArithmeticShiftRight,
|
||||
}
|
||||
|
||||
/// How the operands are interpreted. `Bitwise` exactly when the operation is logical.
|
||||
@@ -132,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.
|
||||
@@ -160,11 +227,17 @@ pub enum SccEffect {
|
||||
SelectedSrc0,
|
||||
}
|
||||
|
||||
/// What a form writes to VCC or EXEC. Stage A forms leave both unchanged.
|
||||
/// Where a form writes its lane mask, if any.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum MaskEffect {
|
||||
/// Not written.
|
||||
Unchanged,
|
||||
/// Wave32 VOPC result (VCC only): `VCC_LO` bit n is EXEC[n] & (lane n
|
||||
/// 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.
|
||||
@@ -188,10 +261,51 @@ pub enum OperandRule {
|
||||
/// SOP1 unary: SDST is s0-s105; SSRC0 is s0-s105, an inline integer -16..64 or
|
||||
/// a literal word. Everything else is rejected as unsupported.
|
||||
Sop1Sgpr,
|
||||
/// SOP1 move: the same sources as Sop1Sgpr, with VCC and EXEC halves
|
||||
/// also allowed as explicit destinations.
|
||||
Sop1Move,
|
||||
/// SOPK integer: SDST is s0-s105 and, except for compares, written (never s0-s7,
|
||||
/// which hold resource descriptors); SIMM16 is the 16-bit immediate. The word
|
||||
/// never takes a literal. Everything else is rejected as unsupported.
|
||||
SopkSgpr,
|
||||
/// 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.
|
||||
@@ -256,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,
|
||||
|
||||
+4814
-85
File diff suppressed because it is too large.
Load diff
@@ -1,8 +1,14 @@
|
||||
//! Ties the generated semantic registry tables to the independent XML metadata table.
|
||||
|
||||
use xenora_isa::meta::{EncodingFamily, FORMS as META_FORMS};
|
||||
use xenora_isa::semantics::{CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, SCHEMA, SccEffect};
|
||||
use xenora_isa::{ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp};
|
||||
use xenora_isa::semantics::{
|
||||
CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, MaskEffect, OperandRule, SCHEMA, SccEffect,
|
||||
Signedness, Wave,
|
||||
};
|
||||
use xenora_isa::{
|
||||
CompareRelation, ScalarAluOp, ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp,
|
||||
ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorCompareVop3Op,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn generated_tables_match_the_schema_and_the_metadata_forms() {
|
||||
@@ -73,6 +79,64 @@ fn scalar_compare_dispatch_selects_exactly_the_registry_sopc_forms() {
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_immediate_dispatch_selects_exactly_the_registry_sopk_forms() {
|
||||
for op in ScalarImmediateOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Sopk);
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(op.reads_scc(), row.carry_in == CarryIn::Scc);
|
||||
assert_eq!(op.writes_scc(), row.scc != SccEffect::Unchanged);
|
||||
}
|
||||
for op in ScalarImmediateCompareOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Sopk);
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(row.relation, Some(op.relation()));
|
||||
}
|
||||
// The two enums together are the registry's SOPK forms; the fixed
|
||||
// s_waitcnt_vscnt word (opcode 23) stays hand-written and is in neither.
|
||||
dispatch_selects_exactly(EncodingFamily::Sopk, |word| {
|
||||
ScalarImmediateOp::from_word(word)
|
||||
.map(|op| op.semantics().name)
|
||||
.or_else(|| ScalarImmediateCompareOp::from_word(word).map(|op| op.semantics().name))
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_immediate_evaluation_extends_simm16_as_the_form_declares() {
|
||||
// SIMM16 = 0x8000 is -32768 signed and 32768 unsigned.
|
||||
let d = 0xffff_8000;
|
||||
assert_eq!(
|
||||
ScalarImmediateOp::MovkI32.evaluate(0, 0x8000, false),
|
||||
(Some(d), None)
|
||||
);
|
||||
assert_eq!(
|
||||
ScalarImmediateOp::CmovkI32.evaluate(7, 0x8000, true),
|
||||
(Some(d), None)
|
||||
);
|
||||
assert_eq!(
|
||||
ScalarImmediateOp::CmovkI32.evaluate(7, 0x8000, false),
|
||||
(None, None)
|
||||
);
|
||||
assert_eq!(
|
||||
ScalarImmediateOp::AddkI32.evaluate(0x7fff_ffff, 1, false),
|
||||
(Some(0x8000_0000), Some(true))
|
||||
);
|
||||
assert_eq!(
|
||||
ScalarImmediateOp::AddkI32.evaluate(5, 0xffff, false),
|
||||
(Some(4), Some(false))
|
||||
);
|
||||
assert_eq!(
|
||||
ScalarImmediateOp::MulkI32.evaluate(3, 0xffff, true),
|
||||
(Some(0xffff_fffd), None)
|
||||
);
|
||||
assert!(ScalarImmediateCompareOp::CmpkEqI32.test(d, 0x8000));
|
||||
assert!(!ScalarImmediateCompareOp::CmpkEqU32.test(d, 0x8000));
|
||||
assert!(ScalarImmediateCompareOp::CmpkGtU32.test(d, 0xffff));
|
||||
assert!(!ScalarImmediateCompareOp::CmpkGtI32.test(d, 0xffff));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_unary_dispatch_selects_exactly_the_registry_sop1_forms() {
|
||||
for op in ScalarUnaryOp::ALL {
|
||||
@@ -81,7 +145,6 @@ fn scalar_unary_dispatch_selects_exactly_the_registry_sop1_forms() {
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(op.writes_scc(), row.scc != SccEffect::Unchanged);
|
||||
}
|
||||
// s_mov_b32 (opcode 3) stays hand-written, so it must not be dispatched here.
|
||||
dispatch_selects_exactly(EncodingFamily::Sop1, |word| {
|
||||
ScalarUnaryOp::from_word(word).map(|op| op.semantics().name)
|
||||
});
|
||||
@@ -97,9 +160,158 @@ fn vector_alu_dispatch_selects_exactly_the_registry_vop2_forms() {
|
||||
assert_eq!(op.swaps_sources(), row.swap_sources);
|
||||
assert_eq!(row.scc, SccEffect::Unchanged);
|
||||
}
|
||||
// The hand-written VOP2 forms (v_and_b32, v_add_f32, ...) must not be
|
||||
// dispatched here.
|
||||
// Exactly the registry VOP2 forms are dispatched here; the hand-written
|
||||
// ones (v_add_f32, v_mul_f32) must not be.
|
||||
dispatch_selects_exactly(EncodingFamily::Vop2, |word| {
|
||||
VectorAluOp::from_word(word).map(|op| op.semantics().name)
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_compare_dispatch_selects_exactly_the_registry_vopc_forms() {
|
||||
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);
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(op.assembly_name(), format!("{}_e32", op.mnemonic()));
|
||||
assert_eq!(row.relation, Some(op.relation()));
|
||||
assert_eq!(op.signed(), row.signedness == Signedness::Signed);
|
||||
assert_eq!(
|
||||
(row.scc, row.vcc, row.exec, row.wave),
|
||||
(
|
||||
SccEffect::Unchanged,
|
||||
MaskEffect::LaneMask,
|
||||
MaskEffect::Unchanged,
|
||||
Wave::Wave32
|
||||
)
|
||||
);
|
||||
// The per-lane test is the declared relation over the declared
|
||||
// signedness, with SRC0 on the left.
|
||||
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)
|
||||
};
|
||||
let expected = match op.relation() {
|
||||
CompareRelation::Less => ordering.is_lt(),
|
||||
CompareRelation::Equal => ordering.is_eq(),
|
||||
CompareRelation::LessOrEqual => ordering.is_le(),
|
||||
CompareRelation::Greater => ordering.is_gt(),
|
||||
CompareRelation::NotEqual => ordering.is_ne(),
|
||||
CompareRelation::GreaterOrEqual => ordering.is_ge(),
|
||||
CompareRelation::False => false,
|
||||
CompareRelation::True => true,
|
||||
};
|
||||
assert_eq!(
|
||||
op.test_bits(src0, src1),
|
||||
expected,
|
||||
"{} {src0:#x} {src1:#x}",
|
||||
row.name
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
// 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)
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vop3_variant_dispatch_selects_exactly_the_registry_vop3_rows() {
|
||||
for op in VectorAluVop3Op::ALL {
|
||||
let (row, base) = (op.semantics(), op.base().semantics());
|
||||
assert_eq!((row.name, row.family), (base.name, EncodingFamily::Vop3));
|
||||
// The variant inherits the base declaration; only identity and the
|
||||
// operand rule differ.
|
||||
assert_eq!(
|
||||
(
|
||||
base.operation,
|
||||
base.signedness,
|
||||
base.scc,
|
||||
base.vcc,
|
||||
base.exec
|
||||
),
|
||||
(row.operation, row.signedness, row.scc, row.vcc, row.exec)
|
||||
);
|
||||
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| {
|
||||
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.
|
||||
for meta in META_FORMS
|
||||
.iter()
|
||||
.filter(|form| form.family != EncodingFamily::Vop3 && form.bytes == 8)
|
||||
{
|
||||
assert_eq!(
|
||||
VectorAluVop3Op::from_word(meta.bits as u32),
|
||||
None,
|
||||
"{}",
|
||||
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" }
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Synthetic interpreter and DBT timings.
|
||||
//!
|
||||
//! 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};
|
||||
@@ -88,14 +95,25 @@ fn check(result: ExecutionResult) {
|
||||
assert_eq!(result.final_state.get(Register::Rax), ADDS as u64);
|
||||
}
|
||||
|
||||
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())
|
||||
}
|
||||
|
||||
fn report(label: &str, samples: &mut [Duration]) {
|
||||
samples.sort_unstable();
|
||||
let median = samples[samples.len() / 2];
|
||||
let median = percentile(samples, 0.50);
|
||||
let p95 = percentile(samples, 0.95);
|
||||
let p99 = percentile(samples, 0.99);
|
||||
let iqr = percentile(samples, 0.75) - percentile(samples, 0.25);
|
||||
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",
|
||||
"{label}: {} samples, median {median:?}, min {min:?}, max {max:?}, p95 {p95:?}, p99 {p99:?}, IQR {iqr:?}, median {mips:.2} MIPS",
|
||||
samples.len()
|
||||
);
|
||||
}
|
||||
@@ -104,6 +122,8 @@ 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,38 +144,52 @@ 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}");
|
||||
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.");
|
||||
report("Interpreter", &mut interpreter);
|
||||
report("Cold DBT", &mut cold);
|
||||
report("Warm DBT", &mut warm);
|
||||
@@ -165,3 +199,38 @@ fn main() {
|
||||
metrics.blocks_compiled, metrics.native_bytes_emitted, metrics.dbt_dispatches
|
||||
);
|
||||
}
|
||||
|
||||
#[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));
|
||||
}
|
||||
}
|
||||
@@ -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"}),
|
||||
@@ -63,6 +65,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"}
|
||||
# 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 +175,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 +272,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 = []
|
||||
|
||||
+148
-14
@@ -306,6 +306,26 @@ impl Arm64Assembler {
|
||||
);
|
||||
}
|
||||
|
||||
/// RBIT Xd, Xn: reverse the bit order of the source.
|
||||
pub fn rbit_64(&mut self, xd: u8, xn: u8) {
|
||||
self.emit(0xdac0_0000 | ((u32::from(xn) & 0x1f) << 5) | (u32::from(xd) & 0x1f));
|
||||
}
|
||||
|
||||
/// CLZ Xd, Xn: count the leading zero bits of the source.
|
||||
pub fn clz_64(&mut self, xd: u8, xn: u8) {
|
||||
self.emit(0xdac0_1000 | ((u32::from(xn) & 0x1f) << 5) | (u32::from(xd) & 0x1f));
|
||||
}
|
||||
|
||||
/// LSLV Xd, Xn, Xm: shift the source left by the amount in Xm.
|
||||
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),
|
||||
);
|
||||
}
|
||||
|
||||
/// LDR Qt, [Xn, #offset] (offset a multiple of 16)
|
||||
pub fn ldr_q_uoff(&mut self, qt: u8, xn: u8, offset: u32) {
|
||||
self.emit(
|
||||
@@ -562,22 +582,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -766,4 +799,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 {
|
||||
|
||||
@@ -330,10 +330,18 @@ pub fn is_translatable(insn: &Insn) -> bool {
|
||||
/// [`DbtMetrics::interpreter_fallbacks`].
|
||||
pub fn is_native(insn: &Insn) -> bool {
|
||||
let wide = matches!(insn.size, 4 | 8);
|
||||
// The bit scans work on any register or memory source, and the bit test
|
||||
// needs the index in a register.
|
||||
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,
|
||||
Op::Inc | Op::Dec | Op::Neg | Op::Not => wide,
|
||||
Op::Cmov => wide,
|
||||
Op::Bsf | Op::Bsr => scanned,
|
||||
// Only the `0F A3` form has the bit index in a register. The `0F BA`
|
||||
// group form takes an immediate index and may write memory, so it
|
||||
// stays on the shared semantics.
|
||||
Op::Bt => scanned && insn.encoding == Encoding::RmReg,
|
||||
Op::Pop => insn.encoding == Encoding::OpReg,
|
||||
Op::Mov
|
||||
| Op::Movzx
|
||||
@@ -500,6 +508,18 @@ impl Emitter<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Zero-extend the low `size` bytes of `xd` to the full 64-bit register.
|
||||
///
|
||||
/// An operation narrower than the register reads only the low bytes of its
|
||||
/// source, so the bits above them must not take part in a bit scan.
|
||||
fn zero_extend(&mut self, xd: u8, size: u8) {
|
||||
match size {
|
||||
8 => {}
|
||||
4 => self.asm.mov_reg_32(xd, xd),
|
||||
_ => self.asm.uxth_32(xd, xd),
|
||||
}
|
||||
}
|
||||
|
||||
/// Effective address into X1, clobbering X9.
|
||||
fn effective_address(&mut self, operand: &MemOperand, with_segment: bool) {
|
||||
let asm = &mut *self.asm;
|
||||
@@ -1032,6 +1052,71 @@ impl Emitter<'_> {
|
||||
self.load_condition(insn.condition);
|
||||
self.store_rm(insn, X12, completed);
|
||||
}
|
||||
Op::Bsf | Op::Bsr => {
|
||||
// BSF and BSR write the index of the lowest or the highest set
|
||||
// bit of the source into the destination and set the zero flag
|
||||
// when the source is zero (Intel SDM Volume 2B, "BSF" and
|
||||
// "BSR"). A zero source leaves the destination undefined, so
|
||||
// the destination keeps its value, which is the same rule the
|
||||
// interpreter and the reference apply.
|
||||
self.load_rm(X9, insn, completed);
|
||||
self.zero_extend(X9, insn.size);
|
||||
match insn.op {
|
||||
// The lowest set bit is the highest set bit of the
|
||||
// reversed value, so its index is the leading zero count
|
||||
// of the reversed value.
|
||||
Op::Bsf => {
|
||||
self.asm.rbit_64(X10, X9);
|
||||
self.asm.clz_64(X10, X10);
|
||||
}
|
||||
// The highest set bit sits at 63 minus the leading zero
|
||||
// count.
|
||||
_ => {
|
||||
self.asm.clz_64(X10, X9);
|
||||
self.asm.movz_64(X13, 63, 0);
|
||||
self.asm.sub_reg_64(X10, X13, X10);
|
||||
}
|
||||
}
|
||||
self.load_reg(X11, insn.reg);
|
||||
self.asm.tst_reg_64(X9, X9);
|
||||
// CSEL takes the first operand when the condition holds, so
|
||||
// the index is the value that replaces the destination.
|
||||
self.asm.csel_64(X11, X10, X11, Condition::Ne);
|
||||
match insn.size {
|
||||
// A 16-bit destination keeps the bits above it, so the
|
||||
// register is merged rather than replaced.
|
||||
2 => self.store_reg(insn.reg, insn.size, X11),
|
||||
// A 32-bit or 64-bit destination is written in full. The
|
||||
// index has no bits above the operand width, so this
|
||||
// matches the interpreter's 32-bit write, and a zero
|
||||
// source keeps the whole register unchanged.
|
||||
_ => self.asm.str_uoff_64(X11, X19, reg_offset(insn.reg.index)),
|
||||
}
|
||||
if flags {
|
||||
// The zero flag is set when the source is zero. The other
|
||||
// flags are undefined and keep their value.
|
||||
self.asm.cset_32(X12, Condition::Eq);
|
||||
self.asm.strb_uoff(X12, X19, ZF);
|
||||
}
|
||||
}
|
||||
Op::Bt => {
|
||||
// BT sets the carry flag from the tested bit and leaves the
|
||||
// other flags undefined (Intel SDM Volume 2B, "BT"). The bit
|
||||
// index comes from the register operand and is masked to the
|
||||
// operand width.
|
||||
self.load_rm(X9, insn, completed);
|
||||
self.zero_extend(X9, insn.size);
|
||||
self.load_reg(X10, insn.reg);
|
||||
self.asm.load_imm_64(X13, u64::from(8 * insn.size - 1));
|
||||
self.asm.and_reg_64(X10, X10, X13);
|
||||
self.asm.load_imm_64(X11, 1);
|
||||
self.asm.lslv_64(X11, X11, X10);
|
||||
self.asm.tst_reg_64(X9, X11);
|
||||
if flags {
|
||||
self.asm.cset_32(X12, Condition::Ne);
|
||||
self.asm.strb_uoff(X12, X19, CF);
|
||||
}
|
||||
}
|
||||
Op::Cmov => {
|
||||
self.load_rm(X10, insn, completed);
|
||||
self.load_reg(X9, insn.reg);
|
||||
@@ -2182,4 +2267,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
@@ -3,6 +3,10 @@
|
||||
//! Bounded parser for the PE32+ import directory (Microsoft PE format,
|
||||
//! "The .idata Section"). Binding and static inspection both use it, so they
|
||||
//! agree on which imports an image has and how they are named.
|
||||
//!
|
||||
//! Static inspection also reads the delay-load directory ("Delay-Load Import
|
||||
//! Tables (Image Only)"). Binding does not: the PE format leaves those imports
|
||||
//! to a delay-load helper that runs inside the image on first use.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
@@ -14,6 +18,9 @@ pub const MAX_IMPORTS: usize = 65_536;
|
||||
pub const MAX_NAME_LEN: usize = 4096;
|
||||
|
||||
const DESCRIPTOR_LEN: u32 = 20;
|
||||
const DELAY_DESCRIPTOR_LEN: u32 = 32;
|
||||
/// Delay-load attribute bit 0: the descriptor's address fields are RVAs.
|
||||
const DELAY_RVA_BASED: u32 = 1;
|
||||
const ORDINAL_FLAG: u64 = 1 << 63;
|
||||
|
||||
/// How an import names its target. A symbol that happens to be spelled like an
|
||||
@@ -42,6 +49,24 @@ pub struct ImportEntry {
|
||||
pub iat_rva: u32,
|
||||
}
|
||||
|
||||
/// A delay-load descriptor field that must hold an RVA.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum DelayField {
|
||||
DllName,
|
||||
AddressTable,
|
||||
NameTable,
|
||||
}
|
||||
|
||||
impl fmt::Display for DelayField {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::DllName => "DLL name",
|
||||
Self::AddressTable => "import address table",
|
||||
Self::NameTable => "import name table",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ImportTableError {
|
||||
/// A structure at this RVA is not fully backed by section data.
|
||||
@@ -56,6 +81,25 @@ pub enum ImportTableError {
|
||||
ReservedBits {
|
||||
rva: u32,
|
||||
},
|
||||
/// The delay-load descriptor at this RVA sets reserved attribute bits.
|
||||
DelayReservedBits {
|
||||
rva: u32,
|
||||
},
|
||||
/// The delay-load descriptor at this RVA has `RvaBased` clear, the earlier
|
||||
/// form whose address fields are virtual addresses. It is not read.
|
||||
DelayVirtualAddresses {
|
||||
rva: u32,
|
||||
},
|
||||
/// The delay-load descriptor at this RVA leaves a required field zero.
|
||||
DelayFieldMissing {
|
||||
rva: u32,
|
||||
field: DelayField,
|
||||
},
|
||||
/// The declared delay-load directory ends at this RVA before its empty
|
||||
/// descriptor.
|
||||
DelayDirectoryEnd {
|
||||
rva: u32,
|
||||
},
|
||||
TooManyDescriptors,
|
||||
TooManyImports,
|
||||
}
|
||||
@@ -63,7 +107,10 @@ pub enum ImportTableError {
|
||||
impl fmt::Display for ImportTableError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::OutOfBounds { rva } => write!(f, "import data at RVA 0x{rva:08x} is truncated"),
|
||||
Self::OutOfBounds { rva } => write!(
|
||||
f,
|
||||
"import data at RVA 0x{rva:08x} is truncated or outside the section data"
|
||||
),
|
||||
Self::MalformedName { rva } => write!(f, "malformed import name at RVA 0x{rva:08x}"),
|
||||
Self::ReservedBits { rva } => {
|
||||
write!(
|
||||
@@ -71,6 +118,21 @@ impl fmt::Display for ImportTableError {
|
||||
"reserved bits set in the import lookup at RVA 0x{rva:08x}"
|
||||
)
|
||||
}
|
||||
Self::DelayReservedBits { rva } => write!(
|
||||
f,
|
||||
"reserved attribute bits set in the delay-load descriptor at RVA 0x{rva:08x}"
|
||||
),
|
||||
Self::DelayVirtualAddresses { rva } => write!(
|
||||
f,
|
||||
"delay-load descriptor at RVA 0x{rva:08x} holds virtual addresses, not RVAs, and is not read"
|
||||
),
|
||||
Self::DelayFieldMissing { rva, field } => {
|
||||
write!(f, "delay-load descriptor at RVA 0x{rva:08x} has no {field}")
|
||||
}
|
||||
Self::DelayDirectoryEnd { rva } => write!(
|
||||
f,
|
||||
"delay-load directory ends at RVA 0x{rva:08x} before its empty descriptor"
|
||||
),
|
||||
Self::TooManyDescriptors => write!(f, "more than {MAX_DESCRIPTORS} import descriptors"),
|
||||
Self::TooManyImports => write!(f, "more than {MAX_IMPORTS} imported symbols"),
|
||||
}
|
||||
@@ -159,7 +221,7 @@ fn collect<F: Fn(u32) -> Option<usize>>(
|
||||
return Ok(());
|
||||
}
|
||||
let module = reader.name(name_rva)?;
|
||||
collect_symbols(reader, &module, lookup_rva, address_rva, entries)?;
|
||||
collect_symbols(reader, &module, lookup_rva, address_rva, false, entries)?;
|
||||
descriptor = descriptor
|
||||
.checked_add(DESCRIPTOR_LEN)
|
||||
.ok_or(ImportTableError::OutOfBounds { rva: descriptor })?;
|
||||
@@ -167,11 +229,88 @@ fn collect<F: Fn(u32) -> Option<usize>>(
|
||||
Err(ImportTableError::TooManyDescriptors)
|
||||
}
|
||||
|
||||
/// Parse the delay-load directory of `directory_size` bytes at `directory_rva`.
|
||||
///
|
||||
/// Only descriptors that lie wholly inside the declared directory are read,
|
||||
/// and the directory must hold the empty descriptor that ends the table.
|
||||
/// Each entry's `iat_rva` is its slot in the delay import address table.
|
||||
/// Returns every import before the first problem, and the problem.
|
||||
pub fn parse_delay_imports(
|
||||
bytes: &[u8],
|
||||
directory_rva: u32,
|
||||
directory_size: u32,
|
||||
rva_to_offset: impl Fn(u32) -> Option<usize>,
|
||||
) -> (Vec<ImportEntry>, Option<ImportTableError>) {
|
||||
let reader = Reader {
|
||||
bytes,
|
||||
rva_to_offset,
|
||||
};
|
||||
let mut entries = Vec::new();
|
||||
let error = collect_delayed(&reader, directory_rva, directory_size, &mut entries).err();
|
||||
(entries, error)
|
||||
}
|
||||
|
||||
fn collect_delayed<F: Fn(u32) -> Option<usize>>(
|
||||
reader: &Reader<'_, F>,
|
||||
directory_rva: u32,
|
||||
directory_size: u32,
|
||||
entries: &mut Vec<ImportEntry>,
|
||||
) -> Result<(), ImportTableError> {
|
||||
let end = directory_rva
|
||||
.checked_add(directory_size)
|
||||
.ok_or(ImportTableError::OutOfBounds { rva: directory_rva })?;
|
||||
let mut descriptor = directory_rva;
|
||||
for _ in 0..MAX_DESCRIPTORS {
|
||||
if end - descriptor < DELAY_DESCRIPTOR_LEN {
|
||||
return Err(ImportTableError::DelayDirectoryEnd { rva: end });
|
||||
}
|
||||
let fields = reader.array::<{ DELAY_DESCRIPTOR_LEN as usize }>(descriptor)?;
|
||||
// The table ends with an empty descriptor.
|
||||
if fields == [0; DELAY_DESCRIPTOR_LEN as usize] {
|
||||
return Ok(());
|
||||
}
|
||||
let attributes = reader.u32(descriptor)?;
|
||||
if attributes & !DELAY_RVA_BASED != 0 {
|
||||
return Err(ImportTableError::DelayReservedBits { rva: descriptor });
|
||||
}
|
||||
if attributes & DELAY_RVA_BASED == 0 {
|
||||
return Err(ImportTableError::DelayVirtualAddresses { rva: descriptor });
|
||||
}
|
||||
let name_rva = reader.u32(descriptor + 4)?;
|
||||
let address_rva = reader.u32(descriptor + 12)?;
|
||||
let names_rva = reader.u32(descriptor + 16)?;
|
||||
// All three are required. The address table holds thunk addresses, so
|
||||
// it cannot stand in for a missing name table.
|
||||
for (field, rva) in [
|
||||
(DelayField::DllName, name_rva),
|
||||
(DelayField::AddressTable, address_rva),
|
||||
(DelayField::NameTable, names_rva),
|
||||
] {
|
||||
if rva == 0 {
|
||||
return Err(ImportTableError::DelayFieldMissing {
|
||||
rva: descriptor,
|
||||
field,
|
||||
});
|
||||
}
|
||||
}
|
||||
// Each must also start in section data, whether or not an import uses it.
|
||||
reader.array::<1>(name_rva)?;
|
||||
reader.array::<8>(address_rva)?;
|
||||
reader.array::<8>(names_rva)?;
|
||||
let module = reader.name(name_rva)?;
|
||||
collect_symbols(reader, &module, names_rva, address_rva, true, entries)?;
|
||||
// The declared end bounds this sum.
|
||||
descriptor += DELAY_DESCRIPTOR_LEN;
|
||||
}
|
||||
Err(ImportTableError::TooManyDescriptors)
|
||||
}
|
||||
|
||||
fn collect_symbols<F: Fn(u32) -> Option<usize>>(
|
||||
reader: &Reader<'_, F>,
|
||||
module: &str,
|
||||
lookup_rva: u32,
|
||||
address_rva: u32,
|
||||
slots_on_disk: bool,
|
||||
entries: &mut Vec<ImportEntry>,
|
||||
) -> Result<(), ImportTableError> {
|
||||
// Without a lookup table the address table holds the same entries on disk.
|
||||
@@ -194,6 +333,10 @@ fn collect_symbols<F: Fn(u32) -> Option<usize>>(
|
||||
return Err(ImportTableError::TooManyImports);
|
||||
}
|
||||
let iat_rva = at(address_rva)?;
|
||||
if slots_on_disk {
|
||||
// A delay-load slot starts out holding its thunk's address.
|
||||
reader.array::<8>(iat_rva)?;
|
||||
}
|
||||
let name = if value & ORDINAL_FLAG != 0 {
|
||||
let ordinal = value & !ORDINAL_FLAG;
|
||||
ImportName::Ordinal(
|
||||
|
||||
+391
-15
@@ -12,6 +12,7 @@ use crate::memory::{GuestMemory, MemoryError};
|
||||
use crate::pe::ParsedPe;
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
use std::sync::{Arc, Mutex, RwLock};
|
||||
|
||||
/// Base virtual address range reserved for synthetic guest import dispatch trampolines.
|
||||
pub const IMPORT_TRAMPOLINE_BASE_VA: u64 = 0x0000_0007_F000_0000;
|
||||
@@ -112,7 +113,10 @@ impl Win64Args {
|
||||
2 => Ok(self.r8),
|
||||
3 => Ok(self.r9),
|
||||
n => {
|
||||
let stack_offset = 40 + ((n - 4) as u64) * 8;
|
||||
let stack_offset = ((n - 4) as u64)
|
||||
.checked_mul(8)
|
||||
.and_then(|offset| offset.checked_add(40))
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
let addr = self
|
||||
.rsp
|
||||
.checked_add(stack_offset)
|
||||
@@ -155,11 +159,117 @@ pub struct ServiceDescriptor {
|
||||
pub status: ServiceStatus,
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct DynamicTrampolines(Arc<RwLock<HashMap<u64, usize>>>);
|
||||
|
||||
impl DynamicTrampolines {
|
||||
pub(crate) fn revoke(&self, indices: impl Iterator<Item = usize>) {
|
||||
let mut entries = self.0.write().expect("dynamic service trampolines");
|
||||
for index in indices {
|
||||
entries.remove(&trampoline_address(index));
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn expose(&self, index: usize) -> u64 {
|
||||
let address = trampoline_address(index);
|
||||
self.0
|
||||
.write()
|
||||
.expect("dynamic service trampolines")
|
||||
.insert(address, index);
|
||||
address
|
||||
}
|
||||
|
||||
fn get(&self, address: u64) -> Option<usize> {
|
||||
if address < IMPORT_TRAMPOLINE_BASE_VA {
|
||||
return None;
|
||||
}
|
||||
self.0
|
||||
.read()
|
||||
.expect("dynamic service trampolines")
|
||||
.get(&address)
|
||||
.copied()
|
||||
}
|
||||
}
|
||||
|
||||
fn trampoline_address(index: usize) -> u64 {
|
||||
IMPORT_TRAMPOLINE_BASE_VA + index as u64 * IMPORT_TRAMPOLINE_STRIDE
|
||||
}
|
||||
|
||||
const CALLBACK_RETURN: u64 = IMPORT_TRAMPOLINE_BASE_VA - IMPORT_TRAMPOLINE_STRIDE;
|
||||
const MAX_CALLBACK_DEPTH: usize = 32;
|
||||
|
||||
pub(crate) struct GuestCallback {
|
||||
pub(crate) entry: u64,
|
||||
pub(crate) context: u64,
|
||||
pub(crate) cancelled: bool,
|
||||
}
|
||||
|
||||
type CallbackDispatch = Box<
|
||||
dyn Fn(&Win64Args, &GuestMemory) -> Result<Option<GuestCallback>, ExitReason> + Send + Sync,
|
||||
>;
|
||||
|
||||
/// What a callback-driven service does next.
|
||||
pub(crate) enum CallbackStep {
|
||||
/// Call guest code at `entry` with the four Win64 integer register arguments.
|
||||
Call { entry: u64, args: [u64; 4] },
|
||||
/// Return `value` in RAX to the service's caller.
|
||||
Return(u64),
|
||||
}
|
||||
|
||||
/// A service that calls guest code one or more times before it returns.
|
||||
pub(crate) trait CallbackTask: Send {
|
||||
/// Continue after the previous guest callback returned `result` in RAX.
|
||||
fn resume(
|
||||
&mut self,
|
||||
result: u64,
|
||||
teb: u64,
|
||||
memory: &mut GuestMemory,
|
||||
) -> Result<CallbackStep, ExitReason>;
|
||||
}
|
||||
|
||||
/// How a callback-driven service begins: return at once, or call guest code
|
||||
/// and continue in a task.
|
||||
pub(crate) enum CallbackStart {
|
||||
Return(u64),
|
||||
Call {
|
||||
task: Box<dyn CallbackTask>,
|
||||
entry: u64,
|
||||
args: [u64; 4],
|
||||
},
|
||||
}
|
||||
|
||||
/// Starts a callback service. The last argument is the address of 16 bytes of
|
||||
/// guest stack the service owns until it returns.
|
||||
type TaskStart = Box<
|
||||
dyn Fn(&Win64Args, u64, &mut GuestMemory, u64) -> Result<CallbackStart, ExitReason>
|
||||
+ Send
|
||||
+ Sync,
|
||||
>;
|
||||
|
||||
/// Stack the dispatcher reserves below the caller's return address for a
|
||||
/// callback frame: the callback's return address, its 32-byte home area,
|
||||
/// 16 bytes of service scratch and alignment padding. 72 keeps the callback
|
||||
/// entry RSP at 8 modulo 16, as after a CALL.
|
||||
const TASK_FRAME: u64 = 72;
|
||||
const TASK_SCRATCH: u64 = 40;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct CallbackFrame {
|
||||
resume: u64,
|
||||
preserved: Nonvolatile,
|
||||
task: Option<Arc<Mutex<Box<dyn CallbackTask>>>>,
|
||||
/// RSP to restore when a task returns to its caller.
|
||||
after: u64,
|
||||
}
|
||||
|
||||
/// Registry for resolving and binding import symbols to guest trampoline VAs.
|
||||
pub struct ImportRegistry {
|
||||
// (lower-case module, name) -> service index. Symbol names keep their case.
|
||||
services: HashMap<(String, ImportName), usize>,
|
||||
handlers: Vec<ServiceDescriptor>,
|
||||
callback_dispatchers: HashMap<usize, CallbackDispatch>,
|
||||
callback_tasks: HashMap<usize, TaskStart>,
|
||||
dynamic_trampolines: DynamicTrampolines,
|
||||
trampoline_to_service: HashMap<u64, usize>, // Trampoline VA -> service_index
|
||||
}
|
||||
|
||||
@@ -174,7 +284,10 @@ impl ImportRegistry {
|
||||
Self {
|
||||
services: HashMap::new(),
|
||||
handlers: Vec::new(),
|
||||
callback_dispatchers: HashMap::new(),
|
||||
callback_tasks: HashMap::new(),
|
||||
trampoline_to_service: HashMap::new(),
|
||||
dynamic_trampolines: DynamicTrampolines::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -191,10 +304,29 @@ impl ImportRegistry {
|
||||
.copied()
|
||||
}
|
||||
|
||||
fn service_index(&self, module: &str, symbol: &str) -> Option<usize> {
|
||||
pub(crate) fn dynamic_trampolines(&self) -> DynamicTrampolines {
|
||||
self.dynamic_trampolines.clone()
|
||||
}
|
||||
|
||||
pub(crate) fn service_index(&self, module: &str, symbol: &str) -> Option<usize> {
|
||||
self.index(module, &ImportName::Name(symbol.to_owned()))
|
||||
}
|
||||
|
||||
pub(crate) fn canonical_exports(
|
||||
&self,
|
||||
module: &str,
|
||||
) -> impl Iterator<Item = (&ImportName, usize)> {
|
||||
self.services
|
||||
.iter()
|
||||
.filter_map(move |((key, name), &index)| {
|
||||
let descriptor = &self.handlers[index];
|
||||
(key == module
|
||||
&& descriptor.module == *key
|
||||
&& descriptor.status != ServiceStatus::Stub)
|
||||
.then_some((name, index))
|
||||
})
|
||||
}
|
||||
|
||||
fn check_key(module: &str, name: &ImportName) -> Result<(), RegistryError> {
|
||||
let printable = |text: &str| {
|
||||
!text.is_empty()
|
||||
@@ -334,30 +466,54 @@ impl ImportRegistry {
|
||||
|
||||
/// Make `module` resolve `symbol` to the service registered as
|
||||
/// `target!symbol`, sharing its trampoline.
|
||||
pub(crate) fn alias(&mut self, module: &str, target: &str, symbol: &str) {
|
||||
self.try_alias(module, target, symbol)
|
||||
.expect("valid built-in service alias");
|
||||
}
|
||||
|
||||
pub fn try_alias(
|
||||
&mut self,
|
||||
module: &str,
|
||||
target: &str,
|
||||
symbol: &str,
|
||||
) -> Result<(), RegistryError> {
|
||||
let name = ImportName::Name(symbol.to_owned());
|
||||
Self::check_key(module, &name)?;
|
||||
let index = self
|
||||
.index(target, &name)
|
||||
.ok_or_else(|| RegistryError::UnknownTarget {
|
||||
module: target.to_owned(),
|
||||
symbol: symbol.to_owned(),
|
||||
})?;
|
||||
self.alias_key(module, target, symbol, ImportName::Name(symbol.to_owned()))
|
||||
}
|
||||
|
||||
/// Publish a documented ordinal for a named export in its canonical module.
|
||||
pub fn try_ordinal_alias(
|
||||
&mut self,
|
||||
module: &str,
|
||||
symbol: &str,
|
||||
ordinal: u16,
|
||||
) -> Result<(), RegistryError> {
|
||||
self.alias_key(module, module, symbol, ImportName::Ordinal(ordinal))
|
||||
}
|
||||
|
||||
fn alias_key(
|
||||
&mut self,
|
||||
module: &str,
|
||||
target: &str,
|
||||
symbol: &str,
|
||||
key: ImportName,
|
||||
) -> Result<(), RegistryError> {
|
||||
Self::check_key(module, &key)?;
|
||||
let index =
|
||||
self.service_index(target, symbol)
|
||||
.ok_or_else(|| RegistryError::UnknownTarget {
|
||||
module: target.to_owned(),
|
||||
symbol: symbol.to_owned(),
|
||||
})?;
|
||||
let previous = *self
|
||||
.services
|
||||
.entry((module.to_ascii_lowercase(), name))
|
||||
.entry((module.to_ascii_lowercase(), key.clone()))
|
||||
.or_insert(index);
|
||||
if previous == index {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(RegistryError::Duplicate {
|
||||
module: module.to_owned(),
|
||||
symbol: symbol.to_owned(),
|
||||
symbol: key.to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -403,9 +559,84 @@ impl ImportRegistry {
|
||||
Ok(slots.len())
|
||||
}
|
||||
|
||||
pub(crate) fn register_callback_dispatch(
|
||||
&mut self,
|
||||
module: &str,
|
||||
symbol: &str,
|
||||
handler: impl Fn(&Win64Args, &GuestMemory) -> Result<Option<GuestCallback>, ExitReason>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
) {
|
||||
self.register_with_status(module, symbol, ServiceStatus::Partial, |_, _, _| {
|
||||
Err(ExitReason::IllegalInstruction(0xff))
|
||||
});
|
||||
let index = self
|
||||
.service_index(module, symbol)
|
||||
.expect("registered dispatcher");
|
||||
self.callback_dispatchers.insert(index, Box::new(handler));
|
||||
}
|
||||
|
||||
/// Register a service that may call guest code before returning. `start`
|
||||
/// receives the arguments, the caller's TEB, guest memory and the address
|
||||
/// of the service's 16-byte stack scratch area.
|
||||
pub(crate) fn register_callback_task(
|
||||
&mut self,
|
||||
module: &str,
|
||||
symbol: &str,
|
||||
status: ServiceStatus,
|
||||
start: impl Fn(&Win64Args, u64, &mut GuestMemory, u64) -> Result<CallbackStart, ExitReason>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
) {
|
||||
self.register_with_status(module, symbol, status, |_, _, _| {
|
||||
Err(ExitReason::IllegalInstruction(0xff))
|
||||
});
|
||||
let index = self
|
||||
.service_index(module, symbol)
|
||||
.expect("registered callback task");
|
||||
self.callback_tasks.insert(index, Box::new(start));
|
||||
}
|
||||
|
||||
/// Enter a guest callback from the task frame whose return slot is `slot`.
|
||||
fn enter_task_callback(
|
||||
cpu: &mut CpuState,
|
||||
memory: &mut GuestMemory,
|
||||
frame: CallbackFrame,
|
||||
slot: u64,
|
||||
entry: u64,
|
||||
args: [u64; 4],
|
||||
) -> Result<(), ExitReason> {
|
||||
let key = (cpu.gs_base, slot + 8);
|
||||
if memory.callback_frames.len() >= MAX_CALLBACK_DEPTH
|
||||
|| memory.callback_frames.contains_key(&key)
|
||||
{
|
||||
return Err(ExitReason::ServiceAbiViolation);
|
||||
}
|
||||
memory
|
||||
.fetch_instruction_byte(entry)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
memory
|
||||
.write_u64(slot, CALLBACK_RETURN)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
memory.callback_frames.insert(key, frame);
|
||||
for (register, value) in [Register::Rcx, Register::Rdx, Register::R8, Register::R9]
|
||||
.into_iter()
|
||||
.zip(args)
|
||||
{
|
||||
cpu.set(register, value);
|
||||
}
|
||||
cpu.set(Register::Rsp, slot);
|
||||
cpu.rip = entry;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check if target RIP matches a synthetic service trampoline.
|
||||
pub fn is_service_trampoline(&self, rip: u64) -> bool {
|
||||
self.trampoline_to_service.contains_key(&rip)
|
||||
rip == CALLBACK_RETURN
|
||||
|| self.trampoline_to_service.contains_key(&rip)
|
||||
|| self.dynamic_trampolines.get(rip).is_some()
|
||||
}
|
||||
|
||||
/// Dispatch a service call when guest RIP hits a service trampoline.
|
||||
@@ -415,9 +646,43 @@ impl ImportRegistry {
|
||||
cpu: &mut CpuState,
|
||||
memory: &mut GuestMemory,
|
||||
) -> Result<(), ExitReason> {
|
||||
let service_idx = *self
|
||||
if rip == CALLBACK_RETURN {
|
||||
let key = (cpu.gs_base, cpu.get(Register::Rsp));
|
||||
let frame = memory
|
||||
.callback_frames
|
||||
.remove(&key)
|
||||
.ok_or(ExitReason::IllegalInstruction(0xff))?;
|
||||
if Nonvolatile::of(cpu) != frame.preserved {
|
||||
return Err(ExitReason::ServiceAbiViolation);
|
||||
}
|
||||
let Some(task) = frame.task.clone() else {
|
||||
cpu.set(Register::Rax, 1);
|
||||
cpu.rip = frame.resume;
|
||||
return Ok(());
|
||||
};
|
||||
let result = cpu.get(Register::Rax);
|
||||
let step =
|
||||
task.lock()
|
||||
.expect("guest callback task")
|
||||
.resume(result, cpu.gs_base, memory)?;
|
||||
return match step {
|
||||
CallbackStep::Call { entry, args } => {
|
||||
let slot = key.1 - 8;
|
||||
Self::enter_task_callback(cpu, memory, frame, slot, entry, args)
|
||||
}
|
||||
CallbackStep::Return(value) => {
|
||||
cpu.set(Register::Rax, value);
|
||||
cpu.set(Register::Rsp, frame.after);
|
||||
cpu.rip = frame.resume;
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
}
|
||||
let service_idx = self
|
||||
.trampoline_to_service
|
||||
.get(&rip)
|
||||
.copied()
|
||||
.or_else(|| self.dynamic_trampolines.get(rip))
|
||||
.ok_or(ExitReason::IllegalInstruction(0xFF))?;
|
||||
|
||||
let descriptor = &self.handlers[service_idx];
|
||||
@@ -431,6 +696,68 @@ impl ImportRegistry {
|
||||
|
||||
let args = Win64Args::new(cpu);
|
||||
let preserved = Nonvolatile::of(cpu);
|
||||
if let Some(start) = self.callback_tasks.get(&service_idx) {
|
||||
let slot = after
|
||||
.checked_sub(TASK_FRAME)
|
||||
.ok_or(ExitReason::MemoryFault(MemoryError::Overflow))?;
|
||||
memory
|
||||
.check_write(slot, (TASK_FRAME - 8) as usize)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
match start(&args, cpu.gs_base, memory, slot + TASK_SCRATCH)? {
|
||||
CallbackStart::Return(value) => {
|
||||
cpu.set(Register::Rax, value);
|
||||
cpu.set(Register::Rsp, after);
|
||||
cpu.rip = ret_addr;
|
||||
}
|
||||
CallbackStart::Call { task, entry, args } => {
|
||||
let mut preserved = preserved;
|
||||
preserved.gpr[4] = slot + 8;
|
||||
let frame = CallbackFrame {
|
||||
resume: ret_addr,
|
||||
preserved,
|
||||
task: Some(Arc::new(Mutex::new(task))),
|
||||
after,
|
||||
};
|
||||
Self::enter_task_callback(cpu, memory, frame, slot, entry, args)?;
|
||||
}
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(dispatcher) = self.callback_dispatchers.get(&service_idx) {
|
||||
let key = (cpu.gs_base, after);
|
||||
if memory.callback_frames.len() >= MAX_CALLBACK_DEPTH
|
||||
|| memory.callback_frames.contains_key(&key)
|
||||
{
|
||||
return Err(ExitReason::ServiceAbiViolation);
|
||||
}
|
||||
memory
|
||||
.check_write(rsp, 8)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
if let Some(callback) = dispatcher(&args, memory)? {
|
||||
memory
|
||||
.write_u64(rsp, CALLBACK_RETURN)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
let mut preserved = preserved;
|
||||
preserved.gpr[4] = after;
|
||||
memory.callback_frames.insert(
|
||||
key,
|
||||
CallbackFrame {
|
||||
resume: ret_addr,
|
||||
preserved,
|
||||
task: None,
|
||||
after,
|
||||
},
|
||||
);
|
||||
cpu.set(Register::Rcx, callback.context);
|
||||
cpu.set(Register::Rdx, u64::from(callback.cancelled));
|
||||
cpu.rip = callback.entry;
|
||||
return Ok(());
|
||||
}
|
||||
cpu.set(Register::Rax, 0);
|
||||
cpu.set(Register::Rsp, after);
|
||||
cpu.rip = ret_addr;
|
||||
return Ok(());
|
||||
}
|
||||
let value = (descriptor.handler)(&args, cpu, memory)?;
|
||||
if Nonvolatile::of(cpu) != preserved {
|
||||
return Err(ExitReason::ServiceAbiViolation);
|
||||
@@ -444,7 +771,7 @@ impl ImportRegistry {
|
||||
}
|
||||
|
||||
/// Registers a Win64 callee must preserve (Microsoft x64 calling convention).
|
||||
#[derive(PartialEq, Eq)]
|
||||
#[derive(Clone, PartialEq, Eq)]
|
||||
struct Nonvolatile {
|
||||
gpr: [u64; 9],
|
||||
xmm: [u128; 10],
|
||||
@@ -477,3 +804,52 @@ pub(crate) fn find_import_directory(bytes: &[u8]) -> Option<u32> {
|
||||
let size = u32_at(optional.checked_add(124)?)?;
|
||||
(rva != 0 && size != 0).then_some(rva)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::memory::MemoryPermissions;
|
||||
|
||||
#[test]
|
||||
fn win64_arguments_follow_register_and_stack_layout() {
|
||||
let args = Win64Args {
|
||||
rcx: 11,
|
||||
rdx: 12,
|
||||
r8: 13,
|
||||
r9: 14,
|
||||
rsp: 0x1000,
|
||||
};
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region(0x1000, 56, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
memory.write_u64(0x1028, 15).unwrap();
|
||||
memory.write_u64(0x1030, 16).unwrap();
|
||||
for (index, expected) in (11..=16).enumerate() {
|
||||
assert_eq!(args.get(index, &memory), Ok(expected));
|
||||
}
|
||||
assert_eq!(
|
||||
args.get(6, &memory),
|
||||
Err(MemoryError::UnmappedAddress(0x1038))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn win64_stack_arguments_reject_overflow_in_offsets_and_addresses() {
|
||||
let mut args = Win64Args {
|
||||
rcx: 0,
|
||||
rdx: 0,
|
||||
r8: 0,
|
||||
r9: 0,
|
||||
rsp: 0x1000,
|
||||
};
|
||||
let memory = GuestMemory::new();
|
||||
assert_eq!(args.get(usize::MAX, &memory), Err(MemoryError::Overflow));
|
||||
assert_eq!(
|
||||
args.get(usize::MAX / 8 + 4, &memory),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
args.rsp = u64::MAX - 39;
|
||||
assert_eq!(args.get(4, &memory), Err(MemoryError::Overflow));
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@ pub mod runtime_table;
|
||||
pub mod services;
|
||||
pub mod softfloat;
|
||||
pub mod startup;
|
||||
pub mod tasks;
|
||||
pub mod tls;
|
||||
pub mod triage;
|
||||
pub mod x86_decode;
|
||||
|
||||
+269
-31
@@ -85,12 +85,24 @@ impl fmt::Display for MemoryError {
|
||||
|
||||
impl std::error::Error for MemoryError {}
|
||||
|
||||
pub(crate) const PROCESS_HEAP: u64 = u64::MAX - 2;
|
||||
const MAX_DYNAMIC_BYTES: usize = 64 * 1024 * 1024;
|
||||
/// Host storage bound for each dynamic allocation kind.
|
||||
pub(crate) const DYNAMIC_BUDGET: u64 = MAX_DYNAMIC_BYTES as u64;
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
enum AllocationKind {
|
||||
ImageOrStatic,
|
||||
Virtual,
|
||||
Heap(u64),
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct MappedRegion {
|
||||
base: u64,
|
||||
data: Vec<u8>,
|
||||
permissions: MemoryPermissions,
|
||||
virtual_allocation: bool,
|
||||
allocation: AllocationKind,
|
||||
}
|
||||
|
||||
impl MappedRegion {
|
||||
@@ -108,14 +120,18 @@ impl MappedRegion {
|
||||
#[derive(Default, Clone)]
|
||||
pub struct GuestMemory {
|
||||
regions: Vec<MappedRegion>,
|
||||
private_heaps: std::collections::BTreeSet<u64>,
|
||||
private_heap_serial: u64,
|
||||
// Stable errno pointers indexed by the guest thread's TEB address.
|
||||
crt_errno: std::collections::BTreeMap<u64, u64>,
|
||||
pub(crate) callback_frames:
|
||||
std::collections::BTreeMap<(u64, u64), crate::imports::CallbackFrame>,
|
||||
}
|
||||
|
||||
impl GuestMemory {
|
||||
/// Create a new empty guest address space.
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
regions: Vec::new(),
|
||||
}
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Map a new region into guest virtual memory.
|
||||
@@ -136,7 +152,13 @@ impl GuestMemory {
|
||||
permissions: MemoryPermissions,
|
||||
initial_data: &[u8],
|
||||
) -> Result<(), MemoryError> {
|
||||
self.insert_region(base, size, permissions, initial_data, false)
|
||||
self.insert_region(
|
||||
base,
|
||||
size,
|
||||
permissions,
|
||||
initial_data,
|
||||
AllocationKind::ImageOrStatic,
|
||||
)
|
||||
}
|
||||
|
||||
fn insert_region(
|
||||
@@ -145,7 +167,7 @@ impl GuestMemory {
|
||||
size: usize,
|
||||
permissions: MemoryPermissions,
|
||||
initial_data: &[u8],
|
||||
virtual_allocation: bool,
|
||||
allocation: AllocationKind,
|
||||
) -> Result<(), MemoryError> {
|
||||
let size_u64 = size as u64;
|
||||
let end = base.checked_add(size_u64).ok_or(MemoryError::Overflow)?;
|
||||
@@ -170,7 +192,7 @@ impl GuestMemory {
|
||||
base,
|
||||
data,
|
||||
permissions,
|
||||
virtual_allocation,
|
||||
allocation,
|
||||
});
|
||||
self.regions.sort_by_key(|r| r.base);
|
||||
Ok(())
|
||||
@@ -182,43 +204,204 @@ impl GuestMemory {
|
||||
size: usize,
|
||||
permissions: MemoryPermissions,
|
||||
) -> Result<u64, MemoryError> {
|
||||
// Bound the host storage retained by the synthetic VirtualAlloc service.
|
||||
const MAX_VIRTUAL_BYTES: usize = 64 * 1024 * 1024;
|
||||
let allocated: usize = self
|
||||
self.map_dynamic_allocation(requested_base, size, permissions, AllocationKind::Virtual)
|
||||
}
|
||||
|
||||
/// Bytes mapped in total, held by virtual allocations, and held by heap
|
||||
/// blocks. Each of the last two kinds is bounded by [`DYNAMIC_BUDGET`].
|
||||
pub(crate) fn usage(&self) -> (u64, u64, u64) {
|
||||
let mapped = self
|
||||
.regions
|
||||
.iter()
|
||||
.filter(|region| region.virtual_allocation)
|
||||
.map(|region| region.data.len())
|
||||
.sum();
|
||||
if size > MAX_VIRTUAL_BYTES - allocated {
|
||||
.sum::<usize>();
|
||||
let virtual_bytes = self.dynamic_bytes(AllocationKind::Virtual);
|
||||
let heap_bytes = self.dynamic_bytes(AllocationKind::Heap(PROCESS_HEAP));
|
||||
(mapped as u64, virtual_bytes as u64, heap_bytes as u64)
|
||||
}
|
||||
|
||||
pub(crate) fn crt_errno_address(&mut self, teb: u64) -> Result<u64, MemoryError> {
|
||||
if let Some(&address) = self.crt_errno.get(&teb) {
|
||||
return Ok(address);
|
||||
}
|
||||
if self.crt_errno.len() >= 1024 {
|
||||
return Err(MemoryError::AllocationFailed);
|
||||
}
|
||||
let address = self.find_dynamic_base(4)?;
|
||||
self.map_region(address, 4, MemoryPermissions::READ_WRITE)?;
|
||||
self.crt_errno.insert(teb, address);
|
||||
Ok(address)
|
||||
}
|
||||
|
||||
pub(crate) fn create_private_heap(&mut self, initial: u64) -> Option<u64> {
|
||||
if initial > MAX_DYNAMIC_BYTES as u64
|
||||
|| self.private_heaps.len() >= 256
|
||||
|| self.private_heap_serial >= i64::MAX as u64 - 3
|
||||
{
|
||||
return None;
|
||||
}
|
||||
self.private_heap_serial += 1;
|
||||
let heap = PROCESS_HEAP - self.private_heap_serial;
|
||||
self.private_heaps.insert(heap);
|
||||
Some(heap)
|
||||
}
|
||||
|
||||
pub(crate) fn has_heap(&self, heap: u64) -> bool {
|
||||
heap == PROCESS_HEAP || self.private_heaps.contains(&heap)
|
||||
}
|
||||
|
||||
pub(crate) fn destroy_private_heap(&mut self, heap: u64) -> bool {
|
||||
if !self.private_heaps.remove(&heap) {
|
||||
return false;
|
||||
}
|
||||
self.regions
|
||||
.retain(|region| region.allocation != AllocationKind::Heap(heap));
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn map_heap_allocation(
|
||||
&mut self,
|
||||
heap: u64,
|
||||
size: usize,
|
||||
) -> Result<u64, MemoryError> {
|
||||
if !self.has_heap(heap) {
|
||||
return Err(MemoryError::AllocationFailed);
|
||||
}
|
||||
self.map_dynamic_allocation(
|
||||
0,
|
||||
size,
|
||||
MemoryPermissions::READ_WRITE,
|
||||
AllocationKind::Heap(heap),
|
||||
)
|
||||
}
|
||||
|
||||
fn map_dynamic_allocation(
|
||||
&mut self,
|
||||
requested_base: u64,
|
||||
size: usize,
|
||||
permissions: MemoryPermissions,
|
||||
allocation: AllocationKind,
|
||||
) -> Result<u64, MemoryError> {
|
||||
// Bound retained host storage independently for each allocation kind.
|
||||
let allocated = self.dynamic_bytes(allocation);
|
||||
if size > MAX_DYNAMIC_BYTES - allocated
|
||||
|| (matches!(allocation, AllocationKind::Heap(_))
|
||||
&& self
|
||||
.regions
|
||||
.iter()
|
||||
.filter(|r| matches!(r.allocation, AllocationKind::Heap(_)))
|
||||
.count()
|
||||
>= 4096)
|
||||
{
|
||||
return Err(MemoryError::AllocationFailed);
|
||||
}
|
||||
|
||||
let mut base = requested_base;
|
||||
if base == 0 {
|
||||
base = 0x0000_0003_0000_0000;
|
||||
for region in &self.regions {
|
||||
let end = base.checked_add(size as u64).ok_or(MemoryError::Overflow)?;
|
||||
if end <= region.base {
|
||||
break;
|
||||
}
|
||||
let region_end = region.base + region.data.len() as u64;
|
||||
if base < region_end {
|
||||
base = region_end
|
||||
.checked_next_multiple_of(ALLOCATION_GRANULARITY)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
self.insert_region(base, size, permissions, &[], true)?;
|
||||
let base = if requested_base == 0 {
|
||||
self.find_dynamic_base(size)?
|
||||
} else {
|
||||
requested_base
|
||||
};
|
||||
self.insert_region(base, size, permissions, &[], allocation)?;
|
||||
Ok(base)
|
||||
}
|
||||
|
||||
fn dynamic_bytes(&self, allocation: AllocationKind) -> usize {
|
||||
self.regions
|
||||
.iter()
|
||||
.filter(|region| match allocation {
|
||||
AllocationKind::Heap(_) => matches!(region.allocation, AllocationKind::Heap(_)),
|
||||
_ => region.allocation == allocation,
|
||||
})
|
||||
.map(|region| region.data.len())
|
||||
.sum()
|
||||
}
|
||||
|
||||
fn find_dynamic_base(&self, size: usize) -> Result<u64, MemoryError> {
|
||||
let mut base = 0x0000_0003_0000_0000u64;
|
||||
for region in &self.regions {
|
||||
let end = base.checked_add(size as u64).ok_or(MemoryError::Overflow)?;
|
||||
if end <= region.base {
|
||||
return Ok(base);
|
||||
}
|
||||
let region_end = region.base + region.data.len() as u64;
|
||||
if base < region_end {
|
||||
base = region_end
|
||||
.checked_next_multiple_of(ALLOCATION_GRANULARITY)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
}
|
||||
}
|
||||
base.checked_add(size as u64).ok_or(MemoryError::Overflow)?;
|
||||
Ok(base)
|
||||
}
|
||||
|
||||
pub(crate) fn resize_heap_allocation(
|
||||
&mut self,
|
||||
heap: u64,
|
||||
base: u64,
|
||||
size: usize,
|
||||
in_place_only: bool,
|
||||
) -> Result<u64, MemoryError> {
|
||||
let index = self
|
||||
.regions
|
||||
.iter()
|
||||
.position(|region| {
|
||||
region.base == base && region.allocation == AllocationKind::Heap(heap)
|
||||
})
|
||||
.ok_or(MemoryError::UnmappedAddress(base))?;
|
||||
let previous = self.regions[index].data.len();
|
||||
let other_bytes = self.dynamic_bytes(AllocationKind::Heap(heap)) - previous;
|
||||
if size > MAX_DYNAMIC_BYTES - other_bytes {
|
||||
return Err(MemoryError::AllocationFailed);
|
||||
}
|
||||
|
||||
let boundary = self
|
||||
.regions
|
||||
.get(index + 1)
|
||||
.map_or(u64::MAX, |next| next.base);
|
||||
let destination = if (size as u64) <= boundary - base {
|
||||
base
|
||||
} else if in_place_only {
|
||||
return Err(MemoryError::AllocationFailed);
|
||||
} else {
|
||||
self.find_dynamic_base(size)?
|
||||
};
|
||||
|
||||
let region = &mut self.regions[index];
|
||||
region
|
||||
.data
|
||||
.try_reserve_exact(size.saturating_sub(previous))
|
||||
.map_err(|_| MemoryError::AllocationFailed)?;
|
||||
region.data.resize(size, 0);
|
||||
if size < previous {
|
||||
region.data.shrink_to_fit();
|
||||
}
|
||||
if destination != base {
|
||||
region.base = destination;
|
||||
self.regions.sort_by_key(|region| region.base);
|
||||
}
|
||||
Ok(destination)
|
||||
}
|
||||
|
||||
pub(crate) fn release_virtual_allocation(&mut self, base: u64) -> bool {
|
||||
self.release_dynamic_allocation(base, AllocationKind::Virtual)
|
||||
}
|
||||
|
||||
pub(crate) fn release_heap_allocation(&mut self, heap: u64, base: u64) -> bool {
|
||||
self.release_dynamic_allocation(base, AllocationKind::Heap(heap))
|
||||
}
|
||||
|
||||
pub(crate) fn heap_allocation_size(&self, heap: u64, base: u64) -> Option<usize> {
|
||||
self.regions
|
||||
.iter()
|
||||
.find(|region| region.base == base && region.allocation == AllocationKind::Heap(heap))
|
||||
.map(|region| region.data.len())
|
||||
}
|
||||
|
||||
fn release_dynamic_allocation(&mut self, base: u64, allocation: AllocationKind) -> bool {
|
||||
let Some(index) = self
|
||||
.regions
|
||||
.iter()
|
||||
.position(|region| region.base == base && region.virtual_allocation)
|
||||
.position(|region| region.base == base && region.allocation == allocation)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
@@ -226,6 +409,10 @@ impl GuestMemory {
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn check_write(&self, address: u64, size: usize) -> Result<(), MemoryError> {
|
||||
self.resolve(address, size, Some("write")).map(|_| ())
|
||||
}
|
||||
|
||||
/// Resolve `[address, address + len)` to `(region index, offset, length)` pieces.
|
||||
///
|
||||
/// An access may span adjacent regions, as it would span adjacent pages, but every
|
||||
@@ -389,3 +576,54 @@ impl GuestMemory {
|
||||
self.write_bytes(address, &value.to_le_bytes())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn private_heap_destruction_reclaims_only_owned_regions() {
|
||||
let mut memory = GuestMemory::new();
|
||||
let private = memory.create_private_heap(0).unwrap();
|
||||
let peer = memory.create_private_heap(0).unwrap();
|
||||
let address = memory.map_heap_allocation(private, 16).unwrap();
|
||||
let retained = memory.map_heap_allocation(peer, 16).unwrap();
|
||||
assert!(!memory.release_heap_allocation(peer, address));
|
||||
assert_eq!(memory.heap_allocation_size(PROCESS_HEAP, address), None);
|
||||
assert!(!memory.destroy_private_heap(PROCESS_HEAP));
|
||||
assert!(memory.destroy_private_heap(private));
|
||||
assert!(!memory.destroy_private_heap(private));
|
||||
assert!(memory.map_heap_allocation(private, 16).is_err());
|
||||
assert!(memory.read_u8(address).is_err());
|
||||
assert_eq!(memory.read_u8(retained), Ok(0));
|
||||
assert_ne!(memory.create_private_heap(0).unwrap(), private);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn heap_resize_moves_only_when_allowed_and_preserves_bytes() {
|
||||
let mut memory = GuestMemory::new();
|
||||
let base = memory.map_heap_allocation(PROCESS_HEAP, 19).unwrap();
|
||||
let neighbor = memory.map_heap_allocation(PROCESS_HEAP, 1).unwrap();
|
||||
memory.write_u8(base, 0xab).unwrap();
|
||||
memory.write_u8(neighbor, 0xcd).unwrap();
|
||||
let growth = (neighbor - base) as usize + 1;
|
||||
assert_eq!(
|
||||
memory.resize_heap_allocation(PROCESS_HEAP, base, growth, true),
|
||||
Err(MemoryError::AllocationFailed)
|
||||
);
|
||||
assert_eq!(memory.heap_allocation_size(PROCESS_HEAP, base), Some(19));
|
||||
let moved = memory
|
||||
.resize_heap_allocation(PROCESS_HEAP, base, growth, false)
|
||||
.unwrap();
|
||||
assert_ne!(moved, base);
|
||||
assert_eq!(memory.read_u8(moved), Ok(0xab));
|
||||
assert_eq!(memory.read_u8(neighbor), Ok(0xcd));
|
||||
assert_eq!(memory.read_u8(moved + growth as u64 - 1), Ok(0));
|
||||
assert_eq!(memory.heap_allocation_size(PROCESS_HEAP, base), None);
|
||||
assert_eq!(
|
||||
memory.resize_heap_allocation(PROCESS_HEAP, moved, 1, true),
|
||||
Ok(moved)
|
||||
);
|
||||
assert_eq!(memory.heap_allocation_size(PROCESS_HEAP, moved), Some(1));
|
||||
}
|
||||
}
|
||||
+125
-37
@@ -11,7 +11,9 @@
|
||||
//! startup blockers.
|
||||
|
||||
use crate::dbt::{is_native, is_translatable};
|
||||
use crate::import_table::{ImportTableError, parse_imports};
|
||||
use crate::import_table::{
|
||||
ImportEntry, ImportName, ImportTableError, parse_delay_imports, parse_imports,
|
||||
};
|
||||
use crate::imports::{ImportRegistry, ServiceStatus};
|
||||
use crate::memory::MemoryPermissions;
|
||||
use crate::pe::{IMAGE_FILE_MACHINE_AMD64, PE32_PLUS_MAGIC, ParsedPe, PeError, PeSection};
|
||||
@@ -596,12 +598,14 @@ pub struct TlsCensus {
|
||||
pub struct ImportedSymbol {
|
||||
pub dll: String,
|
||||
pub symbol: String,
|
||||
pub import_name: ImportName,
|
||||
pub iat_rva: u32,
|
||||
pub category: &'static str,
|
||||
/// The standard synthetic registry has a handler for this exact key.
|
||||
pub is_supported: bool,
|
||||
pub service_status: Option<ServiceStatus>,
|
||||
pub canonical_module: Option<String>,
|
||||
pub canonical_symbol: Option<String>,
|
||||
}
|
||||
|
||||
impl ImportedSymbol {
|
||||
@@ -676,6 +680,11 @@ pub struct ProbeReport {
|
||||
pub imports: Vec<ImportedSymbol>,
|
||||
/// Why the import table could not be read to its end.
|
||||
pub import_error: Option<ImportTableError>,
|
||||
/// Delay-loaded imports before the first malformed entry, if any. Binding
|
||||
/// does not resolve them, so `imports` and its totals leave them out.
|
||||
pub delayed_imports: Vec<ImportedSymbol>,
|
||||
/// Why the delay-load import tables could not be read to their end.
|
||||
pub delay_import_error: Option<ImportTableError>,
|
||||
pub instruction_records: Vec<InstructionRecord>,
|
||||
pub first_unsupported_dbt_insn: Option<InstructionRecord>,
|
||||
}
|
||||
@@ -820,6 +829,30 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
|
||||
} else {
|
||||
0
|
||||
};
|
||||
// The delay import descriptor is data directory 13. It exists only when
|
||||
// NumberOfRvaAndSizes covers it.
|
||||
let (delay_dir_rva, delay_dir_size) = if size_of_optional_header >= 224
|
||||
&& u32::from_le_bytes(
|
||||
bytes[opt_offset + 108..opt_offset + 112]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
) > 13
|
||||
{
|
||||
(
|
||||
u32::from_le_bytes(
|
||||
bytes[opt_offset + 216..opt_offset + 220]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
),
|
||||
u32::from_le_bytes(
|
||||
bytes[opt_offset + 220..opt_offset + 224]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
),
|
||||
)
|
||||
} else {
|
||||
(0, 0)
|
||||
};
|
||||
|
||||
let section_table_offset = opt_offset + size_of_optional_header;
|
||||
let section_header_size = 40;
|
||||
@@ -958,33 +991,40 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
|
||||
&mut registry,
|
||||
Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))),
|
||||
);
|
||||
// Binding accepts only bytes backed by section data; match it exactly.
|
||||
let backed_offset = |rva: u32| {
|
||||
sections.iter().find_map(|section| {
|
||||
let offset = rva.checked_sub(section.virtual_address)?;
|
||||
(offset < section.raw_data_size)
|
||||
.then(|| (section.raw_data_ptr as usize).checked_add(offset as usize))?
|
||||
})
|
||||
};
|
||||
let (entries, import_error) = if import_dir_rva == 0 {
|
||||
(Vec::new(), None)
|
||||
} else {
|
||||
// Binding accepts only bytes backed by section data; match it exactly.
|
||||
parse_imports(bytes, import_dir_rva, |rva| {
|
||||
sections.iter().find_map(|section| {
|
||||
let offset = rva.checked_sub(section.virtual_address)?;
|
||||
(offset < section.raw_data_size)
|
||||
.then(|| (section.raw_data_ptr as usize).checked_add(offset as usize))?
|
||||
})
|
||||
})
|
||||
parse_imports(bytes, import_dir_rva, backed_offset)
|
||||
};
|
||||
let imports: Vec<ImportedSymbol> = entries
|
||||
.into_iter()
|
||||
.map(|entry| {
|
||||
let binding = registry.resolve(&entry.module, &entry.name);
|
||||
ImportedSymbol {
|
||||
category: ProbeReport::categorize_dll(&entry.module),
|
||||
dll: entry.module,
|
||||
symbol: entry.name.to_string(),
|
||||
iat_rva: entry.iat_rva,
|
||||
is_supported: binding.is_some(),
|
||||
service_status: binding.map(|service| service.status),
|
||||
canonical_module: binding.map(|service| service.module.clone()),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
let (delayed_entries, delay_import_error) = if delay_dir_rva == 0 {
|
||||
(Vec::new(), None)
|
||||
} else {
|
||||
parse_delay_imports(bytes, delay_dir_rva, delay_dir_size, backed_offset)
|
||||
};
|
||||
let describe = |entry: ImportEntry| {
|
||||
let binding = registry.resolve(&entry.module, &entry.name);
|
||||
ImportedSymbol {
|
||||
category: ProbeReport::categorize_dll(&entry.module),
|
||||
dll: entry.module,
|
||||
symbol: entry.name.to_string(),
|
||||
import_name: entry.name,
|
||||
iat_rva: entry.iat_rva,
|
||||
is_supported: binding.is_some(),
|
||||
service_status: binding.map(|service| service.status),
|
||||
canonical_module: binding.map(|service| service.module.clone()),
|
||||
canonical_symbol: binding.map(|service| service.symbol.clone()),
|
||||
}
|
||||
};
|
||||
let imports: Vec<ImportedSymbol> = entries.into_iter().map(&describe).collect();
|
||||
let delayed_imports: Vec<ImportedSymbol> = delayed_entries.into_iter().map(&describe).collect();
|
||||
|
||||
// 4. Control-Flow-Aware Static Disassembly
|
||||
//
|
||||
@@ -1120,6 +1160,8 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
|
||||
tls,
|
||||
imports,
|
||||
import_error,
|
||||
delayed_imports,
|
||||
delay_import_error,
|
||||
instruction_records,
|
||||
first_unsupported_dbt_insn,
|
||||
})
|
||||
@@ -1138,9 +1180,9 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
|
||||
|
||||
// 1. imports.csv
|
||||
let mut imports_csv = String::from(
|
||||
"module,symbol_or_ordinal,iat_rva,category,registered_binding,implementation_status,is_alias,canonical_module,startup_priority,startup_cluster,trusted_runner_binding\n",
|
||||
"module,symbol_or_ordinal,iat_rva,import_table,category,registered_binding,implementation_status,is_alias,canonical_module,startup_priority,startup_cluster,trusted_runner_binding,import_kind\n",
|
||||
);
|
||||
let mut missing_csv = String::from("module,symbol_or_ordinal,iat_rva\n");
|
||||
let mut missing_csv = String::from("module,symbol_or_ordinal,iat_rva,import_kind\n");
|
||||
let mut modules = BTreeSet::new();
|
||||
let mut unique_symbols = BTreeSet::new();
|
||||
let mut distinct_imports = BTreeSet::new();
|
||||
@@ -1149,18 +1191,17 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
|
||||
let mut clusters = BTreeMap::<(u8, &str), (usize, usize)>::new();
|
||||
let mut aliases = 0;
|
||||
// The runner admits exactly these bytes and installs a private draw handler.
|
||||
let trusted_fixture = bytes == include_bytes!("../../../fixtures/pe/trusted-runner.exe");
|
||||
let trusted_fixture = bytes == include_bytes!("../../../fixtures/pe/trusted-runner.exe")
|
||||
|| bytes == include_bytes!("../../../fixtures/pe/runtime-services.exe");
|
||||
let mut trusted_runner_slots = 0;
|
||||
let mut missing = 0;
|
||||
for imp in &report.imports {
|
||||
let module_key = imp.dll.to_ascii_lowercase();
|
||||
modules.insert(module_key.clone());
|
||||
distinct_imports.insert((module_key, &imp.symbol));
|
||||
let ordinal_scope = imp
|
||||
.symbol
|
||||
.starts_with("Ordinal#")
|
||||
.then_some(imp.dll.as_str());
|
||||
unique_symbols.insert((ordinal_scope, &imp.symbol));
|
||||
let is_ordinal = matches!(imp.import_name, ImportName::Ordinal(_));
|
||||
let import_kind = if is_ordinal { "ordinal" } else { "name" };
|
||||
unique_symbols.insert((is_ordinal.then_some(module_key.clone()), &imp.import_name));
|
||||
distinct_imports.insert((module_key, &imp.import_name));
|
||||
let module = imp.dll.replace('"', "\"\"");
|
||||
let symbol = imp.symbol.replace('"', "\"\"");
|
||||
let key = format!("\"{module}\",\"{symbol}\",0x{:08x}", imp.iat_rva);
|
||||
@@ -1171,8 +1212,8 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
|
||||
let status = imp.coverage_label();
|
||||
let canonical = imp.canonical_module.as_deref().unwrap_or("");
|
||||
let is_alias = imp.canonical_module.is_some() && !imp.dll.eq_ignore_ascii_case(canonical);
|
||||
if imp.is_supported {
|
||||
canonical_bindings.insert((canonical, &imp.symbol));
|
||||
if let Some(symbol) = &imp.canonical_symbol {
|
||||
canonical_bindings.insert((canonical, symbol));
|
||||
}
|
||||
aliases += usize::from(is_alias);
|
||||
*counts.entry(status).or_default() += 1;
|
||||
@@ -1183,14 +1224,42 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
|
||||
let canonical = canonical.replace('"', "\"\"");
|
||||
let _ = writeln!(
|
||||
imports_csv,
|
||||
"{key},{},{},{status},{is_alias},\"{canonical}\",{priority},{cluster},{trusted_binding}",
|
||||
"{key},ordinary,{},{},{status},{is_alias},\"{canonical}\",{priority},{cluster},{trusted_binding},{import_kind}",
|
||||
imp.category, imp.is_supported
|
||||
);
|
||||
if !imp.is_supported {
|
||||
let _ = writeln!(missing_csv, "{key}");
|
||||
let _ = writeln!(missing_csv, "{key},{import_kind}");
|
||||
missing += 1;
|
||||
}
|
||||
}
|
||||
// Delay-loaded imports follow the ordinary rows. Binding does not resolve
|
||||
// them, so they stay out of every ordinary total, the startup clusters and
|
||||
// `missing_imports.csv`.
|
||||
let mut delayed_modules = BTreeSet::new();
|
||||
for imp in &report.delayed_imports {
|
||||
delayed_modules.insert(imp.dll.to_ascii_lowercase());
|
||||
let is_ordinal = matches!(imp.import_name, ImportName::Ordinal(_));
|
||||
let import_kind = if is_ordinal { "ordinal" } else { "name" };
|
||||
let module = imp.dll.replace('"', "\"\"");
|
||||
let symbol = imp.symbol.replace('"', "\"\"");
|
||||
let canonical = imp.canonical_module.as_deref().unwrap_or("");
|
||||
let is_alias = imp.canonical_module.is_some() && !imp.dll.eq_ignore_ascii_case(canonical);
|
||||
let canonical = canonical.replace('"', "\"\"");
|
||||
let (priority, cluster) = imp.startup_priority();
|
||||
let _ = writeln!(
|
||||
imports_csv,
|
||||
"\"{module}\",\"{symbol}\",0x{:08x},delayed,{},{},{},{is_alias},\"{canonical}\",{priority},{cluster},false,{import_kind}",
|
||||
imp.iat_rva,
|
||||
imp.category,
|
||||
imp.is_supported,
|
||||
imp.coverage_label()
|
||||
);
|
||||
}
|
||||
let delayed_slots = report.delayed_imports.len();
|
||||
let delayed_dlls = delayed_modules.len();
|
||||
let delay_error = report
|
||||
.delay_import_error
|
||||
.map_or_else(|| "none".to_string(), |error| error.to_string());
|
||||
fs::write(out.join("imports.csv"), imports_csv)?;
|
||||
fs::write(out.join("missing_imports.csv"), missing_csv)?;
|
||||
|
||||
@@ -1247,6 +1316,9 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
|
||||
"stub_slots": {stubs},
|
||||
"recognized_unsupported_slots": {unsupported},
|
||||
"missing_handler_slots": {unknown},
|
||||
"delayed_imports": {delayed_slots},
|
||||
"delayed_imported_dlls_count": {delayed_dlls},
|
||||
"delay_import_error": "{delay_error}",
|
||||
"total_relocations": {},
|
||||
"dir64_relocations": {},
|
||||
"tls_callbacks_count": {},
|
||||
@@ -1378,6 +1450,16 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
|
||||
"- **Import table is malformed**: {error}. Only the imports before it are listed, and binding refuses the image.\n"
|
||||
);
|
||||
}
|
||||
let _ = writeln!(
|
||||
md,
|
||||
"- **Delay-Loaded Import Slots**: `{delayed_slots}` across `{delayed_dlls}` DLLs. They are marked `delayed` in `imports.csv` and are not part of the counts above or of `missing_imports.csv`: binding does not resolve them, and the PE format leaves them to the image's delay-load helper.\n"
|
||||
);
|
||||
if let Some(error) = &report.delay_import_error {
|
||||
let _ = writeln!(
|
||||
md,
|
||||
"- **Delay-load import table is malformed**: {error}. Only the delay-loaded imports before it are listed.\n"
|
||||
);
|
||||
}
|
||||
if trusted_runner_slots > 0 {
|
||||
let _ = writeln!(
|
||||
md,
|
||||
@@ -1422,6 +1504,12 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
|
||||
distinct_imports.len(),
|
||||
unique_symbols.len()
|
||||
);
|
||||
if delayed_slots > 0 {
|
||||
let _ = writeln!(
|
||||
matrix,
|
||||
"\nThe delay-load import tables contain {delayed_slots} more slots across {delayed_dlls} DLLs. They are not counted in this document."
|
||||
);
|
||||
}
|
||||
let _ = writeln!(
|
||||
matrix,
|
||||
"\nRegistered slots include {implemented} implemented, {partial} partial, and {stubs} stubs. They reference {} canonical registered services through {aliases} alias slots. The {missing} unresolved slots include {unsupported} explicitly tracked unsupported APIs and {unknown} other missing handlers.",
|
||||
|
||||
+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]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ use crate::services::ServicesState;
|
||||
/// What a service may use.
|
||||
pub struct ServiceContext<'a> {
|
||||
pub state: &'a ServicesState,
|
||||
pub teb: u64,
|
||||
pub memory: &'a mut GuestMemory,
|
||||
}
|
||||
|
||||
@@ -153,3 +154,32 @@ pub struct ServiceMetadata {
|
||||
pub reference: &'static str,
|
||||
pub tests: &'static [&'static str],
|
||||
}
|
||||
/// A 32-bit guest HRESULT returned through the Win64 integer result register.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct HResult(u32);
|
||||
|
||||
impl HResult {
|
||||
pub(crate) const OK: Self = Self(0);
|
||||
pub(crate) const FAIL: Self = Self(0x8000_4005);
|
||||
|
||||
/// Convert using the Windows SDK's HRESULT_FROM_WIN32 rules.
|
||||
pub(crate) const fn from_win32(code: u32) -> Self {
|
||||
if (code as i32) <= 0 {
|
||||
Self(code)
|
||||
} else {
|
||||
Self(0x8007_0000 | (code & 0xffff))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn guest_return(self) -> u64 {
|
||||
u64::from(self.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn hresult_win32_conversion_preserves_status_bits() {
|
||||
assert_eq!(HResult::from_win32(0), HResult::OK);
|
||||
assert_eq!(HResult::from_win32(0x8000_4005), HResult::FAIL);
|
||||
assert_eq!(HResult::from_win32(0x10057).guest_return(), 0x8007_0057);
|
||||
}
|
||||
@@ -238,7 +238,7 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let a1 = call.bool32(1)?;
|
||||
let mut context = ServiceContext { state: &s, memory };
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: bool = handlers::set_process_priority_boost(&mut context, a0, a1)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
@@ -247,14 +247,14 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let a1 = call.out::<4>(1)?;
|
||||
let mut context = ServiceContext { state: &s, memory };
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: bool = handlers::get_process_priority_boost(&mut context, a0, a1)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("kernel32.dll", "GetCurrentProcess", ServiceStatus::Implemented, move |args, cpu, memory| {
|
||||
let _ = args;
|
||||
let mut context = ServiceContext { state: &s, memory };
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::get_current_process(&mut context)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
@@ -262,28 +262,28 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
registry.register_with_status("kernel32.dll", "GetProcessId", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory };
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u32 = handlers::get_process_id(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("kernel32.dll", "GetCurrentThread", ServiceStatus::Implemented, move |args, cpu, memory| {
|
||||
let _ = args;
|
||||
let mut context = ServiceContext { state: &s, memory };
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::get_current_thread(&mut context)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("kernel32.dll", "GetCurrentProcessId", ServiceStatus::Implemented, move |args, cpu, memory| {
|
||||
let _ = args;
|
||||
let mut context = ServiceContext { state: &s, memory };
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u32 = handlers::get_current_process_id(&mut context)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("kernel32.dll", "GetCurrentThreadId", ServiceStatus::Implemented, move |args, cpu, memory| {
|
||||
let _ = args;
|
||||
let mut context = ServiceContext { state: &s, memory };
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u32 = handlers::get_current_thread_id(&mut context)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
@@ -293,7 +293,7 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
let a0 = call.u32(0)?;
|
||||
let a1 = call.bool32(1)?;
|
||||
let a2 = call.u32(2)?;
|
||||
let mut context = ServiceContext { state: &s, memory };
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::open_thread(&mut context, a0, a1, a2)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
@@ -301,7 +301,7 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
registry.register_with_status("kernel32.dll", "GetThreadPriority", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory };
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: i32 = handlers::get_thread_priority(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
@@ -310,7 +310,7 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let a1 = call.i32(1)?;
|
||||
let mut context = ServiceContext { state: &s, memory };
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: bool = handlers::set_thread_priority(&mut context, a0, a1)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
@@ -318,7 +318,7 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
registry.register_with_status("kernel32.dll", "CloseHandle", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory };
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: bool = handlers::close_handle(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
@@ -326,14 +326,14 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
registry.register_with_status("kernel32.dll", "GetSystemTimeAsFileTime", ServiceStatus::Implemented, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.out::<8>(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory };
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let () = handlers::get_system_time_as_file_time(&mut context, a0)?;
|
||||
Ok(0)
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("kernel32.dll", "GetLastError", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let _ = args;
|
||||
let mut context = ServiceContext { state: &s, memory };
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u32 = handlers::get_last_error(&mut context)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
@@ -341,7 +341,7 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
registry.register_with_status("kernel32.dll", "SetLastError", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u32(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory };
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let () = handlers::set_last_error(&mut context, a0)?;
|
||||
Ok(0)
|
||||
});
|
||||
@@ -352,7 +352,7 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
let a1 = call.u64(1)?;
|
||||
let a2 = call.u32(2)?;
|
||||
let a3 = call.u32(3)?;
|
||||
let mut context = ServiceContext { state: &s, memory };
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: u64 = handlers::virtual_alloc(&mut context, a0, a1, a2, a3)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
@@ -362,7 +362,7 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
let a0 = call.u64(0)?;
|
||||
let a1 = call.u64(1)?;
|
||||
let a2 = call.u32(2)?;
|
||||
let mut context = ServiceContext { state: &s, memory };
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: bool = handlers::virtual_free(&mut context, a0, a1, a2)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
@@ -370,7 +370,7 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
registry.register_with_status("ucrtbase.dll", "sqrt", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.f64(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory };
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: crate::runtime::Float64 = handlers::sqrt(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
@@ -378,7 +378,7 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
registry.register_with_status("ucrtbase.dll", "sqrtf", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.f32(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory };
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: crate::runtime::Float32 = handlers::sqrtf(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
@@ -386,7 +386,7 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
registry.register_with_status("ucrtbase.dll", "fabs", ServiceStatus::Implemented, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.f64(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory };
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: crate::runtime::Float64 = handlers::fabs(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
@@ -394,7 +394,7 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
registry.register_with_status("ucrtbase.dll", "fabsf", ServiceStatus::Implemented, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.f32(0)?;
|
||||
let mut context = ServiceContext { state: &s, memory };
|
||||
let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base };
|
||||
let result: crate::runtime::Float32 = handlers::fabsf(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
|
||||
+339
-70
@@ -3,18 +3,34 @@
|
||||
//! Standard Windows and Xbox Scarlett Host Services Implementation for Xenora X15.
|
||||
//!
|
||||
//! Provides verifiable guest implementations of Windows NT and Xbox Scarlett APIs:
|
||||
//! - Time: `GetSystemTimeAsFileTime` (injected deterministic clock or real UTC)
|
||||
//! - Time: UTC file time and a monotonic performance counter
|
||||
//! - Process and thread identity and guest process priority boost policy
|
||||
//! - Error slots: `GetLastError`, `SetLastError`
|
||||
//! - Virtual memory: `VirtualAlloc`, `VirtualFree`
|
||||
//! - Xbox physical memory: `XMemAlloc`, `XMemFree`
|
||||
|
||||
mod crt;
|
||||
mod crt_callbacks;
|
||||
mod events;
|
||||
mod files;
|
||||
mod gdk_queue;
|
||||
mod heap;
|
||||
mod modules;
|
||||
mod platform_fixture;
|
||||
mod synch;
|
||||
pub mod sysinfo;
|
||||
mod task_fixture;
|
||||
mod winsock;
|
||||
|
||||
use crate::runtime::HResult;
|
||||
|
||||
use crate::cpu::ExitReason;
|
||||
use crate::imports::{ImportRegistry, ServiceStatus};
|
||||
use crate::memory::{ALLOCATION_GRANULARITY, GuestMemory, MemoryError, MemoryPermissions};
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Condvar, Mutex, OnceLock};
|
||||
use std::time::Instant;
|
||||
|
||||
const CURRENT_PROCESS: u64 = u64::MAX;
|
||||
const CURRENT_THREAD: u64 = u64::MAX - 1;
|
||||
@@ -28,32 +44,61 @@ const THREAD_QUERY_RIGHTS: u32 = 0x0040 | 0x0800;
|
||||
const THREAD_SET_RIGHTS: u32 = 0x0020 | 0x0400;
|
||||
const THREAD_SUPPORTED_RIGHTS: u32 = THREAD_QUERY_RIGHTS | THREAD_SET_RIGHTS | 0x0010_0000;
|
||||
const THREAD_PRIORITY_ERROR_RETURN: u64 = 0x7fff_ffff;
|
||||
const MAX_THREAD_HANDLES: usize = 1024;
|
||||
const MAX_OBJECT_HANDLES: usize = 1024;
|
||||
const DUPLICATE_SAME_ACCESS: u32 = 2;
|
||||
const HANDLE_API: &str = "api-ms-win-core-handle-l1-1-0.dll";
|
||||
const PAGE_SIZE: u64 = 4096;
|
||||
const MEM_COMMIT_RESERVE: u32 = 0x3000;
|
||||
const MEM_RELEASE: u32 = 0x8000;
|
||||
const ERROR_NOACCESS: u32 = 998;
|
||||
const KERNEL32: &str = "kernel32.dll";
|
||||
const SYSINFO_API: &str = "api-ms-win-core-sysinfo-l1-1-0.dll";
|
||||
const PROCESS_THREADS_V1: &str = "api-ms-win-core-processthreads-l1-1-0.dll";
|
||||
|
||||
const PERFORMANCE_FREQUENCY: u64 = 10_000_000;
|
||||
const MAX_PERFORMANCE_COUNT: u64 = i64::MAX as u64;
|
||||
|
||||
/// Clock trait for injecting deterministic time in tests or host time in production.
|
||||
pub trait Clock: Send + Sync {
|
||||
/// Return Windows 100-nanosecond intervals since January 1, 1601 (UTC).
|
||||
fn now_filetime(&self) -> u64;
|
||||
|
||||
/// Return elapsed monotonic time in 100-nanosecond ticks, capped at `i64::MAX`.
|
||||
fn performance_count(&self) -> u64 {
|
||||
static ORIGIN: OnceLock<Instant> = OnceLock::new();
|
||||
let ticks = ORIGIN.get_or_init(Instant::now).elapsed().as_nanos() / 100;
|
||||
ticks.min(u128::from(MAX_PERFORMANCE_COUNT)) as u64
|
||||
}
|
||||
|
||||
/// Suspend the calling guest thread for `intervals` 100-nanosecond ticks.
|
||||
fn sleep(&self, intervals: u64) {
|
||||
std::thread::sleep(std::time::Duration::from_nanos(
|
||||
intervals.saturating_mul(100),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// Deterministic test clock.
|
||||
pub struct MockClock {
|
||||
current: AtomicU64,
|
||||
performance_count: AtomicU64,
|
||||
}
|
||||
|
||||
impl MockClock {
|
||||
pub fn new(initial_filetime: u64) -> Self {
|
||||
Self {
|
||||
current: AtomicU64::new(initial_filetime),
|
||||
performance_count: AtomicU64::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn advance(&self, intervals: u64) {
|
||||
self.current.fetch_add(intervals, Ordering::SeqCst);
|
||||
self.performance_count
|
||||
.try_update(Ordering::SeqCst, Ordering::SeqCst, |count| {
|
||||
Some(count.saturating_add(intervals).min(MAX_PERFORMANCE_COUNT))
|
||||
})
|
||||
.expect("clock update always returns a value");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,6 +106,15 @@ impl Clock for MockClock {
|
||||
fn now_filetime(&self) -> u64 {
|
||||
self.current.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
fn performance_count(&self) -> u64 {
|
||||
self.performance_count.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// Sleeping advances the mock clock instead of waiting.
|
||||
fn sleep(&self, intervals: u64) {
|
||||
self.advance(intervals);
|
||||
}
|
||||
}
|
||||
|
||||
/// Host system UTC clock.
|
||||
@@ -83,22 +137,45 @@ impl Clock for SystemClock {
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct ThreadState {
|
||||
priority: i32,
|
||||
last_handle: u64,
|
||||
handles: BTreeMap<u64, u32>,
|
||||
enum GuestObject {
|
||||
Thread(u32),
|
||||
File(files::OpenFile),
|
||||
Search(files::Search),
|
||||
Waitable {
|
||||
state: Arc<Mutex<events::Waitable>>,
|
||||
access: u32,
|
||||
},
|
||||
}
|
||||
|
||||
impl ThreadState {
|
||||
#[derive(Default)]
|
||||
struct ObjectState {
|
||||
priority: i32,
|
||||
last_handle: u64,
|
||||
handles: BTreeMap<u64, GuestObject>,
|
||||
files: BTreeMap<String, Vec<u8>>,
|
||||
directories: BTreeSet<String>,
|
||||
}
|
||||
|
||||
impl ObjectState {
|
||||
fn next_handle(&self) -> Option<u64> {
|
||||
self.last_handle
|
||||
.checked_add(4)
|
||||
.filter(|_| self.handles.len() < MAX_OBJECT_HANDLES)
|
||||
}
|
||||
|
||||
fn insert_handle(&mut self, handle: u64, object: GuestObject) {
|
||||
self.handles.insert(handle, object);
|
||||
self.last_handle = handle;
|
||||
}
|
||||
|
||||
fn check_access(&self, handle: u64, required: u32) -> Result<(), u32> {
|
||||
if handle == CURRENT_THREAD {
|
||||
return Ok(());
|
||||
}
|
||||
match self.handles.get(&handle) {
|
||||
Some(access) if access & required != 0 => Ok(()),
|
||||
Some(_) => Err(ERROR_ACCESS_DENIED),
|
||||
None => Err(ERROR_INVALID_HANDLE),
|
||||
Some(GuestObject::Thread(access)) if access & required != 0 => Ok(()),
|
||||
Some(GuestObject::Thread(_)) => Err(ERROR_ACCESS_DENIED),
|
||||
_ => Err(ERROR_INVALID_HANDLE),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -106,11 +183,24 @@ impl ThreadState {
|
||||
/// State container for runtime services.
|
||||
pub struct ServicesState {
|
||||
pub clock: Arc<dyn Clock>,
|
||||
clock_origin: u64,
|
||||
pub process_id: u32,
|
||||
priority_boost_disabled: AtomicBool,
|
||||
pub thread_id: u32,
|
||||
thread: Mutex<ThreadState>,
|
||||
pub last_error: AtomicU32,
|
||||
/// Characteristics the guest is told it runs on. These are simulated and
|
||||
/// independent of the host; see [`sysinfo::HostCapabilities`] for the host.
|
||||
pub guest_profile: sysinfo::GuestSystemProfile,
|
||||
objects: Mutex<ObjectState>,
|
||||
last_errors: Mutex<BTreeMap<u64, u32>>,
|
||||
synch: Mutex<synch::Synch>,
|
||||
/// Functions registered with `atexit`, run in reverse order by `_cexit`.
|
||||
atexit: Mutex<Vec<u64>>,
|
||||
winsock: Mutex<winsock::Winsock>,
|
||||
task_fixture: Mutex<task_fixture::TaskFixture>,
|
||||
platform_fixture: Mutex<platform_fixture::PlatformFixture>,
|
||||
gdk_queues: Mutex<gdk_queue::QueueHandles>,
|
||||
gdk_queue_changed: Condvar,
|
||||
winsock_changed: Condvar,
|
||||
pub next_alloc_addr: AtomicU64,
|
||||
pub graphics: Arc<Mutex<crate::graphics::GraphicsContext>>,
|
||||
}
|
||||
@@ -118,33 +208,84 @@ pub struct ServicesState {
|
||||
impl ServicesState {
|
||||
pub fn new(clock: Arc<dyn Clock>) -> Self {
|
||||
Self {
|
||||
clock_origin: clock.performance_count(),
|
||||
clock,
|
||||
priority_boost_disabled: AtomicBool::new(false),
|
||||
process_id: 0x4100, // Synthetic process ID
|
||||
thread_id: 0x4104, // Synthetic main thread ID
|
||||
thread: Mutex::new(ThreadState::default()),
|
||||
last_error: AtomicU32::new(0),
|
||||
guest_profile: sysinfo::GuestSystemProfile::default(),
|
||||
objects: Mutex::new(ObjectState::default()),
|
||||
last_errors: Mutex::default(),
|
||||
synch: Mutex::default(),
|
||||
atexit: Mutex::default(),
|
||||
winsock: Mutex::default(),
|
||||
task_fixture: Mutex::default(),
|
||||
platform_fixture: Mutex::default(),
|
||||
gdk_queues: Mutex::default(),
|
||||
gdk_queue_changed: Condvar::new(),
|
||||
winsock_changed: Condvar::new(),
|
||||
next_alloc_addr: AtomicU64::new(0x0000_0002_0000_0000), // 8GB guest heap
|
||||
graphics: Arc::new(Mutex::new(crate::graphics::GraphicsContext::new())),
|
||||
}
|
||||
}
|
||||
fn uptime_millis(&self) -> u64 {
|
||||
let ticks = self
|
||||
.clock
|
||||
.performance_count()
|
||||
.saturating_sub(self.clock_origin);
|
||||
ticks / (PERFORMANCE_FREQUENCY / 1_000)
|
||||
}
|
||||
|
||||
/// The scheduling policy recorded for the synthetic process.
|
||||
pub fn priority_boost_disabled(&self) -> bool {
|
||||
self.priority_boost_disabled.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// Read the last-error value for a guest thread's TEB.
|
||||
pub fn last_error(&self, teb: u64) -> u32 {
|
||||
self.last_errors
|
||||
.lock()
|
||||
.expect("guest last-error state")
|
||||
.get(&teb)
|
||||
.copied()
|
||||
.unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Forget the last-error value of a guest thread that has ended, so a
|
||||
/// later thread given the same TEB address starts at zero. Returns
|
||||
/// whether a nonzero value was dropped.
|
||||
///
|
||||
/// Each service call names its own TEB and the values sit behind one
|
||||
/// lock, so calls for different threads may run concurrently. Retire a
|
||||
/// TEB only once no service call for that thread is still running.
|
||||
pub fn retire_thread_last_error(&self, teb: u64) -> bool {
|
||||
self.last_errors
|
||||
.lock()
|
||||
.expect("guest last-error state")
|
||||
.remove(&teb)
|
||||
.is_some()
|
||||
}
|
||||
|
||||
fn set_last_error(&self, teb: u64, error: u32) {
|
||||
let mut errors = self.last_errors.lock().expect("guest last-error state");
|
||||
if error == 0 {
|
||||
errors.remove(&teb);
|
||||
} else {
|
||||
errors.insert(teb, error);
|
||||
}
|
||||
}
|
||||
|
||||
/// Record a guest error and return the documented failure value.
|
||||
fn fail<T>(&self, error: u32, value: T) -> Result<T, ExitReason> {
|
||||
self.last_error.store(error, Ordering::SeqCst);
|
||||
fn fail<T>(&self, teb: u64, error: u32, value: T) -> Result<T, ExitReason> {
|
||||
self.set_last_error(teb, error);
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn is_current_process(&self, handle: u64) -> bool {
|
||||
fn is_current_process(&self, teb: u64, handle: u64) -> bool {
|
||||
if handle == CURRENT_PROCESS {
|
||||
return true;
|
||||
}
|
||||
self.last_error
|
||||
.store(ERROR_INVALID_HANDLE, Ordering::SeqCst);
|
||||
self.set_last_error(teb, ERROR_INVALID_HANDLE);
|
||||
false
|
||||
}
|
||||
}
|
||||
@@ -154,6 +295,137 @@ impl ServicesState {
|
||||
pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc<ServicesState>) {
|
||||
crate::runtime_table::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)?;
|
||||
let thread = s.objects.lock().expect("guest object state");
|
||||
if let Err(error) = thread.check_access(handle, THREAD_QUERY_RIGHTS) {
|
||||
return s.fail(cpu.gs_base, error, 0);
|
||||
}
|
||||
Ok(u64::from(s.thread_id))
|
||||
});
|
||||
|
||||
registry.alias(PROCESS_THREADS_V1, KERNEL32, "GetThreadId");
|
||||
registry.set_status(KERNEL32, "GetThreadId", ServiceStatus::Partial);
|
||||
|
||||
let s = state.clone();
|
||||
registry.register(KERNEL32, "DuplicateHandle", move |args, cpu, mem| {
|
||||
let source_process = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
let source = args.get(1, mem).map_err(ExitReason::MemoryFault)?;
|
||||
let target_process = args.get(2, mem).map_err(ExitReason::MemoryFault)?;
|
||||
let output = args.get(3, mem).map_err(ExitReason::MemoryFault)?;
|
||||
let desired = args.get(4, mem).map_err(ExitReason::MemoryFault)? as u32;
|
||||
let inherit = args.get(5, mem).map_err(ExitReason::MemoryFault)? as u32;
|
||||
let options = args.get(6, mem).map_err(ExitReason::MemoryFault)? as u32;
|
||||
|
||||
if source_process != CURRENT_PROCESS || target_process != CURRENT_PROCESS {
|
||||
return s.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0);
|
||||
}
|
||||
if inherit != 0 || options & !DUPLICATE_SAME_ACCESS != 0 || source == CURRENT_PROCESS {
|
||||
return s.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
let mut thread = s.objects.lock().expect("guest object state");
|
||||
let (granted, mut object) = if source == CURRENT_THREAD {
|
||||
(
|
||||
THREAD_SUPPORTED_RIGHTS,
|
||||
GuestObject::Thread(THREAD_SUPPORTED_RIGHTS),
|
||||
)
|
||||
} else {
|
||||
match thread.handles.get(&source) {
|
||||
Some(GuestObject::Thread(rights)) => (*rights, GuestObject::Thread(*rights)),
|
||||
Some(GuestObject::Waitable { state, access }) => (
|
||||
*access,
|
||||
GuestObject::Waitable {
|
||||
state: Arc::clone(state),
|
||||
access: *access,
|
||||
},
|
||||
),
|
||||
Some(GuestObject::File(file)) => (file.access, GuestObject::File(file.clone())),
|
||||
Some(GuestObject::Search(_)) => return s.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, 0),
|
||||
None => return s.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0),
|
||||
}
|
||||
};
|
||||
let access = if options & DUPLICATE_SAME_ACCESS != 0 {
|
||||
granted
|
||||
} else if desired & !granted == 0 {
|
||||
desired
|
||||
} else {
|
||||
return s.fail(cpu.gs_base, ERROR_ACCESS_DENIED, 0);
|
||||
};
|
||||
let Some(handle) = thread.next_handle() else {
|
||||
return s.fail(cpu.gs_base, ERROR_NOT_ENOUGH_MEMORY, 0);
|
||||
};
|
||||
if output == 0 || mem.write_u64(output, handle).is_err() {
|
||||
return s.fail(cpu.gs_base, ERROR_NOACCESS, 0);
|
||||
}
|
||||
match &mut object {
|
||||
GuestObject::Thread(rights) | GuestObject::Waitable { access: rights, .. } => {
|
||||
*rights = access
|
||||
}
|
||||
GuestObject::File(file) => file.access = access,
|
||||
GuestObject::Search(_) => unreachable!("search handles cannot be duplicated"),
|
||||
}
|
||||
thread.insert_handle(handle, object);
|
||||
Ok(1)
|
||||
});
|
||||
registry.alias(HANDLE_API, KERNEL32, "DuplicateHandle");
|
||||
registry.set_status(KERNEL32, "DuplicateHandle", ServiceStatus::Partial);
|
||||
|
||||
events::register(registry, &state);
|
||||
synch::register(registry, &state);
|
||||
sysinfo::register(registry, &state);
|
||||
files::register(registry, &state);
|
||||
crt::register(registry);
|
||||
crt::register_heap(registry);
|
||||
crt::register_errno(registry);
|
||||
crt::register_conversions(registry);
|
||||
crt_callbacks::register(registry, &state);
|
||||
heap::register(registry, &state);
|
||||
|
||||
let s = state.clone();
|
||||
registry.register(
|
||||
KERNEL32,
|
||||
"QueryPerformanceCounter",
|
||||
move |args, cpu, mem| {
|
||||
let ptr = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
if ptr == 0 || mem.write_u64(ptr, s.clock.performance_count()).is_err() {
|
||||
return s.fail(cpu.gs_base, ERROR_NOACCESS, 0);
|
||||
}
|
||||
Ok(1)
|
||||
},
|
||||
);
|
||||
|
||||
let s = state.clone();
|
||||
registry.register(
|
||||
KERNEL32,
|
||||
"QueryPerformanceFrequency",
|
||||
move |args, cpu, mem| {
|
||||
let ptr = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
if ptr == 0 || mem.write_u64(ptr, PERFORMANCE_FREQUENCY).is_err() {
|
||||
return s.fail(cpu.gs_base, ERROR_NOACCESS, 0);
|
||||
}
|
||||
Ok(1)
|
||||
},
|
||||
);
|
||||
|
||||
for symbol in ["QueryPerformanceCounter", "QueryPerformanceFrequency"] {
|
||||
registry.alias("api-ms-win-core-profile-l1-1-0.dll", KERNEL32, symbol);
|
||||
}
|
||||
|
||||
let s = state.clone();
|
||||
registry.register(KERNEL32, "GetTickCount", move |_, _, _| {
|
||||
Ok(u64::from(s.uptime_millis() as u32))
|
||||
});
|
||||
|
||||
let s = state.clone();
|
||||
registry.register(KERNEL32, "GetTickCount64", move |_, _, _| {
|
||||
Ok(s.uptime_millis())
|
||||
});
|
||||
|
||||
for symbol in ["GetTickCount", "GetTickCount64"] {
|
||||
registry.alias(SYSINFO_API, KERNEL32, symbol);
|
||||
}
|
||||
|
||||
// 8. XMemAlloc(dwSize, dwAllocAttributes) -> LPVOID (Xbox Scarlett allocator in xmem.dll)
|
||||
let s = state.clone();
|
||||
let handler = move |args: &crate::imports::Win64Args,
|
||||
@@ -206,7 +478,7 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc<Serv
|
||||
-> Result<u64, ExitReason> {
|
||||
let pp_device = args.get(3, mem).map_err(ExitReason::MemoryFault)?;
|
||||
if pp_device == 0 {
|
||||
return Ok(0x80070057); // E_INVALIDARG
|
||||
return Ok(HResult::from_win32(ERROR_INVALID_PARAMETER).guest_return());
|
||||
}
|
||||
let mut gfx = s_gfx
|
||||
.lock()
|
||||
@@ -215,9 +487,9 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc<Serv
|
||||
Ok(handle) => {
|
||||
mem.write_u64(pp_device, handle.to_u64())
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
Ok(0) // S_OK
|
||||
Ok(HResult::OK.guest_return())
|
||||
}
|
||||
Err(_) => Ok(0x80004005), // E_FAIL
|
||||
Err(_) => Ok(HResult::FAIL.guest_return()),
|
||||
}
|
||||
};
|
||||
registry.register("xenora_fixture.dll", "CreateGraphicsDevice", handler);
|
||||
@@ -240,7 +512,7 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc<Serv
|
||||
-> Result<u64, ExitReason> {
|
||||
let vtx_addr = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
if vtx_addr == 0 {
|
||||
return Ok(0x80070057); // E_INVALIDARG
|
||||
return Ok(HResult::from_win32(ERROR_INVALID_PARAMETER).guest_return());
|
||||
}
|
||||
let clear_raw = args.get(1, mem).map_err(ExitReason::MemoryFault)? as u32;
|
||||
let clear_color = [
|
||||
@@ -317,7 +589,7 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc<Serv
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
}
|
||||
|
||||
Ok(0) // S_OK
|
||||
Ok(HResult::OK.guest_return())
|
||||
};
|
||||
registry.register("xenora_fixture.dll", "SubmitGuestDraw", handler);
|
||||
registry.set_status(
|
||||
@@ -325,6 +597,11 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc<Serv
|
||||
"SubmitGuestDraw",
|
||||
ServiceStatus::Implemented,
|
||||
);
|
||||
winsock::register(registry, &state);
|
||||
task_fixture::register(registry, &state);
|
||||
platform_fixture::register(registry, &state);
|
||||
gdk_queue::register(registry, &state);
|
||||
modules::register(registry, &state);
|
||||
}
|
||||
|
||||
/// Implementations behind the generated adapters. A failure the guest can
|
||||
@@ -341,7 +618,7 @@ pub(crate) mod handlers {
|
||||
process: u64,
|
||||
disable: bool,
|
||||
) -> Outcome<bool> {
|
||||
if !context.state.is_current_process(process) {
|
||||
if !context.state.is_current_process(context.teb, process) {
|
||||
return Ok(false);
|
||||
}
|
||||
context
|
||||
@@ -356,12 +633,12 @@ pub(crate) mod handlers {
|
||||
process: u64,
|
||||
disabled: OutPtr<4>,
|
||||
) -> Outcome<bool> {
|
||||
if !context.state.is_current_process(process) {
|
||||
if !context.state.is_current_process(context.teb, process) {
|
||||
return Ok(false);
|
||||
}
|
||||
let value = u32::from(context.state.priority_boost_disabled());
|
||||
if disabled.store(context.memory, value.to_le_bytes()).is_err() {
|
||||
return context.state.fail(ERROR_NOACCESS, false);
|
||||
return context.state.fail(context.teb, ERROR_NOACCESS, false);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
@@ -371,7 +648,7 @@ pub(crate) mod handlers {
|
||||
}
|
||||
|
||||
pub fn get_process_id(context: &mut ServiceContext<'_>, process: u64) -> Outcome<u32> {
|
||||
Ok(if context.state.is_current_process(process) {
|
||||
Ok(if context.state.is_current_process(context.teb, process) {
|
||||
context.state.process_id
|
||||
} else {
|
||||
0
|
||||
@@ -398,30 +675,25 @@ pub(crate) mod handlers {
|
||||
) -> Outcome<u64> {
|
||||
let state = context.state;
|
||||
if id != state.thread_id {
|
||||
return state.fail(ERROR_INVALID_PARAMETER, 0);
|
||||
return state.fail(context.teb, ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
if inherit || access & !THREAD_SUPPORTED_RIGHTS != 0 {
|
||||
return state.fail(ERROR_NOT_SUPPORTED, 0);
|
||||
return state.fail(context.teb, ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
let mut thread = state.thread.lock().expect("guest thread state");
|
||||
let Some(handle) = thread
|
||||
.last_handle
|
||||
.checked_add(4)
|
||||
.filter(|_| thread.handles.len() < MAX_THREAD_HANDLES)
|
||||
else {
|
||||
return state.fail(ERROR_NOT_ENOUGH_MEMORY, 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.handles.insert(handle, access);
|
||||
thread.last_handle = handle;
|
||||
thread.insert_handle(handle, GuestObject::Thread(access));
|
||||
Ok(handle)
|
||||
}
|
||||
|
||||
pub fn get_thread_priority(context: &mut ServiceContext<'_>, handle: u64) -> Outcome<i32> {
|
||||
let thread = context.state.thread.lock().expect("guest thread state");
|
||||
let thread = context.state.objects.lock().expect("guest object state");
|
||||
if let Err(error) = thread.check_access(handle, THREAD_QUERY_RIGHTS) {
|
||||
return context
|
||||
.state
|
||||
.fail(error, THREAD_PRIORITY_ERROR_RETURN as i32);
|
||||
.fail(context.teb, error, THREAD_PRIORITY_ERROR_RETURN as i32);
|
||||
}
|
||||
Ok(thread.priority)
|
||||
}
|
||||
@@ -432,34 +704,31 @@ pub(crate) mod handlers {
|
||||
priority: i32,
|
||||
) -> Outcome<bool> {
|
||||
let state = context.state;
|
||||
let mut thread = state.thread.lock().expect("guest thread state");
|
||||
let mut thread = state.objects.lock().expect("guest object state");
|
||||
if let Err(error) = thread.check_access(handle, THREAD_SET_RIGHTS) {
|
||||
return state.fail(error, false);
|
||||
return state.fail(context.teb, error, false);
|
||||
}
|
||||
if matches!(priority, 0x0001_0000 | 0x0002_0000) {
|
||||
return state.fail(ERROR_NOT_SUPPORTED, false);
|
||||
return state.fail(context.teb, ERROR_NOT_SUPPORTED, false);
|
||||
}
|
||||
if !matches!(priority, -15 | -2..=2 | 15) {
|
||||
return state.fail(ERROR_INVALID_PARAMETER, false);
|
||||
return state.fail(context.teb, ERROR_INVALID_PARAMETER, false);
|
||||
}
|
||||
thread.priority = priority;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub fn close_handle(context: &mut ServiceContext<'_>, handle: u64) -> Outcome<bool> {
|
||||
let mut objects = context.state.objects.lock().expect("guest object state");
|
||||
if matches!(objects.handles.get(&handle), Some(GuestObject::Search(_))) {
|
||||
return context.state.fail(context.teb, ERROR_INVALID_HANDLE, false);
|
||||
}
|
||||
let closed = matches!(handle, CURRENT_PROCESS | CURRENT_THREAD)
|
||||
|| context
|
||||
.state
|
||||
.thread
|
||||
.lock()
|
||||
.expect("guest thread state")
|
||||
.handles
|
||||
.remove(&handle)
|
||||
.is_some();
|
||||
|| objects.handles.remove(&handle).is_some();
|
||||
if closed {
|
||||
Ok(true)
|
||||
} else {
|
||||
context.state.fail(ERROR_INVALID_HANDLE, false)
|
||||
context.state.fail(context.teb, ERROR_INVALID_HANDLE, false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -473,11 +742,11 @@ pub(crate) mod handlers {
|
||||
}
|
||||
|
||||
pub fn get_last_error(context: &mut ServiceContext<'_>) -> Outcome<u32> {
|
||||
Ok(context.state.last_error.load(Ordering::SeqCst))
|
||||
Ok(context.state.last_error(context.teb))
|
||||
}
|
||||
|
||||
pub fn set_last_error(context: &mut ServiceContext<'_>, code: u32) -> Outcome<()> {
|
||||
context.state.last_error.store(code, Ordering::SeqCst);
|
||||
context.state.set_last_error(context.teb, code);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -490,28 +759,28 @@ pub(crate) mod handlers {
|
||||
) -> Outcome<u64> {
|
||||
let state = context.state;
|
||||
if size == 0 {
|
||||
return state.fail(ERROR_INVALID_PARAMETER, 0);
|
||||
return state.fail(context.teb, ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
if kind != MEM_COMMIT_RESERVE {
|
||||
return state.fail(ERROR_NOT_SUPPORTED, 0);
|
||||
return state.fail(context.teb, ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
// Executable allocations require guest translation cache invalidation.
|
||||
let permissions = match protect {
|
||||
0x01 => MemoryPermissions::NO_ACCESS,
|
||||
0x02 => MemoryPermissions::READ_ONLY,
|
||||
0x04 => MemoryPermissions::READ_WRITE,
|
||||
_ => return state.fail(ERROR_INVALID_PARAMETER, 0),
|
||||
_ => return state.fail(context.teb, ERROR_INVALID_PARAMETER, 0),
|
||||
};
|
||||
let base = requested & !(ALLOCATION_GRANULARITY - 1);
|
||||
if requested != 0 && base == 0 {
|
||||
return state.fail(ERROR_INVALID_ADDRESS, 0);
|
||||
return state.fail(context.teb, ERROR_INVALID_ADDRESS, 0);
|
||||
}
|
||||
let Some(size) = size
|
||||
.checked_add(requested - base)
|
||||
.and_then(|span| span.checked_next_multiple_of(PAGE_SIZE))
|
||||
.and_then(|span| usize::try_from(span).ok())
|
||||
else {
|
||||
return state.fail(ERROR_INVALID_PARAMETER, 0);
|
||||
return state.fail(context.teb, ERROR_INVALID_PARAMETER, 0);
|
||||
};
|
||||
match context
|
||||
.memory
|
||||
@@ -519,9 +788,9 @@ pub(crate) mod handlers {
|
||||
{
|
||||
Ok(address) => Ok(address),
|
||||
Err(MemoryError::OverlappingRegion { .. } | MemoryError::Overflow) => {
|
||||
state.fail(ERROR_INVALID_ADDRESS, 0)
|
||||
state.fail(context.teb, ERROR_INVALID_ADDRESS, 0)
|
||||
}
|
||||
Err(_) => state.fail(ERROR_NOT_ENOUGH_MEMORY, 0),
|
||||
Err(_) => state.fail(context.teb, ERROR_NOT_ENOUGH_MEMORY, 0),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -533,13 +802,13 @@ pub(crate) mod handlers {
|
||||
) -> Outcome<bool> {
|
||||
let state = context.state;
|
||||
if kind != MEM_RELEASE {
|
||||
return state.fail(ERROR_NOT_SUPPORTED, false);
|
||||
return state.fail(context.teb, ERROR_NOT_SUPPORTED, false);
|
||||
}
|
||||
if size != 0 {
|
||||
return state.fail(ERROR_INVALID_PARAMETER, false);
|
||||
return state.fail(context.teb, ERROR_INVALID_PARAMETER, false);
|
||||
}
|
||||
if !context.memory.release_virtual_allocation(address) {
|
||||
return state.fail(ERROR_INVALID_ADDRESS, false);
|
||||
return state.fail(context.teb, ERROR_INVALID_ADDRESS, false);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,426 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! C runtime services that operate on checked guest memory.
|
||||
|
||||
use crate::cpu::ExitReason;
|
||||
use crate::imports::{ImportRegistry, ServiceStatus, Win64Args};
|
||||
use crate::memory::{GuestMemory, MemoryError, PROCESS_HEAP};
|
||||
|
||||
const SCAN_BUDGET: u64 = 1_048_576;
|
||||
const UCRT: &str = "ucrtbase.dll";
|
||||
const CRT_STRING_API: &str = "api-ms-win-crt-string-l1-1-0.dll";
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum StringUnit {
|
||||
Byte,
|
||||
Wide,
|
||||
}
|
||||
|
||||
impl StringUnit {
|
||||
fn width(self) -> u64 {
|
||||
match self {
|
||||
Self::Byte => 1,
|
||||
Self::Wide => 2,
|
||||
}
|
||||
}
|
||||
|
||||
fn read(self, memory: &GuestMemory, base: u64, offset: u64) -> Result<u16, ExitReason> {
|
||||
if base == 0 {
|
||||
return Err(ExitReason::MemoryFault(MemoryError::UnmappedAddress(0)));
|
||||
}
|
||||
let address = base
|
||||
.checked_add(offset * self.width())
|
||||
.ok_or(ExitReason::MemoryFault(MemoryError::Overflow))?;
|
||||
match self {
|
||||
Self::Byte => memory.read_u8(address).map(u16::from),
|
||||
Self::Wide => memory.read_u16(address),
|
||||
}
|
||||
.map_err(ExitReason::MemoryFault)
|
||||
}
|
||||
}
|
||||
|
||||
fn string_length(
|
||||
memory: &GuestMemory,
|
||||
address: u64,
|
||||
limit: u64,
|
||||
unit: StringUnit,
|
||||
) -> Result<u64, ExitReason> {
|
||||
let budget = SCAN_BUDGET / unit.width();
|
||||
for offset in 0..limit.min(budget) {
|
||||
if unit.read(memory, address, offset)? == 0 {
|
||||
return Ok(offset);
|
||||
}
|
||||
}
|
||||
if limit <= budget {
|
||||
return Ok(limit);
|
||||
}
|
||||
Err(ExitReason::IllegalInstruction(0xFE))
|
||||
}
|
||||
|
||||
fn compare_strings(
|
||||
memory: &GuestMemory,
|
||||
left: u64,
|
||||
right: u64,
|
||||
limit: u64,
|
||||
unit: StringUnit,
|
||||
) -> Result<u64, ExitReason> {
|
||||
let budget = SCAN_BUDGET / unit.width();
|
||||
for offset in 0..limit.min(budget) {
|
||||
let a = unit.read(memory, left, offset)?;
|
||||
let b = unit.read(memory, right, offset)?;
|
||||
if a != b || a == 0 {
|
||||
return Ok(u64::from((i32::from(a) - i32::from(b)) as u32));
|
||||
}
|
||||
}
|
||||
if limit <= budget {
|
||||
return Ok(0);
|
||||
}
|
||||
Err(ExitReason::IllegalInstruction(0xFE))
|
||||
}
|
||||
|
||||
fn transfer_buffer(count: u64, fill: u8) -> Result<Vec<u8>, ExitReason> {
|
||||
if count > SCAN_BUDGET {
|
||||
return Err(ExitReason::IllegalInstruction(0xFE));
|
||||
}
|
||||
let count = count as usize;
|
||||
let mut buffer = Vec::new();
|
||||
buffer
|
||||
.try_reserve_exact(count)
|
||||
.map_err(|_| ExitReason::MemoryFault(MemoryError::AllocationFailed))?;
|
||||
buffer.resize(count, fill);
|
||||
Ok(buffer)
|
||||
}
|
||||
|
||||
pub(super) fn register(registry: &mut ImportRegistry) {
|
||||
for (length, bounded_length, compare, bounded_compare, unit) in [
|
||||
("strlen", "strnlen", "strcmp", "strncmp", StringUnit::Byte),
|
||||
("wcslen", "wcsnlen", "wcscmp", "wcsncmp", StringUnit::Wide),
|
||||
] {
|
||||
registry.register(UCRT, length, move |args, _, memory| {
|
||||
string_length(memory, args.rcx, u64::MAX, unit)
|
||||
});
|
||||
registry.register(UCRT, bounded_length, move |args, _, memory| {
|
||||
string_length(memory, args.rcx, args.rdx, unit)
|
||||
});
|
||||
registry.register(UCRT, compare, move |args, _, memory| {
|
||||
compare_strings(memory, args.rcx, args.rdx, u64::MAX, unit)
|
||||
});
|
||||
registry.register(UCRT, bounded_compare, move |args, _, memory| {
|
||||
compare_strings(memory, args.rcx, args.rdx, args.r8, unit)
|
||||
});
|
||||
for symbol in [length, bounded_length, compare, bounded_compare] {
|
||||
registry.alias(CRT_STRING_API, UCRT, symbol);
|
||||
registry.set_status(UCRT, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
}
|
||||
|
||||
registry.register(UCRT, "memset", |args, _, memory| {
|
||||
if args.r8 != 0 {
|
||||
let buffer = transfer_buffer(args.r8, args.rdx as u8)?;
|
||||
memory
|
||||
.write_bytes(args.rcx, &buffer)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
}
|
||||
Ok(args.rcx)
|
||||
});
|
||||
|
||||
for symbol in ["memcpy", "memmove"] {
|
||||
registry.register(UCRT, symbol, |args, _, memory| {
|
||||
if args.r8 != 0 {
|
||||
let mut buffer = transfer_buffer(args.r8, 0)?;
|
||||
memory
|
||||
.read_bytes(args.rdx, &mut buffer)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
memory
|
||||
.write_bytes(args.rcx, &buffer)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
}
|
||||
Ok(args.rcx)
|
||||
});
|
||||
}
|
||||
|
||||
registry.register(UCRT, "memcmp", |args, _, memory| {
|
||||
if args.r8 == 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
let mut left = transfer_buffer(args.r8, 0)?;
|
||||
let mut right = transfer_buffer(args.r8, 0)?;
|
||||
memory
|
||||
.read_bytes(args.rcx, &mut left)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
memory
|
||||
.read_bytes(args.rdx, &mut right)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
let result = left
|
||||
.iter()
|
||||
.zip(right)
|
||||
.find_map(|(&a, b)| (a != b).then_some(i32::from(a) - i32::from(b)))
|
||||
.unwrap_or(0);
|
||||
Ok(u64::from(result as u32))
|
||||
});
|
||||
|
||||
for symbol in ["memset", "memcpy", "memmove", "memcmp"] {
|
||||
registry.alias(CRT_STRING_API, UCRT, symbol);
|
||||
registry.set_status(UCRT, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
}
|
||||
|
||||
const ENOMEM: u32 = 12;
|
||||
const EINVAL: u32 = 22;
|
||||
|
||||
fn set_errno(memory: &mut GuestMemory, teb: u64, error: u32) -> Result<(), ExitReason> {
|
||||
let address = memory
|
||||
.crt_errno_address(teb)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
memory
|
||||
.write_u32(address, error)
|
||||
.map_err(ExitReason::MemoryFault)
|
||||
}
|
||||
|
||||
fn allocation_result(
|
||||
memory: &mut GuestMemory,
|
||||
teb: u64,
|
||||
result: Result<u64, MemoryError>,
|
||||
) -> Result<u64, ExitReason> {
|
||||
match result {
|
||||
Ok(address) => Ok(address),
|
||||
Err(_) => {
|
||||
set_errno(memory, teb, ENOMEM)?;
|
||||
Ok(0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const ERANGE: u32 = 34;
|
||||
|
||||
fn parse_integer(
|
||||
memory: &mut GuestMemory,
|
||||
args: &Win64Args,
|
||||
teb: u64,
|
||||
signed: bool,
|
||||
wide_result: bool,
|
||||
unit: StringUnit,
|
||||
) -> Result<u64, ExitReason> {
|
||||
let (address, end, mut radix) = (args.rcx, args.rdx, args.r8 as u32);
|
||||
if address == 0 || (radix != 0 && !(2..=36).contains(&radix)) {
|
||||
if end != 0 {
|
||||
memory
|
||||
.write_u64(end, address)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
}
|
||||
set_errno(memory, teb, EINVAL)?;
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let read = |index| {
|
||||
if index >= SCAN_BUDGET / unit.width() {
|
||||
return Err(ExitReason::IllegalInstruction(0xFE));
|
||||
}
|
||||
unit.read(memory, address, index)
|
||||
.map(|value| char::from_u32(u32::from(value)).unwrap_or(char::REPLACEMENT_CHARACTER))
|
||||
};
|
||||
let mut index = 0;
|
||||
let mut next = read(index)?;
|
||||
while matches!(next, ' ' | '\t' | '\n' | '\r' | '\x0b' | '\x0c') {
|
||||
index += 1;
|
||||
next = read(index)?;
|
||||
}
|
||||
let negative = next == '-';
|
||||
if matches!(next, '+' | '-') {
|
||||
index += 1;
|
||||
next = read(index)?;
|
||||
}
|
||||
if next == '0'
|
||||
&& matches!(radix, 0 | 16)
|
||||
&& matches!(read(index + 1)?, 'x' | 'X')
|
||||
&& read(index + 2)?.is_ascii_hexdigit()
|
||||
{
|
||||
radix = 16;
|
||||
index += 2;
|
||||
next = read(index)?;
|
||||
}
|
||||
if radix == 0 {
|
||||
radix = if next == '0' { 8 } else { 10 };
|
||||
}
|
||||
|
||||
let limit = match (wide_result, signed) {
|
||||
(false, false) => u64::from(u32::MAX),
|
||||
(false, true) => i32::MAX as u64 + u64::from(negative),
|
||||
(true, false) => u64::MAX,
|
||||
(true, true) => i64::MAX as u64 + u64::from(negative),
|
||||
};
|
||||
let start = index;
|
||||
let mut value = 0u64;
|
||||
let mut overflow = false;
|
||||
while let Some(digit) = next.to_digit(radix) {
|
||||
match value
|
||||
.checked_mul(u64::from(radix))
|
||||
.and_then(|v| v.checked_add(u64::from(digit)))
|
||||
{
|
||||
Some(v) if v <= limit => value = v,
|
||||
_ => overflow = true,
|
||||
}
|
||||
index += 1;
|
||||
next = read(index)?;
|
||||
}
|
||||
let consumed = if start == index { 0 } else { index };
|
||||
if end != 0 {
|
||||
let pointer = address
|
||||
.checked_add(consumed * unit.width())
|
||||
.ok_or(ExitReason::MemoryFault(MemoryError::Overflow))?;
|
||||
memory
|
||||
.write_u64(end, pointer)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
}
|
||||
if overflow {
|
||||
set_errno(memory, teb, ERANGE)?;
|
||||
value = limit;
|
||||
}
|
||||
if negative && (!overflow || signed) {
|
||||
value = value.wrapping_neg();
|
||||
}
|
||||
Ok(if wide_result {
|
||||
value
|
||||
} else {
|
||||
u64::from(value as u32)
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn register_conversions(registry: &mut ImportRegistry) {
|
||||
for (symbol, signed, wide_result, unit) in [
|
||||
("strtol", true, false, StringUnit::Byte),
|
||||
("strtoul", false, false, StringUnit::Byte),
|
||||
("wcstol", true, false, StringUnit::Wide),
|
||||
("wcstoul", false, false, StringUnit::Wide),
|
||||
("strtoll", true, true, StringUnit::Byte),
|
||||
("strtoull", false, true, StringUnit::Byte),
|
||||
("wcstoll", true, true, StringUnit::Wide),
|
||||
("wcstoull", false, true, StringUnit::Wide),
|
||||
("_strtoi64", true, true, StringUnit::Byte),
|
||||
("_strtoui64", false, true, StringUnit::Byte),
|
||||
("_wcstoi64", true, true, StringUnit::Wide),
|
||||
("_wcstoui64", false, true, StringUnit::Wide),
|
||||
] {
|
||||
registry.register(UCRT, symbol, move |args, cpu, memory| {
|
||||
parse_integer(memory, args, cpu.gs_base, signed, wide_result, unit)
|
||||
});
|
||||
registry.alias("api-ms-win-crt-convert-l1-1-0.dll", UCRT, symbol);
|
||||
registry.set_status(UCRT, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn register_errno(registry: &mut ImportRegistry) {
|
||||
registry.register(UCRT, "_errno", |_, cpu, memory| {
|
||||
memory
|
||||
.crt_errno_address(cpu.gs_base)
|
||||
.map_err(ExitReason::MemoryFault)
|
||||
});
|
||||
registry.register(UCRT, "_set_errno", |args, cpu, memory| {
|
||||
set_errno(memory, cpu.gs_base, args.rcx as u32)?;
|
||||
Ok(0)
|
||||
});
|
||||
registry.register(UCRT, "_get_errno", |args, cpu, memory| {
|
||||
if args.rcx == 0 {
|
||||
set_errno(memory, cpu.gs_base, EINVAL)?;
|
||||
return Ok(u64::from(EINVAL));
|
||||
}
|
||||
let address = memory
|
||||
.crt_errno_address(cpu.gs_base)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
let value = memory.read_u32(address).map_err(ExitReason::MemoryFault)?;
|
||||
memory
|
||||
.write_u32(args.rcx, value)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
Ok(0)
|
||||
});
|
||||
for symbol in ["_errno", "_set_errno", "_get_errno"] {
|
||||
registry.alias("api-ms-win-crt-runtime-l1-1-0.dll", UCRT, symbol);
|
||||
registry.set_status(UCRT, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn register_heap(registry: &mut ImportRegistry) {
|
||||
registry.register(UCRT, "malloc", |args, cpu, memory| {
|
||||
let result = memory.map_heap_allocation(PROCESS_HEAP, args.rcx.max(1) as usize);
|
||||
allocation_result(memory, cpu.gs_base, result)
|
||||
});
|
||||
registry.register(UCRT, "calloc", |args, cpu, memory| {
|
||||
let result = args
|
||||
.rcx
|
||||
.checked_mul(args.rdx)
|
||||
.ok_or(MemoryError::AllocationFailed)
|
||||
.and_then(|size| memory.map_heap_allocation(PROCESS_HEAP, size.max(1) as usize));
|
||||
allocation_result(memory, cpu.gs_base, result)
|
||||
});
|
||||
registry.register(UCRT, "realloc", |args, cpu, memory| {
|
||||
let address = args.rcx;
|
||||
let size = args.rdx;
|
||||
if address == 0 {
|
||||
let result = memory.map_heap_allocation(PROCESS_HEAP, size.max(1) as usize);
|
||||
return allocation_result(memory, cpu.gs_base, result);
|
||||
}
|
||||
if size == 0 {
|
||||
free(memory, address)?;
|
||||
return Ok(0);
|
||||
}
|
||||
let result = memory.resize_heap_allocation(PROCESS_HEAP, address, size as usize, false);
|
||||
allocation_result(memory, cpu.gs_base, result)
|
||||
});
|
||||
registry.register(UCRT, "free", |args, _, memory| {
|
||||
free(memory, args.rcx)?;
|
||||
Ok(0)
|
||||
});
|
||||
|
||||
for symbol in ["malloc", "calloc", "realloc", "free"] {
|
||||
registry.alias("api-ms-win-crt-heap-l1-1-0.dll", UCRT, symbol);
|
||||
registry.set_status(UCRT, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
}
|
||||
|
||||
fn free(memory: &mut GuestMemory, address: u64) -> Result<(), ExitReason> {
|
||||
if address == 0 || memory.release_heap_allocation(PROCESS_HEAP, address) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ExitReason::MemoryFault(MemoryError::UnmappedAddress(
|
||||
address,
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn errno_isolated_by_guest_teb_on_one_host_thread() {
|
||||
use crate::cpu::{CpuState, Register};
|
||||
use crate::import_table::ImportName;
|
||||
|
||||
let mut registry = ImportRegistry::new();
|
||||
register_errno(&mut registry);
|
||||
register_heap(&mut registry);
|
||||
let mut memory = GuestMemory::new();
|
||||
let mut first = CpuState {
|
||||
gs_base: 0x10000,
|
||||
..CpuState::default()
|
||||
};
|
||||
let mut second = CpuState {
|
||||
gs_base: 0x20000,
|
||||
..CpuState::default()
|
||||
};
|
||||
let call = |symbol: &str, cpu: &mut CpuState, memory: &mut GuestMemory| {
|
||||
let service = registry
|
||||
.resolve(UCRT, &ImportName::Name(symbol.to_owned()))
|
||||
.unwrap();
|
||||
(service.handler)(&Win64Args::new(cpu), cpu, memory).unwrap()
|
||||
};
|
||||
|
||||
let first_slot = call("_errno", &mut first, &mut memory);
|
||||
first.set(Register::Rcx, 23);
|
||||
assert_eq!(call("_set_errno", &mut first, &mut memory), 0);
|
||||
let second_slot = call("_errno", &mut second, &mut memory);
|
||||
assert_ne!(first_slot, second_slot);
|
||||
assert_eq!(memory.read_u32(second_slot).unwrap(), 0);
|
||||
second.set(Register::Rcx, u64::MAX);
|
||||
assert_eq!(call("malloc", &mut second, &mut memory), 0);
|
||||
assert_eq!(memory.read_u32(second_slot).unwrap(), ENOMEM);
|
||||
assert_eq!(call("_errno", &mut first, &mut memory), first_slot);
|
||||
assert_eq!(memory.read_u32(first_slot).unwrap(), 23);
|
||||
}
|
||||
@@ -0,0 +1,554 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! CRT services that call guest functions: sorting, searching and the
|
||||
//! initializer tables run during C and C++ static initialization.
|
||||
//!
|
||||
//! Each service is a callback task. The comparator or initializer runs as
|
||||
//! ordinary translated guest code, and the service continues when it returns.
|
||||
|
||||
use super::ServicesState;
|
||||
use crate::cpu::ExitReason;
|
||||
use crate::imports::{CallbackStart, CallbackStep, CallbackTask, ImportRegistry, ServiceStatus};
|
||||
use crate::memory::{GuestMemory, MemoryError, PROCESS_HEAP};
|
||||
use std::sync::Arc;
|
||||
|
||||
const UCRT: &str = "ucrtbase.dll";
|
||||
const CRT_UTILITY_API: &str = "api-ms-win-crt-utility-l1-1-0.dll";
|
||||
const CRT_RUNTIME_API: &str = "api-ms-win-crt-runtime-l1-1-0.dll";
|
||||
/// Largest array, in bytes, that sorting may permute.
|
||||
const SORT_BUDGET: u64 = 1_048_576;
|
||||
/// Largest initializer table, in entries.
|
||||
const MAX_INITIALIZERS: u64 = 65_536;
|
||||
|
||||
/// An invalid argument would reach the CRT invalid-parameter handler, which
|
||||
/// the runtime does not model.
|
||||
fn unsupported<T>() -> Result<T, ExitReason> {
|
||||
Err(ExitReason::IllegalInstruction(0xFE))
|
||||
}
|
||||
|
||||
fn fault(error: MemoryError) -> ExitReason {
|
||||
ExitReason::MemoryFault(error)
|
||||
}
|
||||
|
||||
/// The comparator's `int` result.
|
||||
fn ordering(result: u64) -> i32 {
|
||||
result as u32 as i32
|
||||
}
|
||||
|
||||
/// Comparator arguments. The secure variants pass the caller's context first.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Comparator {
|
||||
entry: u64,
|
||||
context: Option<u64>,
|
||||
}
|
||||
|
||||
impl Comparator {
|
||||
fn call(self, left: u64, right: u64) -> CallbackStep {
|
||||
let args = match self.context {
|
||||
Some(context) => [context, left, right, 0],
|
||||
None => [left, right, 0, 0],
|
||||
};
|
||||
CallbackStep::Call {
|
||||
entry: self.entry,
|
||||
args,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Binary insertion sort over element indices. Elements stay in place while
|
||||
/// the comparator runs and are permuted once at the end.
|
||||
struct Sort {
|
||||
base: u64,
|
||||
width: u64,
|
||||
count: u64,
|
||||
compare: Comparator,
|
||||
sorted: Vec<u64>,
|
||||
next: u64,
|
||||
low: usize,
|
||||
high: usize,
|
||||
}
|
||||
|
||||
impl Sort {
|
||||
fn element(&self, index: u64) -> u64 {
|
||||
self.base + index * self.width
|
||||
}
|
||||
|
||||
fn probe(&self) -> CallbackStep {
|
||||
let middle = (self.low + self.high) / 2;
|
||||
self.compare
|
||||
.call(self.element(self.next), self.element(self.sorted[middle]))
|
||||
}
|
||||
|
||||
fn permute(&self, memory: &mut GuestMemory) -> Result<(), ExitReason> {
|
||||
let mut original = vec![0; (self.count * self.width) as usize];
|
||||
memory.read_bytes(self.base, &mut original).map_err(fault)?;
|
||||
let width = self.width as usize;
|
||||
let mut ordered = Vec::with_capacity(original.len());
|
||||
for &index in &self.sorted {
|
||||
let start = index as usize * width;
|
||||
ordered.extend_from_slice(&original[start..start + width]);
|
||||
}
|
||||
memory.write_bytes(self.base, &ordered).map_err(fault)
|
||||
}
|
||||
}
|
||||
|
||||
impl CallbackTask for Sort {
|
||||
fn resume(
|
||||
&mut self,
|
||||
result: u64,
|
||||
_: u64,
|
||||
memory: &mut GuestMemory,
|
||||
) -> Result<CallbackStep, ExitReason> {
|
||||
let middle = (self.low + self.high) / 2;
|
||||
// Inserting after equal elements keeps equal keys in input order.
|
||||
if ordering(result) < 0 {
|
||||
self.high = middle;
|
||||
} else {
|
||||
self.low = middle + 1;
|
||||
}
|
||||
if self.low < self.high {
|
||||
return Ok(self.probe());
|
||||
}
|
||||
self.sorted.insert(self.low, self.next);
|
||||
self.next += 1;
|
||||
if self.next == self.count {
|
||||
self.permute(memory)?;
|
||||
return Ok(CallbackStep::Return(0));
|
||||
}
|
||||
self.low = 0;
|
||||
self.high = self.sorted.len();
|
||||
Ok(self.probe())
|
||||
}
|
||||
}
|
||||
|
||||
fn start_sort(
|
||||
memory: &mut GuestMemory,
|
||||
base: u64,
|
||||
count: u64,
|
||||
width: u64,
|
||||
compare: Comparator,
|
||||
) -> Result<CallbackStart, ExitReason> {
|
||||
if count > 0 && (base == 0 || width == 0) || compare.entry == 0 {
|
||||
return unsupported();
|
||||
}
|
||||
if count < 2 {
|
||||
return Ok(CallbackStart::Return(0));
|
||||
}
|
||||
let Some(bytes) = count
|
||||
.checked_mul(width)
|
||||
.filter(|&bytes| bytes <= SORT_BUDGET)
|
||||
else {
|
||||
return unsupported();
|
||||
};
|
||||
base.checked_add(bytes)
|
||||
.ok_or(fault(MemoryError::Overflow))?;
|
||||
memory.check_write(base, bytes as usize).map_err(fault)?;
|
||||
let sort = Sort {
|
||||
base,
|
||||
width,
|
||||
count,
|
||||
compare,
|
||||
sorted: vec![0],
|
||||
next: 1,
|
||||
low: 0,
|
||||
high: 1,
|
||||
};
|
||||
let CallbackStep::Call { entry, args } = sort.probe() else {
|
||||
unreachable!("a probe always calls the comparator");
|
||||
};
|
||||
Ok(CallbackStart::Call {
|
||||
task: Box::new(sort),
|
||||
entry,
|
||||
args,
|
||||
})
|
||||
}
|
||||
|
||||
struct Search {
|
||||
key: u64,
|
||||
base: u64,
|
||||
width: u64,
|
||||
compare: Comparator,
|
||||
low: u64,
|
||||
high: u64,
|
||||
}
|
||||
|
||||
impl Search {
|
||||
fn middle(&self) -> u64 {
|
||||
self.low + (self.high - self.low) / 2
|
||||
}
|
||||
|
||||
fn probe(&self) -> CallbackStep {
|
||||
self.compare
|
||||
.call(self.key, self.base + self.middle() * self.width)
|
||||
}
|
||||
}
|
||||
|
||||
impl CallbackTask for Search {
|
||||
fn resume(
|
||||
&mut self,
|
||||
result: u64,
|
||||
_: u64,
|
||||
_: &mut GuestMemory,
|
||||
) -> Result<CallbackStep, ExitReason> {
|
||||
let middle = self.middle();
|
||||
match ordering(result) {
|
||||
0 => return Ok(CallbackStep::Return(self.base + middle * self.width)),
|
||||
order if order < 0 => self.high = middle,
|
||||
_ => self.low = middle + 1,
|
||||
}
|
||||
if self.low < self.high {
|
||||
Ok(self.probe())
|
||||
} else {
|
||||
Ok(CallbackStep::Return(0))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn start_search(
|
||||
key: u64,
|
||||
base: u64,
|
||||
count: u64,
|
||||
width: u64,
|
||||
compare: Comparator,
|
||||
) -> Result<CallbackStart, ExitReason> {
|
||||
if compare.entry == 0 || count > 0 && (base == 0 || width == 0) {
|
||||
return unsupported();
|
||||
}
|
||||
if count == 0 {
|
||||
return Ok(CallbackStart::Return(0));
|
||||
}
|
||||
count
|
||||
.checked_mul(width)
|
||||
.and_then(|bytes| base.checked_add(bytes))
|
||||
.ok_or(fault(MemoryError::Overflow))?;
|
||||
let search = Search {
|
||||
key,
|
||||
base,
|
||||
width,
|
||||
compare,
|
||||
low: 0,
|
||||
high: count,
|
||||
};
|
||||
let CallbackStep::Call { entry, args } = search.probe() else {
|
||||
unreachable!("a probe always calls the comparator");
|
||||
};
|
||||
Ok(CallbackStart::Call {
|
||||
task: Box::new(search),
|
||||
entry,
|
||||
args,
|
||||
})
|
||||
}
|
||||
|
||||
/// Calls each nonnull function pointer in `[cursor, end)` in order.
|
||||
/// `_initterm_e` stops at the first initializer that returns nonzero.
|
||||
struct Initializers {
|
||||
cursor: u64,
|
||||
end: u64,
|
||||
stop_on_error: bool,
|
||||
}
|
||||
|
||||
impl Initializers {
|
||||
fn next(&mut self, memory: &GuestMemory) -> Result<CallbackStep, ExitReason> {
|
||||
while self.cursor < self.end {
|
||||
let entry = memory.read_u64(self.cursor).map_err(fault)?;
|
||||
self.cursor += 8;
|
||||
if entry != 0 {
|
||||
return Ok(CallbackStep::Call {
|
||||
entry,
|
||||
args: [0; 4],
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(CallbackStep::Return(0))
|
||||
}
|
||||
}
|
||||
|
||||
impl CallbackTask for Initializers {
|
||||
fn resume(
|
||||
&mut self,
|
||||
result: u64,
|
||||
_: u64,
|
||||
memory: &mut GuestMemory,
|
||||
) -> Result<CallbackStep, ExitReason> {
|
||||
let status = result as u32;
|
||||
if self.stop_on_error && status != 0 {
|
||||
return Ok(CallbackStep::Return(u64::from(status)));
|
||||
}
|
||||
self.next(memory)
|
||||
}
|
||||
}
|
||||
|
||||
fn start_initializers(
|
||||
memory: &mut GuestMemory,
|
||||
first: u64,
|
||||
last: u64,
|
||||
stop_on_error: bool,
|
||||
) -> Result<CallbackStart, ExitReason> {
|
||||
let Some(span) = last.checked_sub(first) else {
|
||||
return unsupported();
|
||||
};
|
||||
if !span.is_multiple_of(8) || span / 8 > MAX_INITIALIZERS {
|
||||
return unsupported();
|
||||
}
|
||||
let mut table = Initializers {
|
||||
cursor: first,
|
||||
end: last,
|
||||
stop_on_error,
|
||||
};
|
||||
Ok(match table.next(memory)? {
|
||||
CallbackStep::Call { entry, args } => CallbackStart::Call {
|
||||
task: Box::new(table),
|
||||
entry,
|
||||
args,
|
||||
},
|
||||
CallbackStep::Return(value) => CallbackStart::Return(value),
|
||||
})
|
||||
}
|
||||
|
||||
/// `_onexit_table_t` from corecrt_startup.h: `_first`, `_last` and `_end`
|
||||
/// pointers to an array of function pointers.
|
||||
const ONEXIT_TABLE_SIZE: usize = 24;
|
||||
const ONEXIT_INITIAL_ENTRIES: u64 = 32;
|
||||
const MAX_ONEXIT_ENTRIES: u64 = 65_536;
|
||||
const CRT_FAILURE: u64 = u32::MAX as u64;
|
||||
|
||||
fn read_onexit_table(memory: &GuestMemory, table: u64) -> Result<[u64; 3], ExitReason> {
|
||||
let mut bytes = [0; ONEXIT_TABLE_SIZE];
|
||||
memory.read_bytes(table, &mut bytes).map_err(fault)?;
|
||||
Ok(std::array::from_fn(|index| {
|
||||
u64::from_le_bytes(bytes[8 * index..8 * index + 8].try_into().unwrap())
|
||||
}))
|
||||
}
|
||||
|
||||
fn write_onexit_table(
|
||||
memory: &mut GuestMemory,
|
||||
table: u64,
|
||||
pointers: [u64; 3],
|
||||
) -> Result<(), ExitReason> {
|
||||
let mut bytes = [0; ONEXIT_TABLE_SIZE];
|
||||
for (chunk, pointer) in bytes.as_chunks_mut::<8>().0.iter_mut().zip(pointers) {
|
||||
*chunk = pointer.to_le_bytes();
|
||||
}
|
||||
memory.write_bytes(table, &bytes).map_err(fault)
|
||||
}
|
||||
|
||||
/// Append `function`, growing the table's storage on the default process heap.
|
||||
/// Returns false when the storage cannot grow.
|
||||
fn register_onexit(
|
||||
memory: &mut GuestMemory,
|
||||
table: u64,
|
||||
function: u64,
|
||||
) -> Result<bool, ExitReason> {
|
||||
let [mut first, mut last, mut end] = read_onexit_table(memory, table)?;
|
||||
if first == 0 {
|
||||
let bytes = (ONEXIT_INITIAL_ENTRIES * 8) as usize;
|
||||
let Ok(storage) = memory.map_heap_allocation(PROCESS_HEAP, bytes) else {
|
||||
return Ok(false);
|
||||
};
|
||||
(first, last, end) = (storage, storage, storage + bytes as u64);
|
||||
}
|
||||
if last < first || end < last || !(end - first).is_multiple_of(8) {
|
||||
return unsupported();
|
||||
}
|
||||
if last == end {
|
||||
let capacity = (end - first) / 8;
|
||||
if capacity >= MAX_ONEXIT_ENTRIES {
|
||||
return Ok(false);
|
||||
}
|
||||
let bytes = (capacity * 2 * 8) as usize;
|
||||
let Ok(storage) = memory.resize_heap_allocation(PROCESS_HEAP, first, bytes, false) else {
|
||||
return Ok(false);
|
||||
};
|
||||
(first, last, end) = (storage, storage + capacity * 8, storage + bytes as u64);
|
||||
}
|
||||
memory.write_u64(last, function).map_err(fault)?;
|
||||
write_onexit_table(memory, table, [first, last + 8, end])?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Runs registered functions in reverse order of registration.
|
||||
struct ExitFunctions {
|
||||
pending: Vec<u64>,
|
||||
}
|
||||
|
||||
impl ExitFunctions {
|
||||
fn next(&mut self) -> CallbackStep {
|
||||
match self.pending.pop() {
|
||||
Some(entry) => CallbackStep::Call {
|
||||
entry,
|
||||
args: [0; 4],
|
||||
},
|
||||
None => CallbackStep::Return(0),
|
||||
}
|
||||
}
|
||||
|
||||
fn start(mut self) -> CallbackStart {
|
||||
match self.next() {
|
||||
CallbackStep::Call { entry, args } => CallbackStart::Call {
|
||||
task: Box::new(self),
|
||||
entry,
|
||||
args,
|
||||
},
|
||||
CallbackStep::Return(value) => CallbackStart::Return(value),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CallbackTask for ExitFunctions {
|
||||
fn resume(&mut self, _: u64, _: u64, _: &mut GuestMemory) -> Result<CallbackStep, ExitReason> {
|
||||
Ok(self.next())
|
||||
}
|
||||
}
|
||||
|
||||
fn register_exit_tables(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
registry.register(UCRT, "_initialize_onexit_table", |args, _, mem| {
|
||||
let table = args.rcx;
|
||||
if table == 0 {
|
||||
return Ok(CRT_FAILURE);
|
||||
}
|
||||
// An initialized table keeps its registrations.
|
||||
if read_onexit_table(mem, table)?[0] == 0 {
|
||||
write_onexit_table(mem, table, [0; 3])?;
|
||||
}
|
||||
Ok(0)
|
||||
});
|
||||
|
||||
registry.register(UCRT, "_register_onexit_function", |args, _, mem| {
|
||||
if args.rcx == 0 {
|
||||
return Ok(CRT_FAILURE);
|
||||
}
|
||||
Ok(if register_onexit(mem, args.rcx, args.rdx)? {
|
||||
0
|
||||
} else {
|
||||
CRT_FAILURE
|
||||
})
|
||||
});
|
||||
|
||||
registry.register_callback_task(
|
||||
UCRT,
|
||||
"_execute_onexit_table",
|
||||
ServiceStatus::Partial,
|
||||
|args, _, mem, _| {
|
||||
let table = args.rcx;
|
||||
if table == 0 {
|
||||
return Ok(CallbackStart::Return(CRT_FAILURE));
|
||||
}
|
||||
let [first, last, _] = read_onexit_table(mem, table)?;
|
||||
if first == 0 {
|
||||
return Ok(CallbackStart::Return(0));
|
||||
}
|
||||
if last < first || !(last - first).is_multiple_of(8) {
|
||||
return unsupported();
|
||||
}
|
||||
let mut pending = Vec::with_capacity(((last - first) / 8) as usize);
|
||||
for slot in (first..last).step_by(8) {
|
||||
let entry = mem.read_u64(slot).map_err(fault)?;
|
||||
if entry != 0 {
|
||||
pending.push(entry);
|
||||
}
|
||||
}
|
||||
// The table is reset before the functions run, so a function
|
||||
// registered while they run starts a new table.
|
||||
write_onexit_table(mem, table, [0; 3])?;
|
||||
mem.release_heap_allocation(PROCESS_HEAP, first);
|
||||
Ok(ExitFunctions { pending }.start())
|
||||
},
|
||||
);
|
||||
|
||||
for symbol in ["atexit", "_crt_atexit"] {
|
||||
let s = Arc::clone(state);
|
||||
registry.register(UCRT, symbol, move |args, _, _| {
|
||||
let mut functions = s.atexit.lock().expect("guest atexit functions");
|
||||
if args.rcx == 0 || functions.len() as u64 >= MAX_ONEXIT_ENTRIES {
|
||||
return Ok(CRT_FAILURE);
|
||||
}
|
||||
functions.push(args.rcx);
|
||||
Ok(0)
|
||||
});
|
||||
}
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register_callback_task(UCRT, "_cexit", ServiceStatus::Partial, move |_, _, _, _| {
|
||||
let pending = std::mem::take(&mut *s.atexit.lock().expect("guest atexit functions"));
|
||||
Ok(ExitFunctions { pending }.start())
|
||||
});
|
||||
|
||||
for symbol in [
|
||||
"_initialize_onexit_table",
|
||||
"_register_onexit_function",
|
||||
"atexit",
|
||||
"_crt_atexit",
|
||||
] {
|
||||
registry.set_status(UCRT, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
for symbol in [
|
||||
"_initialize_onexit_table",
|
||||
"_register_onexit_function",
|
||||
"_execute_onexit_table",
|
||||
"_crt_atexit",
|
||||
"_cexit",
|
||||
] {
|
||||
registry.alias(CRT_RUNTIME_API, UCRT, symbol);
|
||||
}
|
||||
registry.alias(CRT_RUNTIME_API, UCRT, "atexit");
|
||||
}
|
||||
|
||||
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
register_exit_tables(registry, state);
|
||||
registry.register_callback_task(UCRT, "qsort", ServiceStatus::Partial, |args, _, mem, _| {
|
||||
let compare = Comparator {
|
||||
entry: args.r9,
|
||||
context: None,
|
||||
};
|
||||
start_sort(mem, args.rcx, args.rdx, args.r8, compare)
|
||||
});
|
||||
registry.register_callback_task(
|
||||
UCRT,
|
||||
"qsort_s",
|
||||
ServiceStatus::Partial,
|
||||
|args, _, mem, _| {
|
||||
let context = args.get(4, mem).map_err(fault)?;
|
||||
let compare = Comparator {
|
||||
entry: args.r9,
|
||||
context: Some(context),
|
||||
};
|
||||
start_sort(mem, args.rcx, args.rdx, args.r8, compare)
|
||||
},
|
||||
);
|
||||
registry.register_callback_task(
|
||||
UCRT,
|
||||
"bsearch",
|
||||
ServiceStatus::Partial,
|
||||
|args, _, mem, _| {
|
||||
let compare = Comparator {
|
||||
entry: args.get(4, mem).map_err(fault)?,
|
||||
context: None,
|
||||
};
|
||||
start_search(args.rcx, args.rdx, args.r8, args.r9, compare)
|
||||
},
|
||||
);
|
||||
registry.register_callback_task(
|
||||
UCRT,
|
||||
"bsearch_s",
|
||||
ServiceStatus::Partial,
|
||||
|args, _, mem, _| {
|
||||
let compare = Comparator {
|
||||
entry: args.get(4, mem).map_err(fault)?,
|
||||
context: Some(args.get(5, mem).map_err(fault)?),
|
||||
};
|
||||
start_search(args.rcx, args.rdx, args.r8, args.r9, compare)
|
||||
},
|
||||
);
|
||||
for (symbol, stop_on_error) in [("_initterm", false), ("_initterm_e", true)] {
|
||||
registry.register_callback_task(
|
||||
UCRT,
|
||||
symbol,
|
||||
ServiceStatus::Partial,
|
||||
move |args, _, mem, _| start_initializers(mem, args.rcx, args.rdx, stop_on_error),
|
||||
);
|
||||
registry.alias(CRT_RUNTIME_API, UCRT, symbol);
|
||||
}
|
||||
for symbol in ["qsort", "qsort_s", "bsearch", "bsearch_s"] {
|
||||
registry.alias(CRT_UTILITY_API, UCRT, symbol);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Unnamed event, semaphore and mutex objects and waits that can resolve without a guest scheduler.
|
||||
|
||||
use super::{
|
||||
ERROR_ACCESS_DENIED, ERROR_INVALID_HANDLE, ERROR_INVALID_PARAMETER, ERROR_NOACCESS,
|
||||
ERROR_NOT_ENOUGH_MEMORY, ERROR_NOT_SUPPORTED, GuestObject, KERNEL32, ServicesState,
|
||||
};
|
||||
use crate::cpu::ExitReason;
|
||||
use crate::imports::{ImportRegistry, ServiceStatus};
|
||||
use crate::memory::MemoryError;
|
||||
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;
|
||||
const EVENT_ALL_ACCESS: u32 = 0x001f_0003;
|
||||
const WAIT_OBJECT_0: u64 = 0;
|
||||
const WAIT_TIMEOUT: u64 = 258;
|
||||
const WAIT_FAILED: u64 = u32::MAX as u64;
|
||||
|
||||
const SEMAPHORE_ALL_ACCESS: u32 = 0x001f_0003;
|
||||
const SEMAPHORE_MODIFY_STATE: u32 = 2;
|
||||
const ERROR_TOO_MANY_POSTS: u32 = 298;
|
||||
|
||||
const MUTEX_ALL_ACCESS: u32 = 0x001f_0001;
|
||||
const CREATE_MUTEX_INITIAL_OWNER: u32 = 1;
|
||||
const ERROR_NOT_OWNER: u32 = 288;
|
||||
|
||||
pub(super) enum Waitable {
|
||||
Event {
|
||||
manual_reset: bool,
|
||||
signaled: bool,
|
||||
},
|
||||
Semaphore {
|
||||
count: i32,
|
||||
maximum: i32,
|
||||
},
|
||||
/// Owned by a guest TEB; the owner may acquire it recursively.
|
||||
Mutex {
|
||||
owner: Option<u64>,
|
||||
recursion: u32,
|
||||
},
|
||||
}
|
||||
|
||||
impl Waitable {
|
||||
fn is_ready(&self, teb: u64) -> bool {
|
||||
match self {
|
||||
Self::Event { signaled, .. } => *signaled,
|
||||
Self::Semaphore { count, .. } => *count > 0,
|
||||
Self::Mutex { owner, .. } => owner.is_none_or(|owner| owner == teb),
|
||||
}
|
||||
}
|
||||
|
||||
fn consume(&mut self, teb: u64) {
|
||||
match self {
|
||||
Self::Event {
|
||||
manual_reset,
|
||||
signaled,
|
||||
} => *signaled = *manual_reset,
|
||||
Self::Semaphore { count, .. } => *count -= 1,
|
||||
Self::Mutex { owner, recursion } => {
|
||||
*owner = Some(teb);
|
||||
*recursion += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn at_recursion_limit(&self) -> bool {
|
||||
matches!(self, Self::Mutex { recursion, .. } if *recursion >= i32::MAX as u32)
|
||||
}
|
||||
}
|
||||
|
||||
fn insert_waitable(
|
||||
state: &ServicesState,
|
||||
teb: u64,
|
||||
object: Waitable,
|
||||
access: u32,
|
||||
) -> Result<u64, ExitReason> {
|
||||
let mut objects = state.objects.lock().expect("guest object state");
|
||||
let Some(handle) = objects.next_handle() else {
|
||||
return state.fail(teb, ERROR_NOT_ENOUGH_MEMORY, 0);
|
||||
};
|
||||
objects.insert_handle(
|
||||
handle,
|
||||
GuestObject::Waitable {
|
||||
state: Arc::new(Mutex::new(object)),
|
||||
access,
|
||||
},
|
||||
);
|
||||
Ok(handle)
|
||||
}
|
||||
|
||||
fn insert_mutex(
|
||||
state: &ServicesState,
|
||||
teb: u64,
|
||||
initial_owner: bool,
|
||||
access: u32,
|
||||
) -> Result<u64, ExitReason> {
|
||||
let object = Waitable::Mutex {
|
||||
owner: initial_owner.then_some(teb),
|
||||
recursion: u32::from(initial_owner),
|
||||
};
|
||||
insert_waitable(state, teb, object, access)
|
||||
}
|
||||
|
||||
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
for symbol in ["CreateEventA", "CreateEventW"] {
|
||||
let state = Arc::clone(state);
|
||||
registry.register(KERNEL32, symbol, move |args, cpu, mem| {
|
||||
let attributes = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
let manual_reset = args.get(1, mem).map_err(ExitReason::MemoryFault)? as u32 != 0;
|
||||
let signaled = args.get(2, mem).map_err(ExitReason::MemoryFault)? as u32 != 0;
|
||||
let name = args.get(3, mem).map_err(ExitReason::MemoryFault)?;
|
||||
if attributes != 0 || name != 0 {
|
||||
return state.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
insert_waitable(
|
||||
&state,
|
||||
cpu.gs_base,
|
||||
Waitable::Event {
|
||||
manual_reset,
|
||||
signaled,
|
||||
},
|
||||
EVENT_ALL_ACCESS,
|
||||
)
|
||||
});
|
||||
}
|
||||
|
||||
for (symbol, signaled) in [("SetEvent", true), ("ResetEvent", false)] {
|
||||
let state = Arc::clone(state);
|
||||
registry.register(KERNEL32, symbol, move |args, cpu, mem| {
|
||||
let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
let objects = state.objects.lock().expect("guest object state");
|
||||
let Some(GuestObject::Waitable {
|
||||
state: event,
|
||||
access,
|
||||
}) = objects.handles.get(&handle)
|
||||
else {
|
||||
return state.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0);
|
||||
};
|
||||
let mut event = event.lock().expect("guest waitable state");
|
||||
let Waitable::Event {
|
||||
signaled: current, ..
|
||||
} = &mut *event
|
||||
else {
|
||||
return state.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0);
|
||||
};
|
||||
if access & EVENT_MODIFY_STATE == 0 {
|
||||
return state.fail(cpu.gs_base, ERROR_ACCESS_DENIED, 0);
|
||||
}
|
||||
*current = signaled;
|
||||
Ok(1)
|
||||
});
|
||||
}
|
||||
|
||||
for symbol in ["CreateSemaphoreA", "CreateSemaphoreW"] {
|
||||
let state = Arc::clone(state);
|
||||
registry.register(KERNEL32, symbol, move |args, cpu, mem| {
|
||||
let attributes = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
let count = args.get(1, mem).map_err(ExitReason::MemoryFault)? as i32;
|
||||
let maximum = args.get(2, mem).map_err(ExitReason::MemoryFault)? as i32;
|
||||
let name = args.get(3, mem).map_err(ExitReason::MemoryFault)?;
|
||||
if attributes != 0 || name != 0 {
|
||||
return state.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
if maximum <= 0 || count < 0 || count > maximum {
|
||||
return state.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
insert_waitable(
|
||||
&state,
|
||||
cpu.gs_base,
|
||||
Waitable::Semaphore { count, maximum },
|
||||
SEMAPHORE_ALL_ACCESS,
|
||||
)
|
||||
});
|
||||
}
|
||||
|
||||
let release = Arc::clone(state);
|
||||
registry.register(KERNEL32, "ReleaseSemaphore", move |args, cpu, mem| {
|
||||
let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
let amount = args.get(1, mem).map_err(ExitReason::MemoryFault)? as i32;
|
||||
let output = args.get(2, mem).map_err(ExitReason::MemoryFault)?;
|
||||
if amount <= 0 {
|
||||
return release.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
let objects = release.objects.lock().expect("guest object state");
|
||||
let Some(GuestObject::Waitable { state, access }) = objects.handles.get(&handle) else {
|
||||
return release.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0);
|
||||
};
|
||||
let mut state = state.lock().expect("guest waitable state");
|
||||
let Waitable::Semaphore { count, maximum } = &mut *state else {
|
||||
return release.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0);
|
||||
};
|
||||
if access & SEMAPHORE_MODIFY_STATE == 0 {
|
||||
return release.fail(cpu.gs_base, ERROR_ACCESS_DENIED, 0);
|
||||
}
|
||||
if amount > *maximum - *count {
|
||||
return release.fail(cpu.gs_base, ERROR_TOO_MANY_POSTS, 0);
|
||||
}
|
||||
if output != 0 && mem.write_u32(output, *count as u32).is_err() {
|
||||
return release.fail(cpu.gs_base, ERROR_NOACCESS, 0);
|
||||
}
|
||||
*count += amount;
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
for symbol in ["CreateMutexA", "CreateMutexW"] {
|
||||
let state = Arc::clone(state);
|
||||
registry.register(KERNEL32, symbol, move |args, cpu, mem| {
|
||||
let attributes = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
let initial_owner = args.get(1, mem).map_err(ExitReason::MemoryFault)? as u32 != 0;
|
||||
let name = args.get(2, mem).map_err(ExitReason::MemoryFault)?;
|
||||
if attributes != 0 || name != 0 {
|
||||
return state.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
insert_mutex(&state, cpu.gs_base, initial_owner, MUTEX_ALL_ACCESS)
|
||||
});
|
||||
}
|
||||
|
||||
for symbol in ["CreateMutexExA", "CreateMutexExW"] {
|
||||
let state = Arc::clone(state);
|
||||
registry.register(KERNEL32, symbol, move |args, cpu, mem| {
|
||||
let attributes = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
let name = args.get(1, mem).map_err(ExitReason::MemoryFault)?;
|
||||
let flags = args.get(2, mem).map_err(ExitReason::MemoryFault)? as u32;
|
||||
let access = args.get(3, mem).map_err(ExitReason::MemoryFault)? as u32;
|
||||
if attributes != 0 || name != 0 || access & !MUTEX_ALL_ACCESS != 0 {
|
||||
return state.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
if flags & !CREATE_MUTEX_INITIAL_OWNER != 0 {
|
||||
return state.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
let initial_owner = flags & CREATE_MUTEX_INITIAL_OWNER != 0;
|
||||
insert_mutex(&state, cpu.gs_base, initial_owner, access)
|
||||
});
|
||||
}
|
||||
|
||||
let release = Arc::clone(state);
|
||||
registry.register(KERNEL32, "ReleaseMutex", move |args, cpu, mem| {
|
||||
let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
let objects = release.objects.lock().expect("guest object state");
|
||||
let Some(GuestObject::Waitable { state, .. }) = objects.handles.get(&handle) else {
|
||||
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 {
|
||||
return release.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0);
|
||||
};
|
||||
if *owner != Some(cpu.gs_base) {
|
||||
return release.fail(cpu.gs_base, ERROR_NOT_OWNER, 0);
|
||||
}
|
||||
*recursion -= 1;
|
||||
if *recursion == 0 {
|
||||
*owner = None;
|
||||
}
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
for (symbol, extended) in [
|
||||
("WaitForSingleObject", false),
|
||||
("WaitForSingleObjectEx", true),
|
||||
] {
|
||||
let single = Arc::clone(state);
|
||||
registry.register(KERNEL32, symbol, move |args, cpu, mem| {
|
||||
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 {
|
||||
return single.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, WAIT_FAILED);
|
||||
}
|
||||
wait_for_objects(&single, cpu.gs_base, &[handle], false, timeout)
|
||||
});
|
||||
}
|
||||
for (symbol, extended) in [
|
||||
("WaitForMultipleObjects", false),
|
||||
("WaitForMultipleObjectsEx", true),
|
||||
] {
|
||||
let multiple = Arc::clone(state);
|
||||
registry.register(KERNEL32, symbol, move |args, cpu, mem| {
|
||||
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;
|
||||
let timeout = args.get(3, mem).map_err(ExitReason::MemoryFault)? as u32;
|
||||
if extended && args.get(4, mem).map_err(ExitReason::MemoryFault)? as u32 != 0 {
|
||||
return multiple.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, WAIT_FAILED);
|
||||
}
|
||||
if !(1..=64).contains(&count) || address == 0 {
|
||||
return multiple.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, WAIT_FAILED);
|
||||
}
|
||||
let mut handles = [0; 64];
|
||||
let handles = &mut handles[..count as usize];
|
||||
for (index, handle) in handles.iter_mut().enumerate() {
|
||||
let slot = address
|
||||
.checked_add(index as u64 * 8)
|
||||
.ok_or(ExitReason::MemoryFault(MemoryError::Overflow))?;
|
||||
*handle = mem.read_u64(slot).map_err(ExitReason::MemoryFault)?;
|
||||
}
|
||||
wait_for_objects(&multiple, cpu.gs_base, handles, all, timeout)
|
||||
});
|
||||
}
|
||||
|
||||
for symbol in [
|
||||
"CreateEventA",
|
||||
"CreateEventW",
|
||||
"SetEvent",
|
||||
"ResetEvent",
|
||||
"CreateSemaphoreA",
|
||||
"CreateSemaphoreW",
|
||||
"ReleaseSemaphore",
|
||||
"CreateMutexA",
|
||||
"CreateMutexW",
|
||||
"CreateMutexExA",
|
||||
"CreateMutexExW",
|
||||
"ReleaseMutex",
|
||||
"WaitForSingleObject",
|
||||
"WaitForSingleObjectEx",
|
||||
"WaitForMultipleObjects",
|
||||
"WaitForMultipleObjectsEx",
|
||||
] {
|
||||
registry.alias(SYNCH_API, KERNEL32, symbol);
|
||||
registry.set_status(KERNEL32, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
for symbol in ["WaitForMultipleObjects", "WaitForMultipleObjectsEx"] {
|
||||
registry.alias("api-ms-win-core-synch-l1-2-1.dll", KERNEL32, symbol);
|
||||
}
|
||||
}
|
||||
|
||||
fn wait_for_objects(
|
||||
state: &ServicesState,
|
||||
teb: u64,
|
||||
handles: &[u64],
|
||||
all: bool,
|
||||
timeout: u32,
|
||||
) -> Result<u64, ExitReason> {
|
||||
// The object table remains locked through validation and consumption.
|
||||
let objects = state.objects.lock().expect("guest object state");
|
||||
let mut waitables: Vec<&Arc<Mutex<Waitable>>> = Vec::with_capacity(handles.len());
|
||||
for (index, handle) in handles.iter().enumerate() {
|
||||
if handles[..index].contains(handle) {
|
||||
return state.fail(teb, ERROR_INVALID_PARAMETER, WAIT_FAILED);
|
||||
}
|
||||
match objects.handles.get(handle) {
|
||||
Some(GuestObject::Waitable {
|
||||
state: event,
|
||||
access,
|
||||
}) => {
|
||||
if access & SYNCHRONIZE == 0 {
|
||||
return state.fail(teb, ERROR_ACCESS_DENIED, WAIT_FAILED);
|
||||
}
|
||||
if all
|
||||
&& waitables
|
||||
.iter()
|
||||
.any(|existing| Arc::ptr_eq(existing, event))
|
||||
{
|
||||
return state.fail(teb, ERROR_INVALID_PARAMETER, WAIT_FAILED);
|
||||
}
|
||||
waitables.push(event);
|
||||
}
|
||||
Some(_) => return state.fail(teb, ERROR_NOT_SUPPORTED, WAIT_FAILED),
|
||||
None if matches!(*handle, super::CURRENT_THREAD | super::CURRENT_PROCESS) => {
|
||||
return state.fail(teb, ERROR_NOT_SUPPORTED, WAIT_FAILED);
|
||||
}
|
||||
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 !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.iter().any(|(_, object)| {
|
||||
object
|
||||
.lock()
|
||||
.expect("guest waitable state")
|
||||
.at_recursion_limit()
|
||||
}) {
|
||||
// Windows raises STATUS_MUTANT_LIMIT_EXCEEDED; exceptions are unsupported.
|
||||
return Err(ExitReason::IllegalInstruction(0xFE));
|
||||
}
|
||||
let first = ready[0].0;
|
||||
for (_, event) in ready {
|
||||
event.lock().expect("guest waitable state").consume(teb);
|
||||
}
|
||||
Ok(WAIT_OBJECT_0 + first as u64)
|
||||
}
|
||||
@@ -0,0 +1,627 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Bounded synthetic C: drive with no host filesystem mapping.
|
||||
|
||||
use super::{
|
||||
ERROR_ACCESS_DENIED, ERROR_INVALID_HANDLE, ERROR_INVALID_PARAMETER, ERROR_NOACCESS,
|
||||
ERROR_NOT_ENOUGH_MEMORY, ERROR_NOT_SUPPORTED, GuestObject, KERNEL32, ServicesState,
|
||||
};
|
||||
use crate::cpu::ExitReason;
|
||||
use crate::imports::{ImportRegistry, ServiceStatus};
|
||||
use crate::memory::{GuestMemory, MemoryError};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
const FILE_API: &str = "api-ms-win-core-file-l1-1-0.dll";
|
||||
const INVALID_HANDLE: u64 = u64::MAX;
|
||||
const READ: u32 = 0x8000_0000;
|
||||
const WRITE: u32 = 0x4000_0000;
|
||||
const FILE_NOT_FOUND: u32 = 2;
|
||||
const PATH_NOT_FOUND: u32 = 3;
|
||||
const DIRECTORY_NOT_EMPTY: u32 = 145;
|
||||
const FILE_EXISTS: u32 = 80;
|
||||
const ALREADY_EXISTS: u32 = 183;
|
||||
const INVALID_NAME: u32 = 123;
|
||||
const NEGATIVE_SEEK: u32 = 131;
|
||||
const SHARING_VIOLATION: u32 = 32;
|
||||
const DISK_FULL: u32 = 112;
|
||||
const MAX_FILES: usize = 256;
|
||||
const MAX_DIRECTORIES: usize = 256;
|
||||
const MAX_BYTES: usize = 16 * 1024 * 1024;
|
||||
const MAX_TRANSFER: usize = 1024 * 1024;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct OpenFile {
|
||||
path: String,
|
||||
// The object table serializes all operations on this open instance.
|
||||
position: Arc<AtomicU64>,
|
||||
open_access: u32,
|
||||
pub(super) access: u32,
|
||||
share: u32,
|
||||
}
|
||||
|
||||
fn read_guest_path(memory: &GuestMemory, address: u64) -> Result<Option<String>, MemoryError> {
|
||||
if address == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let mut units = Vec::new();
|
||||
for index in 0..260 {
|
||||
let slot = address
|
||||
.checked_add(index * 2)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
let unit = memory.read_u16(slot)?;
|
||||
if unit == 0 {
|
||||
let Ok(path) = String::from_utf16(&units) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let path = path.replace('/', "\\").to_ascii_lowercase();
|
||||
let name = path.strip_prefix("c:\\").unwrap_or(&path);
|
||||
return Ok(Some(name.to_owned()));
|
||||
}
|
||||
units.push(unit);
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn guest_path(memory: &GuestMemory, address: u64) -> Result<Option<String>, MemoryError> {
|
||||
Ok(read_guest_path(memory, address)?.filter(|name| name.split('\\').all(valid_component)))
|
||||
}
|
||||
|
||||
struct SearchEntry {
|
||||
name: String,
|
||||
attributes: u32,
|
||||
size: u64,
|
||||
}
|
||||
|
||||
pub(super) struct Search {
|
||||
entries: Vec<SearchEntry>,
|
||||
next: usize,
|
||||
}
|
||||
|
||||
fn write_find_data(
|
||||
memory: &mut GuestMemory,
|
||||
output: u64,
|
||||
entry: &SearchEntry,
|
||||
) -> Result<(), MemoryError> {
|
||||
if output == 0 {
|
||||
return Err(MemoryError::UnmappedAddress(0));
|
||||
}
|
||||
// WIN32_FIND_DATAW: attributes, three FILETIMEs, size high/low,
|
||||
// two reserved DWORDs, WCHAR[260], then WCHAR[14].
|
||||
let mut bytes = [0u8; 592];
|
||||
bytes[..4].copy_from_slice(&entry.attributes.to_le_bytes());
|
||||
bytes[28..32].copy_from_slice(&((entry.size >> 32) as u32).to_le_bytes());
|
||||
bytes[32..36].copy_from_slice(&(entry.size as u32).to_le_bytes());
|
||||
for (slot, unit) in bytes[44..564]
|
||||
.as_chunks_mut::<2>()
|
||||
.0
|
||||
.iter_mut()
|
||||
.zip(entry.name.encode_utf16())
|
||||
{
|
||||
slot.copy_from_slice(&unit.to_le_bytes());
|
||||
}
|
||||
memory.write_bytes(output, &bytes)
|
||||
}
|
||||
|
||||
fn wildcard_match(pattern: &str, name: &str) -> bool {
|
||||
let pattern: Vec<_> = pattern.encode_utf16().collect();
|
||||
let name: Vec<_> = name.encode_utf16().collect();
|
||||
let (mut p, mut n, mut retry) = (0, 0, None);
|
||||
while n < name.len() {
|
||||
match pattern.get(p).copied() {
|
||||
Some(42) => {
|
||||
p += 1;
|
||||
retry = Some((p, n));
|
||||
}
|
||||
Some(unit) if unit == 63 || unit == name[n] => {
|
||||
p += 1;
|
||||
n += 1;
|
||||
}
|
||||
_ => {
|
||||
let Some((after_star, previous)) = retry else {
|
||||
return false;
|
||||
};
|
||||
n = previous + 1;
|
||||
p = after_star;
|
||||
retry = Some((p, n));
|
||||
}
|
||||
}
|
||||
}
|
||||
pattern[p..].iter().all(|&unit| unit == 42)
|
||||
}
|
||||
|
||||
fn valid_component(name: &str) -> bool {
|
||||
let device = name.split('.').next().unwrap_or_default();
|
||||
!name.is_empty()
|
||||
&& !name.ends_with([' ', '.'])
|
||||
&& !name
|
||||
.chars()
|
||||
.any(|c| c.is_control() || "\\/:*?\"<>|".contains(c))
|
||||
&& !matches!(device, "con" | "prn" | "aux" | "nul")
|
||||
&& !(device.len() == 4
|
||||
&& (device.starts_with("com") || device.starts_with("lpt"))
|
||||
&& device.as_bytes()[3].is_ascii_digit())
|
||||
}
|
||||
|
||||
fn parent(path: &str) -> &str {
|
||||
path.rsplit_once('\\').map_or("", |(parent, _)| parent)
|
||||
}
|
||||
|
||||
fn share_mask(access: u32) -> u32 {
|
||||
u32::from(access & READ != 0) | (u32::from(access & WRITE != 0) << 1)
|
||||
}
|
||||
|
||||
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
let open = Arc::clone(state);
|
||||
registry.register(KERNEL32, "CreateFileW", move |args, cpu, memory| {
|
||||
let access = args.rdx as u32;
|
||||
let share = args.r8 as u32;
|
||||
let disposition = args.get(4, memory).map_err(ExitReason::MemoryFault)? as u32;
|
||||
let flags = args.get(5, memory).map_err(ExitReason::MemoryFault)? as u32;
|
||||
let template = args.get(6, memory).map_err(ExitReason::MemoryFault)?;
|
||||
if args.r9 != 0
|
||||
|| template != 0
|
||||
|| !matches!(flags, 0 | 0x80)
|
||||
|| access & !(READ | WRITE) != 0
|
||||
|| share & !3 != 0
|
||||
{
|
||||
return open.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, INVALID_HANDLE);
|
||||
}
|
||||
if !(1..=5).contains(&disposition) {
|
||||
return open.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, INVALID_HANDLE);
|
||||
}
|
||||
if matches!(disposition, 2 | 5) && access & WRITE == 0 {
|
||||
return open.fail(cpu.gs_base, ERROR_ACCESS_DENIED, INVALID_HANDLE);
|
||||
}
|
||||
let Some(path) = guest_path(memory, args.rcx).map_err(ExitReason::MemoryFault)? else {
|
||||
return open.fail(cpu.gs_base, INVALID_NAME, INVALID_HANDLE);
|
||||
};
|
||||
let mut objects = open.objects.lock().expect("guest object state");
|
||||
let parent = parent(&path);
|
||||
if !parent.is_empty() && !objects.directories.contains(parent) {
|
||||
return open.fail(cpu.gs_base, PATH_NOT_FOUND, INVALID_HANDLE);
|
||||
}
|
||||
if objects.directories.contains(&path) {
|
||||
return open.fail(cpu.gs_base, ERROR_ACCESS_DENIED, INVALID_HANDLE);
|
||||
}
|
||||
let exists = objects.files.contains_key(&path);
|
||||
if exists && disposition == 1 {
|
||||
return open.fail(cpu.gs_base, FILE_EXISTS, INVALID_HANDLE);
|
||||
}
|
||||
if !exists && matches!(disposition, 3 | 5) {
|
||||
return open.fail(cpu.gs_base, FILE_NOT_FOUND, INVALID_HANDLE);
|
||||
}
|
||||
for object in objects.handles.values() {
|
||||
if let GuestObject::File(file) = object
|
||||
&& file.path == path
|
||||
&& (share_mask(access) & !file.share != 0
|
||||
|| share_mask(file.open_access) & !share != 0)
|
||||
{
|
||||
return open.fail(cpu.gs_base, SHARING_VIOLATION, INVALID_HANDLE);
|
||||
}
|
||||
}
|
||||
let Some(handle) = objects.next_handle() else {
|
||||
return open.fail(cpu.gs_base, ERROR_NOT_ENOUGH_MEMORY, INVALID_HANDLE);
|
||||
};
|
||||
if !exists {
|
||||
if objects.files.len() >= MAX_FILES {
|
||||
return open.fail(cpu.gs_base, DISK_FULL, INVALID_HANDLE);
|
||||
}
|
||||
objects.files.insert(path.clone(), Vec::new());
|
||||
} else if matches!(disposition, 2 | 5) {
|
||||
*objects.files.get_mut(&path).expect("existing file") = Vec::new();
|
||||
}
|
||||
if matches!(disposition, 2 | 4) {
|
||||
open.fail(cpu.gs_base, if exists { ALREADY_EXISTS } else { 0 }, 0)?;
|
||||
}
|
||||
objects.insert_handle(
|
||||
handle,
|
||||
GuestObject::File(OpenFile {
|
||||
path,
|
||||
position: Arc::new(AtomicU64::new(0)),
|
||||
open_access: access,
|
||||
access,
|
||||
share,
|
||||
}),
|
||||
);
|
||||
Ok(handle)
|
||||
});
|
||||
|
||||
let create = Arc::clone(state);
|
||||
registry.register(KERNEL32, "CreateDirectoryW", move |args, cpu, memory| {
|
||||
if args.rdx != 0 {
|
||||
return create.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
let Some(path) = guest_path(memory, args.rcx).map_err(ExitReason::MemoryFault)? else {
|
||||
return create.fail(cpu.gs_base, INVALID_NAME, 0);
|
||||
};
|
||||
let mut objects = create.objects.lock().expect("guest object state");
|
||||
let parent = parent(&path);
|
||||
if !parent.is_empty() && !objects.directories.contains(parent) {
|
||||
return create.fail(cpu.gs_base, PATH_NOT_FOUND, 0);
|
||||
}
|
||||
if objects.directories.contains(&path) || objects.files.contains_key(&path) {
|
||||
return create.fail(cpu.gs_base, ALREADY_EXISTS, 0);
|
||||
}
|
||||
if objects.directories.len() >= MAX_DIRECTORIES {
|
||||
return create.fail(cpu.gs_base, DISK_FULL, 0);
|
||||
}
|
||||
objects.directories.insert(path);
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
let remove = Arc::clone(state);
|
||||
registry.register(KERNEL32, "RemoveDirectoryW", move |args, cpu, memory| {
|
||||
let Some(path) = guest_path(memory, args.rcx).map_err(ExitReason::MemoryFault)? else {
|
||||
return remove.fail(cpu.gs_base, INVALID_NAME, 0);
|
||||
};
|
||||
let mut objects = remove.objects.lock().expect("guest object state");
|
||||
if !objects.directories.contains(&path) {
|
||||
return remove.fail(cpu.gs_base, PATH_NOT_FOUND, 0);
|
||||
}
|
||||
if objects.directories.iter().any(|key| parent(key) == path)
|
||||
|| objects.files.keys().any(|key| parent(key) == path)
|
||||
{
|
||||
return remove.fail(cpu.gs_base, DIRECTORY_NOT_EMPTY, 0);
|
||||
}
|
||||
objects.directories.remove(&path);
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
let delete = Arc::clone(state);
|
||||
registry.register(KERNEL32, "DeleteFileW", move |args, cpu, memory| {
|
||||
let Some(path) = guest_path(memory, args.rcx).map_err(ExitReason::MemoryFault)? else {
|
||||
return delete.fail(cpu.gs_base, INVALID_NAME, 0);
|
||||
};
|
||||
let mut objects = delete.objects.lock().expect("guest object state");
|
||||
if objects.directories.contains(&path) {
|
||||
return delete.fail(cpu.gs_base, ERROR_ACCESS_DENIED, 0);
|
||||
}
|
||||
let parent = parent(&path);
|
||||
if !parent.is_empty() && !objects.directories.contains(parent) {
|
||||
return delete.fail(cpu.gs_base, PATH_NOT_FOUND, 0);
|
||||
}
|
||||
if objects
|
||||
.handles
|
||||
.values()
|
||||
.any(|object| matches!(object, GuestObject::File(file) if file.path == path))
|
||||
{
|
||||
return delete.fail(cpu.gs_base, SHARING_VIOLATION, 0);
|
||||
}
|
||||
if objects.files.remove(&path).is_none() {
|
||||
return delete.fail(cpu.gs_base, FILE_NOT_FOUND, 0);
|
||||
}
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
let attributes = Arc::clone(state);
|
||||
registry.register(KERNEL32, "GetFileAttributesW", move |args, cpu, memory| {
|
||||
const INVALID_ATTRIBUTES: u64 = u32::MAX as u64;
|
||||
let Some(path) = guest_path(memory, args.rcx).map_err(ExitReason::MemoryFault)? else {
|
||||
return attributes.fail(cpu.gs_base, INVALID_NAME, INVALID_ATTRIBUTES);
|
||||
};
|
||||
let objects = attributes.objects.lock().expect("guest object state");
|
||||
if objects.directories.contains(&path) {
|
||||
return Ok(0x10); // FILE_ATTRIBUTE_DIRECTORY
|
||||
}
|
||||
if objects.files.contains_key(&path) {
|
||||
return Ok(0x80); // FILE_ATTRIBUTE_NORMAL
|
||||
}
|
||||
let parent = parent(&path);
|
||||
let error = if parent.is_empty() || objects.directories.contains(parent) {
|
||||
FILE_NOT_FOUND
|
||||
} else {
|
||||
PATH_NOT_FOUND
|
||||
};
|
||||
attributes.fail(cpu.gs_base, error, INVALID_ATTRIBUTES)
|
||||
});
|
||||
|
||||
let rename = Arc::clone(state);
|
||||
registry.register(KERNEL32, "MoveFileW", move |args, cpu, memory| {
|
||||
let Some(source) = guest_path(memory, args.rcx).map_err(ExitReason::MemoryFault)? else {
|
||||
return rename.fail(cpu.gs_base, INVALID_NAME, 0);
|
||||
};
|
||||
let Some(target) = guest_path(memory, args.rdx).map_err(ExitReason::MemoryFault)? else {
|
||||
return rename.fail(cpu.gs_base, INVALID_NAME, 0);
|
||||
};
|
||||
let mut objects = rename.objects.lock().expect("guest object state");
|
||||
if [parent(&source), parent(&target)]
|
||||
.into_iter()
|
||||
.any(|path| !path.is_empty() && !objects.directories.contains(path))
|
||||
{
|
||||
return rename.fail(cpu.gs_base, PATH_NOT_FOUND, 0);
|
||||
}
|
||||
if objects.directories.contains(&source) {
|
||||
return rename.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
if !objects.files.contains_key(&source) {
|
||||
return rename.fail(cpu.gs_base, FILE_NOT_FOUND, 0);
|
||||
}
|
||||
if objects.files.contains_key(&target) || objects.directories.contains(&target) {
|
||||
return rename.fail(cpu.gs_base, ALREADY_EXISTS, 0);
|
||||
}
|
||||
if objects
|
||||
.handles
|
||||
.values()
|
||||
.any(|object| matches!(object, GuestObject::File(file) if file.path == source))
|
||||
{
|
||||
return rename.fail(cpu.gs_base, SHARING_VIOLATION, 0);
|
||||
}
|
||||
let data = objects.files.remove(&source).expect("source file exists");
|
||||
objects.files.insert(target, data);
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
let find = Arc::clone(state);
|
||||
registry.register(KERNEL32, "FindFirstFileW", move |args, cpu, memory| {
|
||||
let Some(path) = read_guest_path(memory, args.rcx).map_err(ExitReason::MemoryFault)? else {
|
||||
return find.fail(cpu.gs_base, INVALID_NAME, INVALID_HANDLE);
|
||||
};
|
||||
let directory = parent(&path);
|
||||
let pattern = path.rsplit('\\').next().unwrap_or_default();
|
||||
if path.starts_with('\\')
|
||||
|| (!directory.is_empty() && !directory.split('\\').all(valid_component))
|
||||
|| !valid_component(&pattern.replace(['*', '?'], "x"))
|
||||
{
|
||||
return find.fail(cpu.gs_base, INVALID_NAME, INVALID_HANDLE);
|
||||
}
|
||||
let pattern = if pattern == "*.*" { "*" } else { pattern };
|
||||
let mut objects = find.objects.lock().expect("guest object state");
|
||||
if !directory.is_empty() && !objects.directories.contains(directory) {
|
||||
return find.fail(cpu.gs_base, PATH_NOT_FOUND, INVALID_HANDLE);
|
||||
}
|
||||
let candidates = objects
|
||||
.directories
|
||||
.iter()
|
||||
.map(|path| (path, 0x10, 0))
|
||||
.chain(
|
||||
objects
|
||||
.files
|
||||
.iter()
|
||||
.map(|(path, data)| (path, 0x80, data.len() as u64)),
|
||||
);
|
||||
let mut entries = Vec::new();
|
||||
for (path, attributes, size) in candidates.filter(|(path, _, _)| parent(path) == directory)
|
||||
{
|
||||
let name = path.rsplit('\\').next().expect("candidate name");
|
||||
if wildcard_match(pattern, name) {
|
||||
entries.push(SearchEntry {
|
||||
name: name.to_owned(),
|
||||
attributes,
|
||||
size,
|
||||
});
|
||||
}
|
||||
}
|
||||
entries.sort_by(|a, b| a.name.cmp(&b.name));
|
||||
let Some(first) = entries.first() else {
|
||||
return find.fail(cpu.gs_base, FILE_NOT_FOUND, INVALID_HANDLE);
|
||||
};
|
||||
if objects
|
||||
.handles
|
||||
.values()
|
||||
.filter(|object| matches!(object, GuestObject::Search(_)))
|
||||
.count()
|
||||
>= 32
|
||||
{
|
||||
return find.fail(cpu.gs_base, ERROR_NOT_ENOUGH_MEMORY, INVALID_HANDLE);
|
||||
}
|
||||
let Some(handle) = objects.next_handle() else {
|
||||
return find.fail(cpu.gs_base, ERROR_NOT_ENOUGH_MEMORY, INVALID_HANDLE);
|
||||
};
|
||||
if write_find_data(memory, args.rdx, first).is_err() {
|
||||
return find.fail(cpu.gs_base, ERROR_NOACCESS, INVALID_HANDLE);
|
||||
}
|
||||
objects.insert_handle(handle, GuestObject::Search(Search { entries, next: 1 }));
|
||||
Ok(handle)
|
||||
});
|
||||
|
||||
let find_next = Arc::clone(state);
|
||||
registry.register(KERNEL32, "FindNextFileW", move |args, cpu, memory| {
|
||||
let mut objects = find_next.objects.lock().expect("guest object state");
|
||||
let Some(GuestObject::Search(search)) = objects.handles.get_mut(&args.rcx) else {
|
||||
return find_next.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0);
|
||||
};
|
||||
let Some(entry) = search.entries.get(search.next) else {
|
||||
return find_next.fail(cpu.gs_base, 18, 0); // ERROR_NO_MORE_FILES
|
||||
};
|
||||
if write_find_data(memory, args.rdx, entry).is_err() {
|
||||
return find_next.fail(cpu.gs_base, ERROR_NOACCESS, 0);
|
||||
}
|
||||
search.next += 1;
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
let find_close = Arc::clone(state);
|
||||
registry.register(KERNEL32, "FindClose", move |args, cpu, _| {
|
||||
let mut objects = find_close.objects.lock().expect("guest object state");
|
||||
if !matches!(objects.handles.get(&args.rcx), Some(GuestObject::Search(_))) {
|
||||
return find_close.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0);
|
||||
}
|
||||
objects.handles.remove(&args.rcx);
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
let size = Arc::clone(state);
|
||||
registry.register(KERNEL32, "GetFileSizeEx", move |args, cpu, memory| {
|
||||
let objects = size.objects.lock().expect("guest object state");
|
||||
let Some(GuestObject::File(file)) = objects.handles.get(&args.rcx) else {
|
||||
return size.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0);
|
||||
};
|
||||
let bytes = objects
|
||||
.files
|
||||
.get(&file.path)
|
||||
.expect("open file exists")
|
||||
.len();
|
||||
if args.rdx == 0 || memory.write_u64(args.rdx, bytes as u64).is_err() {
|
||||
return size.fail(cpu.gs_base, ERROR_NOACCESS, 0);
|
||||
}
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
let seek = Arc::clone(state);
|
||||
registry.register(KERNEL32, "SetFilePointerEx", move |args, cpu, memory| {
|
||||
let mut objects = seek.objects.lock().expect("guest object state");
|
||||
let super::ObjectState { handles, files, .. } = &mut *objects;
|
||||
let Some(GuestObject::File(file)) = handles.get_mut(&args.rcx) else {
|
||||
return seek.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0);
|
||||
};
|
||||
if file.access & (READ | WRITE) == 0 {
|
||||
return seek.fail(cpu.gs_base, ERROR_ACCESS_DENIED, 0);
|
||||
}
|
||||
let origin = match args.r9 as u32 {
|
||||
0 => None,
|
||||
1 => Some(file.position.load(Ordering::Relaxed)),
|
||||
2 => Some(files.get(&file.path).expect("open file exists").len() as u64),
|
||||
_ => return seek.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0),
|
||||
};
|
||||
let position = match origin {
|
||||
None => args.rdx,
|
||||
Some(origin) => {
|
||||
let distance = args.rdx as i64;
|
||||
if distance.is_negative() && distance.unsigned_abs() > origin {
|
||||
return seek.fail(cpu.gs_base, NEGATIVE_SEEK, 0);
|
||||
}
|
||||
let Some(position) = origin.checked_add_signed(distance) else {
|
||||
return seek.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0);
|
||||
};
|
||||
position
|
||||
}
|
||||
};
|
||||
if args.r8 != 0 && memory.write_u64(args.r8, position).is_err() {
|
||||
return seek.fail(cpu.gs_base, ERROR_NOACCESS, 0);
|
||||
}
|
||||
file.position.store(position, Ordering::Relaxed);
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
let truncate = Arc::clone(state);
|
||||
registry.register(KERNEL32, "SetEndOfFile", move |args, cpu, _| {
|
||||
let mut objects = truncate.objects.lock().expect("guest object state");
|
||||
let super::ObjectState { handles, files, .. } = &mut *objects;
|
||||
let Some(GuestObject::File(file)) = handles.get(&args.rcx) else {
|
||||
return truncate.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0);
|
||||
};
|
||||
if file.access & WRITE == 0 {
|
||||
return truncate.fail(cpu.gs_base, ERROR_ACCESS_DENIED, 0);
|
||||
}
|
||||
let position = file.position.load(Ordering::Relaxed);
|
||||
if position > MAX_BYTES as u64 {
|
||||
return truncate.fail(cpu.gs_base, DISK_FULL, 0);
|
||||
}
|
||||
let used = files.values().map(Vec::len).sum::<usize>();
|
||||
let data = files.get_mut(&file.path).expect("open file exists");
|
||||
let length = position as usize;
|
||||
let growth = length.saturating_sub(data.len());
|
||||
if growth > MAX_BYTES - used {
|
||||
return truncate.fail(cpu.gs_base, DISK_FULL, 0);
|
||||
}
|
||||
data.try_reserve_exact(growth)
|
||||
.map_err(|_| ExitReason::MemoryFault(MemoryError::AllocationFailed))?;
|
||||
if length < data.len() {
|
||||
data.truncate(length);
|
||||
data.shrink_to_fit();
|
||||
} else {
|
||||
data.resize(length, 0);
|
||||
}
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
for (symbol, writing) in [("ReadFile", false), ("WriteFile", true)] {
|
||||
let state = Arc::clone(state);
|
||||
registry.register(KERNEL32, symbol, move |args, cpu, memory| {
|
||||
if args.get(4, memory).map_err(ExitReason::MemoryFault)? != 0 {
|
||||
return state.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
let count = args.r8 as u32 as usize;
|
||||
if count > MAX_TRANSFER {
|
||||
return state.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
let mut objects = state.objects.lock().expect("guest object state");
|
||||
let super::ObjectState { handles, files, .. } = &mut *objects;
|
||||
let Some(GuestObject::File(file)) = handles.get_mut(&args.rcx) else {
|
||||
return state.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0);
|
||||
};
|
||||
let required = if writing { WRITE } else { READ };
|
||||
if file.access & required == 0 {
|
||||
return state.fail(cpu.gs_base, ERROR_ACCESS_DENIED, 0);
|
||||
}
|
||||
if args.r9 == 0 || memory.check_write(args.r9, 4).is_err() {
|
||||
return state.fail(cpu.gs_base, ERROR_NOACCESS, 0);
|
||||
}
|
||||
|
||||
let used = if writing {
|
||||
files.values().map(Vec::len).sum::<usize>()
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let data = files.get_mut(&file.path).expect("open file exists");
|
||||
let position = file.position.load(Ordering::Relaxed);
|
||||
let transferred = if writing {
|
||||
if count == 0 {
|
||||
0
|
||||
} else {
|
||||
let Some(end) = position
|
||||
.checked_add(count as u64)
|
||||
.filter(|end| *end <= MAX_BYTES as u64)
|
||||
else {
|
||||
return state.fail(cpu.gs_base, DISK_FULL, 0);
|
||||
};
|
||||
let end = end as usize;
|
||||
let growth = end.saturating_sub(data.len());
|
||||
if growth > MAX_BYTES - used {
|
||||
return state.fail(cpu.gs_base, DISK_FULL, 0);
|
||||
}
|
||||
let mut input = vec![0; count];
|
||||
if args.rdx == 0 || memory.read_bytes(args.rdx, &mut input).is_err() {
|
||||
return state.fail(cpu.gs_base, ERROR_NOACCESS, 0);
|
||||
}
|
||||
if growth != 0 {
|
||||
data.try_reserve_exact(growth)
|
||||
.map_err(|_| ExitReason::MemoryFault(MemoryError::AllocationFailed))?;
|
||||
data.resize(end, 0);
|
||||
}
|
||||
data[position as usize..end].copy_from_slice(&input);
|
||||
count
|
||||
}
|
||||
} else {
|
||||
let start = position.min(data.len() as u64) as usize;
|
||||
let transferred = count.min(data.len() - start);
|
||||
if transferred != 0
|
||||
&& (args.rdx == 0
|
||||
|| memory
|
||||
.write_bytes(args.rdx, &data[start..start + transferred])
|
||||
.is_err())
|
||||
{
|
||||
return state.fail(cpu.gs_base, ERROR_NOACCESS, 0);
|
||||
}
|
||||
transferred
|
||||
};
|
||||
memory
|
||||
.write_u32(args.r9, transferred as u32)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
file.position
|
||||
.store(position + transferred as u64, Ordering::Relaxed);
|
||||
Ok(1)
|
||||
});
|
||||
}
|
||||
|
||||
for symbol in [
|
||||
"CreateFileW",
|
||||
"GetFileSizeEx",
|
||||
"ReadFile",
|
||||
"WriteFile",
|
||||
"SetFilePointerEx",
|
||||
"SetEndOfFile",
|
||||
"CreateDirectoryW",
|
||||
"RemoveDirectoryW",
|
||||
"DeleteFileW",
|
||||
"GetFileAttributesW",
|
||||
"MoveFileW",
|
||||
"FindFirstFileW",
|
||||
"FindNextFileW",
|
||||
"FindClose",
|
||||
] {
|
||||
registry.alias(FILE_API, KERNEL32, symbol);
|
||||
registry.set_status(KERNEL32, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Handle ownership for the documented manual GDK task queue subset.
|
||||
|
||||
use super::ServicesState;
|
||||
use super::{ERROR_INVALID_HANDLE, ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED};
|
||||
use crate::cpu::ExitReason;
|
||||
use crate::imports::{GuestCallback, ImportRegistry, ServiceStatus};
|
||||
use crate::memory::GuestMemory;
|
||||
use crate::runtime::HResult;
|
||||
use std::collections::{BTreeMap, BTreeSet, VecDeque};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const MODULE: &str = "xgameruntime.dll";
|
||||
const MAX_HANDLES: usize = 64;
|
||||
const MAX_DISPATCH_WAIT_MS: u32 = 1_000;
|
||||
const MAX_CALLBACKS_PER_PORT: usize = 32;
|
||||
const ERROR_OUTOFMEMORY: u32 = 14;
|
||||
const MANUAL: u32 = 0;
|
||||
const E_ABORT: u64 = 0x8000_4004;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct QueueHandles {
|
||||
last_id: u64,
|
||||
queues: BTreeMap<u64, Queue>,
|
||||
terminated: BTreeSet<u64>,
|
||||
pending: BTreeMap<u64, VecDeque<ScheduledCallback>>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Queue {
|
||||
id: u64,
|
||||
ports: [u64; 2],
|
||||
}
|
||||
|
||||
struct ScheduledCallback {
|
||||
owner: u64,
|
||||
ready_at: Instant,
|
||||
callback: GuestCallback,
|
||||
}
|
||||
|
||||
impl QueueHandles {
|
||||
fn open(
|
||||
&mut self,
|
||||
duplicate: Option<Queue>,
|
||||
composite: Option<[u64; 2]>,
|
||||
output: u64,
|
||||
memory: &mut GuestMemory,
|
||||
) -> Result<(), u32> {
|
||||
if output == 0 {
|
||||
return Err(ERROR_INVALID_PARAMETER);
|
||||
}
|
||||
if self.queues.len() == MAX_HANDLES {
|
||||
return Err(ERROR_OUTOFMEMORY);
|
||||
}
|
||||
let next = self
|
||||
.last_id
|
||||
.checked_add(1)
|
||||
.filter(|id| *id < (1 << 48))
|
||||
.ok_or(ERROR_OUTOFMEMORY)?;
|
||||
let handle = 0x5144_0000_0000_0000 | next;
|
||||
memory
|
||||
.write_u64(output, handle)
|
||||
.map_err(|_| ERROR_INVALID_PARAMETER)?;
|
||||
self.last_id = next;
|
||||
self.queues.insert(
|
||||
handle,
|
||||
duplicate.unwrap_or(Queue {
|
||||
id: handle,
|
||||
ports: composite
|
||||
.unwrap_or([0x5157_0000_0000_0000 | next, 0x5143_0000_0000_0000 | next]),
|
||||
}),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn close(&mut self, handle: u64) {
|
||||
if let Some(queue) = self.queues.remove(&handle) {
|
||||
if !self.queues.values().any(|live| live.id == queue.id) {
|
||||
self.terminated.remove(&queue.id);
|
||||
}
|
||||
for port in queue.ports {
|
||||
if !self.queues.values().any(|live| live.ports.contains(&port)) {
|
||||
self.pending.remove(&port);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn submit(
|
||||
&mut self,
|
||||
handle: u64,
|
||||
selector: u32,
|
||||
mut callback: ScheduledCallback,
|
||||
) -> Result<(), u32> {
|
||||
let queue = self.queues.get(&handle).ok_or(ERROR_INVALID_HANDLE)?;
|
||||
callback.owner = queue.id;
|
||||
let port = queue
|
||||
.ports
|
||||
.get(selector as usize)
|
||||
.ok_or(ERROR_INVALID_PARAMETER)?;
|
||||
let queue = self.pending.entry(*port).or_default();
|
||||
if queue.len() >= MAX_CALLBACKS_PER_PORT {
|
||||
return Err(ERROR_OUTOFMEMORY);
|
||||
}
|
||||
let index = queue.partition_point(|item| item.ready_at <= callback.ready_at);
|
||||
queue.insert(index, callback);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn guest_hresult(result: Result<(), u32>) -> u64 {
|
||||
match result {
|
||||
Ok(()) => HResult::OK.guest_return(),
|
||||
Err(error) => HResult::from_win32(error).guest_return(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
let create = Arc::clone(state);
|
||||
registry.register_with_status(
|
||||
MODULE,
|
||||
"XTaskQueueCreate",
|
||||
ServiceStatus::Partial,
|
||||
move |args, _, memory| {
|
||||
if args.rcx as u32 != MANUAL || args.rdx as u32 != MANUAL {
|
||||
return Ok(guest_hresult(Err(ERROR_NOT_SUPPORTED)));
|
||||
}
|
||||
let mut queues = create.gdk_queues.lock().expect("GDK queue handle table");
|
||||
Ok(guest_hresult(queues.open(None, None, args.r8, memory)))
|
||||
},
|
||||
);
|
||||
|
||||
let duplicate = Arc::clone(state);
|
||||
registry.register_with_status(
|
||||
MODULE,
|
||||
"XTaskQueueDuplicateHandle",
|
||||
ServiceStatus::Partial,
|
||||
move |args, _, memory| {
|
||||
let mut queues = duplicate.gdk_queues.lock().expect("GDK queue handle table");
|
||||
let Some(&object) = queues.queues.get(&args.rcx) else {
|
||||
return Ok(guest_hresult(Err(ERROR_INVALID_HANDLE)));
|
||||
};
|
||||
Ok(guest_hresult(queues.open(
|
||||
Some(object),
|
||||
None,
|
||||
args.rdx,
|
||||
memory,
|
||||
)))
|
||||
},
|
||||
);
|
||||
|
||||
let close = Arc::clone(state);
|
||||
registry.register_with_status(
|
||||
MODULE,
|
||||
"XTaskQueueCloseHandle",
|
||||
ServiceStatus::Partial,
|
||||
move |args, _, _| {
|
||||
close
|
||||
.gdk_queues
|
||||
.lock()
|
||||
.expect("GDK queue handle table")
|
||||
.close(args.rcx);
|
||||
close.gdk_queue_changed.notify_all();
|
||||
Ok(0)
|
||||
},
|
||||
);
|
||||
|
||||
let get = Arc::clone(state);
|
||||
registry.register_with_status(
|
||||
MODULE,
|
||||
"XTaskQueueGetPort",
|
||||
ServiceStatus::Partial,
|
||||
move |args, _, memory| {
|
||||
let result = (|| {
|
||||
let queues = get.gdk_queues.lock().expect("GDK queue handle table");
|
||||
let ports = queues.queues.get(&args.rcx).ok_or(ERROR_INVALID_HANDLE)?;
|
||||
let port = ports
|
||||
.ports
|
||||
.get(args.rdx as u32 as usize)
|
||||
.ok_or(ERROR_INVALID_PARAMETER)?;
|
||||
if args.r8 == 0 {
|
||||
return Err(ERROR_INVALID_PARAMETER);
|
||||
}
|
||||
memory
|
||||
.write_u64(args.r8, *port)
|
||||
.map_err(|_| ERROR_INVALID_PARAMETER)
|
||||
})();
|
||||
Ok(guest_hresult(result))
|
||||
},
|
||||
);
|
||||
|
||||
let composite = Arc::clone(state);
|
||||
registry.register_with_status(
|
||||
MODULE,
|
||||
"XTaskQueueCreateComposite",
|
||||
ServiceStatus::Partial,
|
||||
move |args, _, memory| {
|
||||
let mut queues = composite.gdk_queues.lock().expect("GDK queue handle table");
|
||||
let ports = [args.rcx, args.rdx];
|
||||
if ports
|
||||
.iter()
|
||||
.any(|port| !queues.queues.values().any(|live| live.ports.contains(port)))
|
||||
{
|
||||
return Ok(guest_hresult(Err(ERROR_INVALID_HANDLE)));
|
||||
}
|
||||
Ok(guest_hresult(queues.open(
|
||||
None,
|
||||
Some(ports),
|
||||
args.r8,
|
||||
memory,
|
||||
)))
|
||||
},
|
||||
);
|
||||
|
||||
for (symbol, delayed) in [
|
||||
("XTaskQueueSubmitCallback", false),
|
||||
("XTaskQueueSubmitDelayedCallback", true),
|
||||
] {
|
||||
let submit = Arc::clone(state);
|
||||
registry.register_with_status(
|
||||
MODULE,
|
||||
symbol,
|
||||
ServiceStatus::Partial,
|
||||
move |args, _, memory| {
|
||||
let (delay, context, entry) = if delayed {
|
||||
let Ok(entry) = args.get(4, memory) else {
|
||||
return Ok(guest_hresult(Err(ERROR_INVALID_PARAMETER)));
|
||||
};
|
||||
(args.r8 as u32, args.r9, entry)
|
||||
} else {
|
||||
(0, args.r8, args.r9)
|
||||
};
|
||||
if entry == 0 || memory.fetch_instruction_byte(entry).is_err() {
|
||||
return Ok(guest_hresult(Err(ERROR_INVALID_PARAMETER)));
|
||||
}
|
||||
let mut queues = submit.gdk_queues.lock().expect("GDK queue handle table");
|
||||
if queues
|
||||
.queues
|
||||
.get(&args.rcx)
|
||||
.is_some_and(|queue| queues.terminated.contains(&queue.id))
|
||||
{
|
||||
return Ok(E_ABORT);
|
||||
}
|
||||
let callback = ScheduledCallback {
|
||||
owner: 0,
|
||||
ready_at: Instant::now() + Duration::from_millis(u64::from(delay)),
|
||||
callback: GuestCallback {
|
||||
entry,
|
||||
context,
|
||||
cancelled: false,
|
||||
},
|
||||
};
|
||||
let result = queues.submit(args.rcx, args.rdx as u32, callback);
|
||||
if result.is_ok() {
|
||||
submit.gdk_queue_changed.notify_all();
|
||||
}
|
||||
Ok(guest_hresult(result))
|
||||
},
|
||||
);
|
||||
}
|
||||
let terminate = Arc::clone(state);
|
||||
registry.register_with_status(
|
||||
MODULE,
|
||||
"XTaskQueueTerminate",
|
||||
ServiceStatus::Partial,
|
||||
move |args, _, _| {
|
||||
if args.rdx as u8 != 0 || args.r9 != 0 {
|
||||
return Ok(guest_hresult(Err(ERROR_NOT_SUPPORTED)));
|
||||
}
|
||||
let mut queues = terminate.gdk_queues.lock().expect("GDK queue handle table");
|
||||
let Some(&queue) = queues.queues.get(&args.rcx) else {
|
||||
return Ok(guest_hresult(Err(ERROR_INVALID_HANDLE)));
|
||||
};
|
||||
if queues.terminated.insert(queue.id) {
|
||||
let now = Instant::now();
|
||||
for pending in queues.pending.values_mut() {
|
||||
for item in pending.iter_mut().filter(|item| item.owner == queue.id) {
|
||||
item.ready_at = item.ready_at.min(now);
|
||||
item.callback.cancelled = true;
|
||||
}
|
||||
pending.make_contiguous().sort_by_key(|item| item.ready_at);
|
||||
}
|
||||
terminate.gdk_queue_changed.notify_all();
|
||||
}
|
||||
Ok(0)
|
||||
},
|
||||
);
|
||||
let dispatch = Arc::clone(state);
|
||||
registry.register_callback_dispatch(MODULE, "XTaskQueueDispatch", move |args, memory| {
|
||||
let timeout = args.r8 as u32;
|
||||
if timeout > MAX_DISPATCH_WAIT_MS {
|
||||
return Ok(None);
|
||||
}
|
||||
let deadline = Instant::now() + Duration::from_millis(u64::from(timeout));
|
||||
let mut queues = dispatch.gdk_queues.lock().expect("GDK queue handle table");
|
||||
loop {
|
||||
let Some(&queue) = queues.queues.get(&args.rcx) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let Some(&port) = queue.ports.get(args.rdx as u32 as usize) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let terminated = queues.terminated.contains(&queue.id);
|
||||
let now = Instant::now();
|
||||
let mut wake_at = deadline;
|
||||
if let Some(pending) = queues.pending.get_mut(&port)
|
||||
&& let Some((index, item)) = pending
|
||||
.iter()
|
||||
.enumerate()
|
||||
.find(|(_, item)| !terminated || item.owner == queue.id)
|
||||
{
|
||||
if item.ready_at <= now {
|
||||
memory
|
||||
.fetch_instruction_byte(item.callback.entry)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
return Ok(pending.remove(index).map(|item| item.callback));
|
||||
}
|
||||
wake_at = wake_at.min(item.ready_at);
|
||||
}
|
||||
if terminated {
|
||||
return Ok(None);
|
||||
}
|
||||
let remaining = wake_at.saturating_duration_since(now);
|
||||
if remaining.is_zero() {
|
||||
return Ok(None);
|
||||
}
|
||||
(queues, _) = dispatch
|
||||
.gdk_queue_changed
|
||||
.wait_timeout(queues, remaining)
|
||||
.expect("GDK queue handle table");
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Guest heap services backed by owned guest memory regions.
|
||||
|
||||
use super::{
|
||||
ERROR_INVALID_ADDRESS, ERROR_INVALID_HANDLE, ERROR_NOT_ENOUGH_MEMORY, ERROR_NOT_SUPPORTED,
|
||||
KERNEL32, ServicesState,
|
||||
};
|
||||
use crate::cpu::ExitReason;
|
||||
use crate::imports::{ImportRegistry, ServiceStatus};
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::memory::PROCESS_HEAP;
|
||||
const HEAP_ZERO_MEMORY: u32 = 8;
|
||||
const HEAP_REALLOC_IN_PLACE_ONLY: u32 = 16;
|
||||
const HEAP_API: &str = "api-ms-win-core-heap-l1-1-0.dll";
|
||||
|
||||
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
registry.register(KERNEL32, "GetProcessHeap", |_, _, _| Ok(PROCESS_HEAP));
|
||||
|
||||
registry.register(KERNEL32, "HeapAlloc", |args, _, memory| {
|
||||
let handle = args.get(0, memory).map_err(ExitReason::MemoryFault)?;
|
||||
let flags = args.get(1, memory).map_err(ExitReason::MemoryFault)? as u32;
|
||||
let size = args.get(2, memory).map_err(ExitReason::MemoryFault)?;
|
||||
if !memory.has_heap(handle) || flags & !HEAP_ZERO_MEMORY != 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
Ok(memory
|
||||
.map_heap_allocation(handle, size.max(1) as usize)
|
||||
.unwrap_or(0))
|
||||
});
|
||||
|
||||
registry.register(KERNEL32, "HeapReAlloc", |args, _, memory| {
|
||||
let handle = args.get(0, memory).map_err(ExitReason::MemoryFault)?;
|
||||
let flags = args.get(1, memory).map_err(ExitReason::MemoryFault)? as u32;
|
||||
let address = args.get(2, memory).map_err(ExitReason::MemoryFault)?;
|
||||
let size = args.get(3, memory).map_err(ExitReason::MemoryFault)?;
|
||||
if !memory.has_heap(handle) || flags & !(HEAP_ZERO_MEMORY | HEAP_REALLOC_IN_PLACE_ONLY) != 0
|
||||
{
|
||||
return Ok(0);
|
||||
}
|
||||
let in_place_only = flags & HEAP_REALLOC_IN_PLACE_ONLY != 0;
|
||||
Ok(memory
|
||||
.resize_heap_allocation(handle, address, size.max(1) as usize, in_place_only)
|
||||
.unwrap_or(0))
|
||||
});
|
||||
|
||||
registry.register(KERNEL32, "HeapSize", |args, _, memory| {
|
||||
let handle = args.get(0, memory).map_err(ExitReason::MemoryFault)?;
|
||||
let flags = args.get(1, memory).map_err(ExitReason::MemoryFault)? as u32;
|
||||
let address = args.get(2, memory).map_err(ExitReason::MemoryFault)?;
|
||||
if !memory.has_heap(handle) || flags != 0 {
|
||||
return Ok(u64::MAX);
|
||||
}
|
||||
Ok(memory
|
||||
.heap_allocation_size(handle, address)
|
||||
.map_or(u64::MAX, |size| size as u64))
|
||||
});
|
||||
|
||||
let service_state = Arc::clone(state);
|
||||
registry.register(KERNEL32, "HeapCreate", move |args, cpu, memory| {
|
||||
let flags = args.get(0, memory).map_err(ExitReason::MemoryFault)? as u32;
|
||||
let initial = args.get(1, memory).map_err(ExitReason::MemoryFault)?;
|
||||
let maximum = args.get(2, memory).map_err(ExitReason::MemoryFault)?;
|
||||
if flags != 0 || maximum != 0 {
|
||||
return service_state.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
match memory.create_private_heap(initial) {
|
||||
Some(handle) => Ok(handle),
|
||||
None => service_state.fail(cpu.gs_base, ERROR_NOT_ENOUGH_MEMORY, 0),
|
||||
}
|
||||
});
|
||||
|
||||
let service_state = Arc::clone(state);
|
||||
registry.register(KERNEL32, "HeapDestroy", move |args, cpu, memory| {
|
||||
let handle = args.get(0, memory).map_err(ExitReason::MemoryFault)?;
|
||||
if !memory.destroy_private_heap(handle) {
|
||||
return service_state.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0);
|
||||
}
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
let state = Arc::clone(state);
|
||||
registry.register(KERNEL32, "HeapFree", move |args, cpu, memory| {
|
||||
let handle = args.get(0, memory).map_err(ExitReason::MemoryFault)?;
|
||||
let flags = args.get(1, memory).map_err(ExitReason::MemoryFault)? as u32;
|
||||
let address = args.get(2, memory).map_err(ExitReason::MemoryFault)?;
|
||||
if !memory.has_heap(handle) {
|
||||
return state.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0);
|
||||
}
|
||||
if flags != 0 {
|
||||
return state.fail(cpu.gs_base, ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
if address != 0 && !memory.release_heap_allocation(handle, address) {
|
||||
return state.fail(cpu.gs_base, ERROR_INVALID_ADDRESS, 0);
|
||||
}
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
for symbol in [
|
||||
"GetProcessHeap",
|
||||
"HeapAlloc",
|
||||
"HeapReAlloc",
|
||||
"HeapSize",
|
||||
"HeapFree",
|
||||
"HeapCreate",
|
||||
"HeapDestroy",
|
||||
] {
|
||||
registry.alias(HEAP_API, KERNEL32, symbol);
|
||||
registry.set_status(KERNEL32, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Module and export lookup for built-in guest services.
|
||||
|
||||
use super::{ERROR_INVALID_HANDLE, ERROR_NOT_ENOUGH_MEMORY, KERNEL32, ServicesState};
|
||||
use crate::cpu::ExitReason;
|
||||
use crate::import_table::ImportName;
|
||||
use crate::imports::{ImportRegistry, ServiceStatus};
|
||||
use crate::memory::{GuestMemory, MemoryError};
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
|
||||
const LOADER_API: &str = "api-ms-win-core-libraryloader-l1-2-0.dll";
|
||||
const UCRT: &str = "ucrtbase.dll";
|
||||
const MODULE_NOT_FOUND: u32 = 126;
|
||||
const PROCEDURE_NOT_FOUND: u32 = 127;
|
||||
const MODULE_BASE: u64 = 0x0000_0007_e000_0000;
|
||||
|
||||
#[derive(Default)]
|
||||
struct Modules {
|
||||
names: BTreeMap<String, u64>,
|
||||
exports: BTreeMap<u64, HashMap<ImportName, usize>>,
|
||||
references: Mutex<BTreeMap<u64, u32>>,
|
||||
}
|
||||
|
||||
fn read_name(
|
||||
memory: &GuestMemory,
|
||||
address: u64,
|
||||
wide: bool,
|
||||
) -> Result<Option<String>, MemoryError> {
|
||||
let mut name = String::new();
|
||||
let width = if wide { 2 } else { 1 };
|
||||
for index in 0..260 {
|
||||
let slot = address
|
||||
.checked_add(index * width)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
let unit = if wide {
|
||||
memory.read_u16(slot)?
|
||||
} else {
|
||||
u16::from(memory.read_u8(slot)?)
|
||||
};
|
||||
if unit == 0 {
|
||||
return Ok(Some(name));
|
||||
}
|
||||
if !(0x20..=0x7e).contains(&unit) {
|
||||
return Ok(None);
|
||||
}
|
||||
name.push(char::from(unit as u8));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
let modules = Arc::new(OnceLock::<Modules>::new());
|
||||
let named_operations = [
|
||||
("GetModuleHandleA", false, false),
|
||||
("GetModuleHandleW", true, false),
|
||||
("LoadLibraryA", false, true),
|
||||
("LoadLibraryW", true, true),
|
||||
];
|
||||
for (symbol, wide, load) in named_operations {
|
||||
let state = Arc::clone(state);
|
||||
let modules = Arc::clone(&modules);
|
||||
registry.register(KERNEL32, symbol, move |args, cpu, memory| {
|
||||
if args.rcx == 0 {
|
||||
return state.fail(cpu.gs_base, MODULE_NOT_FOUND, 0);
|
||||
}
|
||||
let Some(name) = read_name(memory, args.rcx, wide).map_err(ExitReason::MemoryFault)?
|
||||
else {
|
||||
return state.fail(cpu.gs_base, MODULE_NOT_FOUND, 0);
|
||||
};
|
||||
let mut name = name.to_ascii_lowercase();
|
||||
if !name.contains('.') {
|
||||
name.push_str(".dll");
|
||||
}
|
||||
let modules = modules.get().expect("built-in module catalog");
|
||||
let Some(&handle) = modules.names.get(&name) else {
|
||||
return state.fail(cpu.gs_base, MODULE_NOT_FOUND, 0);
|
||||
};
|
||||
let mut references = modules.references.lock().expect("module references");
|
||||
if load {
|
||||
let count = references.entry(handle).or_default();
|
||||
let Some(next) = count.checked_add(1) else {
|
||||
return state.fail(cpu.gs_base, ERROR_NOT_ENOUGH_MEMORY, 0);
|
||||
};
|
||||
*count = next;
|
||||
} else if handle != MODULE_BASE && !references.contains_key(&handle) {
|
||||
return state.fail(cpu.gs_base, MODULE_NOT_FOUND, 0);
|
||||
}
|
||||
Ok(handle)
|
||||
});
|
||||
}
|
||||
|
||||
let release = Arc::clone(&modules);
|
||||
let release_state = Arc::clone(state);
|
||||
let release_trampolines = registry.dynamic_trampolines();
|
||||
registry.register(KERNEL32, "FreeLibrary", move |args, cpu, _| {
|
||||
let modules = release.get().expect("built-in module catalog");
|
||||
let mut references = modules.references.lock().expect("module references");
|
||||
let Some(count) = references.get_mut(&args.rcx) else {
|
||||
return release_state.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0);
|
||||
};
|
||||
*count -= 1;
|
||||
if *count == 0 {
|
||||
references.remove(&args.rcx);
|
||||
if args.rcx != MODULE_BASE {
|
||||
release_trampolines.revoke(modules.exports[&args.rcx].values().copied());
|
||||
}
|
||||
}
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
let lookup = Arc::clone(&modules);
|
||||
let trampolines = registry.dynamic_trampolines();
|
||||
let state = Arc::clone(state);
|
||||
registry.register(KERNEL32, "GetProcAddress", move |args, cpu, memory| {
|
||||
let modules = lookup.get().expect("built-in module catalog");
|
||||
let references = modules.references.lock().expect("module references");
|
||||
if args.rcx != MODULE_BASE && !references.contains_key(&args.rcx) {
|
||||
return state.fail(cpu.gs_base, ERROR_INVALID_HANDLE, 0);
|
||||
}
|
||||
let export = if let Ok(ordinal) = u16::try_from(args.rdx) {
|
||||
ImportName::Ordinal(ordinal)
|
||||
} else {
|
||||
let Some(symbol) =
|
||||
read_name(memory, args.rdx, false).map_err(ExitReason::MemoryFault)?
|
||||
else {
|
||||
return state.fail(cpu.gs_base, PROCEDURE_NOT_FOUND, 0);
|
||||
};
|
||||
ImportName::Name(symbol)
|
||||
};
|
||||
match modules.exports[&args.rcx].get(&export) {
|
||||
Some(&index) => Ok(trampolines.expose(index)),
|
||||
None => state.fail(cpu.gs_base, PROCEDURE_NOT_FOUND, 0),
|
||||
}
|
||||
});
|
||||
|
||||
for symbol in named_operations
|
||||
.map(|(symbol, _, _)| symbol)
|
||||
.into_iter()
|
||||
.chain(["GetProcAddress", "FreeLibrary"])
|
||||
{
|
||||
registry.alias(LOADER_API, KERNEL32, symbol);
|
||||
registry.set_status(KERNEL32, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
|
||||
let mut catalog = Modules::default();
|
||||
// Preserve the startup UCRT binding. Kernel services are resident.
|
||||
catalog.references.get_mut().unwrap().insert(UCRT_HANDLE, 1);
|
||||
for (module, handle) in [(KERNEL32, MODULE_BASE), (UCRT, UCRT_HANDLE)] {
|
||||
catalog.names.insert(module.to_owned(), handle);
|
||||
catalog.exports.insert(
|
||||
handle,
|
||||
registry
|
||||
.canonical_exports(module)
|
||||
.map(|(key, index)| (key.clone(), index))
|
||||
.collect(),
|
||||
);
|
||||
for (alias, _, canonical) in registry.iter_aliases() {
|
||||
if canonical == module {
|
||||
catalog.names.insert(alias.to_owned(), handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(modules.set(catalog).is_ok());
|
||||
}
|
||||
|
||||
const UCRT_HANDLE: u64 = MODULE_BASE + 0x10000;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::cpu::{CpuState, Register};
|
||||
use crate::imports::Win64Args;
|
||||
use crate::memory::MemoryPermissions;
|
||||
use crate::services::{MockClock, register_standard_services};
|
||||
|
||||
#[test]
|
||||
fn guest_module_references_control_dynamic_export_lifetime() {
|
||||
let mut registry = ImportRegistry::new();
|
||||
registry.register(UCRT, "SyntheticOrdinalExport", |_, _, _| Ok(42));
|
||||
registry
|
||||
.try_ordinal_alias(UCRT, "SyntheticOrdinalExport", 42)
|
||||
.unwrap();
|
||||
registry.register(UCRT, "OtherSyntheticExport", |_, _, _| Ok(43));
|
||||
assert!(
|
||||
registry
|
||||
.try_ordinal_alias(UCRT, "OtherSyntheticExport", 42)
|
||||
.is_err()
|
||||
);
|
||||
register_standard_services(
|
||||
&mut registry,
|
||||
Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))),
|
||||
);
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region(0x10000, 4096, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
memory.write_bytes(0x10000, b"UCRTBASE\0").unwrap();
|
||||
memory.write_bytes(0x10100, b"sqrt\0").unwrap();
|
||||
memory.write_bytes(0x10200, b"/unknown.dll\0").unwrap();
|
||||
memory.write_bytes(0x10300, b"Ordinal#42\0").unwrap();
|
||||
let mut call = |symbol: &str, first, second| {
|
||||
let mut cpu = CpuState::default();
|
||||
cpu.set(Register::Rcx, first);
|
||||
cpu.set(Register::Rdx, second);
|
||||
let service = registry
|
||||
.resolve(LOADER_API, &ImportName::Name(symbol.to_owned()))
|
||||
.unwrap();
|
||||
(service.handler)(&Win64Args::new(&cpu), &mut cpu, &mut memory).unwrap()
|
||||
};
|
||||
assert_eq!(call("LoadLibraryA", 0x10200, 0), 0);
|
||||
let handle = call("GetModuleHandleA", 0x10000, 0);
|
||||
assert_ne!(handle, 0);
|
||||
assert_eq!(call("LoadLibraryA", 0x10000, 0), handle);
|
||||
let export = call("GetProcAddress", handle, 0x10100);
|
||||
let ordinal = call("GetProcAddress", handle, 42);
|
||||
assert!(registry.is_service_trampoline(ordinal));
|
||||
assert_ne!(ordinal, export);
|
||||
assert_eq!(call("GetProcAddress", handle, 43), 0);
|
||||
assert_eq!(call("GetProcAddress", handle, 0x10300), 0);
|
||||
assert!(registry.is_service_trampoline(export));
|
||||
assert_eq!(call("FreeLibrary", handle, 0), 1);
|
||||
assert!(registry.is_service_trampoline(export));
|
||||
assert_eq!(call("FreeLibrary", handle, 0), 1);
|
||||
assert!(!registry.is_service_trampoline(export));
|
||||
assert!(!registry.is_service_trampoline(ordinal));
|
||||
assert_eq!(call("GetModuleHandleA", 0x10000, 0), 0);
|
||||
assert_eq!(call("GetProcAddress", handle, 0x10100), 0);
|
||||
assert_eq!(call("FreeLibrary", handle, 0), 0);
|
||||
assert_eq!(call("LoadLibraryA", 0x10000, 0), handle);
|
||||
assert_ne!(call("GetProcAddress", handle, 0x10100), 0);
|
||||
let ordinal = call("GetProcAddress", handle, 42);
|
||||
let mut cpu = CpuState::new(ordinal, 0x10400);
|
||||
memory.write_u64(0x10400, 0x1234).unwrap();
|
||||
registry.dispatch(ordinal, &mut cpu, &mut memory).unwrap();
|
||||
assert_eq!(cpu.get(Register::Rax), 42);
|
||||
assert_eq!(cpu.rip, 0x1234);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Process-local platform services for original guest fixtures.
|
||||
|
||||
use super::{ERROR_INVALID_PARAMETER, ERROR_NOACCESS, ERROR_NOT_ENOUGH_MEMORY, ServicesState};
|
||||
use crate::imports::ImportRegistry;
|
||||
use std::collections::{BTreeMap, VecDeque};
|
||||
use std::sync::Arc;
|
||||
|
||||
const MODULE: &str = "xenora_fixture.dll";
|
||||
const FIXTURE_APP_ID: u64 = 0x5845_4e4f_5241_0001;
|
||||
const ERROR_NOT_FOUND: u32 = 1168;
|
||||
const ERROR_INVALID_STATE: u32 = 5023;
|
||||
const MAX_SETTINGS: usize = 32;
|
||||
const MAX_SAVE_SLOTS: usize = 32;
|
||||
const MAX_SAVE_BYTES: usize = 4096;
|
||||
const SAVE_QUOTA: usize = 16 * 1024;
|
||||
const ERROR_DISK_FULL: u32 = 112;
|
||||
const ERROR_INSUFFICIENT_BUFFER: u32 = 122;
|
||||
const CAP_LOCAL_SETTINGS: u64 = 1 << 0;
|
||||
const CAP_LOCAL_SAVES: u64 = 1 << 1;
|
||||
const CAP_LOCAL_PROFILES: u64 = 1 << 2;
|
||||
const CAP_PROFILE_NOTIFICATIONS: u64 = 1 << 3;
|
||||
const MAX_PROFILES: u64 = 8;
|
||||
const MAX_NOTIFICATIONS: usize = 16;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct PlatformFixture {
|
||||
active: bool,
|
||||
settings: BTreeMap<u32, u64>,
|
||||
saves: BTreeMap<u32, Vec<u8>>,
|
||||
profile_count: u64,
|
||||
selected_profile: u64,
|
||||
profile_changes: VecDeque<(u64, u64)>,
|
||||
}
|
||||
|
||||
impl PlatformFixture {
|
||||
fn used_save_bytes(&self) -> usize {
|
||||
self.saves.values().map(Vec::len).sum()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
for (symbol, active) in [
|
||||
("OpenFixturePlatform", true),
|
||||
("CloseFixturePlatform", false),
|
||||
] {
|
||||
let state = Arc::clone(state);
|
||||
registry.register(MODULE, symbol, move |_, cpu, _| {
|
||||
let mut platform = state.platform_fixture.lock().expect("fixture platform");
|
||||
if platform.active == active {
|
||||
return state.fail(cpu.gs_base, ERROR_INVALID_STATE, 0);
|
||||
}
|
||||
platform.active = active;
|
||||
Ok(1)
|
||||
});
|
||||
}
|
||||
|
||||
let identity = Arc::clone(state);
|
||||
registry.register(MODULE, "GetFixtureApplicationId", move |_, cpu, _| {
|
||||
let platform = identity.platform_fixture.lock().expect("fixture platform");
|
||||
if !platform.active {
|
||||
return identity.fail(cpu.gs_base, ERROR_INVALID_STATE, 0);
|
||||
}
|
||||
Ok(FIXTURE_APP_ID)
|
||||
});
|
||||
|
||||
let set = Arc::clone(state);
|
||||
registry.register(MODULE, "SetFixtureSetting", move |args, cpu, _| {
|
||||
let mut platform = set.platform_fixture.lock().expect("fixture platform");
|
||||
if !platform.active {
|
||||
return set.fail(cpu.gs_base, ERROR_INVALID_STATE, 0);
|
||||
}
|
||||
let key = args.rcx as u32;
|
||||
if key == 0 {
|
||||
return set.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
if platform.settings.len() >= MAX_SETTINGS && !platform.settings.contains_key(&key) {
|
||||
return set.fail(cpu.gs_base, ERROR_NOT_ENOUGH_MEMORY, 0);
|
||||
}
|
||||
platform.settings.insert(key, args.rdx);
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
let get = Arc::clone(state);
|
||||
registry.register(MODULE, "GetFixtureSetting", move |args, cpu, memory| {
|
||||
let platform = get.platform_fixture.lock().expect("fixture platform");
|
||||
if !platform.active {
|
||||
return get.fail(cpu.gs_base, ERROR_INVALID_STATE, 0);
|
||||
}
|
||||
let key = args.rcx as u32;
|
||||
if key == 0 {
|
||||
return get.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
let Some(&value) = platform.settings.get(&key) else {
|
||||
return get.fail(cpu.gs_base, ERROR_NOT_FOUND, 0);
|
||||
};
|
||||
if args.rdx == 0 || memory.write_u64(args.rdx, value).is_err() {
|
||||
return get.fail(cpu.gs_base, ERROR_NOACCESS, 0);
|
||||
}
|
||||
Ok(1)
|
||||
});
|
||||
register_saves(registry, state);
|
||||
register_profiles(registry, state);
|
||||
|
||||
let capabilities = Arc::clone(state);
|
||||
registry.register(
|
||||
MODULE,
|
||||
"GetFixturePlatformCapabilities",
|
||||
move |_, cpu, _| {
|
||||
let platform = capabilities
|
||||
.platform_fixture
|
||||
.lock()
|
||||
.expect("fixture platform");
|
||||
if !platform.active {
|
||||
return capabilities.fail(cpu.gs_base, ERROR_INVALID_STATE, 0);
|
||||
}
|
||||
Ok(CAP_LOCAL_SETTINGS
|
||||
| CAP_LOCAL_SAVES
|
||||
| CAP_LOCAL_PROFILES
|
||||
| CAP_PROFILE_NOTIFICATIONS)
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn register_saves(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
let quota = Arc::clone(state);
|
||||
registry.register(MODULE, "GetFixtureSaveQuota", move |args, cpu, memory| {
|
||||
let platform = quota.platform_fixture.lock().expect("fixture platform");
|
||||
if !platform.active {
|
||||
return quota.fail(cpu.gs_base, ERROR_INVALID_STATE, 0);
|
||||
}
|
||||
// Both values are byte counts. Write the whole record or leave it untouched.
|
||||
let mut record = [0; 16];
|
||||
record[..8].copy_from_slice(&(SAVE_QUOTA as u64).to_le_bytes());
|
||||
record[8..].copy_from_slice(&(platform.used_save_bytes() as u64).to_le_bytes());
|
||||
if args.rcx == 0 || memory.write_bytes(args.rcx, &record).is_err() {
|
||||
return quota.fail(cpu.gs_base, ERROR_NOACCESS, 0);
|
||||
}
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
let save = Arc::clone(state);
|
||||
registry.register(MODULE, "WriteFixtureSave", move |args, cpu, memory| {
|
||||
let mut platform = save.platform_fixture.lock().expect("fixture platform");
|
||||
let fail = |error| save.fail(cpu.gs_base, error, 0);
|
||||
if !platform.active {
|
||||
return fail(ERROR_INVALID_STATE);
|
||||
}
|
||||
let slot = args.rcx as u32;
|
||||
let size = args.r8;
|
||||
if slot == 0 || !(1..=MAX_SAVE_BYTES as u64).contains(&size) {
|
||||
return fail(ERROR_INVALID_PARAMETER);
|
||||
}
|
||||
let previous = platform.saves.get(&slot);
|
||||
let used = platform.used_save_bytes();
|
||||
let size = size as usize;
|
||||
if (previous.is_none() && platform.saves.len() == MAX_SAVE_SLOTS)
|
||||
|| used - previous.map_or(0, Vec::len) + size > SAVE_QUOTA
|
||||
{
|
||||
return fail(ERROR_DISK_FULL);
|
||||
}
|
||||
let mut contents = vec![0; size];
|
||||
if args.rdx == 0 || memory.read_bytes(args.rdx, &mut contents).is_err() {
|
||||
return fail(ERROR_NOACCESS);
|
||||
}
|
||||
platform.saves.insert(slot, contents);
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
let load = Arc::clone(state);
|
||||
registry.register(MODULE, "ReadFixtureSave", move |args, cpu, memory| {
|
||||
let platform = load.platform_fixture.lock().expect("fixture platform");
|
||||
let fail = |error| load.fail(cpu.gs_base, error, 0);
|
||||
if !platform.active {
|
||||
return fail(ERROR_INVALID_STATE);
|
||||
}
|
||||
let Some(contents) = platform.saves.get(&(args.rcx as u32)) else {
|
||||
return fail(ERROR_NOT_FOUND);
|
||||
};
|
||||
if args.r8 < contents.len() as u64 {
|
||||
return fail(ERROR_INSUFFICIENT_BUFFER);
|
||||
}
|
||||
if args.rdx == 0 || memory.write_bytes(args.rdx, contents).is_err() {
|
||||
return fail(ERROR_NOACCESS);
|
||||
}
|
||||
Ok(contents.len() as u64)
|
||||
});
|
||||
|
||||
let delete = Arc::clone(state);
|
||||
registry.register(MODULE, "DeleteFixtureSave", move |args, cpu, _| {
|
||||
let mut platform = delete.platform_fixture.lock().expect("fixture platform");
|
||||
if !platform.active {
|
||||
return delete.fail(cpu.gs_base, ERROR_INVALID_STATE, 0);
|
||||
}
|
||||
if platform.saves.remove(&(args.rcx as u32)).is_none() {
|
||||
return delete.fail(cpu.gs_base, ERROR_NOT_FOUND, 0);
|
||||
}
|
||||
Ok(1)
|
||||
});
|
||||
}
|
||||
|
||||
fn register_profiles(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
let create = Arc::clone(state);
|
||||
registry.register(MODULE, "CreateFixtureProfile", move |_, cpu, _| {
|
||||
let mut platform = create.platform_fixture.lock().expect("fixture platform");
|
||||
if !platform.active {
|
||||
return create.fail(cpu.gs_base, ERROR_INVALID_STATE, 0);
|
||||
}
|
||||
if platform.profile_count == MAX_PROFILES {
|
||||
return create.fail(cpu.gs_base, ERROR_NOT_ENOUGH_MEMORY, 0);
|
||||
}
|
||||
platform.profile_count += 1;
|
||||
Ok(platform.profile_count)
|
||||
});
|
||||
|
||||
let select = Arc::clone(state);
|
||||
registry.register(MODULE, "SelectFixtureProfile", move |args, cpu, _| {
|
||||
let mut platform = select.platform_fixture.lock().expect("fixture platform");
|
||||
let fail = |error| select.fail(cpu.gs_base, error, 0);
|
||||
if !platform.active {
|
||||
return fail(ERROR_INVALID_STATE);
|
||||
}
|
||||
let next = args.rcx;
|
||||
if next > platform.profile_count {
|
||||
return fail(ERROR_NOT_FOUND);
|
||||
}
|
||||
let previous = platform.selected_profile;
|
||||
if previous != next {
|
||||
if platform.profile_changes.len() == MAX_NOTIFICATIONS {
|
||||
return fail(ERROR_NOT_ENOUGH_MEMORY);
|
||||
}
|
||||
platform.profile_changes.push_back((previous, next));
|
||||
platform.selected_profile = next;
|
||||
}
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
let selected = Arc::clone(state);
|
||||
registry.register(MODULE, "GetSelectedFixtureProfile", move |_, cpu, _| {
|
||||
let platform = selected.platform_fixture.lock().expect("fixture platform");
|
||||
if !platform.active {
|
||||
return selected.fail(cpu.gs_base, ERROR_INVALID_STATE, 0);
|
||||
}
|
||||
Ok(platform.selected_profile)
|
||||
});
|
||||
|
||||
let poll = Arc::clone(state);
|
||||
registry.register(
|
||||
MODULE,
|
||||
"PollFixtureProfileChange",
|
||||
move |args, cpu, memory| {
|
||||
let mut platform = poll.platform_fixture.lock().expect("fixture platform");
|
||||
if !platform.active {
|
||||
return poll.fail(cpu.gs_base, ERROR_INVALID_STATE, 0);
|
||||
}
|
||||
let Some(&(previous, next)) = platform.profile_changes.front() else {
|
||||
return Ok(0);
|
||||
};
|
||||
let mut record = [0; 16];
|
||||
record[..8].copy_from_slice(&previous.to_le_bytes());
|
||||
record[8..].copy_from_slice(&next.to_le_bytes());
|
||||
if args.rcx == 0 || memory.write_bytes(args.rcx, &record).is_err() {
|
||||
return poll.fail(cpu.gs_base, ERROR_NOACCESS, 0);
|
||||
}
|
||||
platform.profile_changes.pop_front();
|
||||
Ok(1)
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,981 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! 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.
|
||||
|
||||
use super::{
|
||||
ERROR_INVALID_PARAMETER, ERROR_NOT_ENOUGH_MEMORY, ERROR_NOT_SUPPORTED, KERNEL32, ServicesState,
|
||||
};
|
||||
use crate::cpu::ExitReason;
|
||||
use crate::imports::{CallbackStart, CallbackStep, CallbackTask, ImportRegistry, ServiceStatus};
|
||||
use crate::memory::{GuestMemory, MemoryError};
|
||||
use std::collections::BTreeMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
const SYNCH_API: &str = "api-ms-win-core-synch-l1-1-0.dll";
|
||||
const SYNCH_API_2: &str = "api-ms-win-core-synch-l1-2-0.dll";
|
||||
const SLIST_API: &str = "api-ms-win-core-interlocked-l1-1-0.dll";
|
||||
const TLS_API: &str = "api-ms-win-core-processthreads-l1-1-0.dll";
|
||||
const FLS_API: &str = "api-ms-win-core-fibers-l1-1-0.dll";
|
||||
|
||||
const ERROR_GEN_FAILURE: u32 = 31;
|
||||
const ERROR_TIMEOUT: u32 = 1460;
|
||||
|
||||
/// `RTL_CRITICAL_SECTION` on x64 (winnt.h): DebugInfo, LockCount,
|
||||
/// RecursionCount, OwningThread, LockSemaphore, SpinCount.
|
||||
const CS_SIZE: usize = 40;
|
||||
const CS_LOCK_COUNT: u64 = 8;
|
||||
const CS_RECURSION: u64 = 12;
|
||||
const CS_OWNER: u64 = 16;
|
||||
const CS_SPIN: u64 = 32;
|
||||
const CS_SPIN_MASK: u64 = 0x00ff_ffff;
|
||||
const CRITICAL_SECTION_NO_DEBUG_INFO: u32 = 0x0100_0000;
|
||||
const MAX_CRITICAL_SECTIONS: usize = 4096;
|
||||
|
||||
const MAX_SRW_LOCKS: usize = 4096;
|
||||
const CONDITION_VARIABLE_LOCKMODE_SHARED: u32 = 1;
|
||||
|
||||
const INIT_ONCE_CHECK_ONLY: u32 = 1;
|
||||
const INIT_ONCE_ASYNC: u32 = 2;
|
||||
const INIT_ONCE_INIT_FAILED: u32 = 4;
|
||||
const INIT_ONCE_CTX_RESERVED_MASK: u64 = 3;
|
||||
/// Opaque `INIT_ONCE` values. Completion stores the context with this bit set,
|
||||
/// as the context's two reserved low bits allow.
|
||||
const INIT_ONCE_PENDING: u64 = 1;
|
||||
const INIT_ONCE_COMPLETE: u64 = 2;
|
||||
|
||||
/// `SLIST_HEADER` on x64 is 16 bytes: Depth:16, Sequence:48 in the first
|
||||
/// quadword and Reserved:4, NextEntry:60 (address >> 4) in the second.
|
||||
const SLIST_ALIGNMENT: u64 = 16;
|
||||
const SLIST_MAX_DEPTH: u64 = 0xffff;
|
||||
|
||||
/// TLS_MINIMUM_AVAILABLE (64) plus the documented expansion slots.
|
||||
const TLS_MAX_INDEXES: u32 = 1088;
|
||||
const TLS_OUT_OF_INDEXES: u64 = u32::MAX as u64;
|
||||
/// FLS_MAXIMUM_AVAILABLE in the MinGW-w64 winnt.h.
|
||||
const FLS_MAX_INDEXES: u32 = 128;
|
||||
const FLS_OUT_OF_INDEXES: u64 = u32::MAX as u64;
|
||||
|
||||
fn unsupported<T>() -> Result<T, ExitReason> {
|
||||
Err(ExitReason::IllegalInstruction(0xFE))
|
||||
}
|
||||
|
||||
fn fault(error: MemoryError) -> ExitReason {
|
||||
ExitReason::MemoryFault(error)
|
||||
}
|
||||
|
||||
struct CriticalSection {
|
||||
owner: Option<u64>,
|
||||
recursion: u32,
|
||||
spin: u64,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct SrwLock {
|
||||
exclusive: Option<u64>,
|
||||
shared: BTreeMap<u64, u32>,
|
||||
}
|
||||
|
||||
impl SrwLock {
|
||||
fn is_free(&self) -> bool {
|
||||
self.exclusive.is_none() && self.shared.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
struct FlsSlot {
|
||||
callback: u64,
|
||||
}
|
||||
|
||||
struct FlsCleanup {
|
||||
callback: u64,
|
||||
values: std::vec::IntoIter<u64>,
|
||||
}
|
||||
|
||||
impl CallbackTask for FlsCleanup {
|
||||
fn resume(&mut self, _: u64, _: u64, _: &mut GuestMemory) -> Result<CallbackStep, ExitReason> {
|
||||
Ok(match self.values.next() {
|
||||
Some(value) => CallbackStep::Call {
|
||||
entry: self.callback,
|
||||
args: [value, 0, 0, 0],
|
||||
},
|
||||
None => CallbackStep::Return(1),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// `InitOnceExecuteOnce` after its initializer returns. The initializer wrote
|
||||
/// its context to the service's scratch word.
|
||||
struct InitOnceExecution {
|
||||
state: Arc<ServicesState>,
|
||||
once: u64,
|
||||
context: u64,
|
||||
scratch: u64,
|
||||
}
|
||||
|
||||
impl CallbackTask for InitOnceExecution {
|
||||
fn resume(
|
||||
&mut self,
|
||||
result: u64,
|
||||
teb: u64,
|
||||
memory: &mut GuestMemory,
|
||||
) -> Result<CallbackStep, ExitReason> {
|
||||
let succeeded = result as u32 != 0;
|
||||
let produced = memory.read_u64(self.scratch).map_err(fault)?;
|
||||
let mut synch = self
|
||||
.state
|
||||
.synch
|
||||
.lock()
|
||||
.expect("guest synchronization state");
|
||||
synch.init_once_pending.remove(&self.once);
|
||||
if !succeeded || produced & INIT_ONCE_CTX_RESERVED_MASK != 0 {
|
||||
memory.write_u64(self.once, 0).map_err(fault)?;
|
||||
drop(synch);
|
||||
if succeeded {
|
||||
self.state.set_last_error(teb, ERROR_INVALID_PARAMETER);
|
||||
}
|
||||
return Ok(CallbackStep::Return(0));
|
||||
}
|
||||
memory
|
||||
.write_u64(self.once, produced | INIT_ONCE_COMPLETE)
|
||||
.map_err(fault)?;
|
||||
if self.context != 0 {
|
||||
memory.write_u64(self.context, produced).map_err(fault)?;
|
||||
}
|
||||
Ok(CallbackStep::Return(1))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Synch {
|
||||
sections: BTreeMap<u64, CriticalSection>,
|
||||
srw: BTreeMap<u64, SrwLock>,
|
||||
init_once_pending: BTreeMap<u64, u64>,
|
||||
tls_allocated: BTreeMap<u32, ()>,
|
||||
tls_values: BTreeMap<(u64, u32), u64>,
|
||||
fls_slots: BTreeMap<u32, FlsSlot>,
|
||||
fls_values: BTreeMap<(u64, u32), u64>,
|
||||
}
|
||||
|
||||
impl Synch {
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
/// Write the documented observable fields: LockCount is -1 when free and -2
|
||||
/// when held with no waiters, and OwningThread holds the owner's thread ID.
|
||||
fn mirror_section(
|
||||
memory: &mut GuestMemory,
|
||||
address: u64,
|
||||
section: &CriticalSection,
|
||||
thread_id: u32,
|
||||
) -> Result<(), ExitReason> {
|
||||
let (lock_count, owner) = match section.owner {
|
||||
Some(_) => (-2i32, u64::from(thread_id)),
|
||||
None => (-1, 0),
|
||||
};
|
||||
memory
|
||||
.write_u32(address + CS_LOCK_COUNT, lock_count as u32)
|
||||
.map_err(fault)?;
|
||||
memory
|
||||
.write_u32(address + CS_RECURSION, section.recursion)
|
||||
.map_err(fault)?;
|
||||
memory.write_u64(address + CS_OWNER, owner).map_err(fault)
|
||||
}
|
||||
|
||||
fn initialize_section(
|
||||
state: &ServicesState,
|
||||
memory: &mut GuestMemory,
|
||||
address: u64,
|
||||
spin: u64,
|
||||
) -> Result<bool, ExitReason> {
|
||||
if address == 0 {
|
||||
return Err(fault(MemoryError::UnmappedAddress(0)));
|
||||
}
|
||||
address
|
||||
.checked_add(CS_SIZE as u64)
|
||||
.ok_or(fault(MemoryError::Overflow))?;
|
||||
let mut synch = state.synch.lock().expect("guest synchronization state");
|
||||
match synch.sections.get(&address) {
|
||||
Some(existing) if existing.owner.is_some() => return unsupported(),
|
||||
None if synch.sections.len() >= MAX_CRITICAL_SECTIONS => return Ok(false),
|
||||
_ => {}
|
||||
}
|
||||
let mut image = [0u8; CS_SIZE];
|
||||
image[CS_LOCK_COUNT as usize..CS_RECURSION as usize].copy_from_slice(&(-1i32).to_le_bytes());
|
||||
image[CS_SPIN as usize..].copy_from_slice(&(spin & CS_SPIN_MASK).to_le_bytes());
|
||||
memory.write_bytes(address, &image).map_err(fault)?;
|
||||
synch.sections.insert(
|
||||
address,
|
||||
CriticalSection {
|
||||
owner: None,
|
||||
recursion: 0,
|
||||
spin: spin & CS_SPIN_MASK,
|
||||
},
|
||||
);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Acquire for `teb`. Returns false when another guest thread owns it.
|
||||
fn enter_section(
|
||||
state: &ServicesState,
|
||||
memory: &mut GuestMemory,
|
||||
address: u64,
|
||||
teb: u64,
|
||||
) -> Result<bool, ExitReason> {
|
||||
let mut synch = state.synch.lock().expect("guest synchronization state");
|
||||
let section = synch.section(address)?;
|
||||
match section.owner {
|
||||
Some(owner) if owner != teb => return Ok(false),
|
||||
Some(_) if section.recursion >= i32::MAX as u32 => return unsupported(),
|
||||
_ => {}
|
||||
}
|
||||
section.owner = Some(teb);
|
||||
section.recursion += 1;
|
||||
mirror_section(memory, address, section, state.thread_id)?;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn leave_section(
|
||||
state: &ServicesState,
|
||||
memory: &mut GuestMemory,
|
||||
address: u64,
|
||||
teb: u64,
|
||||
) -> Result<(), ExitReason> {
|
||||
let mut synch = state.synch.lock().expect("guest synchronization state");
|
||||
let section = synch.section(address)?;
|
||||
if section.owner != Some(teb) {
|
||||
return unsupported();
|
||||
}
|
||||
section.recursion -= 1;
|
||||
if section.recursion == 0 {
|
||||
section.owner = None;
|
||||
}
|
||||
mirror_section(memory, address, section, state.thread_id)
|
||||
}
|
||||
|
||||
/// Check that a pointer-sized synchronization object is readable and writable.
|
||||
fn check_word(memory: &mut GuestMemory, address: u64) -> Result<u64, ExitReason> {
|
||||
if address == 0 {
|
||||
return Err(fault(MemoryError::UnmappedAddress(0)));
|
||||
}
|
||||
let value = memory.read_u64(address).map_err(fault)?;
|
||||
memory.write_u64(address, value).map_err(fault)?;
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
enum SrwMode {
|
||||
Exclusive,
|
||||
Shared,
|
||||
}
|
||||
|
||||
/// Acquire without blocking. Returns false when the lock is unavailable.
|
||||
fn try_acquire_srw(
|
||||
state: &ServicesState,
|
||||
memory: &mut GuestMemory,
|
||||
address: u64,
|
||||
teb: u64,
|
||||
mode: SrwMode,
|
||||
) -> Result<bool, ExitReason> {
|
||||
check_word(memory, address)?;
|
||||
let mut synch = state.synch.lock().expect("guest synchronization state");
|
||||
if !synch.srw.contains_key(&address) && synch.srw.len() >= MAX_SRW_LOCKS {
|
||||
return unsupported();
|
||||
}
|
||||
let lock = synch.srw.entry(address).or_default();
|
||||
let acquired = match mode {
|
||||
SrwMode::Exclusive if lock.is_free() => {
|
||||
lock.exclusive = Some(teb);
|
||||
true
|
||||
}
|
||||
SrwMode::Shared if lock.exclusive.is_none() => {
|
||||
let count = lock.shared.entry(teb).or_default();
|
||||
if *count == u32::MAX {
|
||||
return unsupported();
|
||||
}
|
||||
*count += 1;
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
if lock.is_free() {
|
||||
synch.srw.remove(&address);
|
||||
}
|
||||
Ok(acquired)
|
||||
}
|
||||
|
||||
fn release_srw(
|
||||
state: &ServicesState,
|
||||
memory: &mut GuestMemory,
|
||||
address: u64,
|
||||
teb: u64,
|
||||
mode: SrwMode,
|
||||
) -> Result<(), ExitReason> {
|
||||
check_word(memory, address)?;
|
||||
let mut synch = state.synch.lock().expect("guest synchronization state");
|
||||
let Some(lock) = synch.srw.get_mut(&address) else {
|
||||
return unsupported();
|
||||
};
|
||||
match mode {
|
||||
SrwMode::Exclusive if lock.exclusive == Some(teb) => lock.exclusive = None,
|
||||
SrwMode::Shared => match lock.shared.get_mut(&teb) {
|
||||
Some(count) if *count > 1 => *count -= 1,
|
||||
Some(_) => {
|
||||
lock.shared.remove(&teb);
|
||||
}
|
||||
None => return unsupported(),
|
||||
},
|
||||
SrwMode::Exclusive => return unsupported(),
|
||||
}
|
||||
if lock.is_free() {
|
||||
synch.srw.remove(&address);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn holds_srw(state: &ServicesState, address: u64, teb: u64, mode: SrwMode) -> bool {
|
||||
let synch = state.synch.lock().expect("guest synchronization state");
|
||||
synch.srw.get(&address).is_some_and(|lock| match mode {
|
||||
SrwMode::Exclusive => lock.exclusive == Some(teb),
|
||||
SrwMode::Shared => lock.shared.contains_key(&teb),
|
||||
})
|
||||
}
|
||||
|
||||
/// Read an aligned `SLIST_HEADER` as (depth, sequence, first entry).
|
||||
fn read_slist(memory: &GuestMemory, header: u64) -> Result<(u64, u64, u64), ExitReason> {
|
||||
if header == 0 || !header.is_multiple_of(SLIST_ALIGNMENT) {
|
||||
return unsupported();
|
||||
}
|
||||
let low = memory.read_u64(header).map_err(fault)?;
|
||||
let high = memory.read_u64(header + 8).map_err(fault)?;
|
||||
Ok((low & 0xffff, low >> 16, (high >> 4) << 4))
|
||||
}
|
||||
|
||||
fn write_slist(
|
||||
memory: &mut GuestMemory,
|
||||
header: u64,
|
||||
depth: u64,
|
||||
sequence: u64,
|
||||
first: u64,
|
||||
) -> Result<(), ExitReason> {
|
||||
let low = (depth & 0xffff) | (sequence << 16);
|
||||
let mut bytes = [0u8; 16];
|
||||
bytes[..8].copy_from_slice(&low.to_le_bytes());
|
||||
bytes[8..].copy_from_slice(&first.to_le_bytes());
|
||||
memory.write_bytes(header, &bytes).map_err(fault)
|
||||
}
|
||||
|
||||
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
register_critical_sections(registry, state);
|
||||
register_srw_and_conditions(registry, state);
|
||||
register_init_once(registry, state);
|
||||
register_slist(registry, state);
|
||||
register_tls(registry, state);
|
||||
}
|
||||
|
||||
fn register_critical_sections(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
let s = Arc::clone(state);
|
||||
registry.register(
|
||||
KERNEL32,
|
||||
"InitializeCriticalSection",
|
||||
move |args, _, mem| {
|
||||
if !initialize_section(&s, mem, args.rcx, 0)? {
|
||||
return unsupported();
|
||||
}
|
||||
Ok(0)
|
||||
},
|
||||
);
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(
|
||||
KERNEL32,
|
||||
"InitializeCriticalSectionAndSpinCount",
|
||||
move |args, cpu, mem| {
|
||||
if !initialize_section(&s, mem, args.rcx, args.rdx & 0xffff_ffff)? {
|
||||
return s.fail(cpu.gs_base, ERROR_NOT_ENOUGH_MEMORY, 0);
|
||||
}
|
||||
Ok(1)
|
||||
},
|
||||
);
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(
|
||||
KERNEL32,
|
||||
"InitializeCriticalSectionEx",
|
||||
move |args, cpu, mem| {
|
||||
let flags = args.r8 as u32;
|
||||
if flags & !CRITICAL_SECTION_NO_DEBUG_INFO != 0 {
|
||||
return s.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
if !initialize_section(&s, mem, args.rcx, args.rdx & 0xffff_ffff)? {
|
||||
return s.fail(cpu.gs_base, ERROR_NOT_ENOUGH_MEMORY, 0);
|
||||
}
|
||||
Ok(1)
|
||||
},
|
||||
);
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "EnterCriticalSection", move |args, cpu, mem| {
|
||||
if !enter_section(&s, mem, args.rcx, cpu.gs_base)? {
|
||||
// Another guest thread owns it; waiting needs the guest scheduler.
|
||||
return unsupported();
|
||||
}
|
||||
Ok(0)
|
||||
});
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(
|
||||
KERNEL32,
|
||||
"TryEnterCriticalSection",
|
||||
move |args, cpu, mem| Ok(u64::from(enter_section(&s, mem, args.rcx, cpu.gs_base)?)),
|
||||
);
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "LeaveCriticalSection", move |args, cpu, mem| {
|
||||
leave_section(&s, mem, args.rcx, cpu.gs_base)?;
|
||||
Ok(0)
|
||||
});
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "DeleteCriticalSection", move |args, _, _| {
|
||||
let mut synch = s.synch.lock().expect("guest synchronization state");
|
||||
if synch.sections.remove(&args.rcx).is_none() {
|
||||
return unsupported();
|
||||
}
|
||||
Ok(0)
|
||||
});
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(
|
||||
KERNEL32,
|
||||
"SetCriticalSectionSpinCount",
|
||||
move |args, _, mem| {
|
||||
let mut synch = s.synch.lock().expect("guest synchronization state");
|
||||
let section = synch.section(args.rcx)?;
|
||||
let previous = section.spin;
|
||||
section.spin = args.rdx & 0xffff_ffff & CS_SPIN_MASK;
|
||||
mem.write_u64(args.rcx + CS_SPIN, section.spin)
|
||||
.map_err(fault)?;
|
||||
Ok(previous)
|
||||
},
|
||||
);
|
||||
|
||||
for symbol in [
|
||||
"InitializeCriticalSection",
|
||||
"InitializeCriticalSectionAndSpinCount",
|
||||
"InitializeCriticalSectionEx",
|
||||
"EnterCriticalSection",
|
||||
"TryEnterCriticalSection",
|
||||
"LeaveCriticalSection",
|
||||
"DeleteCriticalSection",
|
||||
"SetCriticalSectionSpinCount",
|
||||
] {
|
||||
registry.alias(SYNCH_API, KERNEL32, symbol);
|
||||
registry.set_status(KERNEL32, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
}
|
||||
|
||||
fn register_srw_and_conditions(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "InitializeSRWLock", move |args, _, mem| {
|
||||
check_word(mem, args.rcx)?;
|
||||
let synch = s.synch.lock().expect("guest synchronization state");
|
||||
if synch.srw.get(&args.rcx).is_some_and(|lock| !lock.is_free()) {
|
||||
return unsupported();
|
||||
}
|
||||
mem.write_u64(args.rcx, 0).map_err(fault)?;
|
||||
Ok(0)
|
||||
});
|
||||
|
||||
for (acquire, try_acquire, release, mode) in [
|
||||
(
|
||||
"AcquireSRWLockExclusive",
|
||||
"TryAcquireSRWLockExclusive",
|
||||
"ReleaseSRWLockExclusive",
|
||||
SrwMode::Exclusive,
|
||||
),
|
||||
(
|
||||
"AcquireSRWLockShared",
|
||||
"TryAcquireSRWLockShared",
|
||||
"ReleaseSRWLockShared",
|
||||
SrwMode::Shared,
|
||||
),
|
||||
] {
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, acquire, move |args, cpu, mem| {
|
||||
// SRW locks are not recursive, so a held lock would block or deadlock.
|
||||
if !try_acquire_srw(&s, mem, args.rcx, cpu.gs_base, mode)? {
|
||||
return unsupported();
|
||||
}
|
||||
Ok(0)
|
||||
});
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, try_acquire, move |args, cpu, mem| {
|
||||
Ok(u64::from(try_acquire_srw(
|
||||
&s,
|
||||
mem,
|
||||
args.rcx,
|
||||
cpu.gs_base,
|
||||
mode,
|
||||
)?))
|
||||
});
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, release, move |args, cpu, mem| {
|
||||
release_srw(&s, mem, args.rcx, cpu.gs_base, mode)?;
|
||||
Ok(0)
|
||||
});
|
||||
}
|
||||
|
||||
registry.register(KERNEL32, "InitializeConditionVariable", |args, _, mem| {
|
||||
check_word(mem, args.rcx)?;
|
||||
mem.write_u64(args.rcx, 0).map_err(fault)?;
|
||||
Ok(0)
|
||||
});
|
||||
// No guest thread can be waiting, because a sleep never blocks.
|
||||
for symbol in ["WakeConditionVariable", "WakeAllConditionVariable"] {
|
||||
registry.register(KERNEL32, symbol, |args, _, mem| {
|
||||
check_word(mem, args.rcx)?;
|
||||
Ok(0)
|
||||
});
|
||||
}
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(
|
||||
KERNEL32,
|
||||
"SleepConditionVariableCS",
|
||||
move |args, cpu, mem| {
|
||||
check_word(mem, args.rcx)?;
|
||||
let owned = {
|
||||
let synch = s.synch.lock().expect("guest synchronization state");
|
||||
synch
|
||||
.sections
|
||||
.get(&args.rdx)
|
||||
.is_some_and(|section| section.owner == Some(cpu.gs_base))
|
||||
};
|
||||
if !owned {
|
||||
return unsupported();
|
||||
}
|
||||
sleep_result(&s, cpu.gs_base, args.r8 as u32)
|
||||
},
|
||||
);
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(
|
||||
KERNEL32,
|
||||
"SleepConditionVariableSRW",
|
||||
move |args, cpu, mem| {
|
||||
check_word(mem, args.rcx)?;
|
||||
let flags = args.r9 as u32;
|
||||
if flags & !CONDITION_VARIABLE_LOCKMODE_SHARED != 0 {
|
||||
return s.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
let mode = if flags == 0 {
|
||||
SrwMode::Exclusive
|
||||
} else {
|
||||
SrwMode::Shared
|
||||
};
|
||||
if !holds_srw(&s, args.rdx, cpu.gs_base, mode) {
|
||||
return unsupported();
|
||||
}
|
||||
sleep_result(&s, cpu.gs_base, args.r8 as u32)
|
||||
},
|
||||
);
|
||||
|
||||
for symbol in [
|
||||
"InitializeSRWLock",
|
||||
"AcquireSRWLockExclusive",
|
||||
"AcquireSRWLockShared",
|
||||
"TryAcquireSRWLockExclusive",
|
||||
"TryAcquireSRWLockShared",
|
||||
"ReleaseSRWLockExclusive",
|
||||
"ReleaseSRWLockShared",
|
||||
] {
|
||||
registry.alias(SYNCH_API, KERNEL32, symbol);
|
||||
registry.set_status(KERNEL32, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
for symbol in [
|
||||
"InitializeConditionVariable",
|
||||
"WakeConditionVariable",
|
||||
"WakeAllConditionVariable",
|
||||
"SleepConditionVariableCS",
|
||||
"SleepConditionVariableSRW",
|
||||
] {
|
||||
registry.alias(SYNCH_API_2, KERNEL32, symbol);
|
||||
registry.set_status(KERNEL32, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
}
|
||||
|
||||
/// A zero timeout releases and reacquires the lock, which no other guest
|
||||
/// thread can observe, 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)
|
||||
} else {
|
||||
state.fail(teb, ERROR_NOT_SUPPORTED, 0)
|
||||
}
|
||||
}
|
||||
|
||||
fn register_init_once(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "InitOnceInitialize", move |args, _, mem| {
|
||||
check_word(mem, args.rcx)?;
|
||||
let synch = s.synch.lock().expect("guest synchronization state");
|
||||
if synch.init_once_pending.contains_key(&args.rcx) {
|
||||
return unsupported();
|
||||
}
|
||||
mem.write_u64(args.rcx, 0).map_err(fault)?;
|
||||
Ok(0)
|
||||
});
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(
|
||||
KERNEL32,
|
||||
"InitOnceBeginInitialize",
|
||||
move |args, cpu, mem| {
|
||||
let (once, flags, pending, context) = (args.rcx, args.rdx as u32, args.r8, args.r9);
|
||||
let teb = cpu.gs_base;
|
||||
if flags & !(INIT_ONCE_CHECK_ONLY | INIT_ONCE_ASYNC) != 0 || pending == 0 {
|
||||
return s.fail(teb, ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
if flags & INIT_ONCE_ASYNC != 0 {
|
||||
return s.fail(teb, ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
let value = check_word(mem, once)?;
|
||||
let mut synch = s.synch.lock().expect("guest synchronization state");
|
||||
let pending_here = synch.init_once_pending.contains_key(&once);
|
||||
match value & INIT_ONCE_CTX_RESERVED_MASK {
|
||||
INIT_ONCE_COMPLETE => {
|
||||
mem.check_write(pending, 4).map_err(fault)?;
|
||||
if context != 0 {
|
||||
mem.check_write(context, 8).map_err(fault)?;
|
||||
mem.write_u64(context, value & !INIT_ONCE_CTX_RESERVED_MASK)
|
||||
.map_err(fault)?;
|
||||
}
|
||||
mem.write_u32(pending, 0).map_err(fault)?;
|
||||
Ok(1)
|
||||
}
|
||||
_ if flags & INIT_ONCE_CHECK_ONLY != 0
|
||||
&& (value == 0 || (value == INIT_ONCE_PENDING && pending_here)) =>
|
||||
{
|
||||
s.fail(teb, ERROR_GEN_FAILURE, 0)
|
||||
}
|
||||
0 if value == 0 => {
|
||||
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);
|
||||
Ok(1)
|
||||
}
|
||||
// Pending in another thread would block; pending in this thread
|
||||
// or an unrecognized value is a guest error.
|
||||
_ => unsupported(),
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "InitOnceComplete", move |args, cpu, mem| {
|
||||
let (once, flags, context) = (args.rcx, args.rdx as u32, args.r8);
|
||||
let teb = cpu.gs_base;
|
||||
if flags & !(INIT_ONCE_ASYNC | INIT_ONCE_INIT_FAILED) != 0 {
|
||||
return s.fail(teb, ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
if flags & INIT_ONCE_ASYNC != 0 {
|
||||
return s.fail(teb, ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
let failed = flags & INIT_ONCE_INIT_FAILED != 0;
|
||||
if context & INIT_ONCE_CTX_RESERVED_MASK != 0 || (failed && context != 0) {
|
||||
return s.fail(teb, ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
let value = check_word(mem, once)?;
|
||||
let mut synch = s.synch.lock().expect("guest synchronization state");
|
||||
if value != INIT_ONCE_PENDING || synch.init_once_pending.get(&once) != Some(&teb) {
|
||||
return s.fail(teb, ERROR_GEN_FAILURE, 0);
|
||||
}
|
||||
let next = if failed {
|
||||
0
|
||||
} else {
|
||||
context | INIT_ONCE_COMPLETE
|
||||
};
|
||||
mem.write_u64(once, next).map_err(fault)?;
|
||||
synch.init_once_pending.remove(&once);
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register_callback_task(
|
||||
KERNEL32,
|
||||
"InitOnceExecuteOnce",
|
||||
ServiceStatus::Partial,
|
||||
move |args, teb, mem, scratch| {
|
||||
let (once, initializer, parameter, context) = (args.rcx, args.rdx, args.r8, args.r9);
|
||||
let value = check_word(mem, once)?;
|
||||
if value & INIT_ONCE_CTX_RESERVED_MASK == INIT_ONCE_COMPLETE {
|
||||
if context != 0 {
|
||||
mem.write_u64(context, value & !INIT_ONCE_CTX_RESERVED_MASK)
|
||||
.map_err(fault)?;
|
||||
}
|
||||
return Ok(CallbackStart::Return(1));
|
||||
}
|
||||
if value != 0 {
|
||||
// Another thread's pending initialization would block.
|
||||
return unsupported();
|
||||
}
|
||||
let mut synch = s.synch.lock().expect("guest synchronization state");
|
||||
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);
|
||||
Ok(CallbackStart::Call {
|
||||
task: Box::new(InitOnceExecution {
|
||||
state: Arc::clone(&s),
|
||||
once,
|
||||
context,
|
||||
scratch,
|
||||
}),
|
||||
entry: initializer,
|
||||
args: [once, parameter, scratch, 0],
|
||||
})
|
||||
},
|
||||
);
|
||||
|
||||
for symbol in [
|
||||
"InitOnceInitialize",
|
||||
"InitOnceBeginInitialize",
|
||||
"InitOnceComplete",
|
||||
"InitOnceExecuteOnce",
|
||||
] {
|
||||
registry.alias(SYNCH_API_2, KERNEL32, symbol);
|
||||
registry.set_status(KERNEL32, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
}
|
||||
|
||||
fn register_slist(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
registry.register(KERNEL32, "InitializeSListHead", |args, _, mem| {
|
||||
read_slist(mem, args.rcx)?;
|
||||
write_slist(mem, args.rcx, 0, 0, 0)?;
|
||||
Ok(0)
|
||||
});
|
||||
|
||||
registry.register(KERNEL32, "QueryDepthSList", |args, _, mem| {
|
||||
Ok(read_slist(mem, args.rcx)?.0)
|
||||
});
|
||||
|
||||
// Services run one at a time, which makes each list update atomic with
|
||||
// respect to other services.
|
||||
let s = Arc::clone(state);
|
||||
registry.register(
|
||||
KERNEL32,
|
||||
"InterlockedPushEntrySList",
|
||||
move |args, _, mem| {
|
||||
let _serial = s.synch.lock().expect("guest synchronization state");
|
||||
let (header, entry) = (args.rcx, args.rdx);
|
||||
let (depth, sequence, first) = read_slist(mem, header)?;
|
||||
if entry == 0 || !entry.is_multiple_of(SLIST_ALIGNMENT) || depth == SLIST_MAX_DEPTH {
|
||||
return unsupported();
|
||||
}
|
||||
mem.write_u64(entry, first).map_err(fault)?;
|
||||
write_slist(
|
||||
mem,
|
||||
header,
|
||||
depth + 1,
|
||||
(sequence + 1) & 0xffff_ffff_ffff,
|
||||
entry,
|
||||
)?;
|
||||
Ok(first)
|
||||
},
|
||||
);
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "InterlockedPopEntrySList", move |args, _, mem| {
|
||||
let _serial = s.synch.lock().expect("guest synchronization state");
|
||||
let (depth, sequence, first) = read_slist(mem, args.rcx)?;
|
||||
if first == 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
let next = mem.read_u64(first).map_err(fault)?;
|
||||
if !next.is_multiple_of(SLIST_ALIGNMENT) || depth == 0 {
|
||||
return unsupported();
|
||||
}
|
||||
write_slist(mem, args.rcx, depth - 1, sequence, next)?;
|
||||
Ok(first)
|
||||
});
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "InterlockedFlushSList", move |args, _, mem| {
|
||||
let _serial = s.synch.lock().expect("guest synchronization state");
|
||||
let (_, sequence, first) = read_slist(mem, args.rcx)?;
|
||||
write_slist(mem, args.rcx, 0, sequence, 0)?;
|
||||
Ok(first)
|
||||
});
|
||||
|
||||
for symbol in [
|
||||
"InitializeSListHead",
|
||||
"QueryDepthSList",
|
||||
"InterlockedPushEntrySList",
|
||||
"InterlockedPopEntrySList",
|
||||
"InterlockedFlushSList",
|
||||
] {
|
||||
registry.alias(SLIST_API, KERNEL32, symbol);
|
||||
registry.set_status(KERNEL32, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
}
|
||||
|
||||
fn register_tls(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "TlsAlloc", move |_, cpu, _| {
|
||||
let mut synch = s.synch.lock().expect("guest synchronization state");
|
||||
let Some(index) = (0..TLS_MAX_INDEXES).find(|i| !synch.tls_allocated.contains_key(i))
|
||||
else {
|
||||
drop(synch);
|
||||
return s.fail(cpu.gs_base, ERROR_NOT_ENOUGH_MEMORY, TLS_OUT_OF_INDEXES);
|
||||
};
|
||||
synch.tls_allocated.insert(index, ());
|
||||
synch.tls_values.retain(|&(_, slot), _| slot != index);
|
||||
Ok(u64::from(index))
|
||||
});
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "TlsFree", move |args, cpu, _| {
|
||||
let index = args.rcx as u32;
|
||||
let mut synch = s.synch.lock().expect("guest synchronization state");
|
||||
if synch.tls_allocated.remove(&index).is_none() {
|
||||
drop(synch);
|
||||
return s.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
synch.tls_values.retain(|&(_, slot), _| slot != index);
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "TlsGetValue", move |args, cpu, _| {
|
||||
let index = args.rcx as u32;
|
||||
let synch = s.synch.lock().expect("guest synchronization state");
|
||||
if !synch.tls_allocated.contains_key(&index) {
|
||||
drop(synch);
|
||||
return s.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
let value = synch
|
||||
.tls_values
|
||||
.get(&(cpu.gs_base, index))
|
||||
.copied()
|
||||
.unwrap_or(0);
|
||||
drop(synch);
|
||||
// A successful call clears the last error, so zero is distinguishable.
|
||||
s.set_last_error(cpu.gs_base, 0);
|
||||
Ok(value)
|
||||
});
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "TlsSetValue", move |args, cpu, _| {
|
||||
let index = args.rcx as u32;
|
||||
let mut synch = s.synch.lock().expect("guest synchronization state");
|
||||
if !synch.tls_allocated.contains_key(&index) {
|
||||
drop(synch);
|
||||
return s.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
if args.rdx == 0 {
|
||||
synch.tls_values.remove(&(cpu.gs_base, index));
|
||||
} else {
|
||||
synch.tls_values.insert((cpu.gs_base, index), args.rdx);
|
||||
}
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "FlsAlloc", move |args, cpu, _| {
|
||||
let callback = args.rcx;
|
||||
let mut synch = s.synch.lock().expect("guest synchronization state");
|
||||
let Some(index) = (0..FLS_MAX_INDEXES).find(|i| !synch.fls_slots.contains_key(i)) else {
|
||||
drop(synch);
|
||||
return s.fail(cpu.gs_base, ERROR_NOT_ENOUGH_MEMORY, FLS_OUT_OF_INDEXES);
|
||||
};
|
||||
synch.fls_slots.insert(index, FlsSlot { callback });
|
||||
synch.fls_values.retain(|&(_, slot), _| slot != index);
|
||||
Ok(u64::from(index))
|
||||
});
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register_callback_task(
|
||||
KERNEL32,
|
||||
"FlsFree",
|
||||
ServiceStatus::Partial,
|
||||
move |args, teb, _, _| {
|
||||
let index = args.rcx as u32;
|
||||
let mut synch = s.synch.lock().expect("guest synchronization state");
|
||||
let Some(slot) = synch.fls_slots.remove(&index) else {
|
||||
drop(synch);
|
||||
s.fail(teb, ERROR_INVALID_PARAMETER, 0)?;
|
||||
return Ok(CallbackStart::Return(0));
|
||||
};
|
||||
// The slot is released first; its callback then receives each
|
||||
// thread's nonnull value, in TEB order, on the calling thread.
|
||||
let mut values = Vec::new();
|
||||
synch.fls_values.retain(|&(_, slot), value| {
|
||||
if slot == index {
|
||||
values.push(*value);
|
||||
}
|
||||
slot != index
|
||||
});
|
||||
if slot.callback == 0 || values.is_empty() {
|
||||
return Ok(CallbackStart::Return(1));
|
||||
}
|
||||
let first = values.remove(0);
|
||||
Ok(CallbackStart::Call {
|
||||
task: Box::new(FlsCleanup {
|
||||
callback: slot.callback,
|
||||
values: values.into_iter(),
|
||||
}),
|
||||
entry: slot.callback,
|
||||
args: [first, 0, 0, 0],
|
||||
})
|
||||
},
|
||||
);
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "FlsGetValue", move |args, cpu, _| {
|
||||
let index = args.rcx as u32;
|
||||
let synch = s.synch.lock().expect("guest synchronization state");
|
||||
if !synch.fls_slots.contains_key(&index) {
|
||||
drop(synch);
|
||||
return s.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
let value = synch
|
||||
.fls_values
|
||||
.get(&(cpu.gs_base, index))
|
||||
.copied()
|
||||
.unwrap_or(0);
|
||||
drop(synch);
|
||||
s.set_last_error(cpu.gs_base, 0);
|
||||
Ok(value)
|
||||
});
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "FlsSetValue", move |args, cpu, _| {
|
||||
let index = args.rcx as u32;
|
||||
let mut synch = s.synch.lock().expect("guest synchronization state");
|
||||
if !synch.fls_slots.contains_key(&index) {
|
||||
drop(synch);
|
||||
return s.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
if args.rdx == 0 {
|
||||
synch.fls_values.remove(&(cpu.gs_base, index));
|
||||
} else {
|
||||
synch.fls_values.insert((cpu.gs_base, index), args.rdx);
|
||||
}
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
for symbol in ["TlsAlloc", "TlsFree", "TlsGetValue", "TlsSetValue"] {
|
||||
registry.alias(TLS_API, KERNEL32, symbol);
|
||||
registry.set_status(KERNEL32, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
for symbol in ["FlsAlloc", "FlsFree", "FlsGetValue", "FlsSetValue"] {
|
||||
registry.alias(FLS_API, KERNEL32, symbol);
|
||||
registry.set_status(KERNEL32, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,402 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! System information, calendar time and sleeping.
|
||||
//!
|
||||
//! The guest sees a simulated machine described by [`GuestSystemProfile`].
|
||||
//! [`HostCapabilities`] reports what the Mac actually has. The two are kept
|
||||
//! separate so detected host hardware is never presented to the guest as its
|
||||
//! own, and guest-visible values do not change from one Mac to another.
|
||||
|
||||
use super::{ERROR_INVALID_PARAMETER, KERNEL32, ServicesState};
|
||||
use crate::cpu::ExitReason;
|
||||
use crate::imports::{ImportRegistry, ServiceStatus};
|
||||
use crate::memory::{ALLOCATION_GRANULARITY, DYNAMIC_BUDGET, GuestMemory, MemoryError};
|
||||
use std::sync::Arc;
|
||||
|
||||
const SYSINFO_API: &str = "api-ms-win-core-sysinfo-l1-1-0.dll";
|
||||
const SYSINFO_API_2: &str = "api-ms-win-core-sysinfo-l1-2-0.dll";
|
||||
const TIMEZONE_API: &str = "api-ms-win-core-timezone-l1-1-0.dll";
|
||||
const SYNCH_API: &str = "api-ms-win-core-synch-l1-1-0.dll";
|
||||
const SYNCH_API_2: &str = "api-ms-win-core-synch-l1-2-0.dll";
|
||||
const REALTIME_API: &str = "api-ms-win-core-realtime-l1-1-0.dll";
|
||||
|
||||
const PROCESSOR_ARCHITECTURE_AMD64: u16 = 9;
|
||||
const PROCESSOR_AMD_X8664: u32 = 8664;
|
||||
const GUEST_PAGE_SIZE: u32 = 4096;
|
||||
/// The x64 Windows user address range.
|
||||
const MINIMUM_APPLICATION_ADDRESS: u64 = 0x1_0000;
|
||||
const MAXIMUM_APPLICATION_ADDRESS: u64 = 0x7fff_fffe_ffff;
|
||||
const MEMORYSTATUSEX_SIZE: u32 = 64;
|
||||
|
||||
const INFINITE: u32 = u32::MAX;
|
||||
/// Longest sleep the runtime performs. A single guest thread sleeping longer
|
||||
/// is reported rather than silently shortened.
|
||||
const MAX_SLEEP_MILLIS: u32 = 10_000;
|
||||
|
||||
const TICKS_PER_MILLI: u64 = 10_000;
|
||||
const MILLIS_PER_DAY: u64 = 86_400_000;
|
||||
/// Days from 1601-01-01 to 1970-01-01.
|
||||
const DAYS_1601_TO_1970: i64 = 134_774;
|
||||
/// FILETIME values at or above this are rejected by FileTimeToSystemTime.
|
||||
const MAX_FILETIME: u64 = 0x8000_0000_0000_0000;
|
||||
|
||||
/// What the guest is told about the machine it runs on.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GuestSystemProfile {
|
||||
/// Reported processors. One, because guest code runs on one thread at a time.
|
||||
pub processors: u32,
|
||||
}
|
||||
|
||||
impl Default for GuestSystemProfile {
|
||||
fn default() -> Self {
|
||||
Self { processors: 1 }
|
||||
}
|
||||
}
|
||||
|
||||
/// Hardware detected on the host Mac. Never reported to the guest.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct HostCapabilities {
|
||||
pub logical_processors: Option<u64>,
|
||||
pub physical_memory: Option<u64>,
|
||||
pub page_size: Option<u64>,
|
||||
}
|
||||
|
||||
impl HostCapabilities {
|
||||
pub fn detect() -> Self {
|
||||
let logical_processors = std::thread::available_parallelism()
|
||||
.ok()
|
||||
.map(|count| count.get() as u64);
|
||||
// SAFETY: sysconf takes no pointers.
|
||||
let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
|
||||
Self {
|
||||
logical_processors,
|
||||
physical_memory: physical_memory(),
|
||||
page_size: u64::try_from(page_size).ok().filter(|&size| size > 0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn physical_memory() -> Option<u64> {
|
||||
let mut bytes = 0u64;
|
||||
let mut size = std::mem::size_of::<u64>();
|
||||
// SAFETY: the name is NUL-terminated and the output buffer is a u64 whose
|
||||
// size is passed in `size`; no new value is written.
|
||||
let status = unsafe {
|
||||
libc::sysctlbyname(
|
||||
c"hw.memsize".as_ptr(),
|
||||
(&raw mut bytes).cast(),
|
||||
&raw mut size,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
)
|
||||
};
|
||||
(status == 0 && size == std::mem::size_of::<u64>()).then_some(bytes)
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
fn physical_memory() -> Option<u64> {
|
||||
None
|
||||
}
|
||||
|
||||
/// A Windows `SYSTEMTIME`, in field order.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct SystemTime {
|
||||
year: u16,
|
||||
month: u16,
|
||||
day_of_week: u16,
|
||||
day: u16,
|
||||
hour: u16,
|
||||
minute: u16,
|
||||
second: u16,
|
||||
milliseconds: u16,
|
||||
}
|
||||
|
||||
impl SystemTime {
|
||||
fn to_bytes(self) -> [u8; 16] {
|
||||
let fields = [
|
||||
self.year,
|
||||
self.month,
|
||||
self.day_of_week,
|
||||
self.day,
|
||||
self.hour,
|
||||
self.minute,
|
||||
self.second,
|
||||
self.milliseconds,
|
||||
];
|
||||
let mut bytes = [0; 16];
|
||||
for (chunk, field) in bytes.as_chunks_mut::<2>().0.iter_mut().zip(fields) {
|
||||
*chunk = field.to_le_bytes();
|
||||
}
|
||||
bytes
|
||||
}
|
||||
|
||||
fn from_bytes(bytes: [u8; 16]) -> Self {
|
||||
let field = |index: usize| u16::from_le_bytes([bytes[2 * index], bytes[2 * index + 1]]);
|
||||
Self {
|
||||
year: field(0),
|
||||
month: field(1),
|
||||
day_of_week: field(2),
|
||||
day: field(3),
|
||||
hour: field(4),
|
||||
minute: field(5),
|
||||
second: field(6),
|
||||
milliseconds: field(7),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Proleptic Gregorian date for a day count relative to 1970-01-01.
|
||||
fn civil_from_days(days: i64) -> (i64, u16, u16) {
|
||||
let shifted = days + 719_468;
|
||||
let era = shifted.div_euclid(146_097);
|
||||
let day_of_era = shifted.rem_euclid(146_097);
|
||||
let year_of_era =
|
||||
(day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
|
||||
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
|
||||
let month_index = (5 * day_of_year + 2) / 153;
|
||||
let day = day_of_year - (153 * month_index + 2) / 5 + 1;
|
||||
let month = if month_index < 10 {
|
||||
month_index + 3
|
||||
} else {
|
||||
month_index - 9
|
||||
};
|
||||
let year = year_of_era + era * 400 + i64::from(month <= 2);
|
||||
(year, month as u16, day as u16)
|
||||
}
|
||||
|
||||
fn days_from_civil(year: i64, month: u16, day: u16) -> i64 {
|
||||
let year = year - i64::from(month <= 2);
|
||||
let era = year.div_euclid(400);
|
||||
let year_of_era = year - era * 400;
|
||||
let month_index = (i64::from(month) + 9) % 12;
|
||||
let day_of_year = (153 * month_index + 2) / 5 + i64::from(day) - 1;
|
||||
let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
|
||||
era * 146_097 + day_of_era - 719_468
|
||||
}
|
||||
|
||||
fn is_leap(year: u16) -> bool {
|
||||
year.is_multiple_of(4) && (!year.is_multiple_of(100) || year.is_multiple_of(400))
|
||||
}
|
||||
|
||||
fn days_in_month(year: u16, month: u16) -> u16 {
|
||||
match month {
|
||||
2 if is_leap(year) => 29,
|
||||
2 => 28,
|
||||
4 | 6 | 9 | 11 => 30,
|
||||
_ => 31,
|
||||
}
|
||||
}
|
||||
|
||||
fn filetime_to_system_time(filetime: u64) -> Option<SystemTime> {
|
||||
if filetime >= MAX_FILETIME {
|
||||
return None;
|
||||
}
|
||||
let millis = filetime / TICKS_PER_MILLI;
|
||||
let days = (millis / MILLIS_PER_DAY) as i64;
|
||||
let of_day = millis % MILLIS_PER_DAY;
|
||||
let (year, month, day) = civil_from_days(days - DAYS_1601_TO_1970);
|
||||
Some(SystemTime {
|
||||
year: year as u16,
|
||||
month,
|
||||
// 1601-01-01 was a Monday, and Sunday is zero.
|
||||
day_of_week: ((days + 1) % 7) as u16,
|
||||
day,
|
||||
hour: (of_day / 3_600_000) as u16,
|
||||
minute: (of_day / 60_000 % 60) as u16,
|
||||
second: (of_day / 1000 % 60) as u16,
|
||||
milliseconds: (of_day % 1000) as u16,
|
||||
})
|
||||
}
|
||||
|
||||
/// The day of week is ignored, as documented for SystemTimeToFileTime.
|
||||
fn system_time_to_filetime(time: SystemTime) -> Option<u64> {
|
||||
let valid = (1601..=30827).contains(&time.year)
|
||||
&& (1..=12).contains(&time.month)
|
||||
&& (1..=days_in_month(time.year, time.month)).contains(&time.day)
|
||||
&& time.hour < 24
|
||||
&& time.minute < 60
|
||||
&& time.second < 60
|
||||
&& time.milliseconds < 1000;
|
||||
if !valid {
|
||||
return None;
|
||||
}
|
||||
let days = days_from_civil(i64::from(time.year), time.month, time.day) + DAYS_1601_TO_1970;
|
||||
let millis = days as u64 * MILLIS_PER_DAY
|
||||
+ u64::from(time.hour) * 3_600_000
|
||||
+ u64::from(time.minute) * 60_000
|
||||
+ u64::from(time.second) * 1000
|
||||
+ u64::from(time.milliseconds);
|
||||
Some(millis * TICKS_PER_MILLI)
|
||||
}
|
||||
|
||||
fn fault(error: MemoryError) -> ExitReason {
|
||||
ExitReason::MemoryFault(error)
|
||||
}
|
||||
|
||||
fn write_system_info(
|
||||
state: &ServicesState,
|
||||
memory: &mut GuestMemory,
|
||||
address: u64,
|
||||
) -> Result<(), ExitReason> {
|
||||
let processors = state.guest_profile.processors.clamp(1, 64);
|
||||
let mask = u64::MAX >> (64 - processors);
|
||||
let mut info = [0u8; 48];
|
||||
info[0..2].copy_from_slice(&PROCESSOR_ARCHITECTURE_AMD64.to_le_bytes());
|
||||
info[4..8].copy_from_slice(&GUEST_PAGE_SIZE.to_le_bytes());
|
||||
info[8..16].copy_from_slice(&MINIMUM_APPLICATION_ADDRESS.to_le_bytes());
|
||||
info[16..24].copy_from_slice(&MAXIMUM_APPLICATION_ADDRESS.to_le_bytes());
|
||||
info[24..32].copy_from_slice(&mask.to_le_bytes());
|
||||
info[32..36].copy_from_slice(&processors.to_le_bytes());
|
||||
info[36..40].copy_from_slice(&PROCESSOR_AMD_X8664.to_le_bytes());
|
||||
info[40..44].copy_from_slice(&(ALLOCATION_GRANULARITY as u32).to_le_bytes());
|
||||
// wProcessorLevel and wProcessorRevision stay zero: no CPU model is simulated.
|
||||
memory.write_bytes(address, &info).map_err(fault)
|
||||
}
|
||||
|
||||
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
for symbol in ["GetSystemInfo", "GetNativeSystemInfo"] {
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, symbol, move |args, _, mem| {
|
||||
write_system_info(&s, mem, args.rcx)?;
|
||||
Ok(0)
|
||||
});
|
||||
}
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "GlobalMemoryStatusEx", move |args, cpu, mem| {
|
||||
let address = args.rcx;
|
||||
if mem.read_u32(address).map_err(fault)? != MEMORYSTATUSEX_SIZE {
|
||||
return s.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
let (mapped, virtual_bytes, heap_bytes) = mem.usage();
|
||||
// Guest physical memory is the virtual-allocation and heap budgets;
|
||||
// there is no paging file.
|
||||
let total = 2 * DYNAMIC_BUDGET;
|
||||
let used = (virtual_bytes + heap_bytes).min(total);
|
||||
let total_virtual = MAXIMUM_APPLICATION_ADDRESS - MINIMUM_APPLICATION_ADDRESS + 1;
|
||||
let mut status = [0u8; 64];
|
||||
status[0..4].copy_from_slice(&MEMORYSTATUSEX_SIZE.to_le_bytes());
|
||||
status[4..8].copy_from_slice(&((used * 100 / total) as u32).to_le_bytes());
|
||||
for (offset, value) in [
|
||||
(8, total),
|
||||
(16, total - used),
|
||||
(24, total),
|
||||
(32, total - used),
|
||||
(40, total_virtual),
|
||||
(48, total_virtual.saturating_sub(mapped)),
|
||||
] {
|
||||
status[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
mem.write_bytes(address, &status).map_err(fault)?;
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
// The guest time zone is UTC, so local time equals system time.
|
||||
for symbol in ["GetSystemTime", "GetLocalTime"] {
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, symbol, move |args, _, mem| {
|
||||
let time = filetime_to_system_time(s.clock.now_filetime())
|
||||
.ok_or(ExitReason::IllegalInstruction(0xFE))?;
|
||||
mem.write_bytes(args.rcx, &time.to_bytes()).map_err(fault)?;
|
||||
Ok(0)
|
||||
});
|
||||
}
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(
|
||||
KERNEL32,
|
||||
"GetSystemTimePreciseAsFileTime",
|
||||
move |args, _, mem| {
|
||||
mem.write_u64(args.rcx, s.clock.now_filetime())
|
||||
.map_err(fault)?;
|
||||
Ok(0)
|
||||
},
|
||||
);
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "FileTimeToSystemTime", move |args, cpu, mem| {
|
||||
let filetime = mem.read_u64(args.rcx).map_err(fault)?;
|
||||
let Some(time) = filetime_to_system_time(filetime) else {
|
||||
return s.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0);
|
||||
};
|
||||
mem.write_bytes(args.rdx, &time.to_bytes()).map_err(fault)?;
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, "SystemTimeToFileTime", move |args, cpu, mem| {
|
||||
let mut bytes = [0; 16];
|
||||
mem.read_bytes(args.rcx, &mut bytes).map_err(fault)?;
|
||||
let Some(filetime) = system_time_to_filetime(SystemTime::from_bytes(bytes)) else {
|
||||
return s.fail(cpu.gs_base, ERROR_INVALID_PARAMETER, 0);
|
||||
};
|
||||
mem.write_u64(args.rdx, filetime).map_err(fault)?;
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
let s = Arc::clone(state);
|
||||
registry.register(
|
||||
KERNEL32,
|
||||
"QueryUnbiasedInterruptTime",
|
||||
move |args, _, mem| {
|
||||
let elapsed = s.clock.performance_count().saturating_sub(s.clock_origin);
|
||||
mem.write_u64(args.rcx, elapsed).map_err(fault)?;
|
||||
Ok(1)
|
||||
},
|
||||
);
|
||||
|
||||
// No APCs can be queued, so an alertable SleepEx always runs to completion
|
||||
// and returns zero rather than WAIT_IO_COMPLETION.
|
||||
for symbol in ["Sleep", "SleepEx"] {
|
||||
let s = Arc::clone(state);
|
||||
registry.register(KERNEL32, symbol, move |args, _, _| {
|
||||
let millis = args.rcx as u32;
|
||||
if millis == INFINITE || millis > MAX_SLEEP_MILLIS {
|
||||
return Err(ExitReason::IllegalInstruction(0xFE));
|
||||
}
|
||||
s.clock.sleep(u64::from(millis) * TICKS_PER_MILLI);
|
||||
Ok(0)
|
||||
});
|
||||
}
|
||||
|
||||
for (symbol, api_set) in [
|
||||
("GetSystemInfo", SYSINFO_API),
|
||||
("GetNativeSystemInfo", SYSINFO_API_2),
|
||||
("GlobalMemoryStatusEx", SYSINFO_API),
|
||||
("GetSystemTime", SYSINFO_API),
|
||||
("GetLocalTime", SYSINFO_API),
|
||||
("GetSystemTimePreciseAsFileTime", SYSINFO_API_2),
|
||||
("FileTimeToSystemTime", TIMEZONE_API),
|
||||
("SystemTimeToFileTime", TIMEZONE_API),
|
||||
("QueryUnbiasedInterruptTime", REALTIME_API),
|
||||
("Sleep", SYNCH_API_2),
|
||||
("SleepEx", SYNCH_API),
|
||||
] {
|
||||
registry.alias(api_set, KERNEL32, symbol);
|
||||
registry.set_status(KERNEL32, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn calendar_conversion_round_trips_across_leap_and_century_boundaries() {
|
||||
for days in (-DAYS_1601_TO_1970..2_000_000).step_by(997) {
|
||||
let (year, month, day) = civil_from_days(days);
|
||||
assert_eq!(days_from_civil(year, month, day), days);
|
||||
}
|
||||
assert!(is_leap(2000) && is_leap(2024) && !is_leap(1900) && !is_leap(2100));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_capabilities_are_detected_on_this_mac() {
|
||||
let host = HostCapabilities::detect();
|
||||
assert!(host.logical_processors.unwrap() >= 1);
|
||||
assert!(host.page_size.unwrap() >= 4096);
|
||||
#[cfg(target_os = "macos")]
|
||||
assert!(host.physical_memory.unwrap() >= 1 << 30);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Original guest fixture services for exercising manual task dispatch.
|
||||
|
||||
use super::{ERROR_INVALID_PARAMETER, ERROR_NOACCESS, ERROR_NOT_ENOUGH_MEMORY, ServicesState};
|
||||
use crate::imports::ImportRegistry;
|
||||
use crate::tasks::{TaskId, TaskQueue, TaskResult};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
const MODULE: &str = "xenora_fixture.dll";
|
||||
const COMPLETION_SIZE: usize = 24;
|
||||
|
||||
type Delivered = Option<(TaskId, TaskResult<u64, u32>)>;
|
||||
|
||||
pub(super) struct TaskFixture {
|
||||
queue: TaskQueue<u64, u32>,
|
||||
delivered: Arc<Mutex<Delivered>>,
|
||||
}
|
||||
|
||||
impl Default for TaskFixture {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
queue: TaskQueue::new(16),
|
||||
delivered: Arc::default(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
let submit = Arc::clone(state);
|
||||
registry.register(MODULE, "SubmitFixtureTask", move |args, cpu, _| {
|
||||
let input = args.rcx;
|
||||
let now = Duration::from_millis(submit.uptime_millis());
|
||||
let deadline = (args.rdx != 0).then(|| now + Duration::from_millis(args.rdx));
|
||||
let mut tasks = submit.task_fixture.lock().expect("fixture task queue");
|
||||
let delivered = Arc::clone(&tasks.delivered);
|
||||
match tasks.queue.submit_cancellable(
|
||||
deadline,
|
||||
move |token| {
|
||||
if token.is_cancelled() {
|
||||
return Err(995);
|
||||
}
|
||||
input.checked_mul(input).ok_or(ERROR_INVALID_PARAMETER)
|
||||
},
|
||||
move |id, result| {
|
||||
*delivered.lock().expect("fixture task completion") = Some((id, result));
|
||||
},
|
||||
) {
|
||||
Ok(id) => Ok(id.raw()),
|
||||
Err(_) => submit.fail(cpu.gs_base, ERROR_NOT_ENOUGH_MEMORY, 0),
|
||||
}
|
||||
});
|
||||
|
||||
let cancel = Arc::clone(state);
|
||||
registry.register(MODULE, "CancelFixtureTask", move |args, _, _| {
|
||||
let mut tasks = cancel.task_fixture.lock().expect("fixture task queue");
|
||||
Ok(u64::from(tasks.queue.cancel(TaskId::from_raw(args.rcx))))
|
||||
});
|
||||
|
||||
let work = Arc::clone(state);
|
||||
registry.register(MODULE, "DispatchFixtureWork", move |_, _, _| {
|
||||
let now = Duration::from_millis(work.uptime_millis());
|
||||
let mut tasks = work.task_fixture.lock().expect("fixture task queue");
|
||||
Ok(u64::from(tasks.queue.dispatch_work(now)))
|
||||
});
|
||||
|
||||
let background = Arc::clone(state);
|
||||
registry.register(MODULE, "DispatchFixtureBackground", move |_, cpu, _| {
|
||||
let now = Duration::from_millis(background.uptime_millis());
|
||||
let mut tasks = background.task_fixture.lock().expect("fixture task queue");
|
||||
match tasks.queue.dispatch_background(now) {
|
||||
Ok(started) => Ok(u64::from(started)),
|
||||
Err(_) => background.fail(cpu.gs_base, ERROR_NOT_ENOUGH_MEMORY, 0),
|
||||
}
|
||||
});
|
||||
|
||||
let completion = Arc::clone(state);
|
||||
registry.register(
|
||||
MODULE,
|
||||
"DispatchFixtureCompletion",
|
||||
move |args, cpu, memory| {
|
||||
if args.rcx == 0 || memory.check_write(args.rcx, COMPLETION_SIZE).is_err() {
|
||||
return completion.fail(cpu.gs_base, ERROR_NOACCESS, 0);
|
||||
}
|
||||
let mut tasks = completion.task_fixture.lock().expect("fixture task queue");
|
||||
tasks
|
||||
.queue
|
||||
.advance_time(Duration::from_millis(completion.uptime_millis()));
|
||||
if !tasks.queue.dispatch_completion() {
|
||||
return Ok(0);
|
||||
}
|
||||
let (id, result) = tasks
|
||||
.delivered
|
||||
.lock()
|
||||
.expect("fixture task completion")
|
||||
.take()
|
||||
.expect("dispatch delivers a completion");
|
||||
let (status, value): (u32, u64) = match result {
|
||||
TaskResult::Finished(Ok(value)) => (0, value),
|
||||
TaskResult::Finished(Err(error)) => (error, 0),
|
||||
TaskResult::Cancelled => (995, 0),
|
||||
TaskResult::TimedOut => (1460, 0),
|
||||
TaskResult::WorkerPanicked => (31, 0),
|
||||
};
|
||||
let mut record = [0; COMPLETION_SIZE];
|
||||
record[..8].copy_from_slice(&id.raw().to_le_bytes());
|
||||
record[8..12].copy_from_slice(&status.to_le_bytes());
|
||||
record[16..24].copy_from_slice(&value.to_le_bytes());
|
||||
memory
|
||||
.write_bytes(args.rcx, &record)
|
||||
.map_err(crate::cpu::ExitReason::MemoryFault)?;
|
||||
Ok(1)
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,688 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Process-local Winsock UDP loopback for the synthetic guest.
|
||||
|
||||
use super::{ERROR_INVALID_PARAMETER, ServicesState};
|
||||
use crate::cpu::ExitReason;
|
||||
use crate::imports::{ImportRegistry, ServiceStatus};
|
||||
use crate::memory::GuestMemory;
|
||||
use std::collections::{BTreeMap, VecDeque};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
const MODULE: &str = "ws2_32.dll";
|
||||
const VERSION: u16 = 0x0202;
|
||||
const WSADATA_SIZE: usize = 408;
|
||||
const MAX_DATAGRAM: usize = 65_507;
|
||||
const MAX_PENDING_DATAGRAMS: usize = 16;
|
||||
const MAX_SOCKETS: usize = 64;
|
||||
const SOCKET_ERROR: u64 = u32::MAX as u64;
|
||||
const INVALID_SOCKET: u64 = u64::MAX;
|
||||
const WSAEACCES: u32 = 10013;
|
||||
const WSAEINVAL: u32 = 10022;
|
||||
const WSAEWOULDBLOCK: u32 = 10035;
|
||||
const WSAEMSGSIZE: u32 = 10040;
|
||||
const WSAEADDRINUSE: u32 = 10048;
|
||||
const WSAENOBUFS: u32 = 10055;
|
||||
const WSAENOTCONN: u32 = 10057;
|
||||
const WSAEFAULT: u32 = 10014;
|
||||
const WSAEMFILE: u32 = 10024;
|
||||
const WSAENOTSOCK: u32 = 10038;
|
||||
const WSAEPROTONOSUPPORT: u32 = 10043;
|
||||
const WSAESOCKTNOSUPPORT: u32 = 10044;
|
||||
const WSAEOPNOTSUPP: u32 = 10045;
|
||||
const WSAENOPROTOOPT: u32 = 10042;
|
||||
const WSAEAFNOSUPPORT: u32 = 10047;
|
||||
const WSASYSNOTREADY: u32 = 10091;
|
||||
const WSAVERNOTSUPPORTED: u32 = 10092;
|
||||
const WSANOTINITIALISED: u32 = 10093;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Winsock {
|
||||
refs: u32,
|
||||
serial: u32,
|
||||
sockets: BTreeMap<u64, Socket>,
|
||||
#[cfg(test)]
|
||||
poll_waiters: usize,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Socket {
|
||||
port: Option<u16>,
|
||||
peer: Option<u16>,
|
||||
pending: VecDeque<(u16, Vec<u8>)>,
|
||||
}
|
||||
|
||||
impl Winsock {
|
||||
fn socket(&self, handle: u64) -> Result<&Socket, u32> {
|
||||
if self.refs == 0 {
|
||||
return Err(WSANOTINITIALISED);
|
||||
}
|
||||
self.sockets.get(&handle).ok_or(WSAENOTSOCK)
|
||||
}
|
||||
|
||||
fn port(&self, requested: u16) -> Result<u16, u32> {
|
||||
let available = |port| {
|
||||
self.sockets
|
||||
.values()
|
||||
.all(|socket| socket.port != Some(port))
|
||||
};
|
||||
if requested != 0 {
|
||||
return available(requested)
|
||||
.then_some(requested)
|
||||
.ok_or(WSAEADDRINUSE);
|
||||
}
|
||||
(49152..=65535)
|
||||
.find(|&port| available(port))
|
||||
.ok_or(WSAEADDRINUSE)
|
||||
}
|
||||
}
|
||||
|
||||
fn loopback_port(memory: &GuestMemory, address: u64, size: u32) -> Result<u16, u32> {
|
||||
let mut data = [0; 16];
|
||||
if (size as i32) < 16 || address == 0 || memory.read_bytes(address, &mut data).is_err() {
|
||||
return Err(WSAEFAULT);
|
||||
}
|
||||
if u16::from_le_bytes([data[0], data[1]]) != 2 {
|
||||
return Err(WSAEAFNOSUPPORT);
|
||||
}
|
||||
if data[4..8] != [127, 0, 0, 1] {
|
||||
return Err(WSAEACCES);
|
||||
}
|
||||
Ok(u16::from_be_bytes([data[2], data[3]]))
|
||||
}
|
||||
|
||||
fn socket_result(
|
||||
state: &ServicesState,
|
||||
teb: u64,
|
||||
result: Result<u64, u32>,
|
||||
) -> Result<u64, ExitReason> {
|
||||
match result {
|
||||
Ok(value) => Ok(value),
|
||||
Err(error) => state.fail(teb, error, SOCKET_ERROR),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
let startup = Arc::clone(state);
|
||||
registry.register(MODULE, "WSAStartup", move |args, _, memory| {
|
||||
let requested = args.rcx as u16;
|
||||
let negotiated = match requested.to_le_bytes() {
|
||||
[2, minor] => u16::from_le_bytes([2, minor.min(2)]),
|
||||
_ => return Ok(u64::from(WSAVERNOTSUPPORTED)),
|
||||
};
|
||||
let mut net = startup.winsock.lock().expect("guest Winsock state");
|
||||
let Some(next) = net.refs.checked_add(1) else {
|
||||
return Ok(u64::from(WSASYSNOTREADY));
|
||||
};
|
||||
let mut data = [0; WSADATA_SIZE];
|
||||
data[..2].copy_from_slice(&negotiated.to_le_bytes());
|
||||
data[2..4].copy_from_slice(&VERSION.to_le_bytes());
|
||||
let description = b"Xenora synthetic Winsock";
|
||||
data[16..16 + description.len()].copy_from_slice(description);
|
||||
if args.rdx == 0 || memory.write_bytes(args.rdx, &data).is_err() {
|
||||
return Ok(u64::from(WSAEFAULT));
|
||||
}
|
||||
net.refs = next;
|
||||
Ok(0)
|
||||
});
|
||||
|
||||
let cleanup = Arc::clone(state);
|
||||
registry.register(MODULE, "WSACleanup", move |_, cpu, _| {
|
||||
let mut net = cleanup.winsock.lock().expect("guest Winsock state");
|
||||
if net.refs == 0 {
|
||||
return cleanup.fail(cpu.gs_base, WSANOTINITIALISED, SOCKET_ERROR);
|
||||
}
|
||||
net.refs -= 1;
|
||||
if net.refs == 0 {
|
||||
net.sockets.clear();
|
||||
cleanup.winsock_changed.notify_all();
|
||||
}
|
||||
Ok(0)
|
||||
});
|
||||
|
||||
let open = Arc::clone(state);
|
||||
registry.register(MODULE, "socket", move |args, cpu, _| {
|
||||
let mut net = open.winsock.lock().expect("guest Winsock state");
|
||||
let fail = |error| open.fail(cpu.gs_base, error, INVALID_SOCKET);
|
||||
if net.refs == 0 {
|
||||
return fail(WSANOTINITIALISED);
|
||||
}
|
||||
if args.rcx as u32 != 2 {
|
||||
return fail(WSAEAFNOSUPPORT);
|
||||
}
|
||||
if args.rdx as u32 != 2 {
|
||||
return fail(WSAESOCKTNOSUPPORT);
|
||||
}
|
||||
if !matches!(args.r8 as u32, 0 | 17) {
|
||||
return fail(WSAEPROTONOSUPPORT);
|
||||
}
|
||||
if net.sockets.len() >= MAX_SOCKETS {
|
||||
return fail(WSAEMFILE);
|
||||
}
|
||||
let Some(next) = net.serial.checked_add(1) else {
|
||||
return fail(WSAEMFILE);
|
||||
};
|
||||
net.serial = next;
|
||||
let socket = 0x5300_0000_0000_0000 | u64::from(next);
|
||||
net.sockets.insert(socket, Socket::default());
|
||||
Ok(socket)
|
||||
});
|
||||
|
||||
let close = Arc::clone(state);
|
||||
registry.register(MODULE, "closesocket", move |args, cpu, _| {
|
||||
let mut net = close.winsock.lock().expect("guest Winsock state");
|
||||
if net.refs == 0 {
|
||||
return close.fail(cpu.gs_base, WSANOTINITIALISED, SOCKET_ERROR);
|
||||
}
|
||||
if net.sockets.remove(&args.rcx).is_none() {
|
||||
return close.fail(cpu.gs_base, WSAENOTSOCK, SOCKET_ERROR);
|
||||
}
|
||||
close.winsock_changed.notify_all();
|
||||
Ok(0)
|
||||
});
|
||||
|
||||
register_address_conversion(registry, state);
|
||||
register_loopback(registry, state);
|
||||
register_socket_names(registry, state);
|
||||
register_socket_options(registry, state);
|
||||
register_poll(registry, state);
|
||||
|
||||
let get = Arc::clone(state);
|
||||
registry.register(MODULE, "WSAGetLastError", move |_, cpu, _| {
|
||||
Ok(u64::from(get.last_error(cpu.gs_base)))
|
||||
});
|
||||
let set = Arc::clone(state);
|
||||
registry.register(MODULE, "WSASetLastError", move |args, cpu, _| {
|
||||
set.set_last_error(cpu.gs_base, args.rcx as u32);
|
||||
Ok(0)
|
||||
});
|
||||
for symbol in ["WSAStartup", "WSACleanup", "socket", "closesocket"] {
|
||||
registry.set_status(MODULE, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
}
|
||||
|
||||
fn register_address_conversion(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
for symbol in ["htons", "ntohs"] {
|
||||
registry.register(MODULE, symbol, |args, _, _| {
|
||||
Ok(u64::from((args.rcx as u16).swap_bytes()))
|
||||
});
|
||||
}
|
||||
for symbol in ["htonl", "ntohl"] {
|
||||
registry.register(MODULE, symbol, |args, _, _| {
|
||||
Ok(u64::from((args.rcx as u32).swap_bytes()))
|
||||
});
|
||||
}
|
||||
let format_state = Arc::clone(state);
|
||||
registry.register_with_status(
|
||||
MODULE,
|
||||
"inet_ntop",
|
||||
ServiceStatus::Partial,
|
||||
move |args, cpu, memory| {
|
||||
let fail = |error| format_state.fail(cpu.gs_base, error, 0);
|
||||
if args.rcx as u32 != 2 {
|
||||
return fail(WSAEAFNOSUPPORT);
|
||||
}
|
||||
if args.r8 == 0 || args.r9 == 0 {
|
||||
return fail(ERROR_INVALID_PARAMETER);
|
||||
}
|
||||
let mut address = [0; 4];
|
||||
if args.rdx == 0 || memory.read_bytes(args.rdx, &mut address).is_err() {
|
||||
return fail(WSAEFAULT);
|
||||
}
|
||||
let mut text = std::net::Ipv4Addr::from(address).to_string().into_bytes();
|
||||
text.push(0);
|
||||
if (text.len() as u64) > args.r9 {
|
||||
return fail(ERROR_INVALID_PARAMETER);
|
||||
}
|
||||
if memory.write_bytes(args.r8, &text).is_err() {
|
||||
return fail(WSAEFAULT);
|
||||
}
|
||||
Ok(args.r8)
|
||||
},
|
||||
);
|
||||
let state = Arc::clone(state);
|
||||
registry.register_with_status(
|
||||
MODULE,
|
||||
"inet_pton",
|
||||
ServiceStatus::Partial,
|
||||
move |args, cpu, memory| {
|
||||
let fail = |error| state.fail(cpu.gs_base, error, SOCKET_ERROR);
|
||||
if args.rcx as u32 != 2 {
|
||||
return fail(WSAEAFNOSUPPORT);
|
||||
}
|
||||
if args.rdx == 0 || args.r8 == 0 {
|
||||
return fail(WSAEFAULT);
|
||||
}
|
||||
// The longest dotted decimal IPv4 spelling is 15 bytes plus NUL.
|
||||
let mut text = [0; 15];
|
||||
for len in 0..=text.len() {
|
||||
let Some(address) = args.rdx.checked_add(len as u64) else {
|
||||
return fail(WSAEFAULT);
|
||||
};
|
||||
let Ok(byte) = memory.read_u8(address) else {
|
||||
return fail(WSAEFAULT);
|
||||
};
|
||||
if byte == 0 {
|
||||
let Some(ip) = std::str::from_utf8(&text[..len])
|
||||
.ok()
|
||||
.and_then(|text| text.parse::<std::net::Ipv4Addr>().ok())
|
||||
else {
|
||||
return Ok(0);
|
||||
};
|
||||
return if memory.write_bytes(args.r8, &ip.octets()).is_ok() {
|
||||
Ok(1)
|
||||
} else {
|
||||
fail(WSAEFAULT)
|
||||
};
|
||||
}
|
||||
if len == text.len() {
|
||||
break;
|
||||
}
|
||||
text[len] = byte;
|
||||
}
|
||||
Ok(0)
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn register_loopback(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
for (symbol, connect) in [("bind", false), ("connect", true)] {
|
||||
let state = Arc::clone(state);
|
||||
registry.register_with_status(
|
||||
MODULE,
|
||||
symbol,
|
||||
ServiceStatus::Partial,
|
||||
move |args, cpu, memory| {
|
||||
let mut net = state.winsock.lock().expect("guest Winsock state");
|
||||
let result = (|| {
|
||||
let socket = net.socket(args.rcx)?;
|
||||
let existing = socket.port;
|
||||
let requested = loopback_port(memory, args.rdx, args.r8 as u32)?;
|
||||
if connect && requested == 0 || !connect && existing.is_some() {
|
||||
return Err(WSAEINVAL);
|
||||
}
|
||||
let local = match (connect, existing) {
|
||||
(true, Some(port)) => port,
|
||||
(true, None) => net.port(0)?,
|
||||
(false, _) => net.port(requested)?,
|
||||
};
|
||||
let socket = net.sockets.get_mut(&args.rcx).expect("validated socket");
|
||||
socket.port = Some(local);
|
||||
if connect {
|
||||
socket.peer = Some(requested);
|
||||
socket.pending.retain(|(source, _)| *source == requested);
|
||||
}
|
||||
state.winsock_changed.notify_all();
|
||||
Ok(0)
|
||||
})();
|
||||
socket_result(&state, cpu.gs_base, result)
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
let send = Arc::clone(state);
|
||||
registry.register_with_status(
|
||||
MODULE,
|
||||
"send",
|
||||
ServiceStatus::Partial,
|
||||
move |args, cpu, memory| {
|
||||
let mut net = send.winsock.lock().expect("guest Winsock state");
|
||||
let result = (|| {
|
||||
let socket = net.socket(args.rcx)?;
|
||||
let peer = socket.peer.ok_or(WSAENOTCONN)?;
|
||||
let source = socket.port.expect("connected socket is bound");
|
||||
let length = args.r8 as i32;
|
||||
if length < 0 || args.r9 as u32 != 0 {
|
||||
return Err(WSAEINVAL);
|
||||
}
|
||||
let length = length as usize;
|
||||
if length > MAX_DATAGRAM {
|
||||
return Err(WSAEMSGSIZE);
|
||||
}
|
||||
let mut data = vec![0; length];
|
||||
if length != 0 {
|
||||
memory
|
||||
.read_bytes(args.rdx, &mut data)
|
||||
.map_err(|_| WSAEFAULT)?;
|
||||
}
|
||||
if let Some(target) = net.sockets.values_mut().find(|socket| {
|
||||
socket.port == Some(peer) && socket.peer.is_none_or(|port| port == source)
|
||||
}) {
|
||||
if target.pending.len() == MAX_PENDING_DATAGRAMS {
|
||||
return Err(WSAENOBUFS);
|
||||
}
|
||||
target.pending.push_back((source, data));
|
||||
send.winsock_changed.notify_all();
|
||||
}
|
||||
Ok(length as u64)
|
||||
})();
|
||||
socket_result(&send, cpu.gs_base, result)
|
||||
},
|
||||
);
|
||||
|
||||
let recv = Arc::clone(state);
|
||||
registry.register_with_status(
|
||||
MODULE,
|
||||
"recv",
|
||||
ServiceStatus::Partial,
|
||||
move |args, cpu, memory| {
|
||||
let mut net = recv.winsock.lock().expect("guest Winsock state");
|
||||
let result = (|| {
|
||||
if net.socket(args.rcx)?.port.is_none() {
|
||||
return Err(WSAEINVAL);
|
||||
}
|
||||
let length = args.r8 as i32;
|
||||
if length < 0 || args.r9 as u32 != 0 {
|
||||
return Err(WSAEINVAL);
|
||||
}
|
||||
let socket = net.sockets.get_mut(&args.rcx).expect("validated socket");
|
||||
let (_, data) = socket.pending.front().ok_or(WSAEWOULDBLOCK)?;
|
||||
let copied = (length as usize).min(data.len());
|
||||
if copied != 0 {
|
||||
memory
|
||||
.write_bytes(args.rdx, &data[..copied])
|
||||
.map_err(|_| WSAEFAULT)?;
|
||||
}
|
||||
let truncated = copied < data.len();
|
||||
socket.pending.pop_front();
|
||||
recv.winsock_changed.notify_all();
|
||||
if truncated {
|
||||
return Err(WSAEMSGSIZE);
|
||||
}
|
||||
Ok(copied as u64)
|
||||
})();
|
||||
socket_result(&recv, cpu.gs_base, result)
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn register_socket_names(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
for (symbol, peer) in [("getsockname", false), ("getpeername", true)] {
|
||||
let state = Arc::clone(state);
|
||||
registry.register_with_status(
|
||||
MODULE,
|
||||
symbol,
|
||||
ServiceStatus::Partial,
|
||||
move |args, cpu, memory| {
|
||||
let result = (|| {
|
||||
let net = state.winsock.lock().expect("guest Winsock state");
|
||||
let socket = net.socket(args.rcx)?;
|
||||
let port = if peer {
|
||||
socket.peer.ok_or(WSAENOTCONN)?
|
||||
} else {
|
||||
socket.port.ok_or(WSAEINVAL)?
|
||||
};
|
||||
if args.rdx == 0 || args.r8 == 0 {
|
||||
return Err(WSAEFAULT);
|
||||
}
|
||||
let length = memory.read_u32(args.r8).map_err(|_| WSAEFAULT)? as i32;
|
||||
let mut address = [0; 16];
|
||||
if length < address.len() as i32 {
|
||||
return Err(WSAEFAULT);
|
||||
}
|
||||
memory
|
||||
.check_write(args.rdx, address.len())
|
||||
.map_err(|_| WSAEFAULT)?;
|
||||
memory.check_write(args.r8, 4).map_err(|_| WSAEFAULT)?;
|
||||
address[..2].copy_from_slice(&2_u16.to_le_bytes());
|
||||
address[2..4].copy_from_slice(&port.to_be_bytes());
|
||||
address[4..8].copy_from_slice(&[127, 0, 0, 1]);
|
||||
memory
|
||||
.write_bytes(args.rdx, &address)
|
||||
.map_err(|_| WSAEFAULT)?;
|
||||
memory
|
||||
.write_u32(args.r8, address.len() as u32)
|
||||
.map_err(|_| WSAEFAULT)?;
|
||||
Ok(0)
|
||||
})();
|
||||
socket_result(&state, cpu.gs_base, result)
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn register_socket_options(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
const SOL_SOCKET: u32 = 0xffff;
|
||||
const SO_TYPE: u32 = 0x1008;
|
||||
const SO_MAX_MSG_SIZE: u32 = 0x2003;
|
||||
const SOCK_DGRAM: u32 = 2;
|
||||
|
||||
let state = Arc::clone(state);
|
||||
registry.register_with_status(
|
||||
MODULE,
|
||||
"getsockopt",
|
||||
ServiceStatus::Partial,
|
||||
move |args, cpu, memory| {
|
||||
let result = (|| {
|
||||
let net = state.winsock.lock().expect("guest Winsock state");
|
||||
net.socket(args.rcx)?;
|
||||
let value = match (args.rdx as u32, args.r8 as u32) {
|
||||
(SOL_SOCKET, SO_TYPE) => SOCK_DGRAM,
|
||||
(SOL_SOCKET, SO_MAX_MSG_SIZE) => MAX_DATAGRAM as u32,
|
||||
_ => return Err(WSAENOPROTOOPT),
|
||||
};
|
||||
let length = args.get(4, memory).map_err(|_| WSAEFAULT)?;
|
||||
if args.r9 == 0 || length == 0 {
|
||||
return Err(WSAEFAULT);
|
||||
}
|
||||
if (memory.read_u32(length).map_err(|_| WSAEFAULT)? as i32) < 4 {
|
||||
return Err(WSAEFAULT);
|
||||
}
|
||||
memory.check_write(args.r9, 4).map_err(|_| WSAEFAULT)?;
|
||||
memory.check_write(length, 4).map_err(|_| WSAEFAULT)?;
|
||||
memory.write_u32(args.r9, value).map_err(|_| WSAEFAULT)?;
|
||||
memory.write_u32(length, 4).map_err(|_| WSAEFAULT)?;
|
||||
Ok(0)
|
||||
})();
|
||||
socket_result(&state, cpu.gs_base, result)
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn register_poll(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
const MAX_POLL_MS: i32 = 1_000;
|
||||
const POLLFD_SIZE: usize = 16;
|
||||
const POLLNVAL: u16 = 0x0004;
|
||||
const POLLWRNORM: u16 = 0x0010;
|
||||
const POLLRDNORM: u16 = 0x0100;
|
||||
const POLLRDBAND: u16 = 0x0200;
|
||||
|
||||
let state = Arc::clone(state);
|
||||
registry.register_with_status(
|
||||
MODULE,
|
||||
"WSAPoll",
|
||||
ServiceStatus::Partial,
|
||||
move |args, cpu, memory| {
|
||||
let result = (|| {
|
||||
let mut net = state.winsock.lock().expect("guest Winsock state");
|
||||
if net.refs == 0 {
|
||||
return Err(WSANOTINITIALISED);
|
||||
}
|
||||
let count = args.rdx as u32 as usize;
|
||||
if !(1..=MAX_SOCKETS).contains(&count) {
|
||||
return Err(WSAEINVAL);
|
||||
}
|
||||
let timeout = args.r8 as i32;
|
||||
if !(0..=MAX_POLL_MS).contains(&timeout) {
|
||||
return Err(WSAEOPNOTSUPP);
|
||||
}
|
||||
if args.rcx == 0 {
|
||||
return Err(WSAEFAULT);
|
||||
}
|
||||
let mut storage = [0; MAX_SOCKETS * POLLFD_SIZE];
|
||||
let descriptors = &mut storage[..count * POLLFD_SIZE];
|
||||
memory
|
||||
.read_bytes(args.rcx, descriptors)
|
||||
.map_err(|_| WSAEFAULT)?;
|
||||
memory
|
||||
.check_write(args.rcx, descriptors.len())
|
||||
.map_err(|_| WSAEFAULT)?;
|
||||
let deadline = Instant::now() + Duration::from_millis(timeout as u64);
|
||||
let ready = loop {
|
||||
if net.refs == 0 {
|
||||
return Err(WSANOTINITIALISED);
|
||||
}
|
||||
let mut ready = 0;
|
||||
for fd in descriptors.as_chunks_mut::<POLLFD_SIZE>().0 {
|
||||
let handle = u64::from_le_bytes(fd[..8].try_into().expect("socket handle"));
|
||||
let events = u16::from_le_bytes([fd[8], fd[9]]);
|
||||
if events & !(POLLWRNORM | POLLRDNORM | POLLRDBAND) != 0 {
|
||||
return Err(WSAEINVAL);
|
||||
}
|
||||
let mut result = POLLNVAL;
|
||||
if let Some(socket) = net.sockets.get(&handle) {
|
||||
result = 0;
|
||||
if !socket.pending.is_empty() {
|
||||
result |= events & POLLRDNORM;
|
||||
}
|
||||
if let Some(peer) = socket.peer
|
||||
&& !net.sockets.values().any(|target| {
|
||||
target.port == Some(peer)
|
||||
&& target.peer.is_none_or(|port| Some(port) == socket.port)
|
||||
&& target.pending.len() == MAX_PENDING_DATAGRAMS
|
||||
})
|
||||
{
|
||||
result |= events & POLLWRNORM;
|
||||
}
|
||||
}
|
||||
fd[10..12].copy_from_slice(&result.to_le_bytes());
|
||||
ready += u64::from(result != 0);
|
||||
}
|
||||
let remaining = deadline.saturating_duration_since(Instant::now());
|
||||
if ready != 0 || remaining.is_zero() {
|
||||
break ready;
|
||||
}
|
||||
#[cfg(test)]
|
||||
{
|
||||
net.poll_waiters += 1;
|
||||
}
|
||||
(net, _) = state
|
||||
.winsock_changed
|
||||
.wait_timeout(net, remaining)
|
||||
.expect("guest Winsock state");
|
||||
#[cfg(test)]
|
||||
{
|
||||
net.poll_waiters -= 1;
|
||||
}
|
||||
};
|
||||
memory
|
||||
.write_bytes(args.rcx, descriptors)
|
||||
.map_err(|_| WSAEFAULT)?;
|
||||
Ok(ready)
|
||||
})();
|
||||
socket_result(&state, cpu.gs_base, result)
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn loopback_datagrams_preserve_boundaries_and_reject_external_addresses() {
|
||||
use crate::cpu::{CpuState, Register};
|
||||
use crate::import_table::ImportName;
|
||||
use crate::imports::Win64Args;
|
||||
use crate::memory::MemoryPermissions;
|
||||
use crate::services::MockClock;
|
||||
|
||||
let mut registry = ImportRegistry::new();
|
||||
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0))));
|
||||
register(&mut registry, &state);
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region(0x1000, 4096, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
let call = |memory: &mut GuestMemory, symbol: &str, args: &[u64]| {
|
||||
let mut cpu = CpuState::default();
|
||||
for (reg, &value) in [Register::Rcx, Register::Rdx, Register::R8, Register::R9]
|
||||
.into_iter()
|
||||
.zip(args)
|
||||
{
|
||||
cpu.set(reg, value);
|
||||
}
|
||||
let descriptor = registry
|
||||
.resolve(MODULE, &ImportName::Name(symbol.to_owned()))
|
||||
.unwrap();
|
||||
(descriptor.handler)(&Win64Args::new(&cpu), &mut cpu, memory).unwrap()
|
||||
};
|
||||
assert_eq!(call(&mut memory, "WSAStartup", &[0x0202, 0x1000]), 0);
|
||||
let server = call(&mut memory, "socket", &[2, 2, 17]);
|
||||
let client = call(&mut memory, "socket", &[2, 2, 17]);
|
||||
let mut address = [0; 16];
|
||||
address[..8].copy_from_slice(&[2, 0, 0x13, 0x88, 127, 0, 0, 1]);
|
||||
memory.write_bytes(0x1200, &address).unwrap();
|
||||
assert_eq!(call(&mut memory, "bind", &[server, 0x1200, 16]), 0);
|
||||
assert_eq!(
|
||||
call(&mut memory, "bind", &[client, 0x1200, 16]),
|
||||
SOCKET_ERROR
|
||||
);
|
||||
assert_eq!(
|
||||
call(&mut memory, "WSAGetLastError", &[]),
|
||||
u64::from(WSAEADDRINUSE)
|
||||
);
|
||||
memory.write_u8(0x1204, 192).unwrap();
|
||||
assert_eq!(
|
||||
call(&mut memory, "connect", &[client, 0x1200, 16]),
|
||||
SOCKET_ERROR
|
||||
);
|
||||
assert_eq!(
|
||||
call(&mut memory, "WSAGetLastError", &[]),
|
||||
u64::from(WSAEACCES)
|
||||
);
|
||||
memory.write_u8(0x1204, 127).unwrap();
|
||||
assert_eq!(call(&mut memory, "connect", &[client, 0x1200, 16]), 0);
|
||||
memory.write_bytes(0x1300, b"hello").unwrap();
|
||||
assert_eq!(call(&mut memory, "send", &[client, 0x1300, 5, 0]), 5);
|
||||
assert_eq!(call(&mut memory, "send", &[client, 0x1300, 2, 0]), 2);
|
||||
assert_eq!(
|
||||
call(&mut memory, "recv", &[server, 0xff, 4, 0]),
|
||||
SOCKET_ERROR
|
||||
);
|
||||
assert_eq!(
|
||||
call(&mut memory, "WSAGetLastError", &[]),
|
||||
u64::from(WSAEFAULT)
|
||||
);
|
||||
assert_eq!(
|
||||
call(&mut memory, "recv", &[server, 0x1400, 4, 0]),
|
||||
SOCKET_ERROR
|
||||
);
|
||||
assert_eq!(
|
||||
call(&mut memory, "WSAGetLastError", &[]),
|
||||
u64::from(WSAEMSGSIZE)
|
||||
);
|
||||
let mut received = [0; 4];
|
||||
memory.read_bytes(0x1400, &mut received).unwrap();
|
||||
assert_eq!(&received, b"hell");
|
||||
assert_eq!(call(&mut memory, "recv", &[server, 0x1400, 4, 0]), 2);
|
||||
assert_eq!(
|
||||
call(&mut memory, "recv", &[server, 0x1400, 4, 0]),
|
||||
SOCKET_ERROR
|
||||
);
|
||||
assert_eq!(
|
||||
call(&mut memory, "WSAGetLastError", &[]),
|
||||
u64::from(WSAEWOULDBLOCK)
|
||||
);
|
||||
|
||||
let mut polling_memory = memory.clone();
|
||||
polling_memory.write_u64(0x1500, server).unwrap();
|
||||
polling_memory.write_u16(0x1508, 0x0100).unwrap();
|
||||
std::thread::scope(|scope| {
|
||||
let (finished, completion) = std::sync::mpsc::channel();
|
||||
let polling_memory = &mut polling_memory;
|
||||
scope.spawn(move || {
|
||||
let ready = call(polling_memory, "WSAPoll", &[0x1500, 1, 1000]);
|
||||
finished.send(ready).unwrap();
|
||||
});
|
||||
let deadline = Instant::now() + Duration::from_millis(500);
|
||||
while state.winsock.lock().unwrap().poll_waiters == 0 {
|
||||
assert!(Instant::now() < deadline, "poll did not enter its wait");
|
||||
std::thread::yield_now();
|
||||
}
|
||||
assert_eq!(call(&mut memory, "send", &[client, 0x1300, 5, 0]), 5);
|
||||
assert_eq!(
|
||||
completion.recv_timeout(Duration::from_millis(400)).unwrap(),
|
||||
1
|
||||
);
|
||||
});
|
||||
assert_eq!(polling_memory.read_u16(0x150a).unwrap(), 0x0100);
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -0,0 +1,452 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Bounded manual work and completion ports for synthetic runtime services.
|
||||
//! The caller supplies monotonic time, allowing deterministic dispatch in tests.
|
||||
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::thread::JoinHandle;
|
||||
use std::time::Duration;
|
||||
|
||||
/// Identifier issued by a task queue and never reused within that queue.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct TaskId(u64);
|
||||
|
||||
impl TaskId {
|
||||
pub(crate) fn from_raw(raw: u64) -> Self {
|
||||
Self(raw)
|
||||
}
|
||||
|
||||
pub(crate) fn raw(self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Why the queue could not accept a task.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum SubmitError {
|
||||
Full,
|
||||
IdExhausted,
|
||||
}
|
||||
|
||||
/// Result delivered once through the completion port.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum TaskResult<T, E> {
|
||||
Finished(Result<T, E>),
|
||||
Cancelled,
|
||||
TimedOut,
|
||||
WorkerPanicked,
|
||||
}
|
||||
|
||||
type Work<T, E> = Box<dyn FnOnce() -> Result<T, E> + Send>;
|
||||
type Callback<T, E> = Box<dyn FnOnce(TaskId, TaskResult<T, E>) + Send>;
|
||||
|
||||
/// A cancellation request that a running operation can observe at safe points.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct CancellationToken(Arc<AtomicBool>);
|
||||
|
||||
impl CancellationToken {
|
||||
pub fn is_cancelled(&self) -> bool {
|
||||
self.0.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
fn request(&self) -> bool {
|
||||
!self.0.swap(true, Ordering::AcqRel)
|
||||
}
|
||||
}
|
||||
|
||||
struct Pending<T, E> {
|
||||
id: TaskId,
|
||||
deadline: Option<Duration>,
|
||||
work: Work<T, E>,
|
||||
callback: Callback<T, E>,
|
||||
cancellation: Option<CancellationToken>,
|
||||
}
|
||||
|
||||
struct Completion<T, E> {
|
||||
id: TaskId,
|
||||
result: TaskResult<T, E>,
|
||||
callback: Callback<T, E>,
|
||||
}
|
||||
|
||||
struct Worker<T, E> {
|
||||
id: TaskId,
|
||||
callback: Callback<T, E>,
|
||||
thread: JoinHandle<Result<T, E>>,
|
||||
cancellation: Option<CancellationToken>,
|
||||
deadline: Option<Duration>,
|
||||
timed_out: bool,
|
||||
}
|
||||
|
||||
/// A manual task queue whose capacity covers pending work and undelivered completions.
|
||||
pub struct TaskQueue<T, E> {
|
||||
capacity: usize,
|
||||
last_id: u64,
|
||||
pending: VecDeque<Pending<T, E>>,
|
||||
completions: VecDeque<Completion<T, E>>,
|
||||
worker: Option<Worker<T, E>>,
|
||||
}
|
||||
|
||||
impl<T, E> TaskQueue<T, E> {
|
||||
pub fn new(capacity: usize) -> Self {
|
||||
Self {
|
||||
capacity,
|
||||
last_id: 0,
|
||||
pending: VecDeque::new(),
|
||||
completions: VecDeque::new(),
|
||||
worker: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Enqueue work and a completion callback. The deadline uses the same clock as dispatch.
|
||||
pub fn submit(
|
||||
&mut self,
|
||||
deadline: Option<Duration>,
|
||||
work: impl FnOnce() -> Result<T, E> + Send + 'static,
|
||||
callback: impl FnOnce(TaskId, TaskResult<T, E>) + Send + 'static,
|
||||
) -> Result<TaskId, SubmitError> {
|
||||
self.enqueue(deadline, Box::new(work), Box::new(callback), None)
|
||||
}
|
||||
|
||||
/// Enqueue work that can observe a request received while it is running.
|
||||
pub fn submit_cancellable(
|
||||
&mut self,
|
||||
deadline: Option<Duration>,
|
||||
work: impl FnOnce(CancellationToken) -> Result<T, E> + Send + 'static,
|
||||
callback: impl FnOnce(TaskId, TaskResult<T, E>) + Send + 'static,
|
||||
) -> Result<TaskId, SubmitError> {
|
||||
let token = CancellationToken::default();
|
||||
self.enqueue(
|
||||
deadline,
|
||||
Box::new({
|
||||
let token = token.clone();
|
||||
move || work(token)
|
||||
}),
|
||||
Box::new(callback),
|
||||
Some(token),
|
||||
)
|
||||
}
|
||||
|
||||
fn enqueue(
|
||||
&mut self,
|
||||
deadline: Option<Duration>,
|
||||
work: Work<T, E>,
|
||||
callback: Callback<T, E>,
|
||||
cancellation: Option<CancellationToken>,
|
||||
) -> Result<TaskId, SubmitError> {
|
||||
if self.pending.len() + self.completions.len() + usize::from(self.worker.is_some())
|
||||
>= self.capacity
|
||||
{
|
||||
return Err(SubmitError::Full);
|
||||
}
|
||||
self.last_id = self
|
||||
.last_id
|
||||
.checked_add(1)
|
||||
.ok_or(SubmitError::IdExhausted)?;
|
||||
let id = TaskId(self.last_id);
|
||||
self.pending.push_back(Pending {
|
||||
id,
|
||||
deadline,
|
||||
work,
|
||||
callback,
|
||||
cancellation,
|
||||
});
|
||||
Ok(id)
|
||||
}
|
||||
|
||||
/// Cancel queued work or request cooperative cancellation of an active worker.
|
||||
pub fn cancel(&mut self, id: TaskId) -> bool {
|
||||
self.collect_worker();
|
||||
if let Some(worker) = &self.worker
|
||||
&& worker.id == id
|
||||
{
|
||||
return worker
|
||||
.cancellation
|
||||
.as_ref()
|
||||
.is_some_and(CancellationToken::request);
|
||||
}
|
||||
let Some(index) = self.pending.iter().position(|task| task.id == id) else {
|
||||
return false;
|
||||
};
|
||||
let task = self
|
||||
.pending
|
||||
.remove(index)
|
||||
.expect("position in pending queue");
|
||||
self.completions.push_back(Completion {
|
||||
id,
|
||||
result: TaskResult::Cancelled,
|
||||
callback: task.callback,
|
||||
});
|
||||
true
|
||||
}
|
||||
|
||||
/// Run one queued operation. An expired operation completes without running.
|
||||
pub fn dispatch_work(&mut self, now: Duration) -> bool {
|
||||
self.advance_time(now);
|
||||
if self.worker.is_some() {
|
||||
return false;
|
||||
}
|
||||
let Some(task) = self.pending.pop_front() else {
|
||||
return false;
|
||||
};
|
||||
let result = if task.deadline.is_some_and(|deadline| now >= deadline) {
|
||||
TaskResult::TimedOut
|
||||
} else {
|
||||
TaskResult::Finished((task.work)())
|
||||
};
|
||||
self.completions.push_back(Completion {
|
||||
id: task.id,
|
||||
result,
|
||||
callback: task.callback,
|
||||
});
|
||||
true
|
||||
}
|
||||
|
||||
/// Invoke one callback on the caller's thread.
|
||||
pub fn dispatch_completion(&mut self) -> bool {
|
||||
self.collect_worker();
|
||||
let Some(completion) = self.completions.pop_front() else {
|
||||
return false;
|
||||
};
|
||||
(completion.callback)(completion.id, completion.result);
|
||||
true
|
||||
}
|
||||
|
||||
/// Advance the queue's clock and request cooperative exit from expired work.
|
||||
/// A completion already available when the clock is sampled keeps its result.
|
||||
pub fn advance_time(&mut self, now: Duration) {
|
||||
self.collect_worker();
|
||||
if let Some(worker) = &mut self.worker
|
||||
&& worker.deadline.is_some_and(|deadline| now >= deadline)
|
||||
&& worker
|
||||
.cancellation
|
||||
.as_ref()
|
||||
.is_some_and(CancellationToken::request)
|
||||
{
|
||||
worker.timed_out = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn collect_worker(&mut self) {
|
||||
if self
|
||||
.worker
|
||||
.as_ref()
|
||||
.is_some_and(|worker| worker.thread.is_finished())
|
||||
{
|
||||
let worker = self.worker.take().expect("finished worker");
|
||||
let result = match worker.thread.join() {
|
||||
Err(_) => TaskResult::WorkerPanicked,
|
||||
Ok(_) if worker.timed_out => TaskResult::TimedOut,
|
||||
Ok(_)
|
||||
if worker
|
||||
.cancellation
|
||||
.as_ref()
|
||||
.is_some_and(CancellationToken::is_cancelled) =>
|
||||
{
|
||||
TaskResult::Cancelled
|
||||
}
|
||||
Ok(result) => TaskResult::Finished(result),
|
||||
};
|
||||
self.completions.push_back(Completion {
|
||||
id: worker.id,
|
||||
result,
|
||||
callback: worker.callback,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: Send + 'static, E: Send + 'static> TaskQueue<T, E> {
|
||||
/// Start one background operation. At most one worker runs per queue.
|
||||
pub fn dispatch_background(&mut self, now: Duration) -> std::io::Result<bool> {
|
||||
self.advance_time(now);
|
||||
if self.worker.is_some() {
|
||||
return Ok(false);
|
||||
}
|
||||
let Some(task) = self.pending.front() else {
|
||||
return Ok(false);
|
||||
};
|
||||
if task.deadline.is_some_and(|deadline| now >= deadline) {
|
||||
return Ok(self.dispatch_work(now));
|
||||
}
|
||||
let (send, receive) = std::sync::mpsc::channel::<Work<T, E>>();
|
||||
// Start the thread before removing the task so spawn failure leaves it queued.
|
||||
let thread = std::thread::Builder::new()
|
||||
.name("xenora-task".into())
|
||||
.spawn(move || receive.recv().expect("worker receives one operation")())?;
|
||||
let task = self.pending.pop_front().expect("pending task");
|
||||
assert!(send.send(task.work).is_ok());
|
||||
self.worker = Some(Worker {
|
||||
id: task.id,
|
||||
callback: task.callback,
|
||||
thread,
|
||||
cancellation: task.cancellation,
|
||||
deadline: task.deadline,
|
||||
timed_out: false,
|
||||
});
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, E> Drop for TaskQueue<T, E> {
|
||||
fn drop(&mut self) {
|
||||
if let Some(worker) = self.worker.take() {
|
||||
if let Some(token) = worker.cancellation {
|
||||
token.request();
|
||||
}
|
||||
let _ = worker.thread.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn running_task_observes_cancellation_and_deadlines_before_completion() {
|
||||
use std::sync::mpsc::channel;
|
||||
use std::time::Instant;
|
||||
|
||||
let timeout = Duration::from_millis(5);
|
||||
for expire in [false, true] {
|
||||
let mut queue = TaskQueue::<u32, u32>::new(1);
|
||||
let (running, started) = channel();
|
||||
let (completed, results) = channel();
|
||||
let id = queue
|
||||
.submit_cancellable(
|
||||
Some(timeout),
|
||||
move |token| {
|
||||
running.send(()).unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(2);
|
||||
while !token.is_cancelled() {
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"work did not observe cancellation"
|
||||
);
|
||||
std::thread::yield_now();
|
||||
}
|
||||
Ok(17)
|
||||
},
|
||||
move |id, result| completed.send((id, result)).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(queue.dispatch_background(Duration::ZERO).unwrap());
|
||||
started.recv_timeout(Duration::from_secs(2)).unwrap();
|
||||
if expire {
|
||||
queue.advance_time(timeout - Duration::from_millis(1));
|
||||
assert!(!queue.dispatch_completion());
|
||||
queue.advance_time(timeout);
|
||||
} else {
|
||||
assert!(queue.cancel(id));
|
||||
}
|
||||
assert!(!queue.cancel(id));
|
||||
let deadline = Instant::now() + Duration::from_secs(2);
|
||||
while !queue.dispatch_completion() {
|
||||
assert!(Instant::now() < deadline, "worker did not complete");
|
||||
std::thread::yield_now();
|
||||
}
|
||||
assert_eq!(
|
||||
results.try_recv().unwrap(),
|
||||
(
|
||||
id,
|
||||
if expire {
|
||||
TaskResult::TimedOut
|
||||
} else {
|
||||
TaskResult::Cancelled
|
||||
}
|
||||
)
|
||||
);
|
||||
assert!(!queue.dispatch_completion());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn background_worker_preserves_capacity_and_manual_completion() {
|
||||
use std::sync::mpsc::channel;
|
||||
use std::time::Instant;
|
||||
|
||||
let mut queue = TaskQueue::<u32, u32>::new(1);
|
||||
let (release, gate) = channel();
|
||||
let (completed, results) = channel();
|
||||
let id = queue
|
||||
.submit(
|
||||
None,
|
||||
move || {
|
||||
gate.recv_timeout(Duration::from_secs(2)).unwrap();
|
||||
Ok(17)
|
||||
},
|
||||
move |id, result| completed.send((id, result)).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(queue.dispatch_background(Duration::ZERO).unwrap());
|
||||
assert!(!queue.dispatch_background(Duration::ZERO).unwrap());
|
||||
assert!(!queue.cancel(id));
|
||||
assert!(!queue.dispatch_completion());
|
||||
assert_eq!(
|
||||
queue.submit(None, || Ok(0), |_, _| {}),
|
||||
Err(SubmitError::Full)
|
||||
);
|
||||
release.send(()).unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(2);
|
||||
while !queue.dispatch_completion() {
|
||||
assert!(Instant::now() < deadline, "worker did not complete");
|
||||
std::thread::yield_now();
|
||||
}
|
||||
assert_eq!(
|
||||
results.try_recv().unwrap(),
|
||||
(id, TaskResult::Finished(Ok(17)))
|
||||
);
|
||||
assert!(!queue.dispatch_completion());
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[test]
|
||||
fn manual_ports_deliver_errors_cancellation_and_deadlines_once() {
|
||||
use std::sync::mpsc::channel;
|
||||
|
||||
let mut queue = TaskQueue::<u32, u32>::new(3);
|
||||
let (sender, receiver) = channel();
|
||||
let callback = || {
|
||||
let sender = sender.clone();
|
||||
move |id, result| sender.send((id, result)).unwrap()
|
||||
};
|
||||
let first = queue.submit(None, || Err(7), callback()).unwrap();
|
||||
let cancelled = queue
|
||||
.submit(None, || panic!("cancelled"), callback())
|
||||
.unwrap();
|
||||
let deadline = Duration::from_millis(10);
|
||||
let expired = queue
|
||||
.submit(Some(deadline), || panic!("expired"), callback())
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
queue.submit(None, || Ok(1), callback()),
|
||||
Err(SubmitError::Full)
|
||||
);
|
||||
assert!(queue.cancel(cancelled));
|
||||
assert!(!queue.cancel(cancelled));
|
||||
assert!(queue.dispatch_work(Duration::ZERO));
|
||||
assert!(queue.dispatch_work(deadline));
|
||||
assert!(!queue.dispatch_work(deadline));
|
||||
assert_eq!(
|
||||
queue.submit(None, || Ok(1), callback()),
|
||||
Err(SubmitError::Full)
|
||||
);
|
||||
assert!(receiver.try_recv().is_err());
|
||||
for expected in [
|
||||
(cancelled, TaskResult::Cancelled),
|
||||
(first, TaskResult::Finished(Err(7))),
|
||||
(expired, TaskResult::TimedOut),
|
||||
] {
|
||||
assert!(queue.dispatch_completion());
|
||||
assert_eq!(receiver.try_recv().unwrap(), expected);
|
||||
}
|
||||
assert!(!queue.dispatch_completion());
|
||||
let next = queue.submit(None, || Ok(1), callback()).unwrap();
|
||||
assert_ne!(next, first);
|
||||
assert!(queue.dispatch_work(deadline));
|
||||
assert!(queue.dispatch_completion());
|
||||
assert_eq!(
|
||||
receiver.try_recv().unwrap(),
|
||||
(next, TaskResult::Finished(Ok(1)))
|
||||
);
|
||||
}
|
||||
@@ -144,9 +144,20 @@ pub fn parse_tls_directory(bytes: &[u8], pe: &ParsedPe) -> Result<Option<TlsDire
|
||||
}))
|
||||
}
|
||||
|
||||
/// Bytes reserved at `thread_tls_base` for the thread's TLS pointer array.
|
||||
const TLS_ARRAY_SIZE: usize = 0x1000;
|
||||
|
||||
/// 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.
|
||||
pub fn setup_tls(
|
||||
tls: &TlsDirectory,
|
||||
loaded_base: u64,
|
||||
@@ -187,15 +198,25 @@ pub fn setup_tls(
|
||||
memory.read_bytes(actual_start, &mut template_data)?;
|
||||
}
|
||||
|
||||
// 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,
|
||||
TLS_ARRAY_SIZE,
|
||||
MemoryPermissions::READ_WRITE,
|
||||
)?;
|
||||
memory.map_region_with_data(
|
||||
block_base,
|
||||
map_size,
|
||||
MemoryPermissions::READ_WRITE,
|
||||
&template_data,
|
||||
)?;
|
||||
// Slot 0 belongs to the index assigned above.
|
||||
memory.write_u64(thread_tls_base, block_base)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -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,
|
||||
@@ -167,6 +171,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 +237,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 +265,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 +300,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 +321,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 +332,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 +363,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 +401,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 +461,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 +512,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 {
|
||||
@@ -238,6 +241,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 +287,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),
|
||||
@@ -351,6 +373,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 +388,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 +448,7 @@ pub fn execute(
|
||||
if negative { mask(size) } else { 0 },
|
||||
);
|
||||
}
|
||||
Op::Rol | Op::Ror | Op::Shl | Op::Shr | Op::Sar => {
|
||||
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 +605,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,
|
||||
|
||||
+635
-484
File diff suppressed because it is too large.
Load diff
@@ -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}");
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
use std::sync::Arc;
|
||||
use xenora_loader::cpu::{CpuState, ExitReason};
|
||||
use xenora_loader::imports::{ImportRegistry, ServiceStatus, Win64Args};
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
use xenora_loader::memory::{GuestMemory, MemoryError, MemoryPermissions};
|
||||
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
|
||||
|
||||
#[test]
|
||||
@@ -61,3 +61,51 @@ fn test_unsupported_stub_fails_explicitly() {
|
||||
let res = (desc.handler)(&args, &mut cpu, &mut mem);
|
||||
assert_eq!(res, Err(ExitReason::IllegalInstruction(0xFE)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn crt_handlers_validate_memory_boundaries() {
|
||||
let mut registry = ImportRegistry::new();
|
||||
register_standard_services(
|
||||
&mut registry,
|
||||
Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))),
|
||||
);
|
||||
let mut cpu = CpuState::new(0x1000, 0x8000);
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(0x1000, 4, MemoryPermissions::READ_WRITE, b"abcd")
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region_with_data(0x1004, 4, MemoryPermissions::READ_WRITE, b"efgh")
|
||||
.unwrap();
|
||||
let mut call = |symbol, rcx, rdx, r8, memory: &mut GuestMemory| {
|
||||
let args = Win64Args {
|
||||
rcx,
|
||||
rdx,
|
||||
r8,
|
||||
r9: 0,
|
||||
rsp: 0x8000,
|
||||
};
|
||||
let service = registry.binding("ucrtbase.dll", symbol).unwrap();
|
||||
(service.handler)(&args, &mut cpu, memory)
|
||||
};
|
||||
|
||||
assert_eq!(call("strnlen", 0x1000, 8, 0, &mut memory), Ok(8));
|
||||
assert_eq!(
|
||||
call("strlen", 0x1000, 0, 0, &mut memory),
|
||||
Err(ExitReason::MemoryFault(MemoryError::UnmappedAddress(
|
||||
0x1008
|
||||
)))
|
||||
);
|
||||
assert_eq!(
|
||||
call("memmove", 0x1005, 0x1000, 4, &mut memory),
|
||||
Err(ExitReason::MemoryFault(MemoryError::UnmappedAddress(
|
||||
0x1005
|
||||
)))
|
||||
);
|
||||
let mut bytes = [0; 8];
|
||||
memory.read_bytes(0x1000, &mut bytes).unwrap();
|
||||
assert_eq!(&bytes, b"abcdefgh");
|
||||
assert_eq!(call("memmove", 0x1002, 0x1000, 6, &mut memory), Ok(0x1002));
|
||||
memory.read_bytes(0x1000, &mut bytes).unwrap();
|
||||
assert_eq!(&bytes, b"ababcdef");
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,419 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Static probe reports for delay-loaded PE imports.
|
||||
//!
|
||||
//! The expected names and slot RVAs are read off the layout that
|
||||
//! `fixtures/pe/delay-imports.py` writes, not from the parser.
|
||||
//! `llvm-readobj --coff-imports` from LLVM 23.1.6 lists the same imports in
|
||||
//! the same order, with the address tables at RVA 0x2050, 0x3000 and 0x3020.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use xenora_loader::import_table::{DelayField, ImportTableError, parse_delay_imports};
|
||||
use xenora_loader::probe::{
|
||||
ImportedSymbol, ProbeConfig, ProbeReport, probe_pe_bytes, run_probe_and_export,
|
||||
};
|
||||
|
||||
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/delay-imports.exe");
|
||||
|
||||
/// DLL, symbol or ordinal, and import address table slot RVA.
|
||||
type Row = (&'static str, &'static str, u32);
|
||||
|
||||
const ORDINARY: [Row; 2] = [
|
||||
("fixture-ordinary.dll", "OrdinaryByName", 0x2050),
|
||||
("fixture-ordinary.dll", "Ordinal#3", 0x2058),
|
||||
];
|
||||
const DELAYED: [Row; 3] = [
|
||||
("fixture-delay-a.dll", "DelayedAlpha", 0x3000),
|
||||
("fixture-delay-a.dll", "Ordinal#7", 0x3008),
|
||||
("fixture-delay-b.dll", "DelayedBeta", 0x3020),
|
||||
];
|
||||
|
||||
// File offsets in the fixture.
|
||||
const NUMBER_OF_RVA_AND_SIZES: usize = 0x98 + 108;
|
||||
const DELAY_DIRECTORY_ENTRY: usize = 0x98 + 216;
|
||||
const DELAY_DIRECTORY_SIZE: usize = DELAY_DIRECTORY_ENTRY + 4;
|
||||
const RDATA_RAW_SIZE: usize = 0x188 + 40 + 16;
|
||||
/// The delay-load directory is at RVA 0x2200; `.rdata` maps RVA 0x2000 to 0x600.
|
||||
const FIRST_DESCRIPTOR: usize = 0x800;
|
||||
const SECOND_DESCRIPTOR: usize = 0x820;
|
||||
|
||||
fn rows(imports: &[ImportedSymbol]) -> Vec<(&str, &str, u32)> {
|
||||
imports
|
||||
.iter()
|
||||
.map(|import| (import.dll.as_str(), import.symbol.as_str(), import.iat_rva))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn put(pe: &mut [u8], offset: usize, value: u32) {
|
||||
pe[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
|
||||
}
|
||||
|
||||
/// Probe `pe` and return the report with the text files it exports.
|
||||
fn export(pe: &[u8], name: &str) -> (ProbeReport, BTreeMap<&'static str, String>) {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("xenora-probe-delay-{name}-{}", std::process::id()));
|
||||
let report = run_probe_and_export(pe, &dir, &ProbeConfig::default()).unwrap();
|
||||
let files = [
|
||||
"imports.csv",
|
||||
"missing_imports.csv",
|
||||
"candidate_static_report.json",
|
||||
"candidate_static_report.md",
|
||||
"runtime_gap_matrix.md",
|
||||
]
|
||||
.into_iter()
|
||||
.map(|file| (file, std::fs::read_to_string(dir.join(file)).unwrap()))
|
||||
.collect();
|
||||
std::fs::remove_dir_all(dir).unwrap();
|
||||
(report, files)
|
||||
}
|
||||
|
||||
fn json_field(json: &str, name: &str) -> String {
|
||||
let prefix = format!("\"{name}\": ");
|
||||
json.lines()
|
||||
.find_map(|line| line.trim().strip_prefix(&prefix))
|
||||
.unwrap_or_else(|| panic!("no {name} in the JSON report"))
|
||||
.trim_end_matches(',')
|
||||
.trim_matches('"')
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinary_and_delayed_imports_are_reported_apart() {
|
||||
let (report, files) = export(FIXTURE, "fixture");
|
||||
|
||||
assert_eq!(rows(&report.imports), ORDINARY);
|
||||
assert_eq!(rows(&report.delayed_imports), DELAYED);
|
||||
assert_eq!(report.import_error, None);
|
||||
assert_eq!(report.delay_import_error, None);
|
||||
|
||||
let mut lines = files["imports.csv"].lines();
|
||||
let header = lines.next().unwrap();
|
||||
assert!(header.starts_with("module,symbol_or_ordinal,iat_rva,import_table,"));
|
||||
assert!(header.ends_with(",import_kind"));
|
||||
let columns = header.split(',').count();
|
||||
// The first four columns and the last one of every row.
|
||||
let listed: Vec<String> = lines
|
||||
.map(|line| {
|
||||
let fields: Vec<&str> = line.split(',').collect();
|
||||
assert_eq!(fields.len(), columns, "{line}");
|
||||
format!("{},{}", fields[..4].join(","), fields[columns - 1])
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
listed,
|
||||
[
|
||||
"\"fixture-ordinary.dll\",\"OrdinaryByName\",0x00002050,ordinary,name",
|
||||
"\"fixture-ordinary.dll\",\"Ordinal#3\",0x00002058,ordinary,ordinal",
|
||||
"\"fixture-delay-a.dll\",\"DelayedAlpha\",0x00003000,delayed,name",
|
||||
"\"fixture-delay-a.dll\",\"Ordinal#7\",0x00003008,delayed,ordinal",
|
||||
"\"fixture-delay-b.dll\",\"DelayedBeta\",0x00003020,delayed,name",
|
||||
]
|
||||
);
|
||||
|
||||
// Neither fixture DLL has a handler, so both ordinary imports are missing.
|
||||
// The delayed ones are not the binder's to resolve and stay off its list.
|
||||
assert_eq!(
|
||||
files["missing_imports.csv"].lines().collect::<Vec<_>>(),
|
||||
[
|
||||
"module,symbol_or_ordinal,iat_rva,import_kind",
|
||||
"\"fixture-ordinary.dll\",\"OrdinaryByName\",0x00002050,name",
|
||||
"\"fixture-ordinary.dll\",\"Ordinal#3\",0x00002058,ordinal",
|
||||
]
|
||||
);
|
||||
|
||||
let json = &files["candidate_static_report.json"];
|
||||
for (name, expected) in [
|
||||
("total_imports", "2"),
|
||||
("imported_dlls_count", "1"),
|
||||
("unresolved_imports", "2"),
|
||||
("distinct_import_keys", "2"),
|
||||
("delayed_imports", "3"),
|
||||
("delayed_imported_dlls_count", "2"),
|
||||
("delay_import_error", "none"),
|
||||
] {
|
||||
assert_eq!(json_field(json, name), expected, "{name}");
|
||||
}
|
||||
|
||||
let md = &files["candidate_static_report.md"];
|
||||
assert!(md.contains("- **Total Imported Thunks**: `2`"));
|
||||
assert!(md.contains("- **Delay-Loaded Import Slots**: `3` across `2` DLLs."));
|
||||
assert!(!md.contains("Delay-load import table is malformed"));
|
||||
assert!(
|
||||
files["runtime_gap_matrix.md"]
|
||||
.contains("The delay-load import tables contain 3 more slots across 2 DLLs.")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inspection_decodes_the_entry_point_and_follows_no_delay_slot() {
|
||||
let report = probe_pe_bytes(FIXTURE, &ProbeConfig::default()).unwrap();
|
||||
|
||||
// The entry point is a lone RET at RVA 0x1000. The three delay-load slots
|
||||
// hold the addresses of INT3 stubs at 0x1010, 0x1018 and 0x1020. Reaching
|
||||
// one would mean the probe followed a slot, so none may be decoded.
|
||||
let decoded: Vec<(u32, &[u8])> = report
|
||||
.instruction_records
|
||||
.iter()
|
||||
.map(|record| (record.rva, record.bytes.as_slice()))
|
||||
.collect();
|
||||
assert_eq!(decoded, [(0x1000, &[0xc3][..])]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_without_a_delay_directory_keeps_its_ordinary_imports() {
|
||||
// `fixtures/pe/trusted-runner.py` writes one import, `xenora.dll!fixture_draw`,
|
||||
// with its slot at RVA 0x2040 and no delay import descriptor.
|
||||
let runner = include_bytes!("../../../fixtures/pe/trusted-runner.exe");
|
||||
let (report, files) = export(runner, "runner");
|
||||
assert_eq!(
|
||||
rows(&report.imports),
|
||||
[("xenora.dll", "fixture_draw", 0x2040)]
|
||||
);
|
||||
assert_eq!(report.import_error, None);
|
||||
assert!(report.delayed_imports.is_empty());
|
||||
assert_eq!(report.delay_import_error, None);
|
||||
|
||||
let listed: Vec<&str> = files["imports.csv"].lines().skip(1).collect();
|
||||
assert_eq!(listed.len(), 1);
|
||||
assert!(listed[0].starts_with("\"xenora.dll\",\"fixture_draw\",0x00002040,ordinary,"));
|
||||
let json = &files["candidate_static_report.json"];
|
||||
assert_eq!(json_field(json, "total_imports"), "1");
|
||||
assert_eq!(json_field(json, "imported_dlls_count"), "1");
|
||||
assert_eq!(json_field(json, "delayed_imports"), "0");
|
||||
assert_eq!(json_field(json, "delayed_imported_dlls_count"), "0");
|
||||
assert_eq!(json_field(json, "delay_import_error"), "none");
|
||||
assert!(!files["runtime_gap_matrix.md"].contains("delay-load"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delay_directory_beyond_the_declared_count_is_not_read() {
|
||||
// With 13 data directories the header has no delay import descriptor, so
|
||||
// the bytes at its offset mean nothing.
|
||||
let mut pe = FIXTURE.to_vec();
|
||||
put(&mut pe, NUMBER_OF_RVA_AND_SIZES, 13);
|
||||
let report = probe_pe_bytes(&pe, &ProbeConfig::default()).unwrap();
|
||||
assert_eq!(rows(&report.imports), ORDINARY);
|
||||
assert!(report.delayed_imports.is_empty());
|
||||
assert_eq!(report.delay_import_error, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_delay_tables_are_diagnosed_and_ordinary_imports_kept() {
|
||||
type Case = (
|
||||
&'static str,
|
||||
fn(&mut Vec<u8>),
|
||||
usize,
|
||||
ImportTableError,
|
||||
&'static str,
|
||||
);
|
||||
// (name, damage, delayed imports still listed, error, message)
|
||||
let cases: [Case; 13] = [
|
||||
(
|
||||
"directory-out-of-range",
|
||||
|pe| put(pe, DELAY_DIRECTORY_ENTRY, 0x9000),
|
||||
0,
|
||||
ImportTableError::OutOfBounds { rva: 0x9000 },
|
||||
"import data at RVA 0x00009000 is truncated or outside the section data",
|
||||
),
|
||||
(
|
||||
// `.rdata` keeps 0x230 bytes: the first descriptor and half the second.
|
||||
"section-data-ends-inside-descriptor",
|
||||
|pe| put(pe, RDATA_RAW_SIZE, 0x230),
|
||||
2,
|
||||
ImportTableError::OutOfBounds { rva: 0x2220 },
|
||||
"import data at RVA 0x00002220 is truncated or outside the section data",
|
||||
),
|
||||
(
|
||||
// The file ends where `.data` and its address tables would begin.
|
||||
"file-ends-before-address-table",
|
||||
|pe| pe.truncate(0xa00),
|
||||
0,
|
||||
ImportTableError::OutOfBounds { rva: 0x3000 },
|
||||
"import data at RVA 0x00003000 is truncated or outside the section data",
|
||||
),
|
||||
(
|
||||
"name-table-out-of-range",
|
||||
|pe| put(pe, FIRST_DESCRIPTOR + 16, 0x9000),
|
||||
0,
|
||||
ImportTableError::OutOfBounds { rva: 0x9000 },
|
||||
"import data at RVA 0x00009000 is truncated or outside the section data",
|
||||
),
|
||||
(
|
||||
"address-table-out-of-range",
|
||||
|pe| put(pe, SECOND_DESCRIPTOR + 12, 0x9000),
|
||||
2,
|
||||
ImportTableError::OutOfBounds { rva: 0x9000 },
|
||||
"import data at RVA 0x00009000 is truncated or outside the section data",
|
||||
),
|
||||
(
|
||||
// The second DLL's name table becomes the empty entry that ends the
|
||||
// first one, at RVA 0x2110, so no import reads the address table.
|
||||
"address-table-out-of-range-without-imports",
|
||||
|pe| {
|
||||
put(pe, SECOND_DESCRIPTOR + 16, 0x2110);
|
||||
put(pe, SECOND_DESCRIPTOR + 12, 0x9000);
|
||||
},
|
||||
2,
|
||||
ImportTableError::OutOfBounds { rva: 0x9000 },
|
||||
"import data at RVA 0x00009000 is truncated or outside the section data",
|
||||
),
|
||||
(
|
||||
"dll-name-out-of-range",
|
||||
|pe| put(pe, SECOND_DESCRIPTOR + 4, 0x9000),
|
||||
2,
|
||||
ImportTableError::OutOfBounds { rva: 0x9000 },
|
||||
"import data at RVA 0x00009000 is truncated or outside the section data",
|
||||
),
|
||||
(
|
||||
// RVA 0x2028 is zero padding after the ordinary import directory.
|
||||
"dll-name-empty",
|
||||
|pe| put(pe, SECOND_DESCRIPTOR + 4, 0x2028),
|
||||
2,
|
||||
ImportTableError::MalformedName { rva: 0x2028 },
|
||||
"malformed import name at RVA 0x00002028",
|
||||
),
|
||||
(
|
||||
"dll-name-missing",
|
||||
|pe| put(pe, SECOND_DESCRIPTOR + 4, 0),
|
||||
2,
|
||||
ImportTableError::DelayFieldMissing {
|
||||
rva: 0x2220,
|
||||
field: DelayField::DllName,
|
||||
},
|
||||
"delay-load descriptor at RVA 0x00002220 has no DLL name",
|
||||
),
|
||||
(
|
||||
"address-table-missing",
|
||||
|pe| put(pe, FIRST_DESCRIPTOR + 12, 0),
|
||||
0,
|
||||
ImportTableError::DelayFieldMissing {
|
||||
rva: 0x2200,
|
||||
field: DelayField::AddressTable,
|
||||
},
|
||||
"delay-load descriptor at RVA 0x00002200 has no import address table",
|
||||
),
|
||||
(
|
||||
"name-table-missing",
|
||||
|pe| put(pe, SECOND_DESCRIPTOR + 16, 0),
|
||||
2,
|
||||
ImportTableError::DelayFieldMissing {
|
||||
rva: 0x2220,
|
||||
field: DelayField::NameTable,
|
||||
},
|
||||
"delay-load descriptor at RVA 0x00002220 has no import name table",
|
||||
),
|
||||
(
|
||||
"reserved-attribute-bit",
|
||||
|pe| put(pe, FIRST_DESCRIPTOR, 3),
|
||||
0,
|
||||
ImportTableError::DelayReservedBits { rva: 0x2200 },
|
||||
"reserved attribute bits set in the delay-load descriptor at RVA 0x00002200",
|
||||
),
|
||||
(
|
||||
"virtual-address-form",
|
||||
|pe| put(pe, SECOND_DESCRIPTOR, 0),
|
||||
2,
|
||||
ImportTableError::DelayVirtualAddresses { rva: 0x2220 },
|
||||
"delay-load descriptor at RVA 0x00002220 holds virtual addresses, not RVAs, and is not read",
|
||||
),
|
||||
];
|
||||
|
||||
for (name, damage, listed, error, message) in cases {
|
||||
let mut pe = FIXTURE.to_vec();
|
||||
damage(&mut pe);
|
||||
let (report, files) = export(&pe, name);
|
||||
|
||||
assert_eq!(rows(&report.imports), ORDINARY, "{name}");
|
||||
assert_eq!(report.import_error, None, "{name}");
|
||||
assert_eq!(rows(&report.delayed_imports), DELAYED[..listed], "{name}");
|
||||
assert_eq!(report.delay_import_error, Some(error), "{name}");
|
||||
assert_eq!(error.to_string(), message, "{name}");
|
||||
|
||||
let json = &files["candidate_static_report.json"];
|
||||
assert_eq!(json_field(json, "total_imports"), "2", "{name}");
|
||||
assert_eq!(
|
||||
json_field(json, "delayed_imports"),
|
||||
listed.to_string(),
|
||||
"{name}"
|
||||
);
|
||||
assert_eq!(json_field(json, "delay_import_error"), message, "{name}");
|
||||
assert!(
|
||||
files["candidate_static_report.md"].contains(&format!(
|
||||
"- **Delay-load import table is malformed**: {message}. Only the delay-loaded imports before it are listed."
|
||||
)),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn declared_directory_size_bounds_the_table() {
|
||||
// The fixture declares 96 bytes at RVA 0x2200: two descriptors and the
|
||||
// empty one. A descriptor counts only if the declared size holds all of
|
||||
// it, and the size must reach the empty descriptor.
|
||||
let end = |rva| Some(ImportTableError::DelayDirectoryEnd { rva });
|
||||
for (size, listed, error) in [
|
||||
(0, 0, end(0x2200)),
|
||||
(31, 0, end(0x221f)),
|
||||
(32, 2, end(0x2220)),
|
||||
(63, 2, end(0x223f)),
|
||||
(64, 3, end(0x2240)),
|
||||
(95, 3, end(0x225f)),
|
||||
(96, 3, None),
|
||||
(97, 3, None),
|
||||
(0x1000, 3, None),
|
||||
// The directory would run past the end of the address space.
|
||||
(
|
||||
u32::MAX,
|
||||
0,
|
||||
Some(ImportTableError::OutOfBounds { rva: 0x2200 }),
|
||||
),
|
||||
] {
|
||||
let mut pe = FIXTURE.to_vec();
|
||||
put(&mut pe, DELAY_DIRECTORY_SIZE, size);
|
||||
let report = probe_pe_bytes(&pe, &ProbeConfig::default()).unwrap();
|
||||
assert_eq!(rows(&report.imports), ORDINARY, "size {size}");
|
||||
assert_eq!(
|
||||
rows(&report.delayed_imports),
|
||||
DELAYED[..listed],
|
||||
"size {size}"
|
||||
);
|
||||
assert_eq!(report.delay_import_error, error, "size {size}");
|
||||
}
|
||||
assert_eq!(
|
||||
ImportTableError::DelayDirectoryEnd { rva: 0x2240 }.to_string(),
|
||||
"delay-load directory ends at RVA 0x00002240 before its empty descriptor"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn endless_delay_table_is_refused() {
|
||||
// Every descriptor RVA maps onto the same 32 bytes, so the table never
|
||||
// reaches its empty entry within the megabyte it declares. The descriptor
|
||||
// names module "a" at RVA 0x1000, an empty name table at RVA 0x2000 and an
|
||||
// address table at RVA 0x3000.
|
||||
let mut bytes = vec![0u8; 48];
|
||||
put(&mut bytes, 0, 1);
|
||||
put(&mut bytes, 4, 0x1000);
|
||||
put(&mut bytes, 12, 0x3000);
|
||||
put(&mut bytes, 16, 0x2000);
|
||||
bytes[32] = b'a';
|
||||
let (imports, error) = parse_delay_imports(&bytes, 0x10_0000, 0x10_0000, |rva| match rva {
|
||||
0x1000..0x1002 => Some(32 + (rva - 0x1000) as usize),
|
||||
0x2000..0x2008 => Some(40 + (rva - 0x2000) as usize),
|
||||
0x3000..0x3008 => Some(40 + (rva - 0x3000) as usize),
|
||||
0x10_0000.. => Some((rva % 32) as usize),
|
||||
_ => None,
|
||||
});
|
||||
assert!(imports.is_empty());
|
||||
assert_eq!(error, Some(ImportTableError::TooManyDescriptors));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probe_never_panics_on_a_truncated_delay_fixture() {
|
||||
for len in 1..=FIXTURE.len() {
|
||||
// The probe may reject the file or report unreadable imports, but it
|
||||
// must not panic.
|
||||
let _ = probe_pe_bytes(&FIXTURE[..len], &ProbeConfig::default());
|
||||
}
|
||||
}
|
||||
@@ -200,6 +200,26 @@ fn probe_distinguishes_aliases_from_unavailable_services() {
|
||||
std::fs::remove_dir_all(path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probe_distinguishes_ordinal_from_matching_symbol_text() {
|
||||
let mut pe = include_bytes!("../../../fixtures/pe/runtime-services.exe").to_vec();
|
||||
pe[0x720..0x728].copy_from_slice(&((1_u64 << 63) | 42).to_le_bytes());
|
||||
pe[0x762..0x76e].copy_from_slice(b"Ordinal#42\0\0");
|
||||
let path = std::env::temp_dir().join(format!("xenora-probe-ordinal-{}", std::process::id()));
|
||||
run_probe_and_export(&pe, &path, &ProbeConfig::default()).unwrap();
|
||||
let csv = std::fs::read_to_string(path.join("imports.csv")).unwrap();
|
||||
let json = std::fs::read_to_string(path.join("candidate_static_report.json")).unwrap();
|
||||
std::fs::remove_dir_all(path).unwrap();
|
||||
let rows: Vec<_> = csv
|
||||
.lines()
|
||||
.filter(|row| row.contains("Ordinal#42"))
|
||||
.collect();
|
||||
assert_eq!(rows.len(), 2);
|
||||
assert!(rows[0].ends_with(",ordinal"));
|
||||
assert!(rows[1].ends_with(",name"));
|
||||
assert!(json.contains("\"distinct_import_keys\": 3"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trusted_runner_callback_and_report_match_the_fixture() {
|
||||
let pe = include_bytes!("../../../fixtures/pe/trusted-runner.exe");
|
||||
@@ -230,7 +250,7 @@ fn trusted_runner_callback_and_report_match_the_fixture() {
|
||||
assert!(
|
||||
imports
|
||||
.lines()
|
||||
.any(|line| line.contains("fixture_draw") && line.ends_with(",true"))
|
||||
.any(|line| line.contains("fixture_draw") && line.ends_with(",true,name"))
|
||||
);
|
||||
assert!(json.contains("\"trusted_runner_binding_slots\": 1"));
|
||||
assert!(json.contains("\"unresolved_imports\": 1"));
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -120,17 +120,25 @@ fn build(imports: &[(&str, Symbol)]) -> Image {
|
||||
}
|
||||
|
||||
fn standard(clock: u64) -> (ImportRegistry, Arc<MockClock>) {
|
||||
let clock = Arc::new(MockClock::new(clock));
|
||||
let mut registry = ImportRegistry::new();
|
||||
register_standard_services(&mut registry, Arc::new(ServicesState::new(clock.clone())));
|
||||
let (registry, clock, _) = standard_with_state(clock);
|
||||
(registry, clock)
|
||||
}
|
||||
|
||||
fn standard_with_state(clock: u64) -> (ImportRegistry, Arc<MockClock>, Arc<ServicesState>) {
|
||||
let clock = Arc::new(MockClock::new(clock));
|
||||
let state = Arc::new(ServicesState::new(clock.clone()));
|
||||
let mut registry = ImportRegistry::new();
|
||||
register_standard_services(&mut registry, state.clone());
|
||||
(registry, clock, state)
|
||||
}
|
||||
|
||||
/// A guest whose image imports every generated service from its own library.
|
||||
struct Guest {
|
||||
engine: DbtEngine,
|
||||
memory: GuestMemory,
|
||||
clock: Arc<MockClock>,
|
||||
state: Arc<ServicesState>,
|
||||
teb: u64,
|
||||
/// Upper halves and XMM lanes of unrelated arguments hold this pattern.
|
||||
xmm: [u128; 4],
|
||||
}
|
||||
@@ -150,7 +158,7 @@ impl Guest {
|
||||
memory
|
||||
.map_region(STACK, 0x1000, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
let (mut registry, clock) = standard(0x01DA_0000_1234_5678);
|
||||
let (mut registry, clock, state) = standard_with_state(0x01DA_0000_1234_5678);
|
||||
let bound = registry
|
||||
.bind_imports(&pe, &image.bytes, BASE, &mut memory)
|
||||
.unwrap();
|
||||
@@ -161,6 +169,8 @@ impl Guest {
|
||||
engine,
|
||||
memory,
|
||||
clock,
|
||||
state,
|
||||
teb: 0,
|
||||
xmm: [0xAAAA_BBBB_CCCC_DDDD_EEEE_FFFF_0123_4567; 4],
|
||||
}
|
||||
}
|
||||
@@ -171,6 +181,7 @@ impl Guest {
|
||||
.position(|service| service.symbol == symbol)
|
||||
.unwrap();
|
||||
let mut cpu = CpuState::new(BASE + u64::from(CODE_RVA) + 16 * index as u64, STACK_TOP);
|
||||
cpu.gs_base = self.teb;
|
||||
for (index, register) in cpu.gpr.iter_mut().enumerate() {
|
||||
if index != Register::Rsp as usize {
|
||||
*register = 0x0101_0101_0101_0101 * (index as u64 + 1);
|
||||
@@ -323,6 +334,276 @@ fn system_time_comes_from_the_injected_clock() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guest_udp_loopback_delivers_datagrams_through_bound_imports() {
|
||||
let symbols = [
|
||||
"WSAStartup",
|
||||
"socket",
|
||||
"bind",
|
||||
"connect",
|
||||
"send",
|
||||
"recv",
|
||||
"WSAGetLastError",
|
||||
"WSACleanup",
|
||||
"WSAPoll",
|
||||
"getsockname",
|
||||
"getpeername",
|
||||
"getsockopt",
|
||||
"inet_pton",
|
||||
"inet_ntop",
|
||||
"htons",
|
||||
];
|
||||
let imports = symbols.map(|symbol| ("ws2_32.dll", Symbol::Name(symbol)));
|
||||
let image = build(&imports);
|
||||
let pe = ParsedPe::parse(&image.bytes).unwrap();
|
||||
let mut memory = pe.load_into_memory(&image.bytes).unwrap().memory;
|
||||
memory
|
||||
.map_region(SCRATCH, 4096, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region(STACK, 4096, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
let (mut registry, _) = standard(0);
|
||||
assert_eq!(
|
||||
registry
|
||||
.bind_imports(&pe, &image.bytes, BASE, &mut memory)
|
||||
.unwrap(),
|
||||
symbols.len()
|
||||
);
|
||||
let mut engine = DbtEngine::new(256 * 1024).unwrap();
|
||||
engine.set_import_registry(registry);
|
||||
let mut call = |memory: &mut GuestMemory, symbol, args: &[u64]| {
|
||||
let index = symbols.iter().position(|&name| symbol == name).unwrap() as u64;
|
||||
let mut cpu = CpuState::new(BASE + u64::from(CODE_RVA) + 16 * index, STACK_TOP);
|
||||
for (register, &value) in [Register::Rcx, Register::Rdx, Register::R8, Register::R9]
|
||||
.into_iter()
|
||||
.zip(args)
|
||||
{
|
||||
cpu.set(register, value);
|
||||
}
|
||||
if let Some(&fifth) = args.get(4) {
|
||||
memory.write_u64(STACK_TOP + 32, fifth).unwrap();
|
||||
}
|
||||
let result = engine.run(&mut cpu, memory, 8);
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt, "{symbol}");
|
||||
cpu.get(Register::Rax)
|
||||
};
|
||||
let address = SCRATCH + 0x200;
|
||||
let outgoing = SCRATCH + 0x220;
|
||||
let incoming = SCRATCH + 0x240;
|
||||
let text = SCRATCH + 0x260;
|
||||
let poll = SCRATCH + 0x280;
|
||||
let formatted = SCRATCH + 0x2a0;
|
||||
let address_length = SCRATCH + 0x2b0;
|
||||
let peer_address = SCRATCH + 0x2c0;
|
||||
memory.write_u16(address, 2).unwrap();
|
||||
let port = call(&mut memory, "htons", &[5000]);
|
||||
assert_eq!(port, 0x8813);
|
||||
memory.write_bytes(text, b"127.0.0.1\0").unwrap();
|
||||
assert_eq!(call(&mut memory, "inet_pton", &[2, text, address + 4]), 1);
|
||||
assert_eq!(
|
||||
memory.read_u32(address + 4).unwrap().to_le_bytes(),
|
||||
[127, 0, 0, 1]
|
||||
);
|
||||
memory.write_bytes(text, b"127.0.0.999\0").unwrap();
|
||||
assert_eq!(call(&mut memory, "inet_pton", &[2, text, address + 4]), 0);
|
||||
assert_eq!(
|
||||
memory.read_u32(address + 4).unwrap().to_le_bytes(),
|
||||
[127, 0, 0, 1]
|
||||
);
|
||||
assert_eq!(
|
||||
call(&mut memory, "inet_pton", &[23, text, address + 4]),
|
||||
u64::from(u32::MAX)
|
||||
);
|
||||
assert_eq!(call(&mut memory, "WSAGetLastError", &[]), 10047);
|
||||
memory.write_u8(formatted, 0xaa).unwrap();
|
||||
assert_eq!(
|
||||
call(&mut memory, "inet_ntop", &[2, address + 4, formatted, 9]),
|
||||
0
|
||||
);
|
||||
assert_eq!(call(&mut memory, "WSAGetLastError", &[]), 87);
|
||||
assert_eq!(memory.read_u8(formatted).unwrap(), 0xaa);
|
||||
assert_eq!(
|
||||
call(&mut memory, "inet_ntop", &[2, address + 4, formatted, 10]),
|
||||
formatted
|
||||
);
|
||||
let mut formatted_address = [0; 10];
|
||||
memory
|
||||
.read_bytes(formatted, &mut formatted_address)
|
||||
.unwrap();
|
||||
assert_eq!(&formatted_address, b"127.0.0.1\0");
|
||||
assert_eq!(call(&mut memory, "WSAStartup", &[0x0202, SCRATCH]), 0);
|
||||
let receiver = call(&mut memory, "socket", &[2, 2, 17]);
|
||||
let sender = call(&mut memory, "socket", &[2, 2, 17]);
|
||||
assert_ne!(receiver, u64::MAX);
|
||||
assert_ne!(sender, u64::MAX);
|
||||
assert_ne!(sender, receiver);
|
||||
for (option, expected) in [(0x1008, 2), (0x2003, 65_507)] {
|
||||
memory.write_u32(address_length, 8).unwrap();
|
||||
assert_eq!(
|
||||
call(
|
||||
&mut memory,
|
||||
"getsockopt",
|
||||
&[sender, 0xffff, option, incoming, address_length]
|
||||
),
|
||||
0
|
||||
);
|
||||
assert_eq!(memory.read_u32(incoming).unwrap(), expected);
|
||||
assert_eq!(memory.read_u32(address_length).unwrap(), 4);
|
||||
}
|
||||
memory.write_u32(address_length, 3).unwrap();
|
||||
assert_eq!(
|
||||
call(
|
||||
&mut memory,
|
||||
"getsockopt",
|
||||
&[sender, 0xffff, 0x1008, incoming, address_length]
|
||||
),
|
||||
u64::from(u32::MAX)
|
||||
);
|
||||
assert_eq!(call(&mut memory, "WSAGetLastError", &[]), 10014);
|
||||
assert_eq!(memory.read_u32(incoming).unwrap(), 65_507);
|
||||
assert_eq!(call(&mut memory, "bind", &[receiver, address, 16]), 0);
|
||||
memory.write_u32(address_length, 15).unwrap();
|
||||
assert_eq!(
|
||||
call(
|
||||
&mut memory,
|
||||
"getsockname",
|
||||
&[receiver, address, address_length]
|
||||
),
|
||||
u64::from(u32::MAX)
|
||||
);
|
||||
assert_eq!(call(&mut memory, "WSAGetLastError", &[]), 10014);
|
||||
assert_eq!(memory.read_u16(address + 2).unwrap(), 0);
|
||||
memory.write_u32(address_length, 32).unwrap();
|
||||
assert_eq!(
|
||||
call(
|
||||
&mut memory,
|
||||
"getsockname",
|
||||
&[receiver, address, address_length]
|
||||
),
|
||||
0
|
||||
);
|
||||
assert_eq!(memory.read_u32(address_length).unwrap(), 16);
|
||||
assert_eq!(memory.read_u16(address + 2).unwrap().swap_bytes(), 49152);
|
||||
assert_eq!(call(&mut memory, "connect", &[sender, address, 16]), 0);
|
||||
assert_eq!(
|
||||
call(
|
||||
&mut memory,
|
||||
"getpeername",
|
||||
&[sender, peer_address, address_length]
|
||||
),
|
||||
0
|
||||
);
|
||||
assert_eq!(
|
||||
memory.read_u64(peer_address).unwrap(),
|
||||
memory.read_u64(address).unwrap()
|
||||
);
|
||||
memory.write_u64(poll, receiver).unwrap();
|
||||
memory.write_u16(poll + 8, 0x0100).unwrap();
|
||||
memory.write_u64(poll + 16, sender).unwrap();
|
||||
memory.write_u16(poll + 24, 0x0010).unwrap();
|
||||
assert_eq!(call(&mut memory, "WSAPoll", &[poll, 2, 0]), 1);
|
||||
assert_eq!(memory.read_u16(poll + 10).unwrap(), 0);
|
||||
assert_eq!(memory.read_u16(poll + 26).unwrap(), 0x0010);
|
||||
memory.write_bytes(outgoing, b"loop").unwrap();
|
||||
for _ in 0..16 {
|
||||
assert_eq!(call(&mut memory, "send", &[sender, outgoing, 4, 0]), 4);
|
||||
}
|
||||
assert_eq!(
|
||||
call(&mut memory, "send", &[sender, outgoing, 4, 0]),
|
||||
u64::from(u32::MAX)
|
||||
);
|
||||
assert_eq!(call(&mut memory, "WSAGetLastError", &[]), 10055);
|
||||
assert_eq!(call(&mut memory, "WSAPoll", &[poll, 2, 0]), 1);
|
||||
assert_eq!(memory.read_u16(poll + 10).unwrap(), 0x0100);
|
||||
assert_eq!(memory.read_u16(poll + 26).unwrap(), 0);
|
||||
for _ in 0..16 {
|
||||
assert_eq!(call(&mut memory, "recv", &[receiver, incoming, 4, 0]), 4);
|
||||
let mut received = [0; 4];
|
||||
memory.read_bytes(incoming, &mut received).unwrap();
|
||||
assert_eq!(&received, b"loop");
|
||||
memory.write_u32(incoming, 0).unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
call(&mut memory, "recv", &[receiver, incoming, 4, 0]),
|
||||
u64::from(u32::MAX)
|
||||
);
|
||||
assert_eq!(call(&mut memory, "WSAGetLastError", &[]), 10035);
|
||||
assert_eq!(call(&mut memory, "WSAPoll", &[poll, 2, 0]), 1);
|
||||
assert_eq!(memory.read_u16(poll + 10).unwrap(), 0);
|
||||
assert_eq!(memory.read_u16(poll + 26).unwrap(), 0x0010);
|
||||
let started = std::time::Instant::now();
|
||||
assert_eq!(call(&mut memory, "WSAPoll", &[poll, 1, 10]), 0);
|
||||
assert!(started.elapsed() >= std::time::Duration::from_millis(10));
|
||||
assert_eq!(memory.read_u16(poll + 10).unwrap(), 0);
|
||||
assert_eq!(
|
||||
call(&mut memory, "WSAPoll", &[poll, 1, 1001]),
|
||||
u64::from(u32::MAX)
|
||||
);
|
||||
assert_eq!(call(&mut memory, "WSAGetLastError", &[]), 10045);
|
||||
assert_eq!(call(&mut memory, "WSACleanup", &[]), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn last_error_isolated_across_guest_thread_switches() {
|
||||
let mut guest = Guest::new();
|
||||
guest.teb = 0x10000;
|
||||
guest.call("SetLastError", &[123]);
|
||||
guest.teb = 0x20000;
|
||||
assert_eq!(guest.last_error(), 0);
|
||||
assert_eq!(guest.call("CloseHandle", &[123]), 0);
|
||||
assert_eq!(guest.last_error(), 6);
|
||||
guest.teb = 0x10000;
|
||||
guest.call("GetCurrentProcessId", &[]);
|
||||
assert_eq!(guest.last_error(), 123);
|
||||
guest.call("SetLastError", &[0]);
|
||||
assert_eq!(guest.last_error(), 0);
|
||||
guest.teb = 0x20000;
|
||||
assert_eq!(guest.last_error(), 6);
|
||||
}
|
||||
|
||||
/// The last-error code is documented as kept per thread, and most functions
|
||||
/// set it only when they fail (errhandlingapi.h GetLastError).
|
||||
#[test]
|
||||
fn a_successful_call_keeps_another_threads_error_and_its_own() {
|
||||
let mut guest = Guest::new();
|
||||
guest.teb = 0x10000;
|
||||
assert_eq!(guest.call("VirtualAlloc", &[0, 0, 0x3000, 4]), 0);
|
||||
assert_eq!(guest.last_error(), 87); // ERROR_INVALID_PARAMETER
|
||||
guest.teb = 0x20000;
|
||||
guest.call("SetLastError", &[0xFFFF_FFFF]);
|
||||
assert_eq!(guest.call("GetCurrentProcess", &[]), PROCESS);
|
||||
assert_eq!(guest.call("GetCurrentThreadId", &[]), 0x4104);
|
||||
assert_eq!(
|
||||
guest.last_error(),
|
||||
0xFFFF_FFFF,
|
||||
"success keeps a nonzero error"
|
||||
);
|
||||
guest.teb = 0x10000;
|
||||
assert_eq!(guest.last_error(), 87);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_retired_thread_starts_clean_when_its_teb_address_is_reused() {
|
||||
let mut guest = Guest::new();
|
||||
guest.teb = 0x10000;
|
||||
guest.call("SetLastError", &[998]);
|
||||
guest.teb = 0x20000;
|
||||
guest.call("CloseHandle", &[0x1234]);
|
||||
|
||||
assert!(guest.state.retire_thread_last_error(0x10000));
|
||||
assert!(!guest.state.retire_thread_last_error(0x10000));
|
||||
assert!(
|
||||
!guest.state.retire_thread_last_error(0x30000),
|
||||
"a thread that never failed holds no value"
|
||||
);
|
||||
assert_eq!(guest.last_error(), 6, "the other thread is untouched");
|
||||
guest.teb = 0x10000;
|
||||
assert_eq!(guest.last_error(), 0);
|
||||
guest.call("SetLastError", &[5]);
|
||||
assert_eq!(guest.last_error(), 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn last_error_is_set_by_failures_and_by_the_guest() {
|
||||
let mut guest = Guest::new();
|
||||
|
||||
@@ -0,0 +1,982 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Mutexes, critical sections, SRW locks, condition variables, one-time
|
||||
//! initialization, SLists, thread-local storage and the CRT services that call
|
||||
//! guest functions, called by translated guest code through a bound import
|
||||
//! table.
|
||||
//!
|
||||
//! Two guest threads are modelled by switching the TEB address in GS between
|
||||
//! calls. Guest comparators and initializers are original x86-64 routines in
|
||||
//! the image's text section. Expected values come from the public Win32
|
||||
//! synchapi and processthreadsapi documentation, the C standard, the Microsoft
|
||||
//! CRT reference and the x64 layouts in winnt.h, not from the handlers.
|
||||
|
||||
mod support;
|
||||
|
||||
use support::*;
|
||||
use xenora_loader::cpu::ExitReason;
|
||||
|
||||
const KERNEL32: &str = "kernel32.dll";
|
||||
const SYNCH: &str = "api-ms-win-core-synch-l1-1-0.dll";
|
||||
const SYNCH_2: &str = "api-ms-win-core-synch-l1-2-0.dll";
|
||||
const SLIST: &str = "api-ms-win-core-interlocked-l1-1-0.dll";
|
||||
const THREADS: &str = "api-ms-win-core-processthreads-l1-1-0.dll";
|
||||
const FIBERS: &str = "api-ms-win-core-fibers-l1-1-0.dll";
|
||||
|
||||
const IMPORTS: &[(&str, &str)] = &[
|
||||
(KERNEL32, "GetLastError"),
|
||||
(KERNEL32, "SetLastError"),
|
||||
(KERNEL32, "GetCurrentThreadId"),
|
||||
(KERNEL32, "CloseHandle"),
|
||||
(KERNEL32, "DuplicateHandle"),
|
||||
(KERNEL32, "SetEvent"),
|
||||
(KERNEL32, "CreateEventW"),
|
||||
(KERNEL32, "WaitForSingleObject"),
|
||||
(KERNEL32, "WaitForMultipleObjects"),
|
||||
(KERNEL32, "CreateMutexW"),
|
||||
(SYNCH, "CreateMutexExW"),
|
||||
(SYNCH, "ReleaseMutex"),
|
||||
(KERNEL32, "InitializeCriticalSection"),
|
||||
(KERNEL32, "InitializeCriticalSectionAndSpinCount"),
|
||||
(SYNCH, "InitializeCriticalSectionEx"),
|
||||
(KERNEL32, "EnterCriticalSection"),
|
||||
(SYNCH, "TryEnterCriticalSection"),
|
||||
(KERNEL32, "LeaveCriticalSection"),
|
||||
(KERNEL32, "DeleteCriticalSection"),
|
||||
(KERNEL32, "SetCriticalSectionSpinCount"),
|
||||
(SYNCH, "InitializeSRWLock"),
|
||||
(KERNEL32, "AcquireSRWLockExclusive"),
|
||||
(SYNCH, "AcquireSRWLockShared"),
|
||||
(KERNEL32, "TryAcquireSRWLockExclusive"),
|
||||
(KERNEL32, "TryAcquireSRWLockShared"),
|
||||
(KERNEL32, "ReleaseSRWLockExclusive"),
|
||||
(SYNCH, "ReleaseSRWLockShared"),
|
||||
(KERNEL32, "InitializeConditionVariable"),
|
||||
(KERNEL32, "WakeAllConditionVariable"),
|
||||
(SYNCH_2, "WakeConditionVariable"),
|
||||
(KERNEL32, "SleepConditionVariableCS"),
|
||||
(SYNCH_2, "SleepConditionVariableSRW"),
|
||||
(SYNCH_2, "InitOnceInitialize"),
|
||||
(KERNEL32, "InitOnceBeginInitialize"),
|
||||
(SYNCH_2, "InitOnceComplete"),
|
||||
(KERNEL32, "InitializeSListHead"),
|
||||
(SLIST, "InterlockedPushEntrySList"),
|
||||
(KERNEL32, "InterlockedPopEntrySList"),
|
||||
(SLIST, "InterlockedFlushSList"),
|
||||
(SLIST, "QueryDepthSList"),
|
||||
(KERNEL32, "TlsAlloc"),
|
||||
(THREADS, "TlsGetValue"),
|
||||
(THREADS, "TlsSetValue"),
|
||||
(KERNEL32, "TlsFree"),
|
||||
(FIBERS, "FlsAlloc"),
|
||||
(KERNEL32, "FlsGetValue"),
|
||||
(FIBERS, "FlsSetValue"),
|
||||
(FIBERS, "FlsFree"),
|
||||
(SYNCH_2, "InitOnceExecuteOnce"),
|
||||
(UCRT, "qsort"),
|
||||
(CRT_UTILITY, "qsort_s"),
|
||||
(CRT_UTILITY, "bsearch"),
|
||||
(UCRT, "bsearch_s"),
|
||||
(CRT_RUNTIME, "_initterm"),
|
||||
(UCRT, "_initterm_e"),
|
||||
(CRT_RUNTIME, "_initialize_onexit_table"),
|
||||
(UCRT, "_register_onexit_function"),
|
||||
(CRT_RUNTIME, "_execute_onexit_table"),
|
||||
(UCRT, "atexit"),
|
||||
(CRT_RUNTIME, "_crt_atexit"),
|
||||
(CRT_RUNTIME, "_cexit"),
|
||||
];
|
||||
|
||||
const UCRT: &str = "ucrtbase.dll";
|
||||
const CRT_UTILITY: &str = "api-ms-win-crt-utility-l1-1-0.dll";
|
||||
const CRT_RUNTIME: &str = "api-ms-win-crt-runtime-l1-1-0.dll";
|
||||
|
||||
/// Written by the initializer and cleanup routines.
|
||||
const LOG: u64 = SCRATCH + 0xF00;
|
||||
const COUNTER: u64 = SCRATCH + 0xF08;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Routine {
|
||||
/// `int compare(const int *a, const int *b)`: `*a - *b`.
|
||||
Compare,
|
||||
/// `int compare_s(int64_t *calls, const int *a, const int *b)`: counts calls.
|
||||
CompareCounting,
|
||||
/// `void init(void)` appending `n` as a decimal digit of LOG.
|
||||
Append(u8),
|
||||
/// `int init(void)` returning 7 without touching LOG.
|
||||
Fail,
|
||||
/// Clobbers nonvolatile RBX.
|
||||
ClobberRbx,
|
||||
/// `BOOL init(INIT_ONCE *, void *parameter, void **context)`: stores the
|
||||
/// parameter as the context, increments COUNTER and returns TRUE.
|
||||
InitOnceStore,
|
||||
/// `BOOL init(...)` returning FALSE.
|
||||
InitOnceFail,
|
||||
/// `void cleanup(void *value)` adding the value to LOG.
|
||||
FlsAdd,
|
||||
/// `void count(void)` incrementing COUNTER.
|
||||
Count,
|
||||
}
|
||||
|
||||
const ROUTINES: [Routine; 11] = [
|
||||
Routine::Compare,
|
||||
Routine::CompareCounting,
|
||||
Routine::Append(1),
|
||||
Routine::Append(2),
|
||||
Routine::Append(3),
|
||||
Routine::Fail,
|
||||
Routine::ClobberRbx,
|
||||
Routine::InitOnceStore,
|
||||
Routine::InitOnceFail,
|
||||
Routine::FlsAdd,
|
||||
Routine::Count,
|
||||
];
|
||||
|
||||
impl Routine {
|
||||
fn code(self) -> Vec<u8> {
|
||||
let mov_rax = |address: u64| {
|
||||
let mut code = vec![0x48, 0xB8]; // mov rax, imm64
|
||||
code.extend_from_slice(&address.to_le_bytes());
|
||||
code
|
||||
};
|
||||
match self {
|
||||
// mov eax, [rcx]; sub eax, [rdx]; ret
|
||||
Self::Compare => vec![0x8B, 0x01, 0x2B, 0x02, 0xC3],
|
||||
// inc qword [rcx]; mov eax, [rdx]; sub eax, [r8]; ret
|
||||
Self::CompareCounting => vec![0x48, 0xFF, 0x01, 0x8B, 0x02, 0x41, 0x2B, 0x00, 0xC3],
|
||||
Self::Append(digit) => {
|
||||
let mut code = mov_rax(LOG);
|
||||
code.extend_from_slice(&[
|
||||
0x48, 0x8B, 0x08, // mov rcx, [rax]
|
||||
0x48, 0x6B, 0xC9, 0x0A, // imul rcx, rcx, 10
|
||||
0x48, 0x83, 0xC1, digit, // add rcx, digit
|
||||
0x48, 0x89, 0x08, // mov [rax], rcx
|
||||
0x31, 0xC0, // xor eax, eax
|
||||
0xC3,
|
||||
]);
|
||||
code
|
||||
}
|
||||
// mov eax, 7; ret
|
||||
Self::Fail => vec![0xB8, 7, 0, 0, 0, 0xC3],
|
||||
// mov rbx, 1; ret
|
||||
Self::ClobberRbx => vec![0x48, 0xC7, 0xC3, 1, 0, 0, 0, 0xC3],
|
||||
Self::InitOnceStore => {
|
||||
let mut code = mov_rax(COUNTER);
|
||||
code.extend_from_slice(&[
|
||||
0x48, 0xFF, 0x00, // inc qword [rax]
|
||||
0x49, 0x89, 0x10, // mov [r8], rdx
|
||||
0xB8, 1, 0, 0, 0, // mov eax, 1
|
||||
0xC3,
|
||||
]);
|
||||
code
|
||||
}
|
||||
// xor eax, eax; ret
|
||||
Self::InitOnceFail => vec![0x31, 0xC0, 0xC3],
|
||||
Self::FlsAdd => {
|
||||
let mut code = mov_rax(LOG);
|
||||
code.extend_from_slice(&[0x48, 0x01, 0x08, 0xC3]); // add [rax], rcx; ret
|
||||
code
|
||||
}
|
||||
Self::Count => {
|
||||
let mut code = mov_rax(COUNTER);
|
||||
code.extend_from_slice(&[0x48, 0xFF, 0x00, 0xC3]); // inc qword [rax]; ret
|
||||
code
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const COMPARE: usize = 0;
|
||||
const COMPARE_COUNTING: usize = 1;
|
||||
const APPEND_1: usize = 2;
|
||||
const APPEND_2: usize = 3;
|
||||
const APPEND_3: usize = 4;
|
||||
const FAIL: usize = 5;
|
||||
const CLOBBER_RBX: usize = 6;
|
||||
const INIT_ONCE_STORE: usize = 7;
|
||||
const INIT_ONCE_FAIL: usize = 8;
|
||||
const FLS_ADD: usize = 9;
|
||||
const COUNT: usize = 10;
|
||||
|
||||
const WAIT_TIMEOUT: u64 = 258;
|
||||
const ERROR_INVALID_HANDLE: u64 = 6;
|
||||
const ERROR_GEN_FAILURE: u64 = 31;
|
||||
const ERROR_NOT_SUPPORTED: u64 = 50;
|
||||
const ERROR_INVALID_PARAMETER: u64 = 87;
|
||||
const ERROR_NOT_OWNER: u64 = 288;
|
||||
const ERROR_TIMEOUT: u64 = 1460;
|
||||
|
||||
fn new_guest() -> Guest {
|
||||
let routines: Vec<Vec<u8>> = ROUTINES.iter().map(|routine| routine.code()).collect();
|
||||
Guest::new(IMPORTS, &routines)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mutexes_are_recursive_for_their_owner_and_exclusive_across_threads() {
|
||||
let mut guest = new_guest();
|
||||
let mutex = guest.on(THREAD_A).call("CreateMutexW", &[0, 1, 0]);
|
||||
assert_ne!(mutex, 0);
|
||||
|
||||
// A held mutex is not signaled for another thread, but its owner may
|
||||
// acquire it again; each acquisition needs a matching release.
|
||||
assert_eq!(
|
||||
guest.on(THREAD_B).call("WaitForSingleObject", &[mutex, 0]),
|
||||
WAIT_TIMEOUT
|
||||
);
|
||||
assert_eq!(
|
||||
guest.on(THREAD_A).call("WaitForSingleObject", &[mutex, 0]),
|
||||
0
|
||||
);
|
||||
assert_eq!(guest.on(THREAD_B).call("ReleaseMutex", &[mutex]), 0);
|
||||
assert_eq!(guest.error(), ERROR_NOT_OWNER);
|
||||
assert_eq!(guest.on(THREAD_A).call("ReleaseMutex", &[mutex]), 1);
|
||||
assert_eq!(
|
||||
guest.on(THREAD_B).call("WaitForSingleObject", &[mutex, 0]),
|
||||
WAIT_TIMEOUT
|
||||
);
|
||||
assert_eq!(guest.on(THREAD_A).call("ReleaseMutex", &[mutex]), 1);
|
||||
assert_eq!(guest.call("ReleaseMutex", &[mutex]), 0);
|
||||
assert_eq!(guest.error(), ERROR_NOT_OWNER);
|
||||
|
||||
// Once released, the next waiter acquires ownership.
|
||||
assert_eq!(
|
||||
guest.on(THREAD_B).call("WaitForSingleObject", &[mutex, 0]),
|
||||
0
|
||||
);
|
||||
assert_eq!(
|
||||
guest.on(THREAD_A).call("WaitForSingleObject", &[mutex, 0]),
|
||||
WAIT_TIMEOUT
|
||||
);
|
||||
// A wait that would block needs the guest scheduler.
|
||||
assert_eq!(
|
||||
guest.call("WaitForSingleObject", &[mutex, 10]),
|
||||
u64::from(u32::MAX)
|
||||
);
|
||||
assert_eq!(guest.error(), ERROR_NOT_SUPPORTED);
|
||||
|
||||
// A duplicate refers to the same mutex, so it shares ownership.
|
||||
let output = SCRATCH + 0x800;
|
||||
let duplicate = guest.on(THREAD_B).call(
|
||||
"DuplicateHandle",
|
||||
&[u64::MAX, mutex, u64::MAX, output, 0, 0, 2],
|
||||
);
|
||||
assert_eq!(duplicate, 1);
|
||||
let duplicate = guest.u64_at(output);
|
||||
assert_eq!(guest.call("CloseHandle", &[mutex]), 1);
|
||||
assert_eq!(
|
||||
guest
|
||||
.on(THREAD_A)
|
||||
.call("WaitForSingleObject", &[duplicate, 0]),
|
||||
WAIT_TIMEOUT
|
||||
);
|
||||
assert_eq!(guest.on(THREAD_B).call("ReleaseMutex", &[duplicate]), 1);
|
||||
assert_eq!(
|
||||
guest
|
||||
.on(THREAD_A)
|
||||
.call("WaitForSingleObject", &[duplicate, 0]),
|
||||
0
|
||||
);
|
||||
|
||||
// Mutexes are not events.
|
||||
assert_eq!(guest.call("SetEvent", &[duplicate]), 0);
|
||||
assert_eq!(guest.error(), ERROR_INVALID_HANDLE);
|
||||
|
||||
// CREATE_MUTEX_INITIAL_OWNER is the only defined flag.
|
||||
let owned = guest.call("CreateMutexExW", &[0, 0, 1, 0x001f_0001]);
|
||||
assert_ne!(owned, 0);
|
||||
assert_eq!(
|
||||
guest.on(THREAD_B).call("WaitForSingleObject", &[owned, 0]),
|
||||
WAIT_TIMEOUT
|
||||
);
|
||||
assert_eq!(guest.call("CreateMutexExW", &[0, 0, 2, 0x001f_0001]), 0);
|
||||
assert_eq!(guest.error(), ERROR_INVALID_PARAMETER);
|
||||
|
||||
// Wait-all acquires the mutex and consumes the event together, or neither.
|
||||
let event = guest.call("CreateEventW", &[0, 0, 1, 0]);
|
||||
let unowned = guest.call("CreateMutexW", &[0, 0, 0]);
|
||||
let handles = SCRATCH + 0x900;
|
||||
for (index, handle) in [unowned, event, owned].into_iter().enumerate() {
|
||||
guest
|
||||
.memory
|
||||
.write_u64(handles + 8 * index as u64, handle)
|
||||
.unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
guest
|
||||
.on(THREAD_B)
|
||||
.call("WaitForMultipleObjects", &[3, handles, 1, 0]),
|
||||
WAIT_TIMEOUT
|
||||
);
|
||||
assert_eq!(guest.call("WaitForSingleObject", &[event, 0]), 0);
|
||||
assert_eq!(guest.call("SetEvent", &[event]), 1);
|
||||
assert_eq!(
|
||||
guest
|
||||
.on(THREAD_A)
|
||||
.call("WaitForMultipleObjects", &[3, handles, 1, 0]),
|
||||
0
|
||||
);
|
||||
assert_eq!(
|
||||
guest
|
||||
.on(THREAD_B)
|
||||
.call("WaitForSingleObject", &[unowned, 0]),
|
||||
WAIT_TIMEOUT
|
||||
);
|
||||
assert_eq!(guest.call("WaitForSingleObject", &[event, 0]), WAIT_TIMEOUT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn critical_sections_track_owner_and_recursion_in_the_guest_structure() {
|
||||
let mut guest = new_guest();
|
||||
let section = SCRATCH;
|
||||
guest.memory.write_bytes(section, &[0xAA; 48]).unwrap();
|
||||
assert_eq!(guest.call("InitializeCriticalSection", &[section]), 0);
|
||||
// winnt.h RTL_CRITICAL_SECTION: LockCount at 8 is -1 when free,
|
||||
// RecursionCount at 12, OwningThread at 16, SpinCount at 32.
|
||||
assert_eq!(guest.u32_at(section + 8), u32::MAX);
|
||||
assert_eq!(guest.u32_at(section + 12), 0);
|
||||
assert_eq!(guest.u64_at(section + 16), 0);
|
||||
assert_eq!(guest.u64_at(section + 32), 0);
|
||||
assert_eq!(guest.u64_at(section + 40), 0xAAAA_AAAA_AAAA_AAAA);
|
||||
|
||||
let thread_id = guest.on(THREAD_A).call("GetCurrentThreadId", &[]);
|
||||
assert_eq!(guest.call("EnterCriticalSection", &[section]), 0);
|
||||
assert_eq!(guest.call("TryEnterCriticalSection", &[section]), 1);
|
||||
assert_eq!(guest.u32_at(section + 12), 2);
|
||||
assert_eq!(guest.u64_at(section + 16), thread_id);
|
||||
assert_ne!(guest.u32_at(section + 8), u32::MAX);
|
||||
|
||||
assert_eq!(
|
||||
guest
|
||||
.on(THREAD_B)
|
||||
.call("TryEnterCriticalSection", &[section]),
|
||||
0
|
||||
);
|
||||
assert_eq!(
|
||||
guest.fails("EnterCriticalSection", &[section]),
|
||||
RUNTIME_LIMIT
|
||||
);
|
||||
assert_eq!(
|
||||
guest.fails("LeaveCriticalSection", &[section]),
|
||||
RUNTIME_LIMIT
|
||||
);
|
||||
assert_eq!(guest.u32_at(section + 12), 2);
|
||||
|
||||
assert_eq!(
|
||||
guest.on(THREAD_A).call("LeaveCriticalSection", &[section]),
|
||||
0
|
||||
);
|
||||
assert_eq!(guest.u32_at(section + 12), 1);
|
||||
assert_eq!(guest.call("LeaveCriticalSection", &[section]), 0);
|
||||
assert_eq!(guest.u32_at(section + 8), u32::MAX);
|
||||
assert_eq!(guest.u64_at(section + 16), 0);
|
||||
assert_eq!(
|
||||
guest
|
||||
.on(THREAD_B)
|
||||
.call("TryEnterCriticalSection", &[section]),
|
||||
1
|
||||
);
|
||||
assert_eq!(guest.call("LeaveCriticalSection", &[section]), 0);
|
||||
assert_eq!(guest.call("DeleteCriticalSection", &[section]), 0);
|
||||
assert_eq!(
|
||||
guest.fails("EnterCriticalSection", &[section]),
|
||||
RUNTIME_LIMIT
|
||||
);
|
||||
|
||||
let spinning = SCRATCH + 0x40;
|
||||
assert_eq!(
|
||||
guest.call("InitializeCriticalSectionAndSpinCount", &[spinning, 4000]),
|
||||
1
|
||||
);
|
||||
assert_eq!(guest.u64_at(spinning + 32), 4000);
|
||||
assert_eq!(
|
||||
guest.call("SetCriticalSectionSpinCount", &[spinning, 100]),
|
||||
4000
|
||||
);
|
||||
assert_eq!(guest.u64_at(spinning + 32), 100);
|
||||
|
||||
let extended = SCRATCH + 0x80;
|
||||
// CRITICAL_SECTION_NO_DEBUG_INFO is accepted; other flag bits are reserved.
|
||||
assert_eq!(
|
||||
guest.call("InitializeCriticalSectionEx", &[extended, 0, 0x0100_0000]),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
guest.call(
|
||||
"InitializeCriticalSectionEx",
|
||||
&[extended + 0x40, 0, 0x0200_0000]
|
||||
),
|
||||
0
|
||||
);
|
||||
assert_eq!(guest.error(), ERROR_INVALID_PARAMETER);
|
||||
|
||||
// The structure lives in guest memory, so it must be writable.
|
||||
let text = BASE + u64::from(CODE_RVA);
|
||||
assert!(matches!(
|
||||
guest.fails("InitializeCriticalSection", &[text]),
|
||||
ExitReason::MemoryFault(_)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn srw_locks_allow_shared_readers_or_one_writer_and_condition_sleeps_time_out() {
|
||||
let mut guest = new_guest();
|
||||
let lock = SCRATCH;
|
||||
let condition = SCRATCH + 8;
|
||||
let section = SCRATCH + 0x40;
|
||||
guest.memory.write_u64(lock, u64::MAX).unwrap();
|
||||
assert_eq!(guest.call("InitializeSRWLock", &[lock]), 0);
|
||||
assert_eq!(guest.u64_at(lock), 0); // SRWLOCK_INIT
|
||||
|
||||
assert_eq!(guest.on(THREAD_A).call("AcquireSRWLockShared", &[lock]), 0);
|
||||
assert_eq!(
|
||||
guest.on(THREAD_B).call("TryAcquireSRWLockShared", &[lock]) & 0xff,
|
||||
1
|
||||
);
|
||||
assert_eq!(guest.call("TryAcquireSRWLockExclusive", &[lock]) & 0xff, 0);
|
||||
assert_eq!(
|
||||
guest.fails("ReleaseSRWLockExclusive", &[lock]),
|
||||
RUNTIME_LIMIT
|
||||
);
|
||||
assert_eq!(guest.call("ReleaseSRWLockShared", &[lock]), 0);
|
||||
assert_eq!(guest.call("TryAcquireSRWLockExclusive", &[lock]) & 0xff, 0);
|
||||
assert_eq!(guest.on(THREAD_A).call("ReleaseSRWLockShared", &[lock]), 0);
|
||||
|
||||
assert_eq!(
|
||||
guest
|
||||
.on(THREAD_B)
|
||||
.call("TryAcquireSRWLockExclusive", &[lock])
|
||||
& 0xff,
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
guest.on(THREAD_A).call("TryAcquireSRWLockShared", &[lock]) & 0xff,
|
||||
0
|
||||
);
|
||||
assert_eq!(
|
||||
guest.fails("AcquireSRWLockExclusive", &[lock]),
|
||||
RUNTIME_LIMIT
|
||||
);
|
||||
assert_eq!(
|
||||
guest.fails("ReleaseSRWLockExclusive", &[lock]),
|
||||
RUNTIME_LIMIT
|
||||
);
|
||||
// Exclusive SRW locks are not recursive.
|
||||
assert_eq!(
|
||||
guest.on(THREAD_B).fails("AcquireSRWLockExclusive", &[lock]),
|
||||
RUNTIME_LIMIT
|
||||
);
|
||||
|
||||
guest.memory.write_u64(condition, u64::MAX).unwrap();
|
||||
assert_eq!(guest.call("InitializeConditionVariable", &[condition]), 0);
|
||||
assert_eq!(guest.u64_at(condition), 0); // CONDITION_VARIABLE_INIT
|
||||
assert_eq!(guest.call("WakeConditionVariable", &[condition]), 0);
|
||||
assert_eq!(guest.call("WakeAllConditionVariable", &[condition]), 0);
|
||||
|
||||
// A zero-timeout sleep returns FALSE with ERROR_TIMEOUT and still holds
|
||||
// the lock in its original mode.
|
||||
assert_eq!(
|
||||
guest.call("SleepConditionVariableSRW", &[condition, lock, 0, 0]),
|
||||
0
|
||||
);
|
||||
assert_eq!(guest.error(), ERROR_TIMEOUT);
|
||||
assert_eq!(
|
||||
guest.on(THREAD_A).call("TryAcquireSRWLockShared", &[lock]) & 0xff,
|
||||
0
|
||||
);
|
||||
assert_eq!(
|
||||
guest
|
||||
.on(THREAD_B)
|
||||
.call("SleepConditionVariableSRW", &[condition, lock, 10, 0]),
|
||||
0
|
||||
);
|
||||
assert_eq!(guest.error(), ERROR_NOT_SUPPORTED);
|
||||
assert_eq!(
|
||||
guest.call("SleepConditionVariableSRW", &[condition, lock, 0, 2]),
|
||||
0
|
||||
);
|
||||
assert_eq!(guest.error(), ERROR_INVALID_PARAMETER);
|
||||
// Shared mode does not match the exclusive hold; the caller must own the lock.
|
||||
assert_eq!(
|
||||
guest.fails("SleepConditionVariableSRW", &[condition, lock, 0, 1]),
|
||||
RUNTIME_LIMIT
|
||||
);
|
||||
assert_eq!(guest.call("ReleaseSRWLockExclusive", &[lock]), 0);
|
||||
assert_eq!(
|
||||
guest.fails("SleepConditionVariableSRW", &[condition, lock, 0, 0]),
|
||||
RUNTIME_LIMIT
|
||||
);
|
||||
|
||||
assert_eq!(guest.call("InitializeCriticalSection", &[section]), 0);
|
||||
assert_eq!(
|
||||
guest.fails("SleepConditionVariableCS", &[condition, section, 0]),
|
||||
RUNTIME_LIMIT
|
||||
);
|
||||
assert_eq!(guest.call("EnterCriticalSection", &[section]), 0);
|
||||
assert_eq!(guest.call("EnterCriticalSection", &[section]), 0);
|
||||
assert_eq!(
|
||||
guest.call("SleepConditionVariableCS", &[condition, section, 0]),
|
||||
0
|
||||
);
|
||||
assert_eq!(guest.error(), ERROR_TIMEOUT);
|
||||
assert_eq!(guest.u32_at(section + 12), 2);
|
||||
assert_eq!(
|
||||
guest
|
||||
.on(THREAD_A)
|
||||
.call("TryEnterCriticalSection", &[section]),
|
||||
0
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn init_once_runs_one_initializer_and_publishes_its_context() {
|
||||
let mut guest = new_guest();
|
||||
let once = SCRATCH;
|
||||
let pending = SCRATCH + 0x10;
|
||||
let context = SCRATCH + 0x18;
|
||||
let begin = |guest: &mut Guest, flags: u64| {
|
||||
guest.memory.write_u64(pending, u64::MAX).unwrap();
|
||||
guest.memory.write_u64(context, u64::MAX).unwrap();
|
||||
guest.call("InitOnceBeginInitialize", &[once, flags, pending, context])
|
||||
};
|
||||
guest.memory.write_u64(once, u64::MAX).unwrap();
|
||||
assert_eq!(guest.call("InitOnceInitialize", &[once]), 0);
|
||||
assert_eq!(guest.u64_at(once), 0); // INIT_ONCE_STATIC_INIT
|
||||
|
||||
// INIT_ONCE_CHECK_ONLY reports incomplete initialization as a failure.
|
||||
assert_eq!(begin(&mut guest, 1), 0);
|
||||
assert_eq!(guest.error(), ERROR_GEN_FAILURE);
|
||||
assert_eq!(guest.u64_at(pending), u64::MAX);
|
||||
|
||||
assert_eq!(begin(&mut guest, 0), 1);
|
||||
// fPending is a 4-byte BOOL.
|
||||
assert_eq!(guest.u64_at(pending), 0xffff_ffff_0000_0001);
|
||||
assert_eq!(begin(&mut guest, 1), 0);
|
||||
|
||||
// Context values must leave INIT_ONCE_CTX_RESERVED_BITS (2) clear.
|
||||
assert_eq!(guest.call("InitOnceComplete", &[once, 0, 0x1003]), 0);
|
||||
assert_eq!(guest.error(), ERROR_INVALID_PARAMETER);
|
||||
// Only the thread that began initialization may complete it.
|
||||
assert_eq!(
|
||||
guest
|
||||
.on(THREAD_B)
|
||||
.call("InitOnceComplete", &[once, 0, 0x1000]),
|
||||
0
|
||||
);
|
||||
assert_eq!(guest.error(), ERROR_GEN_FAILURE);
|
||||
assert_eq!(
|
||||
guest
|
||||
.on(THREAD_A)
|
||||
.call("InitOnceComplete", &[once, 0, 0x1000]),
|
||||
1
|
||||
);
|
||||
|
||||
for flags in [0, 1] {
|
||||
assert_eq!(begin(guest.on(THREAD_B), flags), 1);
|
||||
assert_eq!(guest.u64_at(pending), 0xffff_ffff_0000_0000);
|
||||
assert_eq!(guest.u64_at(context), 0x1000);
|
||||
}
|
||||
assert_eq!(guest.call("InitOnceComplete", &[once, 0, 0x1000]), 0);
|
||||
assert_eq!(guest.error(), ERROR_GEN_FAILURE);
|
||||
|
||||
// INIT_ONCE_INIT_FAILED returns the object to its initial state.
|
||||
let retry = SCRATCH + 0x40;
|
||||
assert_eq!(
|
||||
guest.call("InitOnceBeginInitialize", &[retry, 0, pending, 0]),
|
||||
1
|
||||
);
|
||||
assert_eq!(guest.call("InitOnceComplete", &[retry, 4, 8]), 0);
|
||||
assert_eq!(guest.error(), ERROR_INVALID_PARAMETER);
|
||||
assert_eq!(guest.call("InitOnceComplete", &[retry, 4, 0]), 1);
|
||||
assert_eq!(
|
||||
guest.call("InitOnceBeginInitialize", &[retry, 0, pending, 0]),
|
||||
1
|
||||
);
|
||||
assert_eq!(guest.u32_at(pending), 1);
|
||||
|
||||
// A second thread would have to wait for the pending initializer.
|
||||
assert_eq!(
|
||||
guest
|
||||
.on(THREAD_A)
|
||||
.fails("InitOnceBeginInitialize", &[retry, 0, pending, 0]),
|
||||
RUNTIME_LIMIT
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
guest.call("InitOnceBeginInitialize", &[once, 2, pending, 0]),
|
||||
0
|
||||
);
|
||||
assert_eq!(guest.error(), ERROR_NOT_SUPPORTED);
|
||||
assert_eq!(guest.call("InitOnceBeginInitialize", &[once, 0, 0, 0]), 0);
|
||||
assert_eq!(guest.error(), ERROR_INVALID_PARAMETER);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slists_push_and_pop_in_lifo_order_using_the_x64_header_layout() {
|
||||
let mut guest = new_guest();
|
||||
let header = SCRATCH;
|
||||
let (first, second) = (SCRATCH + 0x100, SCRATCH + 0x200);
|
||||
guest.memory.write_bytes(header, &[0xCC; 16]).unwrap();
|
||||
assert_eq!(guest.call("InitializeSListHead", &[header]), 0);
|
||||
assert_eq!((guest.u64_at(header), guest.u64_at(header + 8)), (0, 0));
|
||||
assert_eq!(guest.call("QueryDepthSList", &[header]), 0);
|
||||
|
||||
assert_eq!(guest.call("InterlockedPushEntrySList", &[header, first]), 0);
|
||||
assert_eq!(
|
||||
guest.call("InterlockedPushEntrySList", &[header, second]),
|
||||
first
|
||||
);
|
||||
assert_eq!(guest.call("QueryDepthSList", &[header]), 2);
|
||||
// Depth is the low 16 bits; NextEntry holds the first entry's address
|
||||
// shifted right by four in bits 4..63 of the second quadword.
|
||||
assert_eq!(guest.u64_at(header) & 0xffff, 2);
|
||||
assert_eq!(guest.u64_at(header + 8), second);
|
||||
assert_eq!(guest.u64_at(second), first);
|
||||
assert_eq!(guest.u64_at(first), 0);
|
||||
|
||||
assert_eq!(guest.call("InterlockedPopEntrySList", &[header]), second);
|
||||
assert_eq!(guest.call("QueryDepthSList", &[header]), 1);
|
||||
assert_eq!(
|
||||
guest.call("InterlockedPushEntrySList", &[header, second]),
|
||||
first
|
||||
);
|
||||
assert_eq!(guest.call("InterlockedFlushSList", &[header]), second);
|
||||
assert_eq!(guest.call("QueryDepthSList", &[header]), 0);
|
||||
assert_eq!(guest.call("InterlockedPopEntrySList", &[header]), 0);
|
||||
|
||||
// Entries and headers require MEMORY_ALLOCATION_ALIGNMENT (16 bytes).
|
||||
assert_eq!(
|
||||
guest.fails("InterlockedPushEntrySList", &[header, first + 8]),
|
||||
RUNTIME_LIMIT
|
||||
);
|
||||
assert_eq!(guest.fails("QueryDepthSList", &[header + 8]), RUNTIME_LIMIT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tls_and_fls_values_are_per_thread_and_cleared_on_reallocation() {
|
||||
let mut guest = new_guest();
|
||||
let index = guest.call("TlsAlloc", &[]);
|
||||
assert!(index < 1088, "{index}");
|
||||
guest.call("SetLastError", &[5]);
|
||||
// TlsGetValue clears the last error on success so zero is unambiguous.
|
||||
assert_eq!(guest.call("TlsGetValue", &[index]), 0);
|
||||
assert_eq!(guest.error(), 0);
|
||||
assert_eq!(guest.on(THREAD_A).call("TlsSetValue", &[index, 0xABC0]), 1);
|
||||
assert_eq!(guest.on(THREAD_B).call("TlsGetValue", &[index]), 0);
|
||||
assert_eq!(guest.call("TlsSetValue", &[index, 0xDEF0]), 1);
|
||||
assert_eq!(guest.on(THREAD_A).call("TlsGetValue", &[index]), 0xABC0);
|
||||
assert_eq!(guest.on(THREAD_B).call("TlsGetValue", &[index]), 0xDEF0);
|
||||
|
||||
assert_eq!(guest.call("TlsFree", &[index]), 1);
|
||||
assert_eq!(guest.call("TlsGetValue", &[index]), 0);
|
||||
assert_eq!(guest.error(), ERROR_INVALID_PARAMETER);
|
||||
assert_eq!(guest.call("TlsFree", &[index]), 0);
|
||||
assert_eq!(guest.error(), ERROR_INVALID_PARAMETER);
|
||||
// A newly allocated index reads as zero in every thread.
|
||||
let again = guest.call("TlsAlloc", &[]);
|
||||
assert_eq!(guest.on(THREAD_A).call("TlsGetValue", &[again]), 0);
|
||||
assert_eq!(guest.on(THREAD_B).call("TlsGetValue", &[again]), 0);
|
||||
|
||||
// The documented process limit is 1,088 TLS indexes.
|
||||
let mut allocated = 1;
|
||||
while guest.call("TlsAlloc", &[]) != u64::from(u32::MAX) {
|
||||
allocated += 1;
|
||||
assert!(allocated <= 1088);
|
||||
}
|
||||
assert_eq!(allocated, 1088);
|
||||
|
||||
let plain = guest.call("FlsAlloc", &[0]);
|
||||
assert_ne!(plain, u64::from(u32::MAX));
|
||||
assert_eq!(guest.call("FlsSetValue", &[plain, 7]), 1);
|
||||
assert_eq!(guest.on(THREAD_A).call("FlsGetValue", &[plain]), 0);
|
||||
assert_eq!(guest.on(THREAD_B).call("FlsGetValue", &[plain]), 7);
|
||||
assert_eq!(guest.call("FlsFree", &[plain]), 1);
|
||||
assert_eq!(guest.call("FlsGetValue", &[plain]), 0);
|
||||
assert_eq!(guest.error(), ERROR_INVALID_PARAMETER);
|
||||
|
||||
// FlsFree runs the slot's callback once for each nonnull value.
|
||||
let with_callback = guest.call("FlsAlloc", &[routine(FLS_ADD)]);
|
||||
assert_eq!(
|
||||
guest.on(THREAD_A).call("FlsSetValue", &[with_callback, 5]),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
guest.on(THREAD_B).call("FlsSetValue", &[with_callback, 30]),
|
||||
1
|
||||
);
|
||||
let unset = guest.call("FlsAlloc", &[routine(FLS_ADD)]);
|
||||
guest.memory.write_u64(LOG, 0).unwrap();
|
||||
assert_eq!(guest.call("FlsFree", &[with_callback]), 1);
|
||||
assert_eq!(guest.u64_at(LOG), 35);
|
||||
assert_eq!(guest.call("FlsGetValue", &[with_callback]), 0);
|
||||
assert_eq!(guest.error(), ERROR_INVALID_PARAMETER);
|
||||
assert_eq!(guest.call("FlsFree", &[unset]), 1);
|
||||
assert_eq!(guest.u64_at(LOG), 35);
|
||||
}
|
||||
|
||||
fn write_i32s(guest: &mut Guest, address: u64, values: &[i32]) {
|
||||
for (index, value) in values.iter().enumerate() {
|
||||
guest
|
||||
.memory
|
||||
.write_u32(address + 4 * index as u64, *value as u32)
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn read_i32s(guest: &Guest, address: u64, count: usize) -> Vec<i32> {
|
||||
(0..count)
|
||||
.map(|index| guest.u32_at(address + 4 * index as u64) as i32)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qsort_orders_elements_with_a_guest_comparator() {
|
||||
let mut guest = new_guest();
|
||||
let array = SCRATCH + 0x100;
|
||||
let input = [5, -3, 9, 0, 5, 2, -8, 7, 1, 4, -1];
|
||||
write_i32s(&mut guest, array, &input);
|
||||
let mut expected = input;
|
||||
expected.sort();
|
||||
let count = input.len() as u64;
|
||||
assert_eq!(guest.call("qsort", &[array, count, 4, routine(COMPARE)]), 0);
|
||||
assert_eq!(read_i32s(&guest, array, input.len()), expected);
|
||||
|
||||
// Eight-byte records keyed by their first int: the records move intact.
|
||||
let records = SCRATCH + 0x200;
|
||||
let keyed = [(3, 30), (1, 10), (2, 20), (0, 0)];
|
||||
for (index, (key, tag)) in keyed.iter().enumerate() {
|
||||
write_i32s(&mut guest, records + 8 * index as u64, &[*key, *tag]);
|
||||
}
|
||||
assert_eq!(guest.call("qsort", &[records, 4, 8, routine(COMPARE)]), 0);
|
||||
assert_eq!(read_i32s(&guest, records, 8), [0, 0, 1, 10, 2, 20, 3, 30]);
|
||||
|
||||
// qsort_s passes its context as the comparator's first argument.
|
||||
write_i32s(&mut guest, array, &input);
|
||||
guest.memory.write_u64(COUNTER, 0).unwrap();
|
||||
assert_eq!(
|
||||
guest.call(
|
||||
"qsort_s",
|
||||
&[array, count, 4, routine(COMPARE_COUNTING), COUNTER]
|
||||
),
|
||||
0
|
||||
);
|
||||
assert_eq!(read_i32s(&guest, array, input.len()), expected);
|
||||
// Any comparison sort of n distinct-enough keys needs at least n - 1 calls.
|
||||
let calls = guest.u64_at(COUNTER);
|
||||
assert!(calls >= count - 1 && calls <= count * count, "{calls}");
|
||||
|
||||
// Fewer than two elements need no comparison.
|
||||
guest.memory.write_u64(COUNTER, 0).unwrap();
|
||||
assert_eq!(
|
||||
guest.call(
|
||||
"qsort_s",
|
||||
&[array, 1, 4, routine(COMPARE_COUNTING), COUNTER]
|
||||
),
|
||||
0
|
||||
);
|
||||
assert_eq!(guest.u64_at(COUNTER), 0);
|
||||
// A read-only array cannot be sorted in place.
|
||||
let text = BASE + u64::from(CODE_RVA);
|
||||
assert!(matches!(
|
||||
guest.fails("qsort", &[text, 4, 4, routine(COMPARE)]),
|
||||
ExitReason::MemoryFault(_)
|
||||
));
|
||||
assert_eq!(guest.fails("qsort", &[array, 4, 4, 0]), RUNTIME_LIMIT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bsearch_returns_the_matching_element_or_null() {
|
||||
let mut guest = new_guest();
|
||||
let array = SCRATCH + 0x100;
|
||||
let key = SCRATCH + 0x80;
|
||||
let sorted = [-8, -3, 0, 2, 5, 9, 14];
|
||||
write_i32s(&mut guest, array, &sorted);
|
||||
let count = sorted.len() as u64;
|
||||
for (index, value) in sorted.iter().enumerate() {
|
||||
write_i32s(&mut guest, key, &[*value]);
|
||||
assert_eq!(
|
||||
guest.call("bsearch", &[key, array, count, 4, routine(COMPARE)]),
|
||||
array + 4 * index as u64
|
||||
);
|
||||
}
|
||||
for missing in [-9, 1, 15] {
|
||||
write_i32s(&mut guest, key, &[missing]);
|
||||
assert_eq!(
|
||||
guest.call("bsearch", &[key, array, count, 4, routine(COMPARE)]),
|
||||
0
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
guest.call("bsearch", &[key, array, 0, 4, routine(COMPARE)]),
|
||||
0
|
||||
);
|
||||
|
||||
write_i32s(&mut guest, key, &[14]);
|
||||
guest.memory.write_u64(COUNTER, 0).unwrap();
|
||||
assert_eq!(
|
||||
guest.call(
|
||||
"bsearch_s",
|
||||
&[key, array, count, 4, routine(COMPARE_COUNTING), COUNTER]
|
||||
),
|
||||
array + 24
|
||||
);
|
||||
// A binary search of seven elements needs at most three comparisons.
|
||||
let calls = guest.u64_at(COUNTER);
|
||||
assert!((1..=3).contains(&calls), "{calls}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn initializer_tables_run_in_order_and_stop_on_failure() {
|
||||
let mut guest = new_guest();
|
||||
let table = SCRATCH + 0x300;
|
||||
let write_table = |guest: &mut Guest, entries: &[u64]| {
|
||||
for (index, entry) in entries.iter().enumerate() {
|
||||
guest
|
||||
.memory
|
||||
.write_u64(table + 8 * index as u64, *entry)
|
||||
.unwrap();
|
||||
}
|
||||
table + 8 * entries.len() as u64
|
||||
};
|
||||
|
||||
// Null entries are skipped.
|
||||
let end = write_table(
|
||||
&mut guest,
|
||||
&[routine(APPEND_1), 0, routine(APPEND_2), routine(APPEND_3)],
|
||||
);
|
||||
guest.memory.write_u64(LOG, 0).unwrap();
|
||||
assert_eq!(guest.call("_initterm", &[table, end]), 0);
|
||||
assert_eq!(guest.u64_at(LOG), 123);
|
||||
assert_eq!(guest.call("_initterm", &[table, table]), 0);
|
||||
assert_eq!(guest.u64_at(LOG), 123);
|
||||
|
||||
// _initterm_e returns the first nonzero result and runs nothing after it.
|
||||
let end = write_table(
|
||||
&mut guest,
|
||||
&[routine(APPEND_2), routine(FAIL), routine(APPEND_3)],
|
||||
);
|
||||
guest.memory.write_u64(LOG, 0).unwrap();
|
||||
assert_eq!(guest.call("_initterm_e", &[table, end]), 7);
|
||||
assert_eq!(guest.u64_at(LOG), 2);
|
||||
let end = write_table(&mut guest, &[routine(APPEND_3), routine(APPEND_1)]);
|
||||
guest.memory.write_u64(LOG, 0).unwrap();
|
||||
assert_eq!(guest.call("_initterm_e", &[table, end]), 0);
|
||||
assert_eq!(guest.u64_at(LOG), 31);
|
||||
|
||||
// An initializer that does not preserve RBX breaks the Win64 contract.
|
||||
let end = write_table(&mut guest, &[routine(CLOBBER_RBX)]);
|
||||
assert_eq!(
|
||||
guest.fails("_initterm", &[table, end]),
|
||||
ExitReason::ServiceAbiViolation
|
||||
);
|
||||
// Reversed and misaligned tables are rejected.
|
||||
assert_eq!(guest.fails("_initterm", &[end, table]), RUNTIME_LIMIT);
|
||||
assert_eq!(guest.fails("_initterm", &[table, table + 4]), RUNTIME_LIMIT);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn init_once_execute_once_runs_the_initializer_exactly_once() {
|
||||
let mut guest = new_guest();
|
||||
let once = SCRATCH;
|
||||
let context = SCRATCH + 0x10;
|
||||
guest.memory.write_u64(COUNTER, 0).unwrap();
|
||||
let execute = |guest: &mut Guest, once: u64, initializer: usize, parameter: u64| {
|
||||
guest.call(
|
||||
"InitOnceExecuteOnce",
|
||||
&[once, routine(initializer), parameter, context],
|
||||
)
|
||||
};
|
||||
assert_eq!(execute(&mut guest, once, INIT_ONCE_STORE, 0x5000), 1);
|
||||
assert_eq!(guest.u64_at(context), 0x5000);
|
||||
assert_eq!(guest.u64_at(COUNTER), 1);
|
||||
guest.memory.write_u64(context, 0).unwrap();
|
||||
assert_eq!(
|
||||
execute(guest.on(THREAD_B), once, INIT_ONCE_STORE, 0x6000),
|
||||
1
|
||||
);
|
||||
assert_eq!(guest.u64_at(context), 0x5000);
|
||||
assert_eq!(guest.u64_at(COUNTER), 1);
|
||||
|
||||
// The completed context is visible through InitOnceBeginInitialize.
|
||||
let pending = SCRATCH + 0x18;
|
||||
assert_eq!(
|
||||
guest.call("InitOnceBeginInitialize", &[once, 1, pending, context]),
|
||||
1
|
||||
);
|
||||
assert_eq!(guest.u32_at(pending), 0);
|
||||
|
||||
// A failed initializer leaves the object uninitialized for a retry.
|
||||
let retry = SCRATCH + 0x40;
|
||||
assert_eq!(execute(&mut guest, retry, INIT_ONCE_FAIL, 0), 0);
|
||||
assert_eq!(guest.u64_at(retry), 0);
|
||||
assert_eq!(execute(&mut guest, retry, INIT_ONCE_STORE, 0x7000), 1);
|
||||
assert_eq!(guest.u64_at(context), 0x7000);
|
||||
assert_eq!(guest.u64_at(COUNTER), 2);
|
||||
|
||||
// A context using the reserved low bits cannot be stored.
|
||||
let reserved = SCRATCH + 0x60;
|
||||
assert_eq!(execute(&mut guest, reserved, INIT_ONCE_STORE, 0x7001), 0);
|
||||
assert_eq!(guest.error(), ERROR_INVALID_PARAMETER);
|
||||
assert_eq!(guest.u64_at(reserved), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn onexit_tables_run_registered_functions_in_reverse_order() {
|
||||
let mut guest = new_guest();
|
||||
let table = SCRATCH + 0x400;
|
||||
let pointers = |guest: &Guest| [0, 8, 16].map(|offset| guest.u64_at(table + offset));
|
||||
let status = |value: u64| value as u32;
|
||||
assert_eq!(guest.call("_initialize_onexit_table", &[table]), 0);
|
||||
assert_eq!(pointers(&guest), [0; 3]);
|
||||
assert_eq!(
|
||||
status(guest.call("_initialize_onexit_table", &[0])),
|
||||
u32::MAX
|
||||
);
|
||||
assert_eq!(
|
||||
status(guest.call("_register_onexit_function", &[0, routine(APPEND_1)])),
|
||||
u32::MAX
|
||||
);
|
||||
|
||||
for digit in [APPEND_1, APPEND_2, APPEND_3] {
|
||||
assert_eq!(
|
||||
guest.call("_register_onexit_function", &[table, routine(digit)]),
|
||||
0
|
||||
);
|
||||
}
|
||||
let [first, last, end] = pointers(&guest);
|
||||
assert_ne!(first, 0);
|
||||
assert_eq!(last - first, 24);
|
||||
assert!(end >= last);
|
||||
// Reinitializing a table keeps its registrations.
|
||||
assert_eq!(guest.call("_initialize_onexit_table", &[table]), 0);
|
||||
assert_eq!(pointers(&guest), [first, last, end]);
|
||||
|
||||
guest.memory.write_u64(LOG, 0).unwrap();
|
||||
assert_eq!(guest.call("_execute_onexit_table", &[table]), 0);
|
||||
assert_eq!(guest.u64_at(LOG), 321);
|
||||
assert_eq!(pointers(&guest), [0; 3]);
|
||||
assert_eq!(guest.call("_execute_onexit_table", &[table]), 0);
|
||||
assert_eq!(guest.u64_at(LOG), 321);
|
||||
|
||||
// The table grows past its initial storage.
|
||||
for _ in 0..100 {
|
||||
assert_eq!(
|
||||
guest.call("_register_onexit_function", &[table, routine(COUNT)]),
|
||||
0
|
||||
);
|
||||
}
|
||||
let [first, last, _] = pointers(&guest);
|
||||
assert_eq!(last - first, 800);
|
||||
guest.memory.write_u64(COUNTER, 0).unwrap();
|
||||
assert_eq!(guest.call("_execute_onexit_table", &[table]), 0);
|
||||
assert_eq!(guest.u64_at(COUNTER), 100);
|
||||
|
||||
// atexit functions run in reverse order when the CRT is shut down.
|
||||
assert_eq!(guest.call("atexit", &[routine(APPEND_1)]), 0);
|
||||
assert_eq!(guest.call("_crt_atexit", &[routine(APPEND_2)]), 0);
|
||||
assert_eq!(status(guest.call("atexit", &[0])), u32::MAX);
|
||||
guest.memory.write_u64(LOG, 0).unwrap();
|
||||
assert_eq!(guest.call("_cexit", &[]), 0);
|
||||
assert_eq!(guest.u64_at(LOG), 21);
|
||||
assert_eq!(guest.call("_cexit", &[]), 0);
|
||||
assert_eq!(guest.u64_at(LOG), 21);
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! System information, calendar conversion and sleeping through the guest
|
||||
//! import table.
|
||||
//!
|
||||
//! Layouts and constants come from the public `SYSTEM_INFO`, `MEMORYSTATUSEX`
|
||||
//! and `SYSTEMTIME` documentation and winnt.h. Calendar expectations come from
|
||||
//! the FILETIME epoch (1601-01-01 UTC) and dates computed independently with
|
||||
//! the host `date` utility, not from the conversion code.
|
||||
|
||||
mod support;
|
||||
|
||||
use std::sync::Arc;
|
||||
use support::*;
|
||||
use xenora_loader::services::sysinfo::{GuestSystemProfile, HostCapabilities};
|
||||
use xenora_loader::services::{MockClock, ServicesState};
|
||||
|
||||
const KERNEL32: &str = "kernel32.dll";
|
||||
const SYSINFO: &str = "api-ms-win-core-sysinfo-l1-1-0.dll";
|
||||
|
||||
const IMPORTS: &[(&str, &str)] = &[
|
||||
(KERNEL32, "GetLastError"),
|
||||
(SYSINFO, "GetSystemInfo"),
|
||||
("api-ms-win-core-sysinfo-l1-2-0.dll", "GetNativeSystemInfo"),
|
||||
(SYSINFO, "GlobalMemoryStatusEx"),
|
||||
(SYSINFO, "GetSystemTime"),
|
||||
(KERNEL32, "GetLocalTime"),
|
||||
(KERNEL32, "GetSystemTimeAsFileTime"),
|
||||
(
|
||||
"api-ms-win-core-sysinfo-l1-2-0.dll",
|
||||
"GetSystemTimePreciseAsFileTime",
|
||||
),
|
||||
(
|
||||
"api-ms-win-core-timezone-l1-1-0.dll",
|
||||
"FileTimeToSystemTime",
|
||||
),
|
||||
(KERNEL32, "SystemTimeToFileTime"),
|
||||
(
|
||||
"api-ms-win-core-realtime-l1-1-0.dll",
|
||||
"QueryUnbiasedInterruptTime",
|
||||
),
|
||||
("api-ms-win-core-synch-l1-2-0.dll", "Sleep"),
|
||||
(KERNEL32, "SleepEx"),
|
||||
(KERNEL32, "GetTickCount64"),
|
||||
(KERNEL32, "VirtualAlloc"),
|
||||
(KERNEL32, "GetProcessHeap"),
|
||||
(KERNEL32, "HeapAlloc"),
|
||||
];
|
||||
|
||||
const ERROR_INVALID_PARAMETER: u64 = 87;
|
||||
const UNIX_EPOCH_FILETIME: u64 = 116_444_736_000_000_000;
|
||||
const TICKS_PER_SECOND: u64 = 10_000_000;
|
||||
/// `date -u -j -f "%Y-%m-%d %H:%M:%S" "2026-11-24 12:34:56" +%s`, a Tuesday.
|
||||
const NOV_24_2026: u64 = 1_795_523_696;
|
||||
/// `date -u -j -f "%Y-%m-%d %H:%M:%S" "2024-02-29 23:59:59" +%s`, a Thursday.
|
||||
const FEB_29_2024: u64 = 1_709_251_199;
|
||||
|
||||
fn filetime(unix_seconds: u64, millis: u64) -> u64 {
|
||||
UNIX_EPOCH_FILETIME + unix_seconds * TICKS_PER_SECOND + millis * 10_000
|
||||
}
|
||||
|
||||
/// SYSTEMTIME fields: year, month, day of week, day, hour, minute, second, ms.
|
||||
fn system_time(guest: &Guest, address: u64) -> [u16; 8] {
|
||||
std::array::from_fn(|index| guest.u16_at(address + 2 * index as u64))
|
||||
}
|
||||
|
||||
fn write_system_time(guest: &mut Guest, address: u64, fields: [u16; 8]) {
|
||||
for (index, field) in fields.into_iter().enumerate() {
|
||||
guest
|
||||
.memory
|
||||
.write_u16(address + 2 * index as u64, field)
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn system_info_reports_the_simulated_guest_machine() {
|
||||
let mut guest = Guest::new(IMPORTS, &[]);
|
||||
let info = SCRATCH;
|
||||
for symbol in ["GetSystemInfo", "GetNativeSystemInfo"] {
|
||||
guest.memory.write_bytes(info, &[0xAA; 56]).unwrap();
|
||||
assert_eq!(guest.call(symbol, &[info]), 0);
|
||||
assert_eq!(guest.u16_at(info), 9); // PROCESSOR_ARCHITECTURE_AMD64
|
||||
assert_eq!(guest.u32_at(info + 4), 4096); // dwPageSize
|
||||
assert_eq!(guest.u64_at(info + 8), 0x1_0000);
|
||||
assert_eq!(guest.u64_at(info + 16), 0x7fff_fffe_ffff);
|
||||
assert_eq!(guest.u64_at(info + 24), 1); // dwActiveProcessorMask
|
||||
assert_eq!(guest.u32_at(info + 32), 1); // dwNumberOfProcessors
|
||||
assert_eq!(guest.u32_at(info + 36), 8664); // PROCESSOR_AMD_X8664
|
||||
assert_eq!(guest.u32_at(info + 40), 65_536); // dwAllocationGranularity
|
||||
assert_eq!(guest.u32_at(info + 44), 0); // no simulated CPU model
|
||||
assert_eq!(guest.u64_at(info + 48), 0xAAAA_AAAA_AAAA_AAAA);
|
||||
}
|
||||
|
||||
let mut state = ServicesState::new(Arc::new(MockClock::new(0)));
|
||||
state.guest_profile = GuestSystemProfile { processors: 4 };
|
||||
let mut guest = Guest::with_state(IMPORTS, &[], state);
|
||||
assert_eq!(guest.call("GetSystemInfo", &[info]), 0);
|
||||
assert_eq!(guest.u64_at(info + 24), 0b1111);
|
||||
assert_eq!(guest.u32_at(info + 32), 4);
|
||||
|
||||
// The guest page size does not follow the host's.
|
||||
let host = HostCapabilities::detect();
|
||||
assert!(host.page_size.is_some() && host.logical_processors.is_some());
|
||||
assert_eq!(guest.u32_at(info + 4), 4096);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memory_status_tracks_guest_allocations_against_the_budget() {
|
||||
let mut guest = Guest::new(IMPORTS, &[]);
|
||||
let status = SCRATCH;
|
||||
// dwLength must hold sizeof(MEMORYSTATUSEX).
|
||||
guest.memory.write_u32(status, 0).unwrap();
|
||||
assert_eq!(guest.call("GlobalMemoryStatusEx", &[status]), 0);
|
||||
assert_eq!(guest.error(), ERROR_INVALID_PARAMETER);
|
||||
|
||||
let query = |guest: &mut Guest| {
|
||||
guest.memory.write_u32(status, 64).unwrap();
|
||||
assert_eq!(guest.call("GlobalMemoryStatusEx", &[status]), 1);
|
||||
let load = guest.u32_at(status + 4);
|
||||
let fields: [u64; 7] =
|
||||
std::array::from_fn(|index| guest.u64_at(status + 8 + 8 * index as u64));
|
||||
(load, fields)
|
||||
};
|
||||
const MIB: u64 = 1 << 20;
|
||||
let (
|
||||
load,
|
||||
[
|
||||
total,
|
||||
available,
|
||||
page_total,
|
||||
page_available,
|
||||
total_virtual,
|
||||
_,
|
||||
extended,
|
||||
],
|
||||
) = query(&mut guest);
|
||||
assert_eq!((load, total, available), (0, 128 * MIB, 128 * MIB));
|
||||
assert_eq!((page_total, page_available), (total, available));
|
||||
assert_eq!(total_virtual, 0x7fff_fffe_0000);
|
||||
assert_eq!(extended, 0);
|
||||
|
||||
let region = guest.call("VirtualAlloc", &[0, MIB, 0x3000, 4]);
|
||||
assert_ne!(region, 0);
|
||||
let heap = guest.call("GetProcessHeap", &[]);
|
||||
assert_ne!(guest.call("HeapAlloc", &[heap, 0, 32 * MIB]), 0);
|
||||
let (load, [_, available, ..]) = query(&mut guest);
|
||||
assert_eq!(available, 128 * MIB - 33 * MIB);
|
||||
assert_eq!(load, 25); // 33 of 128 MiB in use, rounded down
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn calendar_time_comes_from_the_injected_clock() {
|
||||
let clock = Arc::new(MockClock::new(filetime(NOV_24_2026, 789)));
|
||||
let state = ServicesState::new(clock.clone());
|
||||
let mut guest = Guest::with_state(IMPORTS, &[], state);
|
||||
let time = SCRATCH;
|
||||
for symbol in ["GetSystemTime", "GetLocalTime"] {
|
||||
assert_eq!(guest.call(symbol, &[time]), 0);
|
||||
assert_eq!(
|
||||
system_time(&guest, time),
|
||||
[2026, 11, 2, 24, 12, 34, 56, 789]
|
||||
);
|
||||
}
|
||||
let precise = SCRATCH + 0x20;
|
||||
assert_eq!(guest.call("GetSystemTimePreciseAsFileTime", &[precise]), 0);
|
||||
assert_eq!(guest.u64_at(precise), filetime(NOV_24_2026, 789));
|
||||
clock.advance(TICKS_PER_SECOND);
|
||||
assert_eq!(guest.call("GetSystemTimeAsFileTime", &[precise]), 0);
|
||||
assert_eq!(guest.u64_at(precise), filetime(NOV_24_2026 + 1, 789));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filetime_and_system_time_convert_in_both_directions() {
|
||||
let mut guest = Guest::new(IMPORTS, &[]);
|
||||
let (input, output, back) = (SCRATCH, SCRATCH + 0x20, SCRATCH + 0x40);
|
||||
for (value, expected) in [
|
||||
(0, [1601, 1, 1, 1, 0, 0, 0, 0]), // a Monday
|
||||
(UNIX_EPOCH_FILETIME, [1970, 1, 4, 1, 0, 0, 0, 0]), // a Thursday
|
||||
(
|
||||
filetime(FEB_29_2024, 999),
|
||||
[2024, 2, 4, 29, 23, 59, 59, 999],
|
||||
),
|
||||
(
|
||||
filetime(NOV_24_2026, 789),
|
||||
[2026, 11, 2, 24, 12, 34, 56, 789],
|
||||
),
|
||||
] {
|
||||
guest.memory.write_u64(input, value).unwrap();
|
||||
assert_eq!(guest.call("FileTimeToSystemTime", &[input, output]), 1);
|
||||
assert_eq!(system_time(&guest, output), expected);
|
||||
// The day of week is ignored on the way back.
|
||||
let mut fields = expected;
|
||||
fields[2] = 6;
|
||||
write_system_time(&mut guest, output, fields);
|
||||
assert_eq!(guest.call("SystemTimeToFileTime", &[output, back]), 1);
|
||||
assert_eq!(guest.u64_at(back), value - value % 10_000);
|
||||
}
|
||||
|
||||
guest
|
||||
.memory
|
||||
.write_u64(input, 0x8000_0000_0000_0000)
|
||||
.unwrap();
|
||||
guest.memory.write_u64(output, u64::MAX).unwrap();
|
||||
assert_eq!(guest.call("FileTimeToSystemTime", &[input, output]), 0);
|
||||
assert_eq!(guest.error(), ERROR_INVALID_PARAMETER);
|
||||
assert_eq!(guest.u64_at(output), u64::MAX);
|
||||
|
||||
for invalid in [
|
||||
[2023, 2, 0, 29, 0, 0, 0, 0], // not a leap year
|
||||
[1900, 2, 0, 29, 0, 0, 0, 0], // century, not a leap year
|
||||
[2026, 13, 0, 1, 0, 0, 0, 0],
|
||||
[2026, 4, 0, 31, 0, 0, 0, 0],
|
||||
[2026, 1, 0, 1, 24, 0, 0, 0],
|
||||
[2026, 1, 0, 1, 0, 0, 0, 1000],
|
||||
[1600, 12, 0, 31, 0, 0, 0, 0],
|
||||
] {
|
||||
write_system_time(&mut guest, output, invalid);
|
||||
guest.memory.write_u64(back, 7).unwrap();
|
||||
assert_eq!(
|
||||
guest.call("SystemTimeToFileTime", &[output, back]),
|
||||
0,
|
||||
"{invalid:?}"
|
||||
);
|
||||
assert_eq!(guest.error(), ERROR_INVALID_PARAMETER);
|
||||
assert_eq!(guest.u64_at(back), 7);
|
||||
}
|
||||
write_system_time(&mut guest, output, [2000, 2, 0, 29, 0, 0, 0, 0]);
|
||||
assert_eq!(guest.call("SystemTimeToFileTime", &[output, back]), 1);
|
||||
write_system_time(&mut guest, output, [30827, 12, 0, 31, 23, 59, 59, 999]);
|
||||
assert_eq!(guest.call("SystemTimeToFileTime", &[output, back]), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sleeping_advances_the_injected_clock() {
|
||||
let clock = Arc::new(MockClock::new(0));
|
||||
let state = ServicesState::new(clock.clone());
|
||||
let mut guest = Guest::with_state(IMPORTS, &[], state);
|
||||
let interrupt = SCRATCH;
|
||||
assert_eq!(guest.call("GetTickCount64", &[]), 0);
|
||||
assert_eq!(guest.call("Sleep", &[250]), 0);
|
||||
assert_eq!(guest.call("GetTickCount64", &[]), 250);
|
||||
assert_eq!(guest.call("SleepEx", &[5, 1]), 0);
|
||||
assert_eq!(guest.call("Sleep", &[0]), 0);
|
||||
assert_eq!(guest.call("GetTickCount64", &[]), 255);
|
||||
assert_eq!(guest.call("QueryUnbiasedInterruptTime", &[interrupt]), 1);
|
||||
assert_eq!(guest.u64_at(interrupt), 2_550_000);
|
||||
// A single guest thread sleeping forever can never wake.
|
||||
assert_eq!(guest.fails("Sleep", &[u64::from(u32::MAX)]), RUNTIME_LIMIT);
|
||||
assert_eq!(guest.fails("SleepEx", &[60_000, 0]), RUNTIME_LIMIT);
|
||||
assert_eq!(guest.call("GetTickCount64", &[]), 255);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,227 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Shared harness for runtime service tests: an original PE32+ image whose
|
||||
//! imports are bound to the standard service registry and called from
|
||||
//! translated guest code.
|
||||
|
||||
#![allow(dead_code)]
|
||||
|
||||
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()
|
||||
}
|
||||
}
|
||||
@@ -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,7 +54,7 @@ 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}"]
|
||||
@@ -84,11 +84,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 +179,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
|
||||
@@ -953,6 +1033,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 +1114,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 +1133,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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -305,6 +305,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 +397,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 +405,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 +433,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,
|
||||
@@ -625,7 +637,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 +672,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 +739,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;
|
||||
@@ -935,7 +989,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 +1000,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 +1226,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
|
||||
@@ -1298,6 +1362,107 @@ fn division_accepts_exactly_the_representable_quotients() {
|
||||
}
|
||||
}
|
||||
|
||||
/// The bit scans and the bit test keep the destination and the flags where
|
||||
/// the architecture puts them.
|
||||
///
|
||||
/// The expectations come from the Intel SDM Volume 2B, "BSF", "BSR" and "BT":
|
||||
/// BSF writes the index of the lowest set bit of the source and BSR the index
|
||||
/// of the highest set bit, and both set the zero flag when the source is
|
||||
/// zero, in which case the destination is undefined and keeps its value. BT
|
||||
/// sets the carry flag from the tested bit, leaves the other flags alone and
|
||||
/// masks the bit index to the operand width.
|
||||
///
|
||||
/// The encodings are `bsf rbx, r9` (49 0F BC D9), `bsr rbx, r9` (49 0F BD
|
||||
/// D9), `bt rbx, r9` (4C 0F A3 CB), `bsf ebx, r9d` (41 0F BC D9),
|
||||
/// `bsr ebx, r9d` (41 0F BD D9), `bt ebx, r9d` (44 0F A3 CB), `bsf bx, r9w`
|
||||
/// (66 41 0F BC D9) and `bt bx, r9w` (66 44 0F A3 CB), as produced by LLVM
|
||||
/// 23.1.6 `llvm-mc -show-encoding`.
|
||||
#[test]
|
||||
fn bit_scans_and_bit_tests_follow_the_architecture() {
|
||||
const BSF64: &[u8] = &[0x49, 0x0F, 0xBC, 0xD9]; // bsf rbx, r9
|
||||
const BSR64: &[u8] = &[0x49, 0x0F, 0xBD, 0xD9]; // bsr rbx, r9
|
||||
const BT64: &[u8] = &[0x4C, 0x0F, 0xA3, 0xCB]; // bt rbx, r9
|
||||
const BSF32: &[u8] = &[0x41, 0x0F, 0xBC, 0xD9]; // bsf ebx, r9d
|
||||
const BSR32: &[u8] = &[0x41, 0x0F, 0xBD, 0xD9]; // bsr ebx, r9d
|
||||
const BT32: &[u8] = &[0x44, 0x0F, 0xA3, 0xCB]; // bt ebx, r9d
|
||||
const BSF16: &[u8] = &[0x66, 0x41, 0x0F, 0xBC, 0xD9]; // bsf bx, r9w
|
||||
const BT16: &[u8] = &[0x66, 0x44, 0x0F, 0xA3, 0xCB]; // bt bx, r9w
|
||||
|
||||
/// A machine with R9 and RBX set and every other register zero.
|
||||
fn machine(source: u64, destination: u64) -> Machine {
|
||||
let mut gpr = [0; 16];
|
||||
gpr[3] = destination;
|
||||
gpr[9] = source;
|
||||
Machine {
|
||||
gpr,
|
||||
flags: Flags::default(),
|
||||
operand: 0,
|
||||
pushed: 0,
|
||||
top: STACK_TOP,
|
||||
}
|
||||
}
|
||||
|
||||
// The lowest set bit of the source is the index BSF writes.
|
||||
let (state, _, _) = run_both(&machine(0x0000_0000_0000_0028, 0xFFFF), BSF64, 1);
|
||||
assert_eq!(state.gpr[3], 3);
|
||||
assert!(!state.flags.zf);
|
||||
|
||||
// The highest set bit of the source is the index BSR writes.
|
||||
let (state, _, _) = run_both(&machine(0x8000_0000_0000_0028, 0xFFFF), BSR64, 1);
|
||||
assert_eq!(state.gpr[3], 63);
|
||||
assert!(!state.flags.zf);
|
||||
|
||||
// A zero source sets the zero flag and leaves the destination alone.
|
||||
let (state, _, _) = run_both(&machine(0, 0xFFFF_FFFF_FFFF_FFFF), BSF64, 1);
|
||||
assert_eq!(state.gpr[3], 0xFFFF_FFFF_FFFF_FFFF);
|
||||
assert!(state.flags.zf);
|
||||
let (state, _, _) = run_both(&machine(0, 0xFFFF_FFFF_FFFF_FFFF), BSR64, 1);
|
||||
assert_eq!(state.gpr[3], 0xFFFF_FFFF_FFFF_FFFF);
|
||||
assert!(state.flags.zf);
|
||||
|
||||
// A 32-bit destination holds a 32-bit index and clears the half above it.
|
||||
let (state, _, _) = run_both(&machine(0x0000_0028, 0xFFFF_FFFF_FFFF_FFFF), BSF32, 1);
|
||||
assert_eq!(state.gpr[3], 3);
|
||||
let (state, _, _) = run_both(&machine(0x8000_0000, 0xFFFF_FFFF_FFFF_FFFF), BSR32, 1);
|
||||
assert_eq!(state.gpr[3], 31);
|
||||
|
||||
// A 16-bit destination keeps the bits above it.
|
||||
let (state, _, _) = run_both(&machine(0x0100, 0xFFFF_FFFF_FFFF_FFFF), BSF16, 1);
|
||||
assert_eq!(state.gpr[3], 0xFFFF_FFFF_FFFF_0008);
|
||||
|
||||
// BT reports the tested bit in the carry flag and leaves the bit string
|
||||
// alone.
|
||||
let (state, _, _) = run_both(&machine(1, 0b1010), BT64, 1);
|
||||
assert!(state.flags.cf);
|
||||
assert_eq!(state.gpr[3], 0b1010);
|
||||
let (state, _, _) = run_both(&machine(0, 0b1010), BT64, 1);
|
||||
assert!(!state.flags.cf);
|
||||
assert_eq!(state.gpr[3], 0b1010);
|
||||
|
||||
// The bit index is masked to the operand width, so 64 selects bit 0 of a
|
||||
// 64-bit bit string and 32 selects bit 0 of a 32-bit one.
|
||||
let (state, _, _) = run_both(&machine(64, 0b1), BT64, 1);
|
||||
assert!(state.flags.cf);
|
||||
let (state, _, _) = run_both(&machine(32, 0b1), BT32, 1);
|
||||
assert!(state.flags.cf);
|
||||
let (state, _, _) = run_both(&machine(16, 0b1), BT16, 1);
|
||||
assert!(state.flags.cf);
|
||||
|
||||
// The bit scans and the register form of the bit test are lowered to
|
||||
// ARM64 instead of falling back to the shared semantics.
|
||||
for code in [BSF64, BSR64, BT64, BSF32, BSR32, BT32, BSF16, BT16] {
|
||||
let insn = decode(ENTRY, |address| {
|
||||
code.get((address - ENTRY) as usize).copied().ok_or(())
|
||||
})
|
||||
.expect("decode");
|
||||
assert!(is_native(&insn), "{code:02X?} is not native");
|
||||
let mut engine = DbtEngine::new(64 * 1024).unwrap();
|
||||
let (mut cpu, mut memory) = load(&machine(0x28, 0), code);
|
||||
engine.run(&mut cpu, &mut memory, 1);
|
||||
assert_eq!(engine.metrics.interpreter_fallbacks, 0, "{code:02X?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pop_rsp_and_push_rsp_use_the_architectural_stack_pointer() {
|
||||
let machine = Random(17).machine();
|
||||
|
||||
@@ -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,11 +54,15 @@ 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" }
|
||||
@@ -85,6 +95,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 +108,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 +186,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 +407,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 +627,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 +782,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 +830,7 @@ 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" }
|
||||
|
||||
# SSE and SSE2 moves and packed integer forms.
|
||||
|
||||
@@ -814,6 +954,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 +1979,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.
|
||||
|
||||
|
||||
@@ -41,6 +41,7 @@ objc2-metal = { version = "=0.3.2", default-features = false, features = [
|
||||
"MTLComputePipeline",
|
||||
"MTLDepthStencil",
|
||||
"MTLDevice",
|
||||
"MTLEvent",
|
||||
"MTLLibrary",
|
||||
"MTLPixelFormat",
|
||||
"MTLPipeline",
|
||||
|
||||
+427
-39
@@ -1,9 +1,12 @@
|
||||
use std::collections::BTreeMap;
|
||||
use std::ffi::c_void;
|
||||
use std::fmt;
|
||||
use std::mem::size_of_val;
|
||||
use std::ptr::{NonNull, copy_nonoverlapping};
|
||||
use std::sync::{Mutex, MutexGuard, PoisonError};
|
||||
use std::time::Instant;
|
||||
|
||||
use objc2::Message;
|
||||
use objc2::rc::{Retained, autoreleasepool};
|
||||
use objc2::runtime::{NSObjectProtocol, ProtocolObject};
|
||||
use objc2::sel;
|
||||
@@ -13,8 +16,8 @@ use objc2_metal::{
|
||||
MTLCompileOptions, MTLComputeCommandEncoder, MTLComputePipelineState,
|
||||
MTLCreateSystemDefaultDevice, MTLDevice, MTLFunction, MTLGPUFamily, MTLLibrary,
|
||||
MTLMathFloatingPointFunctions, MTLMathMode, MTLOrigin, MTLPixelFormat, MTLRegion,
|
||||
MTLResourceOptions, MTLShaderValidation, MTLSize, MTLStorageMode, MTLTexture,
|
||||
MTLTextureDescriptor, MTLTextureUsage,
|
||||
MTLResourceOptions, MTLSamplerState, MTLShaderValidation, MTLSharedEvent, MTLSize,
|
||||
MTLStorageMode, MTLTexture, MTLTextureDescriptor, MTLTextureUsage,
|
||||
};
|
||||
use xenora_texture::{
|
||||
Bc1Upload, BcAlphaFormat, BcAlphaUpload, BcChannelFormat, BcChannelUpload, TiledBc1,
|
||||
@@ -33,6 +36,7 @@ const MAX_THREADS_PER_GROUP: usize = 64;
|
||||
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 BC_READBACK: &str = r"
|
||||
#include <metal_stdlib>
|
||||
@@ -65,7 +69,7 @@ enum ComputeInput<'a> {
|
||||
Texture(&'a ProtocolObject<dyn MTLTexture>, usize),
|
||||
SampledTexture {
|
||||
texture: &'a ProtocolObject<dyn MTLTexture>,
|
||||
sampler: &'a ProtocolObject<dyn objc2_metal::MTLSamplerState>,
|
||||
sampler: &'a ProtocolObject<dyn MTLSamplerState>,
|
||||
coords: &'a [u32],
|
||||
},
|
||||
}
|
||||
@@ -147,7 +151,18 @@ pub struct RunProfile {
|
||||
pub library_seconds: f64,
|
||||
pub pipeline_seconds: f64,
|
||||
pub gpu_seconds: f64,
|
||||
/// Host wall time from the start of setup until wait observes completion.
|
||||
pub host_seconds: f64,
|
||||
/// Host time to allocate the input and output shared buffers.
|
||||
pub alloc_seconds: f64,
|
||||
/// Host time to create the command buffer and encode the dispatch.
|
||||
pub encode_seconds: f64,
|
||||
/// Host time spent in `commit`.
|
||||
pub commit_seconds: f64,
|
||||
/// Host time spent in `waitUntilCompleted`.
|
||||
pub wait_seconds: f64,
|
||||
/// Host time to copy the output words back; not part of `host_seconds`.
|
||||
pub readback_seconds: f64,
|
||||
pub output: Vec<u32>,
|
||||
}
|
||||
|
||||
@@ -155,10 +170,161 @@ pub struct RunProfile {
|
||||
pub struct NativeCompute {
|
||||
device: Retained<ProtocolObject<dyn MTLDevice>>,
|
||||
queue: Retained<ProtocolObject<dyn MTLCommandQueue>>,
|
||||
submissions: Mutex<SubmissionTable>,
|
||||
}
|
||||
|
||||
/// A submitted dispatch whose result can be collected by its issuing context.
|
||||
#[must_use]
|
||||
pub struct Submission<'a> {
|
||||
context: &'a NativeCompute,
|
||||
id: u64,
|
||||
}
|
||||
|
||||
impl Drop for Submission<'_> {
|
||||
fn drop(&mut self) {
|
||||
let mut table = self.context.submissions();
|
||||
if let Some(entry) = table.entries.get_mut(&self.id) {
|
||||
if entry.resources.is_some() {
|
||||
entry.abandoned = true;
|
||||
} else {
|
||||
table.entries.remove(&self.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub struct SubmissionGate {
|
||||
event: Retained<ProtocolObject<dyn MTLSharedEvent>>,
|
||||
}
|
||||
|
||||
impl SubmissionGate {
|
||||
pub fn open(&self) {
|
||||
self.event.setSignaledValue(1);
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SubmissionGate {
|
||||
fn drop(&mut self) {
|
||||
self.open();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct SubmissionTable {
|
||||
next_id: u64,
|
||||
entries: BTreeMap<u64, SubmissionEntry>,
|
||||
}
|
||||
|
||||
impl SubmissionTable {
|
||||
fn in_flight(&self) -> usize {
|
||||
self.entries
|
||||
.values()
|
||||
.filter(|entry| entry.resources.is_some())
|
||||
.count()
|
||||
}
|
||||
|
||||
fn check_capacity(&self) -> Result<(), MetalError> {
|
||||
if self.in_flight() >= MAX_IN_FLIGHT {
|
||||
return Err(MetalError::new(
|
||||
"in-flight limit",
|
||||
format!("at most {MAX_IN_FLIGHT} compute submissions may be in flight"),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct SubmissionEntry {
|
||||
resources: Option<InFlightResources>,
|
||||
result: Result<RunProfile, MetalError>,
|
||||
host_start: Instant,
|
||||
abandoned: bool,
|
||||
waiting: bool,
|
||||
}
|
||||
|
||||
/// Owns every resource referenced by the unretained command buffer until
|
||||
/// Metal reports Completed or Error.
|
||||
struct InFlightResources {
|
||||
command: Retained<ProtocolObject<dyn MTLCommandBuffer>>,
|
||||
_pipeline: Retained<ProtocolObject<dyn MTLComputePipelineState>>,
|
||||
_input: Option<Retained<ProtocolObject<dyn MTLBuffer>>>,
|
||||
output: Retained<ProtocolObject<dyn MTLBuffer>>,
|
||||
_texture: Option<Retained<ProtocolObject<dyn MTLTexture>>>,
|
||||
_sampler: Option<Retained<ProtocolObject<dyn MTLSamplerState>>>,
|
||||
gate: Option<Retained<ProtocolObject<dyn MTLSharedEvent>>>,
|
||||
word_count: usize,
|
||||
}
|
||||
|
||||
// SAFETY: Metal permits command buffers to move between threads with exclusive
|
||||
// access. The table mutex and waiting flag keep sweeps off a command during its
|
||||
// wait. Readback uses private shared storage after GPU completion. Retained
|
||||
// textures and input buffers are only kept alive by the table.
|
||||
unsafe impl Send for InFlightResources {}
|
||||
|
||||
impl SubmissionEntry {
|
||||
fn retire(&mut self, status: MTLCommandBufferStatus) {
|
||||
if !is_terminal(status) {
|
||||
return;
|
||||
}
|
||||
let Some(resources) = self.resources.take() else {
|
||||
return;
|
||||
};
|
||||
if let Err(error) = check_command_status(&resources.command, status) {
|
||||
self.result = Err(error);
|
||||
return;
|
||||
}
|
||||
if let Ok(profile) = &mut self.result {
|
||||
profile.gpu_seconds = resources.command.GPUEndTime() - resources.command.GPUStartTime();
|
||||
profile.host_seconds = self.host_start.elapsed().as_secs_f64();
|
||||
let readback_start = Instant::now();
|
||||
let byte_len = resources.word_count * size_of::<u32>();
|
||||
// SAFETY: The initialized shared output is distinct from the host
|
||||
// vector and the GPU has finished writing to it. Both ranges hold
|
||||
// byte_len bytes and all u32 bit patterns are valid.
|
||||
unsafe {
|
||||
copy_nonoverlapping(
|
||||
resources.output.contents().cast::<u8>().as_ptr(),
|
||||
profile.output.as_mut_ptr().cast::<u8>(),
|
||||
byte_len,
|
||||
);
|
||||
}
|
||||
profile.readback_seconds = readback_start.elapsed().as_secs_f64();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for NativeCompute {
|
||||
fn drop(&mut self) {
|
||||
// Tokens can be abandoned (or forgotten) while their work is pending.
|
||||
// Open all remaining gates before draining the queue.
|
||||
let table = self
|
||||
.submissions
|
||||
.get_mut()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
for resources in table
|
||||
.entries
|
||||
.values()
|
||||
.filter_map(|entry| entry.resources.as_ref())
|
||||
{
|
||||
if let Some(gate) = &resources.gate {
|
||||
gate.setSignaledValue(1);
|
||||
}
|
||||
}
|
||||
for (_, entry) in std::mem::take(&mut table.entries) {
|
||||
if let Some(resources) = entry.resources {
|
||||
resources.command.waitUntilCompleted();
|
||||
if !is_terminal(resources.command.status()) {
|
||||
// Preserve the resources if Metal unexpectedly returns before completion.
|
||||
std::mem::forget(resources);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl NativeCompute {
|
||||
/// Open the default Apple GPU and create a retained-resource command queue.
|
||||
/// Open the default Apple GPU and create a command queue.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
@@ -178,10 +344,47 @@ impl NativeCompute {
|
||||
let queue = device
|
||||
.newCommandQueue()
|
||||
.ok_or_else(|| MetalError::new("newCommandQueue", "queue creation failed"))?;
|
||||
Ok(Self { device, queue })
|
||||
Ok(Self {
|
||||
device,
|
||||
queue,
|
||||
submissions: Mutex::default(),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
fn submissions(&self) -> MutexGuard<'_, SubmissionTable> {
|
||||
self.submissions
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
fn retire_completed(&self) {
|
||||
self.submissions().entries.retain(|_, entry| {
|
||||
if !entry.waiting
|
||||
&& let Some(resources) = &entry.resources
|
||||
{
|
||||
entry.retire(resources.command.status());
|
||||
}
|
||||
!entry.abandoned || entry.resources.is_some()
|
||||
});
|
||||
}
|
||||
|
||||
fn begin_submission(&self) -> Instant {
|
||||
let host_start = Instant::now();
|
||||
self.retire_completed();
|
||||
host_start
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub fn in_flight(&self) -> usize {
|
||||
self.submissions().in_flight()
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub fn tracked(&self) -> usize {
|
||||
self.submissions().entries.len()
|
||||
}
|
||||
|
||||
/// Report the selected device's registered name.
|
||||
pub fn device_name(&self) -> String {
|
||||
autoreleasepool(|_| self.device.name().to_string())
|
||||
@@ -561,6 +764,122 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
self.run_profiled_words(source, entry, input, None)
|
||||
}
|
||||
|
||||
/// Submit trusted MSL with read-only words at buffer 0 and output words at buffer 1.
|
||||
///
|
||||
/// The trusted-kernel requirements of [`Self::run_words`] apply.
|
||||
/// Use [`Self::wait`] to collect the result.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error for invalid input or source, compilation or dispatch
|
||||
/// setup failure, or a full in-flight table.
|
||||
pub fn submit_words(
|
||||
&self,
|
||||
source: &str,
|
||||
entry: &str,
|
||||
input: &[u32],
|
||||
) -> Result<Submission<'_>, MetalError> {
|
||||
autoreleasepool(|_| {
|
||||
let host_start = self.begin_submission();
|
||||
validate_words(source, entry, input)?;
|
||||
self.submit_sized(
|
||||
source,
|
||||
entry,
|
||||
ComputeInput::Words(input),
|
||||
None,
|
||||
None,
|
||||
host_start,
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
pub fn submit_words_gated(
|
||||
&self,
|
||||
source: &str,
|
||||
entry: &str,
|
||||
input: &[u32],
|
||||
) -> Result<(Submission<'_>, SubmissionGate), MetalError> {
|
||||
autoreleasepool(|_| {
|
||||
let host_start = self.begin_submission();
|
||||
validate_words(source, entry, input)?;
|
||||
let event = self
|
||||
.device
|
||||
.newSharedEvent()
|
||||
.ok_or_else(|| MetalError::new("newSharedEvent", "gate creation failed"))?;
|
||||
let submission = self.submit_sized(
|
||||
source,
|
||||
entry,
|
||||
ComputeInput::Words(input),
|
||||
None,
|
||||
Some(&event),
|
||||
host_start,
|
||||
)?;
|
||||
Ok((submission, SubmissionGate { event }))
|
||||
})
|
||||
}
|
||||
|
||||
/// Wait for this context's submission and return its readback and timings.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an error for a token from another context, an unknown submission,
|
||||
/// or a Metal completion failure.
|
||||
pub fn wait(&self, submission: Submission<'_>) -> Result<RunProfile, MetalError> {
|
||||
if !std::ptr::eq(self, submission.context) {
|
||||
return Err(MetalError::new(
|
||||
"submission",
|
||||
"token belongs to another context",
|
||||
));
|
||||
}
|
||||
autoreleasepool(|_| {
|
||||
let id = submission.id;
|
||||
std::mem::forget(submission);
|
||||
let result = self.take_result(id);
|
||||
self.retire_completed();
|
||||
result
|
||||
})
|
||||
}
|
||||
|
||||
fn take_result(&self, id: u64) -> Result<RunProfile, MetalError> {
|
||||
let unknown = || MetalError::new("submission", "unknown submission id");
|
||||
let command = {
|
||||
let mut table = self.submissions();
|
||||
let entry = table.entries.get_mut(&id).ok_or_else(unknown)?;
|
||||
entry.resources.as_ref().map(|resources| {
|
||||
entry.waiting = true;
|
||||
resources.command.clone()
|
||||
})
|
||||
};
|
||||
let wait_seconds = command.map_or(0.0, |command| {
|
||||
// Keep the table available to other submitters while Metal waits.
|
||||
let start = Instant::now();
|
||||
command.waitUntilCompleted();
|
||||
start.elapsed().as_secs_f64()
|
||||
});
|
||||
|
||||
let mut table = self.submissions();
|
||||
let entry = table.entries.get_mut(&id).ok_or_else(unknown)?;
|
||||
entry.waiting = false;
|
||||
let host_seconds = if let Some(resources) = &entry.resources {
|
||||
let status = resources.command.status();
|
||||
if !is_terminal(status) {
|
||||
entry.abandoned = true;
|
||||
check_command_status(&resources.command, status)?;
|
||||
}
|
||||
entry.retire(status);
|
||||
None
|
||||
} else {
|
||||
Some(entry.host_start.elapsed().as_secs_f64())
|
||||
};
|
||||
let mut profile = table.entries.remove(&id).ok_or_else(unknown)?.result?;
|
||||
profile.wait_seconds = wait_seconds;
|
||||
if let Some(host_seconds) = host_seconds {
|
||||
profile.host_seconds = host_seconds;
|
||||
}
|
||||
Ok(profile)
|
||||
}
|
||||
|
||||
/// Run trusted MSL with an explicit one-dimensional threadgroup width.
|
||||
///
|
||||
/// The grid still contains one invocation per input word. The requested width
|
||||
@@ -608,13 +927,7 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
input: &[u32],
|
||||
group_width: Option<usize>,
|
||||
) -> Result<RunProfile, MetalError> {
|
||||
if !(1..=MAX_GRID_WORDS).contains(&input.len()) {
|
||||
return Err(MetalError::new(
|
||||
"dispatch bounds",
|
||||
format!("expected 1..={MAX_GRID_WORDS} words, got {}", input.len()),
|
||||
));
|
||||
}
|
||||
validate_source(source, &[entry])?;
|
||||
validate_words(source, entry, input)?;
|
||||
autoreleasepool(|_| self.run_sized(source, entry, ComputeInput::Words(input), group_width))
|
||||
}
|
||||
|
||||
@@ -636,7 +949,20 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
input: ComputeInput<'_>,
|
||||
group_width: Option<usize>,
|
||||
) -> Result<RunProfile, MetalError> {
|
||||
let host_start = Instant::now();
|
||||
let host_start = self.begin_submission();
|
||||
self.wait(self.submit_sized(source, entry, input, group_width, None, host_start)?)
|
||||
}
|
||||
|
||||
fn submit_sized(
|
||||
&self,
|
||||
source: &str,
|
||||
entry: &str,
|
||||
input: ComputeInput<'_>,
|
||||
group_width: Option<usize>,
|
||||
gate: Option<&ProtocolObject<dyn MTLSharedEvent>>,
|
||||
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)?;
|
||||
@@ -672,17 +998,29 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
"fixture exceeds device buffer limit",
|
||||
));
|
||||
}
|
||||
let alloc_start = Instant::now();
|
||||
let input_buffer = match input {
|
||||
ComputeInput::Words(words) => Some(self.new_buffer(words)?),
|
||||
ComputeInput::SampledTexture { coords, .. } => Some(self.new_buffer(coords)?),
|
||||
ComputeInput::Texture(..) => None,
|
||||
};
|
||||
let mut words = vec![0xA5A5_A5A5; input.len()];
|
||||
let words = vec![0xA5A5_A5A5; input.len()];
|
||||
let output_buffer = self.new_buffer(&words)?;
|
||||
let alloc_seconds = alloc_start.elapsed().as_secs_f64();
|
||||
let mut table = self.submissions();
|
||||
table.check_capacity()?;
|
||||
let id = table.next_id;
|
||||
table.next_id = id
|
||||
.checked_add(1)
|
||||
.ok_or_else(|| MetalError::new("submission", "submission ids exhausted"))?;
|
||||
let encode_start = Instant::now();
|
||||
let command = self
|
||||
.queue
|
||||
.commandBuffer()
|
||||
.commandBufferWithUnretainedReferences()
|
||||
.ok_or_else(|| MetalError::new("commandBuffer", "command buffer creation failed"))?;
|
||||
if let Some(gate) = gate {
|
||||
command.encodeWaitForEvent_value(gate.as_ref(), 1);
|
||||
}
|
||||
let encoder = command.computeCommandEncoder().ok_or_else(|| {
|
||||
MetalError::new("computeCommandEncoder", "compute encoder creation failed")
|
||||
})?;
|
||||
@@ -710,27 +1048,49 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
}
|
||||
encoder.dispatchThreads_threadsPerThreadgroup(size(input.len()), size(width));
|
||||
encoder.endEncoding();
|
||||
complete_command(&command)?;
|
||||
let gpu_seconds = command.GPUEndTime() - command.GPUStartTime();
|
||||
let host_seconds = host_start.elapsed().as_secs_f64();
|
||||
// SAFETY: Metal copied the initialized words into distinct shared storage.
|
||||
// The GPU finished before the CPU touches that storage. Both ranges are
|
||||
// valid for byte_len bytes and don't overlap. A byte copy requires no
|
||||
// additional alignment and all u32 bit patterns are valid.
|
||||
unsafe {
|
||||
copy_nonoverlapping(
|
||||
output_buffer.contents().cast::<u8>().as_ptr(),
|
||||
words.as_mut_ptr().cast::<u8>(),
|
||||
byte_len,
|
||||
);
|
||||
}
|
||||
Ok(RunProfile {
|
||||
library_seconds,
|
||||
pipeline_seconds,
|
||||
gpu_seconds,
|
||||
host_seconds,
|
||||
output: words,
|
||||
})
|
||||
let encode_seconds = encode_start.elapsed().as_secs_f64();
|
||||
let (texture, sampler) = match input {
|
||||
ComputeInput::Texture(texture, _) => (Some(texture.retain()), None),
|
||||
ComputeInput::SampledTexture {
|
||||
texture, sampler, ..
|
||||
} => (Some(texture.retain()), Some(sampler.retain())),
|
||||
ComputeInput::Words(_) => (None, None),
|
||||
};
|
||||
let resources = InFlightResources {
|
||||
command,
|
||||
_pipeline: pipeline,
|
||||
_input: input_buffer,
|
||||
output: output_buffer,
|
||||
_texture: texture,
|
||||
_sampler: sampler,
|
||||
gate: gate.map(Message::retain),
|
||||
word_count: input.len(),
|
||||
};
|
||||
let commit_start = Instant::now();
|
||||
resources.command.commit();
|
||||
let commit_seconds = commit_start.elapsed().as_secs_f64();
|
||||
table.entries.insert(
|
||||
id,
|
||||
SubmissionEntry {
|
||||
resources: Some(resources),
|
||||
result: Ok(RunProfile {
|
||||
library_seconds,
|
||||
pipeline_seconds,
|
||||
gpu_seconds: 0.0,
|
||||
host_seconds: 0.0,
|
||||
alloc_seconds,
|
||||
encode_seconds,
|
||||
commit_seconds,
|
||||
wait_seconds: 0.0,
|
||||
readback_seconds: 0.0,
|
||||
output: words,
|
||||
}),
|
||||
host_start,
|
||||
abandoned: false,
|
||||
waiting: false,
|
||||
},
|
||||
);
|
||||
Ok(Submission { context: self, id })
|
||||
}
|
||||
|
||||
fn compile_library(
|
||||
@@ -790,6 +1150,16 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_words(source: &str, entry: &str, input: &[u32]) -> Result<(), MetalError> {
|
||||
if !(1..=MAX_GRID_WORDS).contains(&input.len()) {
|
||||
return Err(MetalError::new(
|
||||
"dispatch bounds",
|
||||
format!("expected 1..={MAX_GRID_WORDS} words, got {}", input.len()),
|
||||
));
|
||||
}
|
||||
validate_source(source, &[entry])
|
||||
}
|
||||
|
||||
fn validate_source(source: &str, entries: &[&str]) -> Result<(), MetalError> {
|
||||
if source.is_empty()
|
||||
|| source.len() > MAX_SOURCE_BYTES
|
||||
@@ -829,11 +1199,29 @@ fn find_function(
|
||||
|
||||
fn complete_command(command: &ProtocolObject<dyn MTLCommandBuffer>) -> Result<(), MetalError> {
|
||||
command.commit();
|
||||
command.waitUntilCompleted();
|
||||
wait_command(command)
|
||||
}
|
||||
|
||||
if command.status() != MTLCommandBufferStatus::Completed {
|
||||
/// Block until a committed command buffer finishes and check its status.
|
||||
fn wait_command(command: &ProtocolObject<dyn MTLCommandBuffer>) -> Result<(), MetalError> {
|
||||
command.waitUntilCompleted();
|
||||
check_command_status(command, command.status())
|
||||
}
|
||||
|
||||
fn is_terminal(status: MTLCommandBufferStatus) -> bool {
|
||||
matches!(
|
||||
status,
|
||||
MTLCommandBufferStatus::Completed | MTLCommandBufferStatus::Error
|
||||
)
|
||||
}
|
||||
|
||||
fn check_command_status(
|
||||
command: &ProtocolObject<dyn MTLCommandBuffer>,
|
||||
status: MTLCommandBufferStatus,
|
||||
) -> Result<(), MetalError> {
|
||||
if status != MTLCommandBufferStatus::Completed {
|
||||
let error = command.error().map_or_else(
|
||||
|| format!("unexpected command status {:?}", command.status()),
|
||||
|| format!("unexpected command status {status:?}"),
|
||||
|error| error.localizedDescription().to_string(),
|
||||
);
|
||||
return Err(MetalError::new("waitUntilCompleted", error));
|
||||
|
||||
Loaded 100 of 193 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user