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 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
116 changed files with 17107 additions and 357 deletions

No files matched your search

+1
View File
@@ -53,6 +53,7 @@ jobs:
permissions:
contents: read
issues: write
pull-requests: read
concurrency:
group: agent-queue
cancel-in-progress: false
+20 -1
View File
@@ -9,8 +9,26 @@ 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.
@@ -77,6 +95,7 @@ remains unsupported.
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],
Generated
+2
View File
@@ -184,6 +184,8 @@ name = "xenora-ffi"
version = "0.1.0"
dependencies = [
"xenora-loader",
"xenora-metal",
"xenora-shader",
]
[[package]]
+538 -5
View File
@@ -1,11 +1,14 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//
// Gate 1 shell: proves the app links the Rust runtime through the versioned C
// interface. It inspects the bundled trusted fixture and executes no guest code.
// 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
@@ -30,29 +33,559 @@ struct RuntimeProbe {
}
}
/// 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("Guest execution and live display are not available in this build.")
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)
.frame(minWidth: 420, minHeight: 240)
.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() }
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()
+42 -6
View File
@@ -4,7 +4,7 @@ use std::fmt;
pub use xenora_isa::{
Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp,
ScalarCompareOp, ScalarSource, VectorCompareOp, VectorSource,
ScalarCompareOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorCompareOp, VectorSource,
};
use xenora_isa::{
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ,
@@ -17,6 +17,7 @@ use xenora_isa::{
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
@@ -374,6 +375,16 @@ 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 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;
@@ -419,6 +430,21 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
S_CBRANCH_VCCZ.byte_len(),
));
}
if let Some(op) = VectorAluOp::from_word(first) {
// VOP2: SRC0 in bits 0-8, VSRC1 in bits 9-16, VDST in bits 17-24.
let dst = ((first >> 17) & 0xff) as u8;
let src1 = ((first >> 9) & 0xff) as u8;
let (src0, len) = vector_src0(first, bytes, op.assembly_name())?;
return Ok((
Instruction::VectorAlu {
op,
dst,
src0,
src1,
},
len,
));
}
if V_LSHLREV_B32.matches(first) {
let (dst, src0, src1) = vop2_registers(first, "v_lshlrev_b32_e32")?;
return Ok((
@@ -688,10 +714,21 @@ fn vector_compare(
first: u32,
bytes: &[u8],
) -> Result<(Instruction, u8), DecodeErrorKind> {
let source = first & 0x1ff;
let src1 = ((first >> 9) & 0xff) as u8;
let (src0, len) = vector_src0(first, bytes, op.mnemonic())?;
Ok((Instruction::VectorCompare { op, src0, src1 }, len))
}
/// The 9-bit SRC0 of a VOPC or VOP2 word: a VGPR, `s0-s105`, `vcc_lo`, an
/// inline integer -16..64 or a literal word; everything else is unsupported.
fn vector_src0(
first: u32,
bytes: &[u8],
mnemonic: &'static str,
) -> Result<(VectorSource, u8), DecodeErrorKind> {
let source = first & 0x1ff;
let base_len = 4;
let (src0, len) = match source {
Ok(match source {
0..=106 => (VectorSource::Scalar(source as u8), base_len),
128..=192 => (VectorSource::Immediate(source - 128), base_len),
193..=208 => (
@@ -705,12 +742,11 @@ fn vector_compare(
256..=511 => (VectorSource::Register(source as u8), base_len),
_ => {
return Err(unsupported(
op.mnemonic(),
mnemonic,
"expected a VGPR, normal SGPR, vcc_lo, inline integer or literal",
));
}
};
Ok((Instruction::VectorCompare { op, src0, src1 }, len))
})
}
fn move_b32(first: u32, bytes: &[u8]) -> Result<(Instruction, u8), DecodeErrorKind> {
+77 -4
View File
@@ -4,10 +4,13 @@ use std::process::{Command, Stdio};
use xenora_decoder::{
Architecture, CompareRelation, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction,
ScalarAluOp, ScalarSource, VectorSource, decode, decode_at,
ScalarAluOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorSource, decode, decode_at,
};
use xenora_isa::semantics::Signedness;
use xenora_ref::{BranchCondition, CompareSource, Comparison, Op, ScalarAlu, Source, VectorAlu};
use xenora_ref::{
BranchCondition, CompareSource, Comparison, Op, ScalarAlu, ScalarUnary, Source, VectorAlu,
VectorInteger,
};
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin");
const BITWISE_FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/bitwise-branch.bin");
@@ -349,6 +352,22 @@ fn reference_op(instruction: Instruction) -> Op {
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),
@@ -356,6 +375,23 @@ fn reference_op(instruction: Instruction) -> Op {
),
Instruction::AddNoCarryU32 { dst, src0, src1 } => Op::Add(dst, src0, src1),
Instruction::ScalarMoveB32 { dst, src } => Op::ScalarMove(dst, reference_scalar(src)),
Instruction::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
@@ -435,6 +471,34 @@ fn reference_op(instruction: Instruction) -> Op {
},
src1,
),
Instruction::VectorAlu {
op,
dst,
src0,
src1,
} => Op::VectorInteger(
match op {
VectorAluOp::MulI32I24 => VectorInteger::Multiply24 { signed: true },
VectorAluOp::MulHiI32I24 => VectorInteger::MultiplyHigh24 { signed: true },
VectorAluOp::MulU32U24 => VectorInteger::Multiply24 { signed: false },
VectorAluOp::MulHiU32U24 => VectorInteger::MultiplyHigh24 { signed: false },
VectorAluOp::MinI32 => VectorInteger::Minimum { signed: true },
VectorAluOp::MaxI32 => VectorInteger::Maximum { signed: true },
VectorAluOp::MinU32 => VectorInteger::Minimum { signed: false },
VectorAluOp::MaxU32 => VectorInteger::Maximum { signed: false },
VectorAluOp::XnorB32 => VectorInteger::Xnor,
VectorAluOp::AddNcU32 => VectorInteger::Add,
VectorAluOp::SubNcU32 => VectorInteger::Subtract,
VectorAluOp::SubrevNcU32 => VectorInteger::SubtractReverse,
},
dst,
match src0 {
VectorSource::Register(reg) => CompareSource::Vector(reg),
VectorSource::Scalar(reg) => CompareSource::Scalar(reg),
VectorSource::Immediate(bits) => CompareSource::Immediate(bits),
},
src1,
),
Instruction::EndProgram => Op::End,
}
}
@@ -458,13 +522,16 @@ fn compares_fixture_instructions_against_llvm() {
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(), 61, "forms compared: {forms:?}");
assert_eq!(forms.len(), 100, "forms compared: {forms:?}");
eprintln!(
"{count} three-way instruction comparisons across {} forms",
forms.len()
@@ -748,7 +815,13 @@ fn normalize_llvm_assembly(assembly: &str, next_offset: usize) -> String {
let target = next_offset + displacement * 4;
format!("{mnemonic} -> 0x{target:04x}")
}
mnemonic if mnemonic.starts_with("v_cmp_") => {
// VOPC and the registry VOP2 forms print SRC0 (the second operand) as bits.
mnemonic
if mnemonic.starts_with("v_cmp_")
|| VectorAluOp::ALL
.iter()
.any(|op| op.assembly_name() == mnemonic) =>
{
let mut parts: Vec<String> = operands.split(", ").map(str::to_owned).collect();
parts[1] = match literal_bits(&parts[1]) {
Some(bits) => format!("0x{bits:x}"),
+8
View File
@@ -49,3 +49,11 @@ fn declared_semantic_forms_are_exactly_those_decoded_from_fixtures() {
);
}
}
#[test]
fn registry_forms_do_not_duplicate_hand_written_forms() {
// A form declared in the semantic registry and also decoded by hand-written
// code would have two implementations; the hand-written one would win.
let unique: BTreeSet<_> = SEMANTIC_FORMS.into_iter().collect();
assert_eq!(unique.len(), SEMANTIC_FORMS.len());
}
+6
View File
@@ -12,5 +12,11 @@ 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" }
+199
View File
@@ -25,8 +25,49 @@ enum {
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. */
@@ -44,4 +85,162 @@ xenora_status xenora_session_inspect_trusted_fixture(
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()
}
+1537 -4
View File
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);
}
+287 -20
View File
@@ -43,7 +43,19 @@ OPERATIONS = {
"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 = {
@@ -62,9 +74,19 @@ COMPARE_PRIMITIVES = {
}
# 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"}
ARITHMETIC = {"add", "sub"}
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"},
@@ -73,6 +95,13 @@ SOURCE_FORMATS = {
}
# 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 = {
@@ -82,6 +111,7 @@ SCC = {
"signed_overflow": "SignedOverflow",
"nonzero": "Nonzero",
"relation": "Relation",
"selected_src0": "SelectedSrc0",
}
MASK = {"unchanged": "Unchanged"}
WAVE = {"any": "Any", "wave32": "Wave32"}
@@ -128,6 +158,45 @@ PRIMITIVES = {
("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
@@ -136,6 +205,9 @@ UNSUPPORTED_COMBOS = {
"dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null", "src_vcc", "src_exec",
"src_m0", "src_ttmp", "src_float_inline", "src_special", "two_literals",
}
# Every combo name a rule may list (VOP2 also names vcc_hi and NULL sources,
# which SOP2 groups under src_vcc and src_special).
ALL_COMBOS = UNSUPPORTED_COMBOS | {"src_vcc_hi", "src_null"}
OPERAND_RULES = {
"sop2_sgpr": {
"rust": "Sop2Sgpr",
@@ -168,6 +240,39 @@ OPERAND_RULES = {
"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]*$")
@@ -215,7 +320,7 @@ def _check_rule(name, rule, errors):
errors.append(f"operand rule {name}: not implemented by the decoder")
return
unsupported = rule.get("unsupported", [])
unknown = sorted(set(unsupported) - UNSUPPORTED_COMBOS)
unknown = sorted(set(unsupported) - ALL_COMBOS)
if unknown:
errors.append(f"operand rule {name}: unknown unsupported combos {unknown}")
if len(set(unsupported)) != len(unsupported):
@@ -250,12 +355,19 @@ def _check_xml(form, rule, snapshot, errors):
errors.append(f"{label}: opcode {form['opcode']} is not an identifier of {encoding_name}")
operands = {}
scc_in = scc_out = False
implicit = set()
for field, data_format, kind, size, is_input, is_output, _implicit, _encoded in variant["operands"]:
if kind == "OPR_SSRC_SPECIAL_SCC":
scc_in |= is_input
scc_out |= is_output
elif field:
operands[field] = (data_format, size, is_input, is_output)
else:
implicit.add(kind)
# The vocabulary can state only SCC effects (vcc and exec are "unchanged"),
# so any other implicit XML operand, such as VCC, is undeclared.
if implicit:
errors.append(f"{label}: XML implicit operands {sorted(implicit)} are not declared")
if scc_in != (form["carry_in"] == "scc"):
errors.append(f"{label}: carry_in {form['carry_in']} contradicts the XML SCC input")
if scc_out != (form["scc"] != "unchanged"):
@@ -268,22 +380,27 @@ def _check_xml(form, rule, snapshot, errors):
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 SHIFTS and len(rule["src"]) > 1
shift = form["operation"] in CONTROL_S1 and len(rule["src"]) > 1
count_field = rule["src"][1]["field"] if shift else None
for field, is_source in fields:
if field not in operands:
errors.append(f"{label}: XML has no operand {field}")
continue
data_format, size, is_input, is_output = operands[field]
if size != form["width"]:
errors.append(f"{label}: {field} is {size} bits in the XML, declared {form['width']}")
bits = form.get(SOURCE_BITS_KEY) if is_source else None
expected = bits if type(bits) is int else form["width"]
if size != expected:
errors.append(f"{label}: {field} is {size} bits in the XML, declared {expected}")
if (is_input, is_output) != (is_source, not is_source):
errors.append(f"{label}: {field} direction disagrees with the XML")
if field == count_field:
if data_format != "FMT_NUM_U32":
errors.append(
f"{label}: shift count {field} has XML format {data_format}, not FMT_NUM_U32"
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}"
@@ -330,7 +447,10 @@ def validate(registry, snapshot):
for index, form in enumerate(forms):
label = form.get("name", f"form #{index}")
missing = sorted(FORM_KEYS - set(form))
extra = sorted(set(form) - FORM_KEYS - {SHIFT_KEY, RELATION_KEY})
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:
@@ -358,10 +478,12 @@ def validate(registry, snapshot):
for key, value in (
("name", form["name"]),
("opcode", (form["family"], form["opcode"])),
("variant", form["variant"]),
# Variants are names in their operand rule's enum.
("variant", (_rule_enum(form), form["variant"])),
):
if value in seen[key]:
errors.append(f"{label}: duplicate {key} {value}")
shown = form["variant"] if key == "variant" else value
errors.append(f"{label}: duplicate {key} {shown}")
seen[key].add(value)
if (form["operation"] in LOGICAL and form["signedness"] != "bitwise") or (
form["operation"] in ARITHMETIC and form["signedness"] == "bitwise"
@@ -377,6 +499,28 @@ def validate(registry, snapshot):
)
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:
@@ -388,6 +532,11 @@ def validate(registry, snapshot):
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")
@@ -408,8 +557,11 @@ def validate(registry, snapshot):
errors.append(f"{label}: unknown operand rule {form['operands']!r}")
elif rule.get("family") != form["family"]:
errors.append(f"{label}: operand rule {form['operands']} is for {rule.get('family')}")
elif form["operands"] in OPERAND_RULES and (
(OPERAND_RULES[form["operands"]]["kind"] == "compare") != (form["operation"] == "compare")
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)
@@ -424,6 +576,23 @@ def validate(registry, snapshot):
return errors
def _implemented_rule(form):
operands = form.get("operands")
return OPERAND_RULES.get(operands) if isinstance(operands, str) else None
def _rule_kind(form):
"""The implemented kind of the form's operand rule, or None if unknown."""
rule = _implemented_rule(form)
return rule["kind"] if rule else None
def _rule_enum(form):
"""The generated enum of the form's operand rule, or None if unknown."""
rule = _implemented_rule(form)
return rule["enum"] if rule else None
def _check_spec(label, spec, documents, errors):
has_guide = False
for ref in spec:
@@ -455,7 +624,7 @@ def render(registry, snapshot):
"use crate::primitive;",
"use crate::semantics::{",
" CarryIn, Document, Evidence, FormSemantics, MaskEffect, Operation, OperandRule, SccEffect,",
" Signedness, SpecRef, Wave,",
" Signedness, SpecRef, VectorBinary, Wave,",
"};",
"use crate::CompareRelation;",
"",
@@ -495,6 +664,9 @@ def render(registry, snapshot):
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']]},",
@@ -535,7 +707,7 @@ def _render_enum(rule_name, forms, snapshot, positions):
]
for form in forms:
carry = " plus SCC" if form["carry_in"] == "scc" else ""
what = form["operation"] if kind == "alu" else f"compare {form[RELATION_KEY]}"
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']}.",
@@ -590,6 +762,78 @@ def _render_enum(rule_name, forms, snapshot, positions):
" }]",
" }",
]
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 += [
"",
@@ -616,7 +860,7 @@ def _render_enum(rule_name, forms, snapshot, positions):
return out
out += [
"",
" /// Whether the operation reads SCC as a carry-in or borrow-in.",
" /// Whether the operation reads SCC (carry-in, borrow-in or select condition).",
" pub const fn reads_scc(self) -> bool {",
" match self {",
]
@@ -628,22 +872,45 @@ def _render_enum(rule_name, forms, snapshot, positions):
" }",
" }",
"",
" /// The result and the new SCC, with `carry_in` the SCC read by forms that",
" /// consume it (ignored by the others).",
" pub const fn evaluate(self, src0: u32, src1: u32, carry_in: bool) -> (u32, bool) {",
" /// Whether the operation writes SCC.",
" pub const fn writes_scc(self) -> bool {",
" match self {",
]
out += [
f" Self::{form['variant']} => {'false' if form['scc'] == 'unchanged' else 'true'},"
for form in forms
]
out += [
" }",
" }",
"",
" /// The result and, for forms that write it, the new SCC (`None` leaves SCC",
" /// unchanged). `scc_in` is the SCC read by forms that consume it (ignored by",
" /// the others).",
" pub const fn evaluate(self, src0: u32, src1: u32, scc_in: bool) -> (u32, Option<bool>) {",
" match self {",
]
for form in forms:
_, function, takes_carry = PRIMITIVES[(form["operation"], form["signedness"])]
if takes_carry:
argument = "carry_in" if form["carry_in"] == "scc" else "false"
argument = "scc_in" if form["carry_in"] == "scc" else "false"
call = f"primitive::{function}(src0, src1, {argument})"
elif form["operation"] in SHIFTS:
mask = (1 << form[SHIFT_KEY]) - 1
call = f"primitive::{function}(src0, src1 & 0x{mask:x})"
elif form["operation"] == "lshl_add":
call = f"primitive::{function}(src0, src1, {form[SHIFT_AMOUNT_KEY]})"
else:
call = f"primitive::{function}(src0, src1)"
out.append(f" Self::{form['variant']} => {call},")
if form["scc"] == "unchanged":
out.append(f" Self::{form['variant']} => ({call}, None),")
else:
out += [
f" Self::{form['variant']} => {{",
f" let (value, scc) = {call};",
" (value, Some(scc))",
" }",
]
out += [" }", " }", "}"]
return out
+773 -3
View File
@@ -49,11 +49,11 @@ unsupported = [
# family encoding family; must match the XML base encoding
# opcode XML opcode; must match
# variant Rust enum variant of the typed op
# operation primitive: add | sub | and | or | xor
# operation primitive (closed vocabulary in generate_semantics.py OPERATIONS)
# signedness unsigned | signed | bitwise (bitwise iff a logical operation)
# carry_in none | scc (scc only for unsigned add/sub)
# carry_in none | scc (scc for unsigned add/sub carry and the cselect condition)
# width operand and result width in bits
# scc carry_out | borrow | signed_overflow | nonzero
# scc unchanged | carry_out | borrow | signed_overflow | nonzero | relation | selected_src0
# vcc, exec unchanged (stated, not implied)
# wave any | wave32
# operands a key of [operand_rules]
@@ -373,6 +373,317 @@ operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 104 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
# ---- SOP2 32-bit integer arithmetic, select and bit-field forms (#215) ----
# min/max: SCC = S0 chosen by the strict compare (a tie gives S1, SCC 0). cselect
# reads SCC and writes none. bfm, mul, mul_hi write no SCC (Tables 11, 12, 14).
# bfe: offset S1[4:0], width S1[22:16]. lshl_add: SCC = carry of (S0 << N) + S1.
[[form]]
name = "S_MIN_I32"
family = "SOP2"
opcode = 6
variant = "MinI32"
operation = "min"
signedness = "signed"
carry_in = "none"
width = 32
scc = "selected_src0"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 102 },
{ document = "guide", section = "5.4", page = 34 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_MIN_U32"
family = "SOP2"
opcode = 7
variant = "MinU32"
operation = "min"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "selected_src0"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 102 },
{ document = "guide", section = "5.4", page = 34 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_MAX_I32"
family = "SOP2"
opcode = 8
variant = "MaxI32"
operation = "max"
signedness = "signed"
carry_in = "none"
width = 32
scc = "selected_src0"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 102 },
{ document = "guide", section = "5.4", page = 34 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_MAX_U32"
family = "SOP2"
opcode = 9
variant = "MaxU32"
operation = "max"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "selected_src0"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 103 },
{ document = "guide", section = "5.4", page = 34 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CSELECT_B32"
family = "SOP2"
opcode = 10
variant = "CselectB32"
operation = "cselect"
signedness = "bitwise"
carry_in = "scc"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 103 },
{ document = "guide", section = "5.5", page = 34 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_BFM_B32"
family = "SOP2"
opcode = 36
variant = "BfmB32"
operation = "bfm"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 104 },
{ document = "guide", section = "5.7", page = 36 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_MUL_I32"
family = "SOP2"
opcode = 38
variant = "MulI32"
operation = "mul"
signedness = "signed"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 105 },
{ document = "guide", section = "5.4", page = 34 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_BFE_U32"
family = "SOP2"
opcode = 39
variant = "BfeU32"
operation = "bfe"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 105 },
{ document = "guide", section = "5.7", page = 36 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_BFE_I32"
family = "SOP2"
opcode = 40
variant = "BfeI32"
operation = "bfe"
signedness = "signed"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 105 },
{ document = "guide", section = "5.7", page = 36 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_ABSDIFF_I32"
family = "SOP2"
opcode = 44
variant = "AbsdiffI32"
operation = "absdiff"
signedness = "signed"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 105 },
{ document = "guide", section = "5.4", page = 34 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_LSHL1_ADD_U32"
family = "SOP2"
opcode = 46
variant = "Lshl1AddU32"
operation = "lshl_add"
signedness = "unsigned"
carry_in = "none"
width = 32
shift_amount = 1
scc = "carry_out"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 105 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_LSHL2_ADD_U32"
family = "SOP2"
opcode = 47
variant = "Lshl2AddU32"
operation = "lshl_add"
signedness = "unsigned"
carry_in = "none"
width = 32
shift_amount = 2
scc = "carry_out"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 105 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_LSHL3_ADD_U32"
family = "SOP2"
opcode = 48
variant = "Lshl3AddU32"
operation = "lshl_add"
signedness = "unsigned"
carry_in = "none"
width = 32
shift_amount = 3
scc = "carry_out"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 106 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_LSHL4_ADD_U32"
family = "SOP2"
opcode = 49
variant = "Lshl4AddU32"
operation = "lshl_add"
signedness = "unsigned"
carry_in = "none"
width = 32
shift_amount = 4
scc = "carry_out"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 106 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_MUL_HI_U32"
family = "SOP2"
opcode = 53
variant = "MulHiU32"
operation = "mul_hi"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 106 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_MUL_HI_I32"
family = "SOP2"
opcode = 54
variant = "MulHiI32"
operation = "mul_hi"
signedness = "signed"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 106 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
# ---- Stage D: SOPC 32-bit integer compares (#215) ----
# Only SCC is written: SCC = relation(S0, S1), S0 = SSRC0 on the left (guide 12.4).
@@ -639,3 +950,462 @@ spec = [
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
# ---- SOP1 32-bit unary integer forms (#215) ----
# NOT, BCNT0, BCNT1 and ABS set SCC = (D != 0); the others leave SCC unchanged.
# Searches that find nothing return -1 (guide 12.3).
[operand_rules.sop1_sgpr]
family = "SOP1"
dst = { field = "SDST", class = "sgpr", min = 0, max = 105 }
src = [{ field = "SSRC0", class = "scalar_source" }]
max_literals = 1
unsupported = [
"dst_vcc", "dst_exec", "dst_ttmp", "dst_m0", "dst_null",
"src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline", "src_special",
]
[[form]]
name = "S_NOT_B32"
family = "SOP1"
opcode = 7
variant = "NotB32"
operation = "not"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop1_sgpr"
spec = [
{ document = "guide", section = "12.3", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_BREV_B32"
family = "SOP1"
opcode = 11
variant = "BrevB32"
operation = "brev"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop1_sgpr"
spec = [
{ document = "guide", section = "12.3", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_BCNT0_I32_B32"
family = "SOP1"
opcode = 13
variant = "Bcnt0I32B32"
operation = "bcnt0"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop1_sgpr"
spec = [
{ document = "guide", section = "12.3", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_BCNT1_I32_B32"
family = "SOP1"
opcode = 15
variant = "Bcnt1I32B32"
operation = "bcnt1"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop1_sgpr"
spec = [
{ document = "guide", section = "12.3", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_FF0_I32_B32"
family = "SOP1"
opcode = 17
variant = "Ff0I32B32"
operation = "ff0"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop1_sgpr"
spec = [
{ document = "guide", section = "12.3", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_FF1_I32_B32"
family = "SOP1"
opcode = 19
variant = "Ff1I32B32"
operation = "ff1"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop1_sgpr"
spec = [
{ document = "guide", section = "12.3", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_FLBIT_I32_B32"
family = "SOP1"
opcode = 21
variant = "FlbitI32B32"
operation = "flbit"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop1_sgpr"
spec = [
{ document = "guide", section = "12.3", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_FLBIT_I32"
family = "SOP1"
opcode = 23
variant = "FlbitI32"
operation = "flbit"
signedness = "signed"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop1_sgpr"
spec = [
{ document = "guide", section = "12.3", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_SEXT_I32_I8"
family = "SOP1"
opcode = 25
variant = "SextI32I8"
operation = "sext"
signedness = "signed"
carry_in = "none"
width = 32
source_bits = 8
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop1_sgpr"
spec = [
{ document = "guide", section = "12.3", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_SEXT_I32_I16"
family = "SOP1"
opcode = 26
variant = "SextI32I16"
operation = "sext"
signedness = "signed"
carry_in = "none"
width = 32
source_bits = 16
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop1_sgpr"
spec = [
{ document = "guide", section = "12.3", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_ABS_I32"
family = "SOP1"
opcode = 52
variant = "AbsI32"
operation = "abs"
signedness = "signed"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop1_sgpr"
spec = [
{ document = "guide", section = "12.3", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
# ---- VOP2 32-bit vector integer forms (#215) ----
# Per lane under EXEC; no SCC, VCC or EXEC write (guide 12.7). The 24-bit
# multiplies read S0[23:0] and S1[23:0], sign-extended when signed; the high
# forms keep bits 63:32 of the product. SUBREV declares its reversed sources.
[operand_rules.vop2_vgpr]
family = "VOP2"
dst = { field = "VDST", class = "vgpr", min = 0, max = 255 }
src = [
{ field = "SRC0", class = "vector_source" },
{ field = "VSRC1", class = "vgpr" },
]
# vector_source = VGPR, normal SGPR s0-s105, vcc_lo, inline integer -16..64, or a literal word.
max_literals = 1
unsupported = [
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special",
]
[[form]]
name = "V_MUL_I32_I24"
family = "VOP2"
opcode = 9
variant = "MulI32I24"
operation = "mul24"
signedness = "signed"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "vop2_vgpr"
spec = [{ document = "guide", section = "12.7", page = 131 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_MUL_HI_I32_I24"
family = "VOP2"
opcode = 10
variant = "MulHiI32I24"
operation = "mul_hi24"
signedness = "signed"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "vop2_vgpr"
spec = [{ document = "guide", section = "12.7", page = 132 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_MUL_U32_U24"
family = "VOP2"
opcode = 11
variant = "MulU32U24"
operation = "mul24"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "vop2_vgpr"
spec = [{ document = "guide", section = "12.7", page = 132 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_MUL_HI_U32_U24"
family = "VOP2"
opcode = 12
variant = "MulHiU32U24"
operation = "mul_hi24"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "vop2_vgpr"
spec = [{ document = "guide", section = "12.7", page = 132 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_MIN_I32"
family = "VOP2"
opcode = 17
variant = "MinI32"
operation = "min"
signedness = "signed"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "vop2_vgpr"
spec = [{ document = "guide", section = "12.7", page = 133 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_MAX_I32"
family = "VOP2"
opcode = 18
variant = "MaxI32"
operation = "max"
signedness = "signed"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "vop2_vgpr"
spec = [{ document = "guide", section = "12.7", page = 133 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_MIN_U32"
family = "VOP2"
opcode = 19
variant = "MinU32"
operation = "min"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "vop2_vgpr"
spec = [{ document = "guide", section = "12.7", page = 133 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_MAX_U32"
family = "VOP2"
opcode = 20
variant = "MaxU32"
operation = "max"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "vop2_vgpr"
spec = [{ document = "guide", section = "12.7", page = 133 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_XNOR_B32"
family = "VOP2"
opcode = 30
variant = "XnorB32"
operation = "xnor"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "vop2_vgpr"
spec = [{ document = "guide", section = "12.7", page = 134 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_ADD_NC_U32"
family = "VOP2"
opcode = 37
variant = "AddNcU32"
operation = "add"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "vop2_vgpr"
spec = [{ document = "guide", section = "12.7", page = 134 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_SUB_NC_U32"
family = "VOP2"
opcode = 38
variant = "SubNcU32"
operation = "sub"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "vop2_vgpr"
spec = [{ document = "guide", section = "12.7", page = 134 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_SUBREV_NC_U32"
family = "VOP2"
opcode = 39
variant = "SubrevNcU32"
operation = "sub"
signedness = "unsigned"
carry_in = "none"
width = 32
source_order = "reversed"
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "vop2_vgpr"
spec = [{ document = "guide", section = "12.7", page = 134 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
+27 -3
View File
@@ -18,7 +18,7 @@ pub use rdna2::{
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};
pub use semantics_gen::{ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp};
/// SGPR index of `vcc_lo`, the Wave32 vector condition code.
pub const VCC_LO: u8 = 106;
@@ -209,7 +209,15 @@ pub enum Instruction {
AddNoCarryU32 { dst: u8, src0: u8, src1: u8 },
/// SOP1 32-bit move to a normal SGPR or an EXEC/VCC half.
ScalarMoveB32 { dst: u8, src: ScalarSource },
/// SOP2 32-bit integer operation writing a normal SGPR (s0-s105) and SCC.
/// SOP1 32-bit unary integer operation writing a normal SGPR (s0-s105) and,
/// for some operations, SCC.
ScalarUnary {
op: ScalarUnaryOp,
dst: u8,
src: ScalarSource,
},
/// SOP2 32-bit integer operation writing a normal SGPR (s0-s105) and, for
/// most operations, SCC; `s_cselect_b32` also reads SCC.
ScalarAlu {
op: ScalarAluOp,
dst: u8,
@@ -229,6 +237,15 @@ pub enum Instruction {
src0: VectorSource,
src1: u8,
},
/// VOP2 32-bit per-lane integer operation from the semantic registry.
/// `src0` is a VGPR, `s0-s105`, `vcc_lo`, an inline integer or a literal;
/// `src1` is a VGPR. Inactive lanes keep `dst`.
VectorAlu {
op: VectorAluOp,
dst: u8,
src0: VectorSource,
src1: u8,
},
/// SOPP jump to a stream byte offset when SCC is clear.
BranchSccZero { target: usize },
/// SOPP jump when the Wave32 execution mask is empty.
@@ -307,9 +324,11 @@ impl Instruction {
Self::MoveB32 { .. } => "v_mov_b32_e32",
Self::AddNoCarryU32 { .. } => "v_add_nc_u32_e64",
Self::ScalarMoveB32 { .. } => "s_mov_b32",
Self::ScalarUnary { op, .. } => op.mnemonic(),
Self::ScalarAlu { op, .. } => op.mnemonic(),
Self::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",
@@ -371,7 +390,7 @@ impl fmt::Display for Instruction {
| Self::VectorMulF32 { dst, src0, src1 } => {
write!(formatter, " v{dst}, v{src0}, v{src1}")
}
Self::ScalarMoveB32 { dst, src } => {
Self::ScalarMoveB32 { dst, src } | Self::ScalarUnary { dst, src, .. } => {
write!(formatter, " {}, {src}", ScalarDestination(dst))
}
Self::ScalarAlu {
@@ -381,6 +400,11 @@ impl fmt::Display for Instruction {
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 }
+168
View File
@@ -148,3 +148,171 @@ pub const fn lt_u32(a: u32, b: u32) -> bool {
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)
}
+89 -4
View File
@@ -49,6 +49,76 @@ pub enum Operation {
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.
@@ -62,12 +132,12 @@ pub enum Signedness {
Bitwise,
}
/// Extra input consumed by the operation.
/// Whether the operation reads SCC.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CarryIn {
/// No carry or borrow input.
/// SCC is not read.
None,
/// SCC as carry-in (add) or borrow-in (sub).
/// SCC as carry-in (add), borrow-in (sub) or the select condition (select).
Scc,
}
@@ -86,6 +156,8 @@ pub enum SccEffect {
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.
@@ -113,6 +185,13 @@ pub enum OperandRule {
/// 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.
@@ -161,12 +240,18 @@ pub struct FormSemantics {
pub operation: Operation,
/// Operand interpretation.
pub signedness: Signedness,
/// Carry or borrow input.
/// SCC input.
pub carry_in: CarryIn,
/// Operand and result width in bits.
pub width: u8,
/// Low bits of S1 used as the shift count by shift operations; 0 otherwise.
pub shift_count_bits: u8,
/// Fixed left shift of S0 for shift-and-add operations (1 to 4); 0 otherwise.
pub shift_amount: u8,
/// Whether the operation reads its sources in reverse order (`D = op(S1, S0)`).
pub swap_sources: bool,
/// Low bits of S0 that the operation reads: `width`, or 8 or 16 for sign extension.
pub source_bits: u8,
/// The relation tested by compares (S0 on the left); `None` otherwise.
pub relation: Option<CompareRelation>,
/// SCC write.
File diff suppressed because it is too large. Load diff
+34 -2
View File
@@ -1,8 +1,8 @@
//! 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};
use xenora_isa::{ScalarAluOp, ScalarCompareOp};
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() {
@@ -53,6 +53,7 @@ fn scalar_alu_dispatch_selects_exactly_the_registry_sop2_forms() {
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)
@@ -71,3 +72,34 @@ fn scalar_compare_dispatch_selects_exactly_the_registry_sopc_forms() {
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(
+356 -81
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 {
@@ -255,29 +437,26 @@ impl<'a> Interpreter<'a> {
}
fn execute_instruction(&mut self) -> Result<Option<ExitReason>, ExitReason> {
let mut rex_w = false;
let mut rex_r = false;
let mut rex_b = false;
let mut seg_gs = false;
let mut seg_fs = false;
let mut 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()?;
}
@@ -287,10 +466,16 @@ impl<'a> Interpreter<'a> {
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(rex_b) << 3));
let reg = Register::from_index((op & 7) | (u8::from(prefixes.rex_b) << 3));
let value = self.cpu.get(reg);
let reversed = if rex_w {
let reversed = if prefixes.rex_w {
value.swap_bytes()
} else {
u64::from((value as u32).swap_bytes())
@@ -303,9 +488,9 @@ impl<'a> Interpreter<'a> {
// 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 {
@@ -318,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);
@@ -353,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);
@@ -371,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);
@@ -391,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;
@@ -399,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);
@@ -410,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);
@@ -421,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);
@@ -438,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)
@@ -492,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)?;
@@ -501,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);
@@ -532,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 {
@@ -565,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
@@ -590,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 {
@@ -637,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) {
+558 -8
View File
@@ -765,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);
@@ -778,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);
@@ -1245,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(
@@ -1265,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);
}
}
@@ -1283,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(
@@ -1303,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);
}
}
@@ -1453,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) {
@@ -1781,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
@@ -1930,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))
);
}
}
+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);
}
+392 -48
View File
@@ -51,6 +51,8 @@ pub enum Op {
Move(u8, Source),
Add(u8, u8, u8),
ScalarMove(u8, Source),
/// SOP1 unary operation writing an SGPR (s0-s105), and SCC for some.
ScalarUnary(ScalarUnary, u8, Source),
/// VOP1 move of a normal SGPR or `vcc_lo` (106) into a VGPR.
MoveScalar(u8, u8),
/// VOPC 32-bit integer compare writing the Wave32 mask to `vcc_lo`.
@@ -67,6 +69,9 @@ pub enum Op {
condition: BranchCondition,
},
Vector(VectorAlu, u8, u8, u8),
/// VOP2 32-bit integer form: VDST, SRC0 (VGPR, SGPR, `vcc_lo`, inline
/// integer or literal) and VSRC1. Writes neither VCC nor SCC.
VectorInteger(VectorInteger, u8, CompareSource, u8),
End,
}
@@ -105,7 +110,7 @@ impl Comparison {
}
}
/// First source of a VOPC compare.
/// First source of a VOPC compare or a VOP2 integer form.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CompareSource {
/// VGPR index.
@@ -162,6 +167,63 @@ pub enum ScalarAlu {
ShiftRight,
/// D = signext(S0) >> S1[4:0], SCC = (D != 0).
ArithmeticShiftRight,
/// Guide 12.1: D = (S0 < S1) ? S0 : S1, SCC = (S0 < S1); signed or not.
Minimum {
signed: bool,
},
/// D = (S0 > S1) ? S0 : S1, SCC = (S0 > S1).
Maximum {
signed: bool,
},
/// D = SCC ? S0 : S1; reads SCC and leaves it unchanged.
Select,
/// D = ((1 << S0[4:0]) - 1) << S1[4:0]; SCC unchanged.
BitfieldMask,
/// D = low 32 bits of S0 * S1; SCC unchanged.
Multiply,
/// D = (S0 >> S1[4:0]) & ((1 << S1[22:16]) - 1), sign-extended from the
/// field's top bit when signed (S0 then shifts arithmetically);
/// SCC = (D != 0).
BitfieldExtract {
signed: bool,
},
/// D = |S0 - S1| with the 32-bit difference (0x80000000 stays),
/// SCC = (D != 0).
AbsoluteDifference,
/// D = (S0 << N) + S1, SCC = ((S0 << N) + S1 >= 2^32) with N = 1..4.
ShiftLeftAdd(u8),
/// D = high 32 bits of S0 * S1; SCC unchanged.
MultiplyHigh {
signed: bool,
},
}
/// SOP1 unary operations decoded by the reference interpreter (RDNA 2 ISA
/// guide 12.3; SCC per Tables 12 and 14).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ScalarUnary {
/// D = ~S0, SCC = (D != 0).
Not,
/// D[31:0] = S0[0:31].
ReverseBits,
/// D = number of zero bits, SCC = (D != 0).
CountZeros,
/// D = number of one bits, SCC = (D != 0).
CountOnes,
/// D = index of the lowest zero bit, or -1.
FindFirstZero,
/// D = index of the lowest one bit, or -1.
FindFirstOne,
/// D = number of zeros above the highest one bit, or -1 for 0.
FindLastBit,
/// D = number of leading bits equal to the sign bit, or -1 for 0 and -1.
FindLastSignBit,
/// D = signext(S0[7:0]).
SignExtendByte,
/// D = signext(S0[15:0]).
SignExtendShort,
/// D = |S0| (0x80000000 stays), SCC = (D != 0).
Absolute,
}
/// VOP2 operations decoded by the reference interpreter.
@@ -177,6 +239,90 @@ pub enum VectorAlu {
FloatMultiply,
}
/// VOP2 32-bit integer forms with a general SRC0 (AMD RDNA 2 ISA guide
/// section 12.7). None has a carry-in or carry-out.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VectorInteger {
/// 9 / 11: D = low 32 bits of S0[23:0] * S1[23:0], sign-extended from
/// bit 23 when `signed`.
Multiply24 { signed: bool },
/// 10 / 12: D = bits 63:32 of the same 48-bit product.
MultiplyHigh24 { signed: bool },
/// 17 / 19: D = S0 < S1 ? S0 : S1.
Minimum { signed: bool },
/// 18 / 20: D = S0 >= S1 ? S0 : S1.
Maximum { signed: bool },
/// 30: D = ~(S0 ^ S1).
Xnor,
/// 37: D = S0 + S1.
Add,
/// 38: D = S0 - S1.
Subtract,
/// 39: D = S1 - S0.
SubtractReverse,
}
impl VectorInteger {
/// Opcode bits 30-25 of the VOP2 word.
fn from_opcode(opcode: u8) -> Option<Self> {
Some(match opcode {
9 => Self::Multiply24 { signed: true },
10 => Self::MultiplyHigh24 { signed: true },
11 => Self::Multiply24 { signed: false },
12 => Self::MultiplyHigh24 { signed: false },
17 => Self::Minimum { signed: true },
18 => Self::Maximum { signed: true },
19 => Self::Minimum { signed: false },
20 => Self::Maximum { signed: false },
30 => Self::Xnor,
37 => Self::Add,
38 => Self::Subtract,
39 => Self::SubtractReverse,
_ => return None,
})
}
/// D for S0 = `a`, S1 = `b`, from exact i64 arithmetic reduced modulo 2^32.
fn apply(self, a: u32, b: u32) -> u32 {
let field = |bits: u32, signed: bool| {
if signed {
i64::from(((bits << 8) as i32) >> 8)
} else {
i64::from(bits & 0x00ff_ffff)
}
};
let widen = |bits: u32, signed: bool| {
if signed {
i64::from(bits as i32)
} else {
i64::from(bits)
}
};
match self {
Self::Multiply24 { signed } => (field(a, signed) * field(b, signed)) as u32,
Self::MultiplyHigh24 { signed } => ((field(a, signed) * field(b, signed)) >> 32) as u32,
Self::Minimum { signed } => {
if widen(a, signed) < widen(b, signed) {
a
} else {
b
}
}
Self::Maximum { signed } => {
if widen(a, signed) >= widen(b, signed) {
a
} else {
b
}
}
Self::Xnor => !(a ^ b),
Self::Add => a.wrapping_add(b),
Self::Subtract => a.wrapping_sub(b),
Self::SubtractReverse => b.wrapping_sub(a),
}
}
}
/// Execute original little-endian gfx1030 bytes with the synthetic binding ABI.
///
/// Each dispatched lane reads the corresponding input word and may write only
@@ -297,6 +443,31 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
let (source, length) = decode_scalar(*source, tail, offset)?;
(Op::ScalarMove(destination & 0x7f, source), length)
}
// SOP1: ENCODING 0b10_1111101 in bits 23-31, SDST in 16-22 (s0-s105
// only), OP in 8-15.
[
source,
op @ (7 | 11 | 13 | 15 | 17 | 19 | 21 | 23 | 25 | 26 | 52),
destination @ 0x80..=0xe9,
0xbe,
tail @ ..,
] => {
let kind = match op {
7 => ScalarUnary::Not,
11 => ScalarUnary::ReverseBits,
13 => ScalarUnary::CountZeros,
15 => ScalarUnary::CountOnes,
17 => ScalarUnary::FindFirstZero,
19 => ScalarUnary::FindFirstOne,
21 => ScalarUnary::FindLastBit,
23 => ScalarUnary::FindLastSignBit,
25 => ScalarUnary::SignExtendByte,
26 => ScalarUnary::SignExtendShort,
_ => ScalarUnary::Absolute,
};
let (source, length) = decode_scalar(*source, tail, offset)?;
(Op::ScalarUnary(kind, destination & 0x7f, source), length)
}
// SOPC: ENCODING 0b10_1111110 in bits 23-31, OP in 16-22 (guide
// 13.1.4); 0-5 signed and 6-11 unsigned EQ, LG, GT, GE, LT, LE.
[left, right, op @ 0..=11, 0xbf, tail @ ..] if (*left, *right) != (255, 255) => {
@@ -316,35 +487,46 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
(op, left_length.max(right_length))
}
// SOP2: OP in bits 23-29, SDST in bits 16-22, SSRC1, SSRC0.
[
left,
right,
low,
high @ (0x80..=0x82 | 0x87..=0x91),
tail @ ..,
] if (*left, *right) != (255, 255)
&& low & 0x7f <= 105
&& (low & 0x80 == 0 || matches!(high, 0x80..=0x82)) =>
[left, right, low, high @ 0x80..=0xbf, tail @ ..]
if (*left, *right) != (255, 255)
&& low & 0x7f <= 105
&& matches!(
(high & 0x3f) << 1 | low >> 7,
0..=10 | 14 | 16 | 18 | 20 | 22 | 24 | 26 | 28 | 30 | 32 | 34
| 36 | 38..=40 | 44 | 46..=49 | 53 | 54
) =>
{
let kind = match (high, low >> 7) {
(0x80, 0) => ScalarAlu::Add,
(0x80, _) => ScalarAlu::Subtract,
(0x81, 0) => ScalarAlu::AddSigned,
(0x81, _) => ScalarAlu::SubtractSigned,
(0x82, 0) => ScalarAlu::AddWithCarry,
(0x82, _) => ScalarAlu::SubtractWithBorrow,
(0x87, _) => ScalarAlu::And,
(0x88, _) => ScalarAlu::Or,
(0x89, _) => ScalarAlu::Xor,
// Even opcodes 20-34 (bit 23 clear, checked above).
(0x8a, _) => ScalarAlu::AndNot,
(0x8b, _) => ScalarAlu::OrNot,
(0x8c, _) => ScalarAlu::Nand,
(0x8d, _) => ScalarAlu::Nor,
(0x8e, _) => ScalarAlu::Xnor,
(0x8f, _) => ScalarAlu::ShiftLeft,
(0x90, _) => ScalarAlu::ShiftRight,
_ => ScalarAlu::ArithmeticShiftRight,
let kind = match (high & 0x3f) << 1 | low >> 7 {
0 => ScalarAlu::Add,
1 => ScalarAlu::Subtract,
2 => ScalarAlu::AddSigned,
3 => ScalarAlu::SubtractSigned,
4 => ScalarAlu::AddWithCarry,
5 => ScalarAlu::SubtractWithBorrow,
6 => ScalarAlu::Minimum { signed: true },
7 => ScalarAlu::Minimum { signed: false },
8 => ScalarAlu::Maximum { signed: true },
9 => ScalarAlu::Maximum { signed: false },
10 => ScalarAlu::Select,
14 => ScalarAlu::And,
16 => ScalarAlu::Or,
18 => ScalarAlu::Xor,
20 => ScalarAlu::AndNot,
22 => ScalarAlu::OrNot,
24 => ScalarAlu::Nand,
26 => ScalarAlu::Nor,
28 => ScalarAlu::Xnor,
30 => ScalarAlu::ShiftLeft,
32 => ScalarAlu::ShiftRight,
34 => ScalarAlu::ArithmeticShiftRight,
36 => ScalarAlu::BitfieldMask,
38 => ScalarAlu::Multiply,
39 => ScalarAlu::BitfieldExtract { signed: false },
40 => ScalarAlu::BitfieldExtract { signed: true },
44 => ScalarAlu::AbsoluteDifference,
op @ 46..=49 => ScalarAlu::ShiftLeftAdd(op - 45),
53 => ScalarAlu::MultiplyHigh { signed: false },
_ => ScalarAlu::MultiplyHigh { signed: true },
};
let (left, left_length) = decode_scalar(*left, tail, offset)?;
let (right, right_length) = decode_scalar(*right, tail, offset)?;
@@ -406,25 +588,22 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
signed: opcode < 192,
};
let vsrc1 = (packed >> 1) | ((upper & 1) << 7);
let selector = u16::from(*lo) | (u16::from(packed & 1) << 8);
let (src0, length) = match selector {
0..=106 => (CompareSource::Scalar(*lo), 4),
128..=192 => (CompareSource::Immediate(u32::from(selector - 128)), 4),
193..=208 => (
CompareSource::Immediate(0_u32.wrapping_sub(u32::from(selector - 192))),
4,
),
255 => {
let literal = tail
.first_chunk::<4>()
.ok_or_else(|| error(offset, "truncated literal"))?;
(CompareSource::Immediate(u32::from_le_bytes(*literal)), 8)
}
256..=511 => (CompareSource::Vector(*lo), 4),
_ => return Err(error(offset, "unsupported VOPC source")),
};
let (src0, length) =
decode_vector_source(*lo, *packed, tail, offset, "unsupported VOPC source")?;
(Op::Compare(comparison, src0, vsrc1), length)
}
// VOP2 integer forms (bit 31 = 0): OP bits 25-30, VDST 17-24,
// VSRC1 9-16, SRC0 0-8.
[lo, packed, upper, tag @ 0x00..=0x7b, tail @ ..]
if VectorInteger::from_opcode(tag >> 1).is_some() =>
{
let kind = VectorInteger::from_opcode(tag >> 1).unwrap();
let dst = (upper >> 1) | ((tag & 1) << 7);
let vsrc1 = (packed >> 1) | ((upper & 1) << 7);
let (src0, length) =
decode_vector_source(*lo, *packed, tail, offset, "unsupported VOP2 source")?;
(Op::VectorInteger(kind, dst, src0, vsrc1), length)
}
[lo, packed, upper, tag @ 0x7e..=0x7f, tail @ ..]
if packed & 0xfe == 2 && upper & 1 == 0 =>
{
@@ -509,6 +688,34 @@ fn decode_scalar(
}
}
/// A vector SRC0 selector (bits 0-8: `lo` and bit 0 of `packed`): s0-s105 or
/// `vcc_lo` (106), an inline integer, a literal dword from `tail`, or a VGPR.
fn decode_vector_source(
lo: u8,
packed: u8,
tail: &[u8],
offset: usize,
unsupported: &'static str,
) -> Result<(CompareSource, usize), ReferenceError> {
let selector = u16::from(lo) | (u16::from(packed & 1) << 8);
Ok(match selector {
0..=106 => (CompareSource::Scalar(lo), 4),
128..=192 => (CompareSource::Immediate(u32::from(selector - 128)), 4),
193..=208 => (
CompareSource::Immediate(0_u32.wrapping_sub(u32::from(selector - 192))),
4,
),
255 => {
let literal = tail
.first_chunk::<4>()
.ok_or_else(|| error(offset, "truncated literal"))?;
(CompareSource::Immediate(u32::from_le_bytes(*literal)), 8)
}
256..=511 => (CompareSource::Vector(lo), 4),
_ => return Err(error(offset, unsupported)),
})
}
fn vector_alu(op: VectorAlu, a: u32, b: u32, offset: usize) -> Result<u32, ReferenceError> {
let error = || {
error(
@@ -599,7 +806,8 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
Op::Move(dst, _)
| Op::MoveScalar(dst, _)
| Op::Add(dst, ..)
| Op::Vector(_, dst, ..) => {
| Op::Vector(_, dst, ..)
| Op::VectorInteger(_, dst, ..) => {
if exec != 0
&& registers
.iter()
@@ -681,6 +889,31 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
results[lane] = Some((dst, value));
}
}
Op::VectorInteger(kind, dst, src0, src1) => {
if exec != 0 {
// As for a compare, sources are checked once for the wave,
// whichever present lanes are active.
let check = |register: u8| {
(0..lanes).try_for_each(|lane| read(lane, register).map(|_| ()))
};
match src0 {
CompareSource::Vector(register) => check(register)?,
CompareSource::Scalar(register) => {
read_scalar(Source::Register(register))?;
}
CompareSource::Immediate(_) => {}
}
check(src1)?;
}
for lane in (0..lanes).filter(|&lane| executes(lane)) {
let s0 = match src0 {
CompareSource::Vector(register) => read(lane, register)?,
CompareSource::Scalar(register) => read_scalar(Source::Register(register))?,
CompareSource::Immediate(bits) => bits,
};
results[lane] = Some((dst, kind.apply(s0, read(lane, src1)?)));
}
}
Op::ScalarMove(dst, src) => {
if dst < 8 {
return Err(error(offset, "write to a reserved resource SGPR"));
@@ -694,6 +927,44 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
}
scalars[usize::from(dst)] = Some(value);
}
Op::ScalarUnary(kind, dst, src) => {
if dst < 8 {
return Err(error(offset, "write to a reserved resource SGPR"));
}
let value = read_scalar(src)?;
// -1 (all ones) when no bit is found.
let found = |index: u32| if index == 32 { u32::MAX } else { index };
let result = match kind {
ScalarUnary::Not => !value,
ScalarUnary::ReverseBits => value.reverse_bits(),
ScalarUnary::CountZeros => value.count_zeros(),
ScalarUnary::CountOnes => value.count_ones(),
ScalarUnary::FindFirstZero => found(value.trailing_ones()),
ScalarUnary::FindFirstOne => found(value.trailing_zeros()),
ScalarUnary::FindLastBit => found(value.leading_zeros()),
ScalarUnary::FindLastSignBit => {
let same = if value >> 31 == 1 {
value.leading_ones()
} else {
value.leading_zeros()
};
found(same)
}
ScalarUnary::SignExtendByte => value as u8 as i8 as i32 as u32,
ScalarUnary::SignExtendShort => value as u16 as i16 as i32 as u32,
ScalarUnary::Absolute => (value as i32).wrapping_abs() as u32,
};
scalars[usize::from(dst)] = Some(result);
if matches!(
kind,
ScalarUnary::Not
| ScalarUnary::CountZeros
| ScalarUnary::CountOnes
| ScalarUnary::Absolute
) {
scc = Some(result != 0);
}
}
Op::CompareEqual(lhs, rhs) => {
scc = Some(read_scalar(lhs)? == read_scalar(rhs)?);
}
@@ -710,8 +981,13 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
ScalarAlu::AddWithCarry | ScalarAlu::SubtractWithBorrow => i64::from(
scc.ok_or_else(|| error(offset, "carry-in from uninitialized SCC"))?,
),
ScalarAlu::Select => {
i64::from(scc.ok_or_else(|| error(offset, "select on uninitialized SCC"))?)
}
_ => 0,
};
let (signed_lhs, signed_rhs) =
(i64::from(lhs as u32 as i32), i64::from(rhs as u32 as i32));
// Exact integer arithmetic, then reduction modulo 2^32.
let (exact, flag) = match kind {
ScalarAlu::Add | ScalarAlu::AddWithCarry => {
@@ -740,6 +1016,65 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
};
(bits, bits != 0)
}
// Guide 12.1: strict comparisons, so equal operands give
// S1 (the same value) and SCC = 0.
ScalarAlu::Minimum { signed } | ScalarAlu::Maximum { signed } => {
let (a, b) = if signed {
(signed_lhs, signed_rhs)
} else {
(lhs, rhs)
};
let first = if matches!(kind, ScalarAlu::Minimum { .. }) {
a < b
} else {
a > b
};
(if first { lhs } else { rhs }, first)
}
// The SCC-less forms; `flag` is unused for them below.
ScalarAlu::Select => (if carry == 1 { lhs } else { rhs }, false),
ScalarAlu::BitfieldMask => (((1 << (lhs & 0x1f)) - 1) << (rhs & 0x1f), false),
ScalarAlu::Multiply => (signed_lhs * signed_rhs, false),
ScalarAlu::MultiplyHigh { signed } => {
// The unsigned product fits only in u64.
let high = if signed {
(signed_lhs * signed_rhs) >> 32
} else {
((lhs as u64 * rhs as u64) >> 32) as i64
};
(high, false)
}
// Offset S1[4:0], width S1[22:16] (0-127). A width of 32 or
// more keeps every bit of the shifted word.
ScalarAlu::BitfieldExtract { signed } => {
let (shift, width) = (rhs & 0x1f, (rhs >> 16) & 0x7f);
let data = if signed { signed_lhs } else { lhs };
let shifted = data >> shift;
let value = if width == 0 {
0
} else if width >= 32 {
shifted
} else {
let field = shifted & ((1 << width) - 1);
if signed && field >> (width - 1) == 1 {
field - (1 << width)
} else {
field
}
};
(value, value.rem_euclid(1 << 32) != 0)
}
// The 32-bit difference first (guide examples), then |D|.
ScalarAlu::AbsoluteDifference => {
let difference = (signed_lhs - signed_rhs) as u32 as i32;
let value = difference.unsigned_abs();
(i64::from(value), value != 0)
}
// The carry out of the exact (S0 << N) + S1.
ScalarAlu::ShiftLeftAdd(n) => {
let sum = (lhs << n) + rhs;
(sum, sum >= 1 << 32)
}
// Guide 12.1: shifts use only S1[4:0]; all set SCC = (D != 0).
_ => {
let (a, b) = (lhs as u32, rhs as u32);
@@ -758,7 +1093,16 @@ fn execute_wave(program: &[DecodedInstruction], input: &[u32]) -> Result<Vec<u32
};
let value = exact.rem_euclid(1 << 32) as u32;
scalars[usize::from(dst)] = Some(value);
scc = Some(flag);
// Guide 12.1 and Tables 11, 12, 14: these forms leave SCC unchanged.
if !matches!(
kind,
ScalarAlu::Select
| ScalarAlu::BitfieldMask
| ScalarAlu::Multiply
| ScalarAlu::MultiplyHigh { .. }
) {
scc = Some(flag);
}
}
// RDNA 2 ISA section 3.9: VCC[n] = EXEC[n] & test(n), fully written.
Op::Compare(comparison, src0, src1) => {
+130 -8
View File
@@ -9,7 +9,8 @@ pub use graphics::{PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
pub use xenora_decoder::Architecture;
use xenora_decoder::{
DecodeError, DecodedInstruction, Instruction, ScalarSource, VectorCompareOp, VectorSource,
DecodeError, DecodedInstruction, Instruction, ScalarSource, VectorBinary, VectorCompareOp,
VectorSource,
};
/// SGPR index of `vcc_lo`.
@@ -161,6 +162,7 @@ impl Op {
Binary::ShiftLeft | Binary::ShiftRight => {
format!("{left} {symbol} ({right} & 31u)")
}
Binary::Vector(operation) => vector_expression(operation, &left, &right),
_ => format!("{left} {symbol} {right}"),
}
}
@@ -219,6 +221,8 @@ enum Binary {
Xor,
FloatAdd,
FloatMul,
/// A registry VOP2 integer operation, lowered by its typed template.
Vector(VectorBinary),
}
impl Binary {
@@ -233,10 +237,56 @@ impl Binary {
Self::Xor => ("xor.b32", "^"),
Self::FloatAdd => ("add.f32", "+"),
Self::FloatMul => ("mul.f32", "*"),
Self::Vector(operation) => (
match operation {
VectorBinary::Add => "add.u32",
VectorBinary::Sub => "sub.u32",
VectorBinary::Xnor => "xnor.b32",
VectorBinary::MinSigned => "min.i32",
VectorBinary::MinUnsigned => "min.u32",
VectorBinary::MaxSigned => "max.i32",
VectorBinary::MaxUnsigned => "max.u32",
VectorBinary::Mul24Signed => "mul24.i32",
VectorBinary::Mul24Unsigned => "mul24.u32",
VectorBinary::MulHi24Signed => "mulhi24.i32",
VectorBinary::MulHi24Unsigned => "mulhi24.u32",
},
"",
),
}
}
}
/// The MSL template of each per-lane registry operation. Integer arithmetic is
/// on `uint` (wrapping); signed forms reinterpret with `as_type`, and the
/// 24-bit forms sign-extend bit 23 with a shift pair or mask to 24 bits first.
fn vector_expression(operation: VectorBinary, left: &str, right: &str) -> String {
let int = |value: &str| format!("as_type<int>({value})");
let i24 = |value: &str| format!("(as_type<int>({value} << 8u) >> 8)");
let u24 = |value: &str| format!("({value} & 0x00ffffffu)");
match operation {
VectorBinary::Add => format!("{left} + {right}"),
VectorBinary::Sub => format!("{left} - {right}"),
VectorBinary::Xnor => format!("~({left} ^ {right})"),
VectorBinary::MinSigned => format!("as_type<uint>(min({}, {}))", int(left), int(right)),
VectorBinary::MinUnsigned => format!("min({left}, {right})"),
VectorBinary::MaxSigned => format!("as_type<uint>(max({}, {}))", int(left), int(right)),
VectorBinary::MaxUnsigned => format!("max({left}, {right})"),
// The low 32 bits of a product do not depend on signedness, so the
// sign-extended factors multiply as wrapping uint.
VectorBinary::Mul24Signed => format!(
"as_type<uint>({}) * as_type<uint>({})",
i24(left),
i24(right)
),
VectorBinary::Mul24Unsigned => format!("{} * {}", u24(left), u24(right)),
VectorBinary::MulHi24Signed => {
format!("as_type<uint>(mulhi({}, {}))", i24(left), i24(right))
}
VectorBinary::MulHi24Unsigned => format!("mulhi({}, {})", u24(left), u24(right)),
}
}
// Each bit is either known zero, known one or unconstrained.
#[derive(Clone, Copy)]
struct KnownBits {
@@ -632,7 +682,7 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
| Instruction::VectorXorB32 { dst, .. } => dst,
_ => {
return Err(error(
"code skipped by a runtime s_cbranch_vccz may contain only integer vector ALU instructions",
"code skipped by a runtime s_cbranch_vccz may contain only v_mov_b32, v_add_nc_u32_e64 and the hand-written integer VOP2 forms",
));
}
};
@@ -670,7 +720,8 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
| Instruction::VectorOrB32 { .. }
| Instruction::VectorXorB32 { .. }
| Instruction::VectorAddF32 { .. }
| Instruction::VectorMulF32 { .. } => continue,
| Instruction::VectorMulF32 { .. }
| Instruction::VectorAlu { .. } => continue,
_ => {}
}
}
@@ -809,6 +860,21 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
*slot = Some(value);
continue;
}
Instruction::ScalarUnary { op, dst, src } => {
let src = read_scalar(src)?;
if dst < 8 {
return Err(error("scalar unary would modify a resource descriptor"));
}
let (value, flag) = op.evaluate(src);
let slot = scalars
.get_mut(usize::from(dst))
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
*slot = Some(value);
if let Some(flag) = flag {
scc = Some(flag);
}
continue;
}
Instruction::ScalarAlu {
op,
dst,
@@ -816,20 +882,22 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
src1,
} => {
let (src0, src1) = (read_scalar(src0)?, read_scalar(src1)?);
let carry_in = if op.reads_scc() {
scc.ok_or_else(|| error("carry-in or borrow-in reads uninitialized SCC"))?
let scc_in = if op.reads_scc() {
scc.ok_or_else(|| error("SOP2 SCC input reads uninitialized SCC"))?
} else {
false
};
if dst < 8 {
return Err(error("scalar ALU would modify a resource descriptor"));
}
let (value, flag) = op.evaluate(src0, src1, carry_in);
let (value, flag) = op.evaluate(src0, src1, scc_in);
let slot = scalars
.get_mut(usize::from(dst))
.ok_or_else(|| error("scalar destination exceeds the fixture register file"))?;
*slot = Some(value);
scc = Some(flag);
if let Some(flag) = flag {
scc = Some(flag);
}
continue;
}
Instruction::ScalarCompare { op, src0, src1 } => {
@@ -923,6 +991,44 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
},
)
}
Instruction::VectorAlu {
op,
dst,
src0,
src1,
} => {
let src0 = match src0 {
VectorSource::Register(register) => read(register)?,
VectorSource::Scalar(register) if usize::from(register) == VCC_LO => {
match (lane_vcc, scalars[VCC_LO]) {
(Some(mask), _) => mask,
(None, Some(bits)) => {
constant(&mut operations, &mut facts, offset, bits)
}
(None, None) => {
return Err(error("vector ALU reads uninitialized VCC_LO"));
}
}
}
VectorSource::Scalar(register) => {
let bits = read_scalar(ScalarSource::Register(register))?;
constant(&mut operations, &mut facts, offset, bits)
}
VectorSource::Immediate(bits) => {
constant(&mut operations, &mut facts, offset, bits)
}
};
let src1 = read(src1)?;
let (left, right) = if op.swaps_sources() {
(src1, src0)
} else {
(src0, src1)
};
(
Some(dst),
Op::Binary(Binary::Vector(op.lowering()), left, right),
)
}
Instruction::VectorAddF32 { dst, src0, src1 } => (
Some(dst),
Op::Binary(Binary::FloatAdd, read(src0)?, read(src1)?),
@@ -958,6 +1064,9 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
}
_ => KnownBits::UNKNOWN,
};
// Arms may push operand constants first, so the result is the next slot
// now rather than `next`.
let produced = Value(operations.len());
facts.push(value_bits);
operations.push((offset, operation));
if let Some(dest) = dest {
@@ -972,7 +1081,7 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
&mut facts,
offset,
exec,
next,
produced,
registers[slot],
)?);
}
@@ -983,6 +1092,19 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
})
}
/// A wave-uniform constant operand at `offset`.
fn constant(
operations: &mut Vec<(usize, Op)>,
facts: &mut Vec<KnownBits>,
offset: usize,
bits: u32,
) -> Value {
let value = Value(operations.len());
operations.push((offset, Op::Constant(bits)));
facts.push(KnownBits::constant(bits));
value
}
// Keeping a value for inactive lanes requires a previously initialized destination.
fn merge_lanes(
operations: &mut Vec<(usize, Op)>,
+42
View File
@@ -308,6 +308,48 @@ fn scalar_compare_results_resolve_every_branch() {
);
}
#[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");
+3
View File
@@ -54,3 +54,6 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
- [Legal scope](legal.md), [dependency licensing](licenses.md), and [third-party notices](../THIRD_PARTY_NOTICES.md) — Input policy, attribution, and redistribution findings.
- [Contribution guidelines](../CONTRIBUTING.md) — Original authorship, Developer Certificate of Origin sign-off, and evidence requirements.
- [Agent task queue](coordination/agent-tasks.md) — Areas, claiming, leases, upstream sync, verification and the security model for parallel contributors and coding agents.
- [Infrastructure QA ownership](coordination/infrastructure-qa-ownership.md) — Non-overlapping paths for infrastructure and QA tooling.
- [Agent queue smoke evidence](coordination/agent-queue-smoke.md) — Live Actions results from the disposable smoke repository.
- [Infrastructure QA tooling](testing/infrastructure/README.md) — Advisory orchestration, PR validation, benchmark analysis and release checks.
+4 -4
View File
@@ -1,17 +1,17 @@
<svg xmlns="http://www.w3.org/2000/svg" width="530" height="185" viewBox="0 0 530 185" role="img" aria-labelledby="title description">
<title id="title">Xenora · recorded progress</title>
<desc id="description">Decoded gfx1030 forms: 61 of 61. Accepted Metal forms · Apple M5: 18 of 61. Accepted guest milestones · X1–X4: 4 of 4</desc>
<desc id="description">Decoded gfx1030 forms: 100 of 100. Accepted Metal forms · Apple M5: 18 of 100. Accepted guest milestones · X1–X4: 4 of 4</desc>
<rect x="1" y="1" width="528" height="183" rx="10" fill="#18212a" stroke="#516171"/>
<g font-family="system-ui,sans-serif" fill="#eaf0f5">
<text x="20" y="29" font-size="13" font-weight="700">RECORDED FIXTURE PROGRESS</text>
<text x="20" y="58" font-size="13">Decoded gfx1030 forms</text>
<text x="510" y="58" font-size="13" text-anchor="end">61 / 61</text>
<text x="510" y="58" font-size="13" text-anchor="end">100 / 100</text>
<rect x="20" y="65" width="490" height="4" rx="2" fill="#3c4a58"/>
<rect x="20" y="65" width="490.00" height="4" rx="2" fill="#88c6bd"/>
<text x="20" y="96" font-size="13">Accepted Metal forms · Apple M5</text>
<text x="510" y="96" font-size="13" text-anchor="end">18 / 61</text>
<text x="510" y="96" font-size="13" text-anchor="end">18 / 100</text>
<rect x="20" y="103" width="490" height="4" rx="2" fill="#3c4a58"/>
<rect x="20" y="103" width="144.59" height="4" rx="2" fill="#88c6bd"/>
<rect x="20" y="103" width="88.20" height="4" rx="2" fill="#88c6bd"/>
<text x="20" y="134" font-size="13">Accepted guest milestones · X1–X4</text>
<text x="510" y="134" font-size="13" text-anchor="end">4 / 4</text>
<rect x="20" y="141" width="490" height="4" rx="2" fill="#3c4a58"/>

Before

Width:  |  Height:  |  Size: 1.5 KiB

After

Width:  |  Height:  |  Size: 1.5 KiB

+48
View File
@@ -0,0 +1,48 @@
# Agent queue live smoke test
Issue: #180
Disposable repository: [`ranveersoni98/xenora-agent-queue-smoke`](https://github.com/ranveersoni98/xenora-agent-queue-smoke) (private)
Production Xenora workflows are not modified by this exercise except where a
separate coordinated fix is recorded.
## Why a disposable repository
The queue unit suite does not call the GitHub API. Issue #180 requires Actions
evidence for simultaneous claims, refusal, release, stale-lease audit behaviour,
pending-run replay and exact head-SHA verification against a real repository.
## Harness notes
- Copies `scripts/agent_queue/`, the unit tests, `agent-queue.sh`,
`agent-sync.sh` and the two agent workflows from Xenora.
- Uses `ubuntu-latest` runners in the disposable repo only. Queue decisions are
standard-library Python; production Xenora keeps `ubuntu-24.04-arm`.
- Config upstream is `ranveersoni98/xenora-agent-queue-smoke`.
## Evidence log
| Scenario | Result | Evidence | Recorded |
| --- | --- | --- | --- |
| Claim grant on ready task | pass | issue #1 labels `agent:claimed,claimed-by:ranveersoni98`; run `45383910132` | 2026-11-24 |
| Overlap claim refusal | pass | issue #2 bot: file overlap with claimed task #1; run `45384365386` | 2026-11-24 |
| Disjoint second claim | pass | issue #3 claimed; run `45384367521` | 2026-11-24 |
| `/progress` renew | pass | issue #1 bot: Lease renewed; run `45384473061` | 2026-11-24 |
| `/release` | pass | issue #3 returned to `agent:ready`; bot release marker | 2026-11-24 |
| Claim without `agent:ready` | pass | issue #4 refused: not labelled agent:ready | 2026-11-24 |
| Comment-only apply crash | fixed | `ghio.apply_actions` skipped no-op `gh issue edit`; mirrored to smoke | 2026-11-24 |
| Audit `workflow_dispatch` | pass | run `45385817420` after `pull-requests: read` and `summary --now` argparse fix | 2026-11-24 |
| Exact `/verified` head SHA | deferred | needs second eligible non-author account on the smoke repo | 2026-11-24 |
| Full wall-clock stale lease | deferred | covered by unit tests with frozen clock (`lease_hours=168`) | 2026-11-24 |
## Production follow-ups
1. Keep `agent-pr-checks` advisory until this evidence is reviewed.
2. Coordinate adding `pull-requests: read` to the production audit job permissions
(same defect as the smoke audit failure).
3. Add a second QA-eligible verifier before treating `/verified` as smoke-complete.
## Local unit suite
```sh
PYTHONPATH=scripts python3 -m unittest discover -s tests/agent_queue
```
@@ -0,0 +1,44 @@
# Infrastructure QA campaign ledger
Running record for the infrastructure and engineering-quality campaign.
Update after each meaningful commit batch. Do not invent passing tests.
## Baseline
- Branch: `main` synchronized with `origin/main` before each batch
- Hard exclusions: CPU/runtime crates, RDNA2 crates, `app/`, fixtures, GPU tests
- Approved paths: see `infrastructure-qa-ownership.md`
## Commits
| SHA | Summary | Tests |
| --- | --- | --- |
| `8410e3d` | test(qa): cover environment diagnostic helpers. | focused suite before commit |
| `48f44ca` | feat(qa): add operational python3 -m qa CLI. | focused suite before commit |
| `f56d3c9` | feat(release): add python3 -m release CLI entrypoints. | focused suite before commit |
| `22bafeb` | feat(qa): add read-only RDNA2 expansion planning over live inventories. | focused suite before commit |
| `c651a9d` | feat(qa): add unified verification profiles with stale evidence detection. | focused suite before commit |
| `f175a10` | feat(qa): scan CPU opcode and import coverage from existing sources. | focused suite before commit |
| `f400550` | feat(qa): compare recorded benchmarks with identity and noise guards. | focused suite before commit |
| `7a51764` | feat(qa): detect claim collisions across renames and deletions. | focused suite before commit |
| `050df30` | feat(release): build release-readiness reports with SBOM and evidence. | focused suite before commit |
| `63cf359` | test(qa): smoke-test qa and release CLIs against real commands. | focused suite before commit |
| `313430c` | docs(testing): document Phase II qa and release CLI workflows. | focused suite before commit |
| `0f7658b` | docs(changelog): record Phase II infrastructure automation CLIs. | focused suite before commit |
## Smoke repository
- Repo: `ranveersoni98/xenora-agent-queue-smoke`
- See `agent-queue-smoke.md` for Actions evidence
## Limitations
- Phase II deferred: exact `/verified` head-SHA smoke and wall-clock lease expiry still need a second eligible verifier / long wait.
- `qa verify cpu|gpu|app|full` invoke heavy existing commands; use `quick` for local iteration.
- CPU coverage statuses are heuristic where no authoritative opcode inventory file exists.
## Limitations
- Production agent PR checks remain advisory
- Independent `/verified` on smoke PRs needs a second eligible account
- New QA/release tools are local/advisory until review
@@ -0,0 +1,61 @@
# Infrastructure and QA ownership manifest
Non-overlapping file ownership for the infrastructure and engineering-quality
campaign. Active CPU/runtime, RDNA2 and native-application Gates 4–9 work stays
outside this manifest.
Rechecked against `origin/main` at the claim of issue #180. Update this file
when a path is claimed, released or closed.
## Hard exclusions (do not edit under this campaign)
- `crates/loader/`, `crates/import-gen/`, `crates/ffi/`, `crates/isa/`
- `crates/decoder/`, `crates/shader/`, `crates/ref/`, `crates/metal/`, `crates/texture/`
- `app/`, `fixtures/`, `tests/validation/`
- `scripts/test-gpu.sh` and existing CPU/GPU benchmark workload implementations
- Guest execution authorization and trusted-fixture policy
Shared Cargo configuration, production CI workflows and `CHANGELOG.md` require
an explicit per-change coordination note even when a QA issue mentions them.
## Active claims
| Issue | Holder | Paths | Notes |
| --- | --- | --- | --- |
| #180 | ranveersoni98 | `tests/agent_queue/`, `docs/coordination/` | Live smoke evidence; no production workflow edits |
| #277 | held until #180 releases coordination docs | `scripts/qa/`, `tests/qa/`, `scripts/release/`, `tests/release/`, `docs/testing/infrastructure/` | Maintainer-approved new paths; depends on #180 |
## Approved new paths (not yet exclusively held)
Maintainer-approved for the infrastructure/QA campaign once claimed without
overlapping an active issue:
| Path | Intended workstream |
| --- | --- |
| `scripts/qa/` | Advisory PR verification, test orchestration, env diagnostics |
| `tests/qa/` | Independent tests for `scripts/qa/` |
| `scripts/release/` | Native Mach-O, SBOM, checksum and release-evidence tools |
| `tests/release/` | Independent tests for `scripts/release/` |
| `docs/testing/infrastructure/` | Tooling docs; not product GPU/CPU protocol docs |
## Existing scripts to extend or wrap, not duplicate
| Existing path | Relation |
| --- | --- |
| `scripts/agent_queue/` | Owned by the merged queue (#165); #180 smoke-tests only |
| `scripts/audit/native.sh` | ARM64 and linkage gate; release tools may consume its outputs |
| `scripts/audit/claims.sh`, `dependencies.sh`, `status.py`, `test_inventory.py` | Prefer calling or summarizing; do not reimplement |
| `scripts/benchmark.sh` | Analysis tools consume results only; do not change workloads |
## Disposable remote testing
Live agent-queue Actions exercises run only in the maintainer-approved private
repository `ranveersoni98/xenora-agent-queue-smoke`. Do not enable blocking
production checks until that smoke evidence is recorded and reviewed.
## Phase II note
Issue #277 holds `scripts/qa/`, `tests/qa/`, `scripts/release/`, `tests/release/` and
`docs/testing/infrastructure/`. Ledger updates for Phase II commits are recorded in
`docs/coordination/infrastructure-qa-ledger.md` under the #180 coordination claim until
#180 closes, then move with the tooling owners.
+39
View File
@@ -21,6 +21,17 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
| `s_waitcnt_vscnt null, 0` | SOPK, exact null source and zero immediate | 4 B | yes | yes | three-way passed | verified store wait | implemented | fixture verified | fixture verified |
| `s_endpgm` | SOPP, zero immediate | 4 B | yes | yes | three-way passed | verified termination | implemented | fixture verified | fixture verified |
| `s_mov_b32` | Normal SGPR or EXEC/VCC half destination and normal SGPR, inline integer or literal source | `BE880387` | yes | yes | three-way passed | resolved scalar state | implemented | fixture verified | fixture verified |
| `s_not_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = ~S0; SCC = D != 0 | `BE890708` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_brev_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0 bit-reversed; SCC unchanged | `BE8A0B08` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_bcnt0_i32_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = count of zero bits; SCC = D != 0 | `BE8C0D08` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_bcnt1_i32_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = count of one bits; SCC = D != 0 | `BE8B0F08` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_ff0_i32_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = index of the lowest zero bit, or -1; SCC unchanged | `BE8E11FF 0000FFFF` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_ff1_i32_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = index of the lowest one bit, or -1; SCC unchanged | `BE8D13FF 00400000` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_flbit_i32_b32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = zeros above the highest one bit, or -1; SCC unchanged | `BE8F1508` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_flbit_i32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = bits above the highest bit differing from the sign, or -1; SCC unchanged | `BE9017FF FFF00000` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_sext_i32_i8` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0[7:0] sign-extended; SCC unchanged | `BE911908` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_sext_i32_i16` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0[15:0] sign-extended; SCC unchanged | `BE921AFF 00018000` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_abs_i32` | SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = \|S0\| (0x80000000 stays); SCC = D != 0 | `BE933412` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cmp_eq_u32` | Normal SGPR or integer operands, with at most one source selecting a literal | `BF068708` | yes | yes | three-way passed | resolved SCC | implemented | fixture verified | fixture verified |
| `s_cmp_eq_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 == S1 (signed) | `BF00C108` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cmp_lg_i32` | SOPC; normal SGPR, inline integer or literal sources with at most one literal; SCC = S0 != S1 (signed) | `BF010908` | yes | yes | three-way passed | resolved SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
@@ -50,6 +61,22 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
| `s_lshl_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 << S1[4:0]; SCC = result != 0 | `8F0EA40D` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_lshr_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0], zero fill; SCC = result != 0 | `900FFF0E FFFFFFE1` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_ashr_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0], sign fill; SCC = result != 0 | `91109F0E` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_min_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 < S1 (signed) else S1; SCC = S0 < S1 | `830A0908` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_min_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 < S1 (unsigned) else S1; SCC = S0 < S1 | `83988509` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_max_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 > S1 (signed) else S1; SCC = S0 > S1 | `84170908` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_max_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 > S1 (unsigned) else S1; SCC = S0 > S1 | `848C0908` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cselect_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = SCC ? S0 : S1; reads SCC, SCC unchanged | `850B0809` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_bfm_b32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ((1 << S0[4:0]) - 1) << S1[4:0]; SCC unchanged | `920D848C` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_mul_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = low 32 bits of S0 * S1; SCC unchanged | `930F0908` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_bfe_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0] masked to S1[22:16] bits; SCC = D != 0 | `9390FF08 00080004` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_bfe_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0] (sign fill) masked to S1[22:16] bits, sign-extended; SCC = D != 0 | `9411FF08 00080004` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_absdiff_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = \|S0 - S1\| of the 32-bit difference (0x80000000 stays); SCC = D != 0 | `96120809` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_lshl1_add_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 1) + S1; SCC = carry out of the exact sum | `970E0908` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_lshl2_add_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 2) + S1; SCC = carry out of the exact sum | `97990909` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_lshl3_add_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 3) + S1; SCC = carry out of the exact sum | `98130808` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_lshl4_add_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 4) + S1; SCC = carry out of the exact sum | `9894D009` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_mul_hi_u32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = high 32 bits of the unsigned product; SCC unchanged | `9A950808` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_mul_hi_i32` | SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = high 32 bits of the signed product; SCC unchanged | `9B160808` | yes | yes | three-way passed | resolved scalar state and SCC | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_lt_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 < S1), fully written | `7D020701` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_eq_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 == S1), fully written | `7D040280` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_le_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 <= S1), fully written | `7D060208` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
@@ -74,6 +101,18 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
| `v_ashrrev_i32_e32` | Two VGPR sources and one VGPR destination | `31FFFF01` | yes | yes | three-way passed | MSL signed right shift with a five-bit count | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cbranch_execz` | Nonnegative signed dword displacement | `BF880001` | yes | yes | three-way passed | resolved Wave32 EXEC_LO zero check | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cbranch_vccz` | Nonnegative signed dword displacement | `BF860001` | yes | yes | three-way passed | resolved Wave32 VCC_LO zero check, or a wave-uniform join select after a vector compare | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_mul_i32_i24_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = low 32 bits of sext(S0[23:0]) * sext(S1[23:0]) | `120402C3` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_mul_hi_i32_i24_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = bits 63:32 of sext(S0[23:0]) * sext(S1[23:0]) | `14060208` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_mul_u32_u24_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = low 32 bits of S0[23:0] * S1[23:0] | `160802FF 00123456` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_mul_hi_u32_u24_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = bits 63:32 of S0[23:0] * S1[23:0] | `180A0208` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_min_i32_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = signed min(S0, S1) | `220C0501` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_max_i32_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = signed max(S0, S1) | `240E0285` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_min_u32_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = unsigned min(S0, S1) | `26100303` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_max_u32_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = unsigned max(S0, S1) | `28120208` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_xnor_b32_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = ~(S0 ^ S1) | `3C140B04` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_add_nc_u32_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = S0 + S1, no carry | `4A160F06` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_sub_nc_u32_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = S0 - S1, no carry | `4C181308` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_subrev_nc_u32_e32` | VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = S1 - S0, no carry | `4E1A170A` | yes | yes | three-way passed | per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
<!-- status:instructions:end -->
## Automated three-way comparison
+2
View File
@@ -8,6 +8,8 @@ Apple documents `uint`, device address space and the scalar compute grid-positio
The integer emitter uses unsigned addition, bitwise logic, and shifts. Scalar moves and compares are evaluated at translation time using known SGPR initializers. Forward branches must target instruction boundaries. Conditional branches require known scalar condition code (SCC), execution mask (EXEC), or vector condition code (VCC) state. Wave32 zero checks read the low halves of EXEC and VCC. Known partial EXEC masks merge each vector result with the initialized destination according to the logical lane number, computed from the grid index modulo 32. Empty EXEC suppresses vector arithmetic and moves. Reachable vector memory operations require a full mask. The IR records the statically selected path. Scalar values can originate only from constants and initialized SGPRs, and SGPR 0–7 remain reserved for synthetic descriptors. The generated kernel contains only the selected scalar branch path. The partial-mask merge uses a per-invocation selection from two vector values.
Twelve VOP2 integer forms from the semantic registry lower through one typed template per declared operation (`VectorBinary`), not per opcode: wrapping `uint` add, subtract and XNOR; `min`/`max` on `uint`, or on `as_type<int>` for the signed forms; and the 24-bit multiplies, which first sign-extend bit 23 with `as_type<int>(x << 8u) >> 8` (or mask to 24 bits for the unsigned forms), then take the low word as a wrapping `uint` product or the high word with MSL `mulhi`. `v_subrev_nc_u32` declares reversed sources, so the translator swaps them. A wave-uniform SRC0 (an SGPR, inline integer or literal) becomes a constant operand, while the lane's VGPRs stay runtime values; `vcc_lo` as SRC0 uses the lane-derived compare mask when a VOPC produced it. These forms are refused inside code skipped by a runtime `s_cbranch_vccz`, as both interpreters refuse them.
The float subset accepts addition and multiplication only when every possible operand is a positive normal binary32 value and the exact result is itself representable as a normal binary32 value. A known-bit analysis propagates the effect of masks and XOR. It enumerates up to two candidate bit patterns per operand, proves the result for each pair, and retains at most two unique results for an ensuing operation. No rounding mode, signed-zero behavior, subnormal mode, NaN handling or infinity policy is required for this restricted domain. Unknown or inexact cases fail verification.
The generated MSL uses unsigned words for register bits and `as_type` for reinterpretation at individual float operations. It disables contraction and reassociation for these kernels. The compiler tests compare all three fixture outputs against tracked IR and MSL goldens. The [native demonstration](../../scripts/demo.sh) checks executed results.
+3
View File
@@ -8,11 +8,14 @@
| SOPP `S_WAITCNT`, SOPK `S_WAITCNT_VSCNT` | A zero vector-load or vector-store threshold completes the associated transfer. The model permits one pending operation per counter (CLAIM-RDNA2-TRANSFER-WAITS). |
| VOP1 `V_MOV_B32` | Read a register, inline integer or literal. Copy all 32 bits. |
| VOP3 `V_ADD_NC_U32` | Read two vector registers and add modulo 2^32. No implicit carry or flag update. |
| SOP2 `S_MIN_{I32,U32}`, `S_MAX_{I32,U32}`, `S_CSELECT_B32`, `S_BFM_B32`, `S_MUL_I32`, `S_MUL_HI_{U32,I32}`, `S_BFE_{U32,I32}`, `S_ABSDIFF_I32`, `S_LSHL{1,2,3,4}_ADD_U32` | The guide's section 12.1 result, computed exactly and reduced modulo 2^32. Min and max compare strictly (a tie gives S1, SCC = 0); CSELECT reads SCC and refuses it unset; BFM, MUL, MUL_HI and CSELECT leave SCC unchanged; BFE uses offset S1[4:0] and width S1[22:16] (32 or more keeps every shifted bit); ABSDIFF negates the wrapped difference; LSHLn_ADD sets SCC to the carry of the exact sum. Descriptor SGPRs are reserved. |
| SOP1 `S_NOT_B32`, `S_BREV_B32`, `S_BCNT{0,1}_I32_B32`, `S_FF{0,1}_I32_B32`, `S_FLBIT_I32_B32`, `S_FLBIT_I32`, `S_SEXT_I32_I{8,16}`, `S_ABS_I32` | The guide's section 12.3 result; a search that finds nothing gives -1, and `S_ABS_I32` of 0x80000000 is 0x80000000. Only NOT, BCNT0, BCNT1 and ABS write SCC (= D != 0). Descriptor SGPRs are reserved. |
| SOP1 `S_MOV_B32`, SOPC `S_CMP_{EQ,LG,GT,GE,LT,LE}_{I32,U32}` | Copy 32 bits into a scalar register, or compare SSRC0 with SSRC1 (signed for `_I32` ordering, unsigned for `_U32`; EQ and LG on the raw bits) and set only SCC. Descriptor SGPRs are reserved. |
| SOP2 `S_ADD_U32`, `S_SUB_U32`, `S_ADD_I32`, `S_SUB_I32`, `S_ADDC_U32`, `S_SUBB_U32`, `S_AND_B32`, `S_OR_B32`, `S_XOR_B32`, `S_ANDN2_B32`, `S_ORN2_B32`, `S_NAND_B32`, `S_NOR_B32`, `S_XNOR_B32`, `S_LSHL_B32`, `S_LSHR_B32`, `S_ASHR_I32` | Exact integer result reduced modulo 2^32; shifts use S1[4:0]; SCC is the carry-out, the borrow, signed overflow (the exact signed result does not fit in i32), or a nonzero logical or shift result, and ADDC/SUBB consume SCC ([SOP2 scalar ALU](scalar-alu.md)). Descriptor SGPRs are reserved. |
| VOPC `V_CMP_{LT,EQ,LE,GT,NE,GE}_{I32,U32}` | Compare widened 64-bit values per active lane. VCC_LO gets EXEC & the test results and is fully written, so empty EXEC gives 0. A later `S_CBRANCH_VCCZ` on such a mask checks the skipped code statically ([VOPC integer compares](vector-compare.md)). |
| SOPP `S_BRANCH`, `S_CBRANCH_SCC0` | Use a signed dword displacement from the next instruction (CLAIM-RDNA2-SOPP-BRANCH-DISPLACEMENT). Require a nonnegative word displacement to a decoded instruction boundary, including for untaken edges. |
| VOP2 `V_AND_B32`, `V_XOR_B32` | Apply the bitwise operator to two VGPRs. |
| VOP2 `V_MUL_{I32_I24,HI_I32_I24,U32_U24,HI_U32_U24}`, `V_MIN_{I32,U32}`, `V_MAX_{I32,U32}`, `V_XNOR_B32`, `V_ADD_NC_U32`, `V_SUB_NC_U32`, `V_SUBREV_NC_U32` | The guide's section 12.7 result per active lane, computed exactly: the 24-bit multiplies use S0[23:0] and S1[23:0] (sign-extended for I24) and keep bits 31:0 or 63:32; SUBREV gives S1 - S0. SRC0 is a VGPR, s0-s105, `vcc_lo`, an inline integer or a literal. Inactive lanes keep VDST; no SCC or VCC write. |
| VOP2 `V_ADD_F32`, `V_MUL_F32` | Require exact binary32 results by checking the inputs and the wider intermediate. Multiplication of the significands fits in binary64. Addition must also recover the smaller operand by subtracting the larger. |
| SOPP `S_ENDPGM` | Stop at the end of the byte stream. The synthetic contract requires explicitly completed transfers and a produced output first (CLAIM-RDNA2-TRANSFER-WAITS). |
+67 -4
View File
@@ -1,7 +1,9 @@
# SOP2 scalar ALU subset
Xenora decodes and executes seventeen gfx1030 SOP2 forms. Each takes 32-bit
operands, writes a normal SGPR (s0-s105) and sets SCC.
Xenora decodes and executes thirty-three gfx1030 SOP2 forms. Each takes 32-bit
operands and writes a normal SGPR (s0-s105). The seventeen below set SCC; the
sixteen in [Arithmetic, select and bit-field forms](#arithmetic-select-and-bit-field-forms)
set it or leave it as the guide says.
| Form | D | SCC |
| --- | --- | --- |
@@ -68,11 +70,11 @@ the registry.
## Not supported
- Every other SOP2 form, including the 64-bit bitwise forms.
- Every other SOP2 form, including the 64-bit bitwise forms and `s_cselect_b64`.
- Destinations other than s0-s105 (VCC, EXEC, TTMP and M0).
- Sources other than normal SGPRs, inline integers and one literal.
- Both sources selecting a literal.
- ADDC or SUBB before SCC is set.
- ADDC, SUBB or CSELECT before SCC is set.
- Writes to the fixture's resource descriptors s0-s7.
## How it runs
@@ -119,6 +121,45 @@ and the aliasing and immediate cases on native Metal with API and shader
validation. `scripts/test-gpu.sh` runs it. This is local evidence from one
Apple M5 Pro; independent acceptance is pending.
## Arithmetic, select and bit-field forms
Sixteen more 32-bit SOP2 forms are declared in the registry with the same
operand rule (`sop2_sgpr`), each one TOML entry over a shared primitive:
| Form | D | SCC |
| --- | --- | --- |
| `s_min_i32`, `s_min_u32` | S0 if S0 < S1 (signed or unsigned), else S1 | S0 < S1 |
| `s_max_i32`, `s_max_u32` | S0 if S0 > S1, else S1 | S0 > S1 |
| `s_cselect_b32` | SCC ? S0 : S1 | read, not written |
| `s_bfm_b32` | ((1 << S0[4:0]) - 1) << S1[4:0] | unchanged |
| `s_mul_i32` | low 32 bits of S0 * S1 | unchanged |
| `s_mul_hi_u32`, `s_mul_hi_i32` | high 32 bits of the unsigned or signed 64-bit product | unchanged |
| `s_bfe_u32` | (S0 >> S1[4:0]) masked to S1[22:16] bits | D != 0 |
| `s_bfe_i32` | (S0 >> S1[4:0], sign fill) masked to S1[22:16] bits, sign-extended from the field's top bit | D != 0 |
| `s_absdiff_i32` | \|S0 - S1\| of the wrapped 32-bit difference (0x80000000 stays) | D != 0 |
| `s_lshl1_add_u32` to `s_lshl4_add_u32` | (S0 << N) + S1, N = 1 to 4 | carry out of the exact sum, counting bits shifted out of S0 |
These follow the guide's 12.1 pseudocode and Tables 11, 12 and 14 (pages
34-36). Min and max compare strictly, so equal operands give S1 and SCC = 0.
The guide leaves two C-like operators open; Xenora reads them as exact
arithmetic: a BFE width of 32 to 127 keeps every shifted bit, and a width of 0
gives 0. These are guide readings, not hardware evidence. CSELECT is refused
when SCC has not been set, as ADDC and SUBB are.
The registry gained the vocabulary for them: the operations above, a
`selected_src0` SCC effect for min and max, `carry_in = "scc"` for the select
condition, and a declared `shift_amount` (1 to 4) for the shift-and-add forms.
The generated `ScalarAluOp::evaluate` now returns `(u32, Option<bool>)`, with
`None` for forms that leave SCC unchanged.
`tests/validation/tests/sop2_arith.rs` checks 21,070 cases, with expected values
derived from the guide (including its ABSDIFF examples) separately from the
registry, on both CPU interpreters and, through the translator, on native
Metal; its 597 rejected programs are checked on the CPU interpreters and the
compiler. `fixtures/rdna2/scalar-arith.s` (LLVM-assembled, expected input ^
0x81157dfe) chains all sixteen, including a min tie and CSELECT on both SCC
values, and shows SCC surviving the forms that do not write it.
## SOPC compares
The twelve 32-bit SOPC integer compares `s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32}`
@@ -137,3 +178,25 @@ and read back from nine distinct generated kernels). Its 348 rejected programs
are checked on both CPU interpreters and against the compiler, which rejects
them before any Metal dispatch. `fixtures/rdna2/scalar-compare.s` (LLVM-assembled, expected input ^
0x00000d5b) records every compare's SCC through an `s_cbranch_scc0` per form.
## SOP1 unary forms
Eleven 32-bit SOP1 forms are declared in the registry (operand rule
`sop1_sgpr`): `s_not_b32`, `s_brev_b32`, `s_bcnt0_i32_b32`, `s_bcnt1_i32_b32`,
`s_ff0_i32_b32`, `s_ff1_i32_b32`, `s_flbit_i32_b32`, `s_flbit_i32`,
`s_sext_i32_i8`, `s_sext_i32_i16` and `s_abs_i32`. Following the guide (section
12.3): a find-first or find-last search that finds nothing returns -1
(0xffffffff); `s_flbit_i32` returns -1 for both 0 and -1; sign extension reads
S0[7:0] or S0[15:0]; `s_abs_i32` of 0x80000000 is 0x80000000. Only NOT, BCNT0,
BCNT1 and ABS write SCC, as D != 0; the other seven leave it unchanged.
`s_mov_b32` stays hand-written, because it also accepts EXEC and VCC halves as
destinations. As for SOP2, destinations s0-s7 are refused when a fixture runs
(they hold its buffer descriptors), and float inline constants are rejected.
`tests/validation/tests/sop1_unary.rs` checks 4,126 cases, with expected values
derived from the guide (including its worked examples) separately from the
registry, on both CPU interpreters and, through the translator, on native
Metal; its 231 rejected programs are checked on the CPU interpreters and the
compiler. `fixtures/rdna2/scalar-unary.s` (LLVM-assembled, expected input ^
0x0f0080f5) chains all eleven and shows SCC surviving the forms that do not
write it.
+6 -4
View File
@@ -24,19 +24,19 @@ acceptance remain outside the verified count. All results concern synthetic fixt
| MUBUF | 75 | 2 | 0 | 2 | 2 | 2 | 2 | 2 | 0 |
| SCRATCH | 22 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| SMEM | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| SOP1 | 65 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
| SOP2 | 51 | 17 | 17 | 17 | 17 | 17 | 0 | 0 | 12 |
| SOP1 | 65 | 12 | 11 | 12 | 12 | 12 | 1 | 1 | 11 |
| SOP2 | 51 | 33 | 33 | 33 | 33 | 33 | 0 | 0 | 12 |
| SOPC | 18 | 12 | 12 | 12 | 12 | 12 | 1 | 1 | 7 |
| SOPK | 27 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
| SOPP | 36 | 6 | 0 | 6 | 6 | 6 | 4 | 4 | 0 |
| VINTRP | 3 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 0 |
| VOP1 | 81 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
| VOP2 | 47 | 8 | 0 | 8 | 8 | 8 | 7 | 7 | 0 |
| VOP2 | 47 | 20 | 12 | 20 | 20 | 20 | 7 | 7 | 7 |
| VOP3 | 416 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
| VOP3P | 29 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| VOP3SDST | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| VOPC | 190 | 12 | 0 | 12 | 12 | 12 | 0 | 0 | 0 |
| **Total** | 1465 | 61 | 29 | 65 | 61 | 61 | 18 | 18 | 19 |
| **Total** | 1465 | 100 | 68 | 104 | 100 | 100 | 18 | 18 | 37 |
## Unsupported operand variants
@@ -44,5 +44,7 @@ The table counts distinct variant names per family across registry operand rules
| Family | Operand rule | Unsupported variants |
| --- | --- | --- |
| SOP1 | `sop1_sgpr` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc`, `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc` |
| SOP2 | `sop2_sgpr` | `dst_exec`, `dst_m0`, `dst_null`, `dst_ttmp`, `dst_vcc`, `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc`, `two_literals` |
| SOPC | `sopc_scalar` | `src_exec`, `src_float_inline`, `src_m0`, `src_special`, `src_ttmp`, `src_vcc`, `two_literals` |
| VOP2 | `vop2_vgpr` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` |
+37 -8
View File
@@ -51,13 +51,16 @@ error.
| `family` | Encoding family; must match the XML base encoding | e.g. `SOP2` |
| `opcode` | Opcode; must match the XML | non-negative integer |
| `variant` | Rust enum variant of the typed operation | CamelCase, e.g. `AddU32` |
| `operation` | The primitive the form uses | `add`, `sub`, `and`, `or`, `xor`, `andn2`, `orn2`, `nand`, `nor`, `xnor`, `lshl`, `lshr`, `ashr` |
| `signedness` | How operands are read | `unsigned`, `signed`, `bitwise` (always `bitwise` for the logical operations, never for `add` and `sub`; shifts take their primitive's signedness) |
| `carry_in` | Whether the form reads SCC as carry-in or borrow-in | `none`, `scc` (`scc` only for unsigned `add` and `sub`) |
| `operation` | The primitive the form uses | `add`, `sub`, `and`, `or`, `xor`, `andn2`, `orn2`, `nand`, `nor`, `xnor`, `lshl`, `lshr`, `ashr`, `min`, `max`, `cselect`, `bfm`, `mul`, `mul_hi`, `bfe`, `absdiff`, `lshl_add`, `mul24`, `mul_hi24` (vector only), `compare` and the SOP1 unaries |
| `signedness` | How operands are read | `unsigned`, `signed`, `bitwise` (always `bitwise` for the logical operations, `cselect` and `bfm`; never for the arithmetic ones, `add`, `sub`, `min`, `max`, `mul`, `mul_hi`, `bfe`, `absdiff` and `lshl_add`; shifts take their primitive's signedness) |
| `carry_in` | Whether the form reads SCC: carry-in, borrow-in or the select condition | `none`, `scc` (`scc` only for unsigned `add` and `sub`, and required for `cselect`) |
| `width` | Operand and result width in bits | `32` |
| `source_bits` | Sign extension only: the low bits of S0 that are read. The XML must list S0 with that size and format (`FMT_NUM_I8` or `FMT_NUM_I16`) | `8`, `16`; required for `sext`, rejected elsewhere |
| `relation` | Compares only: the relation tested with S0 on the left | `eq`, `lg` (not equal), `gt`, `ge`, `lt`, `le`; required for `compare`, rejected elsewhere |
| `source_order` | Vector forms only: `reversed` when the guide computes `op(S1, S0)` (the XML records no operand order); absent otherwise | `reversed` |
| `shift_amount` | `lshl_add` only: the fixed left shift of S0 before the add | `1` to `4`; required for `lshl_add`, rejected elsewhere |
| `shift_count_bits` | Shifts only: the low bits of S1 used as the count. The generator masks S1 with it, and the XML must list S1 as unsigned | `5` (log2 of `width`); required for shifts, rejected elsewhere |
| `scc` | What the form writes to SCC | `carry_out`, `borrow`, `signed_overflow`, `nonzero`, `relation` (compares only), `unchanged` |
| `scc` | What the form writes to SCC | `carry_out`, `borrow`, `signed_overflow`, `nonzero`, `relation` (compares only), `selected_src0` (min and max: S0 won the strict compare, so a tie gives 0), `unchanged` |
| `vcc`, `exec` | Effect on VCC and EXEC, stated rather than implied | `unchanged` |
| `wave` | Wave sizes the form is valid in | `any` (`wave32` is in the vocabulary but rejected until the decoder can enforce it) |
| `operands` | Name of an `[operand_rules]` entry for the same family | e.g. `sop2_sgpr` |
@@ -77,10 +80,35 @@ fixes the `scc` value:
| `lshl` / `bitwise` | `nonzero` | `lshl_nonzero_b32` | no |
| `lshr` / `unsigned` | `nonzero` | `lshr_nonzero_b32` | no |
| `ashr` / `signed` | `nonzero` | `ashr_nonzero_i32` | no |
| `not`, `bcnt0`, `bcnt1` / `bitwise` | `nonzero` | `not_nonzero_b32`, `bcnt0_nonzero_b32`, `bcnt1_nonzero_b32` | no |
| `brev`, `ff0`, `ff1`, `flbit` / `bitwise` | `unchanged` | `brev_b32`, `ff0_b32`, `ff1_b32`, `flbit_b32` | no |
| `flbit`, `sext` / `signed` | `unchanged` | `flbit_i32`, `sext_i32` | no |
| `abs` / `signed` | `nonzero` | `abs_nonzero_i32` | no |
| `min`, `max` / `signed` or `unsigned` | `selected_src0` | `min_i32`/`min_u32`, `max_i32`/`max_u32` | no |
| `cselect` / `bitwise` | `unchanged` | `cselect_b32` | required |
| `bfm` / `bitwise` | `unchanged` | `bfm_b32` | no |
| `mul` / `signed` | `unchanged` | `mul_lo_i32` | no |
| `mul_hi` / `unsigned` or `signed` | `unchanged` | `mul_hi_u32`, `mul_hi_i32` | no |
| `bfe` / `unsigned` or `signed` | `nonzero` | `bfe_nonzero_u32`, `bfe_nonzero_i32` | no |
| `absdiff` / `signed` | `nonzero` | `absdiff_nonzero_i32` | no |
| `lshl_add` / `unsigned` | `carry_out` | `lshl_add_carry_u32` (with `shift_amount`) | no |
| `compare` / `signed` or `unsigned` | `relation` | `eq_b32`, `ne_b32` (for both signednesses), `gt_i32`/`gt_u32`, `ge_*`, `lt_*`, `le_*` | no |
Vector forms (operand rule `vop2_vgpr`, kind `vector`) use a separate table:
the pair picks the per-lane `VectorBinary` the MSL lowering uses, and `scc`
must be `unchanged` (VOP2 integer forms write no SCC, VCC or EXEC):
| `operation` / `signedness` | `VectorBinary` |
| --- | --- |
| `add` / `unsigned`, `sub` / `unsigned` | `Add`, `Sub` |
| `xnor` / `bitwise` | `Xnor` |
| `min`, `max` / `signed` or `unsigned` | `MinSigned`, `MinUnsigned`, `MaxSigned`, `MaxUnsigned` |
| `mul24`, `mul_hi24` / `signed` or `unsigned` | `Mul24Signed`, `Mul24Unsigned`, `MulHi24Signed`, `MulHi24Unsigned` |
A compare must use an operand rule of the compare kind (`sopc_scalar`: two
sources, no destination), and an ALU operation must not.
sources, no destination), a unary operation one of the unary kind (`sop1_sgpr`:
one source and an SGPR destination), and a two-source ALU operation
`sop2_sgpr`.
Behaviour is chosen only from these declared fields, never from the mnemonic.
@@ -91,12 +119,13 @@ vocabularies above, it rejects:
- contradictions: a declared `scc` or `carry_in` that the primitive does not
have, `bitwise` on an arithmetic operation or the reverse;
- duplicates: the same `name`, the same `(family, opcode)` or the same
`variant` declared twice;
- duplicates: the same `name`, the same `(family, opcode)`, or the same
`variant` twice in one generated enum;
- XML disagreements: a family with no XML encoding, a form with no default XML
variant, a different opcode, an SCC input or output the XML does not show (or
that the declaration omits), an operand width other than `width`, a signed
declaration on unsigned XML formats or the reverse, an operand direction that
declaration on unsigned XML formats or the reverse (a shift count or the `bfe`
field descriptor in S1 must be `FMT_NUM_U32` whatever the signedness), an operand direction that
differs, and XML operands the operand rule does not cover;
- references: a spec citing an undeclared document, a bad section or page, or
no guide page at all;
+4 -1
View File
@@ -127,8 +127,11 @@ While VCC_LO is lane-derived it may be read only by:
lanes (inactive lanes keep vD, as for any partial-EXEC move);
3. SRC0 of a supported compare (`v_cmp_* vcc_lo, vcc_lo, vN`), which reads the
old VCC_LO in every active lane before the new value is written.
4. SRC0 of a registry VOP2 integer form (for example
`v_add_nc_u32_e32 vD, vcc_lo, vN`), which reads the 32-bit mask in every
active lane, as `v_mov_b32_e32` does.
`v_mov_b32_e32 vD, vcc_lo` follows the usual EXEC rules: with EXEC_LO = 0 it
`v_mov_b32_e32 vD, vcc_lo` and the VOP2 forms follow the usual EXEC rules: with EXEC_LO = 0 it
is skipped without reading VCC; otherwise VCC_LO must be known or
lane-derived. Every other read of vcc_lo is rejected in any state: the
supported scalar instructions (`s_mov_b32`, SOP2, `s_cmp_eq_u32`) do not
+468
View File
@@ -135,6 +135,138 @@ recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_not_b32"
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = ~S0; SCC = D != 0"
representation = "`BE890708`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_brev_b32"
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0 bit-reversed; SCC unchanged"
representation = "`BE8A0B08`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_bcnt0_i32_b32"
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = count of zero bits; SCC = D != 0"
representation = "`BE8C0D08`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_bcnt1_i32_b32"
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = count of one bits; SCC = D != 0"
representation = "`BE8B0F08`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_ff0_i32_b32"
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = index of the lowest zero bit, or -1; SCC unchanged"
representation = "`BE8E11FF 0000FFFF`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_ff1_i32_b32"
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = index of the lowest one bit, or -1; SCC unchanged"
representation = "`BE8D13FF 00400000`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_flbit_i32_b32"
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = zeros above the highest one bit, or -1; SCC unchanged"
representation = "`BE8F1508`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_flbit_i32"
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = bits above the highest bit differing from the sign, or -1; SCC unchanged"
representation = "`BE9017FF FFF00000`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_sext_i32_i8"
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0[7:0] sign-extended; SCC unchanged"
representation = "`BE911908`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_sext_i32_i16"
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = S0[15:0] sign-extended; SCC unchanged"
representation = "`BE921AFF 00018000`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_abs_i32"
encoding = "SOP1, normal SGPR destination; normal SGPR, inline integer or literal source; D = |S0| (0x80000000 stays); SCC = D != 0"
representation = "`BE933412`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_cmp_eq_u32"
encoding = "Normal SGPR or integer operands, with at most one source selecting a literal"
@@ -483,6 +615,198 @@ recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_min_i32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 < S1 (signed) else S1; SCC = S0 < S1"
representation = "`830A0908`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_min_u32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 < S1 (unsigned) else S1; SCC = S0 < S1"
representation = "`83988509`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_max_i32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 > S1 (signed) else S1; SCC = S0 > S1"
representation = "`84170908`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_max_u32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 if S0 > S1 (unsigned) else S1; SCC = S0 > S1"
representation = "`848C0908`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_cselect_b32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = SCC ? S0 : S1; reads SCC, SCC unchanged"
representation = "`850B0809`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_bfm_b32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = ((1 << S0[4:0]) - 1) << S1[4:0]; SCC unchanged"
representation = "`920D848C`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_mul_i32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = low 32 bits of S0 * S1; SCC unchanged"
representation = "`930F0908`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_bfe_u32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0] masked to S1[22:16] bits; SCC = D != 0"
representation = "`9390FF08 00080004`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_bfe_i32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = S0 >> S1[4:0] (sign fill) masked to S1[22:16] bits, sign-extended; SCC = D != 0"
representation = "`9411FF08 00080004`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_absdiff_i32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = |S0 - S1| of the 32-bit difference (0x80000000 stays); SCC = D != 0"
representation = "`96120809`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_lshl1_add_u32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 1) + S1; SCC = carry out of the exact sum"
representation = "`970E0908`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_lshl2_add_u32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 2) + S1; SCC = carry out of the exact sum"
representation = "`97990909`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_lshl3_add_u32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 3) + S1; SCC = carry out of the exact sum"
representation = "`98130808`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_lshl4_add_u32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = (S0 << 4) + S1; SCC = carry out of the exact sum"
representation = "`9894D009`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_mul_hi_u32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = high 32 bits of the unsigned product; SCC unchanged"
representation = "`9A950808`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "s_mul_hi_i32"
encoding = "SOP2, normal SGPR destination; normal SGPR, inline integer or literal sources with at most one literal; D = high 32 bits of the signed product; SCC unchanged"
representation = "`9B160808`"
lowering = "resolved scalar state and SCC"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_lt_i32_e32"
encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (signed S0 < S1), fully written"
@@ -770,6 +1094,150 @@ recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_mul_i32_i24_e32"
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = low 32 bits of sext(S0[23:0]) * sext(S1[23:0])"
representation = "`120402C3`"
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_mul_hi_i32_i24_e32"
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = bits 63:32 of sext(S0[23:0]) * sext(S1[23:0])"
representation = "`14060208`"
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_mul_u32_u24_e32"
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = low 32 bits of S0[23:0] * S1[23:0]"
representation = "`160802FF 00123456`"
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_mul_hi_u32_u24_e32"
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = bits 63:32 of S0[23:0] * S1[23:0]"
representation = "`180A0208`"
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_min_i32_e32"
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = signed min(S0, S1)"
representation = "`220C0501`"
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_max_i32_e32"
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = signed max(S0, S1)"
representation = "`240E0285`"
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_min_u32_e32"
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = unsigned min(S0, S1)"
representation = "`26100303`"
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_max_u32_e32"
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = unsigned max(S0, S1)"
representation = "`28120208`"
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_xnor_b32_e32"
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = ~(S0 ^ S1)"
representation = "`3C140B04`"
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_add_nc_u32_e32"
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = S0 + S1, no carry"
representation = "`4A160F06`"
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_sub_nc_u32_e32"
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = S0 - S1, no carry"
representation = "`4C181308`"
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_subrev_nc_u32_e32"
encoding = "VOP2, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1 and VDST; inactive lanes keep VDST; D = S1 - S0, no carry"
representation = "`4E1A170A`"
lowering = "per-thread typed integer template over the lane's own VGPRs; partial EXEC as a lane merge"
reference = "implemented"
cpu = "local known-answer test passed"
gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[guest_milestones]
X1 = "accepted"
X2 = "accepted"
+48
View File
@@ -0,0 +1,48 @@
# Infrastructure QA tooling
Standalone helpers under `scripts/qa/` and `scripts/release/`. They do not replace
`scripts/audit/*`, `scripts/benchmark.sh` or `scripts/test-gpu.sh`. New checks are
advisory until reviewed.
## Suites
| Path | Role |
| --- | --- |
| `scripts/qa/exit_pipe.py` | Preserve command exit status |
| `scripts/qa/orchestrate.py` | Structured multi-suite runs and failure excerpts |
| `scripts/qa/pr_validate.py` | Advisory PR scope, DCO, artifact and evidence checks |
| `scripts/qa/bench_stats.py` | Median/percentile analysis of existing samples |
| `scripts/qa/regression.py` | Compare historical orchestration JSON reports |
| `scripts/qa/env_check.py` | Host, toolchain and branch diagnostics |
| `scripts/qa/claim_conflict.py` | Read-only file-scope conflict prediction |
| `scripts/release/macho.py` | ARM64 arch and forbidden-linkage checks |
| `scripts/release/bundle.py` | App bundle layout and codesign diagnosis |
| `scripts/release/manifest.py` | Checksums, manifests, license inventory |
## Tests
```sh
PYTHONPATH=scripts python3 -m unittest discover -s tests/qa
PYTHONPATH=scripts python3 -m unittest discover -s tests/release
```
## Phase II CLIs
```sh
PYTHONPATH=scripts python3 -m qa rdna2 inventory --compact
PYTHONPATH=scripts python3 -m qa rdna2 candidates --family SOP2 --status reuse-primitives --limit 50
PYTHONPATH=scripts python3 -m qa rdna2 plan --limit 20 --compact
PYTHONPATH=scripts python3 -m qa rdna2 manifests --status reuse-primitives --limit 10 --claims claims.json
PYTHONPATH=scripts python3 -m qa rdna2 reconcile --compact
PYTHONPATH=scripts python3 -m qa rdna2 discrepancies
PYTHONPATH=scripts python3 -m qa rdna2 diff --before before.json --after after.json --compact
PYTHONPATH=scripts python3 -m qa verify quick
PYTHONPATH=scripts python3 -m qa cpu-coverage --blockers
PYTHONPATH=scripts python3 -m qa bench-compare --baseline b.json --current c.json
PYTHONPATH=scripts python3 -m release readiness --revision HEAD --live --binary path --app path.app
```
RDNA2 planning is read-only over the AMD snapshot, semantic registry, decoder tables and
`docs/status.toml`. Candidates and manifests are never counted as implemented forms.
Family claims exclude those families; path-only claims block candidates whose default
permitted files overlap. Reconcile reports mismatches without adjusting planner counts.
+39
View File
@@ -0,0 +1,39 @@
0000: t0 = load.u32 input[index]
0068: branch.uniform 0x0074 taken=true
0074: t2 = const.u32 0x89abcdef
0078: t3 = const.u32 0x00000005
007c: t4 = xor.b32 t2, t3
0080: t5 = const.u32 0x89abcdef
0084: t6 = xor.b32 t4, t5
0088: t7 = const.u32 0x0000fff0
008c: t8 = xor.b32 t6, t7
0090: t9 = const.u32 0x13579be3
0094: t10 = xor.b32 t8, t9
0098: t11 = const.u32 0xb05b05ab
009c: t12 = xor.b32 t10, t11
00a0: t13 = const.u32 0x000000de
00a4: t14 = xor.b32 t12, t13
00a8: t15 = const.u32 0xffffffde
00ac: t16 = xor.b32 t14, t15
00b0: t17 = const.u32 0x76543216
00b4: t18 = xor.b32 t16, t17
00b8: t19 = const.u32 0xd70a3d67
00bc: t20 = xor.b32 t18, t19
00c0: t21 = const.u32 0x00000040
00c4: t22 = xor.b32 t20, t21
00c8: t23 = const.u32 0x4a0955b6
00cc: t24 = xor.b32 t22, t23
00d0: t25 = const.u32 0x36b1b9d8
00d4: t26 = xor.b32 t24, t25
00d8: t27 = const.u32 0x00000005
00dc: t28 = xor.b32 t26, t27
00e0: t29 = const.u32 0x00000005
00e4: t30 = xor.b32 t28, t29
00e8: t31 = const.u32 0x00000019
00ec: t32 = xor.b32 t30, t31
00f0: t33 = const.u32 0x00000005
00f4: t34 = xor.b32 t32, t33
00f8: t35 = const.u32 0x00000000
00fc: t36 = xor.b32 t34, t35
0100: t37 = xor.b32 t0, t36
0104: store.u32 output[index], t37
+45
View File
@@ -0,0 +1,45 @@
#include <metal_stdlib>
using namespace metal;
kernel void xenora_compute(
device const uint* input [[buffer(0)]],
device uint* output [[buffer(1)]],
uint index [[thread_position_in_grid]]) {
uint t0 = input[index];
uint t2 = 0x89abcdefu;
uint t3 = 0x00000005u;
uint t4 = t2 ^ t3;
uint t5 = 0x89abcdefu;
uint t6 = t4 ^ t5;
uint t7 = 0x0000fff0u;
uint t8 = t6 ^ t7;
uint t9 = 0x13579be3u;
uint t10 = t8 ^ t9;
uint t11 = 0xb05b05abu;
uint t12 = t10 ^ t11;
uint t13 = 0x000000deu;
uint t14 = t12 ^ t13;
uint t15 = 0xffffffdeu;
uint t16 = t14 ^ t15;
uint t17 = 0x76543216u;
uint t18 = t16 ^ t17;
uint t19 = 0xd70a3d67u;
uint t20 = t18 ^ t19;
uint t21 = 0x00000040u;
uint t22 = t20 ^ t21;
uint t23 = 0x4a0955b6u;
uint t24 = t22 ^ t23;
uint t25 = 0x36b1b9d8u;
uint t26 = t24 ^ t25;
uint t27 = 0x00000005u;
uint t28 = t26 ^ t27;
uint t29 = 0x00000005u;
uint t30 = t28 ^ t29;
uint t31 = 0x00000019u;
uint t32 = t30 ^ t31;
uint t33 = 0x00000005u;
uint t34 = t32 ^ t33;
uint t35 = 0x00000000u;
uint t36 = t34 ^ t35;
uint t37 = t0 ^ t36;
output[index] = t37;
}
+29
View File
@@ -0,0 +1,29 @@
0000: t0 = load.u32 input[index]
0060: branch.uniform 0x006c taken=true
006c: t2 = const.u32 0xffffff0f
0070: t3 = const.u32 0x0f000000
0074: t4 = xor.b32 t2, t3
0078: t5 = const.u32 0x00000004
007c: t6 = xor.b32 t4, t5
0080: t7 = const.u32 0x0000001c
0084: t8 = xor.b32 t6, t7
0088: t9 = const.u32 0x00000016
008c: t10 = xor.b32 t8, t9
0090: t11 = const.u32 0x00000010
0094: t12 = xor.b32 t10, t11
0098: t13 = const.u32 0x00000018
009c: t14 = xor.b32 t12, t13
00a0: t15 = const.u32 0x0000000c
00a4: t16 = xor.b32 t14, t15
00a8: t17 = const.u32 0xfffffff0
00ac: t18 = xor.b32 t16, t17
00b0: t19 = const.u32 0xffff8000
00b4: t20 = xor.b32 t18, t19
00b8: t21 = const.u32 0x00008000
00bc: t22 = xor.b32 t20, t21
00c0: t23 = const.u32 0x00007fff
00c4: t24 = xor.b32 t22, t23
00c8: t25 = const.u32 0xffffffff
00cc: t26 = xor.b32 t24, t25
00d0: t27 = xor.b32 t0, t26
00d4: store.u32 output[index], t27
+35
View File
@@ -0,0 +1,35 @@
#include <metal_stdlib>
using namespace metal;
kernel void xenora_compute(
device const uint* input [[buffer(0)]],
device uint* output [[buffer(1)]],
uint index [[thread_position_in_grid]]) {
uint t0 = input[index];
uint t2 = 0xffffff0fu;
uint t3 = 0x0f000000u;
uint t4 = t2 ^ t3;
uint t5 = 0x00000004u;
uint t6 = t4 ^ t5;
uint t7 = 0x0000001cu;
uint t8 = t6 ^ t7;
uint t9 = 0x00000016u;
uint t10 = t8 ^ t9;
uint t11 = 0x00000010u;
uint t12 = t10 ^ t11;
uint t13 = 0x00000018u;
uint t14 = t12 ^ t13;
uint t15 = 0x0000000cu;
uint t16 = t14 ^ t15;
uint t17 = 0xfffffff0u;
uint t18 = t16 ^ t17;
uint t19 = 0xffff8000u;
uint t20 = t18 ^ t19;
uint t21 = 0x00008000u;
uint t22 = t20 ^ t21;
uint t23 = 0x00007fffu;
uint t24 = t22 ^ t23;
uint t25 = 0xffffffffu;
uint t26 = t24 ^ t25;
uint t27 = t0 ^ t26;
output[index] = t27;
}
+31
View File
@@ -0,0 +1,31 @@
0000: t0 = load.u32 input[index]
0014: t1 = const.u32 0xfffffffd
0014: t2 = mul24.i32 t1, t0
0018: t3 = const.u32 0x00800001
0018: t4 = mulhi24.i32 t3, t0
001c: t5 = const.u32 0x00123456
001c: t6 = mul24.u32 t5, t0
0024: t7 = const.u32 0x00800001
0024: t8 = mulhi24.u32 t7, t0
0028: t9 = min.i32 t0, t2
002c: t10 = const.u32 0x00000005
002c: t11 = max.i32 t10, t0
0030: t12 = min.u32 t4, t0
0034: t13 = const.u32 0x00800001
0034: t14 = max.u32 t13, t0
0038: t15 = xnor.b32 t6, t8
003c: t16 = add.u32 t9, t11
0040: t17 = sub.u32 t12, t14
0044: t18 = sub.u32 t16, t15
0048: t19 = xor.b32 t2, t4
004c: t20 = xor.b32 t6, t19
0050: t21 = xor.b32 t8, t20
0054: t22 = xor.b32 t9, t21
0058: t23 = xor.b32 t11, t22
005c: t24 = xor.b32 t12, t23
0060: t25 = xor.b32 t14, t24
0064: t26 = xor.b32 t15, t25
0068: t27 = xor.b32 t16, t26
006c: t28 = xor.b32 t17, t27
0070: t29 = xor.b32 t18, t28
0074: store.u32 output[index], t29
+38
View File
@@ -0,0 +1,38 @@
#include <metal_stdlib>
using namespace metal;
kernel void xenora_compute(
device const uint* input [[buffer(0)]],
device uint* output [[buffer(1)]],
uint index [[thread_position_in_grid]]) {
uint t0 = input[index];
uint t1 = 0xfffffffdu;
uint t2 = as_type<uint>((as_type<int>(t1 << 8u) >> 8)) * as_type<uint>((as_type<int>(t0 << 8u) >> 8));
uint t3 = 0x00800001u;
uint t4 = as_type<uint>(mulhi((as_type<int>(t3 << 8u) >> 8), (as_type<int>(t0 << 8u) >> 8)));
uint t5 = 0x00123456u;
uint t6 = (t5 & 0x00ffffffu) * (t0 & 0x00ffffffu);
uint t7 = 0x00800001u;
uint t8 = mulhi((t7 & 0x00ffffffu), (t0 & 0x00ffffffu));
uint t9 = as_type<uint>(min(as_type<int>(t0), as_type<int>(t2)));
uint t10 = 0x00000005u;
uint t11 = as_type<uint>(max(as_type<int>(t10), as_type<int>(t0)));
uint t12 = min(t4, t0);
uint t13 = 0x00800001u;
uint t14 = max(t13, t0);
uint t15 = ~(t6 ^ t8);
uint t16 = t9 + t11;
uint t17 = t12 - t14;
uint t18 = t16 - t15;
uint t19 = t2 ^ t4;
uint t20 = t6 ^ t19;
uint t21 = t8 ^ t20;
uint t22 = t9 ^ t21;
uint t23 = t11 ^ t22;
uint t24 = t12 ^ t23;
uint t25 = t14 ^ t24;
uint t26 = t15 ^ t25;
uint t27 = t16 ^ t26;
uint t28 = t17 ^ t27;
uint t29 = t18 ^ t28;
output[index] = t29;
}
Binary file not shown.
+69
View File
@@ -0,0 +1,69 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Generate the original PE32+ frame-loop fixture without an x86 toolchain.
The guest calls xenora.dll!frame_submit(index) with index = 0, 1, 2, ... and
stops when the import returns 0, then halts. Frame order is guest state (RBX).
"""
import argparse
from pathlib import Path
from struct import pack, pack_into
def fixture():
base = 0x140000000
entry, imports = 0x1000, 0x2000
iat, lookup, module, symbol = (imports + x for x in (0x40, 0x50, 0x60, 0x80))
data = bytearray(0x800)
data[:2] = b"MZ"
pack_into("<I", data, 0x3C, 0x80)
data[0x80:0x84] = b"PE\0\0"
pack_into("<HHIIIHH", data, 0x84, 0x8664, 2, 0, 0, 0, 240, 0x22)
opt = 0x98
pack_into("<H", data, opt, 0x20B)
pack_into("<III", data, opt + 4, 0x200, 0x200, 0)
pack_into("<IIQII", data, opt + 16, entry, entry, base, 0x1000, 0x200)
pack_into("<II", data, opt + 56, 0x3000, 0x400)
pack_into("<HH", data, opt + 68, 3, 0x160)
pack_into("<QQQQII", data, opt + 72, 0x10000, 0x1000, 0x10000, 0x1000, 0, 16)
for index, rva, size in ((1, imports, 40), (12, iat, 16)):
pack_into("<II", data, opt + 112 + index * 8, rva, size)
for index, (name, rva, permissions) in enumerate(
((b".text", entry, 0x60000020), (b".rdata", imports, 0x40000040))
):
pack_into(
"<8sIIIIIIHHI", data, opt + 240 + 40 * index, name, 0x200, rva,
0x200, 0x400 + 0x200 * index, 0, 0, 0, 0, permissions,
)
loop = entry + 6
code = b"\x48\x83\xec\x28" # sub rsp, 0x28 (Win64 home area)
code += b"\x31\xdb" # xor ebx, ebx (frame index)
code += b"\x48\x89\xd9" # loop: mov rcx, rbx
code += b"\xff\x15" + pack("<i", iat - (loop + 9)) # call [rip -> IAT]
code += b"\x48\xff\xc3" # inc rbx
code += b"\x48\x85\xc0" # test rax, rax
code += b"\x75" + pack("<b", loop - (loop + 17)) # jnz loop
code += b"\x48\x83\xc4\x28\xf4" # add rsp, 0x28; hlt
data[0x400:0x400 + len(code)] = code
pack_into("<IIIII", data, 0x600, lookup, 0, 0, module, iat)
pack_into("<Q", data, 0x640, symbol)
pack_into("<Q", data, 0x650, symbol)
data[0x660:0x66B] = b"xenora.dll\0"
data[0x682:0x68E] = b"frame_submit"
return data
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true")
args = parser.parse_args()
path = Path(__file__).with_suffix(".exe")
if args.check:
if path.read_bytes() != fixture():
parser.exit(1, f"fixture bytes differ from generator: {path}\n")
else:
path.write_bytes(fixture())
Binary file not shown.
+100
View File
@@ -0,0 +1,100 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Generate the original PE32+ interactive fixture without an x86 toolchain.
The guest polls host input via xenora.dll!input_poll() and updates its
internal position:
- input 1 (Right): column = (column + 1) % 4
- input 2 (Left): column = (column - 1) % 4
- other: column stays unchanged
The guest then calls xenora.dll!frame_submit(column) and stops when the
import returns 0, then halts.
"""
import argparse
from pathlib import Path
from struct import pack, pack_into
def fixture():
base = 0x140000000
entry, imports = 0x1000, 0x2000
lookup = imports + 0x30
iat = imports + 0x50
module = imports + 0x70
sym_poll = imports + 0x80
sym_submit = imports + 0x90
data = bytearray(0x800)
data[:2] = b"MZ"
pack_into("<I", data, 0x3C, 0x80)
data[0x80:0x84] = b"PE\0\0"
pack_into("<HHIIIHH", data, 0x84, 0x8664, 2, 0, 0, 0, 240, 0x22)
opt = 0x98
pack_into("<H", data, opt, 0x20B)
pack_into("<III", data, opt + 4, 0x200, 0x200, 0)
pack_into("<IIQII", data, opt + 16, entry, entry, base, 0x1000, 0x200)
pack_into("<II", data, opt + 56, 0x3000, 0x400)
pack_into("<HH", data, opt + 68, 3, 0x160)
pack_into("<QQQQII", data, opt + 72, 0x10000, 0x1000, 0x10000, 0x1000, 0, 16)
for index, rva, size in ((1, imports, 40), (12, iat, 24)):
pack_into("<II", data, opt + 112 + index * 8, rva, size)
for index, (name, rva, permissions) in enumerate(
((b".text", entry, 0x60000020), (b".rdata", imports, 0x40000040))
):
pack_into(
"<8sIIIIIIHHI", data, opt + 240 + 40 * index, name, 0x200, rva,
0x200, 0x400 + 0x200 * index, 0, 0, 0, 0, permissions,
)
code = bytearray()
code += b"\x48\x83\xec\x28" # sub rsp, 0x28
code += b"\x48\x31\xdb" # xor rbx, rbx (column: 0)
loop_start = entry + len(code)
# call [rip -> iat[0]: input_poll]
code += b"\xff\x15" + pack("<i", iat - (entry + len(code) + 6))
# cmp rax, 1; jne not_right; add rbx, 1
code += b"\x48\x83\xf8\x01\x75\x04\x48\x83\xc3\x01"
# cmp rax, 2; jne not_left; sub rbx, 1
code += b"\x48\x83\xf8\x02\x75\x04\x48\x83\xeb\x01"
# wrap check: cmp rbx, 4; jl check_min; sub rbx, 4
code += b"\x48\x83\xfb\x04\x7c\x04\x48\x83\xeb\x04"
# check_min: cmp rbx, 0; jge do_submit; add rbx, 4
code += b"\x48\x83\xfb\x00\x7d\x04\x48\x83\xc3\x04"
# do_submit:
code += b"\x48\x89\xd9" # mov rcx, rbx
# call [rip -> iat[1]: frame_submit]
code += b"\xff\x15" + pack("<i", (iat + 8) - (entry + len(code) + 6))
code += b"\x48\x85\xc0" # test rax, rax
rel_loop = loop_start - (entry + len(code) + 2)
code += b"\x75" + pack("<b", rel_loop)
code += b"\x48\x83\xc4\x28" # add rsp, 0x28
code += b"\xf4" # hlt
data[0x400:0x400 + len(code)] = code
pack_into("<IIIII", data, 0x600, lookup, 0, 0, module, iat)
pack_into("<QQ", data, 0x600 + (lookup - imports), sym_poll, sym_submit)
pack_into("<QQ", data, 0x600 + (iat - imports), sym_poll, sym_submit)
data[0x600 + (module - imports):0x600 + (module - imports) + 11] = b"xenora.dll\0"
data[0x600 + (sym_poll - imports) + 2:0x600 + (sym_poll - imports) + 2 + 10] = b"input_poll"
data[0x600 + (sym_submit - imports) + 2:0x600 + (sym_submit - imports) + 2 + 12] = b"frame_submit"
return data
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true")
args = parser.parse_args()
path = Path(__file__).with_suffix(".exe")
if args.check:
if path.read_bytes() != fixture():
parser.exit(1, f"fixture bytes differ from generator: {path}\n")
else:
path.write_bytes(fixture())
Binary file not shown.
+114
View File
@@ -0,0 +1,114 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Generate the original PE32+ persistent texture fixture without an x86 toolchain.
The guest demonstrates persistent GPU resource ownership, dynamic texture updates,
and completion-aware resource retirement through runtime services:
1. Calls xenora.dll!texture_create(2, 2) to allocate a persistent 2x2 texture.
2. Calls xenora.dll!frame_submit_textured(handle) to render frame 0 with initial contents.
3. Calls xenora.dll!texture_update(handle, 0, 0, 2, 2) to dynamically update texture pixels.
4. Calls xenora.dll!frame_submit_textured(handle) to render frame 1 with updated contents.
5. Calls xenora.dll!texture_destroy(handle) to retire the resource.
6. Halts cleanly.
"""
import argparse
from pathlib import Path
from struct import pack, pack_into
def fixture():
base = 0x140000000
entry, imports = 0x1000, 0x2000
lookup = imports + 0x30
iat = imports + 0x60
module = imports + 0x90
sym_create = imports + 0xA0
sym_update = imports + 0xC0
sym_submit = imports + 0xE0
sym_destroy = imports + 0x100
data = bytearray(0x800)
data[:2] = b"MZ"
pack_into("<I", data, 0x3C, 0x80)
data[0x80:0x84] = b"PE\0\0"
pack_into("<HHIIIHH", data, 0x84, 0x8664, 2, 0, 0, 0, 240, 0x22)
opt = 0x98
pack_into("<H", data, opt, 0x20B)
pack_into("<III", data, opt + 4, 0x200, 0x200, 0)
pack_into("<IIQII", data, opt + 16, entry, entry, base, 0x1000, 0x200)
pack_into("<II", data, opt + 56, 0x3000, 0x400)
pack_into("<HH", data, opt + 68, 3, 0x160)
pack_into("<QQQQII", data, opt + 72, 0x10000, 0x1000, 0x10000, 0x1000, 0, 16)
for index, rva, size in ((1, imports, 40), (12, iat, 40)):
pack_into("<II", data, opt + 112 + index * 8, rva, size)
for index, (name, rva, permissions) in enumerate(
((b".text", entry, 0x60000020), (b".rdata", imports, 0x40000040))
):
pack_into(
"<8sIIIIIIHHI", data, opt + 240 + 40 * index, name, 0x200, rva,
0x200, 0x400 + 0x200 * index, 0, 0, 0, 0, permissions,
)
code = bytearray()
code += b"\x48\x83\xec\x28" # sub rsp, 0x28 (Win64 home area)
# 1. texture_create(2, 2)
code += b"\x48\xc7\xc1\x02\x00\x00\x00" # mov rcx, 2
code += b"\x48\xc7\xc2\x02\x00\x00\x00" # mov rdx, 2
# call [rip -> iat[0]: texture_create]
code += b"\xff\x15" + pack("<i", iat - (entry + len(code) + 6))
code += b"\x48\x89\xc3" # mov rbx, rax (save handle)
# 2. frame_submit_textured(handle)
code += b"\x48\x89\xd9" # mov rcx, rbx
# call [rip -> iat[2]: frame_submit_textured]
code += b"\xff\x15" + pack("<i", (iat + 16) - (entry + len(code) + 6))
# 3. texture_update(handle, 0, 0, 2, 2)
code += b"\x48\x89\xd9" # mov rcx, rbx
code += b"\x48\x31\xd2" # xor rdx, rdx (x=0)
code += b"\x49\xc7\xc0\x00\x00\x00\x00" # mov r8, 0 (y=0)
code += b"\x49\xc7\xc1\x02\x00\x00\x00" # mov r9, 2 (w=2)
# call [rip -> iat[1]: texture_update]
code += b"\xff\x15" + pack("<i", (iat + 8) - (entry + len(code) + 6))
# 4. frame_submit_textured(handle)
code += b"\x48\x89\xd9" # mov rcx, rbx
# call [rip -> iat[2]: frame_submit_textured]
code += b"\xff\x15" + pack("<i", (iat + 16) - (entry + len(code) + 6))
# 5. texture_destroy(handle)
code += b"\x48\x89\xd9" # mov rcx, rbx
# call [rip -> iat[3]: texture_destroy]
code += b"\xff\x15" + pack("<i", (iat + 24) - (entry + len(code) + 6))
code += b"\x48\x83\xc4\x28" # add rsp, 0x28
code += b"\xf4" # hlt
data[0x400:0x400 + len(code)] = code
# Import directory table
pack_into("<IIIII", data, 0x600, lookup, 0, 0, module, iat)
# Lookups & IAT
for off in (lookup - imports, iat - imports):
pack_into("<QQQQ", data, 0x600 + off, sym_create, sym_update, sym_submit, sym_destroy)
data[0x600 + (module - imports):0x600 + (module - imports) + 11] = b"xenora.dll\0"
data[0x600 + (sym_create - imports) + 2:0x600 + (sym_create - imports) + 2 + 14] = b"texture_create"
data[0x600 + (sym_update - imports) + 2:0x600 + (sym_update - imports) + 2 + 14] = b"texture_update"
data[0x600 + (sym_submit - imports) + 2:0x600 + (sym_submit - imports) + 2 + 21] = b"frame_submit_textured"
data[0x600 + (sym_destroy - imports) + 2:0x600 + (sym_destroy - imports) + 2 + 15] = b"texture_destroy"
return data
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true")
args = parser.parse_args()
path = Path(__file__).with_suffix(".exe")
if args.check:
if path.read_bytes() != fixture():
parser.exit(1, f"fixture bytes differ from generator: {path}\n")
else:
path.write_bytes(fixture())
Binary file not shown.
+77
View File
@@ -0,0 +1,77 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original SOP2 vectors for the registry-declared arithmetic, select and
// bit-field forms: signed and unsigned min/max (including a tie, which gives S1
// and SCC = 0), select on both SCC values, bit-field mask, low and high
// multiplies, both bit-field extracts, absolute difference and the four
// shift-and-add forms. BFM, MUL, MUL_HI and CSELECT leave SCC unchanged; the
// last SCC writer (LSHL2_ADD, no carry) clears it for the s_cbranch_scc0.
// Values from the guide's 12.1 pseudocode, with s8 = 0x89abcdef (negative as
// i32) and s9 = 5.
// Expected: input ^ 0x81157dfe (the XOR of s10-s27 below).
.text
buffer_load_dword v1, v0, s[0:3], 0 idxen
s_waitcnt vmcnt(0)
s_mov_b32 s8, 0x89abcdef
s_mov_b32 s9, 5
s_min_i32 s10, s8, s9 // s10 = 0x89abcdef, SCC = 1 (S0 < S1 signed)
s_cselect_b32 s11, s9, s8 // s11 = 5 (SCC = 1 picks S0), SCC unchanged
s_max_u32 s12, s8, s9 // s12 = 0x89abcdef, SCC = 1
s_bfm_b32 s13, 12, 4 // s13 = 0xfff << 4 = 0xfff0, SCC unchanged
s_lshl1_add_u32 s14, s8, s9 // (s8 << 1) + 5 = 0x1_13579be3: s14 = 0x13579be3, SCC = 1
s_mul_i32 s15, s8, s9 // 5 * s8 = 0x2_b05b05ab: s15 = 0xb05b05ab
s_bfe_u32 s16, s8, 0x80004 // offset 4, width 8: s16 = 0xde, SCC = 1
s_bfe_i32 s17, s8, 0x80004 // 0xde sign-extended from bit 7: s17 = 0xffffffde, SCC = 1
s_absdiff_i32 s18, s9, s8 // 5 - (-0x76543211) = 0x76543216: s18, SCC = 1
s_lshl3_add_u32 s19, s8, s8 // 9 * s8 = 0x4_d70a3d67: s19 = 0xd70a3d67, SCC = 1
s_lshl4_add_u32 s20, s9, -16 // 80 + 0xfffffff0 = 0x1_00000040: s20 = 0x40, SCC = 1
s_mul_hi_u32 s21, s8, s8 // high word of s8 * s8 (unsigned): s21 = 0x4a0955b6
s_mul_hi_i32 s22, s8, s8 // high word of 0x76543211^2: s22 = 0x36b1b9d8
s_max_i32 s23, s8, s9 // s23 = 5, SCC = 0 (S0 not greater)
s_min_u32 s24, s9, 5 // tie: s24 = 5 (S1), SCC = 0
s_lshl2_add_u32 s25, s9, s9 // 20 + 5: s25 = 25, SCC = 0 (no carry)
s_cselect_b32 s26, s8, s9 // s26 = 5 (SCC = 0 picks S1), SCC unchanged
s_mul_hi_u32 s27, s9, s9 // s27 = 0, SCC unchanged (0)
s_cbranch_scc0 .Lzero
v_mov_b32_e32 v2, 0
s_branch .Ldone
.Lzero:
v_mov_b32_e32 v2, s10
v_mov_b32_e32 v3, s11
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s12
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s13
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s14
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s15
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s16
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s17
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s18
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s19
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s20
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s21
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s22
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s23
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s24
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s25
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s26
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s27
v_xor_b32_e32 v2, v2, v3
v_xor_b32_e32 v2, v1, v2 // v2 = input ^ 0x81157dfe
.Ldone:
buffer_store_dword v2, v0, s[4:7], 0 idxen
s_waitcnt_vscnt null, 0
s_endpgm
Binary file not shown.
+59
View File
@@ -0,0 +1,59 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original SOP1 vectors for the registry-declared unary forms: complement, bit
// reverse, both bit counts, both find-first searches (one finding nothing, which
// gives -1), both find-last-bit forms, sign extension from 8 and 16 bits, and
// absolute value. SCC is set by NOT/BCNT/ABS only: an ABS of zero clears it, and
// the following SEXT and FF1 leave it clear for the s_cbranch_scc0.
// Expected: input ^ 0x0f0080f5 (worked out by hand below).
.text
buffer_load_dword v1, v0, s[0:3], 0 idxen
s_waitcnt vmcnt(0)
s_mov_b32 s8, 0xf0
s_not_b32 s9, s8 // s9 = 0xffffff0f, SCC = 1
s_brev_b32 s10, s8 // s10 = 0x0f000000
s_bcnt1_i32_b32 s11, s8 // s11 = 4, SCC = 1
s_bcnt0_i32_b32 s12, s8 // s12 = 28, SCC = 1
s_ff1_i32_b32 s13, 0x400000 // s13 = 22
s_ff0_i32_b32 s14, 0xffff // s14 = 16
s_flbit_i32_b32 s15, s8 // s15 = 24
s_flbit_i32 s16, 0xfff00000 // s16 = 12 (bits equal to the sign above bit 19)
s_sext_i32_i8 s17, s8 // s17 = 0xfffffff0
s_sext_i32_i16 s18, 0x18000 // s18 = 0xffff8000
s_abs_i32 s19, s18 // s19 = 0x8000, SCC = 1
s_abs_i32 s20, 0 // s20 = 0, SCC = 0
s_sext_i32_i16 s21, 0x7fff // s21 = 0x7fff, SCC unchanged (0)
s_ff1_i32_b32 s22, 0 // s22 = 0xffffffff (none found), SCC unchanged (0)
s_cbranch_scc0 .Lzero
v_mov_b32_e32 v2, 0
s_branch .Ldone
.Lzero:
v_mov_b32_e32 v2, s9
v_mov_b32_e32 v3, s10
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s11
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s12
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s13
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s14
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s15
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s16
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s17
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s18
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s19
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s21
v_xor_b32_e32 v2, v2, v3
v_mov_b32_e32 v3, s22
v_xor_b32_e32 v2, v2, v3
v_xor_b32_e32 v2, v1, v2 // v2 = input ^ 0x0f0080f5
.Ldone:
buffer_store_dword v2, v0, s[4:7], 0 idxen
s_waitcnt_vscnt null, 0
s_endpgm
Binary file not shown.
+38
View File
@@ -0,0 +1,38 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original VOP2 vectors for the registry-declared per-lane integer forms: the
// four 24-bit multiplies, signed and unsigned min/max, XNOR and the three
// no-carry add/subtract forms (SUBREV reads its sources reversed). Every result
// depends on the lane's own input word x = v1, with SRC0 taken from an inline
// constant, a literal, an SGPR or a VGPR. No form writes SCC or VCC.
// Expected per lane: v14 = v2 ^ v3 ^ ... ^ v13, worked out from the guide's
// 12.7 pseudocode in tests/validation/known_answers.rs (vector_integer_key).
.text
buffer_load_dword v1, v0, s[0:3], 0 idxen
s_waitcnt vmcnt(0)
s_mov_b32 s8, 0x800001 // as i24: -0x7fffff
v_mul_i32_i24_e32 v2, -3, v1 // v2 = sext24(x) * -3 (low 32 bits)
v_mul_hi_i32_i24_e32 v3, s8, v1 // v3 = (-0x7fffff * sext24(x)) >> 32
v_mul_u32_u24_e32 v4, 0x123456, v1 // v4 = 0x123456 * x[23:0] (low 32 bits)
v_mul_hi_u32_u24_e32 v5, s8, v1 // v5 = (0x800001 * x[23:0]) >> 32
v_min_i32_e32 v6, v1, v2 // v6 = signed min(x, v2)
v_max_i32_e32 v7, 5, v1 // v7 = signed max(5, x)
v_min_u32_e32 v8, v3, v1 // v8 = unsigned min(v3, x)
v_max_u32_e32 v9, s8, v1 // v9 = unsigned max(0x800001, x)
v_xnor_b32_e32 v10, v4, v5 // v10 = ~(v4 ^ v5)
v_add_nc_u32_e32 v11, v6, v7 // v11 = v6 + v7
v_sub_nc_u32_e32 v12, v8, v9 // v12 = v8 - v9
v_subrev_nc_u32_e32 v13, v10, v11 // v13 = v11 - v10
v_xor_b32_e32 v14, v2, v3
v_xor_b32_e32 v14, v4, v14
v_xor_b32_e32 v14, v5, v14
v_xor_b32_e32 v14, v6, v14
v_xor_b32_e32 v14, v7, v14
v_xor_b32_e32 v14, v8, v14
v_xor_b32_e32 v14, v9, v14
v_xor_b32_e32 v14, v10, v14
v_xor_b32_e32 v14, v11, v14
v_xor_b32_e32 v14, v12, v14
v_xor_b32_e32 v14, v13, v14
buffer_store_dword v14, v0, s[4:7], 0 idxen
s_waitcnt_vscnt null, 0
s_endpgm
+1
View File
@@ -42,6 +42,7 @@ def main(argv):
s = sub.add_parser("apply"); s.add_argument("--repo", required=True); s.add_argument("--actions", required=True)
s = sub.add_parser("audit"); s.add_argument("--state", required=True)
s = sub.add_parser("summary"); s.add_argument("--state", required=True); s.add_argument("--text", action="store_true")
s.add_argument("--now", default="", help="UTC time YYYY-MM-DDTHH:MM:SSZ (overrides parent --now)")
s = sub.add_parser("pr-check"); s.add_argument("--state", required=True)
s = sub.add_parser("acceptance"); s.add_argument("--issue", required=True); s.add_argument("--comments", required=True)
s = sub.add_parser("task"); s.add_argument("--issue", required=True)
+9 -6
View File
@@ -79,12 +79,15 @@ def apply_actions(repo, actions):
n = str(a["issue"])
for label in a["add_labels"]:
gh("label", "create", label, "-R", repo, "--force", "--color", "BFD4F2")
args = ["issue", "edit", n, "-R", repo]
for l in a["add_labels"]:
args += ["--add-label", l]
for l in a["remove_labels"]:
args += ["--remove-label", l]
if len(args) > 4:
# Comment-only actions (for example claim refusals) must not call `gh issue edit`:
# `["issue", "edit", n, "-R", repo]` is already five tokens, so a length check is not
# enough to detect missing label flags and newer gh rejects a no-op edit.
if a["add_labels"] or a["remove_labels"]:
args = ["issue", "edit", n, "-R", repo]
for l in a["add_labels"]:
args += ["--add-label", l]
for l in a["remove_labels"]:
args += ["--remove-label", l]
gh(*args)
if a["comment"]:
gh("issue", "comment", n, "-R", repo, "--body", a["comment"])
+1 -1
View File
@@ -12,7 +12,7 @@ case "${1:-}" in
esac
for name in add bitwise-branch float-exact or shifts ashr \
x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu vector-compare scalar-logic scalar-compare; do
x9-constant-vs x9-constant-ps x9-varying-vs x9-varying-ps x9-transform-vs scalar-alu vector-compare scalar-logic scalar-compare scalar-unary scalar-arith vector-integer; do
"$llvm_bin/llvm-mc" -triple=amdgcn-amd-amdhsa -mcpu=gfx1030 -mattr=+wavefrontsize32 \
-filetype=obj "fixtures/rdna2/$name.s" -o "$scratch/$name.o"
"$llvm_bin/llvm-objcopy" -O binary --only-section=.text "$scratch/$name.o" "$scratch/$name.bin"
+10
View File
@@ -35,6 +35,16 @@ cat > "$bundle/Contents/Info.plist" <<PLIST
<key>CFBundleShortVersionString</key><string>0.1.0</string>
<key>LSMinimumSystemVersion</key><string>14.0</string>
<key>NSHighResolutionCapable</key><true/>
<key>CFBundleDocumentTypes</key>
<array>
<dict>
<key>CFBundleTypeName</key><string>Windows Executable</string>
<key>CFBundleTypeRole</key><string>Viewer</string>
<key>LSHandlerRank</key><string>Alternate</string>
<key>LSItemContentTypes</key>
<array><string>com.microsoft.windows-executable</string></array>
</dict>
</array>
</dict>
</plist>
PLIST
+2
View File
@@ -0,0 +1,2 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Standalone infrastructure QA helpers. Advisory until reviewed."""
+389
View File
@@ -0,0 +1,389 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""CLI entry: python3 -m qa <command> ..."""
from __future__ import annotations
import argparse
import json
import shlex
import subprocess
import sys
from pathlib import Path
from typing import Any
from .bench_regress import IncompatibleComparison, compare_records, dumps_comparison, load_record
from .bench_stats import export_json, human_report, summarize
from .claim_conflict import ClaimSnapshot, format_conflicts, predict_conflicts
from .cpu_coverage import blocker_manifest, build_report as build_cpu_report, compare_reports, dumps_report as dumps_cpu
from .env_check import (
check_branch_sync,
check_git_worktree_clean,
check_llvm_tool,
check_rosetta_translated,
check_rustc_host,
check_swift_version,
check_uname_machine,
format_report,
summarize as summarize_env,
)
from .git_scope import colliding_scopes, effective_paths, parse_name_status
from .orchestrate import SuiteSpec, dumps_report, failure_log_excerpt, run_suites
from .pr_validate import (
check_artifacts,
check_changelog_required,
check_dco,
check_report_commit_identity,
check_scope,
merge_reports,
)
from .rdna2_plan import (
build_manifests,
classify_unsupported,
compact_candidates,
compact_inventory,
compact_manifests,
coverage_diff,
discrepancies,
dumps_candidates,
dumps_inventory,
load_inventories,
parse_claims_file,
plan_batches,
reconcile_with_coverage_report,
summarize_inventory,
write_json,
)
from .coverage_history import historical_report, snapshot_inventory, write_snapshot
from .stale_branch import classify_sync, format_sync_reports
from .verify import dumps_evidence, evidence_is_stale, load_evidence, run_profile
def _root() -> Path:
return Path(__file__).resolve().parents[2]
def main(argv: list[str] | None = None) -> int:
argv = list(sys.argv[1:] if argv is None else argv)
p = argparse.ArgumentParser(prog="qa")
sub = p.add_subparsers(dest="command", required=True)
o = sub.add_parser("orchestrate", help="run command suites and emit JSON")
o.add_argument("--name", action="append", default=[])
o.add_argument("--run", action="append", default=[], dest="runs",
help="shell argv string for one suite")
o.add_argument("--kind", action="append", default=[])
o.add_argument("--stop-on-fail", action="store_true")
o.add_argument("--failures", action="store_true")
b = sub.add_parser("bench-stats", help="summarize numeric samples")
b.add_argument("samples", nargs="+", type=float)
b.add_argument("--metric", default="latency")
b.add_argument("--json", action="store_true")
b.add_argument("--host", default="unknown")
b.add_argument("--toolchain", default="unknown")
b.add_argument("--revision", default="unknown")
br = sub.add_parser("bench-compare", help="compare two recorded benchmark JSON files")
br.add_argument("--baseline", required=True)
br.add_argument("--current", required=True)
br.add_argument("--threshold", type=float, default=1.10)
c = sub.add_parser("predict-conflicts", help="read-only claim overlap check")
c.add_argument("--candidate", action="append", default=[])
c.add_argument("--held", action="append", default=[], help="number:holder:path[,path...]")
g = sub.add_parser("scope-collisions", help="collisions from git name-status input")
g.add_argument("--claimed", action="append", default=[], help="claimed path pattern")
g.add_argument("--name-status-file", default="-")
v = sub.add_parser("validate-pr", help="advisory PR validation from JSON stdin")
v.add_argument("--allowed", action="append", default=[])
r = sub.add_parser("rdna2", help="read-only RDNA2 expansion planning")
r.add_argument(
"action",
choices=("inventory", "candidates", "plan", "discrepancies", "diff", "manifests", "reconcile"),
)
r.add_argument("--limit", type=int, default=0)
r.add_argument("--family", action="append", default=[], help="filter by encoding family")
r.add_argument(
"--status",
action="append",
default=[],
help="filter: reuse-primitives|needs-primitives|needs-operand-rules",
)
r.add_argument("--claims", default="", help="JSON claims file to exclude overlapping work")
r.add_argument("--compact", action="store_true", help="print compact summary to stdout")
r.add_argument("--out", default="", help="write full JSON under this path (prefer artifacts/)")
r.add_argument("--before", default="", help="JSON inventory for diff")
r.add_argument("--after", default="", help="JSON inventory for diff")
cpu = sub.add_parser("cpu-coverage", help="read-only CPU/runtime coverage scan")
cpu.add_argument("--blockers", action="store_true")
cpu.add_argument("--compare", default="", help="previous JSON report path")
ver = sub.add_parser("verify", help="run a verification profile")
ver.add_argument("profile", choices=("quick", "cpu", "gpu", "app", "full", "release"))
ver.add_argument("--revision", default="")
ver.add_argument("--no-stop", action="store_true")
ver.add_argument("--check-stale", default="", help="existing evidence JSON to staleness-check")
env = sub.add_parser("env", help="environment diagnostics from live commands")
hist = sub.add_parser("rdna2-history", help="write or diff RDNA2 coverage snapshots")
hist.add_argument("action", choices=("write", "diff"))
hist.add_argument("--path", default="")
hist.add_argument("--before", default="")
hist.add_argument("--after", default="")
hist.add_argument("--revision", default="")
br = sub.add_parser("branch-sync", help="classify ahead/behind/diverged branch state")
br.add_argument("--branch", required=True)
br.add_argument("--upstream", required=True)
br.add_argument("--ahead", type=int, required=True)
br.add_argument("--behind", type=int, required=True)
args = p.parse_args(argv)
root = _root()
if args.command == "orchestrate":
if not args.name or len(args.name) != len(args.runs):
print("orchestrate requires matching --name and --run lists", file=sys.stderr)
return 2
specs = []
for i, name in enumerate(args.name):
kind = args.kind[i] if i < len(args.kind) else "cpu"
specs.append(SuiteSpec(name, tuple(shlex.split(args.runs[i])), kind))
report = run_suites(specs, stop_on_fail=args.stop_on_fail)
if args.failures:
print(failure_log_excerpt(report), end="")
else:
print(dumps_report(report), end="")
return report.overall_returncode()
if args.command == "bench-stats":
stats = summarize(args.samples)
if args.json:
print(export_json(stats, host=args.host, toolchain=args.toolchain,
revision=args.revision, metric=args.metric), end="")
else:
print(human_report(stats, metric=args.metric), end="")
return 0
if args.command == "bench-compare":
baseline = load_record(json.loads(Path(args.baseline).read_text(encoding="utf-8")))
current = load_record(json.loads(Path(args.current).read_text(encoding="utf-8")))
try:
payload = compare_records(baseline, current, threshold=args.threshold)
except IncompatibleComparison as exc:
print(str(exc), file=sys.stderr)
return 2
print(dumps_comparison(payload), end="")
return 1 if payload["regressing"] else 0
if args.command == "predict-conflicts":
held = []
for item in args.held:
number, holder, paths = item.split(":", 2)
held.append(ClaimSnapshot(int(number), holder, tuple(paths.split(",")), True))
hits = predict_conflicts(args.candidate, held)
print(format_conflicts(hits), end="")
return 1 if hits else 0
if args.command == "scope-collisions":
text = sys.stdin.read() if args.name_status_file == "-" else Path(args.name_status_file).read_text(encoding="utf-8")
changes = parse_name_status(text.splitlines())
paths = sorted(effective_paths(changes))
hits = colliding_scopes(paths, args.claimed)
json.dump({"paths": paths, "collisions": [{"path": a, "pattern": b} for a, b in hits]}, sys.stdout, indent=2)
print()
return 1 if hits else 0
if args.command == "validate-pr":
payload = json.load(sys.stdin)
report = merge_reports(
check_scope(payload.get("files", []), args.allowed),
check_dco(payload.get("messages", [])),
check_artifacts(payload.get("files", [])),
check_changelog_required(payload.get("files", [])),
check_report_commit_identity(payload.get("report_sha", ""), payload.get("head_sha", "")),
)
json.dump({"ok": report.ok, "findings": [f.__dict__ for f in report.findings]}, sys.stdout, indent=2)
print()
return 0 if report.ok else 1
if args.command == "rdna2":
if args.action == "diff":
before = json.loads(Path(args.before).read_text(encoding="utf-8"))
after = json.loads(Path(args.after).read_text(encoding="utf-8"))
from .rdna2_plan import Inventory
def inv(d):
return Inventory(**{k: d[k] for k in (
"identified", "declared", "decoder_supported", "reference_verified",
"metal_verified", "unsupported", "by_family")})
payload = coverage_diff(inv(before), inv(after))
if args.out:
write_json(Path(args.out), payload)
if args.compact or args.out:
print(
f"declared_delta={payload['declared_delta']} "
f"unsupported_delta={payload['unsupported_delta']}"
)
else:
print(json.dumps(payload, indent=2, sort_keys=True))
return 0
data = load_inventories(root)
inv = summarize_inventory(data)
exclude_families: list[str] = []
claimed_paths: list[str] = []
if args.claims:
fams, paths = parse_claims_file(Path(args.claims))
exclude_families = sorted(fams)
claimed_paths = sorted(paths)
limit = args.limit or None
def emit(payload: Any, compact_text: str, full_text: str | None = None) -> int:
if args.out:
write_json(Path(args.out), payload)
if args.compact or args.out:
print(compact_text, end="")
elif full_text is not None:
print(full_text, end="")
else:
print(json.dumps(payload, indent=2, sort_keys=True) + "\n", end="")
return 0
if args.action == "inventory":
return emit(json.loads(dumps_inventory(inv)), compact_inventory(inv), dumps_inventory(inv))
if args.action == "candidates":
cands = classify_unsupported(
data,
limit=limit,
families=args.family or None,
statuses=args.status or None,
exclude_families=exclude_families,
)
payload = json.loads(dumps_candidates(cands))
return emit(payload, compact_candidates(cands), dumps_candidates(cands))
if args.action == "plan":
cands = classify_unsupported(
data,
limit=limit,
families=args.family or None,
statuses=args.status or None,
exclude_families=exclude_families,
)
payload = plan_batches(cands)
return emit(payload, compact_candidates(cands))
if args.action == "manifests":
cands = classify_unsupported(
data,
limit=None,
families=args.family or None,
statuses=args.status or ["reuse-primitives"],
exclude_families=exclude_families,
)
manifests = build_manifests(
cands,
exclude_families=exclude_families,
claimed_paths=claimed_paths,
limit=limit,
)
payload = {
"note": "Codex-ready planning manifests only; forms are not implemented.",
"count": len(manifests),
"manifests": manifests,
}
out = args.out or "artifacts/rdna2-manifests.json"
write_json(Path(out), payload)
print(compact_manifests(manifests), end="")
print(f"wrote {out}")
return 0
if args.action == "discrepancies":
payload = discrepancies(data)
return emit(payload, f"discrepancies={len(payload)}\n")
if args.action == "reconcile":
payload = reconcile_with_coverage_report(root, data)
return emit(
payload,
f"reconcile_ok={payload['ok']} mismatches={len(payload['mismatches'])}\n",
)
if args.command == "cpu-coverage":
report = build_cpu_report(root)
if args.compare:
prev = json.loads(Path(args.compare).read_text(encoding="utf-8"))
print(json.dumps(compare_reports(prev, report.to_dict()), indent=2, sort_keys=True))
return 0
if args.blockers:
print(json.dumps(blocker_manifest(report), indent=2, sort_keys=True))
return 0
print(dumps_cpu(report), end="")
return 0
if args.command == "verify":
if args.check_stale:
evidence = load_evidence(Path(args.check_stale).read_text(encoding="utf-8"))
stale = evidence_is_stale(evidence, root)
json.dump({"stale": stale, "fingerprint": evidence.source_fingerprint}, sys.stdout, indent=2)
print()
return 1 if stale else 0
revision = args.revision or subprocess.check_output(
["git", "rev-parse", "HEAD"], cwd=root, text=True
).strip()
evidence = run_profile(
args.profile, root=root, revision=revision, stop_on_fail=not args.no_stop
)
print(dumps_evidence(evidence), end="")
return evidence.overall_returncode
if args.command == "env":
machine = subprocess.check_output(["uname", "-m"], text=True)
translated = subprocess.check_output(
["sysctl", "-n", "sysctl.proc_translated"], text=True
)
rustc = subprocess.check_output(["rustc", "-vV"], text=True)
swift = subprocess.run(["swift", "--version"], capture_output=True, text=True).stdout
clang_path = subprocess.run(["which", "clang"], capture_output=True, text=True).stdout
clang_ver = subprocess.run(["clang", "--version"], capture_output=True, text=True).stdout
porcelain = subprocess.check_output(["git", "status", "--porcelain"], cwd=root, text=True)
findings = [
check_uname_machine(machine),
check_rosetta_translated(translated),
check_rustc_host(rustc),
check_swift_version(swift),
check_llvm_tool(clang_path, clang_ver),
check_git_worktree_clean(porcelain),
check_branch_sync(ahead=0, behind=0),
]
report = summarize_env(findings)
print(format_report(report), end="")
return 0 if report.ok else 1
if args.command == "rdna2-history":
if args.action == "write":
rev = args.revision or subprocess.check_output(
["git", "rev-parse", "HEAD"], cwd=root, text=True
).strip()
path = Path(args.path or "artifacts/rdna2-coverage.json")
write_snapshot(path, snapshot_inventory(root), revision=rev)
print(path)
return 0
report = historical_report(Path(args.before), Path(args.after))
print(json.dumps(report, indent=2, sort_keys=True))
return 0
if args.command == "branch-sync":
report = classify_sync(
branch=args.branch,
upstream=args.upstream,
ahead=args.ahead,
behind=args.behind,
)
print(format_sync_reports([report]), end="")
return 1 if report.stale or report.diverged else 0
return 2
if __name__ == "__main__":
raise SystemExit(main())
+104
View File
@@ -0,0 +1,104 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Benchmark regression intelligence over recorded results.
Rejects incompatible comparisons and requires actual sample data.
"""
from __future__ import annotations
import json
import math
from dataclasses import asdict, dataclass
from typing import Any, Sequence
from .bench_stats import SampleStats, compare_medians, summarize
@dataclass(frozen=True)
class BenchIdentity:
metric: str
unit: str
workload: str
host: str
toolchain: str
@dataclass(frozen=True)
class BenchRecord:
identity: BenchIdentity
samples: tuple[float, ...]
revision: str
def stats(self) -> SampleStats:
return summarize(self.samples)
class IncompatibleComparison(ValueError):
pass
def identities_compatible(a: BenchIdentity, b: BenchIdentity) -> bool:
return (
a.metric == b.metric
and a.unit == b.unit
and a.workload == b.workload
and a.host == b.host
and a.toolchain == b.toolchain
)
def compare_records(
baseline: BenchRecord,
current: BenchRecord,
*,
threshold: float = 1.10,
min_samples: int = 3,
noise_floor_ratio: float = 0.03,
) -> dict[str, Any]:
if not identities_compatible(baseline.identity, current.identity):
raise IncompatibleComparison(
"refusing comparison across different workload/unit/host/toolchain/metric"
)
if len(baseline.samples) < min_samples or len(current.samples) < min_samples:
raise ValueError(f"need at least {min_samples} samples on each side")
result = compare_medians(baseline.samples, current.samples,
metric=baseline.identity.metric, threshold=threshold)
base_stats = baseline.stats()
cur_stats = current.stats()
# Treat changes within noise_floor_ratio of the baseline median as noise.
noise = abs(base_stats.median) * noise_floor_ratio
delta = cur_stats.median - base_stats.median
meaningful = abs(delta) > max(noise, math.ulp(base_stats.median) * 8)
return {
"identity": asdict(baseline.identity),
"baseline_revision": baseline.revision,
"current_revision": current.revision,
"baseline_stats": asdict(base_stats),
"current_stats": asdict(cur_stats),
"ratio": result.ratio,
"threshold": threshold,
"regressing": bool(result.regressing and meaningful),
"meaningful": meaningful,
"noise_floor": noise,
}
def load_record(data: dict[str, Any]) -> BenchRecord:
ident = data["identity"]
samples = data.get("samples")
if not isinstance(samples, list) or not samples:
raise ValueError("record requires a non-empty samples list; refusing fabricated data")
return BenchRecord(
identity=BenchIdentity(
metric=ident["metric"],
unit=ident["unit"],
workload=ident["workload"],
host=ident["host"],
toolchain=ident["toolchain"],
),
samples=tuple(float(x) for x in samples),
revision=str(data["revision"]),
)
def dumps_comparison(payload: dict[str, Any]) -> str:
return json.dumps(payload, indent=2, sort_keys=True) + "\n"
+122
View File
@@ -0,0 +1,122 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Benchmark result analysis over existing measurement samples.
Consumes numeric samples only. Does not run workloads or invent timings.
"""
from __future__ import annotations
import json
import math
import statistics
from dataclasses import asdict, dataclass
from typing import Any, Sequence
@dataclass(frozen=True)
class SampleStats:
count: int
median: float
p95: float
p99: float
mean: float
stdev: float
iqr: float
minimum: float
maximum: float
@dataclass(frozen=True)
class RegressionResult:
metric: str
baseline_median: float
current_median: float
ratio: float
threshold: float
regressing: bool
def _percentile(sorted_samples: Sequence[float], pct: float) -> float:
if not sorted_samples:
raise ValueError("no samples")
if pct <= 0:
return float(sorted_samples[0])
if pct >= 100:
return float(sorted_samples[-1])
k = (len(sorted_samples) - 1) * (pct / 100.0)
f = math.floor(k)
c = math.ceil(k)
if f == c:
return float(sorted_samples[int(k)])
d0 = sorted_samples[f] * (c - k)
d1 = sorted_samples[c] * (k - f)
return float(d0 + d1)
def summarize(samples: Sequence[float]) -> SampleStats:
if not samples:
raise ValueError("summarize requires at least one sample")
ordered = sorted(float(x) for x in samples)
q1 = _percentile(ordered, 25)
q3 = _percentile(ordered, 75)
stdev = statistics.pstdev(ordered) if len(ordered) > 1 else 0.0
return SampleStats(
count=len(ordered),
median=statistics.median(ordered),
p95=_percentile(ordered, 95),
p99=_percentile(ordered, 99),
mean=statistics.fmean(ordered),
stdev=stdev,
iqr=q3 - q1,
minimum=ordered[0],
maximum=ordered[-1],
)
def compare_medians(
baseline: Sequence[float],
current: Sequence[float],
*,
metric: str = "latency",
threshold: float = 1.10,
) -> RegressionResult:
base = summarize(baseline)
cur = summarize(current)
if base.median <= 0:
ratio = math.inf if cur.median > 0 else 1.0
else:
ratio = cur.median / base.median
return RegressionResult(
metric=metric,
baseline_median=base.median,
current_median=cur.median,
ratio=ratio,
threshold=threshold,
regressing=ratio > threshold,
)
def export_json(
stats: SampleStats,
*,
host: str,
toolchain: str,
revision: str,
metric: str,
) -> str:
payload: dict[str, Any] = {
"metric": metric,
"host": host,
"toolchain": toolchain,
"revision": revision,
"stats": asdict(stats),
}
return json.dumps(payload, indent=2, sort_keys=True) + "\n"
def human_report(stats: SampleStats, *, metric: str) -> str:
return (
f"{metric}: n={stats.count} median={stats.median:.6g} "
f"p95={stats.p95:.6g} p99={stats.p99:.6g} "
f"iqr={stats.iqr:.6g} stdev={stats.stdev:.6g} "
f"min={stats.minimum:.6g} max={stats.maximum:.6g}\n"
)
+85
View File
@@ -0,0 +1,85 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Read-only claim conflict prediction for contributors.
Wraps the same path-overlap idea used by the agent queue without requiring a
network call. Useful before posting /claim or starting edits.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Iterable, Sequence
@dataclass(frozen=True)
class ClaimSnapshot:
number: int
holder: str
files: tuple[str, ...]
claimed: bool
@dataclass(frozen=True)
class ConflictHit:
candidate: int
held_by: int
holder: str
pattern_a: str
pattern_b: str
def _dir_prefix(pattern: str) -> str | None:
if pattern.endswith("/**"):
return pattern[:-3].rstrip("/")
if pattern.endswith("/"):
return pattern.rstrip("/")
return None
def patterns_overlap(a: str, b: str) -> bool:
if a == b:
return True
pa, pb = _dir_prefix(a), _dir_prefix(b)
if pa is not None and (b == pa or b.startswith(pa + "/") or _dir_prefix(b) == pa):
return True
if pb is not None and (a == pb or a.startswith(pb + "/") or _dir_prefix(a) == pb):
return True
# prefix directory without slash: treat trailing path segment containment
if a.endswith("/") and (b.startswith(a) or b == a.rstrip("/")):
return True
if b.endswith("/") and (a.startswith(b) or a == b.rstrip("/")):
return True
return False
def predict_conflicts(candidate_files: Sequence[str], held: Iterable[ClaimSnapshot]) -> tuple[ConflictHit, ...]:
hits: list[ConflictHit] = []
for claim in held:
if not claim.claimed:
continue
for ca in candidate_files:
for hb in claim.files:
if patterns_overlap(ca, hb):
hits.append(ConflictHit(
candidate=-1,
held_by=claim.number,
holder=claim.holder,
pattern_a=ca,
pattern_b=hb,
))
break
else:
continue
break
return tuple(hits)
def format_conflicts(hits: Sequence[ConflictHit]) -> str:
if not hits:
return "no file conflicts predicted\n"
lines = ["predicted claim conflicts:", ""]
for hit in hits:
lines.append(
f"- overlaps claimed #{hit.held_by} by {hit.holder}: `{hit.pattern_a}` vs `{hit.pattern_b}`"
)
lines.append("")
return "\n".join(lines)
+45
View File
@@ -0,0 +1,45 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Historical RDNA2 coverage snapshots for revision-to-revision reports."""
from __future__ import annotations
import json
from dataclasses import asdict
from pathlib import Path
from typing import Any
from .rdna2_plan import Inventory, coverage_diff, dumps_inventory, load_inventories, summarize_inventory
def snapshot_inventory(root: Path) -> Inventory:
return summarize_inventory(load_inventories(root))
def write_snapshot(path: Path, inventory: Inventory, *, revision: str) -> None:
payload = asdict(inventory)
payload["revision"] = revision
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
def read_snapshot(path: Path) -> tuple[str, Inventory]:
data = json.loads(path.read_text(encoding="utf-8"))
revision = str(data.pop("revision", "unknown"))
inv = Inventory(
identified=int(data["identified"]),
declared=int(data["declared"]),
decoder_supported=int(data["decoder_supported"]),
reference_verified=int(data["reference_verified"]),
metal_verified=int(data["metal_verified"]),
unsupported=int(data["unsupported"]),
by_family=dict(data.get("by_family", {})),
)
return revision, inv
def historical_report(before_path: Path, after_path: Path) -> dict[str, Any]:
before_rev, before = read_snapshot(before_path)
after_rev, after = read_snapshot(after_path)
diff = coverage_diff(before, after)
diff["before_revision"] = before_rev
diff["after_revision"] = after_rev
return diff
+215
View File
@@ -0,0 +1,215 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Read-only CPU and runtime coverage intelligence.
Consumes existing source inventories and reports without modifying CPU/runtime
implementation or executable authorization policies.
"""
from __future__ import annotations
import json
import re
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any, Iterable
# Opcode tables are discovered from existing loader sources when present.
OPCODE_MATCH = re.compile(
r"(?:match\s+opcode|Op::|opcode\s*=>|0x([0-9A-Fa-f]{2}))"
)
IMPORT_MATCH = re.compile(
r'^\s*(?:pub\s+)?(?:const|static)?\s*(?:NAME|DLL|dll|module)?[^\"\n]*\"([A-Za-z0-9_.]+)\"',
re.MULTILINE,
)
HANDLER_KIND_MATCH = re.compile(
r"(Unsupported|Todo|todo!|unimplemented!|alias|Alias|forward|Forward)",
)
@dataclass
class OpcodeEntry:
opcode: str
status: str # supported | unsupported | unknown
source: str
@dataclass
class ImportEntry:
name: str
dll: str
kind: str # functional | alias | stub | missing | unknown
source: str
@dataclass
class CoverageReport:
opcodes: list[OpcodeEntry] = field(default_factory=list)
imports: list[ImportEntry] = field(default_factory=list)
interpreter_symbols: list[str] = field(default_factory=list)
dbt_symbols: list[str] = field(default_factory=list)
notes: list[str] = field(default_factory=list)
def to_dict(self) -> dict[str, Any]:
return {
"opcodes": [asdict(o) for o in self.opcodes],
"imports": [asdict(i) for i in self.imports],
"interpreter_symbols": self.interpreter_symbols,
"dbt_symbols": self.dbt_symbols,
"notes": self.notes,
"counts": {
"opcodes": len(self.opcodes),
"imports": len(self.imports),
"interpreter_only": sorted(set(self.interpreter_symbols) - set(self.dbt_symbols)),
"dbt_only": sorted(set(self.dbt_symbols) - set(self.interpreter_symbols)),
},
}
def _read(path: Path) -> str:
return path.read_text(encoding="utf-8") if path.exists() else ""
def scan_opcodes(text: str, *, source: str) -> list[OpcodeEntry]:
found: dict[str, OpcodeEntry] = {}
for match in re.finditer(r"0x([0-9A-Fa-f]{2})", text):
op = match.group(1).lower()
line_start = text.rfind("\n", 0, match.start()) + 1
line_end = text.find("\n", match.end())
if line_end < 0:
line_end = len(text)
line = text[line_start:line_end]
if re.search(r"unsupported|illegal|todo!|unimplemented!", line, re.I):
status = "unsupported"
elif re.search(r"match|Op::|opcode|=>", line, re.I):
status = "supported"
else:
status = "unknown"
prev = found.get(op)
# Prefer explicit unsupported/supported over unknown; do not let a later
# unsupported line rewrite an earlier supported opcode with the same hex.
if prev is None:
found[op] = OpcodeEntry(opcode=op, status=status, source=source)
elif prev.status == "unknown" and status != "unknown":
found[op] = OpcodeEntry(opcode=op, status=status, source=source)
return [found[k] for k in sorted(found)]
def scan_imports(text: str, *, source: str, default_dll: str = "unknown") -> list[ImportEntry]:
entries: list[ImportEntry] = []
for match in re.finditer(r'"([A-Za-z_][A-Za-z0-9_]*)"', text):
name = match.group(1)
if name.endswith(".dll") or name.endswith(".DLL"):
continue
line_start = text.rfind("\n", 0, match.start()) + 1
line_end = text.find("\n", match.end())
if line_end < 0:
line_end = len(text)
line = text[line_start:line_end]
if re.search(r"unsupported|todo!|unimplemented!|stub", line, re.I):
kind = "stub"
elif re.search(r"alias|forward", line, re.I):
kind = "alias"
elif re.search(r"fn |Handler|handler|service", line, re.I):
kind = "functional"
else:
kind = "unknown"
entries.append(ImportEntry(name=name, dll=default_dll, kind=kind, source=source)) # Deduplicate by name keeping stronger kinds
rank = {"functional": 3, "alias": 2, "stub": 1, "missing": 0, "unknown": 0}
best: dict[str, ImportEntry] = {}
for entry in entries:
cur = best.get(entry.name)
if cur is None or rank[entry.kind] > rank[cur.kind]:
best[entry.name] = entry
return [best[k] for k in sorted(best)]
def scan_symbols(text: str, pattern: str) -> list[str]:
return sorted(set(re.findall(pattern, text)))
def build_report(root: Path) -> CoverageReport:
report = CoverageReport(notes=[
"Read-only scan of existing sources; not an architectural claim of completeness.",
"Statuses are heuristic over source text where no authoritative inventory file exists.",
])
cpu = root / "crates" / "loader" / "src" / "cpu.rs"
dbt = root / "crates" / "loader" / "src" / "dbt.rs"
probe = root / "crates" / "loader" / "src" / "probe.rs"
if cpu.exists():
text = _read(cpu)
report.opcodes.extend(scan_opcodes(text, source=str(cpu.relative_to(root))))
report.interpreter_symbols = scan_symbols(text, r"\bfn\s+(execute_[a-z0-9_]+)\b")
if dbt.exists():
text = _read(dbt)
report.dbt_symbols = scan_symbols(text, r"\bfn\s+(lower_[a-z0-9_]+|emit_[a-z0-9_]+)\b")
report.opcodes.extend(scan_opcodes(text, source=str(dbt.relative_to(root))))
if probe.exists():
report.opcodes.extend(scan_opcodes(_read(probe), source=str(probe.relative_to(root))))
# Import generation / service registries when present.
for path in sorted((root / "crates").rglob("*.rs")):
if path.name in {"imports.rs", "services.rs", "win32.rs", "registry.rs"} or "import" in path.name:
rel = str(path.relative_to(root))
report.imports.extend(scan_imports(_read(path), source=rel, default_dll=path.stem))
# Dedup opcodes preferring supported over unsupported over unknown
rank = {"supported": 2, "unsupported": 1, "unknown": 0}
best: dict[str, OpcodeEntry] = {}
for entry in report.opcodes:
cur = best.get(entry.opcode)
if cur is None or rank[entry.status] > rank[cur.status]:
best[entry.opcode] = entry
report.opcodes = [best[k] for k in sorted(best)]
return report
def compare_reports(before: dict[str, Any], after: dict[str, Any]) -> dict[str, Any]:
before_ops = {o["opcode"]: o["status"] for o in before.get("opcodes", [])}
after_ops = {o["opcode"]: o["status"] for o in after.get("opcodes", [])}
newly_supported = sorted(op for op, st in after_ops.items() if st == "supported" and before_ops.get(op) != "supported")
newly_unsupported = sorted(op for op, st in after_ops.items() if st == "unsupported" and before_ops.get(op) != "unsupported")
missing = sorted(set(before_ops) - set(after_ops))
return {
"newly_supported": newly_supported,
"newly_unsupported": newly_unsupported,
"missing_opcodes": missing,
"interpreter_only_delta": sorted(
set(after.get("counts", {}).get("interpreter_only", []))
- set(before.get("counts", {}).get("interpreter_only", []))
),
}
def blocker_manifest(report: CoverageReport, *, limit: int = 50) -> list[dict[str, Any]]:
blockers = []
for entry in report.opcodes:
if entry.status == "unsupported":
blockers.append({
"kind": "opcode",
"id": entry.opcode,
"priority": "high",
"source": entry.source,
"task": f"Implement or document x86 opcode 0x{entry.opcode}",
})
for entry in report.imports:
if entry.kind in {"stub", "missing"}:
blockers.append({
"kind": "import",
"id": entry.name,
"priority": "medium",
"source": entry.source,
"task": f"Replace {entry.kind} import handler for {entry.name}",
})
for sym in sorted(set(report.interpreter_symbols) - set(report.dbt_symbols))[:limit]:
blockers.append({
"kind": "dbt-gap",
"id": sym,
"priority": "medium",
"source": "interpreter-vs-dbt",
"task": f"Consider native DBT coverage for {sym}",
})
return blockers[:limit]
def dumps_report(report: CoverageReport) -> str:
return json.dumps(report.to_dict(), indent=2, sort_keys=True) + "\n"
+87
View File
@@ -0,0 +1,87 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Development environment diagnostics for Apple Silicon Xenora contributors."""
from __future__ import annotations
import re
from dataclasses import dataclass, field
from typing import Iterable
@dataclass
class EnvFinding:
name: str
ok: bool
detail: str
@dataclass
class EnvReport:
findings: list[EnvFinding] = field(default_factory=list)
@property
def ok(self) -> bool:
return all(f.ok for f in self.findings)
def check_uname_machine(machine: str) -> EnvFinding:
ok = machine.strip() == "arm64"
return EnvFinding("host-arch", ok, f"uname -m => {machine.strip()}" + ("" if ok else " (want arm64)"))
def check_rosetta_translated(proc_translated: str) -> EnvFinding:
ok = proc_translated.strip() == "0"
return EnvFinding(
"rosetta",
ok,
f"sysctl.proc_translated => {proc_translated.strip()}" + ("" if ok else " (Rosetta translation active)"),
)
def check_rustc_host(rustc_vv: str) -> EnvFinding:
host = ""
for line in rustc_vv.splitlines():
if line.startswith("host:"):
host = line.split(":", 1)[1].strip()
ok = host == "aarch64-apple-darwin"
return EnvFinding("rustc-host", ok, f"host={host or 'unknown'}" + ("" if ok else " (want aarch64-apple-darwin)"))
def check_swift_version(swift_version: str) -> EnvFinding:
ok = "Swift version" in swift_version
return EnvFinding("swift", ok, swift_version.strip().splitlines()[0] if swift_version.strip() else "missing")
_LLVM_RE = re.compile(r"LLVM|clang", re.IGNORECASE)
def check_llvm_tool(which_path: str, version_text: str) -> EnvFinding:
if not which_path.strip():
return EnvFinding("llvm", False, "tool not found on PATH")
ok = bool(_LLVM_RE.search(version_text) or version_text.strip())
return EnvFinding("llvm", ok, f"{which_path.strip()}: {version_text.strip().splitlines()[0] if version_text.strip() else 'no version'}")
def check_git_worktree_clean(porcelain: str) -> EnvFinding:
ok = porcelain.strip() == ""
return EnvFinding("worktree-clean", ok, "clean" if ok else "dirty worktree")
def check_branch_sync(*, ahead: int, behind: int) -> EnvFinding:
ok = ahead == 0 and behind == 0
detail = f"ahead={ahead} behind={behind}"
return EnvFinding("branch-sync", ok, detail)
def summarize(findings: Iterable[EnvFinding]) -> EnvReport:
return EnvReport(findings=list(findings))
def format_report(report: EnvReport) -> str:
lines = ["# Environment diagnostics", ""]
for finding in report.findings:
mark = "ok" if finding.ok else "FAIL"
lines.append(f"- [{mark}] {finding.name}: {finding.detail}")
lines.append("")
lines.append("overall: " + ("ok" if report.ok else "problems found"))
lines.append("")
return "\n".join(lines)
+48
View File
@@ -0,0 +1,48 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Run a command and preserve its exit status through pipes.
Never report success because a later pipe stage (grep, head) succeeded while
the measured command failed.
"""
from __future__ import annotations
import subprocess
from dataclasses import dataclass
from typing import Sequence
@dataclass(frozen=True)
class PipedResult:
command: tuple[str, ...]
returncode: int
stdout: str
stderr: str
def run_preserving_status(
command: Sequence[str],
*,
cwd: str | None = None,
timeout: float | None = None,
) -> PipedResult:
"""Run `command` with check disabled and return its real exit status."""
completed = subprocess.run(
list(command),
cwd=cwd,
capture_output=True,
text=True,
timeout=timeout,
check=False,
)
return PipedResult(
command=tuple(command),
returncode=int(completed.returncode),
stdout=completed.stdout,
stderr=completed.stderr,
)
def classify_status(returncode: int) -> str:
if returncode == 0:
return "passed"
return "failed"
+84
View File
@@ -0,0 +1,84 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Shared-file collision helpers that account for renames and deletions."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Iterable, Sequence
@dataclass(frozen=True)
class PathChange:
status: str # A | M | D | R
path: str
old_path: str | None = None
def parse_name_status(lines: Iterable[str]) -> list[PathChange]:
"""Parse `git diff --name-status` style lines, including renames."""
out: list[PathChange] = []
for raw in lines:
line = raw.strip("\n")
if not line:
continue
parts = line.split("\t")
status = parts[0]
code = status[0]
if code == "R" and len(parts) >= 3:
out.append(PathChange("R", parts[2], old_path=parts[1]))
elif code == "D" and len(parts) >= 2:
out.append(PathChange("D", parts[1]))
elif len(parts) >= 2:
out.append(PathChange(code, parts[1]))
return out
def effective_paths(changes: Sequence[PathChange]) -> set[str]:
"""Paths that still collide for ownership: added/modified/renamed targets.
Deleted paths are excluded from forward collision checks but retained via
`deleted_paths` for reports.
"""
paths: set[str] = set()
for change in changes:
if change.status == "D":
continue
paths.add(change.path)
if change.status == "R" and change.old_path:
# Renames collide on both old and new until the claim scope updates.
paths.add(change.old_path)
return paths
def deleted_paths(changes: Sequence[PathChange]) -> set[str]:
deleted = {c.path for c in changes if c.status == "D"}
deleted |= {c.old_path for c in changes if c.status == "R" and c.old_path}
return {p for p in deleted if p}
def directory_overlap(a: str, b: str) -> bool:
a = a.rstrip("/")
b = b.rstrip("/")
if a == b:
return True
if a.endswith("/**"):
root = a[:-3].rstrip("/")
return b == root or b.startswith(root + "/")
if b.endswith("/**"):
root = b[:-3].rstrip("/")
return a == root or a.startswith(root + "/")
if a.endswith("/"):
a = a.rstrip("/")
return b == a or b.startswith(a + "/")
if b.endswith("/"):
b = b.rstrip("/")
return a == b or a.startswith(b + "/")
return a.startswith(b + "/") or b.startswith(a + "/")
def colliding_scopes(changed: Iterable[str], claimed_patterns: Sequence[str]) -> list[tuple[str, str]]:
hits: list[tuple[str, str]] = []
for path in changed:
for pattern in claimed_patterns:
if directory_overlap(path, pattern) or directory_overlap(pattern, path):
hits.append((path, pattern))
return hits
+90
View File
@@ -0,0 +1,90 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Contributor progress summaries and engineering handoff reports."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Iterable, Sequence
@dataclass(frozen=True)
class WorkItem:
issue: int
title: str
status: str
paths: tuple[str, ...]
notes: str = ""
@dataclass(frozen=True)
class HandoffReport:
author: str
revision: str
items: tuple[WorkItem, ...]
limitations: tuple[str, ...]
def progress_summary(items: Iterable[WorkItem]) -> str:
rows = list(items)
lines = ["# Contributor progress", "", f"items: {len(rows)}", ""]
for item in rows:
paths = ", ".join(f"`{p}`" for p in item.paths) or "(none)"
lines.append(f"- #{item.issue} [{item.status}] {item.title} — {paths}")
if item.notes:
lines.append(f" - {item.notes}")
lines.append("")
return "\n".join(lines)
def handoff_markdown(report: HandoffReport) -> str:
lines = [
"# Engineering handoff",
"",
f"- author: `{report.author}`",
f"- revision: `{report.revision}`",
"",
"## Work items",
"",
]
lines.append(progress_summary(report.items).split("\n", 2)[-1].lstrip("\n"))
if not report.items:
lines.append("(none)")
lines.append("")
lines.extend(["## Limitations", ""])
if report.limitations:
for lim in report.limitations:
lines.append(f"- {lim}")
else:
lines.append("- (none recorded)")
lines.append("")
return "\n".join(lines)
def conflict_paths(items: Sequence[WorkItem]) -> tuple[tuple[int, int, str], ...]:
"""Return overlapping path pairs between distinct open items."""
hits: list[tuple[int, int, str]] = []
open_items = [i for i in items if i.status in {"claimed", "in-progress", "open"}]
for i, a in enumerate(open_items):
for b in open_items[i + 1 :]:
for pa in a.paths:
for pb in b.paths:
if paths_overlap(pa, pb):
hits.append((a.issue, b.issue, pa if len(pa) <= len(pb) else pb))
return tuple(hits)
def paths_overlap(a: str, b: str) -> bool:
a = a.rstrip("/")
b = b.rstrip("/")
if a == b:
return True
if a.endswith("/**"):
root = a[:-3].rstrip("/")
return b == root or b.startswith(root + "/")
if b.endswith("/**"):
root = b[:-3].rstrip("/")
return a == root or a.startswith(root + "/")
if a.endswith("/"):
return b.startswith(a) or b == a.rstrip("/")
if b.endswith("/"):
return a.startswith(b) or a == b.rstrip("/")
return a.startswith(b + "/") or b.startswith(a + "/")
+172
View File
@@ -0,0 +1,172 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Independent test orchestration with structured JSON reports.
Runs listed commands, records durations and exit codes, and never promotes a
failed command to passed because output was filtered.
"""
from __future__ import annotations
import json
import time
from dataclasses import asdict, dataclass, field
from typing import Any, Sequence
from .exit_pipe import classify_status, run_preserving_status
@dataclass(frozen=True)
class SuiteSpec:
name: str
command: tuple[str, ...]
kind: str = "cpu" # cpu | gpu | other
@dataclass
class SuiteResult:
name: str
kind: str
command: list[str]
status: str
returncode: int
duration_seconds: float
stdout: str
stderr: str
reproduction: str
@dataclass
class OrchestrationReport:
suites: list[SuiteResult] = field(default_factory=list)
started_at: float = 0.0
finished_at: float = 0.0
@property
def passed(self) -> int:
return sum(1 for s in self.suites if s.status == "passed")
@property
def failed(self) -> int:
return sum(1 for s in self.suites if s.status == "failed")
@property
def ignored(self) -> int:
return sum(1 for s in self.suites if s.status == "ignored")
@property
def unexecuted(self) -> int:
return sum(1 for s in self.suites if s.status == "unexecuted")
def overall_returncode(self) -> int:
codes = [s.returncode for s in self.suites if s.status == "failed"]
if not codes:
return 0
return codes[0] if codes[0] != 0 else 1
def to_dict(self) -> dict[str, Any]:
return {
"started_at": self.started_at,
"finished_at": self.finished_at,
"duration_seconds": self.finished_at - self.started_at,
"counts": {
"passed": self.passed,
"failed": self.failed,
"ignored": self.ignored,
"unexecuted": self.unexecuted,
},
"suites": [asdict(s) for s in self.suites],
"overall_returncode": self.overall_returncode(),
}
def shell_quote(part: str) -> str:
if part == "":
return "''"
if all(c.isalnum() or c in "@%_+:=,./-" for c in part):
return part
return "'" + part.replace("'", "'\"'\"'") + "'"
def run_suites(
specs: Sequence[SuiteSpec],
*,
stop_on_fail: bool = False,
) -> OrchestrationReport:
report = OrchestrationReport(started_at=time.time())
halted = False
for spec in specs:
if halted:
report.suites.append(
SuiteResult(
name=spec.name,
kind=spec.kind,
command=list(spec.command),
status="unexecuted",
returncode=-1,
duration_seconds=0.0,
stdout="",
stderr="not executed because a previous suite failed",
reproduction=" ".join(shell_quote(p) for p in spec.command),
)
)
continue
if spec.kind == "ignored":
report.suites.append(
SuiteResult(
name=spec.name,
kind=spec.kind,
command=list(spec.command),
status="ignored",
returncode=0,
duration_seconds=0.0,
stdout="",
stderr="suite marked ignored",
reproduction=" ".join(shell_quote(p) for p in spec.command),
)
)
continue
started = time.time()
result = run_preserving_status(spec.command)
finished = time.time()
status = classify_status(result.returncode)
report.suites.append(
SuiteResult(
name=spec.name,
kind=spec.kind,
command=list(spec.command),
status=status,
returncode=result.returncode,
duration_seconds=finished - started,
stdout=result.stdout,
stderr=result.stderr,
reproduction=" ".join(shell_quote(p) for p in spec.command),
)
)
if stop_on_fail and status == "failed":
halted = True
report.finished_at = time.time()
return report
def dumps_report(report: OrchestrationReport) -> str:
return json.dumps(report.to_dict(), indent=2, sort_keys=True) + "\n"
def failure_log_excerpt(report: OrchestrationReport, *, limit: int = 40) -> str:
lines: list[str] = []
for suite in report.suites:
if suite.status != "failed":
continue
lines.append(f"## {suite.name} (exit {suite.returncode})")
lines.append(f"reproduce: {suite.reproduction}")
err = (suite.stderr or suite.stdout).splitlines()
lines.extend(err[:limit])
lines.append("")
return "\n".join(lines)
def separate_cpu_gpu(report: OrchestrationReport) -> dict[str, list[SuiteResult]]:
out = {"cpu": [], "gpu": [], "other": []}
for suite in report.suites:
bucket = suite.kind if suite.kind in out else "other"
out[bucket].append(suite)
return out
+150
View File
@@ -0,0 +1,150 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Advisory pull-request validation helpers.
Checks changed paths against an approved scope, DCO trailers, native arch
hints, changelog presence and accidental build-artifact inclusion. Advisory
only: callers decide whether to fail a gate.
"""
from __future__ import annotations
import re
from dataclasses import dataclass, field
from pathlib import PurePosixPath
from typing import Iterable, Sequence
DCO_RE = re.compile(r"^Signed-off-by:\s+\S.+\s+<\S+@\S+>\s*$", re.MULTILINE)
FULL_SHA_RE = re.compile(r"^[0-9a-f]{40}$")
ARTIFACT_SUFFIXES = (
".o", ".a", ".dylib", ".so", ".pyc", ".rlib", ".rmeta",
)
ARTIFACT_NAMES = {"__pycache__", "target", ".DS_Store"}
@dataclass
class Finding:
code: str
severity: str # advisory | blocking-candidate
message: str
@dataclass
class ValidationReport:
findings: list[Finding] = field(default_factory=list)
@property
def ok(self) -> bool:
return not any(f.severity == "blocking-candidate" for f in self.findings)
def add(self, code: str, message: str, *, severity: str = "advisory") -> None:
self.findings.append(Finding(code=code, severity=severity, message=message))
def path_in_scope(path: str, patterns: Sequence[str]) -> bool:
posix = PurePosixPath(path)
for pattern in patterns:
pat = pattern.rstrip()
if pat.endswith("/**"):
root = pat[:-3]
if path == root or path.startswith(root.rstrip("/") + "/"):
return True
elif pat.endswith("/"):
if path.startswith(pat) or path == pat.rstrip("/"):
return True
elif "*" in pat or "?" in pat:
if posix.match(pat):
return True
elif path == pat:
return True
return False
def check_scope(changed_files: Iterable[str], allowed: Sequence[str]) -> ValidationReport:
report = ValidationReport()
for path in changed_files:
if not path_in_scope(path, allowed):
report.add(
"scope",
f"changed file outside approved scope: {path}",
severity="blocking-candidate",
)
return report
def check_dco(commit_messages: Iterable[str]) -> ValidationReport:
report = ValidationReport()
for i, message in enumerate(commit_messages, start=1):
if not DCO_RE.search(message or ""):
report.add(
"dco",
f"commit {i} is missing a Signed-off-by trailer",
severity="blocking-candidate",
)
return report
def check_artifacts(changed_files: Iterable[str]) -> ValidationReport:
report = ValidationReport()
for path in changed_files:
name = PurePosixPath(path).name
if name in ARTIFACT_NAMES or any(part in ARTIFACT_NAMES for part in PurePosixPath(path).parts):
report.add("artifact", f"build artifact path included: {path}")
continue
if name.endswith(ARTIFACT_SUFFIXES):
report.add("artifact", f"build artifact suffix included: {path}")
return report
def check_changelog_required(changed_files: Iterable[str], *, require: bool = True) -> ValidationReport:
report = ValidationReport()
files = list(changed_files)
meaningful = [
f for f in files
if not f.startswith("docs/") and f != "CHANGELOG.md" and not f.startswith("tests/")
]
if require and meaningful and "CHANGELOG.md" not in files:
report.add(
"changelog",
"meaningful non-docs code changes without CHANGELOG.md",
severity="advisory",
)
return report
def check_report_commit_identity(report_sha: str, head_sha: str) -> ValidationReport:
report = ValidationReport()
if not FULL_SHA_RE.fullmatch(report_sha or ""):
report.add("evidence-sha", "test report commit is not a full 40-character SHA",
severity="blocking-candidate")
return report
if report_sha != head_sha:
report.add(
"evidence-sha",
f"test report SHA {report_sha} does not match head {head_sha}",
severity="blocking-candidate",
)
return report
def check_native_arch_strings(file_output_lines: Iterable[str]) -> ValidationReport:
"""Advisory scan of `file`/`lipo` style lines for non-arm64 host binaries."""
report = ValidationReport()
for line in file_output_lines:
lower = line.lower()
if "mach-o" not in lower:
continue
if "arm64" in lower or "aarch64" in lower:
continue
if "x86_64" in lower or "i386" in lower:
report.add(
"arch",
f"non-ARM64 Mach-O mention: {line.strip()}",
severity="blocking-candidate",
)
return report
def merge_reports(*reports: ValidationReport) -> ValidationReport:
out = ValidationReport()
for report in reports:
out.findings.extend(report.findings)
return out
+551
View File
@@ -0,0 +1,551 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Read-only RDNA2 expansion planning from existing inventories.
Reuses scripts/audit/semantic_coverage.py loaders and the checked-in AMD
snapshot, semantic registry, generated tables and status evidence. Does not
edit GPU production code. Candidate declarations are never counted as
implemented forms.
"""
from __future__ import annotations
import json
import re
import runpy
import tomllib
from collections import defaultdict
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any, Iterable, Sequence
def _load_coverage_module(root: Path):
path = root / "scripts" / "audit" / "semantic_coverage.py"
return runpy.run_path(str(path))
@dataclass(frozen=True)
class FormRef:
family: str
name: str
opcode: int
@property
def key(self) -> tuple[str, str]:
return (self.family, self.name)
@dataclass
class Candidate:
family: str
name: str
opcode: int
width: int | None
numeric_type: str | None
operand_layout: str | None
reusable_primitives: list[str] = field(default_factory=list)
missing_operand_rules: list[str] = field(default_factory=list)
missing_effects: list[str] = field(default_factory=list)
spec_refs: list[dict[str, Any]] = field(default_factory=list)
priority_batch: str = "unclassified"
priority_rank: int = 99
status: str = "unsupported"
notes: list[str] = field(default_factory=list)
@dataclass
class Inventory:
identified: int
declared: int
decoder_supported: int
reference_verified: int
metal_verified: int
unsupported: int
by_family: dict[str, dict[str, int]]
# Conventional GPU semantic-expansion file set for Codex manifests only.
# Planning does not claim or edit these paths.
DEFAULT_PERMITTED_FILES = (
"crates/isa/semantics/rdna2.toml",
"crates/isa/src/semantics_gen.rs",
"crates/decoder/src/lib.rs",
"crates/shader/",
"crates/ref/",
"tests/validation/",
"docs/status.toml",
"CHANGELOG.md",
)
DEFAULT_ACCEPTANCE = (
"cargo test --locked -p xenora-ref",
"cargo test --locked -p xenora-semantic-review",
"scripts/test-gpu.sh",
"python3 scripts/audit/semantic_coverage.py --check",
)
def load_inventories(root: Path) -> dict[str, Any]:
sc = _load_coverage_module(root)
identified = sc["load_snapshot"](root)
registry = tomllib.loads((root / sc["REGISTRY"]).read_text(encoding="utf-8"))
decoder = sc["parse_decoder"]((root / sc["DECODER"]).read_text(encoding="utf-8"))
generated = sc["parse_generated"]((root / sc["GENERATED"]).read_text(encoding="utf-8"))
decoder_forms = set(decoder) | set(generated)
declared, rules = sc["read_declarations"](registry, identified)
status = tomllib.loads((root / sc["STATUS"]).read_text(encoding="utf-8"))
_, encoded, lowered, reference, metal = _evidence_sets(sc, status, identified)
return {
"sc": sc,
"identified": identified,
"registry": registry,
"rules": rules,
"declared": declared,
"decoder": decoder_forms,
"encoded": encoded,
"lowered": lowered,
"reference": reference,
"metal": metal,
"status": status,
}
def _evidence_sets(sc, status, identified):
encoded, lowered, reference, metal = set(), set(), set(), set()
seen = set()
for row in status["instruction"]:
key = sc["status_form"](row, identified)
if key in seen:
continue
seen.add(key)
if row.get("llvm") == "three-way passed":
encoded.add(key)
lowering = row.get("lowering", "").strip().lower()
if lowering.startswith(("msl ", "resolved ", "verified ", "constant or ", "per-thread ")):
lowered.add(key)
decodes = row.get("decoded") is True
if decodes and row.get("reference") == "implemented" and row.get("cpu") == "fixture verified":
reference.add(key)
if decodes and row.get("gpu") in {"fixture verified", "fixture verified on Apple M5"}:
metal.add(key)
return seen, encoded, lowered, reference, metal
def summarize_inventory(data: dict[str, Any]) -> Inventory:
identified = data["identified"]
declared = data["declared"]
decoder = data["decoder"]
reference = data["reference"]
metal = data["metal"]
unsupported_keys = set(identified) - set(declared)
by_family: dict[str, dict[str, int]] = {}
for family, name in identified:
bucket = by_family.setdefault(family, {
"identified": 0, "declared": 0, "decoder": 0, "unsupported": 0,
"reference": 0, "metal": 0,
})
bucket["identified"] += 1
key = (family, name)
if key in declared:
bucket["declared"] += 1
if key in decoder:
bucket["decoder"] += 1
if key in unsupported_keys:
bucket["unsupported"] += 1
if key in reference:
bucket["reference"] += 1
if key in metal:
bucket["metal"] += 1
return Inventory(
identified=len(identified),
declared=len(declared),
decoder_supported=len(decoder),
reference_verified=len(reference),
metal_verified=len(metal),
unsupported=len(unsupported_keys),
by_family=dict(sorted(by_family.items())),
)
def _declared_ops(registry: dict[str, Any]) -> set[str]:
return {form.get("operation") for form in registry.get("form", []) if form.get("operation")}
def _batch_for(family: str, family_rule_names: list[str], ops: set[str]) -> tuple[str, int, str]:
"""Return (batch_id, priority_rank, status). Lower rank is higher priority."""
if family_rule_names and ops:
return f"batch-{family.lower()}-reuse-primitives", 0, "reuse-primitives"
if family_rule_names:
return f"batch-{family.lower()}-needs-primitives", 1, "needs-primitives"
return f"batch-{family.lower()}-needs-operand-rules", 2, "needs-operand-rules"
def classify_unsupported(
data: dict[str, Any],
*,
limit: int | None = None,
families: Sequence[str] | None = None,
statuses: Sequence[str] | None = None,
exclude_families: Sequence[str] | None = None,
) -> list[Candidate]:
"""Build candidates for identified forms that are not registry-declared.
Does not infer behaviour from the mnemonic. Width/type/layout are filled
only when already present on related declared forms in the same family, or
left null. Results are sorted by priority_rank then family/name.
"""
identified = data["identified"]
declared = data["declared"]
registry = data["registry"]
rules = data["rules"]
ops = _declared_ops(registry)
family_widths: dict[str, set[int]] = defaultdict(set)
family_types: dict[str, set[str]] = defaultdict(set)
for form in registry.get("form", []):
if "width" in form:
family_widths[form["family"]].add(form["width"])
if "signedness" in form:
family_types[form["family"]].add(form["signedness"])
family_filter = {f.upper() for f in families} if families else None
status_filter = {s for s in statuses} if statuses else None
excluded = {f.upper() for f in (exclude_families or ())}
candidates: list[Candidate] = []
unsupported = sorted(set(identified) - set(declared))
for family, name in unsupported:
if family_filter is not None and family.upper() not in family_filter:
continue
if family.upper() in excluded:
continue
opcode = identified[(family, name)]
reusable = sorted(op for op in ops if op)
family_rule_names = [n for n, (fam, _) in rules.items() if fam == family]
missing_rules = []
if not family_rule_names:
missing_rules.append(f"no operand_rules for family {family}")
widths = sorted(family_widths.get(family, []))
types = sorted(family_types.get(family, []))
layout = family_rule_names[0] if len(family_rule_names) == 1 else None
batch, rank, status = _batch_for(family, family_rule_names, ops)
if status_filter is not None and status not in status_filter:
continue
candidates.append(Candidate(
family=family,
name=name,
opcode=opcode,
width=widths[0] if len(widths) == 1 else None,
numeric_type=types[0] if len(types) == 1 else None,
operand_layout=layout,
reusable_primitives=reusable[:20],
missing_operand_rules=missing_rules,
missing_effects=["scc/vcc/exec effects unspecified until registry declaration"],
spec_refs=[{"document": "xml", "note": "identity from pinned AMD snapshot only"}],
priority_batch=batch,
priority_rank=rank,
status=status,
notes=[
"behaviour must come from the public AMD guide, never the mnemonic",
"candidate is not implemented",
],
))
candidates.sort(key=lambda c: (c.priority_rank, c.family, c.name, c.opcode))
if limit is not None:
candidates = candidates[:limit]
return candidates
def plan_batches(candidates: list[Candidate]) -> dict[str, list[dict[str, Any]]]:
batches: dict[str, list[dict[str, Any]]] = defaultdict(list)
for cand in candidates:
batches[cand.priority_batch].append({
"family": cand.family,
"name": cand.name,
"opcode": cand.opcode,
"status": cand.status,
"missing_operand_rules": cand.missing_operand_rules,
"reusable_primitives": cand.reusable_primitives[:5],
})
return dict(sorted(batches.items()))
def discrepancies(data: dict[str, Any]) -> list[dict[str, str]]:
"""Registry vs decoder vs verification evidence mismatches."""
issues: list[dict[str, str]] = []
declared = data["declared"]
decoder = data["decoder"]
reference = data["reference"]
metal = data["metal"]
for key in sorted(declared - decoder):
family, name = key
issues.append({
"kind": "declared-not-decoded",
"family": family,
"name": name,
"detail": "registry declaration is not present in decoder SEMANTIC_FORMS/FORM_IDS",
})
for key in sorted(decoder - declared):
family, name = key
issues.append({
"kind": "decoded-not-declared",
"family": family,
"name": name,
"detail": "decoder lists a form that is not in the semantic registry",
})
for key in sorted(reference - declared):
family, name = key
issues.append({
"kind": "reference-without-declaration",
"family": family,
"name": name,
"detail": "status marks reference verification without a registry declaration",
})
for key in sorted(metal - reference):
family, name = key
issues.append({
"kind": "metal-without-reference",
"family": family,
"name": name,
"detail": "Metal verification without matching reference evidence",
})
return issues
def reconcile_with_coverage_report(root: Path, data: dict[str, Any]) -> dict[str, Any]:
"""Compare planner inventory to canonical semantic_coverage collect_coverage.
Does not inflate planner counts. Reports per-family deltas only.
"""
sc = data["sc"]
identified = data["identified"]
registry = data["registry"]
decoder = data["decoder"]
status = data["status"]
counts, _rules = sc["collect_coverage"](identified, registry, decoder, status)
# collect_coverage tuple per family:
# Identified, Encoding-validated, Declared, Decoder-supported, IR, MSL,
# Reference-verified, Metal-verified, Unsupported operand variants
inv = summarize_inventory(data)
mismatches: list[dict[str, Any]] = []
for family, values in sorted(counts.items()):
canon_identified, _enc, canon_declared, canon_decoder, _ir, _msl, canon_ref, canon_metal, _u = values
bucket = inv.by_family.get(family, {})
pairs = (
("identified", canon_identified, bucket.get("identified", 0)),
("declared", canon_declared, bucket.get("declared", 0)),
("decoder", canon_decoder, bucket.get("decoder", 0)),
("reference", canon_ref, bucket.get("reference", 0)),
("metal", canon_metal, bucket.get("metal", 0)),
)
for field_name, canon, plan in pairs:
if canon != plan:
mismatches.append({
"family": family,
"field": field_name,
"canonical": canon,
"planner": plan,
"delta": plan - canon,
})
return {
"ok": not mismatches,
"canonical_totals": {
"identified": sum(v[0] for v in counts.values()),
"declared": sum(v[2] for v in counts.values()),
"decoder_supported": sum(v[3] for v in counts.values()),
"reference_verified": sum(v[6] for v in counts.values()),
"metal_verified": sum(v[7] for v in counts.values()),
},
"planner_totals": {
"identified": inv.identified,
"declared": inv.declared,
"decoder_supported": inv.decoder_supported,
"reference_verified": inv.reference_verified,
"metal_verified": inv.metal_verified,
},
"mismatches": mismatches,
"note": "Planner counts are not adjusted to match; mismatches must be investigated.",
}
@dataclass(frozen=True)
class ClaimScope:
"""One active claim. Families exclude those families; path-only claims
block candidates whose default permitted files overlap the claimed paths.
A claim that lists both families and paths excludes only the families —
the paths document the claim and do not blanket-block other families.
"""
families: frozenset[str] = frozenset()
paths: frozenset[str] = frozenset()
def parse_claims_file(path: Path) -> tuple[set[str], set[str]]:
"""Load excluded families and path-only claim prefixes.
Expected shape: {"claims":[{"families":["VOP2"], "paths":["crates/isa/**"]}, ...]}
or a bare list of such objects.
Returns (exclude_families, path_only_claimed_paths). Path prefixes from
claims that also name families are ignored for blocking so a SOP2+isa
claim does not suppress every other family's manifests.
"""
scopes = load_claim_scopes(path)
families: set[str] = set()
path_only: set[str] = set()
for scope in scopes:
families.update(scope.families)
if scope.families:
continue
path_only.update(scope.paths)
return families, path_only
def load_claim_scopes(path: Path) -> list[ClaimScope]:
raw = json.loads(path.read_text(encoding="utf-8"))
items = raw["claims"] if isinstance(raw, dict) and "claims" in raw else raw
if not isinstance(items, list):
raise ValueError("claims file must be a list or {\"claims\": [...]}")
scopes: list[ClaimScope] = []
for item in items:
fams = frozenset(str(f).upper() for f in (item.get("families") or []))
paths = frozenset(str(p) for p in (item.get("paths") or []))
if not fams and not paths:
continue
scopes.append(ClaimScope(families=fams, paths=paths))
return scopes
def claims_block_candidate(cand: Candidate, claimed_paths: set[str]) -> bool:
"""True if a path-only claim overlaps the default GPU expansion files."""
if not claimed_paths:
return False
for permitted in DEFAULT_PERMITTED_FILES:
for claimed in claimed_paths:
if _path_overlap(permitted, claimed):
return True
return False
def _path_overlap(a: str, b: str) -> bool:
a = a.rstrip("/")
b = b.rstrip("/")
if a.endswith("/**"):
a = a[:-3].rstrip("/")
if b.endswith("/**"):
b = b[:-3].rstrip("/")
return a == b or a.startswith(b + "/") or b.startswith(a + "/")
def build_manifests(
candidates: list[Candidate],
*,
exclude_families: Sequence[str] | None = None,
claimed_paths: Sequence[str] | None = None,
limit: int | None = None,
) -> list[dict[str, Any]]:
"""Deterministic Codex-ready implementation manifests.
Prioritises reuse-primitives, then needs-primitives, then needs-operand-rules.
Excludes active claim families and path-only claims. Does not invent semantics.
"""
excluded = {f.upper() for f in (exclude_families or ())}
claimed = set(claimed_paths or ())
manifests: list[dict[str, Any]] = []
for cand in candidates:
if cand.family.upper() in excluded:
continue
if claims_block_candidate(cand, claimed):
continue
deps: list[str] = []
if cand.status == "needs-operand-rules":
deps.append(f"define operand_rules for family {cand.family}")
if cand.status == "needs-primitives":
deps.append("add registry operation primitive before declaring this form")
if cand.status == "reuse-primitives":
deps.append("reuse existing registry primitives/operand rules; declare form from AMD guide")
deps.append("do not infer behaviour from the mnemonic")
manifest = {
"id": f"{cand.family}:{cand.name}",
"instruction": {
"family": cand.family,
"name": cand.name,
"opcode": cand.opcode,
},
"priority_rank": cand.priority_rank,
"status": cand.status,
"dependencies": deps,
"specification_references": cand.spec_refs,
"permitted_files": list(DEFAULT_PERMITTED_FILES),
"acceptance_tests": list(DEFAULT_ACCEPTANCE),
"notes": list(cand.notes),
}
manifests.append(manifest)
if limit is not None and len(manifests) >= limit:
break
return manifests
def coverage_diff(before: Inventory, after: Inventory) -> dict[str, Any]:
return {
"identified_delta": after.identified - before.identified,
"declared_delta": after.declared - before.declared,
"decoder_delta": after.decoder_supported - before.decoder_supported,
"unsupported_delta": after.unsupported - before.unsupported,
"reference_delta": after.reference_verified - before.reference_verified,
"metal_delta": after.metal_verified - before.metal_verified,
"before": asdict(before),
"after": asdict(after),
}
def dumps_candidates(candidates: list[Candidate]) -> str:
payload = {
"note": "Candidates are planning aids only; they are not implemented forms.",
"count": len(candidates),
"candidates": [asdict(c) for c in candidates],
}
return json.dumps(payload, indent=2, sort_keys=True) + "\n"
def dumps_inventory(inv: Inventory) -> str:
return json.dumps(asdict(inv), indent=2, sort_keys=True) + "\n"
def compact_inventory(inv: Inventory) -> str:
lines = [
f"identified={inv.identified} declared={inv.declared} "
f"decoder={inv.decoder_supported} unsupported={inv.unsupported} "
f"ref={inv.reference_verified} metal={inv.metal_verified}",
]
for family, bucket in inv.by_family.items():
if bucket.get("unsupported", 0) == 0 and bucket.get("declared", 0) == 0:
continue
lines.append(
f" {family}: id={bucket['identified']} decl={bucket['declared']} "
f"dec={bucket['decoder']} unsup={bucket['unsupported']}"
)
return "\n".join(lines) + "\n"
def compact_candidates(candidates: Sequence[Candidate]) -> str:
lines = [f"candidates={len(candidates)}"]
for cand in candidates:
lines.append(
f" [{cand.priority_rank}:{cand.status}] {cand.family}:{cand.name} "
f"op=0x{cand.opcode:x} batch={cand.priority_batch}"
)
return "\n".join(lines) + "\n"
def compact_manifests(manifests: Sequence[dict[str, Any]]) -> str:
lines = [f"manifests={len(manifests)}"]
for item in manifests:
inst = item["instruction"]
lines.append(
f" [{item['priority_rank']}:{item['status']}] {inst['family']}:{inst['name']} "
f"deps={len(item['dependencies'])}"
)
return "\n".join(lines) + "\n"
def write_json(path: Path, payload: Any) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+65
View File
@@ -0,0 +1,65 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Historical orchestration report comparison."""
from __future__ import annotations
import json
from dataclasses import dataclass
from typing import Any
@dataclass(frozen=True)
class SuiteDelta:
name: str
previous_status: str | None
current_status: str | None
kind: str
@dataclass(frozen=True)
class RegressionDiff:
newly_failed: tuple[SuiteDelta, ...]
newly_passed: tuple[SuiteDelta, ...]
still_failed: tuple[SuiteDelta, ...]
missing: tuple[SuiteDelta, ...]
def load_report(text: str) -> dict[str, Any]:
return json.loads(text)
def _status_map(report: dict[str, Any]) -> dict[str, tuple[str, str]]:
out: dict[str, tuple[str, str]] = {}
for suite in report.get("suites", []):
out[suite["name"]] = (suite.get("status", "unknown"), suite.get("kind", "other"))
return out
def compare_reports(previous: dict[str, Any], current: dict[str, Any]) -> RegressionDiff:
prev = _status_map(previous)
cur = _status_map(current)
newly_failed: list[SuiteDelta] = []
newly_passed: list[SuiteDelta] = []
still_failed: list[SuiteDelta] = []
missing: list[SuiteDelta] = []
for name, (status, kind) in sorted(cur.items()):
before = prev.get(name)
before_status = before[0] if before else None
if status == "failed" and before_status != "failed":
newly_failed.append(SuiteDelta(name, before_status, status, kind))
elif status == "passed" and before_status == "failed":
newly_passed.append(SuiteDelta(name, before_status, status, kind))
elif status == "failed" and before_status == "failed":
still_failed.append(SuiteDelta(name, before_status, status, kind))
for name, (status, kind) in sorted(prev.items()):
if name not in cur:
missing.append(SuiteDelta(name, status, None, kind))
return RegressionDiff(
newly_failed=tuple(newly_failed),
newly_passed=tuple(newly_passed),
still_failed=tuple(still_failed),
missing=tuple(missing),
)
def has_new_regressions(diff: RegressionDiff) -> bool:
return bool(diff.newly_failed or diff.missing)
+50
View File
@@ -0,0 +1,50 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Read-only repository health checks for contributors."""
from __future__ import annotations
from dataclasses import dataclass
from typing import Iterable
@dataclass(frozen=True)
class HealthFinding:
code: str
ok: bool
detail: str
def check_ignored_artifacts_tracked(tracked_paths: Iterable[str]) -> HealthFinding:
bad = []
for path in tracked_paths:
parts = path.split("/")
if "__pycache__" in parts or path.endswith(".pyc"):
bad.append(path)
if "/target/" in f"/{path}/" or path.startswith("target/"):
bad.append(path)
ok = not bad
detail = "no tracked build artifacts" if ok else "tracked artifacts: " + ", ".join(bad[:10])
return HealthFinding("tracked-artifacts", ok, detail)
def check_large_generated_paths(tracked_paths: Iterable[str], *, suspicious_prefixes: tuple[str, ...] = ("artifacts/",)) -> HealthFinding:
hits = [p for p in tracked_paths if any(p.startswith(pref) for pref in suspicious_prefixes)]
ok = not hits
detail = "no generated artifact paths tracked" if ok else "suspicious paths: " + ", ".join(hits[:10])
return HealthFinding("generated-paths", ok, detail)
def check_upstream_configured(remotes: Iterable[str], *, expected: str = "ranveersoni98/Xenora") -> HealthFinding:
names = set(remotes)
# Accept either a remote named upstream or origin pointing at expected.
ok = "upstream" in names or "origin" in names
detail = f"remotes={sorted(names)}; expected repo {expected}"
return HealthFinding("remotes", ok, detail)
def format_health(findings: Iterable[HealthFinding]) -> str:
lines = ["# Repository health", ""]
for finding in findings:
mark = "ok" if finding.ok else "FAIL"
lines.append(f"- [{mark}] {finding.code}: {finding.detail}")
lines.append("")
return "\n".join(lines)
+66
View File
@@ -0,0 +1,66 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Stale branch and divergent history diagnostics (read-only)."""
from __future__ import annotations
from dataclasses import asdict, dataclass
from typing import Iterable
@dataclass(frozen=True)
class BranchSync:
branch: str
upstream: str
ahead: int
behind: int
diverged: bool
stale: bool
detail: str
def classify_sync(
*,
branch: str,
upstream: str,
ahead: int,
behind: int,
stale_behind_threshold: int = 1,
) -> BranchSync:
diverged = ahead > 0 and behind > 0
stale = behind >= stale_behind_threshold
if diverged:
detail = f"diverged: ahead={ahead} behind={behind}"
elif stale:
detail = f"behind upstream by {behind}"
elif ahead > 0:
detail = f"ahead of upstream by {ahead}"
else:
detail = "in sync"
return BranchSync(
branch=branch,
upstream=upstream,
ahead=ahead,
behind=behind,
diverged=diverged,
stale=stale,
detail=detail,
)
def format_sync_reports(reports: Iterable[BranchSync]) -> str:
lines = ["# Branch synchronization", ""]
for report in reports:
if report.diverged:
mark = "DIVERGED"
elif report.stale:
mark = "STALE"
else:
mark = "ok"
lines.append(
f"- [{mark}] `{report.branch}` vs `{report.upstream}`: {report.detail}"
)
lines.append("")
return "\n".join(lines)
def as_jsonable(report: BranchSync) -> dict:
return asdict(report)
+141
View File
@@ -0,0 +1,141 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Unified verification pipeline over existing Xenora commands.
Profiles invoke repository scripts/tests; they do not reimplement them.
GPU suites run serially. Exit codes are preserved exactly.
"""
from __future__ import annotations
import hashlib
import json
import time
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any, Sequence
from .orchestrate import SuiteSpec, run_suites
PROFILES: dict[str, list[SuiteSpec]] = {
"quick": [
SuiteSpec("agent-queue-unit", ("python3", "-m", "unittest", "discover", "-s", "tests/agent_queue"), "cpu"),
SuiteSpec("qa-unit", ("python3", "-m", "unittest", "discover", "-s", "tests/qa"), "cpu"),
SuiteSpec("release-unit", ("python3", "-m", "unittest", "discover", "-s", "tests/release"), "cpu"),
],
"cpu": [
SuiteSpec("cargo-test-workspace", ("cargo", "test", "--workspace", "--locked"), "cpu"),
SuiteSpec("semantic-review", ("cargo", "test", "--locked", "-p", "xenora-semantic-review"), "cpu"),
],
"gpu": [
SuiteSpec("test-gpu", ("scripts/test-gpu.sh",), "gpu"),
],
"app": [
SuiteSpec("build-app-smoke", ("scripts/build-app.sh",), "other"),
],
"release": [
SuiteSpec("native-audit", ("scripts/audit/native.sh",), "other"),
SuiteSpec("qa-unit", ("python3", "-m", "unittest", "discover", "-s", "tests/qa"), "cpu"),
SuiteSpec("release-unit", ("python3", "-m", "unittest", "discover", "-s", "tests/release"), "cpu"),
],
}
PROFILES["full"] = (
list(PROFILES["quick"])
+ [s for s in PROFILES["cpu"]]
+ list(PROFILES["gpu"])
+ list(PROFILES["app"])
)
@dataclass
class Evidence:
profile: str
revision: str
started_at: float
finished_at: float
source_fingerprint: str
suites: list[dict[str, Any]] = field(default_factory=list)
overall_returncode: int = 0
skipped: dict[str, int] = field(default_factory=dict)
def to_dict(self) -> dict[str, Any]:
return asdict(self)
def fingerprint_sources(root: Path, paths: Sequence[Path] | None = None) -> str:
h = hashlib.sha256()
if paths is None:
files = sorted(
p for p in root.rglob("*")
if p.is_file()
and not any(part in {"target", ".git", "__pycache__", "artifacts", "node_modules"} for part in p.parts)
and (p.suffix in {".rs", ".py", ".sh", ".swift", ".toml"} or p.name == "Cargo.lock")
)[:4000]
else:
files = list(paths)
for path in files:
try:
rel = str(path.relative_to(root))
except ValueError:
rel = str(path)
h.update(rel.encode())
h.update(b"\0")
try:
h.update(path.read_bytes())
except OSError:
h.update(b"<missing>")
h.update(b"\0")
return h.hexdigest()
def run_profile(
profile: str,
*,
root: Path,
revision: str,
stop_on_fail: bool = True,
override_specs: Sequence[SuiteSpec] | None = None,
) -> Evidence:
if override_specs is None and profile not in PROFILES:
raise ValueError(f"unknown profile {profile!r}; choose from {sorted(PROFILES)}")
specs = list(override_specs) if override_specs is not None else list(PROFILES[profile])
started = time.time()
# Suites run sequentially; GPU profiles therefore never overlap.
report = run_suites(specs, stop_on_fail=stop_on_fail)
finished = time.time()
skipped = {
"ignored": report.ignored,
"unexecuted": report.unexecuted,
}
return Evidence(
profile=profile,
revision=revision,
started_at=started,
finished_at=finished,
source_fingerprint=fingerprint_sources(root),
suites=[asdict(s) for s in report.suites],
overall_returncode=report.overall_returncode(),
skipped=skipped,
)
def evidence_is_stale(evidence: Evidence, root: Path) -> bool:
return evidence.source_fingerprint != fingerprint_sources(root)
def load_evidence(text: str) -> Evidence:
data = json.loads(text)
return Evidence(
profile=data["profile"],
revision=data["revision"],
started_at=float(data["started_at"]),
finished_at=float(data["finished_at"]),
source_fingerprint=data["source_fingerprint"],
suites=list(data.get("suites", [])),
overall_returncode=int(data.get("overall_returncode", 0)),
skipped=dict(data.get("skipped", {})),
)
def dumps_evidence(evidence: Evidence) -> str:
return json.dumps(evidence.to_dict(), indent=2, sort_keys=True) + "\n"
+2
View File
@@ -0,0 +1,2 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Standalone release and packaging verification helpers."""
+145
View File
@@ -0,0 +1,145 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""CLI entry: python3 -m release <command> ..."""
from __future__ import annotations
import argparse
import json
import subprocess
import sys
from pathlib import Path
from .bundle import check_app_bundle, diagnose_codesign_output
from .macho import check_archs, check_otool_linkage, consistent_deployment_targets
from .manifest import build_manifest, dumps_manifest, license_inventory
from .readiness import (
build_report,
build_sbom,
collect_artifacts,
dumps_report,
inspect_app,
inspect_binary,
require_evidence_files,
)
def main(argv: list[str] | None = None) -> int:
argv = list(sys.argv[1:] if argv is None else argv)
p = argparse.ArgumentParser(prog="release")
sub = p.add_subparsers(dest="command", required=True)
a = sub.add_parser("check-arch")
a.add_argument("--path", required=True)
a.add_argument("--lipo", required=True, help="lipo -archs output")
l = sub.add_parser("check-linkage")
l.add_argument("--path", required=True)
l.add_argument("--otool", required=True, help="otool -L output text file or - for stdin")
b = sub.add_parser("check-bundle")
b.add_argument("--app", required=True)
m = sub.add_parser("manifest")
m.add_argument("--revision", required=True)
m.add_argument("paths", nargs="+")
lic = sub.add_parser("licenses")
lic.add_argument("--entry", action="append", default=[], help="name:license")
ready = sub.add_parser("readiness", help="build a release-readiness report")
ready.add_argument("--revision", required=True)
ready.add_argument("--app", default="")
ready.add_argument("--binary", default="")
ready.add_argument("--lipo", default="")
ready.add_argument("--otool-l", default="")
ready.add_argument("--otool-header", default="")
ready.add_argument("--codesign", default="")
ready.add_argument("--artifact", action="append", default=[])
ready.add_argument("--sbom-entry", action="append", default=[], help="name:version:license")
ready.add_argument("--evidence", action="append", default=[], help="required evidence file path")
ready.add_argument("--live", action="store_true", help="run lipo/otool/codesign on --binary/--app")
args = p.parse_args(argv)
if args.command == "check-arch":
result = check_archs(args.path, args.lipo)
json.dump({"path": result.path, "archs": list(result.archs), "ok": result.ok,
"problems": list(result.problems)}, sys.stdout, indent=2)
print()
return 0 if result.ok else 1
if args.command == "check-linkage":
text = sys.stdin.read() if args.otool == "-" else Path(args.otool).read_text(encoding="utf-8")
result = check_otool_linkage(args.path, text)
json.dump({"path": result.path, "ok": result.ok, "problems": list(result.problems)}, sys.stdout, indent=2)
print()
return 0 if result.ok else 1
if args.command == "check-bundle":
result = check_app_bundle(Path(args.app))
json.dump({"root": result.root, "ok": result.ok, "problems": list(result.problems),
"present": list(result.present)}, sys.stdout, indent=2)
print()
return 0 if result.ok else 1
if args.command == "manifest":
print(dumps_manifest(build_manifest([Path(p) for p in args.paths], revision=args.revision)), end="")
return 0
if args.command == "licenses":
entries = []
for item in args.entry:
name, lic = item.split(":", 1)
entries.append((name, lic))
print(license_inventory(entries), end="")
return 0
if args.command == "readiness":
binary_findings = []
app_findings = []
if args.live and args.binary:
lipo = subprocess.check_output(["lipo", "-archs", args.binary], text=True)
otool_l = subprocess.check_output(["otool", "-L", args.binary], text=True)
header = subprocess.check_output(["otool", "-l", args.binary], text=True)
binary_findings = inspect_binary(
path=args.binary, lipo_archs=lipo, otool_l=otool_l, otool_header=header
)
elif args.binary:
binary_findings = inspect_binary(
path=args.binary,
lipo_archs=args.lipo,
otool_l=Path(args.otool_l).read_text(encoding="utf-8") if args.otool_l else "",
otool_header=Path(args.otool_header).read_text(encoding="utf-8") if args.otool_header else "",
)
if args.app:
codesign_out = args.codesign
if args.live and not codesign_out:
codesign_out = subprocess.run(
["codesign", "-dv", "--verbose=2", args.app],
capture_output=True, text=True,
).stderr
app_findings = inspect_app(Path(args.app), codesign_out)
artifacts, artifact_findings = collect_artifacts(
[Path(p) for p in args.artifact], revision=args.revision
) if args.artifact else ([], [])
sbom_entries = []
for item in args.sbom_entry:
name, version, lic = item.split(":", 2)
sbom_entries.append((name, version, lic))
evidence_findings = require_evidence_files([Path(p) for p in args.evidence])
report = build_report(
revision=args.revision,
binary_findings=binary_findings,
app_findings=app_findings,
artifacts=artifacts,
artifact_findings=artifact_findings,
evidence_findings=evidence_findings,
sbom=build_sbom(sbom_entries),
)
print(dumps_report(report), end="")
return 0 if report.ok else 1
return 2
if __name__ == "__main__":
raise SystemExit(main())
+65
View File
@@ -0,0 +1,65 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Application bundle structure and codesign diagnostic helpers."""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Iterable
REQUIRED_APP_ENTRIES = (
"Contents/Info.plist",
"Contents/MacOS",
)
@dataclass(frozen=True)
class BundleCheck:
root: str
ok: bool
problems: tuple[str, ...]
present: tuple[str, ...]
@dataclass(frozen=True)
class CodesignDiagnosis:
path: str
ok: bool
problems: tuple[str, ...]
notes: tuple[str, ...]
def check_app_bundle(root: Path, entries: Iterable[str] | None = None) -> BundleCheck:
required = tuple(entries) if entries is not None else REQUIRED_APP_ENTRIES
present: list[str] = []
problems: list[str] = []
if not root.exists():
return BundleCheck(root=str(root), ok=False, problems=(f"missing bundle root: {root}",), present=())
if not root.is_dir():
return BundleCheck(root=str(root), ok=False, problems=(f"bundle root is not a directory: {root}",), present=())
for rel in required:
path = root / rel
if path.exists():
present.append(rel)
else:
problems.append(f"missing {rel}")
return BundleCheck(root=str(root), ok=not problems, problems=tuple(problems), present=tuple(present))
def diagnose_codesign_output(path: str, codesign_stderr_or_stdout: str) -> CodesignDiagnosis:
text = codesign_stderr_or_stdout.strip()
notes = tuple(line.strip() for line in text.splitlines() if line.strip())
problems: list[str] = []
lower = text.casefold()
if "code object is not signed at all" in lower:
problems.append("unsigned")
if "cssmerr_tp_cert_expired" in lower or "expired" in lower:
problems.append("certificate expired or reported expired")
if "errsec" in lower or "failed" in lower:
if not problems:
problems.append("codesign reported failure")
ok = not problems
if not text:
problems.append("empty codesign output")
ok = False
return CodesignDiagnosis(path=path, ok=ok, problems=tuple(problems), notes=notes)
+69
View File
@@ -0,0 +1,69 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""ARM64 Mach-O architecture and linkage inspection helpers."""
from __future__ import annotations
import re
from dataclasses import dataclass
from typing import Iterable, Sequence
FORBIDDEN_LINKAGE = ("vulkan", "moltenvk", "libvulkan")
@dataclass(frozen=True)
class ArchCheck:
path: str
archs: tuple[str, ...]
ok: bool
problems: tuple[str, ...]
@dataclass(frozen=True)
class LinkageCheck:
path: str
lines: tuple[str, ...]
ok: bool
problems: tuple[str, ...]
def parse_lipo_archs(text: str) -> tuple[str, ...]:
parts = [p for p in text.strip().split() if p]
return tuple(parts)
def check_archs(path: str, arch_text: str, *, require: Sequence[str] = ("arm64",)) -> ArchCheck:
archs = parse_lipo_archs(arch_text)
problems: list[str] = []
required = tuple(require)
if archs != required:
problems.append(f"expected archs {required}, got {archs}")
return ArchCheck(path=path, archs=archs, ok=not problems, problems=tuple(problems))
def check_otool_linkage(path: str, otool_text: str) -> LinkageCheck:
lines = tuple(line.rstrip() for line in otool_text.splitlines() if line.strip())
problems: list[str] = []
joined = "\n".join(lines).casefold()
for name in FORBIDDEN_LINKAGE:
if name in joined:
problems.append(f"forbidden linkage mention: {name}")
return LinkageCheck(path=path, lines=lines, ok=not problems, problems=tuple(problems))
_DEPLOY_RE = re.compile(r"minos|sdk|version.min", re.IGNORECASE)
def deployment_target_tokens(otool_header_text: str) -> tuple[str, ...]:
tokens: list[str] = []
for line in otool_header_text.splitlines():
if _DEPLOY_RE.search(line):
tokens.append(line.strip())
return tuple(tokens)
def consistent_deployment_targets(texts: Iterable[str]) -> tuple[bool, tuple[str, ...]]:
sets = [frozenset(deployment_target_tokens(t)) for t in texts]
if not sets:
return True, ()
first = sets[0]
ok = all(s == first for s in sets[1:])
return ok, tuple(sorted(first))
+74
View File
@@ -0,0 +1,74 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Reproducible artifact manifests, checksums and simple SBOM stubs."""
from __future__ import annotations
import hashlib
import json
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Iterable
@dataclass(frozen=True)
class ArtifactRecord:
path: str
sha256: str
size: int
@dataclass(frozen=True)
class Manifest:
revision: str
artifacts: tuple[ArtifactRecord, ...]
def to_dict(self) -> dict:
return {
"revision": self.revision,
"artifacts": [asdict(a) for a in self.artifacts],
}
def sha256_bytes(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def sha256_file(path: Path) -> ArtifactRecord:
data = path.read_bytes()
return ArtifactRecord(path=str(path), sha256=sha256_bytes(data), size=len(data))
def build_manifest(paths: Iterable[Path], *, revision: str) -> Manifest:
records = tuple(sha256_file(Path(p)) for p in paths)
return Manifest(revision=revision, artifacts=records)
def dumps_manifest(manifest: Manifest) -> str:
return json.dumps(manifest.to_dict(), indent=2, sort_keys=True) + "\n"
def license_inventory(entries: Iterable[tuple[str, str]]) -> str:
"""Build a deterministic dependency license inventory from (name, license) pairs."""
rows = sorted((name, lic) for name, lic in entries)
lines = ["# Dependency license inventory", ""]
for name, lic in rows:
lines.append(f"- `{name}`: {lic}")
lines.append("")
return "\n".join(lines)
def validate_evidence(
*,
manifest_sha_by_path: dict[str, str],
observed_sha_by_path: dict[str, str],
) -> tuple[bool, tuple[str, ...]]:
problems: list[str] = []
for path, expected in sorted(manifest_sha_by_path.items()):
got = observed_sha_by_path.get(path)
if got is None:
problems.append(f"missing artifact: {path}")
elif got != expected:
problems.append(f"checksum mismatch: {path}")
for path in sorted(observed_sha_by_path):
if path not in manifest_sha_by_path:
problems.append(f"unexpected artifact: {path}")
return not problems, tuple(problems)
+133
View File
@@ -0,0 +1,133 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Release readiness reporting from real inspection outputs.
Does not publish releases. Builds a complete readiness report from Mach-O,
bundle, codesign, checksum, license and verification evidence inputs.
"""
from __future__ import annotations
import json
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Any, Iterable, Sequence
from .bundle import check_app_bundle, diagnose_codesign_output
from .macho import check_archs, check_otool_linkage, consistent_deployment_targets
from .manifest import ArtifactRecord, build_manifest, license_inventory, sha256_file, validate_evidence
@dataclass
class ReadinessFinding:
code: str
ok: bool
detail: str
@dataclass
class ReadinessReport:
revision: str
findings: list[ReadinessFinding] = field(default_factory=list)
sbom: list[dict[str, str]] = field(default_factory=list)
artifacts: list[dict[str, Any]] = field(default_factory=list)
@property
def ok(self) -> bool:
return all(f.ok for f in self.findings)
def to_dict(self) -> dict[str, Any]:
return {
"revision": self.revision,
"ok": self.ok,
"findings": [asdict(f) for f in self.findings],
"sbom": self.sbom,
"artifacts": self.artifacts,
}
def inspect_binary(*, path: str, lipo_archs: str, otool_l: str, otool_header: str = "") -> list[ReadinessFinding]:
findings: list[ReadinessFinding] = []
arch = check_archs(path, lipo_archs)
findings.append(ReadinessFinding("arch", arch.ok, "; ".join(arch.problems) or f"archs={list(arch.archs)}"))
link = check_otool_linkage(path, otool_l)
findings.append(ReadinessFinding("linkage", link.ok, "; ".join(link.problems) or "ok"))
if otool_header:
ok, tokens = consistent_deployment_targets([otool_header])
findings.append(ReadinessFinding(
"deployment-target",
ok,
", ".join(tokens) if tokens else "no deployment tokens found",
))
return findings
def inspect_app(app_root: Path, codesign_output: str = "") -> list[ReadinessFinding]:
findings: list[ReadinessFinding] = []
bundle = check_app_bundle(app_root)
findings.append(ReadinessFinding(
"bundle",
bundle.ok,
"; ".join(bundle.problems) or f"present={list(bundle.present)}",
))
if codesign_output:
diag = diagnose_codesign_output(str(app_root), codesign_output)
findings.append(ReadinessFinding("codesign", diag.ok, "; ".join(diag.problems) or "ok"))
return findings
def build_sbom(entries: Iterable[tuple[str, str, str]]) -> list[dict[str, str]]:
"""Complete SBOM rows: name, version, license."""
rows = sorted({(n, v, lic) for n, v, lic in entries})
return [{"name": n, "version": v, "license": lic} for n, v, lic in rows]
def collect_artifacts(paths: Sequence[Path], *, revision: str) -> tuple[list[dict[str, Any]], list[ReadinessFinding]]:
manifest = build_manifest(paths, revision=revision)
artifacts = [asdict(a) for a in manifest.artifacts]
observed = {a["path"]: a["sha256"] for a in artifacts}
expected = dict(observed)
ok, problems = validate_evidence(manifest_sha_by_path=expected, observed_sha_by_path=observed)
findings = [ReadinessFinding("checksums", ok, "; ".join(problems) or f"{len(artifacts)} artifacts")]
return artifacts, findings
def require_evidence_files(paths: Sequence[Path]) -> list[ReadinessFinding]:
findings = []
for path in paths:
findings.append(ReadinessFinding(
f"evidence:{path.name}",
path.is_file(),
"present" if path.is_file() else f"missing {path}",
))
return findings
def build_report(
*,
revision: str,
binary_findings: Sequence[ReadinessFinding] = (),
app_findings: Sequence[ReadinessFinding] = (),
artifacts: Sequence[dict[str, Any]] = (),
artifact_findings: Sequence[ReadinessFinding] = (),
evidence_findings: Sequence[ReadinessFinding] = (),
sbom: Sequence[dict[str, str]] = (),
) -> ReadinessReport:
findings = list(binary_findings) + list(app_findings) + list(artifact_findings) + list(evidence_findings)
if not sbom:
findings.append(ReadinessFinding("sbom", False, "SBOM is empty; provide dependency inventory"))
else:
findings.append(ReadinessFinding("sbom", True, f"{len(sbom)} components"))
findings.append(ReadinessFinding("revision", bool(revision) and len(revision) >= 7, revision or "missing"))
return ReadinessReport(
revision=revision,
findings=findings,
sbom=list(sbom),
artifacts=list(artifacts),
)
def dumps_report(report: ReadinessReport) -> str:
return json.dumps(report.to_dict(), indent=2, sort_keys=True) + "\n"
def license_text_from_sbom(sbom: Sequence[dict[str, str]]) -> str:
return license_inventory((row["name"], row["license"]) for row in sbom)
+20
View File
@@ -25,6 +25,26 @@ cargo test --locked -p xenora-loader --features gpu-tests --test graphics_d3d12
timeout 30s cargo test --locked -p xenora-loader --features gpu-tests --test graphics_d3d12 -- \
--nocapture --test-threads=1
# The native app interface runs the trusted fixture's guest draw on Metal.
cargo test --locked -p xenora-ffi --features gpu-tests --test native_frame --no-run
timeout 30s cargo test --locked -p xenora-ffi --features gpu-tests --test native_frame -- \
--nocapture --test-threads=1
# The persistent frame loop runs the guest on its own thread and renders on Metal.
cargo test --locked -p xenora-ffi --features gpu-tests --test frame_loop --no-run
timeout 30s cargo test --locked -p xenora-ffi --features gpu-tests --test frame_loop -- \
--nocapture --test-threads=1
# Interactive guest execution with dynamic input handling and rendering (Gate 4, #276).
cargo test --locked -p xenora-ffi --features gpu-tests --test interactive --no-run
timeout 30s cargo test --locked -p xenora-ffi --features gpu-tests --test interactive -- \
--nocapture --test-threads=1
# Persistent GPU resources, dynamic texture updates, and resource retirement (Gate 5, #279).
cargo test --locked -p xenora-ffi --features gpu-tests --test resources --no-run
timeout 30s cargo test --locked -p xenora-ffi --features gpu-tests --test resources -- \
--nocapture --test-threads=1
# Native Metal known answers of the independent semantic review, including SOP2 scalar ALU
# and VOPC compares.
cargo test --locked -p xenora-semantic-review --no-run
+55
View File
@@ -0,0 +1,55 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Regression for live smoke failure: comment-only actions must not call issue edit."""
import unittest
from unittest import mock
from agent_queue import ghio
class ApplyActions(unittest.TestCase):
def test_comment_only_skips_issue_edit(self):
calls = []
def fake_gh(*args):
calls.append(list(args))
return ""
with mock.patch.object(ghio, "gh", side_effect=fake_gh):
ghio.apply_actions("o/r", [{
"issue": 2,
"add_labels": [],
"remove_labels": [],
"comment": "Claim refused for alice: file overlap with claimed task #1.",
}])
self.assertEqual(calls, [[
"issue", "comment", "2", "-R", "o/r", "--body",
"Claim refused for alice: file overlap with claimed task #1.",
]])
def test_label_change_edits_then_comments(self):
calls = []
def fake_gh(*args):
calls.append(list(args))
return ""
with mock.patch.object(ghio, "gh", side_effect=fake_gh):
ghio.apply_actions("o/r", [{
"issue": 1,
"add_labels": ["agent:claimed", "claimed-by:alice"],
"remove_labels": ["agent:ready"],
"comment": "Claimed by alice.\n<!-- agent-queue:grant -->",
}])
self.assertEqual(calls[0][:2], ["label", "create"])
self.assertEqual(calls[1][:2], ["label", "create"])
self.assertEqual(calls[2], [
"issue", "edit", "1", "-R", "o/r",
"--add-label", "agent:claimed",
"--add-label", "claimed-by:alice",
"--remove-label", "agent:ready",
])
self.assertEqual(calls[3][:3], ["issue", "comment", "1"])
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,63 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Read-only conflict prediction before a claim is posted.
Uses the same pure `claim_problem` rules as the bot, without applying labels or
posting comments. Contributors can evaluate overlap, area, dependency and
readiness failures locally before they edit files.
"""
import unittest
from agent_queue.decide import claim_problem, decide, task_index
from helpers import CFG, event, issue, state
class ConflictPredict(unittest.TestCase):
def test_predicts_overlap_without_mutating_state(self):
held = issue(1, labels=("agent:claimed", "claimed-by:gpuer", "area:gpu"),
area="gpu", files="src/gpu/**")
candidate = issue(2, labels=("agent:ready", "area:gpu"),
area="gpu", files="src/gpu/a.rs")
snap = state(held, candidate, task_comments={
"1": [{"user": "github-actions[bot]", "body": "Granted to gpuer.\n<!-- agent-queue:grant -->",
"created_at": "2026-01-10T09:00:00Z"}],
})
before = [dict(i) for i in snap["issues"]]
tasks = task_index(snap)
problem = claim_problem(tasks[2], tasks, CFG, "gpuer")
self.assertIn("file overlap with claimed task #1", problem)
self.assertEqual(snap["issues"], before)
def test_predicts_ready_when_no_conflict(self):
ready = issue(3, labels=("agent:ready", "area:qa"), area="qa", files="tests/qa/**")
tasks = task_index(state(ready))
self.assertEqual(claim_problem(tasks[3], tasks, CFG, "qaer"), "")
def test_predicts_wrong_area_and_open_dependency(self):
dep = issue(4, labels=("agent:ready", "area:cpu"), area="cpu", files="crates/loader/**")
blocked = issue(5, labels=("agent:ready", "area:qa"), area="qa",
files="docs/testing/**", deps="#4")
tasks = task_index(state(dep, blocked))
self.assertIn("not allowed to claim area:cpu", claim_problem(tasks[4], tasks, CFG, "qaer"))
self.assertIn("open dependencies: #4", claim_problem(tasks[5], tasks, CFG, "qaer"))
def test_predict_agrees_with_live_claim_decision(self):
held = issue(6, labels=("agent:claimed", "claimed-by:maint", "area:shared"),
area="shared", files="docs/interfaces.md")
ready = issue(7, labels=("agent:ready", "area:shared"),
area="shared", files="docs/interfaces.md")
snap = state(held, ready, task_comments={
"6": [{"user": "github-actions[bot]", "body": "Granted.\n<!-- agent-queue:grant -->",
"created_at": "2026-01-10T09:00:00Z"}],
})
tasks = task_index(snap)
predicted = claim_problem(tasks[7], tasks, CFG, "maint")
actions = decide(event("maint", "/claim", n=7), snap, CFG)
self.assertTrue(predicted)
self.assertEqual(len(actions), 1)
self.assertIn(predicted, actions[0]["comment"])
self.assertEqual(actions[0].get("add_labels"), [])
if __name__ == "__main__":
unittest.main()
+10
View File
@@ -134,6 +134,16 @@ class Cli(unittest.TestCase):
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual(r.stdout.strip(), "ranveersoni98/Xenora")
def test_summary_accepts_now_after_subcommand(self):
# Actions passes --now after `summary`; parent-only --now used to reject that.
with tempfile.TemporaryDirectory() as d:
state = os.path.join(d, "state.json")
dump({"issues": [], "prs": []}, state)
r = self.run_cli("summary", "--state", state, "--now", "2026-01-10T12:00:00Z")
self.assertEqual(r.returncode, 0, r.stderr)
payload = json.loads(r.stdout)
self.assertEqual(payload["generated_at"], "2026-01-10T12:00:00Z")
def test_acceptance_authorization_end_to_end(self):
from agent_queue import lease as L, tasks as T
i = issue(1)
+50
View File
@@ -0,0 +1,50 @@
# SPDX-License-Identifier: GPL-3.0-or-later
import unittest
from qa.bench_regress import (
BenchIdentity,
BenchRecord,
IncompatibleComparison,
compare_records,
)
def _rec(samples, **kwargs):
ident = BenchIdentity(
metric=kwargs.get("metric", "latency"),
unit=kwargs.get("unit", "ns"),
workload=kwargs.get("workload", "add"),
host=kwargs.get("host", "m5"),
toolchain=kwargs.get("toolchain", "rustc"),
)
return BenchRecord(identity=ident, samples=tuple(samples), revision=kwargs.get("rev", "a"))
class BenchRegress(unittest.TestCase):
def test_rejects_incompatible_identity(self):
a = _rec([10, 10, 10], workload="add")
b = _rec([10, 10, 10], workload="mul")
with self.assertRaises(IncompatibleComparison):
compare_records(a, b)
def test_noise_not_regression(self):
base = _rec([100, 100, 100, 100])
cur = _rec([101, 101, 102, 100], rev="b")
payload = compare_records(base, cur, threshold=1.10, noise_floor_ratio=0.05)
self.assertFalse(payload["regressing"])
self.assertFalse(payload["meaningful"])
def test_clear_regression(self):
base = _rec([100, 100, 100, 100])
cur = _rec([130, 131, 129, 130], rev="b")
payload = compare_records(base, cur, threshold=1.10)
self.assertTrue(payload["regressing"])
self.assertTrue(payload["meaningful"])
def test_requires_samples(self):
with self.assertRaises(ValueError):
compare_records(_rec([1]), _rec([1, 2, 3]), min_samples=3)
if __name__ == "__main__":
unittest.main()
+29
View File
@@ -0,0 +1,29 @@
# SPDX-License-Identifier: GPL-3.0-or-later
import json
import unittest
from qa.bench_stats import compare_medians, export_json, human_report, summarize
class BenchStats(unittest.TestCase):
def test_percentiles_and_export(self):
samples = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
stats = summarize(samples)
self.assertEqual(stats.count, 10)
self.assertEqual(stats.median, 5.5)
self.assertGreaterEqual(stats.p95, stats.median)
self.assertGreaterEqual(stats.p99, stats.p95)
payload = json.loads(export_json(stats, host="m5", toolchain="rustc", revision="abc", metric="gpu"))
self.assertEqual(payload["host"], "m5")
self.assertIn("median", human_report(stats, metric="gpu"))
def test_regression_threshold(self):
ok = compare_medians([10, 10, 10], [10.5, 10.4, 10.6], threshold=1.10)
self.assertFalse(ok.regressing)
bad = compare_medians([10, 10, 10], [12, 12, 12], threshold=1.10)
self.assertTrue(bad.regressing)
self.assertGreater(bad.ratio, 1.10)
if __name__ == "__main__":
unittest.main()
+29
View File
@@ -0,0 +1,29 @@
# SPDX-License-Identifier: GPL-3.0-or-later
import unittest
from qa.claim_conflict import ClaimSnapshot, format_conflicts, predict_conflicts
class ClaimConflict(unittest.TestCase):
def test_predicts_directory_overlap(self):
held = [
ClaimSnapshot(10, "alice", ("scripts/qa/",), True),
ClaimSnapshot(11, "bob", ("scripts/release/",), True),
]
hits = predict_conflicts(["scripts/qa/orchestrate.py"], held)
self.assertEqual(len(hits), 1)
self.assertEqual(hits[0].held_by, 10)
self.assertIn("overlaps claimed #10", format_conflicts(hits))
def test_ignores_unclaimed_and_disjoint(self):
held = [
ClaimSnapshot(12, "", ("scripts/qa/",), False),
ClaimSnapshot(13, "carol", ("docs/testing/infrastructure/",), True),
]
hits = predict_conflicts(["scripts/release/macho.py"], held)
self.assertEqual(hits, ())
self.assertEqual(format_conflicts(hits), "no file conflicts predicted\n")
if __name__ == "__main__":
unittest.main()
+69
View File
@@ -0,0 +1,69 @@
# SPDX-License-Identifier: GPL-3.0-or-later
import json
import os
import subprocess
import tempfile
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
ENV = {**os.environ, "PYTHONPATH": str(ROOT / "scripts")}
def run(*args: str) -> subprocess.CompletedProcess:
return subprocess.run(
["python3", "-m", *args],
cwd=ROOT,
capture_output=True,
text=True,
env=ENV,
)
class CliSmoke(unittest.TestCase):
def test_orchestrate_shlex_and_rdna2_inventory(self):
r = run("qa", "orchestrate", "--name", "ok", "--run", "python3 -c 'print(1)'")
self.assertEqual(r.returncode, 0, r.stderr)
payload = json.loads(r.stdout)
self.assertEqual(payload["counts"]["passed"], 1)
inv = run("qa", "rdna2", "inventory")
self.assertEqual(inv.returncode, 0, inv.stderr)
data = json.loads(inv.stdout)
self.assertGreater(data["identified"], data["declared"])
compact = run("qa", "rdna2", "candidates", "--status", "reuse-primitives", "--limit", "2", "--compact")
self.assertEqual(compact.returncode, 0, compact.stderr)
self.assertIn("candidates=2", compact.stdout)
recon = run("qa", "rdna2", "reconcile", "--compact")
self.assertEqual(recon.returncode, 0, recon.stderr)
self.assertIn("reconcile_ok=", recon.stdout)
with tempfile.TemporaryDirectory() as tmp:
out = Path(tmp) / "manifests.json"
man = run(
"qa", "rdna2", "manifests",
"--status", "reuse-primitives",
"--limit", "2",
"--out", str(out),
)
self.assertEqual(man.returncode, 0, man.stderr)
payload = json.loads(out.read_text(encoding="utf-8"))
self.assertEqual(payload["count"], 2)
self.assertIn("not implemented", payload["note"].lower())
def test_release_readiness_cli_negative(self):
r = run(
"release", "readiness",
"--revision", "deadbeef",
"--lipo", "x86_64",
"--binary", "/tmp/x",
"--otool-l", "/dev/null",
)
# empty otool file + x86_64 should fail readiness
self.assertNotEqual(r.returncode, 0)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,51 @@
# SPDX-License-Identifier: GPL-3.0-or-later
import json
import tempfile
import unittest
from pathlib import Path
from qa.coverage_history import historical_report, read_snapshot, snapshot_inventory, write_snapshot
from qa.rdna2_plan import Inventory
from qa.stale_branch import classify_sync, format_sync_reports
ROOT = Path(__file__).resolve().parents[2]
class CoverageHistoryStaleBranch(unittest.TestCase):
def test_snapshot_roundtrip_and_history(self):
inv = snapshot_inventory(ROOT)
with tempfile.TemporaryDirectory() as tmp:
before = Path(tmp) / "before.json"
after = Path(tmp) / "after.json"
older = Inventory(
identified=inv.identified,
declared=max(0, inv.declared - 3),
decoder_supported=inv.decoder_supported,
reference_verified=inv.reference_verified,
metal_verified=inv.metal_verified,
unsupported=inv.unsupported + 3,
by_family={},
)
write_snapshot(before, older, revision="aaa")
write_snapshot(after, inv, revision="bbb")
rev, loaded = read_snapshot(after)
self.assertEqual(rev, "bbb")
self.assertEqual(loaded.declared, inv.declared)
report = historical_report(before, after)
self.assertEqual(report["declared_delta"], inv.declared - older.declared)
self.assertEqual(report["before_revision"], "aaa")
def test_stale_and_diverged_branches(self):
ok = classify_sync(branch="main", upstream="origin/main", ahead=0, behind=0)
self.assertFalse(ok.stale)
stale = classify_sync(branch="topic", upstream="origin/main", ahead=0, behind=5)
self.assertTrue(stale.stale)
diverged = classify_sync(branch="topic", upstream="origin/main", ahead=2, behind=3)
self.assertTrue(diverged.diverged)
text = format_sync_reports([ok, stale, diverged])
self.assertIn("STALE", text)
self.assertIn("DIVERGED", text)
if __name__ == "__main__":
unittest.main()
+55
View File
@@ -0,0 +1,55 @@
# SPDX-License-Identifier: GPL-3.0-or-later
import json
import tempfile
import unittest
from pathlib import Path
from qa.cpu_coverage import (
blocker_manifest,
build_report,
compare_reports,
dumps_report,
scan_imports,
scan_opcodes,
)
ROOT = Path(__file__).resolve().parents[2]
class CpuCoverage(unittest.TestCase):
def test_scan_opcodes_positive_and_negative(self):
text = """
match opcode {
0x89 => Op::Mov,
0x90 => unimplemented!("nop"),
other => unsupported(0xFF),
}
let litter = 0xAB;
"""
entries = {e.opcode: e.status for e in scan_opcodes(text, source="t.rs")}
self.assertEqual(entries.get("89"), "supported")
self.assertEqual(entries.get("90"), "unsupported")
def test_scan_imports_kinds(self):
text = '''
fn handler() { "CreateFileW" }
let alias = forward("ReadFile");
todo!("stub for {}", "Sleep");
'''
kinds = {e.name: e.kind for e in scan_imports(text, source="imports.rs")}
self.assertEqual(kinds.get("CreateFileW"), "functional")
self.assertEqual(kinds.get("ReadFile"), "alias")
self.assertEqual(kinds.get("Sleep"), "stub")
def test_repo_report_and_blockers(self):
report = build_report(ROOT)
self.assertTrue(report.opcodes or report.imports or report.notes)
payload = json.loads(dumps_report(report))
blockers = blocker_manifest(report, limit=10)
self.assertIsInstance(blockers, list)
delta = compare_reports(payload, payload)
self.assertEqual(delta["newly_supported"], [])
if __name__ == "__main__":
unittest.main()
+44
View File
@@ -0,0 +1,44 @@
# SPDX-License-Identifier: GPL-3.0-or-later
import unittest
from qa.env_check import (
check_branch_sync,
check_git_worktree_clean,
check_llvm_tool,
check_rosetta_translated,
check_rustc_host,
check_swift_version,
check_uname_machine,
format_report,
summarize,
)
class EnvCheck(unittest.TestCase):
def test_positive_and_negative_host_checks(self):
self.assertTrue(check_uname_machine("arm64").ok)
self.assertFalse(check_uname_machine("x86_64").ok)
self.assertTrue(check_rosetta_translated("0").ok)
self.assertFalse(check_rosetta_translated("1").ok)
rust = check_rustc_host("host: aarch64-apple-darwin\n")
self.assertTrue(rust.ok)
self.assertFalse(check_rustc_host("host: x86_64-apple-darwin\n").ok)
def test_toolchain_worktree_and_report(self):
self.assertTrue(check_swift_version("Swift version 6.4\n").ok)
self.assertTrue(check_llvm_tool("/usr/bin/clang", "Apple clang version 17").ok)
self.assertFalse(check_llvm_tool("", "").ok)
self.assertTrue(check_git_worktree_clean("").ok)
self.assertFalse(check_git_worktree_clean(" M file").ok)
self.assertTrue(check_branch_sync(ahead=0, behind=0).ok)
self.assertFalse(check_branch_sync(ahead=2, behind=1).ok)
report = summarize([
check_uname_machine("arm64"),
check_branch_sync(ahead=1, behind=0),
])
self.assertFalse(report.ok)
self.assertIn("FAIL", format_report(report))
if __name__ == "__main__":
unittest.main()
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff. Show more