mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-29 03:31:13 +00:00
Compare commits
152
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e3bbc955bc | ||
|
|
c7351c846d | ||
|
|
78d52c0eeb | ||
|
|
4ebbd4767f | ||
|
|
5a6a3b3e4f | ||
|
|
8cae9772b6 | ||
|
|
13c259027b | ||
|
|
42825b223b | ||
|
|
4db0b9c530 | ||
|
|
2b97a66db9 | ||
|
|
280cd492fe | ||
|
|
b0984673d8 | ||
|
|
c6a354bca5 | ||
|
|
c4d0b6c000 | ||
|
|
9d83e09aa6 | ||
|
|
3bdc43d3ad | ||
|
|
fa434d7174 | ||
|
|
ed657ad802 | ||
|
|
b49ec43ddc | ||
|
|
d00c787544 | ||
|
|
5e7c21bc86 | ||
|
|
4f4d977807 | ||
|
|
f6dfe58695 | ||
|
|
b12aa502a2 | ||
|
|
20780eab24 | ||
|
|
259b3054e1 | ||
|
|
f685edebfb | ||
|
|
c0cb3e72be | ||
|
|
a27d63bfab | ||
|
|
0f7658bb5b | ||
|
|
313430c1c6 | ||
|
|
63cf3595cd | ||
|
|
050df307a1 | ||
|
|
7a5176497a | ||
|
|
f4005501bc | ||
|
|
f175a10033 | ||
|
|
c651a9d320 | ||
|
|
22bafeb0b2 | ||
|
|
f56d3c9862 | ||
|
|
48f44cac3d | ||
|
|
8410e3d0e8 | ||
|
|
dce37dab18 | ||
|
|
70f1793a4c | ||
|
|
19bea60d25 | ||
|
|
f70e6d0534 | ||
|
|
223fe253c9 | ||
|
|
62be091197 | ||
|
|
cf288dd940 | ||
|
|
9f57d8b3bb | ||
|
|
5d4d15d596 | ||
|
|
95ddc28518 | ||
|
|
9cc4a965c4 | ||
|
|
9b767186a2 | ||
|
|
823007888f | ||
|
|
881c2a2e52 | ||
|
|
475b27e5d4 | ||
|
|
cac93574ce | ||
|
|
085b0e28e5 | ||
|
|
835689e5df | ||
|
|
55e1818ccd | ||
|
|
44ea8133fc | ||
|
|
756597a6b4 | ||
|
|
02f9ad9a34 | ||
|
|
4038cdbe41 | ||
|
|
51b60381c5 | ||
|
|
2593f73f29 | ||
|
|
5ab561b0e8 | ||
|
|
3f3f154d2d | ||
|
|
56febbb655 | ||
|
|
4d68733f3c | ||
|
|
d22f046bf9 | ||
|
|
430f63e27d | ||
|
|
ce29b87770 | ||
|
|
ad424d690a | ||
|
|
9e47234e92 | ||
|
|
5ba0496c63 | ||
|
|
cd224d86f4 | ||
|
|
dd4bcb30eb | ||
|
|
0836936011 | ||
|
|
aef29ff65d | ||
|
|
3392c226ce | ||
|
|
bfd14e4c50 | ||
|
|
72bf5f7e32 | ||
|
|
78df3a5c6b | ||
|
|
133c9df448 | ||
|
|
a6d354fb2a | ||
|
|
00f79c10d2 | ||
|
|
95a8c61f1b | ||
|
|
7e09c9ce63 | ||
|
|
31627363f1 | ||
|
|
9cd6f43a62 | ||
|
|
7a3b197215 | ||
|
|
ee2d29a65c | ||
|
|
83ef49c258 | ||
|
|
84b6fb4d50 | ||
|
|
b98380c1b0 | ||
|
|
bc629f5321 | ||
|
|
a953ba9d37 | ||
|
|
7fa240f7ba | ||
|
|
0e9211cd42 | ||
|
|
c41e034fa1 | ||
|
|
7977dd4bf2 | ||
|
|
cd948d4a14 | ||
|
|
a2c696b551 | ||
|
|
d6189ae3ea | ||
|
|
e6eece6983 | ||
|
|
1a78265ede | ||
|
|
2e0e5a36f6 | ||
|
|
ece0fc27eb | ||
|
|
82f2d9e9e6 | ||
|
|
391367a531 | ||
|
|
e71a3da525 | ||
|
|
b96511bfc5 | ||
|
|
84bb80d910 | ||
|
|
9edf644d77 | ||
|
|
b5d0382e89 | ||
|
|
b705104403 | ||
|
|
f148b51a48 | ||
|
|
c979870b3a | ||
|
|
cd59e081d9 | ||
|
|
0bfb12fd17 | ||
|
|
c6d0986da2 | ||
|
|
9a9422c7da | ||
|
|
da41b6420d | ||
|
|
3f710928af | ||
|
|
2fdf01fbb3 | ||
|
|
de00cb2bfd | ||
|
|
d8f9669280 | ||
|
|
19b2e9b5d5 | ||
|
|
bb6bc52c95 | ||
|
|
ba6bbb2e4a | ||
|
|
705b074a08 | ||
|
|
d3c1150854 | ||
|
|
a81d62ffe3 | ||
|
|
bb1372cd70 | ||
|
|
8d53d82981 | ||
|
|
ba2cfc2a00 | ||
|
|
b13ab327f2 | ||
|
|
e7cb8db14f | ||
|
|
e7795d0e5a | ||
|
|
3ff9ddde24 | ||
|
|
ff191d89bd | ||
|
|
4039be8ee2 | ||
|
|
898b79dc84 | ||
|
|
30d20c8f33 | ||
|
|
0687a8add6 | ||
|
|
791b736b0e | ||
|
|
fcda9c09bd | ||
|
|
ad5a6f9c53 | ||
|
|
f856671b6d | ||
|
|
e1317322e1 | ||
|
|
92fd955a8d |
No files matched your search
@@ -53,6 +53,7 @@ jobs:
|
||||
permissions:
|
||||
contents: read
|
||||
issues: write
|
||||
pull-requests: read
|
||||
concurrency:
|
||||
group: agent-queue
|
||||
cancel-in-progress: false
|
||||
|
||||
@@ -37,3 +37,6 @@ __pycache__/
|
||||
*.pyc
|
||||
/diagnostics/gta6-candidate-*/
|
||||
/diagnostics/gta6-check/
|
||||
|
||||
# Native application build output
|
||||
/app/.build/
|
||||
+41
-1
@@ -9,8 +9,36 @@ exact revision and known limitations.
|
||||
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
|
||||
remains unsupported.
|
||||
|
||||
### Added
|
||||
### Changed
|
||||
- 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.
|
||||
|
||||
### Added
|
||||
- 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.
|
||||
- Added XMM0-XMM15 and MXCSR to the guest CPU state, and the SSE and SSE2 moves and packed integer forms: aligned, unaligned, scalar, half and non-temporal moves, MOVD/MOVQ, sign-mask extraction, bitwise operations, wrapping and saturating arithmetic, compares, minimum, maximum, average, multiplies, PSADBW, packs, unpacks, shifts, shuffles, PINSRW, PEXTRW, LDMXCSR and STMXCSR (parts of #124, #125, #126 and #128; awaiting independent review). Operations with identical NEON lane semantics are translated to ARM64; the rest call the shared semantics. Misaligned 16-byte operands and reserved MXCSR bits raise a distinct general-protection exit. MXCSR is state only: floating-point arithmetic is not implemented.
|
||||
- Added 374 LLVM-assembled vector instructions with a byte-array reference, compared with both engines over 23,936 states, plus alignment, fault, width and mixed-sequence tests.
|
||||
- Added a declarative x86-64 instruction registry (`crates/loader/x86/instructions.toml`) and its generator, `crates/loader/generate_x86.py`, with `validate`, `generate` and `--check` modes. The static probe, the interpreter and the native DBT now share one decoder driven by its tables, so instruction boundaries, rejected forms and reported support agree. Overlapping encodings, such as a sign extension claiming the MOV-immediate opcodes, fail validation. See `docs/cpu/instruction-registry.md`.
|
||||
- Added integer instructions for 8-, 16-, 32- and 64-bit register and checked memory operands: the eight ALU operations, TEST, INC, DEC, NEG, NOT, XCHG, ROL, ROR, SHL, SHR, SAR, MUL, IMUL, DIV, IDIV, CMOVcc, SETcc, BT, BTS, BTR, BTC, BSF, BSR, POPCNT, TZCNT, LZCNT, CBW/CWD families, PUSH, POP, LEAVE, RET imm16 and flag instructions, with parity and auxiliary-carry flags and a distinct divide-error exit (parts of #65, #66, #68, #70, #71, #73, #118 to #123, #194 to #196; awaiting independent review). Forms the DBT does not lower to ARM64 call the same Rust semantics and are counted.
|
||||
- Added 985 LLVM-assembled integer instructions with a bit-level reference that reads only their assembly text, compared with the interpreter and the DBT over 47,280 states, plus 4,000 random instruction sequences compared between the engines.
|
||||
- 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 MOVZX, MOVSX (0F B6/B7/BE/BF) and MOVSXD (63) for register and checked memory operands in the interpreter and the native DBT, with exact lengths in the static probe (parts of #65, #66, #67, #68 and #117; awaiting independent review). Covered: 16-, 32- and 64-bit destinations, AH/CH/DH/BH without REX, FS/GS bases and RIP-relative operands. Other 0x66 forms are rejected instead of running at the wrong width. Known-answer encodings come from the LLVM assembler; MOV immediates (B8-BF) have regressions proving they are never read as sign extensions.
|
||||
- Added Phase II infrastructure CLIs under `scripts/qa` and `scripts/release` (#277): read-only RDNA2 expansion planning over live inventories, unified verification profiles with stale-evidence detection, CPU/runtime coverage scans, benchmark regression comparisons that reject incompatible identities, git rename/delete scope collision reports, and release-readiness reports with SBOM/checksum/bundle checks. Covered by `tests/qa` and `tests/release`; advisory until reviewed.
|
||||
- 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.
|
||||
- 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 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`.
|
||||
- Added persistent guest rendering with pause, resume and stop to the native application (Gate 3, #266). The C interface gains `xenora_session_start_frame_loop`, `xenora_session_pause_frame_loop`, `xenora_session_resume_frame_loop`, `xenora_session_stop_frame_loop`, and `xenora_session_frame_loop_status`, plus new states (`XENORA_LOOP_*`). The guest fixture (`fixtures/pe/frame-loop.exe`, generated by `fixtures/pe/frame-loop.py` without external toolchains) runs on a session-owned thread and repeatedly calls `xenora.dll!frame_submit` until told to halt; each frame is rendered on native Metal, checked per pixel against geometric expectations, and returned via read-back RGBA8 buffers. Destroying a running or paused session safely stops its loop outside the global session lock. Xenora.app gains persistent frame-loop controls ("Start 300 frames", "Pause", "Resume", "Stop") and displays live frames with their frame index. Five GPU acceptance tests with Metal API and GPU validation verify frame ordering over 300 frames, live sampling across 2,000 frames without backwards progression, pause/resume/stop lifecycle, prompt join on session destruction, and stable memory footprint across repeated sessions. Added `--smoke-loop` to Xenora.app and wired the acceptance tests into `scripts/test-gpu.sh`.
|
||||
- Added read-only executable inspection to the native app (#267). Xenora.app can open a PE file with Open Executable…, by dropping it on the window, or from Finder (it registers as an alternate viewer for Windows executables). The new C function `xenora_inspect_executable` returns a text report built from the existing static probe and loader validation: file size and SHA-256, header facts, whether `ParsedPe::parse` accepts the file, sections, imports not provided by Xenora's standard runtime services, the bounded static disassembly's count of instructions the ARM64 DBT does not support with the first one's address, and relocation and TLS counts. Nothing in the file is executed, and executing opened files remains unavailable pending #257. Inputs over 256 MiB are refused before reading. A panic inside the probe is reported as a Xenora defect instead of crashing the app; the new truncation test found one in `probe_pe_bytes` (truncations of `trusted-runner.exe` to 1,556–1,665 bytes slice past the end of the file while reading an import name), reported as #270 and not fixed here. Checked with the x1 executables in `experiments/x1/fixtures`, which the app does not embed, with malformed inputs, and in the window through the Finder open path and the Open panel; drag and drop was not exercised.
|
||||
- Added eleven gfx1030 SOP1 unary forms through the semantic registry: `s_not_b32`, `s_brev_b32`, `s_bcnt0_i32_b32`, `s_bcnt1_i32_b32`, `s_ff0_i32_b32`, `s_ff1_i32_b32`, `s_flbit_i32_b32`, `s_flbit_i32`, `s_sext_i32_i8`, `s_sext_i32_i16` and `s_abs_i32` (AMD guide section 12.3). Searches that find nothing return -1, `s_abs_i32` of 0x80000000 stays 0x80000000, and only NOT, BCNT0, BCNT1 and ABS write SCC. The registry gained these primitives, a `sop1_sgpr` operand rule, and a declared `source_bits` for sign extension that is checked against the XML's 8- and 16-bit source operands. The reference and independent semantic-review interpreters, written separately from the guide, evaluate the same eleven forms and are checked against 4,126 guide-derived cases on both CPU interpreters and on native Metal with validation; 231 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all eleven. Part of #215.
|
||||
- Showed the first guest-driven frame in the native app (Gate 2, #263). The C interface gains `xenora_session_run_trusted_fixture`, which runs only the embedded trusted PE fixture: its x86-64 code is translated and executed, its `xenora.dll!fixture_draw` call compiles the x9 RDNA2 shader fixtures to MSL and renders on the native Metal device, and the 4×3 RGBA8 read-back is returned only if the guest halts with the CLI runner's expected results and every pixel equals the pixel shader's export, (1, 0, 0, 1) as opaque red. Xenora.app's "Run trusted fixture" button shows that frame, and `--smoke-frame` prints it. A `gpu-tests` test, run by `scripts/test-gpu.sh`, executes the fixture three times through the interface with Metal validation enabled. The frame is a read-back image, not drawable presentation, and no caller-supplied executable can run. Verified on one Apple Silicon Mac; the window was checked by screenshot.
|
||||
- Added a minimal native macOS application shell and its Rust interface (Gate 1 of the native application work). `crates/ffi` builds a static library with a versioned C interface (`crates/ffi/include/xenora.h`, version 1): opaque, generation-checked 64-bit session handles (never pointers), at most 64 live sessions, stable status codes, and panics caught at the boundary. Version 1 can only create and destroy sessions and parse the bundled trusted PE fixture; it executes no guest code. `app/` is a SwiftUI app built with Swift Package Manager that shows the interface version and the fixture's section count and entry point. `scripts/build-app.sh` builds an ad-hoc-signed, arm64-only `build/Xenora.app` with no entitlements and runs its `--smoke` check. Six Rust tests cover invalid, stale and double-destroyed handles, version mismatch, null outputs, 4,000 concurrent create and destroy cycles, and header/constant agreement. The CLI and headless workflows are unchanged. Verified locally on one Apple Silicon Mac (macOS 27.2.1, Swift 6.4, Rust 1.100.0); not yet run in CI.
|
||||
- Added the gfx1030 SOPC compares `s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32}` through the semantic registry, which replaces the hand-written `s_cmp_eq_u32` path. Each sets only SCC to whether the relation holds with SSRC0 on the left (AMD guide section 12.4); the registry gained a `compare` operation with a declared `relation` and a `sopc_scalar` operand rule. `Instruction::ScalarCompareEqU32` is now `Instruction::ScalarCompare { op: ScalarCompareOp, .. }`; `s_cmp_eq_u32` behaves as before. The reference and independent semantic-review interpreters, written separately from the guide, evaluate all twelve, checked against 7,824 guide-derived cases on both CPU interpreters and on native Metal with validation; 348 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all twelve. Two literal selectors stay rejected. Part of #215, stage D.
|
||||
- Added eight gfx1030 SOP2 forms through the semantic registry alone: `s_andn2_b32`, `s_orn2_b32`, `s_nand_b32`, `s_nor_b32`, `s_xnor_b32`, `s_lshl_b32`, `s_lshr_b32` and `s_ashr_i32`, each with SCC = result != 0. Each is one registry entry with no per-form Rust; the registry gained these primitives and a declared shift-count width (`shift_count_bits = 5`, so shifts use S1[4:0] as in the AMD guide, section 12.1), which the generator applies as a mask and checks against the XML's unsigned count operand. The reference interpreter and the independent semantic-review interpreter, written separately from the guide, now evaluate the same eight forms and are checked against 6,896 guide-derived cases; a new LLVM-assembled fixture (`fixtures/rdna2/scalar-logic.s`) runs on CPU and native Metal with validation. A NULL destination (s125) stays rejected. Part of #215, stage C.
|
||||
- Added an independent operand-domain verification harness for the 9 supported SOP2 scalar ALU forms and 12 VOPC integer compares (`tests/validation/tests/operand_domains.rs`, part of #215 stage E): 4,788 generated cases (boundary values, 64-bit carry and borrow chains, aliased registers, every integer inline constant, literals, s105 and v255, partial and zero EXEC, VCCZ) and 498 rejections (missing literal words, and encodings outside Xenora's supported subset) run on `xenora_ref` and, as an ignored test picked up by `scripts/test-gpu.sh`, on native Metal. Expected values come from the public AMD RDNA 2 guide's pseudocode, written out in the test without Xenora code; this is agreement with a spec-derived reference, not with Xbox hardware. Local verification only: 32 deliberate code breaks were each caught; the guide leaves the width of `S1 + SCC` in `s_subb_u32` open, and those 8 cases are kept in their own family.
|
||||
- Added a declarative semantic registry for gfx1030 instruction forms (`crates/isa/semantics/rdna2.toml`, schema 1) and its generator, `crates/isa/generate_semantics.py`, with `validate`, `generate` and `--check` modes. The generator checks every declaration against a closed vocabulary and the pinned AMD XML snapshot (opcode, family, SCC input and output, operand widths and signed formats), rejects contradictory, incomplete or duplicate definitions, and emits static Rust tables marked as generated. The nine SOP2 forms moved onto it with no change in behaviour: the decoder's SOP2 dispatch and `ScalarAluOp`'s mnemonic, SCC read and evaluation are now generated, and evaluation goes through shared primitives instead of per-opcode code. All existing SOP2 tests, including the native Metal known answers and the LLVM comparison, pass unchanged. Decoding speed is unchanged (10.2 ns before, 10.1 ns after, per SOP2 instruction, release build on an Apple M5 Pro). Also added `scripts/audit/semantic_coverage.py`, which generates `docs/shaders/semantic-coverage.md`: per-family counts of identified, declared, decoded, lowered, reference-verified and Metal-verified forms, taking evidence only from `docs/status.toml`. Part of #215, stages A and B.
|
||||
- Added a native Metal blend pass, `NativeCompute::render_blend`: up to 16 flat-coloured triangles drawn in order into an RGBA8 target, each with its own colour write mask (any subset of R, G, B, A) and either blending disabled or separate RGB and alpha blend factors (Zero, One, source and destination colour and alpha, and their one-minus forms) and operations (Add, Subtract, ReverseSubtract, and Min and Max, which take the unweighted values). Checked on the GPU with Metal validation in 39 passes over two original overlapping triangles: a clear-only pass; blending disabled; each source factor with the destination term zeroed and each destination factor with the source term zeroed; every operation; additive clamping; separate alpha factors; a separate alpha operation; eight write masks (each channel alone, RGB, none, RGBA, and RG with blending); and a pass whose first draw is itself blended and masked. Colours are compared per channel against images derived independently (in exact fractions) from the public Metal blend equations, which a new CPU reference in `xenora-ref` also reproduces. The tolerance was fixed before measuring: channels whose exact result is a whole 8-bit value must match exactly, and channels that need rounding may differ by 1. On an Apple M5 Pro every rounded channel matched round-to-nearest exactly. Synthetic fixtures only; no console blend state is involved.
|
||||
- Added indexed triangle draws. Native Metal: `NativeCompute::render_indexed` issues one real `drawIndexedPrimitives` call per draw (up to 16) on a 16- or 32-bit index buffer with a start index and a signed base vertex, into an RGBA8 target; a draw can sample an original BC1 texture uploaded natively. Before encoding anything it rejects the whole pass for a bad index count, an index range past the buffer, any `index + base vertex` outside the vertex buffer, and, as this API's policy, a raw all-ones index (the primitive-restart value, which Metal does not define for triangle lists). Loader: a synthetic, CPU-side index buffer binding (resource handle and offset, the view running to the end of the resource) with `cmd_set_index_buffer` and `cmd_draw_indexed_instanced`, which fetch one triangle, drawn once, through the index buffer, start index and base vertex and pass it to the existing one-triangle backend; each drawn triangle replaces the previous output. Recording rejects formats other than DXGI `R16_UINT` and `R32_UINT`, offsets not aligned to the index size or past the resource, and unknown resources. Execution checks each draw in turn, so earlier draws have already rendered when a later one fails: index counts other than 0 or 3, more than one instance or a nonzero start instance, a missing index buffer, indices past the buffer and an `index + base vertex` outside the vertex buffer are typed errors; a valid zero index or instance count draws nothing. All-ones indices are ordinary indices there. Checked on the GPU with Metal validation in 16 passes (both index sizes, 32-bit indices above 16 bits, odd 16-bit start, positive and negative base vertex, reversed winding, flat and textured two-triangle draws, draw order, BC1-textured draws), compared per pixel against images derived independently from the geometry, the public D3D12 and Metal index semantics and the public BC1 rules, which a new CPU reference in `xenora-ref` also reproduces; the loader's fetch is checked against literal positions with synthetic guest-backed buffers and through the native Metal renderer. Synthetic fixtures only; no console index-buffer views, guest programs or console draw state are involved.
|
||||
@@ -68,12 +96,23 @@ remains unsupported.
|
||||
- Added Win64 TEB allocation and `gs_base` initialization to synthetic guest startup.
|
||||
|
||||
### Changed
|
||||
- Registering an import key twice is now an error instead of silently replacing the first service, ordinals are distinct from names, and API sets in the import generator match exactly instead of by prefix.
|
||||
- `GetSystemTimeAsFileTime` now stops the guest on a null pointer, as on any other invalid pointer, instead of setting the last error.
|
||||
|
||||
- Simplified the claim rules in `AGENTS.md`, `CONTRIBUTING.md` and the pull request template at the maintainer's request: claim an issue by replying on it in plain words, never claim over an existing claim, and treat a claim as stale only after about one week without a pull request. The task-queue lease (`lease_hours` in `.github/agent-queue.json`) is now 168 hours to match, and `docs/coordination/agent-tasks.md` marks the queue commands as optional.
|
||||
- The static PE probe now marks x86-64 SIB memory addressing as DBT-supported, matching the
|
||||
native DBT.
|
||||
|
||||
### Fixed
|
||||
- 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 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.
|
||||
- Fixed the static probe reporting support for forms an engine rejects, including NOP, TEST, most conditional branches and the FF group in the interpreter.
|
||||
- Fixed the native DBT's `SXTW` encoding, which set bit 3 of the source register and was right only for registers that already had it set; the previous test used such a register by chance.
|
||||
- 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 `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],
|
||||
@@ -157,6 +196,7 @@ remains unsupported.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fixed the intermittent failure of the frame-loop memory-footprint test (#290). Each frame-loop session opened its own Metal command queue. The first command buffer on a queue makes the GPU driver allocate a working set for it (about 45 MiB on an Apple M5 with Metal validation), and the driver frees it asynchronously 10–50 ms after the queue is released, so the process footprint read right after a session ended depended on how far that release had got. Measured immediately after each of 50 destroys, it ranged from 45 to 96 MiB; the unchanged test failed 5 times in 30 runs, with up to 26 MiB of apparent growth. There was no leak: one second after each destroy the footprint was back at the same floor every time. Frame-loop sessions now share one process-wide Metal device and command queue, so the working set is allocated once and kept: the same readings stay within 93–98 MiB across 50 sessions, and the unchanged test passed 30 runs in a row (largest growth 0.31 MiB). The cost is that the process keeps that GPU memory (about 50 MiB with validation, 58 MiB total footprint without) after its first frame loop. A new 50-session test (normal completion, pause and resume, destroy while running) checks the readings stay within 16 MiB; it fails without the fix.
|
||||
- Stop ignoring `fixtures/pe/trusted-runner.exe`. The runner embeds it with `include_bytes!`, so ignoring the file made a fresh checkout fail to compile.
|
||||
- Corrected the ARM64 STP pre-index encoder, which had a hardcoded -32-byte immediate and therefore adjusted the host stack by the wrong amount once the translator frame grew to 48 bytes. The wrong frame silently corrupted the caller's stack and caused SIGSEGV in every native translation test. Emitter encodings are now checked against LLVM's assembler, and a test asserts that each translated block opens and closes the same 48-byte frame.
|
||||
- Translated guest memory faults now stop the block before it commits further architectural effects. A faulting push, call or store leaves guest RSP and registers unchanged, the reported instruction count covers only completed work, and guest RIP identifies the faulting instruction. Previously the block continued after the helper recorded a fault, so later instructions and writes still took effect.
|
||||
|
||||
Generated
+9
@@ -179,6 +179,15 @@ dependencies = [
|
||||
"xenora-ref",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xenora-ffi"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"xenora-loader",
|
||||
"xenora-metal",
|
||||
"xenora-shader",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "xenora-import-gen"
|
||||
version = "0.1.0"
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
// swift-tools-version: 6.0
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
// Build with scripts/build-app.sh, which builds the Rust static library first.
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "Xenora",
|
||||
platforms: [.macOS(.v14)],
|
||||
targets: [
|
||||
.systemLibrary(name: "CXenora", path: "Sources/CXenora"),
|
||||
.executableTarget(name: "Xenora", dependencies: ["CXenora"]),
|
||||
]
|
||||
)
|
||||
@@ -0,0 +1,5 @@
|
||||
module CXenora [system] {
|
||||
header "../../../crates/ffi/include/xenora.h"
|
||||
link "xenora_ffi"
|
||||
export *
|
||||
}
|
||||
@@ -0,0 +1,679 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
//
|
||||
// Native shell over the versioned C interface. "Run trusted fixture" executes the
|
||||
// bundled trusted PE fixture (x86-64 translated to ARM64; its draw request is rendered
|
||||
// by native Metal) and shows the verified read-back frame. No other executable can run.
|
||||
|
||||
import AppKit
|
||||
import CXenora
|
||||
import Foundation
|
||||
import SwiftUI
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
struct RuntimeProbe {
|
||||
var abiVersion: UInt32 = 0
|
||||
var status: Int32 = -1
|
||||
var sections: UInt32 = 0
|
||||
var entryRVA: UInt32 = 0
|
||||
|
||||
var connected: Bool { abiVersion == XENORA_ABI_VERSION && status == XENORA_OK }
|
||||
|
||||
static func run() -> RuntimeProbe {
|
||||
var probe = RuntimeProbe(abiVersion: xenora_abi_version())
|
||||
var session: xenora_session = 0
|
||||
probe.status = xenora_session_create(XENORA_ABI_VERSION, &session)
|
||||
guard probe.status == XENORA_OK else { return probe }
|
||||
defer { _ = xenora_session_destroy(session) }
|
||||
probe.status = xenora_session_inspect_trusted_fixture(session, &probe.sections, &probe.entryRVA)
|
||||
return probe
|
||||
}
|
||||
|
||||
var summary: String {
|
||||
String(format: "abi=%u status=%d sections=%u entry_rva=0x%x", abiVersion, status, sections, entryRVA)
|
||||
}
|
||||
}
|
||||
|
||||
/// The frame produced by one run of the trusted fixture.
|
||||
struct GuestFrame {
|
||||
let status: Int32
|
||||
let width: Int
|
||||
let height: Int
|
||||
let rgba: [UInt8]
|
||||
|
||||
static func run() -> GuestFrame {
|
||||
var session: xenora_session = 0
|
||||
var status = xenora_session_create(XENORA_ABI_VERSION, &session)
|
||||
guard status == XENORA_OK else { return GuestFrame(status: status, width: 0, height: 0, rgba: []) }
|
||||
defer { _ = xenora_session_destroy(session) }
|
||||
var rgba = [UInt8](repeating: 0, count: Int(XENORA_FIXTURE_FRAME_WIDTH * XENORA_FIXTURE_FRAME_HEIGHT * 4))
|
||||
var width: UInt32 = 0
|
||||
var height: UInt32 = 0
|
||||
status = rgba.withUnsafeMutableBufferPointer { buffer in
|
||||
xenora_session_run_trusted_fixture(session, buffer.baseAddress, UInt64(buffer.count), &width, &height)
|
||||
}
|
||||
return GuestFrame(status: status, width: Int(width), height: Int(height), rgba: status == XENORA_OK ? rgba : [])
|
||||
}
|
||||
|
||||
var image: CGImage? {
|
||||
guard status == XENORA_OK, let provider = CGDataProvider(data: Data(rgba) as CFData) else { return nil }
|
||||
return CGImage(
|
||||
width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: width * 4,
|
||||
space: CGColorSpaceCreateDeviceRGB(),
|
||||
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue),
|
||||
provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent)
|
||||
}
|
||||
|
||||
var summary: String {
|
||||
let first = rgba.prefix(4).map(String.init).joined(separator: ",")
|
||||
return "status=\(status) frame=\(width)x\(height) first_pixel=\(first)"
|
||||
}
|
||||
}
|
||||
|
||||
/// The frame produced by running the textured fixture (Gate 5, #279).
|
||||
struct TexturedFrame {
|
||||
let status: Int32
|
||||
let width: Int
|
||||
let height: Int
|
||||
let rgba: [UInt8]
|
||||
|
||||
static func run() -> TexturedFrame {
|
||||
var session: xenora_session = 0
|
||||
var status = xenora_session_create(XENORA_ABI_VERSION, &session)
|
||||
guard status == XENORA_OK else { return TexturedFrame(status: status, width: 0, height: 0, rgba: []) }
|
||||
defer { _ = xenora_session_destroy(session) }
|
||||
var rgba = [UInt8](repeating: 0, count: 16)
|
||||
var width: UInt32 = 0
|
||||
var height: UInt32 = 0
|
||||
status = rgba.withUnsafeMutableBufferPointer { buffer in
|
||||
xenora_session_run_textured_fixture(session, buffer.baseAddress, UInt64(buffer.count), &width, &height)
|
||||
}
|
||||
return TexturedFrame(status: status, width: Int(width), height: Int(height), rgba: status == XENORA_OK ? rgba : [])
|
||||
}
|
||||
|
||||
var image: CGImage? {
|
||||
guard status == XENORA_OK, let provider = CGDataProvider(data: Data(rgba) as CFData) else { return nil }
|
||||
return CGImage(
|
||||
width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: width * 4,
|
||||
space: CGColorSpaceCreateDeviceRGB(),
|
||||
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue),
|
||||
provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent)
|
||||
}
|
||||
|
||||
var summary: String {
|
||||
let pixels = rgba.map(String.init).joined(separator: ",")
|
||||
return "status=\(status) frame=\(width)x\(height) pixels=[\(pixels)]"
|
||||
}
|
||||
}
|
||||
|
||||
/// The frame and audio status produced by running the audio/VFS fixture (Gate 6, #284).
|
||||
struct AudioVfsFrame {
|
||||
let status: Int32
|
||||
let width: Int
|
||||
let height: Int
|
||||
let samples: UInt32
|
||||
let totalAudioBytes: UInt64
|
||||
let rgba: [UInt8]
|
||||
|
||||
static func run() -> 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: [])
|
||||
}
|
||||
defer { _ = xenora_session_destroy(session) }
|
||||
var rgba = [UInt8](repeating: 0, count: 16)
|
||||
var width: UInt32 = 0
|
||||
var height: UInt32 = 0
|
||||
var samples: UInt32 = 0
|
||||
status = rgba.withUnsafeMutableBufferPointer { buffer in
|
||||
xenora_session_run_audio_vfs_fixture(
|
||||
session, buffer.baseAddress, UInt64(buffer.count), &width, &height, &samples)
|
||||
}
|
||||
var queued: UInt32 = 0
|
||||
var underruns: UInt32 = 0
|
||||
var total: UInt64 = 0
|
||||
_ = xenora_session_audio_status(session, &queued, &underruns, &total)
|
||||
return AudioVfsFrame(
|
||||
status: status,
|
||||
width: Int(width),
|
||||
height: Int(height),
|
||||
samples: samples,
|
||||
totalAudioBytes: total,
|
||||
rgba: status == XENORA_OK ? rgba : []
|
||||
)
|
||||
}
|
||||
|
||||
var image: CGImage? {
|
||||
guard status == XENORA_OK, let provider = CGDataProvider(data: Data(rgba) as CFData) else { return nil }
|
||||
return CGImage(
|
||||
width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: width * 4,
|
||||
space: CGColorSpaceCreateDeviceRGB(),
|
||||
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue),
|
||||
provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent)
|
||||
}
|
||||
|
||||
var summary: String {
|
||||
let pixels = rgba.map(String.init).joined(separator: ",")
|
||||
return "status=\(status) frame=\(width)x\(height) samples=\(samples) audio_total=\(totalAudioBytes) pixels=[\(pixels)]"
|
||||
}
|
||||
}
|
||||
|
||||
/// Owns the latest fixture run. A class with @Published avoids SwiftUI macros,
|
||||
/// which the command-line toolchain does not ship.
|
||||
@MainActor
|
||||
final class FrameModel: ObservableObject {
|
||||
@Published var frame: GuestFrame?
|
||||
@Published var running = false
|
||||
@Published var texturedFrame: TexturedFrame?
|
||||
@Published var runningTextured = false
|
||||
@Published var audioVfsFrame: AudioVfsFrame?
|
||||
@Published var runningAudioVfs = false
|
||||
|
||||
func run() {
|
||||
running = true
|
||||
Task {
|
||||
// The fixture blocks while it executes and renders, so keep it off the main thread.
|
||||
frame = await Task.detached { GuestFrame.run() }.value
|
||||
running = false
|
||||
}
|
||||
}
|
||||
|
||||
func runTextured() {
|
||||
runningTextured = true
|
||||
Task {
|
||||
texturedFrame = await Task.detached { TexturedFrame.run() }.value
|
||||
runningTextured = false
|
||||
}
|
||||
}
|
||||
|
||||
func runAudioVfs() {
|
||||
runningAudioVfs = true
|
||||
Task {
|
||||
audioVfsFrame = await Task.detached { AudioVfsFrame.run() }.value
|
||||
runningAudioVfs = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Persistent guest rendering model (Gate 3, #266; Gate 4, #276).
|
||||
@MainActor
|
||||
final class FrameLoopModel: ObservableObject {
|
||||
@Published var state: UInt32 = UInt32(XENORA_LOOP_NONE)
|
||||
@Published var completed: UInt32 = 0
|
||||
@Published var frameId: UInt32 = XENORA_NO_FRAME
|
||||
@Published var image: CGImage?
|
||||
@Published var errorMessage: String?
|
||||
@Published var isInteractive: Bool = false
|
||||
|
||||
private var session: xenora_session = 0
|
||||
private var pollTask: Task<Void, Never>?
|
||||
|
||||
deinit {
|
||||
pollTask?.cancel()
|
||||
if session != 0 {
|
||||
_ = xenora_session_destroy(session)
|
||||
}
|
||||
}
|
||||
|
||||
var isRunning: Bool { state == UInt32(XENORA_LOOP_RUNNING) }
|
||||
var isPaused: Bool { state == UInt32(XENORA_LOOP_PAUSED) }
|
||||
var canStart: Bool {
|
||||
session == 0 || state == UInt32(XENORA_LOOP_NONE) || state == UInt32(XENORA_LOOP_FINISHED)
|
||||
|| state == UInt32(XENORA_LOOP_STOPPED) || state == UInt32(XENORA_LOOP_FAILED)
|
||||
}
|
||||
|
||||
var stateDescription: String {
|
||||
switch state {
|
||||
case UInt32(XENORA_LOOP_NONE): return "Idle"
|
||||
case UInt32(XENORA_LOOP_RUNNING): return "Running"
|
||||
case UInt32(XENORA_LOOP_PAUSED): return "Paused"
|
||||
case UInt32(XENORA_LOOP_FINISHED): return "Finished"
|
||||
case UInt32(XENORA_LOOP_STOPPED): return "Stopped"
|
||||
case UInt32(XENORA_LOOP_FAILED): return "Failed"
|
||||
default: return "Unknown (\(state))"
|
||||
}
|
||||
}
|
||||
|
||||
func start(frameCount: UInt32 = 300) {
|
||||
errorMessage = nil
|
||||
if session != 0 {
|
||||
_ = xenora_session_destroy(session)
|
||||
session = 0
|
||||
}
|
||||
var newSession: xenora_session = 0
|
||||
let createStatus = xenora_session_create(XENORA_ABI_VERSION, &newSession)
|
||||
guard createStatus == XENORA_OK else {
|
||||
errorMessage = "Failed to create session (status \(createStatus))"
|
||||
return
|
||||
}
|
||||
session = newSession
|
||||
let startStatus = xenora_session_start_frame_loop(session, frameCount)
|
||||
guard startStatus == XENORA_OK else {
|
||||
errorMessage = "Failed to start frame loop (status \(startStatus))"
|
||||
_ = xenora_session_destroy(session)
|
||||
session = 0
|
||||
return
|
||||
}
|
||||
isInteractive = false
|
||||
state = UInt32(XENORA_LOOP_RUNNING)
|
||||
completed = 0
|
||||
frameId = XENORA_NO_FRAME
|
||||
image = nil
|
||||
startPolling()
|
||||
}
|
||||
|
||||
func startInteractive(frameCount: UInt32 = 300) {
|
||||
errorMessage = nil
|
||||
if session != 0 {
|
||||
_ = xenora_session_destroy(session)
|
||||
session = 0
|
||||
}
|
||||
var newSession: xenora_session = 0
|
||||
let createStatus = xenora_session_create(XENORA_ABI_VERSION, &newSession)
|
||||
guard createStatus == XENORA_OK else {
|
||||
errorMessage = "Failed to create session (status \(createStatus))"
|
||||
return
|
||||
}
|
||||
session = newSession
|
||||
let startStatus = xenora_session_start_interactive_loop(session, frameCount)
|
||||
guard startStatus == XENORA_OK else {
|
||||
errorMessage = "Failed to start interactive loop (status \(startStatus))"
|
||||
_ = xenora_session_destroy(session)
|
||||
session = 0
|
||||
return
|
||||
}
|
||||
isInteractive = true
|
||||
state = UInt32(XENORA_LOOP_RUNNING)
|
||||
completed = 0
|
||||
frameId = XENORA_NO_FRAME
|
||||
image = nil
|
||||
startPolling()
|
||||
}
|
||||
|
||||
func sendInput(buttons: UInt32) {
|
||||
guard session != 0 else { return }
|
||||
var input = xenora_input_state(
|
||||
buttons: buttons,
|
||||
stick_x: 0,
|
||||
stick_y: 0,
|
||||
mouse_dx: 0,
|
||||
mouse_dy: 0,
|
||||
mouse_buttons: 0,
|
||||
connected: 1,
|
||||
reserved: 0
|
||||
)
|
||||
_ = xenora_session_send_input(session, &input)
|
||||
}
|
||||
|
||||
func pause() {
|
||||
guard session != 0 else { return }
|
||||
_ = xenora_session_pause_frame_loop(session)
|
||||
}
|
||||
|
||||
func resume() {
|
||||
guard session != 0 else { return }
|
||||
_ = xenora_session_resume_frame_loop(session)
|
||||
}
|
||||
|
||||
func stop() {
|
||||
guard session != 0 else { return }
|
||||
_ = xenora_session_stop_frame_loop(session)
|
||||
}
|
||||
|
||||
private func startPolling() {
|
||||
pollTask?.cancel()
|
||||
pollTask = Task { [weak self] in
|
||||
while !Task.isCancelled {
|
||||
try? await Task.sleep(nanoseconds: 16_000_000)
|
||||
guard let self = self, self.session != 0 else { break }
|
||||
var st: UInt32 = 0
|
||||
var comp: UInt32 = 0
|
||||
var fId: UInt32 = 0
|
||||
var rgba = [UInt8](repeating: 0, count: Int(XENORA_FIXTURE_FRAME_WIDTH * XENORA_FIXTURE_FRAME_HEIGHT * 4))
|
||||
let code = rgba.withUnsafeMutableBufferPointer { buffer in
|
||||
xenora_session_frame_loop_status(
|
||||
self.session, &st, &comp, &fId, buffer.baseAddress, UInt64(buffer.count))
|
||||
}
|
||||
guard code == XENORA_OK else { break }
|
||||
self.state = st
|
||||
self.completed = comp
|
||||
self.frameId = fId
|
||||
if fId != XENORA_NO_FRAME, let provider = CGDataProvider(data: Data(rgba) as CFData) {
|
||||
self.image = CGImage(
|
||||
width: Int(XENORA_FIXTURE_FRAME_WIDTH),
|
||||
height: Int(XENORA_FIXTURE_FRAME_HEIGHT),
|
||||
bitsPerComponent: 8,
|
||||
bitsPerPixel: 32,
|
||||
bytesPerRow: Int(XENORA_FIXTURE_FRAME_WIDTH) * 4,
|
||||
space: CGColorSpaceCreateDeviceRGB(),
|
||||
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue),
|
||||
provider: provider,
|
||||
decode: nil,
|
||||
shouldInterpolate: false,
|
||||
intent: .defaultIntent
|
||||
)
|
||||
}
|
||||
if st != UInt32(XENORA_LOOP_RUNNING) && st != UInt32(XENORA_LOOP_PAUSED) {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Read-only compatibility inspection of a user-chosen file. Nothing in it is executed.
|
||||
@MainActor
|
||||
final class InspectionModel: ObservableObject {
|
||||
static let shared = InspectionModel()
|
||||
@Published var fileName: String?
|
||||
@Published var report = ""
|
||||
@Published var status: Int32 = Int32(XENORA_OK)
|
||||
@Published var busy = false
|
||||
@Published var importing = false
|
||||
|
||||
func inspect(_ url: URL) {
|
||||
fileName = url.lastPathComponent
|
||||
busy = true
|
||||
Task {
|
||||
let (newStatus, newReport) = await Task.detached { InspectionModel.run(url) }.value
|
||||
status = newStatus
|
||||
report = newReport
|
||||
busy = false
|
||||
}
|
||||
}
|
||||
|
||||
nonisolated static func run(_ url: URL) -> (Int32, String) {
|
||||
let scoped = url.startAccessingSecurityScopedResource()
|
||||
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
|
||||
// Check the size before reading so an oversized file is never loaded into memory.
|
||||
guard let size = (try? url.resourceValues(forKeys: [.fileSizeKey]))?.fileSize else {
|
||||
return (Int32(XENORA_INVALID_ARGUMENT), "Could not read the file's size.")
|
||||
}
|
||||
guard UInt64(size) <= UInt64(XENORA_MAX_INSPECT_BYTES) else {
|
||||
return (Int32(XENORA_LIMIT_EXCEEDED), "The file is \(size) bytes; inspection accepts at most \(XENORA_MAX_INSPECT_BYTES).")
|
||||
}
|
||||
guard let data = try? Data(contentsOf: url) else {
|
||||
return (Int32(XENORA_INVALID_ARGUMENT), "Could not read the file.")
|
||||
}
|
||||
return data.withUnsafeBytes { raw in
|
||||
let bytes = raw.bindMemory(to: UInt8.self).baseAddress
|
||||
var required: UInt64 = 0
|
||||
var probe: CChar = 0
|
||||
var status = xenora_inspect_executable(bytes, UInt64(data.count), &probe, 1, &required)
|
||||
guard status == Int32(XENORA_BUFFER_TOO_SMALL) else { return (status, "Inspection failed (status \(status)).") }
|
||||
var text = [CChar](repeating: 0, count: Int(required))
|
||||
status = xenora_inspect_executable(bytes, UInt64(data.count), &text, required, &required)
|
||||
return (status, String(cString: text))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Receives files opened from Finder (double-click or Open With).
|
||||
final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
func application(_ application: NSApplication, open urls: [URL]) {
|
||||
guard let url = urls.first else { return }
|
||||
MainActor.assumeIsolated { InspectionModel.shared.inspect(url) }
|
||||
}
|
||||
}
|
||||
|
||||
struct InspectorView: View {
|
||||
@ObservedObject var model: InspectionModel
|
||||
|
||||
var body: some View {
|
||||
Section("Executable inspection (read-only)") {
|
||||
HStack {
|
||||
Button("Open Executable…") { model.importing = true }
|
||||
Text("or drop a file on this window").foregroundStyle(.secondary)
|
||||
}
|
||||
if let name = model.fileName {
|
||||
LabeledContent("File", value: model.busy ? "\(name) (inspecting…)" : name)
|
||||
ScrollView {
|
||||
Text(model.report)
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.textSelection(.enabled)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
.frame(minHeight: 160, maxHeight: 320)
|
||||
}
|
||||
Text("Opened files are inspected only. Running them is not available.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ContentView: View {
|
||||
let probe = RuntimeProbe.run()
|
||||
@ObservedObject var model: FrameModel
|
||||
@ObservedObject var loop: FrameLoopModel
|
||||
@ObservedObject var inspection = InspectionModel.shared
|
||||
private var frame: GuestFrame? { model.frame }
|
||||
private var running: Bool { model.running }
|
||||
|
||||
var body: some View {
|
||||
Form {
|
||||
InspectorView(model: inspection)
|
||||
Section("Guest display") {
|
||||
if let image = frame?.image {
|
||||
Image(decorative: image, scale: 1)
|
||||
.resizable()
|
||||
.interpolation(.none)
|
||||
.aspectRatio(contentMode: .fit)
|
||||
.frame(maxWidth: .infinity, minHeight: 120, maxHeight: 240)
|
||||
.accessibilityLabel("Guest frame, \(frame!.width) by \(frame!.height) pixels")
|
||||
Text("Guest code ran, its draw was rendered by native Metal, and all \(frame!.width * frame!.height) pixels matched the fixture shader's output.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(.secondary)
|
||||
} else if let frame {
|
||||
Text("Run failed (status \(frame.status)). No frame is shown.")
|
||||
.foregroundStyle(.red)
|
||||
}
|
||||
if let tImage = model.texturedFrame?.image {
|
||||
Image(decorative: tImage, scale: 1)
|
||||
.resizable()
|
||||
.interpolation(.none)
|
||||
.aspectRatio(contentMode: .fit)
|
||||
.frame(maxWidth: .infinity, minHeight: 80, maxHeight: 160)
|
||||
.accessibilityLabel("Textured guest frame, 2 by 2 pixels")
|
||||
Text("Textured fixture ran: persistent texture created, dynamically updated, rendered on Metal, and retired.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
if let aImage = model.audioVfsFrame?.image {
|
||||
Image(decorative: aImage, scale: 1)
|
||||
.resizable()
|
||||
.interpolation(.none)
|
||||
.aspectRatio(contentMode: .fit)
|
||||
.frame(maxWidth: .infinity, minHeight: 80, maxHeight: 160)
|
||||
.accessibilityLabel("Audio/VFS guest frame, 2 by 2 pixels")
|
||||
Text("Audio/VFS fixture ran: asset.bin loaded through sandboxed VFS, \(model.audioVfsFrame!.samples) audio samples queued (\(model.audioVfsFrame!.totalAudioBytes) bytes), texture rendered on Metal.")
|
||||
.font(.callout)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
HStack {
|
||||
Button(running ? "Running…" : "Run trusted fixture") { model.run() }
|
||||
.disabled(running || !probe.connected)
|
||||
Button(model.runningTextured ? "Running…" : "Run textured fixture") { model.runTextured() }
|
||||
.disabled(model.runningTextured || !probe.connected)
|
||||
Button(model.runningAudioVfs ? "Running…" : "Run Audio/VFS fixture") { model.runAudioVfs() }
|
||||
.disabled(model.runningAudioVfs || !probe.connected)
|
||||
}
|
||||
}
|
||||
Section("Persistent frame loop") {
|
||||
if let image = loop.image {
|
||||
Image(decorative: image, scale: 1)
|
||||
.resizable()
|
||||
.interpolation(.none)
|
||||
.aspectRatio(contentMode: .fit)
|
||||
.frame(maxWidth: .infinity, minHeight: 120, maxHeight: 240)
|
||||
.accessibilityLabel("Guest frame #\(loop.frameId)")
|
||||
Text("Frame #\(loop.frameId) (\(loop.completed) completed) • \(loop.stateDescription)")
|
||||
.font(.callout)
|
||||
.foregroundStyle(.secondary)
|
||||
} else if let error = loop.errorMessage {
|
||||
Text(error).foregroundStyle(.red)
|
||||
} else if loop.state != UInt32(XENORA_LOOP_NONE) {
|
||||
Text("State: \(loop.stateDescription) • \(loop.completed) completed")
|
||||
.font(.callout)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
HStack {
|
||||
Button("Start 300 frames") { loop.start(frameCount: 300) }
|
||||
.disabled(!loop.canStart || !probe.connected)
|
||||
Button("Interactive (300 frames)") { loop.startInteractive(frameCount: 300) }
|
||||
.disabled(!loop.canStart || !probe.connected)
|
||||
Button("Pause") { loop.pause() }
|
||||
.disabled(!loop.isRunning)
|
||||
Button("Resume") { loop.resume() }
|
||||
.disabled(!loop.isPaused)
|
||||
Button("Stop") { loop.stop() }
|
||||
.disabled(!loop.isRunning && !loop.isPaused)
|
||||
}
|
||||
if loop.isInteractive && (loop.isRunning || loop.isPaused) {
|
||||
HStack {
|
||||
Button("◀ Left") { loop.sendInput(buttons: UInt32(XENORA_INPUT_LEFT)) }
|
||||
Button("▶ Right") { loop.sendInput(buttons: UInt32(XENORA_INPUT_RIGHT)) }
|
||||
Button("Release") { loop.sendInput(buttons: UInt32(XENORA_INPUT_NONE)) }
|
||||
}
|
||||
Text("Interactive guest: steer the rendered strip across columns 0..3 with Left/Right.")
|
||||
.font(.caption)
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
LabeledContent("Runtime", value: probe.connected ? "Connected" : "Unavailable (status \(probe.status))")
|
||||
LabeledContent("Interface version", value: "\(probe.abiVersion)")
|
||||
LabeledContent("Trusted fixture sections", value: "\(probe.sections)")
|
||||
LabeledContent("Trusted fixture entry RVA", value: String(format: "0x%X", probe.entryRVA))
|
||||
Text("Only the bundled trusted fixtures (single-frame, frame-loop, and interactive guest) can run. Presentation uses read-back Metal frames. Arbitrary executables are not available yet.")
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
.formStyle(.grouped)
|
||||
.fileImporter(isPresented: $inspection.importing, allowedContentTypes: [.item]) { result in
|
||||
if case .success(let url) = result { inspection.inspect(url) }
|
||||
}
|
||||
.dropDestination(for: URL.self) { urls, _ in
|
||||
guard let url = urls.first, url.isFileURL else { return false }
|
||||
inspection.inspect(url)
|
||||
return true
|
||||
}
|
||||
.frame(minWidth: 520, minHeight: 680)
|
||||
}
|
||||
}
|
||||
|
||||
struct XenoraApp: App {
|
||||
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
|
||||
let model = FrameModel()
|
||||
let loop = FrameLoopModel()
|
||||
|
||||
var body: some Scene {
|
||||
WindowGroup("Xenora") { ContentView(model: model, loop: loop) }
|
||||
}
|
||||
}
|
||||
|
||||
// `--inspect <path>` prints the read-only report for a file and exits with its status.
|
||||
if let flag = CommandLine.arguments.firstIndex(of: "--inspect"), flag + 1 < CommandLine.arguments.count {
|
||||
let (status, report) = InspectionModel.run(URL(fileURLWithPath: CommandLine.arguments[flag + 1]))
|
||||
print(report.hasSuffix("\n") ? report : report + "\n", terminator: "")
|
||||
print("status=\(status)")
|
||||
exit(status == Int32(XENORA_OK) ? 0 : 1)
|
||||
}
|
||||
|
||||
// `--smoke-resources` tests persistent texture lifecycle, dynamic subregion updates, and retirement on Metal.
|
||||
if CommandLine.arguments.contains("--smoke-resources") {
|
||||
let frame = TexturedFrame.run()
|
||||
print("smoke-resources: \(frame.summary)")
|
||||
let expected: [UInt8] = [255, 255, 0, 255, 0, 255, 255, 255, 255, 0, 255, 255, 64, 64, 64, 255]
|
||||
exit(frame.status == XENORA_OK && frame.width == 2 && frame.height == 2 && frame.rgba == expected ? 0 : 1)
|
||||
}
|
||||
|
||||
// `--smoke-audio-vfs` tests VFS asset loading, PCM audio streaming, and Metal texture presentation.
|
||||
if CommandLine.arguments.contains("--smoke-audio-vfs") {
|
||||
let frame = AudioVfsFrame.run()
|
||||
print("smoke-audio-vfs: \(frame.summary)")
|
||||
let expected: [UInt8] = [255, 128, 0, 255, 128, 0, 255, 255, 0, 255, 128, 255, 255, 0, 128, 255]
|
||||
exit(frame.status == XENORA_OK && frame.width == 2 && frame.height == 2 && frame.samples == 256 && frame.rgba == expected && frame.totalAudioBytes == 512 ? 0 : 1)
|
||||
}
|
||||
|
||||
// `--smoke-interactive` runs 60 frames with queued inputs on the Metal device and exits.
|
||||
if CommandLine.arguments.contains("--smoke-interactive") {
|
||||
var session: xenora_session = 0
|
||||
guard xenora_session_create(XENORA_ABI_VERSION, &session) == XENORA_OK else {
|
||||
print("failed to create session")
|
||||
exit(1)
|
||||
}
|
||||
defer { _ = xenora_session_destroy(session) }
|
||||
guard xenora_session_start_interactive_loop(session, 60) == XENORA_OK else {
|
||||
print("failed to start interactive loop")
|
||||
exit(1)
|
||||
}
|
||||
for f in 0..<60 {
|
||||
let btn: UInt32 = (f < 15) ? UInt32(XENORA_INPUT_RIGHT) :
|
||||
(f < 30) ? UInt32(XENORA_INPUT_NONE) :
|
||||
(f < 45) ? UInt32(XENORA_INPUT_LEFT) : UInt32(XENORA_INPUT_RIGHT)
|
||||
var input = xenora_input_state(buttons: btn, stick_x: 0, stick_y: 0, mouse_dx: 0, mouse_dy: 0, mouse_buttons: 0, connected: 1, reserved: 0)
|
||||
_ = xenora_session_queue_input(session, &input)
|
||||
}
|
||||
var state: UInt32 = 0
|
||||
var completed: UInt32 = 0
|
||||
var frameId: UInt32 = 0
|
||||
var rgba = [UInt8](repeating: 0, count: Int(XENORA_FIXTURE_FRAME_WIDTH * XENORA_FIXTURE_FRAME_HEIGHT * 4))
|
||||
while true {
|
||||
let code = rgba.withUnsafeMutableBufferPointer { buf in
|
||||
xenora_session_frame_loop_status(session, &state, &completed, &frameId, buf.baseAddress, UInt64(buf.count))
|
||||
}
|
||||
if code != XENORA_OK {
|
||||
print("frame_loop_status failed: \(code)")
|
||||
exit(1)
|
||||
}
|
||||
if state != UInt32(XENORA_LOOP_RUNNING) { break }
|
||||
Thread.sleep(forTimeInterval: 0.005)
|
||||
}
|
||||
print("interactive: state=\(state) completed=\(completed) frame_id=\(frameId)")
|
||||
exit(state == UInt32(XENORA_LOOP_FINISHED) && completed == 60 ? 0 : 1)
|
||||
}
|
||||
|
||||
// `--smoke-loop` runs 300 frames on the Metal device and exits; it needs a GPU.
|
||||
if CommandLine.arguments.contains("--smoke-loop") {
|
||||
var session: xenora_session = 0
|
||||
guard xenora_session_create(XENORA_ABI_VERSION, &session) == XENORA_OK else {
|
||||
print("failed to create session")
|
||||
exit(1)
|
||||
}
|
||||
defer { _ = xenora_session_destroy(session) }
|
||||
guard xenora_session_start_frame_loop(session, 300) == XENORA_OK else {
|
||||
print("failed to start frame loop")
|
||||
exit(1)
|
||||
}
|
||||
var state: UInt32 = 0
|
||||
var completed: UInt32 = 0
|
||||
var frameId: UInt32 = 0
|
||||
var rgba = [UInt8](repeating: 0, count: Int(XENORA_FIXTURE_FRAME_WIDTH * XENORA_FIXTURE_FRAME_HEIGHT * 4))
|
||||
while true {
|
||||
let code = rgba.withUnsafeMutableBufferPointer { buf in
|
||||
xenora_session_frame_loop_status(session, &state, &completed, &frameId, buf.baseAddress, UInt64(buf.count))
|
||||
}
|
||||
if code != XENORA_OK {
|
||||
print("frame_loop_status failed: \(code)")
|
||||
exit(1)
|
||||
}
|
||||
if state != UInt32(XENORA_LOOP_RUNNING) { break }
|
||||
Thread.sleep(forTimeInterval: 0.005)
|
||||
}
|
||||
print("state=\(state) completed=\(completed) frame_id=\(frameId)")
|
||||
exit(state == UInt32(XENORA_LOOP_FINISHED) && completed == 300 ? 0 : 1)
|
||||
}
|
||||
|
||||
// `--smoke-frame` runs the trusted fixture on the Metal device and exits; it needs a GPU.
|
||||
if CommandLine.arguments.contains("--smoke-frame") {
|
||||
let frame = GuestFrame.run()
|
||||
print(frame.summary)
|
||||
exit(frame.status == XENORA_OK ? 0 : 1)
|
||||
}
|
||||
|
||||
// `--smoke` prints the probe and exits without opening a window, for scripts and CI.
|
||||
if CommandLine.arguments.contains("--smoke") {
|
||||
let probe = RuntimeProbe.run()
|
||||
print(probe.summary)
|
||||
exit(probe.connected ? 0 : 1)
|
||||
}
|
||||
XenoraApp.main()
|
||||
+54
-18
@@ -4,19 +4,20 @@ use std::fmt;
|
||||
|
||||
pub use xenora_isa::{
|
||||
Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp,
|
||||
ScalarSource, VectorCompareOp, VectorSource,
|
||||
ScalarCompareOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorCompareOp, VectorSource,
|
||||
};
|
||||
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_CMP_EQ_U32, 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,
|
||||
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,
|
||||
};
|
||||
|
||||
use xenora_isa::meta::EncodingFamily;
|
||||
use xenora_isa::semantics::FORM_IDS;
|
||||
pub use xenora_isa::semantics::VectorBinary;
|
||||
|
||||
/// Metadata forms that [`decode`] turns into an [`Instruction`] for at least one
|
||||
/// operand combination: the hand-written forms below followed by every form of
|
||||
@@ -41,7 +42,7 @@ 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); 37] = [
|
||||
const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 36] = [
|
||||
("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf),
|
||||
("BUFFER_STORE_DWORD", EncodingFamily::Mubuf),
|
||||
("EXP", EncodingFamily::Exp),
|
||||
@@ -50,7 +51,6 @@ const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 37] = [
|
||||
("S_CBRANCH_EXECZ", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_SCC0", EncodingFamily::Sopp),
|
||||
("S_CBRANCH_VCCZ", EncodingFamily::Sopp),
|
||||
("S_CMP_EQ_U32", EncodingFamily::Sopc),
|
||||
("S_ENDPGM", EncodingFamily::Sopp),
|
||||
("S_MOV_B32", EncodingFamily::Sop1),
|
||||
("S_WAITCNT", EncodingFamily::Sopp),
|
||||
@@ -375,19 +375,30 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
let (src, len) = scalar_source(first as u8, bytes, "s_mov_b32")?;
|
||||
return Ok((Instruction::ScalarMoveB32 { dst, src }, len));
|
||||
}
|
||||
if S_CMP_EQ_U32.matches(first) {
|
||||
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"));
|
||||
}
|
||||
let (src, len) = scalar_source(first as u8, bytes, mnemonic)?;
|
||||
return Ok((Instruction::ScalarUnary { op, dst, src }, len));
|
||||
}
|
||||
if let Some(op) = ScalarCompareOp::from_word(first) {
|
||||
let mnemonic = op.mnemonic();
|
||||
let src0_bits = first as u8;
|
||||
let src1_bits = (first >> 8) as u8;
|
||||
if src0_bits == 255 && src1_bits == 255 {
|
||||
return Err(unsupported(
|
||||
"s_cmp_eq_u32",
|
||||
mnemonic,
|
||||
"only one source may select a literal",
|
||||
));
|
||||
}
|
||||
let (src0, len0) = scalar_source(src0_bits, bytes, "s_cmp_eq_u32")?;
|
||||
let (src1, len1) = scalar_source(src1_bits, bytes, "s_cmp_eq_u32")?;
|
||||
let (src0, len0) = scalar_source(src0_bits, bytes, mnemonic)?;
|
||||
let (src1, len1) = scalar_source(src1_bits, bytes, mnemonic)?;
|
||||
return Ok((
|
||||
Instruction::ScalarCompareEqU32 { src0, src1 },
|
||||
Instruction::ScalarCompare { op, src0, src1 },
|
||||
len0.max(len1),
|
||||
));
|
||||
}
|
||||
@@ -419,6 +430,21 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
|
||||
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())?;
|
||||
return Ok((
|
||||
Instruction::VectorAlu {
|
||||
op,
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
},
|
||||
len,
|
||||
));
|
||||
}
|
||||
if V_LSHLREV_B32.matches(first) {
|
||||
let (dst, src0, src1) = vop2_registers(first, "v_lshlrev_b32_e32")?;
|
||||
return Ok((
|
||||
@@ -688,10 +714,21 @@ fn vector_compare(
|
||||
first: u32,
|
||||
bytes: &[u8],
|
||||
) -> Result<(Instruction, u8), DecodeErrorKind> {
|
||||
let source = first & 0x1ff;
|
||||
let src1 = ((first >> 9) & 0xff) as u8;
|
||||
let (src0, len) = vector_src0(first, bytes, op.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
|
||||
/// inline integer -16..64 or a literal word; everything else is unsupported.
|
||||
fn vector_src0(
|
||||
first: u32,
|
||||
bytes: &[u8],
|
||||
mnemonic: &'static str,
|
||||
) -> Result<(VectorSource, u8), DecodeErrorKind> {
|
||||
let source = first & 0x1ff;
|
||||
let base_len = 4;
|
||||
let (src0, len) = match source {
|
||||
Ok(match source {
|
||||
0..=106 => (VectorSource::Scalar(source as u8), base_len),
|
||||
128..=192 => (VectorSource::Immediate(source - 128), base_len),
|
||||
193..=208 => (
|
||||
@@ -705,12 +742,11 @@ fn vector_compare(
|
||||
256..=511 => (VectorSource::Register(source as u8), base_len),
|
||||
_ => {
|
||||
return Err(unsupported(
|
||||
op.mnemonic(),
|
||||
mnemonic,
|
||||
"expected a VGPR, normal SGPR, vcc_lo, inline integer or literal",
|
||||
));
|
||||
}
|
||||
};
|
||||
Ok((Instruction::VectorCompare { op, src0, src1 }, len))
|
||||
})
|
||||
}
|
||||
|
||||
fn move_b32(first: u32, bytes: &[u8]) -> Result<(Instruction, u8), DecodeErrorKind> {
|
||||
|
||||
@@ -4,9 +4,13 @@ use std::process::{Command, Stdio};
|
||||
|
||||
use xenora_decoder::{
|
||||
Architecture, CompareRelation, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction,
|
||||
ScalarAluOp, ScalarSource, VectorSource, decode, decode_at,
|
||||
ScalarAluOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorSource, decode, decode_at,
|
||||
};
|
||||
use xenora_isa::semantics::Signedness;
|
||||
use xenora_ref::{
|
||||
BranchCondition, CompareSource, Comparison, Op, ScalarAlu, ScalarUnary, Source, VectorAlu,
|
||||
VectorInteger,
|
||||
};
|
||||
use xenora_ref::{BranchCondition, CompareSource, Comparison, Op, ScalarAlu, Source, VectorAlu};
|
||||
|
||||
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin");
|
||||
const BITWISE_FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/bitwise-branch.bin");
|
||||
@@ -340,6 +344,30 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
ScalarAluOp::AndB32 => ScalarAlu::And,
|
||||
ScalarAluOp::OrB32 => ScalarAlu::Or,
|
||||
ScalarAluOp::XorB32 => ScalarAlu::Xor,
|
||||
ScalarAluOp::Andn2B32 => ScalarAlu::AndNot,
|
||||
ScalarAluOp::Orn2B32 => ScalarAlu::OrNot,
|
||||
ScalarAluOp::NandB32 => ScalarAlu::Nand,
|
||||
ScalarAluOp::NorB32 => ScalarAlu::Nor,
|
||||
ScalarAluOp::XnorB32 => ScalarAlu::Xnor,
|
||||
ScalarAluOp::LshlB32 => ScalarAlu::ShiftLeft,
|
||||
ScalarAluOp::LshrB32 => ScalarAlu::ShiftRight,
|
||||
ScalarAluOp::AshrI32 => ScalarAlu::ArithmeticShiftRight,
|
||||
ScalarAluOp::MinI32 => ScalarAlu::Minimum { signed: true },
|
||||
ScalarAluOp::MinU32 => ScalarAlu::Minimum { signed: false },
|
||||
ScalarAluOp::MaxI32 => ScalarAlu::Maximum { signed: true },
|
||||
ScalarAluOp::MaxU32 => ScalarAlu::Maximum { signed: false },
|
||||
ScalarAluOp::CselectB32 => ScalarAlu::Select,
|
||||
ScalarAluOp::BfmB32 => ScalarAlu::BitfieldMask,
|
||||
ScalarAluOp::MulI32 => ScalarAlu::Multiply,
|
||||
ScalarAluOp::BfeU32 => ScalarAlu::BitfieldExtract { signed: false },
|
||||
ScalarAluOp::BfeI32 => ScalarAlu::BitfieldExtract { signed: true },
|
||||
ScalarAluOp::AbsdiffI32 => ScalarAlu::AbsoluteDifference,
|
||||
ScalarAluOp::Lshl1AddU32 => ScalarAlu::ShiftLeftAdd(1),
|
||||
ScalarAluOp::Lshl2AddU32 => ScalarAlu::ShiftLeftAdd(2),
|
||||
ScalarAluOp::Lshl3AddU32 => ScalarAlu::ShiftLeftAdd(3),
|
||||
ScalarAluOp::Lshl4AddU32 => ScalarAlu::ShiftLeftAdd(4),
|
||||
ScalarAluOp::MulHiU32 => ScalarAlu::MultiplyHigh { signed: false },
|
||||
ScalarAluOp::MulHiI32 => ScalarAlu::MultiplyHigh { signed: true },
|
||||
},
|
||||
dst,
|
||||
reference_scalar(src0),
|
||||
@@ -347,8 +375,38 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
),
|
||||
Instruction::AddNoCarryU32 { dst, src0, src1 } => Op::Add(dst, src0, src1),
|
||||
Instruction::ScalarMoveB32 { dst, src } => Op::ScalarMove(dst, reference_scalar(src)),
|
||||
Instruction::ScalarCompareEqU32 { src0, src1 } => {
|
||||
Op::CompareEqual(reference_scalar(src0), reference_scalar(src1))
|
||||
Instruction::ScalarUnary { op, dst, src } => Op::ScalarUnary(
|
||||
match op {
|
||||
ScalarUnaryOp::NotB32 => ScalarUnary::Not,
|
||||
ScalarUnaryOp::BrevB32 => ScalarUnary::ReverseBits,
|
||||
ScalarUnaryOp::Bcnt0I32B32 => ScalarUnary::CountZeros,
|
||||
ScalarUnaryOp::Bcnt1I32B32 => ScalarUnary::CountOnes,
|
||||
ScalarUnaryOp::Ff0I32B32 => ScalarUnary::FindFirstZero,
|
||||
ScalarUnaryOp::Ff1I32B32 => ScalarUnary::FindFirstOne,
|
||||
ScalarUnaryOp::FlbitI32B32 => ScalarUnary::FindLastBit,
|
||||
ScalarUnaryOp::FlbitI32 => ScalarUnary::FindLastSignBit,
|
||||
ScalarUnaryOp::SextI32I8 => ScalarUnary::SignExtendByte,
|
||||
ScalarUnaryOp::SextI32I16 => ScalarUnary::SignExtendShort,
|
||||
ScalarUnaryOp::AbsI32 => ScalarUnary::Absolute,
|
||||
},
|
||||
dst,
|
||||
reference_scalar(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
|
||||
// offsets (LT 1, EQ 2, LE 3, GT 4, NE 5, GE 6) for the rest.
|
||||
match op.relation() {
|
||||
CompareRelation::Equal => Op::CompareEqual(src0, src1),
|
||||
relation => Op::ScalarCompare(
|
||||
Comparison {
|
||||
offset: relation as u8 + 1,
|
||||
signed: op.semantics().signedness == Signedness::Signed,
|
||||
},
|
||||
src0,
|
||||
src1,
|
||||
),
|
||||
}
|
||||
}
|
||||
Instruction::BranchSccZero { target } => Op::Branch {
|
||||
target,
|
||||
@@ -413,6 +471,34 @@ fn reference_op(instruction: Instruction) -> Op {
|
||||
},
|
||||
src1,
|
||||
),
|
||||
Instruction::VectorAlu {
|
||||
op,
|
||||
dst,
|
||||
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,
|
||||
},
|
||||
dst,
|
||||
match src0 {
|
||||
VectorSource::Register(reg) => CompareSource::Vector(reg),
|
||||
VectorSource::Scalar(reg) => CompareSource::Scalar(reg),
|
||||
VectorSource::Immediate(bits) => CompareSource::Immediate(bits),
|
||||
},
|
||||
src1,
|
||||
),
|
||||
Instruction::EndProgram => Op::End,
|
||||
}
|
||||
}
|
||||
@@ -434,13 +520,18 @@ fn compares_fixture_instructions_against_llvm() {
|
||||
SHIFT_FIXTURE,
|
||||
include_bytes!("../../../fixtures/rdna2/ashr.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-alu.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/scalar-logic.bin"),
|
||||
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/vector-integer.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/vector-compare.bin"),
|
||||
high_registers,
|
||||
&matrix,
|
||||
] {
|
||||
count += compare_against_llvm(fixture, &mut forms);
|
||||
}
|
||||
assert_eq!(forms.len(), 42, "forms compared: {forms:?}");
|
||||
assert_eq!(forms.len(), 100, "forms compared: {forms:?}");
|
||||
eprintln!(
|
||||
"{count} three-way instruction comparisons across {} forms",
|
||||
forms.len()
|
||||
@@ -724,7 +815,13 @@ fn normalize_llvm_assembly(assembly: &str, next_offset: usize) -> String {
|
||||
let target = next_offset + displacement * 4;
|
||||
format!("{mnemonic} -> 0x{target:04x}")
|
||||
}
|
||||
mnemonic if mnemonic.starts_with("v_cmp_") => {
|
||||
// VOPC and the registry VOP2 forms print SRC0 (the second operand) as bits.
|
||||
mnemonic
|
||||
if mnemonic.starts_with("v_cmp_")
|
||||
|| VectorAluOp::ALL
|
||||
.iter()
|
||||
.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]) {
|
||||
Some(bits) => format!("0x{bits:x}"),
|
||||
|
||||
@@ -49,3 +49,11 @@ fn declared_semantic_forms_are_exactly_those_decoded_from_fixtures() {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn registry_forms_do_not_duplicate_hand_written_forms() {
|
||||
// A form declared in the semantic registry and also decoded by hand-written
|
||||
// code would have two implementations; the hand-written one would win.
|
||||
let unique: BTreeSet<_> = SEMANTIC_FORMS.into_iter().collect();
|
||||
assert_eq!(unique.len(), SEMANTIC_FORMS.len());
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
[package]
|
||||
name = "xenora-ffi"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
description = "Versioned C interface between the native macOS application and the Xenora runtime"
|
||||
|
||||
[lib]
|
||||
crate-type = ["staticlib", "rlib"]
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
# Runs the tests that need a native Metal device (scripts/test-gpu.sh).
|
||||
gpu-tests = []
|
||||
|
||||
[dependencies]
|
||||
xenora-loader = { path = "../loader" }
|
||||
xenora-metal = { path = "../metal" }
|
||||
xenora-shader = { path = "../shader" }
|
||||
@@ -0,0 +1,371 @@
|
||||
/* SPDX-License-Identifier: GPL-3.0-or-later */
|
||||
/*
|
||||
* Xenora native application interface, version 1.
|
||||
*
|
||||
* Every function returns a xenora_status. Sessions are identified by opaque
|
||||
* 64-bit handles, never by pointers; 0 is never a valid handle. A destroyed
|
||||
* handle stays invalid even if its slot is reused. Output pointers are owned
|
||||
* by the caller and are written only when the call returns XENORA_OK.
|
||||
* All functions are thread-safe. No Rust panic crosses this boundary: one is
|
||||
* reported as XENORA_INTERNAL_ERROR.
|
||||
*/
|
||||
#ifndef XENORA_H
|
||||
#define XENORA_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#define XENORA_ABI_VERSION 1u
|
||||
|
||||
typedef int32_t xenora_status;
|
||||
enum {
|
||||
XENORA_OK = 0,
|
||||
XENORA_INVALID_ARGUMENT = 1,
|
||||
XENORA_INVALID_HANDLE = 2,
|
||||
XENORA_VERSION_MISMATCH = 3,
|
||||
XENORA_INTERNAL_ERROR = 4,
|
||||
XENORA_PE_ERROR = 5,
|
||||
XENORA_LIMIT_EXCEEDED = 6,
|
||||
XENORA_BUFFER_TOO_SMALL = 7,
|
||||
XENORA_EXECUTION_FAILED = 8,
|
||||
XENORA_INVALID_STATE = 9,
|
||||
};
|
||||
|
||||
/* Frame-loop states reported by xenora_session_frame_loop_status. */
|
||||
enum {
|
||||
XENORA_LOOP_NONE = 0,
|
||||
XENORA_LOOP_RUNNING = 1,
|
||||
XENORA_LOOP_PAUSED = 2,
|
||||
XENORA_LOOP_FINISHED = 3,
|
||||
XENORA_LOOP_STOPPED = 4,
|
||||
XENORA_LOOP_FAILED = 5,
|
||||
};
|
||||
|
||||
#define XENORA_FRAME_LOOP_MAX_FRAMES 100000u
|
||||
/* Frame id reported when no frame has been completed yet. */
|
||||
#define XENORA_NO_FRAME 0xFFFFFFFFu
|
||||
|
||||
/* Input snapshot delivered to guest runtime services (Gate 4, #276). */
|
||||
typedef struct {
|
||||
uint32_t buttons;
|
||||
int16_t stick_x;
|
||||
int16_t stick_y;
|
||||
int16_t mouse_dx;
|
||||
int16_t mouse_dy;
|
||||
uint8_t mouse_buttons;
|
||||
uint8_t connected;
|
||||
uint16_t reserved;
|
||||
} xenora_input_state;
|
||||
|
||||
#define XENORA_INPUT_NONE 0u
|
||||
#define XENORA_INPUT_RIGHT (1u << 0)
|
||||
#define XENORA_INPUT_LEFT (1u << 1)
|
||||
#define XENORA_INPUT_UP (1u << 2)
|
||||
#define XENORA_INPUT_DOWN (1u << 3)
|
||||
#define XENORA_INPUT_ACTION_A (1u << 4)
|
||||
#define XENORA_INPUT_ACTION_B (1u << 5)
|
||||
|
||||
/* Size of the frame drawn by the trusted fixture: RGBA8, rows top to bottom. */
|
||||
#define XENORA_FIXTURE_FRAME_WIDTH 4u
|
||||
#define XENORA_FIXTURE_FRAME_HEIGHT 3u
|
||||
|
||||
typedef uint64_t xenora_session;
|
||||
|
||||
/* The interface version this library implements. */
|
||||
uint32_t xenora_abi_version(void);
|
||||
|
||||
/* Create a session. `abi_version` must equal XENORA_ABI_VERSION. */
|
||||
xenora_status xenora_session_create(uint32_t abi_version, xenora_session *out_session);
|
||||
|
||||
/* Destroy a session. Destroying it again returns XENORA_INVALID_HANDLE. */
|
||||
xenora_status xenora_session_destroy(xenora_session session);
|
||||
|
||||
/* Parse the bundled trusted PE fixture with the runtime loader. No guest code runs. */
|
||||
xenora_status xenora_session_inspect_trusted_fixture(
|
||||
xenora_session session,
|
||||
uint32_t *out_section_count,
|
||||
uint32_t *out_entry_rva);
|
||||
|
||||
/*
|
||||
* Run the bundled trusted PE fixture: its x86-64 code is translated and executed,
|
||||
* and its single draw request is rendered on the native Metal device. On XENORA_OK,
|
||||
* `out_rgba` holds width * height * 4 bytes of the read-back frame, which has been
|
||||
* checked against the fixture shader's known output. `capacity` is the size of
|
||||
* `out_rgba` in bytes. Blocks the calling thread; call it off the main thread.
|
||||
* Only the embedded fixture can run; no caller-supplied executable is accepted.
|
||||
*/
|
||||
xenora_status xenora_session_run_trusted_fixture(
|
||||
xenora_session session,
|
||||
uint8_t *out_rgba,
|
||||
uint64_t capacity,
|
||||
uint32_t *out_width,
|
||||
uint32_t *out_height);
|
||||
|
||||
/*
|
||||
* Persistent rendering (one frame loop per session). Start runs the embedded
|
||||
* frame-loop fixture on a session-owned guest thread: the guest submits frames
|
||||
* 0, 1, 2, ... and each is rendered on native Metal and verified before it
|
||||
* becomes the latest frame. The guest stops after `frame_count` frames
|
||||
* (1..=XENORA_FRAME_LOOP_MAX_FRAMES). Pause holds the guest at its next frame
|
||||
* submission; resume continues it; stop makes it leave its loop and halt, and
|
||||
* waits for its thread. Destroying the session stops the loop first. Starting a
|
||||
* second loop on the same session returns XENORA_INVALID_STATE.
|
||||
*/
|
||||
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_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);
|
||||
xenora_status xenora_session_stop_frame_loop(xenora_session session);
|
||||
|
||||
/*
|
||||
* Retrieve a previously completed frame by sequence index (0 <= frame_index < completed).
|
||||
* Used for deterministic replay verification and frame inspection.
|
||||
*/
|
||||
xenora_status xenora_session_get_recorded_frame(
|
||||
xenora_session session,
|
||||
uint32_t frame_index,
|
||||
uint32_t *out_frame_id,
|
||||
uint8_t *out_rgba,
|
||||
uint64_t capacity
|
||||
);
|
||||
|
||||
/*
|
||||
* Report the loop's state, the number of completed frames, and the latest
|
||||
* verified frame: its id (XENORA_NO_FRAME if none yet) and, when one exists,
|
||||
* its RGBA8 pixels (XENORA_FIXTURE_FRAME_WIDTH x HEIGHT) in `out_rgba`.
|
||||
*/
|
||||
xenora_status xenora_session_frame_loop_status(
|
||||
xenora_session session,
|
||||
uint32_t *out_state,
|
||||
uint32_t *out_completed,
|
||||
uint32_t *out_frame_id,
|
||||
uint8_t *out_rgba,
|
||||
uint64_t capacity);
|
||||
|
||||
/* Largest file xenora_inspect_executable accepts, in bytes. */
|
||||
#define XENORA_MAX_INSPECT_BYTES 268435456u
|
||||
|
||||
/* Opaque persistent GPU resource handle (Gate 5, #279) */
|
||||
typedef uint64_t xenora_resource;
|
||||
#define XENORA_NO_RESOURCE 0u
|
||||
|
||||
enum {
|
||||
XENORA_RESOURCE_TYPE_TEXTURE_2D = 1,
|
||||
XENORA_RESOURCE_TYPE_BUFFER = 2,
|
||||
};
|
||||
|
||||
/*
|
||||
* Create a persistent RGBA8 2D texture owned by the session.
|
||||
* If `initial_rgba` is non-null, it must point to at least width * height * 4 bytes.
|
||||
*/
|
||||
xenora_status xenora_session_create_texture(
|
||||
xenora_session session,
|
||||
uint32_t width,
|
||||
uint32_t height,
|
||||
const uint8_t *initial_rgba,
|
||||
xenora_resource *out_resource
|
||||
);
|
||||
|
||||
/*
|
||||
* Dynamically update a subregion of a persistent texture.
|
||||
*/
|
||||
xenora_status xenora_session_update_texture(
|
||||
xenora_session session,
|
||||
xenora_resource resource,
|
||||
uint32_t x,
|
||||
uint32_t y,
|
||||
uint32_t width,
|
||||
uint32_t height,
|
||||
const uint8_t *rgba,
|
||||
uint64_t byte_count
|
||||
);
|
||||
|
||||
/*
|
||||
* Destroy or retire a persistent resource. If in-flight GPU execution is using
|
||||
* the resource, destruction is deferred until the execution completes.
|
||||
*/
|
||||
xenora_status xenora_session_destroy_resource(
|
||||
xenora_session session,
|
||||
xenora_resource resource
|
||||
);
|
||||
|
||||
/*
|
||||
* Query type, dimensions, and in-flight status of a persistent resource.
|
||||
*/
|
||||
xenora_status xenora_session_resource_info(
|
||||
xenora_session session,
|
||||
xenora_resource resource,
|
||||
uint32_t *out_type,
|
||||
uint32_t *out_width,
|
||||
uint32_t *out_height,
|
||||
uint32_t *out_in_flight
|
||||
);
|
||||
|
||||
/*
|
||||
* Render a frame using a persistent texture resource.
|
||||
*/
|
||||
xenora_status xenora_session_render_textured(
|
||||
xenora_session session,
|
||||
xenora_resource resource,
|
||||
uint8_t *out_rgba,
|
||||
uint64_t capacity,
|
||||
uint32_t *out_width,
|
||||
uint32_t *out_height
|
||||
);
|
||||
|
||||
/*
|
||||
* Run the original textured PE fixture and verify its read-back frame.
|
||||
*/
|
||||
xenora_status xenora_session_run_textured_fixture(
|
||||
xenora_session session,
|
||||
uint8_t *out_rgba,
|
||||
uint64_t capacity,
|
||||
uint32_t *out_width,
|
||||
uint32_t *out_height
|
||||
);
|
||||
|
||||
/* Audio subsystem (Gate 6, #284) */
|
||||
typedef uint32_t xenora_audio_format;
|
||||
enum {
|
||||
XENORA_AUDIO_FORMAT_PCM_S16LE = 1,
|
||||
XENORA_AUDIO_FORMAT_PCM_F32LE = 2,
|
||||
};
|
||||
|
||||
/*
|
||||
* Initialize the audio subsystem for a session.
|
||||
*/
|
||||
xenora_status xenora_session_audio_init(
|
||||
xenora_session session,
|
||||
uint32_t sample_rate,
|
||||
uint32_t channels,
|
||||
xenora_audio_format format
|
||||
);
|
||||
|
||||
/*
|
||||
* Submit PCM audio bytes into the session audio queue.
|
||||
*/
|
||||
xenora_status xenora_session_audio_submit(
|
||||
xenora_session session,
|
||||
const uint8_t *pcm_bytes,
|
||||
uint64_t byte_count
|
||||
);
|
||||
|
||||
/*
|
||||
* Read PCM audio bytes from the session audio queue.
|
||||
*/
|
||||
xenora_status xenora_session_audio_read(
|
||||
xenora_session session,
|
||||
uint8_t *out_pcm,
|
||||
uint64_t capacity,
|
||||
uint64_t *out_bytes_read
|
||||
);
|
||||
|
||||
/*
|
||||
* Query current audio queue status: queued bytes, underruns, total submitted.
|
||||
*/
|
||||
xenora_status xenora_session_audio_status(
|
||||
xenora_session session,
|
||||
uint32_t *out_queued_bytes,
|
||||
uint32_t *out_underruns,
|
||||
uint64_t *out_total_submitted
|
||||
);
|
||||
|
||||
/*
|
||||
* Set audio volume (0.0 to 1.0) and mute state (non-zero = muted).
|
||||
*/
|
||||
xenora_status xenora_session_audio_set_volume(
|
||||
xenora_session session,
|
||||
float volume,
|
||||
uint32_t muted
|
||||
);
|
||||
|
||||
/* Virtual Filesystem (Gate 6, #284) */
|
||||
typedef uint64_t xenora_file;
|
||||
#define XENORA_NO_FILE 0u
|
||||
|
||||
enum {
|
||||
XENORA_SEEK_SET = 0,
|
||||
XENORA_SEEK_CUR = 1,
|
||||
XENORA_SEEK_END = 2,
|
||||
};
|
||||
|
||||
/*
|
||||
* Set the sandboxed root directory for the session virtual filesystem.
|
||||
*/
|
||||
xenora_status xenora_session_vfs_set_root(
|
||||
xenora_session session,
|
||||
const char *root_path
|
||||
);
|
||||
|
||||
/*
|
||||
* Open a file within the virtual filesystem sandboxed root.
|
||||
*/
|
||||
xenora_status xenora_session_vfs_open(
|
||||
xenora_session session,
|
||||
const char *rel_path,
|
||||
uint32_t flags,
|
||||
xenora_file *out_file
|
||||
);
|
||||
|
||||
/*
|
||||
* Read bytes from an open virtual file.
|
||||
*/
|
||||
xenora_status xenora_session_vfs_read(
|
||||
xenora_session session,
|
||||
xenora_file file,
|
||||
uint8_t *out_buffer,
|
||||
uint64_t count,
|
||||
uint64_t *out_bytes_read
|
||||
);
|
||||
|
||||
/*
|
||||
* Seek within an open virtual file.
|
||||
*/
|
||||
xenora_status xenora_session_vfs_seek(
|
||||
xenora_session session,
|
||||
xenora_file file,
|
||||
int64_t offset,
|
||||
uint32_t whence,
|
||||
uint64_t *out_new_offset
|
||||
);
|
||||
|
||||
/*
|
||||
* Close an open virtual file.
|
||||
*/
|
||||
xenora_status xenora_session_vfs_close(
|
||||
xenora_session session,
|
||||
xenora_file file
|
||||
);
|
||||
|
||||
/*
|
||||
* Run the original audio and VFS PE fixture.
|
||||
*/
|
||||
xenora_status xenora_session_run_audio_vfs_fixture(
|
||||
xenora_session session,
|
||||
uint8_t *out_rgba,
|
||||
uint64_t capacity,
|
||||
uint32_t *out_width,
|
||||
uint32_t *out_height,
|
||||
uint32_t *out_audio_samples
|
||||
);
|
||||
|
||||
/*
|
||||
* Read-only compatibility inspection of a caller-supplied PE file. Nothing in
|
||||
* `bytes` is executed: it is parsed and statically disassembled (bounded) only.
|
||||
* On XENORA_OK, XENORA_PE_ERROR or XENORA_INTERNAL_ERROR, `out_report` holds a
|
||||
* NUL-terminated UTF-8 report of `*out_required` bytes including the NUL.
|
||||
* XENORA_PE_ERROR means the file is not an acceptable PE32+ image;
|
||||
* XENORA_INTERNAL_ERROR means Xenora's own probe failed on it. The report says which. If `capacity`
|
||||
* is too small the call returns XENORA_BUFFER_TOO_SMALL with `*out_required`
|
||||
* set and nothing else written. Files over XENORA_MAX_INSPECT_BYTES return
|
||||
* XENORA_LIMIT_EXCEEDED.
|
||||
*/
|
||||
xenora_status xenora_inspect_executable(
|
||||
const uint8_t *bytes,
|
||||
uint64_t length,
|
||||
char *out_report,
|
||||
uint64_t capacity,
|
||||
uint64_t *out_required);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,332 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Persistent guest rendering for one session (Gate 3, #266).
|
||||
//!
|
||||
//! The embedded `frame-loop.exe` fixture calls `xenora.dll!frame_submit(index)`
|
||||
//! with index 0, 1, 2, ... and halts when the call returns 0. The guest runs on
|
||||
//! its own thread for the session's lifetime. Pause, resume and stop act at the
|
||||
//! frame-submit boundary: a paused guest waits inside that call with its
|
||||
//! architectural state untouched, and a stop request makes the call return 0 so
|
||||
//! the guest leaves its loop and halts.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock};
|
||||
use std::thread::JoinHandle;
|
||||
|
||||
use xenora_loader::startup::{StartupLayout, run_synthetic_startup};
|
||||
use xenora_loader::{ExitReason, ImportRegistry, Register};
|
||||
use xenora_metal::NativeCompute;
|
||||
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
|
||||
|
||||
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/frame-loop.exe");
|
||||
const INTERACTIVE_FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/interactive.exe");
|
||||
pub const WIDTH: usize = 4;
|
||||
pub const HEIGHT: usize = 3;
|
||||
pub const FRAME_BYTES: usize = WIDTH * HEIGHT * 4;
|
||||
pub const MAX_FRAMES: u32 = 100_000;
|
||||
/// Guest instructions per loop iteration (mov, call, inc, test, jnz) plus slack.
|
||||
const STEPS_PER_FRAME: usize = 8;
|
||||
const STEPS_PER_INTERACTIVE_FRAME: usize = 24;
|
||||
/// `x9-constant-ps.s` exports (1, 0, 0, 1): opaque red. Everything else is the clear colour.
|
||||
const RED: [u8; 4] = [255, 0, 0, 255];
|
||||
const CLEAR: [u8; 4] = [19, 43, 93, 251];
|
||||
|
||||
pub const RUNNING: u32 = 1;
|
||||
pub const PAUSED: u32 = 2;
|
||||
pub const FINISHED: u32 = 3;
|
||||
pub const STOPPED: u32 = 4;
|
||||
pub const FAILED: u32 = 5;
|
||||
|
||||
#[derive(Default, Copy, Clone)]
|
||||
#[repr(C)]
|
||||
pub struct InputState {
|
||||
pub buttons: u32,
|
||||
pub stick_x: i16,
|
||||
pub stick_y: i16,
|
||||
pub mouse_dx: i16,
|
||||
pub mouse_dy: i16,
|
||||
pub mouse_buttons: u8,
|
||||
pub connected: u8,
|
||||
pub reserved: u16,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
status: u32,
|
||||
paused: bool,
|
||||
stop: bool,
|
||||
interactive: bool,
|
||||
limit: u32,
|
||||
completed: u32,
|
||||
input: InputState,
|
||||
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.
|
||||
calls: u64,
|
||||
latest: Option<(u32, Vec<u8>)>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct FrameLoop {
|
||||
state: Mutex<State>,
|
||||
wake: Condvar,
|
||||
thread: Mutex<Option<JoinHandle<()>>>,
|
||||
}
|
||||
|
||||
pub struct Snapshot {
|
||||
pub status: u32,
|
||||
pub completed: u32,
|
||||
pub latest: Option<(u32, Vec<u8>)>,
|
||||
}
|
||||
|
||||
impl FrameLoop {
|
||||
fn lock(&self) -> MutexGuard<'_, State> {
|
||||
self.state
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
}
|
||||
|
||||
pub fn start(limit: u32, interactive: bool) -> Arc<Self> {
|
||||
let shared = Arc::new(Self::default());
|
||||
{
|
||||
let mut state = shared.lock();
|
||||
state.status = RUNNING;
|
||||
state.limit = limit;
|
||||
state.interactive = interactive;
|
||||
}
|
||||
let guest = Arc::clone(&shared);
|
||||
let handle = std::thread::Builder::new()
|
||||
.name("xenora-guest".into())
|
||||
.spawn(move || guest.run())
|
||||
.ok();
|
||||
if handle.is_none() {
|
||||
shared.lock().status = FAILED;
|
||||
}
|
||||
*shared.thread.lock().unwrap_or_else(|p| p.into_inner()) = handle;
|
||||
shared
|
||||
}
|
||||
|
||||
/// Pause or resume. Returns false unless the loop is running or paused.
|
||||
pub fn set_paused(&self, paused: bool) -> bool {
|
||||
let mut state = self.lock();
|
||||
if !matches!(state.status, RUNNING | PAUSED) {
|
||||
return false;
|
||||
}
|
||||
state.paused = paused;
|
||||
state.status = if paused { PAUSED } else { RUNNING };
|
||||
self.wake.notify_all();
|
||||
true
|
||||
}
|
||||
|
||||
/// Ask the guest to stop at its next frame submission and wait for its thread.
|
||||
pub fn stop(&self) {
|
||||
{
|
||||
let mut state = self.lock();
|
||||
state.stop = true;
|
||||
self.wake.notify_all();
|
||||
}
|
||||
if let Some(handle) = self.thread.lock().unwrap_or_else(|p| p.into_inner()).take() {
|
||||
let _ = handle.join();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn send_input(&self, input: InputState) {
|
||||
let mut state = self.lock();
|
||||
state.input = input;
|
||||
}
|
||||
|
||||
pub fn queue_input(&self, input: InputState) {
|
||||
let mut state = self.lock();
|
||||
state.input_queue.push_back(input);
|
||||
}
|
||||
|
||||
pub fn get_recorded_frame(&self, index: usize) -> Option<(u32, Vec<u8>)> {
|
||||
let state = self.lock();
|
||||
state.recorded_frames.get(index).cloned()
|
||||
}
|
||||
|
||||
pub fn snapshot(&self) -> Snapshot {
|
||||
let state = self.lock();
|
||||
Snapshot {
|
||||
status: state.status,
|
||||
completed: state.completed,
|
||||
latest: state.latest.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn run(self: Arc<Self>) {
|
||||
let outcome = self.execute();
|
||||
let mut state = self.lock();
|
||||
state.status = match outcome {
|
||||
Err(_) => FAILED,
|
||||
Ok(()) if state.stop && state.completed < state.limit => STOPPED,
|
||||
Ok(()) => FINISHED,
|
||||
};
|
||||
}
|
||||
|
||||
fn execute(self: &Arc<Self>) -> Result<(), String> {
|
||||
let shader = compile_graphics(
|
||||
Architecture::Gfx1030,
|
||||
include_bytes!("../../../fixtures/rdna2/x9-constant-vs.bin"),
|
||||
include_bytes!("../../../fixtures/rdna2/x9-constant-ps.bin"),
|
||||
)
|
||||
.map_err(|e| format!("shader translation: {e}"))?;
|
||||
let gpu = shared_gpu()?;
|
||||
// The import runs on the guest thread, so the session's shader lives there too.
|
||||
GPU.with(|slot| *slot.borrow_mut() = Some((gpu, shader.msl)));
|
||||
|
||||
let shared = Arc::clone(self);
|
||||
let mut imports = ImportRegistry::new();
|
||||
imports.register("xenora.dll", "frame_submit", move |args, _, memory| {
|
||||
let index = args.get(0, memory).map_err(ExitReason::MemoryFault)?;
|
||||
shared
|
||||
.submit(index)
|
||||
.ok_or(ExitReason::IllegalInstruction(0xff))
|
||||
});
|
||||
if self.lock().interactive {
|
||||
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 cmd = if input.buttons & crate::XENORA_INPUT_RIGHT != 0 {
|
||||
1u64
|
||||
} else if input.buttons & crate::XENORA_INPUT_LEFT != 0 {
|
||||
2u64
|
||||
} else {
|
||||
0u64
|
||||
};
|
||||
Ok(cmd)
|
||||
});
|
||||
}
|
||||
let limit = self.lock().limit as usize;
|
||||
let is_interactive = self.lock().interactive;
|
||||
let fixture_bytes = if is_interactive {
|
||||
INTERACTIVE_FIXTURE
|
||||
} else {
|
||||
FIXTURE
|
||||
};
|
||||
let steps_per_frame = if is_interactive {
|
||||
STEPS_PER_INTERACTIVE_FRAME
|
||||
} else {
|
||||
STEPS_PER_FRAME
|
||||
};
|
||||
let startup = run_synthetic_startup(
|
||||
fixture_bytes,
|
||||
StartupLayout {
|
||||
image_base: 0x1_4000_0000,
|
||||
stack_top: 0x2_0001_0000,
|
||||
tls_base: 0x3_0000_0000,
|
||||
},
|
||||
imports,
|
||||
(limit + 1) * steps_per_frame + 32,
|
||||
)
|
||||
.map_err(|e| format!("startup: {e}"));
|
||||
GPU.with(|slot| slot.borrow_mut().take());
|
||||
let startup = startup?;
|
||||
let calls = self.lock().calls;
|
||||
let rbx = startup.execution.final_state.get(Register::Rbx);
|
||||
if startup.execution.exit_reason != ExitReason::Halt {
|
||||
return Err(format!(
|
||||
"guest ended with {:?}",
|
||||
startup.execution.exit_reason
|
||||
));
|
||||
}
|
||||
if !is_interactive && rbx != calls {
|
||||
return Err(format!("guest ended with rbx={rbx}, calls={calls}"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Handle one `frame_submit`: wait while paused, then render and verify the
|
||||
/// frame. `None` fails the guest; `Some(0)` tells it to stop.
|
||||
fn submit(&self, index: u64) -> Option<u64> {
|
||||
let mut state = self.lock();
|
||||
state.calls += 1;
|
||||
while state.paused && !state.stop {
|
||||
state = self.wake.wait(state).unwrap_or_else(|p| p.into_inner());
|
||||
}
|
||||
if state.stop || state.completed >= state.limit {
|
||||
return Some(0);
|
||||
}
|
||||
if state.interactive {
|
||||
if index >= WIDTH as u64 {
|
||||
return None; // column must be inside 0..WIDTH
|
||||
}
|
||||
} else if index != u64::from(state.completed) {
|
||||
return None; // frame identities must arrive in order
|
||||
}
|
||||
drop(state);
|
||||
let pixels = render(index as u32)?;
|
||||
let mut state = self.lock();
|
||||
state.completed += 1;
|
||||
state.latest = Some((index as u32, pixels.clone()));
|
||||
if state.interactive {
|
||||
state.recorded_frames.push((index as u32, pixels));
|
||||
}
|
||||
Some(u64::from(state.completed < state.limit && !state.stop))
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static GPU: RefCell<Option<(&'static NativeCompute, String)>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
/// One Metal device and command queue shared by every frame-loop session (#290).
|
||||
///
|
||||
/// The first command buffer submitted on a queue makes the GPU driver allocate a
|
||||
/// working set for it (about 45 MiB on an Apple M5 with Metal validation), and the
|
||||
/// driver frees that memory asynchronously, 10–50 ms after the queue is released.
|
||||
/// A queue per session therefore allocated and freed it once per session, and the
|
||||
/// process footprint depended on how far that release had progressed. One queue
|
||||
/// for the process allocates the working set once and keeps it: bounded caching,
|
||||
/// not per-session churn. `NativeCompute` is `Send + Sync`, and rendering takes
|
||||
/// `&self`, so concurrent sessions can share it. A device that cannot be opened
|
||||
/// is reported to every session that asks.
|
||||
fn shared_gpu() -> Result<&'static NativeCompute, String> {
|
||||
static SHARED: OnceLock<Result<NativeCompute, String>> = OnceLock::new();
|
||||
SHARED
|
||||
.get_or_init(|| NativeCompute::new().map_err(|e| format!("Metal device: {e}")))
|
||||
.as_ref()
|
||||
.map_err(Clone::clone)
|
||||
}
|
||||
|
||||
/// Frame `index` is a red strip in column `index % 4` on the clear colour.
|
||||
///
|
||||
/// The triangle (x0, -10), (x0 + 0.7, 0), (x0, 10) in clip space, with x0 the
|
||||
/// column's left edge, covers that column's pixel centres in all three rows and
|
||||
/// none of its neighbours'.
|
||||
fn render(index: u32) -> Option<Vec<u8>> {
|
||||
let column = (index as usize % WIDTH) as f32;
|
||||
let x0 = -1.0 + column * (2.0 / WIDTH as f32);
|
||||
let pixels = GPU.with(|slot| {
|
||||
let slot = slot.borrow();
|
||||
let (gpu, msl) = slot.as_ref()?;
|
||||
gpu.render_rgba8(
|
||||
msl,
|
||||
[VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT],
|
||||
&[
|
||||
[x0, -10.0, 0.5, 1.0],
|
||||
[x0 + 0.7, 0.0, 0.5, 1.0],
|
||||
[x0, 10.0, 0.5, 1.0],
|
||||
],
|
||||
&[[0.0; 4]; 3],
|
||||
[WIDTH, HEIGHT],
|
||||
CLEAR,
|
||||
)
|
||||
.ok()
|
||||
})?;
|
||||
(pixels == expected(index)).then_some(pixels)
|
||||
}
|
||||
|
||||
/// The expected frame for `index`, from the strip rule alone.
|
||||
pub fn expected(index: u32) -> Vec<u8> {
|
||||
(0..WIDTH * HEIGHT)
|
||||
.flat_map(|pixel| {
|
||||
if pixel % WIDTH == index as usize % WIDTH {
|
||||
RED
|
||||
} else {
|
||||
CLEAR
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,374 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Gate 6 acceptance on a native Metal device: audio PCM streaming and
|
||||
//! sandboxed virtual filesystem (VFS) integration through the C interface (#284).
|
||||
//! Needs `--features gpu-tests` (scripts/test-gpu.sh).
|
||||
#![cfg(feature = "gpu-tests")]
|
||||
|
||||
use std::sync::Mutex;
|
||||
use xenora_ffi::*;
|
||||
|
||||
/// Tests share the process-wide session table and one GPU; run them one at a time.
|
||||
static SERIAL: Mutex<()> = Mutex::new(());
|
||||
|
||||
fn lock_serial() -> std::sync::MutexGuard<'static, ()> {
|
||||
SERIAL.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
fn session() -> u64 {
|
||||
let mut handle = 0;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut handle) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_ne!(handle, 0);
|
||||
handle
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_pcm_queue_streaming_ordering_and_volume() {
|
||||
let _guard = lock_serial();
|
||||
let sess = session();
|
||||
|
||||
// Rejection on invalid arguments
|
||||
assert_eq!(
|
||||
xenora_session_audio_init(sess, 0, 2, XENORA_AUDIO_FORMAT_PCM_S16LE),
|
||||
XENORA_INVALID_ARGUMENT
|
||||
);
|
||||
assert_eq!(
|
||||
xenora_session_audio_init(0xdead_beef, 48000, 2, XENORA_AUDIO_FORMAT_PCM_S16LE),
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
|
||||
// Initialize 48000 Hz stereo 16-bit PCM
|
||||
assert_eq!(
|
||||
xenora_session_audio_init(sess, 48000, 2, XENORA_AUDIO_FORMAT_PCM_S16LE),
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
// Initial status should be empty
|
||||
let (mut queued, mut underruns, mut total) = (0u32, 0u32, 0u64);
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_audio_status(sess, &mut queued, &mut underruns, &mut total) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(queued, 0);
|
||||
assert_eq!(underruns, 0);
|
||||
assert_eq!(total, 0);
|
||||
|
||||
// Generate known PCM samples: 100 stereo samples (400 bytes)
|
||||
let mut pcm = Vec::with_capacity(400);
|
||||
for i in 0..100i16 {
|
||||
let left = i * 100;
|
||||
let right = -left;
|
||||
pcm.extend_from_slice(&left.to_le_bytes());
|
||||
pcm.extend_from_slice(&right.to_le_bytes());
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_audio_submit(sess, pcm.as_ptr(), pcm.len() as u64) },
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_audio_status(sess, &mut queued, &mut underruns, &mut total) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(queued, 400);
|
||||
assert_eq!(total, 400);
|
||||
assert_eq!(underruns, 0);
|
||||
|
||||
// Read back first 50 samples (200 bytes)
|
||||
let mut read_buf = vec![0u8; 200];
|
||||
let mut bytes_read = 0u64;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_audio_read(sess, read_buf.as_mut_ptr(), 200, &mut bytes_read) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(bytes_read, 200);
|
||||
assert_eq!(&read_buf[..], &pcm[..200]);
|
||||
|
||||
// Volume attenuation: set to 0.5
|
||||
assert_eq!(xenora_session_audio_set_volume(sess, 0.5, 0), XENORA_OK);
|
||||
|
||||
// Submit 2 stereo samples (8 bytes): 2000, -2000, 4000, -4000
|
||||
let mut half_vol_in = Vec::new();
|
||||
half_vol_in.extend_from_slice(&2000i16.to_le_bytes());
|
||||
half_vol_in.extend_from_slice(&(-2000i16).to_le_bytes());
|
||||
half_vol_in.extend_from_slice(&4000i16.to_le_bytes());
|
||||
half_vol_in.extend_from_slice(&(-4000i16).to_le_bytes());
|
||||
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_audio_submit(sess, half_vol_in.as_ptr(), half_vol_in.len() as u64)
|
||||
},
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
// Read remaining 200 bytes from first batch
|
||||
let mut drain = vec![0u8; 200];
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_audio_read(sess, drain.as_mut_ptr(), 200, &mut bytes_read) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(bytes_read, 200);
|
||||
assert_eq!(&drain[..], &pcm[200..]);
|
||||
|
||||
// Now read the 8 bytes attenuated samples
|
||||
let mut attenuated = vec![0u8; 8];
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_audio_read(sess, attenuated.as_mut_ptr(), 8, &mut bytes_read) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(bytes_read, 8);
|
||||
let s0 = i16::from_le_bytes([attenuated[0], attenuated[1]]);
|
||||
let s1 = i16::from_le_bytes([attenuated[2], attenuated[3]]);
|
||||
let s2 = i16::from_le_bytes([attenuated[4], attenuated[5]]);
|
||||
let s3 = i16::from_le_bytes([attenuated[6], attenuated[7]]);
|
||||
assert_eq!(s0, 1000);
|
||||
assert_eq!(s1, -1000);
|
||||
assert_eq!(s2, 2000);
|
||||
assert_eq!(s3, -2000);
|
||||
|
||||
// Test mute (muted = 1)
|
||||
assert_eq!(xenora_session_audio_set_volume(sess, 1.0, 1), XENORA_OK);
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_audio_submit(sess, half_vol_in.as_ptr(), half_vol_in.len() as u64)
|
||||
},
|
||||
XENORA_OK
|
||||
);
|
||||
let mut muted_out = vec![0u8; 8];
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_audio_read(sess, muted_out.as_mut_ptr(), 8, &mut bytes_read) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(muted_out, vec![0u8; 8]);
|
||||
|
||||
xenora_session_destroy(sess);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn virtual_filesystem_sandboxing_and_traversal_rejection() {
|
||||
let _guard = lock_serial();
|
||||
let sess = session();
|
||||
|
||||
let mut file = 0u64;
|
||||
|
||||
// Reject non-existent root
|
||||
let bad_root = std::ffi::CString::new("/nonexistent_dir_xenora").unwrap();
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_vfs_set_root(sess, bad_root.as_ptr()) },
|
||||
XENORA_INVALID_ARGUMENT
|
||||
);
|
||||
|
||||
// Set valid root
|
||||
let root_path = if std::path::Path::new("fixtures/assets").exists() {
|
||||
"fixtures/assets"
|
||||
} else {
|
||||
"../../fixtures/assets"
|
||||
};
|
||||
let c_root = std::ffi::CString::new(root_path).unwrap();
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_vfs_set_root(sess, c_root.as_ptr()) },
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
// Traversal attacks rejected
|
||||
for bad in &[
|
||||
"../escape.txt",
|
||||
"../../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());
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_vfs_open(sess, bad_c.as_ptr(), 0, &mut file) },
|
||||
XENORA_INVALID_ARGUMENT,
|
||||
"traversal attempt '{}' was not rejected",
|
||||
bad
|
||||
);
|
||||
}
|
||||
|
||||
// Open existing valid asset
|
||||
let good = std::ffi::CString::new("asset.bin").unwrap();
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_vfs_open(sess, good.as_ptr(), 0, &mut file) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_ne!(file, XENORA_NO_FILE);
|
||||
|
||||
// Read header (20 bytes: 4B magic + 4B ver + 4B width + 4B height + 4B audio_samples)
|
||||
let mut header = [0u8; 20];
|
||||
let mut read_bytes = 0u64;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_vfs_read(sess, file, header.as_mut_ptr(), 20, &mut read_bytes) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(read_bytes, 20);
|
||||
assert_eq!(&header[0..4], b"XAST");
|
||||
let version = u32::from_le_bytes([header[4], header[5], header[6], header[7]]);
|
||||
assert_eq!(version, 1);
|
||||
let width = u32::from_le_bytes([header[8], header[9], header[10], header[11]]);
|
||||
assert_eq!(width, 2);
|
||||
let height = u32::from_le_bytes([header[12], header[13], header[14], header[15]]);
|
||||
assert_eq!(height, 2);
|
||||
let audio_samples = u32::from_le_bytes([header[16], header[17], header[18], header[19]]);
|
||||
assert_eq!(audio_samples, 256);
|
||||
|
||||
// Seek to audio offset (36) using SEEK_SET
|
||||
let mut new_pos = 0u64;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_vfs_seek(sess, file, 36, XENORA_SEEK_SET, &mut new_pos) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(new_pos, 36);
|
||||
|
||||
// Read 4 bytes of audio
|
||||
let mut sample_bytes = [0u8; 4];
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_vfs_read(sess, file, sample_bytes.as_mut_ptr(), 4, &mut read_bytes)
|
||||
},
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(read_bytes, 4);
|
||||
|
||||
// Seek using SEEK_END
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_vfs_seek(sess, file, 0, XENORA_SEEK_END, &mut new_pos) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(new_pos, 20 + 16 + 512); // total asset size = 548 bytes
|
||||
|
||||
// Close file
|
||||
assert_eq!(xenora_session_vfs_close(sess, file), XENORA_OK);
|
||||
|
||||
// Double close rejected
|
||||
assert_eq!(xenora_session_vfs_close(sess, file), XENORA_INVALID_HANDLE);
|
||||
|
||||
xenora_session_destroy(sess);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_vfs_guest_fixture_executes_asset_load_and_pcm_stream() {
|
||||
let _guard = lock_serial();
|
||||
let sess = session();
|
||||
|
||||
let mut out_rgba = [0u8; 16];
|
||||
let mut out_w = 0u32;
|
||||
let mut out_h = 0u32;
|
||||
let mut out_samples = 0u32;
|
||||
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_run_audio_vfs_fixture(
|
||||
sess,
|
||||
out_rgba.as_mut_ptr(),
|
||||
16,
|
||||
&mut out_w,
|
||||
&mut out_h,
|
||||
&mut out_samples,
|
||||
)
|
||||
},
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
assert_eq!(out_w, 2);
|
||||
assert_eq!(out_h, 2);
|
||||
assert_eq!(out_samples, 256);
|
||||
|
||||
// Expected texture from asset.bin: 2x2 RGBA8:
|
||||
// (0,0): Orange [255, 128, 0, 255]
|
||||
// (1,0): Purple [128, 0, 255, 255]
|
||||
// (0,1): Teal [0, 255, 128, 255]
|
||||
// (1,1): Pink [255, 0, 128, 255]
|
||||
let expected_rgba: [u8; 16] = [
|
||||
255, 128, 0, 255, 128, 0, 255, 255, 0, 255, 128, 255, 255, 0, 128, 255,
|
||||
];
|
||||
assert_eq!(
|
||||
out_rgba, expected_rgba,
|
||||
"Metal rendered frame did not match asset texture"
|
||||
);
|
||||
|
||||
// Audio status: guest submitted 256 samples (512 bytes)
|
||||
let (mut queued, mut underruns, mut total) = (0u32, 0u32, 0u64);
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_audio_status(sess, &mut queued, &mut underruns, &mut total) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(queued, 512);
|
||||
assert_eq!(total, 512);
|
||||
assert_eq!(underruns, 0);
|
||||
|
||||
// Read back submitted audio samples and verify
|
||||
let mut pcm_buf = vec![0u8; 512];
|
||||
let mut read_bytes = 0u64;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_audio_read(sess, pcm_buf.as_mut_ptr(), 512, &mut read_bytes) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(read_bytes, 512);
|
||||
|
||||
// The first sample in asset.bin sine wave is 0
|
||||
let s0 = i16::from_le_bytes([pcm_buf[0], pcm_buf[1]]);
|
||||
assert_eq!(s0, 0);
|
||||
|
||||
xenora_session_destroy(sess);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_vfs_rejection_of_invalid_and_stale_handles() {
|
||||
let _guard = lock_serial();
|
||||
let dead_sess = 0xdead_beefu64;
|
||||
|
||||
let mut queued = 0u32;
|
||||
let mut underruns = 0u32;
|
||||
let mut total = 0u64;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_audio_status(dead_sess, &mut queued, &mut underruns, &mut total) },
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
|
||||
let mut file = 0u64;
|
||||
let path = std::ffi::CString::new("asset.bin").unwrap();
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_vfs_open(dead_sess, path.as_ptr(), 0, &mut file) },
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
|
||||
let sess = session();
|
||||
// Null pointer checks
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_vfs_open(sess, std::ptr::null(), 0, &mut file) },
|
||||
XENORA_INVALID_ARGUMENT
|
||||
);
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_vfs_open(sess, path.as_ptr(), 0, std::ptr::null_mut()) },
|
||||
XENORA_INVALID_ARGUMENT
|
||||
);
|
||||
|
||||
// Buffer too small for fixture
|
||||
let mut small_buf = [0u8; 8];
|
||||
let mut w = 0u32;
|
||||
let mut h = 0u32;
|
||||
let mut samples = 0u32;
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_run_audio_vfs_fixture(
|
||||
sess,
|
||||
small_buf.as_mut_ptr(),
|
||||
8,
|
||||
&mut w,
|
||||
&mut h,
|
||||
&mut samples,
|
||||
)
|
||||
},
|
||||
XENORA_BUFFER_TOO_SMALL
|
||||
);
|
||||
|
||||
xenora_session_destroy(sess);
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Gate 3 acceptance on a native Metal device: persistent guest rendering through
|
||||
//! the C interface. Needs `--features gpu-tests` (scripts/test-gpu.sh).
|
||||
#![cfg(feature = "gpu-tests")]
|
||||
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
use xenora_ffi::*;
|
||||
|
||||
/// Tests share the process-wide session table and one GPU; run them one at a time.
|
||||
static SERIAL: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// Expected frame `id`, derived only from the geometry: the guest's frame index picks
|
||||
/// column `id % 4`, which is opaque red (x9-constant-ps exports (1, 0, 0, 1)); the
|
||||
/// other columns keep the clear colour (19, 43, 93, 251).
|
||||
fn expected(id: u32) -> Vec<u8> {
|
||||
let mut frame = Vec::new();
|
||||
for _row in 0..3 {
|
||||
for column in 0..4 {
|
||||
if column == id % 4 {
|
||||
frame.extend([255, 0, 0, 255]);
|
||||
} else {
|
||||
frame.extend([19, 43, 93, 251]);
|
||||
}
|
||||
}
|
||||
}
|
||||
frame
|
||||
}
|
||||
|
||||
struct Status {
|
||||
state: u32,
|
||||
completed: u32,
|
||||
frame_id: u32,
|
||||
rgba: [u8; 48],
|
||||
}
|
||||
|
||||
fn status(session: u64) -> Status {
|
||||
let mut s = Status {
|
||||
state: 99,
|
||||
completed: 0,
|
||||
frame_id: 0,
|
||||
rgba: [0; 48],
|
||||
};
|
||||
let code = unsafe {
|
||||
xenora_session_frame_loop_status(
|
||||
session,
|
||||
&mut s.state,
|
||||
&mut s.completed,
|
||||
&mut s.frame_id,
|
||||
s.rgba.as_mut_ptr(),
|
||||
48,
|
||||
)
|
||||
};
|
||||
assert_eq!(code, XENORA_OK);
|
||||
s
|
||||
}
|
||||
|
||||
fn session() -> u64 {
|
||||
let mut session = 0;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut session) },
|
||||
XENORA_OK
|
||||
);
|
||||
session
|
||||
}
|
||||
|
||||
fn wait_until(session: u64, what: &str, done: impl Fn(&Status) -> bool) -> Status {
|
||||
let deadline = Instant::now() + Duration::from_secs(60);
|
||||
loop {
|
||||
let s = status(session);
|
||||
if done(&s) {
|
||||
return s;
|
||||
}
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"timed out waiting for {what} (state {}, completed {})",
|
||||
s.state,
|
||||
s.completed
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
}
|
||||
}
|
||||
|
||||
/// Physical memory footprint of this process (macOS `proc_pid_rusage`, RUSAGE_INFO_V2).
|
||||
fn footprint() -> u64 {
|
||||
unsafe extern "C" {
|
||||
fn proc_pid_rusage(pid: i32, flavor: i32, buffer: *mut [u64; 32]) -> i32;
|
||||
}
|
||||
let mut info = [0u64; 32];
|
||||
assert_eq!(
|
||||
unsafe { proc_pid_rusage(std::process::id() as i32, 2, &mut info) },
|
||||
0
|
||||
);
|
||||
info[9] // after the 16-byte UUID: user, system, idle wakeups, interrupts, pageins, wired, resident, footprint
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_hundred_guest_frames_arrive_verified_and_in_order() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let session = session();
|
||||
assert_eq!(xenora_session_start_frame_loop(session, 300), XENORA_OK);
|
||||
assert_eq!(
|
||||
xenora_session_start_frame_loop(session, 300),
|
||||
XENORA_INVALID_STATE
|
||||
);
|
||||
let s = wait_until(session, "300 frames", |s| s.state != XENORA_LOOP_RUNNING);
|
||||
assert_eq!(s.state, XENORA_LOOP_FINISHED);
|
||||
assert_eq!(s.completed, 300);
|
||||
assert_eq!(s.frame_id, 299);
|
||||
assert_eq!(s.rgba.to_vec(), expected(299));
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn observed_frame_ids_never_go_backwards_and_match_their_pixels() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let session = session();
|
||||
assert_eq!(xenora_session_start_frame_loop(session, 2_000), XENORA_OK);
|
||||
let mut previous = None;
|
||||
let mut samples = 0;
|
||||
loop {
|
||||
let s = status(session);
|
||||
if s.frame_id != XENORA_NO_FRAME {
|
||||
if let Some(p) = previous {
|
||||
assert!(s.frame_id >= p, "frame id went from {p} to {}", s.frame_id);
|
||||
}
|
||||
assert!(
|
||||
s.frame_id < s.completed,
|
||||
"id {} not below completed {}",
|
||||
s.frame_id,
|
||||
s.completed
|
||||
);
|
||||
assert_eq!(
|
||||
s.rgba.to_vec(),
|
||||
expected(s.frame_id),
|
||||
"frame {}",
|
||||
s.frame_id
|
||||
);
|
||||
previous = Some(s.frame_id);
|
||||
samples += 1;
|
||||
}
|
||||
if s.state != XENORA_LOOP_RUNNING {
|
||||
assert_eq!(s.state, XENORA_LOOP_FINISHED);
|
||||
assert_eq!((s.completed, s.frame_id), (2_000, 1_999));
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(samples > 1);
|
||||
xenora_session_destroy(session);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pause_holds_the_guest_resume_continues_and_stop_halts_it() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let session = session();
|
||||
assert_eq!(
|
||||
xenora_session_start_frame_loop(session, XENORA_FRAME_LOOP_MAX_FRAMES),
|
||||
XENORA_OK
|
||||
);
|
||||
wait_until(session, "10 frames", |s| s.completed >= 10);
|
||||
|
||||
assert_eq!(xenora_session_pause_frame_loop(session), XENORA_OK);
|
||||
// At most the frame already being rendered can still complete after pausing.
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
let held = status(session);
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
let later = status(session);
|
||||
assert_eq!(later.state, XENORA_LOOP_PAUSED);
|
||||
assert_eq!(later.completed, held.completed, "no frames while paused");
|
||||
assert_eq!(later.frame_id, held.completed - 1);
|
||||
assert_eq!(later.rgba.to_vec(), expected(later.frame_id));
|
||||
|
||||
assert_eq!(xenora_session_resume_frame_loop(session), XENORA_OK);
|
||||
let resumed = wait_until(session, "progress after resume", |s| {
|
||||
s.completed >= held.completed + 10
|
||||
});
|
||||
assert_eq!(resumed.state, XENORA_LOOP_RUNNING);
|
||||
|
||||
assert_eq!(xenora_session_stop_frame_loop(session), XENORA_OK);
|
||||
let stopped = status(session);
|
||||
assert_eq!(stopped.state, XENORA_LOOP_STOPPED);
|
||||
assert!(stopped.completed < XENORA_FRAME_LOOP_MAX_FRAMES);
|
||||
assert_eq!(stopped.frame_id, stopped.completed - 1);
|
||||
assert_eq!(stopped.rgba.to_vec(), expected(stopped.frame_id));
|
||||
// Pause and resume are refused once the guest has halted.
|
||||
assert_eq!(
|
||||
xenora_session_pause_frame_loop(session),
|
||||
XENORA_INVALID_STATE
|
||||
);
|
||||
assert_eq!(
|
||||
xenora_session_resume_frame_loop(session),
|
||||
XENORA_INVALID_STATE
|
||||
);
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn destroying_a_running_or_paused_session_stops_it() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
for pause_first in [false, true] {
|
||||
let session = session();
|
||||
assert_eq!(
|
||||
xenora_session_start_frame_loop(session, XENORA_FRAME_LOOP_MAX_FRAMES),
|
||||
XENORA_OK
|
||||
);
|
||||
wait_until(session, "a frame", |s| s.completed >= 1);
|
||||
if pause_first {
|
||||
assert_eq!(xenora_session_pause_frame_loop(session), XENORA_OK);
|
||||
}
|
||||
let started = Instant::now();
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(5),
|
||||
"destroy joined promptly"
|
||||
);
|
||||
let mut x = 0;
|
||||
let mut rgba = [0u8; 48];
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_frame_loop_status(
|
||||
session,
|
||||
&mut x,
|
||||
&mut x,
|
||||
&mut x,
|
||||
rgba.as_mut_ptr(),
|
||||
48,
|
||||
)
|
||||
},
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_sessions_do_not_grow_the_memory_footprint() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let run = || {
|
||||
let session = session();
|
||||
assert_eq!(xenora_session_start_frame_loop(session, 300), XENORA_OK);
|
||||
let s = wait_until(session, "300 frames", |s| s.state != XENORA_LOOP_RUNNING);
|
||||
assert_eq!((s.state, s.completed), (XENORA_LOOP_FINISHED, 300));
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
};
|
||||
// Warm up so one-time allocations (Metal device, shader compiler) are excluded.
|
||||
run();
|
||||
run();
|
||||
let baseline = footprint();
|
||||
for _ in 0..5 {
|
||||
run();
|
||||
}
|
||||
let after = footprint();
|
||||
let growth = after.saturating_sub(baseline);
|
||||
println!("footprint baseline={baseline} after_5_sessions={after} growth={growth}");
|
||||
assert!(
|
||||
growth < 16 << 20,
|
||||
"footprint grew by {growth} bytes over 5 sessions of 300 frames"
|
||||
);
|
||||
}
|
||||
|
||||
/// Regression test for #290: the footprint read right after each destroy must stay
|
||||
/// flat across many sessions. Each session used to open its own Metal command queue,
|
||||
/// and the GPU driver frees a queue's working set (about 45 MiB on an Apple M5 with
|
||||
/// validation) asynchronously after release, so these readings swung by about 50 MiB
|
||||
/// from session to session. Sessions now share one queue. The mix of sessions covers
|
||||
/// normal completion, pause and resume, and destruction while running.
|
||||
#[test]
|
||||
fn fifty_sessions_keep_a_flat_footprint_after_each_destroy() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let one = |kind: usize| {
|
||||
let session = session();
|
||||
match kind {
|
||||
0 => {
|
||||
assert_eq!(xenora_session_start_frame_loop(session, 100), XENORA_OK);
|
||||
let s = wait_until(session, "100 frames", |s| s.state != XENORA_LOOP_RUNNING);
|
||||
assert_eq!((s.state, s.completed), (XENORA_LOOP_FINISHED, 100));
|
||||
}
|
||||
1 => {
|
||||
assert_eq!(xenora_session_start_frame_loop(session, 100), XENORA_OK);
|
||||
wait_until(session, "10 frames", |s| s.completed >= 10);
|
||||
assert_eq!(xenora_session_pause_frame_loop(session), XENORA_OK);
|
||||
assert_eq!(xenora_session_resume_frame_loop(session), XENORA_OK);
|
||||
let s = wait_until(session, "100 frames", |s| s.state != XENORA_LOOP_RUNNING);
|
||||
assert_eq!((s.state, s.completed), (XENORA_LOOP_FINISHED, 100));
|
||||
}
|
||||
_ => {
|
||||
assert_eq!(
|
||||
xenora_session_start_frame_loop(session, XENORA_FRAME_LOOP_MAX_FRAMES),
|
||||
XENORA_OK
|
||||
);
|
||||
wait_until(session, "a frame", |s| s.completed >= 1);
|
||||
}
|
||||
}
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
footprint()
|
||||
};
|
||||
one(0); // the first session allocates the shared queue's working set
|
||||
let readings: Vec<u64> = (0..50).map(|i| one(i % 3)).collect();
|
||||
let mib: Vec<u64> = readings.iter().map(|r| r >> 20).collect();
|
||||
println!("footprint after each destroy (MiB): {mib:?}");
|
||||
let median = |values: &[u64]| {
|
||||
let mut sorted = values.to_vec();
|
||||
sorted.sort_unstable();
|
||||
sorted[sorted.len() / 2]
|
||||
};
|
||||
// Sustained growth: the typical reading at the end against the start.
|
||||
let (start, end) = (median(&readings[..10]), median(&readings[40..]));
|
||||
assert!(
|
||||
end.saturating_sub(start) < 16 << 20,
|
||||
"footprint grew from {start} to {end} bytes (median of first and last ten sessions)"
|
||||
);
|
||||
// Per-session churn, the cause fixed in #290: with a queue per session, about half
|
||||
// of all readings sat some 45 MiB away from the median. With the shared queue,
|
||||
// a reading is still occasionally caught while the driver frees a batch of
|
||||
// per-frame render resources: graphics-tagged memory only, 16 to 44 MiB, gone
|
||||
// within about 100 ms, measured in 13 of 6,000 sessions (0.22%). Allowing two such
|
||||
// readings in 50 keeps a false failure near 1 in 5,000 runs while per-session
|
||||
// churn would exceed it every time.
|
||||
let centre = median(&readings);
|
||||
let outliers: Vec<u64> = readings
|
||||
.iter()
|
||||
.filter(|&&r| r.abs_diff(centre) >= 16 << 20)
|
||||
.map(|r| r >> 20)
|
||||
.collect();
|
||||
assert!(
|
||||
outliers.len() <= 2,
|
||||
"{} of 50 readings were 16 MiB or more from the median {} MiB: {outliers:?}",
|
||||
outliers.len(),
|
||||
centre >> 20
|
||||
);
|
||||
}
|
||||
|
||||
/// Two sessions render at the same time through the shared Metal queue (#290). Each
|
||||
/// must keep its own frame sequence and pixels, pausing one must not stop the other,
|
||||
/// and destroying one mid-run must not disturb the other.
|
||||
#[test]
|
||||
fn concurrent_sessions_share_the_queue_but_stay_isolated() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let (a, b) = (session(), session());
|
||||
assert_eq!(xenora_session_start_frame_loop(a, 400), XENORA_OK);
|
||||
assert_eq!(xenora_session_start_frame_loop(b, 250), XENORA_OK);
|
||||
wait_until(a, "session A started", |s| s.completed >= 5);
|
||||
wait_until(b, "session B started", |s| s.completed >= 5);
|
||||
|
||||
// Pausing A holds only A.
|
||||
assert_eq!(xenora_session_pause_frame_loop(a), XENORA_OK);
|
||||
let a_held = wait_until(a, "session A paused", |s| s.state == XENORA_LOOP_PAUSED);
|
||||
let b_before = status(b).completed;
|
||||
let b_moving = wait_until(b, "session B progress while A is paused", |s| {
|
||||
s.completed >= b_before + 20 || s.state != XENORA_LOOP_RUNNING
|
||||
});
|
||||
assert!(
|
||||
b_moving.completed > b_before,
|
||||
"B kept rendering while A was paused"
|
||||
);
|
||||
let a_still = status(a);
|
||||
assert_eq!(a_still.state, XENORA_LOOP_PAUSED);
|
||||
// At most the frame A was rendering when paused can still complete.
|
||||
assert!(a_still.completed <= a_held.completed + 1);
|
||||
assert_eq!(a_still.rgba.to_vec(), expected(a_still.frame_id));
|
||||
assert_eq!(xenora_session_resume_frame_loop(a), XENORA_OK);
|
||||
|
||||
// Both finish with their own counts and their own final frames.
|
||||
let a_done = wait_until(a, "session A finished", |s| s.state != XENORA_LOOP_RUNNING);
|
||||
let b_done = wait_until(b, "session B finished", |s| s.state != XENORA_LOOP_RUNNING);
|
||||
assert_eq!(
|
||||
(a_done.state, a_done.completed, a_done.frame_id),
|
||||
(XENORA_LOOP_FINISHED, 400, 399)
|
||||
);
|
||||
assert_eq!(
|
||||
(b_done.state, b_done.completed, b_done.frame_id),
|
||||
(XENORA_LOOP_FINISHED, 250, 249)
|
||||
);
|
||||
assert_eq!(a_done.rgba.to_vec(), expected(399));
|
||||
assert_eq!(b_done.rgba.to_vec(), expected(249));
|
||||
assert_eq!(xenora_session_destroy(a), XENORA_OK);
|
||||
assert_eq!(xenora_session_destroy(b), XENORA_OK);
|
||||
|
||||
// Destroying one running session leaves the other running to completion.
|
||||
let (c, d) = (session(), session());
|
||||
assert_eq!(
|
||||
xenora_session_start_frame_loop(c, XENORA_FRAME_LOOP_MAX_FRAMES),
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(xenora_session_start_frame_loop(d, 300), XENORA_OK);
|
||||
wait_until(c, "session C started", |s| s.completed >= 5);
|
||||
wait_until(d, "session D started", |s| s.completed >= 5);
|
||||
assert_eq!(xenora_session_destroy(c), XENORA_OK);
|
||||
let d_done = wait_until(d, "session D finished", |s| s.state != XENORA_LOOP_RUNNING);
|
||||
assert_eq!(
|
||||
(d_done.state, d_done.completed, d_done.frame_id),
|
||||
(XENORA_LOOP_FINISHED, 300, 299)
|
||||
);
|
||||
assert_eq!(d_done.rgba.to_vec(), expected(299));
|
||||
assert_eq!(xenora_session_destroy(d), XENORA_OK);
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Gate 4 acceptance on a native Metal device: interactive guest execution with
|
||||
//! dynamic input handling and rendering through the C interface.
|
||||
//! Needs `--features gpu-tests` (scripts/test-gpu.sh).
|
||||
#![cfg(feature = "gpu-tests")]
|
||||
|
||||
use std::sync::Mutex;
|
||||
use std::time::{Duration, Instant};
|
||||
use xenora_ffi::*;
|
||||
|
||||
/// Tests share the process-wide session table and one GPU; run them one at a time.
|
||||
static SERIAL: Mutex<()> = Mutex::new(());
|
||||
|
||||
/// Expected frame `column` (0..3): column `column` is opaque red (255, 0, 0, 255);
|
||||
/// all other columns keep the clear colour (19, 43, 93, 251).
|
||||
fn expected(column: u32) -> Vec<u8> {
|
||||
let mut frame = Vec::new();
|
||||
for _row in 0..3 {
|
||||
for col in 0..4 {
|
||||
if col == column % 4 {
|
||||
frame.extend([255, 0, 0, 255]);
|
||||
} else {
|
||||
frame.extend([19, 43, 93, 251]);
|
||||
}
|
||||
}
|
||||
}
|
||||
frame
|
||||
}
|
||||
|
||||
struct Status {
|
||||
state: u32,
|
||||
completed: u32,
|
||||
frame_id: u32,
|
||||
rgba: [u8; 48],
|
||||
}
|
||||
|
||||
fn status(session: u64) -> Status {
|
||||
let mut s = Status {
|
||||
state: 99,
|
||||
completed: 0,
|
||||
frame_id: 0,
|
||||
rgba: [0; 48],
|
||||
};
|
||||
let code = unsafe {
|
||||
xenora_session_frame_loop_status(
|
||||
session,
|
||||
&mut s.state,
|
||||
&mut s.completed,
|
||||
&mut s.frame_id,
|
||||
s.rgba.as_mut_ptr(),
|
||||
48,
|
||||
)
|
||||
};
|
||||
assert_eq!(code, XENORA_OK);
|
||||
s
|
||||
}
|
||||
|
||||
fn session() -> u64 {
|
||||
let mut session = 0;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut session) },
|
||||
XENORA_OK
|
||||
);
|
||||
session
|
||||
}
|
||||
|
||||
fn send_buttons(session: u64, buttons: u32) {
|
||||
let input = xenora_input_state {
|
||||
buttons,
|
||||
stick_x: 0,
|
||||
stick_y: 0,
|
||||
mouse_dx: 0,
|
||||
mouse_dy: 0,
|
||||
mouse_buttons: 0,
|
||||
connected: 1,
|
||||
reserved: 0,
|
||||
};
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_send_input(session, &input) },
|
||||
XENORA_OK
|
||||
);
|
||||
}
|
||||
|
||||
fn queue_buttons(session: u64, buttons: u32) {
|
||||
let input = xenora_input_state {
|
||||
buttons,
|
||||
stick_x: 0,
|
||||
stick_y: 0,
|
||||
mouse_dx: 0,
|
||||
mouse_dy: 0,
|
||||
mouse_buttons: 0,
|
||||
connected: 1,
|
||||
reserved: 0,
|
||||
};
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_queue_input(session, &input) },
|
||||
XENORA_OK
|
||||
);
|
||||
}
|
||||
|
||||
fn wait_until(session: u64, what: &str, done: impl Fn(&Status) -> bool) -> Status {
|
||||
let deadline = Instant::now() + Duration::from_secs(60);
|
||||
loop {
|
||||
let s = status(session);
|
||||
if done(&s) {
|
||||
return s;
|
||||
}
|
||||
assert!(
|
||||
Instant::now() < deadline,
|
||||
"timed out waiting for {what} (state {}, completed {})",
|
||||
s.state,
|
||||
s.completed
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(2));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interactive_input_moves_guest_column_and_updates_pixels() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let session = session();
|
||||
|
||||
// Start interactive loop with 120 frames
|
||||
assert_eq!(
|
||||
xenora_session_start_interactive_loop(session, 120),
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
// Initial frames without input stay at column 0
|
||||
let s = wait_until(session, "initial frames", |s| s.completed >= 5);
|
||||
assert_eq!(s.frame_id, 0);
|
||||
assert_eq!(s.rgba.to_vec(), expected(0));
|
||||
|
||||
// Send Right input: column should advance 0 -> 1 -> 2 -> 3 -> 0
|
||||
send_buttons(session, XENORA_INPUT_RIGHT);
|
||||
let s_right = wait_until(session, "column moves right", |s| {
|
||||
s.completed >= 15 && s.frame_id != 0
|
||||
});
|
||||
assert_eq!(s_right.rgba.to_vec(), expected(s_right.frame_id));
|
||||
|
||||
// Release input: position stops moving
|
||||
send_buttons(session, XENORA_INPUT_NONE);
|
||||
let s_hold_start = wait_until(session, "wait for release frame", |s| {
|
||||
s.completed >= s_right.completed + 2
|
||||
});
|
||||
let hold_col = s_hold_start.frame_id;
|
||||
let s_hold = wait_until(session, "position holds on release", |s| {
|
||||
s.completed >= s_hold_start.completed + 10
|
||||
});
|
||||
assert_eq!(s_hold.frame_id, hold_col);
|
||||
assert_eq!(s_hold.rgba.to_vec(), expected(s_hold.frame_id));
|
||||
|
||||
// Send Left input: column should move left
|
||||
send_buttons(session, XENORA_INPUT_LEFT);
|
||||
let s_left = wait_until(session, "column moves left", |s| {
|
||||
s.completed >= s_hold.completed + 10 && s.frame_id != hold_col
|
||||
});
|
||||
assert_eq!(s_left.rgba.to_vec(), expected(s_left.frame_id));
|
||||
|
||||
// Wait until finished
|
||||
let s_end = wait_until(session, "loop finish", |s| s.state == XENORA_LOOP_FINISHED);
|
||||
assert_eq!(s_end.completed, 120);
|
||||
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deterministic_input_replay_produces_identical_frames() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
|
||||
// Timeline of inputs across 60 frames:
|
||||
// frames 0..15: Right
|
||||
// frames 15..30: None
|
||||
// frames 30..45: Left
|
||||
// frames 45..60: Right
|
||||
let replay_sequence: Vec<u32> = (0..60)
|
||||
.map(|f| {
|
||||
if f < 15 {
|
||||
XENORA_INPUT_RIGHT
|
||||
} else if f < 30 {
|
||||
XENORA_INPUT_NONE
|
||||
} else if f < 45 {
|
||||
XENORA_INPUT_LEFT
|
||||
} else {
|
||||
XENORA_INPUT_RIGHT
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
let run_replay = || {
|
||||
let session = session();
|
||||
assert_eq!(
|
||||
xenora_session_start_interactive_loop(session, 60),
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
// Pre-queue the complete input sequence
|
||||
for &btn in &replay_sequence {
|
||||
queue_buttons(session, btn);
|
||||
}
|
||||
|
||||
// Wait until all 60 frames are rendered
|
||||
let s = wait_until(session, "replay completion", |s| {
|
||||
s.state == XENORA_LOOP_FINISHED && s.completed == 60
|
||||
});
|
||||
assert_eq!(s.completed, 60);
|
||||
|
||||
// Inspect all 60 recorded frames
|
||||
let mut frames = Vec::with_capacity(60);
|
||||
for i in 0..60 {
|
||||
let mut id = 0u32;
|
||||
let mut rgba = [0u8; 48];
|
||||
let code = unsafe {
|
||||
xenora_session_get_recorded_frame(session, i, &mut id, rgba.as_mut_ptr(), 48)
|
||||
};
|
||||
assert_eq!(code, XENORA_OK);
|
||||
assert_eq!(rgba.to_vec(), expected(id));
|
||||
frames.push((id, rgba));
|
||||
}
|
||||
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
frames
|
||||
};
|
||||
|
||||
let run1 = run_replay();
|
||||
let run2 = run_replay();
|
||||
|
||||
assert_eq!(run1.len(), 60);
|
||||
assert_eq!(run2.len(), 60);
|
||||
for i in 0..60 {
|
||||
assert_eq!(
|
||||
run1[i].0, run2[i].0,
|
||||
"frame {} column mismatch: {} vs {}",
|
||||
i, run1[i].0, run2[i].0
|
||||
);
|
||||
assert_eq!(run1[i].1, run2[i].1, "frame {} pixel mismatch", i);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn focus_loss_and_release_resets_input_cleanly() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let session = session();
|
||||
|
||||
assert_eq!(
|
||||
xenora_session_start_interactive_loop(session, 100),
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
// Send Right
|
||||
send_buttons(session, XENORA_INPUT_RIGHT);
|
||||
let s1 = wait_until(session, "moving right", |s| s.completed >= 10);
|
||||
|
||||
// Simulate focus loss / key release
|
||||
send_buttons(session, XENORA_INPUT_NONE);
|
||||
// Wait for the release to take effect in the guest
|
||||
let s_released = wait_until(session, "release takes effect", |s| {
|
||||
s.completed >= s1.completed + 2
|
||||
});
|
||||
let stopped_col = s_released.frame_id;
|
||||
|
||||
// Check next 15 frames: frame_id must remain fixed at stopped_col
|
||||
let s2 = wait_until(session, "hold after release", |s| {
|
||||
s.completed >= s_released.completed + 15
|
||||
});
|
||||
assert_eq!(s2.frame_id, stopped_col);
|
||||
assert_eq!(s2.rgba.to_vec(), expected(stopped_col));
|
||||
|
||||
// Clean stop
|
||||
assert_eq!(xenora_session_stop_frame_loop(session), XENORA_OK);
|
||||
let s_stopped = wait_until(session, "stopped", |s| s.state == XENORA_LOOP_STOPPED);
|
||||
assert_eq!(s_stopped.state, XENORA_LOOP_STOPPED);
|
||||
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn destroying_interactive_session_stops_cleanly() {
|
||||
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let session = session();
|
||||
|
||||
assert_eq!(
|
||||
xenora_session_start_interactive_loop(session, 5000),
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
// Wait until it actually starts rendering
|
||||
wait_until(session, "running", |s| s.completed >= 5);
|
||||
|
||||
let start = Instant::now();
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
assert!(
|
||||
start.elapsed() < Duration::from_millis(500),
|
||||
"destroy took too long: {:?}",
|
||||
start.elapsed()
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Runs the trusted fixture through the C interface on a native Metal device.
|
||||
//! Needs `--features gpu-tests` (scripts/test-gpu.sh).
|
||||
#![cfg(feature = "gpu-tests")]
|
||||
|
||||
use xenora_ffi::*;
|
||||
|
||||
/// fixtures/rdna2/x9-constant-ps.s: `v_mov_b32 v8, 1.0; v_mov_b32 v9, 0;
|
||||
/// exp mrt0, v8, v9, v9, v8` writes (1, 0, 0, 1); as RGBA8 unorm that is (255, 0, 0, 255).
|
||||
const SHADER_OUTPUT: [u8; 4] = [255, 0, 0, 255];
|
||||
|
||||
#[test]
|
||||
fn guest_fixture_frame_reaches_the_caller_through_metal() {
|
||||
for run in 0..3 {
|
||||
let mut session = 0;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut session) },
|
||||
XENORA_OK
|
||||
);
|
||||
let (mut rgba, mut width, mut height) = ([0u8; 64], 0u32, 0u32);
|
||||
let status = unsafe {
|
||||
xenora_session_run_trusted_fixture(
|
||||
session,
|
||||
rgba.as_mut_ptr(),
|
||||
64,
|
||||
&mut width,
|
||||
&mut height,
|
||||
)
|
||||
};
|
||||
assert_eq!(status, XENORA_OK, "run {run}");
|
||||
assert_eq!((width, height), (4, 3));
|
||||
assert_eq!(&rgba[..48], SHADER_OUTPUT.repeat(12).as_slice());
|
||||
assert!(
|
||||
rgba[48..].iter().all(|&b| b == 0),
|
||||
"no write past the frame"
|
||||
);
|
||||
assert_eq!(xenora_session_destroy(session), XENORA_OK);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,375 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Gate 5 acceptance on a native Metal device: persistent GPU resources,
|
||||
//! dynamic texture updates, and completion-aware resource retirement through
|
||||
//! the C interface (#279).
|
||||
//! Needs `--features gpu-tests` (scripts/test-gpu.sh).
|
||||
#![cfg(feature = "gpu-tests")]
|
||||
|
||||
use std::sync::Mutex;
|
||||
use xenora_ffi::*;
|
||||
|
||||
/// Tests share the process-wide session table and one GPU; run them one at a time.
|
||||
static SERIAL: Mutex<()> = Mutex::new(());
|
||||
|
||||
fn session() -> u64 {
|
||||
let mut handle = 0;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut handle) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_ne!(handle, 0);
|
||||
handle
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persistent_texture_lifecycle_survives_across_multiple_frames() {
|
||||
let _guard = SERIAL.lock().unwrap();
|
||||
let sess = session();
|
||||
|
||||
// 2x2 initial texture:
|
||||
// (0,0)=red, (1,0)=green, (0,1)=blue, (1,1)=white
|
||||
let initial_rgba: [u8; 16] = [
|
||||
255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
|
||||
];
|
||||
|
||||
let mut res = 0u64;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create_texture(sess, 2, 2, initial_rgba.as_ptr(), &mut res) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_ne!(res, XENORA_NO_RESOURCE);
|
||||
|
||||
// Render 5 consecutive frames from this single persistent texture resource without re-allocation.
|
||||
for frame_idx in 0..5 {
|
||||
let mut out_rgba = [0u8; 16];
|
||||
let mut out_w = 0u32;
|
||||
let mut out_h = 0u32;
|
||||
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_render_textured(
|
||||
sess,
|
||||
res,
|
||||
out_rgba.as_mut_ptr(),
|
||||
16,
|
||||
&mut out_w,
|
||||
&mut out_h,
|
||||
)
|
||||
},
|
||||
XENORA_OK,
|
||||
"render frame {} failed",
|
||||
frame_idx
|
||||
);
|
||||
|
||||
assert_eq!(out_w, 2);
|
||||
assert_eq!(out_h, 2);
|
||||
assert_eq!(
|
||||
out_rgba, initial_rgba,
|
||||
"frame {} pixel mismatch with persistent texture",
|
||||
frame_idx
|
||||
);
|
||||
}
|
||||
|
||||
// Verify resource is still live and un-retired after all frames
|
||||
let (mut r_type, mut r_w, mut r_h, mut r_flight) = (0u32, 0u32, 0u32, 0u32);
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_resource_info(sess, res, &mut r_type, &mut r_w, &mut r_h, &mut r_flight)
|
||||
},
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(r_type, XENORA_RESOURCE_TYPE_TEXTURE_2D);
|
||||
assert_eq!(r_w, 2);
|
||||
assert_eq!(r_h, 2);
|
||||
assert_eq!(r_flight, 0);
|
||||
|
||||
assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK);
|
||||
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dynamic_texture_subregion_update_is_reflected_on_metal() {
|
||||
let _guard = SERIAL.lock().unwrap();
|
||||
let sess = session();
|
||||
|
||||
// 2x2 initial texture:
|
||||
// (0,0)=red, (1,0)=green, (0,1)=blue, (1,1)=white
|
||||
let initial_rgba: [u8; 16] = [
|
||||
255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
|
||||
];
|
||||
|
||||
let mut res = 0u64;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create_texture(sess, 2, 2, initial_rgba.as_ptr(), &mut res) },
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
// 1. Update 1x1 subregion at (x=1, y=0) from green to yellow [255, 255, 0, 255]
|
||||
let yellow_pixel = [255u8, 255, 0, 255];
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_update_texture(sess, res, 1, 0, 1, 1, yellow_pixel.as_ptr(), 4) },
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
let mut frame1 = [0u8; 16];
|
||||
let (mut w, mut h) = (0u32, 0u32);
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_render_textured(sess, res, frame1.as_mut_ptr(), 16, &mut w, &mut h)
|
||||
},
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
let expected_frame1: [u8; 16] = [
|
||||
255, 0, 0, 255, // (0,0) red (untouched)
|
||||
255, 255, 0, 255, // (1,0) yellow (updated)
|
||||
0, 0, 255, 255, // (0,1) blue (untouched)
|
||||
255, 255, 255, 255, // (1,1) white (untouched)
|
||||
];
|
||||
assert_eq!(
|
||||
frame1, expected_frame1,
|
||||
"Metal read-back did not reflect 1x1 subregion update"
|
||||
);
|
||||
|
||||
// 2. Update 2x1 subregion across the bottom row: (0,1) and (1,1)
|
||||
// (0,1)=magenta [255, 0, 255, 255], (1,1)=cyan [0, 255, 255, 255]
|
||||
let bottom_row = [255u8, 0, 255, 255, 0, 255, 255, 255];
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_update_texture(sess, res, 0, 1, 2, 1, bottom_row.as_ptr(), 8) },
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
let mut frame2 = [0u8; 16];
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_render_textured(sess, res, frame2.as_mut_ptr(), 16, &mut w, &mut h)
|
||||
},
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
let expected_frame2: [u8; 16] = [
|
||||
255, 0, 0, 255, // (0,0) red
|
||||
255, 255, 0, 255, // (1,0) yellow
|
||||
255, 0, 255, 255, // (0,1) magenta
|
||||
0, 255, 255, 255, // (1,1) cyan
|
||||
];
|
||||
assert_eq!(
|
||||
frame2, expected_frame2,
|
||||
"Metal read-back did not reflect 2x1 bottom row update"
|
||||
);
|
||||
|
||||
assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK);
|
||||
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deferred_resource_retirement_safely_waits_for_completion() {
|
||||
let _guard = SERIAL.lock().unwrap();
|
||||
let sess = session();
|
||||
|
||||
let mut res = 0u64;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create_texture(sess, 2, 2, std::ptr::null(), &mut res) },
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
// Acquire an in-flight reference simulating active GPU encoding/submission
|
||||
assert_eq!(test_acquire_resource_in_flight(sess, res), Ok(()));
|
||||
|
||||
let (mut r_type, mut r_w, mut r_h, mut r_flight) = (0u32, 0u32, 0u32, 0u32);
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_resource_info(sess, res, &mut r_type, &mut r_w, &mut r_h, &mut r_flight)
|
||||
},
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(r_flight, 1);
|
||||
|
||||
// Calling destroy while in-flight marks the resource retired without dangling pointers
|
||||
assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK);
|
||||
|
||||
// Subsequent caller operations on the retired handle are rejected
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_resource_info(sess, res, &mut r_type, &mut r_w, &mut r_h, &mut r_flight)
|
||||
},
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
assert_eq!(
|
||||
xenora_session_destroy_resource(sess, res),
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
|
||||
let dummy_pixel = [0u8; 4];
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_update_texture(sess, res, 0, 0, 1, 1, dummy_pixel.as_ptr(), 4) },
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
|
||||
let mut out_rgba = [0u8; 16];
|
||||
let (mut w, mut h) = (0u32, 0u32);
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_render_textured(sess, res, out_rgba.as_mut_ptr(), 16, &mut w, &mut h)
|
||||
},
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
|
||||
// Now in-flight execution completes and releases its reference
|
||||
assert_eq!(test_release_resource_in_flight(sess, res), Ok(()));
|
||||
|
||||
// The slot is now safely reclaimed; the next allocation reuses the slot with a new generation
|
||||
let mut res2 = 0u64;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create_texture(sess, 2, 2, std::ptr::null(), &mut res2) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!((res & 0xFFFF_FFFF), (res2 & 0xFFFF_FFFF)); // same slot index
|
||||
assert_ne!(res >> 32, res2 >> 32); // higher generation
|
||||
|
||||
assert_eq!(xenora_session_destroy_resource(sess, res2), XENORA_OK);
|
||||
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_stale_and_double_destroyed_resource_handles_are_rejected() {
|
||||
let _guard = SERIAL.lock().unwrap();
|
||||
let sess = session();
|
||||
|
||||
// Zero handle
|
||||
assert_eq!(
|
||||
xenora_session_destroy_resource(sess, XENORA_NO_RESOURCE),
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
|
||||
// Unallocated slot index
|
||||
let unallocated_handle = (1u64 << 32) | 999u64;
|
||||
assert_eq!(
|
||||
xenora_session_destroy_resource(sess, unallocated_handle),
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
|
||||
// Create and destroy a valid resource
|
||||
let mut res = 0u64;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create_texture(sess, 2, 2, std::ptr::null(), &mut res) },
|
||||
XENORA_OK
|
||||
);
|
||||
assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK);
|
||||
|
||||
// Double destroy
|
||||
assert_eq!(
|
||||
xenora_session_destroy_resource(sess, res),
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
|
||||
// Stale handle queries
|
||||
let (mut r_type, mut r_w, mut r_h, mut r_flight) = (0u32, 0u32, 0u32, 0u32);
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_resource_info(sess, res, &mut r_type, &mut r_w, &mut r_h, &mut r_flight)
|
||||
},
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
|
||||
let pixel = [0u8; 4];
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_update_texture(sess, res, 0, 0, 1, 1, pixel.as_ptr(), 4) },
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
|
||||
let mut out_rgba = [0u8; 16];
|
||||
let (mut w, mut h) = (0u32, 0u32);
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_render_textured(sess, res, out_rgba.as_mut_ptr(), 16, &mut w, &mut h)
|
||||
},
|
||||
XENORA_INVALID_HANDLE
|
||||
);
|
||||
|
||||
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_resource_allocations_and_retirements_do_not_leak_slots() {
|
||||
let _guard = SERIAL.lock().unwrap();
|
||||
let sess = session();
|
||||
|
||||
let initial = [
|
||||
255u8, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
|
||||
];
|
||||
let update = [255u8, 255, 0, 255];
|
||||
|
||||
// Run 200 cycles of create -> update -> render -> destroy
|
||||
for i in 0..200 {
|
||||
let mut res = 0u64;
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_create_texture(sess, 2, 2, initial.as_ptr(), &mut res) },
|
||||
XENORA_OK,
|
||||
"create failed at cycle {}",
|
||||
i
|
||||
);
|
||||
|
||||
// Verify slot index is reused (res_idx is 0)
|
||||
let slot_idx = (res & 0xFFFF_FFFF) as usize;
|
||||
assert_eq!(slot_idx, 0, "slot index leaked at cycle {}", i);
|
||||
|
||||
assert_eq!(
|
||||
unsafe { xenora_session_update_texture(sess, res, 0, 0, 1, 1, update.as_ptr(), 4) },
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
let mut out = [0u8; 16];
|
||||
let (mut w, mut h) = (0u32, 0u32);
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_render_textured(sess, res, out.as_mut_ptr(), 16, &mut w, &mut h)
|
||||
},
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK);
|
||||
}
|
||||
|
||||
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn textured_pe_fixture_executes_dynamic_updates_and_retirement() {
|
||||
let _guard = SERIAL.lock().unwrap();
|
||||
let sess = session();
|
||||
|
||||
let mut out_rgba = [0u8; 16];
|
||||
let mut out_w = 0u32;
|
||||
let mut out_h = 0u32;
|
||||
|
||||
assert_eq!(
|
||||
unsafe {
|
||||
xenora_session_run_textured_fixture(
|
||||
sess,
|
||||
out_rgba.as_mut_ptr(),
|
||||
16,
|
||||
&mut out_w,
|
||||
&mut out_h,
|
||||
)
|
||||
},
|
||||
XENORA_OK
|
||||
);
|
||||
|
||||
assert_eq!(out_w, 2);
|
||||
assert_eq!(out_h, 2);
|
||||
|
||||
let expected_final: [u8; 16] = [
|
||||
255, 255, 0, 255, // (0,0) yellow
|
||||
0, 255, 255, 255, // (1,0) cyan
|
||||
255, 0, 255, 255, // (0,1) magenta
|
||||
64, 64, 64, 255, // (1,1) dark grey
|
||||
];
|
||||
assert_eq!(
|
||||
out_rgba, expected_final,
|
||||
"guest textured fixture read-back frame mismatch"
|
||||
);
|
||||
|
||||
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
|
||||
}
|
||||
@@ -10,49 +10,26 @@
|
||||
//! Source: Public Windows SDK `apisetcounters.h` and documented Microsoft API-set schema.
|
||||
|
||||
/// Resolve an API-set virtual DLL name to its canonical Windows module name.
|
||||
///
|
||||
/// API sets are matched exactly against [`get_api_sets_for_canonical`]. A name
|
||||
/// that merely starts like a known family is not assumed to forward anywhere.
|
||||
pub fn resolve_api_set_canonical(module: &str) -> &'static str {
|
||||
let lower = module.to_ascii_lowercase();
|
||||
let trimmed = lower.strip_suffix(".dll").unwrap_or(&lower);
|
||||
|
||||
if trimmed.starts_with("api-ms-win-core-processthreads")
|
||||
|| trimmed.starts_with("api-ms-win-core-processtopology")
|
||||
|| trimmed.starts_with("api-ms-win-core-profile")
|
||||
|| trimmed.starts_with("api-ms-win-core-sysinfo")
|
||||
|| trimmed.starts_with("api-ms-win-core-interlocked")
|
||||
|| trimmed.starts_with("api-ms-win-core-libraryloader")
|
||||
|| trimmed.starts_with("api-ms-win-core-namedpipe")
|
||||
|| trimmed.starts_with("api-ms-win-core-handle")
|
||||
|| trimmed.starts_with("api-ms-win-core-errorhandling")
|
||||
|| trimmed.starts_with("api-ms-win-core-debug")
|
||||
|| trimmed.starts_with("api-ms-win-core-datetime")
|
||||
|| trimmed.starts_with("api-ms-win-core-timezone")
|
||||
|| trimmed.starts_with("api-ms-win-core-processenvironment")
|
||||
|| trimmed.starts_with("api-ms-win-core-file")
|
||||
|| trimmed.starts_with("api-ms-win-core-io")
|
||||
|| trimmed.starts_with("api-ms-win-core-synch")
|
||||
|| trimmed.starts_with("api-ms-win-core-memory")
|
||||
|| trimmed.starts_with("api-ms-win-core-heap")
|
||||
|| trimmed.starts_with("api-ms-win-core-string")
|
||||
|| trimmed.starts_with("api-ms-win-core-localization")
|
||||
{
|
||||
"kernel32.dll"
|
||||
} else if trimmed.starts_with("api-ms-win-core-rtlsupport") {
|
||||
"ntdll.dll"
|
||||
} else if trimmed.starts_with("api-ms-win-crt-") {
|
||||
"ucrtbase.dll"
|
||||
} else if trimmed == "vcruntime140" || trimmed == "vcruntime140_1" {
|
||||
"vcruntime140.dll"
|
||||
} else if trimmed == "msvcp140" || trimmed == "msvcp140_1" || trimmed == "msvcp140_2" {
|
||||
"msvcp140.dll"
|
||||
} else {
|
||||
match module.to_ascii_lowercase().as_str() {
|
||||
"kernel32.dll" | "kernelbase.dll" => "kernel32.dll",
|
||||
"ntdll.dll" => "ntdll.dll",
|
||||
"ws2_32.dll" => "ws2_32.dll",
|
||||
"advapi32.dll" => "advapi32.dll",
|
||||
_ => "unknown.dll",
|
||||
for canonical in ["kernel32.dll", "ucrtbase.dll"] {
|
||||
if get_api_sets_for_canonical(canonical).contains(&lower.as_str()) {
|
||||
return canonical;
|
||||
}
|
||||
}
|
||||
match lower.as_str() {
|
||||
"kernel32.dll" | "kernelbase.dll" => "kernel32.dll",
|
||||
"ucrtbase.dll" => "ucrtbase.dll",
|
||||
"ntdll.dll" => "ntdll.dll",
|
||||
"ws2_32.dll" => "ws2_32.dll",
|
||||
"advapi32.dll" => "advapi32.dll",
|
||||
"vcruntime140.dll" | "vcruntime140_1.dll" => "vcruntime140.dll",
|
||||
"msvcp140.dll" | "msvcp140_1.dll" | "msvcp140_2.dll" => "msvcp140.dll",
|
||||
_ => "unknown.dll",
|
||||
}
|
||||
}
|
||||
|
||||
/// Known API sets that forward to the given canonical host module.
|
||||
@@ -78,6 +55,7 @@ pub fn get_api_sets_for_canonical(canonical: &str) -> &'static [&'static str] {
|
||||
"api-ms-win-core-interlocked-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-memory-l1-1-0.dll",
|
||||
],
|
||||
"ucrtbase.dll" => &[
|
||||
"api-ms-win-crt-math-l1-1-0.dll",
|
||||
@@ -100,6 +78,26 @@ pub fn get_api_sets_for_canonical(canonical: &str) -> &'static [&'static str] {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn only_listed_api_sets_resolve() {
|
||||
for unknown in [
|
||||
"api-ms-win-core-file-l9-9-9.dll",
|
||||
"api-ms-win-core-processthreads",
|
||||
"api-ms-win-core-filesomething.dll",
|
||||
"api-ms-win-crt-unknown-l1-1-0.dll",
|
||||
] {
|
||||
assert_eq!(
|
||||
resolve_api_set_canonical(unknown),
|
||||
"unknown.dll",
|
||||
"{unknown}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
resolve_api_set_canonical("API-MS-Win-Core-Memory-L1-1-0.DLL"),
|
||||
"kernel32.dll"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_api_set_resolution() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Generate the typed runtime adapters and report. Run from the repository root.
|
||||
//! `--check` regenerates in memory and fails if a committed file differs.
|
||||
|
||||
use std::process::ExitCode;
|
||||
use xenora_import_gen::typed::{generate_report, generate_rust, parse};
|
||||
|
||||
const REGISTRY: &str = "crates/loader/runtime/services.txt";
|
||||
const TESTS: &str = "crates/loader/tests/runtime_services.rs";
|
||||
const RUST: &str = "crates/loader/src/runtime_table.rs";
|
||||
const REPORT: &str = "docs/runtime/services.md";
|
||||
|
||||
fn run() -> Result<String, String> {
|
||||
let mode = std::env::args().nth(1).unwrap_or_default();
|
||||
let read = |path: &str| std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"));
|
||||
let services =
|
||||
parse(&read(REGISTRY)?, &read(TESTS)?).map_err(|e| format!("{REGISTRY}: {e}"))?;
|
||||
let outputs = [
|
||||
(RUST, generate_rust(&services)),
|
||||
(REPORT, generate_report(&services)),
|
||||
];
|
||||
for (path, text) in &outputs {
|
||||
match mode.as_str() {
|
||||
"generate" => std::fs::write(path, text).map_err(|e| format!("{path}: {e}"))?,
|
||||
"--check" if read(path)? != *text => {
|
||||
return Err(format!(
|
||||
"{path} is out of date; run xenora-runtime-gen generate"
|
||||
));
|
||||
}
|
||||
"--check" | "validate" => {}
|
||||
_ => return Err("usage: xenora-runtime-gen validate|generate|--check".into()),
|
||||
}
|
||||
}
|
||||
Ok(format!("{} services", services.len()))
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
match run() {
|
||||
Ok(message) => {
|
||||
println!("{message}");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(message) => {
|
||||
eprintln!("{message}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -130,7 +130,7 @@ fn gen_crt_native_registration(module: &str, symbol: &str, libc_sym: &str, note:
|
||||
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> {{
|
||||
|args: &Win64Args, cpu: &mut CpuState, mem: &mut GuestMemory| -> Result<u64, ExitReason> {{
|
||||
{dispatch}
|
||||
}},
|
||||
);
|
||||
@@ -151,9 +151,8 @@ 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> {{
|
||||
// Safe-CRT wrapper: delegates to underlying function, ignores size argument.
|
||||
// Guest memory is already bounds-checked by the caller's service dispatch.
|
||||
Ok(0) // success
|
||||
// Not implemented: fails explicitly instead of reporting success.
|
||||
Err(ExitReason::IllegalInstruction(0xFE)) // 0xFE = Unsupported Host Service Call
|
||||
}},
|
||||
);
|
||||
"#,
|
||||
@@ -162,15 +161,8 @@ fn gen_crt_wrapper_registration(module: &str, symbol: &str, _libc_sym: &str, not
|
||||
|
||||
/// Generate a registration for a runtime helper (EH frame handlers, etc.).
|
||||
fn gen_runtime_helper_registration(module: &str, symbol: &str, note: &str) -> String {
|
||||
// Most runtime helpers either call abort or return 0
|
||||
let body = if symbol.contains("Throw")
|
||||
|| symbol.contains("terminate")
|
||||
|| symbol.contains("purecall")
|
||||
{
|
||||
"// C++ exception/terminate: halt guest execution.\n Err(ExitReason::Halted)"
|
||||
} else {
|
||||
"Ok(0)"
|
||||
};
|
||||
// Not implemented: fails explicitly instead of reporting success.
|
||||
let body = "Err(ExitReason::IllegalInstruction(0xFE)) // 0xFE = Unsupported Host Service Call";
|
||||
format!(
|
||||
r#"
|
||||
// {note}
|
||||
@@ -194,7 +186,7 @@ fn gen_stubs(manifest: &Manifest) -> String {
|
||||
out.push_str(
|
||||
r#"
|
||||
//! Auto-generated Win32 service stubs.
|
||||
//! Each stub logs its call site (module + symbol) and returns a safe default value.
|
||||
//! Each stub stops the guest with an explicit unsupported-service exit.
|
||||
//! Do not edit manually — regenerate with `xenora imports generate`.
|
||||
|
||||
use crate::cpu::{CpuState, ExitReason};
|
||||
@@ -350,10 +342,11 @@ fn crt_dispatch_expr(symbol: &str, libc_sym: &str) -> String {
|
||||
"acos" | "asin" | "atan" | "cos" | "sin" | "tan" | "exp" | "log" | "log10" | "log2"
|
||||
| "sqrt" | "fabs" | "floor" | "ceil" | "round" | "trunc" | "exp2" => {
|
||||
format!(
|
||||
r#"let x = f64::from_bits(args.rcx);
|
||||
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) }};
|
||||
Ok(r.to_bits())"#,
|
||||
cpu.xmm[0] = u128::from(r.to_bits());
|
||||
Ok(0)"#,
|
||||
libc_sym = libc_sym,
|
||||
)
|
||||
}
|
||||
@@ -362,49 +355,54 @@ fn crt_dispatch_expr(symbol: &str, libc_sym: &str) -> String {
|
||||
| "log2f" | "sqrtf" | "fabsf" | "floorf" | "ceilf" | "roundf" | "truncf" | "cbrtf"
|
||||
| "erff" | "exp2f" => {
|
||||
format!(
|
||||
r#"let x = f32::from_bits(args.rcx as u32);
|
||||
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) }};
|
||||
Ok(r.to_bits() as u64)"#,
|
||||
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(args.rcx);
|
||||
let y = f64::from_bits(args.rdx);
|
||||
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) }};
|
||||
Ok(r.to_bits())"#,
|
||||
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(args.rcx as u32);
|
||||
let y = f32::from_bits(args.rdx as u32);
|
||||
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) }};
|
||||
Ok(r.to_bits() as u64)"#,
|
||||
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(args.rcx);
|
||||
let y = f64::from_bits(args.rdx);
|
||||
let z = f64::from_bits(args.r8);
|
||||
"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) };
|
||||
Ok(r.to_bits())"#
|
||||
cpu.xmm[0] = u128::from(r.to_bits());
|
||||
Ok(0)"#
|
||||
.to_string(),
|
||||
"fmaf" => r#"let x = f32::from_bits(args.rcx as u32);
|
||||
let y = f32::from_bits(args.rdx as u32);
|
||||
let z = f32::from_bits(args.r8 as u32);
|
||||
"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) };
|
||||
Ok(r.to_bits() as u64)"#
|
||||
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
|
||||
|
||||
@@ -31,6 +31,7 @@ pub mod ingest;
|
||||
pub mod manifest;
|
||||
pub mod metadata;
|
||||
pub mod parse;
|
||||
pub mod typed;
|
||||
pub mod verify;
|
||||
|
||||
pub use apiset::{get_api_sets_for_canonical, resolve_api_set_canonical};
|
||||
|
||||
@@ -0,0 +1,453 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Typed runtime services: parse and validate the declarative registry, and
|
||||
//! generate Win64 adapters, static metadata and a coverage report.
|
||||
|
||||
use crate::apiset::get_api_sets_for_canonical;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::fmt::Write as _;
|
||||
|
||||
/// Most arguments one service may declare.
|
||||
const MAX_PARAMETERS: usize = 16;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Parameter {
|
||||
pub name: String,
|
||||
pub kind: String,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Service {
|
||||
pub library: String,
|
||||
pub symbol: String,
|
||||
pub parameters: Vec<Parameter>,
|
||||
pub result: String,
|
||||
pub handler: String,
|
||||
pub status: String,
|
||||
pub aliases: Vec<String>,
|
||||
pub failure: String,
|
||||
pub reference: String,
|
||||
pub tests: Vec<String>,
|
||||
}
|
||||
|
||||
fn is_identifier(text: &str) -> bool {
|
||||
!text.is_empty()
|
||||
&& !text.as_bytes()[0].is_ascii_digit()
|
||||
&& text.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
|
||||
}
|
||||
|
||||
/// Adapter expression reading parameter `index`, or `None` for an unknown type.
|
||||
fn reader(kind: &str, index: usize) -> Option<String> {
|
||||
Some(match kind {
|
||||
"u32" | "i32" | "u64" | "bool32" | "f32" | "f64" => format!("call.{kind}({index})?"),
|
||||
"handle" | "ptr" => format!("call.u64({index})?"),
|
||||
_ => {
|
||||
let size: u32 = kind.strip_prefix("out<")?.strip_suffix('>')?.parse().ok()?;
|
||||
if !(1..=4096).contains(&size) {
|
||||
return None;
|
||||
}
|
||||
format!("call.out::<{size}>({index})?")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Rust type of a result other than void.
|
||||
fn result_type(kind: &str) -> &'static str {
|
||||
match kind {
|
||||
"u32" => "u32",
|
||||
"i32" => "i32",
|
||||
"bool32" => "bool",
|
||||
"f32" => "crate::runtime::Float32",
|
||||
"f64" => "crate::runtime::Float64",
|
||||
_ => "u64",
|
||||
}
|
||||
}
|
||||
|
||||
const RESULTS: [&str; 9] = [
|
||||
"void", "u32", "i32", "u64", "bool32", "handle", "ptr", "f32", "f64",
|
||||
];
|
||||
|
||||
/// Parse and validate the registry. `test_source` is the text of the test file
|
||||
/// that must define every named test.
|
||||
pub fn parse(text: &str, test_source: &str) -> Result<Vec<Service>, String> {
|
||||
let mut services: Vec<Service> = Vec::new();
|
||||
let mut seen_fields = BTreeSet::new();
|
||||
for (number, raw) in text.lines().enumerate() {
|
||||
let at = |message: &str| format!("line {}: {message}", number + 1);
|
||||
let line = raw.trim();
|
||||
if line.is_empty() || line.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
let (keyword, rest) = line.split_once(' ').ok_or_else(|| at("missing value"))?;
|
||||
let rest = rest.trim();
|
||||
if keyword == "service" {
|
||||
services.push(parse_signature(rest).map_err(|message| at(&message))?);
|
||||
seen_fields.clear();
|
||||
continue;
|
||||
}
|
||||
let service = services
|
||||
.last_mut()
|
||||
.ok_or_else(|| at("field outside a service"))?;
|
||||
let repeatable = matches!(keyword, "alias" | "test");
|
||||
if !repeatable && !seen_fields.insert(keyword.to_owned()) {
|
||||
return Err(at(&format!("repeated field {keyword}")));
|
||||
}
|
||||
match keyword {
|
||||
"handler" => service.handler = rest.to_owned(),
|
||||
"status" => service.status = rest.to_owned(),
|
||||
"alias" => service.aliases.push(rest.to_owned()),
|
||||
"fails" => service.failure = rest.to_owned(),
|
||||
"ref" => service.reference = rest.to_owned(),
|
||||
"test" => service.tests.push(rest.to_owned()),
|
||||
other => return Err(at(&format!("unknown field {other}"))),
|
||||
}
|
||||
}
|
||||
validate(&services, test_source)?;
|
||||
Ok(services)
|
||||
}
|
||||
|
||||
fn parse_signature(text: &str) -> Result<Service, String> {
|
||||
let (library, rest) = text.split_once(' ').ok_or("missing symbol")?;
|
||||
let (symbol, rest) = rest.split_once('(').ok_or("missing parameter list")?;
|
||||
let (list, result) = rest.rsplit_once(") -> ").ok_or("missing result type")?;
|
||||
let mut parameters = Vec::new();
|
||||
if !list.trim().is_empty() {
|
||||
for parameter in list.split(',') {
|
||||
let (name, kind) = parameter.split_once(':').ok_or("parameter needs a type")?;
|
||||
parameters.push(Parameter {
|
||||
name: name.trim().to_owned(),
|
||||
kind: kind.trim().to_owned(),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(Service {
|
||||
library: library.to_owned(),
|
||||
symbol: symbol.trim().to_owned(),
|
||||
parameters,
|
||||
result: result.trim().to_owned(),
|
||||
handler: String::new(),
|
||||
status: String::new(),
|
||||
aliases: Vec::new(),
|
||||
failure: String::new(),
|
||||
reference: String::new(),
|
||||
tests: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
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();
|
||||
for (index, service) in services.iter().enumerate() {
|
||||
let name = format!("{}!{}", service.library, service.symbol);
|
||||
let fail = |message: String| Err(format!("{name}: {message}"));
|
||||
if service.library != service.library.to_ascii_lowercase()
|
||||
|| !service.library.ends_with(".dll")
|
||||
|| service.library.starts_with("api-ms-")
|
||||
{
|
||||
return fail("library must be a lower-case canonical module".into());
|
||||
}
|
||||
if !is_identifier(&service.symbol) {
|
||||
return fail("symbol is not an identifier".into());
|
||||
}
|
||||
if !is_identifier(&service.handler) {
|
||||
return fail("missing or invalid handler".into());
|
||||
}
|
||||
if service.parameters.len() > MAX_PARAMETERS {
|
||||
return fail("too many parameters".into());
|
||||
}
|
||||
let mut names = BTreeSet::new();
|
||||
for (position, parameter) in service.parameters.iter().enumerate() {
|
||||
if !is_identifier(¶meter.name) || !names.insert(¶meter.name) {
|
||||
return fail(format!("invalid parameter name {:?}", parameter.name));
|
||||
}
|
||||
if reader(¶meter.kind, position).is_none() {
|
||||
return fail(format!("unsupported parameter type {:?}", parameter.kind));
|
||||
}
|
||||
}
|
||||
if !RESULTS.contains(&service.result.as_str()) {
|
||||
return fail(format!("unsupported result type {:?}", service.result));
|
||||
}
|
||||
if !matches!(service.status.as_str(), "implemented" | "partial" | "stub") {
|
||||
return fail("status must be implemented, partial or stub".into());
|
||||
}
|
||||
if service.failure.is_empty() || service.reference.is_empty() {
|
||||
return fail("needs a failure contract and a reference".into());
|
||||
}
|
||||
if service.tests.is_empty() && service.status != "stub" {
|
||||
return fail("needs a test before it may claim behaviour".into());
|
||||
}
|
||||
for test in &service.tests {
|
||||
if !is_identifier(test) || !test_source.contains(&format!("fn {test}()")) {
|
||||
return fail(format!("test {test} does not exist"));
|
||||
}
|
||||
}
|
||||
let documented = get_api_sets_for_canonical(&service.library);
|
||||
let modules = std::iter::once(&service.library).chain(&service.aliases);
|
||||
for module in modules {
|
||||
if module != &service.library && !documented.contains(&module.as_str()) {
|
||||
return fail(format!("{module} is not a listed API set of its library"));
|
||||
}
|
||||
if keys
|
||||
.insert((module.clone(), &service.symbol), index)
|
||||
.is_some()
|
||||
{
|
||||
return fail(format!("{module} already resolves this symbol"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn status_variant(status: &str) -> &'static str {
|
||||
match status {
|
||||
"implemented" => "Implemented",
|
||||
"partial" => "Partial",
|
||||
_ => "Stub",
|
||||
}
|
||||
}
|
||||
|
||||
fn string_list(items: &[String]) -> String {
|
||||
let quoted: Vec<String> = items.iter().map(|item| format!("{item:?}")).collect();
|
||||
format!("&[{}]", quoted.join(", "))
|
||||
}
|
||||
|
||||
/// Rust source of the adapters and metadata.
|
||||
pub fn generate_rust(services: &[Service]) -> String {
|
||||
let mut out = String::from(
|
||||
"// SPDX-License-Identifier: GPL-3.0-or-later\n\n\
|
||||
// Generated by xenora-runtime-gen from crates/loader/runtime/services.txt.\n\
|
||||
// Do not edit.\n\n\
|
||||
use crate::imports::{ImportRegistry, ServiceStatus};\n\
|
||||
use crate::runtime::{Call, Parameter, Return, ServiceContext, ServiceMetadata};\n\
|
||||
use crate::services::{ServicesState, handlers};\n\
|
||||
use std::sync::Arc;\n\n",
|
||||
);
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"pub static SERVICES: [ServiceMetadata; {}] = [",
|
||||
services.len()
|
||||
);
|
||||
for service in services {
|
||||
let parameters: Vec<String> = service
|
||||
.parameters
|
||||
.iter()
|
||||
.map(|p| format!("Parameter {{ name: {:?}, kind: {:?} }}", p.name, p.kind))
|
||||
.collect();
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" ServiceMetadata {{\n library: {:?},\n symbol: {:?},\n \
|
||||
parameters: &[{}],\n result: {:?},\n status: ServiceStatus::{},\n \
|
||||
aliases: {},\n failure: {:?},\n reference: {:?},\n tests: {},\n }},",
|
||||
service.library,
|
||||
service.symbol,
|
||||
parameters.join(", "),
|
||||
service.result,
|
||||
status_variant(&service.status),
|
||||
string_list(&service.aliases),
|
||||
service.failure,
|
||||
service.reference,
|
||||
string_list(&service.tests),
|
||||
);
|
||||
}
|
||||
out.push_str(
|
||||
"];\n\n/// Register every generated service and its API-set aliases.\n\
|
||||
pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {\n",
|
||||
);
|
||||
for service in services {
|
||||
let count = service.parameters.len();
|
||||
let names: String = (0..count).map(|index| format!(", a{index}")).collect();
|
||||
let _ = writeln!(
|
||||
out,
|
||||
" let s = state.clone();\n registry.register_with_status({:?}, {:?}, ServiceStatus::{}, move |args, cpu, memory| {{",
|
||||
service.library,
|
||||
service.symbol,
|
||||
status_variant(&service.status),
|
||||
);
|
||||
if count == 0 {
|
||||
out.push_str(" let _ = (args, &Call::new);\n");
|
||||
} else {
|
||||
out.push_str(" let call = Call::new(args, cpu, memory);\n");
|
||||
}
|
||||
for (index, parameter) in service.parameters.iter().enumerate() {
|
||||
let read = reader(¶meter.kind, index).unwrap_or_default();
|
||||
let _ = writeln!(out, " let a{index} = {read};");
|
||||
}
|
||||
// The declared type is stated so that a handler returning another one
|
||||
// does not compile.
|
||||
let binding = match service.result.as_str() {
|
||||
"void" => "let ()".to_owned(),
|
||||
result => format!("let result: {}", result_type(result)),
|
||||
};
|
||||
let place = if service.result == "void" {
|
||||
"Ok(0)"
|
||||
} 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 }});",
|
||||
service.handler
|
||||
);
|
||||
}
|
||||
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(
|
||||
" let _ = (args, &Call::new);\n",
|
||||
" let _ = args;\n",
|
||||
)
|
||||
}
|
||||
|
||||
/// Coverage report. Each count is distinct; aliases are never services.
|
||||
pub fn generate_report(services: &[Service]) -> String {
|
||||
let count = |status: &str| services.iter().filter(|s| s.status == status).count();
|
||||
let handlers: BTreeSet<&str> = services.iter().map(|s| s.handler.as_str()).collect();
|
||||
let aliases: usize = services.iter().map(|s| s.aliases.len()).sum();
|
||||
let tested = services.iter().filter(|s| !s.tests.is_empty()).count();
|
||||
let mut out = String::from(
|
||||
"# Typed runtime services\n\nGenerated by `xenora-runtime-gen` from `crates/loader/runtime/services.txt`. Do not edit.\n\n\
|
||||
A declared service is not a claim of compatibility. `implemented` and `partial` describe behaviour against the documented contract for the synthetic guest. No service has been independently accepted.\n\n\
|
||||
| Measure | Count |\n| --- | ---: |\n",
|
||||
);
|
||||
for (label, value) in [
|
||||
("Services with a declared ABI", services.len()),
|
||||
("Generated adapters", services.len()),
|
||||
("Unique handler implementations", handlers.len()),
|
||||
("Implemented", count("implemented")),
|
||||
("Partial", count("partial")),
|
||||
("Stub", count("stub")),
|
||||
("Conformance-tested through guest dispatch", tested),
|
||||
("API-set aliases (not services)", aliases),
|
||||
("Independently accepted", 0),
|
||||
] {
|
||||
let _ = writeln!(out, "| {label} | {value} |");
|
||||
}
|
||||
out.push_str("\n| Service | Signature | Status | Failure |\n| --- | --- | --- | --- |\n");
|
||||
for service in services {
|
||||
let parameters: Vec<String> = service
|
||||
.parameters
|
||||
.iter()
|
||||
.map(|p| format!("{}: {}", p.name, p.kind))
|
||||
.collect();
|
||||
let _ = writeln!(
|
||||
out,
|
||||
"| `{}!{}` | `({}) -> {}` | {} | {} |",
|
||||
service.library,
|
||||
service.symbol,
|
||||
parameters.join(", "),
|
||||
service.result,
|
||||
service.status,
|
||||
service.failure
|
||||
);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const TESTS: &str = "fn works() {}";
|
||||
|
||||
fn entry(signature: &str, extra: &str) -> String {
|
||||
format!(
|
||||
"service {signature}\nhandler h\nstatus partial\nfails never\nref x.h\ntest works\n{extra}\n"
|
||||
)
|
||||
}
|
||||
|
||||
fn rejects(text: &str, message: &str) {
|
||||
let error = parse(text, TESTS).unwrap_err();
|
||||
assert!(error.contains(message), "{error}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_entries_parse_and_generate_deterministically() {
|
||||
let text = entry(
|
||||
"kernel32.dll F(a: u32, b: f64, c: out<8>) -> handle",
|
||||
"alias api-ms-win-core-memory-l1-1-0.dll",
|
||||
);
|
||||
let services = parse(&text, TESTS).unwrap();
|
||||
assert_eq!(services[0].parameters[2].kind, "out<8>");
|
||||
let rust = generate_rust(&services);
|
||||
assert_eq!(rust, generate_rust(&services));
|
||||
for expected in ["call.u32(0)?", "call.f64(1)?", "call.out::<8>(2)?"] {
|
||||
assert!(rust.contains(expected), "{expected}");
|
||||
}
|
||||
assert!(generate_report(&services).contains("| Unique handler implementations | 1 |"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conflicting_keys_are_rejected() {
|
||||
let one = entry("kernel32.dll F() -> void", "");
|
||||
rejects(&(one.clone() + &one), "already resolves");
|
||||
let aliased = entry(
|
||||
"kernel32.dll F() -> void",
|
||||
"alias api-ms-win-core-memory-l1-1-0.dll",
|
||||
);
|
||||
let twice = entry(
|
||||
"kernel32.dll G() -> void",
|
||||
"alias api-ms-win-core-memory-l1-1-0.dll\nalias api-ms-win-core-memory-l1-1-0.dll",
|
||||
);
|
||||
assert!(parse(&aliased, TESTS).is_ok());
|
||||
rejects(&twice, "already resolves");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_declarations_are_rejected() {
|
||||
rejects(
|
||||
&entry("kernel32.dll F(a: struct) -> void", ""),
|
||||
"parameter type",
|
||||
);
|
||||
rejects(
|
||||
&entry("kernel32.dll F(a: out<0>) -> void", ""),
|
||||
"parameter type",
|
||||
);
|
||||
rejects(
|
||||
&entry("kernel32.dll F(a: void) -> void", ""),
|
||||
"parameter type",
|
||||
);
|
||||
rejects(&entry("kernel32.dll F() -> out<4>", ""), "result type");
|
||||
rejects(
|
||||
&entry("kernel32.dll F(a: u32, a: u32) -> void", ""),
|
||||
"parameter name",
|
||||
);
|
||||
rejects(&entry("Kernel32.dll F() -> void", ""), "canonical module");
|
||||
rejects(
|
||||
&entry("api-ms-win-core-memory-l1-1-0.dll F() -> void", ""),
|
||||
"canonical module",
|
||||
);
|
||||
rejects(
|
||||
&entry(
|
||||
"kernel32.dll F() -> void",
|
||||
"alias api-ms-win-core-made-up-l1-1-0.dll",
|
||||
),
|
||||
"not a listed API set",
|
||||
);
|
||||
rejects(
|
||||
&entry("kernel32.dll F() -> void", "colour blue"),
|
||||
"unknown field",
|
||||
);
|
||||
rejects(
|
||||
&entry("kernel32.dll F() -> void", "status stub"),
|
||||
"repeated field",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn behaviour_needs_evidence() {
|
||||
let untested =
|
||||
"service kernel32.dll F() -> void\nhandler h\nstatus partial\nfails never\nref x.h\n";
|
||||
rejects(untested, "needs a test");
|
||||
rejects(&(untested.to_owned() + "test missing\n"), "does not exist");
|
||||
let stub = untested.replace("partial", "stub");
|
||||
assert!(parse(&stub, TESTS).is_ok());
|
||||
rejects(
|
||||
&untested.replace("ref x.h\n", "test works\n"),
|
||||
"needs a failure contract",
|
||||
);
|
||||
rejects("handler h\n", "outside a service");
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,6 @@ VARIANTS = (
|
||||
("V_ADD_NC_U32", "ENC_VOP3"),
|
||||
("S_ENDPGM", "ENC_SOPP"),
|
||||
("S_MOV_B32", "ENC_SOP1"),
|
||||
("S_CMP_EQ_U32", "ENC_SOPC"),
|
||||
("S_CBRANCH_SCC0", "ENC_SOPP"),
|
||||
("S_CBRANCH_EXECZ", "ENC_SOPP"),
|
||||
("S_CBRANCH_VCCZ", "ENC_SOPP"),
|
||||
|
||||
@@ -38,8 +38,70 @@ FORM_KEYS = {
|
||||
}
|
||||
TOP_KEYS = {"schema", "architecture", "source_sha256", "documents", "operand_rules", "form"}
|
||||
|
||||
OPERATIONS = {"add": "Add", "sub": "Sub", "and": "And", "or": "Or", "xor": "Xor"}
|
||||
LOGICAL = {"and", "or", "xor"}
|
||||
OPERATIONS = {
|
||||
"add": "Add", "sub": "Sub", "and": "And", "or": "Or", "xor": "Xor",
|
||||
"andn2": "AndNot", "orn2": "OrNot", "nand": "Nand", "nor": "Nor", "xnor": "Xnor",
|
||||
"lshl": "ShiftLeft", "lshr": "LogicalShiftRight", "ashr": "ArithmeticShiftRight",
|
||||
"compare": "Compare",
|
||||
"not": "Not", "brev": "ReverseBits", "bcnt0": "CountZeros", "bcnt1": "CountOnes",
|
||||
"ff0": "FindFirstZero", "ff1": "FindFirstOne", "flbit": "FindLastBit",
|
||||
"sext": "SignExtend", "abs": "Absolute",
|
||||
"min": "Minimum", "max": "Maximum", "cselect": "Select", "bfm": "BitfieldMask",
|
||||
"mul": "Multiply", "mul_hi": "MultiplyHigh", "bfe": "BitfieldExtract",
|
||||
"absdiff": "AbsoluteDifference", "lshl_add": "ShiftLeftAdd",
|
||||
"mul24": "Multiply24", "mul_hi24": "MultiplyHigh24",
|
||||
}
|
||||
# Unary operations read one source; they need an operand rule of the unary kind.
|
||||
UNARY = {"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "flbit", "sext", "abs"}
|
||||
# Sign extension reads only the low source_bits of S0 (required for sext only).
|
||||
SOURCE_BITS_KEY = "source_bits"
|
||||
SOURCE_BITS = {8, 16}
|
||||
# Compares take a relation (S0 on the left) and set SCC to whether it holds.
|
||||
RELATION_KEY = "relation"
|
||||
RELATIONS = {
|
||||
"eq": "Equal", "lg": "NotEqual", "gt": "Greater", "ge": "GreaterOrEqual",
|
||||
"lt": "Less", "le": "LessOrEqual",
|
||||
}
|
||||
# (relation, signedness) -> primitive. Equality does not depend on signedness,
|
||||
# so both declared signednesses of EQ and LG share one primitive.
|
||||
COMPARE_PRIMITIVES = {
|
||||
("eq", "signed"): "eq_b32", ("eq", "unsigned"): "eq_b32",
|
||||
("lg", "signed"): "ne_b32", ("lg", "unsigned"): "ne_b32",
|
||||
("gt", "signed"): "gt_i32", ("gt", "unsigned"): "gt_u32",
|
||||
("ge", "signed"): "ge_i32", ("ge", "unsigned"): "ge_u32",
|
||||
("lt", "signed"): "lt_i32", ("lt", "unsigned"): "lt_u32",
|
||||
("le", "signed"): "le_i32", ("le", "unsigned"): "le_u32",
|
||||
}
|
||||
# Logical operations take untyped bits; arithmetic ones never do. Shifts take
|
||||
# the signedness their primitive names, and their S1 is an unsigned count.
|
||||
LOGICAL = {
|
||||
"and", "or", "xor", "andn2", "orn2", "nand", "nor", "xnor",
|
||||
"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "cselect", "bfm",
|
||||
}
|
||||
ARITHMETIC = {
|
||||
"add", "sub", "min", "max", "mul", "mul_hi", "bfe", "absdiff", "lshl_add", "mul24", "mul_hi24",
|
||||
}
|
||||
SHIFTS = {"lshl", "lshr", "ashr"}
|
||||
# Operations whose S1 is an unsigned control word (a shift count or a bit-field
|
||||
# descriptor), so the XML gives it FMT_NUM_U32 whatever the form's signedness.
|
||||
CONTROL_S1 = SHIFTS | {"bfe"}
|
||||
# Operations that always read SCC: the select condition. They need carry_in scc.
|
||||
SCC_READERS = {"cselect"}
|
||||
# XML number formats a source may have for each declared signedness.
|
||||
SOURCE_FORMATS = {
|
||||
"signed": {"FMT_NUM_I32"},
|
||||
"unsigned": {"FMT_NUM_U32"},
|
||||
"bitwise": {"FMT_NUM_U32", "FMT_NUM_B32"},
|
||||
}
|
||||
# Optional keys: required exactly when the condition holds.
|
||||
SHIFT_KEY = "shift_count_bits"
|
||||
# Shift-and-add declares its fixed S0 shift (required for lshl_add only).
|
||||
SHIFT_AMOUNT_KEY = "shift_amount"
|
||||
SHIFT_AMOUNTS = {1, 2, 3, 4}
|
||||
# Vector forms whose guide pseudocode reads S1 before S0 (D = op(S1, S0))
|
||||
# declare it; the XML records no operand order.
|
||||
SOURCE_ORDER_KEY = "source_order"
|
||||
SOURCE_ORDERS = {"reversed"}
|
||||
SIGNEDNESS = {"unsigned": "Unsigned", "signed": "Signed", "bitwise": "Bitwise"}
|
||||
CARRY_IN = {"none": "None", "scc": "Scc"}
|
||||
SCC = {
|
||||
@@ -48,6 +110,8 @@ SCC = {
|
||||
"borrow": "Borrow",
|
||||
"signed_overflow": "SignedOverflow",
|
||||
"nonzero": "Nonzero",
|
||||
"relation": "Relation",
|
||||
"selected_src0": "SelectedSrc0",
|
||||
}
|
||||
MASK = {"unchanged": "Unchanged"}
|
||||
WAVE = {"any": "Any", "wave32": "Wave32"}
|
||||
@@ -86,6 +150,53 @@ PRIMITIVES = {
|
||||
("and", "bitwise"): ("nonzero", "and_nonzero_b32", False),
|
||||
("or", "bitwise"): ("nonzero", "or_nonzero_b32", False),
|
||||
("xor", "bitwise"): ("nonzero", "xor_nonzero_b32", False),
|
||||
("andn2", "bitwise"): ("nonzero", "andn2_nonzero_b32", False),
|
||||
("orn2", "bitwise"): ("nonzero", "orn2_nonzero_b32", False),
|
||||
("nand", "bitwise"): ("nonzero", "nand_nonzero_b32", False),
|
||||
("nor", "bitwise"): ("nonzero", "nor_nonzero_b32", False),
|
||||
("xnor", "bitwise"): ("nonzero", "xnor_nonzero_b32", False),
|
||||
("lshl", "bitwise"): ("nonzero", "lshl_nonzero_b32", False),
|
||||
("lshr", "unsigned"): ("nonzero", "lshr_nonzero_b32", False),
|
||||
("ashr", "signed"): ("nonzero", "ashr_nonzero_i32", False),
|
||||
("not", "bitwise"): ("nonzero", "not_nonzero_b32", False),
|
||||
("brev", "bitwise"): ("unchanged", "brev_b32", False),
|
||||
("bcnt0", "bitwise"): ("nonzero", "bcnt0_nonzero_b32", False),
|
||||
("bcnt1", "bitwise"): ("nonzero", "bcnt1_nonzero_b32", False),
|
||||
("ff0", "bitwise"): ("unchanged", "ff0_b32", False),
|
||||
("ff1", "bitwise"): ("unchanged", "ff1_b32", False),
|
||||
("flbit", "bitwise"): ("unchanged", "flbit_b32", False),
|
||||
("flbit", "signed"): ("unchanged", "flbit_i32", False),
|
||||
("sext", "signed"): ("unchanged", "sext_i32", False),
|
||||
("abs", "signed"): ("nonzero", "abs_nonzero_i32", False),
|
||||
("min", "signed"): ("selected_src0", "min_i32", False),
|
||||
("min", "unsigned"): ("selected_src0", "min_u32", False),
|
||||
("max", "signed"): ("selected_src0", "max_i32", False),
|
||||
("max", "unsigned"): ("selected_src0", "max_u32", False),
|
||||
("cselect", "bitwise"): ("unchanged", "cselect_b32", True),
|
||||
("bfm", "bitwise"): ("unchanged", "bfm_b32", False),
|
||||
("mul", "signed"): ("unchanged", "mul_lo_i32", False),
|
||||
("mul_hi", "unsigned"): ("unchanged", "mul_hi_u32", False),
|
||||
("mul_hi", "signed"): ("unchanged", "mul_hi_i32", False),
|
||||
("bfe", "unsigned"): ("nonzero", "bfe_nonzero_u32", False),
|
||||
("bfe", "signed"): ("nonzero", "bfe_nonzero_i32", False),
|
||||
("absdiff", "signed"): ("nonzero", "absdiff_nonzero_i32", False),
|
||||
("lshl_add", "unsigned"): ("carry_out", "lshl_add_carry_u32", False),
|
||||
}
|
||||
|
||||
# Vector (VOP2) forms: (operation, signedness) -> the per-lane VectorBinary their
|
||||
# MSL lowering uses. They write no SCC, VCC or EXEC, so scc must be unchanged.
|
||||
VECTOR_PRIMITIVES = {
|
||||
("add", "unsigned"): "Add",
|
||||
("sub", "unsigned"): "Sub",
|
||||
("xnor", "bitwise"): "Xnor",
|
||||
("min", "signed"): "MinSigned",
|
||||
("min", "unsigned"): "MinUnsigned",
|
||||
("max", "signed"): "MaxSigned",
|
||||
("max", "unsigned"): "MaxUnsigned",
|
||||
("mul24", "signed"): "Mul24Signed",
|
||||
("mul24", "unsigned"): "Mul24Unsigned",
|
||||
("mul_hi24", "signed"): "MulHi24Signed",
|
||||
("mul_hi24", "unsigned"): "MulHi24Unsigned",
|
||||
}
|
||||
|
||||
# Operand rules the decoder implements, each exactly once. A registry rule must
|
||||
@@ -94,6 +205,9 @@ UNSUPPORTED_COMBOS = {
|
||||
"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",
|
||||
}
|
||||
# Every combo name a rule may list (VOP2 also names vcc_hi and NULL sources,
|
||||
# which SOP2 groups under src_vcc and src_special).
|
||||
ALL_COMBOS = UNSUPPORTED_COMBOS | {"src_vcc_hi", "src_null"}
|
||||
OPERAND_RULES = {
|
||||
"sop2_sgpr": {
|
||||
"rust": "Sop2Sgpr",
|
||||
@@ -109,6 +223,55 @@ OPERAND_RULES = {
|
||||
},
|
||||
# Every one of these is rejected by the decoder's SOP2 operand checks.
|
||||
"unsupported": UNSUPPORTED_COMBOS,
|
||||
"kind": "alu",
|
||||
},
|
||||
"sopc_scalar": {
|
||||
"rust": "SopcScalar",
|
||||
"enum": "ScalarCompareOp",
|
||||
"shape": {
|
||||
"family": "SOPC",
|
||||
"src": [
|
||||
{"field": "SSRC0", "class": "scalar_source"},
|
||||
{"field": "SSRC1", "class": "scalar_source"},
|
||||
],
|
||||
"max_literals": 1,
|
||||
},
|
||||
# SOPC has no destination field; the decoder rejects these sources.
|
||||
"unsupported": {combo for combo in UNSUPPORTED_COMBOS if not combo.startswith("dst_")},
|
||||
"kind": "compare",
|
||||
},
|
||||
"sop1_sgpr": {
|
||||
"rust": "Sop1Sgpr",
|
||||
"enum": "ScalarUnaryOp",
|
||||
"shape": {
|
||||
"family": "SOP1",
|
||||
"dst": {"field": "SDST", "class": "sgpr", "min": 0, "max": 105},
|
||||
"src": [{"field": "SSRC0", "class": "scalar_source"}],
|
||||
"max_literals": 1,
|
||||
},
|
||||
# One source, so two literals cannot occur; the rest are rejected.
|
||||
"unsupported": {combo for combo in UNSUPPORTED_COMBOS if combo != "two_literals"},
|
||||
"kind": "unary",
|
||||
},
|
||||
"vop2_vgpr": {
|
||||
"rust": "Vop2Vgpr",
|
||||
"enum": "VectorAluOp",
|
||||
"shape": {
|
||||
"family": "VOP2",
|
||||
"dst": {"field": "VDST", "class": "vgpr", "min": 0, "max": 255},
|
||||
"src": [
|
||||
{"field": "SRC0", "class": "vector_source"},
|
||||
{"field": "VSRC1", "class": "vgpr"},
|
||||
],
|
||||
"max_literals": 1,
|
||||
},
|
||||
# vector_source = VGPR, s0-s105, vcc_lo, inline integer -16..64 or a
|
||||
# literal; the decoder rejects these SRC0 selectors.
|
||||
"unsupported": {
|
||||
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline",
|
||||
"src_special",
|
||||
},
|
||||
"kind": "vector",
|
||||
},
|
||||
}
|
||||
|
||||
@@ -157,7 +320,7 @@ def _check_rule(name, rule, errors):
|
||||
errors.append(f"operand rule {name}: not implemented by the decoder")
|
||||
return
|
||||
unsupported = rule.get("unsupported", [])
|
||||
unknown = sorted(set(unsupported) - UNSUPPORTED_COMBOS)
|
||||
unknown = sorted(set(unsupported) - ALL_COMBOS)
|
||||
if unknown:
|
||||
errors.append(f"operand rule {name}: unknown unsupported combos {unknown}")
|
||||
if len(set(unsupported)) != len(unsupported):
|
||||
@@ -192,30 +355,53 @@ def _check_xml(form, rule, snapshot, errors):
|
||||
errors.append(f"{label}: opcode {form['opcode']} is not an identifier of {encoding_name}")
|
||||
operands = {}
|
||||
scc_in = scc_out = False
|
||||
implicit = set()
|
||||
for field, data_format, kind, size, is_input, is_output, _implicit, _encoded in variant["operands"]:
|
||||
if kind == "OPR_SSRC_SPECIAL_SCC":
|
||||
scc_in |= is_input
|
||||
scc_out |= is_output
|
||||
elif field:
|
||||
operands[field] = (data_format, size, is_input, is_output)
|
||||
else:
|
||||
implicit.add(kind)
|
||||
# The vocabulary can state only SCC effects (vcc and exec are "unchanged"),
|
||||
# so any other implicit XML operand, such as VCC, is undeclared.
|
||||
if implicit:
|
||||
errors.append(f"{label}: XML implicit operands {sorted(implicit)} are not declared")
|
||||
if scc_in != (form["carry_in"] == "scc"):
|
||||
errors.append(f"{label}: carry_in {form['carry_in']} contradicts the XML SCC input")
|
||||
if scc_out != (form["scc"] != "unchanged"):
|
||||
errors.append(f"{label}: scc {form['scc']} contradicts the XML SCC output")
|
||||
if rule is None:
|
||||
return
|
||||
fields = [(rule["dst"]["field"], False)] + [(src["field"], True) for src in rule["src"]]
|
||||
if not isinstance(rule.get("src"), list) or not all(
|
||||
isinstance(src, dict) and isinstance(src.get("field"), str) for src in rule["src"]
|
||||
) or ("dst" in rule and not (isinstance(rule["dst"], dict) and "field" in rule["dst"])):
|
||||
return # the rule check already reported the malformed shape
|
||||
fields = [(rule["dst"]["field"], False)] if "dst" in rule else []
|
||||
fields += [(src["field"], True) for src in rule["src"]]
|
||||
shift = form["operation"] in CONTROL_S1 and len(rule["src"]) > 1
|
||||
count_field = rule["src"][1]["field"] if shift else None
|
||||
for field, is_source in fields:
|
||||
if field not in operands:
|
||||
errors.append(f"{label}: XML has no operand {field}")
|
||||
continue
|
||||
data_format, size, is_input, is_output = operands[field]
|
||||
if size != form["width"]:
|
||||
errors.append(f"{label}: {field} is {size} bits in the XML, declared {form['width']}")
|
||||
bits = form.get(SOURCE_BITS_KEY) if is_source else None
|
||||
expected = bits if type(bits) is int else form["width"]
|
||||
if size != expected:
|
||||
errors.append(f"{label}: {field} is {size} bits in the XML, declared {expected}")
|
||||
if (is_input, is_output) != (is_source, not is_source):
|
||||
errors.append(f"{label}: {field} direction disagrees with the XML")
|
||||
signed_format = data_format.startswith("FMT_NUM_I")
|
||||
if is_source and signed_format != (form["signedness"] == "signed"):
|
||||
if field == count_field:
|
||||
if data_format != "FMT_NUM_U32":
|
||||
errors.append(
|
||||
f"{label}: control operand {field} has XML format {data_format}, not FMT_NUM_U32"
|
||||
)
|
||||
elif type(bits) is int:
|
||||
if data_format != f"FMT_NUM_I{bits}":
|
||||
errors.append(f"{label}: {field} has XML format {data_format}, not FMT_NUM_I{bits}")
|
||||
elif is_source and data_format not in SOURCE_FORMATS.get(form["signedness"], ()):
|
||||
errors.append(
|
||||
f"{label}: signedness {form['signedness']} contradicts XML format {data_format}"
|
||||
)
|
||||
@@ -261,7 +447,10 @@ def validate(registry, snapshot):
|
||||
for index, form in enumerate(forms):
|
||||
label = form.get("name", f"form #{index}")
|
||||
missing = sorted(FORM_KEYS - set(form))
|
||||
extra = sorted(set(form) - FORM_KEYS)
|
||||
extra = sorted(
|
||||
set(form) - FORM_KEYS
|
||||
- {SHIFT_KEY, SHIFT_AMOUNT_KEY, RELATION_KEY, SOURCE_BITS_KEY, SOURCE_ORDER_KEY}
|
||||
)
|
||||
if missing:
|
||||
errors.append(f"{label}: incomplete, missing {missing}")
|
||||
if extra:
|
||||
@@ -289,16 +478,69 @@ def validate(registry, snapshot):
|
||||
for key, value in (
|
||||
("name", form["name"]),
|
||||
("opcode", (form["family"], form["opcode"])),
|
||||
("variant", form["variant"]),
|
||||
# Variants are names in their operand rule's enum.
|
||||
("variant", (_rule_enum(form), form["variant"])),
|
||||
):
|
||||
if value in seen[key]:
|
||||
errors.append(f"{label}: duplicate {key} {value}")
|
||||
shown = form["variant"] if key == "variant" else value
|
||||
errors.append(f"{label}: duplicate {key} {shown}")
|
||||
seen[key].add(value)
|
||||
if (form["signedness"] == "bitwise") != (form["operation"] in LOGICAL):
|
||||
if (form["operation"] in LOGICAL and form["signedness"] != "bitwise") or (
|
||||
form["operation"] in ARITHMETIC and form["signedness"] == "bitwise"
|
||||
):
|
||||
errors.append(
|
||||
f"{label}: signedness {form['signedness']} contradicts operation {form['operation']}"
|
||||
)
|
||||
primitive = PRIMITIVES.get((form["operation"], form["signedness"]))
|
||||
if form["operation"] in SHIFTS:
|
||||
bits = form.get(SHIFT_KEY)
|
||||
if type(bits) is not int or not 0 < bits < 32 or (1 << bits) != form["width"]:
|
||||
errors.append(
|
||||
f"{label}: {SHIFT_KEY} must be log2 of the width ({form['width']}), got {bits!r}"
|
||||
)
|
||||
elif SHIFT_KEY in form:
|
||||
errors.append(f"{label}: {SHIFT_KEY} on a non-shift operation")
|
||||
if form["operation"] == "lshl_add":
|
||||
amount = form.get(SHIFT_AMOUNT_KEY)
|
||||
if type(amount) is not int or amount not in SHIFT_AMOUNTS:
|
||||
errors.append(
|
||||
f"{label}: {SHIFT_AMOUNT_KEY} must be one of {sorted(SHIFT_AMOUNTS)}, got {amount!r}"
|
||||
)
|
||||
elif SHIFT_AMOUNT_KEY in form:
|
||||
errors.append(f"{label}: {SHIFT_AMOUNT_KEY} on a non-lshl_add operation")
|
||||
if SOURCE_ORDER_KEY in form:
|
||||
order = form[SOURCE_ORDER_KEY]
|
||||
if not isinstance(order, str) or order not in SOURCE_ORDERS:
|
||||
errors.append(f"{label}: unknown {SOURCE_ORDER_KEY} {order!r}")
|
||||
elif _rule_kind(form) != "vector":
|
||||
errors.append(f"{label}: {SOURCE_ORDER_KEY} on a non-vector form")
|
||||
if form["operation"] in SCC_READERS and form["carry_in"] != "scc":
|
||||
errors.append(f"{label}: operation {form['operation']} reads SCC (requires carry_in scc)")
|
||||
if form["operation"] == "sext":
|
||||
bits = form.get(SOURCE_BITS_KEY)
|
||||
if type(bits) is not int or bits not in SOURCE_BITS:
|
||||
errors.append(f"{label}: {SOURCE_BITS_KEY} must be one of {sorted(SOURCE_BITS)}, got {bits!r}")
|
||||
elif SOURCE_BITS_KEY in form:
|
||||
errors.append(f"{label}: {SOURCE_BITS_KEY} on a non-sext operation")
|
||||
if form["operation"] == "compare":
|
||||
relation = form.get(RELATION_KEY)
|
||||
if not isinstance(relation, str) or relation not in RELATIONS:
|
||||
errors.append(f"{label}: unknown or missing {RELATION_KEY} {relation!r}")
|
||||
elif (relation, form["signedness"]) not in COMPARE_PRIMITIVES:
|
||||
errors.append(f"{label}: no primitive implements {relation}/{form['signedness']}")
|
||||
if form["scc"] != "relation":
|
||||
errors.append(f"{label}: scc {form['scc']} contradicts compare (requires relation)")
|
||||
if form["carry_in"] != "none":
|
||||
errors.append(f"{label}: carry_in {form['carry_in']} contradicts compare")
|
||||
primitive = ("relation", None, False)
|
||||
elif _rule_kind(form) == "vector":
|
||||
if RELATION_KEY in form:
|
||||
errors.append(f"{label}: {RELATION_KEY} on a non-compare operation")
|
||||
lowering = VECTOR_PRIMITIVES.get((form["operation"], form["signedness"]))
|
||||
primitive = None if lowering is None else ("unchanged", lowering, False)
|
||||
else:
|
||||
if RELATION_KEY in form:
|
||||
errors.append(f"{label}: {RELATION_KEY} on a non-compare operation")
|
||||
primitive = PRIMITIVES.get((form["operation"], form["signedness"]))
|
||||
if primitive is None:
|
||||
errors.append(f"{label}: no primitive implements {form['operation']}/{form['signedness']}")
|
||||
else:
|
||||
@@ -315,6 +557,13 @@ def validate(registry, snapshot):
|
||||
errors.append(f"{label}: unknown operand rule {form['operands']!r}")
|
||||
elif rule.get("family") != form["family"]:
|
||||
errors.append(f"{label}: operand rule {form['operands']} is for {rule.get('family')}")
|
||||
elif form["operands"] in OPERAND_RULES and OPERAND_RULES[form["operands"]]["kind"] != (
|
||||
"compare" if form["operation"] == "compare"
|
||||
else "unary" if form["operation"] in UNARY
|
||||
else "vector" if _rule_kind(form) == "vector" and form["operation"] not in UNARY
|
||||
else "alu"
|
||||
):
|
||||
errors.append(f"{label}: operation {form['operation']} does not fit rule {form['operands']}")
|
||||
_check_spec(label, form["spec"], documents, errors)
|
||||
verify = form["verify"]
|
||||
if not verify:
|
||||
@@ -327,6 +576,23 @@ def validate(registry, snapshot):
|
||||
return errors
|
||||
|
||||
|
||||
def _implemented_rule(form):
|
||||
operands = form.get("operands")
|
||||
return OPERAND_RULES.get(operands) if isinstance(operands, str) else None
|
||||
|
||||
|
||||
def _rule_kind(form):
|
||||
"""The implemented kind of the form's operand rule, or None if unknown."""
|
||||
rule = _implemented_rule(form)
|
||||
return rule["kind"] if rule else None
|
||||
|
||||
|
||||
def _rule_enum(form):
|
||||
"""The generated enum of the form's operand rule, or None if unknown."""
|
||||
rule = _implemented_rule(form)
|
||||
return rule["enum"] if rule else None
|
||||
|
||||
|
||||
def _check_spec(label, spec, documents, errors):
|
||||
has_guide = False
|
||||
for ref in spec:
|
||||
@@ -358,8 +624,9 @@ def render(registry, snapshot):
|
||||
"use crate::primitive;",
|
||||
"use crate::semantics::{",
|
||||
" CarryIn, Document, Evidence, FormSemantics, MaskEffect, Operation, OperandRule, SccEffect,",
|
||||
" Signedness, SpecRef, Wave,",
|
||||
" Signedness, SpecRef, VectorBinary, Wave,",
|
||||
"};",
|
||||
"use crate::CompareRelation;",
|
||||
"",
|
||||
"/// Registry schema of the generated tables.",
|
||||
f"pub const GENERATED_SCHEMA: u32 = {registry['schema']};",
|
||||
@@ -396,6 +663,12 @@ def render(registry, snapshot):
|
||||
f" signedness: Signedness::{SIGNEDNESS[form['signedness']]},",
|
||||
f" carry_in: CarryIn::{CARRY_IN[form['carry_in']]},",
|
||||
f" width: {form['width']},",
|
||||
f" shift_count_bits: {form.get(SHIFT_KEY, 0)},",
|
||||
f" shift_amount: {form.get(SHIFT_AMOUNT_KEY, 0)},",
|
||||
f" swap_sources: {'true' if SOURCE_ORDER_KEY in form else 'false'},",
|
||||
f" source_bits: {form.get(SOURCE_BITS_KEY, form['width'])},",
|
||||
" relation: "
|
||||
+ (f"Some(CompareRelation::{RELATIONS[form[RELATION_KEY]]})," if RELATION_KEY in form else "None,"),
|
||||
f" scc: SccEffect::{SCC[form['scc']]},",
|
||||
f" vcc: MaskEffect::{MASK[form['vcc']]},",
|
||||
f" exec: MaskEffect::{MASK[form['exec']]},",
|
||||
@@ -411,9 +684,21 @@ def render(registry, snapshot):
|
||||
|
||||
def _render_enum(rule_name, forms, snapshot, positions):
|
||||
enum = OPERAND_RULES[rule_name]["enum"]
|
||||
kind = OPERAND_RULES[rule_name]["kind"]
|
||||
table = re.sub(r"(?<!^)(?=[A-Z])", "_", enum).upper() + "_BY_OPCODE"
|
||||
family = forms[0]["family"]
|
||||
encoding = snapshot["encodings"][_family_encoding(family)]
|
||||
mask = encoding["identifier_mask"]
|
||||
(offset, size), = dict((name, ranges) for name, ranges in encoding["fields"])["OP"]
|
||||
op_mask = ((1 << size) - 1) << offset
|
||||
fixed_mask = mask & ~op_mask
|
||||
fixed_bits = encoding["identifiers"][0] & fixed_mask
|
||||
# Every identifier of the family must share the fixed bits, or the split
|
||||
# into an encoding test plus an OP match would change which words match.
|
||||
if any(identifier & fixed_mask != fixed_bits for identifier in encoding["identifiers"]) or (
|
||||
mask & op_mask != op_mask
|
||||
):
|
||||
raise ValueError(f"{family}: identifiers do not split into fixed bits and OP")
|
||||
out = [
|
||||
"",
|
||||
f"/// {family} operations declared in the semantic registry (operand rule `{rule_name}`).",
|
||||
@@ -422,14 +707,26 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
]
|
||||
for form in forms:
|
||||
carry = " plus SCC" if form["carry_in"] == "scc" else ""
|
||||
what = f"compare {form[RELATION_KEY]}" if kind == "compare" else form["operation"]
|
||||
out += [
|
||||
f" /// `{form['name'].lower()}` ({family} opcode {form['opcode']}): "
|
||||
f"{form['signedness']} {form['operation']}{carry}, SCC = {form['scc']}.",
|
||||
f"{form['signedness']} {what}{carry}, SCC = {form['scc']}.",
|
||||
f" {form['variant']},",
|
||||
]
|
||||
by_opcode = {form["opcode"]: form["variant"] for form in forms}
|
||||
out += [
|
||||
"}",
|
||||
"",
|
||||
f"/// {enum} by {family} OP field value; `None` for undeclared opcodes.",
|
||||
f"const {table}: [Option<{enum}>; {1 << size}] = [",
|
||||
]
|
||||
out += [
|
||||
f" Some({enum}::{by_opcode[opcode]})," if opcode in by_opcode else " None,"
|
||||
for opcode in range(1 << size)
|
||||
]
|
||||
out += [
|
||||
"];",
|
||||
"",
|
||||
f"impl {enum} {{",
|
||||
" /// Every operation, in registry order.",
|
||||
f" pub const ALL: [Self; {len(forms)}] = [",
|
||||
@@ -438,15 +735,13 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
out += [
|
||||
" ];",
|
||||
"",
|
||||
f" /// Selects the operation from a first instruction word (mask 0x{mask:09_x}).",
|
||||
f" /// Selects the operation from a first instruction word: the {family} encoding",
|
||||
f" /// bits (mask 0x{fixed_mask:09_x}) and then the OP field (bits {offset}-{offset + size - 1}).",
|
||||
" pub const fn from_word(word: u32) -> Option<Self> {",
|
||||
f" match word & 0x{mask:09_x} {{",
|
||||
]
|
||||
for form in sorted(forms, key=lambda item: item["opcode"]):
|
||||
out.append(f" 0x{_identifier(encoding, form['opcode']):09_x} => Some(Self::{form['variant']}),")
|
||||
out += [
|
||||
" _ => None,",
|
||||
f" if word & 0x{fixed_mask:09_x} != 0x{fixed_bits:09_x} {{",
|
||||
" return None;",
|
||||
" }",
|
||||
f" {table}[((word >> {offset}) & 0x{(1 << size) - 1:x}) as usize]",
|
||||
" }",
|
||||
"",
|
||||
" /// Lower-case mnemonic.",
|
||||
@@ -454,18 +749,6 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
" match self {",
|
||||
]
|
||||
out += [f" Self::{form['variant']} => \"{form['name'].lower()}\"," for form in forms]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// Whether the operation reads SCC as a carry-in or borrow-in.",
|
||||
" pub const fn reads_scc(self) -> bool {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => {'true' if form['carry_in'] == 'scc' else 'false'},"
|
||||
for form in forms
|
||||
]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
@@ -478,20 +761,156 @@ def _render_enum(rule_name, forms, snapshot, positions):
|
||||
out += [
|
||||
" }]",
|
||||
" }",
|
||||
]
|
||||
if kind == "unary":
|
||||
out += [
|
||||
"",
|
||||
" /// Whether the operation writes SCC.",
|
||||
" pub const fn writes_scc(self) -> bool {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => {'false' if form['scc'] == 'unchanged' else 'true'},"
|
||||
for form in forms
|
||||
]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// The result and, for forms that write it, the new SCC (`None` leaves SCC",
|
||||
" /// unchanged).",
|
||||
" pub const fn evaluate(self, src: u32) -> (u32, Option<bool>) {",
|
||||
" match self {",
|
||||
]
|
||||
for form in forms:
|
||||
_, function, _ = PRIMITIVES[(form["operation"], form["signedness"])]
|
||||
if form["operation"] == "sext":
|
||||
value = f"primitive::{function}(src, {form[SOURCE_BITS_KEY]})"
|
||||
else:
|
||||
value = f"primitive::{function}(src)"
|
||||
if form["scc"] == "unchanged":
|
||||
out.append(f" Self::{form['variant']} => ({value}, None),")
|
||||
else:
|
||||
out += [
|
||||
f" Self::{form['variant']} => {{",
|
||||
f" let (value, scc) = {value};",
|
||||
" (value, Some(scc))",
|
||||
" }",
|
||||
]
|
||||
out += [" }", " }", "}"]
|
||||
return out
|
||||
if kind == "vector":
|
||||
out += [
|
||||
"",
|
||||
" /// Assembler name of the 32-bit (VOP2) encoding, as LLVM prints it.",
|
||||
" pub const fn assembly_name(self) -> &'static str {",
|
||||
" match self {",
|
||||
]
|
||||
out += [f" Self::{form['variant']} => \"{form['name'].lower()}_e32\"," for form in forms]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// The per-lane operation its MSL lowering uses.",
|
||||
" pub const fn lowering(self) -> VectorBinary {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => "
|
||||
f"VectorBinary::{VECTOR_PRIMITIVES[(form['operation'], form['signedness'])]},"
|
||||
for form in forms
|
||||
]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// Whether the operation reads its sources reversed (`D = op(S1, S0)`).",
|
||||
" pub const fn swaps_sources(self) -> bool {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => {'true' if SOURCE_ORDER_KEY in form else 'false'},"
|
||||
for form in forms
|
||||
]
|
||||
out += [" }", " }", "}"]
|
||||
return out
|
||||
if kind == "compare":
|
||||
out += [
|
||||
"",
|
||||
" /// The relation tested, with S0 on the left.",
|
||||
" pub const fn relation(self) -> CompareRelation {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => CompareRelation::{RELATIONS[form[RELATION_KEY]]},"
|
||||
for form in forms
|
||||
]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// The new SCC: whether the relation holds for S0 and S1.",
|
||||
" pub const fn test(self, src0: u32, src1: u32) -> bool {",
|
||||
" match self {",
|
||||
]
|
||||
for form in forms:
|
||||
function = COMPARE_PRIMITIVES[(form[RELATION_KEY], form["signedness"])]
|
||||
out.append(f" Self::{form['variant']} => primitive::{function}(src0, src1),")
|
||||
out += [" }", " }", "}"]
|
||||
return out
|
||||
out += [
|
||||
"",
|
||||
" /// The result and the new SCC, with `carry_in` the SCC read by forms that",
|
||||
" /// consume it (ignored by the others).",
|
||||
" pub const fn evaluate(self, src0: u32, src1: u32, carry_in: bool) -> (u32, bool) {",
|
||||
" /// Whether the operation reads SCC (carry-in, borrow-in or select condition).",
|
||||
" pub const fn reads_scc(self) -> bool {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => {'true' if form['carry_in'] == 'scc' else 'false'},"
|
||||
for form in forms
|
||||
]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// Whether the operation writes SCC.",
|
||||
" pub const fn writes_scc(self) -> bool {",
|
||||
" match self {",
|
||||
]
|
||||
out += [
|
||||
f" Self::{form['variant']} => {'false' if form['scc'] == 'unchanged' else 'true'},"
|
||||
for form in forms
|
||||
]
|
||||
out += [
|
||||
" }",
|
||||
" }",
|
||||
"",
|
||||
" /// The result and, for forms that write it, the new SCC (`None` leaves SCC",
|
||||
" /// unchanged). `scc_in` is the SCC read by forms that consume it (ignored by",
|
||||
" /// the others).",
|
||||
" pub const fn evaluate(self, src0: u32, src1: u32, scc_in: bool) -> (u32, Option<bool>) {",
|
||||
" match self {",
|
||||
]
|
||||
for form in forms:
|
||||
_, function, takes_carry = PRIMITIVES[(form["operation"], form["signedness"])]
|
||||
if takes_carry:
|
||||
argument = "carry_in" if form["carry_in"] == "scc" else "false"
|
||||
argument = "scc_in" if form["carry_in"] == "scc" else "false"
|
||||
call = f"primitive::{function}(src0, src1, {argument})"
|
||||
elif form["operation"] in SHIFTS:
|
||||
mask = (1 << form[SHIFT_KEY]) - 1
|
||||
call = f"primitive::{function}(src0, src1 & 0x{mask:x})"
|
||||
elif form["operation"] == "lshl_add":
|
||||
call = f"primitive::{function}(src0, src1, {form[SHIFT_AMOUNT_KEY]})"
|
||||
else:
|
||||
call = f"primitive::{function}(src0, src1)"
|
||||
out.append(f" Self::{form['variant']} => {call},")
|
||||
if form["scc"] == "unchanged":
|
||||
out.append(f" Self::{form['variant']} => ({call}, None),")
|
||||
else:
|
||||
out += [
|
||||
f" Self::{form['variant']} => {{",
|
||||
f" let (value, scc) = {call};",
|
||||
" (value, Some(scc))",
|
||||
" }",
|
||||
]
|
||||
out += [" }", " }", "}"]
|
||||
return out
|
||||
|
||||
|
||||
+1182
-3
File diff suppressed because it is too large.
Load diff
+37
-12
@@ -12,13 +12,13 @@ mod rdna2_meta;
|
||||
mod semantics_gen;
|
||||
pub use rdna2::{
|
||||
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ,
|
||||
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, 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,
|
||||
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,
|
||||
};
|
||||
pub use semantics_gen::ScalarAluOp;
|
||||
pub use semantics_gen::{ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp};
|
||||
|
||||
/// SGPR index of `vcc_lo`, the Wave32 vector condition code.
|
||||
pub const VCC_LO: u8 = 106;
|
||||
@@ -209,15 +209,24 @@ pub enum Instruction {
|
||||
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 },
|
||||
/// SOP2 32-bit integer operation writing a normal SGPR (s0-s105) and SCC.
|
||||
/// SOP1 32-bit unary integer operation writing a normal SGPR (s0-s105) and,
|
||||
/// for some operations, SCC.
|
||||
ScalarUnary {
|
||||
op: ScalarUnaryOp,
|
||||
dst: u8,
|
||||
src: ScalarSource,
|
||||
},
|
||||
/// SOP2 32-bit integer operation writing a normal SGPR (s0-s105) and, for
|
||||
/// most operations, SCC; `s_cselect_b32` also reads SCC.
|
||||
ScalarAlu {
|
||||
op: ScalarAluOp,
|
||||
dst: u8,
|
||||
src0: ScalarSource,
|
||||
src1: ScalarSource,
|
||||
},
|
||||
/// SOPC 32-bit equality comparison writing SCC.
|
||||
ScalarCompareEqU32 {
|
||||
/// SOPC 32-bit integer compare writing only SCC.
|
||||
ScalarCompare {
|
||||
op: ScalarCompareOp,
|
||||
src0: ScalarSource,
|
||||
src1: ScalarSource,
|
||||
},
|
||||
@@ -228,6 +237,15 @@ pub enum Instruction {
|
||||
src0: VectorSource,
|
||||
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`.
|
||||
VectorAlu {
|
||||
op: VectorAluOp,
|
||||
dst: u8,
|
||||
src0: VectorSource,
|
||||
src1: u8,
|
||||
},
|
||||
/// SOPP jump to a stream byte offset when SCC is clear.
|
||||
BranchSccZero { target: usize },
|
||||
/// SOPP jump when the Wave32 execution mask is empty.
|
||||
@@ -306,9 +324,11 @@ impl Instruction {
|
||||
Self::MoveB32 { .. } => "v_mov_b32_e32",
|
||||
Self::AddNoCarryU32 { .. } => "v_add_nc_u32_e64",
|
||||
Self::ScalarMoveB32 { .. } => "s_mov_b32",
|
||||
Self::ScalarUnary { op, .. } => op.mnemonic(),
|
||||
Self::ScalarAlu { op, .. } => op.mnemonic(),
|
||||
Self::ScalarCompareEqU32 { .. } => "s_cmp_eq_u32",
|
||||
Self::ScalarCompare { op, .. } => op.mnemonic(),
|
||||
Self::VectorCompare { op, .. } => op.mnemonic(),
|
||||
Self::VectorAlu { op, .. } => op.assembly_name(),
|
||||
Self::BranchSccZero { .. } => "s_cbranch_scc0",
|
||||
Self::BranchExecZero { .. } => "s_cbranch_execz",
|
||||
Self::BranchVccZero { .. } => "s_cbranch_vccz",
|
||||
@@ -370,16 +390,21 @@ impl fmt::Display for Instruction {
|
||||
| Self::VectorMulF32 { dst, src0, src1 } => {
|
||||
write!(formatter, " v{dst}, v{src0}, v{src1}")
|
||||
}
|
||||
Self::ScalarMoveB32 { dst, src } => {
|
||||
Self::ScalarMoveB32 { dst, src } | Self::ScalarUnary { dst, src, .. } => {
|
||||
write!(formatter, " {}, {src}", ScalarDestination(dst))
|
||||
}
|
||||
Self::ScalarAlu {
|
||||
dst, src0, src1, ..
|
||||
} => write!(formatter, " {}, {src0}, {src1}", ScalarDestination(dst)),
|
||||
Self::ScalarCompareEqU32 { src0, src1 } => write!(formatter, " {src0}, {src1}"),
|
||||
Self::ScalarCompare { src0, src1, .. } => write!(formatter, " {src0}, {src1}"),
|
||||
Self::VectorCompare { src0, src1, .. } => {
|
||||
write!(formatter, " vcc_lo, {src0}, v{src1}")
|
||||
}
|
||||
Self::VectorAlu {
|
||||
dst, src0, src1, ..
|
||||
} => {
|
||||
write!(formatter, " v{dst}, {src0}, v{src1}")
|
||||
}
|
||||
Self::Branch { target }
|
||||
| Self::BranchSccZero { target }
|
||||
| Self::BranchExecZero { target }
|
||||
|
||||
@@ -49,3 +49,270 @@ pub const fn xor_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = a ^ b;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise `a & !b` and whether the result is nonzero.
|
||||
pub const fn andn2_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = a & !b;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise `a | !b` and whether the result is nonzero.
|
||||
pub const fn orn2_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = a | !b;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise `!(a & b)` and whether the result is nonzero.
|
||||
pub const fn nand_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = !(a & b);
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise `!(a | b)` and whether the result is nonzero.
|
||||
pub const fn nor_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = !(a | b);
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Bitwise `!(a ^ b)` and whether the result is nonzero.
|
||||
pub const fn xnor_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = !(a ^ b);
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// `a << count` and whether the result is nonzero. The caller masks the count
|
||||
/// to the declared count width, so `count` is below 32.
|
||||
pub const fn lshl_nonzero_b32(a: u32, count: u32) -> (u32, bool) {
|
||||
let value = a << count;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Logical `a >> count` (zero fill) and whether the result is nonzero; `count` is below 32.
|
||||
pub const fn lshr_nonzero_b32(a: u32, count: u32) -> (u32, bool) {
|
||||
let value = a >> count;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Arithmetic `a >> count` (sign fill) and whether the result is nonzero; `count` is below 32.
|
||||
pub const fn ashr_nonzero_i32(a: u32, count: u32) -> (u32, bool) {
|
||||
let value = ((a as i32) >> count) as u32;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// `a == b` on the raw bits; signedness does not matter for equality.
|
||||
pub const fn eq_b32(a: u32, b: u32) -> bool {
|
||||
a == b
|
||||
}
|
||||
|
||||
/// `a != b` on the raw bits (the guide's LG, "less or greater").
|
||||
pub const fn ne_b32(a: u32, b: u32) -> bool {
|
||||
a != b
|
||||
}
|
||||
|
||||
/// Two's-complement `a > b`.
|
||||
pub const fn gt_i32(a: u32, b: u32) -> bool {
|
||||
(a as i32) > (b as i32)
|
||||
}
|
||||
|
||||
/// Two's-complement `a >= b`.
|
||||
pub const fn ge_i32(a: u32, b: u32) -> bool {
|
||||
(a as i32) >= (b as i32)
|
||||
}
|
||||
|
||||
/// Two's-complement `a < b`.
|
||||
pub const fn lt_i32(a: u32, b: u32) -> bool {
|
||||
(a as i32) < (b as i32)
|
||||
}
|
||||
|
||||
/// Two's-complement `a <= b`.
|
||||
pub const fn le_i32(a: u32, b: u32) -> bool {
|
||||
(a as i32) <= (b as i32)
|
||||
}
|
||||
|
||||
/// Unsigned `a > b`.
|
||||
pub const fn gt_u32(a: u32, b: u32) -> bool {
|
||||
a > b
|
||||
}
|
||||
|
||||
/// Unsigned `a >= b`.
|
||||
pub const fn ge_u32(a: u32, b: u32) -> bool {
|
||||
a >= b
|
||||
}
|
||||
|
||||
/// Unsigned `a < b`.
|
||||
pub const fn lt_u32(a: u32, b: u32) -> bool {
|
||||
a < b
|
||||
}
|
||||
|
||||
/// Unsigned `a <= b`.
|
||||
pub const fn le_u32(a: u32, b: u32) -> bool {
|
||||
a <= b
|
||||
}
|
||||
|
||||
/// `!a` and whether the result is nonzero.
|
||||
pub const fn not_nonzero_b32(a: u32) -> (u32, bool) {
|
||||
let value = !a;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// `a` with bit `i` moved to bit `31 - i`.
|
||||
pub const fn brev_b32(a: u32) -> u32 {
|
||||
a.reverse_bits()
|
||||
}
|
||||
|
||||
/// Number of zero bits and whether that count is nonzero.
|
||||
pub const fn bcnt0_nonzero_b32(a: u32) -> (u32, bool) {
|
||||
let value = a.count_zeros();
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Number of one bits and whether that count is nonzero.
|
||||
pub const fn bcnt1_nonzero_b32(a: u32) -> (u32, bool) {
|
||||
let value = a.count_ones();
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Index of the lowest zero bit, or `0xffffffff` (-1) when every bit is one.
|
||||
pub const fn ff0_b32(a: u32) -> u32 {
|
||||
if a == u32::MAX {
|
||||
u32::MAX
|
||||
} else {
|
||||
a.trailing_ones()
|
||||
}
|
||||
}
|
||||
|
||||
/// Index of the lowest one bit, or `0xffffffff` (-1) when every bit is zero.
|
||||
pub const fn ff1_b32(a: u32) -> u32 {
|
||||
if a == 0 { u32::MAX } else { a.trailing_zeros() }
|
||||
}
|
||||
|
||||
/// Zeros above the highest one bit, or `0xffffffff` (-1) when `a` is zero.
|
||||
pub const fn flbit_b32(a: u32) -> u32 {
|
||||
if a == 0 { u32::MAX } else { a.leading_zeros() }
|
||||
}
|
||||
|
||||
/// Bits above the highest bit that differs from the sign bit, or `0xffffffff`
|
||||
/// (-1) when every bit equals the sign bit (`a` is 0 or -1).
|
||||
pub const fn flbit_i32(a: u32) -> u32 {
|
||||
let differing = if a >> 31 == 0 { a } else { !a };
|
||||
if differing == 0 {
|
||||
u32::MAX
|
||||
} else {
|
||||
differing.leading_zeros()
|
||||
}
|
||||
}
|
||||
|
||||
/// The low `bits` of `a` sign-extended to 32 bits; `bits` is 8 or 16.
|
||||
pub const fn sext_i32(a: u32, bits: u32) -> u32 {
|
||||
let shift = 32 - bits;
|
||||
(((a << shift) as i32) >> shift) 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) {
|
||||
let value = (a as i32).wrapping_abs() as u32;
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Two's-complement minimum and whether S0 was strictly smaller (so equal
|
||||
/// operands give S1 and `false`).
|
||||
pub const fn min_i32(a: u32, b: u32) -> (u32, bool) {
|
||||
let first = (a as i32) < (b as i32);
|
||||
(if first { a } else { b }, first)
|
||||
}
|
||||
|
||||
/// Unsigned minimum and whether S0 was strictly smaller.
|
||||
pub const fn min_u32(a: u32, b: u32) -> (u32, bool) {
|
||||
let first = a < b;
|
||||
(if first { a } else { b }, first)
|
||||
}
|
||||
|
||||
/// Two's-complement maximum and whether S0 was strictly greater (so equal
|
||||
/// operands give S1 and `false`).
|
||||
pub const fn max_i32(a: u32, b: u32) -> (u32, bool) {
|
||||
let first = (a as i32) > (b as i32);
|
||||
(if first { a } else { b }, first)
|
||||
}
|
||||
|
||||
/// Unsigned maximum and whether S0 was strictly greater.
|
||||
pub const fn max_u32(a: u32, b: u32) -> (u32, bool) {
|
||||
let first = a > b;
|
||||
(if first { a } else { b }, first)
|
||||
}
|
||||
|
||||
/// `a` when `condition` (SCC) is set, otherwise `b`.
|
||||
pub const fn cselect_b32(a: u32, b: u32, condition: bool) -> u32 {
|
||||
if condition { a } else { b }
|
||||
}
|
||||
|
||||
/// `((1 << a[4:0]) - 1) << b[4:0]`: a mask of `a[4:0]` ones starting at bit `b[4:0]`.
|
||||
pub const fn bfm_b32(a: u32, b: u32) -> u32 {
|
||||
((1u32 << (a & 0x1f)) - 1) << (b & 0x1f)
|
||||
}
|
||||
|
||||
/// The low 32 bits of the product (identical for signed and unsigned operands).
|
||||
pub const fn mul_lo_i32(a: u32, b: u32) -> u32 {
|
||||
a.wrapping_mul(b)
|
||||
}
|
||||
|
||||
/// The high 32 bits of the unsigned 64-bit product.
|
||||
pub const fn mul_hi_u32(a: u32, b: u32) -> u32 {
|
||||
((a as u64 * b as u64) >> 32) as u32
|
||||
}
|
||||
|
||||
/// The high 32 bits of the two's-complement 64-bit product.
|
||||
pub const fn mul_hi_i32(a: u32, b: u32) -> u32 {
|
||||
((a as i32 as i64 * b as i32 as i64) >> 32) as u32
|
||||
}
|
||||
|
||||
/// The `bfe` field descriptor: offset `b[4:0]` and width `b[22:16]` (0-127).
|
||||
const fn bfe_field(b: u32) -> (u32, u32) {
|
||||
(b & 0x1f, (b >> 16) & 0x7f)
|
||||
}
|
||||
|
||||
/// Unsigned bit-field extract: `(a >> offset) & ((1 << width) - 1)`, where a
|
||||
/// width of 32 or more keeps every shifted bit; and whether the result is nonzero.
|
||||
pub const fn bfe_nonzero_u32(a: u32, b: u32) -> (u32, bool) {
|
||||
let (offset, width) = bfe_field(b);
|
||||
let shifted = a >> offset;
|
||||
let value = if width == 0 {
|
||||
0
|
||||
} else if width >= 32 {
|
||||
shifted
|
||||
} else {
|
||||
shifted & ((1 << width) - 1)
|
||||
};
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// Signed bit-field extract: `a` shifted arithmetically by the offset, the low
|
||||
/// `width` bits kept and sign-extended from bit `width - 1` (a width of 32 or
|
||||
/// more keeps the whole shifted word); and whether the result is nonzero.
|
||||
pub const fn bfe_nonzero_i32(a: u32, b: u32) -> (u32, bool) {
|
||||
let (offset, width) = bfe_field(b);
|
||||
let shifted = ((a as i32) >> offset) as u32;
|
||||
let value = if width == 0 {
|
||||
0
|
||||
} else if width >= 32 {
|
||||
shifted
|
||||
} else {
|
||||
let unused = 32 - width;
|
||||
(((shifted << unused) as i32) >> unused) as u32
|
||||
};
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// `|a - b|` of the wrapped 32-bit difference (so `0x80000000` stays) and
|
||||
/// whether the result is nonzero.
|
||||
pub const fn absdiff_nonzero_i32(a: u32, b: u32) -> (u32, bool) {
|
||||
let value = (a.wrapping_sub(b) as i32).unsigned_abs();
|
||||
(value, value != 0)
|
||||
}
|
||||
|
||||
/// `(a << shift) + b` and the carry out of the exact sum, which counts the bits
|
||||
/// shifted out of `a`; `shift` is 1 to 4.
|
||||
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)
|
||||
}
|
||||
@@ -45,11 +45,6 @@ pub const S_MOV_B32: Opcode = Opcode {
|
||||
bits: 0xbe800300,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_CMP_EQ_U32: Opcode = Opcode {
|
||||
mask: 0xffff0000,
|
||||
bits: 0xbf060000,
|
||||
bytes: 4,
|
||||
};
|
||||
pub const S_CBRANCH_SCC0: Opcode = Opcode {
|
||||
mask: 0xffff0000,
|
||||
bits: 0xbf840000,
|
||||
|
||||
+118
-5
@@ -9,6 +9,7 @@
|
||||
//! The reference interpreter (`crates/ref`) and the independent interpreter
|
||||
//! (`tests/validation/independent_ref.rs`) must not use this module.
|
||||
|
||||
use crate::CompareRelation;
|
||||
use crate::meta::EncodingFamily;
|
||||
|
||||
pub use crate::semantics_gen::{FORM_IDS, FORMS, GENERATED_SCHEMA};
|
||||
@@ -30,6 +31,94 @@ pub enum Operation {
|
||||
Or,
|
||||
/// Bitwise exclusive OR.
|
||||
Xor,
|
||||
/// Bitwise AND with the complement of S1.
|
||||
AndNot,
|
||||
/// Bitwise OR with the complement of S1.
|
||||
OrNot,
|
||||
/// Complement of bitwise AND.
|
||||
Nand,
|
||||
/// Complement of bitwise OR.
|
||||
Nor,
|
||||
/// Complement of bitwise exclusive OR.
|
||||
Xnor,
|
||||
/// Shift S0 left by the masked count in S1, filling with zeros.
|
||||
ShiftLeft,
|
||||
/// Shift S0 right by the masked count in S1, filling with zeros.
|
||||
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,
|
||||
/// Bitwise complement of S0.
|
||||
Not,
|
||||
/// S0 with its bit order reversed.
|
||||
ReverseBits,
|
||||
/// Number of zero bits in S0.
|
||||
CountZeros,
|
||||
/// Number of one bits in S0.
|
||||
CountOnes,
|
||||
/// Index of the lowest zero bit of S0, or -1 when there is none.
|
||||
FindFirstZero,
|
||||
/// Index of the lowest one bit of S0, or -1 when there is none.
|
||||
FindFirstOne,
|
||||
/// Unsigned: count of zeros above the highest one bit; signed: count of bits
|
||||
/// above the highest bit that differs from the sign bit. -1 when none.
|
||||
FindLastBit,
|
||||
/// Sign-extend the low `source_bits` of S0 to 32 bits.
|
||||
SignExtend,
|
||||
/// Two's-complement absolute value; the most negative value maps to itself.
|
||||
Absolute,
|
||||
/// S0 when it is strictly less than S1, otherwise S1.
|
||||
Minimum,
|
||||
/// S0 when it is strictly greater than S1, otherwise S1.
|
||||
Maximum,
|
||||
/// S0 when SCC is set, otherwise S1.
|
||||
Select,
|
||||
/// `((1 << S0[4:0]) - 1) << S1[4:0]`.
|
||||
BitfieldMask,
|
||||
/// Low 32 bits of the product.
|
||||
Multiply,
|
||||
/// High 32 bits of the 64-bit product.
|
||||
MultiplyHigh,
|
||||
/// The field of S0 at offset S1[4:0] with width S1[22:16]; sign-extended when signed.
|
||||
BitfieldExtract,
|
||||
/// Absolute value of the wrapped 32-bit difference S0 - S1.
|
||||
AbsoluteDifference,
|
||||
/// `(S0 << shift_amount) + S1`.
|
||||
ShiftLeftAdd,
|
||||
/// Low 32 bits of the product of S0[23:0] and S1[23:0] (sign-extended when signed).
|
||||
Multiply24,
|
||||
/// Bits 63:32 of the product of S0[23:0] and S1[23:0] (sign-extended when signed).
|
||||
MultiplyHigh24,
|
||||
}
|
||||
|
||||
/// The per-lane integer operation a vector form lowers to. One reusable MSL
|
||||
/// template exists per variant; a form selects it through its declared
|
||||
/// operation and signedness, never through its opcode.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum VectorBinary {
|
||||
/// Wrapping `a + b`.
|
||||
Add,
|
||||
/// Wrapping `a - b`.
|
||||
Sub,
|
||||
/// `!(a ^ b)`.
|
||||
Xnor,
|
||||
/// Two's-complement minimum.
|
||||
MinSigned,
|
||||
/// Unsigned minimum.
|
||||
MinUnsigned,
|
||||
/// Two's-complement maximum.
|
||||
MaxSigned,
|
||||
/// Unsigned maximum.
|
||||
MaxUnsigned,
|
||||
/// Low 32 bits of `sext(a[23:0]) * sext(b[23:0])`.
|
||||
Mul24Signed,
|
||||
/// Low 32 bits of `a[23:0] * b[23:0]`.
|
||||
Mul24Unsigned,
|
||||
/// Bits 63:32 of `sext(a[23:0]) * sext(b[23:0])`.
|
||||
MulHi24Signed,
|
||||
/// Bits 63:32 of `a[23:0] * b[23:0]`.
|
||||
MulHi24Unsigned,
|
||||
}
|
||||
|
||||
/// How the operands are interpreted. `Bitwise` exactly when the operation is logical.
|
||||
@@ -43,12 +132,12 @@ pub enum Signedness {
|
||||
Bitwise,
|
||||
}
|
||||
|
||||
/// Extra input consumed by the operation.
|
||||
/// Whether the operation reads SCC.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum CarryIn {
|
||||
/// No carry or borrow input.
|
||||
/// SCC is not read.
|
||||
None,
|
||||
/// SCC as carry-in (add) or borrow-in (sub).
|
||||
/// SCC as carry-in (add), borrow-in (sub) or the select condition (select).
|
||||
Scc,
|
||||
}
|
||||
|
||||
@@ -65,6 +154,10 @@ pub enum SccEffect {
|
||||
SignedOverflow,
|
||||
/// The result is not zero.
|
||||
Nonzero,
|
||||
/// The compare's relation holds for S0 and S1.
|
||||
Relation,
|
||||
/// The result is S0 by the strict comparison (min, max): equal operands give 0.
|
||||
SelectedSrc0,
|
||||
}
|
||||
|
||||
/// What a form writes to VCC or EXEC. Stage A forms leave both unchanged.
|
||||
@@ -89,6 +182,16 @@ pub enum OperandRule {
|
||||
/// SOP2: SDST is s0-s105; SSRC0/SSRC1 are s0-s105, inline integers -16..64
|
||||
/// or one literal word. Everything else is rejected as unsupported.
|
||||
Sop2Sgpr,
|
||||
/// SOPC: no destination; SSRC0/SSRC1 as for SOP2 sources (s0-s105, inline
|
||||
/// integers -16..64 or one literal word). Everything else is rejected.
|
||||
SopcScalar,
|
||||
/// 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,
|
||||
/// 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,
|
||||
}
|
||||
|
||||
/// Evidence a form needs before it counts as verified.
|
||||
@@ -120,7 +223,7 @@ pub struct SpecRef {
|
||||
pub document: Document,
|
||||
/// Section number, for example `"12.1"`.
|
||||
pub section: &'static str,
|
||||
/// Page in the document, 0 when not paginated.
|
||||
/// Page in the document, or 0 when the page has not been recorded.
|
||||
pub page: u16,
|
||||
}
|
||||
|
||||
@@ -137,10 +240,20 @@ pub struct FormSemantics {
|
||||
pub operation: Operation,
|
||||
/// Operand interpretation.
|
||||
pub signedness: Signedness,
|
||||
/// Carry or borrow input.
|
||||
/// SCC input.
|
||||
pub carry_in: CarryIn,
|
||||
/// Operand and result width in bits.
|
||||
pub width: u8,
|
||||
/// Low bits of S1 used as the shift count by shift operations; 0 otherwise.
|
||||
pub shift_count_bits: u8,
|
||||
/// Fixed left shift of S0 for shift-and-add operations (1 to 4); 0 otherwise.
|
||||
pub shift_amount: u8,
|
||||
/// Whether the operation reads its sources in reverse order (`D = op(S1, S0)`).
|
||||
pub swap_sources: bool,
|
||||
/// Low bits of S0 that the operation reads: `width`, or 8 or 16 for sign extension.
|
||||
pub source_bits: u8,
|
||||
/// The relation tested by compares (S0 on the left); `None` otherwise.
|
||||
pub relation: Option<CompareRelation>,
|
||||
/// SCC write.
|
||||
pub scc: SccEffect,
|
||||
/// VCC write.
|
||||
|
||||
+2672
-43
File diff suppressed because it is too large.
Load diff
@@ -1,8 +1,8 @@
|
||||
//! Ties the generated semantic registry tables to the independent XML metadata table.
|
||||
|
||||
use xenora_isa::ScalarAluOp;
|
||||
use xenora_isa::meta::{EncodingFamily, FORMS as META_FORMS};
|
||||
use xenora_isa::semantics::{CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, SCHEMA};
|
||||
use xenora_isa::semantics::{CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, SCHEMA, SccEffect};
|
||||
use xenora_isa::{ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp};
|
||||
|
||||
#[test]
|
||||
fn generated_tables_match_the_schema_and_the_metadata_forms() {
|
||||
@@ -18,43 +18,88 @@ fn generated_tables_match_the_schema_and_the_metadata_forms() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_alu_dispatch_selects_exactly_the_registry_sop2_forms() {
|
||||
assert_eq!(ScalarAluOp::ALL.len(), FORMS.len());
|
||||
for op in ScalarAluOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(op.reads_scc(), row.carry_in == CarryIn::Scc);
|
||||
}
|
||||
/// Every word of `family` that the XML metadata identifies selects an operation
|
||||
/// exactly when the registry declares that form, and no 32-bit word of another
|
||||
/// family selects one.
|
||||
fn dispatch_selects_exactly(family: EncodingFamily, select: impl Fn(u32) -> Option<&'static str>) {
|
||||
let declared: Vec<_> = FORMS.iter().filter(|row| row.family == family).collect();
|
||||
let mut selected = 0;
|
||||
for meta in META_FORMS
|
||||
.iter()
|
||||
.filter(|form| form.family == EncodingFamily::Sop2)
|
||||
{
|
||||
let word = meta.bits as u32;
|
||||
match ScalarAluOp::from_word(word) {
|
||||
Some(op) => {
|
||||
assert_eq!(op.semantics().name, meta.name);
|
||||
for meta in META_FORMS.iter().filter(|form| form.family == family) {
|
||||
match select(meta.bits as u32) {
|
||||
Some(name) => {
|
||||
assert_eq!(name, meta.name);
|
||||
selected += 1;
|
||||
}
|
||||
None => assert!(
|
||||
FORMS.iter().all(|row| row.name != meta.name),
|
||||
declared.iter().all(|row| row.name != meta.name),
|
||||
"{} is declared but not dispatched",
|
||||
meta.name
|
||||
),
|
||||
}
|
||||
}
|
||||
assert_eq!(selected, FORMS.len());
|
||||
// Other encodings never reach the SOP2 dispatch.
|
||||
assert_eq!(selected, declared.len());
|
||||
for meta in META_FORMS
|
||||
.iter()
|
||||
.filter(|form| form.family != EncodingFamily::Sop2 && form.bytes == 4)
|
||||
.filter(|form| form.family != family && form.bytes == 4)
|
||||
{
|
||||
assert_eq!(
|
||||
ScalarAluOp::from_word(meta.bits as u32),
|
||||
None,
|
||||
"{}",
|
||||
meta.name
|
||||
);
|
||||
assert_eq!(select(meta.bits as u32), None, "{}", meta.name);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_alu_dispatch_selects_exactly_the_registry_sop2_forms() {
|
||||
for op in ScalarAluOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Sop2);
|
||||
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);
|
||||
}
|
||||
dispatch_selects_exactly(EncodingFamily::Sop2, |word| {
|
||||
ScalarAluOp::from_word(word).map(|op| op.semantics().name)
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_compare_dispatch_selects_exactly_the_registry_sopc_forms() {
|
||||
for op in ScalarCompareOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Sopc);
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(row.relation, Some(op.relation()));
|
||||
}
|
||||
dispatch_selects_exactly(EncodingFamily::Sopc, |word| {
|
||||
ScalarCompareOp::from_word(word).map(|op| op.semantics().name)
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_unary_dispatch_selects_exactly_the_registry_sop1_forms() {
|
||||
for op in ScalarUnaryOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Sop1);
|
||||
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)
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_alu_dispatch_selects_exactly_the_registry_vop2_forms() {
|
||||
for op in VectorAluOp::ALL {
|
||||
let row = op.semantics();
|
||||
assert_eq!(row.family, EncodingFamily::Vop2);
|
||||
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
|
||||
assert_eq!(op.assembly_name(), format!("{}_e32", op.mnemonic()));
|
||||
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.
|
||||
dispatch_selects_exactly(EncodingFamily::Vop2, |word| {
|
||||
VectorAluOp::from_word(word).map(|op| op.semantics().name)
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Validate the x86-64 instruction registry and generate its Rust tables.
|
||||
|
||||
validate check crates/loader/x86/instructions.toml
|
||||
generate validate, then write crates/loader/src/x86_table.rs
|
||||
--check validate and regenerate in memory; exit 1 if the committed file
|
||||
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+).
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
import tomllib
|
||||
except ModuleNotFoundError:
|
||||
sys.exit("generate_x86.py needs Python 3.11 or newer (tomllib)")
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
REGISTRY = HERE / "x86/instructions.toml"
|
||||
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"}
|
||||
GROUP_KEYS = {"map", "opcodes", "digits"}
|
||||
FLAGS = ["cf", "zf", "sf", "of", "pf", "af"]
|
||||
MAPS = {"1": "ONE_BYTE", "0f": "TWO_BYTE"}
|
||||
# Two-byte opcode table per mandatory prefix.
|
||||
PREFIXES = {"": "TWO_BYTE", "66": "TWO_BYTE_66", "f3": "TWO_BYTE_F3", "f2": "TWO_BYTE_F2"}
|
||||
SIZES = {"b": "Byte", "v": "Variable", "q": "Quad", "y": "Wide", "n": "None", "x": "Xmm"}
|
||||
IMMS = {"": "None", "ib": "SignedByte", "iz": "SignedFull", "iv": "Full", "iw": "Word", "ub": "Byte",
|
||||
"rel8": "SignedByte", "rel32": "Signed32"}
|
||||
SRCS = {"": 0, "b": 1, "w": 2, "d": 4, "q": 8, "x": 16}
|
||||
# encoding -> (Rust variant, has ModRM, required immediates)
|
||||
ENCS = {
|
||||
"none": ("None", False, {""}),
|
||||
"rm_reg": ("RmReg", True, {""}),
|
||||
"reg_rm": ("RegRm", True, {""}),
|
||||
"reg_rm_imm": ("RegRmImm", True, {"ib", "iz"}),
|
||||
"rm": ("Rm", True, {""}),
|
||||
"rm_only": ("Rm", True, {""}),
|
||||
"rm_unread": ("RmUnread", True, {""}),
|
||||
"rm_imm": ("RmImm", True, {"ib", "iz"}),
|
||||
"rm_one": ("RmOne", True, {""}),
|
||||
"rm_cl": ("RmCl", True, {""}),
|
||||
"acc_imm": ("AccImm", False, {"ib", "iz"}),
|
||||
"op_reg": ("OpReg", False, {""}),
|
||||
"op_reg_imm": ("OpRegImm", False, {"ib", "iv"}),
|
||||
"imm": ("Imm", False, {"ib", "iz", "iw"}),
|
||||
"rel": ("Rel", False, {"rel8", "rel32"}),
|
||||
"xmm_rm": ("XmmRm", True, {""}),
|
||||
"rm_xmm": ("RmXmm", True, {""}),
|
||||
"xmm_rm_imm": ("XmmRmImm", True, {"ub"}),
|
||||
"rm_imm_xmm": ("RmImmXmm", True, {"ub"}),
|
||||
"xmm_gpr": ("XmmGpr", True, {""}),
|
||||
"gpr_xmm": ("GprXmm", True, {""}),
|
||||
"xmm_gpr_imm": ("XmmGprImm", True, {"ub"}),
|
||||
"reg_xmm": ("RegXmm", True, {""}),
|
||||
"reg_xmm_imm": ("RegXmmImm", True, {"ub"}),
|
||||
}
|
||||
# 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.
|
||||
RESERVED = {0x0F, 0x26, 0x2E, 0x36, 0x3E, 0x64, 0x65, 0x66, 0x67, 0xF0, 0xF2, 0xF3,
|
||||
*range(0x40, 0x50)}
|
||||
|
||||
|
||||
class RegistryError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def fail(message):
|
||||
raise RegistryError(message)
|
||||
|
||||
|
||||
def check_keys(where, table, allowed):
|
||||
unknown = set(table) - allowed
|
||||
if unknown:
|
||||
fail(f"{where}: unknown keys {sorted(unknown)}")
|
||||
|
||||
|
||||
def flag_set(where, text):
|
||||
names = text.split()
|
||||
for name in names:
|
||||
if name not in FLAGS:
|
||||
fail(f"{where}: unknown flag {name!r}")
|
||||
if len(set(names)) != len(names):
|
||||
fail(f"{where}: repeated flag")
|
||||
return set(names)
|
||||
|
||||
|
||||
def load(text):
|
||||
"""Parse and validate the registry text, returning (operations, forms)."""
|
||||
data = tomllib.loads(text)
|
||||
check_keys("registry", data, TOP_KEYS)
|
||||
if data.get("schema") != 1 or data.get("architecture") != "x86-64":
|
||||
fail("registry: unsupported schema or architecture")
|
||||
documents = data["documents"]
|
||||
|
||||
operations = {}
|
||||
for name, entry in data["operation"].items():
|
||||
where = f"operation {name}"
|
||||
check_keys(where, entry, OPERATION_KEYS)
|
||||
reads, writes, undefined = (
|
||||
flag_set(where, entry.get(key, "")) for key in ("reads", "writes", "undefined"))
|
||||
if writes & undefined:
|
||||
fail(f"{where}: flags both written and undefined: {sorted(writes & undefined)}")
|
||||
if entry.get("ref", " ").split()[0:1] == [] or entry.get("ref", "").split()[0] not in documents:
|
||||
fail(f"{where}: reference must name a listed document")
|
||||
operations[name] = {
|
||||
"reads": reads, "writes": writes, "undefined": undefined,
|
||||
"conditional": entry.get("conditional", False),
|
||||
"terminator": entry.get("terminator", False),
|
||||
"faults": entry.get("faults", False),
|
||||
}
|
||||
|
||||
forms = [dict(form) for form in data["form"]]
|
||||
for form in forms:
|
||||
check_keys(f"form {form.get('op')}", form, FORM_KEYS)
|
||||
for index, op in enumerate(data["alu"]["operations"]):
|
||||
base = index * 8
|
||||
for offset, (enc, size, imm) in enumerate([
|
||||
("rm_reg", "b", ""), ("rm_reg", "v", ""), ("reg_rm", "b", ""),
|
||||
("reg_rm", "v", ""), ("acc_imm", "b", "ib"), ("acc_imm", "v", "iz")]):
|
||||
forms.append({"op": op, "opcode": base + offset, "enc": enc, "size": size, "imm": imm})
|
||||
for opcode, size, imm in ((0x80, "b", "ib"), (0x81, "v", "iz"), (0x83, "v", "ib")):
|
||||
forms.append({"op": op, "opcode": opcode, "digit": index, "enc": "rm_imm",
|
||||
"size": size, "imm": imm})
|
||||
for group in data["group"]:
|
||||
check_keys("group", group, GROUP_KEYS)
|
||||
for opcode, size, imm, enc in group["opcodes"]:
|
||||
for digit, op in sorted(group["digits"].items()):
|
||||
forms.append({"op": op, "map": group.get("map", "1"), "opcode": opcode,
|
||||
"digit": int(digit), "enc": enc, "size": size, "imm": imm})
|
||||
|
||||
claimed = {}
|
||||
used = set()
|
||||
for form in forms:
|
||||
form.setdefault("map", "1")
|
||||
for key in ("prefix", "imm", "src"):
|
||||
form.setdefault(key, "")
|
||||
form.setdefault("count", 1)
|
||||
form.setdefault("digit", None)
|
||||
where = f"form {form['op']} {form['map']}:{form['opcode']:02x}"
|
||||
for key, allowed in (("op", operations), ("map", MAPS), ("prefix", PREFIXES),
|
||||
("enc", ENCS), ("size", SIZES), ("imm", IMMS), ("src", SRCS)):
|
||||
if form[key] not in allowed:
|
||||
fail(f"{where}: unknown {key} {form[key]!r}")
|
||||
used.add(form["op"])
|
||||
_, modrm, imms = ENCS[form["enc"]]
|
||||
if form["imm"] not in imms:
|
||||
fail(f"{where}: immediate {form['imm']!r} is not valid for {form['enc']}")
|
||||
if form["imm"] == "ib" and form["size"] == "n":
|
||||
fail(f"{where}: a sized immediate needs an operand size")
|
||||
if form["digit"] is not None and (not modrm or not 0 <= form["digit"] <= 7):
|
||||
fail(f"{where}: a digit needs a ModRM encoding and a value 0-7")
|
||||
if form.get("memory_only") and form.get("register_only"):
|
||||
fail(f"{where}: memory_only and register_only contradict")
|
||||
if (form.get("memory_only") or form.get("register_only")) and not modrm:
|
||||
fail(f"{where}: operand restriction without ModRM")
|
||||
sourced = form["enc"] in XMM_RM or form["enc"] == "xmm_gpr_imm"
|
||||
if sourced != bool(form["src"]) and form["enc"] not in ("reg_rm", "rm"):
|
||||
fail(f"{where}: source size does not match the encoding")
|
||||
if form["src"] and not sourced and form["enc"] == "rm" and form["size"] != "n":
|
||||
fail(f"{where}: source size does not match the encoding")
|
||||
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("unaligned") and form["src"] != "x":
|
||||
fail(f"{where}: alignment applies only to 16-byte operands")
|
||||
if form["prefix"] and form["map"] != "0f":
|
||||
fail(f"{where}: mandatory prefixes are only supported in map 0f")
|
||||
if form["count"] not in (1, 8, 16) or form["opcode"] % form["count"]:
|
||||
fail(f"{where}: count must be 1, 8 or 16 and aligned")
|
||||
if form["count"] == 8 and form["enc"] not in ("op_reg", "op_reg_imm"):
|
||||
fail(f"{where}: count 8 encodes a register")
|
||||
if form["count"] == 16 and form["op"] not in ("jcc", "cmov", "setcc"):
|
||||
fail(f"{where}: count 16 encodes a condition")
|
||||
for opcode in range(form["opcode"], form["opcode"] + form["count"]):
|
||||
if not 0 <= opcode <= 0xFF:
|
||||
fail(f"{where}: opcode out of range")
|
||||
if form["map"] == "1" and opcode in RESERVED:
|
||||
fail(f"{where}: {opcode:02x} is a prefix or escape")
|
||||
slots = claimed.setdefault((form["map"], form["prefix"], opcode), {})
|
||||
if form["digit"] in slots or (slots and (None in slots or form["digit"] is None)):
|
||||
fail(f"{where}: overlapping encoding")
|
||||
slots[form["digit"]] = form
|
||||
# 0x66 selects a 16-bit operand for an unprefixed integer form, so a
|
||||
# 66-prefixed form at the same opcode would be ambiguous.
|
||||
for other, sized in (("66", form), ("", None)):
|
||||
if form["map"] == "0f" and form["prefix"] == ("" if other == "66" else "66"):
|
||||
for rival in claimed.get(("0f", other, opcode), {}).values():
|
||||
plain = sized or rival
|
||||
if plain["size"] in ("b", "v"):
|
||||
fail(f"{where}: 0x66 is both an operand size and a mandatory prefix")
|
||||
if form["digit"] is not None:
|
||||
first = next(iter(slots.values()))
|
||||
if (first["size"] in "bn") != (form["size"] in "bn"):
|
||||
fail(f"{where}: group mixes byte and wider operands")
|
||||
unused = set(operations) - used
|
||||
if unused:
|
||||
fail(f"operations without forms: {sorted(unused)}")
|
||||
return operations, forms
|
||||
|
||||
|
||||
def camel(name):
|
||||
return name[0].upper() + name[1:]
|
||||
|
||||
|
||||
def mask(flags):
|
||||
return sum(1 << FLAGS.index(flag) for flag in flags)
|
||||
|
||||
|
||||
def generate(operations, forms):
|
||||
out = ["// SPDX-License-Identifier: GPL-3.0-or-later",
|
||||
"",
|
||||
"// Generated by crates/loader/generate_x86.py from crates/loader/x86/instructions.toml.",
|
||||
"// Do not edit.",
|
||||
"",
|
||||
"use crate::x86_decode::{Encoding, Entry, Form, Immediate, OperandSize};",
|
||||
"",
|
||||
"/// Operations with decodable forms.",
|
||||
"#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]",
|
||||
"pub enum Op {"]
|
||||
out += [f" {camel(name)}," for name in operations]
|
||||
out += ["}", "", "impl Op {",
|
||||
" pub const ALL: &[Op] = &["
|
||||
+ ", ".join(f"Op::{camel(n)}" for n in operations) + "];", ""]
|
||||
|
||||
def method(doc, name, kind, value):
|
||||
out.append(f" /// {doc}")
|
||||
out.append(f" pub const fn {name}(self) -> {kind} {{")
|
||||
out.append(" match self {")
|
||||
for op, entry in operations.items():
|
||||
out.append(f" Op::{camel(op)} => {value(op, entry)},")
|
||||
out.extend([" }", " }", ""])
|
||||
|
||||
method("Lower-case mnemonic stem.", "name", "&'static str", lambda op, e: f'"{op}"')
|
||||
bits = "Flag bits: 1 CF, 2 ZF, 4 SF, 8 OF, 16 PF, 32 AF."
|
||||
method(f"Flags read. {bits}", "flags_read", "u8", lambda op, e: mask(e["reads"]))
|
||||
method(f"Flags always written. {bits}", "flags_written", "u8",
|
||||
lambda op, e: 0 if e["conditional"] else mask(e["writes"]))
|
||||
method(f"Flags this operation may change. {bits}", "flags_touched", "u8",
|
||||
lambda op, e: mask(e["writes"]))
|
||||
method(f"Architecturally undefined flags. {bits}", "flags_undefined", "u8",
|
||||
lambda op, e: mask(e["undefined"]))
|
||||
method("Ends a translated block.", "is_terminator", "bool",
|
||||
lambda op, e: str(e["terminator"]).lower())
|
||||
method("Can raise an arithmetic fault.", "can_fault", "bool",
|
||||
lambda op, e: str(e["faults"]).lower())
|
||||
vector = {form["op"] for form in forms if form["size"] == "x" or "xmm" in form["enc"]}
|
||||
method("Uses an XMM register.", "is_vector", "bool", lambda op, e: str(op in vector).lower())
|
||||
out[-1:] = ["}", ""]
|
||||
|
||||
out.append(f"pub static FORMS: [Form; {len(forms)}] = [")
|
||||
for form in forms:
|
||||
out.append(
|
||||
f" Form {{ op: Op::{camel(form['op'])}, encoding: Encoding::{ENCS[form['enc']][0]}, "
|
||||
f"size: OperandSize::{SIZES[form['size']]}, immediate: Immediate::{IMMS[form['imm']]}, "
|
||||
f"source: {SRCS[form['src']]}, has_modrm: {str(ENCS[form['enc']][1]).lower()}, "
|
||||
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()} }},")
|
||||
out += ["];", ""]
|
||||
|
||||
groups = []
|
||||
tables = {name: ["Entry::Unsupported"] * 256 for name in ("ONE_BYTE", *PREFIXES.values())}
|
||||
slots = {}
|
||||
for index, form in enumerate(forms):
|
||||
table = MAPS[form["map"]] if form["map"] == "1" else PREFIXES[form["prefix"]]
|
||||
for opcode in range(form["opcode"], form["opcode"] + form["count"]):
|
||||
slots.setdefault((table, opcode), {})[form["digit"]] = index
|
||||
for (table, opcode), digits in sorted(slots.items()):
|
||||
if None in digits:
|
||||
tables[table][opcode] = f"Entry::Form({digits[None]})"
|
||||
else:
|
||||
row = [str(digits.get(d, 65535)) for d in range(8)]
|
||||
tables[table][opcode] = f"Entry::Group({len(groups)})"
|
||||
groups.append("[" + ", ".join(row) + "]")
|
||||
out.append("/// Form per ModRM digit; 65535 marks an unsupported digit.")
|
||||
out.append(f"pub static GROUPS: [[u16; 8]; {len(groups)}] = [")
|
||||
out += [f" {row}," for row in groups]
|
||||
out += ["];", ""]
|
||||
for name, entries in tables.items():
|
||||
out.append(f"pub static {name}: [Entry; 256] = [")
|
||||
for start in range(0, 256, 4):
|
||||
out.append(" " + ", ".join(entries[start:start + 4]) + ",")
|
||||
out += ["];", ""]
|
||||
return "\n".join(out[:-1]) + "\n"
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) != 2 or argv[1] not in ("validate", "generate", "--check"):
|
||||
sys.exit("usage: generate_x86.py validate|generate|--check")
|
||||
try:
|
||||
operations, forms = load(REGISTRY.read_text())
|
||||
except (RegistryError, KeyError, tomllib.TOMLDecodeError) as error:
|
||||
sys.exit(f"instructions.toml: {error}")
|
||||
rust = generate(operations, forms)
|
||||
if argv[1] == "generate":
|
||||
RUST.write_text(rust)
|
||||
elif argv[1] == "--check" and (not RUST.exists() or RUST.read_text() != rust):
|
||||
sys.exit("x86_table.rs is out of date; run generate_x86.py generate")
|
||||
encodings = sum(form["count"] for form in forms)
|
||||
print(f"{len(operations)} operations, {len(forms)} forms, {encodings} opcode slots")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv)
|
||||
@@ -0,0 +1,181 @@
|
||||
# Typed runtime service registry.
|
||||
#
|
||||
# Data only. `cargo run -p xenora-import-gen --bin xenora-runtime-gen` validates
|
||||
# it and writes crates/loader/src/runtime_table.rs (typed Win64 adapters and
|
||||
# static metadata) and docs/runtime/services.md (coverage counts).
|
||||
#
|
||||
# service <library> <symbol>(<name>: <type>, ...) -> <type>
|
||||
# handler <Rust function in crates/loader/src/services.rs or crt.rs>
|
||||
# status implemented | partial | stub
|
||||
# alias <documented API set that forwards this symbol>
|
||||
# fails <failure contract>
|
||||
# ref <public header or document>
|
||||
# test <test function in crates/loader/tests/runtime_services.rs>
|
||||
#
|
||||
# Types: u32 i32 u64 bool32 handle ptr out<N> f32 f64, and void as a result.
|
||||
# A bool32 argument is true when nonzero. out<N> is a guest pointer to N bytes
|
||||
# the service writes. Arguments are assigned by position (Microsoft x64 calling
|
||||
# convention): RCX, RDX, R8, R9 or XMM0-XMM3 for floats, then the stack.
|
||||
#
|
||||
# "status" describes behaviour against the documented contract. A service needs
|
||||
# at least one test before it may be implemented or partial.
|
||||
|
||||
service kernel32.dll SetProcessPriorityBoost(process: handle, disable: bool32) -> bool32
|
||||
handler set_process_priority_boost
|
||||
status partial
|
||||
alias api-ms-win-core-processthreads-l1-1-2.dll
|
||||
fails 0 with ERROR_INVALID_HANDLE
|
||||
ref processthreadsapi.h SetProcessPriorityBoost
|
||||
test priority_boost_round_trips_and_checks_its_handle
|
||||
|
||||
service kernel32.dll GetProcessPriorityBoost(process: handle, disabled: out<4>) -> bool32
|
||||
handler get_process_priority_boost
|
||||
status partial
|
||||
alias api-ms-win-core-processthreads-l1-1-2.dll
|
||||
fails 0 with ERROR_INVALID_HANDLE or ERROR_NOACCESS
|
||||
ref processthreadsapi.h GetProcessPriorityBoost
|
||||
test priority_boost_round_trips_and_checks_its_handle
|
||||
|
||||
service kernel32.dll GetCurrentProcess() -> handle
|
||||
handler get_current_process
|
||||
status implemented
|
||||
alias api-ms-win-core-processthreads-l1-1-0.dll
|
||||
fails never
|
||||
ref processthreadsapi.h GetCurrentProcess
|
||||
test identity_services_return_documented_pseudo_handles_and_ids
|
||||
|
||||
service kernel32.dll GetProcessId(process: handle) -> u32
|
||||
handler get_process_id
|
||||
status partial
|
||||
alias api-ms-win-core-processthreads-l1-1-0.dll
|
||||
fails 0 with ERROR_INVALID_HANDLE
|
||||
ref processthreadsapi.h GetProcessId
|
||||
test identity_services_return_documented_pseudo_handles_and_ids
|
||||
|
||||
service kernel32.dll GetCurrentThread() -> handle
|
||||
handler get_current_thread
|
||||
status implemented
|
||||
alias api-ms-win-core-processthreads-l1-1-0.dll
|
||||
fails never
|
||||
ref processthreadsapi.h GetCurrentThread
|
||||
test identity_services_return_documented_pseudo_handles_and_ids
|
||||
|
||||
service kernel32.dll GetCurrentProcessId() -> u32
|
||||
handler get_current_process_id
|
||||
status implemented
|
||||
alias api-ms-win-core-processthreads-l1-1-0.dll
|
||||
fails never
|
||||
ref processthreadsapi.h GetCurrentProcessId
|
||||
test identity_services_return_documented_pseudo_handles_and_ids
|
||||
|
||||
service kernel32.dll GetCurrentThreadId() -> u32
|
||||
handler get_current_thread_id
|
||||
status implemented
|
||||
alias api-ms-win-core-processthreads-l1-1-0.dll
|
||||
fails never
|
||||
ref processthreadsapi.h GetCurrentThreadId
|
||||
test identity_services_return_documented_pseudo_handles_and_ids
|
||||
|
||||
service kernel32.dll OpenThread(access: u32, inherit: bool32, thread: u32) -> handle
|
||||
handler open_thread
|
||||
status partial
|
||||
alias api-ms-win-core-processthreads-l1-1-0.dll
|
||||
fails 0 with ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED or ERROR_NOT_ENOUGH_MEMORY
|
||||
ref processthreadsapi.h OpenThread
|
||||
test thread_handles_check_access_and_are_rejected_once_closed
|
||||
|
||||
service kernel32.dll GetThreadPriority(thread: handle) -> i32
|
||||
handler get_thread_priority
|
||||
status partial
|
||||
alias api-ms-win-core-processthreads-l1-1-0.dll
|
||||
fails THREAD_PRIORITY_ERROR_RETURN with ERROR_INVALID_HANDLE or ERROR_ACCESS_DENIED
|
||||
ref processthreadsapi.h GetThreadPriority
|
||||
test thread_handles_check_access_and_are_rejected_once_closed
|
||||
|
||||
service kernel32.dll SetThreadPriority(thread: handle, priority: i32) -> bool32
|
||||
handler set_thread_priority
|
||||
status partial
|
||||
alias api-ms-win-core-processthreads-l1-1-0.dll
|
||||
fails 0 with ERROR_INVALID_HANDLE, ERROR_ACCESS_DENIED, ERROR_NOT_SUPPORTED or ERROR_INVALID_PARAMETER
|
||||
ref processthreadsapi.h SetThreadPriority
|
||||
test thread_handles_check_access_and_are_rejected_once_closed
|
||||
|
||||
service kernel32.dll CloseHandle(object: handle) -> bool32
|
||||
handler close_handle
|
||||
status partial
|
||||
alias api-ms-win-core-handle-l1-1-0.dll
|
||||
fails 0 with ERROR_INVALID_HANDLE
|
||||
ref handleapi.h CloseHandle
|
||||
test thread_handles_check_access_and_are_rejected_once_closed
|
||||
|
||||
service kernel32.dll GetSystemTimeAsFileTime(time: out<8>) -> void
|
||||
handler get_system_time_as_file_time
|
||||
status implemented
|
||||
alias api-ms-win-core-sysinfo-l1-1-0.dll
|
||||
fails guest fault on an invalid pointer
|
||||
ref sysinfoapi.h GetSystemTimeAsFileTime
|
||||
test system_time_comes_from_the_injected_clock
|
||||
|
||||
service kernel32.dll GetLastError() -> u32
|
||||
handler get_last_error
|
||||
status partial
|
||||
alias api-ms-win-core-errorhandling-l1-1-0.dll
|
||||
fails never
|
||||
ref errhandlingapi.h GetLastError
|
||||
test last_error_is_set_by_failures_and_by_the_guest
|
||||
|
||||
service kernel32.dll SetLastError(code: u32) -> void
|
||||
handler set_last_error
|
||||
status partial
|
||||
alias api-ms-win-core-errorhandling-l1-1-0.dll
|
||||
fails never
|
||||
ref errhandlingapi.h SetLastError
|
||||
test last_error_is_set_by_failures_and_by_the_guest
|
||||
|
||||
service kernel32.dll VirtualAlloc(address: ptr, size: u64, kind: u32, protect: u32) -> ptr
|
||||
handler virtual_alloc
|
||||
status partial
|
||||
alias api-ms-win-core-memory-l1-1-0.dll
|
||||
fails 0 with ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED, ERROR_INVALID_ADDRESS or ERROR_NOT_ENOUGH_MEMORY
|
||||
ref memoryapi.h VirtualAlloc
|
||||
test virtual_memory_is_mapped_released_and_bounded
|
||||
|
||||
service kernel32.dll VirtualFree(address: ptr, size: u64, kind: u32) -> bool32
|
||||
handler virtual_free
|
||||
status partial
|
||||
alias api-ms-win-core-memory-l1-1-0.dll
|
||||
fails 0 with ERROR_NOT_SUPPORTED, ERROR_INVALID_PARAMETER or ERROR_INVALID_ADDRESS
|
||||
ref memoryapi.h VirtualFree
|
||||
test virtual_memory_is_mapped_released_and_bounded
|
||||
|
||||
service ucrtbase.dll sqrt(x: f64) -> f64
|
||||
handler sqrt
|
||||
status partial
|
||||
alias api-ms-win-crt-math-l1-1-0.dll
|
||||
fails NaN for a negative argument; errno is not set
|
||||
ref math.h sqrt (ISO C, IEC 60559 squareRoot)
|
||||
test floating_arguments_and_results_use_xmm_registers
|
||||
|
||||
service ucrtbase.dll sqrtf(x: f32) -> f32
|
||||
handler sqrtf
|
||||
status partial
|
||||
alias api-ms-win-crt-math-l1-1-0.dll
|
||||
fails NaN for a negative argument; errno is not set
|
||||
ref math.h sqrtf (ISO C, IEC 60559 squareRoot)
|
||||
test floating_arguments_and_results_use_xmm_registers
|
||||
|
||||
service ucrtbase.dll fabs(x: f64) -> f64
|
||||
handler fabs
|
||||
status implemented
|
||||
alias api-ms-win-crt-math-l1-1-0.dll
|
||||
fails never
|
||||
ref math.h fabs (ISO C, IEC 60559 abs)
|
||||
test floating_arguments_and_results_use_xmm_registers
|
||||
|
||||
service ucrtbase.dll fabsf(x: f32) -> f32
|
||||
handler fabsf
|
||||
status implemented
|
||||
alias api-ms-win-crt-math-l1-1-0.dll
|
||||
fails never
|
||||
ref math.h fabsf (ISO C, IEC 60559 abs)
|
||||
test floating_arguments_and_results_use_xmm_registers
|
||||
@@ -188,6 +188,198 @@ impl Arm64Assembler {
|
||||
self.emit(0x93403c00 | ((wn as u32 & 0x1f) << 5) | (xd as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// SXTB (32-bit/sign-extended): SXTB Wd, Wn (SBFM Wd, Wn, #0, #7)
|
||||
///
|
||||
/// Writing the 32-bit destination form clears bits 63:32 of the
|
||||
/// destination register, which is what a 32-bit x86 destination requires.
|
||||
pub fn sxtb_32(&mut self, wd: u8, wn: u8) {
|
||||
self.emit(0x13001c00 | ((wn as u32 & 0x1f) << 5) | (wd as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// SXTH (32-bit/sign-extended): SXTH Wd, Wn (SBFM Wd, Wn, #0, #15)
|
||||
///
|
||||
/// Writing the 32-bit destination form clears bits 63:32 of the
|
||||
/// destination register, which is what a 32-bit x86 destination requires.
|
||||
pub fn sxth_32(&mut self, wd: u8, wn: u8) {
|
||||
self.emit(0x13003c00 | ((wn as u32 & 0x1f) << 5) | (wd as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// LSR (immediate, 64-bit): LSR Xd, Xn, #shift (UBFM Xd, Xn, #shift, #63)
|
||||
pub fn lsr_imm_64(&mut self, xd: u8, xn: u8, shift: u8) {
|
||||
self.emit(
|
||||
0xd340fc00
|
||||
| ((u32::from(shift) & 0x3f) << 16)
|
||||
| ((u32::from(xn) & 0x1f) << 5)
|
||||
| (u32::from(xd) & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// CSET Wd, cond (CSINC Wd, WZR, WZR, inverted cond)
|
||||
pub fn cset_32(&mut self, wd: u8, cond: Condition) {
|
||||
self.emit(0x1a9f_07e0 | (((cond as u32) ^ 1) << 12) | (u32::from(wd) & 0x1f));
|
||||
}
|
||||
|
||||
/// CSEL Xd, Xn, Xm, cond
|
||||
pub fn csel_64(&mut self, xd: u8, xn: u8, xm: u8, cond: Condition) {
|
||||
self.emit(
|
||||
0x9a80_0000
|
||||
| ((u32::from(xm) & 0x1f) << 16)
|
||||
| ((cond as u32) << 12)
|
||||
| ((u32::from(xn) & 0x1f) << 5)
|
||||
| (u32::from(xd) & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// STRB Wt, [Xn, #offset]
|
||||
pub fn strb_uoff(&mut self, wt: u8, xn: u8, offset: u32) {
|
||||
self.emit(
|
||||
0x3900_0000
|
||||
| ((offset & 0xfff) << 10)
|
||||
| ((u32::from(xn) & 0x1f) << 5)
|
||||
| (u32::from(wt) & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// LDRB Wt, [Xn, #offset]
|
||||
pub fn ldrb_uoff(&mut self, wt: u8, xn: u8, offset: u32) {
|
||||
self.emit(
|
||||
0x3940_0000
|
||||
| ((offset & 0xfff) << 10)
|
||||
| ((u32::from(xn) & 0x1f) << 5)
|
||||
| (u32::from(wt) & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// EOR Wd, Wn, Wm, LSR #shift
|
||||
pub fn eor_lsr_32(&mut self, wd: u8, wn: u8, wm: u8, shift: u8) {
|
||||
self.emit(
|
||||
0x4a40_0000
|
||||
| ((u32::from(wm) & 0x1f) << 16)
|
||||
| ((u32::from(shift) & 0x1f) << 10)
|
||||
| ((u32::from(wn) & 0x1f) << 5)
|
||||
| (u32::from(wd) & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// ORR Wd, Wn, Wm
|
||||
pub fn orr_reg_32(&mut self, wd: u8, wn: u8, wm: u8) {
|
||||
self.emit(
|
||||
0x2a00_0000
|
||||
| ((u32::from(wm) & 0x1f) << 16)
|
||||
| ((u32::from(wn) & 0x1f) << 5)
|
||||
| (u32::from(wd) & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// BIC Wd, Wn, Wm (Wn & !Wm)
|
||||
pub fn bic_reg_32(&mut self, wd: u8, wn: u8, wm: u8) {
|
||||
self.emit(
|
||||
0x0a20_0000
|
||||
| ((u32::from(wm) & 0x1f) << 16)
|
||||
| ((u32::from(wn) & 0x1f) << 5)
|
||||
| (u32::from(wd) & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// MVN Xd, Xm (ORN Xd, XZR, Xm)
|
||||
pub fn mvn_64(&mut self, xd: u8, xm: u8) {
|
||||
self.emit(0xaa20_03e0 | ((u32::from(xm) & 0x1f) << 16) | (u32::from(xd) & 0x1f));
|
||||
}
|
||||
|
||||
/// UBFX Wd, Wn, #bit, #1
|
||||
pub fn ubfx_bit_32(&mut self, wd: u8, wn: u8, bit: u8) {
|
||||
self.emit(
|
||||
0x5300_0000
|
||||
| ((u32::from(bit) & 0x1f) << 16)
|
||||
| ((u32::from(bit) & 0x1f) << 10)
|
||||
| ((u32::from(wn) & 0x1f) << 5)
|
||||
| (u32::from(wd) & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// REV Xd, Xn, or REV Wd, Wn when not `wide`
|
||||
pub fn rev(&mut self, d: u8, n: u8, wide: bool) {
|
||||
self.emit(
|
||||
(if wide { 0xdac0_0c00 } else { 0x5ac0_0800 })
|
||||
| ((u32::from(n) & 0x1f) << 5)
|
||||
| (u32::from(d) & 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(
|
||||
0x3dc0_0000
|
||||
| (((offset / 16) & 0xfff) << 10)
|
||||
| ((u32::from(xn) & 0x1f) << 5)
|
||||
| (u32::from(qt) & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// STR Qt, [Xn, #offset] (offset a multiple of 16)
|
||||
pub fn str_q_uoff(&mut self, qt: u8, xn: u8, offset: u32) {
|
||||
self.emit(
|
||||
0x3d80_0000
|
||||
| (((offset / 16) & 0xfff) << 10)
|
||||
| ((u32::from(xn) & 0x1f) << 5)
|
||||
| (u32::from(qt) & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// FMOV Dd, Xn (clears the upper half of Vd)
|
||||
pub fn fmov_d_from_x(&mut self, vd: u8, xn: u8) {
|
||||
self.emit(0x9e67_0000 | ((u32::from(xn) & 0x1f) << 5) | (u32::from(vd) & 0x1f));
|
||||
}
|
||||
|
||||
/// MOV Vd.D[1], Xn
|
||||
pub fn ins_d1_from_x(&mut self, vd: u8, xn: u8) {
|
||||
self.emit(0x4e18_1c00 | ((u32::from(xn) & 0x1f) << 5) | (u32::from(vd) & 0x1f));
|
||||
}
|
||||
|
||||
/// Three-register vector instruction from its base word
|
||||
pub fn neon3(&mut self, base: u32, vd: u8, vn: u8, vm: u8) {
|
||||
self.emit(
|
||||
base | ((u32::from(vm) & 0x1f) << 16)
|
||||
| ((u32::from(vn) & 0x1f) << 5)
|
||||
| (u32::from(vd) & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// SHL Vd, Vn, #shift for 0 <= shift < lane
|
||||
pub fn shl_vector(&mut self, vd: u8, vn: u8, lane: u32, shift: u32) {
|
||||
self.emit(
|
||||
0x4f00_5400
|
||||
| ((lane + shift) << 16)
|
||||
| ((u32::from(vn) & 0x1f) << 5)
|
||||
| (u32::from(vd) & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// USHR Vd, Vn, #shift for 1 <= shift <= lane
|
||||
pub fn ushr_vector(&mut self, vd: u8, vn: u8, lane: u32, shift: u32) {
|
||||
self.emit(
|
||||
0x6f00_0400
|
||||
| ((2 * lane - shift) << 16)
|
||||
| ((u32::from(vn) & 0x1f) << 5)
|
||||
| (u32::from(vd) & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// SSHR Vd, Vn, #shift for 1 <= shift <= lane
|
||||
pub fn sshr_vector(&mut self, vd: u8, vn: u8, lane: u32, shift: u32) {
|
||||
self.emit(
|
||||
0x4f00_0400
|
||||
| ((2 * lane - shift) << 16)
|
||||
| ((u32::from(vn) & 0x1f) << 5)
|
||||
| (u32::from(vd) & 0x1f),
|
||||
);
|
||||
}
|
||||
|
||||
/// SXTW (64-bit/sign-extended): SXTW Xd, Wn (SBFM Xd, Xn, #0, #31)
|
||||
pub fn sxtw_64(&mut self, xd: u8, wn: u8) {
|
||||
self.emit(0x93407c00 | ((wn as u32 & 0x1f) << 5) | (xd as u32 & 0x1f));
|
||||
}
|
||||
|
||||
/// ADD (extended/shifted register, 32-bit): ADD Wd, Wn, Wm
|
||||
pub fn add_reg_32(&mut self, wd: u8, wn: u8, wm: u8) {
|
||||
self.emit(
|
||||
|
||||
+227
-506
@@ -6,6 +6,8 @@
|
||||
//! Never executes guest x86-64 code natively on host ARM64.
|
||||
|
||||
use crate::memory::{GuestMemory, MemoryError};
|
||||
use crate::x86_decode::{DecodeError, decode};
|
||||
use crate::x86_exec;
|
||||
use std::fmt;
|
||||
|
||||
/// 64-bit General Purpose Register identifiers in x86-64.
|
||||
@@ -54,12 +56,33 @@ impl Register {
|
||||
}
|
||||
|
||||
/// RFLAGS status bits tracked during guest execution.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct RFlags {
|
||||
pub cf: bool, // Carry flag
|
||||
pub zf: bool, // Zero flag
|
||||
pub sf: bool, // Sign flag
|
||||
pub of: bool, // Overflow flag
|
||||
pub pf: bool, // Parity flag
|
||||
pub af: bool, // Auxiliary carry flag
|
||||
}
|
||||
|
||||
/// SSE control and status register. Reset state masks every exception and
|
||||
/// rounds to nearest (Intel SDM Vol. 1, 10.2.3).
|
||||
#[repr(transparent)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Mxcsr(pub u32);
|
||||
|
||||
impl Mxcsr {
|
||||
pub const RESET: u32 = 0x1F80;
|
||||
/// Bits that exist; loading any other bit raises #GP.
|
||||
pub const WRITABLE: u32 = 0xFFFF;
|
||||
}
|
||||
|
||||
impl Default for Mxcsr {
|
||||
fn default() -> Self {
|
||||
Self(Self::RESET)
|
||||
}
|
||||
}
|
||||
|
||||
/// x86-64 CPU state. Native DBT accesses the general registers and RIP by offset.
|
||||
@@ -71,6 +94,9 @@ pub struct CpuState {
|
||||
pub flags: RFlags,
|
||||
pub gs_base: u64,
|
||||
pub fs_base: u64,
|
||||
/// XMM0-XMM15, lane 0 in the low bits.
|
||||
pub xmm: [u128; 16],
|
||||
pub mxcsr: Mxcsr,
|
||||
}
|
||||
|
||||
impl CpuState {
|
||||
@@ -83,6 +109,8 @@ impl CpuState {
|
||||
flags: RFlags::default(),
|
||||
gs_base: 0,
|
||||
fs_base: 0,
|
||||
xmm: [0; 16],
|
||||
mxcsr: Mxcsr::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -105,6 +133,14 @@ pub enum ExitReason {
|
||||
MemoryFault(MemoryError),
|
||||
IllegalInstruction(u8),
|
||||
StackUnderflow,
|
||||
/// Division by zero or a quotient too large for its destination (#DE).
|
||||
DivideError,
|
||||
/// A misaligned 16-byte operand or a reserved MXCSR bit (#GP).
|
||||
GeneralProtection,
|
||||
/// An unmasked SSE floating-point exception (#XM); MXCSR holds its flags.
|
||||
SimdException,
|
||||
/// A host service changed a register the Win64 ABI requires it to preserve.
|
||||
ServiceAbiViolation,
|
||||
}
|
||||
|
||||
impl fmt::Display for ExitReason {
|
||||
@@ -117,6 +153,12 @@ impl fmt::Display for ExitReason {
|
||||
Self::MemoryFault(e) => write!(f, "memory fault: {e}"),
|
||||
Self::IllegalInstruction(op) => write!(f, "illegal or unsupported opcode: 0x{op:02x}"),
|
||||
Self::StackUnderflow => write!(f, "stack underflow"),
|
||||
Self::DivideError => write!(f, "guest divide error"),
|
||||
Self::GeneralProtection => write!(f, "guest general-protection fault"),
|
||||
Self::SimdException => write!(f, "guest SIMD floating-point exception"),
|
||||
Self::ServiceAbiViolation => {
|
||||
write!(f, "host service changed a nonvolatile guest register")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -137,8 +179,15 @@ mod layout_tests {
|
||||
assert_eq!(std::mem::offset_of!(CpuState, flags), 16 * 8 + 8);
|
||||
assert_eq!(std::mem::offset_of!(CpuState, gs_base), 16 * 8 + 8 + 8);
|
||||
assert_eq!(std::mem::offset_of!(CpuState, fs_base), 16 * 8 + 8 + 8 + 8);
|
||||
assert_eq!(std::mem::size_of::<RFlags>(), 4);
|
||||
assert_eq!(std::mem::size_of::<CpuState>(), 16 * 8 + 8 + 8 + 8 + 8);
|
||||
assert_eq!(std::mem::size_of::<RFlags>(), 6);
|
||||
assert_eq!(std::mem::offset_of!(RFlags, cf), 0);
|
||||
assert_eq!(std::mem::offset_of!(RFlags, zf), 1);
|
||||
assert_eq!(std::mem::offset_of!(RFlags, sf), 2);
|
||||
assert_eq!(std::mem::offset_of!(RFlags, of), 3);
|
||||
assert_eq!(std::mem::offset_of!(RFlags, pf), 4);
|
||||
assert_eq!(std::mem::offset_of!(RFlags, af), 5);
|
||||
assert_eq!(std::mem::offset_of!(CpuState, xmm), 160);
|
||||
assert_eq!(std::mem::offset_of!(CpuState, mxcsr), 160 + 16 * 16);
|
||||
|
||||
let cpu = CpuState::default();
|
||||
let base = std::ptr::addr_of!(cpu) as usize;
|
||||
@@ -153,6 +202,167 @@ mod layout_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod prefix_tests {
|
||||
use super::{CpuState, ExitReason, Interpreter, Register};
|
||||
use crate::memory::{GuestMemory, MemoryPermissions};
|
||||
|
||||
const CODE_BASE: u64 = 0x1000;
|
||||
const CODE_SIZE: usize = 0x1000;
|
||||
const STACK_BASE: u64 = 0x8000_0000;
|
||||
const STACK_SIZE: usize = 0x10000;
|
||||
const FS_BASE: u64 = 0x9000;
|
||||
const GS_BASE: u64 = 0xA000;
|
||||
|
||||
/// A guest memory image with executable code, a stack and distinct FS and
|
||||
/// GS bases.
|
||||
fn memory_with_code(code: &[u8]) -> GuestMemory {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(
|
||||
CODE_BASE,
|
||||
CODE_SIZE,
|
||||
MemoryPermissions::READ_WRITE_EXECUTE,
|
||||
code,
|
||||
)
|
||||
.expect("code region");
|
||||
memory
|
||||
.map_region(STACK_BASE, STACK_SIZE, MemoryPermissions::READ_WRITE)
|
||||
.expect("stack region");
|
||||
// The segment bases are distinct so a swapped prefix is visible.
|
||||
memory
|
||||
.map_region(FS_BASE, 0x1000, MemoryPermissions::READ_WRITE)
|
||||
.expect("fs region");
|
||||
memory
|
||||
.map_region(GS_BASE, 0x1000, MemoryPermissions::READ_WRITE)
|
||||
.expect("gs region");
|
||||
memory
|
||||
}
|
||||
|
||||
/// Run `code` on the interpreter and return the final state and exit reason.
|
||||
fn run(code: &[u8]) -> (CpuState, ExitReason) {
|
||||
let mut memory = memory_with_code(code);
|
||||
let cpu = CpuState::new(CODE_BASE, STACK_BASE + 0x8000);
|
||||
let mut interp = Interpreter::new(cpu, &mut memory, 64);
|
||||
let result = interp.run();
|
||||
(result.final_state, result.exit_reason)
|
||||
}
|
||||
|
||||
/// `mov r8, imm64`: 49 B8 <imm64>.
|
||||
fn mov_r8_imm64(value: u64) -> Vec<u8> {
|
||||
let mut code = vec![0x49, 0xB8];
|
||||
code.extend_from_slice(&value.to_le_bytes());
|
||||
code
|
||||
}
|
||||
|
||||
/// `mov rbx, imm64`: 48 BB <imm64>.
|
||||
fn mov_rbx_imm64(value: u64) -> Vec<u8> {
|
||||
let mut code = vec![0x48, 0xBB];
|
||||
code.extend_from_slice(&value.to_le_bytes());
|
||||
code
|
||||
}
|
||||
|
||||
/// `mov rax, imm64`: 48 B8 <imm64>.
|
||||
fn mov_rax_imm64(value: u64) -> Vec<u8> {
|
||||
let mut code = vec![0x48, 0xB8];
|
||||
code.extend_from_slice(&value.to_le_bytes());
|
||||
code
|
||||
}
|
||||
|
||||
/// REX.B extends the ModRM `rm` field, so `rm=0` selects r8.
|
||||
///
|
||||
/// Encoding 49 89 D8 is `mov r8, rbx`.
|
||||
#[test]
|
||||
fn rex_b_extends_the_rm_field_to_r8() {
|
||||
let mut code = mov_rbx_imm64(0x1122_3344_5566_7788);
|
||||
code.extend_from_slice(&[0x49, 0x89, 0xD8]); // mov r8, rbx
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
let (state, reason) = run(&code);
|
||||
assert_eq!(reason, ExitReason::Halt);
|
||||
assert_eq!(state.get(Register::Rbx), 0x1122_3344_5566_7788);
|
||||
assert_eq!(state.get(Register::R8), 0x1122_3344_5566_7788);
|
||||
// No prefix in this encoding selects r9.
|
||||
assert_eq!(state.get(Register::R9), 0);
|
||||
}
|
||||
|
||||
/// REX.R extends the ModRM `reg` field, so `reg=0` selects r8.
|
||||
///
|
||||
/// Encoding 4C 89 C3 is `mov rbx, r8`.
|
||||
#[test]
|
||||
fn rex_r_extends_the_reg_field_to_r8() {
|
||||
let mut code = mov_r8_imm64(0x1122_3344_5566_7788);
|
||||
code.extend_from_slice(&[0x4C, 0x89, 0xC3]); // mov rbx, r8
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
let (state, reason) = run(&code);
|
||||
assert_eq!(reason, ExitReason::Halt);
|
||||
assert_eq!(state.get(Register::R8), 0x1122_3344_5566_7788);
|
||||
assert_eq!(state.get(Register::Rbx), 0x1122_3344_5566_7788);
|
||||
// No prefix in this encoding selects r9.
|
||||
assert_eq!(state.get(Register::R9), 0);
|
||||
}
|
||||
|
||||
/// REX.R and REX.B extend independent fields, so the destination r9 and
|
||||
/// the source r12 are chosen by different prefix bits.
|
||||
///
|
||||
/// Encoding 4D 89 E1 is `mov r9, r12`.
|
||||
#[test]
|
||||
fn rex_r_and_rex_b_extend_independent_fields() {
|
||||
let mut code = mov_r8_imm64(0x1122_3344_5566_7788);
|
||||
code.extend_from_slice(&[0x4D, 0x89, 0xE1]); // mov r9, r12
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
let (state, reason) = run(&code);
|
||||
assert_eq!(reason, ExitReason::Halt);
|
||||
// r9 receives r12, which is zero here, and not the value in r8.
|
||||
assert_eq!(state.get(Register::R9), 0);
|
||||
assert_eq!(state.get(Register::R12), 0);
|
||||
assert_eq!(state.get(Register::R8), 0x1122_3344_5566_7788);
|
||||
}
|
||||
|
||||
/// Without REX.W the move is 32-bit wide, so the destination keeps only the
|
||||
/// low half of the source and its upper half is cleared.
|
||||
///
|
||||
/// Encoding 89 D8 is `mov eax, ebx`.
|
||||
#[test]
|
||||
fn a_move_without_rex_w_is_32_bit_wide() {
|
||||
let mut code = mov_rbx_imm64(0x1122_3344_5566_7788);
|
||||
code.extend_from_slice(&[0x89, 0xD8]); // mov eax, ebx
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
let (state, reason) = run(&code);
|
||||
assert_eq!(reason, ExitReason::Halt);
|
||||
// Only the low 32 bits of ebx survive, and rax's upper half is cleared.
|
||||
assert_eq!(state.get(Register::Rax), 0x5566_7788);
|
||||
assert_eq!(state.get(Register::Rbx), 0x1122_3344_5566_7788);
|
||||
}
|
||||
|
||||
/// The FS segment override adds the FS base to the effective address.
|
||||
///
|
||||
/// Encoding 64 48 89 04 25 08 00 00 00 is `mov fs:[0x8], rax`.
|
||||
#[test]
|
||||
fn the_fs_prefix_adds_the_fs_base() {
|
||||
let mut code = mov_rax_imm64(0x1122_3344_5566_7788);
|
||||
code.extend_from_slice(&[0x64, 0x48, 0x89, 0x04, 0x25, 0x08, 0x00, 0x00, 0x00]);
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
let mut memory = memory_with_code(&code);
|
||||
let mut cpu = CpuState::new(CODE_BASE, STACK_BASE + 0x8000);
|
||||
cpu.fs_base = FS_BASE;
|
||||
cpu.gs_base = GS_BASE;
|
||||
let mut interp = Interpreter::new(cpu, &mut memory, 64);
|
||||
let result = interp.run();
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
assert_eq!(
|
||||
memory.read_u64(FS_BASE + 0x8).expect("fs read"),
|
||||
0x1122_3344_5566_7788
|
||||
);
|
||||
// The GS base is untouched: the GS-prefixed store did not happen.
|
||||
assert_eq!(memory.read_u64(GS_BASE + 0x8).expect("gs read"), 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Result returned after running guest execution.
|
||||
#[derive(Debug)]
|
||||
pub struct ExecutionResult {
|
||||
@@ -211,512 +421,23 @@ impl<'a> Interpreter<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
fn fetch_u8(&mut self) -> Result<u8, ExitReason> {
|
||||
let b = self
|
||||
.memory
|
||||
.fetch_instruction_byte(self.cpu.rip)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
self.cpu.rip += 1;
|
||||
Ok(b)
|
||||
}
|
||||
|
||||
fn fetch_u32(&mut self) -> Result<u32, ExitReason> {
|
||||
let mut bytes = [0u8; 4];
|
||||
for b in &mut bytes {
|
||||
*b = self.fetch_u8()?;
|
||||
}
|
||||
Ok(u32::from_le_bytes(bytes))
|
||||
}
|
||||
|
||||
fn fetch_u64(&mut self) -> Result<u64, ExitReason> {
|
||||
let mut bytes = [0u8; 8];
|
||||
for b in &mut bytes {
|
||||
*b = self.fetch_u8()?;
|
||||
}
|
||||
Ok(u64::from_le_bytes(bytes))
|
||||
}
|
||||
|
||||
fn fetch_i8(&mut self) -> Result<i8, ExitReason> {
|
||||
Ok(self.fetch_u8()? as i8)
|
||||
}
|
||||
|
||||
fn fetch_i32(&mut self) -> Result<i32, ExitReason> {
|
||||
Ok(self.fetch_u32()? as i32)
|
||||
}
|
||||
|
||||
/// Single-step execution. Returns Ok(Some(ExitReason)) on clean exit (HLT/SYSCALL).
|
||||
/// Single-step execution. Returns Ok(Some(ExitReason)) on clean exit
|
||||
/// (HLT/SYSCALL). An error leaves the guest state unchanged.
|
||||
pub fn step(&mut self) -> Result<Option<ExitReason>, ExitReason> {
|
||||
let start = self.cpu.rip;
|
||||
let result = self.execute_instruction();
|
||||
if result.is_err() {
|
||||
self.cpu.rip = start;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn execute_instruction(&mut self) -> Result<Option<ExitReason>, ExitReason> {
|
||||
let mut rex_w = false;
|
||||
let mut rex_r = false;
|
||||
let mut rex_b = false;
|
||||
let mut seg_gs = false;
|
||||
let mut seg_fs = false;
|
||||
|
||||
let mut byte = self.fetch_u8()?;
|
||||
|
||||
// Handle legacy segment prefixes: 0x65 (GS), 0x64 (FS)
|
||||
while byte == 0x65 || byte == 0x64 {
|
||||
if byte == 0x65 {
|
||||
seg_gs = true;
|
||||
} else {
|
||||
seg_fs = true;
|
||||
}
|
||||
byte = self.fetch_u8()?;
|
||||
}
|
||||
|
||||
// Handle REX prefix (0x40 - 0x4F)
|
||||
if (byte & 0xF0) == 0x40 {
|
||||
rex_w = (byte & 0x08) != 0;
|
||||
rex_r = (byte & 0x04) != 0;
|
||||
rex_b = (byte & 0x01) != 0;
|
||||
byte = self.fetch_u8()?;
|
||||
}
|
||||
|
||||
match byte {
|
||||
// HLT: Halt execution
|
||||
0xF4 => Ok(Some(ExitReason::Halt)),
|
||||
|
||||
0x0F => match self.fetch_u8()? {
|
||||
0x05 => Ok(Some(ExitReason::Syscall(self.cpu.get(Register::Rax)))),
|
||||
op @ 0xC8..=0xCF => {
|
||||
let reg = Register::from_index((op & 7) | (u8::from(rex_b) << 3));
|
||||
let value = self.cpu.get(reg);
|
||||
let reversed = if rex_w {
|
||||
value.swap_bytes()
|
||||
} else {
|
||||
u64::from((value as u32).swap_bytes())
|
||||
};
|
||||
self.cpu.set(reg, reversed);
|
||||
Ok(None)
|
||||
}
|
||||
op => Err(ExitReason::IllegalInstruction(op)),
|
||||
},
|
||||
|
||||
// MOV r32, imm32 (0xB8 + reg) or MOV r64, imm64 with REX.W
|
||||
0xB8..=0xBF => {
|
||||
let reg_idx = (byte - 0xB8) + if rex_b { 8 } else { 0 };
|
||||
let reg = Register::from_index(reg_idx);
|
||||
if rex_w {
|
||||
let imm = self.fetch_u64()?;
|
||||
self.cpu.set(reg, imm);
|
||||
} else {
|
||||
let imm = self.fetch_u32()? as u64; // Zero-extended in x86-64
|
||||
self.cpu.set(reg, imm);
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
// XOR r/m, reg (0x31) or XOR reg, r/m (0x33)
|
||||
0x31 | 0x33 => {
|
||||
let modrm = self.fetch_u8()?;
|
||||
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
|
||||
let (src, dst) = if byte == 0x31 { (reg, rm) } else { (rm, reg) };
|
||||
let val1 = self.cpu.get(dst);
|
||||
let val2 = self.cpu.get(src);
|
||||
let res = if rex_w {
|
||||
val1 ^ val2
|
||||
} else {
|
||||
(val1 as u32 ^ val2 as u32) as u64
|
||||
};
|
||||
self.cpu.set(dst, res);
|
||||
self.update_flags_logic(res, rex_w);
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
// ADD r/m, reg (0x01) or ADD reg, r/m (0x03)
|
||||
0x01 | 0x03 => {
|
||||
let modrm = self.fetch_u8()?;
|
||||
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
|
||||
let (src, dst) = if byte == 0x01 { (reg, rm) } else { (rm, reg) };
|
||||
let val1 = self.cpu.get(dst);
|
||||
let val2 = self.cpu.get(src);
|
||||
let (res, flags) = if rex_w {
|
||||
add64(val1, val2)
|
||||
} else {
|
||||
let (r, f) = add32(val1 as u32, val2 as u32);
|
||||
(r as u64, f)
|
||||
};
|
||||
self.cpu.set(dst, res);
|
||||
self.cpu.flags = flags;
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
// SUB r/m, reg (0x29) or SUB reg, r/m (0x2B)
|
||||
0x29 | 0x2B => {
|
||||
let modrm = self.fetch_u8()?;
|
||||
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
|
||||
let (src, dst) = if byte == 0x29 { (reg, rm) } else { (rm, reg) };
|
||||
let val1 = self.cpu.get(dst);
|
||||
let val2 = self.cpu.get(src);
|
||||
let (res, flags) = if rex_w {
|
||||
sub64(val1, val2)
|
||||
} else {
|
||||
let (r, f) = sub32(val1 as u32, val2 as u32);
|
||||
(r as u64, f)
|
||||
};
|
||||
self.cpu.set(dst, res);
|
||||
self.cpu.flags = flags;
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
// CMP reg, r/m (0x3B) or CMP r/m, reg (0x39)
|
||||
0x39 | 0x3B => {
|
||||
let modrm = self.fetch_u8()?;
|
||||
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
|
||||
let (v1, v2) = if byte == 0x39 {
|
||||
(self.cpu.get(rm), self.cpu.get(reg))
|
||||
} else {
|
||||
(self.cpu.get(reg), self.cpu.get(rm))
|
||||
};
|
||||
let (_, flags) = if rex_w {
|
||||
sub64(v1, v2)
|
||||
} else {
|
||||
let (r, f) = sub32(v1 as u32, v2 as u32);
|
||||
(r as u64, f)
|
||||
};
|
||||
self.cpu.flags = flags;
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
// Immediate group 1: 0x83 /op reg, imm8
|
||||
0x83 => {
|
||||
let modrm = self.fetch_u8()?;
|
||||
let op = (modrm >> 3) & 7;
|
||||
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
|
||||
let imm8 = self.fetch_i8()? as i64;
|
||||
let imm = imm8 as u64;
|
||||
|
||||
let val = self.cpu.get(rm);
|
||||
match op {
|
||||
0 => {
|
||||
// ADD
|
||||
let (res, flags) = if rex_w {
|
||||
add64(val, imm)
|
||||
} else {
|
||||
let (r, f) = add32(val as u32, imm as u32);
|
||||
(r as u64, f)
|
||||
};
|
||||
self.cpu.set(rm, res);
|
||||
self.cpu.flags = flags;
|
||||
}
|
||||
5 => {
|
||||
// SUB
|
||||
let (res, flags) = if rex_w {
|
||||
sub64(val, imm)
|
||||
} else {
|
||||
let (r, f) = sub32(val as u32, imm as u32);
|
||||
(r as u64, f)
|
||||
};
|
||||
self.cpu.set(rm, res);
|
||||
self.cpu.flags = flags;
|
||||
}
|
||||
7 => {
|
||||
// CMP
|
||||
let (_, flags) = if rex_w {
|
||||
sub64(val, imm)
|
||||
} else {
|
||||
let (r, f) = sub32(val as u32, imm as u32);
|
||||
(r as u64, f)
|
||||
};
|
||||
self.cpu.flags = flags;
|
||||
}
|
||||
_ => return Err(ExitReason::IllegalInstruction(byte)),
|
||||
}
|
||||
let _ = reg;
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
// MOV r/m, reg (0x89) or MOV reg, r/m (0x8B)
|
||||
0x89 | 0x8B => {
|
||||
let modrm = self.fetch_u8()?;
|
||||
self.execute_mov_rm(modrm, rex_w, rex_r, rex_b, byte == 0x8B, seg_gs, seg_fs)
|
||||
}
|
||||
|
||||
// JMP rel8 (0xEB)
|
||||
0xEB => {
|
||||
let offset = self.fetch_i8()? as i64;
|
||||
self.cpu.rip = (self.cpu.rip as i64 + offset) as u64;
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
// JMP rel32 (0xE9)
|
||||
0xE9 => {
|
||||
let offset = self.fetch_i32()? as i64;
|
||||
self.cpu.rip = (self.cpu.rip as i64 + offset) as u64;
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
// JZ/JE rel8 (0x74)
|
||||
0x74 => {
|
||||
let offset = self.fetch_i8()? as i64;
|
||||
if self.cpu.flags.zf {
|
||||
self.cpu.rip = (self.cpu.rip as i64 + offset) as u64;
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
// JNZ/JNE rel8 (0x75)
|
||||
0x75 => {
|
||||
let offset = self.fetch_i8()? as i64;
|
||||
if !self.cpu.flags.zf {
|
||||
self.cpu.rip = (self.cpu.rip as i64 + offset) as u64;
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
// CALL rel32 (0xE8)
|
||||
0xE8 => {
|
||||
let offset = self.fetch_i32()? as i64;
|
||||
let target = (self.cpu.rip as i64 + offset) as u64;
|
||||
let ret_addr = self.cpu.rip;
|
||||
self.push_u64(ret_addr)?;
|
||||
self.cpu.rip = target;
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
// RET (0xC3)
|
||||
0xC3 => {
|
||||
let ret_addr = self.pop_u64()?;
|
||||
self.cpu.rip = ret_addr;
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
// PUSH reg (0x50..=0x57)
|
||||
0x50..=0x57 => {
|
||||
let reg_idx = (byte - 0x50) + if rex_b { 8 } else { 0 };
|
||||
let reg = Register::from_index(reg_idx);
|
||||
let val = self.cpu.get(reg);
|
||||
self.push_u64(val)?;
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
// POP reg (0x58..=0x5F)
|
||||
0x58..=0x5F => {
|
||||
let reg_idx = (byte - 0x58) + if rex_b { 8 } else { 0 };
|
||||
let reg = Register::from_index(reg_idx);
|
||||
let val = self.pop_u64()?;
|
||||
self.cpu.set(reg, val);
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
_ => Err(ExitReason::IllegalInstruction(byte)),
|
||||
}
|
||||
}
|
||||
|
||||
fn push_u64(&mut self, val: u64) -> Result<(), ExitReason> {
|
||||
let sp = self.cpu.get(Register::Rsp);
|
||||
let new_sp = sp.checked_sub(8).ok_or(ExitReason::StackUnderflow)?;
|
||||
self.memory
|
||||
.write_u64(new_sp, val)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
self.cpu.set(Register::Rsp, new_sp);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn pop_u64(&mut self) -> Result<u64, ExitReason> {
|
||||
let sp = self.cpu.get(Register::Rsp);
|
||||
let val = self.memory.read_u64(sp).map_err(ExitReason::MemoryFault)?;
|
||||
self.cpu.set(Register::Rsp, sp + 8);
|
||||
Ok(val)
|
||||
}
|
||||
|
||||
fn decode_modrm_reg_reg(
|
||||
&self,
|
||||
modrm: u8,
|
||||
rex_r: bool,
|
||||
rex_b: bool,
|
||||
) -> Result<(Register, Register), ExitReason> {
|
||||
let mode = (modrm >> 6) & 3;
|
||||
if mode != 3 {
|
||||
return Err(ExitReason::IllegalInstruction(modrm));
|
||||
}
|
||||
let reg_idx = ((modrm >> 3) & 7) + if rex_r { 8 } else { 0 };
|
||||
let rm_idx = (modrm & 7) + if rex_b { 8 } else { 0 };
|
||||
Ok((Register::from_index(reg_idx), Register::from_index(rm_idx)))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn execute_mov_rm(
|
||||
&mut self,
|
||||
modrm: u8,
|
||||
rex_w: bool,
|
||||
rex_r: bool,
|
||||
rex_b: bool,
|
||||
is_load: bool,
|
||||
seg_gs: bool,
|
||||
seg_fs: bool,
|
||||
) -> Result<Option<ExitReason>, ExitReason> {
|
||||
let mode = (modrm >> 6) & 3;
|
||||
let reg_idx = ((modrm >> 3) & 7) + if rex_r { 8 } else { 0 };
|
||||
let rm_idx = (modrm & 7) + if rex_b { 8 } else { 0 };
|
||||
let reg = Register::from_index(reg_idx);
|
||||
|
||||
if mode == 3 {
|
||||
// Register-to-register move
|
||||
let rm = Register::from_index(rm_idx);
|
||||
if is_load {
|
||||
let val = self.cpu.get(rm);
|
||||
self.cpu
|
||||
.set(reg, if rex_w { val } else { val as u32 as u64 });
|
||||
} else {
|
||||
let val = self.cpu.get(reg);
|
||||
self.cpu
|
||||
.set(rm, if rex_w { val } else { val as u32 as u64 });
|
||||
}
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
// Memory operand [rm + disp] or SIB
|
||||
let (base_val, disp): (u64, i64) = if (rm_idx & 7) == 4 {
|
||||
// SIB byte follows ModR/M
|
||||
let sib = self.fetch_u8()?;
|
||||
let scale_shift = (sib >> 6) & 3;
|
||||
let index_raw = ((sib >> 3) & 7) + if rex_r { 8 } else { 0 }; // SIB.index can use REX.X; here index_raw
|
||||
let base_raw = (sib & 7) + if rex_b { 8 } else { 0 };
|
||||
|
||||
let base_v = if mode == 0 && (sib & 7) == 5 {
|
||||
// disp32 with no base register
|
||||
0u64
|
||||
} else {
|
||||
self.cpu.get(Register::from_index(base_raw))
|
||||
};
|
||||
|
||||
let index_v = if (sib >> 3) & 7 == 4 {
|
||||
// index == 4 means no index register (ESP/RSP)
|
||||
0u64
|
||||
} else {
|
||||
self.cpu.get(Register::from_index(index_raw)) << scale_shift
|
||||
};
|
||||
|
||||
let d: i64 = match mode {
|
||||
0 => {
|
||||
if (sib & 7) == 5 {
|
||||
self.fetch_i32()? as i64
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
1 => self.fetch_i8()? as i64,
|
||||
2 => self.fetch_i32()? as i64,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
|
||||
(base_v.wrapping_add(index_v), d)
|
||||
} else {
|
||||
let base_reg = Register::from_index(rm_idx);
|
||||
let base_val = self.cpu.get(base_reg);
|
||||
|
||||
let disp: i64 = match mode {
|
||||
0 => {
|
||||
if (rm_idx & 7) == 5 {
|
||||
// RIP-relative displacement disp32
|
||||
self.fetch_i32()? as i64
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
1 => self.fetch_i8()? as i64,
|
||||
2 => self.fetch_i32()? as i64,
|
||||
_ => unreachable!(),
|
||||
};
|
||||
(base_val, disp)
|
||||
};
|
||||
|
||||
let mut effective_addr = if mode == 0 && (rm_idx & 7) == 5 {
|
||||
(self.cpu.rip as i64 + disp) as u64
|
||||
} else {
|
||||
(base_val as i64 + disp) as u64
|
||||
};
|
||||
|
||||
if seg_gs {
|
||||
effective_addr = effective_addr.wrapping_add(self.cpu.gs_base);
|
||||
} else if seg_fs {
|
||||
effective_addr = effective_addr.wrapping_add(self.cpu.fs_base);
|
||||
}
|
||||
|
||||
if is_load {
|
||||
// Load from memory to reg
|
||||
if rex_w {
|
||||
let val = self
|
||||
.memory
|
||||
.read_u64(effective_addr)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
self.cpu.set(reg, val);
|
||||
} else {
|
||||
let val = self
|
||||
.memory
|
||||
.read_u32(effective_addr)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
self.cpu.set(reg, val as u64);
|
||||
}
|
||||
} else {
|
||||
// Store from reg to memory
|
||||
let val = self.cpu.get(reg);
|
||||
if rex_w {
|
||||
self.memory
|
||||
.write_u64(effective_addr, val)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
} else {
|
||||
self.memory
|
||||
.write_u32(effective_addr, val as u32)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn update_flags_logic(&mut self, val: u64, is_64: bool) {
|
||||
self.cpu.flags.cf = false;
|
||||
self.cpu.flags.of = false;
|
||||
if is_64 {
|
||||
self.cpu.flags.zf = val == 0;
|
||||
self.cpu.flags.sf = (val as i64) < 0;
|
||||
} else {
|
||||
let val32 = val as u32;
|
||||
self.cpu.flags.zf = val32 == 0;
|
||||
self.cpu.flags.sf = (val32 as i32) < 0;
|
||||
}
|
||||
let memory = &*self.memory;
|
||||
let insn = decode(self.cpu.rip, |address| {
|
||||
memory.fetch_instruction_byte(address)
|
||||
})
|
||||
.map_err(ExitReason::from)?;
|
||||
x86_exec::execute(&mut self.cpu, self.memory, &insn)
|
||||
}
|
||||
}
|
||||
|
||||
fn add64(a: u64, b: u64) -> (u64, RFlags) {
|
||||
let (res, cf) = a.overflowing_add(b);
|
||||
let of = ((a ^ res) & (b ^ res) & 0x8000_0000_0000_0000) != 0;
|
||||
let sf = (res as i64) < 0;
|
||||
let zf = res == 0;
|
||||
(res, RFlags { cf, zf, sf, of })
|
||||
}
|
||||
|
||||
fn add32(a: u32, b: u32) -> (u32, RFlags) {
|
||||
let (res, cf) = a.overflowing_add(b);
|
||||
let of = ((a ^ res) & (b ^ res) & 0x8000_0000) != 0;
|
||||
let sf = (res as i32) < 0;
|
||||
let zf = res == 0;
|
||||
(res, RFlags { cf, zf, sf, of })
|
||||
}
|
||||
|
||||
fn sub64(a: u64, b: u64) -> (u64, RFlags) {
|
||||
let (res, cf) = a.overflowing_sub(b);
|
||||
let of = ((a ^ b) & (a ^ res) & 0x8000_0000_0000_0000) != 0;
|
||||
let sf = (res as i64) < 0;
|
||||
let zf = res == 0;
|
||||
(res, RFlags { cf, zf, sf, of })
|
||||
}
|
||||
|
||||
fn sub32(a: u32, b: u32) -> (u32, RFlags) {
|
||||
let (res, cf) = a.overflowing_sub(b);
|
||||
let of = ((a ^ b) & (a ^ res) & 0x8000_0000) != 0;
|
||||
let sf = (res as i32) < 0;
|
||||
let zf = res == 0;
|
||||
(res, RFlags { cf, zf, sf, of })
|
||||
impl From<DecodeError<MemoryError>> for ExitReason {
|
||||
fn from(error: DecodeError<MemoryError>) -> Self {
|
||||
match error {
|
||||
DecodeError::Fetch(fault) => Self::MemoryFault(fault),
|
||||
DecodeError::Unsupported(byte) => Self::IllegalInstruction(byte),
|
||||
}
|
||||
}
|
||||
}
|
||||
+1462
-1210
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,218 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! 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.
|
||||
|
||||
use std::fmt;
|
||||
|
||||
/// Most import descriptors accepted in one image.
|
||||
pub const MAX_DESCRIPTORS: usize = 1024;
|
||||
/// Most imported symbols accepted in one image.
|
||||
pub const MAX_IMPORTS: usize = 65_536;
|
||||
/// Longest module or symbol name accepted, in bytes.
|
||||
pub const MAX_NAME_LEN: usize = 4096;
|
||||
|
||||
const DESCRIPTOR_LEN: u32 = 20;
|
||||
const ORDINAL_FLAG: u64 = 1 << 63;
|
||||
|
||||
/// How an import names its target. A symbol that happens to be spelled like an
|
||||
/// ordinal is still a name.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub enum ImportName {
|
||||
Name(String),
|
||||
Ordinal(u16),
|
||||
}
|
||||
|
||||
impl fmt::Display for ImportName {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Name(name) => f.write_str(name),
|
||||
Self::Ordinal(ordinal) => write!(f, "Ordinal#{ordinal}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ImportEntry {
|
||||
/// Module name as spelled in the image.
|
||||
pub module: String,
|
||||
pub name: ImportName,
|
||||
/// RVA of the import address table slot.
|
||||
pub iat_rva: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ImportTableError {
|
||||
/// A structure at this RVA is not fully backed by section data.
|
||||
OutOfBounds {
|
||||
rva: u32,
|
||||
},
|
||||
/// A name is empty, unterminated, too long or not printable ASCII.
|
||||
MalformedName {
|
||||
rva: u32,
|
||||
},
|
||||
/// A lookup entry at this RVA sets reserved bits.
|
||||
ReservedBits {
|
||||
rva: u32,
|
||||
},
|
||||
TooManyDescriptors,
|
||||
TooManyImports,
|
||||
}
|
||||
|
||||
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::MalformedName { rva } => write!(f, "malformed import name at RVA 0x{rva:08x}"),
|
||||
Self::ReservedBits { rva } => {
|
||||
write!(
|
||||
f,
|
||||
"reserved bits set in the import lookup at RVA 0x{rva:08x}"
|
||||
)
|
||||
}
|
||||
Self::TooManyDescriptors => write!(f, "more than {MAX_DESCRIPTORS} import descriptors"),
|
||||
Self::TooManyImports => write!(f, "more than {MAX_IMPORTS} imported symbols"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ImportTableError {}
|
||||
|
||||
/// Reads image bytes by RVA, requiring every byte to be backed by the file.
|
||||
struct Reader<'a, F> {
|
||||
bytes: &'a [u8],
|
||||
rva_to_offset: F,
|
||||
}
|
||||
|
||||
impl<F: Fn(u32) -> Option<usize>> Reader<'_, F> {
|
||||
fn byte(&self, rva: u32) -> Option<u8> {
|
||||
self.bytes.get((self.rva_to_offset)(rva)?).copied()
|
||||
}
|
||||
|
||||
fn array<const N: usize>(&self, rva: u32) -> Result<[u8; N], ImportTableError> {
|
||||
let mut out = [0; N];
|
||||
for (index, byte) in out.iter_mut().enumerate() {
|
||||
*byte = rva
|
||||
.checked_add(index as u32)
|
||||
.and_then(|rva| self.byte(rva))
|
||||
.ok_or(ImportTableError::OutOfBounds { rva })?;
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn u32(&self, rva: u32) -> Result<u32, ImportTableError> {
|
||||
self.array(rva).map(u32::from_le_bytes)
|
||||
}
|
||||
|
||||
fn name(&self, rva: u32) -> Result<String, ImportTableError> {
|
||||
let malformed = ImportTableError::MalformedName { rva };
|
||||
let mut name = String::new();
|
||||
for index in 0..=MAX_NAME_LEN as u32 {
|
||||
let byte = rva
|
||||
.checked_add(index)
|
||||
.and_then(|rva| self.byte(rva))
|
||||
.ok_or(malformed)?;
|
||||
match byte {
|
||||
0 if name.is_empty() => return Err(malformed),
|
||||
0 => return Ok(name),
|
||||
0x21..=0x7E => name.push(char::from(byte)),
|
||||
_ => return Err(malformed),
|
||||
}
|
||||
}
|
||||
Err(malformed)
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse the import directory at `directory_rva`.
|
||||
///
|
||||
/// Returns every import before the first problem, and the problem. Callers that
|
||||
/// execute an image must refuse it if there is one; inspection may report both.
|
||||
pub fn parse_imports(
|
||||
bytes: &[u8],
|
||||
directory_rva: 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(&reader, directory_rva, &mut entries).err();
|
||||
(entries, error)
|
||||
}
|
||||
|
||||
fn collect<F: Fn(u32) -> Option<usize>>(
|
||||
reader: &Reader<'_, F>,
|
||||
directory_rva: u32,
|
||||
entries: &mut Vec<ImportEntry>,
|
||||
) -> Result<(), ImportTableError> {
|
||||
let mut descriptor = directory_rva;
|
||||
for _ in 0..MAX_DESCRIPTORS {
|
||||
// Reading the whole descriptor also proves its field RVAs do not overflow.
|
||||
reader.array::<{ DESCRIPTOR_LEN as usize }>(descriptor)?;
|
||||
let lookup_rva = reader.u32(descriptor)?;
|
||||
let name_rva = reader.u32(descriptor + 12)?;
|
||||
let address_rva = reader.u32(descriptor + 16)?;
|
||||
// The table ends with an empty descriptor.
|
||||
if lookup_rva == 0 && name_rva == 0 && address_rva == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
let module = reader.name(name_rva)?;
|
||||
collect_symbols(reader, &module, lookup_rva, address_rva, entries)?;
|
||||
descriptor = descriptor
|
||||
.checked_add(DESCRIPTOR_LEN)
|
||||
.ok_or(ImportTableError::OutOfBounds { rva: descriptor })?;
|
||||
}
|
||||
Err(ImportTableError::TooManyDescriptors)
|
||||
}
|
||||
|
||||
fn collect_symbols<F: Fn(u32) -> Option<usize>>(
|
||||
reader: &Reader<'_, F>,
|
||||
module: &str,
|
||||
lookup_rva: u32,
|
||||
address_rva: u32,
|
||||
entries: &mut Vec<ImportEntry>,
|
||||
) -> Result<(), ImportTableError> {
|
||||
// Without a lookup table the address table holds the same entries on disk.
|
||||
let start = if lookup_rva != 0 {
|
||||
lookup_rva
|
||||
} else {
|
||||
address_rva
|
||||
};
|
||||
for index in 0.. {
|
||||
let at = |base: u32| {
|
||||
base.checked_add(index * 8)
|
||||
.ok_or(ImportTableError::OutOfBounds { rva: base })
|
||||
};
|
||||
let lookup = at(start)?;
|
||||
let value = u64::from_le_bytes(reader.array(lookup)?);
|
||||
if value == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
if entries.len() == MAX_IMPORTS {
|
||||
return Err(ImportTableError::TooManyImports);
|
||||
}
|
||||
let iat_rva = at(address_rva)?;
|
||||
let name = if value & ORDINAL_FLAG != 0 {
|
||||
let ordinal = value & !ORDINAL_FLAG;
|
||||
ImportName::Ordinal(
|
||||
u16::try_from(ordinal)
|
||||
.map_err(|_| ImportTableError::ReservedBits { rva: lookup })?,
|
||||
)
|
||||
} else {
|
||||
let hint = u32::try_from(value)
|
||||
.ok()
|
||||
.filter(|rva| rva >> 31 == 0)
|
||||
.ok_or(ImportTableError::ReservedBits { rva: lookup })?;
|
||||
// The name follows a two-byte export-table hint.
|
||||
ImportName::Name(reader.name(hint + 2)?)
|
||||
};
|
||||
entries.push(ImportEntry {
|
||||
module: module.to_owned(),
|
||||
name,
|
||||
iat_rva,
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
+215
-168
@@ -7,6 +7,7 @@
|
||||
//! guest services without exposing raw host function pointers.
|
||||
|
||||
use crate::cpu::{CpuState, ExitReason, Register};
|
||||
use crate::import_table::{ImportName, ImportTableError, MAX_NAME_LEN, parse_imports};
|
||||
use crate::memory::{GuestMemory, MemoryError};
|
||||
use crate::pe::ParsedPe;
|
||||
use std::collections::HashMap;
|
||||
@@ -19,8 +20,7 @@ pub const IMPORT_TRAMPOLINE_STRIDE: u64 = 16;
|
||||
/// Typed error resulting from import resolution or service dispatch.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum ImportError {
|
||||
MalformedDirectory,
|
||||
DirectoryOutOfBounds { rva: u32 },
|
||||
Table(ImportTableError),
|
||||
UnresolvedImport { module: String, symbol: String },
|
||||
Memory(MemoryError),
|
||||
}
|
||||
@@ -28,10 +28,7 @@ pub enum ImportError {
|
||||
impl fmt::Display for ImportError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::MalformedDirectory => write!(f, "malformed PE import directory"),
|
||||
Self::DirectoryOutOfBounds { rva } => {
|
||||
write!(f, "import directory at RVA 0x{rva:08x} is out of bounds")
|
||||
}
|
||||
Self::Table(e) => write!(f, "malformed PE imports: {e}"),
|
||||
Self::UnresolvedImport { module, symbol } => {
|
||||
write!(f, "unresolved import dependency: {module}!{symbol}")
|
||||
}
|
||||
@@ -42,6 +39,38 @@ impl fmt::Display for ImportError {
|
||||
|
||||
impl std::error::Error for ImportError {}
|
||||
|
||||
/// Why a service could not be added to the registry.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum RegistryError {
|
||||
/// The key already names a different service.
|
||||
Duplicate {
|
||||
module: String,
|
||||
symbol: String,
|
||||
},
|
||||
/// An alias names a service that does not exist.
|
||||
UnknownTarget {
|
||||
module: String,
|
||||
symbol: String,
|
||||
},
|
||||
InvalidName {
|
||||
module: String,
|
||||
symbol: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl fmt::Display for RegistryError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let (problem, module, symbol) = match self {
|
||||
Self::Duplicate { module, symbol } => ("is already registered", module, symbol),
|
||||
Self::UnknownTarget { module, symbol } => ("is not registered", module, symbol),
|
||||
Self::InvalidName { module, symbol } => ("is not a valid name", module, symbol),
|
||||
};
|
||||
write!(f, "import {module}!{symbol} {problem}")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for RegistryError {}
|
||||
|
||||
impl From<MemoryError> for ImportError {
|
||||
fn from(e: MemoryError) -> Self {
|
||||
Self::Memory(e)
|
||||
@@ -128,7 +157,8 @@ pub struct ServiceDescriptor {
|
||||
|
||||
/// Registry for resolving and binding import symbols to guest trampoline VAs.
|
||||
pub struct ImportRegistry {
|
||||
services: HashMap<(String, String), usize>, // (module_lowercase, symbol) -> service_index
|
||||
// (lower-case module, name) -> service index. Symbol names keep their case.
|
||||
services: HashMap<(String, ImportName), usize>,
|
||||
handlers: Vec<ServiceDescriptor>,
|
||||
trampoline_to_service: HashMap<u64, usize>, // Trampoline VA -> service_index
|
||||
}
|
||||
@@ -148,18 +178,82 @@ impl ImportRegistry {
|
||||
}
|
||||
}
|
||||
|
||||
fn service_index(&self, module: &str, symbol: &str) -> Option<usize> {
|
||||
/// The one lookup used by binding, inspection and reports. Module names
|
||||
/// compare without case, as Windows does; symbol names are exact. API sets
|
||||
/// resolve only through registered aliases.
|
||||
pub fn resolve(&self, module: &str, name: &ImportName) -> Option<&ServiceDescriptor> {
|
||||
self.index(module, name).map(|index| &self.handlers[index])
|
||||
}
|
||||
|
||||
fn index(&self, module: &str, name: &ImportName) -> Option<usize> {
|
||||
self.services
|
||||
.get(&(module.to_ascii_lowercase(), symbol.to_owned()))
|
||||
.get(&(module.to_ascii_lowercase(), name.clone()))
|
||||
.copied()
|
||||
}
|
||||
|
||||
fn service_index(&self, module: &str, symbol: &str) -> Option<usize> {
|
||||
self.index(module, &ImportName::Name(symbol.to_owned()))
|
||||
}
|
||||
|
||||
fn check_key(module: &str, name: &ImportName) -> Result<(), RegistryError> {
|
||||
let printable = |text: &str| {
|
||||
!text.is_empty()
|
||||
&& text.len() <= MAX_NAME_LEN
|
||||
&& text.bytes().all(|b| b.is_ascii_graphic())
|
||||
};
|
||||
let valid = printable(module)
|
||||
&& match name {
|
||||
ImportName::Name(symbol) => printable(symbol),
|
||||
ImportName::Ordinal(_) => true,
|
||||
};
|
||||
if valid {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(RegistryError::InvalidName {
|
||||
module: module.to_owned(),
|
||||
symbol: name.to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Check whether the exact import key has a binding, including stub handlers.
|
||||
pub fn has_binding(&self, module: &str, symbol: &str) -> bool {
|
||||
self.service_index(module, symbol).is_some()
|
||||
}
|
||||
|
||||
/// Register a host-provided guest service.
|
||||
/// Register a host-provided guest service under a name or an ordinal.
|
||||
pub fn try_register(
|
||||
&mut self,
|
||||
module: &str,
|
||||
name: ImportName,
|
||||
status: ServiceStatus,
|
||||
handler: ServiceHandler,
|
||||
) -> Result<(), RegistryError> {
|
||||
Self::check_key(module, &name)?;
|
||||
let key = (module.to_ascii_lowercase(), name);
|
||||
if self.services.contains_key(&key) {
|
||||
return Err(RegistryError::Duplicate {
|
||||
module: key.0,
|
||||
symbol: key.1.to_string(),
|
||||
});
|
||||
}
|
||||
let index = self.handlers.len();
|
||||
self.handlers.push(ServiceDescriptor {
|
||||
module: key.0.clone(),
|
||||
symbol: key.1.to_string(),
|
||||
handler,
|
||||
status,
|
||||
});
|
||||
self.services.insert(key, index);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Register a named service.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// If the name is invalid or already registered, so that one host module
|
||||
/// cannot silently replace another's service.
|
||||
pub fn register<F>(&mut self, module: &str, symbol: &str, handler: F)
|
||||
where
|
||||
F: Fn(&Win64Args, &mut CpuState, &mut GuestMemory) -> Result<u64, ExitReason>
|
||||
@@ -167,16 +261,7 @@ impl ImportRegistry {
|
||||
+ Sync
|
||||
+ 'static,
|
||||
{
|
||||
let mod_key = module.to_ascii_lowercase();
|
||||
let sym_key = symbol.to_string();
|
||||
let index = self.handlers.len();
|
||||
self.handlers.push(ServiceDescriptor {
|
||||
module: mod_key.clone(),
|
||||
symbol: sym_key.clone(),
|
||||
handler: Box::new(handler),
|
||||
status: ServiceStatus::Implemented,
|
||||
});
|
||||
self.services.insert((mod_key, sym_key), index);
|
||||
self.register_with_status(module, symbol, ServiceStatus::Implemented, handler);
|
||||
}
|
||||
|
||||
/// Describe the canonical binding behind an import without calling it.
|
||||
@@ -200,7 +285,10 @@ impl ImportRegistry {
|
||||
pub fn iter_aliases(&self) -> impl Iterator<Item = (&str, &str, &str)> {
|
||||
// `services` maps (module_lc, symbol) -> handler_index.
|
||||
// An alias exists when module_lc != handlers[index].module.to_lowercase().
|
||||
self.services.iter().filter_map(|((mod_lc, sym), &idx)| {
|
||||
self.services.iter().filter_map(|((mod_lc, name), &idx)| {
|
||||
let ImportName::Name(sym) = name else {
|
||||
return None;
|
||||
};
|
||||
let canonical_mod = self.handlers[idx].module.to_ascii_lowercase();
|
||||
if *mod_lc != canonical_mod {
|
||||
Some((
|
||||
@@ -221,7 +309,11 @@ impl ImportRegistry {
|
||||
self.handlers[index].status = status;
|
||||
}
|
||||
|
||||
/// Register a service with an explicit implementation status.
|
||||
/// Register a named service with an explicit implementation status.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// As [`Self::register`].
|
||||
pub fn register_with_status<F>(
|
||||
&mut self,
|
||||
module: &str,
|
||||
@@ -234,17 +326,40 @@ impl ImportRegistry {
|
||||
+ Sync
|
||||
+ 'static,
|
||||
{
|
||||
self.register(module, symbol, handler);
|
||||
self.set_status(module, symbol, status);
|
||||
let name = ImportName::Name(symbol.to_owned());
|
||||
if let Err(error) = self.try_register(module, name, status, Box::new(handler)) {
|
||||
panic!("{error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Point an API-set import at an existing handler and its trampoline.
|
||||
pub(crate) fn alias(&mut self, module: &str, target: &str, symbol: &str) {
|
||||
/// Make `module` resolve `symbol` to the service registered as
|
||||
/// `target!symbol`, sharing its trampoline.
|
||||
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
|
||||
.service_index(target, symbol)
|
||||
.expect("registered alias target");
|
||||
self.services
|
||||
.insert((module.to_ascii_lowercase(), symbol.to_owned()), index);
|
||||
.index(target, &name)
|
||||
.ok_or_else(|| RegistryError::UnknownTarget {
|
||||
module: target.to_owned(),
|
||||
symbol: symbol.to_owned(),
|
||||
})?;
|
||||
let previous = *self
|
||||
.services
|
||||
.entry((module.to_ascii_lowercase(), name))
|
||||
.or_insert(index);
|
||||
if previous == index {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(RegistryError::Duplicate {
|
||||
module: module.to_owned(),
|
||||
symbol: symbol.to_owned(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Bind the PE's Import Address Table (IAT) in guest memory to synthetic trampoline VAs.
|
||||
@@ -255,103 +370,37 @@ impl ImportRegistry {
|
||||
loaded_base: u64,
|
||||
memory: &mut GuestMemory,
|
||||
) -> Result<usize, ImportError> {
|
||||
let import_dir = find_import_directory(bytes)?;
|
||||
let Some((import_rva, import_size)) = import_dir else {
|
||||
let Some(directory) = find_import_directory(bytes) else {
|
||||
return Ok(0);
|
||||
};
|
||||
if import_size == 0 {
|
||||
return Ok(0);
|
||||
let (entries, error) = parse_imports(bytes, directory, |rva| pe.rva_to_file_offset(rva));
|
||||
if let Some(error) = error {
|
||||
return Err(ImportError::Table(error));
|
||||
}
|
||||
|
||||
let mut desc_file_off = pe
|
||||
.rva_to_file_offset(import_rva)
|
||||
.ok_or(ImportError::DirectoryOutOfBounds { rva: import_rva })?;
|
||||
|
||||
let mut bound_count = 0;
|
||||
|
||||
while desc_file_off + 20 <= bytes.len() {
|
||||
let oft =
|
||||
u32::from_le_bytes(bytes[desc_file_off..desc_file_off + 4].try_into().unwrap());
|
||||
let name_rva = u32::from_le_bytes(
|
||||
bytes[desc_file_off + 12..desc_file_off + 16]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
);
|
||||
let ft = u32::from_le_bytes(
|
||||
bytes[desc_file_off + 16..desc_file_off + 20]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
if oft == 0 && name_rva == 0 && ft == 0 {
|
||||
break;
|
||||
}
|
||||
desc_file_off += 20;
|
||||
|
||||
let mod_name = if let Some(no) = pe.rva_to_file_offset(name_rva) {
|
||||
let mut end = no;
|
||||
while end < bytes.len() && bytes[end] != 0 {
|
||||
end += 1;
|
||||
}
|
||||
String::from_utf8_lossy(&bytes[no..end]).into_owned()
|
||||
} else {
|
||||
"UNKNOWN.dll".to_string()
|
||||
// Resolve everything first: a refused image must leave memory unbound.
|
||||
let mut slots = Vec::with_capacity(entries.len());
|
||||
for entry in entries {
|
||||
let Some(index) = self.index(&entry.module, &entry.name) else {
|
||||
return Err(ImportError::UnresolvedImport {
|
||||
module: entry.module,
|
||||
symbol: entry.name.to_string(),
|
||||
});
|
||||
};
|
||||
|
||||
let thunk_rva = if oft != 0 { oft } else { ft };
|
||||
let iat_base_rva = ft;
|
||||
|
||||
let Some(mut thunk_off) = pe.rva_to_file_offset(thunk_rva) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let mut idx = 0u32;
|
||||
while thunk_off + 8 <= bytes.len() {
|
||||
let val = u64::from_le_bytes(bytes[thunk_off..thunk_off + 8].try_into().unwrap());
|
||||
if val == 0 {
|
||||
break;
|
||||
}
|
||||
thunk_off += 8;
|
||||
let iat_rva = iat_base_rva + idx * 8;
|
||||
idx += 1;
|
||||
|
||||
let sym_name = if (val & (1 << 63)) != 0 {
|
||||
format!("Ordinal#{}", val & 0xFFFF)
|
||||
} else {
|
||||
let hint_rva = (val & 0x7FFF_FFFF) as u32;
|
||||
if let Some(ho) = pe.rva_to_file_offset(hint_rva) {
|
||||
let str_start = ho + 2;
|
||||
let mut str_end = str_start;
|
||||
while str_end < bytes.len() && bytes[str_end] != 0 {
|
||||
str_end += 1;
|
||||
}
|
||||
String::from_utf8_lossy(&bytes[str_start..str_end]).into_owned()
|
||||
} else {
|
||||
"UNKNOWN_SYM".to_string()
|
||||
}
|
||||
};
|
||||
|
||||
let Some(service_idx) = self.service_index(&mod_name, &sym_name) else {
|
||||
return Err(ImportError::UnresolvedImport {
|
||||
module: mod_name,
|
||||
symbol: sym_name,
|
||||
});
|
||||
};
|
||||
|
||||
// Assign a deterministic synthetic trampoline VA
|
||||
let trampoline_va =
|
||||
IMPORT_TRAMPOLINE_BASE_VA + (service_idx as u64) * IMPORT_TRAMPOLINE_STRIDE;
|
||||
self.trampoline_to_service
|
||||
.insert(trampoline_va, service_idx);
|
||||
|
||||
// Write trampoline_va into guest IAT entry at (loaded_base + iat_rva)
|
||||
let iat_va = loaded_base + iat_rva as u64;
|
||||
memory.write_u64_bypass(iat_va, trampoline_va)?;
|
||||
bound_count += 1;
|
||||
}
|
||||
let address = loaded_base
|
||||
.checked_add(u64::from(entry.iat_rva))
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
// The loader writes slots regardless of page permissions, so only
|
||||
// mapping is checked here.
|
||||
memory.read_u64_bypass(address)?;
|
||||
slots.push((address, index));
|
||||
}
|
||||
|
||||
Ok(bound_count)
|
||||
for &(address, index) in &slots {
|
||||
let trampoline = IMPORT_TRAMPOLINE_BASE_VA + (index as u64) * IMPORT_TRAMPOLINE_STRIDE;
|
||||
memory.write_u64_bypass(address, trampoline)?;
|
||||
self.trampoline_to_service.insert(trampoline, index);
|
||||
}
|
||||
Ok(slots.len())
|
||||
}
|
||||
|
||||
/// Check if target RIP matches a synthetic service trampoline.
|
||||
@@ -373,60 +422,58 @@ impl ImportRegistry {
|
||||
|
||||
let descriptor = &self.handlers[service_idx];
|
||||
|
||||
// 1. Extract arguments according to Win64 convention
|
||||
let args = Win64Args::new(cpu);
|
||||
|
||||
// 2. Execute service handler
|
||||
let ret_val = (descriptor.handler)(&args, cpu, memory)?;
|
||||
|
||||
// 3. Store return value into RAX
|
||||
cpu.set(Register::Rax, ret_val);
|
||||
|
||||
// 4. Emulate RET instruction: pop return address from guest stack into RIP
|
||||
// Read the return address first, so a call that cannot return has no effect.
|
||||
let rsp = cpu.get(Register::Rsp);
|
||||
let ret_addr = memory.read_u64(rsp).map_err(ExitReason::MemoryFault)?;
|
||||
cpu.set(Register::Rsp, rsp + 8);
|
||||
cpu.rip = ret_addr;
|
||||
let after = rsp
|
||||
.checked_add(8)
|
||||
.ok_or(ExitReason::MemoryFault(MemoryError::Overflow))?;
|
||||
|
||||
let args = Win64Args::new(cpu);
|
||||
let preserved = Nonvolatile::of(cpu);
|
||||
let value = (descriptor.handler)(&args, cpu, memory)?;
|
||||
if Nonvolatile::of(cpu) != preserved {
|
||||
return Err(ExitReason::ServiceAbiViolation);
|
||||
}
|
||||
|
||||
cpu.set(Register::Rax, value);
|
||||
cpu.set(Register::Rsp, after);
|
||||
cpu.rip = ret_addr;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn find_import_directory(bytes: &[u8]) -> Result<Option<(u32, u32)>, ImportError> {
|
||||
if bytes.len() < 0x40 {
|
||||
return Ok(None);
|
||||
}
|
||||
let e_lfanew = u32::from_le_bytes(bytes[0x3C..0x40].try_into().unwrap()) as usize;
|
||||
let opt_offset = e_lfanew + 24;
|
||||
let coff_offset = e_lfanew + 4;
|
||||
if bytes.len() < coff_offset + 18 {
|
||||
return Ok(None);
|
||||
}
|
||||
let size_of_opt = u16::from_le_bytes(
|
||||
bytes[coff_offset + 16..coff_offset + 18]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
) as usize;
|
||||
/// Registers a Win64 callee must preserve (Microsoft x64 calling convention).
|
||||
#[derive(PartialEq, Eq)]
|
||||
struct Nonvolatile {
|
||||
gpr: [u64; 9],
|
||||
xmm: [u128; 10],
|
||||
}
|
||||
|
||||
// Import directory is directory index 1 (offset 112 + 1 * 8 = 120 in Optional Header)
|
||||
if size_of_opt < 128 || bytes.len() < opt_offset + 128 {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let import_rva = u32::from_le_bytes(
|
||||
bytes[opt_offset + 120..opt_offset + 124]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
);
|
||||
let import_size = u32::from_le_bytes(
|
||||
bytes[opt_offset + 124..opt_offset + 128]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
if import_rva == 0 || import_size == 0 {
|
||||
Ok(None)
|
||||
} else {
|
||||
Ok(Some((import_rva, import_size)))
|
||||
impl Nonvolatile {
|
||||
fn of(cpu: &CpuState) -> Self {
|
||||
use Register::{R12, R13, R14, R15, Rbp, Rbx, Rdi, Rsi, Rsp};
|
||||
let mut xmm = [0; 10];
|
||||
xmm.copy_from_slice(&cpu.xmm[6..]);
|
||||
Self {
|
||||
gpr: [Rbx, Rbp, Rdi, Rsi, Rsp, R12, R13, R14, R15].map(|register| cpu.get(register)),
|
||||
xmm,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// RVA of the import directory, if the image has one.
|
||||
pub(crate) fn find_import_directory(bytes: &[u8]) -> Option<u32> {
|
||||
let field = |offset: usize, len: usize| bytes.get(offset..offset.checked_add(len)?);
|
||||
let u32_at = |offset| Some(u32::from_le_bytes(field(offset, 4)?.try_into().ok()?));
|
||||
let coff = (u32_at(0x3C)? as usize).checked_add(4)?;
|
||||
let optional = coff.checked_add(20)?;
|
||||
let optional_len = u16::from_le_bytes(field(coff + 16, 2)?.try_into().ok()?);
|
||||
// The import directory is data directory 1, at offset 120.
|
||||
if optional_len < 128 {
|
||||
return None;
|
||||
}
|
||||
let rva = u32_at(optional.checked_add(120)?)?;
|
||||
let size = u32_at(optional.checked_add(124)?)?;
|
||||
(rva != 0 && size != 0).then_some(rva)
|
||||
}
|
||||
@@ -9,16 +9,27 @@ pub mod arm64;
|
||||
pub mod cpu;
|
||||
pub mod dbt;
|
||||
pub mod graphics;
|
||||
pub mod import_table;
|
||||
pub mod imports;
|
||||
pub mod jit;
|
||||
pub mod memory;
|
||||
pub mod pe;
|
||||
pub mod probe;
|
||||
pub mod reloc;
|
||||
pub mod runtime;
|
||||
#[rustfmt::skip]
|
||||
pub mod runtime_table;
|
||||
pub mod services;
|
||||
pub mod softfloat;
|
||||
pub mod startup;
|
||||
pub mod tls;
|
||||
pub mod triage;
|
||||
pub mod x86_decode;
|
||||
pub mod x86_exec;
|
||||
pub mod x86_float;
|
||||
pub mod x86_simd;
|
||||
#[rustfmt::skip]
|
||||
pub mod x86_table;
|
||||
|
||||
pub use arm64::Arm64Assembler;
|
||||
pub use cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, RFlags, Register};
|
||||
|
||||
+90
-66
@@ -226,57 +226,102 @@ impl GuestMemory {
|
||||
true
|
||||
}
|
||||
|
||||
/// Write raw bytes into guest memory at the specified address, checking permissions.
|
||||
pub fn write_bytes(&mut self, address: u64, src: &[u8]) -> Result<(), MemoryError> {
|
||||
for region in &mut self.regions {
|
||||
if region.contains(address, src.len()) {
|
||||
if !region.permissions.write {
|
||||
return Err(MemoryError::PermissionViolation {
|
||||
address,
|
||||
required: "write",
|
||||
});
|
||||
}
|
||||
let offset = (address - region.base) as usize;
|
||||
region.data[offset..offset + src.len()].copy_from_slice(src);
|
||||
return Ok(());
|
||||
/// Resolve `[address, address + len)` to `(region index, offset, length)` pieces.
|
||||
///
|
||||
/// An access may span adjacent regions, as it would span adjacent pages, but every
|
||||
/// byte must be mapped and every region must grant `required` (`None` bypasses
|
||||
/// permission checks for the loader). The whole range is checked before any byte
|
||||
/// is copied, so a failed access never partially reads or writes.
|
||||
fn resolve(
|
||||
&self,
|
||||
address: u64,
|
||||
len: usize,
|
||||
required: Option<&'static str>,
|
||||
) -> Result<Vec<(usize, usize, usize)>, MemoryError> {
|
||||
let end = address
|
||||
.checked_add(len as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
if len == 0 {
|
||||
return if self.regions.iter().any(|r| r.contains(address, 0)) {
|
||||
Ok(Vec::new())
|
||||
} else {
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
};
|
||||
}
|
||||
let mut pieces = Vec::new();
|
||||
let mut cursor = address;
|
||||
for (index, region) in self.regions.iter().enumerate() {
|
||||
let region_end = region.base + region.data.len() as u64;
|
||||
if region_end <= cursor {
|
||||
continue;
|
||||
}
|
||||
if region.base > cursor {
|
||||
break;
|
||||
}
|
||||
let permitted = match required {
|
||||
None => true,
|
||||
Some("read") => region.permissions.read,
|
||||
Some("write") => region.permissions.write,
|
||||
Some(_) => region.permissions.execute,
|
||||
};
|
||||
if let (false, Some(required)) = (permitted, required) {
|
||||
return Err(MemoryError::PermissionViolation { address, required });
|
||||
}
|
||||
let take = (end.min(region_end) - cursor) as usize;
|
||||
pieces.push((index, (cursor - region.base) as usize, take));
|
||||
cursor += take as u64;
|
||||
if cursor == end {
|
||||
return Ok(pieces);
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
}
|
||||
|
||||
fn read_checked(
|
||||
&self,
|
||||
address: u64,
|
||||
dst: &mut [u8],
|
||||
required: Option<&'static str>,
|
||||
) -> Result<(), MemoryError> {
|
||||
let mut done = 0;
|
||||
for (index, offset, take) in self.resolve(address, dst.len(), required)? {
|
||||
dst[done..done + take]
|
||||
.copy_from_slice(&self.regions[index].data[offset..offset + take]);
|
||||
done += take;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_checked(
|
||||
&mut self,
|
||||
address: u64,
|
||||
src: &[u8],
|
||||
required: Option<&'static str>,
|
||||
) -> Result<(), MemoryError> {
|
||||
let mut done = 0;
|
||||
for (index, offset, take) in self.resolve(address, src.len(), required)? {
|
||||
self.regions[index].data[offset..offset + take]
|
||||
.copy_from_slice(&src[done..done + take]);
|
||||
done += take;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write raw bytes into guest memory at the specified address, checking permissions.
|
||||
pub fn write_bytes(&mut self, address: u64, src: &[u8]) -> Result<(), MemoryError> {
|
||||
self.write_checked(address, src, Some("write"))
|
||||
}
|
||||
|
||||
/// Read raw bytes from guest memory at the specified address, checking permissions.
|
||||
pub fn read_bytes(&self, address: u64, dst: &mut [u8]) -> Result<(), MemoryError> {
|
||||
for region in &self.regions {
|
||||
if region.contains(address, dst.len()) {
|
||||
if !region.permissions.read {
|
||||
return Err(MemoryError::PermissionViolation {
|
||||
address,
|
||||
required: "read",
|
||||
});
|
||||
}
|
||||
let offset = (address - region.base) as usize;
|
||||
dst.copy_from_slice(®ion.data[offset..offset + dst.len()]);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
self.read_checked(address, dst, Some("read"))
|
||||
}
|
||||
|
||||
/// Read an instruction byte from guest memory, verifying execute permission.
|
||||
pub fn fetch_instruction_byte(&self, address: u64) -> Result<u8, MemoryError> {
|
||||
for region in &self.regions {
|
||||
if region.contains(address, 1) {
|
||||
if !region.permissions.execute {
|
||||
return Err(MemoryError::PermissionViolation {
|
||||
address,
|
||||
required: "execute",
|
||||
});
|
||||
}
|
||||
let offset = (address - region.base) as usize;
|
||||
return Ok(region.data[offset]);
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
let mut buf = [0u8; 1];
|
||||
self.read_checked(address, &mut buf, Some("execute"))?;
|
||||
Ok(buf[0])
|
||||
}
|
||||
|
||||
/// Read a 64-bit integer (little endian) from guest memory.
|
||||
@@ -288,14 +333,9 @@ impl GuestMemory {
|
||||
|
||||
/// Read a 64-bit integer ignoring region read permissions (e.g. loader/relocation phase).
|
||||
pub fn read_u64_bypass(&self, address: u64) -> Result<u64, MemoryError> {
|
||||
for region in &self.regions {
|
||||
if region.contains(address, 8) {
|
||||
let offset = (address - region.base) as usize;
|
||||
let buf: [u8; 8] = region.data[offset..offset + 8].try_into().unwrap();
|
||||
return Ok(u64::from_le_bytes(buf));
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
let mut buf = [0u8; 8];
|
||||
self.read_checked(address, &mut buf, None)?;
|
||||
Ok(u64::from_le_bytes(buf))
|
||||
}
|
||||
|
||||
/// Write a 64-bit integer (little endian) to guest memory.
|
||||
@@ -305,15 +345,7 @@ impl GuestMemory {
|
||||
|
||||
/// Write a 64-bit integer ignoring region write permissions (e.g. loader/relocation phase).
|
||||
pub fn write_u64_bypass(&mut self, address: u64, value: u64) -> Result<(), MemoryError> {
|
||||
let bytes = value.to_le_bytes();
|
||||
for region in &mut self.regions {
|
||||
if region.contains(address, 8) {
|
||||
let offset = (address - region.base) as usize;
|
||||
region.data[offset..offset + 8].copy_from_slice(&bytes);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
self.write_checked(address, &value.to_le_bytes(), None)
|
||||
}
|
||||
|
||||
/// Read a 32-bit integer (little endian) from guest memory.
|
||||
@@ -330,15 +362,7 @@ impl GuestMemory {
|
||||
|
||||
/// Write a 32-bit integer ignoring region write permissions (e.g. loader/relocation phase).
|
||||
pub fn write_u32_bypass(&mut self, address: u64, value: u32) -> Result<(), MemoryError> {
|
||||
let bytes = value.to_le_bytes();
|
||||
for region in &mut self.regions {
|
||||
if region.contains(address, 4) {
|
||||
let offset = (address - region.base) as usize;
|
||||
region.data[offset..offset + 4].copy_from_slice(&bytes);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
Err(MemoryError::UnmappedAddress(address))
|
||||
self.write_checked(address, &value.to_le_bytes(), None)
|
||||
}
|
||||
|
||||
/// Read a single byte from guest memory.
|
||||
|
||||
+18
-1
@@ -94,6 +94,9 @@ pub const PE32_PLUS_MAGIC: u16 = 0x020B;
|
||||
/// PE32+ optional header length up to and including NumberOfRvaAndSizes.
|
||||
const PE32_PLUS_MIN_OPTIONAL_HEADER: usize = 112;
|
||||
const SECTION_HEADER_SIZE: usize = 40;
|
||||
/// Host memory budget for all mapped sections of one image. This is a loader policy
|
||||
/// limit, not a property of the PE format.
|
||||
const MAX_MAPPED_IMAGE_BYTES: u64 = 256 * 1024 * 1024;
|
||||
|
||||
fn read_u16(bytes: &[u8], at: usize) -> u16 {
|
||||
u16::from_le_bytes([bytes[at], bytes[at + 1]])
|
||||
@@ -170,7 +173,10 @@ impl ParsedPe {
|
||||
}
|
||||
|
||||
let mut sections = Vec::with_capacity(usize::from(number_of_sections));
|
||||
for sec_bytes in bytes[section_table_offset..table_end].chunks_exact(SECTION_HEADER_SIZE) {
|
||||
for sec_bytes in bytes[section_table_offset..table_end]
|
||||
.as_chunks::<SECTION_HEADER_SIZE>()
|
||||
.0
|
||||
{
|
||||
// Section name (up to 8 bytes UTF-8 or null-padded ASCII)
|
||||
let name_raw = &sec_bytes[0..8];
|
||||
let name_len = name_raw.iter().position(|&b| b == 0).unwrap_or(8);
|
||||
@@ -270,6 +276,17 @@ impl ParsedPe {
|
||||
}
|
||||
|
||||
pub(crate) fn load_at_base(&self, bytes: &[u8], base: u64) -> Result<LoadedImage, PeError> {
|
||||
// Each section becomes a zero-filled host allocation, so bound the total before
|
||||
// allocating anything. Sections may not overlap, so the sum is the mapped size.
|
||||
let mapped: u64 = self
|
||||
.sections
|
||||
.iter()
|
||||
.map(|sec| u64::from(sec.virtual_size.max(sec.raw_data_size)))
|
||||
.sum();
|
||||
if mapped > MAX_MAPPED_IMAGE_BYTES {
|
||||
return Err(PeError::SectionMappingError(MemoryError::AllocationFailed));
|
||||
}
|
||||
|
||||
let mut memory = GuestMemory::new();
|
||||
|
||||
for sec in &self.sections {
|
||||
|
||||
+182
-141
@@ -10,10 +10,14 @@
|
||||
//! padding bytes (e.g. INT3 after an unconditional JMP) are never classified as
|
||||
//! startup blockers.
|
||||
|
||||
use crate::dbt::{is_native, is_translatable};
|
||||
use crate::import_table::{ImportTableError, parse_imports};
|
||||
use crate::imports::{ImportRegistry, ServiceStatus};
|
||||
use crate::memory::MemoryPermissions;
|
||||
use crate::pe::{IMAGE_FILE_MACHINE_AMD64, PE32_PLUS_MAGIC, ParsedPe, PeError, PeSection};
|
||||
use crate::services::{MockClock, ServicesState, register_standard_services};
|
||||
use crate::x86_decode::{Encoding, MAX_INSTRUCTION_LEN, decode};
|
||||
use crate::x86_table::Op;
|
||||
use std::cmp::Reverse;
|
||||
use std::collections::{BTreeMap, BTreeSet, BinaryHeap};
|
||||
use std::fmt::Write as _;
|
||||
@@ -67,6 +71,26 @@ struct CfgDecoded {
|
||||
fall_through: bool,
|
||||
}
|
||||
|
||||
/// Consume a ModRM byte with its SIB byte and displacement, returning the
|
||||
/// ModRM byte and the offset just past the operand, or `None` if truncated.
|
||||
fn modrm_operand(slice: &[u8], pc: usize) -> Option<(u8, usize)> {
|
||||
let modrm = *slice.get(pc)?;
|
||||
let mode = modrm >> 6;
|
||||
let mut end = pc + 1;
|
||||
let mut base = modrm & 7;
|
||||
if mode != 3 && base == 4 {
|
||||
base = slice.get(end)? & 7;
|
||||
end += 1;
|
||||
}
|
||||
end += match mode {
|
||||
1 => 1,
|
||||
2 => 4,
|
||||
0 if base == 5 => 4,
|
||||
_ => 0,
|
||||
};
|
||||
(end <= slice.len()).then_some((modrm, end))
|
||||
}
|
||||
|
||||
/// Decode a single x86-64 instruction from a file-mapped byte slice.
|
||||
///
|
||||
/// `slice` — file bytes beginning at the instruction's raw file offset.
|
||||
@@ -83,16 +107,40 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
|
||||
let mut b0 = slice[pc];
|
||||
pc += 1;
|
||||
|
||||
// Legacy segment prefixes: 0x65 (GS), 0x64 (FS)
|
||||
while (b0 == 0x65 || b0 == 0x64) && pc < slice.len() {
|
||||
// Legacy segment prefixes: 0x65 (GS), 0x64 (FS). The run is bounded by the
|
||||
// architectural instruction-length limit (15 bytes); a longer run is
|
||||
// reported as an overlong prefix sequence instead of decoding past it.
|
||||
while (b0 == 0x65 || b0 == 0x64) && pc < slice.len() && pc < MAX_INSTRUCTION_LEN {
|
||||
b0 = slice[pc];
|
||||
pc += 1;
|
||||
}
|
||||
let overlong_prefix_run =
|
||||
pc < slice.len() && (b0 == 0x65 || b0 == 0x64) && pc >= MAX_INSTRUCTION_LEN;
|
||||
if overlong_prefix_run {
|
||||
return Some(CfgDecoded {
|
||||
rva,
|
||||
insn_len: pc,
|
||||
mnemonic: "overlong prefix run".into(),
|
||||
is_dbt: false,
|
||||
is_interp: false,
|
||||
notes: "instruction length exceeds the 15-byte architectural limit".into(),
|
||||
successors: vec![],
|
||||
fall_through: false,
|
||||
});
|
||||
}
|
||||
|
||||
// Recognize the operand-size override for C7 without changing how the
|
||||
// probe classifies prefixes on unrelated opcodes.
|
||||
let operand_override =
|
||||
b0 == 0x66 && matches!(slice.get(pc..), Some([0xc7, ..] | [0x40..=0x4f, 0xc7, ..]));
|
||||
// Recognize the operand-size override for C7 and the extension family
|
||||
// without changing how the probe classifies prefixes on unrelated opcodes.
|
||||
let operand_override = b0 == 0x66
|
||||
&& matches!(
|
||||
slice.get(pc..),
|
||||
Some(
|
||||
[0xc7, ..]
|
||||
| [0x40..=0x4f, 0xc7, ..]
|
||||
| [0x0f, 0xb6 | 0xb7 | 0xbe | 0xbf, ..]
|
||||
| [0x40..=0x4f, 0x0f, 0xb6 | 0xb7 | 0xbe | 0xbf, ..]
|
||||
)
|
||||
);
|
||||
if operand_override {
|
||||
b0 = slice[pc];
|
||||
pc += 1;
|
||||
@@ -119,8 +167,6 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
|
||||
pc += 1;
|
||||
}
|
||||
|
||||
let mut is_dbt = false;
|
||||
let mut is_interp = false;
|
||||
let mut mnemonic = String::new();
|
||||
let mut notes = String::new();
|
||||
let mut successors: Vec<u32> = Vec::new();
|
||||
@@ -129,14 +175,10 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
|
||||
match op {
|
||||
0xF4 => {
|
||||
mnemonic = "hlt".to_string();
|
||||
is_dbt = true;
|
||||
is_interp = true;
|
||||
fall_through = false; // HLT terminates
|
||||
}
|
||||
0x90 => {
|
||||
mnemonic = "nop".to_string();
|
||||
is_dbt = true;
|
||||
is_interp = true;
|
||||
}
|
||||
0xCC => {
|
||||
mnemonic = "int3".to_string();
|
||||
@@ -146,15 +188,11 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
|
||||
}
|
||||
0xC3 => {
|
||||
mnemonic = "ret".to_string();
|
||||
is_dbt = true;
|
||||
is_interp = true;
|
||||
fall_through = false;
|
||||
}
|
||||
0xC7 => {
|
||||
if let Some(&modrm) = slice.get(pc) {
|
||||
pc += 1;
|
||||
let mode = modrm >> 6;
|
||||
let rm = modrm & 7;
|
||||
if modrm & 0x38 != 0 {
|
||||
mnemonic = format!("unsupported c7 extension (modrm 0x{modrm:02x})");
|
||||
notes = "unknown instruction boundary".into();
|
||||
@@ -174,14 +212,6 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
|
||||
)
|
||||
};
|
||||
mnemonic = format!("mov r/m{width}, {value} (modrm 0x{modrm:02x})");
|
||||
// The native C7 memory path always writes eight bytes and
|
||||
// does not apply segment bases or decode a SIB byte.
|
||||
is_dbt = mode == 3
|
||||
|| (mode == 0 && rm != 4 && rex_w && !matches!(slice[0], 0x64 | 0x65));
|
||||
is_dbt &= !operand_override;
|
||||
if !is_dbt {
|
||||
notes = "MOV immediate operand form lacks native semantics".into();
|
||||
}
|
||||
} else {
|
||||
pc = slice.len();
|
||||
fall_through = false;
|
||||
@@ -201,22 +231,16 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
|
||||
pc += 2;
|
||||
}
|
||||
mnemonic = "retn imm16".to_string();
|
||||
is_dbt = false;
|
||||
is_interp = false;
|
||||
notes = "near return with stack pop".to_string();
|
||||
fall_through = false;
|
||||
}
|
||||
0x50..=0x57 => {
|
||||
let r = op - 0x50;
|
||||
mnemonic = format!("push r{r}");
|
||||
is_dbt = true;
|
||||
is_interp = true;
|
||||
}
|
||||
0x58..=0x5F => {
|
||||
let r = op - 0x58;
|
||||
mnemonic = format!("pop r{r}");
|
||||
is_dbt = true;
|
||||
is_interp = true;
|
||||
}
|
||||
0x01 | 0x03 => {
|
||||
if pc < slice.len() {
|
||||
@@ -224,10 +248,7 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
|
||||
pc += 1;
|
||||
pc += modrm_extra_len(modrm, slice, pc);
|
||||
mnemonic = format!("add (modrm 0x{modrm:02x})");
|
||||
if (modrm >> 6) == 3 {
|
||||
is_dbt = true;
|
||||
is_interp = true;
|
||||
}
|
||||
if (modrm >> 6) == 3 {}
|
||||
}
|
||||
}
|
||||
0x29 | 0x2B => {
|
||||
@@ -236,10 +257,7 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
|
||||
pc += 1;
|
||||
pc += modrm_extra_len(modrm, slice, pc);
|
||||
mnemonic = format!("sub (modrm 0x{modrm:02x})");
|
||||
if (modrm >> 6) == 3 {
|
||||
is_dbt = true;
|
||||
is_interp = true;
|
||||
}
|
||||
if (modrm >> 6) == 3 {}
|
||||
}
|
||||
}
|
||||
0x31 | 0x33 => {
|
||||
@@ -248,10 +266,19 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
|
||||
pc += 1;
|
||||
pc += modrm_extra_len(modrm, slice, pc);
|
||||
mnemonic = format!("xor (modrm 0x{modrm:02x})");
|
||||
if (modrm >> 6) == 3 {
|
||||
is_dbt = true;
|
||||
is_interp = true;
|
||||
}
|
||||
if (modrm >> 6) == 3 {}
|
||||
}
|
||||
}
|
||||
// MOVSXD r, r/m32
|
||||
0x63 => {
|
||||
if let Some((modrm, end)) = modrm_operand(slice, pc) {
|
||||
pc = end;
|
||||
let width = if rex_w { 64 } else { 32 };
|
||||
mnemonic = format!("movsxd r{width}, r/m32 (modrm 0x{modrm:02x})");
|
||||
} else {
|
||||
pc = slice.len();
|
||||
mnemonic = "truncated movsxd".into();
|
||||
fall_through = false;
|
||||
}
|
||||
}
|
||||
0x83 => {
|
||||
@@ -261,10 +288,7 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
|
||||
pc += 2;
|
||||
let sub_op = (modrm >> 3) & 7;
|
||||
mnemonic = format!("imm8_group modrm=0x{modrm:02x} imm=0x{imm:02x}");
|
||||
if (modrm >> 6) == 3 && (sub_op == 0 || sub_op == 5 || sub_op == 7) {
|
||||
is_dbt = true;
|
||||
is_interp = true;
|
||||
}
|
||||
if (modrm >> 6) == 3 && (sub_op == 0 || sub_op == 5 || sub_op == 7) {}
|
||||
}
|
||||
}
|
||||
0x85 => {
|
||||
@@ -274,7 +298,6 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
|
||||
pc += 1;
|
||||
pc += modrm_extra_len(modrm, slice, pc);
|
||||
mnemonic = format!("test (modrm 0x{modrm:02x})");
|
||||
is_interp = true;
|
||||
}
|
||||
}
|
||||
0x89 | 0x8B => {
|
||||
@@ -285,8 +308,6 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
|
||||
let rm = modrm & 7;
|
||||
mnemonic = format!("mov (modrm 0x{modrm:02x})");
|
||||
if mode == 3 {
|
||||
is_dbt = true;
|
||||
is_interp = true;
|
||||
} else if rm == 4 {
|
||||
// SIB
|
||||
if pc < slice.len() {
|
||||
@@ -300,8 +321,6 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
|
||||
pc += 4; // disp32
|
||||
}
|
||||
mnemonic = format!("mov [SIB=0x{sib:02x}]");
|
||||
is_dbt = true;
|
||||
is_interp = true;
|
||||
}
|
||||
} else {
|
||||
if mode == 1 && pc < slice.len() {
|
||||
@@ -309,8 +328,6 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
|
||||
} else if (mode == 2 || (mode == 0 && rm == 5)) && pc + 4 <= slice.len() {
|
||||
pc += 4;
|
||||
}
|
||||
is_dbt = true;
|
||||
is_interp = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -319,8 +336,6 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
|
||||
if pc + imm_len <= slice.len() {
|
||||
pc += imm_len;
|
||||
mnemonic = format!("mov reg, imm{imm_len}");
|
||||
is_dbt = true;
|
||||
is_interp = true;
|
||||
}
|
||||
}
|
||||
// CALL rel32 — both call target and fall-through continuation are successors
|
||||
@@ -331,8 +346,6 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
|
||||
let insn_len = pc as i64;
|
||||
let target_va = (va as i64 + insn_len + rel32 as i64) as u64;
|
||||
mnemonic = format!("call rel32 -> 0x{target_va:016x}");
|
||||
is_dbt = true;
|
||||
is_interp = true;
|
||||
// Push call target as a CFG successor; fall-through (return site) continues.
|
||||
let call_rva = rva.wrapping_add(pc as u32).wrapping_add(rel32 as u32);
|
||||
successors.push(call_rva);
|
||||
@@ -347,8 +360,6 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
|
||||
let insn_len = pc as i64;
|
||||
let target_va = (va as i64 + insn_len + rel32 as i64) as u64;
|
||||
mnemonic = format!("jmp rel32 -> 0x{target_va:016x}");
|
||||
is_dbt = true;
|
||||
is_interp = true;
|
||||
let jmp_rva = rva.wrapping_add(pc as u32).wrapping_add(rel32 as u32);
|
||||
successors.push(jmp_rva);
|
||||
fall_through = false;
|
||||
@@ -362,8 +373,6 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
|
||||
let insn_len = pc as i64;
|
||||
let target_va = (va as i64 + insn_len + rel8 as i64) as u64;
|
||||
mnemonic = format!("jmp rel8 -> 0x{target_va:016x}");
|
||||
is_dbt = true;
|
||||
is_interp = true;
|
||||
let jmp_rva = (rva as i64 + insn_len + rel8 as i64) as u32;
|
||||
successors.push(jmp_rva);
|
||||
fall_through = false;
|
||||
@@ -377,8 +386,6 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
|
||||
let insn_len = pc as i64;
|
||||
let target_va = (va as i64 + insn_len + rel8 as i64) as u64;
|
||||
mnemonic = format!("j{:x} rel8 -> 0x{target_va:016x}", op & 0xF);
|
||||
is_dbt = true;
|
||||
is_interp = true;
|
||||
let jcc_rva = (rva as i64 + insn_len + rel8 as i64) as u32;
|
||||
successors.push(jcc_rva);
|
||||
// fall_through = true (not-taken path)
|
||||
@@ -398,13 +405,32 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
|
||||
let insn_len = pc as i64;
|
||||
let target_va = (va as i64 + insn_len + rel32 as i64) as u64;
|
||||
mnemonic = format!("j{:x} rel32 -> 0x{target_va:016x}", op2 & 0xF);
|
||||
is_dbt = true;
|
||||
is_interp = true;
|
||||
let jcc_rva = (rva as i64 + insn_len + rel32 as i64) as u32;
|
||||
successors.push(jcc_rva);
|
||||
// fall_through = true
|
||||
}
|
||||
}
|
||||
// MOVZX/MOVSX r, r/m8 or r/m16
|
||||
0xB6 | 0xB7 | 0xBE | 0xBF => {
|
||||
if let Some((modrm, end)) = modrm_operand(slice, pc) {
|
||||
pc = end;
|
||||
let name = if op2 < 0xB8 { "movzx" } else { "movsx" };
|
||||
let source = if op2 & 1 == 0 { 8 } else { 16 };
|
||||
let width = if rex_w {
|
||||
64
|
||||
} else if operand_override {
|
||||
16
|
||||
} else {
|
||||
32
|
||||
};
|
||||
mnemonic =
|
||||
format!("{name} r{width}, r/m{source} (modrm 0x{modrm:02x})");
|
||||
} else {
|
||||
pc = slice.len();
|
||||
mnemonic = "truncated extension".into();
|
||||
fall_through = false;
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
mnemonic = format!("0f_{op2:02x}");
|
||||
notes = "unsupported two-byte opcode".to_string();
|
||||
@@ -428,8 +454,6 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
|
||||
mnemonic = format!("call *[RIP + 0x{iat_target:016x}]");
|
||||
notes = "indirect IAT symbol call - requires dynamic import linking"
|
||||
.to_string();
|
||||
is_dbt = true;
|
||||
is_interp = true;
|
||||
// fall_through = true (return will come back here)
|
||||
} else {
|
||||
mnemonic = format!("jmp *[RIP + 0x{iat_target:016x}]");
|
||||
@@ -441,8 +465,6 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
|
||||
if reg_field == 2 {
|
||||
mnemonic = format!("call *r/m (modrm 0x{modrm:02x})");
|
||||
notes = "indirect call - target unknown".to_string();
|
||||
is_dbt = true;
|
||||
is_interp = true;
|
||||
} else {
|
||||
mnemonic = format!("jmp *r/m (modrm 0x{modrm:02x})");
|
||||
notes = "indirect jmp - target unknown statically".to_string();
|
||||
@@ -453,8 +475,6 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
|
||||
// PUSH r/m
|
||||
pc += modrm_extra_len(modrm, slice, pc);
|
||||
mnemonic = format!("push r/m (modrm 0x{modrm:02x})");
|
||||
is_dbt = true;
|
||||
is_interp = true;
|
||||
} else {
|
||||
pc += modrm_extra_len(modrm, slice, pc);
|
||||
mnemonic = format!("ff_group_r{reg_field} (modrm 0x{modrm:02x})");
|
||||
@@ -468,6 +488,51 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
|
||||
}
|
||||
}
|
||||
|
||||
// Architectural instruction-length enforcement: no decoded instruction
|
||||
// may exceed 15 bytes, whatever prefix or opcode path produced it.
|
||||
if pc > MAX_INSTRUCTION_LEN {
|
||||
return Some(CfgDecoded {
|
||||
rva,
|
||||
insn_len: MAX_INSTRUCTION_LEN,
|
||||
mnemonic: "overlong instruction".into(),
|
||||
is_dbt: false,
|
||||
is_interp: false,
|
||||
notes: "instruction length exceeds the 15-byte architectural limit".into(),
|
||||
successors: vec![],
|
||||
fall_through: false,
|
||||
});
|
||||
}
|
||||
|
||||
// The decoder both engines execute with decides support, length and static
|
||||
// control flow, so the report cannot claim a form they reject.
|
||||
let (is_dbt, is_interp) = match decode(va, |address| {
|
||||
slice
|
||||
.get(address.wrapping_sub(va) as usize)
|
||||
.copied()
|
||||
.ok_or(())
|
||||
}) {
|
||||
Ok(insn) => {
|
||||
pc = usize::from(insn.len);
|
||||
if mnemonic.is_empty() || mnemonic.contains("opcode_0x") || mnemonic.starts_with("0f_")
|
||||
{
|
||||
mnemonic = insn.op.name().to_string();
|
||||
notes.clear();
|
||||
}
|
||||
if !is_translatable(&insn) {
|
||||
notes = "raw guest system calls are not dispatched by the DBT".into();
|
||||
} else if !is_native(&insn) {
|
||||
notes = "executed by the shared semantics, not translated to ARM64".into();
|
||||
}
|
||||
let relative = insn.encoding == Encoding::Rel;
|
||||
if relative {
|
||||
successors = vec![insn.imm.wrapping_sub(va).wrapping_add(u64::from(rva)) as u32];
|
||||
}
|
||||
fall_through = !matches!(insn.op, Op::Jmp | Op::Ret | Op::Hlt);
|
||||
(is_translatable(&insn), true)
|
||||
}
|
||||
Err(_) => (false, false),
|
||||
};
|
||||
|
||||
Some(CfgDecoded {
|
||||
rva,
|
||||
insn_len: pc,
|
||||
@@ -607,7 +672,10 @@ pub struct ProbeReport {
|
||||
pub parsed: ParsedPe,
|
||||
pub relocations: RelocationCensus,
|
||||
pub tls: TlsCensus,
|
||||
/// Imports before the first malformed entry, if any.
|
||||
pub imports: Vec<ImportedSymbol>,
|
||||
/// Why the import table could not be read to its end.
|
||||
pub import_error: Option<ImportTableError>,
|
||||
pub instruction_records: Vec<InstructionRecord>,
|
||||
pub first_unsupported_dbt_insn: Option<InstructionRecord>,
|
||||
}
|
||||
@@ -791,12 +859,21 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
|
||||
});
|
||||
}
|
||||
|
||||
// Map an RVA to a file offset.
|
||||
//
|
||||
// The offset is derived from the section header, so on a truncated file it
|
||||
// can point past the end of the buffer. Such an offset is not readable, so
|
||||
// it is reported as unmapped rather than returned and sliced later.
|
||||
let rva_to_offset = |rva: u32| -> Option<usize> {
|
||||
for sec in §ions {
|
||||
let max_span = std::cmp::max(sec.virtual_size, sec.raw_data_size);
|
||||
if rva >= sec.virtual_address && rva < sec.virtual_address.saturating_add(max_span) {
|
||||
let off_in_sec = (rva - sec.virtual_address) as usize;
|
||||
return Some(sec.raw_data_ptr as usize + off_in_sec);
|
||||
let off = sec.raw_data_ptr as usize + off_in_sec;
|
||||
if off >= bytes.len() {
|
||||
return None;
|
||||
}
|
||||
return Some(off);
|
||||
}
|
||||
}
|
||||
None
|
||||
@@ -881,76 +958,33 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
|
||||
&mut registry,
|
||||
Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))),
|
||||
);
|
||||
let mut imports = Vec::new();
|
||||
if import_dir_rva != 0
|
||||
&& let Some(mut desc_off) = rva_to_offset(import_dir_rva)
|
||||
{
|
||||
while desc_off + 20 <= bytes.len() {
|
||||
let oft = u32::from_le_bytes(bytes[desc_off..desc_off + 4].try_into().unwrap());
|
||||
let name_rva =
|
||||
u32::from_le_bytes(bytes[desc_off + 12..desc_off + 16].try_into().unwrap());
|
||||
let ft = u32::from_le_bytes(bytes[desc_off + 16..desc_off + 20].try_into().unwrap());
|
||||
if oft == 0 && name_rva == 0 && ft == 0 {
|
||||
break;
|
||||
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))?
|
||||
})
|
||||
})
|
||||
};
|
||||
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()),
|
||||
}
|
||||
desc_off += 20;
|
||||
|
||||
let dll_name = if let Some(no) = rva_to_offset(name_rva) {
|
||||
let mut end = no;
|
||||
while end < bytes.len() && bytes[end] != 0 {
|
||||
end += 1;
|
||||
}
|
||||
String::from_utf8_lossy(&bytes[no..end]).into_owned()
|
||||
} else {
|
||||
"UNKNOWN.dll".to_string()
|
||||
};
|
||||
|
||||
let category = ProbeReport::categorize_dll(&dll_name);
|
||||
let thunk_rva = if oft != 0 { oft } else { ft };
|
||||
let iat_base_rva = ft;
|
||||
|
||||
if let Some(mut thunk_off) = rva_to_offset(thunk_rva) {
|
||||
let mut idx = 0u32;
|
||||
while thunk_off + 8 <= bytes.len() {
|
||||
let val =
|
||||
u64::from_le_bytes(bytes[thunk_off..thunk_off + 8].try_into().unwrap());
|
||||
if val == 0 {
|
||||
break;
|
||||
}
|
||||
thunk_off += 8;
|
||||
let iat_rva = iat_base_rva + idx * 8;
|
||||
idx += 1;
|
||||
|
||||
let sym_name = if (val & (1 << 63)) != 0 {
|
||||
format!("Ordinal#{}", val & 0xFFFF)
|
||||
} else {
|
||||
let hint_rva = (val & 0x7FFF_FFFF) as u32;
|
||||
if let Some(ho) = rva_to_offset(hint_rva) {
|
||||
let str_start = ho + 2;
|
||||
let mut str_end = str_start;
|
||||
while str_end < bytes.len() && bytes[str_end] != 0 {
|
||||
str_end += 1;
|
||||
}
|
||||
String::from_utf8_lossy(&bytes[str_start..str_end]).into_owned()
|
||||
} else {
|
||||
"UNKNOWN_SYM".to_string()
|
||||
}
|
||||
};
|
||||
|
||||
let binding = registry.binding(&dll_name, &sym_name);
|
||||
imports.push(ImportedSymbol {
|
||||
dll: dll_name.clone(),
|
||||
symbol: sym_name,
|
||||
iat_rva,
|
||||
category,
|
||||
is_supported: binding.is_some(),
|
||||
service_status: binding.map(|service| service.status),
|
||||
canonical_module: binding.map(|service| service.module.clone()),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
// 4. Control-Flow-Aware Static Disassembly
|
||||
//
|
||||
@@ -1085,6 +1119,7 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
|
||||
relocations,
|
||||
tls,
|
||||
imports,
|
||||
import_error,
|
||||
instruction_records,
|
||||
first_unsupported_dbt_insn,
|
||||
})
|
||||
@@ -1337,6 +1372,12 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
|
||||
"- **Unresolved standard import thunks**: `{missing}`. See `missing_imports.csv`. A registered handler may be a stub.\n"
|
||||
);
|
||||
|
||||
if let Some(error) = &report.import_error {
|
||||
let _ = writeln!(
|
||||
md,
|
||||
"- **Import table is malformed**: {error}. Only the imports before it are listed, and binding refuses the image.\n"
|
||||
);
|
||||
}
|
||||
if trusted_runner_slots > 0 {
|
||||
let _ = writeln!(
|
||||
md,
|
||||
|
||||
@@ -117,7 +117,10 @@ pub fn apply_relocations(
|
||||
size: reloc_size,
|
||||
})?;
|
||||
|
||||
if reloc_file_offset + (reloc_size as usize) > bytes.len() {
|
||||
if reloc_file_offset
|
||||
.checked_add(reloc_size as usize)
|
||||
.is_none_or(|end| end > bytes.len())
|
||||
{
|
||||
return Err(RelocationError::DirectoryOutOfBounds {
|
||||
rva: reloc_rva,
|
||||
size: reloc_size,
|
||||
@@ -127,13 +130,20 @@ pub fn apply_relocations(
|
||||
let mut read_bytes = 0usize;
|
||||
let max_read = reloc_size as usize;
|
||||
|
||||
while read_bytes + 8 <= max_read {
|
||||
while read_bytes < max_read {
|
||||
// A partial block header after the last block is malformed, not padding.
|
||||
if max_read - read_bytes < 8 {
|
||||
return Err(RelocationError::MalformedBlockHeader {
|
||||
offset: reloc_file_offset + read_bytes,
|
||||
});
|
||||
}
|
||||
let block_start = reloc_file_offset + read_bytes;
|
||||
let page_rva = u32::from_le_bytes(bytes[block_start..block_start + 4].try_into().unwrap());
|
||||
let block_size =
|
||||
u32::from_le_bytes(bytes[block_start + 4..block_start + 8].try_into().unwrap());
|
||||
|
||||
if block_size < 8 {
|
||||
// A block is an 8-byte header followed by whole 2-byte entries.
|
||||
if block_size < 8 || block_size % 2 != 0 {
|
||||
return Err(RelocationError::MalformedBlockHeader {
|
||||
offset: block_start,
|
||||
});
|
||||
@@ -166,6 +176,15 @@ pub fn apply_relocations(
|
||||
let target_rva = page_rva
|
||||
.checked_add(offset_in_page)
|
||||
.ok_or(RelocationError::ArithmeticOverflow)?;
|
||||
// The 8-byte target must lie inside the image, not in other mapped memory.
|
||||
if target_rva
|
||||
.checked_add(8)
|
||||
.is_none_or(|end| end > pe.size_of_image)
|
||||
{
|
||||
return Err(RelocationError::TargetOutOfBounds {
|
||||
target_va: loaded_base.wrapping_add(u64::from(target_rva)),
|
||||
});
|
||||
}
|
||||
let target_va = loaded_base
|
||||
.checked_add(target_rva as u64)
|
||||
.ok_or(RelocationError::ArithmeticOverflow)?;
|
||||
@@ -213,8 +232,8 @@ fn find_reloc_directory(
|
||||
return Ok(None);
|
||||
}
|
||||
let e_lfanew = u32::from_le_bytes(bytes[0x3C..0x40].try_into().unwrap()) as usize;
|
||||
let opt_offset = e_lfanew + 24;
|
||||
let coff_offset = e_lfanew + 4;
|
||||
let opt_offset = coff_offset + 20;
|
||||
if bytes.len() < coff_offset + 18 {
|
||||
return Ok(None);
|
||||
}
|
||||
@@ -224,10 +243,19 @@ fn find_reloc_directory(
|
||||
.unwrap(),
|
||||
) as usize;
|
||||
|
||||
// Relocation directory is directory index 5 (offset 112 + 5 * 8 = 152 in Optional Header)
|
||||
// Relocation directory is directory index 5 (offset 112 + 5 * 8 = 152 in Optional Header).
|
||||
// It exists only when NumberOfRvaAndSizes (offset 108) covers index 5.
|
||||
if size_of_opt < 160 || bytes.len() < opt_offset + 160 {
|
||||
return Ok(None);
|
||||
}
|
||||
let number_of_rva_and_sizes = u32::from_le_bytes(
|
||||
bytes[opt_offset + 108..opt_offset + 112]
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
);
|
||||
if number_of_rva_and_sizes < 6 {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let reloc_rva = u32::from_le_bytes(
|
||||
bytes[opt_offset + 152..opt_offset + 156]
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Typed Win64 adapters for generated service registrations.
|
||||
//!
|
||||
//! `runtime_table.rs` is generated from `runtime/services.txt`. Each adapter
|
||||
//! reads typed arguments by position (Microsoft x64 calling convention), calls a
|
||||
//! handler that sees only guest memory and service state, and places the typed
|
||||
//! result. Handlers never receive the CPU, so they cannot disturb nonvolatile
|
||||
//! registers.
|
||||
|
||||
use crate::cpu::{CpuState, ExitReason};
|
||||
use crate::imports::{ServiceStatus, Win64Args};
|
||||
use crate::memory::{GuestMemory, MemoryError};
|
||||
use crate::services::ServicesState;
|
||||
|
||||
/// What a service may use.
|
||||
pub struct ServiceContext<'a> {
|
||||
pub state: &'a ServicesState,
|
||||
pub memory: &'a mut GuestMemory,
|
||||
}
|
||||
|
||||
/// Guest pointer to `N` bytes the service writes.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct OutPtr<const N: usize>(pub u64);
|
||||
|
||||
impl<const N: usize> OutPtr<N> {
|
||||
/// Checked, all-or-nothing store.
|
||||
pub fn store(self, memory: &mut GuestMemory, bytes: [u8; N]) -> Result<(), MemoryError> {
|
||||
memory.write_bytes(self.0, &bytes)
|
||||
}
|
||||
}
|
||||
|
||||
/// Raw bits of a floating-point argument or result.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Float32(pub u32);
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Float64(pub u64);
|
||||
|
||||
/// Reads typed arguments. Only the low bits of a narrow argument are defined.
|
||||
pub struct Call<'a> {
|
||||
args: &'a Win64Args,
|
||||
cpu: &'a CpuState,
|
||||
memory: &'a GuestMemory,
|
||||
}
|
||||
|
||||
impl<'a> Call<'a> {
|
||||
pub fn new(args: &'a Win64Args, cpu: &'a CpuState, memory: &'a GuestMemory) -> Self {
|
||||
Self { args, cpu, memory }
|
||||
}
|
||||
|
||||
pub fn u64(&self, index: usize) -> Result<u64, ExitReason> {
|
||||
self.args
|
||||
.get(index, self.memory)
|
||||
.map_err(ExitReason::MemoryFault)
|
||||
}
|
||||
|
||||
pub fn u32(&self, index: usize) -> Result<u32, ExitReason> {
|
||||
Ok(self.u64(index)? as u32)
|
||||
}
|
||||
|
||||
pub fn i32(&self, index: usize) -> Result<i32, ExitReason> {
|
||||
Ok(self.u32(index)? as i32)
|
||||
}
|
||||
|
||||
pub fn bool32(&self, index: usize) -> Result<bool, ExitReason> {
|
||||
Ok(self.u32(index)? != 0)
|
||||
}
|
||||
|
||||
pub fn out<const N: usize>(&self, index: usize) -> Result<OutPtr<N>, ExitReason> {
|
||||
self.u64(index).map(OutPtr)
|
||||
}
|
||||
|
||||
/// The first four positions use XMM0-XMM3; later ones use the stack.
|
||||
fn float_bits(&self, index: usize) -> Result<u64, ExitReason> {
|
||||
if index < 4 {
|
||||
Ok(self.cpu.xmm[index] as u64)
|
||||
} else {
|
||||
self.u64(index)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn f32(&self, index: usize) -> Result<Float32, ExitReason> {
|
||||
Ok(Float32(self.float_bits(index)? as u32))
|
||||
}
|
||||
|
||||
pub fn f64(&self, index: usize) -> Result<Float64, ExitReason> {
|
||||
self.float_bits(index).map(Float64)
|
||||
}
|
||||
}
|
||||
|
||||
/// Places a typed result and returns the value for RAX.
|
||||
pub trait Return {
|
||||
fn place(self, cpu: &mut CpuState) -> u64;
|
||||
}
|
||||
|
||||
impl Return for u32 {
|
||||
fn place(self, _: &mut CpuState) -> u64 {
|
||||
u64::from(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl Return for i32 {
|
||||
fn place(self, _: &mut CpuState) -> u64 {
|
||||
u64::from(self as u32)
|
||||
}
|
||||
}
|
||||
|
||||
impl Return for u64 {
|
||||
fn place(self, _: &mut CpuState) -> u64 {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Return for bool {
|
||||
fn place(self, _: &mut CpuState) -> u64 {
|
||||
u64::from(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl Return for Float32 {
|
||||
fn place(self, cpu: &mut CpuState) -> u64 {
|
||||
cpu.xmm[0] = u128::from(self.0);
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
impl Return for Float64 {
|
||||
fn place(self, cpu: &mut CpuState) -> u64 {
|
||||
cpu.xmm[0] = u128::from(self.0);
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
/// A declared parameter.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Parameter {
|
||||
pub name: &'static str,
|
||||
pub kind: &'static str,
|
||||
}
|
||||
|
||||
/// Static description of a generated service.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct ServiceMetadata {
|
||||
pub library: &'static str,
|
||||
pub symbol: &'static str,
|
||||
pub parameters: &'static [Parameter],
|
||||
pub result: &'static str,
|
||||
pub status: ServiceStatus,
|
||||
/// API sets that resolve to this service.
|
||||
pub aliases: &'static [&'static str],
|
||||
pub failure: &'static str,
|
||||
pub reference: &'static str,
|
||||
pub tests: &'static [&'static str],
|
||||
}
|
||||
@@ -0,0 +1,408 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
// Generated by xenora-runtime-gen from crates/loader/runtime/services.txt.
|
||||
// Do not edit.
|
||||
|
||||
use crate::imports::{ImportRegistry, ServiceStatus};
|
||||
use crate::runtime::{Call, Parameter, Return, ServiceContext, ServiceMetadata};
|
||||
use crate::services::{ServicesState, handlers};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub static SERVICES: [ServiceMetadata; 20] = [
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "SetProcessPriorityBoost",
|
||||
parameters: &[Parameter { name: "process", kind: "handle" }, Parameter { name: "disable", kind: "bool32" }],
|
||||
result: "bool32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-core-processthreads-l1-1-2.dll"],
|
||||
failure: "0 with ERROR_INVALID_HANDLE",
|
||||
reference: "processthreadsapi.h SetProcessPriorityBoost",
|
||||
tests: &["priority_boost_round_trips_and_checks_its_handle"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "GetProcessPriorityBoost",
|
||||
parameters: &[Parameter { name: "process", kind: "handle" }, Parameter { name: "disabled", kind: "out<4>" }],
|
||||
result: "bool32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-core-processthreads-l1-1-2.dll"],
|
||||
failure: "0 with ERROR_INVALID_HANDLE or ERROR_NOACCESS",
|
||||
reference: "processthreadsapi.h GetProcessPriorityBoost",
|
||||
tests: &["priority_boost_round_trips_and_checks_its_handle"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "GetCurrentProcess",
|
||||
parameters: &[],
|
||||
result: "handle",
|
||||
status: ServiceStatus::Implemented,
|
||||
aliases: &["api-ms-win-core-processthreads-l1-1-0.dll"],
|
||||
failure: "never",
|
||||
reference: "processthreadsapi.h GetCurrentProcess",
|
||||
tests: &["identity_services_return_documented_pseudo_handles_and_ids"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "GetProcessId",
|
||||
parameters: &[Parameter { name: "process", kind: "handle" }],
|
||||
result: "u32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-core-processthreads-l1-1-0.dll"],
|
||||
failure: "0 with ERROR_INVALID_HANDLE",
|
||||
reference: "processthreadsapi.h GetProcessId",
|
||||
tests: &["identity_services_return_documented_pseudo_handles_and_ids"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "GetCurrentThread",
|
||||
parameters: &[],
|
||||
result: "handle",
|
||||
status: ServiceStatus::Implemented,
|
||||
aliases: &["api-ms-win-core-processthreads-l1-1-0.dll"],
|
||||
failure: "never",
|
||||
reference: "processthreadsapi.h GetCurrentThread",
|
||||
tests: &["identity_services_return_documented_pseudo_handles_and_ids"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "GetCurrentProcessId",
|
||||
parameters: &[],
|
||||
result: "u32",
|
||||
status: ServiceStatus::Implemented,
|
||||
aliases: &["api-ms-win-core-processthreads-l1-1-0.dll"],
|
||||
failure: "never",
|
||||
reference: "processthreadsapi.h GetCurrentProcessId",
|
||||
tests: &["identity_services_return_documented_pseudo_handles_and_ids"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "GetCurrentThreadId",
|
||||
parameters: &[],
|
||||
result: "u32",
|
||||
status: ServiceStatus::Implemented,
|
||||
aliases: &["api-ms-win-core-processthreads-l1-1-0.dll"],
|
||||
failure: "never",
|
||||
reference: "processthreadsapi.h GetCurrentThreadId",
|
||||
tests: &["identity_services_return_documented_pseudo_handles_and_ids"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "OpenThread",
|
||||
parameters: &[Parameter { name: "access", kind: "u32" }, Parameter { name: "inherit", kind: "bool32" }, Parameter { name: "thread", kind: "u32" }],
|
||||
result: "handle",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-core-processthreads-l1-1-0.dll"],
|
||||
failure: "0 with ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED or ERROR_NOT_ENOUGH_MEMORY",
|
||||
reference: "processthreadsapi.h OpenThread",
|
||||
tests: &["thread_handles_check_access_and_are_rejected_once_closed"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "GetThreadPriority",
|
||||
parameters: &[Parameter { name: "thread", kind: "handle" }],
|
||||
result: "i32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-core-processthreads-l1-1-0.dll"],
|
||||
failure: "THREAD_PRIORITY_ERROR_RETURN with ERROR_INVALID_HANDLE or ERROR_ACCESS_DENIED",
|
||||
reference: "processthreadsapi.h GetThreadPriority",
|
||||
tests: &["thread_handles_check_access_and_are_rejected_once_closed"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "SetThreadPriority",
|
||||
parameters: &[Parameter { name: "thread", kind: "handle" }, Parameter { name: "priority", kind: "i32" }],
|
||||
result: "bool32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-core-processthreads-l1-1-0.dll"],
|
||||
failure: "0 with ERROR_INVALID_HANDLE, ERROR_ACCESS_DENIED, ERROR_NOT_SUPPORTED or ERROR_INVALID_PARAMETER",
|
||||
reference: "processthreadsapi.h SetThreadPriority",
|
||||
tests: &["thread_handles_check_access_and_are_rejected_once_closed"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "CloseHandle",
|
||||
parameters: &[Parameter { name: "object", kind: "handle" }],
|
||||
result: "bool32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-core-handle-l1-1-0.dll"],
|
||||
failure: "0 with ERROR_INVALID_HANDLE",
|
||||
reference: "handleapi.h CloseHandle",
|
||||
tests: &["thread_handles_check_access_and_are_rejected_once_closed"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "GetSystemTimeAsFileTime",
|
||||
parameters: &[Parameter { name: "time", kind: "out<8>" }],
|
||||
result: "void",
|
||||
status: ServiceStatus::Implemented,
|
||||
aliases: &["api-ms-win-core-sysinfo-l1-1-0.dll"],
|
||||
failure: "guest fault on an invalid pointer",
|
||||
reference: "sysinfoapi.h GetSystemTimeAsFileTime",
|
||||
tests: &["system_time_comes_from_the_injected_clock"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "GetLastError",
|
||||
parameters: &[],
|
||||
result: "u32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-core-errorhandling-l1-1-0.dll"],
|
||||
failure: "never",
|
||||
reference: "errhandlingapi.h GetLastError",
|
||||
tests: &["last_error_is_set_by_failures_and_by_the_guest"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "SetLastError",
|
||||
parameters: &[Parameter { name: "code", kind: "u32" }],
|
||||
result: "void",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-core-errorhandling-l1-1-0.dll"],
|
||||
failure: "never",
|
||||
reference: "errhandlingapi.h SetLastError",
|
||||
tests: &["last_error_is_set_by_failures_and_by_the_guest"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "VirtualAlloc",
|
||||
parameters: &[Parameter { name: "address", kind: "ptr" }, Parameter { name: "size", kind: "u64" }, Parameter { name: "kind", kind: "u32" }, Parameter { name: "protect", kind: "u32" }],
|
||||
result: "ptr",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-core-memory-l1-1-0.dll"],
|
||||
failure: "0 with ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED, ERROR_INVALID_ADDRESS or ERROR_NOT_ENOUGH_MEMORY",
|
||||
reference: "memoryapi.h VirtualAlloc",
|
||||
tests: &["virtual_memory_is_mapped_released_and_bounded"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "kernel32.dll",
|
||||
symbol: "VirtualFree",
|
||||
parameters: &[Parameter { name: "address", kind: "ptr" }, Parameter { name: "size", kind: "u64" }, Parameter { name: "kind", kind: "u32" }],
|
||||
result: "bool32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-core-memory-l1-1-0.dll"],
|
||||
failure: "0 with ERROR_NOT_SUPPORTED, ERROR_INVALID_PARAMETER or ERROR_INVALID_ADDRESS",
|
||||
reference: "memoryapi.h VirtualFree",
|
||||
tests: &["virtual_memory_is_mapped_released_and_bounded"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "sqrt",
|
||||
parameters: &[Parameter { name: "x", kind: "f64" }],
|
||||
result: "f64",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-math-l1-1-0.dll"],
|
||||
failure: "NaN for a negative argument; errno is not set",
|
||||
reference: "math.h sqrt (ISO C, IEC 60559 squareRoot)",
|
||||
tests: &["floating_arguments_and_results_use_xmm_registers"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "sqrtf",
|
||||
parameters: &[Parameter { name: "x", kind: "f32" }],
|
||||
result: "f32",
|
||||
status: ServiceStatus::Partial,
|
||||
aliases: &["api-ms-win-crt-math-l1-1-0.dll"],
|
||||
failure: "NaN for a negative argument; errno is not set",
|
||||
reference: "math.h sqrtf (ISO C, IEC 60559 squareRoot)",
|
||||
tests: &["floating_arguments_and_results_use_xmm_registers"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "fabs",
|
||||
parameters: &[Parameter { name: "x", kind: "f64" }],
|
||||
result: "f64",
|
||||
status: ServiceStatus::Implemented,
|
||||
aliases: &["api-ms-win-crt-math-l1-1-0.dll"],
|
||||
failure: "never",
|
||||
reference: "math.h fabs (ISO C, IEC 60559 abs)",
|
||||
tests: &["floating_arguments_and_results_use_xmm_registers"],
|
||||
},
|
||||
ServiceMetadata {
|
||||
library: "ucrtbase.dll",
|
||||
symbol: "fabsf",
|
||||
parameters: &[Parameter { name: "x", kind: "f32" }],
|
||||
result: "f32",
|
||||
status: ServiceStatus::Implemented,
|
||||
aliases: &["api-ms-win-crt-math-l1-1-0.dll"],
|
||||
failure: "never",
|
||||
reference: "math.h fabsf (ISO C, IEC 60559 abs)",
|
||||
tests: &["floating_arguments_and_results_use_xmm_registers"],
|
||||
},
|
||||
];
|
||||
|
||||
/// Register every generated service and its API-set aliases.
|
||||
pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
|
||||
let s = state.clone();
|
||||
registry.register_with_status("kernel32.dll", "SetProcessPriorityBoost", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
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 result: bool = handlers::set_process_priority_boost(&mut context, a0, a1)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("kernel32.dll", "GetProcessPriorityBoost", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
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 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 result: u64 = handlers::get_current_process(&mut context)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
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 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 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 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 result: u32 = handlers::get_current_thread_id(&mut context)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("kernel32.dll", "OpenThread", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u32(0)?;
|
||||
let a1 = call.bool32(1)?;
|
||||
let a2 = call.u32(2)?;
|
||||
let mut context = ServiceContext { state: &s, memory };
|
||||
let result: u64 = handlers::open_thread(&mut context, a0, a1, a2)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
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 result: i32 = handlers::get_thread_priority(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("kernel32.dll", "SetThreadPriority", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
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 result: bool = handlers::set_thread_priority(&mut context, a0, a1)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
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 result: bool = handlers::close_handle(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
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 () = 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 result: u32 = handlers::get_last_error(&mut context)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
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 () = handlers::set_last_error(&mut context, a0)?;
|
||||
Ok(0)
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("kernel32.dll", "VirtualAlloc", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let a1 = call.u64(1)?;
|
||||
let a2 = call.u32(2)?;
|
||||
let a3 = call.u32(3)?;
|
||||
let mut context = ServiceContext { state: &s, memory };
|
||||
let result: u64 = handlers::virtual_alloc(&mut context, a0, a1, a2, a3)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
registry.register_with_status("kernel32.dll", "VirtualFree", ServiceStatus::Partial, move |args, cpu, memory| {
|
||||
let call = Call::new(args, cpu, memory);
|
||||
let a0 = call.u64(0)?;
|
||||
let a1 = call.u64(1)?;
|
||||
let a2 = call.u32(2)?;
|
||||
let mut context = ServiceContext { state: &s, memory };
|
||||
let result: bool = handlers::virtual_free(&mut context, a0, a1, a2)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
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 result: crate::runtime::Float64 = handlers::sqrt(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
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 result: crate::runtime::Float32 = handlers::sqrtf(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
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 result: crate::runtime::Float64 = handlers::fabs(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
let s = state.clone();
|
||||
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 result: crate::runtime::Float32 = handlers::fabsf(&mut context, a0)?;
|
||||
Ok(result.place(cpu))
|
||||
});
|
||||
for service in &SERVICES {
|
||||
for alias in service.aliases {
|
||||
if let Err(error) = registry.try_alias(alias, service.library, service.symbol) {
|
||||
panic!("{error}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+247
-262
@@ -33,9 +33,6 @@ 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 PROCESS_THREADS_V1: &str = "api-ms-win-core-processthreads-l1-1-0.dll";
|
||||
const PROCESS_THREADS_V2: &str = "api-ms-win-core-processthreads-l1-1-2.dll";
|
||||
|
||||
/// Clock trait for injecting deterministic time in tests or host time in production.
|
||||
pub trait Clock: Send + Sync {
|
||||
@@ -136,9 +133,10 @@ impl ServicesState {
|
||||
self.priority_boost_disabled.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
fn fail(&self, error: u32, return_value: u64) -> Result<u64, ExitReason> {
|
||||
/// 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);
|
||||
Ok(return_value)
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn is_current_process(&self, handle: u64) -> bool {
|
||||
@@ -151,264 +149,10 @@ impl ServicesState {
|
||||
}
|
||||
}
|
||||
|
||||
/// Register standard Windows core and Xbox memory services into the registry.
|
||||
/// Register the services generated from `runtime/services.txt` and the
|
||||
/// hand-written fixture services.
|
||||
pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc<ServicesState>) {
|
||||
let s = state.clone();
|
||||
registry.register(KERNEL32, "SetProcessPriorityBoost", move |args, _, mem| {
|
||||
if !s.is_current_process(args.get(0, mem).map_err(ExitReason::MemoryFault)?) {
|
||||
return Ok(0);
|
||||
}
|
||||
let disable = args.get(1, mem).map_err(ExitReason::MemoryFault)? as u32;
|
||||
s.priority_boost_disabled
|
||||
.store(disable != 0, Ordering::SeqCst);
|
||||
Ok(1)
|
||||
});
|
||||
registry.alias(PROCESS_THREADS_V2, KERNEL32, "SetProcessPriorityBoost");
|
||||
|
||||
registry.set_status(KERNEL32, "SetProcessPriorityBoost", ServiceStatus::Partial);
|
||||
|
||||
let s = state.clone();
|
||||
registry.register(KERNEL32, "GetProcessPriorityBoost", move |args, _, mem| {
|
||||
if !s.is_current_process(args.get(0, mem).map_err(ExitReason::MemoryFault)?) {
|
||||
return Ok(0);
|
||||
}
|
||||
let output = args.get(1, mem).map_err(ExitReason::MemoryFault)?;
|
||||
if mem
|
||||
.write_u32(output, u32::from(s.priority_boost_disabled()))
|
||||
.is_err()
|
||||
{
|
||||
s.last_error.store(ERROR_NOACCESS, Ordering::SeqCst);
|
||||
return Ok(0);
|
||||
}
|
||||
Ok(1)
|
||||
});
|
||||
registry.alias(PROCESS_THREADS_V2, KERNEL32, "GetProcessPriorityBoost");
|
||||
registry.set_status(KERNEL32, "GetProcessPriorityBoost", ServiceStatus::Partial);
|
||||
|
||||
registry.register(KERNEL32, "GetCurrentProcess", |_, _, _| Ok(CURRENT_PROCESS));
|
||||
registry.alias(PROCESS_THREADS_V1, KERNEL32, "GetCurrentProcess");
|
||||
|
||||
let s = state.clone();
|
||||
registry.register(KERNEL32, "GetProcessId", move |args, _, mem| {
|
||||
if !s.is_current_process(args.get(0, mem).map_err(ExitReason::MemoryFault)?) {
|
||||
return Ok(0);
|
||||
}
|
||||
Ok(u64::from(s.process_id))
|
||||
});
|
||||
registry.alias(PROCESS_THREADS_V1, KERNEL32, "GetProcessId");
|
||||
registry.set_status(KERNEL32, "GetProcessId", ServiceStatus::Partial);
|
||||
|
||||
registry.register(KERNEL32, "GetCurrentThread", |_, _, _| Ok(CURRENT_THREAD));
|
||||
registry.alias(PROCESS_THREADS_V1, KERNEL32, "GetCurrentThread");
|
||||
|
||||
let s = state.clone();
|
||||
registry.register(KERNEL32, "OpenThread", move |args, _, mem| {
|
||||
let access = args.get(0, mem).map_err(ExitReason::MemoryFault)? as u32;
|
||||
let inherit = args.get(1, mem).map_err(ExitReason::MemoryFault)? as u32;
|
||||
let id = args.get(2, mem).map_err(ExitReason::MemoryFault)? as u32;
|
||||
if id != s.thread_id {
|
||||
return s.fail(ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
if inherit != 0 || access & !THREAD_SUPPORTED_RIGHTS != 0 {
|
||||
return s.fail(ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
let mut thread = s.thread.lock().expect("guest thread state");
|
||||
let Some(handle) = thread
|
||||
.last_handle
|
||||
.checked_add(4)
|
||||
.filter(|_| thread.handles.len() < MAX_THREAD_HANDLES)
|
||||
else {
|
||||
return s.fail(ERROR_NOT_ENOUGH_MEMORY, 0);
|
||||
};
|
||||
thread.handles.insert(handle, access);
|
||||
thread.last_handle = handle;
|
||||
Ok(handle)
|
||||
});
|
||||
|
||||
let s = state.clone();
|
||||
registry.register(KERNEL32, "GetThreadPriority", move |args, _, mem| {
|
||||
let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
let thread = s.thread.lock().expect("guest thread state");
|
||||
if let Err(error) = thread.check_access(handle, THREAD_QUERY_RIGHTS) {
|
||||
return s.fail(error, THREAD_PRIORITY_ERROR_RETURN);
|
||||
}
|
||||
Ok(u64::from(thread.priority as u32))
|
||||
});
|
||||
|
||||
let s = state.clone();
|
||||
registry.register(KERNEL32, "SetThreadPriority", move |args, _, mem| {
|
||||
let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
let priority = args.get(1, mem).map_err(ExitReason::MemoryFault)? as i32;
|
||||
let mut thread = s.thread.lock().expect("guest thread state");
|
||||
if let Err(error) = thread.check_access(handle, THREAD_SET_RIGHTS) {
|
||||
return s.fail(error, 0);
|
||||
}
|
||||
if matches!(priority, 0x0001_0000 | 0x0002_0000) {
|
||||
return s.fail(ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
if !matches!(priority, -15 | -2..=2 | 15) {
|
||||
return s.fail(ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
thread.priority = priority;
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
for symbol in ["OpenThread", "GetThreadPriority", "SetThreadPriority"] {
|
||||
registry.alias(PROCESS_THREADS_V1, KERNEL32, symbol);
|
||||
registry.set_status(KERNEL32, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
|
||||
let s = state.clone();
|
||||
registry.register(KERNEL32, "CloseHandle", move |args, _, mem| {
|
||||
let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
if matches!(handle, CURRENT_PROCESS | CURRENT_THREAD)
|
||||
|| s.thread
|
||||
.lock()
|
||||
.expect("guest thread state")
|
||||
.handles
|
||||
.remove(&handle)
|
||||
.is_some()
|
||||
{
|
||||
return Ok(1);
|
||||
}
|
||||
s.fail(ERROR_INVALID_HANDLE, 0)
|
||||
});
|
||||
registry.alias("api-ms-win-core-handle-l1-1-0.dll", KERNEL32, "CloseHandle");
|
||||
registry.set_status(KERNEL32, "CloseHandle", ServiceStatus::Partial);
|
||||
|
||||
// 1. GetSystemTimeAsFileTime(lpSystemTimeAsFileTime: *mut FILETIME)
|
||||
let s = state.clone();
|
||||
let handler = move |args: &crate::imports::Win64Args,
|
||||
_cpu: &mut crate::cpu::CpuState,
|
||||
mem: &mut GuestMemory|
|
||||
-> Result<u64, ExitReason> {
|
||||
let ptr = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
if ptr == 0 {
|
||||
s.last_error.store(87, Ordering::SeqCst); // ERROR_INVALID_PARAMETER
|
||||
return Ok(0);
|
||||
}
|
||||
let ft = s.clock.now_filetime();
|
||||
mem.write_u64(ptr, ft).map_err(ExitReason::MemoryFault)?;
|
||||
Ok(0)
|
||||
};
|
||||
registry.register(KERNEL32, "GetSystemTimeAsFileTime", handler);
|
||||
registry.alias(
|
||||
"api-ms-win-core-sysinfo-l1-1-0.dll",
|
||||
KERNEL32,
|
||||
"GetSystemTimeAsFileTime",
|
||||
);
|
||||
|
||||
// 2. GetCurrentProcessId() -> DWORD
|
||||
let s = state.clone();
|
||||
let handler = move |_args: &crate::imports::Win64Args,
|
||||
_cpu: &mut crate::cpu::CpuState,
|
||||
_mem: &mut GuestMemory|
|
||||
-> Result<u64, ExitReason> { Ok(s.process_id as u64) };
|
||||
registry.register(KERNEL32, "GetCurrentProcessId", handler);
|
||||
registry.alias(PROCESS_THREADS_V1, KERNEL32, "GetCurrentProcessId");
|
||||
|
||||
// 3. GetCurrentThreadId() -> DWORD
|
||||
let s = state.clone();
|
||||
let handler = move |_args: &crate::imports::Win64Args,
|
||||
_cpu: &mut crate::cpu::CpuState,
|
||||
_mem: &mut GuestMemory|
|
||||
-> Result<u64, ExitReason> { Ok(s.thread_id as u64) };
|
||||
registry.register(KERNEL32, "GetCurrentThreadId", handler);
|
||||
registry.alias(PROCESS_THREADS_V1, KERNEL32, "GetCurrentThreadId");
|
||||
|
||||
// 4. GetLastError() -> DWORD
|
||||
let s = state.clone();
|
||||
let handler =
|
||||
move |_args: &crate::imports::Win64Args,
|
||||
_cpu: &mut crate::cpu::CpuState,
|
||||
_mem: &mut GuestMemory|
|
||||
-> Result<u64, ExitReason> { Ok(s.last_error.load(Ordering::SeqCst) as u64) };
|
||||
registry.register(KERNEL32, "GetLastError", handler);
|
||||
registry.alias(
|
||||
"api-ms-win-core-errorhandling-l1-1-0.dll",
|
||||
KERNEL32,
|
||||
"GetLastError",
|
||||
);
|
||||
|
||||
// 5. SetLastError(dwErrCode: DWORD)
|
||||
let s = state.clone();
|
||||
let handler = move |args: &crate::imports::Win64Args,
|
||||
_cpu: &mut crate::cpu::CpuState,
|
||||
mem: &mut GuestMemory|
|
||||
-> Result<u64, ExitReason> {
|
||||
let code = args.get(0, mem).map_err(ExitReason::MemoryFault)? as u32;
|
||||
s.last_error.store(code, Ordering::SeqCst);
|
||||
Ok(0)
|
||||
};
|
||||
registry.register(KERNEL32, "SetLastError", handler);
|
||||
registry.alias(
|
||||
"api-ms-win-core-errorhandling-l1-1-0.dll",
|
||||
KERNEL32,
|
||||
"SetLastError",
|
||||
);
|
||||
|
||||
let s = state.clone();
|
||||
registry.register(KERNEL32, "VirtualAlloc", move |args, _, mem| {
|
||||
let requested = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
let size = args.get(1, mem).map_err(ExitReason::MemoryFault)?;
|
||||
let allocation_type = args.get(2, mem).map_err(ExitReason::MemoryFault)? as u32;
|
||||
let protect = args.get(3, mem).map_err(ExitReason::MemoryFault)? as u32;
|
||||
|
||||
if size == 0 {
|
||||
return s.fail(ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
if allocation_type != MEM_COMMIT_RESERVE {
|
||||
return s.fail(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 s.fail(ERROR_INVALID_PARAMETER, 0),
|
||||
};
|
||||
let base = requested & !(ALLOCATION_GRANULARITY - 1);
|
||||
if requested != 0 && base == 0 {
|
||||
return s.fail(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 s.fail(ERROR_INVALID_PARAMETER, 0);
|
||||
};
|
||||
|
||||
match mem.map_virtual_allocation(base, size, permissions) {
|
||||
Ok(address) => Ok(address),
|
||||
Err(MemoryError::OverlappingRegion { .. } | MemoryError::Overflow) => {
|
||||
s.fail(ERROR_INVALID_ADDRESS, 0)
|
||||
}
|
||||
Err(_) => s.fail(ERROR_NOT_ENOUGH_MEMORY, 0),
|
||||
}
|
||||
});
|
||||
|
||||
let s = state.clone();
|
||||
registry.register(KERNEL32, "VirtualFree", move |args, _, mem| {
|
||||
let address = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
|
||||
let size = args.get(1, mem).map_err(ExitReason::MemoryFault)?;
|
||||
let free_type = args.get(2, mem).map_err(ExitReason::MemoryFault)? as u32;
|
||||
if free_type != MEM_RELEASE {
|
||||
return s.fail(ERROR_NOT_SUPPORTED, 0);
|
||||
}
|
||||
if size != 0 {
|
||||
return s.fail(ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
if !mem.release_virtual_allocation(address) {
|
||||
return s.fail(ERROR_INVALID_ADDRESS, 0);
|
||||
}
|
||||
Ok(1)
|
||||
});
|
||||
|
||||
for symbol in ["VirtualAlloc", "VirtualFree"] {
|
||||
registry.alias("api-ms-win-core-memory-l1-1-0.dll", KERNEL32, symbol);
|
||||
registry.set_status(KERNEL32, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
crate::runtime_table::register(registry, &state);
|
||||
|
||||
// 8. XMemAlloc(dwSize, dwAllocAttributes) -> LPVOID (Xbox Scarlett allocator in xmem.dll)
|
||||
let s = state.clone();
|
||||
@@ -582,3 +326,244 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc<Serv
|
||||
ServiceStatus::Implemented,
|
||||
);
|
||||
}
|
||||
|
||||
/// Implementations behind the generated adapters. A failure the guest can
|
||||
/// observe sets its last error; `Err` stops the guest.
|
||||
pub(crate) mod handlers {
|
||||
use super::*;
|
||||
use crate::runtime::{Float32, Float64, OutPtr, ServiceContext};
|
||||
use crate::softfloat::{Control, F32, F64, square_root};
|
||||
|
||||
type Outcome<T> = Result<T, ExitReason>;
|
||||
|
||||
pub fn set_process_priority_boost(
|
||||
context: &mut ServiceContext<'_>,
|
||||
process: u64,
|
||||
disable: bool,
|
||||
) -> Outcome<bool> {
|
||||
if !context.state.is_current_process(process) {
|
||||
return Ok(false);
|
||||
}
|
||||
context
|
||||
.state
|
||||
.priority_boost_disabled
|
||||
.store(disable, Ordering::SeqCst);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub fn get_process_priority_boost(
|
||||
context: &mut ServiceContext<'_>,
|
||||
process: u64,
|
||||
disabled: OutPtr<4>,
|
||||
) -> Outcome<bool> {
|
||||
if !context.state.is_current_process(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);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub fn get_current_process(_: &mut ServiceContext<'_>) -> Outcome<u64> {
|
||||
Ok(CURRENT_PROCESS)
|
||||
}
|
||||
|
||||
pub fn get_process_id(context: &mut ServiceContext<'_>, process: u64) -> Outcome<u32> {
|
||||
Ok(if context.state.is_current_process(process) {
|
||||
context.state.process_id
|
||||
} else {
|
||||
0
|
||||
})
|
||||
}
|
||||
|
||||
pub fn get_current_thread(_: &mut ServiceContext<'_>) -> Outcome<u64> {
|
||||
Ok(CURRENT_THREAD)
|
||||
}
|
||||
|
||||
pub fn get_current_process_id(context: &mut ServiceContext<'_>) -> Outcome<u32> {
|
||||
Ok(context.state.process_id)
|
||||
}
|
||||
|
||||
pub fn get_current_thread_id(context: &mut ServiceContext<'_>) -> Outcome<u32> {
|
||||
Ok(context.state.thread_id)
|
||||
}
|
||||
|
||||
pub fn open_thread(
|
||||
context: &mut ServiceContext<'_>,
|
||||
access: u32,
|
||||
inherit: bool,
|
||||
id: u32,
|
||||
) -> Outcome<u64> {
|
||||
let state = context.state;
|
||||
if id != state.thread_id {
|
||||
return state.fail(ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
if inherit || access & !THREAD_SUPPORTED_RIGHTS != 0 {
|
||||
return state.fail(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);
|
||||
};
|
||||
thread.handles.insert(handle, access);
|
||||
thread.last_handle = handle;
|
||||
Ok(handle)
|
||||
}
|
||||
|
||||
pub fn get_thread_priority(context: &mut ServiceContext<'_>, handle: u64) -> Outcome<i32> {
|
||||
let thread = context.state.thread.lock().expect("guest thread state");
|
||||
if let Err(error) = thread.check_access(handle, THREAD_QUERY_RIGHTS) {
|
||||
return context
|
||||
.state
|
||||
.fail(error, THREAD_PRIORITY_ERROR_RETURN as i32);
|
||||
}
|
||||
Ok(thread.priority)
|
||||
}
|
||||
|
||||
pub fn set_thread_priority(
|
||||
context: &mut ServiceContext<'_>,
|
||||
handle: u64,
|
||||
priority: i32,
|
||||
) -> Outcome<bool> {
|
||||
let state = context.state;
|
||||
let mut thread = state.thread.lock().expect("guest thread state");
|
||||
if let Err(error) = thread.check_access(handle, THREAD_SET_RIGHTS) {
|
||||
return state.fail(error, false);
|
||||
}
|
||||
if matches!(priority, 0x0001_0000 | 0x0002_0000) {
|
||||
return state.fail(ERROR_NOT_SUPPORTED, false);
|
||||
}
|
||||
if !matches!(priority, -15 | -2..=2 | 15) {
|
||||
return state.fail(ERROR_INVALID_PARAMETER, false);
|
||||
}
|
||||
thread.priority = priority;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
pub fn close_handle(context: &mut ServiceContext<'_>, handle: u64) -> Outcome<bool> {
|
||||
let closed = matches!(handle, CURRENT_PROCESS | CURRENT_THREAD)
|
||||
|| context
|
||||
.state
|
||||
.thread
|
||||
.lock()
|
||||
.expect("guest thread state")
|
||||
.handles
|
||||
.remove(&handle)
|
||||
.is_some();
|
||||
if closed {
|
||||
Ok(true)
|
||||
} else {
|
||||
context.state.fail(ERROR_INVALID_HANDLE, false)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_system_time_as_file_time(
|
||||
context: &mut ServiceContext<'_>,
|
||||
time: OutPtr<8>,
|
||||
) -> Outcome<()> {
|
||||
let now = context.state.clock.now_filetime();
|
||||
time.store(context.memory, now.to_le_bytes())
|
||||
.map_err(ExitReason::MemoryFault)
|
||||
}
|
||||
|
||||
pub fn get_last_error(context: &mut ServiceContext<'_>) -> Outcome<u32> {
|
||||
Ok(context.state.last_error.load(Ordering::SeqCst))
|
||||
}
|
||||
|
||||
pub fn set_last_error(context: &mut ServiceContext<'_>, code: u32) -> Outcome<()> {
|
||||
context.state.last_error.store(code, Ordering::SeqCst);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn virtual_alloc(
|
||||
context: &mut ServiceContext<'_>,
|
||||
requested: u64,
|
||||
size: u64,
|
||||
kind: u32,
|
||||
protect: u32,
|
||||
) -> Outcome<u64> {
|
||||
let state = context.state;
|
||||
if size == 0 {
|
||||
return state.fail(ERROR_INVALID_PARAMETER, 0);
|
||||
}
|
||||
if kind != MEM_COMMIT_RESERVE {
|
||||
return state.fail(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),
|
||||
};
|
||||
let base = requested & !(ALLOCATION_GRANULARITY - 1);
|
||||
if requested != 0 && base == 0 {
|
||||
return state.fail(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);
|
||||
};
|
||||
match context
|
||||
.memory
|
||||
.map_virtual_allocation(base, size, permissions)
|
||||
{
|
||||
Ok(address) => Ok(address),
|
||||
Err(MemoryError::OverlappingRegion { .. } | MemoryError::Overflow) => {
|
||||
state.fail(ERROR_INVALID_ADDRESS, 0)
|
||||
}
|
||||
Err(_) => state.fail(ERROR_NOT_ENOUGH_MEMORY, 0),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn virtual_free(
|
||||
context: &mut ServiceContext<'_>,
|
||||
address: u64,
|
||||
size: u64,
|
||||
kind: u32,
|
||||
) -> Outcome<bool> {
|
||||
let state = context.state;
|
||||
if kind != MEM_RELEASE {
|
||||
return state.fail(ERROR_NOT_SUPPORTED, false);
|
||||
}
|
||||
if size != 0 {
|
||||
return state.fail(ERROR_INVALID_PARAMETER, false);
|
||||
}
|
||||
if !context.memory.release_virtual_allocation(address) {
|
||||
return state.fail(ERROR_INVALID_ADDRESS, false);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// The guest MXCSR is not visible to a service, so results use the default
|
||||
/// rounding and raise no guest flags; the registry marks them partial.
|
||||
const DEFAULT_MXCSR: u32 = crate::cpu::Mxcsr::RESET;
|
||||
|
||||
pub fn sqrt(_: &mut ServiceContext<'_>, x: Float64) -> Outcome<Float64> {
|
||||
let control = Control::from_mxcsr(DEFAULT_MXCSR);
|
||||
Ok(Float64(square_root(F64, x.0, &control).bits))
|
||||
}
|
||||
|
||||
pub fn sqrtf(_: &mut ServiceContext<'_>, x: Float32) -> Outcome<Float32> {
|
||||
let control = Control::from_mxcsr(DEFAULT_MXCSR);
|
||||
let bits = square_root(F32, u64::from(x.0), &control).bits;
|
||||
Ok(Float32(bits as u32))
|
||||
}
|
||||
|
||||
pub fn fabs(_: &mut ServiceContext<'_>, x: Float64) -> Outcome<Float64> {
|
||||
Ok(Float64(x.0 & !(1 << 63)))
|
||||
}
|
||||
|
||||
pub fn fabsf(_: &mut ServiceContext<'_>, x: Float32) -> Outcome<Float32> {
|
||||
Ok(Float32(x.0 & !(1 << 31)))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,641 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Exact binary32 and binary64 arithmetic with x86 SSE rules.
|
||||
//!
|
||||
//! Every operation computes an exact or sticky integer result and rounds once,
|
||||
//! in any MXCSR rounding mode. NaN selection, the negative default NaN,
|
||||
//! denormals-are-zero, flush-to-zero, tininess after rounding and the sticky
|
||||
//! exception flags follow the Intel SDM (Vol. 1, 4.8, 4.9 and 11.5). Host
|
||||
//! floating point is never used: ARM64 differs in all of those.
|
||||
|
||||
use std::cmp::Ordering;
|
||||
|
||||
/// MXCSR exception flags, in their register positions.
|
||||
pub const INVALID: u32 = 1;
|
||||
pub const DENORMAL: u32 = 1 << 1;
|
||||
pub const DIVIDE_BY_ZERO: u32 = 1 << 2;
|
||||
pub const OVERFLOW: u32 = 1 << 3;
|
||||
pub const UNDERFLOW: u32 = 1 << 4;
|
||||
pub const PRECISION: u32 = 1 << 5;
|
||||
|
||||
/// Exceptions detected before a result is computed.
|
||||
pub const PRE_COMPUTATION: u32 = INVALID | DENORMAL | DIVIDE_BY_ZERO;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Rounding {
|
||||
Nearest,
|
||||
Down,
|
||||
Up,
|
||||
Zero,
|
||||
}
|
||||
|
||||
/// Arithmetic controls from MXCSR.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Control {
|
||||
pub rounding: Rounding,
|
||||
pub denormals_are_zero: bool,
|
||||
pub flush_to_zero: bool,
|
||||
pub underflow_masked: bool,
|
||||
}
|
||||
|
||||
impl Control {
|
||||
pub fn from_mxcsr(mxcsr: u32) -> Self {
|
||||
Self {
|
||||
rounding: match mxcsr >> 13 & 3 {
|
||||
0 => Rounding::Nearest,
|
||||
1 => Rounding::Down,
|
||||
2 => Rounding::Up,
|
||||
_ => Rounding::Zero,
|
||||
},
|
||||
denormals_are_zero: mxcsr & 1 << 6 != 0,
|
||||
flush_to_zero: mxcsr & 1 << 15 != 0,
|
||||
underflow_masked: mxcsr & 1 << 11 != 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A binary interchange format.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Format {
|
||||
pub bits: u32,
|
||||
/// Stored significand bits.
|
||||
fraction: u32,
|
||||
}
|
||||
|
||||
pub const F32: Format = Format {
|
||||
bits: 32,
|
||||
fraction: 23,
|
||||
};
|
||||
pub const F64: Format = Format {
|
||||
bits: 64,
|
||||
fraction: 52,
|
||||
};
|
||||
|
||||
impl Format {
|
||||
fn exponent_max(self) -> u64 {
|
||||
(1 << (self.bits - 1 - self.fraction)) - 1
|
||||
}
|
||||
|
||||
fn bias(self) -> i32 {
|
||||
(self.exponent_max() >> 1) as i32
|
||||
}
|
||||
|
||||
fn sign_bit(self) -> u64 {
|
||||
1 << (self.bits - 1)
|
||||
}
|
||||
|
||||
fn fraction_mask(self) -> u64 {
|
||||
(1 << self.fraction) - 1
|
||||
}
|
||||
|
||||
fn quiet_bit(self) -> u64 {
|
||||
1 << (self.fraction - 1)
|
||||
}
|
||||
|
||||
fn infinity(self, sign: bool) -> u64 {
|
||||
self.signed(sign, self.exponent_max() << self.fraction)
|
||||
}
|
||||
|
||||
fn largest(self, sign: bool) -> u64 {
|
||||
self.infinity(sign) - 1
|
||||
}
|
||||
|
||||
/// The x86 default NaN is negative and quiet.
|
||||
fn default_nan(self) -> u64 {
|
||||
self.infinity(true) | self.quiet_bit()
|
||||
}
|
||||
|
||||
fn signed(self, sign: bool, magnitude: u64) -> u64 {
|
||||
magnitude | if sign { self.sign_bit() } else { 0 }
|
||||
}
|
||||
|
||||
fn sign(self, value: u64) -> bool {
|
||||
value & self.sign_bit() != 0
|
||||
}
|
||||
|
||||
fn magnitude(self, value: u64) -> u64 {
|
||||
value & (self.sign_bit() - 1)
|
||||
}
|
||||
|
||||
fn is_nan(self, value: u64) -> bool {
|
||||
self.magnitude(value) > self.infinity(false)
|
||||
}
|
||||
|
||||
fn is_signaling(self, value: u64) -> bool {
|
||||
self.is_nan(value) && value & self.quiet_bit() == 0
|
||||
}
|
||||
|
||||
fn is_infinite(self, value: u64) -> bool {
|
||||
self.magnitude(value) == self.infinity(false)
|
||||
}
|
||||
|
||||
fn is_zero(self, value: u64) -> bool {
|
||||
self.magnitude(value) == 0
|
||||
}
|
||||
|
||||
fn is_denormal(self, value: u64) -> bool {
|
||||
let magnitude = self.magnitude(value);
|
||||
magnitude != 0 && magnitude <= self.fraction_mask()
|
||||
}
|
||||
|
||||
/// Significand and exponent with value `significand * 2^exponent`, for a
|
||||
/// finite number.
|
||||
fn unpack(self, value: u64) -> (u64, i32) {
|
||||
let field = (self.magnitude(value) >> self.fraction) as i32;
|
||||
let fraction = value & self.fraction_mask();
|
||||
let scale = self.bias() + self.fraction as i32;
|
||||
if field == 0 {
|
||||
(fraction, 1 - scale)
|
||||
} else {
|
||||
(fraction | 1 << self.fraction, field - scale)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A result and the exceptions it raised.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Outcome {
|
||||
pub bits: u64,
|
||||
pub flags: u32,
|
||||
}
|
||||
|
||||
fn exact(bits: u64) -> Outcome {
|
||||
Outcome { bits, flags: 0 }
|
||||
}
|
||||
|
||||
fn invalid(format: Format) -> Outcome {
|
||||
Outcome {
|
||||
bits: format.default_nan(),
|
||||
flags: INVALID,
|
||||
}
|
||||
}
|
||||
|
||||
/// Divide `value` by 2^shift, rounding, where `sticky` marks a nonzero part
|
||||
/// below the integer. Returns the quotient and whether it is inexact.
|
||||
fn round_shift(
|
||||
value: u128,
|
||||
shift: i32,
|
||||
sticky: bool,
|
||||
sign: bool,
|
||||
rounding: Rounding,
|
||||
) -> (u128, bool) {
|
||||
if shift <= 0 {
|
||||
// Callers keep enough bits that a sticky value always has to shift.
|
||||
return (value << -shift, sticky);
|
||||
}
|
||||
let (quotient, half) = if shift > 128 {
|
||||
(0, Ordering::Less)
|
||||
} else if shift == 128 {
|
||||
(0, value.cmp(&(1 << 127)))
|
||||
} else {
|
||||
let remainder = value & ((1 << shift) - 1);
|
||||
(value >> shift, remainder.cmp(&(1 << (shift - 1))))
|
||||
};
|
||||
let lost = if shift >= 128 {
|
||||
value != 0
|
||||
} else {
|
||||
value & ((1 << shift) - 1) != 0
|
||||
};
|
||||
let inexact = lost || sticky;
|
||||
let half = if half == Ordering::Equal && sticky {
|
||||
Ordering::Greater
|
||||
} else {
|
||||
half
|
||||
};
|
||||
let up = inexact
|
||||
&& match rounding {
|
||||
Rounding::Nearest => match half {
|
||||
Ordering::Greater => true,
|
||||
Ordering::Equal => quotient & 1 == 1,
|
||||
Ordering::Less => false,
|
||||
},
|
||||
Rounding::Down => sign,
|
||||
Rounding::Up => !sign,
|
||||
Rounding::Zero => false,
|
||||
};
|
||||
(quotient + u128::from(up), inexact)
|
||||
}
|
||||
|
||||
/// Round `significand * 2^exponent`, slightly larger in magnitude if `sticky`,
|
||||
/// to `format`.
|
||||
fn round(
|
||||
format: Format,
|
||||
sign: bool,
|
||||
significand: u128,
|
||||
exponent: i32,
|
||||
sticky: bool,
|
||||
control: &Control,
|
||||
) -> Outcome {
|
||||
if significand == 0 {
|
||||
return exact(format.signed(sign, 0));
|
||||
}
|
||||
let precision = format.fraction as i32 + 1;
|
||||
let length = 128 - significand.leading_zeros() as i32;
|
||||
let shift = length - precision;
|
||||
let minimum = 1 - format.bias();
|
||||
let mut leading = exponent + length - 1;
|
||||
let round_at = |shift| round_shift(significand, shift, sticky, sign, control.rounding);
|
||||
|
||||
// Tininess is detected after rounding to an unbounded exponent.
|
||||
let (mut value, mut inexact) = round_at(shift);
|
||||
if value >> precision != 0 {
|
||||
value >>= 1;
|
||||
leading += 1;
|
||||
}
|
||||
let tiny = leading < minimum;
|
||||
let mut flags = 0;
|
||||
if tiny && control.flush_to_zero && control.underflow_masked {
|
||||
return Outcome {
|
||||
bits: format.signed(sign, 0),
|
||||
flags: UNDERFLOW | PRECISION,
|
||||
};
|
||||
}
|
||||
let before = exponent + length - 1;
|
||||
if before < minimum {
|
||||
(value, inexact) = round_at(shift + (minimum - before));
|
||||
// A carry out of the fraction lands exactly on the smallest normal.
|
||||
leading = minimum;
|
||||
}
|
||||
if tiny && (inexact || !control.underflow_masked) {
|
||||
flags |= UNDERFLOW;
|
||||
}
|
||||
if inexact {
|
||||
flags |= PRECISION;
|
||||
}
|
||||
if leading > format.bias() {
|
||||
let to_infinity = match control.rounding {
|
||||
Rounding::Nearest => true,
|
||||
Rounding::Down => sign,
|
||||
Rounding::Up => !sign,
|
||||
Rounding::Zero => false,
|
||||
};
|
||||
return Outcome {
|
||||
bits: if to_infinity {
|
||||
format.infinity(sign)
|
||||
} else {
|
||||
format.largest(sign)
|
||||
},
|
||||
flags: OVERFLOW | PRECISION,
|
||||
};
|
||||
}
|
||||
// The leading bit of a normal value adds one to the exponent field.
|
||||
let field = (leading - minimum) as u64;
|
||||
Outcome {
|
||||
bits: format.signed(sign, (field << format.fraction) + value as u64),
|
||||
flags,
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace a denormal by a signed zero under DAZ, otherwise note it.
|
||||
fn operand(format: Format, value: u64, control: &Control) -> (u64, u32) {
|
||||
if !format.is_denormal(value) {
|
||||
(value, 0)
|
||||
} else if control.denormals_are_zero {
|
||||
(value & format.sign_bit(), 0)
|
||||
} else {
|
||||
(value, DENORMAL)
|
||||
}
|
||||
}
|
||||
|
||||
/// The result of a two-operand form with a NaN source: the first NaN, quieted.
|
||||
fn select_nan(format: Format, a: u64, b: u64) -> Option<Outcome> {
|
||||
let chosen = if format.is_nan(a) {
|
||||
a
|
||||
} else if format.is_nan(b) {
|
||||
b
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
let signaling = format.is_signaling(a) || format.is_signaling(b);
|
||||
Some(Outcome {
|
||||
bits: chosen | format.quiet_bit(),
|
||||
flags: if signaling { INVALID } else { 0 },
|
||||
})
|
||||
}
|
||||
|
||||
/// Two-operand arithmetic.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Arithmetic {
|
||||
Add,
|
||||
Sub,
|
||||
Mul,
|
||||
Div,
|
||||
Min,
|
||||
Max,
|
||||
}
|
||||
|
||||
pub fn arithmetic(kind: Arithmetic, format: Format, a: u64, b: u64, control: &Control) -> Outcome {
|
||||
let (a, a_flag) = operand(format, a, control);
|
||||
let (b, b_flag) = operand(format, b, control);
|
||||
if matches!(kind, Arithmetic::Min | Arithmetic::Max) {
|
||||
return extremum(kind == Arithmetic::Min, format, a, b, a_flag | b_flag);
|
||||
}
|
||||
if let Some(outcome) = select_nan(format, a, b) {
|
||||
return outcome;
|
||||
}
|
||||
let (sign_a, sign_b) = (format.sign(a), format.sign(b));
|
||||
let sign = sign_a != sign_b;
|
||||
let infinite = format.is_infinite(a) || format.is_infinite(b);
|
||||
let special = match kind {
|
||||
Arithmetic::Add | Arithmetic::Sub if infinite => {
|
||||
let sign_b = sign_b != (kind == Arithmetic::Sub);
|
||||
Some(if !format.is_infinite(b) {
|
||||
exact(a)
|
||||
} else if format.is_infinite(a) && sign_a != sign_b {
|
||||
invalid(format)
|
||||
} else {
|
||||
exact(format.infinity(sign_b))
|
||||
})
|
||||
}
|
||||
Arithmetic::Mul if infinite => Some(if format.is_zero(a) || format.is_zero(b) {
|
||||
invalid(format)
|
||||
} else {
|
||||
exact(format.infinity(sign))
|
||||
}),
|
||||
Arithmetic::Div => {
|
||||
let undefined = (format.is_infinite(a) && format.is_infinite(b))
|
||||
|| (format.is_zero(a) && format.is_zero(b));
|
||||
if undefined {
|
||||
Some(invalid(format))
|
||||
} else if format.is_infinite(a) {
|
||||
Some(exact(format.infinity(sign)))
|
||||
} else if format.is_infinite(b) {
|
||||
Some(exact(format.signed(sign, 0)))
|
||||
} else if format.is_zero(b) {
|
||||
Some(Outcome {
|
||||
bits: format.infinity(sign),
|
||||
flags: DIVIDE_BY_ZERO,
|
||||
})
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let mut outcome = special.unwrap_or_else(|| {
|
||||
let (sa, ea) = format.unpack(a);
|
||||
let (sb, eb) = format.unpack(b);
|
||||
match kind {
|
||||
Arithmetic::Mul => round(
|
||||
format,
|
||||
sign,
|
||||
u128::from(sa) * u128::from(sb),
|
||||
ea + eb,
|
||||
false,
|
||||
control,
|
||||
),
|
||||
Arithmetic::Div if sa == 0 => exact(format.signed(sign, 0)),
|
||||
Arithmetic::Div => {
|
||||
let shift = u128::from(sa).leading_zeros() as i32 - 1;
|
||||
let dividend = u128::from(sa) << shift;
|
||||
let divisor = u128::from(sb);
|
||||
round(
|
||||
format,
|
||||
sign,
|
||||
dividend / divisor,
|
||||
ea - eb - shift,
|
||||
!dividend.is_multiple_of(divisor),
|
||||
control,
|
||||
)
|
||||
}
|
||||
_ => {
|
||||
let sign_b = sign_b != (kind == Arithmetic::Sub);
|
||||
sum(format, (sign_a, sa, ea), (sign_b, sb, eb), control)
|
||||
}
|
||||
}
|
||||
});
|
||||
// Invalid operation and divide by zero take priority over a denormal operand.
|
||||
if outcome.flags & (INVALID | DIVIDE_BY_ZERO) == 0 {
|
||||
outcome.flags |= a_flag | b_flag;
|
||||
}
|
||||
outcome
|
||||
}
|
||||
|
||||
/// Sum of two finite numbers given as sign, significand and exponent.
|
||||
fn sum(format: Format, a: (bool, u64, i32), b: (bool, u64, i32), control: &Control) -> Outcome {
|
||||
// Alignment is exact up to this distance. Beyond it the larger operand is
|
||||
// normal and the smaller is below 2^-17 of its unit in the last place, so it
|
||||
// moves the exact result only within a quarter unit of the larger operand,
|
||||
// or of the half-sized unit just below a power of two.
|
||||
const EXACT: i32 = 70;
|
||||
if a.1 == 0 || b.1 == 0 {
|
||||
if a.1 == 0 && b.1 == 0 {
|
||||
let negative = if a.0 == b.0 {
|
||||
a.0
|
||||
} else {
|
||||
control.rounding == Rounding::Down
|
||||
};
|
||||
return exact(format.signed(negative, 0));
|
||||
}
|
||||
let (sign, significand, exponent) = if a.1 == 0 { b } else { a };
|
||||
return round(
|
||||
format,
|
||||
sign,
|
||||
u128::from(significand),
|
||||
exponent,
|
||||
false,
|
||||
control,
|
||||
);
|
||||
}
|
||||
let (high, low) = if a.2 >= b.2 { (a, b) } else { (b, a) };
|
||||
let distance = high.2 - low.2;
|
||||
if distance > EXACT {
|
||||
let wide = u128::from(high.1) << EXACT;
|
||||
// Any value strictly inside that interval rounds as the exact one does.
|
||||
let significand = if high.0 == low.0 { wide } else { wide - 1 };
|
||||
return round(format, high.0, significand, high.2 - EXACT, true, control);
|
||||
}
|
||||
let x = (u128::from(high.1) << distance) as i128 * if high.0 { -1 } else { 1 };
|
||||
let y = i128::from(low.1) * if low.0 { -1 } else { 1 };
|
||||
let total = x + y;
|
||||
if total == 0 {
|
||||
return exact(format.signed(control.rounding == Rounding::Down, 0));
|
||||
}
|
||||
round(
|
||||
format,
|
||||
total < 0,
|
||||
total.unsigned_abs(),
|
||||
low.2,
|
||||
false,
|
||||
control,
|
||||
)
|
||||
}
|
||||
|
||||
/// MIN and MAX return the second operand unless the first is strictly smaller
|
||||
/// or larger; any NaN is an invalid operation and selects the second operand.
|
||||
fn extremum(minimum: bool, format: Format, a: u64, b: u64, denormal: u32) -> Outcome {
|
||||
if format.is_nan(a) || format.is_nan(b) {
|
||||
return Outcome {
|
||||
bits: b,
|
||||
flags: INVALID,
|
||||
};
|
||||
}
|
||||
let order = compare_numbers(format, a, b);
|
||||
let first = order
|
||||
== if minimum {
|
||||
Ordering::Less
|
||||
} else {
|
||||
Ordering::Greater
|
||||
};
|
||||
Outcome {
|
||||
bits: if first { a } else { b },
|
||||
flags: denormal,
|
||||
}
|
||||
}
|
||||
|
||||
/// Order of two non-NaN values; zeros of either sign are equal.
|
||||
fn compare_numbers(format: Format, a: u64, b: u64) -> Ordering {
|
||||
let key = |value| {
|
||||
let magnitude = format.magnitude(value) as i128;
|
||||
if format.sign(value) {
|
||||
-magnitude
|
||||
} else {
|
||||
magnitude
|
||||
}
|
||||
};
|
||||
key(a).cmp(&key(b))
|
||||
}
|
||||
|
||||
/// Compare, with `None` for unordered. A quiet NaN is invalid only when
|
||||
/// `signaling` is set.
|
||||
pub fn compare(
|
||||
format: Format,
|
||||
a: u64,
|
||||
b: u64,
|
||||
signaling: bool,
|
||||
control: &Control,
|
||||
) -> (Option<Ordering>, u32) {
|
||||
let (a, a_flag) = operand(format, a, control);
|
||||
let (b, b_flag) = operand(format, b, control);
|
||||
if format.is_nan(a) || format.is_nan(b) {
|
||||
let raises = signaling || format.is_signaling(a) || format.is_signaling(b);
|
||||
return (None, if raises { INVALID } else { 0 });
|
||||
}
|
||||
(Some(compare_numbers(format, a, b)), a_flag | b_flag)
|
||||
}
|
||||
|
||||
pub fn square_root(format: Format, value: u64, control: &Control) -> Outcome {
|
||||
let (value, denormal) = operand(format, value, control);
|
||||
if format.is_nan(value) {
|
||||
return Outcome {
|
||||
bits: value | format.quiet_bit(),
|
||||
flags: if format.is_signaling(value) {
|
||||
INVALID
|
||||
} else {
|
||||
0
|
||||
},
|
||||
};
|
||||
}
|
||||
if format.is_zero(value) {
|
||||
return exact(value);
|
||||
}
|
||||
if format.sign(value) {
|
||||
return invalid(format);
|
||||
}
|
||||
if format.is_infinite(value) {
|
||||
return exact(value);
|
||||
}
|
||||
let (significand, exponent) = format.unpack(value);
|
||||
let mut shift = u128::from(significand).leading_zeros() as i32 - 1;
|
||||
if (exponent - shift) % 2 != 0 {
|
||||
shift -= 1;
|
||||
}
|
||||
let wide = u128::from(significand) << shift;
|
||||
let root = wide.isqrt();
|
||||
let mut outcome = round(
|
||||
format,
|
||||
false,
|
||||
root,
|
||||
(exponent - shift) / 2,
|
||||
root * root != wide,
|
||||
control,
|
||||
);
|
||||
outcome.flags |= denormal;
|
||||
outcome
|
||||
}
|
||||
|
||||
/// Convert between binary32 and binary64.
|
||||
pub fn convert(from: Format, to: Format, value: u64, control: &Control) -> Outcome {
|
||||
let (value, denormal) = operand(from, value, control);
|
||||
let sign = from.sign(value);
|
||||
if from.is_nan(value) {
|
||||
let fraction = value & from.fraction_mask();
|
||||
let moved = if to.fraction >= from.fraction {
|
||||
fraction << (to.fraction - from.fraction)
|
||||
} else {
|
||||
fraction >> (from.fraction - to.fraction)
|
||||
};
|
||||
return Outcome {
|
||||
bits: to.infinity(sign) | moved | to.quiet_bit(),
|
||||
flags: if from.is_signaling(value) { INVALID } else { 0 },
|
||||
};
|
||||
}
|
||||
if from.is_infinite(value) {
|
||||
return exact(to.infinity(sign));
|
||||
}
|
||||
let (significand, exponent) = from.unpack(value);
|
||||
let mut outcome = round(to, sign, u128::from(significand), exponent, false, control);
|
||||
outcome.flags |= denormal;
|
||||
outcome
|
||||
}
|
||||
|
||||
/// Convert a signed integer.
|
||||
pub fn from_integer(format: Format, value: i64, control: &Control) -> Outcome {
|
||||
round(
|
||||
format,
|
||||
value < 0,
|
||||
u128::from(value.unsigned_abs()),
|
||||
0,
|
||||
false,
|
||||
control,
|
||||
)
|
||||
}
|
||||
|
||||
/// Convert to a signed integer of `bits`. A NaN or a value outside the range
|
||||
/// gives the integer indefinite value and raises invalid.
|
||||
pub fn to_integer(
|
||||
format: Format,
|
||||
value: u64,
|
||||
bits: u32,
|
||||
truncate: bool,
|
||||
control: &Control,
|
||||
) -> Outcome {
|
||||
let indefinite = Outcome {
|
||||
bits: 1 << (bits - 1),
|
||||
flags: INVALID,
|
||||
};
|
||||
let (value, _) = operand(format, value, control);
|
||||
if format.is_nan(value) || format.is_infinite(value) {
|
||||
return indefinite;
|
||||
}
|
||||
let sign = format.sign(value);
|
||||
let (significand, exponent) = format.unpack(value);
|
||||
if exponent > 64 && significand != 0 {
|
||||
return indefinite;
|
||||
}
|
||||
let rounding = if truncate {
|
||||
Rounding::Zero
|
||||
} else {
|
||||
control.rounding
|
||||
};
|
||||
let (magnitude, inexact) =
|
||||
round_shift(u128::from(significand), -exponent, false, sign, rounding);
|
||||
let limit = 1u128 << (bits - 1);
|
||||
if magnitude > limit || (magnitude == limit && !sign) {
|
||||
return indefinite;
|
||||
}
|
||||
let mask = if bits == 64 {
|
||||
u64::MAX
|
||||
} else {
|
||||
(1 << bits) - 1
|
||||
};
|
||||
let integer = if sign {
|
||||
(magnitude as u64).wrapping_neg()
|
||||
} else {
|
||||
magnitude as u64
|
||||
};
|
||||
Outcome {
|
||||
bits: integer & mask,
|
||||
flags: if inexact { PRECISION } else { 0 },
|
||||
}
|
||||
}
|
||||
+136
-16
@@ -11,6 +11,14 @@ use crate::{
|
||||
|
||||
const STACK_SIZE: usize = 64 * 1024;
|
||||
const JIT_CAPACITY: usize = 1024 * 1024;
|
||||
/// The TEB is placed this far above the TLS base and spans two 4 KiB pages.
|
||||
const TEB_OFFSET: u64 = 0x10000;
|
||||
const TEB_SIZE: usize = 0x2000;
|
||||
// Win64 TEB fields (NT_TIB prefix plus the TLS slot) written by the harness.
|
||||
const TEB_STACK_BASE: u64 = 0x08;
|
||||
const TEB_STACK_LIMIT: u64 = 0x10;
|
||||
const TEB_SELF: u64 = 0x30;
|
||||
const TEB_TLS_POINTER: u64 = 0x58;
|
||||
|
||||
/// Guest addresses reserved by the fixture harness.
|
||||
pub struct StartupLayout {
|
||||
@@ -79,6 +87,8 @@ pub fn run_synthetic_startup_with_observer(
|
||||
)
|
||||
.into());
|
||||
}
|
||||
// Reject an impossible layout before parsing or mapping anything.
|
||||
let (stack_base, teb_base) = layout_regions(&layout)?;
|
||||
let pe = ParsedPe::parse(bytes)?;
|
||||
observe(StartupEvent::Parsed {
|
||||
sections: pe.sections.len(),
|
||||
@@ -112,24 +122,9 @@ pub fn run_synthetic_startup_with_observer(
|
||||
)?;
|
||||
}
|
||||
|
||||
let stack_base = layout
|
||||
.stack_top
|
||||
.checked_sub(STACK_SIZE as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
memory.map_region(stack_base, STACK_SIZE, MemoryPermissions::READ_WRITE)?;
|
||||
|
||||
// Allocate and initialize Win64 TEB (Thread Environment Block)
|
||||
// Layout in TEB:
|
||||
// +0x08: StackBase (highest address)
|
||||
// +0x10: StackLimit (lowest address)
|
||||
// +0x30: Self pointer (TEB linear address)
|
||||
// +0x58: ThreadLocalStoragePointer
|
||||
let teb_base = layout.tls_base.saturating_add(0x10000);
|
||||
memory.map_region(teb_base, 0x2000, MemoryPermissions::READ_WRITE)?;
|
||||
memory.write_u64_bypass(teb_base + 0x08, layout.stack_top)?;
|
||||
memory.write_u64_bypass(teb_base + 0x10, stack_base)?;
|
||||
memory.write_u64_bypass(teb_base + 0x30, teb_base)?;
|
||||
memory.write_u64_bypass(teb_base + 0x58, layout.tls_base)?;
|
||||
map_teb(memory, teb_base, &layout, stack_base)?;
|
||||
|
||||
let mut engine = DbtEngine::new(JIT_CAPACITY)?;
|
||||
engine.set_import_registry(imports);
|
||||
@@ -171,3 +166,128 @@ pub fn run_synthetic_startup_with_observer(
|
||||
dbt_metrics: engine.metrics,
|
||||
})
|
||||
}
|
||||
|
||||
/// Validate the harness layout and return `(stack_base, teb_base)`.
|
||||
///
|
||||
/// The stack occupies `[stack_top - STACK_SIZE, stack_top)` and the TEB
|
||||
/// `[tls_base + TEB_OFFSET, + TEB_SIZE)`. Both ranges must fit in the address
|
||||
/// space and must not overlap each other.
|
||||
fn layout_regions(layout: &StartupLayout) -> Result<(u64, u64), MemoryError> {
|
||||
let stack_base = layout
|
||||
.stack_top
|
||||
.checked_sub(STACK_SIZE as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
let teb_base = layout
|
||||
.tls_base
|
||||
.checked_add(TEB_OFFSET)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
let teb_end = teb_base
|
||||
.checked_add(TEB_SIZE as u64)
|
||||
.ok_or(MemoryError::Overflow)?;
|
||||
if teb_base < layout.stack_top && stack_base < teb_end {
|
||||
return Err(MemoryError::OverlappingRegion {
|
||||
base: teb_base,
|
||||
size: TEB_SIZE as u64,
|
||||
});
|
||||
}
|
||||
Ok((stack_base, teb_base))
|
||||
}
|
||||
|
||||
/// Map the Win64 TEB and write the fields the harness provides.
|
||||
fn map_teb(
|
||||
memory: &mut crate::GuestMemory,
|
||||
teb_base: u64,
|
||||
layout: &StartupLayout,
|
||||
stack_base: u64,
|
||||
) -> Result<(), MemoryError> {
|
||||
memory.map_region(teb_base, TEB_SIZE, MemoryPermissions::READ_WRITE)?;
|
||||
memory.write_u64_bypass(teb_base + TEB_STACK_BASE, layout.stack_top)?;
|
||||
memory.write_u64_bypass(teb_base + TEB_STACK_LIMIT, stack_base)?;
|
||||
memory.write_u64_bypass(teb_base + TEB_SELF, teb_base)?;
|
||||
memory.write_u64_bypass(teb_base + TEB_TLS_POINTER, layout.tls_base)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::GuestMemory;
|
||||
|
||||
fn layout(stack_top: u64, tls_base: u64) -> StartupLayout {
|
||||
StartupLayout {
|
||||
image_base: 0x1_4000_0000,
|
||||
stack_top,
|
||||
tls_base,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn valid_layout_places_stack_and_teb() {
|
||||
let regions = layout_regions(&layout(0x2_0001_0000, 0x3_0000_0000));
|
||||
assert_eq!(regions, Ok((0x2_0000_0000, 0x3_0001_0000)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stack_below_zero_is_rejected() {
|
||||
assert_eq!(
|
||||
layout_regions(&layout(0x8000, 0x3_0000_0000)),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn teb_address_overflow_is_rejected_not_saturated() {
|
||||
for tls_base in [u64::MAX, u64::MAX - 0xFFFF, u64::MAX - TEB_OFFSET - 0x1FFF] {
|
||||
assert_eq!(
|
||||
layout_regions(&layout(0x2_0001_0000, tls_base)),
|
||||
Err(MemoryError::Overflow),
|
||||
"tls_base {tls_base:#x}"
|
||||
);
|
||||
}
|
||||
// The highest TEB that fits ends at u64::MAX: an end of 2^64 is not
|
||||
// representable, and GuestMemory could not map that range either.
|
||||
let top = u64::MAX - TEB_OFFSET - TEB_SIZE as u64;
|
||||
assert!(layout_regions(&layout(0x2_0001_0000, top)).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn teb_overlapping_stack_is_rejected() {
|
||||
// TEB at 0x2_0000_8000..0x2_0000_A000 lies inside the stack 0x2_0000_0000..0x2_0001_0000.
|
||||
let collide = layout(0x2_0001_0000, 0x1_FFFF_8000);
|
||||
assert!(matches!(
|
||||
layout_regions(&collide),
|
||||
Err(MemoryError::OverlappingRegion { .. })
|
||||
));
|
||||
// Directly above the stack is fine.
|
||||
assert!(layout_regions(&layout(0x2_0001_0000, 0x2_0000_0000)).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_layout_fails_before_parsing() {
|
||||
// Empty bytes would fail PE parsing; the layout error must come first.
|
||||
let err = run_synthetic_startup(
|
||||
&[],
|
||||
layout(0x2_0001_0000, u64::MAX),
|
||||
ImportRegistry::new(),
|
||||
1,
|
||||
)
|
||||
.err()
|
||||
.expect("startup must fail");
|
||||
assert_eq!(
|
||||
err.downcast_ref::<MemoryError>(),
|
||||
Some(&MemoryError::Overflow)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn teb_fields_are_at_win64_offsets() {
|
||||
let l = layout(0x2_0001_0000, 0x3_0000_0000);
|
||||
let (stack_base, teb) = layout_regions(&l).unwrap();
|
||||
let mut memory = GuestMemory::new();
|
||||
map_teb(&mut memory, teb, &l, stack_base).unwrap();
|
||||
assert_eq!(memory.read_u64(teb + 0x08), Ok(0x2_0001_0000));
|
||||
assert_eq!(memory.read_u64(teb + 0x10), Ok(0x2_0000_0000));
|
||||
assert_eq!(memory.read_u64(teb + 0x30), Ok(teb));
|
||||
assert_eq!(memory.read_u64(teb + 0x58), Ok(0x3_0000_0000));
|
||||
assert!(memory.read_u8(teb + TEB_SIZE as u64).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,468 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Shared x86-64 decoder.
|
||||
//!
|
||||
//! The static PE probe, the software interpreter and the native DBT all decode
|
||||
//! through [`decode`], driven by static tables generated from
|
||||
//! `x86/instructions.toml`, so instruction boundaries, operands and rejected
|
||||
//! forms agree across them.
|
||||
|
||||
use crate::x86_table::{
|
||||
FORMS, GROUPS, ONE_BYTE, Op, TWO_BYTE, TWO_BYTE_66, TWO_BYTE_F2, TWO_BYTE_F3,
|
||||
};
|
||||
|
||||
/// Architectural x86-64 instruction length limit, in bytes.
|
||||
///
|
||||
/// An instruction may not exceed 15 bytes (Intel SDM Vol. 2A, "Instruction
|
||||
/// Length"). Sequences longer than this are not decodable and are rejected as
|
||||
/// illegal instructions.
|
||||
pub const MAX_INSTRUCTION_LEN: usize = 15;
|
||||
|
||||
/// Number of leading legacy segment prefix bytes (0x64 FS, 0x65 GS) at the
|
||||
/// start of a code slice, capped at [`MAX_INSTRUCTION_LEN`].
|
||||
///
|
||||
/// The count includes the first byte when it is a segment prefix, so a run of
|
||||
/// more than [`MAX_INSTRUCTION_LEN`] prefixes is reported as
|
||||
/// [`MAX_INSTRUCTION_LEN`].
|
||||
pub fn segment_prefix_len(code: &[u8]) -> usize {
|
||||
let mut len = match code.first() {
|
||||
Some(&0x64 | &0x65) => 1,
|
||||
_ => 0,
|
||||
};
|
||||
while len < MAX_INSTRUCTION_LEN && matches!(code.get(len), Some(&0x64 | &0x65)) {
|
||||
len += 1;
|
||||
}
|
||||
len
|
||||
}
|
||||
|
||||
/// One x86-64 instruction form from the generated registry tables.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Form {
|
||||
pub op: Op,
|
||||
pub encoding: Encoding,
|
||||
pub size: OperandSize,
|
||||
pub immediate: Immediate,
|
||||
/// Source width in bytes when it differs from the operand size, else 0.
|
||||
pub source: u8,
|
||||
pub has_modrm: bool,
|
||||
pub memory_only: bool,
|
||||
pub register_only: bool,
|
||||
pub no_rex_b: bool,
|
||||
/// A 16-byte memory operand may have any alignment.
|
||||
pub unaligned: bool,
|
||||
}
|
||||
|
||||
/// Opcode table entry.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub enum Entry {
|
||||
Unsupported,
|
||||
Form(u16),
|
||||
Group(u16),
|
||||
}
|
||||
|
||||
/// How a form names its operands, destination first.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Encoding {
|
||||
None,
|
||||
RmReg,
|
||||
RegRm,
|
||||
RegRmImm,
|
||||
Rm,
|
||||
RmUnread,
|
||||
RmImm,
|
||||
RmOne,
|
||||
RmCl,
|
||||
AccImm,
|
||||
OpReg,
|
||||
OpRegImm,
|
||||
Imm,
|
||||
Rel,
|
||||
/// XMM `reg` from XMM or memory.
|
||||
XmmRm,
|
||||
/// XMM or memory from XMM `reg`.
|
||||
RmXmm,
|
||||
XmmRmImm,
|
||||
/// XMM `rm` shifted in place by an immediate.
|
||||
RmImmXmm,
|
||||
/// XMM `reg` from a general register or memory.
|
||||
XmmGpr,
|
||||
/// General register or memory from XMM `reg`.
|
||||
GprXmm,
|
||||
XmmGprImm,
|
||||
/// General `reg` from XMM `rm`.
|
||||
RegXmm,
|
||||
RegXmmImm,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum OperandSize {
|
||||
Byte,
|
||||
Variable,
|
||||
Wide,
|
||||
Quad,
|
||||
Xmm,
|
||||
None,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Immediate {
|
||||
None,
|
||||
SignedByte,
|
||||
SignedFull,
|
||||
Signed32,
|
||||
Full,
|
||||
Word,
|
||||
/// Zero-extended byte.
|
||||
Byte,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Segment {
|
||||
Fs,
|
||||
Gs,
|
||||
}
|
||||
|
||||
/// A general or XMM register operand, as the encoding says. `high` selects AH,
|
||||
/// CH, DH or BH of `index`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct RegOperand {
|
||||
pub index: u8,
|
||||
pub high: bool,
|
||||
}
|
||||
|
||||
/// A memory operand. A RIP-relative operand has its absolute address folded
|
||||
/// into `disp` and no base.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct MemOperand {
|
||||
pub base: Option<u8>,
|
||||
pub index: Option<(u8, u8)>,
|
||||
pub disp: i64,
|
||||
pub segment: Option<Segment>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum RmOperand {
|
||||
Reg(RegOperand),
|
||||
Mem(MemOperand),
|
||||
}
|
||||
|
||||
/// A fully decoded instruction at a known address.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Insn {
|
||||
pub op: Op,
|
||||
pub encoding: Encoding,
|
||||
/// Index into [`FORMS`].
|
||||
pub form: u16,
|
||||
/// Guest address of the first byte.
|
||||
pub rip: u64,
|
||||
pub len: u8,
|
||||
/// Operand size in bytes: 1, 2, 4, 8 or 16 (XMM), or 0 when there is none.
|
||||
pub size: u8,
|
||||
/// Width of the ModRM operand in bytes.
|
||||
pub rm_size: u8,
|
||||
pub rm: Option<RmOperand>,
|
||||
/// ModRM `reg` operand, or the register encoded in the opcode.
|
||||
pub reg: RegOperand,
|
||||
/// Sign-extended immediate, or the absolute branch target.
|
||||
pub imm: u64,
|
||||
/// Condition code for Jcc, CMOVcc and SETcc.
|
||||
pub condition: u8,
|
||||
}
|
||||
|
||||
impl Insn {
|
||||
/// Address of the following instruction.
|
||||
pub fn next_rip(&self) -> u64 {
|
||||
self.rip.wrapping_add(u64::from(self.len))
|
||||
}
|
||||
|
||||
/// The memory operand, if any.
|
||||
pub fn memory(&self) -> Option<MemOperand> {
|
||||
match self.rm {
|
||||
Some(RmOperand::Mem(operand)) => Some(operand),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why bytes did not decode.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum DecodeError<E> {
|
||||
/// The byte source refused a fetch.
|
||||
Fetch(E),
|
||||
/// No declared form matches; carries the byte that decided it.
|
||||
Unsupported(u8),
|
||||
}
|
||||
|
||||
struct Cursor<F> {
|
||||
fetch: F,
|
||||
rip: u64,
|
||||
len: usize,
|
||||
last: u8,
|
||||
}
|
||||
|
||||
impl<E, F: FnMut(u64) -> Result<u8, E>> Cursor<F> {
|
||||
fn u8(&mut self) -> Result<u8, DecodeError<E>> {
|
||||
if self.len == MAX_INSTRUCTION_LEN {
|
||||
return Err(DecodeError::Unsupported(self.last));
|
||||
}
|
||||
let byte =
|
||||
(self.fetch)(self.rip.wrapping_add(self.len as u64)).map_err(DecodeError::Fetch)?;
|
||||
self.len += 1;
|
||||
self.last = byte;
|
||||
Ok(byte)
|
||||
}
|
||||
|
||||
/// Little-endian value of `count` bytes.
|
||||
fn bytes(&mut self, count: usize) -> Result<u64, DecodeError<E>> {
|
||||
let mut value = 0;
|
||||
for index in 0..count {
|
||||
value |= u64::from(self.u8()?) << (8 * index);
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
fn signed(&mut self, count: usize) -> Result<u64, DecodeError<E>> {
|
||||
let value = self.bytes(count)?;
|
||||
let shift = 64 - 8 * count as u32;
|
||||
Ok(((value << shift) as i64 >> shift) as u64)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
pub fn decode<E>(
|
||||
rip: u64,
|
||||
fetch: impl FnMut(u64) -> Result<u8, E>,
|
||||
) -> Result<Insn, DecodeError<E>> {
|
||||
let mut cursor = Cursor {
|
||||
fetch,
|
||||
rip,
|
||||
len: 0,
|
||||
last: 0,
|
||||
};
|
||||
let mut operand_size = false;
|
||||
let mut rep = false;
|
||||
let mut repne = false;
|
||||
let mut segment = None;
|
||||
let mut byte = cursor.u8()?;
|
||||
loop {
|
||||
let selected = match byte {
|
||||
0x64 => Segment::Fs,
|
||||
0x65 => Segment::Gs,
|
||||
0x66 => {
|
||||
operand_size = true;
|
||||
byte = cursor.u8()?;
|
||||
continue;
|
||||
}
|
||||
0xF3 => {
|
||||
rep = true;
|
||||
byte = cursor.u8()?;
|
||||
continue;
|
||||
}
|
||||
0xF2 => {
|
||||
repne = 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() => {
|
||||
byte = cursor.u8()?;
|
||||
continue;
|
||||
}
|
||||
_ => break,
|
||||
};
|
||||
// FS and GS together are architecturally undefined (Intel SDM Vol. 2,
|
||||
// "Instruction Prefixes"); the local rule is that GS applies.
|
||||
if segment != Some(Segment::Gs) {
|
||||
segment = Some(selected);
|
||||
}
|
||||
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);
|
||||
|
||||
// F2 and F3 together have no defined meaning for any declared form.
|
||||
if rep && repne {
|
||||
return Err(DecodeError::Unsupported(0xF2));
|
||||
}
|
||||
let two_byte = byte == 0x0F;
|
||||
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) {
|
||||
return Err(DecodeError::Unsupported(if rep { 0xF3 } else { 0xF2 }));
|
||||
}
|
||||
&ONE_BYTE
|
||||
} else if rep {
|
||||
&TWO_BYTE_F3
|
||||
} else if repne {
|
||||
&TWO_BYTE_F2
|
||||
} else if operand_size && !matches!(TWO_BYTE_66[slot], Entry::Unsupported) {
|
||||
// 0x66 selects the form instead of an operand size.
|
||||
operand_size = false;
|
||||
&TWO_BYTE_66
|
||||
} else {
|
||||
&TWO_BYTE
|
||||
};
|
||||
|
||||
let entry = table[slot];
|
||||
let mut modrm = 0;
|
||||
let form_index = match entry {
|
||||
Entry::Unsupported => return Err(DecodeError::Unsupported(opcode)),
|
||||
Entry::Form(index) => index,
|
||||
Entry::Group(index) => {
|
||||
modrm = cursor.u8()?;
|
||||
GROUPS[usize::from(index)][usize::from((modrm >> 3) & 7)]
|
||||
}
|
||||
};
|
||||
let form = FORMS
|
||||
.get(usize::from(form_index))
|
||||
.ok_or(DecodeError::Unsupported(opcode))?;
|
||||
if form.has_modrm && matches!(entry, Entry::Form(_)) {
|
||||
modrm = cursor.u8()?;
|
||||
}
|
||||
|
||||
let size = match form.size {
|
||||
OperandSize::None => 0,
|
||||
OperandSize::Byte => 1,
|
||||
OperandSize::Quad => 8,
|
||||
OperandSize::Xmm => 16,
|
||||
OperandSize::Wide | OperandSize::Variable if rex_w => 8,
|
||||
OperandSize::Variable if operand_size => 2,
|
||||
OperandSize::Wide | OperandSize::Variable => 4,
|
||||
};
|
||||
let takes_operand_size =
|
||||
matches!(form.size, OperandSize::Byte | OperandSize::Variable) || form.op == Op::Nop;
|
||||
// REX.W takes precedence over 0x66 wherever the size is selectable.
|
||||
let overridden = rex_w && form.size == OperandSize::Wide;
|
||||
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 {
|
||||
RegOperand {
|
||||
index: field - 4,
|
||||
high: true,
|
||||
}
|
||||
} else {
|
||||
RegOperand {
|
||||
index: field | extension,
|
||||
high: false,
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let mut rm = None;
|
||||
let mut rip_relative = false;
|
||||
let mut reg = RegOperand {
|
||||
index: 0,
|
||||
high: false,
|
||||
};
|
||||
if form.has_modrm {
|
||||
reg = register((modrm >> 3) & 7, rex_r, size);
|
||||
let mode = modrm >> 6;
|
||||
if mode == 3 {
|
||||
if form.memory_only {
|
||||
return Err(DecodeError::Unsupported(opcode));
|
||||
}
|
||||
rm = Some(RmOperand::Reg(register(modrm & 7, rex_b, rm_size)));
|
||||
} else {
|
||||
if form.register_only {
|
||||
return Err(DecodeError::Unsupported(opcode));
|
||||
}
|
||||
let mut operand = MemOperand {
|
||||
base: Some((modrm & 7) | rex_b),
|
||||
index: None,
|
||||
disp: 0,
|
||||
segment,
|
||||
};
|
||||
let mut low_base = modrm & 7;
|
||||
if low_base == 4 {
|
||||
let sib = cursor.u8()?;
|
||||
low_base = sib & 7;
|
||||
operand.base = Some(low_base | rex_b);
|
||||
// Index 100b means no index unless REX.X selects R12.
|
||||
let index = ((sib >> 3) & 7) | rex_x;
|
||||
operand.index = (index != 4).then_some((index, sib >> 6));
|
||||
} else {
|
||||
rip_relative = mode == 0 && low_base == 5;
|
||||
}
|
||||
if mode == 0 && low_base == 5 {
|
||||
operand.base = None;
|
||||
operand.disp = cursor.signed(4)? as i64;
|
||||
} else if mode != 0 {
|
||||
operand.disp = cursor.signed(if mode == 1 { 1 } else { 4 })? as i64;
|
||||
}
|
||||
rm = Some(RmOperand::Mem(operand));
|
||||
}
|
||||
} else if matches!(form.encoding, Encoding::OpReg | Encoding::OpRegImm) {
|
||||
reg = register(opcode & 7, rex_b, size);
|
||||
}
|
||||
|
||||
let mut imm = match form.immediate {
|
||||
Immediate::None => 0,
|
||||
Immediate::SignedByte => cursor.signed(1)?,
|
||||
Immediate::SignedFull => cursor.signed(usize::from(size.min(4)))?,
|
||||
Immediate::Signed32 => cursor.signed(4)?,
|
||||
Immediate::Full => cursor.bytes(usize::from(size))?,
|
||||
Immediate::Word => cursor.bytes(2)?,
|
||||
Immediate::Byte => cursor.bytes(1)?,
|
||||
};
|
||||
|
||||
let end = rip.wrapping_add(cursor.len as u64);
|
||||
if rip_relative && let Some(RmOperand::Mem(operand)) = &mut rm {
|
||||
operand.disp = end.wrapping_add_signed(operand.disp) as i64;
|
||||
}
|
||||
if form.encoding == Encoding::Rel {
|
||||
imm = end.wrapping_add(imm);
|
||||
}
|
||||
if form.encoding == Encoding::AccImm {
|
||||
reg = RegOperand {
|
||||
index: 0,
|
||||
high: false,
|
||||
};
|
||||
}
|
||||
Ok(Insn {
|
||||
op: form.op,
|
||||
encoding: form.encoding,
|
||||
form: form_index,
|
||||
rip,
|
||||
len: cursor.len as u8,
|
||||
size,
|
||||
rm_size,
|
||||
rm,
|
||||
reg,
|
||||
imm,
|
||||
condition: opcode & 0xF,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{MAX_INSTRUCTION_LEN, segment_prefix_len};
|
||||
|
||||
#[test]
|
||||
fn segment_prefix_len_counts_legacy_segment_prefixes() {
|
||||
assert_eq!(segment_prefix_len(&[]), 0);
|
||||
assert_eq!(segment_prefix_len(&[0x90]), 0);
|
||||
assert_eq!(segment_prefix_len(&[0x65, 0x90]), 1);
|
||||
assert_eq!(segment_prefix_len(&[0x64, 0x65, 0x31, 0xc0]), 2);
|
||||
assert_eq!(segment_prefix_len(&[0x65; 20]), MAX_INSTRUCTION_LEN);
|
||||
assert_eq!(segment_prefix_len(&[0x65; 15]), MAX_INSTRUCTION_LEN);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,621 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Reviewed semantic primitives for decoded x86-64 integer instructions.
|
||||
//!
|
||||
//! The interpreter executes every instruction here. The native DBT calls the
|
||||
//! same code, counted explicitly, for forms it does not lower to ARM64.
|
||||
//!
|
||||
//! Every instruction is all-or-nothing: operands are read and results computed
|
||||
//! first, then memory is written, then registers and flags, so a fault leaves
|
||||
//! 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::memory::GuestMemory;
|
||||
use crate::x86_decode::{Encoding, Insn, MemOperand, RegOperand, RmOperand, Segment};
|
||||
use crate::x86_simd;
|
||||
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 RSP: usize = Register::Rsp as usize;
|
||||
const RBP: usize = Register::Rbp as usize;
|
||||
|
||||
/// Value mask of an operand of `size` bytes.
|
||||
fn mask(size: u8) -> u64 {
|
||||
u64::MAX >> (64 - 8 * u32::from(size))
|
||||
}
|
||||
|
||||
fn sign_bit(size: u8) -> u64 {
|
||||
1 << (8 * u32::from(size) - 1)
|
||||
}
|
||||
|
||||
fn sign_extend(value: u64, size: u8) -> u64 {
|
||||
let shift = 64 - 8 * u32::from(size);
|
||||
((value << shift) as i64 >> shift) as u64
|
||||
}
|
||||
|
||||
/// Effective address including any FS or GS base.
|
||||
pub fn address(cpu: &CpuState, operand: &MemOperand) -> u64 {
|
||||
let base = match operand.segment {
|
||||
Some(Segment::Fs) => cpu.fs_base,
|
||||
Some(Segment::Gs) => cpu.gs_base,
|
||||
None => 0,
|
||||
};
|
||||
base.wrapping_add(offset(cpu, operand))
|
||||
}
|
||||
|
||||
/// Effective address without a segment base, as LEA computes it.
|
||||
fn offset(cpu: &CpuState, operand: &MemOperand) -> u64 {
|
||||
let base = operand.base.map_or(0, |index| cpu.gpr[usize::from(index)]);
|
||||
let index = operand
|
||||
.index
|
||||
.map_or(0, |(index, scale)| cpu.gpr[usize::from(index)] << scale);
|
||||
base.wrapping_add(index).wrapping_add_signed(operand.disp)
|
||||
}
|
||||
|
||||
pub(crate) fn read_reg(cpu: &CpuState, reg: RegOperand, size: u8) -> u64 {
|
||||
let value = cpu.gpr[usize::from(reg.index)];
|
||||
if reg.high {
|
||||
(value >> 8) & 0xFF
|
||||
} else {
|
||||
value & mask(size)
|
||||
}
|
||||
}
|
||||
|
||||
/// Write a register: 8- and 16-bit writes merge, 32-bit writes zero-extend.
|
||||
pub(crate) fn write_reg(cpu: &mut CpuState, reg: RegOperand, size: u8, value: u64) {
|
||||
let slot = &mut cpu.gpr[usize::from(reg.index)];
|
||||
*slot = match (size, reg.high) {
|
||||
(1, true) => (*slot & !0xFF00) | ((value & 0xFF) << 8),
|
||||
(1 | 2, _) => (*slot & !mask(size)) | (value & mask(size)),
|
||||
_ => value & mask(size),
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) fn read_mem(memory: &GuestMemory, address: u64, size: u8) -> Result<u64, ExitReason> {
|
||||
match size {
|
||||
1 => memory.read_u8(address).map(u64::from),
|
||||
2 => memory.read_u16(address).map(u64::from),
|
||||
4 => memory.read_u32(address).map(u64::from),
|
||||
_ => memory.read_u64(address),
|
||||
}
|
||||
.map_err(ExitReason::MemoryFault)
|
||||
}
|
||||
|
||||
pub(crate) fn write_mem(
|
||||
memory: &mut GuestMemory,
|
||||
address: u64,
|
||||
size: u8,
|
||||
value: u64,
|
||||
) -> Result<(), ExitReason> {
|
||||
match size {
|
||||
1 => memory.write_u8(address, value as u8),
|
||||
2 => memory.write_u16(address, value as u16),
|
||||
4 => memory.write_u32(address, value as u32),
|
||||
_ => memory.write_u64(address, value),
|
||||
}
|
||||
.map_err(ExitReason::MemoryFault)
|
||||
}
|
||||
|
||||
pub(crate) fn rm_operand(insn: &Insn) -> Result<RmOperand, ExitReason> {
|
||||
// The decoder supplies a ModRM operand for every form that reaches here.
|
||||
insn.rm.ok_or(ExitReason::IllegalInstruction(0))
|
||||
}
|
||||
|
||||
fn read_rm(cpu: &CpuState, memory: &GuestMemory, insn: &Insn) -> Result<u64, ExitReason> {
|
||||
match rm_operand(insn)? {
|
||||
RmOperand::Reg(reg) => Ok(read_reg(cpu, reg, insn.rm_size)),
|
||||
RmOperand::Mem(operand) => read_mem(memory, address(cpu, &operand), insn.rm_size),
|
||||
}
|
||||
}
|
||||
|
||||
fn write_rm(
|
||||
cpu: &mut CpuState,
|
||||
memory: &mut GuestMemory,
|
||||
insn: &Insn,
|
||||
value: u64,
|
||||
) -> Result<(), ExitReason> {
|
||||
match rm_operand(insn)? {
|
||||
RmOperand::Reg(reg) => write_reg(cpu, reg, insn.rm_size, value),
|
||||
RmOperand::Mem(operand) => {
|
||||
write_mem(memory, address(cpu, &operand), insn.rm_size, value)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// First (destination) and second operand values of a two-operand form.
|
||||
fn operands(cpu: &CpuState, memory: &GuestMemory, insn: &Insn) -> Result<(u64, u64), ExitReason> {
|
||||
let imm = insn.imm & mask(insn.size);
|
||||
Ok(match insn.encoding {
|
||||
Encoding::RmReg => (
|
||||
read_rm(cpu, memory, insn)?,
|
||||
read_reg(cpu, insn.reg, insn.size),
|
||||
),
|
||||
Encoding::RegRm => (
|
||||
read_reg(cpu, insn.reg, insn.size),
|
||||
read_rm(cpu, memory, insn)?,
|
||||
),
|
||||
Encoding::RmImm => (read_rm(cpu, memory, insn)?, imm),
|
||||
Encoding::RmOne => (read_rm(cpu, memory, insn)?, 1),
|
||||
Encoding::RmCl => (read_rm(cpu, memory, insn)?, cpu.gpr[RCX] & 0xFF),
|
||||
Encoding::RegRmImm => (read_rm(cpu, memory, insn)?, imm),
|
||||
Encoding::AccImm => (cpu.gpr[RAX] & mask(insn.size), imm),
|
||||
_ => (read_rm(cpu, memory, insn)?, 0),
|
||||
})
|
||||
}
|
||||
|
||||
/// Store a result in the destination that [`operands`] read first.
|
||||
fn write_dst(
|
||||
cpu: &mut CpuState,
|
||||
memory: &mut GuestMemory,
|
||||
insn: &Insn,
|
||||
value: u64,
|
||||
) -> Result<(), ExitReason> {
|
||||
match insn.encoding {
|
||||
Encoding::RegRm | Encoding::RegRmImm | Encoding::AccImm => {
|
||||
write_reg(cpu, insn.reg, insn.size, value);
|
||||
Ok(())
|
||||
}
|
||||
_ => write_rm(cpu, memory, insn, value),
|
||||
}
|
||||
}
|
||||
|
||||
/// ZF, SF and PF of a result.
|
||||
fn result_flags(flags: &mut RFlags, value: u64, size: u8) {
|
||||
flags.zf = value & mask(size) == 0;
|
||||
flags.sf = value & sign_bit(size) != 0;
|
||||
flags.pf = (value as u8).count_ones().is_multiple_of(2);
|
||||
}
|
||||
|
||||
/// `a + b + carry` with every arithmetic flag.
|
||||
fn add(a: u64, b: u64, carry: bool, size: u8) -> (u64, RFlags) {
|
||||
let wide = u128::from(a) + u128::from(b) + u128::from(carry);
|
||||
let value = wide as u64 & mask(size);
|
||||
let mut flags = RFlags {
|
||||
cf: wide > u128::from(mask(size)),
|
||||
of: (a ^ value) & (b ^ value) & sign_bit(size) != 0,
|
||||
af: (a ^ b ^ value) & 0x10 != 0,
|
||||
..RFlags::default()
|
||||
};
|
||||
result_flags(&mut flags, value, size);
|
||||
(value, flags)
|
||||
}
|
||||
|
||||
/// `a - b - borrow` with every arithmetic flag.
|
||||
fn sub(a: u64, b: u64, borrow: bool, size: u8) -> (u64, RFlags) {
|
||||
let value = a.wrapping_sub(b).wrapping_sub(u64::from(borrow)) & mask(size);
|
||||
let mut flags = RFlags {
|
||||
cf: u128::from(a) < u128::from(b) + u128::from(borrow),
|
||||
of: (a ^ b) & (a ^ value) & sign_bit(size) != 0,
|
||||
af: (a ^ b ^ value) & 0x10 != 0,
|
||||
..RFlags::default()
|
||||
};
|
||||
result_flags(&mut flags, value, size);
|
||||
(value, flags)
|
||||
}
|
||||
|
||||
/// Evaluate an x86 condition code (Intel SDM Vol. 1, appendix B).
|
||||
pub fn condition(flags: &RFlags, code: u8) -> bool {
|
||||
let holds = match code >> 1 {
|
||||
0 => flags.of,
|
||||
1 => flags.cf,
|
||||
2 => flags.zf,
|
||||
3 => flags.cf || flags.zf,
|
||||
4 => flags.sf,
|
||||
5 => flags.pf,
|
||||
6 => flags.sf != flags.of,
|
||||
_ => flags.zf || flags.sf != flags.of,
|
||||
};
|
||||
holds != (code & 1 != 0)
|
||||
}
|
||||
|
||||
/// Shifts and rotates. `None` means a masked count of zero, which changes
|
||||
/// neither the destination nor the flags.
|
||||
fn shift(op: Op, value: u64, count: u64, size: u8, old: RFlags) -> Option<(u64, RFlags)> {
|
||||
let count = (count & if size == 8 { 0x3F } else { 0x1F }) as u32;
|
||||
if count == 0 {
|
||||
return None;
|
||||
}
|
||||
let bits = 8 * u32::from(size);
|
||||
let top = sign_bit(size);
|
||||
let mut flags = old;
|
||||
let wide = u128::from(value);
|
||||
let result = match op {
|
||||
Op::Shl => {
|
||||
let shifted = wide << count;
|
||||
flags.cf = shifted >> bits & 1 != 0;
|
||||
shifted as u64
|
||||
}
|
||||
Op::Shr => {
|
||||
flags.cf = wide >> (count - 1) & 1 != 0;
|
||||
(wide >> count) as u64
|
||||
}
|
||||
Op::Sar => {
|
||||
let signed = i128::from(sign_extend(value, size) as i64);
|
||||
flags.cf = signed >> (count - 1) & 1 != 0;
|
||||
(signed >> count) as u64
|
||||
}
|
||||
_ => {
|
||||
let by = count % bits;
|
||||
let left = if op == Op::Rol {
|
||||
by
|
||||
} else {
|
||||
(bits - by) % bits
|
||||
};
|
||||
let rotated = if left == 0 {
|
||||
value
|
||||
} else {
|
||||
value << left | value >> (bits - left)
|
||||
};
|
||||
flags.cf = rotated & if op == Op::Rol { 1 } else { top } != 0;
|
||||
rotated
|
||||
}
|
||||
} & mask(size);
|
||||
if matches!(op, Op::Shl | Op::Shr | Op::Sar) {
|
||||
result_flags(&mut flags, result, size);
|
||||
// CF after a left or logical right shift by the width or more is
|
||||
// undefined for 8- and 16-bit operands; keep the previous value.
|
||||
if count >= bits && op != Op::Sar {
|
||||
flags.cf = old.cf;
|
||||
}
|
||||
}
|
||||
// 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::Shr => value & top != 0,
|
||||
Op::Sar => false,
|
||||
_ => (result & top != 0) != (result & (top >> 1) != 0),
|
||||
};
|
||||
}
|
||||
Some((result, flags))
|
||||
}
|
||||
|
||||
fn push(cpu: &mut CpuState, memory: &mut GuestMemory, value: u64) -> Result<(), ExitReason> {
|
||||
let sp = cpu.gpr[RSP]
|
||||
.checked_sub(8)
|
||||
.ok_or(ExitReason::StackUnderflow)?;
|
||||
write_mem(memory, sp, 8, value)?;
|
||||
cpu.gpr[RSP] = sp;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Execute one decoded instruction, advancing RIP. On error nothing changes.
|
||||
/// Returns an exit reason when the guest stops voluntarily.
|
||||
pub fn execute(
|
||||
cpu: &mut CpuState,
|
||||
memory: &mut GuestMemory,
|
||||
insn: &Insn,
|
||||
) -> Result<Option<ExitReason>, ExitReason> {
|
||||
let size = insn.size;
|
||||
let mut next = insn.next_rip();
|
||||
match insn.op {
|
||||
Op::Add | Op::Adc | Op::Sub | Op::Sbb | Op::Cmp => {
|
||||
let (a, b) = operands(cpu, memory, insn)?;
|
||||
let carry = cpu.flags.cf;
|
||||
let (value, flags) = match insn.op {
|
||||
Op::Add => add(a, b, false, size),
|
||||
Op::Adc => add(a, b, carry, size),
|
||||
Op::Sbb => sub(a, b, carry, size),
|
||||
_ => sub(a, b, false, size),
|
||||
};
|
||||
if insn.op != Op::Cmp {
|
||||
write_dst(cpu, memory, insn, value)?;
|
||||
}
|
||||
cpu.flags = flags;
|
||||
}
|
||||
Op::And | Op::Or | Op::Xor | Op::Test => {
|
||||
let (a, b) = operands(cpu, memory, insn)?;
|
||||
let value = match insn.op {
|
||||
Op::Or => a | b,
|
||||
Op::Xor => a ^ b,
|
||||
_ => a & b,
|
||||
};
|
||||
if insn.op != Op::Test {
|
||||
write_dst(cpu, memory, insn, value)?;
|
||||
}
|
||||
cpu.flags.cf = false;
|
||||
cpu.flags.of = false;
|
||||
result_flags(&mut cpu.flags, value, size);
|
||||
}
|
||||
Op::Inc | Op::Dec => {
|
||||
let a = read_rm(cpu, memory, insn)?;
|
||||
let (value, mut flags) = if insn.op == Op::Inc {
|
||||
add(a, 1, false, size)
|
||||
} else {
|
||||
sub(a, 1, false, size)
|
||||
};
|
||||
write_rm(cpu, memory, insn, value)?;
|
||||
flags.cf = cpu.flags.cf;
|
||||
cpu.flags = flags;
|
||||
}
|
||||
Op::Neg => {
|
||||
let a = read_rm(cpu, memory, insn)?;
|
||||
let (value, flags) = sub(0, a, false, size);
|
||||
write_rm(cpu, memory, insn, value)?;
|
||||
cpu.flags = flags;
|
||||
}
|
||||
Op::Not => {
|
||||
let a = read_rm(cpu, memory, insn)?;
|
||||
write_rm(cpu, memory, insn, !a & mask(size))?;
|
||||
}
|
||||
Op::Mov => match insn.encoding {
|
||||
Encoding::RmReg => write_rm(cpu, memory, insn, read_reg(cpu, insn.reg, size))?,
|
||||
Encoding::RegRm => {
|
||||
let value = read_rm(cpu, memory, insn)?;
|
||||
write_reg(cpu, insn.reg, size, value);
|
||||
}
|
||||
Encoding::OpRegImm => write_reg(cpu, insn.reg, size, insn.imm),
|
||||
_ => write_rm(cpu, memory, insn, insn.imm & mask(size))?,
|
||||
},
|
||||
Op::Movzx => {
|
||||
let value = read_rm(cpu, memory, insn)?;
|
||||
write_reg(cpu, insn.reg, size, value);
|
||||
}
|
||||
Op::Movsx | Op::Movsxd => {
|
||||
let value = sign_extend(read_rm(cpu, memory, insn)?, insn.rm_size);
|
||||
write_reg(cpu, insn.reg, size, value);
|
||||
}
|
||||
Op::Lea => {
|
||||
if let Some(operand) = insn.memory() {
|
||||
write_reg(cpu, insn.reg, size, offset(cpu, &operand));
|
||||
}
|
||||
}
|
||||
Op::Xchg => {
|
||||
let (a, b) = operands(cpu, memory, insn)?;
|
||||
write_rm(cpu, memory, insn, b)?;
|
||||
write_reg(cpu, insn.reg, size, a);
|
||||
}
|
||||
Op::Bswap => {
|
||||
let value = read_reg(cpu, insn.reg, size).swap_bytes() >> (64 - 8 * u32::from(size));
|
||||
write_reg(cpu, insn.reg, size, value);
|
||||
}
|
||||
Op::Cwde => {
|
||||
// CBW, CWDE and CDQE widen the lower half of the accumulator.
|
||||
let value = sign_extend(cpu.gpr[RAX] & mask(size / 2), size / 2);
|
||||
write_reg(cpu, accumulator(RAX), size, value);
|
||||
}
|
||||
Op::Cdq => {
|
||||
let negative = cpu.gpr[RAX] & sign_bit(size) != 0;
|
||||
write_reg(
|
||||
cpu,
|
||||
accumulator(RDX),
|
||||
size,
|
||||
if negative { mask(size) } else { 0 },
|
||||
);
|
||||
}
|
||||
Op::Rol | Op::Ror | 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)) => {
|
||||
write_rm(cpu, memory, insn, value)?;
|
||||
cpu.flags = flags;
|
||||
}
|
||||
// A zero count still performs the write's permission check and
|
||||
// the 32-bit register zero-extension.
|
||||
None => write_rm(cpu, memory, insn, a)?,
|
||||
}
|
||||
}
|
||||
Op::Mul | Op::Imul => {
|
||||
let factor = read_rm(cpu, memory, insn)?;
|
||||
let acc = cpu.gpr[RAX] & mask(size);
|
||||
let bits = 8 * u32::from(size);
|
||||
let product = if insn.op == Op::Mul {
|
||||
u128::from(acc) * u128::from(factor)
|
||||
} else {
|
||||
(i128::from(sign_extend(acc, size) as i64)
|
||||
* i128::from(sign_extend(factor, size) as i64)) as u128
|
||||
};
|
||||
let low = product as u64 & mask(size);
|
||||
let high = (product >> bits) as u64 & mask(size);
|
||||
if size == 1 {
|
||||
write_reg(cpu, accumulator(RAX), 2, high << 8 | low);
|
||||
} else {
|
||||
write_reg(cpu, accumulator(RAX), size, low);
|
||||
write_reg(cpu, accumulator(RDX), size, high);
|
||||
}
|
||||
let overflow = if insn.op == Op::Mul {
|
||||
high != 0
|
||||
} else {
|
||||
high != if low & sign_bit(size) != 0 {
|
||||
mask(size)
|
||||
} else {
|
||||
0
|
||||
}
|
||||
};
|
||||
cpu.flags.cf = overflow;
|
||||
cpu.flags.of = overflow;
|
||||
}
|
||||
Op::Imul2 => {
|
||||
let (a, b) = operands(cpu, memory, insn)?;
|
||||
let product =
|
||||
i128::from(sign_extend(a, size) as i64) * i128::from(sign_extend(b, size) as i64);
|
||||
let value = product as u64 & mask(size);
|
||||
write_reg(cpu, insn.reg, size, value);
|
||||
let overflow = i128::from(sign_extend(value, size) as i64) != product;
|
||||
cpu.flags.cf = overflow;
|
||||
cpu.flags.of = overflow;
|
||||
}
|
||||
Op::Div | Op::Idiv => divide(cpu, memory, insn)?,
|
||||
Op::Cmov => {
|
||||
// The source is read, and may fault, whatever the condition.
|
||||
let source = read_rm(cpu, memory, insn)?;
|
||||
let value = if condition(&cpu.flags, insn.condition) {
|
||||
source
|
||||
} else {
|
||||
read_reg(cpu, insn.reg, size)
|
||||
};
|
||||
write_reg(cpu, insn.reg, size, value);
|
||||
}
|
||||
Op::Setcc => {
|
||||
let value = u64::from(condition(&cpu.flags, insn.condition));
|
||||
write_rm(cpu, memory, insn, value)?;
|
||||
}
|
||||
Op::Bt | Op::Bts | Op::Btr | Op::Btc => {
|
||||
let (a, index) = operands(cpu, memory, insn)?;
|
||||
let bit = 1u64 << (index & (8 * u64::from(size) - 1));
|
||||
let value = match insn.op {
|
||||
Op::Bts => a | bit,
|
||||
Op::Btr => a & !bit,
|
||||
Op::Btc => a ^ bit,
|
||||
_ => a,
|
||||
};
|
||||
if insn.op != Op::Bt {
|
||||
write_rm(cpu, memory, insn, value)?;
|
||||
}
|
||||
cpu.flags.cf = a & bit != 0;
|
||||
}
|
||||
Op::Bsf | Op::Bsr => {
|
||||
let value = read_rm(cpu, memory, insn)?;
|
||||
cpu.flags.zf = value == 0;
|
||||
// A zero source leaves the destination undefined (SDM) or unchanged
|
||||
// (APM); leave it unchanged.
|
||||
if value != 0 {
|
||||
let index = if insn.op == Op::Bsf {
|
||||
value.trailing_zeros()
|
||||
} else {
|
||||
63 - value.leading_zeros()
|
||||
};
|
||||
write_reg(cpu, insn.reg, size, u64::from(index));
|
||||
}
|
||||
}
|
||||
Op::Popcnt => {
|
||||
let value = read_rm(cpu, memory, insn)?;
|
||||
write_reg(cpu, insn.reg, size, u64::from(value.count_ones()));
|
||||
cpu.flags = RFlags {
|
||||
zf: value == 0,
|
||||
..RFlags::default()
|
||||
};
|
||||
}
|
||||
Op::Tzcnt | Op::Lzcnt => {
|
||||
let value = read_rm(cpu, memory, insn)?;
|
||||
let bits = 8 * u32::from(size);
|
||||
let count = if insn.op == Op::Tzcnt {
|
||||
value.trailing_zeros().min(bits)
|
||||
} else {
|
||||
value.leading_zeros() - (64 - bits)
|
||||
};
|
||||
write_reg(cpu, insn.reg, size, u64::from(count));
|
||||
cpu.flags.cf = value == 0;
|
||||
cpu.flags.zf = count == 0;
|
||||
}
|
||||
Op::Push => {
|
||||
let value = match insn.encoding {
|
||||
Encoding::OpReg => read_reg(cpu, insn.reg, 8),
|
||||
Encoding::Imm => insn.imm,
|
||||
_ => read_rm(cpu, memory, insn)?,
|
||||
};
|
||||
push(cpu, memory, value)?;
|
||||
}
|
||||
Op::Pop => {
|
||||
let old = cpu.gpr[RSP];
|
||||
let value = read_mem(memory, old, 8)?;
|
||||
// A memory destination based on RSP uses the incremented value.
|
||||
cpu.gpr[RSP] = old.wrapping_add(8);
|
||||
if insn.encoding == Encoding::OpReg {
|
||||
write_reg(cpu, insn.reg, 8, value);
|
||||
} else if let Err(fault) = write_rm(cpu, memory, insn, value) {
|
||||
cpu.gpr[RSP] = old;
|
||||
return Err(fault);
|
||||
}
|
||||
}
|
||||
Op::Leave => {
|
||||
let frame = cpu.gpr[RBP];
|
||||
cpu.gpr[RBP] = read_mem(memory, frame, 8)?;
|
||||
cpu.gpr[RSP] = frame.wrapping_add(8);
|
||||
}
|
||||
Op::Call => {
|
||||
let target = branch_target(cpu, memory, insn)?;
|
||||
push(cpu, memory, next)?;
|
||||
next = target;
|
||||
}
|
||||
Op::Jmp => next = branch_target(cpu, memory, insn)?,
|
||||
Op::Jcc => {
|
||||
if condition(&cpu.flags, insn.condition) {
|
||||
next = insn.imm;
|
||||
}
|
||||
}
|
||||
Op::Ret => {
|
||||
let sp = cpu.gpr[RSP];
|
||||
next = read_mem(memory, sp, 8)?;
|
||||
cpu.gpr[RSP] = sp.wrapping_add(8).wrapping_add(insn.imm);
|
||||
}
|
||||
Op::Nop => {}
|
||||
Op::Clc => cpu.flags.cf = false,
|
||||
Op::Stc => cpu.flags.cf = true,
|
||||
Op::Cmc => cpu.flags.cf = !cpu.flags.cf,
|
||||
Op::Hlt => {
|
||||
cpu.rip = next;
|
||||
return Ok(Some(ExitReason::Halt));
|
||||
}
|
||||
Op::Syscall => {
|
||||
cpu.rip = next;
|
||||
return Ok(Some(ExitReason::Syscall(cpu.gpr[RAX])));
|
||||
}
|
||||
_ => x86_simd::execute(cpu, memory, insn)?,
|
||||
}
|
||||
cpu.rip = next;
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
fn accumulator(index: usize) -> RegOperand {
|
||||
RegOperand {
|
||||
index: index as u8,
|
||||
high: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn branch_target(cpu: &CpuState, memory: &GuestMemory, insn: &Insn) -> Result<u64, ExitReason> {
|
||||
if insn.encoding == Encoding::Rel {
|
||||
Ok(insn.imm)
|
||||
} else {
|
||||
read_rm(cpu, memory, insn)
|
||||
}
|
||||
}
|
||||
|
||||
/// DIV and IDIV. A zero divisor or a quotient that does not fit raises #DE.
|
||||
fn divide(cpu: &mut CpuState, memory: &GuestMemory, insn: &Insn) -> Result<(), ExitReason> {
|
||||
let size = insn.size;
|
||||
let divisor = read_rm(cpu, memory, insn)?;
|
||||
if divisor == 0 {
|
||||
return Err(ExitReason::DivideError);
|
||||
}
|
||||
let bits = 8 * u32::from(size);
|
||||
let dividend = if size == 1 {
|
||||
u128::from(cpu.gpr[RAX] & 0xFFFF)
|
||||
} else {
|
||||
u128::from(cpu.gpr[RDX] & mask(size)) << bits | u128::from(cpu.gpr[RAX] & mask(size))
|
||||
};
|
||||
let (quotient, remainder) = if insn.op == Op::Div {
|
||||
let divisor = u128::from(divisor);
|
||||
let quotient = dividend / divisor;
|
||||
if quotient > u128::from(mask(size)) {
|
||||
return Err(ExitReason::DivideError);
|
||||
}
|
||||
(quotient as u64, (dividend % divisor) as u64)
|
||||
} else {
|
||||
let unused = 128 - 2 * bits;
|
||||
let dividend = (dividend << unused) as i128 >> unused;
|
||||
let divisor = i128::from(sign_extend(divisor, size) as i64);
|
||||
// Only i128::MIN / -1 overflows i128, and it overflows #DE too.
|
||||
let quotient = dividend
|
||||
.checked_div(divisor)
|
||||
.ok_or(ExitReason::DivideError)?;
|
||||
let limit = i128::from(sign_bit(size));
|
||||
if quotient < -limit || quotient >= limit {
|
||||
return Err(ExitReason::DivideError);
|
||||
}
|
||||
(quotient as u64, (dividend % divisor) as u64)
|
||||
};
|
||||
if size == 1 {
|
||||
let value = (remainder & 0xFF) << 8 | quotient & 0xFF;
|
||||
write_reg(cpu, accumulator(RAX), 2, value);
|
||||
} else {
|
||||
write_reg(cpu, accumulator(RAX), size, quotient);
|
||||
write_reg(cpu, accumulator(RDX), size, remainder);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! SSE and SSE2 floating-point instructions over [`crate::softfloat`].
|
||||
//!
|
||||
//! Exceptions accumulate in MXCSR. If any is unmasked the instruction has no
|
||||
//! other effect and exits with [`ExitReason::SimdException`]; pre-computation
|
||||
//! exceptions in any lane are considered before post-computation ones.
|
||||
|
||||
use crate::cpu::{CpuState, ExitReason, RFlags};
|
||||
use crate::memory::GuestMemory;
|
||||
use crate::softfloat::{
|
||||
Arithmetic, Control, F32, F64, Format, Outcome, PRE_COMPUTATION, arithmetic, compare, convert,
|
||||
from_integer, square_root, to_integer,
|
||||
};
|
||||
use crate::x86_decode::{Insn, RmOperand};
|
||||
use crate::x86_exec::{address, read_mem, read_reg, rm_operand, write_reg};
|
||||
use crate::x86_simd::{lane, read_rm};
|
||||
use crate::x86_table::Op;
|
||||
use std::cmp::Ordering;
|
||||
|
||||
/// Exception flags collected over the lanes of one instruction.
|
||||
#[derive(Default)]
|
||||
struct Raised(u32);
|
||||
|
||||
impl Raised {
|
||||
fn take(&mut self, outcome: Outcome) -> u64 {
|
||||
self.0 |= outcome.flags;
|
||||
outcome.bits
|
||||
}
|
||||
|
||||
/// Record the flags in MXCSR, failing if an unmasked one was raised.
|
||||
fn commit(&self, cpu: &mut CpuState) -> Result<(), ExitReason> {
|
||||
let masks = cpu.mxcsr.0 >> 7 & 0x3F;
|
||||
let before = self.0 & PRE_COMPUTATION;
|
||||
if before & !masks != 0 {
|
||||
cpu.mxcsr.0 |= before;
|
||||
return Err(ExitReason::SimdException);
|
||||
}
|
||||
cpu.mxcsr.0 |= self.0;
|
||||
if self.0 & !masks != 0 {
|
||||
return Err(ExitReason::SimdException);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Kind {
|
||||
Arithmetic(Arithmetic),
|
||||
SquareRoot,
|
||||
Compare,
|
||||
}
|
||||
|
||||
/// Operation, format and whether only the low lane is involved.
|
||||
fn classify(op: Op) -> Option<(Kind, Format, bool)> {
|
||||
use Arithmetic::{Add, Div, Max, Min, Mul, Sub};
|
||||
use Kind::{Arithmetic as A, Compare, SquareRoot};
|
||||
Some(match op {
|
||||
Op::Addps => (A(Add), F32, false),
|
||||
Op::Addpd => (A(Add), F64, false),
|
||||
Op::Addss => (A(Add), F32, true),
|
||||
Op::Addsd => (A(Add), F64, true),
|
||||
Op::Subps => (A(Sub), F32, false),
|
||||
Op::Subpd => (A(Sub), F64, false),
|
||||
Op::Subss => (A(Sub), F32, true),
|
||||
Op::Subsd => (A(Sub), F64, true),
|
||||
Op::Mulps => (A(Mul), F32, false),
|
||||
Op::Mulpd => (A(Mul), F64, false),
|
||||
Op::Mulss => (A(Mul), F32, true),
|
||||
Op::Mulsd => (A(Mul), F64, true),
|
||||
Op::Divps => (A(Div), F32, false),
|
||||
Op::Divpd => (A(Div), F64, false),
|
||||
Op::Divss => (A(Div), F32, true),
|
||||
Op::Divsd => (A(Div), F64, true),
|
||||
Op::Minps => (A(Min), F32, false),
|
||||
Op::Minpd => (A(Min), F64, false),
|
||||
Op::Minss => (A(Min), F32, true),
|
||||
Op::Minsd => (A(Min), F64, true),
|
||||
Op::Maxps => (A(Max), F32, false),
|
||||
Op::Maxpd => (A(Max), F64, false),
|
||||
Op::Maxss => (A(Max), F32, true),
|
||||
Op::Maxsd => (A(Max), F64, true),
|
||||
Op::Sqrtps => (SquareRoot, F32, false),
|
||||
Op::Sqrtpd => (SquareRoot, F64, false),
|
||||
Op::Sqrtss => (SquareRoot, F32, true),
|
||||
Op::Sqrtsd => (SquareRoot, F64, true),
|
||||
Op::Cmpps => (Compare, F32, false),
|
||||
Op::Cmppd => (Compare, F64, false),
|
||||
Op::Cmpss => (Compare, F32, true),
|
||||
Op::Cmpsd => (Compare, F64, true),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Source format, destination format and lane count of a vector conversion;
|
||||
/// `None` for an integer side.
|
||||
fn conversion(op: Op) -> Option<(Option<Format>, Option<Format>, u32)> {
|
||||
Some(match op {
|
||||
Op::Cvtps2pd => (Some(F32), Some(F64), 2),
|
||||
Op::Cvtpd2ps => (Some(F64), Some(F32), 2),
|
||||
Op::Cvtss2sd => (Some(F32), Some(F64), 1),
|
||||
Op::Cvtsd2ss => (Some(F64), Some(F32), 1),
|
||||
Op::Cvtdq2ps => (None, Some(F32), 4),
|
||||
Op::Cvtdq2pd => (None, Some(F64), 2),
|
||||
Op::Cvtps2dq | Op::Cvttps2dq => (Some(F32), None, 4),
|
||||
Op::Cvtpd2dq | Op::Cvttpd2dq => (Some(F64), None, 2),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// CMPccPS predicate: a relation, optionally negated. Bit 2 negates; LT and LE
|
||||
/// and their negations signal on quiet NaNs.
|
||||
fn predicate(format: Format, a: u64, b: u64, code: u64, control: &Control) -> Outcome {
|
||||
let relation = code & 3;
|
||||
let signaling = matches!(relation, 1 | 2);
|
||||
let (order, flags) = compare(format, a, b, signaling, control);
|
||||
let holds = match relation {
|
||||
0 => order == Some(Ordering::Equal),
|
||||
1 => order == Some(Ordering::Less),
|
||||
2 => matches!(order, Some(Ordering::Less | Ordering::Equal)),
|
||||
_ => order.is_none(),
|
||||
};
|
||||
Outcome {
|
||||
bits: if holds != (code & 4 != 0) {
|
||||
u64::MAX
|
||||
} else {
|
||||
0
|
||||
},
|
||||
flags,
|
||||
}
|
||||
}
|
||||
|
||||
fn low_bits(bits: u32) -> u128 {
|
||||
(1 << bits) - 1
|
||||
}
|
||||
|
||||
/// Place `value` in lane `index` of `bits`.
|
||||
fn insert(target: &mut u128, value: u64, bits: u32, index: u32) {
|
||||
let shift = bits * index;
|
||||
let mask = low_bits(bits) << shift;
|
||||
*target = (*target & !mask) | ((u128::from(value) << shift) & mask);
|
||||
}
|
||||
|
||||
/// Execute a floating-point instruction, or return `false` if it is not one.
|
||||
pub(crate) fn execute(
|
||||
cpu: &mut CpuState,
|
||||
memory: &GuestMemory,
|
||||
insn: &Insn,
|
||||
) -> Result<bool, ExitReason> {
|
||||
let control = Control::from_mxcsr(cpu.mxcsr.0);
|
||||
let reg = usize::from(insn.reg.index);
|
||||
let mut raised = Raised::default();
|
||||
|
||||
if let Some((kind, format, scalar)) = classify(insn.op) {
|
||||
let source = read_rm(cpu, memory, insn)?;
|
||||
let old = cpu.xmm[reg];
|
||||
let mut result = old;
|
||||
let count = if scalar { 1 } else { 128 / format.bits };
|
||||
for index in 0..count {
|
||||
let a = lane(old, format.bits, index);
|
||||
let b = lane(source, format.bits, index);
|
||||
let outcome = match kind {
|
||||
Kind::Arithmetic(kind) => arithmetic(kind, format, a, b, &control),
|
||||
Kind::SquareRoot => square_root(format, b, &control),
|
||||
// Legacy encodings define only predicates 0-7.
|
||||
Kind::Compare => predicate(format, a, b, insn.imm & 7, &control),
|
||||
};
|
||||
insert(&mut result, raised.take(outcome), format.bits, index);
|
||||
}
|
||||
raised.commit(cpu)?;
|
||||
cpu.xmm[reg] = result;
|
||||
return Ok(true);
|
||||
}
|
||||
|
||||
if let Some((from, to, count)) = conversion(insn.op) {
|
||||
let source = read_rm(cpu, memory, insn)?;
|
||||
let truncate = matches!(insn.op, Op::Cvttps2dq | Op::Cvttpd2dq);
|
||||
let merges = matches!(insn.op, Op::Cvtss2sd | Op::Cvtsd2ss);
|
||||
let mut result = if merges { cpu.xmm[reg] } else { 0 };
|
||||
for index in 0..count {
|
||||
let value = lane(source, from.map_or(32, |format| format.bits), index);
|
||||
let outcome = match (from, to) {
|
||||
(Some(from), Some(to)) => convert(from, to, value, &control),
|
||||
(None, Some(to)) => from_integer(to, i64::from(value as u32 as i32), &control),
|
||||
(Some(from), None) => to_integer(from, value, 32, truncate, &control),
|
||||
(None, None) => Outcome { bits: 0, flags: 0 },
|
||||
};
|
||||
let width = to.map_or(32, |format| format.bits);
|
||||
insert(&mut result, raised.take(outcome), width, index);
|
||||
}
|
||||
raised.commit(cpu)?;
|
||||
cpu.xmm[reg] = result;
|
||||
return Ok(true);
|
||||
}
|
||||
|
||||
match insn.op {
|
||||
Op::Cvtsi2ss | Op::Cvtsi2sd => {
|
||||
let value = match rm_operand(insn)? {
|
||||
RmOperand::Reg(source) => read_reg(cpu, source, insn.size),
|
||||
RmOperand::Mem(operand) => read_mem(memory, address(cpu, &operand), insn.size)?,
|
||||
};
|
||||
let integer = if insn.size == 8 {
|
||||
value as i64
|
||||
} else {
|
||||
i64::from(value as u32 as i32)
|
||||
};
|
||||
let format = if insn.op == Op::Cvtsi2ss { F32 } else { F64 };
|
||||
let bits = raised.take(from_integer(format, integer, &control));
|
||||
raised.commit(cpu)?;
|
||||
insert(&mut cpu.xmm[reg], bits, format.bits, 0);
|
||||
}
|
||||
Op::Cvtss2si | Op::Cvttss2si | Op::Cvtsd2si | Op::Cvttsd2si => {
|
||||
let format = if matches!(insn.op, Op::Cvtss2si | Op::Cvttss2si) {
|
||||
F32
|
||||
} else {
|
||||
F64
|
||||
};
|
||||
let truncate = matches!(insn.op, Op::Cvttss2si | Op::Cvttsd2si);
|
||||
let value = lane(read_rm(cpu, memory, insn)?, format.bits, 0);
|
||||
let bits = 8 * u32::from(insn.size);
|
||||
let integer = raised.take(to_integer(format, value, bits, truncate, &control));
|
||||
raised.commit(cpu)?;
|
||||
write_reg(cpu, insn.reg, insn.size, integer);
|
||||
}
|
||||
Op::Comiss | Op::Comisd | Op::Ucomiss | Op::Ucomisd => {
|
||||
let format = if matches!(insn.op, Op::Comiss | Op::Ucomiss) {
|
||||
F32
|
||||
} else {
|
||||
F64
|
||||
};
|
||||
let signaling = matches!(insn.op, Op::Comiss | Op::Comisd);
|
||||
let a = lane(cpu.xmm[reg], format.bits, 0);
|
||||
let b = lane(read_rm(cpu, memory, insn)?, format.bits, 0);
|
||||
let (order, flags) = compare(format, a, b, signaling, &control);
|
||||
raised.0 |= flags;
|
||||
raised.commit(cpu)?;
|
||||
cpu.flags = RFlags {
|
||||
zf: matches!(order, None | Some(Ordering::Equal)),
|
||||
pf: order.is_none(),
|
||||
cf: matches!(order, None | Some(Ordering::Less)),
|
||||
..RFlags::default()
|
||||
};
|
||||
}
|
||||
_ => return Ok(false),
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Semantic primitives for the SSE and SSE2 moves and packed integer forms.
|
||||
//!
|
||||
//! Lane 0 is the least significant. Every instruction is all-or-nothing and none
|
||||
//! changes RFLAGS. Floating-point arithmetic is in [`crate::x86_float`].
|
||||
|
||||
use crate::cpu::{CpuState, ExitReason, Mxcsr};
|
||||
use crate::memory::GuestMemory;
|
||||
use crate::x86_decode::{Encoding, Insn, RegOperand, RmOperand};
|
||||
use crate::x86_exec::{address, read_mem, read_reg, rm_operand, write_mem, write_reg};
|
||||
use crate::x86_float;
|
||||
use crate::x86_table::{FORMS, Op};
|
||||
|
||||
fn lane_mask(bits: u32) -> u128 {
|
||||
(1 << bits) - 1
|
||||
}
|
||||
|
||||
pub(crate) fn lane(value: u128, bits: u32, index: u32) -> u64 {
|
||||
((value >> (bits * index)) & lane_mask(bits)) as u64
|
||||
}
|
||||
|
||||
/// Signed value of a lane of `bits`.
|
||||
fn signed(value: u64, bits: u32) -> i64 {
|
||||
(value << (64 - bits)) as i64 >> (64 - bits)
|
||||
}
|
||||
|
||||
/// Build a vector from a function of the lane index.
|
||||
fn build(bits: u32, f: impl Fn(u32) -> u64) -> u128 {
|
||||
(0..128 / bits).fold(0, |out, index| {
|
||||
out | (u128::from(f(index)) & lane_mask(bits)) << (bits * index)
|
||||
})
|
||||
}
|
||||
|
||||
fn map(a: u128, b: u128, bits: u32, f: impl Fn(u64, u64) -> u64) -> u128 {
|
||||
build(bits, |index| f(lane(a, bits, index), lane(b, bits, index)))
|
||||
}
|
||||
|
||||
fn map_signed(a: u128, b: u128, bits: u32, f: impl Fn(i64, i64) -> i64) -> u128 {
|
||||
map(a, b, bits, |x, y| {
|
||||
f(signed(x, bits), signed(y, bits)) as u64
|
||||
})
|
||||
}
|
||||
|
||||
fn all_ones(condition: bool) -> u64 {
|
||||
if condition { u64::MAX } else { 0 }
|
||||
}
|
||||
|
||||
/// Clamp to the signed range of `bits`.
|
||||
fn saturate(value: i64, bits: u32) -> i64 {
|
||||
let limit = 1i64 << (bits - 1);
|
||||
value.clamp(-limit, limit - 1)
|
||||
}
|
||||
|
||||
/// Clamp to the unsigned range of `bits`.
|
||||
fn saturate_unsigned(value: i64, bits: u32) -> i64 {
|
||||
value.clamp(0, (1 << bits) - 1)
|
||||
}
|
||||
|
||||
/// Narrow the lanes of `a` then `b`, each `bits` wide, to half width.
|
||||
fn pack(a: u128, b: u128, bits: u32, narrow: impl Fn(i64, u32) -> i64) -> u128 {
|
||||
let count = 128 / bits;
|
||||
build(bits / 2, |index| {
|
||||
let source = if index < count { a } else { b };
|
||||
narrow(signed(lane(source, bits, index % count), bits), bits / 2) as u64
|
||||
})
|
||||
}
|
||||
|
||||
/// Interleave the low or high halves of `a` and `b`.
|
||||
fn unpack(a: u128, b: u128, bits: u32, high: bool) -> u128 {
|
||||
let start = if high { 64 / bits } else { 0 };
|
||||
build(bits, |index| {
|
||||
let source = if index % 2 == 0 { a } else { b };
|
||||
lane(source, bits, start + index / 2)
|
||||
})
|
||||
}
|
||||
|
||||
/// Select lanes of `bits` by two-bit fields of `imm`, reading `a` for the low
|
||||
/// half of the result and `b` for the high half.
|
||||
fn shuffle_32(a: u128, b: u128, imm: u64) -> u128 {
|
||||
build(32, |index| {
|
||||
let source = if index < 2 { a } else { b };
|
||||
lane(source, 32, (imm >> (2 * index) & 3) as u32)
|
||||
})
|
||||
}
|
||||
|
||||
/// Shuffle the four words starting at word `start`, keeping the other four.
|
||||
fn shuffle_16(value: u128, imm: u64, start: u32) -> u128 {
|
||||
build(16, |index| {
|
||||
if (start..start + 4).contains(&index) {
|
||||
lane(value, 16, start + (imm >> (2 * (index - start)) & 3) as u32)
|
||||
} else {
|
||||
lane(value, 16, index)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Logical or arithmetic shift of every lane; counts past the width give zero
|
||||
/// or, for arithmetic shifts, copies of the sign.
|
||||
fn shift(op: Op, value: u128, count: u64) -> u128 {
|
||||
let (bits, kind) = match op {
|
||||
Op::Psllw => (16, 0),
|
||||
Op::Pslld => (32, 0),
|
||||
Op::Psllq => (64, 0),
|
||||
Op::Psrlw => (16, 1),
|
||||
Op::Psrld => (32, 1),
|
||||
Op::Psrlq => (64, 1),
|
||||
Op::Psraw => (16, 2),
|
||||
_ => (32, 2),
|
||||
};
|
||||
let over = count >= u64::from(bits);
|
||||
map(value, 0, bits, |x, _| match kind {
|
||||
0 if !over => x << count,
|
||||
1 if !over => x >> count,
|
||||
2 => (signed(x, bits) >> count.min(u64::from(bits) - 1)) as u64,
|
||||
_ => 0,
|
||||
})
|
||||
}
|
||||
|
||||
fn shift_bytes(value: u128, count: u64, left: bool) -> u128 {
|
||||
if count > 15 {
|
||||
0
|
||||
} else if left {
|
||||
value << (8 * count)
|
||||
} else {
|
||||
value >> (8 * count)
|
||||
}
|
||||
}
|
||||
|
||||
/// Result of a two-source packed operation.
|
||||
fn packed(op: Op, a: u128, b: u128) -> u128 {
|
||||
match op {
|
||||
Op::Pand => a & b,
|
||||
Op::Pandn => !a & b,
|
||||
Op::Por => a | b,
|
||||
Op::Pxor => a ^ b,
|
||||
Op::Paddb => map(a, b, 8, u64::wrapping_add),
|
||||
Op::Paddw => map(a, b, 16, u64::wrapping_add),
|
||||
Op::Paddd => map(a, b, 32, u64::wrapping_add),
|
||||
Op::Paddq => map(a, b, 64, u64::wrapping_add),
|
||||
Op::Psubb => map(a, b, 8, u64::wrapping_sub),
|
||||
Op::Psubw => map(a, b, 16, u64::wrapping_sub),
|
||||
Op::Psubd => map(a, b, 32, u64::wrapping_sub),
|
||||
Op::Psubq => map(a, b, 64, u64::wrapping_sub),
|
||||
Op::Paddsb => map_signed(a, b, 8, |x, y| saturate(x + y, 8)),
|
||||
Op::Paddsw => map_signed(a, b, 16, |x, y| saturate(x + y, 16)),
|
||||
Op::Psubsb => map_signed(a, b, 8, |x, y| saturate(x - y, 8)),
|
||||
Op::Psubsw => map_signed(a, b, 16, |x, y| saturate(x - y, 16)),
|
||||
Op::Paddusb => map(a, b, 8, |x, y| (x + y).min(0xFF)),
|
||||
Op::Paddusw => map(a, b, 16, |x, y| (x + y).min(0xFFFF)),
|
||||
Op::Psubusb => map(a, b, 8, u64::saturating_sub),
|
||||
Op::Psubusw => map(a, b, 16, u64::saturating_sub),
|
||||
Op::Pcmpeqb => map(a, b, 8, |x, y| all_ones(x == y)),
|
||||
Op::Pcmpeqw => map(a, b, 16, |x, y| all_ones(x == y)),
|
||||
Op::Pcmpeqd => map(a, b, 32, |x, y| all_ones(x == y)),
|
||||
Op::Pcmpgtb => map_signed(a, b, 8, |x, y| all_ones(x > y) as i64),
|
||||
Op::Pcmpgtw => map_signed(a, b, 16, |x, y| all_ones(x > y) as i64),
|
||||
Op::Pcmpgtd => map_signed(a, b, 32, |x, y| all_ones(x > y) as i64),
|
||||
Op::Pminub => map(a, b, 8, u64::min),
|
||||
Op::Pmaxub => map(a, b, 8, u64::max),
|
||||
Op::Pminsw => map_signed(a, b, 16, i64::min),
|
||||
Op::Pmaxsw => map_signed(a, b, 16, i64::max),
|
||||
Op::Pavgb => map(a, b, 8, |x, y| (x + y + 1) >> 1),
|
||||
Op::Pavgw => map(a, b, 16, |x, y| (x + y + 1) >> 1),
|
||||
Op::Pmullw => map(a, b, 16, u64::wrapping_mul),
|
||||
Op::Pmulhw => map_signed(a, b, 16, |x, y| (x * y) >> 16),
|
||||
Op::Pmulhuw => map(a, b, 16, |x, y| (x * y) >> 16),
|
||||
Op::Pmuludq => map(a, b, 64, |x, y| (x & 0xFFFF_FFFF) * (y & 0xFFFF_FFFF)),
|
||||
Op::Pmaddwd => build(32, |index| {
|
||||
let product = |at| signed(lane(a, 16, at), 16) * signed(lane(b, 16, at), 16);
|
||||
(product(2 * index) + product(2 * index + 1)) as u64
|
||||
}),
|
||||
Op::Psadbw => build(64, |half| {
|
||||
(0..8)
|
||||
.map(|at| lane(a, 8, 8 * half + at).abs_diff(lane(b, 8, 8 * half + at)))
|
||||
.sum()
|
||||
}),
|
||||
Op::Packsswb => pack(a, b, 16, saturate),
|
||||
Op::Packssdw => pack(a, b, 32, saturate),
|
||||
Op::Packuswb => pack(a, b, 16, saturate_unsigned),
|
||||
Op::Punpcklbw => unpack(a, b, 8, false),
|
||||
Op::Punpcklwd => unpack(a, b, 16, false),
|
||||
Op::Punpckldq => unpack(a, b, 32, false),
|
||||
Op::Punpcklqdq => unpack(a, b, 64, false),
|
||||
Op::Punpckhbw => unpack(a, b, 8, true),
|
||||
Op::Punpckhwd => unpack(a, b, 16, true),
|
||||
Op::Punpckhdq => unpack(a, b, 32, true),
|
||||
Op::Punpckhqdq => unpack(a, b, 64, true),
|
||||
// Vector counts are the low 64 bits of the source.
|
||||
_ => shift(op, a, b as u64),
|
||||
}
|
||||
}
|
||||
|
||||
fn low_mask(size: u8) -> u128 {
|
||||
if size == 16 {
|
||||
u128::MAX
|
||||
} else {
|
||||
(1 << (8 * u32::from(size))) - 1
|
||||
}
|
||||
}
|
||||
|
||||
/// Address of the memory operand, checked for 16-byte alignment where required.
|
||||
fn aligned_address(cpu: &CpuState, insn: &Insn) -> Result<Option<u64>, ExitReason> {
|
||||
let Some(operand) = insn.memory() else {
|
||||
return Ok(None);
|
||||
};
|
||||
let address = address(cpu, &operand);
|
||||
let unaligned = FORMS[usize::from(insn.form)].unaligned;
|
||||
if insn.rm_size == 16 && !unaligned && !address.is_multiple_of(16) {
|
||||
return Err(ExitReason::GeneralProtection);
|
||||
}
|
||||
Ok(Some(address))
|
||||
}
|
||||
|
||||
fn read_vector(memory: &GuestMemory, address: u64, size: u8) -> Result<u128, ExitReason> {
|
||||
if size < 16 {
|
||||
return read_mem(memory, address, size).map(u128::from);
|
||||
}
|
||||
let mut bytes = [0; 16];
|
||||
memory
|
||||
.read_bytes(address, &mut bytes)
|
||||
.map_err(ExitReason::MemoryFault)?;
|
||||
Ok(u128::from_le_bytes(bytes))
|
||||
}
|
||||
|
||||
fn write_vector(
|
||||
memory: &mut GuestMemory,
|
||||
address: u64,
|
||||
size: u8,
|
||||
value: u128,
|
||||
) -> Result<(), ExitReason> {
|
||||
if size < 16 {
|
||||
return write_mem(memory, address, size, value as u64);
|
||||
}
|
||||
memory
|
||||
.write_bytes(address, &value.to_le_bytes())
|
||||
.map_err(ExitReason::MemoryFault)
|
||||
}
|
||||
|
||||
fn xmm(reg: RegOperand) -> usize {
|
||||
usize::from(reg.index)
|
||||
}
|
||||
|
||||
/// Full XMM register, or zero-extended memory, named by ModRM `rm`.
|
||||
pub(crate) fn read_rm(
|
||||
cpu: &CpuState,
|
||||
memory: &GuestMemory,
|
||||
insn: &Insn,
|
||||
) -> Result<u128, ExitReason> {
|
||||
match (aligned_address(cpu, insn)?, rm_operand(insn)?) {
|
||||
(Some(address), _) => read_vector(memory, address, insn.rm_size),
|
||||
(None, RmOperand::Reg(reg)) => Ok(cpu.xmm[xmm(reg)]),
|
||||
(None, RmOperand::Mem(_)) => Err(ExitReason::IllegalInstruction(0)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Execute a vector instruction. RIP is advanced by the caller.
|
||||
pub(crate) fn execute(
|
||||
cpu: &mut CpuState,
|
||||
memory: &mut GuestMemory,
|
||||
insn: &Insn,
|
||||
) -> Result<(), ExitReason> {
|
||||
if x86_float::execute(cpu, memory, insn)? {
|
||||
return Ok(());
|
||||
}
|
||||
let reg = xmm(insn.reg);
|
||||
let in_memory = insn.memory().is_some();
|
||||
match (insn.op, insn.encoding) {
|
||||
(Op::Ldmxcsr, _) => {
|
||||
let value = read_rm(cpu, memory, insn)? as u32;
|
||||
if value & !Mxcsr::WRITABLE != 0 {
|
||||
return Err(ExitReason::GeneralProtection);
|
||||
}
|
||||
cpu.mxcsr = Mxcsr(value);
|
||||
}
|
||||
(Op::Stmxcsr, _) => {
|
||||
if let Some(address) = aligned_address(cpu, insn)? {
|
||||
write_mem(memory, address, 4, u64::from(cpu.mxcsr.0))?;
|
||||
}
|
||||
}
|
||||
(Op::Movd, Encoding::XmmGpr) => {
|
||||
let value = match rm_operand(insn)? {
|
||||
RmOperand::Reg(source) => read_reg(cpu, source, insn.size),
|
||||
RmOperand::Mem(operand) => read_mem(memory, address(cpu, &operand), insn.size)?,
|
||||
};
|
||||
cpu.xmm[reg] = u128::from(value);
|
||||
}
|
||||
(Op::Movd, _) => {
|
||||
let value = cpu.xmm[reg] as u64;
|
||||
match rm_operand(insn)? {
|
||||
RmOperand::Reg(target) => write_reg(cpu, target, insn.size, value),
|
||||
RmOperand::Mem(operand) => {
|
||||
write_mem(memory, address(cpu, &operand), insn.size, value)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
(Op::Pinsrw, _) => {
|
||||
let value = match rm_operand(insn)? {
|
||||
RmOperand::Reg(source) => read_reg(cpu, source, 2),
|
||||
RmOperand::Mem(operand) => read_mem(memory, address(cpu, &operand), 2)?,
|
||||
};
|
||||
let shift = 16 * (insn.imm & 7);
|
||||
cpu.xmm[reg] = cpu.xmm[reg] & !(0xFFFF << shift) | u128::from(value) << shift;
|
||||
}
|
||||
(Op::Pextrw, _) => {
|
||||
let value = lane(read_rm(cpu, memory, insn)?, 16, (insn.imm & 7) as u32);
|
||||
write_reg(cpu, insn.reg, insn.size, value);
|
||||
}
|
||||
(Op::Movmskps | Op::Movmskpd | Op::Pmovmskb, _) => {
|
||||
let bits = match insn.op {
|
||||
Op::Movmskps => 32,
|
||||
Op::Movmskpd => 64,
|
||||
_ => 8,
|
||||
};
|
||||
let value = read_rm(cpu, memory, insn)?;
|
||||
let signs = (0..128 / bits).fold(0, |out, index| {
|
||||
out | (lane(value, bits, index) >> (bits - 1)) << index
|
||||
});
|
||||
write_reg(cpu, insn.reg, insn.size, signs);
|
||||
}
|
||||
// MOVHLPS and MOVLHPS are the register forms of these opcodes.
|
||||
(Op::Movlps, Encoding::XmmRm) => {
|
||||
let source = read_rm(cpu, memory, insn)?;
|
||||
let low = if in_memory { source } else { source >> 64 };
|
||||
cpu.xmm[reg] = cpu.xmm[reg] & !low_mask(8) | low;
|
||||
}
|
||||
(Op::Movhps, Encoding::XmmRm) => {
|
||||
let source = read_rm(cpu, memory, insn)?;
|
||||
cpu.xmm[reg] = cpu.xmm[reg] & low_mask(8) | source << 64;
|
||||
}
|
||||
(Op::Movhps, _) => {
|
||||
if let Some(address) = aligned_address(cpu, insn)? {
|
||||
write_vector(memory, address, 8, cpu.xmm[reg] >> 64)?;
|
||||
}
|
||||
}
|
||||
// Scalar loads from memory clear the rest of the register; between
|
||||
// registers MOVSS and MOVSD merge and MOVQ clears.
|
||||
(Op::Movss | Op::Movsd, Encoding::XmmRm) if !in_memory => {
|
||||
let mask = low_mask(insn.rm_size);
|
||||
let source = read_rm(cpu, memory, insn)?;
|
||||
cpu.xmm[reg] = cpu.xmm[reg] & !mask | source & mask;
|
||||
}
|
||||
(
|
||||
Op::Movaps | Op::Movups | Op::Movdqa | Op::Movdqu | Op::Movss | Op::Movsd | Op::Movq,
|
||||
Encoding::XmmRm,
|
||||
) => {
|
||||
cpu.xmm[reg] = read_rm(cpu, memory, insn)? & low_mask(insn.rm_size);
|
||||
}
|
||||
(_, Encoding::RmXmm) => {
|
||||
let mask = low_mask(insn.rm_size);
|
||||
let value = cpu.xmm[reg] & mask;
|
||||
match (aligned_address(cpu, insn)?, rm_operand(insn)?) {
|
||||
(Some(address), _) => write_vector(memory, address, insn.rm_size, value)?,
|
||||
(None, RmOperand::Reg(target)) => {
|
||||
let target = &mut cpu.xmm[xmm(target)];
|
||||
*target = match insn.op {
|
||||
Op::Movq => value,
|
||||
_ => *target & !mask | value,
|
||||
};
|
||||
}
|
||||
(None, RmOperand::Mem(_)) => return Err(ExitReason::IllegalInstruction(0)),
|
||||
}
|
||||
}
|
||||
(_, Encoding::RmImmXmm) => {
|
||||
if let RmOperand::Reg(target) = rm_operand(insn)? {
|
||||
let target = &mut cpu.xmm[xmm(target)];
|
||||
*target = match insn.op {
|
||||
Op::Psrldq => shift_bytes(*target, insn.imm, false),
|
||||
Op::Pslldq => shift_bytes(*target, insn.imm, true),
|
||||
op => shift(op, *target, insn.imm),
|
||||
};
|
||||
}
|
||||
}
|
||||
(_, Encoding::XmmRmImm) => {
|
||||
let source = read_rm(cpu, memory, insn)?;
|
||||
let old = cpu.xmm[reg];
|
||||
let imm = insn.imm;
|
||||
cpu.xmm[reg] = match insn.op {
|
||||
Op::Pshufd => shuffle_32(source, source, imm),
|
||||
Op::Pshuflw => shuffle_16(source, imm, 0),
|
||||
Op::Pshufhw => shuffle_16(source, imm, 4),
|
||||
Op::Shufps => shuffle_32(old, source, imm),
|
||||
_ => build(64, |index| {
|
||||
let from = if index == 0 { old } else { source };
|
||||
lane(from, 64, (imm >> index & 1) as u32)
|
||||
}),
|
||||
};
|
||||
}
|
||||
(op, _) => {
|
||||
let source = read_rm(cpu, memory, insn)?;
|
||||
cpu.xmm[reg] = packed(op, cpu.xmm[reg], source);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,166 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Assembler encodings against LLVM (`clang -target arm64-apple-macos -c`, read
|
||||
//! back with `objdump -d`).
|
||||
|
||||
use xenora_loader::Arm64Assembler;
|
||||
use xenora_loader::arm64::Condition;
|
||||
|
||||
type Emit = fn(&mut Arm64Assembler);
|
||||
|
||||
#[test]
|
||||
fn flag_and_byte_operations_match_llvm() {
|
||||
let cases: &[(&str, Emit, u32)] = &[
|
||||
("cset w0, hs", |a| a.cset_32(0, Condition::Cs), 0x1a9f37e0),
|
||||
("cset w12, vs", |a| a.cset_32(12, Condition::Vs), 0x1a9f77ec),
|
||||
("cset w30, eq", |a| a.cset_32(30, Condition::Eq), 0x1a9f17fe),
|
||||
(
|
||||
"csel x9, x10, x11, ne",
|
||||
|a| a.csel_64(9, 10, 11, Condition::Ne),
|
||||
0x9a8b1149,
|
||||
),
|
||||
(
|
||||
"csel x0, x30, x17, lt",
|
||||
|a| a.csel_64(0, 30, 17, Condition::Lt),
|
||||
0x9a91b3c0,
|
||||
),
|
||||
(
|
||||
"strb w0, [x19, #136]",
|
||||
|a| a.strb_uoff(0, 19, 136),
|
||||
0x39022260,
|
||||
),
|
||||
(
|
||||
"strb wzr, [x19, #141]",
|
||||
|a| a.strb_uoff(31, 19, 141),
|
||||
0x3902367f,
|
||||
),
|
||||
(
|
||||
"ldrb w12, [x19, #140]",
|
||||
|a| a.ldrb_uoff(12, 19, 140),
|
||||
0x3942326c,
|
||||
),
|
||||
(
|
||||
"eor w12, w11, w10, lsr #4",
|
||||
|a| a.eor_lsr_32(12, 11, 10, 4),
|
||||
0x4a4a116c,
|
||||
),
|
||||
(
|
||||
"eor w1, w2, w3, lsr #0",
|
||||
|a| a.eor_lsr_32(1, 2, 3, 0),
|
||||
0x4a430041,
|
||||
),
|
||||
(
|
||||
"orr w12, w13, w14",
|
||||
|a| a.orr_reg_32(12, 13, 14),
|
||||
0x2a0e01ac,
|
||||
),
|
||||
(
|
||||
"bic w12, w13, w14",
|
||||
|a| a.bic_reg_32(12, 13, 14),
|
||||
0x0a2e01ac,
|
||||
),
|
||||
("mvn x11, x9", |a| a.mvn_64(11, 9), 0xaa2903eb),
|
||||
("mvn x0, x30", |a| a.mvn_64(0, 30), 0xaa3e03e0),
|
||||
(
|
||||
"ubfx w12, w13, #4, #1",
|
||||
|a| a.ubfx_bit_32(12, 13, 4),
|
||||
0x530411ac,
|
||||
),
|
||||
("rev x10, x9", |a| a.rev(10, 9, true), 0xdac00d2a),
|
||||
("rev w0, w30", |a| a.rev(0, 30, false), 0x5ac00bc0),
|
||||
("lsr x0, x0, #8", |a| a.lsr_imm_64(0, 0, 8), 0xd348fc00),
|
||||
("lsr x9, x30, #63", |a| a.lsr_imm_64(9, 30, 63), 0xd37fffc9),
|
||||
("sxtb w9, w10", |a| a.sxtb_32(9, 10), 0x13001d49),
|
||||
("sxtb w30, w0", |a| a.sxtb_32(30, 0), 0x13001c1e),
|
||||
("sxth w9, w10", |a| a.sxth_32(9, 10), 0x13003d49),
|
||||
("sxth w0, w30", |a| a.sxth_32(0, 30), 0x13003fc0),
|
||||
];
|
||||
for (text, emit, word) in cases {
|
||||
let mut assembler = Arm64Assembler::new();
|
||||
emit(&mut assembler);
|
||||
assert_eq!(assembler.instructions(), [*word], "{text}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_operations_match_llvm() {
|
||||
let cases: &[(&str, Emit, u32)] = &[
|
||||
(
|
||||
"ldr q1, [x19, #160]",
|
||||
|a| a.ldr_q_uoff(1, 19, 160),
|
||||
0x3dc02a61,
|
||||
),
|
||||
(
|
||||
"str q0, [x19, #400]",
|
||||
|a| a.str_q_uoff(0, 19, 400),
|
||||
0x3d806660,
|
||||
),
|
||||
("fmov d1, x0", |a| a.fmov_d_from_x(1, 0), 0x9e670001),
|
||||
("mov v1.d[1], x1", |a| a.ins_d1_from_x(1, 1), 0x4e181c21),
|
||||
(
|
||||
"and v0.16b, v1.16b, v2.16b",
|
||||
|a| a.neon3(0x4e20_1c00, 0, 1, 2),
|
||||
0x4e221c20,
|
||||
),
|
||||
(
|
||||
"sub v31.2d, v30.2d, v29.2d",
|
||||
|a| a.neon3(0x6ee0_8400, 31, 30, 29),
|
||||
0x6efd87df,
|
||||
),
|
||||
(
|
||||
"shl v0.8h, v1.8h, #0",
|
||||
|a| a.shl_vector(0, 1, 16, 0),
|
||||
0x4f105420,
|
||||
),
|
||||
(
|
||||
"shl v0.8h, v1.8h, #15",
|
||||
|a| a.shl_vector(0, 1, 16, 15),
|
||||
0x4f1f5420,
|
||||
),
|
||||
(
|
||||
"shl v2.4s, v3.4s, #31",
|
||||
|a| a.shl_vector(2, 3, 32, 31),
|
||||
0x4f3f5462,
|
||||
),
|
||||
(
|
||||
"shl v4.2d, v5.2d, #63",
|
||||
|a| a.shl_vector(4, 5, 64, 63),
|
||||
0x4f7f54a4,
|
||||
),
|
||||
(
|
||||
"ushr v0.8h, v1.8h, #1",
|
||||
|a| a.ushr_vector(0, 1, 16, 1),
|
||||
0x6f1f0420,
|
||||
),
|
||||
(
|
||||
"ushr v0.8h, v1.8h, #16",
|
||||
|a| a.ushr_vector(0, 1, 16, 16),
|
||||
0x6f100420,
|
||||
),
|
||||
(
|
||||
"ushr v2.4s, v3.4s, #32",
|
||||
|a| a.ushr_vector(2, 3, 32, 32),
|
||||
0x6f200462,
|
||||
),
|
||||
(
|
||||
"ushr v4.2d, v5.2d, #64",
|
||||
|a| a.ushr_vector(4, 5, 64, 64),
|
||||
0x6f4004a4,
|
||||
),
|
||||
(
|
||||
"sshr v0.8h, v1.8h, #16",
|
||||
|a| a.sshr_vector(0, 1, 16, 16),
|
||||
0x4f100420,
|
||||
),
|
||||
(
|
||||
"sshr v2.4s, v3.4s, #5",
|
||||
|a| a.sshr_vector(2, 3, 32, 5),
|
||||
0x4f3b0462,
|
||||
),
|
||||
];
|
||||
for (text, emit, word) in cases {
|
||||
let mut assembler = Arm64Assembler::new();
|
||||
emit(&mut assembler);
|
||||
assert_eq!(assembler.instructions(), [*word], "{text}");
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
//! End-to-end integration tests for Xenora X12: PE32+ loading & x86-64 execution bootstrap.
|
||||
|
||||
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, Register};
|
||||
use xenora_loader::memory::{MemoryError, MemoryPermissions};
|
||||
use xenora_loader::memory::{GuestMemory, MemoryError, MemoryPermissions};
|
||||
use xenora_loader::pe::{
|
||||
IMAGE_FILE_MACHINE_AMD64, IMAGE_SCN_MEM_EXECUTE, IMAGE_SCN_MEM_READ, PE32_PLUS_MAGIC, ParsedPe,
|
||||
};
|
||||
@@ -289,3 +289,423 @@ fn test_sib_addressing_mode() {
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
assert_eq!(result.final_state.get(Register::Rdx), 0x12345678_9abcdef0);
|
||||
}
|
||||
|
||||
/// Base address of the read-write data region used by the SIB tests.
|
||||
const DATA_BASE: u64 = 0x6000_0000;
|
||||
/// Base address of the read-write stack region used by the SIB tests.
|
||||
const STACK_BASE: u64 = 0x5000_0000;
|
||||
|
||||
/// Run `code` on the interpreter with a writable stack and a writable data
|
||||
/// region, and return the final state, the exit reason and the guest memory.
|
||||
///
|
||||
/// `DATA_BASE` is mapped read-write so a test can observe where a store
|
||||
/// landed. `STACK_BASE` holds the stack pointer.
|
||||
fn run_with_regions(code: &[u8]) -> (CpuState, ExitReason, GuestMemory) {
|
||||
let pe_bytes = build_synthetic_pe32_plus(code);
|
||||
let parsed = ParsedPe::parse(&pe_bytes).expect("parse");
|
||||
let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load");
|
||||
|
||||
loaded
|
||||
.memory
|
||||
.map_region(STACK_BASE, 0x10000, MemoryPermissions::READ_WRITE)
|
||||
.expect("stack mapping should succeed");
|
||||
loaded
|
||||
.memory
|
||||
.map_region(DATA_BASE, 0x10000, MemoryPermissions::READ_WRITE)
|
||||
.expect("data mapping should succeed");
|
||||
|
||||
let cpu = CpuState::new(loaded.entry_point, STACK_BASE + 0x8000);
|
||||
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 100);
|
||||
let result = interp.run();
|
||||
(result.final_state, result.exit_reason, loaded.memory)
|
||||
}
|
||||
|
||||
/// `mov rax, DATA_BASE` (48 B8 <imm64>).
|
||||
fn mov_rax_data_base() -> Vec<u8> {
|
||||
let mut code = vec![0x48, 0xB8];
|
||||
code.extend_from_slice(&DATA_BASE.to_le_bytes());
|
||||
code
|
||||
}
|
||||
|
||||
/// `mov rbx, 0x12345678_9abcdef0` (48 BB <imm64>).
|
||||
fn mov_rbx_value() -> Vec<u8> {
|
||||
let mut code = vec![0x48, 0xBB];
|
||||
code.extend_from_slice(&0x1234_5678_9abc_def0u64.to_le_bytes());
|
||||
code
|
||||
}
|
||||
|
||||
/// A SIB index register is extended by REX.X, not by REX.R.
|
||||
///
|
||||
/// The encoding 4A 89 1C E0 is `mov [rax + r12*8], rbx`. Its REX prefix sets
|
||||
/// REX.X, so the SIB index field 100b selects r12 and the store lands at
|
||||
/// `rax + r12*8`. REX.R is clear in this prefix, so the ModRM `reg` field is
|
||||
/// rbx.
|
||||
#[test]
|
||||
fn test_rex_x_extends_the_sib_index_register() {
|
||||
// mov rax, DATA_BASE (48 b8 <imm64>)
|
||||
// mov r12, 4 (41 bc 04 00 00 00)
|
||||
// mov rbx, 0x12345678_9abcdef0 (48 bb <imm64>)
|
||||
// mov [rax + r12*8], rbx (4a 89 1c e0)
|
||||
// hlt (f4)
|
||||
let mut code = mov_rax_data_base();
|
||||
code.extend_from_slice(&[0x41, 0xBC, 0x04, 0x00, 0x00, 0x00]); // mov r12d, 4
|
||||
code.extend_from_slice(&mov_rbx_value());
|
||||
code.extend_from_slice(&[0x4A, 0x89, 0x1C, 0xE0]); // mov [rax + r12*8], rbx
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
let (_state, reason, memory) = run_with_regions(&code);
|
||||
assert_eq!(reason, ExitReason::Halt);
|
||||
// r12 holds 4, so the store lands at DATA_BASE + 4*8.
|
||||
assert_eq!(
|
||||
memory.read_u64(DATA_BASE + 32).expect("indexed slot"),
|
||||
0x1234_5678_9abc_def0
|
||||
);
|
||||
// The unindexed slot at DATA_BASE must be untouched.
|
||||
assert_eq!(memory.read_u64(DATA_BASE).expect("base slot"), 0);
|
||||
}
|
||||
|
||||
/// REX.R and REX.X extend independent fields in the same instruction.
|
||||
///
|
||||
/// The encoding 4C 89 1C C8 is `mov [rax + rcx*8], r11`. Its REX prefix sets
|
||||
/// REX.R, so the ModRM `reg` field 011 selects r11. It does not set REX.X, so
|
||||
/// the SIB index field 001 selects rcx and must not be extended to r9.
|
||||
#[test]
|
||||
fn test_rex_r_does_not_extend_the_sib_index_register() {
|
||||
// mov rax, DATA_BASE (48 b8 <imm64>)
|
||||
// mov r11, 0x11223344_55667788 (49 bb <imm64>)
|
||||
// mov ecx, 4 (b9 04 00 00 00)
|
||||
// mov r9, 8 (41 b9 08 00 00 00)
|
||||
// mov [rax + rcx*8], r11 (4c 89 1c c8)
|
||||
// hlt (f4)
|
||||
let mut code = mov_rax_data_base();
|
||||
let mut r11 = vec![0x49, 0xBB];
|
||||
r11.extend_from_slice(&0x1122_3344_5566_7788u64.to_le_bytes());
|
||||
code.extend_from_slice(&r11);
|
||||
code.extend_from_slice(&[0xB9, 0x04, 0x00, 0x00, 0x00]); // mov ecx, 4
|
||||
code.extend_from_slice(&[0x41, 0xB9, 0x08, 0x00, 0x00, 0x00]); // mov r9d, 8
|
||||
code.extend_from_slice(&[0x4C, 0x89, 0x1C, 0xC8]); // mov [rax + rcx*8], r11
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
let (_state, reason, memory) = run_with_regions(&code);
|
||||
assert_eq!(reason, ExitReason::Halt);
|
||||
// rcx holds 4, so the store lands at DATA_BASE + 4*8. A wrongly extended
|
||||
// index would have selected r9 and landed at DATA_BASE + 8*8.
|
||||
assert_eq!(
|
||||
memory.read_u64(DATA_BASE + 32).expect("indexed slot"),
|
||||
0x1122_3344_5566_7788
|
||||
);
|
||||
assert_eq!(memory.read_u64(DATA_BASE + 64).expect("r9 slot"), 0);
|
||||
}
|
||||
|
||||
/// REX.R and REX.X set together extend their own fields independently.
|
||||
///
|
||||
/// The encoding 4E 89 1C E0 is `mov [rax + r12*8], r11`. Its REX prefix sets
|
||||
/// both REX.R and REX.X: the ModRM `reg` field 011 becomes r11 and the SIB
|
||||
/// index field 100b becomes r12.
|
||||
#[test]
|
||||
fn test_rex_r_and_rex_x_set_together_extend_independent_fields() {
|
||||
// mov rax, DATA_BASE (48 b8 <imm64>)
|
||||
// mov r11, 0x11223344_55667788 (49 bb <imm64>)
|
||||
// mov r12, 4 (41 bc 04 00 00 00)
|
||||
// mov [rax + r12*8], r11 (4e 89 1c e0)
|
||||
// hlt (f4)
|
||||
let mut code = mov_rax_data_base();
|
||||
let mut r11 = vec![0x49, 0xBB];
|
||||
r11.extend_from_slice(&0x1122_3344_5566_7788u64.to_le_bytes());
|
||||
code.extend_from_slice(&r11);
|
||||
code.extend_from_slice(&[0x41, 0xBC, 0x04, 0x00, 0x00, 0x00]); // mov r12d, 4
|
||||
code.extend_from_slice(&[0x4E, 0x89, 0x1C, 0xE0]); // mov [rax + r12*8], r11
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
let (_state, reason, memory) = run_with_regions(&code);
|
||||
assert_eq!(reason, ExitReason::Halt);
|
||||
assert_eq!(
|
||||
memory.read_u64(DATA_BASE + 32).expect("indexed slot"),
|
||||
0x1122_3344_5566_7788
|
||||
);
|
||||
assert_eq!(memory.read_u64(DATA_BASE).expect("base slot"), 0);
|
||||
}
|
||||
|
||||
/// Without REX.X, a SIB index field of 100b means "no index register" and the
|
||||
/// address is the base alone.
|
||||
///
|
||||
/// The encoding 48 89 1C 24 is `mov [rsp], rbx`: the SIB index field is 100b
|
||||
/// and REX.X is clear, so no index register contributes to the address.
|
||||
#[test]
|
||||
fn test_sib_index_field_100b_without_rex_x_means_no_index() {
|
||||
// mov rbx, 0x12345678_9abcdef0 (48 bb <imm64>)
|
||||
// mov r12, 0x1000 (41 bc 00 10 00 00)
|
||||
// mov [rsp], rbx (48 89 1c 24)
|
||||
// hlt (f4)
|
||||
let mut code = mov_rbx_value();
|
||||
code.extend_from_slice(&[0x41, 0xBC, 0x00, 0x10, 0x00, 0x00]); // mov r12d, 0x1000
|
||||
code.extend_from_slice(&[0x48, 0x89, 0x1C, 0x24]); // mov [rsp], rbx
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
let pe_bytes = build_synthetic_pe32_plus(&code);
|
||||
let parsed = ParsedPe::parse(&pe_bytes).expect("parse");
|
||||
let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load");
|
||||
loaded
|
||||
.memory
|
||||
.map_region(STACK_BASE, 0x10000, MemoryPermissions::READ_WRITE)
|
||||
.expect("stack mapping should succeed");
|
||||
|
||||
let cpu = CpuState::new(loaded.entry_point, STACK_BASE + 0x8000);
|
||||
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 100);
|
||||
let result = interp.run();
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
|
||||
// The index is absent, so the address is the base (rsp) alone.
|
||||
let stack_top = STACK_BASE + 0x8000;
|
||||
assert_eq!(
|
||||
loaded.memory.read_u64(stack_top).expect("base slot"),
|
||||
0x1234_5678_9abc_def0
|
||||
);
|
||||
}
|
||||
|
||||
/// Build a guest program that loads `value` into `rdi` and then runs `body`.
|
||||
///
|
||||
/// `mov rdi, imm64` is 48 BF <imm64>.
|
||||
fn program_with_rdi(value: u64, body: &[u8]) -> Vec<u8> {
|
||||
let mut code = vec![0x48, 0xBF];
|
||||
code.extend_from_slice(&value.to_le_bytes());
|
||||
code.extend_from_slice(body);
|
||||
code.push(0xF4); // hlt
|
||||
code
|
||||
}
|
||||
|
||||
/// Run `code` on the interpreter and return the final state and exit reason.
|
||||
fn run_interpreter(code: &[u8]) -> (CpuState, ExitReason) {
|
||||
let pe_bytes = build_synthetic_pe32_plus(code);
|
||||
let parsed = ParsedPe::parse(&pe_bytes).expect("parse");
|
||||
let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load");
|
||||
loaded
|
||||
.memory
|
||||
.map_region(STACK_BASE, 0x10000, MemoryPermissions::READ_WRITE)
|
||||
.expect("stack mapping should succeed");
|
||||
loaded
|
||||
.memory
|
||||
.map_region(DATA_BASE, 0x10000, MemoryPermissions::READ_WRITE)
|
||||
.expect("data mapping should succeed");
|
||||
|
||||
let cpu = CpuState::new(loaded.entry_point, STACK_BASE + 0x8000);
|
||||
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 100);
|
||||
let result = interp.run();
|
||||
(result.final_state, result.exit_reason)
|
||||
}
|
||||
|
||||
/// MOVZX with a register source, for both destination widths.
|
||||
///
|
||||
/// The encodings are `movzbl eax, bl` (0F B6 C3) and
|
||||
/// `movzbq rdx, bl` (48 0F B6 D3), as produced by LLVM 23.1.6
|
||||
/// `llvm-mc -show-encoding`. A zero extension always produces a zero-extended
|
||||
/// value, so the 32-bit form clears the upper half of rax while the 64-bit
|
||||
/// form produces the same 64-bit value.
|
||||
#[test]
|
||||
fn test_movzx_register_source_zero_extends() {
|
||||
// mov rbx, 0xffffffffffffffff (48 BB <imm64>)
|
||||
let mut code = vec![0x48, 0xBB];
|
||||
code.extend_from_slice(&u64::MAX.to_le_bytes());
|
||||
code.extend_from_slice(&[0x0F, 0xB6, 0xC3]); // movzbl eax, bl
|
||||
code.extend_from_slice(&[0x48, 0x0F, 0xB6, 0xD3]); // movzbq rdx, bl
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
let (state, reason) = run_interpreter(&code);
|
||||
assert_eq!(reason, ExitReason::Halt);
|
||||
// The 32-bit destination holds a zero-extended byte: 0x00000000000000ff.
|
||||
assert_eq!(state.get(Register::Rax), 0x0000_0000_0000_00ff);
|
||||
// The 64-bit destination holds the same zero-extended value.
|
||||
assert_eq!(state.get(Register::Rdx), 0x0000_0000_0000_00ff);
|
||||
}
|
||||
|
||||
/// MOVSX with a register source, for both destination widths.
|
||||
///
|
||||
/// The encodings are `movsbl eax, bl` (0F BE C3) and
|
||||
/// `movsbq rdx, bl` (48 0F BE D3), as produced by LLVM 23.1.6
|
||||
/// `llvm-mc -show-encoding`. A sign extension reaches the destination width,
|
||||
/// so the 32-bit form keeps the sign in bits 31:0 and clears the upper half,
|
||||
/// while the 64-bit form sign-extends across all 64 bits.
|
||||
#[test]
|
||||
fn test_movsx_register_source_sign_extends_to_the_destination_width() {
|
||||
// mov rbx, 0xffffffffffffffff (48 BB <imm64>)
|
||||
let mut code = vec![0x48, 0xBB];
|
||||
code.extend_from_slice(&u64::MAX.to_le_bytes());
|
||||
code.extend_from_slice(&[0x0F, 0xBE, 0xC3]); // movsbl eax, bl
|
||||
code.extend_from_slice(&[0x48, 0x0F, 0xBE, 0xD3]); // movsbq rdx, bl
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
let (state, reason) = run_interpreter(&code);
|
||||
assert_eq!(reason, ExitReason::Halt);
|
||||
// The 32-bit destination holds 0xffffffff and its upper half is cleared.
|
||||
assert_eq!(state.get(Register::Rax), 0x0000_0000_ffff_ffff);
|
||||
// The 64-bit destination keeps the sign extension across all 64 bits.
|
||||
assert_eq!(state.get(Register::Rdx), 0xffff_ffff_ffff_ffff);
|
||||
}
|
||||
|
||||
/// MOVSX from a 16-bit source sign-extends to the destination width.
|
||||
///
|
||||
/// The encodings are `movswl eax, bx` (0F BF C3) and
|
||||
/// `movswq rdx, bx` (48 0F BF D3), as produced by LLVM 23.1.6
|
||||
/// `llvm-mc -show-encoding`.
|
||||
#[test]
|
||||
fn test_movsx_word_register_source_sign_extends() {
|
||||
// mov rbx, 0xffffffffffffffff (48 BB <imm64>)
|
||||
let mut code = vec![0x48, 0xBB];
|
||||
code.extend_from_slice(&u64::MAX.to_le_bytes());
|
||||
code.extend_from_slice(&[0x0F, 0xBF, 0xC3]); // movswl eax, bx
|
||||
code.extend_from_slice(&[0x48, 0x0F, 0xBF, 0xD3]); // movswq rdx, bx
|
||||
code.push(0xF4); // hlt
|
||||
|
||||
let (state, reason) = run_interpreter(&code);
|
||||
assert_eq!(reason, ExitReason::Halt);
|
||||
assert_eq!(state.get(Register::Rax), 0x0000_0000_ffff_ffff);
|
||||
assert_eq!(state.get(Register::Rdx), 0xffff_ffff_ffff_ffff);
|
||||
}
|
||||
|
||||
/// MOVZX with a memory source reads only the low byte of the operand.
|
||||
///
|
||||
/// The encodings are `movzbl eax, byte [rdi]` (0F B6 07) and
|
||||
/// `movzbq rdx, byte [rdi]` (48 0F B6 17), as produced by LLVM 23.1.6
|
||||
/// `llvm-mc -show-encoding`.
|
||||
#[test]
|
||||
fn test_movzx_memory_source_reads_one_byte() {
|
||||
// mov rdi, DATA_BASE (48 BF <imm64>)
|
||||
// movzbl eax, byte [rdi] (0F B6 07)
|
||||
// movzbq rdx, byte [rdi] (48 0F B6 17)
|
||||
let code = program_with_rdi(DATA_BASE, &[0x0F, 0xB6, 0x07, 0x48, 0x0F, 0xB6, 0x17]);
|
||||
|
||||
let pe_bytes = build_synthetic_pe32_plus(&code);
|
||||
let parsed = ParsedPe::parse(&pe_bytes).expect("parse");
|
||||
let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load");
|
||||
loaded
|
||||
.memory
|
||||
.map_region(STACK_BASE, 0x10000, MemoryPermissions::READ_WRITE)
|
||||
.expect("stack mapping should succeed");
|
||||
loaded
|
||||
.memory
|
||||
.map_region(DATA_BASE, 0x10000, MemoryPermissions::READ_WRITE)
|
||||
.expect("data mapping should succeed");
|
||||
// The byte at the source address has the high bit set, so a sign
|
||||
// extension would produce a negative value and a zero extension must not.
|
||||
loaded
|
||||
.memory
|
||||
.write_u8(DATA_BASE, 0xFF)
|
||||
.expect("source byte");
|
||||
|
||||
let cpu = CpuState::new(loaded.entry_point, STACK_BASE + 0x8000);
|
||||
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 100);
|
||||
let result = interp.run();
|
||||
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
assert_eq!(result.final_state.get(Register::Rax), 0x0000_0000_0000_00ff);
|
||||
assert_eq!(result.final_state.get(Register::Rdx), 0x0000_0000_0000_00ff);
|
||||
}
|
||||
|
||||
/// MOVSX with a memory source sign-extends the byte that was read.
|
||||
///
|
||||
/// The encodings are `movsbl eax, byte [rdi]` (0F BE 07) and
|
||||
/// `movsbq rdx, byte [rdi]` (48 0F BE 17), as produced by LLVM 23.1.6
|
||||
/// `llvm-mc -show-encoding`.
|
||||
#[test]
|
||||
fn test_movsx_memory_source_sign_extends() {
|
||||
// mov rdi, DATA_BASE (48 BF <imm64>)
|
||||
// movsbl eax, byte [rdi] (0F BE 07)
|
||||
// movsbq rdx, byte [rdi] (48 0F BE 17)
|
||||
let code = program_with_rdi(DATA_BASE, &[0x0F, 0xBE, 0x07, 0x48, 0x0F, 0xBE, 0x17]);
|
||||
|
||||
let pe_bytes = build_synthetic_pe32_plus(&code);
|
||||
let parsed = ParsedPe::parse(&pe_bytes).expect("parse");
|
||||
let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load");
|
||||
loaded
|
||||
.memory
|
||||
.map_region(STACK_BASE, 0x10000, MemoryPermissions::READ_WRITE)
|
||||
.expect("stack mapping should succeed");
|
||||
loaded
|
||||
.memory
|
||||
.map_region(DATA_BASE, 0x10000, MemoryPermissions::READ_WRITE)
|
||||
.expect("data mapping should succeed");
|
||||
loaded
|
||||
.memory
|
||||
.write_u8(DATA_BASE, 0xFF)
|
||||
.expect("source byte");
|
||||
|
||||
let cpu = CpuState::new(loaded.entry_point, STACK_BASE + 0x8000);
|
||||
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 100);
|
||||
let result = interp.run();
|
||||
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
// The 32-bit destination holds 0xffffffff with the upper half cleared.
|
||||
assert_eq!(result.final_state.get(Register::Rax), 0x0000_0000_ffff_ffff);
|
||||
// The 64-bit destination keeps the sign extension across all 64 bits.
|
||||
assert_eq!(result.final_state.get(Register::Rdx), 0xffff_ffff_ffff_ffff);
|
||||
}
|
||||
|
||||
/// The interpreter must implement the same extension opcodes as the native
|
||||
/// DBT translator.
|
||||
///
|
||||
/// The program exercises all four opcodes with both a register and a memory
|
||||
/// source, and both destination widths:
|
||||
///
|
||||
/// - `movzbl eax, bl` (0F B6 C3), `movzbq rdx, bl` (48 0F B6 D3)
|
||||
/// - `movswl eax, bx` (0F BF C3), `movswq rdx, bx` (48 0F BF D3)
|
||||
/// - `movzbl eax, byte [rdi]` (0F B6 07), `movzbq rdx, byte [rdi]`
|
||||
/// (48 0F B6 17)
|
||||
/// - `movsbl eax, byte [rdi]` (0F BE 07), `movsbq rdx, byte [rdi]`
|
||||
/// (48 0F BE 17)
|
||||
///
|
||||
/// All encodings were produced by LLVM 23.1.6 `llvm-mc -show-encoding`.
|
||||
///
|
||||
/// The expected values follow the Intel SDM rules for MOVZX and MOVSX: MOVZX
|
||||
/// always zero-extends, and MOVSX sign-extends to the destination width, so a
|
||||
/// 32-bit destination keeps the sign in bits 31:0 and clears the upper half
|
||||
/// while a 64-bit destination keeps the sign extension across all 64 bits.
|
||||
#[test]
|
||||
fn test_interpreter_implements_the_extension_opcodes() {
|
||||
let code = program_with_rdi(
|
||||
DATA_BASE,
|
||||
&[
|
||||
0x0F, 0xB6, 0xC3, // movzbl eax, bl
|
||||
0x48, 0x0F, 0xB6, 0xD3, // movzbq rdx, bl
|
||||
0x0F, 0xBF, 0xC3, // movswl eax, bx
|
||||
0x48, 0x0F, 0xBF, 0xD3, // movswq rdx, bx
|
||||
0x0F, 0xB6, 0x07, // movzbl eax, byte [rdi]
|
||||
0x48, 0x0F, 0xB6, 0x17, // movzbq rdx, byte [rdi]
|
||||
0x0F, 0xBE, 0x07, // movsbl eax, byte [rdi]
|
||||
0x48, 0x0F, 0xBE, 0x17, // movsbq rdx, byte [rdi]
|
||||
],
|
||||
);
|
||||
|
||||
let pe_bytes = build_synthetic_pe32_plus(&code);
|
||||
let parsed = ParsedPe::parse(&pe_bytes).expect("parse");
|
||||
let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load");
|
||||
loaded
|
||||
.memory
|
||||
.map_region(STACK_BASE, 0x10000, MemoryPermissions::READ_WRITE)
|
||||
.expect("stack mapping should succeed");
|
||||
loaded
|
||||
.memory
|
||||
.map_region(DATA_BASE, 0x10000, MemoryPermissions::READ_WRITE)
|
||||
.expect("data mapping should succeed");
|
||||
// The bytes at the source address have the high bit set and clear, so a
|
||||
// sign extension and a zero extension give different results.
|
||||
loaded
|
||||
.memory
|
||||
.write_u8(DATA_BASE, 0xFF)
|
||||
.expect("source byte");
|
||||
loaded
|
||||
.memory
|
||||
.write_u8(DATA_BASE + 1, 0x7F)
|
||||
.expect("source byte");
|
||||
let mut cpu = CpuState::new(loaded.entry_point, STACK_BASE + 0x8000);
|
||||
// rbx and rsi hold the register-source values.
|
||||
cpu.set(Register::Rbx, u64::MAX);
|
||||
cpu.set(Register::Rsi, 0x0000_0000_0000_7FFF);
|
||||
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 100);
|
||||
let result = interp.run();
|
||||
|
||||
assert_eq!(result.exit_reason, ExitReason::Halt);
|
||||
// The last write to rax is the 32-bit sign extension of the byte 0xFF.
|
||||
assert_eq!(result.final_state.get(Register::Rax), 0x0000_0000_ffff_ffff);
|
||||
// The last write to rdx is the 64-bit sign extension of the same byte.
|
||||
assert_eq!(result.final_state.get(Register::Rdx), 0xffff_ffff_ffff_ffff);
|
||||
}
|
||||
@@ -31,6 +31,7 @@ fn check_bswap(native: bool) {
|
||||
zf: !wide,
|
||||
sf: wide,
|
||||
of: !wide,
|
||||
..RFlags::default()
|
||||
};
|
||||
let flags = cpu.flags;
|
||||
let mut expected = cpu.gpr;
|
||||
|
||||
@@ -7,33 +7,18 @@ use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
|
||||
|
||||
#[test]
|
||||
fn test_generated_crt_math_in_runtime_registry() {
|
||||
fn test_crt_math_resolves_through_its_api_set_and_uses_xmm0() {
|
||||
let mut registry = ImportRegistry::new();
|
||||
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(100))));
|
||||
register_standard_services(&mut registry, state);
|
||||
|
||||
// Register a sample generated CRT handler (e.g. sqrt)
|
||||
registry.register_with_status(
|
||||
"api-ms-win-crt-math-l1-1-0.dll",
|
||||
"sqrt",
|
||||
ServiceStatus::Partial,
|
||||
|args: &Win64Args,
|
||||
_cpu: &mut CpuState,
|
||||
_mem: &mut GuestMemory|
|
||||
-> Result<u64, ExitReason> {
|
||||
let x = f64::from_bits(args.rcx);
|
||||
let r = x.sqrt();
|
||||
Ok(r.to_bits())
|
||||
},
|
||||
);
|
||||
|
||||
let mut cpu = CpuState::new(0x1000, 0x8000);
|
||||
let mut mem = GuestMemory::new();
|
||||
mem.map_region(0x1000, 0x10000, MemoryPermissions::READ_WRITE_EXECUTE)
|
||||
.unwrap();
|
||||
|
||||
cpu.xmm[0] = u128::from(16.0f64.to_bits());
|
||||
let args = Win64Args {
|
||||
rcx: (16.0f64).to_bits(),
|
||||
rcx: 9.0f64.to_bits(),
|
||||
rdx: 0,
|
||||
r8: 0,
|
||||
r9: 0,
|
||||
@@ -43,8 +28,8 @@ fn test_generated_crt_math_in_runtime_registry() {
|
||||
let desc = registry
|
||||
.binding("api-ms-win-crt-math-l1-1-0.dll", "sqrt")
|
||||
.unwrap();
|
||||
let res = (desc.handler)(&args, &mut cpu, &mut mem).unwrap();
|
||||
assert_eq!(f64::from_bits(res), 4.0);
|
||||
(desc.handler)(&args, &mut cpu, &mut mem).unwrap();
|
||||
assert_eq!(f64::from_bits(cpu.xmm[0] as u64), 4.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Guest memory boundary regression tests (#82).
|
||||
//!
|
||||
//! Expected behavior follows x86-64 data access rules: an access is valid when
|
||||
//! every byte it touches is mapped with the required permission, whether or not
|
||||
//! it is aligned or crosses into an adjacent mapping. A faulting access changes
|
||||
//! nothing.
|
||||
|
||||
use xenora_loader::{GuestMemory, MemoryError, MemoryPermissions as P};
|
||||
|
||||
const A: u64 = 0x10_0000;
|
||||
|
||||
fn two_regions(first: P, second: P) -> GuestMemory {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(A, 0x1000, first, &[0x11; 0x1000])
|
||||
.unwrap();
|
||||
m.map_region_with_data(A + 0x1000, 0x1000, second, &[0x22; 0x1000])
|
||||
.unwrap();
|
||||
m
|
||||
}
|
||||
|
||||
fn bypass_bytes(m: &GuestMemory, at: u64) -> u64 {
|
||||
m.read_u64_bypass(at).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permissions_are_enforced_per_access_kind() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region(A, 0x1000, P::NO_ACCESS).unwrap();
|
||||
m.map_region(A + 0x1000, 0x1000, P::READ_ONLY).unwrap();
|
||||
m.map_region(A + 0x2000, 0x1000, P::READ_WRITE).unwrap();
|
||||
let violation = |address, required| MemoryError::PermissionViolation { address, required };
|
||||
assert_eq!(m.read_u8(A), Err(violation(A, "read")));
|
||||
assert_eq!(
|
||||
m.write_u8(A + 0x1000, 1),
|
||||
Err(violation(A + 0x1000, "write"))
|
||||
);
|
||||
assert_eq!(
|
||||
m.fetch_instruction_byte(A + 0x2000),
|
||||
Err(violation(A + 0x2000, "execute"))
|
||||
);
|
||||
assert!(m.read_u8(A + 0x1000).is_ok());
|
||||
assert!(m.write_u8(A + 0x2000, 1).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn region_end_is_exclusive() {
|
||||
let m = two_regions(P::READ_ONLY, P::NO_ACCESS);
|
||||
assert!(m.read_u32(A + 0xFFC).is_ok());
|
||||
assert!(matches!(
|
||||
m.read_u32(A + 0xFFD),
|
||||
Err(MemoryError::PermissionViolation { .. })
|
||||
));
|
||||
let mut lone = GuestMemory::new();
|
||||
lone.map_region(A, 0x1000, P::READ_ONLY).unwrap();
|
||||
assert_eq!(
|
||||
lone.read_u32(A + 0xFFD),
|
||||
Err(MemoryError::UnmappedAddress(A + 0xFFD))
|
||||
);
|
||||
assert_eq!(
|
||||
lone.read_u8(A - 1),
|
||||
Err(MemoryError::UnmappedAddress(A - 1))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unaligned_accesses_succeed_inside_a_region() {
|
||||
let mut m = two_regions(P::READ_WRITE, P::READ_WRITE);
|
||||
m.write_u64(A + 3, 0x0102_0304_0506_0708).unwrap();
|
||||
assert_eq!(m.read_u64(A + 3), Ok(0x0102_0304_0506_0708));
|
||||
assert_eq!(m.read_u16(A + 3), Ok(0x0708));
|
||||
assert_eq!(m.read_u32(A + 5), Ok(0x0304_0506));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn access_spanning_adjacent_permitted_regions_succeeds() {
|
||||
let mut m = two_regions(P::READ_WRITE, P::READ_WRITE);
|
||||
m.write_u64(A + 0xFFC, 0x8877_6655_4433_2211).unwrap();
|
||||
assert_eq!(m.read_u64(A + 0xFFC), Ok(0x8877_6655_4433_2211));
|
||||
assert_eq!(m.read_u32(A + 0xFFC), Ok(0x4433_2211)); // low half in the first region
|
||||
assert_eq!(m.read_u32(A + 0x1000), Ok(0x8877_6655)); // high half in the second
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spanning_into_a_gap_fails_without_partial_write() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region_with_data(A, 0x1000, P::READ_WRITE, &[0x11; 0x1000])
|
||||
.unwrap();
|
||||
m.map_region(A + 0x2000, 0x1000, P::READ_WRITE).unwrap();
|
||||
assert_eq!(
|
||||
m.write_u64(A + 0xFFC, u64::MAX),
|
||||
Err(MemoryError::UnmappedAddress(A + 0xFFC))
|
||||
);
|
||||
assert_eq!(m.read_u32(A + 0xFFC), Ok(0x1111_1111));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spanning_into_a_forbidden_region_fails_atomically() {
|
||||
let mut m = two_regions(P::READ_WRITE, P::READ_ONLY);
|
||||
assert_eq!(
|
||||
m.write_u64(A + 0xFFC, u64::MAX),
|
||||
Err(MemoryError::PermissionViolation {
|
||||
address: A + 0xFFC,
|
||||
required: "write"
|
||||
})
|
||||
);
|
||||
assert_eq!(bypass_bytes(&m, A + 0xFFC), 0x2222_2222_1111_1111);
|
||||
|
||||
let m = two_regions(P::READ_EXECUTE, P::READ_WRITE);
|
||||
assert!(m.read_u64(A + 0xFFC).is_ok());
|
||||
assert!(m.fetch_instruction_byte(A + 0xFFF).is_ok());
|
||||
assert!(m.fetch_instruction_byte(A + 0x1000).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loader_bypass_ignores_permissions_but_not_mapping() {
|
||||
let mut m = two_regions(P::READ_ONLY, P::NO_ACCESS);
|
||||
m.write_u64_bypass(A + 0xFFC, 0x0A0B_0C0D_0E0F_1011)
|
||||
.unwrap();
|
||||
assert_eq!(m.read_u64_bypass(A + 0xFFC), Ok(0x0A0B_0C0D_0E0F_1011));
|
||||
m.write_u32_bypass(A, 7).unwrap();
|
||||
assert_eq!(m.read_u32(A), Ok(7));
|
||||
assert_eq!(
|
||||
m.write_u64_bypass(A + 0x1FFC, 0),
|
||||
Err(MemoryError::UnmappedAddress(A + 0x1FFC))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn address_overflow_is_reported() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region(u64::MAX - 0xFFF, 0xFFF, P::READ_WRITE)
|
||||
.unwrap();
|
||||
assert_eq!(m.read_u64(u64::MAX - 3), Err(MemoryError::Overflow));
|
||||
assert_eq!(
|
||||
m.write_u64_bypass(u64::MAX - 3, 0),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
assert_eq!(
|
||||
m.map_region(u64::MAX, 2, P::READ_WRITE),
|
||||
Err(MemoryError::Overflow)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_mappings_are_rejected_and_adjacent_ones_accepted() {
|
||||
let mut m = GuestMemory::new();
|
||||
m.map_region(A, 0x1000, P::READ_WRITE).unwrap();
|
||||
assert_eq!(
|
||||
m.map_region(A + 0xFFF, 0x10, P::READ_WRITE),
|
||||
Err(MemoryError::OverlappingRegion {
|
||||
base: A + 0xFFF,
|
||||
size: 0x10
|
||||
})
|
||||
);
|
||||
assert!(m.map_region(A + 0x1000, 0x10, P::READ_WRITE).is_ok());
|
||||
assert!(m.map_region(A - 0x10, 0x10, P::READ_WRITE).is_ok());
|
||||
}
|
||||
@@ -0,0 +1,539 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! MOVZX, MOVSX and MOVSXD known-answer tests (issues #65, #66 and #117), and
|
||||
//! the MOV-immediate regressions that keep one-byte opcodes B8-BF separate from
|
||||
//! the two-byte 0F BE/BF sign extensions.
|
||||
//!
|
||||
//! Every encoding was produced from its Intel-syntax text by the LLVM assembler
|
||||
//! (`clang -target x86_64-apple-macos -c` then `objdump -d`, Apple clang 17.0.0).
|
||||
//! Expected values follow the Intel SDM Vol. 2 operation sections and are
|
||||
//! computed here by modular arithmetic, independently of both engines.
|
||||
|
||||
use xenora_loader::cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, RFlags, Register};
|
||||
use xenora_loader::dbt::DbtEngine;
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
|
||||
const ENTRY: u64 = 0x1000;
|
||||
const DATA: u64 = 0x2000;
|
||||
const DATA_LEN: usize = 0x400;
|
||||
|
||||
struct Case {
|
||||
text: &'static str,
|
||||
code: &'static [u8],
|
||||
signed: bool,
|
||||
dst: usize,
|
||||
dst_bits: u32,
|
||||
/// Register number, or for `high` the parent of AH/CH/DH/BH.
|
||||
src: usize,
|
||||
src_bits: u32,
|
||||
high: bool,
|
||||
}
|
||||
|
||||
#[rustfmt::skip]
|
||||
const CASES: &[Case] = &[
|
||||
Case { text: "movsx ax, cl", code: &[0x66, 0x0F, 0xBE, 0xC1], signed: true, dst: 0, dst_bits: 16, src: 1, src_bits: 8, high: false },
|
||||
Case { text: "movsx bx, al", code: &[0x66, 0x0F, 0xBE, 0xD8], signed: true, dst: 3, dst_bits: 16, src: 0, src_bits: 8, high: false },
|
||||
Case { text: "movsx r8w, r9b", code: &[0x66, 0x45, 0x0F, 0xBE, 0xC1], signed: true, dst: 8, dst_bits: 16, src: 9, src_bits: 8, high: false },
|
||||
Case { text: "movsx cx, r12b", code: &[0x66, 0x41, 0x0F, 0xBE, 0xCC], signed: true, dst: 1, dst_bits: 16, src: 12, src_bits: 8, high: false },
|
||||
Case { text: "movsx r10w, dl", code: &[0x66, 0x44, 0x0F, 0xBE, 0xD2], signed: true, dst: 10, dst_bits: 16, src: 2, src_bits: 8, high: false },
|
||||
Case { text: "movsx si, dil", code: &[0x66, 0x40, 0x0F, 0xBE, 0xF7], signed: true, dst: 6, dst_bits: 16, src: 7, src_bits: 8, high: false },
|
||||
Case { text: "movsx dx, dl", code: &[0x66, 0x0F, 0xBE, 0xD2], signed: true, dst: 2, dst_bits: 16, src: 2, src_bits: 8, high: false },
|
||||
Case { text: "movsx eax, cl", code: &[0x0F, 0xBE, 0xC1], signed: true, dst: 0, dst_bits: 32, src: 1, src_bits: 8, high: false },
|
||||
Case { text: "movsx ebx, al", code: &[0x0F, 0xBE, 0xD8], signed: true, dst: 3, dst_bits: 32, src: 0, src_bits: 8, high: false },
|
||||
Case { text: "movsx r8d, r9b", code: &[0x45, 0x0F, 0xBE, 0xC1], signed: true, dst: 8, dst_bits: 32, src: 9, src_bits: 8, high: false },
|
||||
Case { text: "movsx ecx, r12b", code: &[0x41, 0x0F, 0xBE, 0xCC], signed: true, dst: 1, dst_bits: 32, src: 12, src_bits: 8, high: false },
|
||||
Case { text: "movsx r10d, dl", code: &[0x44, 0x0F, 0xBE, 0xD2], signed: true, dst: 10, dst_bits: 32, src: 2, src_bits: 8, high: false },
|
||||
Case { text: "movsx esi, dil", code: &[0x40, 0x0F, 0xBE, 0xF7], signed: true, dst: 6, dst_bits: 32, src: 7, src_bits: 8, high: false },
|
||||
Case { text: "movsx edx, dl", code: &[0x0F, 0xBE, 0xD2], signed: true, dst: 2, dst_bits: 32, src: 2, src_bits: 8, high: false },
|
||||
Case { text: "movsx rax, cl", code: &[0x48, 0x0F, 0xBE, 0xC1], signed: true, dst: 0, dst_bits: 64, src: 1, src_bits: 8, high: false },
|
||||
Case { text: "movsx rbx, al", code: &[0x48, 0x0F, 0xBE, 0xD8], signed: true, dst: 3, dst_bits: 64, src: 0, src_bits: 8, high: false },
|
||||
Case { text: "movsx r8, r9b", code: &[0x4D, 0x0F, 0xBE, 0xC1], signed: true, dst: 8, dst_bits: 64, src: 9, src_bits: 8, high: false },
|
||||
Case { text: "movsx rcx, r12b", code: &[0x49, 0x0F, 0xBE, 0xCC], signed: true, dst: 1, dst_bits: 64, src: 12, src_bits: 8, high: false },
|
||||
Case { text: "movsx r10, dl", code: &[0x4C, 0x0F, 0xBE, 0xD2], signed: true, dst: 10, dst_bits: 64, src: 2, src_bits: 8, high: false },
|
||||
Case { text: "movsx rsi, dil", code: &[0x48, 0x0F, 0xBE, 0xF7], signed: true, dst: 6, dst_bits: 64, src: 7, src_bits: 8, high: false },
|
||||
Case { text: "movsx rdx, dl", code: &[0x48, 0x0F, 0xBE, 0xD2], signed: true, dst: 2, dst_bits: 64, src: 2, src_bits: 8, high: false },
|
||||
Case { text: "movsx eax, cx", code: &[0x0F, 0xBF, 0xC1], signed: true, dst: 0, dst_bits: 32, src: 1, src_bits: 16, high: false },
|
||||
Case { text: "movsx ebx, ax", code: &[0x0F, 0xBF, 0xD8], signed: true, dst: 3, dst_bits: 32, src: 0, src_bits: 16, high: false },
|
||||
Case { text: "movsx r8d, r9w", code: &[0x45, 0x0F, 0xBF, 0xC1], signed: true, dst: 8, dst_bits: 32, src: 9, src_bits: 16, high: false },
|
||||
Case { text: "movsx ecx, r12w", code: &[0x41, 0x0F, 0xBF, 0xCC], signed: true, dst: 1, dst_bits: 32, src: 12, src_bits: 16, high: false },
|
||||
Case { text: "movsx r10d, dx", code: &[0x44, 0x0F, 0xBF, 0xD2], signed: true, dst: 10, dst_bits: 32, src: 2, src_bits: 16, high: false },
|
||||
Case { text: "movsx esi, bp", code: &[0x0F, 0xBF, 0xF5], signed: true, dst: 6, dst_bits: 32, src: 5, src_bits: 16, high: false },
|
||||
Case { text: "movsx edx, dx", code: &[0x0F, 0xBF, 0xD2], signed: true, dst: 2, dst_bits: 32, src: 2, src_bits: 16, high: false },
|
||||
Case { text: "movsx rax, cx", code: &[0x48, 0x0F, 0xBF, 0xC1], signed: true, dst: 0, dst_bits: 64, src: 1, src_bits: 16, high: false },
|
||||
Case { text: "movsx rbx, ax", code: &[0x48, 0x0F, 0xBF, 0xD8], signed: true, dst: 3, dst_bits: 64, src: 0, src_bits: 16, high: false },
|
||||
Case { text: "movsx r8, r9w", code: &[0x4D, 0x0F, 0xBF, 0xC1], signed: true, dst: 8, dst_bits: 64, src: 9, src_bits: 16, high: false },
|
||||
Case { text: "movsx rcx, r12w", code: &[0x49, 0x0F, 0xBF, 0xCC], signed: true, dst: 1, dst_bits: 64, src: 12, src_bits: 16, high: false },
|
||||
Case { text: "movsx r10, dx", code: &[0x4C, 0x0F, 0xBF, 0xD2], signed: true, dst: 10, dst_bits: 64, src: 2, src_bits: 16, high: false },
|
||||
Case { text: "movsx rsi, bp", code: &[0x48, 0x0F, 0xBF, 0xF5], signed: true, dst: 6, dst_bits: 64, src: 5, src_bits: 16, high: false },
|
||||
Case { text: "movsx rdx, dx", code: &[0x48, 0x0F, 0xBF, 0xD2], signed: true, dst: 2, dst_bits: 64, src: 2, src_bits: 16, high: false },
|
||||
Case { text: "movsx dx, ah", code: &[0x66, 0x0F, 0xBE, 0xD4], signed: true, dst: 2, dst_bits: 16, src: 0, src_bits: 8, high: true },
|
||||
Case { text: "movsx dx, ch", code: &[0x66, 0x0F, 0xBE, 0xD5], signed: true, dst: 2, dst_bits: 16, src: 1, src_bits: 8, high: true },
|
||||
Case { text: "movsx dx, dh", code: &[0x66, 0x0F, 0xBE, 0xD6], signed: true, dst: 2, dst_bits: 16, src: 2, src_bits: 8, high: true },
|
||||
Case { text: "movsx dx, bh", code: &[0x66, 0x0F, 0xBE, 0xD7], signed: true, dst: 2, dst_bits: 16, src: 3, src_bits: 8, high: true },
|
||||
Case { text: "movsx edx, ah", code: &[0x0F, 0xBE, 0xD4], signed: true, dst: 2, dst_bits: 32, src: 0, src_bits: 8, high: true },
|
||||
Case { text: "movsx edx, ch", code: &[0x0F, 0xBE, 0xD5], signed: true, dst: 2, dst_bits: 32, src: 1, src_bits: 8, high: true },
|
||||
Case { text: "movsx edx, dh", code: &[0x0F, 0xBE, 0xD6], signed: true, dst: 2, dst_bits: 32, src: 2, src_bits: 8, high: true },
|
||||
Case { text: "movsx edx, bh", code: &[0x0F, 0xBE, 0xD7], signed: true, dst: 2, dst_bits: 32, src: 3, src_bits: 8, high: true },
|
||||
Case { text: "movzx ax, cl", code: &[0x66, 0x0F, 0xB6, 0xC1], signed: false, dst: 0, dst_bits: 16, src: 1, src_bits: 8, high: false },
|
||||
Case { text: "movzx bx, al", code: &[0x66, 0x0F, 0xB6, 0xD8], signed: false, dst: 3, dst_bits: 16, src: 0, src_bits: 8, high: false },
|
||||
Case { text: "movzx r8w, r9b", code: &[0x66, 0x45, 0x0F, 0xB6, 0xC1], signed: false, dst: 8, dst_bits: 16, src: 9, src_bits: 8, high: false },
|
||||
Case { text: "movzx cx, r12b", code: &[0x66, 0x41, 0x0F, 0xB6, 0xCC], signed: false, dst: 1, dst_bits: 16, src: 12, src_bits: 8, high: false },
|
||||
Case { text: "movzx r10w, dl", code: &[0x66, 0x44, 0x0F, 0xB6, 0xD2], signed: false, dst: 10, dst_bits: 16, src: 2, src_bits: 8, high: false },
|
||||
Case { text: "movzx si, dil", code: &[0x66, 0x40, 0x0F, 0xB6, 0xF7], signed: false, dst: 6, dst_bits: 16, src: 7, src_bits: 8, high: false },
|
||||
Case { text: "movzx dx, dl", code: &[0x66, 0x0F, 0xB6, 0xD2], signed: false, dst: 2, dst_bits: 16, src: 2, src_bits: 8, high: false },
|
||||
Case { text: "movzx eax, cl", code: &[0x0F, 0xB6, 0xC1], signed: false, dst: 0, dst_bits: 32, src: 1, src_bits: 8, high: false },
|
||||
Case { text: "movzx ebx, al", code: &[0x0F, 0xB6, 0xD8], signed: false, dst: 3, dst_bits: 32, src: 0, src_bits: 8, high: false },
|
||||
Case { text: "movzx r8d, r9b", code: &[0x45, 0x0F, 0xB6, 0xC1], signed: false, dst: 8, dst_bits: 32, src: 9, src_bits: 8, high: false },
|
||||
Case { text: "movzx ecx, r12b", code: &[0x41, 0x0F, 0xB6, 0xCC], signed: false, dst: 1, dst_bits: 32, src: 12, src_bits: 8, high: false },
|
||||
Case { text: "movzx r10d, dl", code: &[0x44, 0x0F, 0xB6, 0xD2], signed: false, dst: 10, dst_bits: 32, src: 2, src_bits: 8, high: false },
|
||||
Case { text: "movzx esi, dil", code: &[0x40, 0x0F, 0xB6, 0xF7], signed: false, dst: 6, dst_bits: 32, src: 7, src_bits: 8, high: false },
|
||||
Case { text: "movzx edx, dl", code: &[0x0F, 0xB6, 0xD2], signed: false, dst: 2, dst_bits: 32, src: 2, src_bits: 8, high: false },
|
||||
Case { text: "movzx rax, cl", code: &[0x48, 0x0F, 0xB6, 0xC1], signed: false, dst: 0, dst_bits: 64, src: 1, src_bits: 8, high: false },
|
||||
Case { text: "movzx rbx, al", code: &[0x48, 0x0F, 0xB6, 0xD8], signed: false, dst: 3, dst_bits: 64, src: 0, src_bits: 8, high: false },
|
||||
Case { text: "movzx r8, r9b", code: &[0x4D, 0x0F, 0xB6, 0xC1], signed: false, dst: 8, dst_bits: 64, src: 9, src_bits: 8, high: false },
|
||||
Case { text: "movzx rcx, r12b", code: &[0x49, 0x0F, 0xB6, 0xCC], signed: false, dst: 1, dst_bits: 64, src: 12, src_bits: 8, high: false },
|
||||
Case { text: "movzx r10, dl", code: &[0x4C, 0x0F, 0xB6, 0xD2], signed: false, dst: 10, dst_bits: 64, src: 2, src_bits: 8, high: false },
|
||||
Case { text: "movzx rsi, dil", code: &[0x48, 0x0F, 0xB6, 0xF7], signed: false, dst: 6, dst_bits: 64, src: 7, src_bits: 8, high: false },
|
||||
Case { text: "movzx rdx, dl", code: &[0x48, 0x0F, 0xB6, 0xD2], signed: false, dst: 2, dst_bits: 64, src: 2, src_bits: 8, high: false },
|
||||
Case { text: "movzx eax, cx", code: &[0x0F, 0xB7, 0xC1], signed: false, dst: 0, dst_bits: 32, src: 1, src_bits: 16, high: false },
|
||||
Case { text: "movzx ebx, ax", code: &[0x0F, 0xB7, 0xD8], signed: false, dst: 3, dst_bits: 32, src: 0, src_bits: 16, high: false },
|
||||
Case { text: "movzx r8d, r9w", code: &[0x45, 0x0F, 0xB7, 0xC1], signed: false, dst: 8, dst_bits: 32, src: 9, src_bits: 16, high: false },
|
||||
Case { text: "movzx ecx, r12w", code: &[0x41, 0x0F, 0xB7, 0xCC], signed: false, dst: 1, dst_bits: 32, src: 12, src_bits: 16, high: false },
|
||||
Case { text: "movzx r10d, dx", code: &[0x44, 0x0F, 0xB7, 0xD2], signed: false, dst: 10, dst_bits: 32, src: 2, src_bits: 16, high: false },
|
||||
Case { text: "movzx esi, bp", code: &[0x0F, 0xB7, 0xF5], signed: false, dst: 6, dst_bits: 32, src: 5, src_bits: 16, high: false },
|
||||
Case { text: "movzx edx, dx", code: &[0x0F, 0xB7, 0xD2], signed: false, dst: 2, dst_bits: 32, src: 2, src_bits: 16, high: false },
|
||||
Case { text: "movzx rax, cx", code: &[0x48, 0x0F, 0xB7, 0xC1], signed: false, dst: 0, dst_bits: 64, src: 1, src_bits: 16, high: false },
|
||||
Case { text: "movzx rbx, ax", code: &[0x48, 0x0F, 0xB7, 0xD8], signed: false, dst: 3, dst_bits: 64, src: 0, src_bits: 16, high: false },
|
||||
Case { text: "movzx r8, r9w", code: &[0x4D, 0x0F, 0xB7, 0xC1], signed: false, dst: 8, dst_bits: 64, src: 9, src_bits: 16, high: false },
|
||||
Case { text: "movzx rcx, r12w", code: &[0x49, 0x0F, 0xB7, 0xCC], signed: false, dst: 1, dst_bits: 64, src: 12, src_bits: 16, high: false },
|
||||
Case { text: "movzx r10, dx", code: &[0x4C, 0x0F, 0xB7, 0xD2], signed: false, dst: 10, dst_bits: 64, src: 2, src_bits: 16, high: false },
|
||||
Case { text: "movzx rsi, bp", code: &[0x48, 0x0F, 0xB7, 0xF5], signed: false, dst: 6, dst_bits: 64, src: 5, src_bits: 16, high: false },
|
||||
Case { text: "movzx rdx, dx", code: &[0x48, 0x0F, 0xB7, 0xD2], signed: false, dst: 2, dst_bits: 64, src: 2, src_bits: 16, high: false },
|
||||
Case { text: "movzx dx, ah", code: &[0x66, 0x0F, 0xB6, 0xD4], signed: false, dst: 2, dst_bits: 16, src: 0, src_bits: 8, high: true },
|
||||
Case { text: "movzx dx, ch", code: &[0x66, 0x0F, 0xB6, 0xD5], signed: false, dst: 2, dst_bits: 16, src: 1, src_bits: 8, high: true },
|
||||
Case { text: "movzx dx, dh", code: &[0x66, 0x0F, 0xB6, 0xD6], signed: false, dst: 2, dst_bits: 16, src: 2, src_bits: 8, high: true },
|
||||
Case { text: "movzx dx, bh", code: &[0x66, 0x0F, 0xB6, 0xD7], signed: false, dst: 2, dst_bits: 16, src: 3, src_bits: 8, high: true },
|
||||
Case { text: "movzx edx, ah", code: &[0x0F, 0xB6, 0xD4], signed: false, dst: 2, dst_bits: 32, src: 0, src_bits: 8, high: true },
|
||||
Case { text: "movzx edx, ch", code: &[0x0F, 0xB6, 0xD5], signed: false, dst: 2, dst_bits: 32, src: 1, src_bits: 8, high: true },
|
||||
Case { text: "movzx edx, dh", code: &[0x0F, 0xB6, 0xD6], signed: false, dst: 2, dst_bits: 32, src: 2, src_bits: 8, high: true },
|
||||
Case { text: "movzx edx, bh", code: &[0x0F, 0xB6, 0xD7], signed: false, dst: 2, dst_bits: 32, src: 3, src_bits: 8, high: true },
|
||||
Case { text: "movsxd rax, ecx", code: &[0x48, 0x63, 0xC1], signed: true, dst: 0, dst_bits: 64, src: 1, src_bits: 32, high: false },
|
||||
Case { text: "movsxd rbx, eax", code: &[0x48, 0x63, 0xD8], signed: true, dst: 3, dst_bits: 64, src: 0, src_bits: 32, high: false },
|
||||
Case { text: "movsxd r8, r9d", code: &[0x4D, 0x63, 0xC1], signed: true, dst: 8, dst_bits: 64, src: 9, src_bits: 32, high: false },
|
||||
Case { text: "movsxd rcx, r12d", code: &[0x49, 0x63, 0xCC], signed: true, dst: 1, dst_bits: 64, src: 12, src_bits: 32, high: false },
|
||||
Case { text: "movsxd r10, edx", code: &[0x4C, 0x63, 0xD2], signed: true, dst: 10, dst_bits: 64, src: 2, src_bits: 32, high: false },
|
||||
Case { text: "movsxd rsi, ebp", code: &[0x48, 0x63, 0xF5], signed: true, dst: 6, dst_bits: 64, src: 5, src_bits: 32, high: false },
|
||||
Case { text: "movsxd rdx, edx", code: &[0x48, 0x63, 0xD2], signed: true, dst: 2, dst_bits: 64, src: 2, src_bits: 32, high: false },
|
||||
];
|
||||
|
||||
#[rustfmt::skip]
|
||||
const MOV_IMMEDIATE: &[(&[u8], usize, u64)] = &[
|
||||
(&[0xB8, 0x81, 0xBE, 0xF0, 0x8B], 0, 0x8BF0_BE81), // mov eax, 0x8bf0be81
|
||||
(&[0xB9, 0x81, 0xBE, 0xF0, 0x8B], 1, 0x8BF0_BE81), // mov ecx, 0x8bf0be81
|
||||
(&[0xBA, 0x81, 0xBE, 0xF0, 0x8B], 2, 0x8BF0_BE81), // mov edx, 0x8bf0be81
|
||||
(&[0xBB, 0x81, 0xBE, 0xF0, 0x8B], 3, 0x8BF0_BE81), // mov ebx, 0x8bf0be81
|
||||
(&[0xBC, 0x81, 0xBE, 0xF0, 0x8B], 4, 0x8BF0_BE81), // mov esp, 0x8bf0be81
|
||||
(&[0xBD, 0x81, 0xBE, 0xF0, 0x8B], 5, 0x8BF0_BE81), // mov ebp, 0x8bf0be81
|
||||
(&[0xBE, 0x81, 0xBE, 0xF0, 0x8B], 6, 0x8BF0_BE81), // mov esi, 0x8bf0be81
|
||||
(&[0xBF, 0x81, 0xBE, 0xF0, 0x8B], 7, 0x8BF0_BE81), // mov edi, 0x8bf0be81
|
||||
(&[0x41, 0xB8, 0x81, 0xBE, 0xF0, 0x8B], 8, 0x8BF0_BE81), // mov r8d, 0x8bf0be81
|
||||
(&[0x41, 0xB9, 0x81, 0xBE, 0xF0, 0x8B], 9, 0x8BF0_BE81), // mov r9d, 0x8bf0be81
|
||||
(&[0x41, 0xBA, 0x81, 0xBE, 0xF0, 0x8B], 10, 0x8BF0_BE81), // mov r10d, 0x8bf0be81
|
||||
(&[0x41, 0xBB, 0x81, 0xBE, 0xF0, 0x8B], 11, 0x8BF0_BE81), // mov r11d, 0x8bf0be81
|
||||
(&[0x41, 0xBC, 0x81, 0xBE, 0xF0, 0x8B], 12, 0x8BF0_BE81), // mov r12d, 0x8bf0be81
|
||||
(&[0x41, 0xBD, 0x81, 0xBE, 0xF0, 0x8B], 13, 0x8BF0_BE81), // mov r13d, 0x8bf0be81
|
||||
(&[0x41, 0xBE, 0x81, 0xBE, 0xF0, 0x8B], 14, 0x8BF0_BE81), // mov r14d, 0x8bf0be81
|
||||
(&[0x41, 0xBF, 0x81, 0xBE, 0xF0, 0x8B], 15, 0x8BF0_BE81), // mov r15d, 0x8bf0be81
|
||||
(&[0x48, 0xB8, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 0, 0x80BE_0FBF_63C1_B8F1), // movabs rax, 0x80be0fbf63c1b8f1
|
||||
(&[0x48, 0xB9, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 1, 0x80BE_0FBF_63C1_B8F1), // movabs rcx, 0x80be0fbf63c1b8f1
|
||||
(&[0x48, 0xBA, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 2, 0x80BE_0FBF_63C1_B8F1), // movabs rdx, 0x80be0fbf63c1b8f1
|
||||
(&[0x48, 0xBB, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 3, 0x80BE_0FBF_63C1_B8F1), // movabs rbx, 0x80be0fbf63c1b8f1
|
||||
(&[0x48, 0xBC, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 4, 0x80BE_0FBF_63C1_B8F1), // movabs rsp, 0x80be0fbf63c1b8f1
|
||||
(&[0x48, 0xBD, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 5, 0x80BE_0FBF_63C1_B8F1), // movabs rbp, 0x80be0fbf63c1b8f1
|
||||
(&[0x48, 0xBE, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 6, 0x80BE_0FBF_63C1_B8F1), // movabs rsi, 0x80be0fbf63c1b8f1
|
||||
(&[0x48, 0xBF, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 7, 0x80BE_0FBF_63C1_B8F1), // movabs rdi, 0x80be0fbf63c1b8f1
|
||||
(&[0x49, 0xB8, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 8, 0x80BE_0FBF_63C1_B8F1), // movabs r8, 0x80be0fbf63c1b8f1
|
||||
(&[0x49, 0xB9, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 9, 0x80BE_0FBF_63C1_B8F1), // movabs r9, 0x80be0fbf63c1b8f1
|
||||
(&[0x49, 0xBA, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 10, 0x80BE_0FBF_63C1_B8F1), // movabs r10, 0x80be0fbf63c1b8f1
|
||||
(&[0x49, 0xBB, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 11, 0x80BE_0FBF_63C1_B8F1), // movabs r11, 0x80be0fbf63c1b8f1
|
||||
(&[0x49, 0xBC, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 12, 0x80BE_0FBF_63C1_B8F1), // movabs r12, 0x80be0fbf63c1b8f1
|
||||
(&[0x49, 0xBD, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 13, 0x80BE_0FBF_63C1_B8F1), // movabs r13, 0x80be0fbf63c1b8f1
|
||||
(&[0x49, 0xBE, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 14, 0x80BE_0FBF_63C1_B8F1), // movabs r14, 0x80be0fbf63c1b8f1
|
||||
(&[0x49, 0xBF, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 15, 0x80BE_0FBF_63C1_B8F1), // movabs r15, 0x80be0fbf63c1b8f1
|
||||
];
|
||||
|
||||
fn mask(bits: u32) -> u128 {
|
||||
(1u128 << bits) - 1
|
||||
}
|
||||
|
||||
/// Architectural destination value, derived with modular arithmetic.
|
||||
fn expected(case: &Case, gpr: &[u64; 16]) -> u64 {
|
||||
let shift = if case.high { 8 } else { 0 };
|
||||
let source = (u128::from(gpr[case.src]) >> shift) & mask(case.src_bits);
|
||||
let negative = case.signed && source >= 1u128 << (case.src_bits - 1);
|
||||
let extended = if negative {
|
||||
(1u128 << 64) - (1u128 << case.src_bits) + source
|
||||
} else {
|
||||
source
|
||||
};
|
||||
let low = extended & mask(case.dst_bits);
|
||||
let kept = if case.dst_bits == 16 {
|
||||
u128::from(gpr[case.dst]) & !mask(16)
|
||||
} else {
|
||||
0 // 32-bit writes clear bits 63:32.
|
||||
};
|
||||
(kept | low) as u64
|
||||
}
|
||||
|
||||
fn memory_with(code: &[u8], data: &[u8]) -> GuestMemory {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, code)
|
||||
.unwrap();
|
||||
let mut bytes = vec![0xEEu8; DATA_LEN];
|
||||
bytes[..data.len()].copy_from_slice(data);
|
||||
memory
|
||||
.map_region_with_data(DATA, DATA_LEN, MemoryPermissions::READ_WRITE, &bytes)
|
||||
.unwrap();
|
||||
memory
|
||||
}
|
||||
|
||||
fn interpret(cpu: &CpuState, memory: &mut GuestMemory) -> ExecutionResult {
|
||||
Interpreter::new(cpu.clone(), memory, 1).run()
|
||||
}
|
||||
|
||||
/// Run one instruction as translated native code, proving that it was.
|
||||
fn translate(cpu: &CpuState, memory: &mut GuestMemory, text: &str) -> ExecutionResult {
|
||||
let mut engine = DbtEngine::new(64 * 1024).expect("JIT memory");
|
||||
let result = engine.run(&mut cpu.clone(), memory, 1);
|
||||
if result.exit_reason == ExitReason::StepLimitExceeded {
|
||||
assert_eq!(engine.metrics.blocks_compiled, 1, "{text}");
|
||||
assert_eq!(engine.metrics.dbt_dispatches, 1, "{text}");
|
||||
assert_eq!(engine.metrics.instructions_executed, 1, "{text}");
|
||||
assert_eq!(engine.metrics.interpreter_fallbacks, 0, "{text}");
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn both(
|
||||
code: &[u8],
|
||||
data: &[u8],
|
||||
cpu: &CpuState,
|
||||
text: &str,
|
||||
) -> [(ExecutionResult, GuestMemory); 2] {
|
||||
let mut first = memory_with(code, data);
|
||||
let mut second = memory_with(code, data);
|
||||
let interpreted = interpret(cpu, &mut first);
|
||||
let translated = translate(cpu, &mut second, text);
|
||||
[(interpreted, first), (translated, second)]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn register_extensions_match_the_architecture_in_both_engines() {
|
||||
let low_values: [u64; 12] = [
|
||||
0,
|
||||
1,
|
||||
0x7F,
|
||||
0x80,
|
||||
0xFF,
|
||||
0x100,
|
||||
0x7FFF,
|
||||
0x8000,
|
||||
0xFFFF,
|
||||
0x7FFF_FFFF,
|
||||
0x8000_0000,
|
||||
0xFFFF_FFFF,
|
||||
];
|
||||
let patterns = low_values
|
||||
.into_iter()
|
||||
.flat_map(|low| [low, low | 0xA5A5_5A5A_0000_0000, low << 8]);
|
||||
for pattern in patterns {
|
||||
for case in CASES {
|
||||
for flags_set in [false, true] {
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
for (index, register) in cpu.gpr.iter_mut().enumerate() {
|
||||
*register = 0x1122_3344_5566_7788u64.rotate_left(index as u32 * 4);
|
||||
}
|
||||
cpu.gpr[case.src] = pattern;
|
||||
cpu.flags = RFlags {
|
||||
cf: flags_set,
|
||||
zf: flags_set,
|
||||
sf: flags_set,
|
||||
of: flags_set,
|
||||
..RFlags::default()
|
||||
};
|
||||
let mut gpr = cpu.gpr;
|
||||
gpr[case.dst] = expected(case, &cpu.gpr);
|
||||
for (result, _) in both(case.code, &[], &cpu, case.text) {
|
||||
assert_eq!(
|
||||
result.exit_reason,
|
||||
ExitReason::StepLimitExceeded,
|
||||
"{}",
|
||||
case.text
|
||||
);
|
||||
assert_eq!(result.instructions_executed, 1, "{}", case.text);
|
||||
assert_eq!(result.final_state.gpr, gpr, "{} {pattern:#x}", case.text);
|
||||
assert_eq!(result.final_state.flags, cpu.flags, "{}", case.text);
|
||||
assert_eq!(result.final_state.rip, ENTRY + case.code.len() as u64);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mov_immediate_is_never_decoded_as_a_sign_extension() {
|
||||
for &(code, register, value) in MOV_IMMEDIATE {
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr = [0xFFFF_FFFF_FFFF_FFFF; 16];
|
||||
let mut gpr = cpu.gpr;
|
||||
gpr[register] = value;
|
||||
for (result, _) in both(code, &[], &cpu, "mov immediate") {
|
||||
assert_eq!(
|
||||
result.exit_reason,
|
||||
ExitReason::StepLimitExceeded,
|
||||
"{code:02X?}"
|
||||
);
|
||||
assert_eq!(result.final_state.gpr, gpr, "{code:02X?}");
|
||||
assert_eq!(result.final_state.rip, ENTRY + code.len() as u64);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sixteen_bit_mov_immediate_writes_only_the_low_word() {
|
||||
// 66 B9 34 12 = mov cx, 0x1234
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr = [0xFFFF_FFFF_FFFF_FFFF; 16];
|
||||
let mut gpr = cpu.gpr;
|
||||
gpr[Register::Rcx as usize] = 0xFFFF_FFFF_FFFF_1234;
|
||||
for (result, _) in both(&[0x66, 0xB9, 0x34, 0x12], &[], &cpu, "mov cx, 0x1234") {
|
||||
assert_eq!(result.exit_reason, ExitReason::StepLimitExceeded);
|
||||
assert_eq!(result.final_state.gpr, gpr);
|
||||
assert_eq!(result.final_state.rip, ENTRY + 4);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_truncation_faults_without_changing_state() {
|
||||
let codes = CASES
|
||||
.iter()
|
||||
.map(|case| case.code)
|
||||
.chain(MOV_IMMEDIATE.iter().map(|entry| entry.0));
|
||||
for code in codes {
|
||||
for len in 1..code.len() {
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr = [0x8080_8080_8080_8080; 16];
|
||||
for (result, _) in both(&code[..len], &[], &cpu, "truncated") {
|
||||
assert!(
|
||||
matches!(result.exit_reason, ExitReason::MemoryFault(_)),
|
||||
"{:02X?}: {:?}",
|
||||
&code[..len],
|
||||
result.exit_reason
|
||||
);
|
||||
assert_eq!(result.instructions_executed, 0);
|
||||
assert_eq!(result.final_state, cpu);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memory_extensions_use_checked_addresses_in_both_engines() {
|
||||
let data = [0x80u8, 0xFF, 0x7F, 0x00, 0xFE, 0x80, 0xFF, 0x81, 0xC2, 0x83];
|
||||
let cases: &[(&str, &[u8], u64)] = &[
|
||||
(
|
||||
"movsx eax, byte ptr [rbx]",
|
||||
&[0x0F, 0xBE, 0x03],
|
||||
0xFFFF_FF80,
|
||||
),
|
||||
(
|
||||
"movsx rax, byte ptr [rbx+4]",
|
||||
&[0x48, 0x0F, 0xBE, 0x43, 0x04],
|
||||
0xFFFF_FFFF_FFFF_FFFE,
|
||||
),
|
||||
(
|
||||
"movsx ax, byte ptr [rbx]",
|
||||
&[0x66, 0x0F, 0xBE, 0x03],
|
||||
0xAAAA_AAAA_AAAA_FF80,
|
||||
),
|
||||
(
|
||||
"movsx rax, word ptr [rbx+rcx*2+4]",
|
||||
&[0x48, 0x0F, 0xBF, 0x44, 0x4B, 0x04],
|
||||
0xFFFF_FFFF_FFFF_81FF,
|
||||
),
|
||||
(
|
||||
"movzx eax, byte ptr [rbx+4]",
|
||||
&[0x0F, 0xB6, 0x43, 0x04],
|
||||
0xFE,
|
||||
),
|
||||
(
|
||||
"movsxd rax, dword ptr [rbx+4]",
|
||||
&[0x48, 0x63, 0x43, 0x04],
|
||||
0xFFFF_FFFF_81FF_80FE,
|
||||
),
|
||||
(
|
||||
"movsxd rax, dword ptr [r8+rcx*4]",
|
||||
&[0x49, 0x63, 0x04, 0x88],
|
||||
0xFFFF_FFFF_81FF_80FE,
|
||||
),
|
||||
// The next instruction starts at 0x1007, so the address is 0x2007.
|
||||
(
|
||||
"movsx eax, word ptr [rip+0x1000]",
|
||||
&[0x0F, 0xBF, 0x05, 0x00, 0x10, 0x00, 0x00],
|
||||
0xFFFF_C281,
|
||||
),
|
||||
(
|
||||
"movsxd rax, dword ptr gs:[rbx]",
|
||||
&[0x65, 0x48, 0x63, 0x03],
|
||||
0x007F_FF80,
|
||||
),
|
||||
(
|
||||
"movzx eax, byte ptr fs:[rbx]",
|
||||
&[0x64, 0x0F, 0xB6, 0x03],
|
||||
0xFF,
|
||||
),
|
||||
("mov eax, dword ptr [rbx]", &[0x8B, 0x03], 0x007F_FF80),
|
||||
];
|
||||
for &(text, code, value) in cases {
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[Register::Rax as usize] = 0xAAAA_AAAA_AAAA_AAAA;
|
||||
cpu.gpr[Register::Rbx as usize] = DATA;
|
||||
cpu.gpr[Register::Rcx as usize] = 1;
|
||||
cpu.gpr[Register::R8 as usize] = DATA;
|
||||
match code[0] {
|
||||
0x65 => (cpu.gs_base, cpu.gpr[Register::Rbx as usize]) = (DATA, 0),
|
||||
0x64 => (cpu.fs_base, cpu.gpr[Register::Rbx as usize]) = (DATA - 4, 5),
|
||||
_ => {}
|
||||
}
|
||||
for (result, _) in both(code, &data, &cpu, text) {
|
||||
assert_eq!(result.exit_reason, ExitReason::StepLimitExceeded, "{text}");
|
||||
assert_eq!(result.final_state.gpr[0], value, "{text}");
|
||||
assert_eq!(result.final_state.rip, ENTRY + code.len() as u64, "{text}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memory_operands_crossing_the_region_end_fault_precisely() {
|
||||
// Only the bytes the operand really covers may be touched: the last word,
|
||||
// dword or byte of the region is readable, one byte further is not.
|
||||
let cases: &[(&[u8], u64)] = &[
|
||||
(&[0x0F, 0xBE, 0x03], 1),
|
||||
(&[0x0F, 0xBF, 0x03], 2),
|
||||
(&[0x48, 0x63, 0x03], 4),
|
||||
(&[0x8B, 0x03], 4), // mov eax, dword ptr [rbx]
|
||||
(&[0x89, 0x03], 4), // mov dword ptr [rbx], eax
|
||||
];
|
||||
for &(code, width) in cases {
|
||||
let end = DATA + DATA_LEN as u64;
|
||||
for (address, ok) in [(end - width, true), (end - width + 1, false)] {
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[Register::Rbx as usize] = address;
|
||||
for (result, memory) in both(code, &[], &cpu, "boundary") {
|
||||
if ok {
|
||||
assert_eq!(
|
||||
result.exit_reason,
|
||||
ExitReason::StepLimitExceeded,
|
||||
"{code:02X?}"
|
||||
);
|
||||
} else {
|
||||
assert!(
|
||||
matches!(result.exit_reason, ExitReason::MemoryFault(_)),
|
||||
"{code:02X?}"
|
||||
);
|
||||
assert_eq!(result.instructions_executed, 0);
|
||||
assert_eq!(result.final_state, cpu, "{code:02X?}");
|
||||
let mut tail = [0u8; 4];
|
||||
memory.read_bytes(end - 4, &mut tail).unwrap();
|
||||
assert_eq!(tail, [0xEE; 4]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_32_bit_store_leaves_the_next_four_bytes_unchanged() {
|
||||
// 89 03 = mov dword ptr [rbx], eax
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[Register::Rax as usize] = 0xDDDD_DDDD_1234_5678;
|
||||
cpu.gpr[Register::Rbx as usize] = DATA;
|
||||
for (result, memory) in both(&[0x89, 0x03], &[], &cpu, "mov dword ptr [rbx], eax") {
|
||||
assert_eq!(result.exit_reason, ExitReason::StepLimitExceeded);
|
||||
assert_eq!(memory.read_u64(DATA).unwrap(), 0xEEEE_EEEE_1234_5678);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_sxtw_encodes_every_register() {
|
||||
// LLVM: sxtw x0, w30 then sxtw xN, w(31-N) for N in 1..=30.
|
||||
let llvm: [u32; 31] = [
|
||||
0x93407fc0, 0x93407fc1, 0x93407fa2, 0x93407f83, 0x93407f64, 0x93407f45, 0x93407f26,
|
||||
0x93407f07, 0x93407ee8, 0x93407ec9, 0x93407eaa, 0x93407e8b, 0x93407e6c, 0x93407e4d,
|
||||
0x93407e2e, 0x93407e0f, 0x93407df0, 0x93407dd1, 0x93407db2, 0x93407d93, 0x93407d74,
|
||||
0x93407d55, 0x93407d36, 0x93407d17, 0x93407cf8, 0x93407cd9, 0x93407cba, 0x93407c9b,
|
||||
0x93407c7c, 0x93407c5d, 0x93407c3e,
|
||||
];
|
||||
let mut assembler = xenora_loader::Arm64Assembler::new();
|
||||
for xd in 0..31u8 {
|
||||
assembler.sxtw_64(xd, if xd == 0 { 30 } else { 31 - xd });
|
||||
}
|
||||
assert_eq!(assembler.instructions(), llvm);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probe_reports_exact_extension_lengths_and_support() {
|
||||
use xenora_loader::probe::{ProbeConfig, probe_pe_bytes};
|
||||
for case in CASES {
|
||||
let report = probe_pe_bytes(&probe_image(case.code), &ProbeConfig::default()).unwrap();
|
||||
let record = &report.instruction_records[0];
|
||||
assert_eq!(record.bytes, case.code, "{}", case.text);
|
||||
assert!(
|
||||
record.is_supported_dbt && record.is_supported_interp,
|
||||
"{}",
|
||||
case.text
|
||||
);
|
||||
}
|
||||
for &(code, _, _) in MOV_IMMEDIATE {
|
||||
let report = probe_pe_bytes(&probe_image(code), &ProbeConfig::default()).unwrap();
|
||||
let record = &report.instruction_records[0];
|
||||
assert_eq!(record.bytes, code);
|
||||
assert!(
|
||||
record.mnemonic.starts_with("mov reg, imm"),
|
||||
"{}",
|
||||
record.mnemonic
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Minimal PE32+ image whose entry point holds `code` followed by HLT.
|
||||
fn probe_image(code: &[u8]) -> Vec<u8> {
|
||||
let mut pe = vec![0u8; 0x400];
|
||||
let mut put =
|
||||
|offset: usize, bytes: &[u8]| pe[offset..offset + bytes.len()].copy_from_slice(bytes);
|
||||
put(0, b"MZ");
|
||||
put(0x3C, &0x80u32.to_le_bytes());
|
||||
put(0x80, b"PE\0\0");
|
||||
put(0x84, &0x8664u16.to_le_bytes());
|
||||
put(0x86, &1u16.to_le_bytes());
|
||||
put(0x94, &240u16.to_le_bytes());
|
||||
put(0x98, &0x20Bu16.to_le_bytes());
|
||||
put(0x98 + 16, &(ENTRY as u32).to_le_bytes());
|
||||
put(0x98 + 24, &0x1_4000_0000u64.to_le_bytes());
|
||||
put(0x98 + 32, &0x1000u32.to_le_bytes());
|
||||
put(0x98 + 36, &0x200u32.to_le_bytes());
|
||||
put(0x98 + 56, &0x2000u32.to_le_bytes());
|
||||
put(0x98 + 60, &0x200u32.to_le_bytes());
|
||||
put(0x98 + 108, &16u32.to_le_bytes());
|
||||
let section = 0x98 + 240;
|
||||
put(section, b".text");
|
||||
put(section + 8, &0x200u32.to_le_bytes());
|
||||
put(section + 12, &(ENTRY as u32).to_le_bytes());
|
||||
put(section + 16, &0x200u32.to_le_bytes());
|
||||
put(section + 20, &0x200u32.to_le_bytes());
|
||||
put(section + 36, &0x6000_0020u32.to_le_bytes());
|
||||
put(0x200, code);
|
||||
put(0x200 + code.len(), &[0xF4]);
|
||||
pe
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! PE image mapping budget tests (#80).
|
||||
//!
|
||||
//! A section's mapped size is max(VirtualSize, SizeOfRawData) and the loader
|
||||
//! backs it with zero-filled host memory, so a small file can request a large
|
||||
//! allocation. The loader's documented budget is 256 MiB per image.
|
||||
|
||||
use xenora_loader::{MemoryError, ParsedPe, PeError};
|
||||
|
||||
const BUDGET: u32 = 256 * 1024 * 1024;
|
||||
|
||||
/// An original synthetic image: one 0x200-byte code section at RVA 0x1000 followed by
|
||||
/// uninitialized sections (no raw data) of the given virtual sizes, packed back to back.
|
||||
fn build(bss_sizes: &[u32]) -> Vec<u8> {
|
||||
let mut pe = vec![0u8; 0x400];
|
||||
pe[0..2].copy_from_slice(b"MZ");
|
||||
pe[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
|
||||
pe[0x40..0x44].copy_from_slice(b"PE\0\0");
|
||||
let coff = 0x44;
|
||||
pe[coff..coff + 2].copy_from_slice(&0x8664u16.to_le_bytes());
|
||||
pe[coff + 2..coff + 4].copy_from_slice(&(1 + bss_sizes.len() as u16).to_le_bytes());
|
||||
pe[coff + 16..coff + 18].copy_from_slice(&112u16.to_le_bytes());
|
||||
let opt = coff + 20;
|
||||
pe[opt..opt + 2].copy_from_slice(&0x020Bu16.to_le_bytes());
|
||||
pe[opt + 16..opt + 20].copy_from_slice(&0x1000u32.to_le_bytes());
|
||||
pe[opt + 24..opt + 32].copy_from_slice(&0x1_4000_0000u64.to_le_bytes());
|
||||
|
||||
let mut section = |i: usize, va: u32, vsize: u32, raw: u32, flags: u32| {
|
||||
let h = opt + 112 + i * 40;
|
||||
pe[h + 8..h + 12].copy_from_slice(&vsize.to_le_bytes());
|
||||
pe[h + 12..h + 16].copy_from_slice(&va.to_le_bytes());
|
||||
pe[h + 16..h + 20].copy_from_slice(&(if raw == 0 { 0 } else { 0x200u32 }).to_le_bytes());
|
||||
pe[h + 20..h + 24].copy_from_slice(&raw.to_le_bytes());
|
||||
pe[h + 36..h + 40].copy_from_slice(&flags.to_le_bytes());
|
||||
};
|
||||
section(0, 0x1000, 0x200, 0x200, 0x6000_0020);
|
||||
let mut va = 0x2000u32;
|
||||
for (i, &size) in bss_sizes.iter().enumerate() {
|
||||
section(i + 1, va, size, 0, 0xC000_0080);
|
||||
va += size;
|
||||
}
|
||||
pe
|
||||
}
|
||||
|
||||
fn over_budget() -> PeError {
|
||||
PeError::SectionMappingError(MemoryError::AllocationFailed)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_image_loads() {
|
||||
let bytes = build(&[0x1000]);
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
assert!(pe.load_into_memory(&bytes).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn image_exactly_at_budget_loads() {
|
||||
let bytes = build(&[BUDGET - 0x200]);
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
assert!(pe.load_into_memory(&bytes).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_byte_over_budget_is_rejected() {
|
||||
let bytes = build(&[BUDGET - 0x1FF]);
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn budget_counts_all_sections_together() {
|
||||
// Three 128 MiB sections: each fits alone, the total (384 MiB) does not.
|
||||
let bytes = build(&[128 << 20; 3]);
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn near_4_gib_request_from_a_1_kib_file_is_rejected_before_allocation() {
|
||||
let bytes = build(&[0xF000_0000]);
|
||||
assert_eq!(bytes.len(), 0x400);
|
||||
let pe = ParsedPe::parse(&bytes).expect("headers are valid; only the size is excessive");
|
||||
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repository_fixture_is_within_budget() {
|
||||
let path = concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/../../fixtures/pe/trusted-runner.exe"
|
||||
);
|
||||
let bytes = std::fs::read(path).unwrap();
|
||||
let pe = ParsedPe::parse(&bytes).unwrap();
|
||||
assert!(pe.load_into_memory(&bytes).is_ok());
|
||||
}
|
||||
@@ -222,7 +222,7 @@ fn trusted_runner_callback_and_report_match_the_fixture() {
|
||||
);
|
||||
assert_eq!(callback[1].bytes, [0x48, 0xc7, 0, 17, 0, 0, 0]);
|
||||
assert!(callback[1].is_supported_dbt);
|
||||
assert!(!callback[1].is_supported_interp);
|
||||
assert!(callback[1].is_supported_interp);
|
||||
assert!(report.first_unsupported_dbt_insn.is_none());
|
||||
assert!(md.contains("Sections Census (4)"));
|
||||
assert!(json.contains("\"sections_count\": 4"));
|
||||
@@ -237,14 +237,14 @@ fn trusted_runner_callback_and_report_match_the_fixture() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probe_consumes_complete_c7_operands_even_when_native_support_is_missing() {
|
||||
for (encoding, supported) in [
|
||||
(&[0x48, 0xc7, 0x05, 0, 0, 0, 0, 17, 0, 0, 0][..], true),
|
||||
(&[0xc7, 0xc0, 17, 0, 0, 0], true),
|
||||
(&[0x66, 0xc7, 0xc0, 17, 0], false),
|
||||
(&[0xc7, 0x00, 17, 0, 0, 0], false),
|
||||
(&[0x48, 0xc7, 0x40, 4, 17, 0, 0, 0], false),
|
||||
(&[0x48, 0xc7, 0x04, 0x25, 0, 0, 0, 0, 17, 0, 0, 0], false),
|
||||
fn probe_consumes_complete_c7_operands_and_reports_their_support() {
|
||||
for encoding in [
|
||||
&[0x48, 0xc7, 0x05, 0, 0, 0, 0, 17, 0, 0, 0][..],
|
||||
&[0xc7, 0xc0, 17, 0, 0, 0],
|
||||
&[0x66, 0xc7, 0xc0, 17, 0],
|
||||
&[0xc7, 0x00, 17, 0, 0, 0],
|
||||
&[0x48, 0xc7, 0x40, 4, 17, 0, 0, 0],
|
||||
&[0x48, 0xc7, 0x04, 0x25, 0, 0, 0, 0, 17, 0, 0, 0],
|
||||
] {
|
||||
let mut pe = create_synthetic_probe_pe();
|
||||
let end = 0x200 + encoding.len();
|
||||
@@ -254,7 +254,7 @@ fn probe_consumes_complete_c7_operands_even_when_native_support_is_missing() {
|
||||
let records = report.instruction_records;
|
||||
assert_eq!(records.len(), 2);
|
||||
assert_eq!(records[0].bytes, encoding);
|
||||
assert_eq!(records[0].is_supported_dbt, supported);
|
||||
assert!(records[0].is_supported_dbt && records[0].is_supported_interp);
|
||||
assert_eq!(records[1].rva, 0x1000 + encoding.len() as u32);
|
||||
assert!(!records[1].is_supported_dbt);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
use xenora_loader::probe::{ProbeConfig, probe_pe_bytes};
|
||||
|
||||
/// The static probe must never panic on a truncated PE.
|
||||
///
|
||||
/// The fixture is truncated across its whole length, which covers the range
|
||||
/// where the import directory and the import names overlap the end of the
|
||||
/// file, and every other range where a name or thunk read computed from the
|
||||
/// section header can run past the buffer.
|
||||
#[test]
|
||||
fn probe_never_panics_on_truncated_input() {
|
||||
let pe = include_bytes!("../../../fixtures/pe/trusted-runner.exe");
|
||||
for len in 1..=pe.len() {
|
||||
let truncated = &pe[..len];
|
||||
// The probe may reject the file or report it with unreadable
|
||||
// imports, but it must not panic.
|
||||
let _ = probe_pe_bytes(truncated, &ProbeConfig::default());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Base relocation regression tests (#81).
|
||||
//!
|
||||
//! Images are built byte by byte from the PE/COFF layout: data directory 5
|
||||
//! (Base Relocation Table) at optional-header offset 152, and blocks made of a
|
||||
//! 4-byte page RVA, a 4-byte block size and 2-byte entries whose top 4 bits
|
||||
//! are the type (0 = ABSOLUTE padding, 3 = HIGHLOW, 10 = DIR64).
|
||||
|
||||
use xenora_loader::{GuestMemory, ParsedPe, RelocationError, apply_relocations};
|
||||
|
||||
const PREFERRED: u64 = 0x1_4000_0000;
|
||||
const RELOC_FILE: usize = 0x400;
|
||||
|
||||
/// .text at RVA 0x1000 (file 0x200) holding two pointers, .reloc at RVA 0x2000 (file 0x400).
|
||||
/// `NumberOfRvaAndSizes` and the relocation table bytes are parameters.
|
||||
fn build(rva_and_sizes: u32, table: &[u8], dir_size: u32) -> Vec<u8> {
|
||||
let mut pe = vec![0u8; 0x600];
|
||||
pe[0..2].copy_from_slice(b"MZ");
|
||||
pe[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
|
||||
pe[0x40..0x44].copy_from_slice(b"PE\0\0");
|
||||
let coff = 0x44;
|
||||
pe[coff..coff + 2].copy_from_slice(&0x8664u16.to_le_bytes());
|
||||
pe[coff + 2..coff + 4].copy_from_slice(&2u16.to_le_bytes());
|
||||
pe[coff + 16..coff + 18].copy_from_slice(&240u16.to_le_bytes());
|
||||
let opt = coff + 20;
|
||||
pe[opt..opt + 2].copy_from_slice(&0x020Bu16.to_le_bytes());
|
||||
pe[opt + 16..opt + 20].copy_from_slice(&0x1000u32.to_le_bytes());
|
||||
pe[opt + 24..opt + 32].copy_from_slice(&PREFERRED.to_le_bytes());
|
||||
pe[opt + 32..opt + 36].copy_from_slice(&0x1000u32.to_le_bytes());
|
||||
pe[opt + 36..opt + 40].copy_from_slice(&0x200u32.to_le_bytes());
|
||||
pe[opt + 56..opt + 60].copy_from_slice(&0x3000u32.to_le_bytes());
|
||||
pe[opt + 60..opt + 64].copy_from_slice(&0x200u32.to_le_bytes());
|
||||
pe[opt + 108..opt + 112].copy_from_slice(&rva_and_sizes.to_le_bytes());
|
||||
pe[opt + 152..opt + 156].copy_from_slice(&0x2000u32.to_le_bytes());
|
||||
pe[opt + 156..opt + 160].copy_from_slice(&dir_size.to_le_bytes());
|
||||
|
||||
let sections: [(&[u8], u32, u32, u32, u32); 2] = [
|
||||
(b".text", 0x1000, 0x200, 0x200, 0x6000_0020),
|
||||
// .reloc fills the image up to SizeOfImage (0x3000).
|
||||
(b".reloc", 0x2000, 0x1000, RELOC_FILE as u32, 0x4200_0040),
|
||||
];
|
||||
for (i, (name, va, vsize, raw, flags)) in sections.into_iter().enumerate() {
|
||||
let h = opt + 240 + i * 40;
|
||||
pe[h..h + name.len()].copy_from_slice(name);
|
||||
pe[h + 8..h + 12].copy_from_slice(&vsize.to_le_bytes());
|
||||
pe[h + 12..h + 16].copy_from_slice(&va.to_le_bytes());
|
||||
pe[h + 16..h + 20].copy_from_slice(&0x200u32.to_le_bytes());
|
||||
pe[h + 20..h + 24].copy_from_slice(&raw.to_le_bytes());
|
||||
pe[h + 36..h + 40].copy_from_slice(&flags.to_le_bytes());
|
||||
}
|
||||
|
||||
// Two absolute pointers into the image, at RVAs 0x1010 and 0x1018.
|
||||
pe[0x210..0x218].copy_from_slice(&(PREFERRED + 0x1100).to_le_bytes());
|
||||
pe[0x218..0x220].copy_from_slice(&(PREFERRED + 0x2000).to_le_bytes());
|
||||
pe[RELOC_FILE..RELOC_FILE + table.len()].copy_from_slice(table);
|
||||
pe
|
||||
}
|
||||
|
||||
fn block(page_rva: u32, entries: &[u16]) -> Vec<u8> {
|
||||
let mut b = page_rva.to_le_bytes().to_vec();
|
||||
b.extend_from_slice(&(8 + 2 * entries.len() as u32).to_le_bytes());
|
||||
for e in entries {
|
||||
b.extend_from_slice(&e.to_le_bytes());
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
/// DIR64 at 0x1010 and 0x1018, plus one ABSOLUTE padding entry to keep 4-byte alignment.
|
||||
fn standard_table() -> Vec<u8> {
|
||||
block(0x1000, &[0xA010, 0xA018, 0x0000])
|
||||
}
|
||||
|
||||
fn load(bytes: &[u8], base: u64) -> (ParsedPe, GuestMemory) {
|
||||
let pe = ParsedPe::parse(bytes).expect("parse");
|
||||
let mut memory = GuestMemory::new();
|
||||
for s in &pe.sections {
|
||||
let raw = &bytes[s.raw_data_ptr as usize..(s.raw_data_ptr + s.raw_data_size) as usize];
|
||||
memory
|
||||
.map_region_with_data(
|
||||
base + u64::from(s.virtual_address),
|
||||
0x200,
|
||||
s.permissions,
|
||||
raw,
|
||||
)
|
||||
.expect("map");
|
||||
}
|
||||
(pe, memory)
|
||||
}
|
||||
|
||||
fn relocate(
|
||||
bytes: &[u8],
|
||||
base: u64,
|
||||
) -> (
|
||||
Result<xenora_loader::RelocationReport, RelocationError>,
|
||||
GuestMemory,
|
||||
) {
|
||||
let (pe, mut memory) = load(bytes, base);
|
||||
let result = apply_relocations(&pe, bytes, base, &mut memory);
|
||||
(result, memory)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn positive_rebase_adds_delta_to_each_dir64_target() {
|
||||
let table = standard_table();
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let base = PREFERRED + 0x1_0000_0000;
|
||||
let (result, memory) = relocate(&bytes, base);
|
||||
let report = result.expect("relocate");
|
||||
assert_eq!(report.delta, 0x1_0000_0000);
|
||||
assert_eq!(report.applied_dir64, 2);
|
||||
assert_eq!(report.skipped_absolute, 1);
|
||||
assert_eq!(report.total_entries, 3);
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(base + 0x1010).unwrap(),
|
||||
base + 0x1100
|
||||
);
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(base + 0x1018).unwrap(),
|
||||
base + 0x2000
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negative_rebase_subtracts_delta() {
|
||||
let table = standard_table();
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let base = 0x1000_0000;
|
||||
let (result, memory) = relocate(&bytes, base);
|
||||
assert_eq!(
|
||||
result.expect("relocate").delta,
|
||||
base as i64 - PREFERRED as i64
|
||||
);
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(base + 0x1010).unwrap(),
|
||||
base + 0x1100
|
||||
);
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(base + 0x1018).unwrap(),
|
||||
base + 0x2000
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preferred_base_leaves_targets_unchanged() {
|
||||
let table = standard_table();
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let (result, memory) = relocate(&bytes, PREFERRED);
|
||||
assert_eq!(result.expect("relocate").applied_dir64, 0);
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(PREFERRED + 0x1010).unwrap(),
|
||||
PREFERRED + 0x1100
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directory_beyond_declared_count_is_ignored() {
|
||||
// NumberOfRvaAndSizes = 5 means directory index 5 does not exist.
|
||||
let table = standard_table();
|
||||
let bytes = build(5, &table, table.len() as u32);
|
||||
let base = PREFERRED + 0x1_0000_0000;
|
||||
let (result, memory) = relocate(&bytes, base);
|
||||
assert_eq!(result.expect("relocate").applied_dir64, 0);
|
||||
assert_eq!(
|
||||
memory.read_u64_bypass(base + 0x1010).unwrap(),
|
||||
PREFERRED + 0x1100
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_type_is_rejected() {
|
||||
let table = block(0x1000, &[0x3010, 0x0000]); // HIGHLOW is not a PE32+ fixup here
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
|
||||
assert_eq!(
|
||||
result.unwrap_err(),
|
||||
RelocationError::UnsupportedRelocationType(3)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_block_sizes_are_rejected() {
|
||||
let base = PREFERRED + 0x1000;
|
||||
for size in [0u32, 4, 7, 11] {
|
||||
let mut table = 0x1000u32.to_le_bytes().to_vec();
|
||||
table.extend_from_slice(&size.to_le_bytes());
|
||||
table.extend_from_slice(&[0; 8]);
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let (result, _) = relocate(&bytes, base);
|
||||
assert_eq!(
|
||||
result.unwrap_err(),
|
||||
RelocationError::MalformedBlockHeader { offset: RELOC_FILE },
|
||||
"block size {size}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn block_larger_than_directory_is_rejected() {
|
||||
let table = standard_table(); // 14 bytes
|
||||
let bytes = build(16, &table, 12);
|
||||
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
|
||||
assert_eq!(
|
||||
result.unwrap_err(),
|
||||
RelocationError::BlockSizeOutOfBounds {
|
||||
block_size: 14,
|
||||
max_size: 12
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trailing_partial_block_header_is_rejected() {
|
||||
let mut table = block(0x1000, &[0xA010, 0x0000]);
|
||||
table.extend_from_slice(&[0; 4]);
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
|
||||
assert_eq!(
|
||||
result.unwrap_err(),
|
||||
RelocationError::MalformedBlockHeader {
|
||||
offset: RELOC_FILE + 12
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directory_past_end_of_file_is_rejected() {
|
||||
let table = standard_table();
|
||||
let bytes = build(16, &table, 0x300); // .reloc raw data starts at 0x400 in a 0x600-byte file
|
||||
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
|
||||
assert_eq!(
|
||||
result.unwrap_err(),
|
||||
RelocationError::DirectoryOutOfBounds {
|
||||
rva: 0x2000,
|
||||
size: 0x300
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_outside_image_is_rejected_even_if_mapped() {
|
||||
// SizeOfImage is 0x3000; RVA 0x3000 is past the image but mapped by another region.
|
||||
let table = block(0x3000, &[0xA000, 0x0000]);
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let base = PREFERRED + 0x1000;
|
||||
let (pe, mut memory) = load(&bytes, base);
|
||||
let rw = pe.sections[1].permissions;
|
||||
memory
|
||||
.map_region(base + 0x3000, 0x1000, rw)
|
||||
.expect("adjacent mapping");
|
||||
memory.write_u64_bypass(base + 0x3000, 0x55).unwrap();
|
||||
let result = apply_relocations(&pe, &bytes, base, &mut memory);
|
||||
assert_eq!(
|
||||
result.unwrap_err(),
|
||||
RelocationError::TargetOutOfBounds {
|
||||
target_va: base + 0x3000
|
||||
}
|
||||
);
|
||||
assert_eq!(memory.read_u64_bypass(base + 0x3000).unwrap(), 0x55);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn target_rva_at_top_of_address_space_is_rejected() {
|
||||
let table = block(0xFFFF_F000, &[0xAFFC, 0x0000]);
|
||||
let bytes = build(16, &table, table.len() as u32);
|
||||
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
|
||||
assert!(matches!(
|
||||
result,
|
||||
Err(RelocationError::TargetOutOfBounds { .. })
|
||||
));
|
||||
}
|
||||
@@ -0,0 +1,981 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Typed runtime services, called by translated guest code through a bound
|
||||
//! import table, and the import parser and registry behind them.
|
||||
//!
|
||||
//! Expected values come from the public Win32, ISO C and Microsoft x64 calling
|
||||
//! convention documentation, not from the registry or the handlers.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use xenora_loader::cpu::{CpuState, ExitReason, Register};
|
||||
use xenora_loader::dbt::DbtEngine;
|
||||
use xenora_loader::import_table::{ImportName, ImportTableError, MAX_IMPORTS, parse_imports};
|
||||
use xenora_loader::imports::{
|
||||
ImportError, ImportRegistry, RegistryError, ServiceStatus, Win64Args,
|
||||
};
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
use xenora_loader::pe::ParsedPe;
|
||||
use xenora_loader::probe::{ProbeConfig, ProbeReport, probe_pe_bytes};
|
||||
use xenora_loader::runtime::{Call, Float32, Float64};
|
||||
use xenora_loader::runtime_table::SERVICES;
|
||||
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
|
||||
|
||||
const BASE: u64 = 0x1_4000_0000;
|
||||
const CODE_RVA: u32 = 0x1000;
|
||||
const IDATA_RVA: u32 = 0x10000;
|
||||
const IDATA_RAW: usize = 0x2200;
|
||||
const IDATA_LEN: usize = 0x4000;
|
||||
const SCRATCH: u64 = 0x5_0000;
|
||||
const STACK: u64 = 0x8_0000;
|
||||
const STACK_TOP: u64 = STACK + 0x800;
|
||||
|
||||
#[derive(Clone)]
|
||||
enum Symbol {
|
||||
Name(&'static str),
|
||||
Ordinal(u16),
|
||||
}
|
||||
|
||||
/// Original PE32+ image importing `imports`, one descriptor each. The code for
|
||||
/// import `n`, at RVA 0x1000 + 16n, is `call [its slot]; hlt`.
|
||||
struct Image {
|
||||
bytes: Vec<u8>,
|
||||
slots: Vec<u32>,
|
||||
}
|
||||
|
||||
fn build(imports: &[(&str, Symbol)]) -> Image {
|
||||
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());
|
||||
}
|
||||
|
||||
let file = |rva: u32| IDATA_RAW + (rva - IDATA_RVA) as usize;
|
||||
let mut next = IDATA_RVA + 20 * (imports.len() as u32 + 1);
|
||||
let mut take = |len: usize| {
|
||||
let rva = next;
|
||||
next = (next + len as u32 + 7) & !7;
|
||||
rva
|
||||
};
|
||||
let mut slots = Vec::new();
|
||||
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 entry = match symbol {
|
||||
Symbol::Ordinal(ordinal) => 1 << 63 | u64::from(*ordinal),
|
||||
Symbol::Name(name) => {
|
||||
let hint = take(name.len() + 3);
|
||||
put(&mut pe, file(hint) + 2, name.as_bytes());
|
||||
u64::from(hint)
|
||||
}
|
||||
};
|
||||
let (lookup, slot) = (take(16), take(16));
|
||||
put(&mut pe, file(lookup), &entry.to_le_bytes());
|
||||
put(&mut pe, file(slot), &entry.to_le_bytes());
|
||||
let descriptor = file(IDATA_RVA) + 20 * index;
|
||||
put(&mut pe, descriptor, &lookup.to_le_bytes());
|
||||
put(&mut pe, descriptor + 12, &module_rva.to_le_bytes());
|
||||
put(&mut pe, descriptor + 16, &slot.to_le_bytes());
|
||||
slots.push(slot);
|
||||
|
||||
let code_rva = CODE_RVA + 16 * index as u32;
|
||||
let displacement = slot.wrapping_sub(code_rva + 6);
|
||||
let at = 0x200 + 16 * index;
|
||||
put(&mut pe, at, &[0xFF, 0x15]); // call qword ptr [rip + displacement]
|
||||
put(&mut pe, at + 2, &displacement.to_le_bytes());
|
||||
put(&mut pe, at + 6, &[0xF4]); // hlt
|
||||
}
|
||||
Image { bytes: pe, slots }
|
||||
}
|
||||
|
||||
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())));
|
||||
(registry, clock)
|
||||
}
|
||||
|
||||
/// A guest whose image imports every generated service from its own library.
|
||||
struct Guest {
|
||||
engine: DbtEngine,
|
||||
memory: GuestMemory,
|
||||
clock: Arc<MockClock>,
|
||||
/// Upper halves and XMM lanes of unrelated arguments hold this pattern.
|
||||
xmm: [u128; 4],
|
||||
}
|
||||
|
||||
impl Guest {
|
||||
fn new() -> Self {
|
||||
let imports: Vec<(&str, Symbol)> = SERVICES
|
||||
.iter()
|
||||
.map(|service| (service.library, Symbol::Name(service.symbol)))
|
||||
.collect();
|
||||
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, 0x100, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region(STACK, 0x1000, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
let (mut registry, clock) = standard(0x01DA_0000_1234_5678);
|
||||
let bound = registry
|
||||
.bind_imports(&pe, &image.bytes, BASE, &mut memory)
|
||||
.unwrap();
|
||||
assert_eq!(bound, SERVICES.len());
|
||||
let mut engine = DbtEngine::new(256 * 1024).unwrap();
|
||||
engine.set_import_registry(registry);
|
||||
Self {
|
||||
engine,
|
||||
memory,
|
||||
clock,
|
||||
xmm: [0xAAAA_BBBB_CCCC_DDDD_EEEE_FFFF_0123_4567; 4],
|
||||
}
|
||||
}
|
||||
|
||||
fn run(&mut self, symbol: &str, args: &[u64]) -> (CpuState, ExitReason) {
|
||||
let index = SERVICES
|
||||
.iter()
|
||||
.position(|service| service.symbol == symbol)
|
||||
.unwrap();
|
||||
let mut cpu = CpuState::new(BASE + u64::from(CODE_RVA) + 16 * index as u64, STACK_TOP);
|
||||
for (index, register) in cpu.gpr.iter_mut().enumerate() {
|
||||
if index != Register::Rsp as usize {
|
||||
*register = 0x0101_0101_0101_0101 * (index as u64 + 1);
|
||||
}
|
||||
}
|
||||
for (register, value) in [Register::Rcx, Register::Rdx, Register::R8, Register::R9]
|
||||
.into_iter()
|
||||
.zip(args)
|
||||
{
|
||||
cpu.set(register, *value);
|
||||
}
|
||||
for (index, register) in cpu.xmm.iter_mut().enumerate() {
|
||||
*register = 0x1111_2222_3333_4444_5555_6666_7777_0000 + index as u128;
|
||||
}
|
||||
cpu.xmm[..4].copy_from_slice(&self.xmm);
|
||||
let before = cpu.clone();
|
||||
let result = self.engine.run(&mut cpu, &mut self.memory, 8);
|
||||
if result.exit_reason == ExitReason::Halt {
|
||||
use Register::{R12, R13, R14, R15, Rbp, Rbx, Rdi, Rsi, Rsp};
|
||||
for register in [Rbx, Rbp, Rdi, Rsi, Rsp, R12, R13, R14, R15] {
|
||||
assert_eq!(
|
||||
cpu.get(register),
|
||||
before.get(register),
|
||||
"{symbol} {register:?}"
|
||||
);
|
||||
}
|
||||
assert_eq!(cpu.xmm[6..], before.xmm[6..], "{symbol}");
|
||||
assert_eq!(cpu.mxcsr, before.mxcsr, "{symbol}");
|
||||
}
|
||||
(cpu, result.exit_reason)
|
||||
}
|
||||
|
||||
fn call(&mut self, symbol: &str, args: &[u64]) -> u64 {
|
||||
let (cpu, exit) = self.run(symbol, args);
|
||||
assert_eq!(exit, ExitReason::Halt, "{symbol}");
|
||||
cpu.get(Register::Rax)
|
||||
}
|
||||
|
||||
fn last_error(&mut self) -> u64 {
|
||||
self.call("GetLastError", &[])
|
||||
}
|
||||
}
|
||||
|
||||
const PROCESS: u64 = u64::MAX;
|
||||
const THREAD: u64 = u64::MAX - 1;
|
||||
|
||||
#[test]
|
||||
fn identity_services_return_documented_pseudo_handles_and_ids() {
|
||||
let mut guest = Guest::new();
|
||||
assert_eq!(guest.call("GetCurrentProcess", &[]), PROCESS);
|
||||
assert_eq!(guest.call("GetCurrentThread", &[]), THREAD);
|
||||
let id = guest.call("GetCurrentProcessId", &[]);
|
||||
assert!(id != 0 && id <= u64::from(u32::MAX));
|
||||
assert_ne!(guest.call("GetCurrentThreadId", &[]), id);
|
||||
assert_eq!(guest.call("GetProcessId", &[PROCESS]), id);
|
||||
assert_eq!(guest.call("GetProcessId", &[THREAD]), 0);
|
||||
assert_eq!(guest.last_error(), 6); // ERROR_INVALID_HANDLE
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn priority_boost_round_trips_and_checks_its_handle() {
|
||||
let mut guest = Guest::new();
|
||||
let read = |guest: &mut Guest| {
|
||||
guest.memory.write_u64(SCRATCH, u64::MAX).unwrap();
|
||||
assert_eq!(
|
||||
guest.call("GetProcessPriorityBoost", &[PROCESS, SCRATCH]),
|
||||
1
|
||||
);
|
||||
// A BOOL is four bytes; the next four stay untouched.
|
||||
assert_eq!(guest.memory.read_u32(SCRATCH + 4).unwrap(), u32::MAX);
|
||||
guest.memory.read_u32(SCRATCH).unwrap()
|
||||
};
|
||||
assert_eq!(read(&mut guest), 0);
|
||||
// Any nonzero BOOL disables; bits above 32 are not part of the argument.
|
||||
assert_eq!(
|
||||
guest.call("SetProcessPriorityBoost", &[PROCESS, 0xFFFF_FFFF_0000_0002]),
|
||||
1
|
||||
);
|
||||
assert_eq!(read(&mut guest), 1);
|
||||
assert_eq!(
|
||||
guest.call("SetProcessPriorityBoost", &[PROCESS, 0xFFFF_FFFF_0000_0000]),
|
||||
1
|
||||
);
|
||||
assert_eq!(read(&mut guest), 0);
|
||||
assert_eq!(guest.call("SetProcessPriorityBoost", &[THREAD, 1]), 0);
|
||||
assert_eq!(guest.last_error(), 6);
|
||||
assert_eq!(
|
||||
guest.call("GetProcessPriorityBoost", &[PROCESS, 0x9000_0000]),
|
||||
0
|
||||
);
|
||||
assert_eq!(guest.last_error(), 998); // ERROR_NOACCESS
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_handles_check_access_and_are_rejected_once_closed() {
|
||||
let mut guest = Guest::new();
|
||||
let id = guest.call("GetCurrentThreadId", &[]);
|
||||
// THREAD_QUERY_INFORMATION only.
|
||||
let query = guest.call("OpenThread", &[0x40, 0, id]);
|
||||
assert_ne!(query, 0);
|
||||
assert_eq!(guest.call("GetThreadPriority", &[query]), 0);
|
||||
assert_eq!(guest.call("SetThreadPriority", &[query, 1]), 0);
|
||||
assert_eq!(guest.last_error(), 5); // ERROR_ACCESS_DENIED
|
||||
assert_eq!(guest.call("GetThreadPriority", &[query]), 0);
|
||||
// THREAD_SET_INFORMATION | THREAD_QUERY_INFORMATION.
|
||||
let full = guest.call("OpenThread", &[0x60, 0, id]);
|
||||
assert_ne!(full, query);
|
||||
// A negative int is returned in EAX with the upper half clear.
|
||||
assert_eq!(
|
||||
guest.call("SetThreadPriority", &[full, 0xABCD_0000_FFFF_FFFE]),
|
||||
1
|
||||
);
|
||||
assert_eq!(guest.call("GetThreadPriority", &[full]), 0xFFFF_FFFE);
|
||||
assert_eq!(guest.call("SetThreadPriority", &[full, 3]), 0);
|
||||
assert_eq!(guest.last_error(), 87); // ERROR_INVALID_PARAMETER
|
||||
assert_eq!(guest.call("CloseHandle", &[full]), 1);
|
||||
assert_eq!(guest.call("GetThreadPriority", &[full]), 0x7FFF_FFFF);
|
||||
assert_eq!(guest.last_error(), 6);
|
||||
assert_eq!(guest.call("CloseHandle", &[full]), 0);
|
||||
assert_eq!(guest.call("OpenThread", &[0x40, 0, id + 1]), 0);
|
||||
assert_eq!(guest.last_error(), 87);
|
||||
assert_eq!(guest.call("OpenThread", &[0x40, 1, id]), 0);
|
||||
assert_eq!(guest.last_error(), 50); // ERROR_NOT_SUPPORTED
|
||||
assert_ne!(
|
||||
guest.call("OpenThread", &[0x40, 0, id]),
|
||||
full,
|
||||
"handles are not reused"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn system_time_comes_from_the_injected_clock() {
|
||||
let mut guest = Guest::new();
|
||||
guest.call("GetSystemTimeAsFileTime", &[SCRATCH + 3]);
|
||||
assert_eq!(
|
||||
guest.memory.read_u64(SCRATCH + 3).unwrap(),
|
||||
0x01DA_0000_1234_5678
|
||||
);
|
||||
guest.clock.advance(10);
|
||||
guest.call("GetSystemTimeAsFileTime", &[SCRATCH]);
|
||||
assert_eq!(
|
||||
guest.memory.read_u64(SCRATCH).unwrap(),
|
||||
0x01DA_0000_1234_5682
|
||||
);
|
||||
for pointer in [0, SCRATCH + 0xFC] {
|
||||
let before = guest.memory.read_u32(SCRATCH + 0xFC).unwrap();
|
||||
let (_, exit) = guest.run("GetSystemTimeAsFileTime", &[pointer]);
|
||||
assert!(matches!(exit, ExitReason::MemoryFault(_)), "{exit:?}");
|
||||
assert_eq!(guest.memory.read_u32(SCRATCH + 0xFC).unwrap(), before);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn last_error_is_set_by_failures_and_by_the_guest() {
|
||||
let mut guest = Guest::new();
|
||||
assert_eq!(guest.last_error(), 0);
|
||||
guest.call("SetLastError", &[0xFFFF_FFFF_8000_0001]);
|
||||
assert_eq!(guest.last_error(), 0x8000_0001);
|
||||
assert_eq!(guest.call("GetCurrentProcess", &[]), PROCESS);
|
||||
assert_eq!(
|
||||
guest.last_error(),
|
||||
0x8000_0001,
|
||||
"success leaves it unchanged"
|
||||
);
|
||||
guest.call("CloseHandle", &[0x1234]);
|
||||
assert_eq!(guest.last_error(), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn virtual_memory_is_mapped_released_and_bounded() {
|
||||
let mut guest = Guest::new();
|
||||
const COMMIT_RESERVE: u64 = 0x3000;
|
||||
const RELEASE: u64 = 0x8000;
|
||||
let address = guest.call("VirtualAlloc", &[0, 5000, COMMIT_RESERVE, 0x04]);
|
||||
assert!(address != 0 && address.is_multiple_of(0x1_0000));
|
||||
assert_eq!(
|
||||
guest.memory.read_u64(address + 8184).unwrap(),
|
||||
0,
|
||||
"zeroed, whole pages"
|
||||
);
|
||||
assert!(guest.memory.read_u8(address + 8192).is_err());
|
||||
guest.memory.write_u64(address, 7).unwrap();
|
||||
for (args, error) in [
|
||||
([0, 0, COMMIT_RESERVE, 0x04], 87),
|
||||
([0, 4096, 0x1000, 0x04], 50),
|
||||
([0, 4096, COMMIT_RESERVE, 0x40], 87),
|
||||
([address, 4096, COMMIT_RESERVE, 0x04], 487),
|
||||
([0, u64::MAX, COMMIT_RESERVE, 0x04], 87),
|
||||
([0, 1 << 40, COMMIT_RESERVE, 0x04], 8),
|
||||
] {
|
||||
assert_eq!(guest.call("VirtualAlloc", &args), 0, "{args:x?}");
|
||||
assert_eq!(guest.last_error(), error, "{args:x?}");
|
||||
}
|
||||
for (args, error) in [
|
||||
([address, 4096, RELEASE], 87),
|
||||
([address, 0, 0x4000], 50),
|
||||
([address + 4096, 0, RELEASE], 487),
|
||||
] {
|
||||
assert_eq!(guest.call("VirtualFree", &args), 0, "{args:x?}");
|
||||
assert_eq!(guest.last_error(), error, "{args:x?}");
|
||||
}
|
||||
assert_eq!(guest.call("VirtualFree", &[address, 0, RELEASE]), 1);
|
||||
assert!(guest.memory.read_u8(address).is_err());
|
||||
assert_eq!(guest.call("VirtualFree", &[address, 0, RELEASE]), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn floating_arguments_and_results_use_xmm_registers() {
|
||||
let mut guest = Guest::new();
|
||||
let mut float = |symbol: &str, bits: u64| {
|
||||
// Only the low lane is the argument, and RCX must be ignored.
|
||||
guest.xmm[0] = 0xFFFF_FFFF_FFFF_FFFF << 64 | u128::from(bits);
|
||||
let (cpu, exit) = guest.run(symbol, &[0x4022_0000_0000_0000]);
|
||||
assert_eq!(exit, ExitReason::Halt);
|
||||
cpu.xmm[0]
|
||||
};
|
||||
assert_eq!(
|
||||
float("sqrt", 0x4030_0000_0000_0000) as u64,
|
||||
0x4010_0000_0000_0000
|
||||
); // 16 -> 4
|
||||
assert_eq!(
|
||||
float("sqrt", 0x4000_0000_0000_0000) as u64,
|
||||
0x3FF6_A09E_667F_3BCD
|
||||
); // sqrt 2
|
||||
assert_eq!(
|
||||
float("sqrt", 0x8000_0000_0000_0000) as u64,
|
||||
0x8000_0000_0000_0000
|
||||
); // -0
|
||||
assert_eq!(
|
||||
float("sqrt", 0x7FF0_0000_0000_0000) as u64,
|
||||
0x7FF0_0000_0000_0000
|
||||
);
|
||||
let nan = float("sqrt", 0xBFF0_0000_0000_0000) as u64;
|
||||
assert!(f64::from_bits(nan).is_nan());
|
||||
assert_eq!(
|
||||
float("fabs", 0xC004_0000_0000_0000) as u64,
|
||||
0x4004_0000_0000_0000
|
||||
); // -2.5
|
||||
assert_eq!(float("fabs", 0x8000_0000_0000_0000) as u64, 0);
|
||||
let garbage = 0xDEAD_BEEF_0000_0000;
|
||||
assert_eq!(float("sqrtf", garbage | 0x4110_0000) as u32, 0x4040_0000); // 9 -> 3
|
||||
assert_eq!(float("fabsf", garbage | 0xBF80_0000) as u32, 0x3F80_0000); // -1
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arguments_are_assigned_by_position_and_read_the_stack_after_the_fourth() {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region(STACK, 0x1000, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
// [RSP] return address, 32 bytes of shadow space, then arguments 4 and 5.
|
||||
memory
|
||||
.write_u64(STACK_TOP + 40, 0x1122_3344_5566_7788)
|
||||
.unwrap();
|
||||
memory
|
||||
.write_u64(STACK_TOP + 48, 0x4008_0000_0000_0000)
|
||||
.unwrap();
|
||||
let mut cpu = CpuState::new(0, STACK_TOP);
|
||||
for (index, register) in [Register::Rcx, Register::Rdx, Register::R8, Register::R9]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
cpu.set(register, 0xFFFF_FFFF_0000_0010 + index as u64);
|
||||
cpu.xmm[index] = (1 << 100) + 0xAAAA_AAAA_0000_0020 + index as u128;
|
||||
}
|
||||
let args = Win64Args::new(&cpu);
|
||||
let call = Call::new(&args, &cpu, &memory);
|
||||
assert_eq!(call.u32(0), Ok(0x10));
|
||||
assert_eq!(call.f64(1), Ok(Float64(0xAAAA_AAAA_0000_0021)));
|
||||
assert_eq!(call.f32(2), Ok(Float32(0x22)));
|
||||
assert_eq!(call.u64(3), Ok(0xFFFF_FFFF_0000_0013));
|
||||
assert_eq!(call.i32(4), Ok(0x5566_7788));
|
||||
assert_eq!(call.f64(5), Ok(Float64(0x4008_0000_0000_0000)));
|
||||
cpu.set(Register::Rsp, STACK + 0xFF0);
|
||||
let args = Win64Args::new(&cpu);
|
||||
let call = Call::new(&args, &cpu, &memory);
|
||||
assert!(matches!(call.u64(4), Err(ExitReason::MemoryFault(_))));
|
||||
cpu.set(Register::Rsp, u64::MAX - 8);
|
||||
let args = Win64Args::new(&cpu);
|
||||
assert!(Call::new(&args, &cpu, &memory).f64(4).is_err());
|
||||
}
|
||||
|
||||
// --- registry ----------------------------------------------------------------
|
||||
|
||||
fn named(name: &str) -> ImportName {
|
||||
ImportName::Name(name.to_owned())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_metadata_matches_the_live_registry() {
|
||||
let (registry, _) = standard(0);
|
||||
for service in &SERVICES {
|
||||
let descriptor = registry
|
||||
.resolve(service.library, &named(service.symbol))
|
||||
.unwrap();
|
||||
assert_eq!(descriptor.status, service.status, "{}", service.symbol);
|
||||
assert!(!service.tests.is_empty());
|
||||
for alias in service.aliases {
|
||||
let upper = alias.to_ascii_uppercase();
|
||||
let aliased = registry.resolve(&upper, &named(service.symbol)).unwrap();
|
||||
assert!(
|
||||
std::ptr::eq(aliased, descriptor),
|
||||
"{alias}!{}",
|
||||
service.symbol
|
||||
);
|
||||
}
|
||||
// Symbol names are exact, and unlisted API sets do not resolve.
|
||||
assert!(
|
||||
registry
|
||||
.resolve(
|
||||
service.library,
|
||||
&named(&service.symbol.to_ascii_uppercase())
|
||||
)
|
||||
.is_none()
|
||||
|| service.symbol == service.symbol.to_ascii_uppercase()
|
||||
);
|
||||
assert!(
|
||||
registry
|
||||
.resolve("api-ms-win-core-file-l1-1-0.dll", &named(service.symbol))
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conflicting_or_invalid_registrations_are_refused() {
|
||||
let handler = || Box::new(|_: &Win64Args, _: &mut CpuState, _: &mut GuestMemory| Ok(0));
|
||||
let mut registry = ImportRegistry::new();
|
||||
let mut add = |module: &str, name: ImportName| {
|
||||
registry.try_register(module, name, ServiceStatus::Stub, handler())
|
||||
};
|
||||
assert_eq!(add("a.dll", named("F")), Ok(()));
|
||||
assert_eq!(
|
||||
add("a.dll", named("f")),
|
||||
Ok(()),
|
||||
"symbols are case-sensitive"
|
||||
);
|
||||
assert_eq!(add("b.dll", named("F")), Ok(()));
|
||||
assert!(matches!(
|
||||
add("A.DLL", named("F")),
|
||||
Err(RegistryError::Duplicate { .. })
|
||||
));
|
||||
assert_eq!(add("a.dll", ImportName::Ordinal(7)), Ok(()));
|
||||
assert!(matches!(
|
||||
add("a.dll", ImportName::Ordinal(7)),
|
||||
Err(RegistryError::Duplicate { .. })
|
||||
));
|
||||
assert_eq!(
|
||||
add("a.dll", named("Ordinal#7")),
|
||||
Ok(()),
|
||||
"a name is never an ordinal"
|
||||
);
|
||||
for (module, symbol) in [("", "F"), ("a.dll", ""), ("a b.dll", "F"), ("a.dll", "F\n")] {
|
||||
assert!(matches!(
|
||||
add(module, named(symbol)),
|
||||
Err(RegistryError::InvalidName { .. })
|
||||
));
|
||||
}
|
||||
assert_eq!(registry.try_alias("set.dll", "a.dll", "F"), Ok(()));
|
||||
assert_eq!(
|
||||
registry.try_alias("set.dll", "a.dll", "F"),
|
||||
Ok(()),
|
||||
"repeating is harmless"
|
||||
);
|
||||
assert!(matches!(
|
||||
registry.try_alias("set.dll", "b.dll", "F"),
|
||||
Err(RegistryError::Duplicate { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
registry.try_alias("b.dll", "a.dll", "F"),
|
||||
Err(RegistryError::Duplicate { .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
registry.try_alias("x.dll", "a.dll", "G"),
|
||||
Err(RegistryError::UnknownTarget { .. })
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "kernel32.dll!CloseHandle is already registered")]
|
||||
fn a_host_module_cannot_replace_a_standard_service() {
|
||||
let (mut registry, _) = standard(0);
|
||||
registry.register("KERNEL32.dll", "CloseHandle", |_, _, _| Ok(1));
|
||||
}
|
||||
|
||||
fn bind(registry: &mut ImportRegistry, image: &Image) -> (Result<usize, ImportError>, GuestMemory) {
|
||||
let pe = ParsedPe::parse(&image.bytes).unwrap();
|
||||
let mut memory = pe.load_into_memory(&image.bytes).unwrap().memory;
|
||||
let result = registry.bind_imports(&pe, &image.bytes, BASE, &mut memory);
|
||||
(result, memory)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unresolved_import_leaves_every_slot_unbound() {
|
||||
let image = build(&[
|
||||
("kernel32.dll", Symbol::Name("GetLastError")),
|
||||
("kernel32.dll", Symbol::Name("NoSuchFunction")),
|
||||
]);
|
||||
let (mut registry, _) = standard(0);
|
||||
let (result, memory) = bind(&mut registry, &image);
|
||||
let expected = ImportError::UnresolvedImport {
|
||||
module: "kernel32.dll".into(),
|
||||
symbol: "NoSuchFunction".into(),
|
||||
};
|
||||
assert_eq!(result, Err(expected));
|
||||
for slot in &image.slots {
|
||||
let file = IDATA_RAW + (slot - IDATA_RVA) as usize;
|
||||
let original = u64::from_le_bytes(image.bytes[file..file + 8].try_into().unwrap());
|
||||
assert_eq!(memory.read_u64(BASE + u64::from(*slot)).unwrap(), original);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aliases_share_a_trampoline_and_ordinals_bind_only_ordinals() {
|
||||
let (mut registry, _) = standard(0);
|
||||
registry
|
||||
.try_register(
|
||||
"o.dll",
|
||||
ImportName::Ordinal(7),
|
||||
ServiceStatus::Partial,
|
||||
Box::new(|_, _, _| Ok(77)),
|
||||
)
|
||||
.unwrap();
|
||||
let image = build(&[
|
||||
("KERNEL32.dll", Symbol::Name("GetLastError")),
|
||||
(
|
||||
"API-MS-Win-Core-ErrorHandling-L1-1-0.dll",
|
||||
Symbol::Name("GetLastError"),
|
||||
),
|
||||
("O.DLL", Symbol::Ordinal(7)),
|
||||
]);
|
||||
let (result, memory) = bind(&mut registry, &image);
|
||||
assert_eq!(result, Ok(3));
|
||||
let slot = |index: usize| {
|
||||
memory
|
||||
.read_u64(BASE + u64::from(image.slots[index]))
|
||||
.unwrap()
|
||||
};
|
||||
assert_eq!(slot(0), slot(1));
|
||||
assert_ne!(slot(0), slot(2));
|
||||
for symbol in [Symbol::Name("Ordinal#7"), Symbol::Ordinal(8)] {
|
||||
let (result, _) = bind(&mut registry, &build(&[("o.dll", symbol)]));
|
||||
assert!(
|
||||
matches!(result, Err(ImportError::UnresolvedImport { .. })),
|
||||
"{result:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// A registry with one service bound, and its trampoline address.
|
||||
fn bound_service<F>(handler: F) -> (ImportRegistry, GuestMemory, u64)
|
||||
where
|
||||
F: Fn(&Win64Args, &mut CpuState, &mut GuestMemory) -> Result<u64, ExitReason>
|
||||
+ Send
|
||||
+ Sync
|
||||
+ 'static,
|
||||
{
|
||||
let mut registry = ImportRegistry::new();
|
||||
registry.register("t.dll", "F", handler);
|
||||
let image = build(&[("t.dll", Symbol::Name("F"))]);
|
||||
let (result, mut memory) = bind(&mut registry, &image);
|
||||
assert_eq!(result, Ok(1));
|
||||
memory
|
||||
.map_region(STACK, 0x1000, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
memory.write_u64(STACK_TOP, 0x1234).unwrap();
|
||||
let trampoline = memory.read_u64(BASE + u64::from(image.slots[0])).unwrap();
|
||||
(registry, memory, trampoline)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_service_that_changes_a_nonvolatile_register_stops_the_guest() {
|
||||
use Register::{R8, R9, R10, R11, R12, R13, R14, R15, Rbp, Rbx, Rcx, Rdi, Rdx, Rsi, Rsp};
|
||||
let dispatch = |change: fn(&mut CpuState, usize), which: usize| {
|
||||
let (registry, mut memory, trampoline) = bound_service(move |_, cpu, _| {
|
||||
change(cpu, which);
|
||||
Ok(5)
|
||||
});
|
||||
let mut cpu = CpuState::new(trampoline, STACK_TOP);
|
||||
let result = registry.dispatch(trampoline, &mut cpu, &mut memory);
|
||||
(result, cpu)
|
||||
};
|
||||
for register in [Rbx, Rbp, Rdi, Rsi, Rsp, R12, R13, R14, R15] {
|
||||
let (result, _) = dispatch(|cpu, index| cpu.gpr[index] ^= 8, register as usize);
|
||||
assert_eq!(result, Err(ExitReason::ServiceAbiViolation), "{register:?}");
|
||||
}
|
||||
for register in [Rcx, Rdx, R8, R9, R10, R11] {
|
||||
let (result, cpu) = dispatch(|cpu, index| cpu.gpr[index] ^= 8, register as usize);
|
||||
assert_eq!(result, Ok(()), "{register:?}");
|
||||
assert_eq!(
|
||||
(cpu.rip, cpu.get(Rsp), cpu.get(Register::Rax)),
|
||||
(0x1234, STACK_TOP + 8, 5)
|
||||
);
|
||||
}
|
||||
for index in 0..16 {
|
||||
let (result, _) = dispatch(|cpu, index| cpu.xmm[index] ^= 1 << 127, index);
|
||||
let expected = if index < 6 {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(ExitReason::ServiceAbiViolation)
|
||||
};
|
||||
assert_eq!(result, expected, "xmm{index}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_call_that_cannot_return_runs_no_service() {
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let counter = calls.clone();
|
||||
let (registry, mut memory, trampoline) = bound_service(move |_, _, _| {
|
||||
counter.fetch_add(1, Ordering::SeqCst);
|
||||
Ok(0)
|
||||
});
|
||||
for rsp in [0x9000_0000, STACK + 0xFFC, u64::MAX - 7] {
|
||||
let mut cpu = CpuState::new(trampoline, rsp);
|
||||
let before = cpu.clone();
|
||||
assert!(
|
||||
registry
|
||||
.dispatch(trampoline, &mut cpu, &mut memory)
|
||||
.is_err()
|
||||
);
|
||||
assert_eq!(cpu, before);
|
||||
}
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 0);
|
||||
let mut cpu = CpuState::new(trampoline, STACK_TOP);
|
||||
assert_eq!(registry.dispatch(trampoline, &mut cpu, &mut memory), Ok(()));
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
// --- import table --------------------------------------------------------------
|
||||
|
||||
fn inspect(image: &Image) -> ProbeReport {
|
||||
probe_pe_bytes(&image.bytes, &ProbeConfig::default()).unwrap()
|
||||
}
|
||||
|
||||
/// File offset of an RVA in the import section.
|
||||
fn file(rva: u32) -> usize {
|
||||
IDATA_RAW + (rva - IDATA_RVA) as usize
|
||||
}
|
||||
|
||||
fn u32_at(image: &Image, at: usize) -> u32 {
|
||||
u32::from_le_bytes(image.bytes[at..at + 4].try_into().unwrap())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_import_tables_are_reported_and_never_bound() {
|
||||
let base = || {
|
||||
build(&[
|
||||
("kernel32.dll", Symbol::Name("GetLastError")),
|
||||
("kernel32.dll", Symbol::Name("CloseHandle")),
|
||||
])
|
||||
};
|
||||
let end = IDATA_RVA + IDATA_LEN as u32;
|
||||
let second = IDATA_RAW + 20;
|
||||
type Damage = fn(&mut Image, usize, u32);
|
||||
type Expected = fn(&ImportTableError) -> bool;
|
||||
// (damage to the second descriptor, expected error)
|
||||
let cases: &[(&str, Damage, Expected)] = &[
|
||||
(
|
||||
"name runs off the section (issue #270)",
|
||||
|image, second, end| {
|
||||
let lookup = u32_at(image, second);
|
||||
image.bytes[file(lookup)..file(lookup) + 8]
|
||||
.copy_from_slice(&u64::from(end - 6).to_le_bytes());
|
||||
let at = file(end - 4);
|
||||
image.bytes[at..at + 4].copy_from_slice(b"Name");
|
||||
},
|
||||
|error| matches!(error, ImportTableError::MalformedName { .. }),
|
||||
),
|
||||
(
|
||||
"name pointer at the last byte",
|
||||
|image, second, end| {
|
||||
let lookup = u32_at(image, second);
|
||||
image.bytes[file(lookup)..file(lookup) + 8]
|
||||
.copy_from_slice(&u64::from(end - 1).to_le_bytes());
|
||||
},
|
||||
|error| matches!(error, ImportTableError::MalformedName { .. }),
|
||||
),
|
||||
(
|
||||
"empty name",
|
||||
|image, second, _| {
|
||||
let lookup = u32_at(image, second);
|
||||
let hint = u32_at(image, file(lookup));
|
||||
image.bytes[file(hint) + 2] = 0;
|
||||
},
|
||||
|error| matches!(error, ImportTableError::MalformedName { .. }),
|
||||
),
|
||||
(
|
||||
"non-ASCII name",
|
||||
|image, second, _| {
|
||||
let lookup = u32_at(image, second);
|
||||
let hint = u32_at(image, file(lookup));
|
||||
image.bytes[file(hint) + 4] = 0xC3;
|
||||
},
|
||||
|error| matches!(error, ImportTableError::MalformedName { .. }),
|
||||
),
|
||||
(
|
||||
"module name outside every section",
|
||||
|image, second, _| {
|
||||
image.bytes[second + 12..second + 16].copy_from_slice(&0x7000_0000u32.to_le_bytes())
|
||||
},
|
||||
|error| matches!(error, ImportTableError::MalformedName { .. }),
|
||||
),
|
||||
(
|
||||
"lookup table outside every section",
|
||||
|image, second, _| {
|
||||
image.bytes[second..second + 4].copy_from_slice(&u32::MAX.to_le_bytes())
|
||||
},
|
||||
|error| matches!(error, ImportTableError::OutOfBounds { .. }),
|
||||
),
|
||||
(
|
||||
"reserved bits in a name entry",
|
||||
|image, second, _| {
|
||||
let lookup = u32_at(image, second);
|
||||
image.bytes[file(lookup) + 5] = 1;
|
||||
},
|
||||
|error| matches!(error, ImportTableError::ReservedBits { .. }),
|
||||
),
|
||||
(
|
||||
"bit 31 in a name entry",
|
||||
|image, second, _| {
|
||||
let lookup = u32_at(image, second);
|
||||
image.bytes[file(lookup) + 3] |= 0x80;
|
||||
},
|
||||
|error| matches!(error, ImportTableError::ReservedBits { .. }),
|
||||
),
|
||||
(
|
||||
"name continues in bytes after the section",
|
||||
|image, second, end| {
|
||||
let lookup = u32_at(image, second);
|
||||
image.bytes[file(lookup)..file(lookup) + 8]
|
||||
.copy_from_slice(&u64::from(end - 6).to_le_bytes());
|
||||
let at = file(end - 4);
|
||||
image.bytes[at..at + 4].copy_from_slice(b"Name");
|
||||
image.bytes.extend_from_slice(b"Tail\0");
|
||||
},
|
||||
|error| matches!(error, ImportTableError::MalformedName { .. }),
|
||||
),
|
||||
(
|
||||
"reserved bits in an ordinal entry",
|
||||
|image, second, _| {
|
||||
let lookup = u32_at(image, second);
|
||||
image.bytes[file(lookup)..file(lookup) + 8]
|
||||
.copy_from_slice(&(1u64 << 63 | 0x1_0000).to_le_bytes());
|
||||
},
|
||||
|error| matches!(error, ImportTableError::ReservedBits { .. }),
|
||||
),
|
||||
];
|
||||
for (what, damage, expected) in cases {
|
||||
let mut image = base();
|
||||
damage(&mut image, second, end);
|
||||
let (mut registry, _) = standard(0);
|
||||
let (result, _) = bind(&mut registry, &image);
|
||||
match &result {
|
||||
Err(ImportError::Table(error)) => assert!(expected(error), "{what}: {error:?}"),
|
||||
other => panic!("{what}: {other:?}"),
|
||||
}
|
||||
let report = inspect(&image);
|
||||
assert_eq!(
|
||||
report.import_error.map(ImportError::Table),
|
||||
result.err(),
|
||||
"{what}"
|
||||
);
|
||||
assert_eq!(
|
||||
report.imports.len(),
|
||||
1,
|
||||
"{what}: the first import is still listed"
|
||||
);
|
||||
assert_eq!(report.imports[0].symbol, "GetLastError");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn endless_tables_are_bounded() {
|
||||
// A descriptor at 0, a module name at 0x40, a hint and name at 0x60 and a
|
||||
// lookup entry at 0x80. The mapping repeats one structure without end.
|
||||
let mut bytes = vec![0u8; 0x88];
|
||||
bytes[0..4].copy_from_slice(&0x80u32.to_le_bytes());
|
||||
bytes[12..16].copy_from_slice(&0x40u32.to_le_bytes());
|
||||
bytes[16..20].copy_from_slice(&0x80u32.to_le_bytes());
|
||||
bytes[0x40..0x46].copy_from_slice(b"m.dll\0");
|
||||
bytes[0x62..0x64].copy_from_slice(b"F\0");
|
||||
bytes[0x80] = 0x60;
|
||||
|
||||
// Lookup entries repeat from 0x80 on.
|
||||
let (entries, error) = parse_imports(&bytes, 0, |rva| {
|
||||
let rva = rva as usize;
|
||||
Some(if rva < 0x80 { rva } else { 0x80 + rva % 8 })
|
||||
});
|
||||
assert_eq!(error, Some(ImportTableError::TooManyImports));
|
||||
assert_eq!(entries.len(), MAX_IMPORTS);
|
||||
|
||||
// Descriptors repeat from 0x1000 on; each has one symbol.
|
||||
bytes.extend([0; 8]);
|
||||
let (entries, error) = parse_imports(&bytes, 0x1000, |rva| {
|
||||
let rva = rva as usize;
|
||||
Some(if rva < 0x1000 {
|
||||
rva
|
||||
} else {
|
||||
(rva - 0x1000) % 20
|
||||
})
|
||||
});
|
||||
assert_eq!(error, Some(ImportTableError::TooManyDescriptors));
|
||||
assert_eq!(entries.len(), 1024);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inspection_and_binding_agree_on_damaged_tables() {
|
||||
let base = build(&[
|
||||
("kernel32.dll", Symbol::Name("GetLastError")),
|
||||
(
|
||||
"api-ms-win-core-handle-l1-1-0.dll",
|
||||
Symbol::Name("CloseHandle"),
|
||||
),
|
||||
("ucrtbase.dll", Symbol::Name("sqrt")),
|
||||
("o.dll", Symbol::Ordinal(3)),
|
||||
]);
|
||||
let mut state = 0x2545_F491_4F6C_DD1Du64;
|
||||
let mut next = || {
|
||||
state ^= state >> 12;
|
||||
state ^= state << 25;
|
||||
state ^= state >> 27;
|
||||
state.wrapping_mul(0x9E37_79B9_7F4A_7C15)
|
||||
};
|
||||
let (mut bound, mut malformed, mut unresolved) = (0, 0, 0);
|
||||
for _ in 0..6000 {
|
||||
let mut image = Image {
|
||||
bytes: base.bytes.clone(),
|
||||
slots: base.slots.clone(),
|
||||
};
|
||||
for _ in 0..1 + next() % 3 {
|
||||
let at = IDATA_RAW + (next() % 0x220) as usize;
|
||||
image.bytes[at] = match next() % 4 {
|
||||
0 => 0,
|
||||
1 => 0xFF,
|
||||
_ => next() as u8,
|
||||
};
|
||||
}
|
||||
let (mut registry, _) = standard(0);
|
||||
registry
|
||||
.try_register(
|
||||
"o.dll",
|
||||
ImportName::Ordinal(3),
|
||||
ServiceStatus::Stub,
|
||||
Box::new(|_, _, _| Ok(0)),
|
||||
)
|
||||
.unwrap();
|
||||
let pe = ParsedPe::parse(&image.bytes).unwrap();
|
||||
let mut memory = pe.load_into_memory(&image.bytes).unwrap().memory;
|
||||
let result = registry.bind_imports(&pe, &image.bytes, BASE, &mut memory);
|
||||
let report = inspect(&image);
|
||||
match result {
|
||||
Ok(count) => {
|
||||
bound += 1;
|
||||
assert_eq!(report.import_error, None);
|
||||
assert_eq!(report.imports.len(), count);
|
||||
}
|
||||
Err(ImportError::Table(error)) => {
|
||||
malformed += 1;
|
||||
assert_eq!(report.import_error, Some(error));
|
||||
}
|
||||
Err(ImportError::UnresolvedImport { module, symbol }) => {
|
||||
unresolved += 1;
|
||||
assert_eq!(report.import_error, None);
|
||||
assert!(
|
||||
report
|
||||
.imports
|
||||
.iter()
|
||||
.any(|import| import.dll == module && import.symbol == symbol)
|
||||
);
|
||||
}
|
||||
Err(ImportError::Memory(_)) => {}
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
bound > 100 && malformed > 100 && unresolved > 100,
|
||||
"{bound} {malformed} {unresolved}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inspection_reports_exactly_what_binding_resolves() {
|
||||
let image = build(&[
|
||||
("KERNEL32.dll", Symbol::Name("GetLastError")),
|
||||
("kernel32.dll", Symbol::Name("getlasterror")),
|
||||
(
|
||||
"api-ms-win-core-errorhandling-l1-1-0.dll",
|
||||
Symbol::Name("SetLastError"),
|
||||
),
|
||||
(
|
||||
"api-ms-win-core-errorhandling-l1-1-3.dll",
|
||||
Symbol::Name("SetLastError"),
|
||||
),
|
||||
("kernel32.dll", Symbol::Ordinal(1)),
|
||||
]);
|
||||
let report = inspect(&image);
|
||||
let supported: Vec<bool> = report
|
||||
.imports
|
||||
.iter()
|
||||
.map(|import| import.is_supported)
|
||||
.collect();
|
||||
assert_eq!(supported, [true, false, true, false, false]);
|
||||
assert_eq!(
|
||||
report.imports[2].canonical_module.as_deref(),
|
||||
Some("kernel32.dll")
|
||||
);
|
||||
assert_eq!(report.imports[4].symbol, "Ordinal#1");
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Assemble the original x86-64 fixtures with the LLVM assembler.
|
||||
|
||||
generate write integer.txt, vector.txt and float.txt next to this file
|
||||
--check reassemble in memory and fail if a committed fixture differs
|
||||
|
||||
Each output line is `<hex bytes> | <Intel-syntax text>`. The assembler is
|
||||
`clang -target x86_64-apple-macos` and the bytes are read with `objdump -d`,
|
||||
so no Xenora code takes part in choosing an encoding. Nothing is executed.
|
||||
"""
|
||||
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
LOW = "a c d b sp bp si di".split()
|
||||
CONDITIONS = "o no b ae e ne be a s ns p np l ge le g".split()
|
||||
PTR = {8: "byte", 16: "word", 32: "dword", 64: "qword"}
|
||||
|
||||
|
||||
def reg(index, bits):
|
||||
if index >= 8:
|
||||
return f"r{index}" + {64: "", 32: "d", 16: "w", 8: "b"}[bits]
|
||||
name = LOW[index]
|
||||
if bits == 8:
|
||||
return name + "l"
|
||||
full = name + "x" if index < 4 else name
|
||||
return {64: "r", 32: "e", 16: ""}[bits] + full
|
||||
|
||||
|
||||
def mem(bits):
|
||||
return f"{PTR[bits]} ptr [rsi + 4*rdi + 16]"
|
||||
|
||||
|
||||
def cases():
|
||||
out = []
|
||||
for op in "add or adc sbb and sub xor cmp test".split():
|
||||
for bits in (8, 16, 32, 64):
|
||||
out += [f"{op} {reg(3, bits)}, {reg(1, bits)}", f"{op} {reg(9, bits)}, {reg(12, bits)}",
|
||||
f"{op} {reg(0, bits)}, {reg(0, bits)}", f"{op} {mem(bits)}, {reg(2, bits)}"]
|
||||
if op != "test":
|
||||
# The reversed encoding of a register pair is load-form only.
|
||||
out.append(f"{op} {reg(10, bits)}, {mem(bits)}")
|
||||
imm = {8: "0x7f", 16: "0x1234", 32: "0x12345678", 64: "0x12345678"}[bits]
|
||||
out += [f"{op} {reg(0, bits)}, {imm}", f"{op} {reg(3, bits)}, {imm}",
|
||||
f"{op} {mem(bits)}, {imm}"]
|
||||
if bits != 8:
|
||||
out += [f"{op} {reg(11, bits)}, -3", f"{op} {mem(bits)}, -3"]
|
||||
out += [f"{op} ah, bl", f"{op} cl, dh", f"{op} bh, 0x55"]
|
||||
for op in "inc dec neg not mul imul div idiv".split():
|
||||
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 bits in (8, 16, 32, 64):
|
||||
for count in ("1", "3", "7", "cl"):
|
||||
out += [f"{op} {reg(3, bits)}, {count}", f"{op} {mem(bits)}, {count}"]
|
||||
out += [f"{op} {reg(13, bits)}, {bits - 1}", f"{op} {reg(13, bits)}, 0"]
|
||||
for bits in (16, 32, 64):
|
||||
out += [f"imul {reg(3, bits)}, {reg(9, bits)}", f"imul {reg(3, bits)}, {mem(bits)}",
|
||||
f"imul {reg(8, bits)}, {reg(1, bits)}, -7", f"imul {reg(8, bits)}, {reg(1, bits)}, 0x1234",
|
||||
f"imul {reg(8, bits)}, {mem(bits)}, 0x1234"]
|
||||
for op in "bsf bsr popcnt tzcnt lzcnt".split():
|
||||
out += [f"{op} {reg(3, bits)}, {reg(9, bits)}", f"{op} {reg(10, bits)}, {mem(bits)}"]
|
||||
for op in "bt bts btr btc".split():
|
||||
out += [f"{op} {reg(3, bits)}, {reg(9, bits)}", f"{op} {reg(10, bits)}, 5",
|
||||
f"{op} {mem(bits)}, {bits - 1}"]
|
||||
for cc in CONDITIONS:
|
||||
out += [f"cmov{cc} {reg(3, bits)}, {reg(9, bits)}", f"cmov{cc} {reg(10, bits)}, {mem(bits)}"]
|
||||
for src in (8, 16):
|
||||
if src < bits:
|
||||
for op in ("movzx", "movsx"):
|
||||
out += [f"{op} {reg(3, bits)}, {reg(9, src)}", f"{op} {reg(10, bits)}, {mem(src)}"]
|
||||
out += [f"lea {reg(3, bits)}, [rsi + 4*rdi + 16]", f"lea {reg(12, bits)}, [r9 - 5]",
|
||||
f"lea {reg(0, bits)}, [8*r10 + 64]"]
|
||||
out += ["movsxd rbx, r9d", f"movsxd r10, {mem(32)}", "movzx ebx, ah", "movsx ecx, bh"]
|
||||
for cc in CONDITIONS:
|
||||
out += [f"set{cc} bl", f"set{cc} {mem(8)}", f"set{cc} ah"]
|
||||
for bits in (8, 16, 32, 64):
|
||||
out += [f"mov {reg(3, bits)}, {reg(9, bits)}", f"mov {reg(10, bits)}, {mem(bits)}",
|
||||
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)}"]
|
||||
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",
|
||||
f"push {mem(64)}", "pop rbx", "pop r12", f"pop {mem(64)}", "leave"]
|
||||
return list(dict.fromkeys(out))
|
||||
|
||||
|
||||
PACKED = """punpcklbw punpcklwd punpckldq punpcklqdq punpckhbw punpckhwd punpckhdq punpckhqdq
|
||||
packsswb packssdw packuswb pcmpgtb pcmpgtw pcmpgtd pcmpeqb pcmpeqw pcmpeqd paddb paddw paddd paddq
|
||||
psubb psubw psubd psubq paddsb paddsw paddusb paddusw psubsb psubsw psubusb psubusw pmullw pmulhw
|
||||
pmulhuw pmuludq pmaddwd psadbw pavgb pavgw pminub pmaxub pminsw pmaxsw pand pandn por pxor andps
|
||||
andpd andnps andnpd orps orpd xorps xorpd unpcklps unpcklpd unpckhps unpckhpd psllw pslld psllq
|
||||
psrlw psrld psrlq psraw psrad movaps movapd movups movupd movdqa movdqu""".split()
|
||||
|
||||
|
||||
def vector_cases():
|
||||
wide, quad, dword = (f"{w} ptr [rsi + 4*rdi + 16]" for w in ("xmmword", "qword", "dword"))
|
||||
word = "word ptr [rsi + 4*rdi + 16]"
|
||||
out = []
|
||||
for op in PACKED:
|
||||
out += [f"{op} xmm3, xmm9", f"{op} xmm10, {wide}", f"{op} xmm2, xmm2"]
|
||||
for op in "movaps movapd movups movupd movdqa movdqu movntdq movntps movntpd".split():
|
||||
out.append(f"{op} {wide}, xmm11")
|
||||
for op, width in (("movss", dword), ("movsd", quad), ("movq", quad)):
|
||||
out += [f"{op} xmm3, xmm9", f"{op} xmm10, {width}", f"{op} {width}, xmm11"]
|
||||
for op in "movlps movlpd movhps movhpd".split():
|
||||
out += [f"{op} xmm3, {quad}", f"{op} {quad}, xmm9"]
|
||||
out += ["movhlps xmm3, xmm9", "movlhps xmm10, xmm1", "movhlps xmm2, xmm2", "movlhps xmm2, xmm2"]
|
||||
out += ["movd xmm3, r9d", "movd xmm12, eax", "movq xmm3, r9", "movd r9d, xmm3", "movd ebx, xmm12",
|
||||
"movq r9, xmm3", f"movd xmm3, {dword}", f"movd {dword}, xmm9"]
|
||||
for op in "movmskps movmskpd pmovmskb".split():
|
||||
out += [f"{op} ebx, xmm9", f"{op} r10d, xmm3"]
|
||||
for op, bits in (("w", 16), ("d", 32), ("q", 64)):
|
||||
for name in ("psll", "psrl", "psra"):
|
||||
if name + op != "psraq":
|
||||
out += [f"{name}{op} xmm{3 + 6 * (n % 2)}, {n}" for n in (0, 1, 7, bits - 1, bits, 255)]
|
||||
for op in ("pslldq", "psrldq"):
|
||||
out += [f"{op} xmm9, {n}" for n in (0, 1, 5, 15, 16, 255)]
|
||||
for op in "pshufd pshufhw pshuflw shufps shufpd".split():
|
||||
out += [f"{op} xmm3, xmm9, {n}" for n in (0, 27, 78, 177, 255)]
|
||||
out += [f"{op} xmm10, {wide}, 114", f"{op} xmm2, xmm2, 57"]
|
||||
for n in (0, 3, 7):
|
||||
out += [f"pinsrw xmm9, ebx, {n}", f"pinsrw xmm3, {word}, {n}", f"pextrw r9d, xmm3, {n}"]
|
||||
out += [f"stmxcsr {dword}"]
|
||||
return list(dict.fromkeys(out))
|
||||
|
||||
|
||||
def float_cases():
|
||||
out = []
|
||||
memory = {"ss": "dword", "sd": "qword", "ps": "xmmword", "pd": "xmmword"}
|
||||
place = " ptr [rsi + 4*rdi + 16]"
|
||||
for kind, width in memory.items():
|
||||
for op in "add sub mul div min max sqrt".split():
|
||||
out += [f"{op}{kind} xmm3, xmm9", f"{op}{kind} xmm3, {width}{place}"]
|
||||
for code in range(8):
|
||||
out += [f"cmp{kind} xmm3, xmm9, {code}", f"cmp{kind} xmm3, {width}{place}, {code}"]
|
||||
for kind in ("ss", "sd"):
|
||||
for op in ("comi", "ucomi"):
|
||||
out += [f"{op}{kind} xmm3, xmm9", f"{op}{kind} xmm3, {memory[kind]}{place}"]
|
||||
for op in ("cvt", "cvtt"):
|
||||
for reg in ("r9d", "r9"):
|
||||
out += [f"{op}{kind}2si {reg}, xmm9", f"{op}{kind}2si {reg}, {memory[kind]}{place}"]
|
||||
for reg, width in (("r9d", "dword"), ("r9", "qword")):
|
||||
out += [f"cvtsi2{kind} xmm3, {reg}", f"cvtsi2{kind} xmm3, {width}{place}"]
|
||||
for op, width in (("cvtss2sd", "dword"), ("cvtsd2ss", "qword"), ("cvtps2pd", "qword"), ("cvtpd2ps", "xmmword"),
|
||||
("cvtdq2ps", "xmmword"), ("cvtdq2pd", "qword"), ("cvtps2dq", "xmmword"), ("cvttps2dq", "xmmword"),
|
||||
("cvtpd2dq", "xmmword"), ("cvttpd2dq", "xmmword")):
|
||||
out += [f"{op} xmm3, xmm9", f"{op} xmm3, {width}{place}"]
|
||||
return out
|
||||
|
||||
|
||||
def assemble(lines):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
source, obj = Path(directory, "a.s"), Path(directory, "a.o")
|
||||
source.write_text(".intel_syntax noprefix\n" + "\n".join(lines) + "\n")
|
||||
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)]
|
||||
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))
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) != 2 or argv[1] not in ("generate", "--check"):
|
||||
sys.exit("usage: assemble.py generate|--check")
|
||||
for name, lines in (("integer.txt", cases()), ("vector.txt", vector_cases()),
|
||||
("float.txt", float_cases())):
|
||||
text = assemble(lines)
|
||||
if argv[1] == "generate":
|
||||
(HERE / name).write_text(text)
|
||||
elif (HERE / name).read_text() != text:
|
||||
sys.exit(f"{name} differs from the assembler output")
|
||||
print(f"{name}: {len(lines)} instructions")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv)
|
||||
@@ -0,0 +1,172 @@
|
||||
f3 41 0f 58 d9 | addss xmm3, xmm9
|
||||
f3 0f 58 5c be 10 | addss xmm3, dword ptr [rsi + 4*rdi + 16]
|
||||
f3 41 0f 5c d9 | subss xmm3, xmm9
|
||||
f3 0f 5c 5c be 10 | subss xmm3, dword ptr [rsi + 4*rdi + 16]
|
||||
f3 41 0f 59 d9 | mulss xmm3, xmm9
|
||||
f3 0f 59 5c be 10 | mulss xmm3, dword ptr [rsi + 4*rdi + 16]
|
||||
f3 41 0f 5e d9 | divss xmm3, xmm9
|
||||
f3 0f 5e 5c be 10 | divss xmm3, dword ptr [rsi + 4*rdi + 16]
|
||||
f3 41 0f 5d d9 | minss xmm3, xmm9
|
||||
f3 0f 5d 5c be 10 | minss xmm3, dword ptr [rsi + 4*rdi + 16]
|
||||
f3 41 0f 5f d9 | maxss xmm3, xmm9
|
||||
f3 0f 5f 5c be 10 | maxss xmm3, dword ptr [rsi + 4*rdi + 16]
|
||||
f3 41 0f 51 d9 | sqrtss xmm3, xmm9
|
||||
f3 0f 51 5c be 10 | sqrtss xmm3, dword ptr [rsi + 4*rdi + 16]
|
||||
f3 41 0f c2 d9 00 | cmpss xmm3, xmm9, 0
|
||||
f3 0f c2 5c be 10 00 | cmpss xmm3, dword ptr [rsi + 4*rdi + 16], 0
|
||||
f3 41 0f c2 d9 01 | cmpss xmm3, xmm9, 1
|
||||
f3 0f c2 5c be 10 01 | cmpss xmm3, dword ptr [rsi + 4*rdi + 16], 1
|
||||
f3 41 0f c2 d9 02 | cmpss xmm3, xmm9, 2
|
||||
f3 0f c2 5c be 10 02 | cmpss xmm3, dword ptr [rsi + 4*rdi + 16], 2
|
||||
f3 41 0f c2 d9 03 | cmpss xmm3, xmm9, 3
|
||||
f3 0f c2 5c be 10 03 | cmpss xmm3, dword ptr [rsi + 4*rdi + 16], 3
|
||||
f3 41 0f c2 d9 04 | cmpss xmm3, xmm9, 4
|
||||
f3 0f c2 5c be 10 04 | cmpss xmm3, dword ptr [rsi + 4*rdi + 16], 4
|
||||
f3 41 0f c2 d9 05 | cmpss xmm3, xmm9, 5
|
||||
f3 0f c2 5c be 10 05 | cmpss xmm3, dword ptr [rsi + 4*rdi + 16], 5
|
||||
f3 41 0f c2 d9 06 | cmpss xmm3, xmm9, 6
|
||||
f3 0f c2 5c be 10 06 | cmpss xmm3, dword ptr [rsi + 4*rdi + 16], 6
|
||||
f3 41 0f c2 d9 07 | cmpss xmm3, xmm9, 7
|
||||
f3 0f c2 5c be 10 07 | cmpss xmm3, dword ptr [rsi + 4*rdi + 16], 7
|
||||
f2 41 0f 58 d9 | addsd xmm3, xmm9
|
||||
f2 0f 58 5c be 10 | addsd xmm3, qword ptr [rsi + 4*rdi + 16]
|
||||
f2 41 0f 5c d9 | subsd xmm3, xmm9
|
||||
f2 0f 5c 5c be 10 | subsd xmm3, qword ptr [rsi + 4*rdi + 16]
|
||||
f2 41 0f 59 d9 | mulsd xmm3, xmm9
|
||||
f2 0f 59 5c be 10 | mulsd xmm3, qword ptr [rsi + 4*rdi + 16]
|
||||
f2 41 0f 5e d9 | divsd xmm3, xmm9
|
||||
f2 0f 5e 5c be 10 | divsd xmm3, qword ptr [rsi + 4*rdi + 16]
|
||||
f2 41 0f 5d d9 | minsd xmm3, xmm9
|
||||
f2 0f 5d 5c be 10 | minsd xmm3, qword ptr [rsi + 4*rdi + 16]
|
||||
f2 41 0f 5f d9 | maxsd xmm3, xmm9
|
||||
f2 0f 5f 5c be 10 | maxsd xmm3, qword ptr [rsi + 4*rdi + 16]
|
||||
f2 41 0f 51 d9 | sqrtsd xmm3, xmm9
|
||||
f2 0f 51 5c be 10 | sqrtsd xmm3, qword ptr [rsi + 4*rdi + 16]
|
||||
f2 41 0f c2 d9 00 | cmpsd xmm3, xmm9, 0
|
||||
f2 0f c2 5c be 10 00 | cmpsd xmm3, qword ptr [rsi + 4*rdi + 16], 0
|
||||
f2 41 0f c2 d9 01 | cmpsd xmm3, xmm9, 1
|
||||
f2 0f c2 5c be 10 01 | cmpsd xmm3, qword ptr [rsi + 4*rdi + 16], 1
|
||||
f2 41 0f c2 d9 02 | cmpsd xmm3, xmm9, 2
|
||||
f2 0f c2 5c be 10 02 | cmpsd xmm3, qword ptr [rsi + 4*rdi + 16], 2
|
||||
f2 41 0f c2 d9 03 | cmpsd xmm3, xmm9, 3
|
||||
f2 0f c2 5c be 10 03 | cmpsd xmm3, qword ptr [rsi + 4*rdi + 16], 3
|
||||
f2 41 0f c2 d9 04 | cmpsd xmm3, xmm9, 4
|
||||
f2 0f c2 5c be 10 04 | cmpsd xmm3, qword ptr [rsi + 4*rdi + 16], 4
|
||||
f2 41 0f c2 d9 05 | cmpsd xmm3, xmm9, 5
|
||||
f2 0f c2 5c be 10 05 | cmpsd xmm3, qword ptr [rsi + 4*rdi + 16], 5
|
||||
f2 41 0f c2 d9 06 | cmpsd xmm3, xmm9, 6
|
||||
f2 0f c2 5c be 10 06 | cmpsd xmm3, qword ptr [rsi + 4*rdi + 16], 6
|
||||
f2 41 0f c2 d9 07 | cmpsd xmm3, xmm9, 7
|
||||
f2 0f c2 5c be 10 07 | cmpsd xmm3, qword ptr [rsi + 4*rdi + 16], 7
|
||||
41 0f 58 d9 | addps xmm3, xmm9
|
||||
0f 58 5c be 10 | addps xmm3, xmmword ptr [rsi + 4*rdi + 16]
|
||||
41 0f 5c d9 | subps xmm3, xmm9
|
||||
0f 5c 5c be 10 | subps xmm3, xmmword ptr [rsi + 4*rdi + 16]
|
||||
41 0f 59 d9 | mulps xmm3, xmm9
|
||||
0f 59 5c be 10 | mulps xmm3, xmmword ptr [rsi + 4*rdi + 16]
|
||||
41 0f 5e d9 | divps xmm3, xmm9
|
||||
0f 5e 5c be 10 | divps xmm3, xmmword ptr [rsi + 4*rdi + 16]
|
||||
41 0f 5d d9 | minps xmm3, xmm9
|
||||
0f 5d 5c be 10 | minps xmm3, xmmword ptr [rsi + 4*rdi + 16]
|
||||
41 0f 5f d9 | maxps xmm3, xmm9
|
||||
0f 5f 5c be 10 | maxps xmm3, xmmword ptr [rsi + 4*rdi + 16]
|
||||
41 0f 51 d9 | sqrtps xmm3, xmm9
|
||||
0f 51 5c be 10 | sqrtps xmm3, xmmword ptr [rsi + 4*rdi + 16]
|
||||
41 0f c2 d9 00 | cmpps xmm3, xmm9, 0
|
||||
0f c2 5c be 10 00 | cmpps xmm3, xmmword ptr [rsi + 4*rdi + 16], 0
|
||||
41 0f c2 d9 01 | cmpps xmm3, xmm9, 1
|
||||
0f c2 5c be 10 01 | cmpps xmm3, xmmword ptr [rsi + 4*rdi + 16], 1
|
||||
41 0f c2 d9 02 | cmpps xmm3, xmm9, 2
|
||||
0f c2 5c be 10 02 | cmpps xmm3, xmmword ptr [rsi + 4*rdi + 16], 2
|
||||
41 0f c2 d9 03 | cmpps xmm3, xmm9, 3
|
||||
0f c2 5c be 10 03 | cmpps xmm3, xmmword ptr [rsi + 4*rdi + 16], 3
|
||||
41 0f c2 d9 04 | cmpps xmm3, xmm9, 4
|
||||
0f c2 5c be 10 04 | cmpps xmm3, xmmword ptr [rsi + 4*rdi + 16], 4
|
||||
41 0f c2 d9 05 | cmpps xmm3, xmm9, 5
|
||||
0f c2 5c be 10 05 | cmpps xmm3, xmmword ptr [rsi + 4*rdi + 16], 5
|
||||
41 0f c2 d9 06 | cmpps xmm3, xmm9, 6
|
||||
0f c2 5c be 10 06 | cmpps xmm3, xmmword ptr [rsi + 4*rdi + 16], 6
|
||||
41 0f c2 d9 07 | cmpps xmm3, xmm9, 7
|
||||
0f c2 5c be 10 07 | cmpps xmm3, xmmword ptr [rsi + 4*rdi + 16], 7
|
||||
66 41 0f 58 d9 | addpd xmm3, xmm9
|
||||
66 0f 58 5c be 10 | addpd xmm3, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 41 0f 5c d9 | subpd xmm3, xmm9
|
||||
66 0f 5c 5c be 10 | subpd xmm3, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 41 0f 59 d9 | mulpd xmm3, xmm9
|
||||
66 0f 59 5c be 10 | mulpd xmm3, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 41 0f 5e d9 | divpd xmm3, xmm9
|
||||
66 0f 5e 5c be 10 | divpd xmm3, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 41 0f 5d d9 | minpd xmm3, xmm9
|
||||
66 0f 5d 5c be 10 | minpd xmm3, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 41 0f 5f d9 | maxpd xmm3, xmm9
|
||||
66 0f 5f 5c be 10 | maxpd xmm3, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 41 0f 51 d9 | sqrtpd xmm3, xmm9
|
||||
66 0f 51 5c be 10 | sqrtpd xmm3, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 41 0f c2 d9 00 | cmppd xmm3, xmm9, 0
|
||||
66 0f c2 5c be 10 00 | cmppd xmm3, xmmword ptr [rsi + 4*rdi + 16], 0
|
||||
66 41 0f c2 d9 01 | cmppd xmm3, xmm9, 1
|
||||
66 0f c2 5c be 10 01 | cmppd xmm3, xmmword ptr [rsi + 4*rdi + 16], 1
|
||||
66 41 0f c2 d9 02 | cmppd xmm3, xmm9, 2
|
||||
66 0f c2 5c be 10 02 | cmppd xmm3, xmmword ptr [rsi + 4*rdi + 16], 2
|
||||
66 41 0f c2 d9 03 | cmppd xmm3, xmm9, 3
|
||||
66 0f c2 5c be 10 03 | cmppd xmm3, xmmword ptr [rsi + 4*rdi + 16], 3
|
||||
66 41 0f c2 d9 04 | cmppd xmm3, xmm9, 4
|
||||
66 0f c2 5c be 10 04 | cmppd xmm3, xmmword ptr [rsi + 4*rdi + 16], 4
|
||||
66 41 0f c2 d9 05 | cmppd xmm3, xmm9, 5
|
||||
66 0f c2 5c be 10 05 | cmppd xmm3, xmmword ptr [rsi + 4*rdi + 16], 5
|
||||
66 41 0f c2 d9 06 | cmppd xmm3, xmm9, 6
|
||||
66 0f c2 5c be 10 06 | cmppd xmm3, xmmword ptr [rsi + 4*rdi + 16], 6
|
||||
66 41 0f c2 d9 07 | cmppd xmm3, xmm9, 7
|
||||
66 0f c2 5c be 10 07 | cmppd xmm3, xmmword ptr [rsi + 4*rdi + 16], 7
|
||||
41 0f 2f d9 | comiss xmm3, xmm9
|
||||
0f 2f 5c be 10 | comiss xmm3, dword ptr [rsi + 4*rdi + 16]
|
||||
41 0f 2e d9 | ucomiss xmm3, xmm9
|
||||
0f 2e 5c be 10 | ucomiss xmm3, dword ptr [rsi + 4*rdi + 16]
|
||||
f3 45 0f 2d c9 | cvtss2si r9d, xmm9
|
||||
f3 44 0f 2d 4c be 10 | cvtss2si r9d, dword ptr [rsi + 4*rdi + 16]
|
||||
f3 4d 0f 2d c9 | cvtss2si r9, xmm9
|
||||
f3 4c 0f 2d 4c be 10 | cvtss2si r9, dword ptr [rsi + 4*rdi + 16]
|
||||
f3 45 0f 2c c9 | cvttss2si r9d, xmm9
|
||||
f3 44 0f 2c 4c be 10 | cvttss2si r9d, dword ptr [rsi + 4*rdi + 16]
|
||||
f3 4d 0f 2c c9 | cvttss2si r9, xmm9
|
||||
f3 4c 0f 2c 4c be 10 | cvttss2si r9, dword ptr [rsi + 4*rdi + 16]
|
||||
f3 41 0f 2a d9 | cvtsi2ss xmm3, r9d
|
||||
f3 0f 2a 5c be 10 | cvtsi2ss xmm3, dword ptr [rsi + 4*rdi + 16]
|
||||
f3 49 0f 2a d9 | cvtsi2ss xmm3, r9
|
||||
f3 48 0f 2a 5c be 10 | cvtsi2ss xmm3, qword ptr [rsi + 4*rdi + 16]
|
||||
66 41 0f 2f d9 | comisd xmm3, xmm9
|
||||
66 0f 2f 5c be 10 | comisd xmm3, qword ptr [rsi + 4*rdi + 16]
|
||||
66 41 0f 2e d9 | ucomisd xmm3, xmm9
|
||||
66 0f 2e 5c be 10 | ucomisd xmm3, qword ptr [rsi + 4*rdi + 16]
|
||||
f2 45 0f 2d c9 | cvtsd2si r9d, xmm9
|
||||
f2 44 0f 2d 4c be 10 | cvtsd2si r9d, qword ptr [rsi + 4*rdi + 16]
|
||||
f2 4d 0f 2d c9 | cvtsd2si r9, xmm9
|
||||
f2 4c 0f 2d 4c be 10 | cvtsd2si r9, qword ptr [rsi + 4*rdi + 16]
|
||||
f2 45 0f 2c c9 | cvttsd2si r9d, xmm9
|
||||
f2 44 0f 2c 4c be 10 | cvttsd2si r9d, qword ptr [rsi + 4*rdi + 16]
|
||||
f2 4d 0f 2c c9 | cvttsd2si r9, xmm9
|
||||
f2 4c 0f 2c 4c be 10 | cvttsd2si r9, qword ptr [rsi + 4*rdi + 16]
|
||||
f2 41 0f 2a d9 | cvtsi2sd xmm3, r9d
|
||||
f2 0f 2a 5c be 10 | cvtsi2sd xmm3, dword ptr [rsi + 4*rdi + 16]
|
||||
f2 49 0f 2a d9 | cvtsi2sd xmm3, r9
|
||||
f2 48 0f 2a 5c be 10 | cvtsi2sd xmm3, qword ptr [rsi + 4*rdi + 16]
|
||||
f3 41 0f 5a d9 | cvtss2sd xmm3, xmm9
|
||||
f3 0f 5a 5c be 10 | cvtss2sd xmm3, dword ptr [rsi + 4*rdi + 16]
|
||||
f2 41 0f 5a d9 | cvtsd2ss xmm3, xmm9
|
||||
f2 0f 5a 5c be 10 | cvtsd2ss xmm3, qword ptr [rsi + 4*rdi + 16]
|
||||
41 0f 5a d9 | cvtps2pd xmm3, xmm9
|
||||
0f 5a 5c be 10 | cvtps2pd xmm3, qword ptr [rsi + 4*rdi + 16]
|
||||
66 41 0f 5a d9 | cvtpd2ps xmm3, xmm9
|
||||
66 0f 5a 5c be 10 | cvtpd2ps xmm3, xmmword ptr [rsi + 4*rdi + 16]
|
||||
41 0f 5b d9 | cvtdq2ps xmm3, xmm9
|
||||
0f 5b 5c be 10 | cvtdq2ps xmm3, xmmword ptr [rsi + 4*rdi + 16]
|
||||
f3 41 0f e6 d9 | cvtdq2pd xmm3, xmm9
|
||||
f3 0f e6 5c be 10 | cvtdq2pd xmm3, qword ptr [rsi + 4*rdi + 16]
|
||||
66 41 0f 5b d9 | cvtps2dq xmm3, xmm9
|
||||
66 0f 5b 5c be 10 | cvtps2dq xmm3, xmmword ptr [rsi + 4*rdi + 16]
|
||||
f3 41 0f 5b d9 | cvttps2dq xmm3, xmm9
|
||||
f3 0f 5b 5c be 10 | cvttps2dq xmm3, xmmword ptr [rsi + 4*rdi + 16]
|
||||
f2 41 0f e6 d9 | cvtpd2dq xmm3, xmm9
|
||||
f2 0f e6 5c be 10 | cvtpd2dq xmm3, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 41 0f e6 d9 | cvttpd2dq xmm3, xmm9
|
||||
66 0f e6 5c be 10 | cvttpd2dq xmm3, xmmword ptr [rsi + 4*rdi + 16]
|
||||
@@ -0,0 +1,441 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Reference vectors for SSE and SSE2 floating point, from exact fractions.
|
||||
|
||||
generate write float_vectors.txt next to this file
|
||||
--check recompute in memory and fail if the committed file differs
|
||||
|
||||
Every finite result is computed as an exact `fractions.Fraction` (square roots by
|
||||
integer comparison) and then rounded by definition, so nothing here shares code
|
||||
or method with crates/loader/src/softfloat.rs, and no host floating point is
|
||||
used. Rules: Intel SDM Vol. 1, 4.8, 4.9 and 11.5, and the Vol. 2 operation
|
||||
sections. Cases whose flags those sections leave open are not generated:
|
||||
a denormal dividend over zero, flushing an exact denormal result, and the
|
||||
precision flag of a denormal converted to an integer under DAZ.
|
||||
|
||||
Line: <operation> <mxcsr> <a> <b> <result> <mxcsr flags>, all values hex.
|
||||
"""
|
||||
|
||||
import random
|
||||
import sys
|
||||
from fractions import Fraction
|
||||
from math import isqrt
|
||||
from pathlib import Path
|
||||
|
||||
OUT = Path(__file__).resolve().parent / "float_vectors.txt"
|
||||
IE, DE, ZE, OE, UE, PE = 1, 2, 4, 8, 16, 32
|
||||
NEAREST, DOWN, UP, ZERO = range(4)
|
||||
|
||||
|
||||
class Fmt:
|
||||
def __init__(self, bits, frac):
|
||||
self.bits, self.frac = bits, frac
|
||||
self.ebits = bits - 1 - frac
|
||||
self.emax = 2 ** (self.ebits - 1) - 1
|
||||
self.emin = 1 - self.emax
|
||||
self.inf = (2 ** self.ebits - 1) << frac
|
||||
self.quiet = 1 << (frac - 1)
|
||||
self.top = 1 << (bits - 1)
|
||||
|
||||
def mag(self, v):
|
||||
return v % self.top
|
||||
|
||||
def neg(self, v):
|
||||
return v >= self.top
|
||||
|
||||
def nan(self, v):
|
||||
return self.mag(v) > self.inf
|
||||
|
||||
def snan(self, v):
|
||||
return self.nan(v) and not v & self.quiet
|
||||
|
||||
def isinf(self, v):
|
||||
return self.mag(v) == self.inf
|
||||
|
||||
def denormal(self, v):
|
||||
return 0 < self.mag(v) < (1 << self.frac)
|
||||
|
||||
def value(self, v):
|
||||
m = self.mag(v)
|
||||
field, fraction = m >> self.frac, m % (1 << self.frac)
|
||||
if field == 0:
|
||||
x = Fraction(fraction) * Fraction(2) ** (self.emin - self.frac)
|
||||
else:
|
||||
x = (1 + Fraction(fraction, 1 << self.frac)) * Fraction(2) ** (field - self.emax)
|
||||
return -x if self.neg(v) else x
|
||||
|
||||
def encode(self, sign, x):
|
||||
"""Bits of an exactly representable non-negative x."""
|
||||
if x == 0:
|
||||
m = 0
|
||||
elif x < Fraction(2) ** self.emin:
|
||||
m = int(x / Fraction(2) ** (self.emin - self.frac))
|
||||
else:
|
||||
e = exponent(x)
|
||||
m = ((e + self.emax) << self.frac) + int((x / Fraction(2) ** e - 1) * (1 << self.frac))
|
||||
return m + (self.top if sign else 0)
|
||||
|
||||
|
||||
S, D = Fmt(32, 23), Fmt(64, 52)
|
||||
|
||||
|
||||
def exponent(x):
|
||||
"""floor(log2 x) for x > 0."""
|
||||
e = x.numerator.bit_length() - x.denominator.bit_length()
|
||||
return e if Fraction(2) ** e <= x else e - 1
|
||||
|
||||
|
||||
def pick(below, above, position, sign, mode, even):
|
||||
"""Choose between neighbours; position is -1, 0 or 1 against the midpoint,
|
||||
or None when exactly `below`."""
|
||||
if position is None:
|
||||
return below
|
||||
if mode == NEAREST:
|
||||
if position == 0:
|
||||
return below if even else above
|
||||
return above if position > 0 else below
|
||||
if mode == ZERO:
|
||||
return below
|
||||
return above if (mode == UP) != sign else below
|
||||
|
||||
|
||||
def quantize(n, rest_sign, quantum, sign, mode):
|
||||
"""n quanta below the value; rest_sign as in pick."""
|
||||
return pick(n * quantum, (n + 1) * quantum, rest_sign, sign, mode, n % 2 == 0)
|
||||
|
||||
|
||||
def locate(x, quantum):
|
||||
"""Quanta below the positive fraction x, and its side of the midpoint."""
|
||||
q = x / quantum
|
||||
n = q.numerator // q.denominator
|
||||
rest = q - n
|
||||
if rest == 0:
|
||||
return n, None
|
||||
half = Fraction(1, 2)
|
||||
return n, (rest > half) - (rest < half)
|
||||
|
||||
|
||||
def locate_root(x, quantum):
|
||||
"""As locate, for the square root of x."""
|
||||
q = x / (quantum * quantum)
|
||||
n = isqrt(q.numerator // q.denominator)
|
||||
if n * n == q:
|
||||
return n, None
|
||||
middle = (Fraction(n) + Fraction(1, 2)) ** 2
|
||||
return n, (q > middle) - (q < middle)
|
||||
|
||||
|
||||
def finish(fmt, sign, e, locator, control):
|
||||
"""Round a positive exact value with floor(log2) = e, given its locator."""
|
||||
mode, ftz, flags = control["mode"], control["ftz"], 0
|
||||
n, side = locator(Fraction(2) ** (e - fmt.frac))
|
||||
unbounded = quantize(n, side, Fraction(2) ** (e - fmt.frac), sign, mode)
|
||||
tiny = unbounded < Fraction(2) ** fmt.emin
|
||||
quantum = Fraction(2) ** (max(e, fmt.emin) - fmt.frac)
|
||||
n, side = locator(quantum)
|
||||
result = quantize(n, side, quantum, sign, mode)
|
||||
if tiny and ftz:
|
||||
if side is None:
|
||||
return None # flushing an exact denormal is left open
|
||||
return fmt.encode(sign, Fraction(0)), UE | PE
|
||||
if side is not None:
|
||||
flags |= PE | (UE if tiny else 0)
|
||||
if result >= Fraction(2) ** (fmt.emax + 1):
|
||||
infinite = mode == NEAREST or (mode == UP and not sign) or (mode == DOWN and sign)
|
||||
return (fmt.inf if infinite else fmt.inf - 1) + (fmt.top if sign else 0), OE | PE
|
||||
return fmt.encode(sign, result), flags
|
||||
|
||||
|
||||
def rounded(fmt, x, control):
|
||||
sign = x < 0
|
||||
x = abs(x)
|
||||
return finish(fmt, sign, exponent(x), lambda q: locate(x, q), control)
|
||||
|
||||
|
||||
def default(fmt):
|
||||
return fmt.top + fmt.inf + fmt.quiet
|
||||
|
||||
|
||||
def prepare(fmt, v, control):
|
||||
if control["daz"] and fmt.denormal(v):
|
||||
return fmt.top if fmt.neg(v) else 0
|
||||
return v
|
||||
|
||||
|
||||
def binary(op, fmt, a, b, control):
|
||||
a, b = prepare(fmt, a, control), prepare(fmt, b, control)
|
||||
de = DE if fmt.denormal(a) or fmt.denormal(b) else 0
|
||||
if op in ("min", "max"):
|
||||
if fmt.nan(a) or fmt.nan(b):
|
||||
return b, IE
|
||||
order = compare(fmt, a, b)
|
||||
return (a if order == (-1 if op == "min" else 1) else b), de
|
||||
if fmt.nan(a) or fmt.nan(b):
|
||||
chosen = a if fmt.nan(a) else b
|
||||
return chosen | fmt.quiet, IE if fmt.snan(a) or fmt.snan(b) else 0
|
||||
if op == "sub":
|
||||
b ^= fmt.top
|
||||
sa, sb = fmt.neg(a), fmt.neg(b)
|
||||
sign = sa != sb
|
||||
signed = lambda m: m + (fmt.top if sign else 0)
|
||||
if op in ("add", "sub"):
|
||||
if fmt.isinf(a) and fmt.isinf(b) and sign:
|
||||
return default(fmt), IE
|
||||
if fmt.isinf(a):
|
||||
return a, de
|
||||
if fmt.isinf(b):
|
||||
return b, de
|
||||
x = fmt.value(a) + fmt.value(b)
|
||||
if x == 0:
|
||||
both = fmt.mag(a) == 0 and not sign
|
||||
return (fmt.top if (sa if both else control["mode"] == DOWN) else 0), de
|
||||
elif op == "mul":
|
||||
if fmt.isinf(a) or fmt.isinf(b):
|
||||
if fmt.mag(a) == 0 or fmt.mag(b) == 0:
|
||||
return default(fmt), IE
|
||||
return signed(fmt.inf), de
|
||||
x = fmt.value(a) * fmt.value(b)
|
||||
if x == 0:
|
||||
return signed(0), de
|
||||
else:
|
||||
if (fmt.isinf(a) and fmt.isinf(b)) or (fmt.mag(a) == 0 and fmt.mag(b) == 0):
|
||||
return default(fmt), IE
|
||||
if fmt.isinf(a):
|
||||
return signed(fmt.inf), de
|
||||
if fmt.isinf(b):
|
||||
return signed(0), de
|
||||
if fmt.mag(b) == 0:
|
||||
return None if de else (signed(fmt.inf), ZE)
|
||||
x = fmt.value(a) / fmt.value(b)
|
||||
if x == 0:
|
||||
return signed(0), de
|
||||
out = rounded(fmt, x, control)
|
||||
return out and (out[0], out[1] | de)
|
||||
|
||||
|
||||
def root(fmt, v, control):
|
||||
v = prepare(fmt, v, control)
|
||||
if fmt.nan(v):
|
||||
return v | fmt.quiet, IE if fmt.snan(v) else 0
|
||||
if fmt.mag(v) == 0:
|
||||
return v, 0
|
||||
if fmt.neg(v):
|
||||
return default(fmt), IE
|
||||
if fmt.isinf(v):
|
||||
return v, 0
|
||||
x = fmt.value(v)
|
||||
bits, flags = finish(fmt, False, exponent(x) // 2, lambda q: locate_root(x, q), control)
|
||||
return bits, flags | (DE if fmt.denormal(v) else 0)
|
||||
|
||||
|
||||
def compare(fmt, a, b):
|
||||
def key(v):
|
||||
if fmt.isinf(v):
|
||||
return Fraction(2) ** (fmt.emax + 2) * (-1 if fmt.neg(v) else 1)
|
||||
return fmt.value(v)
|
||||
return (key(a) > key(b)) - (key(a) < key(b))
|
||||
|
||||
|
||||
def ordering(fmt, a, b, signaling, control):
|
||||
"""(-1, 0, 1 or None for unordered), flags."""
|
||||
a, b = prepare(fmt, a, control), prepare(fmt, b, control)
|
||||
if fmt.nan(a) or fmt.nan(b):
|
||||
return None, IE if signaling or fmt.snan(a) or fmt.snan(b) else 0
|
||||
return compare(fmt, a, b), DE if fmt.denormal(a) or fmt.denormal(b) else 0
|
||||
|
||||
|
||||
def predicate(code, fmt, a, b, control):
|
||||
order, flags = ordering(fmt, a, b, code in (1, 2, 5, 6), control)
|
||||
truth = [order == 0, order == -1, order in (-1, 0), order is None,
|
||||
order != 0, order != -1, order not in (-1, 0), order is not None][code]
|
||||
return (2 ** fmt.bits - 1 if truth else 0), flags
|
||||
|
||||
|
||||
def comparison(fmt, a, b, signaling, control):
|
||||
"""RFLAGS as ZF=4, PF=2, CF=1."""
|
||||
order, flags = ordering(fmt, a, b, signaling, control)
|
||||
return {None: 7, 1: 0, -1: 1, 0: 4}[order], flags
|
||||
|
||||
|
||||
def widen(src, dst, v, control):
|
||||
v = prepare(src, v, control)
|
||||
sign = dst.top if src.neg(v) else 0
|
||||
if src.nan(v):
|
||||
payload = Fraction(src.mag(v) - src.inf) * Fraction(2) ** (dst.frac - src.frac)
|
||||
return sign + dst.inf + (int(payload) | dst.quiet), IE if src.snan(v) else 0
|
||||
if src.isinf(v):
|
||||
return sign + dst.inf, 0
|
||||
x = src.value(v)
|
||||
if x == 0:
|
||||
return sign, 0
|
||||
out = rounded(dst, x, control)
|
||||
return out and (out[0], out[1] | (DE if src.denormal(v) else 0))
|
||||
|
||||
|
||||
def to_int(fmt, v, bits, truncate, control):
|
||||
if control["daz"] and fmt.denormal(v):
|
||||
return None
|
||||
indefinite = 2 ** (bits - 1), IE
|
||||
if fmt.nan(v) or fmt.isinf(v):
|
||||
return indefinite
|
||||
x = fmt.value(v)
|
||||
n, side = locate(abs(x), Fraction(1))
|
||||
r = int(quantize(n, side, Fraction(1), x < 0, ZERO if truncate else control["mode"]))
|
||||
r = -r if x < 0 else r
|
||||
if not -(2 ** (bits - 1)) <= r < 2 ** (bits - 1):
|
||||
return indefinite
|
||||
return r % 2 ** bits, 0 if side is None else PE
|
||||
|
||||
|
||||
def from_int(fmt, v, bits, control):
|
||||
x = v - 2 ** bits if v >= 2 ** (bits - 1) else v
|
||||
return rounded(fmt, Fraction(x), control) if x else (0, 0)
|
||||
|
||||
|
||||
def operands(fmt, rng):
|
||||
one = fmt.emax << fmt.frac
|
||||
least = 1 << fmt.frac
|
||||
edge = [0, 1, 2, least - 1, least, least + 1, 2 * least, one - 1, one, one + 1, one + least,
|
||||
one + fmt.quiet, one + (fmt.frac << fmt.frac), one + (fmt.frac << fmt.frac) + 1,
|
||||
fmt.inf - 1, fmt.inf - least, fmt.inf, fmt.inf + fmt.quiet, fmt.inf + fmt.quiet + 5,
|
||||
fmt.inf + 1, fmt.inf + fmt.quiet - 1]
|
||||
choice = rng.randrange(6)
|
||||
if choice < 2:
|
||||
v = rng.choice(edge)
|
||||
elif choice == 2:
|
||||
v = rng.randrange(least) # denormal
|
||||
elif choice == 3: # near one, few significant bits
|
||||
v = one + (rng.randrange(-40, 41) << fmt.frac) + (rng.randrange(16) << (fmt.frac - 4))
|
||||
elif choice == 4: # near the smallest and largest normals
|
||||
v = rng.choice([least * rng.randrange(1, fmt.frac + 4), fmt.inf - least * rng.randrange(1, 4)]) + rng.randrange(least)
|
||||
else:
|
||||
v = rng.randrange(fmt.top)
|
||||
v = min(v, fmt.top - 1)
|
||||
return v + (fmt.top if rng.random() < 0.5 else 0)
|
||||
|
||||
|
||||
def related(fmt, a, rng):
|
||||
"""A second operand, often within a few exponents of the first."""
|
||||
if rng.random() < 0.5 or fmt.mag(a) >= fmt.inf:
|
||||
return operands(fmt, rng)
|
||||
m = fmt.mag(a) + (rng.randrange(-fmt.frac - 3, fmt.frac + 4) << fmt.frac) + rng.randrange(-3, 4)
|
||||
return max(0, min(m, fmt.inf)) + (fmt.top if rng.random() < 0.5 else 0)
|
||||
|
||||
|
||||
def integers(bits, rng):
|
||||
c = rng.randrange(4)
|
||||
if c == 0:
|
||||
return rng.choice([0, 1, 2 ** (bits - 1), 2 ** (bits - 1) - 1, 2 ** bits - 1])
|
||||
if c == 1:
|
||||
return (2 ** rng.randrange(bits) + rng.randrange(-2, 3)) % 2 ** bits
|
||||
return rng.randrange(2 ** bits) >> rng.randrange(bits)
|
||||
|
||||
|
||||
def near_int(fmt, bits, rng):
|
||||
"""Values around halves, integers and the integer range limits."""
|
||||
if rng.random() < 0.3:
|
||||
return operands(fmt, rng)
|
||||
base = rng.choice([Fraction(rng.randrange(-9, 10), 2), Fraction(rng.randrange(-2 ** 24, 2 ** 24), 4),
|
||||
Fraction(2 ** (bits - 1)), Fraction(-(2 ** (bits - 1))), Fraction(rng.randrange(1, 2 ** 20)) * 2 ** rng.randrange(40)])
|
||||
v = fmt.top if base == 0 and rng.random() < 0.5 else 0
|
||||
if base:
|
||||
v = rounded(fmt, base, {"mode": NEAREST, "ftz": False})[0]
|
||||
m = max(0, fmt.mag(v) + rng.randrange(-2, 3))
|
||||
return m + (fmt.top if fmt.neg(v) else 0)
|
||||
|
||||
|
||||
def build():
|
||||
rng = random.Random(0x58454E4F5241)
|
||||
lines = []
|
||||
|
||||
def emit(name, make, compute, count):
|
||||
done = 0
|
||||
while done < count:
|
||||
mode = rng.randrange(4)
|
||||
control = {"mode": mode, "daz": rng.random() < 0.2, "ftz": rng.random() < 0.2}
|
||||
mxcsr = 0x1F80 | mode << 13 | control["daz"] << 6 | control["ftz"] << 15
|
||||
a, b = make()
|
||||
out = compute(a, b, control)
|
||||
if out is None:
|
||||
continue
|
||||
lines.append(f"{name} {mxcsr:x} {a:x} {b:x} {out[0]:x} {out[1]:x}\n")
|
||||
done += 1
|
||||
|
||||
def direct(name, mode, a, b, out):
|
||||
if out is not None:
|
||||
lines.append(f"{name} {0x1F80 | mode << 13:x} {a:x} {b:x} {out[0]:x} {out[1]:x}\n")
|
||||
|
||||
for fmt, s in ((S, "ss"), (D, "sd")):
|
||||
# Every pair of special operands, for every two-operand rule.
|
||||
one, least = fmt.emax << fmt.frac, 1 << fmt.frac
|
||||
special = [0, fmt.top, 1, one, fmt.top + one, fmt.inf - 1, fmt.inf, fmt.top + fmt.inf,
|
||||
fmt.inf + fmt.quiet + 5, fmt.top + fmt.inf + 3]
|
||||
for a in special:
|
||||
for b in special:
|
||||
for op in ("add", "sub", "mul", "div", "min", "max"):
|
||||
mode = rng.randrange(4)
|
||||
control = {"mode": mode, "daz": False, "ftz": False}
|
||||
direct(op + s, mode, a, b, binary(op, fmt, a, b, control))
|
||||
# Products within a rounding step of the smallest normal: (1 + t)(1 - t)
|
||||
# times 2^emin. Tininess is judged after rounding, so some are not tiny.
|
||||
root_of_least = fmt.emin // 2
|
||||
for shift in range(fmt.frac // 2 - 3, fmt.frac // 2 + 6):
|
||||
t = 1 << (fmt.frac - shift)
|
||||
a = ((root_of_least + fmt.emax) << fmt.frac) + t
|
||||
rest = fmt.emin - root_of_least
|
||||
# 1 - t is in the binade below one, with twice the resolution.
|
||||
b = ((rest - 1 + fmt.emax) << fmt.frac) + (least - 2 * t)
|
||||
for mode in range(4):
|
||||
for x, y in ((a, b), (a + fmt.top, b)):
|
||||
control = {"mode": mode, "daz": False, "ftz": False}
|
||||
direct("mul" + s, mode, x, y, binary("mul", fmt, x, y, control))
|
||||
# The same neighbourhood for narrowing: 2^-126 (1 - 2^-k).
|
||||
for k in range(22, 30):
|
||||
b = D.encode(False, Fraction(2) ** S.emin * (1 - Fraction(1, 2 ** k)))
|
||||
for mode in range(4):
|
||||
for x in (b, b + D.top):
|
||||
direct("cvtsd2ss", mode, 0, x, widen(D, S, x, {"mode": mode, "daz": False, "ftz": False}))
|
||||
|
||||
for fmt, s in ((S, "ss"), (D, "sd")):
|
||||
def pair(fmt=fmt):
|
||||
a = operands(fmt, rng)
|
||||
return a, related(fmt, a, rng)
|
||||
for op in ("add", "sub", "mul", "div", "min", "max"):
|
||||
emit(op + s, pair, lambda a, b, c, op=op, fmt=fmt: binary(op, fmt, a, b, c),
|
||||
260 if op in ("add", "sub", "mul", "div") else 100)
|
||||
emit("sqrt" + s, lambda fmt=fmt: (0, operands(fmt, rng)), lambda a, b, c, fmt=fmt: root(fmt, b, c), 200)
|
||||
for code in range(8):
|
||||
emit(f"cmp{s}{code}", pair, lambda a, b, c, code=code, fmt=fmt: predicate(code, fmt, a, b, c), 40)
|
||||
emit("comi" + s, pair, lambda a, b, c, fmt=fmt: comparison(fmt, a, b, True, c), 80)
|
||||
emit("ucomi" + s, pair, lambda a, b, c, fmt=fmt: comparison(fmt, a, b, False, c), 80)
|
||||
for bits, w in ((32, "d"), (64, "q")):
|
||||
for name, truncate in (("cvt", False), ("cvtt", True)):
|
||||
emit(f"{name}{s}2si{w}", lambda fmt=fmt, bits=bits: (0, near_int(fmt, bits, rng)),
|
||||
lambda a, b, c, fmt=fmt, bits=bits, t=truncate: to_int(fmt, b, bits, t, c), 110)
|
||||
emit(f"cvtsi2{s}{w}", lambda bits=bits: (0, integers(bits, rng)),
|
||||
lambda a, b, c, fmt=fmt, bits=bits: from_int(fmt, b, bits, c), 80)
|
||||
emit("cvtss2sd", lambda: (0, operands(S, rng)), lambda a, b, c: widen(S, D, b, c), 120)
|
||||
|
||||
def narrowing():
|
||||
if rng.random() < 0.4:
|
||||
return 0, operands(D, rng)
|
||||
# A binary32 neighbourhood, with bits beyond its precision.
|
||||
v = operands(S, rng)
|
||||
x = widen(S, D, v, {"mode": NEAREST, "daz": False, "ftz": False})[0]
|
||||
return 0, x ^ (rng.choice([0, 1, 1 << 28, (1 << 28) + 1, (1 << 29) - 1]) if D.mag(x) else 0)
|
||||
emit("cvtsd2ss", narrowing, lambda a, b, c: widen(D, S, b, c), 260)
|
||||
return "".join(lines)
|
||||
|
||||
|
||||
def main(argv):
|
||||
if len(argv) != 2 or argv[1] not in ("generate", "--check"):
|
||||
sys.exit("usage: float_reference.py generate|--check")
|
||||
text = build()
|
||||
if argv[1] == "generate":
|
||||
OUT.write_text(text)
|
||||
elif OUT.read_text() != text:
|
||||
sys.exit("float_vectors.txt is out of date")
|
||||
print(f"{text.count(chr(10))} vectors")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main(sys.argv)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,985 @@
|
||||
00 cb | add bl, cl
|
||||
45 00 e1 | add r9b, r12b
|
||||
00 c0 | add al, al
|
||||
00 54 be 10 | add byte ptr [rsi + 4*rdi + 16], dl
|
||||
44 02 54 be 10 | add r10b, byte ptr [rsi + 4*rdi + 16]
|
||||
04 7f | add al, 0x7f
|
||||
80 c3 7f | add bl, 0x7f
|
||||
80 44 be 10 7f | add byte ptr [rsi + 4*rdi + 16], 0x7f
|
||||
66 01 cb | add bx, cx
|
||||
66 45 01 e1 | add r9w, r12w
|
||||
66 01 c0 | add ax, ax
|
||||
66 01 54 be 10 | add word ptr [rsi + 4*rdi + 16], dx
|
||||
66 44 03 54 be 10 | add r10w, word ptr [rsi + 4*rdi + 16]
|
||||
66 05 34 12 | add ax, 0x1234
|
||||
66 81 c3 34 12 | add bx, 0x1234
|
||||
66 81 44 be 10 34 12 | add word ptr [rsi + 4*rdi + 16], 0x1234
|
||||
66 41 83 c3 fd | add r11w, -3
|
||||
66 83 44 be 10 fd | add word ptr [rsi + 4*rdi + 16], -3
|
||||
01 cb | add ebx, ecx
|
||||
45 01 e1 | add r9d, r12d
|
||||
01 c0 | add eax, eax
|
||||
01 54 be 10 | add dword ptr [rsi + 4*rdi + 16], edx
|
||||
44 03 54 be 10 | add r10d, dword ptr [rsi + 4*rdi + 16]
|
||||
05 78 56 34 12 | add eax, 0x12345678
|
||||
81 c3 78 56 34 12 | add ebx, 0x12345678
|
||||
81 44 be 10 78 56 34 12 | add dword ptr [rsi + 4*rdi + 16], 0x12345678
|
||||
41 83 c3 fd | add r11d, -3
|
||||
83 44 be 10 fd | add dword ptr [rsi + 4*rdi + 16], -3
|
||||
48 01 cb | add rbx, rcx
|
||||
4d 01 e1 | add r9, r12
|
||||
48 01 c0 | add rax, rax
|
||||
48 01 54 be 10 | add qword ptr [rsi + 4*rdi + 16], rdx
|
||||
4c 03 54 be 10 | add r10, qword ptr [rsi + 4*rdi + 16]
|
||||
48 05 78 56 34 12 | add rax, 0x12345678
|
||||
48 81 c3 78 56 34 12 | add rbx, 0x12345678
|
||||
48 81 44 be 10 78 56 34 12 | add qword ptr [rsi + 4*rdi + 16], 0x12345678
|
||||
49 83 c3 fd | add r11, -3
|
||||
48 83 44 be 10 fd | add qword ptr [rsi + 4*rdi + 16], -3
|
||||
00 dc | add ah, bl
|
||||
00 f1 | add cl, dh
|
||||
80 c7 55 | add bh, 0x55
|
||||
08 cb | or bl, cl
|
||||
45 08 e1 | or r9b, r12b
|
||||
08 c0 | or al, al
|
||||
08 54 be 10 | or byte ptr [rsi + 4*rdi + 16], dl
|
||||
44 0a 54 be 10 | or r10b, byte ptr [rsi + 4*rdi + 16]
|
||||
0c 7f | or al, 0x7f
|
||||
80 cb 7f | or bl, 0x7f
|
||||
80 4c be 10 7f | or byte ptr [rsi + 4*rdi + 16], 0x7f
|
||||
66 09 cb | or bx, cx
|
||||
66 45 09 e1 | or r9w, r12w
|
||||
66 09 c0 | or ax, ax
|
||||
66 09 54 be 10 | or word ptr [rsi + 4*rdi + 16], dx
|
||||
66 44 0b 54 be 10 | or r10w, word ptr [rsi + 4*rdi + 16]
|
||||
66 0d 34 12 | or ax, 0x1234
|
||||
66 81 cb 34 12 | or bx, 0x1234
|
||||
66 81 4c be 10 34 12 | or word ptr [rsi + 4*rdi + 16], 0x1234
|
||||
66 41 83 cb fd | or r11w, -3
|
||||
66 83 4c be 10 fd | or word ptr [rsi + 4*rdi + 16], -3
|
||||
09 cb | or ebx, ecx
|
||||
45 09 e1 | or r9d, r12d
|
||||
09 c0 | or eax, eax
|
||||
09 54 be 10 | or dword ptr [rsi + 4*rdi + 16], edx
|
||||
44 0b 54 be 10 | or r10d, dword ptr [rsi + 4*rdi + 16]
|
||||
0d 78 56 34 12 | or eax, 0x12345678
|
||||
81 cb 78 56 34 12 | or ebx, 0x12345678
|
||||
81 4c be 10 78 56 34 12 | or dword ptr [rsi + 4*rdi + 16], 0x12345678
|
||||
41 83 cb fd | or r11d, -3
|
||||
83 4c be 10 fd | or dword ptr [rsi + 4*rdi + 16], -3
|
||||
48 09 cb | or rbx, rcx
|
||||
4d 09 e1 | or r9, r12
|
||||
48 09 c0 | or rax, rax
|
||||
48 09 54 be 10 | or qword ptr [rsi + 4*rdi + 16], rdx
|
||||
4c 0b 54 be 10 | or r10, qword ptr [rsi + 4*rdi + 16]
|
||||
48 0d 78 56 34 12 | or rax, 0x12345678
|
||||
48 81 cb 78 56 34 12 | or rbx, 0x12345678
|
||||
48 81 4c be 10 78 56 34 12 | or qword ptr [rsi + 4*rdi + 16], 0x12345678
|
||||
49 83 cb fd | or r11, -3
|
||||
48 83 4c be 10 fd | or qword ptr [rsi + 4*rdi + 16], -3
|
||||
08 dc | or ah, bl
|
||||
08 f1 | or cl, dh
|
||||
80 cf 55 | or bh, 0x55
|
||||
10 cb | adc bl, cl
|
||||
45 10 e1 | adc r9b, r12b
|
||||
10 c0 | adc al, al
|
||||
10 54 be 10 | adc byte ptr [rsi + 4*rdi + 16], dl
|
||||
44 12 54 be 10 | adc r10b, byte ptr [rsi + 4*rdi + 16]
|
||||
14 7f | adc al, 0x7f
|
||||
80 d3 7f | adc bl, 0x7f
|
||||
80 54 be 10 7f | adc byte ptr [rsi + 4*rdi + 16], 0x7f
|
||||
66 11 cb | adc bx, cx
|
||||
66 45 11 e1 | adc r9w, r12w
|
||||
66 11 c0 | adc ax, ax
|
||||
66 11 54 be 10 | adc word ptr [rsi + 4*rdi + 16], dx
|
||||
66 44 13 54 be 10 | adc r10w, word ptr [rsi + 4*rdi + 16]
|
||||
66 15 34 12 | adc ax, 0x1234
|
||||
66 81 d3 34 12 | adc bx, 0x1234
|
||||
66 81 54 be 10 34 12 | adc word ptr [rsi + 4*rdi + 16], 0x1234
|
||||
66 41 83 d3 fd | adc r11w, -3
|
||||
66 83 54 be 10 fd | adc word ptr [rsi + 4*rdi + 16], -3
|
||||
11 cb | adc ebx, ecx
|
||||
45 11 e1 | adc r9d, r12d
|
||||
11 c0 | adc eax, eax
|
||||
11 54 be 10 | adc dword ptr [rsi + 4*rdi + 16], edx
|
||||
44 13 54 be 10 | adc r10d, dword ptr [rsi + 4*rdi + 16]
|
||||
15 78 56 34 12 | adc eax, 0x12345678
|
||||
81 d3 78 56 34 12 | adc ebx, 0x12345678
|
||||
81 54 be 10 78 56 34 12 | adc dword ptr [rsi + 4*rdi + 16], 0x12345678
|
||||
41 83 d3 fd | adc r11d, -3
|
||||
83 54 be 10 fd | adc dword ptr [rsi + 4*rdi + 16], -3
|
||||
48 11 cb | adc rbx, rcx
|
||||
4d 11 e1 | adc r9, r12
|
||||
48 11 c0 | adc rax, rax
|
||||
48 11 54 be 10 | adc qword ptr [rsi + 4*rdi + 16], rdx
|
||||
4c 13 54 be 10 | adc r10, qword ptr [rsi + 4*rdi + 16]
|
||||
48 15 78 56 34 12 | adc rax, 0x12345678
|
||||
48 81 d3 78 56 34 12 | adc rbx, 0x12345678
|
||||
48 81 54 be 10 78 56 34 12 | adc qword ptr [rsi + 4*rdi + 16], 0x12345678
|
||||
49 83 d3 fd | adc r11, -3
|
||||
48 83 54 be 10 fd | adc qword ptr [rsi + 4*rdi + 16], -3
|
||||
10 dc | adc ah, bl
|
||||
10 f1 | adc cl, dh
|
||||
80 d7 55 | adc bh, 0x55
|
||||
18 cb | sbb bl, cl
|
||||
45 18 e1 | sbb r9b, r12b
|
||||
18 c0 | sbb al, al
|
||||
18 54 be 10 | sbb byte ptr [rsi + 4*rdi + 16], dl
|
||||
44 1a 54 be 10 | sbb r10b, byte ptr [rsi + 4*rdi + 16]
|
||||
1c 7f | sbb al, 0x7f
|
||||
80 db 7f | sbb bl, 0x7f
|
||||
80 5c be 10 7f | sbb byte ptr [rsi + 4*rdi + 16], 0x7f
|
||||
66 19 cb | sbb bx, cx
|
||||
66 45 19 e1 | sbb r9w, r12w
|
||||
66 19 c0 | sbb ax, ax
|
||||
66 19 54 be 10 | sbb word ptr [rsi + 4*rdi + 16], dx
|
||||
66 44 1b 54 be 10 | sbb r10w, word ptr [rsi + 4*rdi + 16]
|
||||
66 1d 34 12 | sbb ax, 0x1234
|
||||
66 81 db 34 12 | sbb bx, 0x1234
|
||||
66 81 5c be 10 34 12 | sbb word ptr [rsi + 4*rdi + 16], 0x1234
|
||||
66 41 83 db fd | sbb r11w, -3
|
||||
66 83 5c be 10 fd | sbb word ptr [rsi + 4*rdi + 16], -3
|
||||
19 cb | sbb ebx, ecx
|
||||
45 19 e1 | sbb r9d, r12d
|
||||
19 c0 | sbb eax, eax
|
||||
19 54 be 10 | sbb dword ptr [rsi + 4*rdi + 16], edx
|
||||
44 1b 54 be 10 | sbb r10d, dword ptr [rsi + 4*rdi + 16]
|
||||
1d 78 56 34 12 | sbb eax, 0x12345678
|
||||
81 db 78 56 34 12 | sbb ebx, 0x12345678
|
||||
81 5c be 10 78 56 34 12 | sbb dword ptr [rsi + 4*rdi + 16], 0x12345678
|
||||
41 83 db fd | sbb r11d, -3
|
||||
83 5c be 10 fd | sbb dword ptr [rsi + 4*rdi + 16], -3
|
||||
48 19 cb | sbb rbx, rcx
|
||||
4d 19 e1 | sbb r9, r12
|
||||
48 19 c0 | sbb rax, rax
|
||||
48 19 54 be 10 | sbb qword ptr [rsi + 4*rdi + 16], rdx
|
||||
4c 1b 54 be 10 | sbb r10, qword ptr [rsi + 4*rdi + 16]
|
||||
48 1d 78 56 34 12 | sbb rax, 0x12345678
|
||||
48 81 db 78 56 34 12 | sbb rbx, 0x12345678
|
||||
48 81 5c be 10 78 56 34 12 | sbb qword ptr [rsi + 4*rdi + 16], 0x12345678
|
||||
49 83 db fd | sbb r11, -3
|
||||
48 83 5c be 10 fd | sbb qword ptr [rsi + 4*rdi + 16], -3
|
||||
18 dc | sbb ah, bl
|
||||
18 f1 | sbb cl, dh
|
||||
80 df 55 | sbb bh, 0x55
|
||||
20 cb | and bl, cl
|
||||
45 20 e1 | and r9b, r12b
|
||||
20 c0 | and al, al
|
||||
20 54 be 10 | and byte ptr [rsi + 4*rdi + 16], dl
|
||||
44 22 54 be 10 | and r10b, byte ptr [rsi + 4*rdi + 16]
|
||||
24 7f | and al, 0x7f
|
||||
80 e3 7f | and bl, 0x7f
|
||||
80 64 be 10 7f | and byte ptr [rsi + 4*rdi + 16], 0x7f
|
||||
66 21 cb | and bx, cx
|
||||
66 45 21 e1 | and r9w, r12w
|
||||
66 21 c0 | and ax, ax
|
||||
66 21 54 be 10 | and word ptr [rsi + 4*rdi + 16], dx
|
||||
66 44 23 54 be 10 | and r10w, word ptr [rsi + 4*rdi + 16]
|
||||
66 25 34 12 | and ax, 0x1234
|
||||
66 81 e3 34 12 | and bx, 0x1234
|
||||
66 81 64 be 10 34 12 | and word ptr [rsi + 4*rdi + 16], 0x1234
|
||||
66 41 83 e3 fd | and r11w, -3
|
||||
66 83 64 be 10 fd | and word ptr [rsi + 4*rdi + 16], -3
|
||||
21 cb | and ebx, ecx
|
||||
45 21 e1 | and r9d, r12d
|
||||
21 c0 | and eax, eax
|
||||
21 54 be 10 | and dword ptr [rsi + 4*rdi + 16], edx
|
||||
44 23 54 be 10 | and r10d, dword ptr [rsi + 4*rdi + 16]
|
||||
25 78 56 34 12 | and eax, 0x12345678
|
||||
81 e3 78 56 34 12 | and ebx, 0x12345678
|
||||
81 64 be 10 78 56 34 12 | and dword ptr [rsi + 4*rdi + 16], 0x12345678
|
||||
41 83 e3 fd | and r11d, -3
|
||||
83 64 be 10 fd | and dword ptr [rsi + 4*rdi + 16], -3
|
||||
48 21 cb | and rbx, rcx
|
||||
4d 21 e1 | and r9, r12
|
||||
48 21 c0 | and rax, rax
|
||||
48 21 54 be 10 | and qword ptr [rsi + 4*rdi + 16], rdx
|
||||
4c 23 54 be 10 | and r10, qword ptr [rsi + 4*rdi + 16]
|
||||
48 25 78 56 34 12 | and rax, 0x12345678
|
||||
48 81 e3 78 56 34 12 | and rbx, 0x12345678
|
||||
48 81 64 be 10 78 56 34 12 | and qword ptr [rsi + 4*rdi + 16], 0x12345678
|
||||
49 83 e3 fd | and r11, -3
|
||||
48 83 64 be 10 fd | and qword ptr [rsi + 4*rdi + 16], -3
|
||||
20 dc | and ah, bl
|
||||
20 f1 | and cl, dh
|
||||
80 e7 55 | and bh, 0x55
|
||||
28 cb | sub bl, cl
|
||||
45 28 e1 | sub r9b, r12b
|
||||
28 c0 | sub al, al
|
||||
28 54 be 10 | sub byte ptr [rsi + 4*rdi + 16], dl
|
||||
44 2a 54 be 10 | sub r10b, byte ptr [rsi + 4*rdi + 16]
|
||||
2c 7f | sub al, 0x7f
|
||||
80 eb 7f | sub bl, 0x7f
|
||||
80 6c be 10 7f | sub byte ptr [rsi + 4*rdi + 16], 0x7f
|
||||
66 29 cb | sub bx, cx
|
||||
66 45 29 e1 | sub r9w, r12w
|
||||
66 29 c0 | sub ax, ax
|
||||
66 29 54 be 10 | sub word ptr [rsi + 4*rdi + 16], dx
|
||||
66 44 2b 54 be 10 | sub r10w, word ptr [rsi + 4*rdi + 16]
|
||||
66 2d 34 12 | sub ax, 0x1234
|
||||
66 81 eb 34 12 | sub bx, 0x1234
|
||||
66 81 6c be 10 34 12 | sub word ptr [rsi + 4*rdi + 16], 0x1234
|
||||
66 41 83 eb fd | sub r11w, -3
|
||||
66 83 6c be 10 fd | sub word ptr [rsi + 4*rdi + 16], -3
|
||||
29 cb | sub ebx, ecx
|
||||
45 29 e1 | sub r9d, r12d
|
||||
29 c0 | sub eax, eax
|
||||
29 54 be 10 | sub dword ptr [rsi + 4*rdi + 16], edx
|
||||
44 2b 54 be 10 | sub r10d, dword ptr [rsi + 4*rdi + 16]
|
||||
2d 78 56 34 12 | sub eax, 0x12345678
|
||||
81 eb 78 56 34 12 | sub ebx, 0x12345678
|
||||
81 6c be 10 78 56 34 12 | sub dword ptr [rsi + 4*rdi + 16], 0x12345678
|
||||
41 83 eb fd | sub r11d, -3
|
||||
83 6c be 10 fd | sub dword ptr [rsi + 4*rdi + 16], -3
|
||||
48 29 cb | sub rbx, rcx
|
||||
4d 29 e1 | sub r9, r12
|
||||
48 29 c0 | sub rax, rax
|
||||
48 29 54 be 10 | sub qword ptr [rsi + 4*rdi + 16], rdx
|
||||
4c 2b 54 be 10 | sub r10, qword ptr [rsi + 4*rdi + 16]
|
||||
48 2d 78 56 34 12 | sub rax, 0x12345678
|
||||
48 81 eb 78 56 34 12 | sub rbx, 0x12345678
|
||||
48 81 6c be 10 78 56 34 12 | sub qword ptr [rsi + 4*rdi + 16], 0x12345678
|
||||
49 83 eb fd | sub r11, -3
|
||||
48 83 6c be 10 fd | sub qword ptr [rsi + 4*rdi + 16], -3
|
||||
28 dc | sub ah, bl
|
||||
28 f1 | sub cl, dh
|
||||
80 ef 55 | sub bh, 0x55
|
||||
30 cb | xor bl, cl
|
||||
45 30 e1 | xor r9b, r12b
|
||||
30 c0 | xor al, al
|
||||
30 54 be 10 | xor byte ptr [rsi + 4*rdi + 16], dl
|
||||
44 32 54 be 10 | xor r10b, byte ptr [rsi + 4*rdi + 16]
|
||||
34 7f | xor al, 0x7f
|
||||
80 f3 7f | xor bl, 0x7f
|
||||
80 74 be 10 7f | xor byte ptr [rsi + 4*rdi + 16], 0x7f
|
||||
66 31 cb | xor bx, cx
|
||||
66 45 31 e1 | xor r9w, r12w
|
||||
66 31 c0 | xor ax, ax
|
||||
66 31 54 be 10 | xor word ptr [rsi + 4*rdi + 16], dx
|
||||
66 44 33 54 be 10 | xor r10w, word ptr [rsi + 4*rdi + 16]
|
||||
66 35 34 12 | xor ax, 0x1234
|
||||
66 81 f3 34 12 | xor bx, 0x1234
|
||||
66 81 74 be 10 34 12 | xor word ptr [rsi + 4*rdi + 16], 0x1234
|
||||
66 41 83 f3 fd | xor r11w, -3
|
||||
66 83 74 be 10 fd | xor word ptr [rsi + 4*rdi + 16], -3
|
||||
31 cb | xor ebx, ecx
|
||||
45 31 e1 | xor r9d, r12d
|
||||
31 c0 | xor eax, eax
|
||||
31 54 be 10 | xor dword ptr [rsi + 4*rdi + 16], edx
|
||||
44 33 54 be 10 | xor r10d, dword ptr [rsi + 4*rdi + 16]
|
||||
35 78 56 34 12 | xor eax, 0x12345678
|
||||
81 f3 78 56 34 12 | xor ebx, 0x12345678
|
||||
81 74 be 10 78 56 34 12 | xor dword ptr [rsi + 4*rdi + 16], 0x12345678
|
||||
41 83 f3 fd | xor r11d, -3
|
||||
83 74 be 10 fd | xor dword ptr [rsi + 4*rdi + 16], -3
|
||||
48 31 cb | xor rbx, rcx
|
||||
4d 31 e1 | xor r9, r12
|
||||
48 31 c0 | xor rax, rax
|
||||
48 31 54 be 10 | xor qword ptr [rsi + 4*rdi + 16], rdx
|
||||
4c 33 54 be 10 | xor r10, qword ptr [rsi + 4*rdi + 16]
|
||||
48 35 78 56 34 12 | xor rax, 0x12345678
|
||||
48 81 f3 78 56 34 12 | xor rbx, 0x12345678
|
||||
48 81 74 be 10 78 56 34 12 | xor qword ptr [rsi + 4*rdi + 16], 0x12345678
|
||||
49 83 f3 fd | xor r11, -3
|
||||
48 83 74 be 10 fd | xor qword ptr [rsi + 4*rdi + 16], -3
|
||||
30 dc | xor ah, bl
|
||||
30 f1 | xor cl, dh
|
||||
80 f7 55 | xor bh, 0x55
|
||||
38 cb | cmp bl, cl
|
||||
45 38 e1 | cmp r9b, r12b
|
||||
38 c0 | cmp al, al
|
||||
38 54 be 10 | cmp byte ptr [rsi + 4*rdi + 16], dl
|
||||
44 3a 54 be 10 | cmp r10b, byte ptr [rsi + 4*rdi + 16]
|
||||
3c 7f | cmp al, 0x7f
|
||||
80 fb 7f | cmp bl, 0x7f
|
||||
80 7c be 10 7f | cmp byte ptr [rsi + 4*rdi + 16], 0x7f
|
||||
66 39 cb | cmp bx, cx
|
||||
66 45 39 e1 | cmp r9w, r12w
|
||||
66 39 c0 | cmp ax, ax
|
||||
66 39 54 be 10 | cmp word ptr [rsi + 4*rdi + 16], dx
|
||||
66 44 3b 54 be 10 | cmp r10w, word ptr [rsi + 4*rdi + 16]
|
||||
66 3d 34 12 | cmp ax, 0x1234
|
||||
66 81 fb 34 12 | cmp bx, 0x1234
|
||||
66 81 7c be 10 34 12 | cmp word ptr [rsi + 4*rdi + 16], 0x1234
|
||||
66 41 83 fb fd | cmp r11w, -3
|
||||
66 83 7c be 10 fd | cmp word ptr [rsi + 4*rdi + 16], -3
|
||||
39 cb | cmp ebx, ecx
|
||||
45 39 e1 | cmp r9d, r12d
|
||||
39 c0 | cmp eax, eax
|
||||
39 54 be 10 | cmp dword ptr [rsi + 4*rdi + 16], edx
|
||||
44 3b 54 be 10 | cmp r10d, dword ptr [rsi + 4*rdi + 16]
|
||||
3d 78 56 34 12 | cmp eax, 0x12345678
|
||||
81 fb 78 56 34 12 | cmp ebx, 0x12345678
|
||||
81 7c be 10 78 56 34 12 | cmp dword ptr [rsi + 4*rdi + 16], 0x12345678
|
||||
41 83 fb fd | cmp r11d, -3
|
||||
83 7c be 10 fd | cmp dword ptr [rsi + 4*rdi + 16], -3
|
||||
48 39 cb | cmp rbx, rcx
|
||||
4d 39 e1 | cmp r9, r12
|
||||
48 39 c0 | cmp rax, rax
|
||||
48 39 54 be 10 | cmp qword ptr [rsi + 4*rdi + 16], rdx
|
||||
4c 3b 54 be 10 | cmp r10, qword ptr [rsi + 4*rdi + 16]
|
||||
48 3d 78 56 34 12 | cmp rax, 0x12345678
|
||||
48 81 fb 78 56 34 12 | cmp rbx, 0x12345678
|
||||
48 81 7c be 10 78 56 34 12 | cmp qword ptr [rsi + 4*rdi + 16], 0x12345678
|
||||
49 83 fb fd | cmp r11, -3
|
||||
48 83 7c be 10 fd | cmp qword ptr [rsi + 4*rdi + 16], -3
|
||||
38 dc | cmp ah, bl
|
||||
38 f1 | cmp cl, dh
|
||||
80 ff 55 | cmp bh, 0x55
|
||||
84 cb | test bl, cl
|
||||
45 84 e1 | test r9b, r12b
|
||||
84 c0 | test al, al
|
||||
84 54 be 10 | test byte ptr [rsi + 4*rdi + 16], dl
|
||||
a8 7f | test al, 0x7f
|
||||
f6 c3 7f | test bl, 0x7f
|
||||
f6 44 be 10 7f | test byte ptr [rsi + 4*rdi + 16], 0x7f
|
||||
66 85 cb | test bx, cx
|
||||
66 45 85 e1 | test r9w, r12w
|
||||
66 85 c0 | test ax, ax
|
||||
66 85 54 be 10 | test word ptr [rsi + 4*rdi + 16], dx
|
||||
66 a9 34 12 | test ax, 0x1234
|
||||
66 f7 c3 34 12 | test bx, 0x1234
|
||||
66 f7 44 be 10 34 12 | test word ptr [rsi + 4*rdi + 16], 0x1234
|
||||
66 41 f7 c3 fd ff | test r11w, -3
|
||||
66 f7 44 be 10 fd ff | test word ptr [rsi + 4*rdi + 16], -3
|
||||
85 cb | test ebx, ecx
|
||||
45 85 e1 | test r9d, r12d
|
||||
85 c0 | test eax, eax
|
||||
85 54 be 10 | test dword ptr [rsi + 4*rdi + 16], edx
|
||||
a9 78 56 34 12 | test eax, 0x12345678
|
||||
f7 c3 78 56 34 12 | test ebx, 0x12345678
|
||||
f7 44 be 10 78 56 34 12 | test dword ptr [rsi + 4*rdi + 16], 0x12345678
|
||||
41 f7 c3 fd ff ff ff | test r11d, -3
|
||||
f7 44 be 10 fd ff ff ff | test dword ptr [rsi + 4*rdi + 16], -3
|
||||
48 85 cb | test rbx, rcx
|
||||
4d 85 e1 | test r9, r12
|
||||
48 85 c0 | test rax, rax
|
||||
48 85 54 be 10 | test qword ptr [rsi + 4*rdi + 16], rdx
|
||||
48 a9 78 56 34 12 | test rax, 0x12345678
|
||||
48 f7 c3 78 56 34 12 | test rbx, 0x12345678
|
||||
48 f7 44 be 10 78 56 34 12 | test qword ptr [rsi + 4*rdi + 16], 0x12345678
|
||||
49 f7 c3 fd ff ff ff | test r11, -3
|
||||
48 f7 44 be 10 fd ff ff ff | test qword ptr [rsi + 4*rdi + 16], -3
|
||||
84 dc | test ah, bl
|
||||
84 f1 | test cl, dh
|
||||
f6 c7 55 | test bh, 0x55
|
||||
fe c1 | inc cl
|
||||
41 fe c1 | inc r9b
|
||||
fe 44 be 10 | inc byte ptr [rsi + 4*rdi + 16]
|
||||
66 ff c1 | inc cx
|
||||
66 41 ff c1 | inc r9w
|
||||
66 ff 44 be 10 | inc word ptr [rsi + 4*rdi + 16]
|
||||
ff c1 | inc ecx
|
||||
41 ff c1 | inc r9d
|
||||
ff 44 be 10 | inc dword ptr [rsi + 4*rdi + 16]
|
||||
48 ff c1 | inc rcx
|
||||
49 ff c1 | inc r9
|
||||
48 ff 44 be 10 | inc qword ptr [rsi + 4*rdi + 16]
|
||||
fe c5 | inc ch
|
||||
fe c9 | dec cl
|
||||
41 fe c9 | dec r9b
|
||||
fe 4c be 10 | dec byte ptr [rsi + 4*rdi + 16]
|
||||
66 ff c9 | dec cx
|
||||
66 41 ff c9 | dec r9w
|
||||
66 ff 4c be 10 | dec word ptr [rsi + 4*rdi + 16]
|
||||
ff c9 | dec ecx
|
||||
41 ff c9 | dec r9d
|
||||
ff 4c be 10 | dec dword ptr [rsi + 4*rdi + 16]
|
||||
48 ff c9 | dec rcx
|
||||
49 ff c9 | dec r9
|
||||
48 ff 4c be 10 | dec qword ptr [rsi + 4*rdi + 16]
|
||||
fe cd | dec ch
|
||||
f6 d9 | neg cl
|
||||
41 f6 d9 | neg r9b
|
||||
f6 5c be 10 | neg byte ptr [rsi + 4*rdi + 16]
|
||||
66 f7 d9 | neg cx
|
||||
66 41 f7 d9 | neg r9w
|
||||
66 f7 5c be 10 | neg word ptr [rsi + 4*rdi + 16]
|
||||
f7 d9 | neg ecx
|
||||
41 f7 d9 | neg r9d
|
||||
f7 5c be 10 | neg dword ptr [rsi + 4*rdi + 16]
|
||||
48 f7 d9 | neg rcx
|
||||
49 f7 d9 | neg r9
|
||||
48 f7 5c be 10 | neg qword ptr [rsi + 4*rdi + 16]
|
||||
f6 dd | neg ch
|
||||
f6 d1 | not cl
|
||||
41 f6 d1 | not r9b
|
||||
f6 54 be 10 | not byte ptr [rsi + 4*rdi + 16]
|
||||
66 f7 d1 | not cx
|
||||
66 41 f7 d1 | not r9w
|
||||
66 f7 54 be 10 | not word ptr [rsi + 4*rdi + 16]
|
||||
f7 d1 | not ecx
|
||||
41 f7 d1 | not r9d
|
||||
f7 54 be 10 | not dword ptr [rsi + 4*rdi + 16]
|
||||
48 f7 d1 | not rcx
|
||||
49 f7 d1 | not r9
|
||||
48 f7 54 be 10 | not qword ptr [rsi + 4*rdi + 16]
|
||||
f6 d5 | not ch
|
||||
f6 e1 | mul cl
|
||||
41 f6 e1 | mul r9b
|
||||
f6 64 be 10 | mul byte ptr [rsi + 4*rdi + 16]
|
||||
66 f7 e1 | mul cx
|
||||
66 41 f7 e1 | mul r9w
|
||||
66 f7 64 be 10 | mul word ptr [rsi + 4*rdi + 16]
|
||||
f7 e1 | mul ecx
|
||||
41 f7 e1 | mul r9d
|
||||
f7 64 be 10 | mul dword ptr [rsi + 4*rdi + 16]
|
||||
48 f7 e1 | mul rcx
|
||||
49 f7 e1 | mul r9
|
||||
48 f7 64 be 10 | mul qword ptr [rsi + 4*rdi + 16]
|
||||
f6 e5 | mul ch
|
||||
f6 e9 | imul cl
|
||||
41 f6 e9 | imul r9b
|
||||
f6 6c be 10 | imul byte ptr [rsi + 4*rdi + 16]
|
||||
66 f7 e9 | imul cx
|
||||
66 41 f7 e9 | imul r9w
|
||||
66 f7 6c be 10 | imul word ptr [rsi + 4*rdi + 16]
|
||||
f7 e9 | imul ecx
|
||||
41 f7 e9 | imul r9d
|
||||
f7 6c be 10 | imul dword ptr [rsi + 4*rdi + 16]
|
||||
48 f7 e9 | imul rcx
|
||||
49 f7 e9 | imul r9
|
||||
48 f7 6c be 10 | imul qword ptr [rsi + 4*rdi + 16]
|
||||
f6 ed | imul ch
|
||||
f6 f1 | div cl
|
||||
41 f6 f1 | div r9b
|
||||
f6 74 be 10 | div byte ptr [rsi + 4*rdi + 16]
|
||||
66 f7 f1 | div cx
|
||||
66 41 f7 f1 | div r9w
|
||||
66 f7 74 be 10 | div word ptr [rsi + 4*rdi + 16]
|
||||
f7 f1 | div ecx
|
||||
41 f7 f1 | div r9d
|
||||
f7 74 be 10 | div dword ptr [rsi + 4*rdi + 16]
|
||||
48 f7 f1 | div rcx
|
||||
49 f7 f1 | div r9
|
||||
48 f7 74 be 10 | div qword ptr [rsi + 4*rdi + 16]
|
||||
f6 f5 | div ch
|
||||
f6 f9 | idiv cl
|
||||
41 f6 f9 | idiv r9b
|
||||
f6 7c be 10 | idiv byte ptr [rsi + 4*rdi + 16]
|
||||
66 f7 f9 | idiv cx
|
||||
66 41 f7 f9 | idiv r9w
|
||||
66 f7 7c be 10 | idiv word ptr [rsi + 4*rdi + 16]
|
||||
f7 f9 | idiv ecx
|
||||
41 f7 f9 | idiv r9d
|
||||
f7 7c be 10 | idiv dword ptr [rsi + 4*rdi + 16]
|
||||
48 f7 f9 | idiv rcx
|
||||
49 f7 f9 | idiv r9
|
||||
48 f7 7c be 10 | idiv qword ptr [rsi + 4*rdi + 16]
|
||||
f6 fd | idiv ch
|
||||
d0 c3 | rol bl, 1
|
||||
d0 44 be 10 | rol byte ptr [rsi + 4*rdi + 16], 1
|
||||
c0 c3 03 | rol bl, 3
|
||||
c0 44 be 10 03 | rol byte ptr [rsi + 4*rdi + 16], 3
|
||||
c0 c3 07 | rol bl, 7
|
||||
c0 44 be 10 07 | rol byte ptr [rsi + 4*rdi + 16], 7
|
||||
d2 c3 | rol bl, cl
|
||||
d2 44 be 10 | rol byte ptr [rsi + 4*rdi + 16], cl
|
||||
41 c0 c5 07 | rol r13b, 7
|
||||
41 c0 c5 00 | rol r13b, 0
|
||||
66 d1 c3 | rol bx, 1
|
||||
66 d1 44 be 10 | rol word ptr [rsi + 4*rdi + 16], 1
|
||||
66 c1 c3 03 | rol bx, 3
|
||||
66 c1 44 be 10 03 | rol word ptr [rsi + 4*rdi + 16], 3
|
||||
66 c1 c3 07 | rol bx, 7
|
||||
66 c1 44 be 10 07 | rol word ptr [rsi + 4*rdi + 16], 7
|
||||
66 d3 c3 | rol bx, cl
|
||||
66 d3 44 be 10 | rol word ptr [rsi + 4*rdi + 16], cl
|
||||
66 41 c1 c5 0f | rol r13w, 15
|
||||
66 41 c1 c5 00 | rol r13w, 0
|
||||
d1 c3 | rol ebx, 1
|
||||
d1 44 be 10 | rol dword ptr [rsi + 4*rdi + 16], 1
|
||||
c1 c3 03 | rol ebx, 3
|
||||
c1 44 be 10 03 | rol dword ptr [rsi + 4*rdi + 16], 3
|
||||
c1 c3 07 | rol ebx, 7
|
||||
c1 44 be 10 07 | rol dword ptr [rsi + 4*rdi + 16], 7
|
||||
d3 c3 | rol ebx, cl
|
||||
d3 44 be 10 | rol dword ptr [rsi + 4*rdi + 16], cl
|
||||
41 c1 c5 1f | rol r13d, 31
|
||||
41 c1 c5 00 | rol r13d, 0
|
||||
48 d1 c3 | rol rbx, 1
|
||||
48 d1 44 be 10 | rol qword ptr [rsi + 4*rdi + 16], 1
|
||||
48 c1 c3 03 | rol rbx, 3
|
||||
48 c1 44 be 10 03 | rol qword ptr [rsi + 4*rdi + 16], 3
|
||||
48 c1 c3 07 | rol rbx, 7
|
||||
48 c1 44 be 10 07 | rol qword ptr [rsi + 4*rdi + 16], 7
|
||||
48 d3 c3 | rol rbx, cl
|
||||
48 d3 44 be 10 | rol qword ptr [rsi + 4*rdi + 16], cl
|
||||
49 c1 c5 3f | rol r13, 63
|
||||
49 c1 c5 00 | rol r13, 0
|
||||
d0 cb | ror bl, 1
|
||||
d0 4c be 10 | ror byte ptr [rsi + 4*rdi + 16], 1
|
||||
c0 cb 03 | ror bl, 3
|
||||
c0 4c be 10 03 | ror byte ptr [rsi + 4*rdi + 16], 3
|
||||
c0 cb 07 | ror bl, 7
|
||||
c0 4c be 10 07 | ror byte ptr [rsi + 4*rdi + 16], 7
|
||||
d2 cb | ror bl, cl
|
||||
d2 4c be 10 | ror byte ptr [rsi + 4*rdi + 16], cl
|
||||
41 c0 cd 07 | ror r13b, 7
|
||||
41 c0 cd 00 | ror r13b, 0
|
||||
66 d1 cb | ror bx, 1
|
||||
66 d1 4c be 10 | ror word ptr [rsi + 4*rdi + 16], 1
|
||||
66 c1 cb 03 | ror bx, 3
|
||||
66 c1 4c be 10 03 | ror word ptr [rsi + 4*rdi + 16], 3
|
||||
66 c1 cb 07 | ror bx, 7
|
||||
66 c1 4c be 10 07 | ror word ptr [rsi + 4*rdi + 16], 7
|
||||
66 d3 cb | ror bx, cl
|
||||
66 d3 4c be 10 | ror word ptr [rsi + 4*rdi + 16], cl
|
||||
66 41 c1 cd 0f | ror r13w, 15
|
||||
66 41 c1 cd 00 | ror r13w, 0
|
||||
d1 cb | ror ebx, 1
|
||||
d1 4c be 10 | ror dword ptr [rsi + 4*rdi + 16], 1
|
||||
c1 cb 03 | ror ebx, 3
|
||||
c1 4c be 10 03 | ror dword ptr [rsi + 4*rdi + 16], 3
|
||||
c1 cb 07 | ror ebx, 7
|
||||
c1 4c be 10 07 | ror dword ptr [rsi + 4*rdi + 16], 7
|
||||
d3 cb | ror ebx, cl
|
||||
d3 4c be 10 | ror dword ptr [rsi + 4*rdi + 16], cl
|
||||
41 c1 cd 1f | ror r13d, 31
|
||||
41 c1 cd 00 | ror r13d, 0
|
||||
48 d1 cb | ror rbx, 1
|
||||
48 d1 4c be 10 | ror qword ptr [rsi + 4*rdi + 16], 1
|
||||
48 c1 cb 03 | ror rbx, 3
|
||||
48 c1 4c be 10 03 | ror qword ptr [rsi + 4*rdi + 16], 3
|
||||
48 c1 cb 07 | ror rbx, 7
|
||||
48 c1 4c be 10 07 | ror qword ptr [rsi + 4*rdi + 16], 7
|
||||
48 d3 cb | ror rbx, 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 e3 | shl bl, 1
|
||||
d0 64 be 10 | shl byte ptr [rsi + 4*rdi + 16], 1
|
||||
c0 e3 03 | shl bl, 3
|
||||
c0 64 be 10 03 | shl byte ptr [rsi + 4*rdi + 16], 3
|
||||
c0 e3 07 | shl bl, 7
|
||||
c0 64 be 10 07 | shl byte ptr [rsi + 4*rdi + 16], 7
|
||||
d2 e3 | shl bl, cl
|
||||
d2 64 be 10 | shl byte ptr [rsi + 4*rdi + 16], cl
|
||||
41 c0 e5 07 | shl r13b, 7
|
||||
41 c0 e5 00 | shl r13b, 0
|
||||
66 d1 e3 | shl bx, 1
|
||||
66 d1 64 be 10 | shl word ptr [rsi + 4*rdi + 16], 1
|
||||
66 c1 e3 03 | shl bx, 3
|
||||
66 c1 64 be 10 03 | shl word ptr [rsi + 4*rdi + 16], 3
|
||||
66 c1 e3 07 | shl bx, 7
|
||||
66 c1 64 be 10 07 | shl word ptr [rsi + 4*rdi + 16], 7
|
||||
66 d3 e3 | shl bx, cl
|
||||
66 d3 64 be 10 | shl word ptr [rsi + 4*rdi + 16], cl
|
||||
66 41 c1 e5 0f | shl r13w, 15
|
||||
66 41 c1 e5 00 | shl r13w, 0
|
||||
d1 e3 | shl ebx, 1
|
||||
d1 64 be 10 | shl dword ptr [rsi + 4*rdi + 16], 1
|
||||
c1 e3 03 | shl ebx, 3
|
||||
c1 64 be 10 03 | shl dword ptr [rsi + 4*rdi + 16], 3
|
||||
c1 e3 07 | shl ebx, 7
|
||||
c1 64 be 10 07 | shl dword ptr [rsi + 4*rdi + 16], 7
|
||||
d3 e3 | shl ebx, cl
|
||||
d3 64 be 10 | shl dword ptr [rsi + 4*rdi + 16], cl
|
||||
41 c1 e5 1f | shl r13d, 31
|
||||
41 c1 e5 00 | shl r13d, 0
|
||||
48 d1 e3 | shl rbx, 1
|
||||
48 d1 64 be 10 | shl qword ptr [rsi + 4*rdi + 16], 1
|
||||
48 c1 e3 03 | shl rbx, 3
|
||||
48 c1 64 be 10 03 | shl qword ptr [rsi + 4*rdi + 16], 3
|
||||
48 c1 e3 07 | shl rbx, 7
|
||||
48 c1 64 be 10 07 | shl qword ptr [rsi + 4*rdi + 16], 7
|
||||
48 d3 e3 | shl rbx, cl
|
||||
48 d3 64 be 10 | shl qword ptr [rsi + 4*rdi + 16], cl
|
||||
49 c1 e5 3f | shl r13, 63
|
||||
49 c1 e5 00 | shl r13, 0
|
||||
d0 eb | shr bl, 1
|
||||
d0 6c be 10 | shr byte ptr [rsi + 4*rdi + 16], 1
|
||||
c0 eb 03 | shr bl, 3
|
||||
c0 6c be 10 03 | shr byte ptr [rsi + 4*rdi + 16], 3
|
||||
c0 eb 07 | shr bl, 7
|
||||
c0 6c be 10 07 | shr byte ptr [rsi + 4*rdi + 16], 7
|
||||
d2 eb | shr bl, cl
|
||||
d2 6c be 10 | shr byte ptr [rsi + 4*rdi + 16], cl
|
||||
41 c0 ed 07 | shr r13b, 7
|
||||
41 c0 ed 00 | shr r13b, 0
|
||||
66 d1 eb | shr bx, 1
|
||||
66 d1 6c be 10 | shr word ptr [rsi + 4*rdi + 16], 1
|
||||
66 c1 eb 03 | shr bx, 3
|
||||
66 c1 6c be 10 03 | shr word ptr [rsi + 4*rdi + 16], 3
|
||||
66 c1 eb 07 | shr bx, 7
|
||||
66 c1 6c be 10 07 | shr word ptr [rsi + 4*rdi + 16], 7
|
||||
66 d3 eb | shr bx, cl
|
||||
66 d3 6c be 10 | shr word ptr [rsi + 4*rdi + 16], cl
|
||||
66 41 c1 ed 0f | shr r13w, 15
|
||||
66 41 c1 ed 00 | shr r13w, 0
|
||||
d1 eb | shr ebx, 1
|
||||
d1 6c be 10 | shr dword ptr [rsi + 4*rdi + 16], 1
|
||||
c1 eb 03 | shr ebx, 3
|
||||
c1 6c be 10 03 | shr dword ptr [rsi + 4*rdi + 16], 3
|
||||
c1 eb 07 | shr ebx, 7
|
||||
c1 6c be 10 07 | shr dword ptr [rsi + 4*rdi + 16], 7
|
||||
d3 eb | shr ebx, cl
|
||||
d3 6c be 10 | shr dword ptr [rsi + 4*rdi + 16], cl
|
||||
41 c1 ed 1f | shr r13d, 31
|
||||
41 c1 ed 00 | shr r13d, 0
|
||||
48 d1 eb | shr rbx, 1
|
||||
48 d1 6c be 10 | shr qword ptr [rsi + 4*rdi + 16], 1
|
||||
48 c1 eb 03 | shr rbx, 3
|
||||
48 c1 6c be 10 03 | shr qword ptr [rsi + 4*rdi + 16], 3
|
||||
48 c1 eb 07 | shr rbx, 7
|
||||
48 c1 6c be 10 07 | shr qword ptr [rsi + 4*rdi + 16], 7
|
||||
48 d3 eb | shr rbx, cl
|
||||
48 d3 6c be 10 | shr qword ptr [rsi + 4*rdi + 16], cl
|
||||
49 c1 ed 3f | shr r13, 63
|
||||
49 c1 ed 00 | shr r13, 0
|
||||
d0 fb | sar bl, 1
|
||||
d0 7c be 10 | sar byte ptr [rsi + 4*rdi + 16], 1
|
||||
c0 fb 03 | sar bl, 3
|
||||
c0 7c be 10 03 | sar byte ptr [rsi + 4*rdi + 16], 3
|
||||
c0 fb 07 | sar bl, 7
|
||||
c0 7c be 10 07 | sar byte ptr [rsi + 4*rdi + 16], 7
|
||||
d2 fb | sar bl, cl
|
||||
d2 7c be 10 | sar byte ptr [rsi + 4*rdi + 16], cl
|
||||
41 c0 fd 07 | sar r13b, 7
|
||||
41 c0 fd 00 | sar r13b, 0
|
||||
66 d1 fb | sar bx, 1
|
||||
66 d1 7c be 10 | sar word ptr [rsi + 4*rdi + 16], 1
|
||||
66 c1 fb 03 | sar bx, 3
|
||||
66 c1 7c be 10 03 | sar word ptr [rsi + 4*rdi + 16], 3
|
||||
66 c1 fb 07 | sar bx, 7
|
||||
66 c1 7c be 10 07 | sar word ptr [rsi + 4*rdi + 16], 7
|
||||
66 d3 fb | sar bx, cl
|
||||
66 d3 7c be 10 | sar word ptr [rsi + 4*rdi + 16], cl
|
||||
66 41 c1 fd 0f | sar r13w, 15
|
||||
66 41 c1 fd 00 | sar r13w, 0
|
||||
d1 fb | sar ebx, 1
|
||||
d1 7c be 10 | sar dword ptr [rsi + 4*rdi + 16], 1
|
||||
c1 fb 03 | sar ebx, 3
|
||||
c1 7c be 10 03 | sar dword ptr [rsi + 4*rdi + 16], 3
|
||||
c1 fb 07 | sar ebx, 7
|
||||
c1 7c be 10 07 | sar dword ptr [rsi + 4*rdi + 16], 7
|
||||
d3 fb | sar ebx, cl
|
||||
d3 7c be 10 | sar dword ptr [rsi + 4*rdi + 16], cl
|
||||
41 c1 fd 1f | sar r13d, 31
|
||||
41 c1 fd 00 | sar r13d, 0
|
||||
48 d1 fb | sar rbx, 1
|
||||
48 d1 7c be 10 | sar qword ptr [rsi + 4*rdi + 16], 1
|
||||
48 c1 fb 03 | sar rbx, 3
|
||||
48 c1 7c be 10 03 | sar qword ptr [rsi + 4*rdi + 16], 3
|
||||
48 c1 fb 07 | sar rbx, 7
|
||||
48 c1 7c be 10 07 | sar qword ptr [rsi + 4*rdi + 16], 7
|
||||
48 d3 fb | sar rbx, cl
|
||||
48 d3 7c be 10 | sar qword ptr [rsi + 4*rdi + 16], cl
|
||||
49 c1 fd 3f | sar r13, 63
|
||||
49 c1 fd 00 | sar r13, 0
|
||||
66 41 0f af d9 | imul bx, r9w
|
||||
66 0f af 5c be 10 | imul bx, word ptr [rsi + 4*rdi + 16]
|
||||
66 44 6b c1 f9 | imul r8w, cx, -7
|
||||
66 44 69 c1 34 12 | imul r8w, cx, 0x1234
|
||||
66 44 69 44 be 10 34 12 | imul r8w, word ptr [rsi + 4*rdi + 16], 0x1234
|
||||
66 41 0f bc d9 | bsf bx, r9w
|
||||
66 44 0f bc 54 be 10 | bsf r10w, word ptr [rsi + 4*rdi + 16]
|
||||
66 41 0f bd d9 | bsr bx, r9w
|
||||
66 44 0f bd 54 be 10 | bsr r10w, word ptr [rsi + 4*rdi + 16]
|
||||
66 f3 41 0f b8 d9 | popcnt bx, r9w
|
||||
66 f3 44 0f b8 54 be 10 | popcnt r10w, word ptr [rsi + 4*rdi + 16]
|
||||
66 f3 41 0f bc d9 | tzcnt bx, r9w
|
||||
66 f3 44 0f bc 54 be 10 | tzcnt r10w, word ptr [rsi + 4*rdi + 16]
|
||||
66 f3 41 0f bd d9 | lzcnt bx, r9w
|
||||
66 f3 44 0f bd 54 be 10 | lzcnt r10w, word ptr [rsi + 4*rdi + 16]
|
||||
66 44 0f a3 cb | bt bx, r9w
|
||||
66 41 0f ba e2 05 | bt r10w, 5
|
||||
66 0f ba 64 be 10 0f | bt word ptr [rsi + 4*rdi + 16], 15
|
||||
66 44 0f ab cb | bts bx, r9w
|
||||
66 41 0f ba ea 05 | bts r10w, 5
|
||||
66 0f ba 6c be 10 0f | bts word ptr [rsi + 4*rdi + 16], 15
|
||||
66 44 0f b3 cb | btr bx, r9w
|
||||
66 41 0f ba f2 05 | btr r10w, 5
|
||||
66 0f ba 74 be 10 0f | btr word ptr [rsi + 4*rdi + 16], 15
|
||||
66 44 0f bb cb | btc bx, r9w
|
||||
66 41 0f ba fa 05 | btc r10w, 5
|
||||
66 0f ba 7c be 10 0f | btc word ptr [rsi + 4*rdi + 16], 15
|
||||
66 41 0f 40 d9 | cmovo bx, r9w
|
||||
66 44 0f 40 54 be 10 | cmovo r10w, word ptr [rsi + 4*rdi + 16]
|
||||
66 41 0f 41 d9 | cmovno bx, r9w
|
||||
66 44 0f 41 54 be 10 | cmovno r10w, word ptr [rsi + 4*rdi + 16]
|
||||
66 41 0f 42 d9 | cmovb bx, r9w
|
||||
66 44 0f 42 54 be 10 | cmovb r10w, word ptr [rsi + 4*rdi + 16]
|
||||
66 41 0f 43 d9 | cmovae bx, r9w
|
||||
66 44 0f 43 54 be 10 | cmovae r10w, word ptr [rsi + 4*rdi + 16]
|
||||
66 41 0f 44 d9 | cmove bx, r9w
|
||||
66 44 0f 44 54 be 10 | cmove r10w, word ptr [rsi + 4*rdi + 16]
|
||||
66 41 0f 45 d9 | cmovne bx, r9w
|
||||
66 44 0f 45 54 be 10 | cmovne r10w, word ptr [rsi + 4*rdi + 16]
|
||||
66 41 0f 46 d9 | cmovbe bx, r9w
|
||||
66 44 0f 46 54 be 10 | cmovbe r10w, word ptr [rsi + 4*rdi + 16]
|
||||
66 41 0f 47 d9 | cmova bx, r9w
|
||||
66 44 0f 47 54 be 10 | cmova r10w, word ptr [rsi + 4*rdi + 16]
|
||||
66 41 0f 48 d9 | cmovs bx, r9w
|
||||
66 44 0f 48 54 be 10 | cmovs r10w, word ptr [rsi + 4*rdi + 16]
|
||||
66 41 0f 49 d9 | cmovns bx, r9w
|
||||
66 44 0f 49 54 be 10 | cmovns r10w, word ptr [rsi + 4*rdi + 16]
|
||||
66 41 0f 4a d9 | cmovp bx, r9w
|
||||
66 44 0f 4a 54 be 10 | cmovp r10w, word ptr [rsi + 4*rdi + 16]
|
||||
66 41 0f 4b d9 | cmovnp bx, r9w
|
||||
66 44 0f 4b 54 be 10 | cmovnp r10w, word ptr [rsi + 4*rdi + 16]
|
||||
66 41 0f 4c d9 | cmovl bx, r9w
|
||||
66 44 0f 4c 54 be 10 | cmovl r10w, word ptr [rsi + 4*rdi + 16]
|
||||
66 41 0f 4d d9 | cmovge bx, r9w
|
||||
66 44 0f 4d 54 be 10 | cmovge r10w, word ptr [rsi + 4*rdi + 16]
|
||||
66 41 0f 4e d9 | cmovle bx, r9w
|
||||
66 44 0f 4e 54 be 10 | cmovle r10w, word ptr [rsi + 4*rdi + 16]
|
||||
66 41 0f 4f d9 | cmovg bx, r9w
|
||||
66 44 0f 4f 54 be 10 | cmovg r10w, word ptr [rsi + 4*rdi + 16]
|
||||
66 41 0f b6 d9 | movzx bx, r9b
|
||||
66 44 0f b6 54 be 10 | movzx r10w, byte ptr [rsi + 4*rdi + 16]
|
||||
66 41 0f be d9 | movsx bx, r9b
|
||||
66 44 0f be 54 be 10 | movsx r10w, byte ptr [rsi + 4*rdi + 16]
|
||||
66 8d 5c be 10 | lea bx, [rsi + 4*rdi + 16]
|
||||
66 45 8d 61 fb | lea r12w, [r9 - 5]
|
||||
66 42 8d 04 d5 40 00 00 00 | lea ax, [8*r10 + 64]
|
||||
41 0f af d9 | imul ebx, r9d
|
||||
0f af 5c be 10 | imul ebx, dword ptr [rsi + 4*rdi + 16]
|
||||
44 6b c1 f9 | imul r8d, ecx, -7
|
||||
44 69 c1 34 12 00 00 | imul r8d, ecx, 0x1234
|
||||
44 69 44 be 10 34 12 00 00 | imul r8d, dword ptr [rsi + 4*rdi + 16], 0x1234
|
||||
41 0f bc d9 | bsf ebx, r9d
|
||||
44 0f bc 54 be 10 | bsf r10d, dword ptr [rsi + 4*rdi + 16]
|
||||
41 0f bd d9 | bsr ebx, r9d
|
||||
44 0f bd 54 be 10 | bsr r10d, dword ptr [rsi + 4*rdi + 16]
|
||||
f3 41 0f b8 d9 | popcnt ebx, r9d
|
||||
f3 44 0f b8 54 be 10 | popcnt r10d, dword ptr [rsi + 4*rdi + 16]
|
||||
f3 41 0f bc d9 | tzcnt ebx, r9d
|
||||
f3 44 0f bc 54 be 10 | tzcnt r10d, dword ptr [rsi + 4*rdi + 16]
|
||||
f3 41 0f bd d9 | lzcnt ebx, r9d
|
||||
f3 44 0f bd 54 be 10 | lzcnt r10d, dword ptr [rsi + 4*rdi + 16]
|
||||
44 0f a3 cb | bt ebx, r9d
|
||||
41 0f ba e2 05 | bt r10d, 5
|
||||
0f ba 64 be 10 1f | bt dword ptr [rsi + 4*rdi + 16], 31
|
||||
44 0f ab cb | bts ebx, r9d
|
||||
41 0f ba ea 05 | bts r10d, 5
|
||||
0f ba 6c be 10 1f | bts dword ptr [rsi + 4*rdi + 16], 31
|
||||
44 0f b3 cb | btr ebx, r9d
|
||||
41 0f ba f2 05 | btr r10d, 5
|
||||
0f ba 74 be 10 1f | btr dword ptr [rsi + 4*rdi + 16], 31
|
||||
44 0f bb cb | btc ebx, r9d
|
||||
41 0f ba fa 05 | btc r10d, 5
|
||||
0f ba 7c be 10 1f | btc dword ptr [rsi + 4*rdi + 16], 31
|
||||
41 0f 40 d9 | cmovo ebx, r9d
|
||||
44 0f 40 54 be 10 | cmovo r10d, dword ptr [rsi + 4*rdi + 16]
|
||||
41 0f 41 d9 | cmovno ebx, r9d
|
||||
44 0f 41 54 be 10 | cmovno r10d, dword ptr [rsi + 4*rdi + 16]
|
||||
41 0f 42 d9 | cmovb ebx, r9d
|
||||
44 0f 42 54 be 10 | cmovb r10d, dword ptr [rsi + 4*rdi + 16]
|
||||
41 0f 43 d9 | cmovae ebx, r9d
|
||||
44 0f 43 54 be 10 | cmovae r10d, dword ptr [rsi + 4*rdi + 16]
|
||||
41 0f 44 d9 | cmove ebx, r9d
|
||||
44 0f 44 54 be 10 | cmove r10d, dword ptr [rsi + 4*rdi + 16]
|
||||
41 0f 45 d9 | cmovne ebx, r9d
|
||||
44 0f 45 54 be 10 | cmovne r10d, dword ptr [rsi + 4*rdi + 16]
|
||||
41 0f 46 d9 | cmovbe ebx, r9d
|
||||
44 0f 46 54 be 10 | cmovbe r10d, dword ptr [rsi + 4*rdi + 16]
|
||||
41 0f 47 d9 | cmova ebx, r9d
|
||||
44 0f 47 54 be 10 | cmova r10d, dword ptr [rsi + 4*rdi + 16]
|
||||
41 0f 48 d9 | cmovs ebx, r9d
|
||||
44 0f 48 54 be 10 | cmovs r10d, dword ptr [rsi + 4*rdi + 16]
|
||||
41 0f 49 d9 | cmovns ebx, r9d
|
||||
44 0f 49 54 be 10 | cmovns r10d, dword ptr [rsi + 4*rdi + 16]
|
||||
41 0f 4a d9 | cmovp ebx, r9d
|
||||
44 0f 4a 54 be 10 | cmovp r10d, dword ptr [rsi + 4*rdi + 16]
|
||||
41 0f 4b d9 | cmovnp ebx, r9d
|
||||
44 0f 4b 54 be 10 | cmovnp r10d, dword ptr [rsi + 4*rdi + 16]
|
||||
41 0f 4c d9 | cmovl ebx, r9d
|
||||
44 0f 4c 54 be 10 | cmovl r10d, dword ptr [rsi + 4*rdi + 16]
|
||||
41 0f 4d d9 | cmovge ebx, r9d
|
||||
44 0f 4d 54 be 10 | cmovge r10d, dword ptr [rsi + 4*rdi + 16]
|
||||
41 0f 4e d9 | cmovle ebx, r9d
|
||||
44 0f 4e 54 be 10 | cmovle r10d, dword ptr [rsi + 4*rdi + 16]
|
||||
41 0f 4f d9 | cmovg ebx, r9d
|
||||
44 0f 4f 54 be 10 | cmovg r10d, dword ptr [rsi + 4*rdi + 16]
|
||||
41 0f b6 d9 | movzx ebx, r9b
|
||||
44 0f b6 54 be 10 | movzx r10d, byte ptr [rsi + 4*rdi + 16]
|
||||
41 0f be d9 | movsx ebx, r9b
|
||||
44 0f be 54 be 10 | movsx r10d, byte ptr [rsi + 4*rdi + 16]
|
||||
41 0f b7 d9 | movzx ebx, r9w
|
||||
44 0f b7 54 be 10 | movzx r10d, word ptr [rsi + 4*rdi + 16]
|
||||
41 0f bf d9 | movsx ebx, r9w
|
||||
44 0f bf 54 be 10 | movsx r10d, word ptr [rsi + 4*rdi + 16]
|
||||
8d 5c be 10 | lea ebx, [rsi + 4*rdi + 16]
|
||||
45 8d 61 fb | lea r12d, [r9 - 5]
|
||||
42 8d 04 d5 40 00 00 00 | lea eax, [8*r10 + 64]
|
||||
49 0f af d9 | imul rbx, r9
|
||||
48 0f af 5c be 10 | imul rbx, qword ptr [rsi + 4*rdi + 16]
|
||||
4c 6b c1 f9 | imul r8, rcx, -7
|
||||
4c 69 c1 34 12 00 00 | imul r8, rcx, 0x1234
|
||||
4c 69 44 be 10 34 12 00 00 | imul r8, qword ptr [rsi + 4*rdi + 16], 0x1234
|
||||
49 0f bc d9 | bsf rbx, r9
|
||||
4c 0f bc 54 be 10 | bsf r10, qword ptr [rsi + 4*rdi + 16]
|
||||
49 0f bd d9 | bsr rbx, r9
|
||||
4c 0f bd 54 be 10 | bsr r10, qword ptr [rsi + 4*rdi + 16]
|
||||
f3 49 0f b8 d9 | popcnt rbx, r9
|
||||
f3 4c 0f b8 54 be 10 | popcnt r10, qword ptr [rsi + 4*rdi + 16]
|
||||
f3 49 0f bc d9 | tzcnt rbx, r9
|
||||
f3 4c 0f bc 54 be 10 | tzcnt r10, qword ptr [rsi + 4*rdi + 16]
|
||||
f3 49 0f bd d9 | lzcnt rbx, r9
|
||||
f3 4c 0f bd 54 be 10 | lzcnt r10, qword ptr [rsi + 4*rdi + 16]
|
||||
4c 0f a3 cb | bt rbx, r9
|
||||
49 0f ba e2 05 | bt r10, 5
|
||||
48 0f ba 64 be 10 3f | bt qword ptr [rsi + 4*rdi + 16], 63
|
||||
4c 0f ab cb | bts rbx, r9
|
||||
49 0f ba ea 05 | bts r10, 5
|
||||
48 0f ba 6c be 10 3f | bts qword ptr [rsi + 4*rdi + 16], 63
|
||||
4c 0f b3 cb | btr rbx, r9
|
||||
49 0f ba f2 05 | btr r10, 5
|
||||
48 0f ba 74 be 10 3f | btr qword ptr [rsi + 4*rdi + 16], 63
|
||||
4c 0f bb cb | btc rbx, r9
|
||||
49 0f ba fa 05 | btc r10, 5
|
||||
48 0f ba 7c be 10 3f | btc qword ptr [rsi + 4*rdi + 16], 63
|
||||
49 0f 40 d9 | cmovo rbx, r9
|
||||
4c 0f 40 54 be 10 | cmovo r10, qword ptr [rsi + 4*rdi + 16]
|
||||
49 0f 41 d9 | cmovno rbx, r9
|
||||
4c 0f 41 54 be 10 | cmovno r10, qword ptr [rsi + 4*rdi + 16]
|
||||
49 0f 42 d9 | cmovb rbx, r9
|
||||
4c 0f 42 54 be 10 | cmovb r10, qword ptr [rsi + 4*rdi + 16]
|
||||
49 0f 43 d9 | cmovae rbx, r9
|
||||
4c 0f 43 54 be 10 | cmovae r10, qword ptr [rsi + 4*rdi + 16]
|
||||
49 0f 44 d9 | cmove rbx, r9
|
||||
4c 0f 44 54 be 10 | cmove r10, qword ptr [rsi + 4*rdi + 16]
|
||||
49 0f 45 d9 | cmovne rbx, r9
|
||||
4c 0f 45 54 be 10 | cmovne r10, qword ptr [rsi + 4*rdi + 16]
|
||||
49 0f 46 d9 | cmovbe rbx, r9
|
||||
4c 0f 46 54 be 10 | cmovbe r10, qword ptr [rsi + 4*rdi + 16]
|
||||
49 0f 47 d9 | cmova rbx, r9
|
||||
4c 0f 47 54 be 10 | cmova r10, qword ptr [rsi + 4*rdi + 16]
|
||||
49 0f 48 d9 | cmovs rbx, r9
|
||||
4c 0f 48 54 be 10 | cmovs r10, qword ptr [rsi + 4*rdi + 16]
|
||||
49 0f 49 d9 | cmovns rbx, r9
|
||||
4c 0f 49 54 be 10 | cmovns r10, qword ptr [rsi + 4*rdi + 16]
|
||||
49 0f 4a d9 | cmovp rbx, r9
|
||||
4c 0f 4a 54 be 10 | cmovp r10, qword ptr [rsi + 4*rdi + 16]
|
||||
49 0f 4b d9 | cmovnp rbx, r9
|
||||
4c 0f 4b 54 be 10 | cmovnp r10, qword ptr [rsi + 4*rdi + 16]
|
||||
49 0f 4c d9 | cmovl rbx, r9
|
||||
4c 0f 4c 54 be 10 | cmovl r10, qword ptr [rsi + 4*rdi + 16]
|
||||
49 0f 4d d9 | cmovge rbx, r9
|
||||
4c 0f 4d 54 be 10 | cmovge r10, qword ptr [rsi + 4*rdi + 16]
|
||||
49 0f 4e d9 | cmovle rbx, r9
|
||||
4c 0f 4e 54 be 10 | cmovle r10, qword ptr [rsi + 4*rdi + 16]
|
||||
49 0f 4f d9 | cmovg rbx, r9
|
||||
4c 0f 4f 54 be 10 | cmovg r10, qword ptr [rsi + 4*rdi + 16]
|
||||
49 0f b6 d9 | movzx rbx, r9b
|
||||
4c 0f b6 54 be 10 | movzx r10, byte ptr [rsi + 4*rdi + 16]
|
||||
49 0f be d9 | movsx rbx, r9b
|
||||
4c 0f be 54 be 10 | movsx r10, byte ptr [rsi + 4*rdi + 16]
|
||||
49 0f b7 d9 | movzx rbx, r9w
|
||||
4c 0f b7 54 be 10 | movzx r10, word ptr [rsi + 4*rdi + 16]
|
||||
49 0f bf d9 | movsx rbx, r9w
|
||||
4c 0f bf 54 be 10 | movsx r10, word ptr [rsi + 4*rdi + 16]
|
||||
48 8d 5c be 10 | lea rbx, [rsi + 4*rdi + 16]
|
||||
4d 8d 61 fb | lea r12, [r9 - 5]
|
||||
4a 8d 04 d5 40 00 00 00 | lea rax, [8*r10 + 64]
|
||||
49 63 d9 | movsxd rbx, r9d
|
||||
4c 63 54 be 10 | movsxd r10, dword ptr [rsi + 4*rdi + 16]
|
||||
0f b6 dc | movzx ebx, ah
|
||||
0f be cf | movsx ecx, bh
|
||||
0f 90 c3 | seto bl
|
||||
0f 90 44 be 10 | seto byte ptr [rsi + 4*rdi + 16]
|
||||
0f 90 c4 | seto ah
|
||||
0f 91 c3 | setno bl
|
||||
0f 91 44 be 10 | setno byte ptr [rsi + 4*rdi + 16]
|
||||
0f 91 c4 | setno ah
|
||||
0f 92 c3 | setb bl
|
||||
0f 92 44 be 10 | setb byte ptr [rsi + 4*rdi + 16]
|
||||
0f 92 c4 | setb ah
|
||||
0f 93 c3 | setae bl
|
||||
0f 93 44 be 10 | setae byte ptr [rsi + 4*rdi + 16]
|
||||
0f 93 c4 | setae ah
|
||||
0f 94 c3 | sete bl
|
||||
0f 94 44 be 10 | sete byte ptr [rsi + 4*rdi + 16]
|
||||
0f 94 c4 | sete ah
|
||||
0f 95 c3 | setne bl
|
||||
0f 95 44 be 10 | setne byte ptr [rsi + 4*rdi + 16]
|
||||
0f 95 c4 | setne ah
|
||||
0f 96 c3 | setbe bl
|
||||
0f 96 44 be 10 | setbe byte ptr [rsi + 4*rdi + 16]
|
||||
0f 96 c4 | setbe ah
|
||||
0f 97 c3 | seta bl
|
||||
0f 97 44 be 10 | seta byte ptr [rsi + 4*rdi + 16]
|
||||
0f 97 c4 | seta ah
|
||||
0f 98 c3 | sets bl
|
||||
0f 98 44 be 10 | sets byte ptr [rsi + 4*rdi + 16]
|
||||
0f 98 c4 | sets ah
|
||||
0f 99 c3 | setns bl
|
||||
0f 99 44 be 10 | setns byte ptr [rsi + 4*rdi + 16]
|
||||
0f 99 c4 | setns ah
|
||||
0f 9a c3 | setp bl
|
||||
0f 9a 44 be 10 | setp byte ptr [rsi + 4*rdi + 16]
|
||||
0f 9a c4 | setp ah
|
||||
0f 9b c3 | setnp bl
|
||||
0f 9b 44 be 10 | setnp byte ptr [rsi + 4*rdi + 16]
|
||||
0f 9b c4 | setnp ah
|
||||
0f 9c c3 | setl bl
|
||||
0f 9c 44 be 10 | setl byte ptr [rsi + 4*rdi + 16]
|
||||
0f 9c c4 | setl ah
|
||||
0f 9d c3 | setge bl
|
||||
0f 9d 44 be 10 | setge byte ptr [rsi + 4*rdi + 16]
|
||||
0f 9d c4 | setge ah
|
||||
0f 9e c3 | setle bl
|
||||
0f 9e 44 be 10 | setle byte ptr [rsi + 4*rdi + 16]
|
||||
0f 9e c4 | setle ah
|
||||
0f 9f c3 | setg bl
|
||||
0f 9f 44 be 10 | setg byte ptr [rsi + 4*rdi + 16]
|
||||
0f 9f c4 | setg ah
|
||||
44 88 cb | mov bl, r9b
|
||||
44 8a 54 be 10 | mov r10b, byte ptr [rsi + 4*rdi + 16]
|
||||
88 54 be 10 | mov byte ptr [rsi + 4*rdi + 16], dl
|
||||
41 b6 5a | mov r14b, 0x5a
|
||||
c6 44 be 10 5a | mov byte ptr [rsi + 4*rdi + 16], 0x5a
|
||||
41 86 d9 | xchg bl, r9b
|
||||
86 54 be 10 | xchg byte ptr [rsi + 4*rdi + 16], dl
|
||||
66 44 89 cb | mov bx, r9w
|
||||
66 44 8b 54 be 10 | mov r10w, word ptr [rsi + 4*rdi + 16]
|
||||
66 89 54 be 10 | mov word ptr [rsi + 4*rdi + 16], dx
|
||||
66 41 be 5a 00 | mov r14w, 0x5a
|
||||
66 c7 44 be 10 5a 00 | mov word ptr [rsi + 4*rdi + 16], 0x5a
|
||||
66 41 87 d9 | xchg bx, r9w
|
||||
66 87 54 be 10 | xchg word ptr [rsi + 4*rdi + 16], dx
|
||||
44 89 cb | mov ebx, r9d
|
||||
44 8b 54 be 10 | mov r10d, dword ptr [rsi + 4*rdi + 16]
|
||||
89 54 be 10 | mov dword ptr [rsi + 4*rdi + 16], edx
|
||||
41 be 5a 00 00 00 | mov r14d, 0x5a
|
||||
c7 44 be 10 5a 00 00 00 | mov dword ptr [rsi + 4*rdi + 16], 0x5a
|
||||
41 87 d9 | xchg ebx, r9d
|
||||
87 54 be 10 | xchg dword ptr [rsi + 4*rdi + 16], edx
|
||||
4c 89 cb | mov rbx, r9
|
||||
4c 8b 54 be 10 | mov r10, qword ptr [rsi + 4*rdi + 16]
|
||||
48 89 54 be 10 | mov qword ptr [rsi + 4*rdi + 16], rdx
|
||||
49 c7 c6 5a 00 00 00 | mov r14, 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
|
||||
88 dc | mov ah, bl
|
||||
88 ea | mov dl, ch
|
||||
b7 21 | mov bh, 0x21
|
||||
86 e3 | xchg ah, bl
|
||||
40 88 fe | mov sil, dil
|
||||
49 bf 11 22 33 44 55 66 77 88 | movabs r15, 0x8877665544332211
|
||||
48 c7 c1 fe ff ff ff | mov rcx, -2
|
||||
0f cb | bswap ebx
|
||||
49 0f c9 | bswap r9
|
||||
66 98 | cbw
|
||||
98 | cwde
|
||||
48 98 | cdqe
|
||||
66 99 | cwd
|
||||
99 | cdq
|
||||
48 99 | cqo
|
||||
f8 | clc
|
||||
f9 | stc
|
||||
f5 | cmc
|
||||
90 | nop
|
||||
0f 1f 40 08 | nop dword ptr [rax + 8]
|
||||
f3 90 | pause
|
||||
41 51 | push r9
|
||||
53 | push rbx
|
||||
6a fb | push -5
|
||||
68 78 56 34 12 | push 0x12345678
|
||||
ff 74 be 10 | push qword ptr [rsi + 4*rdi + 16]
|
||||
5b | pop rbx
|
||||
41 5c | pop r12
|
||||
8f 44 be 10 | pop qword ptr [rsi + 4*rdi + 16]
|
||||
c9 | leave
|
||||
@@ -0,0 +1,374 @@
|
||||
66 41 0f 60 d9 | punpcklbw xmm3, xmm9
|
||||
66 44 0f 60 54 be 10 | punpcklbw xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f 60 d2 | punpcklbw xmm2, xmm2
|
||||
66 41 0f 61 d9 | punpcklwd xmm3, xmm9
|
||||
66 44 0f 61 54 be 10 | punpcklwd xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f 61 d2 | punpcklwd xmm2, xmm2
|
||||
66 41 0f 62 d9 | punpckldq xmm3, xmm9
|
||||
66 44 0f 62 54 be 10 | punpckldq xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f 62 d2 | punpckldq xmm2, xmm2
|
||||
66 41 0f 6c d9 | punpcklqdq xmm3, xmm9
|
||||
66 44 0f 6c 54 be 10 | punpcklqdq xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f 6c d2 | punpcklqdq xmm2, xmm2
|
||||
66 41 0f 68 d9 | punpckhbw xmm3, xmm9
|
||||
66 44 0f 68 54 be 10 | punpckhbw xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f 68 d2 | punpckhbw xmm2, xmm2
|
||||
66 41 0f 69 d9 | punpckhwd xmm3, xmm9
|
||||
66 44 0f 69 54 be 10 | punpckhwd xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f 69 d2 | punpckhwd xmm2, xmm2
|
||||
66 41 0f 6a d9 | punpckhdq xmm3, xmm9
|
||||
66 44 0f 6a 54 be 10 | punpckhdq xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f 6a d2 | punpckhdq xmm2, xmm2
|
||||
66 41 0f 6d d9 | punpckhqdq xmm3, xmm9
|
||||
66 44 0f 6d 54 be 10 | punpckhqdq xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f 6d d2 | punpckhqdq xmm2, xmm2
|
||||
66 41 0f 63 d9 | packsswb xmm3, xmm9
|
||||
66 44 0f 63 54 be 10 | packsswb xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f 63 d2 | packsswb xmm2, xmm2
|
||||
66 41 0f 6b d9 | packssdw xmm3, xmm9
|
||||
66 44 0f 6b 54 be 10 | packssdw xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f 6b d2 | packssdw xmm2, xmm2
|
||||
66 41 0f 67 d9 | packuswb xmm3, xmm9
|
||||
66 44 0f 67 54 be 10 | packuswb xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f 67 d2 | packuswb xmm2, xmm2
|
||||
66 41 0f 64 d9 | pcmpgtb xmm3, xmm9
|
||||
66 44 0f 64 54 be 10 | pcmpgtb xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f 64 d2 | pcmpgtb xmm2, xmm2
|
||||
66 41 0f 65 d9 | pcmpgtw xmm3, xmm9
|
||||
66 44 0f 65 54 be 10 | pcmpgtw xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f 65 d2 | pcmpgtw xmm2, xmm2
|
||||
66 41 0f 66 d9 | pcmpgtd xmm3, xmm9
|
||||
66 44 0f 66 54 be 10 | pcmpgtd xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f 66 d2 | pcmpgtd xmm2, xmm2
|
||||
66 41 0f 74 d9 | pcmpeqb xmm3, xmm9
|
||||
66 44 0f 74 54 be 10 | pcmpeqb xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f 74 d2 | pcmpeqb xmm2, xmm2
|
||||
66 41 0f 75 d9 | pcmpeqw xmm3, xmm9
|
||||
66 44 0f 75 54 be 10 | pcmpeqw xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f 75 d2 | pcmpeqw xmm2, xmm2
|
||||
66 41 0f 76 d9 | pcmpeqd xmm3, xmm9
|
||||
66 44 0f 76 54 be 10 | pcmpeqd xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f 76 d2 | pcmpeqd xmm2, xmm2
|
||||
66 41 0f fc d9 | paddb xmm3, xmm9
|
||||
66 44 0f fc 54 be 10 | paddb xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f fc d2 | paddb xmm2, xmm2
|
||||
66 41 0f fd d9 | paddw xmm3, xmm9
|
||||
66 44 0f fd 54 be 10 | paddw xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f fd d2 | paddw xmm2, xmm2
|
||||
66 41 0f fe d9 | paddd xmm3, xmm9
|
||||
66 44 0f fe 54 be 10 | paddd xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f fe d2 | paddd xmm2, xmm2
|
||||
66 41 0f d4 d9 | paddq xmm3, xmm9
|
||||
66 44 0f d4 54 be 10 | paddq xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f d4 d2 | paddq xmm2, xmm2
|
||||
66 41 0f f8 d9 | psubb xmm3, xmm9
|
||||
66 44 0f f8 54 be 10 | psubb xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f f8 d2 | psubb xmm2, xmm2
|
||||
66 41 0f f9 d9 | psubw xmm3, xmm9
|
||||
66 44 0f f9 54 be 10 | psubw xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f f9 d2 | psubw xmm2, xmm2
|
||||
66 41 0f fa d9 | psubd xmm3, xmm9
|
||||
66 44 0f fa 54 be 10 | psubd xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f fa d2 | psubd xmm2, xmm2
|
||||
66 41 0f fb d9 | psubq xmm3, xmm9
|
||||
66 44 0f fb 54 be 10 | psubq xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f fb d2 | psubq xmm2, xmm2
|
||||
66 41 0f ec d9 | paddsb xmm3, xmm9
|
||||
66 44 0f ec 54 be 10 | paddsb xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f ec d2 | paddsb xmm2, xmm2
|
||||
66 41 0f ed d9 | paddsw xmm3, xmm9
|
||||
66 44 0f ed 54 be 10 | paddsw xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f ed d2 | paddsw xmm2, xmm2
|
||||
66 41 0f dc d9 | paddusb xmm3, xmm9
|
||||
66 44 0f dc 54 be 10 | paddusb xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f dc d2 | paddusb xmm2, xmm2
|
||||
66 41 0f dd d9 | paddusw xmm3, xmm9
|
||||
66 44 0f dd 54 be 10 | paddusw xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f dd d2 | paddusw xmm2, xmm2
|
||||
66 41 0f e8 d9 | psubsb xmm3, xmm9
|
||||
66 44 0f e8 54 be 10 | psubsb xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f e8 d2 | psubsb xmm2, xmm2
|
||||
66 41 0f e9 d9 | psubsw xmm3, xmm9
|
||||
66 44 0f e9 54 be 10 | psubsw xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f e9 d2 | psubsw xmm2, xmm2
|
||||
66 41 0f d8 d9 | psubusb xmm3, xmm9
|
||||
66 44 0f d8 54 be 10 | psubusb xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f d8 d2 | psubusb xmm2, xmm2
|
||||
66 41 0f d9 d9 | psubusw xmm3, xmm9
|
||||
66 44 0f d9 54 be 10 | psubusw xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f d9 d2 | psubusw xmm2, xmm2
|
||||
66 41 0f d5 d9 | pmullw xmm3, xmm9
|
||||
66 44 0f d5 54 be 10 | pmullw xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f d5 d2 | pmullw xmm2, xmm2
|
||||
66 41 0f e5 d9 | pmulhw xmm3, xmm9
|
||||
66 44 0f e5 54 be 10 | pmulhw xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f e5 d2 | pmulhw xmm2, xmm2
|
||||
66 41 0f e4 d9 | pmulhuw xmm3, xmm9
|
||||
66 44 0f e4 54 be 10 | pmulhuw xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f e4 d2 | pmulhuw xmm2, xmm2
|
||||
66 41 0f f4 d9 | pmuludq xmm3, xmm9
|
||||
66 44 0f f4 54 be 10 | pmuludq xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f f4 d2 | pmuludq xmm2, xmm2
|
||||
66 41 0f f5 d9 | pmaddwd xmm3, xmm9
|
||||
66 44 0f f5 54 be 10 | pmaddwd xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f f5 d2 | pmaddwd xmm2, xmm2
|
||||
66 41 0f f6 d9 | psadbw xmm3, xmm9
|
||||
66 44 0f f6 54 be 10 | psadbw xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f f6 d2 | psadbw xmm2, xmm2
|
||||
66 41 0f e0 d9 | pavgb xmm3, xmm9
|
||||
66 44 0f e0 54 be 10 | pavgb xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f e0 d2 | pavgb xmm2, xmm2
|
||||
66 41 0f e3 d9 | pavgw xmm3, xmm9
|
||||
66 44 0f e3 54 be 10 | pavgw xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f e3 d2 | pavgw xmm2, xmm2
|
||||
66 41 0f da d9 | pminub xmm3, xmm9
|
||||
66 44 0f da 54 be 10 | pminub xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f da d2 | pminub xmm2, xmm2
|
||||
66 41 0f de d9 | pmaxub xmm3, xmm9
|
||||
66 44 0f de 54 be 10 | pmaxub xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f de d2 | pmaxub xmm2, xmm2
|
||||
66 41 0f ea d9 | pminsw xmm3, xmm9
|
||||
66 44 0f ea 54 be 10 | pminsw xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f ea d2 | pminsw xmm2, xmm2
|
||||
66 41 0f ee d9 | pmaxsw xmm3, xmm9
|
||||
66 44 0f ee 54 be 10 | pmaxsw xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f ee d2 | pmaxsw xmm2, xmm2
|
||||
66 41 0f db d9 | pand xmm3, xmm9
|
||||
66 44 0f db 54 be 10 | pand xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f db d2 | pand xmm2, xmm2
|
||||
66 41 0f df d9 | pandn xmm3, xmm9
|
||||
66 44 0f df 54 be 10 | pandn xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f df d2 | pandn xmm2, xmm2
|
||||
66 41 0f eb d9 | por xmm3, xmm9
|
||||
66 44 0f eb 54 be 10 | por xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f eb d2 | por xmm2, xmm2
|
||||
66 41 0f ef d9 | pxor xmm3, xmm9
|
||||
66 44 0f ef 54 be 10 | pxor xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f ef d2 | pxor xmm2, xmm2
|
||||
41 0f 54 d9 | andps xmm3, xmm9
|
||||
44 0f 54 54 be 10 | andps xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
0f 54 d2 | andps xmm2, xmm2
|
||||
66 41 0f 54 d9 | andpd xmm3, xmm9
|
||||
66 44 0f 54 54 be 10 | andpd xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f 54 d2 | andpd xmm2, xmm2
|
||||
41 0f 55 d9 | andnps xmm3, xmm9
|
||||
44 0f 55 54 be 10 | andnps xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
0f 55 d2 | andnps xmm2, xmm2
|
||||
66 41 0f 55 d9 | andnpd xmm3, xmm9
|
||||
66 44 0f 55 54 be 10 | andnpd xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f 55 d2 | andnpd xmm2, xmm2
|
||||
41 0f 56 d9 | orps xmm3, xmm9
|
||||
44 0f 56 54 be 10 | orps xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
0f 56 d2 | orps xmm2, xmm2
|
||||
66 41 0f 56 d9 | orpd xmm3, xmm9
|
||||
66 44 0f 56 54 be 10 | orpd xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f 56 d2 | orpd xmm2, xmm2
|
||||
41 0f 57 d9 | xorps xmm3, xmm9
|
||||
44 0f 57 54 be 10 | xorps xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
0f 57 d2 | xorps xmm2, xmm2
|
||||
66 41 0f 57 d9 | xorpd xmm3, xmm9
|
||||
66 44 0f 57 54 be 10 | xorpd xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f 57 d2 | xorpd xmm2, xmm2
|
||||
41 0f 14 d9 | unpcklps xmm3, xmm9
|
||||
44 0f 14 54 be 10 | unpcklps xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
0f 14 d2 | unpcklps xmm2, xmm2
|
||||
66 41 0f 14 d9 | unpcklpd xmm3, xmm9
|
||||
66 44 0f 14 54 be 10 | unpcklpd xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f 14 d2 | unpcklpd xmm2, xmm2
|
||||
41 0f 15 d9 | unpckhps xmm3, xmm9
|
||||
44 0f 15 54 be 10 | unpckhps xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
0f 15 d2 | unpckhps xmm2, xmm2
|
||||
66 41 0f 15 d9 | unpckhpd xmm3, xmm9
|
||||
66 44 0f 15 54 be 10 | unpckhpd xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f 15 d2 | unpckhpd xmm2, xmm2
|
||||
66 41 0f f1 d9 | psllw xmm3, xmm9
|
||||
66 44 0f f1 54 be 10 | psllw xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f f1 d2 | psllw xmm2, xmm2
|
||||
66 41 0f f2 d9 | pslld xmm3, xmm9
|
||||
66 44 0f f2 54 be 10 | pslld xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f f2 d2 | pslld xmm2, xmm2
|
||||
66 41 0f f3 d9 | psllq xmm3, xmm9
|
||||
66 44 0f f3 54 be 10 | psllq xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f f3 d2 | psllq xmm2, xmm2
|
||||
66 41 0f d1 d9 | psrlw xmm3, xmm9
|
||||
66 44 0f d1 54 be 10 | psrlw xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f d1 d2 | psrlw xmm2, xmm2
|
||||
66 41 0f d2 d9 | psrld xmm3, xmm9
|
||||
66 44 0f d2 54 be 10 | psrld xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f d2 d2 | psrld xmm2, xmm2
|
||||
66 41 0f d3 d9 | psrlq xmm3, xmm9
|
||||
66 44 0f d3 54 be 10 | psrlq xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f d3 d2 | psrlq xmm2, xmm2
|
||||
66 41 0f e1 d9 | psraw xmm3, xmm9
|
||||
66 44 0f e1 54 be 10 | psraw xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f e1 d2 | psraw xmm2, xmm2
|
||||
66 41 0f e2 d9 | psrad xmm3, xmm9
|
||||
66 44 0f e2 54 be 10 | psrad xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f e2 d2 | psrad xmm2, xmm2
|
||||
41 0f 28 d9 | movaps xmm3, xmm9
|
||||
44 0f 28 54 be 10 | movaps xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
0f 28 d2 | movaps xmm2, xmm2
|
||||
66 41 0f 28 d9 | movapd xmm3, xmm9
|
||||
66 44 0f 28 54 be 10 | movapd xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f 28 d2 | movapd xmm2, xmm2
|
||||
41 0f 10 d9 | movups xmm3, xmm9
|
||||
44 0f 10 54 be 10 | movups xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
0f 10 d2 | movups xmm2, xmm2
|
||||
66 41 0f 10 d9 | movupd xmm3, xmm9
|
||||
66 44 0f 10 54 be 10 | movupd xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f 10 d2 | movupd xmm2, xmm2
|
||||
66 41 0f 6f d9 | movdqa xmm3, xmm9
|
||||
66 44 0f 6f 54 be 10 | movdqa xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
66 0f 6f d2 | movdqa xmm2, xmm2
|
||||
f3 41 0f 6f d9 | movdqu xmm3, xmm9
|
||||
f3 44 0f 6f 54 be 10 | movdqu xmm10, xmmword ptr [rsi + 4*rdi + 16]
|
||||
f3 0f 6f d2 | movdqu xmm2, xmm2
|
||||
44 0f 29 5c be 10 | movaps xmmword ptr [rsi + 4*rdi + 16], xmm11
|
||||
66 44 0f 29 5c be 10 | movapd xmmword ptr [rsi + 4*rdi + 16], xmm11
|
||||
44 0f 11 5c be 10 | movups xmmword ptr [rsi + 4*rdi + 16], xmm11
|
||||
66 44 0f 11 5c be 10 | movupd xmmword ptr [rsi + 4*rdi + 16], xmm11
|
||||
66 44 0f 7f 5c be 10 | movdqa xmmword ptr [rsi + 4*rdi + 16], xmm11
|
||||
f3 44 0f 7f 5c be 10 | movdqu xmmword ptr [rsi + 4*rdi + 16], xmm11
|
||||
66 44 0f e7 5c be 10 | movntdq xmmword ptr [rsi + 4*rdi + 16], xmm11
|
||||
44 0f 2b 5c be 10 | movntps xmmword ptr [rsi + 4*rdi + 16], xmm11
|
||||
66 44 0f 2b 5c be 10 | movntpd xmmword ptr [rsi + 4*rdi + 16], xmm11
|
||||
f3 41 0f 10 d9 | movss xmm3, xmm9
|
||||
f3 44 0f 10 54 be 10 | movss xmm10, dword ptr [rsi + 4*rdi + 16]
|
||||
f3 44 0f 11 5c be 10 | movss dword ptr [rsi + 4*rdi + 16], xmm11
|
||||
f2 41 0f 10 d9 | movsd xmm3, xmm9
|
||||
f2 44 0f 10 54 be 10 | movsd xmm10, qword ptr [rsi + 4*rdi + 16]
|
||||
f2 44 0f 11 5c be 10 | movsd qword ptr [rsi + 4*rdi + 16], xmm11
|
||||
f3 41 0f 7e d9 | movq xmm3, xmm9
|
||||
f3 44 0f 7e 54 be 10 | movq xmm10, qword ptr [rsi + 4*rdi + 16]
|
||||
66 44 0f d6 5c be 10 | movq qword ptr [rsi + 4*rdi + 16], xmm11
|
||||
0f 12 5c be 10 | movlps xmm3, qword ptr [rsi + 4*rdi + 16]
|
||||
44 0f 13 4c be 10 | movlps qword ptr [rsi + 4*rdi + 16], xmm9
|
||||
66 0f 12 5c be 10 | movlpd xmm3, qword ptr [rsi + 4*rdi + 16]
|
||||
66 44 0f 13 4c be 10 | movlpd qword ptr [rsi + 4*rdi + 16], xmm9
|
||||
0f 16 5c be 10 | movhps xmm3, qword ptr [rsi + 4*rdi + 16]
|
||||
44 0f 17 4c be 10 | movhps qword ptr [rsi + 4*rdi + 16], xmm9
|
||||
66 0f 16 5c be 10 | movhpd xmm3, qword ptr [rsi + 4*rdi + 16]
|
||||
66 44 0f 17 4c be 10 | movhpd qword ptr [rsi + 4*rdi + 16], xmm9
|
||||
41 0f 12 d9 | movhlps xmm3, xmm9
|
||||
44 0f 16 d1 | movlhps xmm10, xmm1
|
||||
0f 12 d2 | movhlps xmm2, xmm2
|
||||
0f 16 d2 | movlhps xmm2, xmm2
|
||||
66 41 0f 6e d9 | movd xmm3, r9d
|
||||
66 44 0f 6e e0 | movd xmm12, eax
|
||||
66 49 0f 6e d9 | movq xmm3, r9
|
||||
66 41 0f 7e d9 | movd r9d, xmm3
|
||||
66 44 0f 7e e3 | movd ebx, xmm12
|
||||
66 49 0f 7e d9 | movq r9, xmm3
|
||||
66 0f 6e 5c be 10 | movd xmm3, dword ptr [rsi + 4*rdi + 16]
|
||||
66 44 0f 7e 4c be 10 | movd dword ptr [rsi + 4*rdi + 16], xmm9
|
||||
41 0f 50 d9 | movmskps ebx, xmm9
|
||||
44 0f 50 d3 | movmskps r10d, xmm3
|
||||
66 41 0f 50 d9 | movmskpd ebx, xmm9
|
||||
66 44 0f 50 d3 | movmskpd r10d, xmm3
|
||||
66 41 0f d7 d9 | pmovmskb ebx, xmm9
|
||||
66 44 0f d7 d3 | pmovmskb r10d, xmm3
|
||||
66 0f 71 f3 00 | psllw xmm3, 0
|
||||
66 41 0f 71 f1 01 | psllw xmm9, 1
|
||||
66 41 0f 71 f1 07 | psllw xmm9, 7
|
||||
66 41 0f 71 f1 0f | psllw xmm9, 15
|
||||
66 0f 71 f3 10 | psllw xmm3, 16
|
||||
66 41 0f 71 f1 ff | psllw xmm9, 255
|
||||
66 0f 71 d3 00 | psrlw xmm3, 0
|
||||
66 41 0f 71 d1 01 | psrlw xmm9, 1
|
||||
66 41 0f 71 d1 07 | psrlw xmm9, 7
|
||||
66 41 0f 71 d1 0f | psrlw xmm9, 15
|
||||
66 0f 71 d3 10 | psrlw xmm3, 16
|
||||
66 41 0f 71 d1 ff | psrlw xmm9, 255
|
||||
66 0f 71 e3 00 | psraw xmm3, 0
|
||||
66 41 0f 71 e1 01 | psraw xmm9, 1
|
||||
66 41 0f 71 e1 07 | psraw xmm9, 7
|
||||
66 41 0f 71 e1 0f | psraw xmm9, 15
|
||||
66 0f 71 e3 10 | psraw xmm3, 16
|
||||
66 41 0f 71 e1 ff | psraw xmm9, 255
|
||||
66 0f 72 f3 00 | pslld xmm3, 0
|
||||
66 41 0f 72 f1 01 | pslld xmm9, 1
|
||||
66 41 0f 72 f1 07 | pslld xmm9, 7
|
||||
66 41 0f 72 f1 1f | pslld xmm9, 31
|
||||
66 0f 72 f3 20 | pslld xmm3, 32
|
||||
66 41 0f 72 f1 ff | pslld xmm9, 255
|
||||
66 0f 72 d3 00 | psrld xmm3, 0
|
||||
66 41 0f 72 d1 01 | psrld xmm9, 1
|
||||
66 41 0f 72 d1 07 | psrld xmm9, 7
|
||||
66 41 0f 72 d1 1f | psrld xmm9, 31
|
||||
66 0f 72 d3 20 | psrld xmm3, 32
|
||||
66 41 0f 72 d1 ff | psrld xmm9, 255
|
||||
66 0f 72 e3 00 | psrad xmm3, 0
|
||||
66 41 0f 72 e1 01 | psrad xmm9, 1
|
||||
66 41 0f 72 e1 07 | psrad xmm9, 7
|
||||
66 41 0f 72 e1 1f | psrad xmm9, 31
|
||||
66 0f 72 e3 20 | psrad xmm3, 32
|
||||
66 41 0f 72 e1 ff | psrad xmm9, 255
|
||||
66 0f 73 f3 00 | psllq xmm3, 0
|
||||
66 41 0f 73 f1 01 | psllq xmm9, 1
|
||||
66 41 0f 73 f1 07 | psllq xmm9, 7
|
||||
66 41 0f 73 f1 3f | psllq xmm9, 63
|
||||
66 0f 73 f3 40 | psllq xmm3, 64
|
||||
66 41 0f 73 f1 ff | psllq xmm9, 255
|
||||
66 0f 73 d3 00 | psrlq xmm3, 0
|
||||
66 41 0f 73 d1 01 | psrlq xmm9, 1
|
||||
66 41 0f 73 d1 07 | psrlq xmm9, 7
|
||||
66 41 0f 73 d1 3f | psrlq xmm9, 63
|
||||
66 0f 73 d3 40 | psrlq xmm3, 64
|
||||
66 41 0f 73 d1 ff | psrlq xmm9, 255
|
||||
66 41 0f 73 f9 00 | pslldq xmm9, 0
|
||||
66 41 0f 73 f9 01 | pslldq xmm9, 1
|
||||
66 41 0f 73 f9 05 | pslldq xmm9, 5
|
||||
66 41 0f 73 f9 0f | pslldq xmm9, 15
|
||||
66 41 0f 73 f9 10 | pslldq xmm9, 16
|
||||
66 41 0f 73 f9 ff | pslldq xmm9, 255
|
||||
66 41 0f 73 d9 00 | psrldq xmm9, 0
|
||||
66 41 0f 73 d9 01 | psrldq xmm9, 1
|
||||
66 41 0f 73 d9 05 | psrldq xmm9, 5
|
||||
66 41 0f 73 d9 0f | psrldq xmm9, 15
|
||||
66 41 0f 73 d9 10 | psrldq xmm9, 16
|
||||
66 41 0f 73 d9 ff | psrldq xmm9, 255
|
||||
66 41 0f 70 d9 00 | pshufd xmm3, xmm9, 0
|
||||
66 41 0f 70 d9 1b | pshufd xmm3, xmm9, 27
|
||||
66 41 0f 70 d9 4e | pshufd xmm3, xmm9, 78
|
||||
66 41 0f 70 d9 b1 | pshufd xmm3, xmm9, 177
|
||||
66 41 0f 70 d9 ff | pshufd xmm3, xmm9, 255
|
||||
66 44 0f 70 54 be 10 72 | pshufd xmm10, xmmword ptr [rsi + 4*rdi + 16], 114
|
||||
66 0f 70 d2 39 | pshufd xmm2, xmm2, 57
|
||||
f3 41 0f 70 d9 00 | pshufhw xmm3, xmm9, 0
|
||||
f3 41 0f 70 d9 1b | pshufhw xmm3, xmm9, 27
|
||||
f3 41 0f 70 d9 4e | pshufhw xmm3, xmm9, 78
|
||||
f3 41 0f 70 d9 b1 | pshufhw xmm3, xmm9, 177
|
||||
f3 41 0f 70 d9 ff | pshufhw xmm3, xmm9, 255
|
||||
f3 44 0f 70 54 be 10 72 | pshufhw xmm10, xmmword ptr [rsi + 4*rdi + 16], 114
|
||||
f3 0f 70 d2 39 | pshufhw xmm2, xmm2, 57
|
||||
f2 41 0f 70 d9 00 | pshuflw xmm3, xmm9, 0
|
||||
f2 41 0f 70 d9 1b | pshuflw xmm3, xmm9, 27
|
||||
f2 41 0f 70 d9 4e | pshuflw xmm3, xmm9, 78
|
||||
f2 41 0f 70 d9 b1 | pshuflw xmm3, xmm9, 177
|
||||
f2 41 0f 70 d9 ff | pshuflw xmm3, xmm9, 255
|
||||
f2 44 0f 70 54 be 10 72 | pshuflw xmm10, xmmword ptr [rsi + 4*rdi + 16], 114
|
||||
f2 0f 70 d2 39 | pshuflw xmm2, xmm2, 57
|
||||
41 0f c6 d9 00 | shufps xmm3, xmm9, 0
|
||||
41 0f c6 d9 1b | shufps xmm3, xmm9, 27
|
||||
41 0f c6 d9 4e | shufps xmm3, xmm9, 78
|
||||
41 0f c6 d9 b1 | shufps xmm3, xmm9, 177
|
||||
41 0f c6 d9 ff | shufps xmm3, xmm9, 255
|
||||
44 0f c6 54 be 10 72 | shufps xmm10, xmmword ptr [rsi + 4*rdi + 16], 114
|
||||
0f c6 d2 39 | shufps xmm2, xmm2, 57
|
||||
66 41 0f c6 d9 00 | shufpd xmm3, xmm9, 0
|
||||
66 41 0f c6 d9 1b | shufpd xmm3, xmm9, 27
|
||||
66 41 0f c6 d9 4e | shufpd xmm3, xmm9, 78
|
||||
66 41 0f c6 d9 b1 | shufpd xmm3, xmm9, 177
|
||||
66 41 0f c6 d9 ff | shufpd xmm3, xmm9, 255
|
||||
66 44 0f c6 54 be 10 72 | shufpd xmm10, xmmword ptr [rsi + 4*rdi + 16], 114
|
||||
66 0f c6 d2 39 | shufpd xmm2, xmm2, 57
|
||||
66 44 0f c4 cb 00 | pinsrw xmm9, ebx, 0
|
||||
66 0f c4 5c be 10 00 | pinsrw xmm3, word ptr [rsi + 4*rdi + 16], 0
|
||||
66 44 0f c5 cb 00 | pextrw r9d, xmm3, 0
|
||||
66 44 0f c4 cb 03 | pinsrw xmm9, ebx, 3
|
||||
66 0f c4 5c be 10 03 | pinsrw xmm3, word ptr [rsi + 4*rdi + 16], 3
|
||||
66 44 0f c5 cb 03 | pextrw r9d, xmm3, 3
|
||||
66 44 0f c4 cb 07 | pinsrw xmm9, ebx, 7
|
||||
66 0f c4 5c be 10 07 | pinsrw xmm3, word ptr [rsi + 4*rdi + 16], 7
|
||||
66 44 0f c5 cb 07 | pextrw r9d, xmm3, 7
|
||||
0f ae 5c be 10 | stmxcsr dword ptr [rsi + 4*rdi + 16]
|
||||
@@ -0,0 +1,611 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! SSE and SSE2 floating-point tests.
|
||||
//!
|
||||
//! Expected values come from `tests/x86/float_vectors.txt`, computed with exact
|
||||
//! fractions by `tests/x86/float_reference.py` from the Intel SDM rules, and, for
|
||||
//! round-to-nearest values, from the ARM64 host's IEEE 754 hardware. Encodings
|
||||
//! come from LLVM (`tests/x86/float.txt`). Neither shares code with
|
||||
//! `softfloat.rs`.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use xenora_loader::cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, Mxcsr, RFlags};
|
||||
use xenora_loader::dbt::DbtEngine;
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
use xenora_loader::softfloat::{self, Arithmetic, Control, F32, F64, Format};
|
||||
|
||||
const ENTRY: u64 = 0x1000;
|
||||
const DATA: u64 = 0x2000;
|
||||
/// Address of `[rsi + 4*rdi + 16]` with RSI = DATA and RDI = 4.
|
||||
const OPERAND: u64 = DATA + 32;
|
||||
const FILLER: u128 = 0x1122_3344_5566_7788_99AA_BBCC_DDEE_FF00;
|
||||
|
||||
fn fixture() -> BTreeMap<&'static str, Vec<u8>> {
|
||||
include_str!("x86/float.txt")
|
||||
.lines()
|
||||
.map(|line| {
|
||||
let (hex, text) = line.split_once(" | ").unwrap();
|
||||
let code = hex
|
||||
.split(' ')
|
||||
.map(|b| u8::from_str_radix(b, 16).unwrap())
|
||||
.collect();
|
||||
(text, code)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct Vector {
|
||||
name: &'static str,
|
||||
mxcsr: u32,
|
||||
a: u64,
|
||||
b: u64,
|
||||
result: u64,
|
||||
flags: u32,
|
||||
}
|
||||
|
||||
fn vectors() -> Vec<Vector> {
|
||||
include_str!("x86/float_vectors.txt")
|
||||
.lines()
|
||||
.map(|line| {
|
||||
let parts: Vec<&str> = line.split(' ').collect();
|
||||
let hex = |index: usize| u64::from_str_radix(parts[index], 16).unwrap();
|
||||
Vector {
|
||||
name: parts[0],
|
||||
mxcsr: hex(1) as u32,
|
||||
a: hex(2),
|
||||
b: hex(3),
|
||||
result: hex(4),
|
||||
flags: hex(5) as u32,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Where an operation's result goes and how wide its operands are.
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
|
||||
enum Kind {
|
||||
/// Lane 0 of XMM3, keeping the rest.
|
||||
Scalar {
|
||||
source: u32,
|
||||
result: u32,
|
||||
},
|
||||
/// R9 from XMM9.
|
||||
ToGeneral {
|
||||
source: u32,
|
||||
},
|
||||
/// Lane 0 of XMM3 from R9.
|
||||
FromGeneral {
|
||||
source: u32,
|
||||
result: u32,
|
||||
},
|
||||
Flags {
|
||||
source: u32,
|
||||
},
|
||||
}
|
||||
|
||||
fn width(text: &str) -> u32 {
|
||||
if text.contains("ss") { 32 } else { 64 }
|
||||
}
|
||||
|
||||
/// Instruction text for the register form, and the kind, of a vector's name.
|
||||
fn instruction(name: &str) -> (String, Kind) {
|
||||
if name == "cvtss2sd" || name == "cvtsd2ss" {
|
||||
let source = if name == "cvtss2sd" { 32 } else { 64 };
|
||||
return (
|
||||
format!("{name} xmm3, xmm9"),
|
||||
Kind::Scalar {
|
||||
source,
|
||||
result: 96 - source,
|
||||
},
|
||||
);
|
||||
}
|
||||
if let Some(rest) = name.strip_prefix("cvtsi2") {
|
||||
let (format, size) = rest.split_at(2);
|
||||
let register = if size == "d" { "r9d" } else { "r9" };
|
||||
let source = if size == "d" { 32 } else { 64 };
|
||||
let text = format!("cvtsi2{format} xmm3, {register}");
|
||||
return (
|
||||
text,
|
||||
Kind::FromGeneral {
|
||||
source,
|
||||
result: width(format),
|
||||
},
|
||||
);
|
||||
}
|
||||
if name.contains("2si") {
|
||||
let (stem, size) = name.split_at(name.len() - 1);
|
||||
let register = if size == "d" { "r9d" } else { "r9" };
|
||||
let source = if stem.contains("ss2") { 32 } else { 64 };
|
||||
return (
|
||||
format!("{stem} {register}, xmm9"),
|
||||
Kind::ToGeneral { source },
|
||||
);
|
||||
}
|
||||
if name.contains("comi") {
|
||||
let source = if name.ends_with("ss") { 32 } else { 64 };
|
||||
return (format!("{name} xmm3, xmm9"), Kind::Flags { source });
|
||||
}
|
||||
if let Some(rest) = name.strip_prefix("cmp") {
|
||||
let (format, code) = rest.split_at(2);
|
||||
let bits = if format == "ss" { 32 } else { 64 };
|
||||
return (
|
||||
format!("cmp{format} xmm3, xmm9, {code}"),
|
||||
Kind::Scalar {
|
||||
source: bits,
|
||||
result: bits,
|
||||
},
|
||||
);
|
||||
}
|
||||
let bits = if name.ends_with("ss") { 32 } else { 64 };
|
||||
(
|
||||
format!("{name} xmm3, xmm9"),
|
||||
Kind::Scalar {
|
||||
source: bits,
|
||||
result: bits,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Memory-source text of a register form.
|
||||
fn memory_text(text: &str, kind: Kind) -> String {
|
||||
let source = match kind {
|
||||
Kind::Scalar { source, .. }
|
||||
| Kind::ToGeneral { source }
|
||||
| Kind::FromGeneral { source, .. }
|
||||
| Kind::Flags { source } => source,
|
||||
};
|
||||
let place = format!(
|
||||
"{} ptr [rsi + 4*rdi + 16]",
|
||||
if source == 32 { "dword" } else { "qword" }
|
||||
);
|
||||
let operand = match kind {
|
||||
Kind::FromGeneral { .. } => text.rsplit(", ").next().unwrap(),
|
||||
_ => "xmm9",
|
||||
};
|
||||
let (head, tail) = text.rsplit_once(operand).unwrap();
|
||||
format!("{head}{place}{tail}")
|
||||
}
|
||||
|
||||
fn merge(old: u128, value: u64, bits: u32, index: u32) -> u128 {
|
||||
let modulus = 1u128 << bits;
|
||||
let shift = bits * index;
|
||||
let below = old & ((1u128 << shift) - 1);
|
||||
let above = old.checked_shr(shift + bits).unwrap_or(0);
|
||||
let above = above.checked_shl(shift + bits).unwrap_or(0);
|
||||
below | ((u128::from(value) % modulus) << shift) | above
|
||||
}
|
||||
|
||||
fn load(code: &[u8], mxcsr: u32, a: u128, b: u128, r9: u64) -> (CpuState, GuestMemory) {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, code)
|
||||
.unwrap();
|
||||
memory
|
||||
.map_region(DATA, 0x100, MemoryPermissions::READ_WRITE)
|
||||
.unwrap();
|
||||
memory.write_bytes(OPERAND, &b.to_le_bytes()).unwrap();
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr[6] = DATA;
|
||||
cpu.gpr[7] = 4;
|
||||
cpu.gpr[9] = r9;
|
||||
cpu.xmm = [FILLER; 16];
|
||||
cpu.xmm[3] = a;
|
||||
cpu.xmm[9] = b;
|
||||
cpu.mxcsr = Mxcsr(mxcsr);
|
||||
cpu.flags = RFlags {
|
||||
cf: true,
|
||||
zf: false,
|
||||
sf: true,
|
||||
of: true,
|
||||
pf: false,
|
||||
af: true,
|
||||
};
|
||||
(cpu, memory)
|
||||
}
|
||||
|
||||
fn run(native: bool, cpu: &CpuState, memory: &mut GuestMemory, budget: usize) -> ExecutionResult {
|
||||
if native {
|
||||
DbtEngine::new(64 * 1024)
|
||||
.unwrap()
|
||||
.run(&mut cpu.clone(), memory, budget)
|
||||
} else {
|
||||
Interpreter::new(cpu.clone(), memory, budget).run()
|
||||
}
|
||||
}
|
||||
|
||||
/// Initial XMM3, source operand and R9 of a vector, with unrelated upper bits.
|
||||
fn inputs(vector: &Vector, kind: Kind) -> (u128, u128, u64) {
|
||||
match kind {
|
||||
Kind::Scalar { source, .. } | Kind::Flags { source } => (
|
||||
merge(FILLER, vector.a, source, 0),
|
||||
merge(!FILLER, vector.b, source, 0),
|
||||
0,
|
||||
),
|
||||
Kind::ToGeneral { source } => (FILLER, merge(!FILLER, vector.b, source, 0), u64::MAX),
|
||||
Kind::FromGeneral { source, .. } => {
|
||||
let upper = if source == 32 {
|
||||
0xABCD_EF01_0000_0000
|
||||
} else {
|
||||
0
|
||||
};
|
||||
// The memory form reads the same value from the operand.
|
||||
(FILLER, u128::from(vector.b), vector.b | upper)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn expect(before: &CpuState, vector: &Vector, kind: Kind, length: usize) -> CpuState {
|
||||
let mut after = before.clone();
|
||||
after.rip = ENTRY + length as u64;
|
||||
after.mxcsr = Mxcsr(before.mxcsr.0 | vector.flags);
|
||||
match kind {
|
||||
Kind::Scalar { result, .. } | Kind::FromGeneral { result, .. } => {
|
||||
after.xmm[3] = merge(before.xmm[3], vector.result, result, 0);
|
||||
}
|
||||
Kind::ToGeneral { .. } => after.gpr[9] = vector.result,
|
||||
Kind::Flags { .. } => {
|
||||
after.flags = RFlags {
|
||||
zf: vector.result & 4 != 0,
|
||||
pf: vector.result & 2 != 0,
|
||||
cf: vector.result & 1 != 0,
|
||||
..RFlags::default()
|
||||
};
|
||||
}
|
||||
}
|
||||
after
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_vectors_match_in_both_engines_from_registers_and_memory() {
|
||||
let code = fixture();
|
||||
let all = vectors();
|
||||
assert!(all.len() > 5000);
|
||||
for vector in &all {
|
||||
let (text, kind) = instruction(vector.name);
|
||||
let (a, b, r9) = inputs(vector, kind);
|
||||
for text in [text.clone(), memory_text(&text, kind)] {
|
||||
let code = code.get(text.as_str()).unwrap_or_else(|| panic!("{text}"));
|
||||
for native in [false, true] {
|
||||
let (cpu, mut memory) = load(code, vector.mxcsr, a, b, r9);
|
||||
let result = run(native, &cpu, &mut memory, 1);
|
||||
let wanted = expect(&cpu, vector, kind, code.len());
|
||||
assert_eq!(
|
||||
result.exit_reason,
|
||||
ExitReason::StepLimitExceeded,
|
||||
"{text} {vector:x?}"
|
||||
);
|
||||
assert_eq!(result.final_state, wanted, "{text} {vector:x?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sticky_flags_accumulate_and_are_never_cleared() {
|
||||
let code = fixture();
|
||||
for vector in vectors().iter().step_by(7) {
|
||||
let (text, kind) = instruction(vector.name);
|
||||
let (a, b, r9) = inputs(vector, kind);
|
||||
let code = &code[text.as_str()];
|
||||
let (cpu, mut memory) = load(code, vector.mxcsr | 0x2A, a, b, r9);
|
||||
let result = run(true, &cpu, &mut memory, 1);
|
||||
assert_eq!(
|
||||
result.final_state,
|
||||
expect(&cpu, vector, kind, code.len()),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packed_forms_apply_the_scalar_rules_to_every_lane() {
|
||||
let code = fixture();
|
||||
// Vectors of one operation and MXCSR, taken a register at a time.
|
||||
let mut groups: BTreeMap<(&str, u32), Vec<Vector>> = BTreeMap::new();
|
||||
for vector in vectors() {
|
||||
groups
|
||||
.entry((vector.name, vector.mxcsr))
|
||||
.or_default()
|
||||
.push(vector);
|
||||
}
|
||||
let mut checked = 0;
|
||||
for ((name, mxcsr), group) in groups {
|
||||
// (packed text, source width, result width, lanes, upper half zeroed)
|
||||
let packed = match name {
|
||||
"cvtss2sd" => ("cvtps2pd xmm3, xmm9".to_string(), 32, 64, 2),
|
||||
"cvtsd2ss" => ("cvtpd2ps xmm3, xmm9".to_string(), 64, 32, 2),
|
||||
"cvtss2sid" => ("cvtps2dq xmm3, xmm9".to_string(), 32, 32, 4),
|
||||
"cvttss2sid" => ("cvttps2dq xmm3, xmm9".to_string(), 32, 32, 4),
|
||||
"cvtsd2sid" => ("cvtpd2dq xmm3, xmm9".to_string(), 64, 32, 2),
|
||||
"cvttsd2sid" => ("cvttpd2dq xmm3, xmm9".to_string(), 64, 32, 2),
|
||||
"cvtsi2ssd" => ("cvtdq2ps xmm3, xmm9".to_string(), 32, 32, 4),
|
||||
"cvtsi2sdd" => ("cvtdq2pd xmm3, xmm9".to_string(), 32, 64, 2),
|
||||
_ if name.contains("comi") || name.contains("cvt") => continue,
|
||||
_ => {
|
||||
let (text, _) = instruction(name);
|
||||
let bits = if name.contains("ss") && !name.starts_with("cmpsd") {
|
||||
32
|
||||
} else {
|
||||
64
|
||||
};
|
||||
let text = if bits == 32 {
|
||||
text.replacen("ss ", "ps ", 1)
|
||||
} else {
|
||||
text.replacen("sd ", "pd ", 1)
|
||||
};
|
||||
(text, bits, bits, 128 / bits)
|
||||
}
|
||||
};
|
||||
let (text, source, result, lanes) = packed;
|
||||
let code = code.get(text.as_str()).unwrap_or_else(|| panic!("{text}"));
|
||||
for chunk in group.chunks_exact(lanes as usize) {
|
||||
let (mut a, mut b) = (FILLER, !FILLER);
|
||||
let mut wanted = 0;
|
||||
let mut flags = 0;
|
||||
for (index, vector) in chunk.iter().enumerate() {
|
||||
a = merge(a, vector.a, source, index as u32);
|
||||
b = merge(b, vector.b, source, index as u32);
|
||||
wanted = merge(wanted, vector.result, result, index as u32);
|
||||
flags |= vector.flags;
|
||||
}
|
||||
for native in [false, true] {
|
||||
let (cpu, mut memory) = load(code, mxcsr, a, b, 0);
|
||||
let outcome = run(native, &cpu, &mut memory, 1);
|
||||
assert_eq!(outcome.exit_reason, ExitReason::StepLimitExceeded, "{text}");
|
||||
assert_eq!(outcome.final_state.xmm[3], wanted, "{text} {chunk:x?}");
|
||||
assert_eq!(
|
||||
outcome.final_state.mxcsr.0,
|
||||
mxcsr | flags,
|
||||
"{text} {chunk:x?}"
|
||||
);
|
||||
checked += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(checked > 1500, "{checked}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unmasked_exceptions_stop_without_a_result() {
|
||||
let code = fixture();
|
||||
let mut seen = 0;
|
||||
for vector in vectors().iter().filter(|vector| vector.flags != 0) {
|
||||
let (text, kind) = instruction(vector.name);
|
||||
let (a, b, r9) = inputs(vector, kind);
|
||||
let code = &code[text.as_str()];
|
||||
for bit in 0..6 {
|
||||
if vector.flags & 1 << bit == 0 {
|
||||
continue;
|
||||
}
|
||||
// Flush-to-zero applies only while underflow is masked.
|
||||
if bit == 4 && vector.mxcsr & 1 << 15 != 0 {
|
||||
continue;
|
||||
}
|
||||
let mxcsr = vector.mxcsr & !(1 << (bit + 7));
|
||||
for native in [false, true] {
|
||||
let (cpu, mut memory) = load(code, mxcsr, a, b, r9);
|
||||
let result = run(native, &cpu, &mut memory, 1);
|
||||
assert_eq!(
|
||||
result.exit_reason,
|
||||
ExitReason::SimdException,
|
||||
"{text} {vector:x?}"
|
||||
);
|
||||
assert_eq!(result.instructions_executed, 0);
|
||||
let flags = result.final_state.mxcsr.0 ^ mxcsr;
|
||||
assert!(
|
||||
flags & 1 << bit != 0 && flags & !vector.flags == 0,
|
||||
"{text} {vector:x?}"
|
||||
);
|
||||
let mut unchanged = cpu.clone();
|
||||
unchanged.mxcsr = result.final_state.mxcsr;
|
||||
assert_eq!(result.final_state, unchanged, "{text} {vector:x?}");
|
||||
seen |= 1 << bit;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(seen, 0x3F);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pre_computation_exceptions_in_any_lane_come_first() {
|
||||
let code = fixture();
|
||||
let code = &code["addps xmm3, xmm9"];
|
||||
// Lane 0 is inexact (1 + 2^-30); lane 1 is infinity minus infinity.
|
||||
let one = 0x3F80_0000u128;
|
||||
let a = one | 0x7F80_0000 << 32;
|
||||
let b = 0x3080_0000 | 0xFF80_0000u128 << 32;
|
||||
for (unmasked, flags) in [
|
||||
(1 << 7, 1), // invalid: precision is not reported
|
||||
(1 << 12, 1 | 1 << 5), // precision: both were raised
|
||||
(1 << 7 | 1 << 12, 1), // both: only the pre-computation one
|
||||
] {
|
||||
for native in [false, true] {
|
||||
let (cpu, mut memory) = load(code, 0x1F80 & !unmasked, a, b, 0);
|
||||
let result = run(native, &cpu, &mut memory, 1);
|
||||
assert_eq!(result.exit_reason, ExitReason::SimdException);
|
||||
assert_eq!(result.final_state.mxcsr.0, 0x1F80 & !unmasked | flags);
|
||||
assert_eq!(result.final_state.xmm, cpu.xmm);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unmasked_underflow_reports_an_exact_denormal_result() {
|
||||
let code = fixture();
|
||||
let code = &code["mulss xmm3, xmm9"];
|
||||
// 2^-126 * 0.5 is exactly representable, so it underflows only if unmasked.
|
||||
let (a, b) = (0x0080_0000u128, 0x3F00_0000u128);
|
||||
for native in [false, true] {
|
||||
let (cpu, mut memory) = load(code, 0x1F80, a, b, 0);
|
||||
let result = run(native, &cpu, &mut memory, 1);
|
||||
assert_eq!(result.exit_reason, ExitReason::StepLimitExceeded);
|
||||
assert_eq!(result.final_state.mxcsr.0, 0x1F80);
|
||||
assert_eq!(result.final_state.xmm[3], 0x0040_0000);
|
||||
for ftz in [0, 1 << 15] {
|
||||
let mxcsr = 0x1F80 & !(1 << 11) | ftz;
|
||||
let (cpu, mut memory) = load(code, mxcsr, a, b, 0);
|
||||
let result = run(native, &cpu, &mut memory, 1);
|
||||
assert_eq!(result.exit_reason, ExitReason::SimdException);
|
||||
assert_eq!(result.final_state.mxcsr.0, mxcsr | 1 << 4);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn misaligned_packed_operands_fault() {
|
||||
for (text, code) in fixture() {
|
||||
if !text.contains("xmmword ptr") {
|
||||
continue;
|
||||
}
|
||||
for native in [false, true] {
|
||||
let (mut cpu, mut memory) = load(&code, 0x1F80, 0, 0, 0);
|
||||
cpu.gpr[6] += 8;
|
||||
let result = run(native, &cpu, &mut memory, 1);
|
||||
assert_eq!(result.exit_reason, ExitReason::GeneralProtection, "{text}");
|
||||
assert_eq!(result.final_state, cpu, "{text}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
/// A number biased towards nearby exponents, denormals and short fractions.
|
||||
fn bits(&mut self, format: Format) -> u64 {
|
||||
let fraction = if format.bits == 32 { 23 } else { 52 };
|
||||
let mask = if format.bits == 32 {
|
||||
u64::from(u32::MAX)
|
||||
} else {
|
||||
u64::MAX
|
||||
};
|
||||
let raw = self.next() & mask;
|
||||
let sign = raw & 1 << (format.bits - 1);
|
||||
match self.next() % 6 {
|
||||
0 => raw & !(0x7FFu64 << fraction & mask) | sign,
|
||||
1 => {
|
||||
let exponent_bias = (1u64 << (format.bits - 2 - fraction)) - 1;
|
||||
let exponent = exponent_bias - 30 + self.next() % 61;
|
||||
sign | exponent << fraction | raw & ((1 << fraction) - 1)
|
||||
}
|
||||
2 => raw & !((1 << (fraction - 3)) - 1),
|
||||
_ => raw,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const NEAREST: u32 = 0x1F80;
|
||||
|
||||
#[test]
|
||||
fn nearest_rounding_agrees_with_host_hardware() {
|
||||
let control = Control::from_mxcsr(NEAREST);
|
||||
let mut random = Random(0x6A09_E667_F3BC_C909);
|
||||
let kinds = [
|
||||
Arithmetic::Add,
|
||||
Arithmetic::Sub,
|
||||
Arithmetic::Mul,
|
||||
Arithmetic::Div,
|
||||
];
|
||||
let mut compared = 0;
|
||||
for _ in 0..300_000 {
|
||||
let (a, b) = (random.bits(F32), random.bits(F32));
|
||||
let (x, y) = (f32::from_bits(a as u32), f32::from_bits(b as u32));
|
||||
let hosts = [x + y, x - y, x * y, x / y];
|
||||
for (kind, host) in kinds.into_iter().zip(hosts) {
|
||||
let ours = softfloat::arithmetic(kind, F32, a, b, &control);
|
||||
if host.is_nan() {
|
||||
assert!(f32::from_bits(ours.bits as u32).is_nan());
|
||||
} else {
|
||||
assert_eq!(ours.bits as u32, host.to_bits(), "{kind:?} {a:x} {b:x}");
|
||||
compared += 1;
|
||||
}
|
||||
}
|
||||
let (a, b) = (random.bits(F64), random.bits(F64));
|
||||
let (x, y) = (f64::from_bits(a), f64::from_bits(b));
|
||||
let hosts = [x + y, x - y, x * y, x / y];
|
||||
for (kind, host) in kinds.into_iter().zip(hosts) {
|
||||
let ours = softfloat::arithmetic(kind, F64, a, b, &control);
|
||||
if host.is_nan() {
|
||||
assert!(f64::from_bits(ours.bits).is_nan());
|
||||
} else {
|
||||
assert_eq!(ours.bits, host.to_bits(), "{kind:?} {a:x} {b:x}");
|
||||
compared += 1;
|
||||
}
|
||||
}
|
||||
if x >= 0.0 {
|
||||
let ours = softfloat::square_root(F64, a, &control).bits;
|
||||
assert_eq!(ours, x.sqrt().to_bits(), "sqrt {a:x}");
|
||||
}
|
||||
let single = f32::from_bits(random.next() as u32);
|
||||
if single >= 0.0 {
|
||||
let ours = softfloat::square_root(F32, u64::from(single.to_bits()), &control).bits;
|
||||
assert_eq!(ours as u32, single.sqrt().to_bits());
|
||||
}
|
||||
if !x.is_nan() {
|
||||
let ours = softfloat::convert(F64, F32, a, &control).bits;
|
||||
assert_eq!(ours as u32, (x as f32).to_bits(), "narrow {a:x}");
|
||||
}
|
||||
if !single.is_nan() {
|
||||
let ours = softfloat::convert(F32, F64, u64::from(single.to_bits()), &control).bits;
|
||||
assert_eq!(ours, f64::from(single).to_bits());
|
||||
}
|
||||
let integer = random.next() as i64 >> (random.next() % 64);
|
||||
assert_eq!(
|
||||
softfloat::from_integer(F64, integer, &control).bits,
|
||||
(integer as f64).to_bits()
|
||||
);
|
||||
assert_eq!(
|
||||
softfloat::from_integer(F32, integer, &control).bits as u32,
|
||||
(integer as f32).to_bits()
|
||||
);
|
||||
}
|
||||
assert!(compared > 2_000_000, "{compared}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn float_sequences_agree_between_engines() {
|
||||
let cases: Vec<(&str, Vec<u8>)> = fixture().into_iter().collect();
|
||||
let mut random = Random(0xBB67_AE85_84CA_A73B);
|
||||
for round in 0..2000 {
|
||||
let mut code = Vec::new();
|
||||
let mut text = Vec::new();
|
||||
for _ in 0..1 + random.next() % 14 {
|
||||
let case = &cases[(random.next() % cases.len() as u64) as usize];
|
||||
code.extend_from_slice(&case.1);
|
||||
text.push(case.0);
|
||||
if random.next().is_multiple_of(3) {
|
||||
code.extend_from_slice(&[0x0F, 0x92, 0xC0]); // setb al
|
||||
}
|
||||
}
|
||||
code.push(0xF4);
|
||||
let mut mxcsr = 0x1F80 | (random.next() as u32 & 0xE040);
|
||||
if random.next().is_multiple_of(8) {
|
||||
mxcsr &= !(1 << (7 + random.next() % 6));
|
||||
}
|
||||
let a = u128::from(random.bits(F64)) << 64 | u128::from(random.bits(F32)) << 32;
|
||||
let b = u128::from(random.bits(F64)) << 64 | u128::from(random.bits(F64));
|
||||
let (cpu, mut first) = load(&code, mxcsr, a, b, random.next());
|
||||
let interpreted = run(false, &cpu, &mut first, 64);
|
||||
let (_, mut second) = load(&code, mxcsr, a, b, 0);
|
||||
let translated = run(true, &cpu, &mut second, 64);
|
||||
assert_eq!(
|
||||
translated.exit_reason, interpreted.exit_reason,
|
||||
"{round}: {text:#?}"
|
||||
);
|
||||
assert_eq!(
|
||||
translated.instructions_executed,
|
||||
interpreted.instructions_executed
|
||||
);
|
||||
assert_eq!(
|
||||
translated.final_state, interpreted.final_state,
|
||||
"{round}: {text:#?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,203 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Regression tests for bounded x86-64 prefix decoding and the architectural
|
||||
//! instruction-length limit, enforced across the static PE probe, the software
|
||||
//! interpreter and the native DBT (issue #69).
|
||||
//!
|
||||
//! The architectural limit is 15 bytes. The production constant is
|
||||
//! `xenora_loader::x86_decode::MAX_INSTRUCTION_LEN`; the value is mirrored here
|
||||
//! so the tests fail against the pre-fix implementation rather than only
|
||||
//! compiling.
|
||||
|
||||
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter};
|
||||
use xenora_loader::dbt::DbtEngine;
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
use xenora_loader::probe::{InstructionRecord, ProbeConfig, probe_pe_bytes};
|
||||
|
||||
const MAX_INSTRUCTION_LEN: usize = 15;
|
||||
const ENTRY: u64 = 0x1000;
|
||||
|
||||
/// Minimal synthetic PE32+ image with one executable section whose code
|
||||
/// starts at RVA `ENTRY`. Modelled on the fixtures in `probe_static.rs`.
|
||||
fn synthetic_pe_with_code(code: &[u8]) -> Vec<u8> {
|
||||
let mut pe = vec![0u8; 1024];
|
||||
pe[0] = b'M';
|
||||
pe[1] = b'Z';
|
||||
pe[0x3c] = 0x80;
|
||||
pe[0x80..0x84].copy_from_slice(b"PE\0\0");
|
||||
let coff = 0x84;
|
||||
pe[coff..coff + 2].copy_from_slice(&0x8664u16.to_le_bytes());
|
||||
pe[coff + 2..coff + 4].copy_from_slice(&1u16.to_le_bytes());
|
||||
pe[coff + 16..coff + 18].copy_from_slice(&240u16.to_le_bytes());
|
||||
let opt = coff + 20; // 0x98
|
||||
pe[opt..opt + 2].copy_from_slice(&0x20bu16.to_le_bytes());
|
||||
pe[opt + 16..opt + 20].copy_from_slice(&(ENTRY as u32).to_le_bytes()); // entry point RVA
|
||||
pe[opt + 24..opt + 32].copy_from_slice(&0x140000000u64.to_le_bytes()); // image base
|
||||
pe[opt + 32..opt + 36].copy_from_slice(&0x1000u32.to_le_bytes()); // section alignment
|
||||
pe[opt + 36..opt + 40].copy_from_slice(&0x200u32.to_le_bytes()); // file alignment
|
||||
pe[opt + 56..opt + 60].copy_from_slice(&0x2000u32.to_le_bytes()); // size of image
|
||||
pe[opt + 60..opt + 64].copy_from_slice(&0x400u32.to_le_bytes()); // size of headers
|
||||
pe[opt + 108..opt + 112].copy_from_slice(&16u32.to_le_bytes()); // number of rva and sizes
|
||||
|
||||
let sec = opt + 240;
|
||||
pe[sec..sec + 5].copy_from_slice(b".text");
|
||||
pe[sec + 8..sec + 12].copy_from_slice(&0x200u32.to_le_bytes()); // virtual size
|
||||
pe[sec + 12..sec + 16].copy_from_slice(&(ENTRY as u32).to_le_bytes()); // virtual address
|
||||
pe[sec + 16..sec + 20].copy_from_slice(&0x200u32.to_le_bytes()); // raw data size
|
||||
pe[sec + 20..sec + 24].copy_from_slice(&0x200u32.to_le_bytes()); // raw data pointer
|
||||
let chars: u32 = 0x6000_0020; // CODE | EXECUTE | READ
|
||||
pe[sec + 36..sec + 40].copy_from_slice(&chars.to_le_bytes());
|
||||
|
||||
pe[0x200..0x200 + code.len()].copy_from_slice(code);
|
||||
pe
|
||||
}
|
||||
|
||||
fn probe_records(code: &[u8]) -> Vec<InstructionRecord> {
|
||||
let pe = synthetic_pe_with_code(code);
|
||||
probe_pe_bytes(&pe, &ProbeConfig::default())
|
||||
.expect("probe should succeed")
|
||||
.instruction_records
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probe_reports_overlong_segment_prefix_run() {
|
||||
let records = probe_records(&[0x65; 16]);
|
||||
assert!(
|
||||
records.iter().any(|r| r.mnemonic == "overlong prefix run"),
|
||||
"expected an overlong-prefix record, got {records:?}"
|
||||
);
|
||||
assert!(
|
||||
records
|
||||
.iter()
|
||||
.all(|r| (1..=MAX_INSTRUCTION_LEN).contains(&r.bytes.len())),
|
||||
"every record stays within the architectural limit: {records:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probe_instruction_lengths_stay_within_the_architectural_limit() {
|
||||
// With 0..=13 prefixes the decoded instruction (prefixes + `xor eax,eax`)
|
||||
// stays within the architectural 15-byte limit.
|
||||
for prefixes in 0..=13usize {
|
||||
let mut code = vec![0x65; prefixes];
|
||||
code.extend_from_slice(&[0x31, 0xc0, 0xc3]); // xor eax, eax; ret
|
||||
let records = probe_records(&code);
|
||||
assert!(
|
||||
records
|
||||
.iter()
|
||||
.all(|r| (1..=MAX_INSTRUCTION_LEN).contains(&r.bytes.len())),
|
||||
"prefixes={prefixes}: {records:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Replicate the `cpu_decode` fuzz target's `build_image` for the minimized
|
||||
/// artifact and assert the fuzz target's length invariant on every record.
|
||||
#[test]
|
||||
fn probe_fuzz_harness_minimized_artifact() {
|
||||
const PE_OFFSET: usize = 0x40;
|
||||
const COFF: usize = PE_OFFSET + 4;
|
||||
const OPTIONAL: usize = COFF + 20;
|
||||
const OPTIONAL_LEN: u16 = 0xf0;
|
||||
const TEXT: usize = OPTIONAL + OPTIONAL_LEN as usize;
|
||||
const HEADER_LEN: usize = 0x200;
|
||||
const TEXT_RVA: u32 = 0x1000;
|
||||
const SECTION_ALIGNMENT: u32 = 0x1000;
|
||||
|
||||
// Minimized `cpu_decode` input recorded in the campaign ledger, kept inline
|
||||
// because `fuzz/artifacts/` is not tracked.
|
||||
let mut artifact = vec![0x65u8; 12];
|
||||
artifact.push(0x73);
|
||||
artifact.extend([0x65; 4]);
|
||||
|
||||
let mut header = [0u8; HEADER_LEN];
|
||||
let mut write_field = |offset: usize, bytes: &[u8]| {
|
||||
header[offset..offset + bytes.len()].copy_from_slice(bytes);
|
||||
};
|
||||
write_field(0, b"MZ");
|
||||
write_field(0x3c, &(PE_OFFSET as u32).to_le_bytes());
|
||||
write_field(PE_OFFSET, b"PE\0\0");
|
||||
write_field(COFF, &0x8664u16.to_le_bytes()); // Machine
|
||||
write_field(COFF + 2, &1u16.to_le_bytes()); // NumberOfSections
|
||||
write_field(COFF + 16, &OPTIONAL_LEN.to_le_bytes());
|
||||
write_field(OPTIONAL, &0x20bu16.to_le_bytes()); // Magic
|
||||
write_field(OPTIONAL + 16, &TEXT_RVA.to_le_bytes()); // AddressOfEntryPoint
|
||||
write_field(OPTIONAL + 24, &0x1_4000_0000u64.to_le_bytes()); // ImageBase
|
||||
write_field(OPTIONAL + 32, &SECTION_ALIGNMENT.to_le_bytes());
|
||||
write_field(OPTIONAL + 36, &0x200u32.to_le_bytes()); // FileAlignment
|
||||
write_field(OPTIONAL + 108, &16u32.to_le_bytes()); // NumberOfRvaAndSizes
|
||||
write_field(TEXT, b".text");
|
||||
write_field(TEXT + 12, &TEXT_RVA.to_le_bytes()); // VirtualAddress
|
||||
write_field(TEXT + 20, &(HEADER_LEN as u32).to_le_bytes()); // PointerToRawData
|
||||
write_field(TEXT + 36, &0x6000_0020u32.to_le_bytes()); // CODE | EXECUTE | READ
|
||||
let code_size = artifact.len() as u32;
|
||||
write_field(TEXT + 8, &code_size.to_le_bytes()); // VirtualSize
|
||||
write_field(TEXT + 16, &code_size.to_le_bytes()); // SizeOfRawData
|
||||
|
||||
let mut image = Vec::with_capacity(HEADER_LEN + artifact.len());
|
||||
image.extend_from_slice(&header);
|
||||
image.extend_from_slice(&artifact);
|
||||
|
||||
let report = probe_pe_bytes(&image, &ProbeConfig::default()).expect("probe should succeed");
|
||||
assert!(
|
||||
!report.instruction_records.is_empty(),
|
||||
"entry is decoded at least once"
|
||||
);
|
||||
for rec in &report.instruction_records {
|
||||
assert!(
|
||||
(1..=MAX_INSTRUCTION_LEN).contains(&rec.bytes.len()),
|
||||
"fuzz-harness record: {rec:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn probe_minimized_overlong_prefix_run_input() {
|
||||
// Minimized crash artifact found by the `cpu_decode` fuzz target:
|
||||
// 12x GS + 0x73 (JAE rel8) + 4x GS = 17 bytes, which the fuzz invariant
|
||||
// flags as a decoded instruction longer than 15 bytes.
|
||||
let mut code = vec![0x65; 12];
|
||||
code.push(0x73);
|
||||
code.extend([0x65; 4]);
|
||||
let records = probe_records(&code);
|
||||
assert!(
|
||||
records
|
||||
.iter()
|
||||
.all(|r| (1..=MAX_INSTRUCTION_LEN).contains(&r.bytes.len())),
|
||||
"all records within the limit: {records:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interpreter_rejects_overlong_segment_prefix_run() {
|
||||
let mut code = vec![0x65; 16];
|
||||
code.push(0xC3);
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, &code)
|
||||
.unwrap();
|
||||
let cpu = CpuState::new(ENTRY, 0);
|
||||
let result = Interpreter::new(cpu, &mut memory, 8).run();
|
||||
assert_eq!(result.exit_reason, ExitReason::IllegalInstruction(0x65));
|
||||
assert_eq!(result.instructions_executed, 0);
|
||||
assert_eq!(result.final_state.rip, ENTRY);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dbt_rejects_overlong_segment_prefix_run() {
|
||||
let mut code = vec![0x65; 16];
|
||||
code.push(0xC3);
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, &code)
|
||||
.unwrap();
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
let result = DbtEngine::new(1024 * 1024)
|
||||
.expect("JIT memory allocation")
|
||||
.run(&mut cpu, &mut memory, 8);
|
||||
assert!(
|
||||
matches!(result.exit_reason, ExitReason::IllegalInstruction(_)),
|
||||
"expected IllegalInstruction, got {:?}",
|
||||
result.exit_reason
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,799 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! Independent tests of the SSE and SSE2 moves and packed integer forms.
|
||||
//!
|
||||
//! `tests/x86/vector.txt` pairs LLVM encodings with Intel-syntax text. The
|
||||
//! reference below reads only the text and works on byte arrays with exact
|
||||
//! integer arithmetic, following the operation sections of the Intel SDM Vol. 2.
|
||||
//! It shares nothing with the registry, decoder, production semantics or NEON
|
||||
//! lowering.
|
||||
|
||||
use xenora_loader::cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, Mxcsr, RFlags};
|
||||
use xenora_loader::dbt::{DbtEngine, is_native};
|
||||
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
|
||||
use xenora_loader::x86_decode::decode;
|
||||
|
||||
const ENTRY: u64 = 0x1000;
|
||||
const DATA: u64 = 0x2000;
|
||||
/// Address of `[rsi + 4*rdi + 16]` with RSI = DATA and RDI = 4.
|
||||
const OPERAND: u64 = DATA + 32;
|
||||
type Bytes = [u8; 16];
|
||||
|
||||
struct Case {
|
||||
code: Vec<u8>,
|
||||
text: &'static str,
|
||||
}
|
||||
|
||||
fn parse(fixture: &'static str) -> Vec<Case> {
|
||||
fixture
|
||||
.lines()
|
||||
.map(|line| {
|
||||
let (hex, text) = line.split_once(" | ").unwrap();
|
||||
let code = hex
|
||||
.split(' ')
|
||||
.map(|b| u8::from_str_radix(b, 16).unwrap())
|
||||
.collect();
|
||||
Case { code, text }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn cases() -> Vec<Case> {
|
||||
parse(include_str!("x86/vector.txt"))
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
/// Bytes biased towards lane boundaries and, at times, small shift counts.
|
||||
fn vector(&mut self) -> Bytes {
|
||||
const EDGES: [u8; 8] = [0, 1, 0x7F, 0x80, 0x81, 0xFE, 0xFF, 0x10];
|
||||
let mode = self.next() % 4;
|
||||
let mut out = [0; 16];
|
||||
for byte in &mut out {
|
||||
*byte = match mode {
|
||||
0 => self.next() as u8,
|
||||
_ => EDGES[(self.next() % 8) as usize],
|
||||
};
|
||||
}
|
||||
if mode == 3 {
|
||||
out[..8].copy_from_slice(&(self.next() % 70).to_le_bytes());
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn machine(&mut self) -> Machine {
|
||||
let mut gpr = [0; 16];
|
||||
for register in &mut gpr {
|
||||
*register = self.next();
|
||||
}
|
||||
(gpr[6], gpr[7]) = (DATA, 4);
|
||||
let mut xmm = [[0; 16]; 16];
|
||||
for register in &mut xmm {
|
||||
*register = self.vector();
|
||||
}
|
||||
Machine {
|
||||
gpr,
|
||||
xmm,
|
||||
operand: self.vector(),
|
||||
mxcsr: (self.next() & 0xFFFF) as u32,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Machine {
|
||||
gpr: [u64; 16],
|
||||
xmm: [Bytes; 16],
|
||||
operand: Bytes,
|
||||
mxcsr: u32,
|
||||
}
|
||||
|
||||
// --- reference -------------------------------------------------------------
|
||||
|
||||
/// Unsigned lanes of `width` bytes, lane 0 first.
|
||||
fn split(bytes: &[u8], width: usize) -> Vec<i128> {
|
||||
bytes
|
||||
.chunks(width)
|
||||
.map(|chunk| {
|
||||
chunk
|
||||
.iter()
|
||||
.rev()
|
||||
.fold(0, |value, byte| value * 256 + i128::from(*byte))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn join(lanes: &[i128], width: usize) -> Bytes {
|
||||
let mut out = Vec::new();
|
||||
for lane in lanes {
|
||||
let mut rest = lane.rem_euclid(1i128 << (8 * width));
|
||||
for _ in 0..width {
|
||||
out.push((rest % 256) as u8);
|
||||
rest /= 256;
|
||||
}
|
||||
}
|
||||
out.try_into().unwrap()
|
||||
}
|
||||
|
||||
fn negative_form(value: i128, width: usize) -> i128 {
|
||||
let modulus = 1i128 << (8 * width);
|
||||
if value >= modulus / 2 {
|
||||
value - modulus
|
||||
} else {
|
||||
value
|
||||
}
|
||||
}
|
||||
|
||||
fn zip(a: &Bytes, b: &Bytes, width: usize, f: impl Fn(i128, i128) -> i128) -> Bytes {
|
||||
let pairs: Vec<i128> = split(a, width)
|
||||
.into_iter()
|
||||
.zip(split(b, width))
|
||||
.map(|(x, y)| f(x, y))
|
||||
.collect();
|
||||
join(&pairs, width)
|
||||
}
|
||||
|
||||
fn zip_signed(a: &Bytes, b: &Bytes, width: usize, f: impl Fn(i128, i128) -> i128) -> Bytes {
|
||||
zip(a, b, width, |x, y| {
|
||||
f(negative_form(x, width), negative_form(y, width))
|
||||
})
|
||||
}
|
||||
|
||||
/// Lane width in bytes named by a mnemonic suffix.
|
||||
fn suffix(name: &str) -> usize {
|
||||
match name.as_bytes()[name.len() - 1] {
|
||||
b'b' => 1,
|
||||
b'w' => 2,
|
||||
b'd' => 4,
|
||||
_ => 8,
|
||||
}
|
||||
}
|
||||
|
||||
fn clamp(value: i128, low: i128, high: i128) -> i128 {
|
||||
if value < low {
|
||||
low
|
||||
} else if value > high {
|
||||
high
|
||||
} else {
|
||||
value
|
||||
}
|
||||
}
|
||||
|
||||
fn shifted(name: &str, value: &Bytes, count: i128) -> Bytes {
|
||||
let width = suffix(name);
|
||||
let bits = 8 * width as i128;
|
||||
let lanes: Vec<i128> = split(value, width)
|
||||
.into_iter()
|
||||
.map(|lane| {
|
||||
let mut lane = if name.starts_with("psra") {
|
||||
negative_form(lane, width)
|
||||
} else {
|
||||
lane
|
||||
};
|
||||
for _ in 0..clamp(count, 0, bits) {
|
||||
lane = if name.starts_with("psll") {
|
||||
(lane * 2).rem_euclid(1 << bits)
|
||||
} else {
|
||||
lane.div_euclid(2) // floors, so negative lanes keep their sign
|
||||
};
|
||||
}
|
||||
lane
|
||||
})
|
||||
.collect();
|
||||
join(&lanes, width)
|
||||
}
|
||||
|
||||
fn packed(name: &str, a: &Bytes, b: &Bytes) -> Bytes {
|
||||
let canonical = match name {
|
||||
"andps" | "andpd" => "pand",
|
||||
"andnps" | "andnpd" => "pandn",
|
||||
"orps" | "orpd" => "por",
|
||||
"xorps" | "xorpd" => "pxor",
|
||||
"unpcklps" => "punpckldq",
|
||||
"unpcklpd" => "punpcklqdq",
|
||||
"unpckhps" => "punpckhdq",
|
||||
"unpckhpd" => "punpckhqdq",
|
||||
other => other,
|
||||
};
|
||||
let name = canonical;
|
||||
let width = suffix(name);
|
||||
let top = 1i128 << (8 * width);
|
||||
let truth = |value: bool| if value { -1 } else { 0 };
|
||||
match name {
|
||||
"pand" => zip(a, b, 1, |x, y| x & y),
|
||||
"pandn" => zip(a, b, 1, |x, y| (255 - x) & y),
|
||||
"por" => zip(a, b, 1, |x, y| x | y),
|
||||
"pxor" => zip(a, b, 1, |x, y| x ^ y),
|
||||
"paddb" | "paddw" | "paddd" | "paddq" => zip(a, b, width, |x, y| x + y),
|
||||
"psubb" | "psubw" | "psubd" | "psubq" => zip(a, b, width, |x, y| x - y),
|
||||
"paddsb" | "paddsw" => zip_signed(a, b, width, |x, y| clamp(x + y, -top / 2, top / 2 - 1)),
|
||||
"psubsb" | "psubsw" => zip_signed(a, b, width, |x, y| clamp(x - y, -top / 2, top / 2 - 1)),
|
||||
"paddusb" | "paddusw" => zip(a, b, width, |x, y| clamp(x + y, 0, top - 1)),
|
||||
"psubusb" | "psubusw" => zip(a, b, width, |x, y| clamp(x - y, 0, top - 1)),
|
||||
"pcmpeqb" | "pcmpeqw" | "pcmpeqd" => zip(a, b, width, |x, y| truth(x == y)),
|
||||
"pcmpgtb" | "pcmpgtw" | "pcmpgtd" => zip_signed(a, b, width, |x, y| truth(x > y)),
|
||||
"pminub" => zip(a, b, 1, |x, y| if x < y { x } else { y }),
|
||||
"pmaxub" => zip(a, b, 1, |x, y| if x > y { x } else { y }),
|
||||
"pminsw" => zip_signed(a, b, 2, |x, y| if x < y { x } else { y }),
|
||||
"pmaxsw" => zip_signed(a, b, 2, |x, y| if x > y { x } else { y }),
|
||||
"pavgb" | "pavgw" => zip(a, b, width, |x, y| (x + y + 1) / 2),
|
||||
"pmullw" => zip(a, b, 2, |x, y| x * y),
|
||||
"pmulhw" => zip_signed(a, b, 2, |x, y| (x * y).div_euclid(65536)),
|
||||
"pmulhuw" => zip(a, b, 2, |x, y| x * y / 65536),
|
||||
"pmuludq" => zip(a, b, 8, |x, y| (x % (1 << 32)) * (y % (1 << 32))),
|
||||
"pmaddwd" => {
|
||||
let (x, y) = (split(a, 2), split(b, 2));
|
||||
let product = |i: usize| negative_form(x[i], 2) * negative_form(y[i], 2);
|
||||
join(&[0, 2, 4, 6].map(|i| product(i) + product(i + 1)), 4)
|
||||
}
|
||||
"psadbw" => {
|
||||
let difference = |i: usize| (i128::from(a[i]) - i128::from(b[i])).abs();
|
||||
join(
|
||||
&[(0..8).map(difference).sum(), (8..16).map(difference).sum()],
|
||||
8,
|
||||
)
|
||||
}
|
||||
"packsswb" | "packssdw" | "packuswb" => {
|
||||
let from = if name == "packssdw" { 4 } else { 2 };
|
||||
let half = 1i128 << (4 * from);
|
||||
let (low, high) = if name == "packuswb" {
|
||||
(0, half - 1)
|
||||
} else {
|
||||
(-half / 2, half / 2 - 1)
|
||||
};
|
||||
let lanes: Vec<i128> = split(a, from)
|
||||
.into_iter()
|
||||
.chain(split(b, from))
|
||||
.map(|lane| clamp(negative_form(lane, from), low, high))
|
||||
.collect();
|
||||
join(&lanes, from / 2)
|
||||
}
|
||||
_ if name.starts_with("punpck") => {
|
||||
let width = match &name[7..] {
|
||||
"bw" => 1,
|
||||
"wd" => 2,
|
||||
"dq" => 4,
|
||||
_ => 8,
|
||||
};
|
||||
let start = if name.as_bytes()[6] == b'h' { 8 } else { 0 };
|
||||
let mut out = Vec::new();
|
||||
for at in (start..start + 8).step_by(width) {
|
||||
out.extend_from_slice(&a[at..at + width]);
|
||||
out.extend_from_slice(&b[at..at + width]);
|
||||
}
|
||||
out.try_into().unwrap()
|
||||
}
|
||||
_ if name.starts_with("psll") || name.starts_with("psrl") || name.starts_with("psra") => {
|
||||
shifted(name, a, split(&b[..8], 8)[0])
|
||||
}
|
||||
// Full-width loads.
|
||||
"movaps" | "movapd" | "movups" | "movupd" | "movdqa" | "movdqu" => *b,
|
||||
other => panic!("no reference for {other}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn register(text: &str) -> Option<usize> {
|
||||
text.strip_prefix("xmm")
|
||||
.and_then(|index| index.parse().ok())
|
||||
}
|
||||
|
||||
/// Index and width in bytes of a general register used by the fixture.
|
||||
fn general(text: &str) -> Option<(usize, usize)> {
|
||||
Some(match text {
|
||||
"eax" => (0, 4),
|
||||
"ebx" => (3, 4),
|
||||
"r9d" => (9, 4),
|
||||
"r10d" => (10, 4),
|
||||
"r9" => (9, 8),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn reference(m: &mut Machine, text: &str) {
|
||||
let (name, rest) = text.split_once(' ').unwrap();
|
||||
let parts: Vec<&str> = rest.split(", ").collect();
|
||||
let width = |text: &str| match text.split(' ').next().unwrap() {
|
||||
"xmmword" => 16,
|
||||
"qword" => 8,
|
||||
"dword" => 4,
|
||||
"word" => 2,
|
||||
other => panic!("width {other}"),
|
||||
};
|
||||
if name == "stmxcsr" {
|
||||
m.operand[..4].copy_from_slice(&m.mxcsr.to_le_bytes());
|
||||
return;
|
||||
}
|
||||
let destination = parts[0];
|
||||
if destination.contains(" ptr ") {
|
||||
// Stores write exactly their operand width.
|
||||
let source = m.xmm[register(parts[1]).unwrap()];
|
||||
let start = if name.starts_with("movh") { 8 } else { 0 };
|
||||
let bytes = width(destination);
|
||||
m.operand[..bytes].copy_from_slice(&source[start..start + bytes]);
|
||||
return;
|
||||
}
|
||||
let source_text = parts.get(1).copied().unwrap_or("");
|
||||
let memory = source_text.contains(" ptr ");
|
||||
if let Some((index, bytes)) = general(destination) {
|
||||
let source = m.xmm[register(source_text).unwrap()];
|
||||
let lanes = |width: usize| -> u64 {
|
||||
split(&source, width)
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, lane)| **lane >= 1i128 << (8 * width - 1))
|
||||
.map(|(at, _)| 1u64 << at)
|
||||
.sum()
|
||||
};
|
||||
m.gpr[index] = match name {
|
||||
"movmskps" => lanes(4),
|
||||
"movmskpd" => lanes(8),
|
||||
"pmovmskb" => lanes(1),
|
||||
"pextrw" => split(&source, 2)[parts[2].parse::<usize>().unwrap()] as u64,
|
||||
_ => split(&source, bytes)[0] as u64,
|
||||
};
|
||||
return;
|
||||
}
|
||||
let target = register(destination).unwrap();
|
||||
let old = m.xmm[target];
|
||||
if let Some((index, bytes)) = general(source_text) {
|
||||
let value = m.gpr[index].to_le_bytes();
|
||||
if name == "pinsrw" {
|
||||
let at = 2 * parts[2].parse::<usize>().unwrap();
|
||||
m.xmm[target][at..at + 2].copy_from_slice(&value[..2]);
|
||||
} else {
|
||||
let mut out = [0; 16];
|
||||
out[..bytes].copy_from_slice(&value[..bytes]);
|
||||
m.xmm[target] = out;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if let Ok(count) = source_text.parse::<i128>() {
|
||||
m.xmm[target] = match name {
|
||||
"pslldq" | "psrldq" => {
|
||||
let mut out = [0; 16];
|
||||
for (at, byte) in out.iter_mut().enumerate() {
|
||||
let from = at as i128 + if name == "pslldq" { -count } else { count };
|
||||
if (0..16).contains(&from) {
|
||||
*byte = old[from as usize];
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
_ => shifted(name, &old, count),
|
||||
};
|
||||
return;
|
||||
}
|
||||
let source = if memory {
|
||||
m.operand
|
||||
} else {
|
||||
m.xmm[register(source_text).unwrap()]
|
||||
};
|
||||
let imm = parts.get(2).map(|text| text.parse::<usize>().unwrap());
|
||||
let mut out = old;
|
||||
match name {
|
||||
"movss" | "movsd" | "movq" => {
|
||||
let bytes = match name {
|
||||
"movss" => 4,
|
||||
_ => 8,
|
||||
};
|
||||
if memory || name == "movq" {
|
||||
out = [0; 16];
|
||||
}
|
||||
out[..bytes].copy_from_slice(&source[..bytes]);
|
||||
}
|
||||
"movlps" | "movlpd" => out[..8].copy_from_slice(&source[..8]),
|
||||
"movhps" | "movhpd" => out[8..].copy_from_slice(&source[..8]),
|
||||
"movhlps" => out[..8].copy_from_slice(&source[8..]),
|
||||
"movlhps" => out[8..].copy_from_slice(&source[..8]),
|
||||
"movd" => {
|
||||
out = [0; 16];
|
||||
out[..4].copy_from_slice(&source[..4]);
|
||||
}
|
||||
"pinsrw" => {
|
||||
let at = 2 * imm.unwrap();
|
||||
out[at..at + 2].copy_from_slice(&source[..2]);
|
||||
}
|
||||
"pshufd" | "shufps" => {
|
||||
for lane in 0..4 {
|
||||
let from = imm.unwrap() / 4usize.pow(lane) % 4;
|
||||
let lane = lane as usize;
|
||||
let input = if name == "shufps" && lane < 2 {
|
||||
old
|
||||
} else {
|
||||
source
|
||||
};
|
||||
out[4 * lane..4 * lane + 4].copy_from_slice(&input[4 * from..4 * from + 4]);
|
||||
}
|
||||
}
|
||||
"pshuflw" | "pshufhw" => {
|
||||
out = source;
|
||||
let base = if name == "pshufhw" { 8 } else { 0 };
|
||||
for lane in 0..4 {
|
||||
let from = base + 2 * (imm.unwrap() / 4usize.pow(lane) % 4);
|
||||
let to = base + 2 * lane as usize;
|
||||
out[to..to + 2].copy_from_slice(&source[from..from + 2]);
|
||||
}
|
||||
}
|
||||
"shufpd" => {
|
||||
let low = 8 * (imm.unwrap() % 2);
|
||||
let high = 8 * (imm.unwrap() / 2 % 2);
|
||||
out[..8].copy_from_slice(&old[low..low + 8]);
|
||||
out[8..].copy_from_slice(&source[high..high + 8]);
|
||||
}
|
||||
_ => out = packed(name, &old, &source),
|
||||
}
|
||||
m.xmm[target] = out;
|
||||
}
|
||||
|
||||
// --- harness ---------------------------------------------------------------
|
||||
|
||||
fn load(machine: &Machine, code: &[u8], permissions: MemoryPermissions) -> (CpuState, GuestMemory) {
|
||||
let mut memory = GuestMemory::new();
|
||||
memory
|
||||
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, code)
|
||||
.unwrap();
|
||||
let mut data = vec![0xEE; 0x100];
|
||||
data[32..48].copy_from_slice(&machine.operand);
|
||||
memory
|
||||
.map_region_with_data(DATA, 0x100, permissions, &data)
|
||||
.unwrap();
|
||||
let mut cpu = CpuState::new(ENTRY, 0);
|
||||
cpu.gpr = machine.gpr;
|
||||
cpu.xmm = machine.xmm.map(u128::from_le_bytes);
|
||||
cpu.mxcsr = Mxcsr(machine.mxcsr);
|
||||
cpu.flags = RFlags {
|
||||
cf: true,
|
||||
zf: false,
|
||||
sf: true,
|
||||
of: false,
|
||||
pf: true,
|
||||
af: false,
|
||||
};
|
||||
(cpu, memory)
|
||||
}
|
||||
|
||||
fn run(native: bool, cpu: &CpuState, memory: &mut GuestMemory, budget: usize) -> ExecutionResult {
|
||||
if native {
|
||||
DbtEngine::new(256 * 1024)
|
||||
.unwrap()
|
||||
.run(&mut cpu.clone(), memory, budget)
|
||||
} else {
|
||||
Interpreter::new(cpu.clone(), memory, budget).run()
|
||||
}
|
||||
}
|
||||
|
||||
fn data(memory: &GuestMemory) -> Vec<u8> {
|
||||
let mut out = vec![0; 0x100];
|
||||
memory.read_bytes(DATA, &mut out).unwrap();
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_vector_fixture_matches_the_reference_in_both_engines() {
|
||||
let mut random = Random(0xA076_1D64_78BD_642F);
|
||||
let mut native_forms = 0;
|
||||
for case in cases() {
|
||||
let text = case.text;
|
||||
let insn = decode(ENTRY, |address| {
|
||||
case.code.get((address - ENTRY) as usize).copied().ok_or(())
|
||||
})
|
||||
.unwrap_or_else(|error| panic!("{text}: {error:?}"));
|
||||
let native = is_native(&insn);
|
||||
native_forms += usize::from(native);
|
||||
let mut engine = DbtEngine::new(64 * 1024).unwrap();
|
||||
for _ in 0..64 {
|
||||
let machine = random.machine();
|
||||
let mut expected = machine.clone();
|
||||
reference(&mut expected, text);
|
||||
let (mut wanted, _) = load(&expected, &case.code, MemoryPermissions::READ_WRITE);
|
||||
wanted.rip = ENTRY + case.code.len() as u64;
|
||||
let (cpu, mut memory) = load(&machine, &case.code, MemoryPermissions::READ_WRITE);
|
||||
let interpreted = Interpreter::new(cpu.clone(), &mut memory, 1).run();
|
||||
let (mut dbt_cpu, mut dbt_memory) =
|
||||
load(&machine, &case.code, MemoryPermissions::READ_WRITE);
|
||||
let translated = engine.run(&mut dbt_cpu, &mut dbt_memory, 1);
|
||||
for (result, memory) in [(interpreted, memory), (translated, dbt_memory)] {
|
||||
assert_eq!(result.exit_reason, ExitReason::StepLimitExceeded, "{text}");
|
||||
assert_eq!(result.final_state, wanted, "{text} from {cpu:x?}");
|
||||
let mut bytes = vec![0xEE; 0x100];
|
||||
bytes[32..48].copy_from_slice(&expected.operand);
|
||||
assert_eq!(data(&memory), bytes, "{text}");
|
||||
}
|
||||
}
|
||||
assert_eq!(engine.metrics.interpreter_fallbacks == 0, native, "{text}");
|
||||
}
|
||||
assert!(native_forms > 150, "{native_forms}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aligned_operands_fault_and_unaligned_operands_do_not() {
|
||||
let mut random = Random(0x51);
|
||||
let mut checked = [0, 0];
|
||||
for case in cases()
|
||||
.into_iter()
|
||||
.filter(|case| case.text.contains("xmmword ptr"))
|
||||
{
|
||||
let name = case.text.split(' ').next().unwrap();
|
||||
let unaligned = ["movups", "movupd", "movdqu"].contains(&name);
|
||||
checked[usize::from(unaligned)] += 1;
|
||||
for offset in [1, 4, 8, 15] {
|
||||
let mut machine = random.machine();
|
||||
machine.gpr[6] = DATA + offset;
|
||||
for native in [false, true] {
|
||||
let (cpu, mut memory) = load(&machine, &case.code, MemoryPermissions::READ_WRITE);
|
||||
let before = data(&memory);
|
||||
let result = run(native, &cpu, &mut memory, 1);
|
||||
if unaligned {
|
||||
assert_eq!(
|
||||
result.exit_reason,
|
||||
ExitReason::StepLimitExceeded,
|
||||
"{}",
|
||||
case.text
|
||||
);
|
||||
if case.text.starts_with(&format!("{name} xmm10")) {
|
||||
let mut bytes = [0; 16];
|
||||
bytes.copy_from_slice(&before[32 + offset as usize..48 + offset as usize]);
|
||||
assert_eq!(result.final_state.xmm[10], u128::from_le_bytes(bytes));
|
||||
}
|
||||
} else {
|
||||
assert_eq!(
|
||||
result.exit_reason,
|
||||
ExitReason::GeneralProtection,
|
||||
"{}",
|
||||
case.text
|
||||
);
|
||||
assert_eq!(result.final_state, cpu, "{}", case.text);
|
||||
assert_eq!(data(&memory), before, "{}", case.text);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(checked[0] > 60 && checked[1] == 6, "{checked:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn faulting_vector_accesses_change_nothing() {
|
||||
for case in cases()
|
||||
.into_iter()
|
||||
.filter(|case| case.text.contains(" ptr "))
|
||||
{
|
||||
let store = case.text.split(", ").next().unwrap().contains(" ptr ");
|
||||
let mut machine = Random(0x77).machine();
|
||||
let mut runs = vec![(0x9000, MemoryPermissions::READ_WRITE)];
|
||||
if store {
|
||||
runs.push((DATA, MemoryPermissions::READ_ONLY));
|
||||
}
|
||||
for (base, permissions) in runs {
|
||||
machine.gpr[6] = base;
|
||||
for native in [false, true] {
|
||||
let (cpu, mut memory) = load(&machine, &case.code, permissions);
|
||||
let before = data(&memory);
|
||||
let result = run(native, &cpu, &mut memory, 1);
|
||||
assert!(
|
||||
matches!(result.exit_reason, ExitReason::MemoryFault(_)),
|
||||
"{}",
|
||||
case.text
|
||||
);
|
||||
assert_eq!(result.final_state, cpu, "{}", case.text);
|
||||
assert_eq!(data(&memory), before, "{}", case.text);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_operand_width_is_accessed_at_the_end_of_a_region() {
|
||||
for (code, width) in [
|
||||
(&[0xF3u8, 0x0F, 0x10, 0x03][..], 4), // movss xmm0, [rbx]
|
||||
(&[0xF2, 0x0F, 0x10, 0x03], 8), // movsd xmm0, [rbx]
|
||||
(&[0xF3, 0x0F, 0x7E, 0x03], 8), // movq xmm0, [rbx]
|
||||
(&[0x66, 0x0F, 0xC4, 0x03, 0x01], 2), // pinsrw xmm0, [rbx], 1
|
||||
(&[0x0F, 0x10, 0x03], 16), // movups xmm0, [rbx]
|
||||
(&[0x0F, 0x11, 0x03], 16), // movups [rbx], xmm0
|
||||
] {
|
||||
let end = DATA + 0x100;
|
||||
for (address, ok) in [(end - width, true), (end - width + 1, false)] {
|
||||
let mut machine = Random(0x99).machine();
|
||||
machine.gpr[3] = address;
|
||||
for native in [false, true] {
|
||||
let (cpu, mut memory) = load(&machine, code, MemoryPermissions::READ_WRITE);
|
||||
let result = run(native, &cpu, &mut memory, 1);
|
||||
assert_eq!(
|
||||
result.exit_reason == ExitReason::StepLimitExceeded,
|
||||
ok,
|
||||
"{code:02X?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn register_store_encodings_write_the_rm_operand() {
|
||||
// The store opcodes with a register operand, which assemblers rarely emit;
|
||||
// `objdump` (LLVM) disassembles each as the text given here.
|
||||
let cases: &[(&str, &[u8])] = &[
|
||||
("movaps xmm3, xmm9", &[0x44, 0x0F, 0x29, 0xCB]),
|
||||
("movups xmm3, xmm9", &[0x44, 0x0F, 0x11, 0xCB]),
|
||||
("movdqa xmm3, xmm9", &[0x66, 0x44, 0x0F, 0x7F, 0xCB]),
|
||||
("movdqu xmm3, xmm9", &[0xF3, 0x44, 0x0F, 0x7F, 0xCB]),
|
||||
("movss xmm3, xmm9", &[0xF3, 0x44, 0x0F, 0x11, 0xCB]),
|
||||
("movsd xmm3, xmm9", &[0xF2, 0x44, 0x0F, 0x11, 0xCB]),
|
||||
("movq xmm3, xmm9", &[0x66, 0x44, 0x0F, 0xD6, 0xCB]),
|
||||
];
|
||||
let mut random = Random(0x1234);
|
||||
for (text, code) in cases {
|
||||
for _ in 0..32 {
|
||||
let machine = random.machine();
|
||||
let mut expected = machine.clone();
|
||||
reference(&mut expected, text);
|
||||
for native in [false, true] {
|
||||
let (cpu, mut memory) = load(&machine, code, MemoryPermissions::READ_WRITE);
|
||||
let result = run(native, &cpu, &mut memory, 1);
|
||||
assert_eq!(
|
||||
result.final_state.xmm,
|
||||
expected.xmm.map(u128::from_le_bytes),
|
||||
"{text}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mxcsr_resets_loads_stores_and_rejects_reserved_bits() {
|
||||
assert_eq!(CpuState::new(0, 0).mxcsr, Mxcsr(0x1F80));
|
||||
assert_eq!(CpuState::default().mxcsr, Mxcsr(0x1F80));
|
||||
for (value, accepted) in [
|
||||
(0x1F80u32, true),
|
||||
(0, true),
|
||||
(0xFFFF, true),
|
||||
(0x1_0000, false),
|
||||
(0x8000_1F80, false),
|
||||
] {
|
||||
// ldmxcsr dword ptr [rbx]; stmxcsr dword ptr [rbx+4]
|
||||
let code = [0x0F, 0xAE, 0x13, 0x0F, 0xAE, 0x5B, 0x04];
|
||||
let mut machine = Random(0x55).machine();
|
||||
machine.gpr[3] = OPERAND;
|
||||
machine.operand[..4].copy_from_slice(&value.to_le_bytes());
|
||||
for native in [false, true] {
|
||||
let (cpu, mut memory) = load(&machine, &code, MemoryPermissions::READ_WRITE);
|
||||
let result = run(native, &cpu, &mut memory, 2);
|
||||
if accepted {
|
||||
assert_eq!(result.exit_reason, ExitReason::StepLimitExceeded);
|
||||
assert_eq!(result.final_state.mxcsr, Mxcsr(value));
|
||||
assert_eq!(memory.read_u32(OPERAND + 4).unwrap(), value);
|
||||
} else {
|
||||
assert_eq!(result.exit_reason, ExitReason::GeneralProtection);
|
||||
assert_eq!(result.final_state, cpu);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_vector_encodings_are_rejected() {
|
||||
let rejected: &[&[u8]] = &[
|
||||
&[0x0F, 0xFC, 0xC1], // paddb mm0, mm1 (MMX)
|
||||
&[0x0F, 0x53, 0xC1], // rcpps xmm0, xmm1 (approximation)
|
||||
&[0xF3, 0x0F, 0x52, 0xC1], // rsqrtss xmm0, xmm1 (approximation)
|
||||
&[0x0F, 0x2D, 0xC1], // cvtps2pi mm0, xmm1 (MMX)
|
||||
&[0x66, 0x0F, 0x38, 0x00, 0xC1], // pshufb xmm0, xmm1
|
||||
&[0xC5, 0xF9, 0xFC, 0xC1], // vpaddb (VEX)
|
||||
&[0xF2, 0xF3, 0x0F, 0x10, 0xC1], // both mandatory prefixes
|
||||
&[0x66, 0xF3, 0x0F, 0x10, 0xC1], // 66 with a scalar move
|
||||
&[0x66, 0x0F, 0x12, 0xC1], // movlpd with a register source
|
||||
&[0x0F, 0x13, 0xC1], // movlps register store
|
||||
&[0x66, 0x0F, 0xE7, 0xC1], // movntdq with a register
|
||||
&[0x66, 0x0F, 0x71, 0x11, 0x01], // psrlw with a memory operand
|
||||
&[0x66, 0x0F, 0x71, 0xC1, 0x01], // 71 /0
|
||||
&[0x0F, 0xAE, 0xD1], // ldmxcsr with a register
|
||||
&[0x66, 0x0F, 0xAE, 0x13], // 66 with ldmxcsr
|
||||
];
|
||||
for code in rejected {
|
||||
let padded = [code, &[0x90; 8][..]].concat();
|
||||
let machine = Random(0x31).machine();
|
||||
for native in [false, true] {
|
||||
let (cpu, mut memory) = load(&machine, &padded, MemoryPermissions::READ_WRITE);
|
||||
let result = run(native, &cpu, &mut memory, 1);
|
||||
assert!(
|
||||
matches!(result.exit_reason, ExitReason::IllegalInstruction(_)),
|
||||
"{code:02X?}: {:?}",
|
||||
result.exit_reason
|
||||
);
|
||||
assert_eq!(result.final_state, cpu, "{code:02X?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_vector_and_integer_sequences_agree() {
|
||||
let vectors = cases();
|
||||
let integers: Vec<Case> = parse(include_str!("x86/integer.txt"))
|
||||
.into_iter()
|
||||
.filter(|case| {
|
||||
!["push", "pop", "leave", "div", "idiv"]
|
||||
.iter()
|
||||
.any(|name| case.text.starts_with(name))
|
||||
&& case.text != "mov sil, dil"
|
||||
})
|
||||
.collect();
|
||||
let mut random = Random(0xBEEF);
|
||||
for round in 0..3000 {
|
||||
let mut code = Vec::new();
|
||||
let mut text = Vec::new();
|
||||
for _ in 0..2 + random.next() % 30 {
|
||||
let pool = if random.next().is_multiple_of(4) {
|
||||
&integers
|
||||
} else {
|
||||
&vectors
|
||||
};
|
||||
let case = &pool[(random.next() % pool.len() as u64) as usize];
|
||||
code.extend_from_slice(&case.code);
|
||||
text.push(case.text);
|
||||
}
|
||||
code.push(0xF4);
|
||||
let mut machine = random.machine();
|
||||
if random.next().is_multiple_of(8) {
|
||||
machine.gpr[6] += 1 + random.next() % 15; // misaligned operand
|
||||
}
|
||||
let budget = 1 + (random.next() % 40) as usize;
|
||||
let (cpu, mut first) = load(&machine, &code, MemoryPermissions::READ_WRITE);
|
||||
let interpreted = run(false, &cpu, &mut first, budget);
|
||||
let (_, mut second) = load(&machine, &code, MemoryPermissions::READ_WRITE);
|
||||
let translated = run(true, &cpu, &mut second, budget);
|
||||
assert_eq!(
|
||||
translated.exit_reason, interpreted.exit_reason,
|
||||
"{round}: {text:#?}"
|
||||
);
|
||||
assert_eq!(
|
||||
translated.instructions_executed, interpreted.instructions_executed,
|
||||
"{round}: {text:#?}"
|
||||
);
|
||||
assert_eq!(
|
||||
translated.final_state, interpreted.final_state,
|
||||
"{round}: {text:#?}"
|
||||
);
|
||||
assert_eq!(data(&first), data(&second), "{round}: {text:#?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_shift_counts_use_all_64_low_bits() {
|
||||
// The count is the low quadword of the source; its high quadword is ignored.
|
||||
for case in cases() {
|
||||
let name = case.text.split(' ').next().unwrap();
|
||||
let is_shift = ["psll", "psrl", "psra"]
|
||||
.iter()
|
||||
.any(|prefix| name.starts_with(prefix));
|
||||
if !is_shift || !case.text.ends_with("xmm3, xmm9") {
|
||||
continue;
|
||||
}
|
||||
for (low, high) in [
|
||||
(1u64 << 32 | 1, 0u64),
|
||||
(1 << 63, 0),
|
||||
(u64::MAX, 0),
|
||||
(3, u64::MAX),
|
||||
] {
|
||||
let mut machine = Random(0x41).machine();
|
||||
machine.xmm[9][..8].copy_from_slice(&low.to_le_bytes());
|
||||
machine.xmm[9][8..].copy_from_slice(&high.to_le_bytes());
|
||||
let mut expected = machine.clone();
|
||||
reference(&mut expected, case.text);
|
||||
for native in [false, true] {
|
||||
let (cpu, mut memory) = load(&machine, &case.code, MemoryPermissions::READ_WRITE);
|
||||
let result = run(native, &cpu, &mut memory, 1);
|
||||
let wanted = expected.xmm.map(u128::from_le_bytes);
|
||||
assert_eq!(result.final_state.xmm, wanted, "{} by {low:#x}", case.text);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
+447
-42
@@ -51,18 +51,27 @@ pub enum Op {
|
||||
Move(u8, Source),
|
||||
Add(u8, u8, u8),
|
||||
ScalarMove(u8, Source),
|
||||
/// SOP1 unary operation writing an SGPR (s0-s105), and SCC for some.
|
||||
ScalarUnary(ScalarUnary, u8, Source),
|
||||
/// VOP1 move of a normal SGPR or `vcc_lo` (106) into a VGPR.
|
||||
MoveScalar(u8, u8),
|
||||
/// VOPC 32-bit integer compare writing the Wave32 mask to `vcc_lo`.
|
||||
Compare(Comparison, CompareSource, u8),
|
||||
/// SOP2 operation writing an SGPR and SCC.
|
||||
Scalar(ScalarAlu, u8, Source, Source),
|
||||
/// SOPC `s_cmp_eq_{i32,u32}` (opcodes 0 and 6, identical per guide 12.4).
|
||||
CompareEqual(Source, Source),
|
||||
/// The other SOPC 32-bit integer compares (opcodes 1-5 and 7-11), writing
|
||||
/// only SCC: LG, GT, GE, LT, LE, signed for 1-5, unsigned for 7-11.
|
||||
ScalarCompare(Comparison, Source, Source),
|
||||
Branch {
|
||||
target: usize,
|
||||
condition: BranchCondition,
|
||||
},
|
||||
Vector(VectorAlu, u8, u8, u8),
|
||||
/// VOP2 32-bit integer form: VDST, SRC0 (VGPR, SGPR, `vcc_lo`, inline
|
||||
/// integer or literal) and VSRC1. Writes neither VCC nor SCC.
|
||||
VectorInteger(VectorInteger, u8, CompareSource, u8),
|
||||
End,
|
||||
}
|
||||
|
||||
@@ -101,7 +110,7 @@ impl Comparison {
|
||||
}
|
||||
}
|
||||
|
||||
/// First source of a VOPC compare.
|
||||
/// First source of a VOPC compare or a VOP2 integer form.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum CompareSource {
|
||||
/// VGPR index.
|
||||
@@ -129,7 +138,7 @@ pub enum BranchCondition {
|
||||
///
|
||||
/// AMD RDNA 2 XML descriptions: additions store the carry-out in SCC,
|
||||
/// subtractions the borrow; ADDC/SUBB add or subtract SCC; bitwise
|
||||
/// operations set SCC iff the result is nonzero.
|
||||
/// operations and shifts set SCC iff the result is nonzero.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ScalarAlu {
|
||||
Add,
|
||||
@@ -142,6 +151,79 @@ pub enum ScalarAlu {
|
||||
And,
|
||||
Or,
|
||||
Xor,
|
||||
/// RDNA 2 ISA guide 12.1: D = S0 & ~S1, SCC = (D != 0).
|
||||
AndNot,
|
||||
/// D = S0 | ~S1, SCC = (D != 0).
|
||||
OrNot,
|
||||
/// D = ~(S0 & S1), SCC = (D != 0).
|
||||
Nand,
|
||||
/// D = ~(S0 | S1), SCC = (D != 0).
|
||||
Nor,
|
||||
/// D = ~(S0 ^ S1), SCC = (D != 0).
|
||||
Xnor,
|
||||
/// D = S0 << S1[4:0], SCC = (D != 0).
|
||||
ShiftLeft,
|
||||
/// D = S0 >> S1[4:0] (logical), SCC = (D != 0).
|
||||
ShiftRight,
|
||||
/// D = signext(S0) >> S1[4:0], SCC = (D != 0).
|
||||
ArithmeticShiftRight,
|
||||
/// Guide 12.1: D = (S0 < S1) ? S0 : S1, SCC = (S0 < S1); signed or not.
|
||||
Minimum {
|
||||
signed: bool,
|
||||
},
|
||||
/// D = (S0 > S1) ? S0 : S1, SCC = (S0 > S1).
|
||||
Maximum {
|
||||
signed: bool,
|
||||
},
|
||||
/// D = SCC ? S0 : S1; reads SCC and leaves it unchanged.
|
||||
Select,
|
||||
/// D = ((1 << S0[4:0]) - 1) << S1[4:0]; SCC unchanged.
|
||||
BitfieldMask,
|
||||
/// D = low 32 bits of S0 * S1; SCC unchanged.
|
||||
Multiply,
|
||||
/// D = (S0 >> S1[4:0]) & ((1 << S1[22:16]) - 1), sign-extended from the
|
||||
/// field's top bit when signed (S0 then shifts arithmetically);
|
||||
/// SCC = (D != 0).
|
||||
BitfieldExtract {
|
||||
signed: bool,
|
||||
},
|
||||
/// D = |S0 - S1| with the 32-bit difference (0x80000000 stays),
|
||||
/// SCC = (D != 0).
|
||||
AbsoluteDifference,
|
||||
/// D = (S0 << N) + S1, SCC = ((S0 << N) + S1 >= 2^32) with N = 1..4.
|
||||
ShiftLeftAdd(u8),
|
||||
/// D = high 32 bits of S0 * S1; SCC unchanged.
|
||||
MultiplyHigh {
|
||||
signed: bool,
|
||||
},
|
||||
}
|
||||
|
||||
/// SOP1 unary operations decoded by the reference interpreter (RDNA 2 ISA
|
||||
/// guide 12.3; SCC per Tables 12 and 14).
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum ScalarUnary {
|
||||
/// D = ~S0, SCC = (D != 0).
|
||||
Not,
|
||||
/// D[31:0] = S0[0:31].
|
||||
ReverseBits,
|
||||
/// D = number of zero bits, SCC = (D != 0).
|
||||
CountZeros,
|
||||
/// D = number of one bits, SCC = (D != 0).
|
||||
CountOnes,
|
||||
/// D = index of the lowest zero bit, or -1.
|
||||
FindFirstZero,
|
||||
/// D = index of the lowest one bit, or -1.
|
||||
FindFirstOne,
|
||||
/// D = number of zeros above the highest one bit, or -1 for 0.
|
||||
FindLastBit,
|
||||
/// D = number of leading bits equal to the sign bit, or -1 for 0 and -1.
|
||||
FindLastSignBit,
|
||||
/// D = signext(S0[7:0]).
|
||||
SignExtendByte,
|
||||
/// D = signext(S0[15:0]).
|
||||
SignExtendShort,
|
||||
/// D = |S0| (0x80000000 stays), SCC = (D != 0).
|
||||
Absolute,
|
||||
}
|
||||
|
||||
/// VOP2 operations decoded by the reference interpreter.
|
||||
@@ -157,6 +239,90 @@ pub enum VectorAlu {
|
||||
FloatMultiply,
|
||||
}
|
||||
|
||||
/// VOP2 32-bit integer forms with a general SRC0 (AMD RDNA 2 ISA guide
|
||||
/// section 12.7). None has a carry-in or carry-out.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum VectorInteger {
|
||||
/// 9 / 11: D = low 32 bits of S0[23:0] * S1[23:0], sign-extended from
|
||||
/// bit 23 when `signed`.
|
||||
Multiply24 { signed: bool },
|
||||
/// 10 / 12: D = bits 63:32 of the same 48-bit product.
|
||||
MultiplyHigh24 { signed: bool },
|
||||
/// 17 / 19: D = S0 < S1 ? S0 : S1.
|
||||
Minimum { signed: bool },
|
||||
/// 18 / 20: D = S0 >= S1 ? S0 : S1.
|
||||
Maximum { signed: bool },
|
||||
/// 30: D = ~(S0 ^ S1).
|
||||
Xnor,
|
||||
/// 37: D = S0 + S1.
|
||||
Add,
|
||||
/// 38: D = S0 - S1.
|
||||
Subtract,
|
||||
/// 39: D = S1 - S0.
|
||||
SubtractReverse,
|
||||
}
|
||||
|
||||
impl VectorInteger {
|
||||
/// Opcode bits 30-25 of the VOP2 word.
|
||||
fn from_opcode(opcode: u8) -> Option<Self> {
|
||||
Some(match opcode {
|
||||
9 => Self::Multiply24 { signed: true },
|
||||
10 => Self::MultiplyHigh24 { signed: true },
|
||||
11 => Self::Multiply24 { signed: false },
|
||||
12 => Self::MultiplyHigh24 { signed: false },
|
||||
17 => Self::Minimum { signed: true },
|
||||
18 => Self::Maximum { signed: true },
|
||||
19 => Self::Minimum { signed: false },
|
||||
20 => Self::Maximum { signed: false },
|
||||
30 => Self::Xnor,
|
||||
37 => Self::Add,
|
||||
38 => Self::Subtract,
|
||||
39 => Self::SubtractReverse,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// D for S0 = `a`, S1 = `b`, from exact i64 arithmetic reduced modulo 2^32.
|
||||
fn apply(self, a: u32, b: u32) -> u32 {
|
||||
let field = |bits: u32, signed: bool| {
|
||||
if signed {
|
||||
i64::from(((bits << 8) as i32) >> 8)
|
||||
} else {
|
||||
i64::from(bits & 0x00ff_ffff)
|
||||
}
|
||||
};
|
||||
let widen = |bits: u32, signed: bool| {
|
||||
if signed {
|
||||
i64::from(bits as i32)
|
||||
} else {
|
||||
i64::from(bits)
|
||||
}
|
||||
};
|
||||
match self {
|
||||
Self::Multiply24 { signed } => (field(a, signed) * field(b, signed)) as u32,
|
||||
Self::MultiplyHigh24 { signed } => ((field(a, signed) * field(b, signed)) >> 32) as u32,
|
||||
Self::Minimum { signed } => {
|
||||
if widen(a, signed) < widen(b, signed) {
|
||||
a
|
||||
} else {
|
||||
b
|
||||
}
|
||||
}
|
||||
Self::Maximum { signed } => {
|
||||
if widen(a, signed) >= widen(b, signed) {
|
||||
a
|
||||
} else {
|
||||
b
|
||||
}
|
||||
}
|
||||
Self::Xnor => !(a ^ b),
|
||||
Self::Add => a.wrapping_add(b),
|
||||
Self::Subtract => a.wrapping_sub(b),
|
||||
Self::SubtractReverse => b.wrapping_sub(a),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Execute original little-endian gfx1030 bytes with the synthetic binding ABI.
|
||||
///
|
||||
/// Each dispatched lane reads the corresponding input word and may write only
|
||||
@@ -277,32 +443,90 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
|
||||
let (source, length) = decode_scalar(*source, tail, offset)?;
|
||||
(Op::ScalarMove(destination & 0x7f, source), length)
|
||||
}
|
||||
[left, right, 6, 0xbf, tail @ ..] if (*left, *right) != (255, 255) => {
|
||||
// SOP1: ENCODING 0b10_1111101 in bits 23-31, SDST in 16-22 (s0-s105
|
||||
// only), OP in 8-15.
|
||||
[
|
||||
source,
|
||||
op @ (7 | 11 | 13 | 15 | 17 | 19 | 21 | 23 | 25 | 26 | 52),
|
||||
destination @ 0x80..=0xe9,
|
||||
0xbe,
|
||||
tail @ ..,
|
||||
] => {
|
||||
let kind = match op {
|
||||
7 => ScalarUnary::Not,
|
||||
11 => ScalarUnary::ReverseBits,
|
||||
13 => ScalarUnary::CountZeros,
|
||||
15 => ScalarUnary::CountOnes,
|
||||
17 => ScalarUnary::FindFirstZero,
|
||||
19 => ScalarUnary::FindFirstOne,
|
||||
21 => ScalarUnary::FindLastBit,
|
||||
23 => ScalarUnary::FindLastSignBit,
|
||||
25 => ScalarUnary::SignExtendByte,
|
||||
26 => ScalarUnary::SignExtendShort,
|
||||
_ => ScalarUnary::Absolute,
|
||||
};
|
||||
let (source, length) = decode_scalar(*source, tail, offset)?;
|
||||
(Op::ScalarUnary(kind, destination & 0x7f, source), length)
|
||||
}
|
||||
// SOPC: ENCODING 0b10_1111110 in bits 23-31, OP in 16-22 (guide
|
||||
// 13.1.4); 0-5 signed and 6-11 unsigned EQ, LG, GT, GE, LT, LE.
|
||||
[left, right, op @ 0..=11, 0xbf, tail @ ..] if (*left, *right) != (255, 255) => {
|
||||
let (left, left_length) = decode_scalar(*left, tail, offset)?;
|
||||
let (right, right_length) = decode_scalar(*right, tail, offset)?;
|
||||
(Op::CompareEqual(left, right), left_length.max(right_length))
|
||||
// VOPC relation offsets: LT 1, EQ 2, LE 3, GT 4, NE 5, GE 6.
|
||||
let relation = [2, 5, 4, 6, 1, 3][usize::from(op % 6)];
|
||||
let comparison = Comparison {
|
||||
offset: relation,
|
||||
signed: *op < 6,
|
||||
};
|
||||
let op = if relation == 2 {
|
||||
Op::CompareEqual(left, right)
|
||||
} else {
|
||||
Op::ScalarCompare(comparison, left, right)
|
||||
};
|
||||
(op, left_length.max(right_length))
|
||||
}
|
||||
// SOP2: OP in bits 23-29, SDST in bits 16-22, SSRC1, SSRC0.
|
||||
[
|
||||
left,
|
||||
right,
|
||||
low,
|
||||
high @ (0x80..=0x82 | 0x87 | 0x88 | 0x89),
|
||||
tail @ ..,
|
||||
] if (*left, *right) != (255, 255)
|
||||
&& low & 0x7f <= 105
|
||||
&& (low & 0x80 == 0 || matches!(high, 0x80..=0x82)) =>
|
||||
[left, right, low, high @ 0x80..=0xbf, tail @ ..]
|
||||
if (*left, *right) != (255, 255)
|
||||
&& low & 0x7f <= 105
|
||||
&& matches!(
|
||||
(high & 0x3f) << 1 | low >> 7,
|
||||
0..=10 | 14 | 16 | 18 | 20 | 22 | 24 | 26 | 28 | 30 | 32 | 34
|
||||
| 36 | 38..=40 | 44 | 46..=49 | 53 | 54
|
||||
) =>
|
||||
{
|
||||
let kind = match (high, low >> 7) {
|
||||
(0x80, 0) => ScalarAlu::Add,
|
||||
(0x80, _) => ScalarAlu::Subtract,
|
||||
(0x81, 0) => ScalarAlu::AddSigned,
|
||||
(0x81, _) => ScalarAlu::SubtractSigned,
|
||||
(0x82, 0) => ScalarAlu::AddWithCarry,
|
||||
(0x82, _) => ScalarAlu::SubtractWithBorrow,
|
||||
(0x87, _) => ScalarAlu::And,
|
||||
(0x88, _) => ScalarAlu::Or,
|
||||
_ => ScalarAlu::Xor,
|
||||
let kind = match (high & 0x3f) << 1 | low >> 7 {
|
||||
0 => ScalarAlu::Add,
|
||||
1 => ScalarAlu::Subtract,
|
||||
2 => ScalarAlu::AddSigned,
|
||||
3 => ScalarAlu::SubtractSigned,
|
||||
4 => ScalarAlu::AddWithCarry,
|
||||
5 => ScalarAlu::SubtractWithBorrow,
|
||||
6 => ScalarAlu::Minimum { signed: true },
|
||||
7 => ScalarAlu::Minimum { signed: false },
|
||||
8 => ScalarAlu::Maximum { signed: true },
|
||||
9 => ScalarAlu::Maximum { signed: false },
|
||||
10 => ScalarAlu::Select,
|
||||
14 => ScalarAlu::And,
|
||||
16 => ScalarAlu::Or,
|
||||
18 => ScalarAlu::Xor,
|
||||
20 => ScalarAlu::AndNot,
|
||||
22 => ScalarAlu::OrNot,
|
||||
24 => ScalarAlu::Nand,
|
||||
26 => ScalarAlu::Nor,
|
||||
28 => ScalarAlu::Xnor,
|
||||
30 => ScalarAlu::ShiftLeft,
|
||||
32 => ScalarAlu::ShiftRight,
|
||||
34 => ScalarAlu::ArithmeticShiftRight,
|
||||
36 => ScalarAlu::BitfieldMask,
|
||||
38 => ScalarAlu::Multiply,
|
||||
39 => ScalarAlu::BitfieldExtract { signed: false },
|
||||
40 => ScalarAlu::BitfieldExtract { signed: true },
|
||||
44 => ScalarAlu::AbsoluteDifference,
|
||||
op @ 46..=49 => ScalarAlu::ShiftLeftAdd(op - 45),
|
||||
53 => ScalarAlu::MultiplyHigh { signed: false },
|
||||
_ => ScalarAlu::MultiplyHigh { signed: true },
|
||||
};
|
||||
let (left, left_length) = decode_scalar(*left, tail, offset)?;
|
||||
let (right, right_length) = decode_scalar(*right, tail, offset)?;
|
||||
@@ -364,25 +588,22 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
|
||||
signed: opcode < 192,
|
||||
};
|
||||
let vsrc1 = (packed >> 1) | ((upper & 1) << 7);
|
||||
let selector = u16::from(*lo) | (u16::from(packed & 1) << 8);
|
||||
let (src0, length) = match selector {
|
||||
0..=106 => (CompareSource::Scalar(*lo), 4),
|
||||
128..=192 => (CompareSource::Immediate(u32::from(selector - 128)), 4),
|
||||
193..=208 => (
|
||||
CompareSource::Immediate(0_u32.wrapping_sub(u32::from(selector - 192))),
|
||||
4,
|
||||
),
|
||||
255 => {
|
||||
let literal = tail
|
||||
.first_chunk::<4>()
|
||||
.ok_or_else(|| error(offset, "truncated literal"))?;
|
||||
(CompareSource::Immediate(u32::from_le_bytes(*literal)), 8)
|
||||
}
|
||||
256..=511 => (CompareSource::Vector(*lo), 4),
|
||||
_ => return Err(error(offset, "unsupported VOPC source")),
|
||||
};
|
||||
let (src0, length) =
|
||||
decode_vector_source(*lo, *packed, tail, offset, "unsupported VOPC source")?;
|
||||
(Op::Compare(comparison, src0, vsrc1), length)
|
||||
}
|
||||
// VOP2 integer forms (bit 31 = 0): OP bits 25-30, VDST 17-24,
|
||||
// VSRC1 9-16, SRC0 0-8.
|
||||
[lo, packed, upper, tag @ 0x00..=0x7b, tail @ ..]
|
||||
if VectorInteger::from_opcode(tag >> 1).is_some() =>
|
||||
{
|
||||
let kind = VectorInteger::from_opcode(tag >> 1).unwrap();
|
||||
let dst = (upper >> 1) | ((tag & 1) << 7);
|
||||
let vsrc1 = (packed >> 1) | ((upper & 1) << 7);
|
||||
let (src0, length) =
|
||||
decode_vector_source(*lo, *packed, tail, offset, "unsupported VOP2 source")?;
|
||||
(Op::VectorInteger(kind, dst, src0, vsrc1), length)
|
||||
}
|
||||
[lo, packed, upper, tag @ 0x7e..=0x7f, tail @ ..]
|
||||
if packed & 0xfe == 2 && upper & 1 == 0 =>
|
||||
{
|
||||
@@ -467,6 +688,34 @@ fn decode_scalar(
|
||||
}
|
||||
}
|
||||
|
||||
/// A vector SRC0 selector (bits 0-8: `lo` and bit 0 of `packed`): s0-s105 or
|
||||
/// `vcc_lo` (106), an inline integer, a literal dword from `tail`, or a VGPR.
|
||||
fn decode_vector_source(
|
||||
lo: u8,
|
||||
packed: u8,
|
||||
tail: &[u8],
|
||||
offset: usize,
|
||||
unsupported: &'static str,
|
||||
) -> Result<(CompareSource, usize), ReferenceError> {
|
||||
let selector = u16::from(lo) | (u16::from(packed & 1) << 8);
|
||||
Ok(match selector {
|
||||
0..=106 => (CompareSource::Scalar(lo), 4),
|
||||
128..=192 => (CompareSource::Immediate(u32::from(selector - 128)), 4),
|
||||
193..=208 => (
|
||||
CompareSource::Immediate(0_u32.wrapping_sub(u32::from(selector - 192))),
|
||||
4,
|
||||
),
|
||||
255 => {
|
||||
let literal = tail
|
||||
.first_chunk::<4>()
|
||||
.ok_or_else(|| error(offset, "truncated literal"))?;
|
||||
(CompareSource::Immediate(u32::from_le_bytes(*literal)), 8)
|
||||
}
|
||||
256..=511 => (CompareSource::Vector(lo), 4),
|
||||
_ => return Err(error(offset, unsupported)),
|
||||
})
|
||||
}
|
||||
|
||||
fn vector_alu(op: VectorAlu, a: u32, b: u32, offset: usize) -> Result<u32, ReferenceError> {
|
||||
let error = || {
|
||||
error(
|
||||
@@ -557,7 +806,8 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
|
||||
Op::Move(dst, _)
|
||||
| Op::MoveScalar(dst, _)
|
||||
| Op::Add(dst, ..)
|
||||
| Op::Vector(_, dst, ..) => {
|
||||
| Op::Vector(_, dst, ..)
|
||||
| Op::VectorInteger(_, dst, ..) => {
|
||||
if exec != 0
|
||||
&& registers
|
||||
.iter()
|
||||
@@ -639,6 +889,31 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
|
||||
results[lane] = Some((dst, value));
|
||||
}
|
||||
}
|
||||
Op::VectorInteger(kind, dst, src0, src1) => {
|
||||
if exec != 0 {
|
||||
// As for a compare, sources are checked once for the wave,
|
||||
// whichever present lanes are active.
|
||||
let check = |register: u8| {
|
||||
(0..lanes).try_for_each(|lane| read(lane, register).map(|_| ()))
|
||||
};
|
||||
match src0 {
|
||||
CompareSource::Vector(register) => check(register)?,
|
||||
CompareSource::Scalar(register) => {
|
||||
read_scalar(Source::Register(register))?;
|
||||
}
|
||||
CompareSource::Immediate(_) => {}
|
||||
}
|
||||
check(src1)?;
|
||||
}
|
||||
for lane in (0..lanes).filter(|&lane| executes(lane)) {
|
||||
let s0 = match src0 {
|
||||
CompareSource::Vector(register) => read(lane, register)?,
|
||||
CompareSource::Scalar(register) => read_scalar(Source::Register(register))?,
|
||||
CompareSource::Immediate(bits) => bits,
|
||||
};
|
||||
results[lane] = Some((dst, kind.apply(s0, read(lane, src1)?)));
|
||||
}
|
||||
}
|
||||
Op::ScalarMove(dst, src) => {
|
||||
if dst < 8 {
|
||||
return Err(error(offset, "write to a reserved resource SGPR"));
|
||||
@@ -652,9 +927,51 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
|
||||
}
|
||||
scalars[usize::from(dst)] = Some(value);
|
||||
}
|
||||
Op::ScalarUnary(kind, dst, src) => {
|
||||
if dst < 8 {
|
||||
return Err(error(offset, "write to a reserved resource SGPR"));
|
||||
}
|
||||
let value = read_scalar(src)?;
|
||||
// -1 (all ones) when no bit is found.
|
||||
let found = |index: u32| if index == 32 { u32::MAX } else { index };
|
||||
let result = match kind {
|
||||
ScalarUnary::Not => !value,
|
||||
ScalarUnary::ReverseBits => value.reverse_bits(),
|
||||
ScalarUnary::CountZeros => value.count_zeros(),
|
||||
ScalarUnary::CountOnes => value.count_ones(),
|
||||
ScalarUnary::FindFirstZero => found(value.trailing_ones()),
|
||||
ScalarUnary::FindFirstOne => found(value.trailing_zeros()),
|
||||
ScalarUnary::FindLastBit => found(value.leading_zeros()),
|
||||
ScalarUnary::FindLastSignBit => {
|
||||
let same = if value >> 31 == 1 {
|
||||
value.leading_ones()
|
||||
} else {
|
||||
value.leading_zeros()
|
||||
};
|
||||
found(same)
|
||||
}
|
||||
ScalarUnary::SignExtendByte => value as u8 as i8 as i32 as u32,
|
||||
ScalarUnary::SignExtendShort => value as u16 as i16 as i32 as u32,
|
||||
ScalarUnary::Absolute => (value as i32).wrapping_abs() as u32,
|
||||
};
|
||||
scalars[usize::from(dst)] = Some(result);
|
||||
if matches!(
|
||||
kind,
|
||||
ScalarUnary::Not
|
||||
| ScalarUnary::CountZeros
|
||||
| ScalarUnary::CountOnes
|
||||
| ScalarUnary::Absolute
|
||||
) {
|
||||
scc = Some(result != 0);
|
||||
}
|
||||
}
|
||||
Op::CompareEqual(lhs, rhs) => {
|
||||
scc = Some(read_scalar(lhs)? == read_scalar(rhs)?);
|
||||
}
|
||||
// Guide 12.4: SCC = (S0 <relation> S1); no SGPR is written.
|
||||
Op::ScalarCompare(comparison, lhs, rhs) => {
|
||||
scc = Some(comparison.holds(read_scalar(lhs)?, read_scalar(rhs)?));
|
||||
}
|
||||
Op::Scalar(kind, dst, lhs, rhs) => {
|
||||
if dst < 8 {
|
||||
return Err(error(offset, "write to a reserved resource SGPR"));
|
||||
@@ -664,8 +981,13 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
|
||||
ScalarAlu::AddWithCarry | ScalarAlu::SubtractWithBorrow => i64::from(
|
||||
scc.ok_or_else(|| error(offset, "carry-in from uninitialized SCC"))?,
|
||||
),
|
||||
ScalarAlu::Select => {
|
||||
i64::from(scc.ok_or_else(|| error(offset, "select on uninitialized SCC"))?)
|
||||
}
|
||||
_ => 0,
|
||||
};
|
||||
let (signed_lhs, signed_rhs) =
|
||||
(i64::from(lhs as u32 as i32), i64::from(rhs as u32 as i32));
|
||||
// Exact integer arithmetic, then reduction modulo 2^32.
|
||||
let (exact, flag) = match kind {
|
||||
ScalarAlu::Add | ScalarAlu::AddWithCarry => {
|
||||
@@ -694,10 +1016,93 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
|
||||
};
|
||||
(bits, bits != 0)
|
||||
}
|
||||
// Guide 12.1: strict comparisons, so equal operands give
|
||||
// S1 (the same value) and SCC = 0.
|
||||
ScalarAlu::Minimum { signed } | ScalarAlu::Maximum { signed } => {
|
||||
let (a, b) = if signed {
|
||||
(signed_lhs, signed_rhs)
|
||||
} else {
|
||||
(lhs, rhs)
|
||||
};
|
||||
let first = if matches!(kind, ScalarAlu::Minimum { .. }) {
|
||||
a < b
|
||||
} else {
|
||||
a > b
|
||||
};
|
||||
(if first { lhs } else { rhs }, first)
|
||||
}
|
||||
// The SCC-less forms; `flag` is unused for them below.
|
||||
ScalarAlu::Select => (if carry == 1 { lhs } else { rhs }, false),
|
||||
ScalarAlu::BitfieldMask => (((1 << (lhs & 0x1f)) - 1) << (rhs & 0x1f), false),
|
||||
ScalarAlu::Multiply => (signed_lhs * signed_rhs, false),
|
||||
ScalarAlu::MultiplyHigh { signed } => {
|
||||
// The unsigned product fits only in u64.
|
||||
let high = if signed {
|
||||
(signed_lhs * signed_rhs) >> 32
|
||||
} else {
|
||||
((lhs as u64 * rhs as u64) >> 32) as i64
|
||||
};
|
||||
(high, false)
|
||||
}
|
||||
// Offset S1[4:0], width S1[22:16] (0-127). A width of 32 or
|
||||
// more keeps every bit of the shifted word.
|
||||
ScalarAlu::BitfieldExtract { signed } => {
|
||||
let (shift, width) = (rhs & 0x1f, (rhs >> 16) & 0x7f);
|
||||
let data = if signed { signed_lhs } else { lhs };
|
||||
let shifted = data >> shift;
|
||||
let value = if width == 0 {
|
||||
0
|
||||
} else if width >= 32 {
|
||||
shifted
|
||||
} else {
|
||||
let field = shifted & ((1 << width) - 1);
|
||||
if signed && field >> (width - 1) == 1 {
|
||||
field - (1 << width)
|
||||
} else {
|
||||
field
|
||||
}
|
||||
};
|
||||
(value, value.rem_euclid(1 << 32) != 0)
|
||||
}
|
||||
// The 32-bit difference first (guide examples), then |D|.
|
||||
ScalarAlu::AbsoluteDifference => {
|
||||
let difference = (signed_lhs - signed_rhs) as u32 as i32;
|
||||
let value = difference.unsigned_abs();
|
||||
(i64::from(value), value != 0)
|
||||
}
|
||||
// The carry out of the exact (S0 << N) + S1.
|
||||
ScalarAlu::ShiftLeftAdd(n) => {
|
||||
let sum = (lhs << n) + rhs;
|
||||
(sum, sum >= 1 << 32)
|
||||
}
|
||||
// Guide 12.1: shifts use only S1[4:0]; all set SCC = (D != 0).
|
||||
_ => {
|
||||
let (a, b) = (lhs as u32, rhs as u32);
|
||||
let bits = match kind {
|
||||
ScalarAlu::AndNot => a & !b,
|
||||
ScalarAlu::OrNot => a | !b,
|
||||
ScalarAlu::Nand => !(a & b),
|
||||
ScalarAlu::Nor => !(a | b),
|
||||
ScalarAlu::Xnor => !(a ^ b),
|
||||
ScalarAlu::ShiftLeft => a << (b & 0x1f),
|
||||
ScalarAlu::ShiftRight => a >> (b & 0x1f),
|
||||
_ => ((a as i32) >> (b & 0x1f)) as u32,
|
||||
};
|
||||
(i64::from(bits), bits != 0)
|
||||
}
|
||||
};
|
||||
let value = exact.rem_euclid(1 << 32) as u32;
|
||||
scalars[usize::from(dst)] = Some(value);
|
||||
scc = Some(flag);
|
||||
// Guide 12.1 and Tables 11, 12, 14: these forms leave SCC unchanged.
|
||||
if !matches!(
|
||||
kind,
|
||||
ScalarAlu::Select
|
||||
| ScalarAlu::BitfieldMask
|
||||
| ScalarAlu::Multiply
|
||||
| ScalarAlu::MultiplyHigh { .. }
|
||||
) {
|
||||
scc = Some(flag);
|
||||
}
|
||||
}
|
||||
// RDNA 2 ISA section 3.9: VCC[n] = EXEC[n] & test(n), fully written.
|
||||
Op::Compare(comparison, src0, src1) => {
|
||||
|
||||
+132
-10
@@ -9,7 +9,8 @@ pub use graphics::{PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
|
||||
|
||||
pub use xenora_decoder::Architecture;
|
||||
use xenora_decoder::{
|
||||
DecodeError, DecodedInstruction, Instruction, ScalarSource, VectorCompareOp, VectorSource,
|
||||
DecodeError, DecodedInstruction, Instruction, ScalarSource, VectorBinary, VectorCompareOp,
|
||||
VectorSource,
|
||||
};
|
||||
|
||||
/// SGPR index of `vcc_lo`.
|
||||
@@ -161,6 +162,7 @@ impl Op {
|
||||
Binary::ShiftLeft | Binary::ShiftRight => {
|
||||
format!("{left} {symbol} ({right} & 31u)")
|
||||
}
|
||||
Binary::Vector(operation) => vector_expression(operation, &left, &right),
|
||||
_ => format!("{left} {symbol} {right}"),
|
||||
}
|
||||
}
|
||||
@@ -219,6 +221,8 @@ enum Binary {
|
||||
Xor,
|
||||
FloatAdd,
|
||||
FloatMul,
|
||||
/// A registry VOP2 integer operation, lowered by its typed template.
|
||||
Vector(VectorBinary),
|
||||
}
|
||||
|
||||
impl Binary {
|
||||
@@ -233,10 +237,56 @@ impl Binary {
|
||||
Self::Xor => ("xor.b32", "^"),
|
||||
Self::FloatAdd => ("add.f32", "+"),
|
||||
Self::FloatMul => ("mul.f32", "*"),
|
||||
Self::Vector(operation) => (
|
||||
match operation {
|
||||
VectorBinary::Add => "add.u32",
|
||||
VectorBinary::Sub => "sub.u32",
|
||||
VectorBinary::Xnor => "xnor.b32",
|
||||
VectorBinary::MinSigned => "min.i32",
|
||||
VectorBinary::MinUnsigned => "min.u32",
|
||||
VectorBinary::MaxSigned => "max.i32",
|
||||
VectorBinary::MaxUnsigned => "max.u32",
|
||||
VectorBinary::Mul24Signed => "mul24.i32",
|
||||
VectorBinary::Mul24Unsigned => "mul24.u32",
|
||||
VectorBinary::MulHi24Signed => "mulhi24.i32",
|
||||
VectorBinary::MulHi24Unsigned => "mulhi24.u32",
|
||||
},
|
||||
"",
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The MSL template of each per-lane registry operation. Integer arithmetic is
|
||||
/// on `uint` (wrapping); signed forms reinterpret with `as_type`, and the
|
||||
/// 24-bit forms sign-extend bit 23 with a shift pair or mask to 24 bits first.
|
||||
fn vector_expression(operation: VectorBinary, left: &str, right: &str) -> String {
|
||||
let int = |value: &str| format!("as_type<int>({value})");
|
||||
let i24 = |value: &str| format!("(as_type<int>({value} << 8u) >> 8)");
|
||||
let u24 = |value: &str| format!("({value} & 0x00ffffffu)");
|
||||
match operation {
|
||||
VectorBinary::Add => format!("{left} + {right}"),
|
||||
VectorBinary::Sub => format!("{left} - {right}"),
|
||||
VectorBinary::Xnor => format!("~({left} ^ {right})"),
|
||||
VectorBinary::MinSigned => format!("as_type<uint>(min({}, {}))", int(left), int(right)),
|
||||
VectorBinary::MinUnsigned => format!("min({left}, {right})"),
|
||||
VectorBinary::MaxSigned => format!("as_type<uint>(max({}, {}))", int(left), int(right)),
|
||||
VectorBinary::MaxUnsigned => format!("max({left}, {right})"),
|
||||
// The low 32 bits of a product do not depend on signedness, so the
|
||||
// sign-extended factors multiply as wrapping uint.
|
||||
VectorBinary::Mul24Signed => format!(
|
||||
"as_type<uint>({}) * as_type<uint>({})",
|
||||
i24(left),
|
||||
i24(right)
|
||||
),
|
||||
VectorBinary::Mul24Unsigned => format!("{} * {}", u24(left), u24(right)),
|
||||
VectorBinary::MulHi24Signed => {
|
||||
format!("as_type<uint>(mulhi({}, {}))", i24(left), i24(right))
|
||||
}
|
||||
VectorBinary::MulHi24Unsigned => format!("mulhi({}, {})", u24(left), u24(right)),
|
||||
}
|
||||
}
|
||||
|
||||
// Each bit is either known zero, known one or unconstrained.
|
||||
#[derive(Clone, Copy)]
|
||||
struct KnownBits {
|
||||
@@ -632,7 +682,7 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
| Instruction::VectorXorB32 { dst, .. } => dst,
|
||||
_ => {
|
||||
return Err(error(
|
||||
"code skipped by a runtime s_cbranch_vccz may contain only integer vector ALU instructions",
|
||||
"code skipped by a runtime s_cbranch_vccz may contain only v_mov_b32, v_add_nc_u32_e64 and the hand-written integer VOP2 forms",
|
||||
));
|
||||
}
|
||||
};
|
||||
@@ -670,7 +720,8 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
| Instruction::VectorOrB32 { .. }
|
||||
| Instruction::VectorXorB32 { .. }
|
||||
| Instruction::VectorAddF32 { .. }
|
||||
| Instruction::VectorMulF32 { .. } => continue,
|
||||
| Instruction::VectorMulF32 { .. }
|
||||
| Instruction::VectorAlu { .. } => continue,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -809,6 +860,21 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
*slot = Some(value);
|
||||
continue;
|
||||
}
|
||||
Instruction::ScalarUnary { op, dst, src } => {
|
||||
let src = read_scalar(src)?;
|
||||
if dst < 8 {
|
||||
return Err(error("scalar unary would modify a resource descriptor"));
|
||||
}
|
||||
let (value, flag) = op.evaluate(src);
|
||||
let slot = scalars
|
||||
.get_mut(usize::from(dst))
|
||||
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
|
||||
*slot = Some(value);
|
||||
if let Some(flag) = flag {
|
||||
scc = Some(flag);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Instruction::ScalarAlu {
|
||||
op,
|
||||
dst,
|
||||
@@ -816,24 +882,26 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
src1,
|
||||
} => {
|
||||
let (src0, src1) = (read_scalar(src0)?, read_scalar(src1)?);
|
||||
let carry_in = if op.reads_scc() {
|
||||
scc.ok_or_else(|| error("carry-in or borrow-in reads uninitialized SCC"))?
|
||||
let scc_in = if op.reads_scc() {
|
||||
scc.ok_or_else(|| error("SOP2 SCC input reads uninitialized SCC"))?
|
||||
} else {
|
||||
false
|
||||
};
|
||||
if dst < 8 {
|
||||
return Err(error("scalar ALU would modify a resource descriptor"));
|
||||
}
|
||||
let (value, flag) = op.evaluate(src0, src1, carry_in);
|
||||
let (value, flag) = op.evaluate(src0, src1, scc_in);
|
||||
let slot = scalars
|
||||
.get_mut(usize::from(dst))
|
||||
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
|
||||
*slot = Some(value);
|
||||
scc = Some(flag);
|
||||
if let Some(flag) = flag {
|
||||
scc = Some(flag);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Instruction::ScalarCompareEqU32 { src0, src1 } => {
|
||||
scc = Some(read_scalar(src0)? == read_scalar(src1)?);
|
||||
Instruction::ScalarCompare { op, src0, src1 } => {
|
||||
scc = Some(op.test(read_scalar(src0)?, read_scalar(src1)?));
|
||||
continue;
|
||||
}
|
||||
// docs/shaders/vector-compare.md sections 3 and 5.
|
||||
@@ -923,6 +991,44 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
},
|
||||
)
|
||||
}
|
||||
Instruction::VectorAlu {
|
||||
op,
|
||||
dst,
|
||||
src0,
|
||||
src1,
|
||||
} => {
|
||||
let src0 = match src0 {
|
||||
VectorSource::Register(register) => read(register)?,
|
||||
VectorSource::Scalar(register) if usize::from(register) == VCC_LO => {
|
||||
match (lane_vcc, scalars[VCC_LO]) {
|
||||
(Some(mask), _) => mask,
|
||||
(None, Some(bits)) => {
|
||||
constant(&mut operations, &mut facts, offset, bits)
|
||||
}
|
||||
(None, None) => {
|
||||
return Err(error("vector ALU reads uninitialized VCC_LO"));
|
||||
}
|
||||
}
|
||||
}
|
||||
VectorSource::Scalar(register) => {
|
||||
let bits = read_scalar(ScalarSource::Register(register))?;
|
||||
constant(&mut operations, &mut facts, offset, bits)
|
||||
}
|
||||
VectorSource::Immediate(bits) => {
|
||||
constant(&mut operations, &mut facts, offset, bits)
|
||||
}
|
||||
};
|
||||
let src1 = read(src1)?;
|
||||
let (left, right) = if op.swaps_sources() {
|
||||
(src1, src0)
|
||||
} else {
|
||||
(src0, src1)
|
||||
};
|
||||
(
|
||||
Some(dst),
|
||||
Op::Binary(Binary::Vector(op.lowering()), left, right),
|
||||
)
|
||||
}
|
||||
Instruction::VectorAddF32 { dst, src0, src1 } => (
|
||||
Some(dst),
|
||||
Op::Binary(Binary::FloatAdd, read(src0)?, read(src1)?),
|
||||
@@ -958,6 +1064,9 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
}
|
||||
_ => KnownBits::UNKNOWN,
|
||||
};
|
||||
// Arms may push operand constants first, so the result is the next slot
|
||||
// now rather than `next`.
|
||||
let produced = Value(operations.len());
|
||||
facts.push(value_bits);
|
||||
operations.push((offset, operation));
|
||||
if let Some(dest) = dest {
|
||||
@@ -972,7 +1081,7 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
&mut facts,
|
||||
offset,
|
||||
exec,
|
||||
next,
|
||||
produced,
|
||||
registers[slot],
|
||||
)?);
|
||||
}
|
||||
@@ -983,6 +1092,19 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
|
||||
})
|
||||
}
|
||||
|
||||
/// A wave-uniform constant operand at `offset`.
|
||||
fn constant(
|
||||
operations: &mut Vec<(usize, Op)>,
|
||||
facts: &mut Vec<KnownBits>,
|
||||
offset: usize,
|
||||
bits: u32,
|
||||
) -> Value {
|
||||
let value = Value(operations.len());
|
||||
operations.push((offset, Op::Constant(bits)));
|
||||
facts.push(KnownBits::constant(bits));
|
||||
value
|
||||
}
|
||||
|
||||
// Keeping a value for inactive lanes requires a previously initialized destination.
|
||||
fn merge_lanes(
|
||||
operations: &mut Vec<(usize, Op)>,
|
||||
|
||||
@@ -280,6 +280,76 @@ fn scalar_alu_results_reach_the_kernel_as_constants() {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_logic_results_reach_the_kernel_as_constants() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/scalar-logic.bin");
|
||||
let compiled = compile(Architecture::Gfx1030, code).unwrap();
|
||||
assert_eq!(
|
||||
compiled.ir,
|
||||
include_str!("../../../fixtures/golden/scalar-logic.ir")
|
||||
);
|
||||
assert_eq!(
|
||||
compiled.msl,
|
||||
include_str!("../../../fixtures/golden/scalar-logic.metal")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_compare_results_resolve_every_branch() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/scalar-compare.bin");
|
||||
let compiled = compile(Architecture::Gfx1030, code).unwrap();
|
||||
assert_eq!(
|
||||
compiled.ir,
|
||||
include_str!("../../../fixtures/golden/scalar-compare.ir")
|
||||
);
|
||||
assert_eq!(
|
||||
compiled.msl,
|
||||
include_str!("../../../fixtures/golden/scalar-compare.metal")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_unary_results_reach_the_kernel_as_constants() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/scalar-unary.bin");
|
||||
let compiled = compile(Architecture::Gfx1030, code).unwrap();
|
||||
assert_eq!(
|
||||
compiled.ir,
|
||||
include_str!("../../../fixtures/golden/scalar-unary.ir")
|
||||
);
|
||||
assert_eq!(
|
||||
compiled.msl,
|
||||
include_str!("../../../fixtures/golden/scalar-unary.metal")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalar_arith_results_reach_the_kernel_as_constants() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/scalar-arith.bin");
|
||||
let compiled = compile(Architecture::Gfx1030, code).unwrap();
|
||||
assert_eq!(
|
||||
compiled.ir,
|
||||
include_str!("../../../fixtures/golden/scalar-arith.ir")
|
||||
);
|
||||
assert_eq!(
|
||||
compiled.msl,
|
||||
include_str!("../../../fixtures/golden/scalar-arith.metal")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_integer_forms_lower_to_per_lane_templates() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/vector-integer.bin");
|
||||
let compiled = compile(Architecture::Gfx1030, code).unwrap();
|
||||
assert_eq!(
|
||||
compiled.ir,
|
||||
include_str!("../../../fixtures/golden/vector-integer.ir")
|
||||
);
|
||||
assert_eq!(
|
||||
compiled.msl,
|
||||
include_str!("../../../fixtures/golden/vector-integer.metal")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_compares_lower_to_per_thread_wave_masks_and_selects() {
|
||||
let code = include_bytes!("../../../fixtures/rdna2/vector-compare.bin");
|
||||
|
||||
@@ -31,6 +31,8 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
|
||||
## Guest CPU and runtime experiments
|
||||
|
||||
- [Guest experiment guide](../experiments/x1/README.md) — Bounded x86-64 execution, executable loading, experimental services, native compute, and offscreen rendering.
|
||||
- [x86-64 instruction registry](cpu/instruction-registry.md) — Shared decoder, generated tables, semantics, native lowering and how to add a verified instruction form.
|
||||
- [Runtime service registry](runtime/registry.md) and [generated coverage](runtime/services.md) — Import resolution, typed Win64 adapters and how to add a tested service.
|
||||
- [Guest CPU research](research/cpu-boundary.md) — Public specifications and unresolved console requirements.
|
||||
- [Synthetic import fixtures](../tests/compat_fixtures/README.md) — Reproducible PE32+ builds and expected service behavior.
|
||||
|
||||
@@ -54,3 +56,7 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
|
||||
- [Legal scope](legal.md), [dependency licensing](licenses.md), and [third-party notices](../THIRD_PARTY_NOTICES.md) — Input policy, attribution, and redistribution findings.
|
||||
- [Contribution guidelines](../CONTRIBUTING.md) — Original authorship, Developer Certificate of Origin sign-off, and evidence requirements.
|
||||
- [Agent task queue](coordination/agent-tasks.md) — Areas, claiming, leases, upstream sync, verification and the security model for parallel contributors and coding agents.
|
||||
- [CPU/runtime expansion campaign ledger](coordination/cpu-campaign-ledger.md) — Progress ledger for the Xenora native CPU and runtime compatibility campaign: starting/current commits, completed batches, new forms, verification evidence and the next implementation target.
|
||||
- [Infrastructure QA ownership](coordination/infrastructure-qa-ownership.md) — Non-overlapping paths for infrastructure and QA tooling.
|
||||
- [Agent queue smoke evidence](coordination/agent-queue-smoke.md) — Live Actions results from the disposable smoke repository.
|
||||
- [Infrastructure QA tooling](testing/infrastructure/README.md) — Advisory orchestration, PR validation, benchmark analysis and release checks.
|
||||
@@ -1,17 +1,17 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="530" height="185" viewBox="0 0 530 185" role="img" aria-labelledby="title description">
|
||||
<title id="title">Xenora · recorded progress</title>
|
||||
<desc id="description">Decoded gfx1030 forms: 42 of 42. Accepted Metal forms · Apple M5: 18 of 42. Accepted guest milestones · X1–X4: 4 of 4</desc>
|
||||
<desc id="description">Decoded gfx1030 forms: 100 of 100. Accepted Metal forms · Apple M5: 18 of 100. Accepted guest milestones · X1–X4: 4 of 4</desc>
|
||||
<rect x="1" y="1" width="528" height="183" rx="10" fill="#18212a" stroke="#516171"/>
|
||||
<g font-family="system-ui,sans-serif" fill="#eaf0f5">
|
||||
<text x="20" y="29" font-size="13" font-weight="700">RECORDED FIXTURE PROGRESS</text>
|
||||
<text x="20" y="58" font-size="13">Decoded gfx1030 forms</text>
|
||||
<text x="510" y="58" font-size="13" text-anchor="end">42 / 42</text>
|
||||
<text x="510" y="58" font-size="13" text-anchor="end">100 / 100</text>
|
||||
<rect x="20" y="65" width="490" height="4" rx="2" fill="#3c4a58"/>
|
||||
<rect x="20" y="65" width="490.00" height="4" rx="2" fill="#88c6bd"/>
|
||||
<text x="20" y="96" font-size="13">Accepted Metal forms · Apple M5</text>
|
||||
<text x="510" y="96" font-size="13" text-anchor="end">18 / 42</text>
|
||||
<text x="510" y="96" font-size="13" text-anchor="end">18 / 100</text>
|
||||
<rect x="20" y="103" width="490" height="4" rx="2" fill="#3c4a58"/>
|
||||
<rect x="20" y="103" width="210.00" height="4" rx="2" fill="#88c6bd"/>
|
||||
<rect x="20" y="103" width="88.20" height="4" rx="2" fill="#88c6bd"/>
|
||||
<text x="20" y="134" font-size="13">Accepted guest milestones · X1–X4</text>
|
||||
<text x="510" y="134" font-size="13" text-anchor="end">4 / 4</text>
|
||||
<rect x="20" y="141" width="490" height="4" rx="2" fill="#3c4a58"/>
|
||||
|
||||
|
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 1.5 KiB |
@@ -0,0 +1,48 @@
|
||||
# Agent queue live smoke test
|
||||
|
||||
Issue: #180
|
||||
Disposable repository: [`ranveersoni98/xenora-agent-queue-smoke`](https://github.com/ranveersoni98/xenora-agent-queue-smoke) (private)
|
||||
Production Xenora workflows are not modified by this exercise except where a
|
||||
separate coordinated fix is recorded.
|
||||
|
||||
## Why a disposable repository
|
||||
|
||||
The queue unit suite does not call the GitHub API. Issue #180 requires Actions
|
||||
evidence for simultaneous claims, refusal, release, stale-lease audit behaviour,
|
||||
pending-run replay and exact head-SHA verification against a real repository.
|
||||
|
||||
## Harness notes
|
||||
|
||||
- Copies `scripts/agent_queue/`, the unit tests, `agent-queue.sh`,
|
||||
`agent-sync.sh` and the two agent workflows from Xenora.
|
||||
- Uses `ubuntu-latest` runners in the disposable repo only. Queue decisions are
|
||||
standard-library Python; production Xenora keeps `ubuntu-24.04-arm`.
|
||||
- Config upstream is `ranveersoni98/xenora-agent-queue-smoke`.
|
||||
|
||||
## Evidence log
|
||||
|
||||
| Scenario | Result | Evidence | Recorded |
|
||||
| --- | --- | --- | --- |
|
||||
| Claim grant on ready task | pass | issue #1 labels `agent:claimed,claimed-by:ranveersoni98`; run `45383910132` | 2026-11-24 |
|
||||
| Overlap claim refusal | pass | issue #2 bot: file overlap with claimed task #1; run `45384365386` | 2026-11-24 |
|
||||
| Disjoint second claim | pass | issue #3 claimed; run `45384367521` | 2026-11-24 |
|
||||
| `/progress` renew | pass | issue #1 bot: Lease renewed; run `45384473061` | 2026-11-24 |
|
||||
| `/release` | pass | issue #3 returned to `agent:ready`; bot release marker | 2026-11-24 |
|
||||
| Claim without `agent:ready` | pass | issue #4 refused: not labelled agent:ready | 2026-11-24 |
|
||||
| Comment-only apply crash | fixed | `ghio.apply_actions` skipped no-op `gh issue edit`; mirrored to smoke | 2026-11-24 |
|
||||
| Audit `workflow_dispatch` | pass | run `45385817420` after `pull-requests: read` and `summary --now` argparse fix | 2026-11-24 |
|
||||
| Exact `/verified` head SHA | deferred | needs second eligible non-author account on the smoke repo | 2026-11-24 |
|
||||
| Full wall-clock stale lease | deferred | covered by unit tests with frozen clock (`lease_hours=168`) | 2026-11-24 |
|
||||
|
||||
## Production follow-ups
|
||||
|
||||
1. Keep `agent-pr-checks` advisory until this evidence is reviewed.
|
||||
2. Coordinate adding `pull-requests: read` to the production audit job permissions
|
||||
(same defect as the smoke audit failure).
|
||||
3. Add a second QA-eligible verifier before treating `/verified` as smoke-complete.
|
||||
|
||||
## Local unit suite
|
||||
|
||||
```sh
|
||||
PYTHONPATH=scripts python3 -m unittest discover -s tests/agent_queue
|
||||
```
|
||||
@@ -0,0 +1,128 @@
|
||||
# Xenora CPU/Runtime Expansion Campaign — Progress Ledger
|
||||
|
||||
Evidence below is local to the named host unless stated. Nothing here is independently reviewed yet.
|
||||
|
||||
## Continuation checkpoint
|
||||
|
||||
- Continuation branch base: `0836936` (tip of `feat/cpu-runtime-expansion`), merged with main `d22f046` (#272, #273, #274) as `56febbb`. The merge had no conflicts.
|
||||
- All recorded checkpoints (`a953ba9`, `9cd6f43`, `7e09c9c`, `bfd14e4`, `0836936`) exist upstream. The earlier session's uncommitted MOVSX patch was not available and was not used.
|
||||
- Host: Apple M5 Pro, macOS, Rust 1.100.0, Apple clang 17.0.0. No Homebrew LLVM, `llvm-mc` or full Xcode.
|
||||
- Baseline of the merge: `cargo test --locked --workspace --no-fail-fast` exited 101 with 392 passed, 1 failed, 21 ignored. The failure (`probe_fuzz_harness_minimized_artifact`) also occurs on `0836936`: the test read an untracked file.
|
||||
|
||||
## Corrections to earlier entries
|
||||
|
||||
- The earlier claim of 381 passed and 0 failed did not hold for a fresh checkout (see above).
|
||||
- The SXTW encoding recorded as verified was wrong for most source registers.
|
||||
- #65, #66 and #117 were marked complete prematurely. They stay open until reviewed against their own acceptance criteria.
|
||||
|
||||
## Milestones
|
||||
|
||||
| # | Commit subject | Scope | Evidence |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | cpu: correct the sign- and zero-extension family | MOVZX/MOVSX/MOVSXD, MOV-immediate regressions, SXTW, 32-bit access width, RIP-relative and LEA addressing, self-contained prefix test | `tests/movsxd.rs`: 9 tests over 93 LLVM-assembled register forms and 32 MOV immediates, each run by the interpreter and as native translated code; 16 of 16 targeted mutations caught |
|
||||
| 2 | cpu: share one generated decoder and store guest flags | Registry, generator, shared decoder and semantics, integer expansion, architectural DBT flags, truthful probe support | `tests/x86_integer.rs`, `tests/arm64_encodings.rs`, `tests/x86_generator`; 37 targeted mutations: 36 caught (4 only after new tests), and one equivalent, whose redundant check was removed |
|
||||
| 3 | cpu: add SSE2 state, moves and packed integer forms | XMM and MXCSR state, mandatory prefixes, SSE/SSE2 moves and packed integer operations, NEON lowering | `tests/x86_vector.rs` (9 tests, 374 LLVM-assembled instructions, 64 states each), `tests/arm64_encodings.rs`; 35 targeted mutations: 34 caught (1 only after a new test) and one equivalent |
|
||||
| 4 | cpu: add exact SSE and SSE2 floating point | Software binary32/binary64 arithmetic with MXCSR, compares and conversions | `tests/x86_float.rs` (9 tests, 6,824 exact-fraction vectors, 172 LLVM-assembled instructions, over 2 million host comparisons); 53 targeted mutations: 52 caught (2 only after directed vectors), and one changes a rule deliberately left unasserted |
|
||||
| 5 | runtime: one import resolver and typed service adapters | Bounded import parser shared by probe and binder, strict registry, transactional binding, Win64 preservation check, typed registry and generator, 20 services | `tests/runtime_services.rs` (19 tests; every service is called by translated guest code), generator unit tests (4); 33 valid targeted mutations: all caught, 2 only after new cases |
|
||||
|
||||
Encodings: `clang -target x86_64-apple-macos -c` and `clang -target arm64-apple-macos -c`, read back with `objdump -d`.
|
||||
|
||||
## Verification of milestone 2 (local, real exit codes)
|
||||
|
||||
| Gate | Result |
|
||||
| --- | --- |
|
||||
| `cargo fmt --all -- --check`; strict Clippy, workspace, all targets and features | exit 0; exit 0 |
|
||||
| `cargo test --locked --workspace --no-fail-fast` | exit 0: 409 passed, 0 failed, 21 ignored |
|
||||
| `generate_x86.py --check`, `assemble.py --check`, generator tests (8) | exit 0 |
|
||||
| RDNA2 metadata, semantic registry, coverage and status checks; their Python tests | exit 0 |
|
||||
| `scripts/audit/{claims,dependencies,native}.sh`, release build, `shaders coverage` | exit 0 |
|
||||
| `scripts/test-gpu.sh` | first run exit 124 (its own timeout, in `sop2_arith`, straight after a release build); rerun exit 0: 69 passed, 0 failed, 1 ignored |
|
||||
| `scripts/demo.sh`, `scripts/build-app.sh`, `--smoke-frame`, `--inspect` | exit 0 |
|
||||
| `scripts/assemble-fixture.sh --check`; ignored LLVM tests in `xenora-isa` and `xenora-decoder` | not verified: need Homebrew LLVM (`llvm-mc`) |
|
||||
| Fuzz and mutation campaigns | not run |
|
||||
|
||||
Coverage: 56 operations, 184 declared forms, 279 opcode slots. 985 LLVM-assembled instructions execute every form except control flow and exits, which have their own tests.
|
||||
|
||||
`dbt_bench` on an Apple M5 Pro, 101 samples, three runs each of `5ab561b` and milestone 2, middle run: interpreter 12.69 to 11.12 MIPS, cold DBT 10.43 to 8.86 MIPS, warm DBT 468.83 to 424.86 MIPS, native code 242,608 to 290,184 bytes. The slowdown comes with the new work of storing six flags and the shared decode; the earlier figures belong to code that computed wrong flags. Not optimized yet. These are synthetic and say nothing about games.
|
||||
|
||||
## Verification of milestone 3 (local, real exit codes)
|
||||
|
||||
Main `19bea60` (#278 and QA tooling) was merged first as `70f1793`; it does not touch `crates/loader`. `CHANGELOG.md` and `docs/README.md` conflicted and both sides were kept.
|
||||
|
||||
| Gate | Result |
|
||||
| --- | --- |
|
||||
| Formatting; strict Clippy, workspace, all targets and features | exit 0; exit 0 |
|
||||
| `cargo test --locked --workspace --no-fail-fast` | exit 0: 429 passed, 0 failed, 22 ignored |
|
||||
| `generate_x86.py --check`, `assemble.py --check`, generator tests (10) | exit 0 |
|
||||
| RDNA2 metadata, semantic registry, coverage and status checks; their Python tests; claims, dependencies and native audits; release build | exit 0 |
|
||||
| `scripts/test-gpu.sh`, `demo.sh`, `build-app.sh`, `--smoke-frame`, `--inspect` | exit 0; GPU 74 passed, 0 failed, 1 ignored |
|
||||
| `scripts/assemble-fixture.sh --check` and ignored LLVM AMDGPU tests | not verified: need `llvm-mc` |
|
||||
| Fuzz and mutation campaigns | not run |
|
||||
|
||||
The registry now has 139 operations, 306 forms and 401 opcode slots. `dbt_bench`, integer only, middle of three runs: interpreter 11.18, cold DBT 8.62 and warm DBT 430.19 MIPS, with the same 290,184 native bytes as milestone 2. No SIMD throughput benchmark exists yet.
|
||||
|
||||
## Verification of milestone 4 (local, real exit codes)
|
||||
|
||||
| Gate | Result |
|
||||
| --- | --- |
|
||||
| Formatting; strict Clippy, workspace, all targets and features | exit 0; exit 0 |
|
||||
| `cargo test --locked --workspace --no-fail-fast` | exit 0: 438 passed, 0 failed, 22 ignored |
|
||||
| `generate_x86.py --check`, `assemble.py --check`, `float_reference.py --check`, generator tests (10) | exit 0 |
|
||||
| RDNA2 metadata, semantic registry, coverage and status checks; their Python tests; claims, dependencies and native audits; release build | exit 0 |
|
||||
| `scripts/test-gpu.sh`, `demo.sh`, `build-app.sh`, `--smoke-frame`, `--inspect` | exit 0; GPU 74 passed, 0 failed, 1 ignored |
|
||||
| `scripts/assemble-fixture.sh --check` and ignored LLVM AMDGPU tests | not verified: need `llvm-mc` |
|
||||
| Fuzz and mutation campaigns | not run |
|
||||
|
||||
The registry now has 191 operations, 358 forms and 453 opcode slots. `dbt_bench`, integer only, middle of three runs: interpreter 11.32, cold DBT 8.81 and warm DBT 430.19 MIPS (one warm run read 377.43). No floating-point or SIMD throughput benchmark exists.
|
||||
|
||||
Main moved to 15 commits past this branch after milestone 3; they do not touch `crates/loader` and are not merged yet.
|
||||
|
||||
## Verification of milestone 5 (local, real exit codes)
|
||||
|
||||
Main `f685ede` (QA tooling) was merged first as `5e7c21b`.
|
||||
|
||||
| Gate | Result |
|
||||
| --- | --- |
|
||||
| Formatting; strict Clippy, workspace, all targets and features | exit 0; exit 0 |
|
||||
| `cargo test --locked --workspace --no-fail-fast` | exit 0: 462 passed, 0 failed, 22 ignored |
|
||||
| `xenora-runtime-gen --check`; CPU generator, assembler and float reference checks; generator tests | exit 0 |
|
||||
| RDNA2 metadata, semantic registry, coverage and status checks; their Python tests; claims, dependencies and native audits; release build | exit 0 |
|
||||
| `scripts/test-gpu.sh`, `demo.sh`, `build-app.sh`, `--smoke-frame`, `--inspect` | exit 0; GPU 74 passed, 0 failed, 1 ignored |
|
||||
| `scripts/assemble-fixture.sh --check` and ignored LLVM AMDGPU tests | not verified: need `llvm-mc` |
|
||||
| Fuzz and mutation campaigns | not run |
|
||||
|
||||
`dbt_bench`, middle of three runs: interpreter 11.08, cold DBT 8.48 and warm DBT 409.65 MIPS. Warm runs read 392 to 417, against 430 for milestone 4; no change here is known to affect that path and the cause was not investigated.
|
||||
|
||||
The panic of #270 was reproduced on `5e7c21b` (`range start index 1025 out of range`) and does not occur after this milestone.
|
||||
|
||||
## Integration of main `c6a354b`
|
||||
|
||||
Merged after milestone 5. It carries #280 (#72), #281 (#66) and #283 (#65), published while this branch was not; those issues are not claimed here and the published work takes precedence in authorship.
|
||||
|
||||
- Kept: every upstream test, unchanged (`tests/bootstrap.rs` and the three new tests in `dbt.rs`), and the assembler's `sxtb_32` and `sxth_32`, now checked against LLVM.
|
||||
- Source: `cpu.rs` and `dbt.rs` keep the shared decoder and lowering, which already cover the merged behaviour.
|
||||
- Adopted from upstream: FS and GS together are undefined, and GS applies. This branch used to reject the combination. RIP-relative, negative-displacement and fault-address regressions for both segments were added (11 encodings, both engines); 3 of 3 mutations of the rule caught.
|
||||
- Compared: the integer fixture run through both trees in both engines. Upstream supports 142 instruction and engine pairs. They differ only where upstream stores no guest flags in the DBT (#64, #70), reads AH, CH, DH and BH as SPL, BPL, SIL and DIL (#68, including MOVZX and MOVSX in both engines), or writes eight bytes for a 32-bit store.
|
||||
- Gates: workspace 474 passed, 0 failed, 22 ignored; formatting, strict Clippy, all generator checks, repository audits, release build, GPU suite, demo and app gates exit 0. GPU: 80 passed, 0 failed, 1 ignored.
|
||||
|
||||
Main `4db0b9c` (#286, #287) was merged next. #286 fixed #270 first; its test and its bounds check on section offsets are kept, and imports stay on the shared parser. Gates on that merge: workspace 477 passed, 0 failed, 22 ignored; GPU 84 passed, 0 failed, 1 ignored; formatting, strict Clippy, generator checks, audits, release build, demo and app gates exit 0.
|
||||
|
||||
## Known limitations
|
||||
|
||||
- Only the forms in `x86/instructions.toml` exist. The RCP and RSQRT approximations, SSE3 and later, MMX, VEX, string instructions, RCL, RCR, SHLD, SHRD, LOCK, fences and atomics are unsupported.
|
||||
- Every floating-point form runs through software arithmetic in the DBT; none is lowered to NEON. No x86 hardware comparison exists, and `docs/cpu/instruction-registry.md` lists the choices left unasserted.
|
||||
- Packs, shuffles, high multiplies, PSADBW, sign-mask extraction, word insertion and extraction, byte shifts and shifts by a register count run through the shared semantics in the DBT.
|
||||
- The fixture graphics services, `XMemAlloc` and the `XMemFree` stub are outside the typed registry. Several older generated conformance tests check Rust library functions, not services.
|
||||
- Last error is one value per process; per-thread isolation (#202) waits for guest threads.
|
||||
- 8- and 16-bit ALU operations, shifts, MUL, DIV and bit operations run through the shared semantics in the DBT, not as ARM64.
|
||||
- The reference and the implementation share an author.
|
||||
- New CPU checks are not in CI; `.github` was left unchanged.
|
||||
|
||||
## Pending acceptance
|
||||
|
||||
- Two independent reviews required by `AGENTS.md`: not performed.
|
||||
- Issues touched here have not been claimed on GitHub and stay open.
|
||||
|
||||
## Next task
|
||||
|
||||
Agree with the maintainer and the contributor of #280, #281, #283 and #286 how this branch should be offered, before more overlapping work. Then native CRT memory and string services, which are not started.
|
||||
@@ -0,0 +1,44 @@
|
||||
# Infrastructure QA campaign ledger
|
||||
|
||||
Running record for the infrastructure and engineering-quality campaign.
|
||||
Update after each meaningful commit batch. Do not invent passing tests.
|
||||
|
||||
## Baseline
|
||||
|
||||
- Branch: `main` synchronized with `origin/main` before each batch
|
||||
- Hard exclusions: CPU/runtime crates, RDNA2 crates, `app/`, fixtures, GPU tests
|
||||
- Approved paths: see `infrastructure-qa-ownership.md`
|
||||
|
||||
## Commits
|
||||
|
||||
| SHA | Summary | Tests |
|
||||
| --- | --- | --- |
|
||||
| `8410e3d` | test(qa): cover environment diagnostic helpers. | focused suite before commit |
|
||||
| `48f44ca` | feat(qa): add operational python3 -m qa CLI. | focused suite before commit |
|
||||
| `f56d3c9` | feat(release): add python3 -m release CLI entrypoints. | focused suite before commit |
|
||||
| `22bafeb` | feat(qa): add read-only RDNA2 expansion planning over live inventories. | focused suite before commit |
|
||||
| `c651a9d` | feat(qa): add unified verification profiles with stale evidence detection. | focused suite before commit |
|
||||
| `f175a10` | feat(qa): scan CPU opcode and import coverage from existing sources. | focused suite before commit |
|
||||
| `f400550` | feat(qa): compare recorded benchmarks with identity and noise guards. | focused suite before commit |
|
||||
| `7a51764` | feat(qa): detect claim collisions across renames and deletions. | focused suite before commit |
|
||||
| `050df30` | feat(release): build release-readiness reports with SBOM and evidence. | focused suite before commit |
|
||||
| `63cf359` | test(qa): smoke-test qa and release CLIs against real commands. | focused suite before commit |
|
||||
| `313430c` | docs(testing): document Phase II qa and release CLI workflows. | focused suite before commit |
|
||||
| `0f7658b` | docs(changelog): record Phase II infrastructure automation CLIs. | focused suite before commit |
|
||||
|
||||
## Smoke repository
|
||||
|
||||
- Repo: `ranveersoni98/xenora-agent-queue-smoke`
|
||||
- See `agent-queue-smoke.md` for Actions evidence
|
||||
|
||||
## Limitations
|
||||
|
||||
- Phase II deferred: exact `/verified` head-SHA smoke and wall-clock lease expiry still need a second eligible verifier / long wait.
|
||||
- `qa verify cpu|gpu|app|full` invoke heavy existing commands; use `quick` for local iteration.
|
||||
- CPU coverage statuses are heuristic where no authoritative opcode inventory file exists.
|
||||
|
||||
## Limitations
|
||||
|
||||
- Production agent PR checks remain advisory
|
||||
- Independent `/verified` on smoke PRs needs a second eligible account
|
||||
- New QA/release tools are local/advisory until review
|
||||
@@ -0,0 +1,61 @@
|
||||
# Infrastructure and QA ownership manifest
|
||||
|
||||
Non-overlapping file ownership for the infrastructure and engineering-quality
|
||||
campaign. Active CPU/runtime, RDNA2 and native-application Gates 4–9 work stays
|
||||
outside this manifest.
|
||||
|
||||
Rechecked against `origin/main` at the claim of issue #180. Update this file
|
||||
when a path is claimed, released or closed.
|
||||
|
||||
## Hard exclusions (do not edit under this campaign)
|
||||
|
||||
- `crates/loader/`, `crates/import-gen/`, `crates/ffi/`, `crates/isa/`
|
||||
- `crates/decoder/`, `crates/shader/`, `crates/ref/`, `crates/metal/`, `crates/texture/`
|
||||
- `app/`, `fixtures/`, `tests/validation/`
|
||||
- `scripts/test-gpu.sh` and existing CPU/GPU benchmark workload implementations
|
||||
- Guest execution authorization and trusted-fixture policy
|
||||
|
||||
Shared Cargo configuration, production CI workflows and `CHANGELOG.md` require
|
||||
an explicit per-change coordination note even when a QA issue mentions them.
|
||||
|
||||
## Active claims
|
||||
|
||||
| Issue | Holder | Paths | Notes |
|
||||
| --- | --- | --- | --- |
|
||||
| #180 | ranveersoni98 | `tests/agent_queue/`, `docs/coordination/` | Live smoke evidence; no production workflow edits |
|
||||
| #277 | held until #180 releases coordination docs | `scripts/qa/`, `tests/qa/`, `scripts/release/`, `tests/release/`, `docs/testing/infrastructure/` | Maintainer-approved new paths; depends on #180 |
|
||||
|
||||
## Approved new paths (not yet exclusively held)
|
||||
|
||||
Maintainer-approved for the infrastructure/QA campaign once claimed without
|
||||
overlapping an active issue:
|
||||
|
||||
| Path | Intended workstream |
|
||||
| --- | --- |
|
||||
| `scripts/qa/` | Advisory PR verification, test orchestration, env diagnostics |
|
||||
| `tests/qa/` | Independent tests for `scripts/qa/` |
|
||||
| `scripts/release/` | Native Mach-O, SBOM, checksum and release-evidence tools |
|
||||
| `tests/release/` | Independent tests for `scripts/release/` |
|
||||
| `docs/testing/infrastructure/` | Tooling docs; not product GPU/CPU protocol docs |
|
||||
|
||||
## Existing scripts to extend or wrap, not duplicate
|
||||
|
||||
| Existing path | Relation |
|
||||
| --- | --- |
|
||||
| `scripts/agent_queue/` | Owned by the merged queue (#165); #180 smoke-tests only |
|
||||
| `scripts/audit/native.sh` | ARM64 and linkage gate; release tools may consume its outputs |
|
||||
| `scripts/audit/claims.sh`, `dependencies.sh`, `status.py`, `test_inventory.py` | Prefer calling or summarizing; do not reimplement |
|
||||
| `scripts/benchmark.sh` | Analysis tools consume results only; do not change workloads |
|
||||
|
||||
## Disposable remote testing
|
||||
|
||||
Live agent-queue Actions exercises run only in the maintainer-approved private
|
||||
repository `ranveersoni98/xenora-agent-queue-smoke`. Do not enable blocking
|
||||
production checks until that smoke evidence is recorded and reviewed.
|
||||
|
||||
## Phase II note
|
||||
|
||||
Issue #277 holds `scripts/qa/`, `tests/qa/`, `scripts/release/`, `tests/release/` and
|
||||
`docs/testing/infrastructure/`. Ledger updates for Phase II commits are recorded in
|
||||
`docs/coordination/infrastructure-qa-ledger.md` under the #180 coordination claim until
|
||||
#180 closes, then move with the tooling owners.
|
||||
@@ -0,0 +1,50 @@
|
||||
# x86-64 instruction registry
|
||||
|
||||
The static PE probe, the interpreter and the native ARM64 dynamic binary translator (DBT) decode guest code through one function, `x86_decode::decode`. Its tables are generated from `crates/loader/x86/instructions.toml`.
|
||||
|
||||
| Part | File | Role |
|
||||
| --- | --- | --- |
|
||||
| Registry | `crates/loader/x86/instructions.toml` | Opcode map, opcode, ModRM digit, operand encoding, size, immediate, flag effects and public reference. Data only. |
|
||||
| Generator | `crates/loader/generate_x86.py` | `validate`, `generate` and `--check`. Rejects overlapping encodings, opcodes that are prefixes, contradictory operand rules, unknown vocabulary and flags both written and undefined. |
|
||||
| Tables | `crates/loader/src/x86_table.rs` | Generated static tables. No metadata is parsed at run time. |
|
||||
| Semantics | `crates/loader/src/x86_exec.rs`, `x86_simd.rs`, `x86_float.rs`, `softfloat.rs` | Rust primitives for integer, vector and floating-point forms. Every instruction is all-or-nothing. |
|
||||
| Lowering | `crates/loader/src/dbt.rs` | ARM64 for the forms `is_native` accepts. Every other form calls the shared semantics and is counted in `DbtMetrics::interpreter_fallbacks`. |
|
||||
|
||||
## Adding a form
|
||||
|
||||
1. Add the form, and its operation if new, to the registry with an Intel SDM or AMD APM reference.
|
||||
2. Run `python3 crates/loader/generate_x86.py generate`.
|
||||
3. Implement the operation in `x86_exec.rs`. Leave flags the manuals call undefined unchanged.
|
||||
4. Add assembly text to `crates/loader/tests/x86/assemble.py`, run it with `generate`, and extend the reference in `tests/x86_integer.rs` or `tests/x86_vector.rs`. A declared form without a fixture fails `every_declared_form_is_executed_by_a_fixture`.
|
||||
5. Lower it natively only if the ARM64 result and flags match. The same tests require native forms never to call the helper, and helper forms always to.
|
||||
|
||||
A declared form is decodable, not implemented. Count a form as supported only when the tests above cover it.
|
||||
|
||||
## Independence
|
||||
|
||||
The references in `tests/x86_integer.rs` and `tests/x86_vector.rs` read only LLVM assembly text. They do not use the encodings, registry, decoder or production semantics, and work bit by bit or on byte arrays. They were written by the same contributor as the implementation, so independent review is still required.
|
||||
|
||||
## Guest flags
|
||||
|
||||
The DBT stores CF, ZF, SF, OF, PF and AF in `CpuState::flags`. It skips the store only when a later instruction in the block overwrites all six before anything can read them, fault or leave the block.
|
||||
|
||||
FS and GS overrides together are architecturally undefined; GS applies, in both engines.
|
||||
|
||||
## Vector state
|
||||
|
||||
XMM registers live in `CpuState::xmm`, lane 0 in the low bits, and MXCSR in `CpuState::mxcsr`. A mandatory 0x66, F3 or F2 prefix selects a form; the generator rejects an opcode where 0x66 could be both a mandatory prefix and an operand size. A 16-byte memory operand must be aligned unless its form says otherwise, and a violation exits with `GeneralProtection` before any memory access. Non-temporal stores are ordinary stores.
|
||||
|
||||
## Floating point
|
||||
|
||||
`softfloat.rs` follows the Intel SDM (Vol. 1, 4.8, 4.9 and 11.5) without host floating point. Expected values come from exact fractions in `tests/x86/float_reference.py`. Some behaviour is implemented one way but not asserted, because the sections used leave it open or it was not found there:
|
||||
|
||||
- a denormal dividend over zero raises divide-by-zero only, not also denormal-operand;
|
||||
- flush-to-zero also flushes a tiny result that is exact, raising underflow and precision;
|
||||
- DAZ applies before conversion to an integer;
|
||||
- an unmasked overflow also records precision.
|
||||
|
||||
None of it has been compared with x86 hardware.
|
||||
|
||||
## Rejected on purpose
|
||||
|
||||
LOCK, F2 or F3 where it is neither PAUSE nor part of a declared form, F2 combined with F3, address-size overrides, an ignored segment override after FS or GS, 16-bit stack and branch forms, 16-bit BSWAP and MOVSXD, bit tests of memory by a register index, RCL, RCR, SHLD, SHRD, string instructions, MMX, the RCP and RSQRT approximations, SSE3 and later, VEX, atomics and fences. The DBT also refuses raw SYSCALL.
|
||||
@@ -0,0 +1,29 @@
|
||||
# Runtime service registry
|
||||
|
||||
Guest imports resolve through one lookup, `ImportRegistry::resolve`. Binding, the static probe and the command-line reports all use it, and they read the import directory with one bounded parser, `import_table::parse_imports`.
|
||||
|
||||
| Part | File | Role |
|
||||
| --- | --- | --- |
|
||||
| Registry | `crates/loader/runtime/services.txt` | Library, symbol, typed signature, API-set aliases, failure contract, status, reference and tests. Data only. |
|
||||
| Generator | `xenora-runtime-gen` in `crates/import-gen` | `validate`, `generate` and `--check`. Rejects conflicting keys, unlisted API sets, unsupported types, and behaviour without a named, existing test. |
|
||||
| Adapters | `crates/loader/src/runtime_table.rs` | Generated Win64 argument and result adapters and static metadata. |
|
||||
| Handlers | `handlers` in `crates/loader/src/services.rs` | Rust implementations. They see guest memory and service state, never the CPU. |
|
||||
| Report | [services.md](services.md) | Generated counts. Aliases are counted apart from services. |
|
||||
|
||||
## Rules
|
||||
|
||||
- Module names compare without case; symbol names are exact. A name spelled `Ordinal#7` is not ordinal 7.
|
||||
- An API set resolves only if the registry lists that exact set for that symbol. A similar name forwards nowhere.
|
||||
- Registering a key twice is an error. A host module cannot replace a standard service.
|
||||
- Binding resolves every import before it writes any slot. A malformed table or an unresolved import leaves every slot unbound.
|
||||
- A service call reads its return address first, and stops the guest with `ServiceAbiViolation` if the service changed a nonvolatile register, including XMM6 to XMM15.
|
||||
|
||||
## Adding a service
|
||||
|
||||
1. Write a test in `crates/loader/tests/runtime_services.rs` that calls it from guest code and derives its expectations from the public documentation.
|
||||
2. Add the entry to `services.txt` and the handler to `services.rs`.
|
||||
3. Run `cargo run -p xenora-import-gen --bin xenora-runtime-gen generate`.
|
||||
|
||||
## Outside this registry
|
||||
|
||||
The fixture graphics services, `XMemAlloc` and the `XMemFree` stub are still registered by hand. The older import-list generator in `crates/import-gen` is separate: its output is not compiled into the loader, and several of its generated conformance tests check Rust library functions rather than a service.
|
||||
@@ -0,0 +1,40 @@
|
||||
# Typed runtime services
|
||||
|
||||
Generated by `xenora-runtime-gen` from `crates/loader/runtime/services.txt`. Do not edit.
|
||||
|
||||
A declared service is not a claim of compatibility. `implemented` and `partial` describe behaviour against the documented contract for the synthetic guest. No service has been independently accepted.
|
||||
|
||||
| Measure | Count |
|
||||
| --- | ---: |
|
||||
| Services with a declared ABI | 20 |
|
||||
| Generated adapters | 20 |
|
||||
| Unique handler implementations | 20 |
|
||||
| Implemented | 7 |
|
||||
| Partial | 13 |
|
||||
| Stub | 0 |
|
||||
| Conformance-tested through guest dispatch | 20 |
|
||||
| API-set aliases (not services) | 20 |
|
||||
| Independently accepted | 0 |
|
||||
|
||||
| Service | Signature | Status | Failure |
|
||||
| --- | --- | --- | --- |
|
||||
| `kernel32.dll!SetProcessPriorityBoost` | `(process: handle, disable: bool32) -> bool32` | partial | 0 with ERROR_INVALID_HANDLE |
|
||||
| `kernel32.dll!GetProcessPriorityBoost` | `(process: handle, disabled: out<4>) -> bool32` | partial | 0 with ERROR_INVALID_HANDLE or ERROR_NOACCESS |
|
||||
| `kernel32.dll!GetCurrentProcess` | `() -> handle` | implemented | never |
|
||||
| `kernel32.dll!GetProcessId` | `(process: handle) -> u32` | partial | 0 with ERROR_INVALID_HANDLE |
|
||||
| `kernel32.dll!GetCurrentThread` | `() -> handle` | implemented | never |
|
||||
| `kernel32.dll!GetCurrentProcessId` | `() -> u32` | implemented | never |
|
||||
| `kernel32.dll!GetCurrentThreadId` | `() -> u32` | implemented | never |
|
||||
| `kernel32.dll!OpenThread` | `(access: u32, inherit: bool32, thread: u32) -> handle` | partial | 0 with ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED or ERROR_NOT_ENOUGH_MEMORY |
|
||||
| `kernel32.dll!GetThreadPriority` | `(thread: handle) -> i32` | partial | THREAD_PRIORITY_ERROR_RETURN with ERROR_INVALID_HANDLE or ERROR_ACCESS_DENIED |
|
||||
| `kernel32.dll!SetThreadPriority` | `(thread: handle, priority: i32) -> bool32` | partial | 0 with ERROR_INVALID_HANDLE, ERROR_ACCESS_DENIED, ERROR_NOT_SUPPORTED or ERROR_INVALID_PARAMETER |
|
||||
| `kernel32.dll!CloseHandle` | `(object: handle) -> bool32` | partial | 0 with ERROR_INVALID_HANDLE |
|
||||
| `kernel32.dll!GetSystemTimeAsFileTime` | `(time: out<8>) -> void` | implemented | guest fault on an invalid pointer |
|
||||
| `kernel32.dll!GetLastError` | `() -> u32` | partial | never |
|
||||
| `kernel32.dll!SetLastError` | `(code: u32) -> void` | partial | never |
|
||||
| `kernel32.dll!VirtualAlloc` | `(address: ptr, size: u64, kind: u32, protect: u32) -> ptr` | partial | 0 with ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED, ERROR_INVALID_ADDRESS or ERROR_NOT_ENOUGH_MEMORY |
|
||||
| `kernel32.dll!VirtualFree` | `(address: ptr, size: u64, kind: u32) -> bool32` | partial | 0 with ERROR_NOT_SUPPORTED, ERROR_INVALID_PARAMETER or ERROR_INVALID_ADDRESS |
|
||||
| `ucrtbase.dll!sqrt` | `(x: f64) -> f64` | partial | NaN for a negative argument; errno is not set |
|
||||
| `ucrtbase.dll!sqrtf` | `(x: f32) -> f32` | partial | NaN for a negative argument; errno is not set |
|
||||
| `ucrtbase.dll!fabs` | `(x: f64) -> f64` | implemented | never |
|
||||
| `ucrtbase.dll!fabsf` | `(x: f32) -> f32` | implemented | never |
|
||||
@@ -21,7 +21,29 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
|
||||
| `s_waitcnt_vscnt null, 0` | SOPK, exact null source and zero immediate | 4 B | yes | yes | three-way passed | verified store wait | implemented | fixture verified | fixture verified |
|
||||
| `s_endpgm` | SOPP, zero immediate | 4 B | yes | yes | three-way passed | verified termination | implemented | fixture verified | fixture verified |
|
||||
| `s_mov_b32` | Normal SGPR or EXEC/VCC half destination and normal SGPR, inline integer or literal source | `BE880387` | yes | yes | three-way passed | resolved scalar state | implemented | fixture verified | fixture verified |
|
||||
| `s_not_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = ~S0; SCC = D != 0 | `BE890708` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_brev_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0 bit-reversed; SCC unchanged | `BE8A0B08` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_bcnt0_i32_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = count of zero bits; SCC = D != 0 | `BE8C0D08` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_bcnt1_i32_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = count of one bits; SCC = D != 0 | `BE8B0F08` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_ff0_i32_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = index of the lowest zero bit, or -1; SCC unchanged | `BE8E11FF 0000FFFF` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_ff1_i32_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = index of the lowest one bit, or -1; SCC unchanged | `BE8D13FF 00400000` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_flbit_i32_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = zeros above the highest one bit, or -1; SCC unchanged | `BE8F1508` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_flbit_i32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = bits above the highest bit differing from the sign, or -1; SCC unchanged | `BE9017FF FFF00000` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_sext_i32_i8` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0[7:0] sign-extended; SCC unchanged | `BE911908` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_sext_i32_i16` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0[15:0] sign-extended; SCC unchanged | `BE921AFF 00018000` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_abs_i32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = \|S0\| (0x80000000 stays); SCC = D != 0 | `BE933412` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_eq_u32` | Normal SGPR or integer operands, with at most one source selecting a literal | `BF068708` | yes | yes | three-way passed | resolved SCC | implemented | fixture verified | fixture verified |
|
||||
| `s_cmp_eq_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 == S1 (signed) | `BF00C108` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_lg_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 != S1 (signed) | `BF010908` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_gt_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 > S1 (signed) | `BF020908` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_ge_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 >= S1 (signed) | `BF030909` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_lt_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 < S1 (signed) | `BF040908` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_le_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 <= S1 (signed) | `BF050809` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_lg_u32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 != S1 (unsigned) | `BF07FF0A 89ABCDEF` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_gt_u32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 > S1 (unsigned) | `BF080908` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_ge_u32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 >= S1 (unsigned) | `BF090809` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_lt_u32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 < S1 (unsigned) | `BF0A0809` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cmp_le_u32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 <= S1 (unsigned) | `BF0BC009` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_add_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = carry-out | `80088308` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_sub_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = borrow | `808A8180` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_add_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = signed overflow | `8110C109` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
@@ -31,6 +53,30 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
|
||||
| `s_and_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = result != 0 | `870D090C` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_or_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = result != 0 | `880ED00D` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_xor_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = result != 0 | `890C0A0B` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_andn2_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 & ~S1; SCC = result != 0 | `8A09FF08 FF00FF00` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_orn2_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 \| ~S1; SCC = result != 0 | `8B0AC109` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_nand_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 & S1); SCC = result != 0 | `8C0B0808` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_nor_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 \| S1); SCC = result != 0 | `8D0C090B` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_xnor_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 ^ S1); SCC = result != 0 | `8E0D080C` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_lshl_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 << S1[4:0]; SCC = result != 0 | `8F0EA40D` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_lshr_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0], zero fill; SCC = result != 0 | `900FFF0E FFFFFFE1` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_ashr_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0], sign fill; SCC = result != 0 | `91109F0E` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_min_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 < S1 (signed) else S1; SCC = S0 < S1 | `830A0908` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_min_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 < S1 (unsigned) else S1; SCC = S0 < S1 | `83988509` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_max_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 > S1 (signed) else S1; SCC = S0 > S1 | `84170908` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_max_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 > S1 (unsigned) else S1; SCC = S0 > S1 | `848C0908` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cselect_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = SCC ? S0 : S1; reads SCC, SCC unchanged | `850B0809` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_bfm_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ((1 << S0[4:0]) - 1) << S1[4:0]; SCC unchanged | `920D848C` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_mul_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = low 32 bits of S0 * S1; SCC unchanged | `930F0908` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_bfe_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0] masked to S1[22:16] bits; SCC = D != 0 | `9390FF08 00080004` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_bfe_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0] (sign fill) masked to S1[22:16] bits, sign-extended; SCC = D != 0 | `9411FF08 00080004` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_absdiff_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = \|S0 - S1\| of the 32-bit difference (0x80000000 stays); SCC = D != 0 | `96120809` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_lshl1_add_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 1) + S1; SCC = carry out of the exact sum | `970E0908` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_lshl2_add_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 2) + S1; SCC = carry out of the exact sum | `97990909` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_lshl3_add_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 3) + S1; SCC = carry out of the exact sum | `98130808` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_lshl4_add_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 4) + S1; SCC = carry out of the exact sum | `9894D009` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_mul_hi_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = high 32 bits of the unsigned product; SCC unchanged | `9A950808` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_mul_hi_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = high 32 bits of the signed product; SCC unchanged | `9B160808` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_lt_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 < S1), fully written | `7D020701` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_eq_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 == S1), fully written | `7D040280` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_cmp_le_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 <= S1), fully written | `7D060208` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
@@ -55,6 +101,18 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
|
||||
| `v_ashrrev_i32_e32` | Two VGPR sources and one VGPR destination | `31FFFF01` | yes | yes | three-way passed | MSL signed right shift with a five-bit count | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cbranch_execz` | Nonnegative signed dword displacement | `BF880001` | yes | yes | three-way passed | resolved Wave32 EXEC_LO zero check | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `s_cbranch_vccz` | Nonnegative signed dword displacement | `BF860001` | yes | yes | three-way passed | resolved Wave32 VCC_LO zero check, or a wave-uniform join select after a vector compare | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_mul_i32_i24_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = low 32 bits of sext(S0[23:0]) * sext(S1[23:0]) | `120402C3` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_mul_hi_i32_i24_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = bits 63:32 of sext(S0[23:0]) * sext(S1[23:0]) | `14060208` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_mul_u32_u24_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = low 32 bits of S0[23:0] * S1[23:0] | `160802FF 00123456` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_mul_hi_u32_u24_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = bits 63:32 of S0[23:0] * S1[23:0] | `180A0208` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_min_i32_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = signed min(S0, S1) | `220C0501` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_max_i32_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = signed max(S0, S1) | `240E0285` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_min_u32_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = unsigned min(S0, S1) | `26100303` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_max_u32_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = unsigned max(S0, S1) | `28120208` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_xnor_b32_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = ~(S0 ^ S1) | `3C140B04` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_add_nc_u32_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = S0 + S1, no carry | `4A160F06` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_sub_nc_u32_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = S0 - S1, no carry | `4C181308` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
| `v_subrev_nc_u32_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = S1 - S0, no carry | `4E1A170A` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
|
||||
<!-- status:instructions:end -->
|
||||
|
||||
## Automated three-way comparison
|
||||
|
||||
@@ -8,6 +8,8 @@ Apple documents `uint`, device address space and the scalar compute grid-positio
|
||||
|
||||
The integer emitter uses unsigned addition, bitwise logic, and shifts. Scalar moves and compares are evaluated at translation time using known SGPR initializers. Forward branches must target instruction boundaries. Conditional branches require known scalar condition code (SCC), execution mask (EXEC), or vector condition code (VCC) state. Wave32 zero checks read the low halves of EXEC and VCC. Known partial EXEC masks merge each vector result with the initialized destination according to the logical lane number, computed from the grid index modulo 32. Empty EXEC suppresses vector arithmetic and moves. Reachable vector memory operations require a full mask. The IR records the statically selected path. Scalar values can originate only from constants and initialized SGPRs, and SGPR 0–7 remain reserved for synthetic descriptors. The generated kernel contains only the selected scalar branch path. The partial-mask merge uses a per-invocation selection from two vector values.
|
||||
|
||||
Twelve VOP2 integer forms from the semantic registry lower through one typed template per declared operation (`VectorBinary`), not per opcode: wrapping `uint` add, subtract and XNOR; `min`/`max` on `uint`, or on `as_type<int>` for the signed forms; and the 24-bit multiplies, which first sign-extend bit 23 with `as_type<int>(x << 8u) >> 8` (or mask to 24 bits for the unsigned forms), then take the low word as a wrapping `uint` product or the high word with MSL `mulhi`. `v_subrev_nc_u32` declares reversed sources, so the translator swaps them. A wave-uniform SRC0 (an SGPR, inline integer or literal) becomes a constant operand, while the lane's VGPRs stay runtime values; `vcc_lo` as SRC0 uses the lane-derived compare mask when a VOPC produced it. These forms are refused inside code skipped by a runtime `s_cbranch_vccz`, as both interpreters refuse them.
|
||||
|
||||
The float subset accepts addition and multiplication only when every possible operand is a positive normal binary32 value and the exact result is itself representable as a normal binary32 value. A known-bit analysis propagates the effect of masks and XOR. It enumerates up to two candidate bit patterns per operand, proves the result for each pair, and retains at most two unique results for an ensuing operation. No rounding mode, signed-zero behavior, subnormal mode, NaN handling or infinity policy is required for this restricted domain. Unknown or inexact cases fail verification.
|
||||
|
||||
The generated MSL uses unsigned words for register bits and `as_type` for reinterpretation at individual float operations. It disables contraction and reassociation for these kernels. The compiler tests compare all three fixture outputs against tracked IR and MSL goldens. The [native demonstration](../../scripts/demo.sh) checks executed results.
|
||||
@@ -8,11 +8,14 @@
|
||||
| SOPP `S_WAITCNT`, SOPK `S_WAITCNT_VSCNT` | A zero vector-load or vector-store threshold completes the associated transfer. The model permits one pending operation per counter (CLAIM-RDNA2-TRANSFER-WAITS). |
|
||||
| VOP1 `V_MOV_B32` | Read a register, inline integer or literal. Copy all 32 bits. |
|
||||
| VOP3 `V_ADD_NC_U32` | Read two vector registers and add modulo 2^32. No implicit carry or flag update. |
|
||||
| SOP1 `S_MOV_B32`, SOPC `S_CMP_EQ_U32` | Copy 32 bits into a scalar register or compare two operands and set SCC. Descriptor SGPRs are reserved. |
|
||||
| SOP2 `S_ADD_U32`, `S_SUB_U32`, `S_ADD_I32`, `S_SUB_I32`, `S_ADDC_U32`, `S_SUBB_U32`, `S_AND_B32`, `S_OR_B32`, `S_XOR_B32` | Exact integer result reduced modulo 2^32; SCC is the carry-out, the borrow, signed overflow (the exact signed result does not fit in i32), or a nonzero bitwise result, and ADDC/SUBB consume SCC ([SOP2 scalar ALU](scalar-alu.md)). Descriptor SGPRs are reserved. |
|
||||
| SOP2 `S_MIN_{I32,U32}`, `S_MAX_{I32,U32}`, `S_CSELECT_B32`, `S_BFM_B32`, `S_MUL_I32`, `S_MUL_HI_{U32,I32}`, `S_BFE_{U32,I32}`, `S_ABSDIFF_I32`, `S_LSHL{1,2,3,4}_ADD_U32` | The guide's section 12.1 result, computed exactly and reduced modulo 2^32. Min and max compare strictly (a tie gives S1, SCC = 0); CSELECT reads SCC and refuses it unset; BFM, MUL, MUL_HI and CSELECT leave SCC unchanged; BFE uses offset S1[4:0] and width S1[22:16] (32 or more keeps every shifted bit); ABSDIFF negates the wrapped difference; LSHLn_ADD sets SCC to the carry of the exact sum. Descriptor SGPRs are reserved. |
|
||||
| SOP1 `S_NOT_B32`, `S_BREV_B32`, `S_BCNT{0,1}_I32_B32`, `S_FF{0,1}_I32_B32`, `S_FLBIT_I32_B32`, `S_FLBIT_I32`, `S_SEXT_I32_I{8,16}`, `S_ABS_I32` | The guide's section 12.3 result; a search that finds nothing gives -1, and `S_ABS_I32` of 0x80000000 is 0x80000000. Only NOT, BCNT0, BCNT1 and ABS write SCC (= D != 0). Descriptor SGPRs are reserved. |
|
||||
| SOP1 `S_MOV_B32`, SOPC `S_CMP_{EQ,LG,GT,GE,LT,LE}_{I32,U32}` | Copy 32 bits into a scalar register, or compare SSRC0 with SSRC1 (signed for `_I32` ordering, unsigned for `_U32`; EQ and LG on the raw bits) and set only SCC. Descriptor SGPRs are reserved. |
|
||||
| SOP2 `S_ADD_U32`, `S_SUB_U32`, `S_ADD_I32`, `S_SUB_I32`, `S_ADDC_U32`, `S_SUBB_U32`, `S_AND_B32`, `S_OR_B32`, `S_XOR_B32`, `S_ANDN2_B32`, `S_ORN2_B32`, `S_NAND_B32`, `S_NOR_B32`, `S_XNOR_B32`, `S_LSHL_B32`, `S_LSHR_B32`, `S_ASHR_I32` | Exact integer result reduced modulo 2^32; shifts use S1[4:0]; SCC is the carry-out, the borrow, signed overflow (the exact signed result does not fit in i32), or a nonzero logical or shift result, and ADDC/SUBB consume SCC ([SOP2 scalar ALU](scalar-alu.md)). Descriptor SGPRs are reserved. |
|
||||
| VOPC `V_CMP_{LT,EQ,LE,GT,NE,GE}_{I32,U32}` | Compare widened 64-bit values per active lane. VCC_LO gets EXEC & the test results and is fully written, so empty EXEC gives 0. A later `S_CBRANCH_VCCZ` on such a mask checks the skipped code statically ([VOPC integer compares](vector-compare.md)). |
|
||||
| SOPP `S_BRANCH`, `S_CBRANCH_SCC0` | Use a signed dword displacement from the next instruction (CLAIM-RDNA2-SOPP-BRANCH-DISPLACEMENT). Require a nonnegative word displacement to a decoded instruction boundary, including for untaken edges. |
|
||||
| VOP2 `V_AND_B32`, `V_XOR_B32` | Apply the bitwise operator to two VGPRs. |
|
||||
| VOP2 `V_MUL_{I32_I24,HI_I32_I24,U32_U24,HI_U32_U24}`, `V_MIN_{I32,U32}`, `V_MAX_{I32,U32}`, `V_XNOR_B32`, `V_ADD_NC_U32`, `V_SUB_NC_U32`, `V_SUBREV_NC_U32` | The guide's section 12.7 result per active lane, computed exactly: the 24-bit multiplies use S0[23:0] and S1[23:0] (sign-extended for I24) and keep bits 31:0 or 63:32; SUBREV gives S1 - S0. SRC0 is a VGPR, s0-s105, `vcc_lo`, an inline integer or a literal. Inactive lanes keep VDST; no SCC or VCC write. |
|
||||
| VOP2 `V_ADD_F32`, `V_MUL_F32` | Require exact binary32 results by checking the inputs and the wider intermediate. Multiplication of the significands fits in binary64. Addition must also recover the smaller operand by subtracting the larger. |
|
||||
| SOPP `S_ENDPGM` | Stop at the end of the byte stream. The synthetic contract requires explicitly completed transfers and a produced output first (CLAIM-RDNA2-TRANSFER-WAITS). |
|
||||
|
||||
|
||||
+109
-7
@@ -1,7 +1,9 @@
|
||||
# SOP2 scalar ALU subset
|
||||
|
||||
Xenora decodes and executes nine gfx1030 SOP2 forms. Each takes 32-bit
|
||||
operands, writes a normal SGPR (s0-s105) and sets SCC.
|
||||
Xenora decodes and executes thirty-three gfx1030 SOP2 forms. Each takes 32-bit
|
||||
operands and writes a normal SGPR (s0-s105). The seventeen below set SCC; the
|
||||
sixteen in [Arithmetic, select and bit-field forms](#arithmetic-select-and-bit-field-forms)
|
||||
set it or leave it as the guide says.
|
||||
|
||||
| Form | D | SCC |
|
||||
| --- | --- | --- |
|
||||
@@ -14,10 +16,23 @@ operands, writes a normal SGPR (s0-s105) and sets SCC.
|
||||
| `s_and_b32` | S0 & S1 | D != 0 |
|
||||
| `s_or_b32` | S0 \| S1 | D != 0 |
|
||||
| `s_xor_b32` | S0 ^ S1 | D != 0 |
|
||||
| `s_andn2_b32` | S0 & ~S1 | D != 0 |
|
||||
| `s_orn2_b32` | S0 \| ~S1 | D != 0 |
|
||||
| `s_nand_b32` | ~(S0 & S1) | D != 0 |
|
||||
| `s_nor_b32` | ~(S0 \| S1) | D != 0 |
|
||||
| `s_xnor_b32` | ~(S0 ^ S1) | D != 0 |
|
||||
| `s_lshl_b32` | S0 << S1[4:0] | D != 0 |
|
||||
| `s_lshr_b32` | S0 >> S1[4:0], zero fill | D != 0 |
|
||||
| `s_ashr_i32` | S0 >> S1[4:0], sign fill | D != 0 |
|
||||
|
||||
The last eight were added through the semantic registry alone: one TOML entry
|
||||
each, with no hand-written Rust per form. Shifts use only the low five bits of
|
||||
S1 as the count, as the guide's pseudocode states (section 12.1); higher bits are
|
||||
ignored.
|
||||
|
||||
Sources are normal SGPRs, inline integers (-16 to 64) or one literal word.
|
||||
|
||||
These nine forms are declared as data in the semantic registry,
|
||||
These forms are declared as data in the semantic registry,
|
||||
`crates/isa/semantics/rdna2.toml`: opcode, operation, signedness, carry-in,
|
||||
SCC effect, operand rule and guide references. `crates/isa/generate_semantics.py`
|
||||
checks each declaration against the pinned AMD XML snapshot and rejects
|
||||
@@ -55,17 +70,17 @@ the registry.
|
||||
|
||||
## Not supported
|
||||
|
||||
- Every other SOP2 form, including the 64-bit bitwise forms.
|
||||
- Every other SOP2 form, including the 64-bit bitwise forms and `s_cselect_b64`.
|
||||
- Destinations other than s0-s105 (VCC, EXEC, TTMP and M0).
|
||||
- Sources other than normal SGPRs, inline integers and one literal.
|
||||
- Both sources selecting a literal.
|
||||
- ADDC or SUBB before SCC is set.
|
||||
- ADDC, SUBB or CSELECT before SCC is set.
|
||||
- Writes to the fixture's resource descriptors s0-s7.
|
||||
|
||||
## How it runs
|
||||
|
||||
Scalar state in a compute fixture is wave-uniform and known while the code is
|
||||
translated. As with `s_mov_b32` and `s_cmp_eq_u32`, the translator evaluates
|
||||
translated. As with `s_mov_b32` and the SOPC compares, the translator evaluates
|
||||
SOP2 forms itself. It resolves SCC-dependent branches and emits SGPR values
|
||||
read by `v_mov_b32_e32` as constants (`fixtures/golden/scalar-alu.ir`). So the
|
||||
IR and MSL contain the results, not scalar instructions.
|
||||
@@ -85,7 +100,7 @@ literal operands, bitwise results that set and clear SCC, and an
|
||||
Its expected output, input ^ 0x0000000e,
|
||||
was derived by hand.
|
||||
|
||||
`tests/validation/known_answers.rs` runs every supported form over 10 boundary
|
||||
`tests/validation/known_answers.rs` runs the first nine forms over 10 boundary
|
||||
operands squared, with SCC clear and set. That is 1,800 programs. The same file
|
||||
covers aliasing, inline and literal operands, and rejected forms. Expected
|
||||
values come from exact integer definitions in the test. Three implementations
|
||||
@@ -94,7 +109,94 @@ must agree with them:
|
||||
- the reference interpreter (exact integers, reduced modulo 2^32);
|
||||
- the independent interpreter (a bit-serial ripple-carry adder).
|
||||
|
||||
The eight logical and shift forms added through the registry have their own
|
||||
suite, `tests/validation/tests/sop2_stage_c.rs`: 6,896 cases whose expected
|
||||
values were derived from the guide separately from the registry, checked on
|
||||
both CPU interpreters and, through the translator, on native Metal. The
|
||||
LLVM-assembled `fixtures/rdna2/scalar-logic.s` (expected input ^ 0x887f00f8)
|
||||
runs on all three and on native Metal.
|
||||
|
||||
`scalar_alu_native_metal_known_answers` runs the fixture, the 1,800 programs
|
||||
and the aliasing and immediate cases on native Metal with API and shader
|
||||
validation. `scripts/test-gpu.sh` runs it. This is local evidence from one
|
||||
Apple M5 Pro; independent acceptance is pending.
|
||||
|
||||
## Arithmetic, select and bit-field forms
|
||||
|
||||
Sixteen more 32-bit SOP2 forms are declared in the registry with the same
|
||||
operand rule (`sop2_sgpr`), each one TOML entry over a shared primitive:
|
||||
|
||||
| Form | D | SCC |
|
||||
| --- | --- | --- |
|
||||
| `s_min_i32`, `s_min_u32` | S0 if S0 < S1 (signed or unsigned), else S1 | S0 < S1 |
|
||||
| `s_max_i32`, `s_max_u32` | S0 if S0 > S1, else S1 | S0 > S1 |
|
||||
| `s_cselect_b32` | SCC ? S0 : S1 | read, not written |
|
||||
| `s_bfm_b32` | ((1 << S0[4:0]) - 1) << S1[4:0] | unchanged |
|
||||
| `s_mul_i32` | low 32 bits of S0 * S1 | unchanged |
|
||||
| `s_mul_hi_u32`, `s_mul_hi_i32` | high 32 bits of the unsigned or signed 64-bit product | unchanged |
|
||||
| `s_bfe_u32` | (S0 >> S1[4:0]) masked to S1[22:16] bits | D != 0 |
|
||||
| `s_bfe_i32` | (S0 >> S1[4:0], sign fill) masked to S1[22:16] bits, sign-extended from the field's top bit | D != 0 |
|
||||
| `s_absdiff_i32` | \|S0 - S1\| of the wrapped 32-bit difference (0x80000000 stays) | D != 0 |
|
||||
| `s_lshl1_add_u32` to `s_lshl4_add_u32` | (S0 << N) + S1, N = 1 to 4 | carry out of the exact sum, counting bits shifted out of S0 |
|
||||
|
||||
These follow the guide's 12.1 pseudocode and Tables 11, 12 and 14 (pages
|
||||
34-36). Min and max compare strictly, so equal operands give S1 and SCC = 0.
|
||||
The guide leaves two C-like operators open; Xenora reads them as exact
|
||||
arithmetic: a BFE width of 32 to 127 keeps every shifted bit, and a width of 0
|
||||
gives 0. These are guide readings, not hardware evidence. CSELECT is refused
|
||||
when SCC has not been set, as ADDC and SUBB are.
|
||||
|
||||
The registry gained the vocabulary for them: the operations above, a
|
||||
`selected_src0` SCC effect for min and max, `carry_in = "scc"` for the select
|
||||
condition, and a declared `shift_amount` (1 to 4) for the shift-and-add forms.
|
||||
The generated `ScalarAluOp::evaluate` now returns `(u32, Option<bool>)`, with
|
||||
`None` for forms that leave SCC unchanged.
|
||||
|
||||
`tests/validation/tests/sop2_arith.rs` checks 21,070 cases, with expected values
|
||||
derived from the guide (including its ABSDIFF examples) separately from the
|
||||
registry, on both CPU interpreters and, through the translator, on native
|
||||
Metal; its 597 rejected programs are checked on the CPU interpreters and the
|
||||
compiler. `fixtures/rdna2/scalar-arith.s` (LLVM-assembled, expected input ^
|
||||
0x81157dfe) chains all sixteen, including a min tie and CSELECT on both SCC
|
||||
values, and shows SCC surviving the forms that do not write it.
|
||||
|
||||
## SOPC compares
|
||||
|
||||
The twelve 32-bit SOPC integer compares `s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32}`
|
||||
are declared in the same registry (operand rule `sopc_scalar`). Each sets only
|
||||
SCC, to whether the relation holds with SSRC0 on the left; LG means not equal.
|
||||
EQ and LG give the same result for `_i32` and `_u32`; GT, GE, LT and LE compare
|
||||
two's-complement values for `_i32` and unsigned values for `_u32` (guide section
|
||||
12.4). Sources follow the SOP2 rule: normal SGPRs, inline integers or one
|
||||
literal. Both sources selecting the literal encoding (255) is rejected for SOPC
|
||||
as for SOP2; whether the guide allows one shared literal there was not settled.
|
||||
|
||||
`tests/validation/tests/sopc_stage_d.rs` checks 7,824 cases, with expected
|
||||
values derived from the guide separately from the registry, on both CPU
|
||||
interpreters and, through the translator, on native Metal (compiled per case
|
||||
and read back from nine distinct generated kernels). Its 348 rejected programs
|
||||
are checked on both CPU interpreters and against the compiler, which rejects
|
||||
them before any Metal dispatch. `fixtures/rdna2/scalar-compare.s` (LLVM-assembled, expected input ^
|
||||
0x00000d5b) records every compare's SCC through an `s_cbranch_scc0` per form.
|
||||
|
||||
## SOP1 unary forms
|
||||
|
||||
Eleven 32-bit SOP1 forms are declared in the registry (operand rule
|
||||
`sop1_sgpr`): `s_not_b32`, `s_brev_b32`, `s_bcnt0_i32_b32`, `s_bcnt1_i32_b32`,
|
||||
`s_ff0_i32_b32`, `s_ff1_i32_b32`, `s_flbit_i32_b32`, `s_flbit_i32`,
|
||||
`s_sext_i32_i8`, `s_sext_i32_i16` and `s_abs_i32`. Following the guide (section
|
||||
12.3): a find-first or find-last search that finds nothing returns -1
|
||||
(0xffffffff); `s_flbit_i32` returns -1 for both 0 and -1; sign extension reads
|
||||
S0[7:0] or S0[15:0]; `s_abs_i32` of 0x80000000 is 0x80000000. Only NOT, BCNT0,
|
||||
BCNT1 and ABS write SCC, as D != 0; the other seven leave it unchanged.
|
||||
`s_mov_b32` stays hand-written, because it also accepts EXEC and VCC halves as
|
||||
destinations. As for SOP2, destinations s0-s7 are refused when a fixture runs
|
||||
(they hold its buffer descriptors), and float inline constants are rejected.
|
||||
|
||||
`tests/validation/tests/sop1_unary.rs` checks 4,126 cases, with expected values
|
||||
derived from the guide (including its worked examples) separately from the
|
||||
registry, on both CPU interpreters and, through the translator, on native
|
||||
Metal; its 231 rejected programs are checked on the CPU interpreters and the
|
||||
compiler. `fixtures/rdna2/scalar-unary.s` (LLVM-assembled, expected input ^
|
||||
0x0f0080f5) chains all eleven and shows SCC surviving the forms that do not
|
||||
write it.
|
||||
@@ -24,19 +24,19 @@ acceptance remain outside the verified count. All results concern synthetic fixt
|
||||
| MUBUF | 75 | 2 | 0 | 2 | 2 | 2 | 2 | 2 | 0 |
|
||||
| SCRATCH | 22 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| SMEM | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| SOP1 | 65 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
|
||||
| SOP2 | 51 | 9 | 9 | 9 | 9 | 9 | 0 | 0 | 12 |
|
||||
| SOPC | 18 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
|
||||
| SOP1 | 65 | 12 | 11 | 12 | 12 | 12 | 1 | 1 | 11 |
|
||||
| SOP2 | 51 | 33 | 33 | 33 | 33 | 33 | 0 | 0 | 12 |
|
||||
| SOPC | 18 | 12 | 12 | 12 | 12 | 12 | 1 | 1 | 7 |
|
||||
| SOPK | 27 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
|
||||
| SOPP | 36 | 6 | 0 | 6 | 6 | 6 | 4 | 4 | 0 |
|
||||
| VINTRP | 3 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 |
|
||||
| VOP1 | 81 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
|
||||
| VOP2 | 47 | 8 | 0 | 8 | 8 | 8 | 7 | 7 | 0 |
|
||||
| VOP2 | 47 | 20 | 12 | 20 | 20 | 20 | 7 | 7 | 7 |
|
||||
| VOP3 | 416 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
|
||||
| VOP3P | 29 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| VOP3SDST | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
|
||||
| VOPC | 190 | 12 | 0 | 12 | 12 | 12 | 0 | 0 | 0 |
|
||||
| **Total** | 1465 | 42 | 9 | 46 | 42 | 42 | 18 | 18 | 12 |
|
||||
| **Total** | 1465 | 100 | 68 | 104 | 100 | 100 | 18 | 18 | 37 |
|
||||
|
||||
## Unsupported operand variants
|
||||
|
||||
@@ -44,4 +44,7 @@ The table counts distinct variant names per family across registry operand rules
|
||||
|
||||
| Family | Operand rule | Unsupported variants |
|
||||
| --- | --- | --- |
|
||||
| SOP1 | `sop1_sgpr` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc`, `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc` |
|
||||
| SOP2 | `sop2_sgpr` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc`, `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc`, `two_literals` |
|
||||
| SOPC | `sopc_scalar` | `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc`, `two_literals` |
|
||||
| VOP2 | `vop2_vgpr` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` |
|
||||
@@ -51,11 +51,16 @@ error.
|
||||
| `family` | Encoding family; must match the XML base encoding | e.g. `SOP2` |
|
||||
| `opcode` | Opcode; must match the XML | non-negative integer |
|
||||
| `variant` | Rust enum variant of the typed operation | CamelCase, e.g. `AddU32` |
|
||||
| `operation` | The primitive the form uses | `add`, `sub`, `and`, `or`, `xor` |
|
||||
| `signedness` | How operands are read | `unsigned`, `signed`, `bitwise` (`bitwise` exactly for `and`, `or`, `xor`) |
|
||||
| `carry_in` | Whether the form reads SCC as carry-in or borrow-in | `none`, `scc` (`scc` only for unsigned `add` and `sub`) |
|
||||
| `operation` | The primitive the form uses | `add`, `sub`, `and`, `or`, `xor`, `andn2`, `orn2`, `nand`, `nor`, `xnor`, `lshl`, `lshr`, `ashr`, `min`, `max`, `cselect`, `bfm`, `mul`, `mul_hi`, `bfe`, `absdiff`, `lshl_add`, `mul24`, `mul_hi24` (vector only), `compare` and the SOP1 unaries |
|
||||
| `signedness` | How operands are read | `unsigned`, `signed`, `bitwise` (always `bitwise` for the logical operations, `cselect` and `bfm`; never for the arithmetic ones, `add`, `sub`, `min`, `max`, `mul`, `mul_hi`, `bfe`, `absdiff` and `lshl_add`; shifts take their primitive's signedness) |
|
||||
| `carry_in` | Whether the form reads SCC: carry-in, borrow-in or the select condition | `none`, `scc` (`scc` only for unsigned `add` and `sub`, and required for `cselect`) |
|
||||
| `width` | Operand and result width in bits | `32` |
|
||||
| `scc` | What the form writes to SCC | `carry_out`, `borrow`, `signed_overflow`, `nonzero`, `unchanged` |
|
||||
| `source_bits` | Sign extension only: the low bits of S0 that are read. The XML must list S0 with that size and format (`FMT_NUM_I8` or `FMT_NUM_I16`) | `8`, `16`; required for `sext`, rejected elsewhere |
|
||||
| `relation` | Compares only: the relation tested with S0 on the left | `eq`, `lg` (not equal), `gt`, `ge`, `lt`, `le`; required for `compare`, rejected elsewhere |
|
||||
| `source_order` | Vector forms only: `reversed` when the guide computes `op(S1, S0)` (the XML records no operand order); absent otherwise | `reversed` |
|
||||
| `shift_amount` | `lshl_add` only: the fixed left shift of S0 before the add | `1` to `4`; required for `lshl_add`, rejected elsewhere |
|
||||
| `shift_count_bits` | Shifts only: the low bits of S1 used as the count. The generator masks S1 with it, and the XML must list S1 as unsigned | `5` (log2 of `width`); required for shifts, rejected elsewhere |
|
||||
| `scc` | What the form writes to SCC | `carry_out`, `borrow`, `signed_overflow`, `nonzero`, `relation` (compares only), `selected_src0` (min and max: S0 won the strict compare, so a tie gives 0), `unchanged` |
|
||||
| `vcc`, `exec` | Effect on VCC and EXEC, stated rather than implied | `unchanged` |
|
||||
| `wave` | Wave sizes the form is valid in | `any` (`wave32` is in the vocabulary but rejected until the decoder can enforce it) |
|
||||
| `operands` | Name of an `[operand_rules]` entry for the same family | e.g. `sop2_sgpr` |
|
||||
@@ -71,7 +76,39 @@ fixes the `scc` value:
|
||||
| `sub` / `unsigned` | `borrow` | `sub_borrow_u32` | allowed |
|
||||
| `add` / `signed` | `signed_overflow` | `add_overflow_i32` | no |
|
||||
| `sub` / `signed` | `signed_overflow` | `sub_overflow_i32` | no |
|
||||
| `and`, `or`, `xor` / `bitwise` | `nonzero` | `and_nonzero_b32`, `or_nonzero_b32`, `xor_nonzero_b32` | no |
|
||||
| `and`, `or`, `xor`, `andn2`, `orn2`, `nand`, `nor`, `xnor` / `bitwise` | `nonzero` | `and_nonzero_b32`, `or_nonzero_b32`, `xor_nonzero_b32`, `andn2_nonzero_b32`, `orn2_nonzero_b32`, `nand_nonzero_b32`, `nor_nonzero_b32`, `xnor_nonzero_b32` | no |
|
||||
| `lshl` / `bitwise` | `nonzero` | `lshl_nonzero_b32` | no |
|
||||
| `lshr` / `unsigned` | `nonzero` | `lshr_nonzero_b32` | no |
|
||||
| `ashr` / `signed` | `nonzero` | `ashr_nonzero_i32` | no |
|
||||
| `not`, `bcnt0`, `bcnt1` / `bitwise` | `nonzero` | `not_nonzero_b32`, `bcnt0_nonzero_b32`, `bcnt1_nonzero_b32` | no |
|
||||
| `brev`, `ff0`, `ff1`, `flbit` / `bitwise` | `unchanged` | `brev_b32`, `ff0_b32`, `ff1_b32`, `flbit_b32` | no |
|
||||
| `flbit`, `sext` / `signed` | `unchanged` | `flbit_i32`, `sext_i32` | no |
|
||||
| `abs` / `signed` | `nonzero` | `abs_nonzero_i32` | no |
|
||||
| `min`, `max` / `signed` or `unsigned` | `selected_src0` | `min_i32`/`min_u32`, `max_i32`/`max_u32` | no |
|
||||
| `cselect` / `bitwise` | `unchanged` | `cselect_b32` | required |
|
||||
| `bfm` / `bitwise` | `unchanged` | `bfm_b32` | no |
|
||||
| `mul` / `signed` | `unchanged` | `mul_lo_i32` | no |
|
||||
| `mul_hi` / `unsigned` or `signed` | `unchanged` | `mul_hi_u32`, `mul_hi_i32` | no |
|
||||
| `bfe` / `unsigned` or `signed` | `nonzero` | `bfe_nonzero_u32`, `bfe_nonzero_i32` | no |
|
||||
| `absdiff` / `signed` | `nonzero` | `absdiff_nonzero_i32` | no |
|
||||
| `lshl_add` / `unsigned` | `carry_out` | `lshl_add_carry_u32` (with `shift_amount`) | no |
|
||||
| `compare` / `signed` or `unsigned` | `relation` | `eq_b32`, `ne_b32` (for both signednesses), `gt_i32`/`gt_u32`, `ge_*`, `lt_*`, `le_*` | no |
|
||||
|
||||
Vector forms (operand rule `vop2_vgpr`, kind `vector`) use a separate table:
|
||||
the pair picks the per-lane `VectorBinary` the MSL lowering uses, and `scc`
|
||||
must be `unchanged` (VOP2 integer forms write no SCC, VCC or EXEC):
|
||||
|
||||
| `operation` / `signedness` | `VectorBinary` |
|
||||
| --- | --- |
|
||||
| `add` / `unsigned`, `sub` / `unsigned` | `Add`, `Sub` |
|
||||
| `xnor` / `bitwise` | `Xnor` |
|
||||
| `min`, `max` / `signed` or `unsigned` | `MinSigned`, `MinUnsigned`, `MaxSigned`, `MaxUnsigned` |
|
||||
| `mul24`, `mul_hi24` / `signed` or `unsigned` | `Mul24Signed`, `Mul24Unsigned`, `MulHi24Signed`, `MulHi24Unsigned` |
|
||||
|
||||
A compare must use an operand rule of the compare kind (`sopc_scalar`: two
|
||||
sources, no destination), a unary operation one of the unary kind (`sop1_sgpr`:
|
||||
one source and an SGPR destination), and a two-source ALU operation
|
||||
`sop2_sgpr`.
|
||||
|
||||
Behaviour is chosen only from these declared fields, never from the mnemonic.
|
||||
|
||||
@@ -82,12 +119,13 @@ vocabularies above, it rejects:
|
||||
|
||||
- contradictions: a declared `scc` or `carry_in` that the primitive does not
|
||||
have, `bitwise` on an arithmetic operation or the reverse;
|
||||
- duplicates: the same `name`, the same `(family, opcode)` or the same
|
||||
`variant` declared twice;
|
||||
- duplicates: the same `name`, the same `(family, opcode)`, or the same
|
||||
`variant` twice in one generated enum;
|
||||
- XML disagreements: a family with no XML encoding, a form with no default XML
|
||||
variant, a different opcode, an SCC input or output the XML does not show (or
|
||||
that the declaration omits), an operand width other than `width`, a signed
|
||||
declaration on unsigned XML formats or the reverse, an operand direction that
|
||||
declaration on unsigned XML formats or the reverse (a shift count or the `bfe`
|
||||
field descriptor in S1 must be `FMT_NUM_U32` whatever the signedness), an operand direction that
|
||||
differs, and XML operands the operand rule does not cover;
|
||||
- references: a spec citing an undeclared document, a bad section or page, or
|
||||
no guide page at all;
|
||||
|
||||
@@ -127,8 +127,11 @@ While VCC_LO is lane-derived it may be read only by:
|
||||
lanes (inactive lanes keep vD, as for any partial-EXEC move);
|
||||
3. SRC0 of a supported compare (`v_cmp_* vcc_lo, vcc_lo, vN`), which reads the
|
||||
old VCC_LO in every active lane before the new value is written.
|
||||
4. SRC0 of a registry VOP2 integer form (for example
|
||||
`v_add_nc_u32_e32 vD, vcc_lo, vN`), which reads the 32-bit mask in every
|
||||
active lane, as `v_mov_b32_e32` does.
|
||||
|
||||
`v_mov_b32_e32 vD, vcc_lo` follows the usual EXEC rules: with EXEC_LO = 0 it
|
||||
`v_mov_b32_e32 vD, vcc_lo` and the VOP2 forms follow the usual EXEC rules: with EXEC_LO = 0 it
|
||||
is skipped without reading VCC; otherwise VCC_LO must be known or
|
||||
lane-derived. Every other read of vcc_lo is rejected in any state: the
|
||||
supported scalar instructions (`s_mov_b32`, SOP2, `s_cmp_eq_u32`) do not
|
||||
|
||||
@@ -135,6 +135,138 @@ recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_not_b32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = ~S0; SCC = D != 0"
|
||||
representation = "`BE890708`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_brev_b32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0 bit-reversed; SCC unchanged"
|
||||
representation = "`BE8A0B08`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_bcnt0_i32_b32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = count of zero bits; SCC = D != 0"
|
||||
representation = "`BE8C0D08`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_bcnt1_i32_b32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = count of one bits; SCC = D != 0"
|
||||
representation = "`BE8B0F08`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_ff0_i32_b32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = index of the lowest zero bit, or -1; SCC unchanged"
|
||||
representation = "`BE8E11FF 0000FFFF`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_ff1_i32_b32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = index of the lowest one bit, or -1; SCC unchanged"
|
||||
representation = "`BE8D13FF 00400000`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_flbit_i32_b32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = zeros above the highest one bit, or -1; SCC unchanged"
|
||||
representation = "`BE8F1508`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_flbit_i32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = bits above the highest bit differing from the sign, or -1; SCC unchanged"
|
||||
representation = "`BE9017FF FFF00000`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_sext_i32_i8"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0[7:0] sign-extended; SCC unchanged"
|
||||
representation = "`BE911908`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_sext_i32_i16"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0[15:0] sign-extended; SCC unchanged"
|
||||
representation = "`BE921AFF 00018000`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_abs_i32"
|
||||
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = |S0| (0x80000000 stays); SCC = D != 0"
|
||||
representation = "`BE933412`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_eq_u32"
|
||||
encoding = "Normal SGPR or integer operands, with at most one source selecting a literal"
|
||||
@@ -147,6 +279,138 @@ recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_eq_i32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 == S1 (signed)"
|
||||
representation = "`BF00C108`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_lg_i32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 != S1 (signed)"
|
||||
representation = "`BF010908`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_gt_i32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 > S1 (signed)"
|
||||
representation = "`BF020908`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_ge_i32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 >= S1 (signed)"
|
||||
representation = "`BF030909`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_lt_i32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 < S1 (signed)"
|
||||
representation = "`BF040908`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_le_i32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 <= S1 (signed)"
|
||||
representation = "`BF050809`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_lg_u32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 != S1 (unsigned)"
|
||||
representation = "`BF07FF0A 89ABCDEF`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_gt_u32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 > S1 (unsigned)"
|
||||
representation = "`BF080908`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_ge_u32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 >= S1 (unsigned)"
|
||||
representation = "`BF090809`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_lt_u32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 < S1 (unsigned)"
|
||||
representation = "`BF0A0809`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cmp_le_u32"
|
||||
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 <= S1 (unsigned)"
|
||||
representation = "`BF0BC009`"
|
||||
lowering = "resolved SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_add_u32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; SCC = carry-out"
|
||||
@@ -255,6 +519,294 @@ recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_andn2_b32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 & ~S1; SCC = result != 0"
|
||||
representation = "`8A09FF08 FF00FF00`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_orn2_b32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 | ~S1; SCC = result != 0"
|
||||
representation = "`8B0AC109`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_nand_b32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 & S1); SCC = result != 0"
|
||||
representation = "`8C0B0808`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_nor_b32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 | S1); SCC = result != 0"
|
||||
representation = "`8D0C090B`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_xnor_b32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ~(S0 ^ S1); SCC = result != 0"
|
||||
representation = "`8E0D080C`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_lshl_b32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 << S1[4:0]; SCC = result != 0"
|
||||
representation = "`8F0EA40D`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_lshr_b32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0], zero fill; SCC = result != 0"
|
||||
representation = "`900FFF0E FFFFFFE1`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_ashr_i32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0], sign fill; SCC = result != 0"
|
||||
representation = "`91109F0E`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_min_i32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 < S1 (signed) else S1; SCC = S0 < S1"
|
||||
representation = "`830A0908`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_min_u32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 < S1 (unsigned) else S1; SCC = S0 < S1"
|
||||
representation = "`83988509`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_max_i32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 > S1 (signed) else S1; SCC = S0 > S1"
|
||||
representation = "`84170908`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_max_u32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 > S1 (unsigned) else S1; SCC = S0 > S1"
|
||||
representation = "`848C0908`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_cselect_b32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = SCC ? S0 : S1; reads SCC, SCC unchanged"
|
||||
representation = "`850B0809`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_bfm_b32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ((1 << S0[4:0]) - 1) << S1[4:0]; SCC unchanged"
|
||||
representation = "`920D848C`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_mul_i32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = low 32 bits of S0 * S1; SCC unchanged"
|
||||
representation = "`930F0908`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_bfe_u32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0] masked to S1[22:16] bits; SCC = D != 0"
|
||||
representation = "`9390FF08 00080004`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_bfe_i32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0] (sign fill) masked to S1[22:16] bits, sign-extended; SCC = D != 0"
|
||||
representation = "`9411FF08 00080004`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_absdiff_i32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = |S0 - S1| of the 32-bit difference (0x80000000 stays); SCC = D != 0"
|
||||
representation = "`96120809`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_lshl1_add_u32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 1) + S1; SCC = carry out of the exact sum"
|
||||
representation = "`970E0908`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_lshl2_add_u32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 2) + S1; SCC = carry out of the exact sum"
|
||||
representation = "`97990909`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_lshl3_add_u32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 3) + S1; SCC = carry out of the exact sum"
|
||||
representation = "`98130808`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_lshl4_add_u32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 4) + S1; SCC = carry out of the exact sum"
|
||||
representation = "`9894D009`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_mul_hi_u32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = high 32 bits of the unsigned product; SCC unchanged"
|
||||
representation = "`9A950808`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "s_mul_hi_i32"
|
||||
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = high 32 bits of the signed product; SCC unchanged"
|
||||
representation = "`9B160808`"
|
||||
lowering = "resolved scalar state and SCC"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_cmp_lt_i32_e32"
|
||||
encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 < S1), fully written"
|
||||
@@ -542,6 +1094,150 @@ recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_mul_i32_i24_e32"
|
||||
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = low 32 bits of sext(S0[23:0]) * sext(S1[23:0])"
|
||||
representation = "`120402C3`"
|
||||
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_mul_hi_i32_i24_e32"
|
||||
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = bits 63:32 of sext(S0[23:0]) * sext(S1[23:0])"
|
||||
representation = "`14060208`"
|
||||
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_mul_u32_u24_e32"
|
||||
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = low 32 bits of S0[23:0] * S1[23:0]"
|
||||
representation = "`160802FF 00123456`"
|
||||
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_mul_hi_u32_u24_e32"
|
||||
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = bits 63:32 of S0[23:0] * S1[23:0]"
|
||||
representation = "`180A0208`"
|
||||
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_min_i32_e32"
|
||||
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = signed min(S0, S1)"
|
||||
representation = "`220C0501`"
|
||||
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_max_i32_e32"
|
||||
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = signed max(S0, S1)"
|
||||
representation = "`240E0285`"
|
||||
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_min_u32_e32"
|
||||
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = unsigned min(S0, S1)"
|
||||
representation = "`26100303`"
|
||||
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_max_u32_e32"
|
||||
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = unsigned max(S0, S1)"
|
||||
representation = "`28120208`"
|
||||
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_xnor_b32_e32"
|
||||
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = ~(S0 ^ S1)"
|
||||
representation = "`3C140B04`"
|
||||
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_add_nc_u32_e32"
|
||||
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = S0 + S1, no carry"
|
||||
representation = "`4A160F06`"
|
||||
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_sub_nc_u32_e32"
|
||||
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = S0 - S1, no carry"
|
||||
representation = "`4C181308`"
|
||||
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[[instruction]]
|
||||
form = "v_subrev_nc_u32_e32"
|
||||
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = S1 - S0, no carry"
|
||||
representation = "`4E1A170A`"
|
||||
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
|
||||
reference = "implemented"
|
||||
cpu = "local known-answer test passed"
|
||||
gpu = "local Apple M5 readback passed; acceptance pending"
|
||||
recognized = true
|
||||
decoded = true
|
||||
llvm = "three-way passed"
|
||||
|
||||
[guest_milestones]
|
||||
X1 = "accepted"
|
||||
X2 = "accepted"
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
# Infrastructure QA tooling
|
||||
|
||||
Standalone helpers under `scripts/qa/` and `scripts/release/`. They do not replace
|
||||
`scripts/audit/*`, `scripts/benchmark.sh` or `scripts/test-gpu.sh`. New checks are
|
||||
advisory until reviewed.
|
||||
|
||||
## Suites
|
||||
|
||||
| Path | Role |
|
||||
| --- | --- |
|
||||
| `scripts/qa/exit_pipe.py` | Preserve command exit status |
|
||||
| `scripts/qa/orchestrate.py` | Structured multi-suite runs and failure excerpts |
|
||||
| `scripts/qa/pr_validate.py` | Advisory PR scope, DCO, artifact and evidence checks |
|
||||
| `scripts/qa/bench_stats.py` | Median/percentile analysis of existing samples |
|
||||
| `scripts/qa/regression.py` | Compare historical orchestration JSON reports |
|
||||
| `scripts/qa/env_check.py` | Host, toolchain and branch diagnostics |
|
||||
| `scripts/qa/claim_conflict.py` | Read-only file-scope conflict prediction |
|
||||
| `scripts/release/macho.py` | ARM64 arch and forbidden-linkage checks |
|
||||
| `scripts/release/bundle.py` | App bundle layout and codesign diagnosis |
|
||||
| `scripts/release/manifest.py` | Checksums, manifests, license inventory |
|
||||
|
||||
## Tests
|
||||
|
||||
```sh
|
||||
PYTHONPATH=scripts python3 -m unittest discover -s tests/qa
|
||||
PYTHONPATH=scripts python3 -m unittest discover -s tests/release
|
||||
```
|
||||
|
||||
## Phase II CLIs
|
||||
|
||||
```sh
|
||||
PYTHONPATH=scripts python3 -m qa rdna2 inventory --compact
|
||||
PYTHONPATH=scripts python3 -m qa rdna2 candidates --family SOP2 --status reuse-primitives --limit 50
|
||||
PYTHONPATH=scripts python3 -m qa rdna2 plan --limit 20 --compact
|
||||
PYTHONPATH=scripts python3 -m qa rdna2 manifests --status reuse-primitives --limit 10 --claims claims.json
|
||||
PYTHONPATH=scripts python3 -m qa rdna2 reconcile --compact
|
||||
PYTHONPATH=scripts python3 -m qa rdna2 discrepancies
|
||||
PYTHONPATH=scripts python3 -m qa rdna2 diff --before before.json --after after.json --compact
|
||||
PYTHONPATH=scripts python3 -m qa verify quick
|
||||
PYTHONPATH=scripts python3 -m qa cpu-coverage --blockers
|
||||
PYTHONPATH=scripts python3 -m qa bench-compare --baseline b.json --current c.json
|
||||
PYTHONPATH=scripts python3 -m release readiness --revision HEAD --live --binary path --app path.app
|
||||
```
|
||||
|
||||
RDNA2 planning is read-only over the AMD snapshot, semantic registry, decoder tables and
|
||||
`docs/status.toml`. Candidates and manifests are never counted as implemented forms.
|
||||
Family claims exclude those families; path-only claims block candidates whose default
|
||||
permitted files overlap. Reconcile reports mismatches without adjusting planner counts.
|
||||
Binary file not shown.
@@ -0,0 +1,49 @@
|
||||
# SPDX-License-Identifier: GPL-3.0-or-later
|
||||
"""Generate the clean-room binary asset fixture for Gate 6 VFS testing."""
|
||||
|
||||
import argparse
|
||||
import math
|
||||
from pathlib import Path
|
||||
from struct import pack
|
||||
|
||||
|
||||
def generate_asset():
|
||||
data = bytearray()
|
||||
# 1. Header: Magic 'XAST' (4B), version 1 (4B), width 2 (4B), height 2 (4B), audio_samples 256 (4B)
|
||||
data += b"XAST"
|
||||
data += pack("<IIII", 1, 2, 2, 256)
|
||||
|
||||
# 2. Texture data: 2x2 RGBA8 (16 bytes)
|
||||
# (0,0): Orange [255, 128, 0, 255]
|
||||
# (1,0): Purple [128, 0, 255, 255]
|
||||
# (0,1): Teal [0, 255, 128, 255]
|
||||
# (1,1): Pink [255, 0, 128, 255]
|
||||
texture_bytes = bytes([
|
||||
255, 128, 0, 255,
|
||||
128, 0, 255, 255,
|
||||
0, 255, 128, 255,
|
||||
255, 0, 128, 255,
|
||||
])
|
||||
data += texture_bytes
|
||||
|
||||
# 3. Audio data: 256 samples of 440Hz sine wave (16-bit signed PCM mono, 512 bytes)
|
||||
sample_rate = 48000
|
||||
freq = 440.0
|
||||
for i in range(256):
|
||||
sample_val = int(32767.0 * 0.5 * math.sin(2.0 * math.pi * freq * (i / sample_rate)))
|
||||
data += pack("<h", sample_val)
|
||||
|
||||
return bytes(data)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--check", action="store_true")
|
||||
args = parser.parse_args()
|
||||
path = Path(__file__).parent / "asset.bin"
|
||||
expected = generate_asset()
|
||||
if args.check:
|
||||
if not path.exists() or path.read_bytes() != expected:
|
||||
parser.exit(1, f"asset binary differs from generator: {path}\n")
|
||||
else:
|
||||
path.write_bytes(expected)
|
||||
Loaded 100 of 191 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user