Compare commits

...
Author SHA1 Message Date
Swastick Chowdhury 8cae9772b6 loader: restore and complete FS/GS segment-override tests (#289)
Restore the six #280 regression tests that the merge resolving #280's
conflict with #283 removed. Add FS and GS RIP-relative loads and stores
with positive and negative displacements, a differential run comparing
the native DBT and interpreter registers and memory bytes, and
RIP-relative faults reporting the segment-adjusted address. Make the
existing differential test compare both paths' memory.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 18:08:32 +05:30
Ranveer Soni c6a354bca5 Merge pull request #285 from ranveersoni98/feat/rdna2-planner-opt
feat(qa): tighten RDNA2 planning filters, manifests and claim exclusion
2026-11-24 17:57:31 +05:30
Ranveer Soni 9d83e09aa6 feat(qa): tighten RDNA2 planning filters, manifests and claim exclusion.
Add family/status filters, compact output, Codex manifests, path-only vs family claim scoping, and coverage reconcile without inflating counts.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:56:13 +05:30
Ranveer Soni 3bdc43d3ad Merge pull request #281 from Swastickc/task/66-movsx-movzx
loader: implement MOVZX and MOVSX in the interpreter (#66)
2026-11-24 17:47:21 +05:30
Ranveer Soni fa434d7174 Merge pull request #282 from Swastickc/task/279-native-app-gate5
app: persistent GPU resources, dynamic texture updates, and resource retirement (#279)
2026-11-24 17:46:43 +05:30
Ranveer Soni ed657ad802 Merge pull request #280 from Swastickc/task/72-segment-override
loader: add the FS and GS segment base to RIP-relative operands in the DBT (#72)
2026-11-24 17:46:25 +05:30
Ranveer Soni b49ec43ddc Merge branch 'main' into task/72-segment-override 2026-11-24 17:46:11 +05:30
Ranveer Soni d00c787544 Merge pull request #283 from Swastickc/task/65-movsx-dest-width
loader: clear the upper half of a 32-bit MOVSX destination (#65)
2026-11-24 17:45:40 +05:30
Swastick Chowdhury f6dfe58695 loader: implement MOVZX and MOVSX in the interpreter (#66)
The native DBT translator implements the four extension opcodes MOVZX r32/r64,
r/m8 (0F B6), MOVZX r32/r64, r/m16 (0F B7), MOVSX r32/r64, r/m8 (0F BE) and
MOVSX r32/r64, r/m16 (0F BF), with both register and memory source operands.
The interpreter implemented none of them: its 0x0F handler covered only SYSCALL
(0F 05) and BSWAP (0F C8..CF), so any of the four opcodes exited with
IllegalInstruction and the two execution paths accepted different instruction
sets for the same bytes.

Implement them in the interpreter:

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

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

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

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

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

Closes #66

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 17:37:02 +05:30
Swastick Chowdhury b12aa502a2 loader: add the FS and GS segment base to RIP-relative operands in the DBT (#72)
The native DBT translator computed the RIP-relative address and passed it
straight to the memory helper, without adding the FS or GS segment base. The
non-RIP-relative path went through emit_effective_address, which does add it,
so the two paths in the same translator disagreed with each other, and the
interpreter in crates/loader/src/cpu.rs disagreed with both.

Per the Intel SDM Volume 3A, section 3.4.4, "When FS and GS segment overrides
are used in 64-bit mode, their respective base addresses are used in the
linear address calculation: (FS or GS).base + index + displacement", and the
AMD64 Architecture Programmer's Manual Volume 1, section 2.2.3.3, "Use of the
FS or GS prefix causes their respective segment bases to be added to the
effective address calculation." The base is added for every addressing form,
so the RIP-relative form needs it too.

The segment base is a runtime guest value, so it cannot be folded into the
translation-time immediate. The addition is factored into emit_segment_base,
which reads the base from the guest CPU state at run time, and is now called
from the RIP-relative MOV paths as well as from emit_effective_address.

Add six regression tests in the dbt test module:

- fs_segment_override_adds_the_fs_base_to_the_address: a segment-relative
  store and load land at the FS base plus the displacement, not at the bare
  displacement.
- gs_segment_override_adds_the_gs_base_to_the_address: the GS base is used,
  and a distinct FS base is left untouched.
- rip_relative_segment_override_adds_the_segment_base: the RIP-relative form
  adds the segment base. This test fails without the fix.
- segment_relative_access_to_an_unmapped_address_faults: a segment-relative
  access outside the mapped regions faults and reports the segment-adjusted
  address.
- interpreter_and_native_dbt_agree_on_segment_relative_addressing: the same
  program runs through the interpreter and the native DBT and produces the same
  state and the same memory writes.
- redundant_fs_and_gs_overrides_are_handled_the_same_by_both_paths: an
  instruction carrying both an FS and a GS override is architecturally
  undefined, so this pins the local rule that both paths prefer GS and that
  they agree with each other.

Every encoding was produced by LLVM 23.1.6 llvm-mc -show-encoding, and the
expected addresses were derived from the SDM rule above.

Closes #72

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 17:36:38 +05:30
Swastick Chowdhury 20780eab24 loader: clear the upper half of a 32-bit MOVSX destination (#65)
The native DBT translator sign-extended to 64 bits unconditionally and stored
the full 64-bit result, so a 32-bit MOVSX destination kept the sign extension
in bits 63:32 instead of having them cleared.

Before, both MOVSX paths did this:

    asm.sxtb_64(X9, X9);   // or sxth_64
    asm.str_uoff_64(X9, X19, (reg_idx as u32) * 8);

`sxtb_64` is `SBFM Xd, Xn, #0, #7`, which sign-extends the byte to 64 bits,
and `str_uoff_64` writes all 64 bits of the destination register.

That is correct for the REX.W form `movsbq rax, bl`, but the Intel SDM
requires a 32-bit result for the 32-bit destination form `movsbl eax, bl`. The
translator therefore left `rax = 0xFFFFFFFFFFFFFFFF` where the architecture
requires `rax = 0x00000000FFFFFFFF`.

Select the sign-extension width from REX.W:

- REX.W set: keep the 64-bit extension, which is already correct.
- REX.W clear: sign-extend to 32 bits, which also clears bits 63:32 of the
  destination because the 32-bit form writes a W register.

This needs two new assembler instructions, `sxtb_32` and `sxth_32`, which are
the 32-bit forms of the existing `sxtb_64` and `sxth_64`:

    sxtb_32: SBFM Wd, Wn, #0, #7   (0x13001c00)
    sxth_32: SBFM Wd, Wn, #0, #15  (0x13003c00)

Both encodings were confirmed against LLVM 23.1.6 `llvm-mc -triple=aarch64
-show-encoding`.

The MOVZX paths are unchanged: a zero extension produces the same value at
both destination widths, because the 32-bit form already clears the upper half.

Add three regression tests in the dbt test module covering the register and
memory source forms and the byte and word sources, each at both destination
widths. Every encoding was produced by LLVM 23.1.6 llvm-mc -show-encoding and
the expected values follow the Intel SDM rules for MOVSX.

All three tests fail against the unmodified translator and pass with this
change.

Closes #65

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 17:35:49 +05:30
Swastick Chowdhury 259b3054e1 app: persistent GPU resources, dynamic texture updates, and resource retirement (#279)
Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 17:34:01 +05:30
Ranveer Soni f685edebfb feat(qa): wire coverage history and branch-sync into the qa CLI.
Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:27:35 +05:30
Ranveer Soni c0cb3e72be feat(qa): add RDNA2 coverage history snapshots and stale-branch reports.
Persists inventory snapshots between revisions and classifies ahead,
behind and diverged contributor branches.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:27:35 +05:30
Ranveer Soni a27d63bfab docs(coordination): refresh infrastructure QA ledger for Phase II.
Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:26:33 +05:30
Ranveer Soni 0f7658bb5b docs(changelog): record Phase II infrastructure automation CLIs.
Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:26:33 +05:30
Ranveer Soni 313430c1c6 docs(testing): document Phase II qa and release CLI workflows.
Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:26:33 +05:30
Ranveer Soni 63cf3595cd test(qa): smoke-test qa and release CLIs against real commands.
Covers shlex orchestration, live RDNA2 inventory and negative
readiness exit codes.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:26:32 +05:30
Ranveer Soni 050df307a1 feat(release): build release-readiness reports with SBOM and evidence.
Combines Mach-O, bundle, codesign, checksum and dependency inventory
checks into one non-publishing readiness report.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:26:32 +05:30
Ranveer Soni 7a5176497a feat(qa): detect claim collisions across renames and deletions.
Parses git name-status lines so renamed and deleted paths are handled
in shared-file collision reports.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:26:32 +05:30
Ranveer Soni f4005501bc feat(qa): compare recorded benchmarks with identity and noise guards.
Rejects mismatched workload/host/toolchain pairs and ignores median
moves inside a configurable noise floor.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:26:32 +05:30
Ranveer Soni f175a10033 feat(qa): scan CPU opcode and import coverage from existing sources.
Produces machine-readable inventories, interpreter-vs-DBT gaps and
prioritized blocker manifests without changing runtime policy.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:26:32 +05:30
Ranveer Soni c651a9d320 feat(qa): add unified verification profiles with stale evidence detection.
Runs existing repository commands serially, preserves exit codes and
fingerprints sources so outdated reports fail closed.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:26:32 +05:30
Ranveer Soni 22bafeb0b2 feat(qa): add read-only RDNA2 expansion planning over live inventories.
Discovers unsupported forms dynamically from the AMD snapshot, registry,
decoder tables and status evidence without editing GPU production code.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:26:32 +05:30
Ranveer Soni f56d3c9862 feat(release): add python3 -m release CLI entrypoints.
Wraps arch, linkage, bundle, manifest, license and readiness commands
for packaging checks without publishing releases.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:26:32 +05:30
Ranveer Soni 48f44cac3d feat(qa): add operational python3 -m qa CLI.
Exposes orchestration, PR validation, conflict prediction, RDNA2
planning, verification profiles, CPU coverage and env diagnostics.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:26:32 +05:30
Ranveer Soni 8410e3d0e8 test(qa): cover environment diagnostic helpers.
Positive and negative checks for host arch, Rosetta, rustc host, Swift,
LLVM, worktree cleanliness and branch sync.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:26:32 +05:30
Ranveer Soni 19bea60d25 Merge pull request #278 from Swastickc/task/276-native-app-gate4
app: interactive guest execution with input handling and dynamic rendering (#276)
2026-11-24 17:11:42 +05:30
Ranveer Soni f70e6d0534 Merge branch 'main' into task/276-native-app-gate4 2026-11-24 17:11:30 +05:30
Swastick Chowdhury 223fe253c9 app: interactive guest execution with input handling and dynamic rendering (#276)
Add interactive guest execution with dynamic input handling and rendering
(Gate 4) through the versioned C runtime interface. The guest fixture
(fixtures/pe/interactive.exe, generated by fixtures/pe/interactive.py)
runs on a dedicated session-owned thread and polls host input snapshots
via xenora.dll!input_poll. It steers its rendered column position (0..3)
on native Metal and submits frames with xenora.dll!frame_submit(column).

Add xenora_session_start_interactive_loop, xenora_session_send_input,
xenora_session_queue_input, and xenora_session_get_recorded_frame to the
C interface, plus input masks (XENORA_INPUT_*) and xenora_input_state.
Pre-queuing inputs enables deterministic replay across independent
sessions without physical interaction.

Xenora.app gains interactive frame-loop controls (Interactive 300 frames,
Left, Right, Release) and a --smoke-interactive CLI flag. Four GPU
acceptance tests verify input-driven state changes, reproducible frame
sequences across deterministic replays, clean release/focus behavior
without stuck keys, and prompt join on session destruction.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 17:09:04 +05:30
Ranveer Soni 62be091197 docs(coordination): fill infrastructure QA ledger with commit SHAs.
Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:19 +05:30
Ranveer Soni cf288dd940 docs(changelog): note infrastructure QA tooling and agent-queue smoke fixes.
Records advisory scripts/qa and scripts/release helpers plus the live
smoke-driven agent-queue apply/audit fixes.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:19 +05:30
Ranveer Soni 9f57d8b3bb docs(testing): index infrastructure QA and release tooling.
Adds the tooling README and links from docs/README.md for new
coordination and infrastructure documents.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:19 +05:30
Ranveer Soni 5d4d15d596 feat(release): build checksum manifests and license inventories.
SHA-256 artifact manifests with evidence validation and deterministic
dependency license listings for release packaging.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:18 +05:30
Ranveer Soni 95ddc28518 feat(release): verify ARM64 Mach-O arch, linkage and app bundles.
Rejects non-arm64 lipo output, forbidden Vulkan/MoltenVK linkage and
incomplete .app layouts; diagnoses unsigned codesign output.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:18 +05:30
Ranveer Soni 9cc4a965c4 feat(qa): predict claim file-scope conflicts before editing.
Read-only overlap checks against held claims so contributors can avoid
collisions without posting /claim.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:18 +05:30
Ranveer Soni 9b767186a2 feat(qa): add Apple Silicon environment diagnostic helpers.
Checks host arch, Rosetta translation, rustc host triple, Swift/LLVM
presence and branch sync state from caller-supplied command outputs.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:18 +05:30
Ranveer Soni 823007888f feat(qa): compare orchestration history and emit handoff reports.
Detects newly failed suites, summarizes contributor progress and flags
tracked build artifacts in read-only health checks.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:18 +05:30
Ranveer Soni 881c2a2e52 feat(qa): analyze existing benchmark samples for percentiles.
Computes median, p95, p99, IQR and thresholded median regressions
without modifying benchmark workloads.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:18 +05:30
Ranveer Soni 475b27e5d4 feat(qa): add advisory PR scope, DCO and artifact validators.
Standalone checks for ownership scope, Signed-off-by trailers, build
artifacts, changelog presence and evidence SHA identity.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:18 +05:30
Ranveer Soni cac93574ce feat(qa): add structured multi-suite test orchestration reports.
Records durations, exit codes, ignored/unexecuted suites, CPU/GPU
separation, failure excerpts and reproduction commands.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:18 +05:30
Ranveer Soni 085b0e28e5 feat(qa): preserve command exit status for orchestration pipes.
Provides the contract that failed commands stay failed even when their
stdout contains a greppable success token.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:18 +05:30
Ranveer Soni 835689e5df docs(coordination): add infrastructure QA campaign ledger.
Tracks commits, smoke status and limitations for the QA tooling campaign.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:18 +05:30
Ranveer Soni 55e1818ccd docs(coordination): record agent-queue disposable smoke evidence.
Documents live Actions results for claim, overlap refusal, release,
progress, denial and a successful audit (#180).

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:18 +05:30
Ranveer Soni 44ea8133fc fix(ci): grant agent-queue audit pull-requests:read.
Live smoke audits failed on gh pr list without this permission.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:18 +05:30
Ranveer Soni 756597a6b4 fix(agent-queue): accept summary --now after the subcommand.
Actions passes --now after summary; parent-only argparse rejected that
and failed the live audit smoke run.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 17:08:18 +05:30
Ranveer Soni 4038cdbe41 docs(coordination): record infrastructure QA ownership manifest.
Lists hard exclusions, active claims, approved tooling paths and
existing scripts that must be wrapped rather than duplicated (#180).

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 16:57:34 +05:30
Ranveer Soni 51b60381c5 test(agent-queue): add read-only claim conflict prediction coverage.
Exercises claim_problem against overlap, area and dependency failures
without mutating queue state, matching live claim refusal text.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 16:57:34 +05:30
Ranveer Soni 2593f73f29 fix(agent-queue): skip no-op gh issue edit on comment-only actions.
Claim refusals and other comment-only decisions crashed apply_actions
because the edit argv already had five tokens before any label flags.
Caught by the disposable smoke repository on live Actions.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 16:57:34 +05:30
Ranveer Soni 3f3f154d2d Merge pull request #275 from elforeign/task/215-vop2
isa, decoder, shader: twelve VOP2 vector integer forms through the semantic registry (#215)
2026-11-24 16:48:47 +05:30
elforeign 4d68733f3c Merge remote-tracking branch 'origin/main' into task/215-vop2 2026-11-24 05:12:54 -06:00
Ranveer Soni d22f046bf9 Merge pull request #274 from Swastickc/task/266-native-app-gate3
app: persistent guest rendering with pause, resume and stop (#266)
2026-11-24 16:42:33 +05:30
Ranveer Soni 430f63e27d Merge branch 'main' into task/266-native-app-gate3 2026-11-24 16:42:24 +05:30
elforeign ce29b87770 Merge remote-tracking branch 'origin/main' into task/215-vop2 2026-11-24 05:11:31 -06:00
elforeign ad424d690a isa, validation: reject undeclared implicit XML operands; runtime vcc_lo for VOP2 (#215)
Review follow-up: the generator now rejects a form whose XML lists an
implicit operand other than SCC (for example the VCC carry of
v_add_co_ci_u32 or the VCC select of v_cndmask_b32), since the
vocabulary can only declare VCC and EXEC unchanged. New known-answer
tests read a lane-derived vcc_lo as VOP2 SRC0 (also on native Metal)
and require the forms to be refused inside a runtime s_cbranch_vccz skip
region. The LLVM comparison normalises inline SRC0 for the registry VOP2
forms as for VOPC; docs and counts follow.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 05:11:31 -06:00
Swastick Chowdhury 9e47234e92 app: persistent guest rendering with pause, resume and stop (#266)
Add persistent frame-loop guest rendering (Gate 3) through the versioned
C runtime interface. The guest fixture (fixtures/pe/frame-loop.exe,
generated by fixtures/pe/frame-loop.py) runs on a dedicated guest thread,
calling xenora.dll!frame_submit(index) until commanded to halt. Each frame
is rendered on native Metal, verified against the geometry strip rule, and
returned as read-back RGBA8 buffers.

Add xenora_session_start_frame_loop, xenora_session_pause_frame_loop,
xenora_session_resume_frame_loop, xenora_session_stop_frame_loop, and
xenora_session_frame_loop_status to the C interface, plus new states.
Destroying a live session safely stops and joins the guest loop without
holding the global session lock.

Xenora.app gains persistent frame-loop controls (start 300 frames, pause,
resume, stop) and displays live frames with their index and completion
count. Add --smoke-loop CLI flag and wire the five GPU acceptance tests
into scripts/test-gpu.sh.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 16:37:34 +05:30
elforeign 5ba0496c63 isa, decoder, shader: twelve VOP2 vector integer forms through the semantic registry (#215)
Adds v_mul_{i32_i24,hi_i32_i24,u32_u24,hi_u32_u24}, v_min/max_{i32,u32},
v_xnor_b32 and v_{add,sub,subrev}_nc_u32 as registry data under a new
vop2_vgpr operand rule (VGPR destination; SRC0 a VGPR, s0-s105, vcc_lo,
an inline integer or a literal; VGPR VSRC1). Vector forms select a
per-lane VectorBinary from their declared operation and signedness, and
the shader lowers each VectorBinary through one typed MSL template; SUBREV
declares source_order = reversed. Variant names are now unique per
generated enum. The decoder shares the VOPC SRC0 decode, and the
translator binds a result to the slot it was pushed at, since operand
constants may now be pushed first. The oracle merged from
task/215-vop2-oracle supplies the reference side; a new LLVM-assembled
fixture computes every lane from its own input.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 05:06:48 -06:00
Ranveer Soni cd224d86f4 Merge pull request #272 from Swastickc/task/63-rex-x-sib
loader: extend the SIB index register with REX.X, not REX.R (#63)
2026-11-24 16:29:21 +05:30
Ranveer Soni dd4bcb30eb Merge pull request #273 from elforeign/task/215-sop2-arith
isa, decoder: sixteen SOP2 integer forms through the semantic registry (#215)
2026-11-24 16:29:07 +05:30
elforeign aef29ff65d Merge branch 'task/215-vop2-oracle' into task/215-vop2 2026-11-24 04:57:47 -06:00
elforeign 3392c226ce validation: SCC stays unset across SOP2 forms that do not write it; compiler rejections at the SOP2 word (#215)
Review follow-up: four programs run BFM, MUL or MUL_HI and then CSELECT
with SCC never written, and every interpreter and the compiler must
refuse the CSELECT. The native test now also requires the compiler to
reject each program at the same word as the interpreters, so a later
failure cannot stand in (shown by a translator that turns an unset SCC
into false, which only this check catches).

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:56:28 -06:00
elforeign 72bf5f7e32 validation: VOP2 integer review gaps: reserved SRC0, literal under empty EXEC, VCC under partial EXEC (#215)
A Codex review found three ways a defective interpreter would still pass:
selectors 209-232 were never refused (a negative inline range one too
long passed), the literal was never decoded with EXEC = 0, and VCC was
only checked under full EXEC, so a VCC write limited to active lanes
went unseen. Each now has cases; a reference accepting selector 209 and
one ANDing VCC_LO with EXEC were both shown failing.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:55:51 -06:00
Swastick Chowdhury 78df3a5c6b loader: extend the SIB index register with REX.X, not REX.R (#63)
The interpreter used REX.R to extend the SIB index field and ignored REX.X
entirely, so the two paths disagreed with the native DBT translator, which
already extends the index with REX.X.

Two defects are fixed in the SIB branch of the MOV r/m effective-address
computation:

- The index register is now extended by REX.X. REX.R extends the ModRM reg
  field and must not affect the index.
- A SIB index field of 100b selects r12 when REX.X is set, and means "no
  index register" only when REX.X is clear.

REX.X is decoded from the REX prefix into the typed Prefixes struct.

Add regression tests covering an extended index register including r12, an
independent REX.R and REX.X combination, both prefix bits set together, and
the no-index case. Every encoding was produced by LLVM 23.1.6 llvm-mc and the
expected addresses were derived from the Intel SDM SIB rules.

The three REX.X tests fail against the unfixed interpreter and pass with the
fix; the no-index test passes in both cases.

Closes #63

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 16:24:57 +05:30
elforeign 133c9df448 Merge remote-tracking branch 'origin/main' into task/215-sop2-arith 2026-11-24 04:54:47 -06:00
elforeign a6d354fb2a validation: rustfmt the VOP2 integer oracle (#215)
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:52:53 -06:00
elforeign 00f79c10d2 isa, decoder, shader: sixteen SOP2 integer forms through the semantic registry (#215)
Adds s_min/max_{i32,u32}, s_cselect_b32, s_bfm_b32, s_mul_i32,
s_mul_hi_{u32,i32}, s_bfe_{u32,i32}, s_absdiff_i32 and
s_lshl1..4_add_u32 as registry data over new shared primitives. The
vocabulary gains a selected_src0 SCC effect (min and max: S0 won the
strict compare), the select's SCC input (carry_in = scc, required for
cselect), a declared shift_amount for the shift-and-add forms, and a
check that BFE's S1 descriptor is unsigned in the XML. The generated
ScalarAluOp::evaluate now returns an optional SCC, so forms whose XML
shows no SCC output leave it unchanged in the translator. The decoder
picks them up through the generated SOP2 table; the oracle merged from
task/215-sop2-arith-oracle supplies the reference side. A new
LLVM-assembled fixture chains all sixteen.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:51:33 -06:00
elforeign 95a8c61f1b ref, validation: twelve VOP2 integer forms in both interpreters (#215)
The VOP2 decode in both interpreters accepted only a VGPR as SRC0, so
the 24-bit multiplies, MIN/MAX, XNOR and the no-carry add/sub forms
also take an SGPR, vcc_lo, an inline integer or a literal through the
VOPC source decode, now shared. The reference uses exact i64
arithmetic; the second interpreter a shift-and-add multiplier with
Euclidean division for the high half, sign-flipped unsigned order for
MIN/MAX and the ripple adder for add and subtract. Neither writes VCC
or SCC, and inactive lanes keep VDST. The earlier hand-written VOP2
forms keep their VGPR-only SRC0.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:51:02 -06:00
elforeign 31627363f1 validation: guide-derived per-lane oracle for twelve VOP2 integer forms (#215)
Expected values for the 24-bit multiplies, MIN/MAX, XNOR and the no-carry
add/sub forms come from the RDNA 2 guide section 12.7 only, checked per
lane over boundary operands, every SRC0 kind, aliasing, v255, partial and
empty EXEC, a partial final wave and VCC/SCC seeds. Both interpreters
reject these forms today, so the reference and independent tests fail
until they gain the forms.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:49:32 -06:00
Ranveer Soni ee2d29a65c Merge pull request #271 from Swastickc/task/267-app-inspect
app: open a PE executable and show read-only compatibility diagnostics (#267)
2026-11-24 16:12:12 +05:30
Ranveer Soni 83ef49c258 Merge branch 'main' into task/267-app-inspect 2026-11-24 16:11:56 +05:30
elforeign 84b6fb4d50 Merge branch 'task/215-sop2-arith-oracle' into task/215-sop2-arith 2026-11-24 04:41:40 -06:00
elforeign b98380c1b0 Merge branch 'task/215-sop2-arith-oracle' into task/215-vop2-oracle 2026-11-24 04:41:22 -06:00
Swastick Chowdhury 7fa240f7ba app: open a PE executable and show read-only compatibility diagnostics (#267)
Add xenora_inspect_executable to the C interface: a bounded, read-only
report from the static probe and loader validation (hash, headers,
sections, imports not provided by the standard runtime services, DBT
coverage of the bounded disassembly, relocation and TLS counts). Nothing
in the file is executed. A probe panic becomes a report labelled as a
Xenora defect (#270). Xenora.app opens files via Open Executable..., drag
and drop, and Finder (alternate viewer for Windows executables).

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 16:09:15 +05:30
elforeign 0e9211cd42 validation: s105 operands for the SOP2 integer forms; s_min_i32 is no longer an unsupported example (#215)
A review found that every passing sop2_arith case wrote s8-s10, so an
interpreter refusing a high destination would pass; s105 now appears as
destination, either source and all three. known_answers used s_min_i32
as an opcode outside the subset; it is supported now, so s_cselect_b64
takes its place.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:38:51 -06:00
elforeign c41e034fa1 ref, validation: 16 SOP2 integer forms in both interpreters (#215)
xenora_ref and independent_ref now run s_min/max_{i32,u32},
s_cselect_b32, s_bfm_b32, s_mul_i32, s_bfe_{u32,i32}, s_absdiff_i32,
s_lshl1..4_add_u32 and s_mul_hi_{u32,i32} as the RDNA 2 ISA guide 12.1
describes, so the guide-derived sop2_arith expectations pass on both.
CSELECT reads SCC and is refused when SCC was never written; CSELECT,
BFM, MUL_I32 and MUL_HI leave SCC unchanged. The second interpreter
uses bit loops, a ripple adder and shift-and-add products rather than
the reference's host arithmetic.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:36:31 -06:00
Ranveer Soni 7977dd4bf2 Merge pull request #268 from elforeign/task/215-sop1
isa, decoder: eleven SOP1 unary forms through the semantic registry (#215)
2026-11-24 16:06:11 +05:30
Ranveer Soni cd948d4a14 Merge pull request #269 from Swastickc/task/62-prefix-struct
loader: group interpreter instruction prefixes into a typed struct (#62)
2026-11-24 16:05:46 +05:30
elforeign a2c696b551 validation: guide-derived expectations for 16 SOP2 integer forms (#215)
Expected D and SCC for s_min/max_{i32,u32}, s_cselect_b32, s_bfm_b32,
s_mul_i32, s_bfe_{u32,i32}, s_absdiff_i32, s_lshl1..4_add_u32 and
s_mul_hi_{u32,i32}, written from the RDNA 2 ISA guide (12.1 and the
section 5 tables) before either interpreter supports them, so both fail
here. A separate guide-only table agrees on all 5086 shared inputs.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:34:26 -06:00
Swastick Chowdhury d6189ae3ea loader: group interpreter instruction prefixes into a typed struct (#62)
Replace the #[allow(clippy::too_many_arguments)] on execute_mov_rm with a
Prefixes struct that carries rex_w, rex_r, rex_b, seg_gs and seg_fs. The
interpreter decodes the prefixes once per instruction and passes the struct to
the helpers that need them, so the lint is satisfied by construction instead
of suppressed.

Add a regression test module that pins the prefix and register-extension
behaviour of the interpreter: REX.R and REX.B selecting the expected ModRM
reg and rm registers, the two bits extending independent fields, a move
without REX.W staying 32-bit wide, and the FS prefix adding the FS base.
The test was run against unmodified main first and passed there, so the
refactor is shown to preserve semantics.

Closes #62

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 16:02:10 +05:30
elforeign e6eece6983 validation: require the compiler's SOP1 rejections at the SOP1 word (#215)
Review follow-up: the native test only checked that compilation failed,
so a regressed destination guard still passed when a later instruction
read an uninitialized SGPR (shown by allowing vcc_lo as a destination).
It now requires a decode error at the SOP1 offset. Also check that no
registry form duplicates a hand-written decoder form.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:30:44 -06:00
elforeign 1a78265ede Merge remote-tracking branch 'origin/main' into task/215-sop1
# Conflicts:
#	CHANGELOG.md
2026-11-24 04:27:26 -06:00
elforeign 2e0e5a36f6 isa, decoder, shader: SOP1 unary integer forms through the semantic registry (#215)
Adds eleven SOP1 forms as registry data: complement, bit reverse, bit
counts, find-first and find-last searches, sign extension and absolute
value. Sign extension declares source_bits, which the generator checks
against the XML's 8- and 16-bit source operands; forms whose XML shows
no SCC output must declare SCC unchanged. The decoder dispatches them
through the generated SOP1 table after s_mov_b32, and the translator
folds them with ScalarUnaryOp::evaluate. The separately written oracle
from task/215-sop1-oracle supplies the reference side.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:27:14 -06:00
Ranveer Soni ece0fc27eb Merge pull request #265 from Swastickc/task/263-native-app-gate2
app: show the trusted fixture's guest-driven Metal frame (Gate 2, #263)
2026-11-24 15:56:25 +05:30
Swastick Chowdhury 82f2d9e9e6 app: show the trusted fixture's guest-driven Metal frame (#263)
Add xenora_session_run_trusted_fixture to the C interface. It runs only
the embedded trusted PE fixture through DBT startup; the guest's
fixture_draw import compiles the x9 RDNA2 shaders to MSL and renders on
native Metal. The 4x3 RGBA8 read-back is returned only when the guest
halts with the runner's expected results and every pixel equals the
pixel shader's export. Xenora.app shows the frame; --smoke-frame prints
it. Add a gpu-tests test run by scripts/test-gpu.sh.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:56:07 +05:30
elforeign 391367a531 Merge branch 'task/215-sop1-oracle' into task/215-sop1 2026-11-24 04:23:47 -06:00
Ranveer Soni e71a3da525 Merge pull request #264 from elforeign/task/215-stage-d
isa, decoder: SOPC integer compares through the semantic registry (#215 stage D)
2026-11-24 15:52:40 +05:30
elforeign b96511bfc5 validation: cover s105 in the SOP1 unary cases (#215)
Review found that every register operand was s8 or s10, so a decoder that
dropped the top bit of SDST or SSRC0 would pass. s105 now appears as source,
destination and both.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:22:34 -06:00
elforeign 84bb80d910 ref, validation: evaluate eleven SOP1 unary forms in both interpreters (#215)
Both interpreters now run s_not/brev/bcnt0/bcnt1/ff0/ff1/flbit(_b32)/
sext_i8/sext_i16/abs with SDST s0-s105. Not-found searches return -1,
s_flbit_i32 returns -1 for 0 and -1, abs keeps 0x80000000, and only NOT,
BCNT0, BCNT1 and ABS write SCC (D != 0). The reference uses host bit
intrinsics; the second interpreter works from an explicit bit array and
arithmetic, so they do not share an evaluation path.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:20:56 -06:00
elforeign 9edf644d77 Merge remote-tracking branch 'origin/main' into task/215-stage-d 2026-11-24 04:20:17 -06:00
elforeign b5d0382e89 semantics, docs: review follow-ups for the SOPC compares (#215)
Malformed relations and operand rules are diagnostics instead of
Python exceptions; the fixture now really carries a SOPC literal (LLVM
had encoded 0xffffffff as inline -1); the reference-interpreter table
and registry field table describe the current forms; the docs and
changelog state separately that the 348 rejections run on the CPU
interpreters and the compiler, not on Metal.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:20:16 -06:00
elforeign b705104403 validation: guide-derived expectations for eleven SOP1 unary forms (#215)
D and SCC for s_not/brev/bcnt0/bcnt1/ff0/ff1/flbit(_b32)/sext_i8/sext_i16/abs
are written from the RDNA 2 ISA guide (12.3 pseudocode and examples, Tables 12
and 14 for SCC) before either interpreter implements them.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:19:31 -06:00
Ranveer Soni f148b51a48 Merge pull request #262 from Swastickc/task/261-native-app-gate1
app: native macOS shell and versioned C runtime interface (Gate 1, #261)
2026-11-24 15:46:34 +05:30
elforeign c979870b3a Merge remote-tracking branch 'origin/main' into task/215-stage-d 2026-11-24 04:16:09 -06:00
elforeign cd59e081d9 isa, decoder: SOPC integer compares through the semantic registry (#215 stage D)
Adds a compare operation with a declared relation and the sopc_scalar
operand rule, so all twelve s_cmp_*_{i32,u32} forms are registry data.
The decoder dispatches them through the generated OP table and the
translator resolves SCC with ScalarCompareOp::test; the hand-written
s_cmp_eq_u32 path and its opcode constant are gone. A new LLVM-assembled
fixture records every compare's SCC, and the separately written oracle
from task/215-stage-d-oracle supplies the reference side.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:16:09 -06:00
Ranveer Soni 0bfb12fd17 Merge branch 'main' into task/261-native-app-gate1 2026-11-24 15:45:49 +05:30
Swastick Chowdhury c6d0986da2 app: add native macOS shell and versioned C runtime interface (#261)
Add crates/ffi, a static library exposing a version 1 C interface with
opaque generation-checked session handles, stable status codes and
panic containment. It can create and destroy sessions and parse the
bundled trusted PE fixture; no guest code runs. Add a minimal SwiftUI
app (Swift Package Manager) that links it, and scripts/build-app.sh to
build an ad-hoc signed, arm64-only Xenora.app and run its smoke check.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:43:08 +05:30
Ranveer Soni 9a9422c7da Merge pull request #260 from elforeign/task/215-stage-c
isa: eight SOP2 logical and shift forms through the semantic registry (#215 stage C)
2026-11-24 15:41:50 +05:30
elforeign da41b6420d Merge branch 'task/215-stage-d-oracle' into task/215-stage-d 2026-11-24 04:10:54 -06:00
elforeign 3f710928af validation: close four blind spots in the stage D cases (#215)
Review found cases that a broken implementation would still pass: an inline
or literal value that compares like its neighbour against both registers, an
extra write to the SCC-setting scratch SGPR s12, and rejections accepted at
any offset. Inline and literal cases now also compare a value with itself,
s12 is read back, and every rejection must happen at the SOPC word.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:10:00 -06:00
elforeign 2fdf01fbb3 ref, validation: evaluate the twelve SOPC integer compares in both interpreters (#215)
Both interpreters now run s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32}: SCC = S0 <rel>
S1, signed for opcodes 0-5 and unsigned for 6-11, with no SGPR written. The
reference keeps Op::CompareEqual for the two EQ opcodes (its public shape is
used by other crates' tests) and adds Op::ScalarCompare for the rest, reusing
the VOPC relation; the second interpreter orders signed operands by flipping
the sign bits, so the two do not share the comparison code.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:08:32 -06:00
elforeign de00cb2bfd Merge remote-tracking branch 'origin/main' into task/215-stage-c 2026-11-24 04:08:15 -06:00
elforeign d8f9669280 semantics: require exact XML number formats and a sane count width (#215)
Review follow-up: a shift count must be FMT_NUM_U32 and other sources
must have the format their signedness implies, so a float format no
longer passes; a negative shift_count_bits is a diagnostic instead of a
crash. The stage C rows cite the guide pages where the forms are listed,
and the scalar ALU page names which suite covers which forms.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:08:15 -06:00
elforeign 19b2e9b5d5 semantics: dispatch through a generated OP-indexed table (#215)
With 17 forms the generated match on the masked word cost about 0.4 ns
(4 %) more per decoded SOP2 instruction than main. The generator now
emits a fixed-bits test plus a static table indexed by the OP field,
both derived from the XML snapshot and checked to select exactly the
same words; decoding is back to main's speed (10.05 ns).

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:07:17 -06:00
Ranveer Soni bb6bc52c95 Merge pull request #258 from Swastickc/task/80-pe-mapping-limits
loader: bound total mapped PE image size before allocation (#80)
2026-11-24 15:37:11 +05:30
Ranveer Soni ba6bbb2e4a Merge pull request #259 from Swastickc/task/77-teb-startup-bounds
loader: validate startup stack and TEB layout before mapping (#77)
2026-11-24 15:36:51 +05:30
elforeign 705b074a08 validation: guide-derived expectations for the stage D scalar compares (#215)
SCC for s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32} is written from the RDNA 2 ISA
guide (12.4, 13.1.4, 5.3) before either interpreter implements the new forms,
with cases for both branch edges, unchanged SGPRs and rejected operands.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:05:59 -06:00
elforeign d3c1150854 changelog: stage C SOP2 forms through the registry (#215)
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:04:22 -06:00
elforeign a81d62ffe3 decoder: map the stage C SOP2 operations onto the reference in the consistency test (#215)
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:04:00 -06:00
Swastick Chowdhury bb1372cd70 loader: validate startup stack and TEB layout before mapping (#77)
Replace the saturating TEB address with checked arithmetic and reject a
stack below address zero, an overflowing TEB range, or a TEB overlapping
the stack before the image is parsed. Name the Win64 TEB field offsets
and add unit tests for layout validation and field placement.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:33:38 +05:30
elforeign 8d53d82981 Merge branch 'task/215-stage-c-oracle' into task/215-stage-c 2026-11-24 04:03:01 -06:00
elforeign ba2cfc2a00 validation: close two blind spots in the stage C cases (#215)
Review found that one register operand per inline constant hides some wrong
inline values (ANDN2 with s8 = 0x80000f0f cannot tell 16 from 0), and that the
odd-opcode check used a misaligned SGPR pair. Each inline now runs against a
word and its complement, and the 64-bit neighbours read aligned pairs.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:02:10 -06:00
elforeign b13ab327f2 ref, validation: evaluate the stage C SOP2 forms in both interpreters (#215)
The reference interpreter and the second, independent interpreter now run
s_andn2/orn2/nand/nor/xnor_b32, s_lshl/lshr_b32 and s_ashr_i32 per the RDNA 2
guide: shifts use only S1[4:0] and every form sets SCC = (D != 0). The two use
different arithmetic (host bit ops vs per-bit and power-of-two evaluation),
so they cannot share a mistake with each other or with the expectations.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 04:00:28 -06:00
Swastick Chowdhury e7cb8db14f loader: bound total mapped PE image size before allocation (#80)
Sum max(VirtualSize, SizeOfRawData) over all sections and reject images
above a 256 MiB loader budget with SectionMappingError(AllocationFailed)
before any host allocation. Adds pe_mapping_limits tests.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:29:34 +05:30
elforeign e7795d0e5a validation: guide-derived expectations for the stage C SOP2 forms (#215)
Expected D and SCC for s_andn2/orn2/nand/nor/xnor_b32, s_lshl/lshr_b32 and
s_ashr_i32 are written from the RDNA 2 ISA guide (12.1, 5.3) before either
interpreter implements them, so the implementation cannot shape the oracle.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:57:55 -06:00
Ranveer Soni 3ff9ddde24 Merge pull request #255 from Swastickc/task/82-memory-boundaries
loader: check guest memory accesses across region boundaries (#82)
2026-11-24 15:25:18 +05:30
elforeign ff191d89bd isa: declare eight more SOP2 logical and shift forms in the registry (#215 stage C, WIP)
Adds andn2, orn2, nand, nor, xnor, lshl, lshr and ashr as registry
primitives with a declared shift-count width that the generator applies
as a mask and checks against the XML's unsigned count operand. The forms
reach the decoder and translator through the generated dispatch with no
per-form Rust. The independent oracle side lands separately.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:55:00 -06:00
Ranveer Soni 4039be8ee2 Merge pull request #256 from elforeign/task/215-s1-operand-domains
test(validation): independent operand-domain verification for SOP2/VOPC (#215 stage E)
2026-11-24 15:24:48 +05:30
Ranveer Soni 898b79dc84 Merge pull request #253 from Swastickc/task/81-reloc-validation
loader: validate base relocation directory, blocks and targets (#81)
2026-11-24 15:24:29 +05:30
Ranveer Soni 30d20c8f33 Merge pull request #254 from Swastickc/task/79-clippy-as-chunks
loader: use as_chunks for PE section headers (Clippy fix, #79 follow-up)
2026-11-24 15:24:21 +05:30
Swastick Chowdhury 0687a8add6 loader: check guest memory accesses across region boundaries (#82)
Route reads, writes, instruction fetches and loader bypass writes through
one resolver. Accesses may span adjacent mapped regions when each grants
the required permission; the whole range is checked before any byte is
copied, so failed accesses change nothing; address wraparound returns
Overflow. Adds memory_validation tests.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:22:14 +05:30
elforeign 791b736b0e changelog: note the operand-domain verification harness (#215 stage E)
Contributors need to know the harness exists, what it covers and that
its expectations are spec-derived, not hardware results.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:51:06 -06:00
elforeign fcda9c09bd Merge remote-tracking branch 'origin/main' into task/215-s1-operand-domains
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:50:44 -06:00
elforeign ad5a6f9c53 validation: operand-domain harness for SOP2 and VOPC forms (part of #215, stage E)
The nine SOP2 forms and twelve VOPC integer compares had known answers
for a few chosen inputs only. This harness generates their operand
domains (boundary values, 64-bit carry and borrow chains observing both
words, aliased registers, every integer inline constant, literals, s105
and v255, partial and zero EXEC with VCC seeded to -1, VCCZ through
s_cbranch_vccz, 32 distinct lane inputs) and runs each case on the
reference interpreter and on native Metal against expectations written
out from the public RDNA 2 guide in oracle.rs, which imports no Xenora
crate. Rejections cover a missing literal word (as truncated) and
encodings outside Xenora's subset (two literal selectors, VCC/TTMP/M0/
EXEC destinations, float inline constants), at the expected offset.

4788 cases and 498 rejections. Failures are listed per family. The
Metal part compiles its 1777 distinct programs on four threads: 16 s
with a cold shader cache on an M5 Pro, against 47 s on one thread.

The oracle agrees with an independent guide-only table on 436 of 440
cases; the other 4 are s_subb_u32 with S1 = 0xffffffff and SCC set,
where the guide leaves the width of S1 + SCC open. The oracle reads it
at full width and keeps those cases in their own family.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:50:44 -06:00
Ranveer Soni f856671b6d Merge pull request #252 from elforeign/feat/semantic-registry
isa, decoder: declarative semantic registry with generated SOP2 dispatch (#215 stages A+B)
2026-11-24 15:14:41 +05:30
Swastick Chowdhury e1317322e1 loader: use as_chunks for PE section headers (#79 follow-up)
Rust 1.100 Clippy rejects chunks_exact with a constant size
(chunks_exact_to_as_chunks), which fails the pinned
cargo clippy -D warnings gate on main since #250. No behavior change.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:14:00 +05:30
Swastick Chowdhury 92fd955a8d loader: validate base relocation directory, blocks and targets (#81)
Read the relocation directory only when NumberOfRvaAndSizes covers it,
reject odd block sizes and trailing partial block headers, keep DIR64
targets inside SizeOfImage, and check the directory end offset. Adds
relocation_validation tests for positive, negative and zero rebasing and
each malformed case.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:13:12 +05:30
elforeign 0609012903 docs: bring the registry guide in line with the post-review rules (#215)
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:41:10 -06:00
elforeign dffa50cd9c semantics: run the generator unit tests in CI and fail clearly below Python 3.11 (#215)
Align the merged generator tests with the pinned documents and the
complete unsupported list, add tests for the rules added after review,
run them in the existing CI step next to the coverage tests, and give
the coverage script the same explicit Python 3.11 error as the
generator instead of a traceback.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:40:52 -06:00
elforeign b541dce0cc Merge branch 'feat/semantic-registry-s4' into feat/semantic-registry 2026-11-24 03:40:09 -06:00
elforeign 52ecece126 docs, tests: semantic registry contributor guide and generator unit tests (#215)
Contributors had no written path for adding a form through the registry,
and the generator's rejection rules had no direct tests: a disabled check
would only show up if the real registry happened to break it.

The new unit tests feed small in-memory registries and a hand-written
snapshot that each break one rule, check that the real registry passes,
that render is deterministic and independent of key order, and that the
CLI's validate, generate and --check modes exit as documented. Each of
44 deliberate generator mutations makes at least one test fail.

The guide covers the files, every field and its allowed values, what the
validator checks, what the generator does not do, the commands, and a
worked example on s_addc_u32.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:39:17 -06:00
elforeign 440856a997 semantics: pin cited documents and reject a boolean schema; reject duplicate generated rows in coverage (#215)
Follow-up to the independent review: a citation can no longer point at
another file, schema = true no longer passes as 1, the coverage reader
fails on a duplicated FORM_IDS row, and 'not yet' lowering is not
counted.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:38:49 -06:00
elforeign 1eeb614ea2 Merge remote-tracking branch 'origin/main' into feat/semantic-registry 2026-11-24 03:36:34 -06:00
elforeign afd936b20b semantics: close validation gaps found in review; check generated files in CI (#215)
The generator now rejects float widths, reserved variant names,
out-of-range pages and opcodes, Wave32 restrictions the decoder cannot
enforce yet, operand rules whose unsupported list differs from what the
decoder rejects, and undeclared or empty guide documents. The coverage
report reads decoder support from the compiled FORM_IDS table instead of
the registry, needs a decoding row before counting reference or Metal
evidence, and fails on unimplemented lowering. CI runs both --check
modes and the coverage unit tests so a stale generated file fails.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:36:18 -06:00
Ranveer Soni 6772205213 Merge pull request #251 from Swastickc/task/83-jit-capacity
loader: check JIT page size and capacity arithmetic (#83)
2026-11-24 15:04:40 +05:30
Ranveer Soni 4b5e2b690d Merge pull request #250 from Swastickc/task/79-pe-validation
loader: validate PE headers, section ranges and entry point (#79)
2026-11-24 15:04:31 +05:30
Ranveer Soni ee6c9ac067 fix(docs): synchronize generated status tables
Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 15:03:22 +05:30
elforeign 1680e6b19c docs: describe the semantic registry and link the coverage report (#215)
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:32:41 -06:00
elforeign 3eef0ecfa8 Merge remote-tracking branch 'origin/main' into feat/semantic-registry 2026-11-24 03:32:10 -06:00
Swastick Chowdhury 999de9f2df loader: validate PE headers, section ranges and entry point (#79)
Fix two parser panics found by the pe_parse fuzz target: a truncated
PE32+ optional header and unchecked RVA range arithmetic. Also require
the 112-byte fixed optional header, check section table and raw data
bounds, reject overlapping sections and require the entry point to lie in
an executable section. Adds pe_validation regression tests built from
original synthetic images.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:02:00 +05:30
elforeign e616583c3f audit: add the semantic coverage report (#215 stage F slice)
Counts identified, encoding-validated, declared, decoder, IR/MSL,
reference and Metal evidence per encoding family, reading evidence only
from docs/status.toml so registry requirements never count as results.
Unrecognized inputs fail instead of being skipped. --check never writes.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:31:57 -06:00
Swastick Chowdhury 025f9dfd21 loader: check JIT page size and capacity arithmetic (#83)
Reject a failed, zero or non-power-of-two page size, and use checked
arithmetic for page rounding, emitted instruction length and code-cache
capacity. Adds unit tests for each overflow and boundary case.

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 15:01:50 +05:30
Ranveer Soni d8c02270ee stuff 2026-11-24 15:01:17 +05:30
Ranveer Soni 08c4451e68 docs: add draw, blend and depth contract sections to the interface contracts 2026-11-24 15:01:17 +05:30
Ranveer Soni 2ab189ddbe docs: refresh the engineering progress page for the current state 2026-11-24 15:01:17 +05:30
Ranveer Soni fa94b56ba3 docs: refresh the documentation index for the current state 2026-11-24 15:01:17 +05:30
Ranveer Soni 385e7a0729 readme: refresh the closing statement with the current research focus 2026-11-24 15:01:17 +05:30
Ranveer Soni 819699e8a7 readme: refresh the build, test and verification sections 2026-11-24 15:01:17 +05:30
Ranveer Soni 4404e3f4bb readme: refresh texture support and current limitations for the current state 2026-11-24 15:01:17 +05:30
Ranveer Soni d35cea8eff readme: refresh the architecture section for the current graphics passes 2026-11-24 15:01:17 +05:30
Ranveer Soni 8a69f80aa0 readme: add blend pass, indexed draws and depth pass as verified graphics work 2026-11-24 15:01:17 +05:30
Ranveer Soni c21d9ba92a readme: update milestone table statuses for the current state 2026-11-24 15:01:17 +05:30
Ranveer Soni e06242f2e0 readme: refresh the header and project summary for the current state 2026-11-24 15:01:17 +05:30
elforeign c9e3394eb3 isa, decoder: generate SOP2 dispatch from the semantic registry (#215 stage A+B)
generate_semantics.py validates the registry against its closed
vocabulary and the pinned XML snapshot (opcode, family, SCC input and
output, operand widths and signed formats) and emits static Rust tables.
The decoder now selects SOP2 operations through the generated from_word
match, and ScalarAluOp's mnemonic, SCC read and evaluation come from the
registry through shared primitives instead of hand-written per-opcode
code. The nine SOP2 opcode entries leave generate_rdna2.py.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:27:07 -06:00
Ranveer Soni 72d2ceb967 Merge pull request #249 from elforeign/task/156-cpu-decode-fuzz
fuzz: bounded CPU decoder fuzz target
2026-11-24 14:56:13 +05:30
elforeign 358ddc5eba isa: pin the semantic registry schema and Rust vocabulary (#215 stage A)
Freeze the registry format and typed vocabulary first so the parallel
slices (verification harness, coverage report, docs) can build against
them. The nine SOP2 forms are declared as data; the generator, validation
and decoder wiring follow.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:22:05 -06:00
elforeign 09cf27186c fuzz: add bounded cpu_decode target for the static probe decoder
Issue #156 asks for a bounded, non-executing fuzz target for the CPU
decoder. No public single-instruction decode API exists, so the target
wraps up to 4096 fuzz bytes as the code section of a fixed, original
PE32+ header and runs the public read-only probe_pe_bytes twice with a
bounded ProbeConfig. It asserts identical reports, the 15-byte x86
instruction limit, and that each record lies in and matches the input.
A startup self-check (nop; ret must decode to two records) stops a run
whose synthetic header no longer reaches the decoder.

A 600 s campaign found one decoder defect (unlimited segment prefixes
give instructions over 15 bytes), reported on #74 and not fixed here.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:19:21 -06:00
Ranveer Soni 9ac1343e34 Merge pull request #248 from elforeign/task/193-blending
gpu: native blend pass with per-draw blend state and write masks (#193)
2026-11-24 14:41:20 +05:30
elforeign 078afd4591 ref: bound the blend reference extent and parse rounding flags strictly (#193)
The second independent review found that an extent such as [usize::MAX, 1]
passed the overflow check and then panicked in the allocation, and that any
flag character other than 'e' silently granted the native tolerance. The
reference now accepts 1..=4096 pixels, the native limit, and the parser
rejects unknown flags.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:09:23 -06:00
elforeign 4741409de1 Merge remote-tracking branch 'origin/main' into task/193-blending
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
#	crates/metal/src/compute.rs
#	crates/metal/src/lib.rs
#	crates/metal/src/render.rs
#	crates/ref/src/lib.rs
2026-11-24 03:06:27 -06:00
elforeign 6cbe976990 gpu: address independent review of the blend pass (#193)
The review found that the CPU blend reference multiplied an unchecked extent
before allocating, that only the second draw of each case varied its state,
and that the docs did not say Min/Max ignore the factors.

- The reference rejects empty or overflowing extents, with a unit test.
- New clean-room case first_draw_blended: a blended, masked first draw
  under a differently configured second draw (re-derived in a fresh
  session that reproduced the first 38 cases exactly).
- Doc and changelog wording now state the coverage scope precisely.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:06:03 -06:00
Ranveer Soni 857bec29e1 Merge pull request #247 from elforeign/task/192-indexed-draws
gpu: indexed draws with base vertex, native Metal and loader (#192)
2026-11-24 14:32:46 +05:30
elforeign 7b6c6fd92c Merge remote-tracking branch 'origin/main' into task/193-blending
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 03:01:19 -06:00
elforeign 28846561ab gpu: native blend pass with per-draw blend state and write mask (#193)
Blending and colour write masks had no native path or check. Add
NativeCompute::render_blend: flat triangles drawn in order into an RGBA8
target, each with its own write mask and either blending disabled or
separate RGB and alpha factors and operations (one pipeline per draw,
since both are pipeline state in Metal).

xenora-ref gains an exact blend reference that also reports which
channels need rounding. Expected images were derived independently in a
clean room from the public Metal blend equations. The tolerance was fixed
before measuring: exact channels must match, rounded channels may differ
by 1.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 03:01:09 -06:00
elforeign 817a95b419 loader: test a vertex-buffer offset and zero-count backend calls; split recording and execution errors in the changelog (#192)
The second independent review asked for coverage of a nonzero vertex-buffer
offset and proof that zero-count draws never reach the backend, and for the
changelog to say which errors recording raises and which execution raises.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:58:29 -06:00
elforeign 33c025a785 Merge remote-tracking branch 'origin/main' into task/192-indexed-draws
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 02:55:08 -06:00
elforeign c0cbc2f787 gpu: tighten the indexed-draw contract after independent review (#192)
The review found that a raw primitive-restart index could pass the native
range check with a negative base vertex, that the loader ignored instance
parameters and could wrap a guest address, and that coverage missed flat
multi-triangle draws, an unadjusted textured draw and 32-bit indices above
16 bits.

- Native and CPU reference reject the raw restart value whatever the base.
- The loader rejects index counts other than 0 or 3 first, more than one
  instance and a nonzero start instance, and checks guest address
  arithmetic through the last byte read.
- Three clean-room cases added (re-derived in a fresh session, which also
  reproduced the first 13); native error checks now name each reason, and
  the loader error test proves no rejected draw reaches the backend.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:54:55 -06:00
Ranveer Soni e8b0a380e9 Merge pull request #246 from elforeign/task/157-pe-parse-fuzz
fuzz: bounded PE parser fuzz target
2026-11-24 14:24:24 +05:30
elforeign df3b9674a3 Merge remote-tracking branch 'origin/main' into task/157-pe-parse-fuzz
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 02:51:15 -06:00
elforeign db50deb9f7 fuzz: add bounded PE parser fuzz target
Add a pe_parse cargo-fuzz target that feeds malformed bytes to
ParsedPe::parse and rva_to_file_offset and, only when the summed
section mapping size and SizeOfImage are at most 64 MiB, to the checked
load_into_memory mapping step. No guest code is executed.

Refs #157

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:51:05 -06:00
elforeign 76679a9c05 changelog: keep the Added list without blank lines
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:47:59 -06:00
elforeign 6785cb04e3 Merge remote-tracking branch 'origin/main' into task/192-indexed-draws
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 02:47:49 -06:00
elforeign 99c8331576 gpu: indexed draws with base vertex, native Metal and loader (#192)
Indexed draws had no contract: the loader had no index buffer command and
the Metal backend only drew non-indexed triangles. Add a bounded one:

- NativeCompute::render_indexed issues real drawIndexedPrimitives calls on
  a 16- or 32-bit index buffer with a start index and signed base vertex,
  optionally sampling a natively uploaded BC1 texture.
- The loader gains SetIndexBuffer (DXGI R16_UINT/R32_UINT only) and
  DrawIndexedInstanced, which fetches one triangle through the index
  buffer and base vertex and feeds the existing one-triangle backend.
- Both reject bad formats, offsets and counts, indices past the buffer and
  any index + base vertex outside the vertex buffer before drawing.
- xenora-ref gains an index-fetch reference over the depth rasteriser.

Expected images and fetch lists were derived independently (clean room)
from public D3D12, Metal and BC1 documentation.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:46:58 -06:00
Ranveer Soni 077a215d49 Merge pull request #243 from elforeign/task/138-threadgroup-sizing
metal: measure threadgroup sizing; keep the 64-thread default (#138)
2026-11-24 14:08:26 +05:30
Ranveer Soni 3c710b53ba Merge pull request #242 from atesahmet0/task/200-indirect-control
Verify indirect CALL and JMP target fetch, stack and retirement
2026-11-24 14:06:31 +05:30
Ranveer Soni 4886e9cd80 Merge pull request #241 from atesahmet0/task/86-precise-faults
Preserve precise guest fault state and retired instructions
2026-11-24 14:06:25 +05:30
elforeign 4dc10ae437 metal: check the requested group width directly; report all bench runs
The independent review noted that a 65-thread grid at width 1024 would also
pass if the width were clamped to the grid, so threads now also report
dispatch_threads_per_threadgroup. The changelog now gives all three benchmark
runs, including the slower first one.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:34:06 -06:00
elforeign 16debc8fdb Merge remote-tracking branch 'origin/main' into task/138-threadgroup-sizing
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 02:31:44 -06:00
elforeign ee8347a39f metal: explicit threadgroup widths, measured against the default (#138)
Expose a bounded way to dispatch at a chosen width so every legal
configuration can be checked for identical known answers, including grids
that do not divide evenly, and timed against the default policy. On an
Apple M5 Pro widths 64-256 tie (median 58.8 us GPU), 512 is 6% slower and
1024 about 2x, so the default of 64 stays. run() keeps its signature; the
sized path is a separate private helper.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:31:33 -06:00
Ranveer Soni 6689761db3 Merge pull request #240 from elforeign/task/191-depth-attachment
metal: depth attachment known-answer rendering (#191)
2026-11-24 14:00:29 +05:30
ates 7aa8166cf2 Verify indirect CALL and JMP target fetch, stack and retirement
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-24 11:30:08 +03:00
ates c107f3a43f Preserve precise guest fault state and retired instructions
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-24 11:30:08 +03:00
elforeign b041952437 Merge remote-tracking branch 'origin/main' into task/191-depth-attachment
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 02:29:02 -06:00
Ranveer Soni ae80d7fd8f Merge pull request #238 from elforeign/fix/vop3-interp-length
isa: VOP3 interpolation attribute fields never select a literal
2026-11-24 13:58:26 +05:30
Ranveer Soni d57e9c031c Merge pull request #239 from elforeign/feat/vopc-compare
shader: Wave32 VOPC integer compares with VCC/EXEC rules
2026-11-24 13:58:02 +05:30
elforeign 924d68afbc metal: take the BC1 upload type in depth passes, gate BC per case
An independent review found that DepthPass accepted a Bc1Subresource, whose
public fields let a caller pair a short slice with a larger pitch before
replaceRegion. Take the validated Bc1Upload instead. Supply the texture only
to the textured case so a device without BC support fails that case alone.
The CPU reference now rejects depth outside 0..=1 since it does not clip,
and checks the texture size with checked arithmetic.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:27:43 -06:00
elforeign 840eca0a29 metal: depth attachment known-answer rendering (#191)
Draw ordered triangles with an optional Depth32Float attachment, per-draw
compare function and write enable, and read back colour and stored depth,
so depth compare, clear, write enable and disabled depth can each be
checked against independently derived values. One draw samples an original
BC1 texture through the native BC1 path, so the BC upload is exercised by
rendering, not only by compute readback.

Also adds the missing changelog lines for PR #224 (BC7) and PR #231 (#172).

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:23:31 -06:00
elforeign 0749330868 shader: Wave32 VOPC integer compares with VCC/EXEC rules
Adds v_cmp_{lt,eq,le,gt,ne,ge}_{i32,u32}_e32 across the chain: opcodes
generated from the pinned AMD XML, one typed VectorCompare instruction
(relation + signedness, table-driven decode), the reference interpreter,
the independent semantic-review interpreter, typed IR and MSL.

Rules (RDNA 2 ISA guide 3.9, 2.1, 3.3; contract in
docs/shaders/vector-compare.md): VCC_LO[n] = EXEC_LO[n] & test(lane n),
always fully written, so empty EXEC gives 0 and reads no source; VCC_HI
becomes unknown; EXEC, SCC and VGPRs are unchanged. A lane-derived
VCC_LO may feed only s_cbranch_vccz, v_mov_b32 vN, vcc_lo and another
compare's SRC0, so EXEC never becomes data-dependent. A runtime
s_cbranch_vccz is wave-uniform: the skipped code may hold only integer
vector ALU instructions with initialized destinations, checked whether
or not it is taken, and lowers to selects at the join.

The Metal kernel makes no SIMD-group, threadgroup or barrier assumption:
each thread rebuilds its RDNA wave's mask by recomputing the 32 lanes'
operands from their input words, bounded by threads_per_grid. The
reference now runs lockstep Wave32 waves; absent lanes of a final
partial wave contribute 0.

Verified with an original LLVM-assembled fixture and 251 programs
(every form on 10 boundary values in both operand orders, partial and
empty EXEC, both runtime branch edges in one dispatch, mask chains,
32 pinned rejections) against exact integer definitions. Translator,
reference and second interpreter agree on CPU; all 252 programs match
on native Metal with validation; LLVM agrees on every encoding.
Breaking any implementation (signedness, EXEC masking, empty EXEC,
absent-lane bound, join polarity or uniformity) fails the tests.

Fixes #186

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:22:19 -06:00
elforeign 2ddd2a2485 isa: VOP3 interpolation attribute fields never select a literal
identify() treated SRC0 = 255 as the literal selector in every VOP3 form
with the LITERAL extension, so six interpolation forms (v_interp_p1_f32,
v_interp_p2_f32, v_interp_mov_f32 in VOP3, v_interp_p1ll_f16,
v_interp_p1lv_f16, v_interp_p2_f16) were read as 12 bytes. In these
forms SRC0 is not an operand selector: the RDNA 2 ISA guide, section
10.4.2, says SRC0 "is treated as a set of bit-fields" {attr_word,
attr_chan, attr}, and the XML gives its operand type as OPR_ATTR. LLVM
23.1.6 decodes all six as 8 bytes.

Fields typed OPR_ATTR are now skipped when looking for a literal. VGPR-
only sources are unchanged: LLVM still reads v_permlane16_b32 and
v_movrels_b32 with selector 255 as 12 bytes (invalid operand), and the
new test pins that too. The corpus check's six pinned mismatch rows
are gone: v_interp_mov_f32 now agrees fully and the other five are
operand_flagged (same form and length, LLVM flags the operand).

The new test fails on the old rule.

Fixes #235

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:20:01 -06:00
Ranveer Soni 0e7fa4aa93 Merge pull request #234 from elforeign/task/209-llvm-corpus
test(isa): independent LLVM corpus check of gfx1030 identification (#209)
2026-11-24 13:38:57 +05:30
Ranveer Soni 1ee557bdc4 Merge pull request #233 from atesahmet0/task/197-bswap
Implement 32-bit and 64-bit BSWAP in both CPU engines
2026-11-24 13:38:32 +05:30
elforeign fa4d4b9d71 Merge remote-tracking branch 'origin/main' into task/209-llvm-corpus 2026-11-24 02:06:03 -06:00
elforeign bf3cca0718 isa: independent LLVM corpus check of gfx1030 identification (#209)
Issue #209 asks for LLVM-generated original samples beyond the existing
oracle cases, with measured coverage and unresolved differences. The
corpus has 317 original instructions assembled by llvm-mc and 6,574 byte
probes built from every metadata form's identifying bits: one with zero
operands, one per extension selector its family can carry, and two with
random operand bits. llvm-objdump decodes each probe, giving LLVM's
instruction and the bytes its decoder consumed (llvm-mc --disassemble
re-encodes, which hides consumed length for MIMG NSA).

The test compares identify with every row and pins per-source class
counts, the 130 disagreeing rows and a digest of the random probes, so
any metadata change fails until reviewed. Disagreements are reported, not
fixed: 18 MIMG names LLVM does not know, 6 VOP3 interpolation forms whose
attribute field 255 is read as a literal, and 21 extension cases on
operand-less or SGPR-pair instructions.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:05:58 -06:00
Ranveer Soni a86100c00d Merge pull request #231 from elforeign/task/172-extension-word-negative
test(isa): gfx1030 extension-word negative tests (#172)
2026-11-24 13:33:40 +05:30
ates 044f036ea5 Implement 32-bit and 64-bit BSWAP in both CPU engines
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-24 10:57:26 +03:00
elforeign 79947ec998 Merge remote-tracking branch 'origin/main' into task/172-extension-word-negative 2026-11-24 01:55:01 -06:00
Ranveer Soni 17fe880bdc Merge pull request #230 from elforeign/feat/sop2-signed-add-sub
shader: add s_add_i32 and s_sub_i32 with signed-overflow SCC (follow-up to #185)
2026-11-24 13:24:39 +05:30
elforeign e93e4e1e2a isa: negative tests for gfx1030 extension words (#172)
Issue #172 asks for independent truncated and invalid literal, SDWA, DPP
and NSA cases, and for length recognition to be kept apart from semantic
validity. Every case starts from bytes llvm-mc assembled from an original
instruction; expected results come from LLVM's disassembly of the cut or
altered bytes, not from the decoder.

Covers 62 proper prefixes of 18 literal/SDWA/DPP/NSA instructions with the
exact length each needs, 7 extension selectors on forms that do not allow
them, two reserved control values that keep their trailer length, and 8
back-to-back pairs whose second instruction starts after the trailer. An
ignored test re-checks every source encoding with LLVM.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:54:22 -06:00
elforeign 425327a0f2 shader: add s_add_i32 and s_sub_i32 with signed-overflow SCC
#185 left both forms unsupported because the pinned XML says only
"carry-out" for them. The AMD RDNA 2 ISA reference guide (GPUOpen,
section 12.1 SOP2 Instructions, p. 101-102, and section 5.3 Scalar
Condition Code, p. 33) defines SCC for both as signed overflow:
add overflows when the operands share a sign that the result lacks;
subtract when the operands' signs differ and the result's sign differs
from S0's. The guide also confirms the unsigned rules used in #185.

Adds both forms to the generated opcodes, the decoder, the reference
(exact signed result must fit in i32), the independent interpreter (the
guide's sign-bit rule over its ripple adder) and the translator, plus
400 boundary programs, eight hand-worked overflow and no-overflow cases
(-1 + 1 and 0 - 1 carry or borrow but do not overflow) and two signed
overflows in the scalar ALU fixture. Inverting the overflow rule in any
one implementation fails three tests. s_min_i32 and the other SOP2
forms stay unsupported.

Refs #185

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:48:52 -06:00
Ranveer Soni 1212280ab8 Merge pull request #224 from elforeign/task/171-bc7-decoder
feat(texture): BC7 block decoder, all eight modes, with independent vectors (#171)
2026-11-24 13:13:55 +05:30
Ranveer Soni c6665ebfb4 Merge pull request #229 from elforeign/feat/sop2-scalar-alu
shader: SOP2 scalar add, subtract and bitwise forms with SCC (fixes #185)
2026-11-24 13:13:32 +05:30
elforeign 96e2baeb75 Merge remote-tracking branch 'origin/main' into feat/sop2-scalar-alu
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 01:40:26 -06:00
Ranveer Soni b9be341dfc Merge pull request #227 from elforeign/feat/test-inventory
audit: compare Cargo test inventories between two commits
2026-11-24 13:09:55 +05:30
elforeign b2391b4de4 Merge remote-tracking branch 'origin/main' into feat/sop2-scalar-alu
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:39:50 -06:00
Ranveer Soni ecc109a7e2 Merge pull request #225 from elforeign/ci/pr-template-check
ci: require pull requests to follow the PR template
2026-11-24 13:09:07 +05:30
Ranveer Soni 67e6565fc2 Merge branch 'main' into ci/pr-template-check 2026-11-24 13:08:58 +05:30
elforeign 994efd38f9 shader: decode and execute SOP2 scalar add, subtract and bitwise forms
Adds s_add_u32, s_sub_u32, s_addc_u32, s_subb_u32, s_and_b32, s_or_b32
and s_xor_b32 across the chain: generated opcodes from the pinned AMD
XML, a typed ScalarAlu instruction, decoding, the reference interpreter,
the independent semantic-review interpreter and the translator, which
resolves scalar state and SCC as it already does for s_mov/s_cmp.
v_mov_b32_e32 may now read a normal SGPR, so results reach vector code
as constants.

SCC: the XML states carry-out for additions, carry-in for ADDC/SUBB and
nonzero results for bitwise forms. For subtraction it says carry-out
without fixing the polarity; LLVM's lowering of usubo and of 64-bit
subtraction to s_sub_u32/s_subb_u32 requires SCC to be the borrow.
s_add_i32/s_sub_i32 stay unsupported: no pinned source settles whether
their SCC is the carry or signed overflow.

Verified with an original LLVM-assembled fixture and 1,400 boundary
programs (every form, 10x10 operands, SCC clear and set) against exact
integer definitions; translator, reference (exact integers) and
independent interpreter (bit-serial ripple adder) all agree, and all
1,401 programs match on native Metal with validation. LLVM agrees on
every encoding. Breaking any one implementation fails the tests.

Fixes #185
Independent review fixes: both interpreters now require a known SGPR
for v_mov_b32 from an SGPR even in an inactive lane, as translation
does; alias, literal and inline cases also assert the translated result
and run on Metal; rejections are pinned to the SOP2 word's offset; GPU
status is recorded as local evidence with acceptance pending.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:38:54 -06:00
Ranveer Soni aac0f31b93 Merge pull request #226 from elforeign/docs/readme-contributors
docs: add contributors section to README
2026-11-24 13:08:35 +05:30
elforeign ef0e472d5d docs: add contributors section to README
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:37:56 -06:00
elforeign 1784836639 audit: compare Cargo test inventories between two commits
Testing the old #166 and #165 heads silently ran without 12 BC texture
tests that main already had, because those heads predated the merge
that added them; nothing flagged the smaller inventory.

scripts/audit/test_inventory.py lists every test (and the ignored set)
of a base and a candidate commit, each in a temporary detached worktree
it always removes, and reports removed, added, newly ignored and newly
un-ignored tests keyed by package, target and name. Unexplained losses
exit 1; an --allow file with a reason per key explains intended ones.

951189c -> 5450612: removed 12 (all xenora-texture bc_formats), exit 1.
0cac6c4 -> 0cac6c4: 219 tests each side, no change, exit 0.

Fixes #208

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:37:54 -06:00
Ranveer Soni 68fc4e25dc Merge branch 'main' into task/171-bc7-decoder 2026-11-24 13:07:25 +05:30
Ranveer Soni cdaff0a391 Merge pull request #223 from elforeign/task/169-metal-bc4-bc5
feat(metal): native BC4 and BC5 UNORM/SNORM upload and readback (#169)
2026-11-24 13:06:51 +05:30
Ranveer Soni 184149561a Merge pull request #222 from elforeign/docs/plain-reply-claims
docs: claim by plain reply, one-week stale rule
2026-11-24 13:06:34 +05:30
Ranveer Soni e83475be17 Merge pull request #216 from elforeign/feat/gpu-compatibility-expansion
isa: fix isolated-branch inspection and verified form count (follow-up to #166)
2026-11-24 13:06:13 +05:30
elforeign fa55066699 ci: fail pull requests whose description skips the PR template
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:35:54 -06:00
elforeign f25060e891 changelog: restore the gfx1030 metadata and shader inspection entries
The upstream merge of main into this branch (01deb3f) resolved the
CHANGELOG conflict by dropping this PR's three entries;
documented_form_counts_match_the_generated_table caught it.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:35:27 -06:00
elforeign 9318e68840 Merge remote-tracking branch 'origin/main' into feat/gpu-compatibility-expansion
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:34:37 -06:00
elforeign abd6698a66 Merge remote-tracking branch 'origin/main' into task/171-bc7-decoder 2026-11-24 01:32:50 -06:00
elforeign 5f8867bd30 Merge remote-tracking branch 'origin/main' into task/169-metal-bc4-bc5 2026-11-24 01:32:50 -06:00
Ranveer Soni 5ca90bfac0 Merge pull request #221 from atesahmet0/task/177-probe-report-consistency
Test probe report consistency across JSON, Markdown, and CSV
2026-11-24 12:59:38 +05:30
elforeign 7cc35ffd41 Merge remote-tracking branch 'origin/main' into task/169-metal-bc4-bc5
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 01:28:23 -06:00
elforeign 57f10c1d7c Merge remote-tracking branch 'origin/main' into task/171-bc7-decoder
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
#	crates/texture/src/lib.rs
2026-11-24 01:26:50 -06:00
elforeign 76620e274b texture: iterate texels directly in the BC7 tests
Strict Clippy (needless_range_loop) rejects indexing the output by the
loop counter; the assertions are unchanged.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:26:34 -06:00
elforeign 240302fabe texture: add a BC7 block decoder from the Khronos BPTC text (#171)
Issue #171 asks for bounded BC7 decoding with independent vectors for
partitions, endpoint precision and indices. All eight modes are decoded:
the partition and anchor tables are extracted mechanically from Khronos
Data Format Specification 1.3 section 20.1, and blocks with a zero low
byte decode to zero as that section requires.

Hand-derived tests cover each mode's distinctive field (P-bits, shared
P-bits, anchors, rotation, index selection, the section's own mode 2
bit-position example), and 430 known-answer vectors come from a separate
clean-room reference decoder. CPU only; no Metal BC7 path is claimed.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:25:45 -06:00
Ranveer Soni 01deb3f8a8 Merge branch 'main' into feat/gpu-compatibility-expansion 2026-11-24 12:55:06 +05:30
Ranveer Soni e6b9a27242 Merge pull request #218 from elforeign/task/168-bc23-audit
test(metal): BC2/BC3 edge blocks, invalid payloads and capability reporting (follow-up to #214)
2026-11-24 12:54:35 +05:30
elforeign 8fdb569052 docs: claim by plain reply, one-week stale rule
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:23:57 -06:00
Ranveer Soni e79bd1ccaf Merge pull request #220 from elforeign/task/170-bc6h-subset
feat(texture): bounded BC6H subset decoder (single-subset modes) (#170)
2026-11-24 12:51:55 +05:30
Ranveer Soni 066bc3fc83 Merge pull request #217 from elforeign/feat/agent-task-queue
agent queue: command-only triggers, durable claim replay and review fixes (follow-up to #165)
2026-11-24 12:47:00 +05:30
ates a533d8107e Test cross-format probe reports against fixture counts and offsets
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-24 10:16:45 +03:00
elforeign 3109b620fd texture: decode the single-subset BC6H modes
#170 asks for a documented, bounded BC6H subset with explicit rejection
of what is not implemented. This adds a CPU decoder for the four
single-subset modes (Khronos 3, 7, 11 and 15; Microsoft 11 to 14) in
signed and unsigned form, written from the Khronos Data Format 1.3 text
(Tables 121 and 122, unquantization and final unquantization). Reserved
modes decode to zero as the specification requires; the ten two-subset
modes return Bc6hError::UnsupportedMode, and BC6H_SUPPORTED_MODES lists
coverage by mode.

Tests use hand-derived values (saturation to 65504 and -65504, the
11-bit transform wrap, both reversed-bit fields, signed -32768 to
negative infinity) and 128 known-answer vectors from a separate
clean-room reference decoder, 16 per supported and reserved mode.
Flipping the reversed bit order, dropping the wrap mask, using 31/64
for signed data, a 4-bit anchor, accepting mode 0 or not zeroing
reserved modes each fails the tests.

Refs #170

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:16:24 -06:00
elforeign 878f554dcd Merge task/168-bc23-audit into task/169-metal-bc4-bc5
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
#	crates/metal/tests/native/texture_bc_alpha.rs
2026-11-24 01:12:31 -06:00
elforeign 46e2d36064 metal: compare non-interpolated BC4/BC5 codes exactly
The full-texel check applied the two-code tolerance to every channel, so
an endpoint or six-value fixed code outside the anchors could be off by
two and still pass. Each texel's tolerance now comes from its own index:
zero for stored and fixed codes and constant channels, two only for
interpolated codes. A readback kernel that lowers near-maximum red by two
now fails the BC4 and BC5 UNORM tests.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:12:20 -06:00
elforeign d94121bbb0 metal: compare non-interpolated BC2/BC3 codes exactly
An independent review of the #214 tests found that the full-texel check
applied the two-code interpolation tolerance to every channel, so an
endpoint, a BC2 alpha nibble or BC3's fixed 0 or 255 outside the anchors
could be off by two and still pass. The tolerance now comes from each
texel's own indices: zero for stored and fixed codes, two only for
interpolated ones. A readback kernel that lowers near-opaque alpha by two
now fails all three tests. The 1.14-code bound is stated as 8/7.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:11:43 -06:00
elforeign ef4fbba797 Merge upstream main into task/169-metal-bc4-bc5
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:08:59 -06:00
elforeign 97ea2541bb metal: cover BC2/BC3 edge blocks and report missing BC support apart
The section 12 audit of #214 found three gaps: no level narrower than a
block row (Metal's zero-stride single-row upload) or of 1x1, no checks
for zero extents or oversized and block-count-mismatched payloads, and a
missing BC capability surfaced the same way as an implementation fault.

Adds a 5x3 and 1x1 GPU test with hand-derived anchors, the extra upload
rejections, and MetalError::is_capability_unavailable; the GPU tests now
print CAPABILITY UNAVAILABLE or IMPLEMENTATION FAILURE. Rounding the
texture to whole blocks, accepting oversized payloads, or a device
without BC support each makes the tests fail with the matching message.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:08:34 -06:00
elforeign f1ec653b91 Merge remote-tracking branch 'origin/main' into feat/agent-task-queue
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:06:04 -06:00
elforeign b1ab08c09d agent queue: apply claim checks when /reassign creates a claim
/reassign turned a ready task into a claim without the dependency and
file-overlap checks /claim applies, so a maintainer reassignment could
grant two overlapping claims. Run the same checks for the new holder.

Refs #211

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:05:47 -06:00
elforeign 6b479a6617 agent queue: fix review findings in replies, verification and issue forms
From independent review of the queue follow-up:
- Bot replies echoed user text (/blocked reasons, /reassign logins,
  file patterns) verbatim. Markers count when the bot posts them, so a
  reason containing an approval or done marker became a bot marker and
  could approve an acceptance command or hide another user's claim.
  Echoed text now has angle brackets and backticks escaped.
- /verified accepted a 7-character prefix and ignored extra arguments;
  a commit with the same short prefix is cheap to make. Require exactly
  one full 40-character SHA, with one parser shared by decide and the
  check.
- After a verification, the job looked up the check run by the pull
  request head SHA, but pull_request_target runs carry the base branch
  SHA, so it found nothing and || true hid it. The verify job now
  evaluates the same advisory check itself and no longer needs
  actions: write.
- The issue form renders Files inside a ```text fence and the parser
  took "text" as a path, so any two form-created tasks overlapped.
  Fence lines are skipped.
- A command still unanswered after lease_hours now gets a "Not decided"
  reply (window 2 x lease_hours) instead of being dropped silently.

Each fix has a test shown to fail with the fix reverted.

Refs #210, #211

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:05:28 -06:00
elforeign 7a10d7eac8 metal: cover BC4/BC5 edge blocks and invalid payloads
Section 12's audit asks for levels that are not whole blocks and for
rejected payloads. Adds a 5x3 (single block row, zero Metal stride) and
1x1 GPU test over BC4/BC5 UNORM and SNORM with hand-derived anchors, the
zero-extent and wrong-length upload rejections, and routes the GPU reads
through the shared capability-aware unwrap. Rounding the texture to whole
blocks, accepting oversized payloads, or a device without BC support each
makes the tests fail with the matching message.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:03:48 -06:00
elforeign 0e51ddda76 Merge test/metal-bc2-bc3 into the BC4/BC5 branch
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 01:02:47 -06:00
elforeign b5a462fb54 Merge remote-tracking branch 'origin/main' into feat/gpu-compatibility-expansion
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:02:17 -06:00
elforeign 09e0bea55d shaders, isa: tighten inspection wording and review-found test gaps
From independent review:
- The summary said "not executable" for instructions that merely have
  no semantic decoding; a decoded program can still fail compilation.
  Say "without semantic decoding".
- When identification stops early, a branch target past the identified
  prefix was reported invalid although its boundaries are unknown;
  report it as unverified.
- The VOP3 and VOP3P literal probes used 1.0, which LLVM encodes as an
  inline constant (8 bytes), so neither exercised a literal. Use
  0x3f800001 and 0x3c01 and assert the 12-byte encoding and trailer.
- The coverage JSON test now also checks the document's shape.

Refs #183, #184

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:01:38 -06:00
elforeign 1260e07ba1 metal: cover BC2/BC3 edge blocks and report missing BC support apart
The section 12 audit of #214 found three gaps: no level narrower than a
block row (Metal's zero-stride single-row upload) or of 1x1, no checks
for zero extents or oversized and block-count-mismatched payloads, and a
missing BC capability surfaced the same way as an implementation fault.

Adds a 5x3 and 1x1 GPU test with hand-derived anchors, the extra upload
rejections, and MetalError::is_capability_unavailable; the GPU tests now
print CAPABILITY UNAVAILABLE or IMPLEMENTATION FAILURE. Rounding the
texture to whole blocks, accepting oversized payloads, or a device
without BC support each makes the tests fail with the matching message.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:01:26 -06:00
elforeign e70780f30a Merge remote-tracking branch 'origin/main' into feat/agent-task-queue
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 01:00:40 -06:00
elforeign ef481368d6 Merge remote-tracking branch 'origin/main' into feat/gpu-compatibility-expansion
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 01:00:40 -06:00
Ranveer Soni 0cac6c4fcf Merge pull request #214 from elforeign/test/metal-bc2-bc3
test(metal): BC2/BC3 upload and sampling conformance (#168)
2026-11-24 12:30:21 +05:30
elforeign 3a598a83e1 shaders: assert add.bin inspects as 7 semantic instructions
Refs #183

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:59:45 -06:00
Ranveer Soni b69d4b97c6 Merge pull request #166 from elforeign/feat/gpu-compatibility-expansion
isa: complete gfx1030 instruction metadata and identification
2026-11-24 12:26:27 +05:30
Ranveer Soni 97598903e2 Merge branch 'main' into feat/gpu-compatibility-expansion 2026-11-24 12:26:13 +05:30
elforeign 9fda5aab18 agent queue: re-run the check only after an accepted verification
The verify job re-ran the pull request check after any /verified
comment, including refused ones: the author's own, a non-verifier's, a
stale or unknown head or a malformed SHA. decide now marks only an
accepted verification of the current head, and the job re-runs the check
only when should-rerun confirms it. A test checks that what re-runs the
check is exactly what the check counts.

Replay decides a comment listed twice only once. Tests cover duplicate
and out-of-order listings, and every arrival order of a five-claim burst
grants exactly one of two overlapping claims.

Fixes #210, fixes #211

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:56:00 -06:00
Ranveer Soni af68f7da74 Merge pull request #165 from elforeign/feat/agent-task-queue
coordination: agent task queue for cpu, gpu, runtime, shared and qa work
2026-11-24 12:25:45 +05:30
Ranveer Soni dcf723e49d Merge branch 'main' into feat/agent-task-queue 2026-11-24 12:25:28 +05:30
elforeign 6d7523f5d1 Merge upstream main into test/metal-bc2-bc3
Resolves the CHANGELOG.md conflict with the claim-rules entry; both
entries are kept.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:55:23 -06:00
elforeign cf2d0cfb0b isa, shaders: test that coverage totals and documented counts match FORMS
At 5450612 the generated table held 1,460 forms while the docs and PR
said 1,465; 1493dcf added the five literal-only forms the LLVM oracle
found, so the table, xenora shaders coverage (text and JSON) and docs
now agree on 1,465 across 21 families. Nothing checked that they stay
in step. Test the JSON and text totals and per-family sum against
FORMS and SEMANTIC_FORMS, and the counts stated in docs/research/rdna2.md
and CHANGELOG.md against FORMS.len().

The branch inspection fix for #183 is the previous commit 9640269.

Fixes #183, fixes #184

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:54:07 -06:00
elforeign 585edd313f metal: upload and read BC4 and BC5 blocks natively
BC4 and BC5 had CPU decoders (#167) but no native Metal path, so nothing
showed that single- and dual-channel blocks reach the GPU and decode as
the specifications describe, signed formats included. This adds a pitched
BcChannelUpload (8-byte BC4 or 16-byte BC5 blocks, sharing the pitch
rules) and NativeCompute::read_bc_channel_upload, which places the blocks
in BC4_R/BC5_RG UNORM or SNORM textures behind the BC capability check.
Signed texels are read back as channel * 127 in two's-complement bytes.

The GPU tests cover six- and eight-value interpolation, equal and extreme
endpoints (stored -128 reads as -1.0, as specified), red-green order,
padded row and slice pitches, two layers and two mips: 232 texels against
the CPU decoders and hand-derived anchors. On an Apple M5 Pro interpolated
codes lie within 1.71 codes of the exact values and two codes of the
truncating CPU reference, which set the tolerances. Uploading SNORM as
UNORM, BC5 as BC4, scaling signed readback by 128 or swapping red and
green each fails the tests.

Refs #169

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:53:30 -06:00
elforeign 69812d97c0 Merge remote-tracking branch 'origin/main' into feat/gpu-compatibility-expansion
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 00:52:10 -06:00
Ranveer Soni e86eedf583 Merge pull request #213 from elforeign/docs/claim-before-work
docs: require claiming an issue before starting work
2026-11-24 12:20:55 +05:30
elforeign 59ee786a12 metal: upload and read BC2 and BC3 blocks natively
BC2 and BC3 had CPU decoders (#167) but no native Metal path, so nothing
showed that the original 16-byte blocks reach the GPU and decode as the
specifications describe. This adds a pitched BcAlphaUpload with the BC1
upload's validation (shared, now measured in 16-byte blocks) and
NativeCompute::read_bc_alpha_upload, which places the blocks in BC2_RGBA
or BC3_RGBA textures behind the existing BC capability check.

The GPU tests cover explicit 4-bit alpha, six- and eight-value
interpolated alpha (equal endpoints included), descending, ascending and
equal colour endpoints, padded row and slice pitches, two layers and two
mips. Texels are compared with the CPU decoders and hand-derived anchors.
On an Apple M5 Pro interpolated values lie within 1.14 codes of the exact
values, two codes at most from the truncating CPU reference, which sets
the tolerance. Uploading BC3 as BC2, BC2 as BC1, or ignoring the row
pitch each fails the tests.

Refs #168

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:49:17 -06:00
elforeign 5df1f9146f docs: require claiming an issue before starting work
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:48:25 -06:00
elforeign e37c8566c6 agent queue: start runs only for commands and replay cancelled claims
Every pull request comment started the verify job, which gathered state
and re-ran the pull request check, so ordinary review discussion re-ran
verification. Gate the verify job on comments that start with /verified
and the claim job on comments that start with /.

Claim runs share one concurrency group with cancel-in-progress: false.
GitHub keeps one waiting run per group and cancels it when a newer run
queues, so with the run deciding only its own comment, a /claim posted
while another claim was being decided could be dropped without a reply.
Each run now replays every command of the last lease_hours that has no
bot reply, oldest first, updating labels in memory between commands; the
hourly audit does the same, so a cancelled run's command is answered by
the run that replaced it at the latest within the hour. Replies carry a
done marker that counts only from the Actions bot.

The pull request check is advisory until a live smoke test and the
migration of existing issues: problems are a warning and the job passes.

Tests model the concurrency group (the old event-only design loses the
cancelled claim; replay answers all four commands), in-order overlap
decisions, bot-only markers and the workflow triggers.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:46:21 -06:00
Ranveer Soni 48e42d6d4b Merge pull request #182 from atesahmet0/fix/75-static-probe-c7
Fix C7 instruction boundaries and trusted fixture probe reporting
2026-11-24 12:12:44 +05:30
elforeign 964026901f shaders: decode inspected instructions at their stream offset
xenora shaders inspect passed each identified instruction to decode() on
its own. decode() checks that every branch target lands on an instruction
in the stream it was given, and a lone branch has no other instruction to
land on, so every supported s_branch and s_cbranch_* was reported as
"unsupported operands" (3 of 15 rows in bitwise-branch.bin).

Add decode_at(), which decodes one instruction at its real stream offset
without the stream-wide target check, and DecodedInstruction::branch_target().
inspect now identifies the whole stream first and checks each branch
target against those boundaries, reporting a bad target separately.
decode() is rebuilt on decode_at() with unchanged behaviour.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:40:55 -06:00
elforeign 98bbe57471 Merge remote-tracking branch 'origin/main' into feat/agent-task-queue
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 00:38:58 -06:00
elforeign 5baa630ff0 Merge remote-tracking branch 'origin/main' into feat/gpu-compatibility-expansion
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 00:38:51 -06:00
Ranveer Soni 951189c61b Merge pull request #167 from elforeign/feat/texture-bc-formats
texture: BC2, BC3, BC4 and BC5 CPU block decoders
2026-11-24 11:58:17 +05:30
elforeign 1493dcf83b isa: check identification against LLVM and add literal-only forms
The extension-word length rules were written by hand because the XML
gives none, so they needed an outside oracle. An LLVM test now compares
names and lengths for one instruction per family and extension word.
It found five instructions the XML lists only under a literal encoding,
which the first table omitted; they are now base forms that always carry
a literal.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:20:26 -06:00
elforeign 54506125d4 Merge remote-tracking branch 'origin/main' into feat/gpu-compatibility-expansion
# Conflicts:
#	CHANGELOG.md
2026-11-24 00:11:41 -06:00
elforeign 7c89ed62a2 changelog: record BC2-BC5 CPU block decoders
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:11:35 -06:00
elforeign b9b0a40101 Merge remote-tracking branch 'origin/main' into feat/agent-task-queue
# Conflicts:
#	CHANGELOG.md
2026-11-24 00:11:26 -06:00
elforeign f19d57967d Merge remote-tracking branch 'origin/main' into feat/texture-bc-formats 2026-11-24 00:11:08 -06:00
elforeign 62c933051b isa: generate complete gfx1030 instruction metadata and identification
The decoder knew 25 hand-matched forms, so any other instruction stopped
decoding with no record of what it was or how long it was. A two-stage
generator now reduces AMD's public RDNA 2 XML to all 1,460 base forms,
with a committed snapshot so CI can check the generated table offline.
identify() finds any form's exact length, including literal, SDWA, DPP
and NSA words, and the shaders CLI reports discovered against executable
forms so metadata coverage is never read as GPU support.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:11:00 -06:00
elforeign e35df04069 Expand the agent task queue to cpu/gpu/runtime/shared/qa with deterministic checks
The queue now has three engineering tracks plus shared and qa work. Queue
rules move from shell/awk in workflows into a standard-library Python package
so they are testable offline: claim decisions (dependencies, cycles, file
overlap, area permission), leases renewed only by the holder, reassign and
release, acceptance-command approval by hash, pull request ownership/overlap/
stale/verification checks and a machine-readable summary. Workflows apply the
decisions with minimal permissions, never put user text in run blocks and
never check out pull request code. The sync script fetches the real upstream
so interface changes during work are reported.

Not yet run on GitHub.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:09:38 -06:00
elforeign ef1a94ce71 texture: add BC2, BC3, BC4 and BC5 block decoders
Adds spec-derived CPU decoders (UNORM and SNORM for BC4/BC5) with
truncating integer interpolation and hand-computed tests, so later
texture work has verified references for these formats.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:01:14 -06:00
elforeign a89f9d8d06 coordination: add GitHub issue task queue for parallel agents
CPU and GPU work proceed in parallel, largely through coding agents.
Tasks posted as issues with owned file lists and an acceptance command
can be claimed through a serialised workflow, so work is picked up
without relaying prompts by hand and two claims never edit one file.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-23 23:58:25 -06:00
248 changed files with 59398 additions and 682 deletions

No files matched your search

+67
View File
@@ -0,0 +1,67 @@
name: Agent task
description: A self-contained work item that a contributor or coding agent can claim with /claim.
title: "task: "
labels: [agent:ready]
body:
- type: dropdown
id: area
attributes:
label: Area
description: "cpu: translation, DBT, PE loading, guest startup, guest memory. gpu: RDNA2, shaders, Metal. runtime: Win32, CRT, C++ runtime, import generation, OS services, platform abstractions. shared: cross-subsystem interfaces. qa: verification, regression, security review."
options:
- cpu
- gpu
- runtime
- shared
- qa
validations:
required: true
- type: dropdown
id: priority
attributes:
label: Priority
options:
- critical
- high
- medium
- low
validations:
required: true
- type: input
id: interface
attributes:
label: Interface
description: For shared tasks, the interface name and the version or upstream commit it targets. Leave empty otherwise.
- type: textarea
id: goal
attributes:
label: Goal
description: What must be true when the task is finished, in one or two sentences.
validations:
required: true
- type: textarea
id: files
attributes:
label: Files
description: Paths the task may edit, one per line: exact paths, directories ending in "/", or globs with * and **. Two claimed tasks never overlap.
render: text
validations:
required: true
- type: textarea
id: acceptance
attributes:
label: Acceptance command
description: The exact command whose success proves the task is done. It must fail before the change. It is never run automatically; a maintainer must approve it with /approve-acceptance.
render: sh
validations:
required: true
- type: input
id: depends
attributes:
label: Depends on
description: Issue numbers that must be closed first, for example "#12, #15". Leave empty when none.
- type: textarea
id: context
attributes:
label: Context
description: Specification sections, interface notes and known limits. Public sources only.
+4 -1
View File
@@ -1,6 +1,8 @@
## Summary
<!-- What changes, and why? Link an issue if relevant. -->
<!-- What changes, and why? -->
Closes #<!-- the issue you claimed -->
## Implementation and evidence
@@ -23,6 +25,7 @@
## Checklist
- [ ] I claimed the linked issue with a reply before starting, and nobody else held a live claim on it.
- [ ] I reviewed the changes and disclosed material AI assistance below, if applicable.
- [ ] The change preserves native ARM64 and Metal-first requirements.
- [ ] I added relevant tests or explained why they are not applicable.
+9
View File
@@ -0,0 +1,9 @@
{
"lease_hours": 168,
"upstream": "ranveersoni98/Xenora",
"maintainers": ["ranveersoni98"],
"contributors": {
"ranveersoni98": ["cpu", "shared", "qa"],
"elforeign": ["gpu", "shared", "qa"]
}
}
+89
View File
@@ -0,0 +1,89 @@
name: Agent task claims
# Applies queue commands (/claim, /release, /reassign, /progress, /blocked,
# /unblock, /approve-acceptance) and audits the queue hourly. Comment and issue
# text is only parsed as data by scripts/agent_queue; it is never executed and
# never interpolated into a shell. Not yet run on GitHub.
#
# Both jobs share one concurrency group, so decisions never race. GitHub keeps
# at most one pending run per group and cancels the older pending run when a
# newer one queues, so a run does not decide only its own comment: `replay`
# decides every command of the last lease_hours that has no bot reply yet,
# oldest first. The surviving run, or at the latest the hourly audit, answers
# the commands of cancelled runs. Comments that do not start with `/` start no run.
on:
issue_comment:
types: [created]
schedule:
- cron: "17 * * * *"
workflow_dispatch:
permissions: {}
jobs:
command:
if: github.event_name == 'issue_comment' && !github.event.issue.pull_request && startsWith(github.event.comment.body, '/')
runs-on: ubuntu-24.04-arm
permissions:
contents: read
issues: write
# One global group: claims are decided one at a time so file-overlap checks cannot race.
concurrency:
group: agent-queue
cancel-in-progress: false
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Decide and apply
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
PYTHONPATH: scripts
run: |
set -eu
python3 -m agent_queue gather --repo "$GH_REPO" --no-prs --recent-commands > "$RUNNER_TEMP/state.json"
python3 -m agent_queue replay --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/actions.json"
python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/actions.json"
audit:
if: github.event_name != 'issue_comment'
runs-on: ubuntu-24.04-arm
permissions:
contents: read
issues: write
pull-requests: read
concurrency:
group: agent-queue
cancel-in-progress: false
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Decide commands whose runs were cancelled
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
PYTHONPATH: scripts
run: |
set -eu
python3 -m agent_queue gather --repo "$GH_REPO" --no-prs --recent-commands > "$RUNNER_TEMP/commands.json"
python3 -m agent_queue replay --state "$RUNNER_TEMP/commands.json" > "$RUNNER_TEMP/replay.json"
python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/replay.json"
- name: Lapse stale claims, flag invalid tasks, write summary
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
PYTHONPATH: scripts
run: |
set -eu
python3 -m agent_queue gather --repo "$GH_REPO" > "$RUNNER_TEMP/state.json"
python3 -m agent_queue audit --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/actions.json"
python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/actions.json"
{
echo '## Agent queue summary'
echo '```json'
python3 -m agent_queue summary --state "$RUNNER_TEMP/state.json" --now "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
+102
View File
@@ -0,0 +1,102 @@
name: Agent PR checks
# Checks pull requests against the task queue: linked claimed task, file
# ownership, overlap with other open pull requests, and independent
# verification. Runs on the base branch only: pull request code is never checked
# out or executed; changed files come from the API. Not yet run on GitHub.
#
# Advisory: problems are reported as a warning and in the run summary, but the
# check does not fail until a live smoke test and the migration of existing
# issues are done (docs/coordination/agent-tasks.md). Only a comment starting
# with /verified starts the verify job; ordinary comments start nothing.
on:
pull_request_target:
types: [opened, synchronize, reopened, edited]
issue_comment:
types: [created]
permissions: {}
jobs:
check:
if: github.event_name == 'pull_request_target'
runs-on: ubuntu-24.04-arm
permissions:
contents: read
issues: read
pull-requests: read
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check pull request
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
PYTHONPATH: scripts
run: |
set -eu
python3 -m agent_queue event --path "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/event.json"
number=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["number"])' "$RUNNER_TEMP/event.json")
python3 -m agent_queue gather --repo "$GH_REPO" --pr "$number" > "$RUNNER_TEMP/state.json"
status=0
python3 -m agent_queue pr-check --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/result.json" || status=$?
{
echo '## Agent PR check'
echo '```json'
cat "$RUNNER_TEMP/result.json"
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
# 1 means problems were found: advisory for now. Anything else is a failure of the check itself.
if [ "$status" -eq 1 ]; then
echo "::warning title=Agent PR check (advisory)::problems found; see the run summary"
elif [ "$status" -ne 0 ]; then
exit "$status"
fi
verify:
if: github.event_name == 'issue_comment' && github.event.issue.pull_request && startsWith(github.event.comment.body, '/verified')
runs-on: ubuntu-24.04-arm
# issues: write posts the reply.
permissions:
contents: read
issues: write
pull-requests: read
concurrency:
group: agent-verify-${{ github.event.issue.number }}
cancel-in-progress: false
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Record verification and check again
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
PYTHONPATH: scripts
run: |
set -eu
python3 -m agent_queue event --path "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/event.json"
number=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["number"])' "$RUNNER_TEMP/event.json")
python3 -m agent_queue gather --repo "$GH_REPO" --pr "$number" > "$RUNNER_TEMP/state.json"
python3 -m agent_queue decide --event "$RUNNER_TEMP/event.json" --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/actions.json"
python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/actions.json"
# Check again only after an accepted verification of the current head: refused, stale,
# malformed or unauthorized /verified comments get a reply and nothing else.
if ! python3 -m agent_queue should-rerun --actions "$RUNNER_TEMP/actions.json"; then exit 0; fi
# pull_request_target runs are recorded against the base branch, not the pull request
# head, so the earlier check run cannot be found by head SHA. Evaluate the same check here.
status=0
python3 -m agent_queue pr-check --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/result.json" || status=$?
{
echo '## Agent PR check after verification'
echo '```json'
cat "$RUNNER_TEMP/result.json"
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
if [ "$status" -eq 1 ]; then
echo "::warning title=Agent PR check (advisory)::problems found; see the run summary"
elif [ "$status" -ne 0 ]; then
exit "$status"
fi
+13
View File
@@ -37,10 +37,23 @@ jobs:
rustc -vV
- name: Check generated status and PE fixtures
run: |
python3 crates/isa/generate_rdna2_meta.py --check
python3 crates/isa/generate_semantics.py --check
python3 scripts/audit/semantic_coverage.py --check
python3 scripts/audit/status.py --check
for fixture in x2 x3 x4; do
python3 "experiments/x1/fixtures/$fixture.py" --check || exit 1
done
- name: Test agent task queue
run: |
PYTHONPATH=scripts python3 -m unittest discover -s tests/agent_queue
sh -n scripts/agent-queue.sh scripts/agent-sync.sh
- name: Test pull request template check
run: PYTHONPATH=scripts python3 -m unittest discover -s tests/pr_template
- name: Test semantic registry generator and coverage report
run: |
python3 -m unittest discover -s tests/semantics_generator
PYTHONPATH=scripts python3 -m unittest discover -s tests/semantic_coverage
- name: Check formatting and lint
run: |
cargo fmt --all -- --check
+38
View File
@@ -0,0 +1,38 @@
name: PR template
# Fails when a pull request description does not follow
# .github/PULL_REQUEST_TEMPLATE.md: every section present and filled in, a
# linked issue ("Closes #N" or "No linked issue: <reason>"), and the
# claimed-first and DCO checkboxes ticked. Runs again whenever the description
# is edited; comments never start it. Runs on the base branch: pull request
# code is never checked out or executed, and the description is read as data.
#
# To make it blocking, mark the "PR template / description" check as required
# in the branch protection rule for main.
on:
pull_request_target:
types: [opened, edited, reopened, synchronize]
permissions: {}
jobs:
description:
runs-on: ubuntu-24.04-arm
permissions:
contents: read
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check the description against the template
run: |
set -u
status=0
python3 scripts/pr_template_check.py --event "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/result.txt" || status=$?
cat "$RUNNER_TEMP/result.txt"
{ echo '## PR template'; cat "$RUNNER_TEMP/result.txt"; } >> "$GITHUB_STEP_SUMMARY"
if [ "$status" -ne 0 ]; then
echo "::error title=PR description does not follow the template::$(tail -n +2 "$RUNNER_TEMP/result.txt" | head -n -1 | tr '\n' ' ')"
fi
exit "$status"
+3
View File
@@ -37,3 +37,6 @@ __pycache__/
*.pyc
/diagnostics/gta6-candidate-*/
/diagnostics/gta6-check/
# Native application build output
/app/.build/
+13
View File
@@ -45,6 +45,19 @@ No AI slop (section 29).
Read docs/interfaces.md and docs/progress.md before implementation.
## Claiming work before you start
Several people and coding agents work on this repository at the same time. Claim an issue before you edit anything, and never take work someone else has claimed.
1. **Check.** Read every comment on the issue and look for open pull requests that link it. A claim is any comment in which someone says they are taking the issue, in any words (for example "I'll take this" or `/claim`). If a claim exists and is not stale (step 4), pick another issue.
2. **Claim.** Reply on the issue in plain words, for example: "I'm taking this. Plan: …". No command, label or bot step is needed. The earliest claim wins. Claim one issue per comment.
3. **Stay in scope.** If the issue lists files, edit only those, and ask on the issue before widening the list. Do not start work that edits the same files as another claimed issue.
4. **Stale claims.** A claim is stale when the claimer has not opened a pull request for the issue within about one week (7 days) of the claim. Only then may someone else take it, by replying on the issue, for example: "Taking this over: @name's claim from <date> has no pull request after 7 days." A claim with an open pull request is never stale; ask the claimer or the maintainer instead.
5. **Release.** If you stop working on an issue, say so on the issue so others can take it.
6. **Link.** Put `Closes #<n>` in the pull request description.
A coding agent claims in the name of the person it works for and follows the same rules. It must read the comments before claiming, and must never claim over, remove or ignore another person's claim. The optional task-queue commands in `docs/coordination/agent-tasks.md` do not replace these rules: a plain-reply claim counts even though the bot does not track it.
## Changelog maintenance
- At the start of every engineering task, read `CHANGELOG.md` alongside the relevant project documentation. Review the existing `[Unreleased]` entries before implementation to avoid duplicating completed work.
+71 -1
View File
@@ -9,8 +9,75 @@ exact revision and known limitations.
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
remains unsupported.
### Added
### Changed
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
### Added
- Added Phase II infrastructure CLIs under `scripts/qa` and `scripts/release` (#277): read-only RDNA2 expansion planning over live inventories, unified verification profiles with stale-evidence detection, CPU/runtime coverage scans, benchmark regression comparisons that reject incompatible identities, git rename/delete scope collision reports, and release-readiness reports with SBOM/checksum/bundle checks. Covered by `tests/qa` and `tests/release`; advisory until reviewed.
- Added advisory infrastructure QA helpers under `scripts/qa/` and `scripts/release/` (issue #277): exit-status-preserving orchestration with JSON reports, PR scope/DCO/artifact checks, benchmark percentile analysis over existing samples, environment and repository health diagnostics, ARM64 Mach-O/bundle/codesign helpers, and checksum manifests. Covered by `tests/qa/` and `tests/release/`; checks stay advisory until reviewed.
- Recorded agent-queue live smoke evidence for issue #180 against the disposable private repository `ranveersoni98/xenora-agent-queue-smoke`, including claim grant, overlap refusal, release, not-ready denial, progress renew and a successful audit dispatch after fixing comment-only `apply_actions` and audit permissions/argparse issues.
- Added twelve gfx1030 VOP2 vector integer forms through the semantic registry: `v_mul_i32_i24`, `v_mul_hi_i32_i24`, `v_mul_u32_u24`, `v_mul_hi_u32_u24`, `v_min_i32`, `v_max_i32`, `v_min_u32`, `v_max_u32`, `v_xnor_b32`, `v_add_nc_u32`, `v_sub_nc_u32` and `v_subrev_nc_u32` (AMD guide section 12.7), with SRC0 a VGPR, an SGPR, `vcc_lo`, an inline integer or a literal. The registry gained a `vop2_vgpr` operand rule, the vector operations `mul24` and `mul_hi24`, a declared `source_order` for SUBREV, and a per-lane `VectorBinary` that selects one reusable MSL template per operation. Both reference interpreters, written separately from the guide, run the same twelve forms and are checked against 2,040 guide-derived cases, each asserting every lane of a 7-, 32- or 45-lane dispatch (partial, empty and full EXEC), on both CPU interpreters and on native Metal; 575 rejected programs are refused by both interpreters and by the compiler at the same word. A new LLVM-assembled fixture computes every lane from its own input. Part of #215.
- Added sixteen gfx1030 SOP2 integer forms through the semantic registry: `s_min_i32`, `s_min_u32`, `s_max_i32`, `s_max_u32`, `s_cselect_b32`, `s_bfm_b32`, `s_mul_i32`, `s_bfe_u32`, `s_bfe_i32`, `s_absdiff_i32`, `s_lshl1_add_u32` to `s_lshl4_add_u32`, `s_mul_hi_u32` and `s_mul_hi_i32` (AMD guide section 12.1). Min and max set SCC from the strict compare (a tie gives S1 and SCC 0), `s_cselect_b32` reads SCC and is refused when SCC is unset, and BFM, MUL, MUL_HI and CSELECT leave SCC unchanged. The registry gained these primitives, a `selected_src0` SCC effect, the select's SCC input and a declared `shift_amount` for the shift-and-add forms; `ScalarAluOp::evaluate` now returns an optional SCC. Both reference interpreters, written separately from the guide, run the same sixteen forms and are checked against 21,070 guide-derived cases on both CPU interpreters and on native Metal; 597 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all sixteen. Part of #215.
- Added persistent GPU resources, dynamic texture updates, and resource retirement to the native application (Gate 5, #279). The C interface gains `xenora_resource`, resource types (`XENORA_RESOURCE_TYPE_*`), `xenora_session_create_texture`, `xenora_session_update_texture`, `xenora_session_destroy_resource`, `xenora_session_resource_info`, `xenora_session_render_textured`, and `xenora_session_run_textured_fixture`. Persistent GPU resources (textures) are explicitly allocated and owned by the execution session, surviving across execution slices without re-allocation. Dynamic texture subregion updates modify GPU texture contents in-place on native Metal. Resource retirement is completion-aware: destroying a resource held by in-flight GPU execution marks it retired and safely defers destruction until in-flight work completes, while rejecting subsequent caller queries with typed error codes. An original PE fixture (`fixtures/pe/textured.exe`, generated by `fixtures/pe/textured.py` using only the supported ARM64 DBT instruction subset) creates a persistent 2x2 texture via `xenora.dll!texture_create`, renders frame 0, updates pixels via `xenora.dll!texture_update`, renders frame 1, and retires the resource via `xenora.dll!texture_destroy`. Xenora.app gains "Run textured fixture" controls and `--smoke-resources`. Six GPU acceptance tests with Metal validation verify persistent texture lifecycle across multiple frames, dynamic 1x1 and 2x1 subregion updates on native Metal, completion-aware deferred retirement, rejection of invalid/stale/double-destroyed handles, slot reuse across 200 cycles without leaking, and full guest fixture execution. Wired acceptance tests into `scripts/test-gpu.sh`.
- Added interactive guest execution with dynamic input handling and rendering to the native application (Gate 4, #276). The C interface gains `xenora_session_start_interactive_loop`, `xenora_session_send_input`, `xenora_session_queue_input`, and `xenora_session_get_recorded_frame`, along with input masks (`XENORA_INPUT_*`) and `xenora_input_state`. The original interactive guest fixture (`fixtures/pe/interactive.exe`, generated by `fixtures/pe/interactive.py` using only the supported ARM64 DBT instruction subset) polls host input via `xenora.dll!input_poll` and steers its rendered column position (0..3) on native Metal. Xenora.app gains interactive frame-loop controls ("Interactive (300 frames)", "◀ Left", "▶ Right", "Release") and `--smoke-interactive`. Four GPU acceptance tests with Metal validation verify that input events drive guest state and pixel geometry, deterministic input replay reproduces identical frame sequences across multiple sessions, key release and focus loss cleanly hold position without stuck keys, and destroying an interactive session joins promptly. Wired the interactive tests into `scripts/test-gpu.sh`.
- Added persistent guest rendering with pause, resume and stop to the native application (Gate 3, #266). The C interface gains `xenora_session_start_frame_loop`, `xenora_session_pause_frame_loop`, `xenora_session_resume_frame_loop`, `xenora_session_stop_frame_loop`, and `xenora_session_frame_loop_status`, plus new states (`XENORA_LOOP_*`). The guest fixture (`fixtures/pe/frame-loop.exe`, generated by `fixtures/pe/frame-loop.py` without external toolchains) runs on a session-owned thread and repeatedly calls `xenora.dll!frame_submit` until told to halt; each frame is rendered on native Metal, checked per pixel against geometric expectations, and returned via read-back RGBA8 buffers. Destroying a running or paused session safely stops its loop outside the global session lock. Xenora.app gains persistent frame-loop controls ("Start 300 frames", "Pause", "Resume", "Stop") and displays live frames with their frame index. Five GPU acceptance tests with Metal API and GPU validation verify frame ordering over 300 frames, live sampling across 2,000 frames without backwards progression, pause/resume/stop lifecycle, prompt join on session destruction, and stable memory footprint across repeated sessions. Added `--smoke-loop` to Xenora.app and wired the acceptance tests into `scripts/test-gpu.sh`.
- Added read-only executable inspection to the native app (#267). Xenora.app can open a PE file with Open Executable…, by dropping it on the window, or from Finder (it registers as an alternate viewer for Windows executables). The new C function `xenora_inspect_executable` returns a text report built from the existing static probe and loader validation: file size and SHA-256, header facts, whether `ParsedPe::parse` accepts the file, sections, imports not provided by Xenora's standard runtime services, the bounded static disassembly's count of instructions the ARM64 DBT does not support with the first one's address, and relocation and TLS counts. Nothing in the file is executed, and executing opened files remains unavailable pending #257. Inputs over 256 MiB are refused before reading. A panic inside the probe is reported as a Xenora defect instead of crashing the app; the new truncation test found one in `probe_pe_bytes` (truncations of `trusted-runner.exe` to 1,556–1,665 bytes slice past the end of the file while reading an import name), reported as #270 and not fixed here. Checked with the x1 executables in `experiments/x1/fixtures`, which the app does not embed, with malformed inputs, and in the window through the Finder open path and the Open panel; drag and drop was not exercised.
- Added eleven gfx1030 SOP1 unary forms through the semantic registry: `s_not_b32`, `s_brev_b32`, `s_bcnt0_i32_b32`, `s_bcnt1_i32_b32`, `s_ff0_i32_b32`, `s_ff1_i32_b32`, `s_flbit_i32_b32`, `s_flbit_i32`, `s_sext_i32_i8`, `s_sext_i32_i16` and `s_abs_i32` (AMD guide section 12.3). Searches that find nothing return -1, `s_abs_i32` of 0x80000000 stays 0x80000000, and only NOT, BCNT0, BCNT1 and ABS write SCC. The registry gained these primitives, a `sop1_sgpr` operand rule, and a declared `source_bits` for sign extension that is checked against the XML's 8- and 16-bit source operands. The reference and independent semantic-review interpreters, written separately from the guide, evaluate the same eleven forms and are checked against 4,126 guide-derived cases on both CPU interpreters and on native Metal with validation; 231 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all eleven. Part of #215.
- Showed the first guest-driven frame in the native app (Gate 2, #263). The C interface gains `xenora_session_run_trusted_fixture`, which runs only the embedded trusted PE fixture: its x86-64 code is translated and executed, its `xenora.dll!fixture_draw` call compiles the x9 RDNA2 shader fixtures to MSL and renders on the native Metal device, and the 4×3 RGBA8 read-back is returned only if the guest halts with the CLI runner's expected results and every pixel equals the pixel shader's export, (1, 0, 0, 1) as opaque red. Xenora.app's "Run trusted fixture" button shows that frame, and `--smoke-frame` prints it. A `gpu-tests` test, run by `scripts/test-gpu.sh`, executes the fixture three times through the interface with Metal validation enabled. The frame is a read-back image, not drawable presentation, and no caller-supplied executable can run. Verified on one Apple Silicon Mac; the window was checked by screenshot.
- Added a minimal native macOS application shell and its Rust interface (Gate 1 of the native application work). `crates/ffi` builds a static library with a versioned C interface (`crates/ffi/include/xenora.h`, version 1): opaque, generation-checked 64-bit session handles (never pointers), at most 64 live sessions, stable status codes, and panics caught at the boundary. Version 1 can only create and destroy sessions and parse the bundled trusted PE fixture; it executes no guest code. `app/` is a SwiftUI app built with Swift Package Manager that shows the interface version and the fixture's section count and entry point. `scripts/build-app.sh` builds an ad-hoc-signed, arm64-only `build/Xenora.app` with no entitlements and runs its `--smoke` check. Six Rust tests cover invalid, stale and double-destroyed handles, version mismatch, null outputs, 4,000 concurrent create and destroy cycles, and header/constant agreement. The CLI and headless workflows are unchanged. Verified locally on one Apple Silicon Mac (macOS 27.2.1, Swift 6.4, Rust 1.100.0); not yet run in CI.
- Added the gfx1030 SOPC compares `s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32}` through the semantic registry, which replaces the hand-written `s_cmp_eq_u32` path. Each sets only SCC to whether the relation holds with SSRC0 on the left (AMD guide section 12.4); the registry gained a `compare` operation with a declared `relation` and a `sopc_scalar` operand rule. `Instruction::ScalarCompareEqU32` is now `Instruction::ScalarCompare { op: ScalarCompareOp, .. }`; `s_cmp_eq_u32` behaves as before. The reference and independent semantic-review interpreters, written separately from the guide, evaluate all twelve, checked against 7,824 guide-derived cases on both CPU interpreters and on native Metal with validation; 348 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all twelve. Two literal selectors stay rejected. Part of #215, stage D.
- Added eight gfx1030 SOP2 forms through the semantic registry alone: `s_andn2_b32`, `s_orn2_b32`, `s_nand_b32`, `s_nor_b32`, `s_xnor_b32`, `s_lshl_b32`, `s_lshr_b32` and `s_ashr_i32`, each with SCC = result != 0. Each is one registry entry with no per-form Rust; the registry gained these primitives and a declared shift-count width (`shift_count_bits = 5`, so shifts use S1[4:0] as in the AMD guide, section 12.1), which the generator applies as a mask and checks against the XML's unsigned count operand. The reference interpreter and the independent semantic-review interpreter, written separately from the guide, now evaluate the same eight forms and are checked against 6,896 guide-derived cases; a new LLVM-assembled fixture (`fixtures/rdna2/scalar-logic.s`) runs on CPU and native Metal with validation. A NULL destination (s125) stays rejected. Part of #215, stage C.
- Added an independent operand-domain verification harness for the 9 supported SOP2 scalar ALU forms and 12 VOPC integer compares (`tests/validation/tests/operand_domains.rs`, part of #215 stage E): 4,788 generated cases (boundary values, 64-bit carry and borrow chains, aliased registers, every integer inline constant, literals, s105 and v255, partial and zero EXEC, VCCZ) and 498 rejections (missing literal words, and encodings outside Xenora's supported subset) run on `xenora_ref` and, as an ignored test picked up by `scripts/test-gpu.sh`, on native Metal. Expected values come from the public AMD RDNA 2 guide's pseudocode, written out in the test without Xenora code; this is agreement with a spec-derived reference, not with Xbox hardware. Local verification only: 32 deliberate code breaks were each caught; the guide leaves the width of `S1 + SCC` in `s_subb_u32` open, and those 8 cases are kept in their own family.
- Added a declarative semantic registry for gfx1030 instruction forms (`crates/isa/semantics/rdna2.toml`, schema 1) and its generator, `crates/isa/generate_semantics.py`, with `validate`, `generate` and `--check` modes. The generator checks every declaration against a closed vocabulary and the pinned AMD XML snapshot (opcode, family, SCC input and output, operand widths and signed formats), rejects contradictory, incomplete or duplicate definitions, and emits static Rust tables marked as generated. The nine SOP2 forms moved onto it with no change in behaviour: the decoder's SOP2 dispatch and `ScalarAluOp`'s mnemonic, SCC read and evaluation are now generated, and evaluation goes through shared primitives instead of per-opcode code. All existing SOP2 tests, including the native Metal known answers and the LLVM comparison, pass unchanged. Decoding speed is unchanged (10.2 ns before, 10.1 ns after, per SOP2 instruction, release build on an Apple M5 Pro). Also added `scripts/audit/semantic_coverage.py`, which generates `docs/shaders/semantic-coverage.md`: per-family counts of identified, declared, decoded, lowered, reference-verified and Metal-verified forms, taking evidence only from `docs/status.toml`. Part of #215, stages A and B.
- Added a native Metal blend pass, `NativeCompute::render_blend`: up to 16 flat-coloured triangles drawn in order into an RGBA8 target, each with its own colour write mask (any subset of R, G, B, A) and either blending disabled or separate RGB and alpha blend factors (Zero, One, source and destination colour and alpha, and their one-minus forms) and operations (Add, Subtract, ReverseSubtract, and Min and Max, which take the unweighted values). Checked on the GPU with Metal validation in 39 passes over two original overlapping triangles: a clear-only pass; blending disabled; each source factor with the destination term zeroed and each destination factor with the source term zeroed; every operation; additive clamping; separate alpha factors; a separate alpha operation; eight write masks (each channel alone, RGB, none, RGBA, and RG with blending); and a pass whose first draw is itself blended and masked. Colours are compared per channel against images derived independently (in exact fractions) from the public Metal blend equations, which a new CPU reference in `xenora-ref` also reproduces. The tolerance was fixed before measuring: channels whose exact result is a whole 8-bit value must match exactly, and channels that need rounding may differ by 1. On an Apple M5 Pro every rounded channel matched round-to-nearest exactly. Synthetic fixtures only; no console blend state is involved.
- Added indexed triangle draws. Native Metal: `NativeCompute::render_indexed` issues one real `drawIndexedPrimitives` call per draw (up to 16) on a 16- or 32-bit index buffer with a start index and a signed base vertex, into an RGBA8 target; a draw can sample an original BC1 texture uploaded natively. Before encoding anything it rejects the whole pass for a bad index count, an index range past the buffer, any `index + base vertex` outside the vertex buffer, and, as this API's policy, a raw all-ones index (the primitive-restart value, which Metal does not define for triangle lists). Loader: a synthetic, CPU-side index buffer binding (resource handle and offset, the view running to the end of the resource) with `cmd_set_index_buffer` and `cmd_draw_indexed_instanced`, which fetch one triangle, drawn once, through the index buffer, start index and base vertex and pass it to the existing one-triangle backend; each drawn triangle replaces the previous output. Recording rejects formats other than DXGI `R16_UINT` and `R32_UINT`, offsets not aligned to the index size or past the resource, and unknown resources. Execution checks each draw in turn, so earlier draws have already rendered when a later one fails: index counts other than 0 or 3, more than one instance or a nonzero start instance, a missing index buffer, indices past the buffer and an `index + base vertex` outside the vertex buffer are typed errors; a valid zero index or instance count draws nothing. All-ones indices are ordinary indices there. Checked on the GPU with Metal validation in 16 passes (both index sizes, 32-bit indices above 16 bits, odd 16-bit start, positive and negative base vertex, reversed winding, flat and textured two-triangle draws, draw order, BC1-textured draws), compared per pixel against images derived independently from the geometry, the public D3D12 and Metal index semantics and the public BC1 rules, which a new CPU reference in `xenora-ref` also reproduces; the loader's fetch is checked against literal positions with synthetic guest-backed buffers and through the native Metal renderer. Synthetic fixtures only; no console index-buffer views, guest programs or console draw state are involved.
- Added a `cpu_decode` cargo-fuzz target for the static x86-64 decoder used by the read-only PE probe. It places up to 4,096 fuzz bytes as the code section of a fixed, original PE32+ header and runs `probe_pe_bytes` twice with a bounded `ProbeConfig` (4,096 bytes, 2,048 instructions, 1,024 worklist entries); nothing is executed. It checks that the two reports are identical and that every decoded instruction is 1 to 15 bytes long, lies inside the code and matches the input bytes. A startup self-check aborts the run if the synthetic header stops reaching the decoder. A 600-second local campaign (nightly cargo-fuzz, one fork-mode worker, seeded from instruction bytes in the loader's probe tests; about 2.38 million executions, coverage 1,350 edges) found one decoder defect, reported to the CPU owner on #74 and not fixed here: the probe accepts unlimited FS/GS segment prefixes and reports instructions longer than 15 bytes (minimized input: 16 bytes of `0x65`). Run it with `rustup run nightly cargo fuzz run cpu_decode`; `scripts/fuzz.sh` does not list it yet.
- Added a `pe_parse` cargo-fuzz target that feeds malformed bytes to the PE32+ parser (`ParsedPe::parse`, `rva_to_file_offset`) and, only when the summed section mapping size and `SizeOfImage` are both at most 64 MiB, to the checked guest-memory mapping step (`load_into_memory`); nothing is executed. A 600-second local campaign (nightly cargo-fuzz, fork mode, seeded from the repository's synthetic PE fixtures, about 120,000 executions, coverage 267 edges) found two loader panics, reported to the CPU owner and not fixed here: truncated optional headers panic on out-of-range slices in `parse`, and `rva_to_file_offset` overflows `u32` when a section's address plus size exceeds 4 GiB. Run it with `rustup run nightly cargo fuzz run pe_parse`; `scripts/fuzz.sh` does not list it yet.
- Added `NativeCompute::run_words_with_group_width` and `max_group_width` to run a trusted kernel at an explicit threadgroup width, rejecting zero and widths above the device or pipeline limit. Native tests check 91 legal width and grid-size pairs (widths 1 to 1,024, including non-divisible grids) against independently computed outputs, and confirm the dispatched group sizes, including trimmed last groups. On an Apple M5 Pro, in three release runs of a 4,096-thread integer-mixing kernel (30 samples per width), widths 64, 128 and 256 were within 0.3 % of each other in two runs, at a median of 58.8 µs of GPU time. Width 512 was 5 to 6 % slower and width 1,024 about twice as slow in all three runs. The first run was about 4.7 times slower overall for reasons not determined, and in it 128 and 256 were 3 to 4 % faster than 64. The default width of 64 is unchanged. This was measured on one device and one workload.
- Added a native Metal depth pass, `NativeCompute::render_depth`: up to 16 triangles drawn in order into an RGBA8 target with an optional `Depth32Float` attachment, a chosen clear depth, a per-draw depth compare function (all eight) and depth write enable. A pass without an attachment accepts only `DepthState::DISABLED`. Colour and the stored depth are both read back; the depth values are returned as the texture read gives them, without numeric conversion. A draw can sample an original BC1 texture whose blocks are uploaded to a native `BC1_RGBA` texture without CPU decoding, gated on `supportsBCTextureCompression`. Checked on the GPU with Metal validation in 30 passes of original overlapping triangles: clear, every compare function at three depths, write enabled and disabled, depth test disabled (`Always` without writes) with an attachment and no attachment at all, and a BC1-textured draw. Colour and depth are compared per pixel against expectations derived independently from the geometry, the Metal compare semantics and the public BC1 rules, which a new CPU reference in `xenora-ref` also reproduces. These are synthetic fixtures only; no console depth formats or guest render state are involved.
- Added a CPU BC7 block decoder in `xenora-texture` for all eight modes, with explicit handling of the invalid all-zero mode byte. It is checked by hand-derived tests and 430 known-answer vectors from a separate clean-room reference written from the Khronos Data Format Specification (merged in PR #224 without a changelog entry).
- Added independent negative tests for gfx1030 extension words: truncated literal, SDWA, DPP16, DPP8 and MIMG NSA trailers (62 prefixes of 18 LLVM-assembled instructions), disallowed extensions, and length recognition kept apart from semantic validity. Tests only, with no decoder change (merged in PR #231 without a changelog entry).
- Added the gfx1030 Wave32 VOPC compares `v_cmp_{lt,eq,le,gt,ne,ge}_{i32,u32}_e32`. VCC_LO is EXEC_LO & the per-lane test, always fully written, so empty EXEC gives 0. A compare result can feed `s_cbranch_vccz`, `v_mov_b32_e32 vN, vcc_lo` and another compare's source; nothing else, so EXEC never becomes data-dependent. A data-dependent `s_cbranch_vccz` is a wave-uniform branch over integer vector ALU code, lowered to a select at the join. The Metal kernel builds each mask by recomputing the 32 lanes of its own RDNA wave, with no SIMD-group, threadgroup or barrier assumption. The reference now runs lockstep Wave32 waves. Verified on an LLVM-assembled fixture plus 251 original programs (boundary operands, partial and empty EXEC, both branch edges, a partial final wave) against exact integer definitions: translator, reference and second interpreter agree on CPU, and all 252 match on native Metal with validation. LLVM agrees on every encoding. VOP3, SDWA, DPP, `v_cmpx` and Wave64 stay rejected. See `docs/shaders/vector-compare.md`.
- Added the gfx1030 SOP2 forms `s_add_i32` and `s_sub_i32`, with SCC as signed overflow as defined in the AMD RDNA 2 ISA guide (sections 5.3 and 12.1). They are checked on CPU and on native Metal with validation on 400 boundary programs, four immediate-operand overflows and the scalar ALU fixture, plus eight hand-worked overflow and no-overflow cases on CPU.
- Added the gfx1030 SOP2 scalar forms `s_add_u32`, `s_sub_u32`, `s_addc_u32`, `s_subb_u32`, `s_and_b32`, `s_or_b32` and `s_xor_b32`. They are decoded, executed by the reference and independent interpreters, and resolved by the translator, with SCC as carry, borrow or nonzero result. `v_mov_b32_e32` can now read a normal SGPR. Verified on 1,400 original operand vectors plus an LLVM-assembled fixture, on CPU and on native Metal with validation. The other SOP2 forms stay unsupported. See `docs/shaders/scalar-alu.md`.
- Added `scripts/audit/test_inventory.py`, which lists the Cargo test inventory of two commits in temporary detached worktrees and reports removed, added, newly ignored and newly un-ignored tests, failing on any loss not explained in an `--allow` file. Run against the old PR #166 head 5450612 and main 951189c, it reports the 12 BC texture tests that head was missing (exit 1); the same commit against itself reports no change. Default features only; see `docs/testing/test-inventory.md`.
- Added complete gfx1030 instruction metadata generated from AMD's public RDNA 2 XML: 1,465 base forms across 21 encoding families with fields, operands, flags and allowed extension words. A committed, normalised snapshot lets `crates/isa/generate_rdna2_meta.py --check` verify the generated table offline; CI runs it.
- Added `xenora_isa::meta::identify`, which finds any gfx1030 instruction's form and exact length, including literal, SDWA, DPP and NSA words, and rejects truncated, unassigned and disallowed-extension encodings. It agrees with every LLVM-assembled fixture and with LLVM 23.1.6 on a probe set covering each family and extension word. Identification does not make an instruction executable: `SEMANTIC_FORMS` lists the forms with semantic decoding (46 as of the VOPC compares).
- Added `xenora shaders coverage [--json]` and `xenora shaders inspect <file>` for per-family coverage and stream listings that separate decoding failures from unsupported semantics. Each instruction is decoded at its stream offset and branch targets are checked against the whole stream's boundaries, so supported branches are no longer misreported as unsupported operands. `xenora_decoder::decode_at` decodes a single instruction for such callers.
- Added an agent task queue for the cpu, gpu, runtime, shared and qa areas: an *Agent task* issue form with priority and interface fields, a workflow that decides `/claim`, `/release`, `/reassign`, `/progress`, `/blocked`, `/unblock` and `/approve-acceptance` comments one at a time (dependency, cycle and file-overlap checks, 24-hour leases renewed by progress), a pull request check (linked claimed task, file ownership, overlap with other pull requests, independent `/verified <head sha>`), `scripts/agent-queue.sh` and `scripts/agent-sync.sh` (upstream fetch every 12 minutes, task branches in separate worktrees) and a machine-readable queue summary. The rules are standard-library Python in `scripts/agent_queue/` with unit tests in `tests/agent_queue/`; issue text is never executed and acceptance commands need maintainer approval. Only comments that start with a command start a job, so ordinary pull request comments never re-run verification, and only an accepted `/verified <full head sha>` evaluates the check again; and each claim run decides every unanswered command in order, so commands whose pending runs GitHub cancelled are still answered. See `docs/coordination/agent-tasks.md`. Unit tests pass locally; the workflows have not run on GitHub yet, and the pull request check stays advisory (it never blocks a merge) until a live smoke test and the migration of existing issues are done.
- Added explicit claim-before-work rules for contributors and coding agents to `AGENTS.md`, `CONTRIBUTING.md` and the pull request template: check for existing claims, claim with `/claim`, keep a 24-hour lease alive with `/progress`, `/release` when stopping, and link the claimed issue. Without the claim workflow, the earliest valid claim comment wins.
- Added a CPU decoder for a bounded subset of BC6H (signed and unsigned HDR) in
`xenora-texture`: the four single-subset modes (Khronos modes 3, 7, 11 and 15, Microsoft
modes 11 to 14), listed in `BC6H_SUPPORTED_MODES`, plus the reserved modes, which decode to
zero as specified. The ten two-subset modes are rejected with `Bc6hError::UnsupportedMode`
and are not implemented. Tests check hand-derived values and 128 known-answer vectors from a
separate clean-room reference decoder.
- Added native Metal upload and readback of BC4 and BC5 textures (UNORM and SNORM):
`xenora-texture` gains a pitched `BcChannelUpload`, and `NativeCompute::read_bc_channel_upload`
sends the original blocks to `BC4_R*` or `BC5_RG*` textures when the device reports BC
support, failing with `supportsBCTextureCompression` otherwise. GPU tests cover six- and
eight-value interpolation, equal and extreme endpoints (signed -128 reads as -1.0), red-green
channel order, padded row and slice pitches, two layers and two mips against the CPU decoders
and hand-derived anchors. On an Apple M5 Pro interpolated codes were within 1.71 codes of the
exact values and up to two codes from the truncating CPU reference.
Edge levels of 5×3 and 1×1 and invalid payloads (zero extents, short, oversized or
block-count-mismatched buffers) are covered.
- Added native Metal upload and readback of BC2 and BC3 textures: `xenora-texture` gains a
pitched `BcAlphaUpload` for 16-byte blocks, and `NativeCompute::read_bc_alpha_upload` sends
the original blocks to `BC2_RGBA` or `BC3_RGBA` textures when the device reports BC support.
GPU tests cover explicit and interpolated (six- and eight-value) alpha, both colour endpoint
orders, padded row and slice pitches, two layers and two mips against the CPU decoders and
hand-derived anchors. On an Apple M5 Pro the native decoder's interpolated values were within
8/7 (about 1.14) codes of the exact values, so up to two codes from the truncating CPU reference.
Edge levels of 5×3 (one block row) and 1×1 are covered, invalid payloads (zero extents,
short, oversized or block-count-mismatched buffers, bad pitches) are rejected before upload,
and `MetalError::is_capability_unavailable` separates a device without BC support from an
implementation failure.
- Added CPU block decoders for BC2, BC3, BC4 and BC5 (UNORM and SNORM) in `xenora-texture`, with tests whose expected texels were derived by hand from the Microsoft and Khronos block-compression specifications. Interpolated values truncate toward zero, as the existing BC1 decoder does; GPU upload and sampling of these formats are not implemented yet.
- Added `dbt::tests::sib_store_executes_through_the_native_dbt`, an independent DBT execution
test that runs the SIB store form `mov [rsp + 0x20], rbx` through the native ARM64 DBT and
verifies the value lands in guest memory.
@@ -23,11 +90,14 @@ remains unsupported.
### Changed
- Simplified the claim rules in `AGENTS.md`, `CONTRIBUTING.md` and the pull request template at the maintainer's request: claim an issue by replying on it in plain words, never claim over an existing claim, and treat a claim as stale only after about one week without a pull request. The task-queue lease (`lease_hours` in `.github/agent-queue.json`) is now 168 hours to match, and `docs/coordination/agent-tasks.md` marks the queue commands as optional.
- The static PE probe now marks x86-64 SIB memory addressing as DBT-supported, matching the
native DBT.
### Fixed
- Fixed agent-queue `apply_actions` crashing on comment-only decisions (claim refusals) by skipping no-op `gh issue edit` calls; accept `summary --now` after the subcommand; grant the audit job `pull-requests: read` so live audits can list open PRs (issue #180).
- Fixed `xenora_isa::meta::identify` reading six VOP3 interpolation forms (`v_interp_p1_f32_e64`, `v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`, `v_interp_p1ll_f16`, `v_interp_p1lv_f16`, `v_interp_p2_f16`) as 12 bytes when SRC0 is 255. In these forms SRC0 holds attribute bit-fields, not an operand selector (AMD RDNA 2 ISA guide section 10.4.2; XML operand type `OPR_ATTR`), so SRC0 = 255 no longer adds a literal word. The six corpus probes are now 8 bytes, as LLVM 23.1.6 also decodes them. The six pinned `mismatch` rows in the LLVM corpus check are gone: one now agrees fully, and five are `operand_flagged` (same instruction and length; LLVM flags an operand).
- Updated `test_probe_static_analysis_does_not_execute_code`: the SIB store `mov [rsp + 0x20],
rbx` at RVA 0x1004 is now genuinely supported by the native DBT (verified by the independent
execution test above), so the probe reports no blocker for this program.
+2
View File
@@ -6,6 +6,7 @@ Xenora is an experimental Xbox Series X|S recompilation framework for Apple Sili
- Read `README.md` and, when present, `AGENTS.md`, `docs/interfaces.md`, `docs/status.toml` and the relevant architecture decisions.
- Discuss substantial changes in an issue before implementing them; small fixes do not require prior approval.
- Claim an issue before working on it by replying on it in plain words, after checking its comments for an existing claim. Never claim over someone else. A claim with no pull request after about one week may be taken over with a reply saying so. Coding agents follow the same rules; see "Claiming work before you start" in `AGENTS.md`.
- Use a native ARM64 macOS environment with Rust and the appropriate Xcode/Metal tools. LLVM AMDGPU tools are needed for ISA fixture generation; extra tooling depends on the subsystem.
- Keep changes focused and preserve existing public interfaces unless a change is justified and documented.
@@ -43,6 +44,7 @@ Before incorporating third-party code, verify per-file license compatibility wit
## Pull requests
- Branch from the current main branch, keep commits focused, and link relevant issues.
- Fill in every section of the pull request template, keep `Closes #<number>` (or write `No linked issue: <reason>`), and tick the claimed-first and DCO checkboxes. The *PR template* check fails until the description does, and runs again each time you edit it.
- Include a clear explanation, tests and any documentation/status updates. Separate unverified work from supported behavior.
- Disclose material AI assistance and personally review generated changes. AI output is not an authoritative source, test oracle or substitute for independent review.
- Never include secrets, personal paths, credentials or private data in patches or logs.
Generated
+11
View File
@@ -153,7 +153,9 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
name = "xenora"
version = "0.1.0"
dependencies = [
"xenora-decoder",
"xenora-import-gen",
"xenora-isa",
"xenora-loader",
"xenora-metal",
"xenora-ref",
@@ -177,6 +179,15 @@ dependencies = [
"xenora-ref",
]
[[package]]
name = "xenora-ffi"
version = "0.1.0"
dependencies = [
"xenora-loader",
"xenora-metal",
"xenora-shader",
]
[[package]]
name = "xenora-import-gen"
version = "0.1.0"
+55 -14
View File
@@ -2,13 +2,17 @@
**Experimental Xbox Series X|S emulation research for Apple Silicon Macs.**
Xenora is an open-source project written primarily in Rust, exploring native Xbox Series X|S compatibility on ARM64 macOS.
The project combines a bounded x86-64 guest execution environment, Portable Executable (PE32+) loading, AMD RDNA 2 shader translation, and a native Apple Metal graphics backend.
Xenora is an open-source project written primarily in Rust that builds and verifies a native, bounded execution environment on Apple Silicon: an independent x86-64 guest path, original PE32+ loading, AMD RDNA 2 shader translation, and a native Apple Metal graphics backend.
**No Wine. No CrossOver. No Rosetta. No Vulkan runtime.**
Xenora is still experimental. It currently executes independently authored synthetic guest programs and shaders. **Commercial Xbox games, including Grand Theft Auto VI, do not boot.** Authentic Xbox executable loading and system-service compatibility remain unsupported.
Xenora is still experimental. Verified work is restricted to independently authored synthetic programs and shaders; authentic Xbox executable loading, system-service compatibility and commercial game execution remain unsupported. See the [current limitations](#current-limitations).
### At a glance
- **Native graphics:** translated gfx1030 vertex and pixel stages and native passes (indexed draws, blend, depth) run on Apple Silicon GPUs — verified, see [Blend pass](#blend-pass) and [Verified Apple M5 results](#verified-apple-m5-results).
- **Guest execution:** bounded x86-64 execution, original PE32+ loading, synthetic services and guest-driven GPU dispatch — verified milestones X1–X9.
- **Not supported:** authentic Xbox executable loading and commercial game execution; see the [milestone table](#development-milestones).
[![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)
@@ -18,7 +22,7 @@ Xenora is still experimental. It currently executes independently authored synth
Xenora has progressed from executing individual x86-64 instructions to running original PE32+ guest programs that interact with translated GPU workloads on Apple Silicon.
The latest verified milestone includes **translated gfx1030 vertex and pixel shaders executing through native Apple Metal**, with rendered pixels compared against independently calculated reference results.
The latest verified milestones include **translated gfx1030 vertex and pixel shaders executing through native Apple Metal**, the native Metal **blend pass** (`NativeCompute::render_blend`) and **indexed triangle draws** (`NativeCompute::render_indexed`) into offscreen targets, with rendered pixels compared against independently calculated reference results.
### Development milestones
@@ -33,14 +37,14 @@ The latest verified milestone includes **translated gfx1030 vertex and pixel sha
| X7 — Imported services | Named imports, guest-to-host service dispatch and result validation | Verified |
| X8 — Translated compute | Original gfx1030 compute shaders executing on Metal, partial Wave32 handling and BC1 readback | Verified subset |
| X9 — Translated graphics | Persistent resource handles, translated vertex/pixel stages and offscreen Metal rendering | Verified subset |
| X10 — Texture sampling | Translate RDNA2 image instructions, implement samplers, mipmapping and guest-backed texture bindings | Planned |
| X11 — Graphics pipeline | Multiple draw calls, vertex buffers, index buffers, depth/stencil testing, blending and render targets | Planned |
| X10 — Texture sampling | Translated image instructions are still planned; upload, readback and decode of BC compressed formats is implemented (see [Texture support](#texture-support)) | Planned |
| X11 — Graphics pipeline | Bounded multi-draw passes into offscreen RGBA8 targets: translated vertex and pixel stages, indexed triangle draws, colour write masks and blend state | Implemented |
| X12 — Wave execution | Expand Wave32/Wave64 semantics, divergent control flow, cross-lane operations, LDS and barriers | Planned |
| X13 — Advanced shaders | Mesh, geometry and additional compute shader capabilities with verified Metal execution | Planned |
| X14 — CPU recompilation | Native ARM64 dynamic recompilation of supported x86-64 instructions in synthetic fixtures | Implemented subset |
| X15 — Executable compatibility | Static PE inspection reports sections, relocations, thread-local storage (TLS) callbacks, imports and entry-point instructions | Static probe implemented |
| X16 — Guest memory and threading | Virtual memory mapping, thread scheduling, synchronization primitives and atomic operations | Implemented subset |
| X17 — System services | Implement a tested subset of Xbox-compatible runtime APIs, memory services, filesystem access and application lifecycle | Implemented subet |
| X17 — System services | Implement a tested subset of Xbox-compatible runtime APIs, memory services, filesystem access and application lifecycle | Implemented subset |
| X18 — Graphics API translation | Translate supported Xbox graphics commands, resource descriptors, command queues, barriers and fences into Metal operations | Planned |
| X19 — Advanced GPU features | Indirect rendering, asynchronous compute, additional texture formats and ray-tracing compatibility research | Planned |
| X20 — Integrated guest runtime | Connect CPU recompilation, executable loading, system services and graphics translation into one persistent runtime | Planned |
@@ -97,14 +101,35 @@ The current graphics subset supports:
- Offscreen RGBA8 render targets.
- Native GPU readback and pixel-by-pixel validation.
- Explicit rejection of unsupported shader forms.
- Flat-coloured triangle draws with colour write masks and blending (see [Blend pass](#blend-pass)).
- Indexed triangle draws (see [Indexed draws](#indexed-draws)).
- Depth testing with an optional `Depth32Float` attachment (see [Depth pass](#depth-pass)).
These are genuine translated shader stages, not merely demonstrations using handwritten Metal vertex and fragment programs.
The current rendering tests are deliberately narrow: original fixtures, a single triangle per draw, and controlled shader inputs and outputs.
### Blend pass
`NativeCompute::render_blend` draws up to 16 flat-coloured triangles in order into an offscreen RGBA8 target. Each draw has its own colour write mask (any subset of R, G, B, A) and either blending disabled or separate RGB and alpha blend factors (Zero, One, source and destination colour and alpha, and their one-minus forms) and operations (Add, Subtract, ReverseSubtract, and Min and Max). Colours are compared per channel against images derived independently (in exact fractions) from the public Metal blend equations.
GPU verification (Metal API and shader validation enabled): 39 Metal-validated passes over two original overlapping triangles — a clear-only pass; blending disabled; each source factor with the destination term zeroed and each destination factor with the source term zeroed; every operation; additive clamping; separate alpha factors; a separate alpha operation; eight write masks; and a pass whose first draw is itself blended and masked. On an Apple M5 Pro every rounded channel matched round-to-nearest exactly.
### Indexed draws
`NativeCompute::render_indexed` issues one real `drawIndexedPrimitives` call per draw (up to 16) on a 16- or 32-bit index buffer with a start index and a signed base vertex, into an offscreen RGBA8 target. A draw can sample an original BC1 texture uploaded natively.
GPU verification (Metal API and shader validation enabled): 16 Metal-validated passes (both index sizes, 32-bit indices above 16 bits, odd 16-bit start, positive and negative base vertex, reversed winding, flat and textured two-triangle draws, draw order, BC1-textured draws), compared per pixel against images derived independently from the geometry, the public D3D12 and Metal index semantics and the public BC1 rules.
### Depth pass
`NativeCompute::render_depth` draws up to 16 triangles in order into an offscreen RGBA8 target with an optional `Depth32Float` attachment, a chosen clear depth, a per-draw depth compare function (all eight) and depth write enable. Colour and the stored depth are both read back.
GPU verification (Metal API and shader validation enabled): 30 Metal-validated passes of original overlapping triangles: clear, every compare function at three depths, write enabled and disabled, depth test disabled with an attachment and no attachment at all, and a BC1-textured draw.
### Verified Apple M5 results
The X9 native Metal acceptance run reported **20 passing tests, zero failures and zero ignored tests**, with Metal API and GPU validation enabled.
The X9 native Metal acceptance run reported **20 passing tests, zero failures and zero ignored tests**, with Metal API and GPU validation enabled. The newer passes below are separate Metal-validated campaigns, also with Metal API and shader validation enabled.
Representative checks include:
@@ -115,6 +140,9 @@ Representative checks include:
| Perspective interpolation | Exact checks of 16 pixels and another 16 after swapping vertex color channels |
| BC1 texture handling | 33 texels across selected mip levels and array layers |
| Guest rendering | PE32+ guest receives and checks the translated render output |
| Blend pass | 39 Metal-validated passes over two overlapping triangles |
| Indexed draws | 16 Metal-validated passes (both index sizes, signed base vertices, draw order) |
| Depth pass | 30 Metal-validated passes (all eight compare functions, no-attachment case) |
The expected results were calculated independently of the production shader translation path.
@@ -141,20 +169,20 @@ The resource system remains experimental. Native GPU work already in flight duri
## Texture support
Xenora includes an original BC1 texture-processing path.
Xenora includes original texture upload, readback and block-compression paths.
Implemented and tested functionality includes:
- Validated mip levels and array layers.
- Pitched texture uploads.
- Block-compressed texture handling.
- Block-compressed texture handling, including BC4/BC5 upload and readback and a CPU BC7 decoder for the eight modes.
- Native Metal texture readback.
- Edge-block and transparency tests.
- Invalid descriptor and bounds rejection.
**Translated texture-sampling instructions are not yet implemented.**
The existing texture readback path uses an authored Metal kernel. It should not be confused with executing arbitrary RDNA2 texture-fetch instructions.
The existing texture readback path uses authored Metal kernels. It should not be confused with executing arbitrary RDNA2 texture-fetch instructions.
Xbox-specific texture layouts and additional compression formats require further research and validation.
@@ -209,6 +237,8 @@ flowchart TD
Xenora's host execution environment is native ARM64. The guest architecture being interpreted is x86-64.
The native graphics pipeline runs translated vertex and pixel stages, the indexed-draw and blend passes and the depth pass into offscreen Metal targets, with GPU readback compared against independent CPU references.
The project does not currently provide a general-purpose x86-64 dynamic recompiler or a complete Xbox operating-system implementation.
See [Interface Contracts](docs/interfaces.md) for the documented execution and resource boundaries.
@@ -227,8 +257,8 @@ The following remain unsupported or incomplete:
| Executable loader | General relocations, TLS, DLL initialization and authentic Xbox startup |
| Xbox runtime | Console-specific services, system APIs, filesystem and application lifecycle |
| RDNA2 shaders | General control flow, broader instructions, Wave64, cross-lane operations and mesh stages |
| Graphics | Translated texture sampling, broader resource binding, synchronization and general draw workloads |
| Textures | Authentic Xbox memory layouts and broader compressed-format support |
| Graphics | Translated texture sampling and broader resource binding |
| Textures | Authentic Xbox memory layouts and translated sampling |
| Performance | Production-scale workloads, CPU/GPU profiling and optimized execution |
| Game compatibility | No demonstrated execution of commercial Xbox titles |
@@ -272,6 +302,10 @@ cargo clippy --locked --workspace --all-targets -- -D warnings
cargo test --locked --workspace
```
The format, lint and test trio is the standard check set. The native Metal
passes use Metal API and shader validation; `scripts/audit/status.py --check`
verifies the generated status tables.
### Run native Metal tests
These require a Metal-capable Apple Silicon Mac.
@@ -320,6 +354,9 @@ Testing distinguishes between:
Compiling a shader is not equivalent to proving its GPU output is correct.
### Where the work is heading
See the [roadmap table](#development-milestones) for proposed milestones, and the [changelog](CHANGELOG.md) for the current unreleased additions, such as the native blend pass, indexed draws and the depth pass. The remaining research steps are the outstanding items in [current limitations](#current-limitations).
---
@@ -327,6 +364,10 @@ Compiling a shader is not equivalent to proving its GPU output is correct.
---
### Contributors
[![Contributors](https://contrib.rocks/image?repo=ranveersoni98/Xenora)](https://github.com/ranveersoni98/Xenora/graphs/contributors)
## License
Xenora is licensed under the [GNU General Public License v3 or later](LICENSE).
+13
View File
@@ -0,0 +1,13 @@
// swift-tools-version: 6.0
// SPDX-License-Identifier: GPL-3.0-or-later
// Build with scripts/build-app.sh, which builds the Rust static library first.
import PackageDescription
let package = Package(
name: "Xenora",
platforms: [.macOS(.v14)],
targets: [
.systemLibrary(name: "CXenora", path: "Sources/CXenora"),
.executableTarget(name: "Xenora", dependencies: ["CXenora"]),
]
)
+5
View File
@@ -0,0 +1,5 @@
module CXenora [system] {
header "../../../crates/ffi/include/xenora.h"
link "xenora_ffi"
export *
}
+595
View File
@@ -0,0 +1,595 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//
// Native shell over the versioned C interface. "Run trusted fixture" executes the
// bundled trusted PE fixture (x86-64 translated to ARM64; its draw request is rendered
// by native Metal) and shows the verified read-back frame. No other executable can run.
import AppKit
import CXenora
import Foundation
import SwiftUI
import UniformTypeIdentifiers
struct RuntimeProbe {
var abiVersion: UInt32 = 0
var status: Int32 = -1
var sections: UInt32 = 0
var entryRVA: UInt32 = 0
var connected: Bool { abiVersion == XENORA_ABI_VERSION && status == XENORA_OK }
static func run() -> RuntimeProbe {
var probe = RuntimeProbe(abiVersion: xenora_abi_version())
var session: xenora_session = 0
probe.status = xenora_session_create(XENORA_ABI_VERSION, &session)
guard probe.status == XENORA_OK else { return probe }
defer { _ = xenora_session_destroy(session) }
probe.status = xenora_session_inspect_trusted_fixture(session, &probe.sections, &probe.entryRVA)
return probe
}
var summary: String {
String(format: "abi=%u status=%d sections=%u entry_rva=0x%x", abiVersion, status, sections, entryRVA)
}
}
/// The frame produced by one run of the trusted fixture.
struct GuestFrame {
let status: Int32
let width: Int
let height: Int
let rgba: [UInt8]
static func run() -> GuestFrame {
var session: xenora_session = 0
var status = xenora_session_create(XENORA_ABI_VERSION, &session)
guard status == XENORA_OK else { return GuestFrame(status: status, width: 0, height: 0, rgba: []) }
defer { _ = xenora_session_destroy(session) }
var rgba = [UInt8](repeating: 0, count: Int(XENORA_FIXTURE_FRAME_WIDTH * XENORA_FIXTURE_FRAME_HEIGHT * 4))
var width: UInt32 = 0
var height: UInt32 = 0
status = rgba.withUnsafeMutableBufferPointer { buffer in
xenora_session_run_trusted_fixture(session, buffer.baseAddress, UInt64(buffer.count), &width, &height)
}
return GuestFrame(status: status, width: Int(width), height: Int(height), rgba: status == XENORA_OK ? rgba : [])
}
var image: CGImage? {
guard status == XENORA_OK, let provider = CGDataProvider(data: Data(rgba) as CFData) else { return nil }
return CGImage(
width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: width * 4,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue),
provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent)
}
var summary: String {
let first = rgba.prefix(4).map(String.init).joined(separator: ",")
return "status=\(status) frame=\(width)x\(height) first_pixel=\(first)"
}
}
/// The frame produced by running the textured fixture (Gate 5, #279).
struct TexturedFrame {
let status: Int32
let width: Int
let height: Int
let rgba: [UInt8]
static func run() -> TexturedFrame {
var session: xenora_session = 0
var status = xenora_session_create(XENORA_ABI_VERSION, &session)
guard status == XENORA_OK else { return TexturedFrame(status: status, width: 0, height: 0, rgba: []) }
defer { _ = xenora_session_destroy(session) }
var rgba = [UInt8](repeating: 0, count: 16)
var width: UInt32 = 0
var height: UInt32 = 0
status = rgba.withUnsafeMutableBufferPointer { buffer in
xenora_session_run_textured_fixture(session, buffer.baseAddress, UInt64(buffer.count), &width, &height)
}
return TexturedFrame(status: status, width: Int(width), height: Int(height), rgba: status == XENORA_OK ? rgba : [])
}
var image: CGImage? {
guard status == XENORA_OK, let provider = CGDataProvider(data: Data(rgba) as CFData) else { return nil }
return CGImage(
width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: width * 4,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue),
provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent)
}
var summary: String {
let pixels = rgba.map(String.init).joined(separator: ",")
return "status=\(status) frame=\(width)x\(height) pixels=[\(pixels)]"
}
}
/// Owns the latest fixture run. A class with @Published avoids SwiftUI macros,
/// which the command-line toolchain does not ship.
@MainActor
final class FrameModel: ObservableObject {
@Published var frame: GuestFrame?
@Published var running = false
@Published var texturedFrame: TexturedFrame?
@Published var runningTextured = false
func run() {
running = true
Task {
// The fixture blocks while it executes and renders, so keep it off the main thread.
frame = await Task.detached { GuestFrame.run() }.value
running = false
}
}
func runTextured() {
runningTextured = true
Task {
texturedFrame = await Task.detached { TexturedFrame.run() }.value
runningTextured = false
}
}
}
/// Persistent guest rendering model (Gate 3, #266; Gate 4, #276).
@MainActor
final class FrameLoopModel: ObservableObject {
@Published var state: UInt32 = UInt32(XENORA_LOOP_NONE)
@Published var completed: UInt32 = 0
@Published var frameId: UInt32 = XENORA_NO_FRAME
@Published var image: CGImage?
@Published var errorMessage: String?
@Published var isInteractive: Bool = false
private var session: xenora_session = 0
private var pollTask: Task<Void, Never>?
deinit {
pollTask?.cancel()
if session != 0 {
_ = xenora_session_destroy(session)
}
}
var isRunning: Bool { state == UInt32(XENORA_LOOP_RUNNING) }
var isPaused: Bool { state == UInt32(XENORA_LOOP_PAUSED) }
var canStart: Bool {
session == 0 || state == UInt32(XENORA_LOOP_NONE) || state == UInt32(XENORA_LOOP_FINISHED)
|| state == UInt32(XENORA_LOOP_STOPPED) || state == UInt32(XENORA_LOOP_FAILED)
}
var stateDescription: String {
switch state {
case UInt32(XENORA_LOOP_NONE): return "Idle"
case UInt32(XENORA_LOOP_RUNNING): return "Running"
case UInt32(XENORA_LOOP_PAUSED): return "Paused"
case UInt32(XENORA_LOOP_FINISHED): return "Finished"
case UInt32(XENORA_LOOP_STOPPED): return "Stopped"
case UInt32(XENORA_LOOP_FAILED): return "Failed"
default: return "Unknown (\(state))"
}
}
func start(frameCount: UInt32 = 300) {
errorMessage = nil
if session != 0 {
_ = xenora_session_destroy(session)
session = 0
}
var newSession: xenora_session = 0
let createStatus = xenora_session_create(XENORA_ABI_VERSION, &newSession)
guard createStatus == XENORA_OK else {
errorMessage = "Failed to create session (status \(createStatus))"
return
}
session = newSession
let startStatus = xenora_session_start_frame_loop(session, frameCount)
guard startStatus == XENORA_OK else {
errorMessage = "Failed to start frame loop (status \(startStatus))"
_ = xenora_session_destroy(session)
session = 0
return
}
isInteractive = false
state = UInt32(XENORA_LOOP_RUNNING)
completed = 0
frameId = XENORA_NO_FRAME
image = nil
startPolling()
}
func startInteractive(frameCount: UInt32 = 300) {
errorMessage = nil
if session != 0 {
_ = xenora_session_destroy(session)
session = 0
}
var newSession: xenora_session = 0
let createStatus = xenora_session_create(XENORA_ABI_VERSION, &newSession)
guard createStatus == XENORA_OK else {
errorMessage = "Failed to create session (status \(createStatus))"
return
}
session = newSession
let startStatus = xenora_session_start_interactive_loop(session, frameCount)
guard startStatus == XENORA_OK else {
errorMessage = "Failed to start interactive loop (status \(startStatus))"
_ = xenora_session_destroy(session)
session = 0
return
}
isInteractive = true
state = UInt32(XENORA_LOOP_RUNNING)
completed = 0
frameId = XENORA_NO_FRAME
image = nil
startPolling()
}
func sendInput(buttons: UInt32) {
guard session != 0 else { return }
var input = xenora_input_state(
buttons: buttons,
stick_x: 0,
stick_y: 0,
mouse_dx: 0,
mouse_dy: 0,
mouse_buttons: 0,
connected: 1,
reserved: 0
)
_ = xenora_session_send_input(session, &input)
}
func pause() {
guard session != 0 else { return }
_ = xenora_session_pause_frame_loop(session)
}
func resume() {
guard session != 0 else { return }
_ = xenora_session_resume_frame_loop(session)
}
func stop() {
guard session != 0 else { return }
_ = xenora_session_stop_frame_loop(session)
}
private func startPolling() {
pollTask?.cancel()
pollTask = Task { [weak self] in
while !Task.isCancelled {
try? await Task.sleep(nanoseconds: 16_000_000)
guard let self = self, self.session != 0 else { break }
var st: UInt32 = 0
var comp: UInt32 = 0
var fId: UInt32 = 0
var rgba = [UInt8](repeating: 0, count: Int(XENORA_FIXTURE_FRAME_WIDTH * XENORA_FIXTURE_FRAME_HEIGHT * 4))
let code = rgba.withUnsafeMutableBufferPointer { buffer in
xenora_session_frame_loop_status(
self.session, &st, &comp, &fId, buffer.baseAddress, UInt64(buffer.count))
}
guard code == XENORA_OK else { break }
self.state = st
self.completed = comp
self.frameId = fId
if fId != XENORA_NO_FRAME, let provider = CGDataProvider(data: Data(rgba) as CFData) {
self.image = CGImage(
width: Int(XENORA_FIXTURE_FRAME_WIDTH),
height: Int(XENORA_FIXTURE_FRAME_HEIGHT),
bitsPerComponent: 8,
bitsPerPixel: 32,
bytesPerRow: Int(XENORA_FIXTURE_FRAME_WIDTH) * 4,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue),
provider: provider,
decode: nil,
shouldInterpolate: false,
intent: .defaultIntent
)
}
if st != UInt32(XENORA_LOOP_RUNNING) && st != UInt32(XENORA_LOOP_PAUSED) {
break
}
}
}
}
}
/// Read-only compatibility inspection of a user-chosen file. Nothing in it is executed.
@MainActor
final class InspectionModel: ObservableObject {
static let shared = InspectionModel()
@Published var fileName: String?
@Published var report = ""
@Published var status: Int32 = Int32(XENORA_OK)
@Published var busy = false
@Published var importing = false
func inspect(_ url: URL) {
fileName = url.lastPathComponent
busy = true
Task {
let (newStatus, newReport) = await Task.detached { InspectionModel.run(url) }.value
status = newStatus
report = newReport
busy = false
}
}
nonisolated static func run(_ url: URL) -> (Int32, String) {
let scoped = url.startAccessingSecurityScopedResource()
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
// Check the size before reading so an oversized file is never loaded into memory.
guard let size = (try? url.resourceValues(forKeys: [.fileSizeKey]))?.fileSize else {
return (Int32(XENORA_INVALID_ARGUMENT), "Could not read the file's size.")
}
guard UInt64(size) <= UInt64(XENORA_MAX_INSPECT_BYTES) else {
return (Int32(XENORA_LIMIT_EXCEEDED), "The file is \(size) bytes; inspection accepts at most \(XENORA_MAX_INSPECT_BYTES).")
}
guard let data = try? Data(contentsOf: url) else {
return (Int32(XENORA_INVALID_ARGUMENT), "Could not read the file.")
}
return data.withUnsafeBytes { raw in
let bytes = raw.bindMemory(to: UInt8.self).baseAddress
var required: UInt64 = 0
var probe: CChar = 0
var status = xenora_inspect_executable(bytes, UInt64(data.count), &probe, 1, &required)
guard status == Int32(XENORA_BUFFER_TOO_SMALL) else { return (status, "Inspection failed (status \(status)).") }
var text = [CChar](repeating: 0, count: Int(required))
status = xenora_inspect_executable(bytes, UInt64(data.count), &text, required, &required)
return (status, String(cString: text))
}
}
}
/// Receives files opened from Finder (double-click or Open With).
final class AppDelegate: NSObject, NSApplicationDelegate {
func application(_ application: NSApplication, open urls: [URL]) {
guard let url = urls.first else { return }
MainActor.assumeIsolated { InspectionModel.shared.inspect(url) }
}
}
struct InspectorView: View {
@ObservedObject var model: InspectionModel
var body: some View {
Section("Executable inspection (read-only)") {
HStack {
Button("Open Executable…") { model.importing = true }
Text("or drop a file on this window").foregroundStyle(.secondary)
}
if let name = model.fileName {
LabeledContent("File", value: model.busy ? "\(name) (inspecting…)" : name)
ScrollView {
Text(model.report)
.font(.system(.caption, design: .monospaced))
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}
.frame(minHeight: 160, maxHeight: 320)
}
Text("Opened files are inspected only. Running them is not available.")
.font(.callout)
.foregroundStyle(.secondary)
}
}
}
struct ContentView: View {
let probe = RuntimeProbe.run()
@ObservedObject var model: FrameModel
@ObservedObject var loop: FrameLoopModel
@ObservedObject var inspection = InspectionModel.shared
private var frame: GuestFrame? { model.frame }
private var running: Bool { model.running }
var body: some View {
Form {
InspectorView(model: inspection)
Section("Guest display") {
if let image = frame?.image {
Image(decorative: image, scale: 1)
.resizable()
.interpolation(.none)
.aspectRatio(contentMode: .fit)
.frame(maxWidth: .infinity, minHeight: 120, maxHeight: 240)
.accessibilityLabel("Guest frame, \(frame!.width) by \(frame!.height) pixels")
Text("Guest code ran, its draw was rendered by native Metal, and all \(frame!.width * frame!.height) pixels matched the fixture shader's output.")
.font(.callout)
.foregroundStyle(.secondary)
} else if let frame {
Text("Run failed (status \(frame.status)). No frame is shown.")
.foregroundStyle(.red)
}
if let tImage = model.texturedFrame?.image {
Image(decorative: tImage, scale: 1)
.resizable()
.interpolation(.none)
.aspectRatio(contentMode: .fit)
.frame(maxWidth: .infinity, minHeight: 80, maxHeight: 160)
.accessibilityLabel("Textured guest frame, 2 by 2 pixels")
Text("Textured fixture ran: persistent texture created, dynamically updated, rendered on Metal, and retired.")
.font(.callout)
.foregroundStyle(.secondary)
}
HStack {
Button(running ? "Running…" : "Run trusted fixture") { model.run() }
.disabled(running || !probe.connected)
Button(model.runningTextured ? "Running…" : "Run textured fixture") { model.runTextured() }
.disabled(model.runningTextured || !probe.connected)
}
}
Section("Persistent frame loop") {
if let image = loop.image {
Image(decorative: image, scale: 1)
.resizable()
.interpolation(.none)
.aspectRatio(contentMode: .fit)
.frame(maxWidth: .infinity, minHeight: 120, maxHeight: 240)
.accessibilityLabel("Guest frame #\(loop.frameId)")
Text("Frame #\(loop.frameId) (\(loop.completed) completed) • \(loop.stateDescription)")
.font(.callout)
.foregroundStyle(.secondary)
} else if let error = loop.errorMessage {
Text(error).foregroundStyle(.red)
} else if loop.state != UInt32(XENORA_LOOP_NONE) {
Text("State: \(loop.stateDescription) • \(loop.completed) completed")
.font(.callout)
.foregroundStyle(.secondary)
}
HStack {
Button("Start 300 frames") { loop.start(frameCount: 300) }
.disabled(!loop.canStart || !probe.connected)
Button("Interactive (300 frames)") { loop.startInteractive(frameCount: 300) }
.disabled(!loop.canStart || !probe.connected)
Button("Pause") { loop.pause() }
.disabled(!loop.isRunning)
Button("Resume") { loop.resume() }
.disabled(!loop.isPaused)
Button("Stop") { loop.stop() }
.disabled(!loop.isRunning && !loop.isPaused)
}
if loop.isInteractive && (loop.isRunning || loop.isPaused) {
HStack {
Button("◀ Left") { loop.sendInput(buttons: UInt32(XENORA_INPUT_LEFT)) }
Button("▶ Right") { loop.sendInput(buttons: UInt32(XENORA_INPUT_RIGHT)) }
Button("Release") { loop.sendInput(buttons: UInt32(XENORA_INPUT_NONE)) }
}
Text("Interactive guest: steer the rendered strip across columns 0..3 with Left/Right.")
.font(.caption)
.foregroundStyle(.secondary)
}
}
LabeledContent("Runtime", value: probe.connected ? "Connected" : "Unavailable (status \(probe.status))")
LabeledContent("Interface version", value: "\(probe.abiVersion)")
LabeledContent("Trusted fixture sections", value: "\(probe.sections)")
LabeledContent("Trusted fixture entry RVA", value: String(format: "0x%X", probe.entryRVA))
Text("Only the bundled trusted fixtures (single-frame, frame-loop, and interactive guest) can run. Presentation uses read-back Metal frames. Arbitrary executables are not available yet.")
.foregroundStyle(.secondary)
}
.formStyle(.grouped)
.fileImporter(isPresented: $inspection.importing, allowedContentTypes: [.item]) { result in
if case .success(let url) = result { inspection.inspect(url) }
}
.dropDestination(for: URL.self) { urls, _ in
guard let url = urls.first, url.isFileURL else { return false }
inspection.inspect(url)
return true
}
.frame(minWidth: 520, minHeight: 680)
}
}
struct XenoraApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
let model = FrameModel()
let loop = FrameLoopModel()
var body: some Scene {
WindowGroup("Xenora") { ContentView(model: model, loop: loop) }
}
}
// `--inspect <path>` prints the read-only report for a file and exits with its status.
if let flag = CommandLine.arguments.firstIndex(of: "--inspect"), flag + 1 < CommandLine.arguments.count {
let (status, report) = InspectionModel.run(URL(fileURLWithPath: CommandLine.arguments[flag + 1]))
print(report.hasSuffix("\n") ? report : report + "\n", terminator: "")
print("status=\(status)")
exit(status == Int32(XENORA_OK) ? 0 : 1)
}
// `--smoke-resources` tests persistent texture lifecycle, dynamic subregion updates, and retirement on Metal.
if CommandLine.arguments.contains("--smoke-resources") {
let frame = TexturedFrame.run()
print("smoke-resources: \(frame.summary)")
let expected: [UInt8] = [255, 255, 0, 255, 0, 255, 255, 255, 255, 0, 255, 255, 64, 64, 64, 255]
exit(frame.status == XENORA_OK && frame.width == 2 && frame.height == 2 && frame.rgba == expected ? 0 : 1)
}
// `--smoke-interactive` runs 60 frames with queued inputs on the Metal device and exits.
if CommandLine.arguments.contains("--smoke-interactive") {
var session: xenora_session = 0
guard xenora_session_create(XENORA_ABI_VERSION, &session) == XENORA_OK else {
print("failed to create session")
exit(1)
}
defer { _ = xenora_session_destroy(session) }
guard xenora_session_start_interactive_loop(session, 60) == XENORA_OK else {
print("failed to start interactive loop")
exit(1)
}
for f in 0..<60 {
let btn: UInt32 = (f < 15) ? UInt32(XENORA_INPUT_RIGHT) :
(f < 30) ? UInt32(XENORA_INPUT_NONE) :
(f < 45) ? UInt32(XENORA_INPUT_LEFT) : UInt32(XENORA_INPUT_RIGHT)
var input = xenora_input_state(buttons: btn, stick_x: 0, stick_y: 0, mouse_dx: 0, mouse_dy: 0, mouse_buttons: 0, connected: 1, reserved: 0)
_ = xenora_session_queue_input(session, &input)
}
var state: UInt32 = 0
var completed: UInt32 = 0
var frameId: UInt32 = 0
var rgba = [UInt8](repeating: 0, count: Int(XENORA_FIXTURE_FRAME_WIDTH * XENORA_FIXTURE_FRAME_HEIGHT * 4))
while true {
let code = rgba.withUnsafeMutableBufferPointer { buf in
xenora_session_frame_loop_status(session, &state, &completed, &frameId, buf.baseAddress, UInt64(buf.count))
}
if code != XENORA_OK {
print("frame_loop_status failed: \(code)")
exit(1)
}
if state != UInt32(XENORA_LOOP_RUNNING) { break }
Thread.sleep(forTimeInterval: 0.005)
}
print("interactive: state=\(state) completed=\(completed) frame_id=\(frameId)")
exit(state == UInt32(XENORA_LOOP_FINISHED) && completed == 60 ? 0 : 1)
}
// `--smoke-loop` runs 300 frames on the Metal device and exits; it needs a GPU.
if CommandLine.arguments.contains("--smoke-loop") {
var session: xenora_session = 0
guard xenora_session_create(XENORA_ABI_VERSION, &session) == XENORA_OK else {
print("failed to create session")
exit(1)
}
defer { _ = xenora_session_destroy(session) }
guard xenora_session_start_frame_loop(session, 300) == XENORA_OK else {
print("failed to start frame loop")
exit(1)
}
var state: UInt32 = 0
var completed: UInt32 = 0
var frameId: UInt32 = 0
var rgba = [UInt8](repeating: 0, count: Int(XENORA_FIXTURE_FRAME_WIDTH * XENORA_FIXTURE_FRAME_HEIGHT * 4))
while true {
let code = rgba.withUnsafeMutableBufferPointer { buf in
xenora_session_frame_loop_status(session, &state, &completed, &frameId, buf.baseAddress, UInt64(buf.count))
}
if code != XENORA_OK {
print("frame_loop_status failed: \(code)")
exit(1)
}
if state != UInt32(XENORA_LOOP_RUNNING) { break }
Thread.sleep(forTimeInterval: 0.005)
}
print("state=\(state) completed=\(completed) frame_id=\(frameId)")
exit(state == UInt32(XENORA_LOOP_FINISHED) && completed == 300 ? 0 : 1)
}
// `--smoke-frame` runs the trusted fixture on the Metal device and exits; it needs a GPU.
if CommandLine.arguments.contains("--smoke-frame") {
let frame = GuestFrame.run()
print(frame.summary)
exit(frame.status == XENORA_OK ? 0 : 1)
}
// `--smoke` prints the probe and exits without opening a window, for scripts and CI.
if CommandLine.arguments.contains("--smoke") {
let probe = RuntimeProbe.run()
print(probe.summary)
exit(probe.connected ? 0 : 1)
}
XenoraApp.main()
+2
View File
@@ -9,6 +9,8 @@ rust-version.workspace = true
workspace = true
[dependencies]
xenora-decoder = { path = "../decoder" }
xenora-isa = { path = "../isa" }
xenora-metal = { path = "../metal" }
xenora-ref = { path = "../ref" }
xenora-shader = { path = "../shader" }
+3 -1
View File
@@ -2,6 +2,7 @@
mod demo;
mod runner;
mod shaders;
use std::process::ExitCode;
@@ -40,6 +41,7 @@ fn main() -> ExitCode {
},
Some("run") => runner::command(std::env::args_os().skip(2)),
Some("imports") => imports_command(std::env::args().skip(2).collect()),
Some("shaders") => shaders::command(&std::env::args().skip(2).collect::<Vec<_>>()),
Some("probe") => {
let args: Vec<String> = std::env::args().collect();
let mut pe_path: Option<String> = None;
@@ -132,7 +134,7 @@ fn main() -> ExitCode {
}
}
_ => {
eprintln!("usage: xenora <info|demo|inspect|probe|run|imports>");
eprintln!("usage: xenora <info|demo|inspect|probe|run|imports|shaders>");
ExitCode::from(2)
}
}
+288
View File
@@ -0,0 +1,288 @@
//! `xenora shaders`: instruction inventory and stream inspection.
use std::process::ExitCode;
use xenora_decoder::{Architecture, SEMANTIC_FORMS, decode_at};
use xenora_isa::meta::{self, EncodingFamily, FORMS, identify};
const USAGE: &str = "usage: xenora shaders <coverage [--json] | inspect <gfx1030.bin>>";
pub fn command(args: &[String]) -> ExitCode {
match args.first().map(String::as_str) {
Some("coverage") => coverage(args.get(1).map(String::as_str) == Some("--json")),
Some("inspect") => match args.get(1) {
Some(path) => inspect(path),
None => usage(),
},
_ => usage(),
}
}
fn usage() -> ExitCode {
eprintln!("{USAGE}");
ExitCode::from(2)
}
fn semantic(family: EncodingFamily) -> usize {
SEMANTIC_FORMS
.iter()
.filter(|(_, form_family)| *form_family == family)
.count()
}
/// Per-family counts. "Discovered" forms come from AMD's XML and are identified
/// with their length; "semantic" forms decode into executable instructions.
/// Reference, Metal and native GPU evidence per form stays in docs/status.toml.
fn coverage(json: bool) -> ExitCode {
print!("{}", coverage_report(json));
ExitCode::SUCCESS
}
fn coverage_report(json: bool) -> String {
use std::fmt::Write as _;
let rows: Vec<_> = meta::inventory()
.into_iter()
.map(|(family, discovered)| (family, discovered, semantic(family)))
.collect();
let total: usize = rows.iter().map(|row| row.1).sum();
let supported: usize = rows.iter().map(|row| row.2).sum();
let mut out = String::new();
if json {
let families: Vec<String> = rows
.iter()
.map(|(family, discovered, semantic)| {
format!(
"{{\"family\":\"{}\",\"discovered\":{discovered},\"semantic\":{semantic}}}",
family.name()
)
})
.collect();
writeln!(
out,
"{{\"architecture\":\"gfx1030\",\"source_sha256\":\"{}\",\"discovered\":{total},\"semantic\":{supported},\"families\":[{}]}}",
meta::SOURCE_SHA256,
families.join(",")
)
.unwrap();
} else {
writeln!(
out,
"{:<10} {:>10} {:>9}",
"family", "discovered", "semantic"
)
.unwrap();
for (family, discovered, semantic) in &rows {
writeln!(out, "{:<10} {discovered:>10} {semantic:>9}", family.name()).unwrap();
}
writeln!(out, "{:<10} {total:>10} {supported:>9}", "total").unwrap();
writeln!(
out,
"Semantic forms decode for the operand subsets in docs/status.toml only."
)
.unwrap();
}
out
}
fn inspect(path: &str) -> ExitCode {
let bytes = match std::fs::read(path) {
Ok(bytes) => bytes,
Err(error) => {
eprintln!("{path}: {error}");
return ExitCode::FAILURE;
}
};
let listing = listing(&bytes);
for row in &listing.rows {
println!("{row}");
}
if let Some(failure) = listing.failure {
println!("{failure}");
return ExitCode::FAILURE;
}
println!(
"{} instructions inspected against {} gfx1030 forms; {} without semantic decoding",
listing.rows.len(),
FORMS.len(),
listing.unsupported
);
ExitCode::SUCCESS
}
/// The printed rows of `xenora shaders inspect`, the number of rows that do
/// not decode into executable instructions and the identification failure
/// that ended the stream early, if any.
struct Listing {
rows: Vec<String>,
unsupported: usize,
failure: Option<String>,
}
fn listing(bytes: &[u8]) -> Listing {
let mut listing = Listing {
rows: Vec::new(),
unsupported: 0,
failure: None,
};
// Identify every instruction first: a branch target is valid only if it
// lands on one of these boundaries, which no single instruction can show.
let mut forms = Vec::new();
let mut offset = 0;
while offset < bytes.len() {
match identify(&bytes[offset..]) {
Ok(found) => {
forms.push((offset, found));
offset += found.len;
}
Err(error) => {
listing.failure = Some(format!("{offset:#06x} decode failure: {error}"));
break;
}
}
}
let boundary = |target: usize| forms.binary_search_by_key(&target, |form| form.0).is_ok();
// Past the last identified instruction the boundaries are unknown.
let identified = forms
.last()
.map_or(0, |&(offset, found)| offset + found.len);
for &(offset, found) in &forms {
let instruction = &bytes[offset..offset + found.len];
let words: Vec<String> = instruction
.chunks(4)
.map(|chunk| format!("{:08x}", u32::from_le_bytes(chunk.try_into().unwrap())))
.collect();
let status = match decode_at(Architecture::Gfx1030, &bytes[..offset + found.len], offset) {
Ok(decoded) => match decoded.branch_target() {
Some(target) if listing.failure.is_some() && target >= identified => {
format!("branch target {target:#04x} unverified: stream not identified there")
}
Some(target) if !boundary(target) => {
format!("invalid branch target {target:#04x}")
}
_ => "semantic".to_owned(),
},
Err(error) if SEMANTIC_FORMS.contains(&(found.form.name, found.form.family)) => {
format!("unsupported operands: {error}")
}
Err(_) => "unsupported instruction semantics".to_owned(),
};
if status != "semantic" {
listing.unsupported += 1;
}
listing.rows.push(format!(
"{offset:#06x} {:<8} {:<28} {:<26} {status}",
found.form.family.name(),
found.form.name.to_ascii_lowercase(),
words.join(" ")
));
}
listing
}
#[cfg(test)]
mod tests {
use super::{coverage_report, listing};
use xenora_decoder::SEMANTIC_FORMS;
use xenora_isa::meta::{EncodingFamily, FORMS};
#[test]
fn coverage_totals_match_the_generated_table() {
let json = coverage_report(true);
assert!(json.starts_with("{\"architecture\":\"gfx1030\""), "{json}");
assert!(json.ends_with("}]}\n"), "{json}");
assert_eq!(json.matches('{').count(), json.matches('}').count());
let totals = format!(
"\"discovered\":{},\"semantic\":{},\"families\":[",
FORMS.len(),
SEMANTIC_FORMS.len()
);
assert!(json.contains(&totals), "{json}");
let families: Vec<usize> = json
.split("{\"family\":")
.skip(1)
.map(|row| {
let count = row.split("\"discovered\":").nth(1).unwrap();
count[..count.find(',').unwrap()].parse().unwrap()
})
.collect();
assert_eq!(families.len(), EncodingFamily::ALL.len());
assert_eq!(families.iter().sum::<usize>(), FORMS.len());
let text = coverage_report(false);
let total = format!(
"{:<10} {:>10} {:>9}\n",
"total",
FORMS.len(),
SEMANTIC_FORMS.len()
);
assert!(text.contains(&total), "{text}");
}
fn program(words: &[u32]) -> Vec<u8> {
words.iter().flat_map(|word| word.to_le_bytes()).collect()
}
#[test]
fn branches_in_a_valid_program_are_semantic() {
let fixture = include_bytes!("../../../fixtures/rdna2/bitwise-branch.bin");
let listing = listing(fixture);
assert_eq!(listing.failure, None);
assert_eq!(listing.rows.len(), 15);
let branches: Vec<_> = listing
.rows
.iter()
.filter(|row| row.contains("branch"))
.collect();
assert_eq!(branches.len(), 3);
for row in &branches {
assert!(row.ends_with(" semantic"), "{row}");
}
assert_eq!(listing.unsupported, 0);
}
#[test]
fn targets_past_an_identification_failure_are_unverified() {
// s_branch 1 targets 0x08; 0xbfff0000 is not a gfx1030 form, so
// nothing past 0x04 is identified; s_endpgm.
let listing = listing(&program(&[0xbf82_0001, 0xbfff_0000, 0xbf81_0000]));
assert!(listing.failure.as_deref().unwrap().starts_with("0x0004"));
assert_eq!(listing.rows.len(), 1);
assert!(
listing.rows[0].ends_with("branch target 0x08 unverified: stream not identified there"),
"{}",
listing.rows[0]
);
}
#[test]
fn add_fixture_is_fully_semantic() {
let listing = listing(include_bytes!("../../../fixtures/rdna2/add.bin"));
assert_eq!(listing.failure, None);
assert_eq!(listing.rows.len(), 7);
assert_eq!(listing.unsupported, 0);
}
#[test]
fn branch_targets_are_checked_against_the_whole_stream() {
// s_branch 1 skips one word; s_cbranch_scc0 1 lands inside the
// two-word v_mov_b32 literal form; s_endpgm.
let listing = listing(&program(&[
0xbf82_0001,
0xbf84_0001,
0x7e04_02ff,
0x00ff_00ff,
0xbf81_0000,
]));
assert_eq!(listing.failure, None);
assert!(
listing.rows[0].ends_with(" semantic"),
"{}",
listing.rows[0]
);
assert!(
listing.rows[1].ends_with("invalid branch target 0x0c"),
"{}",
listing.rows[1]
);
assert_eq!(listing.unsupported, 1);
}
}
+252 -25
View File
@@ -3,15 +3,84 @@
use std::fmt;
pub use xenora_isa::{
Architecture, ExportTarget, Instruction, InterpolationPhase, ScalarSource, VectorSource,
Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp,
ScalarCompareOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorCompareOp, VectorSource,
};
use xenora_isa::{
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ,
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT,
V_ADD_F32, V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_INTERP_P1_F32, V_INTERP_P2_F32,
V_LSHLREV_B32, V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, V_ADD_F32,
V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_CMP_EQ_I32, V_CMP_EQ_U32, V_CMP_GE_I32, V_CMP_GE_U32,
V_CMP_GT_I32, V_CMP_GT_U32, V_CMP_LE_I32, V_CMP_LE_U32, V_CMP_LT_I32, V_CMP_LT_U32,
V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32, V_LSHRREV_B32,
V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32, VCC_LO,
};
use xenora_isa::meta::EncodingFamily;
use xenora_isa::semantics::FORM_IDS;
pub use xenora_isa::semantics::VectorBinary;
/// Metadata forms that [`decode`] turns into an [`Instruction`] for at least one
/// operand combination: the hand-written forms below followed by every form of
/// the semantic registry ([`xenora_isa::semantics::FORM_IDS`]). Operand
/// restrictions are listed in docs/status.toml; every other form in
/// [`xenora_isa::meta::FORMS`] is rejected as unsupported.
pub const SEMANTIC_FORMS: [(&str, EncodingFamily); HANDWRITTEN_FORMS.len() + FORM_IDS.len()] =
concat_forms();
const fn concat_forms<const N: usize>() -> [(&'static str, EncodingFamily); N] {
let mut forms = [("", EncodingFamily::Sop2); N];
let mut index = 0;
while index < N {
forms[index] = if index < HANDWRITTEN_FORMS.len() {
HANDWRITTEN_FORMS[index]
} else {
FORM_IDS[index - HANDWRITTEN_FORMS.len()]
};
index += 1;
}
forms
}
/// Decoded forms not yet described by the semantic registry.
const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 36] = [
("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf),
("BUFFER_STORE_DWORD", EncodingFamily::Mubuf),
("EXP", EncodingFamily::Exp),
("IMAGE_SAMPLE_LZ", EncodingFamily::Mimg),
("S_BRANCH", EncodingFamily::Sopp),
("S_CBRANCH_EXECZ", EncodingFamily::Sopp),
("S_CBRANCH_SCC0", EncodingFamily::Sopp),
("S_CBRANCH_VCCZ", EncodingFamily::Sopp),
("S_ENDPGM", EncodingFamily::Sopp),
("S_MOV_B32", EncodingFamily::Sop1),
("S_WAITCNT", EncodingFamily::Sopp),
("S_WAITCNT_VSCNT", EncodingFamily::Sopk),
("V_ADD_F32", EncodingFamily::Vop2),
("V_ADD_NC_U32", EncodingFamily::Vop3),
("V_AND_B32", EncodingFamily::Vop2),
("V_ASHRREV_I32", EncodingFamily::Vop2),
("V_CMP_EQ_I32", EncodingFamily::Vopc),
("V_CMP_EQ_U32", EncodingFamily::Vopc),
("V_CMP_GE_I32", EncodingFamily::Vopc),
("V_CMP_GE_U32", EncodingFamily::Vopc),
("V_CMP_GT_I32", EncodingFamily::Vopc),
("V_CMP_GT_U32", EncodingFamily::Vopc),
("V_CMP_LE_I32", EncodingFamily::Vopc),
("V_CMP_LE_U32", EncodingFamily::Vopc),
("V_CMP_LT_I32", EncodingFamily::Vopc),
("V_CMP_LT_U32", EncodingFamily::Vopc),
("V_CMP_NE_I32", EncodingFamily::Vopc),
("V_CMP_NE_U32", EncodingFamily::Vopc),
("V_INTERP_P1_F32", EncodingFamily::Vintrp),
("V_INTERP_P2_F32", EncodingFamily::Vintrp),
("V_LSHLREV_B32", EncodingFamily::Vop2),
("V_LSHRREV_B32", EncodingFamily::Vop2),
("V_MOV_B32", EncodingFamily::Vop1),
("V_MUL_F32", EncodingFamily::Vop2),
("V_OR_B32", EncodingFamily::Vop2),
("V_XOR_B32", EncodingFamily::Vop2),
];
/// A successfully decoded instruction and its location in the input stream.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct DecodedInstruction {
@@ -23,6 +92,20 @@ pub struct DecodedInstruction {
pub instruction: Instruction,
}
impl DecodedInstruction {
/// Destination byte offset of a branch, from the start of the stream.
#[must_use]
pub fn branch_target(&self) -> Option<usize> {
match self.instruction {
Instruction::Branch { target }
| Instruction::BranchSccZero { target }
| Instruction::BranchExecZero { target }
| Instruction::BranchVccZero { target } => Some(target),
_ => None,
}
}
}
impl fmt::Display for DecodedInstruction {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{:04x}: {}", self.offset, self.instruction)
@@ -107,26 +190,15 @@ pub fn decode(
architecture: Architecture,
bytes: &[u8],
) -> Result<Vec<DecodedInstruction>, DecodeError> {
let decode_instruction = match architecture {
Architecture::Gfx1030 => decode_gfx1030,
};
let mut result = Vec::new();
let mut offset = 0;
while offset < bytes.len() {
let (instruction, byte_len) = decode_instruction(&bytes[offset..], offset)
.map_err(|kind| DecodeError { offset, kind })?;
result.push(DecodedInstruction {
offset,
byte_len,
instruction,
});
offset += usize::from(byte_len);
let decoded = decode_at(architecture, bytes, offset)?;
offset += usize::from(decoded.byte_len);
result.push(decoded);
}
for decoded in &result {
if let Instruction::Branch { target }
| Instruction::BranchSccZero { target }
| Instruction::BranchExecZero { target }
| Instruction::BranchVccZero { target } = decoded.instruction
if let Some(target) = decoded.branch_target()
&& result
.binary_search_by_key(&target, |item| item.offset)
.is_err()
@@ -140,6 +212,32 @@ pub fn decode(
Ok(result)
}
/// Decodes the one instruction that starts at `offset` in `bytes`. Branch
/// targets are stream offsets, but whether they land on an instruction
/// boundary is left to the caller, which knows the rest of the stream.
///
/// # Errors
///
/// Returns `offset` with a truncated instruction, unsupported opcode or
/// unsupported form. An `offset` at or past the end is truncated.
pub fn decode_at(
architecture: Architecture,
bytes: &[u8],
offset: usize,
) -> Result<DecodedInstruction, DecodeError> {
let decode_instruction = match architecture {
Architecture::Gfx1030 => decode_gfx1030,
};
let rest = bytes.get(offset..).unwrap_or_default();
let (instruction, byte_len) =
decode_instruction(rest, offset).map_err(|kind| DecodeError { offset, kind })?;
Ok(DecodedInstruction {
offset,
byte_len,
instruction,
})
}
fn word(bytes: &[u8], end: u8) -> Result<u32, DecodeErrorKind> {
let end_index = usize::from(end);
let Some(word) = bytes
@@ -240,6 +338,27 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
if V_MOV_B32.matches(first) {
return move_b32(first, bytes);
}
{
use CompareRelation::{Equal, Greater, GreaterOrEqual, Less, LessOrEqual, NotEqual};
for (opcode, relation, signed) in [
(V_CMP_LT_I32, Less, true),
(V_CMP_EQ_I32, Equal, true),
(V_CMP_LE_I32, LessOrEqual, true),
(V_CMP_GT_I32, Greater, true),
(V_CMP_NE_I32, NotEqual, true),
(V_CMP_GE_I32, GreaterOrEqual, true),
(V_CMP_LT_U32, Less, false),
(V_CMP_EQ_U32, Equal, false),
(V_CMP_LE_U32, LessOrEqual, false),
(V_CMP_GT_U32, Greater, false),
(V_CMP_NE_U32, NotEqual, false),
(V_CMP_GE_U32, GreaterOrEqual, false),
] {
if opcode.matches(first) {
return vector_compare(VectorCompareOp { relation, signed }, first, bytes);
}
}
}
if V_ADD_NC_U32.matches(first) {
let len = V_ADD_NC_U32.byte_len();
let second = word(bytes, len)?;
@@ -256,19 +375,30 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
let (src, len) = scalar_source(first as u8, bytes, "s_mov_b32")?;
return Ok((Instruction::ScalarMoveB32 { dst, src }, len));
}
if S_CMP_EQ_U32.matches(first) {
if let Some(op) = ScalarUnaryOp::from_word(first) {
// SOP1: SSRC0 in bits 0-7, SDST in bits 16-22.
let mnemonic = op.mnemonic();
let dst = ((first >> 16) & 0x7f) as u8;
if dst > 105 {
return Err(unsupported(mnemonic, "expected a normal SGPR destination"));
}
let (src, len) = scalar_source(first as u8, bytes, mnemonic)?;
return Ok((Instruction::ScalarUnary { op, dst, src }, len));
}
if let Some(op) = ScalarCompareOp::from_word(first) {
let mnemonic = op.mnemonic();
let src0_bits = first as u8;
let src1_bits = (first >> 8) as u8;
if src0_bits == 255 && src1_bits == 255 {
return Err(unsupported(
"s_cmp_eq_u32",
mnemonic,
"only one source may select a literal",
));
}
let (src0, len0) = scalar_source(src0_bits, bytes, "s_cmp_eq_u32")?;
let (src1, len1) = scalar_source(src1_bits, bytes, "s_cmp_eq_u32")?;
let (src0, len0) = scalar_source(src0_bits, bytes, mnemonic)?;
let (src1, len1) = scalar_source(src1_bits, bytes, mnemonic)?;
return Ok((
Instruction::ScalarCompareEqU32 { src0, src1 },
Instruction::ScalarCompare { op, src0, src1 },
len0.max(len1),
));
}
@@ -276,6 +406,9 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
let target = branch_target(first, offset, "s_branch")?;
return Ok((Instruction::Branch { target }, S_BRANCH.byte_len()));
}
if let Some(op) = ScalarAluOp::from_word(first) {
return scalar_alu(op, first, bytes);
}
if S_CBRANCH_SCC0.matches(first) {
let target = branch_target(first, offset, "s_cbranch_scc0")?;
return Ok((
@@ -297,6 +430,21 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
S_CBRANCH_VCCZ.byte_len(),
));
}
if let Some(op) = VectorAluOp::from_word(first) {
// VOP2: SRC0 in bits 0-8, VSRC1 in bits 9-16, VDST in bits 17-24.
let dst = ((first >> 17) & 0xff) as u8;
let src1 = ((first >> 9) & 0xff) as u8;
let (src0, len) = vector_src0(first, bytes, op.assembly_name())?;
return Ok((
Instruction::VectorAlu {
op,
dst,
src0,
src1,
},
len,
));
}
if V_LSHLREV_B32.matches(first) {
let (dst, src0, src1) = vop2_registers(first, "v_lshlrev_b32_e32")?;
return Ok((
@@ -384,6 +532,39 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
Err(DecodeErrorKind::UnsupportedOpcode { word: first })
}
/// SOP2: SSRC0 in bits 0-7, SSRC1 in bits 8-15, SDST in bits 16-22.
/// Other SOP2 opcodes stay unsupported.
fn scalar_alu(
op: ScalarAluOp,
first: u32,
bytes: &[u8],
) -> Result<(Instruction, u8), DecodeErrorKind> {
let mnemonic = op.mnemonic();
let dst = ((first >> 16) & 0x7f) as u8;
if dst > 105 {
return Err(unsupported(mnemonic, "expected a normal SGPR destination"));
}
let src0_bits = first as u8;
let src1_bits = (first >> 8) as u8;
if src0_bits == 255 && src1_bits == 255 {
return Err(unsupported(
mnemonic,
"only one source may select a literal",
));
}
let (src0, len0) = scalar_source(src0_bits, bytes, mnemonic)?;
let (src1, len1) = scalar_source(src1_bits, bytes, mnemonic)?;
Ok((
Instruction::ScalarAlu {
op,
dst,
src0,
src1,
},
len0.max(len1),
))
}
fn scalar_source(
bits: u8,
bytes: &[u8],
@@ -525,11 +706,57 @@ fn buffer_operands(
Ok((data, index, resource))
}
/// VOPC: SRC0 in bits 0-8, VSRC1 in bits 9-16 (RDNA 2 ISA section 12.9). The
/// destination is implicitly `vcc_lo`. SRC0 excludes inline float constants,
/// `vcc_hi`, EXEC, M0, TTMPs and the condition selectors (SDWA 249, DPP 250/233).
fn vector_compare(
op: VectorCompareOp,
first: u32,
bytes: &[u8],
) -> Result<(Instruction, u8), DecodeErrorKind> {
let src1 = ((first >> 9) & 0xff) as u8;
let (src0, len) = vector_src0(first, bytes, op.mnemonic())?;
Ok((Instruction::VectorCompare { op, src0, src1 }, len))
}
/// The 9-bit SRC0 of a VOPC or VOP2 word: a VGPR, `s0-s105`, `vcc_lo`, an
/// inline integer -16..64 or a literal word; everything else is unsupported.
fn vector_src0(
first: u32,
bytes: &[u8],
mnemonic: &'static str,
) -> Result<(VectorSource, u8), DecodeErrorKind> {
let source = first & 0x1ff;
let base_len = 4;
Ok(match source {
0..=106 => (VectorSource::Scalar(source as u8), base_len),
128..=192 => (VectorSource::Immediate(source - 128), base_len),
193..=208 => (
VectorSource::Immediate(192u32.wrapping_sub(source)),
base_len,
),
255 => {
let len = base_len + 4;
(VectorSource::Immediate(word(bytes, len)?), len)
}
256..=511 => (VectorSource::Register(source as u8), base_len),
_ => {
return Err(unsupported(
mnemonic,
"expected a VGPR, normal SGPR, vcc_lo, inline integer or literal",
));
}
})
}
fn move_b32(first: u32, bytes: &[u8]) -> Result<(Instruction, u8), DecodeErrorKind> {
let dst = (first >> 17) as u8;
let source = first & 0x1ff;
let base_len = V_MOV_B32.byte_len();
let (src, len) = match source {
0..=105 => (VectorSource::Scalar(source as u8), base_len),
// vcc_lo, which may hold a lane-derived compare mask (docs/shaders/vector-compare.md).
106 => (VectorSource::Scalar(VCC_LO), base_len),
128..=192 => (VectorSource::Immediate(source - 128), base_len),
193..=208 => (
VectorSource::Immediate(192u32.wrapping_sub(source)),
@@ -545,7 +772,7 @@ fn move_b32(first: u32, bytes: &[u8]) -> Result<(Instruction, u8), DecodeErrorKi
_ => {
return Err(unsupported(
"v_mov_b32_e32",
"expected a VGPR, inline integer, inline +1.0f or literal",
"expected a VGPR, normal SGPR, vcc_lo, inline integer, inline +1.0f or literal",
));
}
};
+253 -9
View File
@@ -3,10 +3,14 @@ use std::path::PathBuf;
use std::process::{Command, Stdio};
use xenora_decoder::{
Architecture, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction, ScalarSource,
VectorSource, decode,
Architecture, CompareRelation, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction,
ScalarAluOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorSource, decode, decode_at,
};
use xenora_isa::semantics::Signedness;
use xenora_ref::{
BranchCondition, CompareSource, Comparison, Op, ScalarAlu, ScalarUnary, Source, VectorAlu,
VectorInteger,
};
use xenora_ref::{BranchCondition, Op, Source, VectorAlu};
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin");
const BITWISE_FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/bitwise-branch.bin");
@@ -97,7 +101,12 @@ fn rejects_other_opcodes_and_noncanonical_operands() {
(&[0xe070_2000, 0x801b_0100], "buffer_store_dword"),
(&[0xbf8c_3f71], "s_waitcnt"),
(&[0xbbfd_0001], "s_waitcnt_vscnt"),
(&[0x7e04_0200], "v_mov_b32_e32"),
(&[0x7e04_026b], "v_mov_b32_e32"), // VCC_HI is outside the source subset.
(&[0x7d02_046b], "v_cmp_lt_i32_e32"), // VCC_HI source.
(&[0x7d02_047e], "v_cmp_lt_i32_e32"), // EXEC_LO source.
(&[0x7d02_04f0], "v_cmp_lt_i32_e32"), // Inline 0.5 source.
(&[0x7d84_04f9, 0x0606_0601], "v_cmp_eq_u32_e32"), // SDWA.
(&[0x7d84_04fa, 0], "v_cmp_eq_u32_e32"), // DPP16.
(&[0x7e04_02fa, 0], "v_mov_b32_e32"),
(&[0xd525_8001, 0x0202_0501], "v_add_nc_u32_e64"),
(&[0xd525_0001, 0x0202_0480], "v_add_nc_u32_e64"),
@@ -281,6 +290,7 @@ fn reference_source(vector: VectorSource) -> Source {
match vector {
VectorSource::Register(reg) => Source::Register(reg),
VectorSource::Immediate(bits) => Source::Immediate(bits),
VectorSource::Scalar(_) => unreachable!("mapped to Op::MoveScalar"),
}
}
@@ -313,11 +323,90 @@ fn reference_op(instruction: Instruction) -> Op {
},
Instruction::WaitLoad => Op::WaitRead,
Instruction::WaitStore => Op::WaitWrite,
Instruction::MoveB32 {
dst,
src: VectorSource::Scalar(src),
} => Op::MoveScalar(dst, src),
Instruction::MoveB32 { dst, src } => Op::Move(dst, reference_source(src)),
Instruction::ScalarAlu {
op,
dst,
src0,
src1,
} => Op::Scalar(
match op {
ScalarAluOp::AddU32 => ScalarAlu::Add,
ScalarAluOp::SubU32 => ScalarAlu::Subtract,
ScalarAluOp::AddI32 => ScalarAlu::AddSigned,
ScalarAluOp::SubI32 => ScalarAlu::SubtractSigned,
ScalarAluOp::AddcU32 => ScalarAlu::AddWithCarry,
ScalarAluOp::SubbU32 => ScalarAlu::SubtractWithBorrow,
ScalarAluOp::AndB32 => ScalarAlu::And,
ScalarAluOp::OrB32 => ScalarAlu::Or,
ScalarAluOp::XorB32 => ScalarAlu::Xor,
ScalarAluOp::Andn2B32 => ScalarAlu::AndNot,
ScalarAluOp::Orn2B32 => ScalarAlu::OrNot,
ScalarAluOp::NandB32 => ScalarAlu::Nand,
ScalarAluOp::NorB32 => ScalarAlu::Nor,
ScalarAluOp::XnorB32 => ScalarAlu::Xnor,
ScalarAluOp::LshlB32 => ScalarAlu::ShiftLeft,
ScalarAluOp::LshrB32 => ScalarAlu::ShiftRight,
ScalarAluOp::AshrI32 => ScalarAlu::ArithmeticShiftRight,
ScalarAluOp::MinI32 => ScalarAlu::Minimum { signed: true },
ScalarAluOp::MinU32 => ScalarAlu::Minimum { signed: false },
ScalarAluOp::MaxI32 => ScalarAlu::Maximum { signed: true },
ScalarAluOp::MaxU32 => ScalarAlu::Maximum { signed: false },
ScalarAluOp::CselectB32 => ScalarAlu::Select,
ScalarAluOp::BfmB32 => ScalarAlu::BitfieldMask,
ScalarAluOp::MulI32 => ScalarAlu::Multiply,
ScalarAluOp::BfeU32 => ScalarAlu::BitfieldExtract { signed: false },
ScalarAluOp::BfeI32 => ScalarAlu::BitfieldExtract { signed: true },
ScalarAluOp::AbsdiffI32 => ScalarAlu::AbsoluteDifference,
ScalarAluOp::Lshl1AddU32 => ScalarAlu::ShiftLeftAdd(1),
ScalarAluOp::Lshl2AddU32 => ScalarAlu::ShiftLeftAdd(2),
ScalarAluOp::Lshl3AddU32 => ScalarAlu::ShiftLeftAdd(3),
ScalarAluOp::Lshl4AddU32 => ScalarAlu::ShiftLeftAdd(4),
ScalarAluOp::MulHiU32 => ScalarAlu::MultiplyHigh { signed: false },
ScalarAluOp::MulHiI32 => ScalarAlu::MultiplyHigh { signed: true },
},
dst,
reference_scalar(src0),
reference_scalar(src1),
),
Instruction::AddNoCarryU32 { dst, src0, src1 } => Op::Add(dst, src0, src1),
Instruction::ScalarMoveB32 { dst, src } => Op::ScalarMove(dst, reference_scalar(src)),
Instruction::ScalarCompareEqU32 { src0, src1 } => {
Op::CompareEqual(reference_scalar(src0), reference_scalar(src1))
Instruction::ScalarUnary { op, dst, src } => Op::ScalarUnary(
match op {
ScalarUnaryOp::NotB32 => ScalarUnary::Not,
ScalarUnaryOp::BrevB32 => ScalarUnary::ReverseBits,
ScalarUnaryOp::Bcnt0I32B32 => ScalarUnary::CountZeros,
ScalarUnaryOp::Bcnt1I32B32 => ScalarUnary::CountOnes,
ScalarUnaryOp::Ff0I32B32 => ScalarUnary::FindFirstZero,
ScalarUnaryOp::Ff1I32B32 => ScalarUnary::FindFirstOne,
ScalarUnaryOp::FlbitI32B32 => ScalarUnary::FindLastBit,
ScalarUnaryOp::FlbitI32 => ScalarUnary::FindLastSignBit,
ScalarUnaryOp::SextI32I8 => ScalarUnary::SignExtendByte,
ScalarUnaryOp::SextI32I16 => ScalarUnary::SignExtendShort,
ScalarUnaryOp::AbsI32 => ScalarUnary::Absolute,
},
dst,
reference_scalar(src),
),
Instruction::ScalarCompare { op, src0, src1 } => {
let (src0, src1) = (reference_scalar(src0), reference_scalar(src1));
// The reference keeps CompareEqual for EQ and uses its VOPC relation
// offsets (LT 1, EQ 2, LE 3, GT 4, NE 5, GE 6) for the rest.
match op.relation() {
CompareRelation::Equal => Op::CompareEqual(src0, src1),
relation => Op::ScalarCompare(
Comparison {
offset: relation as u8 + 1,
signed: op.semantics().signedness == Signedness::Signed,
},
src0,
src1,
),
}
}
Instruction::BranchSccZero { target } => Op::Branch {
target,
@@ -363,6 +452,53 @@ fn reference_op(instruction: Instruction) -> Op {
panic!("compute reference matrix received a graphics/image instruction")
}
Instruction::VectorCompare { op, src0, src1 } => Op::Compare(
Comparison {
offset: match op.relation {
CompareRelation::Less => 1,
CompareRelation::Equal => 2,
CompareRelation::LessOrEqual => 3,
CompareRelation::Greater => 4,
CompareRelation::NotEqual => 5,
CompareRelation::GreaterOrEqual => 6,
},
signed: op.signed,
},
match src0 {
VectorSource::Register(reg) => CompareSource::Vector(reg),
VectorSource::Scalar(reg) => CompareSource::Scalar(reg),
VectorSource::Immediate(bits) => CompareSource::Immediate(bits),
},
src1,
),
Instruction::VectorAlu {
op,
dst,
src0,
src1,
} => Op::VectorInteger(
match op {
VectorAluOp::MulI32I24 => VectorInteger::Multiply24 { signed: true },
VectorAluOp::MulHiI32I24 => VectorInteger::MultiplyHigh24 { signed: true },
VectorAluOp::MulU32U24 => VectorInteger::Multiply24 { signed: false },
VectorAluOp::MulHiU32U24 => VectorInteger::MultiplyHigh24 { signed: false },
VectorAluOp::MinI32 => VectorInteger::Minimum { signed: true },
VectorAluOp::MaxI32 => VectorInteger::Maximum { signed: true },
VectorAluOp::MinU32 => VectorInteger::Minimum { signed: false },
VectorAluOp::MaxU32 => VectorInteger::Maximum { signed: false },
VectorAluOp::XnorB32 => VectorInteger::Xnor,
VectorAluOp::AddNcU32 => VectorInteger::Add,
VectorAluOp::SubNcU32 => VectorInteger::Subtract,
VectorAluOp::SubrevNcU32 => VectorInteger::SubtractReverse,
},
dst,
match src0 {
VectorSource::Register(reg) => CompareSource::Vector(reg),
VectorSource::Scalar(reg) => CompareSource::Scalar(reg),
VectorSource::Immediate(bits) => CompareSource::Immediate(bits),
},
src1,
),
Instruction::EndProgram => Op::End,
}
}
@@ -383,12 +519,19 @@ fn compares_fixture_instructions_against_llvm() {
OR_FIXTURE,
SHIFT_FIXTURE,
include_bytes!("../../../fixtures/rdna2/ashr.bin"),
include_bytes!("../../../fixtures/rdna2/scalar-alu.bin"),
include_bytes!("../../../fixtures/rdna2/scalar-logic.bin"),
include_bytes!("../../../fixtures/rdna2/scalar-compare.bin"),
include_bytes!("../../../fixtures/rdna2/scalar-unary.bin"),
include_bytes!("../../../fixtures/rdna2/scalar-arith.bin"),
include_bytes!("../../../fixtures/rdna2/vector-integer.bin"),
include_bytes!("../../../fixtures/rdna2/vector-compare.bin"),
high_registers,
&matrix,
] {
count += compare_against_llvm(fixture, &mut forms);
}
assert_eq!(forms.len(), 21, "forms compared: {forms:?}");
assert_eq!(forms.len(), 100, "forms compared: {forms:?}");
eprintln!(
"{count} three-way instruction comparisons across {} forms",
forms.len()
@@ -396,6 +539,7 @@ fn compares_fixture_instructions_against_llvm() {
}
fn assemble_matrix() -> Vec<u8> {
use std::fmt::Write as _;
// Cover register banks and extrema, immediate classes in both scalar
// compare positions, zero displacement and branches over literal words.
let mut assembly = String::from(
@@ -433,13 +577,48 @@ fn assemble_matrix() -> Vec<u8> {
v_mov_b32_e32 v255, lit(0x1)
s_mov_b32 s105, lit(0x1)
s_cmp_eq_u32 s105, lit(0x1)
s_add_u32 s105, s104, 0xdeadbeef
s_add_u32 s8, -16, 64
s_sub_u32 s105, s1, s2
s_sub_u32 s9, 0xdeadbeef, -16
s_addc_u32 s104, 0xdeadbeef, s105
s_subb_u32 s0, s0, s0
s_add_i32 s101, 0x7fffffff, s100
s_sub_i32 s100, -16, 0x80000000
s_and_b32 s1, -1, s2
s_or_b32 s103, s3, 0x80000000
s_xor_b32 s102, s104, -16
s_xor_b32 s7, s7, lit(0x1)
v_mov_b32_e32 v255, s105
v_mov_b32_e32 v0, s0
v_mov_b32_e32 v128, vcc_lo
",
);
use std::fmt::Write as _;
// Every supported VOPC form with each source class: VGPR, SGPR, vcc_lo,
// inline integers at both ends, inline zero and a literal.
for relation in ["lt", "eq", "le", "gt", "ne", "ge"] {
for kind in ["i32", "u32"] {
for src0 in [
"v255",
"v0",
"s0",
"s105",
"vcc_lo",
"-16",
"64",
"0",
"0x80000000",
] {
writeln!(assembly, "v_cmp_{relation}_{kind}_e32 vcc_lo, {src0}, v128").unwrap();
}
writeln!(assembly, "v_cmp_{relation}_{kind}_e32 vcc_lo, v1, v255").unwrap();
}
}
for value in -16..=64 {
writeln!(assembly, "v_mov_b32_e32 v255, {value}").unwrap();
writeln!(assembly, "s_mov_b32 s105, {value}").unwrap();
writeln!(assembly, "s_cmp_eq_u32 {value}, {value}").unwrap();
writeln!(assembly, "s_add_u32 s10, {value}, s11").unwrap();
}
assembly.push_str("s_endpgm\n");
let output = llvm_mc(&[], assembly.as_bytes());
@@ -563,7 +742,17 @@ fn distinguishes_llvm_invalid_encodings_from_xenora_subset_rejections() {
&[0xd516_0001],
];
let outside_subset: &[&[u32]] = &[
&[0x7e04_0200], // VOP1 SGPR source
&[0x7e04_026b], // VOP1 VCC_HI source
&[0x7da2_0501], // v_cmpx_eq_u32_e32
&[0x7d00_0501], // v_cmp_f_i32_e32
&[0x7d0e_0501], // v_cmp_t_i32_e32
&[0xd482_006a, 0x0002_0501], // v_cmp_lt_i32_e64
&[0x8788_0908], // s_and_b64
&[0x8008_ffff, 0x1234_5678], // SOP2 with two literal sources
&[0x806c_0908], // SOP2 TTMP destination
&[0x807e_0908], // SOP2 EXEC_LO destination
&[0x806a_0908], // SOP2 VCC_LO destination
&[0x8008_096a], // SOP2 VCC_LO source
&[0x3803_fe80], // OR with an inline SRC0
&[0x3803_fe08], // OR with an SGPR SRC0
&[0x3803_feff, 0xdead_beef], // OR with a literal SRC0
@@ -626,6 +815,23 @@ fn normalize_llvm_assembly(assembly: &str, next_offset: usize) -> String {
let target = next_offset + displacement * 4;
format!("{mnemonic} -> 0x{target:04x}")
}
// VOPC and the registry VOP2 forms print SRC0 (the second operand) as bits.
mnemonic
if mnemonic.starts_with("v_cmp_")
|| VectorAluOp::ALL
.iter()
.any(|op| op.assembly_name() == mnemonic) =>
{
let mut parts: Vec<String> = operands.split(", ").map(str::to_owned).collect();
parts[1] = match literal_bits(&parts[1]) {
Some(bits) => format!("0x{bits:x}"),
None => parts[1].parse::<i32>().map_or_else(
|_| parts[1].clone(),
|value| format!("0x{:x}", value as u32),
),
};
format!("{mnemonic} {}", parts.join(", "))
}
"v_mov_b32_e32" => {
let (destination, source) = operands.split_once(", ").unwrap();
let normalized = match source {
@@ -651,6 +857,18 @@ fn normalize_llvm_assembly(assembly: &str, next_offset: usize) -> String {
};
format!("{mnemonic} {}, {}", scalar(left), scalar(right))
}
"s_add_u32" | "s_sub_u32" | "s_add_i32" | "s_sub_i32" | "s_addc_u32" | "s_subb_u32"
| "s_and_b32" | "s_or_b32" | "s_xor_b32" => {
let scalar = |operand: &str| match literal_bits(operand) {
Some(bits) => match bits as i32 {
inline @ -16..=64 => inline.to_string(),
_ => format!("0x{bits:x}"),
},
None => operand.to_owned(),
};
let operands: Vec<_> = operands.split(", ").map(scalar).collect();
format!("{mnemonic} {}", operands.join(", "))
}
_ => assembly.to_owned(),
}
}
@@ -786,3 +1004,29 @@ fn accepts_scalar_destination_105_and_vgpr_zero_add_sources() {
}
);
}
#[test]
fn decode_at_resolves_branch_targets_from_the_stream_offset() {
let decoded = decode_at(Architecture::Gfx1030, BITWISE_FIXTURE, 0x1c).unwrap();
assert_eq!(decoded.offset, 0x1c);
assert_eq!(decoded.byte_len, 4);
assert_eq!(decoded.branch_target(), Some(0x3c));
// Alone, the same branch still reports its stream target; only the whole
// stream can say whether that target is an instruction boundary.
let isolated = decode_at(Architecture::Gfx1030, &BITWISE_FIXTURE[..0x20], 0x1c).unwrap();
assert_eq!(isolated.branch_target(), Some(0x3c));
assert_eq!(
decode_at(
Architecture::Gfx1030,
BITWISE_FIXTURE,
BITWISE_FIXTURE.len()
),
Err(DecodeError {
offset: BITWISE_FIXTURE.len(),
kind: DecodeErrorKind::Truncated {
needed: 4,
available: 0
},
})
);
}
+59
View File
@@ -0,0 +1,59 @@
//! Ties the decoder's declared semantic forms to what it decodes from LLVM-assembled fixtures.
use std::collections::BTreeSet;
use std::fs;
use std::path::Path;
use xenora_decoder::{Architecture, SEMANTIC_FORMS, decode};
use xenora_isa::meta::{FORMS, identify};
#[test]
fn declared_semantic_forms_are_exactly_those_decoded_from_fixtures() {
let directory = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/rdna2");
let mut decoded = BTreeSet::new();
for entry in fs::read_dir(directory).unwrap() {
let path = entry.unwrap().path();
if path.extension().is_none_or(|extension| extension != "bin") {
continue;
}
let binary = fs::read(&path).unwrap();
for instruction in decode(Architecture::Gfx1030, &binary).unwrap() {
let found = identify(&binary[instruction.offset..]).unwrap();
assert_eq!(
found.len,
usize::from(instruction.byte_len),
"{}",
path.display()
);
decoded.insert((found.form.name, found.form.family));
}
}
let declared: BTreeSet<_> = SEMANTIC_FORMS.into_iter().collect();
assert!(
decoded.is_subset(&declared),
"{:?}",
decoded.difference(&declared)
);
// Covered by inline words in tests/gfx1030.rs rather than fixture binaries.
let inline_only: BTreeSet<_> = declared
.difference(&decoded)
.map(|(name, _)| *name)
.collect();
assert_eq!(inline_only, BTreeSet::from(["IMAGE_SAMPLE_LZ"]));
for (name, family) in SEMANTIC_FORMS {
assert!(
FORMS
.iter()
.any(|form| form.name == name && form.family == family),
"{name}"
);
}
}
#[test]
fn registry_forms_do_not_duplicate_hand_written_forms() {
// A form declared in the semantic registry and also decoded by hand-written
// code would have two implementations; the hand-written one would win.
let unique: BTreeSet<_> = SEMANTIC_FORMS.into_iter().collect();
assert_eq!(unique.len(), SEMANTIC_FORMS.len());
}
+22
View File
@@ -0,0 +1,22 @@
[package]
name = "xenora-ffi"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
description = "Versioned C interface between the native macOS application and the Xenora runtime"
[lib]
crate-type = ["staticlib", "rlib"]
[lints]
workspace = true
[features]
# Runs the tests that need a native Metal device (scripts/test-gpu.sh).
gpu-tests = []
[dependencies]
xenora-loader = { path = "../loader" }
xenora-metal = { path = "../metal" }
xenora-shader = { path = "../shader" }
+246
View File
@@ -0,0 +1,246 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/*
* Xenora native application interface, version 1.
*
* Every function returns a xenora_status. Sessions are identified by opaque
* 64-bit handles, never by pointers; 0 is never a valid handle. A destroyed
* handle stays invalid even if its slot is reused. Output pointers are owned
* by the caller and are written only when the call returns XENORA_OK.
* All functions are thread-safe. No Rust panic crosses this boundary: one is
* reported as XENORA_INTERNAL_ERROR.
*/
#ifndef XENORA_H
#define XENORA_H
#include <stdint.h>
#define XENORA_ABI_VERSION 1u
typedef int32_t xenora_status;
enum {
XENORA_OK = 0,
XENORA_INVALID_ARGUMENT = 1,
XENORA_INVALID_HANDLE = 2,
XENORA_VERSION_MISMATCH = 3,
XENORA_INTERNAL_ERROR = 4,
XENORA_PE_ERROR = 5,
XENORA_LIMIT_EXCEEDED = 6,
XENORA_BUFFER_TOO_SMALL = 7,
XENORA_EXECUTION_FAILED = 8,
XENORA_INVALID_STATE = 9,
};
/* Frame-loop states reported by xenora_session_frame_loop_status. */
enum {
XENORA_LOOP_NONE = 0,
XENORA_LOOP_RUNNING = 1,
XENORA_LOOP_PAUSED = 2,
XENORA_LOOP_FINISHED = 3,
XENORA_LOOP_STOPPED = 4,
XENORA_LOOP_FAILED = 5,
};
#define XENORA_FRAME_LOOP_MAX_FRAMES 100000u
/* Frame id reported when no frame has been completed yet. */
#define XENORA_NO_FRAME 0xFFFFFFFFu
/* Input snapshot delivered to guest runtime services (Gate 4, #276). */
typedef struct {
uint32_t buttons;
int16_t stick_x;
int16_t stick_y;
int16_t mouse_dx;
int16_t mouse_dy;
uint8_t mouse_buttons;
uint8_t connected;
uint16_t reserved;
} xenora_input_state;
#define XENORA_INPUT_NONE 0u
#define XENORA_INPUT_RIGHT (1u << 0)
#define XENORA_INPUT_LEFT (1u << 1)
#define XENORA_INPUT_UP (1u << 2)
#define XENORA_INPUT_DOWN (1u << 3)
#define XENORA_INPUT_ACTION_A (1u << 4)
#define XENORA_INPUT_ACTION_B (1u << 5)
/* Size of the frame drawn by the trusted fixture: RGBA8, rows top to bottom. */
#define XENORA_FIXTURE_FRAME_WIDTH 4u
#define XENORA_FIXTURE_FRAME_HEIGHT 3u
typedef uint64_t xenora_session;
/* The interface version this library implements. */
uint32_t xenora_abi_version(void);
/* Create a session. `abi_version` must equal XENORA_ABI_VERSION. */
xenora_status xenora_session_create(uint32_t abi_version, xenora_session *out_session);
/* Destroy a session. Destroying it again returns XENORA_INVALID_HANDLE. */
xenora_status xenora_session_destroy(xenora_session session);
/* Parse the bundled trusted PE fixture with the runtime loader. No guest code runs. */
xenora_status xenora_session_inspect_trusted_fixture(
xenora_session session,
uint32_t *out_section_count,
uint32_t *out_entry_rva);
/*
* Run the bundled trusted PE fixture: its x86-64 code is translated and executed,
* and its single draw request is rendered on the native Metal device. On XENORA_OK,
* `out_rgba` holds width * height * 4 bytes of the read-back frame, which has been
* checked against the fixture shader's known output. `capacity` is the size of
* `out_rgba` in bytes. Blocks the calling thread; call it off the main thread.
* Only the embedded fixture can run; no caller-supplied executable is accepted.
*/
xenora_status xenora_session_run_trusted_fixture(
xenora_session session,
uint8_t *out_rgba,
uint64_t capacity,
uint32_t *out_width,
uint32_t *out_height);
/*
* Persistent rendering (one frame loop per session). Start runs the embedded
* frame-loop fixture on a session-owned guest thread: the guest submits frames
* 0, 1, 2, ... and each is rendered on native Metal and verified before it
* becomes the latest frame. The guest stops after `frame_count` frames
* (1..=XENORA_FRAME_LOOP_MAX_FRAMES). Pause holds the guest at its next frame
* submission; resume continues it; stop makes it leave its loop and halt, and
* waits for its thread. Destroying the session stops the loop first. Starting a
* second loop on the same session returns XENORA_INVALID_STATE.
*/
xenora_status xenora_session_start_frame_loop(xenora_session session, uint32_t frame_count);
xenora_status xenora_session_start_interactive_loop(xenora_session session, uint32_t frame_count);
xenora_status xenora_session_send_input(xenora_session session, const xenora_input_state *input);
xenora_status xenora_session_queue_input(xenora_session session, const xenora_input_state *input);
xenora_status xenora_session_pause_frame_loop(xenora_session session);
xenora_status xenora_session_resume_frame_loop(xenora_session session);
xenora_status xenora_session_stop_frame_loop(xenora_session session);
/*
* Retrieve a previously completed frame by sequence index (0 <= frame_index < completed).
* Used for deterministic replay verification and frame inspection.
*/
xenora_status xenora_session_get_recorded_frame(
xenora_session session,
uint32_t frame_index,
uint32_t *out_frame_id,
uint8_t *out_rgba,
uint64_t capacity
);
/*
* Report the loop's state, the number of completed frames, and the latest
* verified frame: its id (XENORA_NO_FRAME if none yet) and, when one exists,
* its RGBA8 pixels (XENORA_FIXTURE_FRAME_WIDTH x HEIGHT) in `out_rgba`.
*/
xenora_status xenora_session_frame_loop_status(
xenora_session session,
uint32_t *out_state,
uint32_t *out_completed,
uint32_t *out_frame_id,
uint8_t *out_rgba,
uint64_t capacity);
/* Largest file xenora_inspect_executable accepts, in bytes. */
#define XENORA_MAX_INSPECT_BYTES 268435456u
/* Opaque persistent GPU resource handle (Gate 5, #279) */
typedef uint64_t xenora_resource;
#define XENORA_NO_RESOURCE 0u
enum {
XENORA_RESOURCE_TYPE_TEXTURE_2D = 1,
XENORA_RESOURCE_TYPE_BUFFER = 2,
};
/*
* Create a persistent RGBA8 2D texture owned by the session.
* If `initial_rgba` is non-null, it must point to at least width * height * 4 bytes.
*/
xenora_status xenora_session_create_texture(
xenora_session session,
uint32_t width,
uint32_t height,
const uint8_t *initial_rgba,
xenora_resource *out_resource
);
/*
* Dynamically update a subregion of a persistent texture.
*/
xenora_status xenora_session_update_texture(
xenora_session session,
xenora_resource resource,
uint32_t x,
uint32_t y,
uint32_t width,
uint32_t height,
const uint8_t *rgba,
uint64_t byte_count
);
/*
* Destroy or retire a persistent resource. If in-flight GPU execution is using
* the resource, destruction is deferred until the execution completes.
*/
xenora_status xenora_session_destroy_resource(
xenora_session session,
xenora_resource resource
);
/*
* Query type, dimensions, and in-flight status of a persistent resource.
*/
xenora_status xenora_session_resource_info(
xenora_session session,
xenora_resource resource,
uint32_t *out_type,
uint32_t *out_width,
uint32_t *out_height,
uint32_t *out_in_flight
);
/*
* Render a frame using a persistent texture resource.
*/
xenora_status xenora_session_render_textured(
xenora_session session,
xenora_resource resource,
uint8_t *out_rgba,
uint64_t capacity,
uint32_t *out_width,
uint32_t *out_height
);
/*
* Run the original textured PE fixture and verify its read-back frame.
*/
xenora_status xenora_session_run_textured_fixture(
xenora_session session,
uint8_t *out_rgba,
uint64_t capacity,
uint32_t *out_width,
uint32_t *out_height
);
/*
* Read-only compatibility inspection of a caller-supplied PE file. Nothing in
* `bytes` is executed: it is parsed and statically disassembled (bounded) only.
* On XENORA_OK, XENORA_PE_ERROR or XENORA_INTERNAL_ERROR, `out_report` holds a
* NUL-terminated UTF-8 report of `*out_required` bytes including the NUL.
* XENORA_PE_ERROR means the file is not an acceptable PE32+ image;
* XENORA_INTERNAL_ERROR means Xenora's own probe failed on it. The report says which. If `capacity`
* is too small the call returns XENORA_BUFFER_TOO_SMALL with `*out_required`
* set and nothing else written. Files over XENORA_MAX_INSPECT_BYTES return
* XENORA_LIMIT_EXCEEDED.
*/
xenora_status xenora_inspect_executable(
const uint8_t *bytes,
uint64_t length,
char *out_report,
uint64_t capacity,
uint64_t *out_required);
#endif
+313
View File
@@ -0,0 +1,313 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Persistent guest rendering for one session (Gate 3, #266).
//!
//! The embedded `frame-loop.exe` fixture calls `xenora.dll!frame_submit(index)`
//! with index 0, 1, 2, ... and halts when the call returns 0. The guest runs on
//! its own thread for the session's lifetime. Pause, resume and stop act at the
//! frame-submit boundary: a paused guest waits inside that call with its
//! architectural state untouched, and a stop request makes the call return 0 so
//! the guest leaves its loop and halts.
use std::cell::RefCell;
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use std::thread::JoinHandle;
use xenora_loader::startup::{StartupLayout, run_synthetic_startup};
use xenora_loader::{ExitReason, ImportRegistry, Register};
use xenora_metal::NativeCompute;
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/frame-loop.exe");
const INTERACTIVE_FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/interactive.exe");
pub const WIDTH: usize = 4;
pub const HEIGHT: usize = 3;
pub const FRAME_BYTES: usize = WIDTH * HEIGHT * 4;
pub const MAX_FRAMES: u32 = 100_000;
/// Guest instructions per loop iteration (mov, call, inc, test, jnz) plus slack.
const STEPS_PER_FRAME: usize = 8;
const STEPS_PER_INTERACTIVE_FRAME: usize = 24;
/// `x9-constant-ps.s` exports (1, 0, 0, 1): opaque red. Everything else is the clear colour.
const RED: [u8; 4] = [255, 0, 0, 255];
const CLEAR: [u8; 4] = [19, 43, 93, 251];
pub const RUNNING: u32 = 1;
pub const PAUSED: u32 = 2;
pub const FINISHED: u32 = 3;
pub const STOPPED: u32 = 4;
pub const FAILED: u32 = 5;
#[derive(Default, Copy, Clone)]
#[repr(C)]
pub struct InputState {
pub buttons: u32,
pub stick_x: i16,
pub stick_y: i16,
pub mouse_dx: i16,
pub mouse_dy: i16,
pub mouse_buttons: u8,
pub connected: u8,
pub reserved: u16,
}
#[derive(Default)]
struct State {
status: u32,
paused: bool,
stop: bool,
interactive: bool,
limit: u32,
completed: u32,
input: InputState,
input_queue: std::collections::VecDeque<InputState>,
recorded_frames: Vec<(u32, Vec<u8>)>,
/// Every `frame_submit` call the guest made, including the one answered with 0.
calls: u64,
latest: Option<(u32, Vec<u8>)>,
}
#[derive(Default)]
pub struct FrameLoop {
state: Mutex<State>,
wake: Condvar,
thread: Mutex<Option<JoinHandle<()>>>,
}
pub struct Snapshot {
pub status: u32,
pub completed: u32,
pub latest: Option<(u32, Vec<u8>)>,
}
impl FrameLoop {
fn lock(&self) -> MutexGuard<'_, State> {
self.state
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
pub fn start(limit: u32, interactive: bool) -> Arc<Self> {
let shared = Arc::new(Self::default());
{
let mut state = shared.lock();
state.status = RUNNING;
state.limit = limit;
state.interactive = interactive;
}
let guest = Arc::clone(&shared);
let handle = std::thread::Builder::new()
.name("xenora-guest".into())
.spawn(move || guest.run())
.ok();
if handle.is_none() {
shared.lock().status = FAILED;
}
*shared.thread.lock().unwrap_or_else(|p| p.into_inner()) = handle;
shared
}
/// Pause or resume. Returns false unless the loop is running or paused.
pub fn set_paused(&self, paused: bool) -> bool {
let mut state = self.lock();
if !matches!(state.status, RUNNING | PAUSED) {
return false;
}
state.paused = paused;
state.status = if paused { PAUSED } else { RUNNING };
self.wake.notify_all();
true
}
/// Ask the guest to stop at its next frame submission and wait for its thread.
pub fn stop(&self) {
{
let mut state = self.lock();
state.stop = true;
self.wake.notify_all();
}
if let Some(handle) = self.thread.lock().unwrap_or_else(|p| p.into_inner()).take() {
let _ = handle.join();
}
}
pub fn send_input(&self, input: InputState) {
let mut state = self.lock();
state.input = input;
}
pub fn queue_input(&self, input: InputState) {
let mut state = self.lock();
state.input_queue.push_back(input);
}
pub fn get_recorded_frame(&self, index: usize) -> Option<(u32, Vec<u8>)> {
let state = self.lock();
state.recorded_frames.get(index).cloned()
}
pub fn snapshot(&self) -> Snapshot {
let state = self.lock();
Snapshot {
status: state.status,
completed: state.completed,
latest: state.latest.clone(),
}
}
fn run(self: Arc<Self>) {
let outcome = self.execute();
let mut state = self.lock();
state.status = match outcome {
Err(_) => FAILED,
Ok(()) if state.stop && state.completed < state.limit => STOPPED,
Ok(()) => FINISHED,
};
}
fn execute(self: &Arc<Self>) -> Result<(), String> {
let shader = compile_graphics(
Architecture::Gfx1030,
include_bytes!("../../../fixtures/rdna2/x9-constant-vs.bin"),
include_bytes!("../../../fixtures/rdna2/x9-constant-ps.bin"),
)
.map_err(|e| format!("shader translation: {e}"))?;
let gpu = NativeCompute::new().map_err(|e| format!("Metal device: {e}"))?;
// The session's GPU resources live on the guest thread, where the import runs.
GPU.with(|slot| *slot.borrow_mut() = Some((gpu, shader.msl)));
let shared = Arc::clone(self);
let mut imports = ImportRegistry::new();
imports.register("xenora.dll", "frame_submit", move |args, _, memory| {
let index = args.get(0, memory).map_err(ExitReason::MemoryFault)?;
shared
.submit(index)
.ok_or(ExitReason::IllegalInstruction(0xff))
});
if self.lock().interactive {
let shared_poll = Arc::clone(self);
imports.register("xenora.dll", "input_poll", move |_args, _, _memory| {
let mut state = shared_poll.lock();
let input = state.input_queue.pop_front().unwrap_or(state.input);
let cmd = if input.buttons & crate::XENORA_INPUT_RIGHT != 0 {
1u64
} else if input.buttons & crate::XENORA_INPUT_LEFT != 0 {
2u64
} else {
0u64
};
Ok(cmd)
});
}
let limit = self.lock().limit as usize;
let is_interactive = self.lock().interactive;
let fixture_bytes = if is_interactive {
INTERACTIVE_FIXTURE
} else {
FIXTURE
};
let steps_per_frame = if is_interactive {
STEPS_PER_INTERACTIVE_FRAME
} else {
STEPS_PER_FRAME
};
let startup = run_synthetic_startup(
fixture_bytes,
StartupLayout {
image_base: 0x1_4000_0000,
stack_top: 0x2_0001_0000,
tls_base: 0x3_0000_0000,
},
imports,
(limit + 1) * steps_per_frame + 32,
)
.map_err(|e| format!("startup: {e}"));
GPU.with(|slot| slot.borrow_mut().take());
let startup = startup?;
let calls = self.lock().calls;
let rbx = startup.execution.final_state.get(Register::Rbx);
if startup.execution.exit_reason != ExitReason::Halt {
return Err(format!(
"guest ended with {:?}",
startup.execution.exit_reason
));
}
if !is_interactive && rbx != calls {
return Err(format!("guest ended with rbx={rbx}, calls={calls}"));
}
Ok(())
}
/// Handle one `frame_submit`: wait while paused, then render and verify the
/// frame. `None` fails the guest; `Some(0)` tells it to stop.
fn submit(&self, index: u64) -> Option<u64> {
let mut state = self.lock();
state.calls += 1;
while state.paused && !state.stop {
state = self.wake.wait(state).unwrap_or_else(|p| p.into_inner());
}
if state.stop || state.completed >= state.limit {
return Some(0);
}
if state.interactive {
if index >= WIDTH as u64 {
return None; // column must be inside 0..WIDTH
}
} else if index != u64::from(state.completed) {
return None; // frame identities must arrive in order
}
drop(state);
let pixels = render(index as u32)?;
let mut state = self.lock();
state.completed += 1;
state.latest = Some((index as u32, pixels.clone()));
if state.interactive {
state.recorded_frames.push((index as u32, pixels));
}
Some(u64::from(state.completed < state.limit && !state.stop))
}
}
thread_local! {
static GPU: RefCell<Option<(NativeCompute, String)>> = const { RefCell::new(None) };
}
/// Frame `index` is a red strip in column `index % 4` on the clear colour.
///
/// The triangle (x0, -10), (x0 + 0.7, 0), (x0, 10) in clip space, with x0 the
/// column's left edge, covers that column's pixel centres in all three rows and
/// none of its neighbours'.
fn render(index: u32) -> Option<Vec<u8>> {
let column = (index as usize % WIDTH) as f32;
let x0 = -1.0 + column * (2.0 / WIDTH as f32);
let pixels = GPU.with(|slot| {
let slot = slot.borrow();
let (gpu, msl) = slot.as_ref()?;
gpu.render_rgba8(
msl,
[VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT],
&[
[x0, -10.0, 0.5, 1.0],
[x0 + 0.7, 0.0, 0.5, 1.0],
[x0, 10.0, 0.5, 1.0],
],
&[[0.0; 4]; 3],
[WIDTH, HEIGHT],
CLEAR,
)
.ok()
})?;
(pixels == expected(index)).then_some(pixels)
}
/// The expected frame for `index`, from the strip rule alone.
pub fn expected(index: u32) -> Vec<u8> {
(0..WIDTH * HEIGHT)
.flat_map(|pixel| {
if pixel % WIDTH == index as usize % WIDTH {
RED
} else {
CLEAR
}
})
.collect()
}
File diff suppressed because it is too large. Load diff
+259
View File
@@ -0,0 +1,259 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Gate 3 acceptance on a native Metal device: persistent guest rendering through
//! the C interface. Needs `--features gpu-tests` (scripts/test-gpu.sh).
#![cfg(feature = "gpu-tests")]
use std::sync::Mutex;
use std::time::{Duration, Instant};
use xenora_ffi::*;
/// Tests share the process-wide session table and one GPU; run them one at a time.
static SERIAL: Mutex<()> = Mutex::new(());
/// Expected frame `id`, derived only from the geometry: the guest's frame index picks
/// column `id % 4`, which is opaque red (x9-constant-ps exports (1, 0, 0, 1)); the
/// other columns keep the clear colour (19, 43, 93, 251).
fn expected(id: u32) -> Vec<u8> {
let mut frame = Vec::new();
for _row in 0..3 {
for column in 0..4 {
if column == id % 4 {
frame.extend([255, 0, 0, 255]);
} else {
frame.extend([19, 43, 93, 251]);
}
}
}
frame
}
struct Status {
state: u32,
completed: u32,
frame_id: u32,
rgba: [u8; 48],
}
fn status(session: u64) -> Status {
let mut s = Status {
state: 99,
completed: 0,
frame_id: 0,
rgba: [0; 48],
};
let code = unsafe {
xenora_session_frame_loop_status(
session,
&mut s.state,
&mut s.completed,
&mut s.frame_id,
s.rgba.as_mut_ptr(),
48,
)
};
assert_eq!(code, XENORA_OK);
s
}
fn session() -> u64 {
let mut session = 0;
assert_eq!(
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut session) },
XENORA_OK
);
session
}
fn wait_until(session: u64, what: &str, done: impl Fn(&Status) -> bool) -> Status {
let deadline = Instant::now() + Duration::from_secs(60);
loop {
let s = status(session);
if done(&s) {
return s;
}
assert!(
Instant::now() < deadline,
"timed out waiting for {what} (state {}, completed {})",
s.state,
s.completed
);
std::thread::sleep(Duration::from_millis(2));
}
}
/// Physical memory footprint of this process (macOS `proc_pid_rusage`, RUSAGE_INFO_V2).
fn footprint() -> u64 {
unsafe extern "C" {
fn proc_pid_rusage(pid: i32, flavor: i32, buffer: *mut [u64; 32]) -> i32;
}
let mut info = [0u64; 32];
assert_eq!(
unsafe { proc_pid_rusage(std::process::id() as i32, 2, &mut info) },
0
);
info[9] // after the 16-byte UUID: user, system, idle wakeups, interrupts, pageins, wired, resident, footprint
}
#[test]
fn three_hundred_guest_frames_arrive_verified_and_in_order() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
let session = session();
assert_eq!(xenora_session_start_frame_loop(session, 300), XENORA_OK);
assert_eq!(
xenora_session_start_frame_loop(session, 300),
XENORA_INVALID_STATE
);
let s = wait_until(session, "300 frames", |s| s.state != XENORA_LOOP_RUNNING);
assert_eq!(s.state, XENORA_LOOP_FINISHED);
assert_eq!(s.completed, 300);
assert_eq!(s.frame_id, 299);
assert_eq!(s.rgba.to_vec(), expected(299));
assert_eq!(xenora_session_destroy(session), XENORA_OK);
}
#[test]
fn observed_frame_ids_never_go_backwards_and_match_their_pixels() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
let session = session();
assert_eq!(xenora_session_start_frame_loop(session, 2_000), XENORA_OK);
let mut previous = None;
let mut samples = 0;
loop {
let s = status(session);
if s.frame_id != XENORA_NO_FRAME {
if let Some(p) = previous {
assert!(s.frame_id >= p, "frame id went from {p} to {}", s.frame_id);
}
assert!(
s.frame_id < s.completed,
"id {} not below completed {}",
s.frame_id,
s.completed
);
assert_eq!(
s.rgba.to_vec(),
expected(s.frame_id),
"frame {}",
s.frame_id
);
previous = Some(s.frame_id);
samples += 1;
}
if s.state != XENORA_LOOP_RUNNING {
assert_eq!(s.state, XENORA_LOOP_FINISHED);
assert_eq!((s.completed, s.frame_id), (2_000, 1_999));
break;
}
}
assert!(samples > 1);
xenora_session_destroy(session);
}
#[test]
fn pause_holds_the_guest_resume_continues_and_stop_halts_it() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
let session = session();
assert_eq!(
xenora_session_start_frame_loop(session, XENORA_FRAME_LOOP_MAX_FRAMES),
XENORA_OK
);
wait_until(session, "10 frames", |s| s.completed >= 10);
assert_eq!(xenora_session_pause_frame_loop(session), XENORA_OK);
// At most the frame already being rendered can still complete after pausing.
std::thread::sleep(Duration::from_millis(50));
let held = status(session);
std::thread::sleep(Duration::from_millis(200));
let later = status(session);
assert_eq!(later.state, XENORA_LOOP_PAUSED);
assert_eq!(later.completed, held.completed, "no frames while paused");
assert_eq!(later.frame_id, held.completed - 1);
assert_eq!(later.rgba.to_vec(), expected(later.frame_id));
assert_eq!(xenora_session_resume_frame_loop(session), XENORA_OK);
let resumed = wait_until(session, "progress after resume", |s| {
s.completed >= held.completed + 10
});
assert_eq!(resumed.state, XENORA_LOOP_RUNNING);
assert_eq!(xenora_session_stop_frame_loop(session), XENORA_OK);
let stopped = status(session);
assert_eq!(stopped.state, XENORA_LOOP_STOPPED);
assert!(stopped.completed < XENORA_FRAME_LOOP_MAX_FRAMES);
assert_eq!(stopped.frame_id, stopped.completed - 1);
assert_eq!(stopped.rgba.to_vec(), expected(stopped.frame_id));
// Pause and resume are refused once the guest has halted.
assert_eq!(
xenora_session_pause_frame_loop(session),
XENORA_INVALID_STATE
);
assert_eq!(
xenora_session_resume_frame_loop(session),
XENORA_INVALID_STATE
);
assert_eq!(xenora_session_destroy(session), XENORA_OK);
}
#[test]
fn destroying_a_running_or_paused_session_stops_it() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
for pause_first in [false, true] {
let session = session();
assert_eq!(
xenora_session_start_frame_loop(session, XENORA_FRAME_LOOP_MAX_FRAMES),
XENORA_OK
);
wait_until(session, "a frame", |s| s.completed >= 1);
if pause_first {
assert_eq!(xenora_session_pause_frame_loop(session), XENORA_OK);
}
let started = Instant::now();
assert_eq!(xenora_session_destroy(session), XENORA_OK);
assert!(
started.elapsed() < Duration::from_secs(5),
"destroy joined promptly"
);
let mut x = 0;
let mut rgba = [0u8; 48];
assert_eq!(
unsafe {
xenora_session_frame_loop_status(
session,
&mut x,
&mut x,
&mut x,
rgba.as_mut_ptr(),
48,
)
},
XENORA_INVALID_HANDLE
);
}
}
#[test]
fn repeated_sessions_do_not_grow_the_memory_footprint() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
let run = || {
let session = session();
assert_eq!(xenora_session_start_frame_loop(session, 300), XENORA_OK);
let s = wait_until(session, "300 frames", |s| s.state != XENORA_LOOP_RUNNING);
assert_eq!((s.state, s.completed), (XENORA_LOOP_FINISHED, 300));
assert_eq!(xenora_session_destroy(session), XENORA_OK);
};
// Warm up so one-time allocations (Metal device, shader compiler) are excluded.
run();
run();
let baseline = footprint();
for _ in 0..5 {
run();
}
let after = footprint();
let growth = after.saturating_sub(baseline);
println!("footprint baseline={baseline} after_5_sessions={after} growth={growth}");
assert!(
growth < 16 << 20,
"footprint grew by {growth} bytes over 5 sessions of 300 frames"
);
}
+298
View File
@@ -0,0 +1,298 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Gate 4 acceptance on a native Metal device: interactive guest execution with
//! dynamic input handling and rendering through the C interface.
//! Needs `--features gpu-tests` (scripts/test-gpu.sh).
#![cfg(feature = "gpu-tests")]
use std::sync::Mutex;
use std::time::{Duration, Instant};
use xenora_ffi::*;
/// Tests share the process-wide session table and one GPU; run them one at a time.
static SERIAL: Mutex<()> = Mutex::new(());
/// Expected frame `column` (0..3): column `column` is opaque red (255, 0, 0, 255);
/// all other columns keep the clear colour (19, 43, 93, 251).
fn expected(column: u32) -> Vec<u8> {
let mut frame = Vec::new();
for _row in 0..3 {
for col in 0..4 {
if col == column % 4 {
frame.extend([255, 0, 0, 255]);
} else {
frame.extend([19, 43, 93, 251]);
}
}
}
frame
}
struct Status {
state: u32,
completed: u32,
frame_id: u32,
rgba: [u8; 48],
}
fn status(session: u64) -> Status {
let mut s = Status {
state: 99,
completed: 0,
frame_id: 0,
rgba: [0; 48],
};
let code = unsafe {
xenora_session_frame_loop_status(
session,
&mut s.state,
&mut s.completed,
&mut s.frame_id,
s.rgba.as_mut_ptr(),
48,
)
};
assert_eq!(code, XENORA_OK);
s
}
fn session() -> u64 {
let mut session = 0;
assert_eq!(
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut session) },
XENORA_OK
);
session
}
fn send_buttons(session: u64, buttons: u32) {
let input = xenora_input_state {
buttons,
stick_x: 0,
stick_y: 0,
mouse_dx: 0,
mouse_dy: 0,
mouse_buttons: 0,
connected: 1,
reserved: 0,
};
assert_eq!(
unsafe { xenora_session_send_input(session, &input) },
XENORA_OK
);
}
fn queue_buttons(session: u64, buttons: u32) {
let input = xenora_input_state {
buttons,
stick_x: 0,
stick_y: 0,
mouse_dx: 0,
mouse_dy: 0,
mouse_buttons: 0,
connected: 1,
reserved: 0,
};
assert_eq!(
unsafe { xenora_session_queue_input(session, &input) },
XENORA_OK
);
}
fn wait_until(session: u64, what: &str, done: impl Fn(&Status) -> bool) -> Status {
let deadline = Instant::now() + Duration::from_secs(60);
loop {
let s = status(session);
if done(&s) {
return s;
}
assert!(
Instant::now() < deadline,
"timed out waiting for {what} (state {}, completed {})",
s.state,
s.completed
);
std::thread::sleep(Duration::from_millis(2));
}
}
#[test]
fn interactive_input_moves_guest_column_and_updates_pixels() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
let session = session();
// Start interactive loop with 120 frames
assert_eq!(
xenora_session_start_interactive_loop(session, 120),
XENORA_OK
);
// Initial frames without input stay at column 0
let s = wait_until(session, "initial frames", |s| s.completed >= 5);
assert_eq!(s.frame_id, 0);
assert_eq!(s.rgba.to_vec(), expected(0));
// Send Right input: column should advance 0 -> 1 -> 2 -> 3 -> 0
send_buttons(session, XENORA_INPUT_RIGHT);
let s_right = wait_until(session, "column moves right", |s| {
s.completed >= 15 && s.frame_id != 0
});
assert_eq!(s_right.rgba.to_vec(), expected(s_right.frame_id));
// Release input: position stops moving
send_buttons(session, XENORA_INPUT_NONE);
let s_hold_start = wait_until(session, "wait for release frame", |s| {
s.completed >= s_right.completed + 2
});
let hold_col = s_hold_start.frame_id;
let s_hold = wait_until(session, "position holds on release", |s| {
s.completed >= s_hold_start.completed + 10
});
assert_eq!(s_hold.frame_id, hold_col);
assert_eq!(s_hold.rgba.to_vec(), expected(s_hold.frame_id));
// Send Left input: column should move left
send_buttons(session, XENORA_INPUT_LEFT);
let s_left = wait_until(session, "column moves left", |s| {
s.completed >= s_hold.completed + 10 && s.frame_id != hold_col
});
assert_eq!(s_left.rgba.to_vec(), expected(s_left.frame_id));
// Wait until finished
let s_end = wait_until(session, "loop finish", |s| s.state == XENORA_LOOP_FINISHED);
assert_eq!(s_end.completed, 120);
assert_eq!(xenora_session_destroy(session), XENORA_OK);
}
#[test]
fn deterministic_input_replay_produces_identical_frames() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
// Timeline of inputs across 60 frames:
// frames 0..15: Right
// frames 15..30: None
// frames 30..45: Left
// frames 45..60: Right
let replay_sequence: Vec<u32> = (0..60)
.map(|f| {
if f < 15 {
XENORA_INPUT_RIGHT
} else if f < 30 {
XENORA_INPUT_NONE
} else if f < 45 {
XENORA_INPUT_LEFT
} else {
XENORA_INPUT_RIGHT
}
})
.collect();
let run_replay = || {
let session = session();
assert_eq!(
xenora_session_start_interactive_loop(session, 60),
XENORA_OK
);
// Pre-queue the complete input sequence
for &btn in &replay_sequence {
queue_buttons(session, btn);
}
// Wait until all 60 frames are rendered
let s = wait_until(session, "replay completion", |s| {
s.state == XENORA_LOOP_FINISHED && s.completed == 60
});
assert_eq!(s.completed, 60);
// Inspect all 60 recorded frames
let mut frames = Vec::with_capacity(60);
for i in 0..60 {
let mut id = 0u32;
let mut rgba = [0u8; 48];
let code = unsafe {
xenora_session_get_recorded_frame(session, i, &mut id, rgba.as_mut_ptr(), 48)
};
assert_eq!(code, XENORA_OK);
assert_eq!(rgba.to_vec(), expected(id));
frames.push((id, rgba));
}
assert_eq!(xenora_session_destroy(session), XENORA_OK);
frames
};
let run1 = run_replay();
let run2 = run_replay();
assert_eq!(run1.len(), 60);
assert_eq!(run2.len(), 60);
for i in 0..60 {
assert_eq!(
run1[i].0, run2[i].0,
"frame {} column mismatch: {} vs {}",
i, run1[i].0, run2[i].0
);
assert_eq!(run1[i].1, run2[i].1, "frame {} pixel mismatch", i);
}
}
#[test]
fn focus_loss_and_release_resets_input_cleanly() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
let session = session();
assert_eq!(
xenora_session_start_interactive_loop(session, 100),
XENORA_OK
);
// Send Right
send_buttons(session, XENORA_INPUT_RIGHT);
let s1 = wait_until(session, "moving right", |s| s.completed >= 10);
// Simulate focus loss / key release
send_buttons(session, XENORA_INPUT_NONE);
// Wait for the release to take effect in the guest
let s_released = wait_until(session, "release takes effect", |s| {
s.completed >= s1.completed + 2
});
let stopped_col = s_released.frame_id;
// Check next 15 frames: frame_id must remain fixed at stopped_col
let s2 = wait_until(session, "hold after release", |s| {
s.completed >= s_released.completed + 15
});
assert_eq!(s2.frame_id, stopped_col);
assert_eq!(s2.rgba.to_vec(), expected(stopped_col));
// Clean stop
assert_eq!(xenora_session_stop_frame_loop(session), XENORA_OK);
let s_stopped = wait_until(session, "stopped", |s| s.state == XENORA_LOOP_STOPPED);
assert_eq!(s_stopped.state, XENORA_LOOP_STOPPED);
assert_eq!(xenora_session_destroy(session), XENORA_OK);
}
#[test]
fn destroying_interactive_session_stops_cleanly() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
let session = session();
assert_eq!(
xenora_session_start_interactive_loop(session, 5000),
XENORA_OK
);
// Wait until it actually starts rendering
wait_until(session, "running", |s| s.completed >= 5);
let start = Instant::now();
assert_eq!(xenora_session_destroy(session), XENORA_OK);
assert!(
start.elapsed() < Duration::from_millis(500),
"destroy took too long: {:?}",
start.elapsed()
);
}
+40
View File
@@ -0,0 +1,40 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Runs the trusted fixture through the C interface on a native Metal device.
//! Needs `--features gpu-tests` (scripts/test-gpu.sh).
#![cfg(feature = "gpu-tests")]
use xenora_ffi::*;
/// fixtures/rdna2/x9-constant-ps.s: `v_mov_b32 v8, 1.0; v_mov_b32 v9, 0;
/// exp mrt0, v8, v9, v9, v8` writes (1, 0, 0, 1); as RGBA8 unorm that is (255, 0, 0, 255).
const SHADER_OUTPUT: [u8; 4] = [255, 0, 0, 255];
#[test]
fn guest_fixture_frame_reaches_the_caller_through_metal() {
for run in 0..3 {
let mut session = 0;
assert_eq!(
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut session) },
XENORA_OK
);
let (mut rgba, mut width, mut height) = ([0u8; 64], 0u32, 0u32);
let status = unsafe {
xenora_session_run_trusted_fixture(
session,
rgba.as_mut_ptr(),
64,
&mut width,
&mut height,
)
};
assert_eq!(status, XENORA_OK, "run {run}");
assert_eq!((width, height), (4, 3));
assert_eq!(&rgba[..48], SHADER_OUTPUT.repeat(12).as_slice());
assert!(
rgba[48..].iter().all(|&b| b == 0),
"no write past the frame"
);
assert_eq!(xenora_session_destroy(session), XENORA_OK);
}
}
+375
View File
@@ -0,0 +1,375 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Gate 5 acceptance on a native Metal device: persistent GPU resources,
//! dynamic texture updates, and completion-aware resource retirement through
//! the C interface (#279).
//! Needs `--features gpu-tests` (scripts/test-gpu.sh).
#![cfg(feature = "gpu-tests")]
use std::sync::Mutex;
use xenora_ffi::*;
/// Tests share the process-wide session table and one GPU; run them one at a time.
static SERIAL: Mutex<()> = Mutex::new(());
fn session() -> u64 {
let mut handle = 0;
assert_eq!(
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut handle) },
XENORA_OK
);
assert_ne!(handle, 0);
handle
}
#[test]
fn persistent_texture_lifecycle_survives_across_multiple_frames() {
let _guard = SERIAL.lock().unwrap();
let sess = session();
// 2x2 initial texture:
// (0,0)=red, (1,0)=green, (0,1)=blue, (1,1)=white
let initial_rgba: [u8; 16] = [
255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
];
let mut res = 0u64;
assert_eq!(
unsafe { xenora_session_create_texture(sess, 2, 2, initial_rgba.as_ptr(), &mut res) },
XENORA_OK
);
assert_ne!(res, XENORA_NO_RESOURCE);
// Render 5 consecutive frames from this single persistent texture resource without re-allocation.
for frame_idx in 0..5 {
let mut out_rgba = [0u8; 16];
let mut out_w = 0u32;
let mut out_h = 0u32;
assert_eq!(
unsafe {
xenora_session_render_textured(
sess,
res,
out_rgba.as_mut_ptr(),
16,
&mut out_w,
&mut out_h,
)
},
XENORA_OK,
"render frame {} failed",
frame_idx
);
assert_eq!(out_w, 2);
assert_eq!(out_h, 2);
assert_eq!(
out_rgba, initial_rgba,
"frame {} pixel mismatch with persistent texture",
frame_idx
);
}
// Verify resource is still live and un-retired after all frames
let (mut r_type, mut r_w, mut r_h, mut r_flight) = (0u32, 0u32, 0u32, 0u32);
assert_eq!(
unsafe {
xenora_session_resource_info(sess, res, &mut r_type, &mut r_w, &mut r_h, &mut r_flight)
},
XENORA_OK
);
assert_eq!(r_type, XENORA_RESOURCE_TYPE_TEXTURE_2D);
assert_eq!(r_w, 2);
assert_eq!(r_h, 2);
assert_eq!(r_flight, 0);
assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK);
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
}
#[test]
fn dynamic_texture_subregion_update_is_reflected_on_metal() {
let _guard = SERIAL.lock().unwrap();
let sess = session();
// 2x2 initial texture:
// (0,0)=red, (1,0)=green, (0,1)=blue, (1,1)=white
let initial_rgba: [u8; 16] = [
255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
];
let mut res = 0u64;
assert_eq!(
unsafe { xenora_session_create_texture(sess, 2, 2, initial_rgba.as_ptr(), &mut res) },
XENORA_OK
);
// 1. Update 1x1 subregion at (x=1, y=0) from green to yellow [255, 255, 0, 255]
let yellow_pixel = [255u8, 255, 0, 255];
assert_eq!(
unsafe { xenora_session_update_texture(sess, res, 1, 0, 1, 1, yellow_pixel.as_ptr(), 4) },
XENORA_OK
);
let mut frame1 = [0u8; 16];
let (mut w, mut h) = (0u32, 0u32);
assert_eq!(
unsafe {
xenora_session_render_textured(sess, res, frame1.as_mut_ptr(), 16, &mut w, &mut h)
},
XENORA_OK
);
let expected_frame1: [u8; 16] = [
255, 0, 0, 255, // (0,0) red (untouched)
255, 255, 0, 255, // (1,0) yellow (updated)
0, 0, 255, 255, // (0,1) blue (untouched)
255, 255, 255, 255, // (1,1) white (untouched)
];
assert_eq!(
frame1, expected_frame1,
"Metal read-back did not reflect 1x1 subregion update"
);
// 2. Update 2x1 subregion across the bottom row: (0,1) and (1,1)
// (0,1)=magenta [255, 0, 255, 255], (1,1)=cyan [0, 255, 255, 255]
let bottom_row = [255u8, 0, 255, 255, 0, 255, 255, 255];
assert_eq!(
unsafe { xenora_session_update_texture(sess, res, 0, 1, 2, 1, bottom_row.as_ptr(), 8) },
XENORA_OK
);
let mut frame2 = [0u8; 16];
assert_eq!(
unsafe {
xenora_session_render_textured(sess, res, frame2.as_mut_ptr(), 16, &mut w, &mut h)
},
XENORA_OK
);
let expected_frame2: [u8; 16] = [
255, 0, 0, 255, // (0,0) red
255, 255, 0, 255, // (1,0) yellow
255, 0, 255, 255, // (0,1) magenta
0, 255, 255, 255, // (1,1) cyan
];
assert_eq!(
frame2, expected_frame2,
"Metal read-back did not reflect 2x1 bottom row update"
);
assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK);
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
}
#[test]
fn deferred_resource_retirement_safely_waits_for_completion() {
let _guard = SERIAL.lock().unwrap();
let sess = session();
let mut res = 0u64;
assert_eq!(
unsafe { xenora_session_create_texture(sess, 2, 2, std::ptr::null(), &mut res) },
XENORA_OK
);
// Acquire an in-flight reference simulating active GPU encoding/submission
assert_eq!(test_acquire_resource_in_flight(sess, res), Ok(()));
let (mut r_type, mut r_w, mut r_h, mut r_flight) = (0u32, 0u32, 0u32, 0u32);
assert_eq!(
unsafe {
xenora_session_resource_info(sess, res, &mut r_type, &mut r_w, &mut r_h, &mut r_flight)
},
XENORA_OK
);
assert_eq!(r_flight, 1);
// Calling destroy while in-flight marks the resource retired without dangling pointers
assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK);
// Subsequent caller operations on the retired handle are rejected
assert_eq!(
unsafe {
xenora_session_resource_info(sess, res, &mut r_type, &mut r_w, &mut r_h, &mut r_flight)
},
XENORA_INVALID_HANDLE
);
assert_eq!(
xenora_session_destroy_resource(sess, res),
XENORA_INVALID_HANDLE
);
let dummy_pixel = [0u8; 4];
assert_eq!(
unsafe { xenora_session_update_texture(sess, res, 0, 0, 1, 1, dummy_pixel.as_ptr(), 4) },
XENORA_INVALID_HANDLE
);
let mut out_rgba = [0u8; 16];
let (mut w, mut h) = (0u32, 0u32);
assert_eq!(
unsafe {
xenora_session_render_textured(sess, res, out_rgba.as_mut_ptr(), 16, &mut w, &mut h)
},
XENORA_INVALID_HANDLE
);
// Now in-flight execution completes and releases its reference
assert_eq!(test_release_resource_in_flight(sess, res), Ok(()));
// The slot is now safely reclaimed; the next allocation reuses the slot with a new generation
let mut res2 = 0u64;
assert_eq!(
unsafe { xenora_session_create_texture(sess, 2, 2, std::ptr::null(), &mut res2) },
XENORA_OK
);
assert_eq!((res & 0xFFFF_FFFF), (res2 & 0xFFFF_FFFF)); // same slot index
assert_ne!(res >> 32, res2 >> 32); // higher generation
assert_eq!(xenora_session_destroy_resource(sess, res2), XENORA_OK);
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
}
#[test]
fn invalid_stale_and_double_destroyed_resource_handles_are_rejected() {
let _guard = SERIAL.lock().unwrap();
let sess = session();
// Zero handle
assert_eq!(
xenora_session_destroy_resource(sess, XENORA_NO_RESOURCE),
XENORA_INVALID_HANDLE
);
// Unallocated slot index
let unallocated_handle = (1u64 << 32) | 999u64;
assert_eq!(
xenora_session_destroy_resource(sess, unallocated_handle),
XENORA_INVALID_HANDLE
);
// Create and destroy a valid resource
let mut res = 0u64;
assert_eq!(
unsafe { xenora_session_create_texture(sess, 2, 2, std::ptr::null(), &mut res) },
XENORA_OK
);
assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK);
// Double destroy
assert_eq!(
xenora_session_destroy_resource(sess, res),
XENORA_INVALID_HANDLE
);
// Stale handle queries
let (mut r_type, mut r_w, mut r_h, mut r_flight) = (0u32, 0u32, 0u32, 0u32);
assert_eq!(
unsafe {
xenora_session_resource_info(sess, res, &mut r_type, &mut r_w, &mut r_h, &mut r_flight)
},
XENORA_INVALID_HANDLE
);
let pixel = [0u8; 4];
assert_eq!(
unsafe { xenora_session_update_texture(sess, res, 0, 0, 1, 1, pixel.as_ptr(), 4) },
XENORA_INVALID_HANDLE
);
let mut out_rgba = [0u8; 16];
let (mut w, mut h) = (0u32, 0u32);
assert_eq!(
unsafe {
xenora_session_render_textured(sess, res, out_rgba.as_mut_ptr(), 16, &mut w, &mut h)
},
XENORA_INVALID_HANDLE
);
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
}
#[test]
fn repeated_resource_allocations_and_retirements_do_not_leak_slots() {
let _guard = SERIAL.lock().unwrap();
let sess = session();
let initial = [
255u8, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
];
let update = [255u8, 255, 0, 255];
// Run 200 cycles of create -> update -> render -> destroy
for i in 0..200 {
let mut res = 0u64;
assert_eq!(
unsafe { xenora_session_create_texture(sess, 2, 2, initial.as_ptr(), &mut res) },
XENORA_OK,
"create failed at cycle {}",
i
);
// Verify slot index is reused (res_idx is 0)
let slot_idx = (res & 0xFFFF_FFFF) as usize;
assert_eq!(slot_idx, 0, "slot index leaked at cycle {}", i);
assert_eq!(
unsafe { xenora_session_update_texture(sess, res, 0, 0, 1, 1, update.as_ptr(), 4) },
XENORA_OK
);
let mut out = [0u8; 16];
let (mut w, mut h) = (0u32, 0u32);
assert_eq!(
unsafe {
xenora_session_render_textured(sess, res, out.as_mut_ptr(), 16, &mut w, &mut h)
},
XENORA_OK
);
assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK);
}
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
}
#[test]
fn textured_pe_fixture_executes_dynamic_updates_and_retirement() {
let _guard = SERIAL.lock().unwrap();
let sess = session();
let mut out_rgba = [0u8; 16];
let mut out_w = 0u32;
let mut out_h = 0u32;
assert_eq!(
unsafe {
xenora_session_run_textured_fixture(
sess,
out_rgba.as_mut_ptr(),
16,
&mut out_w,
&mut out_h,
)
},
XENORA_OK
);
assert_eq!(out_w, 2);
assert_eq!(out_h, 2);
let expected_final: [u8; 16] = [
255, 255, 0, 255, // (0,0) yellow
0, 255, 255, 255, // (1,0) cyan
255, 0, 255, 255, // (0,1) magenta
64, 64, 64, 255, // (1,1) dark grey
];
assert_eq!(
out_rgba, expected_final,
"guest textured fixture read-back frame mismatch"
);
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
}
File diff suppressed because it is too large. Load diff
+12 -1
View File
@@ -17,7 +17,6 @@ VARIANTS = (
("V_ADD_NC_U32", "ENC_VOP3"),
("S_ENDPGM", "ENC_SOPP"),
("S_MOV_B32", "ENC_SOP1"),
("S_CMP_EQ_U32", "ENC_SOPC"),
("S_CBRANCH_SCC0", "ENC_SOPP"),
("S_CBRANCH_EXECZ", "ENC_SOPP"),
("S_CBRANCH_VCCZ", "ENC_SOPP"),
@@ -30,6 +29,18 @@ VARIANTS = (
("V_XOR_B32", "ENC_VOP2"),
("V_ADD_F32", "ENC_VOP2"),
("V_MUL_F32", "ENC_VOP2"),
("V_CMP_LT_I32", "ENC_VOPC"),
("V_CMP_EQ_I32", "ENC_VOPC"),
("V_CMP_LE_I32", "ENC_VOPC"),
("V_CMP_GT_I32", "ENC_VOPC"),
("V_CMP_NE_I32", "ENC_VOPC"),
("V_CMP_GE_I32", "ENC_VOPC"),
("V_CMP_LT_U32", "ENC_VOPC"),
("V_CMP_EQ_U32", "ENC_VOPC"),
("V_CMP_LE_U32", "ENC_VOPC"),
("V_CMP_GT_U32", "ENC_VOPC"),
("V_CMP_NE_U32", "ENC_VOPC"),
("V_CMP_GE_U32", "ENC_VOPC"),
("EXP", "ENC_EXP"),
("V_INTERP_P1_F32", "ENC_VINTRP"),
("V_INTERP_P2_F32", "ENC_VINTRP"),
+437
View File
@@ -0,0 +1,437 @@
#!/usr/bin/env python3
"""Generate the complete gfx1030 instruction metadata table.
Two stages keep regeneration offline and checkable without the 11 MB AMD XML:
snapshot AMD RDNA 2 XML -> crates/isa/data/rdna2.jsonl (normalised, sorted)
rust crates/isa/data/rdna2.jsonl -> crates/isa/src/rdna2_meta.rs
`--check` regenerates in memory and fails when a committed file differs.
Only the Python standard library is used. See docs/research/rdna2.md.
"""
import argparse
import hashlib
import json
import sys
from pathlib import Path
from xml.etree import ElementTree
SOURCE_SHA256 = "d671ecbc36543674ab59e9b2feffd56718fd2137e7ad913c314f2e2508b9f4f7"
ARCHITECTURE = "AMD RDNA 2"
ROOT = Path(__file__).resolve().parents[2]
SNAPSHOT = ROOT / "crates/isa/data/rdna2.jsonl"
RUST = ROOT / "crates/isa/src/rdna2_meta.rs"
SCHEMA = 1
# Encodings whose default condition defines an instruction's base form. The
# remaining XML encodings are literal, SDWA, DPP or NSA extensions of these.
BASE_ENCODINGS = {
"ENC_SOP1": "Sop1",
"ENC_SOP2": "Sop2",
"ENC_SOPC": "Sopc",
"ENC_SOPK": "Sopk",
"ENC_SOPP": "Sopp",
"ENC_SMEM": "Smem",
"ENC_VOP1": "Vop1",
"ENC_VOP2": "Vop2",
"ENC_VOPC": "Vopc",
"ENC_VOP3": "Vop3",
"VOP3_SDST_ENC": "Vop3Sdst",
"ENC_VOP3P": "Vop3p",
"ENC_VINTRP": "Vintrp",
"ENC_DS": "Ds",
"ENC_MUBUF": "Mubuf",
"ENC_MTBUF": "Mtbuf",
"ENC_MIMG": "Mimg",
"ENC_EXP": "Exp",
"ENC_FLAT": "Flat",
"ENC_FLAT_GLBL": "Global",
"ENC_FLAT_SCRATCH": "Scratch",
}
# Extension encoding -> (base encoding, extension kind). The XML names the
# variant and its operands but gives no expression for when it applies; the
# decoder implements those rules by hand (docs/research/rdna2.md).
EXTENSIONS = {
"SOP1_INST_LITERAL": ("ENC_SOP1", "literal"),
"SOP2_INST_LITERAL": ("ENC_SOP2", "literal"),
"SOPC_INST_LITERAL": ("ENC_SOPC", "literal"),
"SOPK_INST_LITERAL": ("ENC_SOPK", "literal"),
"VOP1_INST_LITERAL": ("ENC_VOP1", "literal"),
"VOP2_INST_LITERAL": ("ENC_VOP2", "literal"),
"VOPC_INST_LITERAL": ("ENC_VOPC", "literal"),
"VOP3_INST_LITERAL": ("ENC_VOP3", "literal"),
"VOP3_SDST_ENC_INST_LITERAL": ("VOP3_SDST_ENC", "literal"),
"VOP3P_INST_LITERAL": ("ENC_VOP3P", "literal"),
"VOP1_VOP_SDWA": ("ENC_VOP1", "sdwa"),
"VOP2_VOP_SDWA": ("ENC_VOP2", "sdwa"),
"VOP2_VOP_SDWA_SDST_ENC": ("ENC_VOP2", "sdwa"),
"VOPC_VOP_SDWA_SDST_ENC": ("ENC_VOPC", "sdwa"),
"VOP1_VOP_DPP8": ("ENC_VOP1", "dpp8"),
"VOP2_VOP_DPP8": ("ENC_VOP2", "dpp8"),
"VOP1_VOP_DPP16": ("ENC_VOP1", "dpp16"),
"VOP2_VOP_DPP16": ("ENC_VOP2", "dpp16"),
"MIMG_NSA1": ("ENC_MIMG", "nsa"),
"MIMG_NSA2": ("ENC_MIMG", "nsa"),
"MIMG_NSA3": ("ENC_MIMG", "nsa"),
}
FLAGS = ("IsBranch", "IsConditionalBranch", "IsIndirectBranch", "IsProgramTerminator", "IsImmediatelyExecuted")
def fail(message):
raise SystemExit(f"generate_rdna2_meta: {message}")
def text(element, path):
value = element.findtext(path)
if value is None:
fail(f"missing <{path}>")
return value.strip()
def boolean(value):
if value not in ("TRUE", "FALSE", "true", "false"):
fail(f"unexpected boolean {value!r}")
return value.lower() == "true"
def snapshot_from_xml(data):
if hashlib.sha256(data).hexdigest() != SOURCE_SHA256:
fail("RDNA 2 XML does not match the approved input SHA-256")
root = ElementTree.fromstring(data)
document = root.find("Document")
isa = root.find("ISA")
if text(isa, "Architecture/ArchitectureName") != ARCHITECTURE:
fail("XML is not the RDNA 2 architecture")
records = [{
"kind": "source",
"schema": SCHEMA,
"architecture": ARCHITECTURE,
"sha256": SOURCE_SHA256,
"release": text(document, "ReleaseDate"),
"xml_schema": text(document, "SchemaVersion"),
"license": text(document, "License"),
"copyright": text(document, "Copyright"),
}]
known = set(BASE_ENCODINGS) | set(EXTENSIONS)
encodings = {}
for encoding in isa.findall("Encodings/Encoding"):
name = text(encoding, "EncodingName")
if name not in known:
fail(f"unclassified encoding {name}; add it to BASE_ENCODINGS or EXTENSIONS")
bits = int(text(encoding, "BitCount"))
mask = int(text(encoding, "EncodingIdentifierMask"), 2)
identifiers = sorted(int(item.text, 2) for item in encoding.findall("EncodingIdentifiers/EncodingIdentifier"))
if mask >> 32 or any(identifier >> 32 for identifier in identifiers):
fail(f"{name} identifies instructions beyond the first dword")
fields = []
for field in encoding.findall("MicrocodeFormat/BitMap/Field"):
ranges = sorted(field.findall("BitLayout/Range"), key=lambda item: int(item.attrib.get("Order", 0)))
fields.append([
text(field, "FieldName"),
[[int(text(item, "BitOffset")), int(text(item, "BitCount"))] for item in ranges],
])
fields.sort(key=lambda item: (item[1][0][0], item[0]))
encodings[name] = {"mask": mask, "identifiers": set(identifiers)}
records.append({
"kind": "encoding",
"name": name,
"bits": bits,
"identifier_mask": mask,
"identifiers": identifiers,
"conditions": sorted(text(item, "ConditionName") for item in encoding.findall("EncodingConditions/EncodingCondition")),
"fields": fields,
})
missing = known - set(encodings)
if missing:
fail(f"encodings absent from the XML: {sorted(missing)}")
for operand_type in isa.findall("OperandTypes/OperandType"):
values = sorted(
[text(value, "Name"), int(text(value, "Value"))]
for value in operand_type.findall("OperandPredefinedValues/PredefinedValue")
)
records.append({
"kind": "operand_type",
"name": text(operand_type, "OperandTypeName"),
"partitioned": boolean(operand_type.attrib.get("IsPartitioned", "false")),
"values": values,
})
for data_format in isa.findall("DataFormats/DataFormat"):
records.append({
"kind": "data_format",
"name": text(data_format, "DataFormatName"),
"data_type": text(data_format, "DataType"),
"bits": int(text(data_format, "BitCount")),
"components": int(text(data_format, "ComponentCount")),
})
seen = set()
for instruction in isa.findall("Instructions/Instruction"):
name = text(instruction, "InstructionName")
flags = {flag: boolean(text(instruction, f"InstructionFlags/{flag}")) for flag in FLAGS}
group = instruction.find("FunctionalGroup")
for variant in instruction.findall("InstructionEncodings/InstructionEncoding"):
encoding_name = text(variant, "EncodingName")
condition = text(variant, "EncodingCondition")
opcode = int(text(variant, "Opcode"))
key = (name, encoding_name, condition)
if key in seen:
fail(f"duplicate variant {key}")
seen.add(key)
operands = []
for operand in sorted(variant.findall("Operands/Operand"), key=lambda item: int(item.attrib["Order"])):
operands.append([
operand.findtext("FieldName") or "",
operand.findtext("DataFormatName") or "",
operand.findtext("OperandType") or "",
int(operand.findtext("OperandSize") or 0),
boolean(operand.attrib["Input"]),
boolean(operand.attrib["Output"]),
boolean(operand.attrib["IsImplicit"]),
boolean(operand.attrib.get("IsBinaryMicrocodeRequired", "true")),
])
record = {
"kind": "variant",
"instruction": name,
"encoding": encoding_name,
"condition": condition,
"opcode": opcode,
}
# Extension variants keep only what classifies them; their
# operands repeat the base form with a literal, SDWA, DPP or NSA word.
if encoding_name in BASE_ENCODINGS or condition == "default":
record.update({
"flags": sorted(flag for flag, value in flags.items() if value),
"group": text(group, "Name"),
"subgroups": sorted(item.text.strip() for item in group.findall("FunctionalSubgroups/Subgroup")),
"operands": operands,
})
records.append(record)
order = {"source": 0, "encoding": 1, "operand_type": 2, "data_format": 3, "variant": 4}
records.sort(key=lambda record: (
order[record["kind"]],
record.get("name", ""),
record.get("encoding", ""),
record.get("instruction", ""),
record.get("condition", ""),
))
return "".join(json.dumps(record, sort_keys=True, separators=(",", ":")) + "\n" for record in records)
def place(value, ranges):
"""Places `value` into a field layout; returns (mask, bits) within the first two dwords."""
mask = bits = 0
for offset, count in ranges:
if offset + count > 64:
fail("opcode field extends beyond the second dword")
low = (1 << count) - 1
bits |= (value & low) << offset
mask |= low << offset
value >>= count
if value:
fail("opcode does not fit its field")
return mask, bits
def forms_from_snapshot(snapshot):
records = [json.loads(line) for line in snapshot.splitlines()]
source = records[0]
if source.get("kind") != "source" or source.get("schema") != SCHEMA or source.get("sha256") != SOURCE_SHA256:
fail("snapshot header does not match this generator")
encodings = {record["name"]: record for record in records if record["kind"] == "encoding"}
variants = [record for record in records if record["kind"] == "variant"]
extensions = {}
for variant in variants:
if variant["encoding"] in EXTENSIONS:
base, kind = EXTENSIONS[variant["encoding"]]
entry = extensions.setdefault((variant["instruction"], base), set())
if kind == "literal" and variant["condition"] == "default":
entry.add("always_literal")
entry.add(kind)
based = {(variant["instruction"], variant["encoding"]) for variant in variants if variant["encoding"] in BASE_ENCODINGS}
forms = []
for variant in variants:
encoding_name = variant["encoding"]
identity = encoding_name
if encoding_name in EXTENSIONS:
# A few instructions exist only with a literal (S_SETREG_IMM32_B32,
# V_FMAMK_F32, ...): the XML lists them under the literal encoding's
# default condition and gives them no base variant.
base, kind = EXTENSIONS[encoding_name]
if kind != "literal" or variant["condition"] != "default" or (variant["instruction"], base) in based:
continue
encoding_name = base
elif encoding_name not in BASE_ENCODINGS:
continue
# Three VOP1/VOP3 relative moves name the excluded extensions instead of "default".
if variant["condition"] != "default" and not variant["condition"].startswith("Nothas_"):
fail(f"{variant['instruction']} has non-default base condition {variant['condition']}")
encoding = encodings[encoding_name]
id_encoding = encodings[identity]
fields = dict((name, ranges) for name, ranges in encoding["fields"])
prefix_mask, _ = place(0, fields["ENCODING"])
prefixes = {identifier & prefix_mask for identifier in id_encoding["identifiers"]}
if len(prefixes) != 1:
fail(f"{encoding_name} has an ambiguous encoding prefix")
prefix = prefixes.pop()
id_mask = id_encoding["identifier_mask"] & 0xFFFFFFFF
opcode = variant["opcode"]
if "OP" in fields:
op_mask, op_bits = place(opcode, fields["OP"])
elif opcode == 0:
op_mask = op_bits = 0
else:
fail(f"{encoding_name} has no OP field for opcode {opcode}")
# The identifier mask can add selector bits beyond ENCODING and OP,
# such as the FLAT segment field. Take them from the listed identifier.
# MTBUF keeps one opcode bit in the second dword, which the
# first-dword identifiers cannot express; carry it separately.
low = 0xFFFFFFFF
candidates = sorted({
identifier & 0xFFFFFFFF for identifier in id_encoding["identifiers"]
if identifier & (prefix_mask | op_mask) & low == (prefix | op_bits) & low
})
if len(candidates) != 1:
fail(f"{variant['instruction']} matches {len(candidates)} {encoding_name} identifiers")
forms.append({
"name": variant["instruction"],
"encoding": BASE_ENCODINGS[encoding_name],
"opcode": opcode,
# Opcode bits outside the identifier mask (MIMG bit 0, MTBUF bit 53)
# still select the instruction.
"mask": id_mask | op_mask,
"bits": (candidates[0] & id_mask) | op_bits,
"bytes": encoding["bits"] // 8,
"flags": variant["flags"],
"group": variant["group"],
"extensions": sorted(extensions.get((variant["instruction"], encoding_name), ())),
"operands": variant["operands"],
})
by_pattern = {}
for form in forms:
if form["bits"] & ~form["mask"]:
fail(f"{form['name']} has identifying bits outside its mask")
key = (form["mask"], form["bits"])
if key in by_pattern:
fail(f"{form['name']} and {by_pattern[key]['name']} share an encoding")
by_pattern[key] = form
for left in forms:
for right in forms:
if left is right or left["mask"] == right["mask"]:
continue
common = left["mask"] & right["mask"]
if (left["bits"] ^ right["bits"]) & common == 0:
fail(f"{left['name']} ({left['encoding']}) overlaps {right['name']} ({right['encoding']})")
forms.sort(key=lambda form: (form["encoding"], form["opcode"]))
return source, encodings, forms
def rust_from_snapshot(snapshot):
source, encodings, forms = forms_from_snapshot(snapshot)
out = []
emit = out.append
emit("// Generated by crates/isa/generate_rdna2_meta.py from crates/isa/data/rdna2.jsonl. Do not edit.")
emit(f"// Source: AMD RDNA 2 XML, {source['release']}, schema {source['xml_schema']}, SHA-256 {source['sha256']}.")
emit(f"// {source['copyright']}")
emit("// SPDX-License-Identifier: MIT")
emit("")
emit("use super::meta::{EncodingFamily, Extensions, FieldLayout, Form, FormFlags, OperandInfo};")
emit("")
emit(f'/// SHA-256 of the AMD XML the table was generated from.\npub const SOURCE_SHA256: &str = "{source["sha256"]}";')
emit("")
operand_sets = {}
for form in forms:
operand_sets.setdefault(json.dumps(form["operands"]), len(operand_sets))
emit("static OPERANDS: [&[OperandInfo]; %d] = [" % len(operand_sets))
for operands_json in operand_sets:
operands = json.loads(operands_json)
items = ", ".join(
"OperandInfo { field: %s, format: %s, kind: %s, bits: %d, input: %s, output: %s, implicit: %s, encoded: %s }"
% (json.dumps(field), json.dumps(data_format), json.dumps(kind), size,
str(i).lower(), str(o).lower(), str(implicit).lower(), str(encoded).lower())
for field, data_format, kind, size, i, o, implicit, encoded in operands
)
emit(f" &[{items}],")
emit("];")
emit("")
families = sorted({form["encoding"] for form in forms})
emit("/// Field layouts of each base encoding, as (bit offset, bit count) pieces from least significant.")
emit("pub static FIELDS: [(EncodingFamily, &[FieldLayout]); %d] = [" % len(families))
reverse = {value: key for key, value in BASE_ENCODINGS.items()}
for family in families:
fields = encodings[reverse[family]]["fields"]
items = ", ".join(
"FieldLayout { name: %s, pieces: &[%s] }" % (json.dumps(name), ", ".join(f"({o}, {c})" for o, c in ranges))
for name, ranges in fields
)
emit(f" (EncodingFamily::{family}, &[{items}]),")
emit("];")
emit("")
flag_bits = {
"IsBranch": 1,
"IsConditionalBranch": 2,
"IsIndirectBranch": 4,
"IsProgramTerminator": 8,
"IsImmediatelyExecuted": 16,
}
extension_bits = {"literal": 1, "always_literal": 2, "sdwa": 4, "dpp8": 8, "dpp16": 16, "nsa": 32}
emit("/// Every gfx1030 base instruction form in the AMD XML, sorted by encoding family and opcode.")
emit("pub static FORMS: [Form; %d] = [" % len(forms))
for form in forms:
flags = sum(flag_bits[flag] for flag in form["flags"])
extensions = sum(extension_bits[item] for item in form["extensions"])
emit(
" Form { name: %s, family: EncodingFamily::%s, opcode: %d, mask: 0x%016x, bits: 0x%016x, bytes: %d, "
"flags: FormFlags(0x%02x), extensions: Extensions(0x%02x), group: %s, operands: OPERANDS[%d] },"
% (json.dumps(form["name"]), form["encoding"], form["opcode"], form["mask"], form["bits"], form["bytes"],
flags, extensions, json.dumps(form["group"]), operand_sets[json.dumps(form["operands"])])
)
emit("];")
return "\n".join(out) + "\n"
def compare(path, expected):
actual = path.read_text() if path.exists() else ""
if actual != expected:
print(f"{path.relative_to(ROOT)} is out of date; rerun crates/isa/generate_rdna2_meta.py", file=sys.stderr)
return False
return True
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--xml", type=Path, help="approved amdgpu_isa_rdna2.xml; regenerates the snapshot too")
parser.add_argument("--check", action="store_true", help="fail when committed outputs differ")
args = parser.parse_args()
if args.xml:
snapshot = snapshot_from_xml(args.xml.read_bytes())
elif SNAPSHOT.exists():
snapshot = SNAPSHOT.read_text()
else:
fail("no snapshot; pass --xml")
rust = rust_from_snapshot(snapshot)
if args.check:
ok = compare(RUST, rust)
if args.xml:
ok = compare(SNAPSHOT, snapshot) and ok
raise SystemExit(0 if ok else 1)
SNAPSHOT.parent.mkdir(parents=True, exist_ok=True)
SNAPSHOT.write_text(snapshot)
RUST.write_text(rust)
if __name__ == "__main__":
main()
+960
View File
@@ -0,0 +1,960 @@
#!/usr/bin/env python3
"""Validate the declarative gfx1030 semantic registry and generate its Rust tables.
validate check crates/isa/semantics/rdna2.toml against its closed vocabulary
and the pinned AMD XML snapshot (crates/isa/data/rdna2.jsonl)
generate validate, then write crates/isa/src/semantics_gen.rs
--check validate and regenerate in memory; exit 1 if the committed file
differs. Never writes.
The registry is data only. Behaviour is chosen from a closed set of primitives
(crates/isa/src/primitive.rs) by the declared operation, signedness and SCC
effect, never from a mnemonic. Only the Python standard library is used
(tomllib needs Python 3.11 or newer). See docs/shaders/semantic-registry.md.
"""
import argparse
import json
import re
import sys
from pathlib import Path
try:
import tomllib
except ModuleNotFoundError: # pragma: no cover - depends on the interpreter
sys.exit("generate_semantics.py needs Python 3.11 or newer (tomllib)")
ROOT = Path(__file__).resolve().parents[2]
REGISTRY = ROOT / "crates/isa/semantics/rdna2.toml"
SNAPSHOT = ROOT / "crates/isa/data/rdna2.jsonl"
RUST = ROOT / "crates/isa/src/semantics_gen.rs"
SCHEMA = 1
ARCHITECTURE = "gfx1030"
FORM_KEYS = {
"name", "family", "opcode", "variant", "operation", "signedness", "carry_in",
"width", "scc", "vcc", "exec", "wave", "operands", "spec", "verify",
}
TOP_KEYS = {"schema", "architecture", "source_sha256", "documents", "operand_rules", "form"}
OPERATIONS = {
"add": "Add", "sub": "Sub", "and": "And", "or": "Or", "xor": "Xor",
"andn2": "AndNot", "orn2": "OrNot", "nand": "Nand", "nor": "Nor", "xnor": "Xnor",
"lshl": "ShiftLeft", "lshr": "LogicalShiftRight", "ashr": "ArithmeticShiftRight",
"compare": "Compare",
"not": "Not", "brev": "ReverseBits", "bcnt0": "CountZeros", "bcnt1": "CountOnes",
"ff0": "FindFirstZero", "ff1": "FindFirstOne", "flbit": "FindLastBit",
"sext": "SignExtend", "abs": "Absolute",
"min": "Minimum", "max": "Maximum", "cselect": "Select", "bfm": "BitfieldMask",
"mul": "Multiply", "mul_hi": "MultiplyHigh", "bfe": "BitfieldExtract",
"absdiff": "AbsoluteDifference", "lshl_add": "ShiftLeftAdd",
"mul24": "Multiply24", "mul_hi24": "MultiplyHigh24",
}
# Unary operations read one source; they need an operand rule of the unary kind.
UNARY = {"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "flbit", "sext", "abs"}
# Sign extension reads only the low source_bits of S0 (required for sext only).
SOURCE_BITS_KEY = "source_bits"
SOURCE_BITS = {8, 16}
# Compares take a relation (S0 on the left) and set SCC to whether it holds.
RELATION_KEY = "relation"
RELATIONS = {
"eq": "Equal", "lg": "NotEqual", "gt": "Greater", "ge": "GreaterOrEqual",
"lt": "Less", "le": "LessOrEqual",
}
# (relation, signedness) -> primitive. Equality does not depend on signedness,
# so both declared signednesses of EQ and LG share one primitive.
COMPARE_PRIMITIVES = {
("eq", "signed"): "eq_b32", ("eq", "unsigned"): "eq_b32",
("lg", "signed"): "ne_b32", ("lg", "unsigned"): "ne_b32",
("gt", "signed"): "gt_i32", ("gt", "unsigned"): "gt_u32",
("ge", "signed"): "ge_i32", ("ge", "unsigned"): "ge_u32",
("lt", "signed"): "lt_i32", ("lt", "unsigned"): "lt_u32",
("le", "signed"): "le_i32", ("le", "unsigned"): "le_u32",
}
# Logical operations take untyped bits; arithmetic ones never do. Shifts take
# the signedness their primitive names, and their S1 is an unsigned count.
LOGICAL = {
"and", "or", "xor", "andn2", "orn2", "nand", "nor", "xnor",
"not", "brev", "bcnt0", "bcnt1", "ff0", "ff1", "cselect", "bfm",
}
ARITHMETIC = {
"add", "sub", "min", "max", "mul", "mul_hi", "bfe", "absdiff", "lshl_add", "mul24", "mul_hi24",
}
SHIFTS = {"lshl", "lshr", "ashr"}
# Operations whose S1 is an unsigned control word (a shift count or a bit-field
# descriptor), so the XML gives it FMT_NUM_U32 whatever the form's signedness.
CONTROL_S1 = SHIFTS | {"bfe"}
# Operations that always read SCC: the select condition. They need carry_in scc.
SCC_READERS = {"cselect"}
# XML number formats a source may have for each declared signedness.
SOURCE_FORMATS = {
"signed": {"FMT_NUM_I32"},
"unsigned": {"FMT_NUM_U32"},
"bitwise": {"FMT_NUM_U32", "FMT_NUM_B32"},
}
# Optional keys: required exactly when the condition holds.
SHIFT_KEY = "shift_count_bits"
# Shift-and-add declares its fixed S0 shift (required for lshl_add only).
SHIFT_AMOUNT_KEY = "shift_amount"
SHIFT_AMOUNTS = {1, 2, 3, 4}
# Vector forms whose guide pseudocode reads S1 before S0 (D = op(S1, S0))
# declare it; the XML records no operand order.
SOURCE_ORDER_KEY = "source_order"
SOURCE_ORDERS = {"reversed"}
SIGNEDNESS = {"unsigned": "Unsigned", "signed": "Signed", "bitwise": "Bitwise"}
CARRY_IN = {"none": "None", "scc": "Scc"}
SCC = {
"unchanged": "Unchanged",
"carry_out": "CarryOut",
"borrow": "Borrow",
"signed_overflow": "SignedOverflow",
"nonzero": "Nonzero",
"relation": "Relation",
"selected_src0": "SelectedSrc0",
}
MASK = {"unchanged": "Unchanged"}
WAVE = {"any": "Any", "wave32": "Wave32"}
# The decoder has no wave-size input at the registry dispatch yet, so a Wave32
# restriction could be declared but not enforced. Reject it until it can be.
ENFORCED_WAVES = {"any"}
EVIDENCE = {
"reference": "Reference",
"independent": "Independent",
"metal": "Metal",
"llvm_encoding": "LlvmEncoding",
}
DOCUMENTS = {"guide": "Guide", "xml": "Xml"}
# The public documents spec references may cite, pinned so a citation cannot
# silently point at another file.
PINNED_DOCUMENTS = {
"guide": {
"title": "AMD RDNA 2 Instruction Set Architecture Reference Guide",
"file": "rdna2-shader-instruction-set-architecture.pdf",
"pages": 291,
},
"xml": {
"title": "AMD RDNA 2 machine-readable ISA (pinned XML)",
"file": "amdgpu_isa_rdna2.xml",
},
}
WIDTHS = {32}
# (operation, signedness) -> (required SCC effect, primitive, takes carry-in).
# A form whose declaration is not a row here has no primitive and is rejected.
PRIMITIVES = {
("add", "unsigned"): ("carry_out", "add_carry_u32", True),
("sub", "unsigned"): ("borrow", "sub_borrow_u32", True),
("add", "signed"): ("signed_overflow", "add_overflow_i32", False),
("sub", "signed"): ("signed_overflow", "sub_overflow_i32", False),
("and", "bitwise"): ("nonzero", "and_nonzero_b32", False),
("or", "bitwise"): ("nonzero", "or_nonzero_b32", False),
("xor", "bitwise"): ("nonzero", "xor_nonzero_b32", False),
("andn2", "bitwise"): ("nonzero", "andn2_nonzero_b32", False),
("orn2", "bitwise"): ("nonzero", "orn2_nonzero_b32", False),
("nand", "bitwise"): ("nonzero", "nand_nonzero_b32", False),
("nor", "bitwise"): ("nonzero", "nor_nonzero_b32", False),
("xnor", "bitwise"): ("nonzero", "xnor_nonzero_b32", False),
("lshl", "bitwise"): ("nonzero", "lshl_nonzero_b32", False),
("lshr", "unsigned"): ("nonzero", "lshr_nonzero_b32", False),
("ashr", "signed"): ("nonzero", "ashr_nonzero_i32", False),
("not", "bitwise"): ("nonzero", "not_nonzero_b32", False),
("brev", "bitwise"): ("unchanged", "brev_b32", False),
("bcnt0", "bitwise"): ("nonzero", "bcnt0_nonzero_b32", False),
("bcnt1", "bitwise"): ("nonzero", "bcnt1_nonzero_b32", False),
("ff0", "bitwise"): ("unchanged", "ff0_b32", False),
("ff1", "bitwise"): ("unchanged", "ff1_b32", False),
("flbit", "bitwise"): ("unchanged", "flbit_b32", False),
("flbit", "signed"): ("unchanged", "flbit_i32", False),
("sext", "signed"): ("unchanged", "sext_i32", False),
("abs", "signed"): ("nonzero", "abs_nonzero_i32", False),
("min", "signed"): ("selected_src0", "min_i32", False),
("min", "unsigned"): ("selected_src0", "min_u32", False),
("max", "signed"): ("selected_src0", "max_i32", False),
("max", "unsigned"): ("selected_src0", "max_u32", False),
("cselect", "bitwise"): ("unchanged", "cselect_b32", True),
("bfm", "bitwise"): ("unchanged", "bfm_b32", False),
("mul", "signed"): ("unchanged", "mul_lo_i32", False),
("mul_hi", "unsigned"): ("unchanged", "mul_hi_u32", False),
("mul_hi", "signed"): ("unchanged", "mul_hi_i32", False),
("bfe", "unsigned"): ("nonzero", "bfe_nonzero_u32", False),
("bfe", "signed"): ("nonzero", "bfe_nonzero_i32", False),
("absdiff", "signed"): ("nonzero", "absdiff_nonzero_i32", False),
("lshl_add", "unsigned"): ("carry_out", "lshl_add_carry_u32", False),
}
# Vector (VOP2) forms: (operation, signedness) -> the per-lane VectorBinary their
# MSL lowering uses. They write no SCC, VCC or EXEC, so scc must be unchanged.
VECTOR_PRIMITIVES = {
("add", "unsigned"): "Add",
("sub", "unsigned"): "Sub",
("xnor", "bitwise"): "Xnor",
("min", "signed"): "MinSigned",
("min", "unsigned"): "MinUnsigned",
("max", "signed"): "MaxSigned",
("max", "unsigned"): "MaxUnsigned",
("mul24", "signed"): "Mul24Signed",
("mul24", "unsigned"): "Mul24Unsigned",
("mul_hi24", "signed"): "MulHi24Signed",
("mul_hi24", "unsigned"): "MulHi24Unsigned",
}
# Operand rules the decoder implements, each exactly once. A registry rule must
# match one of these shapes; anything else is an unimplemented rule.
UNSUPPORTED_COMBOS = {
"dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null", "src_vcc", "src_exec",
"src_m0", "src_ttmp", "src_float_inline", "src_special", "two_literals",
}
# Every combo name a rule may list (VOP2 also names vcc_hi and NULL sources,
# which SOP2 groups under src_vcc and src_special).
ALL_COMBOS = UNSUPPORTED_COMBOS | {"src_vcc_hi", "src_null"}
OPERAND_RULES = {
"sop2_sgpr": {
"rust": "Sop2Sgpr",
"enum": "ScalarAluOp",
"shape": {
"family": "SOP2",
"dst": {"field": "SDST", "class": "sgpr", "min": 0, "max": 105},
"src": [
{"field": "SSRC0", "class": "scalar_source"},
{"field": "SSRC1", "class": "scalar_source"},
],
"max_literals": 1,
},
# Every one of these is rejected by the decoder's SOP2 operand checks.
"unsupported": UNSUPPORTED_COMBOS,
"kind": "alu",
},
"sopc_scalar": {
"rust": "SopcScalar",
"enum": "ScalarCompareOp",
"shape": {
"family": "SOPC",
"src": [
{"field": "SSRC0", "class": "scalar_source"},
{"field": "SSRC1", "class": "scalar_source"},
],
"max_literals": 1,
},
# SOPC has no destination field; the decoder rejects these sources.
"unsupported": {combo for combo in UNSUPPORTED_COMBOS if not combo.startswith("dst_")},
"kind": "compare",
},
"sop1_sgpr": {
"rust": "Sop1Sgpr",
"enum": "ScalarUnaryOp",
"shape": {
"family": "SOP1",
"dst": {"field": "SDST", "class": "sgpr", "min": 0, "max": 105},
"src": [{"field": "SSRC0", "class": "scalar_source"}],
"max_literals": 1,
},
# One source, so two literals cannot occur; the rest are rejected.
"unsupported": {combo for combo in UNSUPPORTED_COMBOS if combo != "two_literals"},
"kind": "unary",
},
"vop2_vgpr": {
"rust": "Vop2Vgpr",
"enum": "VectorAluOp",
"shape": {
"family": "VOP2",
"dst": {"field": "VDST", "class": "vgpr", "min": 0, "max": 255},
"src": [
{"field": "SRC0", "class": "vector_source"},
{"field": "VSRC1", "class": "vgpr"},
],
"max_literals": 1,
},
# vector_source = VGPR, s0-s105, vcc_lo, inline integer -16..64 or a
# literal; the decoder rejects these SRC0 selectors.
"unsupported": {
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline",
"src_special",
},
"kind": "vector",
},
}
VARIANT = re.compile(r"^[A-Z][A-Za-z0-9]*$")
RESERVED_VARIANTS = {"Self", "ALL"}
U16_MAX = 0xFFFF
NAME = re.compile(r"^[A-Z][A-Z0-9_]*$")
SECTION = re.compile(r"^[0-9]+(\.[0-9]+)*$")
def load_registry(path=REGISTRY):
"""Parse the TOML registry into a dict."""
with open(path, "rb") as handle:
return tomllib.load(handle)
def load_snapshot(path=SNAPSHOT):
"""Index the normalised XML snapshot: source line, encodings, default variants."""
source = None
encodings = {}
variants = {}
with open(path, encoding="utf-8") as handle:
for line in handle:
record = json.loads(line)
kind = record.get("kind")
if kind == "source":
source = record
elif kind == "encoding":
encodings[record["name"]] = record
elif kind == "variant" and record.get("condition") == "default":
variants[(record["instruction"], record["encoding"])] = record
return {"source": source or {}, "encodings": encodings, "variants": variants}
def _family_encoding(family):
return "ENC_" + family
def _rust_family(family):
return family[0] + family[1:].lower()
def _check_rule(name, rule, errors):
implemented = OPERAND_RULES.get(name)
if implemented is None:
errors.append(f"operand rule {name}: not implemented by the decoder")
return
unsupported = rule.get("unsupported", [])
unknown = sorted(set(unsupported) - ALL_COMBOS)
if unknown:
errors.append(f"operand rule {name}: unknown unsupported combos {unknown}")
if len(set(unsupported)) != len(unsupported):
errors.append(f"operand rule {name}: duplicate unsupported combos")
if set(unsupported) != implemented["unsupported"]:
errors.append(
f"operand rule {name}: unsupported combos differ from those the decoder rejects"
)
declared = {key: value for key, value in rule.items() if key != "unsupported"}
if declared != implemented["shape"]:
errors.append(
f"operand rule {name}: declaration differs from the decoder's implemented rule"
)
def _check_xml(form, rule, snapshot, errors):
label = form["name"]
encoding_name = _family_encoding(form["family"])
encoding = snapshot["encodings"].get(encoding_name)
if encoding is None:
errors.append(f"{label}: family {form['family']} has no XML encoding {encoding_name}")
return
variant = snapshot["variants"].get((form["name"], encoding_name))
if variant is None:
errors.append(f"{label}: no default {encoding_name} variant in the XML snapshot")
return
if variant["opcode"] != form["opcode"]:
errors.append(
f"{label}: opcode {form['opcode']} disagrees with the XML opcode {variant['opcode']}"
)
if _identifier(encoding, form["opcode"]) not in encoding["identifiers"]:
errors.append(f"{label}: opcode {form['opcode']} is not an identifier of {encoding_name}")
operands = {}
scc_in = scc_out = False
implicit = set()
for field, data_format, kind, size, is_input, is_output, _implicit, _encoded in variant["operands"]:
if kind == "OPR_SSRC_SPECIAL_SCC":
scc_in |= is_input
scc_out |= is_output
elif field:
operands[field] = (data_format, size, is_input, is_output)
else:
implicit.add(kind)
# The vocabulary can state only SCC effects (vcc and exec are "unchanged"),
# so any other implicit XML operand, such as VCC, is undeclared.
if implicit:
errors.append(f"{label}: XML implicit operands {sorted(implicit)} are not declared")
if scc_in != (form["carry_in"] == "scc"):
errors.append(f"{label}: carry_in {form['carry_in']} contradicts the XML SCC input")
if scc_out != (form["scc"] != "unchanged"):
errors.append(f"{label}: scc {form['scc']} contradicts the XML SCC output")
if rule is None:
return
if not isinstance(rule.get("src"), list) or not all(
isinstance(src, dict) and isinstance(src.get("field"), str) for src in rule["src"]
) or ("dst" in rule and not (isinstance(rule["dst"], dict) and "field" in rule["dst"])):
return # the rule check already reported the malformed shape
fields = [(rule["dst"]["field"], False)] if "dst" in rule else []
fields += [(src["field"], True) for src in rule["src"]]
shift = form["operation"] in CONTROL_S1 and len(rule["src"]) > 1
count_field = rule["src"][1]["field"] if shift else None
for field, is_source in fields:
if field not in operands:
errors.append(f"{label}: XML has no operand {field}")
continue
data_format, size, is_input, is_output = operands[field]
bits = form.get(SOURCE_BITS_KEY) if is_source else None
expected = bits if type(bits) is int else form["width"]
if size != expected:
errors.append(f"{label}: {field} is {size} bits in the XML, declared {expected}")
if (is_input, is_output) != (is_source, not is_source):
errors.append(f"{label}: {field} direction disagrees with the XML")
if field == count_field:
if data_format != "FMT_NUM_U32":
errors.append(
f"{label}: control operand {field} has XML format {data_format}, not FMT_NUM_U32"
)
elif type(bits) is int:
if data_format != f"FMT_NUM_I{bits}":
errors.append(f"{label}: {field} has XML format {data_format}, not FMT_NUM_I{bits}")
elif is_source and data_format not in SOURCE_FORMATS.get(form["signedness"], ()):
errors.append(
f"{label}: signedness {form['signedness']} contradicts XML format {data_format}"
)
extra = sorted(set(operands) - {field for field, _ in fields})
if extra:
errors.append(f"{label}: XML operands {extra} are not covered by rule {form['operands']}")
def _identifier(encoding, opcode):
fields = dict((name, ranges) for name, ranges in encoding["fields"])
(offset, size), = fields["OP"]
base = encoding["identifiers"][0] & ~(((1 << size) - 1) << offset)
return base | (opcode << offset)
def validate(registry, snapshot):
"""Return every error in the registry; an empty list means it is valid."""
errors = []
unknown = sorted(set(registry) - TOP_KEYS)
if unknown:
errors.append(f"unknown top-level keys {unknown}")
if type(registry.get("schema")) is not int or registry["schema"] != SCHEMA:
errors.append(f"schema {registry.get('schema')!r} is not {SCHEMA}")
if registry.get("architecture") != ARCHITECTURE:
errors.append(f"architecture {registry.get('architecture')!r} is not {ARCHITECTURE}")
if registry.get("source_sha256") != snapshot["source"].get("sha256"):
errors.append("source_sha256 does not match the XML snapshot")
documents = registry.get("documents", {})
for name, document in documents.items():
if name not in DOCUMENTS:
errors.append(f"unknown document {name}")
elif document != PINNED_DOCUMENTS[name]:
errors.append(f"document {name}: differs from the pinned public document")
if "guide" not in documents:
errors.append("the guide document is not declared")
rules = registry.get("operand_rules", {})
for name, rule in rules.items():
_check_rule(name, rule, errors)
forms = registry.get("form", [])
if not forms:
errors.append("the registry declares no forms")
seen = {"name": set(), "opcode": set(), "variant": set()}
for index, form in enumerate(forms):
label = form.get("name", f"form #{index}")
missing = sorted(FORM_KEYS - set(form))
extra = sorted(
set(form) - FORM_KEYS
- {SHIFT_KEY, SHIFT_AMOUNT_KEY, RELATION_KEY, SOURCE_BITS_KEY, SOURCE_ORDER_KEY}
)
if missing:
errors.append(f"{label}: incomplete, missing {missing}")
if extra:
errors.append(f"{label}: unknown keys {extra}")
if missing:
continue
for key, vocabulary in (
("operation", OPERATIONS), ("signedness", SIGNEDNESS), ("carry_in", CARRY_IN),
("scc", SCC), ("vcc", MASK), ("exec", MASK), ("wave", WAVE),
):
if form[key] not in vocabulary:
errors.append(f"{label}: unknown {key} {form[key]!r}")
if not isinstance(form["name"], str) or not NAME.match(form["name"]):
errors.append(f"{label}: invalid name")
if not isinstance(form["variant"], str) or not VARIANT.match(form["variant"]):
errors.append(f"{label}: invalid variant {form['variant']!r}")
if form["variant"] in RESERVED_VARIANTS:
errors.append(f"{label}: variant {form['variant']!r} is reserved")
if type(form["opcode"]) is not int or not 0 <= form["opcode"] <= U16_MAX:
errors.append(f"{label}: invalid opcode")
if form["wave"] in WAVE and form["wave"] not in ENFORCED_WAVES:
errors.append(f"{label}: wave {form['wave']} has no decoder enforcement yet")
if type(form["width"]) is not int or form["width"] not in WIDTHS:
errors.append(f"{label}: width {form['width']} is not supported")
for key, value in (
("name", form["name"]),
("opcode", (form["family"], form["opcode"])),
# Variants are names in their operand rule's enum.
("variant", (_rule_enum(form), form["variant"])),
):
if value in seen[key]:
shown = form["variant"] if key == "variant" else value
errors.append(f"{label}: duplicate {key} {shown}")
seen[key].add(value)
if (form["operation"] in LOGICAL and form["signedness"] != "bitwise") or (
form["operation"] in ARITHMETIC and form["signedness"] == "bitwise"
):
errors.append(
f"{label}: signedness {form['signedness']} contradicts operation {form['operation']}"
)
if form["operation"] in SHIFTS:
bits = form.get(SHIFT_KEY)
if type(bits) is not int or not 0 < bits < 32 or (1 << bits) != form["width"]:
errors.append(
f"{label}: {SHIFT_KEY} must be log2 of the width ({form['width']}), got {bits!r}"
)
elif SHIFT_KEY in form:
errors.append(f"{label}: {SHIFT_KEY} on a non-shift operation")
if form["operation"] == "lshl_add":
amount = form.get(SHIFT_AMOUNT_KEY)
if type(amount) is not int or amount not in SHIFT_AMOUNTS:
errors.append(
f"{label}: {SHIFT_AMOUNT_KEY} must be one of {sorted(SHIFT_AMOUNTS)}, got {amount!r}"
)
elif SHIFT_AMOUNT_KEY in form:
errors.append(f"{label}: {SHIFT_AMOUNT_KEY} on a non-lshl_add operation")
if SOURCE_ORDER_KEY in form:
order = form[SOURCE_ORDER_KEY]
if not isinstance(order, str) or order not in SOURCE_ORDERS:
errors.append(f"{label}: unknown {SOURCE_ORDER_KEY} {order!r}")
elif _rule_kind(form) != "vector":
errors.append(f"{label}: {SOURCE_ORDER_KEY} on a non-vector form")
if form["operation"] in SCC_READERS and form["carry_in"] != "scc":
errors.append(f"{label}: operation {form['operation']} reads SCC (requires carry_in scc)")
if form["operation"] == "sext":
bits = form.get(SOURCE_BITS_KEY)
if type(bits) is not int or bits not in SOURCE_BITS:
errors.append(f"{label}: {SOURCE_BITS_KEY} must be one of {sorted(SOURCE_BITS)}, got {bits!r}")
elif SOURCE_BITS_KEY in form:
errors.append(f"{label}: {SOURCE_BITS_KEY} on a non-sext operation")
if form["operation"] == "compare":
relation = form.get(RELATION_KEY)
if not isinstance(relation, str) or relation not in RELATIONS:
errors.append(f"{label}: unknown or missing {RELATION_KEY} {relation!r}")
elif (relation, form["signedness"]) not in COMPARE_PRIMITIVES:
errors.append(f"{label}: no primitive implements {relation}/{form['signedness']}")
if form["scc"] != "relation":
errors.append(f"{label}: scc {form['scc']} contradicts compare (requires relation)")
if form["carry_in"] != "none":
errors.append(f"{label}: carry_in {form['carry_in']} contradicts compare")
primitive = ("relation", None, False)
elif _rule_kind(form) == "vector":
if RELATION_KEY in form:
errors.append(f"{label}: {RELATION_KEY} on a non-compare operation")
lowering = VECTOR_PRIMITIVES.get((form["operation"], form["signedness"]))
primitive = None if lowering is None else ("unchanged", lowering, False)
else:
if RELATION_KEY in form:
errors.append(f"{label}: {RELATION_KEY} on a non-compare operation")
primitive = PRIMITIVES.get((form["operation"], form["signedness"]))
if primitive is None:
errors.append(f"{label}: no primitive implements {form['operation']}/{form['signedness']}")
else:
scc, _, takes_carry = primitive
if form["scc"] != scc:
errors.append(
f"{label}: scc {form['scc']} contradicts {form['operation']}/"
f"{form['signedness']} (requires {scc})"
)
if form["carry_in"] == "scc" and not takes_carry:
errors.append(f"{label}: carry_in scc contradicts {form['operation']}/{form['signedness']}")
rule = rules.get(form["operands"])
if rule is None:
errors.append(f"{label}: unknown operand rule {form['operands']!r}")
elif rule.get("family") != form["family"]:
errors.append(f"{label}: operand rule {form['operands']} is for {rule.get('family')}")
elif form["operands"] in OPERAND_RULES and OPERAND_RULES[form["operands"]]["kind"] != (
"compare" if form["operation"] == "compare"
else "unary" if form["operation"] in UNARY
else "vector" if _rule_kind(form) == "vector" and form["operation"] not in UNARY
else "alu"
):
errors.append(f"{label}: operation {form['operation']} does not fit rule {form['operands']}")
_check_spec(label, form["spec"], documents, errors)
verify = form["verify"]
if not verify:
errors.append(f"{label}: no verification requirement")
if any(item not in EVIDENCE for item in verify):
errors.append(f"{label}: unknown verification requirement in {verify}")
if len(set(verify)) != len(verify):
errors.append(f"{label}: duplicate verification requirement")
_check_xml(form, rule, snapshot, errors)
return errors
def _implemented_rule(form):
operands = form.get("operands")
return OPERAND_RULES.get(operands) if isinstance(operands, str) else None
def _rule_kind(form):
"""The implemented kind of the form's operand rule, or None if unknown."""
rule = _implemented_rule(form)
return rule["kind"] if rule else None
def _rule_enum(form):
"""The generated enum of the form's operand rule, or None if unknown."""
rule = _implemented_rule(form)
return rule["enum"] if rule else None
def _check_spec(label, spec, documents, errors):
has_guide = False
for ref in spec:
if set(ref) != {"document", "section", "page"}:
errors.append(f"{label}: spec reference needs exactly document, section, page")
continue
if ref["document"] not in documents:
errors.append(f"{label}: spec cites undeclared document {ref['document']!r}")
if not SECTION.match(str(ref["section"])):
errors.append(f"{label}: invalid spec section {ref['section']!r}")
if type(ref["page"]) is not int or not 0 <= ref["page"] <= U16_MAX:
errors.append(f"{label}: invalid spec page")
if ref["document"] == "guide" and type(ref["page"]) is int and ref["page"] > 0:
has_guide = True
if not has_guide:
errors.append(f"{label}: missing a guide section and page reference")
def render(registry, snapshot):
"""Return the complete generated Rust source. Requires a valid registry."""
forms = registry["form"]
rule_names = sorted({form["operands"] for form in forms})
positions = {form["name"]: position for position, form in enumerate(forms)}
out = [
"// @generated by crates/isa/generate_semantics.py from crates/isa/semantics/rdna2.toml.",
"// Do not edit. Regenerate: python3 crates/isa/generate_semantics.py generate",
"",
"use crate::meta::EncodingFamily;",
"use crate::primitive;",
"use crate::semantics::{",
" CarryIn, Document, Evidence, FormSemantics, MaskEffect, Operation, OperandRule, SccEffect,",
" Signedness, SpecRef, VectorBinary, Wave,",
"};",
"use crate::CompareRelation;",
"",
"/// Registry schema of the generated tables.",
f"pub const GENERATED_SCHEMA: u32 = {registry['schema']};",
]
for rule_name in rule_names:
selected = [form for form in forms if form["operands"] == rule_name]
out += _render_enum(rule_name, selected, snapshot, positions)
out += [
"",
"/// Identity of every registry form, in registry order.",
f"pub const FORM_IDS: [(&str, EncodingFamily); {len(forms)}] = [",
]
for form in forms:
out.append(f" (\"{form['name']}\", EncodingFamily::{_rust_family(form['family'])}),")
out += [
"];",
"",
"/// One validated row per registry form, in registry order.",
f"pub static FORMS: [FormSemantics; {len(forms)}] = [",
]
for form in forms:
spec = ", ".join(
f"SpecRef {{ document: Document::{DOCUMENTS[ref['document']]}, "
f"section: \"{ref['section']}\", page: {ref['page']} }}"
for ref in form["spec"]
)
verify = ", ".join(f"Evidence::{EVIDENCE[item]}" for item in form["verify"])
out += [
" FormSemantics {",
f" name: \"{form['name']}\",",
f" family: EncodingFamily::{_rust_family(form['family'])},",
f" opcode: {form['opcode']},",
f" operation: Operation::{OPERATIONS[form['operation']]},",
f" signedness: Signedness::{SIGNEDNESS[form['signedness']]},",
f" carry_in: CarryIn::{CARRY_IN[form['carry_in']]},",
f" width: {form['width']},",
f" shift_count_bits: {form.get(SHIFT_KEY, 0)},",
f" shift_amount: {form.get(SHIFT_AMOUNT_KEY, 0)},",
f" swap_sources: {'true' if SOURCE_ORDER_KEY in form else 'false'},",
f" source_bits: {form.get(SOURCE_BITS_KEY, form['width'])},",
" relation: "
+ (f"Some(CompareRelation::{RELATIONS[form[RELATION_KEY]]})," if RELATION_KEY in form else "None,"),
f" scc: SccEffect::{SCC[form['scc']]},",
f" vcc: MaskEffect::{MASK[form['vcc']]},",
f" exec: MaskEffect::{MASK[form['exec']]},",
f" wave: Wave::{WAVE[form['wave']]},",
f" operands: OperandRule::{OPERAND_RULES[form['operands']]['rust']},",
f" spec: &[{spec}],",
f" verify: &[{verify}],",
" },",
]
out += ["];", ""]
return "\n".join(out)
def _render_enum(rule_name, forms, snapshot, positions):
enum = OPERAND_RULES[rule_name]["enum"]
kind = OPERAND_RULES[rule_name]["kind"]
table = re.sub(r"(?<!^)(?=[A-Z])", "_", enum).upper() + "_BY_OPCODE"
family = forms[0]["family"]
encoding = snapshot["encodings"][_family_encoding(family)]
mask = encoding["identifier_mask"]
(offset, size), = dict((name, ranges) for name, ranges in encoding["fields"])["OP"]
op_mask = ((1 << size) - 1) << offset
fixed_mask = mask & ~op_mask
fixed_bits = encoding["identifiers"][0] & fixed_mask
# Every identifier of the family must share the fixed bits, or the split
# into an encoding test plus an OP match would change which words match.
if any(identifier & fixed_mask != fixed_bits for identifier in encoding["identifiers"]) or (
mask & op_mask != op_mask
):
raise ValueError(f"{family}: identifiers do not split into fixed bits and OP")
out = [
"",
f"/// {family} operations declared in the semantic registry (operand rule `{rule_name}`).",
"#[derive(Clone, Copy, Debug, Eq, PartialEq)]",
f"pub enum {enum} {{",
]
for form in forms:
carry = " plus SCC" if form["carry_in"] == "scc" else ""
what = f"compare {form[RELATION_KEY]}" if kind == "compare" else form["operation"]
out += [
f" /// `{form['name'].lower()}` ({family} opcode {form['opcode']}): "
f"{form['signedness']} {what}{carry}, SCC = {form['scc']}.",
f" {form['variant']},",
]
by_opcode = {form["opcode"]: form["variant"] for form in forms}
out += [
"}",
"",
f"/// {enum} by {family} OP field value; `None` for undeclared opcodes.",
f"const {table}: [Option<{enum}>; {1 << size}] = [",
]
out += [
f" Some({enum}::{by_opcode[opcode]})," if opcode in by_opcode else " None,"
for opcode in range(1 << size)
]
out += [
"];",
"",
f"impl {enum} {{",
" /// Every operation, in registry order.",
f" pub const ALL: [Self; {len(forms)}] = [",
]
out += [f" Self::{form['variant']}," for form in forms]
out += [
" ];",
"",
f" /// Selects the operation from a first instruction word: the {family} encoding",
f" /// bits (mask 0x{fixed_mask:09_x}) and then the OP field (bits {offset}-{offset + size - 1}).",
" pub const fn from_word(word: u32) -> Option<Self> {",
f" if word & 0x{fixed_mask:09_x} != 0x{fixed_bits:09_x} {{",
" return None;",
" }",
f" {table}[((word >> {offset}) & 0x{(1 << size) - 1:x}) as usize]",
" }",
"",
" /// Lower-case mnemonic.",
" pub const fn mnemonic(self) -> &'static str {",
" match self {",
]
out += [f" Self::{form['variant']} => \"{form['name'].lower()}\"," for form in forms]
out += [
" }",
" }",
"",
" /// The validated registry row.",
" pub fn semantics(self) -> &'static FormSemantics {",
" &FORMS[match self {",
]
out += [f" Self::{form['variant']} => {positions[form['name']]}," for form in forms]
out += [
" }]",
" }",
]
if kind == "unary":
out += [
"",
" /// Whether the operation writes SCC.",
" pub const fn writes_scc(self) -> bool {",
" match self {",
]
out += [
f" Self::{form['variant']} => {'false' if form['scc'] == 'unchanged' else 'true'},"
for form in forms
]
out += [
" }",
" }",
"",
" /// The result and, for forms that write it, the new SCC (`None` leaves SCC",
" /// unchanged).",
" pub const fn evaluate(self, src: u32) -> (u32, Option<bool>) {",
" match self {",
]
for form in forms:
_, function, _ = PRIMITIVES[(form["operation"], form["signedness"])]
if form["operation"] == "sext":
value = f"primitive::{function}(src, {form[SOURCE_BITS_KEY]})"
else:
value = f"primitive::{function}(src)"
if form["scc"] == "unchanged":
out.append(f" Self::{form['variant']} => ({value}, None),")
else:
out += [
f" Self::{form['variant']} => {{",
f" let (value, scc) = {value};",
" (value, Some(scc))",
" }",
]
out += [" }", " }", "}"]
return out
if kind == "vector":
out += [
"",
" /// Assembler name of the 32-bit (VOP2) encoding, as LLVM prints it.",
" pub const fn assembly_name(self) -> &'static str {",
" match self {",
]
out += [f" Self::{form['variant']} => \"{form['name'].lower()}_e32\"," for form in forms]
out += [
" }",
" }",
"",
" /// The per-lane operation its MSL lowering uses.",
" pub const fn lowering(self) -> VectorBinary {",
" match self {",
]
out += [
f" Self::{form['variant']} => "
f"VectorBinary::{VECTOR_PRIMITIVES[(form['operation'], form['signedness'])]},"
for form in forms
]
out += [
" }",
" }",
"",
" /// Whether the operation reads its sources reversed (`D = op(S1, S0)`).",
" pub const fn swaps_sources(self) -> bool {",
" match self {",
]
out += [
f" Self::{form['variant']} => {'true' if SOURCE_ORDER_KEY in form else 'false'},"
for form in forms
]
out += [" }", " }", "}"]
return out
if kind == "compare":
out += [
"",
" /// The relation tested, with S0 on the left.",
" pub const fn relation(self) -> CompareRelation {",
" match self {",
]
out += [
f" Self::{form['variant']} => CompareRelation::{RELATIONS[form[RELATION_KEY]]},"
for form in forms
]
out += [
" }",
" }",
"",
" /// The new SCC: whether the relation holds for S0 and S1.",
" pub const fn test(self, src0: u32, src1: u32) -> bool {",
" match self {",
]
for form in forms:
function = COMPARE_PRIMITIVES[(form[RELATION_KEY], form["signedness"])]
out.append(f" Self::{form['variant']} => primitive::{function}(src0, src1),")
out += [" }", " }", "}"]
return out
out += [
"",
" /// Whether the operation reads SCC (carry-in, borrow-in or select condition).",
" pub const fn reads_scc(self) -> bool {",
" match self {",
]
out += [
f" Self::{form['variant']} => {'true' if form['carry_in'] == 'scc' else 'false'},"
for form in forms
]
out += [
" }",
" }",
"",
" /// Whether the operation writes SCC.",
" pub const fn writes_scc(self) -> bool {",
" match self {",
]
out += [
f" Self::{form['variant']} => {'false' if form['scc'] == 'unchanged' else 'true'},"
for form in forms
]
out += [
" }",
" }",
"",
" /// The result and, for forms that write it, the new SCC (`None` leaves SCC",
" /// unchanged). `scc_in` is the SCC read by forms that consume it (ignored by",
" /// the others).",
" pub const fn evaluate(self, src0: u32, src1: u32, scc_in: bool) -> (u32, Option<bool>) {",
" match self {",
]
for form in forms:
_, function, takes_carry = PRIMITIVES[(form["operation"], form["signedness"])]
if takes_carry:
argument = "scc_in" if form["carry_in"] == "scc" else "false"
call = f"primitive::{function}(src0, src1, {argument})"
elif form["operation"] in SHIFTS:
mask = (1 << form[SHIFT_KEY]) - 1
call = f"primitive::{function}(src0, src1 & 0x{mask:x})"
elif form["operation"] == "lshl_add":
call = f"primitive::{function}(src0, src1, {form[SHIFT_AMOUNT_KEY]})"
else:
call = f"primitive::{function}(src0, src1)"
if form["scc"] == "unchanged":
out.append(f" Self::{form['variant']} => ({call}, None),")
else:
out += [
f" Self::{form['variant']} => {{",
f" let (value, scc) = {call};",
" (value, Some(scc))",
" }",
]
out += [" }", " }", "}"]
return out
def _display(path):
try:
return path.resolve().relative_to(ROOT)
except ValueError:
return path
def main():
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("mode", nargs="?", choices=("generate", "validate"))
parser.add_argument("--check", action="store_true", help="fail if the committed file is stale")
parser.add_argument("--registry", type=Path, default=REGISTRY)
parser.add_argument("--snapshot", type=Path, default=SNAPSHOT)
parser.add_argument("--output", type=Path, default=RUST)
arguments = parser.parse_args()
if bool(arguments.mode) == arguments.check:
parser.error("choose exactly one of generate, validate or --check")
registry = load_registry(arguments.registry)
snapshot = load_snapshot(arguments.snapshot)
errors = validate(registry, snapshot)
if errors:
for error in errors:
print(f"error: {error}", file=sys.stderr)
return 1
count = len(registry["form"])
if arguments.mode == "validate":
print(f"registry valid: {count} forms")
return 0
text = render(registry, snapshot)
if arguments.check:
current = arguments.output.read_text(encoding="utf-8") if arguments.output.exists() else ""
if current != text:
print(f"{_display(arguments.output)} is stale; run generate", file=sys.stderr)
return 1
print(f"registry valid and generated code current: {count} forms")
return 0
arguments.output.write_text(text, encoding="utf-8")
print(f"wrote {_display(arguments.output)}: {count} forms")
return 0
if __name__ == "__main__":
sys.exit(main())
File diff suppressed because it is too large. Load diff
+164 -14
View File
@@ -2,13 +2,26 @@
use std::fmt;
pub mod meta;
pub mod primitive;
mod rdna2;
pub mod semantics;
#[rustfmt::skip]
mod rdna2_meta;
#[rustfmt::skip]
mod semantics_gen;
pub use rdna2::{
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ,
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT,
V_ADD_F32, V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_INTERP_P1_F32, V_INTERP_P2_F32,
V_LSHLREV_B32, V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, V_ADD_F32,
V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_CMP_EQ_I32, V_CMP_EQ_U32, V_CMP_GE_I32, V_CMP_GE_U32,
V_CMP_GT_I32, V_CMP_GT_U32, V_CMP_LE_I32, V_CMP_LE_U32, V_CMP_LT_I32, V_CMP_LT_U32,
V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32, V_LSHRREV_B32,
V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
};
pub use semantics_gen::{ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp};
/// SGPR index of `vcc_lo`, the Wave32 vector condition code.
pub const VCC_LO: u8 = 106;
/// Selects the instruction encoding independently of the container and execution ABI.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
@@ -42,6 +55,8 @@ impl Opcode {
pub enum VectorSource {
/// VGPR index.
Register(u8),
/// Normal SGPR index (s0-s105) or `vcc_lo` (106), read as a wave-uniform value.
Scalar(u8),
/// Inline integer or literal word, represented by its bits.
Immediate(u32),
}
@@ -50,6 +65,8 @@ impl fmt::Display for VectorSource {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Register(register) => write!(formatter, "v{register}"),
Self::Scalar(VCC_LO) => formatter.write_str("vcc_lo"),
Self::Scalar(register) => write!(formatter, "s{register}"),
Self::Immediate(value) => write!(formatter, "0x{value:x}"),
}
}
@@ -76,6 +93,81 @@ impl fmt::Display for ScalarSource {
}
}
/// Relation tested by a VOPC integer compare; S0 is SRC0 and S1 is VSRC1.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CompareRelation {
/// S0 < S1 (opcode offset 1).
Less,
/// S0 == S1 (offset 2).
Equal,
/// S0 <= S1 (offset 3).
LessOrEqual,
/// S0 > S1 (offset 4).
Greater,
/// S0 != S1 (offset 5).
NotEqual,
/// S0 >= S1 (offset 6).
GreaterOrEqual,
}
/// A 32-bit VOPC integer compare: one relation over signed or unsigned operands.
///
/// The per-lane test follows the RDNA 2 ISA guide, section 12.9 (Table 59) and
/// the pinned XML descriptions. VCC and EXEC rules are in
/// docs/shaders/vector-compare.md.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct VectorCompareOp {
/// The tested relation.
pub relation: CompareRelation,
/// `_i32` (two's complement) when true, `_u32` when false.
pub signed: bool,
}
impl VectorCompareOp {
/// Lower-case mnemonic of the 32-bit VOPC encoding.
pub fn mnemonic(self) -> &'static str {
const SIGNED: [&str; 6] = [
"v_cmp_lt_i32_e32",
"v_cmp_eq_i32_e32",
"v_cmp_le_i32_e32",
"v_cmp_gt_i32_e32",
"v_cmp_ne_i32_e32",
"v_cmp_ge_i32_e32",
];
const UNSIGNED: [&str; 6] = [
"v_cmp_lt_u32_e32",
"v_cmp_eq_u32_e32",
"v_cmp_le_u32_e32",
"v_cmp_gt_u32_e32",
"v_cmp_ne_u32_e32",
"v_cmp_ge_u32_e32",
];
let index = self.relation as usize;
if self.signed {
SIGNED[index]
} else {
UNSIGNED[index]
}
}
/// The per-lane test result for operand bits S0 and S1.
pub fn test(self, src0: u32, src1: u32) -> bool {
let ordering = if self.signed {
(src0 as i32).cmp(&(src1 as i32))
} else {
src0.cmp(&src1)
};
match self.relation {
CompareRelation::Less => ordering.is_lt(),
CompareRelation::Equal => ordering.is_eq(),
CompareRelation::LessOrEqual => ordering.is_le(),
CompareRelation::Greater => ordering.is_gt(),
CompareRelation::NotEqual => ordering.is_ne(),
CompareRelation::GreaterOrEqual => ordering.is_ge(),
}
}
}
/// Output targeted by a supported uncompressed four-component export.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ExportTarget {
@@ -117,11 +209,43 @@ pub enum Instruction {
AddNoCarryU32 { dst: u8, src0: u8, src1: u8 },
/// SOP1 32-bit move to a normal SGPR or an EXEC/VCC half.
ScalarMoveB32 { dst: u8, src: ScalarSource },
/// SOPC 32-bit equality comparison writing SCC.
ScalarCompareEqU32 {
/// SOP1 32-bit unary integer operation writing a normal SGPR (s0-s105) and,
/// for some operations, SCC.
ScalarUnary {
op: ScalarUnaryOp,
dst: u8,
src: ScalarSource,
},
/// SOP2 32-bit integer operation writing a normal SGPR (s0-s105) and, for
/// most operations, SCC; `s_cselect_b32` also reads SCC.
ScalarAlu {
op: ScalarAluOp,
dst: u8,
src0: ScalarSource,
src1: ScalarSource,
},
/// SOPC 32-bit integer compare writing only SCC.
ScalarCompare {
op: ScalarCompareOp,
src0: ScalarSource,
src1: ScalarSource,
},
/// VOPC 32-bit integer compare writing a Wave32 mask to `vcc_lo`.
/// `src0` is a VGPR, `s0-s105`, `vcc_lo`, an inline integer or a literal.
VectorCompare {
op: VectorCompareOp,
src0: VectorSource,
src1: u8,
},
/// VOP2 32-bit per-lane integer operation from the semantic registry.
/// `src0` is a VGPR, `s0-s105`, `vcc_lo`, an inline integer or a literal;
/// `src1` is a VGPR. Inactive lanes keep `dst`.
VectorAlu {
op: VectorAluOp,
dst: u8,
src0: VectorSource,
src1: u8,
},
/// SOPP jump to a stream byte offset when SCC is clear.
BranchSccZero { target: usize },
/// SOPP jump when the Wave32 execution mask is empty.
@@ -174,6 +298,21 @@ pub enum Instruction {
EndProgram,
}
/// Formats an SGPR destination with LLVM's names for the EXEC and VCC halves.
struct ScalarDestination(u8);
impl fmt::Display for ScalarDestination {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.0 {
106 => formatter.write_str("vcc_lo"),
107 => formatter.write_str("vcc_hi"),
126 => formatter.write_str("exec_lo"),
127 => formatter.write_str("exec_hi"),
register => write!(formatter, "s{register}"),
}
}
}
impl Instruction {
/// Returns the mnemonic for the exact encoding family represented.
pub fn mnemonic(self) -> &'static str {
@@ -185,7 +324,11 @@ impl Instruction {
Self::MoveB32 { .. } => "v_mov_b32_e32",
Self::AddNoCarryU32 { .. } => "v_add_nc_u32_e64",
Self::ScalarMoveB32 { .. } => "s_mov_b32",
Self::ScalarCompareEqU32 { .. } => "s_cmp_eq_u32",
Self::ScalarUnary { op, .. } => op.mnemonic(),
Self::ScalarAlu { op, .. } => op.mnemonic(),
Self::ScalarCompare { op, .. } => op.mnemonic(),
Self::VectorCompare { op, .. } => op.mnemonic(),
Self::VectorAlu { op, .. } => op.assembly_name(),
Self::BranchSccZero { .. } => "s_cbranch_scc0",
Self::BranchExecZero { .. } => "s_cbranch_execz",
Self::BranchVccZero { .. } => "s_cbranch_vccz",
@@ -247,14 +390,21 @@ impl fmt::Display for Instruction {
| Self::VectorMulF32 { dst, src0, src1 } => {
write!(formatter, " v{dst}, v{src0}, v{src1}")
}
Self::ScalarMoveB32 { dst, src } => match dst {
106 => write!(formatter, " vcc_lo, {src}"),
107 => write!(formatter, " vcc_hi, {src}"),
126 => write!(formatter, " exec_lo, {src}"),
127 => write!(formatter, " exec_hi, {src}"),
_ => write!(formatter, " s{dst}, {src}"),
},
Self::ScalarCompareEqU32 { src0, src1 } => write!(formatter, " {src0}, {src1}"),
Self::ScalarMoveB32 { dst, src } | Self::ScalarUnary { dst, src, .. } => {
write!(formatter, " {}, {src}", ScalarDestination(dst))
}
Self::ScalarAlu {
dst, src0, src1, ..
} => write!(formatter, " {}, {src0}, {src1}", ScalarDestination(dst)),
Self::ScalarCompare { src0, src1, .. } => write!(formatter, " {src0}, {src1}"),
Self::VectorCompare { src0, src1, .. } => {
write!(formatter, " vcc_lo, {src0}, v{src1}")
}
Self::VectorAlu {
dst, src0, src1, ..
} => {
write!(formatter, " v{dst}, {src0}, v{src1}")
}
Self::Branch { target }
| Self::BranchSccZero { target }
| Self::BranchExecZero { target }
+424
View File
@@ -0,0 +1,424 @@
//! Complete gfx1030 instruction metadata generated from AMD's public RDNA 2 XML.
//!
//! Identification here establishes an instruction's form and length only. It is
//! not semantic support: [`crate::Instruction`] lists the forms Xenora executes.
//! The XML names literal, SDWA, DPP and NSA variants without saying when they
//! apply, so [`identify`] implements those length rules by hand from the RDNA 2
//! ISA reference guide (see docs/research/rdna2.md).
use std::fmt;
pub use crate::rdna2_meta::{FIELDS, FORMS, SOURCE_SHA256};
/// AMD base encoding of an instruction form.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[allow(missing_docs)]
pub enum EncodingFamily {
Ds,
Exp,
Flat,
Global,
Mimg,
Mtbuf,
Mubuf,
Scratch,
Smem,
Sop1,
Sop2,
Sopc,
Sopk,
Sopp,
Vintrp,
Vop1,
Vop2,
Vop3,
Vop3Sdst,
Vop3p,
Vopc,
}
impl EncodingFamily {
/// Every family, in table order.
pub const ALL: [Self; 21] = [
Self::Ds,
Self::Exp,
Self::Flat,
Self::Global,
Self::Mimg,
Self::Mtbuf,
Self::Mubuf,
Self::Scratch,
Self::Smem,
Self::Sop1,
Self::Sop2,
Self::Sopc,
Self::Sopk,
Self::Sopp,
Self::Vintrp,
Self::Vop1,
Self::Vop2,
Self::Vop3,
Self::Vop3Sdst,
Self::Vop3p,
Self::Vopc,
];
/// Lower-case name used in reports.
pub fn name(self) -> &'static str {
match self {
Self::Ds => "ds",
Self::Exp => "exp",
Self::Flat => "flat",
Self::Global => "global",
Self::Mimg => "mimg",
Self::Mtbuf => "mtbuf",
Self::Mubuf => "mubuf",
Self::Scratch => "scratch",
Self::Smem => "smem",
Self::Sop1 => "sop1",
Self::Sop2 => "sop2",
Self::Sopc => "sopc",
Self::Sopk => "sopk",
Self::Sopp => "sopp",
Self::Vintrp => "vintrp",
Self::Vop1 => "vop1",
Self::Vop2 => "vop2",
Self::Vop3 => "vop3",
Self::Vop3Sdst => "vop3-sdst",
Self::Vop3p => "vop3p",
Self::Vopc => "vopc",
}
}
}
/// Control-flow flags recorded by the XML.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct FormFlags(pub u8);
impl FormFlags {
#[allow(missing_docs)]
pub const NONE: Self = Self(0);
#[allow(missing_docs)]
pub const BRANCH: Self = Self(1);
#[allow(missing_docs)]
pub const CONDITIONAL: Self = Self(2);
#[allow(missing_docs)]
pub const INDIRECT: Self = Self(4);
#[allow(missing_docs)]
pub const TERMINATOR: Self = Self(8);
#[allow(missing_docs)]
pub const IMMEDIATE: Self = Self(16);
/// Whether every flag in `other` is set.
pub fn contains(self, other: Self) -> bool {
self.0 & other.0 == other.0
}
}
/// Extension words an instruction form may carry.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Extensions(pub u8);
impl Extensions {
#[allow(missing_docs)]
pub const NONE: Self = Self(0);
/// A source field may select a trailing 32-bit literal.
pub const LITERAL: Self = Self(1);
/// The form always carries a trailing 32-bit literal.
pub const ALWAYS_LITERAL: Self = Self(2);
#[allow(missing_docs)]
pub const SDWA: Self = Self(4);
#[allow(missing_docs)]
pub const DPP8: Self = Self(8);
#[allow(missing_docs)]
pub const DPP16: Self = Self(16);
/// MIMG non-sequential address dwords.
pub const NSA: Self = Self(32);
/// Whether every extension in `other` is allowed.
pub fn contains(self, other: Self) -> bool {
self.0 & other.0 == other.0
}
}
/// One encoded field: pieces of (bit offset, bit count), least significant piece first.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct FieldLayout {
#[allow(missing_docs)]
pub name: &'static str,
#[allow(missing_docs)]
pub pieces: &'static [(u8, u8)],
}
impl FieldLayout {
/// Extracts the field from the instruction's first two dwords.
pub fn extract(&self, value: u64) -> u32 {
let mut result = 0u64;
let mut shift = 0;
for &(offset, count) in self.pieces {
result |= ((value >> offset) & ((1u64 << count) - 1)) << shift;
shift += count;
}
result as u32
}
}
/// An operand as described by the XML.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[allow(missing_docs)]
pub struct OperandInfo {
pub field: &'static str,
pub format: &'static str,
pub kind: &'static str,
pub bits: u16,
pub input: bool,
pub output: bool,
pub implicit: bool,
/// Whether the operand occupies microcode bits.
pub encoded: bool,
}
/// One instruction in one base encoding.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[allow(missing_docs)]
pub struct Form {
pub name: &'static str,
pub family: EncodingFamily,
pub opcode: u16,
/// Identifying bits over the first two dwords (little-endian, first dword low).
pub mask: u64,
pub bits: u64,
/// Base length before literal, SDWA, DPP or NSA words.
pub bytes: u8,
pub flags: FormFlags,
pub extensions: Extensions,
pub group: &'static str,
pub operands: &'static [OperandInfo],
}
impl Form {
/// The base encoding's field layouts.
pub fn fields(&self) -> &'static [FieldLayout] {
FIELDS
.iter()
.find(|(family, _)| *family == self.family)
.map(|(_, fields)| *fields)
.unwrap_or(&[])
}
/// The named field's layout, if the encoding has one.
pub fn field(&self, name: &str) -> Option<&'static FieldLayout> {
self.fields().iter().find(|field| field.name == name)
}
}
/// Which extension words an identified instruction carries.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct Trailer {
/// A 32-bit literal follows the base encoding.
pub literal: bool,
/// SDWA, DPP8 or DPP16 control dword (VOP1, VOP2, VOPC only).
pub vector_control: Option<VectorControl>,
/// Extra MIMG address dwords.
pub nsa_dwords: u8,
}
/// The dword that replaces SRC0 in a VOP1, VOP2 or VOPC instruction.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[allow(missing_docs)]
pub enum VectorControl {
Sdwa,
Dpp8 { fetch_inactive: bool },
Dpp16,
}
/// An identified instruction.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Identified {
/// The matched form.
pub form: &'static Form,
/// First two dwords; the second is zero for 32-bit encodings.
pub raw: u64,
/// Total length in bytes, including extension words.
pub len: usize,
/// Extension words present.
pub trailer: Trailer,
}
impl Identified {
/// Extracts a named field of the base encoding.
pub fn field(&self, name: &str) -> Option<u32> {
self.form.field(name).map(|field| field.extract(self.raw))
}
}
/// Why an instruction could not be identified.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum IdentifyError {
/// Fewer bytes remain than the encoding or its extension words need.
Truncated {
/// Bytes required from the instruction start.
needed: usize,
},
/// No gfx1030 form matches; the bits are reserved or belong to another architecture.
Unassigned,
/// The bits select an extension the form does not allow.
InvalidExtension(&'static str),
}
impl fmt::Display for IdentifyError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Truncated { needed } => write!(formatter, "truncated: needs {needed} bytes"),
Self::Unassigned => formatter.write_str("no gfx1030 instruction has this encoding"),
Self::InvalidExtension(what) => write!(formatter, "invalid extension: {what}"),
}
}
}
impl std::error::Error for IdentifyError {}
/// Source operand value selecting a trailing literal (XML `SRC_LITERAL`).
pub const SRC_LITERAL: u32 = 255;
/// VOP1/VOP2/VOPC SRC0 value selecting an SDWA control dword.
pub const SRC_SDWA: u32 = 0xf9;
/// VOP1/VOP2/VOPC SRC0 value selecting a DPP16 control dword.
pub const SRC_DPP16: u32 = 0xfa;
/// VOP1/VOP2/VOPC SRC0 value selecting a DPP8 control dword.
pub const SRC_DPP8: u32 = 0xe9;
/// DPP8 with fetch-inactive set.
pub const SRC_DPP8_FI: u32 = 0xea;
fn read_dword(bytes: &[u8], index: usize) -> Option<u32> {
let start = index.checked_mul(4)?;
let chunk = bytes.get(start..start.checked_add(4)?)?;
Some(u32::from_le_bytes(chunk.try_into().ok()?))
}
/// Finds the form whose identifying bits match.
///
/// Masks never overlap ambiguously; the generator rejects such tables.
pub fn lookup(raw: u64) -> Option<&'static Form> {
FORMS.iter().find(|form| raw & form.mask == form.bits)
}
/// Identifies the instruction at the start of `bytes` and computes its length.
pub fn identify(bytes: &[u8]) -> Result<Identified, IdentifyError> {
let first = read_dword(bytes, 0).ok_or(IdentifyError::Truncated { needed: 4 })?;
let second = read_dword(bytes, 1);
let raw_guess = u64::from(first) | (u64::from(second.unwrap_or(0)) << 32);
// A 32-bit form never inspects the second dword; a 64-bit form needs it.
let form = FORMS
.iter()
.find(|form| (form.bytes == 4 || second.is_some()) && raw_guess & form.mask == form.bits)
.or_else(|| {
// Distinguish a truncated 64-bit instruction from unassigned bits.
FORMS.iter().find(|form| {
form.bytes == 8
&& u64::from(first) & form.mask & 0xffff_ffff == form.bits & 0xffff_ffff
})
})
.ok_or(IdentifyError::Unassigned)?;
if form.bytes == 8 && second.is_none() {
return Err(IdentifyError::Truncated { needed: 8 });
}
let raw = if form.bytes == 4 {
u64::from(first)
} else {
raw_guess
};
let mut trailer = Trailer::default();
let source = |name: &str| form.field(name).map(|field| field.extract(raw));
match form.family {
EncodingFamily::Sop1 | EncodingFamily::Sop2 | EncodingFamily::Sopc => {
trailer.literal = [source("SSRC0"), source("SSRC1")]
.into_iter()
.flatten()
.any(|value| value == SRC_LITERAL);
}
EncodingFamily::Vop1 | EncodingFamily::Vop2 | EncodingFamily::Vopc => {
match source("SRC0") {
Some(SRC_LITERAL) => trailer.literal = true,
Some(SRC_SDWA) => trailer.vector_control = Some(VectorControl::Sdwa),
Some(SRC_DPP16) => trailer.vector_control = Some(VectorControl::Dpp16),
Some(SRC_DPP8) => {
trailer.vector_control = Some(VectorControl::Dpp8 {
fetch_inactive: false,
})
}
Some(SRC_DPP8_FI) => {
trailer.vector_control = Some(VectorControl::Dpp8 {
fetch_inactive: true,
})
}
_ => {}
}
}
EncodingFamily::Vop3 | EncodingFamily::Vop3Sdst | EncodingFamily::Vop3p => {
// An attribute field (XML OPR_ATTR) is not an operand selector: in the
// VOP3 interpolation forms SRC0 holds {attr_word, attr_chan, attr}
// bit-fields (AMD RDNA 2 ISA guide, section 10.4.2), so 255 there
// does not select a literal.
trailer.literal = ["SRC0", "SRC1", "SRC2"]
.into_iter()
.filter(|name| {
!form
.operands
.iter()
.any(|operand| operand.field == *name && operand.kind == "OPR_ATTR")
})
.filter_map(source)
.any(|value| value == SRC_LITERAL);
}
EncodingFamily::Mimg => {
trailer.nsa_dwords = source("NSA").unwrap_or(0) as u8;
}
_ => {}
}
if form.extensions.contains(Extensions::ALWAYS_LITERAL) {
trailer.literal = true;
} else if trailer.literal && !form.extensions.contains(Extensions::LITERAL) {
return Err(IdentifyError::InvalidExtension("literal"));
}
match trailer.vector_control {
Some(VectorControl::Sdwa) if !form.extensions.contains(Extensions::SDWA) => {
return Err(IdentifyError::InvalidExtension("sdwa"));
}
Some(VectorControl::Dpp8 { .. }) if !form.extensions.contains(Extensions::DPP8) => {
return Err(IdentifyError::InvalidExtension("dpp8"));
}
Some(VectorControl::Dpp16) if !form.extensions.contains(Extensions::DPP16) => {
return Err(IdentifyError::InvalidExtension("dpp16"));
}
_ => {}
}
if trailer.nsa_dwords > 0 && !form.extensions.contains(Extensions::NSA) {
return Err(IdentifyError::InvalidExtension("nsa"));
}
let len = usize::from(form.bytes)
+ 4 * usize::from(trailer.literal)
+ 4 * usize::from(trailer.vector_control.is_some())
+ 4 * usize::from(trailer.nsa_dwords);
if bytes.len() < len {
return Err(IdentifyError::Truncated { needed: len });
}
Ok(Identified {
form,
raw,
len,
trailer,
})
}
/// Number of forms per encoding family in the metadata.
pub fn inventory() -> Vec<(EncodingFamily, usize)> {
EncodingFamily::ALL
.iter()
.map(|&family| {
(
family,
FORMS.iter().filter(|form| form.family == family).count(),
)
})
.collect()
}
+318
View File
@@ -0,0 +1,318 @@
//! Reusable integer semantic primitives selected by the generated registry dispatch.
//!
//! Each function implements one closed [`crate::semantics::Operation`] at one
//! signedness, with the condition-code rule the RDNA 2 guide gives for it
//! (section 5.3, "Scalar Condition Code", and the SOP2 pseudocode in 12.1).
//! Forms share a primitive only when their declared operation, signedness and
//! SCC effect are identical; the generator never selects one by mnemonic.
/// Unsigned `a + b + carry_in` and the carry-out of bit 31.
pub const fn add_carry_u32(a: u32, b: u32, carry_in: bool) -> (u32, bool) {
let (partial, first) = a.overflowing_add(b);
let (value, second) = partial.overflowing_add(carry_in as u32);
(value, first || second)
}
/// Unsigned `a - b - borrow_in` and the borrow (`b + borrow_in > a`).
pub const fn sub_borrow_u32(a: u32, b: u32, borrow_in: bool) -> (u32, bool) {
let (partial, first) = a.overflowing_sub(b);
let (value, second) = partial.overflowing_sub(borrow_in as u32);
(value, first || second)
}
/// Two's-complement `a + b` and whether the exact sum leaves the i32 range.
pub const fn add_overflow_i32(a: u32, b: u32) -> (u32, bool) {
let (value, overflow) = (a as i32).overflowing_add(b as i32);
(value as u32, overflow)
}
/// Two's-complement `a - b` and whether the exact difference leaves the i32 range.
pub const fn sub_overflow_i32(a: u32, b: u32) -> (u32, bool) {
let (value, overflow) = (a as i32).overflowing_sub(b as i32);
(value as u32, overflow)
}
/// Bitwise AND and whether the result is nonzero.
pub const fn and_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = a & b;
(value, value != 0)
}
/// Bitwise OR and whether the result is nonzero.
pub const fn or_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = a | b;
(value, value != 0)
}
/// Bitwise XOR and whether the result is nonzero.
pub const fn xor_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = a ^ b;
(value, value != 0)
}
/// Bitwise `a & !b` and whether the result is nonzero.
pub const fn andn2_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = a & !b;
(value, value != 0)
}
/// Bitwise `a | !b` and whether the result is nonzero.
pub const fn orn2_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = a | !b;
(value, value != 0)
}
/// Bitwise `!(a & b)` and whether the result is nonzero.
pub const fn nand_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = !(a & b);
(value, value != 0)
}
/// Bitwise `!(a | b)` and whether the result is nonzero.
pub const fn nor_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = !(a | b);
(value, value != 0)
}
/// Bitwise `!(a ^ b)` and whether the result is nonzero.
pub const fn xnor_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = !(a ^ b);
(value, value != 0)
}
/// `a << count` and whether the result is nonzero. The caller masks the count
/// to the declared count width, so `count` is below 32.
pub const fn lshl_nonzero_b32(a: u32, count: u32) -> (u32, bool) {
let value = a << count;
(value, value != 0)
}
/// Logical `a >> count` (zero fill) and whether the result is nonzero; `count` is below 32.
pub const fn lshr_nonzero_b32(a: u32, count: u32) -> (u32, bool) {
let value = a >> count;
(value, value != 0)
}
/// Arithmetic `a >> count` (sign fill) and whether the result is nonzero; `count` is below 32.
pub const fn ashr_nonzero_i32(a: u32, count: u32) -> (u32, bool) {
let value = ((a as i32) >> count) as u32;
(value, value != 0)
}
/// `a == b` on the raw bits; signedness does not matter for equality.
pub const fn eq_b32(a: u32, b: u32) -> bool {
a == b
}
/// `a != b` on the raw bits (the guide's LG, "less or greater").
pub const fn ne_b32(a: u32, b: u32) -> bool {
a != b
}
/// Two's-complement `a > b`.
pub const fn gt_i32(a: u32, b: u32) -> bool {
(a as i32) > (b as i32)
}
/// Two's-complement `a >= b`.
pub const fn ge_i32(a: u32, b: u32) -> bool {
(a as i32) >= (b as i32)
}
/// Two's-complement `a < b`.
pub const fn lt_i32(a: u32, b: u32) -> bool {
(a as i32) < (b as i32)
}
/// Two's-complement `a <= b`.
pub const fn le_i32(a: u32, b: u32) -> bool {
(a as i32) <= (b as i32)
}
/// Unsigned `a > b`.
pub const fn gt_u32(a: u32, b: u32) -> bool {
a > b
}
/// Unsigned `a >= b`.
pub const fn ge_u32(a: u32, b: u32) -> bool {
a >= b
}
/// Unsigned `a < b`.
pub const fn lt_u32(a: u32, b: u32) -> bool {
a < b
}
/// Unsigned `a <= b`.
pub const fn le_u32(a: u32, b: u32) -> bool {
a <= b
}
/// `!a` and whether the result is nonzero.
pub const fn not_nonzero_b32(a: u32) -> (u32, bool) {
let value = !a;
(value, value != 0)
}
/// `a` with bit `i` moved to bit `31 - i`.
pub const fn brev_b32(a: u32) -> u32 {
a.reverse_bits()
}
/// Number of zero bits and whether that count is nonzero.
pub const fn bcnt0_nonzero_b32(a: u32) -> (u32, bool) {
let value = a.count_zeros();
(value, value != 0)
}
/// Number of one bits and whether that count is nonzero.
pub const fn bcnt1_nonzero_b32(a: u32) -> (u32, bool) {
let value = a.count_ones();
(value, value != 0)
}
/// Index of the lowest zero bit, or `0xffffffff` (-1) when every bit is one.
pub const fn ff0_b32(a: u32) -> u32 {
if a == u32::MAX {
u32::MAX
} else {
a.trailing_ones()
}
}
/// Index of the lowest one bit, or `0xffffffff` (-1) when every bit is zero.
pub const fn ff1_b32(a: u32) -> u32 {
if a == 0 { u32::MAX } else { a.trailing_zeros() }
}
/// Zeros above the highest one bit, or `0xffffffff` (-1) when `a` is zero.
pub const fn flbit_b32(a: u32) -> u32 {
if a == 0 { u32::MAX } else { a.leading_zeros() }
}
/// Bits above the highest bit that differs from the sign bit, or `0xffffffff`
/// (-1) when every bit equals the sign bit (`a` is 0 or -1).
pub const fn flbit_i32(a: u32) -> u32 {
let differing = if a >> 31 == 0 { a } else { !a };
if differing == 0 {
u32::MAX
} else {
differing.leading_zeros()
}
}
/// The low `bits` of `a` sign-extended to 32 bits; `bits` is 8 or 16.
pub const fn sext_i32(a: u32, bits: u32) -> u32 {
let shift = 32 - bits;
(((a << shift) as i32) >> shift) as u32
}
/// Two's-complement absolute value (wrapping, so `0x80000000` stays) and
/// whether the result is nonzero.
pub const fn abs_nonzero_i32(a: u32) -> (u32, bool) {
let value = (a as i32).wrapping_abs() as u32;
(value, value != 0)
}
/// Two's-complement minimum and whether S0 was strictly smaller (so equal
/// operands give S1 and `false`).
pub const fn min_i32(a: u32, b: u32) -> (u32, bool) {
let first = (a as i32) < (b as i32);
(if first { a } else { b }, first)
}
/// Unsigned minimum and whether S0 was strictly smaller.
pub const fn min_u32(a: u32, b: u32) -> (u32, bool) {
let first = a < b;
(if first { a } else { b }, first)
}
/// Two's-complement maximum and whether S0 was strictly greater (so equal
/// operands give S1 and `false`).
pub const fn max_i32(a: u32, b: u32) -> (u32, bool) {
let first = (a as i32) > (b as i32);
(if first { a } else { b }, first)
}
/// Unsigned maximum and whether S0 was strictly greater.
pub const fn max_u32(a: u32, b: u32) -> (u32, bool) {
let first = a > b;
(if first { a } else { b }, first)
}
/// `a` when `condition` (SCC) is set, otherwise `b`.
pub const fn cselect_b32(a: u32, b: u32, condition: bool) -> u32 {
if condition { a } else { b }
}
/// `((1 << a[4:0]) - 1) << b[4:0]`: a mask of `a[4:0]` ones starting at bit `b[4:0]`.
pub const fn bfm_b32(a: u32, b: u32) -> u32 {
((1u32 << (a & 0x1f)) - 1) << (b & 0x1f)
}
/// The low 32 bits of the product (identical for signed and unsigned operands).
pub const fn mul_lo_i32(a: u32, b: u32) -> u32 {
a.wrapping_mul(b)
}
/// The high 32 bits of the unsigned 64-bit product.
pub const fn mul_hi_u32(a: u32, b: u32) -> u32 {
((a as u64 * b as u64) >> 32) as u32
}
/// The high 32 bits of the two's-complement 64-bit product.
pub const fn mul_hi_i32(a: u32, b: u32) -> u32 {
((a as i32 as i64 * b as i32 as i64) >> 32) as u32
}
/// The `bfe` field descriptor: offset `b[4:0]` and width `b[22:16]` (0-127).
const fn bfe_field(b: u32) -> (u32, u32) {
(b & 0x1f, (b >> 16) & 0x7f)
}
/// Unsigned bit-field extract: `(a >> offset) & ((1 << width) - 1)`, where a
/// width of 32 or more keeps every shifted bit; and whether the result is nonzero.
pub const fn bfe_nonzero_u32(a: u32, b: u32) -> (u32, bool) {
let (offset, width) = bfe_field(b);
let shifted = a >> offset;
let value = if width == 0 {
0
} else if width >= 32 {
shifted
} else {
shifted & ((1 << width) - 1)
};
(value, value != 0)
}
/// Signed bit-field extract: `a` shifted arithmetically by the offset, the low
/// `width` bits kept and sign-extended from bit `width - 1` (a width of 32 or
/// more keeps the whole shifted word); and whether the result is nonzero.
pub const fn bfe_nonzero_i32(a: u32, b: u32) -> (u32, bool) {
let (offset, width) = bfe_field(b);
let shifted = ((a as i32) >> offset) as u32;
let value = if width == 0 {
0
} else if width >= 32 {
shifted
} else {
let unused = 32 - width;
(((shifted << unused) as i32) >> unused) as u32
};
(value, value != 0)
}
/// `|a - b|` of the wrapped 32-bit difference (so `0x80000000` stays) and
/// whether the result is nonzero.
pub const fn absdiff_nonzero_i32(a: u32, b: u32) -> (u32, bool) {
let value = (a.wrapping_sub(b) as i32).unsigned_abs();
(value, value != 0)
}
/// `(a << shift) + b` and the carry out of the exact sum, which counts the bits
/// shifted out of `a`; `shift` is 1 to 4.
pub const fn lshl_add_carry_u32(a: u32, b: u32, shift: u32) -> (u32, bool) {
let sum = ((a as u64) << shift) + b as u64;
(sum as u32, sum >> 32 != 0)
}
+60 -5
View File
@@ -45,11 +45,6 @@ pub const S_MOV_B32: Opcode = Opcode {
bits: 0xbe800300,
bytes: 4,
};
pub const S_CMP_EQ_U32: Opcode = Opcode {
mask: 0xffff0000,
bits: 0xbf060000,
bytes: 4,
};
pub const S_CBRANCH_SCC0: Opcode = Opcode {
mask: 0xffff0000,
bits: 0xbf840000,
@@ -110,6 +105,66 @@ pub const V_MUL_F32: Opcode = Opcode {
bits: 0x10000000,
bytes: 4,
};
pub const V_CMP_LT_I32: Opcode = Opcode {
mask: 0xfffe0000,
bits: 0x7d020000,
bytes: 4,
};
pub const V_CMP_EQ_I32: Opcode = Opcode {
mask: 0xfffe0000,
bits: 0x7d040000,
bytes: 4,
};
pub const V_CMP_LE_I32: Opcode = Opcode {
mask: 0xfffe0000,
bits: 0x7d060000,
bytes: 4,
};
pub const V_CMP_GT_I32: Opcode = Opcode {
mask: 0xfffe0000,
bits: 0x7d080000,
bytes: 4,
};
pub const V_CMP_NE_I32: Opcode = Opcode {
mask: 0xfffe0000,
bits: 0x7d0a0000,
bytes: 4,
};
pub const V_CMP_GE_I32: Opcode = Opcode {
mask: 0xfffe0000,
bits: 0x7d0c0000,
bytes: 4,
};
pub const V_CMP_LT_U32: Opcode = Opcode {
mask: 0xfffe0000,
bits: 0x7d820000,
bytes: 4,
};
pub const V_CMP_EQ_U32: Opcode = Opcode {
mask: 0xfffe0000,
bits: 0x7d840000,
bytes: 4,
};
pub const V_CMP_LE_U32: Opcode = Opcode {
mask: 0xfffe0000,
bits: 0x7d860000,
bytes: 4,
};
pub const V_CMP_GT_U32: Opcode = Opcode {
mask: 0xfffe0000,
bits: 0x7d880000,
bytes: 4,
};
pub const V_CMP_NE_U32: Opcode = Opcode {
mask: 0xfffe0000,
bits: 0x7d8a0000,
bytes: 4,
};
pub const V_CMP_GE_U32: Opcode = Opcode {
mask: 0xfffe0000,
bits: 0x7d8c0000,
bytes: 4,
};
pub const EXP: Opcode = Opcode {
mask: 0xfc000000,
bits: 0xf8000000,
File diff suppressed because it is too large. Load diff
+271
View File
@@ -0,0 +1,271 @@
//! Typed vocabulary of the declarative semantic registry (`crates/isa/semantics/rdna2.toml`).
//!
//! The registry is data. `crates/isa/generate_semantics.py` validates it against
//! this closed vocabulary and the pinned AMD XML snapshot, then emits
//! `semantics_gen.rs`: the typed operation enums, their opcode dispatch and one
//! static [`FormSemantics`] row per form. Nothing here interprets metadata at run
//! time; the decoder and translator call the generated `const fn`s and `match`es.
//!
//! The reference interpreter (`crates/ref`) and the independent interpreter
//! (`tests/validation/independent_ref.rs`) must not use this module.
use crate::CompareRelation;
use crate::meta::EncodingFamily;
pub use crate::semantics_gen::{FORM_IDS, FORMS, GENERATED_SCHEMA};
/// Version of the registry schema this crate was generated against.
pub const SCHEMA: u32 = 1;
/// Reusable semantic primitive selected by a form. Closed: the generator rejects
/// any other name, and each primitive has one implementation in `primitive.rs`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Operation {
/// Integer addition.
Add,
/// Integer subtraction.
Sub,
/// Bitwise AND.
And,
/// Bitwise OR.
Or,
/// Bitwise exclusive OR.
Xor,
/// Bitwise AND with the complement of S1.
AndNot,
/// Bitwise OR with the complement of S1.
OrNot,
/// Complement of bitwise AND.
Nand,
/// Complement of bitwise OR.
Nor,
/// Complement of bitwise exclusive OR.
Xnor,
/// Shift S0 left by the masked count in S1, filling with zeros.
ShiftLeft,
/// Shift S0 right by the masked count in S1, filling with zeros.
LogicalShiftRight,
/// Shift S0 right by the masked count in S1, filling with its sign bit.
ArithmeticShiftRight,
/// Compare S0 with S1 under the form's relation; writes only SCC.
Compare,
/// Bitwise complement of S0.
Not,
/// S0 with its bit order reversed.
ReverseBits,
/// Number of zero bits in S0.
CountZeros,
/// Number of one bits in S0.
CountOnes,
/// Index of the lowest zero bit of S0, or -1 when there is none.
FindFirstZero,
/// Index of the lowest one bit of S0, or -1 when there is none.
FindFirstOne,
/// Unsigned: count of zeros above the highest one bit; signed: count of bits
/// above the highest bit that differs from the sign bit. -1 when none.
FindLastBit,
/// Sign-extend the low `source_bits` of S0 to 32 bits.
SignExtend,
/// Two's-complement absolute value; the most negative value maps to itself.
Absolute,
/// S0 when it is strictly less than S1, otherwise S1.
Minimum,
/// S0 when it is strictly greater than S1, otherwise S1.
Maximum,
/// S0 when SCC is set, otherwise S1.
Select,
/// `((1 << S0[4:0]) - 1) << S1[4:0]`.
BitfieldMask,
/// Low 32 bits of the product.
Multiply,
/// High 32 bits of the 64-bit product.
MultiplyHigh,
/// The field of S0 at offset S1[4:0] with width S1[22:16]; sign-extended when signed.
BitfieldExtract,
/// Absolute value of the wrapped 32-bit difference S0 - S1.
AbsoluteDifference,
/// `(S0 << shift_amount) + S1`.
ShiftLeftAdd,
/// Low 32 bits of the product of S0[23:0] and S1[23:0] (sign-extended when signed).
Multiply24,
/// Bits 63:32 of the product of S0[23:0] and S1[23:0] (sign-extended when signed).
MultiplyHigh24,
}
/// The per-lane integer operation a vector form lowers to. One reusable MSL
/// template exists per variant; a form selects it through its declared
/// operation and signedness, never through its opcode.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VectorBinary {
/// Wrapping `a + b`.
Add,
/// Wrapping `a - b`.
Sub,
/// `!(a ^ b)`.
Xnor,
/// Two's-complement minimum.
MinSigned,
/// Unsigned minimum.
MinUnsigned,
/// Two's-complement maximum.
MaxSigned,
/// Unsigned maximum.
MaxUnsigned,
/// Low 32 bits of `sext(a[23:0]) * sext(b[23:0])`.
Mul24Signed,
/// Low 32 bits of `a[23:0] * b[23:0]`.
Mul24Unsigned,
/// Bits 63:32 of `sext(a[23:0]) * sext(b[23:0])`.
MulHi24Signed,
/// Bits 63:32 of `a[23:0] * b[23:0]`.
MulHi24Unsigned,
}
/// How the operands are interpreted. `Bitwise` exactly when the operation is logical.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Signedness {
/// Unsigned integers.
Unsigned,
/// Two's-complement integers.
Signed,
/// Untyped bits.
Bitwise,
}
/// Whether the operation reads SCC.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CarryIn {
/// SCC is not read.
None,
/// SCC as carry-in (add), borrow-in (sub) or the select condition (select).
Scc,
}
/// What a form writes to SCC.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SccEffect {
/// SCC is not written.
Unchanged,
/// Unsigned carry-out of the top bit.
CarryOut,
/// Unsigned borrow (subtrahend plus borrow-in exceeds the minuend).
Borrow,
/// Two's-complement overflow of the exact result.
SignedOverflow,
/// The result is not zero.
Nonzero,
/// The compare's relation holds for S0 and S1.
Relation,
/// The result is S0 by the strict comparison (min, max): equal operands give 0.
SelectedSrc0,
}
/// What a form writes to VCC or EXEC. Stage A forms leave both unchanged.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MaskEffect {
/// Not written.
Unchanged,
}
/// Wave-size restriction.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Wave {
/// Behaviour does not depend on the wave size.
Any,
/// Only Wave32 behaviour is declared; Wave64 stays unsupported.
Wave32,
}
/// Shared operand rule. The decoder implements each rule once.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum OperandRule {
/// SOP2: SDST is s0-s105; SSRC0/SSRC1 are s0-s105, inline integers -16..64
/// or one literal word. Everything else is rejected as unsupported.
Sop2Sgpr,
/// SOPC: no destination; SSRC0/SSRC1 as for SOP2 sources (s0-s105, inline
/// integers -16..64 or one literal word). Everything else is rejected.
SopcScalar,
/// SOP1 unary: SDST is s0-s105; SSRC0 is s0-s105, an inline integer -16..64 or
/// a literal word. Everything else is rejected as unsupported.
Sop1Sgpr,
/// VOP2 vector: VDST is v0-v255; SRC0 is a VGPR, s0-s105, `vcc_lo`, an inline
/// integer -16..64 or a literal word; VSRC1 is a VGPR. Everything else is
/// rejected as unsupported.
Vop2Vgpr,
}
/// Evidence a form needs before it counts as verified.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Evidence {
/// `crates/ref` lockstep reference.
Reference,
/// `tests/validation/independent_ref.rs`.
Independent,
/// Native Metal known-answer runs.
Metal,
/// LLVM assembler/disassembler encoding agreement.
LlvmEncoding,
}
/// Public document a [`SpecRef`] points at.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Document {
/// AMD RDNA 2 ISA reference guide (PDF).
Guide,
/// Pinned AMD machine-readable XML.
Xml,
}
/// One public specification reference.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SpecRef {
/// Source document.
pub document: Document,
/// Section number, for example `"12.1"`.
pub section: &'static str,
/// Page in the document, or 0 when the page has not been recorded.
pub page: u16,
}
/// One validated registry row, emitted as a static table by the generator.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct FormSemantics {
/// XML instruction name, the stable form identity.
pub name: &'static str,
/// Encoding family (matches [`crate::meta::FORMS`]).
pub family: EncodingFamily,
/// Opcode within the family.
pub opcode: u16,
/// Primitive.
pub operation: Operation,
/// Operand interpretation.
pub signedness: Signedness,
/// SCC input.
pub carry_in: CarryIn,
/// Operand and result width in bits.
pub width: u8,
/// Low bits of S1 used as the shift count by shift operations; 0 otherwise.
pub shift_count_bits: u8,
/// Fixed left shift of S0 for shift-and-add operations (1 to 4); 0 otherwise.
pub shift_amount: u8,
/// Whether the operation reads its sources in reverse order (`D = op(S1, S0)`).
pub swap_sources: bool,
/// Low bits of S0 that the operation reads: `width`, or 8 or 16 for sign extension.
pub source_bits: u8,
/// The relation tested by compares (S0 on the left); `None` otherwise.
pub relation: Option<CompareRelation>,
/// SCC write.
pub scc: SccEffect,
/// VCC write.
pub vcc: MaskEffect,
/// EXEC write.
pub exec: MaskEffect,
/// Wave-size restriction.
pub wave: Wave,
/// Operand rule.
pub operands: OperandRule,
/// Public references.
pub spec: &'static [SpecRef],
/// Required evidence.
pub verify: &'static [Evidence],
}
File diff suppressed because it is too large. Load diff
+454
View File
@@ -0,0 +1,454 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! gfx1030 extension-word negative tests (issue #172): truncated and invalid
//! literal, SDWA, DPP16, DPP8 and MIMG NSA trailers.
//!
//! Every source instruction is original and was assembled by llvm-mc 23.1.6
//! (`source_encodings_match_llvm` re-checks the bytes). Expected results come
//! from LLVM's disassembly of the cut or altered bytes and from the field
//! layouts in AMD's public "RDNA 2 Instruction Set Architecture" reference
//! (microcode formats: SDWA, DPP16, DPP8, MIMG NSA), never from Xenora's
//! decoder. `identify` recognises lengths and allowed extensions; it does not
//! validate control-word values (see `reserved_control_values_keep_their_trailer_lengths`).
use std::io::Write;
use std::process::{Command, Stdio};
use xenora_isa::meta::{
IdentifyError, SRC_DPP8, SRC_DPP16, SRC_LITERAL, SRC_SDWA, Trailer, VectorControl, identify,
};
struct Fixture {
source: &'static str,
bytes: &'static [u8],
}
const SOP2_LITERAL: Fixture = Fixture {
source: "s_add_u32 s9, 0x12345679, s11",
bytes: &[0xff, 0x0b, 0x09, 0x80, 0x79, 0x56, 0x34, 0x12],
};
const SOPK_IMMEDIATE: Fixture = Fixture {
source: "s_setreg_imm32_b32 hwreg(HW_REG_MODE), 0x125678ab",
bytes: &[0x01, 0xf8, 0x80, 0xba, 0xab, 0x78, 0x56, 0x12],
};
const VOP1_LITERAL: Fixture = Fixture {
source: "v_mov_b32_e32 v7, 0x12345679",
bytes: &[0xff, 0x02, 0x0e, 0x7e, 0x79, 0x56, 0x34, 0x12],
};
const VOP2_LITERAL: Fixture = Fixture {
source: "v_add_f32_e32 v7, 0x3f800003, v8",
bytes: &[0xff, 0x10, 0x0e, 0x06, 0x03, 0x00, 0x80, 0x3f],
};
const FMAMK: Fixture = Fixture {
source: "v_fmamk_f32 v7, v8, 0x40000001, v9",
bytes: &[0x08, 0x13, 0x0e, 0x58, 0x01, 0x00, 0x00, 0x40],
};
const FMAAK: Fixture = Fixture {
source: "v_fmaak_f32 v7, v8, v9, 0x40000002",
bytes: &[0x08, 0x13, 0x0e, 0x5a, 0x02, 0x00, 0x00, 0x40],
};
const VOPC_LITERAL: Fixture = Fixture {
source: "v_cmp_eq_u32_e32 vcc_lo, 0x1235, v9",
bytes: &[0xff, 0x12, 0x84, 0x7d, 0x35, 0x12, 0x00, 0x00],
};
const VOP3_LITERAL: Fixture = Fixture {
source: "v_fma_f32 v7, v8, v9, 0x3f800003",
bytes: &[
0x07, 0x00, 0x4b, 0xd5, 0x08, 0x13, 0xfe, 0x03, 0x03, 0x00, 0x80, 0x3f,
],
};
const VOP3P_LITERAL: Fixture = Fixture {
source: "v_pk_fma_f16 v7, v8, v9, 0x3c02",
bytes: &[
0x07, 0x40, 0x0e, 0xcc, 0x08, 0x13, 0xfe, 0x1b, 0x02, 0x3c, 0x00, 0x00,
],
};
const VOP1_SDWA: Fixture = Fixture {
source: "v_mov_b32_sdwa v7, v8 dst_sel:BYTE_1 dst_unused:UNUSED_PAD src0_sel:DWORD",
bytes: &[0xf9, 0x02, 0x0e, 0x7e, 0x08, 0x01, 0x06, 0x00],
};
const VOP2_SDWA: Fixture = Fixture {
source: "v_add_f32_sdwa v7, v8, v9 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_0 src1_sel:DWORD",
bytes: &[0xf9, 0x12, 0x0e, 0x06, 0x08, 0x06, 0x04, 0x06],
};
const VOPC_SDWA: Fixture = Fixture {
source: "v_cmp_eq_u32_sdwa s4, v8, v9 src0_sel:DWORD src1_sel:DWORD",
bytes: &[0xf9, 0x12, 0x84, 0x7d, 0x08, 0x84, 0x06, 0x06],
};
const DPP16: Fixture = Fixture {
source: "v_add_f32_dpp v7, v8, v9 row_shl:2 row_mask:0xf bank_mask:0xf",
bytes: &[0xfa, 0x12, 0x0e, 0x06, 0x08, 0x02, 0x01, 0xff],
};
const DPP8: Fixture = Fixture {
source: "v_mov_b32_dpp v7, v8 dpp8:[2,3,0,1,6,7,4,5]",
bytes: &[0xe9, 0x02, 0x0e, 0x7e, 0x08, 0x1a, 0xe2, 0xb3],
};
const DPP8_FI: Fixture = Fixture {
source: "v_mov_b32_dpp v7, v8 dpp8:[2,3,0,1,6,7,4,5] fi:1",
bytes: &[0xea, 0x02, 0x0e, 0x7e, 0x08, 0x1a, 0xe2, 0xb3],
};
const NSA1: Fixture = Fixture {
source: "image_sample v[4:7], [v8, v10], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D",
bytes: &[
0x0a, 0x0f, 0x80, 0xf0, 0x08, 0x04, 0x40, 0x00, 0x0a, 0x00, 0x00, 0x00,
],
};
const NSA2: Fixture = Fixture {
source: "image_sample_d v[4:7], [v8, v10, v12, v14, v16, v18], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D",
bytes: &[
0x0c, 0x0f, 0x88, 0xf0, 0x08, 0x04, 0x40, 0x00, 0x0a, 0x0c, 0x0e, 0x10, 0x12, 0x00, 0x00,
0x00,
],
};
const NSA3: Fixture = Fixture {
source: "image_sample_c_d_cl v[4:7], [v8, v10, v12, v14, v16, v18, v20, v22, v24, v26, v28], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_3D",
bytes: &[
0x16, 0x0f, 0xac, 0xf0, 0x08, 0x04, 0x40, 0x00, 0x0a, 0x0c, 0x0e, 0x10, 0x12, 0x14, 0x16,
0x18, 0x1a, 0x1c, 0x00, 0x00,
],
};
const FRACT_F64: Fixture = Fixture {
source: "v_fract_f64_e32 v[6:7], v[8:9]",
bytes: &[0x08, 0x7d, 0x0c, 0x7e],
};
const READFIRSTLANE: Fixture = Fixture {
source: "v_readfirstlane_b32 s7, v8",
bytes: &[0x08, 0x05, 0x0e, 0x7e],
};
const FMAC: Fixture = Fixture {
source: "v_fmac_f32_e32 v7, v8, v9",
bytes: &[0x08, 0x13, 0x0e, 0x56],
};
const READLANE: Fixture = Fixture {
source: "v_readlane_b32 s7, v8, s9",
bytes: &[0x07, 0x00, 0x60, 0xd7, 0x08, 0x13, 0x00, 0x02],
};
const NOP: Fixture = Fixture {
source: "s_nop 7",
bytes: &[0x07, 0x00, 0x80, 0xbf],
};
const VOPC_REGISTER: Fixture = Fixture {
source: "v_cmp_eq_u32_e32 vcc_lo, v8, v9",
bytes: &[0x08, 0x13, 0x84, 0x7d],
};
#[test]
fn proper_prefixes_report_exact_required_lengths() {
// Each row cuts at every dword boundary and one byte before the end.
// LLVM emits no original instruction for any prefix. Below, "silent"
// means no diagnostic, and "invalid" means LLVM's invalid encoding warning.
// Empty input is silent in all rows. The expected values are the next
// base boundary (4 or 8) until the base is present, then the LLVM length.
let cases: &[(&Fixture, &[usize])] = &[
// silent, SSRC0 selects the literal dword.
(&SOP2_LITERAL, &[4, 8, 8]),
// invalid, mandatory SOPK immediate.
(&SOPK_IMMEDIATE, &[4, 8, 8]),
// silent, literal selector.
(&VOP1_LITERAL, &[4, 8, 8]),
// silent, literal selector.
(&VOP2_LITERAL, &[4, 8, 8]),
// invalid, embedded multiplier dword.
(&FMAMK, &[4, 8, 8]),
// invalid, embedded addend dword.
(&FMAAK, &[4, 8, 8]),
// silent, literal selector.
(&VOPC_LITERAL, &[4, 8, 8]),
// invalid at 4 then silent, 8-byte base and literal.
(&VOP3_LITERAL, &[4, 8, 12, 12]),
// invalid at 4 then silent, 8-byte base and literal.
(&VOP3P_LITERAL, &[4, 8, 12, 12]),
// invalid, SDWA control dword.
(&VOP1_SDWA, &[4, 8, 8]),
// invalid, SDWA control dword.
(&VOP2_SDWA, &[4, 8, 8]),
// invalid, SDWAB control dword.
(&VOPC_SDWA, &[4, 8, 8]),
// invalid, DPP16 control dword.
(&DPP16, &[4, 8, 8]),
// invalid, DPP8 control dword (fi:0).
(&DPP8, &[4, 8, 8]),
// invalid, DPP8 control dword (fi:1).
(&DPP8_FI, &[4, 8, 8]),
// invalid, 8-byte base and one NSA dword.
(&NSA1, &[4, 8, 12, 12]),
// invalid, 8-byte base and two NSA dwords.
// LLVM also prints a stray v_mul_f32 from the address bytes.
(&NSA2, &[4, 8, 16, 16, 16]),
// invalid, 8-byte base and three NSA dwords.
// LLVM also prints stray v_mul_f32 and v_mul_hi_u32_u24 from the address bytes.
(&NSA3, &[4, 8, 20, 20, 20, 20]),
];
for &(fixture, expected) in cases {
let len = fixture.bytes.len();
let prefixes: Vec<_> = (0..len).step_by(4).chain([len - 1]).collect();
assert_eq!(prefixes.len(), expected.len(), "{}", fixture.source);
for (prefix, &needed) in prefixes.into_iter().zip(expected) {
assert_eq!(
identify(&fixture.bytes[..prefix]),
Err(IdentifyError::Truncated { needed }),
"{} at {prefix}/{len} bytes",
fixture.source,
);
}
}
}
#[test]
fn disallowed_vector_selectors_and_literal_are_rejected() {
// Replace the nine-bit SRC0 field of each assembled e32 instruction
// and append a known control or literal dword.
let cases = [
// LLVM rejects SDWA on v_fract_f64. Expect InvalidExtension("sdwa").
(&FRACT_F64, SRC_SDWA, &VOP1_SDWA, "sdwa"),
// LLVM rejects DPP16 on v_fract_f64. Expect InvalidExtension("dpp16").
(&FRACT_F64, SRC_DPP16, &DPP16, "dpp16"),
// LLVM rejects DPP8 on v_fract_f64 and prints the trailer as s_cmpk_lt_i32.
// Expect InvalidExtension("dpp8") for the rejected first instruction.
(&FRACT_F64, SRC_DPP8, &DPP8, "dpp8"),
// LLVM rejects SDWA on v_fmac_f32. Expect InvalidExtension("sdwa").
(&FMAC, SRC_SDWA, &VOP1_SDWA, "sdwa"),
// LLVM rejects DPP16 on this v_cmp_eq_u32. Expect InvalidExtension("dpp16").
(&VOPC_REGISTER, SRC_DPP16, &DPP16, "dpp16"),
// LLVM prints v_readfirstlane_b32 with "Invalid immediate" because
// this source must be a VGPR. Expect InvalidExtension("literal").
(&READFIRSTLANE, SRC_LITERAL, &VOP1_LITERAL, "literal"),
];
for (fixture, selector, trailer, reason) in cases {
let mut bytes = fixture.bytes.to_vec();
let word = u32::from_le_bytes(fixture.bytes.try_into().unwrap());
bytes.copy_from_slice(&((word & !0x1ff) | selector).to_le_bytes());
bytes.extend_from_slice(&trailer.bytes[4..]);
assert_eq!(
identify(&bytes),
Err(IdentifyError::InvalidExtension(reason)),
"{} with SRC0={selector:#x}: {bytes:02x?}",
fixture.source,
);
}
}
#[test]
fn literal_for_vop3_readlane_is_rejected() {
// v_readlane_b32: change SRC0 in the second base dword at bits 8:0
// and append the v_mov_b32 literal. LLVM prints "Invalid immediate"
// for the VGPR-only source. Expect the form to reject the literal.
let mut bytes = READLANE.bytes.to_vec();
let word = u32::from_le_bytes(bytes[4..8].try_into().unwrap());
bytes[4..8].copy_from_slice(&((word & !0x1ff) | SRC_LITERAL).to_le_bytes());
bytes.extend_from_slice(&VOP1_LITERAL.bytes[4..]);
assert_eq!(
identify(&bytes),
Err(IdentifyError::InvalidExtension("literal"))
);
}
/// Identification recognizes length independently of control-word validation.
#[test]
fn reserved_control_values_keep_their_trailer_lengths() {
let cases = [
// v_add_f32_dpp: replace DPP_CTRL 0x102 with 0x100, which LLVM reports as reserved.
// LLVM prints "Invalid dpp_ctrl value". Expect 8 bytes and DPP16.
(&DPP16, 5, 0, "V_ADD_F32", VectorControl::Dpp16),
// v_mov_b32_sdwa: change SRC0_SEL from 6 to 7, which LLVM treats as reserved.
// LLVM prints DWORD and reassembles it as 6. Expect 8 bytes and SDWA.
(&VOP1_SDWA, 6, 7, "V_MOV_B32", VectorControl::Sdwa),
];
for (fixture, offset, value, name, control) in cases {
let mut bytes = fixture.bytes.to_vec();
bytes[offset] = value;
let found = identify(&bytes).unwrap();
assert_eq!(found.form.name, name);
assert_eq!(found.len, 8);
assert_eq!(
found.trailer,
Trailer {
vector_control: Some(control),
..Trailer::default()
},
);
}
}
#[test]
fn next_instruction_starts_after_the_trailer() {
// Append s_nop 7 to each original instruction. LLVM disassembles the
// two instructions with lengths (offset, 4). Expect that boundary from
// identify and the trailer selected by SRC0, SSRC0, or MIMG.NSA.
let cases = [
// LLVM emits s_nop at byte 8. Expect a scalar literal dword.
(
&SOP2_LITERAL,
"S_ADD_U32",
8,
Trailer {
literal: true,
..Trailer::default()
},
),
// LLVM emits s_nop at byte 8. Expect an SDWA control dword.
(
&VOP1_SDWA,
"V_MOV_B32",
8,
Trailer {
vector_control: Some(VectorControl::Sdwa),
..Trailer::default()
},
),
// LLVM emits s_nop at byte 8. Expect a DPP16 control dword.
(
&DPP16,
"V_ADD_F32",
8,
Trailer {
vector_control: Some(VectorControl::Dpp16),
..Trailer::default()
},
),
// LLVM emits s_nop at byte 8. Expect DPP8 with fi:0.
(
&DPP8,
"V_MOV_B32",
8,
Trailer {
vector_control: Some(VectorControl::Dpp8 {
fetch_inactive: false,
}),
..Trailer::default()
},
),
// LLVM emits s_nop at byte 8. Expect DPP8 with fi:1.
(
&DPP8_FI,
"V_MOV_B32",
8,
Trailer {
vector_control: Some(VectorControl::Dpp8 {
fetch_inactive: true,
}),
..Trailer::default()
},
),
// LLVM emits s_nop at byte 12. Expect one NSA dword.
(
&NSA1,
"IMAGE_SAMPLE",
12,
Trailer {
nsa_dwords: 1,
..Trailer::default()
},
),
// LLVM emits s_nop at byte 16. Expect two NSA dwords.
(
&NSA2,
"IMAGE_SAMPLE_D",
16,
Trailer {
nsa_dwords: 2,
..Trailer::default()
},
),
// LLVM emits s_nop at byte 20. Expect three NSA dwords.
(
&NSA3,
"IMAGE_SAMPLE_C_D_CL",
20,
Trailer {
nsa_dwords: 3,
..Trailer::default()
},
),
];
for (fixture, name, offset, trailer) in cases {
let bytes = [fixture.bytes, NOP.bytes].concat();
let first = identify(&bytes).unwrap();
assert_eq!(
(first.form.name, first.len, first.trailer),
(name, offset, trailer),
"{} followed by {}",
fixture.source,
NOP.source,
);
let second = identify(&bytes[first.len..]).unwrap();
assert_eq!(
(second.form.name, second.len, second.trailer),
("S_NOP", 4, Trailer::default()),
);
assert_eq!(first.len + second.len, bytes.len());
}
}
#[test]
#[ignore = "requires LLVM with the gfx1030 AMDGPU target"]
fn source_encodings_match_llvm() {
let fixtures = [
&SOP2_LITERAL,
&SOPK_IMMEDIATE,
&VOP1_LITERAL,
&VOP2_LITERAL,
&FMAMK,
&FMAAK,
&VOPC_LITERAL,
&VOP3_LITERAL,
&VOP3P_LITERAL,
&VOP1_SDWA,
&VOP2_SDWA,
&VOPC_SDWA,
&DPP16,
&DPP8,
&DPP8_FI,
&NSA1,
&NSA2,
&NSA3,
&FRACT_F64,
&READFIRSTLANE,
&FMAC,
&READLANE,
&NOP,
&VOPC_REGISTER,
];
let executable = std::env::var_os("LLVM_BIN").map_or_else(
|| "llvm-mc".into(),
|directory| std::path::PathBuf::from(directory).join("llvm-mc"),
);
let mut llvm = Command::new(executable)
.args([
"-triple=amdgcn-amd-amdhsa",
"-mcpu=gfx1030",
"-mattr=+wavefrontsize32",
"-show-encoding",
])
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("launch llvm-mc (provide its directory in LLVM_BIN or put it on PATH)");
{
let mut input = llvm.stdin.take().unwrap();
for fixture in fixtures {
writeln!(input, "{}", fixture.source).unwrap();
}
}
let output = llvm.wait_with_output().unwrap();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr),
);
let assembly = String::from_utf8(output.stdout).unwrap();
let encodings: Vec<_> = assembly
.lines()
.filter_map(|line| line.split_once("; encoding: [").map(|(_, bytes)| bytes))
.collect();
assert_eq!(encodings.len(), fixtures.len());
for (fixture, encoding) in fixtures.into_iter().zip(encodings) {
let bytes: Vec<_> = encoding
.strip_suffix(']')
.unwrap()
.split(',')
.map(|byte| u8::from_str_radix(byte.trim().strip_prefix("0x").unwrap(), 16).unwrap())
.collect();
assert_eq!(bytes, fixture.bytes, "{}", fixture.source);
}
}
+311
View File
@@ -0,0 +1,311 @@
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-3.0-or-later
"""Regenerate the gfx1030 Wave32 instruction-identification oracle corpus."""
import argparse
from collections import defaultdict
from itertools import islice, zip_longest
from pathlib import Path
import random
import re
import runpy
import subprocess
import tempfile
HERE = Path(__file__).resolve().parent
ISA = HERE.parents[1]
TARGET = ("-triple=amdgcn-amd-amdhsa", "-mcpu=gfx1030", "-mattr=+wavefrontsize32")
BASE_32 = {"SOP1", "SOP2", "SOPC", "SOPK", "SOPP", "VINTRP", "VOP1", "VOP2", "VOPC"}
ENCODING = re.compile(r"^\s*(.*?)\s*; encoding: \[([^\]]+)\]", re.MULTILINE)
SECTION = re.compile(r"^Disassembly of section \.text\.(\d+):")
# Instruction text, offset, consumed words, then optional trailing text: a
# branch-target annotation such as `<.text+0x841c>` or an LLVM warning such as
# `; Warning: ... scalar reg isn't aligned`, neither of which stops decoding.
INSTRUCTION = re.compile(r"^\t(.*?)\s*// ([0-9A-F]{12}): ((?:[0-9A-F]{8}(?: |$))+)(.*)$")
def llvm(executable, *args, source=None):
return subprocess.run(
[executable, *TARGET, "-show-encoding", *args],
input=source, text=True, capture_output=True, check=True,
)
def encodings(output):
for text, bytes_text in ENCODING.findall(output):
yield " ".join(text.split()), bytes(int(token, 16) for token in bytes_text.split(","))
def disassemble_batch(llvm_bin, blobs):
"""LLVM's decode of the first instruction of each blob.
Each blob goes into its own section of one object built from `.byte`
directives; llvm-objdump disassembles every section from offset zero and
prints the words it consumed. That length is what the decoder read, not the
length of a re-encoding (llvm-mc --disassemble re-encodes, which shortens
inconsistent MIMG NSA probes). Returns (text, consumed bytes) or None when
LLVM cannot decode offset zero (it prints `.long`/`.short`/`.byte`).
"""
source = []
for index, blob in enumerate(blobs):
source.append(f'.section .text.{index},"ax"')
if blob:
source.append(".byte " + ",".join(f"0x{byte:02x}" for byte in blob))
with tempfile.TemporaryDirectory() as directory:
assembly_path = Path(directory) / "probes.s"
object_path = Path(directory) / "probes.o"
assembly_path.write_text("\n".join(source) + "\n")
subprocess.run(
[llvm_bin / "llvm-mc", *TARGET, "-filetype=obj", assembly_path, "-o", object_path],
check=True, capture_output=True,
)
dump = subprocess.run(
[llvm_bin / "llvm-objdump", "-d", "--mcpu=gfx1030", "--mattr=+wavefrontsize32", object_path],
check=True, capture_output=True, text=True,
).stdout
first = {}
section = None
for line in dump.splitlines():
header = SECTION.match(line)
if header:
section = int(header.group(1))
continue
instruction = INSTRUCTION.match(line)
if section is None or section in first or not instruction:
continue
text, offset, words, warning = instruction.groups()
if int(offset, 16) != 0:
continue
if text.startswith((".long", ".short", ".byte")):
first[section] = None
else:
text = " ".join(text.split())
warning = warning.strip()
if warning.startswith(";"):
text += f" [LLVM: {warning.lstrip('; ')}]"
first[section] = (text, 4 * len(words.split()))
return [first.get(index) for index in range(len(blobs))]
CRASHED = "crashed"
def disassemble_all(llvm_bin, blobs):
"""Batches of 128; a batch that crashes llvm-objdump is split until the
crashing blobs are isolated, and each of those is reported as CRASHED."""
results = []
for start in range(0, len(blobs), 128):
results.extend(_isolate(llvm_bin, blobs[start:start + 128]))
return results
def _isolate(llvm_bin, blobs):
try:
return disassemble_batch(llvm_bin, blobs)
except subprocess.CalledProcessError as error:
if error.returncode != -11:
raise
if len(blobs) == 1:
return [CRASHED]
half = len(blobs) // 2
return _isolate(llvm_bin, blobs[:half]) + _isolate(llvm_bin, blobs[half:])
def extension(text, length, family):
mnemonic = text.split()[0]
if "dpp8:" in text:
return "dpp8fi" if "fi:1" in text else "dpp8"
if mnemonic.endswith("_dpp"):
return "dpp16"
if mnemonic.endswith("_sdwa"):
return "sdwa"
base_bytes = 4 if family in BASE_32 else 8
if mnemonic.endswith("_e64"):
base_bytes = 8
extra = length - base_bytes
if mnemonic.startswith("image_") and extra > 0:
return f"nsa{extra // 4}"
# After excluding vector control and image addresses, an extra dword
# carrying a numeric operand is the literal (including mandatory literals).
if extra == 4 and re.search(r"(?:,|\s)\s*-?(?:0x[\da-f]+|\d+)(?=,|\s|$|/\*)", text):
return "literal"
if extra > 0:
raise ValueError(f"unclassified LLVM extension: {length} bytes {text}")
return "-"
def assembly(executable):
source = HERE / "corpus.s"
families = [
line.split("//", 1)[1].strip()
for line in source.read_text().splitlines()
if line.split("//", 1)[0].strip()
]
result = llvm(executable, source)
if result.stderr:
raise ValueError(result.stderr)
decoded = list(encodings(result.stdout))
if len(decoded) != len(families):
raise ValueError("LLVM must emit exactly one encoding per assembly line")
return [(family, text, data) for family, (text, data) in zip(families, decoded)]
def metadata_forms():
snapshot = ISA / "data/rdna2.jsonl"
project = runpy.run_path(str(ISA / "generate_rdna2_meta.py"))["forms_from_snapshot"]
return project(snapshot.read_text())[2]
def probes():
# The normalized snapshot stores instruction variants and encoding records
# separately. Reuse its projection to obtain identifiers, widths and labels
# for coverage. The projected mnemonic and extensions are never consulted.
forms = metadata_forms()
rng = random.Random(209)
for form in forms:
width = form["bytes"]
# One probe with every non-identifying bit zero (operands s0/v0, no
# modifiers), then two with seeded random operand bits.
yield "zero", form["encoding"].upper(), form["bits"].to_bytes(width, "little") + bytes(16)
for _ in range(2):
value = form["bits"] | (rng.getrandbits(width * 8) & ~form["mask"])
yield "random", form["encoding"].upper(), value.to_bytes(width, "little") + rng.randbytes(16)
# Extension selectors from the RDNA 2 ISA reference: the SRC0 (VOP1, VOP2,
# VOPC, VOP3*) or SSRC0 (SOP1, SOP2, SOPC) value that makes one extra dword
# follow the base encoding.
SELECTORS = {"literal": 0xFF, "sdwa": 0xF9, "dpp16": 0xFA, "dpp8": 0xE9, "dpp8fi": 0xEA}
# Instructions whose last dword is a legal control word for each extension;
# LLVM assembles them, so the control words are LLVM's own.
CONTROL_SOURCES = {
"sdwa": "v_add_f32_sdwa v0, v0, v0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD src1_sel:DWORD",
"sdwa-vop1": "v_mov_b32_sdwa v0, v0 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:DWORD",
"sdwa-vopc": "v_cmp_eq_f32_sdwa vcc_lo, v0, v0 src0_sel:DWORD src1_sel:DWORD",
"dpp16": "v_add_f32_dpp v0, v0, v0 quad_perm:[0,1,2,3] row_mask:0xf bank_mask:0xf",
"dpp8": "v_add_f32_dpp v0, v0, v0 dpp8:[0,1,2,3,4,5,6,7]",
"dpp8fi": "v_add_f32_dpp v0, v0, v0 dpp8:[0,1,2,3,4,5,6,7] fi:1",
}
LITERAL = (0x12345678).to_bytes(4, "little")
def controls(executable):
source = "\n".join(CONTROL_SOURCES.values()) + "\n"
decoded = list(encodings(llvm(executable, source=source).stdout))
return {name: data[-4:] for name, (_, data) in zip(CONTROL_SOURCES, decoded)}
def extension_probes(executable, forms):
"""Every form's zero-operand base with each extension selector its family
can carry, followed by a legal control dword or literal. LLVM decides which
combinations are instructions; the metadata's extension list is not read."""
control = controls(executable)
for form in forms:
family = form["encoding"].upper()
base = form["bits"]
if family in ("VOP1", "VOP2", "VOPC"):
kinds = ["literal", "sdwa", "dpp16", "dpp8", "dpp8fi"]
shift = 0
elif family in ("VOP3", "VOP3SDST", "VOP3P"):
kinds, shift = ["literal"], 32
elif family in ("SOP1", "SOP2", "SOPC"):
kinds, shift = ["literal"], 0
else:
continue
field = 0x1FF if shift == 32 or family.startswith("VOP") else 0xFF
if base & form["mask"] & (field << shift):
continue # SRC0/SSRC0 is part of this form's identifier
for kind in kinds:
value = (base & ~(field << shift)) | (SELECTORS[kind] << shift)
if kind == "literal":
trailer = LITERAL
elif kind == "sdwa" and family in ("VOPC", "VOP1"):
trailer = control[f"sdwa-{family.lower()}"]
else:
trailer = control[kind]
yield kind, family, value.to_bytes(form["bytes"], "little") + trailer + bytes(12)
def truncations(entries):
by_family = defaultdict(list)
for entry in entries:
by_family[entry[0]].append(entry)
groups = [
sorted(group, key=lambda entry: -len(entry[2]))
for _, group in sorted(by_family.items())
]
interleaved = (entry for batch in zip_longest(*groups) for entry in batch if entry)
yield from islice(interleaved, 40)
def decoded_columns(text, length, family):
return text.split()[0], str(length), extension(text, length, family)
def generate(llvm_bin):
rows = []
entries = assembly(llvm_bin / "llvm-mc")
for family, text, data in entries:
rows.append(("asm", data.hex(), *decoded_columns(text, len(data), family), f"{family} {text}"))
probe_list = list(probes()) + [
(f"ext-{kind}", family, data)
for kind, family, data in extension_probes(llvm_bin / "llvm-mc", metadata_forms())
]
cut_list = [
(family, text, data, data[:size])
for family, text, data in truncations(entries)
for size in range(0, len(data), 4)
]
decoded_all = disassemble_all(llvm_bin, [data for _, _, data in probe_list] + [cut for *_, cut in cut_list])
for (kind, family, data), decoded in zip(probe_list, decoded_all):
if decoded is None:
columns = ("invalid", "0", "-")
note = "LLVM cannot decode offset zero"
elif decoded == CRASHED:
columns = ("crashed", "0", "-")
note = "llvm-objdump crashed (SIGSEGV)"
elif "/*Invalid" not in decoded[0]:
text, length = decoded
columns = decoded_columns(text, length, family)
note = text
if decoded not in (None, CRASHED) and "/*Invalid" in decoded[0]:
# LLVM decodes the words (so it knows the opcode and the length)
# but flags an operand the instruction cannot take, for example an
# SGPR or literal for a VGPR-only source.
text, length = decoded
mnemonic, *rest = decoded_columns(text, length, family)
columns = (f"invalid-operand:{mnemonic}", *rest)
note = text
source = f"probe-{kind}" if kind in ("zero", "random") else "probe-ext"
if kind.startswith("ext-"):
note = f"{kind[4:]} {note}"
rows.append((source, data.hex(), *columns, f"{family} {note}"))
for (family, text, data, prefix), decoded in zip(cut_list, decoded_all[len(probe_list):]):
if decoded is None:
observed = "cannot decode" if prefix else "no instruction"
elif decoded == CRASHED:
observed = "crashed (SIGSEGV)"
else:
observed = f"decoded {decoded[1]} bytes: {decoded[0]}"
note = f"{family} LLVM {observed} | cut {data.hex()} {text}"
rows.append(("truncation", prefix.hex(), "truncated", "0", "-", note))
header = "source\thex\tllvm_mnemonic\tllvm_len\tllvm_ext\tnote\n"
return header + "".join("\t".join(row) + "\n" for row in sorted(rows))
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--llvm-bin", required=True, type=Path)
parser.add_argument("--check", action="store_true")
args = parser.parse_args()
data = generate(args.llvm_bin.resolve())
output = HERE / "corpus.tsv"
if args.check:
if output.read_bytes() != data.encode():
parser.exit(1, f"{output} differs from the LLVM output\n")
else:
output.write_bytes(data.encode())
if __name__ == "__main__":
main()
+320
View File
@@ -0,0 +1,320 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original gfx1030 Wave32 instruction identification cases.
s_mov_b32 s105, s0 // SOP1
s_mov_b32 exec_lo, -16 // SOP1
s_mov_b32 m0, 64 // SOP1
s_mov_b32 vcc_hi, 0xdeadbeef // SOP1
s_mov_b64 exec, vcc // SOP1
s_mov_b64 vcc, 0x12345678 // SOP1
s_not_b32 s0, s105 // SOP1
s_not_b64 s[104:105], s[0:1] // SOP1
s_brev_b32 s105, m0 // SOP1
s_bcnt1_i32_b32 s0, exec_lo // SOP1
s_ff1_i32_b32 s105, -16 // SOP1
s_flbit_i32_b32 s105, 0x80000100 // SOP1
s_sext_i32_i8 s0, s105 // SOP1
s_sext_i32_i16 s105, s0 // SOP1
s_getpc_b64 s[104:105] // SOP1
s_setpc_b64 s[0:1] // SOP1
s_and_saveexec_b64 s[0:1], s[104:105] // SOP1
s_wqm_b64 s[104:105], exec // SOP1
s_add_u32 s105, s0, 0x12345678 // SOP2
s_add_u32 s0, 0xdeadbeef, s105 // SOP2
s_add_i32 s0, -16, 64 // SOP2
s_sub_i32 s105, s0, m0 // SOP2
s_subb_u32 s0, vcc_lo, exec_lo // SOP2
s_min_i32 s105, s104, -16 // SOP2
s_max_u32 s0, s105, 64 // SOP2
s_cselect_b32 s105, -1, s0 // SOP2
s_and_b64 s[104:105], exec, vcc // SOP2
s_or_b64 vcc, s[0:1], exec // SOP2
s_xor_b32 s0, s0, 0xdeadbeef // SOP2
s_nand_b32 s105, m0, vcc_lo // SOP2
s_lshl_b32 s0, s105, 31 // SOP2
s_lshr_b64 s[104:105], s[0:1], 63 // SOP2
s_ashr_i32 s105, 0x87654321, 31 // SOP2
s_mul_i32 s0, s105, -16 // SOP2
s_bfe_u32 s105, s0, 0x0010000f // SOP2
s_cmp_eq_i32 s0, s105 // SOPC
s_cmp_lg_i32 m0, -16 // SOPC
s_cmp_gt_i32 64, s105 // SOPC
s_cmp_ge_i32 s105, 0xdeadbeef // SOPC
s_cmp_lt_u32 0x12345678, exec_hi // SOPC
s_cmp_le_u32 vcc_lo, 64 // SOPC
s_cmp_eq_u64 s[104:105], vcc // SOPC
s_bitcmp0_b32 s105, 31 // SOPC
s_bitcmp1_b64 exec, 63 // SOPC
s_movk_i32 s0, -32768 // SOPK
s_movk_i32 s105, 32767 // SOPK
s_movk_i32 m0, -1 // SOPK
s_addk_i32 s105, -32768 // SOPK
s_mulk_i32 s0, 32767 // SOPK
s_cmpk_eq_i32 s105, -32768 // SOPK
s_cmpk_lg_u32 s0, 65535 // SOPK
s_getreg_b32 s105, hwreg(HW_REG_MODE) // SOPK
s_setreg_b32 hwreg(HW_REG_MODE, 4, 8), s0 // SOPK
s_setreg_imm32_b32 hwreg(HW_REG_MODE, 8, 16), 0xdeadbeef // SOPK
s_setreg_imm32_b32 hwreg(HW_REG_MODE), 0 // SOPK
s_nop 15 // SOPP
s_endpgm 0 // SOPP
s_branch -32768 // SOPP
s_cbranch_scc0 32767 // SOPP
s_cbranch_scc1 -1 // SOPP
s_cbranch_vccz 0 // SOPP
s_cbranch_vccnz 3 // SOPP
s_cbranch_execz 7 // SOPP
s_cbranch_execnz -7 // SOPP
s_barrier // SOPP
s_waitcnt vmcnt(0) lgkmcnt(1) expcnt(7) // SOPP
s_sleep 127 // SOPP
s_trap 255 // SOPP
s_load_dword s105, s[0:1], 1048575 // SMEM
s_load_dword s0, s[104:105], -1048576 // SMEM
s_load_dwordx2 s[104:105], s[0:1], 0 glc // SMEM
s_load_dwordx4 s[0:3], s[100:101], s105 // SMEM
s_load_dwordx8 s[96:103], s[0:1], 7 // SMEM
s_load_dwordx16 s[0:15], s[104:105], 16 // SMEM
s_buffer_load_dword s105, s[0:3], 4095 // SMEM
s_buffer_load_dwordx2 s[104:105], s[0:3], 0 // SMEM
s_buffer_load_dwordx4 s[0:3], s[100:103], s105 // SMEM
s_memtime s[104:105] // SMEM
s_dcache_inv // SMEM
v_mov_b32_e32 v255, v0 // VOP1
v_mov_b32_e32 v0, s105 // VOP1
v_mov_b32_e32 v255, 0xdeadbeef // VOP1
v_mov_b32_e32 v0, -16 // VOP1
v_mov_b32_e32 v255, 64 // VOP1
v_mov_b32_e32 v0, 0.5 // VOP1
v_mov_b32_e32 v255, -4.0 // VOP1
v_mov_b32_e32 v0, 0.15915494 // VOP1
v_cvt_f32_i32_e32 v255, v0 // VOP1
v_cvt_f32_u32_e32 v0, v255 // VOP1
v_cvt_i32_f32_e32 v255, 0x3f800001 // VOP1
v_rcp_f32_e32 v0, v255 // VOP1
v_sqrt_f32_e32 v255, v0 // VOP1
v_readfirstlane_b32 s105, v255 // VOP1
v_mov_b32_sdwa v255, v0 dst_sel:BYTE_3 dst_unused:UNUSED_PRESERVE src0_sel:WORD_0 // VOP1
v_mov_b32_dpp v0, v255 quad_perm:[3,2,1,0] row_mask:0x1 bank_mask:0x8 // VOP1
v_mov_b32_dpp v255, v0 row_shl:15 bound_ctrl:1 // VOP1
v_mov_b32_dpp v0, v255 row_share:15 // VOP1
v_mov_b32_dpp v255, v0 dpp8:[7,6,5,4,3,2,1,0] fi:0 // VOP1
v_mov_b32_dpp v0, v255 dpp8:[0,0,0,0,7,7,7,7] fi:1 // VOP1
v_mov_b32_e32 v255, 0x3e22f983 // VOP1
v_add_f32_e32 v0, v255, v0 // VOP2
v_sub_f32_e32 v255, 0x3f800001, v0 // VOP2
v_subrev_f32_e32 v0, s105, v255 // VOP2
v_mul_f32_e32 v255, -4.0, v0 // VOP2
v_mul_i32_i24_e32 v0, -16, v255 // VOP2
v_mul_u32_u24_e32 v255, 64, v0 // VOP2
v_min_f32_e32 v0, 0.5, v255 // VOP2
v_max_f32_e32 v255, 0.15915494, v0 // VOP2
v_lshrrev_b32_e32 v0, 31, v255 // VOP2
v_ashrrev_i32_e32 v255, 31, v0 // VOP2
v_lshlrev_b32_e32 v0, 31, v255 // VOP2
v_and_b32_e32 v255, 0xdeadbeef, v0 // VOP2
v_or_b32_e32 v0, m0, v255 // VOP2
v_xor_b32_e32 v255, vcc_lo, v0 // VOP2
v_add_nc_u32_e32 v0, exec_lo, v255 // VOP2
v_fmamk_f32 v255, v0, 0x3f800001, v255 // VOP2
v_fmaak_f32 v0, v255, v0, 0xdeadbeef // VOP2
v_add_f32_sdwa v255, v0, v255 dst_sel:WORD_1 dst_unused:UNUSED_SEXT src0_sel:BYTE_0 src1_sel:WORD_0 // VOP2
v_add_f32_dpp v0, v255, v0 row_shl:7 bound_ctrl:1 // VOP2
v_mul_f32_dpp v255, v0, v255 dpp8:[1,2,3,4,5,6,7,0] fi:1 // VOP2
v_cmp_eq_f32_e32 vcc_lo, 0.5, v255 // VOPC
v_cmp_lt_f32_e32 vcc_lo, -4.0, v0 // VOPC
v_cmp_ge_f32_e32 vcc_lo, 0x3f800001, v255 // VOPC
v_cmp_ne_u32_e32 vcc_lo, 0xdeadbeef, v0 // VOPC
v_cmp_gt_i32_e32 vcc_lo, -16, v255 // VOPC
v_cmp_le_i32_e32 vcc_lo, s105, v0 // VOPC
v_cmpx_eq_u32_e32 64, v255 // VOPC
v_cmp_eq_i32_sdwa s105, v255, v0 src0_sel:WORD_0 src1_sel:BYTE_3 // VOPC
v_cmp_lt_u32_sdwa vcc_lo, v0, v255 src0_sel:BYTE_1 src1_sel:WORD_1 // VOPC
v_cmp_class_f32_e32 vcc_lo, v0, v255 // VOPC
v_add_f32_e64 v255, -v0, |v255| clamp // VOP3
v_add_f32_e64 v0, 0x3f800001, v255 // VOP3
v_mul_f32_e64 v255, v0, 0.5 mul:2 // VOP3
v_fma_f32 v0, v255, 0x3f800001, v0 // VOP3
v_fma_f32 v255, -v0, |v255|, -4.0 // VOP3
v_mad_u32_u24 v0, v255, 64, v0 // VOP3
v_mad_i32_i24 v255, v0, -16, v255 // VOP3
v_min3_f32 v0, v255, v0, 0.5 // VOP3
v_max3_i32 v255, v0, v255, -16 // VOP3
v_med3_u32 v0, v255, v0, 64 // VOP3
v_bfe_u32 v255, v0, 31, 1 // VOP3
v_bfe_i32 v0, v255, 0, 32 // VOP3
v_bfi_b32 v255, v0, v255, 0x12345678 // VOP3
v_alignbit_b32 v0, v255, v0, 31 // VOP3
v_cmp_eq_u32_e64 s105, v255, 0xdeadbeef // VOP3
v_readlane_b32 s105, v255, 31 // VOP3
v_writelane_b32 v255, s105, 31 // VOP3
v_add_co_u32 v255, s105, v0, v255 // VOP3SDST
v_add_co_u32 v0, vcc_lo, 0xdeadbeef, v255 // VOP3SDST
v_sub_co_u32 v255, s0, v0, v255 // VOP3SDST
v_subrev_co_u32 v0, s105, v255, v0 // VOP3SDST
v_div_scale_f32 v255, s105, v0, v0, v255 // VOP3SDST
v_div_scale_f64 v[254:255], vcc_lo, v[0:1], v[0:1], v[2:3] // VOP3SDST
v_pk_add_f16 v255, v0, v255 op_sel:[1,0] op_sel_hi:[0,1] // VOP3P
v_pk_mul_f16 v0, v255, 0x3c01 // VOP3P
v_pk_fma_f16 v255, v0, v255, 0x3c01 // VOP3P
v_pk_add_i16 v0, v255, 64 clamp // VOP3P
v_pk_sub_i16 v255, v0, -16 // VOP3P
v_pk_mul_lo_u16 v0, v255, v0 // VOP3P
v_pk_min_i16 v255, v0, v255 // VOP3P
v_pk_max_u16 v0, v255, v0 // VOP3P
v_pk_lshlrev_b16 v255, 15, v0 // VOP3P
v_dot2_f32_f16 v0, v255, v0, 0.5 // VOP3P
v_interp_p1_f32 v255, v0, attr32.w // VINTRP
v_interp_p2_f32 v0, v255, attr0.x // VINTRP
v_interp_mov_f32 v255, p0, attr32.y // VINTRP
v_interp_mov_f32 v0, p10, attr1.z // VINTRP
v_interp_p1_f32 v0, v255, attr1.y // VINTRP
v_interp_p2_f32 v255, v0, attr31.z // VINTRP
ds_write_b32 v255, v0 offset:65535 // DS
ds_read_b32 v0, v255 offset:65535 // DS
ds_write_b8 v0, v255 offset:0 // DS
ds_write_b16 v255, v0 offset:32768 // DS
ds_read_u8 v0, v255 offset:1 // DS
ds_read_i16 v255, v0 offset:65534 // DS
ds_write_b64 v255, v[254:255] offset:8 // DS
ds_read_b64 v[0:1], v255 offset:16 // DS
ds_write2_b32 v0, v255, v0 offset0:255 offset1:0 // DS
ds_read2_b32 v[254:255], v0 offset0:0 offset1:255 // DS
ds_add_u32 v255, v0 offset:65535 // DS
ds_add_rtn_u32 v0, v255, v0 offset:1 // DS
ds_cmpst_b32 v0, v255, v0 offset:32 // DS
ds_bpermute_b32 v255, v0, v255 // DS
ds_permute_b32 v0, v255, v0 // DS
buffer_load_dword v255, off, s[100:103], 0 offset:4095 // MUBUF
buffer_load_dword v0, v255, s[0:3], s105 offen offset:1 // MUBUF
buffer_load_dword v255, v0, s[0:3], 0 idxen // MUBUF
buffer_load_dword v0, v[254:255], s[0:3], 0 idxen offen glc slc // MUBUF
buffer_load_ubyte v255, off, s[0:3], 0 // MUBUF
buffer_load_sshort v0, off, s[0:3], 0 // MUBUF
buffer_load_dwordx2 v[254:255], off, s[0:3], 0 offset:4095 // MUBUF
buffer_load_dwordx3 v[0:2], off, s[0:3], 0 // MUBUF
buffer_store_dwordx4 v[252:255], off, s[100:103], 0 offset:4095 // MUBUF
buffer_store_byte v0, v255, s[0:3], s105 offen // MUBUF
buffer_atomic_add v255, off, s[0:3], 0 glc // MUBUF
buffer_atomic_cmpswap v[254:255], off, s[0:3], 0 glc // MUBUF
tbuffer_load_format_x v255, off, s[100:103], 0 format:[BUF_FMT_32_UINT] offset:4095 // MTBUF
tbuffer_load_format_xy v[0:1], v255, s[0:3], s105 format:[BUF_FMT_32_32_FLOAT] offen // MTBUF
tbuffer_load_format_xyz v[253:255], off, s[0:3], 0 format:[BUF_FMT_32_32_32_FLOAT] // MTBUF
tbuffer_load_format_xyzw v[0:3], off, s[0:3], 0 format:[BUF_FMT_32_32_32_32_FLOAT] // MTBUF
tbuffer_store_format_x v255, v0, s[100:103], 0 format:[BUF_FMT_32_SINT] idxen // MTBUF
tbuffer_store_format_xy v[254:255], off, s[0:3], 0 format:[BUF_FMT_32_32_UINT] // MTBUF
tbuffer_store_format_xyz v[0:2], off, s[0:3], 0 format:[BUF_FMT_32_32_32_UINT] // MTBUF
tbuffer_store_format_xyzw v[252:255], off, s[0:3], 0 format:[BUF_FMT_32_32_32_32_UINT] offset:4095 // MTBUF
tbuffer_load_format_d16_xy v255, off, s[0:3], 0 format:[BUF_FMT_16_16_FLOAT] // MTBUF
tbuffer_store_format_d16_xyzw v[254:255], off, s[0:3], 0 format:[BUF_FMT_16_16_16_16_FLOAT] // MTBUF
image_load v255, v0, s[96:103] dmask:0x1 dim:SQ_RSRC_IMG_1D unorm // MIMG
image_load_mip v[254:255], v[0:2], s[0:7] dmask:0x9 dim:SQ_RSRC_IMG_2D unorm // MIMG
image_store v255, v[0:1], s[0:7] dmask:0x8 dim:SQ_RSRC_IMG_2D unorm // MIMG
image_sample v[252:255], [v255,v0], s[0:7], s[100:103] dmask:0xf dim:SQ_RSRC_IMG_2D // MIMG
image_sample v255, [v0,v128,v255], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_3D // MIMG
image_sample_c v[254:255], [v255,v5,v1,v0], s[0:7], s[8:11] dmask:0x5 dim:SQ_RSRC_IMG_2D_ARRAY // MIMG
image_sample_c_l v255, [v0,v2,v4,v6,v255], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_2D_ARRAY // MIMG
image_sample_d v255, [v0,v2,v4,v6,v8,v255], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_2D // MIMG
image_sample_d v0, [v255,v2,v4,v6,v8,v10,v12,v14,v16], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_3D // MIMG
image_gather4 v[252:255], v[0:1], s[0:7], s[8:11] dmask:0x8 dim:SQ_RSRC_IMG_2D // MIMG
image_atomic_add v255, v[0:1], s[0:7] dmask:0x1 dim:SQ_RSRC_IMG_2D unorm glc // MIMG
image_sample_d_cl v255, [v0,v2,v4,v6,v8,v10,v12,v14,v16,v18], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_3D // MIMG
image_sample_c_d_cl v0, [v0,v2,v4,v6,v8,v10,v12,v14,v16,v18,v20], s[0:7], s[8:11] dmask:0x1 dim:SQ_RSRC_IMG_3D // MIMG
exp mrt0 v255, off, off, v0 done // EXP
exp mrt7 off, v255, v0, off // EXP
exp pos0 v0, v255, v0, v255 done // EXP
exp pos3 v255, v0, v255, v0 // EXP
exp param0 v255, off, v0, off // EXP
exp param31 v0, v255, off, off // EXP
exp null off, off, off, off done // EXP
flat_load_dword v255, v[0:1] offset:2047 // FLAT
flat_load_dword v0, v[254:255] offset:1024 // FLAT
flat_load_ubyte v255, v[0:1] offset:0 // FLAT
flat_load_sbyte v0, v[254:255] glc // FLAT
flat_load_dwordx2 v[254:255], v[0:1] slc // FLAT
flat_load_dwordx4 v[0:3], v[254:255] // FLAT
flat_store_dword v[254:255], v0 offset:2047 // FLAT
flat_store_short v[0:1], v255 offset:1 // FLAT
flat_atomic_add v255, v[0:1], v255 glc // FLAT
flat_atomic_swap v[254:255], v0 // FLAT
global_load_dword v255, v[0:1], off offset:-2048 // GLOBAL
global_load_dword v0, v255, s[104:105] offset:2047 // GLOBAL
global_load_ubyte v255, v0, s[0:1] // GLOBAL
global_load_dwordx3 v[253:255], v[0:1], off glc // GLOBAL
global_store_dword v255, v0, s[104:105] offset:-2048 // GLOBAL
global_store_dwordx4 v[254:255], v[0:3], off offset:2047 // GLOBAL
global_store_byte v0, v255, s[0:1] // GLOBAL
global_atomic_or v255, v0, v255, s[104:105] glc // GLOBAL
global_atomic_add v[254:255], v0, off // GLOBAL
scratch_load_dword v255, v0, off offset:2047 // SCRATCH
scratch_load_dword v0, off, s105 offset:-2048 // SCRATCH
scratch_load_ushort v255, v0, off // SCRATCH
scratch_load_dwordx2 v[254:255], off, s0 // SCRATCH
scratch_load_dwordx4 v[0:3], v255, off // SCRATCH
scratch_store_dword v255, v0, off offset:-2048 // SCRATCH
scratch_store_dword off, v255, s0 offset:2047 // SCRATCH
scratch_store_byte v0, v255, off // SCRATCH
scratch_store_dwordx4 off, v[252:255], s105 // SCRATCH
// Forms the byte probes could not reach with legal operands (FLAT SADDR, DS GDS, BVH).
ds_gws_init v1 offset:65535 gds // DS
ds_gws_barrier v1 offset:0 gds // DS
ds_gws_sema_v gds // DS
ds_gws_sema_br v1 gds // DS
ds_gws_sema_p gds // DS
ds_gws_sema_release_all gds // DS
ds_ordered_count v0, v1 offset:65535 gds // DS
flat_load_dwordx3 v[0:2], v[254:255] offset:2047 // FLAT
flat_load_sshort v255, v[254:255] offset:2047 // FLAT
flat_load_ushort v0, v[254:255] offset:2047 // FLAT
flat_load_sbyte_d16 v0, v[254:255] offset:2047 // FLAT
flat_load_sbyte_d16_hi v0, v[254:255] offset:2047 // FLAT
flat_load_short_d16 v0, v[254:255] offset:2047 // FLAT
flat_load_short_d16_hi v0, v[254:255] offset:2047 // FLAT
flat_load_ubyte_d16 v0, v[254:255] offset:2047 // FLAT
flat_load_ubyte_d16_hi v0, v[254:255] offset:2047 // FLAT
flat_store_byte v[0:1], v2 // FLAT
flat_store_byte_d16_hi v[0:1], v2 // FLAT
flat_store_dwordx2 v[0:1], v[2:3] // FLAT
flat_store_dwordx3 v[0:1], v[2:4] // FLAT
flat_store_dwordx4 v[0:1], v[2:5] // FLAT
flat_store_short_d16_hi v[0:1], v2 // FLAT
flat_atomic_add v0, v[0:1], v2 glc // FLAT
flat_atomic_add_x2 v[0:1], v[2:3] // FLAT
flat_atomic_and v0, v[0:1], v2 glc // FLAT
flat_atomic_and_x2 v[0:1], v[2:3] // FLAT
flat_atomic_dec v0, v[0:1], v2 glc // FLAT
flat_atomic_dec_x2 v[0:1], v[2:3] // FLAT
flat_atomic_inc v0, v[0:1], v2 glc // FLAT
flat_atomic_inc_x2 v[0:1], v[2:3] // FLAT
flat_atomic_or v0, v[0:1], v2 glc // FLAT
flat_atomic_or_x2 v[0:1], v[2:3] // FLAT
flat_atomic_smax v0, v[0:1], v2 glc // FLAT
flat_atomic_smax_x2 v[0:1], v[2:3] // FLAT
flat_atomic_smin v0, v[0:1], v2 glc // FLAT
flat_atomic_smin_x2 v[0:1], v[2:3] // FLAT
flat_atomic_sub v0, v[0:1], v2 glc // FLAT
flat_atomic_sub_x2 v[0:1], v[2:3] // FLAT
flat_atomic_umax v0, v[0:1], v2 glc // FLAT
flat_atomic_umax_x2 v[0:1], v[2:3] // FLAT
flat_atomic_umin v0, v[0:1], v2 glc // FLAT
flat_atomic_umin_x2 v[0:1], v[2:3] // FLAT
flat_atomic_xor v0, v[0:1], v2 glc // FLAT
flat_atomic_xor_x2 v[0:1], v[2:3] // FLAT
flat_atomic_fmax v0, v[0:1], v2 glc // FLAT
flat_atomic_fmax_x2 v[0:1], v[2:3] // FLAT
flat_atomic_fmin v0, v[0:1], v2 glc // FLAT
flat_atomic_fmin_x2 v[0:1], v[2:3] // FLAT
flat_atomic_swap_x2 v[0:1], v[2:3] offset:2047 // FLAT
flat_atomic_cmpswap v0, v[0:1], v[2:3] glc // FLAT
flat_atomic_cmpswap_x2 v[0:1], v[2:5] // FLAT
flat_atomic_fcmpswap v[0:1], v[2:3] // FLAT
flat_atomic_fcmpswap_x2 v[0:1], v[2:5] // FLAT
image_bvh_intersect_ray v[0:3], v[0:10], s[0:3] // MIMG
image_bvh64_intersect_ray v[0:3], v[0:11], s[0:3] // MIMG
image_bvh_intersect_ray v[0:3], [v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14], s[0:3] // MIMG
v_interp_p1ll_f16 v0, v1, attr0.x // VOP3
v_interp_p1lv_f16 v0, v1, attr0.x, v2 // VOP3
v_interp_p2_f16 v0, v1, attr0.x, v2 // VOP3
v_mqsad_u32_u8 v[0:3], v[2:3], v4, v[4:7] // VOP3
v_permlane16_b32 v0, v1, s2, s3 // VOP3
v_permlanex16_b32 v255, v1, s105, m0 op_sel:[1,1] // VOP3
v_swaprel_b32 v0, v1 // VOP1
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,132 @@
# Rows of the asm, probe-zero and probe-ext sources where identify and LLVM do not simply agree
# (neither `identified` nor `both_reject`), as `class hex`, sorted by hex. Pinned by meta_corpus.rs;
# review each change against LLVM.
operand_flagged 000000d60000000000000000000000000000000000000000
operand_flagged 000000d6ff00000078563412000000000000000000000000
metadata_only 000000dd0000000000000000000000000000000000000000
operand_flagged 000001d60000000000000000000000000000000000000000
operand_flagged 000001d6ff00000078563412000000000000000000000000
metadata_only 000008f10000000000000000000000000000000000000000
metadata_only 00000cf10000000000000000000000000000000000000000
metadata_only 000020dc0000000000000000000000000000000000000000
metadata_only 000024dc0000000000000000000000000000000000000000
metadata_only 000028dc0000000000000000000000000000000000000000
metadata_only 000028f10000000000000000000000000000000000000000
metadata_only 00002cdc0000000000000000000000000000000000000000
metadata_only 00002cf10000000000000000000000000000000000000000
metadata_only 000030dc0000000000000000000000000000000000000000
metadata_only 000034dc0000000000000000000000000000000000000000
metadata_only 000038dc0000000000000000000000000000000000000000
metadata_only 00003cdc0000000000000000000000000000000000000000
metadata_only 000040dd0000000000000000000000000000000000000000
operand_flagged 000042d70000000000000000000000000000000000000000
operand_flagged 000042d7ff00000078563412000000000000000000000000
operand_flagged 000043d70000000000000000000000000000000000000000
operand_flagged 000043d7ff00000078563412000000000000000000000000
metadata_only 000044dd0000000000000000000000000000000000000000
metadata_only 000048dd0000000000000000000000000000000000000000
metadata_only 000048f10000000000000000000000000000000000000000
metadata_only 00004cdd0000000000000000000000000000000000000000
metadata_only 00004cf10000000000000000000000000000000000000000
metadata_only 000054dd0000000000000000000000000000000000000000
metadata_only 000058dd0000000000000000000000000000000000000000
operand_flagged 00005ad70000000000000000000000000000000000000000
operand_flagged 00005ad7ff00000078563412000000000000000000000000
metadata_only 00005cdd0000000000000000000000000000000000000000
operand_flagged 000060d70000000000000000000000000000000000000000
metadata_only 000060d80000000000000000000000000000000000000000
metadata_only 000060dc0000000000000000000000000000000000000000
metadata_only 000060dd0000000000000000000000000000000000000000
metadata_only 000064d80000000000000000000000000000000000000000
metadata_only 000064dc0000000000000000000000000000000000000000
metadata_only 000064dd0000000000000000000000000000000000000000
metadata_only 000068d80000000000000000000000000000000000000000
metadata_only 000068dc0000000000000000000000000000000000000000
metadata_only 000068dd0000000000000000000000000000000000000000
metadata_only 000068f10000000000000000000000000000000000000000
metadata_only 00006cd80000000000000000000000000000000000000000
metadata_only 00006cdc0000000000000000000000000000000000000000
metadata_only 00006cdd0000000000000000000000000000000000000000
metadata_only 00006cf10000000000000000000000000000000000000000
metadata_only 000070d80000000000000000000000000000000000000000
metadata_only 000070dc0000000000000000000000000000000000000000
metadata_only 000070dd0000000000000000000000000000000000000000
metadata_only 000074d80000000000000000000000000000000000000000
metadata_only 000074dc0000000000000000000000000000000000000000
metadata_only 000074dd0000000000000000000000000000000000000000
operand_flagged 000075d50000000000000000000000000000000000000000
operand_flagged 000075d5ff00000078563412000000000000000000000000
operand_flagged 000077d70000000000000000000000000000000000000000
operand_flagged 000077d7ff00000078563412000000000000000000000000
operand_flagged 000078d70000000000000000000000000000000000000000
operand_flagged 000078d7ff00000078563412000000000000000000000000
metadata_only 000078dc0000000000000000000000000000000000000000
metadata_only 000078dd0000000000000000000000000000000000000000
metadata_only 00007cdc0000000000000000000000000000000000000000
metadata_only 00007cdd0000000000000000000000000000000000000000
oracle_only 000080d5ff00000078563412000000000000000000000000
metadata_only 000080dc0000000000000000000000000000000000000000
metadata_only 000080dd0000000000000000000000000000000000000000
metadata_only 000082d50000000000000000000000000000000000000000
metadata_only 000084dc0000000000000000000000000000000000000000
metadata_only 000088dc0000000000000000000000000000000000000000
metadata_only 000088f10000000000000000000000000000000000000000
metadata_only 00008cdc0000000000000000000000000000000000000000
metadata_only 00008cf10000000000000000000000000000000000000000
metadata_only 000090dc0000000000000000000000000000000000000000
metadata_only 000094dc0000000000000000000000000000000000000000
oracle_only 00009bd5ff00000078563412000000000000000000000000
metadata_only 0000c0dc0000000000000000000000000000000000000000
metadata_only 0000c0f10000000000000000000000000000000000000000
oracle_only 0000c1d5ff00000078563412000000000000000000000000
operand_flagged 0000c3d50000000000000000000000000000000000000000
operand_flagged 0000c4d50000000000000000000000000000000000000000
metadata_only 0000c4dc0000000000000000000000000000000000000000
metadata_only 0000c4f10000000000000000000000000000000000000000
operand_flagged 0000c8d50000000000000000000000000000000000000000
metadata_only 0000c8dc0000000000000000000000000000000000000000
metadata_only 0000ccdc0000000000000000000000000000000000000000
metadata_only 0000ccf10000000000000000000000000000000000000000
metadata_only 0000d0f10000000000000000000000000000000000000000
metadata_only 0000d4dc0000000000000000000000000000000000000000
metadata_only 0000d8dc0000000000000000000000000000000000000000
metadata_only 0000d8f10000000000000000000000000000000000000000
metadata_only 0000dcdc0000000000000000000000000000000000000000
metadata_only 0000dcf10000000000000000000000000000000000000000
metadata_only 0000e0dc0000000000000000000000000000000000000000
metadata_only 0000e4dc0000000000000000000000000000000000000000
metadata_only 0000e4f10000000000000000000000000000000000000000
metadata_only 0000e8dc0000000000000000000000000000000000000000
metadata_only 0000e8f10000000000000000000000000000000000000000
metadata_only 0000ecdc0000000000000000000000000000000000000000
metadata_only 0000f0dc0000000000000000000000000000000000000000
metadata_only 0000f4dc0000000000000000000000000000000000000000
metadata_only 0000f8dc0000000000000000000000000000000000000000
metadata_only 0000fcd80000000000000000000000000000000000000000
metadata_only 0000fcdc0000000000000000000000000000000000000000
operand_flagged 0004007e00000000000000000000000000000000
operand_flagged 0086007e00000000000000000000000000000000
operand_flagged 0088007e00000000000000000000000000000000
operand_flagged 0090007e00000000000000000000000000000000
operand_flagged 00ca007e00000000000000000000000000000000
operand_flagged 00d0007e00000000000000000000000000000000
metadata_only 010098f10000000000000000000000000000000000000000
metadata_only 01009cf10000000000000000000000000000000000000000
oracle_only e900007e0088c6fa000000000000000000000000
oracle_only e936007e0088c6fa000000000000000000000000
oracle_only e982007e0088c6fa000000000000000000000000
oracle_only ea00007e0088c6fa000000000000000000000000
oracle_only ea36007e0088c6fa000000000000000000000000
oracle_only ea82007e0088c6fa000000000000000000000000
oracle_only f900007e00060600000000000000000000000000
oracle_only f936007e00060600000000000000000000000000
oracle_only f982007e00060600000000000000000000000000
oracle_only fa00007e00e400ff000000000000000000000000
oracle_only fa36007e00e400ff000000000000000000000000
oracle_only fa82007e00e400ff000000000000000000000000
oracle_only ff00007e78563412000000000000000000000000
oracle_only ff1f80be78563412000000000000000000000000
oracle_only ff2180be78563412000000000000000000000000
oracle_only ff36007e78563412000000000000000000000000
oracle_only ff4980be78563412000000000000000000000000
oracle_only ff82007e78563412000000000000000000000000
+41
View File
@@ -0,0 +1,41 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// One instruction per line for each family and extension word; checked against llvm-mc.
s_mov_b32 s0, 0x12345678
s_add_u32 s0, s1, 0x1234
s_cmp_eq_u32 s0, 0xdeadbeef
s_movk_i32 s0, 0x1234
s_setreg_imm32_b32 hwreg(HW_REG_MODE), 0x0
s_load_dwordx4 s[0:3], s[4:5], 0x10
s_nop 0
s_endpgm
v_mov_b32 v0, 0x12345678
v_mov_b32_sdwa v0, v1 dst_sel:BYTE_0 dst_unused:UNUSED_PAD src0_sel:DWORD
v_mov_b32_dpp v0, v1 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf
v_mov_b32_dpp v0, v1 dpp8:[1,0,3,2,5,4,7,6]
v_mov_b32_dpp v0, v1 dpp8:[1,0,3,2,5,4,7,6] fi:1
v_add_f32_sdwa v0, v1, v2 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1 src1_sel:DWORD
v_add_f32_dpp v0, v1, v2 row_shl:1 row_mask:0xf bank_mask:0xf
v_cmp_eq_u32_e32 vcc_lo, 0x1234, v1
v_cmp_eq_u32_sdwa s0, v1, v2 src0_sel:DWORD src1_sel:DWORD
v_fmamk_f32 v0, v1, 0x40000000, v2
v_fmaak_f32 v0, v1, v2, 0x40000000
v_fma_f32 v0, v1, v2, 0x3f800001
v_add_co_u32 v0, s0, v1, v2
v_readlane_b32 s0, v1, 0
v_pk_add_f16 v0, v1, v2
v_pk_fma_f16 v0, v1, v2, 0x3c01
v_interp_p1_f32 v0, v1, attr0.x
ds_write_b32 v0, v1
ds_read_b32 v0, v1 offset:16
buffer_load_dword v0, off, s[0:3], 0
tbuffer_load_format_x v0, off, s[0:3], 0 format:[BUF_FMT_32_FLOAT]
tbuffer_load_format_d16_x v0, off, s[0:3], 0 format:[BUF_FMT_32_FLOAT]
tbuffer_store_format_d16_xyzw v[0:1], off, s[0:3], 0 format:[BUF_FMT_32_FLOAT]
image_sample v[0:3], v[0:1], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D
image_sample v[0:3], [v0, v2], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D
image_sample_c v[0:3], [v0, v2, v4, v6], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY
image_msaa_load v[0:3], v[0:2], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_2D_MSAA unorm
flat_load_dword v0, v[0:1]
global_load_dword v0, v[0:1], off
scratch_load_dword v0, v1, off
exp mrt0 v0, v0, v0, v0 done
+230
View File
@@ -0,0 +1,230 @@
//! Instruction identification against LLVM-assembled fixtures and hand-assembled words.
use std::fs;
use std::path::Path;
use xenora_isa::meta::{
EncodingFamily, Extensions, FORMS, IdentifyError, VectorControl, identify, inventory, lookup,
};
fn words(values: &[u32]) -> Vec<u8> {
values
.iter()
.flat_map(|value| value.to_le_bytes())
.collect()
}
fn name_of(values: &[u32]) -> (&'static str, usize) {
let found = identify(&words(values)).unwrap();
(found.form.name, found.len)
}
/// Mnemonics in a fixture's assembly source, without LLVM's encoding suffixes.
fn source_mnemonics(source: &str) -> Vec<String> {
source
.lines()
.map(|line| line.split("//").next().unwrap().trim())
.filter(|line| !line.is_empty() && !line.starts_with('.') && !line.ends_with(':'))
.map(|line| {
let mnemonic = line.split_whitespace().next().unwrap().to_ascii_uppercase();
mnemonic
.trim_end_matches("_E32")
.trim_end_matches("_E64")
.to_owned()
})
.collect()
}
#[test]
fn llvm_fixtures_identify_with_exact_boundaries_and_mnemonics() {
let directory = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/rdna2");
let mut checked = 0;
for entry in fs::read_dir(&directory).unwrap() {
let path = entry.unwrap().path();
if path.extension().is_none_or(|extension| extension != "bin") {
continue;
}
let binary = fs::read(&path).unwrap();
let source = fs::read_to_string(path.with_extension("s")).unwrap();
let mut offset = 0;
let mut identified = Vec::new();
while offset < binary.len() {
let found = identify(&binary[offset..])
.unwrap_or_else(|error| panic!("{} at {offset:#x}: {error}", path.display()));
identified.push(found.form.name.to_owned());
offset += found.len;
}
assert_eq!(offset, binary.len(), "{}", path.display());
assert_eq!(identified, source_mnemonics(&source), "{}", path.display());
checked += 1;
}
assert!(checked >= 11, "only {checked} fixtures found");
}
#[test]
fn hand_assembled_words_identify() {
// SOPP s_endpgm (opcode 1), SOP1 s_mov_b32 s0, s1 (opcode 3).
assert_eq!(name_of(&[0xbf81_0000]), ("S_ENDPGM", 4));
assert_eq!(name_of(&[0xbe80_0301]), ("S_MOV_B32", 4));
// VOP1 v_mov_b32 v0, v1: SRC0 = 256 + 1.
assert_eq!(name_of(&[0x7e00_0301]), ("V_MOV_B32", 4));
// VOP2 v_add_f32 v0, v1, v2: opcode 3 at bits 30:25, VSRC1 = 2 at bits 16:9.
assert_eq!(name_of(&[0x0600_0501]), ("V_ADD_F32", 4));
// VOP3 v_add_f32_e64 v0, v1, v2 (LLVM 23 encoding): opcode 259 = 256 + VOP2 opcode 3.
assert_eq!(name_of(&[0xd503_0000, 0x0202_0501]), ("V_ADD_F32", 8));
}
#[test]
fn literal_sdwa_and_dpp_words_extend_the_length() {
// v_mov_b32 v0, 0x12345678: SRC0 = 255 selects a literal.
let literal = identify(&words(&[0x7e00_02ff, 0x1234_5678])).unwrap();
assert_eq!((literal.form.name, literal.len), ("V_MOV_B32", 8));
assert!(literal.trailer.literal);
// s_add_u32 s0, s1, literal: SSRC1 = 255.
assert_eq!(name_of(&[0x8000_ff01, 0x0000_1234]), ("S_ADD_U32", 8));
// VOP3 with SRC2 = 255.
let fma = identify(&words(&[0xd54b_0000, 0x03fe_0501, 0x3f80_0000]));
assert!(matches!(fma, Ok(found) if found.len == 12 && found.trailer.literal));
let sdwa = identify(&words(&[0x7e00_02f9, 0x0006_0601])).unwrap();
assert_eq!(sdwa.trailer.vector_control, Some(VectorControl::Sdwa));
assert_eq!(sdwa.len, 8);
let dpp16 = identify(&words(&[0x7e00_02fa, 0x00ff_0001])).unwrap();
assert_eq!(dpp16.trailer.vector_control, Some(VectorControl::Dpp16));
let dpp8 = identify(&words(&[0x7e00_02ea, 0x00fa_c688])).unwrap();
assert_eq!(
dpp8.trailer.vector_control,
Some(VectorControl::Dpp8 {
fetch_inactive: true
})
);
}
#[test]
fn vop3_interpolation_attribute_fields_never_select_a_literal() {
// AMD RDNA 2 ISA guide section 10.4.2: in the VOP3 interpolation forms SRC0
// holds {attr_word, attr_chan, attr} bit-fields (XML OPR_ATTR), so SRC0 = 255
// is attr 63, channel w (and attr_word 0) and the instruction is 8 bytes.
// LLVM 23.1.6 agrees (#235).
for (first, name) in [
(0xd600_0000, "V_INTERP_P1_F32"),
(0xd601_0000, "V_INTERP_P2_F32"),
(0xd602_0000, "V_INTERP_MOV_F32"),
(0xd742_0000, "V_INTERP_P1LL_F16"),
(0xd743_0000, "V_INTERP_P1LV_F16"),
(0xd75a_0000, "V_INTERP_P2_F16"),
] {
let found = identify(&words(&[first, 0x0000_00ff, 0x1234_5678])).unwrap();
assert_eq!((found.form.name, found.len), (name, 8));
assert!(!found.trailer.literal, "{name}");
}
// A general VOP3 source with the same selector still takes the literal.
let add = identify(&words(&[0xd503_0000, 0x0000_00ff, 0x1234_5678])).unwrap();
assert_eq!((add.form.name, add.len), ("V_ADD_F32", 12));
// So does a VGPR-only source (LLVM reports these 12 bytes with an invalid operand).
let permlane = identify(&words(&[0xd777_0000, 0x0000_00ff, 0x1234_5678])).unwrap();
assert_eq!((permlane.form.name, permlane.len), ("V_PERMLANE16_B32", 12));
}
#[test]
fn truncated_and_unassigned_inputs_are_rejected() {
assert_eq!(identify(&[]), Err(IdentifyError::Truncated { needed: 4 }));
assert_eq!(
identify(&[0x00, 0x00, 0x81]),
Err(IdentifyError::Truncated { needed: 4 })
);
// VOP3 first dword alone.
assert_eq!(
identify(&words(&[0xd503_0000])),
Err(IdentifyError::Truncated { needed: 8 })
);
// Literal selected but absent.
assert_eq!(
identify(&words(&[0x7e00_02ff])),
Err(IdentifyError::Truncated { needed: 8 })
);
// SOPP opcodes are 7 bits; this table has no SOPP opcode 127.
assert!(lookup(0xbf80_0000 | (127 << 16)).is_none());
assert_eq!(
identify(&words(&[0xbfff_0000])),
Err(IdentifyError::Unassigned)
);
}
#[test]
fn extensions_outside_a_forms_metadata_are_rejected() {
let without_sdwa = FORMS
.iter()
.find(|form| {
form.family == EncodingFamily::Vop1 && !form.extensions.contains(Extensions::SDWA)
})
.expect("a VOP1 form without SDWA");
let word = (without_sdwa.bits as u32) | 0xf9;
assert_eq!(
identify(&words(&[word, 0])),
Err(IdentifyError::InvalidExtension("sdwa"))
);
}
#[test]
fn every_form_identifies_as_itself() {
for form in &FORMS {
assert_eq!(lookup(form.bits).map(|found| found.name), Some(form.name));
assert_eq!(
lookup(form.bits).unwrap().family,
form.family,
"{}",
form.name
);
}
let total: usize = inventory().iter().map(|(_, count)| count).sum();
assert_eq!(total, FORMS.len());
}
#[test]
fn documented_form_counts_match_the_generated_table() {
let count = FORMS.len();
let count = format!("{},{:03}", count / 1000, count % 1000);
let families = EncodingFamily::ALL.len();
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
for (file, claim) in [
(
"docs/research/rdna2.md",
format!("{count} forms in {families} encoding families"),
),
(
"CHANGELOG.md",
format!("{count} base forms across {families} encoding families"),
),
] {
let text = fs::read_to_string(root.join(file)).unwrap();
assert!(
text.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
.contains(&claim),
"{file} must state \"{claim}\""
);
}
}
#[test]
fn first_word_opcode_table_agrees_with_full_metadata() {
use xenora_isa::{BUFFER_LOAD_DWORD, S_ENDPGM, V_ADD_F32, V_ADD_NC_U32, V_MOV_B32};
for (opcode, name, family) in [
(
BUFFER_LOAD_DWORD,
"BUFFER_LOAD_DWORD",
EncodingFamily::Mubuf,
),
(S_ENDPGM, "S_ENDPGM", EncodingFamily::Sopp),
(V_ADD_F32, "V_ADD_F32", EncodingFamily::Vop2),
(V_ADD_NC_U32, "V_ADD_NC_U32", EncodingFamily::Vop3),
(V_MOV_B32, "V_MOV_B32", EncodingFamily::Vop1),
] {
let form = FORMS
.iter()
.find(|form| form.name == name && form.family == family)
.unwrap();
assert!(opcode.matches(form.bits as u32), "{name}");
}
}
+304
View File
@@ -0,0 +1,304 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Independent LLVM corpus check of gfx1030 instruction identification (#209).
//!
//! `llvm/corpus.tsv` is generated by `llvm/corpus.py` from LLVM 23.1.6 alone:
//! llvm-mc assembles the original instructions in `llvm/corpus.s`, and
//! llvm-objdump decodes byte probes built from each metadata form's
//! identifying bits (one with every other bit zero, two with seeded random
//! operand bits). The expected name, consumed length and extension of every
//! row are LLVM's. This test compares `identify` with them and pins what it
//! measures: per-source class counts, the exact rows where the two disagree
//! for assembled and zero-operand inputs, and a digest of the random-probe
//! classification.
//!
//! Identification is not execution support: a row counted as identified only
//! means both agree on which instruction the bytes are and how long it is.
use std::collections::BTreeMap;
use xenora_isa::meta::{FORMS, Identified, IdentifyError, VectorControl, identify};
const CORPUS: &str = include_str!("llvm/corpus.tsv");
/// Row classes, in report order.
const CLASSES: [&str; 9] = [
"identified", // both decode: same name, length and extension
"mismatch", // both decode, but name, length or extension differ
"oracle_only", // LLVM decodes, identify returns an error
"metadata_only", // identify decodes, LLVM cannot
"both_reject", // neither decodes
"oracle_crash", // llvm-objdump crashed; no oracle answer
"truncated", // a proper prefix: identify asks for more bytes
"truncation_other",
"operand_flagged", // same instruction and length; LLVM flags an operand as invalid
];
const SOURCES: [&str; 5] = [
"asm",
"probe-zero",
"probe-ext",
"probe-random",
"truncation",
];
fn base_name(mnemonic: &str) -> String {
let upper = mnemonic.to_ascii_uppercase();
["_E32", "_E64", "_SDWA", "_DPP"]
.into_iter()
.find_map(|suffix| upper.strip_suffix(suffix))
.unwrap_or(&upper)
.to_owned()
}
fn extension(found: &Identified) -> String {
let nsa = format!("nsa{}", found.trailer.nsa_dwords);
let mut parts = Vec::new();
if found.trailer.literal {
parts.push("literal");
}
match found.trailer.vector_control {
Some(VectorControl::Sdwa) => parts.push("sdwa"),
Some(VectorControl::Dpp8 {
fetch_inactive: false,
}) => parts.push("dpp8"),
Some(VectorControl::Dpp8 {
fetch_inactive: true,
}) => parts.push("dpp8fi"),
Some(VectorControl::Dpp16) => parts.push("dpp16"),
None => {}
}
if found.trailer.nsa_dwords != 0 {
parts.push(&nsa);
}
if parts.is_empty() {
"-".into()
} else {
parts.join("+")
}
}
struct Row<'a> {
source: usize,
form: Option<&'static str>,
family: &'a str,
hex: &'a str,
class: usize,
detail: String,
}
fn classify(line: &str) -> Row<'_> {
let [source, hex, mnemonic, len, ext, note] = line.split('\t').collect::<Vec<_>>()[..] else {
panic!("bad corpus row: {line}");
};
let source = SOURCES
.iter()
.position(|s| *s == source)
.unwrap_or_else(|| panic!("bad source: {line}"));
let (family, text) = note.split_once(' ').unwrap();
let bytes: Vec<u8> = (0..hex.len())
.step_by(2)
.map(|i| u8::from_str_radix(&hex[i..i + 2], 16).unwrap())
.collect();
let len: usize = len.parse().unwrap();
let found = identify(&bytes);
let answer = match &found {
Ok(found) => format!(
"{} ({} bytes, {})",
found.form.name,
found.len,
extension(found)
),
Err(error) => format!("{error:?}"),
};
let mut differences = Vec::new();
// LLVM decoded the words but flagged an operand the instruction cannot
// take. identify does not validate operands; it must still agree on the
// instruction and its length, or reject the extension outright.
let (flagged, mnemonic) = match mnemonic.strip_prefix("invalid-operand:") {
Some(mnemonic) => (true, mnemonic),
None => (false, mnemonic),
};
let class = match (mnemonic, &found) {
("truncated", Err(IdentifyError::Truncated { needed })) if *needed > bytes.len() => 6,
("truncated", _) => 7,
("crashed", _) => 5,
("invalid", Err(_)) => 4,
("invalid", Ok(_)) => 3,
(_, Err(IdentifyError::InvalidExtension(_))) if flagged => 4,
(_, Err(_)) => 2,
(_, Ok(found)) => {
if found.form.name != base_name(mnemonic) {
differences.push("name");
}
if found.len != len {
differences.push("length");
}
if extension(found) != ext {
differences.push("extension");
}
if !differences.is_empty() {
1
} else if flagged {
8
} else {
0
}
}
};
let kind = if differences.is_empty() {
CLASSES[class].to_owned()
} else {
format!("mismatch/{}", differences.join("+"))
};
Row {
source,
form: found.ok().map(|found| found.form.name),
family,
hex,
class,
detail: format!("{kind}: {hex} | LLVM {text} ({len} bytes, {ext}) | Xenora {answer}"),
}
}
/// FNV-1a over the sorted `class hex` lines, to pin thousands of rows compactly.
fn digest(lines: &[String]) -> u64 {
lines
.iter()
.flat_map(|l| l.bytes().chain(*b"\n"))
.fold(0xcbf2_9ce4_8422_2325, |hash, byte| {
(hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
})
}
// Measured against LLVM 23.1.6 on 2026-11-24. Any change needs the affected
// rows reviewed against LLVM, not an update of these numbers alone.
// Rows: one per source, columns in CLASSES order.
const COUNTS: [[usize; 9]; 5] = [
[317, 0, 0, 0, 0, 0, 0, 0, 0], // asm
[1365, 0, 0, 82, 0, 0, 0, 0, 18], // probe-zero
[1398, 0, 21, 0, 752, 0, 0, 0, 8], // probe-ext
[1236, 0, 0, 1678, 3, 2, 0, 0, 11], // probe-random
[0, 0, 0, 0, 0, 0, 87, 0, 0], // truncation
];
/// Every assembled, zero-operand or extension-probe row where the two disagree
/// (neither `identified` nor `both_reject`), as `class hex`, sorted by hex.
const DISAGREEMENTS: &str = include_str!("llvm/corpus_disagreements.txt");
/// Digest of the sorted `class hex` lines of the random probes.
const RANDOM_DIGEST: u64 = 0x32fb_5d7d_0826_ce14;
#[test]
fn identification_agrees_with_the_llvm_corpus() {
let mut lines = CORPUS.lines();
assert_eq!(
lines.next(),
Some("source\thex\tllvm_mnemonic\tllvm_len\tllvm_ext\tnote")
);
let rows: Vec<_> = lines.map(classify).collect();
let mut counts = [[0usize; 9]; 5];
let mut by_family = BTreeMap::<&str, [usize; 9]>::new();
for row in &rows {
counts[row.source][row.class] += 1;
by_family.entry(row.family).or_default()[row.class] += 1;
}
println!("{:9} {}", "family", CLASSES.join(" "));
for (family, c) in &by_family {
print!("{family:9}");
for (name, n) in CLASSES.iter().zip(c) {
print!(" {n:>w$}", w = name.len());
}
println!();
}
for (source, c) in SOURCES.iter().zip(&counts) {
println!("{source:13} {c:?}");
}
let mut disagreements: Vec<_> = rows
.iter()
.filter(|r| r.source < 3 && !matches!(r.class, 0 | 4))
.collect();
disagreements.sort_unstable_by_key(|r| r.hex);
for r in &disagreements {
println!("{}", r.detail);
}
let disagreements: Vec<_> = disagreements
.iter()
.map(|r| format!("{} {}", CLASSES[r.class], r.hex))
.collect();
let mut random: Vec<_> = rows
.iter()
.filter(|r| r.source == 3)
.map(|r| format!("{} {}", CLASSES[r.class], r.hex))
.collect();
random.sort_unstable();
let random_digest = digest(&random);
println!("random digest {random_digest:#018x}");
for r in rows
.iter()
.filter(|r| r.source == 3 && r.class == 1)
.take(5)
{
println!("random example {}", r.detail);
}
// Distinct metadata forms: agreed by LLVM on at least one row, or only
// ever decoded by Xenora (LLVM rejected every probe of that form).
let mut forms = BTreeMap::<&str, (usize, usize)>::new();
for row in &rows {
if let Some(form) = row.form {
let entry = forms.entry(form).or_default();
match row.class {
0 | 8 => entry.0 += 1,
3 => entry.1 += 1,
_ => {}
}
}
}
let agreed = forms.values().filter(|(a, _)| *a > 0).count();
let never: Vec<_> = forms
.iter()
.filter(|(_, (a, m))| *a == 0 && *m > 0)
.map(|(name, _)| *name)
.collect();
println!(
"distinct forms seen {}: agreed {agreed}, metadata-only on every row {}",
forms.len(),
never.len()
);
println!("never decoded by LLVM: {}", never.join(" "));
let mut all_names: Vec<_> = FORMS.iter().map(|form| form.name).collect();
all_names.sort_unstable();
all_names.dedup();
let unseen: Vec<_> = all_names
.iter()
.filter(|name| !forms.contains_key(*name))
.collect();
println!(
"metadata: {} forms, {} distinct names, {} names with no corpus row: {unseen:?}",
FORMS.len(),
all_names.len(),
unseen.len()
);
assert_eq!(counts, COUNTS, "class counts per source changed");
let pinned: Vec<_> = DISAGREEMENTS
.lines()
.filter(|line| !line.starts_with('#'))
.collect();
assert_eq!(disagreements, pinned, "disagreeing rows changed");
assert_eq!(
random_digest, RANDOM_DIGEST,
"random-probe classification changed"
);
}
#[test]
#[ignore = "requires LLVM with the gfx1030 AMDGPU target (set LLVM_BIN)"]
fn llvm_corpus_is_fresh() {
let bin = std::env::var("LLVM_BIN").expect("LLVM_BIN");
let status = std::process::Command::new("python3")
.arg(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/llvm/corpus.py"))
.args(["--llvm-bin", &bin, "--check"])
.status()
.expect("run corpus.py");
assert!(
status.success(),
"corpus.tsv differs from LLVM's current output"
);
}
+87
View File
@@ -0,0 +1,87 @@
//! LLVM oracle for instruction identification: names and lengths from llvm-mc encodings.
use std::process::Command;
use xenora_isa::meta::identify;
const SOURCE: &str = include_str!("llvm/identify.s");
fn encodings() -> Vec<(String, Vec<u8>)> {
let executable = std::env::var_os("LLVM_BIN").map_or_else(
|| "llvm-mc".into(),
|directory| std::path::PathBuf::from(directory).join("llvm-mc"),
);
let path = std::env::temp_dir().join(format!("xenora-identify-{}.s", std::process::id()));
std::fs::write(&path, SOURCE).unwrap();
let output = Command::new(executable)
.args([
"-triple=amdgcn-amd-amdhsa",
"-mcpu=gfx1030",
"-mattr=+wavefrontsize32",
"-show-encoding",
])
.arg(&path)
.output()
.expect("launch llvm-mc (provide its directory in LLVM_BIN or put it on PATH)");
std::fs::remove_file(&path).ok();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
String::from_utf8(output.stdout)
.unwrap()
.lines()
.filter_map(|line| {
let (text, encoding) = line.split_once("; encoding: [")?;
let mnemonic = text.split_whitespace().next()?.to_ascii_uppercase();
let bytes = encoding
.trim_end_matches(']')
.split(',')
.map(|byte| u8::from_str_radix(byte.trim().trim_start_matches("0x"), 16).unwrap())
.collect();
Some((mnemonic, bytes))
})
.collect()
}
fn base_name(mnemonic: &str) -> &str {
["_E32", "_E64", "_SDWA", "_DPP"]
.iter()
.fold(mnemonic, |name, suffix| name.trim_end_matches(suffix))
}
#[test]
#[ignore = "requires LLVM with the gfx1030 AMDGPU target"]
fn identification_matches_llvm_names_and_lengths() {
let encodings = encodings();
let expected_lines = SOURCE
.lines()
.filter(|line| !line.is_empty() && !line.starts_with("//"))
.count();
assert_eq!(encodings.len(), expected_lines);
// The VOP3 and VOP3P literal probes must really carry a literal trailer:
// 1.0 in either width would be an inline constant and only eight bytes.
for (probe, literal) in [("V_FMA_F32", 0x3f80_0001_u32), ("V_PK_FMA_F16", 0x3c01)] {
let (_, bytes) = encodings
.iter()
.find(|(mnemonic, _)| mnemonic == probe)
.unwrap_or_else(|| panic!("{probe} probe missing"));
assert_eq!(bytes.len(), 12, "{probe}");
assert_eq!(bytes[8..], literal.to_le_bytes(), "{probe}");
}
let mut stream = Vec::new();
for (mnemonic, bytes) in &encodings {
let found = identify(bytes).unwrap_or_else(|error| panic!("{mnemonic}: {error}"));
assert_eq!(found.form.name, base_name(mnemonic), "{mnemonic}");
assert_eq!(found.len, bytes.len(), "{mnemonic}");
stream.extend_from_slice(bytes);
}
let mut offset = 0;
for (mnemonic, bytes) in &encodings {
let found = identify(&stream[offset..]).unwrap();
assert_eq!(found.len, bytes.len(), "{mnemonic} in stream");
offset += found.len;
}
assert_eq!(offset, stream.len());
}
+105
View File
@@ -0,0 +1,105 @@
//! Ties the generated semantic registry tables to the independent XML metadata table.
use xenora_isa::meta::{EncodingFamily, FORMS as META_FORMS};
use xenora_isa::semantics::{CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, SCHEMA, SccEffect};
use xenora_isa::{ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp};
#[test]
fn generated_tables_match_the_schema_and_the_metadata_forms() {
assert_eq!(GENERATED_SCHEMA, SCHEMA);
assert_eq!(FORM_IDS.len(), FORMS.len());
for (row, (name, family)) in FORMS.iter().zip(FORM_IDS) {
assert_eq!((row.name, row.family), (name, family));
let meta = META_FORMS
.iter()
.find(|form| form.name == row.name && form.family == row.family)
.unwrap_or_else(|| panic!("{} is not an identified form", row.name));
assert_eq!(meta.opcode, row.opcode, "{}", row.name);
}
}
/// Every word of `family` that the XML metadata identifies selects an operation
/// exactly when the registry declares that form, and no 32-bit word of another
/// family selects one.
fn dispatch_selects_exactly(family: EncodingFamily, select: impl Fn(u32) -> Option<&'static str>) {
let declared: Vec<_> = FORMS.iter().filter(|row| row.family == family).collect();
let mut selected = 0;
for meta in META_FORMS.iter().filter(|form| form.family == family) {
match select(meta.bits as u32) {
Some(name) => {
assert_eq!(name, meta.name);
selected += 1;
}
None => assert!(
declared.iter().all(|row| row.name != meta.name),
"{} is declared but not dispatched",
meta.name
),
}
}
assert_eq!(selected, declared.len());
for meta in META_FORMS
.iter()
.filter(|form| form.family != family && form.bytes == 4)
{
assert_eq!(select(meta.bits as u32), None, "{}", meta.name);
}
}
#[test]
fn scalar_alu_dispatch_selects_exactly_the_registry_sop2_forms() {
for op in ScalarAluOp::ALL {
let row = op.semantics();
assert_eq!(row.family, EncodingFamily::Sop2);
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
assert_eq!(op.reads_scc(), row.carry_in == CarryIn::Scc);
assert_eq!(op.writes_scc(), row.scc != SccEffect::Unchanged);
}
dispatch_selects_exactly(EncodingFamily::Sop2, |word| {
ScalarAluOp::from_word(word).map(|op| op.semantics().name)
});
}
#[test]
fn scalar_compare_dispatch_selects_exactly_the_registry_sopc_forms() {
for op in ScalarCompareOp::ALL {
let row = op.semantics();
assert_eq!(row.family, EncodingFamily::Sopc);
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
assert_eq!(row.relation, Some(op.relation()));
}
dispatch_selects_exactly(EncodingFamily::Sopc, |word| {
ScalarCompareOp::from_word(word).map(|op| op.semantics().name)
});
}
#[test]
fn scalar_unary_dispatch_selects_exactly_the_registry_sop1_forms() {
for op in ScalarUnaryOp::ALL {
let row = op.semantics();
assert_eq!(row.family, EncodingFamily::Sop1);
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
assert_eq!(op.writes_scc(), row.scc != SccEffect::Unchanged);
}
// s_mov_b32 (opcode 3) stays hand-written, so it must not be dispatched here.
dispatch_selects_exactly(EncodingFamily::Sop1, |word| {
ScalarUnaryOp::from_word(word).map(|op| op.semantics().name)
});
}
#[test]
fn vector_alu_dispatch_selects_exactly_the_registry_vop2_forms() {
for op in VectorAluOp::ALL {
let row = op.semantics();
assert_eq!(row.family, EncodingFamily::Vop2);
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
assert_eq!(op.assembly_name(), format!("{}_e32", op.mnemonic()));
assert_eq!(op.swaps_sources(), row.swap_sources);
assert_eq!(row.scc, SccEffect::Unchanged);
}
// The hand-written VOP2 forms (v_and_b32, v_add_f32, ...) must not be
// dispatched here.
dispatch_selects_exactly(EncodingFamily::Vop2, |word| {
VectorAluOp::from_word(word).map(|op| op.semantics().name)
});
}
+16
View File
@@ -183,11 +183,27 @@ impl Arm64Assembler {
self.emit(0x93401c00 | ((wn as u32 & 0x1f) << 5) | (xd as u32 & 0x1f));
}
/// SXTB (32-bit/sign-extended): SXTB Wd, Wn (SBFM Wd, Wn, #0, #7)
///
/// Writing the 32-bit destination form clears bits 63:32 of the
/// destination register, which is what a 32-bit x86 destination requires.
pub fn sxtb_32(&mut self, wd: u8, wn: u8) {
self.emit(0x13001c00 | ((wn as u32 & 0x1f) << 5) | (wd as u32 & 0x1f));
}
/// SXTH (64-bit/sign-extended): SXTH Xd, Wn (SBFM Xd, Xn, #0, #15)
pub fn sxth_64(&mut self, xd: u8, wn: u8) {
self.emit(0x93403c00 | ((wn as u32 & 0x1f) << 5) | (xd as u32 & 0x1f));
}
/// SXTH (32-bit/sign-extended): SXTH Wd, Wn (SBFM Wd, Wn, #0, #15)
///
/// Writing the 32-bit destination form clears bits 63:32 of the
/// destination register, which is what a 32-bit x86 destination requires.
pub fn sxth_32(&mut self, wd: u8, wn: u8) {
self.emit(0x13003c00 | ((wn as u32 & 0x1f) << 5) | (wd as u32 & 0x1f));
}
/// ADD (extended/shifted register, 32-bit): ADD Wd, Wn, Wm
pub fn add_reg_32(&mut self, wd: u8, wn: u8, wm: u8) {
self.emit(
+377 -88
View File
@@ -53,6 +53,27 @@ impl Register {
}
}
/// Instruction prefixes decoded ahead of an opcode.
///
/// The interpreter decodes these once per instruction and passes them to the
/// helpers that need them, so prefix state travels as one typed value instead
/// of a list of independent booleans.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct Prefixes {
/// REX.W: 64-bit operand size.
rex_w: bool,
/// REX.R: extends the ModRM `reg` field to R8-R15.
rex_r: bool,
/// REX.X: extends the SIB `index` field to R8-R15.
rex_x: bool,
/// REX.B: extends the ModRM `rm` field to R8-R15.
rex_b: bool,
/// The GS segment override prefix (0x65) is present.
seg_gs: bool,
/// The FS segment override prefix (0x64) is present.
seg_fs: bool,
}
/// RFLAGS status bits tracked during guest execution.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct RFlags {
@@ -153,6 +174,167 @@ mod layout_tests {
}
}
#[cfg(test)]
mod prefix_tests {
use super::{CpuState, ExitReason, Interpreter, Register};
use crate::memory::{GuestMemory, MemoryPermissions};
const CODE_BASE: u64 = 0x1000;
const CODE_SIZE: usize = 0x1000;
const STACK_BASE: u64 = 0x8000_0000;
const STACK_SIZE: usize = 0x10000;
const FS_BASE: u64 = 0x9000;
const GS_BASE: u64 = 0xA000;
/// A guest memory image with executable code, a stack and distinct FS and
/// GS bases.
fn memory_with_code(code: &[u8]) -> GuestMemory {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(
CODE_BASE,
CODE_SIZE,
MemoryPermissions::READ_WRITE_EXECUTE,
code,
)
.expect("code region");
memory
.map_region(STACK_BASE, STACK_SIZE, MemoryPermissions::READ_WRITE)
.expect("stack region");
// The segment bases are distinct so a swapped prefix is visible.
memory
.map_region(FS_BASE, 0x1000, MemoryPermissions::READ_WRITE)
.expect("fs region");
memory
.map_region(GS_BASE, 0x1000, MemoryPermissions::READ_WRITE)
.expect("gs region");
memory
}
/// Run `code` on the interpreter and return the final state and exit reason.
fn run(code: &[u8]) -> (CpuState, ExitReason) {
let mut memory = memory_with_code(code);
let cpu = CpuState::new(CODE_BASE, STACK_BASE + 0x8000);
let mut interp = Interpreter::new(cpu, &mut memory, 64);
let result = interp.run();
(result.final_state, result.exit_reason)
}
/// `mov r8, imm64`: 49 B8 <imm64>.
fn mov_r8_imm64(value: u64) -> Vec<u8> {
let mut code = vec![0x49, 0xB8];
code.extend_from_slice(&value.to_le_bytes());
code
}
/// `mov rbx, imm64`: 48 BB <imm64>.
fn mov_rbx_imm64(value: u64) -> Vec<u8> {
let mut code = vec![0x48, 0xBB];
code.extend_from_slice(&value.to_le_bytes());
code
}
/// `mov rax, imm64`: 48 B8 <imm64>.
fn mov_rax_imm64(value: u64) -> Vec<u8> {
let mut code = vec![0x48, 0xB8];
code.extend_from_slice(&value.to_le_bytes());
code
}
/// REX.B extends the ModRM `rm` field, so `rm=0` selects r8.
///
/// Encoding 49 89 D8 is `mov r8, rbx`.
#[test]
fn rex_b_extends_the_rm_field_to_r8() {
let mut code = mov_rbx_imm64(0x1122_3344_5566_7788);
code.extend_from_slice(&[0x49, 0x89, 0xD8]); // mov r8, rbx
code.push(0xF4); // hlt
let (state, reason) = run(&code);
assert_eq!(reason, ExitReason::Halt);
assert_eq!(state.get(Register::Rbx), 0x1122_3344_5566_7788);
assert_eq!(state.get(Register::R8), 0x1122_3344_5566_7788);
// No prefix in this encoding selects r9.
assert_eq!(state.get(Register::R9), 0);
}
/// REX.R extends the ModRM `reg` field, so `reg=0` selects r8.
///
/// Encoding 4C 89 C3 is `mov rbx, r8`.
#[test]
fn rex_r_extends_the_reg_field_to_r8() {
let mut code = mov_r8_imm64(0x1122_3344_5566_7788);
code.extend_from_slice(&[0x4C, 0x89, 0xC3]); // mov rbx, r8
code.push(0xF4); // hlt
let (state, reason) = run(&code);
assert_eq!(reason, ExitReason::Halt);
assert_eq!(state.get(Register::R8), 0x1122_3344_5566_7788);
assert_eq!(state.get(Register::Rbx), 0x1122_3344_5566_7788);
// No prefix in this encoding selects r9.
assert_eq!(state.get(Register::R9), 0);
}
/// REX.R and REX.B extend independent fields, so the destination r9 and
/// the source r12 are chosen by different prefix bits.
///
/// Encoding 4D 89 E1 is `mov r9, r12`.
#[test]
fn rex_r_and_rex_b_extend_independent_fields() {
let mut code = mov_r8_imm64(0x1122_3344_5566_7788);
code.extend_from_slice(&[0x4D, 0x89, 0xE1]); // mov r9, r12
code.push(0xF4); // hlt
let (state, reason) = run(&code);
assert_eq!(reason, ExitReason::Halt);
// r9 receives r12, which is zero here, and not the value in r8.
assert_eq!(state.get(Register::R9), 0);
assert_eq!(state.get(Register::R12), 0);
assert_eq!(state.get(Register::R8), 0x1122_3344_5566_7788);
}
/// Without REX.W the move is 32-bit wide, so the destination keeps only the
/// low half of the source and its upper half is cleared.
///
/// Encoding 89 D8 is `mov eax, ebx`.
#[test]
fn a_move_without_rex_w_is_32_bit_wide() {
let mut code = mov_rbx_imm64(0x1122_3344_5566_7788);
code.extend_from_slice(&[0x89, 0xD8]); // mov eax, ebx
code.push(0xF4); // hlt
let (state, reason) = run(&code);
assert_eq!(reason, ExitReason::Halt);
// Only the low 32 bits of ebx survive, and rax's upper half is cleared.
assert_eq!(state.get(Register::Rax), 0x5566_7788);
assert_eq!(state.get(Register::Rbx), 0x1122_3344_5566_7788);
}
/// The FS segment override adds the FS base to the effective address.
///
/// Encoding 64 48 89 04 25 08 00 00 00 is `mov fs:[0x8], rax`.
#[test]
fn the_fs_prefix_adds_the_fs_base() {
let mut code = mov_rax_imm64(0x1122_3344_5566_7788);
code.extend_from_slice(&[0x64, 0x48, 0x89, 0x04, 0x25, 0x08, 0x00, 0x00, 0x00]);
code.push(0xF4); // hlt
let mut memory = memory_with_code(&code);
let mut cpu = CpuState::new(CODE_BASE, STACK_BASE + 0x8000);
cpu.fs_base = FS_BASE;
cpu.gs_base = GS_BASE;
let mut interp = Interpreter::new(cpu, &mut memory, 64);
let result = interp.run();
assert_eq!(result.exit_reason, ExitReason::Halt);
assert_eq!(
memory.read_u64(FS_BASE + 0x8).expect("fs read"),
0x1122_3344_5566_7788
);
// The GS base is untouched: the GS-prefixed store did not happen.
assert_eq!(memory.read_u64(GS_BASE + 0x8).expect("gs read"), 0);
}
}
/// Result returned after running guest execution.
#[derive(Debug)]
pub struct ExecutionResult {
@@ -246,29 +428,35 @@ impl<'a> Interpreter<'a> {
/// Single-step execution. Returns Ok(Some(ExitReason)) on clean exit (HLT/SYSCALL).
pub fn step(&mut self) -> Result<Option<ExitReason>, ExitReason> {
let mut rex_w = false;
let mut rex_r = false;
let mut rex_b = false;
let mut seg_gs = false;
let mut seg_fs = false;
let start = self.cpu.rip;
let result = self.execute_instruction();
if result.is_err() {
self.cpu.rip = start;
}
result
}
fn execute_instruction(&mut self) -> Result<Option<ExitReason>, ExitReason> {
let mut prefixes = Prefixes::default();
let mut byte = self.fetch_u8()?;
// Handle legacy segment prefixes: 0x65 (GS), 0x64 (FS)
while byte == 0x65 || byte == 0x64 {
if byte == 0x65 {
seg_gs = true;
prefixes.seg_gs = true;
} else {
seg_fs = true;
prefixes.seg_fs = true;
}
byte = self.fetch_u8()?;
}
// Handle REX prefix (0x40 - 0x4F)
if (byte & 0xF0) == 0x40 {
rex_w = (byte & 0x08) != 0;
rex_r = (byte & 0x04) != 0;
rex_b = (byte & 0x01) != 0;
prefixes.rex_w = (byte & 0x08) != 0;
prefixes.rex_r = (byte & 0x04) != 0;
prefixes.rex_x = (byte & 0x02) != 0;
prefixes.rex_b = (byte & 0x01) != 0;
byte = self.fetch_u8()?;
}
@@ -276,22 +464,33 @@ impl<'a> Interpreter<'a> {
// HLT: Halt execution
0xF4 => Ok(Some(ExitReason::Halt)),
// SYSCALL: 0x0F 0x05
0x0F => {
let second = self.fetch_u8()?;
if second == 0x05 {
let syscall_num = self.cpu.get(Register::Rax);
Ok(Some(ExitReason::Syscall(syscall_num)))
} else {
Err(ExitReason::IllegalInstruction(second))
0x0F => match self.fetch_u8()? {
0x05 => Ok(Some(ExitReason::Syscall(self.cpu.get(Register::Rax)))),
// MOVZX r32/r64, r/m8 (0xB6), MOVZX r32/r64, r/m16 (0xB7),
// MOVSX r32/r64, r/m8 (0xBE), MOVSX r32/r64, r/m16 (0xBF).
op @ (0xB6 | 0xB7 | 0xBE | 0xBF) => {
let modrm = self.fetch_u8()?;
self.execute_mov_ext(modrm, &prefixes, op)
}
}
op @ 0xC8..=0xCF => {
let reg = Register::from_index((op & 7) | (u8::from(prefixes.rex_b) << 3));
let value = self.cpu.get(reg);
let reversed = if prefixes.rex_w {
value.swap_bytes()
} else {
u64::from((value as u32).swap_bytes())
};
self.cpu.set(reg, reversed);
Ok(None)
}
op => Err(ExitReason::IllegalInstruction(op)),
},
// MOV r32, imm32 (0xB8 + reg) or MOV r64, imm64 with REX.W
0xB8..=0xBF => {
let reg_idx = (byte - 0xB8) + if rex_b { 8 } else { 0 };
let reg_idx = (byte - 0xB8) + if prefixes.rex_b { 8 } else { 0 };
let reg = Register::from_index(reg_idx);
if rex_w {
if prefixes.rex_w {
let imm = self.fetch_u64()?;
self.cpu.set(reg, imm);
} else {
@@ -304,28 +503,28 @@ impl<'a> Interpreter<'a> {
// XOR r/m, reg (0x31) or XOR reg, r/m (0x33)
0x31 | 0x33 => {
let modrm = self.fetch_u8()?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
let (src, dst) = if byte == 0x31 { (reg, rm) } else { (rm, reg) };
let val1 = self.cpu.get(dst);
let val2 = self.cpu.get(src);
let res = if rex_w {
let res = if prefixes.rex_w {
val1 ^ val2
} else {
(val1 as u32 ^ val2 as u32) as u64
};
self.cpu.set(dst, res);
self.update_flags_logic(res, rex_w);
self.update_flags_logic(res, prefixes.rex_w);
Ok(None)
}
// ADD r/m, reg (0x01) or ADD reg, r/m (0x03)
0x01 | 0x03 => {
let modrm = self.fetch_u8()?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
let (src, dst) = if byte == 0x01 { (reg, rm) } else { (rm, reg) };
let val1 = self.cpu.get(dst);
let val2 = self.cpu.get(src);
let (res, flags) = if rex_w {
let (res, flags) = if prefixes.rex_w {
add64(val1, val2)
} else {
let (r, f) = add32(val1 as u32, val2 as u32);
@@ -339,11 +538,11 @@ impl<'a> Interpreter<'a> {
// SUB r/m, reg (0x29) or SUB reg, r/m (0x2B)
0x29 | 0x2B => {
let modrm = self.fetch_u8()?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
let (src, dst) = if byte == 0x29 { (reg, rm) } else { (rm, reg) };
let val1 = self.cpu.get(dst);
let val2 = self.cpu.get(src);
let (res, flags) = if rex_w {
let (res, flags) = if prefixes.rex_w {
sub64(val1, val2)
} else {
let (r, f) = sub32(val1 as u32, val2 as u32);
@@ -357,13 +556,13 @@ impl<'a> Interpreter<'a> {
// CMP reg, r/m (0x3B) or CMP r/m, reg (0x39)
0x39 | 0x3B => {
let modrm = self.fetch_u8()?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
let (v1, v2) = if byte == 0x39 {
(self.cpu.get(rm), self.cpu.get(reg))
} else {
(self.cpu.get(reg), self.cpu.get(rm))
};
let (_, flags) = if rex_w {
let (_, flags) = if prefixes.rex_w {
sub64(v1, v2)
} else {
let (r, f) = sub32(v1 as u32, v2 as u32);
@@ -377,7 +576,7 @@ impl<'a> Interpreter<'a> {
0x83 => {
let modrm = self.fetch_u8()?;
let op = (modrm >> 3) & 7;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
let imm8 = self.fetch_i8()? as i64;
let imm = imm8 as u64;
@@ -385,7 +584,7 @@ impl<'a> Interpreter<'a> {
match op {
0 => {
// ADD
let (res, flags) = if rex_w {
let (res, flags) = if prefixes.rex_w {
add64(val, imm)
} else {
let (r, f) = add32(val as u32, imm as u32);
@@ -396,7 +595,7 @@ impl<'a> Interpreter<'a> {
}
5 => {
// SUB
let (res, flags) = if rex_w {
let (res, flags) = if prefixes.rex_w {
sub64(val, imm)
} else {
let (r, f) = sub32(val as u32, imm as u32);
@@ -407,7 +606,7 @@ impl<'a> Interpreter<'a> {
}
7 => {
// CMP
let (_, flags) = if rex_w {
let (_, flags) = if prefixes.rex_w {
sub64(val, imm)
} else {
let (r, f) = sub32(val as u32, imm as u32);
@@ -424,7 +623,7 @@ impl<'a> Interpreter<'a> {
// MOV r/m, reg (0x89) or MOV reg, r/m (0x8B)
0x89 | 0x8B => {
let modrm = self.fetch_u8()?;
self.execute_mov_rm(modrm, rex_w, rex_r, rex_b, byte == 0x8B, seg_gs, seg_fs)
self.execute_mov_rm(modrm, &prefixes, byte == 0x8B)
}
// JMP rel8 (0xEB)
@@ -478,7 +677,7 @@ impl<'a> Interpreter<'a> {
// PUSH reg (0x50..=0x57)
0x50..=0x57 => {
let reg_idx = (byte - 0x50) + if rex_b { 8 } else { 0 };
let reg_idx = (byte - 0x50) + if prefixes.rex_b { 8 } else { 0 };
let reg = Register::from_index(reg_idx);
let val = self.cpu.get(reg);
self.push_u64(val)?;
@@ -487,7 +686,7 @@ impl<'a> Interpreter<'a> {
// POP reg (0x58..=0x5F)
0x58..=0x5F => {
let reg_idx = (byte - 0x58) + if rex_b { 8 } else { 0 };
let reg_idx = (byte - 0x58) + if prefixes.rex_b { 8 } else { 0 };
let reg = Register::from_index(reg_idx);
let val = self.pop_u64()?;
self.cpu.set(reg, val);
@@ -518,32 +717,92 @@ impl<'a> Interpreter<'a> {
fn decode_modrm_reg_reg(
&self,
modrm: u8,
rex_r: bool,
rex_b: bool,
prefixes: &Prefixes,
) -> Result<(Register, Register), ExitReason> {
let mode = (modrm >> 6) & 3;
if mode != 3 {
return Err(ExitReason::IllegalInstruction(modrm));
}
let reg_idx = ((modrm >> 3) & 7) + if rex_r { 8 } else { 0 };
let rm_idx = (modrm & 7) + if rex_b { 8 } else { 0 };
let reg_idx = ((modrm >> 3) & 7) + if prefixes.rex_r { 8 } else { 0 };
let rm_idx = (modrm & 7) + if prefixes.rex_b { 8 } else { 0 };
Ok((Register::from_index(reg_idx), Register::from_index(rm_idx)))
}
#[allow(clippy::too_many_arguments)]
/// Execute a MOVZX or MOVSX extension instruction.
///
/// `op` is the second opcode byte: `0xB6` extends a byte, `0xB7` extends
/// a word, `0xBE` sign-extends a byte and `0xBF` sign-extends a word.
///
/// The source width follows the opcode and the destination width follows
/// REX.W: without REX.W the destination is 32 bits and its upper half is
/// cleared, and with REX.W it is 64 bits. MOVSX sign-extends to the
/// destination width, so a 32-bit destination keeps the sign in bits
/// 31:0 and a zeroed upper half, while a 64-bit destination keeps the
/// sign extension across all 64 bits.
fn execute_mov_ext(
&mut self,
modrm: u8,
prefixes: &Prefixes,
op: u8,
) -> Result<Option<ExitReason>, ExitReason> {
let mode = (modrm >> 6) & 3;
let reg_idx = ((modrm >> 3) & 7) + if prefixes.rex_r { 8 } else { 0 };
let rm_idx = (modrm & 7) + if prefixes.rex_b { 8 } else { 0 };
let reg = Register::from_index(reg_idx);
let is_word = op == 0xB7 || op == 0xBF;
let is_signed = op == 0xBE || op == 0xBF;
let source = if mode == 3 {
// Register source: only the low 8 or 16 bits are read.
let value = self.cpu.get(Register::from_index(rm_idx));
if is_word {
value as u16 as u64
} else {
value as u8 as u64
}
} else {
let address = self.effective_address(modrm, prefixes)?;
if is_word {
self.memory
.read_u16(address)
.map_err(ExitReason::MemoryFault)? as u64
} else {
self.memory
.read_u8(address)
.map_err(ExitReason::MemoryFault)? as u64
}
};
let extended = if is_signed {
if is_word {
source as u16 as i16 as i64 as u64
} else {
source as u8 as i8 as i64 as u64
}
} else {
source
};
// A 32-bit destination holds a 32-bit result, so its upper half is
// cleared; a 64-bit destination keeps the full extension.
let result = if prefixes.rex_w {
extended
} else {
extended as u32 as u64
};
self.cpu.set(reg, result);
Ok(None)
}
fn execute_mov_rm(
&mut self,
modrm: u8,
rex_w: bool,
rex_r: bool,
rex_b: bool,
prefixes: &Prefixes,
is_load: bool,
seg_gs: bool,
seg_fs: bool,
) -> Result<Option<ExitReason>, ExitReason> {
let mode = (modrm >> 6) & 3;
let reg_idx = ((modrm >> 3) & 7) + if rex_r { 8 } else { 0 };
let rm_idx = (modrm & 7) + if rex_b { 8 } else { 0 };
let reg_idx = ((modrm >> 3) & 7) + if prefixes.rex_r { 8 } else { 0 };
let rm_idx = (modrm & 7) + if prefixes.rex_b { 8 } else { 0 };
let reg = Register::from_index(reg_idx);
if mode == 3 {
@@ -551,23 +810,82 @@ impl<'a> Interpreter<'a> {
let rm = Register::from_index(rm_idx);
if is_load {
let val = self.cpu.get(rm);
self.cpu
.set(reg, if rex_w { val } else { val as u32 as u64 });
self.cpu.set(
reg,
if prefixes.rex_w {
val
} else {
val as u32 as u64
},
);
} else {
let val = self.cpu.get(reg);
self.cpu
.set(rm, if rex_w { val } else { val as u32 as u64 });
self.cpu.set(
rm,
if prefixes.rex_w {
val
} else {
val as u32 as u64
},
);
}
return Ok(None);
}
// Memory operand [rm + disp] or SIB
let effective_addr = self.effective_address(modrm, prefixes)?;
if is_load {
// Load from memory to reg
if prefixes.rex_w {
let val = self
.memory
.read_u64(effective_addr)
.map_err(ExitReason::MemoryFault)?;
self.cpu.set(reg, val);
} else {
let val = self
.memory
.read_u32(effective_addr)
.map_err(ExitReason::MemoryFault)?;
self.cpu.set(reg, val as u64);
}
} else {
// Store from reg to memory
let val = self.cpu.get(reg);
if prefixes.rex_w {
self.memory
.write_u64(effective_addr, val)
.map_err(ExitReason::MemoryFault)?;
} else {
self.memory
.write_u32(effective_addr, val as u32)
.map_err(ExitReason::MemoryFault)?;
}
}
Ok(None)
}
/// Compute the effective address of a memory operand.
///
/// Consumes the SIB byte and the displacement from the instruction
/// stream. The FS or GS segment base is added when the corresponding
/// segment override prefix is present.
fn effective_address(&mut self, modrm: u8, prefixes: &Prefixes) -> Result<u64, ExitReason> {
let mode = (modrm >> 6) & 3;
let rm_idx = (modrm & 7) + if prefixes.rex_b { 8 } else { 0 };
let (base_val, disp): (u64, i64) = if (rm_idx & 7) == 4 {
// SIB byte follows ModR/M
let sib = self.fetch_u8()?;
let scale_shift = (sib >> 6) & 3;
let index_raw = ((sib >> 3) & 7) + if rex_r { 8 } else { 0 }; // SIB.index can use REX.X; here index_raw
let base_raw = (sib & 7) + if rex_b { 8 } else { 0 };
// REX.X extends the SIB index field; REX.R extends the ModRM reg
// field and must not affect the index. An index field of 100b
// selects r12 when REX.X is set, and means "no index" otherwise.
let index_field = (sib >> 3) & 7;
let index_raw = index_field + if prefixes.rex_x { 8 } else { 0 };
let base_raw = (sib & 7) + if prefixes.rex_b { 8 } else { 0 };
let base_v = if mode == 0 && (sib & 7) == 5 {
// disp32 with no base register
@@ -576,7 +894,7 @@ impl<'a> Interpreter<'a> {
self.cpu.get(Register::from_index(base_raw))
};
let index_v = if (sib >> 3) & 7 == 4 {
let index_v = if index_field == 4 && !prefixes.rex_x {
// index == 4 means no index register (ESP/RSP)
0u64
} else {
@@ -623,42 +941,13 @@ impl<'a> Interpreter<'a> {
(base_val as i64 + disp) as u64
};
if seg_gs {
if prefixes.seg_gs {
effective_addr = effective_addr.wrapping_add(self.cpu.gs_base);
} else if seg_fs {
} else if prefixes.seg_fs {
effective_addr = effective_addr.wrapping_add(self.cpu.fs_base);
}
if is_load {
// Load from memory to reg
if rex_w {
let val = self
.memory
.read_u64(effective_addr)
.map_err(ExitReason::MemoryFault)?;
self.cpu.set(reg, val);
} else {
let val = self
.memory
.read_u32(effective_addr)
.map_err(ExitReason::MemoryFault)?;
self.cpu.set(reg, val as u64);
}
} else {
// Store from reg to memory
let val = self.cpu.get(reg);
if rex_w {
self.memory
.write_u64(effective_addr, val)
.map_err(ExitReason::MemoryFault)?;
} else {
self.memory
.write_u32(effective_addr, val as u32)
.map_err(ExitReason::MemoryFault)?;
}
}
Ok(None)
Ok(effective_addr)
}
fn update_flags_logic(&mut self, val: u64, is_64: bool) {
+633 -9
View File
@@ -112,7 +112,19 @@ impl DbtEngine {
// Look up or translate block at cpu.rip
let block_limit = (max_instructions - instructions_count).min(MAX_BLOCK_INSTRUCTIONS);
let block_fn_ptr = match self.get_or_compile_block(cpu.rip, memory, block_limit) {
let mut block = self.get_or_compile_block(cpu.rip, memory, block_limit);
// A decode failure can belong to a later instruction in the block.
// Execute the current instruction alone so earlier effects retire
// and an earlier data fault takes precedence over speculative fetch.
if block_limit > 1
&& matches!(
block,
Err(ExitReason::IllegalInstruction(_) | ExitReason::MemoryFault(_))
)
{
block = self.get_or_compile_block(cpu.rip, memory, 1);
}
let block_fn_ptr = match block {
Ok(ptr) => ptr,
Err(reason) => {
return ExecutionResult {
@@ -753,6 +765,7 @@ impl DbtEngine {
// MOV reg, [RIP + disp32]
asm.mov_reg_64(X0, X20);
asm.load_imm_64(X1, target_ea);
Self::emit_segment_base(asm, seg_gs, seg_fs);
let helper_fn = read_u64_helper as *const () as u64;
asm.load_imm_64(X4, helper_fn);
asm.blr(X4);
@@ -766,6 +779,7 @@ impl DbtEngine {
asm.ldr_uoff_64(X2, X19, (reg_idx as u32) * 8);
asm.mov_reg_64(X0, X20);
asm.load_imm_64(X1, target_ea);
Self::emit_segment_base(asm, seg_gs, seg_fs);
let helper_fn = write_u64_helper as *const () as u64;
asm.load_imm_64(X4, helper_fn);
asm.blr(X4);
@@ -1077,6 +1091,16 @@ impl DbtEngine {
cur_rip += 1;
match op2 {
// BSWAP r32/r64: the register is encoded in the opcode.
0xC8..=0xCF => {
insn_count += 1;
let reg = (op2 & 7) | (u8::from(rex_b) << 3);
let offset = u32::from(reg) * 8;
asm.ldr_uoff_64(X9, X19, offset);
// REV X9, X9 or REV W9, W9. A W write clears the upper half.
asm.emit(if rex_w { 0xdac0_0d29 } else { 0x5ac0_0929 });
asm.str_uoff_64(X9, X19, offset);
}
// Jcc rel32 (0x0F 0x80..=0x8F)
0x80..=0x8F => {
insn_count += 1;
@@ -1223,7 +1247,13 @@ impl DbtEngine {
if mode == 3 {
asm.ldr_uoff_64(X9, X19, (rm_idx as u32) * 8);
asm.sxtb_64(X9, X9);
if rex_w {
asm.sxtb_64(X9, X9);
} else {
// A 32-bit destination holds a 32-bit
// result, so the upper half is cleared.
asm.sxtb_32(X9, X9);
}
asm.str_uoff_64(X9, X19, (reg_idx as u32) * 8);
} else {
Self::emit_effective_address(
@@ -1243,7 +1273,13 @@ impl DbtEngine {
asm.load_imm_64(X4, helper_fn);
asm.blr(X4);
emit_fault_guard(asm, &mut fault_guards, insn_count - 1, insn_rip);
asm.sxtb_64(X0, X0);
if rex_w {
asm.sxtb_64(X0, X0);
} else {
// A 32-bit destination holds a 32-bit
// result, so the upper half is cleared.
asm.sxtb_32(X0, X0);
}
asm.str_uoff_64(X0, X19, (reg_idx as u32) * 8);
}
}
@@ -1261,7 +1297,13 @@ impl DbtEngine {
if mode == 3 {
asm.ldr_uoff_64(X9, X19, (rm_idx as u32) * 8);
asm.sxth_64(X9, X9);
if rex_w {
asm.sxth_64(X9, X9);
} else {
// A 32-bit destination holds a 32-bit
// result, so the upper half is cleared.
asm.sxth_32(X9, X9);
}
asm.str_uoff_64(X9, X19, (reg_idx as u32) * 8);
} else {
Self::emit_effective_address(
@@ -1281,7 +1323,13 @@ impl DbtEngine {
asm.load_imm_64(X4, helper_fn);
asm.blr(X4);
emit_fault_guard(asm, &mut fault_guards, insn_count - 1, insn_rip);
asm.sxth_64(X0, X0);
if rex_w {
asm.sxth_64(X0, X0);
} else {
// A 32-bit destination holds a 32-bit
// result, so the upper half is cleared.
asm.sxth_32(X0, X0);
}
asm.str_uoff_64(X0, X19, (reg_idx as u32) * 8);
}
}
@@ -1431,17 +1479,36 @@ impl DbtEngine {
}
}
Self::emit_segment_base(asm, seg_gs, seg_fs);
Ok(())
}
/// Add the FS or GS segment base to the effective address held in X1.
///
/// In 64-bit mode an FS or GS segment override adds the segment base to
/// the effective address, so the linear address is
/// `(FS or GS).base + base + (scale * index) + displacement`
/// (Intel SDM Volume 3A, section 3.4.4; AMD64 Architecture Programmer's
/// Manual Volume 1, section 2.2.3.3).
///
/// The base is a runtime guest value, so it is read from the guest CPU
/// state rather than folded into the translated address.
///
/// When both FS and GS overrides are present the encoding is
/// architecturally undefined (Intel SDM Volume 2: "The effect of redundant
/// prefixes ... is undefined"), so this uses a fixed local rule of
/// preferring GS. The interpreter applies the same rule.
fn emit_segment_base(asm: &mut Arm64Assembler, seg_gs: bool, seg_fs: bool) {
if seg_gs {
// Add CpuState.gs_base (offset 16*8 + 8 + 8 = 144) to X1
// CpuState.gs_base (offset 16*8 + 8 + 8 = 144) to X1
asm.ldr_uoff_64(X9, X19, 144);
asm.add_reg_64(X1, X1, X9);
} else if seg_fs {
// Add CpuState.fs_base (offset 16*8 + 8 + 8 + 8 = 152) to X1
// CpuState.fs_base (offset 16*8 + 8 + 8 + 8 = 152) to X1
asm.ldr_uoff_64(X9, X19, 152);
asm.add_reg_64(X1, X1, X9);
}
Ok(())
}
fn emit_set_exit_reason(asm: &mut Arm64Assembler, code: u32, next_rip: u64) {
@@ -1651,6 +1718,58 @@ mod tests {
assert_eq!(unsupported.instructions_executed, 0);
}
#[test]
fn completed_store_survives_the_next_fault_or_budget_boundary() {
for native in [false, true] {
for (tail, fault) in [
(&[0xcc][..], ExitReason::IllegalInstruction(0xcc)),
(
&[0xb8, 1][..],
ExitReason::MemoryFault(MemoryError::UnmappedAddress(ENTRY + 5)),
),
(
&[0x48, 0x8b, 0x02, 0xf4][..],
ExitReason::MemoryFault(MemoryError::UnmappedAddress(0x4000)),
),
] {
for budget in [0, 1, 16] {
// mov [rcx], rax; then an illegal, truncated or faulting instruction.
let code = [&[0x48, 0x89, 0x01][..], tail].concat();
let (mut engine, mut cpu, mut memory) = fixture(&code);
memory
.map_region(0x3000, 8, MemoryPermissions::READ_WRITE)
.unwrap();
cpu.set(Register::Rax, 0x1234);
cpu.set(Register::Rcx, 0x3000);
cpu.set(Register::Rdx, 0x4000);
let mut expected = cpu.clone();
if budget > 0 {
expected.rip += 3;
}
let result = if native {
engine.run(&mut cpu, &mut memory, budget)
} else {
crate::cpu::Interpreter::new(cpu, &mut memory, budget).run()
};
assert_eq!(result.instructions_executed, budget.min(1));
assert_eq!(
result.exit_reason,
if budget <= 1 {
ExitReason::StepLimitExceeded
} else {
fault
}
);
assert_eq!(result.final_state, expected);
assert_eq!(
memory.read_u64(0x3000).unwrap(),
if budget == 0 { 0 } else { 0x1234 }
);
}
}
}
}
#[test]
fn hlt_preserves_first_memory_fault() {
let code = [
@@ -1707,6 +1826,92 @@ mod tests {
assert_eq!(memory.read_u64(STORED_ADDR).unwrap(), STORED_VALUE);
}
/// A 32-bit MOVSX destination holds a 32-bit result, so the upper half of
/// the register must be cleared.
///
/// The encodings are `movsbl eax, bl` (0F BE C3) and
/// `movsbq rdx, bl` (48 0F BE D3), as produced by LLVM 23.1.6
/// `llvm-mc -show-encoding`. With `bl = 0xFF` the 32-bit destination holds
/// 0x00000000ffffffff while the 64-bit destination holds the sign
/// extension across all 64 bits.
///
/// Per Intel SDM Volume 1, "Address Calculations in 64-Bit Mode": "32-bit
/// operands generate a 32-bit result, zero-extended to a 64-bit result in
/// the destination general-purpose register."
#[test]
fn movsx_to_a_32_bit_destination_clears_the_upper_half() {
// mov rbx, 0xffffffffffffffff (48 BB <imm64>)
// movsbl eax, bl (0F BE C3)
// movsbq rdx, bl (48 0F BE D3)
let mut code = vec![0x48, 0xBB];
code.extend_from_slice(&u64::MAX.to_le_bytes());
code.extend_from_slice(&[0x0F, 0xBE, 0xC3]);
code.extend_from_slice(&[0x48, 0x0F, 0xBE, 0xD3]);
code.push(0xF4); // hlt
let (mut engine, mut cpu, mut memory) = fixture(&code);
cpu.set(Register::Rbx, u64::MAX);
let result = engine.run(&mut cpu, &mut memory, 16);
assert_eq!(result.exit_reason, ExitReason::Halt);
assert_eq!(result.final_state.get(Register::Rax), 0x0000_0000_ffff_ffff);
assert_eq!(result.final_state.get(Register::Rdx), 0xffff_ffff_ffff_ffff);
}
/// A 32-bit MOVSX destination from a 16-bit source also holds a 32-bit
/// result.
///
/// The encodings are `movswl eax, bx` (0F BF C3) and
/// `movswq rdx, bx` (48 0F BF D3), as produced by LLVM 23.1.6
/// `llvm-mc -show-encoding`.
#[test]
fn movsx_from_a_word_to_a_32_bit_destination_clears_the_upper_half() {
// mov rbx, 0xffffffffffffffff (48 BB <imm64>)
// movswl eax, bx (0F BF C3)
// movswq rdx, bx (48 0F BF D3)
let mut code = vec![0x48, 0xBB];
code.extend_from_slice(&u64::MAX.to_le_bytes());
code.extend_from_slice(&[0x0F, 0xBF, 0xC3]);
code.extend_from_slice(&[0x48, 0x0F, 0xBF, 0xD3]);
code.push(0xF4); // hlt
let (mut engine, mut cpu, mut memory) = fixture(&code);
cpu.set(Register::Rbx, u64::MAX);
let result = engine.run(&mut cpu, &mut memory, 16);
assert_eq!(result.exit_reason, ExitReason::Halt);
assert_eq!(result.final_state.get(Register::Rax), 0x0000_0000_ffff_ffff);
assert_eq!(result.final_state.get(Register::Rdx), 0xffff_ffff_ffff_ffff);
}
/// The same 32-bit destination rule applies to the memory source forms.
///
/// The encodings are `movsbl eax, byte [rdi]` (0F BE 07) and
/// `movsbq rdx, byte [rdi]` (48 0F BE 17), as produced by LLVM 23.1.6
/// `llvm-mc -show-encoding`.
#[test]
fn movsx_from_memory_to_a_32_bit_destination_clears_the_upper_half() {
// mov rdi, 0x4000 (48 BF <imm64>)
// movsbl eax, byte [rdi] (0F BE 07)
// movsbq rdx, byte [rdi] (48 0F BE 17)
let mut code = vec![0x48, 0xBF];
code.extend_from_slice(&0x4000u64.to_le_bytes());
code.extend_from_slice(&[0x0F, 0xBE, 0x07]);
code.extend_from_slice(&[0x48, 0x0F, 0xBE, 0x17]);
code.push(0xF4); // hlt
let (mut engine, mut cpu, mut memory) = fixture(&code);
memory
.map_region(0x4000, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
memory.write_u8(0x4000, 0xFF).unwrap();
let result = engine.run(&mut cpu, &mut memory, 16);
assert_eq!(result.exit_reason, ExitReason::Halt);
assert_eq!(result.final_state.get(Register::Rax), 0x0000_0000_ffff_ffff);
assert_eq!(result.final_state.get(Register::Rdx), 0xffff_ffff_ffff_ffff);
}
#[test]
fn indirect_call_target_fault_leaves_guest_stack_unchanged() {
// call qword ptr [rip + 0x1000]; hlt. The IAT slot is outside the
@@ -1856,4 +2061,423 @@ mod tests {
]
);
}
// FS/GS segment override regression tests from #280 (#72), restored after a
// merge-conflict resolution dropped them.
/// A segment-relative store and load through the FS base.
///
/// The encodings are `mov [fs:0x8], rbx` (64 48 89 1C 25 08 00 00 00)
/// and `mov rdx, [fs:0x8]` (64 48 8B 14 25 08 00 00 00), as produced by
/// LLVM 23.1.6 `llvm-mc -show-encoding`. The SIB byte 0x25 selects "no
/// index" and "no base", so the address is the FS base plus the
/// displacement 8.
///
/// Per Intel SDM Volume 3A section 3.4.4 the linear address is
/// `(FS or GS).base + index + displacement`, so the store must land at
/// `FS_BASE + 8`.
#[test]
fn fs_segment_override_adds_the_fs_base_to_the_address() {
let code = [
0x64, 0x48, 0x89, 0x1C, 0x25, 0x08, 0x00, 0x00, 0x00, // mov [fs:0x8], rbx
0x64, 0x48, 0x8B, 0x14, 0x25, 0x08, 0x00, 0x00, 0x00, // mov rdx, [fs:0x8]
0xF4, // hlt
];
let (mut engine, mut cpu, mut memory) = fixture(&code);
const FS_BASE: u64 = 0x7000;
const GS_BASE: u64 = 0x8000;
const STORED_VALUE: u64 = 0x1122_3344_5566_7788;
cpu.fs_base = FS_BASE;
cpu.gs_base = GS_BASE;
cpu.set(Register::Rbx, STORED_VALUE);
memory
.map_region(FS_BASE, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
memory
.map_region(GS_BASE, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
let result = engine.run(&mut cpu, &mut memory, 16);
assert_eq!(result.exit_reason, ExitReason::Halt);
// The store landed at the FS base plus the displacement, not at the
// bare displacement and not at the GS base. The bare displacement
// address 8 is not mapped at all, so reaching it would have faulted.
assert_eq!(memory.read_u64(FS_BASE + 8).unwrap(), STORED_VALUE);
assert_eq!(memory.read_u64(GS_BASE + 8).unwrap(), 0);
// The load read back the same location.
assert_eq!(result.final_state.get(Register::Rdx), STORED_VALUE);
}
/// A RIP-relative segment-relative store adds the segment base too.
///
/// The encoding is `mov [fs:(%rip)], rbx` (64 48 89 1D 00 00 00 00), as
/// produced by LLVM 23.1.6 `llvm-mc -show-encoding`. The displacement is
/// zero, so the address is the address of the next instruction plus the
/// FS base.
///
/// The segment base is added to the effective address for every addressing
/// form, so this must land at `FS_BASE + ENTRY + 8` and not at the bare
/// RIP-relative address.
#[test]
fn rip_relative_segment_override_adds_the_segment_base() {
let code = [
0x64, 0x48, 0x89, 0x1D, 0x00, 0x00, 0x00, 0x00, // mov [fs:(%rip)], rbx
0xF4, // hlt
];
let (mut engine, mut cpu, mut memory) = fixture(&code);
const FS_BASE: u64 = 0x7000;
const STORED_VALUE: u64 = 0x1122_3344_5566_7788;
cpu.fs_base = FS_BASE;
cpu.set(Register::Rbx, STORED_VALUE);
// The segment-adjusted address is FS_BASE + ENTRY + 8, so the region
// has to reach that far.
memory
.map_region(FS_BASE, 0x2000, MemoryPermissions::READ_WRITE)
.unwrap();
let result = engine.run(&mut cpu, &mut memory, 16);
assert_eq!(result.exit_reason, ExitReason::Halt);
// The instruction is 8 bytes long, so the next instruction is at
// ENTRY + 8 and the displacement of zero makes that the offset.
assert_eq!(memory.read_u64(FS_BASE + ENTRY + 8).unwrap(), STORED_VALUE);
}
/// The two execution paths must agree on segment-relative addressing.
///
/// The native DBT translator and the software interpreter are separate
/// implementations of the same guest semantics, so a program that uses a
/// segment override must produce the same result and the same memory
/// writes under both.
///
/// The encodings are `mov [fs:0x8], rbx` (64 48 89 1C 25 08 00 00 00),
/// `mov [gs:0x10], rbx` (65 48 89 1C 25 10 00 00 00),
/// `mov rdx, [fs:0x8]` (64 48 8B 14 25 08 00 00 00) and
/// `mov rsi, [gs:0x10]` (65 48 8B 34 25 10 00 00 00), as produced by
/// LLVM 23.1.6 `llvm-mc -show-encoding`.
#[test]
fn interpreter_and_native_dbt_agree_on_segment_relative_addressing() {
const CODE: [u8; 37] = [
0x64, 0x48, 0x89, 0x1C, 0x25, 0x08, 0x00, 0x00, 0x00, // mov [fs:0x8], rbx
0x65, 0x48, 0x89, 0x1C, 0x25, 0x10, 0x00, 0x00, 0x00, // mov [gs:0x10], rbx
0x64, 0x48, 0x8B, 0x14, 0x25, 0x08, 0x00, 0x00, 0x00, // mov rdx, [fs:0x8]
0x65, 0x48, 0x8B, 0x34, 0x25, 0x10, 0x00, 0x00, 0x00, // mov rsi, [gs:0x10]
0xF4, // hlt
];
const FS_BASE: u64 = 0x7000;
const GS_BASE: u64 = 0x8000;
const STORED_VALUE: u64 = 0x1122_3344_5566_7788;
// The native DBT path.
let (mut engine, mut cpu, mut memory) = fixture(&CODE);
cpu.fs_base = FS_BASE;
cpu.gs_base = GS_BASE;
cpu.set(Register::Rbx, STORED_VALUE);
memory
.map_region(FS_BASE, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
memory
.map_region(GS_BASE, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
let native = engine.run(&mut cpu, &mut memory, 16);
assert_eq!(native.exit_reason, ExitReason::Halt);
let native_memory = memory;
// The software interpreter path over the same program.
let mut memory = GuestMemory::new();
memory
.map_region_with_data(ENTRY, CODE.len(), MemoryPermissions::READ_EXECUTE, &CODE)
.unwrap();
memory
.map_region(FS_BASE, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
memory
.map_region(GS_BASE, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
let mut cpu = CpuState::new(ENTRY, 0);
cpu.fs_base = FS_BASE;
cpu.gs_base = GS_BASE;
cpu.set(Register::Rbx, STORED_VALUE);
let mut interp = crate::cpu::Interpreter::new(cpu, &mut memory, 16);
let interpreted = interp.run();
assert_eq!(interpreted.exit_reason, native.exit_reason);
assert_eq!(interpreted.final_state, native.final_state);
assert_eq!(
memory.read_u64(FS_BASE + 8).unwrap(),
native.final_state.get(Register::Rbx)
);
assert_eq!(
memory.read_u64(GS_BASE + 0x10).unwrap(),
native.final_state.get(Register::Rbx)
);
// The bytes each path left in guest memory must be identical, not only the
// two words checked above.
for base in [FS_BASE, GS_BASE] {
assert_eq!(
region_bytes(&native_memory, base, 0x100),
region_bytes(&memory, base, 0x100),
"segment region at {base:#x}"
);
}
}
fn region_bytes(memory: &GuestMemory, base: u64, len: usize) -> Vec<u8> {
let mut bytes = vec![0; len];
memory.read_bytes(base, &mut bytes).unwrap();
bytes
}
/// FS and GS RIP-relative loads and stores with positive and negative
/// displacements. The effective address is the segment base plus the address of
/// the next instruction plus the signed disp32 (AMD64 APM vol. 1, RIP-relative
/// addressing; FS/GS overrides still apply in 64-bit mode). Each expected address
/// below is worked out by hand from that rule.
const RIP_CODE: [u8; 33] = [
// 0x1000: mov fs:[rip - 0x100], rbx -> FS + 0x1008 - 0x100 = FS + 0x0F08
0x64, 0x48, 0x89, 0x1D, 0x00, 0xFF, 0xFF, 0xFF,
// 0x1008: mov gs:[rip + 0x40], rbx -> GS + 0x1010 + 0x40 = GS + 0x1050
0x65, 0x48, 0x89, 0x1D, 0x40, 0x00, 0x00, 0x00,
// 0x1010: mov rdx, fs:[rip - 0x28] -> FS + 0x1018 - 0x28 = FS + 0x0FF0
0x64, 0x48, 0x8B, 0x15, 0xD8, 0xFF, 0xFF, 0xFF,
// 0x1018: mov rsi, gs:[rip + 0x20] -> GS + 0x1020 + 0x20 = GS + 0x1040
0x65, 0x48, 0x8B, 0x35, 0x20, 0x00, 0x00, 0x00, // 0x1020: hlt
0xF4,
];
const RIP_FS: u64 = 0x10_0000;
const RIP_GS: u64 = 0x20_0000;
const RIP_STORED: u64 = 0x0102_0304_0506_0708;
const RIP_FS_SEED: u64 = 0xA1A2_A3A4_A5A6_A7A8;
const RIP_GS_SEED: u64 = 0xB1B2_B3B4_B5B6_B7B8;
fn rip_setup(cpu: &mut CpuState, memory: &mut GuestMemory) {
cpu.fs_base = RIP_FS;
cpu.gs_base = RIP_GS;
cpu.set(Register::Rbx, RIP_STORED);
for base in [RIP_FS, RIP_GS] {
memory
.map_region(base, 0x2000, MemoryPermissions::READ_WRITE)
.unwrap();
}
memory.write_u64(RIP_FS + 0x0FF0, RIP_FS_SEED).unwrap();
memory.write_u64(RIP_GS + 0x1040, RIP_GS_SEED).unwrap();
}
fn check_rip_results(state: &CpuState, memory: &GuestMemory, path: &str) {
assert_eq!(
memory.read_u64(RIP_FS + 0x0F08).unwrap(),
RIP_STORED,
"{path}: FS store, negative disp"
);
assert_eq!(
memory.read_u64(RIP_GS + 0x1050).unwrap(),
RIP_STORED,
"{path}: GS store, positive disp"
);
assert_eq!(
state.get(Register::Rdx),
RIP_FS_SEED,
"{path}: FS load, negative disp"
);
assert_eq!(
state.get(Register::Rsi),
RIP_GS_SEED,
"{path}: GS load, positive disp"
);
}
#[test]
fn fs_and_gs_rip_relative_loads_and_stores_use_the_segment_base() {
let (mut engine, mut cpu, mut memory) = fixture(&RIP_CODE);
rip_setup(&mut cpu, &mut memory);
let native = engine.run(&mut cpu, &mut memory, 16);
assert_eq!(native.exit_reason, ExitReason::Halt);
check_rip_results(&native.final_state, &memory, "native DBT");
}
#[test]
fn interpreter_and_native_dbt_agree_on_rip_relative_segment_accesses() {
let (mut engine, mut cpu, mut native_memory) = fixture(&RIP_CODE);
rip_setup(&mut cpu, &mut native_memory);
let native = engine.run(&mut cpu, &mut native_memory, 16);
let (_, mut cpu, mut memory) = fixture(&RIP_CODE);
rip_setup(&mut cpu, &mut memory);
let interpreted = crate::cpu::Interpreter::new(cpu, &mut memory, 16).run();
assert_eq!(interpreted.exit_reason, native.exit_reason);
assert_eq!(interpreted.final_state, native.final_state);
check_rip_results(&interpreted.final_state, &memory, "interpreter");
for base in [RIP_FS, RIP_GS] {
assert_eq!(
region_bytes(&native_memory, base, 0x2000),
region_bytes(&memory, base, 0x2000),
"segment region at {base:#x}"
);
}
}
#[test]
fn rip_relative_segment_faults_report_the_segment_adjusted_address() {
// One instruction per case, with nothing mapped at either segment base.
let cases: [(&[u8], u64); 4] = [
// mov fs:[rip - 0x10], rbx -> FS + 0x1008 - 0x10
(
&[0x64, 0x48, 0x89, 0x1D, 0xF0, 0xFF, 0xFF, 0xFF, 0xF4],
RIP_FS + 0x0FF8,
),
// mov gs:[rip + 0x30], rbx -> GS + 0x1008 + 0x30
(
&[0x65, 0x48, 0x89, 0x1D, 0x30, 0x00, 0x00, 0x00, 0xF4],
RIP_GS + 0x1038,
),
// mov rdx, fs:[rip - 0x800] -> FS + 0x1008 - 0x800
(
&[0x64, 0x48, 0x8B, 0x15, 0x00, 0xF8, 0xFF, 0xFF, 0xF4],
RIP_FS + 0x0808,
),
// mov rsi, gs:[rip + 0x8] -> GS + 0x1008 + 0x8
(
&[0x65, 0x48, 0x8B, 0x35, 0x08, 0x00, 0x00, 0x00, 0xF4],
RIP_GS + 0x1010,
),
];
for (code, fault) in cases {
let expected = ExitReason::MemoryFault(MemoryError::UnmappedAddress(fault));
let (mut engine, mut cpu, mut memory) = fixture(code);
cpu.fs_base = RIP_FS;
cpu.gs_base = RIP_GS;
let native = engine.run(&mut cpu, &mut memory, 16);
assert_eq!(
native.exit_reason, expected,
"native DBT, fault at {fault:#x}"
);
let (_, mut cpu, mut memory) = fixture(code);
cpu.fs_base = RIP_FS;
cpu.gs_base = RIP_GS;
let interpreted = crate::cpu::Interpreter::new(cpu, &mut memory, 16).run();
assert_eq!(
interpreted.exit_reason, expected,
"interpreter, fault at {fault:#x}"
);
}
}
/// Both execution paths must agree when an instruction carries an FS and
/// a GS override together.
///
/// The Intel SDM states that "the effect of redundant prefixes (more than
/// one prefix from a group) is undefined", and FS and GS are in the same
/// prefix group. The architecture therefore does not define which base
/// applies, so this test pins the local rule instead: both paths prefer
/// GS, and they must agree with each other.
///
/// The encoding is `mov [fs:0x8], rbx` preceded by a GS override
/// (65 64 48 89 1C 25 08 00 00 00).
#[test]
fn redundant_fs_and_gs_overrides_are_handled_the_same_by_both_paths() {
const CODE: [u8; 11] = [
0x65, 0x64, 0x48, 0x89, 0x1C, 0x25, 0x08, 0x00, 0x00, 0x00, // mov [fs:0x8], rbx
0xF4, // hlt
];
const FS_BASE: u64 = 0x7000;
const GS_BASE: u64 = 0x8000;
const STORED_VALUE: u64 = 0x1122_3344_5566_7788;
let (mut engine, mut cpu, mut memory) = fixture(&CODE);
cpu.fs_base = FS_BASE;
cpu.gs_base = GS_BASE;
cpu.set(Register::Rbx, STORED_VALUE);
memory
.map_region(FS_BASE, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
memory
.map_region(GS_BASE, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
let native = engine.run(&mut cpu, &mut memory, 16);
assert_eq!(native.exit_reason, ExitReason::Halt);
let mut memory = GuestMemory::new();
memory
.map_region_with_data(ENTRY, CODE.len(), MemoryPermissions::READ_EXECUTE, &CODE)
.unwrap();
memory
.map_region(FS_BASE, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
memory
.map_region(GS_BASE, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
let mut cpu = CpuState::new(ENTRY, 0);
cpu.fs_base = FS_BASE;
cpu.gs_base = GS_BASE;
cpu.set(Register::Rbx, STORED_VALUE);
let mut interp = crate::cpu::Interpreter::new(cpu, &mut memory, 16);
let interpreted = interp.run();
assert_eq!(interpreted.exit_reason, native.exit_reason);
assert_eq!(interpreted.final_state, native.final_state);
// The local rule prefers GS, so the store landed at the GS base.
assert_eq!(memory.read_u64(GS_BASE + 8).unwrap(), STORED_VALUE);
assert_eq!(memory.read_u64(FS_BASE + 8).unwrap(), 0);
}
/// The GS segment override adds the GS base, and distinct FS and GS bases
/// must not be confused with each other.
///
/// The encodings are `mov [gs:0x8], rbx` (65 48 89 1C 25 08 00 00 00)
/// and `mov rdx, [gs:0x8]` (65 48 8B 14 25 08 00 00 00), as produced by
/// LLVM 23.1.6 `llvm-mc -show-encoding`.
#[test]
fn gs_segment_override_adds_the_gs_base_to_the_address() {
let code = [
0x65, 0x48, 0x89, 0x1C, 0x25, 0x08, 0x00, 0x00, 0x00, // mov [gs:0x8], rbx
0x65, 0x48, 0x8B, 0x14, 0x25, 0x08, 0x00, 0x00, 0x00, // mov rdx, [gs:0x8]
0xF4, // hlt
];
let (mut engine, mut cpu, mut memory) = fixture(&code);
const FS_BASE: u64 = 0x7000;
const GS_BASE: u64 = 0x8000;
const STORED_VALUE: u64 = 0x1122_3344_5566_7788;
cpu.fs_base = FS_BASE;
cpu.gs_base = GS_BASE;
cpu.set(Register::Rbx, STORED_VALUE);
memory
.map_region(FS_BASE, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
memory
.map_region(GS_BASE, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
let result = engine.run(&mut cpu, &mut memory, 16);
assert_eq!(result.exit_reason, ExitReason::Halt);
assert_eq!(memory.read_u64(GS_BASE + 8).unwrap(), STORED_VALUE);
// The FS base must be untouched.
assert_eq!(memory.read_u64(FS_BASE + 8).unwrap(), 0);
assert_eq!(result.final_state.get(Register::Rdx), STORED_VALUE);
}
/// A segment-relative access to an unmapped address must fault, and the
/// fault must report the segment-adjusted address.
///
/// The encoding is `mov [fs:0x8], rbx` (64 48 89 1C 25 08 00 00 00).
/// The FS base points outside every mapped region, so the store faults at
/// `FS_BASE + 8`.
#[test]
fn segment_relative_access_to_an_unmapped_address_faults() {
let code = [
0x64, 0x48, 0x89, 0x1C, 0x25, 0x08, 0x00, 0x00, 0x00, // mov [fs:0x8], rbx
0xF4, // hlt
];
let (mut engine, mut cpu, mut memory) = fixture(&code);
const FS_BASE: u64 = 0x7000;
cpu.fs_base = FS_BASE;
cpu.set(Register::Rbx, 0x1122_3344_5566_7788);
// No region is mapped at FS_BASE, so the segment-adjusted address
// FS_BASE + 8 is unmapped.
let result = engine.run(&mut cpu, &mut memory, 16);
assert_eq!(
result.exit_reason,
ExitReason::MemoryFault(MemoryError::UnmappedAddress(FS_BASE + 8))
);
}
}
+241 -1
View File
@@ -117,6 +117,11 @@ pub enum GraphicsError {
DeviceCreationFailure(String),
BackendError(String),
NativeMetalRequired,
/// An index buffer format other than DXGI `R16_UINT` (57) or `R32_UINT` (42).
InvalidIndexFormat(u32),
/// An indexed draw reads past its index buffer or fetches a vertex,
/// after applying the base vertex, outside its vertex buffer.
IndexOutOfRange,
}
impl std::fmt::Display for GraphicsError {
@@ -140,6 +145,10 @@ impl std::fmt::Display for GraphicsError {
f,
"native Metal backend required but not provided or failed"
),
Self::InvalidIndexFormat(format) => {
write!(f, "unsupported index buffer format {format}")
}
Self::IndexOutOfRange => write!(f, "indexed draw outside its index or vertex buffer"),
}
}
}
@@ -173,6 +182,32 @@ pub struct GraphicsResource {
pub data: Vec<u8>,
}
/// Index size of an index buffer view, as `D3D12_INDEX_BUFFER_VIEW::Format`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum IndexFormat {
R16Uint,
R32Uint,
}
impl IndexFormat {
/// The format for a DXGI format code: `R16_UINT` (57) or `R32_UINT` (42).
pub const fn from_dxgi(format: u32) -> Option<Self> {
match format {
57 => Some(Self::R16Uint),
42 => Some(Self::R32Uint),
_ => None,
}
}
/// Bytes per index.
pub const fn size(self) -> usize {
match self {
Self::R16Uint => 2,
Self::R32Uint => 4,
}
}
}
/// Primitive Draw Command recorded in a Command List.
#[derive(Clone, Debug)]
pub enum GraphicsCommand {
@@ -200,6 +235,18 @@ pub enum GraphicsCommand {
start_vertex_location: u32,
start_instance_location: u32,
},
SetIndexBuffer {
resource: GraphicsHandle,
offset: usize,
format: IndexFormat,
},
DrawIndexedInstanced {
index_count_per_instance: u32,
instance_count: u32,
start_index_location: u32,
base_vertex_location: i32,
start_instance_location: u32,
},
}
/// Command List in recording or closed state.
@@ -548,6 +595,72 @@ impl GraphicsContext {
Ok(())
}
/// Record set index buffer. `format` is a DXGI format code; only
/// `R16_UINT` (57) and `R32_UINT` (42) are index formats.
pub fn cmd_set_index_buffer(
&mut self,
list: GraphicsHandle,
resource: GraphicsHandle,
offset: usize,
format: u32,
) -> Result<(), GraphicsError> {
let cmd_list = self
.command_lists
.get_mut(&list)
.ok_or(GraphicsError::InvalidCommandListHandle)?;
if !cmd_list.is_recording {
return Err(GraphicsError::CommandListNotRecording);
}
let format =
IndexFormat::from_dxgi(format).ok_or(GraphicsError::InvalidIndexFormat(format))?;
let res = self
.resources
.get(&resource)
.ok_or(GraphicsError::InvalidResourceHandle)?;
if !offset.is_multiple_of(format.size()) || offset > res.data.len() {
return Err(GraphicsError::InvalidDescriptor);
}
cmd_list.commands.push(GraphicsCommand::SetIndexBuffer {
resource,
offset,
format,
});
Ok(())
}
/// Record draw indexed instanced. Each draw renders one triangle once: at
/// execution the index count must be 0 or 3, the instance count 0 or 1 and
/// the start instance 0, or the draw is rejected; a zero index or instance
/// count draws nothing. Index values are ordinary triangle-list indices
/// (no primitive restart), range checked after adding the base vertex.
pub fn cmd_draw_indexed_instanced(
&mut self,
list: GraphicsHandle,
index_count_per_instance: u32,
instance_count: u32,
start_index_location: u32,
base_vertex_location: i32,
start_instance_location: u32,
) -> Result<(), GraphicsError> {
let cmd_list = self
.command_lists
.get_mut(&list)
.ok_or(GraphicsError::InvalidCommandListHandle)?;
if !cmd_list.is_recording {
return Err(GraphicsError::CommandListNotRecording);
}
cmd_list
.commands
.push(GraphicsCommand::DrawIndexedInstanced {
index_count_per_instance,
instance_count,
start_index_location,
base_vertex_location,
start_instance_location,
});
Ok(())
}
/// Close command list.
pub fn close_command_list(&mut self, list: GraphicsHandle) -> Result<(), GraphicsError> {
let cmd_list = self
@@ -649,6 +762,8 @@ impl GraphicsContext {
let mut target_handle: Option<GraphicsHandle> = None;
let mut vertex_resource: Option<GraphicsHandle> = None;
let mut vertex_offset = 0usize;
let mut vertex_stride = 0usize;
let mut index_buffer: Option<(GraphicsHandle, usize, IndexFormat)> = None;
let mut rendered_output: Option<Vec<u8>> = None;
let mut draw_count = 0usize;
@@ -679,10 +794,57 @@ impl GraphicsContext {
viewport = (*width, *height);
}
GraphicsCommand::SetVertexBuffer {
resource, offset, ..
resource,
offset,
stride,
} => {
vertex_resource = Some(*resource);
vertex_offset = *offset;
vertex_stride = *stride;
}
GraphicsCommand::SetIndexBuffer {
resource,
offset,
format,
} => index_buffer = Some((*resource, *offset, *format)),
GraphicsCommand::DrawIndexedInstanced {
index_count_per_instance,
instance_count,
start_index_location,
base_vertex_location,
start_instance_location,
} => {
if !matches!(index_count_per_instance, 0 | 3)
|| *instance_count > 1
|| *start_instance_location != 0
{
return Err(GraphicsError::InvalidDescriptor);
}
if *index_count_per_instance == 0 || *instance_count == 0 {
continue;
}
let vertices = self.fetch_indexed_triangle(
memory,
index_buffer,
(vertex_resource, vertex_offset, vertex_stride),
*start_index_location,
*base_vertex_location,
)?;
draw_count += 1;
let pixels = if let Some(renderer) = backend_renderer {
renderer(&vertices, viewport, clear_color)?
} else if backend_id == GraphicsBackendId::MetalNative {
return Err(GraphicsError::NativeMetalRequired);
} else {
Self::execute_software_reference_draw(&vertices, viewport, clear_color)?
};
if let Some(th) = target_handle
&& let Some(target_res) = self.resources.get_mut(&th)
&& target_res.data.len() >= pixels.len()
{
target_res.data[..pixels.len()].copy_from_slice(&pixels);
}
rendered_output = Some(pixels);
}
GraphicsCommand::DrawInstanced {
vertex_count_per_instance,
@@ -761,6 +923,84 @@ impl GraphicsContext {
})
}
/// The three float4 positions one indexed triangle fetches: index `k` is
/// read at `offset + (start + k) * size` of the index buffer, and vertex
/// `index + base_vertex` at `offset + vertex * stride` of the vertex buffer.
fn fetch_indexed_triangle(
&self,
memory: &GuestMemory,
index_buffer: Option<(GraphicsHandle, usize, IndexFormat)>,
(vertex_resource, vertex_offset, vertex_stride): (Option<GraphicsHandle>, usize, usize),
start: u32,
base_vertex: i32,
) -> Result<[[f32; 4]; 3], GraphicsError> {
let resource = |handle: Option<GraphicsHandle>| {
handle
.and_then(|handle| self.resources.get(&handle))
.ok_or(GraphicsError::InvalidResourceHandle)
};
let (index_handle, index_offset, format) =
index_buffer.ok_or(GraphicsError::InvalidResourceHandle)?;
let index_res = resource(Some(index_handle))?;
let vertex_res = resource(vertex_resource)?;
if vertex_stride < 16 {
return Err(GraphicsError::InvalidDescriptor);
}
let size = format.size();
let mut raw_indices = [0u8; 12];
let raw_indices = &mut raw_indices[..3 * size];
let first = (start as usize)
.checked_mul(size)
.and_then(|bytes| bytes.checked_add(index_offset))
.ok_or(GraphicsError::IndexOutOfRange)?;
Self::read_resource(index_res, memory, first, raw_indices)?;
let mut vertices = [[0.0f32; 4]; 3];
for (row, index) in vertices.iter_mut().zip(raw_indices.chunks_exact(size)) {
let index = if size == 2 {
u32::from(u16::from_le_bytes([index[0], index[1]]))
} else {
u32::from_le_bytes(index.try_into().unwrap())
};
let vertex = usize::try_from(i64::from(index) + i64::from(base_vertex))
.map_err(|_| GraphicsError::IndexOutOfRange)?;
let at = vertex
.checked_mul(vertex_stride)
.and_then(|bytes| bytes.checked_add(vertex_offset))
.ok_or(GraphicsError::IndexOutOfRange)?;
let mut raw = [0u8; 16];
Self::read_resource(vertex_res, memory, at, &mut raw)?;
for (value, bytes) in row.iter_mut().zip(raw.as_chunks::<4>().0) {
*value = f32::from_le_bytes(*bytes);
}
}
Ok(vertices)
}
/// Read `out.len()` bytes at `offset` of a resource, from its guest backing
/// when it has one. The range must lie inside the resource's size.
fn read_resource(
res: &GraphicsResource,
memory: &GuestMemory,
offset: usize,
out: &mut [u8],
) -> Result<(), GraphicsError> {
let end = offset
.checked_add(out.len())
.filter(|&end| end <= res.data.len())
.ok_or(GraphicsError::IndexOutOfRange)?;
match res.guest_backing_addr {
Some(guest_addr) => {
let address = guest_addr
.checked_add(offset as u64)
.filter(|address| address.checked_add(out.len() as u64).is_some())
.ok_or(GraphicsError::IndexOutOfRange)?;
memory.read_bytes(address, out)?;
}
None => out.copy_from_slice(&res.data[offset..end]),
}
Ok(())
}
/// Software reference rasterizer for deterministic test verification when GPU tests are off.
pub fn execute_software_reference_draw(
vertices: &[[f32; 4]; 3],
+89 -6
View File
@@ -47,8 +47,8 @@ unsafe impl Sync for JitMemory {}
impl JitMemory {
/// Allocate a new JIT memory region using `MAP_JIT`.
pub fn new(capacity: usize) -> Result<Self, JitError> {
let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize };
let aligned_capacity = (capacity + page_size - 1) & !(page_size - 1);
let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
let aligned_capacity = aligned_capacity(capacity, page_size)?;
let ptr = unsafe {
libc::mmap(
@@ -98,10 +98,7 @@ impl JitMemory {
/// Automatically manages `pthread_jit_write_protect_np`, copies bytes,
/// flushes data cache and invalidates instruction cache.
pub fn emit_block(&mut self, instructions: &[u32]) -> Result<*const u8, JitError> {
let bytes_len = instructions.len() * 4;
if self.used + bytes_len > self.capacity {
return Err(JitError::CapacityExceeded);
}
let bytes_len = emit_len(self.used, instructions.len(), self.capacity)?;
let emit_offset = self.used;
let dst_ptr = unsafe { self.ptr.as_ptr().add(emit_offset) };
@@ -131,6 +128,27 @@ impl JitMemory {
}
}
/// Round `capacity` up to a whole number of pages, rejecting an invalid page size
/// (`sysconf` failure, zero or not a power of two) and arithmetic overflow.
fn aligned_capacity(capacity: usize, page_size: libc::c_long) -> Result<usize, JitError> {
let page_size = usize::try_from(page_size)
.ok()
.filter(|p| p.is_power_of_two())
.ok_or(JitError::AllocationFailed(libc::EINVAL))?;
capacity
.checked_add(page_size - 1)
.map(|c| c & !(page_size - 1))
.ok_or(JitError::CapacityExceeded)
}
/// Byte length of `count` 4-byte instructions, if they fit after `used` bytes.
fn emit_len(used: usize, count: usize, capacity: usize) -> Result<usize, JitError> {
count
.checked_mul(4)
.filter(|len| used.checked_add(*len).is_some_and(|end| end <= capacity))
.ok_or(JitError::CapacityExceeded)
}
impl Drop for JitMemory {
fn drop(&mut self) {
unsafe {
@@ -138,3 +156,68 @@ impl Drop for JitMemory {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn capacity_rounds_up_to_whole_pages() {
assert_eq!(aligned_capacity(1, 16384), Ok(16384));
assert_eq!(aligned_capacity(16384, 16384), Ok(16384));
assert_eq!(aligned_capacity(16385, 16384), Ok(32768));
assert_eq!(aligned_capacity(0, 4096), Ok(0));
}
#[test]
fn invalid_page_size_is_rejected() {
for page in [-1, 0, 3, 12288] {
assert_eq!(
aligned_capacity(4096, page),
Err(JitError::AllocationFailed(libc::EINVAL)),
"page size {page}"
);
}
}
#[test]
fn capacity_rounding_overflow_is_rejected() {
assert_eq!(
aligned_capacity(usize::MAX, 16384),
Err(JitError::CapacityExceeded)
);
assert_eq!(
aligned_capacity(usize::MAX - 16382, 16384),
Err(JitError::CapacityExceeded)
);
}
#[test]
fn emit_length_is_checked() {
assert_eq!(emit_len(0, 4, 16), Ok(16));
assert_eq!(emit_len(4, 3, 16), Ok(12));
assert_eq!(emit_len(4, 4, 16), Err(JitError::CapacityExceeded));
// count * 4 overflows usize.
assert_eq!(
emit_len(0, usize::MAX / 2, usize::MAX),
Err(JitError::CapacityExceeded)
);
// used + len overflows usize.
assert_eq!(
emit_len(usize::MAX - 3, 2, usize::MAX),
Err(JitError::CapacityExceeded)
);
}
#[test]
fn emit_past_capacity_fails_and_leaves_usage_unchanged() {
let mut jit = JitMemory::new(1).expect("MAP_JIT allocation");
let words = jit.capacity() / 4;
assert!(jit.emit_block(&vec![0xD503_201F; words]).is_ok()); // NOP fills the page
assert_eq!(
jit.emit_block(&[0xD503_201F]),
Err(JitError::CapacityExceeded)
);
assert_eq!(jit.used(), jit.capacity());
}
}
+90 -66
View File
@@ -226,57 +226,102 @@ impl GuestMemory {
true
}
/// Write raw bytes into guest memory at the specified address, checking permissions.
pub fn write_bytes(&mut self, address: u64, src: &[u8]) -> Result<(), MemoryError> {
for region in &mut self.regions {
if region.contains(address, src.len()) {
if !region.permissions.write {
return Err(MemoryError::PermissionViolation {
address,
required: "write",
});
}
let offset = (address - region.base) as usize;
region.data[offset..offset + src.len()].copy_from_slice(src);
return Ok(());
/// Resolve `[address, address + len)` to `(region index, offset, length)` pieces.
///
/// An access may span adjacent regions, as it would span adjacent pages, but every
/// byte must be mapped and every region must grant `required` (`None` bypasses
/// permission checks for the loader). The whole range is checked before any byte
/// is copied, so a failed access never partially reads or writes.
fn resolve(
&self,
address: u64,
len: usize,
required: Option<&'static str>,
) -> Result<Vec<(usize, usize, usize)>, MemoryError> {
let end = address
.checked_add(len as u64)
.ok_or(MemoryError::Overflow)?;
if len == 0 {
return if self.regions.iter().any(|r| r.contains(address, 0)) {
Ok(Vec::new())
} else {
Err(MemoryError::UnmappedAddress(address))
};
}
let mut pieces = Vec::new();
let mut cursor = address;
for (index, region) in self.regions.iter().enumerate() {
let region_end = region.base + region.data.len() as u64;
if region_end <= cursor {
continue;
}
if region.base > cursor {
break;
}
let permitted = match required {
None => true,
Some("read") => region.permissions.read,
Some("write") => region.permissions.write,
Some(_) => region.permissions.execute,
};
if let (false, Some(required)) = (permitted, required) {
return Err(MemoryError::PermissionViolation { address, required });
}
let take = (end.min(region_end) - cursor) as usize;
pieces.push((index, (cursor - region.base) as usize, take));
cursor += take as u64;
if cursor == end {
return Ok(pieces);
}
}
Err(MemoryError::UnmappedAddress(address))
}
fn read_checked(
&self,
address: u64,
dst: &mut [u8],
required: Option<&'static str>,
) -> Result<(), MemoryError> {
let mut done = 0;
for (index, offset, take) in self.resolve(address, dst.len(), required)? {
dst[done..done + take]
.copy_from_slice(&self.regions[index].data[offset..offset + take]);
done += take;
}
Ok(())
}
fn write_checked(
&mut self,
address: u64,
src: &[u8],
required: Option<&'static str>,
) -> Result<(), MemoryError> {
let mut done = 0;
for (index, offset, take) in self.resolve(address, src.len(), required)? {
self.regions[index].data[offset..offset + take]
.copy_from_slice(&src[done..done + take]);
done += take;
}
Ok(())
}
/// Write raw bytes into guest memory at the specified address, checking permissions.
pub fn write_bytes(&mut self, address: u64, src: &[u8]) -> Result<(), MemoryError> {
self.write_checked(address, src, Some("write"))
}
/// Read raw bytes from guest memory at the specified address, checking permissions.
pub fn read_bytes(&self, address: u64, dst: &mut [u8]) -> Result<(), MemoryError> {
for region in &self.regions {
if region.contains(address, dst.len()) {
if !region.permissions.read {
return Err(MemoryError::PermissionViolation {
address,
required: "read",
});
}
let offset = (address - region.base) as usize;
dst.copy_from_slice(&region.data[offset..offset + dst.len()]);
return Ok(());
}
}
Err(MemoryError::UnmappedAddress(address))
self.read_checked(address, dst, Some("read"))
}
/// Read an instruction byte from guest memory, verifying execute permission.
pub fn fetch_instruction_byte(&self, address: u64) -> Result<u8, MemoryError> {
for region in &self.regions {
if region.contains(address, 1) {
if !region.permissions.execute {
return Err(MemoryError::PermissionViolation {
address,
required: "execute",
});
}
let offset = (address - region.base) as usize;
return Ok(region.data[offset]);
}
}
Err(MemoryError::UnmappedAddress(address))
let mut buf = [0u8; 1];
self.read_checked(address, &mut buf, Some("execute"))?;
Ok(buf[0])
}
/// Read a 64-bit integer (little endian) from guest memory.
@@ -288,14 +333,9 @@ impl GuestMemory {
/// Read a 64-bit integer ignoring region read permissions (e.g. loader/relocation phase).
pub fn read_u64_bypass(&self, address: u64) -> Result<u64, MemoryError> {
for region in &self.regions {
if region.contains(address, 8) {
let offset = (address - region.base) as usize;
let buf: [u8; 8] = region.data[offset..offset + 8].try_into().unwrap();
return Ok(u64::from_le_bytes(buf));
}
}
Err(MemoryError::UnmappedAddress(address))
let mut buf = [0u8; 8];
self.read_checked(address, &mut buf, None)?;
Ok(u64::from_le_bytes(buf))
}
/// Write a 64-bit integer (little endian) to guest memory.
@@ -305,15 +345,7 @@ impl GuestMemory {
/// Write a 64-bit integer ignoring region write permissions (e.g. loader/relocation phase).
pub fn write_u64_bypass(&mut self, address: u64, value: u64) -> Result<(), MemoryError> {
let bytes = value.to_le_bytes();
for region in &mut self.regions {
if region.contains(address, 8) {
let offset = (address - region.base) as usize;
region.data[offset..offset + 8].copy_from_slice(&bytes);
return Ok(());
}
}
Err(MemoryError::UnmappedAddress(address))
self.write_checked(address, &value.to_le_bytes(), None)
}
/// Read a 32-bit integer (little endian) from guest memory.
@@ -330,15 +362,7 @@ impl GuestMemory {
/// Write a 32-bit integer ignoring region write permissions (e.g. loader/relocation phase).
pub fn write_u32_bypass(&mut self, address: u64, value: u32) -> Result<(), MemoryError> {
let bytes = value.to_le_bytes();
for region in &mut self.regions {
if region.contains(address, 4) {
let offset = (address - region.base) as usize;
region.data[offset..offset + 4].copy_from_slice(&bytes);
return Ok(());
}
}
Err(MemoryError::UnmappedAddress(address))
self.write_checked(address, &value.to_le_bytes(), None)
}
/// Read a single byte from guest memory.
+108 -51
View File
@@ -91,6 +91,20 @@ pub const IMAGE_SCN_MEM_WRITE: u32 = 0x80000000;
// Standard Constants
pub const IMAGE_FILE_MACHINE_AMD64: u16 = 0x8664;
pub const PE32_PLUS_MAGIC: u16 = 0x020B;
/// PE32+ optional header length up to and including NumberOfRvaAndSizes.
const PE32_PLUS_MIN_OPTIONAL_HEADER: usize = 112;
const SECTION_HEADER_SIZE: usize = 40;
/// Host memory budget for all mapped sections of one image. This is a loader policy
/// limit, not a property of the PE format.
const MAX_MAPPED_IMAGE_BYTES: u64 = 256 * 1024 * 1024;
fn read_u16(bytes: &[u8], at: usize) -> u16 {
u16::from_le_bytes([bytes[at], bytes[at + 1]])
}
fn read_u32(bytes: &[u8], at: usize) -> u32 {
u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap())
}
impl ParsedPe {
/// Parse PE32+ headers from an in-memory byte slice.
@@ -105,80 +119,85 @@ impl ParsedPe {
}
let e_lfanew = u32::from_le_bytes(bytes[0x3C..0x40].try_into().unwrap()) as usize;
if bytes.len() < e_lfanew + 24 {
let coff_offset = e_lfanew.checked_add(4).ok_or(PeError::TooSmall)?;
if bytes.len() < coff_offset.checked_add(20).ok_or(PeError::TooSmall)? {
return Err(PeError::TooSmall);
}
// 2. PE Signature
if &bytes[e_lfanew..e_lfanew + 4] != b"PE\0\0" {
if &bytes[e_lfanew..coff_offset] != b"PE\0\0" {
return Err(PeError::InvalidPeSignature);
}
// 3. COFF File Header
let coff_offset = e_lfanew + 4;
let machine = u16::from_le_bytes(bytes[coff_offset..coff_offset + 2].try_into().unwrap());
let machine = read_u16(bytes, coff_offset);
if machine != IMAGE_FILE_MACHINE_AMD64 {
return Err(PeError::UnsupportedMachine(machine));
}
let number_of_sections = read_u16(bytes, coff_offset + 2);
let time_date_stamp = read_u32(bytes, coff_offset + 4);
let size_of_optional_header = usize::from(read_u16(bytes, coff_offset + 16));
let number_of_sections =
u16::from_le_bytes(bytes[coff_offset + 2..coff_offset + 4].try_into().unwrap());
let time_date_stamp =
u32::from_le_bytes(bytes[coff_offset + 4..coff_offset + 8].try_into().unwrap());
let size_of_optional_header = u16::from_le_bytes(
bytes[coff_offset + 16..coff_offset + 18]
.try_into()
.unwrap(),
) as usize;
// 4. Optional Header (PE32+ is required)
// 4. Optional Header (PE32+ is required). The fixed PE32+ fields end at
// NumberOfRvaAndSizes (offset 108, 4 bytes); a shorter header is malformed.
let opt_offset = coff_offset + 20;
if bytes.len() < opt_offset + size_of_optional_header {
let section_table_offset = opt_offset + size_of_optional_header;
if bytes.len() < opt_offset + 2 {
return Err(PeError::TooSmall);
}
let magic = u16::from_le_bytes(bytes[opt_offset..opt_offset + 2].try_into().unwrap());
let magic = read_u16(bytes, opt_offset);
if magic != PE32_PLUS_MAGIC {
return Err(PeError::InvalidMagic(magic));
}
if size_of_optional_header < PE32_PLUS_MIN_OPTIONAL_HEADER
|| bytes.len() < section_table_offset
{
return Err(PeError::TooSmall);
}
let entry_point_rva =
u32::from_le_bytes(bytes[opt_offset + 16..opt_offset + 20].try_into().unwrap());
let entry_point_rva = read_u32(bytes, opt_offset + 16);
let image_base =
u64::from_le_bytes(bytes[opt_offset + 24..opt_offset + 32].try_into().unwrap());
let section_alignment =
u32::from_le_bytes(bytes[opt_offset + 32..opt_offset + 36].try_into().unwrap());
let file_alignment =
u32::from_le_bytes(bytes[opt_offset + 36..opt_offset + 40].try_into().unwrap());
let size_of_image =
u32::from_le_bytes(bytes[opt_offset + 56..opt_offset + 60].try_into().unwrap());
let size_of_headers =
u32::from_le_bytes(bytes[opt_offset + 60..opt_offset + 64].try_into().unwrap());
let section_alignment = read_u32(bytes, opt_offset + 32);
let file_alignment = read_u32(bytes, opt_offset + 36);
let size_of_image = read_u32(bytes, opt_offset + 56);
let size_of_headers = read_u32(bytes, opt_offset + 60);
// 5. Section Headers
let mut sections = Vec::with_capacity(number_of_sections as usize);
let section_table_offset = opt_offset + size_of_optional_header;
let section_header_size = 40;
if bytes.len() < section_table_offset + (number_of_sections as usize * section_header_size)
{
let table_end = usize::from(number_of_sections)
.checked_mul(SECTION_HEADER_SIZE)
.and_then(|len| section_table_offset.checked_add(len))
.ok_or(PeError::InvalidSectionHeaders)?;
if bytes.len() < table_end {
return Err(PeError::InvalidSectionHeaders);
}
for i in 0..number_of_sections as usize {
let offset = section_table_offset + i * section_header_size;
let sec_bytes = &bytes[offset..offset + section_header_size];
let mut sections = Vec::with_capacity(usize::from(number_of_sections));
for sec_bytes in bytes[section_table_offset..table_end]
.as_chunks::<SECTION_HEADER_SIZE>()
.0
{
// Section name (up to 8 bytes UTF-8 or null-padded ASCII)
let name_raw = &sec_bytes[0..8];
let name_len = name_raw.iter().position(|&b| b == 0).unwrap_or(8);
let name = String::from_utf8_lossy(&name_raw[..name_len]).into_owned();
let virtual_size = u32::from_le_bytes(sec_bytes[8..12].try_into().unwrap());
let virtual_address = u32::from_le_bytes(sec_bytes[12..16].try_into().unwrap());
let raw_data_size = u32::from_le_bytes(sec_bytes[16..20].try_into().unwrap());
let raw_data_ptr = u32::from_le_bytes(sec_bytes[20..24].try_into().unwrap());
let characteristics = u32::from_le_bytes(sec_bytes[36..40].try_into().unwrap());
let virtual_size = read_u32(sec_bytes, 8);
let virtual_address = read_u32(sec_bytes, 12);
let raw_data_size = read_u32(sec_bytes, 16);
let raw_data_ptr = read_u32(sec_bytes, 20);
let characteristics = read_u32(sec_bytes, 36);
// The mapped range must fit in the 32-bit RVA space, and raw data must be in the file.
virtual_address
.checked_add(virtual_size.max(raw_data_size))
.ok_or(PeError::InvalidSectionHeaders)?;
if raw_data_size > 0 {
let raw_end = u64::from(raw_data_ptr) + u64::from(raw_data_size);
if raw_end > bytes.len() as u64 {
return Err(PeError::InvalidSectionHeaders);
}
}
let permissions = MemoryPermissions {
read: (characteristics & IMAGE_SCN_MEM_READ) != 0,
@@ -197,6 +216,32 @@ impl ParsedPe {
});
}
// Mapped section ranges must not overlap. Zero-sized sections map nothing.
let mut ranges: Vec<(u32, u32)> = sections
.iter()
.map(|s| {
(
s.virtual_address,
s.virtual_address + s.virtual_size.max(s.raw_data_size),
)
})
.filter(|(start, end)| start < end)
.collect();
ranges.sort_unstable();
if ranges.windows(2).any(|w| w[1].0 < w[0].1) {
return Err(PeError::InvalidSectionHeaders);
}
// The entry point must lie inside an executable section.
let entry_ok = sections.iter().any(|s| {
s.permissions.execute
&& entry_point_rva >= s.virtual_address
&& entry_point_rva - s.virtual_address < s.virtual_size.max(s.raw_data_size)
});
if !entry_ok {
return Err(PeError::InvalidEntryPoint);
}
Ok(ParsedPe {
machine,
number_of_sections,
@@ -214,13 +259,12 @@ impl ParsedPe {
/// Translate a Relative Virtual Address (RVA) to a raw file offset.
pub fn rva_to_file_offset(&self, rva: u32) -> Option<usize> {
for sec in &self.sections {
let start = sec.virtual_address;
let size = std::cmp::max(sec.virtual_size, sec.raw_data_size);
if rva >= start && rva < start + size {
let diff = (rva - start) as usize;
if diff < sec.raw_data_size as usize {
return Some(sec.raw_data_ptr as usize + diff);
}
// Sections are public and may not come from `parse`, so stay checked here.
let Some(diff) = rva.checked_sub(sec.virtual_address) else {
continue;
};
if diff < sec.virtual_size.max(sec.raw_data_size) && diff < sec.raw_data_size {
return (sec.raw_data_ptr as usize).checked_add(diff as usize);
}
}
None
@@ -232,6 +276,17 @@ impl ParsedPe {
}
pub(crate) fn load_at_base(&self, bytes: &[u8], base: u64) -> Result<LoadedImage, PeError> {
// Each section becomes a zero-filled host allocation, so bound the total before
// allocating anything. Sections may not overlap, so the sum is the mapped size.
let mapped: u64 = self
.sections
.iter()
.map(|sec| u64::from(sec.virtual_size.max(sec.raw_data_size)))
.sum();
if mapped > MAX_MAPPED_IMAGE_BYTES {
return Err(PeError::SectionMappingError(MemoryError::AllocationFailed));
}
let mut memory = GuestMemory::new();
for sec in &self.sections {
@@ -245,7 +300,9 @@ impl ParsedPe {
let initial_data = if sec.raw_data_size > 0 && sec.raw_data_ptr > 0 {
let start = sec.raw_data_ptr as usize;
let end = start + sec.raw_data_size as usize;
let end = start
.checked_add(sec.raw_data_size as usize)
.ok_or(PeError::InvalidSectionHeaders)?;
bytes
.get(start..end)
.ok_or(PeError::InvalidSectionHeaders)?
+33 -5
View File
@@ -117,7 +117,10 @@ pub fn apply_relocations(
size: reloc_size,
})?;
if reloc_file_offset + (reloc_size as usize) > bytes.len() {
if reloc_file_offset
.checked_add(reloc_size as usize)
.is_none_or(|end| end > bytes.len())
{
return Err(RelocationError::DirectoryOutOfBounds {
rva: reloc_rva,
size: reloc_size,
@@ -127,13 +130,20 @@ pub fn apply_relocations(
let mut read_bytes = 0usize;
let max_read = reloc_size as usize;
while read_bytes + 8 <= max_read {
while read_bytes < max_read {
// A partial block header after the last block is malformed, not padding.
if max_read - read_bytes < 8 {
return Err(RelocationError::MalformedBlockHeader {
offset: reloc_file_offset + read_bytes,
});
}
let block_start = reloc_file_offset + read_bytes;
let page_rva = u32::from_le_bytes(bytes[block_start..block_start + 4].try_into().unwrap());
let block_size =
u32::from_le_bytes(bytes[block_start + 4..block_start + 8].try_into().unwrap());
if block_size < 8 {
// A block is an 8-byte header followed by whole 2-byte entries.
if block_size < 8 || block_size % 2 != 0 {
return Err(RelocationError::MalformedBlockHeader {
offset: block_start,
});
@@ -166,6 +176,15 @@ pub fn apply_relocations(
let target_rva = page_rva
.checked_add(offset_in_page)
.ok_or(RelocationError::ArithmeticOverflow)?;
// The 8-byte target must lie inside the image, not in other mapped memory.
if target_rva
.checked_add(8)
.is_none_or(|end| end > pe.size_of_image)
{
return Err(RelocationError::TargetOutOfBounds {
target_va: loaded_base.wrapping_add(u64::from(target_rva)),
});
}
let target_va = loaded_base
.checked_add(target_rva as u64)
.ok_or(RelocationError::ArithmeticOverflow)?;
@@ -213,8 +232,8 @@ fn find_reloc_directory(
return Ok(None);
}
let e_lfanew = u32::from_le_bytes(bytes[0x3C..0x40].try_into().unwrap()) as usize;
let opt_offset = e_lfanew + 24;
let coff_offset = e_lfanew + 4;
let opt_offset = coff_offset + 20;
if bytes.len() < coff_offset + 18 {
return Ok(None);
}
@@ -224,10 +243,19 @@ fn find_reloc_directory(
.unwrap(),
) as usize;
// Relocation directory is directory index 5 (offset 112 + 5 * 8 = 152 in Optional Header)
// Relocation directory is directory index 5 (offset 112 + 5 * 8 = 152 in Optional Header).
// It exists only when NumberOfRvaAndSizes (offset 108) covers index 5.
if size_of_opt < 160 || bytes.len() < opt_offset + 160 {
return Ok(None);
}
let number_of_rva_and_sizes = u32::from_le_bytes(
bytes[opt_offset + 108..opt_offset + 112]
.try_into()
.unwrap(),
);
if number_of_rva_and_sizes < 6 {
return Ok(None);
}
let reloc_rva = u32::from_le_bytes(
bytes[opt_offset + 152..opt_offset + 156]
+136 -16
View File
@@ -11,6 +11,14 @@ use crate::{
const STACK_SIZE: usize = 64 * 1024;
const JIT_CAPACITY: usize = 1024 * 1024;
/// The TEB is placed this far above the TLS base and spans two 4 KiB pages.
const TEB_OFFSET: u64 = 0x10000;
const TEB_SIZE: usize = 0x2000;
// Win64 TEB fields (NT_TIB prefix plus the TLS slot) written by the harness.
const TEB_STACK_BASE: u64 = 0x08;
const TEB_STACK_LIMIT: u64 = 0x10;
const TEB_SELF: u64 = 0x30;
const TEB_TLS_POINTER: u64 = 0x58;
/// Guest addresses reserved by the fixture harness.
pub struct StartupLayout {
@@ -79,6 +87,8 @@ pub fn run_synthetic_startup_with_observer(
)
.into());
}
// Reject an impossible layout before parsing or mapping anything.
let (stack_base, teb_base) = layout_regions(&layout)?;
let pe = ParsedPe::parse(bytes)?;
observe(StartupEvent::Parsed {
sections: pe.sections.len(),
@@ -112,24 +122,9 @@ pub fn run_synthetic_startup_with_observer(
)?;
}
let stack_base = layout
.stack_top
.checked_sub(STACK_SIZE as u64)
.ok_or(MemoryError::Overflow)?;
memory.map_region(stack_base, STACK_SIZE, MemoryPermissions::READ_WRITE)?;
// Allocate and initialize Win64 TEB (Thread Environment Block)
// Layout in TEB:
// +0x08: StackBase (highest address)
// +0x10: StackLimit (lowest address)
// +0x30: Self pointer (TEB linear address)
// +0x58: ThreadLocalStoragePointer
let teb_base = layout.tls_base.saturating_add(0x10000);
memory.map_region(teb_base, 0x2000, MemoryPermissions::READ_WRITE)?;
memory.write_u64_bypass(teb_base + 0x08, layout.stack_top)?;
memory.write_u64_bypass(teb_base + 0x10, stack_base)?;
memory.write_u64_bypass(teb_base + 0x30, teb_base)?;
memory.write_u64_bypass(teb_base + 0x58, layout.tls_base)?;
map_teb(memory, teb_base, &layout, stack_base)?;
let mut engine = DbtEngine::new(JIT_CAPACITY)?;
engine.set_import_registry(imports);
@@ -171,3 +166,128 @@ pub fn run_synthetic_startup_with_observer(
dbt_metrics: engine.metrics,
})
}
/// Validate the harness layout and return `(stack_base, teb_base)`.
///
/// The stack occupies `[stack_top - STACK_SIZE, stack_top)` and the TEB
/// `[tls_base + TEB_OFFSET, + TEB_SIZE)`. Both ranges must fit in the address
/// space and must not overlap each other.
fn layout_regions(layout: &StartupLayout) -> Result<(u64, u64), MemoryError> {
let stack_base = layout
.stack_top
.checked_sub(STACK_SIZE as u64)
.ok_or(MemoryError::Overflow)?;
let teb_base = layout
.tls_base
.checked_add(TEB_OFFSET)
.ok_or(MemoryError::Overflow)?;
let teb_end = teb_base
.checked_add(TEB_SIZE as u64)
.ok_or(MemoryError::Overflow)?;
if teb_base < layout.stack_top && stack_base < teb_end {
return Err(MemoryError::OverlappingRegion {
base: teb_base,
size: TEB_SIZE as u64,
});
}
Ok((stack_base, teb_base))
}
/// Map the Win64 TEB and write the fields the harness provides.
fn map_teb(
memory: &mut crate::GuestMemory,
teb_base: u64,
layout: &StartupLayout,
stack_base: u64,
) -> Result<(), MemoryError> {
memory.map_region(teb_base, TEB_SIZE, MemoryPermissions::READ_WRITE)?;
memory.write_u64_bypass(teb_base + TEB_STACK_BASE, layout.stack_top)?;
memory.write_u64_bypass(teb_base + TEB_STACK_LIMIT, stack_base)?;
memory.write_u64_bypass(teb_base + TEB_SELF, teb_base)?;
memory.write_u64_bypass(teb_base + TEB_TLS_POINTER, layout.tls_base)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::GuestMemory;
fn layout(stack_top: u64, tls_base: u64) -> StartupLayout {
StartupLayout {
image_base: 0x1_4000_0000,
stack_top,
tls_base,
}
}
#[test]
fn valid_layout_places_stack_and_teb() {
let regions = layout_regions(&layout(0x2_0001_0000, 0x3_0000_0000));
assert_eq!(regions, Ok((0x2_0000_0000, 0x3_0001_0000)));
}
#[test]
fn stack_below_zero_is_rejected() {
assert_eq!(
layout_regions(&layout(0x8000, 0x3_0000_0000)),
Err(MemoryError::Overflow)
);
}
#[test]
fn teb_address_overflow_is_rejected_not_saturated() {
for tls_base in [u64::MAX, u64::MAX - 0xFFFF, u64::MAX - TEB_OFFSET - 0x1FFF] {
assert_eq!(
layout_regions(&layout(0x2_0001_0000, tls_base)),
Err(MemoryError::Overflow),
"tls_base {tls_base:#x}"
);
}
// The highest TEB that fits ends at u64::MAX: an end of 2^64 is not
// representable, and GuestMemory could not map that range either.
let top = u64::MAX - TEB_OFFSET - TEB_SIZE as u64;
assert!(layout_regions(&layout(0x2_0001_0000, top)).is_ok());
}
#[test]
fn teb_overlapping_stack_is_rejected() {
// TEB at 0x2_0000_8000..0x2_0000_A000 lies inside the stack 0x2_0000_0000..0x2_0001_0000.
let collide = layout(0x2_0001_0000, 0x1_FFFF_8000);
assert!(matches!(
layout_regions(&collide),
Err(MemoryError::OverlappingRegion { .. })
));
// Directly above the stack is fine.
assert!(layout_regions(&layout(0x2_0001_0000, 0x2_0000_0000)).is_ok());
}
#[test]
fn invalid_layout_fails_before_parsing() {
// Empty bytes would fail PE parsing; the layout error must come first.
let err = run_synthetic_startup(
&[],
layout(0x2_0001_0000, u64::MAX),
ImportRegistry::new(),
1,
)
.err()
.expect("startup must fail");
assert_eq!(
err.downcast_ref::<MemoryError>(),
Some(&MemoryError::Overflow)
);
}
#[test]
fn teb_fields_are_at_win64_offsets() {
let l = layout(0x2_0001_0000, 0x3_0000_0000);
let (stack_base, teb) = layout_regions(&l).unwrap();
let mut memory = GuestMemory::new();
map_teb(&mut memory, teb, &l, stack_base).unwrap();
assert_eq!(memory.read_u64(teb + 0x08), Ok(0x2_0001_0000));
assert_eq!(memory.read_u64(teb + 0x10), Ok(0x2_0000_0000));
assert_eq!(memory.read_u64(teb + 0x30), Ok(teb));
assert_eq!(memory.read_u64(teb + 0x58), Ok(0x3_0000_0000));
assert!(memory.read_u8(teb + TEB_SIZE as u64).is_err());
}
}
+421 -1
View File
@@ -3,7 +3,7 @@
//! End-to-end integration tests for Xenora X12: PE32+ loading & x86-64 execution bootstrap.
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, Register};
use xenora_loader::memory::{MemoryError, MemoryPermissions};
use xenora_loader::memory::{GuestMemory, MemoryError, MemoryPermissions};
use xenora_loader::pe::{
IMAGE_FILE_MACHINE_AMD64, IMAGE_SCN_MEM_EXECUTE, IMAGE_SCN_MEM_READ, PE32_PLUS_MAGIC, ParsedPe,
};
@@ -289,3 +289,423 @@ fn test_sib_addressing_mode() {
assert_eq!(result.exit_reason, ExitReason::Halt);
assert_eq!(result.final_state.get(Register::Rdx), 0x12345678_9abcdef0);
}
/// Base address of the read-write data region used by the SIB tests.
const DATA_BASE: u64 = 0x6000_0000;
/// Base address of the read-write stack region used by the SIB tests.
const STACK_BASE: u64 = 0x5000_0000;
/// Run `code` on the interpreter with a writable stack and a writable data
/// region, and return the final state, the exit reason and the guest memory.
///
/// `DATA_BASE` is mapped read-write so a test can observe where a store
/// landed. `STACK_BASE` holds the stack pointer.
fn run_with_regions(code: &[u8]) -> (CpuState, ExitReason, GuestMemory) {
let pe_bytes = build_synthetic_pe32_plus(code);
let parsed = ParsedPe::parse(&pe_bytes).expect("parse");
let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load");
loaded
.memory
.map_region(STACK_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("stack mapping should succeed");
loaded
.memory
.map_region(DATA_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("data mapping should succeed");
let cpu = CpuState::new(loaded.entry_point, STACK_BASE + 0x8000);
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 100);
let result = interp.run();
(result.final_state, result.exit_reason, loaded.memory)
}
/// `mov rax, DATA_BASE` (48 B8 <imm64>).
fn mov_rax_data_base() -> Vec<u8> {
let mut code = vec![0x48, 0xB8];
code.extend_from_slice(&DATA_BASE.to_le_bytes());
code
}
/// `mov rbx, 0x12345678_9abcdef0` (48 BB <imm64>).
fn mov_rbx_value() -> Vec<u8> {
let mut code = vec![0x48, 0xBB];
code.extend_from_slice(&0x1234_5678_9abc_def0u64.to_le_bytes());
code
}
/// A SIB index register is extended by REX.X, not by REX.R.
///
/// The encoding 4A 89 1C E0 is `mov [rax + r12*8], rbx`. Its REX prefix sets
/// REX.X, so the SIB index field 100b selects r12 and the store lands at
/// `rax + r12*8`. REX.R is clear in this prefix, so the ModRM `reg` field is
/// rbx.
#[test]
fn test_rex_x_extends_the_sib_index_register() {
// mov rax, DATA_BASE (48 b8 <imm64>)
// mov r12, 4 (41 bc 04 00 00 00)
// mov rbx, 0x12345678_9abcdef0 (48 bb <imm64>)
// mov [rax + r12*8], rbx (4a 89 1c e0)
// hlt (f4)
let mut code = mov_rax_data_base();
code.extend_from_slice(&[0x41, 0xBC, 0x04, 0x00, 0x00, 0x00]); // mov r12d, 4
code.extend_from_slice(&mov_rbx_value());
code.extend_from_slice(&[0x4A, 0x89, 0x1C, 0xE0]); // mov [rax + r12*8], rbx
code.push(0xF4); // hlt
let (_state, reason, memory) = run_with_regions(&code);
assert_eq!(reason, ExitReason::Halt);
// r12 holds 4, so the store lands at DATA_BASE + 4*8.
assert_eq!(
memory.read_u64(DATA_BASE + 32).expect("indexed slot"),
0x1234_5678_9abc_def0
);
// The unindexed slot at DATA_BASE must be untouched.
assert_eq!(memory.read_u64(DATA_BASE).expect("base slot"), 0);
}
/// REX.R and REX.X extend independent fields in the same instruction.
///
/// The encoding 4C 89 1C C8 is `mov [rax + rcx*8], r11`. Its REX prefix sets
/// REX.R, so the ModRM `reg` field 011 selects r11. It does not set REX.X, so
/// the SIB index field 001 selects rcx and must not be extended to r9.
#[test]
fn test_rex_r_does_not_extend_the_sib_index_register() {
// mov rax, DATA_BASE (48 b8 <imm64>)
// mov r11, 0x11223344_55667788 (49 bb <imm64>)
// mov ecx, 4 (b9 04 00 00 00)
// mov r9, 8 (41 b9 08 00 00 00)
// mov [rax + rcx*8], r11 (4c 89 1c c8)
// hlt (f4)
let mut code = mov_rax_data_base();
let mut r11 = vec![0x49, 0xBB];
r11.extend_from_slice(&0x1122_3344_5566_7788u64.to_le_bytes());
code.extend_from_slice(&r11);
code.extend_from_slice(&[0xB9, 0x04, 0x00, 0x00, 0x00]); // mov ecx, 4
code.extend_from_slice(&[0x41, 0xB9, 0x08, 0x00, 0x00, 0x00]); // mov r9d, 8
code.extend_from_slice(&[0x4C, 0x89, 0x1C, 0xC8]); // mov [rax + rcx*8], r11
code.push(0xF4); // hlt
let (_state, reason, memory) = run_with_regions(&code);
assert_eq!(reason, ExitReason::Halt);
// rcx holds 4, so the store lands at DATA_BASE + 4*8. A wrongly extended
// index would have selected r9 and landed at DATA_BASE + 8*8.
assert_eq!(
memory.read_u64(DATA_BASE + 32).expect("indexed slot"),
0x1122_3344_5566_7788
);
assert_eq!(memory.read_u64(DATA_BASE + 64).expect("r9 slot"), 0);
}
/// REX.R and REX.X set together extend their own fields independently.
///
/// The encoding 4E 89 1C E0 is `mov [rax + r12*8], r11`. Its REX prefix sets
/// both REX.R and REX.X: the ModRM `reg` field 011 becomes r11 and the SIB
/// index field 100b becomes r12.
#[test]
fn test_rex_r_and_rex_x_set_together_extend_independent_fields() {
// mov rax, DATA_BASE (48 b8 <imm64>)
// mov r11, 0x11223344_55667788 (49 bb <imm64>)
// mov r12, 4 (41 bc 04 00 00 00)
// mov [rax + r12*8], r11 (4e 89 1c e0)
// hlt (f4)
let mut code = mov_rax_data_base();
let mut r11 = vec![0x49, 0xBB];
r11.extend_from_slice(&0x1122_3344_5566_7788u64.to_le_bytes());
code.extend_from_slice(&r11);
code.extend_from_slice(&[0x41, 0xBC, 0x04, 0x00, 0x00, 0x00]); // mov r12d, 4
code.extend_from_slice(&[0x4E, 0x89, 0x1C, 0xE0]); // mov [rax + r12*8], r11
code.push(0xF4); // hlt
let (_state, reason, memory) = run_with_regions(&code);
assert_eq!(reason, ExitReason::Halt);
assert_eq!(
memory.read_u64(DATA_BASE + 32).expect("indexed slot"),
0x1122_3344_5566_7788
);
assert_eq!(memory.read_u64(DATA_BASE).expect("base slot"), 0);
}
/// Without REX.X, a SIB index field of 100b means "no index register" and the
/// address is the base alone.
///
/// The encoding 48 89 1C 24 is `mov [rsp], rbx`: the SIB index field is 100b
/// and REX.X is clear, so no index register contributes to the address.
#[test]
fn test_sib_index_field_100b_without_rex_x_means_no_index() {
// mov rbx, 0x12345678_9abcdef0 (48 bb <imm64>)
// mov r12, 0x1000 (41 bc 00 10 00 00)
// mov [rsp], rbx (48 89 1c 24)
// hlt (f4)
let mut code = mov_rbx_value();
code.extend_from_slice(&[0x41, 0xBC, 0x00, 0x10, 0x00, 0x00]); // mov r12d, 0x1000
code.extend_from_slice(&[0x48, 0x89, 0x1C, 0x24]); // mov [rsp], rbx
code.push(0xF4); // hlt
let pe_bytes = build_synthetic_pe32_plus(&code);
let parsed = ParsedPe::parse(&pe_bytes).expect("parse");
let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load");
loaded
.memory
.map_region(STACK_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("stack mapping should succeed");
let cpu = CpuState::new(loaded.entry_point, STACK_BASE + 0x8000);
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 100);
let result = interp.run();
assert_eq!(result.exit_reason, ExitReason::Halt);
// The index is absent, so the address is the base (rsp) alone.
let stack_top = STACK_BASE + 0x8000;
assert_eq!(
loaded.memory.read_u64(stack_top).expect("base slot"),
0x1234_5678_9abc_def0
);
}
/// Build a guest program that loads `value` into `rdi` and then runs `body`.
///
/// `mov rdi, imm64` is 48 BF <imm64>.
fn program_with_rdi(value: u64, body: &[u8]) -> Vec<u8> {
let mut code = vec![0x48, 0xBF];
code.extend_from_slice(&value.to_le_bytes());
code.extend_from_slice(body);
code.push(0xF4); // hlt
code
}
/// Run `code` on the interpreter and return the final state and exit reason.
fn run_interpreter(code: &[u8]) -> (CpuState, ExitReason) {
let pe_bytes = build_synthetic_pe32_plus(code);
let parsed = ParsedPe::parse(&pe_bytes).expect("parse");
let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load");
loaded
.memory
.map_region(STACK_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("stack mapping should succeed");
loaded
.memory
.map_region(DATA_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("data mapping should succeed");
let cpu = CpuState::new(loaded.entry_point, STACK_BASE + 0x8000);
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 100);
let result = interp.run();
(result.final_state, result.exit_reason)
}
/// MOVZX with a register source, for both destination widths.
///
/// The encodings are `movzbl eax, bl` (0F B6 C3) and
/// `movzbq rdx, bl` (48 0F B6 D3), as produced by LLVM 23.1.6
/// `llvm-mc -show-encoding`. A zero extension always produces a zero-extended
/// value, so the 32-bit form clears the upper half of rax while the 64-bit
/// form produces the same 64-bit value.
#[test]
fn test_movzx_register_source_zero_extends() {
// mov rbx, 0xffffffffffffffff (48 BB <imm64>)
let mut code = vec![0x48, 0xBB];
code.extend_from_slice(&u64::MAX.to_le_bytes());
code.extend_from_slice(&[0x0F, 0xB6, 0xC3]); // movzbl eax, bl
code.extend_from_slice(&[0x48, 0x0F, 0xB6, 0xD3]); // movzbq rdx, bl
code.push(0xF4); // hlt
let (state, reason) = run_interpreter(&code);
assert_eq!(reason, ExitReason::Halt);
// The 32-bit destination holds a zero-extended byte: 0x00000000000000ff.
assert_eq!(state.get(Register::Rax), 0x0000_0000_0000_00ff);
// The 64-bit destination holds the same zero-extended value.
assert_eq!(state.get(Register::Rdx), 0x0000_0000_0000_00ff);
}
/// MOVSX with a register source, for both destination widths.
///
/// The encodings are `movsbl eax, bl` (0F BE C3) and
/// `movsbq rdx, bl` (48 0F BE D3), as produced by LLVM 23.1.6
/// `llvm-mc -show-encoding`. A sign extension reaches the destination width,
/// so the 32-bit form keeps the sign in bits 31:0 and clears the upper half,
/// while the 64-bit form sign-extends across all 64 bits.
#[test]
fn test_movsx_register_source_sign_extends_to_the_destination_width() {
// mov rbx, 0xffffffffffffffff (48 BB <imm64>)
let mut code = vec![0x48, 0xBB];
code.extend_from_slice(&u64::MAX.to_le_bytes());
code.extend_from_slice(&[0x0F, 0xBE, 0xC3]); // movsbl eax, bl
code.extend_from_slice(&[0x48, 0x0F, 0xBE, 0xD3]); // movsbq rdx, bl
code.push(0xF4); // hlt
let (state, reason) = run_interpreter(&code);
assert_eq!(reason, ExitReason::Halt);
// The 32-bit destination holds 0xffffffff and its upper half is cleared.
assert_eq!(state.get(Register::Rax), 0x0000_0000_ffff_ffff);
// The 64-bit destination keeps the sign extension across all 64 bits.
assert_eq!(state.get(Register::Rdx), 0xffff_ffff_ffff_ffff);
}
/// MOVSX from a 16-bit source sign-extends to the destination width.
///
/// The encodings are `movswl eax, bx` (0F BF C3) and
/// `movswq rdx, bx` (48 0F BF D3), as produced by LLVM 23.1.6
/// `llvm-mc -show-encoding`.
#[test]
fn test_movsx_word_register_source_sign_extends() {
// mov rbx, 0xffffffffffffffff (48 BB <imm64>)
let mut code = vec![0x48, 0xBB];
code.extend_from_slice(&u64::MAX.to_le_bytes());
code.extend_from_slice(&[0x0F, 0xBF, 0xC3]); // movswl eax, bx
code.extend_from_slice(&[0x48, 0x0F, 0xBF, 0xD3]); // movswq rdx, bx
code.push(0xF4); // hlt
let (state, reason) = run_interpreter(&code);
assert_eq!(reason, ExitReason::Halt);
assert_eq!(state.get(Register::Rax), 0x0000_0000_ffff_ffff);
assert_eq!(state.get(Register::Rdx), 0xffff_ffff_ffff_ffff);
}
/// MOVZX with a memory source reads only the low byte of the operand.
///
/// The encodings are `movzbl eax, byte [rdi]` (0F B6 07) and
/// `movzbq rdx, byte [rdi]` (48 0F B6 17), as produced by LLVM 23.1.6
/// `llvm-mc -show-encoding`.
#[test]
fn test_movzx_memory_source_reads_one_byte() {
// mov rdi, DATA_BASE (48 BF <imm64>)
// movzbl eax, byte [rdi] (0F B6 07)
// movzbq rdx, byte [rdi] (48 0F B6 17)
let code = program_with_rdi(DATA_BASE, &[0x0F, 0xB6, 0x07, 0x48, 0x0F, 0xB6, 0x17]);
let pe_bytes = build_synthetic_pe32_plus(&code);
let parsed = ParsedPe::parse(&pe_bytes).expect("parse");
let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load");
loaded
.memory
.map_region(STACK_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("stack mapping should succeed");
loaded
.memory
.map_region(DATA_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("data mapping should succeed");
// The byte at the source address has the high bit set, so a sign
// extension would produce a negative value and a zero extension must not.
loaded
.memory
.write_u8(DATA_BASE, 0xFF)
.expect("source byte");
let cpu = CpuState::new(loaded.entry_point, STACK_BASE + 0x8000);
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 100);
let result = interp.run();
assert_eq!(result.exit_reason, ExitReason::Halt);
assert_eq!(result.final_state.get(Register::Rax), 0x0000_0000_0000_00ff);
assert_eq!(result.final_state.get(Register::Rdx), 0x0000_0000_0000_00ff);
}
/// MOVSX with a memory source sign-extends the byte that was read.
///
/// The encodings are `movsbl eax, byte [rdi]` (0F BE 07) and
/// `movsbq rdx, byte [rdi]` (48 0F BE 17), as produced by LLVM 23.1.6
/// `llvm-mc -show-encoding`.
#[test]
fn test_movsx_memory_source_sign_extends() {
// mov rdi, DATA_BASE (48 BF <imm64>)
// movsbl eax, byte [rdi] (0F BE 07)
// movsbq rdx, byte [rdi] (48 0F BE 17)
let code = program_with_rdi(DATA_BASE, &[0x0F, 0xBE, 0x07, 0x48, 0x0F, 0xBE, 0x17]);
let pe_bytes = build_synthetic_pe32_plus(&code);
let parsed = ParsedPe::parse(&pe_bytes).expect("parse");
let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load");
loaded
.memory
.map_region(STACK_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("stack mapping should succeed");
loaded
.memory
.map_region(DATA_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("data mapping should succeed");
loaded
.memory
.write_u8(DATA_BASE, 0xFF)
.expect("source byte");
let cpu = CpuState::new(loaded.entry_point, STACK_BASE + 0x8000);
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 100);
let result = interp.run();
assert_eq!(result.exit_reason, ExitReason::Halt);
// The 32-bit destination holds 0xffffffff with the upper half cleared.
assert_eq!(result.final_state.get(Register::Rax), 0x0000_0000_ffff_ffff);
// The 64-bit destination keeps the sign extension across all 64 bits.
assert_eq!(result.final_state.get(Register::Rdx), 0xffff_ffff_ffff_ffff);
}
/// The interpreter must implement the same extension opcodes as the native
/// DBT translator.
///
/// The program exercises all four opcodes with both a register and a memory
/// source, and both destination widths:
///
/// - `movzbl eax, bl` (0F B6 C3), `movzbq rdx, bl` (48 0F B6 D3)
/// - `movswl eax, bx` (0F BF C3), `movswq rdx, bx` (48 0F BF D3)
/// - `movzbl eax, byte [rdi]` (0F B6 07), `movzbq rdx, byte [rdi]`
/// (48 0F B6 17)
/// - `movsbl eax, byte [rdi]` (0F BE 07), `movsbq rdx, byte [rdi]`
/// (48 0F BE 17)
///
/// All encodings were produced by LLVM 23.1.6 `llvm-mc -show-encoding`.
///
/// The expected values follow the Intel SDM rules for MOVZX and MOVSX: MOVZX
/// always zero-extends, and MOVSX sign-extends to the destination width, so a
/// 32-bit destination keeps the sign in bits 31:0 and clears the upper half
/// while a 64-bit destination keeps the sign extension across all 64 bits.
#[test]
fn test_interpreter_implements_the_extension_opcodes() {
let code = program_with_rdi(
DATA_BASE,
&[
0x0F, 0xB6, 0xC3, // movzbl eax, bl
0x48, 0x0F, 0xB6, 0xD3, // movzbq rdx, bl
0x0F, 0xBF, 0xC3, // movswl eax, bx
0x48, 0x0F, 0xBF, 0xD3, // movswq rdx, bx
0x0F, 0xB6, 0x07, // movzbl eax, byte [rdi]
0x48, 0x0F, 0xB6, 0x17, // movzbq rdx, byte [rdi]
0x0F, 0xBE, 0x07, // movsbl eax, byte [rdi]
0x48, 0x0F, 0xBE, 0x17, // movsbq rdx, byte [rdi]
],
);
let pe_bytes = build_synthetic_pe32_plus(&code);
let parsed = ParsedPe::parse(&pe_bytes).expect("parse");
let mut loaded = parsed.load_into_memory(&pe_bytes).expect("load");
loaded
.memory
.map_region(STACK_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("stack mapping should succeed");
loaded
.memory
.map_region(DATA_BASE, 0x10000, MemoryPermissions::READ_WRITE)
.expect("data mapping should succeed");
// The bytes at the source address have the high bit set and clear, so a
// sign extension and a zero extension give different results.
loaded
.memory
.write_u8(DATA_BASE, 0xFF)
.expect("source byte");
loaded
.memory
.write_u8(DATA_BASE + 1, 0x7F)
.expect("source byte");
let mut cpu = CpuState::new(loaded.entry_point, STACK_BASE + 0x8000);
// rbx and rsi hold the register-source values.
cpu.set(Register::Rbx, u64::MAX);
cpu.set(Register::Rsi, 0x0000_0000_0000_7FFF);
let mut interp = Interpreter::new(cpu, &mut loaded.memory, 100);
let result = interp.run();
assert_eq!(result.exit_reason, ExitReason::Halt);
// The last write to rax is the 32-bit sign extension of the byte 0xFF.
assert_eq!(result.final_state.get(Register::Rax), 0x0000_0000_ffff_ffff);
// The last write to rdx is the 64-bit sign extension of the same byte.
assert_eq!(result.final_state.get(Register::Rdx), 0xffff_ffff_ffff_ffff);
}
+78
View File
@@ -0,0 +1,78 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, RFlags};
use xenora_loader::dbt::DbtEngine;
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
fn check_bswap(native: bool) {
const ENTRY: u64 = 0x1000;
const INPUT: u64 = 0x1122_3344_5566_7788;
for reg in 0_u8..16 {
for width in [16, 32, 64] {
let wide = width == 64;
let mut code = Vec::new();
if width == 16 {
code.push(0x66);
}
let rex = 0x40 | (u8::from(wide) << 3) | (reg >> 3);
if rex != 0x40 {
code.push(rex);
}
code.extend([0x0f, 0xc8 + (reg & 7)]);
let mut memory = GuestMemory::new();
memory
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, &code)
.unwrap();
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr.fill(0xdead_beef);
cpu.gpr[reg as usize] = INPUT;
cpu.flags = RFlags {
cf: wide,
zf: !wide,
sf: wide,
of: !wide,
};
let flags = cpu.flags;
let mut expected = cpu.gpr;
let result = if native {
DbtEngine::new(16 * 1024)
.unwrap()
.run(&mut cpu, &mut memory, 1)
} else {
Interpreter::new(cpu, &mut memory, 1).run()
};
if width == 16 {
assert!(matches!(
result.exit_reason,
ExitReason::IllegalInstruction(_)
));
assert_eq!(result.instructions_executed, 0);
} else {
assert_eq!(
result.exit_reason,
ExitReason::StepLimitExceeded,
"{code:02x?}"
);
assert_eq!(result.instructions_executed, 1);
assert_eq!(result.final_state.rip, ENTRY + code.len() as u64);
expected[reg as usize] = if wide {
0x8877_6655_4433_2211
} else {
0x8877_6655
};
}
assert_eq!(result.final_state.gpr, expected);
assert_eq!(result.final_state.flags, flags);
}
}
}
#[test]
fn interpreter_bswap() {
check_bswap(false);
}
#[test]
fn native_bswap() {
check_bswap(true);
}
+411
View File
@@ -590,3 +590,414 @@ fn test_guest_dbt_graphics_pipeline_metal_render_dual_inputs() {
let expected_clear = [10, 20, 30, 255];
assert_eq!(pixels2, expected_clear.repeat(12));
}
/// Guest addresses of the indexed-draw fixtures.
const INDEXED_VB: u64 = 0x7000_0000;
const INDEXED_IB: u64 = 0x7100_0000;
/// Vertex stride of the indexed fixtures: a float4 position and 16 unused bytes.
const INDEXED_STRIDE: usize = 32;
/// Triangle (4,3) (16,4) (6,16) of a 16x16 target in clip space; no pixel
/// centre lies on one of its edges.
const INDEXED_TRIANGLE: [[f32; 4]; 3] = [
[-0.5, 0.625, 0.5, 1.0],
[1.0, 0.5, 0.5, 1.0],
[-0.25, -1.0, 0.5, 1.0],
];
/// Ten vertices: the triangle at vertices 5, 7 and 2, and decoys elsewhere,
/// so a wrong fetch passes different positions.
fn indexed_vertices() -> Vec<u8> {
let mut bytes = Vec::new();
for vertex in 0..10 {
let position = match vertex {
5 => INDEXED_TRIANGLE[0],
7 => INDEXED_TRIANGLE[1],
2 => INDEXED_TRIANGLE[2],
other => [other as f32 * 0.125 - 0.75, -0.5, 0.5, 1.0],
};
for value in position {
bytes.extend(value.to_le_bytes());
}
bytes.extend([0xAB; 16]);
}
bytes
}
struct IndexedRig {
ctx: GraphicsContext,
memory: GuestMemory,
queue: GraphicsHandle,
alloc: GraphicsHandle,
list: GraphicsHandle,
vb: GraphicsHandle,
ib16: GraphicsHandle,
ib32: GraphicsHandle,
}
/// A context with guest-backed vertex and index buffers. The 16-bit buffer
/// holds 9, 9, 6, 8, 3, 5, 0 and the 32-bit buffer 9, 3, 5, 0, 7 and three
/// indices above 16 bits, 0x10003, 0x10005, 0x10000.
fn indexed_rig() -> IndexedRig {
use xenora_loader::memory::MemoryPermissions;
let mut ctx = GraphicsContext::new();
let device = ctx.create_device().unwrap();
let queue = ctx
.create_command_queue(device, CommandListType::Direct)
.unwrap();
let alloc = ctx
.create_command_allocator(device, CommandListType::Direct)
.unwrap();
let list = ctx
.create_command_list(device, alloc, CommandListType::Direct)
.unwrap();
let buffer = |ctx: &mut GraphicsContext, bytes: usize, addr| {
let desc = ResourceDesc {
dimension: ResourceDimension::Buffer,
width: bytes as u64,
height: 1,
depth_or_array_size: 1,
mip_levels: 1,
format_rgba8: false,
};
ctx.create_committed_resource(device, desc, ResourceStates::COMMON, Some(addr))
.unwrap()
};
let vertices = indexed_vertices();
let ib16: Vec<u8> = [9u16, 9, 6, 8, 3, 5, 0]
.iter()
.flat_map(|index| index.to_le_bytes())
.collect();
let ib32: Vec<u8> = [9u32, 3, 5, 0, 7, 0x1_0003, 0x1_0005, 0x1_0000]
.iter()
.flat_map(|index| index.to_le_bytes())
.collect();
let vb = buffer(&mut ctx, vertices.len(), INDEXED_VB);
let ib16_handle = buffer(&mut ctx, ib16.len(), INDEXED_IB);
let ib32_handle = buffer(&mut ctx, ib32.len(), INDEXED_IB + 0x1000);
let mut memory = GuestMemory::new();
for (addr, bytes) in [
(INDEXED_VB, &vertices),
(INDEXED_IB, &ib16),
(INDEXED_IB + 0x1000, &ib32),
] {
memory
.map_region_with_data(addr, 0x1000, MemoryPermissions::READ_ONLY, bytes)
.unwrap();
}
IndexedRig {
ctx,
memory,
queue,
alloc,
list,
vb,
ib16: ib16_handle,
ib32: ib32_handle,
}
}
/// Record one indexed draw (16x16 viewport, the rig's vertex buffer) and run it.
fn run_indexed(
rig: &mut IndexedRig,
index_buffer: (GraphicsHandle, usize, u32),
draw: (u32, u32, u32, i32),
) -> Result<xenora_loader::graphics::ExecutionOutcome, GraphicsError> {
let ctx = &mut rig.ctx;
ctx.reset_command_list(rig.list, rig.alloc)?;
ctx.cmd_set_viewport(rig.list, 16, 16)?;
ctx.cmd_set_vertex_buffer(rig.list, rig.vb, 0, INDEXED_STRIDE)?;
ctx.cmd_set_index_buffer(rig.list, index_buffer.0, index_buffer.1, index_buffer.2)?;
let (count, instances, start, base) = draw;
ctx.cmd_draw_indexed_instanced(rig.list, count, instances, start, base, 0)?;
ctx.close_command_list(rig.list)?;
ctx.execute_command_list(rig.queue, rig.list, &rig.memory)
}
const R16_UINT: u32 = 57;
const R32_UINT: u32 = 42;
/// Start index, signed base vertex, index size and buffer offset all select
/// vertices 5, 7, 2: the backend receives exactly the triangle's positions
/// (literal values), never a decoy.
#[test]
fn test_d3d12_indexed_draw_fetches_start_and_base_vertex() {
let mut rig = indexed_rig();
let seen = Arc::new(std::sync::Mutex::new(Vec::new()));
let record = seen.clone();
rig.ctx.set_metal_backend(move |vtx, viewport, clear| {
record.lock().unwrap().push(*vtx);
GraphicsContext::execute_software_reference_draw(vtx, viewport, clear)
});
let (ib16, ib32) = (rig.ib16, rig.ib32);
for (name, buffer, draw) in [
// 16-bit indices 3, 5, 0 at index 4, base vertex +2.
("u16 positive base", (ib16, 0, R16_UINT), (3, 1, 4, 2)),
// 16-bit indices 6, 8, 3 at index 2, base vertex -1.
("u16 negative base", (ib16, 0, R16_UINT), (3, 1, 2, -1)),
// The same through a buffer offset of one index (2 bytes).
("u16 buffer offset", (ib16, 2, R16_UINT), (3, 1, 1, -1)),
// 32-bit indices 3, 5, 0 at index 1, base vertex +2.
("u32 positive base", (ib32, 0, R32_UINT), (3, 1, 1, 2)),
// 32-bit indices above 16 bits, base vertex -65534: all 32 bits count.
("u32 wide indices", (ib32, 0, R32_UINT), (3, 1, 5, -65534)),
] {
seen.lock().unwrap().clear();
let outcome = run_indexed(&mut rig, buffer, draw).expect(name);
assert_eq!(outcome.draw_count, 1, "{name}");
assert_eq!(*seen.lock().unwrap(), vec![INDEXED_TRIANGLE], "{name}");
assert_eq!(
outcome.pixels,
GraphicsContext::execute_software_reference_draw(
&INDEXED_TRIANGLE,
(16, 16),
[0, 0, 0, 255]
)
.unwrap(),
"{name}"
);
}
// A vertex buffer offset of two vertices does the base vertex's work.
seen.lock().unwrap().clear();
let ctx = &mut rig.ctx;
ctx.reset_command_list(rig.list, rig.alloc).unwrap();
ctx.cmd_set_viewport(rig.list, 16, 16).unwrap();
ctx.cmd_set_vertex_buffer(rig.list, rig.vb, 2 * INDEXED_STRIDE, INDEXED_STRIDE)
.unwrap();
ctx.cmd_set_index_buffer(rig.list, ib16, 0, R16_UINT)
.unwrap();
ctx.cmd_draw_indexed_instanced(rig.list, 3, 1, 4, 0, 0)
.unwrap();
ctx.close_command_list(rig.list).unwrap();
let outcome = ctx
.execute_command_list(rig.queue, rig.list, &rig.memory)
.expect("vertex buffer offset");
assert_eq!(outcome.draw_count, 1);
assert_eq!(*seen.lock().unwrap(), vec![INDEXED_TRIANGLE]);
// Zero indices or zero instances draw nothing and never call the backend.
seen.lock().unwrap().clear();
for draw in [(0, 1, 0, 0), (3, 0, 0, 0)] {
let outcome = run_indexed(&mut rig, (ib16, 0, R16_UINT), draw).unwrap();
assert_eq!(outcome.draw_count, 0);
}
assert!(seen.lock().unwrap().is_empty());
}
/// Index format, offset, count, range, negative fetch and unknown or missing
/// buffers each fail with a typed error, and nothing reaches the backend.
#[test]
fn test_d3d12_indexed_draw_errors() {
let mut rig = indexed_rig();
let calls = Arc::new(std::sync::Mutex::new(0usize));
let counter = calls.clone();
rig.ctx.set_metal_backend(move |vtx, viewport, clear| {
*counter.lock().unwrap() += 1;
GraphicsContext::execute_software_reference_draw(vtx, viewport, clear)
});
let (ib16, ib32) = (rig.ib16, rig.ib32);
let unknown = GraphicsHandle {
id: 999,
generation: 1,
};
for format in [0, 41, 56, 58, 28] {
assert_eq!(
run_indexed(&mut rig, (ib16, 0, format), (3, 1, 0, 0)).unwrap_err(),
GraphicsError::InvalidIndexFormat(format)
);
}
for (name, buffer, draw, error) in [
(
"misaligned offset",
(ib32, 2, R32_UINT),
(3, 1, 0, 0),
GraphicsError::InvalidDescriptor,
),
(
"offset past buffer",
(ib16, 16, R16_UINT),
(3, 1, 0, 0),
GraphicsError::InvalidDescriptor,
),
(
"unknown buffer",
(unknown, 0, R16_UINT),
(3, 1, 0, 0),
GraphicsError::InvalidResourceHandle,
),
(
"count not one triangle",
(ib16, 0, R16_UINT),
(6, 1, 0, 0),
GraphicsError::InvalidDescriptor,
),
(
"bad count with zero instances",
(ib16, 0, R16_UINT),
(6, 0, 0, 0),
GraphicsError::InvalidDescriptor,
),
(
"two instances",
(ib16, 0, R16_UINT),
(3, 2, 4, 2),
GraphicsError::InvalidDescriptor,
),
(
"indices past buffer",
(ib16, 0, R16_UINT),
(3, 1, 5, 0),
GraphicsError::IndexOutOfRange,
),
(
"start overflow",
(ib32, 0, R32_UINT),
(3, 1, u32::MAX, 0),
GraphicsError::IndexOutOfRange,
),
(
"negative vertex",
(ib16, 0, R16_UINT),
(3, 1, 4, -1),
GraphicsError::IndexOutOfRange,
),
(
"vertex past buffer",
(ib16, 0, R16_UINT),
(3, 1, 0, 1),
GraphicsError::IndexOutOfRange,
),
(
"base overflow",
(ib32, 0, R32_UINT),
(3, 1, 0, i32::MAX),
GraphicsError::IndexOutOfRange,
),
] {
let got = run_indexed(&mut rig, buffer, draw);
assert_eq!(got.unwrap_err(), error, "{name}");
}
// A draw without an index buffer is rejected at execution.
let ctx = &mut rig.ctx;
ctx.reset_command_list(rig.list, rig.alloc).unwrap();
ctx.cmd_set_vertex_buffer(rig.list, rig.vb, 0, INDEXED_STRIDE)
.unwrap();
ctx.cmd_draw_indexed_instanced(rig.list, 3, 1, 0, 0, 0)
.unwrap();
ctx.close_command_list(rig.list).unwrap();
assert_eq!(
ctx.execute_command_list(rig.queue, rig.list, &rig.memory),
Err(GraphicsError::InvalidResourceHandle)
);
// A stride smaller than one float4 position is rejected.
ctx.reset_command_list(rig.list, rig.alloc).unwrap();
ctx.cmd_set_vertex_buffer(rig.list, rig.vb, 0, 12).unwrap();
ctx.cmd_set_index_buffer(rig.list, ib16, 0, R16_UINT)
.unwrap();
ctx.cmd_draw_indexed_instanced(rig.list, 3, 1, 4, 2, 0)
.unwrap();
ctx.close_command_list(rig.list).unwrap();
assert_eq!(
ctx.execute_command_list(rig.queue, rig.list, &rig.memory),
Err(GraphicsError::InvalidDescriptor)
);
// A nonzero start instance is rejected.
ctx.reset_command_list(rig.list, rig.alloc).unwrap();
ctx.cmd_set_vertex_buffer(rig.list, rig.vb, 0, INDEXED_STRIDE)
.unwrap();
ctx.cmd_set_index_buffer(rig.list, ib16, 0, R16_UINT)
.unwrap();
ctx.cmd_draw_indexed_instanced(rig.list, 3, 1, 4, 2, 1)
.unwrap();
ctx.close_command_list(rig.list).unwrap();
assert_eq!(
ctx.execute_command_list(rig.queue, rig.list, &rig.memory),
Err(GraphicsError::InvalidDescriptor)
);
// An index buffer whose guest backing would wrap the address space is
// rejected, not read at a wrapped address.
let device = ctx.create_device().unwrap();
// The read's start wraps (start 8 at 2 bytes each), then only its end does.
for (guest_addr, start) in [(u64::MAX - 8, 8), (u64::MAX - 2, 0)] {
let wrapping = rig
.ctx
.create_committed_resource(
device,
ResourceDesc {
dimension: ResourceDimension::Buffer,
width: 64,
height: 1,
depth_or_array_size: 1,
mip_levels: 1,
format_rgba8: false,
},
ResourceStates::COMMON,
Some(guest_addr),
)
.unwrap();
assert_eq!(
run_indexed(&mut rig, (wrapping, 0, R16_UINT), (3, 1, start, 0)).unwrap_err(),
GraphicsError::IndexOutOfRange,
"guest address {guest_addr:#x} start {start}"
);
}
// No rejected draw reached the backend.
assert_eq!(*calls.lock().unwrap(), 0);
}
/// The loader's indexed fetch feeds the native Metal renderer: the GPU image
/// of the fetched triangle equals the image of the literal triangle.
#[test]
#[cfg_attr(
not(feature = "gpu-tests"),
ignore = "needs native Metal device; run scripts/test-gpu.sh"
)]
fn test_d3d12_indexed_draw_native_metal() {
use xenora_metal::NativeCompute;
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
let vs_bytes = include_bytes!("../../../fixtures/rdna2/x9-constant-vs.bin");
let ps_bytes = include_bytes!("../../../fixtures/rdna2/x9-constant-ps.bin");
let msl = compile_graphics(Architecture::Gfx1030, vs_bytes, ps_bytes)
.expect("compile graphics RDNA2 shaders")
.msl;
let gpu = Arc::new(NativeCompute::new().expect("native Metal GPU device"));
let render = {
let gpu = gpu.clone();
let msl = msl.clone();
move |vtx: &[[f32; 4]; 3], vp: (usize, usize), cc: [u8; 4]| {
gpu.render_rgba8(
&msl,
[VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT],
vtx,
&[[0.0; 4]; 3],
[vp.0, vp.1],
cc,
)
.map_err(|e| GraphicsError::BackendError(format!("Metal GPU error: {e:?}")))
}
};
let direct = render(&INDEXED_TRIANGLE, (16, 16), [0, 0, 0, 255]).expect("direct render");
let mut rig = indexed_rig();
rig.ctx.set_metal_backend(render);
let ib16 = rig.ib16;
let outcome = run_indexed(&mut rig, (ib16, 0, R16_UINT), (3, 1, 2, -1)).expect("indexed");
assert_eq!(outcome.backend, GraphicsBackendId::MetalNative);
assert_eq!(outcome.pixels, direct);
// The constant shader paints the covered pixels red; the CPU rasteriser
// agrees pixel for pixel, and the triangle covers some but not all pixels.
let reference = GraphicsContext::execute_software_reference_draw(
&INDEXED_TRIANGLE,
(16, 16),
[0, 0, 0, 255],
)
.unwrap();
assert_eq!(outcome.pixels, reference);
let red = outcome
.pixels
.chunks(4)
.filter(|p| *p == [255, 0, 0, 255])
.count();
assert!((1..256).contains(&red), "{red} red pixels");
println!("indexed native Metal draw: {red} of 256 pixels covered");
}
+95
View File
@@ -0,0 +1,95 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use xenora_loader::cpu::{CpuState, ExitReason, Register};
use xenora_loader::dbt::DbtEngine;
use xenora_loader::memory::{GuestMemory, MemoryError, MemoryPermissions};
#[test]
fn native_indirect_transfers_commit_before_target_fetch() {
const ENTRY: u64 = 0x2000;
const SLOT: u64 = 0x1800;
const TARGET: u64 = 0x3000;
const STACK: u64 = 0x4000;
const SENTINEL: u64 = 0xabcd_1234;
// R9 or [RIP - 0x806]. Both memory operands point back to SLOT.
for (branch, call) in [
(&[0x41, 0xff, 0xd1][..], true),
(&[0x41, 0xff, 0xe1][..], false),
(&[0xff, 0x15, 0xfa, 0xf7, 0xff, 0xff][..], true),
(&[0xff, 0x25, 0xfa, 0xf7, 0xff, 0xff][..], false),
] {
for target_permissions in [
Some(MemoryPermissions::READ_EXECUTE),
Some(MemoryPermissions::READ_WRITE),
None,
] {
let return_address = ENTRY + branch.len() as u64;
let mut code = branch.to_vec();
code.push(0xf4);
let mut memory = GuestMemory::new();
memory
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, &code)
.unwrap();
memory
.map_region_with_data(
SLOT,
8,
MemoryPermissions::READ_WRITE,
&TARGET.to_le_bytes(),
)
.unwrap();
memory
.map_region_with_data(
STACK,
8,
MemoryPermissions::READ_WRITE,
&SENTINEL.to_le_bytes(),
)
.unwrap();
if let Some(permissions) = target_permissions {
let target_opcode = if call { 0xc3 } else { 0xf4 };
memory
.map_region_with_data(TARGET, 1, permissions, &[target_opcode])
.unwrap();
}
let mut cpu = CpuState::new(ENTRY, STACK + 8);
cpu.set(Register::R9, TARGET);
let mut engine = DbtEngine::new(16 * 1024).unwrap();
let transfer = engine.run(&mut cpu, &mut memory, 1);
assert_eq!(transfer.exit_reason, ExitReason::StepLimitExceeded);
assert_eq!(transfer.instructions_executed, 1);
assert_eq!(cpu.rip, TARGET);
let stack_after_transfer = if call { STACK } else { STACK + 8 };
assert_eq!(cpu.get(Register::Rsp), stack_after_transfer);
assert_eq!(
memory.read_u64(STACK).unwrap(),
if call { return_address } else { SENTINEL }
);
let resumed = engine.run(&mut cpu, &mut memory, 3);
match target_permissions {
Some(MemoryPermissions::READ_EXECUTE) => {
assert_eq!(resumed.exit_reason, ExitReason::Halt);
assert_eq!(resumed.instructions_executed, if call { 2 } else { 1 });
assert_eq!(cpu.rip, if call { return_address + 1 } else { TARGET + 1 });
assert_eq!(cpu.get(Register::Rsp), STACK + 8);
}
permissions => {
let fault = if permissions.is_some() {
MemoryError::PermissionViolation {
address: TARGET,
required: "execute",
}
} else {
MemoryError::UnmappedAddress(TARGET)
};
assert_eq!(resumed.exit_reason, ExitReason::MemoryFault(fault));
assert_eq!(resumed.instructions_executed, 0);
assert_eq!(cpu.rip, TARGET);
assert_eq!(cpu.get(Register::Rsp), stack_after_transfer);
}
}
}
}
}
+159
View File
@@ -0,0 +1,159 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Guest memory boundary regression tests (#82).
//!
//! Expected behavior follows x86-64 data access rules: an access is valid when
//! every byte it touches is mapped with the required permission, whether or not
//! it is aligned or crosses into an adjacent mapping. A faulting access changes
//! nothing.
use xenora_loader::{GuestMemory, MemoryError, MemoryPermissions as P};
const A: u64 = 0x10_0000;
fn two_regions(first: P, second: P) -> GuestMemory {
let mut m = GuestMemory::new();
m.map_region_with_data(A, 0x1000, first, &[0x11; 0x1000])
.unwrap();
m.map_region_with_data(A + 0x1000, 0x1000, second, &[0x22; 0x1000])
.unwrap();
m
}
fn bypass_bytes(m: &GuestMemory, at: u64) -> u64 {
m.read_u64_bypass(at).unwrap()
}
#[test]
fn permissions_are_enforced_per_access_kind() {
let mut m = GuestMemory::new();
m.map_region(A, 0x1000, P::NO_ACCESS).unwrap();
m.map_region(A + 0x1000, 0x1000, P::READ_ONLY).unwrap();
m.map_region(A + 0x2000, 0x1000, P::READ_WRITE).unwrap();
let violation = |address, required| MemoryError::PermissionViolation { address, required };
assert_eq!(m.read_u8(A), Err(violation(A, "read")));
assert_eq!(
m.write_u8(A + 0x1000, 1),
Err(violation(A + 0x1000, "write"))
);
assert_eq!(
m.fetch_instruction_byte(A + 0x2000),
Err(violation(A + 0x2000, "execute"))
);
assert!(m.read_u8(A + 0x1000).is_ok());
assert!(m.write_u8(A + 0x2000, 1).is_ok());
}
#[test]
fn region_end_is_exclusive() {
let m = two_regions(P::READ_ONLY, P::NO_ACCESS);
assert!(m.read_u32(A + 0xFFC).is_ok());
assert!(matches!(
m.read_u32(A + 0xFFD),
Err(MemoryError::PermissionViolation { .. })
));
let mut lone = GuestMemory::new();
lone.map_region(A, 0x1000, P::READ_ONLY).unwrap();
assert_eq!(
lone.read_u32(A + 0xFFD),
Err(MemoryError::UnmappedAddress(A + 0xFFD))
);
assert_eq!(
lone.read_u8(A - 1),
Err(MemoryError::UnmappedAddress(A - 1))
);
}
#[test]
fn unaligned_accesses_succeed_inside_a_region() {
let mut m = two_regions(P::READ_WRITE, P::READ_WRITE);
m.write_u64(A + 3, 0x0102_0304_0506_0708).unwrap();
assert_eq!(m.read_u64(A + 3), Ok(0x0102_0304_0506_0708));
assert_eq!(m.read_u16(A + 3), Ok(0x0708));
assert_eq!(m.read_u32(A + 5), Ok(0x0304_0506));
}
#[test]
fn access_spanning_adjacent_permitted_regions_succeeds() {
let mut m = two_regions(P::READ_WRITE, P::READ_WRITE);
m.write_u64(A + 0xFFC, 0x8877_6655_4433_2211).unwrap();
assert_eq!(m.read_u64(A + 0xFFC), Ok(0x8877_6655_4433_2211));
assert_eq!(m.read_u32(A + 0xFFC), Ok(0x4433_2211)); // low half in the first region
assert_eq!(m.read_u32(A + 0x1000), Ok(0x8877_6655)); // high half in the second
}
#[test]
fn spanning_into_a_gap_fails_without_partial_write() {
let mut m = GuestMemory::new();
m.map_region_with_data(A, 0x1000, P::READ_WRITE, &[0x11; 0x1000])
.unwrap();
m.map_region(A + 0x2000, 0x1000, P::READ_WRITE).unwrap();
assert_eq!(
m.write_u64(A + 0xFFC, u64::MAX),
Err(MemoryError::UnmappedAddress(A + 0xFFC))
);
assert_eq!(m.read_u32(A + 0xFFC), Ok(0x1111_1111));
}
#[test]
fn spanning_into_a_forbidden_region_fails_atomically() {
let mut m = two_regions(P::READ_WRITE, P::READ_ONLY);
assert_eq!(
m.write_u64(A + 0xFFC, u64::MAX),
Err(MemoryError::PermissionViolation {
address: A + 0xFFC,
required: "write"
})
);
assert_eq!(bypass_bytes(&m, A + 0xFFC), 0x2222_2222_1111_1111);
let m = two_regions(P::READ_EXECUTE, P::READ_WRITE);
assert!(m.read_u64(A + 0xFFC).is_ok());
assert!(m.fetch_instruction_byte(A + 0xFFF).is_ok());
assert!(m.fetch_instruction_byte(A + 0x1000).is_err());
}
#[test]
fn loader_bypass_ignores_permissions_but_not_mapping() {
let mut m = two_regions(P::READ_ONLY, P::NO_ACCESS);
m.write_u64_bypass(A + 0xFFC, 0x0A0B_0C0D_0E0F_1011)
.unwrap();
assert_eq!(m.read_u64_bypass(A + 0xFFC), Ok(0x0A0B_0C0D_0E0F_1011));
m.write_u32_bypass(A, 7).unwrap();
assert_eq!(m.read_u32(A), Ok(7));
assert_eq!(
m.write_u64_bypass(A + 0x1FFC, 0),
Err(MemoryError::UnmappedAddress(A + 0x1FFC))
);
}
#[test]
fn address_overflow_is_reported() {
let mut m = GuestMemory::new();
m.map_region(u64::MAX - 0xFFF, 0xFFF, P::READ_WRITE)
.unwrap();
assert_eq!(m.read_u64(u64::MAX - 3), Err(MemoryError::Overflow));
assert_eq!(
m.write_u64_bypass(u64::MAX - 3, 0),
Err(MemoryError::Overflow)
);
assert_eq!(
m.map_region(u64::MAX, 2, P::READ_WRITE),
Err(MemoryError::Overflow)
);
}
#[test]
fn overlapping_mappings_are_rejected_and_adjacent_ones_accepted() {
let mut m = GuestMemory::new();
m.map_region(A, 0x1000, P::READ_WRITE).unwrap();
assert_eq!(
m.map_region(A + 0xFFF, 0x10, P::READ_WRITE),
Err(MemoryError::OverlappingRegion {
base: A + 0xFFF,
size: 0x10
})
);
assert!(m.map_region(A + 0x1000, 0x10, P::READ_WRITE).is_ok());
assert!(m.map_region(A - 0x10, 0x10, P::READ_WRITE).is_ok());
}
+96
View File
@@ -0,0 +1,96 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! PE image mapping budget tests (#80).
//!
//! A section's mapped size is max(VirtualSize, SizeOfRawData) and the loader
//! backs it with zero-filled host memory, so a small file can request a large
//! allocation. The loader's documented budget is 256 MiB per image.
use xenora_loader::{MemoryError, ParsedPe, PeError};
const BUDGET: u32 = 256 * 1024 * 1024;
/// An original synthetic image: one 0x200-byte code section at RVA 0x1000 followed by
/// uninitialized sections (no raw data) of the given virtual sizes, packed back to back.
fn build(bss_sizes: &[u32]) -> Vec<u8> {
let mut pe = vec![0u8; 0x400];
pe[0..2].copy_from_slice(b"MZ");
pe[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
pe[0x40..0x44].copy_from_slice(b"PE\0\0");
let coff = 0x44;
pe[coff..coff + 2].copy_from_slice(&0x8664u16.to_le_bytes());
pe[coff + 2..coff + 4].copy_from_slice(&(1 + bss_sizes.len() as u16).to_le_bytes());
pe[coff + 16..coff + 18].copy_from_slice(&112u16.to_le_bytes());
let opt = coff + 20;
pe[opt..opt + 2].copy_from_slice(&0x020Bu16.to_le_bytes());
pe[opt + 16..opt + 20].copy_from_slice(&0x1000u32.to_le_bytes());
pe[opt + 24..opt + 32].copy_from_slice(&0x1_4000_0000u64.to_le_bytes());
let mut section = |i: usize, va: u32, vsize: u32, raw: u32, flags: u32| {
let h = opt + 112 + i * 40;
pe[h + 8..h + 12].copy_from_slice(&vsize.to_le_bytes());
pe[h + 12..h + 16].copy_from_slice(&va.to_le_bytes());
pe[h + 16..h + 20].copy_from_slice(&(if raw == 0 { 0 } else { 0x200u32 }).to_le_bytes());
pe[h + 20..h + 24].copy_from_slice(&raw.to_le_bytes());
pe[h + 36..h + 40].copy_from_slice(&flags.to_le_bytes());
};
section(0, 0x1000, 0x200, 0x200, 0x6000_0020);
let mut va = 0x2000u32;
for (i, &size) in bss_sizes.iter().enumerate() {
section(i + 1, va, size, 0, 0xC000_0080);
va += size;
}
pe
}
fn over_budget() -> PeError {
PeError::SectionMappingError(MemoryError::AllocationFailed)
}
#[test]
fn small_image_loads() {
let bytes = build(&[0x1000]);
let pe = ParsedPe::parse(&bytes).unwrap();
assert!(pe.load_into_memory(&bytes).is_ok());
}
#[test]
fn image_exactly_at_budget_loads() {
let bytes = build(&[BUDGET - 0x200]);
let pe = ParsedPe::parse(&bytes).unwrap();
assert!(pe.load_into_memory(&bytes).is_ok());
}
#[test]
fn one_byte_over_budget_is_rejected() {
let bytes = build(&[BUDGET - 0x1FF]);
let pe = ParsedPe::parse(&bytes).unwrap();
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
}
#[test]
fn budget_counts_all_sections_together() {
// Three 128 MiB sections: each fits alone, the total (384 MiB) does not.
let bytes = build(&[128 << 20; 3]);
let pe = ParsedPe::parse(&bytes).unwrap();
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
}
#[test]
fn near_4_gib_request_from_a_1_kib_file_is_rejected_before_allocation() {
let bytes = build(&[0xF000_0000]);
assert_eq!(bytes.len(), 0x400);
let pe = ParsedPe::parse(&bytes).expect("headers are valid; only the size is excessive");
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
}
#[test]
fn repository_fixture_is_within_budget() {
let path = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../fixtures/pe/trusted-runner.exe"
);
let bytes = std::fs::read(path).unwrap();
let pe = ParsedPe::parse(&bytes).unwrap();
assert!(pe.load_into_memory(&bytes).is_ok());
}
+239
View File
@@ -0,0 +1,239 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Malformed-input regression tests for the PE32+ parser (#79).
//!
//! Every image here is built byte by byte from the Microsoft PE/COFF
//! specification layout: DOS header with e_lfanew at 0x3C, "PE\0\0", the
//! 20-byte COFF header, the PE32+ optional header (112 fixed bytes before the
//! data directories) and 40-byte section headers.
use xenora_loader::{ParsedPe, PeError, PeSection};
const RX: u32 = 0x6000_0020; // code | execute | read
const R: u32 = 0x4000_0040; // initialized data | read
struct Sec {
va: u32,
vsize: u32,
raw_ptr: u32,
raw_size: u32,
flags: u32,
}
/// A two-section image: .text at RVA 0x1000 (file 0x200) and .rdata at RVA 0x2000 (file 0x400).
fn valid_sections() -> Vec<Sec> {
vec![
Sec {
va: 0x1000,
vsize: 0x100,
raw_ptr: 0x200,
raw_size: 0x200,
flags: RX,
},
Sec {
va: 0x2000,
vsize: 0x80,
raw_ptr: 0x400,
raw_size: 0x200,
flags: R,
},
]
}
fn build(opt_size: u16, entry: u32, secs: &[Sec]) -> Vec<u8> {
let mut pe = vec![0u8; 0x600];
pe[0..2].copy_from_slice(b"MZ");
pe[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
pe[0x40..0x44].copy_from_slice(b"PE\0\0");
let coff = 0x44;
pe[coff..coff + 2].copy_from_slice(&0x8664u16.to_le_bytes());
pe[coff + 2..coff + 4].copy_from_slice(&(secs.len() as u16).to_le_bytes());
pe[coff + 16..coff + 18].copy_from_slice(&opt_size.to_le_bytes());
let opt = coff + 20;
pe[opt..opt + 2].copy_from_slice(&0x020Bu16.to_le_bytes());
pe[opt + 16..opt + 20].copy_from_slice(&entry.to_le_bytes());
pe[opt + 24..opt + 32].copy_from_slice(&0x1_4000_0000u64.to_le_bytes());
pe[opt + 32..opt + 36].copy_from_slice(&0x1000u32.to_le_bytes());
pe[opt + 36..opt + 40].copy_from_slice(&0x200u32.to_le_bytes());
pe[opt + 56..opt + 60].copy_from_slice(&0x3000u32.to_le_bytes());
pe[opt + 60..opt + 64].copy_from_slice(&0x200u32.to_le_bytes());
let table = opt + usize::from(opt_size);
for (i, s) in secs.iter().enumerate() {
let h = table + i * 40;
pe[h..h + 5].copy_from_slice(b".sect");
pe[h + 8..h + 12].copy_from_slice(&s.vsize.to_le_bytes());
pe[h + 12..h + 16].copy_from_slice(&s.va.to_le_bytes());
pe[h + 16..h + 20].copy_from_slice(&s.raw_size.to_le_bytes());
pe[h + 20..h + 24].copy_from_slice(&s.raw_ptr.to_le_bytes());
pe[h + 36..h + 40].copy_from_slice(&s.flags.to_le_bytes());
}
pe
}
#[test]
fn valid_image_parses_maps_and_translates() {
let bytes = build(112, 0x1010, &valid_sections());
let pe = ParsedPe::parse(&bytes).expect("valid image");
assert_eq!(pe.entry_point_rva, 0x1010);
assert_eq!(pe.sections.len(), 2);
assert_eq!(pe.rva_to_file_offset(0x1010), Some(0x210));
assert_eq!(pe.rva_to_file_offset(0x2004), Some(0x404));
assert_eq!(pe.rva_to_file_offset(0x3000), None);
let loaded = pe.load_into_memory(&bytes).expect("load");
assert_eq!(loaded.entry_point, 0x1_4000_1010);
}
#[test]
fn optional_header_with_data_directories_is_accepted() {
let bytes = build(240, 0x1000, &valid_sections());
assert!(ParsedPe::parse(&bytes).is_ok());
}
#[test]
fn repository_fixtures_still_parse_and_load() {
let root = concat!(env!("CARGO_MANIFEST_DIR"), "/../..");
for path in [
"fixtures/pe/trusted-runner.exe",
"experiments/x1/fixtures/x2.exe",
"experiments/x1/fixtures/x3.exe",
"experiments/x1/fixtures/x4-17.exe",
"experiments/x1/fixtures/x4-93.exe",
"experiments/x1/fixtures/x5.exe",
"experiments/x1/fixtures/x6.exe",
] {
let bytes = std::fs::read(format!("{root}/{path}")).expect(path);
let pe = ParsedPe::parse(&bytes).unwrap_or_else(|e| panic!("{path}: {e}"));
pe.load_into_memory(&bytes)
.unwrap_or_else(|e| panic!("{path}: {e}"));
}
}
/// Reproducer from #79: 90 bytes, SizeOfOptionalHeader = 2, file ends after the magic.
#[test]
fn truncated_optional_header_is_rejected_not_panicking() {
let mut bytes = vec![0u8; 90];
bytes[0..2].copy_from_slice(b"MZ");
bytes[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
bytes[0x40..0x44].copy_from_slice(b"PE\0\0");
bytes[0x44..0x46].copy_from_slice(&0x8664u16.to_le_bytes());
bytes[0x54..0x56].copy_from_slice(&2u16.to_le_bytes());
bytes[0x58..0x5A].copy_from_slice(&0x020Bu16.to_le_bytes());
assert_eq!(ParsedPe::parse(&bytes).unwrap_err(), PeError::TooSmall);
}
#[test]
fn optional_header_shorter_than_pe32_plus_fixed_fields_is_rejected() {
for opt_size in [24u16, 64, 111] {
let bytes = build(opt_size, 0x1000, &valid_sections());
assert_eq!(
ParsedPe::parse(&bytes).unwrap_err(),
PeError::TooSmall,
"{opt_size}"
);
}
}
#[test]
fn e_lfanew_past_end_of_file_is_rejected() {
let mut bytes = build(112, 0x1000, &valid_sections());
bytes[0x3C..0x40].copy_from_slice(&u32::MAX.to_le_bytes());
assert_eq!(ParsedPe::parse(&bytes).unwrap_err(), PeError::TooSmall);
}
#[test]
fn section_table_past_end_of_file_is_rejected() {
let mut bytes = build(112, 0x1000, &valid_sections());
bytes[0x46..0x48].copy_from_slice(&u16::MAX.to_le_bytes());
assert_eq!(
ParsedPe::parse(&bytes).unwrap_err(),
PeError::InvalidSectionHeaders
);
}
#[test]
fn section_range_overflowing_rva_space_is_rejected() {
let mut secs = valid_sections();
secs[1].va = 0xFFFF_F000;
secs[1].vsize = 0x2000;
let bytes = build(112, 0x1000, &secs);
assert_eq!(
ParsedPe::parse(&bytes).unwrap_err(),
PeError::InvalidSectionHeaders
);
}
/// Reproducer from #79: lookup over a section whose end overflows u32 must not panic or wrap.
#[test]
fn rva_lookup_with_overflowing_section_returns_none() {
let bytes = build(112, 0x1000, &valid_sections());
let mut pe = ParsedPe::parse(&bytes).unwrap();
pe.sections.insert(
0,
PeSection {
name: "wrap".into(),
virtual_address: 0xFFFF_FF00,
virtual_size: 0x200,
raw_data_ptr: 0x200,
raw_data_size: 0x200,
characteristics: R,
permissions: pe.sections[1].permissions,
},
);
// A wrapped end (0xFFFF_FF00 + 0x200 = 0x100) would wrongly capture RVA 0x80.
assert_eq!(pe.rva_to_file_offset(0x80), None);
assert_eq!(pe.rva_to_file_offset(0xFFFF_FF10), Some(0x210));
assert_eq!(pe.rva_to_file_offset(0x1004), Some(0x204));
}
#[test]
fn overlapping_sections_are_rejected() {
let mut secs = valid_sections();
secs[1].va = 0x1100; // .text maps 0x1000..0x1200 (raw size wins)
let bytes = build(112, 0x1000, &secs);
assert_eq!(
ParsedPe::parse(&bytes).unwrap_err(),
PeError::InvalidSectionHeaders
);
}
#[test]
fn adjacent_sections_are_accepted() {
let mut secs = valid_sections();
secs[1].va = 0x1200;
let bytes = build(112, 0x1000, &secs);
assert!(ParsedPe::parse(&bytes).is_ok());
}
#[test]
fn truncated_section_data_is_rejected() {
let mut secs = valid_sections();
secs[1].raw_size = 0x201; // file is 0x600 bytes; 0x400 + 0x201 runs one byte past the end
let bytes = build(112, 0x1000, &secs);
assert_eq!(
ParsedPe::parse(&bytes).unwrap_err(),
PeError::InvalidSectionHeaders
);
secs[1].raw_size = 0x200;
secs[1].raw_ptr = u32::MAX;
let bytes = build(112, 0x1000, &secs);
assert_eq!(
ParsedPe::parse(&bytes).unwrap_err(),
PeError::InvalidSectionHeaders
);
}
#[test]
fn entry_point_outside_executable_section_is_rejected() {
// Past the end of .text's mapped range, in non-executable .rdata, and outside every section.
for entry in [0x1200, 0x2000, 0x0, u32::MAX] {
let bytes = build(112, entry, &valid_sections());
assert_eq!(
ParsedPe::parse(&bytes).unwrap_err(),
PeError::InvalidEntryPoint,
"entry {entry:#x}"
);
}
// Last byte of .text is still inside it.
assert!(ParsedPe::parse(&build(112, 0x11FF, &valid_sections())).is_ok());
}
+103
View File
@@ -259,3 +259,106 @@ fn probe_consumes_complete_c7_operands_even_when_native_support_is_missing() {
assert!(!records[1].is_supported_dbt);
}
}
#[test]
fn exported_reports_agree_across_fixtures_and_blocker_locations() {
let dir =
std::env::temp_dir().join(format!("xenora-report-consistency-{}", std::process::id()));
// (file offset, RVA) for a reachable instruction immediately after a MOV.
for (fixture, file_offset, rva, sections, imports) in [
(create_synthetic_probe_pe(), 0x209, 0x1009_u32, 1, 0),
(
include_bytes!("../../../fixtures/pe/trusted-runner.exe").to_vec(),
0x44e,
0x104e,
4,
1,
),
] {
assert_eq!(fixture[file_offset], 0xc3);
for padding in [None, Some(0), Some(1), Some(7)] {
let mut pe = fixture.clone();
let blocker = padding.map(|n| {
pe[file_offset..file_offset + n].fill(0x90);
pe[file_offset + n] = 0xcc;
rva + n as u32
});
run_probe_and_export(&pe, &dir, &ProbeConfig::default()).unwrap();
let read = |name| std::fs::read_to_string(dir.join(name)).unwrap();
let md = read("candidate_static_report.md");
let json = read("candidate_static_report.json");
let cpu = read("cpu_coverage.csv");
let import_csv = read("imports.csv");
std::fs::remove_dir_all(&dir).unwrap();
let json_field = |name: &str| {
let prefix = format!("\"{name}\": ");
json.lines()
.find_map(|line| line.trim().strip_prefix(&prefix))
.unwrap()
.trim_end_matches(',')
.trim_matches('"')
};
assert_eq!(json_field("sections_count"), sections.to_string());
assert!(
md.lines()
.any(|line| line == format!("## Sections Census ({sections})"))
);
assert_eq!(
md.lines()
.filter(|line| line.contains(" VirtualSize: "))
.count(),
sections
);
assert_eq!(json_field("total_imports"), imports.to_string());
assert!(
md.lines()
.any(|line| line == format!("- **Total Imported Thunks**: `{imports}`"))
);
assert_eq!(import_csv.lines().skip(1).count(), imports);
let expected = blocker.map(|addr| format!("0x{addr:08x}"));
assert_eq!(
json_field("first_unsupported_dbt_rva"),
expected.as_deref().unwrap_or("none")
);
let md_rvas: Vec<_> = md
.lines()
.filter_map(|line| {
line.strip_prefix("- **RVA**: `")?
.split_once('`')
.map(|(addr, _)| addr)
})
.collect();
assert_eq!(md_rvas, expected.iter().collect::<Vec<_>>());
// The first columns precede quoted fields. Read the support flags from
// the closing quote of the mnemonic, which can itself contain commas.
let mut unsupported = Vec::new();
let mut tail = Vec::new();
for row in cpu.lines().skip(1) {
let (addr, rest) = row.split_once(',').unwrap();
let (_, fields) = rest.split_once(",\"").unwrap();
let (bytes, mnemonic) = fields.split_once("\",\"").unwrap();
let (_, flags) = mnemonic.split_once("\",").unwrap();
if flags.split(',').next() == Some("false") {
unsupported.push(addr);
}
let address = u32::from_str_radix(addr.strip_prefix("0x").unwrap(), 16).unwrap();
if address >= rva {
tail.push((address, bytes));
}
}
assert_eq!(unsupported, expected.iter().collect::<Vec<_>>());
let mut expected_tail = Vec::new();
if let Some(end) = blocker {
expected_tail.extend((rva..end).map(|addr| (addr, "90")));
expected_tail.push((end, "cc"));
} else {
expected_tail.push((rva, "c3"));
}
assert_eq!(tail, expected_tail);
}
}
}
@@ -0,0 +1,271 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Base relocation regression tests (#81).
//!
//! Images are built byte by byte from the PE/COFF layout: data directory 5
//! (Base Relocation Table) at optional-header offset 152, and blocks made of a
//! 4-byte page RVA, a 4-byte block size and 2-byte entries whose top 4 bits
//! are the type (0 = ABSOLUTE padding, 3 = HIGHLOW, 10 = DIR64).
use xenora_loader::{GuestMemory, ParsedPe, RelocationError, apply_relocations};
const PREFERRED: u64 = 0x1_4000_0000;
const RELOC_FILE: usize = 0x400;
/// .text at RVA 0x1000 (file 0x200) holding two pointers, .reloc at RVA 0x2000 (file 0x400).
/// `NumberOfRvaAndSizes` and the relocation table bytes are parameters.
fn build(rva_and_sizes: u32, table: &[u8], dir_size: u32) -> Vec<u8> {
let mut pe = vec![0u8; 0x600];
pe[0..2].copy_from_slice(b"MZ");
pe[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
pe[0x40..0x44].copy_from_slice(b"PE\0\0");
let coff = 0x44;
pe[coff..coff + 2].copy_from_slice(&0x8664u16.to_le_bytes());
pe[coff + 2..coff + 4].copy_from_slice(&2u16.to_le_bytes());
pe[coff + 16..coff + 18].copy_from_slice(&240u16.to_le_bytes());
let opt = coff + 20;
pe[opt..opt + 2].copy_from_slice(&0x020Bu16.to_le_bytes());
pe[opt + 16..opt + 20].copy_from_slice(&0x1000u32.to_le_bytes());
pe[opt + 24..opt + 32].copy_from_slice(&PREFERRED.to_le_bytes());
pe[opt + 32..opt + 36].copy_from_slice(&0x1000u32.to_le_bytes());
pe[opt + 36..opt + 40].copy_from_slice(&0x200u32.to_le_bytes());
pe[opt + 56..opt + 60].copy_from_slice(&0x3000u32.to_le_bytes());
pe[opt + 60..opt + 64].copy_from_slice(&0x200u32.to_le_bytes());
pe[opt + 108..opt + 112].copy_from_slice(&rva_and_sizes.to_le_bytes());
pe[opt + 152..opt + 156].copy_from_slice(&0x2000u32.to_le_bytes());
pe[opt + 156..opt + 160].copy_from_slice(&dir_size.to_le_bytes());
let sections: [(&[u8], u32, u32, u32, u32); 2] = [
(b".text", 0x1000, 0x200, 0x200, 0x6000_0020),
// .reloc fills the image up to SizeOfImage (0x3000).
(b".reloc", 0x2000, 0x1000, RELOC_FILE as u32, 0x4200_0040),
];
for (i, (name, va, vsize, raw, flags)) in sections.into_iter().enumerate() {
let h = opt + 240 + i * 40;
pe[h..h + name.len()].copy_from_slice(name);
pe[h + 8..h + 12].copy_from_slice(&vsize.to_le_bytes());
pe[h + 12..h + 16].copy_from_slice(&va.to_le_bytes());
pe[h + 16..h + 20].copy_from_slice(&0x200u32.to_le_bytes());
pe[h + 20..h + 24].copy_from_slice(&raw.to_le_bytes());
pe[h + 36..h + 40].copy_from_slice(&flags.to_le_bytes());
}
// Two absolute pointers into the image, at RVAs 0x1010 and 0x1018.
pe[0x210..0x218].copy_from_slice(&(PREFERRED + 0x1100).to_le_bytes());
pe[0x218..0x220].copy_from_slice(&(PREFERRED + 0x2000).to_le_bytes());
pe[RELOC_FILE..RELOC_FILE + table.len()].copy_from_slice(table);
pe
}
fn block(page_rva: u32, entries: &[u16]) -> Vec<u8> {
let mut b = page_rva.to_le_bytes().to_vec();
b.extend_from_slice(&(8 + 2 * entries.len() as u32).to_le_bytes());
for e in entries {
b.extend_from_slice(&e.to_le_bytes());
}
b
}
/// DIR64 at 0x1010 and 0x1018, plus one ABSOLUTE padding entry to keep 4-byte alignment.
fn standard_table() -> Vec<u8> {
block(0x1000, &[0xA010, 0xA018, 0x0000])
}
fn load(bytes: &[u8], base: u64) -> (ParsedPe, GuestMemory) {
let pe = ParsedPe::parse(bytes).expect("parse");
let mut memory = GuestMemory::new();
for s in &pe.sections {
let raw = &bytes[s.raw_data_ptr as usize..(s.raw_data_ptr + s.raw_data_size) as usize];
memory
.map_region_with_data(
base + u64::from(s.virtual_address),
0x200,
s.permissions,
raw,
)
.expect("map");
}
(pe, memory)
}
fn relocate(
bytes: &[u8],
base: u64,
) -> (
Result<xenora_loader::RelocationReport, RelocationError>,
GuestMemory,
) {
let (pe, mut memory) = load(bytes, base);
let result = apply_relocations(&pe, bytes, base, &mut memory);
(result, memory)
}
#[test]
fn positive_rebase_adds_delta_to_each_dir64_target() {
let table = standard_table();
let bytes = build(16, &table, table.len() as u32);
let base = PREFERRED + 0x1_0000_0000;
let (result, memory) = relocate(&bytes, base);
let report = result.expect("relocate");
assert_eq!(report.delta, 0x1_0000_0000);
assert_eq!(report.applied_dir64, 2);
assert_eq!(report.skipped_absolute, 1);
assert_eq!(report.total_entries, 3);
assert_eq!(
memory.read_u64_bypass(base + 0x1010).unwrap(),
base + 0x1100
);
assert_eq!(
memory.read_u64_bypass(base + 0x1018).unwrap(),
base + 0x2000
);
}
#[test]
fn negative_rebase_subtracts_delta() {
let table = standard_table();
let bytes = build(16, &table, table.len() as u32);
let base = 0x1000_0000;
let (result, memory) = relocate(&bytes, base);
assert_eq!(
result.expect("relocate").delta,
base as i64 - PREFERRED as i64
);
assert_eq!(
memory.read_u64_bypass(base + 0x1010).unwrap(),
base + 0x1100
);
assert_eq!(
memory.read_u64_bypass(base + 0x1018).unwrap(),
base + 0x2000
);
}
#[test]
fn preferred_base_leaves_targets_unchanged() {
let table = standard_table();
let bytes = build(16, &table, table.len() as u32);
let (result, memory) = relocate(&bytes, PREFERRED);
assert_eq!(result.expect("relocate").applied_dir64, 0);
assert_eq!(
memory.read_u64_bypass(PREFERRED + 0x1010).unwrap(),
PREFERRED + 0x1100
);
}
#[test]
fn directory_beyond_declared_count_is_ignored() {
// NumberOfRvaAndSizes = 5 means directory index 5 does not exist.
let table = standard_table();
let bytes = build(5, &table, table.len() as u32);
let base = PREFERRED + 0x1_0000_0000;
let (result, memory) = relocate(&bytes, base);
assert_eq!(result.expect("relocate").applied_dir64, 0);
assert_eq!(
memory.read_u64_bypass(base + 0x1010).unwrap(),
PREFERRED + 0x1100
);
}
#[test]
fn unsupported_type_is_rejected() {
let table = block(0x1000, &[0x3010, 0x0000]); // HIGHLOW is not a PE32+ fixup here
let bytes = build(16, &table, table.len() as u32);
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
assert_eq!(
result.unwrap_err(),
RelocationError::UnsupportedRelocationType(3)
);
}
#[test]
fn malformed_block_sizes_are_rejected() {
let base = PREFERRED + 0x1000;
for size in [0u32, 4, 7, 11] {
let mut table = 0x1000u32.to_le_bytes().to_vec();
table.extend_from_slice(&size.to_le_bytes());
table.extend_from_slice(&[0; 8]);
let bytes = build(16, &table, table.len() as u32);
let (result, _) = relocate(&bytes, base);
assert_eq!(
result.unwrap_err(),
RelocationError::MalformedBlockHeader { offset: RELOC_FILE },
"block size {size}"
);
}
}
#[test]
fn block_larger_than_directory_is_rejected() {
let table = standard_table(); // 14 bytes
let bytes = build(16, &table, 12);
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
assert_eq!(
result.unwrap_err(),
RelocationError::BlockSizeOutOfBounds {
block_size: 14,
max_size: 12
}
);
}
#[test]
fn trailing_partial_block_header_is_rejected() {
let mut table = block(0x1000, &[0xA010, 0x0000]);
table.extend_from_slice(&[0; 4]);
let bytes = build(16, &table, table.len() as u32);
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
assert_eq!(
result.unwrap_err(),
RelocationError::MalformedBlockHeader {
offset: RELOC_FILE + 12
}
);
}
#[test]
fn directory_past_end_of_file_is_rejected() {
let table = standard_table();
let bytes = build(16, &table, 0x300); // .reloc raw data starts at 0x400 in a 0x600-byte file
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
assert_eq!(
result.unwrap_err(),
RelocationError::DirectoryOutOfBounds {
rva: 0x2000,
size: 0x300
}
);
}
#[test]
fn target_outside_image_is_rejected_even_if_mapped() {
// SizeOfImage is 0x3000; RVA 0x3000 is past the image but mapped by another region.
let table = block(0x3000, &[0xA000, 0x0000]);
let bytes = build(16, &table, table.len() as u32);
let base = PREFERRED + 0x1000;
let (pe, mut memory) = load(&bytes, base);
let rw = pe.sections[1].permissions;
memory
.map_region(base + 0x3000, 0x1000, rw)
.expect("adjacent mapping");
memory.write_u64_bypass(base + 0x3000, 0x55).unwrap();
let result = apply_relocations(&pe, &bytes, base, &mut memory);
assert_eq!(
result.unwrap_err(),
RelocationError::TargetOutOfBounds {
target_va: base + 0x3000
}
);
assert_eq!(memory.read_u64_bypass(base + 0x3000).unwrap(), 0x55);
}
#[test]
fn target_rva_at_top_of_address_space_is_rejected() {
let table = block(0xFFFF_F000, &[0xAFFC, 0x0000]);
let bytes = build(16, &table, table.len() as u32);
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
assert!(matches!(
result,
Err(RelocationError::TargetOutOfBounds { .. })
));
}
+2
View File
@@ -32,12 +32,14 @@ objc2-foundation = { version = "=0.3.2", default-features = false, features = ["
objc2-metal = { version = "=0.3.2", default-features = false, features = [
"std",
"MTLAllocation",
"MTLArgument",
"MTLBuffer",
"MTLCommandBuffer",
"MTLCommandEncoder",
"MTLCommandQueue",
"MTLComputeCommandEncoder",
"MTLComputePipeline",
"MTLDepthStencil",
"MTLDevice",
"MTLLibrary",
"MTLPixelFormat",
+244 -40
View File
@@ -16,28 +16,50 @@ use objc2_metal::{
MTLResourceOptions, MTLShaderValidation, MTLSize, MTLStorageMode, MTLTexture,
MTLTextureDescriptor, MTLTextureUsage,
};
use xenora_texture::{Bc1Upload, TiledBc1};
use xenora_texture::{
Bc1Upload, BcAlphaFormat, BcAlphaUpload, BcChannelFormat, BcChannelUpload, TiledBc1,
};
#[path = "render.rs"]
mod render;
pub use render::{
BlendDraw, BlendFactor, BlendOperation, BlendPass, BlendState, ColorWriteMask, DepthCompare,
DepthDraw, DepthFill, DepthOutput, DepthPass, DepthState, IndexBuffer, IndexedDraw,
IndexedPass,
};
const MAX_THREADS_PER_GROUP: usize = 64;
const MAX_GROUPS: usize = 64;
const MAX_GRID_WORDS: usize = MAX_GROUPS * MAX_THREADS_PER_GROUP;
const MAX_SOURCE_BYTES: usize = 64 * 1024;
const BC1_READBACK: &str = r"
const BC_READBACK: &str = r"
#include <metal_stdlib>
using namespace metal;
kernel void read_bc1(texture2d<float, access::read> image [[texture(0)]],
device uint *output [[buffer(1)]],
uint index [[thread_position_in_grid]]) {
kernel void read_bc(texture2d<float, access::read> image [[texture(0)]],
device uint *output [[buffer(1)]],
uint index [[thread_position_in_grid]]) {
uint width = image.get_width();
uint4 channels = uint4(round(image.read(uint2(index % width, index / width)) * 255.0f));
output[index] = channels.r | (channels.g << 8u) | (channels.b << 16u) | (channels.a << 24u);
}
";
// Signed formats return -1.0..=1.0; each byte holds the channel times 127.
const BC_SNORM_READBACK: &str = r"
#include <metal_stdlib>
using namespace metal;
kernel void read_bc_snorm(texture2d<float, access::read> image [[texture(0)]],
device uint *output [[buffer(1)]],
uint index [[thread_position_in_grid]]) {
uint width = image.get_width();
float4 texel = clamp(image.read(uint2(index % width, index / width)), -1.0f, 1.0f);
uint4 bytes = uint4(int4(round(texel * 127.0f))) & 0xffu;
output[index] = bytes.r | (bytes.g << 8u) | (bytes.b << 16u) | (bytes.a << 24u);
}
";
enum ComputeInput<'a> {
Words(&'a [u32]),
Texture(&'a ProtocolObject<dyn MTLTexture>, usize),
@@ -88,6 +110,17 @@ pub struct MetalError {
}
impl MetalError {
/// Operation name of the error returned when the device lacks BC texture
/// compression, which is a hardware capability, not an implementation fault.
pub const BC_UNAVAILABLE: &'static str = "supportsBCTextureCompression";
/// Whether the device lacks a required capability, as opposed to a failure
/// in Xenora's validation or Metal execution.
#[must_use]
pub fn is_capability_unavailable(&self) -> bool {
self.operation == Self::BC_UNAVAILABLE
}
pub(crate) fn new(operation: &'static str, detail: impl Into<String>) -> Self {
Self {
operation,
@@ -184,11 +217,18 @@ impl NativeCompute {
let (width, height) = tiled
.mip_extent(mip)
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
let pixels = self.validate_bc1_extent(width, height)?;
let pixels = self.validate_bc_extent(width, height, "BC1")?;
let blocks = tiled
.linearize(layer, mip)
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
self.read_bc1_blocks(&blocks, width.div_ceil(4) * 8, width, height, pixels)
self.read_bc_blocks(
MTLPixelFormat::BC1_RGBA,
&blocks,
width.div_ceil(4) * 8,
width,
height,
pixels,
)
}
/// Sample a native Metal RGBA8 texture using a native Metal sampler on Apple Silicon GPU.
@@ -269,8 +309,9 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
let level = upload
.subresource(layer, mip)
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
let pixels = self.validate_bc1_extent(level.width, level.height)?;
self.read_bc1_blocks(
let pixels = self.validate_bc_extent(level.width, level.height, "BC1")?;
self.read_bc_blocks(
MTLPixelFormat::BC1_RGBA,
level.bytes,
level.row_pitch,
level.width,
@@ -279,22 +320,100 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
)
}
fn validate_bc1_extent(&self, width: usize, height: usize) -> Result<usize, MetalError> {
/// Read a selected subresource from a validated pitched BC2 or BC3 upload.
///
/// The original 16-byte blocks go to a native `BC2_RGBA` or `BC3_RGBA`
/// texture, and the output has the layout of [`Self::read_bc1_upload`].
///
/// # Errors
///
/// Returns an error for an invalid layer or mip, out-of-policy size,
/// unavailable BC compression, or Metal setup or execution failure.
pub fn read_bc_alpha_upload(
&self,
upload: &BcAlphaUpload<'_>,
layer: usize,
mip: u32,
) -> Result<Vec<u32>, MetalError> {
let level = upload
.subresource(layer, mip)
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
let (format, name) = match upload.format() {
BcAlphaFormat::Bc2 => (MTLPixelFormat::BC2_RGBA, "BC2"),
BcAlphaFormat::Bc3 => (MTLPixelFormat::BC3_RGBA, "BC3"),
};
let pixels = self.validate_bc_extent(level.width, level.height, name)?;
self.read_bc_blocks(
format,
level.bytes,
level.row_pitch,
level.width,
level.height,
pixels,
)
}
/// Read a selected subresource from a validated pitched BC4 or BC5 upload.
///
/// The original blocks go to a native `BC4_R*` or `BC5_RG*` texture.
/// Unsigned output has the layout of [`Self::read_bc1_upload`]. Signed
/// output stores each channel, times 127 and rounded, as a two's-complement
/// byte in the same order. Metal fills missing green and blue with 0 and
/// alpha with 1.
///
/// # Errors
///
/// Returns an error for an invalid layer or mip, out-of-policy size,
/// unavailable BC compression (operation `supportsBCTextureCompression`),
/// or Metal setup or execution failure.
pub fn read_bc_channel_upload(
&self,
upload: &BcChannelUpload<'_>,
layer: usize,
mip: u32,
) -> Result<Vec<u32>, MetalError> {
let level = upload
.subresource(layer, mip)
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
let (format, name) = match upload.format() {
BcChannelFormat::Bc4Unorm => (MTLPixelFormat::BC4_RUnorm, "BC4 UNORM"),
BcChannelFormat::Bc4Snorm => (MTLPixelFormat::BC4_RSnorm, "BC4 SNORM"),
BcChannelFormat::Bc5Unorm => (MTLPixelFormat::BC5_RGUnorm, "BC5 UNORM"),
BcChannelFormat::Bc5Snorm => (MTLPixelFormat::BC5_RGSnorm, "BC5 SNORM"),
};
let pixels = self.validate_bc_extent(level.width, level.height, name)?;
self.read_bc_blocks(
format,
level.bytes,
level.row_pitch,
level.width,
level.height,
pixels,
)
}
fn validate_bc_extent(
&self,
width: usize,
height: usize,
name: &str,
) -> Result<usize, MetalError> {
let pixels = width
.checked_mul(height)
.filter(|pixels| (1..=MAX_GRID_WORDS).contains(pixels))
.ok_or_else(|| MetalError::new("texture bounds", "expected 1..=4096 texels"))?;
if !self.device.supportsBCTextureCompression() {
return Err(MetalError::new(
"supportsBCTextureCompression",
"BC1 is unavailable",
MetalError::BC_UNAVAILABLE,
format!("{name} is unavailable"),
));
}
Ok(pixels)
}
fn read_bc1_blocks(
fn read_bc_blocks(
&self,
format: MTLPixelFormat,
blocks: &[u8],
row_pitch: usize,
width: usize,
@@ -302,14 +421,11 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
pixels: usize,
) -> Result<Vec<u32>, MetalError> {
autoreleasepool(|_| {
// SAFETY: The positive bounded dimensions and supported BC1 format
// SAFETY: The positive bounded dimensions and supported BC format
// describe a 2D texture with just its base level.
let descriptor = unsafe {
MTLTextureDescriptor::texture2DDescriptorWithPixelFormat_width_height_mipmapped(
MTLPixelFormat::BC1_RGBA,
width,
height,
false,
format, width, height, false,
)
};
descriptor.setStorageMode(MTLStorageMode::Shared);
@@ -318,7 +434,7 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
.device
.newTextureWithDescriptor(&descriptor)
.ok_or_else(|| {
MetalError::new("newTextureWithDescriptor", "BC1 allocation failed")
MetalError::new("newTextureWithDescriptor", "BC allocation failed")
})?;
let region = MTLRegion {
origin: MTLOrigin { x: 0, y: 0, z: 0 },
@@ -332,7 +448,8 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
let bytes_per_row = if height <= 4 { 0 } else { row_pitch };
// SAFETY: The region spans the whole level, including any partial
// edge block. Both callers validate that the input holds all rows
// of complete BC1 blocks at the supplied, block-aligned stride.
// of complete blocks of this format at the supplied, block-aligned
// stride.
unsafe {
texture.replaceRegion_mipmapLevel_withBytes_bytesPerRow(
region,
@@ -341,12 +458,14 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
bytes_per_row,
);
}
self.run(
BC1_READBACK,
"read_bc1",
ComputeInput::Texture(&texture, pixels),
)
.map(|profile| profile.output)
let (source, entry) =
if format == MTLPixelFormat::BC4_RSnorm || format == MTLPixelFormat::BC5_RGSnorm {
(BC_SNORM_READBACK, "read_bc_snorm")
} else {
(BC_READBACK, "read_bc")
};
self.run(source, entry, ComputeInput::Texture(&texture, pixels))
.map(|profile| profile.output)
})
}
@@ -438,6 +557,56 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
source: &str,
entry: &str,
input: &[u32],
) -> Result<RunProfile, MetalError> {
self.run_profiled_words(source, entry, input, None)
}
/// Run trusted MSL with an explicit one-dimensional threadgroup width.
///
/// The grid still contains one invocation per input word. The requested width
/// is passed to Metal even when the grid is smaller or ends in a partial group.
/// The trusted-kernel requirements of [`Self::run_words`] apply.
///
/// # Errors
///
/// Returns the same errors as [`Self::run_words_profiled`], with dispatch
/// bounds evaluated using this width. Zero and widths above the device or
/// pipeline limit are rejected.
pub fn run_words_with_group_width(
&self,
source: &str,
entry: &str,
input: &[u32],
width: usize,
) -> Result<RunProfile, MetalError> {
self.run_profiled_words(source, entry, input, Some(width))
}
/// Compile the kernel and report the smaller of the device and pipeline width limits.
///
/// Input size and threadgroup count are checked separately at dispatch.
///
/// # Errors
///
/// Returns an error if source validation, compilation or pipeline setup fails.
pub fn max_group_width(&self, source: &str, entry: &str) -> Result<usize, MetalError> {
validate_source(source, &[entry])?;
autoreleasepool(|_| {
let options = compile_options()?;
let library = self.compile_library(source, &options)?;
let function = find_function(&library, entry)?;
let pipeline = self.compute_pipeline(&function)?;
verify_shader_validation(&pipeline)?;
Ok(self.pipeline_group_width_limit(&pipeline))
})
}
fn run_profiled_words(
&self,
source: &str,
entry: &str,
input: &[u32],
group_width: Option<usize>,
) -> Result<RunProfile, MetalError> {
if !(1..=MAX_GRID_WORDS).contains(&input.len()) {
return Err(MetalError::new(
@@ -446,7 +615,7 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
));
}
validate_source(source, &[entry])?;
autoreleasepool(|_| self.run(source, entry, ComputeInput::Words(input)))
autoreleasepool(|_| self.run_sized(source, entry, ComputeInput::Words(input), group_width))
}
fn run(
@@ -454,6 +623,18 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
source: &str,
entry: &str,
input: ComputeInput<'_>,
) -> Result<RunProfile, MetalError> {
self.run_sized(source, entry, input, None)
}
/// [`Self::run`] with an optional explicit threadgroup width; `None` keeps
/// the default sizing.
fn run_sized(
&self,
source: &str,
entry: &str,
input: ComputeInput<'_>,
group_width: Option<usize>,
) -> Result<RunProfile, MetalError> {
let host_start = Instant::now();
let options = compile_options()?;
@@ -462,22 +643,21 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
let library_seconds = library_start.elapsed().as_secs_f64();
let function = find_function(&library, entry)?;
let pipeline_start = Instant::now();
let pipeline = self
.device
.newComputePipelineStateWithFunction_error(&function)
.map_err(|error| {
MetalError::new(
"newComputePipelineStateWithFunction",
error.localizedDescription().to_string(),
)
})?;
let pipeline = self.compute_pipeline(&function)?;
let pipeline_seconds = pipeline_start.elapsed().as_secs_f64();
verify_shader_validation(&pipeline)?;
let width = MAX_THREADS_PER_GROUP
.min(input.len())
.min(self.device.maxThreadsPerThreadgroup().width)
.min(pipeline.maxTotalThreadsPerThreadgroup());
let limit = self.pipeline_group_width_limit(&pipeline);
let width = match group_width {
Some(width) if (1..=limit).contains(&width) => width,
Some(width) => {
return Err(MetalError::new(
"threadgroup width",
format!("expected a nonzero width at most {limit}, got {width}"),
));
}
None => MAX_THREADS_PER_GROUP.min(input.len()).min(limit),
};
if width == 0 || input.len().div_ceil(width) > MAX_GROUPS {
return Err(MetalError::new(
"dispatch bounds",
@@ -568,6 +748,30 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
})
}
fn compute_pipeline(
&self,
function: &ProtocolObject<dyn MTLFunction>,
) -> Result<Retained<ProtocolObject<dyn MTLComputePipelineState>>, MetalError> {
self.device
.newComputePipelineStateWithFunction_error(function)
.map_err(|error| {
MetalError::new(
"newComputePipelineStateWithFunction",
error.localizedDescription().to_string(),
)
})
}
fn pipeline_group_width_limit(
&self,
pipeline: &ProtocolObject<dyn MTLComputePipelineState>,
) -> usize {
self.device
.maxThreadsPerThreadgroup()
.width
.min(pipeline.maxTotalThreadsPerThreadgroup())
}
fn new_buffer(
&self,
words: &[u32],
+5 -1
View File
@@ -13,7 +13,11 @@ pub mod sampler;
pub mod texture_pipeline;
#[cfg(all(target_arch = "aarch64", target_os = "macos"))]
pub use compute::{GuestBuffer, GuestBufferView, MetalError, NativeCompute, RunProfile};
pub use compute::{
BlendDraw, BlendFactor, BlendOperation, BlendPass, BlendState, ColorWriteMask, DepthCompare,
DepthDraw, DepthFill, DepthOutput, DepthPass, DepthState, GuestBuffer, GuestBufferView,
IndexBuffer, IndexedDraw, IndexedPass, MetalError, NativeCompute, RunProfile,
};
#[cfg(all(target_arch = "aarch64", target_os = "macos"))]
pub use sampler::MetalSampler;
File diff suppressed because it is too large. Load diff
+36
View File
@@ -0,0 +1,36 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! CPU check: the blend reference agrees with the independently derived
//! expectations for every blend case, colour and rounding flags alike. Runs
//! without a GPU.
#[path = "support/blend_cases.rs"]
mod blend_cases;
use blend_cases::{CLEAR, SIZE, cases, expected};
use xenora_ref::blend::{RefBlendDraw, render_blend};
#[test]
fn reference_matches_independent_expectations() {
let (cases, expected) = (cases(), expected());
assert_eq!(cases.len(), 39);
assert_eq!(expected.len(), cases.len());
for (case, want) in cases.iter().zip(&expected) {
assert_eq!(case.name, want.name);
let draws: Vec<_> = case
.draws
.iter()
.map(|draw| RefBlendDraw {
positions: draw.positions,
color: draw.color,
blend: draw.blend,
mask: draw.mask,
})
.collect();
let pixels = render_blend([SIZE, SIZE], CLEAR, &draws).expect("reference render");
let color: Vec<_> = pixels.iter().map(|p| p.map(|c| c.value)).collect();
let exact: Vec<_> = pixels.iter().map(|p| p.map(|c| c.exact)).collect();
assert_eq!(color, want.color, "{} colour", case.name);
assert_eq!(exact, want.exact, "{} rounding flags", case.name);
}
}
+64
View File
@@ -0,0 +1,64 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! CPU check: the reference rasteriser agrees with the independently derived
//! expectations for every depth case. Runs without a GPU.
#[path = "support/depth_cases.rs"]
mod depth_cases;
use depth_cases::{BC1_BLOCKS, Fill, SIZE, cases, expected};
use xenora_ref::depth::{RefDraw, RefFill, RefTexture, render_depth};
/// Row-major 8x8 texels decoded block by block with the CPU BC1 decoder.
pub fn bc1_texels() -> Vec<[u8; 4]> {
let mut texels = vec![[0; 4]; 64];
for (block, bytes) in BC1_BLOCKS.as_chunks::<8>().0.iter().enumerate() {
let decoded = xenora_texture::decode_bc1(*bytes);
for (index, texel) in decoded.iter().enumerate() {
let x = (block % 2) * 4 + index % 4;
let y = (block / 2) * 4 + index / 4;
texels[y * 8 + x] = *texel;
}
}
texels
}
#[test]
fn reference_matches_independent_expectations() {
let texels = bc1_texels();
let texture = RefTexture {
width: 8,
height: 8,
texels: &texels,
};
let expected = expected();
let cases = cases();
assert_eq!(cases.len(), 30);
assert_eq!(expected.len(), cases.len());
for (case, want) in cases.iter().zip(&expected) {
assert_eq!(case.name, want.name);
let draws: Vec<_> = case
.draws
.iter()
.map(|draw| RefDraw {
positions: draw.positions,
fill: match draw.fill {
Fill::Flat(rgba) => RefFill::Flat(rgba),
Fill::Texture => RefFill::Texture,
},
compare: draw.compare,
write: draw.write,
})
.collect();
let (color, depth) = render_depth(
[SIZE, SIZE],
case.clear_color,
case.clear_depth,
&draws,
Some(texture),
)
.expect("reference render");
assert_eq!(color, want.color, "{} colour", case.name);
assert_eq!(depth, want.depth, "{} depth", case.name);
}
}
+842
View File
@@ -0,0 +1,842 @@
case clear
palette A 32 64 96 128 eeee
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
end
case disabled
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 60 180 240 96 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCCCCCCC
color AAAACCCCCCCCCCCB
color AAAAACCCCCCCCCBB
color AAAAACCCCCCCCBBB
color AAAAACCCCCCCBBBB
color AAABBCCCCCCBBBBB
color AABBBCCCCCCBBBBB
color ABBBBCCCCCBBBBBB
color BBBBBCCCCBBBBBBB
color BBBBBBCCBBBBBBBB
color BBBBBBCBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case src_Zero
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 0 0 0 0 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCCCCCCC
color AAAACCCCCCCCCCCB
color AAAAACCCCCCCCCBB
color AAAAACCCCCCCCBBB
color AAAAACCCCCCCBBBB
color AAABBCCCCCCBBBBB
color AABBBCCCCCCBBBBB
color ABBBBCCCCCBBBBBB
color BBBBBCCCCBBBBBBB
color BBBBBBCCBBBBBBBB
color BBBBBBCBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case src_One
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 60 180 240 96 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCCCCCCC
color AAAACCCCCCCCCCCB
color AAAAACCCCCCCCCBB
color AAAAACCCCCCCCBBB
color AAAAACCCCCCCBBBB
color AAABBCCCCCCBBBBB
color AABBBCCCCCCBBBBB
color ABBBBCCCCCBBBBBB
color BBBBBCCCCBBBBBBB
color BBBBBBCCBBBBBBBB
color BBBBBBCBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case src_SourceColor
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 14 127 226 36 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCCCCCCC
color AAAACCCCCCCCCCCB
color AAAAACCCCCCCCCBB
color AAAAACCCCCCCCBBB
color AAAAACCCCCCCBBBB
color AAABBCCCCCCBBBBB
color AABBBCCCCCCBBBBB
color ABBBBCCCCCBBBBBB
color BBBBBCCCCBBBBBBB
color BBBBBBCCBBBBBBBB
color BBBBBBCBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case src_OneMinusSourceColor
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 46 53 14 60 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCCCCCCC
color AAAACCCCCCCCCCCB
color AAAAACCCCCCCCCBB
color AAAAACCCCCCCCBBB
color AAAAACCCCCCCBBBB
color AAABBCCCCCCBBBBB
color AABBBCCCCCCBBBBB
color ABBBBCCCCCBBBBBB
color BBBBBCCCCBBBBBBB
color BBBBBBCCBBBBBBBB
color BBBBBBCBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case src_SourceAlpha
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 23 68 90 36 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCCCCCCC
color AAAACCCCCCCCCCCB
color AAAAACCCCCCCCCBB
color AAAAACCCCCCCCBBB
color AAAAACCCCCCCBBBB
color AAABBCCCCCCBBBBB
color AABBBCCCCCCBBBBB
color ABBBBCCCCCBBBBBB
color BBBBBCCCCBBBBBBB
color BBBBBBCCBBBBBBBB
color BBBBBBCBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case src_OneMinusSourceAlpha
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 37 112 150 60 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCCCCCCC
color AAAACCCCCCCCCCCB
color AAAAACCCCCCCCCBB
color AAAAACCCCCCCCBBB
color AAAAACCCCCCCBBBB
color AAABBCCCCCCBBBBB
color AABBBCCCCCCBBBBB
color ABBBBCCCCCBBBBBB
color BBBBBCCCCBBBBBBB
color BBBBBBCCBBBBBBBB
color BBBBBBCBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case src_DestinationColor
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 47 71 47 60 rrrr
palette D 8 45 90 48 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case src_OneMinusDestinationColor
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 13 109 193 36 rrrr
palette D 52 135 150 48 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case src_DestinationAlpha
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 38 113 151 60 rrrr
palette D 30 90 120 48 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case src_OneMinusDestinationAlpha
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 22 67 89 36 rrrr
palette D 30 90 120 48 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case dst_Zero
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 0 0 0 0 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCCCCCCC
color AAAACCCCCCCCCCCB
color AAAAACCCCCCCCCBB
color AAAAACCCCCCCCBBB
color AAAAACCCCCCCBBBB
color AAABBCCCCCCBBBBB
color AABBBCCCCCCBBBBB
color ABBBBCCCCCBBBBBB
color BBBBBCCCCBBBBBBB
color BBBBBBCCBBBBBBBB
color BBBBBBCBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case dst_One
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAAAAAAAAABBBBB
color AAAAAAAAAABBBBBB
color AAAAAAAAABBBBBBB
color AAAAAAABBBBBBBBB
color AAAAAABBBBBBBBBB
color AAAAABBBBBBBBBBB
color AAABBBBBBBBBBBBB
color AABBBBBBBBBBBBBB
color ABBBBBBBBBBBBBBB
color BBBBBBBBBBBBBBBB
color BBBBBBBBBBBBBBBB
color BBBBBBBBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case dst_SourceColor
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 47 71 47 60 rrrr
palette D 8 45 90 48 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case dst_OneMinusSourceColor
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 153 29 3 100 rrrr
palette D 24 19 6 80 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case dst_SourceAlpha
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 75 38 19 60 rrrr
palette D 12 24 36 48 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case dst_OneMinusSourceAlpha
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 125 62 31 100 rrrr
palette D 20 40 60 80 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case dst_DestinationColor
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 157 39 10 100 rrrr
palette D 4 16 36 64 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case dst_OneMinusDestinationColor
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 43 61 40 60 rrrr
palette D 28 48 60 64 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case dst_DestinationAlpha
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 125 63 31 100 rrrr
palette D 16 32 48 64 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case dst_OneMinusDestinationAlpha
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 75 37 19 60 rrrr
palette D 16 32 48 64 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case op_Add
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 147 130 122 136 rrrr
palette D 43 108 150 116 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case op_Subtract
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 0 5 59 0 erre
palette D 3 28 30 0 rrre
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case op_ReverseSubtract
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 102 0 0 64 reer
palette D 0 0 0 44 eeer
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case op_Min
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 60 100 50 96 eeee
palette D 32 64 96 96 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case op_Max
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 200 180 240 160 eeee
palette D 60 180 240 128 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case additive_clamp
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 255 255 255 255 eeee
palette D 92 244 255 224 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case separate_alpha
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 147 130 122 96 rrre
palette D 43 108 150 96 rrre
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case mask_R
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 60 100 50 160 eeee
palette D 60 64 96 128 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case mask_G
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 200 180 50 160 eeee
palette D 32 180 96 128 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case mask_B
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 200 100 240 160 eeee
palette D 32 64 240 128 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case mask_A
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 200 100 50 96 eeee
palette D 32 64 96 96 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case mask_RGB
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 60 180 240 160 eeee
palette D 60 180 240 128 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case mask_none
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAAAAAAAAABBBBB
color AAAAAAAAAABBBBBB
color AAAAAAAAABBBBBBB
color AAAAAAABBBBBBBBB
color AAAAAABBBBBBBBBB
color AAAAABBBBBBBBBBB
color AAABBBBBBBBBBBBB
color AABBBBBBBBBBBBBB
color ABBBBBBBBBBBBBBB
color BBBBBBBBBBBBBBBB
color BBBBBBBBBBBBBBBB
color BBBBBBBBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case mask_RGBA
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 60 180 240 96 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCCCCCCC
color AAAACCCCCCCCCCCB
color AAAAACCCCCCCCCBB
color AAAAACCCCCCCCBBB
color AAAAACCCCCCCBBBB
color AAABBCCCCCCBBBBB
color AABBBCCCCCCBBBBB
color ABBBBCCCCCBBBBBB
color BBBBBCCCCBBBBBBB
color BBBBBBCCBBBBBBBB
color BBBBBBCBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case mask_RG_blended
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 147 130 50 160 rree
palette D 43 108 96 128 rree
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case separate_operation
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 147 130 122 64 rrre
palette D 43 108 150 32 rrre
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case first_draw_blended
palette A 32 87 67 148 errr
palette B 32 64 96 128 eeee
palette C 60 180 67 148 eerr
palette D 60 180 96 128 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
File diff suppressed because it is too large. Load diff
+361
View File
@@ -0,0 +1,361 @@
case clear
palette 0 16 32 48 255
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
end
case u16_first
fetch 0 1 2
palette 0 255 0 0 255
palette 1 0 0 0 255
color 0000000000000001
color 0000000000000011
color 0000000000000111
color 0000000000011111
color 0000000000111111
color 0000000001111111
color 0000000111111111
color 0000001111111111
color 0000011111111111
color 0001111111111111
color 0011111111111111
color 0111111111111111
color 1111111111111111
color 1111111111111111
color 1111111111111111
color 1111111111111111
end
case u32_first
fetch 0 1 2
palette 0 255 0 0 255
palette 1 0 0 0 255
color 0000000000000001
color 0000000000000011
color 0000000000000111
color 0000000000011111
color 0000000000111111
color 0000000001111111
color 0000000111111111
color 0000001111111111
color 0000011111111111
color 0001111111111111
color 0011111111111111
color 0111111111111111
color 1111111111111111
color 1111111111111111
color 1111111111111111
color 1111111111111111
end
case u16_odd_start
fetch 3 4 5
palette 0 0 0 0 255
palette 1 0 255 0 255
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000111111000000
color 0000111111111111
color 0000111111111110
color 0000011111111100
color 0000011111111000
color 0000011111110000
color 0000011111100000
color 0000011111100000
color 0000011111000000
color 0000011110000000
color 0000001100000000
color 0000001000000000
color 0000000000000000
end
case u32_start
fetch 3 4 5
palette 0 0 0 0 255
palette 1 0 255 0 255
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000111111000000
color 0000111111111111
color 0000111111111110
color 0000011111111100
color 0000011111111000
color 0000011111110000
color 0000011111100000
color 0000011111100000
color 0000011111000000
color 0000011110000000
color 0000001100000000
color 0000001000000000
color 0000000000000000
end
case u16_base_positive
fetch 6 7 8
palette 0 0 0 0 255
palette 1 0 0 255 255
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 1111111110000000
color 1111111100000000
color 1111111000000000
color 1111110000000000
color 1111000000000000
color 1110000000000000
color 1100000000000000
color 1000000000000000
end
case u16_base_negative
fetch 6 7 8
palette 0 0 0 0 255
palette 1 0 0 255 255
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 1111111110000000
color 1111111100000000
color 1111111000000000
color 1111110000000000
color 1111000000000000
color 1110000000000000
color 1100000000000000
color 1000000000000000
end
case u32_base_negative
fetch 6 7 8
palette 0 0 0 0 255
palette 1 0 0 255 255
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 1111111110000000
color 1111111100000000
color 1111111000000000
color 1111110000000000
color 1111000000000000
color 1110000000000000
color 1100000000000000
color 1000000000000000
end
case reversed_winding
fetch 2 1 0
palette 0 255 0 0 255
palette 1 0 0 0 255
color 0000000000000001
color 0000000000000011
color 0000000000000111
color 0000000000011111
color 0000000000111111
color 0000000001111111
color 0000000111111111
color 0000001111111111
color 0000011111111111
color 0001111111111111
color 0011111111111111
color 0111111111111111
color 1111111111111111
color 1111111111111111
color 1111111111111111
color 1111111111111111
end
case two_triangles_textured
fetch 9 10 11 9 11 12
palette 0 255 0 0 255
palette 1 0 0 255 255
palette 2 0 0 0 0
palette 3 0 255 0 255
palette 4 255 255 255 255
palette 5 255 255 0 255
palette 6 132 130 132 255
palette 7 8 8 8 255
palette 8 0 0 0 255
color 0011001122223333
color 0011001122223333
color 1100110033332222
color 1100110033332222
color 0000111133223344
color 0000111133223344
color 1111000044332233
color 1111000044332233
color 5555555566777766
color 5555555566777766
color 8888888877666677
color 8888888877666677
color 5555555566777766
color 5555555566777766
color 8888888877666677
color 8888888888888888
end
case textured_base_vertex
fetch 9 10 11
palette 0 0 0 0 255
palette 1 255 0 0 255
palette 2 0 0 255 255
palette 3 0 0 0 0
palette 4 0 255 0 255
palette 5 255 255 255 255
palette 6 132 130 132 255
palette 7 8 8 8 255
color 0122112233334444
color 0022112233334444
color 0001221144443333
color 0000221144443333
color 0000022244334455
color 0000002244334455
color 0000000155443344
color 0000000055443344
color 0000000006777766
color 0000000000777766
color 0000000000066677
color 0000000000006677
color 0000000000000766
color 0000000000000066
color 0000000000000007
color 0000000000000000
end
case painter_order
fetch 0 1 2
fetch 3 4 5
fetch 6 7 8
palette 0 255 0 0 255
palette 1 0 0 0 255
palette 2 0 255 0 255
palette 3 0 0 255 255
color 0000000000000001
color 0000000000000011
color 0000000000000111
color 0000222222011111
color 0000222222222222
color 0000222222222221
color 0000022222222211
color 0000022222222111
color 3333333332221111
color 3333333322211111
color 3333333222211111
color 3333332222111111
color 3333122221111111
color 3331112211111111
color 3311112111111111
color 3111111111111111
end
case u32_mixed
fetch 9 10 11 9 11 12
fetch 9 10 11
fetch 0 1 2
palette 0 255 0 0 255
palette 1 0 255 0 255
palette 2 255 255 0 255
palette 3 132 130 132 255
palette 4 0 0 0 255
palette 5 8 8 8 255
color 0000000000000001
color 0000000000000011
color 0000000000000111
color 0000000000011111
color 0000000000111111
color 0000000001111111
color 0000000111111111
color 0000000011111111
color 0000022231111111
color 0002222233111111
color 0044444455311111
color 0444444455331111
color 2222222233555111
color 2222222233555511
color 4444444455333351
color 4444444444444444
end
case flat_two_triangles
fetch 9 10 11 9 11 12
palette 0 0 255 0 255
palette 1 0 0 0 255
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000011111111
end
case textured_first
fetch 0 1 2
palette 0 255 0 0 255
palette 1 0 0 255 255
palette 2 0 0 0 0
palette 3 0 255 0 255
palette 4 0 0 0 255
palette 5 255 255 0 255
color 0011001122223334
color 0011001122223344
color 1100110033332444
color 1100110033344444
color 0000111133444444
color 0000111134444444
color 1111000444444444
color 1111004444444444
color 5555544444444444
color 5554444444444444
color 4444444444444444
color 4444444444444444
color 4444444444444444
color 4444444444444444
color 4444444444444444
color 4444444444444444
end
case u32_high_indices
fetch 9 10 11
palette 0 0 0 0 255
palette 1 255 0 0 255
color 0111111111111111
color 0011111111111111
color 0001111111111111
color 0000111111111111
color 0000011111111111
color 0000001111111111
color 0000000111111111
color 0000000011111111
color 0000000001111111
color 0000000000111111
color 0000000000011111
color 0000000000001111
color 0000000000000111
color 0000000000000011
color 0000000000000001
color 0000000000000000
end
+73
View File
@@ -0,0 +1,73 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! CPU check: the reference index fetch and rasteriser agree with the
//! independently derived expectations for every indexed case. Runs without a GPU.
#[path = "support/indexed_cases.rs"]
mod indexed_cases;
use indexed_cases::{BC1_BLOCKS, Fill, INDICES, SIZE, cases, expected, vertices, wide_indices};
use xenora_ref::depth::{RefFill, RefTexture};
use xenora_ref::indexed::{RefIndexedDraw, RefIndices, fetch, render_indexed};
fn bc1_texels() -> Vec<[u8; 4]> {
let mut texels = vec![[0; 4]; 64];
for (block, bytes) in BC1_BLOCKS.as_chunks::<8>().0.iter().enumerate() {
for (index, texel) in xenora_texture::decode_bc1(*bytes).iter().enumerate() {
texels[((block / 2) * 4 + index / 4) * 8 + (block % 2) * 4 + index % 4] = *texel;
}
}
texels
}
#[test]
fn reference_matches_independent_expectations() {
let texels = bc1_texels();
let texture = RefTexture {
width: 8,
height: 8,
texels: &texels,
};
let wide = wide_indices();
let vertices = vertices();
let (cases, expected) = (cases(), expected());
assert_eq!(cases.len(), 16);
assert_eq!(expected.len(), cases.len());
for (case, want) in cases.iter().zip(&expected) {
assert_eq!(case.name, want.name);
let indices = if case.wide {
RefIndices::U32(&wide)
} else {
RefIndices::U16(&INDICES)
};
let draws: Vec<_> = case
.draws
.iter()
.map(|draw| RefIndexedDraw {
start: draw.start,
count: draw.count,
base_vertex: draw.base_vertex,
fill: match draw.fill {
Fill::Flat(rgba) => RefFill::Flat(rgba),
Fill::Texture => RefFill::Texture,
},
})
.collect();
let fetched: Vec<_> = draws
.iter()
.enumerate()
.map(|(number, draw)| fetch(number, draw, indices, vertices.len()).expect("fetch"))
.collect();
assert_eq!(fetched, want.fetch, "{} fetch", case.name);
let color = render_indexed(
[SIZE, SIZE],
case.clear_color,
&vertices,
indices,
&draws,
Some(texture),
)
.expect("reference render");
assert_eq!(color, want.color, "{} colour", case.name);
}
}
+150
View File
@@ -0,0 +1,150 @@
use xenora_metal::{BlendDraw, BlendFactor, BlendOperation, BlendPass, BlendState, ColorWriteMask};
use xenora_ref::blend::{RefBlend, RefBlendFactor, RefBlendOperation};
use super::blend_cases::{CLEAR, Case, SIZE, cases, expected};
use super::{context, native};
/// Tolerance, fixed before any native measurement: a channel whose exact
/// result is a whole unorm8 value must match exactly; a channel that needs
/// rounding may differ by at most this much, because Metal does not document
/// how it rounds blended unorm values.
const ROUNDING_TOLERANCE: u8 = 1;
fn factor(factor: RefBlendFactor) -> BlendFactor {
match factor {
RefBlendFactor::Zero => BlendFactor::Zero,
RefBlendFactor::One => BlendFactor::One,
RefBlendFactor::SourceColor => BlendFactor::SourceColor,
RefBlendFactor::OneMinusSourceColor => BlendFactor::OneMinusSourceColor,
RefBlendFactor::SourceAlpha => BlendFactor::SourceAlpha,
RefBlendFactor::OneMinusSourceAlpha => BlendFactor::OneMinusSourceAlpha,
RefBlendFactor::DestinationColor => BlendFactor::DestinationColor,
RefBlendFactor::OneMinusDestinationColor => BlendFactor::OneMinusDestinationColor,
RefBlendFactor::DestinationAlpha => BlendFactor::DestinationAlpha,
RefBlendFactor::OneMinusDestinationAlpha => BlendFactor::OneMinusDestinationAlpha,
}
}
fn operation(operation: RefBlendOperation) -> BlendOperation {
match operation {
RefBlendOperation::Add => BlendOperation::Add,
RefBlendOperation::Subtract => BlendOperation::Subtract,
RefBlendOperation::ReverseSubtract => BlendOperation::ReverseSubtract,
RefBlendOperation::Min => BlendOperation::Min,
RefBlendOperation::Max => BlendOperation::Max,
}
}
fn state(blend: RefBlend) -> BlendState {
BlendState {
source_rgb: factor(blend.source_rgb),
destination_rgb: factor(blend.destination_rgb),
rgb_operation: operation(blend.rgb_operation),
source_alpha: factor(blend.source_alpha),
destination_alpha: factor(blend.destination_alpha),
alpha_operation: operation(blend.alpha_operation),
}
}
fn metal_draws(case: &Case) -> Vec<BlendDraw> {
case.draws
.iter()
.map(|draw| BlendDraw {
positions: draw.positions,
color: draw.color,
blend: draw.blend.map(state),
write_mask: ColorWriteMask {
red: draw.mask[0],
green: draw.mask[1],
blue: draw.mask[2],
alpha: draw.mask[3],
},
})
.collect()
}
/// Each case's native colour must equal the independently derived image,
/// per channel: exactly where the exact result is a whole unorm8 value, and
/// within [`ROUNDING_TOLERANCE`] where it needs rounding.
#[test]
fn blend_known_answers() {
let gpu = context();
let (cases, expected) = (cases(), expected());
assert_eq!(cases.len(), expected.len());
let (mut rounded, mut off_by_one, mut largest) = (0usize, 0usize, 0u8);
for (case, want) in cases.iter().zip(&expected) {
assert_eq!(case.name, want.name);
let draws = metal_draws(case);
let color = native(gpu.render_blend(&BlendPass {
extent: [SIZE, SIZE],
clear_color: CLEAR,
draws: &draws,
}));
assert_eq!(color.len(), SIZE * SIZE * 4);
for (index, ((pixel, wanted), exact)) in color
.as_chunks::<4>()
.0
.iter()
.zip(&want.color)
.zip(&want.exact)
.enumerate()
{
let (x, y) = (index % SIZE, index / SIZE);
for channel in 0..4 {
let difference = pixel[channel].abs_diff(wanted[channel]);
let allowed = if exact[channel] {
0
} else {
ROUNDING_TOLERANCE
};
assert!(
difference <= allowed,
"{} at ({x}, {y}) channel {channel}: {pixel:?} vs {wanted:?} (allowed {allowed})",
case.name
);
if !exact[channel] {
rounded += 1;
off_by_one += usize::from(difference == 1);
largest = largest.max(difference);
}
}
}
}
println!(
"checked {} blend passes; {rounded} rounded channels, {off_by_one} off by one, largest difference {largest}",
cases.len()
);
}
#[test]
fn too_many_blend_draws_are_rejected() {
let gpu = context();
let draw = BlendDraw {
positions: [
[-1.0, -1.0, 0.5, 1.0],
[3.0, -1.0, 0.5, 1.0],
[-1.0, 3.0, 0.5, 1.0],
],
color: [255; 4],
blend: None,
write_mask: ColorWriteMask::ALL,
};
let error = gpu
.render_blend(&BlendPass {
extent: [SIZE, SIZE],
clear_color: CLEAR,
draws: &[draw; 17],
})
.expect_err("17 draws must be rejected");
assert!(error.to_string().contains("at most 16 draws"), "{error}");
let mut bad = draw;
bad.positions[1][0] = f32::NAN;
let error = gpu
.render_blend(&BlendPass {
extent: [SIZE, SIZE],
clear_color: CLEAR,
draws: &[bad],
})
.expect_err("non-finite positions must be rejected");
assert!(error.to_string().contains("finite"), "{error}");
}
+151
View File
@@ -0,0 +1,151 @@
use xenora_metal::{DepthCompare, DepthDraw, DepthFill, DepthPass, DepthState};
use xenora_ref::depth::CompareFunction;
use xenora_texture::{Bc1Upload, Bc1UploadDesc};
use super::depth_cases::{BC1_BLOCKS, Case, Fill, GREEN, SIZE, cases, expected};
use super::{context, native};
fn compare(function: CompareFunction) -> DepthCompare {
match function {
CompareFunction::Never => DepthCompare::Never,
CompareFunction::Less => DepthCompare::Less,
CompareFunction::Equal => DepthCompare::Equal,
CompareFunction::LessEqual => DepthCompare::LessEqual,
CompareFunction::Greater => DepthCompare::Greater,
CompareFunction::NotEqual => DepthCompare::NotEqual,
CompareFunction::GreaterEqual => DepthCompare::GreaterEqual,
CompareFunction::Always => DepthCompare::Always,
}
}
fn metal_draws(case: &Case) -> Vec<DepthDraw> {
case.draws
.iter()
.map(|draw| DepthDraw {
positions: draw.positions,
fill: match draw.fill {
Fill::Flat(rgba) => DepthFill::Flat(rgba),
Fill::Texture => DepthFill::Bc1Texture,
},
depth: DepthState {
compare: compare(draw.compare),
write: draw.write,
},
})
.collect()
}
fn bc1_upload() -> Bc1Upload<'static> {
Bc1Upload::new(
&BC1_BLOCKS,
Bc1UploadDesc {
width: 8,
height: 8,
mips: 1,
layers: 1,
format: 1,
usage: 1,
row_pitch: 16,
slice_pitch: 32,
},
)
.expect("valid BC1 upload")
}
/// Each case's native colour and depth must equal the independently derived
/// values (which the CPU reference also reproduces in `depth_reference`).
/// Colour and depth are compared separately, per pixel.
#[test]
fn depth_attachment_known_answers() {
let gpu = context();
let upload = bc1_upload();
let expected = expected();
let cases = cases();
assert_eq!(cases.len(), expected.len());
let mut checked = 0;
for (case, want) in cases.iter().zip(&expected) {
assert_eq!(case.name, want.name);
let draws = metal_draws(case);
let output = native(
gpu.render_depth(&DepthPass {
extent: [SIZE, SIZE],
clear_color: case.clear_color,
clear_depth: case.clear_depth,
draws: &draws,
// Only the textured case needs BC support, so a device without it
// fails that case alone, as a capability error.
texture: case
.draws
.iter()
.any(|draw| matches!(draw.fill, Fill::Texture))
.then_some(&upload),
}),
);
for (index, (pixel, wanted)) in output
.color
.as_chunks::<4>()
.0
.iter()
.zip(&want.color)
.enumerate()
{
let (x, y) = (index % SIZE, index / SIZE);
assert_eq!(pixel, wanted, "{} colour at ({x}, {y})", case.name);
}
assert_eq!(output.color.len(), SIZE * SIZE * 4);
match (&output.depth, &want.depth) {
(Some(depth), Some(wanted)) => {
assert_eq!(depth.len(), wanted.len());
for (index, (value, wanted)) in depth.iter().zip(wanted).enumerate() {
let (x, y) = (index % SIZE, index / SIZE);
assert_eq!(
value.to_bits(),
wanted.to_bits(),
"{} depth at ({x}, {y}): {value} vs {wanted}",
case.name
);
}
}
(None, None) => {}
(got, want) => panic!("{}: depth presence {got:?} vs {want:?}", case.name),
}
checked += 1;
}
println!("checked {checked} depth passes of {} pixels", SIZE * SIZE);
}
#[test]
fn depth_state_without_attachment_is_rejected() {
let gpu = context();
let draw = DepthDraw {
positions: [
[-1.0, -1.0, 0.5, 1.0],
[3.0, -1.0, 0.5, 1.0],
[-1.0, 3.0, 0.5, 1.0],
],
fill: DepthFill::Flat(GREEN),
depth: DepthState {
compare: DepthCompare::Less,
write: false,
},
};
let pass = |clear_depth, draw: DepthDraw| {
gpu.render_depth(&DepthPass {
extent: [SIZE, SIZE],
clear_color: [0; 4],
clear_depth,
draws: &[draw],
texture: None,
})
};
let error = pass(None, draw).expect_err("depth test without attachment");
assert!(!error.is_capability_unavailable(), "{error}");
for clear in [-0.25, 1.5, f32::NAN] {
pass(Some(clear), draw).expect_err("clear depth outside 0..=1");
}
let textured = DepthDraw {
fill: DepthFill::Bc1Texture,
..draw
};
pass(Some(1.0), textured).expect_err("textured draw without texture");
}
+165
View File
@@ -0,0 +1,165 @@
use xenora_metal::{DepthFill, IndexBuffer, IndexedDraw, IndexedPass};
use xenora_texture::{Bc1Upload, Bc1UploadDesc};
use super::indexed_cases::{
BC1_BLOCKS, Case, Fill, INDICES, SIZE, cases, expected, vertices, wide_indices,
};
use super::{context, native};
fn metal_draws(case: &Case) -> Vec<IndexedDraw> {
case.draws
.iter()
.map(|draw| IndexedDraw {
start_index: draw.start,
index_count: draw.count,
base_vertex: draw.base_vertex,
fill: match draw.fill {
Fill::Flat(rgba) => DepthFill::Flat(rgba),
Fill::Texture => DepthFill::Bc1Texture,
},
})
.collect()
}
fn bc1_upload() -> Bc1Upload<'static> {
Bc1Upload::new(
&BC1_BLOCKS,
Bc1UploadDesc {
width: 8,
height: 8,
mips: 1,
layers: 1,
format: 1,
usage: 1,
row_pitch: 16,
slice_pitch: 32,
},
)
.expect("valid BC1 upload")
}
/// Each case's native colour must equal the independently derived image
/// (which the CPU reference also reproduces in `indexed_reference`), per pixel.
/// Metal fetches the vertices itself from the index buffer, start offset and
/// base vertex of each `drawIndexedPrimitives` call.
#[test]
fn indexed_draw_known_answers() {
let gpu = context();
let upload = bc1_upload();
let vertices = vertices();
let wide = wide_indices();
let (cases, expected) = (cases(), expected());
assert_eq!(cases.len(), expected.len());
let mut checked = 0;
for (case, want) in cases.iter().zip(&expected) {
assert_eq!(case.name, want.name);
// One independently derived fetch list per draw keeps the fixtures aligned.
assert_eq!(want.fetch.len(), case.draws.len(), "{}", case.name);
let draws = metal_draws(case);
let color = native(
gpu.render_indexed(&IndexedPass {
extent: [SIZE, SIZE],
clear_color: case.clear_color,
vertices: &vertices,
indices: if case.wide {
IndexBuffer::U32(&wide)
} else {
IndexBuffer::U16(&INDICES)
},
draws: &draws,
// Only textured cases need BC support, so a device without it fails
// those cases alone, as a capability error.
texture: case
.draws
.iter()
.any(|draw| draw.fill == Fill::Texture)
.then_some(&upload),
}),
);
assert_eq!(color.len(), SIZE * SIZE * 4);
for (index, (pixel, wanted)) in color.as_chunks::<4>().0.iter().zip(&want.color).enumerate()
{
let (x, y) = (index % SIZE, index / SIZE);
assert_eq!(pixel, wanted, "{} colour at ({x}, {y})", case.name);
}
checked += 1;
}
println!("checked {checked} indexed passes of {} pixels", SIZE * SIZE);
}
/// Every malformed draw is rejected before encoding, with its own reason.
#[test]
fn invalid_indexed_draws_are_rejected() {
let gpu = context();
let vertices = vertices();
let restart = [0, 1, u16::MAX];
let flat = DepthFill::Flat([255; 4]);
let run = |indices, start_index, index_count, base_vertex, fill| {
gpu.render_indexed(&IndexedPass {
extent: [SIZE, SIZE],
clear_color: [0; 4],
vertices: &vertices,
indices,
draws: &[IndexedDraw {
start_index,
index_count,
base_vertex,
fill,
}],
texture: None,
})
.expect_err("invalid draw must be rejected")
.to_string()
};
let short = IndexBuffer::U16(&INDICES);
let count = "index count must be a nonzero multiple of 3";
let range = "index range past the index buffer";
let outside = "outside the vertex buffer";
let restart_value = "primitive-restart value";
for (reason, error, wanted) in [
// First: Metal itself would draw this one, so only the check rejects it.
(
"count not a multiple of 3",
run(short, 0, 4, 0, flat),
count,
),
("zero count", run(short, 0, 0, 0, flat), count),
("range past buffer", run(short, 19, 3, 0, flat), range),
("start overflow", run(short, usize::MAX, 3, 0, flat), range),
("negative vertex", run(short, 0, 3, -1, flat), outside),
("vertex past buffer", run(short, 9, 3, 2, flat), outside),
(
"32-bit index past buffer",
run(IndexBuffer::U32(&[0, 1, 13]), 0, 3, 0, flat),
outside,
),
(
"16-bit restart value",
run(IndexBuffer::U16(&restart), 0, 3, 0, flat),
restart_value,
),
// In range after the base vertex, but still the raw restart value.
(
"16-bit restart value with base vertex",
run(IndexBuffer::U16(&[65533, 65534, 65535]), 0, 3, -65533, flat),
restart_value,
),
(
"32-bit restart value",
run(IndexBuffer::U32(&[0, 1, u32::MAX]), 0, 3, 0, flat),
restart_value,
),
("base overflow", run(short, 0, 3, i32::MAX, flat), outside),
(
"texture missing",
run(short, 0, 3, 0, DepthFill::Bc1Texture),
"textured draw without texture",
),
] {
println!("{reason}: {error}");
assert!(
error.contains("indexed pass") && error.contains(wanted),
"{reason}: {error}"
);
}
}
@@ -0,0 +1,404 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Native Metal upload and readback of original BC2 and BC3 blocks.
//!
//! Every block below was written for this test. The full-texel reference is
//! the `xenora-texture` CPU decoder; the anchor texels are worked by hand from
//! the Microsoft Direct3D 11 block-compression documentation (BC2, BC3) and
//! the Khronos Data Format Specification 1.3 (S3TC DXT3/DXT5). Apple's GPU
//! decoder is the value under test, so expected and actual values come from
//! different decoders.
use super::{context, native};
use xenora_texture::{BcAlphaFormat, BcAlphaUpload, BcAlphaUploadDesc, decode_bc2, decode_bc3};
/// The specifications define colour and BC3 alpha interpolation in real
/// numbers, and the CPU reference truncates them. On an Apple M5 Pro the
/// native decoder's interpolated values lie within 8/7 (1.143) codes of the real
/// value (they match 6-bit fixed-point weights), so they can sit two codes
/// above the truncated reference: 124 against 122 for BC3 alpha
/// (4 * 200 + 3 * 20) / 7 = 122.86. Endpoints, BC2 alpha and BC3's fixed
/// 0 and 255 are exact and are pinned by the anchor checks.
const TOLERANCE: u8 = 2;
/// Bound for anchors against the real-number value of an interpolated code.
const REAL_TOLERANCE: f64 = 1.5;
fn assert_near(label: &str, actual: u8, real: f64) {
assert!(
(f64::from(actual) - real).abs() <= REAL_TOLERANCE,
"{label}: got {actual}, real value {real:.2}"
);
}
const WIDTH: usize = 5;
const HEIGHT: usize = 5;
const ROW_PITCH: usize = 48;
const SLICE_PITCH: usize = 112;
/// Colour half: two little-endian RGB565 endpoints, then 2-bit indices.
/// Every row of 0xe4 selects palette entries 0, 1, 2, 3 from left to right.
fn colour((first, second): (u16, u16)) -> [u8; 8] {
let [a, b] = first.to_le_bytes();
let [c, d] = second.to_le_bytes();
[a, b, c, d, 0xe4, 0xe4, 0xe4, 0xe4]
}
/// BC3 alpha half whose texel `t` selects palette entry `(t + 6) % 8`, so
/// every row starts with the indices 6 and 7 and a full block uses all eight.
fn bc3_alpha(first: u8, second: u8) -> [u8; 8] {
let bits = (0..16u64).fold(0, |bits, texel| bits | (((texel + 6) % 8) << (3 * texel)));
let i = bits.to_le_bytes();
[first, second, i[0], i[1], i[2], i[3], i[4], i[5]]
}
fn block(alpha: [u8; 8], colour: [u8; 8]) -> [u8; 16] {
let mut block = [0; 16];
block[..8].copy_from_slice(&alpha);
block[8..].copy_from_slice(&colour);
block
}
// First endpoint greater: red over blue.
const DESCENDING: (u16, u16) = (0xf800, 0x001f);
// First endpoint smaller, with odd channel values that exercise rounding.
const ASCENDING: (u16, u16) = (0x52aa, 0xad55);
// Equal endpoints: BC1 would decode index 3 as transparent black.
const EQUAL: (u16, u16) = (0x07e0, 0x07e0);
/// White with zero alpha (BC2 nibbles 0; BC3 endpoints 0 and 0) in every
/// padding slot, so a wrong row or slice pitch reads visibly wrong texels.
const PAD: [u8; 16] = [0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff, 0, 0, 0, 0];
/// Logical blocks of one layer: the 2×2 base-level grid, then mip 1.
type Layer = [[u8; 16]; 5];
/// Two layers of a 5×5 texture with two mips. Each subresource has seven
/// physical blocks: rows of two logical blocks plus one padding block, a
/// padding block that closes the slice, and mip 1 uses only its block zero.
fn upload_bytes(layers: [Layer; 2]) -> Vec<u8> {
let mut bytes = Vec::new();
for [b0, b1, b2, b3, small] in layers {
for slot in [b0, b1, PAD, b2, b3, PAD, PAD] {
bytes.extend_from_slice(&slot);
}
for slot in [small, PAD, PAD, PAD, PAD, PAD, PAD] {
bytes.extend_from_slice(&slot);
}
}
assert_eq!(bytes.len(), 2 * 2 * SLICE_PITCH);
bytes
}
/// Per-channel tolerance of each texel of `block`: zero where the index
/// selects a stored endpoint, a BC2 alpha nibble or BC3's fixed 0 or 255,
/// and [`TOLERANCE`] only for interpolated codes.
fn tolerances(format: BcAlphaFormat, block: [u8; 16]) -> [[u8; 4]; 16] {
let colour = u32::from_le_bytes([block[12], block[13], block[14], block[15]]);
let mut alpha_bits = [0; 8];
alpha_bits[..6].copy_from_slice(&block[2..8]);
let alpha_indices = u64::from_le_bytes(alpha_bits);
let six_value = block[0] <= block[1];
std::array::from_fn(|t| {
let rgb = if (colour >> (2 * t)) & 3 < 2 {
0
} else {
TOLERANCE
};
let index = (alpha_indices >> (3 * t)) & 7;
let a = match format {
BcAlphaFormat::Bc2 => 0,
BcAlphaFormat::Bc3 if index < 2 || (six_value && index >= 6) => 0,
BcAlphaFormat::Bc3 => TOLERANCE,
};
[rgb, rgb, rgb, a]
})
}
/// Crops a row-major grid of blocks to a `width`×`height` level of CPU-decoded
/// words (red in the lowest byte, as the readback kernel writes them), each
/// with its per-channel tolerance.
fn reference(
format: BcAlphaFormat,
decode: fn([u8; 16]) -> [[u8; 4]; 16],
blocks: &[[u8; 16]],
blocks_x: usize,
(width, height): (usize, usize),
) -> Vec<(u32, [u8; 4])> {
let mut texels = Vec::new();
for y in 0..height {
for x in 0..width {
let block = blocks[(y / 4) * blocks_x + x / 4];
let t = (y % 4) * 4 + x % 4;
let word = u32::from_le_bytes(decode(block)[t]);
texels.push((word, tolerances(format, block)[t]));
}
}
texels
}
fn alpha(word: u32) -> u8 {
word.to_le_bytes()[3]
}
/// Returns the largest per-channel difference, failing on any channel above
/// its tolerance with the texel index and both values.
fn assert_close(label: &str, actual: &[u32], expected: &[(u32, [u8; 4])]) -> u8 {
assert_eq!(actual.len(), expected.len(), "{label}: texel count");
let mut worst = 0;
for (texel, (&got, &(want, tolerance))) in actual.iter().zip(expected).enumerate() {
for ((g, w), limit) in got
.to_le_bytes()
.into_iter()
.zip(want.to_le_bytes())
.zip(tolerance)
{
assert!(
g.abs_diff(w) <= limit,
"{label}: texel {texel} got {got:#010x}, want {want:#010x} (per-channel limit {tolerance:?})"
);
worst = worst.max(g.abs_diff(w));
}
}
worst
}
/// GPU reads of both layers: `[layer][mip]`.
type Reads = [[Vec<u32>; 2]; 2];
/// Uploads both layers, reads all four subresources on the GPU, compares
/// them with the CPU decoder and returns the reads with the worst difference.
fn read_and_compare(
format: BcAlphaFormat,
decode: fn([u8; 16]) -> [[u8; 4]; 16],
layers: [Layer; 2],
) -> (Reads, u8) {
let bytes = upload_bytes(layers);
let upload = BcAlphaUpload::new(
&bytes,
BcAlphaUploadDesc {
width: WIDTH,
height: HEIGHT,
mips: 2,
layers: 2,
format,
row_pitch: ROW_PITCH,
slice_pitch: SLICE_PITCH,
},
)
.unwrap();
let gpu = context();
let mut worst = 0;
let reads = std::array::from_fn(|layer| {
let base = native(gpu.read_bc_alpha_upload(&upload, layer, 0));
let expected = reference(format, decode, &layers[layer][..4], 2, (WIDTH, HEIGHT));
let label = format!("{format:?} layer {layer}");
worst = worst.max(assert_close(&format!("{label} mip 0"), &base, &expected));
let small = native(gpu.read_bc_alpha_upload(&upload, layer, 1));
let expected = reference(format, decode, &layers[layer][4..], 1, (2, 2));
worst = worst.max(assert_close(&format!("{label} mip 1"), &small, &expected));
[base, small]
});
for (layer, mip) in [(2, 0), (0, 2)] {
assert_eq!(
gpu.read_bc_alpha_upload(&upload, layer, mip)
.unwrap_err()
.operation,
"texture subresource"
);
}
(reads, worst)
}
#[test]
fn reads_pitched_bc2_explicit_alpha_across_mips_and_layers() {
// Nibble t in texel t, low nibble first: alpha t * 17.
let ramp = [0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe];
let reverse = ramp.map(|byte: u8| !byte);
let opaque = [0xff; 8];
let [descending, ascending, equal] = [DESCENDING, ASCENDING, EQUAL].map(colour);
let (reads, worst) = read_and_compare(
BcAlphaFormat::Bc2,
decode_bc2,
[
[
block(ramp, descending),
block(reverse, ascending),
block(opaque, equal),
block(ramp, ascending),
block(reverse, descending),
],
[
block(opaque, ascending),
block(ramp, equal),
block(reverse, descending),
block(opaque, descending),
block(ramp, equal),
],
],
);
// Hand-derived anchors, independent of the CPU decoder.
let base = &reads[0][0];
// (0, 0): red endpoint, nibble 0. (1, 0): blue endpoint, nibble 1.
assert_eq!(base[0], 0x0000_00ff);
assert_eq!(base[1], 0x11ff_0000);
// (0, 2) is texel 8 of block 0: red endpoint, nibble 8 -> 0x88.
assert_eq!(base[2 * WIDTH], 0x8800_00ff);
// (3, 3) is texel 15 of block 0: nibble 15 -> opaque.
assert_eq!(alpha(base[3 * WIDTH + 3]), 0xff);
// (4, 0) is texel 0 of block 1: reversed ramp, nibble 15.
assert_eq!(alpha(base[4]), 0xff);
// (3, 4) is index 3 of block 2's equal green endpoints: opaque green,
// not BC1's transparent black.
assert_eq!(base[4 * WIDTH + 3], 0xff00_ff00);
// Layer 1 mip 1: green endpoints, ramp nibbles 0, 1, 4, 5.
assert_eq!(
reads[1][1],
[0x0000_ff00, 0x1100_ff00, 0x4400_ff00, 0x5500_ff00]
);
println!("checked 58 BC2 texels from four subresources, worst channel difference {worst}");
}
#[test]
fn reads_pitched_bc3_interpolated_alpha_across_mips_and_layers() {
// First endpoint greater: eight-value palette.
let eight = bc3_alpha(200, 20);
// First endpoint smaller: six-value palette with fixed 0 and 255.
let six = bc3_alpha(20, 200);
// Equal endpoints also select the six-value palette.
let level = bc3_alpha(128, 128);
let [descending, ascending, equal] = [DESCENDING, ASCENDING, EQUAL].map(colour);
let (reads, worst) = read_and_compare(
BcAlphaFormat::Bc3,
decode_bc3,
[
[
block(eight, descending),
block(six, ascending),
block(level, equal),
block(eight, ascending),
block(six, descending),
],
[
block(six, equal),
block(eight, ascending),
block(level, descending),
block(six, ascending),
block(eight, equal),
],
],
);
// Hand-derived anchors, independent of the CPU decoder.
let base = &reads[0][0];
let a = |x: usize, y: usize| alpha(base[y * WIDTH + x]);
// Block 0, eight-value: row 0 holds indices 6, 7, 0, 1, and row 1
// indices 2, 3, 4, 5, each (k = index - 1) ((7 - k) * 200 + k * 20) / 7.
assert_near("index 6", a(0, 0), (2.0 * 200.0 + 5.0 * 20.0) / 7.0);
assert_near("index 7", a(1, 0), (200.0 + 6.0 * 20.0) / 7.0);
for (x, k) in (0..4).zip(1..) {
let real = f64::from((7 - k) * 200 + k * 20) / 7.0;
assert_near(&format!("index {}", k + 1), a(x, 1), real);
}
// Then the endpoints themselves, exactly; texel (0, 0) is the red endpoint.
assert_eq!([a(2, 0), a(3, 0)], [200, 20]);
assert_eq!(base[0] & 0x00ff_ffff, 0x0000_00ff);
// Block 1, six-value: column 4 holds indices 6, 2, 6, 2. Index 6 is the
// fixed 0 and index 2 is (4 * 20 + 200) / 5 = 56.
assert_eq!([a(4, 0), a(4, 2)], [0, 0]);
assert_near("six-value index 2", a(4, 1), 56.0);
assert_near("six-value index 2", a(4, 3), 56.0);
// Block 2, equal endpoints of 128: row 4 holds indices 6, 7, 0, 1, so the
// six-value mode shows as the fixed 0 and 255.
assert_eq!([a(0, 4), a(1, 4), a(2, 4), a(3, 4)], [0, 255, 128, 128]);
// Mip 1, six-value: indices 6, 7, 2, 3 -> 0, 255, 56, (3 * 20 + 2 * 200) / 5 = 92.
let small: Vec<_> = reads[0][1].iter().copied().map(alpha).collect();
assert_eq!(small[..2], [0, 255]);
assert_near("six-value index 2", small[2], 56.0);
assert_near("six-value index 3", small[3], 92.0);
println!("checked 58 BC3 texels from four subresources, worst channel difference {worst}");
}
/// Reads one-mip, one-layer uploads of `width`×`height` from `blocks` laid
/// out with `row_pitch`, comparing with the CPU decoder.
fn read_edge(
format: BcAlphaFormat,
decode: fn([u8; 16]) -> [[u8; 4]; 16],
blocks: &[[u8; 16]],
(width, height, row_pitch): (usize, usize, usize),
) -> Vec<u32> {
let bytes = blocks.as_flattened();
let upload = BcAlphaUpload::new(
bytes,
BcAlphaUploadDesc {
width,
height,
mips: 1,
layers: 1,
format,
row_pitch,
slice_pitch: bytes.len(),
},
)
.unwrap();
let actual = native(context().read_bc_alpha_upload(&upload, 0, 0));
let expected = reference(format, decode, blocks, width.div_ceil(4), (width, height));
assert_close(&format!("{format:?} {width}x{height}"), &actual, &expected);
actual
}
#[test]
fn reads_bc2_and_bc3_edge_blocks() {
let ramp = [0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe];
let reverse = ramp.map(|byte: u8| !byte);
let [descending, equal] = [DESCENDING, EQUAL].map(colour);
// 5×3 is one row of two blocks: Metal receives a zero row stride, and
// both blocks are cut at row 3, the second also at column 1. The row
// pitch keeps one padding block.
let wide = (5, 3, 48);
let bc2 = read_edge(
BcAlphaFormat::Bc2,
decode_bc2,
&[block(ramp, descending), block(reverse, equal), PAD],
wide,
);
// (0, 0) red, nibble 0; (4, 0) green, reversed nibble 15; (0, 2) red,
// nibble 8; (4, 2) green, reversed nibble 7.
assert_eq!(
[bc2[0], bc2[4], bc2[10], bc2[14]],
[0x0000_00ff, 0xff00_ff00, 0x8800_00ff, 0x7700_ff00]
);
let bc3 = read_edge(
BcAlphaFormat::Bc3,
decode_bc3,
&[
block(bc3_alpha(200, 20), descending),
block(bc3_alpha(20, 200), equal),
PAD,
],
wide,
);
// Row 0 of block 0 is indices 6, 7, 0, 1: (2, 0) and (3, 0) are the
// endpoints 200 and 20. Column 0 of block 1 is indices 6, 2, 6: green
// with the fixed 0, then (4 * 20 + 200) / 5 = 56.
assert_eq!([alpha(bc3[2]), alpha(bc3[3])], [200, 20]);
assert_eq!([bc3[4], bc3[14]], [0x0000_ff00; 2]);
assert_near("six-value index 2", alpha(bc3[9]), 56.0);
// 1×1 is a single block cut to its first texel.
let one = (1, 1, 16);
let bc2 = read_edge(
BcAlphaFormat::Bc2,
decode_bc2,
&[block(reverse, descending)],
one,
);
assert_eq!(bc2, [0xff00_00ff]);
let bc3 = read_edge(
BcAlphaFormat::Bc3,
decode_bc3,
&[block(bc3_alpha(20, 200), descending)],
one,
);
assert_eq!(bc3, [0x0000_00ff]);
println!("checked 32 BC2 and BC3 texels from 5x3 and 1x1 edge levels");
}
@@ -0,0 +1,535 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Native Metal upload and readback of original BC4 and BC5 blocks.
//!
//! Every block below was written for this test. The full-texel reference is
//! the `xenora-texture` CPU decoder; the anchor texels are worked by hand from
//! the Microsoft Direct3D 11 block-compression documentation (BC4, BC5) and
//! the Khronos Data Format Specification 1.3 (RGTC). Apple's GPU decoder is
//! the value under test, so expected and actual values come from different
//! decoders.
use super::{context, native};
use xenora_texture::{
BcChannelFormat, BcChannelUpload, BcChannelUploadDesc, decode_bc4_snorm, decode_bc4_unorm,
decode_bc5_snorm, decode_bc5_unorm,
};
/// The specifications define interpolation in real numbers and the CPU
/// reference truncates toward zero. On an Apple M5 Pro every format's
/// interpolated codes sit up to two codes from that reference; each test
/// prints its measured worst case. Endpoints and the six-value fixed codes
/// are exact and are pinned by the anchor checks.
const TOLERANCE: u8 = 2;
/// Bound for anchors against the real-number value of an interpolated code.
/// The measured worst on an Apple M5 Pro is 1.71 codes: signed eight-value
/// index 4 of 100 and -100 is (4 * 100 - 3 * 100) / 7 = 14.29 and reads 16.
const REAL_TOLERANCE: f64 = 2.0;
const WIDTH: usize = 5;
const HEIGHT: usize = 5;
/// One 8-byte channel block whose texel `t` selects palette entry
/// `(t + 6) % 8`: every row starts with indices 6 and 7, and a full block
/// uses all eight.
fn channel(first: u8, second: u8) -> [u8; 8] {
let bits = (0..16u64).fold(0, |bits, texel| bits | (((texel + 6) % 8) << (3 * texel)));
let i = bits.to_le_bytes();
[first, second, i[0], i[1], i[2], i[3], i[4], i[5]]
}
fn signed(first: i8, second: i8) -> [u8; 8] {
channel(first.to_le_bytes()[0], second.to_le_bytes()[0])
}
/// Index 0 everywhere at endpoint 0x7f: 127 unsigned or 1.0 signed, so a
/// wrong row or slice pitch reads visibly wrong texels.
const PAD: [u8; 8] = [0x7f, 0x7f, 0, 0, 0, 0, 0, 0];
/// Logical blocks of one layer: the 2×2 base-level grid, then mip 1.
type Layer = [Vec<u8>; 5];
struct Case {
format: BcChannelFormat,
/// Expected little-endian texel words of one block.
reference: fn(&[u8]) -> [u32; 16],
layers: [Layer; 2],
}
fn unorm_word(r: u8, g: u8) -> u32 {
u32::from_le_bytes([r, g, 0, 255])
}
/// Both -128 and -127 decode to -1.0, so the native output is -127 for each.
fn snorm_word(r: i8, g: i8) -> u32 {
let byte = |value: i8| value.max(-127).to_le_bytes()[0];
u32::from_le_bytes([byte(r), byte(g), 0, 127])
}
fn bc4_unorm(block: &[u8]) -> [u32; 16] {
decode_bc4_unorm(block.try_into().unwrap()).map(|r| unorm_word(r, 0))
}
fn bc4_snorm(block: &[u8]) -> [u32; 16] {
decode_bc4_snorm(block.try_into().unwrap()).map(|r| snorm_word(r, 0))
}
fn bc5_unorm(block: &[u8]) -> [u32; 16] {
decode_bc5_unorm(block.try_into().unwrap()).map(|[r, g]| unorm_word(r, g))
}
fn bc5_snorm(block: &[u8]) -> [u32; 16] {
decode_bc5_snorm(block.try_into().unwrap()).map(|[r, g]| snorm_word(r, g))
}
fn dual(red: [u8; 8], green: [u8; 8]) -> Vec<u8> {
[red, green].concat()
}
/// Seven physical blocks per subresource: rows of two logical blocks plus
/// one padding block, a padding block closing the slice, and mip 1 using
/// only its block zero. Returns the bytes with the row and slice pitch.
fn upload_bytes(format: BcChannelFormat, layers: &[Layer; 2]) -> (Vec<u8>, usize, usize) {
let block = format.block_bytes();
let pad = PAD.repeat(block / PAD.len());
let mut bytes = Vec::new();
for [b0, b1, b2, b3, small] in layers {
for slot in [b0, b1, &pad, b2, b3, &pad, &pad] {
bytes.extend_from_slice(slot);
}
bytes.extend_from_slice(small);
for _ in 0..6 {
bytes.extend_from_slice(&pad);
}
}
(bytes, 3 * block, 7 * block)
}
/// Crops decoded blocks (a row-major block grid) to a `width`×`height` level.
fn crop<T: Copy>(blocks: &[[T; 16]], blocks_x: usize, width: usize, height: usize) -> Vec<T> {
let mut texels = Vec::new();
for y in 0..height {
for x in 0..width {
texels.push(blocks[(y / 4) * blocks_x + x / 4][(y % 4) * 4 + x % 4]);
}
}
texels
}
/// Per-channel distances; signed formats compare bytes as two's complement.
fn distances(format: BcChannelFormat, got: u32, want: u32) -> [u8; 4] {
let signed = matches!(
format,
BcChannelFormat::Bc4Snorm | BcChannelFormat::Bc5Snorm
);
let (got, want) = (got.to_le_bytes(), want.to_le_bytes());
std::array::from_fn(|c| {
if signed {
(got[c] as i8).abs_diff(want[c] as i8)
} else {
got[c].abs_diff(want[c])
}
})
}
/// Per-channel tolerance of each texel: zero where a channel block's index
/// selects a stored endpoint or a six-value fixed code (and for the constant
/// channels), [`TOLERANCE`] only for interpolated codes.
fn tolerances(format: BcChannelFormat, block: &[u8]) -> [[u8; 4]; 16] {
let signed = matches!(
format,
BcChannelFormat::Bc4Snorm | BcChannelFormat::Bc5Snorm
);
let limit = |channel: &[u8], t: usize| {
let mut bits = [0; 8];
bits[..6].copy_from_slice(&channel[2..8]);
let index = (u64::from_le_bytes(bits) >> (3 * t)) & 7;
let six_value = if signed {
channel[0] as i8 <= channel[1] as i8
} else {
channel[0] <= channel[1]
};
if index < 2 || (six_value && index >= 6) {
0
} else {
TOLERANCE
}
};
std::array::from_fn(|t| {
let green = if block.len() == 16 {
limit(&block[8..], t)
} else {
0
};
[limit(&block[..8], t), green, 0, 0]
})
}
/// Asserts every channel is within its tolerance and returns the worst.
fn check_texels(
label: &str,
format: BcChannelFormat,
actual: &[u32],
expected: &[(u32, [u8; 4])],
) -> u8 {
assert_eq!(actual.len(), expected.len(), "{label}: texel count");
let mut worst = 0;
for (texel, (&got, &(want, limit))) in actual.iter().zip(expected).enumerate() {
let diff = distances(format, got, want);
assert!(
diff.iter().zip(limit).all(|(&d, l)| d <= l),
"{label}: texel {texel} got {got:#010x}, want {want:#010x} (per-channel limit {limit:?})"
);
worst = worst.max(*diff.iter().max().unwrap());
}
worst
}
/// CPU reference words of `block` with their per-channel tolerances.
fn expected_block(
case_format: BcChannelFormat,
reference: fn(&[u8]) -> [u32; 16],
block: &[u8],
) -> [(u32, [u8; 4]); 16] {
let words = reference(block);
let limits = tolerances(case_format, block);
std::array::from_fn(|t| (words[t], limits[t]))
}
/// GPU reads of both layers: `[layer][mip]`.
type Reads = [[Vec<u32>; 2]; 2];
/// Uploads both layers, reads all four subresources on the GPU, compares
/// them with the CPU decoder and returns the reads with the worst difference.
fn read_and_compare(case: &Case) -> (Reads, u8) {
let (bytes, row_pitch, slice_pitch) = upload_bytes(case.format, &case.layers);
let upload = BcChannelUpload::new(
&bytes,
BcChannelUploadDesc {
width: WIDTH,
height: HEIGHT,
mips: 2,
layers: 2,
format: case.format,
row_pitch,
slice_pitch,
},
)
.unwrap();
let gpu = context();
let mut worst = 0;
let reads = std::array::from_fn(|layer| {
let decoded: Vec<_> = case.layers[layer]
.iter()
.map(|block| expected_block(case.format, case.reference, block))
.collect();
let levels = [
crop(&decoded[..4], 2, WIDTH, HEIGHT),
crop(&decoded[4..], 1, 2, 2),
];
std::array::from_fn(|mip| {
let actual = native(gpu.read_bc_channel_upload(&upload, layer, mip as u32));
let expected = &levels[mip];
let label = format!("{:?} layer {layer} mip {mip}", case.format);
worst = worst.max(check_texels(&label, case.format, &actual, expected));
actual
})
});
for (layer, mip) in [(2, 0), (0, 2)] {
assert_eq!(
gpu.read_bc_channel_upload(&upload, layer, mip)
.unwrap_err()
.operation,
"texture subresource"
);
}
(reads, worst)
}
fn assert_near(label: &str, actual: f64, real: f64) {
assert!(
(actual - real).abs() <= REAL_TOLERANCE,
"{label}: got {actual}, real value {real:.2}"
);
}
fn byte(word: u32, channel: usize) -> u8 {
word.to_le_bytes()[channel]
}
fn sbyte(word: u32, channel: usize) -> i8 {
byte(word, channel) as i8
}
/// Unsigned blocks: eight-value (200 > 20), six-value (20 < 200), extremes
/// in both orders, and equal endpoints, which select the six-value mode.
fn unsigned_blocks() -> [[u8; 8]; 5] {
[
channel(200, 20),
channel(20, 200),
channel(128, 128),
channel(255, 0),
channel(0, 255),
]
}
/// Signed blocks: eight-value (100 > -100), six-value (-100 < 100), equal
/// zeros, and the extremes 127 and -128 in both orders.
fn signed_blocks() -> [[u8; 8]; 5] {
[
signed(100, -100),
signed(-100, 100),
signed(0, 0),
signed(127, -128),
signed(-128, 127),
]
}
/// Checks the hand-derived values of the base level of layer 0, whose
/// blocks are the five channel blocks in order.
fn unsigned_anchors(base: &[u32], channel: usize) {
let v = |x: usize, y: usize| byte(base[y * WIDTH + x], channel);
// Block 0, eight-value 200, 20: row 0 indices 6, 7, 0, 1, row 1 2..=5.
assert_eq!([v(2, 0), v(3, 0)], [200, 20]);
for (x, k) in (0..2).chain(0..4).zip([5, 6, 1, 2, 3, 4]) {
let y = usize::from(k < 5);
let real = f64::from((7 - k) * 200 + k * 20) / 7.0;
assert_near(
&format!("eight-value index {}", k + 1),
v(x, y).into(),
real,
);
}
// Block 1, six-value 20, 200: column 4 holds indices 6, 2, 6, 2; index 6
// is the fixed 0 and index 2 is (4 * 20 + 200) / 5 = 56.
assert_eq!([v(4, 0), v(4, 2)], [0, 0]);
assert_near("six-value index 2", v(4, 1).into(), 56.0);
// Block 2, equal 128: row 4 indices 6, 7, 0, 1 -> fixed 0 and 255.
assert_eq!([v(0, 4), v(1, 4), v(2, 4), v(3, 4)], [0, 255, 128, 128]);
// Block 3, 255 > 0: texel (4, 4) is its texel 0, index 6:
// (2 * 255) / 7 = 72.9.
assert_near("extreme index 6", v(4, 4).into(), 510.0 / 7.0);
}
fn signed_anchors(base: &[u32], channel: usize) {
let v = |x: usize, y: usize| sbyte(base[y * WIDTH + x], channel);
// Block 0, eight-value 100, -100: row 0 indices 6, 7, 0, 1.
assert_eq!([v(2, 0), v(3, 0)], [100, -100]);
for (x, k) in (0..2).chain(0..4).zip([5, 6, 1, 2, 3, 4]) {
let y = usize::from(k < 5);
let real = f64::from((7 - k) * 100 - k * 100) / 7.0;
assert_near(
&format!("eight-value index {}", k + 1),
v(x, y).into(),
real,
);
}
// Block 1, six-value -100, 100: column 4 holds indices 6, 2, 6, 2; index
// 6 is the fixed -1.0 and index 2 is (4 * -100 + 100) / 5 = -60.
assert_eq!([v(4, 0), v(4, 2)], [-127, -127]);
assert_near("six-value index 2", v(4, 1).into(), -60.0);
// Block 2, equal zeros: row 4 indices 6, 7, 0, 1 -> fixed -1.0, 1.0, 0, 0.
assert_eq!([v(0, 4), v(1, 4), v(2, 4), v(3, 4)], [-127, 127, 0, 0]);
// Block 3, 127 > -128: index 6 is (2 * 127 + 5 * -127) / 7 = -54.4, with
// -128 read as -1.0.
assert_near("extreme index 6", v(4, 4).into(), -381.0 / 7.0);
}
fn layers(
blocks: [[u8; 8]; 5],
other: [[u8; 8]; 5],
pair: fn([u8; 8], [u8; 8]) -> Vec<u8>,
) -> [Layer; 2] {
[
blocks.map(|b| pair(b, other[0])),
// Layer 1 rotates the blocks so each layer and mip differs.
std::array::from_fn(|i| pair(blocks[(i + 2) % 5], other[(i + 1) % 5])),
]
}
fn single(block: [u8; 8], _: [u8; 8]) -> Vec<u8> {
block.to_vec()
}
/// BC5 with the first block in red and a different block in green.
fn red_green(red: [u8; 8], green: [u8; 8]) -> Vec<u8> {
dual(red, green)
}
#[test]
fn reads_pitched_bc4_unorm_across_mips_and_layers() {
let blocks = unsigned_blocks();
let case = Case {
format: BcChannelFormat::Bc4Unorm,
reference: bc4_unorm,
layers: layers(blocks, blocks, single),
};
let (reads, worst) = read_and_compare(&case);
let base = &reads[0][0];
unsigned_anchors(base, 0);
// A single channel reads as (red, 0, 0, 1).
assert!(base.iter().all(|&word| word & 0xffff_ff00 == 0xff00_0000));
println!("checked 58 BC4 UNORM texels, worst channel difference {worst}");
}
#[test]
fn reads_pitched_bc4_snorm_across_mips_and_layers() {
let blocks = signed_blocks();
let case = Case {
format: BcChannelFormat::Bc4Snorm,
reference: bc4_snorm,
layers: layers(blocks, blocks, single),
};
let (reads, worst) = read_and_compare(&case);
let base = &reads[0][0];
signed_anchors(base, 0);
assert!(base.iter().all(|&word| word & 0xffff_ff00 == 0x7f00_0000));
// Layer 1 mip 1 is block 1 (-100 < 100, six-value): indices 6, 7, 2, 3.
let small: Vec<_> = reads[1][1].iter().map(|&word| sbyte(word, 0)).collect();
assert_eq!(small[..2], [-127, 127]);
println!("checked 58 BC4 SNORM texels, worst channel difference {worst}");
}
#[test]
fn reads_pitched_bc5_unorm_in_red_green_order() {
let blocks = unsigned_blocks();
let case = Case {
format: BcChannelFormat::Bc5Unorm,
reference: bc5_unorm,
layers: [
blocks.map(|b| red_green(b, blocks[1])),
layers(blocks, blocks, red_green)[1].clone(),
],
};
let (reads, worst) = read_and_compare(&case);
let base = &reads[0][0];
unsigned_anchors(base, 0);
// Green holds the six-value block 1 throughout layer 0: (0, 0) is its
// index 6, the fixed 0, and (1, 0) its index 7, the fixed 255.
assert_eq!([byte(base[0], 1), byte(base[1], 1)], [0, 255]);
assert!(base.iter().all(|&word| word & 0xffff_0000 == 0xff00_0000));
println!("checked 58 BC5 UNORM texels, worst channel difference {worst}");
}
#[test]
fn reads_pitched_bc5_snorm_in_red_green_order() {
let blocks = signed_blocks();
let case = Case {
format: BcChannelFormat::Bc5Snorm,
reference: bc5_snorm,
layers: [
blocks.map(|b| red_green(b, blocks[1])),
layers(blocks, blocks, red_green)[1].clone(),
],
};
let (reads, worst) = read_and_compare(&case);
let base = &reads[0][0];
signed_anchors(base, 0);
// Green holds the six-value block 1 throughout layer 0: (0, 0) and
// (1, 0) are its fixed -1.0 and 1.0.
assert_eq!([sbyte(base[0], 1), sbyte(base[1], 1)], [-127, 127]);
assert!(base.iter().all(|&word| word & 0xffff_0000 == 0x7f00_0000));
println!("checked 58 BC5 SNORM texels, worst channel difference {worst}");
}
/// Reads a one-mip, one-layer upload of `width`×`height` from `blocks` with
/// one padding block per row, comparing with the CPU decoder.
fn read_edge(
format: BcChannelFormat,
reference: fn(&[u8]) -> [u32; 16],
blocks: &[Vec<u8>],
(width, height): (usize, usize),
) -> Vec<u32> {
let block = format.block_bytes();
let pad = PAD.repeat(block / PAD.len());
let blocks_x = width.div_ceil(4);
let mut bytes = Vec::new();
for row in blocks.chunks(blocks_x) {
for slot in row {
bytes.extend_from_slice(slot);
}
bytes.extend_from_slice(&pad);
}
let upload = BcChannelUpload::new(
&bytes,
BcChannelUploadDesc {
width,
height,
mips: 1,
layers: 1,
format,
row_pitch: (blocks_x + 1) * block,
slice_pitch: bytes.len(),
},
)
.unwrap();
let actual = native(context().read_bc_channel_upload(&upload, 0, 0));
let decoded: Vec<_> = blocks
.iter()
.map(|block| expected_block(format, reference, block))
.collect();
let expected = crop(&decoded, blocks_x, width, height);
check_texels(
&format!("{format:?} {width}x{height}"),
format,
&actual,
&expected,
);
actual
}
#[test]
fn reads_bc4_and_bc5_edge_blocks() {
let [eight, six, ..] = unsigned_blocks();
let [s_eight, s_six, _, _, s_low] = signed_blocks();
// 5×3 is one row of two blocks (Metal's zero row stride), both cut at
// row 3 and the second at column 1; 1×1 is one block cut to texel 0.
// Row 0 of every block holds indices 6, 7, 0, 1; column 0 holds 6, 2, 6.
let wide = read_edge(
BcChannelFormat::Bc4Unorm,
bc4_unorm,
&[eight.to_vec(), six.to_vec()],
(5, 3),
);
let red: Vec<_> = wide.iter().map(|&w| byte(w, 0)).collect();
assert_eq!([red[2], red[3], red[4], red[14]], [200, 20, 0, 0]);
assert_near("six-value index 2", red[9].into(), 56.0);
let wide = read_edge(
BcChannelFormat::Bc5Snorm,
bc5_snorm,
&[dual(s_eight, s_six), dual(s_six, s_eight)],
(5, 3),
);
// Block 0: red eight-value endpoints 100, -100; green six-value 0 and 1
// indices -100, 100. Block 1: red six-value fixed -1.0 at index 6, green
// eight-value index 6 (2 * 100 + 5 * -100) / 7 = -42.9.
let texel = |i: usize| [sbyte(wide[i], 0), sbyte(wide[i], 1)];
assert_eq!([texel(2), texel(3)], [[100, -100], [-100, 100]]);
assert_eq!(texel(4)[0], -127);
assert_near(
"green eight-value index 6",
texel(4)[1].into(),
-300.0 / 7.0,
);
// Index 6 of -128 < 127 is the six-value fixed -1.0.
let one = read_edge(
BcChannelFormat::Bc4Snorm,
bc4_snorm,
&[s_low.to_vec()],
(1, 1),
);
assert_eq!(one, [0x7f00_0081]);
let one = read_edge(
BcChannelFormat::Bc5Unorm,
bc5_unorm,
&[dual(six, eight)],
(1, 1),
);
assert_eq!(byte(one[0], 0), 0);
assert_near(
"green eight-value index 6",
byte(one[0], 1).into(),
500.0 / 7.0,
);
println!("checked 32 BC4 and BC5 texels from 5x3 and 1x1 edge levels");
}
+221
View File
@@ -1,11 +1,27 @@
use xenora_metal::NativeCompute;
#[path = "native/blend.rs"]
mod blend;
#[path = "support/blend_cases.rs"]
mod blend_cases;
#[path = "native/depth.rs"]
mod depth;
#[path = "support/depth_cases.rs"]
mod depth_cases;
#[path = "native/guest_buffer.rs"]
mod guest_buffer;
#[path = "native/indexed.rs"]
mod indexed;
#[path = "support/indexed_cases.rs"]
mod indexed_cases;
#[path = "native/offscreen.rs"]
mod offscreen;
#[path = "native/texture.rs"]
mod texture;
#[path = "native/texture_bc_alpha.rs"]
mod texture_bc_alpha;
#[path = "native/texture_bc_channel.rs"]
mod texture_bc_channel;
#[path = "native/texture_sampling.rs"]
mod texture_sampling;
#[path = "native/translated_render.rs"]
@@ -29,6 +45,17 @@ fn context() -> NativeCompute {
NativeCompute::new().expect("native Metal device and queue")
}
/// Unwraps a native result, reporting a missing device capability apart from
/// an implementation failure. Both fail the test; neither counts as a pass.
fn native<T>(result: Result<T, xenora_metal::MetalError>) -> T {
result.unwrap_or_else(|error| {
if error.is_capability_unavailable() {
panic!("CAPABILITY UNAVAILABLE on this device, not an implementation failure: {error}")
}
panic!("IMPLEMENTATION FAILURE: {error}")
})
}
fn verify_words(body: &str, input: &[u32], expected: &[u32]) {
let actual = context()
.run_words(&fixture(body), "fixture", input)
@@ -36,6 +63,165 @@ fn verify_words(body: &str, input: &[u32], expected: &[u32]) {
assert_eq!(actual, expected);
}
const MAX_DISPATCH_GROUPS: usize = 64;
fn mixing_fixture(rounds: u32) -> String {
fixture(&format!(
"
uint value = input[id] ^ (id * 0x9e3779b9u);
for (uint round = 0u; round < {rounds}u; ++round) {{
value ^= value << 13u;
value ^= value >> 17u;
value ^= value << 5u;
value = value * 0x85ebca6bu + round;
}}
output[id] = value;
"
))
}
fn mixing_expectation(input: &[u32], rounds: u32) -> Vec<u32> {
(0_u32..)
.zip(input)
.map(|(id, &word)| {
let mut value = word ^ id.wrapping_mul(0x9e37_79b9);
for round in 0..rounds {
let left = value ^ (value << 13);
let right = left ^ (left >> 17);
let mixed = right ^ (right << 5);
value = mixed.wrapping_mul(0x85eb_ca6b).wrapping_add(round);
}
value
})
.collect()
}
fn mixing_input(words: u32) -> Vec<u32> {
(0..words)
.map(|id| id.wrapping_mul(0xc2b2_ae35) ^ 0xdead_beef)
.collect()
}
#[test]
fn threadgroup_widths_give_identical_known_answers() {
const WIDTHS: [usize; 16] = [
1, 2, 3, 7, 31, 32, 33, 63, 64, 65, 96, 128, 255, 256, 512, 1024,
];
const GRIDS: [u32; 7] = [1, 63, 64, 65, 1000, 4093, 4096];
const ROUNDS: u32 = 37;
let context = context();
let source = mixing_fixture(ROUNDS);
let limit = native(context.max_group_width(&source, "fixture"));
let mut checked = 0;
let mut skipped = 0;
for grid in GRIDS {
let input = mixing_input(grid);
let expected = mixing_expectation(&input, ROUNDS);
for width in WIDTHS {
if width > limit {
println!("skipped grid={grid} width={width}: device/pipeline limit is {limit}");
skipped += 1;
continue;
}
let groups = input.len().div_ceil(width);
if groups > MAX_DISPATCH_GROUPS {
println!(
"skipped grid={grid} width={width}: {groups} groups exceed {MAX_DISPATCH_GROUPS}"
);
skipped += 1;
continue;
}
let profile =
native(context.run_words_with_group_width(&source, "fixture", &input, width));
assert_eq!(profile.output, expected, "grid={grid} width={width}");
checked += 1;
}
}
assert!(checked > 0);
println!("checked {checked} configurations, skipped {skipped}");
}
#[test]
fn threadgroup_width_rejections() {
let context = context();
let source = fixture("output[id] = input[id];");
let limit = native(context.max_group_width(&source, "fixture"));
for width in [0, limit + 1] {
let error = context
.run_words_with_group_width(&source, "fixture", &[25], width)
.expect_err("invalid threadgroup width must fail");
assert_eq!(error.operation, "threadgroup width");
}
let error = context
.run_words_with_group_width(&source, "fixture", &[25; MAX_DISPATCH_GROUPS + 1], 1)
.expect_err("too many threadgroups must fail");
assert_eq!(error.operation, "dispatch bounds");
}
fn timing_summary(samples: &mut [f64]) -> String {
samples.sort_by(f64::total_cmp);
let count = samples.len();
let median = f64::midpoint(samples[(count - 1) / 2], samples[count / 2]);
let p95 = samples[(count * 95).div_ceil(100) - 1];
format!(
"median={:.3} min={:.3} max={:.3} p95={:.3}",
median * 1e6,
samples[0] * 1e6,
samples[count - 1] * 1e6,
p95 * 1e6,
)
}
#[test]
#[ignore = "manual GPU timing run"]
fn threadgroup_width_benchmark() {
const ROUNDS: u32 = 2000;
const WARMUPS: usize = 5;
const SAMPLES: usize = 30;
let context = context();
let device = context.device_name();
let source = mixing_fixture(ROUNDS);
let input = mixing_input(4096);
let expected = mixing_expectation(&input, ROUNDS);
let limit = native(context.max_group_width(&source, "fixture"));
let mut widths = vec![None];
for width in [32, 64, 128, 256, 512, 1024] {
if width > limit {
println!("device={device} skipped width={width}: device/pipeline limit is {limit}");
} else if input.len().div_ceil(width) > MAX_DISPATCH_GROUPS {
println!("device={device} skipped width={width}: exceeds {MAX_DISPATCH_GROUPS} groups");
} else {
widths.push(Some(width));
}
}
let mut timings = vec![([0.0; SAMPLES], [0.0; SAMPLES]); widths.len()];
for round in 0..WARMUPS + SAMPLES {
for (width, (gpu, host)) in widths.iter().zip(&mut timings) {
let profile = native(match width {
Some(width) => {
context.run_words_with_group_width(&source, "fixture", &input, *width)
}
None => context.run_words_profiled(&source, "fixture", &input),
});
assert_eq!(profile.output, expected, "width={width:?} round={round}");
if round >= WARMUPS {
gpu[round - WARMUPS] = profile.gpu_seconds;
host[round - WARMUPS] = profile.host_seconds;
}
}
}
for (width, (gpu, host)) in widths.into_iter().zip(&mut timings) {
let width = width.map_or_else(|| "default".to_owned(), |width| width.to_string());
println!(
"device={device} width={width} gpu_us[{}] host_us[{}]",
timing_summary(gpu),
timing_summary(host),
);
}
}
#[test]
fn integer_multiplication() {
let context = context();
@@ -188,3 +374,38 @@ fn errors_propagate() {
.expect_err("excessive dispatch must fail");
assert_eq!(error.operation, "dispatch bounds");
}
/// Identical outputs alone cannot show which width ran, so each thread also
/// reports the requested group width, its own group's size and its in-group
/// index (11, 11 and 10 bits).
#[test]
fn requested_threadgroup_width_is_dispatched() {
const SOURCE: &str = r"
#include <metal_stdlib>
using namespace metal;
kernel void fixture(device const uint *input [[buffer(0)]],
device uint *output [[buffer(1)]],
uint id [[thread_position_in_grid]],
uint local [[thread_index_in_threadgroup]],
uint group_size [[threads_per_threadgroup]],
uint requested [[dispatch_threads_per_threadgroup]]) {
output[id] = (requested << 21u) | (group_size << 10u) | local;
}
";
let context = context();
let limit = native(context.max_group_width(SOURCE, "fixture"));
for (grid, width) in [(1000_usize, 33_usize), (4093, 64), (4096, 256), (65, 1024)] {
if width > limit {
println!("skipped grid={grid} width={width}: device/pipeline limit is {limit}");
continue;
}
let profile =
native(context.run_words_with_group_width(SOURCE, "fixture", &vec![0; grid], width));
for (id, word) in profile.output.iter().enumerate() {
// dispatchThreads trims the last group to the grid's remainder.
let size = width.min(grid - id / width * width);
let expected = u32::try_from((width << 21) | (size << 10) | (id % width)).unwrap();
assert_eq!(*word, expected, "grid={grid} width={width} id={id}");
}
}
}
+212
View File
@@ -0,0 +1,212 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Original blend-pass fixtures shared by the CPU reference check and the
//! native Metal test, and the parser for the independently derived
//! expectations in `fixtures/blend_expected.txt`.
//!
//! The expectations record, per channel, whether the exact result needed
//! rounding; the native test's tolerance (`native/blend.rs`) depends on it.
use xenora_ref::blend::{RefBlend, RefBlendFactor, RefBlendOperation};
pub const SIZE: usize = 16;
pub const CLEAR: [u8; 4] = [32, 64, 96, 128];
const DST: [u8; 4] = [200, 100, 50, 160];
const SRC: [u8; 4] = [60, 180, 240, 96];
// Triangles in pixel coordinates; no pixel centre lies on any edge.
const A: [[f32; 2]; 3] = [[0.0, 0.0], [16.0, 0.0], [0.0, 12.0]];
const B: [[f32; 2]; 3] = [[4.0, 3.0], [16.0, 4.0], [6.0, 16.0]];
#[derive(Clone, Copy, Debug)]
pub struct Draw {
pub positions: [[f32; 4]; 3],
pub color: [u8; 4],
pub blend: Option<RefBlend>,
/// Written channels R, G, B, A.
pub mask: [bool; 4],
}
#[derive(Debug)]
pub struct Case {
pub name: String,
pub draws: Vec<Draw>,
}
fn clip(tri: [[f32; 2]; 3]) -> [[f32; 4]; 3] {
tri.map(|[x, y]| [x / 8.0 - 1.0, 1.0 - y / 8.0, 0.5, 1.0])
}
fn same(
source: RefBlendFactor,
destination: RefBlendFactor,
operation: RefBlendOperation,
) -> RefBlend {
RefBlend {
source_rgb: source,
destination_rgb: destination,
rgb_operation: operation,
source_alpha: source,
destination_alpha: destination,
alpha_operation: operation,
}
}
/// Destination triangle A, then source triangle B with `blend` and `mask`.
fn case(name: String, blend: Option<RefBlend>, mask: [bool; 4]) -> Case {
Case {
name,
draws: vec![
Draw {
positions: clip(A),
color: DST,
blend: None,
mask: [true; 4],
},
Draw {
positions: clip(B),
color: SRC,
blend,
mask,
},
],
}
}
/// Every case, in fixture order.
pub fn cases() -> Vec<Case> {
use RefBlendFactor::{One, OneMinusSourceAlpha, SourceAlpha, Zero};
use RefBlendOperation::Add;
let all = [true; 4];
let mut cases = vec![
Case {
name: "clear".to_owned(),
draws: Vec::new(),
},
case("disabled".to_owned(), None, all),
];
for factor in RefBlendFactor::ALL {
cases.push(case(
format!("src_{factor:?}"),
Some(same(factor, Zero, Add)),
all,
));
}
for factor in RefBlendFactor::ALL {
cases.push(case(
format!("dst_{factor:?}"),
Some(same(Zero, factor, Add)),
all,
));
}
for operation in RefBlendOperation::ALL {
cases.push(case(
format!("op_{operation:?}"),
Some(same(SourceAlpha, OneMinusSourceAlpha, operation)),
all,
));
}
cases.push(case(
"additive_clamp".to_owned(),
Some(same(One, One, Add)),
all,
));
cases.push(case(
"separate_alpha".to_owned(),
Some(RefBlend {
source_alpha: One,
destination_alpha: Zero,
..same(SourceAlpha, OneMinusSourceAlpha, Add)
}),
all,
));
for (name, mask) in [
("R", [true, false, false, false]),
("G", [false, true, false, false]),
("B", [false, false, true, false]),
("A", [false, false, false, true]),
("RGB", [true, true, true, false]),
("none", [false; 4]),
("RGBA", all),
] {
cases.push(case(format!("mask_{name}"), None, mask));
}
cases.push(case(
"mask_RG_blended".to_owned(),
Some(same(SourceAlpha, OneMinusSourceAlpha, Add)),
[true, true, false, false],
));
let mut first = case(
"first_draw_blended".to_owned(),
None,
[true, true, false, false],
);
first.draws[0].blend = Some(same(SourceAlpha, OneMinusSourceAlpha, Add));
first.draws[0].mask = [false, true, true, true];
cases.push(case(
"separate_operation".to_owned(),
Some(RefBlend {
source_alpha: One,
destination_alpha: One,
alpha_operation: RefBlendOperation::ReverseSubtract,
..same(SourceAlpha, OneMinusSourceAlpha, Add)
}),
all,
));
cases.push(first);
cases
}
/// One case of `blend_expected.txt`: per pixel, the colour and whether each
/// channel needed rounding.
#[derive(Debug)]
pub struct Expected {
pub name: String,
pub color: Vec<[u8; 4]>,
pub exact: Vec<[bool; 4]>,
}
/// Parse the independently derived expectations.
pub fn expected() -> Vec<Expected> {
let text = include_str!("../fixtures/blend_expected.txt");
let mut out = Vec::new();
let mut lines = text.lines().filter(|line| !line.trim().is_empty());
while let Some(header) = lines.next() {
let name = header.strip_prefix("case ").expect("case line").to_owned();
let (mut palette, mut color, mut exact) = (Vec::new(), Vec::new(), Vec::new());
for line in lines.by_ref() {
let words: Vec<&str> = line.split_whitespace().collect();
match words[0] {
"palette" => {
let key = words[1].chars().next().unwrap();
let rgba: Vec<u8> = words[2..6].iter().map(|w| w.parse().unwrap()).collect();
let flags: Vec<bool> = words[6]
.chars()
.map(|c| match c {
'e' => true,
'r' => false,
other => panic!("unexpected rounding flag {other}"),
})
.collect();
palette.push((
key,
<[u8; 4]>::try_from(rgba).unwrap(),
<[bool; 4]>::try_from(flags).unwrap(),
));
}
"color" => {
for c in words[1].chars() {
let entry = palette.iter().find(|(k, ..)| *k == c).expect("palette key");
color.push(entry.1);
exact.push(entry.2);
}
}
"end" => break,
other => panic!("unexpected fixture line {other}"),
}
}
assert_eq!(color.len(), SIZE * SIZE, "{name} colour rows");
out.push(Expected { name, color, exact });
}
out
}
+187
View File
@@ -0,0 +1,187 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Original depth-pass fixtures shared by the CPU reference check and the
//! native Metal test, and the parser for the independently derived
//! expectations in `fixtures/depth_expected.txt`.
use xenora_ref::depth::CompareFunction;
pub const SIZE: usize = 16;
pub const RED: [u8; 4] = [255, 0, 0, 255];
pub const GREEN: [u8; 4] = [0, 255, 0, 255];
pub const BLUE: [u8; 4] = [0, 0, 255, 255];
const BLACK: [u8; 4] = [0, 0, 0, 255];
/// Four original BC1 blocks (8x8 texels) using only endpoint and
/// transparent selectors, so every decoded texel is exact.
pub const BC1_BLOCKS: [u8; 32] = [
0x00, 0xF8, 0x1F, 0x00, 0x44, 0x11, 0x50, 0x05, // red / blue, four-colour
0xE0, 0x07, 0xFF, 0xFF, 0x0F, 0xF0, 0x4C, 0x31, // green / white, three-colour
0xE0, 0xFF, 0x00, 0x00, 0x00, 0x55, 0x00, 0x55, // yellow / black
0x10, 0x84, 0x41, 0x08, 0x14, 0x41, 0x14, 0x41, // grey / near black
];
// Triangles in pixel coordinates; no pixel centre lies on any edge.
const FULL: [[f32; 2]; 3] = [[0.0, 16.0], [32.0, 16.0], [0.0, -16.0]];
const A: [[f32; 2]; 3] = [[0.0, 0.0], [16.0, 0.0], [0.0, 12.0]];
const B: [[f32; 2]; 3] = [[4.0, 3.0], [16.0, 4.0], [6.0, 16.0]];
const C: [[f32; 2]; 3] = [[0.0, 8.0], [10.0, 8.0], [0.0, 16.0]];
#[derive(Clone, Copy, Debug)]
pub enum Fill {
Flat([u8; 4]),
Texture,
}
#[derive(Clone, Copy, Debug)]
pub struct Draw {
pub positions: [[f32; 4]; 3],
pub fill: Fill,
pub compare: CompareFunction,
pub write: bool,
}
#[derive(Debug)]
pub struct Case {
pub name: String,
pub clear_color: [u8; 4],
pub clear_depth: Option<f32>,
pub draws: Vec<Draw>,
}
fn draw(tri: [[f32; 2]; 3], z: f32, fill: Fill, compare: CompareFunction, write: bool) -> Draw {
Draw {
positions: tri.map(|[x, y]| [x / 8.0 - 1.0, 1.0 - y / 8.0, z, 1.0]),
fill,
compare,
write,
}
}
fn case(name: &str, clear_color: [u8; 4], clear_depth: Option<f32>, draws: Vec<Draw>) -> Case {
Case {
name: name.to_owned(),
clear_color,
clear_depth,
draws,
}
}
/// Every case, each exercising one feature, in fixture order.
pub fn cases() -> Vec<Case> {
use CompareFunction::{Always, Less, LessEqual};
let red = Fill::Flat(RED);
let green = Fill::Flat(GREEN);
let blue = Fill::Flat(BLUE);
let mut cases = vec![case("clear", [16, 32, 48, 255], Some(0.375), Vec::new())];
for compare in CompareFunction::ALL {
for z in [0.25, 0.5, 0.75] {
cases.push(case(
&format!("compare_{compare:?}_{z}"),
BLACK,
Some(1.0),
vec![
draw(A, 0.5, red, Always, true),
draw(B, z, green, compare, true),
],
));
}
}
for (name, write) in [("write_disabled", false), ("write_enabled", true)] {
cases.push(case(
name,
BLACK,
Some(1.0),
vec![
draw(A, 0.5, red, Always, true),
draw(B, 0.25, green, Always, write),
draw(C, 0.75, blue, LessEqual, true),
],
));
}
let painter = |depth| {
case(
if depth {
"disabled_attachment"
} else {
"no_attachment"
},
BLACK,
depth.then_some(1.0),
vec![
draw(A, 0.25, red, Always, false),
draw(B, 0.75, green, Always, false),
],
)
};
cases.push(painter(true));
cases.push(painter(false));
cases.push(case(
"textured",
BLACK,
Some(1.0),
vec![
draw(FULL, 0.5, Fill::Texture, Less, true),
draw(B, 0.75, green, Less, true),
draw(A, 0.25, red, Less, true),
],
));
cases
}
/// Independently derived colour and depth of one case.
#[derive(Debug, PartialEq)]
pub struct Expected {
pub name: String,
pub color: Vec<[u8; 4]>,
pub depth: Option<Vec<f32>>,
}
pub fn expected() -> Vec<Expected> {
let text = include_str!("../fixtures/depth_expected.txt");
let mut out = Vec::new();
let mut lines = text.lines().filter(|line| !line.trim().is_empty());
while let Some(header) = lines.next() {
let name = header.strip_prefix("case ").expect("case line").to_owned();
let (mut palette, mut depthkey) = (Vec::new(), Vec::new());
let (mut color, mut depth, mut no_depth) = (Vec::new(), Vec::new(), false);
for line in lines.by_ref() {
let mut words = line.split_whitespace();
match words.next().expect("keyword") {
"palette" => {
let key = words.next().unwrap().chars().next().unwrap();
let rgba: Vec<u8> = words.map(|w| w.parse().unwrap()).collect();
palette.push((key, <[u8; 4]>::try_from(rgba).unwrap()));
}
"depthkey" => {
let key = words.next().unwrap().chars().next().unwrap();
depthkey.push((key, words.next().unwrap().parse::<f32>().unwrap()));
}
"color" => color.extend(words.next().unwrap().chars().map(|c| {
palette
.iter()
.find(|(k, _)| *k == c)
.expect("palette key")
.1
})),
"depth" => match words.next().unwrap() {
"none" => no_depth = true,
row => depth.extend(
row.chars()
.map(|c| depthkey.iter().find(|(k, _)| *k == c).expect("depth key").1),
),
},
"end" => break,
other => panic!("unexpected fixture line {other}"),
}
}
assert_eq!(color.len(), SIZE * SIZE, "{name} colour rows");
assert!(no_depth || depth.len() == SIZE * SIZE, "{name} depth rows");
out.push(Expected {
name,
color,
depth: (!no_depth).then_some(depth),
});
}
out
}
+188
View File
@@ -0,0 +1,188 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Original indexed-draw fixtures shared by the CPU reference check and the
//! native Metal test, and the parser for the independently derived
//! expectations in `fixtures/indexed_expected.txt`.
pub const SIZE: usize = 16;
const RED: [u8; 4] = [255, 0, 0, 255];
const GREEN: [u8; 4] = [0, 255, 0, 255];
const BLUE: [u8; 4] = [0, 0, 255, 255];
const BLACK: [u8; 4] = [0, 0, 0, 255];
/// The four original BC1 blocks of the depth fixtures (8x8 texels), using
/// only endpoint and transparent selectors so every decoded texel is exact.
pub const BC1_BLOCKS: [u8; 32] = [
0x00, 0xF8, 0x1F, 0x00, 0x44, 0x11, 0x50, 0x05, // red / blue, four-colour
0xE0, 0x07, 0xFF, 0xFF, 0x0F, 0xF0, 0x4C, 0x31, // green / white, three-colour
0xE0, 0xFF, 0x00, 0x00, 0x00, 0x55, 0x00, 0x55, // yellow / black
0x10, 0x84, 0x41, 0x08, 0x14, 0x41, 0x14, 0x41, // grey / near black
];
/// Vertex buffer in pixel coordinates; no pixel centre lies on any edge of
/// a triangle the cases draw.
const VERTICES: [[f32; 2]; 13] = [
[0.0, 0.0],
[16.0, 0.0],
[0.0, 12.0],
[4.0, 3.0],
[16.0, 4.0],
[6.0, 16.0],
[0.0, 8.0],
[10.0, 8.0],
[0.0, 16.0],
[0.0, 0.0],
[16.0, 0.0],
[16.0, 15.0],
[0.0, 16.0],
];
/// The index buffer of the 16-bit cases.
pub const INDICES: [u16; 21] = [
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 9, 11, 12, 2, 1, 0, 10, 11, 12,
];
/// The index buffer of the 32-bit cases: [`INDICES`] and three indices that
/// need more than 16 bits.
pub fn wide_indices() -> Vec<u32> {
INDICES
.iter()
.map(|&index| u32::from(index))
.chain([65545, 65546, 65547])
.collect()
}
/// Clip-space positions of [`VERTICES`] at depth 0.5.
pub fn vertices() -> Vec<[f32; 4]> {
VERTICES
.iter()
.map(|[x, y]| [x / 8.0 - 1.0, 1.0 - y / 8.0, 0.5, 1.0])
.collect()
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Fill {
Flat([u8; 4]),
Texture,
}
#[derive(Clone, Copy, Debug)]
pub struct Draw {
pub start: usize,
pub count: usize,
pub base_vertex: i32,
pub fill: Fill,
}
#[derive(Debug)]
pub struct Case {
pub name: &'static str,
pub wide: bool,
pub clear_color: [u8; 4],
pub draws: Vec<Draw>,
}
/// Every case, in fixture order.
pub fn cases() -> Vec<Case> {
let draw = |start, count, base_vertex, fill| Draw {
start,
count,
base_vertex,
fill,
};
let (red, green, blue, texture) = (
Fill::Flat(RED),
Fill::Flat(GREEN),
Fill::Flat(BLUE),
Fill::Texture,
);
let case = |name, wide, draws| Case {
name,
wide,
clear_color: BLACK,
draws,
};
vec![
Case {
clear_color: [16, 32, 48, 255],
..case("clear", false, Vec::new())
},
case("u16_first", false, vec![draw(0, 3, 0, red)]),
case("u32_first", true, vec![draw(0, 3, 0, red)]),
case("u16_odd_start", false, vec![draw(3, 3, 0, green)]),
case("u32_start", true, vec![draw(3, 3, 0, green)]),
case("u16_base_positive", false, vec![draw(0, 3, 6, blue)]),
case("u16_base_negative", false, vec![draw(18, 3, -4, blue)]),
case("u32_base_negative", true, vec![draw(18, 3, -4, blue)]),
case("reversed_winding", false, vec![draw(15, 3, 0, red)]),
case(
"two_triangles_textured",
false,
vec![draw(9, 6, 0, texture)],
),
case("textured_base_vertex", false, vec![draw(0, 3, 9, texture)]),
case(
"painter_order",
false,
vec![
draw(0, 3, 0, red),
draw(3, 3, 0, green),
draw(0, 3, 6, blue),
],
),
case(
"u32_mixed",
true,
vec![
draw(9, 6, 0, texture),
draw(18, 3, -1, green),
draw(6, 3, -6, red),
],
),
case("flat_two_triangles", false, vec![draw(9, 6, 0, green)]),
case("textured_first", false, vec![draw(0, 3, 0, texture)]),
case("u32_high_indices", true, vec![draw(21, 3, -65536, red)]),
]
}
/// One case of `indexed_expected.txt`: fetched vertices per draw and colours.
#[derive(Debug)]
pub struct Expected {
pub name: String,
pub fetch: Vec<Vec<usize>>,
pub color: Vec<[u8; 4]>,
}
/// Parse the independently derived expectations.
pub fn expected() -> Vec<Expected> {
let text = include_str!("../fixtures/indexed_expected.txt");
let mut out = Vec::new();
let mut lines = text.lines().filter(|line| !line.trim().is_empty());
while let Some(header) = lines.next() {
let name = header.strip_prefix("case ").expect("case line").to_owned();
let (mut fetch, mut palette, mut color) = (Vec::new(), Vec::new(), Vec::new());
for line in lines.by_ref() {
let mut words = line.split_whitespace();
match words.next().expect("keyword") {
"fetch" => fetch.push(words.map(|word| word.parse().unwrap()).collect()),
"palette" => {
let key = words.next().unwrap().chars().next().unwrap();
let rgba: Vec<u8> = words.map(|word| word.parse().unwrap()).collect();
palette.push((key, <[u8; 4]>::try_from(rgba).unwrap()));
}
"color" => color.extend(words.next().unwrap().chars().map(|c| {
palette
.iter()
.find(|(key, _)| *key == c)
.expect("palette key")
.1
})),
"end" => break,
other => panic!("unexpected fixture line {other}"),
}
}
assert_eq!(color.len(), SIZE * SIZE, "{name} colour rows");
out.push(Expected { name, fetch, color });
}
out
}
+310
View File
@@ -0,0 +1,310 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Independent CPU reference for blended, write-masked triangle draws into an
//! RGBA8 unorm target.
//!
//! Every value is kept exact: a unorm8 value `v` means `v / 255`, so a
//! weighted term `value * factor` is an integer count of `1 / 255²`. The
//! result is clamped to 0..=1 and rounded to the nearest unorm8 value. The
//! reference also reports, per channel, whether that rounding was needed, so
//! a native comparison can hold exact results to exact equality. Coverage
//! comes from [`crate::depth::render_depth`].
use std::fmt;
use crate::depth::{CompareFunction, DepthRefError, RefDraw, RefFill, render_depth};
/// A blend factor; the colour factors use the alpha channel's own value for alpha.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RefBlendFactor {
Zero,
One,
SourceColor,
OneMinusSourceColor,
SourceAlpha,
OneMinusSourceAlpha,
DestinationColor,
OneMinusDestinationColor,
DestinationAlpha,
OneMinusDestinationAlpha,
}
impl RefBlendFactor {
pub const ALL: [Self; 10] = [
Self::Zero,
Self::One,
Self::SourceColor,
Self::OneMinusSourceColor,
Self::SourceAlpha,
Self::OneMinusSourceAlpha,
Self::DestinationColor,
Self::OneMinusDestinationColor,
Self::DestinationAlpha,
Self::OneMinusDestinationAlpha,
];
/// The factor for `channel` in units of 1/255.
fn value(self, source: [u8; 4], destination: [u8; 4], channel: usize) -> i64 {
let (s, d) = (i64::from(source[channel]), i64::from(destination[channel]));
let (sa, da) = (i64::from(source[3]), i64::from(destination[3]));
match self {
Self::Zero => 0,
Self::One => 255,
Self::SourceColor => s,
Self::OneMinusSourceColor => 255 - s,
Self::SourceAlpha => sa,
Self::OneMinusSourceAlpha => 255 - sa,
Self::DestinationColor => d,
Self::OneMinusDestinationColor => 255 - d,
Self::DestinationAlpha => da,
Self::OneMinusDestinationAlpha => 255 - da,
}
}
}
/// A blend operation; `Min` and `Max` ignore the factors.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RefBlendOperation {
Add,
Subtract,
ReverseSubtract,
Min,
Max,
}
impl RefBlendOperation {
pub const ALL: [Self; 5] = [
Self::Add,
Self::Subtract,
Self::ReverseSubtract,
Self::Min,
Self::Max,
];
}
/// Separate RGB and alpha blend equations.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RefBlend {
pub source_rgb: RefBlendFactor,
pub destination_rgb: RefBlendFactor,
pub rgb_operation: RefBlendOperation,
pub source_alpha: RefBlendFactor,
pub destination_alpha: RefBlendFactor,
pub alpha_operation: RefBlendOperation,
}
/// One flat-coloured triangle; `mask` lists the written channels R, G, B, A.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RefBlendDraw {
pub positions: [[f32; 4]; 3],
pub color: [u8; 4],
pub blend: Option<RefBlend>,
pub mask: [bool; 4],
}
/// A blended channel value and whether rounding was needed to reach it.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct RefChannel {
pub value: u8,
pub exact: bool,
}
/// Blend one channel (0 to 3: R, G, B, A) of `source` over `destination`.
///
/// # Panics
///
/// Panics when `channel` is above 3.
pub fn blend_channel(
blend: RefBlend,
source: [u8; 4],
destination: [u8; 4],
channel: usize,
) -> RefChannel {
let (factors, operation) = if channel == 3 {
(
(blend.source_alpha, blend.destination_alpha),
blend.alpha_operation,
)
} else {
(
(blend.source_rgb, blend.destination_rgb),
blend.rgb_operation,
)
};
let (s, d) = (i64::from(source[channel]), i64::from(destination[channel]));
let weighted_s = s * factors.0.value(source, destination, channel);
let weighted_d = d * factors.1.value(source, destination, channel);
// In units of 1/255².
let result = match operation {
RefBlendOperation::Add => weighted_s + weighted_d,
RefBlendOperation::Subtract => weighted_s - weighted_d,
RefBlendOperation::ReverseSubtract => weighted_d - weighted_s,
RefBlendOperation::Min => s.min(d) * 255,
RefBlendOperation::Max => s.max(d) * 255,
}
.clamp(0, 255 * 255);
RefChannel {
// Round half up: floor(result / 255 + 1/2).
value: u8::try_from((2 * result + 255) / 510).expect("clamped to 0..=255"),
exact: result % 255 == 0,
}
}
#[derive(Debug, Eq, PartialEq)]
pub enum BlendRefError {
/// The extent is empty or holds more than 4096 pixels, the native limit.
Extent,
/// The triangle coverage could not be computed.
Raster(DepthRefError),
}
impl fmt::Display for BlendRefError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self:?}")
}
}
impl std::error::Error for BlendRefError {}
/// Render `draws` in order over a target cleared to `clear_color`, returning
/// each pixel's channels and whether each needed rounding (a cleared or
/// replaced channel is exact).
///
/// # Errors
///
/// Returns an error for an extent that is empty or above 4096 pixels, or when a triangle's
/// coverage cannot be computed (see [`render_depth`]).
pub fn render_blend(
extent: [usize; 2],
clear_color: [u8; 4],
draws: &[RefBlendDraw],
) -> Result<Vec<[RefChannel; 4]>, BlendRefError> {
let exact = |value| RefChannel { value, exact: true };
let pixels = extent[0]
.checked_mul(extent[1])
.filter(|&n| (1..=4096).contains(&n))
.ok_or(BlendRefError::Extent)?;
let mut target = vec![clear_color.map(exact); pixels];
for draw in draws {
// Coverage: a white triangle over black, without depth attachment.
let (coverage, _) = render_depth(
extent,
[0; 4],
None,
&[RefDraw {
positions: draw.positions,
fill: RefFill::Flat([255; 4]),
compare: CompareFunction::Always,
write: false,
}],
None,
)
.map_err(BlendRefError::Raster)?;
for (pixel, covered) in target.iter_mut().zip(coverage) {
if covered != [255; 4] {
continue;
}
let destination = pixel.map(|channel| channel.value);
for (channel, slot) in pixel.iter_mut().enumerate() {
if !draw.mask[channel] {
continue;
}
*slot = match draw.blend {
None => exact(draw.color[channel]),
Some(blend) => blend_channel(blend, draw.color, destination, channel),
};
}
}
}
Ok(target)
}
#[cfg(test)]
mod tests {
use super::*;
use RefBlendFactor::{One, OneMinusSourceAlpha, SourceAlpha, Zero};
use RefBlendOperation::{Add, Max, Min, ReverseSubtract, Subtract};
fn blend(
source: RefBlendFactor,
destination: RefBlendFactor,
operation: RefBlendOperation,
) -> RefBlend {
RefBlend {
source_rgb: source,
destination_rgb: destination,
rgb_operation: operation,
source_alpha: source,
destination_alpha: destination,
alpha_operation: operation,
}
}
#[test]
fn bad_extents_are_rejected() {
for extent in [[0, 4], [4, 0], [usize::MAX, 2], [usize::MAX, 1], [65, 64]] {
assert_eq!(
render_blend(extent, [0; 4], &[]),
Err(BlendRefError::Extent)
);
}
}
#[test]
fn channels_follow_the_blend_equation() {
let (s, d) = ([60, 180, 240, 96], [200, 100, 50, 160]);
let channel = |state, c| blend_channel(state, s, d, c);
// 60 * 96 / 255 + 200 * 159 / 255 = 147.29...
assert_eq!(
channel(blend(SourceAlpha, OneMinusSourceAlpha, Add), 0),
RefChannel {
value: 147,
exact: false
}
);
assert_eq!(
channel(blend(One, Zero, Add), 1),
RefChannel {
value: 180,
exact: true
}
);
// 240 + 50 clamps to 255; 60 - 200 clamps to 0.
assert_eq!(
channel(blend(One, One, Add), 2),
RefChannel {
value: 255,
exact: true
}
);
assert_eq!(
channel(blend(One, One, Subtract), 0),
RefChannel {
value: 0,
exact: true
}
);
assert_eq!(
channel(blend(One, One, ReverseSubtract), 0),
RefChannel {
value: 140,
exact: true
}
);
// Min and Max ignore the factors.
assert_eq!(
channel(blend(Zero, Zero, Min), 1),
RefChannel {
value: 100,
exact: true
}
);
assert_eq!(
channel(blend(Zero, Zero, Max), 3),
RefChannel {
value: 160,
exact: true
}
);
}
}
+305
View File
@@ -0,0 +1,305 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Independent CPU reference for depth-tested offscreen triangle rendering.
//!
//! A pixel is covered when its centre lies strictly inside a triangle. Inputs
//! whose pixel centres lie exactly on an edge are rejected rather than resolved
//! by a fill rule, so the reference never depends on rasteriser tie-breaking.
use std::fmt;
/// Depth comparison of the fragment depth against the stored depth.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CompareFunction {
Never,
Less,
Equal,
LessEqual,
Greater,
NotEqual,
GreaterEqual,
Always,
}
impl CompareFunction {
pub const ALL: [Self; 8] = [
Self::Never,
Self::Less,
Self::Equal,
Self::LessEqual,
Self::Greater,
Self::NotEqual,
Self::GreaterEqual,
Self::Always,
];
#[must_use]
pub fn passes(self, fragment: f32, stored: f32) -> bool {
match self {
Self::Never => false,
Self::Less => fragment < stored,
Self::Equal => fragment == stored,
Self::LessEqual => fragment <= stored,
Self::Greater => fragment > stored,
Self::NotEqual => fragment != stored,
Self::GreaterEqual => fragment >= stored,
Self::Always => true,
}
}
}
/// Colour source of one reference draw.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RefFill {
Flat([u8; 4]),
/// Nearest texel of the pass texture at the pixel centre.
Texture,
}
/// One triangle with clip-space positions (`w` must be 1).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RefDraw {
pub positions: [[f32; 4]; 3],
pub fill: RefFill,
pub compare: CompareFunction,
pub write: bool,
}
/// Decoded RGBA8 texels in row-major order.
#[derive(Clone, Copy, Debug)]
pub struct RefTexture<'a> {
pub width: usize,
pub height: usize,
pub texels: &'a [[u8; 4]],
}
#[derive(Debug, Eq, PartialEq)]
pub enum DepthRefError {
Extent,
NonUnitW,
/// A position is non-finite or its depth lies outside 0..=1: (draw).
Unclipped(usize),
/// A pixel centre lies on a triangle edge: (draw, x, y).
EdgeTie(usize, usize, usize),
MissingTexture,
/// Without a depth attachment every draw must be `Always` without writes.
DepthStateWithoutAttachment(usize),
}
impl fmt::Display for DepthRefError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self:?}")
}
}
impl std::error::Error for DepthRefError {}
/// Colour (row-major, top row first) and, with an attachment, stored depth.
pub type DepthRefOutput = (Vec<[u8; 4]>, Option<Vec<f32>>);
/// Render `draws` in order over a cleared target with viewport depth range 0..1.
///
/// # Errors
///
/// Returns an error for an empty extent, non-unit `w`, a non-finite position
/// or depth outside 0..=1, a pixel centre on an edge, a textured draw without texture, or a depth state without attachment.
pub fn render_depth(
[width, height]: [usize; 2],
clear_color: [u8; 4],
clear_depth: Option<f32>,
draws: &[RefDraw],
texture: Option<RefTexture<'_>>,
) -> Result<DepthRefOutput, DepthRefError> {
let pixels = width.checked_mul(height).filter(|&n| n > 0);
let pixels = pixels.ok_or(DepthRefError::Extent)?;
if let Some(texture) = texture
&& texture.width.checked_mul(texture.height).filter(|&n| n > 0)
!= Some(texture.texels.len())
{
return Err(DepthRefError::Extent);
}
let mut color = vec![clear_color; pixels];
let mut depth = clear_depth.map(|value| vec![value; pixels]);
for (index, draw) in draws.iter().enumerate() {
if depth.is_none() && (draw.compare != CompareFunction::Always || draw.write) {
return Err(DepthRefError::DepthStateWithoutAttachment(index));
}
if draw.fill == RefFill::Texture && texture.is_none() {
return Err(DepthRefError::MissingTexture);
}
if draw.positions.iter().any(|p| p[3] != 1.0) {
return Err(DepthRefError::NonUnitW);
}
// The reference does not clip, so depth must already lie in the
// viewport range 0..=1 (this also rejects non-finite depth).
if draw
.positions
.iter()
.any(|p| !p.iter().all(|v| v.is_finite()) || !(0.0..=1.0).contains(&p[2]))
{
return Err(DepthRefError::Unclipped(index));
}
// Viewport transform: NDC x, y in -1..1 map to pixels, y down.
let screen = draw.positions.map(|[x, y, z, _]| {
[
(f64::from(x) + 1.0) * 0.5 * width as f64,
(1.0 - f64::from(y)) * 0.5 * height as f64,
f64::from(z),
]
});
let area = edge(screen[0], screen[1], screen[2]);
if area == 0.0 {
continue;
}
for y in 0..height {
for x in 0..width {
let centre = [x as f64 + 0.5, y as f64 + 0.5, 0.0];
let weights = [
edge(screen[1], screen[2], centre),
edge(screen[2], screen[0], centre),
edge(screen[0], screen[1], centre),
];
if weights.contains(&0.0) {
let others_inside = weights
.iter()
.filter(|&&w| w != 0.0)
.all(|&w| (w > 0.0) == (area > 0.0));
if others_inside {
return Err(DepthRefError::EdgeTie(index, x, y));
}
continue;
}
if !weights.iter().all(|&w| (w > 0.0) == (area > 0.0)) {
continue;
}
let z = (weights[0] * screen[0][2]
+ weights[1] * screen[1][2]
+ weights[2] * screen[2][2])
/ area;
let z = z as f32;
let slot = y * width + x;
if let Some(stored) = depth.as_mut() {
if !draw.compare.passes(z, stored[slot]) {
continue;
}
if draw.write {
stored[slot] = z;
}
}
color[slot] = match (draw.fill, texture) {
(RefFill::Flat(rgba), _) => rgba,
(RefFill::Texture, Some(t)) => {
let u = ((x as f64 + 0.5) / width as f64 * t.width as f64) as usize;
let v = ((y as f64 + 0.5) / height as f64 * t.height as f64) as usize;
t.texels[v.min(t.height - 1) * t.width + u.min(t.width - 1)]
}
(RefFill::Texture, None) => return Err(DepthRefError::MissingTexture),
};
}
}
}
Ok((color, depth))
}
fn edge(a: [f64; 3], b: [f64; 3], p: [f64; 3]) -> f64 {
(b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0])
}
#[cfg(test)]
mod tests {
use super::*;
const RED: [u8; 4] = [255, 0, 0, 255];
fn draw(positions: [[f32; 4]; 3], compare: CompareFunction, write: bool) -> RefDraw {
RefDraw {
positions,
fill: RefFill::Flat(RED),
compare,
write,
}
}
// A 2x2 target; this triangle covers only the centre of pixel (0, 1).
const LOWER_LEFT: [[f32; 4]; 3] = [
[-1.0, -1.0, 0.25, 1.0],
[0.5, -1.0, 0.25, 1.0],
[-1.0, 0.5, 0.25, 1.0],
];
#[test]
fn covers_by_pixel_centre_and_writes_depth() {
let (color, depth) = render_depth(
[2, 2],
[0; 4],
Some(1.0),
&[draw(LOWER_LEFT, CompareFunction::Less, true)],
None,
)
.unwrap();
assert_eq!(color, [[0; 4], [0; 4], RED, [0; 4]]);
assert_eq!(depth.unwrap(), [1.0, 1.0, 0.25, 1.0]);
}
#[test]
fn compare_functions_follow_metal_semantics() {
let expect = [false, true, false, true, false, true, false, true];
let equal = [false, false, true, true, false, false, true, true];
for (function, (&less, &eq)) in CompareFunction::ALL.iter().zip(expect.iter().zip(&equal)) {
assert_eq!(function.passes(0.25, 0.5), less, "{function:?} less");
assert_eq!(function.passes(0.5, 0.5), eq, "{function:?} equal");
assert_eq!(
function.passes(0.75, 0.5),
!matches!(
function,
CompareFunction::Never
| CompareFunction::Less
| CompareFunction::Equal
| CompareFunction::LessEqual
),
"{function:?} greater"
);
}
}
#[test]
fn rejects_edge_ties_and_depth_without_attachment() {
let tie = [
[-1.0, -1.0, 0.5, 1.0],
[1.0, 1.0, 0.5, 1.0],
[-1.0, 1.0, 0.5, 1.0],
];
assert!(matches!(
render_depth(
[2, 2],
[0; 4],
Some(1.0),
&[draw(tie, CompareFunction::Always, true)],
None
),
Err(DepthRefError::EdgeTie(0, _, _))
));
let mut far = LOWER_LEFT;
far[0][2] = 1.25;
assert_eq!(
render_depth(
[2, 2],
[0; 4],
Some(1.0),
&[draw(far, CompareFunction::Always, true)],
None
),
Err(DepthRefError::Unclipped(0))
);
assert_eq!(
render_depth(
[2, 2],
[0; 4],
None,
&[draw(LOWER_LEFT, CompareFunction::Less, false)],
None
),
Err(DepthRefError::DepthStateWithoutAttachment(0))
);
}
}
+202
View File
@@ -0,0 +1,202 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Independent CPU reference for indexed triangle-list draws.
//!
//! A draw reads `count` indices starting at index `start` and fetches vertex
//! `index + base_vertex` for each, as `DrawIndexedInstanced` and Metal's
//! `drawIndexedPrimitives` describe. Every fetched vertex must lie inside the
//! vertex buffer, and no index may be the primitive-restart value (all bits
//! set); the reference rejects the draw instead of defining either behaviour. The triangles are then rasterised by
//! [`crate::depth::render_depth`] without a depth attachment.
use std::fmt;
use crate::depth::{CompareFunction, RefDraw, RefFill, RefTexture, render_depth};
/// An index buffer of 16- or 32-bit unsigned indices.
#[derive(Clone, Copy, Debug)]
pub enum RefIndices<'a> {
U16(&'a [u16]),
U32(&'a [u32]),
}
impl RefIndices<'_> {
fn len(self) -> usize {
match self {
Self::U16(indices) => indices.len(),
Self::U32(indices) => indices.len(),
}
}
fn restart(self) -> u32 {
match self {
Self::U16(_) => u32::from(u16::MAX),
Self::U32(_) => u32::MAX,
}
}
fn get(self, position: usize) -> Option<u32> {
match self {
Self::U16(indices) => indices.get(position).map(|&index| u32::from(index)),
Self::U32(indices) => indices.get(position).copied(),
}
}
}
/// One indexed draw: a range of the index buffer, a signed base vertex and a fill.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RefIndexedDraw {
pub start: usize,
pub count: usize,
pub base_vertex: i32,
pub fill: RefFill,
}
#[derive(Debug, Eq, PartialEq)]
pub enum IndexedRefError {
/// The index count of the draw is zero or not a multiple of 3: (draw).
Count(usize),
/// The index range of the draw ends past the index buffer: (draw).
IndexRange(usize),
/// `index + base_vertex` lies outside the vertex buffer: (draw, index position).
VertexRange(usize, usize),
/// The index is the primitive-restart value: (draw, index position).
Restart(usize, usize),
/// The resolved triangles could not be rasterised.
Raster(crate::depth::DepthRefError),
}
impl fmt::Display for IndexedRefError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self:?}")
}
}
impl std::error::Error for IndexedRefError {}
/// The vertex numbers draw `draw` of a pass fetches, in index order.
///
/// # Errors
///
/// Returns an error for a count that is zero or not a multiple of 3, an index
/// range past the buffer, a primitive-restart index, or a fetched vertex
/// outside `0..vertex_count`.
pub fn fetch(
draw_number: usize,
draw: &RefIndexedDraw,
indices: RefIndices<'_>,
vertex_count: usize,
) -> Result<Vec<usize>, IndexedRefError> {
if draw.count == 0 || !draw.count.is_multiple_of(3) {
return Err(IndexedRefError::Count(draw_number));
}
let end = draw
.start
.checked_add(draw.count)
.filter(|&end| end <= indices.len())
.ok_or(IndexedRefError::IndexRange(draw_number))?;
(draw.start..end)
.map(|position| {
let index = indices.get(position).expect("position checked above");
if index == indices.restart() {
return Err(IndexedRefError::Restart(draw_number, position));
}
usize::try_from(i64::from(index) + i64::from(draw.base_vertex))
.ok()
.filter(|&vertex| vertex < vertex_count)
.ok_or(IndexedRefError::VertexRange(draw_number, position))
})
.collect()
}
/// Render indexed draws in order over a target cleared to `clear_color`.
///
/// # Errors
///
/// Returns an error when [`fetch`] rejects a draw or the resolved triangles
/// cannot be rasterised (see [`render_depth`]).
pub fn render_indexed(
extent: [usize; 2],
clear_color: [u8; 4],
vertices: &[[f32; 4]],
indices: RefIndices<'_>,
draws: &[RefIndexedDraw],
texture: Option<RefTexture<'_>>,
) -> Result<Vec<[u8; 4]>, IndexedRefError> {
let mut triangles = Vec::new();
for (number, draw) in draws.iter().enumerate() {
let fetched = fetch(number, draw, indices, vertices.len())?;
triangles.extend(fetched.as_chunks::<3>().0.iter().map(|triangle| RefDraw {
positions: triangle.map(|vertex| vertices[vertex]),
fill: draw.fill,
compare: CompareFunction::Always,
write: false,
}));
}
render_depth(extent, clear_color, None, &triangles, texture)
.map(|(color, _)| color)
.map_err(IndexedRefError::Raster)
}
#[cfg(test)]
mod tests {
use super::*;
fn draw(start: usize, count: usize, base_vertex: i32) -> RefIndexedDraw {
RefIndexedDraw {
start,
count,
base_vertex,
fill: RefFill::Flat([255; 4]),
}
}
#[test]
fn fetch_applies_start_and_signed_base_vertex() {
let indices = RefIndices::U16(&[7, 0, 1, 2, 5]);
assert_eq!(fetch(0, &draw(1, 3, 2), indices, 5), Ok(vec![2, 3, 4]));
assert_eq!(fetch(0, &draw(2, 3, -1), indices, 5), Ok(vec![0, 1, 4]));
}
#[test]
fn fetch_rejects_bad_counts_ranges_and_vertices() {
let indices = RefIndices::U32(&[0, 1, 2, u32::MAX]);
assert_eq!(
fetch(3, &draw(0, 0, 0), indices, 3),
Err(IndexedRefError::Count(3))
);
assert_eq!(
fetch(0, &draw(0, 2, 0), indices, 3),
Err(IndexedRefError::Count(0))
);
assert_eq!(
fetch(0, &draw(2, 3, 0), indices, 3),
Err(IndexedRefError::IndexRange(0))
);
assert_eq!(
fetch(0, &draw(usize::MAX, 3, 0), indices, 3),
Err(IndexedRefError::IndexRange(0))
);
assert_eq!(
fetch(0, &draw(0, 3, -1), indices, 3),
Err(IndexedRefError::VertexRange(0, 0))
);
assert_eq!(
fetch(0, &draw(0, 3, 1), indices, 3),
Err(IndexedRefError::VertexRange(0, 2))
);
assert_eq!(
fetch(0, &draw(1, 3, 0), indices, 3),
Err(IndexedRefError::Restart(0, 3))
);
// The raw restart value is rejected even when the base vertex would
// bring it into range.
let high = RefIndices::U16(&[65533, 65534, 65535]);
assert_eq!(
fetch(0, &draw(0, 3, -65533), high, 3),
Err(IndexedRefError::Restart(0, 2))
);
let high = RefIndices::U16(&[65532, 65533, 65534]);
assert_eq!(fetch(0, &draw(0, 3, -65532), high, 3), Ok(vec![0, 1, 2]));
}
}
+817 -56
View File
File diff suppressed because it is too large. Load diff
+3
View File
@@ -223,6 +223,9 @@ fn lift(
VectorSource::Immediate(_) => {
return Err(error("graphics move requires finite FP32 bits"));
}
VectorSource::Scalar(_) => {
return Err(error("graphics move from an SGPR is unsupported"));
}
};
registers[usize::from(dst)] = Some(value);
}
+530 -30
View File
@@ -8,7 +8,15 @@ mod graphics;
pub use graphics::{PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
pub use xenora_decoder::Architecture;
use xenora_decoder::{DecodeError, DecodedInstruction, Instruction, ScalarSource, VectorSource};
use xenora_decoder::{
DecodeError, DecodedInstruction, Instruction, ScalarSource, VectorBinary, VectorCompareOp,
VectorSource,
};
/// SGPR index of `vcc_lo`.
const VCC_LO: usize = 106;
/// SGPR index of `vcc_hi`.
const VCC_HI: usize = 107;
/// Entry point of all kernels produced by this compiler.
pub const ENTRY_POINT: &str = "xenora_compute";
@@ -94,6 +102,112 @@ enum Op {
target: usize,
taken: bool,
},
/// Wave32 VOPC result: bit n is EXEC[n] & (lane n exists) & test(lane n).
/// The value is wave-uniform; every thread computes it for its own wave.
LaneMask {
op: VectorCompareOp,
src0: Value,
src1: Value,
exec: u32,
},
/// `s_cbranch_vccz` on a lane-derived VCC_LO (IR annotation only).
RuntimeBranch {
mask: Value,
target: usize,
},
/// Join after a runtime `s_cbranch_vccz`: the fall-through value when the
/// mask is nonzero (branch not taken), else the value from before the branch.
JoinVccz {
mask: Value,
fallthrough: Value,
taken: Value,
},
}
impl Op {
fn operands(self) -> Vec<Value> {
match self {
Self::Load | Self::Constant(_) | Self::ScalarBranch { .. } => Vec::new(),
Self::Binary(_, left, right) => vec![left, right],
Self::MergeLanes {
active, inactive, ..
} => vec![active, inactive],
Self::Store(value) => vec![value],
Self::LaneMask { src0, src1, .. } => vec![src0, src1],
Self::RuntimeBranch { mask, .. } => vec![mask],
Self::JoinVccz {
mask,
fallthrough,
taken,
} => vec![mask, fallthrough, taken],
}
}
/// The MSL expression of a per-thread value, with operand names, the
/// dispatch index and the lane given by the caller.
fn expression(self, name: &dyn Fn(Value) -> String, index: &str, lane: &str) -> String {
match self {
Self::Load => format!("input[{index}]"),
Self::Constant(value) => format!("0x{value:08x}u"),
Self::Binary(operator, left, right) => {
let (left, right) = (name(left), name(right));
let (_, symbol) = operator.operator();
match operator {
Binary::FloatAdd | Binary::FloatMul => format!(
"as_type<uint>(as_type<float>({left}) {symbol} as_type<float>({right}))"
),
Binary::ArithmeticShiftRight => {
format!("as_type<uint>(as_type<int>({left}) {symbol} ({right} & 31u))")
}
Binary::ShiftLeft | Binary::ShiftRight => {
format!("{left} {symbol} ({right} & 31u)")
}
Binary::Vector(operation) => vector_expression(operation, &left, &right),
_ => format!("{left} {symbol} {right}"),
}
}
Self::MergeLanes {
mask,
active,
inactive,
} => format!(
"((0x{mask:08x}u >> {lane}) & 1u) != 0u ? {} : {}",
name(active),
name(inactive)
),
Self::JoinVccz {
mask,
fallthrough,
taken,
} => format!(
"{} != 0u ? {} : {}",
name(mask),
name(fallthrough),
name(taken)
),
Self::Store(_)
| Self::ScalarBranch { .. }
| Self::LaneMask { .. }
| Self::RuntimeBranch { .. } => unreachable!("not a per-thread expression"),
}
}
}
fn compare_expression(op: VectorCompareOp, left: &str, right: &str) -> String {
use xenora_decoder::CompareRelation;
let symbol = match op.relation {
CompareRelation::Less => "<",
CompareRelation::Equal => "==",
CompareRelation::LessOrEqual => "<=",
CompareRelation::Greater => ">",
CompareRelation::NotEqual => "!=",
CompareRelation::GreaterOrEqual => ">=",
};
if op.signed {
format!("as_type<int>({left}) {symbol} as_type<int>({right})")
} else {
format!("{left} {symbol} {right}")
}
}
#[derive(Clone, Copy)]
@@ -107,6 +221,8 @@ enum Binary {
Xor,
FloatAdd,
FloatMul,
/// A registry VOP2 integer operation, lowered by its typed template.
Vector(VectorBinary),
}
impl Binary {
@@ -121,10 +237,56 @@ impl Binary {
Self::Xor => ("xor.b32", "^"),
Self::FloatAdd => ("add.f32", "+"),
Self::FloatMul => ("mul.f32", "*"),
Self::Vector(operation) => (
match operation {
VectorBinary::Add => "add.u32",
VectorBinary::Sub => "sub.u32",
VectorBinary::Xnor => "xnor.b32",
VectorBinary::MinSigned => "min.i32",
VectorBinary::MinUnsigned => "min.u32",
VectorBinary::MaxSigned => "max.i32",
VectorBinary::MaxUnsigned => "max.u32",
VectorBinary::Mul24Signed => "mul24.i32",
VectorBinary::Mul24Unsigned => "mul24.u32",
VectorBinary::MulHi24Signed => "mulhi24.i32",
VectorBinary::MulHi24Unsigned => "mulhi24.u32",
},
"",
),
}
}
}
/// The MSL template of each per-lane registry operation. Integer arithmetic is
/// on `uint` (wrapping); signed forms reinterpret with `as_type`, and the
/// 24-bit forms sign-extend bit 23 with a shift pair or mask to 24 bits first.
fn vector_expression(operation: VectorBinary, left: &str, right: &str) -> String {
let int = |value: &str| format!("as_type<int>({value})");
let i24 = |value: &str| format!("(as_type<int>({value} << 8u) >> 8)");
let u24 = |value: &str| format!("({value} & 0x00ffffffu)");
match operation {
VectorBinary::Add => format!("{left} + {right}"),
VectorBinary::Sub => format!("{left} - {right}"),
VectorBinary::Xnor => format!("~({left} ^ {right})"),
VectorBinary::MinSigned => format!("as_type<uint>(min({}, {}))", int(left), int(right)),
VectorBinary::MinUnsigned => format!("min({left}, {right})"),
VectorBinary::MaxSigned => format!("as_type<uint>(max({}, {}))", int(left), int(right)),
VectorBinary::MaxUnsigned => format!("max({left}, {right})"),
// The low 32 bits of a product do not depend on signedness, so the
// sign-extended factors multiply as wrapping uint.
VectorBinary::Mul24Signed => format!(
"as_type<uint>({}) * as_type<uint>({})",
i24(left),
i24(right)
),
VectorBinary::Mul24Unsigned => format!("{} * {}", u24(left), u24(right)),
VectorBinary::MulHi24Signed => {
format!("as_type<uint>(mulhi({}, {}))", i24(left), i24(right))
}
VectorBinary::MulHi24Unsigned => format!("mulhi({}, {})", u24(left), u24(right)),
}
}
// Each bit is either known zero, known one or unconstrained.
#[derive(Clone, Copy)]
struct KnownBits {
@@ -239,8 +401,16 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
let disassembly = decoded.iter().map(|line| format!("{line}\n")).collect();
let mut ir = String::new();
let has_mask = operations
.iter()
.any(|(_, operation)| matches!(operation, Op::LaneMask { .. }));
let grid = if has_mask {
",\n uint grid [[threads_per_grid]]"
} else {
""
};
let mut msl = format!(
"#include <metal_stdlib>\nusing namespace metal;\nkernel void {ENTRY_POINT}(\n device const uint* input [[buffer(0)]],\n device uint* output [[buffer(1)]],\n uint index [[thread_position_in_grid]]) {{\n"
"#include <metal_stdlib>\nusing namespace metal;\nkernel void {ENTRY_POINT}(\n device const uint* input [[buffer(0)]],\n device uint* output [[buffer(1)]],\n uint index [[thread_position_in_grid]]{grid}) {{\n"
);
if operations.iter().any(|(_, operation)| {
matches!(
@@ -250,36 +420,32 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
}) {
msl.push_str(" #pragma clang fp contract(off)\n #pragma clang fp reassociate(off)\n");
}
for (index, (offset, operation)) in operations.into_iter().enumerate() {
// Wave-uniform values: identical in every lane of an RDNA wave.
let mut uniform = Vec::with_capacity(operations.len());
for (index, &(offset, operation)) in operations.iter().enumerate() {
let dest = Value(index);
uniform.push(match operation {
Op::Constant(_) | Op::LaneMask { .. } => true,
Op::Load | Op::MergeLanes { .. } => false,
_ => operation.operands().iter().all(|value| uniform[value.0]),
});
let thread = |value: Value| value.to_string();
let (step, statement) = match operation {
Op::Load => (
format!("{dest} = load.u32 input[index]"),
format!("uint {dest} = input[index];"),
format!(
"uint {dest} = {};",
operation.expression(&thread, "index", "")
),
),
Op::Constant(value) => (
format!("{dest} = const.u32 0x{value:08x}"),
format!("uint {dest} = 0x{value:08x}u;"),
format!("uint {dest} = {};", operation.expression(&thread, "", "")),
),
Op::Binary(operator, left, right) => (
format!("{dest} = {} {left}, {right}", operator.operator().0),
format!("uint {dest} = {};", operation.expression(&thread, "", "")),
),
Op::Binary(operator, left, right) => {
let (mnemonic, symbol) = operator.operator();
let expression = match operator {
Binary::FloatAdd | Binary::FloatMul => format!(
"as_type<uint>(as_type<float>({left}) {symbol} as_type<float>({right}))"
),
Binary::ArithmeticShiftRight => {
format!("as_type<uint>(as_type<int>({left}) {symbol} ({right} & 31u))")
}
Binary::ShiftLeft | Binary::ShiftRight => {
format!("{left} {symbol} ({right} & 31u)")
}
_ => format!("{left} {symbol} {right}"),
};
(
format!("{dest} = {mnemonic} {left}, {right}"),
format!("uint {dest} = {expression};"),
)
}
Op::ScalarBranch { target, taken } => {
let _ = writeln!(
ir,
@@ -287,6 +453,10 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
);
continue;
}
Op::RuntimeBranch { mask, target } => {
let _ = writeln!(ir, "{offset:04x}: branch.vccz {mask} -> 0x{target:04x}");
continue;
}
Op::MergeLanes {
mask,
active,
@@ -294,9 +464,32 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
} => (
format!("{dest} = merge.lanes mask=0x{mask:08x}, {active}, {inactive}"),
format!(
"uint {dest} = ((0x{mask:08x}u >> (index & 31u)) & 1u) != 0u ? {active} : {inactive};"
"uint {dest} = {};",
operation.expression(&thread, "", "(index & 31u)")
),
),
Op::JoinVccz {
mask,
fallthrough,
taken,
} => (
format!("{dest} = join.vccz {mask}, {fallthrough}, {taken}"),
format!("uint {dest} = {};", operation.expression(&thread, "", "")),
),
Op::LaneMask {
op,
src0,
src1,
exec,
} => {
let _ = writeln!(
ir,
"{offset:04x}: {dest} = wave.mask {} {src0}, {src1} exec=0x{exec:08x}",
op.mnemonic()
);
emit_lane_mask(&mut msl, &operations, &uniform, index, op, src0, src1, exec);
continue;
}
Op::Store(value) => (
format!("store.u32 output[index], {value}"),
format!("output[index] = {value};"),
@@ -314,6 +507,59 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
})
}
/// Emit a Wave32 compare mask without any cross-thread operation: the thread
/// recomputes the lane-dependent operands of each lane of its own RDNA wave
/// (dispatch indices `(index & ~31) + n`) from those lanes' input words.
/// Absent lanes of a final partial wave contribute 0.
#[allow(clippy::too_many_arguments)]
fn emit_lane_mask(
msl: &mut String,
operations: &[(usize, Op)],
uniform: &[bool],
index: usize,
op: VectorCompareOp,
src0: Value,
src1: Value,
exec: u32,
) {
let mut cone = vec![false; index];
let mut pending = vec![src0, src1];
while let Some(value) = pending.pop() {
if uniform[value.0] || cone[value.0] {
continue;
}
cone[value.0] = true;
pending.extend(operations[value.0].1.operands());
}
let name = |value: Value| {
if cone[value.0] {
format!("l{}", value.0)
} else {
value.to_string()
}
};
let dest = Value(index);
let _ = writeln!(msl, " uint {dest} = 0u;");
let _ = writeln!(
msl,
" for (uint lane = 0u; lane < 32u; ++lane) {{\n uint lane_index = (index & ~31u) + lane;\n if (lane_index >= grid) {{ break; }}"
);
for (position, &(_, operation)) in operations[..index].iter().enumerate() {
if cone[position] {
let _ = writeln!(
msl,
" uint l{position} = {};",
operation.expression(&name, "lane_index", "lane")
);
}
}
let _ = writeln!(
msl,
" uint pass = ({}) ? 1u : 0u;\n {dest} |= ((0x{exec:08x}u >> lane) & pass) << lane;\n }}",
compare_expression(op, &name(src0), &name(src1))
);
}
fn decode_fixture(
architecture: Architecture,
bytes: &[u8],
@@ -326,7 +572,7 @@ fn decode_fixture(
fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, Op)>, CompileError> {
let mut operations = Vec::new();
let mut registers = [None; 256];
let mut registers = [None::<Value>; 256];
let mut facts = Vec::<KnownBits>::new();
let mut pending_load = None;
let mut stored = false;
@@ -336,6 +582,10 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
scalars[126] = Some(exec);
let mut scc = None;
let mut skip_before = 0;
// Set while VCC_LO holds a lane-derived compare mask (scalars[VCC_LO] is then None).
let mut lane_vcc: Option<Value> = None;
// An open runtime `s_cbranch_vccz` region: its end, mask and the VGPRs at the branch.
let mut region: Option<(usize, Value, [Option<Value>; 256])> = None;
// Every decoded instruction must satisfy the fixture layout and binding
// contract, even when a known branch skips it.
@@ -378,6 +628,70 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
for instruction in decoded {
let offset = instruction.offset;
let error = |reason| CompileError::Verify { offset, reason };
if let Some((end, mask, before)) = region
&& offset >= end
{
region = None;
for slot in 0..registers.len() {
if let (Some(fallthrough), Some(taken)) = (registers[slot], before[slot])
&& fallthrough.0 != taken.0
{
let next = Value(operations.len());
operations.push((
end,
Op::JoinVccz {
mask,
fallthrough,
taken,
},
));
let (left, right) = (facts[fallthrough.0], facts[taken.0]);
// Keep up to two candidate values when both edges have them.
let values = match (left.values, right.values) {
(Some([a, b]), Some([c, d])) => {
let mut union = vec![a, b, c, d];
union.sort_unstable();
union.dedup();
match union.as_slice() {
[only] => Some([*only; 2]),
[first, second] => Some([*first, *second]),
_ => None,
}
}
_ => None,
};
facts.push(KnownBits {
zero: left.zero & right.zero,
one: left.one & right.one,
values,
});
registers[slot] = Some(next);
}
}
}
// docs/shaders/vector-compare.md section 6: checked whatever EXEC is.
if let Some((_, _, before)) = &region {
let dst = match instruction.instruction {
Instruction::MoveB32 { dst, .. }
| Instruction::AddNoCarryU32 { dst, .. }
| Instruction::VectorLshlrevB32 { dst, .. }
| Instruction::VectorLshrrevB32 { dst, .. }
| Instruction::VectorAshrrevI32 { dst, .. }
| Instruction::VectorAndB32 { dst, .. }
| Instruction::VectorOrB32 { dst, .. }
| Instruction::VectorXorB32 { dst, .. } => dst,
_ => {
return Err(error(
"code skipped by a runtime s_cbranch_vccz may contain only v_mov_b32, v_add_nc_u32_e64 and the hand-written integer VOP2 forms",
));
}
};
if before[usize::from(dst)].is_none() {
return Err(error(
"a VGPR written under a runtime s_cbranch_vccz must be initialized before the branch",
));
}
}
let read = |register: u8| {
registers[usize::from(register)].ok_or_else(|| {
error("source register is uninitialized, pending a load wait, or reserved for indexing")
@@ -406,7 +720,8 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
| Instruction::VectorOrB32 { .. }
| Instruction::VectorXorB32 { .. }
| Instruction::VectorAddF32 { .. }
| Instruction::VectorMulF32 { .. } => continue,
| Instruction::VectorMulF32 { .. }
| Instruction::VectorAlu { .. } => continue,
_ => {}
}
}
@@ -474,6 +789,36 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
dst,
src: VectorSource::Immediate(value),
} => (Some(dst), Op::Constant(value)),
Instruction::MoveB32 {
dst,
src: VectorSource::Scalar(register),
} if usize::from(register) == VCC_LO
&& let Some(mask) = lane_vcc =>
{
let slot = usize::from(dst);
if dst == 0 || pending_load.is_some_and(|(register, _)| register == slot) {
return Err(error(
"move writes the index register or replaces a pending load",
));
}
registers[slot] = Some(merge_lanes(
&mut operations,
&mut facts,
offset,
exec,
mask,
registers[slot],
)?);
continue;
}
// SGPR values are wave-uniform and known during translation.
Instruction::MoveB32 {
dst,
src: VectorSource::Scalar(register),
} => (
Some(dst),
Op::Constant(read_scalar(ScalarSource::Register(register))?),
),
Instruction::AddNoCarryU32 { dst, src0, src1 } => {
(Some(dst), Op::Binary(Binary::Add, read(src0)?, read(src1)?))
}
@@ -506,16 +851,117 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
if dst == 126 {
exec = value;
}
if usize::from(dst) == VCC_LO {
lane_vcc = None;
}
let slot = scalars
.get_mut(usize::from(dst))
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
*slot = Some(value);
continue;
}
Instruction::ScalarCompareEqU32 { src0, src1 } => {
scc = Some(read_scalar(src0)? == read_scalar(src1)?);
Instruction::ScalarUnary { op, dst, src } => {
let src = read_scalar(src)?;
if dst < 8 {
return Err(error("scalar unary would modify a resource descriptor"));
}
let (value, flag) = op.evaluate(src);
let slot = scalars
.get_mut(usize::from(dst))
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
*slot = Some(value);
if let Some(flag) = flag {
scc = Some(flag);
}
continue;
}
Instruction::ScalarAlu {
op,
dst,
src0,
src1,
} => {
let (src0, src1) = (read_scalar(src0)?, read_scalar(src1)?);
let scc_in = if op.reads_scc() {
scc.ok_or_else(|| error("SOP2 SCC input reads uninitialized SCC"))?
} else {
false
};
if dst < 8 {
return Err(error("scalar ALU would modify a resource descriptor"));
}
let (value, flag) = op.evaluate(src0, src1, scc_in);
let slot = scalars
.get_mut(usize::from(dst))
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
*slot = Some(value);
if let Some(flag) = flag {
scc = Some(flag);
}
continue;
}
Instruction::ScalarCompare { op, src0, src1 } => {
scc = Some(op.test(read_scalar(src0)?, read_scalar(src1)?));
continue;
}
// docs/shaders/vector-compare.md sections 3 and 5.
Instruction::VectorCompare { op, src0, src1 } => {
if exec == 0 {
scalars[VCC_HI] = None;
scalars[VCC_LO] = Some(0);
lane_vcc = None;
continue;
}
let constant =
|operations: &mut Vec<(usize, Op)>, facts: &mut Vec<KnownBits>, bits: u32| {
let value = Value(operations.len());
operations.push((offset, Op::Constant(bits)));
facts.push(KnownBits::constant(bits));
value
};
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, bits),
(None, None) => {
return Err(error("compare reads uninitialized VCC_LO"));
}
}
}
VectorSource::Scalar(register) => {
let bits = read_scalar(ScalarSource::Register(register))?;
constant(&mut operations, &mut facts, bits)
}
VectorSource::Immediate(bits) => constant(&mut operations, &mut facts, bits),
};
let src1 = read(src1)?;
let mask = Value(operations.len());
operations.push((
offset,
Op::LaneMask {
op,
src0,
src1,
exec,
},
));
facts.push(KnownBits::UNKNOWN);
scalars[VCC_LO] = None;
scalars[VCC_HI] = None;
lane_vcc = Some(mask);
continue;
}
Instruction::BranchVccZero { target } if let Some(mask) = lane_vcc => {
if pending_load.is_some() {
return Err(error(
"a runtime s_cbranch_vccz requires no outstanding vector load",
));
}
region = Some((target, mask, registers));
(None, Op::RuntimeBranch { mask, target })
}
Instruction::BranchSccZero { target }
| Instruction::BranchExecZero { target }
| Instruction::BranchVccZero { target } => {
@@ -545,6 +991,44 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
},
)
}
Instruction::VectorAlu {
op,
dst,
src0,
src1,
} => {
let src0 = match src0 {
VectorSource::Register(register) => read(register)?,
VectorSource::Scalar(register) if usize::from(register) == VCC_LO => {
match (lane_vcc, scalars[VCC_LO]) {
(Some(mask), _) => mask,
(None, Some(bits)) => {
constant(&mut operations, &mut facts, offset, bits)
}
(None, None) => {
return Err(error("vector ALU reads uninitialized VCC_LO"));
}
}
}
VectorSource::Scalar(register) => {
let bits = read_scalar(ScalarSource::Register(register))?;
constant(&mut operations, &mut facts, offset, bits)
}
VectorSource::Immediate(bits) => {
constant(&mut operations, &mut facts, offset, bits)
}
};
let src1 = read(src1)?;
let (left, right) = if op.swaps_sources() {
(src1, src0)
} else {
(src0, src1)
};
(
Some(dst),
Op::Binary(Binary::Vector(op.lowering()), left, right),
)
}
Instruction::VectorAddF32 { dst, src0, src1 } => (
Some(dst),
Op::Binary(Binary::FloatAdd, read(src0)?, read(src1)?),
@@ -580,6 +1064,9 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
}
_ => KnownBits::UNKNOWN,
};
// Arms may push operand constants first, so the result is the next slot
// now rather than `next`.
let produced = Value(operations.len());
facts.push(value_bits);
operations.push((offset, operation));
if let Some(dest) = dest {
@@ -594,7 +1081,7 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
&mut facts,
offset,
exec,
next,
produced,
registers[slot],
)?);
}
@@ -605,6 +1092,19 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
})
}
/// A wave-uniform constant operand at `offset`.
fn constant(
operations: &mut Vec<(usize, Op)>,
facts: &mut Vec<KnownBits>,
offset: usize,
bits: u32,
) -> Value {
let value = Value(operations.len());
operations.push((offset, Op::Constant(bits)));
facts.push(KnownBits::constant(bits));
value
}
// Keeping a value for inactive lanes requires a previously initialized destination.
fn merge_lanes(
operations: &mut Vec<(usize, Op)>,
+98
View File
@@ -265,3 +265,101 @@ fn checks_fixture_layout_and_bindings_even_in_skipped_code() {
assert!(compiled.msl.contains("uint t1 = input[index];"));
assert!(compiled.msl.contains("output[index] = t3;"));
}
#[test]
fn scalar_alu_results_reach_the_kernel_as_constants() {
let code = include_bytes!("../../../fixtures/rdna2/scalar-alu.bin");
let compiled = compile(Architecture::Gfx1030, code).unwrap();
assert_eq!(
compiled.ir,
include_str!("../../../fixtures/golden/scalar-alu.ir")
);
assert_eq!(
compiled.msl,
include_str!("../../../fixtures/golden/scalar-alu.metal")
);
}
#[test]
fn scalar_logic_results_reach_the_kernel_as_constants() {
let code = include_bytes!("../../../fixtures/rdna2/scalar-logic.bin");
let compiled = compile(Architecture::Gfx1030, code).unwrap();
assert_eq!(
compiled.ir,
include_str!("../../../fixtures/golden/scalar-logic.ir")
);
assert_eq!(
compiled.msl,
include_str!("../../../fixtures/golden/scalar-logic.metal")
);
}
#[test]
fn scalar_compare_results_resolve_every_branch() {
let code = include_bytes!("../../../fixtures/rdna2/scalar-compare.bin");
let compiled = compile(Architecture::Gfx1030, code).unwrap();
assert_eq!(
compiled.ir,
include_str!("../../../fixtures/golden/scalar-compare.ir")
);
assert_eq!(
compiled.msl,
include_str!("../../../fixtures/golden/scalar-compare.metal")
);
}
#[test]
fn scalar_unary_results_reach_the_kernel_as_constants() {
let code = include_bytes!("../../../fixtures/rdna2/scalar-unary.bin");
let compiled = compile(Architecture::Gfx1030, code).unwrap();
assert_eq!(
compiled.ir,
include_str!("../../../fixtures/golden/scalar-unary.ir")
);
assert_eq!(
compiled.msl,
include_str!("../../../fixtures/golden/scalar-unary.metal")
);
}
#[test]
fn scalar_arith_results_reach_the_kernel_as_constants() {
let code = include_bytes!("../../../fixtures/rdna2/scalar-arith.bin");
let compiled = compile(Architecture::Gfx1030, code).unwrap();
assert_eq!(
compiled.ir,
include_str!("../../../fixtures/golden/scalar-arith.ir")
);
assert_eq!(
compiled.msl,
include_str!("../../../fixtures/golden/scalar-arith.metal")
);
}
#[test]
fn vector_integer_forms_lower_to_per_lane_templates() {
let code = include_bytes!("../../../fixtures/rdna2/vector-integer.bin");
let compiled = compile(Architecture::Gfx1030, code).unwrap();
assert_eq!(
compiled.ir,
include_str!("../../../fixtures/golden/vector-integer.ir")
);
assert_eq!(
compiled.msl,
include_str!("../../../fixtures/golden/vector-integer.metal")
);
}
#[test]
fn vector_compares_lower_to_per_thread_wave_masks_and_selects() {
let code = include_bytes!("../../../fixtures/rdna2/vector-compare.bin");
let result = compile(Architecture::Gfx1030, code).unwrap();
assert_eq!(
result.ir,
include_str!("../../../fixtures/golden/vector-compare.ir")
);
assert_eq!(
result.msl,
include_str!("../../../fixtures/golden/vector-compare.metal")
);
}
+138
View File
@@ -0,0 +1,138 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! CPU block decoders for BC2, BC3, BC4 and BC5.
//!
//! Sources (public): Microsoft, "Texture Block Compression in Direct3D 11"
//! (sections BC2, BC3, BC4, BC5) and "Block Compression (Direct3D 10)"; Khronos
//! Data Format Specification 1.3, sections "S3TC compressed texture image
//! formats" and "RGTC compressed texture image formats".
//!
//! Colour blocks of BC2 and BC3 always use the four-colour interpolation,
//! whatever the order of their endpoints (Khronos, "S3TC compressed texture
//! image formats", DXT3/DXT5 subsections; the BC1 three-colour/alpha mode does
//! not apply). Texels are row-major, texel 0 at the top-left.
//!
//! Rounding: every interpolated value uses integer division that truncates
//! toward zero (the same rule `decode_bc1` uses). For unsigned values that is
//! floor. BC2 alpha nibbles expand as `v * 17`. The specifications define the
//! interpolation in real numbers; truncation is this crate's integer choice.
//!
//! SNORM: the specification maps both -128 and -127 to -1.0. Endpoints are
//! compared as the stored signed bytes; for interpolation -128 is treated as
//! -127. Output bytes are the stored endpoint bytes for indices 0 and 1 (so
//! -128 is preserved, not rewritten) and -127 / 127 for the fixed values.
use super::rgb565;
/// Reads texel `n` of a packed little-endian 48-bit array of 3-bit indices.
fn index3(bytes: &[u8; 6], n: usize) -> usize {
let mut bits = 0u64;
for (i, b) in bytes.iter().enumerate() {
bits |= u64::from(*b) << (8 * i);
}
((bits >> (3 * n)) & 7) as usize
}
fn unorm_palette(a0: u8, a1: u8) -> [u8; 8] {
let (x, y) = (u16::from(a0), u16::from(a1));
let mut p = [a0, a1, 0, 0, 0, 0, 0, 255];
if a0 > a1 {
for k in 1..=6u16 {
p[(k + 1) as usize] = (((7 - k) * x + k * y) / 7) as u8;
}
} else {
for k in 1..=4u16 {
p[(k + 1) as usize] = (((5 - k) * x + k * y) / 5) as u8;
}
p[6] = 0;
}
p
}
fn snorm_palette(a0: i8, a1: i8) -> [i8; 8] {
let x = i16::from(a0).max(-127);
let y = i16::from(a1).max(-127);
let mut p = [a0, a1, 0, 0, 0, 0, 0, 0];
if a0 > a1 {
for k in 1..=6i16 {
p[(k + 1) as usize] = (((7 - k) * x + k * y) / 7) as i8;
}
} else {
for k in 1..=4i16 {
p[(k + 1) as usize] = (((5 - k) * x + k * y) / 5) as i8;
}
p[6] = -127;
p[7] = 127;
}
p
}
fn unorm_block(block: &[u8]) -> [u8; 16] {
let p = unorm_palette(block[0], block[1]);
let idx: [u8; 6] = block[2..8].try_into().unwrap();
std::array::from_fn(|t| p[index3(&idx, t)])
}
fn snorm_block(block: &[u8]) -> [i8; 16] {
let p = snorm_palette(block[0] as i8, block[1] as i8);
let idx: [u8; 6] = block[2..8].try_into().unwrap();
std::array::from_fn(|t| p[index3(&idx, t)])
}
/// Decodes a BC4 UNORM block to 16 row-major red values.
pub fn decode_bc4_unorm(block: [u8; 8]) -> [u8; 16] {
unorm_block(&block)
}
/// Decodes a BC4 SNORM block to 16 row-major signed red values.
pub fn decode_bc4_snorm(block: [u8; 8]) -> [i8; 16] {
snorm_block(&block)
}
/// Decodes a BC5 UNORM block; each texel is `[red, green]` (first 8 bytes red).
pub fn decode_bc5_unorm(block: [u8; 16]) -> [[u8; 2]; 16] {
let r = unorm_block(&block[..8]);
let g = unorm_block(&block[8..]);
std::array::from_fn(|t| [r[t], g[t]])
}
/// Decodes a BC5 SNORM block; each texel is `[red, green]`.
pub fn decode_bc5_snorm(block: [u8; 16]) -> [[i8; 2]; 16] {
let r = snorm_block(&block[..8]);
let g = snorm_block(&block[8..]);
std::array::from_fn(|t| [r[t], g[t]])
}
/// Four-colour BC1-style palette, forced regardless of endpoint order.
fn colour_block(block: &[u8]) -> [[u8; 4]; 16] {
let first = u16::from_le_bytes([block[0], block[1]]);
let second = u16::from_le_bytes([block[2], block[3]]);
let mut p = [rgb565(first), rgb565(second), [255; 4], [255; 4]];
for c in 0..3 {
let a = u16::from(p[0][c]);
let b = u16::from(p[1][c]);
p[2][c] = ((2 * a + b) / 3) as u8;
p[3][c] = ((a + 2 * b) / 3) as u8;
}
let bits = u32::from_le_bytes([block[4], block[5], block[6], block[7]]);
std::array::from_fn(|t| p[((bits >> (2 * t)) & 3) as usize])
}
/// Decodes a BC2 block to 16 row-major RGBA8 texels (explicit 4-bit alpha).
pub fn decode_bc2(block: [u8; 16]) -> [[u8; 4]; 16] {
let mut out = colour_block(&block[8..]);
for (t, px) in out.iter_mut().enumerate() {
// Two texels per byte, low nibble first.
px[3] = ((block[t / 2] >> (4 * (t % 2))) & 15) * 17;
}
out
}
/// Decodes a BC3 block to 16 row-major RGBA8 texels (interpolated alpha).
pub fn decode_bc3(block: [u8; 16]) -> [[u8; 4]; 16] {
let mut out = colour_block(&block[8..]);
let alpha = unorm_block(&block[..8]);
for (px, a) in out.iter_mut().zip(alpha) {
px[3] = a;
}
out
}
+198
View File
@@ -0,0 +1,198 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! CPU block decoder for a bounded subset of BC6H.
//!
//! Source (public): Khronos Data Format Specification 1.3, section 20.2
//! "BC6H" (Tables 121 and 122, unquantization and final unquantization) and
//! section 20.1 (BC7 interpolation, Equation 2 and Table 119); Microsoft,
//! "BC6H Format" (Direct3D 11).
//!
//! Supported: the four single-subset modes, numbered as Khronos numbers
//! them (Microsoft's modes 11 to 14 in brackets): 3 (11, 10-bit endpoints),
//! 7 (12, 11-bit base, 9-bit deltas), 11 (13, 12-bit base, 8-bit deltas) and
//! 15 (14, 16-bit base, 4-bit deltas), for both signed and unsigned data.
//! Reserved modes 19, 23, 27 and 31 decode to zero as the specification
//! requires. The ten two-subset modes are rejected with
//! [`Bc6hError::UnsupportedMode`]; they are not implemented.
//!
//! Output texels are row-major `[r, g, b]` half-float bit patterns; the
//! format's alpha is always 1.0 and is not returned.
//!
//! Final unquantization follows the Khronos text: a negative interpolated
//! value keeps its sign bit even when its magnitude rounds to zero, so -1
//! becomes 0x8000 (-0.0). Microsoft's sample code returns 0x0000 there. This
//! is an open difference between the two public sources, not a hardware fact.
/// Khronos mode numbers this decoder implements.
pub const BC6H_SUPPORTED_MODES: [u8; 4] = [3, 7, 11, 15];
#[derive(Debug, PartialEq, Eq)]
pub enum Bc6hError {
/// A two-subset mode, identified by its Khronos mode number.
UnsupportedMode(u8),
}
/// Returns the block's Khronos mode number: the low two bits when they are
/// below two, otherwise the low five bits.
pub fn bc6h_mode(block: [u8; 16]) -> u8 {
if block[0] & 3 < 2 {
block[0] & 3
} else {
block[0] & 31
}
}
/// Decodes an unsigned (UF16) BC6H block.
pub fn decode_bc6h_ufloat(block: [u8; 16]) -> Result<[[u16; 3]; 16], Bc6hError> {
decode(block, false)
}
/// Decodes a signed (SF16) BC6H block.
pub fn decode_bc6h_sfloat(block: [u8; 16]) -> Result<[[u16; 3]; 16], Bc6hError> {
decode(block, true)
}
/// Reads the block from its least significant bit upward.
struct Bits {
bits: u128,
offset: u32,
}
impl Bits {
fn take(&mut self, count: u32) -> u32 {
let value = (self.bits >> self.offset) as u32 & ((1u32 << count) - 1);
self.offset += count;
value
}
/// `v[high..=low]`, lowest block bit first into bit `low`.
fn field(&mut self, target: &mut i32, high: u32, low: u32) {
*target |= (self.take(high - low + 1) << low) as i32;
}
/// Table 122's reversed `v[a..b]` with `a < b`: the lowest block bit
/// lands in bit `b` and each following bit one position lower.
fn reversed(&mut self, target: &mut i32, low: u32, high: u32) {
for bit in (low..=high).rev() {
*target |= (self.take(1) << bit) as i32;
}
}
}
/// Endpoint bits, delta bits and whether E1 is stored relative to E0.
fn single_subset(mode: u8) -> Option<(u32, u32, bool)> {
match mode {
3 => Some((10, 10, false)),
7 => Some((11, 9, true)),
11 => Some((12, 8, true)),
15 => Some((16, 4, true)),
_ => None,
}
}
fn sign_extend(value: i32, bits: u32) -> i32 {
let shift = 32 - bits;
(value << shift) >> shift
}
fn unquantize(x: i32, bits: u32, signed: bool) -> i32 {
if !signed {
if bits >= 15 {
x
} else if x == 0 {
0
} else if x == (1 << bits) - 1 {
0xffff
} else {
((x << 15) + 0x4000) >> (bits - 1)
}
} else if bits >= 16 {
x
} else {
let magnitude = x.abs();
let unq = if magnitude == 0 {
0
} else if magnitude >= (1 << (bits - 1)) - 1 {
0x7fff
} else {
((magnitude << 15) + 0x4000) >> (bits - 1)
};
if x < 0 { -unq } else { unq }
}
}
fn finish(i: i32, signed: bool) -> u16 {
if !signed {
((i * 31) >> 6) as u16
} else if i < 0 {
((((-i) * 31) >> 5) | 0x8000) as u16
} else {
((i * 31) >> 5) as u16
}
}
const WEIGHTS: [i32; 16] = [0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64];
fn decode(block: [u8; 16], signed: bool) -> Result<[[u16; 3]; 16], Bc6hError> {
let mode = bc6h_mode(block);
if matches!(mode, 19 | 23 | 27 | 31) {
return Ok([[0; 3]; 16]);
}
let (epb, delta, transformed) = single_subset(mode).ok_or(Bc6hError::UnsupportedMode(mode))?;
let mut bits = Bits {
bits: u128::from_le_bytes(block),
offset: 5,
};
let mut e0 = [0i32; 3];
let mut e1 = [0i32; 3];
for channel in &mut e0 {
bits.field(channel, 9, 0);
}
for c in 0..3 {
match mode {
3 => bits.field(&mut e1[c], 9, 0),
7 => {
bits.field(&mut e1[c], 8, 0);
bits.field(&mut e0[c], 10, 10);
}
11 => {
bits.field(&mut e1[c], 7, 0);
bits.reversed(&mut e0[c], 10, 11);
}
_ => {
bits.field(&mut e1[c], 3, 0);
bits.reversed(&mut e0[c], 10, 15);
}
}
}
debug_assert_eq!(bits.offset, 65);
let mut ends = [[0i32; 3]; 2];
for c in 0..3 {
let mut a = e0[c];
let mut b = e1[c];
if signed {
a = sign_extend(a, epb);
}
if transformed || signed {
b = sign_extend(b, delta);
}
if transformed {
b = (a + b) & ((1 << epb) - 1);
if signed {
b = sign_extend(b, epb);
}
}
ends[0][c] = unquantize(a, epb, signed);
ends[1][c] = unquantize(b, epb, signed);
}
let mut texels = [[0u16; 3]; 16];
for (texel, out) in texels.iter_mut().enumerate() {
// Texel 0 is the anchor: its implicit high index bit is zero.
let index = bits.take(if texel == 0 { 3 } else { 4 }) as usize;
let w = WEIGHTS[index];
for c in 0..3 {
let i = ((64 - w) * ends[0][c] + w * ends[1][c] + 32) >> 6;
out[c] = finish(i, signed);
}
}
Ok(texels)
}
+366
View File
@@ -0,0 +1,366 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! CPU block decoder for BC7 (BPTC RGBA, unsigned normalized).
//!
//! Source (public): Khronos Data Format Specification 1.3, section 20.1
//! "BC7": Table 109 (mode parameters), Table 111 (bit layout), the endpoint
//! P-bit and bit-replication text, Tables 114-118 (partitions and anchor
//! indices), the index-offset formula, Equation 2 with Table 119 (weights)
//! and Table 120 (rotation). Microsoft's "BC7 Format" pages describe the same
//! format. The partition and anchor tables below were extracted mechanically
//! from the Khronos HTML and checked for consistency (every anchor lies in its
//! subset).
//!
//! All eight modes are decoded. A block whose low byte is zero has no mode;
//! the specification says decoders return 0 for every channel of every texel,
//! and [`decode_bc7`] does so. [`bc7_mode`] tells such blocks apart.
//!
//! Output is the 8-bit value of each channel, row-major, texel 0 at the
//! top-left. The sRGB variant uses the same bytes with a different transfer
//! function, which is outside this decoder.
/// Modes this decoder implements (Khronos/Microsoft numbering).
pub const BC7_SUPPORTED_MODES: [u8; 8] = [0, 1, 2, 3, 4, 5, 6, 7];
/// Table 109, one row per mode.
struct Mode {
subsets: usize,
partition_bits: u32,
rotation_bits: u32,
index_selection_bits: u32,
color_bits: u32,
alpha_bits: u32,
endpoint_pbits: bool,
shared_pbits: bool,
index_bits: u32,
index2_bits: u32,
}
#[rustfmt::skip]
const MODES: [Mode; 8] = [
Mode { subsets: 3, partition_bits: 4, rotation_bits: 0, index_selection_bits: 0, color_bits: 4, alpha_bits: 0, endpoint_pbits: true, shared_pbits: false, index_bits: 3, index2_bits: 0 },
Mode { subsets: 2, partition_bits: 6, rotation_bits: 0, index_selection_bits: 0, color_bits: 6, alpha_bits: 0, endpoint_pbits: false, shared_pbits: true, index_bits: 3, index2_bits: 0 },
Mode { subsets: 3, partition_bits: 6, rotation_bits: 0, index_selection_bits: 0, color_bits: 5, alpha_bits: 0, endpoint_pbits: false, shared_pbits: false, index_bits: 2, index2_bits: 0 },
Mode { subsets: 2, partition_bits: 6, rotation_bits: 0, index_selection_bits: 0, color_bits: 7, alpha_bits: 0, endpoint_pbits: true, shared_pbits: false, index_bits: 2, index2_bits: 0 },
Mode { subsets: 1, partition_bits: 0, rotation_bits: 2, index_selection_bits: 1, color_bits: 5, alpha_bits: 6, endpoint_pbits: false, shared_pbits: false, index_bits: 2, index2_bits: 3 },
Mode { subsets: 1, partition_bits: 0, rotation_bits: 2, index_selection_bits: 0, color_bits: 7, alpha_bits: 8, endpoint_pbits: false, shared_pbits: false, index_bits: 2, index2_bits: 2 },
Mode { subsets: 1, partition_bits: 0, rotation_bits: 0, index_selection_bits: 0, color_bits: 7, alpha_bits: 7, endpoint_pbits: true, shared_pbits: false, index_bits: 4, index2_bits: 0 },
Mode { subsets: 2, partition_bits: 6, rotation_bits: 0, index_selection_bits: 0, color_bits: 5, alpha_bits: 5, endpoint_pbits: true, shared_pbits: false, index_bits: 2, index2_bits: 0 },
];
/// Table 119 weights for 2-, 3- and 4-bit indices.
const WEIGHTS2: [u16; 4] = [0, 21, 43, 64];
const WEIGHTS3: [u16; 8] = [0, 9, 18, 27, 37, 46, 55, 64];
const WEIGHTS4: [u16; 16] = [0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64];
/// Table 114: subset of each texel (row-major) for the 64 two-subset partitions.
const PARTITION2: [[u8; 16]; 64] = [
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1], // 0
[0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1], // 1
[0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1], // 2
[0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1], // 3
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1], // 4
[0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1], // 5
[0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1], // 6
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1], // 7
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1], // 8
[0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], // 9
[0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1], // 10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1], // 11
[0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], // 12
[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1], // 13
[0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], // 14
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1], // 15
[0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1], // 16
[0, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], // 17
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0], // 18
[0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0], // 19
[0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0], // 20
[0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0], // 21
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0], // 22
[0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1], // 23
[0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0], // 24
[0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0], // 25
[0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0], // 26
[0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0], // 27
[0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0], // 28
[0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0], // 29
[0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0], // 30
[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0], // 31
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1], // 32
[0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1], // 33
[0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0], // 34
[0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0], // 35
[0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0], // 36
[0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0], // 37
[0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1], // 38
[0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1], // 39
[0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0], // 40
[0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0], // 41
[0, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0], // 42
[0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0], // 43
[0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0], // 44
[0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1], // 45
[0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1], // 46
[0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0], // 47
[0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0], // 48
[0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0], // 49
[0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0], // 50
[0, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], // 51
[0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1], // 52
[0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 1], // 53
[0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0], // 54
[0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0], // 55
[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 1], // 56
[0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1], // 57
[0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1], // 58
[0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1], // 59
[0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1], // 60
[0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0], // 61
[0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0], // 62
[0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1], // 63
];
/// Table 115: subset of each texel (row-major) for the 64 three-subset partitions.
const PARTITION3: [[u8; 16]; 64] = [
[0, 0, 1, 1, 0, 0, 1, 1, 0, 2, 2, 1, 2, 2, 2, 2], // 0
[0, 0, 0, 1, 0, 0, 1, 1, 2, 2, 1, 1, 2, 2, 2, 1], // 1
[0, 0, 0, 0, 2, 0, 0, 1, 2, 2, 1, 1, 2, 2, 1, 1], // 2
[0, 2, 2, 2, 0, 0, 2, 2, 0, 0, 1, 1, 0, 1, 1, 1], // 3
[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 2, 1, 1, 2, 2], // 4
[0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 2, 2, 0, 0, 2, 2], // 5
[0, 0, 2, 2, 0, 0, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1], // 6
[0, 0, 1, 1, 0, 0, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1], // 7
[0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2], // 8
[0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2], // 9
[0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2], // 10
[0, 0, 1, 2, 0, 0, 1, 2, 0, 0, 1, 2, 0, 0, 1, 2], // 11
[0, 1, 1, 2, 0, 1, 1, 2, 0, 1, 1, 2, 0, 1, 1, 2], // 12
[0, 1, 2, 2, 0, 1, 2, 2, 0, 1, 2, 2, 0, 1, 2, 2], // 13
[0, 0, 1, 1, 0, 1, 1, 2, 1, 1, 2, 2, 1, 2, 2, 2], // 14
[0, 0, 1, 1, 2, 0, 0, 1, 2, 2, 0, 0, 2, 2, 2, 0], // 15
[0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 2, 1, 1, 2, 2], // 16
[0, 1, 1, 1, 0, 0, 1, 1, 2, 0, 0, 1, 2, 2, 0, 0], // 17
[0, 0, 0, 0, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2], // 18
[0, 0, 2, 2, 0, 0, 2, 2, 0, 0, 2, 2, 1, 1, 1, 1], // 19
[0, 1, 1, 1, 0, 1, 1, 1, 0, 2, 2, 2, 0, 2, 2, 2], // 20
[0, 0, 0, 1, 0, 0, 0, 1, 2, 2, 2, 1, 2, 2, 2, 1], // 21
[0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 2, 2, 0, 1, 2, 2], // 22
[0, 0, 0, 0, 1, 1, 0, 0, 2, 2, 1, 0, 2, 2, 1, 0], // 23
[0, 1, 2, 2, 0, 1, 2, 2, 0, 0, 1, 1, 0, 0, 0, 0], // 24
[0, 0, 1, 2, 0, 0, 1, 2, 1, 1, 2, 2, 2, 2, 2, 2], // 25
[0, 1, 1, 0, 1, 2, 2, 1, 1, 2, 2, 1, 0, 1, 1, 0], // 26
[0, 0, 0, 0, 0, 1, 1, 0, 1, 2, 2, 1, 1, 2, 2, 1], // 27
[0, 0, 2, 2, 1, 1, 0, 2, 1, 1, 0, 2, 0, 0, 2, 2], // 28
[0, 1, 1, 0, 0, 1, 1, 0, 2, 0, 0, 2, 2, 2, 2, 2], // 29
[0, 0, 1, 1, 0, 1, 2, 2, 0, 1, 2, 2, 0, 0, 1, 1], // 30
[0, 0, 0, 0, 2, 0, 0, 0, 2, 2, 1, 1, 2, 2, 2, 1], // 31
[0, 0, 0, 0, 0, 0, 0, 2, 1, 1, 2, 2, 1, 2, 2, 2], // 32
[0, 2, 2, 2, 0, 0, 2, 2, 0, 0, 1, 2, 0, 0, 1, 1], // 33
[0, 0, 1, 1, 0, 0, 1, 2, 0, 0, 2, 2, 0, 2, 2, 2], // 34
[0, 1, 2, 0, 0, 1, 2, 0, 0, 1, 2, 0, 0, 1, 2, 0], // 35
[0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 0, 0, 0, 0], // 36
[0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0], // 37
[0, 1, 2, 0, 2, 0, 1, 2, 1, 2, 0, 1, 0, 1, 2, 0], // 38
[0, 0, 1, 1, 2, 2, 0, 0, 1, 1, 2, 2, 0, 0, 1, 1], // 39
[0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 0, 0, 0, 0, 1, 1], // 40
[0, 1, 0, 1, 0, 1, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2], // 41
[0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 2, 1, 2, 1, 2, 1], // 42
[0, 0, 2, 2, 1, 1, 2, 2, 0, 0, 2, 2, 1, 1, 2, 2], // 43
[0, 0, 2, 2, 0, 0, 1, 1, 0, 0, 2, 2, 0, 0, 1, 1], // 44
[0, 2, 2, 0, 1, 2, 2, 1, 0, 2, 2, 0, 1, 2, 2, 1], // 45
[0, 1, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 0, 1, 0, 1], // 46
[0, 0, 0, 0, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1, 2, 1], // 47
[0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 2, 2, 2, 2], // 48
[0, 2, 2, 2, 0, 1, 1, 1, 0, 2, 2, 2, 0, 1, 1, 1], // 49
[0, 0, 0, 2, 1, 1, 1, 2, 0, 0, 0, 2, 1, 1, 1, 2], // 50
[0, 0, 0, 0, 2, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2], // 51
[0, 2, 2, 2, 0, 1, 1, 1, 0, 1, 1, 1, 0, 2, 2, 2], // 52
[0, 0, 0, 2, 1, 1, 1, 2, 1, 1, 1, 2, 0, 0, 0, 2], // 53
[0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 2, 2, 2, 2], // 54
[0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 1, 2, 2, 1, 1, 2], // 55
[0, 1, 1, 0, 0, 1, 1, 0, 2, 2, 2, 2, 2, 2, 2, 2], // 56
[0, 0, 2, 2, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 2, 2], // 57
[0, 0, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2, 0, 0, 2, 2], // 58
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 1, 2], // 59
[0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 1], // 60
[0, 2, 2, 2, 1, 2, 2, 2, 0, 2, 2, 2, 1, 2, 2, 2], // 61
[0, 1, 0, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2], // 62
[0, 1, 1, 1, 2, 0, 1, 1, 2, 2, 0, 1, 2, 2, 2, 0], // 63
];
/// Table 118: anchor index of subset 1, two-subset partitions.
const ANCHOR2: [u8; 64] = [
15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 2, 8, 2, 2, 8, 8, 15, 2, 8,
2, 2, 8, 8, 2, 2, 15, 15, 6, 8, 2, 8, 15, 15, 2, 8, 2, 2, 2, 15, 15, 6, 6, 2, 6, 8, 15, 15, 2,
2, 15, 15, 15, 15, 15, 2, 2, 15,
];
/// Table 116: anchor index of subset 1, three-subset partitions.
const ANCHOR3_2: [u8; 64] = [
3, 3, 15, 15, 8, 3, 15, 15, 8, 8, 6, 6, 6, 5, 3, 3, 3, 3, 8, 15, 3, 3, 6, 10, 5, 8, 8, 6, 8, 5,
15, 15, 8, 15, 3, 5, 6, 10, 8, 15, 15, 3, 15, 5, 15, 15, 15, 15, 3, 15, 5, 5, 5, 8, 5, 10, 5,
10, 8, 13, 15, 12, 3, 3,
];
/// Table 117: anchor index of subset 2, three-subset partitions.
const ANCHOR3_3: [u8; 64] = [
15, 8, 8, 3, 15, 15, 3, 8, 15, 15, 15, 15, 15, 15, 15, 8, 15, 8, 15, 3, 15, 8, 15, 8, 3, 15, 6,
10, 15, 15, 10, 8, 15, 3, 15, 10, 10, 8, 9, 10, 6, 15, 8, 15, 3, 6, 6, 8, 15, 3, 15, 15, 15,
15, 15, 15, 15, 15, 15, 15, 3, 15, 15, 8,
];
/// Reads the block's bits in increasing order, starting at bit 0 of byte 0.
struct Bits {
value: u128,
pos: u32,
}
impl Bits {
fn read(&mut self, n: u32) -> u32 {
let v = if n == 0 {
0
} else {
((self.value >> self.pos) & ((1u128 << n) - 1)) as u32
};
self.pos += n;
v
}
}
/// Returns the block's mode (the position of the lowest set bit of byte 0),
/// or `None` when byte 0 is zero, which the specification reserves.
pub fn bc7_mode(block: &[u8; 16]) -> Option<u8> {
(block[0] != 0).then(|| block[0].trailing_zeros() as u8)
}
/// Appends the P-bit (when present) below the stored bits and fills the rest
/// of the byte by replicating the top bits.
fn expand(stored: u32, bits: u32, pbit: Option<u32>) -> u8 {
let (v, width) = match pbit {
Some(p) => ((stored << 1) | p, bits + 1),
None => (stored, bits),
};
let high = v << (8 - width);
(high | (high >> width)) as u8
}
fn weights(bits: u32) -> &'static [u16] {
match bits {
2 => &WEIGHTS2,
3 => &WEIGHTS3,
_ => &WEIGHTS4,
}
}
/// Equation 2.
fn interpolate(e0: u8, e1: u8, weight: u16) -> u8 {
(((64 - weight) * u16::from(e0) + weight * u16::from(e1) + 32) >> 6) as u8
}
/// Decodes one BC7 block to sixteen RGBA8 texels, row-major.
pub fn decode_bc7(block: [u8; 16]) -> [[u8; 4]; 16] {
let Some(mode_number) = bc7_mode(&block) else {
return [[0; 4]; 16];
};
let mode = &MODES[usize::from(mode_number)];
let mut bits = Bits {
value: u128::from_le_bytes(block),
pos: u32::from(mode_number) + 1,
};
let partition = bits.read(mode.partition_bits) as usize;
let rotation = bits.read(mode.rotation_bits);
let index_selection = bits.read(mode.index_selection_bits);
// Endpoint fields: channel-major, then subset, then endpoint.
let endpoints = 2 * mode.subsets;
let mut raw = [[0u32; 4]; 6];
for channel in 0..3 {
for e in raw.iter_mut().take(endpoints) {
e[channel] = bits.read(mode.color_bits);
}
}
for e in raw.iter_mut().take(endpoints) {
e[3] = bits.read(mode.alpha_bits);
}
let mut pbits = [None; 6];
if mode.endpoint_pbits {
for p in pbits.iter_mut().take(endpoints) {
*p = Some(bits.read(1));
}
}
if mode.shared_pbits {
for subset in 0..mode.subsets {
let p = bits.read(1);
pbits[2 * subset] = Some(p);
pbits[2 * subset + 1] = Some(p);
}
}
let mut colors = [[0u8; 4]; 6];
for (e, color) in colors.iter_mut().enumerate().take(endpoints) {
for channel in 0..3 {
color[channel] = expand(raw[e][channel], mode.color_bits, pbits[e]);
}
color[3] = if mode.alpha_bits == 0 {
255
} else {
expand(raw[e][3], mode.alpha_bits, pbits[e])
};
}
let subset_of = |texel: usize| -> usize {
match mode.subsets {
2 => usize::from(PARTITION2[partition][texel]),
3 => usize::from(PARTITION3[partition][texel]),
_ => 0,
}
};
let is_anchor = |texel: usize| -> bool {
texel == 0
|| match mode.subsets {
2 => texel == usize::from(ANCHOR2[partition]),
3 => {
texel == usize::from(ANCHOR3_2[partition])
|| texel == usize::from(ANCHOR3_3[partition])
}
_ => false,
}
};
let mut read_indices = |width: u32| -> [u32; 16] {
let mut out = [0u32; 16];
if width > 0 {
for (texel, index) in out.iter_mut().enumerate() {
*index = bits.read(width - u32::from(is_anchor(texel)));
}
}
out
};
let primary = read_indices(mode.index_bits);
let secondary = read_indices(mode.index2_bits);
// Index selection: colour from the secondary indices when the bit is one;
// alpha from the secondary indices when they exist and the bit is zero.
let (color_index, color_bits, alpha_index, alpha_bits) = if mode.index2_bits == 0 {
(primary, mode.index_bits, primary, mode.index_bits)
} else if index_selection == 1 {
(secondary, mode.index2_bits, primary, mode.index_bits)
} else {
(primary, mode.index_bits, secondary, mode.index2_bits)
};
let mut out = [[0u8; 4]; 16];
for (texel, px) in out.iter_mut().enumerate() {
let subset = subset_of(texel);
let (e0, e1) = (colors[2 * subset], colors[2 * subset + 1]);
let wc = weights(color_bits)[color_index[texel] as usize];
let wa = weights(alpha_bits)[alpha_index[texel] as usize];
for channel in 0..3 {
px[channel] = interpolate(e0[channel], e1[channel], wc);
}
px[3] = interpolate(e0[3], e1[3], wa);
// Table 120.
if rotation > 0 {
px.swap(3, rotation as usize - 1);
}
}
out
}
+14 -1
View File
@@ -7,10 +7,23 @@
#![forbid(unsafe_code)]
mod bc;
mod bc6h;
mod bc7;
pub mod sampler;
mod upload;
pub use bc::{
decode_bc2, decode_bc3, decode_bc4_snorm, decode_bc4_unorm, decode_bc5_snorm, decode_bc5_unorm,
};
pub use bc6h::{
BC6H_SUPPORTED_MODES, Bc6hError, bc6h_mode, decode_bc6h_sfloat, decode_bc6h_ufloat,
};
pub use bc7::{BC7_SUPPORTED_MODES, bc7_mode, decode_bc7};
pub use sampler::{AddressMode, FilterMode, SamplerDesc, SamplerError, TextureMetadata};
pub use upload::{Bc1Subresource, Bc1Upload, Bc1UploadDesc};
pub use upload::{
Bc1Subresource, Bc1Upload, Bc1UploadDesc, BcAlphaFormat, BcAlphaUpload, BcAlphaUploadDesc,
BcChannelFormat, BcChannelUpload, BcChannelUploadDesc,
};
const BLOCK_BYTES: usize = 8;
const TILE_BLOCKS: usize = 2;
Loaded 100 of 248 files, more files were not shown because too many files have changed in this diff. Show more