Compare commits

..
Author SHA1 Message Date
Bartosz Szczepański d2f77cdea3 Merge upstream main into cpu/195-adc-sbb-dbt
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-24 21:55:01 +01:00
Zach Doxsee 3a36379db4 Merge pull request #342 from Swastickc/qa/cpu-test-selection-159
qa: measure CPU test runtime and add deterministic test-target shards (#159)
2026-11-24 21:53:45 +01:00
Zach Doxsee 147e2a9f1a Merge pull request #372 from GDemay/perf/104-allocation-free-fetch
loader: avoid allocations when fetching instruction bytes
2026-11-24 21:53:30 +01:00
Zach Doxsee e6b657a2e9 Merge pull request #341 from sahib453/task/175-page-boundary-faults
loader: report the first inaccessible byte of a page-crossing guest fault (#175)
2026-11-24 21:43:08 +01:00
Zach Doxsee c05e631c6d Merge pull request #343 from sahib453/task/78-tls-callback-metadata
loader: reject malformed TLS callback metadata and unusable callback stacks (#78)
2026-11-24 21:42:51 +01:00
Zach Doxsee 34a583b101 Merge pull request #356 from sahib453/task/76-tls-pointer-array
loader: give the thread a TLS pointer array separate from its data (#76)
2026-11-24 21:32:15 +01:00
zachdoxsee 3b52215a30 Merge upstream main into task/175-page-boundary-faults
Conflict in CHANGELOG.md only: both new entries are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 21:20:41 +01:00
Guillaume Demay 0214a7bab5 loader: avoid allocations when fetching instruction bytes
Signed-off-by: Guillaume Demay <guillaumedemay@hotmail.fr>
2026-11-24 21:20:28 +01:00
zachdoxsee 47b526fba9 Merge the TLS pointer array branch into task/78-tls-callback-metadata
Brings in #356, which is merged first, along with main. Conflicts:
CHANGELOG.md, where every entry is kept, and crates/loader/src/tls.rs,
where the new read_callbacks function and the TLS_ARRAY_SIZE constant
were added at the same place; both are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 21:19:10 +01:00
zachdoxsee c68e3ccb4c Merge upstream main into task/78-tls-callback-metadata
Conflict in CHANGELOG.md only: both new entries are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 21:17:57 +01:00
zachdoxsee fb6282ceb2 Merge upstream main into task/76-tls-pointer-array
Conflict in CHANGELOG.md only: both new entries are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 21:16:38 +01:00
Zach Doxsee bb6a9f6912 Merge pull request #361 from sahib453/task/125-movnti
loader: add MOVNTI, the non-temporal store of a general register (#125)
2026-11-24 21:15:11 +01:00
Zach Doxsee a7e3e1e42c Merge pull request #358 from sahib453/task/199-fences
loader: accept MFENCE, LFENCE and SFENCE and document guest memory ordering (#199)
2026-11-24 21:14:51 +01:00
Zach Doxsee 9c76bf16f0 Merge pull request #357 from Arths17/test/205-handle-lifetime
test: cover guest handle lifetime and failed-call nonmutation (#205)
2026-11-24 21:14:37 +01:00
Bartosz Szczepański 788de1e83b Merge upstream main into cpu/195-adc-sbb-dbt
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-24 21:08:00 +01:00
Zach Doxsee 7dd1329866 Merge pull request #367 from jelly013/probe-default-folder
cli: use a neutral default folder for probe reports (#364)
2026-11-24 21:07:02 +01:00
Zach Doxsee 4b579af70d Merge pull request #360 from 1Bartosz/perf/116-release-lto
build: use fat LTO and one codegen unit for release builds (#116)
2026-11-24 21:06:47 +01:00
zachdoxsee b4f45573cf Merge the updated fences branch into task/125-movnti
Brings the branch up to main after #366 and #368, with #358, which is
merged first. No conflicts.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 21:05:39 +01:00
zachdoxsee 0766307acc Merge upstream main into task/199-fences
Brings the branch up to main after #366 and #368. No conflicts.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 21:05:39 +01:00
Zach Doxsee 9dfdfd1134 Merge pull request #365 from Arths17/fix/363-native-audit-utf8
Read native audit JSON as UTF-8
2026-11-24 21:05:34 +01:00
zachdoxsee ce8d16e367 Merge upstream main into test/205-handle-lifetime
Conflict in CHANGELOG.md only: both new entries are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 21:05:23 +01:00
atharvranjan 8df13ae976 ci: retrigger 2026-11-24 14:02:59 -06:00
Zach Doxsee 3c8b6bad97 Merge pull request #366 from vedantdadhich21/fix/gpu-semantic-timeout
Scripts: allow longer Metal semantic-review runs
2026-11-24 21:01:35 +01:00
Zach Doxsee d4c29cd7dd Merge pull request #368 from izdat-sl4w/fix/unsigned-jcc-boundaries
cpu: pin the unsigned Jcc conditions at their boundaries
2026-11-24 20:59:17 +01:00
zachdoxsee 938cbd3028 Merge upstream main and the fences branch into task/125-movnti
Conflicts: CHANGELOG.md and the rejected-encodings list in
x86_integer.rs, where both sides are kept; the case list in
tests/x86/assemble.py, which now has the fences followed by MOVNTI; and
the generated x86_table.rs and tests/x86/integer.txt, rebuilt with
generate_x86.py and assemble.py from the merged sources.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 20:56:21 +01:00
zachdoxsee c9505e53e2 Merge upstream main into task/199-fences
Conflicts: CHANGELOG.md, where both entries are kept; the generated
crates/loader/src/x86_table.rs, rebuilt with generate_x86.py from the
merged instructions.toml; and one sentence of
docs/cpu/instruction-registry.md, where the list of rejected
instructions now drops both RCL/RCR (from #351) and the fences.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 20:54:40 +01:00
Zach Doxsee 02eb8046a1 Merge pull request #355 from sahib453/task/118-xchg-accumulator
loader: add the accumulator short form of XCHG (#118)
2026-11-24 20:46:47 +01:00
Zach Doxsee 4a0b5d4ded Merge pull request #344 from sahib453/task/128-exact-unmasked-overflow
loader: set only the overflow flag for an exact unmasked overflow (#128)
2026-11-24 20:46:33 +01:00
atharvranjan 00eb6971e9 Preserve UTF-8 native inspection output
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 13:45:16 -06:00
Bartosz Szczepański 1013746e17 Merge upstream main into cpu/195-adc-sbb-dbt
Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-24 20:44:24 +01:00
izdat-sl4w 7c88e5d655 cpu: pin the unsigned Jcc conditions at their boundaries
The native DBT had no test for the 0x70..=0x7F or the 0F 80..=8F block
at all. These four conditions are the ones an ARM64 condition code
cannot provide directly: SUBS sets C when a subtraction does not
borrow, so x86 CF is its inverse, and ARM64's HI and LS are defined on
that same inverted carry.

Three tests derive CF and ZF from the operands (Intel SDM Volume 1,
3.4.3.1), then check JB, JAE, JBE and JA in the short and the near
encoding at both ends of the 32-bit and 64-bit ranges, with SUB as well
as CMP, and with the compare and the branch in separate translated
blocks. Inverting the borrow polarity in the lowering makes all three
fail.

Closes #64

Signed-off-by: izdat-sl4w <76667566+izdat-sl4w@users.noreply.github.com>
2026-11-24 20:43:54 +01:00
zachdoxsee bb318ed2ba Merge upstream main into task/118-xchg-accumulator
Conflicts in CHANGELOG.md, where both new entries are kept, and in the
generated crates/loader/src/x86_table.rs, which is rebuilt with
generate_x86.py from the merged instructions.toml.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 20:41:29 +01:00
zachdoxsee b1b57cf16a Merge upstream main into task/128-exact-unmasked-overflow
Conflict in CHANGELOG.md only: both new entries are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 20:40:31 +01:00
jelly013 e5aca73c55 cli: use a neutral default folder for probe reports
`xenora probe` and `xenora imports sync` defaulted to a folder named after
one commercial game. Give both one shared default, `diagnostics/probe`, and
ignore it in Git. Keep the old ignore rules so existing local reports stay
out of commits.

Closes #364

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-24 20:31:13 +01:00
atharvranjan 281d92bfb5 Read native audit JSON as UTF-8
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 13:28:35 -06:00
Vedant Dadhich fec13fa27a Scripts: allow longer Metal semantic-review runs
The full semantic-review batch can exceed the hard-coded 120-second timeout on a cold Apple Silicon host. A local M1 acceptance run exited 124 while tests were still progressing; the same batch passed with a longer limit. Add XENORA_SEMANTIC_TIMEOUT, default it to 300 seconds, and document the override.

Signed-off-by: Vedant Dadhich <vedantdadhich21@gmail.com>
2026-11-25 00:57:15 +05:30
sahib453 94783fa603 docs: take the fences off the rejected-on-purpose list (#199)
The instruction registry document listed fences among the forms
rejected on purpose. This branch accepts them and explains why in the
new memory-ordering section, so the list no longer names them.

Signed-off-by: sahib453 <117431595+sahib453@users.noreply.github.com>
2026-11-25 00:44:40 +05:30
atharvranjan 974d1fc62c ci: retrigger 2026-11-24 13:13:14 -06:00
sahib453 223a754eb7 loader: add MOVNTI, the non-temporal store of a general register (#125)
Both engines refused MOVNTI (0F C3 /r) as an illegal instruction. It is
the SSE2 move still missing next to the XMM moves already implemented.

- instructions.toml, x86_table.rs (generated): MOVNTI for 32- and
  64-bit operands with a memory destination only.
- x86_exec.rs: an ordinary store of the register, as the other
  non-temporal stores already are.
- cpu_known_answers.rs: the SDM-derived case that ends in a MOVNTI
  moves from refused to verified.
- tests/x86: four assembled instructions with the text-only reference;
  the register form and the 66 prefix join the rejected encodings.

MASKMOVDQU stays rejected and SSE2 stays unreported by CPUID.

Signed-off-by: sahib453 <117431595+sahib453@users.noreply.github.com>
2026-11-25 00:40:02 +05:30
sahib453 d195978903 loader: accept MFENCE, LFENCE and SFENCE and document guest memory ordering (#199)
Both engines refused the three fences as illegal instructions, and no
document said what ordering guest memory accesses have.

- instructions.toml, x86_table.rs (generated): the register forms of
  0F AE digits 5, 6 and 7. The memory forms stay undeclared.
- x86_exec.rs: a fence changes nothing. Each engine runs one guest
  instruction at a time on one host thread and completes its loads and
  stores before the next, so accesses are already totally ordered.
- docs/cpu/instruction-registry.md: states that ordering, why the
  fences are no-ops under it, and that it holds only while guest
  threads do not run on several host threads.
- Tests: five single-thread known-answer cases, three assembled
  fixtures, two rejected memory forms, and MASKMOVDQU as the refused
  SSE2 instruction in cpu_features.rs now that MFENCE runs.

No multi-thread behaviour is established.

Signed-off-by: sahib453 <117431595+sahib453@users.noreply.github.com>
2026-11-25 00:25:27 +05:30
sahib453 782c49167c loader: give the thread a TLS pointer array separate from its data (#76)
The harness stores the thread's TLS base in the TEB's TLS pointer field,
and setup_tls mapped the thread's copy of the template at that address.
Compiled code indexes that pointer by the module's TLS index to find the
data block, so it took the first eight bytes of the template for the
block address.

- tls.rs: setup_tls maps a pointer array at the thread's TLS base and
  the data block one page above it, and stores the block address in the
  slot of the index it assigns. startup.rs is unchanged.
- tests/tls_layout.rs: follows the access sequence through guest memory
  for a template with zero fill, a rebased image and a zero-fill-only
  directory, and checks the image's template is left alone.

Signed-off-by: sahib453 <117431595+sahib453@users.noreply.github.com>
2026-11-25 00:17:10 +05:30
Arths17 6106c37912 test: cover guest handle lifetime and failed-call nonmutation
Signed-off-by: Arths17 <166588440+Arths17@users.noreply.github.com>
2026-11-24 12:46:32 -06:00
sahib453 823a5812a0 loader: add the accumulator short form of XCHG (#118)
Both engines refused XCHG with the register in the opcode (91 to 97,
and 90 with REX.B) as an illegal instruction. Assemblers choose this
form whenever one operand is the accumulator.

- instructions.toml, x86_table.rs (generated): one form per opcode 91
  to 97. A row of eight would have to start at 90, which is NOP.
- x86_decode.rs: 90 stays NOP without REX.B and decodes as the 91 form
  with register r8 when REX.B is set. F3 before it is rejected.
- x86_exec.rs: exchange the accumulator with the named register at 16,
  32 and 64 bits.
- cpu_known_answers.rs: three SDM-derived cases move from refused to
  verified.
- tests/x86: 20 assembled instructions, checked by the existing
  text-only reference. `xchg r8, rax` leaves the rejected list.

Nothing is lowered to ARM64.

Signed-off-by: sahib453 <117431595+sahib453@users.noreply.github.com>
2026-11-25 00:09:31 +05:30
Bartosz Szczepański c95e175210 loader: run ADC and SBB register and immediate forms natively in the DBT (#195)
The DBT now lowers the 32- and 64-bit register and immediate forms of
ADC and SBB to ADCS and SBCS instead of calling the shared semantics.
The guest CF is moved into the host carry first, inverted for SBB
because SBCS subtracts NOT C while SBB subtracts CF. Memory forms and
8- and 16-bit forms stay on the shared semantics.

Adds the ADCS and SBCS encodings to the ARM64 assembler, checked
against llvm-mc, and tests/x86_carry_chain.rs: 256-bit add and
subtract chains of 64- and 32-bit limbs, in one block and split one
block per limb, against widening u128/i128 reference arithmetic in
both engines, plus 128-bit immediate increments and decrements and the
sbb reg, reg carry mask.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-24 19:12:29 +01:00
sahib453 403a67747f loader: set only the overflow flag for an exact unmasked overflow (#128)
With the overflow exception unmasked, an overflow whose result is exact
before the exponent is bounded set the MXCSR precision flag as well as
the overflow flag. The Intel SDM (Vol. 1, D.4.2.3, Table D-16) reports
precision there only if rounding with an unbounded exponent is inexact.

- softfloat.rs: Control reads the overflow mask, and round() reports
  precision on an unmasked overflow only when the result was rounded.
  The masked response is unchanged.
- cpu_known_answers.rs: the five exact-overflow cases are no longer an
  ignored defect, three more cover the other rounding modes, and the
  scalar and conversion sweeps now compare the precision flag here.
- docs/cpu/instruction-registry.md: the behaviour is no longer listed
  as unasserted.

Signed-off-by: sahib453 <117431595+sahib453@users.noreply.github.com>
2026-11-24 23:25:07 +05:30
sahib453 509811aad0 loader: reject malformed TLS callback metadata and unusable callback stacks (#78)
The TLS directory parser accepted or misread several malformed callback
lists without an error, and the callback runner could overflow on a
small stack top.

- A non-zero AddressOfCallbacks outside every section, or 4 GiB or more
  above the image base, is refused. It used to mean "no callbacks" or
  read the list from an unrelated place.
- The list must reach its null entry inside its section. The section's
  zero-filled tail counts as zero; bytes that follow in the file do not.
- More than 64 callbacks is an error, not a silent cut.
- execute_tls_callbacks refuses a stack top that is not 16-byte aligned
  or cannot hold the entry frame, before any callback runs.
- A file cut inside the TLS data-directory entry no longer panics.

TlsError gains four variants. Twelve unit tests use original headers
and code and also cover the argument registers, the entry and return
stack pointer, callback order and the instruction budget.

Signed-off-by: sahib453 <117431595+sahib453@users.noreply.github.com>
2026-11-24 23:19:19 +05:30
Swastickc b9372408c8 qa: measure CPU test runtime and add deterministic test-target shards (#159)
Add scripts/cpu-tests.sh, which lists the default-feature workspace test
targets, runs shard K of N of them in a fixed round-robin order, and checks
that N shards cover every target exactly once. It fails when Cargo cannot
build the workspace instead of running a partial list. The full gate
(cargo test --locked --workspace) and scripts/test-gpu.sh are unchanged.

Record the measured gate cost and the selected-versus-full comparison in
docs/testing/cpu-coverage.md, index it in docs/README.md, and add a
changelog entry.

Signed-off-by: Swastickc <28708247+Swastickc@users.noreply.github.com>
2026-11-24 23:11:18 +05:30
sahib453 8b67479526 loader: report the first inaccessible byte of a page-crossing guest fault (#175)
A guest access that starts in a mapped 4 KiB page and runs into an
unmapped or forbidden one reported the start of the access. It now
reports the lowest address the access may not touch, which is what the
Intel SDM page-fault cases from #155 expect. Which accesses succeed is
unchanged, and a failed access still reads and writes nothing.

- memory.rs: resolve() reports the failing byte for both
  UnmappedAddress and PermissionViolation.
- tests/memory_page_boundaries.rs: permissions, adjacent pages, address
  overflow and the fault address at every 4 KiB guest boundary across
  two host pages (16 KiB each on Apple Silicon).
- cpu_known_answers.rs: the three page-crossing fault cases are no
  longer an ignored defect; they pass on both engines.
- memory_validation.rs, generated_runtime_integration.rs: five
  expectations that pinned the start address now name the first
  inaccessible byte.

Signed-off-by: sahib453 <117431595+sahib453@users.noreply.github.com>
2026-11-24 23:09:42 +05:30
35 changed files with 2823 additions and 226 deletions

No files matched your search

+2
View File
@@ -52,6 +52,8 @@ jobs:
sh -n scripts/agent-queue.sh scripts/agent-sync.sh
- name: Test pull request template check
run: PYTHONPATH=scripts python3 -m unittest discover -s tests/pr_template
- name: Test native audit JSON decoding
run: python3 -m unittest discover -s tests/audit
- name: Test semantic registry generator and coverage report
run: |
python3 -m unittest discover -s tests/semantics_generator
+1
View File
@@ -35,6 +35,7 @@
__pycache__/
*.pyc
/diagnostics/probe/
/diagnostics/gta6-candidate-*/
/diagnostics/gta6-check/
+21
View File
@@ -10,9 +10,12 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Changed
- The native ARM64 DBT now runs the 32- and 64-bit register and immediate forms of ADC and SBB itself instead of falling back to the shared interpreter (#195). The guest CF is moved into the host carry before ADCS or SBCS, inverted for SBB because SBCS subtracts NOT C while SBB subtracts CF. Memory forms and 8- and 16-bit forms still use the shared semantics. `tests/x86_carry_chain.rs` runs 256-bit add and subtract chains of 64- and 32-bit limbs, in one block and split one block per limb, against widening `u128`/`i128` reference arithmetic in both engines, plus immediate 128-bit increments and decrements and the `sbb reg, reg` carry mask. Locally verified on Apple M5 only.
- Removed the temporary region-list allocation from each instruction-byte fetch while preserving lookup order, execute-permission checks and error behavior (part of #104).
- Release and bench builds now use fat link-time optimization with one codegen unit (#116). On a local Apple M5, `dbt_bench` medians over five alternating runs dropped by about 6 % for the interpreter (903 to 845 µs) and about 9 % for cold DBT (1.155 to 1.046 ms), while warm DBT (cache hits) became about 2 % slower (21.83-22.08 to 22.29-22.54 µs over four further runs). The `xenora` binary shrank from 2.73 to 2.11 MB. A clean release build of the workspace takes about 14 s instead of 6 s. Debug and test builds are unchanged.
- The ARM64 assembler loads 64-bit constants with the fewest MOVZ or MOVN plus MOVK instructions (#92). It no longer emits MOVK for zero halfwords and starts from MOVN when more halfwords are 0xFFFF than zero, so small negative values take one instruction instead of four. On Apple M5 the DBT benchmark emits 245,168 instead of 290,184 native bytes for its 626 blocks (-15.5%) and the 1,048 integer fixture instructions 128,724 instead of 145,732 (-11.7%); benchmark run times did not change measurably. New tests check the sequences against LLVM encodings and execute 1,056 of them on the host through the JIT.
- Resolve the tiled BC1 mip and array layer once per linearization and copy contiguous block runs within each tile row. Partial edge blocks are retained and padding slots are skipped. Closes #349.
- Changed the default report folder of `xenora probe` and `xenora imports sync` to `diagnostics/probe`, which Git ignores (#364). Anyone relying on the earlier default has to pass `--report`.
- Relocation reports now build their type histogram once per image, avoiding a tree lookup for every entry. Target checks and fixup order are unchanged; synthetic regressions and an opt-in relocation timing test cover the change (#109).
- Moved the six supported gfx1030 SOPP compute control forms into the semantic registry, preserving instruction decoding and shader lowering. Part of #215.
- Moved gfx1030 `s_mov_b32` (SOP1) into the semantic registry, preserving its existing decode domain and shader output. The move operand rule retains explicit VCC and EXEC half destinations. Part of #215.
@@ -20,10 +23,23 @@ remains unsupported.
- Added non-blocking Metal compute submission through `submit_words` and `wait`, with completion-aware resource retirement and a sixteen-dispatch in-flight limit. Synchronous calls keep their existing behavior. The benchmark reports the host submission split and compares synchronous and pipelined batches.
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
### Fixed
- Made the native semantic-review timeout in `scripts/test-gpu.sh` configurable with `XENORA_SEMANTIC_TIMEOUT` and raised its default from 120 to 300 seconds, so cold Apple Silicon runs do not fail while the expanded Metal known-answer suite is still progressing.
### Added
- Added synthetic guest handle-lifetime regression tests (#205) for capacity reuse, stale handles, duplicate rights and lifetime, wrong object types, thread pseudo handles and failed-output nonmutation. Runtime behavior is unchanged; independent acceptance is pending.
- Added a documented independent acceptance rule for promoting AMD RDNA2 desktop GPU (gfx1030) forms from local CPU and Metal results to `fixture verified`, including clean-commit evidence, reviewer independence, raw-log location, review-log summary, failure handling and status regeneration (#302).
- Added the VOP3A (`_e64`) encodings of eleven gfx1030 VOP2 integer forms (`v_mul_{i32_i24,hi_i32_i24,u32_u24,hi_u32_u24}`, `v_{min,max}_{i32,u32}`, `v_xnor_b32`, `v_sub_nc_u32`, `v_subrev_nc_u32`) and of the sixteen Wave32 integer compares (explicit SGPR mask destination, `s_cbranch_vccz` through `vcc_lo`, a translation error for reads of runtime-only SGPR results) as semantic-registry encoding variants, with VGPR sources only. New fixtures `vop3-integer` and `vop3-compare` with IR and MSL goldens, and an independent guide-derived oracle (`tests/validation/tests/vop3_{integer,compare}.rs`) that agrees on both reference interpreters and on native Metal. Part of #215.
- Added `scripts/cpu-tests.sh`, which lists the default-feature workspace test targets and runs
deterministic shards of them (`--shard K/N`), with `--check N` showing every target lands in
exactly one shard. It does not replace `cargo test --locked --workspace` or
`scripts/test-gpu.sh`. `docs/testing/cpu-coverage.md` records local CPU gate timings on one
Apple M4 host (about 40 s wall time; one loader target takes about 19 s) and shows that the 2- and
3-shard unions match the full gate's 681 passed and 34 ignored tests (#159).
- Added guest texture binding through D3D12-style descriptor tables (#303): shader-visible CBV_SRV_UAV and sampler heaps, `CreateShaderResourceView` for one-level RGBA8 and BC1 2D textures, a point/clamp `CreateSampler`, a root signature with one pixel-stage SRV table and one sampler table, and `SetDescriptorHeaps`/`SetGraphicsRootDescriptorTable` in `crates/loader/src/graphics.rs`, plus `NativeCompute::render_rgba8_sampled_bc1`. Verified locally on an Apple M5 Pro under Metal validation: a guest draw with the translated `image_sample_lz` pixel stage matches the software reference and hand-derived images on 16 of 16 pixels for two RGBA8 textures and 64 of 64 for an 8×8 BC1 texture. A wrong descriptor slot changes the image, off-centre and out-of-range coordinates point-sample with clamping, and a rejected binding, draw shape or resource state never reaches the backend. The software reference samples BC1 with the spec-exact decoder, while Apple's hardware rounds BC1's interpolated palette entries differently (171/84 against 170/85), so the BC1 fixtures use only endpoint colours. Not yet reachable from guest imports. Not yet independently accepted.
- Added MOVNTI, the SSE2 non-temporal store of a 32- or 64-bit general register to memory (part of #125). Both engines used to stop on it with an illegal-instruction exit. It is an ordinary store, as the other non-temporal stores already are; the register form and the 66 prefix stay rejected, and a destination that cannot be written faults without changing state. The SDM-derived case `movdqa_movaps_aligned_store_and_load` in `cpu_known_answers.rs`, which ends in a MOVNTI, moved from refused to verified, and `tests/x86/integer.txt` gains four assembled instructions checked by the text-only reference in `x86_integer.rs`. MASKMOVDQU stays rejected and SSE2 stays unreported by CPUID. Not compared with x86 hardware; awaiting independent review.
- Added MFENCE, LFENCE and SFENCE and documented the ordering of guest memory accesses (part of #199). Both engines used to stop on a fence with an illegal-instruction exit. Each engine runs one guest instruction at a time on one host thread and completes its loads and stores before the next, so accesses are already totally ordered and the fences change nothing; `docs/cpu/instruction-registry.md` states this and that it holds only while guest threads do not run on several host threads. Five single-thread cases in `cpu_known_answers.rs` and three assembled fixtures cover them, and the memory forms that share the opcode stay rejected. SSE2 is still not reported by CPUID because other SSE2 instructions are rejected; the refused SSE2 instruction that `cpu_features.rs` holds is now MASKMOVDQU. No multi-thread behaviour is established, and nothing was compared with x86 hardware; awaiting independent review.
- Added the accumulator short form of XCHG, opcodes 91 to 97 and 90 with REX.B, at 16, 32 and 64 bits (part of #118). Assemblers choose this form whenever one operand is the accumulator, and both engines used to stop on it with an illegal-instruction exit. A 16-bit exchange keeps the upper 48 bits of both registers, a 32-bit one clears both upper halves, and `49 90` exchanges RAX with R8 while plain `90` stays NOP. Both engines run the shared semantics; nothing is lowered to ARM64. Three SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and `tests/x86/integer.txt` gains 20 assembled instructions checked by the text-only reference in `x86_integer.rs`. F3 before this form, 16-bit PUSH and POP and LODSW stay rejected. Not compared with x86 hardware; awaiting independent review.
- Added RCL and RCR, the rotates through the carry flag, for 8-, 16-, 32- and 64-bit register and memory operands with a count of one, CL or an immediate (part of #121). The count is masked to five bits (six for 64-bit operands) and then reduced modulo 9 or 17 for 8- and 16-bit operands; a masked count of zero changes nothing, CF receives the last bit rotated out, and OF is set only for a count of one. Both engines run the shared semantics; nothing is lowered to ARM64. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and its shift sweep now runs both instructions at every width, count and carry against its bit-loop model. `tests/x86/integer.txt` gains 80 assembled RCL and RCR instructions, checked by the single-step reference in `x86_integer.rs`. SHLD and SHRD stay rejected. Not compared with x86 hardware; awaiting independent review.
- Added four Wave32 gfx1030 VOP2 select and carry forms through the semantic registry. Conditional select, add with carry and both subtract orders with borrow use a per-lane VCC bit and have a guide-derived oracle that passes on both CPU interpreters and on native Metal (local Apple M5, API and shader validation); independent acceptance is pending. Part of #215.
- Added decoding and Metal shader translation for twelve Wave32 VOPC 16-bit integer compares (#215). The signed and unsigned forms compare the low 16 bits of each source and write the Wave32 VCC mask. CPU verification covers 1,572 compiler acceptance cases and 408 rejections from the guide-derived oracle, which also passes on native Metal (1,572 cases in 1,420 programs on a local Apple M5 under API and shader validation); acceptance is pending.
@@ -193,7 +209,12 @@ remains unsupported.
native DBT.
### Fixed
- Fixed the address reported when a guest memory access faults part-way across a 4 KiB page boundary (#175). An access that starts in a mapped page and runs into an unmapped or forbidden one now reports the first byte it may not touch; it used to report the start of the access. An access whose first byte fails reports the same address as before, and a failed access still reads and writes nothing. Three Intel SDM page-fault cases in `cpu_known_answers.rs` moved from open defect to verified on both engines. `crates/loader/tests/memory_page_boundaries.rs` checks permissions, adjacent pages, address overflow and the fault address at every 4 KiB guest boundary across two host pages (16 KiB each on Apple Silicon). Guest memory is checked in software, so the host page size does not affect these results. Four #82 expectations and one CRT `memmove` expectation that pinned the start address were corrected. Not compared with x86 hardware; awaiting independent review.
- Fixed the native dependency audit reading Cargo JSON and inspection-tool output in the process locale encoding; it now reads and reports UTF-8 paths and diagnostics under an ASCII locale (#363).
- Made the static probe and the binder share one bounded import parser, after the truncated-name fix for #270. Truncated, unterminated, empty or non-ASCII names, reserved bits and endless tables are reported by the probe and refused by the binder.
- Fixed TLS callback metadata that was accepted or misread without an error (#78). A non-zero `AddressOfCallbacks` outside the image's sections, or 4 GiB or more above the image base, is now refused; it used to mean "no callbacks" or read the list from an unrelated place. The callback list must reach its null entry inside its section, where the section's zero-filled tail counts, and a list of more than 64 callbacks is refused where it used to be cut short. `execute_tls_callbacks` refuses a stack top that is not 16-byte aligned or cannot hold the entry frame, which used to overflow a subtraction, and a file cut inside the TLS data-directory entry no longer panics the parser. `TlsError` gains four variants for these cases. Twelve unit tests in `crates/loader/src/tls.rs` use original headers and code, and also check the argument registers, the stack pointer at entry and after return, callback order and the instruction budget. Expectations come from Microsoft's public PE Format and x64 calling convention pages; nothing ran on Windows, and independent review is pending.
- Fixed the thread's TLS pointer naming the TLS data itself (#76). Compiled code loads the pointer from the thread environment block, indexes it by the module's TLS index to get the address of the data block, and then adds a variable's offset; the loader had mapped the data where the pointer array belongs, so the first eight bytes of the template were used as the block address. `setup_tls` now maps a pointer array at the thread's TLS base and the data block one page above it, and stores the block address in the slot of the index it assigns. `crates/loader/tests/tls_layout.rs` follows that access sequence through guest memory for a template with zero fill, a rebased image and a zero-fill-only directory. The data block of the fixture harness can now be at most 60 KiB, down from 64 KiB, before it would meet the thread environment block. Alignment requests above 4 KiB and more than one module's TLS are not handled. The access sequence follows Microsoft's public PE Format page; nothing ran on Windows, and independent review is pending.
- Fixed the MXCSR flags of an unmasked floating-point overflow whose result is exact before the exponent is bounded, such as the largest binary32 value times two (#128). Only the overflow flag is set; the precision flag used to be set as well although nothing was rounded. A masked overflow still sets both flags and delivers infinity or the largest finite value, and an unmasked overflow that is also inexact still sets both. Five Intel SDM cases in `cpu_known_answers.rs` moved from open defect to verified on both engines, with three more for the other rounding modes, and the scalar and conversion sweeps now compare the precision flag in this case as well. Not compared with x86 hardware; awaiting independent review.
- Fixed the decoder refusing an instruction whose REX prefix is followed by a legacy prefix (#69). Such a REX is ignored, as the Intel SDM (Vol. 2A, 2.2.1) specifies, so `48 66 01 D8` now runs as `add ax, bx`; it used to stop the guest with an illegal-instruction exit. The ignored byte still counts toward the instruction's length, and a REX that directly precedes the opcode behaves as before. The interpreter, the DBT and the static probe share the decoder. One SDM-derived case in `cpu_known_answers.rs` moved from refused to verified and three were added, for an ignored REX.B, an ignored REX.W before a segment prefix, and a later REX that does apply. Two REX bytes in a row and the address-size prefix stay rejected. Not compared with x86 hardware; awaiting independent review.
- Fixed import binding writing some slots before finding an unresolved import, and service calls taking effect before an unreadable return address was noticed. A service that changes a nonvolatile register, including XMM6 to XMM15, now stops the guest (part of #201).
- Fixed older import-generator templates that reported success for unimplemented wrappers, used a nonexistent exit reason, and read floating-point arguments from integer registers.
+1 -1
View File
@@ -309,7 +309,7 @@ These require a Metal-capable Apple Silicon Mac.
scripts/test-gpu.sh
```
The native test suite enables Metal API and shader validation and tests the supported compute, rendering and texture paths.
The native test suite enables Metal API and shader validation and tests the supported compute, rendering and texture paths. The full semantic-review batch defaults to a 300-second timeout; set `XENORA_SEMANTIC_TIMEOUT` to raise or lower it for a slower or faster host.
### Verify guest execution
+5 -2
View File
@@ -6,6 +6,9 @@ mod shaders;
use std::process::ExitCode;
/// Where `probe` writes and `imports sync` reads without `--report`.
const DEFAULT_REPORT_DIR: &str = "diagnostics/probe";
fn main() -> ExitCode {
match std::env::args().nth(1).as_deref() {
Some("info") => {
@@ -46,7 +49,7 @@ fn main() -> ExitCode {
let args: Vec<String> = std::env::args().collect();
let mut pe_path: Option<String> = None;
let mut mode = "static".to_string();
let mut report_dir = "diagnostics/gta6-candidate-e95020b2".to_string();
let mut report_dir = DEFAULT_REPORT_DIR.to_string();
let mut i = 2;
while i < args.len() {
@@ -373,7 +376,7 @@ fn run_imports_generate_cli(args: &[String]) -> ExitCode {
}
fn run_imports_sync_cli(args: &[String]) -> ExitCode {
let mut report_dir = "diagnostics/gta6-candidate-e95020b2".to_string();
let mut report_dir = DEFAULT_REPORT_DIR.to_string();
let mut check_mode = false;
let mut i = 0;
+27
View File
@@ -0,0 +1,27 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Default report folder of `xenora probe` and `xenora imports sync`.
use std::process::Command;
#[test]
fn probe_and_sync_use_the_same_default_folder() {
let fixture = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../fixtures/pe/delay-imports.exe"
);
let folder = std::env::temp_dir().join(format!("xenora-default-{}", std::process::id()));
std::fs::create_dir(&folder).unwrap();
for arguments in [&["probe", "--pe", fixture][..], &["imports", "sync"]] {
let status = Command::new(env!("CARGO_BIN_EXE_xenora"))
.args(arguments)
.current_dir(&folder)
.status()
.unwrap();
assert!(status.success(), "{arguments:?}");
}
let written = ["imports.csv", "import_backlog.md"]
.map(|name| folder.join("diagnostics/probe").join(name).is_file());
std::fs::remove_dir_all(folder).unwrap();
assert_eq!(written, [true, true]);
}
+40
View File
@@ -430,6 +430,46 @@ impl Arm64Assembler {
);
}
/// ADCS (64-bit, flags updating): ADCS Xd, Xn, Xm computes Xn + Xm + C.
pub fn adcs_reg_64(&mut self, xd: u8, xn: u8, xm: u8) {
self.emit(
0xba000000
| ((xm as u32 & 0x1f) << 16)
| ((xn as u32 & 0x1f) << 5)
| (xd as u32 & 0x1f),
);
}
/// ADCS (32-bit, flags updating): ADCS Wd, Wn, Wm computes Wn + Wm + C.
pub fn adcs_reg_32(&mut self, wd: u8, wn: u8, wm: u8) {
self.emit(
0x3a000000
| ((wm as u32 & 0x1f) << 16)
| ((wn as u32 & 0x1f) << 5)
| (wd as u32 & 0x1f),
);
}
/// SBCS (64-bit, flags updating): SBCS Xd, Xn, Xm computes Xn - Xm - !C.
pub fn sbcs_reg_64(&mut self, xd: u8, xn: u8, xm: u8) {
self.emit(
0xfa000000
| ((xm as u32 & 0x1f) << 16)
| ((xn as u32 & 0x1f) << 5)
| (xd as u32 & 0x1f),
);
}
/// SBCS (32-bit, flags updating): SBCS Wd, Wn, Wm computes Wn - Wm - !C.
pub fn sbcs_reg_32(&mut self, wd: u8, wn: u8, wm: u8) {
self.emit(
0x7a000000
| ((wm as u32 & 0x1f) << 16)
| ((wn as u32 & 0x1f) << 5)
| (wd as u32 & 0x1f),
);
}
/// ADD (immediate, 64-bit): ADD Xd, Xn, #imm12
pub fn add_imm_64(&mut self, xd: u8, xn: u8, imm12: u16) {
self.emit(
+224 -1
View File
@@ -335,6 +335,9 @@ pub fn is_native(insn: &Insn) -> bool {
let scanned = matches!(insn.size, 2 | 4 | 8);
match insn.op {
Op::Add | Op::Sub | Op::Cmp | Op::And | Op::Or | Op::Xor | Op::Test => wide,
// Register and immediate forms only; a memory destination would have
// to restore the guest carry again after the store helper call.
Op::Adc | Op::Sbb => wide && insn.memory().is_none(),
Op::Inc | Op::Dec | Op::Neg | Op::Not => wide,
Op::Cmov => wide,
Op::Bsf | Op::Bsr => scanned,
@@ -587,9 +590,26 @@ impl Emitter<'_> {
}
/// X11 = X9 op X10, setting host NZCV only for the arithmetic operations.
/// ADC and SBB also read the guest CF and clobber X12 and X13.
fn compute(&mut self, op: Op, wide: bool) {
let asm = &mut *self.asm;
if matches!(op, Op::Adc | Op::Sbb) {
// ADCS adds the host C, so C must equal the guest CF. SBCS
// subtracts NOT C, while x86 SBB subtracts the borrow CF, so there
// C must be its inverse. A compare sets C when it does not borrow.
asm.ldrb_uoff(X12, X19, CF);
if op == Op::Adc {
asm.load_imm_64(X13, 1);
asm.cmp_reg_32(X12, X13); // C = CF >= 1
} else {
asm.cmp_reg_32(XZR, X12); // C = 0 >= CF
}
}
match (op, wide) {
(Op::Adc, true) => asm.adcs_reg_64(X11, X9, X10),
(Op::Adc, false) => asm.adcs_reg_32(X11, X9, X10),
(Op::Sbb, true) => asm.sbcs_reg_64(X11, X9, X10),
(Op::Sbb, false) => asm.sbcs_reg_32(X11, X9, X10),
(Op::Add | Op::Inc, true) => asm.adds_reg_64(X11, X9, X10),
(Op::Add | Op::Inc, false) => asm.adds_reg_32(X11, X9, X10),
(Op::And | Op::Test, true) => asm.ands_reg_64(X11, X9, X10),
@@ -623,7 +643,7 @@ impl Emitter<'_> {
match op {
// INC and DEC leave CF unchanged.
Op::Inc | Op::Dec => {}
Op::Add => {
Op::Add | Op::Adc => {
asm.cset_32(X12, Condition::Cs);
asm.strb_uoff(X12, X19, CF);
}
@@ -2267,4 +2287,207 @@ mod tests {
ExitReason::MemoryFault(MemoryError::UnmappedAddress(FS_BASE + 8))
);
}
/// Intel SDM Volume 1, section 3.4.3.1: for `SUB` and `CMP`, `CF` is the
/// borrow out of the most significant bit. `JB` is `CF = 1`, `JAE` is
/// `CF = 0`, `JBE` is `CF = 1 or ZF = 1` and `JA` is `CF = 0 and ZF = 0`.
///
/// ARM64 reports the inverse: `SUBS` sets `C` when the subtraction does
/// *not* borrow, and its `HI`/`LS` conditions are defined on that same
/// inverted carry. These four x86 conditions therefore cannot be taken
/// from an ARM64 condition code without translating the borrow first,
/// which makes them the ones to pin at the boundaries.
/// One unsigned condition: the low nibble pair as encoded in the `0x70`
/// block, and the rule that decides it from CF and ZF.
type UnsignedCondition = (u8, fn(bool, bool) -> bool);
const UNSIGNED_CONDITIONS: [UnsignedCondition; 4] = [
(0x72, |cf, _zf| cf), // JB, JC, JNAE
(0x73, |cf, _zf| !cf), // JAE, JNB, JNC
(0x76, |cf, zf| cf || zf), // JBE, JNA
(0x77, |cf, zf| !cf && !zf), // JA, JNBE
];
/// Build `<op> eax, ebx` (or `rax, rbx`) followed by the short or near form
/// of `condition`. The not-taken path writes 1 to `ECX` and halts, the
/// taken path writes 2. A near branch targets offset 140, which a `disp8`
/// cannot reach, so the two encodings are exercised separately.
fn unsigned_branch_program(op: [u8; 2], condition: u8, wide: bool, near: bool) -> Vec<u8> {
let mut code = Vec::new();
if wide {
code.push(0x48); // REX.W
}
code.extend_from_slice(&op); // cmp/sub eax, ebx
let jcc = code.len();
if near {
// The near form is `0F 8x`, where x is the low nibble of the
// short form's opcode.
code.extend_from_slice(&[0x0F, 0x80 | (condition & 0x0F), 0, 0, 0, 0]);
} else {
code.extend_from_slice(&[condition, 0]);
}
code.extend_from_slice(&[0xB9, 1, 0, 0, 0]); // mov ecx, 1
code.push(0xF4); // hlt
let target = if near { 140 } else { code.len() };
while code.len() < target {
code.push(0x90); // nop
}
code.extend_from_slice(&[0xB9, 2, 0, 0, 0]); // mov ecx, 2
code.push(0xF4); // hlt
let next = jcc + if near { 6 } else { 2 };
let displacement = target as i64 - next as i64;
if near {
code[jcc + 2..jcc + 6].copy_from_slice(&(displacement as i32).to_le_bytes());
} else {
code[jcc + 1] = displacement as i8 as u8;
}
code
}
/// Run one branch program and return `(ecx, cf, zf)`.
fn run_unsigned_branch(code: &[u8], left: u64, right: u64) -> (u64, bool, bool) {
let (mut engine, mut cpu, mut memory) = fixture(code);
cpu.set(Register::Rax, left);
cpu.set(Register::Rbx, right);
let result = engine.run(&mut cpu, &mut memory, 32);
assert_eq!(result.exit_reason, ExitReason::Halt);
// Either the two-instruction taken path or the two-instruction
// not-taken path runs after the compare and the branch.
assert_eq!(result.instructions_executed, 4);
// The compare, the branch and the halting move all run as translated
// ARM64, not through the shared interpreter.
assert_eq!(engine.metrics.interpreter_fallbacks, 0);
(cpu.get(Register::Rcx), cpu.flags.cf, cpu.flags.zf)
}
/// The four unsigned conditions, at both ends of the 32-bit and 64-bit
/// ranges, in the short and the near encoding. Expected flags and
/// outcomes come from the SDM rules above, not from the lowering.
#[test]
fn unsigned_branch_conditions_follow_the_borrow_at_every_boundary() {
const CMP: [u8; 2] = [0x39, 0xD8];
let cases: &[(bool, u64, u64)] = &[
// 32-bit: zero, one, equal operands, both ends of the range, and
// the pair where the sign bit flips but the unsigned order holds.
(false, 0, 0),
(false, 0, 1),
(false, 1, 0),
(false, 0xFFFF_FFFF, 0xFFFF_FFFF),
(false, 0xFFFF_FFFF, 0),
(false, 0, 0xFFFF_FFFF),
(false, 0x7FFF_FFFF, 0x8000_0000),
(false, 0x8000_0000, 0x7FFF_FFFF),
// The same boundaries at 64 bits, plus a subtraction that clears
// the sign bit without borrowing.
(true, 0, 0),
(true, 0, 1),
(true, 1, 0),
(true, u64::MAX, u64::MAX),
(true, u64::MAX, 0),
(true, 0, u64::MAX),
(true, 0x7FFF_FFFF_FFFF_FFFF, 0x8000_0000_0000_0000),
(true, 0x8000_0000_0000_0000, 0x7FFF_FFFF_FFFF_FFFF),
(true, 0x8000_0000_0000_0000, 1),
];
for &(wide, left, right) in cases {
let mask = if wide { u64::MAX } else { u64::from(u32::MAX) };
let (left, right) = (left & mask, right & mask);
// SDM: CF is the borrow out of the most significant bit, ZF is a
// zero result. Both follow from the operands alone.
let (cf, zf) = (left < right, left == right);
for &(condition, holds) in &UNSIGNED_CONDITIONS {
let taken = holds(cf, zf);
for &near in &[false, true] {
let code = unsigned_branch_program(CMP, condition, wide, near);
let (ecx, got_cf, got_zf) = run_unsigned_branch(&code, left, right);
let case = format!(
"{condition:#04x} {:#x} {:#x} {}",
left,
right,
if near { "near" } else { "short" }
);
assert_eq!(got_cf, cf, "{case}: CF");
assert_eq!(got_zf, zf, "{case}: ZF");
assert_eq!(ecx, if taken { 2 } else { 1 }, "{case}: branch outcome");
}
}
}
}
/// `SUB` is the other producer of the carry these conditions read, and the
/// one where the ARM64 carry is inverted: `0 - 1` borrows, while
/// `0x8000_0000_0000_0000 - 1` does not borrow even though it clears the
/// sign bit.
#[test]
fn subtract_borrow_into_and_out_of_the_high_bit_feeds_the_unsigned_branches() {
const SUB: [u8; 2] = [0x29, 0xD8];
let cases: &[(bool, u64, u64)] = &[
(false, 0, 1),
(false, 0x8000_0000, 1),
(true, 0, 1),
(true, 0x8000_0000_0000_0000, 1),
];
for &(wide, left, right) in cases {
let mask = if wide { u64::MAX } else { u64::from(u32::MAX) };
let (left, right) = (left & mask, right & mask);
let (cf, zf) = (left < right, left == right);
for &(condition, holds) in &UNSIGNED_CONDITIONS {
let taken = holds(cf, zf);
for &near in &[false, true] {
let code = unsigned_branch_program(SUB, condition, wide, near);
let (ecx, got_cf, got_zf) = run_unsigned_branch(&code, left, right);
let case = format!(
"{condition:#04x} {:#x} {:#x} {}",
left,
right,
if near { "near" } else { "short" }
);
assert_eq!(got_cf, cf, "{case}: CF");
assert_eq!(got_zf, zf, "{case}: ZF");
assert_eq!(ecx, if taken { 2 } else { 1 }, "{case}: branch outcome");
}
}
}
}
/// The carry these conditions read is produced in one translated block and
/// consumed in the next. A lowering that left it in the host's condition
/// flags would pass the single-block cases above and fail here.
#[test]
fn unsigned_branch_reads_flags_stored_by_a_previous_block() {
const CMP: [u8; 2] = [0x39, 0xD8];
let cases: &[(bool, u64, u64)] = &[
(false, 0, 0), // CF = 0, ZF = 1
(false, 0, 1), // CF = 1, ZF = 0
(false, 0xFFFF_FFFF, 0), // CF = 0, ZF = 0
(true, 0x8000_0000_0000_0000, 1), // CF = 0 although the sign bit clears
];
for &(wide, left, right) in cases {
let (cf, zf) = (left < right, left == right);
for &(condition, holds) in &UNSIGNED_CONDITIONS {
let taken = holds(cf, zf);
let code = unsigned_branch_program(CMP, condition, wide, false);
let (mut engine, mut cpu, mut memory) = fixture(&code);
cpu.set(Register::Rax, left);
cpu.set(Register::Rbx, right);
// One instruction per run: the compare is translated as a
// one-instruction block, so the branch is compiled separately
// and can only read the flags the first block stored.
let first = engine.run(&mut cpu, &mut memory, 1);
assert_eq!(first.exit_reason, ExitReason::StepLimitExceeded);
assert_eq!(cpu.rip, ENTRY + if wide { 3 } else { 2 });
assert_eq!((cpu.flags.cf, cpu.flags.zf), (cf, zf));
let second = engine.run(&mut cpu, &mut memory, 8);
assert_eq!(second.exit_reason, ExitReason::Halt);
assert_eq!(second.instructions_executed, 3);
assert_eq!(cpu.get(Register::Rcx), if taken { 2 } else { 1 });
assert_eq!(engine.metrics.interpreter_fallbacks, 0);
}
}
}
}
+232 -5
View File
@@ -419,6 +419,12 @@ impl GuestMemory {
/// byte must be mapped and every region must grant `required` (`None` bypasses
/// permission checks for the loader). The whole range is checked before any byte
/// is copied, so a failed access never partially reads or writes.
///
/// A failed access reports the lowest address it may not touch, which is the
/// start of the access only when its first byte fails. An access that begins in
/// a mapped page and runs into an unmapped or forbidden one therefore reports
/// the first byte of that page, as an x86 page fault reports the linear address
/// that could not be translated or accessed.
fn resolve(
&self,
address: u64,
@@ -452,7 +458,10 @@ impl GuestMemory {
Some(_) => region.permissions.execute,
};
if let (false, Some(required)) = (permitted, required) {
return Err(MemoryError::PermissionViolation { address, required });
return Err(MemoryError::PermissionViolation {
address: cursor,
required,
});
}
let take = (end.min(region_end) - cursor) as usize;
pieces.push((index, (cursor - region.base) as usize, take));
@@ -461,7 +470,7 @@ impl GuestMemory {
return Ok(pieces);
}
}
Err(MemoryError::UnmappedAddress(address))
Err(MemoryError::UnmappedAddress(cursor))
}
fn read_checked(
@@ -506,9 +515,20 @@ impl GuestMemory {
/// Read an instruction byte from guest memory, verifying execute permission.
pub fn fetch_instruction_byte(&self, address: u64) -> Result<u8, MemoryError> {
let mut buf = [0u8; 1];
self.read_checked(address, &mut buf, Some("execute"))?;
Ok(buf[0])
address.checked_add(1).ok_or(MemoryError::Overflow)?;
let region = self
.regions
.iter()
.find(|region| region.base + region.data.len() as u64 > address)
.filter(|region| region.base <= address)
.ok_or(MemoryError::UnmappedAddress(address))?;
if !region.permissions.execute {
return Err(MemoryError::PermissionViolation {
address,
required: "execute",
});
}
Ok(region.data[(address - region.base) as usize])
}
/// Read a 64-bit integer (little endian) from guest memory.
@@ -627,3 +647,210 @@ mod tests {
assert_eq!(memory.heap_allocation_size(PROCESS_HEAP, moved), Some(1));
}
}
#[cfg(test)]
mod instruction_fetch_tests {
use super::{MemoryPermissions as P, *};
fn denied(address: u64) -> Result<u8, MemoryError> {
Err(MemoryError::PermissionViolation {
address,
required: "execute",
})
}
fn missing(address: u64) -> Result<u8, MemoryError> {
Err(MemoryError::UnmappedAddress(address))
}
#[test]
fn fetch_reports_overflow_before_lookup() {
let m = GuestMemory::new();
for at in [0, 1, 0x1000, u64::MAX - 1] {
assert_eq!(m.fetch_instruction_byte(at), missing(at));
}
assert_eq!(
m.fetch_instruction_byte(u64::MAX),
Err(MemoryError::Overflow)
);
let mut m = GuestMemory::new();
m.map_region(u64::MAX, 0, P::NO_ACCESS).unwrap();
assert_eq!(
m.fetch_instruction_byte(u64::MAX),
Err(MemoryError::Overflow)
);
}
#[test]
fn fetch_checks_execute_permission_for_every_byte_value() {
let bytes: Vec<u8> = (0..=255).collect();
for flags in 0..8 {
let permission = P {
read: flags & 1 != 0,
write: flags & 2 != 0,
execute: flags & 4 != 0,
};
let mut m = GuestMemory::new();
m.map_region_with_data(0x1000, bytes.len(), permission, &bytes)
.unwrap();
for (offset, byte) in bytes.iter().enumerate() {
let at = 0x1000 + offset as u64;
assert_eq!(
m.fetch_instruction_byte(at),
if flags & 4 != 0 {
Ok(*byte)
} else {
denied(at)
},
"flags={flags}, at={at:x}"
);
}
}
}
#[test]
fn fetch_handles_sparse_and_out_of_order_mappings() {
let mut m = GuestMemory::new();
m.map_region_with_data(0x3000, 2, P::READ_EXECUTE, &[0xc1, 0xc2])
.unwrap();
m.map_region_with_data(0, 2, P::READ_EXECUTE, &[0x01, 0x02])
.unwrap();
m.map_region_with_data(0x2000, 1, P::READ_ONLY, &[0xb1])
.unwrap();
m.map_region_with_data(0x1000, 2, P::READ_EXECUTE, &[0xa1, 0xa2])
.unwrap();
for (at, byte) in [
(0, 1),
(1, 2),
(0x1000, 0xa1),
(0x1001, 0xa2),
(0x3000, 0xc1),
(0x3001, 0xc2),
] {
assert_eq!(m.fetch_instruction_byte(at), Ok(byte));
}
assert_eq!(m.fetch_instruction_byte(0x2000), denied(0x2000));
for at in [2, 0xfff, 0x1002, 0x2001, 0x2fff, 0x3002] {
assert_eq!(m.fetch_instruction_byte(at), missing(at));
}
}
#[test]
fn fetch_ignores_empty_mappings_at_shared_boundaries() {
for zero_first in [false, true] {
for execute in [false, true] {
let mut m = GuestMemory::new();
let permission = P {
read: false,
write: false,
execute,
};
if zero_first {
for _ in 0..7 {
m.map_region(0x1000, 0, P::READ_WRITE_EXECUTE).unwrap();
}
}
m.map_region_with_data(0x1000, 2, permission, &[0x34, 0x56])
.unwrap();
for _ in 0..7 {
m.map_region(0x1000, 0, P::NO_ACCESS).unwrap();
}
for _ in 0..7 {
m.map_region(0x1002, 0, P::READ_WRITE_EXECUTE).unwrap();
}
for (at, byte) in [(0x1000, 0x34), (0x1001, 0x56)] {
assert_eq!(
m.fetch_instruction_byte(at),
if execute { Ok(byte) } else { denied(at) }
);
}
assert_eq!(m.fetch_instruction_byte(0x1002), missing(0x1002));
}
}
let mut m = GuestMemory::new();
for at in [1, 1, 2, 0x1000] {
m.map_region(at, 0, P::READ_WRITE_EXECUTE).unwrap();
}
for at in [0, 1, 2, 3, 0x1000] {
assert_eq!(m.fetch_instruction_byte(at), missing(at));
}
}
#[test]
fn fetch_checks_adjacent_mapping_permissions() {
let mut m = GuestMemory::new();
m.map_region_with_data(0x1000, 1, P::READ_EXECUTE, &[0xa5])
.unwrap();
m.map_region_with_data(0x1001, 1, P::READ_WRITE, &[0x5a])
.unwrap();
m.map_region(0x1001, 0, P::READ_EXECUTE).unwrap();
m.map_region_with_data(0x1002, 1, P::READ_EXECUTE, &[0xc3])
.unwrap();
assert_eq!(m.fetch_instruction_byte(0x1000), Ok(0xa5));
assert_eq!(m.fetch_instruction_byte(0x1001), denied(0x1001));
assert_eq!(m.fetch_instruction_byte(0x1002), Ok(0xc3));
assert_eq!(m.fetch_instruction_byte(0x1003), missing(0x1003));
}
#[test]
fn fetch_handles_the_highest_region_end() {
let mut m = GuestMemory::new();
m.map_region_with_data(u64::MAX - 2, 2, P::READ_EXECUTE, &[0x12, 0x34])
.unwrap();
m.map_region(u64::MAX, 0, P::READ_EXECUTE).unwrap();
assert_eq!(
m.fetch_instruction_byte(u64::MAX - 3),
missing(u64::MAX - 3)
);
assert_eq!(m.fetch_instruction_byte(u64::MAX - 2), Ok(0x12));
assert_eq!(m.fetch_instruction_byte(u64::MAX - 1), Ok(0x34));
assert_eq!(
m.fetch_instruction_byte(u64::MAX),
Err(MemoryError::Overflow)
);
}
#[test]
fn fetch_observes_writes_clones_and_mapping_changes() {
let mut m = GuestMemory::new();
m.map_region_with_data(0x1000, 1, P::READ_WRITE_EXECUTE, &[0x11])
.unwrap();
let mut clone = m.clone();
m.write_u8(0x1000, 0x22).unwrap();
clone.write_u8(0x1000, 0x33).unwrap();
assert_eq!(m.fetch_instruction_byte(0x1000), Ok(0x22));
assert_eq!(clone.fetch_instruction_byte(0x1000), Ok(0x33));
let base = m
.map_virtual_allocation(0x4000, 1, P::READ_WRITE_EXECUTE)
.unwrap();
m.write_u8(base, 0x44).unwrap();
assert_eq!(m.fetch_instruction_byte(base), Ok(0x44));
assert!(m.release_virtual_allocation(base));
assert_eq!(m.fetch_instruction_byte(base), missing(base));
m.map_region_with_data(base, 1, P::READ_ONLY, &[0x55])
.unwrap();
assert_eq!(m.fetch_instruction_byte(base), denied(base));
assert_eq!(clone.fetch_instruction_byte(base), missing(base));
}
#[test]
fn fetch_keeps_first_mapping_priority_after_empty_heap_growth() {
// Existing private allocation methods can grow a zero allocation onto an
// earlier mapping at its base. The fetch-only patch must preserve the
// original mapping's priority even for this already-representable state.
let mut m = GuestMemory::new();
m.map_region_with_data(0x1000, 1, P::READ_EXECUTE, &[0x90])
.unwrap();
const BASE: u64 = 0x0000_0003_0000_0000;
m.map_region_with_data(BASE, 4, P::READ_EXECUTE, &[0x11, 0x22, 0x33, 0x44])
.unwrap();
let empty = m.map_heap_allocation(PROCESS_HEAP, 0).unwrap();
assert_eq!(empty, BASE);
assert_eq!(
m.resize_heap_allocation(PROCESS_HEAP, empty, 2, true),
Ok(BASE)
);
assert_eq!(m.fetch_instruction_byte(BASE), Ok(0x11));
assert_eq!(m.fetch_instruction_byte(BASE + 1), Ok(0x22));
assert_eq!(m.fetch_instruction_byte(BASE + 3), Ok(0x44));
}
}
+10
View File
@@ -35,6 +35,7 @@ pub struct Control {
pub rounding: Rounding,
pub denormals_are_zero: bool,
pub flush_to_zero: bool,
pub overflow_masked: bool,
pub underflow_masked: bool,
}
@@ -49,6 +50,7 @@ impl Control {
},
denormals_are_zero: mxcsr & 1 << 6 != 0,
flush_to_zero: mxcsr & 1 << 15 != 0,
overflow_masked: mxcsr & 1 << 10 != 0,
underflow_masked: mxcsr & 1 << 11 != 0,
}
}
@@ -263,6 +265,14 @@ fn round(
flags |= PRECISION;
}
if leading > format.bias() {
if !control.overflow_masked {
// No result is delivered. Precision is reported only if rounding
// with an unbounded exponent was inexact.
return Outcome {
bits: 0,
flags: OVERFLOW | if inexact { PRECISION } else { 0 },
};
}
let to_infinity = match control.rounding {
Rounding::Nearest => true,
Rounding::Down => sign,
+446 -26
View File
@@ -11,11 +11,39 @@ use crate::memory::{GuestMemory, MemoryError, MemoryPermissions};
use crate::pe::ParsedPe;
use std::fmt;
/// Most callbacks one TLS directory may list.
pub const MAX_TLS_CALLBACKS: usize = 64;
/// Bytes below the stack top that a callback is entered with: the return
/// address and the 32-byte home space the Win64 convention gives every callee.
const CALLBACK_FRAME: u64 = 40;
/// Errors arising during TLS setup or callback invocation.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum TlsError {
DirectoryOutOfBounds { rva: u32 },
InvalidTemplateRange { start: u64, end: u64 },
DirectoryOutOfBounds {
rva: u32,
},
InvalidTemplateRange {
start: u64,
end: u64,
},
/// `AddressOfCallbacks` is not zero and not inside a section of the image.
CallbackArrayOutOfBounds {
address: u64,
},
/// The callback array leaves its section before a null entry.
CallbackArrayUnterminated {
address: u64,
},
/// The callback array lists more than [`MAX_TLS_CALLBACKS`] entries.
TooManyCallbacks {
limit: usize,
},
/// The stack cannot hold a callback's entry frame or is not 16-byte aligned.
InvalidCallbackStack {
stack_top: u64,
},
CallbackExecutionFault(ExitReason),
Memory(MemoryError),
}
@@ -32,6 +60,27 @@ impl fmt::Display for TlsError {
"invalid TLS template range: 0x{start:016x}..0x{end:016x}"
)
}
Self::CallbackArrayOutOfBounds { address } => {
write!(
f,
"TLS callback array at 0x{address:016x} is outside the image"
)
}
Self::CallbackArrayUnterminated { address } => {
write!(
f,
"TLS callback array at 0x{address:016x} has no null entry in its section"
)
}
Self::TooManyCallbacks { limit } => {
write!(f, "TLS callback array lists more than {limit} callbacks")
}
Self::InvalidCallbackStack { stack_top } => {
write!(
f,
"stack top 0x{stack_top:016x} cannot hold an aligned TLS callback frame"
)
}
Self::CallbackExecutionFault(e) => {
write!(f, "fault during TLS callback execution: {e}")
}
@@ -78,7 +127,7 @@ pub fn parse_tls_directory(bytes: &[u8], pe: &ParsedPe) -> Result<Option<TlsDire
) as usize;
// TLS directory is directory index 9 (offset 112 + 9 * 8 = 184 in Optional Header)
if size_of_opt < 192 || bytes.len() < opt_offset + 188 {
if size_of_opt < 192 || bytes.len() < opt_offset + 192 {
return Ok(None);
}
@@ -114,24 +163,7 @@ pub fn parse_tls_directory(bytes: &[u8], pe: &ParsedPe) -> Result<Option<TlsDire
u32::from_le_bytes(bytes[tls_off + 32..tls_off + 36].try_into().unwrap());
let characteristics = u32::from_le_bytes(bytes[tls_off + 36..tls_off + 40].try_into().unwrap());
let mut callbacks = Vec::new();
if callbacks_address >= pe.image_base {
let cb_rva = (callbacks_address - pe.image_base) as u32;
if let Some(cb_off) = pe.rva_to_file_offset(cb_rva) {
let mut curr = cb_off;
while curr + 8 <= bytes.len() {
let target = u64::from_le_bytes(bytes[curr..curr + 8].try_into().unwrap());
if target == 0 {
break;
}
callbacks.push(target);
curr += 8;
if callbacks.len() >= 64 {
break;
}
}
}
}
let callbacks = read_callbacks(bytes, pe, callbacks_address)?;
Ok(Some(TlsDirectory {
raw_data_start_va,
@@ -144,9 +176,74 @@ pub fn parse_tls_directory(bytes: &[u8], pe: &ParsedPe) -> Result<Option<TlsDire
}))
}
/// Read the null-terminated callback array that `address` names.
///
/// A null `address` means the image has no callbacks. Any other value must be a
/// virtual address inside one section, and the array must reach its null entry
/// inside that section. Bytes past the section's file data, up to its virtual
/// size, are zero in the loaded image and are read as zero here.
fn read_callbacks(bytes: &[u8], pe: &ParsedPe, address: u64) -> Result<Vec<u64>, TlsError> {
if address == 0 {
return Ok(Vec::new());
}
let (section, start) = address
.checked_sub(pe.image_base)
.and_then(|rva| u32::try_from(rva).ok())
.and_then(|rva| {
pe.sections.iter().find_map(|section| {
let offset = rva.checked_sub(section.virtual_address)?;
let extent = section.virtual_size.max(section.raw_data_size);
(offset < extent).then_some((section, u64::from(offset)))
})
})
.ok_or(TlsError::CallbackArrayOutOfBounds { address })?;
let extent = u64::from(section.virtual_size.max(section.raw_data_size));
let byte_at = |offset: u64| -> Option<u8> {
if offset >= extent {
None
} else if offset >= u64::from(section.raw_data_size) {
Some(0)
} else {
let file = u64::from(section.raw_data_ptr) + offset;
bytes.get(usize::try_from(file).ok()?).copied()
}
};
let mut callbacks = Vec::new();
let mut offset = start;
loop {
let mut entry = [0u8; 8];
for byte in &mut entry {
*byte = byte_at(offset).ok_or(TlsError::CallbackArrayUnterminated { address })?;
offset += 1;
}
let target = u64::from_le_bytes(entry);
if target == 0 {
return Ok(callbacks);
}
if callbacks.len() == MAX_TLS_CALLBACKS {
return Err(TlsError::TooManyCallbacks {
limit: MAX_TLS_CALLBACKS,
});
}
callbacks.push(target);
}
}
/// Bytes reserved at `thread_tls_base` for the thread's TLS pointer array.
const TLS_ARRAY_SIZE: usize = 0x1000;
/// Set up TLS runtime state in guest memory:
/// 1. Assign TLS index (e.g. 0) at `index_address`.
/// 2. Allocate and initialize per-thread TLS storage from the template.
/// 1. Assign TLS index 0 at `index_address`.
/// 2. Map the thread's TLS pointer array at `thread_tls_base`.
/// 3. Map the thread's data block one page above it, initialized from the
/// template and zero fill, and store its address in the array slot of the
/// index.
///
/// `thread_tls_base` is the value the thread environment block holds as its
/// TLS pointer. Compiled code loads that pointer, indexes it by the module's
/// TLS index to find the data block, and then adds a variable's offset, so the
/// array and the data are separate regions.
pub fn setup_tls(
tls: &TlsDirectory,
loaded_base: u64,
@@ -187,15 +284,25 @@ pub fn setup_tls(
memory.read_bytes(actual_start, &mut template_data)?;
}
// Allocate per-thread TLS block
// Allocate the pointer array and the per-thread TLS block.
let block_base = thread_tls_base
.checked_add(TLS_ARRAY_SIZE as u64)
.ok_or(MemoryError::Overflow)?;
let page_size = 4096;
let map_size = (total_size + page_size - 1) & !(page_size - 1);
memory.map_region_with_data(
memory.map_region(
thread_tls_base,
TLS_ARRAY_SIZE,
MemoryPermissions::READ_WRITE,
)?;
memory.map_region_with_data(
block_base,
map_size,
MemoryPermissions::READ_WRITE,
&template_data,
)?;
// Slot 0 belongs to the index assigned above.
memory.write_u64(thread_tls_base, block_base)?;
}
Ok(())
@@ -206,6 +313,11 @@ pub fn setup_tls(
/// - RCX = DllHandle (loaded_base)
/// - RDX = Reason (DLL_PROCESS_ATTACH = 1)
/// - R8 = Reserved (0)
///
/// Each callback is entered as after a CALL from a 16-byte aligned stack: RSP
/// is `stack_top - 40`, holding the return address below 32 bytes of home
/// space. A `stack_top` that is not 16-byte aligned or cannot hold that frame
/// is rejected before any callback runs.
pub fn execute_tls_callbacks(
callbacks: &[u64],
loaded_base: u64,
@@ -215,6 +327,12 @@ pub fn execute_tls_callbacks(
memory: &mut GuestMemory,
dbt: &mut DbtEngine,
) -> Result<usize, TlsError> {
if callbacks.is_empty() {
return Ok(0);
}
if stack_top < CALLBACK_FRAME || !stack_top.is_multiple_of(16) {
return Err(TlsError::InvalidCallbackStack { stack_top });
}
let delta = (loaded_base as i128) - (preferred_base as i128);
let mut executed_count = 0;
@@ -224,7 +342,7 @@ pub fn execute_tls_callbacks(
// Reset CPU state for callback execution adhering to Win64 ABI
cpu.rip = actual_cb_va;
// Stack pointer aligned with 32-byte shadow space + return address
let rsp = stack_top - 40;
let rsp = stack_top - CALLBACK_FRAME;
cpu.set(Register::Rsp, rsp);
// Write synthetic magic return address (0xFFFF_FFFF_FFFF_0000) into [RSP]
let magic_ret = 0xFFFF_FFFF_FFFF_0000u64;
@@ -261,3 +379,305 @@ pub fn execute_tls_callbacks(
Ok(executed_count)
}
#[cfg(test)]
mod tests {
//! Expectations come from Microsoft's public PE Format page (the TLS
//! directory: `AddressOfCallbacks` is a virtual address of a null-terminated
//! array, and a callback is `void cb(PVOID DllHandle, DWORD Reason, PVOID
//! Reserved)`) and its x64 calling convention page (the stack is 16-byte
//! aligned before a call, the caller provides 32 bytes of home space, and
//! the first three integer arguments are in RCX, RDX and R8). The headers
//! and code bytes below are original. Nothing here ran on Windows.
use super::*;
use crate::pe::PeSection;
const IMAGE_BASE: u64 = 0x1_4000_0000;
const SECTION_RVA: u32 = 0x1000;
const SECTION_FILE: usize = 0x400;
const SECTION_SIZE: u32 = 0x400;
/// Offset of the optional header: `e_lfanew` (0x80), signature, COFF header.
const OPTIONAL_HEADER: usize = 0x80 + 24;
fn parsed(virtual_size: u32) -> ParsedPe {
ParsedPe {
machine: 0x8664,
number_of_sections: 1,
time_date_stamp: 0,
image_base: IMAGE_BASE,
section_alignment: 0x1000,
file_alignment: 0x200,
size_of_image: 0x3000,
size_of_headers: 0x400,
entry_point_rva: 0,
sections: vec![PeSection {
name: ".rdata".into(),
virtual_address: SECTION_RVA,
virtual_size,
raw_data_ptr: SECTION_FILE as u32,
raw_data_size: SECTION_SIZE,
characteristics: crate::pe::IMAGE_SCN_MEM_READ,
permissions: MemoryPermissions::READ_ONLY,
}],
}
}
/// A file with one section holding a TLS directory at its start and the
/// callback `entries` at `array_rva`. The directory names `callbacks_address`.
/// Every byte after the section's file data is 0xCC.
fn file(callbacks_address: u64, array_rva: u32, entries: &[u64]) -> Vec<u8> {
let section_end = SECTION_FILE + SECTION_SIZE as usize;
let mut bytes = vec![0u8; section_end];
bytes.resize(section_end + 0x200, 0xCC);
bytes[0x3C..0x40].copy_from_slice(&0x80u32.to_le_bytes());
// SizeOfOptionalHeader: a PE32+ optional header with 16 data directories.
bytes[0x94..0x96].copy_from_slice(&240u16.to_le_bytes());
// Data directory 9 (TLS): RVA and size.
let entry = OPTIONAL_HEADER + 112 + 9 * 8;
bytes[entry..entry + 4].copy_from_slice(&SECTION_RVA.to_le_bytes());
bytes[entry + 4..entry + 8].copy_from_slice(&40u32.to_le_bytes());
// IMAGE_TLS_DIRECTORY64.AddressOfCallBacks is its fourth 8-byte field.
bytes[SECTION_FILE + 24..SECTION_FILE + 32]
.copy_from_slice(&callbacks_address.to_le_bytes());
let mut at = SECTION_FILE + (array_rva - SECTION_RVA) as usize;
for entry in entries {
bytes[at..at + 8].copy_from_slice(&entry.to_le_bytes());
at += 8;
}
bytes
}
fn callbacks_of(bytes: &[u8], pe: &ParsedPe) -> Result<Vec<u64>, TlsError> {
parse_tls_directory(bytes, pe).map(|tls| tls.expect("a TLS directory").callbacks)
}
const ARRAY_RVA: u32 = 0x1100;
const ARRAY: u64 = IMAGE_BASE + ARRAY_RVA as u64;
const FIRST: u64 = IMAGE_BASE + 0x2000;
const SECOND: u64 = IMAGE_BASE + 0x2010;
#[test]
fn callbacks_are_read_in_order_up_to_the_null_entry() {
let bytes = file(ARRAY, ARRAY_RVA, &[FIRST, SECOND, 0, IMAGE_BASE + 0x2020]);
assert_eq!(
callbacks_of(&bytes, &parsed(SECTION_SIZE)),
Ok(vec![FIRST, SECOND])
);
}
#[test]
fn a_null_callbacks_address_means_no_callbacks() {
let bytes = file(0, ARRAY_RVA, &[FIRST, 0]);
assert_eq!(callbacks_of(&bytes, &parsed(SECTION_SIZE)), Ok(vec![]));
}
#[test]
fn a_callback_array_outside_the_image_is_rejected() {
for address in [8, IMAGE_BASE - 8, IMAGE_BASE + 0x800, IMAGE_BASE + 0x5000] {
let bytes = file(address, ARRAY_RVA, &[FIRST, 0]);
assert_eq!(
callbacks_of(&bytes, &parsed(SECTION_SIZE)),
Err(TlsError::CallbackArrayOutOfBounds { address }),
"{address:#x}"
);
}
}
#[test]
fn a_callback_array_address_is_not_truncated_to_32_bits() {
// The low 32 bits of the offset name the real array.
let address = ARRAY + (1 << 32);
let bytes = file(address, ARRAY_RVA, &[FIRST, 0]);
assert_eq!(
callbacks_of(&bytes, &parsed(SECTION_SIZE)),
Err(TlsError::CallbackArrayOutOfBounds { address })
);
}
#[test]
fn a_callback_array_must_end_inside_its_section() {
// Two entries fill the last 16 bytes of the section; the file goes on.
let rva = SECTION_RVA + SECTION_SIZE - 16;
let address = IMAGE_BASE + u64::from(rva);
let bytes = file(address, rva, &[FIRST, SECOND]);
assert_eq!(
callbacks_of(&bytes, &parsed(SECTION_SIZE)),
Err(TlsError::CallbackArrayUnterminated { address })
);
}
#[test]
fn zero_fill_after_the_section_file_data_ends_the_array() {
// The section is larger in memory than in the file, so the bytes after
// its file data are zero when loaded, whatever follows in the file.
let rva = SECTION_RVA + SECTION_SIZE - 16;
let address = IMAGE_BASE + u64::from(rva);
let bytes = file(address, rva, &[FIRST, SECOND]);
assert_eq!(
callbacks_of(&bytes, &parsed(SECTION_SIZE + 0x100)),
Ok(vec![FIRST, SECOND])
);
}
#[test]
fn a_callback_array_over_the_limit_is_rejected() {
let entries: Vec<u64> = (0..65).map(|index| FIRST + index * 16).collect();
let mut at_limit = entries[..MAX_TLS_CALLBACKS].to_vec();
at_limit.push(0);
let bytes = file(ARRAY, ARRAY_RVA, &at_limit);
assert_eq!(
callbacks_of(&bytes, &parsed(SECTION_SIZE)),
Ok(entries[..64].to_vec())
);
let mut over = entries.clone();
over.push(0);
let bytes = file(ARRAY, ARRAY_RVA, &over);
assert_eq!(
callbacks_of(&bytes, &parsed(SECTION_SIZE)),
Err(TlsError::TooManyCallbacks { limit: 64 })
);
}
#[test]
fn a_file_cut_inside_the_tls_data_directory_has_no_tls_directory() {
let bytes = file(ARRAY, ARRAY_RVA, &[FIRST, 0]);
let entry = OPTIONAL_HEADER + 112 + 9 * 8;
for length in entry..entry + 8 {
let directory = parse_tls_directory(&bytes[..length], &parsed(SECTION_SIZE));
assert!(matches!(directory, Ok(None)), "length {length:#x}");
}
}
const CODE: u64 = 0x40_0000;
const STACK_TOP: u64 = 0x80_0000;
const SENTINEL: u64 = 0xFFFF_FFFF_FFFF_0000;
/// Code at `CODE`, a 4 KiB stack below `STACK_TOP` and a fresh translator.
fn guest(code: &[u8]) -> (CpuState, GuestMemory, DbtEngine) {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(CODE, 0x1000, MemoryPermissions::READ_EXECUTE, code)
.unwrap();
memory
.map_region(STACK_TOP - 0x1000, 0x1000, MemoryPermissions::READ_WRITE)
.unwrap();
(
CpuState::new(0, 0),
memory,
DbtEngine::new(64 * 1024).unwrap(),
)
}
/// Two callbacks 16 bytes apart. Each shifts RAX left by four bits and sets
/// its own number in the low bits, so RAX records the order they ran in.
const TAGGING: [u8; 25] = [
0x48, 0xC1, 0xE0, 0x04, // shl rax, 4
0x48, 0x83, 0xC8, 0x01, // or rax, 1
0xC3, // ret
0, 0, 0, 0, 0, 0, 0, // padding
0x48, 0xC1, 0xE0, 0x04, // shl rax, 4
0x48, 0x83, 0xC8, 0x02, // or rax, 2
0xC3, // ret
];
#[test]
fn a_callback_is_entered_with_the_win64_arguments_and_frame() {
let code = [0x48, 0x89, 0xE0, 0xC3]; // mov rax, rsp; ret
let (mut cpu, mut memory, mut dbt) = guest(&code);
// Loaded 64 KiB above the preferred base: the listed address is rebased.
let loaded = IMAGE_BASE + 0x1_0000;
let listed = [CODE - 0x1_0000];
let ran = execute_tls_callbacks(
&listed,
loaded,
IMAGE_BASE,
STACK_TOP,
&mut cpu,
&mut memory,
&mut dbt,
);
assert_eq!(ran, Ok(1));
let entry_rsp = cpu.get(Register::Rax);
assert_eq!(entry_rsp, STACK_TOP - 40);
// A callee is entered 8 bytes off 16-byte alignment, as after a CALL.
assert_eq!(entry_rsp % 16, 8);
assert_eq!(memory.read_u64(entry_rsp), Ok(SENTINEL));
assert_eq!(cpu.get(Register::Rcx), loaded);
assert_eq!(cpu.get(Register::Rdx), 1); // DLL_PROCESS_ATTACH
assert_eq!(cpu.get(Register::R8), 0);
// RET popped the return address and nothing else.
assert_eq!(cpu.get(Register::Rsp), entry_rsp + 8);
assert_eq!(cpu.rip, SENTINEL);
}
#[test]
fn callbacks_run_in_array_order() {
for (order, recorded) in [([CODE, CODE + 16], 0x12), ([CODE + 16, CODE], 0x21)] {
let (mut cpu, mut memory, mut dbt) = guest(&TAGGING);
let ran = execute_tls_callbacks(
&order,
IMAGE_BASE,
IMAGE_BASE,
STACK_TOP,
&mut cpu,
&mut memory,
&mut dbt,
);
assert_eq!(ran, Ok(2));
assert_eq!(cpu.get(Register::Rax), recorded);
}
}
#[test]
fn a_callback_over_the_instruction_budget_stops_the_sequence() {
let mut code = TAGGING.to_vec();
code.resize(32, 0);
code.extend([0xEB, 0xFE]); // jmp to itself
let (mut cpu, mut memory, mut dbt) = guest(&code);
let ran = execute_tls_callbacks(
&[CODE, CODE + 32, CODE + 16],
IMAGE_BASE,
IMAGE_BASE,
STACK_TOP,
&mut cpu,
&mut memory,
&mut dbt,
);
assert_eq!(
ran,
Err(TlsError::CallbackExecutionFault(
ExitReason::StepLimitExceeded
))
);
// The first callback ran; the one after the endless one did not.
assert_eq!(cpu.get(Register::Rax), 0x1);
}
#[test]
fn an_unusable_callback_stack_is_rejected_before_anything_runs() {
for stack_top in [0, 32, STACK_TOP - 8, STACK_TOP - 1] {
let (mut cpu, mut memory, mut dbt) = guest(&TAGGING);
let ran = execute_tls_callbacks(
&[CODE],
IMAGE_BASE,
IMAGE_BASE,
stack_top,
&mut cpu,
&mut memory,
&mut dbt,
);
assert_eq!(
ran,
Err(TlsError::InvalidCallbackStack { stack_top }),
"{stack_top:#x}"
);
assert_eq!(cpu, CpuState::new(0, 0));
assert_eq!(memory.read_u64(STACK_TOP - 48), Ok(0));
// No callback, no frame: the stack is not looked at.
let none = execute_tls_callbacks(&[], 0, 0, stack_top, &mut cpu, &mut memory, &mut dbt);
assert_eq!(none, Ok(0));
}
}
}
+16 -5
View File
@@ -363,9 +363,24 @@ pub fn decode<E>(
GROUPS[usize::from(index)][usize::from((modrm >> 3) & 7)]
}
};
let form = FORMS
let mut form = FORMS
.get(usize::from(form_index))
.ok_or(DecodeError::Unsupported(opcode))?;
let mut form_index = form_index;
if form.no_rex_b && rex_b != 0 {
// 90 is NOP only without REX.B. With it the byte exchanges r8 with the
// accumulator, as the first register of the 91..97 row would (Intel
// SDM Vol. 2B, "NOP" and "XCHG").
match ONE_BYTE[slot + 1] {
Entry::Form(index)
if !two_byte && !rep && FORMS[usize::from(index)].encoding == Encoding::OpReg =>
{
form_index = index;
form = &FORMS[usize::from(index)];
}
_ => return Err(DecodeError::Unsupported(opcode)),
}
}
if form.has_modrm && matches!(entry, Entry::Form(_)) {
modrm = cursor.u8()?;
}
@@ -386,10 +401,6 @@ pub fn decode<E>(
if operand_size && !takes_operand_size && !overridden {
return Err(DecodeError::Unsupported(0x66));
}
if form.no_rex_b && rex_b != 0 {
return Err(DecodeError::Unsupported(opcode));
}
let rm_size = if form.source != 0 { form.source } else { size };
let register = |field: u8, extension: u8, width: u8| {
if width == 1 && rex == 0 && field >= 4 {
+14
View File
@@ -373,6 +373,8 @@ pub fn execute(
Encoding::OpRegImm => write_reg(cpu, insn.reg, size, insn.imm),
_ => write_rm(cpu, memory, insn, insn.imm & mask(size))?,
},
// A non-temporal store is an ordinary store: there is no cache to bypass.
Op::Movnti => write_rm(cpu, memory, insn, read_reg(cpu, insn.reg, size))?,
Op::Movzx => {
let value = read_rm(cpu, memory, insn)?;
write_reg(cpu, insn.reg, size, value);
@@ -386,6 +388,14 @@ pub fn execute(
write_reg(cpu, insn.reg, size, offset(cpu, &operand));
}
}
Op::Xchg if insn.encoding == Encoding::OpReg => {
// The accumulator with the register in the opcode, never itself:
// 90 without REX.B is NOP.
let rax = accumulator(RAX);
let (a, b) = (read_reg(cpu, rax, size), read_reg(cpu, insn.reg, size));
write_reg(cpu, rax, size, b);
write_reg(cpu, insn.reg, size, a);
}
Op::Xchg => {
let (a, b) = operands(cpu, memory, insn)?;
write_rm(cpu, memory, insn, b)?;
@@ -595,6 +605,10 @@ pub fn execute(
cpu.gpr[RSP] = sp.wrapping_add(8).wrapping_add(insn.imm);
}
Op::Nop => {}
// Every load and store of an instruction completes before the next
// instruction starts, on one host thread, so guest accesses are already
// totally ordered and a fence has nothing further to enforce.
Op::Lfence | Op::Mfence | Op::Sfence => {}
Op::Cpuid => {
// The leaf is EAX and the subleaf ECX. Each result is a 32-bit
// register write, so the upper halves are cleared.
+172 -125
View File
@@ -78,6 +78,7 @@ pub enum Op {
Movdqa,
Movdqu,
Movntdq,
Movnti,
Movntps,
Movss,
Movsd,
@@ -155,6 +156,9 @@ pub enum Op {
Pinsrw,
Pextrw,
Ldmxcsr,
Lfence,
Mfence,
Sfence,
Stmxcsr,
Sqrtps,
Sqrtpd,
@@ -211,7 +215,7 @@ pub enum Op {
}
impl Op {
pub const ALL: &[Op] = &[Op::Add, Op::Or, Op::Adc, Op::Sbb, Op::And, Op::Sub, Op::Xor, Op::Cmp, Op::Test, Op::Inc, Op::Dec, Op::Neg, Op::Not, Op::Mov, Op::Movzx, Op::Movsx, Op::Movsxd, Op::Lea, Op::Xchg, Op::Xadd, Op::Cmpxchg, Op::Bswap, Op::Cwde, Op::Cdq, Op::Rol, Op::Ror, Op::Rcl, Op::Rcr, Op::Shl, Op::Shr, Op::Sar, Op::Mul, Op::Imul, Op::Imul2, Op::Div, Op::Idiv, Op::Cmov, Op::Setcc, Op::Bt, Op::Bts, Op::Btr, Op::Btc, Op::Bsf, Op::Bsr, Op::Popcnt, Op::Tzcnt, Op::Lzcnt, Op::Push, Op::Pop, Op::Leave, Op::Call, Op::Jmp, Op::Jcc, Op::Ret, Op::Nop, Op::Hlt, Op::Syscall, Op::Clc, Op::Stc, Op::Cmc, Op::Cpuid, Op::Cld, Op::Std, Op::Movs, Op::Stos, Op::Movaps, Op::Movups, Op::Movdqa, Op::Movdqu, Op::Movntdq, Op::Movntps, Op::Movss, Op::Movsd, Op::Movq, Op::Movd, Op::Movlps, Op::Movhps, Op::Movmskps, Op::Movmskpd, Op::Pmovmskb, Op::Pand, Op::Pandn, Op::Por, Op::Pxor, Op::Punpcklbw, Op::Punpcklwd, Op::Punpckldq, Op::Packsswb, Op::Pcmpgtb, Op::Pcmpgtw, Op::Pcmpgtd, Op::Packuswb, Op::Punpckhbw, Op::Punpckhwd, Op::Punpckhdq, Op::Packssdw, Op::Punpcklqdq, Op::Punpckhqdq, Op::Pcmpeqb, Op::Pcmpeqw, Op::Pcmpeqd, Op::Paddq, Op::Pmullw, Op::Psubusb, Op::Psubusw, Op::Pminub, Op::Paddusb, Op::Paddusw, Op::Pmaxub, Op::Pavgb, Op::Pavgw, Op::Pmulhuw, Op::Pmulhw, Op::Psubsb, Op::Psubsw, Op::Pminsw, Op::Paddsb, Op::Paddsw, Op::Pmaxsw, Op::Pmuludq, Op::Pmaddwd, Op::Psadbw, Op::Psubb, Op::Psubw, Op::Psubd, Op::Psubq, Op::Paddb, Op::Paddw, Op::Paddd, Op::Psrlw, Op::Psraw, Op::Psllw, Op::Psrld, Op::Psrad, Op::Pslld, Op::Psrlq, Op::Psllq, Op::Psrldq, Op::Pslldq, Op::Pshufd, Op::Pshufhw, Op::Pshuflw, Op::Shufps, Op::Shufpd, Op::Pinsrw, Op::Pextrw, Op::Ldmxcsr, Op::Stmxcsr, Op::Sqrtps, Op::Sqrtpd, Op::Sqrtss, Op::Sqrtsd, Op::Addps, Op::Addpd, Op::Addss, Op::Addsd, Op::Mulps, Op::Mulpd, Op::Mulss, Op::Mulsd, Op::Subps, Op::Subpd, Op::Subss, Op::Subsd, Op::Minps, Op::Minpd, Op::Minss, Op::Minsd, Op::Divps, Op::Divpd, Op::Divss, Op::Divsd, Op::Maxps, Op::Maxpd, Op::Maxss, Op::Maxsd, Op::Cmpps, Op::Cmppd, Op::Cmpss, Op::Cmpsd, Op::Ucomiss, Op::Comiss, Op::Ucomisd, Op::Comisd, Op::Cvtps2pd, Op::Cvtpd2ps, Op::Cvtss2sd, Op::Cvtsd2ss, Op::Cvtdq2ps, Op::Cvtps2dq, Op::Cvttps2dq, Op::Cvttpd2dq, Op::Cvtdq2pd, Op::Cvtpd2dq, Op::Cvtsi2ss, Op::Cvttss2si, Op::Cvtss2si, Op::Cvtsi2sd, Op::Cvttsd2si, Op::Cvtsd2si];
pub const ALL: &[Op] = &[Op::Add, Op::Or, Op::Adc, Op::Sbb, Op::And, Op::Sub, Op::Xor, Op::Cmp, Op::Test, Op::Inc, Op::Dec, Op::Neg, Op::Not, Op::Mov, Op::Movzx, Op::Movsx, Op::Movsxd, Op::Lea, Op::Xchg, Op::Xadd, Op::Cmpxchg, Op::Bswap, Op::Cwde, Op::Cdq, Op::Rol, Op::Ror, Op::Rcl, Op::Rcr, Op::Shl, Op::Shr, Op::Sar, Op::Mul, Op::Imul, Op::Imul2, Op::Div, Op::Idiv, Op::Cmov, Op::Setcc, Op::Bt, Op::Bts, Op::Btr, Op::Btc, Op::Bsf, Op::Bsr, Op::Popcnt, Op::Tzcnt, Op::Lzcnt, Op::Push, Op::Pop, Op::Leave, Op::Call, Op::Jmp, Op::Jcc, Op::Ret, Op::Nop, Op::Hlt, Op::Syscall, Op::Clc, Op::Stc, Op::Cmc, Op::Cpuid, Op::Cld, Op::Std, Op::Movs, Op::Stos, Op::Movaps, Op::Movups, Op::Movdqa, Op::Movdqu, Op::Movntdq, Op::Movnti, Op::Movntps, Op::Movss, Op::Movsd, Op::Movq, Op::Movd, Op::Movlps, Op::Movhps, Op::Movmskps, Op::Movmskpd, Op::Pmovmskb, Op::Pand, Op::Pandn, Op::Por, Op::Pxor, Op::Punpcklbw, Op::Punpcklwd, Op::Punpckldq, Op::Packsswb, Op::Pcmpgtb, Op::Pcmpgtw, Op::Pcmpgtd, Op::Packuswb, Op::Punpckhbw, Op::Punpckhwd, Op::Punpckhdq, Op::Packssdw, Op::Punpcklqdq, Op::Punpckhqdq, Op::Pcmpeqb, Op::Pcmpeqw, Op::Pcmpeqd, Op::Paddq, Op::Pmullw, Op::Psubusb, Op::Psubusw, Op::Pminub, Op::Paddusb, Op::Paddusw, Op::Pmaxub, Op::Pavgb, Op::Pavgw, Op::Pmulhuw, Op::Pmulhw, Op::Psubsb, Op::Psubsw, Op::Pminsw, Op::Paddsb, Op::Paddsw, Op::Pmaxsw, Op::Pmuludq, Op::Pmaddwd, Op::Psadbw, Op::Psubb, Op::Psubw, Op::Psubd, Op::Psubq, Op::Paddb, Op::Paddw, Op::Paddd, Op::Psrlw, Op::Psraw, Op::Psllw, Op::Psrld, Op::Psrad, Op::Pslld, Op::Psrlq, Op::Psllq, Op::Psrldq, Op::Pslldq, Op::Pshufd, Op::Pshufhw, Op::Pshuflw, Op::Shufps, Op::Shufpd, Op::Pinsrw, Op::Pextrw, Op::Ldmxcsr, Op::Lfence, Op::Mfence, Op::Sfence, Op::Stmxcsr, Op::Sqrtps, Op::Sqrtpd, Op::Sqrtss, Op::Sqrtsd, Op::Addps, Op::Addpd, Op::Addss, Op::Addsd, Op::Mulps, Op::Mulpd, Op::Mulss, Op::Mulsd, Op::Subps, Op::Subpd, Op::Subss, Op::Subsd, Op::Minps, Op::Minpd, Op::Minss, Op::Minsd, Op::Divps, Op::Divpd, Op::Divss, Op::Divsd, Op::Maxps, Op::Maxpd, Op::Maxss, Op::Maxsd, Op::Cmpps, Op::Cmppd, Op::Cmpss, Op::Cmpsd, Op::Ucomiss, Op::Comiss, Op::Ucomisd, Op::Comisd, Op::Cvtps2pd, Op::Cvtpd2ps, Op::Cvtss2sd, Op::Cvtsd2ss, Op::Cvtdq2ps, Op::Cvtps2dq, Op::Cvttps2dq, Op::Cvttpd2dq, Op::Cvtdq2pd, Op::Cvtpd2dq, Op::Cvtsi2ss, Op::Cvttss2si, Op::Cvtss2si, Op::Cvtsi2sd, Op::Cvttsd2si, Op::Cvtsd2si];
/// Lower-case mnemonic stem.
pub const fn name(self) -> &'static str {
@@ -286,6 +290,7 @@ impl Op {
Op::Movdqa => "movdqa",
Op::Movdqu => "movdqu",
Op::Movntdq => "movntdq",
Op::Movnti => "movnti",
Op::Movntps => "movntps",
Op::Movss => "movss",
Op::Movsd => "movsd",
@@ -363,6 +368,9 @@ impl Op {
Op::Pinsrw => "pinsrw",
Op::Pextrw => "pextrw",
Op::Ldmxcsr => "ldmxcsr",
Op::Lfence => "lfence",
Op::Mfence => "mfence",
Op::Sfence => "sfence",
Op::Stmxcsr => "stmxcsr",
Op::Sqrtps => "sqrtps",
Op::Sqrtpd => "sqrtpd",
@@ -492,6 +500,7 @@ impl Op {
Op::Movdqa => 0,
Op::Movdqu => 0,
Op::Movntdq => 0,
Op::Movnti => 0,
Op::Movntps => 0,
Op::Movss => 0,
Op::Movsd => 0,
@@ -569,6 +578,9 @@ impl Op {
Op::Pinsrw => 0,
Op::Pextrw => 0,
Op::Ldmxcsr => 0,
Op::Lfence => 0,
Op::Mfence => 0,
Op::Sfence => 0,
Op::Stmxcsr => 0,
Op::Sqrtps => 0,
Op::Sqrtpd => 0,
@@ -698,6 +710,7 @@ impl Op {
Op::Movdqa => 0,
Op::Movdqu => 0,
Op::Movntdq => 0,
Op::Movnti => 0,
Op::Movntps => 0,
Op::Movss => 0,
Op::Movsd => 0,
@@ -775,6 +788,9 @@ impl Op {
Op::Pinsrw => 0,
Op::Pextrw => 0,
Op::Ldmxcsr => 0,
Op::Lfence => 0,
Op::Mfence => 0,
Op::Sfence => 0,
Op::Stmxcsr => 0,
Op::Sqrtps => 0,
Op::Sqrtpd => 0,
@@ -904,6 +920,7 @@ impl Op {
Op::Movdqa => 0,
Op::Movdqu => 0,
Op::Movntdq => 0,
Op::Movnti => 0,
Op::Movntps => 0,
Op::Movss => 0,
Op::Movsd => 0,
@@ -981,6 +998,9 @@ impl Op {
Op::Pinsrw => 0,
Op::Pextrw => 0,
Op::Ldmxcsr => 0,
Op::Lfence => 0,
Op::Mfence => 0,
Op::Sfence => 0,
Op::Stmxcsr => 0,
Op::Sqrtps => 0,
Op::Sqrtpd => 0,
@@ -1110,6 +1130,7 @@ impl Op {
Op::Movdqa => 0,
Op::Movdqu => 0,
Op::Movntdq => 0,
Op::Movnti => 0,
Op::Movntps => 0,
Op::Movss => 0,
Op::Movsd => 0,
@@ -1187,6 +1208,9 @@ impl Op {
Op::Pinsrw => 0,
Op::Pextrw => 0,
Op::Ldmxcsr => 0,
Op::Lfence => 0,
Op::Mfence => 0,
Op::Sfence => 0,
Op::Stmxcsr => 0,
Op::Sqrtps => 0,
Op::Sqrtpd => 0,
@@ -1316,6 +1340,7 @@ impl Op {
Op::Movdqa => false,
Op::Movdqu => false,
Op::Movntdq => false,
Op::Movnti => false,
Op::Movntps => false,
Op::Movss => false,
Op::Movsd => false,
@@ -1393,6 +1418,9 @@ impl Op {
Op::Pinsrw => false,
Op::Pextrw => false,
Op::Ldmxcsr => false,
Op::Lfence => false,
Op::Mfence => false,
Op::Sfence => false,
Op::Stmxcsr => false,
Op::Sqrtps => false,
Op::Sqrtpd => false,
@@ -1522,6 +1550,7 @@ impl Op {
Op::Movdqa => false,
Op::Movdqu => false,
Op::Movntdq => false,
Op::Movnti => false,
Op::Movntps => false,
Op::Movss => false,
Op::Movsd => false,
@@ -1599,6 +1628,9 @@ impl Op {
Op::Pinsrw => false,
Op::Pextrw => false,
Op::Ldmxcsr => false,
Op::Lfence => false,
Op::Mfence => false,
Op::Sfence => false,
Op::Stmxcsr => false,
Op::Sqrtps => true,
Op::Sqrtpd => true,
@@ -1728,6 +1760,7 @@ impl Op {
Op::Movdqa => true,
Op::Movdqu => true,
Op::Movntdq => true,
Op::Movnti => false,
Op::Movntps => true,
Op::Movss => true,
Op::Movsd => true,
@@ -1805,6 +1838,9 @@ impl Op {
Op::Pinsrw => true,
Op::Pextrw => true,
Op::Ldmxcsr => false,
Op::Lfence => false,
Op::Mfence => false,
Op::Sfence => false,
Op::Stmxcsr => false,
Op::Sqrtps => true,
Op::Sqrtpd => true,
@@ -1862,7 +1898,7 @@ impl Op {
}
}
pub static FORMS: [Form; 381] = [
pub static FORMS: [Form; 392] = [
Form { op: Op::Movsxd, encoding: Encoding::RegRm, size: OperandSize::Wide, immediate: Immediate::None, source: 4, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Push, encoding: Encoding::OpReg, size: OperandSize::Quad, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Pop, encoding: Encoding::OpReg, size: OperandSize::Quad, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
@@ -1885,6 +1921,13 @@ pub static FORMS: [Form; 381] = [
Form { op: Op::Test, encoding: Encoding::RmImm, size: OperandSize::Variable, immediate: Immediate::SignedFull, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Xchg, encoding: Encoding::RmReg, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Xchg, encoding: Encoding::RmReg, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Xchg, encoding: Encoding::OpReg, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Xchg, encoding: Encoding::OpReg, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Xchg, encoding: Encoding::OpReg, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Xchg, encoding: Encoding::OpReg, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Xchg, encoding: Encoding::OpReg, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Xchg, encoding: Encoding::OpReg, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Xchg, encoding: Encoding::OpReg, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: false, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Mov, encoding: Encoding::RmReg, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Mov, encoding: Encoding::RmReg, size: OperandSize::Variable, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Mov, encoding: Encoding::RegRm, size: OperandSize::Byte, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
@@ -1949,6 +1992,7 @@ pub static FORMS: [Form; 381] = [
Form { op: Op::Movdqu, encoding: Encoding::XmmRm, size: OperandSize::Xmm, immediate: Immediate::None, source: 16, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: true, lockable: false },
Form { op: Op::Movdqu, encoding: Encoding::RmXmm, size: OperandSize::Xmm, immediate: Immediate::None, source: 16, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: true, lockable: false },
Form { op: Op::Movntdq, encoding: Encoding::RmXmm, size: OperandSize::Xmm, immediate: Immediate::None, source: 16, has_modrm: true, memory_only: true, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Movnti, encoding: Encoding::RmReg, size: OperandSize::Wide, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: true, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Movntps, encoding: Encoding::RmXmm, size: OperandSize::Xmm, immediate: Immediate::None, source: 16, has_modrm: true, memory_only: true, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Movntps, encoding: Encoding::RmXmm, size: OperandSize::Xmm, immediate: Immediate::None, source: 16, has_modrm: true, memory_only: true, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Movss, encoding: Encoding::XmmRm, size: OperandSize::Xmm, immediate: Immediate::None, source: 4, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
@@ -2058,6 +2102,9 @@ pub static FORMS: [Form; 381] = [
Form { op: Op::Pextrw, encoding: Encoding::RegXmmImm, size: OperandSize::Wide, immediate: Immediate::Byte, source: 16, has_modrm: true, memory_only: false, register_only: true, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Ldmxcsr, encoding: Encoding::Rm, size: OperandSize::None, immediate: Immediate::None, source: 4, has_modrm: true, memory_only: true, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Stmxcsr, encoding: Encoding::Rm, size: OperandSize::None, immediate: Immediate::None, source: 4, has_modrm: true, memory_only: true, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Lfence, encoding: Encoding::RmUnread, size: OperandSize::None, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: true, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Mfence, encoding: Encoding::RmUnread, size: OperandSize::None, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: true, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Sfence, encoding: Encoding::RmUnread, size: OperandSize::None, immediate: Immediate::None, source: 0, has_modrm: true, memory_only: false, register_only: true, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Sqrtps, encoding: Encoding::XmmRm, size: OperandSize::Xmm, immediate: Immediate::None, source: 16, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Sqrtpd, encoding: Encoding::XmmRm, size: OperandSize::Xmm, immediate: Immediate::None, source: 16, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
Form { op: Op::Sqrtss, encoding: Encoding::XmmRm, size: OperandSize::Xmm, immediate: Immediate::None, source: 4, has_modrm: true, memory_only: false, register_only: false, no_rex_b: false, unaligned: false, lockable: false },
@@ -2248,47 +2295,47 @@ pub static FORMS: [Form; 381] = [
/// Form per ModRM digit; 65535 marks an unsupported digit.
pub static GROUPS: [[u16; 8]; 22] = [
[253, 262, 271, 280, 289, 298, 307, 316],
[254, 263, 272, 281, 290, 299, 308, 317],
[255, 264, 273, 282, 291, 300, 309, 318],
[264, 273, 282, 291, 300, 309, 318, 327],
[265, 274, 283, 292, 301, 310, 319, 328],
[266, 275, 284, 293, 302, 311, 320, 329],
[6, 65535, 65535, 65535, 65535, 65535, 65535, 65535],
[339, 340, 341, 342, 343, 344, 65535, 345],
[346, 347, 348, 349, 350, 351, 65535, 352],
[33, 65535, 65535, 65535, 65535, 65535, 65535, 65535],
[34, 65535, 65535, 65535, 65535, 65535, 65535, 65535],
[353, 354, 355, 356, 357, 358, 65535, 359],
[360, 361, 362, 363, 364, 365, 65535, 366],
[367, 368, 369, 370, 371, 372, 65535, 373],
[374, 375, 376, 377, 378, 379, 65535, 380],
[18, 65535, 323, 324, 325, 326, 327, 328],
[19, 65535, 329, 330, 331, 332, 333, 334],
[335, 336, 65535, 65535, 65535, 65535, 65535, 65535],
[337, 338, 41, 65535, 42, 65535, 5, 65535],
[28, 65535, 65535, 65535, 65535, 65535, 65535, 65535],
[65535, 65535, 193, 194, 65535, 65535, 65535, 65535],
[65535, 65535, 65535, 65535, 319, 320, 321, 322],
[65535, 65535, 165, 65535, 167, 65535, 169, 65535],
[65535, 65535, 171, 65535, 173, 65535, 175, 65535],
[65535, 65535, 177, 180, 65535, 65535, 179, 181],
[350, 351, 352, 353, 354, 355, 65535, 356],
[357, 358, 359, 360, 361, 362, 65535, 363],
[40, 65535, 65535, 65535, 65535, 65535, 65535, 65535],
[41, 65535, 65535, 65535, 65535, 65535, 65535, 65535],
[364, 365, 366, 367, 368, 369, 65535, 370],
[371, 372, 373, 374, 375, 376, 65535, 377],
[378, 379, 380, 381, 382, 383, 65535, 384],
[385, 386, 387, 388, 389, 390, 65535, 391],
[18, 65535, 334, 335, 336, 337, 338, 339],
[19, 65535, 340, 341, 342, 343, 344, 345],
[346, 347, 65535, 65535, 65535, 65535, 65535, 65535],
[348, 349, 48, 65535, 49, 65535, 5, 65535],
[35, 65535, 65535, 65535, 65535, 65535, 65535, 65535],
[65535, 65535, 201, 202, 65535, 203, 204, 205],
[65535, 65535, 65535, 65535, 330, 331, 332, 333],
[65535, 65535, 173, 65535, 175, 65535, 177, 65535],
[65535, 65535, 179, 65535, 181, 65535, 183, 65535],
[65535, 65535, 185, 188, 65535, 65535, 187, 189],
];
pub static ONE_BYTE: [Entry; 256] = [
Entry::Form(247), Entry::Form(248), Entry::Form(249), Entry::Form(250),
Entry::Form(251), Entry::Form(252), Entry::Unsupported, Entry::Unsupported,
Entry::Form(256), Entry::Form(257), Entry::Form(258), Entry::Form(259),
Entry::Form(260), Entry::Form(261), Entry::Unsupported, Entry::Unsupported,
Entry::Form(265), Entry::Form(266), Entry::Form(267), Entry::Form(268),
Entry::Form(269), Entry::Form(270), Entry::Unsupported, Entry::Unsupported,
Entry::Form(274), Entry::Form(275), Entry::Form(276), Entry::Form(277),
Entry::Form(278), Entry::Form(279), Entry::Unsupported, Entry::Unsupported,
Entry::Form(283), Entry::Form(284), Entry::Form(285), Entry::Form(286),
Entry::Form(287), Entry::Form(288), Entry::Unsupported, Entry::Unsupported,
Entry::Form(292), Entry::Form(293), Entry::Form(294), Entry::Form(295),
Entry::Form(296), Entry::Form(297), Entry::Unsupported, Entry::Unsupported,
Entry::Form(301), Entry::Form(302), Entry::Form(303), Entry::Form(304),
Entry::Form(305), Entry::Form(306), Entry::Unsupported, Entry::Unsupported,
Entry::Form(310), Entry::Form(311), Entry::Form(312), Entry::Form(313),
Entry::Form(314), Entry::Form(315), Entry::Unsupported, Entry::Unsupported,
Entry::Form(258), Entry::Form(259), Entry::Form(260), Entry::Form(261),
Entry::Form(262), Entry::Form(263), Entry::Unsupported, Entry::Unsupported,
Entry::Form(267), Entry::Form(268), Entry::Form(269), Entry::Form(270),
Entry::Form(271), Entry::Form(272), Entry::Unsupported, Entry::Unsupported,
Entry::Form(276), Entry::Form(277), Entry::Form(278), Entry::Form(279),
Entry::Form(280), Entry::Form(281), Entry::Unsupported, Entry::Unsupported,
Entry::Form(285), Entry::Form(286), Entry::Form(287), Entry::Form(288),
Entry::Form(289), Entry::Form(290), Entry::Unsupported, Entry::Unsupported,
Entry::Form(294), Entry::Form(295), Entry::Form(296), Entry::Form(297),
Entry::Form(298), Entry::Form(299), Entry::Unsupported, Entry::Unsupported,
Entry::Form(303), Entry::Form(304), Entry::Form(305), Entry::Form(306),
Entry::Form(307), Entry::Form(308), Entry::Unsupported, Entry::Unsupported,
Entry::Form(312), Entry::Form(313), Entry::Form(314), Entry::Form(315),
Entry::Form(316), Entry::Form(317), Entry::Unsupported, Entry::Unsupported,
Entry::Form(321), Entry::Form(322), Entry::Form(323), Entry::Form(324),
Entry::Form(325), Entry::Form(326), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
@@ -2307,23 +2354,23 @@ pub static ONE_BYTE: [Entry; 256] = [
Entry::Form(10), Entry::Form(10), Entry::Form(10), Entry::Form(10),
Entry::Group(0), Entry::Group(1), Entry::Unsupported, Entry::Group(2),
Entry::Form(14), Entry::Form(15), Entry::Form(20), Entry::Form(21),
Entry::Form(22), Entry::Form(23), Entry::Form(24), Entry::Form(25),
Entry::Unsupported, Entry::Form(26), Entry::Unsupported, Entry::Group(3),
Entry::Form(27), Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(29), Entry::Form(30), Entry::Unsupported, Entry::Unsupported,
Entry::Form(29), Entry::Form(30), Entry::Form(31), Entry::Form(32),
Entry::Unsupported, Entry::Form(33), Entry::Unsupported, Entry::Group(3),
Entry::Form(34), Entry::Form(22), Entry::Form(23), Entry::Form(24),
Entry::Form(25), Entry::Form(26), Entry::Form(27), Entry::Form(28),
Entry::Form(36), Entry::Form(37), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(49), Entry::Form(50), Entry::Unsupported, Entry::Unsupported,
Entry::Form(16), Entry::Form(17), Entry::Form(51), Entry::Form(52),
Entry::Form(56), Entry::Form(57), Entry::Unsupported, Entry::Unsupported,
Entry::Form(16), Entry::Form(17), Entry::Form(58), Entry::Form(59),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(31), Entry::Form(31), Entry::Form(31), Entry::Form(31),
Entry::Form(31), Entry::Form(31), Entry::Form(31), Entry::Form(31),
Entry::Form(32), Entry::Form(32), Entry::Form(32), Entry::Form(32),
Entry::Form(32), Entry::Form(32), Entry::Form(32), Entry::Form(32),
Entry::Group(4), Entry::Group(5), Entry::Form(35), Entry::Form(36),
Entry::Form(38), Entry::Form(38), Entry::Form(38), Entry::Form(38),
Entry::Form(38), Entry::Form(38), Entry::Form(38), Entry::Form(38),
Entry::Form(39), Entry::Form(39), Entry::Form(39), Entry::Form(39),
Entry::Form(39), Entry::Form(39), Entry::Form(39), Entry::Form(39),
Entry::Group(4), Entry::Group(5), Entry::Form(42), Entry::Form(43),
Entry::Unsupported, Entry::Unsupported, Entry::Group(6), Entry::Group(7),
Entry::Unsupported, Entry::Form(37), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Form(44), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Group(8), Entry::Group(9), Entry::Group(10), Entry::Group(11),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
@@ -2331,27 +2378,27 @@ pub static ONE_BYTE: [Entry; 256] = [
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(38), Entry::Form(39), Entry::Unsupported, Entry::Form(40),
Entry::Form(45), Entry::Form(46), Entry::Unsupported, Entry::Form(47),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(43), Entry::Form(44), Entry::Group(12), Entry::Group(13),
Entry::Form(45), Entry::Form(46), Entry::Unsupported, Entry::Unsupported,
Entry::Form(53), Entry::Form(54), Entry::Group(14), Entry::Group(15),
Entry::Form(50), Entry::Form(51), Entry::Group(12), Entry::Group(13),
Entry::Form(52), Entry::Form(53), Entry::Unsupported, Entry::Unsupported,
Entry::Form(60), Entry::Form(61), Entry::Group(14), Entry::Group(15),
];
pub static TWO_BYTE: [Entry; 256] = [
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Form(47), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Form(54), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(77), Entry::Form(78), Entry::Form(96), Entry::Form(98),
Entry::Form(187), Entry::Form(189), Entry::Form(100), Entry::Form(102),
Entry::Form(84), Entry::Form(85), Entry::Form(104), Entry::Form(106),
Entry::Form(195), Entry::Form(197), Entry::Form(108), Entry::Form(110),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Group(16),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(73), Entry::Form(74), Entry::Unsupported, Entry::Form(86),
Entry::Unsupported, Entry::Unsupported, Entry::Form(227), Entry::Form(228),
Entry::Form(80), Entry::Form(81), Entry::Unsupported, Entry::Form(94),
Entry::Unsupported, Entry::Unsupported, Entry::Form(238), Entry::Form(239),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
@@ -2360,10 +2407,10 @@ pub static TWO_BYTE: [Entry; 256] = [
Entry::Form(12), Entry::Form(12), Entry::Form(12), Entry::Form(12),
Entry::Form(12), Entry::Form(12), Entry::Form(12), Entry::Form(12),
Entry::Form(12), Entry::Form(12), Entry::Form(12), Entry::Form(12),
Entry::Form(104), Entry::Form(195), Entry::Unsupported, Entry::Unsupported,
Entry::Form(108), Entry::Form(111), Entry::Form(114), Entry::Form(117),
Entry::Form(199), Entry::Form(203), Entry::Form(231), Entry::Form(235),
Entry::Form(207), Entry::Form(211), Entry::Form(215), Entry::Form(219),
Entry::Form(112), Entry::Form(206), Entry::Unsupported, Entry::Unsupported,
Entry::Form(116), Entry::Form(119), Entry::Form(122), Entry::Form(125),
Entry::Form(210), Entry::Form(214), Entry::Form(242), Entry::Form(246),
Entry::Form(218), Entry::Form(222), Entry::Form(226), Entry::Form(230),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
@@ -2380,18 +2427,18 @@ pub static TWO_BYTE: [Entry; 256] = [
Entry::Form(13), Entry::Form(13), Entry::Form(13), Entry::Form(13),
Entry::Form(13), Entry::Form(13), Entry::Form(13), Entry::Form(13),
Entry::Form(13), Entry::Form(13), Entry::Form(13), Entry::Form(13),
Entry::Unsupported, Entry::Unsupported, Entry::Form(48), Entry::Form(65),
Entry::Unsupported, Entry::Unsupported, Entry::Form(55), Entry::Form(72),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Form(66),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Form(73),
Entry::Unsupported, Entry::Unsupported, Entry::Group(17), Entry::Form(9),
Entry::Form(69), Entry::Form(70), Entry::Unsupported, Entry::Form(67),
Entry::Unsupported, Entry::Unsupported, Entry::Form(55), Entry::Form(56),
Entry::Unsupported, Entry::Unsupported, Entry::Group(18), Entry::Form(68),
Entry::Form(60), Entry::Form(61), Entry::Form(57), Entry::Form(58),
Entry::Form(71), Entry::Form(72), Entry::Form(223), Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(185), Entry::Unsupported,
Entry::Form(59), Entry::Form(59), Entry::Form(59), Entry::Form(59),
Entry::Form(59), Entry::Form(59), Entry::Form(59), Entry::Form(59),
Entry::Form(76), Entry::Form(77), Entry::Unsupported, Entry::Form(74),
Entry::Unsupported, Entry::Unsupported, Entry::Form(62), Entry::Form(63),
Entry::Unsupported, Entry::Unsupported, Entry::Group(18), Entry::Form(75),
Entry::Form(67), Entry::Form(68), Entry::Form(64), Entry::Form(65),
Entry::Form(78), Entry::Form(79), Entry::Form(234), Entry::Form(93),
Entry::Unsupported, Entry::Unsupported, Entry::Form(193), Entry::Unsupported,
Entry::Form(66), Entry::Form(66), Entry::Form(66), Entry::Form(66),
Entry::Form(66), Entry::Form(66), Entry::Form(66), Entry::Form(66),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
@@ -2411,14 +2458,14 @@ pub static TWO_BYTE_66: [Entry; 256] = [
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(79), Entry::Form(80), Entry::Form(97), Entry::Form(99),
Entry::Form(188), Entry::Form(190), Entry::Form(101), Entry::Form(103),
Entry::Form(86), Entry::Form(87), Entry::Form(105), Entry::Form(107),
Entry::Form(196), Entry::Form(198), Entry::Form(109), Entry::Form(111),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(75), Entry::Form(76), Entry::Unsupported, Entry::Form(87),
Entry::Unsupported, Entry::Unsupported, Entry::Form(229), Entry::Form(230),
Entry::Form(82), Entry::Form(83), Entry::Unsupported, Entry::Form(95),
Entry::Unsupported, Entry::Unsupported, Entry::Form(240), Entry::Form(241),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
@@ -2427,18 +2474,18 @@ pub static TWO_BYTE_66: [Entry; 256] = [
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(105), Entry::Form(196), Entry::Unsupported, Entry::Unsupported,
Entry::Form(109), Entry::Form(112), Entry::Form(115), Entry::Form(118),
Entry::Form(200), Entry::Form(204), Entry::Form(232), Entry::Form(236),
Entry::Form(208), Entry::Form(212), Entry::Form(216), Entry::Form(220),
Entry::Form(119), Entry::Form(120), Entry::Form(121), Entry::Form(122),
Entry::Form(123), Entry::Form(124), Entry::Form(125), Entry::Form(126),
Entry::Form(113), Entry::Form(207), Entry::Unsupported, Entry::Unsupported,
Entry::Form(117), Entry::Form(120), Entry::Form(123), Entry::Form(126),
Entry::Form(211), Entry::Form(215), Entry::Form(243), Entry::Form(247),
Entry::Form(219), Entry::Form(223), Entry::Form(227), Entry::Form(231),
Entry::Form(127), Entry::Form(128), Entry::Form(129), Entry::Form(130),
Entry::Form(131), Entry::Form(132), Entry::Form(94), Entry::Form(81),
Entry::Form(182), Entry::Group(19), Entry::Group(20), Entry::Group(21),
Entry::Form(133), Entry::Form(134), Entry::Form(135), Entry::Unsupported,
Entry::Form(131), Entry::Form(132), Entry::Form(133), Entry::Form(134),
Entry::Form(135), Entry::Form(136), Entry::Form(137), Entry::Form(138),
Entry::Form(139), Entry::Form(140), Entry::Form(102), Entry::Form(88),
Entry::Form(190), Entry::Group(19), Entry::Group(20), Entry::Group(21),
Entry::Form(141), Entry::Form(142), Entry::Form(143), Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(95), Entry::Form(82),
Entry::Unsupported, Entry::Unsupported, Entry::Form(103), Entry::Form(89),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
@@ -2455,22 +2502,22 @@ pub static TWO_BYTE_66: [Entry; 256] = [
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(224), Entry::Unsupported,
Entry::Form(191), Entry::Form(192), Entry::Form(186), Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(235), Entry::Unsupported,
Entry::Form(199), Entry::Form(200), Entry::Form(194), Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Form(164), Entry::Form(170), Entry::Form(176),
Entry::Form(136), Entry::Form(137), Entry::Form(93), Entry::Form(106),
Entry::Form(138), Entry::Form(139), Entry::Form(140), Entry::Form(107),
Entry::Form(141), Entry::Form(142), Entry::Form(143), Entry::Form(110),
Entry::Form(144), Entry::Form(166), Entry::Form(172), Entry::Form(145),
Entry::Form(146), Entry::Form(147), Entry::Form(238), Entry::Form(85),
Entry::Form(148), Entry::Form(149), Entry::Form(150), Entry::Form(113),
Entry::Form(151), Entry::Form(152), Entry::Form(153), Entry::Form(116),
Entry::Unsupported, Entry::Form(168), Entry::Form(174), Entry::Form(178),
Entry::Form(154), Entry::Form(155), Entry::Form(156), Entry::Unsupported,
Entry::Form(157), Entry::Form(158), Entry::Form(159), Entry::Form(160),
Entry::Form(161), Entry::Form(162), Entry::Form(163), Entry::Unsupported,
Entry::Unsupported, Entry::Form(172), Entry::Form(178), Entry::Form(184),
Entry::Form(144), Entry::Form(145), Entry::Form(101), Entry::Form(114),
Entry::Form(146), Entry::Form(147), Entry::Form(148), Entry::Form(115),
Entry::Form(149), Entry::Form(150), Entry::Form(151), Entry::Form(118),
Entry::Form(152), Entry::Form(174), Entry::Form(180), Entry::Form(153),
Entry::Form(154), Entry::Form(155), Entry::Form(249), Entry::Form(92),
Entry::Form(156), Entry::Form(157), Entry::Form(158), Entry::Form(121),
Entry::Form(159), Entry::Form(160), Entry::Form(161), Entry::Form(124),
Entry::Unsupported, Entry::Form(176), Entry::Form(182), Entry::Form(186),
Entry::Form(162), Entry::Form(163), Entry::Form(164), Entry::Unsupported,
Entry::Form(165), Entry::Form(166), Entry::Form(167), Entry::Form(168),
Entry::Form(169), Entry::Form(170), Entry::Form(171), Entry::Unsupported,
];
pub static TWO_BYTE_F3: [Entry; 256] = [
@@ -2478,14 +2525,14 @@ pub static TWO_BYTE_F3: [Entry; 256] = [
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(88), Entry::Form(89), Entry::Unsupported, Entry::Unsupported,
Entry::Form(96), Entry::Form(97), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(241), Entry::Unsupported,
Entry::Form(242), Entry::Form(243), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(252), Entry::Unsupported,
Entry::Form(253), Entry::Form(254), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
@@ -2494,18 +2541,18 @@ pub static TWO_BYTE_F3: [Entry; 256] = [
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Form(197), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Form(208), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(201), Entry::Form(205), Entry::Form(233), Entry::Form(237),
Entry::Form(209), Entry::Form(213), Entry::Form(217), Entry::Form(221),
Entry::Form(212), Entry::Form(216), Entry::Form(244), Entry::Form(248),
Entry::Form(220), Entry::Form(224), Entry::Form(228), Entry::Form(232),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Form(83),
Entry::Form(183), Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Form(90),
Entry::Form(191), Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(92), Entry::Form(84),
Entry::Unsupported, Entry::Unsupported, Entry::Form(100), Entry::Form(91),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
@@ -2520,9 +2567,9 @@ pub static TWO_BYTE_F3: [Entry; 256] = [
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(62), Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(63), Entry::Form(64), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(225), Entry::Unsupported,
Entry::Form(69), Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(70), Entry::Form(71), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(236), Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
@@ -2531,7 +2578,7 @@ pub static TWO_BYTE_F3: [Entry; 256] = [
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(239), Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(250), Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
@@ -2545,14 +2592,14 @@ pub static TWO_BYTE_F2: [Entry; 256] = [
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(90), Entry::Form(91), Entry::Unsupported, Entry::Unsupported,
Entry::Form(98), Entry::Form(99), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(244), Entry::Unsupported,
Entry::Form(245), Entry::Form(246), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(255), Entry::Unsupported,
Entry::Form(256), Entry::Form(257), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
@@ -2561,15 +2608,15 @@ pub static TWO_BYTE_F2: [Entry; 256] = [
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Form(198), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Form(209), Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(202), Entry::Form(206), Entry::Form(234), Entry::Unsupported,
Entry::Form(210), Entry::Form(214), Entry::Form(218), Entry::Form(222),
Entry::Form(213), Entry::Form(217), Entry::Form(245), Entry::Unsupported,
Entry::Form(221), Entry::Form(225), Entry::Form(229), Entry::Form(233),
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(184), Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Form(192), Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
@@ -2589,7 +2636,7 @@ pub static TWO_BYTE_F2: [Entry; 256] = [
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(226), Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(237), Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
@@ -2598,7 +2645,7 @@ pub static TWO_BYTE_F2: [Entry; 256] = [
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(240), Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Form(251), Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
Entry::Unsupported, Entry::Unsupported, Entry::Unsupported, Entry::Unsupported,
+42
View File
@@ -164,3 +164,45 @@ fn vector_operations_match_llvm() {
assert_eq!(assembler.instructions(), [*word], "{text}");
}
}
#[test]
fn carry_arithmetic_matches_llvm() {
// `llvm-mc -triple=aarch64-apple-macos -show-encoding`.
let cases: &[(&str, Emit, u32)] = &[
(
"adcs x11, x9, x10",
|a| a.adcs_reg_64(11, 9, 10),
0xba0a012b,
),
(
"adcs w11, w9, w10",
|a| a.adcs_reg_32(11, 9, 10),
0x3a0a012b,
),
(
"adcs x0, x30, x17",
|a| a.adcs_reg_64(0, 30, 17),
0xba1103c0,
),
(
"sbcs x11, x9, x10",
|a| a.sbcs_reg_64(11, 9, 10),
0xfa0a012b,
),
(
"sbcs w11, w9, w10",
|a| a.sbcs_reg_32(11, 9, 10),
0x7a0a012b,
),
(
"sbcs w0, w30, w17",
|a| a.sbcs_reg_32(0, 30, 17),
0x7a1103c0,
),
];
for (text, emit, word) in cases {
let mut assembler = Arm64Assembler::new();
emit(&mut assembler);
assert_eq!(assembler.instructions(), [*word], "{text}");
}
}
+16 -16
View File
@@ -199,15 +199,15 @@ fn reported_features_have_all_their_instructions_in_the_fixtures() {
fn unreported_features_each_have_an_instruction_that_is_refused() {
// (feature, leaf, result register, bit, an instruction of that feature)
let witnesses: &[(&str, u32, usize, u32, &[u8])] = &[
("FPU", 1, EDX, 0, &[0xD9, 0xE8]), // fld1
("TSC", 1, EDX, 4, &[0x0F, 0x31]), // rdtsc
("CX8", 1, EDX, 8, &[0x0F, 0xC7, 0x0E]), // cmpxchg8b [rsi]
("CLFSH", 1, EDX, 19, &[0x0F, 0xAE, 0x3E]), // clflush [rsi]
("MMX", 1, EDX, 23, &[0x0F, 0x77]), // emms
("FXSR", 1, EDX, 24, &[0x0F, 0xAE, 0x06]), // fxsave [rsi]
("SSE", 1, EDX, 25, &[0x0F, 0x52, 0xC1]), // rsqrtps xmm0, xmm1
("SSE2", 1, EDX, 26, &[0x0F, 0xAE, 0xF0]), // mfence
("SSE3", 1, ECX, 0, &[0xF2, 0x0F, 0x7C, 0xC1]), // haddps xmm0, xmm1
("FPU", 1, EDX, 0, &[0xD9, 0xE8]), // fld1
("TSC", 1, EDX, 4, &[0x0F, 0x31]), // rdtsc
("CX8", 1, EDX, 8, &[0x0F, 0xC7, 0x0E]), // cmpxchg8b [rsi]
("CLFSH", 1, EDX, 19, &[0x0F, 0xAE, 0x3E]), // clflush [rsi]
("MMX", 1, EDX, 23, &[0x0F, 0x77]), // emms
("FXSR", 1, EDX, 24, &[0x0F, 0xAE, 0x06]), // fxsave [rsi]
("SSE", 1, EDX, 25, &[0x0F, 0x52, 0xC1]), // rsqrtps xmm0, xmm1
("SSE2", 1, EDX, 26, &[0x66, 0x0F, 0xF7, 0xC1]), // maskmovdqu xmm0, xmm1
("SSE3", 1, ECX, 0, &[0xF2, 0x0F, 0x7C, 0xC1]), // haddps xmm0, xmm1
(
"PCLMULQDQ",
1,
@@ -222,17 +222,17 @@ fn unreported_features_each_have_an_instruction_that_is_refused() {
("SSE4.2", 1, ECX, 20, &[0xF2, 0x0F, 0x38, 0xF1, 0xC1]), // crc32 eax, ecx
("MOVBE", 1, ECX, 22, &[0x0F, 0x38, 0xF0, 0x06]), // movbe eax, [rsi]
("AESNI", 1, ECX, 25, &[0x66, 0x0F, 0x38, 0xDC, 0xC1]), // aesenc xmm0, xmm1
("XSAVE", 1, ECX, 26, &[0x0F, 0x01, 0xD0]), // xgetbv
("AVX", 1, ECX, 28, &[0xC5, 0xF4, 0x58, 0xC2]), // vaddps ymm0, ymm1, ymm2
("XSAVE", 1, ECX, 26, &[0x0F, 0x01, 0xD0]), // xgetbv
("AVX", 1, ECX, 28, &[0xC5, 0xF4, 0x58, 0xC2]), // vaddps ymm0, ymm1, ymm2
("F16C", 1, ECX, 29, &[0xC4, 0xE2, 0x79, 0x13, 0xC1]), // vcvtph2ps xmm0, xmm1
("RDRAND", 1, ECX, 30, &[0x0F, 0xC7, 0xF0]), // rdrand eax
("RDRAND", 1, ECX, 30, &[0x0F, 0xC7, 0xF0]), // rdrand eax
("BMI1", 7, EBX, 3, &[0xC4, 0xE2, 0x70, 0xF2, 0xC2]), // andn eax, ecx, edx
("AVX2", 7, EBX, 5, &[0xC5, 0xF5, 0xFE, 0xC2]), // vpaddd ymm0, ymm1, ymm2
("AVX2", 7, EBX, 5, &[0xC5, 0xF5, 0xFE, 0xC2]), // vpaddd ymm0, ymm1, ymm2
("BMI2", 7, EBX, 8, &[0xC4, 0xE2, 0x73, 0xF6, 0xC2]), // mulx eax, ecx, edx
("RDSEED", 7, EBX, 18, &[0x0F, 0xC7, 0xF8]), // rdseed eax
("RDSEED", 7, EBX, 18, &[0x0F, 0xC7, 0xF8]), // rdseed eax
("ADX", 7, EBX, 19, &[0x66, 0x0F, 0x38, 0xF6, 0xC1]), // adcx eax, ecx
("SHA", 7, EBX, 29, &[0x0F, 0x38, 0xC9, 0xC1]), // sha1msg1 xmm0, xmm1
("LAHF/SAHF", 0x8000_0001, ECX, 0, &[0x9F]), // lahf
("SHA", 7, EBX, 29, &[0x0F, 0x38, 0xC9, 0xC1]), // sha1msg1 xmm0, xmm1
("LAHF/SAHF", 0x8000_0001, ECX, 0, &[0x9F]), // lahf
("PREFETCHW", 0x8000_0001, ECX, 8, &[0x0F, 0x0D, 0x0E]), // prefetchw [rsi]
("SYSCALL/SYSRET", 0x8000_0001, EDX, 11, &[0x48, 0x0F, 0x07]), // sysretq
("RDTSCP", 0x8000_0001, EDX, 27, &[0x0F, 0x01, 0xF9]), // rdtscp
+45 -26
View File
@@ -1365,6 +1365,33 @@ mov_moffs8_store: rax=77 m0=00000000 => m0=00000077 f=*
thirteen_byte_fs_add_imm32: rax=10 rbx=8 fs120=0000000000000000 => fs120=4433221100000000 f=cPazso
";
/// Single-thread baseline for the fences (#199). Each engine completes every
/// load and store of an instruction before the next instruction starts, so the
/// cases only require that a fence changes nothing and that accesses on either
/// side of it happen in program order. Nothing here involves a second thread.
const FENCES: &str = r"
@ mov [rdi], rax; mfence; mov rbx, [rdi]
488907 0faef0 488b1f
SDM 2B MFENCE
mfence_store_is_visible_to_a_later_load: rdi=D rax=1122334455667788 m0=0000000000000000 => rbx=1122334455667788 m0=8877665544332211 f=*
@ mov [rdi], rax; sfence; mov rbx, [rdi+8]
488907 0faef8 488b5f08
SDM 2B SFENCE
sfence_after_a_store_keeps_other_memory: rdi=D rax=1 m0=0000000000000000 m8=aabbccddeeff0011 => rbx=1100ffeeddccbbaa m0=0100000000000000 f=*
@ mov rbx, [rdi]; lfence; mov [rdi], rax
488b1f 0faee8 488907
SDM 2B LFENCE
lfence_load_precedes_a_later_store: rdi=D rax=5 m0=0200000000000000 => rbx=2 m0=0500000000000000 f=*
@ mfence; lfence; sfence
0faef0 0faee8 0faef8
SDM 2B MFENCE; 2B LFENCE; 2B SFENCE
fences_change_no_register_or_flag: rax=1122334455667788 rbx=99aabbccddeeff00 => f=*
@ .byte 0x0f,0xae,0xf5; .byte 0x0f,0xae,0xeb; .byte 0x0f,0xae,0xff
0faef5 0faeeb 0faeff
SDM 2B MFENCE; 2B LFENCE; 2B SFENCE (the r/m field is ignored)
fences_ignore_the_rm_field: rax=1122334455667788 => f=*
";
const MEMORY_FAULTS: &str = r"
@ mov r8d, 1; add al, bl; mov rcx, [rsi]; mov r9d, 2
41b801000000 00d8 !488b0e 41b902000000
@@ -1505,7 +1532,7 @@ jump_to_unmapped_faults_at_target: rbx=U => rax=1 rip=U f=* ! PFX U
jump_to_data_page_faults_at_target: rbx=D+40 => rip=D+40 f=* ! PFX D+40
";
const DEFECT_STRADDLING_FAULT_ADDRESS: &str = r"
const STRADDLING_FAULT_ADDRESS: &str = r"
@ mov rcx, [rsi-4]
!488b4efc
SDM 3A 5.7 (the address with no translation); 3A 7.15 Interrupt 14
@@ -2608,12 +2635,15 @@ add_memory_crosses_contiguous_pages: rdi=D+1000 mffd=ffffffffffffffff => mffd=00
push_pop_cross_contiguous_pages: rsp=D+1004 rax=1122334455667788 => rbx=1122334455667788 mffc=8877665544332211 f=*
";
const DEFECT_EXACT_UNMASKED_OVERFLOW: &str = r"
const EXACT_UNMASKED_OVERFLOW: &str = r"
@ mulss xmm1, xmm2
!f30f59ca
SDM 1 D.4.2.3 Table D-16 (PE only if inexact); APM 1 4.10.2.8
unmasked_overflow_exact_sets_only_oe: x1=s:7f7fffff x2=s:40000000 mx=1b80 => mx=1b88 f=* ! XM
unmasked_negative_overflow_exact_sets_only_oe: x1=s:ff7fffff x2=s:40000000 mx=1b80 => mx=1b88 f=* ! XM
unmasked_overflow_exact_sets_only_oe_down: x1=s:7f7fffff x2=s:40000000 mx=3b80 => mx=3b88 f=* ! XM
unmasked_overflow_exact_sets_only_oe_up: x1=s:7f7fffff x2=s:40000000 mx=5b80 => mx=5b88 f=* ! XM
unmasked_overflow_exact_sets_only_oe_zero: x1=s:7f7fffff x2=s:40000000 mx=7b80 => mx=7b88 f=* ! XM
@ addsd xmm1, xmm2
!f20f58ca
SDM 1 D.4.2.3 Table D-16 (PE only if inexact); APM 1 4.10.2.8
@@ -2643,11 +2673,9 @@ const GROUPS: &[(&str, &str)] = &[
("strings", STRINGS),
("fs_gs", FS_GS),
("decoding", DECODING),
("fences", FENCES),
("memory_faults", MEMORY_FAULTS),
(
"defect_straddling_fault_address",
DEFECT_STRADDLING_FAULT_ADDRESS,
),
("straddling_fault_address", STRADDLING_FAULT_ADDRESS),
("defect_noncanonical_address", DEFECT_NONCANONICAL_ADDRESS),
("packed_integer_sse2", PACKED_INTEGER_SSE2),
("packed_integer_beyond_sse2", PACKED_INTEGER_BEYOND_SSE2),
@@ -2661,10 +2689,7 @@ const GROUPS: &[(&str, &str)] = &[
("fp_mxcsr_and_unmasked", FP_MXCSR_AND_UNMASKED),
("fp_beyond_sse2", FP_BEYOND_SSE2),
("defect_overlong_instruction", DEFECT_OVERLONG_INSTRUCTION),
(
"defect_exact_unmasked_overflow",
DEFECT_EXACT_UNMASKED_OVERFLOW,
),
("exact_unmasked_overflow", EXACT_UNMASKED_OVERFLOW),
("page_crossing", PAGE_CROSSING),
];
@@ -2710,7 +2735,6 @@ const UNSUPPORTED: &[(&str, usize)] = &[
("mov_moffs64_load", 0),
("mov_moffs8_store", 0),
("movddup_movsldup_movshdup", 0),
("movdqa_movaps_aligned_store_and_load", 3),
("mpsadbw", 0),
("pabs_min_is_unchanged", 0),
("packusdw", 0),
@@ -2758,9 +2782,6 @@ const UNSUPPORTED: &[(&str, usize)] = &[
("shrd32_by8", 0),
("shrd64_by1_sign_change", 0),
("shrd64_cl64_is_count_zero", 0),
("xchg_ax_r9w_preserves_both_uppers", 0),
("xchg_eax_ebx_clears_both_uppers", 0),
("xchg_rax_r8_is_not_nop", 0),
];
// ---------------------------------------------------------------------------
@@ -3431,15 +3452,19 @@ fn decoding() {
check_group(DECODING);
}
#[test]
fn fences() {
check_group(FENCES);
}
#[test]
fn memory_faults() {
check_group(MEMORY_FAULTS);
}
#[test]
#[ignore = "known defect (#155): a page-crossing fault reports the start of the access"]
fn defect_straddling_fault_address() {
check_group(DEFECT_STRADDLING_FAULT_ADDRESS);
fn straddling_fault_address() {
check_group(STRADDLING_FAULT_ADDRESS);
}
#[test]
@@ -3510,9 +3535,8 @@ fn defect_overlong_instruction() {
}
#[test]
#[ignore = "known defect (#155): an exact unmasked overflow sets PE as well as OE"]
fn defect_exact_unmasked_overflow() {
check_group(DEFECT_EXACT_UNMASKED_OVERFLOW);
fn exact_unmasked_overflow() {
check_group(EXACT_UNMASKED_OVERFLOW);
}
#[test]
@@ -4731,12 +4755,7 @@ fn deliver(
}
if lowest + precision - 1 > format.max_exponent() {
if mxcsr & OM == 0 {
// PE of an exact overflow is `defect_exact_unmasked_overflow`; this
// sweep compares every other bit.
return Outcome {
open: if unbounded_exact { PE } else { 0 },
..outcome(0, OE | unbounded_inexact)
};
return outcome(0, OE | unbounded_inexact);
}
let to_infinity = match mode {
0 => true,
@@ -96,10 +96,11 @@ fn crt_handlers_validate_memory_boundaries() {
0x1008
)))
);
// The destination 0x1005..0x1009 is mapped up to 0x1008.
assert_eq!(
call("memmove", 0x1005, 0x1000, 4, &mut memory),
Err(ExitReason::MemoryFault(MemoryError::UnmappedAddress(
0x1005
0x1008
)))
);
let mut bytes = [0; 8];
@@ -0,0 +1,274 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Guest 4 KiB page boundaries on a host with larger pages (#175).
//!
//! Apple Silicon uses 16 KiB host pages, so four guest pages share one host
//! page and host page protection cannot separate them. Guest memory is checked
//! in software, byte by byte, and is never mapped with host protections. These
//! tests lay 4 KiB guest pages across two spans of the detected host page size
//! and require the same results at every guest page boundary, whether or not it
//! is also a host page boundary.
//!
//! The expected fault address is the first byte, in address order, that the
//! access may not touch: the linear address with no translation or without the
//! needed right. This is the reading of the Intel SDM used by the page-fault
//! cases in `cpu_known_answers.rs` (Volume 3A, Sections 5.7 and 7.15, Interrupt
//! 14). Every expectation below is a literal address or a table written from
//! that rule, not a value read back from the memory model. Nothing here was
//! compared with x86 hardware.
use xenora_loader::services::sysinfo::HostCapabilities;
use xenora_loader::{GuestMemory, MemoryError, MemoryPermissions as P};
const GUEST_PAGE: u64 = 0x1000;
/// Aligned to every host page size up to 1 GiB.
const BASE: u64 = 0x4000_0000;
fn host_page() -> u64 {
let size = HostCapabilities::detect()
.page_size
.expect("the host reports a page size");
assert_eq!(size % GUEST_PAGE, 0, "host page size {size:#x}");
size
}
/// Guest page boundaries strictly inside two host pages starting at `BASE`.
/// On a 16 KiB host that is seven boundaries, one of them a host page boundary.
fn boundaries() -> Vec<u64> {
let pages = 2 * host_page() / GUEST_PAGE;
(1..pages).map(|page| BASE + page * GUEST_PAGE).collect()
}
fn unmapped(address: u64) -> MemoryError {
MemoryError::UnmappedAddress(address)
}
fn violation(address: u64, required: &'static str) -> MemoryError {
MemoryError::PermissionViolation { address, required }
}
/// The page below `boundary`, filled with 0x5a, and optionally the page above
/// it, filled with 0xa5.
fn pages_around(boundary: u64, below: P, above: Option<P>) -> GuestMemory {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(boundary - GUEST_PAGE, 0x1000, below, &[0x5a; 0x1000])
.unwrap();
if let Some(above) = above {
memory
.map_region_with_data(boundary, 0x1000, above, &[0xa5; 0x1000])
.unwrap();
}
memory
}
/// The 16 bytes centred on `boundary`, read without permission checks.
fn bytes_around(memory: &GuestMemory, boundary: u64) -> (u64, u64) {
(
memory.read_u64_bypass(boundary - 8).unwrap(),
memory.read_u64_bypass(boundary).unwrap(),
)
}
const BELOW: u64 = 0x5a5a_5a5a_5a5a_5a5a;
const ABOVE: u64 = 0xa5a5_a5a5_a5a5_a5a5;
#[test]
fn apple_silicon_host_pages_hold_four_guest_pages() {
let size = host_page();
if cfg!(all(target_os = "macos", target_arch = "aarch64")) {
assert_eq!(size, 0x4000);
assert_eq!(boundaries().len(), 7);
assert!(boundaries().contains(&(BASE + 0x4000)));
}
}
#[test]
fn each_guest_page_in_a_host_page_keeps_its_own_permissions() {
// (permissions, read allowed, write allowed, execute allowed)
let kinds = [
(P::READ_WRITE, true, true, false),
(P::READ_ONLY, true, false, false),
(P::NO_ACCESS, false, false, false),
(P::READ_EXECUTE, true, false, true),
];
let pages = 2 * host_page() / GUEST_PAGE;
let mut memory = GuestMemory::new();
for page in 0..pages {
let fill = [page as u8 + 1; 0x1000];
let kind = kinds[page as usize % kinds.len()].0;
memory
.map_region_with_data(BASE + page * GUEST_PAGE, 0x1000, kind, &fill)
.unwrap();
}
for page in 0..pages {
let (_, read, write, execute) = kinds[page as usize % kinds.len()];
let fill = page as u8 + 1;
let first = BASE + page * GUEST_PAGE;
for address in [first, first + 0xFFF] {
let expected = |allowed, required| {
if allowed {
Ok(fill)
} else {
Err(violation(address, required))
}
};
assert_eq!(memory.read_u8(address), expected(read, "read"));
assert_eq!(
memory.fetch_instruction_byte(address),
expected(execute, "execute")
);
assert_eq!(
memory.write_u8(address, fill),
expected(write, "write").map(|_| ())
);
}
}
assert_eq!(memory.read_u8(BASE - 1), Err(unmapped(BASE - 1)));
let end = BASE + pages * GUEST_PAGE;
assert_eq!(memory.read_u8(end), Err(unmapped(end)));
}
#[test]
fn access_across_adjacent_guest_pages_lands_in_both() {
for boundary in boundaries() {
let mut memory = pages_around(boundary, P::READ_WRITE, Some(P::READ_WRITE));
memory
.write_u64(boundary - 3, 0x8877_6655_4433_2211)
.unwrap();
assert_eq!(memory.read_u64(boundary - 3), Ok(0x8877_6655_4433_2211));
// Little endian: three bytes below the boundary, five above it.
assert_eq!(
bytes_around(&memory, boundary),
(0x3322_115a_5a5a_5a5a, 0xa5a5_a588_7766_5544),
"boundary {boundary:#x}"
);
}
}
#[test]
fn crossing_into_an_unmapped_page_faults_at_its_first_byte() {
for boundary in boundaries() {
let mut memory = pages_around(boundary, P::READ_WRITE, None);
let fault = Err(unmapped(boundary));
for back in 1..8u64 {
let start = boundary - back;
let context = format!("boundary {boundary:#x}, start -{back}");
assert_eq!(memory.read_u64(start).map(|_| ()), fault, "{context}");
assert_eq!(memory.write_u64(start, 0), fault, "{context}");
assert_eq!(memory.write_u64_bypass(start, 0), fault, "{context}");
assert_eq!(memory.read_u64_bypass(start).map(|_| ()), fault);
}
for (back, width) in [(1u64, 2usize), (3, 4), (15, 16), (1, 0x1001)] {
let mut buffer = vec![0u8; width];
assert_eq!(memory.read_bytes(boundary - back, &mut buffer), fault);
assert_eq!(memory.write_bytes(boundary - back, &buffer), fault);
}
// The failed stores wrote nothing below the boundary, and the last
// access that fits still succeeds.
assert_eq!(memory.read_u64(boundary - 8), Ok(BELOW));
// An access that does not touch the mapped page faults at its own
// first byte.
assert_eq!(memory.read_u64(boundary).map(|_| ()), fault);
assert_eq!(
memory.read_u64(boundary + 5).map(|_| ()),
Err(unmapped(boundary + 5))
);
}
}
#[test]
fn starting_in_an_unmapped_page_faults_at_the_access_start() {
for boundary in boundaries() {
// Only the page above the boundary exists.
let mut memory = GuestMemory::new();
memory
.map_region_with_data(boundary, 0x1000, P::READ_WRITE, &[0xa5; 0x1000])
.unwrap();
for back in 1..8u64 {
let start = boundary - back;
assert_eq!(memory.read_u64(start).map(|_| ()), Err(unmapped(start)));
assert_eq!(memory.write_u64(start, 0), Err(unmapped(start)));
}
assert_eq!(memory.read_u64(boundary), Ok(ABOVE));
}
}
#[test]
fn crossing_into_a_page_without_the_right_faults_at_its_first_byte() {
for boundary in boundaries() {
// A store into a read-only page.
let mut memory = pages_around(boundary, P::READ_WRITE, Some(P::READ_ONLY));
for back in 1..8u64 {
assert_eq!(
memory.write_u64(boundary - back, 0),
Err(violation(boundary, "write")),
"boundary {boundary:#x}, start -{back}"
);
assert!(memory.read_u64(boundary - back).is_ok());
}
assert_eq!(bytes_around(&memory, boundary), (BELOW, ABOVE));
// A load from a page with no access.
let memory = pages_around(boundary, P::READ_ONLY, Some(P::NO_ACCESS));
for back in 1..8u64 {
assert_eq!(
memory.read_u64(boundary - back).map(|_| ()),
Err(violation(boundary, "read")),
"boundary {boundary:#x}, start -{back}"
);
}
assert_eq!(memory.read_u64(boundary - 8), Ok(BELOW));
}
}
#[test]
fn the_lowest_failing_byte_decides_the_fault() {
for boundary in boundaries() {
// Forbidden first page, unmapped second page: the first byte fails.
let mut memory = pages_around(boundary, P::READ_ONLY, None);
assert_eq!(
memory.write_u64(boundary - 4, 0),
Err(violation(boundary - 4, "write"))
);
assert_eq!(
memory.read_u64(boundary - 4).map(|_| ()),
Err(unmapped(boundary))
);
// Writable, then read-only, then unmapped: a store over all three
// stops at the read-only page, a load at the unmapped one.
let mut memory = pages_around(boundary, P::READ_WRITE, Some(P::READ_ONLY));
let mut buffer = vec![0u8; 0x1008];
assert_eq!(
memory.write_bytes(boundary - 4, &buffer),
Err(violation(boundary, "write"))
);
assert_eq!(
memory.read_bytes(boundary - 4, &mut buffer),
Err(unmapped(boundary + GUEST_PAGE))
);
assert_eq!(bytes_around(&memory, boundary), (BELOW, ABOVE));
}
}
#[test]
fn the_highest_guest_page_boundaries_do_not_wrap() {
// The last page that can be mapped ends one page below 2^64.
let top = u64::MAX - 0xFFF; // 0xffff_ffff_ffff_f000
let mut memory = pages_around(top, P::READ_WRITE, None);
assert_eq!(
memory.map_region(top, 0x1000, P::READ_WRITE),
Err(MemoryError::Overflow)
);
assert_eq!(memory.read_u64(top - 8), Ok(BELOW));
assert_eq!(memory.read_u64(top - 4).map(|_| ()), Err(unmapped(top)));
assert_eq!(memory.write_u64(top - 4, 0), Err(unmapped(top)));
// An access whose end passes 2^64 is an overflow wherever it starts.
assert_eq!(memory.read_u64(u64::MAX - 6), Err(MemoryError::Overflow));
assert_eq!(
memory.write_u64(u64::MAX - 6, 0),
Err(MemoryError::Overflow)
);
assert_eq!(memory.read_u64(top - 8), Ok(BELOW));
}
+5 -5
View File
@@ -5,7 +5,7 @@
//! Expected behavior follows x86-64 data access rules: an access is valid when
//! every byte it touches is mapped with the required permission, whether or not
//! it is aligned or crosses into an adjacent mapping. A faulting access changes
//! nothing.
//! nothing and reports the lowest address it may not touch (#175).
use xenora_loader::{GuestMemory, MemoryError, MemoryPermissions as P};
@@ -56,7 +56,7 @@ fn region_end_is_exclusive() {
lone.map_region(A, 0x1000, P::READ_ONLY).unwrap();
assert_eq!(
lone.read_u32(A + 0xFFD),
Err(MemoryError::UnmappedAddress(A + 0xFFD))
Err(MemoryError::UnmappedAddress(A + 0x1000))
);
assert_eq!(
lone.read_u8(A - 1),
@@ -90,7 +90,7 @@ fn spanning_into_a_gap_fails_without_partial_write() {
m.map_region(A + 0x2000, 0x1000, P::READ_WRITE).unwrap();
assert_eq!(
m.write_u64(A + 0xFFC, u64::MAX),
Err(MemoryError::UnmappedAddress(A + 0xFFC))
Err(MemoryError::UnmappedAddress(A + 0x1000))
);
assert_eq!(m.read_u32(A + 0xFFC), Ok(0x1111_1111));
}
@@ -101,7 +101,7 @@ fn spanning_into_a_forbidden_region_fails_atomically() {
assert_eq!(
m.write_u64(A + 0xFFC, u64::MAX),
Err(MemoryError::PermissionViolation {
address: A + 0xFFC,
address: A + 0x1000,
required: "write"
})
);
@@ -123,7 +123,7 @@ fn loader_bypass_ignores_permissions_but_not_mapping() {
assert_eq!(m.read_u32(A), Ok(7));
assert_eq!(
m.write_u64_bypass(A + 0x1FFC, 0),
Err(MemoryError::UnmappedAddress(A + 0x1FFC))
Err(MemoryError::UnmappedAddress(A + 0x2000))
);
}
@@ -0,0 +1,233 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Synthetic guest calls through the standard import registry. Expectations use
//! Microsoft's public CloseHandle, DuplicateHandle and synchronization contracts:
//! https://learn.microsoft.com/windows/win32/api/handleapi/nf-handleapi-closehandle
//! https://learn.microsoft.com/windows/win32/api/handleapi/nf-handleapi-duplicatehandle
//! https://learn.microsoft.com/windows/win32/sync/synchronization-object-security-and-access-rights
//!
//! Capacity, rejected rights escalation and failed-output nonmutation are Xenora
//! subset policies, not claims about every Windows handle implementation. The
//! current runtime avoids stale aliases with increasing IDs, not generations.
mod support;
use support::{Guest, SCRATCH, SCRATCH_LEN};
use xenora_loader::memory::MemoryPermissions;
const IMPORTS: &[(&str, &str)] = &[
("kernel32.dll", "GetLastError"),
("kernel32.dll", "CreateEventW"),
("kernel32.dll", "CreateSemaphoreW"),
("kernel32.dll", "SetEvent"),
("kernel32.dll", "ReleaseSemaphore"),
("kernel32.dll", "WaitForSingleObject"),
("kernel32.dll", "CloseHandle"),
("kernel32.dll", "DuplicateHandle"),
("kernel32.dll", "GetCurrentThread"),
("kernel32.dll", "GetCurrentThreadId"),
("kernel32.dll", "GetThreadId"),
];
const CURRENT_PROCESS: u64 = u64::MAX;
const SAME_ACCESS: u64 = 2;
const MODIFY: u64 = 2;
const SYNCHRONIZE: u64 = 0x0010_0000;
const WAIT_TIMEOUT: u64 = 258;
const WAIT_FAILED: u64 = u32::MAX as u64;
const INVALID_HANDLE: u64 = 6;
const ACCESS_DENIED: u64 = 5;
const NOACCESS: u64 = 998;
const SENTINEL: u64 = 0xABCD_1234_5678_90EF;
// Xenora's bounded object table, not a Windows limit.
const CAPACITY: usize = 1024;
fn event(guest: &mut Guest) -> u64 {
let handle = guest.call("CreateEventW", &[0, 0, 0, 0]);
assert_ne!(handle, 0);
handle
}
fn duplicate(guest: &mut Guest, source: u64, output: u64, rights: u64, options: u64) -> u64 {
guest.call(
"DuplicateHandle",
&[
CURRENT_PROCESS,
source,
CURRENT_PROCESS,
output,
rights,
0,
options,
],
)
}
fn copy(guest: &mut Guest, source: u64, rights: u64, options: u64) -> u64 {
guest.memory.write_u64(SCRATCH, SENTINEL).unwrap();
assert_eq!(duplicate(guest, source, SCRATCH, rights, options), 1);
let handle = guest.u64_at(SCRATCH);
assert_ne!(handle, 0);
assert_ne!(handle, source);
assert_ne!(handle, SENTINEL);
handle
}
#[test]
fn reclaimed_capacity_never_revives_closed_handles() {
let mut guest = Guest::new(IMPORTS, &[]);
let handles: Vec<_> = (0..CAPACITY).map(|_| event(&mut guest)).collect();
assert_eq!(guest.call("CreateEventW", &[0, 0, 0, 0]), 0);
assert_eq!(guest.error(), 8); // ERROR_NOT_ENOUGH_MEMORY
// Release one slot at a time while the table stays otherwise full.
for old in handles {
assert_eq!(guest.call("CloseHandle", &[old]), 1);
let replacement = event(&mut guest);
assert_ne!(replacement, old);
assert_eq!(guest.call("SetEvent", &[old]), 0);
assert_eq!(guest.error(), INVALID_HANDLE);
assert_eq!(guest.call("CloseHandle", &[old]), 0);
assert_eq!(guest.error(), INVALID_HANDLE);
// Neither stale operation may signal or destroy the replacement.
assert_eq!(
guest.call("WaitForSingleObject", &[replacement, 0]),
WAIT_TIMEOUT
);
assert_eq!(guest.call("SetEvent", &[replacement]), 1);
assert_eq!(guest.call("WaitForSingleObject", &[replacement, 0]), 0);
}
}
#[test]
fn duplicates_share_signal_state_but_keep_independent_rights_and_lifetimes() {
let mut guest = Guest::new(IMPORTS, &[]);
let source = event(&mut guest);
let waiter = copy(&mut guest, source, SYNCHRONIZE, 0);
let setter = copy(&mut guest, source, MODIFY, 0);
assert_eq!(guest.call("SetEvent", &[waiter]), 0);
assert_eq!(guest.error(), ACCESS_DENIED);
assert_eq!(
guest.call("WaitForSingleObject", &[source, 0]),
WAIT_TIMEOUT
);
assert_eq!(guest.call("SetEvent", &[setter]), 1);
assert_eq!(guest.call("WaitForSingleObject", &[setter, 0]), WAIT_FAILED);
assert_eq!(guest.error(), ACCESS_DENIED);
// A denied wait must not consume the auto-reset event's signal.
assert_eq!(guest.call("WaitForSingleObject", &[waiter, 0]), 0);
assert_eq!(
guest.call("WaitForSingleObject", &[source, 0]),
WAIT_TIMEOUT
);
assert_eq!(guest.call("CloseHandle", &[source]), 1);
assert_eq!(guest.call("SetEvent", &[setter]), 1);
assert_eq!(guest.call("WaitForSingleObject", &[waiter, 0]), 0);
// SAME_ACCESS ignores desired access, and must retain the reduced rights.
let second_waiter = copy(&mut guest, waiter, u64::MAX, SAME_ACCESS);
assert_eq!(guest.call("CloseHandle", &[waiter]), 1);
assert_eq!(guest.call("SetEvent", &[second_waiter]), 0);
assert_eq!(guest.error(), ACCESS_DENIED);
assert_eq!(guest.call("SetEvent", &[setter]), 1);
assert_eq!(guest.call("CloseHandle", &[setter]), 1);
assert_eq!(guest.call("WaitForSingleObject", &[second_waiter, 0]), 0);
assert_eq!(
guest.call("WaitForSingleObject", &[second_waiter, 0]),
WAIT_TIMEOUT
);
assert_eq!(guest.call("CloseHandle", &[second_waiter]), 1);
}
#[test]
fn failed_duplicate_outputs_leave_memory_source_and_capacity_unchanged() {
let mut guest = Guest::new(IMPORTS, &[]);
let source = event(&mut guest);
let readonly = 0x6_0000;
guest
.memory
.map_region(readonly, 8, MemoryPermissions::READ_ONLY)
.unwrap();
guest
.memory
.write_u64(SCRATCH + SCRATCH_LEN - 8, SENTINEL)
.unwrap();
assert_eq!(guest.call("SetEvent", &[source]), 1);
for output in [0, readonly, 0xDEAD_0000, SCRATCH + SCRATCH_LEN - 4] {
// Repeated failures must not fill the table with unreachable duplicates.
for _ in 0..CAPACITY {
assert_eq!(duplicate(&mut guest, source, output, 0, SAME_ACCESS), 0);
assert_eq!(guest.error(), NOACCESS);
}
}
assert_eq!(guest.u64_at(readonly), 0);
assert_eq!(guest.u64_at(SCRATCH + SCRATCH_LEN - 8), SENTINEL);
assert_eq!(guest.call("WaitForSingleObject", &[source, 0]), 0);
assert_eq!(
guest.call("WaitForSingleObject", &[source, 0]),
WAIT_TIMEOUT
);
// All remaining slots must still be available after the failed calls.
for _ in 1..CAPACITY {
event(&mut guest);
}
assert_eq!(guest.call("CreateEventW", &[0, 0, 0, 0]), 0);
assert_eq!(guest.error(), 8);
}
#[test]
fn wrong_types_and_rights_escalation_preserve_objects_and_output() {
let mut guest = Guest::new(IMPORTS, &[]);
let source = event(&mut guest);
let semaphore = guest.call("CreateSemaphoreW", &[0, 1, 2, 0]);
assert_ne!(semaphore, 0);
assert_eq!(guest.call("SetEvent", &[semaphore]), 0);
assert_eq!(guest.error(), INVALID_HANDLE);
assert_eq!(guest.call("ReleaseSemaphore", &[source, 1, 0]), 0);
assert_eq!(guest.error(), INVALID_HANDLE);
for handle in [source, semaphore] {
assert_eq!(guest.call("GetThreadId", &[handle]), 0);
assert_eq!(guest.error(), INVALID_HANDLE);
}
assert_eq!(guest.call("WaitForSingleObject", &[semaphore, 0]), 0);
assert_eq!(
guest.call("WaitForSingleObject", &[semaphore, 0]),
WAIT_TIMEOUT
);
assert_eq!(
guest.call("WaitForSingleObject", &[source, 0]),
WAIT_TIMEOUT
);
let waiter = copy(&mut guest, source, SYNCHRONIZE, 0);
guest.memory.write_u64(SCRATCH, SENTINEL).unwrap();
assert_eq!(duplicate(&mut guest, waiter, SCRATCH, MODIFY, 0), 0);
assert_eq!(guest.error(), ACCESS_DENIED);
assert_eq!(guest.u64_at(SCRATCH), SENTINEL);
assert_eq!(guest.call("SetEvent", &[source]), 1);
assert_eq!(guest.call("WaitForSingleObject", &[waiter, 0]), 0);
assert_eq!(guest.call("CloseHandle", &[waiter]), 1);
assert_eq!(duplicate(&mut guest, waiter, SCRATCH, 0, SAME_ACCESS), 0);
assert_eq!(guest.error(), INVALID_HANDLE);
assert_eq!(guest.u64_at(SCRATCH), SENTINEL);
}
#[test]
fn thread_pseudo_handle_survives_real_duplicate_closure() {
let mut guest = Guest::new(IMPORTS, &[]);
let pseudo = guest.call("GetCurrentThread", &[]);
let id = guest.call("GetCurrentThreadId", &[]);
let first = copy(&mut guest, pseudo, 0x0800, 0); // THREAD_QUERY_LIMITED_INFORMATION
assert_eq!(guest.call("GetThreadId", &[first]), id);
assert_eq!(guest.call("CloseHandle", &[first]), 1);
let second = copy(&mut guest, pseudo, 0x0800, 0);
assert_ne!(first, second);
assert_eq!(guest.call("GetThreadId", &[first]), 0);
assert_eq!(guest.error(), INVALID_HANDLE);
assert_eq!(guest.call("GetThreadId", &[second]), id);
assert_eq!(guest.call("GetThreadId", &[pseudo]), id);
assert_eq!(guest.call("CloseHandle", &[second]), 1);
assert_eq!(guest.call("GetThreadId", &[pseudo]), id);
}
+130
View File
@@ -0,0 +1,130 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Thread-local storage layout as compiled code reads it (#76).
//!
//! Microsoft's public PE Format page ("The .tls Section") describes the
//! access: load the address of the thread's TLS array from the thread
//! environment block, load the module's TLS index from the address the TLS
//! directory names, use the index times the pointer size as an offset into
//! the array to get the address of the module's data block, then add the
//! variable's offset in the template. The block starts as a copy of the
//! template followed by `SizeOfZeroFill` zero bytes.
//!
//! The startup harness stores the `thread_tls_base` it passes to `setup_tls`
//! in the TEB's TLS pointer field, so these tests start from that value and
//! follow the same steps through guest memory. The directory and template are
//! original. Nothing here ran on Windows.
use xenora_loader::{GuestMemory, MemoryError, MemoryPermissions as P, TlsDirectory, setup_tls};
const IMAGE: u64 = 0x1_4000_0000;
const TEMPLATE: u64 = IMAGE + 0x3000;
const INDEX: u64 = IMAGE + 0x4000;
const THREAD_TLS: u64 = 0x3_0000_0000;
/// Read as a pointer, the first eight bytes are the template's own address, so
/// a layout that takes the data for the array still finds readable memory.
const TEMPLATE_BYTES: [u8; 20] = [
0x00, 0x30, 0x00, 0x40, 0x01, 0x00, 0x00, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88,
0xA1, 0xB2, 0xC3, 0xD4,
];
fn directory(template_len: u64, zero_fill: u32) -> TlsDirectory {
TlsDirectory {
raw_data_start_va: TEMPLATE,
raw_data_end_va: TEMPLATE + template_len,
index_address: INDEX,
size_of_zero_fill: zero_fill,
..TlsDirectory::default()
}
}
/// An image with the template in read-only data and a writable index that
/// does not start at zero.
fn image(base: u64) -> GuestMemory {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(
TEMPLATE - IMAGE + base,
0x1000,
P::READ_ONLY,
&TEMPLATE_BYTES,
)
.unwrap();
memory
.map_region_with_data(INDEX - IMAGE + base, 0x1000, P::READ_WRITE, &[0xFF; 8])
.unwrap();
memory
}
/// The address of the module's data block, found the way compiled code does.
fn block_address(memory: &GuestMemory, teb_tls_pointer: u64, index_address: u64) -> u64 {
let index = u64::from(memory.read_u32(index_address).unwrap());
memory.read_u64(teb_tls_pointer + index * 8).unwrap()
}
#[test]
fn the_tls_array_slot_leads_to_a_copy_of_the_template() {
let mut memory = image(IMAGE);
setup_tls(&directory(20, 12), IMAGE, IMAGE, &mut memory, THREAD_TLS).unwrap();
assert_eq!(memory.read_u32(INDEX), Ok(0));
let block = block_address(&memory, THREAD_TLS, INDEX);
assert_ne!(block, THREAD_TLS, "the array is not the data block");
assert_ne!(block, TEMPLATE, "the block is the thread's own copy");
let mut data = [0xEEu8; 32];
memory.read_bytes(block, &mut data).unwrap();
assert_eq!(data[..20], TEMPLATE_BYTES);
assert_eq!(data[20..], [0u8; 12]);
}
#[test]
fn the_thread_block_is_writable_and_separate_from_the_template() {
let mut memory = image(IMAGE);
setup_tls(&directory(20, 12), IMAGE, IMAGE, &mut memory, THREAD_TLS).unwrap();
let block = block_address(&memory, THREAD_TLS, INDEX);
memory.write_u64(block + 8, 0x0102_0304_0506_0708).unwrap();
assert_eq!(memory.read_u64(block + 8), Ok(0x0102_0304_0506_0708));
// The image's template is the initial value for later threads.
let mut template = [0u8; 20];
memory.read_bytes(TEMPLATE, &mut template).unwrap();
assert_eq!(template, TEMPLATE_BYTES);
// The array slot still names the block after the block is written.
assert_eq!(block_address(&memory, THREAD_TLS, INDEX), block);
}
#[test]
fn a_rebased_image_uses_its_loaded_addresses() {
let loaded = IMAGE + 0x20_0000;
let mut memory = image(loaded);
setup_tls(&directory(20, 0), loaded, IMAGE, &mut memory, THREAD_TLS).unwrap();
let index_address = INDEX - IMAGE + loaded;
assert_eq!(memory.read_u32(index_address), Ok(0));
let block = block_address(&memory, THREAD_TLS, index_address);
let mut data = [0u8; 20];
memory.read_bytes(block, &mut data).unwrap();
assert_eq!(data, TEMPLATE_BYTES);
}
#[test]
fn a_zero_fill_only_directory_gets_a_zeroed_block() {
let mut memory = image(IMAGE);
setup_tls(&directory(0, 24), IMAGE, IMAGE, &mut memory, THREAD_TLS).unwrap();
let block = block_address(&memory, THREAD_TLS, INDEX);
let mut data = [0xEEu8; 24];
memory.read_bytes(block, &mut data).unwrap();
assert_eq!(data, [0u8; 24]);
}
#[test]
fn an_inverted_template_range_is_rejected_before_anything_is_mapped() {
let mut memory = image(IMAGE);
let mut inverted = directory(20, 0);
inverted.raw_data_end_va = TEMPLATE - 1;
assert!(setup_tls(&inverted, IMAGE, IMAGE, &mut memory, THREAD_TLS).is_err());
assert_eq!(
memory.read_u64(THREAD_TLS),
Err(MemoryError::UnmappedAddress(THREAD_TLS))
);
}
+8 -1
View File
@@ -96,8 +96,15 @@ def cases():
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", "cpuid",
"nop dword ptr [rax + 8]", "pause", "push r9", "push rbx", "push -5", "push 0x12345678",
"nop dword ptr [rax + 8]", "pause", "lfence", "mfence", "sfence",
f"movnti {mem(32)}, ebx", f"movnti {mem(64)}, rbx",
f"movnti {mem(32)}, r9d", f"movnti {mem(64)}, r14", "push r9", "push rbx", "push -5", "push 0x12345678",
f"push {mem(64)}", "pop rbx", "pop r12", f"pop {mem(64)}", "leave"]
# The accumulator short form of XCHG: 91..97, and 90 with REX.B.
for index in range(1, 16):
bits = (16, 32, 64)[index % 3]
out.append(f"xchg {reg(0, bits)}, {reg(index, bits)}")
out += ["xchg r8w, ax", "xchg r8, rax", "xchg r8d, eax", "xchg ecx, eax", "xchg r15w, ax"]
return list(dict.fromkeys(out))
+27
View File
@@ -1117,6 +1117,13 @@ f5 | cmc
0f a2 | cpuid
0f 1f 40 08 | nop dword ptr [rax + 8]
f3 90 | pause
0f ae e8 | lfence
0f ae f0 | mfence
0f ae f8 | sfence
0f c3 5c be 10 | movnti dword ptr [rsi + 4*rdi + 16], ebx
48 0f c3 5c be 10 | movnti qword ptr [rsi + 4*rdi + 16], rbx
44 0f c3 4c be 10 | movnti dword ptr [rsi + 4*rdi + 16], r9d
4c 0f c3 74 be 10 | movnti qword ptr [rsi + 4*rdi + 16], r14
41 51 | push r9
53 | push rbx
6a fb | push -5
@@ -1126,3 +1133,23 @@ ff 74 be 10 | push qword ptr [rsi + 4*rdi + 16]
41 5c | pop r12
8f 44 be 10 | pop qword ptr [rsi + 4*rdi + 16]
c9 | leave
91 | xchg eax, ecx
48 92 | xchg rax, rdx
66 93 | xchg ax, bx
94 | xchg eax, esp
48 95 | xchg rax, rbp
66 96 | xchg ax, si
97 | xchg eax, edi
49 90 | xchg rax, r8
66 41 91 | xchg ax, r9w
41 92 | xchg eax, r10d
49 93 | xchg rax, r11
66 41 94 | xchg ax, r12w
41 95 | xchg eax, r13d
49 96 | xchg rax, r14
66 41 97 | xchg ax, r15w
66 41 90 | xchg r8w, ax
49 90 | xchg r8, rax
41 90 | xchg r8d, eax
91 | xchg ecx, eax
66 41 97 | xchg r15w, ax
+384
View File
@@ -0,0 +1,384 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Multiword ADC and SBB carry chains through the interpreter and the native
//! DBT.
//!
//! Encodings were assembled with LLVM (`llvm-mc -triple=x86_64`, Intel syntax).
//! Expected values come from widening `u128` and `i128` arithmetic over the
//! limbs, following the ADC and SBB operation sections of the Intel SDM Vol. 2:
//! DEST = DEST + SRC + CF and DEST = DEST - (SRC + CF). They never read the
//! production semantics. Both engines must also agree on the complete state,
//! including PF and AF, which the reference does not model.
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter};
use xenora_loader::dbt::{DbtEngine, is_native};
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
use xenora_loader::x86_decode::decode;
use xenora_loader::x86_table::Op;
const ENTRY: u64 = 0x1000;
/// `jmp +0`: ends the translated block, so the next instruction reads CF from
/// the guest state stored by the previous block.
const JMP: [u8; 2] = [0xEB, 0x00];
const HLT: u8 = 0xF4;
/// Limb registers: A in RAX, RBX, RCX, RDX and B in R8 to R11.
const A: [usize; 4] = [0, 3, 1, 2];
const B: [usize; 4] = [8, 9, 10, 11];
// add rax, r8; adc rbx, r9; adc rcx, r10; adc rdx, r11 (and the SUB/SBB and
// 32-bit equivalents).
const ADD64: [&[u8]; 4] = [
&[0x4C, 0x01, 0xC0],
&[0x4C, 0x11, 0xCB],
&[0x4C, 0x11, 0xD1],
&[0x4C, 0x11, 0xDA],
];
const SUB64: [&[u8]; 4] = [
&[0x4C, 0x29, 0xC0],
&[0x4C, 0x19, 0xCB],
&[0x4C, 0x19, 0xD1],
&[0x4C, 0x19, 0xDA],
];
const ADD32: [&[u8]; 4] = [
&[0x44, 0x01, 0xC0],
&[0x44, 0x11, 0xCB],
&[0x44, 0x11, 0xD1],
&[0x44, 0x11, 0xDA],
];
const SUB32: [&[u8]; 4] = [
&[0x44, 0x29, 0xC0],
&[0x44, 0x19, 0xCB],
&[0x44, 0x19, 0xD1],
&[0x44, 0x19, 0xDA],
];
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Chain {
Add,
Sub,
}
/// Expected limbs and CF, ZF, SF, OF of the last limb.
#[derive(PartialEq, Eq, Debug)]
struct Expected {
limbs: [u64; 4],
cf: bool,
zf: bool,
sf: bool,
of: bool,
}
fn reference(chain: Chain, bits: u32, a: [u64; 4], b: [u64; 4]) -> Expected {
let mask = if bits == 64 {
u64::MAX
} else {
(1u64 << bits) - 1
};
let modulus = 1u128 << bits;
let signed = |value: u64| -> i128 {
let value = i128::from(value & mask);
if value >= (1i128 << (bits - 1)) {
value - (1i128 << bits)
} else {
value
}
};
let mut limbs = [0; 4];
let mut carry = 0u128;
let mut of = false;
for i in 0..4 {
let (x, y) = (u128::from(a[i] & mask), u128::from(b[i] & mask));
let wide = match chain {
Chain::Add => x + y + carry,
Chain::Sub => x + modulus - y - carry,
};
limbs[i] = (wide % modulus) as u64;
let exact = match chain {
Chain::Add => signed(a[i]) + signed(b[i]) + carry as i128,
Chain::Sub => signed(a[i]) - signed(b[i]) - carry as i128,
};
of = exact != signed(limbs[i]);
carry = match chain {
Chain::Add => u128::from(wide >= modulus),
Chain::Sub => u128::from(y + carry > x),
};
}
Expected {
limbs,
cf: carry != 0,
zf: limbs[3] == 0,
sf: limbs[3] >> (bits - 1) & 1 != 0,
of,
}
}
fn program(parts: &[&[u8]], split: bool) -> Vec<u8> {
let mut code = Vec::new();
for (i, part) in parts.iter().enumerate() {
if split && i > 0 {
code.extend_from_slice(&JMP);
}
code.extend_from_slice(part);
}
code.push(HLT);
code
}
fn load(code: &[u8], gpr: [u64; 16], cf: bool) -> (CpuState, GuestMemory) {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, code)
.unwrap();
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr = gpr;
cpu.flags.cf = cf;
(cpu, memory)
}
/// Run `code` to its HLT in both engines, check they agree on the whole state
/// and that the DBT never left native code, and return the final state.
fn run_both(code: &[u8], gpr: [u64; 16], cf: bool, context: &str) -> CpuState {
let (cpu, mut memory) = load(code, gpr, cf);
let interpreted = Interpreter::new(cpu, &mut memory, 64).run();
let (mut cpu, mut memory) = load(code, gpr, cf);
let mut engine = DbtEngine::new(16 * 1024).unwrap();
let translated = engine.run(&mut cpu, &mut memory, 64);
assert_eq!(interpreted.exit_reason, ExitReason::Halt, "{context}");
assert_eq!(translated.exit_reason, ExitReason::Halt, "{context}");
assert_eq!(translated.final_state, interpreted.final_state, "{context}");
assert_eq!(engine.metrics.interpreter_fallbacks, 0, "{context}");
interpreted.final_state
}
struct Random(u64);
impl Random {
fn next(&mut self) -> u64 {
self.0 ^= self.0 >> 12;
self.0 ^= self.0 << 25;
self.0 ^= self.0 >> 27;
self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
}
}
/// Limb values at the carry and overflow boundaries of a `bits`-wide limb.
fn edges(bits: u32) -> [u64; 6] {
let max = if bits == 64 {
u64::MAX
} else {
(1u64 << bits) - 1
};
let sign = 1u64 << (bits - 1);
[0, 1, max - 1, max, sign, sign - 1]
}
fn operand_sets(bits: u32) -> Vec<([u64; 4], [u64; 4])> {
let edges = edges(bits);
let mut sets = Vec::new();
for &x in &edges {
for &y in &edges {
sets.push(([x; 4], [y; 4]));
sets.push(([x, y, x, y], [y, x, y, x]));
}
}
let mut random = Random(0x0195_ADC5_BB00_0001);
for _ in 0..256 {
let mut pick = || {
let raw = random.next();
if raw & 3 == 0 {
edges[(raw >> 8) as usize % edges.len()] | raw & !edges[3]
} else {
raw
}
};
let a = [pick(), pick(), pick(), pick()];
let b = [pick(), pick(), pick(), pick()];
sets.push((a, b));
}
sets
}
fn check_chain(chain: Chain, bits: u32, parts: [&[u8]; 4]) {
for part in &parts[1..] {
let insn = decode(ENTRY, |address| {
part.get((address - ENTRY) as usize).copied().ok_or(())
})
.unwrap();
assert!(matches!(insn.op, Op::Adc | Op::Sbb));
assert!(is_native(&insn), "{:?}", insn.op);
}
let mut random = Random(u64::from(bits) << 8 | chain as u64);
for (a, b) in operand_sets(bits) {
let expected = reference(chain, bits, a, b);
for split in [false, true] {
let code = program(&parts, split);
let mut gpr: [u64; 16] = std::array::from_fn(|_| random.next());
for i in 0..4 {
gpr[A[i]] = a[i];
gpr[B[i]] = b[i];
}
// The leading ADD or SUB must ignore the incoming carry.
for cf in [false, true] {
let context = format!("{chain:?}{bits} split={split} cf={cf} a={a:x?} b={b:x?}");
let state = run_both(&code, gpr, cf, &context);
let limbs = A.map(|index| state.gpr[index]);
// A 32-bit destination clears bits 63:32.
assert_eq!(limbs, expected.limbs, "{context}");
assert_eq!(B.map(|index| state.gpr[index]), b, "{context}");
let flags = (
state.flags.cf,
state.flags.zf,
state.flags.sf,
state.flags.of,
);
let wanted = (expected.cf, expected.zf, expected.sf, expected.of);
assert_eq!(flags, wanted, "{context}");
}
}
}
}
#[test]
fn reference_matches_native_wide_arithmetic() {
// 128-bit sanity checks of the reference itself on the low two limbs.
let cases = [
(u128::MAX, 1u128),
(0, 1),
(1u128 << 64, 1),
(0x8000_0000_0000_0000_0000_0000_0000_0000, 1),
];
for (x, y) in cases {
let a = [x as u64, (x >> 64) as u64, 0, 0];
let b = [y as u64, (y >> 64) as u64, 0, 0];
let sum = reference(Chain::Add, 64, a, b);
let expected = x.wrapping_add(y);
assert_eq!(sum.limbs[0], expected as u64);
assert_eq!(sum.limbs[1], (expected >> 64) as u64);
let difference = reference(Chain::Sub, 64, a, b);
let expected = x.wrapping_sub(y);
assert_eq!(difference.limbs[0], expected as u64);
assert_eq!(difference.limbs[1], (expected >> 64) as u64);
// The upper limbs are zero, so the 256-bit borrow is the 128-bit one.
assert_eq!(difference.cf, y > x);
}
}
#[test]
fn add_adc_chains_of_64_bit_limbs_carry_across_blocks() {
check_chain(Chain::Add, 64, ADD64);
}
#[test]
fn sub_sbb_chains_of_64_bit_limbs_borrow_across_blocks() {
check_chain(Chain::Sub, 64, SUB64);
}
#[test]
fn add_adc_chains_of_32_bit_limbs_carry_across_blocks() {
check_chain(Chain::Add, 32, ADD32);
}
#[test]
fn sub_sbb_chains_of_32_bit_limbs_borrow_across_blocks() {
check_chain(Chain::Sub, 32, SUB32);
}
#[test]
fn split_chains_run_one_block_per_limb() {
let code = program(&ADD64, true);
let (mut cpu, mut memory) = load(&code, [0; 16], false);
let mut engine = DbtEngine::new(16 * 1024).unwrap();
let result = engine.run(&mut cpu, &mut memory, 64);
assert_eq!(result.exit_reason, ExitReason::Halt);
assert_eq!(engine.metrics.blocks_compiled, 4);
assert_eq!(engine.metrics.interpreter_fallbacks, 0);
}
#[test]
fn immediate_forms_increment_and_decrement_a_128_bit_value() {
// add rax, 1; adc rbx, 0 and sub rax, 1; sbb rbx, 0.
let increment: [&[u8]; 2] = [&[0x48, 0x83, 0xC0, 0x01], &[0x48, 0x83, 0xD3, 0x00]];
let decrement: [&[u8]; 2] = [&[0x48, 0x83, 0xE8, 0x01], &[0x48, 0x83, 0xDB, 0x00]];
let values = [
0u128,
1,
u64::MAX as u128,
1u128 << 64,
u128::MAX,
u128::MAX - 1,
1u128 << 127,
(1u128 << 127) - 1,
];
for value in values {
for split in [false, true] {
for (parts, expected, carry, overflow) in [
(
&increment,
value.wrapping_add(1),
value == u128::MAX,
value == (1u128 << 127) - 1,
),
(
&decrement,
value.wrapping_sub(1),
value == 0,
value == 1u128 << 127,
),
] {
let code = program(parts, split);
let mut gpr = [0x5A5A_5A5A_5A5A_5A5A; 16];
gpr[0] = value as u64;
gpr[3] = (value >> 64) as u64;
let context = format!("{value:#x} split={split} {:x?}", parts[0]);
let state = run_both(&code, gpr, true, &context);
assert_eq!(state.gpr[0], expected as u64, "{context}");
assert_eq!(state.gpr[3], (expected >> 64) as u64, "{context}");
assert_eq!(state.flags.cf, carry, "{context}");
assert_eq!(state.flags.of, overflow, "{context}");
assert_eq!(state.flags.zf, (expected >> 64) == 0, "{context}");
assert_eq!(state.flags.sf, expected >> 127 != 0, "{context}");
}
}
}
}
#[test]
fn sbb_of_a_register_with_itself_materializes_the_carry_mask() {
// sbb esi, esi and sbb rsi, rsi give -CF and borrow exactly when CF was
// set; adc edi, 0 adds CF to 0x89ABCDEF without a carry out. The 32-bit
// forms clear bits 63:32.
// (code, destination register, value from CF, CF out from CF in)
type Case = (&'static [u8], usize, fn(bool) -> u64, fn(bool) -> bool);
let cases: [Case; 3] = [
(
&[0x19, 0xF6],
6,
|cf| if cf { 0xFFFF_FFFF } else { 0 },
|cf| cf,
),
(
&[0x48, 0x19, 0xF6],
6,
|cf| if cf { u64::MAX } else { 0 },
|cf| cf,
),
(
&[0x83, 0xD7, 0x00],
7,
|cf| u64::from(cf) + 0x89AB_CDEF,
|_| false,
),
];
for (code, register, value, carry) in cases {
for cf in [false, true] {
let mut gpr = [0x0123_4567_89AB_CDEF; 16];
gpr[6] = 0xDEAD_BEEF_0000_0001;
let program = [code, &[HLT]].concat();
let context = format!("{code:x?} cf={cf}");
let state = run_both(&program, gpr, cf, &context);
assert_eq!(state.gpr[register], value(cf), "{context}");
assert_eq!(state.flags.cf, carry(cf), "{context}");
}
}
}
+9 -3
View File
@@ -637,7 +637,8 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
..none
})
}
"mov" | "movabs" => {
// MOVNTI stores like MOV; the non-temporal hint changes no result.
"mov" | "movabs" | "movnti" => {
let value = read(m, places[1], bits);
write(m, places[0], value);
Outcome::Done(none)
@@ -738,7 +739,8 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
m.flags.cf = !m.flags.cf;
Outcome::Done(none)
}
"nop" | "pause" => Outcome::Done(none),
// The fences order memory accesses and compute nothing.
"nop" | "pause" | "lfence" | "mfence" | "sfence" => Outcome::Done(none),
"cpuid" => {
// Xenora's guest CPUID contract, restated: the vendor "Xenora guest"
// and the four features whose every instruction exists, CMOV and
@@ -1232,8 +1234,12 @@ fn undeclared_and_ambiguous_encodings_are_rejected() {
&[0x66, 0xE8, 0, 0], // call rel16
&[0x66, 0x0F, 0xC9], // bswap cx (undefined)
&[0x66, 0x63, 0xC1], // 16-bit movsxd
&[0x41, 0x90], // xchg r8, rax
&[0xF3, 0x41, 0x90], // F3 on xchg r8, rax
&[0x8D, 0xC0], // lea with a register operand
&[0x0F, 0xAE, 0x2E], // 0F AE /5 with a memory operand
&[0x0F, 0xAE, 0x36], // 0F AE /6 with a memory operand
&[0x0F, 0xC3, 0xC1], // movnti with a register destination
&[0x66, 0x0F, 0xC3, 0x06], // 66 with movnti
&[0x0F, 0xA3, 0x06], // bt [rsi], eax
&[0xC6, 0xC8, 0x01], // C6 /1
&[0xFF, 0xF8], // FF /7
+87
View File
@@ -108,6 +108,7 @@ movups = { ref = "sdm MOVUPS" }
movdqa = { ref = "sdm MOVDQA" }
movdqu = { ref = "sdm MOVDQU" }
movntdq = { ref = "sdm MOVNTDQ" }
movnti = { ref = "sdm MOVNTI" }
movntps = { ref = "sdm MOVNTPS/MOVNTPD" }
movss = { ref = "sdm MOVSS" }
movsd = { ref = "sdm MOVSD (scalar double)" }
@@ -185,6 +186,9 @@ shufpd = { ref = "sdm SHUFPD" }
pinsrw = { ref = "sdm PINSRW" }
pextrw = { ref = "sdm PEXTRW" }
ldmxcsr = { ref = "sdm LDMXCSR" }
lfence = { ref = "sdm LFENCE" }
mfence = { ref = "sdm MFENCE" }
sfence = { ref = "sdm SFENCE" }
stmxcsr = { ref = "sdm STMXCSR" }
# Floating point. Every form can raise a SIMD floating-point exception.
@@ -403,6 +407,51 @@ opcode = 0x87
enc = "rm_reg"
size = "v"
# The accumulator with the register in the opcode. Opcode 0x90 is NOP; with
# REX.B the decoder reads it as 0x91 with register 0, which is then r8. A row
# of eight would have to start at 0x90, so each opcode is its own form.
[[form]]
op = "xchg"
opcode = 0x91
enc = "op_reg"
size = "v"
[[form]]
op = "xchg"
opcode = 0x92
enc = "op_reg"
size = "v"
[[form]]
op = "xchg"
opcode = 0x93
enc = "op_reg"
size = "v"
[[form]]
op = "xchg"
opcode = 0x94
enc = "op_reg"
size = "v"
[[form]]
op = "xchg"
opcode = 0x95
enc = "op_reg"
size = "v"
[[form]]
op = "xchg"
opcode = 0x96
enc = "op_reg"
size = "v"
[[form]]
op = "xchg"
opcode = 0x97
enc = "op_reg"
size = "v"
[[form]]
op = "mov"
opcode = 0x88
@@ -905,6 +954,14 @@ size = "x"
src = "x"
memory_only = true
[[form]]
op = "movnti"
map = "0f"
opcode = 0xC3
enc = "rm_reg"
size = "y"
memory_only = true
[[form]]
op = "movntps"
map = "0f"
@@ -1922,6 +1979,36 @@ size = "n"
src = "d"
memory_only = true
# The fences are the register forms of digits 5 to 7; the r/m field is ignored.
# The memory forms of those digits (the XSAVE family and CLFLUSH) are not
# declared.
[[form]]
op = "lfence"
map = "0f"
opcode = 0xAE
digit = 5
enc = "rm_unread"
size = "n"
register_only = true
[[form]]
op = "mfence"
map = "0f"
opcode = 0xAE
digit = 6
enc = "rm_unread"
size = "n"
register_only = true
[[form]]
op = "sfence"
map = "0f"
opcode = 0xAE
digit = 7
enc = "rm_unread"
size = "n"
register_only = true
# SSE and SSE2 floating-point forms. RCP and RSQRT approximations are not
# architecturally exact and are left out.
+1
View File
@@ -43,6 +43,7 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
- [Testing and acceptance index](testing/README.md) — Entry point for test procedures, evidence and review records.
- [AMD RDNA2 desktop GPU (gfx1030) form acceptance](testing/shader-form-acceptance.md) — Independence, command, log and promotion rules for fixture-verified instruction forms.
- [Engineering progress](progress.md) — Verification commands, metric definitions, and open release gates.
- [CPU test runtime and shard selection](testing/cpu-coverage.md) — Measured CPU gate cost and deterministic test-target shards.
- [Test inventory comparison](testing/test-inventory.md) — Detect missing or newly ignored Cargo tests across commits.
- [Persistent resource and translated rendering acceptance](testing/x9-acceptance.md) — Pinned upstream tests, native ARM64 results and unsupported cases.
- [Baseline acceptance](testing/phase-02-baseline.md), [Phase 01 assurance](testing/phase01-assurance.md), and [independent reviews](testing/review-log.md) — Candidate-specific results and release findings.
+13 -4
View File
@@ -40,8 +40,9 @@ XMM registers live in `CpuState::xmm`, lane 0 in the low bits, and MXCSR in `Cpu
- 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.
- DAZ applies before conversion to an integer.
An unmasked overflow records precision only when rounding with an unbounded exponent is inexact (Intel SDM Vol. 1, D.4.2.3, Table D-16). The known-answer cases in `tests/cpu_known_answers.rs` assert this.
None of it has been compared with x86 hardware.
@@ -59,6 +60,14 @@ These rules hold for both engines and are what a guest scheduler has to preserve
The SDM cases for these forms in `tests/cpu_known_answers.rs` were written before this implementation, by another contributor. `tests/x86_atomic.rs` adds the LOCK rules, both compare outcomes at every width, unaligned operands and faults. None of it has been compared with x86 hardware, and nothing here establishes multi-thread behaviour.
## Memory ordering and fences
Guest memory accesses are totally ordered today. Each engine runs one guest instruction at a time on one host thread, and every load and store of an instruction completes before the next instruction starts. There is no store buffer and nothing is reordered, so a load always sees the latest earlier store. That is stronger than the ordering the Intel SDM (Vol. 3A, "Memory Ordering") gives a real processor, where a store may sit in a buffer while later loads from other locations run.
MFENCE, LFENCE and SFENCE (`0F AE` with a register ModRM byte and digit 6, 5 or 7; the SDM states that the r/m field is ignored) are therefore accepted and change no register, flag or memory. They have nothing left to enforce. Non-temporal stores are ordinary stores, so SFENCE has no weakly ordered store to wait for either. The memory forms that share those digits, the XSAVE family and CLFLUSH, stay rejected.
This holds only while guest threads do not run on several host threads. ARM64 orders memory more weakly than x86, so an engine that ran guest threads in parallel would have to restore x86's ordering for ordinary accesses and give the fences a real effect. Nothing here provides or tests that. `tests/cpu_known_answers.rs` holds the single-thread cases: a store, a fence and a later load in program order, and no change to any other state. None of it has been compared with x86 hardware.
## String instructions
MOVS and STOS exist for 8-, 16-, 32- and 64-bit elements, alone and with REP (F3), together with the direction flag and CLD and STD. `CpuState::df` holds the flag. It is not one of the six status flags the registry tracks.
@@ -85,7 +94,7 @@ CPUID (`0F A2`) returns a fixed table that never reads the host. It describes a
A feature bit is set only when every instruction of that feature is implemented. That is stricter than "some of it works", and it has consequences:
- SSE and SSE2 are not reported, although most of their instructions exist, because parts are still rejected: RSQRTPS and MFENCE, for example. BMI1 is not reported although TZCNT exists, because ANDN does not. The x87 FPU, MMX, FXSAVE, CMPXCHG8B, the time-stamp counter, LAHF and SYSRET are absent too.
- SSE and SSE2 are not reported, although most of their instructions exist, because parts are still rejected: RSQRTPS and MASKMOVDQU, for example. BMI1 is not reported although TZCNT exists, because ANDN does not. The x87 FPU, MMX, FXSAVE, CMPXCHG8B, the time-stamp counter, LAHF and SYSRET are absent too.
- The table is therefore truthful about Xenora, not plausible as hardware: every real 64-bit processor reports the FPU and SSE2. A guest that tests a bit before using a feature avoids it; a guest that assumes SSE2 because it runs in 64-bit mode still gets every form that exists and an illegal-instruction exit for one that does not.
- A leaf that is not listed returns zeros, whatever the subleaf. Intel processors answer a leaf above the highest basic one with that leaf's data instead; software is expected to read the highest leaf first.
@@ -95,4 +104,4 @@ A feature bit is set only when every instruction of that feature is implemented.
## Rejected on purpose
LOCK except as described above, F2 or F3 where it is neither PAUSE nor part of a declared form, F2 combined with F3, address-size overrides, an ignored segment override after FS or GS, 16-bit stack and branch forms, 16-bit BSWAP and MOVSXD, bit tests of memory by a register index, SHLD, SHRD, LODS, CMPS, SCAS, REPE and REPNE, MMX, the RCP and RSQRT approximations, SSE3 and later, VEX, CMPXCHG8B, CMPXCHG16B and fences. The DBT also refuses raw SYSCALL.
LOCK except as described above, F2 or F3 where it is neither PAUSE nor part of a declared form, F2 combined with F3, address-size overrides, an ignored segment override after FS or GS, 16-bit stack and branch forms, 16-bit BSWAP and MOVSXD, bit tests of memory by a register index, SHLD, SHRD, LODS, CMPS, SCAS, REPE and REPNE, MMX, the RCP and RSQRT approximations, SSE3 and later, VEX, CMPXCHG8B and CMPXCHG16B. The DBT also refuses raw SYSCALL.
+2 -1
View File
@@ -70,7 +70,8 @@ uses a Win64-aligned stack and terminates with HLT. The result includes the load
guest memory and the entry execution outcome.
`xenora probe --mode static` inventories ordinary and delay-loaded PE imports
without guest execution. `missing_imports.csv` lists unresolved ordinary keys
without guest execution. Without `--report` it writes to `diagnostics/probe`,
where `xenora imports sync` also looks. `missing_imports.csv` lists unresolved ordinary keys
with their import address table relative virtual addresses. The full inventory,
`imports.csv`, marks each entry `ordinary` or `delayed` in its `import_table`
column and records whether each key is registered, its implementation
+98
View File
@@ -0,0 +1,98 @@
# CPU test runtime and shard selection
This page records what the CPU test gate costs and describes
`scripts/cpu-tests.sh`, which splits that gate into deterministic shards. The
shards are a convenience for local iteration and parallel runners. They do not
replace any gate: `cargo test --locked --workspace` stays the full CPU gate, and
`scripts/test-gpu.sh` stays the GPU gate.
## What counts as a CPU test
A CPU test is any test target that `cargo test --locked --workspace` builds with
default features. Targets that need a Metal device are either behind the
`gpu-tests` feature (`xenora-metal`, `xenora-loader`, `xenora-ffi`) or marked
`#[ignore = "requires a native Metal device ..."]` (for example
`tests/validation/known_answers.rs`), so the default run does not execute them.
`scripts/test-gpu.sh` runs them. The selection uses Cargo's own target list, so
it never decides by file name which tests are CPU tests.
One exception: two `xenora-ffi` library tests
(`test_resource_management_lifecycle_and_validation` and
`test_deferred_resource_retirement_waits_for_in_flight`) call
`xenora_session_create_texture`. When a Metal device is available, that
function creates one and uploads a texture; when none is available, it
continues without one. So on a Mac these default tests do touch Metal, and they
are not GPU verification. The selection keeps them because the full gate runs
them.
## Usage
```sh
scripts/cpu-tests.sh --list # every default-feature test target, sorted
scripts/cpu-tests.sh --shard 2/3 # run shard 2 of 3
scripts/cpu-tests.sh --check 3 # show that 3 shards cover every target once
```
Targets are sorted by package, kind and name. Shard K of N takes each target
whose zero-based index i satisfies i mod N = K - 1. Shard 1 also runs the
workspace doctests. A new target joins a shard without any edit to the script.
The script exits 1 when any selected target fails or when Cargo cannot build the
workspace. Partial target lists never run. It exits 2 on bad arguments.
It uses at most four Cargo build jobs unless `CARGO_BUILD_JOBS` says otherwise.
## Measurements
Host: Apple M4 (10 cores), macOS on ARM64, `cargo 1.100.0`, target
`aarch64-apple-darwin`, debug test profile, main at `d7f7d58`. All runs used a
warm build unless noted. These are single-host samples, not benchmarks.
Full gate, `cargo test --locked --workspace`, three runs: 40.47 s, 39.99 s and
40.12 s wall time. It ran 82 test targets plus doctests (92 `test result` lines):
681 passed, 0 failed, 34 ignored.
Running each target alone through `cargo test -p <package> <selector>` adds up
to 79.5 s, because every invocation pays Cargo start-up. The five most expensive
targets, one sample each:
| Target | Wall time | Passed / ignored |
| --- | --- | --- |
| `xenora-loader --test runtime_services` | 19.13 s | 23 / 0 |
| `xenora-loader --test cpu_known_answers` | 8.18 s | 42 / 5 |
| `xenora-loader --test probe_delay_imports` | 3.53 s | 8 / 0 |
| `xenora-loader --test probe_truncation` | 3.32 s | 1 / 0 |
| `xenora-ffi --lib` | 2.16 s | 18 / 0 |
`runtime_services` alone is about a quarter of the summed cost. Any shard that
contains it takes at least about 19 s. The next step for a faster gate is
profiling that target, not finer sharding.
Shard runs, one sample each, sequential on the same host:
| Selection | Wall time per shard | Passed | Failed | Ignored | Result lines |
| --- | --- | --- | --- | --- | --- |
| 2 shards | 37.98 s, 4.55 s | 360 + 321 = 681 | 0 | 21 + 13 = 34 | 51 + 41 = 92 |
| 3 shards | 6.54 s, 29.55 s, 6.27 s | 160 + 282 + 239 = 681 | 0 | 9 + 12 + 13 = 34 | 38 + 27 + 27 = 92 |
For both shard counts, the union of the shards matches the full gate exactly
in passed, failed, ignored and result-line counts. Round-robin by name does
not balance cost: with one dominant target, parallel shards finish no sooner
than the shard that holds it. Running the shards one after another costs more
than the full gate, because each target pays Cargo start-up.
## Verification of the script
- `--check N` for N = 1 to 4 reports that all 82 targets are covered once.
- `--check 3` fails when the selection expression is changed to skip a
residue or to repeat a target.
- `--list` exits 1 with an error when a crate fails to compile, instead of
printing a shortened list.
- Bad arguments (`--shard 0/2`, `--shard 3/2`, `--check x`) exit 2.
## Limitations
- Timings come from one machine and few samples. Re-measure before using them
for decisions.
- Shard membership changes when targets are added or renamed. Shards from two
different commits are not comparable.
- The experiment workspace `experiments/x1` is outside the selection. CI runs
it separately.
+6 -3
View File
@@ -17,10 +17,13 @@ python3 - <<'PY'
import json
from pathlib import Path
import subprocess
import sys
sys.stdout.reconfigure(encoding="utf-8")
executables = set()
for filename in ("native-build.jsonl", "native-tests.jsonl"):
for line in (Path("artifacts") / filename).read_text().splitlines():
for line in (Path("artifacts") / filename).read_text(encoding="utf-8").splitlines():
entry = json.loads(line)
if entry.get("executable"):
executables.add(entry["executable"])
@@ -32,11 +35,11 @@ if not executables:
raise SystemExit("No Cargo executable or loadable dependency artifacts found.")
for path in sorted(executables):
subprocess.run(["file", path], check=True)
archs = subprocess.check_output(["lipo", "-archs", path], text=True).strip()
archs = subprocess.check_output(["lipo", "-archs", path], encoding="utf-8").strip()
print(archs, flush=True)
if archs != "arm64":
raise SystemExit(f"Non-ARM64 build artifact: {path}")
linkage = subprocess.check_output(["otool", "-L", path], text=True)
linkage = subprocess.check_output(["otool", "-L", path], encoding="utf-8")
print(linkage, end="", flush=True)
if any(name in linkage.casefold() for name in ("vulkan", "moltenvk")):
raise SystemExit(f"Unexpected graphics linkage: {path}")
+113
View File
@@ -0,0 +1,113 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
#
# Deterministic CPU-only selection of the workspace test targets (#159).
#
# scripts/cpu-tests.sh --list print every default-feature test target
# scripts/cpu-tests.sh --shard K/N run shard K of N (1 <= K <= N)
# scripts/cpu-tests.sh --check N prove N shards cover every target once
#
# Targets are the ones `cargo test --locked --workspace` builds with default
# features, sorted by package, kind and name. Shard K takes every target whose
# index i in that order has i mod N == K - 1; shard 1 also runs the doctests.
# New targets join a shard automatically. The selection never replaces the full
# gate, `cargo test --locked --workspace`; `gpu-tests` targets stay in
# scripts/test-gpu.sh.
set -eu
cd "$(dirname "$0")/.."
export CARGO_BUILD_JOBS=${CARGO_BUILD_JOBS:-4}
usage() {
echo "usage: $0 --list | --shard K/N | --check N" >&2
exit 2
}
# Prints "package selector..." for each test target, one per line, sorted.
# Fails when Cargo cannot build every target, so a partial list never runs.
targets() {
json=$(cargo test --locked --workspace --no-run --message-format=json) || {
echo "cpu-tests: cargo could not build the workspace test targets" >&2
exit 1
}
printf '%s\n' "$json" | python3 -c '
import json, sys
rows = set()
for line in sys.stdin:
m = json.loads(line)
if m.get("reason") != "compiler-artifact" or not m.get("executable"):
continue
if not m["profile"]["test"]:
continue
pkg = m["package_id"].split("#")[-1].split("@")[0]
kind, name = m["target"]["kind"][0], m["target"]["name"]
sel = {"test": "--test " + name, "bin": "--bin " + name}.get(kind, "--lib")
rows.add(f"{pkg} {sel}")
if not rows:
sys.exit("cpu-tests: no test targets found; does the workspace build?")
print("\n".join(sorted(rows)))
'
}
# Keeps the lines of stdin that belong to shard $1 of $2.
select_shard() {
awk -v k="$1" -v n="$2" '(NR - 1) % n == k - 1'
}
parse_count() {
case $1 in '' | *[!0-9]*) usage ;; esac
[ "$1" -ge 1 ] || usage
}
[ $# -ge 1 ] || usage
case $1 in
--list)
[ $# -eq 1 ] || usage
targets
;;
--check)
[ $# -eq 2 ] || usage
parse_count "$2"
all=$(targets)
total=$(printf '%s\n' "$all" | wc -l | tr -d ' ')
union=$(k=1; while [ "$k" -le "$2" ]; do
printf '%s\n' "$all" | select_shard "$k" "$2"
k=$((k + 1))
done)
if [ "$(printf '%s\n' "$union" | sort)" != "$(printf '%s\n' "$all" | sort)" ]; then
echo "cpu-tests: $2 shards do not cover the $total targets exactly once" >&2
exit 1
fi
echo "cpu-tests: $2 shards cover all $total targets exactly once"
;;
--shard)
[ $# -eq 2 ] || usage
k=${2%/*}
n=${2#*/}
[ "$k/$n" = "$2" ] || usage
parse_count "$k"
parse_count "$n"
[ "$k" -le "$n" ] || usage
all=$(targets)
selected=$(printf '%s\n' "$all" | select_shard "$k" "$n")
failed=0
# Word splitting of $line is intended: it holds "package --test name".
while IFS= read -r line; do
[ -n "$line" ] || continue
echo "cpu-tests[$k/$n]: cargo test --locked -p $line"
# shellcheck disable=SC2086
cargo test --locked -p $line || failed=$((failed + 1))
done <<EOF
$selected
EOF
if [ "$k" -eq 1 ]; then
echo "cpu-tests[$k/$n]: cargo test --locked --workspace --doc"
cargo test --locked --workspace --doc || failed=$((failed + 1))
fi
if [ "$failed" -ne 0 ]; then
echo "cpu-tests[$k/$n]: $failed target(s) failed" >&2
exit 1
fi
echo "cpu-tests[$k/$n]: all selected targets passed"
;;
*) usage ;;
esac
+5 -1
View File
@@ -8,6 +8,10 @@ export MTL_SHADER_VALIDATION=1
export MTL_SHADER_VALIDATION_REPORT_TO_STDERR=1
export MTL_SHADER_VALIDATION_ABORT_ON_FAULT=1
export CARGO_BUILD_JOBS=${CARGO_BUILD_JOBS:-4}
# The full semantic-review batch is much larger than the individual GPU tests.
# Cold Apple Silicon runs can exceed two minutes; keep the default bounded but
# allow slower hosts to raise it without editing the script.
export XENORA_SEMANTIC_TIMEOUT=${XENORA_SEMANTIC_TIMEOUT:-300s}
cargo test --locked -p xenora-metal --features gpu-tests --test native_compute --no-run
timeout 30s cargo test --locked -p xenora-metal --features gpu-tests --test native_compute -- \
@@ -58,4 +62,4 @@ timeout 30s cargo test --locked -p xenora-ffi --features gpu-tests --test audio_
# 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 120s cargo test --locked -p xenora-semantic-review -- --ignored --nocapture --test-threads=1
timeout "$XENORA_SEMANTIC_TIMEOUT" cargo test --locked -p xenora-semantic-review -- --ignored --nocapture --test-threads=1
+112
View File
@@ -0,0 +1,112 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Exercise native audit JSON decoding and inspection under an ASCII locale."""
import json
import os
from pathlib import Path
import platform
import subprocess
import sys
import tempfile
import unittest
ROOT = Path(__file__).resolve().parents[2]
SCRIPT = (ROOT / "scripts/audit/native.sh").read_text(encoding="utf-8")
AUDIT = SCRIPT.split("python3 - <<'PY'\n", 1)[1].rsplit("\nPY", 1)[0]
# Reader-only cases stop before the native executable inspection.
READER = AUDIT.split("\nif not executables:", 1)[0]
class NativeJsonTests(unittest.TestCase):
def run_audit(self, streams, code=READER):
with tempfile.TemporaryDirectory() as directory:
artifacts = Path(directory) / "artifacts"
artifacts.mkdir()
for name, payload in zip(
("native-build.jsonl", "native-tests.jsonl"), streams, strict=True
):
(artifacts / name).write_bytes(payload)
return subprocess.run(
[
sys.executable,
"-c",
"import locale\n"
"assert locale.getencoding().lower() in ('ascii', 'us-ascii')\n"
+ code
+ "\nprint(json.dumps(sorted(executables)))\n",
],
cwd=directory,
env={
**os.environ,
"LC_ALL": "C",
"PYTHONCOERCECLOCALE": "0",
"PYTHONUTF8": "0",
},
capture_output=True,
encoding="utf-8",
check=False,
)
def test_utf8_in_each_cargo_stream(self):
for stream in (0, 1):
with self.subTest(stream=stream):
entry = {
"executable": "/synthetic/caf\u00e9/bin",
"filenames": ["/synthetic/caf\u00e9/lib.dylib"],
"message": {"rendered": "synthetic diagnostic: \u03bb"},
}
streams = [b'{}\n', b'{}\n']
streams[stream] = (json.dumps(entry, ensure_ascii=False) + "\n").encode(
"utf-8"
)
result = self.run_audit(streams)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(
json.loads(result.stdout),
["/synthetic/caf\u00e9/bin", "/synthetic/caf\u00e9/lib.dylib"],
)
def test_ascii_streams_keep_deduplicated_artifacts(self):
entry = b'{"executable":"/synthetic/bin","filenames":["/synthetic/lib.so","/synthetic/lib.rlib"]}\n'
result = self.run_audit([entry, entry])
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(
json.loads(result.stdout), ["/synthetic/bin", "/synthetic/lib.so"]
)
def test_invalid_utf8_is_rejected(self):
result = self.run_audit([b'{"executable":"\xff"}\n', b'{}\n'])
self.assertNotEqual(result.returncode, 0)
self.assertIn("UnicodeDecodeError", result.stderr)
@unittest.skipUnless(
sys.platform == "darwin" and platform.machine() == "arm64",
"requires native ARM64 macOS inspection tools",
)
def test_native_inspection_of_unicode_path_under_ascii_locale(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
source = root / "fixture.c"
source.write_text("int main(void) { return 0; }\n", encoding="utf-8")
binary = root / "caf\u00e9"
subprocess.run(
["/usr/bin/clang", "-arch", "arm64", str(source), "-o", str(binary)],
check=True,
capture_output=True,
)
entry = (
json.dumps({"executable": str(binary)}, ensure_ascii=False) + "\n"
).encode("utf-8")
for stream in (0, 1):
with self.subTest(stream=stream):
streams = [b'{}\n', b'{}\n']
streams[stream] = entry
result = self.run_audit(streams, code=AUDIT)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn(str(binary), result.stdout)
self.assertIn("Checked 1 native executables", result.stdout)
if __name__ == "__main__":
unittest.main()