Compare commits

...
Author SHA1 Message Date
Ranveer Soni 82cafe9664 Merge branch 'main' into task/198-changelog-entry 2026-11-24 21:33:31 +05:30
Ranveer Soni bf2c279dc7 Merge pull request #322 from zachdoxsee/task/130-cpuid-contract
loader: add CPUID with a truthful guest feature contract (#130)
2026-11-24 21:33:00 +05:30
zachdoxsee da16b36499 loader: add CPUID with a truthful guest feature contract (#130)
CPUID returns a fixed table that never reads the host: a synthetic
vendor, and a feature bit only when every instruction of that feature
is implemented. Today that is CMOV, POPCNT, LZCNT and long mode. SSE
and SSE2 stay unreported while parts of them are rejected. Unlisted
leaves return zeros.

tests/cpu_features.rs pins every leaf in both engines, requires each
reported feature's instruction set among the executed fixtures, and
holds a refused witness instruction for each unreported feature, so a
bit cannot be set early or forgotten later.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 16:59:50 +01:00
zachdoxsee 061568a6ee changelog: restore the XADD, CMPXCHG and LOCK entry (#198)
The merge of main into the branch of #320 kept only main's side of the
changelog conflict, so the entry for that change did not reach main.
Put it back. No code changes.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 16:58:07 +01:00
Ranveer Soni a03188315d Merge pull request #320 from zachdoxsee/task/198-atomic-rmw
loader: add XADD, CMPXCHG and LOCK on their memory forms (#198)
2026-11-24 21:25:42 +05:30
Ranveer Soni 95f6b52d9f Merge branch 'main' into task/198-atomic-rmw 2026-11-24 21:24:32 +05:30
Ranveer Soni 7499d6f6c3 Merge pull request #318 from elforeign/task/215-vop1-xlate
isa, decoder, shader: the six VOP1 integer forms through the semantic registry, Metal-verifying the B3 oracle (#215)
2026-11-24 21:22:04 +05:30
zachdoxsee 3a3f0c52af loader: add XADD, CMPXCHG and LOCK on their memory forms (#198)
Declare XADD and CMPXCHG in the instruction registry for 8- to 64-bit
register and memory destinations. The LOCK prefix is accepted on the
forms the registry marks lockable and only with a memory destination;
every other use stays an illegal instruction.

Both engines run the new forms on the shared semantics. A failed
CMPXCHG still writes its destination, so it faults on memory that
cannot be written, and a fault changes nothing. The registry document
states the ordering, alignment, compare-failure and fault rules a guest
scheduler has to preserve. Nothing is lowered to ARM64 atomics.

Fourteen SDM-derived cases already in cpu_known_answers.rs move from
refused to verified. Adds 62 LLVM-assembled fixtures with reference
arms, generator checks for the lock key and tests/x86_atomic.rs.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 16:46:01 +01:00
elforeign 989bb79d6c Merge remote-tracking branch 'origin/main' into task/215-vop1-xlate
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	crates/isa/generate_semantics.py
#	crates/isa/src/semantics_gen.rs
#	crates/shader/src/lib.rs
#	docs/shaders/semantic-coverage.md
#	docs/shaders/semantic-registry.md
2026-11-24 09:45:44 -06:00
elforeign d157f802d3 docs: record the VOP1 integer Metal readback (#215)
scripts/test-gpu.sh now runs the oracle on native Metal: 752 cases in
613 programs pass under API and shader validation. Also states which half
of the oracle checks values and which checks rejection offsets (review nit).

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 09:44:19 -06:00
Ranveer Soni fb0544652b Merge pull request #317 from elforeign/task/215-smov
isa, decoder, shader: move s_mov_b32 into the semantic registry (#215)
2026-11-24 21:13:46 +05:30
elforeign 61943d23b6 Merge remote-tracking branch 'origin/main' into task/215-vop1-xlate
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 09:42:01 -06:00
elforeign 947d6e4eaf isa, decoder, shader: the six VOP1 integer forms through the semantic registry (#215)
The B3 oracle (#309) checks v_not_b32, v_bfrev_b32, v_ffbh_u32,
v_ffbl_b32, v_ffbh_i32 and v_swap_b32 against the guide on both CPU
interpreters, but its native Metal half was skipped because the
translator did not accept the forms. This adds the VOP1 registry file and
operand rule, decoder dispatch, IR and MSL lowering (v_swap_b32 writes
both VGPRs, each merged under EXEC), fixture and goldens, and removes
the oracle's skip from scripts/test-gpu.sh.

A new CPU test checks that the compiler accepts every case of the
oracle and rejects each of its rejections at the same word.
v_mov_b32 stays hand-written.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 09:41:08 -06:00
elforeign bdcdd57c55 docs: s_mov_b32 is now a registry SOP1 form (#215)
Review finding: the scalar ALU page still called it hand-written.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 09:39:39 -06:00
elforeign 5b894777ce Merge remote-tracking branch 'origin/main' into task/215-smov 2026-11-24 09:37:41 -06:00
elforeign dc44c5c64b isa, decoder, shader: move s_mov_b32 into the semantic registry (#215)
s_mov_b32 was the last hand-written SOP1 decode path. It becomes
ScalarUnaryOp::MovB32 under a new sop1_move operand rule that matches the
old hand-written domain exactly (it accepts more SDST and SSRC0 classes
than sop1_sgpr, which other unary forms keep).

A decode sweep of 33,664 s_mov_b32 words shows no behaviour change: the
21,010 accepted words differ only in the instruction's name and the 12,654
rejections are identical. IR and MSL goldens are unchanged.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 09:37:41 -06:00
Ranveer Soni b9f6985d57 Merge pull request #315 from zachdoxsee/task/244-delay-imports
loader: report delay-loaded PE imports in the static probe (#244)
2026-11-24 21:01:45 +05:30
zachdoxsee db40a1307d loader, cli: bound delay-load tables by their declared size (#244)
Address review on the delay-import probe change:

- Read only descriptors inside the delay import directory's declared
  size, and require that size to hold the terminating empty descriptor.
- Require each descriptor's DLL name, import address table and import
  name table to be present and to start in section data, with a
  diagnostic naming the missing field.
- Leave delayed rows out of the xenora imports sync backlog, so its
  totals stay ordinary-only.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 16:28:02 +01:00
zachdoxsee b174b45bed loader: report delay-loaded PE imports in the static probe (#244)
Read the PE32+ delay-load directory (data directory 13) with a bounded
parser and list each delay-loaded import in imports.csv, marked by a new
import_table column. Ordinary totals and missing_imports.csv are
unchanged; the JSON report counts delayed slots and DLLs separately and
carries a diagnostic for truncated, out-of-range or unsupported tables.

Adds an original fixture with ordinary and delayed imports, generated by
fixtures/pe/delay-imports.py and cross-checked with llvm-readobj.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 16:25:14 +01:00
Ranveer Soni 7504a5d48d Merge pull request #305 from LanaCodes-Boop/runtime/last-error-per-thread
loader: retire a guest thread's last error and test the per-TEB contract (#202)
2026-11-24 20:53:03 +05:30
Ranveer Soni 2b858ab7c6 Merge branch 'main' into runtime/last-error-per-thread 2026-11-24 20:52:39 +05:30
Ranveer Soni 076f3e52aa Merge pull request #313 from elforeign/task/215-gpu-skip
scripts: restore the VOP1 oracle's GPU gate skip (#215)
2026-11-24 20:51:33 +05:30
Ranveer Soni e17e3bfc63 Merge pull request #314 from elforeign/task/215-sopk-oracle
isa, decoder, shader, ref: the sixteen SOPK integer forms through the semantic registry (#215)
2026-11-24 20:50:46 +05:30
Ranveer Soni 1915e2374c Merge pull request #297 from Swastickc/task/196-bit-scan-bit-test
loader: lower BSF, BSR and register BT in the ARM64 DBT (#196)
2026-11-24 20:49:54 +05:30
elforeign 6545a25b7b Merge remote-tracking branch 'origin/main' into task/215-sopk-oracle 2026-11-24 09:12:11 -06:00
LanaCodes-Boop d5514aa9d8 Merge main into runtime/last-error-per-thread
Signed-off-by: LanaCodes-Boop <139008131+LanaCodes-Boop@users.noreply.github.com>
2026-11-24 12:10:25 -03:00
LanaCodes-Boop 7623fde0e7 loader: retire a guest thread's last error and test the per-TEB contract (#202)
main keeps the last error per TEB since #310. This adds the missing
retirement step, so a reused TEB address starts at zero, and two
conformance tests: a successful call keeps a nonzero error, and one
thread's failure does not reach another.

Signed-off-by: LanaCodes-Boop <139008131+LanaCodes-Boop@users.noreply.github.com>
2026-11-24 12:10:20 -03:00
Ranveer Soni f2e6db03a9 Update README.md 2026-11-24 20:39:34 +05:30
LanaCodes-Boop 3a14bd98ab Merge main into runtime/last-error-per-thread
main gained per-TEB last-error handling in #310. The conflicts in
CHANGELOG.md, services.rs and runtime_services.rs are resolved to main's
version, which drops this branch's separate thread-context mechanism.

Signed-off-by: LanaCodes-Boop <139008131+LanaCodes-Boop@users.noreply.github.com>
2026-11-24 12:08:04 -03:00
elforeign 81cfe69143 Merge remote-tracking branch 'origin/main' into task/215-sopk-oracle
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 09:06:03 -06:00
elforeign 91fe3f345b isa: cmov reads SCC in the registry validator (#215)
A form declared operation = "cmov" without carry_in = "scc" passed
validation and would have generated a move that never writes D. The new
generator test fails without the fix.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 09:05:49 -06:00
elforeign 0cf4e8a9e9 docs: status rows for the sixteen SOPK forms (#215)
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:58:43 -06:00
elforeign d8c117cdd3 docs: SOPK contract, coverage and changelog (#215)
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:55:52 -06:00
elforeign 9ef9537540 isa, decoder, shader: SOPK integer forms through the semantic registry (#215)
Declares s_movk_i32, s_cmovk_i32, s_cmpk_{eq,lg,gt,ge,lt,le}_{i32,u32},
s_addk_i32 and s_mulk_i32 as registry data under the new operand rules
sopk_sgpr and sopk_compare (SDST s0-s105 only, SIMM16 never a literal),
with the operations mov and cmov, the sext_simm16 primitive and an XML
check of the 16-bit immediate. The decoder dispatches them through the
generated ScalarImmediateOp and ScalarImmediateCompareOp (the fixed
0xbbfd0000 fence keeps its own decoding) and the translator folds them
into its scalar state like SOP2 and SOPC, refusing writes to s0-s7.

The guide-derived oracle in tests/validation/tests/sopk.rs is unchanged.
Adds IR and MSL goldens for the new fixture, LLVM-checked decoder words,
a known answer, an isa dispatch test and generator unit tests.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:55:52 -06:00
elforeign 081f9c9e06 fixtures: add an original SOPK scalar-immediate fixture (#215)
Uses all sixteen s_*k_* integer forms: the twelve s_cmpk compares split
signed from unsigned SIMM16 extension, s_addk_i32 sets SCC on signed
overflow, s_mulk_i32 leaves it alone and s_cmovk_i32 moves only while
SCC is set. The expected input ^ 0x40008275 is worked out by hand in the
file from guide section 12.2.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:55:52 -06:00
elforeign fbe1d3c4d1 Merge remote-tracking branch 'origin/main' into task/215-sopk-oracle 2026-11-24 08:47:37 -06:00
elforeign 9e35434f63 Merge remote-tracking branch 'origin/main' into task/215-sopk-oracle
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:41:06 -06:00
LanaCodes-Boop 6e64737021 loader: keep a guest last error per modeled thread context (#202)
ServicesState held one process-wide last-error value, so every modeled
guest thread would have read and overwritten the same slot. The running
context now owns the live slot and the others are parked by identifier,
bounded at 1,024. No guest thread is scheduled: the embedder switches
contexts between service calls.

Signed-off-by: LanaCodes-Boop <139008131+LanaCodes-Boop@users.noreply.github.com>
2026-11-24 11:41:05 -03:00
elforeign 8b0b62a771 validation: close SOPK test gaps from review
Compares now run with both SCC values before, so an implementation that
only flips SCC fails. New checks: a taken s_cmovk_i32 initializes an
unwritten SDST, s_cmovk_i32 without SCC is refused, the forms write no
SGPR but SDST, and s_waitcnt_vscnt null with a nonzero count is refused.
The opcode comment now lists 17 and 20 as unlisted.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:40:55 -06:00
elforeign 9500ed17e5 ref, validation: independent oracle for the SOPK integer forms
Adds s_movk_i32, s_cmovk_i32, s_cmpk_{eq,lg,gt,ge,lt,le}_{i32,u32},
s_addk_i32 and s_mulk_i32 (guide 12.2, 13.1.2) to the reference
interpreter and the second interpreter, each written from the guide
separately, and a guide-derived test that runs both. SDST is limited to
s0-s105; every other SOPK opcode and SDST stays refused.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:37:00 -06:00
Swastick Chowdhury 547b10250d loader: lower BSF, BSR and register BT in the ARM64 DBT (#196)
BSF, BSR and BT were decoded and executed by the interpreter, but every
occurrence of them in a translated block fell back to the shared semantics,
because `is_native` did not list them. The static probe therefore counted
them among the instructions the ARM64 DBT does not support.

Lower them to ARM64:

- BSF writes the index of the lowest set bit of the source and BSR the index
  of the highest set bit. The lowest set bit is the highest set bit of the
  reversed value, so BSF is `RBIT` followed by `CLZ`, and BSR is 63 minus the
  leading zero count.
- A zero source sets the zero flag and leaves the destination undefined, so
  the destination keeps its value. The interpreter and the independent
  reference apply the same rule, and the reference marks the destination as
  undefined so it is not compared.
- BT sets the carry flag from the tested bit, with the bit index masked to
  the operand width. The bit string is not modified.

Only the `0F A3` form of BT is lowered. The `0F BA` group form takes an
immediate index and may write memory, so it stays on the shared semantics and
is not advertised as natively supported.

The new encodings of RBIT, CLZ and LSLV were cross-checked against LLVM 23.1.6
`llvm-mc -show-encoding`.

The BSF, BSR and BT fixtures in `tests/x86/integer.txt` already cover the
16-bit, 32-bit and 64-bit forms with register and memory sources, and the
fixture test asserts that a native form never reaches the shared-semantics
helper, so those fixtures now exercise the new native path against the
independent reference. A new test pins the zero source, the highest bit, the
operand widths, the flag results and the masked bit index.

Closes #196

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 19:17:53 +05:30
67 changed files with 6783 additions and 688 deletions

No files matched your search

+6
View File
@@ -10,11 +10,17 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Changed
- Moved gfx1030 `s_mov_b32` (SOP1) into the semantic registry, preserving its existing decode domain and shader output. The move operand rule retains explicit VCC and EXEC half destinations. Part of #215.
- Moved the six hand-written gfx1030 VOP2 logical and shift forms (`v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`, `v_ashrrev_i32`, AMD guide section 12.7) into the semantic registry under a new VGPR-only operand rule `vop2_vgpr2`, with no behaviour change: a sweep of 132,608 VOP2, VOP1 and SOP1 words decodes to the same text, length and error before and after, the MSL goldens are unchanged, and the runtime-region allowlist admits exactly the same six forms. The per-lane `VectorBinary` gained `And`, `Or`, `Xor` and the three shifts (count masked to S0[4:0]); 6 hand-written instruction variants and their decoder and lowering arms are gone (17 hand-written forms remain). Part of #215.
- Added non-blocking Metal compute submission through `submit_words` and `wait`, with completion-aware resource retirement and a sixteen-dispatch in-flight limit. Synchronous calls keep their existing behavior. The benchmark reports the host submission split and compares synchronous and pipelined batches.
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
### Added
- Added XADD and CMPXCHG for 8- to 64-bit register and memory destinations, and the LOCK prefix on their memory forms (#198). LOCK anywhere else, CMPXCHG8B and CMPXCHG16B stay rejected. Both engines run the new forms on the shared semantics, one instruction at a time, so a locked instruction is indivisible today and LOCK changes no result; `docs/cpu/instruction-registry.md` states the ordering, alignment, compare-failure and fault rules a guest scheduler must preserve. A failed compare still writes the destination, so it faults on memory that cannot be written. Nothing is lowered to ARM64 atomic instructions, and no multi-thread behaviour is established. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, with 62 LLVM-assembled fixtures and five new tests in `x86_atomic.rs`; not compared with x86 hardware and awaiting independent review.
- Added CPUID with a fixed, host-independent guest contract (#130). It reports a synthetic processor with the vendor string `Xenora guest` and sets a feature bit only when every instruction of that feature is implemented: CMOV, POPCNT, LZCNT and long mode today. SSE and SSE2 are not reported while parts of them, such as RSQRTPS and MFENCE, are still rejected, so the table is truthful about Xenora and not a plausible hardware model. Unlisted leaves return zeros. `tests/cpu_features.rs` pins every leaf in both engines, requires each reported feature's instructions among the executed fixtures, and holds a refused witness instruction for 31 unreported features. `docs/cpu/instruction-registry.md` gives the table and the rule for reporting a new feature. Not compared with a processor; awaiting independent review.
- Added six Wave32 gfx1030 VOP1 integer forms through the semantic registry, including bit scans and a two-register swap under EXEC (AMD RDNA 2 ISA guide section 12.8, #215). The compiler accepts 752 guide-derived cases and rejects 610 programs at the oracle’s expected offsets. Native Metal verification and independent acceptance are pending.
- Added delay-loaded imports to the static PE probe (#244). `xenora probe --mode static` now reads the PE32+ delay-load directory and lists each delay-loaded import in `imports.csv` with its DLL, symbol or ordinal, and delay import address table slot. A new `import_table` column, inserted after `iat_rva`, marks every row `ordinary` or `delayed`; `import_kind` stays the last column. The existing totals and `missing_imports.csv` still cover ordinary imports only, and the JSON report adds `delayed_imports`, `delayed_imported_dlls_count` and `delay_import_error`. The table is bounded by the directory's declared size, which must hold the empty descriptor that ends it, and each descriptor's DLL name, import address table and import name table must be present and start in section data. A table that breaks these rules, is truncated, sets a reserved attribute bit or uses the earlier virtual-address descriptor form is reported with the entries read before the problem. `xenora imports sync` leaves delayed rows out of its backlog. Inspection stays static: nothing is bound or executed. Covered by an original fixture (`fixtures/pe/delay-imports.exe`, generated by `fixtures/pe/delay-imports.py`) whose imports were cross-checked locally with `llvm-readobj --coff-imports` from LLVM 23.1.6; awaiting independent review.
- Added the sixteen gfx1030 SOPK integer forms through the semantic registry: `s_movk_i32`, `s_cmovk_i32`, `s_cmpk_{eq,lg,gt,ge,lt,le}_{i32,u32}`, `s_addk_i32` and `s_mulk_i32` (AMD guide sections 12.2 and 13.1.2), with SDST s0-s105 only and SIMM16 sign-extended (zero-extended for the unsigned compares). The registry gained the operand rules `sopk_sgpr` and `sopk_compare` and the operations `mov` and `cmov`; the decoder and the scalar translation fold them like SOP2 and SOPC. An independent guide-derived oracle (`tests/validation/tests/sopk.rs`, 4,184 cases and 398 rejections on both CPU interpreters and native Metal), an LLVM-assembled fixture `scalar-immediate.s` with IR and MSL goldens, and the LLVM three-way decoder check cover them (part of #215).
- Added an independent guide-derived oracle for the Wave32 16-bit (`v_cmp_{lt..ge}_{i16,u16}_e32`) and 64-bit (`v_cmp_{f..t}_{i64,u64}_e32`) integer compares in the reference and the second interpreter (6,212 lane cases, 1,208 rejections; contract in `docs/shaders/vector-compare.md` section 2a). The decoder and translator still reject these forms, and native Metal agreement is not yet shown. Part of #215.
- Added `python3 -m qa rdna2 rank` to the read-only RDNA2 planner: it groups undeclared gfx1030 forms by the piece of work that would unlock them (an encoding variant of a declared form, a new operand rule, or a new primitive, from XML identity and operand shape only) and ranks the groups by forms per estimated cost, excluding claimed scopes, with `--no-float` to leave out floating-point groups until the FP contract exists (part of #215).
- Added authoritative read-only x86-64 CPU inventory CLI (`python3 -m qa cpu-inventory`) over `crates/loader/x86/instructions.toml` via `generate_x86.load`, with opcode-map/prefix/operand summaries, native vs shared-semantic operation partitions from `dbt.rs`, fixture mnemonic evidence and a separate unsupported catalog. Does not count candidates as implemented. Covered by `tests/qa/test_cpu_inventory.py`.
+1 -1
View File
@@ -9,7 +9,7 @@ Xenora is an open-source project written primarily in Rust that builds and verif
Xenora is still experimental. Verified work is restricted to independently authored synthetic programs and shaders; authentic Xbox executable loading, system-service compatibility and commercial game execution remain unsupported. See the [current limitations](#current-limitations).
> [!CAUTION]
> **Xenora strictly opposes piracy.** Xenora is an independent, clean-room, general-purpose emulation research project that neither distributes copyrighted game files nor supports unauthorized content, DRM circumvention, or leaked materials. Use only legally obtained software. Xenora is not affiliated with Microsoft, Rockstar Games, Take-Two Interactive, or any other publisher or platform holder.
> **Xenora strictly opposes piracy.** Xenora is an independent, clean-room, general-purpose emulation research project that neither distributes copyrighted game files nor supports unauthorized content, DRM circumvention, or leaked materials. Use only legally obtained software. Xenora is not affiliated with Microsoft or any other publisher or platform holder.
[![Native Rust checks](https://github.com/ranveersoni98/Xenora/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/ranveersoni98/Xenora/actions/workflows/ci.yml)
+9 -3
View File
@@ -454,10 +454,16 @@ fn run_imports_sync(
let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new();
let mut lines = csv_text.lines();
let has_import_kind = lines
.next()
.is_some_and(|header| header.ends_with(",import_kind"));
let header = lines.next().unwrap_or_default();
let has_import_kind = header.ends_with(",import_kind");
// Binding does not resolve delay-loaded imports, so the backlog omits them.
let table_column = header
.split(',')
.position(|column| column == "import_table");
for line in lines {
if table_column.and_then(|index| line.split(',').nth(index)) == Some("delayed") {
continue;
}
// Format: "module","symbol",0xRVA,category,registered,status,is_alias,"canonical",priority,cluster
// We re-query the live registry rather than trusting cached status.
let fields: Vec<&str> = line.splitn(10, ',').collect();
+35
View File
@@ -0,0 +1,35 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! `xenora imports sync` over a probe report that lists delay-loaded imports.
use std::process::Command;
#[test]
fn backlog_leaves_out_delay_loaded_imports() {
// `fixtures/pe/delay-imports.py` writes two ordinary imports from
// `fixture-ordinary.dll` and three delay-loaded ones from two other DLLs.
let fixture = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../fixtures/pe/delay-imports.exe"
);
let report = std::env::temp_dir().join(format!("xenora-sync-delayed-{}", std::process::id()));
let xenora = |arguments: &[&str]| {
let status = Command::new(env!("CARGO_BIN_EXE_xenora"))
.args(arguments)
.arg("--report")
.arg(&report)
.status()
.unwrap();
assert!(status.success(), "{arguments:?}");
};
xenora(&["probe", "--pe", fixture]);
xenora(&["imports", "sync"]);
let listed = std::fs::read_to_string(report.join("imports.csv")).unwrap();
let backlog = std::fs::read_to_string(report.join("import_backlog.md")).unwrap();
std::fs::remove_dir_all(report).unwrap();
assert_eq!(listed.matches(",delayed,").count(), 3);
assert!(backlog.contains("| **Total** | 2 |"), "{backlog}");
assert!(backlog.contains("fixture-ordinary.dll"), "{backlog}");
assert!(!backlog.contains("fixture-delay"), "{backlog}");
}
+54 -20
View File
@@ -4,18 +4,18 @@ use std::fmt;
pub use xenora_isa::{
Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp,
ScalarCompareOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp,
VectorSource,
ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, ScalarSource, ScalarUnaryOp,
VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorSource, VectorSwapOp, VectorUnaryOp,
};
use xenora_isa::{
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ,
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, V_ADD_F32,
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_ENDPGM, S_WAITCNT, S_WAITCNT_VSCNT, V_ADD_F32,
V_INTERP_P1_F32, V_INTERP_P2_F32, V_MOV_B32, V_MUL_F32, VCC_LO,
};
use xenora_isa::meta::EncodingFamily;
pub use xenora_isa::semantics::VectorBinary;
use xenora_isa::semantics::{FORM_IDS, OperandRule};
pub use xenora_isa::semantics::{VectorBinary, VectorUnary};
/// Metadata forms that [`decode`] turns into an [`Instruction`] for at least one
/// operand combination: the hand-written forms below followed by every form of
@@ -40,7 +40,7 @@ const fn concat_forms<const N: usize>() -> [(&'static str, EncodingFamily); N] {
}
/// Decoded forms not yet described by the semantic registry.
const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 17] = [
const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 16] = [
("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf),
("BUFFER_STORE_DWORD", EncodingFamily::Mubuf),
("EXP", EncodingFamily::Exp),
@@ -50,7 +50,6 @@ const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 17] = [
("S_CBRANCH_SCC0", EncodingFamily::Sopp),
("S_CBRANCH_VCCZ", EncodingFamily::Sopp),
("S_ENDPGM", EncodingFamily::Sopp),
("S_MOV_B32", EncodingFamily::Sop1),
("S_WAITCNT", EncodingFamily::Sopp),
("S_WAITCNT_VSCNT", EncodingFamily::Sopk),
("V_ADD_F32", EncodingFamily::Vop2),
@@ -317,6 +316,23 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
if V_MOV_B32.matches(first) {
return move_b32(first, bytes);
}
// AMD RDNA 2 ISA guide 13.3.2: VDST occupies bits 17–24 and SRC0 bits 0–8.
if let Some(op) = VectorUnaryOp::from_word(first) {
let dst = (first >> 17) as u8;
let (src, len) = vector_src0(first, bytes, op.assembly_name())?;
return Ok((Instruction::VectorUnary { op, dst, src }, len));
}
if let Some(op) = VectorSwapOp::from_word(first) {
if first & 0x100 == 0 {
return Err(unsupported(
op.assembly_name(),
"expected a VGPR SRC0 for writeback",
));
}
let dst = (first >> 17) as u8;
let src = first as u8;
return Ok((Instruction::VectorSwap { op, dst, src }, 4));
}
if let Some(op) = VectorCompareOp::from_word(first) {
return vector_compare(op, first, bytes);
}
@@ -324,23 +340,21 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
let second = word(bytes, 8)?;
return Ok((vop3_vgpr2(op, first, second)?, 8));
}
if S_MOV_B32.matches(first) {
let dst = ((first >> 16) & 0x7f) as u8;
if !matches!(dst, 0..=107 | 126..=127) {
return Err(unsupported(
"s_mov_b32",
"expected a normal SGPR or EXEC/VCC destination",
));
}
let (src, len) = scalar_source(first as u8, bytes, "s_mov_b32")?;
return Ok((Instruction::ScalarMoveB32 { dst, src }, len));
}
if let Some(op) = ScalarUnaryOp::from_word(first) {
// SOP1: SSRC0 in bits 0-7, SDST in bits 16-22.
let mnemonic = op.mnemonic();
let dst = ((first >> 16) & 0x7f) as u8;
if dst > 105 {
return Err(unsupported(mnemonic, "expected a normal SGPR destination"));
match op.semantics().operands {
OperandRule::Sop1Move if !matches!(dst, 0..=107 | 126..=127) => {
return Err(unsupported(
mnemonic,
"expected a normal SGPR or EXEC/VCC destination",
));
}
OperandRule::Sop1Sgpr if dst > 105 => {
return Err(unsupported(mnemonic, "expected a normal SGPR destination"));
}
_ => {}
}
let (src, len) = scalar_source(first as u8, bytes, mnemonic)?;
return Ok((Instruction::ScalarUnary { op, dst, src }, len));
@@ -362,6 +376,26 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
len0.max(len1),
));
}
if let Some(op) = ScalarImmediateOp::from_word(first) {
// SOPK: SIMM16 in bits 0-15, SDST in bits 16-22; the word has no literal.
let dst = ((first >> 16) & 0x7f) as u8;
if dst > 105 {
return Err(unsupported(
op.mnemonic(),
"expected a normal SGPR destination",
));
}
let simm16 = first as u16;
return Ok((Instruction::ScalarImmediate { op, dst, simm16 }, 4));
}
if let Some(op) = ScalarImmediateCompareOp::from_word(first) {
let src = ((first >> 16) & 0x7f) as u8;
if src > 105 {
return Err(unsupported(op.mnemonic(), "expected a normal SGPR operand"));
}
let simm16 = first as u16;
return Ok((Instruction::ScalarImmediateCompare { op, src, simm16 }, 4));
}
if S_BRANCH.matches(first) {
let target = branch_target(first, offset, "s_branch")?;
return Ok((Instruction::Branch { target }, S_BRANCH.byte_len()));
@@ -644,7 +678,7 @@ fn vector_compare(
Ok((Instruction::VectorCompare { op, src0, src1 }, len))
}
/// The 9-bit SRC0 of a VOPC or VOP2 word: a VGPR, `s0-s105`, `vcc_lo`, an
/// The 9-bit SRC0 of a VOP1, VOP2 or VOPC word: a VGPR, `s0-s105`, `vcc_lo`, an
/// inline integer -16..64 or a literal word; everything else is unsupported.
fn vector_src0(
first: u32,
+175 -15
View File
@@ -4,13 +4,13 @@ use std::process::{Command, Stdio};
use xenora_decoder::{
Architecture, CompareRelation, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction,
ScalarAluOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorSource, decode,
decode_at,
ScalarAluOp, ScalarImmediateOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op,
VectorSource, VectorUnaryOp, decode, decode_at,
};
use xenora_isa::semantics::Signedness;
use xenora_ref::{
BranchCondition, CompareSource, Comparison, Op, ScalarAlu, ScalarUnary, Source, VectorAlu,
VectorInteger,
BranchCondition, CompareSource, Comparison, Op, ScalarAlu, ScalarImmediate, ScalarUnary,
Source, VectorAlu, VectorInteger, VectorUnary,
};
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin");
@@ -330,6 +330,22 @@ fn reference_op(instruction: Instruction) -> Op {
src: VectorSource::Scalar(src),
} => Op::MoveScalar(dst, src),
Instruction::MoveB32 { dst, src } => Op::Move(dst, reference_source(src)),
Instruction::VectorUnary { op, dst, src } => Op::VectorUnary(
match op {
VectorUnaryOp::NotB32 => VectorUnary::Not,
VectorUnaryOp::BfrevB32 => VectorUnary::ReverseBits,
VectorUnaryOp::FfbhU32 => VectorUnary::FindFirstOneFromMsb,
VectorUnaryOp::FfblB32 => VectorUnary::FindFirstOneFromLsb,
VectorUnaryOp::FfbhI32 => VectorUnary::FindSignChange,
},
dst,
match src {
VectorSource::Register(reg) => CompareSource::Vector(reg),
VectorSource::Scalar(reg) => CompareSource::Scalar(reg),
VectorSource::Immediate(bits) => CompareSource::Immediate(bits),
},
),
Instruction::VectorSwap { dst, src, .. } => Op::Swap(dst, src),
Instruction::ScalarAlu {
op,
dst,
@@ -382,9 +398,10 @@ fn reference_op(instruction: Instruction) -> Op {
src0,
src1,
} => Op::Add(dst, src0, src1),
Instruction::ScalarMoveB32 { dst, src } => Op::ScalarMove(dst, reference_scalar(src)),
Instruction::ScalarUnary { op, dst, src } => Op::ScalarUnary(
match op {
Instruction::ScalarUnary { op, dst, src } => {
let src = reference_scalar(src);
let unary = match op {
ScalarUnaryOp::MovB32 => return Op::ScalarMove(dst, src),
ScalarUnaryOp::NotB32 => ScalarUnary::Not,
ScalarUnaryOp::BrevB32 => ScalarUnary::ReverseBits,
ScalarUnaryOp::Bcnt0I32B32 => ScalarUnary::CountZeros,
@@ -396,10 +413,9 @@ fn reference_op(instruction: Instruction) -> Op {
ScalarUnaryOp::SextI32I8 => ScalarUnary::SignExtendByte,
ScalarUnaryOp::SextI32I16 => ScalarUnary::SignExtendShort,
ScalarUnaryOp::AbsI32 => ScalarUnary::Absolute,
},
dst,
reference_scalar(src),
),
};
Op::ScalarUnary(unary, dst, src)
}
Instruction::ScalarCompare { op, src0, src1 } => {
let (src0, src1) = (reference_scalar(src0), reference_scalar(src1));
// The reference keeps CompareEqual for EQ and uses its VOPC relation
@@ -416,6 +432,25 @@ fn reference_op(instruction: Instruction) -> Op {
),
}
}
Instruction::ScalarImmediate { op, dst, simm16 } => Op::ScalarImmediate(
match op {
ScalarImmediateOp::MovkI32 => ScalarImmediate::Move,
ScalarImmediateOp::CmovkI32 => ScalarImmediate::ConditionalMove,
ScalarImmediateOp::AddkI32 => ScalarImmediate::Add,
ScalarImmediateOp::MulkI32 => ScalarImmediate::Multiply,
},
dst,
simm16,
),
Instruction::ScalarImmediateCompare { op, src, simm16 } => Op::ScalarImmediate(
ScalarImmediate::Compare(Comparison {
// The reference's VOPC relation offsets, as for SOPC above.
offset: op.relation() as u8 + 1,
signed: op.semantics().signedness == Signedness::Signed,
}),
src,
simm16,
),
Instruction::BranchSccZero { target } => Op::Branch {
target,
condition: BranchCondition::SccZero,
@@ -545,15 +580,17 @@ fn compares_fixture_instructions_against_llvm() {
include_bytes!("../../../fixtures/rdna2/scalar-compare.bin"),
include_bytes!("../../../fixtures/rdna2/scalar-unary.bin"),
include_bytes!("../../../fixtures/rdna2/scalar-arith.bin"),
include_bytes!("../../../fixtures/rdna2/scalar-immediate.bin"),
include_bytes!("../../../fixtures/rdna2/vector-integer.bin"),
include_bytes!("../../../fixtures/rdna2/vector-compare.bin"),
include_bytes!("../../../fixtures/rdna2/vector-compare-ft.bin"),
include_bytes!("../../../fixtures/rdna2/vector-unary.bin"),
high_registers,
&matrix,
] {
count += compare_against_llvm(fixture, &mut forms);
}
assert_eq!(forms.len(), 104, "forms compared: {forms:?}");
assert_eq!(forms.len(), 126, "forms compared: {forms:?}");
eprintln!(
"{count} three-way instruction comparisons across {} forms",
forms.len()
@@ -611,6 +648,12 @@ fn assemble_matrix() -> Vec<u8> {
s_or_b32 s103, s3, 0x80000000
s_xor_b32 s102, s104, -16
s_xor_b32 s7, s7, lit(0x1)
s_movk_i32 s105, 0xffff
s_movk_i32 s8, 0
s_cmovk_i32 s105, 0x8000
s_addk_i32 s9, 0x7fff
s_addk_i32 s105, 0xffff
s_mulk_i32 s8, 0x8001
v_mov_b32_e32 v255, s105
v_mov_b32_e32 v0, s0
v_mov_b32_e32 v128, vcc_lo
@@ -636,6 +679,15 @@ fn assemble_matrix() -> Vec<u8> {
writeln!(assembly, "v_cmp_{relation}_{kind}_e32 vcc_lo, v1, v255").unwrap();
}
}
// Every SOPK compare on the lowest and highest readable SGPR.
for relation in ["eq", "lg", "gt", "ge", "lt", "le"] {
for kind in ["i32", "u32"] {
for register in ["s0", "s7", "s8", "s105"] {
writeln!(assembly, "s_cmpk_{relation}_{kind} {register}, 0x8000").unwrap();
}
writeln!(assembly, "s_cmpk_{relation}_{kind} s9, 0").unwrap();
}
}
for value in -16..=64 {
writeln!(assembly, "v_mov_b32_e32 v255, {value}").unwrap();
writeln!(assembly, "s_mov_b32 s105, {value}").unwrap();
@@ -956,14 +1008,16 @@ fn decodes_inline_negative_and_register_sources() {
let decoded = decode(Architecture::Gfx1030, &bytes).unwrap();
assert_eq!(
decoded[0].instruction,
Instruction::ScalarMoveB32 {
Instruction::ScalarUnary {
op: ScalarUnaryOp::MovB32,
dst: 10,
src: ScalarSource::Immediate(5)
}
);
assert_eq!(
decoded[1].instruction,
Instruction::ScalarMoveB32 {
Instruction::ScalarUnary {
op: ScalarUnaryOp::MovB32,
dst: 11,
src: ScalarSource::Immediate(0xffff_fffd)
}
@@ -997,7 +1051,8 @@ fn accepts_scalar_destination_105_and_vgpr_zero_add_sources() {
let valid = 0xbee9_0380u32.to_le_bytes();
assert_eq!(
decode(Architecture::Gfx1030, &valid).unwrap()[0].instruction,
Instruction::ScalarMoveB32 {
Instruction::ScalarUnary {
op: ScalarUnaryOp::MovB32,
dst: 105,
src: ScalarSource::Immediate(0)
}
@@ -1051,3 +1106,108 @@ fn decode_at_resolves_branch_targets_from_the_stream_offset() {
})
);
}
#[test]
fn decodes_sopk_immediates_and_rejects_non_sgpr_operands() {
use xenora_decoder::ScalarImmediateCompareOp;
let decode_word = |word: u32| decode(Architecture::Gfx1030, &word.to_le_bytes());
// Words assembled by LLVM for gfx1030 (llvm-mc --show-encoding).
// s_movk_i32 s8, 0x8000
let decoded = decode_word(0xb008_8000).unwrap();
assert_eq!(decoded[0].byte_len, 4);
assert_eq!(
decoded[0].instruction,
Instruction::ScalarImmediate {
op: ScalarImmediateOp::MovkI32,
dst: 8,
simm16: 0x8000
}
);
// s_cmovk_i32 s105, 0xffff keeps the full 16 bits: the sign extension is
// the translator's job, not the decoder's.
assert_eq!(
decode_word(0xb169_ffff).unwrap()[0].instruction,
Instruction::ScalarImmediate {
op: ScalarImmediateOp::CmovkI32,
dst: 105,
simm16: 0xffff
}
);
// s_cmpk_gt_u32 s0, 0x1234 and s_cmpk_le_i32 s7, 0xffff read SDST s0-s7.
assert_eq!(
decode_word(0xb580_1234).unwrap()[0].instruction,
Instruction::ScalarImmediateCompare {
op: ScalarImmediateCompareOp::CmpkGtU32,
src: 0,
simm16: 0x1234
}
);
assert_eq!(
decode_word(0xb407_ffff).unwrap()[0].instruction,
Instruction::ScalarImmediateCompare {
op: ScalarImmediateCompareOp::CmpkLeI32,
src: 7,
simm16: 0xffff
}
);
// s_addk_i32 s9, 0x7fff and s_mulk_i32 s105, 0
assert_eq!(
decode_word(0xb789_7fff).unwrap()[0].instruction,
Instruction::ScalarImmediate {
op: ScalarImmediateOp::AddkI32,
dst: 9,
simm16: 0x7fff
}
);
assert_eq!(
decode_word(0xb869_0000).unwrap()[0].instruction,
Instruction::ScalarImmediate {
op: ScalarImmediateOp::MulkI32,
dst: 105,
simm16: 0
}
);
// vcc_lo, exec_lo, null and ttmp0 as SDST, and s_cmpk_eq_i32 m0: refused.
for (word, mnemonic, detail) in [
(
0xb06a_0001,
"s_movk_i32",
"expected a normal SGPR destination",
),
(
0xb07e_0001,
"s_movk_i32",
"expected a normal SGPR destination",
),
(
0xb07d_0001,
"s_movk_i32",
"expected a normal SGPR destination",
),
(
0xb06c_0001,
"s_movk_i32",
"expected a normal SGPR destination",
),
(
0xb1fc_0001,
"s_cmpk_eq_i32",
"expected a normal SGPR operand",
),
] {
assert_eq!(
decode_word(word).unwrap_err().kind,
DecodeErrorKind::UnsupportedForm { mnemonic, detail },
"{word:#010x}"
);
}
// Other SOPK opcodes (opcode 1 s_version, 17 s_getreg_b32) stay unsupported.
for word in [0xb080_0000u32, 0xb888_0000] {
assert!(decode_word(word).is_err(), "{word:#010x}");
}
// The fixed store fence is still the one decoded SOPK word outside the registry.
assert_eq!(
decode_word(0xbbfd_0000).unwrap()[0].instruction,
Instruction::WaitStore
);
}
+256 -10
View File
@@ -61,6 +61,7 @@ OPERATIONS = {
"mul": "Multiply", "mul_hi": "MultiplyHigh", "bfe": "BitfieldExtract",
"absdiff": "AbsoluteDifference", "lshl_add": "ShiftLeftAdd",
"mul24": "Multiply24", "mul_hi24": "MultiplyHigh24",
"mov": "Move", "cmov": "ConditionalMove", "swap": "Swap",
}
# Unary operations read one source; they need an operand rule of the unary kind.
UNARY = {"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "flbit", "sext", "abs"}
@@ -96,7 +97,7 @@ COMPARE_PRIMITIVES = {
# the signedness their primitive names, and their S1 is an unsigned count.
LOGICAL = {
"and", "or", "xor", "andn2", "orn2", "nand", "nor", "xnor",
"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "cselect", "bfm",
"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "cselect", "bfm", "swap",
}
ARITHMETIC = {
"add", "sub", "min", "max", "mul", "mul_hi", "bfe", "absdiff", "lshl_add", "mul24", "mul_hi24",
@@ -106,7 +107,7 @@ SHIFTS = {"lshl", "lshr", "ashr"}
# descriptor), so the XML gives it FMT_NUM_U32 whatever the form's signedness.
CONTROL_S1 = SHIFTS | {"bfe"}
# Operations that always read SCC: the select condition. They need carry_in scc.
SCC_READERS = {"cselect"}
SCC_READERS = {"cselect", "cmov"}
# XML number formats a source may have for each declared signedness.
SOURCE_FORMATS = {
"signed": {"FMT_NUM_I32"},
@@ -142,7 +143,7 @@ WAVE = {"any": "Any", "wave32": "Wave32"}
# wave size: the lane-mask compares, whose one entry point is the Wave32
# compute fixture ABI (docs/shaders/vector-compare.md section 2). Every other
# kind must be "any".
WAVE_BY_KIND = {"vector_compare": "wave32"}
WAVE_BY_KIND = {"vector_compare": "wave32", "vector_unary": "wave32", "vector_swap": "wave32"}
EVIDENCE = {
"reference": "Reference",
"independent": "Independent",
@@ -183,6 +184,7 @@ PRIMITIVES = {
("lshl", "bitwise"): ("nonzero", "lshl_nonzero_b32", False),
("lshr", "unsigned"): ("nonzero", "lshr_nonzero_b32", False),
("ashr", "signed"): ("nonzero", "ashr_nonzero_i32", False),
("mov", "bitwise"): ("unchanged", "mov_b32", False),
("not", "bitwise"): ("nonzero", "not_nonzero_b32", False),
("brev", "bitwise"): ("unchanged", "brev_b32", False),
("bcnt0", "bitwise"): ("nonzero", "bcnt0_nonzero_b32", False),
@@ -208,6 +210,22 @@ PRIMITIVES = {
("lshl_add", "unsigned"): ("carry_out", "lshl_add_carry_u32", False),
}
# SOPK forms (operation, signedness) -> (SCC effect, primitive, reads SCC). D is
# SDST and the immediate is SIMM16 sign-extended (guide 12.2); `sext_simm16` is
# the sign extension, so a move or conditional move writes it unchanged.
IMMEDIATE_PRIMITIVES = {
("mov", "signed"): ("unchanged", "sext_simm16", False),
("cmov", "signed"): ("unchanged", "sext_simm16", True),
("add", "signed"): ("signed_overflow", "add_overflow_i32", False),
("mul", "signed"): ("unchanged", "mul_lo_i32", False),
}
# SOPK compares: the opcode is the group base (3 signed, 9 unsigned) plus the
# relation's index in this order (guide 13.1.2).
SOPK_COMPARE_BASES = {"signed": 3, "unsigned": 9}
SOPK_RELATION_ORDER = ["eq", "lg", "gt", "ge", "lt", "le"]
# Operand-rule kinds whose forms have a 16-bit immediate field.
IMMEDIATE_KINDS = {"immediate", "immediate_compare"}
# Vector (VOP2) forms: (operation, signedness) -> the per-lane VectorBinary their
# MSL lowering uses. They write no SCC, VCC or EXEC, so scc must be unchanged.
VECTOR_PRIMITIVES = {
@@ -241,7 +259,45 @@ UNSUPPORTED_COMBOS = {
# VOP3 rules also name source classes and encoding fields they refuse.
VOP3_COMBOS = {"src_sgpr", "src_inline", "src_literal", "modifiers", "src2"}
ALL_COMBOS = UNSUPPORTED_COMBOS | {"src_vcc_hi", "src_null"} | VOP3_COMBOS
VECTOR_UNARY_PRIMITIVES = {
("not", "bitwise"): "Not",
("brev", "bitwise"): "ReverseBits",
("flbit", "unsigned"): "FindHighUnsigned",
("ff1", "bitwise"): "FindLow",
("flbit", "signed"): "FindHighSigned",
}
OPERAND_RULES = {
"vop1_vgpr": {
"rust": "Vop1Vgpr",
"enum": "VectorUnaryOp",
"shape": {
"family": "VOP1",
"dst": {"field": "VDST", "class": "vgpr", "min": 0, "max": 255},
"src": [{"field": "SRC0", "class": "vector_source"}],
"max_literals": 1,
},
"unsupported": {
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline",
"src_special",
},
"kind": "vector_unary",
},
"vop1_swap": {
"rust": "Vop1Swap",
"enum": "VectorSwapOp",
"shape": {
"family": "VOP1",
"dst": {"field": "VDST", "class": "vgpr", "min": 0, "max": 255},
"src": [{"field": "SRC0", "class": "vgpr"}],
"max_literals": 0,
},
"unsupported": {
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
"src_float_inline", "src_special", "src_literal",
},
"kind": "vector_swap",
},
"sop2_sgpr": {
"rust": "Sop2Sgpr",
"enum": "ScalarAluOp",
@@ -286,6 +342,46 @@ OPERAND_RULES = {
"unsupported": {combo for combo in UNSUPPORTED_COMBOS if combo != "two_literals"},
"kind": "unary",
},
"sop1_move": {
"rust": "Sop1Move",
"enum": "ScalarUnaryOp",
"shape": {
"family": "SOP1",
"dst": {"field": "SDST", "class": "sgpr_or_vcc_exec"},
"src": [{"field": "SSRC0", "class": "scalar_source"}],
"max_literals": 1,
},
"unsupported": UNSUPPORTED_COMBOS - {"two_literals", "dst_vcc", "dst_exec"},
"kind": "unary",
},
"sopk_sgpr": {
"rust": "SopkSgpr",
"enum": "ScalarImmediateOp",
"shape": {
"family": "SOPK",
"dst": {"field": "SDST", "class": "sgpr", "min": 0, "max": 105},
"src": [{"field": "SIMM16", "class": "simm16"}],
"max_literals": 0,
},
# SOPK never takes a literal dword; the decoder rejects SDST 106-127.
"unsupported": {combo for combo in UNSUPPORTED_COMBOS if combo.startswith("dst_")},
"kind": "immediate",
},
"sopk_compare": {
"rust": "SopkCompare",
"enum": "ScalarImmediateCompareOp",
"shape": {
"family": "SOPK",
"src": [
{"field": "SDST", "class": "sgpr", "min": 0, "max": 105},
{"field": "SIMM16", "class": "simm16"},
],
"max_literals": 0,
},
# The compared register is SDST (S0); the decoder rejects SDST 106-127.
"unsupported": {combo for combo in UNSUPPORTED_COMBOS if combo.startswith("dst_")},
"kind": "immediate_compare",
},
"vopc_vcc": {
"rust": "VopcVcc",
"enum": "VectorCompareOp",
@@ -579,11 +675,23 @@ def _check_xml(form, rule, snapshot, errors):
errors.append(f"{label}: XML has no operand {field}")
continue
data_format, size, is_input, is_output = operands[field]
if field == "SIMM16":
# The 16-bit immediate: signed forms read it as FMT_NUM_I16 (sign
# extended), unsigned compares as FMT_NUM_U16 (zero extended).
wanted = "FMT_NUM_U16" if form["signedness"] == "unsigned" else "FMT_NUM_I16"
if size != 16 or data_format != wanted:
errors.append(f"{label}: SIMM16 is {size} bits {data_format} in the XML, expected 16 {wanted}")
if (is_input, is_output) != (True, False):
errors.append(f"{label}: {field} direction disagrees with the XML")
continue
bits = form.get(SOURCE_BITS_KEY) if is_source else None
expected = bits if type(bits) is int else form["width"]
if size != expected:
errors.append(f"{label}: {field} is {size} bits in the XML, declared {expected}")
if (is_input, is_output) != (is_source, not is_source):
# The XML marks both swap operands as outputs. Guide 12.8 also
# reads both old values before assigning either result.
direction = (False, True) if _rule_kind(form) == "vector_swap" else (is_source, not is_source)
if (is_input, is_output) != direction:
errors.append(f"{label}: {field} direction disagrees with the XML")
if field == count_field:
if data_format != "FMT_NUM_U32":
@@ -730,6 +838,15 @@ def validate(registry, snapshot):
errors.append(f"{label}: no primitive implements {relation}/{form['signedness']}")
elif relation in VECTOR_ONLY_RELATIONS and _rule_kind(form) != "vector_compare":
errors.append(f"{label}: relation {relation} exists only for VOPC compares")
elif _rule_kind(form) == "immediate_compare":
base = SOPK_COMPARE_BASES.get(form["signedness"])
expected = None if base is None else base + SOPK_RELATION_ORDER.index(relation) \
if relation in SOPK_RELATION_ORDER else None
if form["opcode"] != expected:
errors.append(
f"{label}: relation {relation}/{form['signedness']} has SOPK opcode "
f"{expected} (guide 13.1.2), not {form['opcode']}"
)
elif _rule_kind(form) == "vector_compare":
base = VOPC_INTEGER_BASES.get(form["signedness"])
expected = None if base is None else base + VOPC_RELATION_OFFSETS[relation]
@@ -745,15 +862,22 @@ def validate(registry, snapshot):
if form["carry_in"] != "none":
errors.append(f"{label}: carry_in {form['carry_in']} contradicts compare")
primitive = (scc, None, False)
elif _rule_kind(form) == "vector":
elif _rule_kind(form) in ("vector", "vector_unary", "vector_swap"):
if RELATION_KEY in form:
errors.append(f"{label}: {RELATION_KEY} on a non-compare operation")
lowering = VECTOR_PRIMITIVES.get((form["operation"], form["signedness"]))
key = (form["operation"], form["signedness"])
table = {
"vector": VECTOR_PRIMITIVES,
"vector_unary": VECTOR_UNARY_PRIMITIVES,
"vector_swap": {("swap", "bitwise"): "Swap"},
}[_rule_kind(form)]
lowering = table.get(key)
primitive = None if lowering is None else ("unchanged", lowering, False)
else:
if RELATION_KEY in form:
errors.append(f"{label}: {RELATION_KEY} on a non-compare operation")
primitive = PRIMITIVES.get((form["operation"], form["signedness"]))
table = IMMEDIATE_PRIMITIVES if _rule_kind(form) == "immediate" else PRIMITIVES
primitive = table.get((form["operation"], form["signedness"]))
if primitive is None:
errors.append(f"{label}: no primitive implements {form['operation']}/{form['signedness']}")
else:
@@ -773,10 +897,15 @@ def validate(registry, snapshot):
elif rule.get("family") != form["family"]:
errors.append(f"{label}: operand rule {form['operands']} is for {rule.get('family')}")
elif form["operands"] in OPERAND_RULES and OPERAND_RULES[form["operands"]]["kind"] != (
("vector_compare" if _rule_kind(form) == "vector_compare" else "compare")
(_rule_kind(form) if _rule_kind(form) in ("vector_compare", "immediate_compare") else "compare")
if form["operation"] == "compare"
else "unary" if form["operation"] in UNARY
else "vector_swap" if form["operation"] == "swap"
else "vector_unary" if _rule_kind(form) == "vector_unary" and form["operation"] in UNARY
else "unary" if form["operation"] in UNARY or (
form["operation"] == "mov" and form["family"] == "SOP1"
)
else "vector" if _rule_kind(form) == "vector" and form["operation"] not in UNARY
else "immediate" if _rule_kind(form) == "immediate"
else "alu"
):
errors.append(f"{label}: operation {form['operation']} does not fit rule {form['operands']}")
@@ -962,7 +1091,7 @@ def render(registry, snapshot):
"use crate::primitive;",
"use crate::semantics::{",
" CarryIn, Document, Evidence, FormSemantics, MaskEffect, Operation, OperandRule, SccEffect,",
" Signedness, SpecRef, VectorBinary, Wave,",
" Signedness, SpecRef, VectorBinary, VectorUnary, Wave,",
"};",
"use crate::CompareRelation;",
"",
@@ -1209,6 +1338,123 @@ def _render_enum(rule_name, forms, snapshot, positions):
" }]",
" }",
]
if kind in ("vector_unary", "vector_swap"):
out += [
"",
" /// Assembler name of the 32-bit VOP1 encoding.",
" pub const fn assembly_name(self) -> &'static str {",
" match self {",
]
suffix = "_e32" if kind == "vector_unary" else ""
out += [f" Self::{form['variant']} => \"{form['name'].lower()}{suffix}\"," for form in forms]
out += [" }", " }"]
if kind == "vector_swap":
return out + ["}"]
if kind == "vector_unary":
out += [
"",
" /// Per-lane integer operation selected by the registry.",
" pub const fn lowering(self) -> VectorUnary {",
" match self {",
]
out += [
f" Self::{form['variant']} => "
f"VectorUnary::{VECTOR_UNARY_PRIMITIVES[(form['operation'], form['signedness'])]},"
for form in forms
]
return out + [" }", " }", "}"]
if kind == "immediate":
out += [
"",
" /// Whether the operation reads SCC (the conditional move's condition).",
" pub const fn reads_scc(self) -> bool {",
" match self {",
]
out += [
f" Self::{form['variant']} => {'true' if form['carry_in'] == 'scc' else 'false'},"
for form in forms
]
out += [
" }",
" }",
"",
" /// Whether the operation writes SCC.",
" pub const fn writes_scc(self) -> bool {",
" match self {",
]
out += [
f" Self::{form['variant']} => {'false' if form['scc'] == 'unchanged' else 'true'},"
for form in forms
]
out += [
" }",
" }",
"",
" /// Whether the operation always reads the old SDST (`D = D op imm`).",
" pub const fn reads_dst(self) -> bool {",
" match self {",
]
out += [
f" Self::{form['variant']} => {'true' if form['operation'] in ('add', 'mul') else 'false'},"
for form in forms
]
out += [
" }",
" }",
"",
" /// The new SDST (`None` leaves it unchanged) and, for forms that write it, the",
" /// new SCC (`None` leaves SCC unchanged). `dst` is the old SDST (ignored by",
" /// forms that do not read it) and `scc_in` the SCC read by the conditional move.",
" pub const fn evaluate(self, dst: u32, simm16: u16, scc_in: bool) -> (Option<u32>, Option<bool>) {",
" match self {",
]
for form in forms:
_, function, _ = IMMEDIATE_PRIMITIVES[(form["operation"], form["signedness"])]
immediate = "primitive::sext_simm16(simm16)"
variant = form["variant"]
if form["operation"] == "mov":
out.append(f" Self::{variant} => (Some({immediate}), None),")
elif form["operation"] == "cmov":
out.append(
f" Self::{variant} => (if scc_in {{ Some({immediate}) }} else {{ None }}, None),"
)
elif form["scc"] == "unchanged":
out.append(f" Self::{variant} => (Some(primitive::{function}(dst, {immediate})), None),")
else:
out += [
f" Self::{variant} => {{",
f" let (value, scc) = primitive::{function}(dst, {immediate});",
" (Some(value), Some(scc))",
" }",
]
out += [" }", " }", "}"]
return out
if kind == "immediate_compare":
out += [
"",
" /// The relation tested, with SDST (S0) on the left.",
" pub const fn relation(self) -> CompareRelation {",
" match self {",
]
out += [
f" Self::{form['variant']} => CompareRelation::{RELATIONS[form[RELATION_KEY]]},"
for form in forms
]
out += [
" }",
" }",
"",
" /// The SCC: whether the relation holds for SDST and SIMM16, which signed forms",
" /// sign-extend and unsigned forms zero-extend.",
" pub const fn test(self, dst: u32, simm16: u16) -> bool {",
" match self {",
]
for form in forms:
function = COMPARE_PRIMITIVES[(form[RELATION_KEY], form["signedness"])]
immediate = "primitive::sext_simm16(simm16)" if form["signedness"] == "signed" else "simm16 as u32"
out.append(f" Self::{form['variant']} => primitive::{function}(dst, {immediate}),")
out += [" }", " }", "}"]
return out
if kind == "unary":
out += [
"",
+3 -1
View File
@@ -19,7 +19,9 @@ source_sha256 = "d671ecbc36543674ab59e9b2feffd56718fd2137e7ad913c314f2e2508b9f4f
include = [
"rdna2/sop2.toml",
"rdna2/sopc.toml",
"rdna2/sopk.toml",
"rdna2/sop1.toml",
"rdna2/vop1.toml",
"rdna2/vop2.toml",
"rdna2/vopc.toml",
"rdna2/vop3.toml",
@@ -46,7 +48,7 @@ file = "amdgpu_isa_rdna2.xml"
# width operand and result width in bits
# scc unchanged | carry_out | borrow | signed_overflow | nonzero | relation | selected_src0
# vcc, exec unchanged (stated, not implied) | lane_mask (vcc of a Wave32 VOPC compare)
# wave any | wave32 (wave32 exactly for the VOPC lane-mask compares)
# wave any | wave32 (wave32 for VOPC compares and VOP1 integer forms)
# operands a key of [operand_rules]
# spec references; at least one guide section with a page
# verify evidence required before the form counts as verified
+32
View File
@@ -15,6 +15,38 @@ unsupported = [
"src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline", "src_special",
]
# Guide sections 5.3 and 12.3. VCC and EXEC halves can be explicit
# destinations; the move has no implicit mask or SCC effects.
[operand_rules.sop1_move]
family = "SOP1"
dst = { field = "SDST", class = "sgpr_or_vcc_exec" }
src = [{ field = "SSRC0", class = "scalar_source" }]
max_literals = 1
unsupported = [
"dst_ttmp", "dst_m0", "dst_null",
"src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline", "src_special",
]
[[form]]
name = "S_MOV_B32"
family = "SOP1"
opcode = 3
variant = "MovB32"
operation = "mov"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop1_move"
spec = [
{ document = "guide", section = "12.3", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_NOT_B32"
family = "SOP1"
+358
View File
@@ -0,0 +1,358 @@
# SOPK forms of the gfx1030 semantic registry; included by ../rdna2.toml.
# Data only; see the root file for the field meanings.
# ---- SOPK 16-bit immediate integer forms (#215) ----
# SDST is the destination, and the left operand of the compares; SIMM16 is
# sign-extended except by the unsigned compares (guide 12.2). The word never
# takes a literal dword. SDST s0-s105 only; s0-s7 hold resource descriptors,
# so the decoder accepts them as compare operands and the translator never
# writes them.
[operand_rules.sopk_sgpr]
family = "SOPK"
dst = { field = "SDST", class = "sgpr", min = 0, max = 105 }
src = [{ field = "SIMM16", class = "simm16" }]
max_literals = 0
unsupported = ["dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null"]
[operand_rules.sopk_compare]
family = "SOPK"
src = [
{ field = "SDST", class = "sgpr", min = 0, max = 105 },
{ field = "SIMM16", class = "simm16" },
]
max_literals = 0
unsupported = ["dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null"]
[[form]]
name = "S_MOVK_I32"
family = "SOPK"
opcode = 0
variant = "MovkI32"
operation = "mov"
signedness = "signed"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopk_sgpr"
spec = [
{ document = "guide", section = "12.2", page = 106 },
{ document = "guide", section = "13.1.2", page = 240 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMOVK_I32"
family = "SOPK"
opcode = 2
variant = "CmovkI32"
operation = "cmov"
signedness = "signed"
carry_in = "scc"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopk_sgpr"
spec = [
{ document = "guide", section = "12.2", page = 106 },
{ document = "guide", section = "13.1.2", page = 240 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMPK_EQ_I32"
family = "SOPK"
opcode = 3
variant = "CmpkEqI32"
operation = "compare"
relation = "eq"
signedness = "signed"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopk_compare"
spec = [
{ document = "guide", section = "12.2", page = 106 },
{ document = "guide", section = "13.1.2", page = 240 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMPK_LG_I32"
family = "SOPK"
opcode = 4
variant = "CmpkLgI32"
operation = "compare"
relation = "lg"
signedness = "signed"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopk_compare"
spec = [
{ document = "guide", section = "12.2", page = 106 },
{ document = "guide", section = "13.1.2", page = 240 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMPK_GT_I32"
family = "SOPK"
opcode = 5
variant = "CmpkGtI32"
operation = "compare"
relation = "gt"
signedness = "signed"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopk_compare"
spec = [
{ document = "guide", section = "12.2", page = 106 },
{ document = "guide", section = "13.1.2", page = 240 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMPK_GE_I32"
family = "SOPK"
opcode = 6
variant = "CmpkGeI32"
operation = "compare"
relation = "ge"
signedness = "signed"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopk_compare"
spec = [
{ document = "guide", section = "12.2", page = 106 },
{ document = "guide", section = "13.1.2", page = 240 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMPK_LT_I32"
family = "SOPK"
opcode = 7
variant = "CmpkLtI32"
operation = "compare"
relation = "lt"
signedness = "signed"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopk_compare"
spec = [
{ document = "guide", section = "12.2", page = 106 },
{ document = "guide", section = "13.1.2", page = 240 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMPK_LE_I32"
family = "SOPK"
opcode = 8
variant = "CmpkLeI32"
operation = "compare"
relation = "le"
signedness = "signed"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopk_compare"
spec = [
{ document = "guide", section = "12.2", page = 106 },
{ document = "guide", section = "13.1.2", page = 240 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMPK_EQ_U32"
family = "SOPK"
opcode = 9
variant = "CmpkEqU32"
operation = "compare"
relation = "eq"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopk_compare"
spec = [
{ document = "guide", section = "12.2", page = 106 },
{ document = "guide", section = "13.1.2", page = 240 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMPK_LG_U32"
family = "SOPK"
opcode = 10
variant = "CmpkLgU32"
operation = "compare"
relation = "lg"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopk_compare"
spec = [
{ document = "guide", section = "12.2", page = 106 },
{ document = "guide", section = "13.1.2", page = 240 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMPK_GT_U32"
family = "SOPK"
opcode = 11
variant = "CmpkGtU32"
operation = "compare"
relation = "gt"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopk_compare"
spec = [
{ document = "guide", section = "12.2", page = 106 },
{ document = "guide", section = "13.1.2", page = 240 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMPK_GE_U32"
family = "SOPK"
opcode = 12
variant = "CmpkGeU32"
operation = "compare"
relation = "ge"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopk_compare"
spec = [
{ document = "guide", section = "12.2", page = 106 },
{ document = "guide", section = "13.1.2", page = 240 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMPK_LT_U32"
family = "SOPK"
opcode = 13
variant = "CmpkLtU32"
operation = "compare"
relation = "lt"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopk_compare"
spec = [
{ document = "guide", section = "12.2", page = 106 },
{ document = "guide", section = "13.1.2", page = 240 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMPK_LE_U32"
family = "SOPK"
opcode = 14
variant = "CmpkLeU32"
operation = "compare"
relation = "le"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopk_compare"
spec = [
{ document = "guide", section = "12.2", page = 106 },
{ document = "guide", section = "13.1.2", page = 240 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_ADDK_I32"
family = "SOPK"
opcode = 15
variant = "AddkI32"
operation = "add"
signedness = "signed"
carry_in = "none"
width = 32
scc = "signed_overflow"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopk_sgpr"
spec = [
{ document = "guide", section = "12.2", page = 106 },
{ document = "guide", section = "13.1.2", page = 240 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_MULK_I32"
family = "SOPK"
opcode = 16
variant = "MulkI32"
operation = "mul"
signedness = "signed"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopk_sgpr"
spec = [
{ document = "guide", section = "12.2", page = 106 },
{ document = "guide", section = "13.1.2", page = 240 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
+123
View File
@@ -0,0 +1,123 @@
# Wave32 VOP1 integer forms, AMD RDNA 2 ISA guide 12.8.
[operand_rules.vop1_vgpr]
family = "VOP1"
dst = { field = "VDST", class = "vgpr", min = 0, max = 255 }
src = [{ field = "SRC0", class = "vector_source" }]
max_literals = 1
unsupported = [
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special",
]
# Both operands are read and written by swap; SRC0 must select a VGPR.
[operand_rules.vop1_swap]
family = "VOP1"
dst = { field = "VDST", class = "vgpr", min = 0, max = 255 }
src = [{ field = "SRC0", class = "vgpr" }]
max_literals = 0
unsupported = [
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
"src_float_inline", "src_special", "src_literal",
]
[[form]]
name = "V_NOT_B32"
family = "VOP1"
opcode = 55
variant = "NotB32"
operation = "not"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "wave32"
operands = "vop1_vgpr"
spec = [{ document = "guide", section = "12.8", page = 143 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_BFREV_B32"
family = "VOP1"
opcode = 56
variant = "BfrevB32"
operation = "brev"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "wave32"
operands = "vop1_vgpr"
spec = [{ document = "guide", section = "12.8", page = 143 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_FFBH_U32"
family = "VOP1"
opcode = 57
variant = "FfbhU32"
operation = "flbit"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "wave32"
operands = "vop1_vgpr"
spec = [{ document = "guide", section = "12.8", page = 143 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_FFBL_B32"
family = "VOP1"
opcode = 58
variant = "FfblB32"
operation = "ff1"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "wave32"
operands = "vop1_vgpr"
spec = [{ document = "guide", section = "12.8", page = 143 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_FFBH_I32"
family = "VOP1"
opcode = 59
variant = "FfbhI32"
operation = "flbit"
signedness = "signed"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "wave32"
operands = "vop1_vgpr"
spec = [{ document = "guide", section = "12.8", page = 144 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_SWAP_B32"
family = "VOP1"
opcode = 101
variant = "SwapB32"
operation = "swap"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "wave32"
operands = "vop1_swap"
spec = [{ document = "guide", section = "12.8", page = 149 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
+42 -8
View File
@@ -19,7 +19,8 @@ pub use rdna2::{
V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
};
pub use semantics_gen::{
ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp,
ScalarAluOp, ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp, ScalarUnaryOp,
VectorAluOp, VectorAluVop3Op, VectorCompareOp, VectorSwapOp, VectorUnaryOp,
};
/// SGPR index of `vcc_lo`, the Wave32 vector condition code.
@@ -154,6 +155,14 @@ pub enum Instruction {
WaitStore,
/// VOP1 unmodified 32-bit vector move.
MoveB32 { dst: u8, src: VectorSource },
/// VOP1 unary integer operation with a single VGPR result.
VectorUnary {
op: VectorUnaryOp,
dst: u8,
src: VectorSource,
},
/// VOP1 register swap. Both operands are inputs and outputs.
VectorSwap { op: VectorSwapOp, dst: u8, src: u8 },
/// VOP3 encoding of a registry VOP2 integer operation (operand rule
/// `vop3_vgpr2`): two VGPR sources and no input or output modifiers.
VectorAluVop3 {
@@ -162,10 +171,8 @@ pub enum Instruction {
src0: u8,
src1: u8,
},
/// SOP1 32-bit move to a normal SGPR or an EXEC/VCC half.
ScalarMoveB32 { dst: u8, src: ScalarSource },
/// SOP1 32-bit unary integer operation writing a normal SGPR (s0-s105) and,
/// for some operations, SCC.
/// SOP1 32-bit unary integer operation. The move also allows an explicit
/// VCC or EXEC half destination. Some unary operations write SCC.
ScalarUnary {
op: ScalarUnaryOp,
dst: u8,
@@ -185,6 +192,21 @@ pub enum Instruction {
src0: ScalarSource,
src1: ScalarSource,
},
/// SOPK 32-bit integer operation on SDST (s0-s105, never s0-s7) and the
/// 16-bit immediate `simm16`; `s_addk_i32` also writes SCC and
/// `s_cmovk_i32` reads it.
ScalarImmediate {
op: ScalarImmediateOp,
dst: u8,
simm16: u16,
},
/// SOPK 32-bit integer compare of `src` (s0-s105) with the 16-bit
/// immediate, writing only SCC.
ScalarImmediateCompare {
op: ScalarImmediateCompareOp,
src: u8,
simm16: u16,
},
/// VOPC 32-bit integer compare writing a Wave32 mask to `vcc_lo`.
/// `src0` is a VGPR, `s0-s105`, `vcc_lo`, an inline integer or a literal.
VectorCompare {
@@ -265,11 +287,14 @@ impl Instruction {
Self::WaitLoad => "s_waitcnt",
Self::WaitStore => "s_waitcnt_vscnt",
Self::MoveB32 { .. } => "v_mov_b32_e32",
Self::VectorUnary { op, .. } => op.assembly_name(),
Self::VectorSwap { op, .. } => op.assembly_name(),
Self::VectorAluVop3 { op, .. } => op.assembly_name(),
Self::ScalarMoveB32 { .. } => "s_mov_b32",
Self::ScalarUnary { op, .. } => op.mnemonic(),
Self::ScalarAlu { op, .. } => op.mnemonic(),
Self::ScalarCompare { op, .. } => op.mnemonic(),
Self::ScalarImmediate { op, .. } => op.mnemonic(),
Self::ScalarImmediateCompare { op, .. } => op.mnemonic(),
Self::VectorCompare { op, .. } => op.assembly_name(),
Self::VectorAlu { op, .. } => op.assembly_name(),
Self::BranchSccZero { .. } => "s_cbranch_scc0",
@@ -315,7 +340,10 @@ impl fmt::Display for Instruction {
}
Self::WaitLoad => formatter.write_str(" vmcnt(0)"),
Self::WaitStore => formatter.write_str(" null, 0"),
Self::MoveB32 { dst, src } => write!(formatter, " v{dst}, {src}"),
Self::MoveB32 { dst, src } | Self::VectorUnary { dst, src, .. } => {
write!(formatter, " v{dst}, {src}")
}
Self::VectorSwap { dst, src, .. } => write!(formatter, " v{dst}, v{src}"),
Self::VectorAluVop3 {
dst, src0, src1, ..
}
@@ -323,13 +351,19 @@ impl fmt::Display for Instruction {
| Self::VectorMulF32 { dst, src0, src1 } => {
write!(formatter, " v{dst}, v{src0}, v{src1}")
}
Self::ScalarMoveB32 { dst, src } | Self::ScalarUnary { dst, src, .. } => {
Self::ScalarUnary { dst, src, .. } => {
write!(formatter, " {}, {src}", ScalarDestination(dst))
}
Self::ScalarAlu {
dst, src0, src1, ..
} => write!(formatter, " {}, {src0}, {src1}", ScalarDestination(dst)),
Self::ScalarCompare { src0, src1, .. } => write!(formatter, " {src0}, {src1}"),
Self::ScalarImmediate { dst, simm16, .. } => {
write!(formatter, " s{dst}, {simm16:#x}")
}
Self::ScalarImmediateCompare { src, simm16, .. } => {
write!(formatter, " s{src}, {simm16:#x}")
}
Self::VectorCompare { src0, src1, .. } => {
write!(formatter, " vcc_lo, {src0}, v{src1}")
}
+10
View File
@@ -218,6 +218,11 @@ pub const fn sext_i32(a: u32, bits: u32) -> u32 {
(((a << shift) as i32) >> shift) as u32
}
/// SIMM16 sign-extended to 32 bits (SOPK, guide 12.2).
pub const fn sext_simm16(simm16: u16) -> u32 {
simm16 as i16 as i32 as u32
}
/// Two's-complement absolute value (wrapping, so `0x80000000` stays) and
/// whether the result is nonzero.
pub const fn abs_nonzero_i32(a: u32) -> (u32, bool) {
@@ -326,3 +331,8 @@ pub const fn lshl_add_carry_u32(a: u32, b: u32, shift: u32) -> (u32, bool) {
let sum = ((a as u64) << shift) + b as u64;
(sum as u32, sum >> 32 != 0)
}
/// A bitwise copy of the source (RDNA 2 guide section 12.3).
pub(crate) const fn mov_b32(src: u32) -> u32 {
src
}
+35
View File
@@ -90,6 +90,27 @@ pub enum Operation {
Multiply24,
/// Bits 63:32 of the product of S0[23:0] and S1[23:0] (sign-extended when signed).
MultiplyHigh24,
/// SOPK: SDST receives the sign-extended SIMM16.
Move,
/// SOPK: SDST receives the sign-extended SIMM16 when SCC is set.
ConditionalMove,
/// Swap the two old per-lane VGPR values (guide 12.8).
Swap,
}
/// Per-lane integer operation with one input and one result.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VectorUnary {
/// Bitwise complement.
Not,
/// Reverse bit order.
ReverseBits,
/// Count leading zeros, or return all ones for zero.
FindHighUnsigned,
/// Count trailing zeros, or return all ones for zero.
FindLow,
/// Count leading sign bits, or return all ones if every bit matches.
FindHighSigned,
}
/// The per-lane integer operation a vector form lowers to. One reusable MSL
@@ -204,6 +225,16 @@ pub enum OperandRule {
/// SOP1 unary: SDST is s0-s105; SSRC0 is s0-s105, an inline integer -16..64 or
/// a literal word. Everything else is rejected as unsupported.
Sop1Sgpr,
/// SOP1 move: the same sources as Sop1Sgpr, with VCC and EXEC halves
/// also allowed as explicit destinations.
Sop1Move,
/// SOPK integer: SDST is s0-s105 and, except for compares, written (never s0-s7,
/// which hold resource descriptors); SIMM16 is the 16-bit immediate. The word
/// never takes a literal. Everything else is rejected as unsupported.
SopkSgpr,
/// SOPK integer compare: SDST (s0-s105) is the left operand, SIMM16 the right
/// (sign-extended for `_i32`, zero-extended for `_u32`); only SCC is written.
SopkCompare,
/// VOPC vector compare: the destination is `vcc_lo` (Wave32); SRC0 is a VGPR,
/// s0-s105, `vcc_lo`, an inline integer -16..64 or a literal word; VSRC1 is a
/// VGPR. Everything else is rejected as unsupported.
@@ -219,6 +250,10 @@ pub enum OperandRule {
/// VOP2 vector, VGPR sources only: VDST is v0-v255; SRC0 and VSRC1 are VGPRs.
/// Everything else (SGPR, inline, literal SRC0) is rejected as unsupported.
Vop2Vgpr2,
/// VOP1 unary: VGPR VDST and the same SRC0 domain as VOP2.
Vop1Vgpr,
/// VOP1 swap: VDST and SRC0 each read and write a VGPR.
Vop1Swap,
}
/// Evidence a form needs before it counts as verified.
File diff suppressed because it is too large. Load diff
+60 -3
View File
@@ -5,8 +5,8 @@ use xenora_isa::semantics::{
CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, MaskEffect, SCHEMA, SccEffect, Signedness, Wave,
};
use xenora_isa::{
CompareRelation, ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op,
VectorCompareOp,
CompareRelation, ScalarAluOp, ScalarCompareOp, ScalarImmediateCompareOp, ScalarImmediateOp,
ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp,
};
#[test]
@@ -78,6 +78,64 @@ fn scalar_compare_dispatch_selects_exactly_the_registry_sopc_forms() {
});
}
#[test]
fn scalar_immediate_dispatch_selects_exactly_the_registry_sopk_forms() {
for op in ScalarImmediateOp::ALL {
let row = op.semantics();
assert_eq!(row.family, EncodingFamily::Sopk);
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
assert_eq!(op.reads_scc(), row.carry_in == CarryIn::Scc);
assert_eq!(op.writes_scc(), row.scc != SccEffect::Unchanged);
}
for op in ScalarImmediateCompareOp::ALL {
let row = op.semantics();
assert_eq!(row.family, EncodingFamily::Sopk);
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
assert_eq!(row.relation, Some(op.relation()));
}
// The two enums together are the registry's SOPK forms; the fixed
// s_waitcnt_vscnt word (opcode 23) stays hand-written and is in neither.
dispatch_selects_exactly(EncodingFamily::Sopk, |word| {
ScalarImmediateOp::from_word(word)
.map(|op| op.semantics().name)
.or_else(|| ScalarImmediateCompareOp::from_word(word).map(|op| op.semantics().name))
});
}
#[test]
fn scalar_immediate_evaluation_extends_simm16_as_the_form_declares() {
// SIMM16 = 0x8000 is -32768 signed and 32768 unsigned.
let d = 0xffff_8000;
assert_eq!(
ScalarImmediateOp::MovkI32.evaluate(0, 0x8000, false),
(Some(d), None)
);
assert_eq!(
ScalarImmediateOp::CmovkI32.evaluate(7, 0x8000, true),
(Some(d), None)
);
assert_eq!(
ScalarImmediateOp::CmovkI32.evaluate(7, 0x8000, false),
(None, None)
);
assert_eq!(
ScalarImmediateOp::AddkI32.evaluate(0x7fff_ffff, 1, false),
(Some(0x8000_0000), Some(true))
);
assert_eq!(
ScalarImmediateOp::AddkI32.evaluate(5, 0xffff, false),
(Some(4), Some(false))
);
assert_eq!(
ScalarImmediateOp::MulkI32.evaluate(3, 0xffff, true),
(Some(0xffff_fffd), None)
);
assert!(ScalarImmediateCompareOp::CmpkEqI32.test(d, 0x8000));
assert!(!ScalarImmediateCompareOp::CmpkEqU32.test(d, 0x8000));
assert!(ScalarImmediateCompareOp::CmpkGtU32.test(d, 0xffff));
assert!(!ScalarImmediateCompareOp::CmpkGtI32.test(d, 0xffff));
}
#[test]
fn scalar_unary_dispatch_selects_exactly_the_registry_sop1_forms() {
for op in ScalarUnaryOp::ALL {
@@ -86,7 +144,6 @@ fn scalar_unary_dispatch_selects_exactly_the_registry_sop1_forms() {
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
assert_eq!(op.writes_scc(), row.scc != SccEffect::Unchanged);
}
// s_mov_b32 (opcode 3) stays hand-written, so it must not be dispatched here.
dispatch_selects_exactly(EncodingFamily::Sop1, |word| {
ScalarUnaryOp::from_word(word).map(|op| op.semantics().name)
});
+10 -4
View File
@@ -7,8 +7,9 @@
differs. Never writes.
Rejects unknown keys and vocabulary, overlapping encodings, digit and plain
forms sharing an opcode, operand constraints that contradict each other, and
flags declared both written and undefined. Standard library only (Python 3.11+).
forms sharing an opcode, operand constraints that contradict each other, LOCK
on a form that cannot write memory, and flags declared both written and
undefined. Standard library only (Python 3.11+).
"""
import sys
@@ -26,7 +27,7 @@ RUST = HERE / "src/x86_table.rs"
TOP_KEYS = {"schema", "architecture", "documents", "operation", "alu", "form", "group"}
OPERATION_KEYS = {"reads", "writes", "undefined", "conditional", "terminator", "faults", "ref"}
FORM_KEYS = {"op", "map", "prefix", "opcode", "count", "digit", "enc", "size", "imm", "src",
"memory_only", "register_only", "no_rex_b", "unaligned"}
"memory_only", "register_only", "no_rex_b", "unaligned", "lock"}
GROUP_KEYS = {"map", "opcodes", "digits"}
FLAGS = ["cf", "zf", "sf", "of", "pf", "af"]
MAPS = {"1": "ONE_BYTE", "0f": "TWO_BYTE"}
@@ -63,6 +64,8 @@ ENCS = {
"reg_xmm": ("RegXmm", True, {""}),
"reg_xmm_imm": ("RegXmmImm", True, {"ub"}),
}
# Encodings whose ModRM operand is the destination, so LOCK can apply to it.
RM_DESTINATIONS = {"rm_reg", "rm", "rm_imm", "rm_one", "rm_cl"}
# Encodings whose ModRM operand is an XMM register or memory of the source width.
XMM_RM = {"xmm_rm", "rm_xmm", "xmm_rm_imm", "rm_imm_xmm", "reg_xmm", "reg_xmm_imm"}
# One-byte opcodes that are prefixes or the two-byte escape, never instructions.
@@ -171,6 +174,8 @@ def load(text):
if (form["size"] == "x") != (form["enc"] in XMM_RM - {"reg_xmm", "reg_xmm_imm"}
or form["enc"] == "xmm_gpr_imm"):
fail(f"{where}: XMM size does not match the encoding")
if form.get("lock") and (form["enc"] not in RM_DESTINATIONS or form.get("register_only")):
fail(f"{where}: LOCK needs a memory destination")
if form.get("unaligned") and form["src"] != "x":
fail(f"{where}: alignment applies only to 16-byte operands")
if form["prefix"] and form["map"] != "0f":
@@ -266,7 +271,8 @@ def generate(operations, forms):
f"memory_only: {str(bool(form.get('memory_only'))).lower()}, "
f"register_only: {str(bool(form.get('register_only'))).lower()}, "
f"no_rex_b: {str(bool(form.get('no_rex_b'))).lower()}, "
f"unaligned: {str(bool(form.get('unaligned'))).lower()} }},")
f"unaligned: {str(bool(form.get('unaligned'))).lower()}, "
f"lockable: {str(bool(form.get('lock'))).lower()} }},")
out += ["];", ""]
groups = []
+20
View File
@@ -306,6 +306,26 @@ impl Arm64Assembler {
);
}
/// RBIT Xd, Xn: reverse the bit order of the source.
pub fn rbit_64(&mut self, xd: u8, xn: u8) {
self.emit(0xdac0_0000 | ((u32::from(xn) & 0x1f) << 5) | (u32::from(xd) & 0x1f));
}
/// CLZ Xd, Xn: count the leading zero bits of the source.
pub fn clz_64(&mut self, xd: u8, xn: u8) {
self.emit(0xdac0_1000 | ((u32::from(xn) & 0x1f) << 5) | (u32::from(xd) & 0x1f));
}
/// LSLV Xd, Xn, Xm: shift the source left by the amount in Xm.
pub fn lslv_64(&mut self, xd: u8, xn: u8, xm: u8) {
self.emit(
0x9ac2_2000
| ((u32::from(xm) & 0x1f) << 16)
| ((u32::from(xn) & 0x1f) << 5)
| (u32::from(xd) & 0x1f),
);
}
/// LDR Qt, [Xn, #offset] (offset a multiple of 16)
pub fn ldr_q_uoff(&mut self, qt: u8, xn: u8, offset: u32) {
self.emit(
+29
View File
@@ -123,6 +123,35 @@ impl CpuState {
}
}
/// CPUID leaf 1, EDX: CMOVcc.
pub const CPUID_CMOV: u32 = 1 << 15;
/// CPUID leaf 1, ECX: POPCNT.
pub const CPUID_POPCNT: u32 = 1 << 23;
/// CPUID leaf 0x8000_0001, ECX: LZCNT.
pub const CPUID_LZCNT: u32 = 1 << 5;
/// CPUID leaf 0x8000_0001, EDX: 64-bit mode.
pub const CPUID_LONG_MODE: u32 = 1 << 29;
/// What the guest's CPUID returns in EAX, EBX, ECX and EDX.
///
/// The table is fixed and never reads the host. It names a synthetic
/// processor, not an Intel or AMD product, and sets a feature bit only when
/// every instruction of that feature is implemented. A leaf that is not
/// listed returns zeros.
pub fn cpuid(leaf: u32, _subleaf: u32) -> [u32; 4] {
let word = |text: &[u8; 4]| u32::from_le_bytes(*text);
match leaf {
// Highest basic leaf, then "Xenora guest" in EBX, EDX, ECX.
0 => [1, word(b"Xeno"), word(b"uest"), word(b"ra g")],
// No family, model or stepping: this is no shipped processor.
1 => [0, 0, CPUID_POPCNT, CPUID_CMOV],
// Highest extended leaf.
0x8000_0000 => [0x8000_0001, 0, 0, 0],
0x8000_0001 => [0, 0, CPUID_LZCNT, CPUID_LONG_MODE],
_ => [0; 4],
}
}
/// Termination reason for guest execution.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ExitReason {
+85
View File
@@ -330,10 +330,18 @@ pub fn is_translatable(insn: &Insn) -> bool {
/// [`DbtMetrics::interpreter_fallbacks`].
pub fn is_native(insn: &Insn) -> bool {
let wide = matches!(insn.size, 4 | 8);
// The bit scans work on any register or memory source, and the bit test
// needs the index in a register.
let scanned = matches!(insn.size, 2 | 4 | 8);
match insn.op {
Op::Add | Op::Sub | Op::Cmp | Op::And | Op::Or | Op::Xor | Op::Test => wide,
Op::Inc | Op::Dec | Op::Neg | Op::Not => wide,
Op::Cmov => wide,
Op::Bsf | Op::Bsr => scanned,
// Only the `0F A3` form has the bit index in a register. The `0F BA`
// group form takes an immediate index and may write memory, so it
// stays on the shared semantics.
Op::Bt => scanned && insn.encoding == Encoding::RmReg,
Op::Pop => insn.encoding == Encoding::OpReg,
Op::Mov
| Op::Movzx
@@ -500,6 +508,18 @@ impl Emitter<'_> {
}
}
/// Zero-extend the low `size` bytes of `xd` to the full 64-bit register.
///
/// An operation narrower than the register reads only the low bytes of its
/// source, so the bits above them must not take part in a bit scan.
fn zero_extend(&mut self, xd: u8, size: u8) {
match size {
8 => {}
4 => self.asm.mov_reg_32(xd, xd),
_ => self.asm.uxth_32(xd, xd),
}
}
/// Effective address into X1, clobbering X9.
fn effective_address(&mut self, operand: &MemOperand, with_segment: bool) {
let asm = &mut *self.asm;
@@ -1032,6 +1052,71 @@ impl Emitter<'_> {
self.load_condition(insn.condition);
self.store_rm(insn, X12, completed);
}
Op::Bsf | Op::Bsr => {
// BSF and BSR write the index of the lowest or the highest set
// bit of the source into the destination and set the zero flag
// when the source is zero (Intel SDM Volume 2B, "BSF" and
// "BSR"). A zero source leaves the destination undefined, so
// the destination keeps its value, which is the same rule the
// interpreter and the reference apply.
self.load_rm(X9, insn, completed);
self.zero_extend(X9, insn.size);
match insn.op {
// The lowest set bit is the highest set bit of the
// reversed value, so its index is the leading zero count
// of the reversed value.
Op::Bsf => {
self.asm.rbit_64(X10, X9);
self.asm.clz_64(X10, X10);
}
// The highest set bit sits at 63 minus the leading zero
// count.
_ => {
self.asm.clz_64(X10, X9);
self.asm.movz_64(X13, 63, 0);
self.asm.sub_reg_64(X10, X13, X10);
}
}
self.load_reg(X11, insn.reg);
self.asm.tst_reg_64(X9, X9);
// CSEL takes the first operand when the condition holds, so
// the index is the value that replaces the destination.
self.asm.csel_64(X11, X10, X11, Condition::Ne);
match insn.size {
// A 16-bit destination keeps the bits above it, so the
// register is merged rather than replaced.
2 => self.store_reg(insn.reg, insn.size, X11),
// A 32-bit or 64-bit destination is written in full. The
// index has no bits above the operand width, so this
// matches the interpreter's 32-bit write, and a zero
// source keeps the whole register unchanged.
_ => self.asm.str_uoff_64(X11, X19, reg_offset(insn.reg.index)),
}
if flags {
// The zero flag is set when the source is zero. The other
// flags are undefined and keep their value.
self.asm.cset_32(X12, Condition::Eq);
self.asm.strb_uoff(X12, X19, ZF);
}
}
Op::Bt => {
// BT sets the carry flag from the tested bit and leaves the
// other flags undefined (Intel SDM Volume 2B, "BT"). The bit
// index comes from the register operand and is masked to the
// operand width.
self.load_rm(X9, insn, completed);
self.zero_extend(X9, insn.size);
self.load_reg(X10, insn.reg);
self.asm.load_imm_64(X13, u64::from(8 * insn.size - 1));
self.asm.and_reg_64(X10, X10, X13);
self.asm.load_imm_64(X11, 1);
self.asm.lslv_64(X11, X11, X10);
self.asm.tst_reg_64(X9, X11);
if flags {
self.asm.cset_32(X12, Condition::Ne);
self.asm.strb_uoff(X12, X19, CF);
}
}
Op::Cmov => {
self.load_rm(X10, insn, completed);
self.load_reg(X9, insn.reg);
+145 -2
View File
@@ -3,6 +3,10 @@
//! Bounded parser for the PE32+ import directory (Microsoft PE format,
//! "The .idata Section"). Binding and static inspection both use it, so they
//! agree on which imports an image has and how they are named.
//!
//! Static inspection also reads the delay-load directory ("Delay-Load Import
//! Tables (Image Only)"). Binding does not: the PE format leaves those imports
//! to a delay-load helper that runs inside the image on first use.
use std::fmt;
@@ -14,6 +18,9 @@ pub const MAX_IMPORTS: usize = 65_536;
pub const MAX_NAME_LEN: usize = 4096;
const DESCRIPTOR_LEN: u32 = 20;
const DELAY_DESCRIPTOR_LEN: u32 = 32;
/// Delay-load attribute bit 0: the descriptor's address fields are RVAs.
const DELAY_RVA_BASED: u32 = 1;
const ORDINAL_FLAG: u64 = 1 << 63;
/// How an import names its target. A symbol that happens to be spelled like an
@@ -42,6 +49,24 @@ pub struct ImportEntry {
pub iat_rva: u32,
}
/// A delay-load descriptor field that must hold an RVA.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DelayField {
DllName,
AddressTable,
NameTable,
}
impl fmt::Display for DelayField {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::DllName => "DLL name",
Self::AddressTable => "import address table",
Self::NameTable => "import name table",
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ImportTableError {
/// A structure at this RVA is not fully backed by section data.
@@ -56,6 +81,25 @@ pub enum ImportTableError {
ReservedBits {
rva: u32,
},
/// The delay-load descriptor at this RVA sets reserved attribute bits.
DelayReservedBits {
rva: u32,
},
/// The delay-load descriptor at this RVA has `RvaBased` clear, the earlier
/// form whose address fields are virtual addresses. It is not read.
DelayVirtualAddresses {
rva: u32,
},
/// The delay-load descriptor at this RVA leaves a required field zero.
DelayFieldMissing {
rva: u32,
field: DelayField,
},
/// The declared delay-load directory ends at this RVA before its empty
/// descriptor.
DelayDirectoryEnd {
rva: u32,
},
TooManyDescriptors,
TooManyImports,
}
@@ -63,7 +107,10 @@ pub enum ImportTableError {
impl fmt::Display for ImportTableError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::OutOfBounds { rva } => write!(f, "import data at RVA 0x{rva:08x} is truncated"),
Self::OutOfBounds { rva } => write!(
f,
"import data at RVA 0x{rva:08x} is truncated or outside the section data"
),
Self::MalformedName { rva } => write!(f, "malformed import name at RVA 0x{rva:08x}"),
Self::ReservedBits { rva } => {
write!(
@@ -71,6 +118,21 @@ impl fmt::Display for ImportTableError {
"reserved bits set in the import lookup at RVA 0x{rva:08x}"
)
}
Self::DelayReservedBits { rva } => write!(
f,
"reserved attribute bits set in the delay-load descriptor at RVA 0x{rva:08x}"
),
Self::DelayVirtualAddresses { rva } => write!(
f,
"delay-load descriptor at RVA 0x{rva:08x} holds virtual addresses, not RVAs, and is not read"
),
Self::DelayFieldMissing { rva, field } => {
write!(f, "delay-load descriptor at RVA 0x{rva:08x} has no {field}")
}
Self::DelayDirectoryEnd { rva } => write!(
f,
"delay-load directory ends at RVA 0x{rva:08x} before its empty descriptor"
),
Self::TooManyDescriptors => write!(f, "more than {MAX_DESCRIPTORS} import descriptors"),
Self::TooManyImports => write!(f, "more than {MAX_IMPORTS} imported symbols"),
}
@@ -159,7 +221,7 @@ fn collect<F: Fn(u32) -> Option<usize>>(
return Ok(());
}
let module = reader.name(name_rva)?;
collect_symbols(reader, &module, lookup_rva, address_rva, entries)?;
collect_symbols(reader, &module, lookup_rva, address_rva, false, entries)?;
descriptor = descriptor
.checked_add(DESCRIPTOR_LEN)
.ok_or(ImportTableError::OutOfBounds { rva: descriptor })?;
@@ -167,11 +229,88 @@ fn collect<F: Fn(u32) -> Option<usize>>(
Err(ImportTableError::TooManyDescriptors)
}
/// Parse the delay-load directory of `directory_size` bytes at `directory_rva`.
///
/// Only descriptors that lie wholly inside the declared directory are read,
/// and the directory must hold the empty descriptor that ends the table.
/// Each entry's `iat_rva` is its slot in the delay import address table.
/// Returns every import before the first problem, and the problem.
pub fn parse_delay_imports(
bytes: &[u8],
directory_rva: u32,
directory_size: u32,
rva_to_offset: impl Fn(u32) -> Option<usize>,
) -> (Vec<ImportEntry>, Option<ImportTableError>) {
let reader = Reader {
bytes,
rva_to_offset,
};
let mut entries = Vec::new();
let error = collect_delayed(&reader, directory_rva, directory_size, &mut entries).err();
(entries, error)
}
fn collect_delayed<F: Fn(u32) -> Option<usize>>(
reader: &Reader<'_, F>,
directory_rva: u32,
directory_size: u32,
entries: &mut Vec<ImportEntry>,
) -> Result<(), ImportTableError> {
let end = directory_rva
.checked_add(directory_size)
.ok_or(ImportTableError::OutOfBounds { rva: directory_rva })?;
let mut descriptor = directory_rva;
for _ in 0..MAX_DESCRIPTORS {
if end - descriptor < DELAY_DESCRIPTOR_LEN {
return Err(ImportTableError::DelayDirectoryEnd { rva: end });
}
let fields = reader.array::<{ DELAY_DESCRIPTOR_LEN as usize }>(descriptor)?;
// The table ends with an empty descriptor.
if fields == [0; DELAY_DESCRIPTOR_LEN as usize] {
return Ok(());
}
let attributes = reader.u32(descriptor)?;
if attributes & !DELAY_RVA_BASED != 0 {
return Err(ImportTableError::DelayReservedBits { rva: descriptor });
}
if attributes & DELAY_RVA_BASED == 0 {
return Err(ImportTableError::DelayVirtualAddresses { rva: descriptor });
}
let name_rva = reader.u32(descriptor + 4)?;
let address_rva = reader.u32(descriptor + 12)?;
let names_rva = reader.u32(descriptor + 16)?;
// All three are required. The address table holds thunk addresses, so
// it cannot stand in for a missing name table.
for (field, rva) in [
(DelayField::DllName, name_rva),
(DelayField::AddressTable, address_rva),
(DelayField::NameTable, names_rva),
] {
if rva == 0 {
return Err(ImportTableError::DelayFieldMissing {
rva: descriptor,
field,
});
}
}
// Each must also start in section data, whether or not an import uses it.
reader.array::<1>(name_rva)?;
reader.array::<8>(address_rva)?;
reader.array::<8>(names_rva)?;
let module = reader.name(name_rva)?;
collect_symbols(reader, &module, names_rva, address_rva, true, entries)?;
// The declared end bounds this sum.
descriptor += DELAY_DESCRIPTOR_LEN;
}
Err(ImportTableError::TooManyDescriptors)
}
fn collect_symbols<F: Fn(u32) -> Option<usize>>(
reader: &Reader<'_, F>,
module: &str,
lookup_rva: u32,
address_rva: u32,
slots_on_disk: bool,
entries: &mut Vec<ImportEntry>,
) -> Result<(), ImportTableError> {
// Without a lookup table the address table holds the same entries on disk.
@@ -194,6 +333,10 @@ fn collect_symbols<F: Fn(u32) -> Option<usize>>(
return Err(ImportTableError::TooManyImports);
}
let iat_rva = at(address_rva)?;
if slots_on_disk {
// A delay-load slot starts out holding its thunk's address.
reader.array::<8>(iat_rva)?;
}
let name = if value & ORDINAL_FLAG != 0 {
let ordinal = value & !ORDINAL_FLAG;
ImportName::Ordinal(
+113 -28
View File
@@ -11,7 +11,9 @@
//! startup blockers.
use crate::dbt::{is_native, is_translatable};
use crate::import_table::{ImportName, ImportTableError, parse_imports};
use crate::import_table::{
ImportEntry, ImportName, ImportTableError, parse_delay_imports, parse_imports,
};
use crate::imports::{ImportRegistry, ServiceStatus};
use crate::memory::MemoryPermissions;
use crate::pe::{IMAGE_FILE_MACHINE_AMD64, PE32_PLUS_MAGIC, ParsedPe, PeError, PeSection};
@@ -678,6 +680,11 @@ pub struct ProbeReport {
pub imports: Vec<ImportedSymbol>,
/// Why the import table could not be read to its end.
pub import_error: Option<ImportTableError>,
/// Delay-loaded imports before the first malformed entry, if any. Binding
/// does not resolve them, so `imports` and its totals leave them out.
pub delayed_imports: Vec<ImportedSymbol>,
/// Why the delay-load import tables could not be read to their end.
pub delay_import_error: Option<ImportTableError>,
pub instruction_records: Vec<InstructionRecord>,
pub first_unsupported_dbt_insn: Option<InstructionRecord>,
}
@@ -822,6 +829,30 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
} else {
0
};
// The delay import descriptor is data directory 13. It exists only when
// NumberOfRvaAndSizes covers it.
let (delay_dir_rva, delay_dir_size) = if size_of_optional_header >= 224
&& u32::from_le_bytes(
bytes[opt_offset + 108..opt_offset + 112]
.try_into()
.unwrap(),
) > 13
{
(
u32::from_le_bytes(
bytes[opt_offset + 216..opt_offset + 220]
.try_into()
.unwrap(),
),
u32::from_le_bytes(
bytes[opt_offset + 220..opt_offset + 224]
.try_into()
.unwrap(),
),
)
} else {
(0, 0)
};
let section_table_offset = opt_offset + size_of_optional_header;
let section_header_size = 40;
@@ -960,35 +991,40 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
&mut registry,
Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))),
);
// Binding accepts only bytes backed by section data; match it exactly.
let backed_offset = |rva: u32| {
sections.iter().find_map(|section| {
let offset = rva.checked_sub(section.virtual_address)?;
(offset < section.raw_data_size)
.then(|| (section.raw_data_ptr as usize).checked_add(offset as usize))?
})
};
let (entries, import_error) = if import_dir_rva == 0 {
(Vec::new(), None)
} else {
// Binding accepts only bytes backed by section data; match it exactly.
parse_imports(bytes, import_dir_rva, |rva| {
sections.iter().find_map(|section| {
let offset = rva.checked_sub(section.virtual_address)?;
(offset < section.raw_data_size)
.then(|| (section.raw_data_ptr as usize).checked_add(offset as usize))?
})
})
parse_imports(bytes, import_dir_rva, backed_offset)
};
let imports: Vec<ImportedSymbol> = entries
.into_iter()
.map(|entry| {
let binding = registry.resolve(&entry.module, &entry.name);
ImportedSymbol {
category: ProbeReport::categorize_dll(&entry.module),
dll: entry.module,
symbol: entry.name.to_string(),
import_name: entry.name,
iat_rva: entry.iat_rva,
is_supported: binding.is_some(),
service_status: binding.map(|service| service.status),
canonical_module: binding.map(|service| service.module.clone()),
canonical_symbol: binding.map(|service| service.symbol.clone()),
}
})
.collect();
let (delayed_entries, delay_import_error) = if delay_dir_rva == 0 {
(Vec::new(), None)
} else {
parse_delay_imports(bytes, delay_dir_rva, delay_dir_size, backed_offset)
};
let describe = |entry: ImportEntry| {
let binding = registry.resolve(&entry.module, &entry.name);
ImportedSymbol {
category: ProbeReport::categorize_dll(&entry.module),
dll: entry.module,
symbol: entry.name.to_string(),
import_name: entry.name,
iat_rva: entry.iat_rva,
is_supported: binding.is_some(),
service_status: binding.map(|service| service.status),
canonical_module: binding.map(|service| service.module.clone()),
canonical_symbol: binding.map(|service| service.symbol.clone()),
}
};
let imports: Vec<ImportedSymbol> = entries.into_iter().map(&describe).collect();
let delayed_imports: Vec<ImportedSymbol> = delayed_entries.into_iter().map(&describe).collect();
// 4. Control-Flow-Aware Static Disassembly
//
@@ -1124,6 +1160,8 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
tls,
imports,
import_error,
delayed_imports,
delay_import_error,
instruction_records,
first_unsupported_dbt_insn,
})
@@ -1142,7 +1180,7 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
// 1. imports.csv
let mut imports_csv = String::from(
"module,symbol_or_ordinal,iat_rva,category,registered_binding,implementation_status,is_alias,canonical_module,startup_priority,startup_cluster,trusted_runner_binding,import_kind\n",
"module,symbol_or_ordinal,iat_rva,import_table,category,registered_binding,implementation_status,is_alias,canonical_module,startup_priority,startup_cluster,trusted_runner_binding,import_kind\n",
);
let mut missing_csv = String::from("module,symbol_or_ordinal,iat_rva,import_kind\n");
let mut modules = BTreeSet::new();
@@ -1186,7 +1224,7 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
let canonical = canonical.replace('"', "\"\"");
let _ = writeln!(
imports_csv,
"{key},{},{},{status},{is_alias},\"{canonical}\",{priority},{cluster},{trusted_binding},{import_kind}",
"{key},ordinary,{},{},{status},{is_alias},\"{canonical}\",{priority},{cluster},{trusted_binding},{import_kind}",
imp.category, imp.is_supported
);
if !imp.is_supported {
@@ -1194,6 +1232,34 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
missing += 1;
}
}
// Delay-loaded imports follow the ordinary rows. Binding does not resolve
// them, so they stay out of every ordinary total, the startup clusters and
// `missing_imports.csv`.
let mut delayed_modules = BTreeSet::new();
for imp in &report.delayed_imports {
delayed_modules.insert(imp.dll.to_ascii_lowercase());
let is_ordinal = matches!(imp.import_name, ImportName::Ordinal(_));
let import_kind = if is_ordinal { "ordinal" } else { "name" };
let module = imp.dll.replace('"', "\"\"");
let symbol = imp.symbol.replace('"', "\"\"");
let canonical = imp.canonical_module.as_deref().unwrap_or("");
let is_alias = imp.canonical_module.is_some() && !imp.dll.eq_ignore_ascii_case(canonical);
let canonical = canonical.replace('"', "\"\"");
let (priority, cluster) = imp.startup_priority();
let _ = writeln!(
imports_csv,
"\"{module}\",\"{symbol}\",0x{:08x},delayed,{},{},{},{is_alias},\"{canonical}\",{priority},{cluster},false,{import_kind}",
imp.iat_rva,
imp.category,
imp.is_supported,
imp.coverage_label()
);
}
let delayed_slots = report.delayed_imports.len();
let delayed_dlls = delayed_modules.len();
let delay_error = report
.delay_import_error
.map_or_else(|| "none".to_string(), |error| error.to_string());
fs::write(out.join("imports.csv"), imports_csv)?;
fs::write(out.join("missing_imports.csv"), missing_csv)?;
@@ -1250,6 +1316,9 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
"stub_slots": {stubs},
"recognized_unsupported_slots": {unsupported},
"missing_handler_slots": {unknown},
"delayed_imports": {delayed_slots},
"delayed_imported_dlls_count": {delayed_dlls},
"delay_import_error": "{delay_error}",
"total_relocations": {},
"dir64_relocations": {},
"tls_callbacks_count": {},
@@ -1381,6 +1450,16 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
"- **Import table is malformed**: {error}. Only the imports before it are listed, and binding refuses the image.\n"
);
}
let _ = writeln!(
md,
"- **Delay-Loaded Import Slots**: `{delayed_slots}` across `{delayed_dlls}` DLLs. They are marked `delayed` in `imports.csv` and are not part of the counts above or of `missing_imports.csv`: binding does not resolve them, and the PE format leaves them to the image's delay-load helper.\n"
);
if let Some(error) = &report.delay_import_error {
let _ = writeln!(
md,
"- **Delay-load import table is malformed**: {error}. Only the delay-loaded imports before it are listed.\n"
);
}
if trusted_runner_slots > 0 {
let _ = writeln!(
md,
@@ -1425,6 +1504,12 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
distinct_imports.len(),
unique_symbols.len()
);
if delayed_slots > 0 {
let _ = writeln!(
matrix,
"\nThe delay-load import tables contain {delayed_slots} more slots across {delayed_dlls} DLLs. They are not counted in this document."
);
}
let _ = writeln!(
matrix,
"\nRegistered slots include {implemented} implemented, {partial} partial, and {stubs} stubs. They reference {} canonical registered services through {aliases} alias slots. The {missing} unresolved slots include {unsupported} explicitly tracked unsupported APIs and {unknown} other missing handlers.",
+15
View File
@@ -251,6 +251,21 @@ impl ServicesState {
.unwrap_or(0)
}
/// Forget the last-error value of a guest thread that has ended, so a
/// later thread given the same TEB address starts at zero. Returns
/// whether a nonzero value was dropped.
///
/// Each service call names its own TEB and the values sit behind one
/// lock, so calls for different threads may run concurrently. Retire a
/// TEB only once no service call for that thread is still running.
pub fn retire_thread_last_error(&self, teb: u64) -> bool {
self.last_errors
.lock()
.expect("guest last-error state")
.remove(&teb)
.is_some()
}
fn set_last_error(&self, teb: u64, error: u32) {
let mut errors = self.last_errors.lock().expect("guest last-error state");
if error == 0 {
+20 -2
View File
@@ -50,6 +50,8 @@ pub struct Form {
pub no_rex_b: bool,
/// A 16-byte memory operand may have any alignment.
pub unaligned: bool,
/// The LOCK prefix is accepted when the ModRM operand is memory.
pub lockable: bool,
}
/// Opcode table entry.
@@ -167,6 +169,9 @@ pub struct Insn {
pub imm: u64,
/// Condition code for Jcc, CMOVcc and SETcc.
pub condition: u8,
/// Carries a LOCK prefix. Set only for a lockable form with a memory
/// destination.
pub lock: bool,
}
impl Insn {
@@ -231,8 +236,9 @@ impl<E, F: FnMut(u64) -> Result<u8, E>> Cursor<F> {
/// Decode one instruction at `rip`. `fetch` supplies the byte at an address and
/// is called only for bytes that belong to the instruction, in order.
///
/// Forms the registry does not declare, LOCK, address-size overrides and an
/// ignored segment override after FS or GS are rejected rather than approximated.
/// Forms the registry does not declare, LOCK anywhere but on a lockable form
/// with a memory destination, address-size overrides and an ignored segment
/// override after FS or GS are rejected rather than approximated.
pub fn decode<E>(
rip: u64,
fetch: impl FnMut(u64) -> Result<u8, E>,
@@ -246,6 +252,7 @@ pub fn decode<E>(
let mut operand_size = false;
let mut rep = false;
let mut repne = false;
let mut lock = false;
let mut segment = None;
let mut byte = cursor.u8()?;
loop {
@@ -267,6 +274,11 @@ pub fn decode<E>(
byte = cursor.u8()?;
continue;
}
0xF0 => {
lock = true;
byte = cursor.u8()?;
continue;
}
// CS, DS, ES and SS overrides have no effect in 64-bit mode. After
// FS or GS their meaning is not relied on, so it is rejected.
0x26 | 0x2E | 0x36 | 0x3E if segment.is_none() => {
@@ -413,6 +425,11 @@ pub fn decode<E>(
} else if matches!(form.encoding, Encoding::OpReg | Encoding::OpRegImm) {
reg = register(opcode & 7, rex_b, size);
}
// LOCK is an invalid opcode unless the instruction is lockable and its
// destination is memory (Intel SDM Vol. 2, "LOCK").
if lock && !(form.lockable && matches!(rm, Some(RmOperand::Mem(_)))) {
return Err(DecodeError::Unsupported(0xF0));
}
let mut imm = match form.immediate {
Immediate::None => 0,
@@ -449,6 +466,7 @@ pub fn decode<E>(
reg,
imm,
condition: opcode & 0xF,
lock,
})
}
+39 -1
View File
@@ -10,7 +10,7 @@
//! the state unchanged. Flags that the architecture leaves undefined keep their
//! previous value, which is permitted but not something guests may rely on.
use crate::cpu::{CpuState, ExitReason, RFlags, Register};
use crate::cpu::{CpuState, ExitReason, RFlags, Register, cpuid};
use crate::memory::GuestMemory;
use crate::x86_decode::{Encoding, Insn, MemOperand, RegOperand, RmOperand, Segment};
use crate::x86_simd;
@@ -19,6 +19,7 @@ use crate::x86_table::Op;
const RAX: usize = Register::Rax as usize;
const RCX: usize = Register::Rcx as usize;
const RDX: usize = Register::Rdx as usize;
const RBX: usize = Register::Rbx as usize;
const RSP: usize = Register::Rsp as usize;
const RBP: usize = Register::Rbp as usize;
@@ -369,6 +370,35 @@ pub fn execute(
write_rm(cpu, memory, insn, b)?;
write_reg(cpu, insn.reg, size, a);
}
Op::Xadd => {
let (a, b) = operands(cpu, memory, insn)?;
let (value, flags) = add(a, b, false, size);
write_rm(cpu, memory, insn, value)?;
// The source is loaded before the destination is stored, so a
// register added to itself keeps the sum.
if insn.rm != Some(RmOperand::Reg(insn.reg)) {
write_reg(cpu, insn.reg, size, a);
}
cpu.flags = flags;
}
Op::Cmpxchg => {
let (destination, source) = operands(cpu, memory, insn)?;
let expected = cpu.gpr[RAX] & mask(size);
let (_, flags) = sub(expected, destination, false, size);
// The destination is written whether or not the values match, so a
// mismatch on memory that cannot be written still faults.
let matched = expected == destination;
write_rm(
cpu,
memory,
insn,
if matched { source } else { destination },
)?;
if !matched {
write_reg(cpu, accumulator(RAX), size, destination);
}
cpu.flags = flags;
}
Op::Bswap => {
let value = read_reg(cpu, insn.reg, size).swap_bytes() >> (64 - 8 * u32::from(size));
write_reg(cpu, insn.reg, size, value);
@@ -544,6 +574,14 @@ pub fn execute(
cpu.gpr[RSP] = sp.wrapping_add(8).wrapping_add(insn.imm);
}
Op::Nop => {}
Op::Cpuid => {
// The leaf is EAX and the subleaf ECX. Each result is a 32-bit
// register write, so the upper halves are cleared.
let values = cpuid(cpu.gpr[RAX] as u32, cpu.gpr[RCX] as u32);
for (register, value) in [RAX, RBX, RCX, RDX].into_iter().zip(values) {
cpu.gpr[register] = u64::from(value);
}
}
Op::Clc => cpu.flags.cf = false,
Op::Stc => cpu.flags.cf = true,
Op::Cmc => cpu.flags.cf = !cpu.flags.cf,
File diff suppressed because it is too large. Load diff
+282
View File
@@ -0,0 +1,282 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! The guest CPUID contract (issue #130).
//!
//! CPUID reports a fixed synthetic processor. A feature bit is set only when
//! every instruction of that feature is implemented, so each bit that is set
//! is checked against instructions that run, and each bit software commonly
//! tests that is clear has a witness instruction of that feature which both
//! engines refuse. The witness must be removed before its bit can be set.
//!
//! Bit positions and the feature each instruction belongs to are from the
//! Intel SDM Vol. 2, CPUID and the instruction entries. Encodings were
//! assembled with `clang -target x86_64-apple-macos` and read with `objdump`.
use xenora_loader::cpu::{
CPUID_CMOV, CPUID_LONG_MODE, CPUID_LZCNT, CPUID_POPCNT, CpuState, ExitReason, Interpreter,
RFlags, cpuid,
};
use xenora_loader::dbt::DbtEngine;
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
use xenora_loader::x86_decode::decode;
const ENTRY: u64 = 0x1000;
const RAX: usize = 0;
const RCX: usize = 1;
const RDX: usize = 2;
const RBX: usize = 3;
const RSI: usize = 6;
/// Index of a CPUID result, which come in the order EAX, EBX, ECX, EDX.
const EBX: usize = 1;
const ECX: usize = 2;
const EDX: usize = 3;
fn image(code: &[u8]) -> GuestMemory {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, code)
.unwrap();
memory
}
/// Final state and exit reason from the interpreter, then from the DBT.
fn both(cpu: &CpuState, code: &[u8], budget: usize) -> [(&'static str, CpuState, ExitReason); 2] {
let mut memory = image(code);
let interpreted = Interpreter::new(cpu.clone(), &mut memory, budget).run();
let mut memory = image(code);
let mut state = cpu.clone();
let translated = DbtEngine::new(64 * 1024)
.unwrap()
.run(&mut state, &mut memory, budget);
[
(
"interpreter",
interpreted.final_state,
interpreted.exit_reason,
),
("DBT", translated.final_state, translated.exit_reason),
]
}
const SET: RFlags = RFlags {
cf: true,
zf: true,
sf: true,
of: true,
pf: true,
af: true,
};
#[test]
fn every_leaf_returns_its_documented_values() {
// (leaf, subleaf, [EAX, EBX, ECX, EDX])
let leaves: &[(u32, u32, [u32; 4])] = &[
// Highest basic leaf 1, and "Xeno", "uest", "ra g" as little-endian text.
(0, 0, [1, 0x6F6E_6558, 0x7473_6575, 0x6720_6172]),
// POPCNT is ECX bit 23 and CMOV is EDX bit 15. No signature.
(1, 0, [0, 0, 0x0080_0000, 0x0000_8000]),
(1, 0xFFFF_FFFF, [0, 0, 0x0080_0000, 0x0000_8000]),
// Highest extended leaf.
(0x8000_0000, 0, [0x8000_0001, 0, 0, 0]),
// LZCNT is ECX bit 5 and long mode is EDX bit 29.
(0x8000_0001, 0, [0, 0, 0x0000_0020, 0x2000_0000]),
(0x8000_0001, 7, [0, 0, 0x0000_0020, 0x2000_0000]),
// Everything else, above or between the highest leaves, is zeros.
(2, 0, [0; 4]),
(4, 0, [0; 4]),
(6, 0, [0; 4]),
(7, 0, [0; 4]),
(7, 1, [0; 4]),
(0xB, 0, [0; 4]),
(0xD, 1, [0; 4]),
(0x16, 0, [0; 4]),
(0x4000_0000, 0, [0; 4]),
(0x7FFF_FFFF, 0, [0; 4]),
(0x8000_0002, 0, [0; 4]),
(0x8000_0008, 0, [0; 4]),
(0xFFFF_FFFF, 0, [0; 4]),
];
for &(leaf, subleaf, wanted) in leaves {
// Only EAX and ECX select the leaf: the upper halves are noise.
let mut cpu = CpuState::new(ENTRY, 0);
for (index, register) in cpu.gpr.iter_mut().enumerate() {
*register = 0xA5A5_0000_1111_0000 + index as u64;
}
cpu.gpr[RAX] = 0xDEAD_BEEF_0000_0000 | u64::from(leaf);
cpu.gpr[RCX] = 0xFEED_FACE_0000_0000 | u64::from(subleaf);
cpu.flags = SET;
// Each result is a 32-bit register write, so it clears the upper half.
// CPUID changes no flag and no other register.
let mut expected = cpu.clone();
expected.rip = ENTRY + 2;
for (register, value) in [RAX, RBX, RCX, RDX].into_iter().zip(wanted) {
expected.gpr[register] = u64::from(value);
}
for (engine, state, exit) in both(&cpu, &[0x0F, 0xA2], 1) {
let what = format!("leaf {leaf:#x} subleaf {subleaf:#x} on the {engine}");
assert_eq!(exit, ExitReason::StepLimitExceeded, "{what}");
assert_eq!(state, expected, "{what}");
}
// The function a runtime service would read agrees with the instruction.
assert_eq!(cpuid(leaf, subleaf), wanted, "leaf {leaf:#x}");
}
let [_, ebx, ecx, edx] = cpuid(0, 0);
let vendor: Vec<u8> = [ebx, edx, ecx]
.into_iter()
.flat_map(u32::to_le_bytes)
.collect();
assert_eq!(vendor, b"Xenora guest");
assert_eq!(
(CPUID_POPCNT, CPUID_CMOV, CPUID_LZCNT, CPUID_LONG_MODE),
(1 << 23, 1 << 15, 1 << 5, 1 << 29)
);
}
#[test]
fn reported_features_have_all_their_instructions_in_the_fixtures() {
// `tests/x86_integer.rs` runs every line of this file through both engines
// against an independent reference. Here each reported feature must have
// its whole instruction set among those lines.
let fixture = include_str!("x86/integer.txt");
let decodable = |text: &str| {
let line = fixture
.lines()
.find(|line| line.split_once(" | ").is_some_and(|(_, asm)| asm == text))
.unwrap_or_else(|| panic!("no fixture for {text}"));
let code: Vec<u8> = line
.split_once(" | ")
.unwrap()
.0
.split(' ')
.map(|byte| u8::from_str_radix(byte, 16).unwrap())
.collect();
decode(ENTRY, |at| {
code.get((at - ENTRY) as usize).copied().ok_or(())
})
.unwrap_or_else(|error| panic!("{text}: {error:?}"));
};
let memory = |bits: u32| {
let width = match bits {
16 => "word",
32 => "dword",
_ => "qword",
};
format!("{width} ptr [rsi + 4*rdi + 16]")
};
// 16-, 32- and 64-bit destinations (RBX and R10) from a register and from memory.
let sizes = [
(16, "bx", "r9w", "r10w"),
(32, "ebx", "r9d", "r10d"),
(64, "rbx", "r9", "r10"),
];
assert_ne!(cpuid(1, 0)[EDX] & CPUID_CMOV, 0);
for condition in "o no b ae e ne be a s ns p np l ge le g".split(' ') {
for (bits, low, source, high) in sizes {
decodable(&format!("cmov{condition} {low}, {source}"));
decodable(&format!("cmov{condition} {high}, {}", memory(bits)));
}
}
for (feature, bit, name) in [
(cpuid(1, 0)[ECX], CPUID_POPCNT, "popcnt"),
(cpuid(0x8000_0001, 0)[ECX], CPUID_LZCNT, "lzcnt"),
] {
assert_ne!(feature & bit, 0, "{name}");
for (bits, low, source, high) in sizes {
decodable(&format!("{name} {low}, {source}"));
decodable(&format!("{name} {high}, {}", memory(bits)));
}
}
// Long mode: 64-bit operands and the registers only it has.
assert_ne!(cpuid(0x8000_0001, 0)[EDX] & CPUID_LONG_MODE, 0);
decodable("add r9, r12");
decodable("movabs r15, 0x8877665544332211");
}
#[test]
fn unreported_features_each_have_an_instruction_that_is_refused() {
// (feature, leaf, result register, bit, an instruction of that feature)
let witnesses: &[(&str, u32, usize, u32, &[u8])] = &[
("FPU", 1, EDX, 0, &[0xD9, 0xE8]), // fld1
("TSC", 1, EDX, 4, &[0x0F, 0x31]), // rdtsc
("CX8", 1, EDX, 8, &[0x0F, 0xC7, 0x0E]), // cmpxchg8b [rsi]
("CLFSH", 1, EDX, 19, &[0x0F, 0xAE, 0x3E]), // clflush [rsi]
("MMX", 1, EDX, 23, &[0x0F, 0x77]), // emms
("FXSR", 1, EDX, 24, &[0x0F, 0xAE, 0x06]), // fxsave [rsi]
("SSE", 1, EDX, 25, &[0x0F, 0x52, 0xC1]), // rsqrtps xmm0, xmm1
("SSE2", 1, EDX, 26, &[0x0F, 0xAE, 0xF0]), // mfence
("SSE3", 1, ECX, 0, &[0xF2, 0x0F, 0x7C, 0xC1]), // haddps xmm0, xmm1
(
"PCLMULQDQ",
1,
ECX,
1,
&[0x66, 0x0F, 0x3A, 0x44, 0xC1, 0x00],
), // pclmulqdq xmm0, xmm1, 0
("SSSE3", 1, ECX, 9, &[0x66, 0x0F, 0x38, 0x00, 0xC1]), // pshufb xmm0, xmm1
("FMA", 1, ECX, 12, &[0xC4, 0xE2, 0x71, 0x98, 0xC2]), // vfmadd132ps xmm0, xmm1, xmm2
("CMPXCHG16B", 1, ECX, 13, &[0x48, 0x0F, 0xC7, 0x0E]), // cmpxchg16b [rsi]
("SSE4.1", 1, ECX, 19, &[0x66, 0x0F, 0x38, 0x40, 0xC1]), // pmulld xmm0, xmm1
("SSE4.2", 1, ECX, 20, &[0xF2, 0x0F, 0x38, 0xF1, 0xC1]), // crc32 eax, ecx
("MOVBE", 1, ECX, 22, &[0x0F, 0x38, 0xF0, 0x06]), // movbe eax, [rsi]
("AESNI", 1, ECX, 25, &[0x66, 0x0F, 0x38, 0xDC, 0xC1]), // aesenc xmm0, xmm1
("XSAVE", 1, ECX, 26, &[0x0F, 0x01, 0xD0]), // xgetbv
("AVX", 1, ECX, 28, &[0xC5, 0xF4, 0x58, 0xC2]), // vaddps ymm0, ymm1, ymm2
("F16C", 1, ECX, 29, &[0xC4, 0xE2, 0x79, 0x13, 0xC1]), // vcvtph2ps xmm0, xmm1
("RDRAND", 1, ECX, 30, &[0x0F, 0xC7, 0xF0]), // rdrand eax
("BMI1", 7, EBX, 3, &[0xC4, 0xE2, 0x70, 0xF2, 0xC2]), // andn eax, ecx, edx
("AVX2", 7, EBX, 5, &[0xC5, 0xF5, 0xFE, 0xC2]), // vpaddd ymm0, ymm1, ymm2
("BMI2", 7, EBX, 8, &[0xC4, 0xE2, 0x73, 0xF6, 0xC2]), // mulx eax, ecx, edx
("RDSEED", 7, EBX, 18, &[0x0F, 0xC7, 0xF8]), // rdseed eax
("ADX", 7, EBX, 19, &[0x66, 0x0F, 0x38, 0xF6, 0xC1]), // adcx eax, ecx
("SHA", 7, EBX, 29, &[0x0F, 0x38, 0xC9, 0xC1]), // sha1msg1 xmm0, xmm1
("LAHF/SAHF", 0x8000_0001, ECX, 0, &[0x9F]), // lahf
("PREFETCHW", 0x8000_0001, ECX, 8, &[0x0F, 0x0D, 0x0E]), // prefetchw [rsi]
("SYSCALL/SYSRET", 0x8000_0001, EDX, 11, &[0x48, 0x0F, 0x07]), // sysretq
("RDTSCP", 0x8000_0001, EDX, 27, &[0x0F, 0x01, 0xF9]), // rdtscp
];
for &(feature, leaf, register, bit, code) in witnesses {
assert_eq!(
cpuid(leaf, 0)[register] >> bit & 1,
0,
"{feature} is reported"
);
let mut padded = code.to_vec();
padded.extend([0x90; 8]);
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[RSI] = ENTRY;
for (engine, state, exit) in both(&cpu, &padded, 1) {
assert!(
matches!(exit, ExitReason::IllegalInstruction(_)),
"{feature}: {code:02X?} ran on the {engine} ({exit:?}); report the feature only \
once all of it is implemented"
);
assert_eq!(state, cpu, "{feature} on the {engine}");
}
}
}
#[test]
fn a_guest_can_use_an_instruction_after_testing_its_feature_bit() {
// mov eax, 1
// cpuid
// bt ecx, 23 ; POPCNT
// jnc done
// popcnt rax, rsi
// done: hlt
let code = [
0xB8, 0x01, 0x00, 0x00, 0x00, 0x0F, 0xA2, 0x0F, 0xBA, 0xE1, 0x17, 0x73, 0x05, 0xF3, 0x48,
0x0F, 0xB8, 0xC6, 0xF4,
];
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[RSI] = 0xF0F0_0000_0000_0001;
for (engine, state, exit) in both(&cpu, &code, 16) {
assert_eq!(exit, ExitReason::Halt, "{engine}");
// Nine bits are set in RSI. Leaf 1 leaves EAX zero, so a skipped
// POPCNT would show as 0.
assert_eq!(state.gpr[RAX], 9, "{engine}");
assert_eq!(state.rip, ENTRY + code.len() as u64, "{engine}");
}
}
-14
View File
@@ -2672,15 +2672,9 @@ const UNSUPPORTED: &[(&str, usize)] = &[
("cmpxchg16b_not_equal", 0),
("cmpxchg16b_unaligned_is_gp", 0),
("cmpxchg16b_unaligned_without_lock_is_gp", 0),
("cmpxchg32_equal", 0),
("cmpxchg64_memory_equal_without_lock", 0),
("cmpxchg64_memory_not_equal", 0),
("cmpxchg64_memory_not_equal_without_lock", 0),
("cmpxchg8_not_equal_loads_al", 0),
("cmpxchg8b_equal", 0),
("cmpxchg8b_equal_without_lock", 0),
("cmpxchg8b_not_equal", 0),
("cmpxchg_mismatch_still_writes", 0),
("crc32c_byte_and_qword_forms_agree", 0),
("crc32c_check_string", 0),
("dpps_mask", 0),
@@ -2689,8 +2683,6 @@ const UNSUPPORTED: &[(&str, usize)] = &[
("fs_addr32_truncates_before_adding_base", 0),
("fs_rep_movsb_overrides_source_only", 0),
("fs_rep_movsb_overrides_source_only_df_clear", 0),
("gs_lock_xadd", 0),
("gs_xadd_without_lock", 0),
("haddps_hsubpd_addsubps", 0),
("insertps_zero_mask", 0),
("jecxz_tests_low_32_bits", 1),
@@ -2783,12 +2775,6 @@ const UNSUPPORTED: &[(&str, usize)] = &[
("shrd32_by8", 0),
("shrd64_by1_sign_change", 0),
("shrd64_cl64_is_count_zero", 0),
("xadd32_reg_reg", 0),
("xadd64_memory", 0),
("xadd64_memory_without_lock", 0),
("xadd64_same_register_doubles", 0),
("xadd8_al_ah", 0),
("xadd_readonly_page_keeps_register", 0),
("xchg_ax_r9w_preserves_both_uppers", 0),
("xchg_eax_ebx_clears_both_uppers", 0),
("xchg_rax_r8_is_not_nop", 0),
+419
View File
@@ -0,0 +1,419 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Static probe reports for delay-loaded PE imports.
//!
//! The expected names and slot RVAs are read off the layout that
//! `fixtures/pe/delay-imports.py` writes, not from the parser.
//! `llvm-readobj --coff-imports` from LLVM 23.1.6 lists the same imports in
//! the same order, with the address tables at RVA 0x2050, 0x3000 and 0x3020.
use std::collections::BTreeMap;
use xenora_loader::import_table::{DelayField, ImportTableError, parse_delay_imports};
use xenora_loader::probe::{
ImportedSymbol, ProbeConfig, ProbeReport, probe_pe_bytes, run_probe_and_export,
};
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/delay-imports.exe");
/// DLL, symbol or ordinal, and import address table slot RVA.
type Row = (&'static str, &'static str, u32);
const ORDINARY: [Row; 2] = [
("fixture-ordinary.dll", "OrdinaryByName", 0x2050),
("fixture-ordinary.dll", "Ordinal#3", 0x2058),
];
const DELAYED: [Row; 3] = [
("fixture-delay-a.dll", "DelayedAlpha", 0x3000),
("fixture-delay-a.dll", "Ordinal#7", 0x3008),
("fixture-delay-b.dll", "DelayedBeta", 0x3020),
];
// File offsets in the fixture.
const NUMBER_OF_RVA_AND_SIZES: usize = 0x98 + 108;
const DELAY_DIRECTORY_ENTRY: usize = 0x98 + 216;
const DELAY_DIRECTORY_SIZE: usize = DELAY_DIRECTORY_ENTRY + 4;
const RDATA_RAW_SIZE: usize = 0x188 + 40 + 16;
/// The delay-load directory is at RVA 0x2200; `.rdata` maps RVA 0x2000 to 0x600.
const FIRST_DESCRIPTOR: usize = 0x800;
const SECOND_DESCRIPTOR: usize = 0x820;
fn rows(imports: &[ImportedSymbol]) -> Vec<(&str, &str, u32)> {
imports
.iter()
.map(|import| (import.dll.as_str(), import.symbol.as_str(), import.iat_rva))
.collect()
}
fn put(pe: &mut [u8], offset: usize, value: u32) {
pe[offset..offset + 4].copy_from_slice(&value.to_le_bytes());
}
/// Probe `pe` and return the report with the text files it exports.
fn export(pe: &[u8], name: &str) -> (ProbeReport, BTreeMap<&'static str, String>) {
let dir =
std::env::temp_dir().join(format!("xenora-probe-delay-{name}-{}", std::process::id()));
let report = run_probe_and_export(pe, &dir, &ProbeConfig::default()).unwrap();
let files = [
"imports.csv",
"missing_imports.csv",
"candidate_static_report.json",
"candidate_static_report.md",
"runtime_gap_matrix.md",
]
.into_iter()
.map(|file| (file, std::fs::read_to_string(dir.join(file)).unwrap()))
.collect();
std::fs::remove_dir_all(dir).unwrap();
(report, files)
}
fn json_field(json: &str, name: &str) -> String {
let prefix = format!("\"{name}\": ");
json.lines()
.find_map(|line| line.trim().strip_prefix(&prefix))
.unwrap_or_else(|| panic!("no {name} in the JSON report"))
.trim_end_matches(',')
.trim_matches('"')
.to_string()
}
#[test]
fn ordinary_and_delayed_imports_are_reported_apart() {
let (report, files) = export(FIXTURE, "fixture");
assert_eq!(rows(&report.imports), ORDINARY);
assert_eq!(rows(&report.delayed_imports), DELAYED);
assert_eq!(report.import_error, None);
assert_eq!(report.delay_import_error, None);
let mut lines = files["imports.csv"].lines();
let header = lines.next().unwrap();
assert!(header.starts_with("module,symbol_or_ordinal,iat_rva,import_table,"));
assert!(header.ends_with(",import_kind"));
let columns = header.split(',').count();
// The first four columns and the last one of every row.
let listed: Vec<String> = lines
.map(|line| {
let fields: Vec<&str> = line.split(',').collect();
assert_eq!(fields.len(), columns, "{line}");
format!("{},{}", fields[..4].join(","), fields[columns - 1])
})
.collect();
assert_eq!(
listed,
[
"\"fixture-ordinary.dll\",\"OrdinaryByName\",0x00002050,ordinary,name",
"\"fixture-ordinary.dll\",\"Ordinal#3\",0x00002058,ordinary,ordinal",
"\"fixture-delay-a.dll\",\"DelayedAlpha\",0x00003000,delayed,name",
"\"fixture-delay-a.dll\",\"Ordinal#7\",0x00003008,delayed,ordinal",
"\"fixture-delay-b.dll\",\"DelayedBeta\",0x00003020,delayed,name",
]
);
// Neither fixture DLL has a handler, so both ordinary imports are missing.
// The delayed ones are not the binder's to resolve and stay off its list.
assert_eq!(
files["missing_imports.csv"].lines().collect::<Vec<_>>(),
[
"module,symbol_or_ordinal,iat_rva,import_kind",
"\"fixture-ordinary.dll\",\"OrdinaryByName\",0x00002050,name",
"\"fixture-ordinary.dll\",\"Ordinal#3\",0x00002058,ordinal",
]
);
let json = &files["candidate_static_report.json"];
for (name, expected) in [
("total_imports", "2"),
("imported_dlls_count", "1"),
("unresolved_imports", "2"),
("distinct_import_keys", "2"),
("delayed_imports", "3"),
("delayed_imported_dlls_count", "2"),
("delay_import_error", "none"),
] {
assert_eq!(json_field(json, name), expected, "{name}");
}
let md = &files["candidate_static_report.md"];
assert!(md.contains("- **Total Imported Thunks**: `2`"));
assert!(md.contains("- **Delay-Loaded Import Slots**: `3` across `2` DLLs."));
assert!(!md.contains("Delay-load import table is malformed"));
assert!(
files["runtime_gap_matrix.md"]
.contains("The delay-load import tables contain 3 more slots across 2 DLLs.")
);
}
#[test]
fn inspection_decodes_the_entry_point_and_follows_no_delay_slot() {
let report = probe_pe_bytes(FIXTURE, &ProbeConfig::default()).unwrap();
// The entry point is a lone RET at RVA 0x1000. The three delay-load slots
// hold the addresses of INT3 stubs at 0x1010, 0x1018 and 0x1020. Reaching
// one would mean the probe followed a slot, so none may be decoded.
let decoded: Vec<(u32, &[u8])> = report
.instruction_records
.iter()
.map(|record| (record.rva, record.bytes.as_slice()))
.collect();
assert_eq!(decoded, [(0x1000, &[0xc3][..])]);
}
#[test]
fn image_without_a_delay_directory_keeps_its_ordinary_imports() {
// `fixtures/pe/trusted-runner.py` writes one import, `xenora.dll!fixture_draw`,
// with its slot at RVA 0x2040 and no delay import descriptor.
let runner = include_bytes!("../../../fixtures/pe/trusted-runner.exe");
let (report, files) = export(runner, "runner");
assert_eq!(
rows(&report.imports),
[("xenora.dll", "fixture_draw", 0x2040)]
);
assert_eq!(report.import_error, None);
assert!(report.delayed_imports.is_empty());
assert_eq!(report.delay_import_error, None);
let listed: Vec<&str> = files["imports.csv"].lines().skip(1).collect();
assert_eq!(listed.len(), 1);
assert!(listed[0].starts_with("\"xenora.dll\",\"fixture_draw\",0x00002040,ordinary,"));
let json = &files["candidate_static_report.json"];
assert_eq!(json_field(json, "total_imports"), "1");
assert_eq!(json_field(json, "imported_dlls_count"), "1");
assert_eq!(json_field(json, "delayed_imports"), "0");
assert_eq!(json_field(json, "delayed_imported_dlls_count"), "0");
assert_eq!(json_field(json, "delay_import_error"), "none");
assert!(!files["runtime_gap_matrix.md"].contains("delay-load"));
}
#[test]
fn delay_directory_beyond_the_declared_count_is_not_read() {
// With 13 data directories the header has no delay import descriptor, so
// the bytes at its offset mean nothing.
let mut pe = FIXTURE.to_vec();
put(&mut pe, NUMBER_OF_RVA_AND_SIZES, 13);
let report = probe_pe_bytes(&pe, &ProbeConfig::default()).unwrap();
assert_eq!(rows(&report.imports), ORDINARY);
assert!(report.delayed_imports.is_empty());
assert_eq!(report.delay_import_error, None);
}
#[test]
fn malformed_delay_tables_are_diagnosed_and_ordinary_imports_kept() {
type Case = (
&'static str,
fn(&mut Vec<u8>),
usize,
ImportTableError,
&'static str,
);
// (name, damage, delayed imports still listed, error, message)
let cases: [Case; 13] = [
(
"directory-out-of-range",
|pe| put(pe, DELAY_DIRECTORY_ENTRY, 0x9000),
0,
ImportTableError::OutOfBounds { rva: 0x9000 },
"import data at RVA 0x00009000 is truncated or outside the section data",
),
(
// `.rdata` keeps 0x230 bytes: the first descriptor and half the second.
"section-data-ends-inside-descriptor",
|pe| put(pe, RDATA_RAW_SIZE, 0x230),
2,
ImportTableError::OutOfBounds { rva: 0x2220 },
"import data at RVA 0x00002220 is truncated or outside the section data",
),
(
// The file ends where `.data` and its address tables would begin.
"file-ends-before-address-table",
|pe| pe.truncate(0xa00),
0,
ImportTableError::OutOfBounds { rva: 0x3000 },
"import data at RVA 0x00003000 is truncated or outside the section data",
),
(
"name-table-out-of-range",
|pe| put(pe, FIRST_DESCRIPTOR + 16, 0x9000),
0,
ImportTableError::OutOfBounds { rva: 0x9000 },
"import data at RVA 0x00009000 is truncated or outside the section data",
),
(
"address-table-out-of-range",
|pe| put(pe, SECOND_DESCRIPTOR + 12, 0x9000),
2,
ImportTableError::OutOfBounds { rva: 0x9000 },
"import data at RVA 0x00009000 is truncated or outside the section data",
),
(
// The second DLL's name table becomes the empty entry that ends the
// first one, at RVA 0x2110, so no import reads the address table.
"address-table-out-of-range-without-imports",
|pe| {
put(pe, SECOND_DESCRIPTOR + 16, 0x2110);
put(pe, SECOND_DESCRIPTOR + 12, 0x9000);
},
2,
ImportTableError::OutOfBounds { rva: 0x9000 },
"import data at RVA 0x00009000 is truncated or outside the section data",
),
(
"dll-name-out-of-range",
|pe| put(pe, SECOND_DESCRIPTOR + 4, 0x9000),
2,
ImportTableError::OutOfBounds { rva: 0x9000 },
"import data at RVA 0x00009000 is truncated or outside the section data",
),
(
// RVA 0x2028 is zero padding after the ordinary import directory.
"dll-name-empty",
|pe| put(pe, SECOND_DESCRIPTOR + 4, 0x2028),
2,
ImportTableError::MalformedName { rva: 0x2028 },
"malformed import name at RVA 0x00002028",
),
(
"dll-name-missing",
|pe| put(pe, SECOND_DESCRIPTOR + 4, 0),
2,
ImportTableError::DelayFieldMissing {
rva: 0x2220,
field: DelayField::DllName,
},
"delay-load descriptor at RVA 0x00002220 has no DLL name",
),
(
"address-table-missing",
|pe| put(pe, FIRST_DESCRIPTOR + 12, 0),
0,
ImportTableError::DelayFieldMissing {
rva: 0x2200,
field: DelayField::AddressTable,
},
"delay-load descriptor at RVA 0x00002200 has no import address table",
),
(
"name-table-missing",
|pe| put(pe, SECOND_DESCRIPTOR + 16, 0),
2,
ImportTableError::DelayFieldMissing {
rva: 0x2220,
field: DelayField::NameTable,
},
"delay-load descriptor at RVA 0x00002220 has no import name table",
),
(
"reserved-attribute-bit",
|pe| put(pe, FIRST_DESCRIPTOR, 3),
0,
ImportTableError::DelayReservedBits { rva: 0x2200 },
"reserved attribute bits set in the delay-load descriptor at RVA 0x00002200",
),
(
"virtual-address-form",
|pe| put(pe, SECOND_DESCRIPTOR, 0),
2,
ImportTableError::DelayVirtualAddresses { rva: 0x2220 },
"delay-load descriptor at RVA 0x00002220 holds virtual addresses, not RVAs, and is not read",
),
];
for (name, damage, listed, error, message) in cases {
let mut pe = FIXTURE.to_vec();
damage(&mut pe);
let (report, files) = export(&pe, name);
assert_eq!(rows(&report.imports), ORDINARY, "{name}");
assert_eq!(report.import_error, None, "{name}");
assert_eq!(rows(&report.delayed_imports), DELAYED[..listed], "{name}");
assert_eq!(report.delay_import_error, Some(error), "{name}");
assert_eq!(error.to_string(), message, "{name}");
let json = &files["candidate_static_report.json"];
assert_eq!(json_field(json, "total_imports"), "2", "{name}");
assert_eq!(
json_field(json, "delayed_imports"),
listed.to_string(),
"{name}"
);
assert_eq!(json_field(json, "delay_import_error"), message, "{name}");
assert!(
files["candidate_static_report.md"].contains(&format!(
"- **Delay-load import table is malformed**: {message}. Only the delay-loaded imports before it are listed."
)),
"{name}"
);
}
}
#[test]
fn declared_directory_size_bounds_the_table() {
// The fixture declares 96 bytes at RVA 0x2200: two descriptors and the
// empty one. A descriptor counts only if the declared size holds all of
// it, and the size must reach the empty descriptor.
let end = |rva| Some(ImportTableError::DelayDirectoryEnd { rva });
for (size, listed, error) in [
(0, 0, end(0x2200)),
(31, 0, end(0x221f)),
(32, 2, end(0x2220)),
(63, 2, end(0x223f)),
(64, 3, end(0x2240)),
(95, 3, end(0x225f)),
(96, 3, None),
(97, 3, None),
(0x1000, 3, None),
// The directory would run past the end of the address space.
(
u32::MAX,
0,
Some(ImportTableError::OutOfBounds { rva: 0x2200 }),
),
] {
let mut pe = FIXTURE.to_vec();
put(&mut pe, DELAY_DIRECTORY_SIZE, size);
let report = probe_pe_bytes(&pe, &ProbeConfig::default()).unwrap();
assert_eq!(rows(&report.imports), ORDINARY, "size {size}");
assert_eq!(
rows(&report.delayed_imports),
DELAYED[..listed],
"size {size}"
);
assert_eq!(report.delay_import_error, error, "size {size}");
}
assert_eq!(
ImportTableError::DelayDirectoryEnd { rva: 0x2240 }.to_string(),
"delay-load directory ends at RVA 0x00002240 before its empty descriptor"
);
}
#[test]
fn endless_delay_table_is_refused() {
// Every descriptor RVA maps onto the same 32 bytes, so the table never
// reaches its empty entry within the megabyte it declares. The descriptor
// names module "a" at RVA 0x1000, an empty name table at RVA 0x2000 and an
// address table at RVA 0x3000.
let mut bytes = vec![0u8; 48];
put(&mut bytes, 0, 1);
put(&mut bytes, 4, 0x1000);
put(&mut bytes, 12, 0x3000);
put(&mut bytes, 16, 0x2000);
bytes[32] = b'a';
let (imports, error) = parse_delay_imports(&bytes, 0x10_0000, 0x10_0000, |rva| match rva {
0x1000..0x1002 => Some(32 + (rva - 0x1000) as usize),
0x2000..0x2008 => Some(40 + (rva - 0x2000) as usize),
0x3000..0x3008 => Some(40 + (rva - 0x3000) as usize),
0x10_0000.. => Some((rva % 32) as usize),
_ => None,
});
assert!(imports.is_empty());
assert_eq!(error, Some(ImportTableError::TooManyDescriptors));
}
#[test]
fn probe_never_panics_on_a_truncated_delay_fixture() {
for len in 1..=FIXTURE.len() {
// The probe may reject the file or report unreadable imports, but it
// must not panic.
let _ = probe_pe_bytes(&FIXTURE[..len], &ProbeConfig::default());
}
}
+54 -4
View File
@@ -120,17 +120,24 @@ fn build(imports: &[(&str, Symbol)]) -> Image {
}
fn standard(clock: u64) -> (ImportRegistry, Arc<MockClock>) {
let clock = Arc::new(MockClock::new(clock));
let mut registry = ImportRegistry::new();
register_standard_services(&mut registry, Arc::new(ServicesState::new(clock.clone())));
let (registry, clock, _) = standard_with_state(clock);
(registry, clock)
}
fn standard_with_state(clock: u64) -> (ImportRegistry, Arc<MockClock>, Arc<ServicesState>) {
let clock = Arc::new(MockClock::new(clock));
let state = Arc::new(ServicesState::new(clock.clone()));
let mut registry = ImportRegistry::new();
register_standard_services(&mut registry, state.clone());
(registry, clock, state)
}
/// A guest whose image imports every generated service from its own library.
struct Guest {
engine: DbtEngine,
memory: GuestMemory,
clock: Arc<MockClock>,
state: Arc<ServicesState>,
teb: u64,
/// Upper halves and XMM lanes of unrelated arguments hold this pattern.
xmm: [u128; 4],
@@ -151,7 +158,7 @@ impl Guest {
memory
.map_region(STACK, 0x1000, MemoryPermissions::READ_WRITE)
.unwrap();
let (mut registry, clock) = standard(0x01DA_0000_1234_5678);
let (mut registry, clock, state) = standard_with_state(0x01DA_0000_1234_5678);
let bound = registry
.bind_imports(&pe, &image.bytes, BASE, &mut memory)
.unwrap();
@@ -162,6 +169,7 @@ impl Guest {
engine,
memory,
clock,
state,
teb: 0,
xmm: [0xAAAA_BBBB_CCCC_DDDD_EEEE_FFFF_0123_4567; 4],
}
@@ -554,6 +562,48 @@ fn last_error_isolated_across_guest_thread_switches() {
assert_eq!(guest.last_error(), 6);
}
/// The last-error code is documented as kept per thread, and most functions
/// set it only when they fail (errhandlingapi.h GetLastError).
#[test]
fn a_successful_call_keeps_another_threads_error_and_its_own() {
let mut guest = Guest::new();
guest.teb = 0x10000;
assert_eq!(guest.call("VirtualAlloc", &[0, 0, 0x3000, 4]), 0);
assert_eq!(guest.last_error(), 87); // ERROR_INVALID_PARAMETER
guest.teb = 0x20000;
guest.call("SetLastError", &[0xFFFF_FFFF]);
assert_eq!(guest.call("GetCurrentProcess", &[]), PROCESS);
assert_eq!(guest.call("GetCurrentThreadId", &[]), 0x4104);
assert_eq!(
guest.last_error(),
0xFFFF_FFFF,
"success keeps a nonzero error"
);
guest.teb = 0x10000;
assert_eq!(guest.last_error(), 87);
}
#[test]
fn a_retired_thread_starts_clean_when_its_teb_address_is_reused() {
let mut guest = Guest::new();
guest.teb = 0x10000;
guest.call("SetLastError", &[998]);
guest.teb = 0x20000;
guest.call("CloseHandle", &[0x1234]);
assert!(guest.state.retire_thread_last_error(0x10000));
assert!(!guest.state.retire_thread_last_error(0x10000));
assert!(
!guest.state.retire_thread_last_error(0x30000),
"a thread that never failed holds no value"
);
assert_eq!(guest.last_error(), 6, "the other thread is untouched");
guest.teb = 0x10000;
assert_eq!(guest.last_error(), 0);
guest.call("SetLastError", &[5]);
assert_eq!(guest.last_error(), 5);
}
#[test]
fn last_error_is_set_by_failures_and_by_the_guest() {
let mut guest = Guest::new();
+17 -2
View File
@@ -84,9 +84,18 @@ def cases():
f"mov {mem(bits)}, {reg(2, bits)}", f"mov {reg(14, bits)}, 0x5a",
f"mov {mem(bits)}, 0x5a", f"xchg {reg(3, bits)}, {reg(9, bits)}",
f"xchg {mem(bits)}, {reg(2, bits)}"]
for op in ("xadd", "cmpxchg"):
for bits in (8, 16, 32, 64):
# Destination RAX always matches the accumulator; a register with
# itself keeps the sum. LOCK is valid only with a memory destination.
out += [f"{op} {reg(3, bits)}, {reg(1, bits)}", f"{op} {reg(9, bits)}, {reg(12, bits)}",
f"{op} {reg(0, bits)}, {reg(2, bits)}", f"{op} {reg(3, bits)}, {reg(3, bits)}",
f"{op} {mem(bits)}, {reg(2, bits)}", f"lock {op} {mem(bits)}, {reg(2, bits)}",
f"lock {op} {mem(bits)}, {reg(0, bits)}"]
out += [f"{op} ah, bl", f"{op} cl, dh", f"{op} {mem(8)}, ch"]
out += ["mov ah, bl", "mov dl, ch", "mov bh, 0x21", "xchg ah, bl", "mov sil, dil",
"movabs r15, 0x8877665544332211", "mov rcx, -2", "bswap ebx", "bswap r9",
"cbw", "cwde", "cdqe", "cwd", "cdq", "cqo", "clc", "stc", "cmc", "nop",
"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",
f"push {mem(64)}", "pop rbx", "pop r12", f"pop {mem(64)}", "leave"]
return list(dict.fromkeys(out))
@@ -163,7 +172,13 @@ def assemble(lines):
subprocess.run(["clang", "-target", "x86_64-apple-macos", "-c", source, "-o", obj], check=True)
# One line per instruction: objdump never wraps its raw bytes.
listing = subprocess.run(["objdump", "-d", obj], check=True, capture_output=True, text=True).stdout
rows = [m.group(1).split() for m in re.finditer(r"^\s*[0-9a-f]+:\s((?:[0-9a-f]{2}\s)+)", listing, re.M)]
rows, prefix = [], []
for match in re.finditer(r"^\s*[0-9a-f]+:\s((?:[0-9a-f]{2}\s)+)(.*)$", listing, re.M):
row = prefix + match.group(1).split()
# objdump lists a leading LOCK prefix on a row of its own.
prefix = row if match.group(2).strip() == "lock" else []
if not prefix:
rows.append(row)
if len(rows) != len(lines):
sys.exit(f"{len(lines)} instructions assembled to {len(rows)} rows")
return "".join(f"{' '.join(row)} | {line}\n" for row, line in zip(rows, lines))
+63
View File
@@ -953,6 +953,68 @@ c7 44 be 10 5a 00 00 00 | mov dword ptr [rsi + 4*rdi + 16], 0x5a
48 c7 44 be 10 5a 00 00 00 | mov qword ptr [rsi + 4*rdi + 16], 0x5a
49 87 d9 | xchg rbx, r9
48 87 54 be 10 | xchg qword ptr [rsi + 4*rdi + 16], rdx
0f c0 cb | xadd bl, cl
45 0f c0 e1 | xadd r9b, r12b
0f c0 d0 | xadd al, dl
0f c0 db | xadd bl, bl
0f c0 54 be 10 | xadd byte ptr [rsi + 4*rdi + 16], dl
f0 0f c0 54 be 10 | lock xadd byte ptr [rsi + 4*rdi + 16], dl
f0 0f c0 44 be 10 | lock xadd byte ptr [rsi + 4*rdi + 16], al
66 0f c1 cb | xadd bx, cx
66 45 0f c1 e1 | xadd r9w, r12w
66 0f c1 d0 | xadd ax, dx
66 0f c1 db | xadd bx, bx
66 0f c1 54 be 10 | xadd word ptr [rsi + 4*rdi + 16], dx
66 f0 0f c1 54 be 10 | lock xadd word ptr [rsi + 4*rdi + 16], dx
66 f0 0f c1 44 be 10 | lock xadd word ptr [rsi + 4*rdi + 16], ax
0f c1 cb | xadd ebx, ecx
45 0f c1 e1 | xadd r9d, r12d
0f c1 d0 | xadd eax, edx
0f c1 db | xadd ebx, ebx
0f c1 54 be 10 | xadd dword ptr [rsi + 4*rdi + 16], edx
f0 0f c1 54 be 10 | lock xadd dword ptr [rsi + 4*rdi + 16], edx
f0 0f c1 44 be 10 | lock xadd dword ptr [rsi + 4*rdi + 16], eax
48 0f c1 cb | xadd rbx, rcx
4d 0f c1 e1 | xadd r9, r12
48 0f c1 d0 | xadd rax, rdx
48 0f c1 db | xadd rbx, rbx
48 0f c1 54 be 10 | xadd qword ptr [rsi + 4*rdi + 16], rdx
f0 48 0f c1 54 be 10 | lock xadd qword ptr [rsi + 4*rdi + 16], rdx
f0 48 0f c1 44 be 10 | lock xadd qword ptr [rsi + 4*rdi + 16], rax
0f c0 dc | xadd ah, bl
0f c0 f1 | xadd cl, dh
0f c0 6c be 10 | xadd byte ptr [rsi + 4*rdi + 16], ch
0f b0 cb | cmpxchg bl, cl
45 0f b0 e1 | cmpxchg r9b, r12b
0f b0 d0 | cmpxchg al, dl
0f b0 db | cmpxchg bl, bl
0f b0 54 be 10 | cmpxchg byte ptr [rsi + 4*rdi + 16], dl
f0 0f b0 54 be 10 | lock cmpxchg byte ptr [rsi + 4*rdi + 16], dl
f0 0f b0 44 be 10 | lock cmpxchg byte ptr [rsi + 4*rdi + 16], al
66 0f b1 cb | cmpxchg bx, cx
66 45 0f b1 e1 | cmpxchg r9w, r12w
66 0f b1 d0 | cmpxchg ax, dx
66 0f b1 db | cmpxchg bx, bx
66 0f b1 54 be 10 | cmpxchg word ptr [rsi + 4*rdi + 16], dx
66 f0 0f b1 54 be 10 | lock cmpxchg word ptr [rsi + 4*rdi + 16], dx
66 f0 0f b1 44 be 10 | lock cmpxchg word ptr [rsi + 4*rdi + 16], ax
0f b1 cb | cmpxchg ebx, ecx
45 0f b1 e1 | cmpxchg r9d, r12d
0f b1 d0 | cmpxchg eax, edx
0f b1 db | cmpxchg ebx, ebx
0f b1 54 be 10 | cmpxchg dword ptr [rsi + 4*rdi + 16], edx
f0 0f b1 54 be 10 | lock cmpxchg dword ptr [rsi + 4*rdi + 16], edx
f0 0f b1 44 be 10 | lock cmpxchg dword ptr [rsi + 4*rdi + 16], eax
48 0f b1 cb | cmpxchg rbx, rcx
4d 0f b1 e1 | cmpxchg r9, r12
48 0f b1 d0 | cmpxchg rax, rdx
48 0f b1 db | cmpxchg rbx, rbx
48 0f b1 54 be 10 | cmpxchg qword ptr [rsi + 4*rdi + 16], rdx
f0 48 0f b1 54 be 10 | lock cmpxchg qword ptr [rsi + 4*rdi + 16], rdx
f0 48 0f b1 44 be 10 | lock cmpxchg qword ptr [rsi + 4*rdi + 16], rax
0f b0 dc | cmpxchg ah, bl
0f b0 f1 | cmpxchg cl, dh
0f b0 6c be 10 | cmpxchg byte ptr [rsi + 4*rdi + 16], ch
88 dc | mov ah, bl
88 ea | mov dl, ch
b7 21 | mov bh, 0x21
@@ -972,6 +1034,7 @@ f8 | clc
f9 | stc
f5 | cmc
90 | nop
0f a2 | cpuid
0f 1f 40 08 | nop dword ptr [rax + 8]
f3 90 | pause
41 51 | push r9
+376
View File
@@ -0,0 +1,376 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! XADD, CMPXCHG and the LOCK prefix (issue #198).
//!
//! Expected values follow the operation sections of the Intel SDM Vol. 2 for
//! XADD, CMPXCHG and LOCK, stated here as literal results. Encodings were
//! assembled with `clang -target x86_64-apple-macos` and read with `objdump`.
//! Nothing was compared with x86 hardware.
//!
//! Both engines run one guest instruction at a time on one host thread, so
//! these tests establish the single-thread results that any later guest
//! scheduler has to preserve. They say nothing about concurrent execution.
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, RFlags};
use xenora_loader::dbt::{DbtEngine, is_native};
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
use xenora_loader::x86_decode::decode;
const ENTRY: u64 = 0x1000;
/// Two writable pages. Nothing is mapped after them unless a test says so.
const DATA: u64 = 0x4000;
const PAGE: u64 = 0x1000;
const END: u64 = DATA + 2 * PAGE;
const RAX: usize = 0;
const RCX: usize = 1;
const RDX: usize = 2;
const RBX: usize = 3;
const RSI: usize = 6;
fn image(code: &[u8]) -> GuestMemory {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, code)
.unwrap();
memory
.map_region(DATA, 2 * PAGE as usize, MemoryPermissions::READ_WRITE)
.unwrap();
memory
}
fn data(memory: &GuestMemory) -> Vec<u8> {
let mut out = vec![0; 2 * PAGE as usize];
memory.read_bytes(DATA, &mut out).unwrap();
out
}
struct Run {
name: &'static str,
cpu: CpuState,
exit: ExitReason,
memory: GuestMemory,
/// Instructions the DBT ran on the shared semantics.
helpers: usize,
}
/// The interpreter and the DBT, each from its own copy of `cpu` and `memory`.
fn both(cpu: &CpuState, memory: &GuestMemory, budget: usize) -> [Run; 2] {
let mut interpreted = memory.clone();
let result = Interpreter::new(cpu.clone(), &mut interpreted, budget).run();
let mut translated = memory.clone();
let mut engine = DbtEngine::new(64 * 1024).unwrap();
let mut state = cpu.clone();
let native = engine.run(&mut state, &mut translated, budget);
[
Run {
name: "interpreter",
cpu: result.final_state,
exit: result.exit_reason,
memory: interpreted,
helpers: 0,
},
Run {
name: "DBT",
cpu: native.final_state,
exit: native.exit_reason,
memory: translated,
helpers: engine.metrics.interpreter_fallbacks,
},
]
}
fn flags(cf: bool, zf: bool, sf: bool, of: bool, pf: bool, af: bool) -> RFlags {
RFlags {
cf,
zf,
sf,
of,
pf,
af,
}
}
fn low(bits: u32) -> u64 {
u64::MAX >> (64 - bits)
}
#[test]
fn lock_is_accepted_only_on_xadd_and_cmpxchg_with_a_memory_destination() {
let accepted: &[&[u8]] = &[
&[0xF0, 0x0F, 0xC1, 0x0E], // lock xadd [rsi], ecx
&[0xF0, 0x0F, 0xB1, 0x0E], // lock cmpxchg [rsi], ecx
&[0x66, 0xF0, 0x0F, 0xC1, 0x0E], // lock xadd [rsi], cx, in LLVM's prefix order
&[0xF0, 0x66, 0x0F, 0xC1, 0x0E], // the same with LOCK first
&[0x65, 0xF0, 0x0F, 0xB0, 0x0E], // lock cmpxchg gs:[rsi], cl
&[0xF0, 0x48, 0x0F, 0xC1, 0x0E], // lock xadd [rsi], rcx
];
for code in accepted {
let lock = code.iter().position(|byte| *byte == 0xF0).unwrap();
let mut unlocked = code.to_vec();
unlocked.remove(lock);
let insn = decode(ENTRY, |at| {
code.get((at - ENTRY) as usize).copied().ok_or(())
})
.unwrap();
assert!(insn.lock && !is_native(&insn), "{code:02X?}");
assert_eq!(usize::from(insn.len), code.len(), "{code:02X?}");
// The accumulator matches the operand, so each exchange stores RCX.
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[RAX] = 0x2122_2324_2526_2728;
cpu.gpr[RCX] = 0x1112_1314_1516_1718;
cpu.gpr[RSI] = DATA + 0x40;
let mut memory = image(code);
memory
.write_u64(DATA + 0x40, 0x2122_2324_2526_2728)
.unwrap();
let mut plain = image(&unlocked);
plain.write_u64(DATA + 0x40, 0x2122_2324_2526_2728).unwrap();
// LOCK changes no result here: only the instruction is a byte longer.
for (locked, wanted) in both(&cpu, &memory, 1).iter().zip(both(&cpu, &plain, 1)) {
assert_eq!(locked.exit, ExitReason::StepLimitExceeded, "{code:02X?}");
assert_eq!(locked.cpu.rip, ENTRY + code.len() as u64, "{code:02X?}");
let mut shifted = wanted.cpu.clone();
shifted.rip += 1;
assert_eq!(locked.cpu, shifted, "{code:02X?} on the {}", locked.name);
assert_eq!(data(&locked.memory), data(&wanted.memory), "{code:02X?}");
assert_ne!(data(&locked.memory), data(&memory), "{code:02X?}");
}
}
let rejected: &[&[u8]] = &[
&[0xF0, 0x0F, 0xC1, 0xC8], // lock xadd eax, ecx: register destination
&[0xF0, 0x0F, 0xB1, 0xCB], // lock cmpxchg ebx, ecx: register destination
&[0xF0, 0x01, 0x0E], // lock add [rsi], ecx: outside the locked subset
&[0xF0, 0x87, 0x0E], // lock xchg [rsi], ecx: outside the locked subset
&[0xF0, 0x0F, 0xC7, 0x0E], // lock cmpxchg8b [rsi]: not implemented
&[0xF0, 0x8B, 0x06], // lock mov eax, [rsi]: never lockable
&[0xF0, 0x90], // lock nop
];
for code in rejected {
let mut padded = code.to_vec();
padded.extend([0x90; 8]);
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[RSI] = DATA;
let memory = image(&padded);
for run in both(&cpu, &memory, 1) {
assert!(
matches!(run.exit, ExitReason::IllegalInstruction(_)),
"{code:02X?} on the {}: {:?}",
run.name,
run.exit
);
assert_eq!(run.cpu, cpu, "{code:02X?}");
assert_eq!(data(&run.memory), data(&memory), "{code:02X?}");
}
}
}
#[test]
fn compare_and_exchange_takes_each_branch_at_every_width() {
// Destination [rsi] or RBX, source RCX, accumulator RAX.
let forms: &[(&[u8], u32, bool)] = &[
(&[0xF0, 0x0F, 0xB0, 0x0E], 8, true), // lock cmpxchg [rsi], cl
(&[0x66, 0xF0, 0x0F, 0xB1, 0x0E], 16, true), // lock cmpxchg [rsi], cx
(&[0xF0, 0x0F, 0xB1, 0x0E], 32, true), // lock cmpxchg [rsi], ecx
(&[0xF0, 0x48, 0x0F, 0xB1, 0x0E], 64, true), // lock cmpxchg [rsi], rcx
(&[0x0F, 0xB0, 0xCB], 8, false), // cmpxchg bl, cl
(&[0x66, 0x0F, 0xB1, 0xCB], 16, false), // cmpxchg bx, cx
(&[0x0F, 0xB1, 0xCB], 32, false), // cmpxchg ebx, ecx
(&[0x48, 0x0F, 0xB1, 0xCB], 64, false), // cmpxchg rbx, rcx
];
const ACCUMULATOR: u64 = 0x1111_2222_3333_4444;
const SOURCE: u64 = 0xAAAA_BBBB_CCCC_DDDD;
const ABOVE: u64 = 0x5555_6666_7777_8888;
for &(code, bits, in_memory) in forms {
let mask = low(bits);
for matches in [true, false] {
// The destination holds the accumulator's low bits, or differs in
// bit 0, under bits the operation must not read.
let old = (ABOVE & !mask) | ((ACCUMULATOR ^ u64::from(!matches)) & mask);
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[RAX] = ACCUMULATOR;
cpu.gpr[RCX] = SOURCE;
cpu.gpr[RBX] = old;
cpu.gpr[RSI] = DATA + 0x80;
// accumulator - destination is 0, or -1 when the destination is
// one more. Start from the opposite flags so each must be written.
let after = if matches {
flags(false, true, false, false, true, false)
} else {
flags(true, false, true, false, true, true)
};
cpu.flags = flags(
!after.cf, !after.zf, !after.sf, !after.of, !after.pf, !after.af,
);
let mut memory = image(code);
memory.write_u64(DATA + 0x80, old).unwrap();
// A match stores the source. A mismatch stores the old value back
// and loads it into the accumulator. An 8- or 16-bit register write
// keeps the bits above it, a 32-bit one clears them, and a memory
// write touches only its own bytes.
let stored = if matches { SOURCE & mask } else { old & mask };
let merged = |before: u64, value: u64| match bits {
32 => value,
_ => (before & !mask) | value,
};
let mut wanted = cpu.clone();
wanted.rip = ENTRY + code.len() as u64;
wanted.flags = after;
if !matches {
wanted.gpr[RAX] = merged(ACCUMULATOR, old & mask);
}
let wanted_memory = if in_memory {
(old & !mask) | stored
} else {
wanted.gpr[RBX] = merged(old, stored);
old
};
for run in both(&cpu, &memory, 1) {
let what = format!("{code:02X?} matches={matches} on the {}", run.name);
assert_eq!(run.exit, ExitReason::StepLimitExceeded, "{what}");
assert_eq!(run.cpu, wanted, "{what}");
assert_eq!(
run.memory.read_u64(DATA + 0x80).unwrap(),
wanted_memory,
"{what}"
);
}
}
}
}
#[test]
fn locked_operands_may_be_unaligned_and_span_two_regions() {
// No alignment is required of a locked operand (SDM Vol. 2, "LOCK"). The
// last address straddles the data and a second writable region after it.
let spanning = |code: &[u8]| {
let mut memory = image(code);
memory
.map_region(END, PAGE as usize, MemoryPermissions::READ_WRITE)
.unwrap();
memory
};
for at in [DATA + 1, DATA + 0x33, DATA + PAGE - 3, END - 8, END - 3] {
// lock xadd [rsi], rcx
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[RCX] = 0x0000_0001_0000_0003;
cpu.gpr[RSI] = at;
let mut memory = spanning(&[0xF0, 0x48, 0x0F, 0xC1, 0x0E]);
memory.write_u64(at, 0xFFFF_FFFF_FFFF_FFFE).unwrap();
for run in both(&cpu, &memory, 1) {
assert_eq!(run.exit, ExitReason::StepLimitExceeded, "{at:#x}");
assert_eq!(run.cpu.gpr[RCX], 0xFFFF_FFFF_FFFF_FFFE, "{at:#x}");
assert_eq!(
run.memory.read_u64(at).unwrap(),
0x0000_0001_0000_0001,
"{at:#x}"
);
// 0xFFFF_FFFF_FFFF_FFFE + 0x0000_0001_0000_0003 carries out of bit
// 63 and bit 3; the sum is positive, nonzero and ends in 0x01.
assert_eq!(
run.cpu.flags,
flags(true, false, false, false, false, true),
"{at:#x}"
);
}
// lock cmpxchg [rsi], rcx, with a matching accumulator
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[RAX] = 0x8877_6655_4433_2211;
cpu.gpr[RCX] = 0x0102_0304_0506_0708;
cpu.gpr[RSI] = at;
let mut memory = spanning(&[0xF0, 0x48, 0x0F, 0xB1, 0x0E]);
memory.write_u64(at, 0x8877_6655_4433_2211).unwrap();
for run in both(&cpu, &memory, 1) {
assert_eq!(run.exit, ExitReason::StepLimitExceeded, "{at:#x}");
assert_eq!(run.cpu.gpr[RAX], 0x8877_6655_4433_2211, "{at:#x}");
assert_eq!(
run.memory.read_u64(at).unwrap(),
0x0102_0304_0506_0708,
"{at:#x}"
);
}
}
}
#[test]
fn a_fault_on_any_byte_of_the_operand_changes_nothing() {
let xadd: &[u8] = &[0xF0, 0x48, 0x0F, 0xC1, 0x0E]; // lock xadd [rsi], rcx
let cmpxchg: &[u8] = &[0xF0, 0x48, 0x0F, 0xB1, 0x0E]; // lock cmpxchg [rsi], rcx
// The last three bytes of writable memory, then five bytes that are
// unmapped or read-only.
let at = END - 3;
for code in [xadd, cmpxchg] {
for read_only_tail in [false, true] {
// Accumulators that match and that do not match the operand's
// writable bytes: a failed compare needs the write access too.
for accumulator in [0x0000_0000_00CC_BBAA_u64, 7] {
let mut memory = image(code);
memory.write_bytes(at, &[0xAA, 0xBB, 0xCC]).unwrap();
if read_only_tail {
memory
.map_region(END, PAGE as usize, MemoryPermissions::READ_ONLY)
.unwrap();
}
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[RAX] = accumulator;
cpu.gpr[RCX] = 0x1122_3344_5566_7788;
cpu.gpr[RSI] = at;
cpu.flags = flags(true, false, true, false, true, false);
for run in both(&cpu, &memory, 1) {
let what = format!(
"{code:02X?} tail read-only={read_only_tail} rax={accumulator:#x} on the {}",
run.name
);
assert!(
matches!(run.exit, ExitReason::MemoryFault(_)),
"{what}: {:?}",
run.exit
);
assert_eq!(run.cpu, cpu, "{what}");
assert_eq!(data(&run.memory), data(&memory), "{what}");
}
}
}
}
}
#[test]
fn compare_and_swap_loop_retries_then_fetch_and_add_follows() {
// retry: lea rcx, [rax + 1]
// lock cmpxchg [rsi], rcx
// jne retry
// mov edx, 5
// lock xadd [rsi], rdx
// hlt
let code = [
0x48, 0x8D, 0x48, 0x01, 0xF0, 0x48, 0x0F, 0xB1, 0x0E, 0x75, 0xF5, 0xBA, 0x05, 0x00, 0x00,
0x00, 0xF0, 0x48, 0x0F, 0xC1, 0x16, 0xF4,
];
const COUNTER: u64 = DATA + 0x100;
let mut cpu = CpuState::new(ENTRY, 0);
// A stale expectation: the first exchange fails and reloads RAX, the
// second succeeds.
cpu.gpr[RAX] = 0xDEAD;
cpu.gpr[RSI] = COUNTER;
let mut memory = image(&code);
memory.write_u64(COUNTER, 41).unwrap();
for run in both(&cpu, &memory, 64) {
assert_eq!(run.exit, ExitReason::Halt, "{}", run.name);
assert_eq!(run.cpu.gpr[RAX], 41, "{}", run.name);
assert_eq!(run.cpu.gpr[RCX], 42, "{}", run.name);
// XADD returns the value before its addition.
assert_eq!(run.cpu.gpr[RDX], 42, "{}", run.name);
assert_eq!(run.memory.read_u64(COUNTER).unwrap(), 47, "{}", run.name);
assert_eq!(run.cpu.rip, ENTRY + code.len() as u64, "{}", run.name);
// Two exchanges and one addition, none lowered to ARM64 yet.
if run.name == "DBT" {
assert_eq!(run.helpers, 3);
}
}
}
+143
View File
@@ -305,6 +305,8 @@ enum Outcome {
}
fn reference(m: &mut Machine, text: &str) -> Outcome {
// LOCK changes no result on a machine that runs one instruction at a time.
let text = text.strip_prefix("lock ").unwrap_or(text);
let (name, rest) = text.split_once(' ').unwrap_or((text, ""));
let places: Vec<Place> = if rest.is_empty() || name == "lea" || name == "nop" {
Vec::new()
@@ -659,6 +661,28 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
write(m, places[1], a);
Outcome::Done(none)
}
"xadd" => {
// TEMP := SRC + DEST; SRC := DEST; DEST := TEMP.
let (a, b) = (read(m, places[0], bits), read(m, places[1], bits));
let sum = arithmetic(m, a, b, false, false, bits);
write(m, places[1], a);
write(m, places[0], sum);
Outcome::Done(none)
}
"cmpxchg" => {
// The accumulator is compared with DEST as CMP would. On a match
// DEST := SRC; otherwise accumulator := DEST and DEST := DEST.
let accumulator = read(m, rax(bits), bits);
let (destination, source) = (read(m, places[0], bits), read(m, places[1], bits));
arithmetic(m, accumulator, destination, true, false, bits);
if accumulator == destination {
write(m, places[0], source);
} else {
write(m, rax(bits), destination);
write(m, places[0], destination);
}
Outcome::Done(none)
}
"bswap" => {
let value = read(m, places[0], bits);
let bytes = bits / 8;
@@ -705,6 +729,24 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
Outcome::Done(none)
}
"nop" | "pause" => Outcome::Done(none),
"cpuid" => {
// Xenora's guest CPUID contract, restated: the vendor "Xenora guest"
// and the four features whose every instruction exists, CMOV and
// POPCNT in leaf 1, LZCNT and long mode in leaf 0x8000_0001.
let word = |text: &[u8; 4]| u32::from_le_bytes(*text);
let values = match m.gpr[RAX] as u32 {
0 => [1, word(b"Xeno"), word(b"uest"), word(b"ra g")],
1 => [0, 0, 1 << 23, 1 << 15],
0x8000_0000 => [0x8000_0001, 0, 0, 0],
0x8000_0001 => [0, 0, 1 << 5, 1 << 29],
_ => [0; 4],
};
// EAX, EBX, ECX and EDX, each zero-extended.
for (index, value) in [0, 3, 1, 2].into_iter().zip(values) {
m.gpr[index] = u64::from(value);
}
Outcome::Done(none)
}
"push" => {
m.pushed = read(m, places[0], 64) as u64;
m.gpr[4] -= 8;
@@ -1298,6 +1340,107 @@ fn division_accepts_exactly_the_representable_quotients() {
}
}
/// The bit scans and the bit test keep the destination and the flags where
/// the architecture puts them.
///
/// The expectations come from the Intel SDM Volume 2B, "BSF", "BSR" and "BT":
/// BSF writes the index of the lowest set bit of the source and BSR the index
/// of the highest set bit, and both set the zero flag when the source is
/// zero, in which case the destination is undefined and keeps its value. BT
/// sets the carry flag from the tested bit, leaves the other flags alone and
/// masks the bit index to the operand width.
///
/// The encodings are `bsf rbx, r9` (49 0F BC D9), `bsr rbx, r9` (49 0F BD
/// D9), `bt rbx, r9` (4C 0F A3 CB), `bsf ebx, r9d` (41 0F BC D9),
/// `bsr ebx, r9d` (41 0F BD D9), `bt ebx, r9d` (44 0F A3 CB), `bsf bx, r9w`
/// (66 41 0F BC D9) and `bt bx, r9w` (66 44 0F A3 CB), as produced by LLVM
/// 23.1.6 `llvm-mc -show-encoding`.
#[test]
fn bit_scans_and_bit_tests_follow_the_architecture() {
const BSF64: &[u8] = &[0x49, 0x0F, 0xBC, 0xD9]; // bsf rbx, r9
const BSR64: &[u8] = &[0x49, 0x0F, 0xBD, 0xD9]; // bsr rbx, r9
const BT64: &[u8] = &[0x4C, 0x0F, 0xA3, 0xCB]; // bt rbx, r9
const BSF32: &[u8] = &[0x41, 0x0F, 0xBC, 0xD9]; // bsf ebx, r9d
const BSR32: &[u8] = &[0x41, 0x0F, 0xBD, 0xD9]; // bsr ebx, r9d
const BT32: &[u8] = &[0x44, 0x0F, 0xA3, 0xCB]; // bt ebx, r9d
const BSF16: &[u8] = &[0x66, 0x41, 0x0F, 0xBC, 0xD9]; // bsf bx, r9w
const BT16: &[u8] = &[0x66, 0x44, 0x0F, 0xA3, 0xCB]; // bt bx, r9w
/// A machine with R9 and RBX set and every other register zero.
fn machine(source: u64, destination: u64) -> Machine {
let mut gpr = [0; 16];
gpr[3] = destination;
gpr[9] = source;
Machine {
gpr,
flags: Flags::default(),
operand: 0,
pushed: 0,
top: STACK_TOP,
}
}
// The lowest set bit of the source is the index BSF writes.
let (state, _, _) = run_both(&machine(0x0000_0000_0000_0028, 0xFFFF), BSF64, 1);
assert_eq!(state.gpr[3], 3);
assert!(!state.flags.zf);
// The highest set bit of the source is the index BSR writes.
let (state, _, _) = run_both(&machine(0x8000_0000_0000_0028, 0xFFFF), BSR64, 1);
assert_eq!(state.gpr[3], 63);
assert!(!state.flags.zf);
// A zero source sets the zero flag and leaves the destination alone.
let (state, _, _) = run_both(&machine(0, 0xFFFF_FFFF_FFFF_FFFF), BSF64, 1);
assert_eq!(state.gpr[3], 0xFFFF_FFFF_FFFF_FFFF);
assert!(state.flags.zf);
let (state, _, _) = run_both(&machine(0, 0xFFFF_FFFF_FFFF_FFFF), BSR64, 1);
assert_eq!(state.gpr[3], 0xFFFF_FFFF_FFFF_FFFF);
assert!(state.flags.zf);
// A 32-bit destination holds a 32-bit index and clears the half above it.
let (state, _, _) = run_both(&machine(0x0000_0028, 0xFFFF_FFFF_FFFF_FFFF), BSF32, 1);
assert_eq!(state.gpr[3], 3);
let (state, _, _) = run_both(&machine(0x8000_0000, 0xFFFF_FFFF_FFFF_FFFF), BSR32, 1);
assert_eq!(state.gpr[3], 31);
// A 16-bit destination keeps the bits above it.
let (state, _, _) = run_both(&machine(0x0100, 0xFFFF_FFFF_FFFF_FFFF), BSF16, 1);
assert_eq!(state.gpr[3], 0xFFFF_FFFF_FFFF_0008);
// BT reports the tested bit in the carry flag and leaves the bit string
// alone.
let (state, _, _) = run_both(&machine(1, 0b1010), BT64, 1);
assert!(state.flags.cf);
assert_eq!(state.gpr[3], 0b1010);
let (state, _, _) = run_both(&machine(0, 0b1010), BT64, 1);
assert!(!state.flags.cf);
assert_eq!(state.gpr[3], 0b1010);
// The bit index is masked to the operand width, so 64 selects bit 0 of a
// 64-bit bit string and 32 selects bit 0 of a 32-bit one.
let (state, _, _) = run_both(&machine(64, 0b1), BT64, 1);
assert!(state.flags.cf);
let (state, _, _) = run_both(&machine(32, 0b1), BT32, 1);
assert!(state.flags.cf);
let (state, _, _) = run_both(&machine(16, 0b1), BT16, 1);
assert!(state.flags.cf);
// The bit scans and the register form of the bit test are lowered to
// ARM64 instead of falling back to the shared semantics.
for code in [BSF64, BSR64, BT64, BSF32, BSR32, BT32, BSF16, BT16] {
let insn = decode(ENTRY, |address| {
code.get((address - ENTRY) as usize).copied().ok_or(())
})
.expect("decode");
assert!(is_native(&insn), "{code:02X?} is not native");
let mut engine = DbtEngine::new(64 * 1024).unwrap();
let (mut cpu, mut memory) = load(&machine(0x28, 0), code);
engine.run(&mut cpu, &mut memory, 1);
assert_eq!(engine.metrics.interpreter_fallbacks, 0, "{code:02X?}");
}
}
#[test]
fn pop_rsp_and_push_rsp_use_the_architectural_stack_pointer() {
let machine = Random(17).machine();
+45
View File
@@ -10,6 +10,9 @@
# decodable; a form counts as implemented only once its operation has semantics
# and independent tests. Forms not listed here are rejected.
#
# lock = true accepts the LOCK prefix (F0) when the ModRM operand is memory.
# Every other use of LOCK is rejected, as the architecture's #UD.
#
# prefix is a mandatory prefix: "66", "f3" or "f2". SSE forms use size x (XMM)
# and give the ModRM operand width in src: x = 16 bytes, q = 8, d = 4, w = 2.
# A 16-byte memory operand must be aligned unless unaligned = true.
@@ -48,6 +51,8 @@ movsx = { ref = "sdm MOVSX/MOVSXD" }
movsxd = { ref = "sdm MOVSX/MOVSXD" }
lea = { ref = "sdm LEA" }
xchg = { ref = "sdm XCHG" }
xadd = { writes = "cf zf sf of pf af", ref = "sdm XADD" }
cmpxchg = { writes = "cf zf sf of pf af", ref = "sdm CMPXCHG" }
bswap = { ref = "sdm BSWAP" }
cwde = { ref = "sdm CBW/CWDE/CDQE" }
cdq = { ref = "sdm CWD/CDQ/CQO" }
@@ -85,6 +90,7 @@ syscall = { terminator = true, ref = "sdm SYSCALL" }
clc = { writes = "cf", ref = "sdm CLC" }
stc = { writes = "cf", ref = "sdm STC" }
cmc = { reads = "cf", writes = "cf", ref = "sdm CMC" }
cpuid = { ref = "sdm CPUID" }
# SSE and SSE2 moves and packed integer operations. None reads or writes RFLAGS.
movaps = { ref = "sdm MOVAPS" }
@@ -562,6 +568,13 @@ opcode = 0x05
enc = "none"
size = "n"
[[form]]
op = "cpuid"
map = "0f"
opcode = 0xA2
enc = "none"
size = "n"
[[form]]
op = "movzx"
map = "0f"
@@ -674,6 +687,38 @@ enc = "rm_reg"
size = "v"
register_only = true
[[form]]
op = "cmpxchg"
map = "0f"
opcode = 0xB0
enc = "rm_reg"
size = "b"
lock = true
[[form]]
op = "cmpxchg"
map = "0f"
opcode = 0xB1
enc = "rm_reg"
size = "v"
lock = true
[[form]]
op = "xadd"
map = "0f"
opcode = 0xC0
enc = "rm_reg"
size = "b"
lock = true
[[form]]
op = "xadd"
map = "0f"
opcode = 0xC1
enc = "rm_reg"
size = "v"
lock = true
# Groups whose digits select an operation: [opcode, size, immediate, encoding].
[[group]]
map = "0f"
+81
View File
@@ -68,6 +68,8 @@ pub enum Op {
/// The other SOPC 32-bit integer compares (opcodes 1-5 and 7-11), writing
/// only SCC: LG, GT, GE, LT, LE, signed for 1-5, unsigned for 7-11.
ScalarCompare(Comparison, Source, Source),
/// SOPK operation on SGPR `SDST` (s0-s105) and the raw SIMM16.
ScalarImmediate(ScalarImmediate, u8, u16),
Branch {
target: usize,
condition: BranchCondition,
@@ -281,6 +283,23 @@ pub enum ScalarUnary {
Absolute,
}
/// SOPK operations decoded by the reference interpreter (RDNA 2 ISA guide
/// 12.2; SCC per Tables 11, 12, 13 and 14).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ScalarImmediate {
/// 0 `s_movk_i32`: D = signext(SIMM16).
Move,
/// 2 `s_cmovk_i32`: if SCC, D = signext(SIMM16); SCC unchanged.
ConditionalMove,
/// 3-14 `s_cmpk_*`: SCC = (D <relation> K), K = signext(SIMM16) for the
/// signed forms 3-8 and SIMM16 zero-extended for the unsigned 9-14.
Compare(Comparison),
/// 15 `s_addk_i32`: D = D + signext(SIMM16), SCC = signed overflow.
Add,
/// 16 `s_mulk_i32`: D = low 32 bits of D * signext(SIMM16); SCC unchanged.
Multiply,
}
/// VOP2 operations decoded by the reference interpreter.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VectorAlu {
@@ -589,6 +608,26 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
};
(op, left_length.max(right_length))
}
// SOPK (guide 13.1.2): ENCODING 0b1011 in bits 28-31, OP 23-27,
// SDST 16-22 (s0-s105 only), SIMM16 0-15. The format never takes
// a literal dword (guide 12.2), so the word is always 4 bytes.
[lo, hi, low, high @ 0xb0..=0xb8, ..]
if low & 0x7f <= 105 && matches!((high & 0xf) << 1 | low >> 7, 0 | 2..=16) =>
{
let kind = match (high & 0xf) << 1 | low >> 7 {
0 => ScalarImmediate::Move,
2 => ScalarImmediate::ConditionalMove,
// EQ, LG, GT, GE, LT, LE as VOPC relation offsets (see SOPC).
op @ 3..=14 => ScalarImmediate::Compare(Comparison {
offset: [2, 5, 4, 6, 1, 3][usize::from((op - 3) % 6)],
signed: op <= 8,
}),
15 => ScalarImmediate::Add,
_ => ScalarImmediate::Multiply,
};
let simm16 = u16::from_le_bytes([*lo, *hi]);
(Op::ScalarImmediate(kind, low & 0x7f, simm16), 4)
}
// SOP2: OP in bits 23-29, SDST in bits 16-22, SSRC1, SSRC0.
[left, right, low, high @ 0x80..=0xbf, tail @ ..]
if (*left, *right) != (255, 255)
@@ -1158,6 +1197,48 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
Op::ScalarCompare(comparison, lhs, rhs) => {
scc = Some(comparison.holds(read_scalar(lhs)?, read_scalar(rhs)?));
}
// Guide 12.2: SDST is also the second source; SIMM16 is
// sign-extended except by the unsigned compares.
Op::ScalarImmediate(kind, dst, simm16) => {
let extended = i32::from(simm16 as i16);
if let ScalarImmediate::Compare(comparison) = kind {
let constant = if comparison.signed {
extended as u32
} else {
u32::from(simm16)
};
let value = read_scalar(Source::Register(dst))?;
scc = Some(comparison.holds(value, constant));
} else {
if dst < 8 {
return Err(error(offset, "write to a reserved resource SGPR"));
}
let value = match kind {
ScalarImmediate::ConditionalMove
if !scc
.ok_or_else(|| error(offset, "move on uninitialized SCC"))? =>
{
None
}
ScalarImmediate::Add => {
let exact = i64::from(read_scalar(Source::Register(dst))? as i32)
+ i64::from(extended);
// SCC = the exact signed sum does not fit in i32.
scc = Some(i32::try_from(exact).is_err());
Some(exact as u32)
}
ScalarImmediate::Multiply => {
let exact = i64::from(read_scalar(Source::Register(dst))? as i32)
* i64::from(extended);
Some(exact.rem_euclid(1 << 32) as u32)
}
_ => Some(extended as u32),
};
if let Some(value) = value {
scalars[usize::from(dst)] = Some(value);
}
}
}
Op::Scalar(kind, dst, lhs, rhs) => {
if dst < 8 {
return Err(error(offset, "write to a reserved resource SGPR"));
+121 -26
View File
@@ -9,8 +9,8 @@ pub use graphics::{PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
pub use xenora_decoder::Architecture;
use xenora_decoder::{
DecodeError, DecodedInstruction, Instruction, ScalarSource, VectorAluOp, VectorAluVop3Op,
VectorBinary, VectorCompareOp, VectorSource,
DecodeError, DecodedInstruction, Instruction, ScalarSource, ScalarUnaryOp, VectorAluOp,
VectorAluVop3Op, VectorBinary, VectorCompareOp, VectorSource, VectorUnary,
};
/// SGPR index of `vcc_lo`.
@@ -92,6 +92,7 @@ enum Op {
Load,
Constant(u32),
Binary(Binary, Value, Value),
Unary(VectorUnary, Value),
MergeLanes {
mask: u32,
active: Value,
@@ -129,6 +130,7 @@ impl Op {
match self {
Self::Load | Self::Constant(_) | Self::ScalarBranch { .. } => Vec::new(),
Self::Binary(_, left, right) => vec![left, right],
Self::Unary(_, source) => vec![source],
Self::MergeLanes {
active, inactive, ..
} => vec![active, inactive],
@@ -149,6 +151,21 @@ impl Op {
match self {
Self::Load => format!("input[{index}]"),
Self::Constant(value) => format!("0x{value:08x}u"),
Self::Unary(op, source) => {
let src = name(source);
// AMD guide 12.8: all three scans return -1 if no bit matches.
match op {
VectorUnary::Not => format!("~{src}"),
VectorUnary::ReverseBits => format!("reverse_bits({src})"),
VectorUnary::FindHighUnsigned => {
format!("{src} == 0u ? 0xffffffffu : clz({src})")
}
VectorUnary::FindLow => format!("{src} == 0u ? 0xffffffffu : ctz({src})"),
VectorUnary::FindHighSigned => format!(
"({src} == 0u || {src} == 0xffffffffu) ? 0xffffffffu : clz({src} ^ (0u - ({src} >> 31u)))"
),
}
}
Self::Binary(operator, left, right) => {
let (left, right) = (name(left), name(right));
let (_, symbol) = operator.operator();
@@ -440,6 +457,19 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
format!("{dest} = const.u32 0x{value:08x}"),
format!("uint {dest} = {};", operation.expression(&thread, "", "")),
),
Op::Unary(operator, source) => {
let mnemonic = match operator {
VectorUnary::Not => "not.b32",
VectorUnary::ReverseBits => "brev.b32",
VectorUnary::FindHighUnsigned => "ffbh.u32",
VectorUnary::FindLow => "ffbl.b32",
VectorUnary::FindHighSigned => "ffbh.i32",
};
(
format!("{dest} = {mnemonic} {source}"),
format!("uint {dest} = {};", operation.expression(&thread, "", "")),
)
}
Op::Binary(operator, left, right) => (
format!("{dest} = {} {left}, {right}", operator.operator().0),
format!("uint {dest} = {};", operation.expression(&thread, "", "")),
@@ -726,6 +756,25 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
.flatten()
.ok_or_else(|| error("scalar source has no known value")),
};
let read_vector = |source, operations: &mut Vec<_>, facts: &mut Vec<_>| {
Ok(match source {
VectorSource::Register(register) => read(register)?,
VectorSource::Scalar(register) if usize::from(register) == VCC_LO => {
match (lane_vcc, scalars[VCC_LO]) {
(Some(mask), _) => mask,
(None, Some(bits)) => constant(operations, facts, offset, bits),
(None, None) => {
return Err(error("vector ALU reads uninitialized VCC_LO"));
}
}
}
VectorSource::Scalar(register) => {
let bits = read_scalar(ScalarSource::Register(register))?;
constant(operations, facts, offset, bits)
}
VectorSource::Immediate(bits) => constant(operations, facts, offset, bits),
})
};
// Scalar instructions and waits still execute when all lanes are inactive.
if exec == 0 {
match instruction.instruction {
@@ -733,7 +782,9 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
| Instruction::VectorAluVop3 { .. }
| Instruction::VectorAddF32 { .. }
| Instruction::VectorMulF32 { .. }
| Instruction::VectorAlu { .. } => continue,
| Instruction::VectorAlu { .. }
| Instruction::VectorUnary { .. }
| Instruction::VectorSwap { .. } => continue,
_ => {}
}
}
@@ -848,8 +899,12 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
Op::Binary(Binary::Vector(op.lowering()), left, right),
)
}
Instruction::ScalarMoveB32 { dst, src } => {
let value = read_scalar(src)?;
Instruction::ScalarUnary {
op: op @ ScalarUnaryOp::MovB32,
dst,
src,
} => {
let (value, _) = op.evaluate(read_scalar(src)?);
if dst < 8 {
return Err(error("scalar move would modify a resource descriptor"));
}
@@ -909,6 +964,37 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
scc = Some(op.test(read_scalar(src0)?, read_scalar(src1)?));
continue;
}
// docs/shaders/scalar-immediate.md.
Instruction::ScalarImmediate { op, dst, simm16 } => {
if dst < 8 {
return Err(error("scalar immediate would modify a resource descriptor"));
}
let scc_in = if op.reads_scc() {
scc.ok_or_else(|| error("SOPK SCC input reads uninitialized SCC"))?
} else {
false
};
let slot = scalars
.get_mut(usize::from(dst))
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
let old = if op.reads_dst() {
slot.ok_or_else(|| error("SOPK reads an uninitialized SGPR"))?
} else {
0
};
let (value, flag) = op.evaluate(old, simm16, scc_in);
if let Some(value) = value {
*slot = Some(value);
}
if let Some(flag) = flag {
scc = Some(flag);
}
continue;
}
Instruction::ScalarImmediateCompare { op, src, simm16 } => {
scc = Some(op.test(read_scalar(ScalarSource::Register(src))?, simm16));
continue;
}
// docs/shaders/vector-compare.md sections 3 and 5.
Instruction::VectorCompare { op, src0, src1 } => {
if exec == 0 {
@@ -1002,27 +1088,7 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
src0,
src1,
} => {
let src0 = match src0 {
VectorSource::Register(register) => read(register)?,
VectorSource::Scalar(register) if usize::from(register) == VCC_LO => {
match (lane_vcc, scalars[VCC_LO]) {
(Some(mask), _) => mask,
(None, Some(bits)) => {
constant(&mut operations, &mut facts, offset, bits)
}
(None, None) => {
return Err(error("vector ALU reads uninitialized VCC_LO"));
}
}
}
VectorSource::Scalar(register) => {
let bits = read_scalar(ScalarSource::Register(register))?;
constant(&mut operations, &mut facts, offset, bits)
}
VectorSource::Immediate(bits) => {
constant(&mut operations, &mut facts, offset, bits)
}
};
let src0 = read_vector(src0, &mut operations, &mut facts)?;
let src1 = read(src1)?;
let (left, right) = if op.swaps_sources() {
(src1, src0)
@@ -1034,6 +1100,35 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
Op::Binary(Binary::Vector(op.lowering()), left, right),
)
}
Instruction::VectorUnary { op, dst, src } => {
let source = read_vector(src, &mut operations, &mut facts)?;
(Some(dst), Op::Unary(op.lowering(), source))
}
Instruction::VectorSwap { dst, src, .. } => {
// Guide 12.8: capture both old values before updating either VGPR.
// read() also rejects v0 and registers with outstanding loads.
let old_dst = read(dst)?;
let old_src = read(src)?;
if dst != src {
registers[usize::from(dst)] = Some(merge_lanes(
&mut operations,
&mut facts,
offset,
exec,
old_src,
Some(old_dst),
)?);
registers[usize::from(src)] = Some(merge_lanes(
&mut operations,
&mut facts,
offset,
exec,
old_dst,
Some(old_src),
)?);
}
continue;
}
Instruction::VectorAddF32 { dst, src0, src1 } => (
Some(dst),
Op::Binary(Binary::FloatAdd, read(src0)?, read(src1)?),
+28
View File
@@ -308,6 +308,20 @@ fn scalar_compare_results_resolve_every_branch() {
);
}
#[test]
fn scalar_immediate_results_resolve_every_branch() {
let code = include_bytes!("../../../fixtures/rdna2/scalar-immediate.bin");
let compiled = compile(Architecture::Gfx1030, code).unwrap();
assert_eq!(
compiled.ir,
include_str!("../../../fixtures/golden/scalar-immediate.ir")
);
assert_eq!(
compiled.msl,
include_str!("../../../fixtures/golden/scalar-immediate.metal")
);
}
#[test]
fn scalar_unary_results_reach_the_kernel_as_constants() {
let code = include_bytes!("../../../fixtures/rdna2/scalar-unary.bin");
@@ -377,3 +391,17 @@ fn vector_compares_lower_to_per_thread_wave_masks_and_selects() {
include_str!("../../../fixtures/golden/vector-compare.metal")
);
}
#[test]
fn vop1_integer_fixture_lowers_unary_and_masked_swap() {
let code = include_bytes!("../../../fixtures/rdna2/vector-unary.bin");
let compiled = compile(Architecture::Gfx1030, code).unwrap();
assert_eq!(
compiled.ir,
include_str!("../../../fixtures/golden/vector-unary.ir")
);
assert_eq!(
compiled.msl,
include_str!("../../../fixtures/golden/vector-unary.metal")
);
}
+1
View File
@@ -25,6 +25,7 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
- [Semantic coverage](shaders/semantic-coverage.md) — Generated per-family counts of identified, declared, decoded, lowered and verified gfx1030 forms.
- [SOP2 scalar ALU](shaders/scalar-alu.md) — Supported scalar add, subtract and bitwise forms, their SCC rules and sources.
- [Semantic registry](shaders/semantic-registry.md) — How to add an instruction form: registry fields, validation, generation and the independence rule.
- [VOP1 vector unary and swap](shaders/vector-unary.md) — Wave32 integer bit operations, register exchange, and operand limits.
- [VOPC integer compares](shaders/vector-compare.md) — Wave32 compare forms, the VCC/EXEC contract, runtime `s_cbranch_vccz` and the Metal mapping.
- [Metal Shading Language generation](shaders/msl.md) and [independent CPU reference](shaders/reference-interpreter.md) — Translation rules and separate CPU execution models.
+4 -4
View File
@@ -1,17 +1,17 @@
<svg xmlns="http://www.w3.org/2000/svg" width="530" height="185" viewBox="0 0 530 185" role="img" aria-labelledby="title description">
<title id="title">Xenora · recorded progress</title>
<desc id="description">Decoded gfx1030 forms: 104 of 104. Accepted Metal forms · Apple M5: 18 of 104. Accepted guest milestones · X1–X4: 4 of 4</desc>
<desc id="description">Decoded gfx1030 forms: 126 of 126. Accepted Metal forms · Apple M5: 18 of 126. Accepted guest milestones · X1–X4: 4 of 4</desc>
<rect x="1" y="1" width="528" height="183" rx="10" fill="#18212a" stroke="#516171"/>
<g font-family="system-ui,sans-serif" fill="#eaf0f5">
<text x="20" y="29" font-size="13" font-weight="700">RECORDED FIXTURE PROGRESS</text>
<text x="20" y="58" font-size="13">Decoded gfx1030 forms</text>
<text x="510" y="58" font-size="13" text-anchor="end">104 / 104</text>
<text x="510" y="58" font-size="13" text-anchor="end">126 / 126</text>
<rect x="20" y="65" width="490" height="4" rx="2" fill="#3c4a58"/>
<rect x="20" y="65" width="490.00" height="4" rx="2" fill="#88c6bd"/>
<text x="20" y="96" font-size="13">Accepted Metal forms · Apple M5</text>
<text x="510" y="96" font-size="13" text-anchor="end">18 / 104</text>
<text x="510" y="96" font-size="13" text-anchor="end">18 / 126</text>
<rect x="20" y="103" width="490" height="4" rx="2" fill="#3c4a58"/>
<rect x="20" y="103" width="84.81" height="4" rx="2" fill="#88c6bd"/>
<rect x="20" y="103" width="70.00" height="4" rx="2" fill="#88c6bd"/>
<text x="20" y="134" font-size="13">Accepted guest milestones · X1–X4</text>
<text x="510" y="134" font-size="13" text-anchor="end">4 / 4</text>
<rect x="20" y="141" width="490" height="4" rx="2" fill="#3c4a58"/>

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

+37 -1
View File
@@ -45,6 +45,42 @@ XMM registers live in `CpuState::xmm`, lane 0 in the low bits, and MXCSR in `Cpu
None of it has been compared with x86 hardware.
## Locked instructions
XADD and CMPXCHG exist for 8-, 16-, 32- and 64-bit register and memory destinations. The LOCK prefix (F0) is accepted on exactly the forms the registry marks `lock = true`, and only when the destination is memory. Today those are the memory forms of XADD and CMPXCHG. LOCK anywhere else is an illegal instruction, as the Intel SDM (Vol. 2, "LOCK") specifies for a register destination or an instruction that cannot be locked. LOCK on the other instructions the SDM allows (ADD, ADC, AND, BTC, BTR, BTS, DEC, INC, NEG, NOT, OR, SBB, SUB, XOR and XCHG), CMPXCHG8B and CMPXCHG16B are not implemented and stay rejected.
These rules hold for both engines and are what a guest scheduler has to preserve:
- **Ordering.** Each engine runs one guest instruction at a time on one host thread, and an instruction either completes or changes nothing. A locked instruction is therefore indivisible and totally ordered with every other guest access, and LOCK changes no result: the locked and unlocked encodings leave identical state. A scheduler that switches guest threads only between instructions keeps this. One that runs guest threads on several host threads does not, and must first make each locked instruction atomic against every access to its operand, with x86's ordering rather than ARM64's weaker one. Nothing here provides or tests that.
- **Alignment.** A locked operand may have any alignment and may span two mapped regions.
- **Compare failure.** CMPXCHG compares the accumulator with the destination as CMP would and sets all six status flags from it. On a match it stores the source and leaves the accumulator alone. On a mismatch it loads the destination into the accumulator and stores the destination's old value back, so the destination is written either way and a mismatch on memory that cannot be written still faults. With a 32-bit register destination both stores clear the upper half of that register, following the SDM's operation text.
- **Faults.** If any byte of the operand cannot be read or written, the instruction faults before memory, registers or flags change.
- **Lowering.** The DBT runs these forms on the shared semantics. They are not lowered to ARM64 atomic instructions, which could only be judged against concurrent guest threads.
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.
## Guest CPUID
CPUID (`0F A2`) returns a fixed table that never reads the host. It describes a synthetic processor: the vendor string is `Xenora guest`, not Intel's or AMD's, and leaf 1 reports no family, model or stepping.
| Leaf (EAX) | EAX | EBX | ECX | EDX |
| --- | --- | --- | --- | --- |
| 0 | 1, the highest basic leaf | `Xeno` | `uest` | `ra g` |
| 1 | 0 | 0 | POPCNT (bit 23) | CMOV (bit 15) |
| 0x8000_0000 | 0x8000_0001, the highest extended leaf | 0 | 0 | 0 |
| 0x8000_0001 | 0 | 0 | LZCNT (bit 5) | long mode (bit 29) |
| any other | 0 | 0 | 0 | 0 |
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.
- 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.
`xenora_loader::cpu::cpuid` is the one copy of the table. A runtime service that reports processor features should read it rather than keep its own list.
`tests/cpu_features.rs` pins every leaf in both engines. For each reported feature it requires the feature's whole instruction set among the fixtures that `tests/x86_integer.rs` executes. For each feature software commonly tests that is not reported, it holds one instruction of that feature that both engines must refuse. To report a new feature: implement all of its instructions, remove its witness, add its instruction list to the reported set, then set the bit. The pairing of instructions with feature bits follows the Intel SDM; nothing was compared with a processor.
## Rejected on purpose
LOCK, F2 or F3 where it is neither PAUSE nor part of a declared form, F2 combined with F3, address-size overrides, an ignored segment override after FS or GS, 16-bit stack and branch forms, 16-bit BSWAP and MOVSXD, bit tests of memory by a register index, RCL, RCR, SHLD, SHRD, string instructions, MMX, the RCP and RSQRT approximations, SSE3 and later, VEX, atomics and fences. The DBT also refuses raw SYSCALL.
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, RCL, RCR, SHLD, SHRD, string instructions, MMX, the RCP and RSQRT approximations, SSE3 and later, VEX, CMPXCHG8B, CMPXCHG16B and fences. The DBT also refuses raw SYSCALL.
+31 -10
View File
@@ -69,16 +69,37 @@ storage, invokes its callbacks and runs the entry point. The fixture entry point
uses a Win64-aligned stack and terminates with HLT. The result includes the loaded
guest memory and the entry execution outcome.
`xenora probe --mode static` inventories ordinary PE imports without guest
execution. `missing_imports.csv` lists unresolved keys with their import address
table relative virtual addresses. The full inventory records whether each key is registered, its implementation
status, and the canonical module behind API-set aliases. Runtime-loaded modules
and services require separate analysis. The coverage matrix groups unresolved
imports by shared startup prerequisites. Static imports do not reveal call
order. The JSON report counts import slots, DLL and symbol keys, distinct
names with DLL-scoped ordinals, and canonical registered handlers separately.
The unresolved total includes explicitly tracked unsupported APIs and other
missing handlers. Existing stubs remain visible in the full inventory.
`xenora probe --mode static` inventories ordinary and delay-loaded PE imports
without guest execution. `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
status, and the canonical module behind API-set aliases. Modules and services
loaded by other means at run time require separate analysis. The coverage matrix
groups unresolved ordinary imports by shared startup prerequisites. Static
imports do not reveal call order. The JSON report counts import slots, DLL and
symbol keys, distinct names with DLL-scoped ordinals, and canonical registered
handlers separately. The unresolved total includes explicitly tracked
unsupported APIs and other missing handlers. Existing stubs remain visible in
the full inventory.
Delay-loaded imports come from the PE32+ delay-load directory, data directory
13 in Microsoft's PE format. The probe reports each one with its DLL, symbol or
ordinal, and slot in the delay import address table, after the ordinary rows.
Binding does not resolve them: the PE format leaves that to a delay-load helper
inside the image. The totals above and `missing_imports.csv` therefore cover
ordinary imports only, and the JSON report counts delayed slots and DLLs in
`delayed_imports` and `delayed_imported_dlls_count`. `xenora imports sync`
leaves delayed rows out of its backlog for the same reason.
The probe reads only descriptors that lie wholly inside the directory's
declared size, and expects that size to hold the empty descriptor that ends the
table. It reads descriptors whose `RvaBased` attribute is set, and requires each
one's DLL name, import address table and import name table to be present and to
start in section data. A table that breaks one of these rules, sets a reserved
attribute bit, is truncated, or uses the earlier virtual-address descriptor form
is reported in `delay_import_error` and in the Markdown report, together with
the entries read before it.
The synthetic process registry supports the current-process pseudo handle and
its process ID. The priority boost setter and getter record and query a guest
+22
View File
@@ -33,6 +33,22 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
| `s_sext_i32_i16` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0[15:0] sign-extended; SCC unchanged | `BE921AFF 00018000` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_abs_i32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = \|S0\| (0x80000000 stays); SCC = D != 0 | `BE933412` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cmp_eq_u32` | Normal SGPR or integer operands, with at most one source selecting a literal | `BF068708` | yes | yes | three-way passed | resolved SCC | implemented | fixture verified | fixture verified |
| `s_movk_i32` | SOPK, normal SGPR destination s8-s105 (s0-s7 hold resource descriptors and are never written); D = sext(SIMM16); SCC unchanged | `B0088000` | yes | yes | three-way passed | resolved scalar state | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cmovk_i32` | SOPK, normal SGPR destination s8-s105 (s0-s7 hold resource descriptors and are never written); if SCC then D = sext(SIMM16), SCC known during translation; SCC unchanged | `B1088000` | yes | yes | three-way passed | resolved scalar state | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cmpk_eq_i32` | SOPK; initialized normal SGPR s0-s105; SCC = S == sext(SIMM16) (signed) | `B1888000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cmpk_lg_i32` | SOPK; initialized normal SGPR s0-s105; SCC = S != sext(SIMM16) (signed) | `B2088000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cmpk_gt_i32` | SOPK; initialized normal SGPR s0-s105; SCC = S > sext(SIMM16) (signed) | `B2888000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cmpk_ge_i32` | SOPK; initialized normal SGPR s0-s105; SCC = S >= sext(SIMM16) (signed) | `B3088000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cmpk_lt_i32` | SOPK; initialized normal SGPR s0-s105; SCC = S < sext(SIMM16) (signed) | `B3888000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cmpk_le_i32` | SOPK; initialized normal SGPR s0-s105; SCC = S <= sext(SIMM16) (signed) | `B4088000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cmpk_eq_u32` | SOPK; initialized normal SGPR s0-s105; SCC = S == zext(SIMM16) (unsigned) | `B4888000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cmpk_lg_u32` | SOPK; initialized normal SGPR s0-s105; SCC = S != zext(SIMM16) (unsigned) | `B5088000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cmpk_gt_u32` | SOPK; initialized normal SGPR s0-s105; SCC = S > zext(SIMM16) (unsigned) | `B5888000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cmpk_ge_u32` | SOPK; initialized normal SGPR s0-s105; SCC = S >= zext(SIMM16) (unsigned) | `B6088000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cmpk_lt_u32` | SOPK; initialized normal SGPR s0-s105; SCC = S < zext(SIMM16) (unsigned) | `B6888000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cmpk_le_u32` | SOPK; initialized normal SGPR s0-s105; SCC = S <= zext(SIMM16) (unsigned) | `B7088000` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_addk_i32` | SOPK, normal SGPR destination s8-s105 (s0-s7 hold resource descriptors and are never written), initialized; D = D + sext(SIMM16); SCC = signed overflow | `B7888000` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_mulk_i32` | SOPK, normal SGPR destination s8-s105 (s0-s7 hold resource descriptors and are never written), initialized; D = low 32 bits of D * sext(SIMM16); SCC unchanged | `B8088000` | yes | yes | three-way passed | resolved scalar state | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cmp_eq_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 == S1 (signed) | `BF00C108` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cmp_lg_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 != S1 (signed) | `BF010908` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cmp_gt_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 > S1 (signed) | `BF020908` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
@@ -105,6 +121,12 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
| `v_ashrrev_i32_e32` | Two VGPR sources and one VGPR destination | `31FFFF01` | yes | yes | three-way passed | MSL signed right shift with a five-bit count | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cbranch_execz` | Nonnegative signed dword displacement | `BF880001` | yes | yes | three-way passed | resolved Wave32 EXEC_LO zero check | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cbranch_vccz` | Nonnegative signed dword displacement | `BF860001` | yes | yes | three-way passed | resolved Wave32 VCC_LO zero check, or a wave-uniform join select after a vector compare | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_not_b32_e32` | VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; bitwise complement | `7E046F01` | yes | yes | three-way passed | per-thread unary integer operation with a lane merge under partial EXEC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_bfrev_b32_e32` | VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; reverse bit order | `7E067101` | yes | yes | three-way passed | per-thread unary integer operation with a lane merge under partial EXEC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_ffbh_u32_e32` | VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; count leading zeros, or -1 for zero | `7E087302` | yes | yes | three-way passed | per-thread unary integer operation with a lane merge under partial EXEC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_ffbl_b32_e32` | VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; count trailing zeros, or -1 for zero | `7E0A7501` | yes | yes | three-way passed | per-thread unary integer operation with a lane merge under partial EXEC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_ffbh_i32_e32` | VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; count leading sign bits, or -1 if all bits match | `7E0C7702` | yes | yes | three-way passed | per-thread unary integer operation with a lane merge under partial EXEC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_swap_b32` | VOP1, Wave32; VGPR VDST and SRC0; exchange the old values of VDST and SRC0 | `7E02CB02` | yes | yes | three-way passed | per-thread exchange of both register values with lane merges under partial EXEC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_mul_i32_i24_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = low 32 bits of sext(S0[23:0]) * sext(S1[23:0]) | `120402C3` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_mul_hi_i32_i24_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = bits 63:32 of sext(S0[23:0]) * sext(S1[23:0]) | `14060208` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_mul_u32_u24_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = low 32 bits of S0[23:0] * S1[23:0] | `160802FF 00123456` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
+3 -2
View File
@@ -189,8 +189,9 @@ Eleven 32-bit SOP1 forms are declared in the registry (operand rule
(0xffffffff); `s_flbit_i32` returns -1 for both 0 and -1; sign extension reads
S0[7:0] or S0[15:0]; `s_abs_i32` of 0x80000000 is 0x80000000. Only NOT, BCNT0,
BCNT1 and ABS write SCC, as D != 0; the other seven leave it unchanged.
`s_mov_b32` stays hand-written, because it also accepts EXEC and VCC halves as
destinations. As for SOP2, destinations s0-s7 are refused when a fixture runs
`s_mov_b32` is the twelfth registry SOP1 form, under its own operand rule
`sop1_move`, because it also accepts EXEC and VCC halves as destinations (the
domain the hand-written decoder accepted before #215 moved it). As for SOP2, destinations s0-s7 are refused when a fixture runs
(they hold its buffer descriptors), and float inline constants are rejected.
`tests/validation/tests/sop1_unary.rs` checks 4,126 cases, with expected values
+47
View File
@@ -0,0 +1,47 @@
# SOPK scalar immediate forms
Xenora decodes and translates sixteen gfx1030 SOPK integer forms through the
semantic registry (`crates/isa/semantics/rdna2/sopk.toml`, operand rules
`sopk_sgpr` and `sopk_compare`). Each is one 32-bit word: SIMM16 in bits 0-15,
SDST in bits 16-22, OP in bits 23-27, ENCODING `0b1011` in bits 28-31
(guide 13.1.2). The word never takes a literal dword (guide 12.2), so a SIMM16
whose low byte is `0xff` is an immediate, not a literal marker.
| Form | Opcode | Operation | SCC |
| --- | ---: | --- | --- |
| `s_movk_i32` | 0 | D = signext(SIMM16) | unchanged |
| `s_cmovk_i32` | 2 | if SCC, D = signext(SIMM16); otherwise D keeps its value | read, unchanged |
| `s_cmpk_{eq,lg,gt,ge,lt,le}_i32` | 3-8 | SCC = (D relation signext(SIMM16)), signed | the relation |
| `s_cmpk_{eq,lg,gt,ge,lt,le}_u32` | 9-14 | SCC = (D relation SIMM16), SIMM16 zero-extended, unsigned | the relation |
| `s_addk_i32` | 15 | D = D + signext(SIMM16) | signed overflow of the sum |
| `s_mulk_i32` | 16 | D = low 32 bits of D * signext(SIMM16) | unchanged |
## Operands
SDST is `s0`-`s105`. `s0`-`s7` hold the resource descriptors of the fixture
ABI, so they may be read (the compares) but are never written: the translator
refuses a write there even when `s_cmovk_i32` would not take it. SDST 106-127
(`vcc`, `ttmp`, `m0`, `null`, `exec`) is rejected at decode. The other SOPK
opcodes stay unsupported, except the fixed store fence `s_waitcnt_vscnt null,
0` (`0xbbfd0000`), which keeps its own decoding.
## How it runs
SGPR values are known while translating, so a SOPK instruction folds into the
translator's scalar state exactly like the SOP2 and SOPC forms: no IR node is
emitted. `s_cmpk_*` sets SCC; `s_addk_i32` writes D and SCC; `s_mulk_i32` writes
D; `s_movk_i32` and a taken `s_cmovk_i32` write D. `s_addk_i32`, `s_mulk_i32`
and the compares read D, so an SDST nothing has written is rejected.
`s_cmovk_i32` reads SCC and is rejected when SCC is uninitialized; with SCC clear
it neither reads nor writes D, so an unwritten SDST stays unwritten.
## Verification
`tests/validation/tests/sopk.rs` derives its expected values from the guide
alone and runs 4,184 cases on both CPU interpreters and, through the translator,
on native Metal (that test is `#[ignore]`d and runs under `scripts/test-gpu.sh`),
plus 398 rejected programs. `fixtures/rdna2/scalar-immediate.s` (LLVM-assembled,
expected input ^ 0x40008275) uses all sixteen forms, recording each compare's SCC
through an `s_cbranch_scc0`; its IR and MSL are pinned under
`fixtures/golden/scalar-immediate.*`. Agreement with a spec-derived reference is
not agreement with hardware.
+9 -4
View File
@@ -24,19 +24,19 @@ acceptance remain outside the verified count. All results concern synthetic fixt
| MUBUF | 75 | 2 | 0 | 2 | 2 | 2 | 2 | 2 | 0 |
| SCRATCH | 22 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| SMEM | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| SOP1 | 65 | 12 | 11 | 12 | 12 | 12 | 1 | 1 | 11 |
| SOP1 | 65 | 12 | 12 | 12 | 12 | 12 | 1 | 1 | 11 |
| SOP2 | 51 | 33 | 33 | 33 | 33 | 33 | 0 | 0 | 12 |
| SOPC | 18 | 12 | 12 | 12 | 12 | 12 | 1 | 1 | 7 |
| SOPK | 27 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
| SOPK | 27 | 17 | 16 | 17 | 17 | 17 | 1 | 1 | 5 |
| SOPP | 36 | 6 | 0 | 6 | 6 | 6 | 4 | 4 | 0 |
| VINTRP | 3 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 |
| VOP1 | 81 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
| VOP1 | 81 | 7 | 6 | 7 | 7 | 7 | 1 | 1 | 11 |
| VOP2 | 47 | 20 | 18 | 20 | 20 | 20 | 7 | 7 | 11 |
| VOP3 | 416 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 12 |
| VOP3P | 29 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| VOP3SDST | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| VOPC | 190 | 16 | 16 | 16 | 16 | 16 | 0 | 0 | 7 |
| **Total** | 1465 | 104 | 91 | 108 | 104 | 104 | 18 | 18 | 60 |
| **Total** | 1465 | 126 | 114 | 130 | 126 | 126 | 18 | 18 | 76 |
## Unsupported operand variants
@@ -44,9 +44,14 @@ The table counts distinct variant names per family across registry operand rules
| Family | Operand rule | Unsupported variants |
| --- | --- | --- |
| SOP1 | `sop1_move` | `dst_m0`, `dst_null`, `dst_ttmp`, `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc` |
| SOP1 | `sop1_sgpr` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc`, `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc` |
| SOP2 | `sop2_sgpr` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc`, `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc`, `two_literals` |
| SOPC | `sopc_scalar` | `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc`, `two_literals` |
| SOPK | `sopk_compare` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc` |
| SOPK | `sopk_sgpr` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc` |
| VOP1 | `vop1_swap` | `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` |
| VOP1 | `vop1_vgpr` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` |
| VOP2 | `vop2_vgpr` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` |
| VOP2 | `vop2_vgpr2` | `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` |
| VOP3 | `vop3_vgpr2` | `modifiers`, `src2`, `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` |
+28 -5
View File
@@ -13,7 +13,7 @@ The registry covers the nine SOP2 forms listed in [SOP2 scalar ALU](scalar-alu.m
| File | Role |
| --- | --- |
| `crates/isa/semantics/rdna2.toml` | The registry root: schema, architecture, the snapshot hash, the cited documents and the ordered `include` list of family files. |
| `crates/isa/semantics/rdna2/<family>.toml` | One file per encoding family (`sop2.toml`, `sopc.toml`, `sop1.toml`, `vop2.toml`, `vopc.toml`, `vop3.toml`): that family's operand rules, forms and encoding variants only. Data only: every value comes from a closed vocabulary. |
| `crates/isa/semantics/rdna2/<family>.toml` | One file per encoding family (`sop2.toml`, `sopc.toml`, `sopk.toml`, `sop1.toml`, `vop2.toml`, `vopc.toml`, `vop3.toml`): that family's operand rules, forms and encoding variants only. Data only: every value comes from a closed vocabulary. |
| `crates/isa/generate_semantics.py` | Validates the registry and writes the Rust tables. Python 3.11 or newer, standard library only. |
| `crates/isa/data/rdna2.jsonl` | Pinned snapshot of the AMD machine-readable ISA XML, used to cross-check identity and operands. |
| `crates/isa/src/semantics_gen.rs` | Generated output. Never edit it by hand. |
@@ -109,7 +109,7 @@ error.
| `family` | Encoding family; must match the XML base encoding | e.g. `SOP2` |
| `opcode` | Opcode; must match the XML | non-negative integer |
| `variant` | Rust enum variant of the typed operation | CamelCase, e.g. `AddU32` |
| `operation` | The primitive the form uses | `add`, `sub`, `and`, `or`, `xor`, `andn2`, `orn2`, `nand`, `nor`, `xnor`, `lshl`, `lshr`, `ashr`, `min`, `max`, `cselect`, `bfm`, `mul`, `mul_hi`, `bfe`, `absdiff`, `lshl_add`, `mul24`, `mul_hi24` (vector only), `compare` and the SOP1 unaries |
| `operation` | The primitive the form uses | `add`, `sub`, `and`, `or`, `xor`, `andn2`, `orn2`, `nand`, `nor`, `xnor`, `lshl`, `lshr`, `ashr`, `min`, `max`, `cselect`, `bfm`, `mul`, `mul_hi`, `bfe`, `absdiff`, `lshl_add`, `mul24`, `mul_hi24` (vector only), `mov` (SOP1 and SOPK), `cmov` (SOPK only), `compare` and the SOP1 unaries |
| `signedness` | How operands are read | `unsigned`, `signed`, `bitwise` (always `bitwise` for the logical operations, `cselect` and `bfm`; never for the arithmetic ones, `add`, `sub`, `min`, `max`, `mul`, `mul_hi`, `bfe`, `absdiff` and `lshl_add`; shifts take their primitive's signedness) |
| `carry_in` | Whether the form reads SCC: carry-in, borrow-in or the select condition | `none`, `scc` (`scc` only for unsigned `add` and `sub`, and required for `cselect`) |
| `width` | Operand and result width in bits | `32` |
@@ -118,9 +118,9 @@ error.
| `source_order` | Vector forms only: `reversed` when the guide computes `op(S1, S0)` (the XML records no operand order); absent otherwise | `reversed` |
| `shift_amount` | `lshl_add` only: the fixed left shift of S0 before the add | `1` to `4`; required for `lshl_add`, rejected elsewhere |
| `shift_count_bits` | Shifts only: the low bits of the count source used as the count: S1, or S0 for a vector form with `source_order = "reversed"`. Scalar forms mask it in the generated evaluation, vector forms in their MSL template; the XML must list the count source as unsigned | `5` (log2 of `width`); required for shifts, rejected elsewhere |
| `scc` | What the form writes to SCC | `carry_out`, `borrow`, `signed_overflow`, `nonzero`, `relation` (SOPC compares only), `selected_src0` (min and max: S0 won the strict compare, so a tie gives 0), `unchanged` |
| `vcc`, `exec` | Effect on VCC and EXEC, stated rather than implied | `unchanged`; `vcc` is `lane_mask` exactly for the VOPC compares (VCC_LO bit n = EXEC[n] & test, fully written; VCC_HI unknown afterwards, see [vector-compare.md](vector-compare.md)); `exec` must be `unchanged` (no EXEC-writing contract yet) |
| `wave` | Wave sizes the form is valid in | `wave32` exactly for the VOPC compares (their one entry point is the Wave32 compute fixture ABI, vector-compare.md section 2), `any` for everything else; the decoder has no wave-size input, so no other form may claim `wave32` |
| `scc` | What the form writes to SCC | `carry_out`, `borrow`, `signed_overflow`, `nonzero`, `relation` (SOPC and SOPK compares only), `selected_src0` (min and max: S0 won the strict compare, so a tie gives 0), `unchanged` |
| `vcc`, `exec` | Implicit effect on VCC and EXEC | `unchanged`; `vcc` is `lane_mask` exactly for the VOPC compares (VCC_LO bit n = EXEC[n] & test, fully written; VCC_HI unknown afterwards, see [vector-compare.md](vector-compare.md)); `exec` must be `unchanged` (explicit destinations are covered by the operand rule) |
| `wave` | Wave sizes the form is valid in | `wave32` for VOPC compares and VOP1 integer forms in the Wave32 compute fixture ABI, `any` for other registry forms |
| `operands` | Name of an `[operand_rules]` entry for the same family | e.g. `sop2_sgpr` |
| `spec` | References `{ document, section, page }` | at least one `guide` reference with a page above 0 |
| `verify` | Evidence the form needs before it counts as verified | `reference`, `independent`, `metal`, `llvm_encoding` |
@@ -150,8 +150,18 @@ fixes the `scc` value:
| `bfe` / `unsigned` or `signed` | `nonzero` | `bfe_nonzero_u32`, `bfe_nonzero_i32` | no |
| `absdiff` / `signed` | `nonzero` | `absdiff_nonzero_i32` | no |
| `lshl_add` / `unsigned` | `carry_out` | `lshl_add_carry_u32` (with `shift_amount`) | no |
| `mov` / `signed` (SOPK only) | `unchanged` | `sext_simm16` | no |
| `cmov` / `signed` (SOPK only) | `unchanged` | `sext_simm16` | required |
| `compare` / `signed` or `unsigned` | `relation` | `eq_b32`, `ne_b32` (for both signednesses), `gt_i32`/`gt_u32`, `ge_*`, `lt_*`, `le_*` | no |
SOP1 unary forms share `ScalarUnaryOp`. The `sop1_sgpr` rule accepts
destination encodings 0–105. The `sop1_move` rule for `s_mov_b32` also accepts
106–107 (VCC halves) and 126–127 (EXEC halves) as explicit destinations.
Both rules accept source registers s0–s105, inline integers −16 through 64,
and one literal dword. The move copies the source and leaves SCC unchanged.
The destination vocabulary preserves the original decoder subset of the
RDNA 2 guide sections 5.3 and 12.3.
Vector forms (operand rules `vop2_vgpr` and `vop2_vgpr2`, kind `vector`; both
generate the one `VectorAluOp` enum, whose `operand_rule()` tells the decoder
which rule a form uses) use a separate table:
@@ -187,6 +197,19 @@ sources, no destination), a unary operation one of the unary kind (`sop1_sgpr`:
one source and an SGPR destination), and a two-source ALU operation
`sop2_sgpr`.
SOPK forms (guide 12.2) use two rules. `sopk_sgpr` (kind `immediate`, enum
`ScalarImmediateOp`) has SDST `s0`-`s105` as the destination and SIMM16 as the one
source; it takes `mov`, `cmov` (reads SCC, so `carry_in = "scc"`), `add` (`D = D +
signext(SIMM16)`, `scc = "signed_overflow"`) and `mul` (`scc = "unchanged"`), all
`signed`, and the `add` and `mul` forms read the old SDST. `sopk_compare` (kind
`immediate_compare`, enum `ScalarImmediateCompareOp`) takes `compare` with SDST as
the left operand and the SIMM16 as the right one: sign-extended for `signed`,
zero-extended for `unsigned`. A SOPK compare's opcode must be 3 (`signed`) or 9
(`unsigned`) plus the relation's index in `eq, lg, gt, ge, lt, le` (guide 13.1.2).
The XML must give SIMM16 as 16-bit `FMT_NUM_I16` (`FMT_NUM_U16` for `unsigned`).
The word never takes a literal dword. The details are in
[scalar-immediate.md](scalar-immediate.md).
Behaviour is chosen only from these declared fields, never from the mnemonic.
## What the validator checks
+38
View File
@@ -0,0 +1,38 @@
# Wave32 vector unary integer operations and swap
Xenora translates six gfx1030 VOP1 integer forms for the synthetic Wave32 compute
ABI. The AMD RDNA 2 ISA Reference Guide defines the operations in section 12.8,
the encoding in section 13.3.2, and the execution mask (EXEC) in section 3.3.
| Form | Result in each active lane |
| --- | --- |
| `v_not_b32_e32` | Complement all 32 bits. |
| `v_bfrev_b32_e32` | Reverse the order of the 32 bits. |
| `v_ffbh_u32_e32` | Count leading zeros. Return all ones if the source is zero. |
| `v_ffbl_b32_e32` | Count trailing zeros. Return all ones if the source is zero. |
| `v_ffbh_i32_e32` | Count leading bits equal to the sign bit. Return all ones if all bits match. |
| `v_swap_b32` | Exchange the old values of two vector general-purpose registers (VGPRs). A register swapped with itself keeps its value. |
The unary forms accept a VGPR, scalar register `s0`–`s105`, `vcc_lo` (the low
half of the vector condition code), inline integer `-16`–`64`, or a literal
word as SRC0. Swap requires a VGPR as SRC0 because it writes both operands.
Both operands of swap must be initialized when EXEC is nonzero. The compute
ABI reserves `v0` for indexing and requires waiting for buffer loads before
using or overwriting their destination. Inactive lanes retain their old
values. The six forms leave EXEC, VCC and the scalar condition code (SCC)
unchanged.
The compiler emits per-thread Metal Shading Language for unary operations.
For swap it captures both old values in the intermediate representation before
updating either register binding. Under partial EXEC, each register receives
its own lane merge.
The [guide-derived oracle](../../tests/validation/tests/vop1_integer.rs) checks
the 752 accepted cases' outputs against its expected values on each CPU
interpreter and, through the translator, on native Metal (Apple M5, API and
shader validation on: 752 cases in 613 programs). A CPU test checks that the
compiler accepts every case and refuses each of the 610 rejected programs at
the same instruction offset as the interpreters. The
[LLVM-assembled fixture](../../fixtures/rdna2/vector-unary.s) exercises all
six forms with a partial EXEC swap. Independent acceptance of the
translator is pending. Xbox hardware agreement is unknown.
+264
View File
@@ -279,6 +279,198 @@ recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_movk_i32"
encoding = "SOPK, normal SGPR destination s8-s105 (s0-s7 hold resource descriptors and are never written); D = sext(SIMM16); SCC unchanged"
representation = "`B0088000`"
lowering = "resolved scalar state"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_cmovk_i32"
encoding = "SOPK, normal SGPR destination s8-s105 (s0-s7 hold resource descriptors and are never written); if SCC then D = sext(SIMM16), SCC known during translation; SCC unchanged"
representation = "`B1088000`"
lowering = "resolved scalar state"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_cmpk_eq_i32"
encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S == sext(SIMM16) (signed)"
representation = "`B1888000`"
lowering = "resolved SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_cmpk_lg_i32"
encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S != sext(SIMM16) (signed)"
representation = "`B2088000`"
lowering = "resolved SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_cmpk_gt_i32"
encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S > sext(SIMM16) (signed)"
representation = "`B2888000`"
lowering = "resolved SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_cmpk_ge_i32"
encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S >= sext(SIMM16) (signed)"
representation = "`B3088000`"
lowering = "resolved SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_cmpk_lt_i32"
encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S < sext(SIMM16) (signed)"
representation = "`B3888000`"
lowering = "resolved SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_cmpk_le_i32"
encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S <= sext(SIMM16) (signed)"
representation = "`B4088000`"
lowering = "resolved SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_cmpk_eq_u32"
encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S == zext(SIMM16) (unsigned)"
representation = "`B4888000`"
lowering = "resolved SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_cmpk_lg_u32"
encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S != zext(SIMM16) (unsigned)"
representation = "`B5088000`"
lowering = "resolved SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_cmpk_gt_u32"
encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S > zext(SIMM16) (unsigned)"
representation = "`B5888000`"
lowering = "resolved SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_cmpk_ge_u32"
encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S >= zext(SIMM16) (unsigned)"
representation = "`B6088000`"
lowering = "resolved SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_cmpk_lt_u32"
encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S < zext(SIMM16) (unsigned)"
representation = "`B6888000`"
lowering = "resolved SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_cmpk_le_u32"
encoding = "SOPK; initialized normal SGPR s0-s105; SCC = S <= zext(SIMM16) (unsigned)"
representation = "`B7088000`"
lowering = "resolved SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_addk_i32"
encoding = "SOPK, normal SGPR destination s8-s105 (s0-s7 hold resource descriptors and are never written), initialized; D = D + sext(SIMM16); SCC = signed overflow"
representation = "`B7888000`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_mulk_i32"
encoding = "SOPK, normal SGPR destination s8-s105 (s0-s7 hold resource descriptors and are never written), initialized; D = low 32 bits of D * sext(SIMM16); SCC unchanged"
representation = "`B8088000`"
lowering = "resolved scalar state"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_cmp_eq_i32"
encoding = "SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 == S1 (signed)"
@@ -1142,6 +1334,78 @@ recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_not_b32_e32"
encoding = "VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; bitwise complement"
representation = "`7E046F01`"
lowering = "per-thread unary integer operation with a lane merge under partial EXEC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_bfrev_b32_e32"
encoding = "VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; reverse bit order"
representation = "`7E067101`"
lowering = "per-thread unary integer operation with a lane merge under partial EXEC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_ffbh_u32_e32"
encoding = "VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; count leading zeros, or -1 for zero"
representation = "`7E087302`"
lowering = "per-thread unary integer operation with a lane merge under partial EXEC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_ffbl_b32_e32"
encoding = "VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; count trailing zeros, or -1 for zero"
representation = "`7E0A7501`"
lowering = "per-thread unary integer operation with a lane merge under partial EXEC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_ffbh_i32_e32"
encoding = "VOP1, Wave32; VGPR VDST with VGPR, normal SGPR, vcc_lo, inline integer or literal SRC0; count leading sign bits, or -1 if all bits match"
representation = "`7E0C7702`"
lowering = "per-thread unary integer operation with a lane merge under partial EXEC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_swap_b32"
encoding = "VOP1, Wave32; VGPR VDST and SRC0; exchange the old values of VDST and SRC0"
representation = "`7E02CB02`"
lowering = "per-thread exchange of both register values with lane merges under partial EXEC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_mul_i32_i24_e32"
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = low 32 bits of sext(S0[23:0]) * sext(S1[23:0])"
+26
View File
@@ -0,0 +1,26 @@
0000: t0 = load.u32 input[index]
0018: branch.uniform 0x0020 taken=false
0024: branch.uniform 0x002c taken=true
0030: branch.uniform 0x0038 taken=false
003c: branch.uniform 0x0044 taken=true
0048: branch.uniform 0x0050 taken=false
0054: branch.uniform 0x005c taken=false
0060: branch.uniform 0x0068 taken=false
006c: branch.uniform 0x0078 taken=true
007c: branch.uniform 0x0088 taken=false
008c: branch.uniform 0x0098 taken=true
009c: branch.uniform 0x00a8 taken=false
00ac: branch.uniform 0x00b8 taken=false
00c8: branch.uniform 0x00d4 taken=false
00d8: branch.uniform 0x00e4 taken=false
00e8: branch.uniform 0x00f4 taken=false
00f8: branch.uniform 0x0104 taken=true
0118: t17 = const.u32 0x00007d75
011c: t18 = const.u32 0xc000ffff
0120: t19 = xor.b32 t18, t17
0124: t20 = const.u32 0x7fffffff
0128: t21 = xor.b32 t20, t19
012c: t22 = const.u32 0xffffff00
0130: t23 = xor.b32 t22, t21
0134: t24 = xor.b32 t0, t23
0138: store.u32 output[index], t24
+17
View File
@@ -0,0 +1,17 @@
#include <metal_stdlib>
using namespace metal;
kernel void xenora_compute(
device const uint* input [[buffer(0)]],
device uint* output [[buffer(1)]],
uint index [[thread_position_in_grid]]) {
uint t0 = input[index];
uint t17 = 0x00007d75u;
uint t18 = 0xc000ffffu;
uint t19 = t18 ^ t17;
uint t20 = 0x7fffffffu;
uint t21 = t20 ^ t19;
uint t22 = 0xffffff00u;
uint t23 = t22 ^ t21;
uint t24 = t0 ^ t23;
output[index] = t24;
}
+12
View File
@@ -0,0 +1,12 @@
0000: t0 = load.u32 input[index]
000c: t1 = not.b32 t0
0018: t2 = merge.lanes mask=0xaaaaaaaa, t1, t0
0018: t3 = merge.lanes mask=0xaaaaaaaa, t0, t1
0020: t4 = brev.b32 t2
0024: t5 = ffbh.u32 t3
0028: t6 = ffbl.b32 t2
002c: t7 = ffbh.i32 t3
0030: t8 = xor.b32 t4, t5
0034: t9 = xor.b32 t6, t8
0038: t10 = xor.b32 t7, t9
003c: store.u32 output[index], t10
+19
View File
@@ -0,0 +1,19 @@
#include <metal_stdlib>
using namespace metal;
kernel void xenora_compute(
device const uint* input [[buffer(0)]],
device uint* output [[buffer(1)]],
uint index [[thread_position_in_grid]]) {
uint t0 = input[index];
uint t1 = ~t0;
uint t2 = ((0xaaaaaaaau >> (index & 31u)) & 1u) != 0u ? t1 : t0;
uint t3 = ((0xaaaaaaaau >> (index & 31u)) & 1u) != 0u ? t0 : t1;
uint t4 = reverse_bits(t2);
uint t5 = t3 == 0u ? 0xffffffffu : clz(t3);
uint t6 = t2 == 0u ? 0xffffffffu : ctz(t2);
uint t7 = (t3 == 0u || t3 == 0xffffffffu) ? 0xffffffffu : clz(t3 ^ (0u - (t3 >> 31u)));
uint t8 = t4 ^ t5;
uint t9 = t6 ^ t8;
uint t10 = t7 ^ t9;
output[index] = t10;
}
Binary file not shown.
+125
View File
@@ -0,0 +1,125 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Generate the original PE32+ delay-load import fixture without an x86 toolchain.
The image has one ordinary import DLL and two delay-loaded DLLs, each with a
named import and one of them with an import by ordinal. It follows Microsoft's
PE format specification ("The .idata Section" and "Delay-Load Import Tables
(Image Only)"). It is for static inspection: the entry point returns at once and
nothing calls an import.
"""
import argparse
from pathlib import Path
from struct import pack_into
BASE = 0x140000000
TEXT, RDATA, DATA = 0x1000, 0x2000, 0x3000
# File offset of each section's data, after the 0x400-byte headers.
RAW = {TEXT: 0x400, RDATA: 0x600, DATA: 0xA00}
ORDINAL = 1 << 63
# Ordinary imports, in .rdata.
IMPORT_DIRECTORY = RDATA
LOOKUP, IAT = RDATA + 0x30, RDATA + 0x50
ORDINARY_DLL, ORDINARY_NAME = RDATA + 0x70, RDATA + 0x90
# Delay-load names and name tables, in .rdata before their directory so that a
# file cut inside the directory still holds everything the first entry names.
NAMES_A, NAMES_B = RDATA + 0x100, RDATA + 0x118
DELAY_DLL_A, DELAY_DLL_B = RDATA + 0x130, RDATA + 0x150
DELAY_NAME_A, DELAY_NAME_B = RDATA + 0x170, RDATA + 0x190
DELAY_DIRECTORY = RDATA + 0x200
# Delay-load address tables and module handles, in writable .data.
DELAY_IAT_A, DELAY_IAT_B = DATA, DATA + 0x20
HANDLE_A, HANDLE_B = DATA + 0x40, DATA + 0x48
# Each delay-load address slot starts out pointing at its own stub.
STUBS = (TEXT + 0x10, TEXT + 0x18, TEXT + 0x20)
def fixture():
data = bytearray(0xC00)
def offset(rva):
section = rva & ~0xFFF
return RAW[section] + rva - section
def put(rva, layout, *values):
pack_into(layout, data, offset(rva), *values)
def text(rva, value):
data[offset(rva):offset(rva) + len(value) + 1] = value + b"\0"
data[:2] = b"MZ"
pack_into("<I", data, 0x3C, 0x80)
data[0x80:0x84] = b"PE\0\0"
# AMD64, three sections, 240-byte optional header; relocations stripped,
# executable, large-address-aware.
pack_into("<HHIIIHH", data, 0x84, 0x8664, 3, 0, 0, 0, 240, 0x23)
opt = 0x98
pack_into("<H", data, opt, 0x20B)
pack_into("<III", data, opt + 4, 0x200, 0x600, 0)
pack_into("<IIQII", data, opt + 16, TEXT, TEXT, BASE, 0x1000, 0x200)
pack_into("<HHHHHH", data, opt + 40, 6, 0, 0, 0, 6, 0)
pack_into("<II", data, opt + 56, 0x4000, 0x400)
# Console subsystem; NX compatible at a fixed base.
pack_into("<HH", data, opt + 68, 3, 0x100)
pack_into("<QQQQII", data, opt + 72, 0x10000, 0x1000, 0x10000, 0x1000, 0, 16)
# Import table, import address table and delay import descriptor.
for index, rva, size in (
(1, IMPORT_DIRECTORY, 40),
(12, IAT, 24),
(13, DELAY_DIRECTORY, 96),
):
pack_into("<II", data, opt + 112 + index * 8, rva, size)
sections = (
(b".text", TEXT, 0x200, 0x60000020),
(b".rdata", RDATA, 0x400, 0x40000040),
(b".data", DATA, 0x200, 0xC0000040),
)
for index, (name, rva, size, characteristics) in enumerate(sections):
pack_into(
"<8sIIIIIIHHI", data, opt + 240 + 40 * index, name, size, rva,
size, offset(rva), 0, 0, 0, 0, characteristics,
)
# Entry returns. The stubs are INT3 because the fixture is never run.
data[offset(TEXT)] = 0xC3
for stub in STUBS:
data[offset(stub)] = 0xCC
# One ordinary DLL: a named import and ordinal 3.
put(IMPORT_DIRECTORY, "<IIIII", LOOKUP, 0, 0, ORDINARY_DLL, IAT)
for table in (LOOKUP, IAT):
put(table, "<QQQ", ORDINARY_NAME, ORDINAL | 3, 0)
text(ORDINARY_DLL, b"fixture-ordinary.dll")
text(ORDINARY_NAME + 2, b"OrdinaryByName")
# Two delay-loaded DLLs. Attributes bit 0 marks the fields as RVAs.
put(DELAY_DIRECTORY, "<IIIIIIII",
1, DELAY_DLL_A, HANDLE_A, DELAY_IAT_A, NAMES_A, 0, 0, 0)
put(DELAY_DIRECTORY + 32, "<IIIIIIII",
1, DELAY_DLL_B, HANDLE_B, DELAY_IAT_B, NAMES_B, 0, 0, 0)
put(NAMES_A, "<QQQ", DELAY_NAME_A, ORDINAL | 7, 0)
put(NAMES_B, "<QQ", DELAY_NAME_B, 0)
text(DELAY_DLL_A, b"fixture-delay-a.dll")
text(DELAY_DLL_B, b"fixture-delay-b.dll")
text(DELAY_NAME_A + 2, b"DelayedAlpha")
text(DELAY_NAME_B + 2, b"DelayedBeta")
put(DELAY_IAT_A, "<QQQ", BASE + STUBS[0], BASE + STUBS[1], 0)
put(DELAY_IAT_B, "<QQ", BASE + STUBS[2], 0)
return data
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true")
args = parser.parse_args()
path = Path(__file__).with_suffix(".exe")
if args.check:
if path.read_bytes() != fixture():
parser.exit(1, f"fixture bytes differ from generator: {path}\n")
else:
path.write_bytes(fixture())
Binary file not shown.
+94
View File
@@ -0,0 +1,94 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original SOPK vectors: the sixteen 16-bit-immediate integer forms. s8 =
// 0xffff8000 (s_movk_i32 sign-extends 0x8000), so the twelve s_cmpk compares
// split signed (sign-extended SIMM16) from unsigned (zero-extended); an
// s_cbranch_scc0 skips setting that compare's bit in s20. s_addk_i32 sets SCC
// on signed overflow, s_mulk_i32 leaves SCC alone, and s_cmovk_i32 moves only
// while SCC is set. Bits worked out by hand below.
// Expected: input ^ 0x40008275 (s20 ^ s9 ^ s10 ^ s11).
.text
buffer_load_dword v1, v0, s[0:3], 0 idxen
s_waitcnt vmcnt(0)
s_movk_i32 s8, 0x8000 // s8 = 0xffff8000
s_mov_b32 s20, 0
s_cmpk_eq_i32 s8, 0x8000 // SCC = 1 (-32768 == -32768)
s_cbranch_scc0 .Lskip0
s_or_b32 s20, s20, 0x1
.Lskip0:
s_cmpk_eq_u32 s8, 0x8000 // 0xffff8000 == 0x00008000: SCC = 0
s_cbranch_scc0 .Lskip1
s_or_b32 s20, s20, 0x2
.Lskip1:
s_cmpk_lg_i32 s8, 0x7fff // -32768 != 32767: SCC = 1
s_cbranch_scc0 .Lskip2
s_or_b32 s20, s20, 0x4
.Lskip2:
s_cmpk_gt_i32 s8, 0xffff // -32768 > -1 (0xffff sign-extends): SCC = 0
s_cbranch_scc0 .Lskip3
s_or_b32 s20, s20, 0x8
.Lskip3:
s_cmpk_gt_u32 s8, 0xffff // 0xffff8000 > 0x0000ffff (zero-extends): SCC = 1
s_cbranch_scc0 .Lskip4
s_or_b32 s20, s20, 0x10
.Lskip4:
s_cmpk_ge_i32 s8, 0x8000 // -32768 >= -32768: SCC = 1
s_cbranch_scc0 .Lskip5
s_or_b32 s20, s20, 0x20
.Lskip5:
s_cmpk_lt_i32 s8, 0x1 // -32768 < 1: SCC = 1
s_cbranch_scc0 .Lskip6
s_or_b32 s20, s20, 0x40
.Lskip6:
s_cmpk_lt_u32 s8, 0x1 // 0xffff8000 < 1: SCC = 0
s_cbranch_scc0 .Lskip7
s_or_b32 s20, s20, 0x80
.Lskip7:
s_cmpk_le_i32 s8, 0x8000 // -32768 <= -32768: SCC = 1
s_cbranch_scc0 .Lskip8
s_or_b32 s20, s20, 0x100
.Lskip8:
s_cmpk_le_u32 s8, 0x8000 // 0xffff8000 <= 0x8000: SCC = 0
s_cbranch_scc0 .Lskip9
s_or_b32 s20, s20, 0x200
.Lskip9:
s_cmpk_ge_u32 s8, 0x8000 // 0xffff8000 >= 0x8000: SCC = 1
s_cbranch_scc0 .Lskip10
s_or_b32 s20, s20, 0x400
.Lskip10:
s_cmpk_lg_u32 s8, 0x8000 // 0xffff8000 != 0x8000: SCC = 1
s_cbranch_scc0 .Lskip11
s_or_b32 s20, s20, 0x800
.Lskip11:
s_movk_i32 s9, 0x7fff // s9 = 32767
s_mov_b32 s10, 0x7fffffff
s_addk_i32 s10, 1 // 0x7fffffff + 1 overflows: s10 = 0x80000000, SCC = 1
s_cbranch_scc0 .Lskip12
s_or_b32 s20, s20, 0x1000
.Lskip12:
s_mulk_i32 s9, 0x8000 // 32767 * -32768: s9 = 0xc0008000, SCC stays 1
s_cbranch_scc0 .Lskip13
s_or_b32 s20, s20, 0x2000
.Lskip13:
s_addk_i32 s10, 0xffff // 0x80000000 + -1 overflows: s10 = 0x7fffffff, SCC = 1
s_cbranch_scc0 .Lskip14
s_or_b32 s20, s20, 0x4000
.Lskip14:
s_addk_i32 s9, 0x7fff // 0xc0008000 + 32767 = 0xc000ffff, no overflow: SCC = 0
s_cbranch_scc0 .Lskip15
s_or_b32 s20, s20, 0x8000
.Lskip15:
s_mov_b32 s11, 0x1111
s_cmovk_i32 s11, 0xff00 // SCC = 0: s11 stays 0x1111
s_cmpk_eq_u32 s11, 0x1111 // SCC = 1
s_cmovk_i32 s11, 0xff00 // SCC = 1: s11 = 0xffffff00
v_mov_b32_e32 v2, s20 // s20 = 0x00007d75
v_mov_b32_e32 v3, s9 // s9 = 0xc000ffff
v_xor_b32_e32 v2, v3, v2
v_mov_b32_e32 v3, s10 // s10 = 0x7fffffff
v_xor_b32_e32 v2, v3, v2
v_mov_b32_e32 v3, s11 // s11 = 0xffffff00
v_xor_b32_e32 v2, v3, v2
v_xor_b32_e32 v2, v1, v2
buffer_store_dword v2, v0, s[4:7], 0 idxen
s_waitcnt_vscnt null, 0
s_endpgm
Binary file not shown.
+21
View File
@@ -0,0 +1,21 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Wave32 VOP1 integer forms (AMD RDNA 2 ISA guide 12.8).
// Exchange the input and its complement in odd lanes, then use both values
// and all three bit scans to form the output.
.text
buffer_load_dword v1, v0, s[0:3], 0 idxen
s_waitcnt vmcnt(0)
v_not_b32_e32 v2, v1
s_mov_b32 exec_lo, 0xaaaaaaaa
v_swap_b32 v1, v2
s_mov_b32 exec_lo, -1
v_bfrev_b32_e32 v3, v1
v_ffbh_u32_e32 v4, v2
v_ffbl_b32_e32 v5, v1
v_ffbh_i32_e32 v6, v2
v_xor_b32_e32 v7, v3, v4
v_xor_b32_e32 v7, v5, v7
v_xor_b32_e32 v7, v6, v7
buffer_store_dword v7, v0, s[4:7], 0 idxen
s_waitcnt_vscnt null, 0
s_endpgm
+1 -1
View File
@@ -12,7 +12,7 @@ case "${1:-}" in
esac
for name in add bitwise-branch float-exact or shifts ashr \
x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu vector-compare scalar-logic scalar-compare scalar-unary scalar-arith vector-integer vector-compare-ft; do
x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu vector-compare scalar-logic scalar-compare scalar-unary scalar-arith scalar-immediate vector-integer vector-compare-ft vector-unary; do
"$llvm_bin/llvm-mc" -triple=amdgcn-amd-amdhsa -mcpu=gfx1030 -mattr=+wavefrontsize32 \
-filetype=obj "fixtures/rdna2/$name.s" -o "$scratch/$name.o"
"$llvm_bin/llvm-objcopy" -O binary --only-section=.text "$scratch/$name.o" "$scratch/$name.bin"
+1 -2
View File
@@ -56,5 +56,4 @@ cargo test --locked -p xenora-semantic-review --no-run
# Oracles whose translator side has not landed are skipped by name until it does
# (#215: the PR that translates the forms removes its skip).
timeout 120s cargo test --locked -p xenora-semantic-review -- --ignored --nocapture --test-threads=1 \
--skip vopc_wide_match_the_guide_on_native_metal \
--skip vop1_integer_forms_match_the_guide_on_native_metal
--skip vopc_wide_match_the_guide_on_native_metal
@@ -1429,5 +1429,71 @@ class CommandLine(unittest.TestCase):
self.assertEqual(result.stdout.strip(), f"registry valid: {len(gen.load_registry()['form'])} forms")
class SopkForms(unittest.TestCase):
"""SOPK immediate forms, checked against the real registry and XML snapshot."""
@classmethod
def setUpClass(cls):
cls.snapshot = gen.load_snapshot()
def registry(self):
return gen.load_registry()
def rejects(self, reg, fragment):
errors = gen.validate(reg, self.snapshot)
self.assertTrue(
any(fragment in error for error in errors),
f"expected an error containing {fragment!r}, got {errors}",
)
def test_the_registry_declares_the_sixteen_sopk_forms(self):
names = {item["name"] for item in self.registry()["form"] if item["family"] == "SOPK"}
self.assertEqual(len(names), 16)
self.assertTrue({"S_MOVK_I32", "S_CMOVK_I32", "S_ADDK_I32", "S_MULK_I32"} <= names)
def test_rejects_a_compare_with_the_wrong_sopk_opcode(self):
reg = self.registry()
form(reg, "S_CMPK_GT_U32")["opcode"] = 10
self.rejects(reg, "S_CMPK_GT_U32: relation gt/unsigned has SOPK opcode 11")
def test_rejects_an_unsigned_compare_declared_signed(self):
reg = self.registry()
form(reg, "S_CMPK_GT_U32")["signedness"] = "signed"
self.rejects(reg, "SIMM16 is 16 bits FMT_NUM_U16")
def test_rejects_addk_without_the_overflow_flag(self):
reg = self.registry()
form(reg, "S_ADDK_I32")["scc"] = "unchanged"
self.rejects(reg, "S_ADDK_I32: scc unchanged contradicts add/signed")
def test_rejects_cmovk_that_does_not_read_scc(self):
reg = self.registry()
form(reg, "S_CMOVK_I32")["carry_in"] = "none"
self.rejects(reg, "S_CMOVK_I32: carry_in none contradicts the XML SCC input")
def test_rejects_a_conditional_move_that_does_not_read_scc(self):
# S_MOVK_I32 has no SCC input, so as a cmov it would see SCC = 0 and
# never write D.
reg = self.registry()
form(reg, "S_MOVK_I32")["operation"] = "cmov"
self.rejects(reg, "S_MOVK_I32: operation cmov reads SCC (requires carry_in scc)")
def test_rejects_a_two_source_operation_on_a_sopk_rule(self):
reg = self.registry()
form(reg, "S_MULK_I32")["operation"] = "and"
form(reg, "S_MULK_I32")["signedness"] = "bitwise"
self.rejects(reg, "S_MULK_I32: no primitive implements and/bitwise")
def test_rejects_a_move_on_the_compare_rule(self):
reg = self.registry()
form(reg, "S_MOVK_I32")["operands"] = "sopk_compare"
self.rejects(reg, "S_MOVK_I32: operation mov does not fit rule sopk_compare")
def test_generated_compare_extends_signed_and_unsigned_immediates_differently(self):
text = gen.render(self.registry(), self.snapshot)
self.assertIn("Self::CmpkGtI32 => primitive::gt_i32(dst, primitive::sext_simm16(simm16)),", text)
self.assertIn("Self::CmpkGtU32 => primitive::gt_u32(dst, simm16 as u32),", text)
if __name__ == "__main__":
unittest.main()
+73
View File
@@ -69,6 +69,8 @@ enum Insn {
SAlu(u32, u8, Src, Src),
/// SOPC opcode 0-11: `s_cmp_{eq,lg,gt,ge,lt,le}_i32` then `_u32`.
SCmp(u32, Src, Src),
/// SOPK opcode 0 or 2-16 on SGPR `SDST` (s0-s105) with the raw SIMM16.
SImm(u32, u8, u16),
BranchScc0(usize),
BranchMaskZero {
target: usize,
@@ -263,6 +265,9 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result<Vec<u32>, String>
None
})
}),
Insn::SImm(opcode, dst, simm16) => {
scalar_immediate(&mut sgpr, &mut scc, (opcode, dst, simm16), offset).map(|()| None)
}
Insn::SAlu(opcode, dst, a, b) => {
scalar_alu(&mut sgpr, &mut scc, (opcode, dst, a, b), offset).map(|()| None)
}
@@ -320,6 +325,65 @@ fn run_wave(program: &[(usize, Insn)], wave: &[u32]) -> Result<Vec<u32>, String>
Err(first_error(&lanes).unwrap_or_else(|| "stream ended without s_endpgm".to_string()))
}
/// One SOPK instruction, per the operation text of guide 12.2. SDST names
/// the destination and, for every form but the two moves, the first source.
fn scalar_immediate(
sgpr: &mut [Option<u32>; 128],
scc: &mut Option<bool>,
(opcode, dst, simm16): (u32, u8, u16),
offset: usize,
) -> Result<(), String> {
let d = |sgpr: &[Option<u32>; 128]| {
sgpr[dst as usize].ok_or_else(|| format!("{offset:#x}: uninitialized s{dst}"))
};
// signext(SIMM16[15:0]): copy bit 15 into bits 16-31.
let sext = u32::from(simm16) | if simm16 >> 15 == 1 { 0xffff_0000 } else { 0 };
// The unsigned compares use SIMM16[15:0] as is, zero-extended.
let zext = u32::from(simm16);
if (3..=14).contains(&opcode) {
let s0 = d(sgpr)?;
let (a, k) = (s0 as i32, sext as i32);
*scc = Some(match opcode {
3 => a == k,
4 => a != k,
5 => a > k,
6 => a >= k,
7 => a < k,
8 => a <= k,
9 => s0 == zext,
10 => s0 != zext,
11 => s0 > zext,
12 => s0 >= zext,
13 => s0 < zext,
_ => s0 <= zext,
});
return Ok(());
}
if dst < 8 {
return Err(format!("{offset:#x}: write to a resource SGPR"));
}
let value = match opcode {
0 => sext,
2 => {
if !scc.ok_or_else(|| format!("{offset:#x}: uninitialized SCC"))? {
return Ok(());
}
sext
}
15 => {
let tmp = d(sgpr)?;
let sum = tmp.wrapping_add(sext);
// tmp[31] == SIMM16[15] && tmp[31] != D[31].
*scc = Some(tmp >> 31 == u32::from(simm16 >> 15) && tmp >> 31 != sum >> 31);
sum
}
// 16: the low 32 bits of the product, the same for both signednesses.
_ => d(sgpr)?.wrapping_mul(sext),
};
sgpr[dst as usize] = Some(value);
Ok(())
}
fn scalar_alu(
sgpr: &mut [Option<u32>; 128],
scc: &mut Option<bool>,
@@ -1220,6 +1284,15 @@ fn decode_one(code: &[u8], offset: usize) -> Result<(Insn, usize), String> {
let (src, len) = scalar_source(code, offset, first as u8)?;
return Ok((Insn::SMov(dst, src), len));
}
// SOPK: ENCODING 0b1011 in bits 28-31, OP 23-27, SDST 16-22, SIMM16 0-15
// (guide 13.1.2). Guide 12.2: no literal dword may follow.
if first >> 28 == 0b1011 && matches!((first >> 23) & 0x1f, 0 | 2..=16) {
let dst = ((first >> 16) & 0x7f) as u8;
if dst > 105 {
return Err(fail("unsupported SOPK register"));
}
return Ok((Insn::SImm((first >> 23) & 0x1f, dst, first as u16), 4));
}
// SOP2: ENCODING 0b10 in bits 30-31, OP in bits 23-29, SDST in 16-22.
if first >> 30 == 0b10
&& matches!(
+16
View File
@@ -774,6 +774,10 @@ mod review {
const SCALAR_COMPARE_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/scalar-compare.bin");
// Hand-derived in fixtures/rdna2/scalar-compare.s from the guide's 12.4 pseudocode.
const SCALAR_COMPARE_KEY: u32 = 0x0000_0d5b;
const SCALAR_IMMEDIATE_FIXTURE: &[u8] =
include_bytes!("../../fixtures/rdna2/scalar-immediate.bin");
// Hand-derived in fixtures/rdna2/scalar-immediate.s from the guide's 12.2 pseudocode.
const SCALAR_IMMEDIATE_KEY: u32 = 0x4000_8275;
const SCALAR_UNARY_FIXTURE: &[u8] = include_bytes!("../../fixtures/rdna2/scalar-unary.bin");
// Hand-derived in fixtures/rdna2/scalar-unary.s from the guide's 12.3 pseudocode.
const SCALAR_UNARY_KEY: u32 = 0x0f00_80f5;
@@ -964,6 +968,18 @@ mod review {
assert!(compiled.disassembly.contains("s_cmp_le_u32 s9, 64"));
}
#[test]
fn scalar_immediate_fixture_records_every_registry_sopk_form() {
let input = [0, 1, u32::MAX, SCALAR_IMMEDIATE_KEY, 0x1234_5678];
let expected: Vec<_> = input
.iter()
.map(|word| word ^ SCALAR_IMMEDIATE_KEY)
.collect();
verify(SCALAR_IMMEDIATE_FIXTURE, &input, Some(&expected));
let compiled = compile(Architecture::Gfx1030, SCALAR_IMMEDIATE_FIXTURE).unwrap();
assert!(compiled.disassembly.contains("s_cmpk_le_u32 s8, 0x8000"));
}
#[test]
fn scalar_unary_fixture_chains_registry_unary_forms() {
let input = [0, 1, u32::MAX, SCALAR_UNARY_KEY, 0x1234_5678];
+493
View File
@@ -0,0 +1,493 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Independent expected values for the sixteen SOPK integer forms of #215:
//! `s_movk_i32`, `s_cmovk_i32`, `s_cmpk_{eq,lg,gt,ge,lt,le}_{i32,u32}`,
//! `s_addk_i32` and `s_mulk_i32`.
//!
//! The expectations are written below from the public AMD "RDNA 2" Instruction
//! Set Architecture Reference Guide only: section 12.2 "SOPK Instructions" for
//! each form's operation (and that no literal dword may follow), section
//! 13.1.2 for the SOPK word and its SDST range, and Tables 11-14 of sections
//! 5.4-5.7 for which forms set SCC. Nothing here comes from the ISA crate, the
//! semantic registry, the decoder or the shader compiler. Every case runs on
//! the reference interpreter `xenora_ref` and on the second interpreter
//! `independent_ref`; the ignored test also runs the translated MSL on native
//! Metal.
//!
//! Supported subset: SDST s0-s105 (s0-s7 are readable but, as resource
//! SGPRs, never written). Refused: SDST 106-127 (VCC, TTMP, M0, NULL, EXEC)
//! and every other SOPK opcode (`s_version`, `s_getreg`, `s_setreg*`,
//! `s_call_b64`, `s_waitcnt_*` other than the fixed `s_waitcnt_vscnt null, 0`
//! store fence, and the subvector loops).
#[path = "operand_domains/harness.rs"]
#[allow(dead_code)]
mod harness;
#[path = "../independent_ref.rs"]
mod independent_ref;
use std::collections::BTreeMap;
use harness::{Case, words};
use xenora_shader::{Architecture, compile};
/// The sixteen forms with their ENC_SOPK opcodes (guide 13.1.2, Table 66).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Form {
MovK = 0,
CmovK = 2,
CmpEqI32 = 3,
CmpLgI32 = 4,
CmpGtI32 = 5,
CmpGeI32 = 6,
CmpLtI32 = 7,
CmpLeI32 = 8,
CmpEqU32 = 9,
CmpLgU32 = 10,
CmpGtU32 = 11,
CmpGeU32 = 12,
CmpLtU32 = 13,
CmpLeU32 = 14,
AddK = 15,
MulK = 16,
}
const FORMS: [(Form, &str); 16] = [
(Form::MovK, "s_movk_i32"),
(Form::CmovK, "s_cmovk_i32"),
(Form::CmpEqI32, "s_cmpk_eq_i32"),
(Form::CmpLgI32, "s_cmpk_lg_i32"),
(Form::CmpGtI32, "s_cmpk_gt_i32"),
(Form::CmpGeI32, "s_cmpk_ge_i32"),
(Form::CmpLtI32, "s_cmpk_lt_i32"),
(Form::CmpLeI32, "s_cmpk_le_i32"),
(Form::CmpEqU32, "s_cmpk_eq_u32"),
(Form::CmpLgU32, "s_cmpk_lg_u32"),
(Form::CmpGtU32, "s_cmpk_gt_u32"),
(Form::CmpGeU32, "s_cmpk_ge_u32"),
(Form::CmpLtU32, "s_cmpk_lt_u32"),
(Form::CmpLeU32, "s_cmpk_le_u32"),
(Form::AddK, "s_addk_i32"),
(Form::MulK, "s_mulk_i32"),
];
fn is_compare(form: Form) -> bool {
(Form::CmpEqI32 as u32..=Form::CmpLeU32 as u32).contains(&(form as u32))
}
/// signext(SIMM16[15:0]) as a 32-bit word.
fn sext(simm16: u16) -> u32 {
i32::from(simm16 as i16) as u32
}
/// The guide's (D after, SCC after) for `form` with D = `d` before, SCC =
/// `scc` before and the immediate `k`.
fn expect(form: Form, d: u32, scc: bool, k: u16) -> (u32, bool) {
let (di, ki, ku) = (d as i32, sext(k) as i32, u32::from(k));
match form {
// 0 S_MOVK_I32: D.i32 = signext(SIMM16[15:0]); Table 14: no SCC.
Form::MovK => (sext(k), scc),
// 2 S_CMOVK_I32: if (SCC) D.i32 = signext(SIMM16[15:0]); Table 12: no SCC.
Form::CmovK => (if scc { sext(k) } else { d }, scc),
// 3-8: SCC = (S0.i32 <cond> signext(SIMM16[15:0])), S0 = D.
Form::CmpEqI32 => (d, di == ki),
Form::CmpLgI32 => (d, di != ki),
Form::CmpGtI32 => (d, di > ki),
Form::CmpGeI32 => (d, di >= ki),
Form::CmpLtI32 => (d, di < ki),
Form::CmpLeI32 => (d, di <= ki),
// 9-14: SCC = (S0.u32 <cond> SIMM16[15:0]), zero-extended.
Form::CmpEqU32 => (d, d == ku),
Form::CmpLgU32 => (d, d != ku),
Form::CmpGtU32 => (d, d > ku),
Form::CmpGeU32 => (d, d >= ku),
Form::CmpLtU32 => (d, d < ku),
Form::CmpLeU32 => (d, d <= ku),
// 15 S_ADDK_I32: D.i32 = D.i32 + signext(SIMM16), SCC = signed overflow.
Form::AddK => match di.checked_add(ki) {
Some(sum) => (sum as u32, false),
None => (di.wrapping_add(ki) as u32, true),
},
// 16 S_MULK_I32: D.i32 = D.i32 * signext(SIMM16) (low 32 bits); Table 11: no SCC.
Form::MulK => ((i64::from(di) * i64::from(ki)) as u32, scc),
}
}
/// SIMM16 values: zero, one, both sides of bit 15, all ones, an all-ones low
/// byte (selector 255 as a register field would mean a literal) and two
/// mixed patterns.
const IMMEDIATES: [u16; 10] = [
0, 1, 0x7fff, 0x8000, 0x8001, 0xfffe, 0xffff, 0x00ff, 0x1234, 0xedcb,
];
/// Signed and unsigned boundaries, and the words the sign- and zero-extended
/// immediates produce.
const VALUES: [u32; 15] = [
0,
1,
0x7fff_fffe,
0x7fff_ffff,
0x8000_0000,
0x8000_0001,
0xffff_fffe,
0xffff_ffff,
0x7fff,
0x8000,
0xffff,
0x1_0000,
0xffff_8000,
0xffff_7fff,
0x8001,
];
/// The value s10 holds throughout.
const MARKER: u32 = 0x0f0f_1234;
const INPUT: [u32; 2] = [0, u32::MAX];
const COUNTS: [(&str, usize); 9] = [
("sopk movk", 10 * 2),
("sopk cmovk", 10 * 2 * 2),
("sopk cmpk", 12 * 15 * 10 * 2),
("sopk addk", 15 * 10),
("sopk mulk", 15 * 10 * 2),
("sopk no literal", 16 * 2),
("sopk s105", 16),
("sopk cmovk unwritten sdst", 10),
("sopk no other write", 16),
];
/// Per form: SDST 106-127; per writing form: SDST s0-s7; per reading form: an
/// uninitialized SDST.
const REJECTIONS: usize = 16 * 22 + 4 * 8 + 14;
/// ENCODING 0b1011 in bits 28-31, OP 23-27, SDST 16-22, SIMM16 0-15 (guide
/// 13.1.2).
fn sopk(op: u32, sdst: u32, simm16: u16) -> u32 {
0xb000_0000 | op << 23 | sdst << 16 | u32::from(simm16)
}
/// The program around `alu`: load v1, `s_mov_b32` each `init` pair and
/// s10 = MARKER, set SCC to `scc` with `s_and_b32 s12, x, x` (x = 1 or 0),
/// run `alu`, then v2 = s<result>, `s_cbranch_scc0` over
/// `v_xor_b32 v2, v1, v2`, and store v2. With the lane input [0, !0] the
/// output is [R, R] when SCC is clear and [R, !R] when it is set.
fn program(init: &[(u32, u32)], scc: bool, alu: &[u32], result: u32) -> Vec<u8> {
let mut code = vec![0xe030_2000, 0x8000_0100, 0xbf8c_3f70];
for &(reg, value) in init.iter().chain(&[(10, MARKER)]) {
code.extend([0xbe80_03ff | reg << 16, value]);
}
let x = if scc { 129 } else { 128 };
code.push(0x8000_0000 | 14 << 23 | 12 << 16 | x << 8 | x);
code.extend(alu);
code.extend([0x7e04_0200 | result, 0xbf84_0001, 0x3a04_0501]);
code.extend([0xe070_2000, 0x8001_0200, 0xbbfd_0000, 0xbf81_0000]);
words(&code)
}
fn case(
name: &'static str,
family: &'static str,
label: String,
code: Vec<u8>,
out: (u32, bool),
) -> Case {
let (r, scc) = out;
Case {
form: name,
family,
label: format!("{name} {label}"),
code,
input: INPUT.to_vec(),
expected: vec![r, if scc { !r } else { r }],
}
}
/// One form on s8 = `d` with SCC = `scc` before; the result is s8.
fn single(form: Form, name: &'static str, family: &'static str, d: u32, scc: bool, k: u16) -> Case {
let code = program(&[(8, d)], scc, &[sopk(form as u32, 8, k)], 8);
let label = format!("s8 {d:#x}, simm16 {k:#06x}, scc before {scc}");
case(name, family, label, code, expect(form, d, scc, k))
}
fn cases() -> Vec<Case> {
let mut cases = Vec::new();
for (form, name) in FORMS {
let op = form as u32;
for k in IMMEDIATES {
match form {
Form::MovK => {
for scc in [false, true] {
cases.push(single(form, name, "sopk movk", 0x5a5a_5a5a, scc, k));
}
}
Form::CmovK => {
for d in [0x5a5a_5a5a, sext(k)] {
for scc in [false, true] {
cases.push(single(form, name, "sopk cmovk", d, scc, k));
}
}
}
// SCC before is the opposite of the result, so a missing
// write shows.
Form::AddK => {
for d in VALUES {
let scc = !expect(form, d, false, k).1;
cases.push(single(form, name, "sopk addk", d, scc, k));
}
}
Form::MulK => {
for d in VALUES {
for scc in [false, true] {
cases.push(single(form, name, "sopk mulk", d, scc, k));
}
}
}
// Both SCC values before, so neither a missing write nor a
// flip of the old SCC passes.
_ => {
for d in VALUES {
for scc in [false, true] {
cases.push(single(form, name, "sopk cmpk", d, scc, k));
}
}
}
}
}
// An immediate whose low byte is 0xff (or both bytes) followed by
// `s_movk_i32 s9, 0x42`: had the word taken a literal, the move would
// be consumed and s9 never written.
for k in [0x00ff, 0xffff] {
let (d, scc) = (0x8000_0000, true);
let code = program(&[(8, d)], scc, &[sopk(op, 8, k), sopk(0, 9, 0x42)], 9);
let label = format!("simm16 {k:#06x}, then s_movk_i32 s9");
let after = expect(form, d, scc, k).1;
cases.push(case(name, "sopk no literal", label, code, (0x42, after)));
}
// s10 (the marker) and s9 keep their values: the form writes only
// SDST s8. The result is s10.
let code = program(
&[(8, 0x8000_0000), (9, 0x9999)],
true,
&[sopk(op, 8, 0x8000)],
10,
);
let after = expect(form, 0x8000_0000, true, 0x8000).1;
let label = "s10 after the form on s8".to_string();
cases.push(case(
name,
"sopk no other write",
label,
code,
(MARKER, after),
));
if form == Form::CmovK {
// A taken move initializes a never-written SDST: s20 is not read.
for k in IMMEDIATES {
let code = program(&[], true, &[sopk(op, 20, k)], 20);
let label = format!("s20 unwritten, simm16 {k:#06x}");
let family = "sopk cmovk unwritten sdst";
cases.push(case(name, family, label, code, (sext(k), true)));
}
}
// The top supported SGPR, s105, as SDST; the result is s105.
let (d, k) = (0x7fff_fff0, 0x0020);
let scc = if is_compare(form) || form == Form::AddK {
!expect(form, d, false, k).1
} else {
true
};
let code = program(&[(105, d)], scc, &[sopk(op, 105, k)], 105);
let label = format!("s105 {d:#x}, simm16 {k:#06x}");
cases.push(case(
name,
"sopk s105",
label,
code,
expect(form, d, scc, k),
));
}
cases
}
/// The SOPK word's byte offset in `program` with `init` SGPR moves: three
/// header words, one 8-byte move per init pair and the marker, and the AND.
fn alu_offset(init: usize) -> usize {
12 + 8 * (init + 1) + 4
}
/// Both interpreters must refuse `code` at the SOPK word, not later.
fn assert_rejected_at_alu(label: &str, code: &[u8], init: usize) {
let offset = alu_offset(init);
match xenora_ref::execute(code, &INPUT) {
Ok(_) => panic!("reference accepted {label}"),
Err(error) => assert_eq!(error.offset, offset, "reference rejected {label} elsewhere"),
}
match independent_ref::execute(code, &INPUT) {
Ok(_) => panic!("independent accepted {label}"),
Err(error) => assert!(
error.starts_with(&format!("{offset:#x}:")),
"independent rejected {label} elsewhere: {error}"
),
}
}
/// Programs both interpreters must refuse at the SOPK word, with the number
/// of init pairs before it.
fn rejections() -> Vec<(String, Vec<u8>, usize)> {
let mut all = Vec::new();
for (form, name) in FORMS {
let op = form as u32;
// VCC_LO/HI, TTMP0-15, M0, NULL, EXEC_LO/HI: outside the subset.
for sdst in 106..=127 {
let code = program(&[(8, 1)], true, &[sopk(op, sdst, 1)], 8);
all.push((format!("{name} sdst {sdst}"), code, 1));
}
if is_compare(form) {
// s20 is never written: the compare reads SDST.
let code = program(&[(8, 1)], true, &[sopk(op, 20, 1)], 8);
all.push((format!("{name} uninitialized s20"), code, 1));
} else {
for sdst in 0..8 {
let code = program(&[(8, 1)], true, &[sopk(op, sdst, 1)], 8);
all.push((format!("{name} write to resource s{sdst}"), code, 1));
}
if matches!(form, Form::AddK | Form::MulK) {
let code = program(&[(8, 1)], true, &[sopk(op, 20, 1)], 8);
all.push((format!("{name} uninitialized s20"), code, 1));
}
}
}
all
}
fn tally(cases: &[Case], key: fn(&Case) -> &'static str) -> BTreeMap<&'static str, usize> {
let mut counts = BTreeMap::new();
for case in cases {
*counts.entry(key(case)).or_default() += 1;
}
counts
}
/// Runs `execute` on every case and returns one line per failing family: the
/// number of failures and the first one.
fn failures(
cases: &[Case],
execute: impl Fn(&[u8], &[u32]) -> Result<Vec<u32>, String>,
) -> Vec<String> {
let mut failed: BTreeMap<&str, (usize, String)> = BTreeMap::new();
for case in cases {
let output = execute(&case.code, &case.input);
if output.as_deref().ok() != Some(case.expected.as_slice()) {
let first = format!("{}: {output:?}, expected {:?}", case.label, case.expected);
failed.entry(case.family).or_insert((0, first)).0 += 1;
}
}
failed
.into_iter()
.map(|(family, (n, first))| format!(" {family}: {n} failed, first: {first}"))
.collect()
}
fn checked_cases() -> Vec<Case> {
let cases = cases();
assert_eq!(tally(&cases, |case| case.family), BTreeMap::from(COUNTS));
cases
}
fn reference(code: &[u8], input: &[u32]) -> Result<Vec<u32>, String> {
xenora_ref::execute(code, input).map_err(|error| format!("{error:?}"))
}
#[test]
fn sopk_forms_match_the_guide_on_the_reference() {
let cases = checked_cases();
let failed = failures(&cases, reference);
assert!(
failed.is_empty(),
"reference disagrees with the guide:\n{}",
failed.join("\n")
);
eprintln!("sopk: {} reference cases", cases.len());
for (form, n) in tally(&cases, |case| case.form) {
eprintln!(" form {form}: {n}");
}
}
#[test]
fn sopk_forms_match_the_guide_on_the_independent_interpreter() {
let cases = checked_cases();
let failed = failures(&cases, independent_ref::execute);
assert!(
failed.is_empty(),
"independent interpreter disagrees with the guide:\n{}",
failed.join("\n")
);
eprintln!("sopk: {} independent-interpreter cases", cases.len());
}
#[test]
fn unsupported_sopk_operands_are_rejected() {
let rejections = rejections();
assert_eq!(rejections.len(), REJECTIONS);
for (label, code, init) in &rejections {
assert_rejected_at_alu(label, code, *init);
}
eprintln!("sopk: {} rejections", rejections.len());
}
#[test]
fn other_sopk_opcodes_stay_unsupported() {
// Table 66: 1 s_version, 18-19 getreg and setreg, 21 setreg_imm32 (its
// literal here would be the next word, refused all the same), 22 call,
// 23-26 waitcnt and 27-28 subvector loops; 17 and 20 are unlisted. 29-31
// are the SOP1, SOPC and SOPP encodings. With SDST s8, opcode 23 is not
// the `null, 0` store fence either.
for op in [1].into_iter().chain(17..=28) {
let code = program(&[(8, 1)], true, &[sopk(op, 8, 0)], 8);
assert_rejected_at_alu(&format!("opcode {op}"), &code, 1);
}
// `s_waitcnt_vscnt null, 1`: only the zero count is the supported fence.
let code = program(&[(8, 1)], true, &[sopk(23, 125, 1)], 8);
assert_rejected_at_alu("s_waitcnt_vscnt null, 1", &code, 1);
}
#[test]
fn cmovk_without_scc_is_rejected() {
// The header and the s10 marker move, then `s_cmovk_i32 s8, 1` with SCC
// never written: both interpreters must refuse it at byte 20.
let code = words(&[
0xe030_2000,
0x8000_0100,
0xbf8c_3f70,
0xbe80_03ff | 10 << 16,
MARKER,
sopk(Form::CmovK as u32, 8, 1),
0x7e04_0208,
0xe070_2000,
0x8001_0200,
0xbbfd_0000,
0xbf81_0000,
]);
match xenora_ref::execute(&code, &INPUT) {
Ok(_) => panic!("reference accepted s_cmovk_i32 without SCC"),
Err(error) => assert_eq!(error.offset, 20, "reference rejected it elsewhere"),
}
match independent_ref::execute(&code, &INPUT) {
Ok(_) => panic!("independent accepted s_cmovk_i32 without SCC"),
Err(error) => assert!(error.starts_with("0x14:"), "independent: {error}"),
}
}
#[test]
#[ignore = "requires a native Metal device with API and shader validation"]
fn sopk_forms_match_the_guide_on_native_metal() {
assert_eq!(std::env::var("MTL_DEBUG_LAYER").as_deref(), Ok("1"));
assert_eq!(std::env::var("MTL_SHADER_VALIDATION").as_deref(), Ok("1"));
for (label, code, _) in rejections() {
assert!(
compile(Architecture::Gfx1030, &code).is_err(),
"compiler accepted {label}"
);
}
let cases = checked_cases();
let (failures, programs) = harness::check_metal(&cases);
failures.assert_none("native Metal disagrees with the guide");
eprintln!("sopk: {} Metal cases in {programs} programs", cases.len());
}
+22 -4
View File
@@ -843,10 +843,20 @@ fn other_vop1_opcodes_stay_unsupported() {
}
#[test]
#[ignore = "requires a native Metal device with API and shader validation, and the translator's VOP1 integer forms (skipped by scripts/test-gpu.sh until then)"]
fn vop1_integer_forms_match_the_guide_on_native_metal() {
assert_eq!(std::env::var("MTL_DEBUG_LAYER").as_deref(), Ok("1"));
assert_eq!(std::env::var("MTL_SHADER_VALIDATION").as_deref(), Ok("1"));
fn compiler_matches_the_vop1_integer_operand_domain() {
let cases = checked_cases();
for case in &cases {
compile(Architecture::Gfx1030, &case.code)
.unwrap_or_else(|error| panic!("compiler rejected {}: {error:?}", case.label));
}
check_compiler_rejections();
eprintln!(
"vop1_integer: {} compiler cases and {REJECTIONS} rejections",
cases.len()
);
}
fn check_compiler_rejections() {
for (label, code, offset) in rejections() {
// Refused at the same word as by the interpreters, so a later failure
// cannot stand in.
@@ -857,7 +867,15 @@ fn vop1_integer_forms_match_the_guide_on_native_metal() {
};
assert_eq!(at, offset, "compiler rejected {label} elsewhere");
}
}
#[test]
#[ignore = "requires a native Metal device with API and shader validation"]
fn vop1_integer_forms_match_the_guide_on_native_metal() {
assert_eq!(std::env::var("MTL_DEBUG_LAYER").as_deref(), Ok("1"));
assert_eq!(std::env::var("MTL_SHADER_VALIDATION").as_deref(), Ok("1"));
let cases = checked_cases();
check_compiler_rejections();
let (failures, programs) = harness::check_metal(&cases);
failures.assert_none("native Metal disagrees with the guide");
eprintln!(
+12
View File
@@ -67,6 +67,18 @@ class GenerateX86(unittest.TestCase):
self.rejects(self.form('op = "movq"\nmap = "0f"\nprefix = "66"\nopcode = 0xF0\nenc = "xmm_rm"\nsize = "x"\nsrc = "q"\nunaligned = true'), "alignment applies")
self.rejects(self.form('op = "nop"\nprefix = "66"\nopcode = 0xD7\nenc = "none"\nsize = "n"'), "map 0f")
def test_lock_needs_a_memory_destination(self):
# Not a form without ModRM, not one whose ModRM operand is the source,
# and not one that takes only a register.
message = "LOCK needs a memory destination"
self.rejects(self.form('op = "nop"\nopcode = 0xD7\nenc = "none"\nsize = "n"\nlock = true'), message)
self.rejects(self.form('op = "mov"\nopcode = 0xD7\nenc = "reg_rm"\nsize = "v"\nlock = true'), message)
self.rejects(self.form('op = "xadd"\nopcode = 0xD7\nenc = "rm_reg"\nsize = "v"\nregister_only = true\nlock = true'), message)
def test_only_xadd_and_cmpxchg_are_lockable(self):
_, forms = generate_x86.load(REGISTRY)
self.assertEqual({form["op"] for form in forms if form.get("lock")}, {"cmpxchg", "xadd"})
def test_unknown_vocabulary_is_rejected(self):
self.rejects(self.form('op = "frob"\nopcode = 0xD7\nenc = "none"\nsize = "n"'), "unknown op")
self.rejects(self.form('op = "nop"\nopcode = 0xD7\nenc = "none"\nsize = "z"'), "unknown size")