Compare commits

...
Author SHA1 Message Date
Swastick Chowdhury e3bbc955bc ffi: share one Metal device and queue across frame-loop sessions (#290)
Each frame-loop session opened its own Metal command queue. The GPU
driver allocates a per-queue working set on the first command buffer
(about 45 MiB on an Apple M5 with validation) and frees it
asynchronously 10-50 ms after the queue is released, so the footprint
read right after a session ended swung by about 50 MiB and the
repeated-sessions footprint test failed intermittently (5 of 30 runs).
There was no leak. Sessions now share one process-wide NativeCompute,
which is Send + Sync, so the working set is allocated once and kept.

Remove the settled_footprint wait added in #292: the original test
measures the immediate footprint again. Add a 50-session regression
test (completion, pause and resume, destroy while running) and a
concurrent two-session test for shared-queue correctness and session
isolation.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 19:07:18 +05:30
Ranveer Soni c7351c846d Merge pull request #291 from Swastickc/task/289-segment-tests
loader: restore and complete FS/GS segment-override tests (#289)
2026-11-24 18:13:09 +05:30
Ranveer Soni 78d52c0eeb Merge pull request #292 from Swastickc/task/290-footprint-settle
test(ffi): read a settled memory footprint in the frame-loop test (#290)
2026-11-24 18:12:55 +05:30
Ranveer Soni 4ebbd4767f Merge pull request #288 from jelly013/cpu-runtime-continuation
CPU and runtime: shared x86-64 decoder, SSE2, exact floating point and typed imports
2026-11-24 18:12:23 +05:30
Swastick Chowdhury 5a6a3b3e4f test(ffi): read a settled memory footprint in the frame-loop test (#290)
After a session is destroyed, Metal returns its memory asynchronously;
an immediate reading can sit up to about 45 MiB above the floor it
returns to within a second. Read the footprint until two consecutive
readings agree within 1 MiB (at most 5 s) for both the baseline and the
final sample. The 16 MiB threshold and Metal validation are unchanged,
and an injected per-session leak still fails the test.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 18:08:35 +05:30
Swastick Chowdhury 8cae9772b6 loader: restore and complete FS/GS segment-override tests (#289)
Restore the six #280 regression tests that the merge resolving #280's
conflict with #283 removed. Add FS and GS RIP-relative loads and stores
with positive and negative displacements, a differential run comparing
the native DBT and interpreter registers and memory bytes, and
RIP-relative faults reporting the segment-adjusted address. Make the
existing differential test compare both paths' memory.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 18:08:32 +05:30
jelly013 13c259027b Merge upstream main (#286, #287) into CPU/runtime continuation
Keep the probe truncation test and the bounds check on section offsets from

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
#286, with imports on the shared parser.
2026-11-24 13:35:58 +01:00
jelly013 42825b223b Merge upstream main (#280, #281, #282, #283) into CPU/runtime continuation
Keep every upstream test and the new assembler forms. Keep the shared
decoder and lowering, which already cover the merged MOVZX, MOVSX and
segment fixes, and adopt upstream's rule that GS applies when FS and GS
overrides are combined. Add segment regressions for RIP-relative operands,
negative displacements and fault addresses in both engines.

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-24 13:33:18 +01:00
Ranveer Soni 4db0b9c530 Merge pull request #286 from Swastickc/task/270-probe-truncated-names
loader: stop the static probe panicking on truncated PE names (#270)
2026-11-24 18:01:12 +05:30
Ranveer Soni 2b97a66db9 Merge pull request #287 from Swastickc/task/284-native-app-gate6
app: audio PCM streaming and virtual filesystem integration (#284)
2026-11-24 18:00:58 +05:30
jelly013 280cd492fe runtime: one import resolver and typed service adapters
Parse import directories with one bounded parser shared by the static probe
and the binder, and resolve imports through one registry lookup. Refuse
conflicting registrations, keep ordinals apart from names, match API sets
exactly, and bind only when every import resolves.

Generate typed Win64 adapters, metadata and a coverage report from a
declarative service registry. Pass floating-point arguments and results in
XMM registers, and stop the guest if a service changes a nonvolatile
register. Make unimplemented generated wrappers fail explicitly.

Verify 20 services by calling them from translated guest code through bound
import slots, and the parser on damaged tables.

Refs #201, #270

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-24 13:29:40 +01:00
Swastick Chowdhury b0984673d8 app: audio PCM streaming and virtual filesystem integration (#284)
Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 17:57:54 +05:30
Ranveer Soni c6a354bca5 Merge pull request #285 from ranveersoni98/feat/rdna2-planner-opt
feat(qa): tighten RDNA2 planning filters, manifests and claim exclusion
2026-11-24 17:57:31 +05:30
Swastick Chowdhury c4d0b6c000 loader: stop the static probe panicking on truncated PE names (#270)
`probe_pe_bytes` panicked on a truncated PE instead of returning an error or
reporting the import as unreadable.

The cause was in `crates/loader/src/probe.rs`. `rva_to_offset` maps an RVA to
a file offset using the section header, so on a truncated file the computed
offset can point past the end of the buffer. The loop that finds the
terminating NUL then stopped at `bytes.len()`, leaving `no > end`, and the
slice `bytes[no..end]` panicked with "range start index 1632 out of range for
slice of length 1556".

Fix both name reads:

- `rva_to_offset` now returns `None` when the computed offset is at or past
  the end of the file, because such an offset is not readable. This applies to
  every caller, so the relocation, TLS, thunk and disassembly paths are
  covered by the same rule.
- A new `read_c_string` helper reads a NUL-terminated string and returns
  `None` when the string starts outside the buffer. It replaces the
  hand-written scan in the DLL-name read and in the symbol-name read, which
  also had an unchecked `ho + 2` for the two-byte import hint.

A name that cannot be read is reported as `UNKNOWN.dll` or `UNKNOWN_SYM`,
which is what the probe already did when the RVA did not resolve at all. The
probe stays read-only and still performs no guest execution.

Add a regression test that truncates the in-repo `fixtures/pe/trusted-runner.exe`
at every length from 1 to the file size and asserts that `probe_pe_bytes`
never panics. The reported range was 1,556 to 1,665 bytes; the sweep covers
the whole file, so it also covers the other name and thunk reads that the
report noted might share the pattern. The test fails against the unmodified
probe with the reported panic and passes with this change.

Closes #270

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 17:57:26 +05:30
Ranveer Soni 9d83e09aa6 feat(qa): tighten RDNA2 planning filters, manifests and claim exclusion.
Add family/status filters, compact output, Codex manifests, path-only vs family claim scoping, and coverage reconcile without inflating counts.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:56:13 +05:30
Ranveer Soni 3bdc43d3ad Merge pull request #281 from Swastickc/task/66-movsx-movzx
loader: implement MOVZX and MOVSX in the interpreter (#66)
2026-11-24 17:47:21 +05:30
Ranveer Soni fa434d7174 Merge pull request #282 from Swastickc/task/279-native-app-gate5
app: persistent GPU resources, dynamic texture updates, and resource retirement (#279)
2026-11-24 17:46:43 +05:30
Ranveer Soni ed657ad802 Merge pull request #280 from Swastickc/task/72-segment-override
loader: add the FS and GS segment base to RIP-relative operands in the DBT (#72)
2026-11-24 17:46:25 +05:30
jelly013 5e7c21bc86 Merge upstream main (QA tooling) into CPU/runtime continuation
Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-24 13:13:17 +01:00
jelly013 4f4d977807 cpu: add exact SSE and SSE2 floating point
Add the scalar and packed binary32 and binary64 arithmetic, compares and
conversions, computed exactly and rounded once in software. Follow MXCSR
rounding, sticky flags, denormals-are-zero, flush-to-zero, tininess after
rounding and x86 NaN selection. Stop on unmasked exceptions without a
result. Host floating point is not used, and no form is lowered to NEON.

Verify 6,824 vectors computed with exact fractions by an independent Python
reference in both engines, and round-to-nearest results against the host.
List the behaviour that is implemented but left unasserted.

Refs #127, #128

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-24 13:11:07 +01:00
Swastick Chowdhury f6dfe58695 loader: implement MOVZX and MOVSX in the interpreter (#66)
The native DBT translator implements the four extension opcodes MOVZX r32/r64,
r/m8 (0F B6), MOVZX r32/r64, r/m16 (0F B7), MOVSX r32/r64, r/m8 (0F BE) and
MOVSX r32/r64, r/m16 (0F BF), with both register and memory source operands.
The interpreter implemented none of them: its 0x0F handler covered only SYSCALL
(0F 05) and BSWAP (0F C8..CF), so any of the four opcodes exited with
IllegalInstruction and the two execution paths accepted different instruction
sets for the same bytes.

Implement them in the interpreter:

- The source width follows the opcode, so 0F B6 and 0F BE read one byte and
  0F B7 and 0F BF read one word.
- The destination width follows REX.W. Without REX.W the destination is 32
  bits and its upper half is cleared; with REX.W it is 64 bits.
- MOVZX zero-extends, so both destination widths hold the same value.
- MOVSX sign-extends to the destination width, so a 32-bit destination keeps
  the sign in bits 31:0 with the upper half cleared, while a 64-bit
  destination keeps the sign extension across all 64 bits.

The effective-address computation shared by the memory forms of MOV,
MOVZX and MOVSX is extracted into an `effective_address` method so both
instruction families use one implementation. That is a pure refactor: the
address computation itself is unchanged.

Add six regression tests in crates/loader/tests/bootstrap.rs covering the
register and the memory source forms independently, both destination widths,
and the sign-extension boundary values. Every encoding was produced by LLVM
23.1.6 llvm-mc -show-encoding and the expected values follow the Intel SDM
rules for MOVZX and MOVSX.

All six tests fail against the unmodified interpreter and pass with this
change.

A related defect in the native DBT translator was found while writing these
tests: its MOVSX paths sign-extend to 64 bits unconditionally, so a 32-bit
destination keeps the sign extension in bits 63:32 instead of having them
cleared. That belongs to #65, which permits the translator files, and is
reported there rather than fixed here.

Closes #66

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 17:37:02 +05:30
Swastick Chowdhury 259b3054e1 app: persistent GPU resources, dynamic texture updates, and resource retirement (#279)
Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 17:34:01 +05:30
jelly013 dce37dab18 cpu: add SSE2 state, moves and packed integer forms
Add XMM0-XMM15 and MXCSR to the guest state and extend the registry with
mandatory prefixes, so the shared decoder covers the SSE and SSE2 moves and
packed integer operations. Reject opcodes where 0x66 could be both an
operand size and a mandatory prefix.

Translate operations with identical NEON lane semantics to ARM64; other
forms call the shared semantics and are counted. Raise a distinct
general-protection exit for misaligned 16-byte operands and reserved MXCSR
bits. Floating-point arithmetic is not implemented.

Verify 374 LLVM-assembled instructions against a byte-array reference that
reads only their assembly text, and mixed sequences between the engines.

Refs #124, #125, #126, #128

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-24 12:53:35 +01:00
jelly013 70f1793a4c Merge upstream main (#278 and QA tooling) into CPU/runtime continuation
Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-24 12:44:40 +01:00
jelly013 02f9ad9a34 cpu: share one generated decoder and store guest flags
Add a declarative x86-64 instruction registry with a validating generator,
and decode through its tables in the static probe, the interpreter and the
native DBT. Move integer semantics into shared reviewed primitives and
extend them to 8-, 16-, 32- and 64-bit register and memory operands.

Store all six arithmetic flags in the guest state so they survive helper
calls and block boundaries, and correct unsigned branch conditions. Lower
common forms to ARM64; other forms call the shared semantics and are
counted. Report probe support from the decoder that executes.

Verify 985 LLVM-assembled instructions against a bit-level reference that
reads only their assembly text, and random sequences between the engines.

Refs #64, #65, #66, #68, #70, #71, #73, #118, #119, #120, #121, #122,

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
#123, #194, #195, #196
2026-11-24 12:36:52 +01:00
jelly013 5ab561b0e8 cpu: correct the sign- and zero-extension family
Implement MOVZX, MOVSX (0F B6/B7/BE/BF) and MOVSXD (63) for register and
checked memory operands in the interpreter and the native DBT, and report
their exact lengths in the static probe. Cover 16-, 32- and 64-bit
destinations, legacy high-byte registers and RIP-relative operands.

Fix the DBT SXTW encoding, 32-bit accesses that touched eight bytes,
RIP-relative byte and extension operands, and LEA with a segment prefix.
Make the prefix-length regression independent of an untracked file and
correct the campaign ledger.

Refs #65, #66, #67, #68, #69, #117

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-24 12:20:01 +01:00
jelly013 56febbb655 Merge upstream main (#272, #273, #274) into CPU/runtime continuation
Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-24 12:17:05 +01:00
Ranveer Soni 0836936011 docs(cpu): add campaign progress ledger
Add docs/coordination/cpu-campaign-ledger.md tracking the Xenora native
CPU/runtime expansion campaign: starting commit, current commit, completed
batches, new forms and the remaining implementation plan.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 16:27:58 +05:30
Ranveer Soni bfd14e4c50 feat(dbt): implement native ARM64 MOVSXD register lowering
Add SXTW to the ARM64 assembler (encoding 0x93407D00 | Wn<<5 | Xd, verified
against llvm-mc 23.1.6) and a 0x63 arm to the DBT's compile_block that loads
the source word, emits SXTW into the destination register and stores it.
Sixth test executes the instruction through the native DBT.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 16:26:24 +05:30
Ranveer Soni 7e09c9ce63 feat(cpu): implement MOVSX/MOVSXD (0x63) semantics in the interpreter
Add the 0x63 arm to the software interpreter (issue #117): with REX.W it
sign-extends the 32-bit source into the destination (MOVSXD r64, r/m32);
without REX.W it writes the 32-bit destination register and zeroes the
upper half. REX.R and REX.B extend the destination and source registers.
Five interpreter known-answer tests cover negative and positive sign
extension, upper-half zeroing and register extension.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 16:19:38 +05:30
Ranveer Soni 9cd6f43a62 fix(cpu): bound interpreter segment prefix run by the architectural instruction length
Integrate the missing instruction-length correction into the upstream Prefixes
architecture (issue #69): the interpreter now tracks the instruction length in
execute_instruction and returns Err(IllegalInstruction) when the legacy
segment prefix run or the REX fetch would exceed the 15-byte architectural
limit, preserving the upstream Prefixes struct and interfaces. Regression
tests unchanged (x86_prefix_length.rs).

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 16:15:18 +05:30
Ranveer Soni 7a3b197215 Merge branch 'main' of https://github.com/ranveersoni98/Xenora 2026-11-24 16:12:51 +05:30
Ranveer Soni bc629f5321 Merge branch 'origin/main' — typed Prefixes struct in cpu.rs (completes #62)
Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 16:09:58 +05:30
Ranveer Soni a953ba9d37 fix(cpu): enforce bounded prefix and architectural instruction length in probe, interpreter and DBT
Add crates/loader/src/x86_decode.rs with the shared architectural limit
MAX_INSTRUCTION_LEN (15 bytes) and segment_prefix_len. Bounded the legacy
segment prefix runs in the static probe, the software interpreter and the
native DBT so overlong prefix runs decode as illegal instructions instead of
consuming past the architectural limit, and the probe now rejects any decoded
record longer than 15 bytes. Regression tests cover the overlong prefix run,
prefix-count lengths, the minimized fuzz-artifact input, and interpreter and
DBT rejections (issue #69).

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 16:09:41 +05:30
68 changed files with 29342 additions and 2520 deletions

No files matched your search

+26 -3
View File
@@ -9,17 +9,29 @@ exact revision and known limitations.
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
remains unsupported.
### 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.
@@ -84,12 +96,22 @@ 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).
@@ -174,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.
+155 -2
View File
@@ -69,12 +69,105 @@ struct GuestFrame {
}
}
/// 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
@@ -84,6 +177,22 @@ final class FrameModel: ObservableObject {
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).
@@ -359,8 +468,36 @@ struct ContentView: View {
Text("Run failed (status \(frame.status)). No frame is shown.")
.foregroundStyle(.red)
}
Button(running ? "Running…" : "Run trusted fixture") { model.run() }
.disabled(running || !probe.connected)
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 {
@@ -441,6 +578,22 @@ if let flag = CommandLine.arguments.firstIndex(of: "--inspect"), flag + 1 < Comm
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
+204
View File
@@ -146,6 +146,210 @@ xenora_status xenora_session_frame_loop_status(
/* 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.
+23 -4
View File
@@ -10,7 +10,7 @@
//! the guest leaves its loop and halts.
use std::cell::RefCell;
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, OnceLock};
use std::thread::JoinHandle;
use xenora_loader::startup::{StartupLayout, run_synthetic_startup};
@@ -171,8 +171,8 @@ impl FrameLoop {
include_bytes!("../../../fixtures/rdna2/x9-constant-ps.bin"),
)
.map_err(|e| format!("shader translation: {e}"))?;
let gpu = NativeCompute::new().map_err(|e| format!("Metal device: {e}"))?;
// The session's GPU resources live on the guest thread, where the import runs.
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);
@@ -268,7 +268,26 @@ impl FrameLoop {
}
thread_local! {
static GPU: RefCell<Option<(NativeCompute, String)>> = const { RefCell::new(None) };
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.
+1626 -1
View File
File diff suppressed because it is too large. Load diff
+374
View File
@@ -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);
}
+137
View File
@@ -257,3 +257,140 @@ fn repeated_sessions_do_not_grow_the_memory_footprint() {
"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);
}
+375
View File
@@ -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);
}
+37 -39
View File
@@ -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
}
}
}
+30 -32
View File
@@ -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
+1
View File
@@ -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};
+453
View File
@@ -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(&parameter.name) || !names.insert(&parameter.name) {
return fail(format!("invalid parameter name {:?}", parameter.name));
}
if reader(&parameter.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(&parameter.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");
}
}
+315
View File
@@ -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)
+181
View File
@@ -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
+181 -5
View File
@@ -183,6 +183,11 @@ impl Arm64Assembler {
self.emit(0x93401c00 | ((wn as u32 & 0x1f) << 5) | (xd as u32 & 0x1f));
}
/// SXTH (64-bit/sign-extended): SXTH Xd, Wn (SBFM Xd, Xn, #0, #15)
pub fn sxth_64(&mut self, xd: u8, wn: u8) {
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
@@ -191,11 +196,6 @@ impl Arm64Assembler {
self.emit(0x13001c00 | ((wn as u32 & 0x1f) << 5) | (wd as u32 & 0x1f));
}
/// SXTH (64-bit/sign-extended): SXTH Xd, Wn (SBFM Xd, Xn, #0, #15)
pub fn sxth_64(&mut self, xd: u8, wn: u8) {
self.emit(0x93403c00 | ((wn as u32 & 0x1f) << 5) | (xd 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
@@ -204,6 +204,182 @@ impl Arm64Assembler {
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(
+66 -534
View File
@@ -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.
@@ -53,34 +55,34 @@ impl Register {
}
}
/// Instruction prefixes decoded ahead of an opcode.
///
/// The interpreter decodes these once per instruction and passes them to the
/// helpers that need them, so prefix state travels as one typed value instead
/// of a list of independent booleans.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct Prefixes {
/// REX.W: 64-bit operand size.
rex_w: bool,
/// REX.R: extends the ModRM `reg` field to R8-R15.
rex_r: bool,
/// REX.X: extends the SIB `index` field to R8-R15.
rex_x: bool,
/// REX.B: extends the ModRM `rm` field to R8-R15.
rex_b: bool,
/// The GS segment override prefix (0x65) is present.
seg_gs: bool,
/// The FS segment override prefix (0x64) is present.
seg_fs: bool,
}
/// 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.
@@ -92,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 {
@@ -104,6 +109,8 @@ impl CpuState {
flags: RFlags::default(),
gs_base: 0,
fs_base: 0,
xmm: [0; 16],
mxcsr: Mxcsr::default(),
}
}
@@ -126,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 {
@@ -138,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")
}
}
}
}
@@ -158,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;
@@ -393,519 +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 prefixes = Prefixes::default();
let mut byte = self.fetch_u8()?;
// Handle legacy segment prefixes: 0x65 (GS), 0x64 (FS)
while byte == 0x65 || byte == 0x64 {
if byte == 0x65 {
prefixes.seg_gs = true;
} else {
prefixes.seg_fs = true;
}
byte = self.fetch_u8()?;
}
// Handle REX prefix (0x40 - 0x4F)
if (byte & 0xF0) == 0x40 {
prefixes.rex_w = (byte & 0x08) != 0;
prefixes.rex_r = (byte & 0x04) != 0;
prefixes.rex_x = (byte & 0x02) != 0;
prefixes.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(prefixes.rex_b) << 3));
let value = self.cpu.get(reg);
let reversed = if prefixes.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 prefixes.rex_b { 8 } else { 0 };
let reg = Register::from_index(reg_idx);
if prefixes.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, &prefixes)?;
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 prefixes.rex_w {
val1 ^ val2
} else {
(val1 as u32 ^ val2 as u32) as u64
};
self.cpu.set(dst, res);
self.update_flags_logic(res, prefixes.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, &prefixes)?;
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 prefixes.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, &prefixes)?;
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 prefixes.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, &prefixes)?;
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 prefixes.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, &prefixes)?;
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 prefixes.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 prefixes.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 prefixes.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, &prefixes, byte == 0x8B)
}
// 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 prefixes.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 prefixes.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,
prefixes: &Prefixes,
) -> Result<(Register, Register), ExitReason> {
let mode = (modrm >> 6) & 3;
if mode != 3 {
return Err(ExitReason::IllegalInstruction(modrm));
}
let reg_idx = ((modrm >> 3) & 7) + if prefixes.rex_r { 8 } else { 0 };
let rm_idx = (modrm & 7) + if prefixes.rex_b { 8 } else { 0 };
Ok((Register::from_index(reg_idx), Register::from_index(rm_idx)))
}
fn execute_mov_rm(
&mut self,
modrm: u8,
prefixes: &Prefixes,
is_load: bool,
) -> Result<Option<ExitReason>, ExitReason> {
let mode = (modrm >> 6) & 3;
let reg_idx = ((modrm >> 3) & 7) + if prefixes.rex_r { 8 } else { 0 };
let rm_idx = (modrm & 7) + if prefixes.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 prefixes.rex_w {
val
} else {
val as u32 as u64
},
);
} else {
let val = self.cpu.get(reg);
self.cpu.set(
rm,
if prefixes.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;
// REX.X extends the SIB index field; REX.R extends the ModRM reg
// field and must not affect the index. An index field of 100b
// selects r12 when REX.X is set, and means "no index" otherwise.
let index_field = (sib >> 3) & 7;
let index_raw = index_field + if prefixes.rex_x { 8 } else { 0 };
let base_raw = (sib & 7) + if prefixes.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 index_field == 4 && !prefixes.rex_x {
// 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 prefixes.seg_gs {
effective_addr = effective_addr.wrapping_add(self.cpu.gs_base);
} else if prefixes.seg_fs {
effective_addr = effective_addr.wrapping_add(self.cpu.fs_base);
}
if is_load {
// Load from memory to reg
if prefixes.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 prefixes.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),
}
}
}
+1373 -1252
View File
File diff suppressed because it is too large. Load diff
+218
View File
@@ -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
View File
@@ -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)
}
+11
View File
@@ -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};
+182 -141
View File
@@ -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 &sections {
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,
+155
View File
@@ -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],
}
+408
View File
@@ -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
View File
@@ -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)))
}
}
+641
View File
@@ -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 },
}
}
+468
View File
@@ -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);
}
}
+621
View File
@@ -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(())
}
+247
View File
@@ -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)
}
+395
View File
@@ -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
+166
View File
@@ -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}");
}
}
+247
View File
@@ -462,3 +462,250 @@ fn test_sib_index_field_100b_without_rex_x_means_no_index() {
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);
}
+1
View File
@@ -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]
+539
View File
@@ -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
}
+10 -10
View File
@@ -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);
}
+18
View File
@@ -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());
}
}
+981
View File
@@ -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");
}
+186
View File
@@ -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)
+172
View File
@@ -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]
+441
View File
@@ -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
+985
View File
@@ -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
+374
View File
@@ -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]
+611
View File
@@ -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
+203
View File
@@ -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
);
}
+799
View File
@@ -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
+3
View File
@@ -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,6 +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.
+128
View File
@@ -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.
+50
View File
@@ -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.
+29
View File
@@ -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.
+40
View File
@@ -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 |
+9 -4
View File
@@ -29,10 +29,13 @@ PYTHONPATH=scripts python3 -m unittest discover -s tests/release
## Phase II CLIs
```sh
PYTHONPATH=scripts python3 -m qa rdna2 inventory
PYTHONPATH=scripts python3 -m qa rdna2 candidates --limit 50
PYTHONPATH=scripts python3 -m qa rdna2 plan
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
@@ -40,4 +43,6 @@ PYTHONPATH=scripts python3 -m release readiness --revision HEAD --live --binary
```
RDNA2 planning is read-only over the AMD snapshot, semantic registry, decoder tables and
`docs/status.toml`. Candidates are never counted as implemented forms.
`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.
+49
View File
@@ -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)
Binary file not shown.
+124
View File
@@ -0,0 +1,124 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Generate the clean-room PE32+ audio and virtual filesystem fixture without an x86 toolchain.
The guest demonstrates virtual asset loading and PCM audio streaming through runtime services:
1. Calls xenora.dll!vfs_open_asset() to open the authorized asset 'asset.bin'.
2. Calls xenora.dll!vfs_read_asset(handle, 548) to load asset header, texture, and PCM audio.
3. Calls xenora.dll!vfs_close_asset(handle) to close the asset file.
4. Calls xenora.dll!audio_init(48000, 1, 1) to initialize audio (48kHz, mono, S16LE).
5. Calls xenora.dll!audio_submit_pcm(512) to submit the 256 PCM audio samples.
6. Calls xenora.dll!frame_submit_textured(0) to render the 2x2 loaded texture on Metal.
7. Halts cleanly.
"""
import argparse
from pathlib import Path
from struct import pack, pack_into
def fixture():
base = 0x140000000
entry, imports = 0x1000, 0x2000
lookup = imports + 0x30
iat = imports + 0x70
module = imports + 0xB0
sym_vfs_open = imports + 0xC0
sym_vfs_read = imports + 0xE0
sym_vfs_close = imports + 0x100
sym_audio_init = imports + 0x120
sym_audio_submit = imports + 0x140
sym_frame_submit = imports + 0x160
data = bytearray(0x800)
data[:2] = b"MZ"
pack_into("<I", data, 0x3C, 0x80)
data[0x80:0x84] = b"PE\0\0"
pack_into("<HHIIIHH", data, 0x84, 0x8664, 2, 0, 0, 0, 240, 0x22)
opt = 0x98
pack_into("<H", data, opt, 0x20B)
pack_into("<III", data, opt + 4, 0x200, 0x200, 0)
pack_into("<IIQII", data, opt + 16, entry, entry, base, 0x1000, 0x200)
pack_into("<II", data, opt + 56, 0x3000, 0x400)
pack_into("<HH", data, opt + 68, 3, 0x160)
pack_into("<QQQQII", data, opt + 72, 0x10000, 0x1000, 0x10000, 0x1000, 0, 16)
for index, rva, size in ((1, imports, 40), (12, iat, 56)):
pack_into("<II", data, opt + 112 + index * 8, rva, size)
for index, (name, rva, permissions) in enumerate(
((b".text", entry, 0x60000020), (b".rdata", imports, 0x40000040))
):
pack_into(
"<8sIIIIIIHHI", data, opt + 240 + 40 * index, name, 0x200, rva,
0x200, 0x400 + 0x200 * index, 0, 0, 0, 0, permissions,
)
code = bytearray()
code += b"\x48\x83\xec\x28" # sub rsp, 0x28 (Win64 home area)
# 1. vfs_open_asset() -> rax = file handle
# call [rip -> iat[0]: vfs_open_asset]
code += b"\xff\x15" + pack("<i", iat - (entry + len(code) + 6))
code += b"\x48\x89\xc3" # mov rbx, rax (save file handle)
# 2. vfs_read_asset(handle, 548) -> rax = bytes read
code += b"\x48\x89\xd9" # mov rcx, rbx (handle)
code += b"\xba\x24\x02\x00\x00" # mov edx, 548 (header 20B + tex 16B + audio 512B)
# call [rip -> iat[1]: vfs_read_asset]
code += b"\xff\x15" + pack("<i", (iat + 8) - (entry + len(code) + 6))
# 3. vfs_close_asset(handle)
code += b"\x48\x89\xd9" # mov rcx, rbx (handle)
# call [rip -> iat[2]: vfs_close_asset]
code += b"\xff\x15" + pack("<i", (iat + 16) - (entry + len(code) + 6))
# 4. audio_init(48000, 1, 1)
code += b"\xb9\x80\xbb\x00\x00" # mov ecx, 48000 (sample rate)
code += b"\xba\x01\x00\x00\x00" # mov edx, 1 (mono)
code += b"\x41\xb8\x01\x00\x00\x00" # mov r8d, 1 (S16LE)
# call [rip -> iat[3]: audio_init]
code += b"\xff\x15" + pack("<i", (iat + 24) - (entry + len(code) + 6))
# 5. audio_submit_pcm(512)
code += b"\xb9\x00\x02\x00\x00" # mov ecx, 512 (bytes)
# call [rip -> iat[4]: audio_submit_pcm]
code += b"\xff\x15" + pack("<i", (iat + 32) - (entry + len(code) + 6))
# 6. frame_submit_textured(0)
code += b"\x31\xc9" # xor ecx, ecx
# call [rip -> iat[5]: frame_submit_textured]
code += b"\xff\x15" + pack("<i", (iat + 40) - (entry + len(code) + 6))
code += b"\x48\x83\xc4\x28" # add rsp, 0x28
code += b"\xf4" # hlt
data[0x400:0x400 + len(code)] = code
# Import directory table
pack_into("<IIIII", data, 0x600, lookup, 0, 0, module, iat)
# Lookups & IAT (6 imports)
for off in (lookup - imports, iat - imports):
pack_into("<QQQQQQ", data, 0x600 + off,
sym_vfs_open, sym_vfs_read, sym_vfs_close,
sym_audio_init, sym_audio_submit, sym_frame_submit)
data[0x600 + (module - imports):0x600 + (module - imports) + 11] = b"xenora.dll\0"
data[0x600 + (sym_vfs_open - imports) + 2:0x600 + (sym_vfs_open - imports) + 2 + 14] = b"vfs_open_asset"
data[0x600 + (sym_vfs_read - imports) + 2:0x600 + (sym_vfs_read - imports) + 2 + 14] = b"vfs_read_asset"
data[0x600 + (sym_vfs_close - imports) + 2:0x600 + (sym_vfs_close - imports) + 2 + 15] = b"vfs_close_asset"
data[0x600 + (sym_audio_init - imports) + 2:0x600 + (sym_audio_init - imports) + 2 + 10] = b"audio_init"
data[0x600 + (sym_audio_submit - imports) + 2:0x600 + (sym_audio_submit - imports) + 2 + 16] = b"audio_submit_pcm"
data[0x600 + (sym_frame_submit - imports) + 2:0x600 + (sym_frame_submit - imports) + 2 + 21] = b"frame_submit_textured"
return data
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true")
args = parser.parse_args()
path = Path(__file__).with_suffix(".exe")
expected = fixture()
if args.check:
if not path.exists() or path.read_bytes() != expected:
parser.exit(1, f"fixture bytes differ from generator: {path}\n")
else:
path.write_bytes(expected)
Binary file not shown.
+114
View File
@@ -0,0 +1,114 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Generate the original PE32+ persistent texture fixture without an x86 toolchain.
The guest demonstrates persistent GPU resource ownership, dynamic texture updates,
and completion-aware resource retirement through runtime services:
1. Calls xenora.dll!texture_create(2, 2) to allocate a persistent 2x2 texture.
2. Calls xenora.dll!frame_submit_textured(handle) to render frame 0 with initial contents.
3. Calls xenora.dll!texture_update(handle, 0, 0, 2, 2) to dynamically update texture pixels.
4. Calls xenora.dll!frame_submit_textured(handle) to render frame 1 with updated contents.
5. Calls xenora.dll!texture_destroy(handle) to retire the resource.
6. Halts cleanly.
"""
import argparse
from pathlib import Path
from struct import pack, pack_into
def fixture():
base = 0x140000000
entry, imports = 0x1000, 0x2000
lookup = imports + 0x30
iat = imports + 0x60
module = imports + 0x90
sym_create = imports + 0xA0
sym_update = imports + 0xC0
sym_submit = imports + 0xE0
sym_destroy = imports + 0x100
data = bytearray(0x800)
data[:2] = b"MZ"
pack_into("<I", data, 0x3C, 0x80)
data[0x80:0x84] = b"PE\0\0"
pack_into("<HHIIIHH", data, 0x84, 0x8664, 2, 0, 0, 0, 240, 0x22)
opt = 0x98
pack_into("<H", data, opt, 0x20B)
pack_into("<III", data, opt + 4, 0x200, 0x200, 0)
pack_into("<IIQII", data, opt + 16, entry, entry, base, 0x1000, 0x200)
pack_into("<II", data, opt + 56, 0x3000, 0x400)
pack_into("<HH", data, opt + 68, 3, 0x160)
pack_into("<QQQQII", data, opt + 72, 0x10000, 0x1000, 0x10000, 0x1000, 0, 16)
for index, rva, size in ((1, imports, 40), (12, iat, 40)):
pack_into("<II", data, opt + 112 + index * 8, rva, size)
for index, (name, rva, permissions) in enumerate(
((b".text", entry, 0x60000020), (b".rdata", imports, 0x40000040))
):
pack_into(
"<8sIIIIIIHHI", data, opt + 240 + 40 * index, name, 0x200, rva,
0x200, 0x400 + 0x200 * index, 0, 0, 0, 0, permissions,
)
code = bytearray()
code += b"\x48\x83\xec\x28" # sub rsp, 0x28 (Win64 home area)
# 1. texture_create(2, 2)
code += b"\x48\xc7\xc1\x02\x00\x00\x00" # mov rcx, 2
code += b"\x48\xc7\xc2\x02\x00\x00\x00" # mov rdx, 2
# call [rip -> iat[0]: texture_create]
code += b"\xff\x15" + pack("<i", iat - (entry + len(code) + 6))
code += b"\x48\x89\xc3" # mov rbx, rax (save handle)
# 2. frame_submit_textured(handle)
code += b"\x48\x89\xd9" # mov rcx, rbx
# call [rip -> iat[2]: frame_submit_textured]
code += b"\xff\x15" + pack("<i", (iat + 16) - (entry + len(code) + 6))
# 3. texture_update(handle, 0, 0, 2, 2)
code += b"\x48\x89\xd9" # mov rcx, rbx
code += b"\x48\x31\xd2" # xor rdx, rdx (x=0)
code += b"\x49\xc7\xc0\x00\x00\x00\x00" # mov r8, 0 (y=0)
code += b"\x49\xc7\xc1\x02\x00\x00\x00" # mov r9, 2 (w=2)
# call [rip -> iat[1]: texture_update]
code += b"\xff\x15" + pack("<i", (iat + 8) - (entry + len(code) + 6))
# 4. frame_submit_textured(handle)
code += b"\x48\x89\xd9" # mov rcx, rbx
# call [rip -> iat[2]: frame_submit_textured]
code += b"\xff\x15" + pack("<i", (iat + 16) - (entry + len(code) + 6))
# 5. texture_destroy(handle)
code += b"\x48\x89\xd9" # mov rcx, rbx
# call [rip -> iat[3]: texture_destroy]
code += b"\xff\x15" + pack("<i", (iat + 24) - (entry + len(code) + 6))
code += b"\x48\x83\xc4\x28" # add rsp, 0x28
code += b"\xf4" # hlt
data[0x400:0x400 + len(code)] = code
# Import directory table
pack_into("<IIIII", data, 0x600, lookup, 0, 0, module, iat)
# Lookups & IAT
for off in (lookup - imports, iat - imports):
pack_into("<QQQQ", data, 0x600 + off, sym_create, sym_update, sym_submit, sym_destroy)
data[0x600 + (module - imports):0x600 + (module - imports) + 11] = b"xenora.dll\0"
data[0x600 + (sym_create - imports) + 2:0x600 + (sym_create - imports) + 2 + 14] = b"texture_create"
data[0x600 + (sym_update - imports) + 2:0x600 + (sym_update - imports) + 2 + 14] = b"texture_update"
data[0x600 + (sym_submit - imports) + 2:0x600 + (sym_submit - imports) + 2 + 21] = b"frame_submit_textured"
data[0x600 + (sym_destroy - imports) + 2:0x600 + (sym_destroy - imports) + 2 + 15] = b"texture_destroy"
return data
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true")
args = parser.parse_args()
path = Path(__file__).with_suffix(".exe")
if args.check:
if path.read_bytes() != fixture():
parser.exit(1, f"fixture bytes differ from generator: {path}\n")
else:
path.write_bytes(fixture())
+101 -11
View File
@@ -8,6 +8,7 @@ import shlex
import subprocess
import sys
from pathlib import Path
from typing import Any
from .bench_regress import IncompatibleComparison, compare_records, dumps_comparison, load_record
from .bench_stats import export_json, human_report, summarize
@@ -35,14 +36,21 @@ from .pr_validate import (
merge_reports,
)
from .rdna2_plan import (
build_manifests,
classify_unsupported,
compact_candidates,
compact_inventory,
compact_manifests,
coverage_diff,
discrepancies,
dumps_candidates,
dumps_inventory,
load_inventories,
parse_claims_file,
plan_batches,
reconcile_with_coverage_report,
summarize_inventory,
write_json,
)
from .coverage_history import historical_report, snapshot_inventory, write_snapshot
from .stale_branch import classify_sync, format_sync_reports
@@ -91,8 +99,21 @@ def main(argv: list[str] | None = None) -> int:
v.add_argument("--allowed", action="append", default=[])
r = sub.add_parser("rdna2", help="read-only RDNA2 expansion planning")
r.add_argument("action", choices=("inventory", "candidates", "plan", "discrepancies", "diff"))
r.add_argument(
"action",
choices=("inventory", "candidates", "plan", "discrepancies", "diff", "manifests", "reconcile"),
)
r.add_argument("--limit", type=int, default=0)
r.add_argument("--family", action="append", default=[], help="filter by encoding family")
r.add_argument(
"--status",
action="append",
default=[],
help="filter: reuse-primitives|needs-primitives|needs-operand-rules",
)
r.add_argument("--claims", default="", help="JSON claims file to exclude overlapping work")
r.add_argument("--compact", action="store_true", help="print compact summary to stdout")
r.add_argument("--out", default="", help="write full JSON under this path (prefer artifacts/)")
r.add_argument("--before", default="", help="JSON inventory for diff")
r.add_argument("--after", default="", help="JSON inventory for diff")
@@ -199,24 +220,93 @@ def main(argv: list[str] | None = None) -> int:
return Inventory(**{k: d[k] for k in (
"identified", "declared", "decoder_supported", "reference_verified",
"metal_verified", "unsupported", "by_family")})
print(json.dumps(coverage_diff(inv(before), inv(after)), indent=2, sort_keys=True))
payload = coverage_diff(inv(before), inv(after))
if args.out:
write_json(Path(args.out), payload)
if args.compact or args.out:
print(
f"declared_delta={payload['declared_delta']} "
f"unsupported_delta={payload['unsupported_delta']}"
)
else:
print(json.dumps(payload, indent=2, sort_keys=True))
return 0
data = load_inventories(root)
inv = summarize_inventory(data)
exclude_families: list[str] = []
claimed_paths: list[str] = []
if args.claims:
fams, paths = parse_claims_file(Path(args.claims))
exclude_families = sorted(fams)
claimed_paths = sorted(paths)
limit = args.limit or None
def emit(payload: Any, compact_text: str, full_text: str | None = None) -> int:
if args.out:
write_json(Path(args.out), payload)
if args.compact or args.out:
print(compact_text, end="")
elif full_text is not None:
print(full_text, end="")
else:
print(json.dumps(payload, indent=2, sort_keys=True) + "\n", end="")
return 0
if args.action == "inventory":
print(dumps_inventory(inv), end="")
return 0
return emit(json.loads(dumps_inventory(inv)), compact_inventory(inv), dumps_inventory(inv))
if args.action == "candidates":
limit = args.limit or None
print(dumps_candidates(classify_unsupported(data, limit=limit)), end="")
return 0
cands = classify_unsupported(
data,
limit=limit,
families=args.family or None,
statuses=args.status or None,
exclude_families=exclude_families,
)
payload = json.loads(dumps_candidates(cands))
return emit(payload, compact_candidates(cands), dumps_candidates(cands))
if args.action == "plan":
cands = classify_unsupported(data, limit=(args.limit or None))
print(json.dumps(plan_batches(cands), indent=2, sort_keys=True))
cands = classify_unsupported(
data,
limit=limit,
families=args.family or None,
statuses=args.status or None,
exclude_families=exclude_families,
)
payload = plan_batches(cands)
return emit(payload, compact_candidates(cands))
if args.action == "manifests":
cands = classify_unsupported(
data,
limit=None,
families=args.family or None,
statuses=args.status or ["reuse-primitives"],
exclude_families=exclude_families,
)
manifests = build_manifests(
cands,
exclude_families=exclude_families,
claimed_paths=claimed_paths,
limit=limit,
)
payload = {
"note": "Codex-ready planning manifests only; forms are not implemented.",
"count": len(manifests),
"manifests": manifests,
}
out = args.out or "artifacts/rdna2-manifests.json"
write_json(Path(out), payload)
print(compact_manifests(manifests), end="")
print(f"wrote {out}")
return 0
if args.action == "discrepancies":
print(json.dumps(discrepancies(data), indent=2, sort_keys=True))
return 0
payload = discrepancies(data)
return emit(payload, f"discrepancies={len(payload)}\n")
if args.action == "reconcile":
payload = reconcile_with_coverage_report(root, data)
return emit(
payload,
f"reconcile_ok={payload['ok']} mismatches={len(payload['mismatches'])}\n",
)
if args.command == "cpu-coverage":
report = build_cpu_report(root)
+278 -28
View File
@@ -9,12 +9,13 @@ implemented forms.
from __future__ import annotations
import json
import re
import runpy
import tomllib
from collections import defaultdict
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any
from typing import Any, Iterable, Sequence
def _load_coverage_module(root: Path):
@@ -46,6 +47,8 @@ class Candidate:
missing_effects: list[str] = field(default_factory=list)
spec_refs: list[dict[str, Any]] = field(default_factory=list)
priority_batch: str = "unclassified"
priority_rank: int = 99
status: str = "unsupported"
notes: list[str] = field(default_factory=list)
@@ -60,6 +63,27 @@ class Inventory:
by_family: dict[str, dict[str, int]]
# Conventional GPU semantic-expansion file set for Codex manifests only.
# Planning does not claim or edit these paths.
DEFAULT_PERMITTED_FILES = (
"crates/isa/semantics/rdna2.toml",
"crates/isa/src/semantics_gen.rs",
"crates/decoder/src/lib.rs",
"crates/shader/",
"crates/ref/",
"tests/validation/",
"docs/status.toml",
"CHANGELOG.md",
)
DEFAULT_ACCEPTANCE = (
"cargo test --locked -p xenora-ref",
"cargo test --locked -p xenora-semantic-review",
"scripts/test-gpu.sh",
"python3 scripts/audit/semantic_coverage.py --check",
)
def load_inventories(root: Path) -> dict[str, Any]:
sc = _load_coverage_module(root)
identified = sc["load_snapshot"](root)
@@ -146,52 +170,65 @@ def _declared_ops(registry: dict[str, Any]) -> set[str]:
return {form.get("operation") for form in registry.get("form", []) if form.get("operation")}
def _declared_rules(registry: dict[str, Any]) -> set[str]:
return set(registry.get("operand_rules", {}))
def _batch_for(family: str, family_rule_names: list[str], ops: set[str]) -> tuple[str, int, str]:
"""Return (batch_id, priority_rank, status). Lower rank is higher priority."""
if family_rule_names and ops:
return f"batch-{family.lower()}-reuse-primitives", 0, "reuse-primitives"
if family_rule_names:
return f"batch-{family.lower()}-needs-primitives", 1, "needs-primitives"
return f"batch-{family.lower()}-needs-operand-rules", 2, "needs-operand-rules"
def classify_unsupported(data: dict[str, Any], *, limit: int | None = None) -> list[Candidate]:
def classify_unsupported(
data: dict[str, Any],
*,
limit: int | None = None,
families: Sequence[str] | None = None,
statuses: Sequence[str] | None = None,
exclude_families: Sequence[str] | None = None,
) -> list[Candidate]:
"""Build candidates for identified forms that are not registry-declared.
Does not infer behaviour from the mnemonic. Width/type/layout are filled
only when already present on related declared forms in the same family, or
left null.
left null. Results are sorted by priority_rank then family/name.
"""
identified = data["identified"]
declared = data["declared"]
registry = data["registry"]
rules = data["rules"]
ops = _declared_ops(registry)
rule_names = _declared_rules(registry)
family_rules = defaultdict(list)
family_widths = defaultdict(set)
family_types = defaultdict(set)
family_widths: dict[str, set[int]] = defaultdict(set)
family_types: dict[str, set[str]] = defaultdict(set)
for form in registry.get("form", []):
family_rules[form["family"]].append(form.get("operands"))
if "width" in form:
family_widths[form["family"]].add(form["width"])
if "signedness" in form:
family_types[form["family"]].add(form["signedness"])
family_filter = {f.upper() for f in families} if families else None
status_filter = {s for s in statuses} if statuses else None
excluded = {f.upper() for f in (exclude_families or ())}
candidates: list[Candidate] = []
unsupported = sorted(set(identified) - set(declared))
if limit is not None:
unsupported = unsupported[:limit]
for family, name in unsupported:
if family_filter is not None and family.upper() not in family_filter:
continue
if family.upper() in excluded:
continue
opcode = identified[(family, name)]
reusable = sorted(op for op in ops if op) # available primitives, not guessed mapping
missing_rules = []
# If the family has no operand rule yet, record that gap.
reusable = sorted(op for op in ops if op)
family_rule_names = [n for n, (fam, _) in rules.items() if fam == family]
missing_rules = []
if not family_rule_names:
missing_rules.append(f"no operand_rules for family {family}")
missing_effects = []
# Architectural effects are unknown until specified; flag absence.
missing_effects.append("scc/vcc/exec effects unspecified until registry declaration")
widths = sorted(family_widths.get(family, []))
types = sorted(family_types.get(family, []))
layout = family_rule_names[0] if len(family_rule_names) == 1 else None
batch = _batch_for(family, family_rule_names, ops)
batch, rank, status = _batch_for(family, family_rule_names, ops)
if status_filter is not None and status not in status_filter:
continue
candidates.append(Candidate(
family=family,
name=name,
@@ -201,25 +238,22 @@ def classify_unsupported(data: dict[str, Any], *, limit: int | None = None) -> l
operand_layout=layout,
reusable_primitives=reusable[:20],
missing_operand_rules=missing_rules,
missing_effects=missing_effects,
missing_effects=["scc/vcc/exec effects unspecified until registry declaration"],
spec_refs=[{"document": "xml", "note": "identity from pinned AMD snapshot only"}],
priority_batch=batch,
priority_rank=rank,
status=status,
notes=[
"behaviour must come from the public AMD guide, never the mnemonic",
"candidate is not implemented",
],
))
candidates.sort(key=lambda c: (c.priority_rank, c.family, c.name, c.opcode))
if limit is not None:
candidates = candidates[:limit]
return candidates
def _batch_for(family: str, family_rule_names: list[str], ops: set[str]) -> str:
if family_rule_names and ops:
return f"batch-{family.lower()}-reuse-primitives"
if family_rule_names:
return f"batch-{family.lower()}-needs-primitives"
return f"batch-{family.lower()}-needs-operand-rules"
def plan_batches(candidates: list[Candidate]) -> dict[str, list[dict[str, Any]]]:
batches: dict[str, list[dict[str, Any]]] = defaultdict(list)
for cand in candidates:
@@ -227,6 +261,7 @@ def plan_batches(candidates: list[Candidate]) -> dict[str, list[dict[str, Any]]]
"family": cand.family,
"name": cand.name,
"opcode": cand.opcode,
"status": cand.status,
"missing_operand_rules": cand.missing_operand_rules,
"reusable_primitives": cand.reusable_primitives[:5],
})
@@ -275,6 +310,179 @@ def discrepancies(data: dict[str, Any]) -> list[dict[str, str]]:
return issues
def reconcile_with_coverage_report(root: Path, data: dict[str, Any]) -> dict[str, Any]:
"""Compare planner inventory to canonical semantic_coverage collect_coverage.
Does not inflate planner counts. Reports per-family deltas only.
"""
sc = data["sc"]
identified = data["identified"]
registry = data["registry"]
decoder = data["decoder"]
status = data["status"]
counts, _rules = sc["collect_coverage"](identified, registry, decoder, status)
# collect_coverage tuple per family:
# Identified, Encoding-validated, Declared, Decoder-supported, IR, MSL,
# Reference-verified, Metal-verified, Unsupported operand variants
inv = summarize_inventory(data)
mismatches: list[dict[str, Any]] = []
for family, values in sorted(counts.items()):
canon_identified, _enc, canon_declared, canon_decoder, _ir, _msl, canon_ref, canon_metal, _u = values
bucket = inv.by_family.get(family, {})
pairs = (
("identified", canon_identified, bucket.get("identified", 0)),
("declared", canon_declared, bucket.get("declared", 0)),
("decoder", canon_decoder, bucket.get("decoder", 0)),
("reference", canon_ref, bucket.get("reference", 0)),
("metal", canon_metal, bucket.get("metal", 0)),
)
for field_name, canon, plan in pairs:
if canon != plan:
mismatches.append({
"family": family,
"field": field_name,
"canonical": canon,
"planner": plan,
"delta": plan - canon,
})
return {
"ok": not mismatches,
"canonical_totals": {
"identified": sum(v[0] for v in counts.values()),
"declared": sum(v[2] for v in counts.values()),
"decoder_supported": sum(v[3] for v in counts.values()),
"reference_verified": sum(v[6] for v in counts.values()),
"metal_verified": sum(v[7] for v in counts.values()),
},
"planner_totals": {
"identified": inv.identified,
"declared": inv.declared,
"decoder_supported": inv.decoder_supported,
"reference_verified": inv.reference_verified,
"metal_verified": inv.metal_verified,
},
"mismatches": mismatches,
"note": "Planner counts are not adjusted to match; mismatches must be investigated.",
}
@dataclass(frozen=True)
class ClaimScope:
"""One active claim. Families exclude those families; path-only claims
block candidates whose default permitted files overlap the claimed paths.
A claim that lists both families and paths excludes only the families —
the paths document the claim and do not blanket-block other families.
"""
families: frozenset[str] = frozenset()
paths: frozenset[str] = frozenset()
def parse_claims_file(path: Path) -> tuple[set[str], set[str]]:
"""Load excluded families and path-only claim prefixes.
Expected shape: {"claims":[{"families":["VOP2"], "paths":["crates/isa/**"]}, ...]}
or a bare list of such objects.
Returns (exclude_families, path_only_claimed_paths). Path prefixes from
claims that also name families are ignored for blocking so a SOP2+isa
claim does not suppress every other family's manifests.
"""
scopes = load_claim_scopes(path)
families: set[str] = set()
path_only: set[str] = set()
for scope in scopes:
families.update(scope.families)
if scope.families:
continue
path_only.update(scope.paths)
return families, path_only
def load_claim_scopes(path: Path) -> list[ClaimScope]:
raw = json.loads(path.read_text(encoding="utf-8"))
items = raw["claims"] if isinstance(raw, dict) and "claims" in raw else raw
if not isinstance(items, list):
raise ValueError("claims file must be a list or {\"claims\": [...]}")
scopes: list[ClaimScope] = []
for item in items:
fams = frozenset(str(f).upper() for f in (item.get("families") or []))
paths = frozenset(str(p) for p in (item.get("paths") or []))
if not fams and not paths:
continue
scopes.append(ClaimScope(families=fams, paths=paths))
return scopes
def claims_block_candidate(cand: Candidate, claimed_paths: set[str]) -> bool:
"""True if a path-only claim overlaps the default GPU expansion files."""
if not claimed_paths:
return False
for permitted in DEFAULT_PERMITTED_FILES:
for claimed in claimed_paths:
if _path_overlap(permitted, claimed):
return True
return False
def _path_overlap(a: str, b: str) -> bool:
a = a.rstrip("/")
b = b.rstrip("/")
if a.endswith("/**"):
a = a[:-3].rstrip("/")
if b.endswith("/**"):
b = b[:-3].rstrip("/")
return a == b or a.startswith(b + "/") or b.startswith(a + "/")
def build_manifests(
candidates: list[Candidate],
*,
exclude_families: Sequence[str] | None = None,
claimed_paths: Sequence[str] | None = None,
limit: int | None = None,
) -> list[dict[str, Any]]:
"""Deterministic Codex-ready implementation manifests.
Prioritises reuse-primitives, then needs-primitives, then needs-operand-rules.
Excludes active claim families and path-only claims. Does not invent semantics.
"""
excluded = {f.upper() for f in (exclude_families or ())}
claimed = set(claimed_paths or ())
manifests: list[dict[str, Any]] = []
for cand in candidates:
if cand.family.upper() in excluded:
continue
if claims_block_candidate(cand, claimed):
continue
deps: list[str] = []
if cand.status == "needs-operand-rules":
deps.append(f"define operand_rules for family {cand.family}")
if cand.status == "needs-primitives":
deps.append("add registry operation primitive before declaring this form")
if cand.status == "reuse-primitives":
deps.append("reuse existing registry primitives/operand rules; declare form from AMD guide")
deps.append("do not infer behaviour from the mnemonic")
manifest = {
"id": f"{cand.family}:{cand.name}",
"instruction": {
"family": cand.family,
"name": cand.name,
"opcode": cand.opcode,
},
"priority_rank": cand.priority_rank,
"status": cand.status,
"dependencies": deps,
"specification_references": cand.spec_refs,
"permitted_files": list(DEFAULT_PERMITTED_FILES),
"acceptance_tests": list(DEFAULT_ACCEPTANCE),
"notes": list(cand.notes),
}
manifests.append(manifest)
if limit is not None and len(manifests) >= limit:
break
return manifests
def coverage_diff(before: Inventory, after: Inventory) -> dict[str, Any]:
return {
"identified_delta": after.identified - before.identified,
@@ -299,3 +507,45 @@ def dumps_candidates(candidates: list[Candidate]) -> str:
def dumps_inventory(inv: Inventory) -> str:
return json.dumps(asdict(inv), indent=2, sort_keys=True) + "\n"
def compact_inventory(inv: Inventory) -> str:
lines = [
f"identified={inv.identified} declared={inv.declared} "
f"decoder={inv.decoder_supported} unsupported={inv.unsupported} "
f"ref={inv.reference_verified} metal={inv.metal_verified}",
]
for family, bucket in inv.by_family.items():
if bucket.get("unsupported", 0) == 0 and bucket.get("declared", 0) == 0:
continue
lines.append(
f" {family}: id={bucket['identified']} decl={bucket['declared']} "
f"dec={bucket['decoder']} unsup={bucket['unsupported']}"
)
return "\n".join(lines) + "\n"
def compact_candidates(candidates: Sequence[Candidate]) -> str:
lines = [f"candidates={len(candidates)}"]
for cand in candidates:
lines.append(
f" [{cand.priority_rank}:{cand.status}] {cand.family}:{cand.name} "
f"op=0x{cand.opcode:x} batch={cand.priority_batch}"
)
return "\n".join(lines) + "\n"
def compact_manifests(manifests: Sequence[dict[str, Any]]) -> str:
lines = [f"manifests={len(manifests)}"]
for item in manifests:
inst = item["instruction"]
lines.append(
f" [{item['priority_rank']}:{item['status']}] {inst['family']}:{inst['name']} "
f"deps={len(item['dependencies'])}"
)
return "\n".join(lines) + "\n"
def write_json(path: Path, payload: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+11 -1
View File
@@ -40,7 +40,17 @@ cargo test --locked -p xenora-ffi --features gpu-tests --test interactive --no-r
timeout 30s cargo test --locked -p xenora-ffi --features gpu-tests --test interactive -- \
--nocapture --test-threads=1
# Persistent GPU resources, dynamic texture updates, and resource retirement (Gate 5, #279).
cargo test --locked -p xenora-ffi --features gpu-tests --test resources --no-run
timeout 30s cargo test --locked -p xenora-ffi --features gpu-tests --test resources -- \
--nocapture --test-threads=1
# Audio PCM streaming and sandboxed virtual filesystem integration (Gate 6, #284).
cargo test --locked -p xenora-ffi --features gpu-tests --test audio_vfs --no-run
timeout 30s cargo test --locked -p xenora-ffi --features gpu-tests --test audio_vfs -- \
--nocapture --test-threads=1
# Native Metal known answers of the independent semantic review, including SOP2 scalar ALU
# and VOPC compares.
cargo test --locked -p xenora-semantic-review --no-run
timeout 60s cargo test --locked -p xenora-semantic-review -- --ignored --nocapture --test-threads=1
timeout 120s cargo test --locked -p xenora-semantic-review -- --ignored --nocapture --test-threads=1
+21
View File
@@ -32,6 +32,27 @@ class CliSmoke(unittest.TestCase):
data = json.loads(inv.stdout)
self.assertGreater(data["identified"], data["declared"])
compact = run("qa", "rdna2", "candidates", "--status", "reuse-primitives", "--limit", "2", "--compact")
self.assertEqual(compact.returncode, 0, compact.stderr)
self.assertIn("candidates=2", compact.stdout)
recon = run("qa", "rdna2", "reconcile", "--compact")
self.assertEqual(recon.returncode, 0, recon.stderr)
self.assertIn("reconcile_ok=", recon.stdout)
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp) / "manifests.json"
man = run(
"qa", "rdna2", "manifests",
"--status", "reuse-primitives",
"--limit", "2",
"--out", str(out),
)
self.assertEqual(man.returncode, 0, man.stderr)
payload = json.loads(out.read_text(encoding="utf-8"))
self.assertEqual(payload["count"], 2)
self.assertIn("not implemented", payload["note"].lower())
def test_release_readiness_cli_negative(self):
r = run(
"release", "readiness",
+86 -3
View File
@@ -1,16 +1,22 @@
# SPDX-License-Identifier: GPL-3.0-or-later
import json
import tempfile
import unittest
from pathlib import Path
from qa.rdna2_plan import (
Inventory,
build_manifests,
classify_unsupported,
compact_candidates,
compact_inventory,
coverage_diff,
discrepancies,
dumps_candidates,
load_inventories,
parse_claims_file,
plan_batches,
reconcile_with_coverage_report,
summarize_inventory,
)
@@ -40,9 +46,85 @@ class Rdna2Plan(unittest.TestCase):
batches = plan_batches(cands)
self.assertTrue(batches)
def test_discrepancies_and_diff(self):
issues = discrepancies(self.data)
self.assertIsInstance(issues, list)
def test_family_status_limit_and_priority(self):
reuse = classify_unsupported(
self.data, families=["SOP2"], statuses=["reuse-primitives"], limit=5
)
self.assertLessEqual(len(reuse), 5)
for cand in reuse:
self.assertEqual(cand.family, "SOP2")
self.assertEqual(cand.status, "reuse-primitives")
self.assertEqual(cand.priority_rank, 0)
needs_rules = classify_unsupported(
self.data, statuses=["needs-operand-rules"], limit=3
)
for cand in needs_rules:
self.assertEqual(cand.status, "needs-operand-rules")
self.assertEqual(cand.priority_rank, 2)
# Priority ordering: reuse before needs-operand-rules when unfiltered.
mixed = classify_unsupported(self.data, limit=20)
ranks = [c.priority_rank for c in mixed]
self.assertEqual(ranks, sorted(ranks))
def test_manifests_exclude_claims_and_stay_deterministic(self):
cands = classify_unsupported(self.data, statuses=["reuse-primitives"], limit=50)
with tempfile.TemporaryDirectory() as tmp:
claims = Path(tmp) / "claims.json"
claims.write_text(
json.dumps({"claims": [{"families": ["SOP2"], "paths": ["crates/isa/**"]}]}),
encoding="utf-8",
)
fams, paths = parse_claims_file(claims)
self.assertIn("SOP2", fams)
# Family+path claims must not path-block every other family.
self.assertEqual(paths, set())
manifests = build_manifests(
cands, exclude_families=sorted(fams), claimed_paths=sorted(paths), limit=5
)
self.assertGreater(len(manifests), 0)
for item in manifests:
self.assertNotEqual(item["instruction"]["family"], "SOP2")
self.assertIn("permitted_files", item)
self.assertIn("acceptance_tests", item)
self.assertIn("specification_references", item)
self.assertIn("dependencies", item)
again = build_manifests(
cands, exclude_families=sorted(fams), claimed_paths=sorted(paths), limit=5
)
self.assertEqual(manifests, again)
path_only = Path(tmp) / "path_only.json"
path_only.write_text(
json.dumps({"claims": [{"paths": ["crates/isa/**"]}]}),
encoding="utf-8",
)
_, path_claims = parse_claims_file(path_only)
self.assertIn("crates/isa/**", path_claims)
blocked = build_manifests(
cands, claimed_paths=sorted(path_claims), limit=5
)
self.assertEqual(blocked, [])
def test_reconcile_does_not_inflate_coverage(self):
report = reconcile_with_coverage_report(ROOT, self.data)
self.assertIn("mismatches", report)
self.assertEqual(
report["planner_totals"]["identified"],
report["canonical_totals"]["identified"],
)
# Declared/decoder may differ in representation but planner must not
# silently bump counts to hide mismatches.
before = self.inv.declared
_ = reconcile_with_coverage_report(ROOT, self.data)
after = summarize_inventory(self.data).declared
self.assertEqual(before, after)
self.assertTrue(report["ok"] or isinstance(report["mismatches"], list))
def test_compact_helpers_and_diff(self):
text = compact_inventory(self.inv)
self.assertIn("identified=", text)
cands = classify_unsupported(self.data, limit=2)
self.assertIn("candidates=2", compact_candidates(cands))
before = Inventory(
identified=self.inv.identified,
declared=self.inv.declared - 1 if self.inv.declared else 0,
@@ -54,6 +136,7 @@ class Rdna2Plan(unittest.TestCase):
)
delta = coverage_diff(before, self.inv)
self.assertEqual(delta["declared_delta"], self.inv.declared - before.declared)
self.assertIsInstance(discrepancies(self.data), list)
if __name__ == "__main__":
+82
View File
@@ -0,0 +1,82 @@
"""Validation and freshness tests for crates/loader/generate_x86.py."""
import importlib.util
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
SPEC = importlib.util.spec_from_file_location("generate_x86", ROOT / "crates/loader/generate_x86.py")
generate_x86 = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(generate_x86)
REGISTRY = (ROOT / "crates/loader/x86/instructions.toml").read_text()
class GenerateX86(unittest.TestCase):
def rejects(self, text, message):
with self.assertRaisesRegex(generate_x86.RegistryError, message):
generate_x86.load(text)
def form(self, body):
return REGISTRY + "\n[[form]]\n" + body
def test_committed_table_is_fresh_and_deterministic(self):
first = generate_x86.generate(*generate_x86.load(REGISTRY))
self.assertEqual(first, generate_x86.generate(*generate_x86.load(REGISTRY)))
self.assertEqual(first, (ROOT / "crates/loader/src/x86_table.rs").read_text())
def test_sign_extension_cannot_claim_mov_immediate_opcodes(self):
# The defect that started this work: BE/BF in the one-byte map.
for opcode in (0xBE, 0xBF):
self.rejects(
self.form(f'op = "movsx"\nopcode = {opcode}\nenc = "reg_rm"\nsize = "v"\nsrc = "b"'),
"overlapping encoding")
def test_every_mov_immediate_opcode_is_a_mov(self):
_, forms = generate_x86.load(REGISTRY)
for opcode in range(0xB0, 0xC0):
owners = [f["op"] for f in forms if f["map"] == "1"
and f["opcode"] <= opcode < f["opcode"] + f["count"]]
self.assertEqual(owners, ["mov"])
def test_overlaps_are_rejected(self):
self.rejects(self.form('op = "nop"\nopcode = 0x90\nenc = "none"\nsize = "n"'), "overlapping")
self.rejects(self.form('op = "nop"\nopcode = 0x57\nenc = "none"\nsize = "n"'), "overlapping")
self.rejects(self.form('op = "not"\nopcode = 0xF7\ndigit = 2\nenc = "rm"\nsize = "v"'), "overlapping")
self.rejects(self.form('op = "not"\nopcode = 0xF7\nenc = "rm"\nsize = "v"'), "overlapping")
def test_prefixes_and_escapes_are_not_instructions(self):
for opcode in (0x0F, 0x48, 0x66, 0xF0):
self.rejects(self.form(f'op = "nop"\nopcode = {opcode}\nenc = "none"\nsize = "n"'), "prefix or escape")
def test_contradictory_operands_are_rejected(self):
self.rejects(self.form('op = "lea"\nopcode = 0xD7\nenc = "reg_rm"\nsize = "v"\nmemory_only = true\nregister_only = true'), "contradict")
self.rejects(self.form('op = "nop"\nopcode = 0xD7\nenc = "none"\nsize = "n"\nmemory_only = true'), "without ModRM")
self.rejects(self.form('op = "nop"\nopcode = 0xD7\nenc = "none"\nsize = "n"\nimm = "ib"'), "not valid for none")
self.rejects(self.form('op = "nop"\nopcode = 0xD7\ndigit = 1\nenc = "none"\nsize = "n"'), "digit needs")
self.rejects(self.form('op = "nop"\nopcode = 0xD4\ncount = 8\nenc = "none"\nsize = "n"'), "aligned")
def test_mandatory_prefix_cannot_shadow_an_operand_size(self):
# 66 0F AF is a 16-bit IMUL, and 66 0F 6E is a MOVD; neither may be both.
self.rejects(self.form('op = "paddb"\nmap = "0f"\nprefix = "66"\nopcode = 0xAF\nenc = "xmm_rm"\nsize = "x"\nsrc = "x"'), "both an operand size")
self.rejects(self.form('op = "imul2"\nmap = "0f"\nopcode = 0x6E\nenc = "reg_rm"\nsize = "v"'), "both an operand size")
def test_vector_operand_rules(self):
self.rejects(self.form('op = "paddb"\nmap = "0f"\nprefix = "66"\nopcode = 0xF0\nenc = "xmm_rm"\nsize = "x"'), "source size")
self.rejects(self.form('op = "paddb"\nmap = "0f"\nprefix = "66"\nopcode = 0xF0\nenc = "xmm_rm"\nsize = "v"\nsrc = "x"'), "XMM size")
self.rejects(self.form('op = "movq"\nmap = "0f"\nprefix = "66"\nopcode = 0xF0\nenc = "xmm_rm"\nsize = "x"\nsrc = "q"\nunaligned = true'), "alignment applies")
self.rejects(self.form('op = "nop"\nprefix = "66"\nopcode = 0xD7\nenc = "none"\nsize = "n"'), "map 0f")
def test_unknown_vocabulary_is_rejected(self):
self.rejects(self.form('op = "frob"\nopcode = 0xD7\nenc = "none"\nsize = "n"'), "unknown op")
self.rejects(self.form('op = "nop"\nopcode = 0xD7\nenc = "none"\nsize = "z"'), "unknown size")
self.rejects(self.form('op = "nop"\nopcode = 0xD7\nenc = "none"\nsize = "n"\nextra = 1'), "unknown keys")
def test_contradictory_effects_are_rejected(self):
self.rejects(REGISTRY.replace('bt = { writes = "cf",', 'bt = { writes = "cf sf",', 1), "both written and undefined")
self.rejects(REGISTRY.replace('clc = { writes = "cf"', 'clc = { writes = "cx"', 1), "unknown flag")
self.rejects(REGISTRY.replace('ref = "sdm CLC"', 'ref = "blog CLC"', 1), "listed document")
if __name__ == "__main__":
unittest.main()