Compare commits

..
Author SHA1 Message Date
Ranveer Soni d6f21217a2 Merge branch 'main' into task/215-vop1-int-oracle 2026-11-24 20:27:11 +05:30
Ranveer Soni 9478795696 Merge pull request #308 from elforeign/task/215-vopc-wide-oracle
ref, validation: independent oracle for the Wave32 16-bit and 64-bit integer compares (#215)
2026-11-24 20:26:40 +05:30
elforeign 3250ae8fd1 Merge remote-tracking branch 'origin/main' into task/215-vop1-int-oracle 2026-11-24 08:51:35 -06:00
elforeign 6ff79431bc validation: swap rejections for v0, honest pending-load labels (#215)
v_swap_b32 gains rejections for v0 as SRC0 and as VDST under full EXEC.
Its outstanding-load case is a VDST read, so it is labelled as one. The
GPU gate skip names #215.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:51:35 -06:00
elforeign c1fc4d373f Merge remote-tracking branch 'origin/main' into task/215-vopc-wide-oracle 2026-11-24 08:50:10 -06:00
elforeign 1b4911ffea validation, docs: close the wide-compare review gaps (#215)
A CPU test checks that the production compiler still rejects all 28
forms, and each 64-bit form gains a rejection for v255 as VSRC1 after an
inline integer (dropping that check in the second interpreter now fails
the rejection test). Docs and counts follow.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:50:10 -06:00
Ranveer Soni a2a6a56222 Update README.md 2026-11-24 20:17:47 +05:30
elforeign 8f67a9680d scripts, changelog: VOP1 integer oracle; skip its Metal test until the translator lands (#215)
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:46:52 -06:00
elforeign 74af0d8eb9 scripts: skip the wide-compare Metal oracle in the GPU gate until the translator lands (#215)
The ignored native Metal test fails today because the translator rejects
the 16- and 64-bit compares; scripts/test-gpu.sh runs every ignored
semantic-review test, so it skips this one by name.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:46:52 -06:00
elforeign 4bc268c931 Merge remote-tracking branch 'origin/main' into task/215-vop1-int-oracle 2026-11-24 08:45:35 -06:00
elforeign 0b00fb378d docs, validation: document the 16-bit and 64-bit compare oracle subset (#215)
vector-compare.md gains section 2a for the subset the reference
interpreters accept, and no longer says the reference rejects these
forms. vopc_f_t.rs stops listing the 64-bit F/T opcodes as unsupported:
the reference accepts them now, and the check passed only because v2 of
the v[1:2] pair was uninitialized.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:44:01 -06:00
elforeign d5437c1c18 Merge remote-tracking branch 'origin/main' into task/215-vopc-wide-oracle 2026-11-24 08:43:19 -06:00
Ranveer Soni ad4d07492d Merge pull request #299 from jelly013/task/155-cpu-known-answers
test(loader): x86-64 architectural known answers from the Intel SDM (#155)
2026-11-24 20:12:42 +05:30
Ranveer Soni 65bf3ec3fc Merge pull request #293 from Swastickc/task/290-shared-gpu-context
ffi: share one Metal device and queue across frame-loop sessions (#290)
2026-11-24 20:12:20 +05:30
Ranveer Soni 0afae6fa45 Merge pull request #304 from elforeign/task/215-m27
isa, decoder, shader: move the six VOP2 logical and shift forms into the registry (#215)
2026-11-24 20:11:45 +05:30
jelly013 c586a4a82a test(loader): tighten the x86-64 known answers after review (#155)
Pin MXCSR for a flushed exact tiny result, PE for unmasked overflow and
underflow, and run the sweeps with each exception unmasked alone. Require a
refused form to stop at its exact instruction with all state unchanged,
assert the cached DBT run hits the cache, and check the fallback counter for
every straight-line case. Add a faulting zero-count memory shift.

The tighter checks expose one more defect, kept as an ignored test: an exact
unmasked overflow sets PE as well as OE.

Correct the chronology: 700 table cases were written before the CPU source
was read, and the other cases and the sweeps afterwards. The message of
1c5c320 says otherwise.

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-24 15:41:20 +01:00
elforeign d658907fd7 Merge remote-tracking branch 'origin/main' into task/215-m27
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	crates/decoder/src/lib.rs
#	crates/isa/semantics/rdna2/vop2.toml
#	crates/isa/src/lib.rs
#	crates/isa/src/semantics_gen.rs
#	crates/shader/src/lib.rs
#	docs/shaders/semantic-coverage.md
2026-11-24 08:38:00 -06:00
elforeign a2cc14d223 isa, decoder, shader, scripts: split the semantic registry per family and add encoding variants (#215) (#300)
* isa, decoder, shader: move the twelve Wave32 VOPC compares into the semantic registry (#215)

The v_cmp_{lt,eq,le,gt,ne,ge}_{i32,u32}_e32 forms from #239 are now
registry data under a new vopc_vcc operand rule (SRC0 a vector_source,
VSRC1 a VGPR, destination implicitly vcc_lo). The decoder dispatches them
through the generated VectorCompareOp instead of a hand-written opcode
table, and the hand-written VectorCompareOp struct in xenora-isa is gone.
No behaviour change: goldens, known answers and the LLVM oracle are
unchanged.

The vocabulary gains vcc = "lane_mask", allowed exactly for the VOPC rule
and required to account for the XML's implicit VCC output, and wave =
"wave32", now allowed exactly for that rule (its one entry point is the
Wave32 compute fixture ABI) and still rejected elsewhere. exec must stay
unchanged, so v_cmpx cannot be declared.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* test(vopc): independent oracle for v_cmp_{f,t}_{i32,u32}_e32 (#215)

The registry stage adds the four constant 32-bit integer VOPC compares,
which nothing could check: the reference and the second interpreter both
rejected them. Derive them from the RDNA 2 guide only (12.9 Table 61:
D = 0 / D = 1; 3.9: VCC[n] = EXEC[n] & test, fully written) under the
#239 Wave32 contract, so T writes EXEC_LO masked to existing lanes, F
writes 0, and sources keep the allowlist and initialization rules.

vopc_f_t.rs covers every SRC0 class, aliasing, full, partial and empty
EXEC with a stale VCC_LO, a partial final wave, s_cbranch_vccz on both
edges and the rejections; the native Metal part is ignored until the
translator side lands. known_answers no longer expects F and T to be
rejected.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* isa, decoder, shader: v_cmp_{f,t}_{i32,u32} through the semantic registry (#215)

Adds the four constant Wave32 VOPC compares as registry forms with the
relations f and t (guide Table 59 offsets 0 and 7), valid only for the
vopc_vcc rule, backed by false_b32/true_b32 primitives. They keep the
#239 contract: sources are decoded and checked as for every compare,
VCC_LO := EXEC & existing lanes & test, fully written, and the mask is
lane-derived. Their MSL wave mask reads no operand bits. A new
LLVM-assembled fixture covers F clearing a stale VCC, T and F under
partial EXEC, T reading vcc_lo and runtime s_cbranch_vccz on both
results; the oracle merged from task/215-vopc-oracle supplies the
reference side.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* test(vopc): cover EXEC preservation, known-0 branch, pending loads (#215)

Review found four ways F/T could be wrong and still pass: clearing EXEC
under partial EXEC, treating the empty-EXEC result as lane-derived,
ignoring an outstanding load on a source, and decoding opcode 200. Add a
case or rejection for each; each was shown failing with that break.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* isa: check VOPC relations against the Table 59 opcode layout and the VCC write direction (#215)

Review fixes. A VOPC compare's opcode must equal its group base (128
signed, 192 unsigned) plus its relation's Table 59 offset, so a row such
as V_CMP_T_I32 with relation f is rejected instead of lowering to false.
A lane_mask form now needs exactly one fieldless XML VCC operand that is
written and not read. The generator tests render the real F/T rows, and
the vector-compare doc names the file each count comes from.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* isa: split the semantic registry into one file per encoding family (#215)

crates/isa/semantics/rdna2.toml keeps the schema, architecture, snapshot
hash, cited documents and field meanings, and lists the family files under
`include`: rdna2/{sop2,sopc,sop1,vop2,vopc}.toml, each holding only the
operand rules and forms of the family it is named after. The generator
merges them in include order, and rejects a form or rule of another
family, a rule declared twice, root keys in a family file and a missing or
repeated include. The merged registry equals the former single file, and
semantics_gen.rs is byte-identical (generate_semantics.py --check passes
unchanged). The coverage report and the RDNA2 planner read the merged
registry; their output is unchanged. Parallel work on different families
no longer edits the same file.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* isa, decoder, shader: registry encoding variants; v_add_nc_u32_e64 as the first (#215)

An [[encoding_variant]] re-encodes a declared form in another family: it
names the form, the family, its opcode there and that encoding's operand
rule, and inherits the rest. The XML check runs on the inherited
declaration, and the generator rejects variants of undeclared forms, in
the form's own family, duplicates, rules that cannot encode the form and
forms that use a variant-only rule. It emits from_<family>_word and
<family>_assembly_name on the base enum and one FORMS row per variant.

rdna2/vop3.toml declares the vop3_vgpr2 rule (the subset the hand-written
decoder accepted: VGPR sources, no modifiers, unused SRC2) and the VOP3
encoding of V_ADD_NC_U32. The decoder dispatches it through
VectorAluOp::from_vop3_word into Instruction::VectorAluVop3, which replaces
AddNoCarryU32; the shader lowers it through the VOP2 form's template and
still admits only v_add_nc_u32_e64 inside a runtime s_cbranch_vccz region.
Goldens, known answers and the LLVM oracle are unchanged.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* isa, scripts: review fixes for the registry split and encoding variants (#215)

- Includes must be `<root stem>/<family>.toml`, so a family file cannot
  live outside the registry directory or be aliased past the repeat
  guard. The coverage report (and through it the RDNA2 planner) now uses
  the generator's loader, so the family-file guards apply to every
  consumer.
- A variant's explicit XML operand formats, destination included, must
  equal its base encoding's; malformed variant fields are diagnosed
  instead of raising.
- Variants get their own generated enum (VectorAluVop3Op: from_word,
  base, assembly_name, semantics), so Instruction::VectorAluVop3 cannot
  name an undeclared encoding and formatting cannot panic.
- The planner no longer counts a variant-only operand rule as a rule that
  can host new forms of its family (V_FMA_F32 was shown as reuse-ready).
- The isa test checks that no first word of another 64-bit family
  (VOP3B) selects a VOP3 variant; docs describe the variant files.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* isa, scripts: second round of registry review fixes (#215)

- A family file must be a regular file directly in the registry
  directory: links (and so second names for one file) are rejected.
- Variant operand formats are compared by role (destination, then the
  sources in rule order), not by XML row order.
- Malformed spec and verify values are diagnosed instead of raising.
- vop3_vgpr2 declares variant_only = true in the data; the planner reads
  that flag instead of inferring it from which entries use the rule.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* isa: third round of registry review fixes (#215)

- The family directory must not be a link, and two includes must not be
  hard links to one file.
- The role-based format comparison skips malformed rules (they keep their
  rule diagnostic instead of raising), and its test now reproduces the
  row-order case the old comparison got wrong.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* isa: fourth round of registry review fixes (#215)

A self-referential family-directory link is reported instead of raising,
a malformed rule destination field is a rule diagnostic in the XML check
too, and the row-order test asserts a fully valid registry so it catches
the old row-order comparison.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* isa, scripts: registry loader and variant validation give diagnostics, not tracebacks (#215)

- A standalone registry (no include) no longer needs a family directory.
- A variant of an incomplete form reports the form instead of a KeyError.
- A non-array encoding_variant, or a non-table entry, is a diagnostic in
  the loader, the validator and the coverage report.
Each case has a test that fails on the previous code. The split-registry
test now compares the whole merged result with a hand concatenation, and
vop3.toml cites guide 12.7.1 for the VOP3 opcode offset.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* isa, scripts: two more registry crash paths become diagnostics (#215)

- A variant whose first duplicate base form is incomplete: the completeness
  check and the XML check now use the same base row (no KeyError).
- qa rdna2 inventory and rank report a malformed encoding_variant (missing
  'of', non-string operands) as an error with exit 2, not a traceback; the
  coverage reader checks the field types.
Each has a test that fails on the previous code.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

---------

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:37:03 -06:00
elforeign 980436a963 Merge commit '263284f' into task/215-m27 2026-11-24 08:35:57 -06:00
elforeign d6b751976d docs, shader, isa: review fixes for the VOP2 logical and shift move (#215)
The registry doc states where a reversed shift takes its count and which
side masks it, and that a family may have several operand rules; the
runtime-region rejection message and a test comment no longer call the
six forms hand-written.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:35:00 -06:00
elforeign 263284ff4f isa, scripts: two more registry crash paths become diagnostics (#215)
- A variant whose first duplicate base form is incomplete: the completeness
  check and the XML check now use the same base row (no KeyError).
- qa rdna2 inventory and rank report a malformed encoding_variant (missing
  'of', non-string operands) as an error with exit 2, not a traceback; the
  coverage reader checks the field types.
Each has a test that fails on the previous code.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:34:00 -06:00
elforeign e1e261ea82 isa, decoder, shader: move the six VOP2 logical and shift forms into the registry (#215)
v_and_b32, v_or_b32, v_xor_b32, v_lshlrev_b32, v_lshrrev_b32 and
v_ashrrev_i32 (_e32) are now registry forms under a new operand rule
vop2_vgpr2: both sources VGPRs, the subset the hand-written decoder
accepted. The rule shares the VectorAluOp enum with vop2_vgpr; the
generator renders one enum per shared rule set and an operand_rule()
the decoder dispatches on. VectorBinary gains And, Or, Xor and the three
shifts with the count masked to S0[4:0]; the shifts declare reversed
sources, and the generator now checks the XML count format on SRC0 for
reversed forms. The six hand-written Instruction variants, decoder arms
and shader Binary variants are removed; the runtime-region allowlist
admits exactly the same six forms.

No behaviour change: 132,608 VOP2/VOP1/SOP1 words decode to the same
text, length and error before and after; the MSL goldens are unchanged.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:30:54 -06:00
elforeign f4c4b5f9d0 Merge remote-tracking branch 'origin/main' into task/215-vop1-int-oracle
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:29:04 -06:00
elforeign c5238a83a3 Tighten the VOP1 checks the review found weak
A fresh review showed that the swap max-register cases saw only one of
the two writes, the flag cases could not see a VCC rotation, the swap
SRC0 sweep could pass on a failed SGPR read, and no case read or wrote a
VGPR with a load outstanding. Add the other-register reads, a partial
VCC_LO seed, a decode-level check of every swap SRC0 selector and twelve
pending-load rejections.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:28:45 -06:00
elforeign de536c033b Merge remote-tracking branch 'origin/main' into task/215-registry-split 2026-11-24 08:27:07 -06:00
elforeign eb85731d5d metal: retire command buffers on completion (#135) (#301)
* metal: time each host stage of a compute dispatch

The Apple M5 benchmark shows ~215 us host wall per translated dispatch
against ~1.4 us of GPU time, with ~170 us unexplained around submission.
Record buffer allocation, encoding, commit, waitUntilCompleted and
readback in RunProfile and export them, with the remainder, in the
benchmark's results.json and a new report table, so the cost can be
attributed before changing command-buffer retirement (#135).

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* metal: retire command buffers on completion (#135)

Every compute dispatch committed and then blocked in waitUntilCompleted,
which the stage timers show is ~94% of the host time not spent compiling
(launch ~78 us and wake ~58 us around ~7 us of GPU work on an M5 Pro).
A caller with several dispatches paid that round trip for each one.

Add submit_words, which commits without blocking and returns a
Submission token, and wait, which collects the result. Command buffers
now use unretained references: an in-flight table owns the pipeline,
buffers, textures and sampler until Metal reports the buffer Completed
or Error. A sweep on every submit and wait then frees those resources,
keeping the result for a live token and discarding it for a dropped
one. At most 16 submissions hold GPU resources; the next submit
returns an in-flight limit error instead of blocking. The existing
synchronous calls run as submit plus wait and keep their results and
error names. The benchmark adds a batched row: 8 dispatches with one
wait each versus 8 synchronous runs.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

---------

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:26:36 -06:00
elforeign 06ded40d54 isa, scripts: registry loader and variant validation give diagnostics, not tracebacks (#215)
- A standalone registry (no include) no longer needs a family directory.
- A variant of an incomplete form reports the form instead of a KeyError.
- A non-array encoding_variant, or a non-table entry, is a diagnostic in
  the loader, the validator and the coverage report.
Each case has a test that fails on the previous code. The split-registry
test now compares the whole merged result with a hand concatenation, and
vop3.toml cites guide 12.7.1 for the VOP3 opcode offset.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:26:23 -06:00
elforeign 22e1864b36 Clarify what the VOP1 rejection sweeps establish
The guide-only cross-check noted that the opcode sweep cannot isolate why
a form is refused and that the SRC0 rejections are the accepted subset,
not a guide limit; say so. Also name the bit-position pattern type for
clippy.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:24:53 -06:00
elforeign 21da49b109 Merge remote-tracking branch 'origin/main' into task/215-registry-split
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
#	crates/decoder/src/lib.rs
#	crates/isa/generate_semantics.py
#	crates/isa/semantics/rdna2.toml
#	crates/isa/src/lib.rs
#	crates/isa/src/semantics.rs
#	crates/isa/src/semantics_gen.rs
#	crates/isa/tests/semantics.rs
#	docs/shaders/semantic-coverage.md
#	docs/shaders/vector-compare.md
#	tests/semantics_generator/test_generate_semantics.py
2026-11-24 08:24:19 -06:00
elforeign 175335e1f6 Add a guide-derived oracle for the VOP1 integer forms
Issue #215 slice S12: the reference and the second interpreter now decode
and run v_not_b32, v_bfrev_b32, v_ffbh_u32, v_ffbl_b32, v_ffbh_i32 (SRC0:
SGPR, vcc_lo, inline integer, literal or VGPR) and v_swap_b32 (VGPR SRC0),
all _e32, from the RDNA 2 ISA guide section 12.8 pseudocode. The new
vop1_integer test checks both against expectations written separately from
the guide, and checks that both refuse the other SRC0 selectors and every
other VOP1 opcode at the same word. Float forms, lane-crossing and
M0-relative forms, and V_SAT_PK_U8_I16 (its guide entry does not define
sat8) stay unsupported.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:22:51 -06:00
elforeign b37a859cd6 isa, decoder, shader: Wave32 VOPC integer compares through the semantic registry, plus v_cmp_{f,t}_{i32,u32} (#215) (#295)
* isa, decoder, shader: move the twelve Wave32 VOPC compares into the semantic registry (#215)

The v_cmp_{lt,eq,le,gt,ne,ge}_{i32,u32}_e32 forms from #239 are now
registry data under a new vopc_vcc operand rule (SRC0 a vector_source,
VSRC1 a VGPR, destination implicitly vcc_lo). The decoder dispatches them
through the generated VectorCompareOp instead of a hand-written opcode
table, and the hand-written VectorCompareOp struct in xenora-isa is gone.
No behaviour change: goldens, known answers and the LLVM oracle are
unchanged.

The vocabulary gains vcc = "lane_mask", allowed exactly for the VOPC rule
and required to account for the XML's implicit VCC output, and wave =
"wave32", now allowed exactly for that rule (its one entry point is the
Wave32 compute fixture ABI) and still rejected elsewhere. exec must stay
unchanged, so v_cmpx cannot be declared.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* test(vopc): independent oracle for v_cmp_{f,t}_{i32,u32}_e32 (#215)

The registry stage adds the four constant 32-bit integer VOPC compares,
which nothing could check: the reference and the second interpreter both
rejected them. Derive them from the RDNA 2 guide only (12.9 Table 61:
D = 0 / D = 1; 3.9: VCC[n] = EXEC[n] & test, fully written) under the
#239 Wave32 contract, so T writes EXEC_LO masked to existing lanes, F
writes 0, and sources keep the allowlist and initialization rules.

vopc_f_t.rs covers every SRC0 class, aliasing, full, partial and empty
EXEC with a stale VCC_LO, a partial final wave, s_cbranch_vccz on both
edges and the rejections; the native Metal part is ignored until the
translator side lands. known_answers no longer expects F and T to be
rejected.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* isa, decoder, shader: v_cmp_{f,t}_{i32,u32} through the semantic registry (#215)

Adds the four constant Wave32 VOPC compares as registry forms with the
relations f and t (guide Table 59 offsets 0 and 7), valid only for the
vopc_vcc rule, backed by false_b32/true_b32 primitives. They keep the
#239 contract: sources are decoded and checked as for every compare,
VCC_LO := EXEC & existing lanes & test, fully written, and the mask is
lane-derived. Their MSL wave mask reads no operand bits. A new
LLVM-assembled fixture covers F clearing a stale VCC, T and F under
partial EXEC, T reading vcc_lo and runtime s_cbranch_vccz on both
results; the oracle merged from task/215-vopc-oracle supplies the
reference side.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* test(vopc): cover EXEC preservation, known-0 branch, pending loads (#215)

Review found four ways F/T could be wrong and still pass: clearing EXEC
under partial EXEC, treating the empty-EXEC result as lane-derived,
ignoring an outstanding load on a source, and decoding opcode 200. Add a
case or rejection for each; each was shown failing with that break.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

* isa: check VOPC relations against the Table 59 opcode layout and the VCC write direction (#215)

Review fixes. A VOPC compare's opcode must equal its group base (128
signed, 192 unsigned) plus its relation's Table 59 offset, so a row such
as V_CMP_T_I32 with relation f is rejected instead of lowering to false.
A lane_mask form now needs exactly one fieldless XML VCC operand that is
written and not read. The generator tests render the real F/T rows, and
the vector-compare doc names the file each count comes from.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

---------

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:22:04 -06:00
elforeign 714efd873b qa: rank RDNA2 expansion batches by forms unlocked per missing piece of work (#215) (#298)
Adds `qa rdna2 rank`: each undeclared identified form gets an unlock key
from its XML identity and operand shape (encoding variant of a declared
form, new operand rule, or new primitive), forms are grouped by key and
the groups ranked by count over a documented planning cost (1, 2, 4).
Claimed families and paths are excluded, float groups are marked and can
be left out with --no-float, and the output is deterministic. Reuses the
planner's inventory and claim parsing; writes nothing unless --out.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:18:13 -06:00
elforeign 06d895ec23 test(vopc): close review gaps in the 64-bit oracle (#215)
The fresh review found the independent interpreter accepted v255 as a
VSRC1 pair base when SRC0 was an SGPR pair (and overflowed at run time),
and that four checks could pass with a wrong implementation: overlapping
and highest pairs decided by the high dword alone, a second wave equal
to the first, and a known-zero vccz branch over an unread SGPR. Fix the
interpreter, add both rejections, and make each case observable.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:14:28 -06:00
elforeign a359956033 refactor(ref): keep Op::Compare for 32-bit forms, add Op::WideCompare (#215)
The decoder's gfx1030 test builds Op::Compare from its own decode, so
adding a width argument broke that crate's test build. Keep the 32-bit
variant as it was and carry 16- and 64-bit forms in a new variant that
shares the same evaluation.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:11:54 -06:00
elforeign 625e26affc isa: fourth round of registry review fixes (#215)
A self-referential family-directory link is reported instead of raising,
a malformed rule destination field is a rule diagnostic in the XML check
too, and the row-order test asserts a fully valid registry so it catches
the old row-order comparison.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:10:51 -06:00
elforeign 01a8445412 test(vopc): check pair halves with no active lane; tighten guide notes (#215)
A reference that checked only the low register of a 64-bit pair still
passed every case, because an executing lane reads both halves anyway.
The difference shows only when EXEC_LO enables just absent lanes, so add
that rejection per 64-bit form. The guide-only cross-check also pointed
out that odd SGPR bases are illegal per 3.6.3 (not unsettled), that the
negative inline bit patterns are a reading of Table 20, and that "empty
EXEC reads nothing" is the contract's rule; say so in the module notes.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:10:26 -06:00
elforeign 06614f2219 isa: third round of registry review fixes (#215)
- The family directory must not be a link, and two includes must not be
  hard links to one file.
- The role-based format comparison skips malformed rules (they keep their
  rule diagnostic instead of raising), and its test now reproduces the
  row-order case the old comparison got wrong.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:09:16 -06:00
elforeign 93d26d6e45 test(vopc): independent oracle for 16- and 64-bit integer compares (#215)
B1 adds v_cmp_{lt..ge}_{i16,u16}_e32 and v_cmp_{f..t}_{i64,u64}_e32 as
registry forms. To check them without trusting the registry, decoder or
shader, both interpreters now decode and evaluate the 28 forms from the
RDNA 2 guide alone: 16-bit forms read bits 15:0 and ignore the upper
half, 64-bit forms read register pairs low dword first, inline integers
keep their value at the operand width, and VCC_LO = EXEC & lanes & test.
Points the guide does not settle (literals, vcc as a pair, odd SGPR
bases, v255 as a pair base) are rejected. vopc_wide.rs derives the
expected lanes per form: 6212 cases on each interpreter, 1128 rejections.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:08:00 -06:00
elforeign 846589abce isa, scripts: second round of registry review fixes (#215)
- A family file must be a regular file directly in the registry
  directory: links (and so second names for one file) are rejected.
- Variant operand formats are compared by role (destination, then the
  sources in rule order), not by XML row order.
- Malformed spec and verify values are diagnosed instead of raising.
- vop3_vgpr2 declares variant_only = true in the data; the planner reads
  that flag instead of inferring it from which entries use the rule.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:06:26 -06:00
jelly013 1c5c320437 test(loader): x86-64 architectural known answers from the Intel SDM (#155)
Add 727 cases and definition-based sweeps for the guest CPU, derived from
the Intel SDM (revision 093) before the CPU code was read. The interpreter
and the DBT run the same cases.

588 cases are verified, 133 use forms both engines refuse, and four ignored
tests state open defects: stale DBT blocks after the guest rewrites code,
the address of a page-crossing fault, and the fault class of a
non-canonical address and of an instruction over 15 bytes.

Signed-off-by: jelly013 <22855910+jelly013@users.noreply.github.com>
2026-11-24 15:02:24 +01:00
elforeign 6bc88d6c51 isa, scripts: review fixes for the registry split and encoding variants (#215)
- Includes must be `<root stem>/<family>.toml`, so a family file cannot
  live outside the registry directory or be aliased past the repeat
  guard. The coverage report (and through it the RDNA2 planner) now uses
  the generator's loader, so the family-file guards apply to every
  consumer.
- A variant's explicit XML operand formats, destination included, must
  equal its base encoding's; malformed variant fields are diagnosed
  instead of raising.
- Variants get their own generated enum (VectorAluVop3Op: from_word,
  base, assembly_name, semantics), so Instruction::VectorAluVop3 cannot
  name an undeclared encoding and formatting cannot panic.
- The planner no longer counts a variant-only operand rule as a rule that
  can host new forms of its family (V_FMA_F32 was shown as reuse-ready).
- The isa test checks that no first word of another 64-bit family
  (VOP3B) selects a VOP3 variant; docs describe the variant files.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 08:01:18 -06:00
elforeign 516976fb9f isa, decoder, shader: registry encoding variants; v_add_nc_u32_e64 as the first (#215)
An [[encoding_variant]] re-encodes a declared form in another family: it
names the form, the family, its opcode there and that encoding's operand
rule, and inherits the rest. The XML check runs on the inherited
declaration, and the generator rejects variants of undeclared forms, in
the form's own family, duplicates, rules that cannot encode the form and
forms that use a variant-only rule. It emits from_<family>_word and
<family>_assembly_name on the base enum and one FORMS row per variant.

rdna2/vop3.toml declares the vop3_vgpr2 rule (the subset the hand-written
decoder accepted: VGPR sources, no modifiers, unused SRC2) and the VOP3
encoding of V_ADD_NC_U32. The decoder dispatches it through
VectorAluOp::from_vop3_word into Instruction::VectorAluVop3, which replaces
AddNoCarryU32; the shader lowers it through the VOP2 form's template and
still admits only v_add_nc_u32_e64 inside a runtime s_cbranch_vccz region.
Goldens, known answers and the LLVM oracle are unchanged.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 07:53:50 -06:00
elforeign 2384bed8b4 isa: split the semantic registry into one file per encoding family (#215)
crates/isa/semantics/rdna2.toml keeps the schema, architecture, snapshot
hash, cited documents and field meanings, and lists the family files under
`include`: rdna2/{sop2,sopc,sop1,vop2,vopc}.toml, each holding only the
operand rules and forms of the family it is named after. The generator
merges them in include order, and rejects a form or rule of another
family, a rule declared twice, root keys in a family file and a missing or
repeated include. The merged registry equals the former single file, and
semantics_gen.rs is byte-identical (generate_semantics.py --check passes
unchanged). The coverage report and the RDNA2 planner read the merged
registry; their output is unchanged. Parallel work on different families
no longer edits the same file.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 07:49:07 -06:00
elforeign ef90105a26 isa: check VOPC relations against the Table 59 opcode layout and the VCC write direction (#215)
Review fixes. A VOPC compare's opcode must equal its group base (128
signed, 192 unsigned) plus its relation's Table 59 offset, so a row such
as V_CMP_T_I32 with relation f is rejected instead of lowering to false.
A lane_mask form now needs exactly one fieldless XML VCC operand that is
written and not read. The generator tests render the real F/T rows, and
the vector-compare doc names the file each count comes from.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 07:43:08 -06:00
elforeign e95b0a055d Merge commit '8909b99' into task/215-vopc 2026-11-24 07:40:30 -06:00
elforeign 8909b99ece test(vopc): cover EXEC preservation, known-0 branch, pending loads (#215)
Review found four ways F/T could be wrong and still pass: clearing EXEC
under partial EXEC, treating the empty-EXEC result as lane-derived,
ignoring an outstanding load on a source, and decoding opcode 200. Add a
case or rejection for each; each was shown failing with that break.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 07:39:24 -06:00
elforeign b559fb575c isa, decoder, shader: v_cmp_{f,t}_{i32,u32} through the semantic registry (#215)
Adds the four constant Wave32 VOPC compares as registry forms with the
relations f and t (guide Table 59 offsets 0 and 7), valid only for the
vopc_vcc rule, backed by false_b32/true_b32 primitives. They keep the
#239 contract: sources are decoded and checked as for every compare,
VCC_LO := EXEC & existing lanes & test, fully written, and the mask is
lane-derived. Their MSL wave mask reads no operand bits. A new
LLVM-assembled fixture covers F clearing a stale VCC, T and F under
partial EXEC, T reading vcc_lo and runtime s_cbranch_vccz on both
results; the oracle merged from task/215-vopc-oracle supplies the
reference side.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 07:38:55 -06:00
elforeign f916998f10 Merge branch 'task/215-vopc-oracle' into task/215-vopc 2026-11-24 07:37:55 -06:00
Swastick Chowdhury e3bbc955bc ffi: share one Metal device and queue across frame-loop sessions (#290)
Each frame-loop session opened its own Metal command queue. The GPU
driver allocates a per-queue working set on the first command buffer
(about 45 MiB on an Apple M5 with validation) and frees it
asynchronously 10-50 ms after the queue is released, so the footprint
read right after a session ended swung by about 50 MiB and the
repeated-sessions footprint test failed intermittently (5 of 30 runs).
There was no leak. Sessions now share one process-wide NativeCompute,
which is Send + Sync, so the working set is allocated once and kept.

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

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 19:07:18 +05:30
elforeign 1ac4f82d7a test(vopc): independent oracle for v_cmp_{f,t}_{i32,u32}_e32 (#215)
The registry stage adds the four constant 32-bit integer VOPC compares,
which nothing could check: the reference and the second interpreter both
rejected them. Derive them from the RDNA 2 guide only (12.9 Table 61:
D = 0 / D = 1; 3.9: VCC[n] = EXEC[n] & test, fully written) under the
#239 Wave32 contract, so T writes EXEC_LO masked to existing lanes, F
writes 0, and sources keep the allowlist and initialization rules.

vopc_f_t.rs covers every SRC0 class, aliasing, full, partial and empty
EXEC with a stale VCC_LO, a partial final wave, s_cbranch_vccz on both
edges and the rejections; the native Metal part is ignored until the
translator side lands. known_answers no longer expects F and T to be
rejected.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 07:34:38 -06:00
elforeign 544ee8de83 isa, decoder, shader: move the twelve Wave32 VOPC compares into the semantic registry (#215)
The v_cmp_{lt,eq,le,gt,ne,ge}_{i32,u32}_e32 forms from #239 are now
registry data under a new vopc_vcc operand rule (SRC0 a vector_source,
VSRC1 a VGPR, destination implicitly vcc_lo). The decoder dispatches them
through the generated VectorCompareOp instead of a hand-written opcode
table, and the hand-written VectorCompareOp struct in xenora-isa is gone.
No behaviour change: goldens, known answers and the LLVM oracle are
unchanged.

The vocabulary gains vcc = "lane_mask", allowed exactly for the VOPC rule
and required to account for the XML's implicit VCC output, and wave =
"wave32", now allowed exactly for that rule (its one entry point is the
Wave32 compute fixture ABI) and still rejected elsewhere. exec must stay
unchanged, so v_cmpx cannot be declared.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 07:33:50 -06:00
Ranveer Soni 6d073a99b5 Merge pull request #294 from ranveersoni98/feat/infra-phase3-compat
Feat/infra phase3 compat
2026-11-24 18:57:23 +05:30
Ranveer Soni 60bfaff97e wip(qa): checkpoint compatibility gap analysis
Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 18:55:53 +05:30
Ranveer Soni b29a504506 feat(qa): add typed runtime service inventory from services.txt.
Report implemented, partial and stub services separately from API-set aliases; do not invent independent verification.

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 18:53:27 +05:30
Ranveer Soni b2a36e9c16 feat(qa): add authoritative x86 CPU inventory from the instruction registry.
Replace heuristic opcode scanning for Phase III planning with generate_x86.load over instructions.toml, native/shared partitions from dbt.rs, and a separate unsupported catalog.

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

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

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

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

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

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

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

Refs #201, #270

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

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

Fix both name reads:

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

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

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

Closes #270

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

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

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

Refs #127, #128

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

Implement them in the interpreter:

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

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

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

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

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

Closes #66

Signed-off-by: Swastick Chowdhury <28708247+Swastickc@users.noreply.github.com>
2026-11-24 17:37:02 +05:30
Swastick Chowdhury 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
jelly013 dce37dab18 cpu: add SSE2 state, moves and packed integer forms
Add XMM0-XMM15 and MXCSR to the guest state and extend the registry with
mandatory prefixes, so the shared decoder covers the SSE and SSE2 moves and
packed integer operations. Reject opcodes where 0x66 could be both an
operand size and a mandatory prefix.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Signed-off-by: Ranveer Soni <git@ranveersoni.me>
2026-11-24 16:09:41 +05:30
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
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
187 changed files with 55347 additions and 3913 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
+45 -1
View File
@@ -9,8 +9,40 @@ exact revision and known limitations.
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
remains unsupported.
### Added
### Changed
- Moved the six hand-written gfx1030 VOP2 logical and shift forms (`v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`, `v_ashrrev_i32`, AMD guide section 12.7) into the semantic registry under a new VGPR-only operand rule `vop2_vgpr2`, with no behaviour change: a sweep of 132,608 VOP2, VOP1 and SOP1 words decodes to the same text, length and error before and after, the MSL goldens are unchanged, and the runtime-region allowlist admits exactly the same six forms. The per-lane `VectorBinary` gained `And`, `Or`, `Xor` and the three shifts (count masked to S0[4:0]); 6 hand-written instruction variants and their decoder and lowering arms are gone (17 hand-written forms remain). Part of #215.
- Added non-blocking Metal compute submission through `submit_words` and `wait`, with completion-aware resource retirement and a sixteen-dispatch in-flight limit. Synchronous calls keep their existing behavior. The benchmark reports the host submission split and compares synchronous and pipelined batches.
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
### Added
- Added an independent guide-derived oracle for the Wave32 16-bit (`v_cmp_{lt..ge}_{i16,u16}_e32`) and 64-bit (`v_cmp_{f..t}_{i64,u64}_e32`) integer compares in the reference and the second interpreter (6,212 lane cases, 1,208 rejections; contract in `docs/shaders/vector-compare.md` section 2a). The decoder and translator still reject these forms, and native Metal agreement is not yet shown. Part of #215.
- Added `python3 -m qa rdna2 rank` to the read-only RDNA2 planner: it groups undeclared gfx1030 forms by the piece of work that would unlock them (an encoding variant of a declared form, a new operand rule, or a new primitive, from XML identity and operand shape only) and ranks the groups by forms per estimated cost, excluding claimed scopes, with `--no-float` to leave out floating-point groups until the FP contract exists (part of #215).
- Added authoritative read-only x86-64 CPU inventory CLI (`python3 -m qa cpu-inventory`) over `crates/loader/x86/instructions.toml` via `generate_x86.load`, with opcode-map/prefix/operand summaries, native vs shared-semantic operation partitions from `dbt.rs`, fixture mnemonic evidence and a separate unsupported catalog. Does not count candidates as implemented. Covered by `tests/qa/test_cpu_inventory.py`.
- Added typed runtime inventory CLI (`python3 -m qa runtime-inventory`) over `crates/loader/runtime/services.txt`, reporting implemented/partial/stub services separately from API-set aliases and leaving independently-verified empty unless recorded. Covered by `tests/qa/test_runtime_inventory.py`.
- Added `crates/loader/tests/cpu_known_answers.rs` (#155): 736 x86-64 cases whose results, flags, MXCSR state and faults come from the Intel SDM, with the AMD APM for some MXCSR flags, plus arithmetic, shift, packed-integer, multiply, divide and floating-point sweeps computed from the manuals' definitions. 700 cases were written before the CPU source was read; the rest and the sweeps came afterwards. The interpreter and the DBT both run them; the DBT route (ARM64 code or Rust helper) is confirmed by the fallback counter for straight-line cases and predicted for the others. 592 cases are verified, 133 use forms both engines refuse, and eleven, plus a self-modifying-code test, record open defects in five ignored tests: the reported address of a page-crossing fault, the fault class of a non-canonical address and of an instruction over 15 bytes, PE set by an exact unmasked overflow, and DBT blocks that stay cached after the guest rewrites them. Not compared with x86 hardware; awaiting independent review.
- Added a typed runtime service registry (`crates/loader/runtime/services.txt`) and `xenora-runtime-gen`, which generates Win64 argument and result adapters, static metadata and a coverage report. It covers 20 services: 16 existing kernel32 services moved to typed handlers, and `sqrt`, `sqrtf`, `fabs` and `fabsf` with arguments and results in XMM registers. Conflicting keys, unlisted API sets, unsupported types and behaviour without an existing test are rejected. See `docs/runtime/registry.md`.
- Added SSE and SSE2 floating point in scalar and packed, binary32 and binary64 forms: add, subtract, multiply, divide, minimum, maximum, square root, compares, COMI/UCOMI and the conversions between formats and integers (parts of #127 and #128; awaiting independent review). `crates/loader/src/softfloat.rs` computes every result exactly and rounds once, with MXCSR rounding modes, sticky flags, denormals-are-zero, flush-to-zero, tininess after rounding and x86 NaN rules; host floating point is not used because ARM64 differs. An unmasked exception exits with `SimdException` and leaves everything but MXCSR unchanged. RCP, RSQRT and MMX conversions are rejected, and no floating-point form is translated to NEON yet.
- Added 6,824 floating-point vectors computed with exact fractions by `tests/x86/float_reference.py`, run through both engines from registers and memory and through the packed forms, and more than two million round-to-nearest results compared with the host's IEEE 754 hardware.
- Added XMM0-XMM15 and MXCSR to the guest CPU state, and the SSE and SSE2 moves and packed integer forms: aligned, unaligned, scalar, half and non-temporal moves, MOVD/MOVQ, sign-mask extraction, bitwise operations, wrapping and saturating arithmetic, compares, minimum, maximum, average, multiplies, PSADBW, packs, unpacks, shifts, shuffles, PINSRW, PEXTRW, LDMXCSR and STMXCSR (parts of #124, #125, #126 and #128; awaiting independent review). Operations with identical NEON lane semantics are translated to ARM64; the rest call the shared semantics. Misaligned 16-byte operands and reserved MXCSR bits raise a distinct general-protection exit. MXCSR is state only: floating-point arithmetic is not implemented.
- Added 374 LLVM-assembled vector instructions with a byte-array reference, compared with both engines over 23,936 states, plus alignment, fault, width and mixed-sequence tests.
- Added a declarative x86-64 instruction registry (`crates/loader/x86/instructions.toml`) and its generator, `crates/loader/generate_x86.py`, with `validate`, `generate` and `--check` modes. The static probe, the interpreter and the native DBT now share one decoder driven by its tables, so instruction boundaries, rejected forms and reported support agree. Overlapping encodings, such as a sign extension claiming the MOV-immediate opcodes, fail validation. See `docs/cpu/instruction-registry.md`.
- Added integer instructions for 8-, 16-, 32- and 64-bit register and checked memory operands: the eight ALU operations, TEST, INC, DEC, NEG, NOT, XCHG, ROL, ROR, SHL, SHR, SAR, MUL, IMUL, DIV, IDIV, CMOVcc, SETcc, BT, BTS, BTR, BTC, BSF, BSR, POPCNT, TZCNT, LZCNT, CBW/CWD families, PUSH, POP, LEAVE, RET imm16 and flag instructions, with parity and auxiliary-carry flags and a distinct divide-error exit (parts of #65, #66, #68, #70, #71, #73, #118 to #123, #194 to #196; awaiting independent review). Forms the DBT does not lower to ARM64 call the same Rust semantics and are counted.
- Added 985 LLVM-assembled integer instructions with a bit-level reference that reads only their assembly text, compared with the interpreter and the DBT over 47,280 states, plus 4,000 random instruction sequences compared between the engines.
- Added sixteen gfx1030 SOP2 integer forms through the semantic registry: `s_min_i32`, `s_min_u32`, `s_max_i32`, `s_max_u32`, `s_cselect_b32`, `s_bfm_b32`, `s_mul_i32`, `s_bfe_u32`, `s_bfe_i32`, `s_absdiff_i32`, `s_lshl1_add_u32` to `s_lshl4_add_u32`, `s_mul_hi_u32` and `s_mul_hi_i32` (AMD guide section 12.1). Min and max set SCC from the strict compare (a tie gives S1 and SCC 0), `s_cselect_b32` reads SCC and is refused when SCC is unset, and BFM, MUL, MUL_HI and CSELECT leave SCC unchanged. The registry gained these primitives, a `selected_src0` SCC effect, the select's SCC input and a declared `shift_amount` for the shift-and-add forms; `ScalarAluOp::evaluate` now returns an optional SCC. Both reference interpreters, written separately from the guide, run the same sixteen forms and are checked against 21,070 guide-derived cases on both CPU interpreters and on native Metal; 597 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all sixteen. Part of #215.
- Added MOVZX, MOVSX (0F B6/B7/BE/BF) and MOVSXD (63) for register and checked memory operands in the interpreter and the native DBT, with exact lengths in the static probe (parts of #65, #66, #67, #68 and #117; awaiting independent review). Covered: 16-, 32- and 64-bit destinations, AH/CH/DH/BH without REX, FS/GS bases and RIP-relative operands. Other 0x66 forms are rejected instead of running at the wrong width. Known-answer encodings come from the LLVM assembler; MOV immediates (B8-BF) have regressions proving they are never read as sign extensions.
- Added Phase II infrastructure CLIs under `scripts/qa` and `scripts/release` (#277): read-only RDNA2 expansion planning over live inventories, unified verification profiles with stale-evidence detection, CPU/runtime coverage scans, benchmark regression comparisons that reject incompatible identities, git rename/delete scope collision reports, and release-readiness reports with SBOM/checksum/bundle checks. Covered by `tests/qa` and `tests/release`; advisory until reviewed.
- Added advisory infrastructure QA helpers under `scripts/qa/` and `scripts/release/` (issue #277): exit-status-preserving orchestration with JSON reports, PR scope/DCO/artifact checks, benchmark percentile analysis over existing samples, environment and repository health diagnostics, ARM64 Mach-O/bundle/codesign helpers, and checksum manifests. Covered by `tests/qa/` and `tests/release/`; checks stay advisory until reviewed.
- Recorded agent-queue live smoke evidence for issue #180 against the disposable private repository `ranveersoni98/xenora-agent-queue-smoke`, including claim grant, overlap refusal, release, not-ready denial, progress renew and a successful audit dispatch after fixing comment-only `apply_actions` and audit permissions/argparse issues.
- Added twelve gfx1030 VOP2 vector integer forms through the semantic registry: `v_mul_i32_i24`, `v_mul_hi_i32_i24`, `v_mul_u32_u24`, `v_mul_hi_u32_u24`, `v_min_i32`, `v_max_i32`, `v_min_u32`, `v_max_u32`, `v_xnor_b32`, `v_add_nc_u32`, `v_sub_nc_u32` and `v_subrev_nc_u32` (AMD guide section 12.7), with SRC0 a VGPR, an SGPR, `vcc_lo`, an inline integer or a literal. The registry gained a `vop2_vgpr` operand rule, the vector operations `mul24` and `mul_hi24`, a declared `source_order` for SUBREV, and a per-lane `VectorBinary` that selects one reusable MSL template per operation. Both reference interpreters, written separately from the guide, run the same twelve forms and are checked against 2,040 guide-derived cases, each asserting every lane of a 7-, 32- or 45-lane dispatch (partial, empty and full EXEC), on both CPU interpreters and on native Metal; 575 rejected programs are refused by both interpreters and by the compiler at the same word. A new LLVM-assembled fixture computes every lane from its own input. Part of #215.
- Moved the twelve Wave32 VOPC integer compares from #239 into the semantic registry (operand rule `vopc_vcc`, `vcc = "lane_mask"`, `wave = "wave32"`) with no behaviour change, and added `v_cmp_f_i32`, `v_cmp_t_i32`, `v_cmp_f_u32` and `v_cmp_t_u32` as registry forms under the same Wave32 VCC/EXEC contract, verified by an independent guide-derived oracle (`tests/validation/tests/vopc_f_t.rs`), a new LLVM-assembled fixture and native Metal (part of #215). `v_cmpx_*`, the VOP3 encoding and Wave64 stay unsupported.
- Split the gfx1030 semantic registry into one file per encoding family (`crates/isa/semantics/rdna2/{sop2,sopc,sop1,vop2,vopc,vop3}.toml`, included in order by `rdna2.toml`; the split left the generated tables byte-identical), and added registry encoding variants: another encoding of a declared form is pure data. `v_add_nc_u32_e64` is now the first VOP3 variant of `v_add_nc_u32` (operand rule `vop3_vgpr2`), replacing its hand-written decoder and instruction with no behaviour change (part of #215).
- Added sixteen gfx1030 SOP2 integer forms through the semantic registry: `s_min_i32`, `s_min_u32`, `s_max_i32`, `s_max_u32`, `s_cselect_b32`, `s_bfm_b32`, `s_mul_i32`, `s_bfe_u32`, `s_bfe_i32`, `s_absdiff_i32`, `s_lshl1_add_u32` to `s_lshl4_add_u32`, `s_mul_hi_u32` and `s_mul_hi_i32` (AMD guide section 12.1). Min and max set SCC from the strict compare (a tie gives S1 and SCC 0), `s_cselect_b32` reads SCC and is refused when SCC is unset, and BFM, MUL, MUL_HI and CSELECT leave SCC unchanged. The registry gained these primitives, a `selected_src0` SCC effect, the select's SCC input and a declared `shift_amount` for the shift-and-add forms; `ScalarAluOp::evaluate` now returns an optional SCC. Both reference interpreters, written separately from the guide, run the same sixteen forms and are checked against 21,070 guide-derived cases on both CPU interpreters and on native Metal; 597 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all sixteen. Part of #215.
- Added audio PCM streaming and sandboxed virtual filesystem (VFS) integration to the native application runtime (Gate 6, #284). The C interface gains audio management functions (`xenora_session_audio_init`, `xenora_session_audio_submit`, `xenora_session_audio_read`, `xenora_session_audio_status`, `xenora_session_audio_set_volume`) and virtual filesystem functions (`xenora_session_vfs_set_root`, `xenora_session_vfs_open`, `xenora_session_vfs_read`, `xenora_session_vfs_seek`, `xenora_session_vfs_close`, `xenora_session_run_audio_vfs_fixture`). The audio subsystem implements a bounded ring buffer supporting configurable sample rates, channel configurations, PCM formats (S16LE, F32LE), volume attenuation, mute, and buffer underrun tracking. The virtual filesystem operates within an explicitly configured, sandboxed directory root (`fixtures/assets`), strictly rejecting path traversal attempts (`..`, absolute paths, null bytes) and invalid or stale handles, while supporting sequential and seekable file reads (`XENORA_SEEK_SET`, `XENORA_SEEK_CUR`, `XENORA_SEEK_END`). An original PE fixture (`fixtures/pe/audio_vfs.exe`, generated by `fixtures/pe/audio_vfs.py` using only the supported ARM64 DBT instruction subset) opens `asset.bin` (generated by `fixtures/assets/generate.py`), loads a 2x2 RGBA texture and 256 PCM audio samples via VFS, initializes audio, submits the PCM audio queue, and renders the loaded texture on Metal. Verified with unit tests, four Metal acceptance tests in `crates/ffi/tests/audio_vfs.rs`, UI controls and a `--smoke-audio-vfs` CLI in `Xenora.app`.
- Added persistent GPU resources, dynamic texture updates, and resource retirement to the native application (Gate 5, #279). The C interface gains `xenora_resource`, resource types (`XENORA_RESOURCE_TYPE_*`), `xenora_session_create_texture`, `xenora_session_update_texture`, `xenora_session_destroy_resource`, `xenora_session_resource_info`, `xenora_session_render_textured`, and `xenora_session_run_textured_fixture`. Persistent GPU resources (textures) are explicitly allocated and owned by the execution session, surviving across execution slices without re-allocation. Dynamic texture subregion updates modify GPU texture contents in-place on native Metal. Resource retirement is completion-aware: destroying a resource held by in-flight GPU execution marks it retired and safely defers destruction until in-flight work completes, while rejecting subsequent caller queries with typed error codes. An original PE fixture (`fixtures/pe/textured.exe`, generated by `fixtures/pe/textured.py` using only the supported ARM64 DBT instruction subset) creates a persistent 2x2 texture via `xenora.dll!texture_create`, renders frame 0, updates pixels via `xenora.dll!texture_update`, renders frame 1, and retires the resource via `xenora.dll!texture_destroy`. Xenora.app gains "Run textured fixture" controls and `--smoke-resources`. Six GPU acceptance tests with Metal validation verify persistent texture lifecycle across multiple frames, dynamic 1x1 and 2x1 subregion updates on native Metal, completion-aware deferred retirement, rejection of invalid/stale/double-destroyed handles, slot reuse across 200 cycles without leaking, and full guest fixture execution. Wired acceptance tests into `scripts/test-gpu.sh`.
- Added interactive guest execution with dynamic input handling and rendering to the native application (Gate 4, #276). The C interface gains `xenora_session_start_interactive_loop`, `xenora_session_send_input`, `xenora_session_queue_input`, and `xenora_session_get_recorded_frame`, along with input masks (`XENORA_INPUT_*`) and `xenora_input_state`. The original interactive guest fixture (`fixtures/pe/interactive.exe`, generated by `fixtures/pe/interactive.py` using only the supported ARM64 DBT instruction subset) polls host input via `xenora.dll!input_poll` and steers its rendered column position (0..3) on native Metal. Xenora.app gains interactive frame-loop controls ("Interactive (300 frames)", "◀ Left", "▶ Right", "Release") and `--smoke-interactive`. Four GPU acceptance tests with Metal validation verify that input events drive guest state and pixel geometry, deterministic input replay reproduces identical frame sequences across multiple sessions, key release and focus loss cleanly hold position without stuck keys, and destroying an interactive session joins promptly. Wired the interactive tests into `scripts/test-gpu.sh`.
- Added persistent guest rendering with pause, resume and stop to the native application (Gate 3, #266). The C interface gains `xenora_session_start_frame_loop`, `xenora_session_pause_frame_loop`, `xenora_session_resume_frame_loop`, `xenora_session_stop_frame_loop`, and `xenora_session_frame_loop_status`, plus new states (`XENORA_LOOP_*`). The guest fixture (`fixtures/pe/frame-loop.exe`, generated by `fixtures/pe/frame-loop.py` without external toolchains) runs on a session-owned thread and repeatedly calls `xenora.dll!frame_submit` until told to halt; each frame is rendered on native Metal, checked per pixel against geometric expectations, and returned via read-back RGBA8 buffers. Destroying a running or paused session safely stops its loop outside the global session lock. Xenora.app gains persistent frame-loop controls ("Start 300 frames", "Pause", "Resume", "Stop") and displays live frames with their frame index. Five GPU acceptance tests with Metal API and GPU validation verify frame ordering over 300 frames, live sampling across 2,000 frames without backwards progression, pause/resume/stop lifecycle, prompt join on session destruction, and stable memory footprint across repeated sessions. Added `--smoke-loop` to Xenora.app and wired the acceptance tests into `scripts/test-gpu.sh`.
- Added read-only executable inspection to the native app (#267). Xenora.app can open a PE file with Open Executable…, by dropping it on the window, or from Finder (it registers as an alternate viewer for Windows executables). The new C function `xenora_inspect_executable` returns a text report built from the existing static probe and loader validation: file size and SHA-256, header facts, whether `ParsedPe::parse` accepts the file, sections, imports not provided by Xenora's standard runtime services, the bounded static disassembly's count of instructions the ARM64 DBT does not support with the first one's address, and relocation and TLS counts. Nothing in the file is executed, and executing opened files remains unavailable pending #257. Inputs over 256 MiB are refused before reading. A panic inside the probe is reported as a Xenora defect instead of crashing the app; the new truncation test found one in `probe_pe_bytes` (truncations of `trusted-runner.exe` to 1,556–1,665 bytes slice past the end of the file while reading an import name), reported as #270 and not fixed here. Checked with the x1 executables in `experiments/x1/fixtures`, which the app does not embed, with malformed inputs, and in the window through the Finder open path and the Open panel; drag and drop was not exercised.
- Added eleven gfx1030 SOP1 unary forms through the semantic registry: `s_not_b32`, `s_brev_b32`, `s_bcnt0_i32_b32`, `s_bcnt1_i32_b32`, `s_ff0_i32_b32`, `s_ff1_i32_b32`, `s_flbit_i32_b32`, `s_flbit_i32`, `s_sext_i32_i8`, `s_sext_i32_i16` and `s_abs_i32` (AMD guide section 12.3). Searches that find nothing return -1, `s_abs_i32` of 0x80000000 stays 0x80000000, and only NOT, BCNT0, BCNT1 and ABS write SCC. The registry gained these primitives, a `sop1_sgpr` operand rule, and a declared `source_bits` for sign extension that is checked against the XML's 8- and 16-bit source operands. The reference and independent semantic-review interpreters, written separately from the guide, evaluate the same eleven forms and are checked against 4,126 guide-derived cases on both CPU interpreters and on native Metal with validation; 231 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all eleven. Part of #215.
- Showed the first guest-driven frame in the native app (Gate 2, #263). The C interface gains `xenora_session_run_trusted_fixture`, which runs only the embedded trusted PE fixture: its x86-64 code is translated and executed, its `xenora.dll!fixture_draw` call compiles the x9 RDNA2 shader fixtures to MSL and renders on the native Metal device, and the 4×3 RGBA8 read-back is returned only if the guest halts with the CLI runner's expected results and every pixel equals the pixel shader's export, (1, 0, 0, 1) as opaque red. Xenora.app's "Run trusted fixture" button shows that frame, and `--smoke-frame` prints it. A `gpu-tests` test, run by `scripts/test-gpu.sh`, executes the fixture three times through the interface with Metal validation enabled. The frame is a read-back image, not drawable presentation, and no caller-supplied executable can run. Verified on one Apple Silicon Mac; the window was checked by screenshot.
- 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.
@@ -74,12 +106,23 @@ remains unsupported.
- Added Win64 TEB allocation and `gs_base` initialization to synthetic guest startup.
### Changed
- Registering an import key twice is now an error instead of silently replacing the first service, ordinals are distinct from names, and API sets in the import generator match exactly instead of by prefix.
- `GetSystemTimeAsFileTime` now stops the guest on a null pointer, as on any other invalid pointer, instead of setting the last error.
- Simplified the claim rules in `AGENTS.md`, `CONTRIBUTING.md` and the pull request template at the maintainer's request: claim an issue by replying on it in plain words, never claim over an existing claim, and treat a claim as stale only after about one week without a pull request. The task-queue lease (`lease_hours` in `.github/agent-queue.json`) is now 168 hours to match, and `docs/coordination/agent-tasks.md` marks the queue commands as optional.
- The static PE probe now marks x86-64 SIB memory addressing as DBT-supported, matching the
native DBT.
### Fixed
- Made the static probe and the binder share one bounded import parser, after the truncated-name fix for #270. Truncated, unterminated, empty or non-ASCII names, reserved bits and endless tables are reported by the probe and refused by the binder.
- Fixed import binding writing some slots before finding an unresolved import, and service calls taking effect before an unreadable return address was noticed. A service that changes a nonvolatile register, including XMM6 to XMM15, now stops the guest (part of #201).
- Fixed older import-generator templates that reported success for unimplemented wrappers, used a nonexistent exit reason, and read floating-point arguments from integer registers.
- Fixed guest flags in the native DBT (#64, #70). They lived only in host NZCV, so they were lost across helper calls and block boundaries and register ADD, SUB and XOR set none. JB, JAE, JBE and JA used ARM carry polarity, which is inverted for subtraction. Flags are now stored in the guest state.
- Fixed the static probe reporting support for forms an engine rejects, including NOP, TEST, most conditional branches and the FF group in the interpreter.
- Fixed the native DBT's `SXTW` encoding, which set bit 3 of the source register and was right only for registers that already had it set; the previous test used such a register by chance.
- Fixed 32-bit guest stores and loads in the native DBT (MOV 89/8B and C7 /0), which accessed eight bytes: stores overwrote the next four guest bytes and accesses at the end of a mapping faulted. RIP-relative operands of byte moves and extensions, which were read as RBP-relative, and LEA with a segment prefix, which added the segment base, are fixed too.
- Fixed an x86 prefix-length test that read an untracked fuzz artifact and so failed on every fresh checkout; its input is now inline.
- Fixed agent-queue `apply_actions` crashing on comment-only decisions (claim refusals) by skipping no-op `gh issue edit` calls; accept `summary --now` after the subcommand; grant the audit job `pull-requests: read` so live audits can list open PRs (issue #180).
- Fixed `xenora_isa::meta::identify` reading six VOP3 interpolation forms (`v_interp_p1_f32_e64`, `v_interp_p2_f32_e64`, `v_interp_mov_f32_e64`, `v_interp_p1ll_f16`, `v_interp_p1lv_f16`, `v_interp_p2_f16`) as 12 bytes when SRC0 is 255. In these forms SRC0 holds attribute bit-fields, not an operand selector (AMD RDNA 2 ISA guide section 10.4.2; XML operand type `OPR_ATTR`), so SRC0 = 255 no longer adds a literal word. The six corpus probes are now 8 bytes, as LLVM 23.1.6 also decodes them. The six pinned `mismatch` rows in the LLVM corpus check are gone: one now agrees fully, and five are `operand_flagged` (same instruction and length; LLVM flags an operand).
- Updated `test_probe_static_analysis_does_not_execute_code`: the SIB store `mov [rsp + 0x20],
@@ -163,6 +206,7 @@ remains unsupported.
### Fixed
- Fixed the intermittent failure of the frame-loop memory-footprint test (#290). Each frame-loop session opened its own Metal command queue. The first command buffer on a queue makes the GPU driver allocate a working set for it (about 45 MiB on an Apple M5 with Metal validation), and the driver frees it asynchronously 10–50 ms after the queue is released, so the process footprint read right after a session ended depended on how far that release had got. Measured immediately after each of 50 destroys, it ranged from 45 to 96 MiB; the unchanged test failed 5 times in 30 runs, with up to 26 MiB of apparent growth. There was no leak: one second after each destroy the footprint was back at the same floor every time. Frame-loop sessions now share one process-wide Metal device and command queue, so the working set is allocated once and kept: the same readings stay within 93–98 MiB across 50 sessions, and the unchanged test passed 30 runs in a row (largest growth 0.31 MiB). The cost is that the process keeps that GPU memory (about 50 MiB with validation, 58 MiB total footprint without) after its first frame loop. A new 50-session test (normal completion, pause and resume, destroy while running) checks the readings stay within 16 MiB; it fails without the fix.
- Stop ignoring `fixtures/pe/trusted-runner.exe`. The runner embeds it with `include_bytes!`, so ignoring the file made a fresh checkout fail to compile.
- Corrected the ARM64 STP pre-index encoder, which had a hardcoded -32-byte immediate and therefore adjusted the host stack by the wrong amount once the translator frame grew to 48 bytes. The wrong frame silently corrupted the caller's stack and caused SIGSEGV in every native translation test. Emitter encodings are now checked against LLVM's assembler, and a test asserts that each translated block opens and closes the same 48-byte frame.
- Translated guest memory faults now stop the block before it commits further architectural effects. A faulting push, call or store leaves guest RSP and registers unchanged, the reported instruction count covers only completed work, and guest RIP identifies the faulting instruction. Previously the block continued after the helper recorded a fault, so later instructions and writes still took effect.
+3 -8
View File
@@ -8,11 +8,8 @@ Xenora is an open-source project written primarily in Rust that builds and verif
Xenora is still experimental. Verified work is restricted to independently authored synthetic programs and shaders; authentic Xbox executable loading, system-service compatibility and commercial game execution remain unsupported. See the [current limitations](#current-limitations).
### At a glance
- **Native graphics:** translated gfx1030 vertex and pixel stages and native passes (indexed draws, blend, depth) run on Apple Silicon GPUs — verified, see [Blend pass](#blend-pass) and [Verified Apple M5 results](#verified-apple-m5-results).
- **Guest execution:** bounded x86-64 execution, original PE32+ loading, synthetic services and guest-driven GPU dispatch — verified milestones X1–X9.
- **Not supported:** authentic Xbox executable loading and commercial game execution; see the [milestone table](#development-milestones).
> [!CAUTION]
> **Xenora strictly opposes piracy.** Xenora is an independent, clean-room, general-purpose emulation research project that neither distributes copyrighted game files nor supports unauthorized content, DRM circumvention, or leaked materials. Use only legally obtained software. Xenora is not affiliated with Microsoft, Rockstar Games, Take-Two Interactive, or any other publisher or platform holder.
[![Native Rust checks](https://github.com/ranveersoni98/Xenora/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/ranveersoni98/Xenora/actions/workflows/ci.yml)
@@ -58,8 +55,6 @@ The latest verified milestones include **translated gfx1030 vertex and pixel sha
All existing verification refers to independently authored synthetic programs and shaders. Commercial-game compatibility remains unverified.
See the [X9 acceptance matrix](docs/testing/x9-acceptance.md) for specific tests, results and unsupported behavior.
## Native graphics translation
Xenora's graphics pipeline translates a supported subset of AMD RDNA 2 instructions into Metal Shading Language.
@@ -376,4 +371,4 @@ See [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md) for third-party attribution
Xenora is an independent open-source project and is not affiliated with Microsoft, Xbox, Rockstar Games or Apple.
---
---
+436 -5
View File
@@ -69,12 +69,105 @@ struct GuestFrame {
}
}
/// The frame produced by running the textured fixture (Gate 5, #279).
struct TexturedFrame {
let status: Int32
let width: Int
let height: Int
let rgba: [UInt8]
static func run() -> TexturedFrame {
var session: xenora_session = 0
var status = xenora_session_create(XENORA_ABI_VERSION, &session)
guard status == XENORA_OK else { return TexturedFrame(status: status, width: 0, height: 0, rgba: []) }
defer { _ = xenora_session_destroy(session) }
var rgba = [UInt8](repeating: 0, count: 16)
var width: UInt32 = 0
var height: UInt32 = 0
status = rgba.withUnsafeMutableBufferPointer { buffer in
xenora_session_run_textured_fixture(session, buffer.baseAddress, UInt64(buffer.count), &width, &height)
}
return TexturedFrame(status: status, width: Int(width), height: Int(height), rgba: status == XENORA_OK ? rgba : [])
}
var image: CGImage? {
guard status == XENORA_OK, let provider = CGDataProvider(data: Data(rgba) as CFData) else { return nil }
return CGImage(
width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: width * 4,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue),
provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent)
}
var summary: String {
let pixels = rgba.map(String.init).joined(separator: ",")
return "status=\(status) frame=\(width)x\(height) pixels=[\(pixels)]"
}
}
/// The frame and audio status produced by running the audio/VFS fixture (Gate 6, #284).
struct AudioVfsFrame {
let status: Int32
let width: Int
let height: Int
let samples: UInt32
let totalAudioBytes: UInt64
let rgba: [UInt8]
static func run() -> AudioVfsFrame {
var session: xenora_session = 0
var status = xenora_session_create(XENORA_ABI_VERSION, &session)
guard status == XENORA_OK else {
return AudioVfsFrame(status: status, width: 0, height: 0, samples: 0, totalAudioBytes: 0, rgba: [])
}
defer { _ = xenora_session_destroy(session) }
var rgba = [UInt8](repeating: 0, count: 16)
var width: UInt32 = 0
var height: UInt32 = 0
var samples: UInt32 = 0
status = rgba.withUnsafeMutableBufferPointer { buffer in
xenora_session_run_audio_vfs_fixture(
session, buffer.baseAddress, UInt64(buffer.count), &width, &height, &samples)
}
var queued: UInt32 = 0
var underruns: UInt32 = 0
var total: UInt64 = 0
_ = xenora_session_audio_status(session, &queued, &underruns, &total)
return AudioVfsFrame(
status: status,
width: Int(width),
height: Int(height),
samples: samples,
totalAudioBytes: total,
rgba: status == XENORA_OK ? rgba : []
)
}
var image: CGImage? {
guard status == XENORA_OK, let provider = CGDataProvider(data: Data(rgba) as CFData) else { return nil }
return CGImage(
width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: width * 4,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue),
provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent)
}
var summary: String {
let pixels = rgba.map(String.init).joined(separator: ",")
return "status=\(status) frame=\(width)x\(height) samples=\(samples) audio_total=\(totalAudioBytes) pixels=[\(pixels)]"
}
}
/// Owns the latest fixture run. A class with @Published avoids SwiftUI macros,
/// which the command-line toolchain does not ship.
@MainActor
final class FrameModel: ObservableObject {
@Published var frame: GuestFrame?
@Published var running = false
@Published var texturedFrame: TexturedFrame?
@Published var runningTextured = false
@Published var audioVfsFrame: AudioVfsFrame?
@Published var runningAudioVfs = false
func run() {
running = true
@@ -84,6 +177,188 @@ final class FrameModel: ObservableObject {
running = false
}
}
func runTextured() {
runningTextured = true
Task {
texturedFrame = await Task.detached { TexturedFrame.run() }.value
runningTextured = false
}
}
func runAudioVfs() {
runningAudioVfs = true
Task {
audioVfsFrame = await Task.detached { AudioVfsFrame.run() }.value
runningAudioVfs = false
}
}
}
/// Persistent guest rendering model (Gate 3, #266; Gate 4, #276).
@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.
@@ -170,6 +445,7 @@ struct InspectorView: View {
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 }
@@ -192,14 +468,83 @@ struct ContentView: View {
Text("Run failed (status \(frame.status)). No frame is shown.")
.foregroundStyle(.red)
}
Button(running ? "Running…" : "Run trusted fixture") { model.run() }
.disabled(running || !probe.connected)
if let tImage = model.texturedFrame?.image {
Image(decorative: tImage, scale: 1)
.resizable()
.interpolation(.none)
.aspectRatio(contentMode: .fit)
.frame(maxWidth: .infinity, minHeight: 80, maxHeight: 160)
.accessibilityLabel("Textured guest frame, 2 by 2 pixels")
Text("Textured fixture ran: persistent texture created, dynamically updated, rendered on Metal, and retired.")
.font(.callout)
.foregroundStyle(.secondary)
}
if let aImage = model.audioVfsFrame?.image {
Image(decorative: aImage, scale: 1)
.resizable()
.interpolation(.none)
.aspectRatio(contentMode: .fit)
.frame(maxWidth: .infinity, minHeight: 80, maxHeight: 160)
.accessibilityLabel("Audio/VFS guest frame, 2 by 2 pixels")
Text("Audio/VFS fixture ran: asset.bin loaded through sandboxed VFS, \(model.audioVfsFrame!.samples) audio samples queued (\(model.audioVfsFrame!.totalAudioBytes) bytes), texture rendered on Metal.")
.font(.callout)
.foregroundStyle(.secondary)
}
HStack {
Button(running ? "Running…" : "Run trusted fixture") { model.run() }
.disabled(running || !probe.connected)
Button(model.runningTextured ? "Running…" : "Run textured fixture") { model.runTextured() }
.disabled(model.runningTextured || !probe.connected)
Button(model.runningAudioVfs ? "Running…" : "Run Audio/VFS fixture") { model.runAudioVfs() }
.disabled(model.runningAudioVfs || !probe.connected)
}
}
Section("Persistent frame loop") {
if let image = loop.image {
Image(decorative: image, scale: 1)
.resizable()
.interpolation(.none)
.aspectRatio(contentMode: .fit)
.frame(maxWidth: .infinity, minHeight: 120, maxHeight: 240)
.accessibilityLabel("Guest frame #\(loop.frameId)")
Text("Frame #\(loop.frameId) (\(loop.completed) completed) • \(loop.stateDescription)")
.font(.callout)
.foregroundStyle(.secondary)
} else if let error = loop.errorMessage {
Text(error).foregroundStyle(.red)
} else if loop.state != UInt32(XENORA_LOOP_NONE) {
Text("State: \(loop.stateDescription) • \(loop.completed) completed")
.font(.callout)
.foregroundStyle(.secondary)
}
HStack {
Button("Start 300 frames") { loop.start(frameCount: 300) }
.disabled(!loop.canStart || !probe.connected)
Button("Interactive (300 frames)") { loop.startInteractive(frameCount: 300) }
.disabled(!loop.canStart || !probe.connected)
Button("Pause") { loop.pause() }
.disabled(!loop.isRunning)
Button("Resume") { loop.resume() }
.disabled(!loop.isPaused)
Button("Stop") { loop.stop() }
.disabled(!loop.isRunning && !loop.isPaused)
}
if loop.isInteractive && (loop.isRunning || loop.isPaused) {
HStack {
Button("◀ Left") { loop.sendInput(buttons: UInt32(XENORA_INPUT_LEFT)) }
Button("▶ Right") { loop.sendInput(buttons: UInt32(XENORA_INPUT_RIGHT)) }
Button("Release") { loop.sendInput(buttons: UInt32(XENORA_INPUT_NONE)) }
}
Text("Interactive guest: steer the rendered strip across columns 0..3 with Left/Right.")
.font(.caption)
.foregroundStyle(.secondary)
}
}
LabeledContent("Runtime", value: probe.connected ? "Connected" : "Unavailable (status \(probe.status))")
LabeledContent("Interface version", value: "\(probe.abiVersion)")
LabeledContent("Trusted fixture sections", value: "\(probe.sections)")
LabeledContent("Trusted fixture entry RVA", value: String(format: "0x%X", probe.entryRVA))
Text("Only the bundled trusted fixture can run. Live presentation, persistent sessions and input are not available yet.")
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)
@@ -211,16 +556,17 @@ struct ContentView: View {
inspection.inspect(url)
return true
}
.frame(minWidth: 520, minHeight: 560)
.frame(minWidth: 520, minHeight: 680)
}
}
struct XenoraApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
let model = FrameModel()
let loop = FrameLoopModel()
var body: some Scene {
WindowGroup("Xenora") { ContentView(model: model) }
WindowGroup("Xenora") { ContentView(model: model, loop: loop) }
}
}
@@ -232,6 +578,91 @@ if let flag = CommandLine.arguments.firstIndex(of: "--inspect"), flag + 1 < Comm
exit(status == Int32(XENORA_OK) ? 0 : 1)
}
// `--smoke-resources` tests persistent texture lifecycle, dynamic subregion updates, and retirement on Metal.
if CommandLine.arguments.contains("--smoke-resources") {
let frame = TexturedFrame.run()
print("smoke-resources: \(frame.summary)")
let expected: [UInt8] = [255, 255, 0, 255, 0, 255, 255, 255, 255, 0, 255, 255, 64, 64, 64, 255]
exit(frame.status == XENORA_OK && frame.width == 2 && frame.height == 2 && frame.rgba == expected ? 0 : 1)
}
// `--smoke-audio-vfs` tests VFS asset loading, PCM audio streaming, and Metal texture presentation.
if CommandLine.arguments.contains("--smoke-audio-vfs") {
let frame = AudioVfsFrame.run()
print("smoke-audio-vfs: \(frame.summary)")
let expected: [UInt8] = [255, 128, 0, 255, 128, 0, 255, 255, 0, 255, 128, 255, 255, 0, 128, 255]
exit(frame.status == XENORA_OK && frame.width == 2 && frame.height == 2 && frame.samples == 256 && frame.rgba == expected && frame.totalAudioBytes == 512 ? 0 : 1)
}
// `--smoke-interactive` runs 60 frames with queued inputs on the Metal device and exits.
if CommandLine.arguments.contains("--smoke-interactive") {
var session: xenora_session = 0
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()
+226 -4
View File
@@ -14,11 +14,12 @@ use std::path::PathBuf;
use std::process::Command;
use std::time::{SystemTime, UNIX_EPOCH};
use xenora_metal::NativeCompute;
use xenora_metal::{NativeCompute, RunProfile};
use xenora_shader::{Architecture, ENTRY_POINT, compile};
const WARMUP_REPS: usize = 2;
const DEFAULT_REPS: usize = 7;
const BATCH: usize = 8;
#[derive(Debug, Clone)]
struct Fixture {
@@ -83,10 +84,66 @@ struct SizeResult {
pipeline: Stats,
gpu: Stats,
host: Stats,
/// Host submission stages inside `host`, plus readback after it.
submit: SubmitStats,
/// Fraction of samples whose GPU timestamp delta was zero.
gpu_zero_fraction: f64,
}
/// Host-side split of one dispatch's submission path.
///
/// `other` is `host` minus library, pipeline and the four stages below it,
/// per sample: compile options, function lookup, bounds and validation checks.
#[derive(Debug, Clone, Default)]
struct SubmitStats {
alloc: Stats,
encode: Stats,
commit: Stats,
wait: Stats,
readback: Stats,
other: Stats,
}
#[derive(Debug, Clone, Default)]
struct SubmitSamples {
alloc: Vec<f64>,
encode: Vec<f64>,
commit: Vec<f64>,
wait: Vec<f64>,
readback: Vec<f64>,
other: Vec<f64>,
}
impl SubmitSamples {
fn push(&mut self, profile: &RunProfile) {
self.alloc.push(profile.alloc_seconds);
self.encode.push(profile.encode_seconds);
self.commit.push(profile.commit_seconds);
self.wait.push(profile.wait_seconds);
self.readback.push(profile.readback_seconds);
self.other.push(
profile.host_seconds
- profile.library_seconds
- profile.pipeline_seconds
- profile.alloc_seconds
- profile.encode_seconds
- profile.commit_seconds
- profile.wait_seconds,
);
}
fn stats(self) -> SubmitStats {
SubmitStats {
alloc: Stats::from_samples(self.alloc),
encode: Stats::from_samples(self.encode),
commit: Stats::from_samples(self.commit),
wait: Stats::from_samples(self.wait),
readback: Stats::from_samples(self.readback),
other: Stats::from_samples(self.other),
}
}
}
#[derive(Debug, Clone)]
struct FixtureResult {
name: String,
@@ -95,6 +152,14 @@ struct FixtureResult {
status: String,
reason: String,
sizes: Vec<SizeResult>,
batch: Option<BatchResult>,
}
#[derive(Debug, Clone)]
struct BatchResult {
words: usize,
sync: Stats,
pipelined: Stats,
}
fn main() -> Result<(), Box<dyn Error>> {
@@ -180,6 +245,7 @@ fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> Fixture
status: "not-implemented".to_string(),
reason: String::new(),
sizes: Vec::new(),
batch: None,
};
let code = match fs::read(&fixture.path) {
@@ -242,6 +308,7 @@ fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> Fixture
let mut pipeline_samples = Vec::with_capacity(reps);
let mut gpu_samples = Vec::with_capacity(reps);
let mut host_samples = Vec::with_capacity(reps);
let mut submit_samples = SubmitSamples::default();
let mut gpu_zero = 0usize;
let mut mismatch = None;
@@ -275,6 +342,7 @@ fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> Fixture
pipeline_samples.push(profile.pipeline_seconds);
gpu_samples.push(profile.gpu_seconds);
host_samples.push(profile.host_seconds);
submit_samples.push(&profile);
if profile.gpu_seconds <= 0.0 {
gpu_zero += 1;
}
@@ -294,6 +362,7 @@ fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> Fixture
pipeline: Stats::from_samples(pipeline_samples),
gpu: Stats::from_samples(gpu_samples),
host: Stats::from_samples(host_samples),
submit: submit_samples.stats(),
gpu_zero_fraction: if measured == 0 {
0.0
} else {
@@ -302,11 +371,83 @@ fn run_fixture(metal: &NativeCompute, fixture: &Fixture, reps: usize) -> Fixture
});
}
let batch_words = fixture
.sizes
.iter()
.copied()
.min_by_key(|words| words.abs_diff(1024))
.unwrap_or(1024);
match measure_batch(metal, &code, fixture, batch_words, reps) {
Ok(batch) => result.batch = Some(batch),
Err(reason) => {
result.status = "excluded".to_string();
result.reason = reason;
return result;
}
}
result.sizes = sizes;
result.status = "benchmarked".to_string();
result
}
fn measure_batch(
metal: &NativeCompute,
code: &[u8],
fixture: &Fixture,
words: usize,
reps: usize,
) -> Result<BatchResult, String> {
let input = expand(&fixture.input, words);
let expected = expand(&fixture.expected, words);
let mut sync = Vec::with_capacity(reps);
let mut pipelined = Vec::with_capacity(reps);
for rep in 0..(WARMUP_REPS + reps) {
for (samples, variant) in [(&mut sync, "sync"), (&mut pipelined, "pipelined")] {
let mut tokens = Vec::with_capacity(BATCH);
let mut outputs = Vec::with_capacity(BATCH);
let start = std::time::Instant::now();
for _ in 0..BATCH {
let compiled = compile(Architecture::Gfx1030, code).map_err(|error| {
format!("{variant} batch compile failed at {words} words: {error}")
})?;
if variant == "sync" {
let profile = metal
.run_words_profiled(&compiled.msl, ENTRY_POINT, &input)
.map_err(|error| {
format!("{variant} batch run failed at {words} words: {error}")
})?;
outputs.push(profile.output);
} else {
let token = metal
.submit_words(&compiled.msl, ENTRY_POINT, &input)
.map_err(|error| {
format!("{variant} batch submit failed at {words} words: {error}")
})?;
tokens.push(token);
}
}
for token in tokens {
let profile = metal.wait(token).map_err(|error| {
format!("{variant} batch wait failed at {words} words: {error}")
})?;
outputs.push(profile.output);
}
let per_dispatch = start.elapsed().as_secs_f64() / BATCH as f64;
if outputs.iter().any(|output| *output != expected) {
return Err(format!("{variant} batch GPU mismatch at {words} words"));
}
if rep >= WARMUP_REPS {
samples.push(per_dispatch);
}
}
}
Ok(BatchResult {
words,
sync: Stats::from_samples(sync),
pipelined: Stats::from_samples(pipelined),
})
}
fn expand(base: &[u32], words: usize) -> Vec<u32> {
(0..words).map(|i| base[i % base.len()]).collect()
}
@@ -612,13 +753,19 @@ fn results_json(results: &[FixtureResult]) -> String {
for (size_index, size) in result.sizes.iter().enumerate() {
let _ = writeln!(
out,
" {{ \"words\": {}, \"compile\": {}, \"library\": {}, \"pipeline\": {}, \"gpu\": {}, \"host\": {}, \"gpu_zero_fraction\": {:.4} }}{}",
" {{ \"words\": {}, \"compile\": {}, \"library\": {}, \"pipeline\": {}, \"gpu\": {}, \"host\": {}, \"alloc\": {}, \"encode\": {}, \"commit\": {}, \"wait\": {}, \"readback\": {}, \"host_other\": {}, \"gpu_zero_fraction\": {:.4} }}{}",
size.words,
stats_json(&size.compile),
stats_json(&size.library),
stats_json(&size.pipeline),
stats_json(&size.gpu),
stats_json(&size.host),
stats_json(&size.submit.alloc),
stats_json(&size.submit.encode),
stats_json(&size.submit.commit),
stats_json(&size.submit.wait),
stats_json(&size.submit.readback),
stats_json(&size.submit.other),
size.gpu_zero_fraction,
if size_index + 1 == result.sizes.len() {
""
@@ -627,9 +774,19 @@ fn results_json(results: &[FixtureResult]) -> String {
}
);
}
out.push_str(" ]");
if let Some(batch) = &result.batch {
let _ = write!(
out,
",\n \"batch\": {{ \"dispatches\": {BATCH}, \"words\": {}, \"sync\": {}, \"pipelined\": {} }}",
batch.words,
stats_json(&batch.sync),
stats_json(&batch.pipelined)
);
}
let _ = writeln!(
out,
" ]\n }}{}",
"\n }}{}",
if index + 1 == results.len() { "" } else { "," }
);
}
@@ -644,7 +801,7 @@ fn report_markdown(metadata: &Metadata, results: &[FixtureResult]) -> String {
let _ = writeln!(
out,
"Generated by `xenora-bench`. Every timed fixture passed its correctness test in this run. \
Timings are single command-buffer samples; see `docs/testing/benchmarks.md` for the protocol."
See `docs/testing/benchmarks.md` for the single-dispatch protocol."
);
let _ = writeln!(out);
let _ = writeln!(out, "## Environment");
@@ -739,5 +896,70 @@ fn report_markdown(metadata: &Metadata, results: &[FixtureResult]) -> String {
);
}
}
let _ = writeln!(out);
let _ = writeln!(out, "## Submission split");
let _ = writeln!(out);
let _ = writeln!(
out,
"Medians in microseconds of the host stages inside `host`: `alloc` creates the input and \
output shared buffers, `encode` creates the command buffer and encodes the dispatch, \
`commit` and `wait` time `commit` and `waitUntilCompleted`, and `other` is the per-sample \
remainder of `host` after library, pipeline and these four stages. `readback` copies \
the output after `host` ends."
);
let _ = writeln!(out);
let _ = writeln!(
out,
"| Fixture | Words | host | alloc | encode | commit | wait | other | readback |"
);
let _ = writeln!(
out,
"| --- | --- | --- | --- | --- | --- | --- | --- | --- |"
);
for result in results.iter().filter(|r| r.status == "benchmarked") {
for size in &result.sizes {
let stages = &size.submit;
let _ = writeln!(
out,
"| {} | {} | {:.2} | {:.2} | {:.2} | {:.2} | {:.2} | {:.2} | {:.2} |",
result.name,
size.words,
size.host.median * 1e6,
stages.alloc.median * 1e6,
stages.encode.median * 1e6,
stages.commit.median * 1e6,
stages.wait.median * 1e6,
stages.other.median * 1e6,
stages.readback.median * 1e6
);
}
}
let _ = writeln!(out);
let _ = writeln!(out, "## Batched submission");
let _ = writeln!(out);
let _ = writeln!(
out,
"Median host microseconds per dispatch in batches of {BATCH}, including recompilation."
);
let _ = writeln!(out);
let _ = writeln!(
out,
"| Fixture | Words | Sync (µs) | Pipelined (µs) | Sync / pipelined |"
);
let _ = writeln!(out, "| --- | --- | --- | --- | --- |");
for result in results {
if let Some(batch) = &result.batch {
let _ = writeln!(
out,
"| {} | {} | {:.2} | {:.2} | {:.2}× |",
result.name,
batch.words,
batch.sync.median * 1e6,
batch.pipelined.median * 1e6,
batch.sync.median / batch.pipelined.median
);
}
}
out
}
+57 -99
View File
@@ -4,19 +4,18 @@ use std::fmt;
pub use xenora_isa::{
Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp,
ScalarCompareOp, ScalarSource, ScalarUnaryOp, VectorCompareOp, VectorSource,
ScalarCompareOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp,
VectorSource,
};
use xenora_isa::{
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ,
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT, V_ADD_F32,
V_ADD_NC_U32, V_AND_B32, V_ASHRREV_I32, V_CMP_EQ_I32, V_CMP_EQ_U32, V_CMP_GE_I32, V_CMP_GE_U32,
V_CMP_GT_I32, V_CMP_GT_U32, V_CMP_LE_I32, V_CMP_LE_U32, V_CMP_LT_I32, V_CMP_LT_U32,
V_CMP_NE_I32, V_CMP_NE_U32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32, V_LSHRREV_B32,
V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32, VCC_LO,
V_INTERP_P1_F32, V_INTERP_P2_F32, V_MOV_B32, V_MUL_F32, VCC_LO,
};
use xenora_isa::meta::EncodingFamily;
use xenora_isa::semantics::FORM_IDS;
pub use xenora_isa::semantics::VectorBinary;
use xenora_isa::semantics::{FORM_IDS, OperandRule};
/// Metadata forms that [`decode`] turns into an [`Instruction`] for at least one
/// operand combination: the hand-written forms below followed by every form of
@@ -41,7 +40,7 @@ const fn concat_forms<const N: usize>() -> [(&'static str, EncodingFamily); N] {
}
/// Decoded forms not yet described by the semantic registry.
const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 36] = [
const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 17] = [
("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf),
("BUFFER_STORE_DWORD", EncodingFamily::Mubuf),
("EXP", EncodingFamily::Exp),
@@ -55,29 +54,10 @@ const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 36] = [
("S_WAITCNT", EncodingFamily::Sopp),
("S_WAITCNT_VSCNT", EncodingFamily::Sopk),
("V_ADD_F32", EncodingFamily::Vop2),
("V_ADD_NC_U32", EncodingFamily::Vop3),
("V_AND_B32", EncodingFamily::Vop2),
("V_ASHRREV_I32", EncodingFamily::Vop2),
("V_CMP_EQ_I32", EncodingFamily::Vopc),
("V_CMP_EQ_U32", EncodingFamily::Vopc),
("V_CMP_GE_I32", EncodingFamily::Vopc),
("V_CMP_GE_U32", EncodingFamily::Vopc),
("V_CMP_GT_I32", EncodingFamily::Vopc),
("V_CMP_GT_U32", EncodingFamily::Vopc),
("V_CMP_LE_I32", EncodingFamily::Vopc),
("V_CMP_LE_U32", EncodingFamily::Vopc),
("V_CMP_LT_I32", EncodingFamily::Vopc),
("V_CMP_LT_U32", EncodingFamily::Vopc),
("V_CMP_NE_I32", EncodingFamily::Vopc),
("V_CMP_NE_U32", EncodingFamily::Vopc),
("V_INTERP_P1_F32", EncodingFamily::Vintrp),
("V_INTERP_P2_F32", EncodingFamily::Vintrp),
("V_LSHLREV_B32", EncodingFamily::Vop2),
("V_LSHRREV_B32", EncodingFamily::Vop2),
("V_MOV_B32", EncodingFamily::Vop1),
("V_MUL_F32", EncodingFamily::Vop2),
("V_OR_B32", EncodingFamily::Vop2),
("V_XOR_B32", EncodingFamily::Vop2),
];
/// A successfully decoded instruction and its location in the input stream.
@@ -337,31 +317,12 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
if V_MOV_B32.matches(first) {
return move_b32(first, bytes);
}
{
use CompareRelation::{Equal, Greater, GreaterOrEqual, Less, LessOrEqual, NotEqual};
for (opcode, relation, signed) in [
(V_CMP_LT_I32, Less, true),
(V_CMP_EQ_I32, Equal, true),
(V_CMP_LE_I32, LessOrEqual, true),
(V_CMP_GT_I32, Greater, true),
(V_CMP_NE_I32, NotEqual, true),
(V_CMP_GE_I32, GreaterOrEqual, true),
(V_CMP_LT_U32, Less, false),
(V_CMP_EQ_U32, Equal, false),
(V_CMP_LE_U32, LessOrEqual, false),
(V_CMP_GT_U32, Greater, false),
(V_CMP_NE_U32, NotEqual, false),
(V_CMP_GE_U32, GreaterOrEqual, false),
] {
if opcode.matches(first) {
return vector_compare(VectorCompareOp { relation, signed }, first, bytes);
}
}
if let Some(op) = VectorCompareOp::from_word(first) {
return vector_compare(op, first, bytes);
}
if V_ADD_NC_U32.matches(first) {
let len = V_ADD_NC_U32.byte_len();
let second = word(bytes, len)?;
return Ok((add_u32(first, second)?, len));
if let Some(op) = VectorAluVop3Op::from_word(first) {
let second = word(bytes, 8)?;
return Ok((vop3_vgpr2(op, first, second)?, 8));
}
if S_MOV_B32.matches(first) {
let dst = ((first >> 16) & 0x7f) as u8;
@@ -429,46 +390,26 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
S_CBRANCH_VCCZ.byte_len(),
));
}
if V_LSHLREV_B32.matches(first) {
let (dst, src0, src1) = vop2_registers(first, "v_lshlrev_b32_e32")?;
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) = match op.operand_rule() {
// Operand rule `vop2_vgpr2`: SRC0 must select a VGPR (256-511).
OperandRule::Vop2Vgpr2 => {
let (_, src0, _) = vop2_registers(first, op.assembly_name())?;
(VectorSource::Register(src0), 4)
}
_ => vector_src0(first, bytes, op.assembly_name())?,
};
return Ok((
Instruction::VectorLshlrevB32 { dst, src0, src1 },
V_LSHLREV_B32.byte_len(),
));
}
if V_ASHRREV_I32.matches(first) {
let (dst, src0, src1) = vop2_registers(first, "v_ashrrev_i32_e32")?;
return Ok((
Instruction::VectorAshrrevI32 { dst, src0, src1 },
V_ASHRREV_I32.byte_len(),
));
}
if V_LSHRREV_B32.matches(first) {
let (dst, src0, src1) = vop2_registers(first, "v_lshrrev_b32_e32")?;
return Ok((
Instruction::VectorLshrrevB32 { dst, src0, src1 },
V_LSHRREV_B32.byte_len(),
));
}
if V_AND_B32.matches(first) {
let (dst, src0, src1) = vop2_registers(first, "v_and_b32_e32")?;
return Ok((
Instruction::VectorAndB32 { dst, src0, src1 },
V_AND_B32.byte_len(),
));
}
if V_OR_B32.matches(first) {
let (dst, src0, src1) = vop2_registers(first, "v_or_b32_e32")?;
return Ok((
Instruction::VectorOrB32 { dst, src0, src1 },
V_OR_B32.byte_len(),
));
}
if V_XOR_B32.matches(first) {
let (dst, src0, src1) = vop2_registers(first, "v_xor_b32_e32")?;
return Ok((
Instruction::VectorXorB32 { dst, src0, src1 },
V_XOR_B32.byte_len(),
Instruction::VectorAlu {
op,
dst,
src0,
src1,
},
len,
));
}
if V_ADD_F32.matches(first) {
@@ -698,10 +639,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.assembly_name())?;
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 => (
@@ -715,12 +667,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> {
@@ -753,18 +704,25 @@ fn move_b32(first: u32, bytes: &[u8]) -> Result<(Instruction, u8), DecodeErrorKi
Ok((Instruction::MoveB32 { dst, src }, len))
}
fn add_u32(first: u32, second: u32) -> Result<Instruction, DecodeErrorKind> {
/// Operand rule `vop3_vgpr2`: VDST in bits 0-7 of the first word, SRC0 and SRC1
/// in bits 0-8 and 9-17 of the second (RDNA 2 ISA section 13.3.4, VOP3A). Both sources
/// are VGPRs, ABS, OP_SEL, CLAMP, OMOD and NEG are clear, and the unused SRC2 is
/// the gfx1030 assembler's inline-zero operand encoding.
fn vop3_vgpr2(
op: VectorAluVop3Op,
first: u32,
second: u32,
) -> Result<Instruction, DecodeErrorKind> {
let src0 = second & 0x1ff;
let src1 = (second >> 9) & 0x1ff;
// All output and input modifiers are clear. The unused third source uses
// the gfx1030 assembler's inline-zero operand encoding.
if first & 0xff00 != 0 || second >> 18 != 128 || src0 < 256 || src1 < 256 {
return Err(unsupported(
"v_add_nc_u32_e64",
op.assembly_name(),
"expected two VGPR sources and no modifiers",
));
}
Ok(Instruction::AddNoCarryU32 {
Ok(Instruction::VectorAluVop3 {
op,
dst: first as u8,
src0: src0 as u8,
src1: src1 as u8,
+101 -27
View File
@@ -4,11 +4,13 @@ use std::process::{Command, Stdio};
use xenora_decoder::{
Architecture, CompareRelation, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction,
ScalarAluOp, ScalarSource, ScalarUnaryOp, VectorSource, decode, decode_at,
ScalarAluOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorSource, decode,
decode_at,
};
use xenora_isa::semantics::Signedness;
use xenora_ref::{
BranchCondition, CompareSource, Comparison, Op, ScalarAlu, ScalarUnary, Source, VectorAlu,
VectorInteger,
};
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin");
@@ -42,7 +44,8 @@ fn decodes_each_fixture_instruction_with_offset_and_length() {
(
20,
8,
Instruction::AddNoCarryU32 {
Instruction::VectorAluVop3 {
op: VectorAluVop3Op::AddNcU32,
dst: 1,
src0: 1,
src1: 2,
@@ -351,12 +354,34 @@ 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),
reference_scalar(src1),
),
Instruction::AddNoCarryU32 { dst, src0, src1 } => Op::Add(dst, src0, src1),
// The reference's VOP3 add; it is the only VOP3 variant so far.
Instruction::VectorAluVop3 {
op: VectorAluVop3Op::AddNcU32,
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 {
@@ -407,22 +432,32 @@ fn reference_op(instruction: Instruction) -> Op {
target,
condition: BranchCondition::Always,
},
Instruction::VectorAndB32 { dst, src0, src1 } => {
Op::Vector(VectorAlu::And, dst, src0, src1)
}
Instruction::VectorLshlrevB32 { dst, src0, src1 } => {
Op::Vector(VectorAlu::ShiftLeft, dst, src0, src1)
}
Instruction::VectorAshrrevI32 { dst, src0, src1 } => {
Op::Vector(VectorAlu::ArithmeticShiftRight, dst, src0, src1)
}
Instruction::VectorLshrrevB32 { dst, src0, src1 } => {
Op::Vector(VectorAlu::ShiftRight, dst, src0, src1)
}
Instruction::VectorOrB32 { dst, src0, src1 } => Op::Vector(VectorAlu::Or, dst, src0, src1),
Instruction::VectorXorB32 { dst, src0, src1 } => {
Op::Vector(VectorAlu::Xor, dst, src0, src1)
}
// The six logical and shift forms migrated from hand-written code
// (#215 M27) keep the reference's VGPR-only VectorAlu ops.
Instruction::VectorAlu {
op:
op @ (VectorAluOp::AndB32
| VectorAluOp::OrB32
| VectorAluOp::XorB32
| VectorAluOp::LshlrevB32
| VectorAluOp::LshrrevB32
| VectorAluOp::AshrrevI32),
dst,
src0: VectorSource::Register(src0),
src1,
} => Op::Vector(
match op {
VectorAluOp::AndB32 => VectorAlu::And,
VectorAluOp::OrB32 => VectorAlu::Or,
VectorAluOp::XorB32 => VectorAlu::Xor,
VectorAluOp::LshlrevB32 => VectorAlu::ShiftLeft,
VectorAluOp::LshrrevB32 => VectorAlu::ShiftRight,
_ => VectorAlu::ArithmeticShiftRight,
},
dst,
src0,
src1,
),
Instruction::VectorAddF32 { dst, src0, src1 } => {
Op::Vector(VectorAlu::FloatAdd, dst, src0, src1)
}
@@ -437,15 +472,17 @@ fn reference_op(instruction: Instruction) -> Op {
Instruction::VectorCompare { op, src0, src1 } => Op::Compare(
Comparison {
offset: match op.relation {
offset: match op.relation() {
CompareRelation::Less => 1,
CompareRelation::Equal => 2,
CompareRelation::LessOrEqual => 3,
CompareRelation::Greater => 4,
CompareRelation::NotEqual => 5,
CompareRelation::GreaterOrEqual => 6,
CompareRelation::False => 0,
CompareRelation::True => 7,
},
signed: op.signed,
signed: op.signed(),
},
match src0 {
VectorSource::Register(reg) => CompareSource::Vector(reg),
@@ -454,6 +491,35 @@ 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,
_ => panic!("{op:?} decodes only with a VGPR SRC0 (operand rule vop2_vgpr2)"),
},
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,
}
}
@@ -478,13 +544,16 @@ fn compares_fixture_instructions_against_llvm() {
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"),
include_bytes!("../../../fixtures/rdna2/vector-compare-ft.bin"),
high_registers,
&matrix,
] {
count += compare_against_llvm(fixture, &mut forms);
}
assert_eq!(forms.len(), 72, "forms compared: {forms:?}");
assert_eq!(forms.len(), 104, "forms compared: {forms:?}");
eprintln!(
"{count} three-way instruction comparisons across {} forms",
forms.len()
@@ -549,7 +618,7 @@ fn assemble_matrix() -> Vec<u8> {
);
// Every supported VOPC form with each source class: VGPR, SGPR, vcc_lo,
// inline integers at both ends, inline zero and a literal.
for relation in ["lt", "eq", "le", "gt", "ne", "ge"] {
for relation in ["f", "lt", "eq", "le", "gt", "ne", "ge", "t"] {
for kind in ["i32", "u32"] {
for src0 in [
"v255",
@@ -697,8 +766,6 @@ fn distinguishes_llvm_invalid_encodings_from_xenora_subset_rejections() {
let outside_subset: &[&[u32]] = &[
&[0x7e04_026b], // VOP1 VCC_HI source
&[0x7da2_0501], // v_cmpx_eq_u32_e32
&[0x7d00_0501], // v_cmp_f_i32_e32
&[0x7d0e_0501], // v_cmp_t_i32_e32
&[0xd482_006a, 0x0002_0501], // v_cmp_lt_i32_e64
&[0x8788_0908], // s_and_b64
&[0x8008_ffff, 0x1234_5678], // SOP2 with two literal sources
@@ -768,7 +835,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}"),
@@ -944,7 +1017,8 @@ fn accepts_scalar_destination_105_and_vgpr_zero_add_sources() {
let bytes: Vec<_> = words.iter().flat_map(|word| word.to_le_bytes()).collect();
assert_eq!(
decode(Architecture::Gfx1030, &bytes).unwrap()[0].instruction,
Instruction::AddNoCarryU32 {
Instruction::VectorAluVop3 {
op: VectorAluVop3Op::AddNcU32,
dst: 1,
src0: 0,
src1: 0
+282
View File
@@ -27,8 +27,43 @@ enum {
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
@@ -65,9 +100,256 @@ xenora_status xenora_session_run_trusted_fixture(
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
);
/* Audio subsystem (Gate 6, #284) */
typedef uint32_t xenora_audio_format;
enum {
XENORA_AUDIO_FORMAT_PCM_S16LE = 1,
XENORA_AUDIO_FORMAT_PCM_F32LE = 2,
};
/*
* Initialize the audio subsystem for a session.
*/
xenora_status xenora_session_audio_init(
xenora_session session,
uint32_t sample_rate,
uint32_t channels,
xenora_audio_format format
);
/*
* Submit PCM audio bytes into the session audio queue.
*/
xenora_status xenora_session_audio_submit(
xenora_session session,
const uint8_t *pcm_bytes,
uint64_t byte_count
);
/*
* Read PCM audio bytes from the session audio queue.
*/
xenora_status xenora_session_audio_read(
xenora_session session,
uint8_t *out_pcm,
uint64_t capacity,
uint64_t *out_bytes_read
);
/*
* Query current audio queue status: queued bytes, underruns, total submitted.
*/
xenora_status xenora_session_audio_status(
xenora_session session,
uint32_t *out_queued_bytes,
uint32_t *out_underruns,
uint64_t *out_total_submitted
);
/*
* Set audio volume (0.0 to 1.0) and mute state (non-zero = muted).
*/
xenora_status xenora_session_audio_set_volume(
xenora_session session,
float volume,
uint32_t muted
);
/* Virtual Filesystem (Gate 6, #284) */
typedef uint64_t xenora_file;
#define XENORA_NO_FILE 0u
enum {
XENORA_SEEK_SET = 0,
XENORA_SEEK_CUR = 1,
XENORA_SEEK_END = 2,
};
/*
* Set the sandboxed root directory for the session virtual filesystem.
*/
xenora_status xenora_session_vfs_set_root(
xenora_session session,
const char *root_path
);
/*
* Open a file within the virtual filesystem sandboxed root.
*/
xenora_status xenora_session_vfs_open(
xenora_session session,
const char *rel_path,
uint32_t flags,
xenora_file *out_file
);
/*
* Read bytes from an open virtual file.
*/
xenora_status xenora_session_vfs_read(
xenora_session session,
xenora_file file,
uint8_t *out_buffer,
uint64_t count,
uint64_t *out_bytes_read
);
/*
* Seek within an open virtual file.
*/
xenora_status xenora_session_vfs_seek(
xenora_session session,
xenora_file file,
int64_t offset,
uint32_t whence,
uint64_t *out_new_offset
);
/*
* Close an open virtual file.
*/
xenora_status xenora_session_vfs_close(
xenora_session session,
xenora_file file
);
/*
* Run the original audio and VFS PE fixture.
*/
xenora_status xenora_session_run_audio_vfs_fixture(
xenora_session session,
uint8_t *out_rgba,
uint64_t capacity,
uint32_t *out_width,
uint32_t *out_height,
uint32_t *out_audio_samples
);
/*
* Read-only compatibility inspection of a caller-supplied PE file. Nothing in
* `bytes` is executed: it is parsed and statically disassembled (bounded) only.
+332
View File
@@ -0,0 +1,332 @@
// 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, OnceLock};
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 = shared_gpu()?;
// The import runs on the guest thread, so the session's shader lives there too.
GPU.with(|slot| *slot.borrow_mut() = Some((gpu, shader.msl)));
let shared = Arc::clone(self);
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<(&'static NativeCompute, String)>> = const { RefCell::new(None) };
}
/// One Metal device and command queue shared by every frame-loop session (#290).
///
/// The first command buffer submitted on a queue makes the GPU driver allocate a
/// working set for it (about 45 MiB on an Apple M5 with Metal validation), and the
/// driver frees that memory asynchronously, 10–50 ms after the queue is released.
/// A queue per session therefore allocated and freed it once per session, and the
/// process footprint depended on how far that release had progressed. One queue
/// for the process allocates the working set once and keeps it: bounded caching,
/// not per-session churn. `NativeCompute` is `Send + Sync`, and rendering takes
/// `&self`, so concurrent sessions can share it. A device that cannot be opened
/// is reported to every session that asks.
fn shared_gpu() -> Result<&'static NativeCompute, String> {
static SHARED: OnceLock<Result<NativeCompute, String>> = OnceLock::new();
SHARED
.get_or_init(|| NativeCompute::new().map_err(|e| format!("Metal device: {e}")))
.as_ref()
.map_err(Clone::clone)
}
/// Frame `index` is a red strip in column `index % 4` on the clear colour.
///
/// 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()
}
+1976 -3
View File
File diff suppressed because it is too large. Load diff
+374
View File
@@ -0,0 +1,374 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Gate 6 acceptance on a native Metal device: audio PCM streaming and
//! sandboxed virtual filesystem (VFS) integration through the C interface (#284).
//! Needs `--features gpu-tests` (scripts/test-gpu.sh).
#![cfg(feature = "gpu-tests")]
use std::sync::Mutex;
use xenora_ffi::*;
/// Tests share the process-wide session table and one GPU; run them one at a time.
static SERIAL: Mutex<()> = Mutex::new(());
fn lock_serial() -> std::sync::MutexGuard<'static, ()> {
SERIAL.lock().unwrap_or_else(|e| e.into_inner())
}
fn session() -> u64 {
let mut handle = 0;
assert_eq!(
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut handle) },
XENORA_OK
);
assert_ne!(handle, 0);
handle
}
#[test]
fn audio_pcm_queue_streaming_ordering_and_volume() {
let _guard = lock_serial();
let sess = session();
// Rejection on invalid arguments
assert_eq!(
xenora_session_audio_init(sess, 0, 2, XENORA_AUDIO_FORMAT_PCM_S16LE),
XENORA_INVALID_ARGUMENT
);
assert_eq!(
xenora_session_audio_init(0xdead_beef, 48000, 2, XENORA_AUDIO_FORMAT_PCM_S16LE),
XENORA_INVALID_HANDLE
);
// Initialize 48000 Hz stereo 16-bit PCM
assert_eq!(
xenora_session_audio_init(sess, 48000, 2, XENORA_AUDIO_FORMAT_PCM_S16LE),
XENORA_OK
);
// Initial status should be empty
let (mut queued, mut underruns, mut total) = (0u32, 0u32, 0u64);
assert_eq!(
unsafe { xenora_session_audio_status(sess, &mut queued, &mut underruns, &mut total) },
XENORA_OK
);
assert_eq!(queued, 0);
assert_eq!(underruns, 0);
assert_eq!(total, 0);
// Generate known PCM samples: 100 stereo samples (400 bytes)
let mut pcm = Vec::with_capacity(400);
for i in 0..100i16 {
let left = i * 100;
let right = -left;
pcm.extend_from_slice(&left.to_le_bytes());
pcm.extend_from_slice(&right.to_le_bytes());
}
assert_eq!(
unsafe { xenora_session_audio_submit(sess, pcm.as_ptr(), pcm.len() as u64) },
XENORA_OK
);
assert_eq!(
unsafe { xenora_session_audio_status(sess, &mut queued, &mut underruns, &mut total) },
XENORA_OK
);
assert_eq!(queued, 400);
assert_eq!(total, 400);
assert_eq!(underruns, 0);
// Read back first 50 samples (200 bytes)
let mut read_buf = vec![0u8; 200];
let mut bytes_read = 0u64;
assert_eq!(
unsafe { xenora_session_audio_read(sess, read_buf.as_mut_ptr(), 200, &mut bytes_read) },
XENORA_OK
);
assert_eq!(bytes_read, 200);
assert_eq!(&read_buf[..], &pcm[..200]);
// Volume attenuation: set to 0.5
assert_eq!(xenora_session_audio_set_volume(sess, 0.5, 0), XENORA_OK);
// Submit 2 stereo samples (8 bytes): 2000, -2000, 4000, -4000
let mut half_vol_in = Vec::new();
half_vol_in.extend_from_slice(&2000i16.to_le_bytes());
half_vol_in.extend_from_slice(&(-2000i16).to_le_bytes());
half_vol_in.extend_from_slice(&4000i16.to_le_bytes());
half_vol_in.extend_from_slice(&(-4000i16).to_le_bytes());
assert_eq!(
unsafe {
xenora_session_audio_submit(sess, half_vol_in.as_ptr(), half_vol_in.len() as u64)
},
XENORA_OK
);
// Read remaining 200 bytes from first batch
let mut drain = vec![0u8; 200];
assert_eq!(
unsafe { xenora_session_audio_read(sess, drain.as_mut_ptr(), 200, &mut bytes_read) },
XENORA_OK
);
assert_eq!(bytes_read, 200);
assert_eq!(&drain[..], &pcm[200..]);
// Now read the 8 bytes attenuated samples
let mut attenuated = vec![0u8; 8];
assert_eq!(
unsafe { xenora_session_audio_read(sess, attenuated.as_mut_ptr(), 8, &mut bytes_read) },
XENORA_OK
);
assert_eq!(bytes_read, 8);
let s0 = i16::from_le_bytes([attenuated[0], attenuated[1]]);
let s1 = i16::from_le_bytes([attenuated[2], attenuated[3]]);
let s2 = i16::from_le_bytes([attenuated[4], attenuated[5]]);
let s3 = i16::from_le_bytes([attenuated[6], attenuated[7]]);
assert_eq!(s0, 1000);
assert_eq!(s1, -1000);
assert_eq!(s2, 2000);
assert_eq!(s3, -2000);
// Test mute (muted = 1)
assert_eq!(xenora_session_audio_set_volume(sess, 1.0, 1), XENORA_OK);
assert_eq!(
unsafe {
xenora_session_audio_submit(sess, half_vol_in.as_ptr(), half_vol_in.len() as u64)
},
XENORA_OK
);
let mut muted_out = vec![0u8; 8];
assert_eq!(
unsafe { xenora_session_audio_read(sess, muted_out.as_mut_ptr(), 8, &mut bytes_read) },
XENORA_OK
);
assert_eq!(muted_out, vec![0u8; 8]);
xenora_session_destroy(sess);
}
#[test]
fn virtual_filesystem_sandboxing_and_traversal_rejection() {
let _guard = lock_serial();
let sess = session();
let mut file = 0u64;
// Reject non-existent root
let bad_root = std::ffi::CString::new("/nonexistent_dir_xenora").unwrap();
assert_eq!(
unsafe { xenora_session_vfs_set_root(sess, bad_root.as_ptr()) },
XENORA_INVALID_ARGUMENT
);
// Set valid root
let root_path = if std::path::Path::new("fixtures/assets").exists() {
"fixtures/assets"
} else {
"../../fixtures/assets"
};
let c_root = std::ffi::CString::new(root_path).unwrap();
assert_eq!(
unsafe { xenora_session_vfs_set_root(sess, c_root.as_ptr()) },
XENORA_OK
);
// Traversal attacks rejected
for bad in &[
"../escape.txt",
"../../etc/passwd",
"/etc/passwd",
"sub/../../secret",
"asset.bin\0extra",
"",
] {
let bad_c = std::ffi::CString::new(*bad)
.unwrap_or_else(|_| std::ffi::CString::new("fallback_bad").unwrap());
assert_eq!(
unsafe { xenora_session_vfs_open(sess, bad_c.as_ptr(), 0, &mut file) },
XENORA_INVALID_ARGUMENT,
"traversal attempt '{}' was not rejected",
bad
);
}
// Open existing valid asset
let good = std::ffi::CString::new("asset.bin").unwrap();
assert_eq!(
unsafe { xenora_session_vfs_open(sess, good.as_ptr(), 0, &mut file) },
XENORA_OK
);
assert_ne!(file, XENORA_NO_FILE);
// Read header (20 bytes: 4B magic + 4B ver + 4B width + 4B height + 4B audio_samples)
let mut header = [0u8; 20];
let mut read_bytes = 0u64;
assert_eq!(
unsafe { xenora_session_vfs_read(sess, file, header.as_mut_ptr(), 20, &mut read_bytes) },
XENORA_OK
);
assert_eq!(read_bytes, 20);
assert_eq!(&header[0..4], b"XAST");
let version = u32::from_le_bytes([header[4], header[5], header[6], header[7]]);
assert_eq!(version, 1);
let width = u32::from_le_bytes([header[8], header[9], header[10], header[11]]);
assert_eq!(width, 2);
let height = u32::from_le_bytes([header[12], header[13], header[14], header[15]]);
assert_eq!(height, 2);
let audio_samples = u32::from_le_bytes([header[16], header[17], header[18], header[19]]);
assert_eq!(audio_samples, 256);
// Seek to audio offset (36) using SEEK_SET
let mut new_pos = 0u64;
assert_eq!(
unsafe { xenora_session_vfs_seek(sess, file, 36, XENORA_SEEK_SET, &mut new_pos) },
XENORA_OK
);
assert_eq!(new_pos, 36);
// Read 4 bytes of audio
let mut sample_bytes = [0u8; 4];
assert_eq!(
unsafe {
xenora_session_vfs_read(sess, file, sample_bytes.as_mut_ptr(), 4, &mut read_bytes)
},
XENORA_OK
);
assert_eq!(read_bytes, 4);
// Seek using SEEK_END
assert_eq!(
unsafe { xenora_session_vfs_seek(sess, file, 0, XENORA_SEEK_END, &mut new_pos) },
XENORA_OK
);
assert_eq!(new_pos, 20 + 16 + 512); // total asset size = 548 bytes
// Close file
assert_eq!(xenora_session_vfs_close(sess, file), XENORA_OK);
// Double close rejected
assert_eq!(xenora_session_vfs_close(sess, file), XENORA_INVALID_HANDLE);
xenora_session_destroy(sess);
}
#[test]
fn audio_vfs_guest_fixture_executes_asset_load_and_pcm_stream() {
let _guard = lock_serial();
let sess = session();
let mut out_rgba = [0u8; 16];
let mut out_w = 0u32;
let mut out_h = 0u32;
let mut out_samples = 0u32;
assert_eq!(
unsafe {
xenora_session_run_audio_vfs_fixture(
sess,
out_rgba.as_mut_ptr(),
16,
&mut out_w,
&mut out_h,
&mut out_samples,
)
},
XENORA_OK
);
assert_eq!(out_w, 2);
assert_eq!(out_h, 2);
assert_eq!(out_samples, 256);
// Expected texture from asset.bin: 2x2 RGBA8:
// (0,0): Orange [255, 128, 0, 255]
// (1,0): Purple [128, 0, 255, 255]
// (0,1): Teal [0, 255, 128, 255]
// (1,1): Pink [255, 0, 128, 255]
let expected_rgba: [u8; 16] = [
255, 128, 0, 255, 128, 0, 255, 255, 0, 255, 128, 255, 255, 0, 128, 255,
];
assert_eq!(
out_rgba, expected_rgba,
"Metal rendered frame did not match asset texture"
);
// Audio status: guest submitted 256 samples (512 bytes)
let (mut queued, mut underruns, mut total) = (0u32, 0u32, 0u64);
assert_eq!(
unsafe { xenora_session_audio_status(sess, &mut queued, &mut underruns, &mut total) },
XENORA_OK
);
assert_eq!(queued, 512);
assert_eq!(total, 512);
assert_eq!(underruns, 0);
// Read back submitted audio samples and verify
let mut pcm_buf = vec![0u8; 512];
let mut read_bytes = 0u64;
assert_eq!(
unsafe { xenora_session_audio_read(sess, pcm_buf.as_mut_ptr(), 512, &mut read_bytes) },
XENORA_OK
);
assert_eq!(read_bytes, 512);
// The first sample in asset.bin sine wave is 0
let s0 = i16::from_le_bytes([pcm_buf[0], pcm_buf[1]]);
assert_eq!(s0, 0);
xenora_session_destroy(sess);
}
#[test]
fn audio_vfs_rejection_of_invalid_and_stale_handles() {
let _guard = lock_serial();
let dead_sess = 0xdead_beefu64;
let mut queued = 0u32;
let mut underruns = 0u32;
let mut total = 0u64;
assert_eq!(
unsafe { xenora_session_audio_status(dead_sess, &mut queued, &mut underruns, &mut total) },
XENORA_INVALID_HANDLE
);
let mut file = 0u64;
let path = std::ffi::CString::new("asset.bin").unwrap();
assert_eq!(
unsafe { xenora_session_vfs_open(dead_sess, path.as_ptr(), 0, &mut file) },
XENORA_INVALID_HANDLE
);
let sess = session();
// Null pointer checks
assert_eq!(
unsafe { xenora_session_vfs_open(sess, std::ptr::null(), 0, &mut file) },
XENORA_INVALID_ARGUMENT
);
assert_eq!(
unsafe { xenora_session_vfs_open(sess, path.as_ptr(), 0, std::ptr::null_mut()) },
XENORA_INVALID_ARGUMENT
);
// Buffer too small for fixture
let mut small_buf = [0u8; 8];
let mut w = 0u32;
let mut h = 0u32;
let mut samples = 0u32;
assert_eq!(
unsafe {
xenora_session_run_audio_vfs_fixture(
sess,
small_buf.as_mut_ptr(),
8,
&mut w,
&mut h,
&mut samples,
)
},
XENORA_BUFFER_TOO_SMALL
);
xenora_session_destroy(sess);
}
+396
View File
@@ -0,0 +1,396 @@
// 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"
);
}
/// Regression test for #290: the footprint read right after each destroy must stay
/// flat across many sessions. Each session used to open its own Metal command queue,
/// and the GPU driver frees a queue's working set (about 45 MiB on an Apple M5 with
/// validation) asynchronously after release, so these readings swung by about 50 MiB
/// from session to session. Sessions now share one queue. The mix of sessions covers
/// normal completion, pause and resume, and destruction while running.
#[test]
fn fifty_sessions_keep_a_flat_footprint_after_each_destroy() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
let one = |kind: usize| {
let session = session();
match kind {
0 => {
assert_eq!(xenora_session_start_frame_loop(session, 100), XENORA_OK);
let s = wait_until(session, "100 frames", |s| s.state != XENORA_LOOP_RUNNING);
assert_eq!((s.state, s.completed), (XENORA_LOOP_FINISHED, 100));
}
1 => {
assert_eq!(xenora_session_start_frame_loop(session, 100), XENORA_OK);
wait_until(session, "10 frames", |s| s.completed >= 10);
assert_eq!(xenora_session_pause_frame_loop(session), XENORA_OK);
assert_eq!(xenora_session_resume_frame_loop(session), XENORA_OK);
let s = wait_until(session, "100 frames", |s| s.state != XENORA_LOOP_RUNNING);
assert_eq!((s.state, s.completed), (XENORA_LOOP_FINISHED, 100));
}
_ => {
assert_eq!(
xenora_session_start_frame_loop(session, XENORA_FRAME_LOOP_MAX_FRAMES),
XENORA_OK
);
wait_until(session, "a frame", |s| s.completed >= 1);
}
}
assert_eq!(xenora_session_destroy(session), XENORA_OK);
footprint()
};
one(0); // the first session allocates the shared queue's working set
let readings: Vec<u64> = (0..50).map(|i| one(i % 3)).collect();
let mib: Vec<u64> = readings.iter().map(|r| r >> 20).collect();
println!("footprint after each destroy (MiB): {mib:?}");
let median = |values: &[u64]| {
let mut sorted = values.to_vec();
sorted.sort_unstable();
sorted[sorted.len() / 2]
};
// Sustained growth: the typical reading at the end against the start.
let (start, end) = (median(&readings[..10]), median(&readings[40..]));
assert!(
end.saturating_sub(start) < 16 << 20,
"footprint grew from {start} to {end} bytes (median of first and last ten sessions)"
);
// Per-session churn, the cause fixed in #290: with a queue per session, about half
// of all readings sat some 45 MiB away from the median. With the shared queue,
// a reading is still occasionally caught while the driver frees a batch of
// per-frame render resources: graphics-tagged memory only, 16 to 44 MiB, gone
// within about 100 ms, measured in 13 of 6,000 sessions (0.22%). Allowing two such
// readings in 50 keeps a false failure near 1 in 5,000 runs while per-session
// churn would exceed it every time.
let centre = median(&readings);
let outliers: Vec<u64> = readings
.iter()
.filter(|&&r| r.abs_diff(centre) >= 16 << 20)
.map(|r| r >> 20)
.collect();
assert!(
outliers.len() <= 2,
"{} of 50 readings were 16 MiB or more from the median {} MiB: {outliers:?}",
outliers.len(),
centre >> 20
);
}
/// Two sessions render at the same time through the shared Metal queue (#290). Each
/// must keep its own frame sequence and pixels, pausing one must not stop the other,
/// and destroying one mid-run must not disturb the other.
#[test]
fn concurrent_sessions_share_the_queue_but_stay_isolated() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
let (a, b) = (session(), session());
assert_eq!(xenora_session_start_frame_loop(a, 400), XENORA_OK);
assert_eq!(xenora_session_start_frame_loop(b, 250), XENORA_OK);
wait_until(a, "session A started", |s| s.completed >= 5);
wait_until(b, "session B started", |s| s.completed >= 5);
// Pausing A holds only A.
assert_eq!(xenora_session_pause_frame_loop(a), XENORA_OK);
let a_held = wait_until(a, "session A paused", |s| s.state == XENORA_LOOP_PAUSED);
let b_before = status(b).completed;
let b_moving = wait_until(b, "session B progress while A is paused", |s| {
s.completed >= b_before + 20 || s.state != XENORA_LOOP_RUNNING
});
assert!(
b_moving.completed > b_before,
"B kept rendering while A was paused"
);
let a_still = status(a);
assert_eq!(a_still.state, XENORA_LOOP_PAUSED);
// At most the frame A was rendering when paused can still complete.
assert!(a_still.completed <= a_held.completed + 1);
assert_eq!(a_still.rgba.to_vec(), expected(a_still.frame_id));
assert_eq!(xenora_session_resume_frame_loop(a), XENORA_OK);
// Both finish with their own counts and their own final frames.
let a_done = wait_until(a, "session A finished", |s| s.state != XENORA_LOOP_RUNNING);
let b_done = wait_until(b, "session B finished", |s| s.state != XENORA_LOOP_RUNNING);
assert_eq!(
(a_done.state, a_done.completed, a_done.frame_id),
(XENORA_LOOP_FINISHED, 400, 399)
);
assert_eq!(
(b_done.state, b_done.completed, b_done.frame_id),
(XENORA_LOOP_FINISHED, 250, 249)
);
assert_eq!(a_done.rgba.to_vec(), expected(399));
assert_eq!(b_done.rgba.to_vec(), expected(249));
assert_eq!(xenora_session_destroy(a), XENORA_OK);
assert_eq!(xenora_session_destroy(b), XENORA_OK);
// Destroying one running session leaves the other running to completion.
let (c, d) = (session(), session());
assert_eq!(
xenora_session_start_frame_loop(c, XENORA_FRAME_LOOP_MAX_FRAMES),
XENORA_OK
);
assert_eq!(xenora_session_start_frame_loop(d, 300), XENORA_OK);
wait_until(c, "session C started", |s| s.completed >= 5);
wait_until(d, "session D started", |s| s.completed >= 5);
assert_eq!(xenora_session_destroy(c), XENORA_OK);
let d_done = wait_until(d, "session D finished", |s| s.state != XENORA_LOOP_RUNNING);
assert_eq!(
(d_done.state, d_done.completed, d_done.frame_id),
(XENORA_LOOP_FINISHED, 300, 299)
);
assert_eq!(d_done.rgba.to_vec(), expected(299));
assert_eq!(xenora_session_destroy(d), XENORA_OK);
}
+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()
);
}
+375
View File
@@ -0,0 +1,375 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Gate 5 acceptance on a native Metal device: persistent GPU resources,
//! dynamic texture updates, and completion-aware resource retirement through
//! the C interface (#279).
//! Needs `--features gpu-tests` (scripts/test-gpu.sh).
#![cfg(feature = "gpu-tests")]
use std::sync::Mutex;
use xenora_ffi::*;
/// Tests share the process-wide session table and one GPU; run them one at a time.
static SERIAL: Mutex<()> = Mutex::new(());
fn session() -> u64 {
let mut handle = 0;
assert_eq!(
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut handle) },
XENORA_OK
);
assert_ne!(handle, 0);
handle
}
#[test]
fn persistent_texture_lifecycle_survives_across_multiple_frames() {
let _guard = SERIAL.lock().unwrap();
let sess = session();
// 2x2 initial texture:
// (0,0)=red, (1,0)=green, (0,1)=blue, (1,1)=white
let initial_rgba: [u8; 16] = [
255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
];
let mut res = 0u64;
assert_eq!(
unsafe { xenora_session_create_texture(sess, 2, 2, initial_rgba.as_ptr(), &mut res) },
XENORA_OK
);
assert_ne!(res, XENORA_NO_RESOURCE);
// Render 5 consecutive frames from this single persistent texture resource without re-allocation.
for frame_idx in 0..5 {
let mut out_rgba = [0u8; 16];
let mut out_w = 0u32;
let mut out_h = 0u32;
assert_eq!(
unsafe {
xenora_session_render_textured(
sess,
res,
out_rgba.as_mut_ptr(),
16,
&mut out_w,
&mut out_h,
)
},
XENORA_OK,
"render frame {} failed",
frame_idx
);
assert_eq!(out_w, 2);
assert_eq!(out_h, 2);
assert_eq!(
out_rgba, initial_rgba,
"frame {} pixel mismatch with persistent texture",
frame_idx
);
}
// Verify resource is still live and un-retired after all frames
let (mut r_type, mut r_w, mut r_h, mut r_flight) = (0u32, 0u32, 0u32, 0u32);
assert_eq!(
unsafe {
xenora_session_resource_info(sess, res, &mut r_type, &mut r_w, &mut r_h, &mut r_flight)
},
XENORA_OK
);
assert_eq!(r_type, XENORA_RESOURCE_TYPE_TEXTURE_2D);
assert_eq!(r_w, 2);
assert_eq!(r_h, 2);
assert_eq!(r_flight, 0);
assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK);
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
}
#[test]
fn dynamic_texture_subregion_update_is_reflected_on_metal() {
let _guard = SERIAL.lock().unwrap();
let sess = session();
// 2x2 initial texture:
// (0,0)=red, (1,0)=green, (0,1)=blue, (1,1)=white
let initial_rgba: [u8; 16] = [
255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
];
let mut res = 0u64;
assert_eq!(
unsafe { xenora_session_create_texture(sess, 2, 2, initial_rgba.as_ptr(), &mut res) },
XENORA_OK
);
// 1. Update 1x1 subregion at (x=1, y=0) from green to yellow [255, 255, 0, 255]
let yellow_pixel = [255u8, 255, 0, 255];
assert_eq!(
unsafe { xenora_session_update_texture(sess, res, 1, 0, 1, 1, yellow_pixel.as_ptr(), 4) },
XENORA_OK
);
let mut frame1 = [0u8; 16];
let (mut w, mut h) = (0u32, 0u32);
assert_eq!(
unsafe {
xenora_session_render_textured(sess, res, frame1.as_mut_ptr(), 16, &mut w, &mut h)
},
XENORA_OK
);
let expected_frame1: [u8; 16] = [
255, 0, 0, 255, // (0,0) red (untouched)
255, 255, 0, 255, // (1,0) yellow (updated)
0, 0, 255, 255, // (0,1) blue (untouched)
255, 255, 255, 255, // (1,1) white (untouched)
];
assert_eq!(
frame1, expected_frame1,
"Metal read-back did not reflect 1x1 subregion update"
);
// 2. Update 2x1 subregion across the bottom row: (0,1) and (1,1)
// (0,1)=magenta [255, 0, 255, 255], (1,1)=cyan [0, 255, 255, 255]
let bottom_row = [255u8, 0, 255, 255, 0, 255, 255, 255];
assert_eq!(
unsafe { xenora_session_update_texture(sess, res, 0, 1, 2, 1, bottom_row.as_ptr(), 8) },
XENORA_OK
);
let mut frame2 = [0u8; 16];
assert_eq!(
unsafe {
xenora_session_render_textured(sess, res, frame2.as_mut_ptr(), 16, &mut w, &mut h)
},
XENORA_OK
);
let expected_frame2: [u8; 16] = [
255, 0, 0, 255, // (0,0) red
255, 255, 0, 255, // (1,0) yellow
255, 0, 255, 255, // (0,1) magenta
0, 255, 255, 255, // (1,1) cyan
];
assert_eq!(
frame2, expected_frame2,
"Metal read-back did not reflect 2x1 bottom row update"
);
assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK);
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
}
#[test]
fn deferred_resource_retirement_safely_waits_for_completion() {
let _guard = SERIAL.lock().unwrap();
let sess = session();
let mut res = 0u64;
assert_eq!(
unsafe { xenora_session_create_texture(sess, 2, 2, std::ptr::null(), &mut res) },
XENORA_OK
);
// Acquire an in-flight reference simulating active GPU encoding/submission
assert_eq!(test_acquire_resource_in_flight(sess, res), Ok(()));
let (mut r_type, mut r_w, mut r_h, mut r_flight) = (0u32, 0u32, 0u32, 0u32);
assert_eq!(
unsafe {
xenora_session_resource_info(sess, res, &mut r_type, &mut r_w, &mut r_h, &mut r_flight)
},
XENORA_OK
);
assert_eq!(r_flight, 1);
// Calling destroy while in-flight marks the resource retired without dangling pointers
assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK);
// Subsequent caller operations on the retired handle are rejected
assert_eq!(
unsafe {
xenora_session_resource_info(sess, res, &mut r_type, &mut r_w, &mut r_h, &mut r_flight)
},
XENORA_INVALID_HANDLE
);
assert_eq!(
xenora_session_destroy_resource(sess, res),
XENORA_INVALID_HANDLE
);
let dummy_pixel = [0u8; 4];
assert_eq!(
unsafe { xenora_session_update_texture(sess, res, 0, 0, 1, 1, dummy_pixel.as_ptr(), 4) },
XENORA_INVALID_HANDLE
);
let mut out_rgba = [0u8; 16];
let (mut w, mut h) = (0u32, 0u32);
assert_eq!(
unsafe {
xenora_session_render_textured(sess, res, out_rgba.as_mut_ptr(), 16, &mut w, &mut h)
},
XENORA_INVALID_HANDLE
);
// Now in-flight execution completes and releases its reference
assert_eq!(test_release_resource_in_flight(sess, res), Ok(()));
// The slot is now safely reclaimed; the next allocation reuses the slot with a new generation
let mut res2 = 0u64;
assert_eq!(
unsafe { xenora_session_create_texture(sess, 2, 2, std::ptr::null(), &mut res2) },
XENORA_OK
);
assert_eq!((res & 0xFFFF_FFFF), (res2 & 0xFFFF_FFFF)); // same slot index
assert_ne!(res >> 32, res2 >> 32); // higher generation
assert_eq!(xenora_session_destroy_resource(sess, res2), XENORA_OK);
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
}
#[test]
fn invalid_stale_and_double_destroyed_resource_handles_are_rejected() {
let _guard = SERIAL.lock().unwrap();
let sess = session();
// Zero handle
assert_eq!(
xenora_session_destroy_resource(sess, XENORA_NO_RESOURCE),
XENORA_INVALID_HANDLE
);
// Unallocated slot index
let unallocated_handle = (1u64 << 32) | 999u64;
assert_eq!(
xenora_session_destroy_resource(sess, unallocated_handle),
XENORA_INVALID_HANDLE
);
// Create and destroy a valid resource
let mut res = 0u64;
assert_eq!(
unsafe { xenora_session_create_texture(sess, 2, 2, std::ptr::null(), &mut res) },
XENORA_OK
);
assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK);
// Double destroy
assert_eq!(
xenora_session_destroy_resource(sess, res),
XENORA_INVALID_HANDLE
);
// Stale handle queries
let (mut r_type, mut r_w, mut r_h, mut r_flight) = (0u32, 0u32, 0u32, 0u32);
assert_eq!(
unsafe {
xenora_session_resource_info(sess, res, &mut r_type, &mut r_w, &mut r_h, &mut r_flight)
},
XENORA_INVALID_HANDLE
);
let pixel = [0u8; 4];
assert_eq!(
unsafe { xenora_session_update_texture(sess, res, 0, 0, 1, 1, pixel.as_ptr(), 4) },
XENORA_INVALID_HANDLE
);
let mut out_rgba = [0u8; 16];
let (mut w, mut h) = (0u32, 0u32);
assert_eq!(
unsafe {
xenora_session_render_textured(sess, res, out_rgba.as_mut_ptr(), 16, &mut w, &mut h)
},
XENORA_INVALID_HANDLE
);
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
}
#[test]
fn repeated_resource_allocations_and_retirements_do_not_leak_slots() {
let _guard = SERIAL.lock().unwrap();
let sess = session();
let initial = [
255u8, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
];
let update = [255u8, 255, 0, 255];
// Run 200 cycles of create -> update -> render -> destroy
for i in 0..200 {
let mut res = 0u64;
assert_eq!(
unsafe { xenora_session_create_texture(sess, 2, 2, initial.as_ptr(), &mut res) },
XENORA_OK,
"create failed at cycle {}",
i
);
// Verify slot index is reused (res_idx is 0)
let slot_idx = (res & 0xFFFF_FFFF) as usize;
assert_eq!(slot_idx, 0, "slot index leaked at cycle {}", i);
assert_eq!(
unsafe { xenora_session_update_texture(sess, res, 0, 0, 1, 1, update.as_ptr(), 4) },
XENORA_OK
);
let mut out = [0u8; 16];
let (mut w, mut h) = (0u32, 0u32);
assert_eq!(
unsafe {
xenora_session_render_textured(sess, res, out.as_mut_ptr(), 16, &mut w, &mut h)
},
XENORA_OK
);
assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK);
}
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
}
#[test]
fn textured_pe_fixture_executes_dynamic_updates_and_retirement() {
let _guard = SERIAL.lock().unwrap();
let sess = session();
let mut out_rgba = [0u8; 16];
let mut out_w = 0u32;
let mut out_h = 0u32;
assert_eq!(
unsafe {
xenora_session_run_textured_fixture(
sess,
out_rgba.as_mut_ptr(),
16,
&mut out_w,
&mut out_h,
)
},
XENORA_OK
);
assert_eq!(out_w, 2);
assert_eq!(out_h, 2);
let expected_final: [u8; 16] = [
255, 255, 0, 255, // (0,0) yellow
0, 255, 255, 255, // (1,0) cyan
255, 0, 255, 255, // (0,1) magenta
64, 64, 64, 255, // (1,1) dark grey
];
assert_eq!(
out_rgba, expected_final,
"guest textured fixture read-back frame mismatch"
);
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
}
+37 -39
View File
@@ -10,49 +10,26 @@
//! Source: Public Windows SDK `apisetcounters.h` and documented Microsoft API-set schema.
/// Resolve an API-set virtual DLL name to its canonical Windows module name.
///
/// API sets are matched exactly against [`get_api_sets_for_canonical`]. A name
/// that merely starts like a known family is not assumed to forward anywhere.
pub fn resolve_api_set_canonical(module: &str) -> &'static str {
let lower = module.to_ascii_lowercase();
let trimmed = lower.strip_suffix(".dll").unwrap_or(&lower);
if trimmed.starts_with("api-ms-win-core-processthreads")
|| trimmed.starts_with("api-ms-win-core-processtopology")
|| trimmed.starts_with("api-ms-win-core-profile")
|| trimmed.starts_with("api-ms-win-core-sysinfo")
|| trimmed.starts_with("api-ms-win-core-interlocked")
|| trimmed.starts_with("api-ms-win-core-libraryloader")
|| trimmed.starts_with("api-ms-win-core-namedpipe")
|| trimmed.starts_with("api-ms-win-core-handle")
|| trimmed.starts_with("api-ms-win-core-errorhandling")
|| trimmed.starts_with("api-ms-win-core-debug")
|| trimmed.starts_with("api-ms-win-core-datetime")
|| trimmed.starts_with("api-ms-win-core-timezone")
|| trimmed.starts_with("api-ms-win-core-processenvironment")
|| trimmed.starts_with("api-ms-win-core-file")
|| trimmed.starts_with("api-ms-win-core-io")
|| trimmed.starts_with("api-ms-win-core-synch")
|| trimmed.starts_with("api-ms-win-core-memory")
|| trimmed.starts_with("api-ms-win-core-heap")
|| trimmed.starts_with("api-ms-win-core-string")
|| trimmed.starts_with("api-ms-win-core-localization")
{
"kernel32.dll"
} else if trimmed.starts_with("api-ms-win-core-rtlsupport") {
"ntdll.dll"
} else if trimmed.starts_with("api-ms-win-crt-") {
"ucrtbase.dll"
} else if trimmed == "vcruntime140" || trimmed == "vcruntime140_1" {
"vcruntime140.dll"
} else if trimmed == "msvcp140" || trimmed == "msvcp140_1" || trimmed == "msvcp140_2" {
"msvcp140.dll"
} else {
match module.to_ascii_lowercase().as_str() {
"kernel32.dll" | "kernelbase.dll" => "kernel32.dll",
"ntdll.dll" => "ntdll.dll",
"ws2_32.dll" => "ws2_32.dll",
"advapi32.dll" => "advapi32.dll",
_ => "unknown.dll",
for canonical in ["kernel32.dll", "ucrtbase.dll"] {
if get_api_sets_for_canonical(canonical).contains(&lower.as_str()) {
return canonical;
}
}
match lower.as_str() {
"kernel32.dll" | "kernelbase.dll" => "kernel32.dll",
"ucrtbase.dll" => "ucrtbase.dll",
"ntdll.dll" => "ntdll.dll",
"ws2_32.dll" => "ws2_32.dll",
"advapi32.dll" => "advapi32.dll",
"vcruntime140.dll" | "vcruntime140_1.dll" => "vcruntime140.dll",
"msvcp140.dll" | "msvcp140_1.dll" | "msvcp140_2.dll" => "msvcp140.dll",
_ => "unknown.dll",
}
}
/// Known API sets that forward to the given canonical host module.
@@ -78,6 +55,7 @@ pub fn get_api_sets_for_canonical(canonical: &str) -> &'static [&'static str] {
"api-ms-win-core-interlocked-l1-1-0.dll",
"api-ms-win-core-datetime-l1-1-1.dll",
"api-ms-win-core-timezone-l1-1-0.dll",
"api-ms-win-core-memory-l1-1-0.dll",
],
"ucrtbase.dll" => &[
"api-ms-win-crt-math-l1-1-0.dll",
@@ -100,6 +78,26 @@ pub fn get_api_sets_for_canonical(canonical: &str) -> &'static [&'static str] {
mod tests {
use super::*;
#[test]
fn only_listed_api_sets_resolve() {
for unknown in [
"api-ms-win-core-file-l9-9-9.dll",
"api-ms-win-core-processthreads",
"api-ms-win-core-filesomething.dll",
"api-ms-win-crt-unknown-l1-1-0.dll",
] {
assert_eq!(
resolve_api_set_canonical(unknown),
"unknown.dll",
"{unknown}"
);
}
assert_eq!(
resolve_api_set_canonical("API-MS-Win-Core-Memory-L1-1-0.DLL"),
"kernel32.dll"
);
}
#[test]
fn test_api_set_resolution() {
assert_eq!(
@@ -0,0 +1,49 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Generate the typed runtime adapters and report. Run from the repository root.
//! `--check` regenerates in memory and fails if a committed file differs.
use std::process::ExitCode;
use xenora_import_gen::typed::{generate_report, generate_rust, parse};
const REGISTRY: &str = "crates/loader/runtime/services.txt";
const TESTS: &str = "crates/loader/tests/runtime_services.rs";
const RUST: &str = "crates/loader/src/runtime_table.rs";
const REPORT: &str = "docs/runtime/services.md";
fn run() -> Result<String, String> {
let mode = std::env::args().nth(1).unwrap_or_default();
let read = |path: &str| std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"));
let services =
parse(&read(REGISTRY)?, &read(TESTS)?).map_err(|e| format!("{REGISTRY}: {e}"))?;
let outputs = [
(RUST, generate_rust(&services)),
(REPORT, generate_report(&services)),
];
for (path, text) in &outputs {
match mode.as_str() {
"generate" => std::fs::write(path, text).map_err(|e| format!("{path}: {e}"))?,
"--check" if read(path)? != *text => {
return Err(format!(
"{path} is out of date; run xenora-runtime-gen generate"
));
}
"--check" | "validate" => {}
_ => return Err("usage: xenora-runtime-gen validate|generate|--check".into()),
}
}
Ok(format!("{} services", services.len()))
}
fn main() -> ExitCode {
match run() {
Ok(message) => {
println!("{message}");
ExitCode::SUCCESS
}
Err(message) => {
eprintln!("{message}");
ExitCode::FAILURE
}
}
}
+30 -32
View File
@@ -130,7 +130,7 @@ fn gen_crt_native_registration(module: &str, symbol: &str, libc_sym: &str, note:
registry.register_with_status(
"{module}", "{symbol}",
ServiceStatus::Partial, // upgraded to Implemented when conformance test passes
|args: &Win64Args, _cpu: &mut CpuState, mem: &mut GuestMemory| -> Result<u64, ExitReason> {{
|args: &Win64Args, cpu: &mut CpuState, mem: &mut GuestMemory| -> Result<u64, ExitReason> {{
{dispatch}
}},
);
@@ -151,9 +151,8 @@ fn gen_crt_wrapper_registration(module: &str, symbol: &str, _libc_sym: &str, not
"{module}", "{symbol}",
ServiceStatus::Stub,
|args: &Win64Args, _cpu: &mut CpuState, mem: &mut GuestMemory| -> Result<u64, ExitReason> {{
// Safe-CRT wrapper: delegates to underlying function, ignores size argument.
// Guest memory is already bounds-checked by the caller's service dispatch.
Ok(0) // success
// Not implemented: fails explicitly instead of reporting success.
Err(ExitReason::IllegalInstruction(0xFE)) // 0xFE = Unsupported Host Service Call
}},
);
"#,
@@ -162,15 +161,8 @@ fn gen_crt_wrapper_registration(module: &str, symbol: &str, _libc_sym: &str, not
/// Generate a registration for a runtime helper (EH frame handlers, etc.).
fn gen_runtime_helper_registration(module: &str, symbol: &str, note: &str) -> String {
// Most runtime helpers either call abort or return 0
let body = if symbol.contains("Throw")
|| symbol.contains("terminate")
|| symbol.contains("purecall")
{
"// C++ exception/terminate: halt guest execution.\n Err(ExitReason::Halted)"
} else {
"Ok(0)"
};
// Not implemented: fails explicitly instead of reporting success.
let body = "Err(ExitReason::IllegalInstruction(0xFE)) // 0xFE = Unsupported Host Service Call";
format!(
r#"
// {note}
@@ -194,7 +186,7 @@ fn gen_stubs(manifest: &Manifest) -> String {
out.push_str(
r#"
//! Auto-generated Win32 service stubs.
//! Each stub logs its call site (module + symbol) and returns a safe default value.
//! Each stub stops the guest with an explicit unsupported-service exit.
//! Do not edit manually — regenerate with `xenora imports generate`.
use crate::cpu::{CpuState, ExitReason};
@@ -350,10 +342,11 @@ fn crt_dispatch_expr(symbol: &str, libc_sym: &str) -> String {
"acos" | "asin" | "atan" | "cos" | "sin" | "tan" | "exp" | "log" | "log10" | "log2"
| "sqrt" | "fabs" | "floor" | "ceil" | "round" | "trunc" | "exp2" => {
format!(
r#"let x = f64::from_bits(args.rcx);
r#"let x = f64::from_bits(cpu.xmm[0] as u64);
extern "C" {{ fn {libc_sym}(x: f64) -> f64; }}
let r = unsafe {{ {libc_sym}(x) }};
Ok(r.to_bits())"#,
cpu.xmm[0] = u128::from(r.to_bits());
Ok(0)"#,
libc_sym = libc_sym,
)
}
@@ -362,49 +355,54 @@ fn crt_dispatch_expr(symbol: &str, libc_sym: &str) -> String {
| "log2f" | "sqrtf" | "fabsf" | "floorf" | "ceilf" | "roundf" | "truncf" | "cbrtf"
| "erff" | "exp2f" => {
format!(
r#"let x = f32::from_bits(args.rcx as u32);
r#"let x = f32::from_bits(cpu.xmm[0] as u32);
extern "C" {{ fn {libc_sym}(x: f32) -> f32; }}
let r = unsafe {{ {libc_sym}(x) }};
Ok(r.to_bits() as u64)"#,
cpu.xmm[0] = u128::from(r.to_bits());
Ok(0)"#,
libc_sym = libc_sym,
)
}
// Math f64 × f64 → f64, two args
"atan2" | "pow" | "fmod" | "hypot" | "fmax" | "fmin" | "copysign" => {
format!(
r#"let x = f64::from_bits(args.rcx);
let y = f64::from_bits(args.rdx);
r#"let x = f64::from_bits(cpu.xmm[0] as u64);
let y = f64::from_bits(cpu.xmm[1] as u64);
extern "C" {{ fn {libc_sym}(x: f64, y: f64) -> f64; }}
let r = unsafe {{ {libc_sym}(x, y) }};
Ok(r.to_bits())"#,
cpu.xmm[0] = u128::from(r.to_bits());
Ok(0)"#,
libc_sym = libc_sym,
)
}
// Math f32 × f32 → f32
"atan2f" | "powf" | "fmodf" | "hypotf" | "fmaxf" | "fminf" | "copysignf" => {
format!(
r#"let x = f32::from_bits(args.rcx as u32);
let y = f32::from_bits(args.rdx as u32);
r#"let x = f32::from_bits(cpu.xmm[0] as u32);
let y = f32::from_bits(cpu.xmm[1] as u32);
extern "C" {{ fn {libc_sym}(x: f32, y: f32) -> f32; }}
let r = unsafe {{ {libc_sym}(x, y) }};
Ok(r.to_bits() as u64)"#,
cpu.xmm[0] = u128::from(r.to_bits());
Ok(0)"#,
libc_sym = libc_sym,
)
}
// Math f64 × f64 × f64 → f64 (fma)
"fma" => r#"let x = f64::from_bits(args.rcx);
let y = f64::from_bits(args.rdx);
let z = f64::from_bits(args.r8);
"fma" => r#"let x = f64::from_bits(cpu.xmm[0] as u64);
let y = f64::from_bits(cpu.xmm[1] as u64);
let z = f64::from_bits(cpu.xmm[2] as u64);
extern "C" { fn fma(x: f64, y: f64, z: f64) -> f64; }
let r = unsafe { fma(x, y, z) };
Ok(r.to_bits())"#
cpu.xmm[0] = u128::from(r.to_bits());
Ok(0)"#
.to_string(),
"fmaf" => r#"let x = f32::from_bits(args.rcx as u32);
let y = f32::from_bits(args.rdx as u32);
let z = f32::from_bits(args.r8 as u32);
"fmaf" => r#"let x = f32::from_bits(cpu.xmm[0] as u32);
let y = f32::from_bits(cpu.xmm[1] as u32);
let z = f32::from_bits(cpu.xmm[2] as u32);
extern "C" { fn fmaf(x: f32, y: f32, z: f32) -> f32; }
let r = unsafe { fmaf(x, y, z) };
Ok(r.to_bits() as u64)"#
cpu.xmm[0] = u128::from(r.to_bits());
Ok(0)"#
.to_string(),
// strlen(ptr) -> size_t
"strlen" => r#"// strlen: RCX = guest pointer to null-terminated string
+1
View File
@@ -31,6 +31,7 @@ pub mod ingest;
pub mod manifest;
pub mod metadata;
pub mod parse;
pub mod typed;
pub mod verify;
pub use apiset::{get_api_sets_for_canonical, resolve_api_set_canonical};
+453
View File
@@ -0,0 +1,453 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Typed runtime services: parse and validate the declarative registry, and
//! generate Win64 adapters, static metadata and a coverage report.
use crate::apiset::get_api_sets_for_canonical;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write as _;
/// Most arguments one service may declare.
const MAX_PARAMETERS: usize = 16;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Parameter {
pub name: String,
pub kind: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Service {
pub library: String,
pub symbol: String,
pub parameters: Vec<Parameter>,
pub result: String,
pub handler: String,
pub status: String,
pub aliases: Vec<String>,
pub failure: String,
pub reference: String,
pub tests: Vec<String>,
}
fn is_identifier(text: &str) -> bool {
!text.is_empty()
&& !text.as_bytes()[0].is_ascii_digit()
&& text.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_')
}
/// Adapter expression reading parameter `index`, or `None` for an unknown type.
fn reader(kind: &str, index: usize) -> Option<String> {
Some(match kind {
"u32" | "i32" | "u64" | "bool32" | "f32" | "f64" => format!("call.{kind}({index})?"),
"handle" | "ptr" => format!("call.u64({index})?"),
_ => {
let size: u32 = kind.strip_prefix("out<")?.strip_suffix('>')?.parse().ok()?;
if !(1..=4096).contains(&size) {
return None;
}
format!("call.out::<{size}>({index})?")
}
})
}
/// Rust type of a result other than void.
fn result_type(kind: &str) -> &'static str {
match kind {
"u32" => "u32",
"i32" => "i32",
"bool32" => "bool",
"f32" => "crate::runtime::Float32",
"f64" => "crate::runtime::Float64",
_ => "u64",
}
}
const RESULTS: [&str; 9] = [
"void", "u32", "i32", "u64", "bool32", "handle", "ptr", "f32", "f64",
];
/// Parse and validate the registry. `test_source` is the text of the test file
/// that must define every named test.
pub fn parse(text: &str, test_source: &str) -> Result<Vec<Service>, String> {
let mut services: Vec<Service> = Vec::new();
let mut seen_fields = BTreeSet::new();
for (number, raw) in text.lines().enumerate() {
let at = |message: &str| format!("line {}: {message}", number + 1);
let line = raw.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let (keyword, rest) = line.split_once(' ').ok_or_else(|| at("missing value"))?;
let rest = rest.trim();
if keyword == "service" {
services.push(parse_signature(rest).map_err(|message| at(&message))?);
seen_fields.clear();
continue;
}
let service = services
.last_mut()
.ok_or_else(|| at("field outside a service"))?;
let repeatable = matches!(keyword, "alias" | "test");
if !repeatable && !seen_fields.insert(keyword.to_owned()) {
return Err(at(&format!("repeated field {keyword}")));
}
match keyword {
"handler" => service.handler = rest.to_owned(),
"status" => service.status = rest.to_owned(),
"alias" => service.aliases.push(rest.to_owned()),
"fails" => service.failure = rest.to_owned(),
"ref" => service.reference = rest.to_owned(),
"test" => service.tests.push(rest.to_owned()),
other => return Err(at(&format!("unknown field {other}"))),
}
}
validate(&services, test_source)?;
Ok(services)
}
fn parse_signature(text: &str) -> Result<Service, String> {
let (library, rest) = text.split_once(' ').ok_or("missing symbol")?;
let (symbol, rest) = rest.split_once('(').ok_or("missing parameter list")?;
let (list, result) = rest.rsplit_once(") -> ").ok_or("missing result type")?;
let mut parameters = Vec::new();
if !list.trim().is_empty() {
for parameter in list.split(',') {
let (name, kind) = parameter.split_once(':').ok_or("parameter needs a type")?;
parameters.push(Parameter {
name: name.trim().to_owned(),
kind: kind.trim().to_owned(),
});
}
}
Ok(Service {
library: library.to_owned(),
symbol: symbol.trim().to_owned(),
parameters,
result: result.trim().to_owned(),
handler: String::new(),
status: String::new(),
aliases: Vec::new(),
failure: String::new(),
reference: String::new(),
tests: Vec::new(),
})
}
fn validate(services: &[Service], test_source: &str) -> Result<(), String> {
// Every key a guest could import, with the service it resolves to.
let mut keys: BTreeMap<(String, &str), usize> = BTreeMap::new();
for (index, service) in services.iter().enumerate() {
let name = format!("{}!{}", service.library, service.symbol);
let fail = |message: String| Err(format!("{name}: {message}"));
if service.library != service.library.to_ascii_lowercase()
|| !service.library.ends_with(".dll")
|| service.library.starts_with("api-ms-")
{
return fail("library must be a lower-case canonical module".into());
}
if !is_identifier(&service.symbol) {
return fail("symbol is not an identifier".into());
}
if !is_identifier(&service.handler) {
return fail("missing or invalid handler".into());
}
if service.parameters.len() > MAX_PARAMETERS {
return fail("too many parameters".into());
}
let mut names = BTreeSet::new();
for (position, parameter) in service.parameters.iter().enumerate() {
if !is_identifier(&parameter.name) || !names.insert(&parameter.name) {
return fail(format!("invalid parameter name {:?}", parameter.name));
}
if reader(&parameter.kind, position).is_none() {
return fail(format!("unsupported parameter type {:?}", parameter.kind));
}
}
if !RESULTS.contains(&service.result.as_str()) {
return fail(format!("unsupported result type {:?}", service.result));
}
if !matches!(service.status.as_str(), "implemented" | "partial" | "stub") {
return fail("status must be implemented, partial or stub".into());
}
if service.failure.is_empty() || service.reference.is_empty() {
return fail("needs a failure contract and a reference".into());
}
if service.tests.is_empty() && service.status != "stub" {
return fail("needs a test before it may claim behaviour".into());
}
for test in &service.tests {
if !is_identifier(test) || !test_source.contains(&format!("fn {test}()")) {
return fail(format!("test {test} does not exist"));
}
}
let documented = get_api_sets_for_canonical(&service.library);
let modules = std::iter::once(&service.library).chain(&service.aliases);
for module in modules {
if module != &service.library && !documented.contains(&module.as_str()) {
return fail(format!("{module} is not a listed API set of its library"));
}
if keys
.insert((module.clone(), &service.symbol), index)
.is_some()
{
return fail(format!("{module} already resolves this symbol"));
}
}
}
Ok(())
}
fn status_variant(status: &str) -> &'static str {
match status {
"implemented" => "Implemented",
"partial" => "Partial",
_ => "Stub",
}
}
fn string_list(items: &[String]) -> String {
let quoted: Vec<String> = items.iter().map(|item| format!("{item:?}")).collect();
format!("&[{}]", quoted.join(", "))
}
/// Rust source of the adapters and metadata.
pub fn generate_rust(services: &[Service]) -> String {
let mut out = String::from(
"// SPDX-License-Identifier: GPL-3.0-or-later\n\n\
// Generated by xenora-runtime-gen from crates/loader/runtime/services.txt.\n\
// Do not edit.\n\n\
use crate::imports::{ImportRegistry, ServiceStatus};\n\
use crate::runtime::{Call, Parameter, Return, ServiceContext, ServiceMetadata};\n\
use crate::services::{ServicesState, handlers};\n\
use std::sync::Arc;\n\n",
);
let _ = writeln!(
out,
"pub static SERVICES: [ServiceMetadata; {}] = [",
services.len()
);
for service in services {
let parameters: Vec<String> = service
.parameters
.iter()
.map(|p| format!("Parameter {{ name: {:?}, kind: {:?} }}", p.name, p.kind))
.collect();
let _ = writeln!(
out,
" ServiceMetadata {{\n library: {:?},\n symbol: {:?},\n \
parameters: &[{}],\n result: {:?},\n status: ServiceStatus::{},\n \
aliases: {},\n failure: {:?},\n reference: {:?},\n tests: {},\n }},",
service.library,
service.symbol,
parameters.join(", "),
service.result,
status_variant(&service.status),
string_list(&service.aliases),
service.failure,
service.reference,
string_list(&service.tests),
);
}
out.push_str(
"];\n\n/// Register every generated service and its API-set aliases.\n\
pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {\n",
);
for service in services {
let count = service.parameters.len();
let names: String = (0..count).map(|index| format!(", a{index}")).collect();
let _ = writeln!(
out,
" let s = state.clone();\n registry.register_with_status({:?}, {:?}, ServiceStatus::{}, move |args, cpu, memory| {{",
service.library,
service.symbol,
status_variant(&service.status),
);
if count == 0 {
out.push_str(" let _ = (args, &Call::new);\n");
} else {
out.push_str(" let call = Call::new(args, cpu, memory);\n");
}
for (index, parameter) in service.parameters.iter().enumerate() {
let read = reader(&parameter.kind, index).unwrap_or_default();
let _ = writeln!(out, " let a{index} = {read};");
}
// The declared type is stated so that a handler returning another one
// does not compile.
let binding = match service.result.as_str() {
"void" => "let ()".to_owned(),
result => format!("let result: {}", result_type(result)),
};
let place = if service.result == "void" {
"Ok(0)"
} else {
"Ok(result.place(cpu))"
};
let cpu = if service.result == "void" && count == 0 {
" let _ = cpu;\n"
} else {
""
};
let _ = writeln!(
out,
"{cpu} let mut context = ServiceContext {{ state: &s, memory }};\n {binding} = handlers::{}(&mut context{names})?;\n {place}\n }});",
service.handler
);
}
out.push_str(" for service in &SERVICES {\n for alias in service.aliases {\n if let Err(error) = registry.try_alias(alias, service.library, service.symbol) {\n panic!(\"{error}\");\n }\n }\n }\n}\n");
out.replace(
" let _ = (args, &Call::new);\n",
" let _ = args;\n",
)
}
/// Coverage report. Each count is distinct; aliases are never services.
pub fn generate_report(services: &[Service]) -> String {
let count = |status: &str| services.iter().filter(|s| s.status == status).count();
let handlers: BTreeSet<&str> = services.iter().map(|s| s.handler.as_str()).collect();
let aliases: usize = services.iter().map(|s| s.aliases.len()).sum();
let tested = services.iter().filter(|s| !s.tests.is_empty()).count();
let mut out = String::from(
"# Typed runtime services\n\nGenerated by `xenora-runtime-gen` from `crates/loader/runtime/services.txt`. Do not edit.\n\n\
A declared service is not a claim of compatibility. `implemented` and `partial` describe behaviour against the documented contract for the synthetic guest. No service has been independently accepted.\n\n\
| Measure | Count |\n| --- | ---: |\n",
);
for (label, value) in [
("Services with a declared ABI", services.len()),
("Generated adapters", services.len()),
("Unique handler implementations", handlers.len()),
("Implemented", count("implemented")),
("Partial", count("partial")),
("Stub", count("stub")),
("Conformance-tested through guest dispatch", tested),
("API-set aliases (not services)", aliases),
("Independently accepted", 0),
] {
let _ = writeln!(out, "| {label} | {value} |");
}
out.push_str("\n| Service | Signature | Status | Failure |\n| --- | --- | --- | --- |\n");
for service in services {
let parameters: Vec<String> = service
.parameters
.iter()
.map(|p| format!("{}: {}", p.name, p.kind))
.collect();
let _ = writeln!(
out,
"| `{}!{}` | `({}) -> {}` | {} | {} |",
service.library,
service.symbol,
parameters.join(", "),
service.result,
service.status,
service.failure
);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
const TESTS: &str = "fn works() {}";
fn entry(signature: &str, extra: &str) -> String {
format!(
"service {signature}\nhandler h\nstatus partial\nfails never\nref x.h\ntest works\n{extra}\n"
)
}
fn rejects(text: &str, message: &str) {
let error = parse(text, TESTS).unwrap_err();
assert!(error.contains(message), "{error}");
}
#[test]
fn valid_entries_parse_and_generate_deterministically() {
let text = entry(
"kernel32.dll F(a: u32, b: f64, c: out<8>) -> handle",
"alias api-ms-win-core-memory-l1-1-0.dll",
);
let services = parse(&text, TESTS).unwrap();
assert_eq!(services[0].parameters[2].kind, "out<8>");
let rust = generate_rust(&services);
assert_eq!(rust, generate_rust(&services));
for expected in ["call.u32(0)?", "call.f64(1)?", "call.out::<8>(2)?"] {
assert!(rust.contains(expected), "{expected}");
}
assert!(generate_report(&services).contains("| Unique handler implementations | 1 |"));
}
#[test]
fn conflicting_keys_are_rejected() {
let one = entry("kernel32.dll F() -> void", "");
rejects(&(one.clone() + &one), "already resolves");
let aliased = entry(
"kernel32.dll F() -> void",
"alias api-ms-win-core-memory-l1-1-0.dll",
);
let twice = entry(
"kernel32.dll G() -> void",
"alias api-ms-win-core-memory-l1-1-0.dll\nalias api-ms-win-core-memory-l1-1-0.dll",
);
assert!(parse(&aliased, TESTS).is_ok());
rejects(&twice, "already resolves");
}
#[test]
fn unsupported_declarations_are_rejected() {
rejects(
&entry("kernel32.dll F(a: struct) -> void", ""),
"parameter type",
);
rejects(
&entry("kernel32.dll F(a: out<0>) -> void", ""),
"parameter type",
);
rejects(
&entry("kernel32.dll F(a: void) -> void", ""),
"parameter type",
);
rejects(&entry("kernel32.dll F() -> out<4>", ""), "result type");
rejects(
&entry("kernel32.dll F(a: u32, a: u32) -> void", ""),
"parameter name",
);
rejects(&entry("Kernel32.dll F() -> void", ""), "canonical module");
rejects(
&entry("api-ms-win-core-memory-l1-1-0.dll F() -> void", ""),
"canonical module",
);
rejects(
&entry(
"kernel32.dll F() -> void",
"alias api-ms-win-core-made-up-l1-1-0.dll",
),
"not a listed API set",
);
rejects(
&entry("kernel32.dll F() -> void", "colour blue"),
"unknown field",
);
rejects(
&entry("kernel32.dll F() -> void", "status stub"),
"repeated field",
);
}
#[test]
fn behaviour_needs_evidence() {
let untested =
"service kernel32.dll F() -> void\nhandler h\nstatus partial\nfails never\nref x.h\n";
rejects(untested, "needs a test");
rejects(&(untested.to_owned() + "test missing\n"), "does not exist");
let stub = untested.replace("partial", "stub");
assert!(parse(&stub, TESTS).is_ok());
rejects(
&untested.replace("ref x.h\n", "test works\n"),
"needs a failure contract",
);
rejects("handler h\n", "outside a service");
}
}
File diff suppressed because it is too large. Load diff
+17 -842
View File
@@ -8,12 +8,22 @@
# per form, never from the mnemonic. See docs/shaders/semantic-registry.md.
#
# Independence: the reference interpreter (crates/ref) and the second
# interpreter (tests/validation/independent_ref.rs) never read this file.
# interpreter (tests/validation/independent_ref.rs) never read these files.
schema = 1
architecture = "gfx1030"
# Must equal the "sha256" of the source line in crates/isa/data/rdna2.jsonl.
source_sha256 = "d671ecbc36543674ab59e9b2feffd56718fd2137e7ad913c314f2e2508b9f4f7"
# Family files, in this order (forms keep the order they are listed in; each
# file holds the operand rules and forms of one encoding family, named after it).
include = [
"rdna2/sop2.toml",
"rdna2/sopc.toml",
"rdna2/sop1.toml",
"rdna2/vop2.toml",
"rdna2/vopc.toml",
"rdna2/vop3.toml",
]
# Named public documents that spec references point at.
[documents.guide]
@@ -25,853 +35,18 @@ pages = 291
title = "AMD RDNA 2 machine-readable ISA (pinned XML)"
file = "amdgpu_isa_rdna2.xml"
# Operand rules shared by a family. A rule names its destination and source
# classes; the decoder implements each rule once (rules are not per opcode).
[operand_rules.sop2_sgpr]
family = "SOP2"
dst = { field = "SDST", class = "sgpr", min = 0, max = 105 }
src = [
{ field = "SSRC0", class = "scalar_source" },
{ field = "SSRC1", class = "scalar_source" },
]
# scalar_source = normal SGPR s0-s105, inline integer -16..64, or a literal word.
max_literals = 1
# Encodings this rule rejects, so they stay unsupported rather than guessed.
unsupported = [
"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",
]
# ---- SOP2 32-bit integer and logical forms (migrated from #229/#230) ----
# Field meanings:
# Form field meanings (every family file):
# name XML instruction name (stable identity)
# 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
# vcc, exec unchanged (stated, not implied)
# wave any | wave32
# scc unchanged | carry_out | borrow | signed_overflow | nonzero | relation | selected_src0
# vcc, exec unchanged (stated, not implied) | lane_mask (vcc of a Wave32 VOPC compare)
# wave any | wave32 (wave32 exactly for the VOPC lane-mask compares)
# operands a key of [operand_rules]
# spec references; at least one guide section with a page
# verify evidence required before the form counts as verified
[[form]]
name = "S_ADD_U32"
family = "SOP2"
opcode = 0
variant = "AddU32"
operation = "add"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "carry_out"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 101 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_SUB_U32"
family = "SOP2"
opcode = 1
variant = "SubU32"
operation = "sub"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "borrow"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 101 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_ADD_I32"
family = "SOP2"
opcode = 2
variant = "AddI32"
operation = "add"
signedness = "signed"
carry_in = "none"
width = 32
scc = "signed_overflow"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 101 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_SUB_I32"
family = "SOP2"
opcode = 3
variant = "SubI32"
operation = "sub"
signedness = "signed"
carry_in = "none"
width = 32
scc = "signed_overflow"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 101 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_ADDC_U32"
family = "SOP2"
opcode = 4
variant = "AddcU32"
operation = "add"
signedness = "unsigned"
carry_in = "scc"
width = 32
scc = "carry_out"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 102 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_SUBB_U32"
family = "SOP2"
opcode = 5
variant = "SubbU32"
operation = "sub"
signedness = "unsigned"
carry_in = "scc"
width = 32
scc = "borrow"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 102 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_AND_B32"
family = "SOP2"
opcode = 14
variant = "AndB32"
operation = "and"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 102 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_OR_B32"
family = "SOP2"
opcode = 16
variant = "OrB32"
operation = "or"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 102 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_XOR_B32"
family = "SOP2"
opcode = 18
variant = "XorB32"
operation = "xor"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 102 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
# ---- Stage C: further SOP2 logical and shift forms (#215) ----
# Shifts use the low shift_count_bits of S1 as the count (guide 12.1 pseudocode).
[[form]]
name = "S_ANDN2_B32"
family = "SOP2"
opcode = 20
variant = "Andn2B32"
operation = "andn2"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 103 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_ORN2_B32"
family = "SOP2"
opcode = 22
variant = "Orn2B32"
operation = "orn2"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 103 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_NAND_B32"
family = "SOP2"
opcode = 24
variant = "NandB32"
operation = "nand"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 104 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_NOR_B32"
family = "SOP2"
opcode = 26
variant = "NorB32"
operation = "nor"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 104 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_XNOR_B32"
family = "SOP2"
opcode = 28
variant = "XnorB32"
operation = "xnor"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 104 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_LSHL_B32"
family = "SOP2"
opcode = 30
variant = "LshlB32"
operation = "lshl"
signedness = "bitwise"
carry_in = "none"
width = 32
shift_count_bits = 5
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 104 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_LSHR_B32"
family = "SOP2"
opcode = 32
variant = "LshrB32"
operation = "lshr"
signedness = "unsigned"
carry_in = "none"
width = 32
shift_count_bits = 5
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 104 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_ASHR_I32"
family = "SOP2"
opcode = 34
variant = "AshrI32"
operation = "ashr"
signedness = "signed"
carry_in = "none"
width = 32
shift_count_bits = 5
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 104 }]
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).
[operand_rules.sopc_scalar]
family = "SOPC"
src = [
{ field = "SSRC0", class = "scalar_source" },
{ field = "SSRC1", class = "scalar_source" },
]
max_literals = 1
unsupported = [
"src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline",
"src_special", "two_literals",
]
[[form]]
name = "S_CMP_EQ_I32"
family = "SOPC"
opcode = 0
variant = "CmpEqI32"
operation = "compare"
relation = "eq"
signedness = "signed"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_LG_I32"
family = "SOPC"
opcode = 1
variant = "CmpLgI32"
operation = "compare"
relation = "lg"
signedness = "signed"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_GT_I32"
family = "SOPC"
opcode = 2
variant = "CmpGtI32"
operation = "compare"
relation = "gt"
signedness = "signed"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_GE_I32"
family = "SOPC"
opcode = 3
variant = "CmpGeI32"
operation = "compare"
relation = "ge"
signedness = "signed"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_LT_I32"
family = "SOPC"
opcode = 4
variant = "CmpLtI32"
operation = "compare"
relation = "lt"
signedness = "signed"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_LE_I32"
family = "SOPC"
opcode = 5
variant = "CmpLeI32"
operation = "compare"
relation = "le"
signedness = "signed"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_EQ_U32"
family = "SOPC"
opcode = 6
variant = "CmpEqU32"
operation = "compare"
relation = "eq"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_LG_U32"
family = "SOPC"
opcode = 7
variant = "CmpLgU32"
operation = "compare"
relation = "lg"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_GT_U32"
family = "SOPC"
opcode = 8
variant = "CmpGtU32"
operation = "compare"
relation = "gt"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_GE_U32"
family = "SOPC"
opcode = 9
variant = "CmpGeU32"
operation = "compare"
relation = "ge"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_LT_U32"
family = "SOPC"
opcode = 10
variant = "CmpLtU32"
operation = "compare"
relation = "lt"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_LE_U32"
family = "SOPC"
opcode = 11
variant = "CmpLeU32"
operation = "compare"
relation = "le"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ 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"]
+238
View File
@@ -0,0 +1,238 @@
# SOP1 forms of the gfx1030 semantic registry; included by ../rdna2.toml.
# Data only; see the root file for the field meanings.
# ---- 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"]
+647
View File
@@ -0,0 +1,647 @@
# SOP2 forms of the gfx1030 semantic registry; included by ../rdna2.toml.
# Data only; see the root file for the field meanings.
# ---- SOP2 32-bit integer and logical forms (migrated from #229/#230) ----
# Operand rules shared by a family. A rule names its destination and source
# classes; the decoder implements each rule once (rules are not per opcode).
[operand_rules.sop2_sgpr]
family = "SOP2"
dst = { field = "SDST", class = "sgpr", min = 0, max = 105 }
src = [
{ field = "SSRC0", class = "scalar_source" },
{ field = "SSRC1", class = "scalar_source" },
]
# scalar_source = normal SGPR s0-s105, inline integer -16..64, or a literal word.
max_literals = 1
# Encodings this rule rejects, so they stay unsupported rather than guessed.
unsupported = [
"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",
]
[[form]]
name = "S_ADD_U32"
family = "SOP2"
opcode = 0
variant = "AddU32"
operation = "add"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "carry_out"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 101 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_SUB_U32"
family = "SOP2"
opcode = 1
variant = "SubU32"
operation = "sub"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "borrow"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 101 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_ADD_I32"
family = "SOP2"
opcode = 2
variant = "AddI32"
operation = "add"
signedness = "signed"
carry_in = "none"
width = 32
scc = "signed_overflow"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 101 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_SUB_I32"
family = "SOP2"
opcode = 3
variant = "SubI32"
operation = "sub"
signedness = "signed"
carry_in = "none"
width = 32
scc = "signed_overflow"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 101 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_ADDC_U32"
family = "SOP2"
opcode = 4
variant = "AddcU32"
operation = "add"
signedness = "unsigned"
carry_in = "scc"
width = 32
scc = "carry_out"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 102 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_SUBB_U32"
family = "SOP2"
opcode = 5
variant = "SubbU32"
operation = "sub"
signedness = "unsigned"
carry_in = "scc"
width = 32
scc = "borrow"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [
{ document = "guide", section = "12.1", page = 102 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_AND_B32"
family = "SOP2"
opcode = 14
variant = "AndB32"
operation = "and"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 102 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_OR_B32"
family = "SOP2"
opcode = 16
variant = "OrB32"
operation = "or"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 102 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_XOR_B32"
family = "SOP2"
opcode = 18
variant = "XorB32"
operation = "xor"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 102 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
# ---- Stage C: further SOP2 logical and shift forms (#215) ----
# Shifts use the low shift_count_bits of S1 as the count (guide 12.1 pseudocode).
[[form]]
name = "S_ANDN2_B32"
family = "SOP2"
opcode = 20
variant = "Andn2B32"
operation = "andn2"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 103 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_ORN2_B32"
family = "SOP2"
opcode = 22
variant = "Orn2B32"
operation = "orn2"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 103 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_NAND_B32"
family = "SOP2"
opcode = 24
variant = "NandB32"
operation = "nand"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 104 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_NOR_B32"
family = "SOP2"
opcode = 26
variant = "NorB32"
operation = "nor"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 104 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_XNOR_B32"
family = "SOP2"
opcode = 28
variant = "XnorB32"
operation = "xnor"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 104 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_LSHL_B32"
family = "SOP2"
opcode = 30
variant = "LshlB32"
operation = "lshl"
signedness = "bitwise"
carry_in = "none"
width = 32
shift_count_bits = 5
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 104 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_LSHR_B32"
family = "SOP2"
opcode = 32
variant = "LshrB32"
operation = "lshr"
signedness = "unsigned"
carry_in = "none"
width = 32
shift_count_bits = 5
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sop2_sgpr"
spec = [{ document = "guide", section = "12.1", page = 104 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_ASHR_I32"
family = "SOP2"
opcode = 34
variant = "AshrI32"
operation = "ashr"
signedness = "signed"
carry_in = "none"
width = 32
shift_count_bits = 5
scc = "nonzero"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
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"]
+269
View File
@@ -0,0 +1,269 @@
# SOPC forms of the gfx1030 semantic registry; included by ../rdna2.toml.
# Data only; see the root file for the field meanings.
# ---- Stage D: SOPC 32-bit integer compares (#215) ----
# Only SCC is written: SCC = relation(S0, S1), S0 = SSRC0 on the left (guide 12.4).
[operand_rules.sopc_scalar]
family = "SOPC"
src = [
{ field = "SSRC0", class = "scalar_source" },
{ field = "SSRC1", class = "scalar_source" },
]
max_literals = 1
unsupported = [
"src_vcc", "src_exec", "src_m0", "src_ttmp", "src_float_inline",
"src_special", "two_literals",
]
[[form]]
name = "S_CMP_EQ_I32"
family = "SOPC"
opcode = 0
variant = "CmpEqI32"
operation = "compare"
relation = "eq"
signedness = "signed"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_LG_I32"
family = "SOPC"
opcode = 1
variant = "CmpLgI32"
operation = "compare"
relation = "lg"
signedness = "signed"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_GT_I32"
family = "SOPC"
opcode = 2
variant = "CmpGtI32"
operation = "compare"
relation = "gt"
signedness = "signed"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_GE_I32"
family = "SOPC"
opcode = 3
variant = "CmpGeI32"
operation = "compare"
relation = "ge"
signedness = "signed"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_LT_I32"
family = "SOPC"
opcode = 4
variant = "CmpLtI32"
operation = "compare"
relation = "lt"
signedness = "signed"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_LE_I32"
family = "SOPC"
opcode = 5
variant = "CmpLeI32"
operation = "compare"
relation = "le"
signedness = "signed"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_EQ_U32"
family = "SOPC"
opcode = 6
variant = "CmpEqU32"
operation = "compare"
relation = "eq"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_LG_U32"
family = "SOPC"
opcode = 7
variant = "CmpLgU32"
operation = "compare"
relation = "lg"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_GT_U32"
family = "SOPC"
opcode = 8
variant = "CmpGtU32"
operation = "compare"
relation = "gt"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_GE_U32"
family = "SOPC"
opcode = 9
variant = "CmpGeU32"
operation = "compare"
relation = "ge"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_LT_U32"
family = "SOPC"
opcode = 10
variant = "CmpLtU32"
operation = "compare"
relation = "lt"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "S_CMP_LE_U32"
family = "SOPC"
opcode = 11
variant = "CmpLeU32"
operation = "compare"
relation = "le"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "relation"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "sopc_scalar"
spec = [
{ document = "guide", section = "12.4", page = 0 },
{ document = "guide", section = "5.3", page = 33 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
+350
View File
@@ -0,0 +1,350 @@
# VOP2 forms of the gfx1030 semantic registry; included by ../rdna2.toml.
# Data only; see the root file for the field meanings.
# ---- 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"]
# ---- VOP2 logical and shift forms migrated from hand-written code (#215 M27) ----
# Per lane under EXEC; no SCC, VCC or EXEC write (guide 12.7). The shifts read
# their sources reversed: D = S1 shifted by S0[4:0]; ASHRREV fills with S1's sign.
# These keep the subset the hand-written decoder accepted: both sources VGPRs.
[operand_rules.vop2_vgpr2]
family = "VOP2"
dst = { field = "VDST", class = "vgpr", min = 0, max = 255 }
src = [
{ field = "SRC0", class = "vgpr" },
{ field = "VSRC1", class = "vgpr" },
]
max_literals = 0
unsupported = [
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
"src_float_inline", "src_special", "src_literal",
]
[[form]]
name = "V_LSHRREV_B32"
family = "VOP2"
opcode = 22
variant = "LshrrevB32"
operation = "lshr"
signedness = "bitwise"
carry_in = "none"
width = 32
shift_count_bits = 5
source_order = "reversed"
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "vop2_vgpr2"
spec = [{ document = "guide", section = "12.7", page = 133 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_ASHRREV_I32"
family = "VOP2"
opcode = 24
variant = "AshrrevI32"
operation = "ashr"
signedness = "signed"
carry_in = "none"
width = 32
shift_count_bits = 5
source_order = "reversed"
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "vop2_vgpr2"
spec = [{ document = "guide", section = "12.7", page = 133 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_LSHLREV_B32"
family = "VOP2"
opcode = 26
variant = "LshlrevB32"
operation = "lshl"
signedness = "bitwise"
carry_in = "none"
width = 32
shift_count_bits = 5
source_order = "reversed"
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "vop2_vgpr2"
spec = [{ document = "guide", section = "12.7", page = 133 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_AND_B32"
family = "VOP2"
opcode = 27
variant = "AndB32"
operation = "and"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "vop2_vgpr2"
spec = [{ document = "guide", section = "12.7", page = 133 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_OR_B32"
family = "VOP2"
opcode = 28
variant = "OrB32"
operation = "or"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "vop2_vgpr2"
spec = [{ document = "guide", section = "12.7", page = 133 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_XOR_B32"
family = "VOP2"
opcode = 29
variant = "XorB32"
operation = "xor"
signedness = "bitwise"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "unchanged"
exec = "unchanged"
wave = "any"
operands = "vop2_vgpr2"
spec = [{ document = "guide", section = "12.7", page = 133 }]
verify = ["reference", "independent", "metal", "llvm_encoding"]
+39
View File
@@ -0,0 +1,39 @@
# VOP3 encodings of the gfx1030 semantic registry; included by ../rdna2.toml.
# Data only; see the root file for the field meanings.
# ---- VOP3 encoding variants of registry forms (#215) ----
# An [[encoding_variant]] re-encodes a form declared in another family file: it
# names the form (`of`), this family, the XML opcode here and the operand rule
# of this encoding, and inherits everything else (operation, signedness,
# effects) from the form. The XML must agree with the inherited declaration.
# Two VGPR sources, VGPR destination, no modifiers (ABS, OP_SEL, CLAMP, OMOD
# and NEG clear) and SRC2 the assembler's unused inline zero. This is the
# subset the decoder accepted for v_add_nc_u32_e64 before the registry.
[operand_rules.vop3_vgpr2]
family = "VOP3"
dst = { field = "VDST", class = "vgpr", min = 0, max = 255 }
src = [
{ field = "SRC0", class = "vgpr" },
{ field = "SRC1", class = "vgpr" },
]
max_literals = 0
# Only [[encoding_variant]] entries may use this rule; it hosts no new forms.
variant_only = true
unsupported = [
"src_sgpr", "src_vcc", "src_exec", "src_m0", "src_ttmp", "src_null", "src_inline",
"src_float_inline", "src_special", "src_literal", "modifiers", "src2",
]
# VOP3 opcode of a VOP2 form = VOP2 opcode + 0x100 (guide 12.7.1), e.g. 37 + 256
# = 293; each opcode below is still checked against the pinned XML.
[[encoding_variant]]
of = "V_ADD_NC_U32"
family = "VOP3"
opcode = 293
operands = "vop3_vgpr2"
spec = [
{ document = "guide", section = "12.12", page = 167 },
{ document = "guide", section = "12.7", page = 134 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
+360
View File
@@ -0,0 +1,360 @@
# VOPC forms of the gfx1030 semantic registry; included by ../rdna2.toml.
# Data only; see the root file for the field meanings.
# ---- VOPC Wave32 32-bit integer compares (migrated from #239) ----
# VCC_LO := lanes where EXEC and the relation (S0 = SRC0 on the left) hold;
# the contract is docs/shaders/vector-compare.md. relation "lg" is the guide's
# LG/NE offset 5 (Table 59), named V_CMP_NE_* in the XML. v_cmpx (EXEC writes),
# the VOP3 encoding and Wave64 stay unsupported.
[operand_rules.vopc_vcc]
family = "VOPC"
src = [
{ field = "SRC0", class = "vector_source" },
{ field = "VSRC1", class = "vgpr" },
]
# The destination is implicitly vcc_lo; SRC0 is a vector_source as for VOP2.
max_literals = 1
unsupported = [
"src_vcc_hi", "src_exec", "src_m0", "src_ttmp", "src_null", "src_float_inline", "src_special",
]
[[form]]
name = "V_CMP_LT_I32"
family = "VOPC"
opcode = 129
variant = "CmpLtI32"
operation = "compare"
relation = "lt"
signedness = "signed"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "lane_mask"
exec = "unchanged"
wave = "wave32"
operands = "vopc_vcc"
spec = [
{ document = "guide", section = "12.9", page = 150 },
{ document = "guide", section = "3.9", page = 19 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_CMP_EQ_I32"
family = "VOPC"
opcode = 130
variant = "CmpEqI32"
operation = "compare"
relation = "eq"
signedness = "signed"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "lane_mask"
exec = "unchanged"
wave = "wave32"
operands = "vopc_vcc"
spec = [
{ document = "guide", section = "12.9", page = 150 },
{ document = "guide", section = "3.9", page = 19 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_CMP_LE_I32"
family = "VOPC"
opcode = 131
variant = "CmpLeI32"
operation = "compare"
relation = "le"
signedness = "signed"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "lane_mask"
exec = "unchanged"
wave = "wave32"
operands = "vopc_vcc"
spec = [
{ document = "guide", section = "12.9", page = 150 },
{ document = "guide", section = "3.9", page = 19 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_CMP_GT_I32"
family = "VOPC"
opcode = 132
variant = "CmpGtI32"
operation = "compare"
relation = "gt"
signedness = "signed"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "lane_mask"
exec = "unchanged"
wave = "wave32"
operands = "vopc_vcc"
spec = [
{ document = "guide", section = "12.9", page = 150 },
{ document = "guide", section = "3.9", page = 19 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_CMP_NE_I32"
family = "VOPC"
opcode = 133
variant = "CmpNeI32"
operation = "compare"
relation = "lg"
signedness = "signed"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "lane_mask"
exec = "unchanged"
wave = "wave32"
operands = "vopc_vcc"
spec = [
{ document = "guide", section = "12.9", page = 150 },
{ document = "guide", section = "3.9", page = 19 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_CMP_GE_I32"
family = "VOPC"
opcode = 134
variant = "CmpGeI32"
operation = "compare"
relation = "ge"
signedness = "signed"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "lane_mask"
exec = "unchanged"
wave = "wave32"
operands = "vopc_vcc"
spec = [
{ document = "guide", section = "12.9", page = 150 },
{ document = "guide", section = "3.9", page = 19 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_CMP_LT_U32"
family = "VOPC"
opcode = 193
variant = "CmpLtU32"
operation = "compare"
relation = "lt"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "lane_mask"
exec = "unchanged"
wave = "wave32"
operands = "vopc_vcc"
spec = [
{ document = "guide", section = "12.9", page = 150 },
{ document = "guide", section = "3.9", page = 19 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_CMP_EQ_U32"
family = "VOPC"
opcode = 194
variant = "CmpEqU32"
operation = "compare"
relation = "eq"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "lane_mask"
exec = "unchanged"
wave = "wave32"
operands = "vopc_vcc"
spec = [
{ document = "guide", section = "12.9", page = 150 },
{ document = "guide", section = "3.9", page = 19 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_CMP_LE_U32"
family = "VOPC"
opcode = 195
variant = "CmpLeU32"
operation = "compare"
relation = "le"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "lane_mask"
exec = "unchanged"
wave = "wave32"
operands = "vopc_vcc"
spec = [
{ document = "guide", section = "12.9", page = 150 },
{ document = "guide", section = "3.9", page = 19 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_CMP_GT_U32"
family = "VOPC"
opcode = 196
variant = "CmpGtU32"
operation = "compare"
relation = "gt"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "lane_mask"
exec = "unchanged"
wave = "wave32"
operands = "vopc_vcc"
spec = [
{ document = "guide", section = "12.9", page = 150 },
{ document = "guide", section = "3.9", page = 19 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_CMP_NE_U32"
family = "VOPC"
opcode = 197
variant = "CmpNeU32"
operation = "compare"
relation = "lg"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "lane_mask"
exec = "unchanged"
wave = "wave32"
operands = "vopc_vcc"
spec = [
{ document = "guide", section = "12.9", page = 150 },
{ document = "guide", section = "3.9", page = 19 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_CMP_GE_U32"
family = "VOPC"
opcode = 198
variant = "CmpGeU32"
operation = "compare"
relation = "ge"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "lane_mask"
exec = "unchanged"
wave = "wave32"
operands = "vopc_vcc"
spec = [
{ document = "guide", section = "12.9", page = 150 },
{ document = "guide", section = "3.9", page = 19 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
# ---- VOPC F and T compares (guide Table 59 offsets 0 and 7) ----
# The test is false or true for every lane, so VCC_LO := 0 or the EXEC lanes
# that exist. Sources are still decoded and checked as for the other compares
# (docs/shaders/vector-compare.md section 5).
[[form]]
name = "V_CMP_F_I32"
family = "VOPC"
opcode = 128
variant = "CmpFI32"
operation = "compare"
relation = "f"
signedness = "signed"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "lane_mask"
exec = "unchanged"
wave = "wave32"
operands = "vopc_vcc"
spec = [
{ document = "guide", section = "12.9", page = 150 },
{ document = "guide", section = "3.9", page = 19 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_CMP_T_I32"
family = "VOPC"
opcode = 135
variant = "CmpTI32"
operation = "compare"
relation = "t"
signedness = "signed"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "lane_mask"
exec = "unchanged"
wave = "wave32"
operands = "vopc_vcc"
spec = [
{ document = "guide", section = "12.9", page = 150 },
{ document = "guide", section = "3.9", page = 19 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_CMP_F_U32"
family = "VOPC"
opcode = 192
variant = "CmpFU32"
operation = "compare"
relation = "f"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "lane_mask"
exec = "unchanged"
wave = "wave32"
operands = "vopc_vcc"
spec = [
{ document = "guide", section = "12.9", page = 150 },
{ document = "guide", section = "3.9", page = 19 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
[[form]]
name = "V_CMP_T_U32"
family = "VOPC"
opcode = 199
variant = "CmpTU32"
operation = "compare"
relation = "t"
signedness = "unsigned"
carry_in = "none"
width = 32
scc = "unchanged"
vcc = "lane_mask"
exec = "unchanged"
wave = "wave32"
operands = "vopc_vcc"
spec = [
{ document = "guide", section = "12.9", page = 150 },
{ document = "guide", section = "3.9", page = 19 },
]
verify = ["reference", "independent", "metal", "llvm_encoding"]
+39 -90
View File
@@ -18,7 +18,9 @@ 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, ScalarUnaryOp};
pub use semantics_gen::{
ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp,
};
/// SGPR index of `vcc_lo`, the Wave32 vector condition code.
pub const VCC_LO: u8 = 106;
@@ -93,7 +95,8 @@ impl fmt::Display for ScalarSource {
}
}
/// Relation tested by a VOPC integer compare; S0 is SRC0 and S1 is VSRC1.
/// Relation tested by a SOPC or VOPC integer compare; S0 (SSRC0 or SRC0) is on
/// the left.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CompareRelation {
/// S0 < S1 (opcode offset 1).
@@ -108,64 +111,10 @@ pub enum CompareRelation {
NotEqual,
/// S0 >= S1 (offset 6).
GreaterOrEqual,
}
/// A 32-bit VOPC integer compare: one relation over signed or unsigned operands.
///
/// The per-lane test follows the RDNA 2 ISA guide, section 12.9 (Table 59) and
/// the pinned XML descriptions. VCC and EXEC rules are in
/// docs/shaders/vector-compare.md.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct VectorCompareOp {
/// The tested relation.
pub relation: CompareRelation,
/// `_i32` (two's complement) when true, `_u32` when false.
pub signed: bool,
}
impl VectorCompareOp {
/// Lower-case mnemonic of the 32-bit VOPC encoding.
pub fn mnemonic(self) -> &'static str {
const SIGNED: [&str; 6] = [
"v_cmp_lt_i32_e32",
"v_cmp_eq_i32_e32",
"v_cmp_le_i32_e32",
"v_cmp_gt_i32_e32",
"v_cmp_ne_i32_e32",
"v_cmp_ge_i32_e32",
];
const UNSIGNED: [&str; 6] = [
"v_cmp_lt_u32_e32",
"v_cmp_eq_u32_e32",
"v_cmp_le_u32_e32",
"v_cmp_gt_u32_e32",
"v_cmp_ne_u32_e32",
"v_cmp_ge_u32_e32",
];
let index = self.relation as usize;
if self.signed {
SIGNED[index]
} else {
UNSIGNED[index]
}
}
/// The per-lane test result for operand bits S0 and S1.
pub fn test(self, src0: u32, src1: u32) -> bool {
let ordering = if self.signed {
(src0 as i32).cmp(&(src1 as i32))
} else {
src0.cmp(&src1)
};
match self.relation {
CompareRelation::Less => ordering.is_lt(),
CompareRelation::Equal => ordering.is_eq(),
CompareRelation::LessOrEqual => ordering.is_le(),
CompareRelation::Greater => ordering.is_gt(),
CompareRelation::NotEqual => ordering.is_ne(),
CompareRelation::GreaterOrEqual => ordering.is_ge(),
}
}
/// Never holds (VOPC F, offset 0).
False,
/// Always holds (VOPC T, offset 7).
True,
}
/// Output targeted by a supported uncompressed four-component export.
@@ -205,8 +154,14 @@ pub enum Instruction {
WaitStore,
/// VOP1 unmodified 32-bit vector move.
MoveB32 { dst: u8, src: VectorSource },
/// VOP3 unsigned 32-bit addition with no carry or input/output modifiers.
AddNoCarryU32 { dst: u8, src0: u8, src1: u8 },
/// VOP3 encoding of a registry VOP2 integer operation (operand rule
/// `vop3_vgpr2`): two VGPR sources and no input or output modifiers.
VectorAluVop3 {
op: VectorAluVop3Op,
dst: u8,
src0: u8,
src1: u8,
},
/// SOP1 32-bit move to a normal SGPR or an EXEC/VCC half.
ScalarMoveB32 { dst: u8, src: ScalarSource },
/// SOP1 32-bit unary integer operation writing a normal SGPR (s0-s105) and,
@@ -216,7 +171,8 @@ pub enum Instruction {
dst: u8,
src: ScalarSource,
},
/// SOP2 32-bit integer operation writing a normal SGPR (s0-s105) and SCC.
/// 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,
@@ -236,6 +192,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.
@@ -244,18 +209,6 @@ pub enum Instruction {
BranchVccZero { target: usize },
/// SOPP unconditional jump to a stream byte offset.
Branch { target: usize },
/// VOP2 logical left shift with the count in src0.
VectorLshlrevB32 { dst: u8, src0: u8, src1: u8 },
/// VOP2 logical right shift with the count in src0.
VectorLshrrevB32 { dst: u8, src0: u8, src1: u8 },
/// VOP2 arithmetic right shift with the count in src0.
VectorAshrrevI32 { dst: u8, src0: u8, src1: u8 },
/// VOP2 bitwise AND.
VectorAndB32 { dst: u8, src0: u8, src1: u8 },
/// VOP2 bitwise OR.
VectorOrB32 { dst: u8, src0: u8, src1: u8 },
/// VOP2 bitwise XOR.
VectorXorB32 { dst: u8, src0: u8, src1: u8 },
/// VOP2 single-precision addition. Execution requires an explicit FP mode.
VectorAddF32 { dst: u8, src0: u8, src1: u8 },
/// VOP2 single-precision multiplication. Execution requires an explicit FP mode.
@@ -312,22 +265,17 @@ impl Instruction {
Self::WaitLoad => "s_waitcnt",
Self::WaitStore => "s_waitcnt_vscnt",
Self::MoveB32 { .. } => "v_mov_b32_e32",
Self::AddNoCarryU32 { .. } => "v_add_nc_u32_e64",
Self::VectorAluVop3 { op, .. } => op.assembly_name(),
Self::ScalarMoveB32 { .. } => "s_mov_b32",
Self::ScalarUnary { op, .. } => op.mnemonic(),
Self::ScalarAlu { op, .. } => op.mnemonic(),
Self::ScalarCompare { op, .. } => op.mnemonic(),
Self::VectorCompare { op, .. } => op.mnemonic(),
Self::VectorCompare { op, .. } => op.assembly_name(),
Self::VectorAlu { op, .. } => op.assembly_name(),
Self::BranchSccZero { .. } => "s_cbranch_scc0",
Self::BranchExecZero { .. } => "s_cbranch_execz",
Self::BranchVccZero { .. } => "s_cbranch_vccz",
Self::Branch { .. } => "s_branch",
Self::VectorLshlrevB32 { .. } => "v_lshlrev_b32_e32",
Self::VectorLshrrevB32 { .. } => "v_lshrrev_b32_e32",
Self::VectorAshrrevI32 { .. } => "v_ashrrev_i32_e32",
Self::VectorAndB32 { .. } => "v_and_b32_e32",
Self::VectorOrB32 { .. } => "v_or_b32_e32",
Self::VectorXorB32 { .. } => "v_xor_b32_e32",
Self::VectorAddF32 { .. } => "v_add_f32_e32",
Self::VectorMulF32 { .. } => "v_mul_f32_e32",
Self::Export { .. } => "exp",
@@ -368,13 +316,9 @@ impl fmt::Display for Instruction {
Self::WaitLoad => formatter.write_str(" vmcnt(0)"),
Self::WaitStore => formatter.write_str(" null, 0"),
Self::MoveB32 { dst, src } => write!(formatter, " v{dst}, {src}"),
Self::AddNoCarryU32 { dst, src0, src1 }
| Self::VectorLshlrevB32 { dst, src0, src1 }
| Self::VectorLshrrevB32 { dst, src0, src1 }
| Self::VectorAshrrevI32 { dst, src0, src1 }
| Self::VectorAndB32 { dst, src0, src1 }
| Self::VectorOrB32 { dst, src0, src1 }
| Self::VectorXorB32 { dst, src0, src1 }
Self::VectorAluVop3 {
dst, src0, src1, ..
}
| Self::VectorAddF32 { dst, src0, src1 }
| Self::VectorMulF32 { dst, src0, src1 } => {
write!(formatter, " v{dst}, v{src0}, v{src1}")
@@ -389,6 +333,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 }
+112
View File
@@ -99,6 +99,16 @@ pub const fn ashr_nonzero_i32(a: u32, count: u32) -> (u32, bool) {
(value, value != 0)
}
/// The VOPC F test: false for every operand pair.
pub const fn false_b32(_a: u32, _b: u32) -> bool {
false
}
/// The VOPC T test: true for every operand pair.
pub const fn true_b32(_a: u32, _b: u32) -> bool {
true
}
/// `a == b` on the raw bits; signedness does not matter for equality.
pub const fn eq_b32(a: u32, b: u32) -> bool {
a == b
@@ -214,3 +224,105 @@ 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)
}
+93 -5
View File
@@ -68,6 +68,69 @@ pub enum Operation {
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,
/// `a & b`.
And,
/// `a | b`.
Or,
/// `a ^ b`.
Xor,
/// `a << (b & 31)`.
ShiftLeft,
/// Logical `a >> (b & 31)`.
ShiftRight,
/// Arithmetic (sign-filling) `a >> (b & 31)`.
ArithmeticShiftRight,
}
/// How the operands are interpreted. `Bitwise` exactly when the operation is logical.
@@ -81,12 +144,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,
}
@@ -105,13 +168,19 @@ 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.
/// What a form writes to VCC or EXEC.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum MaskEffect {
/// Not written.
Unchanged,
/// Wave32 VOPC result (VCC only): `VCC_LO` bit n is EXEC[n] & (lane n
/// exists) & test(lane n), fully written; `VCC_HI` has no known value after
/// it (docs/shaders/vector-compare.md section 3).
LaneMask,
}
/// Wave-size restriction.
@@ -135,6 +204,21 @@ pub enum OperandRule {
/// SOP1 unary: SDST is s0-s105; SSRC0 is s0-s105, an inline integer -16..64 or
/// a literal word. Everything else is rejected as unsupported.
Sop1Sgpr,
/// VOPC vector compare: the destination is `vcc_lo` (Wave32); SRC0 is a VGPR,
/// s0-s105, `vcc_lo`, an inline integer -16..64 or a literal word; VSRC1 is a
/// VGPR. Everything else is rejected as unsupported.
VopcVcc,
/// VOP3 encoding of a VOP2 vector form: VDST is v0-v255, SRC0 and SRC1 are
/// VGPRs, no input or output modifiers, SRC2 unused. Everything else is
/// rejected as unsupported.
Vop3Vgpr2,
/// 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,
/// VOP2 vector, VGPR sources only: VDST is v0-v255; SRC0 and VSRC1 are VGPRs.
/// Everything else (SGPR, inline, literal SRC0) is rejected as unsupported.
Vop2Vgpr2,
}
/// Evidence a form needs before it counts as verified.
@@ -183,12 +267,16 @@ 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.
File diff suppressed because it is too large. Load diff
+116 -2
View File
@@ -1,8 +1,13 @@
//! Ties the generated semantic registry tables to the independent XML metadata table.
use xenora_isa::meta::{EncodingFamily, FORMS as META_FORMS};
use xenora_isa::semantics::{CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, SCHEMA, SccEffect};
use xenora_isa::{ScalarAluOp, ScalarCompareOp, ScalarUnaryOp};
use xenora_isa::semantics::{
CarryIn, FORM_IDS, FORMS, GENERATED_SCHEMA, MaskEffect, SCHEMA, SccEffect, Signedness, Wave,
};
use xenora_isa::{
CompareRelation, ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op,
VectorCompareOp,
};
#[test]
fn generated_tables_match_the_schema_and_the_metadata_forms() {
@@ -53,6 +58,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)
@@ -85,3 +91,111 @@ fn scalar_unary_dispatch_selects_exactly_the_registry_sop1_forms() {
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);
}
// Exactly the registry VOP2 forms are dispatched here; the hand-written
// ones (v_add_f32, v_mul_f32) must not be.
dispatch_selects_exactly(EncodingFamily::Vop2, |word| {
VectorAluOp::from_word(word).map(|op| op.semantics().name)
});
}
#[test]
fn vector_compare_dispatch_selects_exactly_the_registry_vopc_forms() {
const OPERANDS: [u32; 6] = [0, 1, 0x7fff_ffff, 0x8000_0000, 0xffff_fffe, 0xffff_ffff];
for op in VectorCompareOp::ALL {
let row = op.semantics();
assert_eq!(row.family, EncodingFamily::Vopc);
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
assert_eq!(op.assembly_name(), format!("{}_e32", op.mnemonic()));
assert_eq!(row.relation, Some(op.relation()));
assert_eq!(op.signed(), row.signedness == Signedness::Signed);
assert_eq!(
(row.scc, row.vcc, row.exec, row.wave),
(
SccEffect::Unchanged,
MaskEffect::LaneMask,
MaskEffect::Unchanged,
Wave::Wave32
)
);
// The per-lane test is the declared relation over the declared
// signedness, with SRC0 on the left.
for src0 in OPERANDS {
for src1 in OPERANDS {
let ordering = if op.signed() {
(src0 as i32).cmp(&(src1 as i32))
} else {
src0.cmp(&src1)
};
let expected = match op.relation() {
CompareRelation::Less => ordering.is_lt(),
CompareRelation::Equal => ordering.is_eq(),
CompareRelation::LessOrEqual => ordering.is_le(),
CompareRelation::Greater => ordering.is_gt(),
CompareRelation::NotEqual => ordering.is_ne(),
CompareRelation::GreaterOrEqual => ordering.is_ge(),
CompareRelation::False => false,
CompareRelation::True => true,
};
assert_eq!(
op.test(src0, src1),
expected,
"{} {src0:#x} {src1:#x}",
row.name
);
}
}
}
// v_cmpx and the 16-, 64-bit and float compares must not be dispatched.
dispatch_selects_exactly(EncodingFamily::Vopc, |word| {
VectorCompareOp::from_word(word).map(|op| op.semantics().name)
});
}
#[test]
fn vop3_variant_dispatch_selects_exactly_the_registry_vop3_rows() {
for op in VectorAluVop3Op::ALL {
let (row, base) = (op.semantics(), op.base().semantics());
assert_eq!((row.name, row.family), (base.name, EncodingFamily::Vop3));
// The variant inherits the base declaration; only identity and the
// operand rule differ.
assert_eq!(
(
base.operation,
base.signedness,
base.scc,
base.vcc,
base.exec
),
(row.operation, row.signedness, row.scc, row.vcc, row.exec)
);
assert_eq!(row.swap_sources, base.swap_sources);
assert_eq!(op.assembly_name(), format!("{}_e64", op.base().mnemonic()));
}
dispatch_selects_exactly(EncodingFamily::Vop3, |word| {
VectorAluVop3Op::from_word(word).map(|op| op.semantics().name)
});
// No first word of the other 64-bit families (VOP3B shares VOP3's
// encoding bits) selects a variant.
for meta in META_FORMS
.iter()
.filter(|form| form.family != EncodingFamily::Vop3 && form.bytes == 8)
{
assert_eq!(
VectorAluVop3Op::from_word(meta.bits as u32),
None,
"{}",
meta.name
);
}
}
+315
View File
@@ -0,0 +1,315 @@
#!/usr/bin/env python3
"""Validate the x86-64 instruction registry and generate its Rust tables.
validate check crates/loader/x86/instructions.toml
generate validate, then write crates/loader/src/x86_table.rs
--check validate and regenerate in memory; exit 1 if the committed file
differs. Never writes.
Rejects unknown keys and vocabulary, overlapping encodings, digit and plain
forms sharing an opcode, operand constraints that contradict each other, and
flags declared both written and undefined. Standard library only (Python 3.11+).
"""
import sys
from pathlib import Path
try:
import tomllib
except ModuleNotFoundError:
sys.exit("generate_x86.py needs Python 3.11 or newer (tomllib)")
HERE = Path(__file__).resolve().parent
REGISTRY = HERE / "x86/instructions.toml"
RUST = HERE / "src/x86_table.rs"
TOP_KEYS = {"schema", "architecture", "documents", "operation", "alu", "form", "group"}
OPERATION_KEYS = {"reads", "writes", "undefined", "conditional", "terminator", "faults", "ref"}
FORM_KEYS = {"op", "map", "prefix", "opcode", "count", "digit", "enc", "size", "imm", "src",
"memory_only", "register_only", "no_rex_b", "unaligned"}
GROUP_KEYS = {"map", "opcodes", "digits"}
FLAGS = ["cf", "zf", "sf", "of", "pf", "af"]
MAPS = {"1": "ONE_BYTE", "0f": "TWO_BYTE"}
# Two-byte opcode table per mandatory prefix.
PREFIXES = {"": "TWO_BYTE", "66": "TWO_BYTE_66", "f3": "TWO_BYTE_F3", "f2": "TWO_BYTE_F2"}
SIZES = {"b": "Byte", "v": "Variable", "q": "Quad", "y": "Wide", "n": "None", "x": "Xmm"}
IMMS = {"": "None", "ib": "SignedByte", "iz": "SignedFull", "iv": "Full", "iw": "Word", "ub": "Byte",
"rel8": "SignedByte", "rel32": "Signed32"}
SRCS = {"": 0, "b": 1, "w": 2, "d": 4, "q": 8, "x": 16}
# encoding -> (Rust variant, has ModRM, required immediates)
ENCS = {
"none": ("None", False, {""}),
"rm_reg": ("RmReg", True, {""}),
"reg_rm": ("RegRm", True, {""}),
"reg_rm_imm": ("RegRmImm", True, {"ib", "iz"}),
"rm": ("Rm", True, {""}),
"rm_only": ("Rm", True, {""}),
"rm_unread": ("RmUnread", True, {""}),
"rm_imm": ("RmImm", True, {"ib", "iz"}),
"rm_one": ("RmOne", True, {""}),
"rm_cl": ("RmCl", True, {""}),
"acc_imm": ("AccImm", False, {"ib", "iz"}),
"op_reg": ("OpReg", False, {""}),
"op_reg_imm": ("OpRegImm", False, {"ib", "iv"}),
"imm": ("Imm", False, {"ib", "iz", "iw"}),
"rel": ("Rel", False, {"rel8", "rel32"}),
"xmm_rm": ("XmmRm", True, {""}),
"rm_xmm": ("RmXmm", True, {""}),
"xmm_rm_imm": ("XmmRmImm", True, {"ub"}),
"rm_imm_xmm": ("RmImmXmm", True, {"ub"}),
"xmm_gpr": ("XmmGpr", True, {""}),
"gpr_xmm": ("GprXmm", True, {""}),
"xmm_gpr_imm": ("XmmGprImm", True, {"ub"}),
"reg_xmm": ("RegXmm", True, {""}),
"reg_xmm_imm": ("RegXmmImm", True, {"ub"}),
}
# Encodings whose ModRM operand is an XMM register or memory of the source width.
XMM_RM = {"xmm_rm", "rm_xmm", "xmm_rm_imm", "rm_imm_xmm", "reg_xmm", "reg_xmm_imm"}
# One-byte opcodes that are prefixes or the two-byte escape, never instructions.
RESERVED = {0x0F, 0x26, 0x2E, 0x36, 0x3E, 0x64, 0x65, 0x66, 0x67, 0xF0, 0xF2, 0xF3,
*range(0x40, 0x50)}
class RegistryError(Exception):
pass
def fail(message):
raise RegistryError(message)
def check_keys(where, table, allowed):
unknown = set(table) - allowed
if unknown:
fail(f"{where}: unknown keys {sorted(unknown)}")
def flag_set(where, text):
names = text.split()
for name in names:
if name not in FLAGS:
fail(f"{where}: unknown flag {name!r}")
if len(set(names)) != len(names):
fail(f"{where}: repeated flag")
return set(names)
def load(text):
"""Parse and validate the registry text, returning (operations, forms)."""
data = tomllib.loads(text)
check_keys("registry", data, TOP_KEYS)
if data.get("schema") != 1 or data.get("architecture") != "x86-64":
fail("registry: unsupported schema or architecture")
documents = data["documents"]
operations = {}
for name, entry in data["operation"].items():
where = f"operation {name}"
check_keys(where, entry, OPERATION_KEYS)
reads, writes, undefined = (
flag_set(where, entry.get(key, "")) for key in ("reads", "writes", "undefined"))
if writes & undefined:
fail(f"{where}: flags both written and undefined: {sorted(writes & undefined)}")
if entry.get("ref", " ").split()[0:1] == [] or entry.get("ref", "").split()[0] not in documents:
fail(f"{where}: reference must name a listed document")
operations[name] = {
"reads": reads, "writes": writes, "undefined": undefined,
"conditional": entry.get("conditional", False),
"terminator": entry.get("terminator", False),
"faults": entry.get("faults", False),
}
forms = [dict(form) for form in data["form"]]
for form in forms:
check_keys(f"form {form.get('op')}", form, FORM_KEYS)
for index, op in enumerate(data["alu"]["operations"]):
base = index * 8
for offset, (enc, size, imm) in enumerate([
("rm_reg", "b", ""), ("rm_reg", "v", ""), ("reg_rm", "b", ""),
("reg_rm", "v", ""), ("acc_imm", "b", "ib"), ("acc_imm", "v", "iz")]):
forms.append({"op": op, "opcode": base + offset, "enc": enc, "size": size, "imm": imm})
for opcode, size, imm in ((0x80, "b", "ib"), (0x81, "v", "iz"), (0x83, "v", "ib")):
forms.append({"op": op, "opcode": opcode, "digit": index, "enc": "rm_imm",
"size": size, "imm": imm})
for group in data["group"]:
check_keys("group", group, GROUP_KEYS)
for opcode, size, imm, enc in group["opcodes"]:
for digit, op in sorted(group["digits"].items()):
forms.append({"op": op, "map": group.get("map", "1"), "opcode": opcode,
"digit": int(digit), "enc": enc, "size": size, "imm": imm})
claimed = {}
used = set()
for form in forms:
form.setdefault("map", "1")
for key in ("prefix", "imm", "src"):
form.setdefault(key, "")
form.setdefault("count", 1)
form.setdefault("digit", None)
where = f"form {form['op']} {form['map']}:{form['opcode']:02x}"
for key, allowed in (("op", operations), ("map", MAPS), ("prefix", PREFIXES),
("enc", ENCS), ("size", SIZES), ("imm", IMMS), ("src", SRCS)):
if form[key] not in allowed:
fail(f"{where}: unknown {key} {form[key]!r}")
used.add(form["op"])
_, modrm, imms = ENCS[form["enc"]]
if form["imm"] not in imms:
fail(f"{where}: immediate {form['imm']!r} is not valid for {form['enc']}")
if form["imm"] == "ib" and form["size"] == "n":
fail(f"{where}: a sized immediate needs an operand size")
if form["digit"] is not None and (not modrm or not 0 <= form["digit"] <= 7):
fail(f"{where}: a digit needs a ModRM encoding and a value 0-7")
if form.get("memory_only") and form.get("register_only"):
fail(f"{where}: memory_only and register_only contradict")
if (form.get("memory_only") or form.get("register_only")) and not modrm:
fail(f"{where}: operand restriction without ModRM")
sourced = form["enc"] in XMM_RM or form["enc"] == "xmm_gpr_imm"
if sourced != bool(form["src"]) and form["enc"] not in ("reg_rm", "rm"):
fail(f"{where}: source size does not match the encoding")
if form["src"] and not sourced and form["enc"] == "rm" and form["size"] != "n":
fail(f"{where}: source size does not match the encoding")
if (form["size"] == "x") != (form["enc"] in XMM_RM - {"reg_xmm", "reg_xmm_imm"}
or form["enc"] == "xmm_gpr_imm"):
fail(f"{where}: XMM size does not match the encoding")
if form.get("unaligned") and form["src"] != "x":
fail(f"{where}: alignment applies only to 16-byte operands")
if form["prefix"] and form["map"] != "0f":
fail(f"{where}: mandatory prefixes are only supported in map 0f")
if form["count"] not in (1, 8, 16) or form["opcode"] % form["count"]:
fail(f"{where}: count must be 1, 8 or 16 and aligned")
if form["count"] == 8 and form["enc"] not in ("op_reg", "op_reg_imm"):
fail(f"{where}: count 8 encodes a register")
if form["count"] == 16 and form["op"] not in ("jcc", "cmov", "setcc"):
fail(f"{where}: count 16 encodes a condition")
for opcode in range(form["opcode"], form["opcode"] + form["count"]):
if not 0 <= opcode <= 0xFF:
fail(f"{where}: opcode out of range")
if form["map"] == "1" and opcode in RESERVED:
fail(f"{where}: {opcode:02x} is a prefix or escape")
slots = claimed.setdefault((form["map"], form["prefix"], opcode), {})
if form["digit"] in slots or (slots and (None in slots or form["digit"] is None)):
fail(f"{where}: overlapping encoding")
slots[form["digit"]] = form
# 0x66 selects a 16-bit operand for an unprefixed integer form, so a
# 66-prefixed form at the same opcode would be ambiguous.
for other, sized in (("66", form), ("", None)):
if form["map"] == "0f" and form["prefix"] == ("" if other == "66" else "66"):
for rival in claimed.get(("0f", other, opcode), {}).values():
plain = sized or rival
if plain["size"] in ("b", "v"):
fail(f"{where}: 0x66 is both an operand size and a mandatory prefix")
if form["digit"] is not None:
first = next(iter(slots.values()))
if (first["size"] in "bn") != (form["size"] in "bn"):
fail(f"{where}: group mixes byte and wider operands")
unused = set(operations) - used
if unused:
fail(f"operations without forms: {sorted(unused)}")
return operations, forms
def camel(name):
return name[0].upper() + name[1:]
def mask(flags):
return sum(1 << FLAGS.index(flag) for flag in flags)
def generate(operations, forms):
out = ["// SPDX-License-Identifier: GPL-3.0-or-later",
"",
"// Generated by crates/loader/generate_x86.py from crates/loader/x86/instructions.toml.",
"// Do not edit.",
"",
"use crate::x86_decode::{Encoding, Entry, Form, Immediate, OperandSize};",
"",
"/// Operations with decodable forms.",
"#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]",
"pub enum Op {"]
out += [f" {camel(name)}," for name in operations]
out += ["}", "", "impl Op {",
" pub const ALL: &[Op] = &["
+ ", ".join(f"Op::{camel(n)}" for n in operations) + "];", ""]
def method(doc, name, kind, value):
out.append(f" /// {doc}")
out.append(f" pub const fn {name}(self) -> {kind} {{")
out.append(" match self {")
for op, entry in operations.items():
out.append(f" Op::{camel(op)} => {value(op, entry)},")
out.extend([" }", " }", ""])
method("Lower-case mnemonic stem.", "name", "&'static str", lambda op, e: f'"{op}"')
bits = "Flag bits: 1 CF, 2 ZF, 4 SF, 8 OF, 16 PF, 32 AF."
method(f"Flags read. {bits}", "flags_read", "u8", lambda op, e: mask(e["reads"]))
method(f"Flags always written. {bits}", "flags_written", "u8",
lambda op, e: 0 if e["conditional"] else mask(e["writes"]))
method(f"Flags this operation may change. {bits}", "flags_touched", "u8",
lambda op, e: mask(e["writes"]))
method(f"Architecturally undefined flags. {bits}", "flags_undefined", "u8",
lambda op, e: mask(e["undefined"]))
method("Ends a translated block.", "is_terminator", "bool",
lambda op, e: str(e["terminator"]).lower())
method("Can raise an arithmetic fault.", "can_fault", "bool",
lambda op, e: str(e["faults"]).lower())
vector = {form["op"] for form in forms if form["size"] == "x" or "xmm" in form["enc"]}
method("Uses an XMM register.", "is_vector", "bool", lambda op, e: str(op in vector).lower())
out[-1:] = ["}", ""]
out.append(f"pub static FORMS: [Form; {len(forms)}] = [")
for form in forms:
out.append(
f" Form {{ op: Op::{camel(form['op'])}, encoding: Encoding::{ENCS[form['enc']][0]}, "
f"size: OperandSize::{SIZES[form['size']]}, immediate: Immediate::{IMMS[form['imm']]}, "
f"source: {SRCS[form['src']]}, has_modrm: {str(ENCS[form['enc']][1]).lower()}, "
f"memory_only: {str(bool(form.get('memory_only'))).lower()}, "
f"register_only: {str(bool(form.get('register_only'))).lower()}, "
f"no_rex_b: {str(bool(form.get('no_rex_b'))).lower()}, "
f"unaligned: {str(bool(form.get('unaligned'))).lower()} }},")
out += ["];", ""]
groups = []
tables = {name: ["Entry::Unsupported"] * 256 for name in ("ONE_BYTE", *PREFIXES.values())}
slots = {}
for index, form in enumerate(forms):
table = MAPS[form["map"]] if form["map"] == "1" else PREFIXES[form["prefix"]]
for opcode in range(form["opcode"], form["opcode"] + form["count"]):
slots.setdefault((table, opcode), {})[form["digit"]] = index
for (table, opcode), digits in sorted(slots.items()):
if None in digits:
tables[table][opcode] = f"Entry::Form({digits[None]})"
else:
row = [str(digits.get(d, 65535)) for d in range(8)]
tables[table][opcode] = f"Entry::Group({len(groups)})"
groups.append("[" + ", ".join(row) + "]")
out.append("/// Form per ModRM digit; 65535 marks an unsupported digit.")
out.append(f"pub static GROUPS: [[u16; 8]; {len(groups)}] = [")
out += [f" {row}," for row in groups]
out += ["];", ""]
for name, entries in tables.items():
out.append(f"pub static {name}: [Entry; 256] = [")
for start in range(0, 256, 4):
out.append(" " + ", ".join(entries[start:start + 4]) + ",")
out += ["];", ""]
return "\n".join(out[:-1]) + "\n"
def main(argv):
if len(argv) != 2 or argv[1] not in ("validate", "generate", "--check"):
sys.exit("usage: generate_x86.py validate|generate|--check")
try:
operations, forms = load(REGISTRY.read_text())
except (RegistryError, KeyError, tomllib.TOMLDecodeError) as error:
sys.exit(f"instructions.toml: {error}")
rust = generate(operations, forms)
if argv[1] == "generate":
RUST.write_text(rust)
elif argv[1] == "--check" and (not RUST.exists() or RUST.read_text() != rust):
sys.exit("x86_table.rs is out of date; run generate_x86.py generate")
encodings = sum(form["count"] for form in forms)
print(f"{len(operations)} operations, {len(forms)} forms, {encodings} opcode slots")
if __name__ == "__main__":
main(sys.argv)
+181
View File
@@ -0,0 +1,181 @@
# Typed runtime service registry.
#
# Data only. `cargo run -p xenora-import-gen --bin xenora-runtime-gen` validates
# it and writes crates/loader/src/runtime_table.rs (typed Win64 adapters and
# static metadata) and docs/runtime/services.md (coverage counts).
#
# service <library> <symbol>(<name>: <type>, ...) -> <type>
# handler <Rust function in crates/loader/src/services.rs or crt.rs>
# status implemented | partial | stub
# alias <documented API set that forwards this symbol>
# fails <failure contract>
# ref <public header or document>
# test <test function in crates/loader/tests/runtime_services.rs>
#
# Types: u32 i32 u64 bool32 handle ptr out<N> f32 f64, and void as a result.
# A bool32 argument is true when nonzero. out<N> is a guest pointer to N bytes
# the service writes. Arguments are assigned by position (Microsoft x64 calling
# convention): RCX, RDX, R8, R9 or XMM0-XMM3 for floats, then the stack.
#
# "status" describes behaviour against the documented contract. A service needs
# at least one test before it may be implemented or partial.
service kernel32.dll SetProcessPriorityBoost(process: handle, disable: bool32) -> bool32
handler set_process_priority_boost
status partial
alias api-ms-win-core-processthreads-l1-1-2.dll
fails 0 with ERROR_INVALID_HANDLE
ref processthreadsapi.h SetProcessPriorityBoost
test priority_boost_round_trips_and_checks_its_handle
service kernel32.dll GetProcessPriorityBoost(process: handle, disabled: out<4>) -> bool32
handler get_process_priority_boost
status partial
alias api-ms-win-core-processthreads-l1-1-2.dll
fails 0 with ERROR_INVALID_HANDLE or ERROR_NOACCESS
ref processthreadsapi.h GetProcessPriorityBoost
test priority_boost_round_trips_and_checks_its_handle
service kernel32.dll GetCurrentProcess() -> handle
handler get_current_process
status implemented
alias api-ms-win-core-processthreads-l1-1-0.dll
fails never
ref processthreadsapi.h GetCurrentProcess
test identity_services_return_documented_pseudo_handles_and_ids
service kernel32.dll GetProcessId(process: handle) -> u32
handler get_process_id
status partial
alias api-ms-win-core-processthreads-l1-1-0.dll
fails 0 with ERROR_INVALID_HANDLE
ref processthreadsapi.h GetProcessId
test identity_services_return_documented_pseudo_handles_and_ids
service kernel32.dll GetCurrentThread() -> handle
handler get_current_thread
status implemented
alias api-ms-win-core-processthreads-l1-1-0.dll
fails never
ref processthreadsapi.h GetCurrentThread
test identity_services_return_documented_pseudo_handles_and_ids
service kernel32.dll GetCurrentProcessId() -> u32
handler get_current_process_id
status implemented
alias api-ms-win-core-processthreads-l1-1-0.dll
fails never
ref processthreadsapi.h GetCurrentProcessId
test identity_services_return_documented_pseudo_handles_and_ids
service kernel32.dll GetCurrentThreadId() -> u32
handler get_current_thread_id
status implemented
alias api-ms-win-core-processthreads-l1-1-0.dll
fails never
ref processthreadsapi.h GetCurrentThreadId
test identity_services_return_documented_pseudo_handles_and_ids
service kernel32.dll OpenThread(access: u32, inherit: bool32, thread: u32) -> handle
handler open_thread
status partial
alias api-ms-win-core-processthreads-l1-1-0.dll
fails 0 with ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED or ERROR_NOT_ENOUGH_MEMORY
ref processthreadsapi.h OpenThread
test thread_handles_check_access_and_are_rejected_once_closed
service kernel32.dll GetThreadPriority(thread: handle) -> i32
handler get_thread_priority
status partial
alias api-ms-win-core-processthreads-l1-1-0.dll
fails THREAD_PRIORITY_ERROR_RETURN with ERROR_INVALID_HANDLE or ERROR_ACCESS_DENIED
ref processthreadsapi.h GetThreadPriority
test thread_handles_check_access_and_are_rejected_once_closed
service kernel32.dll SetThreadPriority(thread: handle, priority: i32) -> bool32
handler set_thread_priority
status partial
alias api-ms-win-core-processthreads-l1-1-0.dll
fails 0 with ERROR_INVALID_HANDLE, ERROR_ACCESS_DENIED, ERROR_NOT_SUPPORTED or ERROR_INVALID_PARAMETER
ref processthreadsapi.h SetThreadPriority
test thread_handles_check_access_and_are_rejected_once_closed
service kernel32.dll CloseHandle(object: handle) -> bool32
handler close_handle
status partial
alias api-ms-win-core-handle-l1-1-0.dll
fails 0 with ERROR_INVALID_HANDLE
ref handleapi.h CloseHandle
test thread_handles_check_access_and_are_rejected_once_closed
service kernel32.dll GetSystemTimeAsFileTime(time: out<8>) -> void
handler get_system_time_as_file_time
status implemented
alias api-ms-win-core-sysinfo-l1-1-0.dll
fails guest fault on an invalid pointer
ref sysinfoapi.h GetSystemTimeAsFileTime
test system_time_comes_from_the_injected_clock
service kernel32.dll GetLastError() -> u32
handler get_last_error
status partial
alias api-ms-win-core-errorhandling-l1-1-0.dll
fails never
ref errhandlingapi.h GetLastError
test last_error_is_set_by_failures_and_by_the_guest
service kernel32.dll SetLastError(code: u32) -> void
handler set_last_error
status partial
alias api-ms-win-core-errorhandling-l1-1-0.dll
fails never
ref errhandlingapi.h SetLastError
test last_error_is_set_by_failures_and_by_the_guest
service kernel32.dll VirtualAlloc(address: ptr, size: u64, kind: u32, protect: u32) -> ptr
handler virtual_alloc
status partial
alias api-ms-win-core-memory-l1-1-0.dll
fails 0 with ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED, ERROR_INVALID_ADDRESS or ERROR_NOT_ENOUGH_MEMORY
ref memoryapi.h VirtualAlloc
test virtual_memory_is_mapped_released_and_bounded
service kernel32.dll VirtualFree(address: ptr, size: u64, kind: u32) -> bool32
handler virtual_free
status partial
alias api-ms-win-core-memory-l1-1-0.dll
fails 0 with ERROR_NOT_SUPPORTED, ERROR_INVALID_PARAMETER or ERROR_INVALID_ADDRESS
ref memoryapi.h VirtualFree
test virtual_memory_is_mapped_released_and_bounded
service ucrtbase.dll sqrt(x: f64) -> f64
handler sqrt
status partial
alias api-ms-win-crt-math-l1-1-0.dll
fails NaN for a negative argument; errno is not set
ref math.h sqrt (ISO C, IEC 60559 squareRoot)
test floating_arguments_and_results_use_xmm_registers
service ucrtbase.dll sqrtf(x: f32) -> f32
handler sqrtf
status partial
alias api-ms-win-crt-math-l1-1-0.dll
fails NaN for a negative argument; errno is not set
ref math.h sqrtf (ISO C, IEC 60559 squareRoot)
test floating_arguments_and_results_use_xmm_registers
service ucrtbase.dll fabs(x: f64) -> f64
handler fabs
status implemented
alias api-ms-win-crt-math-l1-1-0.dll
fails never
ref math.h fabs (ISO C, IEC 60559 abs)
test floating_arguments_and_results_use_xmm_registers
service ucrtbase.dll fabsf(x: f32) -> f32
handler fabsf
status implemented
alias api-ms-win-crt-math-l1-1-0.dll
fails never
ref math.h fabsf (ISO C, IEC 60559 abs)
test floating_arguments_and_results_use_xmm_registers
+192
View File
@@ -188,6 +188,198 @@ impl Arm64Assembler {
self.emit(0x93403c00 | ((wn as u32 & 0x1f) << 5) | (xd as u32 & 0x1f));
}
/// SXTB (32-bit/sign-extended): SXTB Wd, Wn (SBFM Wd, Wn, #0, #7)
///
/// Writing the 32-bit destination form clears bits 63:32 of the
/// 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 (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));
}
/// LSR (immediate, 64-bit): LSR Xd, Xn, #shift (UBFM Xd, Xn, #shift, #63)
pub fn lsr_imm_64(&mut self, xd: u8, xn: u8, shift: u8) {
self.emit(
0xd340fc00
| ((u32::from(shift) & 0x3f) << 16)
| ((u32::from(xn) & 0x1f) << 5)
| (u32::from(xd) & 0x1f),
);
}
/// CSET Wd, cond (CSINC Wd, WZR, WZR, inverted cond)
pub fn cset_32(&mut self, wd: u8, cond: Condition) {
self.emit(0x1a9f_07e0 | (((cond as u32) ^ 1) << 12) | (u32::from(wd) & 0x1f));
}
/// CSEL Xd, Xn, Xm, cond
pub fn csel_64(&mut self, xd: u8, xn: u8, xm: u8, cond: Condition) {
self.emit(
0x9a80_0000
| ((u32::from(xm) & 0x1f) << 16)
| ((cond as u32) << 12)
| ((u32::from(xn) & 0x1f) << 5)
| (u32::from(xd) & 0x1f),
);
}
/// STRB Wt, [Xn, #offset]
pub fn strb_uoff(&mut self, wt: u8, xn: u8, offset: u32) {
self.emit(
0x3900_0000
| ((offset & 0xfff) << 10)
| ((u32::from(xn) & 0x1f) << 5)
| (u32::from(wt) & 0x1f),
);
}
/// LDRB Wt, [Xn, #offset]
pub fn ldrb_uoff(&mut self, wt: u8, xn: u8, offset: u32) {
self.emit(
0x3940_0000
| ((offset & 0xfff) << 10)
| ((u32::from(xn) & 0x1f) << 5)
| (u32::from(wt) & 0x1f),
);
}
/// EOR Wd, Wn, Wm, LSR #shift
pub fn eor_lsr_32(&mut self, wd: u8, wn: u8, wm: u8, shift: u8) {
self.emit(
0x4a40_0000
| ((u32::from(wm) & 0x1f) << 16)
| ((u32::from(shift) & 0x1f) << 10)
| ((u32::from(wn) & 0x1f) << 5)
| (u32::from(wd) & 0x1f),
);
}
/// ORR Wd, Wn, Wm
pub fn orr_reg_32(&mut self, wd: u8, wn: u8, wm: u8) {
self.emit(
0x2a00_0000
| ((u32::from(wm) & 0x1f) << 16)
| ((u32::from(wn) & 0x1f) << 5)
| (u32::from(wd) & 0x1f),
);
}
/// BIC Wd, Wn, Wm (Wn & !Wm)
pub fn bic_reg_32(&mut self, wd: u8, wn: u8, wm: u8) {
self.emit(
0x0a20_0000
| ((u32::from(wm) & 0x1f) << 16)
| ((u32::from(wn) & 0x1f) << 5)
| (u32::from(wd) & 0x1f),
);
}
/// MVN Xd, Xm (ORN Xd, XZR, Xm)
pub fn mvn_64(&mut self, xd: u8, xm: u8) {
self.emit(0xaa20_03e0 | ((u32::from(xm) & 0x1f) << 16) | (u32::from(xd) & 0x1f));
}
/// UBFX Wd, Wn, #bit, #1
pub fn ubfx_bit_32(&mut self, wd: u8, wn: u8, bit: u8) {
self.emit(
0x5300_0000
| ((u32::from(bit) & 0x1f) << 16)
| ((u32::from(bit) & 0x1f) << 10)
| ((u32::from(wn) & 0x1f) << 5)
| (u32::from(wd) & 0x1f),
);
}
/// REV Xd, Xn, or REV Wd, Wn when not `wide`
pub fn rev(&mut self, d: u8, n: u8, wide: bool) {
self.emit(
(if wide { 0xdac0_0c00 } else { 0x5ac0_0800 })
| ((u32::from(n) & 0x1f) << 5)
| (u32::from(d) & 0x1f),
);
}
/// LDR Qt, [Xn, #offset] (offset a multiple of 16)
pub fn ldr_q_uoff(&mut self, qt: u8, xn: u8, offset: u32) {
self.emit(
0x3dc0_0000
| (((offset / 16) & 0xfff) << 10)
| ((u32::from(xn) & 0x1f) << 5)
| (u32::from(qt) & 0x1f),
);
}
/// STR Qt, [Xn, #offset] (offset a multiple of 16)
pub fn str_q_uoff(&mut self, qt: u8, xn: u8, offset: u32) {
self.emit(
0x3d80_0000
| (((offset / 16) & 0xfff) << 10)
| ((u32::from(xn) & 0x1f) << 5)
| (u32::from(qt) & 0x1f),
);
}
/// FMOV Dd, Xn (clears the upper half of Vd)
pub fn fmov_d_from_x(&mut self, vd: u8, xn: u8) {
self.emit(0x9e67_0000 | ((u32::from(xn) & 0x1f) << 5) | (u32::from(vd) & 0x1f));
}
/// MOV Vd.D[1], Xn
pub fn ins_d1_from_x(&mut self, vd: u8, xn: u8) {
self.emit(0x4e18_1c00 | ((u32::from(xn) & 0x1f) << 5) | (u32::from(vd) & 0x1f));
}
/// Three-register vector instruction from its base word
pub fn neon3(&mut self, base: u32, vd: u8, vn: u8, vm: u8) {
self.emit(
base | ((u32::from(vm) & 0x1f) << 16)
| ((u32::from(vn) & 0x1f) << 5)
| (u32::from(vd) & 0x1f),
);
}
/// SHL Vd, Vn, #shift for 0 <= shift < lane
pub fn shl_vector(&mut self, vd: u8, vn: u8, lane: u32, shift: u32) {
self.emit(
0x4f00_5400
| ((lane + shift) << 16)
| ((u32::from(vn) & 0x1f) << 5)
| (u32::from(vd) & 0x1f),
);
}
/// USHR Vd, Vn, #shift for 1 <= shift <= lane
pub fn ushr_vector(&mut self, vd: u8, vn: u8, lane: u32, shift: u32) {
self.emit(
0x6f00_0400
| ((2 * lane - shift) << 16)
| ((u32::from(vn) & 0x1f) << 5)
| (u32::from(vd) & 0x1f),
);
}
/// SSHR Vd, Vn, #shift for 1 <= shift <= lane
pub fn sshr_vector(&mut self, vd: u8, vn: u8, lane: u32, shift: u32) {
self.emit(
0x4f00_0400
| ((2 * lane - shift) << 16)
| ((u32::from(vn) & 0x1f) << 5)
| (u32::from(vd) & 0x1f),
);
}
/// SXTW (64-bit/sign-extended): SXTW Xd, Wn (SBFM Xd, Xn, #0, #31)
pub fn sxtw_64(&mut self, xd: u8, wn: u8) {
self.emit(0x93407c00 | ((wn as u32 & 0x1f) << 5) | (xd as u32 & 0x1f));
}
/// ADD (extended/shifted register, 32-bit): ADD Wd, Wn, Wm
pub fn add_reg_32(&mut self, wd: u8, wn: u8, wm: u8) {
self.emit(
+66 -527
View File
@@ -6,6 +6,8 @@
//! Never executes guest x86-64 code natively on host ARM64.
use crate::memory::{GuestMemory, MemoryError};
use crate::x86_decode::{DecodeError, decode};
use crate::x86_exec;
use std::fmt;
/// 64-bit General Purpose Register identifiers in x86-64.
@@ -53,32 +55,34 @@ impl Register {
}
}
/// Instruction prefixes decoded ahead of an opcode.
///
/// The interpreter decodes these once per instruction and passes them to the
/// helpers that need them, so prefix state travels as one typed value instead
/// of a list of independent booleans.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
struct Prefixes {
/// REX.W: 64-bit operand size.
rex_w: bool,
/// REX.R: extends the ModRM `reg` field to R8-R15.
rex_r: bool,
/// REX.B: extends the ModRM `rm` field to R8-R15.
rex_b: bool,
/// The GS segment override prefix (0x65) is present.
seg_gs: bool,
/// The FS segment override prefix (0x64) is present.
seg_fs: bool,
}
/// RFLAGS status bits tracked during guest execution.
#[repr(C)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct RFlags {
pub cf: bool, // Carry flag
pub zf: bool, // Zero flag
pub sf: bool, // Sign flag
pub of: bool, // Overflow flag
pub pf: bool, // Parity flag
pub af: bool, // Auxiliary carry flag
}
/// SSE control and status register. Reset state masks every exception and
/// rounds to nearest (Intel SDM Vol. 1, 10.2.3).
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Mxcsr(pub u32);
impl Mxcsr {
pub const RESET: u32 = 0x1F80;
/// Bits that exist; loading any other bit raises #GP.
pub const WRITABLE: u32 = 0xFFFF;
}
impl Default for Mxcsr {
fn default() -> Self {
Self(Self::RESET)
}
}
/// x86-64 CPU state. Native DBT accesses the general registers and RIP by offset.
@@ -90,6 +94,9 @@ pub struct CpuState {
pub flags: RFlags,
pub gs_base: u64,
pub fs_base: u64,
/// XMM0-XMM15, lane 0 in the low bits.
pub xmm: [u128; 16],
pub mxcsr: Mxcsr,
}
impl CpuState {
@@ -102,6 +109,8 @@ impl CpuState {
flags: RFlags::default(),
gs_base: 0,
fs_base: 0,
xmm: [0; 16],
mxcsr: Mxcsr::default(),
}
}
@@ -124,6 +133,14 @@ pub enum ExitReason {
MemoryFault(MemoryError),
IllegalInstruction(u8),
StackUnderflow,
/// Division by zero or a quotient too large for its destination (#DE).
DivideError,
/// A misaligned 16-byte operand or a reserved MXCSR bit (#GP).
GeneralProtection,
/// An unmasked SSE floating-point exception (#XM); MXCSR holds its flags.
SimdException,
/// A host service changed a register the Win64 ABI requires it to preserve.
ServiceAbiViolation,
}
impl fmt::Display for ExitReason {
@@ -136,6 +153,12 @@ impl fmt::Display for ExitReason {
Self::MemoryFault(e) => write!(f, "memory fault: {e}"),
Self::IllegalInstruction(op) => write!(f, "illegal or unsupported opcode: 0x{op:02x}"),
Self::StackUnderflow => write!(f, "stack underflow"),
Self::DivideError => write!(f, "guest divide error"),
Self::GeneralProtection => write!(f, "guest general-protection fault"),
Self::SimdException => write!(f, "guest SIMD floating-point exception"),
Self::ServiceAbiViolation => {
write!(f, "host service changed a nonvolatile guest register")
}
}
}
}
@@ -156,8 +179,15 @@ mod layout_tests {
assert_eq!(std::mem::offset_of!(CpuState, flags), 16 * 8 + 8);
assert_eq!(std::mem::offset_of!(CpuState, gs_base), 16 * 8 + 8 + 8);
assert_eq!(std::mem::offset_of!(CpuState, fs_base), 16 * 8 + 8 + 8 + 8);
assert_eq!(std::mem::size_of::<RFlags>(), 4);
assert_eq!(std::mem::size_of::<CpuState>(), 16 * 8 + 8 + 8 + 8 + 8);
assert_eq!(std::mem::size_of::<RFlags>(), 6);
assert_eq!(std::mem::offset_of!(RFlags, cf), 0);
assert_eq!(std::mem::offset_of!(RFlags, zf), 1);
assert_eq!(std::mem::offset_of!(RFlags, sf), 2);
assert_eq!(std::mem::offset_of!(RFlags, of), 3);
assert_eq!(std::mem::offset_of!(RFlags, pf), 4);
assert_eq!(std::mem::offset_of!(RFlags, af), 5);
assert_eq!(std::mem::offset_of!(CpuState, xmm), 160);
assert_eq!(std::mem::offset_of!(CpuState, mxcsr), 160 + 16 * 16);
let cpu = CpuState::default();
let base = std::ptr::addr_of!(cpu) as usize;
@@ -391,514 +421,23 @@ impl<'a> Interpreter<'a> {
}
}
fn fetch_u8(&mut self) -> Result<u8, ExitReason> {
let b = self
.memory
.fetch_instruction_byte(self.cpu.rip)
.map_err(ExitReason::MemoryFault)?;
self.cpu.rip += 1;
Ok(b)
}
fn fetch_u32(&mut self) -> Result<u32, ExitReason> {
let mut bytes = [0u8; 4];
for b in &mut bytes {
*b = self.fetch_u8()?;
}
Ok(u32::from_le_bytes(bytes))
}
fn fetch_u64(&mut self) -> Result<u64, ExitReason> {
let mut bytes = [0u8; 8];
for b in &mut bytes {
*b = self.fetch_u8()?;
}
Ok(u64::from_le_bytes(bytes))
}
fn fetch_i8(&mut self) -> Result<i8, ExitReason> {
Ok(self.fetch_u8()? as i8)
}
fn fetch_i32(&mut self) -> Result<i32, ExitReason> {
Ok(self.fetch_u32()? as i32)
}
/// Single-step execution. Returns Ok(Some(ExitReason)) on clean exit (HLT/SYSCALL).
/// Single-step execution. Returns Ok(Some(ExitReason)) on clean exit
/// (HLT/SYSCALL). An error leaves the guest state unchanged.
pub fn step(&mut self) -> Result<Option<ExitReason>, ExitReason> {
let start = self.cpu.rip;
let result = self.execute_instruction();
if result.is_err() {
self.cpu.rip = start;
}
result
}
fn execute_instruction(&mut self) -> Result<Option<ExitReason>, ExitReason> {
let mut prefixes = Prefixes::default();
let mut byte = self.fetch_u8()?;
// Handle legacy segment prefixes: 0x65 (GS), 0x64 (FS)
while byte == 0x65 || byte == 0x64 {
if byte == 0x65 {
prefixes.seg_gs = true;
} else {
prefixes.seg_fs = true;
}
byte = self.fetch_u8()?;
}
// Handle REX prefix (0x40 - 0x4F)
if (byte & 0xF0) == 0x40 {
prefixes.rex_w = (byte & 0x08) != 0;
prefixes.rex_r = (byte & 0x04) != 0;
prefixes.rex_b = (byte & 0x01) != 0;
byte = self.fetch_u8()?;
}
match byte {
// HLT: Halt execution
0xF4 => Ok(Some(ExitReason::Halt)),
0x0F => match self.fetch_u8()? {
0x05 => Ok(Some(ExitReason::Syscall(self.cpu.get(Register::Rax)))),
op @ 0xC8..=0xCF => {
let reg = Register::from_index((op & 7) | (u8::from(prefixes.rex_b) << 3));
let value = self.cpu.get(reg);
let reversed = if prefixes.rex_w {
value.swap_bytes()
} else {
u64::from((value as u32).swap_bytes())
};
self.cpu.set(reg, reversed);
Ok(None)
}
op => Err(ExitReason::IllegalInstruction(op)),
},
// MOV r32, imm32 (0xB8 + reg) or MOV r64, imm64 with REX.W
0xB8..=0xBF => {
let reg_idx = (byte - 0xB8) + if prefixes.rex_b { 8 } else { 0 };
let reg = Register::from_index(reg_idx);
if prefixes.rex_w {
let imm = self.fetch_u64()?;
self.cpu.set(reg, imm);
} else {
let imm = self.fetch_u32()? as u64; // Zero-extended in x86-64
self.cpu.set(reg, imm);
}
Ok(None)
}
// XOR r/m, reg (0x31) or XOR reg, r/m (0x33)
0x31 | 0x33 => {
let modrm = self.fetch_u8()?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
let (src, dst) = if byte == 0x31 { (reg, rm) } else { (rm, reg) };
let val1 = self.cpu.get(dst);
let val2 = self.cpu.get(src);
let res = if prefixes.rex_w {
val1 ^ val2
} else {
(val1 as u32 ^ val2 as u32) as u64
};
self.cpu.set(dst, res);
self.update_flags_logic(res, prefixes.rex_w);
Ok(None)
}
// ADD r/m, reg (0x01) or ADD reg, r/m (0x03)
0x01 | 0x03 => {
let modrm = self.fetch_u8()?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
let (src, dst) = if byte == 0x01 { (reg, rm) } else { (rm, reg) };
let val1 = self.cpu.get(dst);
let val2 = self.cpu.get(src);
let (res, flags) = if prefixes.rex_w {
add64(val1, val2)
} else {
let (r, f) = add32(val1 as u32, val2 as u32);
(r as u64, f)
};
self.cpu.set(dst, res);
self.cpu.flags = flags;
Ok(None)
}
// SUB r/m, reg (0x29) or SUB reg, r/m (0x2B)
0x29 | 0x2B => {
let modrm = self.fetch_u8()?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
let (src, dst) = if byte == 0x29 { (reg, rm) } else { (rm, reg) };
let val1 = self.cpu.get(dst);
let val2 = self.cpu.get(src);
let (res, flags) = if prefixes.rex_w {
sub64(val1, val2)
} else {
let (r, f) = sub32(val1 as u32, val2 as u32);
(r as u64, f)
};
self.cpu.set(dst, res);
self.cpu.flags = flags;
Ok(None)
}
// CMP reg, r/m (0x3B) or CMP r/m, reg (0x39)
0x39 | 0x3B => {
let modrm = self.fetch_u8()?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
let (v1, v2) = if byte == 0x39 {
(self.cpu.get(rm), self.cpu.get(reg))
} else {
(self.cpu.get(reg), self.cpu.get(rm))
};
let (_, flags) = if prefixes.rex_w {
sub64(v1, v2)
} else {
let (r, f) = sub32(v1 as u32, v2 as u32);
(r as u64, f)
};
self.cpu.flags = flags;
Ok(None)
}
// Immediate group 1: 0x83 /op reg, imm8
0x83 => {
let modrm = self.fetch_u8()?;
let op = (modrm >> 3) & 7;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, &prefixes)?;
let imm8 = self.fetch_i8()? as i64;
let imm = imm8 as u64;
let val = self.cpu.get(rm);
match op {
0 => {
// ADD
let (res, flags) = if prefixes.rex_w {
add64(val, imm)
} else {
let (r, f) = add32(val as u32, imm as u32);
(r as u64, f)
};
self.cpu.set(rm, res);
self.cpu.flags = flags;
}
5 => {
// SUB
let (res, flags) = if prefixes.rex_w {
sub64(val, imm)
} else {
let (r, f) = sub32(val as u32, imm as u32);
(r as u64, f)
};
self.cpu.set(rm, res);
self.cpu.flags = flags;
}
7 => {
// CMP
let (_, flags) = if prefixes.rex_w {
sub64(val, imm)
} else {
let (r, f) = sub32(val as u32, imm as u32);
(r as u64, f)
};
self.cpu.flags = flags;
}
_ => return Err(ExitReason::IllegalInstruction(byte)),
}
let _ = reg;
Ok(None)
}
// MOV r/m, reg (0x89) or MOV reg, r/m (0x8B)
0x89 | 0x8B => {
let modrm = self.fetch_u8()?;
self.execute_mov_rm(modrm, &prefixes, byte == 0x8B)
}
// JMP rel8 (0xEB)
0xEB => {
let offset = self.fetch_i8()? as i64;
self.cpu.rip = (self.cpu.rip as i64 + offset) as u64;
Ok(None)
}
// JMP rel32 (0xE9)
0xE9 => {
let offset = self.fetch_i32()? as i64;
self.cpu.rip = (self.cpu.rip as i64 + offset) as u64;
Ok(None)
}
// JZ/JE rel8 (0x74)
0x74 => {
let offset = self.fetch_i8()? as i64;
if self.cpu.flags.zf {
self.cpu.rip = (self.cpu.rip as i64 + offset) as u64;
}
Ok(None)
}
// JNZ/JNE rel8 (0x75)
0x75 => {
let offset = self.fetch_i8()? as i64;
if !self.cpu.flags.zf {
self.cpu.rip = (self.cpu.rip as i64 + offset) as u64;
}
Ok(None)
}
// CALL rel32 (0xE8)
0xE8 => {
let offset = self.fetch_i32()? as i64;
let target = (self.cpu.rip as i64 + offset) as u64;
let ret_addr = self.cpu.rip;
self.push_u64(ret_addr)?;
self.cpu.rip = target;
Ok(None)
}
// RET (0xC3)
0xC3 => {
let ret_addr = self.pop_u64()?;
self.cpu.rip = ret_addr;
Ok(None)
}
// PUSH reg (0x50..=0x57)
0x50..=0x57 => {
let reg_idx = (byte - 0x50) + if prefixes.rex_b { 8 } else { 0 };
let reg = Register::from_index(reg_idx);
let val = self.cpu.get(reg);
self.push_u64(val)?;
Ok(None)
}
// POP reg (0x58..=0x5F)
0x58..=0x5F => {
let reg_idx = (byte - 0x58) + if prefixes.rex_b { 8 } else { 0 };
let reg = Register::from_index(reg_idx);
let val = self.pop_u64()?;
self.cpu.set(reg, val);
Ok(None)
}
_ => Err(ExitReason::IllegalInstruction(byte)),
}
}
fn push_u64(&mut self, val: u64) -> Result<(), ExitReason> {
let sp = self.cpu.get(Register::Rsp);
let new_sp = sp.checked_sub(8).ok_or(ExitReason::StackUnderflow)?;
self.memory
.write_u64(new_sp, val)
.map_err(ExitReason::MemoryFault)?;
self.cpu.set(Register::Rsp, new_sp);
Ok(())
}
fn pop_u64(&mut self) -> Result<u64, ExitReason> {
let sp = self.cpu.get(Register::Rsp);
let val = self.memory.read_u64(sp).map_err(ExitReason::MemoryFault)?;
self.cpu.set(Register::Rsp, sp + 8);
Ok(val)
}
fn decode_modrm_reg_reg(
&self,
modrm: u8,
prefixes: &Prefixes,
) -> Result<(Register, Register), ExitReason> {
let mode = (modrm >> 6) & 3;
if mode != 3 {
return Err(ExitReason::IllegalInstruction(modrm));
}
let reg_idx = ((modrm >> 3) & 7) + if prefixes.rex_r { 8 } else { 0 };
let rm_idx = (modrm & 7) + if prefixes.rex_b { 8 } else { 0 };
Ok((Register::from_index(reg_idx), Register::from_index(rm_idx)))
}
fn execute_mov_rm(
&mut self,
modrm: u8,
prefixes: &Prefixes,
is_load: bool,
) -> Result<Option<ExitReason>, ExitReason> {
let mode = (modrm >> 6) & 3;
let reg_idx = ((modrm >> 3) & 7) + if prefixes.rex_r { 8 } else { 0 };
let rm_idx = (modrm & 7) + if prefixes.rex_b { 8 } else { 0 };
let reg = Register::from_index(reg_idx);
if mode == 3 {
// Register-to-register move
let rm = Register::from_index(rm_idx);
if is_load {
let val = self.cpu.get(rm);
self.cpu.set(
reg,
if prefixes.rex_w {
val
} else {
val as u32 as u64
},
);
} else {
let val = self.cpu.get(reg);
self.cpu.set(
rm,
if prefixes.rex_w {
val
} else {
val as u32 as u64
},
);
}
return Ok(None);
}
// Memory operand [rm + disp] or SIB
let (base_val, disp): (u64, i64) = if (rm_idx & 7) == 4 {
// SIB byte follows ModR/M
let sib = self.fetch_u8()?;
let scale_shift = (sib >> 6) & 3;
let index_raw = ((sib >> 3) & 7) + if prefixes.rex_r { 8 } else { 0 }; // SIB.index can use REX.X; here index_raw
let base_raw = (sib & 7) + if prefixes.rex_b { 8 } else { 0 };
let base_v = if mode == 0 && (sib & 7) == 5 {
// disp32 with no base register
0u64
} else {
self.cpu.get(Register::from_index(base_raw))
};
let index_v = if (sib >> 3) & 7 == 4 {
// index == 4 means no index register (ESP/RSP)
0u64
} else {
self.cpu.get(Register::from_index(index_raw)) << scale_shift
};
let d: i64 = match mode {
0 => {
if (sib & 7) == 5 {
self.fetch_i32()? as i64
} else {
0
}
}
1 => self.fetch_i8()? as i64,
2 => self.fetch_i32()? as i64,
_ => unreachable!(),
};
(base_v.wrapping_add(index_v), d)
} else {
let base_reg = Register::from_index(rm_idx);
let base_val = self.cpu.get(base_reg);
let disp: i64 = match mode {
0 => {
if (rm_idx & 7) == 5 {
// RIP-relative displacement disp32
self.fetch_i32()? as i64
} else {
0
}
}
1 => self.fetch_i8()? as i64,
2 => self.fetch_i32()? as i64,
_ => unreachable!(),
};
(base_val, disp)
};
let mut effective_addr = if mode == 0 && (rm_idx & 7) == 5 {
(self.cpu.rip as i64 + disp) as u64
} else {
(base_val as i64 + disp) as u64
};
if prefixes.seg_gs {
effective_addr = effective_addr.wrapping_add(self.cpu.gs_base);
} else if prefixes.seg_fs {
effective_addr = effective_addr.wrapping_add(self.cpu.fs_base);
}
if is_load {
// Load from memory to reg
if prefixes.rex_w {
let val = self
.memory
.read_u64(effective_addr)
.map_err(ExitReason::MemoryFault)?;
self.cpu.set(reg, val);
} else {
let val = self
.memory
.read_u32(effective_addr)
.map_err(ExitReason::MemoryFault)?;
self.cpu.set(reg, val as u64);
}
} else {
// Store from reg to memory
let val = self.cpu.get(reg);
if prefixes.rex_w {
self.memory
.write_u64(effective_addr, val)
.map_err(ExitReason::MemoryFault)?;
} else {
self.memory
.write_u32(effective_addr, val as u32)
.map_err(ExitReason::MemoryFault)?;
}
}
Ok(None)
}
fn update_flags_logic(&mut self, val: u64, is_64: bool) {
self.cpu.flags.cf = false;
self.cpu.flags.of = false;
if is_64 {
self.cpu.flags.zf = val == 0;
self.cpu.flags.sf = (val as i64) < 0;
} else {
let val32 = val as u32;
self.cpu.flags.zf = val32 == 0;
self.cpu.flags.sf = (val32 as i32) < 0;
}
let memory = &*self.memory;
let insn = decode(self.cpu.rip, |address| {
memory.fetch_instruction_byte(address)
})
.map_err(ExitReason::from)?;
x86_exec::execute(&mut self.cpu, self.memory, &insn)
}
}
fn add64(a: u64, b: u64) -> (u64, RFlags) {
let (res, cf) = a.overflowing_add(b);
let of = ((a ^ res) & (b ^ res) & 0x8000_0000_0000_0000) != 0;
let sf = (res as i64) < 0;
let zf = res == 0;
(res, RFlags { cf, zf, sf, of })
}
fn add32(a: u32, b: u32) -> (u32, RFlags) {
let (res, cf) = a.overflowing_add(b);
let of = ((a ^ res) & (b ^ res) & 0x8000_0000) != 0;
let sf = (res as i32) < 0;
let zf = res == 0;
(res, RFlags { cf, zf, sf, of })
}
fn sub64(a: u64, b: u64) -> (u64, RFlags) {
let (res, cf) = a.overflowing_sub(b);
let of = ((a ^ b) & (a ^ res) & 0x8000_0000_0000_0000) != 0;
let sf = (res as i64) < 0;
let zf = res == 0;
(res, RFlags { cf, zf, sf, of })
}
fn sub32(a: u32, b: u32) -> (u32, RFlags) {
let (res, cf) = a.overflowing_sub(b);
let of = ((a ^ b) & (a ^ res) & 0x8000_0000) != 0;
let sf = (res as i32) < 0;
let zf = res == 0;
(res, RFlags { cf, zf, sf, of })
impl From<DecodeError<MemoryError>> for ExitReason {
fn from(error: DecodeError<MemoryError>) -> Self {
match error {
DecodeError::Fetch(fault) => Self::MemoryFault(fault),
DecodeError::Unsupported(byte) => Self::IllegalInstruction(byte),
}
}
}
+1462 -1210
View File
File diff suppressed because it is too large. Load diff
+218
View File
@@ -0,0 +1,218 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Bounded parser for the PE32+ import directory (Microsoft PE format,
//! "The .idata Section"). Binding and static inspection both use it, so they
//! agree on which imports an image has and how they are named.
use std::fmt;
/// Most import descriptors accepted in one image.
pub const MAX_DESCRIPTORS: usize = 1024;
/// Most imported symbols accepted in one image.
pub const MAX_IMPORTS: usize = 65_536;
/// Longest module or symbol name accepted, in bytes.
pub const MAX_NAME_LEN: usize = 4096;
const DESCRIPTOR_LEN: u32 = 20;
const ORDINAL_FLAG: u64 = 1 << 63;
/// How an import names its target. A symbol that happens to be spelled like an
/// ordinal is still a name.
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum ImportName {
Name(String),
Ordinal(u16),
}
impl fmt::Display for ImportName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Name(name) => f.write_str(name),
Self::Ordinal(ordinal) => write!(f, "Ordinal#{ordinal}"),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ImportEntry {
/// Module name as spelled in the image.
pub module: String,
pub name: ImportName,
/// RVA of the import address table slot.
pub iat_rva: u32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ImportTableError {
/// A structure at this RVA is not fully backed by section data.
OutOfBounds {
rva: u32,
},
/// A name is empty, unterminated, too long or not printable ASCII.
MalformedName {
rva: u32,
},
/// A lookup entry at this RVA sets reserved bits.
ReservedBits {
rva: u32,
},
TooManyDescriptors,
TooManyImports,
}
impl fmt::Display for ImportTableError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::OutOfBounds { rva } => write!(f, "import data at RVA 0x{rva:08x} is truncated"),
Self::MalformedName { rva } => write!(f, "malformed import name at RVA 0x{rva:08x}"),
Self::ReservedBits { rva } => {
write!(
f,
"reserved bits set in the import lookup at RVA 0x{rva:08x}"
)
}
Self::TooManyDescriptors => write!(f, "more than {MAX_DESCRIPTORS} import descriptors"),
Self::TooManyImports => write!(f, "more than {MAX_IMPORTS} imported symbols"),
}
}
}
impl std::error::Error for ImportTableError {}
/// Reads image bytes by RVA, requiring every byte to be backed by the file.
struct Reader<'a, F> {
bytes: &'a [u8],
rva_to_offset: F,
}
impl<F: Fn(u32) -> Option<usize>> Reader<'_, F> {
fn byte(&self, rva: u32) -> Option<u8> {
self.bytes.get((self.rva_to_offset)(rva)?).copied()
}
fn array<const N: usize>(&self, rva: u32) -> Result<[u8; N], ImportTableError> {
let mut out = [0; N];
for (index, byte) in out.iter_mut().enumerate() {
*byte = rva
.checked_add(index as u32)
.and_then(|rva| self.byte(rva))
.ok_or(ImportTableError::OutOfBounds { rva })?;
}
Ok(out)
}
fn u32(&self, rva: u32) -> Result<u32, ImportTableError> {
self.array(rva).map(u32::from_le_bytes)
}
fn name(&self, rva: u32) -> Result<String, ImportTableError> {
let malformed = ImportTableError::MalformedName { rva };
let mut name = String::new();
for index in 0..=MAX_NAME_LEN as u32 {
let byte = rva
.checked_add(index)
.and_then(|rva| self.byte(rva))
.ok_or(malformed)?;
match byte {
0 if name.is_empty() => return Err(malformed),
0 => return Ok(name),
0x21..=0x7E => name.push(char::from(byte)),
_ => return Err(malformed),
}
}
Err(malformed)
}
}
/// Parse the import directory at `directory_rva`.
///
/// Returns every import before the first problem, and the problem. Callers that
/// execute an image must refuse it if there is one; inspection may report both.
pub fn parse_imports(
bytes: &[u8],
directory_rva: u32,
rva_to_offset: impl Fn(u32) -> Option<usize>,
) -> (Vec<ImportEntry>, Option<ImportTableError>) {
let reader = Reader {
bytes,
rva_to_offset,
};
let mut entries = Vec::new();
let error = collect(&reader, directory_rva, &mut entries).err();
(entries, error)
}
fn collect<F: Fn(u32) -> Option<usize>>(
reader: &Reader<'_, F>,
directory_rva: u32,
entries: &mut Vec<ImportEntry>,
) -> Result<(), ImportTableError> {
let mut descriptor = directory_rva;
for _ in 0..MAX_DESCRIPTORS {
// Reading the whole descriptor also proves its field RVAs do not overflow.
reader.array::<{ DESCRIPTOR_LEN as usize }>(descriptor)?;
let lookup_rva = reader.u32(descriptor)?;
let name_rva = reader.u32(descriptor + 12)?;
let address_rva = reader.u32(descriptor + 16)?;
// The table ends with an empty descriptor.
if lookup_rva == 0 && name_rva == 0 && address_rva == 0 {
return Ok(());
}
let module = reader.name(name_rva)?;
collect_symbols(reader, &module, lookup_rva, address_rva, entries)?;
descriptor = descriptor
.checked_add(DESCRIPTOR_LEN)
.ok_or(ImportTableError::OutOfBounds { rva: descriptor })?;
}
Err(ImportTableError::TooManyDescriptors)
}
fn collect_symbols<F: Fn(u32) -> Option<usize>>(
reader: &Reader<'_, F>,
module: &str,
lookup_rva: u32,
address_rva: u32,
entries: &mut Vec<ImportEntry>,
) -> Result<(), ImportTableError> {
// Without a lookup table the address table holds the same entries on disk.
let start = if lookup_rva != 0 {
lookup_rva
} else {
address_rva
};
for index in 0.. {
let at = |base: u32| {
base.checked_add(index * 8)
.ok_or(ImportTableError::OutOfBounds { rva: base })
};
let lookup = at(start)?;
let value = u64::from_le_bytes(reader.array(lookup)?);
if value == 0 {
return Ok(());
}
if entries.len() == MAX_IMPORTS {
return Err(ImportTableError::TooManyImports);
}
let iat_rva = at(address_rva)?;
let name = if value & ORDINAL_FLAG != 0 {
let ordinal = value & !ORDINAL_FLAG;
ImportName::Ordinal(
u16::try_from(ordinal)
.map_err(|_| ImportTableError::ReservedBits { rva: lookup })?,
)
} else {
let hint = u32::try_from(value)
.ok()
.filter(|rva| rva >> 31 == 0)
.ok_or(ImportTableError::ReservedBits { rva: lookup })?;
// The name follows a two-byte export-table hint.
ImportName::Name(reader.name(hint + 2)?)
};
entries.push(ImportEntry {
module: module.to_owned(),
name,
iat_rva,
});
}
Ok(())
}
+215 -168
View File
@@ -7,6 +7,7 @@
//! guest services without exposing raw host function pointers.
use crate::cpu::{CpuState, ExitReason, Register};
use crate::import_table::{ImportName, ImportTableError, MAX_NAME_LEN, parse_imports};
use crate::memory::{GuestMemory, MemoryError};
use crate::pe::ParsedPe;
use std::collections::HashMap;
@@ -19,8 +20,7 @@ pub const IMPORT_TRAMPOLINE_STRIDE: u64 = 16;
/// Typed error resulting from import resolution or service dispatch.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ImportError {
MalformedDirectory,
DirectoryOutOfBounds { rva: u32 },
Table(ImportTableError),
UnresolvedImport { module: String, symbol: String },
Memory(MemoryError),
}
@@ -28,10 +28,7 @@ pub enum ImportError {
impl fmt::Display for ImportError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::MalformedDirectory => write!(f, "malformed PE import directory"),
Self::DirectoryOutOfBounds { rva } => {
write!(f, "import directory at RVA 0x{rva:08x} is out of bounds")
}
Self::Table(e) => write!(f, "malformed PE imports: {e}"),
Self::UnresolvedImport { module, symbol } => {
write!(f, "unresolved import dependency: {module}!{symbol}")
}
@@ -42,6 +39,38 @@ impl fmt::Display for ImportError {
impl std::error::Error for ImportError {}
/// Why a service could not be added to the registry.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RegistryError {
/// The key already names a different service.
Duplicate {
module: String,
symbol: String,
},
/// An alias names a service that does not exist.
UnknownTarget {
module: String,
symbol: String,
},
InvalidName {
module: String,
symbol: String,
},
}
impl fmt::Display for RegistryError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let (problem, module, symbol) = match self {
Self::Duplicate { module, symbol } => ("is already registered", module, symbol),
Self::UnknownTarget { module, symbol } => ("is not registered", module, symbol),
Self::InvalidName { module, symbol } => ("is not a valid name", module, symbol),
};
write!(f, "import {module}!{symbol} {problem}")
}
}
impl std::error::Error for RegistryError {}
impl From<MemoryError> for ImportError {
fn from(e: MemoryError) -> Self {
Self::Memory(e)
@@ -128,7 +157,8 @@ pub struct ServiceDescriptor {
/// Registry for resolving and binding import symbols to guest trampoline VAs.
pub struct ImportRegistry {
services: HashMap<(String, String), usize>, // (module_lowercase, symbol) -> service_index
// (lower-case module, name) -> service index. Symbol names keep their case.
services: HashMap<(String, ImportName), usize>,
handlers: Vec<ServiceDescriptor>,
trampoline_to_service: HashMap<u64, usize>, // Trampoline VA -> service_index
}
@@ -148,18 +178,82 @@ impl ImportRegistry {
}
}
fn service_index(&self, module: &str, symbol: &str) -> Option<usize> {
/// The one lookup used by binding, inspection and reports. Module names
/// compare without case, as Windows does; symbol names are exact. API sets
/// resolve only through registered aliases.
pub fn resolve(&self, module: &str, name: &ImportName) -> Option<&ServiceDescriptor> {
self.index(module, name).map(|index| &self.handlers[index])
}
fn index(&self, module: &str, name: &ImportName) -> Option<usize> {
self.services
.get(&(module.to_ascii_lowercase(), symbol.to_owned()))
.get(&(module.to_ascii_lowercase(), name.clone()))
.copied()
}
fn service_index(&self, module: &str, symbol: &str) -> Option<usize> {
self.index(module, &ImportName::Name(symbol.to_owned()))
}
fn check_key(module: &str, name: &ImportName) -> Result<(), RegistryError> {
let printable = |text: &str| {
!text.is_empty()
&& text.len() <= MAX_NAME_LEN
&& text.bytes().all(|b| b.is_ascii_graphic())
};
let valid = printable(module)
&& match name {
ImportName::Name(symbol) => printable(symbol),
ImportName::Ordinal(_) => true,
};
if valid {
Ok(())
} else {
Err(RegistryError::InvalidName {
module: module.to_owned(),
symbol: name.to_string(),
})
}
}
/// Check whether the exact import key has a binding, including stub handlers.
pub fn has_binding(&self, module: &str, symbol: &str) -> bool {
self.service_index(module, symbol).is_some()
}
/// Register a host-provided guest service.
/// Register a host-provided guest service under a name or an ordinal.
pub fn try_register(
&mut self,
module: &str,
name: ImportName,
status: ServiceStatus,
handler: ServiceHandler,
) -> Result<(), RegistryError> {
Self::check_key(module, &name)?;
let key = (module.to_ascii_lowercase(), name);
if self.services.contains_key(&key) {
return Err(RegistryError::Duplicate {
module: key.0,
symbol: key.1.to_string(),
});
}
let index = self.handlers.len();
self.handlers.push(ServiceDescriptor {
module: key.0.clone(),
symbol: key.1.to_string(),
handler,
status,
});
self.services.insert(key, index);
Ok(())
}
/// Register a named service.
///
/// # Panics
///
/// If the name is invalid or already registered, so that one host module
/// cannot silently replace another's service.
pub fn register<F>(&mut self, module: &str, symbol: &str, handler: F)
where
F: Fn(&Win64Args, &mut CpuState, &mut GuestMemory) -> Result<u64, ExitReason>
@@ -167,16 +261,7 @@ impl ImportRegistry {
+ Sync
+ 'static,
{
let mod_key = module.to_ascii_lowercase();
let sym_key = symbol.to_string();
let index = self.handlers.len();
self.handlers.push(ServiceDescriptor {
module: mod_key.clone(),
symbol: sym_key.clone(),
handler: Box::new(handler),
status: ServiceStatus::Implemented,
});
self.services.insert((mod_key, sym_key), index);
self.register_with_status(module, symbol, ServiceStatus::Implemented, handler);
}
/// Describe the canonical binding behind an import without calling it.
@@ -200,7 +285,10 @@ impl ImportRegistry {
pub fn iter_aliases(&self) -> impl Iterator<Item = (&str, &str, &str)> {
// `services` maps (module_lc, symbol) -> handler_index.
// An alias exists when module_lc != handlers[index].module.to_lowercase().
self.services.iter().filter_map(|((mod_lc, sym), &idx)| {
self.services.iter().filter_map(|((mod_lc, name), &idx)| {
let ImportName::Name(sym) = name else {
return None;
};
let canonical_mod = self.handlers[idx].module.to_ascii_lowercase();
if *mod_lc != canonical_mod {
Some((
@@ -221,7 +309,11 @@ impl ImportRegistry {
self.handlers[index].status = status;
}
/// Register a service with an explicit implementation status.
/// Register a named service with an explicit implementation status.
///
/// # Panics
///
/// As [`Self::register`].
pub fn register_with_status<F>(
&mut self,
module: &str,
@@ -234,17 +326,40 @@ impl ImportRegistry {
+ Sync
+ 'static,
{
self.register(module, symbol, handler);
self.set_status(module, symbol, status);
let name = ImportName::Name(symbol.to_owned());
if let Err(error) = self.try_register(module, name, status, Box::new(handler)) {
panic!("{error}");
}
}
/// Point an API-set import at an existing handler and its trampoline.
pub(crate) fn alias(&mut self, module: &str, target: &str, symbol: &str) {
/// Make `module` resolve `symbol` to the service registered as
/// `target!symbol`, sharing its trampoline.
pub fn try_alias(
&mut self,
module: &str,
target: &str,
symbol: &str,
) -> Result<(), RegistryError> {
let name = ImportName::Name(symbol.to_owned());
Self::check_key(module, &name)?;
let index = self
.service_index(target, symbol)
.expect("registered alias target");
self.services
.insert((module.to_ascii_lowercase(), symbol.to_owned()), index);
.index(target, &name)
.ok_or_else(|| RegistryError::UnknownTarget {
module: target.to_owned(),
symbol: symbol.to_owned(),
})?;
let previous = *self
.services
.entry((module.to_ascii_lowercase(), name))
.or_insert(index);
if previous == index {
Ok(())
} else {
Err(RegistryError::Duplicate {
module: module.to_owned(),
symbol: symbol.to_owned(),
})
}
}
/// Bind the PE's Import Address Table (IAT) in guest memory to synthetic trampoline VAs.
@@ -255,103 +370,37 @@ impl ImportRegistry {
loaded_base: u64,
memory: &mut GuestMemory,
) -> Result<usize, ImportError> {
let import_dir = find_import_directory(bytes)?;
let Some((import_rva, import_size)) = import_dir else {
let Some(directory) = find_import_directory(bytes) else {
return Ok(0);
};
if import_size == 0 {
return Ok(0);
let (entries, error) = parse_imports(bytes, directory, |rva| pe.rva_to_file_offset(rva));
if let Some(error) = error {
return Err(ImportError::Table(error));
}
let mut desc_file_off = pe
.rva_to_file_offset(import_rva)
.ok_or(ImportError::DirectoryOutOfBounds { rva: import_rva })?;
let mut bound_count = 0;
while desc_file_off + 20 <= bytes.len() {
let oft =
u32::from_le_bytes(bytes[desc_file_off..desc_file_off + 4].try_into().unwrap());
let name_rva = u32::from_le_bytes(
bytes[desc_file_off + 12..desc_file_off + 16]
.try_into()
.unwrap(),
);
let ft = u32::from_le_bytes(
bytes[desc_file_off + 16..desc_file_off + 20]
.try_into()
.unwrap(),
);
if oft == 0 && name_rva == 0 && ft == 0 {
break;
}
desc_file_off += 20;
let mod_name = if let Some(no) = pe.rva_to_file_offset(name_rva) {
let mut end = no;
while end < bytes.len() && bytes[end] != 0 {
end += 1;
}
String::from_utf8_lossy(&bytes[no..end]).into_owned()
} else {
"UNKNOWN.dll".to_string()
// Resolve everything first: a refused image must leave memory unbound.
let mut slots = Vec::with_capacity(entries.len());
for entry in entries {
let Some(index) = self.index(&entry.module, &entry.name) else {
return Err(ImportError::UnresolvedImport {
module: entry.module,
symbol: entry.name.to_string(),
});
};
let thunk_rva = if oft != 0 { oft } else { ft };
let iat_base_rva = ft;
let Some(mut thunk_off) = pe.rva_to_file_offset(thunk_rva) else {
continue;
};
let mut idx = 0u32;
while thunk_off + 8 <= bytes.len() {
let val = u64::from_le_bytes(bytes[thunk_off..thunk_off + 8].try_into().unwrap());
if val == 0 {
break;
}
thunk_off += 8;
let iat_rva = iat_base_rva + idx * 8;
idx += 1;
let sym_name = if (val & (1 << 63)) != 0 {
format!("Ordinal#{}", val & 0xFFFF)
} else {
let hint_rva = (val & 0x7FFF_FFFF) as u32;
if let Some(ho) = pe.rva_to_file_offset(hint_rva) {
let str_start = ho + 2;
let mut str_end = str_start;
while str_end < bytes.len() && bytes[str_end] != 0 {
str_end += 1;
}
String::from_utf8_lossy(&bytes[str_start..str_end]).into_owned()
} else {
"UNKNOWN_SYM".to_string()
}
};
let Some(service_idx) = self.service_index(&mod_name, &sym_name) else {
return Err(ImportError::UnresolvedImport {
module: mod_name,
symbol: sym_name,
});
};
// Assign a deterministic synthetic trampoline VA
let trampoline_va =
IMPORT_TRAMPOLINE_BASE_VA + (service_idx as u64) * IMPORT_TRAMPOLINE_STRIDE;
self.trampoline_to_service
.insert(trampoline_va, service_idx);
// Write trampoline_va into guest IAT entry at (loaded_base + iat_rva)
let iat_va = loaded_base + iat_rva as u64;
memory.write_u64_bypass(iat_va, trampoline_va)?;
bound_count += 1;
}
let address = loaded_base
.checked_add(u64::from(entry.iat_rva))
.ok_or(MemoryError::Overflow)?;
// The loader writes slots regardless of page permissions, so only
// mapping is checked here.
memory.read_u64_bypass(address)?;
slots.push((address, index));
}
Ok(bound_count)
for &(address, index) in &slots {
let trampoline = IMPORT_TRAMPOLINE_BASE_VA + (index as u64) * IMPORT_TRAMPOLINE_STRIDE;
memory.write_u64_bypass(address, trampoline)?;
self.trampoline_to_service.insert(trampoline, index);
}
Ok(slots.len())
}
/// Check if target RIP matches a synthetic service trampoline.
@@ -373,60 +422,58 @@ impl ImportRegistry {
let descriptor = &self.handlers[service_idx];
// 1. Extract arguments according to Win64 convention
let args = Win64Args::new(cpu);
// 2. Execute service handler
let ret_val = (descriptor.handler)(&args, cpu, memory)?;
// 3. Store return value into RAX
cpu.set(Register::Rax, ret_val);
// 4. Emulate RET instruction: pop return address from guest stack into RIP
// Read the return address first, so a call that cannot return has no effect.
let rsp = cpu.get(Register::Rsp);
let ret_addr = memory.read_u64(rsp).map_err(ExitReason::MemoryFault)?;
cpu.set(Register::Rsp, rsp + 8);
cpu.rip = ret_addr;
let after = rsp
.checked_add(8)
.ok_or(ExitReason::MemoryFault(MemoryError::Overflow))?;
let args = Win64Args::new(cpu);
let preserved = Nonvolatile::of(cpu);
let value = (descriptor.handler)(&args, cpu, memory)?;
if Nonvolatile::of(cpu) != preserved {
return Err(ExitReason::ServiceAbiViolation);
}
cpu.set(Register::Rax, value);
cpu.set(Register::Rsp, after);
cpu.rip = ret_addr;
Ok(())
}
}
fn find_import_directory(bytes: &[u8]) -> Result<Option<(u32, u32)>, ImportError> {
if bytes.len() < 0x40 {
return Ok(None);
}
let e_lfanew = u32::from_le_bytes(bytes[0x3C..0x40].try_into().unwrap()) as usize;
let opt_offset = e_lfanew + 24;
let coff_offset = e_lfanew + 4;
if bytes.len() < coff_offset + 18 {
return Ok(None);
}
let size_of_opt = u16::from_le_bytes(
bytes[coff_offset + 16..coff_offset + 18]
.try_into()
.unwrap(),
) as usize;
/// Registers a Win64 callee must preserve (Microsoft x64 calling convention).
#[derive(PartialEq, Eq)]
struct Nonvolatile {
gpr: [u64; 9],
xmm: [u128; 10],
}
// Import directory is directory index 1 (offset 112 + 1 * 8 = 120 in Optional Header)
if size_of_opt < 128 || bytes.len() < opt_offset + 128 {
return Ok(None);
}
let import_rva = u32::from_le_bytes(
bytes[opt_offset + 120..opt_offset + 124]
.try_into()
.unwrap(),
);
let import_size = u32::from_le_bytes(
bytes[opt_offset + 124..opt_offset + 128]
.try_into()
.unwrap(),
);
if import_rva == 0 || import_size == 0 {
Ok(None)
} else {
Ok(Some((import_rva, import_size)))
impl Nonvolatile {
fn of(cpu: &CpuState) -> Self {
use Register::{R12, R13, R14, R15, Rbp, Rbx, Rdi, Rsi, Rsp};
let mut xmm = [0; 10];
xmm.copy_from_slice(&cpu.xmm[6..]);
Self {
gpr: [Rbx, Rbp, Rdi, Rsi, Rsp, R12, R13, R14, R15].map(|register| cpu.get(register)),
xmm,
}
}
}
/// RVA of the import directory, if the image has one.
pub(crate) fn find_import_directory(bytes: &[u8]) -> Option<u32> {
let field = |offset: usize, len: usize| bytes.get(offset..offset.checked_add(len)?);
let u32_at = |offset| Some(u32::from_le_bytes(field(offset, 4)?.try_into().ok()?));
let coff = (u32_at(0x3C)? as usize).checked_add(4)?;
let optional = coff.checked_add(20)?;
let optional_len = u16::from_le_bytes(field(coff + 16, 2)?.try_into().ok()?);
// The import directory is data directory 1, at offset 120.
if optional_len < 128 {
return None;
}
let rva = u32_at(optional.checked_add(120)?)?;
let size = u32_at(optional.checked_add(124)?)?;
(rva != 0 && size != 0).then_some(rva)
}
+11
View File
@@ -9,16 +9,27 @@ pub mod arm64;
pub mod cpu;
pub mod dbt;
pub mod graphics;
pub mod import_table;
pub mod imports;
pub mod jit;
pub mod memory;
pub mod pe;
pub mod probe;
pub mod reloc;
pub mod runtime;
#[rustfmt::skip]
pub mod runtime_table;
pub mod services;
pub mod softfloat;
pub mod startup;
pub mod tls;
pub mod triage;
pub mod x86_decode;
pub mod x86_exec;
pub mod x86_float;
pub mod x86_simd;
#[rustfmt::skip]
pub mod x86_table;
pub use arm64::Arm64Assembler;
pub use cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, RFlags, Register};
+182 -141
View File
@@ -10,10 +10,14 @@
//! padding bytes (e.g. INT3 after an unconditional JMP) are never classified as
//! startup blockers.
use crate::dbt::{is_native, is_translatable};
use crate::import_table::{ImportTableError, parse_imports};
use crate::imports::{ImportRegistry, ServiceStatus};
use crate::memory::MemoryPermissions;
use crate::pe::{IMAGE_FILE_MACHINE_AMD64, PE32_PLUS_MAGIC, ParsedPe, PeError, PeSection};
use crate::services::{MockClock, ServicesState, register_standard_services};
use crate::x86_decode::{Encoding, MAX_INSTRUCTION_LEN, decode};
use crate::x86_table::Op;
use std::cmp::Reverse;
use std::collections::{BTreeMap, BTreeSet, BinaryHeap};
use std::fmt::Write as _;
@@ -67,6 +71,26 @@ struct CfgDecoded {
fall_through: bool,
}
/// Consume a ModRM byte with its SIB byte and displacement, returning the
/// ModRM byte and the offset just past the operand, or `None` if truncated.
fn modrm_operand(slice: &[u8], pc: usize) -> Option<(u8, usize)> {
let modrm = *slice.get(pc)?;
let mode = modrm >> 6;
let mut end = pc + 1;
let mut base = modrm & 7;
if mode != 3 && base == 4 {
base = slice.get(end)? & 7;
end += 1;
}
end += match mode {
1 => 1,
2 => 4,
0 if base == 5 => 4,
_ => 0,
};
(end <= slice.len()).then_some((modrm, end))
}
/// Decode a single x86-64 instruction from a file-mapped byte slice.
///
/// `slice` — file bytes beginning at the instruction's raw file offset.
@@ -83,16 +107,40 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
let mut b0 = slice[pc];
pc += 1;
// Legacy segment prefixes: 0x65 (GS), 0x64 (FS)
while (b0 == 0x65 || b0 == 0x64) && pc < slice.len() {
// Legacy segment prefixes: 0x65 (GS), 0x64 (FS). The run is bounded by the
// architectural instruction-length limit (15 bytes); a longer run is
// reported as an overlong prefix sequence instead of decoding past it.
while (b0 == 0x65 || b0 == 0x64) && pc < slice.len() && pc < MAX_INSTRUCTION_LEN {
b0 = slice[pc];
pc += 1;
}
let overlong_prefix_run =
pc < slice.len() && (b0 == 0x65 || b0 == 0x64) && pc >= MAX_INSTRUCTION_LEN;
if overlong_prefix_run {
return Some(CfgDecoded {
rva,
insn_len: pc,
mnemonic: "overlong prefix run".into(),
is_dbt: false,
is_interp: false,
notes: "instruction length exceeds the 15-byte architectural limit".into(),
successors: vec![],
fall_through: false,
});
}
// Recognize the operand-size override for C7 without changing how the
// probe classifies prefixes on unrelated opcodes.
let operand_override =
b0 == 0x66 && matches!(slice.get(pc..), Some([0xc7, ..] | [0x40..=0x4f, 0xc7, ..]));
// Recognize the operand-size override for C7 and the extension family
// without changing how the probe classifies prefixes on unrelated opcodes.
let operand_override = b0 == 0x66
&& matches!(
slice.get(pc..),
Some(
[0xc7, ..]
| [0x40..=0x4f, 0xc7, ..]
| [0x0f, 0xb6 | 0xb7 | 0xbe | 0xbf, ..]
| [0x40..=0x4f, 0x0f, 0xb6 | 0xb7 | 0xbe | 0xbf, ..]
)
);
if operand_override {
b0 = slice[pc];
pc += 1;
@@ -119,8 +167,6 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
pc += 1;
}
let mut is_dbt = false;
let mut is_interp = false;
let mut mnemonic = String::new();
let mut notes = String::new();
let mut successors: Vec<u32> = Vec::new();
@@ -129,14 +175,10 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
match op {
0xF4 => {
mnemonic = "hlt".to_string();
is_dbt = true;
is_interp = true;
fall_through = false; // HLT terminates
}
0x90 => {
mnemonic = "nop".to_string();
is_dbt = true;
is_interp = true;
}
0xCC => {
mnemonic = "int3".to_string();
@@ -146,15 +188,11 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
}
0xC3 => {
mnemonic = "ret".to_string();
is_dbt = true;
is_interp = true;
fall_through = false;
}
0xC7 => {
if let Some(&modrm) = slice.get(pc) {
pc += 1;
let mode = modrm >> 6;
let rm = modrm & 7;
if modrm & 0x38 != 0 {
mnemonic = format!("unsupported c7 extension (modrm 0x{modrm:02x})");
notes = "unknown instruction boundary".into();
@@ -174,14 +212,6 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
)
};
mnemonic = format!("mov r/m{width}, {value} (modrm 0x{modrm:02x})");
// The native C7 memory path always writes eight bytes and
// does not apply segment bases or decode a SIB byte.
is_dbt = mode == 3
|| (mode == 0 && rm != 4 && rex_w && !matches!(slice[0], 0x64 | 0x65));
is_dbt &= !operand_override;
if !is_dbt {
notes = "MOV immediate operand form lacks native semantics".into();
}
} else {
pc = slice.len();
fall_through = false;
@@ -201,22 +231,16 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
pc += 2;
}
mnemonic = "retn imm16".to_string();
is_dbt = false;
is_interp = false;
notes = "near return with stack pop".to_string();
fall_through = false;
}
0x50..=0x57 => {
let r = op - 0x50;
mnemonic = format!("push r{r}");
is_dbt = true;
is_interp = true;
}
0x58..=0x5F => {
let r = op - 0x58;
mnemonic = format!("pop r{r}");
is_dbt = true;
is_interp = true;
}
0x01 | 0x03 => {
if pc < slice.len() {
@@ -224,10 +248,7 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
pc += 1;
pc += modrm_extra_len(modrm, slice, pc);
mnemonic = format!("add (modrm 0x{modrm:02x})");
if (modrm >> 6) == 3 {
is_dbt = true;
is_interp = true;
}
if (modrm >> 6) == 3 {}
}
}
0x29 | 0x2B => {
@@ -236,10 +257,7 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
pc += 1;
pc += modrm_extra_len(modrm, slice, pc);
mnemonic = format!("sub (modrm 0x{modrm:02x})");
if (modrm >> 6) == 3 {
is_dbt = true;
is_interp = true;
}
if (modrm >> 6) == 3 {}
}
}
0x31 | 0x33 => {
@@ -248,10 +266,19 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
pc += 1;
pc += modrm_extra_len(modrm, slice, pc);
mnemonic = format!("xor (modrm 0x{modrm:02x})");
if (modrm >> 6) == 3 {
is_dbt = true;
is_interp = true;
}
if (modrm >> 6) == 3 {}
}
}
// MOVSXD r, r/m32
0x63 => {
if let Some((modrm, end)) = modrm_operand(slice, pc) {
pc = end;
let width = if rex_w { 64 } else { 32 };
mnemonic = format!("movsxd r{width}, r/m32 (modrm 0x{modrm:02x})");
} else {
pc = slice.len();
mnemonic = "truncated movsxd".into();
fall_through = false;
}
}
0x83 => {
@@ -261,10 +288,7 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
pc += 2;
let sub_op = (modrm >> 3) & 7;
mnemonic = format!("imm8_group modrm=0x{modrm:02x} imm=0x{imm:02x}");
if (modrm >> 6) == 3 && (sub_op == 0 || sub_op == 5 || sub_op == 7) {
is_dbt = true;
is_interp = true;
}
if (modrm >> 6) == 3 && (sub_op == 0 || sub_op == 5 || sub_op == 7) {}
}
}
0x85 => {
@@ -274,7 +298,6 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
pc += 1;
pc += modrm_extra_len(modrm, slice, pc);
mnemonic = format!("test (modrm 0x{modrm:02x})");
is_interp = true;
}
}
0x89 | 0x8B => {
@@ -285,8 +308,6 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
let rm = modrm & 7;
mnemonic = format!("mov (modrm 0x{modrm:02x})");
if mode == 3 {
is_dbt = true;
is_interp = true;
} else if rm == 4 {
// SIB
if pc < slice.len() {
@@ -300,8 +321,6 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
pc += 4; // disp32
}
mnemonic = format!("mov [SIB=0x{sib:02x}]");
is_dbt = true;
is_interp = true;
}
} else {
if mode == 1 && pc < slice.len() {
@@ -309,8 +328,6 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
} else if (mode == 2 || (mode == 0 && rm == 5)) && pc + 4 <= slice.len() {
pc += 4;
}
is_dbt = true;
is_interp = true;
}
}
}
@@ -319,8 +336,6 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
if pc + imm_len <= slice.len() {
pc += imm_len;
mnemonic = format!("mov reg, imm{imm_len}");
is_dbt = true;
is_interp = true;
}
}
// CALL rel32 — both call target and fall-through continuation are successors
@@ -331,8 +346,6 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
let insn_len = pc as i64;
let target_va = (va as i64 + insn_len + rel32 as i64) as u64;
mnemonic = format!("call rel32 -> 0x{target_va:016x}");
is_dbt = true;
is_interp = true;
// Push call target as a CFG successor; fall-through (return site) continues.
let call_rva = rva.wrapping_add(pc as u32).wrapping_add(rel32 as u32);
successors.push(call_rva);
@@ -347,8 +360,6 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
let insn_len = pc as i64;
let target_va = (va as i64 + insn_len + rel32 as i64) as u64;
mnemonic = format!("jmp rel32 -> 0x{target_va:016x}");
is_dbt = true;
is_interp = true;
let jmp_rva = rva.wrapping_add(pc as u32).wrapping_add(rel32 as u32);
successors.push(jmp_rva);
fall_through = false;
@@ -362,8 +373,6 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
let insn_len = pc as i64;
let target_va = (va as i64 + insn_len + rel8 as i64) as u64;
mnemonic = format!("jmp rel8 -> 0x{target_va:016x}");
is_dbt = true;
is_interp = true;
let jmp_rva = (rva as i64 + insn_len + rel8 as i64) as u32;
successors.push(jmp_rva);
fall_through = false;
@@ -377,8 +386,6 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
let insn_len = pc as i64;
let target_va = (va as i64 + insn_len + rel8 as i64) as u64;
mnemonic = format!("j{:x} rel8 -> 0x{target_va:016x}", op & 0xF);
is_dbt = true;
is_interp = true;
let jcc_rva = (rva as i64 + insn_len + rel8 as i64) as u32;
successors.push(jcc_rva);
// fall_through = true (not-taken path)
@@ -398,13 +405,32 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
let insn_len = pc as i64;
let target_va = (va as i64 + insn_len + rel32 as i64) as u64;
mnemonic = format!("j{:x} rel32 -> 0x{target_va:016x}", op2 & 0xF);
is_dbt = true;
is_interp = true;
let jcc_rva = (rva as i64 + insn_len + rel32 as i64) as u32;
successors.push(jcc_rva);
// fall_through = true
}
}
// MOVZX/MOVSX r, r/m8 or r/m16
0xB6 | 0xB7 | 0xBE | 0xBF => {
if let Some((modrm, end)) = modrm_operand(slice, pc) {
pc = end;
let name = if op2 < 0xB8 { "movzx" } else { "movsx" };
let source = if op2 & 1 == 0 { 8 } else { 16 };
let width = if rex_w {
64
} else if operand_override {
16
} else {
32
};
mnemonic =
format!("{name} r{width}, r/m{source} (modrm 0x{modrm:02x})");
} else {
pc = slice.len();
mnemonic = "truncated extension".into();
fall_through = false;
}
}
_ => {
mnemonic = format!("0f_{op2:02x}");
notes = "unsupported two-byte opcode".to_string();
@@ -428,8 +454,6 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
mnemonic = format!("call *[RIP + 0x{iat_target:016x}]");
notes = "indirect IAT symbol call - requires dynamic import linking"
.to_string();
is_dbt = true;
is_interp = true;
// fall_through = true (return will come back here)
} else {
mnemonic = format!("jmp *[RIP + 0x{iat_target:016x}]");
@@ -441,8 +465,6 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
if reg_field == 2 {
mnemonic = format!("call *r/m (modrm 0x{modrm:02x})");
notes = "indirect call - target unknown".to_string();
is_dbt = true;
is_interp = true;
} else {
mnemonic = format!("jmp *r/m (modrm 0x{modrm:02x})");
notes = "indirect jmp - target unknown statically".to_string();
@@ -453,8 +475,6 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
// PUSH r/m
pc += modrm_extra_len(modrm, slice, pc);
mnemonic = format!("push r/m (modrm 0x{modrm:02x})");
is_dbt = true;
is_interp = true;
} else {
pc += modrm_extra_len(modrm, slice, pc);
mnemonic = format!("ff_group_r{reg_field} (modrm 0x{modrm:02x})");
@@ -468,6 +488,51 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
}
}
// Architectural instruction-length enforcement: no decoded instruction
// may exceed 15 bytes, whatever prefix or opcode path produced it.
if pc > MAX_INSTRUCTION_LEN {
return Some(CfgDecoded {
rva,
insn_len: MAX_INSTRUCTION_LEN,
mnemonic: "overlong instruction".into(),
is_dbt: false,
is_interp: false,
notes: "instruction length exceeds the 15-byte architectural limit".into(),
successors: vec![],
fall_through: false,
});
}
// The decoder both engines execute with decides support, length and static
// control flow, so the report cannot claim a form they reject.
let (is_dbt, is_interp) = match decode(va, |address| {
slice
.get(address.wrapping_sub(va) as usize)
.copied()
.ok_or(())
}) {
Ok(insn) => {
pc = usize::from(insn.len);
if mnemonic.is_empty() || mnemonic.contains("opcode_0x") || mnemonic.starts_with("0f_")
{
mnemonic = insn.op.name().to_string();
notes.clear();
}
if !is_translatable(&insn) {
notes = "raw guest system calls are not dispatched by the DBT".into();
} else if !is_native(&insn) {
notes = "executed by the shared semantics, not translated to ARM64".into();
}
let relative = insn.encoding == Encoding::Rel;
if relative {
successors = vec![insn.imm.wrapping_sub(va).wrapping_add(u64::from(rva)) as u32];
}
fall_through = !matches!(insn.op, Op::Jmp | Op::Ret | Op::Hlt);
(is_translatable(&insn), true)
}
Err(_) => (false, false),
};
Some(CfgDecoded {
rva,
insn_len: pc,
@@ -607,7 +672,10 @@ pub struct ProbeReport {
pub parsed: ParsedPe,
pub relocations: RelocationCensus,
pub tls: TlsCensus,
/// Imports before the first malformed entry, if any.
pub imports: Vec<ImportedSymbol>,
/// Why the import table could not be read to its end.
pub import_error: Option<ImportTableError>,
pub instruction_records: Vec<InstructionRecord>,
pub first_unsupported_dbt_insn: Option<InstructionRecord>,
}
@@ -791,12 +859,21 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
});
}
// Map an RVA to a file offset.
//
// The offset is derived from the section header, so on a truncated file it
// can point past the end of the buffer. Such an offset is not readable, so
// it is reported as unmapped rather than returned and sliced later.
let rva_to_offset = |rva: u32| -> Option<usize> {
for sec in &sections {
let max_span = std::cmp::max(sec.virtual_size, sec.raw_data_size);
if rva >= sec.virtual_address && rva < sec.virtual_address.saturating_add(max_span) {
let off_in_sec = (rva - sec.virtual_address) as usize;
return Some(sec.raw_data_ptr as usize + off_in_sec);
let off = sec.raw_data_ptr as usize + off_in_sec;
if off >= bytes.len() {
return None;
}
return Some(off);
}
}
None
@@ -881,76 +958,33 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
&mut registry,
Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))),
);
let mut imports = Vec::new();
if import_dir_rva != 0
&& let Some(mut desc_off) = rva_to_offset(import_dir_rva)
{
while desc_off + 20 <= bytes.len() {
let oft = u32::from_le_bytes(bytes[desc_off..desc_off + 4].try_into().unwrap());
let name_rva =
u32::from_le_bytes(bytes[desc_off + 12..desc_off + 16].try_into().unwrap());
let ft = u32::from_le_bytes(bytes[desc_off + 16..desc_off + 20].try_into().unwrap());
if oft == 0 && name_rva == 0 && ft == 0 {
break;
let (entries, import_error) = if import_dir_rva == 0 {
(Vec::new(), None)
} else {
// Binding accepts only bytes backed by section data; match it exactly.
parse_imports(bytes, import_dir_rva, |rva| {
sections.iter().find_map(|section| {
let offset = rva.checked_sub(section.virtual_address)?;
(offset < section.raw_data_size)
.then(|| (section.raw_data_ptr as usize).checked_add(offset as usize))?
})
})
};
let imports: Vec<ImportedSymbol> = entries
.into_iter()
.map(|entry| {
let binding = registry.resolve(&entry.module, &entry.name);
ImportedSymbol {
category: ProbeReport::categorize_dll(&entry.module),
dll: entry.module,
symbol: entry.name.to_string(),
iat_rva: entry.iat_rva,
is_supported: binding.is_some(),
service_status: binding.map(|service| service.status),
canonical_module: binding.map(|service| service.module.clone()),
}
desc_off += 20;
let dll_name = if let Some(no) = rva_to_offset(name_rva) {
let mut end = no;
while end < bytes.len() && bytes[end] != 0 {
end += 1;
}
String::from_utf8_lossy(&bytes[no..end]).into_owned()
} else {
"UNKNOWN.dll".to_string()
};
let category = ProbeReport::categorize_dll(&dll_name);
let thunk_rva = if oft != 0 { oft } else { ft };
let iat_base_rva = ft;
if let Some(mut thunk_off) = rva_to_offset(thunk_rva) {
let mut idx = 0u32;
while thunk_off + 8 <= bytes.len() {
let val =
u64::from_le_bytes(bytes[thunk_off..thunk_off + 8].try_into().unwrap());
if val == 0 {
break;
}
thunk_off += 8;
let iat_rva = iat_base_rva + idx * 8;
idx += 1;
let sym_name = if (val & (1 << 63)) != 0 {
format!("Ordinal#{}", val & 0xFFFF)
} else {
let hint_rva = (val & 0x7FFF_FFFF) as u32;
if let Some(ho) = rva_to_offset(hint_rva) {
let str_start = ho + 2;
let mut str_end = str_start;
while str_end < bytes.len() && bytes[str_end] != 0 {
str_end += 1;
}
String::from_utf8_lossy(&bytes[str_start..str_end]).into_owned()
} else {
"UNKNOWN_SYM".to_string()
}
};
let binding = registry.binding(&dll_name, &sym_name);
imports.push(ImportedSymbol {
dll: dll_name.clone(),
symbol: sym_name,
iat_rva,
category,
is_supported: binding.is_some(),
service_status: binding.map(|service| service.status),
canonical_module: binding.map(|service| service.module.clone()),
});
}
}
}
}
})
.collect();
// 4. Control-Flow-Aware Static Disassembly
//
@@ -1085,6 +1119,7 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result<ProbeReport,
relocations,
tls,
imports,
import_error,
instruction_records,
first_unsupported_dbt_insn,
})
@@ -1337,6 +1372,12 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
"- **Unresolved standard import thunks**: `{missing}`. See `missing_imports.csv`. A registered handler may be a stub.\n"
);
if let Some(error) = &report.import_error {
let _ = writeln!(
md,
"- **Import table is malformed**: {error}. Only the imports before it are listed, and binding refuses the image.\n"
);
}
if trusted_runner_slots > 0 {
let _ = writeln!(
md,
+155
View File
@@ -0,0 +1,155 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Typed Win64 adapters for generated service registrations.
//!
//! `runtime_table.rs` is generated from `runtime/services.txt`. Each adapter
//! reads typed arguments by position (Microsoft x64 calling convention), calls a
//! handler that sees only guest memory and service state, and places the typed
//! result. Handlers never receive the CPU, so they cannot disturb nonvolatile
//! registers.
use crate::cpu::{CpuState, ExitReason};
use crate::imports::{ServiceStatus, Win64Args};
use crate::memory::{GuestMemory, MemoryError};
use crate::services::ServicesState;
/// What a service may use.
pub struct ServiceContext<'a> {
pub state: &'a ServicesState,
pub memory: &'a mut GuestMemory,
}
/// Guest pointer to `N` bytes the service writes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct OutPtr<const N: usize>(pub u64);
impl<const N: usize> OutPtr<N> {
/// Checked, all-or-nothing store.
pub fn store(self, memory: &mut GuestMemory, bytes: [u8; N]) -> Result<(), MemoryError> {
memory.write_bytes(self.0, &bytes)
}
}
/// Raw bits of a floating-point argument or result.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Float32(pub u32);
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Float64(pub u64);
/// Reads typed arguments. Only the low bits of a narrow argument are defined.
pub struct Call<'a> {
args: &'a Win64Args,
cpu: &'a CpuState,
memory: &'a GuestMemory,
}
impl<'a> Call<'a> {
pub fn new(args: &'a Win64Args, cpu: &'a CpuState, memory: &'a GuestMemory) -> Self {
Self { args, cpu, memory }
}
pub fn u64(&self, index: usize) -> Result<u64, ExitReason> {
self.args
.get(index, self.memory)
.map_err(ExitReason::MemoryFault)
}
pub fn u32(&self, index: usize) -> Result<u32, ExitReason> {
Ok(self.u64(index)? as u32)
}
pub fn i32(&self, index: usize) -> Result<i32, ExitReason> {
Ok(self.u32(index)? as i32)
}
pub fn bool32(&self, index: usize) -> Result<bool, ExitReason> {
Ok(self.u32(index)? != 0)
}
pub fn out<const N: usize>(&self, index: usize) -> Result<OutPtr<N>, ExitReason> {
self.u64(index).map(OutPtr)
}
/// The first four positions use XMM0-XMM3; later ones use the stack.
fn float_bits(&self, index: usize) -> Result<u64, ExitReason> {
if index < 4 {
Ok(self.cpu.xmm[index] as u64)
} else {
self.u64(index)
}
}
pub fn f32(&self, index: usize) -> Result<Float32, ExitReason> {
Ok(Float32(self.float_bits(index)? as u32))
}
pub fn f64(&self, index: usize) -> Result<Float64, ExitReason> {
self.float_bits(index).map(Float64)
}
}
/// Places a typed result and returns the value for RAX.
pub trait Return {
fn place(self, cpu: &mut CpuState) -> u64;
}
impl Return for u32 {
fn place(self, _: &mut CpuState) -> u64 {
u64::from(self)
}
}
impl Return for i32 {
fn place(self, _: &mut CpuState) -> u64 {
u64::from(self as u32)
}
}
impl Return for u64 {
fn place(self, _: &mut CpuState) -> u64 {
self
}
}
impl Return for bool {
fn place(self, _: &mut CpuState) -> u64 {
u64::from(self)
}
}
impl Return for Float32 {
fn place(self, cpu: &mut CpuState) -> u64 {
cpu.xmm[0] = u128::from(self.0);
0
}
}
impl Return for Float64 {
fn place(self, cpu: &mut CpuState) -> u64 {
cpu.xmm[0] = u128::from(self.0);
0
}
}
/// A declared parameter.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Parameter {
pub name: &'static str,
pub kind: &'static str,
}
/// Static description of a generated service.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ServiceMetadata {
pub library: &'static str,
pub symbol: &'static str,
pub parameters: &'static [Parameter],
pub result: &'static str,
pub status: ServiceStatus,
/// API sets that resolve to this service.
pub aliases: &'static [&'static str],
pub failure: &'static str,
pub reference: &'static str,
pub tests: &'static [&'static str],
}
+408
View File
@@ -0,0 +1,408 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Generated by xenora-runtime-gen from crates/loader/runtime/services.txt.
// Do not edit.
use crate::imports::{ImportRegistry, ServiceStatus};
use crate::runtime::{Call, Parameter, Return, ServiceContext, ServiceMetadata};
use crate::services::{ServicesState, handlers};
use std::sync::Arc;
pub static SERVICES: [ServiceMetadata; 20] = [
ServiceMetadata {
library: "kernel32.dll",
symbol: "SetProcessPriorityBoost",
parameters: &[Parameter { name: "process", kind: "handle" }, Parameter { name: "disable", kind: "bool32" }],
result: "bool32",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-core-processthreads-l1-1-2.dll"],
failure: "0 with ERROR_INVALID_HANDLE",
reference: "processthreadsapi.h SetProcessPriorityBoost",
tests: &["priority_boost_round_trips_and_checks_its_handle"],
},
ServiceMetadata {
library: "kernel32.dll",
symbol: "GetProcessPriorityBoost",
parameters: &[Parameter { name: "process", kind: "handle" }, Parameter { name: "disabled", kind: "out<4>" }],
result: "bool32",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-core-processthreads-l1-1-2.dll"],
failure: "0 with ERROR_INVALID_HANDLE or ERROR_NOACCESS",
reference: "processthreadsapi.h GetProcessPriorityBoost",
tests: &["priority_boost_round_trips_and_checks_its_handle"],
},
ServiceMetadata {
library: "kernel32.dll",
symbol: "GetCurrentProcess",
parameters: &[],
result: "handle",
status: ServiceStatus::Implemented,
aliases: &["api-ms-win-core-processthreads-l1-1-0.dll"],
failure: "never",
reference: "processthreadsapi.h GetCurrentProcess",
tests: &["identity_services_return_documented_pseudo_handles_and_ids"],
},
ServiceMetadata {
library: "kernel32.dll",
symbol: "GetProcessId",
parameters: &[Parameter { name: "process", kind: "handle" }],
result: "u32",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-core-processthreads-l1-1-0.dll"],
failure: "0 with ERROR_INVALID_HANDLE",
reference: "processthreadsapi.h GetProcessId",
tests: &["identity_services_return_documented_pseudo_handles_and_ids"],
},
ServiceMetadata {
library: "kernel32.dll",
symbol: "GetCurrentThread",
parameters: &[],
result: "handle",
status: ServiceStatus::Implemented,
aliases: &["api-ms-win-core-processthreads-l1-1-0.dll"],
failure: "never",
reference: "processthreadsapi.h GetCurrentThread",
tests: &["identity_services_return_documented_pseudo_handles_and_ids"],
},
ServiceMetadata {
library: "kernel32.dll",
symbol: "GetCurrentProcessId",
parameters: &[],
result: "u32",
status: ServiceStatus::Implemented,
aliases: &["api-ms-win-core-processthreads-l1-1-0.dll"],
failure: "never",
reference: "processthreadsapi.h GetCurrentProcessId",
tests: &["identity_services_return_documented_pseudo_handles_and_ids"],
},
ServiceMetadata {
library: "kernel32.dll",
symbol: "GetCurrentThreadId",
parameters: &[],
result: "u32",
status: ServiceStatus::Implemented,
aliases: &["api-ms-win-core-processthreads-l1-1-0.dll"],
failure: "never",
reference: "processthreadsapi.h GetCurrentThreadId",
tests: &["identity_services_return_documented_pseudo_handles_and_ids"],
},
ServiceMetadata {
library: "kernel32.dll",
symbol: "OpenThread",
parameters: &[Parameter { name: "access", kind: "u32" }, Parameter { name: "inherit", kind: "bool32" }, Parameter { name: "thread", kind: "u32" }],
result: "handle",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-core-processthreads-l1-1-0.dll"],
failure: "0 with ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED or ERROR_NOT_ENOUGH_MEMORY",
reference: "processthreadsapi.h OpenThread",
tests: &["thread_handles_check_access_and_are_rejected_once_closed"],
},
ServiceMetadata {
library: "kernel32.dll",
symbol: "GetThreadPriority",
parameters: &[Parameter { name: "thread", kind: "handle" }],
result: "i32",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-core-processthreads-l1-1-0.dll"],
failure: "THREAD_PRIORITY_ERROR_RETURN with ERROR_INVALID_HANDLE or ERROR_ACCESS_DENIED",
reference: "processthreadsapi.h GetThreadPriority",
tests: &["thread_handles_check_access_and_are_rejected_once_closed"],
},
ServiceMetadata {
library: "kernel32.dll",
symbol: "SetThreadPriority",
parameters: &[Parameter { name: "thread", kind: "handle" }, Parameter { name: "priority", kind: "i32" }],
result: "bool32",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-core-processthreads-l1-1-0.dll"],
failure: "0 with ERROR_INVALID_HANDLE, ERROR_ACCESS_DENIED, ERROR_NOT_SUPPORTED or ERROR_INVALID_PARAMETER",
reference: "processthreadsapi.h SetThreadPriority",
tests: &["thread_handles_check_access_and_are_rejected_once_closed"],
},
ServiceMetadata {
library: "kernel32.dll",
symbol: "CloseHandle",
parameters: &[Parameter { name: "object", kind: "handle" }],
result: "bool32",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-core-handle-l1-1-0.dll"],
failure: "0 with ERROR_INVALID_HANDLE",
reference: "handleapi.h CloseHandle",
tests: &["thread_handles_check_access_and_are_rejected_once_closed"],
},
ServiceMetadata {
library: "kernel32.dll",
symbol: "GetSystemTimeAsFileTime",
parameters: &[Parameter { name: "time", kind: "out<8>" }],
result: "void",
status: ServiceStatus::Implemented,
aliases: &["api-ms-win-core-sysinfo-l1-1-0.dll"],
failure: "guest fault on an invalid pointer",
reference: "sysinfoapi.h GetSystemTimeAsFileTime",
tests: &["system_time_comes_from_the_injected_clock"],
},
ServiceMetadata {
library: "kernel32.dll",
symbol: "GetLastError",
parameters: &[],
result: "u32",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-core-errorhandling-l1-1-0.dll"],
failure: "never",
reference: "errhandlingapi.h GetLastError",
tests: &["last_error_is_set_by_failures_and_by_the_guest"],
},
ServiceMetadata {
library: "kernel32.dll",
symbol: "SetLastError",
parameters: &[Parameter { name: "code", kind: "u32" }],
result: "void",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-core-errorhandling-l1-1-0.dll"],
failure: "never",
reference: "errhandlingapi.h SetLastError",
tests: &["last_error_is_set_by_failures_and_by_the_guest"],
},
ServiceMetadata {
library: "kernel32.dll",
symbol: "VirtualAlloc",
parameters: &[Parameter { name: "address", kind: "ptr" }, Parameter { name: "size", kind: "u64" }, Parameter { name: "kind", kind: "u32" }, Parameter { name: "protect", kind: "u32" }],
result: "ptr",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-core-memory-l1-1-0.dll"],
failure: "0 with ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED, ERROR_INVALID_ADDRESS or ERROR_NOT_ENOUGH_MEMORY",
reference: "memoryapi.h VirtualAlloc",
tests: &["virtual_memory_is_mapped_released_and_bounded"],
},
ServiceMetadata {
library: "kernel32.dll",
symbol: "VirtualFree",
parameters: &[Parameter { name: "address", kind: "ptr" }, Parameter { name: "size", kind: "u64" }, Parameter { name: "kind", kind: "u32" }],
result: "bool32",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-core-memory-l1-1-0.dll"],
failure: "0 with ERROR_NOT_SUPPORTED, ERROR_INVALID_PARAMETER or ERROR_INVALID_ADDRESS",
reference: "memoryapi.h VirtualFree",
tests: &["virtual_memory_is_mapped_released_and_bounded"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "sqrt",
parameters: &[Parameter { name: "x", kind: "f64" }],
result: "f64",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-math-l1-1-0.dll"],
failure: "NaN for a negative argument; errno is not set",
reference: "math.h sqrt (ISO C, IEC 60559 squareRoot)",
tests: &["floating_arguments_and_results_use_xmm_registers"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "sqrtf",
parameters: &[Parameter { name: "x", kind: "f32" }],
result: "f32",
status: ServiceStatus::Partial,
aliases: &["api-ms-win-crt-math-l1-1-0.dll"],
failure: "NaN for a negative argument; errno is not set",
reference: "math.h sqrtf (ISO C, IEC 60559 squareRoot)",
tests: &["floating_arguments_and_results_use_xmm_registers"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "fabs",
parameters: &[Parameter { name: "x", kind: "f64" }],
result: "f64",
status: ServiceStatus::Implemented,
aliases: &["api-ms-win-crt-math-l1-1-0.dll"],
failure: "never",
reference: "math.h fabs (ISO C, IEC 60559 abs)",
tests: &["floating_arguments_and_results_use_xmm_registers"],
},
ServiceMetadata {
library: "ucrtbase.dll",
symbol: "fabsf",
parameters: &[Parameter { name: "x", kind: "f32" }],
result: "f32",
status: ServiceStatus::Implemented,
aliases: &["api-ms-win-crt-math-l1-1-0.dll"],
failure: "never",
reference: "math.h fabsf (ISO C, IEC 60559 abs)",
tests: &["floating_arguments_and_results_use_xmm_registers"],
},
];
/// Register every generated service and its API-set aliases.
pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
let s = state.clone();
registry.register_with_status("kernel32.dll", "SetProcessPriorityBoost", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.u64(0)?;
let a1 = call.bool32(1)?;
let mut context = ServiceContext { state: &s, memory };
let result: bool = handlers::set_process_priority_boost(&mut context, a0, a1)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("kernel32.dll", "GetProcessPriorityBoost", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.u64(0)?;
let a1 = call.out::<4>(1)?;
let mut context = ServiceContext { state: &s, memory };
let result: bool = handlers::get_process_priority_boost(&mut context, a0, a1)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("kernel32.dll", "GetCurrentProcess", ServiceStatus::Implemented, move |args, cpu, memory| {
let _ = args;
let mut context = ServiceContext { state: &s, memory };
let result: u64 = handlers::get_current_process(&mut context)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("kernel32.dll", "GetProcessId", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.u64(0)?;
let mut context = ServiceContext { state: &s, memory };
let result: u32 = handlers::get_process_id(&mut context, a0)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("kernel32.dll", "GetCurrentThread", ServiceStatus::Implemented, move |args, cpu, memory| {
let _ = args;
let mut context = ServiceContext { state: &s, memory };
let result: u64 = handlers::get_current_thread(&mut context)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("kernel32.dll", "GetCurrentProcessId", ServiceStatus::Implemented, move |args, cpu, memory| {
let _ = args;
let mut context = ServiceContext { state: &s, memory };
let result: u32 = handlers::get_current_process_id(&mut context)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("kernel32.dll", "GetCurrentThreadId", ServiceStatus::Implemented, move |args, cpu, memory| {
let _ = args;
let mut context = ServiceContext { state: &s, memory };
let result: u32 = handlers::get_current_thread_id(&mut context)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("kernel32.dll", "OpenThread", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.u32(0)?;
let a1 = call.bool32(1)?;
let a2 = call.u32(2)?;
let mut context = ServiceContext { state: &s, memory };
let result: u64 = handlers::open_thread(&mut context, a0, a1, a2)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("kernel32.dll", "GetThreadPriority", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.u64(0)?;
let mut context = ServiceContext { state: &s, memory };
let result: i32 = handlers::get_thread_priority(&mut context, a0)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("kernel32.dll", "SetThreadPriority", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.u64(0)?;
let a1 = call.i32(1)?;
let mut context = ServiceContext { state: &s, memory };
let result: bool = handlers::set_thread_priority(&mut context, a0, a1)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("kernel32.dll", "CloseHandle", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.u64(0)?;
let mut context = ServiceContext { state: &s, memory };
let result: bool = handlers::close_handle(&mut context, a0)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("kernel32.dll", "GetSystemTimeAsFileTime", ServiceStatus::Implemented, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.out::<8>(0)?;
let mut context = ServiceContext { state: &s, memory };
let () = handlers::get_system_time_as_file_time(&mut context, a0)?;
Ok(0)
});
let s = state.clone();
registry.register_with_status("kernel32.dll", "GetLastError", ServiceStatus::Partial, move |args, cpu, memory| {
let _ = args;
let mut context = ServiceContext { state: &s, memory };
let result: u32 = handlers::get_last_error(&mut context)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("kernel32.dll", "SetLastError", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.u32(0)?;
let mut context = ServiceContext { state: &s, memory };
let () = handlers::set_last_error(&mut context, a0)?;
Ok(0)
});
let s = state.clone();
registry.register_with_status("kernel32.dll", "VirtualAlloc", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.u64(0)?;
let a1 = call.u64(1)?;
let a2 = call.u32(2)?;
let a3 = call.u32(3)?;
let mut context = ServiceContext { state: &s, memory };
let result: u64 = handlers::virtual_alloc(&mut context, a0, a1, a2, a3)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("kernel32.dll", "VirtualFree", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.u64(0)?;
let a1 = call.u64(1)?;
let a2 = call.u32(2)?;
let mut context = ServiceContext { state: &s, memory };
let result: bool = handlers::virtual_free(&mut context, a0, a1, a2)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "sqrt", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.f64(0)?;
let mut context = ServiceContext { state: &s, memory };
let result: crate::runtime::Float64 = handlers::sqrt(&mut context, a0)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "sqrtf", ServiceStatus::Partial, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.f32(0)?;
let mut context = ServiceContext { state: &s, memory };
let result: crate::runtime::Float32 = handlers::sqrtf(&mut context, a0)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "fabs", ServiceStatus::Implemented, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.f64(0)?;
let mut context = ServiceContext { state: &s, memory };
let result: crate::runtime::Float64 = handlers::fabs(&mut context, a0)?;
Ok(result.place(cpu))
});
let s = state.clone();
registry.register_with_status("ucrtbase.dll", "fabsf", ServiceStatus::Implemented, move |args, cpu, memory| {
let call = Call::new(args, cpu, memory);
let a0 = call.f32(0)?;
let mut context = ServiceContext { state: &s, memory };
let result: crate::runtime::Float32 = handlers::fabsf(&mut context, a0)?;
Ok(result.place(cpu))
});
for service in &SERVICES {
for alias in service.aliases {
if let Err(error) = registry.try_alias(alias, service.library, service.symbol) {
panic!("{error}");
}
}
}
}
+247 -262
View File
@@ -33,9 +33,6 @@ const PAGE_SIZE: u64 = 4096;
const MEM_COMMIT_RESERVE: u32 = 0x3000;
const MEM_RELEASE: u32 = 0x8000;
const ERROR_NOACCESS: u32 = 998;
const KERNEL32: &str = "kernel32.dll";
const PROCESS_THREADS_V1: &str = "api-ms-win-core-processthreads-l1-1-0.dll";
const PROCESS_THREADS_V2: &str = "api-ms-win-core-processthreads-l1-1-2.dll";
/// Clock trait for injecting deterministic time in tests or host time in production.
pub trait Clock: Send + Sync {
@@ -136,9 +133,10 @@ impl ServicesState {
self.priority_boost_disabled.load(Ordering::SeqCst)
}
fn fail(&self, error: u32, return_value: u64) -> Result<u64, ExitReason> {
/// Record a guest error and return the documented failure value.
fn fail<T>(&self, error: u32, value: T) -> Result<T, ExitReason> {
self.last_error.store(error, Ordering::SeqCst);
Ok(return_value)
Ok(value)
}
fn is_current_process(&self, handle: u64) -> bool {
@@ -151,264 +149,10 @@ impl ServicesState {
}
}
/// Register standard Windows core and Xbox memory services into the registry.
/// Register the services generated from `runtime/services.txt` and the
/// hand-written fixture services.
pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc<ServicesState>) {
let s = state.clone();
registry.register(KERNEL32, "SetProcessPriorityBoost", move |args, _, mem| {
if !s.is_current_process(args.get(0, mem).map_err(ExitReason::MemoryFault)?) {
return Ok(0);
}
let disable = args.get(1, mem).map_err(ExitReason::MemoryFault)? as u32;
s.priority_boost_disabled
.store(disable != 0, Ordering::SeqCst);
Ok(1)
});
registry.alias(PROCESS_THREADS_V2, KERNEL32, "SetProcessPriorityBoost");
registry.set_status(KERNEL32, "SetProcessPriorityBoost", ServiceStatus::Partial);
let s = state.clone();
registry.register(KERNEL32, "GetProcessPriorityBoost", move |args, _, mem| {
if !s.is_current_process(args.get(0, mem).map_err(ExitReason::MemoryFault)?) {
return Ok(0);
}
let output = args.get(1, mem).map_err(ExitReason::MemoryFault)?;
if mem
.write_u32(output, u32::from(s.priority_boost_disabled()))
.is_err()
{
s.last_error.store(ERROR_NOACCESS, Ordering::SeqCst);
return Ok(0);
}
Ok(1)
});
registry.alias(PROCESS_THREADS_V2, KERNEL32, "GetProcessPriorityBoost");
registry.set_status(KERNEL32, "GetProcessPriorityBoost", ServiceStatus::Partial);
registry.register(KERNEL32, "GetCurrentProcess", |_, _, _| Ok(CURRENT_PROCESS));
registry.alias(PROCESS_THREADS_V1, KERNEL32, "GetCurrentProcess");
let s = state.clone();
registry.register(KERNEL32, "GetProcessId", move |args, _, mem| {
if !s.is_current_process(args.get(0, mem).map_err(ExitReason::MemoryFault)?) {
return Ok(0);
}
Ok(u64::from(s.process_id))
});
registry.alias(PROCESS_THREADS_V1, KERNEL32, "GetProcessId");
registry.set_status(KERNEL32, "GetProcessId", ServiceStatus::Partial);
registry.register(KERNEL32, "GetCurrentThread", |_, _, _| Ok(CURRENT_THREAD));
registry.alias(PROCESS_THREADS_V1, KERNEL32, "GetCurrentThread");
let s = state.clone();
registry.register(KERNEL32, "OpenThread", move |args, _, mem| {
let access = args.get(0, mem).map_err(ExitReason::MemoryFault)? as u32;
let inherit = args.get(1, mem).map_err(ExitReason::MemoryFault)? as u32;
let id = args.get(2, mem).map_err(ExitReason::MemoryFault)? as u32;
if id != s.thread_id {
return s.fail(ERROR_INVALID_PARAMETER, 0);
}
if inherit != 0 || access & !THREAD_SUPPORTED_RIGHTS != 0 {
return s.fail(ERROR_NOT_SUPPORTED, 0);
}
let mut thread = s.thread.lock().expect("guest thread state");
let Some(handle) = thread
.last_handle
.checked_add(4)
.filter(|_| thread.handles.len() < MAX_THREAD_HANDLES)
else {
return s.fail(ERROR_NOT_ENOUGH_MEMORY, 0);
};
thread.handles.insert(handle, access);
thread.last_handle = handle;
Ok(handle)
});
let s = state.clone();
registry.register(KERNEL32, "GetThreadPriority", move |args, _, mem| {
let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
let thread = s.thread.lock().expect("guest thread state");
if let Err(error) = thread.check_access(handle, THREAD_QUERY_RIGHTS) {
return s.fail(error, THREAD_PRIORITY_ERROR_RETURN);
}
Ok(u64::from(thread.priority as u32))
});
let s = state.clone();
registry.register(KERNEL32, "SetThreadPriority", move |args, _, mem| {
let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
let priority = args.get(1, mem).map_err(ExitReason::MemoryFault)? as i32;
let mut thread = s.thread.lock().expect("guest thread state");
if let Err(error) = thread.check_access(handle, THREAD_SET_RIGHTS) {
return s.fail(error, 0);
}
if matches!(priority, 0x0001_0000 | 0x0002_0000) {
return s.fail(ERROR_NOT_SUPPORTED, 0);
}
if !matches!(priority, -15 | -2..=2 | 15) {
return s.fail(ERROR_INVALID_PARAMETER, 0);
}
thread.priority = priority;
Ok(1)
});
for symbol in ["OpenThread", "GetThreadPriority", "SetThreadPriority"] {
registry.alias(PROCESS_THREADS_V1, KERNEL32, symbol);
registry.set_status(KERNEL32, symbol, ServiceStatus::Partial);
}
let s = state.clone();
registry.register(KERNEL32, "CloseHandle", move |args, _, mem| {
let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
if matches!(handle, CURRENT_PROCESS | CURRENT_THREAD)
|| s.thread
.lock()
.expect("guest thread state")
.handles
.remove(&handle)
.is_some()
{
return Ok(1);
}
s.fail(ERROR_INVALID_HANDLE, 0)
});
registry.alias("api-ms-win-core-handle-l1-1-0.dll", KERNEL32, "CloseHandle");
registry.set_status(KERNEL32, "CloseHandle", ServiceStatus::Partial);
// 1. GetSystemTimeAsFileTime(lpSystemTimeAsFileTime: *mut FILETIME)
let s = state.clone();
let handler = move |args: &crate::imports::Win64Args,
_cpu: &mut crate::cpu::CpuState,
mem: &mut GuestMemory|
-> Result<u64, ExitReason> {
let ptr = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
if ptr == 0 {
s.last_error.store(87, Ordering::SeqCst); // ERROR_INVALID_PARAMETER
return Ok(0);
}
let ft = s.clock.now_filetime();
mem.write_u64(ptr, ft).map_err(ExitReason::MemoryFault)?;
Ok(0)
};
registry.register(KERNEL32, "GetSystemTimeAsFileTime", handler);
registry.alias(
"api-ms-win-core-sysinfo-l1-1-0.dll",
KERNEL32,
"GetSystemTimeAsFileTime",
);
// 2. GetCurrentProcessId() -> DWORD
let s = state.clone();
let handler = move |_args: &crate::imports::Win64Args,
_cpu: &mut crate::cpu::CpuState,
_mem: &mut GuestMemory|
-> Result<u64, ExitReason> { Ok(s.process_id as u64) };
registry.register(KERNEL32, "GetCurrentProcessId", handler);
registry.alias(PROCESS_THREADS_V1, KERNEL32, "GetCurrentProcessId");
// 3. GetCurrentThreadId() -> DWORD
let s = state.clone();
let handler = move |_args: &crate::imports::Win64Args,
_cpu: &mut crate::cpu::CpuState,
_mem: &mut GuestMemory|
-> Result<u64, ExitReason> { Ok(s.thread_id as u64) };
registry.register(KERNEL32, "GetCurrentThreadId", handler);
registry.alias(PROCESS_THREADS_V1, KERNEL32, "GetCurrentThreadId");
// 4. GetLastError() -> DWORD
let s = state.clone();
let handler =
move |_args: &crate::imports::Win64Args,
_cpu: &mut crate::cpu::CpuState,
_mem: &mut GuestMemory|
-> Result<u64, ExitReason> { Ok(s.last_error.load(Ordering::SeqCst) as u64) };
registry.register(KERNEL32, "GetLastError", handler);
registry.alias(
"api-ms-win-core-errorhandling-l1-1-0.dll",
KERNEL32,
"GetLastError",
);
// 5. SetLastError(dwErrCode: DWORD)
let s = state.clone();
let handler = move |args: &crate::imports::Win64Args,
_cpu: &mut crate::cpu::CpuState,
mem: &mut GuestMemory|
-> Result<u64, ExitReason> {
let code = args.get(0, mem).map_err(ExitReason::MemoryFault)? as u32;
s.last_error.store(code, Ordering::SeqCst);
Ok(0)
};
registry.register(KERNEL32, "SetLastError", handler);
registry.alias(
"api-ms-win-core-errorhandling-l1-1-0.dll",
KERNEL32,
"SetLastError",
);
let s = state.clone();
registry.register(KERNEL32, "VirtualAlloc", move |args, _, mem| {
let requested = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
let size = args.get(1, mem).map_err(ExitReason::MemoryFault)?;
let allocation_type = args.get(2, mem).map_err(ExitReason::MemoryFault)? as u32;
let protect = args.get(3, mem).map_err(ExitReason::MemoryFault)? as u32;
if size == 0 {
return s.fail(ERROR_INVALID_PARAMETER, 0);
}
if allocation_type != MEM_COMMIT_RESERVE {
return s.fail(ERROR_NOT_SUPPORTED, 0);
}
// Executable allocations require guest translation cache invalidation.
let permissions = match protect {
0x01 => MemoryPermissions::NO_ACCESS,
0x02 => MemoryPermissions::READ_ONLY,
0x04 => MemoryPermissions::READ_WRITE,
_ => return s.fail(ERROR_INVALID_PARAMETER, 0),
};
let base = requested & !(ALLOCATION_GRANULARITY - 1);
if requested != 0 && base == 0 {
return s.fail(ERROR_INVALID_ADDRESS, 0);
}
let Some(size) = size
.checked_add(requested - base)
.and_then(|span| span.checked_next_multiple_of(PAGE_SIZE))
.and_then(|span| usize::try_from(span).ok())
else {
return s.fail(ERROR_INVALID_PARAMETER, 0);
};
match mem.map_virtual_allocation(base, size, permissions) {
Ok(address) => Ok(address),
Err(MemoryError::OverlappingRegion { .. } | MemoryError::Overflow) => {
s.fail(ERROR_INVALID_ADDRESS, 0)
}
Err(_) => s.fail(ERROR_NOT_ENOUGH_MEMORY, 0),
}
});
let s = state.clone();
registry.register(KERNEL32, "VirtualFree", move |args, _, mem| {
let address = args.get(0, mem).map_err(ExitReason::MemoryFault)?;
let size = args.get(1, mem).map_err(ExitReason::MemoryFault)?;
let free_type = args.get(2, mem).map_err(ExitReason::MemoryFault)? as u32;
if free_type != MEM_RELEASE {
return s.fail(ERROR_NOT_SUPPORTED, 0);
}
if size != 0 {
return s.fail(ERROR_INVALID_PARAMETER, 0);
}
if !mem.release_virtual_allocation(address) {
return s.fail(ERROR_INVALID_ADDRESS, 0);
}
Ok(1)
});
for symbol in ["VirtualAlloc", "VirtualFree"] {
registry.alias("api-ms-win-core-memory-l1-1-0.dll", KERNEL32, symbol);
registry.set_status(KERNEL32, symbol, ServiceStatus::Partial);
}
crate::runtime_table::register(registry, &state);
// 8. XMemAlloc(dwSize, dwAllocAttributes) -> LPVOID (Xbox Scarlett allocator in xmem.dll)
let s = state.clone();
@@ -582,3 +326,244 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc<Serv
ServiceStatus::Implemented,
);
}
/// Implementations behind the generated adapters. A failure the guest can
/// observe sets its last error; `Err` stops the guest.
pub(crate) mod handlers {
use super::*;
use crate::runtime::{Float32, Float64, OutPtr, ServiceContext};
use crate::softfloat::{Control, F32, F64, square_root};
type Outcome<T> = Result<T, ExitReason>;
pub fn set_process_priority_boost(
context: &mut ServiceContext<'_>,
process: u64,
disable: bool,
) -> Outcome<bool> {
if !context.state.is_current_process(process) {
return Ok(false);
}
context
.state
.priority_boost_disabled
.store(disable, Ordering::SeqCst);
Ok(true)
}
pub fn get_process_priority_boost(
context: &mut ServiceContext<'_>,
process: u64,
disabled: OutPtr<4>,
) -> Outcome<bool> {
if !context.state.is_current_process(process) {
return Ok(false);
}
let value = u32::from(context.state.priority_boost_disabled());
if disabled.store(context.memory, value.to_le_bytes()).is_err() {
return context.state.fail(ERROR_NOACCESS, false);
}
Ok(true)
}
pub fn get_current_process(_: &mut ServiceContext<'_>) -> Outcome<u64> {
Ok(CURRENT_PROCESS)
}
pub fn get_process_id(context: &mut ServiceContext<'_>, process: u64) -> Outcome<u32> {
Ok(if context.state.is_current_process(process) {
context.state.process_id
} else {
0
})
}
pub fn get_current_thread(_: &mut ServiceContext<'_>) -> Outcome<u64> {
Ok(CURRENT_THREAD)
}
pub fn get_current_process_id(context: &mut ServiceContext<'_>) -> Outcome<u32> {
Ok(context.state.process_id)
}
pub fn get_current_thread_id(context: &mut ServiceContext<'_>) -> Outcome<u32> {
Ok(context.state.thread_id)
}
pub fn open_thread(
context: &mut ServiceContext<'_>,
access: u32,
inherit: bool,
id: u32,
) -> Outcome<u64> {
let state = context.state;
if id != state.thread_id {
return state.fail(ERROR_INVALID_PARAMETER, 0);
}
if inherit || access & !THREAD_SUPPORTED_RIGHTS != 0 {
return state.fail(ERROR_NOT_SUPPORTED, 0);
}
let mut thread = state.thread.lock().expect("guest thread state");
let Some(handle) = thread
.last_handle
.checked_add(4)
.filter(|_| thread.handles.len() < MAX_THREAD_HANDLES)
else {
return state.fail(ERROR_NOT_ENOUGH_MEMORY, 0);
};
thread.handles.insert(handle, access);
thread.last_handle = handle;
Ok(handle)
}
pub fn get_thread_priority(context: &mut ServiceContext<'_>, handle: u64) -> Outcome<i32> {
let thread = context.state.thread.lock().expect("guest thread state");
if let Err(error) = thread.check_access(handle, THREAD_QUERY_RIGHTS) {
return context
.state
.fail(error, THREAD_PRIORITY_ERROR_RETURN as i32);
}
Ok(thread.priority)
}
pub fn set_thread_priority(
context: &mut ServiceContext<'_>,
handle: u64,
priority: i32,
) -> Outcome<bool> {
let state = context.state;
let mut thread = state.thread.lock().expect("guest thread state");
if let Err(error) = thread.check_access(handle, THREAD_SET_RIGHTS) {
return state.fail(error, false);
}
if matches!(priority, 0x0001_0000 | 0x0002_0000) {
return state.fail(ERROR_NOT_SUPPORTED, false);
}
if !matches!(priority, -15 | -2..=2 | 15) {
return state.fail(ERROR_INVALID_PARAMETER, false);
}
thread.priority = priority;
Ok(true)
}
pub fn close_handle(context: &mut ServiceContext<'_>, handle: u64) -> Outcome<bool> {
let closed = matches!(handle, CURRENT_PROCESS | CURRENT_THREAD)
|| context
.state
.thread
.lock()
.expect("guest thread state")
.handles
.remove(&handle)
.is_some();
if closed {
Ok(true)
} else {
context.state.fail(ERROR_INVALID_HANDLE, false)
}
}
pub fn get_system_time_as_file_time(
context: &mut ServiceContext<'_>,
time: OutPtr<8>,
) -> Outcome<()> {
let now = context.state.clock.now_filetime();
time.store(context.memory, now.to_le_bytes())
.map_err(ExitReason::MemoryFault)
}
pub fn get_last_error(context: &mut ServiceContext<'_>) -> Outcome<u32> {
Ok(context.state.last_error.load(Ordering::SeqCst))
}
pub fn set_last_error(context: &mut ServiceContext<'_>, code: u32) -> Outcome<()> {
context.state.last_error.store(code, Ordering::SeqCst);
Ok(())
}
pub fn virtual_alloc(
context: &mut ServiceContext<'_>,
requested: u64,
size: u64,
kind: u32,
protect: u32,
) -> Outcome<u64> {
let state = context.state;
if size == 0 {
return state.fail(ERROR_INVALID_PARAMETER, 0);
}
if kind != MEM_COMMIT_RESERVE {
return state.fail(ERROR_NOT_SUPPORTED, 0);
}
// Executable allocations require guest translation cache invalidation.
let permissions = match protect {
0x01 => MemoryPermissions::NO_ACCESS,
0x02 => MemoryPermissions::READ_ONLY,
0x04 => MemoryPermissions::READ_WRITE,
_ => return state.fail(ERROR_INVALID_PARAMETER, 0),
};
let base = requested & !(ALLOCATION_GRANULARITY - 1);
if requested != 0 && base == 0 {
return state.fail(ERROR_INVALID_ADDRESS, 0);
}
let Some(size) = size
.checked_add(requested - base)
.and_then(|span| span.checked_next_multiple_of(PAGE_SIZE))
.and_then(|span| usize::try_from(span).ok())
else {
return state.fail(ERROR_INVALID_PARAMETER, 0);
};
match context
.memory
.map_virtual_allocation(base, size, permissions)
{
Ok(address) => Ok(address),
Err(MemoryError::OverlappingRegion { .. } | MemoryError::Overflow) => {
state.fail(ERROR_INVALID_ADDRESS, 0)
}
Err(_) => state.fail(ERROR_NOT_ENOUGH_MEMORY, 0),
}
}
pub fn virtual_free(
context: &mut ServiceContext<'_>,
address: u64,
size: u64,
kind: u32,
) -> Outcome<bool> {
let state = context.state;
if kind != MEM_RELEASE {
return state.fail(ERROR_NOT_SUPPORTED, false);
}
if size != 0 {
return state.fail(ERROR_INVALID_PARAMETER, false);
}
if !context.memory.release_virtual_allocation(address) {
return state.fail(ERROR_INVALID_ADDRESS, false);
}
Ok(true)
}
/// The guest MXCSR is not visible to a service, so results use the default
/// rounding and raise no guest flags; the registry marks them partial.
const DEFAULT_MXCSR: u32 = crate::cpu::Mxcsr::RESET;
pub fn sqrt(_: &mut ServiceContext<'_>, x: Float64) -> Outcome<Float64> {
let control = Control::from_mxcsr(DEFAULT_MXCSR);
Ok(Float64(square_root(F64, x.0, &control).bits))
}
pub fn sqrtf(_: &mut ServiceContext<'_>, x: Float32) -> Outcome<Float32> {
let control = Control::from_mxcsr(DEFAULT_MXCSR);
let bits = square_root(F32, u64::from(x.0), &control).bits;
Ok(Float32(bits as u32))
}
pub fn fabs(_: &mut ServiceContext<'_>, x: Float64) -> Outcome<Float64> {
Ok(Float64(x.0 & !(1 << 63)))
}
pub fn fabsf(_: &mut ServiceContext<'_>, x: Float32) -> Outcome<Float32> {
Ok(Float32(x.0 & !(1 << 31)))
}
}
+641
View File
@@ -0,0 +1,641 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Exact binary32 and binary64 arithmetic with x86 SSE rules.
//!
//! Every operation computes an exact or sticky integer result and rounds once,
//! in any MXCSR rounding mode. NaN selection, the negative default NaN,
//! denormals-are-zero, flush-to-zero, tininess after rounding and the sticky
//! exception flags follow the Intel SDM (Vol. 1, 4.8, 4.9 and 11.5). Host
//! floating point is never used: ARM64 differs in all of those.
use std::cmp::Ordering;
/// MXCSR exception flags, in their register positions.
pub const INVALID: u32 = 1;
pub const DENORMAL: u32 = 1 << 1;
pub const DIVIDE_BY_ZERO: u32 = 1 << 2;
pub const OVERFLOW: u32 = 1 << 3;
pub const UNDERFLOW: u32 = 1 << 4;
pub const PRECISION: u32 = 1 << 5;
/// Exceptions detected before a result is computed.
pub const PRE_COMPUTATION: u32 = INVALID | DENORMAL | DIVIDE_BY_ZERO;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Rounding {
Nearest,
Down,
Up,
Zero,
}
/// Arithmetic controls from MXCSR.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Control {
pub rounding: Rounding,
pub denormals_are_zero: bool,
pub flush_to_zero: bool,
pub underflow_masked: bool,
}
impl Control {
pub fn from_mxcsr(mxcsr: u32) -> Self {
Self {
rounding: match mxcsr >> 13 & 3 {
0 => Rounding::Nearest,
1 => Rounding::Down,
2 => Rounding::Up,
_ => Rounding::Zero,
},
denormals_are_zero: mxcsr & 1 << 6 != 0,
flush_to_zero: mxcsr & 1 << 15 != 0,
underflow_masked: mxcsr & 1 << 11 != 0,
}
}
}
/// A binary interchange format.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Format {
pub bits: u32,
/// Stored significand bits.
fraction: u32,
}
pub const F32: Format = Format {
bits: 32,
fraction: 23,
};
pub const F64: Format = Format {
bits: 64,
fraction: 52,
};
impl Format {
fn exponent_max(self) -> u64 {
(1 << (self.bits - 1 - self.fraction)) - 1
}
fn bias(self) -> i32 {
(self.exponent_max() >> 1) as i32
}
fn sign_bit(self) -> u64 {
1 << (self.bits - 1)
}
fn fraction_mask(self) -> u64 {
(1 << self.fraction) - 1
}
fn quiet_bit(self) -> u64 {
1 << (self.fraction - 1)
}
fn infinity(self, sign: bool) -> u64 {
self.signed(sign, self.exponent_max() << self.fraction)
}
fn largest(self, sign: bool) -> u64 {
self.infinity(sign) - 1
}
/// The x86 default NaN is negative and quiet.
fn default_nan(self) -> u64 {
self.infinity(true) | self.quiet_bit()
}
fn signed(self, sign: bool, magnitude: u64) -> u64 {
magnitude | if sign { self.sign_bit() } else { 0 }
}
fn sign(self, value: u64) -> bool {
value & self.sign_bit() != 0
}
fn magnitude(self, value: u64) -> u64 {
value & (self.sign_bit() - 1)
}
fn is_nan(self, value: u64) -> bool {
self.magnitude(value) > self.infinity(false)
}
fn is_signaling(self, value: u64) -> bool {
self.is_nan(value) && value & self.quiet_bit() == 0
}
fn is_infinite(self, value: u64) -> bool {
self.magnitude(value) == self.infinity(false)
}
fn is_zero(self, value: u64) -> bool {
self.magnitude(value) == 0
}
fn is_denormal(self, value: u64) -> bool {
let magnitude = self.magnitude(value);
magnitude != 0 && magnitude <= self.fraction_mask()
}
/// Significand and exponent with value `significand * 2^exponent`, for a
/// finite number.
fn unpack(self, value: u64) -> (u64, i32) {
let field = (self.magnitude(value) >> self.fraction) as i32;
let fraction = value & self.fraction_mask();
let scale = self.bias() + self.fraction as i32;
if field == 0 {
(fraction, 1 - scale)
} else {
(fraction | 1 << self.fraction, field - scale)
}
}
}
/// A result and the exceptions it raised.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Outcome {
pub bits: u64,
pub flags: u32,
}
fn exact(bits: u64) -> Outcome {
Outcome { bits, flags: 0 }
}
fn invalid(format: Format) -> Outcome {
Outcome {
bits: format.default_nan(),
flags: INVALID,
}
}
/// Divide `value` by 2^shift, rounding, where `sticky` marks a nonzero part
/// below the integer. Returns the quotient and whether it is inexact.
fn round_shift(
value: u128,
shift: i32,
sticky: bool,
sign: bool,
rounding: Rounding,
) -> (u128, bool) {
if shift <= 0 {
// Callers keep enough bits that a sticky value always has to shift.
return (value << -shift, sticky);
}
let (quotient, half) = if shift > 128 {
(0, Ordering::Less)
} else if shift == 128 {
(0, value.cmp(&(1 << 127)))
} else {
let remainder = value & ((1 << shift) - 1);
(value >> shift, remainder.cmp(&(1 << (shift - 1))))
};
let lost = if shift >= 128 {
value != 0
} else {
value & ((1 << shift) - 1) != 0
};
let inexact = lost || sticky;
let half = if half == Ordering::Equal && sticky {
Ordering::Greater
} else {
half
};
let up = inexact
&& match rounding {
Rounding::Nearest => match half {
Ordering::Greater => true,
Ordering::Equal => quotient & 1 == 1,
Ordering::Less => false,
},
Rounding::Down => sign,
Rounding::Up => !sign,
Rounding::Zero => false,
};
(quotient + u128::from(up), inexact)
}
/// Round `significand * 2^exponent`, slightly larger in magnitude if `sticky`,
/// to `format`.
fn round(
format: Format,
sign: bool,
significand: u128,
exponent: i32,
sticky: bool,
control: &Control,
) -> Outcome {
if significand == 0 {
return exact(format.signed(sign, 0));
}
let precision = format.fraction as i32 + 1;
let length = 128 - significand.leading_zeros() as i32;
let shift = length - precision;
let minimum = 1 - format.bias();
let mut leading = exponent + length - 1;
let round_at = |shift| round_shift(significand, shift, sticky, sign, control.rounding);
// Tininess is detected after rounding to an unbounded exponent.
let (mut value, mut inexact) = round_at(shift);
if value >> precision != 0 {
value >>= 1;
leading += 1;
}
let tiny = leading < minimum;
let mut flags = 0;
if tiny && control.flush_to_zero && control.underflow_masked {
return Outcome {
bits: format.signed(sign, 0),
flags: UNDERFLOW | PRECISION,
};
}
let before = exponent + length - 1;
if before < minimum {
(value, inexact) = round_at(shift + (minimum - before));
// A carry out of the fraction lands exactly on the smallest normal.
leading = minimum;
}
if tiny && (inexact || !control.underflow_masked) {
flags |= UNDERFLOW;
}
if inexact {
flags |= PRECISION;
}
if leading > format.bias() {
let to_infinity = match control.rounding {
Rounding::Nearest => true,
Rounding::Down => sign,
Rounding::Up => !sign,
Rounding::Zero => false,
};
return Outcome {
bits: if to_infinity {
format.infinity(sign)
} else {
format.largest(sign)
},
flags: OVERFLOW | PRECISION,
};
}
// The leading bit of a normal value adds one to the exponent field.
let field = (leading - minimum) as u64;
Outcome {
bits: format.signed(sign, (field << format.fraction) + value as u64),
flags,
}
}
/// Replace a denormal by a signed zero under DAZ, otherwise note it.
fn operand(format: Format, value: u64, control: &Control) -> (u64, u32) {
if !format.is_denormal(value) {
(value, 0)
} else if control.denormals_are_zero {
(value & format.sign_bit(), 0)
} else {
(value, DENORMAL)
}
}
/// The result of a two-operand form with a NaN source: the first NaN, quieted.
fn select_nan(format: Format, a: u64, b: u64) -> Option<Outcome> {
let chosen = if format.is_nan(a) {
a
} else if format.is_nan(b) {
b
} else {
return None;
};
let signaling = format.is_signaling(a) || format.is_signaling(b);
Some(Outcome {
bits: chosen | format.quiet_bit(),
flags: if signaling { INVALID } else { 0 },
})
}
/// Two-operand arithmetic.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Arithmetic {
Add,
Sub,
Mul,
Div,
Min,
Max,
}
pub fn arithmetic(kind: Arithmetic, format: Format, a: u64, b: u64, control: &Control) -> Outcome {
let (a, a_flag) = operand(format, a, control);
let (b, b_flag) = operand(format, b, control);
if matches!(kind, Arithmetic::Min | Arithmetic::Max) {
return extremum(kind == Arithmetic::Min, format, a, b, a_flag | b_flag);
}
if let Some(outcome) = select_nan(format, a, b) {
return outcome;
}
let (sign_a, sign_b) = (format.sign(a), format.sign(b));
let sign = sign_a != sign_b;
let infinite = format.is_infinite(a) || format.is_infinite(b);
let special = match kind {
Arithmetic::Add | Arithmetic::Sub if infinite => {
let sign_b = sign_b != (kind == Arithmetic::Sub);
Some(if !format.is_infinite(b) {
exact(a)
} else if format.is_infinite(a) && sign_a != sign_b {
invalid(format)
} else {
exact(format.infinity(sign_b))
})
}
Arithmetic::Mul if infinite => Some(if format.is_zero(a) || format.is_zero(b) {
invalid(format)
} else {
exact(format.infinity(sign))
}),
Arithmetic::Div => {
let undefined = (format.is_infinite(a) && format.is_infinite(b))
|| (format.is_zero(a) && format.is_zero(b));
if undefined {
Some(invalid(format))
} else if format.is_infinite(a) {
Some(exact(format.infinity(sign)))
} else if format.is_infinite(b) {
Some(exact(format.signed(sign, 0)))
} else if format.is_zero(b) {
Some(Outcome {
bits: format.infinity(sign),
flags: DIVIDE_BY_ZERO,
})
} else {
None
}
}
_ => None,
};
let mut outcome = special.unwrap_or_else(|| {
let (sa, ea) = format.unpack(a);
let (sb, eb) = format.unpack(b);
match kind {
Arithmetic::Mul => round(
format,
sign,
u128::from(sa) * u128::from(sb),
ea + eb,
false,
control,
),
Arithmetic::Div if sa == 0 => exact(format.signed(sign, 0)),
Arithmetic::Div => {
let shift = u128::from(sa).leading_zeros() as i32 - 1;
let dividend = u128::from(sa) << shift;
let divisor = u128::from(sb);
round(
format,
sign,
dividend / divisor,
ea - eb - shift,
!dividend.is_multiple_of(divisor),
control,
)
}
_ => {
let sign_b = sign_b != (kind == Arithmetic::Sub);
sum(format, (sign_a, sa, ea), (sign_b, sb, eb), control)
}
}
});
// Invalid operation and divide by zero take priority over a denormal operand.
if outcome.flags & (INVALID | DIVIDE_BY_ZERO) == 0 {
outcome.flags |= a_flag | b_flag;
}
outcome
}
/// Sum of two finite numbers given as sign, significand and exponent.
fn sum(format: Format, a: (bool, u64, i32), b: (bool, u64, i32), control: &Control) -> Outcome {
// Alignment is exact up to this distance. Beyond it the larger operand is
// normal and the smaller is below 2^-17 of its unit in the last place, so it
// moves the exact result only within a quarter unit of the larger operand,
// or of the half-sized unit just below a power of two.
const EXACT: i32 = 70;
if a.1 == 0 || b.1 == 0 {
if a.1 == 0 && b.1 == 0 {
let negative = if a.0 == b.0 {
a.0
} else {
control.rounding == Rounding::Down
};
return exact(format.signed(negative, 0));
}
let (sign, significand, exponent) = if a.1 == 0 { b } else { a };
return round(
format,
sign,
u128::from(significand),
exponent,
false,
control,
);
}
let (high, low) = if a.2 >= b.2 { (a, b) } else { (b, a) };
let distance = high.2 - low.2;
if distance > EXACT {
let wide = u128::from(high.1) << EXACT;
// Any value strictly inside that interval rounds as the exact one does.
let significand = if high.0 == low.0 { wide } else { wide - 1 };
return round(format, high.0, significand, high.2 - EXACT, true, control);
}
let x = (u128::from(high.1) << distance) as i128 * if high.0 { -1 } else { 1 };
let y = i128::from(low.1) * if low.0 { -1 } else { 1 };
let total = x + y;
if total == 0 {
return exact(format.signed(control.rounding == Rounding::Down, 0));
}
round(
format,
total < 0,
total.unsigned_abs(),
low.2,
false,
control,
)
}
/// MIN and MAX return the second operand unless the first is strictly smaller
/// or larger; any NaN is an invalid operation and selects the second operand.
fn extremum(minimum: bool, format: Format, a: u64, b: u64, denormal: u32) -> Outcome {
if format.is_nan(a) || format.is_nan(b) {
return Outcome {
bits: b,
flags: INVALID,
};
}
let order = compare_numbers(format, a, b);
let first = order
== if minimum {
Ordering::Less
} else {
Ordering::Greater
};
Outcome {
bits: if first { a } else { b },
flags: denormal,
}
}
/// Order of two non-NaN values; zeros of either sign are equal.
fn compare_numbers(format: Format, a: u64, b: u64) -> Ordering {
let key = |value| {
let magnitude = format.magnitude(value) as i128;
if format.sign(value) {
-magnitude
} else {
magnitude
}
};
key(a).cmp(&key(b))
}
/// Compare, with `None` for unordered. A quiet NaN is invalid only when
/// `signaling` is set.
pub fn compare(
format: Format,
a: u64,
b: u64,
signaling: bool,
control: &Control,
) -> (Option<Ordering>, u32) {
let (a, a_flag) = operand(format, a, control);
let (b, b_flag) = operand(format, b, control);
if format.is_nan(a) || format.is_nan(b) {
let raises = signaling || format.is_signaling(a) || format.is_signaling(b);
return (None, if raises { INVALID } else { 0 });
}
(Some(compare_numbers(format, a, b)), a_flag | b_flag)
}
pub fn square_root(format: Format, value: u64, control: &Control) -> Outcome {
let (value, denormal) = operand(format, value, control);
if format.is_nan(value) {
return Outcome {
bits: value | format.quiet_bit(),
flags: if format.is_signaling(value) {
INVALID
} else {
0
},
};
}
if format.is_zero(value) {
return exact(value);
}
if format.sign(value) {
return invalid(format);
}
if format.is_infinite(value) {
return exact(value);
}
let (significand, exponent) = format.unpack(value);
let mut shift = u128::from(significand).leading_zeros() as i32 - 1;
if (exponent - shift) % 2 != 0 {
shift -= 1;
}
let wide = u128::from(significand) << shift;
let root = wide.isqrt();
let mut outcome = round(
format,
false,
root,
(exponent - shift) / 2,
root * root != wide,
control,
);
outcome.flags |= denormal;
outcome
}
/// Convert between binary32 and binary64.
pub fn convert(from: Format, to: Format, value: u64, control: &Control) -> Outcome {
let (value, denormal) = operand(from, value, control);
let sign = from.sign(value);
if from.is_nan(value) {
let fraction = value & from.fraction_mask();
let moved = if to.fraction >= from.fraction {
fraction << (to.fraction - from.fraction)
} else {
fraction >> (from.fraction - to.fraction)
};
return Outcome {
bits: to.infinity(sign) | moved | to.quiet_bit(),
flags: if from.is_signaling(value) { INVALID } else { 0 },
};
}
if from.is_infinite(value) {
return exact(to.infinity(sign));
}
let (significand, exponent) = from.unpack(value);
let mut outcome = round(to, sign, u128::from(significand), exponent, false, control);
outcome.flags |= denormal;
outcome
}
/// Convert a signed integer.
pub fn from_integer(format: Format, value: i64, control: &Control) -> Outcome {
round(
format,
value < 0,
u128::from(value.unsigned_abs()),
0,
false,
control,
)
}
/// Convert to a signed integer of `bits`. A NaN or a value outside the range
/// gives the integer indefinite value and raises invalid.
pub fn to_integer(
format: Format,
value: u64,
bits: u32,
truncate: bool,
control: &Control,
) -> Outcome {
let indefinite = Outcome {
bits: 1 << (bits - 1),
flags: INVALID,
};
let (value, _) = operand(format, value, control);
if format.is_nan(value) || format.is_infinite(value) {
return indefinite;
}
let sign = format.sign(value);
let (significand, exponent) = format.unpack(value);
if exponent > 64 && significand != 0 {
return indefinite;
}
let rounding = if truncate {
Rounding::Zero
} else {
control.rounding
};
let (magnitude, inexact) =
round_shift(u128::from(significand), -exponent, false, sign, rounding);
let limit = 1u128 << (bits - 1);
if magnitude > limit || (magnitude == limit && !sign) {
return indefinite;
}
let mask = if bits == 64 {
u64::MAX
} else {
(1 << bits) - 1
};
let integer = if sign {
(magnitude as u64).wrapping_neg()
} else {
magnitude as u64
};
Outcome {
bits: integer & mask,
flags: if inexact { PRECISION } else { 0 },
}
}
+468
View File
@@ -0,0 +1,468 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Shared x86-64 decoder.
//!
//! The static PE probe, the software interpreter and the native DBT all decode
//! through [`decode`], driven by static tables generated from
//! `x86/instructions.toml`, so instruction boundaries, operands and rejected
//! forms agree across them.
use crate::x86_table::{
FORMS, GROUPS, ONE_BYTE, Op, TWO_BYTE, TWO_BYTE_66, TWO_BYTE_F2, TWO_BYTE_F3,
};
/// Architectural x86-64 instruction length limit, in bytes.
///
/// An instruction may not exceed 15 bytes (Intel SDM Vol. 2A, "Instruction
/// Length"). Sequences longer than this are not decodable and are rejected as
/// illegal instructions.
pub const MAX_INSTRUCTION_LEN: usize = 15;
/// Number of leading legacy segment prefix bytes (0x64 FS, 0x65 GS) at the
/// start of a code slice, capped at [`MAX_INSTRUCTION_LEN`].
///
/// The count includes the first byte when it is a segment prefix, so a run of
/// more than [`MAX_INSTRUCTION_LEN`] prefixes is reported as
/// [`MAX_INSTRUCTION_LEN`].
pub fn segment_prefix_len(code: &[u8]) -> usize {
let mut len = match code.first() {
Some(&0x64 | &0x65) => 1,
_ => 0,
};
while len < MAX_INSTRUCTION_LEN && matches!(code.get(len), Some(&0x64 | &0x65)) {
len += 1;
}
len
}
/// One x86-64 instruction form from the generated registry tables.
#[derive(Clone, Copy, Debug)]
pub struct Form {
pub op: Op,
pub encoding: Encoding,
pub size: OperandSize,
pub immediate: Immediate,
/// Source width in bytes when it differs from the operand size, else 0.
pub source: u8,
pub has_modrm: bool,
pub memory_only: bool,
pub register_only: bool,
pub no_rex_b: bool,
/// A 16-byte memory operand may have any alignment.
pub unaligned: bool,
}
/// Opcode table entry.
#[derive(Clone, Copy, Debug)]
pub enum Entry {
Unsupported,
Form(u16),
Group(u16),
}
/// How a form names its operands, destination first.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Encoding {
None,
RmReg,
RegRm,
RegRmImm,
Rm,
RmUnread,
RmImm,
RmOne,
RmCl,
AccImm,
OpReg,
OpRegImm,
Imm,
Rel,
/// XMM `reg` from XMM or memory.
XmmRm,
/// XMM or memory from XMM `reg`.
RmXmm,
XmmRmImm,
/// XMM `rm` shifted in place by an immediate.
RmImmXmm,
/// XMM `reg` from a general register or memory.
XmmGpr,
/// General register or memory from XMM `reg`.
GprXmm,
XmmGprImm,
/// General `reg` from XMM `rm`.
RegXmm,
RegXmmImm,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum OperandSize {
Byte,
Variable,
Wide,
Quad,
Xmm,
None,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Immediate {
None,
SignedByte,
SignedFull,
Signed32,
Full,
Word,
/// Zero-extended byte.
Byte,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Segment {
Fs,
Gs,
}
/// A general or XMM register operand, as the encoding says. `high` selects AH,
/// CH, DH or BH of `index`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RegOperand {
pub index: u8,
pub high: bool,
}
/// A memory operand. A RIP-relative operand has its absolute address folded
/// into `disp` and no base.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MemOperand {
pub base: Option<u8>,
pub index: Option<(u8, u8)>,
pub disp: i64,
pub segment: Option<Segment>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RmOperand {
Reg(RegOperand),
Mem(MemOperand),
}
/// A fully decoded instruction at a known address.
#[derive(Clone, Copy, Debug)]
pub struct Insn {
pub op: Op,
pub encoding: Encoding,
/// Index into [`FORMS`].
pub form: u16,
/// Guest address of the first byte.
pub rip: u64,
pub len: u8,
/// Operand size in bytes: 1, 2, 4, 8 or 16 (XMM), or 0 when there is none.
pub size: u8,
/// Width of the ModRM operand in bytes.
pub rm_size: u8,
pub rm: Option<RmOperand>,
/// ModRM `reg` operand, or the register encoded in the opcode.
pub reg: RegOperand,
/// Sign-extended immediate, or the absolute branch target.
pub imm: u64,
/// Condition code for Jcc, CMOVcc and SETcc.
pub condition: u8,
}
impl Insn {
/// Address of the following instruction.
pub fn next_rip(&self) -> u64 {
self.rip.wrapping_add(u64::from(self.len))
}
/// The memory operand, if any.
pub fn memory(&self) -> Option<MemOperand> {
match self.rm {
Some(RmOperand::Mem(operand)) => Some(operand),
_ => None,
}
}
}
/// Why bytes did not decode.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DecodeError<E> {
/// The byte source refused a fetch.
Fetch(E),
/// No declared form matches; carries the byte that decided it.
Unsupported(u8),
}
struct Cursor<F> {
fetch: F,
rip: u64,
len: usize,
last: u8,
}
impl<E, F: FnMut(u64) -> Result<u8, E>> Cursor<F> {
fn u8(&mut self) -> Result<u8, DecodeError<E>> {
if self.len == MAX_INSTRUCTION_LEN {
return Err(DecodeError::Unsupported(self.last));
}
let byte =
(self.fetch)(self.rip.wrapping_add(self.len as u64)).map_err(DecodeError::Fetch)?;
self.len += 1;
self.last = byte;
Ok(byte)
}
/// Little-endian value of `count` bytes.
fn bytes(&mut self, count: usize) -> Result<u64, DecodeError<E>> {
let mut value = 0;
for index in 0..count {
value |= u64::from(self.u8()?) << (8 * index);
}
Ok(value)
}
fn signed(&mut self, count: usize) -> Result<u64, DecodeError<E>> {
let value = self.bytes(count)?;
let shift = 64 - 8 * count as u32;
Ok(((value << shift) as i64 >> shift) as u64)
}
}
/// Decode one instruction at `rip`. `fetch` supplies the byte at an address and
/// is called only for bytes that belong to the instruction, in order.
///
/// Forms the registry does not declare, LOCK, address-size overrides and an
/// ignored segment override after FS or GS are rejected rather than approximated.
pub fn decode<E>(
rip: u64,
fetch: impl FnMut(u64) -> Result<u8, E>,
) -> Result<Insn, DecodeError<E>> {
let mut cursor = Cursor {
fetch,
rip,
len: 0,
last: 0,
};
let mut operand_size = false;
let mut rep = false;
let mut repne = false;
let mut segment = None;
let mut byte = cursor.u8()?;
loop {
let selected = match byte {
0x64 => Segment::Fs,
0x65 => Segment::Gs,
0x66 => {
operand_size = true;
byte = cursor.u8()?;
continue;
}
0xF3 => {
rep = true;
byte = cursor.u8()?;
continue;
}
0xF2 => {
repne = true;
byte = cursor.u8()?;
continue;
}
// CS, DS, ES and SS overrides have no effect in 64-bit mode. After
// FS or GS their meaning is not relied on, so it is rejected.
0x26 | 0x2E | 0x36 | 0x3E if segment.is_none() => {
byte = cursor.u8()?;
continue;
}
_ => break,
};
// FS and GS together are architecturally undefined (Intel SDM Vol. 2,
// "Instruction Prefixes"); the local rule is that GS applies.
if segment != Some(Segment::Gs) {
segment = Some(selected);
}
byte = cursor.u8()?;
}
let rex = if byte & 0xF0 == 0x40 { byte } else { 0 };
if rex != 0 {
byte = cursor.u8()?;
}
let (rex_w, rex_r, rex_x, rex_b) =
(rex & 8 != 0, (rex & 4) << 1, (rex & 2) << 2, (rex & 1) << 3);
// F2 and F3 together have no defined meaning for any declared form.
if rep && repne {
return Err(DecodeError::Unsupported(0xF2));
}
let two_byte = byte == 0x0F;
let opcode = if two_byte { cursor.u8()? } else { byte };
let slot = usize::from(opcode);
let table = if !two_byte {
// Only PAUSE (F3 90) has a meaning here for F3 on a one-byte opcode.
if repne || (rep && opcode != 0x90) {
return Err(DecodeError::Unsupported(if rep { 0xF3 } else { 0xF2 }));
}
&ONE_BYTE
} else if rep {
&TWO_BYTE_F3
} else if repne {
&TWO_BYTE_F2
} else if operand_size && !matches!(TWO_BYTE_66[slot], Entry::Unsupported) {
// 0x66 selects the form instead of an operand size.
operand_size = false;
&TWO_BYTE_66
} else {
&TWO_BYTE
};
let entry = table[slot];
let mut modrm = 0;
let form_index = match entry {
Entry::Unsupported => return Err(DecodeError::Unsupported(opcode)),
Entry::Form(index) => index,
Entry::Group(index) => {
modrm = cursor.u8()?;
GROUPS[usize::from(index)][usize::from((modrm >> 3) & 7)]
}
};
let form = FORMS
.get(usize::from(form_index))
.ok_or(DecodeError::Unsupported(opcode))?;
if form.has_modrm && matches!(entry, Entry::Form(_)) {
modrm = cursor.u8()?;
}
let size = match form.size {
OperandSize::None => 0,
OperandSize::Byte => 1,
OperandSize::Quad => 8,
OperandSize::Xmm => 16,
OperandSize::Wide | OperandSize::Variable if rex_w => 8,
OperandSize::Variable if operand_size => 2,
OperandSize::Wide | OperandSize::Variable => 4,
};
let takes_operand_size =
matches!(form.size, OperandSize::Byte | OperandSize::Variable) || form.op == Op::Nop;
// REX.W takes precedence over 0x66 wherever the size is selectable.
let overridden = rex_w && form.size == OperandSize::Wide;
if operand_size && !takes_operand_size && !overridden {
return Err(DecodeError::Unsupported(0x66));
}
if form.no_rex_b && rex_b != 0 {
return Err(DecodeError::Unsupported(opcode));
}
let rm_size = if form.source != 0 { form.source } else { size };
let register = |field: u8, extension: u8, width: u8| {
if width == 1 && rex == 0 && field >= 4 {
RegOperand {
index: field - 4,
high: true,
}
} else {
RegOperand {
index: field | extension,
high: false,
}
}
};
let mut rm = None;
let mut rip_relative = false;
let mut reg = RegOperand {
index: 0,
high: false,
};
if form.has_modrm {
reg = register((modrm >> 3) & 7, rex_r, size);
let mode = modrm >> 6;
if mode == 3 {
if form.memory_only {
return Err(DecodeError::Unsupported(opcode));
}
rm = Some(RmOperand::Reg(register(modrm & 7, rex_b, rm_size)));
} else {
if form.register_only {
return Err(DecodeError::Unsupported(opcode));
}
let mut operand = MemOperand {
base: Some((modrm & 7) | rex_b),
index: None,
disp: 0,
segment,
};
let mut low_base = modrm & 7;
if low_base == 4 {
let sib = cursor.u8()?;
low_base = sib & 7;
operand.base = Some(low_base | rex_b);
// Index 100b means no index unless REX.X selects R12.
let index = ((sib >> 3) & 7) | rex_x;
operand.index = (index != 4).then_some((index, sib >> 6));
} else {
rip_relative = mode == 0 && low_base == 5;
}
if mode == 0 && low_base == 5 {
operand.base = None;
operand.disp = cursor.signed(4)? as i64;
} else if mode != 0 {
operand.disp = cursor.signed(if mode == 1 { 1 } else { 4 })? as i64;
}
rm = Some(RmOperand::Mem(operand));
}
} else if matches!(form.encoding, Encoding::OpReg | Encoding::OpRegImm) {
reg = register(opcode & 7, rex_b, size);
}
let mut imm = match form.immediate {
Immediate::None => 0,
Immediate::SignedByte => cursor.signed(1)?,
Immediate::SignedFull => cursor.signed(usize::from(size.min(4)))?,
Immediate::Signed32 => cursor.signed(4)?,
Immediate::Full => cursor.bytes(usize::from(size))?,
Immediate::Word => cursor.bytes(2)?,
Immediate::Byte => cursor.bytes(1)?,
};
let end = rip.wrapping_add(cursor.len as u64);
if rip_relative && let Some(RmOperand::Mem(operand)) = &mut rm {
operand.disp = end.wrapping_add_signed(operand.disp) as i64;
}
if form.encoding == Encoding::Rel {
imm = end.wrapping_add(imm);
}
if form.encoding == Encoding::AccImm {
reg = RegOperand {
index: 0,
high: false,
};
}
Ok(Insn {
op: form.op,
encoding: form.encoding,
form: form_index,
rip,
len: cursor.len as u8,
size,
rm_size,
rm,
reg,
imm,
condition: opcode & 0xF,
})
}
#[cfg(test)]
mod tests {
use super::{MAX_INSTRUCTION_LEN, segment_prefix_len};
#[test]
fn segment_prefix_len_counts_legacy_segment_prefixes() {
assert_eq!(segment_prefix_len(&[]), 0);
assert_eq!(segment_prefix_len(&[0x90]), 0);
assert_eq!(segment_prefix_len(&[0x65, 0x90]), 1);
assert_eq!(segment_prefix_len(&[0x64, 0x65, 0x31, 0xc0]), 2);
assert_eq!(segment_prefix_len(&[0x65; 20]), MAX_INSTRUCTION_LEN);
assert_eq!(segment_prefix_len(&[0x65; 15]), MAX_INSTRUCTION_LEN);
}
}
+621
View File
@@ -0,0 +1,621 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Reviewed semantic primitives for decoded x86-64 integer instructions.
//!
//! The interpreter executes every instruction here. The native DBT calls the
//! same code, counted explicitly, for forms it does not lower to ARM64.
//!
//! Every instruction is all-or-nothing: operands are read and results computed
//! first, then memory is written, then registers and flags, so a fault leaves
//! the state unchanged. Flags that the architecture leaves undefined keep their
//! previous value, which is permitted but not something guests may rely on.
use crate::cpu::{CpuState, ExitReason, RFlags, Register};
use crate::memory::GuestMemory;
use crate::x86_decode::{Encoding, Insn, MemOperand, RegOperand, RmOperand, Segment};
use crate::x86_simd;
use crate::x86_table::Op;
const RAX: usize = Register::Rax as usize;
const RCX: usize = Register::Rcx as usize;
const RDX: usize = Register::Rdx as usize;
const RSP: usize = Register::Rsp as usize;
const RBP: usize = Register::Rbp as usize;
/// Value mask of an operand of `size` bytes.
fn mask(size: u8) -> u64 {
u64::MAX >> (64 - 8 * u32::from(size))
}
fn sign_bit(size: u8) -> u64 {
1 << (8 * u32::from(size) - 1)
}
fn sign_extend(value: u64, size: u8) -> u64 {
let shift = 64 - 8 * u32::from(size);
((value << shift) as i64 >> shift) as u64
}
/// Effective address including any FS or GS base.
pub fn address(cpu: &CpuState, operand: &MemOperand) -> u64 {
let base = match operand.segment {
Some(Segment::Fs) => cpu.fs_base,
Some(Segment::Gs) => cpu.gs_base,
None => 0,
};
base.wrapping_add(offset(cpu, operand))
}
/// Effective address without a segment base, as LEA computes it.
fn offset(cpu: &CpuState, operand: &MemOperand) -> u64 {
let base = operand.base.map_or(0, |index| cpu.gpr[usize::from(index)]);
let index = operand
.index
.map_or(0, |(index, scale)| cpu.gpr[usize::from(index)] << scale);
base.wrapping_add(index).wrapping_add_signed(operand.disp)
}
pub(crate) fn read_reg(cpu: &CpuState, reg: RegOperand, size: u8) -> u64 {
let value = cpu.gpr[usize::from(reg.index)];
if reg.high {
(value >> 8) & 0xFF
} else {
value & mask(size)
}
}
/// Write a register: 8- and 16-bit writes merge, 32-bit writes zero-extend.
pub(crate) fn write_reg(cpu: &mut CpuState, reg: RegOperand, size: u8, value: u64) {
let slot = &mut cpu.gpr[usize::from(reg.index)];
*slot = match (size, reg.high) {
(1, true) => (*slot & !0xFF00) | ((value & 0xFF) << 8),
(1 | 2, _) => (*slot & !mask(size)) | (value & mask(size)),
_ => value & mask(size),
};
}
pub(crate) fn read_mem(memory: &GuestMemory, address: u64, size: u8) -> Result<u64, ExitReason> {
match size {
1 => memory.read_u8(address).map(u64::from),
2 => memory.read_u16(address).map(u64::from),
4 => memory.read_u32(address).map(u64::from),
_ => memory.read_u64(address),
}
.map_err(ExitReason::MemoryFault)
}
pub(crate) fn write_mem(
memory: &mut GuestMemory,
address: u64,
size: u8,
value: u64,
) -> Result<(), ExitReason> {
match size {
1 => memory.write_u8(address, value as u8),
2 => memory.write_u16(address, value as u16),
4 => memory.write_u32(address, value as u32),
_ => memory.write_u64(address, value),
}
.map_err(ExitReason::MemoryFault)
}
pub(crate) fn rm_operand(insn: &Insn) -> Result<RmOperand, ExitReason> {
// The decoder supplies a ModRM operand for every form that reaches here.
insn.rm.ok_or(ExitReason::IllegalInstruction(0))
}
fn read_rm(cpu: &CpuState, memory: &GuestMemory, insn: &Insn) -> Result<u64, ExitReason> {
match rm_operand(insn)? {
RmOperand::Reg(reg) => Ok(read_reg(cpu, reg, insn.rm_size)),
RmOperand::Mem(operand) => read_mem(memory, address(cpu, &operand), insn.rm_size),
}
}
fn write_rm(
cpu: &mut CpuState,
memory: &mut GuestMemory,
insn: &Insn,
value: u64,
) -> Result<(), ExitReason> {
match rm_operand(insn)? {
RmOperand::Reg(reg) => write_reg(cpu, reg, insn.rm_size, value),
RmOperand::Mem(operand) => {
write_mem(memory, address(cpu, &operand), insn.rm_size, value)?;
}
}
Ok(())
}
/// First (destination) and second operand values of a two-operand form.
fn operands(cpu: &CpuState, memory: &GuestMemory, insn: &Insn) -> Result<(u64, u64), ExitReason> {
let imm = insn.imm & mask(insn.size);
Ok(match insn.encoding {
Encoding::RmReg => (
read_rm(cpu, memory, insn)?,
read_reg(cpu, insn.reg, insn.size),
),
Encoding::RegRm => (
read_reg(cpu, insn.reg, insn.size),
read_rm(cpu, memory, insn)?,
),
Encoding::RmImm => (read_rm(cpu, memory, insn)?, imm),
Encoding::RmOne => (read_rm(cpu, memory, insn)?, 1),
Encoding::RmCl => (read_rm(cpu, memory, insn)?, cpu.gpr[RCX] & 0xFF),
Encoding::RegRmImm => (read_rm(cpu, memory, insn)?, imm),
Encoding::AccImm => (cpu.gpr[RAX] & mask(insn.size), imm),
_ => (read_rm(cpu, memory, insn)?, 0),
})
}
/// Store a result in the destination that [`operands`] read first.
fn write_dst(
cpu: &mut CpuState,
memory: &mut GuestMemory,
insn: &Insn,
value: u64,
) -> Result<(), ExitReason> {
match insn.encoding {
Encoding::RegRm | Encoding::RegRmImm | Encoding::AccImm => {
write_reg(cpu, insn.reg, insn.size, value);
Ok(())
}
_ => write_rm(cpu, memory, insn, value),
}
}
/// ZF, SF and PF of a result.
fn result_flags(flags: &mut RFlags, value: u64, size: u8) {
flags.zf = value & mask(size) == 0;
flags.sf = value & sign_bit(size) != 0;
flags.pf = (value as u8).count_ones().is_multiple_of(2);
}
/// `a + b + carry` with every arithmetic flag.
fn add(a: u64, b: u64, carry: bool, size: u8) -> (u64, RFlags) {
let wide = u128::from(a) + u128::from(b) + u128::from(carry);
let value = wide as u64 & mask(size);
let mut flags = RFlags {
cf: wide > u128::from(mask(size)),
of: (a ^ value) & (b ^ value) & sign_bit(size) != 0,
af: (a ^ b ^ value) & 0x10 != 0,
..RFlags::default()
};
result_flags(&mut flags, value, size);
(value, flags)
}
/// `a - b - borrow` with every arithmetic flag.
fn sub(a: u64, b: u64, borrow: bool, size: u8) -> (u64, RFlags) {
let value = a.wrapping_sub(b).wrapping_sub(u64::from(borrow)) & mask(size);
let mut flags = RFlags {
cf: u128::from(a) < u128::from(b) + u128::from(borrow),
of: (a ^ b) & (a ^ value) & sign_bit(size) != 0,
af: (a ^ b ^ value) & 0x10 != 0,
..RFlags::default()
};
result_flags(&mut flags, value, size);
(value, flags)
}
/// Evaluate an x86 condition code (Intel SDM Vol. 1, appendix B).
pub fn condition(flags: &RFlags, code: u8) -> bool {
let holds = match code >> 1 {
0 => flags.of,
1 => flags.cf,
2 => flags.zf,
3 => flags.cf || flags.zf,
4 => flags.sf,
5 => flags.pf,
6 => flags.sf != flags.of,
_ => flags.zf || flags.sf != flags.of,
};
holds != (code & 1 != 0)
}
/// Shifts and rotates. `None` means a masked count of zero, which changes
/// neither the destination nor the flags.
fn shift(op: Op, value: u64, count: u64, size: u8, old: RFlags) -> Option<(u64, RFlags)> {
let count = (count & if size == 8 { 0x3F } else { 0x1F }) as u32;
if count == 0 {
return None;
}
let bits = 8 * u32::from(size);
let top = sign_bit(size);
let mut flags = old;
let wide = u128::from(value);
let result = match op {
Op::Shl => {
let shifted = wide << count;
flags.cf = shifted >> bits & 1 != 0;
shifted as u64
}
Op::Shr => {
flags.cf = wide >> (count - 1) & 1 != 0;
(wide >> count) as u64
}
Op::Sar => {
let signed = i128::from(sign_extend(value, size) as i64);
flags.cf = signed >> (count - 1) & 1 != 0;
(signed >> count) as u64
}
_ => {
let by = count % bits;
let left = if op == Op::Rol {
by
} else {
(bits - by) % bits
};
let rotated = if left == 0 {
value
} else {
value << left | value >> (bits - left)
};
flags.cf = rotated & if op == Op::Rol { 1 } else { top } != 0;
rotated
}
} & mask(size);
if matches!(op, Op::Shl | Op::Shr | Op::Sar) {
result_flags(&mut flags, result, size);
// CF after a left or logical right shift by the width or more is
// undefined for 8- and 16-bit operands; keep the previous value.
if count >= bits && op != Op::Sar {
flags.cf = old.cf;
}
}
// OF is defined only for a count of one.
if count == 1 {
flags.of = match op {
Op::Shl | Op::Rol => (result & top != 0) != flags.cf,
Op::Shr => value & top != 0,
Op::Sar => false,
_ => (result & top != 0) != (result & (top >> 1) != 0),
};
}
Some((result, flags))
}
fn push(cpu: &mut CpuState, memory: &mut GuestMemory, value: u64) -> Result<(), ExitReason> {
let sp = cpu.gpr[RSP]
.checked_sub(8)
.ok_or(ExitReason::StackUnderflow)?;
write_mem(memory, sp, 8, value)?;
cpu.gpr[RSP] = sp;
Ok(())
}
/// Execute one decoded instruction, advancing RIP. On error nothing changes.
/// Returns an exit reason when the guest stops voluntarily.
pub fn execute(
cpu: &mut CpuState,
memory: &mut GuestMemory,
insn: &Insn,
) -> Result<Option<ExitReason>, ExitReason> {
let size = insn.size;
let mut next = insn.next_rip();
match insn.op {
Op::Add | Op::Adc | Op::Sub | Op::Sbb | Op::Cmp => {
let (a, b) = operands(cpu, memory, insn)?;
let carry = cpu.flags.cf;
let (value, flags) = match insn.op {
Op::Add => add(a, b, false, size),
Op::Adc => add(a, b, carry, size),
Op::Sbb => sub(a, b, carry, size),
_ => sub(a, b, false, size),
};
if insn.op != Op::Cmp {
write_dst(cpu, memory, insn, value)?;
}
cpu.flags = flags;
}
Op::And | Op::Or | Op::Xor | Op::Test => {
let (a, b) = operands(cpu, memory, insn)?;
let value = match insn.op {
Op::Or => a | b,
Op::Xor => a ^ b,
_ => a & b,
};
if insn.op != Op::Test {
write_dst(cpu, memory, insn, value)?;
}
cpu.flags.cf = false;
cpu.flags.of = false;
result_flags(&mut cpu.flags, value, size);
}
Op::Inc | Op::Dec => {
let a = read_rm(cpu, memory, insn)?;
let (value, mut flags) = if insn.op == Op::Inc {
add(a, 1, false, size)
} else {
sub(a, 1, false, size)
};
write_rm(cpu, memory, insn, value)?;
flags.cf = cpu.flags.cf;
cpu.flags = flags;
}
Op::Neg => {
let a = read_rm(cpu, memory, insn)?;
let (value, flags) = sub(0, a, false, size);
write_rm(cpu, memory, insn, value)?;
cpu.flags = flags;
}
Op::Not => {
let a = read_rm(cpu, memory, insn)?;
write_rm(cpu, memory, insn, !a & mask(size))?;
}
Op::Mov => match insn.encoding {
Encoding::RmReg => write_rm(cpu, memory, insn, read_reg(cpu, insn.reg, size))?,
Encoding::RegRm => {
let value = read_rm(cpu, memory, insn)?;
write_reg(cpu, insn.reg, size, value);
}
Encoding::OpRegImm => write_reg(cpu, insn.reg, size, insn.imm),
_ => write_rm(cpu, memory, insn, insn.imm & mask(size))?,
},
Op::Movzx => {
let value = read_rm(cpu, memory, insn)?;
write_reg(cpu, insn.reg, size, value);
}
Op::Movsx | Op::Movsxd => {
let value = sign_extend(read_rm(cpu, memory, insn)?, insn.rm_size);
write_reg(cpu, insn.reg, size, value);
}
Op::Lea => {
if let Some(operand) = insn.memory() {
write_reg(cpu, insn.reg, size, offset(cpu, &operand));
}
}
Op::Xchg => {
let (a, b) = operands(cpu, memory, insn)?;
write_rm(cpu, memory, insn, b)?;
write_reg(cpu, insn.reg, size, a);
}
Op::Bswap => {
let value = read_reg(cpu, insn.reg, size).swap_bytes() >> (64 - 8 * u32::from(size));
write_reg(cpu, insn.reg, size, value);
}
Op::Cwde => {
// CBW, CWDE and CDQE widen the lower half of the accumulator.
let value = sign_extend(cpu.gpr[RAX] & mask(size / 2), size / 2);
write_reg(cpu, accumulator(RAX), size, value);
}
Op::Cdq => {
let negative = cpu.gpr[RAX] & sign_bit(size) != 0;
write_reg(
cpu,
accumulator(RDX),
size,
if negative { mask(size) } else { 0 },
);
}
Op::Rol | Op::Ror | Op::Shl | Op::Shr | Op::Sar => {
let (a, count) = operands(cpu, memory, insn)?;
match shift(insn.op, a, count, size, cpu.flags) {
Some((value, flags)) => {
write_rm(cpu, memory, insn, value)?;
cpu.flags = flags;
}
// A zero count still performs the write's permission check and
// the 32-bit register zero-extension.
None => write_rm(cpu, memory, insn, a)?,
}
}
Op::Mul | Op::Imul => {
let factor = read_rm(cpu, memory, insn)?;
let acc = cpu.gpr[RAX] & mask(size);
let bits = 8 * u32::from(size);
let product = if insn.op == Op::Mul {
u128::from(acc) * u128::from(factor)
} else {
(i128::from(sign_extend(acc, size) as i64)
* i128::from(sign_extend(factor, size) as i64)) as u128
};
let low = product as u64 & mask(size);
let high = (product >> bits) as u64 & mask(size);
if size == 1 {
write_reg(cpu, accumulator(RAX), 2, high << 8 | low);
} else {
write_reg(cpu, accumulator(RAX), size, low);
write_reg(cpu, accumulator(RDX), size, high);
}
let overflow = if insn.op == Op::Mul {
high != 0
} else {
high != if low & sign_bit(size) != 0 {
mask(size)
} else {
0
}
};
cpu.flags.cf = overflow;
cpu.flags.of = overflow;
}
Op::Imul2 => {
let (a, b) = operands(cpu, memory, insn)?;
let product =
i128::from(sign_extend(a, size) as i64) * i128::from(sign_extend(b, size) as i64);
let value = product as u64 & mask(size);
write_reg(cpu, insn.reg, size, value);
let overflow = i128::from(sign_extend(value, size) as i64) != product;
cpu.flags.cf = overflow;
cpu.flags.of = overflow;
}
Op::Div | Op::Idiv => divide(cpu, memory, insn)?,
Op::Cmov => {
// The source is read, and may fault, whatever the condition.
let source = read_rm(cpu, memory, insn)?;
let value = if condition(&cpu.flags, insn.condition) {
source
} else {
read_reg(cpu, insn.reg, size)
};
write_reg(cpu, insn.reg, size, value);
}
Op::Setcc => {
let value = u64::from(condition(&cpu.flags, insn.condition));
write_rm(cpu, memory, insn, value)?;
}
Op::Bt | Op::Bts | Op::Btr | Op::Btc => {
let (a, index) = operands(cpu, memory, insn)?;
let bit = 1u64 << (index & (8 * u64::from(size) - 1));
let value = match insn.op {
Op::Bts => a | bit,
Op::Btr => a & !bit,
Op::Btc => a ^ bit,
_ => a,
};
if insn.op != Op::Bt {
write_rm(cpu, memory, insn, value)?;
}
cpu.flags.cf = a & bit != 0;
}
Op::Bsf | Op::Bsr => {
let value = read_rm(cpu, memory, insn)?;
cpu.flags.zf = value == 0;
// A zero source leaves the destination undefined (SDM) or unchanged
// (APM); leave it unchanged.
if value != 0 {
let index = if insn.op == Op::Bsf {
value.trailing_zeros()
} else {
63 - value.leading_zeros()
};
write_reg(cpu, insn.reg, size, u64::from(index));
}
}
Op::Popcnt => {
let value = read_rm(cpu, memory, insn)?;
write_reg(cpu, insn.reg, size, u64::from(value.count_ones()));
cpu.flags = RFlags {
zf: value == 0,
..RFlags::default()
};
}
Op::Tzcnt | Op::Lzcnt => {
let value = read_rm(cpu, memory, insn)?;
let bits = 8 * u32::from(size);
let count = if insn.op == Op::Tzcnt {
value.trailing_zeros().min(bits)
} else {
value.leading_zeros() - (64 - bits)
};
write_reg(cpu, insn.reg, size, u64::from(count));
cpu.flags.cf = value == 0;
cpu.flags.zf = count == 0;
}
Op::Push => {
let value = match insn.encoding {
Encoding::OpReg => read_reg(cpu, insn.reg, 8),
Encoding::Imm => insn.imm,
_ => read_rm(cpu, memory, insn)?,
};
push(cpu, memory, value)?;
}
Op::Pop => {
let old = cpu.gpr[RSP];
let value = read_mem(memory, old, 8)?;
// A memory destination based on RSP uses the incremented value.
cpu.gpr[RSP] = old.wrapping_add(8);
if insn.encoding == Encoding::OpReg {
write_reg(cpu, insn.reg, 8, value);
} else if let Err(fault) = write_rm(cpu, memory, insn, value) {
cpu.gpr[RSP] = old;
return Err(fault);
}
}
Op::Leave => {
let frame = cpu.gpr[RBP];
cpu.gpr[RBP] = read_mem(memory, frame, 8)?;
cpu.gpr[RSP] = frame.wrapping_add(8);
}
Op::Call => {
let target = branch_target(cpu, memory, insn)?;
push(cpu, memory, next)?;
next = target;
}
Op::Jmp => next = branch_target(cpu, memory, insn)?,
Op::Jcc => {
if condition(&cpu.flags, insn.condition) {
next = insn.imm;
}
}
Op::Ret => {
let sp = cpu.gpr[RSP];
next = read_mem(memory, sp, 8)?;
cpu.gpr[RSP] = sp.wrapping_add(8).wrapping_add(insn.imm);
}
Op::Nop => {}
Op::Clc => cpu.flags.cf = false,
Op::Stc => cpu.flags.cf = true,
Op::Cmc => cpu.flags.cf = !cpu.flags.cf,
Op::Hlt => {
cpu.rip = next;
return Ok(Some(ExitReason::Halt));
}
Op::Syscall => {
cpu.rip = next;
return Ok(Some(ExitReason::Syscall(cpu.gpr[RAX])));
}
_ => x86_simd::execute(cpu, memory, insn)?,
}
cpu.rip = next;
Ok(None)
}
fn accumulator(index: usize) -> RegOperand {
RegOperand {
index: index as u8,
high: false,
}
}
fn branch_target(cpu: &CpuState, memory: &GuestMemory, insn: &Insn) -> Result<u64, ExitReason> {
if insn.encoding == Encoding::Rel {
Ok(insn.imm)
} else {
read_rm(cpu, memory, insn)
}
}
/// DIV and IDIV. A zero divisor or a quotient that does not fit raises #DE.
fn divide(cpu: &mut CpuState, memory: &GuestMemory, insn: &Insn) -> Result<(), ExitReason> {
let size = insn.size;
let divisor = read_rm(cpu, memory, insn)?;
if divisor == 0 {
return Err(ExitReason::DivideError);
}
let bits = 8 * u32::from(size);
let dividend = if size == 1 {
u128::from(cpu.gpr[RAX] & 0xFFFF)
} else {
u128::from(cpu.gpr[RDX] & mask(size)) << bits | u128::from(cpu.gpr[RAX] & mask(size))
};
let (quotient, remainder) = if insn.op == Op::Div {
let divisor = u128::from(divisor);
let quotient = dividend / divisor;
if quotient > u128::from(mask(size)) {
return Err(ExitReason::DivideError);
}
(quotient as u64, (dividend % divisor) as u64)
} else {
let unused = 128 - 2 * bits;
let dividend = (dividend << unused) as i128 >> unused;
let divisor = i128::from(sign_extend(divisor, size) as i64);
// Only i128::MIN / -1 overflows i128, and it overflows #DE too.
let quotient = dividend
.checked_div(divisor)
.ok_or(ExitReason::DivideError)?;
let limit = i128::from(sign_bit(size));
if quotient < -limit || quotient >= limit {
return Err(ExitReason::DivideError);
}
(quotient as u64, (dividend % divisor) as u64)
};
if size == 1 {
let value = (remainder & 0xFF) << 8 | quotient & 0xFF;
write_reg(cpu, accumulator(RAX), 2, value);
} else {
write_reg(cpu, accumulator(RAX), size, quotient);
write_reg(cpu, accumulator(RDX), size, remainder);
}
Ok(())
}
+247
View File
@@ -0,0 +1,247 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! SSE and SSE2 floating-point instructions over [`crate::softfloat`].
//!
//! Exceptions accumulate in MXCSR. If any is unmasked the instruction has no
//! other effect and exits with [`ExitReason::SimdException`]; pre-computation
//! exceptions in any lane are considered before post-computation ones.
use crate::cpu::{CpuState, ExitReason, RFlags};
use crate::memory::GuestMemory;
use crate::softfloat::{
Arithmetic, Control, F32, F64, Format, Outcome, PRE_COMPUTATION, arithmetic, compare, convert,
from_integer, square_root, to_integer,
};
use crate::x86_decode::{Insn, RmOperand};
use crate::x86_exec::{address, read_mem, read_reg, rm_operand, write_reg};
use crate::x86_simd::{lane, read_rm};
use crate::x86_table::Op;
use std::cmp::Ordering;
/// Exception flags collected over the lanes of one instruction.
#[derive(Default)]
struct Raised(u32);
impl Raised {
fn take(&mut self, outcome: Outcome) -> u64 {
self.0 |= outcome.flags;
outcome.bits
}
/// Record the flags in MXCSR, failing if an unmasked one was raised.
fn commit(&self, cpu: &mut CpuState) -> Result<(), ExitReason> {
let masks = cpu.mxcsr.0 >> 7 & 0x3F;
let before = self.0 & PRE_COMPUTATION;
if before & !masks != 0 {
cpu.mxcsr.0 |= before;
return Err(ExitReason::SimdException);
}
cpu.mxcsr.0 |= self.0;
if self.0 & !masks != 0 {
return Err(ExitReason::SimdException);
}
Ok(())
}
}
#[derive(Clone, Copy)]
enum Kind {
Arithmetic(Arithmetic),
SquareRoot,
Compare,
}
/// Operation, format and whether only the low lane is involved.
fn classify(op: Op) -> Option<(Kind, Format, bool)> {
use Arithmetic::{Add, Div, Max, Min, Mul, Sub};
use Kind::{Arithmetic as A, Compare, SquareRoot};
Some(match op {
Op::Addps => (A(Add), F32, false),
Op::Addpd => (A(Add), F64, false),
Op::Addss => (A(Add), F32, true),
Op::Addsd => (A(Add), F64, true),
Op::Subps => (A(Sub), F32, false),
Op::Subpd => (A(Sub), F64, false),
Op::Subss => (A(Sub), F32, true),
Op::Subsd => (A(Sub), F64, true),
Op::Mulps => (A(Mul), F32, false),
Op::Mulpd => (A(Mul), F64, false),
Op::Mulss => (A(Mul), F32, true),
Op::Mulsd => (A(Mul), F64, true),
Op::Divps => (A(Div), F32, false),
Op::Divpd => (A(Div), F64, false),
Op::Divss => (A(Div), F32, true),
Op::Divsd => (A(Div), F64, true),
Op::Minps => (A(Min), F32, false),
Op::Minpd => (A(Min), F64, false),
Op::Minss => (A(Min), F32, true),
Op::Minsd => (A(Min), F64, true),
Op::Maxps => (A(Max), F32, false),
Op::Maxpd => (A(Max), F64, false),
Op::Maxss => (A(Max), F32, true),
Op::Maxsd => (A(Max), F64, true),
Op::Sqrtps => (SquareRoot, F32, false),
Op::Sqrtpd => (SquareRoot, F64, false),
Op::Sqrtss => (SquareRoot, F32, true),
Op::Sqrtsd => (SquareRoot, F64, true),
Op::Cmpps => (Compare, F32, false),
Op::Cmppd => (Compare, F64, false),
Op::Cmpss => (Compare, F32, true),
Op::Cmpsd => (Compare, F64, true),
_ => return None,
})
}
/// Source format, destination format and lane count of a vector conversion;
/// `None` for an integer side.
fn conversion(op: Op) -> Option<(Option<Format>, Option<Format>, u32)> {
Some(match op {
Op::Cvtps2pd => (Some(F32), Some(F64), 2),
Op::Cvtpd2ps => (Some(F64), Some(F32), 2),
Op::Cvtss2sd => (Some(F32), Some(F64), 1),
Op::Cvtsd2ss => (Some(F64), Some(F32), 1),
Op::Cvtdq2ps => (None, Some(F32), 4),
Op::Cvtdq2pd => (None, Some(F64), 2),
Op::Cvtps2dq | Op::Cvttps2dq => (Some(F32), None, 4),
Op::Cvtpd2dq | Op::Cvttpd2dq => (Some(F64), None, 2),
_ => return None,
})
}
/// CMPccPS predicate: a relation, optionally negated. Bit 2 negates; LT and LE
/// and their negations signal on quiet NaNs.
fn predicate(format: Format, a: u64, b: u64, code: u64, control: &Control) -> Outcome {
let relation = code & 3;
let signaling = matches!(relation, 1 | 2);
let (order, flags) = compare(format, a, b, signaling, control);
let holds = match relation {
0 => order == Some(Ordering::Equal),
1 => order == Some(Ordering::Less),
2 => matches!(order, Some(Ordering::Less | Ordering::Equal)),
_ => order.is_none(),
};
Outcome {
bits: if holds != (code & 4 != 0) {
u64::MAX
} else {
0
},
flags,
}
}
fn low_bits(bits: u32) -> u128 {
(1 << bits) - 1
}
/// Place `value` in lane `index` of `bits`.
fn insert(target: &mut u128, value: u64, bits: u32, index: u32) {
let shift = bits * index;
let mask = low_bits(bits) << shift;
*target = (*target & !mask) | ((u128::from(value) << shift) & mask);
}
/// Execute a floating-point instruction, or return `false` if it is not one.
pub(crate) fn execute(
cpu: &mut CpuState,
memory: &GuestMemory,
insn: &Insn,
) -> Result<bool, ExitReason> {
let control = Control::from_mxcsr(cpu.mxcsr.0);
let reg = usize::from(insn.reg.index);
let mut raised = Raised::default();
if let Some((kind, format, scalar)) = classify(insn.op) {
let source = read_rm(cpu, memory, insn)?;
let old = cpu.xmm[reg];
let mut result = old;
let count = if scalar { 1 } else { 128 / format.bits };
for index in 0..count {
let a = lane(old, format.bits, index);
let b = lane(source, format.bits, index);
let outcome = match kind {
Kind::Arithmetic(kind) => arithmetic(kind, format, a, b, &control),
Kind::SquareRoot => square_root(format, b, &control),
// Legacy encodings define only predicates 0-7.
Kind::Compare => predicate(format, a, b, insn.imm & 7, &control),
};
insert(&mut result, raised.take(outcome), format.bits, index);
}
raised.commit(cpu)?;
cpu.xmm[reg] = result;
return Ok(true);
}
if let Some((from, to, count)) = conversion(insn.op) {
let source = read_rm(cpu, memory, insn)?;
let truncate = matches!(insn.op, Op::Cvttps2dq | Op::Cvttpd2dq);
let merges = matches!(insn.op, Op::Cvtss2sd | Op::Cvtsd2ss);
let mut result = if merges { cpu.xmm[reg] } else { 0 };
for index in 0..count {
let value = lane(source, from.map_or(32, |format| format.bits), index);
let outcome = match (from, to) {
(Some(from), Some(to)) => convert(from, to, value, &control),
(None, Some(to)) => from_integer(to, i64::from(value as u32 as i32), &control),
(Some(from), None) => to_integer(from, value, 32, truncate, &control),
(None, None) => Outcome { bits: 0, flags: 0 },
};
let width = to.map_or(32, |format| format.bits);
insert(&mut result, raised.take(outcome), width, index);
}
raised.commit(cpu)?;
cpu.xmm[reg] = result;
return Ok(true);
}
match insn.op {
Op::Cvtsi2ss | Op::Cvtsi2sd => {
let value = match rm_operand(insn)? {
RmOperand::Reg(source) => read_reg(cpu, source, insn.size),
RmOperand::Mem(operand) => read_mem(memory, address(cpu, &operand), insn.size)?,
};
let integer = if insn.size == 8 {
value as i64
} else {
i64::from(value as u32 as i32)
};
let format = if insn.op == Op::Cvtsi2ss { F32 } else { F64 };
let bits = raised.take(from_integer(format, integer, &control));
raised.commit(cpu)?;
insert(&mut cpu.xmm[reg], bits, format.bits, 0);
}
Op::Cvtss2si | Op::Cvttss2si | Op::Cvtsd2si | Op::Cvttsd2si => {
let format = if matches!(insn.op, Op::Cvtss2si | Op::Cvttss2si) {
F32
} else {
F64
};
let truncate = matches!(insn.op, Op::Cvttss2si | Op::Cvttsd2si);
let value = lane(read_rm(cpu, memory, insn)?, format.bits, 0);
let bits = 8 * u32::from(insn.size);
let integer = raised.take(to_integer(format, value, bits, truncate, &control));
raised.commit(cpu)?;
write_reg(cpu, insn.reg, insn.size, integer);
}
Op::Comiss | Op::Comisd | Op::Ucomiss | Op::Ucomisd => {
let format = if matches!(insn.op, Op::Comiss | Op::Ucomiss) {
F32
} else {
F64
};
let signaling = matches!(insn.op, Op::Comiss | Op::Comisd);
let a = lane(cpu.xmm[reg], format.bits, 0);
let b = lane(read_rm(cpu, memory, insn)?, format.bits, 0);
let (order, flags) = compare(format, a, b, signaling, &control);
raised.0 |= flags;
raised.commit(cpu)?;
cpu.flags = RFlags {
zf: matches!(order, None | Some(Ordering::Equal)),
pf: order.is_none(),
cf: matches!(order, None | Some(Ordering::Less)),
..RFlags::default()
};
}
_ => return Ok(false),
}
Ok(true)
}
+395
View File
@@ -0,0 +1,395 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Semantic primitives for the SSE and SSE2 moves and packed integer forms.
//!
//! Lane 0 is the least significant. Every instruction is all-or-nothing and none
//! changes RFLAGS. Floating-point arithmetic is in [`crate::x86_float`].
use crate::cpu::{CpuState, ExitReason, Mxcsr};
use crate::memory::GuestMemory;
use crate::x86_decode::{Encoding, Insn, RegOperand, RmOperand};
use crate::x86_exec::{address, read_mem, read_reg, rm_operand, write_mem, write_reg};
use crate::x86_float;
use crate::x86_table::{FORMS, Op};
fn lane_mask(bits: u32) -> u128 {
(1 << bits) - 1
}
pub(crate) fn lane(value: u128, bits: u32, index: u32) -> u64 {
((value >> (bits * index)) & lane_mask(bits)) as u64
}
/// Signed value of a lane of `bits`.
fn signed(value: u64, bits: u32) -> i64 {
(value << (64 - bits)) as i64 >> (64 - bits)
}
/// Build a vector from a function of the lane index.
fn build(bits: u32, f: impl Fn(u32) -> u64) -> u128 {
(0..128 / bits).fold(0, |out, index| {
out | (u128::from(f(index)) & lane_mask(bits)) << (bits * index)
})
}
fn map(a: u128, b: u128, bits: u32, f: impl Fn(u64, u64) -> u64) -> u128 {
build(bits, |index| f(lane(a, bits, index), lane(b, bits, index)))
}
fn map_signed(a: u128, b: u128, bits: u32, f: impl Fn(i64, i64) -> i64) -> u128 {
map(a, b, bits, |x, y| {
f(signed(x, bits), signed(y, bits)) as u64
})
}
fn all_ones(condition: bool) -> u64 {
if condition { u64::MAX } else { 0 }
}
/// Clamp to the signed range of `bits`.
fn saturate(value: i64, bits: u32) -> i64 {
let limit = 1i64 << (bits - 1);
value.clamp(-limit, limit - 1)
}
/// Clamp to the unsigned range of `bits`.
fn saturate_unsigned(value: i64, bits: u32) -> i64 {
value.clamp(0, (1 << bits) - 1)
}
/// Narrow the lanes of `a` then `b`, each `bits` wide, to half width.
fn pack(a: u128, b: u128, bits: u32, narrow: impl Fn(i64, u32) -> i64) -> u128 {
let count = 128 / bits;
build(bits / 2, |index| {
let source = if index < count { a } else { b };
narrow(signed(lane(source, bits, index % count), bits), bits / 2) as u64
})
}
/// Interleave the low or high halves of `a` and `b`.
fn unpack(a: u128, b: u128, bits: u32, high: bool) -> u128 {
let start = if high { 64 / bits } else { 0 };
build(bits, |index| {
let source = if index % 2 == 0 { a } else { b };
lane(source, bits, start + index / 2)
})
}
/// Select lanes of `bits` by two-bit fields of `imm`, reading `a` for the low
/// half of the result and `b` for the high half.
fn shuffle_32(a: u128, b: u128, imm: u64) -> u128 {
build(32, |index| {
let source = if index < 2 { a } else { b };
lane(source, 32, (imm >> (2 * index) & 3) as u32)
})
}
/// Shuffle the four words starting at word `start`, keeping the other four.
fn shuffle_16(value: u128, imm: u64, start: u32) -> u128 {
build(16, |index| {
if (start..start + 4).contains(&index) {
lane(value, 16, start + (imm >> (2 * (index - start)) & 3) as u32)
} else {
lane(value, 16, index)
}
})
}
/// Logical or arithmetic shift of every lane; counts past the width give zero
/// or, for arithmetic shifts, copies of the sign.
fn shift(op: Op, value: u128, count: u64) -> u128 {
let (bits, kind) = match op {
Op::Psllw => (16, 0),
Op::Pslld => (32, 0),
Op::Psllq => (64, 0),
Op::Psrlw => (16, 1),
Op::Psrld => (32, 1),
Op::Psrlq => (64, 1),
Op::Psraw => (16, 2),
_ => (32, 2),
};
let over = count >= u64::from(bits);
map(value, 0, bits, |x, _| match kind {
0 if !over => x << count,
1 if !over => x >> count,
2 => (signed(x, bits) >> count.min(u64::from(bits) - 1)) as u64,
_ => 0,
})
}
fn shift_bytes(value: u128, count: u64, left: bool) -> u128 {
if count > 15 {
0
} else if left {
value << (8 * count)
} else {
value >> (8 * count)
}
}
/// Result of a two-source packed operation.
fn packed(op: Op, a: u128, b: u128) -> u128 {
match op {
Op::Pand => a & b,
Op::Pandn => !a & b,
Op::Por => a | b,
Op::Pxor => a ^ b,
Op::Paddb => map(a, b, 8, u64::wrapping_add),
Op::Paddw => map(a, b, 16, u64::wrapping_add),
Op::Paddd => map(a, b, 32, u64::wrapping_add),
Op::Paddq => map(a, b, 64, u64::wrapping_add),
Op::Psubb => map(a, b, 8, u64::wrapping_sub),
Op::Psubw => map(a, b, 16, u64::wrapping_sub),
Op::Psubd => map(a, b, 32, u64::wrapping_sub),
Op::Psubq => map(a, b, 64, u64::wrapping_sub),
Op::Paddsb => map_signed(a, b, 8, |x, y| saturate(x + y, 8)),
Op::Paddsw => map_signed(a, b, 16, |x, y| saturate(x + y, 16)),
Op::Psubsb => map_signed(a, b, 8, |x, y| saturate(x - y, 8)),
Op::Psubsw => map_signed(a, b, 16, |x, y| saturate(x - y, 16)),
Op::Paddusb => map(a, b, 8, |x, y| (x + y).min(0xFF)),
Op::Paddusw => map(a, b, 16, |x, y| (x + y).min(0xFFFF)),
Op::Psubusb => map(a, b, 8, u64::saturating_sub),
Op::Psubusw => map(a, b, 16, u64::saturating_sub),
Op::Pcmpeqb => map(a, b, 8, |x, y| all_ones(x == y)),
Op::Pcmpeqw => map(a, b, 16, |x, y| all_ones(x == y)),
Op::Pcmpeqd => map(a, b, 32, |x, y| all_ones(x == y)),
Op::Pcmpgtb => map_signed(a, b, 8, |x, y| all_ones(x > y) as i64),
Op::Pcmpgtw => map_signed(a, b, 16, |x, y| all_ones(x > y) as i64),
Op::Pcmpgtd => map_signed(a, b, 32, |x, y| all_ones(x > y) as i64),
Op::Pminub => map(a, b, 8, u64::min),
Op::Pmaxub => map(a, b, 8, u64::max),
Op::Pminsw => map_signed(a, b, 16, i64::min),
Op::Pmaxsw => map_signed(a, b, 16, i64::max),
Op::Pavgb => map(a, b, 8, |x, y| (x + y + 1) >> 1),
Op::Pavgw => map(a, b, 16, |x, y| (x + y + 1) >> 1),
Op::Pmullw => map(a, b, 16, u64::wrapping_mul),
Op::Pmulhw => map_signed(a, b, 16, |x, y| (x * y) >> 16),
Op::Pmulhuw => map(a, b, 16, |x, y| (x * y) >> 16),
Op::Pmuludq => map(a, b, 64, |x, y| (x & 0xFFFF_FFFF) * (y & 0xFFFF_FFFF)),
Op::Pmaddwd => build(32, |index| {
let product = |at| signed(lane(a, 16, at), 16) * signed(lane(b, 16, at), 16);
(product(2 * index) + product(2 * index + 1)) as u64
}),
Op::Psadbw => build(64, |half| {
(0..8)
.map(|at| lane(a, 8, 8 * half + at).abs_diff(lane(b, 8, 8 * half + at)))
.sum()
}),
Op::Packsswb => pack(a, b, 16, saturate),
Op::Packssdw => pack(a, b, 32, saturate),
Op::Packuswb => pack(a, b, 16, saturate_unsigned),
Op::Punpcklbw => unpack(a, b, 8, false),
Op::Punpcklwd => unpack(a, b, 16, false),
Op::Punpckldq => unpack(a, b, 32, false),
Op::Punpcklqdq => unpack(a, b, 64, false),
Op::Punpckhbw => unpack(a, b, 8, true),
Op::Punpckhwd => unpack(a, b, 16, true),
Op::Punpckhdq => unpack(a, b, 32, true),
Op::Punpckhqdq => unpack(a, b, 64, true),
// Vector counts are the low 64 bits of the source.
_ => shift(op, a, b as u64),
}
}
fn low_mask(size: u8) -> u128 {
if size == 16 {
u128::MAX
} else {
(1 << (8 * u32::from(size))) - 1
}
}
/// Address of the memory operand, checked for 16-byte alignment where required.
fn aligned_address(cpu: &CpuState, insn: &Insn) -> Result<Option<u64>, ExitReason> {
let Some(operand) = insn.memory() else {
return Ok(None);
};
let address = address(cpu, &operand);
let unaligned = FORMS[usize::from(insn.form)].unaligned;
if insn.rm_size == 16 && !unaligned && !address.is_multiple_of(16) {
return Err(ExitReason::GeneralProtection);
}
Ok(Some(address))
}
fn read_vector(memory: &GuestMemory, address: u64, size: u8) -> Result<u128, ExitReason> {
if size < 16 {
return read_mem(memory, address, size).map(u128::from);
}
let mut bytes = [0; 16];
memory
.read_bytes(address, &mut bytes)
.map_err(ExitReason::MemoryFault)?;
Ok(u128::from_le_bytes(bytes))
}
fn write_vector(
memory: &mut GuestMemory,
address: u64,
size: u8,
value: u128,
) -> Result<(), ExitReason> {
if size < 16 {
return write_mem(memory, address, size, value as u64);
}
memory
.write_bytes(address, &value.to_le_bytes())
.map_err(ExitReason::MemoryFault)
}
fn xmm(reg: RegOperand) -> usize {
usize::from(reg.index)
}
/// Full XMM register, or zero-extended memory, named by ModRM `rm`.
pub(crate) fn read_rm(
cpu: &CpuState,
memory: &GuestMemory,
insn: &Insn,
) -> Result<u128, ExitReason> {
match (aligned_address(cpu, insn)?, rm_operand(insn)?) {
(Some(address), _) => read_vector(memory, address, insn.rm_size),
(None, RmOperand::Reg(reg)) => Ok(cpu.xmm[xmm(reg)]),
(None, RmOperand::Mem(_)) => Err(ExitReason::IllegalInstruction(0)),
}
}
/// Execute a vector instruction. RIP is advanced by the caller.
pub(crate) fn execute(
cpu: &mut CpuState,
memory: &mut GuestMemory,
insn: &Insn,
) -> Result<(), ExitReason> {
if x86_float::execute(cpu, memory, insn)? {
return Ok(());
}
let reg = xmm(insn.reg);
let in_memory = insn.memory().is_some();
match (insn.op, insn.encoding) {
(Op::Ldmxcsr, _) => {
let value = read_rm(cpu, memory, insn)? as u32;
if value & !Mxcsr::WRITABLE != 0 {
return Err(ExitReason::GeneralProtection);
}
cpu.mxcsr = Mxcsr(value);
}
(Op::Stmxcsr, _) => {
if let Some(address) = aligned_address(cpu, insn)? {
write_mem(memory, address, 4, u64::from(cpu.mxcsr.0))?;
}
}
(Op::Movd, Encoding::XmmGpr) => {
let value = match rm_operand(insn)? {
RmOperand::Reg(source) => read_reg(cpu, source, insn.size),
RmOperand::Mem(operand) => read_mem(memory, address(cpu, &operand), insn.size)?,
};
cpu.xmm[reg] = u128::from(value);
}
(Op::Movd, _) => {
let value = cpu.xmm[reg] as u64;
match rm_operand(insn)? {
RmOperand::Reg(target) => write_reg(cpu, target, insn.size, value),
RmOperand::Mem(operand) => {
write_mem(memory, address(cpu, &operand), insn.size, value)?;
}
}
}
(Op::Pinsrw, _) => {
let value = match rm_operand(insn)? {
RmOperand::Reg(source) => read_reg(cpu, source, 2),
RmOperand::Mem(operand) => read_mem(memory, address(cpu, &operand), 2)?,
};
let shift = 16 * (insn.imm & 7);
cpu.xmm[reg] = cpu.xmm[reg] & !(0xFFFF << shift) | u128::from(value) << shift;
}
(Op::Pextrw, _) => {
let value = lane(read_rm(cpu, memory, insn)?, 16, (insn.imm & 7) as u32);
write_reg(cpu, insn.reg, insn.size, value);
}
(Op::Movmskps | Op::Movmskpd | Op::Pmovmskb, _) => {
let bits = match insn.op {
Op::Movmskps => 32,
Op::Movmskpd => 64,
_ => 8,
};
let value = read_rm(cpu, memory, insn)?;
let signs = (0..128 / bits).fold(0, |out, index| {
out | (lane(value, bits, index) >> (bits - 1)) << index
});
write_reg(cpu, insn.reg, insn.size, signs);
}
// MOVHLPS and MOVLHPS are the register forms of these opcodes.
(Op::Movlps, Encoding::XmmRm) => {
let source = read_rm(cpu, memory, insn)?;
let low = if in_memory { source } else { source >> 64 };
cpu.xmm[reg] = cpu.xmm[reg] & !low_mask(8) | low;
}
(Op::Movhps, Encoding::XmmRm) => {
let source = read_rm(cpu, memory, insn)?;
cpu.xmm[reg] = cpu.xmm[reg] & low_mask(8) | source << 64;
}
(Op::Movhps, _) => {
if let Some(address) = aligned_address(cpu, insn)? {
write_vector(memory, address, 8, cpu.xmm[reg] >> 64)?;
}
}
// Scalar loads from memory clear the rest of the register; between
// registers MOVSS and MOVSD merge and MOVQ clears.
(Op::Movss | Op::Movsd, Encoding::XmmRm) if !in_memory => {
let mask = low_mask(insn.rm_size);
let source = read_rm(cpu, memory, insn)?;
cpu.xmm[reg] = cpu.xmm[reg] & !mask | source & mask;
}
(
Op::Movaps | Op::Movups | Op::Movdqa | Op::Movdqu | Op::Movss | Op::Movsd | Op::Movq,
Encoding::XmmRm,
) => {
cpu.xmm[reg] = read_rm(cpu, memory, insn)? & low_mask(insn.rm_size);
}
(_, Encoding::RmXmm) => {
let mask = low_mask(insn.rm_size);
let value = cpu.xmm[reg] & mask;
match (aligned_address(cpu, insn)?, rm_operand(insn)?) {
(Some(address), _) => write_vector(memory, address, insn.rm_size, value)?,
(None, RmOperand::Reg(target)) => {
let target = &mut cpu.xmm[xmm(target)];
*target = match insn.op {
Op::Movq => value,
_ => *target & !mask | value,
};
}
(None, RmOperand::Mem(_)) => return Err(ExitReason::IllegalInstruction(0)),
}
}
(_, Encoding::RmImmXmm) => {
if let RmOperand::Reg(target) = rm_operand(insn)? {
let target = &mut cpu.xmm[xmm(target)];
*target = match insn.op {
Op::Psrldq => shift_bytes(*target, insn.imm, false),
Op::Pslldq => shift_bytes(*target, insn.imm, true),
op => shift(op, *target, insn.imm),
};
}
}
(_, Encoding::XmmRmImm) => {
let source = read_rm(cpu, memory, insn)?;
let old = cpu.xmm[reg];
let imm = insn.imm;
cpu.xmm[reg] = match insn.op {
Op::Pshufd => shuffle_32(source, source, imm),
Op::Pshuflw => shuffle_16(source, imm, 0),
Op::Pshufhw => shuffle_16(source, imm, 4),
Op::Shufps => shuffle_32(old, source, imm),
_ => build(64, |index| {
let from = if index == 0 { old } else { source };
lane(from, 64, (imm >> index & 1) as u32)
}),
};
}
(op, _) => {
let source = read_rm(cpu, memory, insn)?;
cpu.xmm[reg] = packed(op, cpu.xmm[reg], source);
}
}
Ok(())
}
File diff suppressed because it is too large. Load diff
+166
View File
@@ -0,0 +1,166 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Assembler encodings against LLVM (`clang -target arm64-apple-macos -c`, read
//! back with `objdump -d`).
use xenora_loader::Arm64Assembler;
use xenora_loader::arm64::Condition;
type Emit = fn(&mut Arm64Assembler);
#[test]
fn flag_and_byte_operations_match_llvm() {
let cases: &[(&str, Emit, u32)] = &[
("cset w0, hs", |a| a.cset_32(0, Condition::Cs), 0x1a9f37e0),
("cset w12, vs", |a| a.cset_32(12, Condition::Vs), 0x1a9f77ec),
("cset w30, eq", |a| a.cset_32(30, Condition::Eq), 0x1a9f17fe),
(
"csel x9, x10, x11, ne",
|a| a.csel_64(9, 10, 11, Condition::Ne),
0x9a8b1149,
),
(
"csel x0, x30, x17, lt",
|a| a.csel_64(0, 30, 17, Condition::Lt),
0x9a91b3c0,
),
(
"strb w0, [x19, #136]",
|a| a.strb_uoff(0, 19, 136),
0x39022260,
),
(
"strb wzr, [x19, #141]",
|a| a.strb_uoff(31, 19, 141),
0x3902367f,
),
(
"ldrb w12, [x19, #140]",
|a| a.ldrb_uoff(12, 19, 140),
0x3942326c,
),
(
"eor w12, w11, w10, lsr #4",
|a| a.eor_lsr_32(12, 11, 10, 4),
0x4a4a116c,
),
(
"eor w1, w2, w3, lsr #0",
|a| a.eor_lsr_32(1, 2, 3, 0),
0x4a430041,
),
(
"orr w12, w13, w14",
|a| a.orr_reg_32(12, 13, 14),
0x2a0e01ac,
),
(
"bic w12, w13, w14",
|a| a.bic_reg_32(12, 13, 14),
0x0a2e01ac,
),
("mvn x11, x9", |a| a.mvn_64(11, 9), 0xaa2903eb),
("mvn x0, x30", |a| a.mvn_64(0, 30), 0xaa3e03e0),
(
"ubfx w12, w13, #4, #1",
|a| a.ubfx_bit_32(12, 13, 4),
0x530411ac,
),
("rev x10, x9", |a| a.rev(10, 9, true), 0xdac00d2a),
("rev w0, w30", |a| a.rev(0, 30, false), 0x5ac00bc0),
("lsr x0, x0, #8", |a| a.lsr_imm_64(0, 0, 8), 0xd348fc00),
("lsr x9, x30, #63", |a| a.lsr_imm_64(9, 30, 63), 0xd37fffc9),
("sxtb w9, w10", |a| a.sxtb_32(9, 10), 0x13001d49),
("sxtb w30, w0", |a| a.sxtb_32(30, 0), 0x13001c1e),
("sxth w9, w10", |a| a.sxth_32(9, 10), 0x13003d49),
("sxth w0, w30", |a| a.sxth_32(0, 30), 0x13003fc0),
];
for (text, emit, word) in cases {
let mut assembler = Arm64Assembler::new();
emit(&mut assembler);
assert_eq!(assembler.instructions(), [*word], "{text}");
}
}
#[test]
fn vector_operations_match_llvm() {
let cases: &[(&str, Emit, u32)] = &[
(
"ldr q1, [x19, #160]",
|a| a.ldr_q_uoff(1, 19, 160),
0x3dc02a61,
),
(
"str q0, [x19, #400]",
|a| a.str_q_uoff(0, 19, 400),
0x3d806660,
),
("fmov d1, x0", |a| a.fmov_d_from_x(1, 0), 0x9e670001),
("mov v1.d[1], x1", |a| a.ins_d1_from_x(1, 1), 0x4e181c21),
(
"and v0.16b, v1.16b, v2.16b",
|a| a.neon3(0x4e20_1c00, 0, 1, 2),
0x4e221c20,
),
(
"sub v31.2d, v30.2d, v29.2d",
|a| a.neon3(0x6ee0_8400, 31, 30, 29),
0x6efd87df,
),
(
"shl v0.8h, v1.8h, #0",
|a| a.shl_vector(0, 1, 16, 0),
0x4f105420,
),
(
"shl v0.8h, v1.8h, #15",
|a| a.shl_vector(0, 1, 16, 15),
0x4f1f5420,
),
(
"shl v2.4s, v3.4s, #31",
|a| a.shl_vector(2, 3, 32, 31),
0x4f3f5462,
),
(
"shl v4.2d, v5.2d, #63",
|a| a.shl_vector(4, 5, 64, 63),
0x4f7f54a4,
),
(
"ushr v0.8h, v1.8h, #1",
|a| a.ushr_vector(0, 1, 16, 1),
0x6f1f0420,
),
(
"ushr v0.8h, v1.8h, #16",
|a| a.ushr_vector(0, 1, 16, 16),
0x6f100420,
),
(
"ushr v2.4s, v3.4s, #32",
|a| a.ushr_vector(2, 3, 32, 32),
0x6f200462,
),
(
"ushr v4.2d, v5.2d, #64",
|a| a.ushr_vector(4, 5, 64, 64),
0x6f4004a4,
),
(
"sshr v0.8h, v1.8h, #16",
|a| a.sshr_vector(0, 1, 16, 16),
0x4f100420,
),
(
"sshr v2.4s, v3.4s, #5",
|a| a.sshr_vector(2, 3, 32, 5),
0x4f3b0462,
),
];
for (text, emit, word) in cases {
let mut assembler = Arm64Assembler::new();
emit(&mut assembler);
assert_eq!(assembler.instructions(), [*word], "{text}");
}
}
+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);
}
+1
View File
@@ -31,6 +31,7 @@ fn check_bswap(native: bool) {
zf: !wide,
sf: wide,
of: !wide,
..RFlags::default()
};
let flags = cpu.flags;
let mut expected = cpu.gpr;
File diff suppressed because it is too large. Load diff
@@ -7,33 +7,18 @@ use xenora_loader::memory::{GuestMemory, MemoryPermissions};
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
#[test]
fn test_generated_crt_math_in_runtime_registry() {
fn test_crt_math_resolves_through_its_api_set_and_uses_xmm0() {
let mut registry = ImportRegistry::new();
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(100))));
register_standard_services(&mut registry, state);
// Register a sample generated CRT handler (e.g. sqrt)
registry.register_with_status(
"api-ms-win-crt-math-l1-1-0.dll",
"sqrt",
ServiceStatus::Partial,
|args: &Win64Args,
_cpu: &mut CpuState,
_mem: &mut GuestMemory|
-> Result<u64, ExitReason> {
let x = f64::from_bits(args.rcx);
let r = x.sqrt();
Ok(r.to_bits())
},
);
let mut cpu = CpuState::new(0x1000, 0x8000);
let mut mem = GuestMemory::new();
mem.map_region(0x1000, 0x10000, MemoryPermissions::READ_WRITE_EXECUTE)
.unwrap();
cpu.xmm[0] = u128::from(16.0f64.to_bits());
let args = Win64Args {
rcx: (16.0f64).to_bits(),
rcx: 9.0f64.to_bits(),
rdx: 0,
r8: 0,
r9: 0,
@@ -43,8 +28,8 @@ fn test_generated_crt_math_in_runtime_registry() {
let desc = registry
.binding("api-ms-win-crt-math-l1-1-0.dll", "sqrt")
.unwrap();
let res = (desc.handler)(&args, &mut cpu, &mut mem).unwrap();
assert_eq!(f64::from_bits(res), 4.0);
(desc.handler)(&args, &mut cpu, &mut mem).unwrap();
assert_eq!(f64::from_bits(cpu.xmm[0] as u64), 4.0);
}
#[test]
+539
View File
@@ -0,0 +1,539 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! MOVZX, MOVSX and MOVSXD known-answer tests (issues #65, #66 and #117), and
//! the MOV-immediate regressions that keep one-byte opcodes B8-BF separate from
//! the two-byte 0F BE/BF sign extensions.
//!
//! Every encoding was produced from its Intel-syntax text by the LLVM assembler
//! (`clang -target x86_64-apple-macos -c` then `objdump -d`, Apple clang 17.0.0).
//! Expected values follow the Intel SDM Vol. 2 operation sections and are
//! computed here by modular arithmetic, independently of both engines.
use xenora_loader::cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, RFlags, Register};
use xenora_loader::dbt::DbtEngine;
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
const ENTRY: u64 = 0x1000;
const DATA: u64 = 0x2000;
const DATA_LEN: usize = 0x400;
struct Case {
text: &'static str,
code: &'static [u8],
signed: bool,
dst: usize,
dst_bits: u32,
/// Register number, or for `high` the parent of AH/CH/DH/BH.
src: usize,
src_bits: u32,
high: bool,
}
#[rustfmt::skip]
const CASES: &[Case] = &[
Case { text: "movsx ax, cl", code: &[0x66, 0x0F, 0xBE, 0xC1], signed: true, dst: 0, dst_bits: 16, src: 1, src_bits: 8, high: false },
Case { text: "movsx bx, al", code: &[0x66, 0x0F, 0xBE, 0xD8], signed: true, dst: 3, dst_bits: 16, src: 0, src_bits: 8, high: false },
Case { text: "movsx r8w, r9b", code: &[0x66, 0x45, 0x0F, 0xBE, 0xC1], signed: true, dst: 8, dst_bits: 16, src: 9, src_bits: 8, high: false },
Case { text: "movsx cx, r12b", code: &[0x66, 0x41, 0x0F, 0xBE, 0xCC], signed: true, dst: 1, dst_bits: 16, src: 12, src_bits: 8, high: false },
Case { text: "movsx r10w, dl", code: &[0x66, 0x44, 0x0F, 0xBE, 0xD2], signed: true, dst: 10, dst_bits: 16, src: 2, src_bits: 8, high: false },
Case { text: "movsx si, dil", code: &[0x66, 0x40, 0x0F, 0xBE, 0xF7], signed: true, dst: 6, dst_bits: 16, src: 7, src_bits: 8, high: false },
Case { text: "movsx dx, dl", code: &[0x66, 0x0F, 0xBE, 0xD2], signed: true, dst: 2, dst_bits: 16, src: 2, src_bits: 8, high: false },
Case { text: "movsx eax, cl", code: &[0x0F, 0xBE, 0xC1], signed: true, dst: 0, dst_bits: 32, src: 1, src_bits: 8, high: false },
Case { text: "movsx ebx, al", code: &[0x0F, 0xBE, 0xD8], signed: true, dst: 3, dst_bits: 32, src: 0, src_bits: 8, high: false },
Case { text: "movsx r8d, r9b", code: &[0x45, 0x0F, 0xBE, 0xC1], signed: true, dst: 8, dst_bits: 32, src: 9, src_bits: 8, high: false },
Case { text: "movsx ecx, r12b", code: &[0x41, 0x0F, 0xBE, 0xCC], signed: true, dst: 1, dst_bits: 32, src: 12, src_bits: 8, high: false },
Case { text: "movsx r10d, dl", code: &[0x44, 0x0F, 0xBE, 0xD2], signed: true, dst: 10, dst_bits: 32, src: 2, src_bits: 8, high: false },
Case { text: "movsx esi, dil", code: &[0x40, 0x0F, 0xBE, 0xF7], signed: true, dst: 6, dst_bits: 32, src: 7, src_bits: 8, high: false },
Case { text: "movsx edx, dl", code: &[0x0F, 0xBE, 0xD2], signed: true, dst: 2, dst_bits: 32, src: 2, src_bits: 8, high: false },
Case { text: "movsx rax, cl", code: &[0x48, 0x0F, 0xBE, 0xC1], signed: true, dst: 0, dst_bits: 64, src: 1, src_bits: 8, high: false },
Case { text: "movsx rbx, al", code: &[0x48, 0x0F, 0xBE, 0xD8], signed: true, dst: 3, dst_bits: 64, src: 0, src_bits: 8, high: false },
Case { text: "movsx r8, r9b", code: &[0x4D, 0x0F, 0xBE, 0xC1], signed: true, dst: 8, dst_bits: 64, src: 9, src_bits: 8, high: false },
Case { text: "movsx rcx, r12b", code: &[0x49, 0x0F, 0xBE, 0xCC], signed: true, dst: 1, dst_bits: 64, src: 12, src_bits: 8, high: false },
Case { text: "movsx r10, dl", code: &[0x4C, 0x0F, 0xBE, 0xD2], signed: true, dst: 10, dst_bits: 64, src: 2, src_bits: 8, high: false },
Case { text: "movsx rsi, dil", code: &[0x48, 0x0F, 0xBE, 0xF7], signed: true, dst: 6, dst_bits: 64, src: 7, src_bits: 8, high: false },
Case { text: "movsx rdx, dl", code: &[0x48, 0x0F, 0xBE, 0xD2], signed: true, dst: 2, dst_bits: 64, src: 2, src_bits: 8, high: false },
Case { text: "movsx eax, cx", code: &[0x0F, 0xBF, 0xC1], signed: true, dst: 0, dst_bits: 32, src: 1, src_bits: 16, high: false },
Case { text: "movsx ebx, ax", code: &[0x0F, 0xBF, 0xD8], signed: true, dst: 3, dst_bits: 32, src: 0, src_bits: 16, high: false },
Case { text: "movsx r8d, r9w", code: &[0x45, 0x0F, 0xBF, 0xC1], signed: true, dst: 8, dst_bits: 32, src: 9, src_bits: 16, high: false },
Case { text: "movsx ecx, r12w", code: &[0x41, 0x0F, 0xBF, 0xCC], signed: true, dst: 1, dst_bits: 32, src: 12, src_bits: 16, high: false },
Case { text: "movsx r10d, dx", code: &[0x44, 0x0F, 0xBF, 0xD2], signed: true, dst: 10, dst_bits: 32, src: 2, src_bits: 16, high: false },
Case { text: "movsx esi, bp", code: &[0x0F, 0xBF, 0xF5], signed: true, dst: 6, dst_bits: 32, src: 5, src_bits: 16, high: false },
Case { text: "movsx edx, dx", code: &[0x0F, 0xBF, 0xD2], signed: true, dst: 2, dst_bits: 32, src: 2, src_bits: 16, high: false },
Case { text: "movsx rax, cx", code: &[0x48, 0x0F, 0xBF, 0xC1], signed: true, dst: 0, dst_bits: 64, src: 1, src_bits: 16, high: false },
Case { text: "movsx rbx, ax", code: &[0x48, 0x0F, 0xBF, 0xD8], signed: true, dst: 3, dst_bits: 64, src: 0, src_bits: 16, high: false },
Case { text: "movsx r8, r9w", code: &[0x4D, 0x0F, 0xBF, 0xC1], signed: true, dst: 8, dst_bits: 64, src: 9, src_bits: 16, high: false },
Case { text: "movsx rcx, r12w", code: &[0x49, 0x0F, 0xBF, 0xCC], signed: true, dst: 1, dst_bits: 64, src: 12, src_bits: 16, high: false },
Case { text: "movsx r10, dx", code: &[0x4C, 0x0F, 0xBF, 0xD2], signed: true, dst: 10, dst_bits: 64, src: 2, src_bits: 16, high: false },
Case { text: "movsx rsi, bp", code: &[0x48, 0x0F, 0xBF, 0xF5], signed: true, dst: 6, dst_bits: 64, src: 5, src_bits: 16, high: false },
Case { text: "movsx rdx, dx", code: &[0x48, 0x0F, 0xBF, 0xD2], signed: true, dst: 2, dst_bits: 64, src: 2, src_bits: 16, high: false },
Case { text: "movsx dx, ah", code: &[0x66, 0x0F, 0xBE, 0xD4], signed: true, dst: 2, dst_bits: 16, src: 0, src_bits: 8, high: true },
Case { text: "movsx dx, ch", code: &[0x66, 0x0F, 0xBE, 0xD5], signed: true, dst: 2, dst_bits: 16, src: 1, src_bits: 8, high: true },
Case { text: "movsx dx, dh", code: &[0x66, 0x0F, 0xBE, 0xD6], signed: true, dst: 2, dst_bits: 16, src: 2, src_bits: 8, high: true },
Case { text: "movsx dx, bh", code: &[0x66, 0x0F, 0xBE, 0xD7], signed: true, dst: 2, dst_bits: 16, src: 3, src_bits: 8, high: true },
Case { text: "movsx edx, ah", code: &[0x0F, 0xBE, 0xD4], signed: true, dst: 2, dst_bits: 32, src: 0, src_bits: 8, high: true },
Case { text: "movsx edx, ch", code: &[0x0F, 0xBE, 0xD5], signed: true, dst: 2, dst_bits: 32, src: 1, src_bits: 8, high: true },
Case { text: "movsx edx, dh", code: &[0x0F, 0xBE, 0xD6], signed: true, dst: 2, dst_bits: 32, src: 2, src_bits: 8, high: true },
Case { text: "movsx edx, bh", code: &[0x0F, 0xBE, 0xD7], signed: true, dst: 2, dst_bits: 32, src: 3, src_bits: 8, high: true },
Case { text: "movzx ax, cl", code: &[0x66, 0x0F, 0xB6, 0xC1], signed: false, dst: 0, dst_bits: 16, src: 1, src_bits: 8, high: false },
Case { text: "movzx bx, al", code: &[0x66, 0x0F, 0xB6, 0xD8], signed: false, dst: 3, dst_bits: 16, src: 0, src_bits: 8, high: false },
Case { text: "movzx r8w, r9b", code: &[0x66, 0x45, 0x0F, 0xB6, 0xC1], signed: false, dst: 8, dst_bits: 16, src: 9, src_bits: 8, high: false },
Case { text: "movzx cx, r12b", code: &[0x66, 0x41, 0x0F, 0xB6, 0xCC], signed: false, dst: 1, dst_bits: 16, src: 12, src_bits: 8, high: false },
Case { text: "movzx r10w, dl", code: &[0x66, 0x44, 0x0F, 0xB6, 0xD2], signed: false, dst: 10, dst_bits: 16, src: 2, src_bits: 8, high: false },
Case { text: "movzx si, dil", code: &[0x66, 0x40, 0x0F, 0xB6, 0xF7], signed: false, dst: 6, dst_bits: 16, src: 7, src_bits: 8, high: false },
Case { text: "movzx dx, dl", code: &[0x66, 0x0F, 0xB6, 0xD2], signed: false, dst: 2, dst_bits: 16, src: 2, src_bits: 8, high: false },
Case { text: "movzx eax, cl", code: &[0x0F, 0xB6, 0xC1], signed: false, dst: 0, dst_bits: 32, src: 1, src_bits: 8, high: false },
Case { text: "movzx ebx, al", code: &[0x0F, 0xB6, 0xD8], signed: false, dst: 3, dst_bits: 32, src: 0, src_bits: 8, high: false },
Case { text: "movzx r8d, r9b", code: &[0x45, 0x0F, 0xB6, 0xC1], signed: false, dst: 8, dst_bits: 32, src: 9, src_bits: 8, high: false },
Case { text: "movzx ecx, r12b", code: &[0x41, 0x0F, 0xB6, 0xCC], signed: false, dst: 1, dst_bits: 32, src: 12, src_bits: 8, high: false },
Case { text: "movzx r10d, dl", code: &[0x44, 0x0F, 0xB6, 0xD2], signed: false, dst: 10, dst_bits: 32, src: 2, src_bits: 8, high: false },
Case { text: "movzx esi, dil", code: &[0x40, 0x0F, 0xB6, 0xF7], signed: false, dst: 6, dst_bits: 32, src: 7, src_bits: 8, high: false },
Case { text: "movzx edx, dl", code: &[0x0F, 0xB6, 0xD2], signed: false, dst: 2, dst_bits: 32, src: 2, src_bits: 8, high: false },
Case { text: "movzx rax, cl", code: &[0x48, 0x0F, 0xB6, 0xC1], signed: false, dst: 0, dst_bits: 64, src: 1, src_bits: 8, high: false },
Case { text: "movzx rbx, al", code: &[0x48, 0x0F, 0xB6, 0xD8], signed: false, dst: 3, dst_bits: 64, src: 0, src_bits: 8, high: false },
Case { text: "movzx r8, r9b", code: &[0x4D, 0x0F, 0xB6, 0xC1], signed: false, dst: 8, dst_bits: 64, src: 9, src_bits: 8, high: false },
Case { text: "movzx rcx, r12b", code: &[0x49, 0x0F, 0xB6, 0xCC], signed: false, dst: 1, dst_bits: 64, src: 12, src_bits: 8, high: false },
Case { text: "movzx r10, dl", code: &[0x4C, 0x0F, 0xB6, 0xD2], signed: false, dst: 10, dst_bits: 64, src: 2, src_bits: 8, high: false },
Case { text: "movzx rsi, dil", code: &[0x48, 0x0F, 0xB6, 0xF7], signed: false, dst: 6, dst_bits: 64, src: 7, src_bits: 8, high: false },
Case { text: "movzx rdx, dl", code: &[0x48, 0x0F, 0xB6, 0xD2], signed: false, dst: 2, dst_bits: 64, src: 2, src_bits: 8, high: false },
Case { text: "movzx eax, cx", code: &[0x0F, 0xB7, 0xC1], signed: false, dst: 0, dst_bits: 32, src: 1, src_bits: 16, high: false },
Case { text: "movzx ebx, ax", code: &[0x0F, 0xB7, 0xD8], signed: false, dst: 3, dst_bits: 32, src: 0, src_bits: 16, high: false },
Case { text: "movzx r8d, r9w", code: &[0x45, 0x0F, 0xB7, 0xC1], signed: false, dst: 8, dst_bits: 32, src: 9, src_bits: 16, high: false },
Case { text: "movzx ecx, r12w", code: &[0x41, 0x0F, 0xB7, 0xCC], signed: false, dst: 1, dst_bits: 32, src: 12, src_bits: 16, high: false },
Case { text: "movzx r10d, dx", code: &[0x44, 0x0F, 0xB7, 0xD2], signed: false, dst: 10, dst_bits: 32, src: 2, src_bits: 16, high: false },
Case { text: "movzx esi, bp", code: &[0x0F, 0xB7, 0xF5], signed: false, dst: 6, dst_bits: 32, src: 5, src_bits: 16, high: false },
Case { text: "movzx edx, dx", code: &[0x0F, 0xB7, 0xD2], signed: false, dst: 2, dst_bits: 32, src: 2, src_bits: 16, high: false },
Case { text: "movzx rax, cx", code: &[0x48, 0x0F, 0xB7, 0xC1], signed: false, dst: 0, dst_bits: 64, src: 1, src_bits: 16, high: false },
Case { text: "movzx rbx, ax", code: &[0x48, 0x0F, 0xB7, 0xD8], signed: false, dst: 3, dst_bits: 64, src: 0, src_bits: 16, high: false },
Case { text: "movzx r8, r9w", code: &[0x4D, 0x0F, 0xB7, 0xC1], signed: false, dst: 8, dst_bits: 64, src: 9, src_bits: 16, high: false },
Case { text: "movzx rcx, r12w", code: &[0x49, 0x0F, 0xB7, 0xCC], signed: false, dst: 1, dst_bits: 64, src: 12, src_bits: 16, high: false },
Case { text: "movzx r10, dx", code: &[0x4C, 0x0F, 0xB7, 0xD2], signed: false, dst: 10, dst_bits: 64, src: 2, src_bits: 16, high: false },
Case { text: "movzx rsi, bp", code: &[0x48, 0x0F, 0xB7, 0xF5], signed: false, dst: 6, dst_bits: 64, src: 5, src_bits: 16, high: false },
Case { text: "movzx rdx, dx", code: &[0x48, 0x0F, 0xB7, 0xD2], signed: false, dst: 2, dst_bits: 64, src: 2, src_bits: 16, high: false },
Case { text: "movzx dx, ah", code: &[0x66, 0x0F, 0xB6, 0xD4], signed: false, dst: 2, dst_bits: 16, src: 0, src_bits: 8, high: true },
Case { text: "movzx dx, ch", code: &[0x66, 0x0F, 0xB6, 0xD5], signed: false, dst: 2, dst_bits: 16, src: 1, src_bits: 8, high: true },
Case { text: "movzx dx, dh", code: &[0x66, 0x0F, 0xB6, 0xD6], signed: false, dst: 2, dst_bits: 16, src: 2, src_bits: 8, high: true },
Case { text: "movzx dx, bh", code: &[0x66, 0x0F, 0xB6, 0xD7], signed: false, dst: 2, dst_bits: 16, src: 3, src_bits: 8, high: true },
Case { text: "movzx edx, ah", code: &[0x0F, 0xB6, 0xD4], signed: false, dst: 2, dst_bits: 32, src: 0, src_bits: 8, high: true },
Case { text: "movzx edx, ch", code: &[0x0F, 0xB6, 0xD5], signed: false, dst: 2, dst_bits: 32, src: 1, src_bits: 8, high: true },
Case { text: "movzx edx, dh", code: &[0x0F, 0xB6, 0xD6], signed: false, dst: 2, dst_bits: 32, src: 2, src_bits: 8, high: true },
Case { text: "movzx edx, bh", code: &[0x0F, 0xB6, 0xD7], signed: false, dst: 2, dst_bits: 32, src: 3, src_bits: 8, high: true },
Case { text: "movsxd rax, ecx", code: &[0x48, 0x63, 0xC1], signed: true, dst: 0, dst_bits: 64, src: 1, src_bits: 32, high: false },
Case { text: "movsxd rbx, eax", code: &[0x48, 0x63, 0xD8], signed: true, dst: 3, dst_bits: 64, src: 0, src_bits: 32, high: false },
Case { text: "movsxd r8, r9d", code: &[0x4D, 0x63, 0xC1], signed: true, dst: 8, dst_bits: 64, src: 9, src_bits: 32, high: false },
Case { text: "movsxd rcx, r12d", code: &[0x49, 0x63, 0xCC], signed: true, dst: 1, dst_bits: 64, src: 12, src_bits: 32, high: false },
Case { text: "movsxd r10, edx", code: &[0x4C, 0x63, 0xD2], signed: true, dst: 10, dst_bits: 64, src: 2, src_bits: 32, high: false },
Case { text: "movsxd rsi, ebp", code: &[0x48, 0x63, 0xF5], signed: true, dst: 6, dst_bits: 64, src: 5, src_bits: 32, high: false },
Case { text: "movsxd rdx, edx", code: &[0x48, 0x63, 0xD2], signed: true, dst: 2, dst_bits: 64, src: 2, src_bits: 32, high: false },
];
#[rustfmt::skip]
const MOV_IMMEDIATE: &[(&[u8], usize, u64)] = &[
(&[0xB8, 0x81, 0xBE, 0xF0, 0x8B], 0, 0x8BF0_BE81), // mov eax, 0x8bf0be81
(&[0xB9, 0x81, 0xBE, 0xF0, 0x8B], 1, 0x8BF0_BE81), // mov ecx, 0x8bf0be81
(&[0xBA, 0x81, 0xBE, 0xF0, 0x8B], 2, 0x8BF0_BE81), // mov edx, 0x8bf0be81
(&[0xBB, 0x81, 0xBE, 0xF0, 0x8B], 3, 0x8BF0_BE81), // mov ebx, 0x8bf0be81
(&[0xBC, 0x81, 0xBE, 0xF0, 0x8B], 4, 0x8BF0_BE81), // mov esp, 0x8bf0be81
(&[0xBD, 0x81, 0xBE, 0xF0, 0x8B], 5, 0x8BF0_BE81), // mov ebp, 0x8bf0be81
(&[0xBE, 0x81, 0xBE, 0xF0, 0x8B], 6, 0x8BF0_BE81), // mov esi, 0x8bf0be81
(&[0xBF, 0x81, 0xBE, 0xF0, 0x8B], 7, 0x8BF0_BE81), // mov edi, 0x8bf0be81
(&[0x41, 0xB8, 0x81, 0xBE, 0xF0, 0x8B], 8, 0x8BF0_BE81), // mov r8d, 0x8bf0be81
(&[0x41, 0xB9, 0x81, 0xBE, 0xF0, 0x8B], 9, 0x8BF0_BE81), // mov r9d, 0x8bf0be81
(&[0x41, 0xBA, 0x81, 0xBE, 0xF0, 0x8B], 10, 0x8BF0_BE81), // mov r10d, 0x8bf0be81
(&[0x41, 0xBB, 0x81, 0xBE, 0xF0, 0x8B], 11, 0x8BF0_BE81), // mov r11d, 0x8bf0be81
(&[0x41, 0xBC, 0x81, 0xBE, 0xF0, 0x8B], 12, 0x8BF0_BE81), // mov r12d, 0x8bf0be81
(&[0x41, 0xBD, 0x81, 0xBE, 0xF0, 0x8B], 13, 0x8BF0_BE81), // mov r13d, 0x8bf0be81
(&[0x41, 0xBE, 0x81, 0xBE, 0xF0, 0x8B], 14, 0x8BF0_BE81), // mov r14d, 0x8bf0be81
(&[0x41, 0xBF, 0x81, 0xBE, 0xF0, 0x8B], 15, 0x8BF0_BE81), // mov r15d, 0x8bf0be81
(&[0x48, 0xB8, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 0, 0x80BE_0FBF_63C1_B8F1), // movabs rax, 0x80be0fbf63c1b8f1
(&[0x48, 0xB9, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 1, 0x80BE_0FBF_63C1_B8F1), // movabs rcx, 0x80be0fbf63c1b8f1
(&[0x48, 0xBA, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 2, 0x80BE_0FBF_63C1_B8F1), // movabs rdx, 0x80be0fbf63c1b8f1
(&[0x48, 0xBB, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 3, 0x80BE_0FBF_63C1_B8F1), // movabs rbx, 0x80be0fbf63c1b8f1
(&[0x48, 0xBC, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 4, 0x80BE_0FBF_63C1_B8F1), // movabs rsp, 0x80be0fbf63c1b8f1
(&[0x48, 0xBD, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 5, 0x80BE_0FBF_63C1_B8F1), // movabs rbp, 0x80be0fbf63c1b8f1
(&[0x48, 0xBE, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 6, 0x80BE_0FBF_63C1_B8F1), // movabs rsi, 0x80be0fbf63c1b8f1
(&[0x48, 0xBF, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 7, 0x80BE_0FBF_63C1_B8F1), // movabs rdi, 0x80be0fbf63c1b8f1
(&[0x49, 0xB8, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 8, 0x80BE_0FBF_63C1_B8F1), // movabs r8, 0x80be0fbf63c1b8f1
(&[0x49, 0xB9, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 9, 0x80BE_0FBF_63C1_B8F1), // movabs r9, 0x80be0fbf63c1b8f1
(&[0x49, 0xBA, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 10, 0x80BE_0FBF_63C1_B8F1), // movabs r10, 0x80be0fbf63c1b8f1
(&[0x49, 0xBB, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 11, 0x80BE_0FBF_63C1_B8F1), // movabs r11, 0x80be0fbf63c1b8f1
(&[0x49, 0xBC, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 12, 0x80BE_0FBF_63C1_B8F1), // movabs r12, 0x80be0fbf63c1b8f1
(&[0x49, 0xBD, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 13, 0x80BE_0FBF_63C1_B8F1), // movabs r13, 0x80be0fbf63c1b8f1
(&[0x49, 0xBE, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 14, 0x80BE_0FBF_63C1_B8F1), // movabs r14, 0x80be0fbf63c1b8f1
(&[0x49, 0xBF, 0xF1, 0xB8, 0xC1, 0x63, 0xBF, 0x0F, 0xBE, 0x80], 15, 0x80BE_0FBF_63C1_B8F1), // movabs r15, 0x80be0fbf63c1b8f1
];
fn mask(bits: u32) -> u128 {
(1u128 << bits) - 1
}
/// Architectural destination value, derived with modular arithmetic.
fn expected(case: &Case, gpr: &[u64; 16]) -> u64 {
let shift = if case.high { 8 } else { 0 };
let source = (u128::from(gpr[case.src]) >> shift) & mask(case.src_bits);
let negative = case.signed && source >= 1u128 << (case.src_bits - 1);
let extended = if negative {
(1u128 << 64) - (1u128 << case.src_bits) + source
} else {
source
};
let low = extended & mask(case.dst_bits);
let kept = if case.dst_bits == 16 {
u128::from(gpr[case.dst]) & !mask(16)
} else {
0 // 32-bit writes clear bits 63:32.
};
(kept | low) as u64
}
fn memory_with(code: &[u8], data: &[u8]) -> GuestMemory {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, code)
.unwrap();
let mut bytes = vec![0xEEu8; DATA_LEN];
bytes[..data.len()].copy_from_slice(data);
memory
.map_region_with_data(DATA, DATA_LEN, MemoryPermissions::READ_WRITE, &bytes)
.unwrap();
memory
}
fn interpret(cpu: &CpuState, memory: &mut GuestMemory) -> ExecutionResult {
Interpreter::new(cpu.clone(), memory, 1).run()
}
/// Run one instruction as translated native code, proving that it was.
fn translate(cpu: &CpuState, memory: &mut GuestMemory, text: &str) -> ExecutionResult {
let mut engine = DbtEngine::new(64 * 1024).expect("JIT memory");
let result = engine.run(&mut cpu.clone(), memory, 1);
if result.exit_reason == ExitReason::StepLimitExceeded {
assert_eq!(engine.metrics.blocks_compiled, 1, "{text}");
assert_eq!(engine.metrics.dbt_dispatches, 1, "{text}");
assert_eq!(engine.metrics.instructions_executed, 1, "{text}");
assert_eq!(engine.metrics.interpreter_fallbacks, 0, "{text}");
}
result
}
fn both(
code: &[u8],
data: &[u8],
cpu: &CpuState,
text: &str,
) -> [(ExecutionResult, GuestMemory); 2] {
let mut first = memory_with(code, data);
let mut second = memory_with(code, data);
let interpreted = interpret(cpu, &mut first);
let translated = translate(cpu, &mut second, text);
[(interpreted, first), (translated, second)]
}
#[test]
fn register_extensions_match_the_architecture_in_both_engines() {
let low_values: [u64; 12] = [
0,
1,
0x7F,
0x80,
0xFF,
0x100,
0x7FFF,
0x8000,
0xFFFF,
0x7FFF_FFFF,
0x8000_0000,
0xFFFF_FFFF,
];
let patterns = low_values
.into_iter()
.flat_map(|low| [low, low | 0xA5A5_5A5A_0000_0000, low << 8]);
for pattern in patterns {
for case in CASES {
for flags_set in [false, true] {
let mut cpu = CpuState::new(ENTRY, 0);
for (index, register) in cpu.gpr.iter_mut().enumerate() {
*register = 0x1122_3344_5566_7788u64.rotate_left(index as u32 * 4);
}
cpu.gpr[case.src] = pattern;
cpu.flags = RFlags {
cf: flags_set,
zf: flags_set,
sf: flags_set,
of: flags_set,
..RFlags::default()
};
let mut gpr = cpu.gpr;
gpr[case.dst] = expected(case, &cpu.gpr);
for (result, _) in both(case.code, &[], &cpu, case.text) {
assert_eq!(
result.exit_reason,
ExitReason::StepLimitExceeded,
"{}",
case.text
);
assert_eq!(result.instructions_executed, 1, "{}", case.text);
assert_eq!(result.final_state.gpr, gpr, "{} {pattern:#x}", case.text);
assert_eq!(result.final_state.flags, cpu.flags, "{}", case.text);
assert_eq!(result.final_state.rip, ENTRY + case.code.len() as u64);
}
}
}
}
}
#[test]
fn mov_immediate_is_never_decoded_as_a_sign_extension() {
for &(code, register, value) in MOV_IMMEDIATE {
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr = [0xFFFF_FFFF_FFFF_FFFF; 16];
let mut gpr = cpu.gpr;
gpr[register] = value;
for (result, _) in both(code, &[], &cpu, "mov immediate") {
assert_eq!(
result.exit_reason,
ExitReason::StepLimitExceeded,
"{code:02X?}"
);
assert_eq!(result.final_state.gpr, gpr, "{code:02X?}");
assert_eq!(result.final_state.rip, ENTRY + code.len() as u64);
}
}
}
#[test]
fn sixteen_bit_mov_immediate_writes_only_the_low_word() {
// 66 B9 34 12 = mov cx, 0x1234
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr = [0xFFFF_FFFF_FFFF_FFFF; 16];
let mut gpr = cpu.gpr;
gpr[Register::Rcx as usize] = 0xFFFF_FFFF_FFFF_1234;
for (result, _) in both(&[0x66, 0xB9, 0x34, 0x12], &[], &cpu, "mov cx, 0x1234") {
assert_eq!(result.exit_reason, ExitReason::StepLimitExceeded);
assert_eq!(result.final_state.gpr, gpr);
assert_eq!(result.final_state.rip, ENTRY + 4);
}
}
#[test]
fn every_truncation_faults_without_changing_state() {
let codes = CASES
.iter()
.map(|case| case.code)
.chain(MOV_IMMEDIATE.iter().map(|entry| entry.0));
for code in codes {
for len in 1..code.len() {
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr = [0x8080_8080_8080_8080; 16];
for (result, _) in both(&code[..len], &[], &cpu, "truncated") {
assert!(
matches!(result.exit_reason, ExitReason::MemoryFault(_)),
"{:02X?}: {:?}",
&code[..len],
result.exit_reason
);
assert_eq!(result.instructions_executed, 0);
assert_eq!(result.final_state, cpu);
}
}
}
}
#[test]
fn memory_extensions_use_checked_addresses_in_both_engines() {
let data = [0x80u8, 0xFF, 0x7F, 0x00, 0xFE, 0x80, 0xFF, 0x81, 0xC2, 0x83];
let cases: &[(&str, &[u8], u64)] = &[
(
"movsx eax, byte ptr [rbx]",
&[0x0F, 0xBE, 0x03],
0xFFFF_FF80,
),
(
"movsx rax, byte ptr [rbx+4]",
&[0x48, 0x0F, 0xBE, 0x43, 0x04],
0xFFFF_FFFF_FFFF_FFFE,
),
(
"movsx ax, byte ptr [rbx]",
&[0x66, 0x0F, 0xBE, 0x03],
0xAAAA_AAAA_AAAA_FF80,
),
(
"movsx rax, word ptr [rbx+rcx*2+4]",
&[0x48, 0x0F, 0xBF, 0x44, 0x4B, 0x04],
0xFFFF_FFFF_FFFF_81FF,
),
(
"movzx eax, byte ptr [rbx+4]",
&[0x0F, 0xB6, 0x43, 0x04],
0xFE,
),
(
"movsxd rax, dword ptr [rbx+4]",
&[0x48, 0x63, 0x43, 0x04],
0xFFFF_FFFF_81FF_80FE,
),
(
"movsxd rax, dword ptr [r8+rcx*4]",
&[0x49, 0x63, 0x04, 0x88],
0xFFFF_FFFF_81FF_80FE,
),
// The next instruction starts at 0x1007, so the address is 0x2007.
(
"movsx eax, word ptr [rip+0x1000]",
&[0x0F, 0xBF, 0x05, 0x00, 0x10, 0x00, 0x00],
0xFFFF_C281,
),
(
"movsxd rax, dword ptr gs:[rbx]",
&[0x65, 0x48, 0x63, 0x03],
0x007F_FF80,
),
(
"movzx eax, byte ptr fs:[rbx]",
&[0x64, 0x0F, 0xB6, 0x03],
0xFF,
),
("mov eax, dword ptr [rbx]", &[0x8B, 0x03], 0x007F_FF80),
];
for &(text, code, value) in cases {
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[Register::Rax as usize] = 0xAAAA_AAAA_AAAA_AAAA;
cpu.gpr[Register::Rbx as usize] = DATA;
cpu.gpr[Register::Rcx as usize] = 1;
cpu.gpr[Register::R8 as usize] = DATA;
match code[0] {
0x65 => (cpu.gs_base, cpu.gpr[Register::Rbx as usize]) = (DATA, 0),
0x64 => (cpu.fs_base, cpu.gpr[Register::Rbx as usize]) = (DATA - 4, 5),
_ => {}
}
for (result, _) in both(code, &data, &cpu, text) {
assert_eq!(result.exit_reason, ExitReason::StepLimitExceeded, "{text}");
assert_eq!(result.final_state.gpr[0], value, "{text}");
assert_eq!(result.final_state.rip, ENTRY + code.len() as u64, "{text}");
}
}
}
#[test]
fn memory_operands_crossing_the_region_end_fault_precisely() {
// Only the bytes the operand really covers may be touched: the last word,
// dword or byte of the region is readable, one byte further is not.
let cases: &[(&[u8], u64)] = &[
(&[0x0F, 0xBE, 0x03], 1),
(&[0x0F, 0xBF, 0x03], 2),
(&[0x48, 0x63, 0x03], 4),
(&[0x8B, 0x03], 4), // mov eax, dword ptr [rbx]
(&[0x89, 0x03], 4), // mov dword ptr [rbx], eax
];
for &(code, width) in cases {
let end = DATA + DATA_LEN as u64;
for (address, ok) in [(end - width, true), (end - width + 1, false)] {
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[Register::Rbx as usize] = address;
for (result, memory) in both(code, &[], &cpu, "boundary") {
if ok {
assert_eq!(
result.exit_reason,
ExitReason::StepLimitExceeded,
"{code:02X?}"
);
} else {
assert!(
matches!(result.exit_reason, ExitReason::MemoryFault(_)),
"{code:02X?}"
);
assert_eq!(result.instructions_executed, 0);
assert_eq!(result.final_state, cpu, "{code:02X?}");
let mut tail = [0u8; 4];
memory.read_bytes(end - 4, &mut tail).unwrap();
assert_eq!(tail, [0xEE; 4]);
}
}
}
}
}
#[test]
fn a_32_bit_store_leaves_the_next_four_bytes_unchanged() {
// 89 03 = mov dword ptr [rbx], eax
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[Register::Rax as usize] = 0xDDDD_DDDD_1234_5678;
cpu.gpr[Register::Rbx as usize] = DATA;
for (result, memory) in both(&[0x89, 0x03], &[], &cpu, "mov dword ptr [rbx], eax") {
assert_eq!(result.exit_reason, ExitReason::StepLimitExceeded);
assert_eq!(memory.read_u64(DATA).unwrap(), 0xEEEE_EEEE_1234_5678);
}
}
#[test]
fn native_sxtw_encodes_every_register() {
// LLVM: sxtw x0, w30 then sxtw xN, w(31-N) for N in 1..=30.
let llvm: [u32; 31] = [
0x93407fc0, 0x93407fc1, 0x93407fa2, 0x93407f83, 0x93407f64, 0x93407f45, 0x93407f26,
0x93407f07, 0x93407ee8, 0x93407ec9, 0x93407eaa, 0x93407e8b, 0x93407e6c, 0x93407e4d,
0x93407e2e, 0x93407e0f, 0x93407df0, 0x93407dd1, 0x93407db2, 0x93407d93, 0x93407d74,
0x93407d55, 0x93407d36, 0x93407d17, 0x93407cf8, 0x93407cd9, 0x93407cba, 0x93407c9b,
0x93407c7c, 0x93407c5d, 0x93407c3e,
];
let mut assembler = xenora_loader::Arm64Assembler::new();
for xd in 0..31u8 {
assembler.sxtw_64(xd, if xd == 0 { 30 } else { 31 - xd });
}
assert_eq!(assembler.instructions(), llvm);
}
#[test]
fn probe_reports_exact_extension_lengths_and_support() {
use xenora_loader::probe::{ProbeConfig, probe_pe_bytes};
for case in CASES {
let report = probe_pe_bytes(&probe_image(case.code), &ProbeConfig::default()).unwrap();
let record = &report.instruction_records[0];
assert_eq!(record.bytes, case.code, "{}", case.text);
assert!(
record.is_supported_dbt && record.is_supported_interp,
"{}",
case.text
);
}
for &(code, _, _) in MOV_IMMEDIATE {
let report = probe_pe_bytes(&probe_image(code), &ProbeConfig::default()).unwrap();
let record = &report.instruction_records[0];
assert_eq!(record.bytes, code);
assert!(
record.mnemonic.starts_with("mov reg, imm"),
"{}",
record.mnemonic
);
}
}
/// Minimal PE32+ image whose entry point holds `code` followed by HLT.
fn probe_image(code: &[u8]) -> Vec<u8> {
let mut pe = vec![0u8; 0x400];
let mut put =
|offset: usize, bytes: &[u8]| pe[offset..offset + bytes.len()].copy_from_slice(bytes);
put(0, b"MZ");
put(0x3C, &0x80u32.to_le_bytes());
put(0x80, b"PE\0\0");
put(0x84, &0x8664u16.to_le_bytes());
put(0x86, &1u16.to_le_bytes());
put(0x94, &240u16.to_le_bytes());
put(0x98, &0x20Bu16.to_le_bytes());
put(0x98 + 16, &(ENTRY as u32).to_le_bytes());
put(0x98 + 24, &0x1_4000_0000u64.to_le_bytes());
put(0x98 + 32, &0x1000u32.to_le_bytes());
put(0x98 + 36, &0x200u32.to_le_bytes());
put(0x98 + 56, &0x2000u32.to_le_bytes());
put(0x98 + 60, &0x200u32.to_le_bytes());
put(0x98 + 108, &16u32.to_le_bytes());
let section = 0x98 + 240;
put(section, b".text");
put(section + 8, &0x200u32.to_le_bytes());
put(section + 12, &(ENTRY as u32).to_le_bytes());
put(section + 16, &0x200u32.to_le_bytes());
put(section + 20, &0x200u32.to_le_bytes());
put(section + 36, &0x6000_0020u32.to_le_bytes());
put(0x200, code);
put(0x200 + code.len(), &[0xF4]);
pe
}
+10 -10
View File
@@ -222,7 +222,7 @@ fn trusted_runner_callback_and_report_match_the_fixture() {
);
assert_eq!(callback[1].bytes, [0x48, 0xc7, 0, 17, 0, 0, 0]);
assert!(callback[1].is_supported_dbt);
assert!(!callback[1].is_supported_interp);
assert!(callback[1].is_supported_interp);
assert!(report.first_unsupported_dbt_insn.is_none());
assert!(md.contains("Sections Census (4)"));
assert!(json.contains("\"sections_count\": 4"));
@@ -237,14 +237,14 @@ fn trusted_runner_callback_and_report_match_the_fixture() {
}
#[test]
fn probe_consumes_complete_c7_operands_even_when_native_support_is_missing() {
for (encoding, supported) in [
(&[0x48, 0xc7, 0x05, 0, 0, 0, 0, 17, 0, 0, 0][..], true),
(&[0xc7, 0xc0, 17, 0, 0, 0], true),
(&[0x66, 0xc7, 0xc0, 17, 0], false),
(&[0xc7, 0x00, 17, 0, 0, 0], false),
(&[0x48, 0xc7, 0x40, 4, 17, 0, 0, 0], false),
(&[0x48, 0xc7, 0x04, 0x25, 0, 0, 0, 0, 17, 0, 0, 0], false),
fn probe_consumes_complete_c7_operands_and_reports_their_support() {
for encoding in [
&[0x48, 0xc7, 0x05, 0, 0, 0, 0, 17, 0, 0, 0][..],
&[0xc7, 0xc0, 17, 0, 0, 0],
&[0x66, 0xc7, 0xc0, 17, 0],
&[0xc7, 0x00, 17, 0, 0, 0],
&[0x48, 0xc7, 0x40, 4, 17, 0, 0, 0],
&[0x48, 0xc7, 0x04, 0x25, 0, 0, 0, 0, 17, 0, 0, 0],
] {
let mut pe = create_synthetic_probe_pe();
let end = 0x200 + encoding.len();
@@ -254,7 +254,7 @@ fn probe_consumes_complete_c7_operands_even_when_native_support_is_missing() {
let records = report.instruction_records;
assert_eq!(records.len(), 2);
assert_eq!(records[0].bytes, encoding);
assert_eq!(records[0].is_supported_dbt, supported);
assert!(records[0].is_supported_dbt && records[0].is_supported_interp);
assert_eq!(records[1].rva, 0x1000 + encoding.len() as u32);
assert!(!records[1].is_supported_dbt);
}
+18
View File
@@ -0,0 +1,18 @@
use xenora_loader::probe::{ProbeConfig, probe_pe_bytes};
/// The static probe must never panic on a truncated PE.
///
/// The fixture is truncated across its whole length, which covers the range
/// where the import directory and the import names overlap the end of the
/// file, and every other range where a name or thunk read computed from the
/// section header can run past the buffer.
#[test]
fn probe_never_panics_on_truncated_input() {
let pe = include_bytes!("../../../fixtures/pe/trusted-runner.exe");
for len in 1..=pe.len() {
let truncated = &pe[..len];
// The probe may reject the file or report it with unreadable
// imports, but it must not panic.
let _ = probe_pe_bytes(truncated, &ProbeConfig::default());
}
}
+981
View File
@@ -0,0 +1,981 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Typed runtime services, called by translated guest code through a bound
//! import table, and the import parser and registry behind them.
//!
//! Expected values come from the public Win32, ISO C and Microsoft x64 calling
//! convention documentation, not from the registry or the handlers.
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use xenora_loader::cpu::{CpuState, ExitReason, Register};
use xenora_loader::dbt::DbtEngine;
use xenora_loader::import_table::{ImportName, ImportTableError, MAX_IMPORTS, parse_imports};
use xenora_loader::imports::{
ImportError, ImportRegistry, RegistryError, ServiceStatus, Win64Args,
};
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
use xenora_loader::pe::ParsedPe;
use xenora_loader::probe::{ProbeConfig, ProbeReport, probe_pe_bytes};
use xenora_loader::runtime::{Call, Float32, Float64};
use xenora_loader::runtime_table::SERVICES;
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
const BASE: u64 = 0x1_4000_0000;
const CODE_RVA: u32 = 0x1000;
const IDATA_RVA: u32 = 0x10000;
const IDATA_RAW: usize = 0x2200;
const IDATA_LEN: usize = 0x4000;
const SCRATCH: u64 = 0x5_0000;
const STACK: u64 = 0x8_0000;
const STACK_TOP: u64 = STACK + 0x800;
#[derive(Clone)]
enum Symbol {
Name(&'static str),
Ordinal(u16),
}
/// Original PE32+ image importing `imports`, one descriptor each. The code for
/// import `n`, at RVA 0x1000 + 16n, is `call [its slot]; hlt`.
struct Image {
bytes: Vec<u8>,
slots: Vec<u32>,
}
fn build(imports: &[(&str, Symbol)]) -> Image {
let mut pe = vec![0u8; IDATA_RAW + IDATA_LEN];
fn put(pe: &mut [u8], at: usize, bytes: &[u8]) {
pe[at..at + bytes.len()].copy_from_slice(bytes);
}
put(&mut pe, 0, b"MZ");
put(&mut pe, 0x3C, &0x80u32.to_le_bytes());
put(&mut pe, 0x80, b"PE\0\0");
put(&mut pe, 0x84, &0x8664u16.to_le_bytes());
put(&mut pe, 0x86, &2u16.to_le_bytes());
put(&mut pe, 0x94, &240u16.to_le_bytes());
let optional = 0x98;
put(&mut pe, optional, &0x20Bu16.to_le_bytes());
put(&mut pe, optional + 16, &CODE_RVA.to_le_bytes());
put(&mut pe, optional + 24, &BASE.to_le_bytes());
put(&mut pe, optional + 32, &0x1000u32.to_le_bytes());
put(&mut pe, optional + 36, &0x200u32.to_le_bytes());
put(&mut pe, optional + 56, &0x20000u32.to_le_bytes());
put(&mut pe, optional + 60, &0x200u32.to_le_bytes());
put(&mut pe, optional + 108, &16u32.to_le_bytes());
put(&mut pe, optional + 120, &IDATA_RVA.to_le_bytes());
put(&mut pe, optional + 124, &0x100u32.to_le_bytes());
for (index, (name, rva, raw, len, flags)) in [
(b".text", CODE_RVA, 0x200, 0x2000, 0x6000_0020u32),
(b".idat", IDATA_RVA, IDATA_RAW, IDATA_LEN, 0xC000_0040),
]
.into_iter()
.enumerate()
{
let section = optional + 240 + 40 * index;
put(&mut pe, section, name);
put(&mut pe, section + 8, &(len as u32).to_le_bytes());
put(&mut pe, section + 12, &rva.to_le_bytes());
put(&mut pe, section + 16, &(len as u32).to_le_bytes());
put(&mut pe, section + 20, &(raw as u32).to_le_bytes());
put(&mut pe, section + 36, &flags.to_le_bytes());
}
let file = |rva: u32| IDATA_RAW + (rva - IDATA_RVA) as usize;
let mut next = IDATA_RVA + 20 * (imports.len() as u32 + 1);
let mut take = |len: usize| {
let rva = next;
next = (next + len as u32 + 7) & !7;
rva
};
let mut slots = Vec::new();
for (index, (module, symbol)) in imports.iter().enumerate() {
let module_rva = take(module.len() + 1);
put(&mut pe, file(module_rva), module.as_bytes());
let entry = match symbol {
Symbol::Ordinal(ordinal) => 1 << 63 | u64::from(*ordinal),
Symbol::Name(name) => {
let hint = take(name.len() + 3);
put(&mut pe, file(hint) + 2, name.as_bytes());
u64::from(hint)
}
};
let (lookup, slot) = (take(16), take(16));
put(&mut pe, file(lookup), &entry.to_le_bytes());
put(&mut pe, file(slot), &entry.to_le_bytes());
let descriptor = file(IDATA_RVA) + 20 * index;
put(&mut pe, descriptor, &lookup.to_le_bytes());
put(&mut pe, descriptor + 12, &module_rva.to_le_bytes());
put(&mut pe, descriptor + 16, &slot.to_le_bytes());
slots.push(slot);
let code_rva = CODE_RVA + 16 * index as u32;
let displacement = slot.wrapping_sub(code_rva + 6);
let at = 0x200 + 16 * index;
put(&mut pe, at, &[0xFF, 0x15]); // call qword ptr [rip + displacement]
put(&mut pe, at + 2, &displacement.to_le_bytes());
put(&mut pe, at + 6, &[0xF4]); // hlt
}
Image { bytes: pe, slots }
}
fn standard(clock: u64) -> (ImportRegistry, Arc<MockClock>) {
let clock = Arc::new(MockClock::new(clock));
let mut registry = ImportRegistry::new();
register_standard_services(&mut registry, Arc::new(ServicesState::new(clock.clone())));
(registry, clock)
}
/// A guest whose image imports every generated service from its own library.
struct Guest {
engine: DbtEngine,
memory: GuestMemory,
clock: Arc<MockClock>,
/// Upper halves and XMM lanes of unrelated arguments hold this pattern.
xmm: [u128; 4],
}
impl Guest {
fn new() -> Self {
let imports: Vec<(&str, Symbol)> = SERVICES
.iter()
.map(|service| (service.library, Symbol::Name(service.symbol)))
.collect();
let image = build(&imports);
let pe = ParsedPe::parse(&image.bytes).unwrap();
let mut memory = pe.load_into_memory(&image.bytes).unwrap().memory;
memory
.map_region(SCRATCH, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
memory
.map_region(STACK, 0x1000, MemoryPermissions::READ_WRITE)
.unwrap();
let (mut registry, clock) = standard(0x01DA_0000_1234_5678);
let bound = registry
.bind_imports(&pe, &image.bytes, BASE, &mut memory)
.unwrap();
assert_eq!(bound, SERVICES.len());
let mut engine = DbtEngine::new(256 * 1024).unwrap();
engine.set_import_registry(registry);
Self {
engine,
memory,
clock,
xmm: [0xAAAA_BBBB_CCCC_DDDD_EEEE_FFFF_0123_4567; 4],
}
}
fn run(&mut self, symbol: &str, args: &[u64]) -> (CpuState, ExitReason) {
let index = SERVICES
.iter()
.position(|service| service.symbol == symbol)
.unwrap();
let mut cpu = CpuState::new(BASE + u64::from(CODE_RVA) + 16 * index as u64, STACK_TOP);
for (index, register) in cpu.gpr.iter_mut().enumerate() {
if index != Register::Rsp as usize {
*register = 0x0101_0101_0101_0101 * (index as u64 + 1);
}
}
for (register, value) in [Register::Rcx, Register::Rdx, Register::R8, Register::R9]
.into_iter()
.zip(args)
{
cpu.set(register, *value);
}
for (index, register) in cpu.xmm.iter_mut().enumerate() {
*register = 0x1111_2222_3333_4444_5555_6666_7777_0000 + index as u128;
}
cpu.xmm[..4].copy_from_slice(&self.xmm);
let before = cpu.clone();
let result = self.engine.run(&mut cpu, &mut self.memory, 8);
if result.exit_reason == ExitReason::Halt {
use Register::{R12, R13, R14, R15, Rbp, Rbx, Rdi, Rsi, Rsp};
for register in [Rbx, Rbp, Rdi, Rsi, Rsp, R12, R13, R14, R15] {
assert_eq!(
cpu.get(register),
before.get(register),
"{symbol} {register:?}"
);
}
assert_eq!(cpu.xmm[6..], before.xmm[6..], "{symbol}");
assert_eq!(cpu.mxcsr, before.mxcsr, "{symbol}");
}
(cpu, result.exit_reason)
}
fn call(&mut self, symbol: &str, args: &[u64]) -> u64 {
let (cpu, exit) = self.run(symbol, args);
assert_eq!(exit, ExitReason::Halt, "{symbol}");
cpu.get(Register::Rax)
}
fn last_error(&mut self) -> u64 {
self.call("GetLastError", &[])
}
}
const PROCESS: u64 = u64::MAX;
const THREAD: u64 = u64::MAX - 1;
#[test]
fn identity_services_return_documented_pseudo_handles_and_ids() {
let mut guest = Guest::new();
assert_eq!(guest.call("GetCurrentProcess", &[]), PROCESS);
assert_eq!(guest.call("GetCurrentThread", &[]), THREAD);
let id = guest.call("GetCurrentProcessId", &[]);
assert!(id != 0 && id <= u64::from(u32::MAX));
assert_ne!(guest.call("GetCurrentThreadId", &[]), id);
assert_eq!(guest.call("GetProcessId", &[PROCESS]), id);
assert_eq!(guest.call("GetProcessId", &[THREAD]), 0);
assert_eq!(guest.last_error(), 6); // ERROR_INVALID_HANDLE
}
#[test]
fn priority_boost_round_trips_and_checks_its_handle() {
let mut guest = Guest::new();
let read = |guest: &mut Guest| {
guest.memory.write_u64(SCRATCH, u64::MAX).unwrap();
assert_eq!(
guest.call("GetProcessPriorityBoost", &[PROCESS, SCRATCH]),
1
);
// A BOOL is four bytes; the next four stay untouched.
assert_eq!(guest.memory.read_u32(SCRATCH + 4).unwrap(), u32::MAX);
guest.memory.read_u32(SCRATCH).unwrap()
};
assert_eq!(read(&mut guest), 0);
// Any nonzero BOOL disables; bits above 32 are not part of the argument.
assert_eq!(
guest.call("SetProcessPriorityBoost", &[PROCESS, 0xFFFF_FFFF_0000_0002]),
1
);
assert_eq!(read(&mut guest), 1);
assert_eq!(
guest.call("SetProcessPriorityBoost", &[PROCESS, 0xFFFF_FFFF_0000_0000]),
1
);
assert_eq!(read(&mut guest), 0);
assert_eq!(guest.call("SetProcessPriorityBoost", &[THREAD, 1]), 0);
assert_eq!(guest.last_error(), 6);
assert_eq!(
guest.call("GetProcessPriorityBoost", &[PROCESS, 0x9000_0000]),
0
);
assert_eq!(guest.last_error(), 998); // ERROR_NOACCESS
}
#[test]
fn thread_handles_check_access_and_are_rejected_once_closed() {
let mut guest = Guest::new();
let id = guest.call("GetCurrentThreadId", &[]);
// THREAD_QUERY_INFORMATION only.
let query = guest.call("OpenThread", &[0x40, 0, id]);
assert_ne!(query, 0);
assert_eq!(guest.call("GetThreadPriority", &[query]), 0);
assert_eq!(guest.call("SetThreadPriority", &[query, 1]), 0);
assert_eq!(guest.last_error(), 5); // ERROR_ACCESS_DENIED
assert_eq!(guest.call("GetThreadPriority", &[query]), 0);
// THREAD_SET_INFORMATION | THREAD_QUERY_INFORMATION.
let full = guest.call("OpenThread", &[0x60, 0, id]);
assert_ne!(full, query);
// A negative int is returned in EAX with the upper half clear.
assert_eq!(
guest.call("SetThreadPriority", &[full, 0xABCD_0000_FFFF_FFFE]),
1
);
assert_eq!(guest.call("GetThreadPriority", &[full]), 0xFFFF_FFFE);
assert_eq!(guest.call("SetThreadPriority", &[full, 3]), 0);
assert_eq!(guest.last_error(), 87); // ERROR_INVALID_PARAMETER
assert_eq!(guest.call("CloseHandle", &[full]), 1);
assert_eq!(guest.call("GetThreadPriority", &[full]), 0x7FFF_FFFF);
assert_eq!(guest.last_error(), 6);
assert_eq!(guest.call("CloseHandle", &[full]), 0);
assert_eq!(guest.call("OpenThread", &[0x40, 0, id + 1]), 0);
assert_eq!(guest.last_error(), 87);
assert_eq!(guest.call("OpenThread", &[0x40, 1, id]), 0);
assert_eq!(guest.last_error(), 50); // ERROR_NOT_SUPPORTED
assert_ne!(
guest.call("OpenThread", &[0x40, 0, id]),
full,
"handles are not reused"
);
}
#[test]
fn system_time_comes_from_the_injected_clock() {
let mut guest = Guest::new();
guest.call("GetSystemTimeAsFileTime", &[SCRATCH + 3]);
assert_eq!(
guest.memory.read_u64(SCRATCH + 3).unwrap(),
0x01DA_0000_1234_5678
);
guest.clock.advance(10);
guest.call("GetSystemTimeAsFileTime", &[SCRATCH]);
assert_eq!(
guest.memory.read_u64(SCRATCH).unwrap(),
0x01DA_0000_1234_5682
);
for pointer in [0, SCRATCH + 0xFC] {
let before = guest.memory.read_u32(SCRATCH + 0xFC).unwrap();
let (_, exit) = guest.run("GetSystemTimeAsFileTime", &[pointer]);
assert!(matches!(exit, ExitReason::MemoryFault(_)), "{exit:?}");
assert_eq!(guest.memory.read_u32(SCRATCH + 0xFC).unwrap(), before);
}
}
#[test]
fn last_error_is_set_by_failures_and_by_the_guest() {
let mut guest = Guest::new();
assert_eq!(guest.last_error(), 0);
guest.call("SetLastError", &[0xFFFF_FFFF_8000_0001]);
assert_eq!(guest.last_error(), 0x8000_0001);
assert_eq!(guest.call("GetCurrentProcess", &[]), PROCESS);
assert_eq!(
guest.last_error(),
0x8000_0001,
"success leaves it unchanged"
);
guest.call("CloseHandle", &[0x1234]);
assert_eq!(guest.last_error(), 6);
}
#[test]
fn virtual_memory_is_mapped_released_and_bounded() {
let mut guest = Guest::new();
const COMMIT_RESERVE: u64 = 0x3000;
const RELEASE: u64 = 0x8000;
let address = guest.call("VirtualAlloc", &[0, 5000, COMMIT_RESERVE, 0x04]);
assert!(address != 0 && address.is_multiple_of(0x1_0000));
assert_eq!(
guest.memory.read_u64(address + 8184).unwrap(),
0,
"zeroed, whole pages"
);
assert!(guest.memory.read_u8(address + 8192).is_err());
guest.memory.write_u64(address, 7).unwrap();
for (args, error) in [
([0, 0, COMMIT_RESERVE, 0x04], 87),
([0, 4096, 0x1000, 0x04], 50),
([0, 4096, COMMIT_RESERVE, 0x40], 87),
([address, 4096, COMMIT_RESERVE, 0x04], 487),
([0, u64::MAX, COMMIT_RESERVE, 0x04], 87),
([0, 1 << 40, COMMIT_RESERVE, 0x04], 8),
] {
assert_eq!(guest.call("VirtualAlloc", &args), 0, "{args:x?}");
assert_eq!(guest.last_error(), error, "{args:x?}");
}
for (args, error) in [
([address, 4096, RELEASE], 87),
([address, 0, 0x4000], 50),
([address + 4096, 0, RELEASE], 487),
] {
assert_eq!(guest.call("VirtualFree", &args), 0, "{args:x?}");
assert_eq!(guest.last_error(), error, "{args:x?}");
}
assert_eq!(guest.call("VirtualFree", &[address, 0, RELEASE]), 1);
assert!(guest.memory.read_u8(address).is_err());
assert_eq!(guest.call("VirtualFree", &[address, 0, RELEASE]), 0);
}
#[test]
fn floating_arguments_and_results_use_xmm_registers() {
let mut guest = Guest::new();
let mut float = |symbol: &str, bits: u64| {
// Only the low lane is the argument, and RCX must be ignored.
guest.xmm[0] = 0xFFFF_FFFF_FFFF_FFFF << 64 | u128::from(bits);
let (cpu, exit) = guest.run(symbol, &[0x4022_0000_0000_0000]);
assert_eq!(exit, ExitReason::Halt);
cpu.xmm[0]
};
assert_eq!(
float("sqrt", 0x4030_0000_0000_0000) as u64,
0x4010_0000_0000_0000
); // 16 -> 4
assert_eq!(
float("sqrt", 0x4000_0000_0000_0000) as u64,
0x3FF6_A09E_667F_3BCD
); // sqrt 2
assert_eq!(
float("sqrt", 0x8000_0000_0000_0000) as u64,
0x8000_0000_0000_0000
); // -0
assert_eq!(
float("sqrt", 0x7FF0_0000_0000_0000) as u64,
0x7FF0_0000_0000_0000
);
let nan = float("sqrt", 0xBFF0_0000_0000_0000) as u64;
assert!(f64::from_bits(nan).is_nan());
assert_eq!(
float("fabs", 0xC004_0000_0000_0000) as u64,
0x4004_0000_0000_0000
); // -2.5
assert_eq!(float("fabs", 0x8000_0000_0000_0000) as u64, 0);
let garbage = 0xDEAD_BEEF_0000_0000;
assert_eq!(float("sqrtf", garbage | 0x4110_0000) as u32, 0x4040_0000); // 9 -> 3
assert_eq!(float("fabsf", garbage | 0xBF80_0000) as u32, 0x3F80_0000); // -1
}
#[test]
fn arguments_are_assigned_by_position_and_read_the_stack_after_the_fourth() {
let mut memory = GuestMemory::new();
memory
.map_region(STACK, 0x1000, MemoryPermissions::READ_WRITE)
.unwrap();
// [RSP] return address, 32 bytes of shadow space, then arguments 4 and 5.
memory
.write_u64(STACK_TOP + 40, 0x1122_3344_5566_7788)
.unwrap();
memory
.write_u64(STACK_TOP + 48, 0x4008_0000_0000_0000)
.unwrap();
let mut cpu = CpuState::new(0, STACK_TOP);
for (index, register) in [Register::Rcx, Register::Rdx, Register::R8, Register::R9]
.into_iter()
.enumerate()
{
cpu.set(register, 0xFFFF_FFFF_0000_0010 + index as u64);
cpu.xmm[index] = (1 << 100) + 0xAAAA_AAAA_0000_0020 + index as u128;
}
let args = Win64Args::new(&cpu);
let call = Call::new(&args, &cpu, &memory);
assert_eq!(call.u32(0), Ok(0x10));
assert_eq!(call.f64(1), Ok(Float64(0xAAAA_AAAA_0000_0021)));
assert_eq!(call.f32(2), Ok(Float32(0x22)));
assert_eq!(call.u64(3), Ok(0xFFFF_FFFF_0000_0013));
assert_eq!(call.i32(4), Ok(0x5566_7788));
assert_eq!(call.f64(5), Ok(Float64(0x4008_0000_0000_0000)));
cpu.set(Register::Rsp, STACK + 0xFF0);
let args = Win64Args::new(&cpu);
let call = Call::new(&args, &cpu, &memory);
assert!(matches!(call.u64(4), Err(ExitReason::MemoryFault(_))));
cpu.set(Register::Rsp, u64::MAX - 8);
let args = Win64Args::new(&cpu);
assert!(Call::new(&args, &cpu, &memory).f64(4).is_err());
}
// --- registry ----------------------------------------------------------------
fn named(name: &str) -> ImportName {
ImportName::Name(name.to_owned())
}
#[test]
fn generated_metadata_matches_the_live_registry() {
let (registry, _) = standard(0);
for service in &SERVICES {
let descriptor = registry
.resolve(service.library, &named(service.symbol))
.unwrap();
assert_eq!(descriptor.status, service.status, "{}", service.symbol);
assert!(!service.tests.is_empty());
for alias in service.aliases {
let upper = alias.to_ascii_uppercase();
let aliased = registry.resolve(&upper, &named(service.symbol)).unwrap();
assert!(
std::ptr::eq(aliased, descriptor),
"{alias}!{}",
service.symbol
);
}
// Symbol names are exact, and unlisted API sets do not resolve.
assert!(
registry
.resolve(
service.library,
&named(&service.symbol.to_ascii_uppercase())
)
.is_none()
|| service.symbol == service.symbol.to_ascii_uppercase()
);
assert!(
registry
.resolve("api-ms-win-core-file-l1-1-0.dll", &named(service.symbol))
.is_none()
);
}
}
#[test]
fn conflicting_or_invalid_registrations_are_refused() {
let handler = || Box::new(|_: &Win64Args, _: &mut CpuState, _: &mut GuestMemory| Ok(0));
let mut registry = ImportRegistry::new();
let mut add = |module: &str, name: ImportName| {
registry.try_register(module, name, ServiceStatus::Stub, handler())
};
assert_eq!(add("a.dll", named("F")), Ok(()));
assert_eq!(
add("a.dll", named("f")),
Ok(()),
"symbols are case-sensitive"
);
assert_eq!(add("b.dll", named("F")), Ok(()));
assert!(matches!(
add("A.DLL", named("F")),
Err(RegistryError::Duplicate { .. })
));
assert_eq!(add("a.dll", ImportName::Ordinal(7)), Ok(()));
assert!(matches!(
add("a.dll", ImportName::Ordinal(7)),
Err(RegistryError::Duplicate { .. })
));
assert_eq!(
add("a.dll", named("Ordinal#7")),
Ok(()),
"a name is never an ordinal"
);
for (module, symbol) in [("", "F"), ("a.dll", ""), ("a b.dll", "F"), ("a.dll", "F\n")] {
assert!(matches!(
add(module, named(symbol)),
Err(RegistryError::InvalidName { .. })
));
}
assert_eq!(registry.try_alias("set.dll", "a.dll", "F"), Ok(()));
assert_eq!(
registry.try_alias("set.dll", "a.dll", "F"),
Ok(()),
"repeating is harmless"
);
assert!(matches!(
registry.try_alias("set.dll", "b.dll", "F"),
Err(RegistryError::Duplicate { .. })
));
assert!(matches!(
registry.try_alias("b.dll", "a.dll", "F"),
Err(RegistryError::Duplicate { .. })
));
assert!(matches!(
registry.try_alias("x.dll", "a.dll", "G"),
Err(RegistryError::UnknownTarget { .. })
));
}
#[test]
#[should_panic(expected = "kernel32.dll!CloseHandle is already registered")]
fn a_host_module_cannot_replace_a_standard_service() {
let (mut registry, _) = standard(0);
registry.register("KERNEL32.dll", "CloseHandle", |_, _, _| Ok(1));
}
fn bind(registry: &mut ImportRegistry, image: &Image) -> (Result<usize, ImportError>, GuestMemory) {
let pe = ParsedPe::parse(&image.bytes).unwrap();
let mut memory = pe.load_into_memory(&image.bytes).unwrap().memory;
let result = registry.bind_imports(&pe, &image.bytes, BASE, &mut memory);
(result, memory)
}
#[test]
fn an_unresolved_import_leaves_every_slot_unbound() {
let image = build(&[
("kernel32.dll", Symbol::Name("GetLastError")),
("kernel32.dll", Symbol::Name("NoSuchFunction")),
]);
let (mut registry, _) = standard(0);
let (result, memory) = bind(&mut registry, &image);
let expected = ImportError::UnresolvedImport {
module: "kernel32.dll".into(),
symbol: "NoSuchFunction".into(),
};
assert_eq!(result, Err(expected));
for slot in &image.slots {
let file = IDATA_RAW + (slot - IDATA_RVA) as usize;
let original = u64::from_le_bytes(image.bytes[file..file + 8].try_into().unwrap());
assert_eq!(memory.read_u64(BASE + u64::from(*slot)).unwrap(), original);
}
}
#[test]
fn aliases_share_a_trampoline_and_ordinals_bind_only_ordinals() {
let (mut registry, _) = standard(0);
registry
.try_register(
"o.dll",
ImportName::Ordinal(7),
ServiceStatus::Partial,
Box::new(|_, _, _| Ok(77)),
)
.unwrap();
let image = build(&[
("KERNEL32.dll", Symbol::Name("GetLastError")),
(
"API-MS-Win-Core-ErrorHandling-L1-1-0.dll",
Symbol::Name("GetLastError"),
),
("O.DLL", Symbol::Ordinal(7)),
]);
let (result, memory) = bind(&mut registry, &image);
assert_eq!(result, Ok(3));
let slot = |index: usize| {
memory
.read_u64(BASE + u64::from(image.slots[index]))
.unwrap()
};
assert_eq!(slot(0), slot(1));
assert_ne!(slot(0), slot(2));
for symbol in [Symbol::Name("Ordinal#7"), Symbol::Ordinal(8)] {
let (result, _) = bind(&mut registry, &build(&[("o.dll", symbol)]));
assert!(
matches!(result, Err(ImportError::UnresolvedImport { .. })),
"{result:?}"
);
}
}
/// A registry with one service bound, and its trampoline address.
fn bound_service<F>(handler: F) -> (ImportRegistry, GuestMemory, u64)
where
F: Fn(&Win64Args, &mut CpuState, &mut GuestMemory) -> Result<u64, ExitReason>
+ Send
+ Sync
+ 'static,
{
let mut registry = ImportRegistry::new();
registry.register("t.dll", "F", handler);
let image = build(&[("t.dll", Symbol::Name("F"))]);
let (result, mut memory) = bind(&mut registry, &image);
assert_eq!(result, Ok(1));
memory
.map_region(STACK, 0x1000, MemoryPermissions::READ_WRITE)
.unwrap();
memory.write_u64(STACK_TOP, 0x1234).unwrap();
let trampoline = memory.read_u64(BASE + u64::from(image.slots[0])).unwrap();
(registry, memory, trampoline)
}
#[test]
fn a_service_that_changes_a_nonvolatile_register_stops_the_guest() {
use Register::{R8, R9, R10, R11, R12, R13, R14, R15, Rbp, Rbx, Rcx, Rdi, Rdx, Rsi, Rsp};
let dispatch = |change: fn(&mut CpuState, usize), which: usize| {
let (registry, mut memory, trampoline) = bound_service(move |_, cpu, _| {
change(cpu, which);
Ok(5)
});
let mut cpu = CpuState::new(trampoline, STACK_TOP);
let result = registry.dispatch(trampoline, &mut cpu, &mut memory);
(result, cpu)
};
for register in [Rbx, Rbp, Rdi, Rsi, Rsp, R12, R13, R14, R15] {
let (result, _) = dispatch(|cpu, index| cpu.gpr[index] ^= 8, register as usize);
assert_eq!(result, Err(ExitReason::ServiceAbiViolation), "{register:?}");
}
for register in [Rcx, Rdx, R8, R9, R10, R11] {
let (result, cpu) = dispatch(|cpu, index| cpu.gpr[index] ^= 8, register as usize);
assert_eq!(result, Ok(()), "{register:?}");
assert_eq!(
(cpu.rip, cpu.get(Rsp), cpu.get(Register::Rax)),
(0x1234, STACK_TOP + 8, 5)
);
}
for index in 0..16 {
let (result, _) = dispatch(|cpu, index| cpu.xmm[index] ^= 1 << 127, index);
let expected = if index < 6 {
Ok(())
} else {
Err(ExitReason::ServiceAbiViolation)
};
assert_eq!(result, expected, "xmm{index}");
}
}
#[test]
fn a_call_that_cannot_return_runs_no_service() {
let calls = Arc::new(AtomicUsize::new(0));
let counter = calls.clone();
let (registry, mut memory, trampoline) = bound_service(move |_, _, _| {
counter.fetch_add(1, Ordering::SeqCst);
Ok(0)
});
for rsp in [0x9000_0000, STACK + 0xFFC, u64::MAX - 7] {
let mut cpu = CpuState::new(trampoline, rsp);
let before = cpu.clone();
assert!(
registry
.dispatch(trampoline, &mut cpu, &mut memory)
.is_err()
);
assert_eq!(cpu, before);
}
assert_eq!(calls.load(Ordering::SeqCst), 0);
let mut cpu = CpuState::new(trampoline, STACK_TOP);
assert_eq!(registry.dispatch(trampoline, &mut cpu, &mut memory), Ok(()));
assert_eq!(calls.load(Ordering::SeqCst), 1);
}
// --- import table --------------------------------------------------------------
fn inspect(image: &Image) -> ProbeReport {
probe_pe_bytes(&image.bytes, &ProbeConfig::default()).unwrap()
}
/// File offset of an RVA in the import section.
fn file(rva: u32) -> usize {
IDATA_RAW + (rva - IDATA_RVA) as usize
}
fn u32_at(image: &Image, at: usize) -> u32 {
u32::from_le_bytes(image.bytes[at..at + 4].try_into().unwrap())
}
#[test]
fn malformed_import_tables_are_reported_and_never_bound() {
let base = || {
build(&[
("kernel32.dll", Symbol::Name("GetLastError")),
("kernel32.dll", Symbol::Name("CloseHandle")),
])
};
let end = IDATA_RVA + IDATA_LEN as u32;
let second = IDATA_RAW + 20;
type Damage = fn(&mut Image, usize, u32);
type Expected = fn(&ImportTableError) -> bool;
// (damage to the second descriptor, expected error)
let cases: &[(&str, Damage, Expected)] = &[
(
"name runs off the section (issue #270)",
|image, second, end| {
let lookup = u32_at(image, second);
image.bytes[file(lookup)..file(lookup) + 8]
.copy_from_slice(&u64::from(end - 6).to_le_bytes());
let at = file(end - 4);
image.bytes[at..at + 4].copy_from_slice(b"Name");
},
|error| matches!(error, ImportTableError::MalformedName { .. }),
),
(
"name pointer at the last byte",
|image, second, end| {
let lookup = u32_at(image, second);
image.bytes[file(lookup)..file(lookup) + 8]
.copy_from_slice(&u64::from(end - 1).to_le_bytes());
},
|error| matches!(error, ImportTableError::MalformedName { .. }),
),
(
"empty name",
|image, second, _| {
let lookup = u32_at(image, second);
let hint = u32_at(image, file(lookup));
image.bytes[file(hint) + 2] = 0;
},
|error| matches!(error, ImportTableError::MalformedName { .. }),
),
(
"non-ASCII name",
|image, second, _| {
let lookup = u32_at(image, second);
let hint = u32_at(image, file(lookup));
image.bytes[file(hint) + 4] = 0xC3;
},
|error| matches!(error, ImportTableError::MalformedName { .. }),
),
(
"module name outside every section",
|image, second, _| {
image.bytes[second + 12..second + 16].copy_from_slice(&0x7000_0000u32.to_le_bytes())
},
|error| matches!(error, ImportTableError::MalformedName { .. }),
),
(
"lookup table outside every section",
|image, second, _| {
image.bytes[second..second + 4].copy_from_slice(&u32::MAX.to_le_bytes())
},
|error| matches!(error, ImportTableError::OutOfBounds { .. }),
),
(
"reserved bits in a name entry",
|image, second, _| {
let lookup = u32_at(image, second);
image.bytes[file(lookup) + 5] = 1;
},
|error| matches!(error, ImportTableError::ReservedBits { .. }),
),
(
"bit 31 in a name entry",
|image, second, _| {
let lookup = u32_at(image, second);
image.bytes[file(lookup) + 3] |= 0x80;
},
|error| matches!(error, ImportTableError::ReservedBits { .. }),
),
(
"name continues in bytes after the section",
|image, second, end| {
let lookup = u32_at(image, second);
image.bytes[file(lookup)..file(lookup) + 8]
.copy_from_slice(&u64::from(end - 6).to_le_bytes());
let at = file(end - 4);
image.bytes[at..at + 4].copy_from_slice(b"Name");
image.bytes.extend_from_slice(b"Tail\0");
},
|error| matches!(error, ImportTableError::MalformedName { .. }),
),
(
"reserved bits in an ordinal entry",
|image, second, _| {
let lookup = u32_at(image, second);
image.bytes[file(lookup)..file(lookup) + 8]
.copy_from_slice(&(1u64 << 63 | 0x1_0000).to_le_bytes());
},
|error| matches!(error, ImportTableError::ReservedBits { .. }),
),
];
for (what, damage, expected) in cases {
let mut image = base();
damage(&mut image, second, end);
let (mut registry, _) = standard(0);
let (result, _) = bind(&mut registry, &image);
match &result {
Err(ImportError::Table(error)) => assert!(expected(error), "{what}: {error:?}"),
other => panic!("{what}: {other:?}"),
}
let report = inspect(&image);
assert_eq!(
report.import_error.map(ImportError::Table),
result.err(),
"{what}"
);
assert_eq!(
report.imports.len(),
1,
"{what}: the first import is still listed"
);
assert_eq!(report.imports[0].symbol, "GetLastError");
}
}
#[test]
fn endless_tables_are_bounded() {
// A descriptor at 0, a module name at 0x40, a hint and name at 0x60 and a
// lookup entry at 0x80. The mapping repeats one structure without end.
let mut bytes = vec![0u8; 0x88];
bytes[0..4].copy_from_slice(&0x80u32.to_le_bytes());
bytes[12..16].copy_from_slice(&0x40u32.to_le_bytes());
bytes[16..20].copy_from_slice(&0x80u32.to_le_bytes());
bytes[0x40..0x46].copy_from_slice(b"m.dll\0");
bytes[0x62..0x64].copy_from_slice(b"F\0");
bytes[0x80] = 0x60;
// Lookup entries repeat from 0x80 on.
let (entries, error) = parse_imports(&bytes, 0, |rva| {
let rva = rva as usize;
Some(if rva < 0x80 { rva } else { 0x80 + rva % 8 })
});
assert_eq!(error, Some(ImportTableError::TooManyImports));
assert_eq!(entries.len(), MAX_IMPORTS);
// Descriptors repeat from 0x1000 on; each has one symbol.
bytes.extend([0; 8]);
let (entries, error) = parse_imports(&bytes, 0x1000, |rva| {
let rva = rva as usize;
Some(if rva < 0x1000 {
rva
} else {
(rva - 0x1000) % 20
})
});
assert_eq!(error, Some(ImportTableError::TooManyDescriptors));
assert_eq!(entries.len(), 1024);
}
#[test]
fn inspection_and_binding_agree_on_damaged_tables() {
let base = build(&[
("kernel32.dll", Symbol::Name("GetLastError")),
(
"api-ms-win-core-handle-l1-1-0.dll",
Symbol::Name("CloseHandle"),
),
("ucrtbase.dll", Symbol::Name("sqrt")),
("o.dll", Symbol::Ordinal(3)),
]);
let mut state = 0x2545_F491_4F6C_DD1Du64;
let mut next = || {
state ^= state >> 12;
state ^= state << 25;
state ^= state >> 27;
state.wrapping_mul(0x9E37_79B9_7F4A_7C15)
};
let (mut bound, mut malformed, mut unresolved) = (0, 0, 0);
for _ in 0..6000 {
let mut image = Image {
bytes: base.bytes.clone(),
slots: base.slots.clone(),
};
for _ in 0..1 + next() % 3 {
let at = IDATA_RAW + (next() % 0x220) as usize;
image.bytes[at] = match next() % 4 {
0 => 0,
1 => 0xFF,
_ => next() as u8,
};
}
let (mut registry, _) = standard(0);
registry
.try_register(
"o.dll",
ImportName::Ordinal(3),
ServiceStatus::Stub,
Box::new(|_, _, _| Ok(0)),
)
.unwrap();
let pe = ParsedPe::parse(&image.bytes).unwrap();
let mut memory = pe.load_into_memory(&image.bytes).unwrap().memory;
let result = registry.bind_imports(&pe, &image.bytes, BASE, &mut memory);
let report = inspect(&image);
match result {
Ok(count) => {
bound += 1;
assert_eq!(report.import_error, None);
assert_eq!(report.imports.len(), count);
}
Err(ImportError::Table(error)) => {
malformed += 1;
assert_eq!(report.import_error, Some(error));
}
Err(ImportError::UnresolvedImport { module, symbol }) => {
unresolved += 1;
assert_eq!(report.import_error, None);
assert!(
report
.imports
.iter()
.any(|import| import.dll == module && import.symbol == symbol)
);
}
Err(ImportError::Memory(_)) => {}
}
}
assert!(
bound > 100 && malformed > 100 && unresolved > 100,
"{bound} {malformed} {unresolved}"
);
}
#[test]
fn inspection_reports_exactly_what_binding_resolves() {
let image = build(&[
("KERNEL32.dll", Symbol::Name("GetLastError")),
("kernel32.dll", Symbol::Name("getlasterror")),
(
"api-ms-win-core-errorhandling-l1-1-0.dll",
Symbol::Name("SetLastError"),
),
(
"api-ms-win-core-errorhandling-l1-1-3.dll",
Symbol::Name("SetLastError"),
),
("kernel32.dll", Symbol::Ordinal(1)),
]);
let report = inspect(&image);
let supported: Vec<bool> = report
.imports
.iter()
.map(|import| import.is_supported)
.collect();
assert_eq!(supported, [true, false, true, false, false]);
assert_eq!(
report.imports[2].canonical_module.as_deref(),
Some("kernel32.dll")
);
assert_eq!(report.imports[4].symbol, "Ordinal#1");
}
+186
View File
@@ -0,0 +1,186 @@
#!/usr/bin/env python3
"""Assemble the original x86-64 fixtures with the LLVM assembler.
generate write integer.txt, vector.txt and float.txt next to this file
--check reassemble in memory and fail if a committed fixture differs
Each output line is `<hex bytes> | <Intel-syntax text>`. The assembler is
`clang -target x86_64-apple-macos` and the bytes are read with `objdump -d`,
so no Xenora code takes part in choosing an encoding. Nothing is executed.
"""
import re
import subprocess
import sys
import tempfile
from pathlib import Path
HERE = Path(__file__).resolve().parent
LOW = "a c d b sp bp si di".split()
CONDITIONS = "o no b ae e ne be a s ns p np l ge le g".split()
PTR = {8: "byte", 16: "word", 32: "dword", 64: "qword"}
def reg(index, bits):
if index >= 8:
return f"r{index}" + {64: "", 32: "d", 16: "w", 8: "b"}[bits]
name = LOW[index]
if bits == 8:
return name + "l"
full = name + "x" if index < 4 else name
return {64: "r", 32: "e", 16: ""}[bits] + full
def mem(bits):
return f"{PTR[bits]} ptr [rsi + 4*rdi + 16]"
def cases():
out = []
for op in "add or adc sbb and sub xor cmp test".split():
for bits in (8, 16, 32, 64):
out += [f"{op} {reg(3, bits)}, {reg(1, bits)}", f"{op} {reg(9, bits)}, {reg(12, bits)}",
f"{op} {reg(0, bits)}, {reg(0, bits)}", f"{op} {mem(bits)}, {reg(2, bits)}"]
if op != "test":
# The reversed encoding of a register pair is load-form only.
out.append(f"{op} {reg(10, bits)}, {mem(bits)}")
imm = {8: "0x7f", 16: "0x1234", 32: "0x12345678", 64: "0x12345678"}[bits]
out += [f"{op} {reg(0, bits)}, {imm}", f"{op} {reg(3, bits)}, {imm}",
f"{op} {mem(bits)}, {imm}"]
if bits != 8:
out += [f"{op} {reg(11, bits)}, -3", f"{op} {mem(bits)}, -3"]
out += [f"{op} ah, bl", f"{op} cl, dh", f"{op} bh, 0x55"]
for op in "inc dec neg not mul imul div idiv".split():
for bits in (8, 16, 32, 64):
out += [f"{op} {reg(1, bits)}", f"{op} {reg(9, bits)}", f"{op} {mem(bits)}"]
out.append(f"{op} ch")
for op in "rol ror shl shr sar".split():
for bits in (8, 16, 32, 64):
for count in ("1", "3", "7", "cl"):
out += [f"{op} {reg(3, bits)}, {count}", f"{op} {mem(bits)}, {count}"]
out += [f"{op} {reg(13, bits)}, {bits - 1}", f"{op} {reg(13, bits)}, 0"]
for bits in (16, 32, 64):
out += [f"imul {reg(3, bits)}, {reg(9, bits)}", f"imul {reg(3, bits)}, {mem(bits)}",
f"imul {reg(8, bits)}, {reg(1, bits)}, -7", f"imul {reg(8, bits)}, {reg(1, bits)}, 0x1234",
f"imul {reg(8, bits)}, {mem(bits)}, 0x1234"]
for op in "bsf bsr popcnt tzcnt lzcnt".split():
out += [f"{op} {reg(3, bits)}, {reg(9, bits)}", f"{op} {reg(10, bits)}, {mem(bits)}"]
for op in "bt bts btr btc".split():
out += [f"{op} {reg(3, bits)}, {reg(9, bits)}", f"{op} {reg(10, bits)}, 5",
f"{op} {mem(bits)}, {bits - 1}"]
for cc in CONDITIONS:
out += [f"cmov{cc} {reg(3, bits)}, {reg(9, bits)}", f"cmov{cc} {reg(10, bits)}, {mem(bits)}"]
for src in (8, 16):
if src < bits:
for op in ("movzx", "movsx"):
out += [f"{op} {reg(3, bits)}, {reg(9, src)}", f"{op} {reg(10, bits)}, {mem(src)}"]
out += [f"lea {reg(3, bits)}, [rsi + 4*rdi + 16]", f"lea {reg(12, bits)}, [r9 - 5]",
f"lea {reg(0, bits)}, [8*r10 + 64]"]
out += ["movsxd rbx, r9d", f"movsxd r10, {mem(32)}", "movzx ebx, ah", "movsx ecx, bh"]
for cc in CONDITIONS:
out += [f"set{cc} bl", f"set{cc} {mem(8)}", f"set{cc} ah"]
for bits in (8, 16, 32, 64):
out += [f"mov {reg(3, bits)}, {reg(9, bits)}", f"mov {reg(10, bits)}, {mem(bits)}",
f"mov {mem(bits)}, {reg(2, bits)}", f"mov {reg(14, bits)}, 0x5a",
f"mov {mem(bits)}, 0x5a", f"xchg {reg(3, bits)}, {reg(9, bits)}",
f"xchg {mem(bits)}, {reg(2, bits)}"]
out += ["mov ah, bl", "mov dl, ch", "mov bh, 0x21", "xchg ah, bl", "mov sil, dil",
"movabs r15, 0x8877665544332211", "mov rcx, -2", "bswap ebx", "bswap r9",
"cbw", "cwde", "cdqe", "cwd", "cdq", "cqo", "clc", "stc", "cmc", "nop",
"nop dword ptr [rax + 8]", "pause", "push r9", "push rbx", "push -5", "push 0x12345678",
f"push {mem(64)}", "pop rbx", "pop r12", f"pop {mem(64)}", "leave"]
return list(dict.fromkeys(out))
PACKED = """punpcklbw punpcklwd punpckldq punpcklqdq punpckhbw punpckhwd punpckhdq punpckhqdq
packsswb packssdw packuswb pcmpgtb pcmpgtw pcmpgtd pcmpeqb pcmpeqw pcmpeqd paddb paddw paddd paddq
psubb psubw psubd psubq paddsb paddsw paddusb paddusw psubsb psubsw psubusb psubusw pmullw pmulhw
pmulhuw pmuludq pmaddwd psadbw pavgb pavgw pminub pmaxub pminsw pmaxsw pand pandn por pxor andps
andpd andnps andnpd orps orpd xorps xorpd unpcklps unpcklpd unpckhps unpckhpd psllw pslld psllq
psrlw psrld psrlq psraw psrad movaps movapd movups movupd movdqa movdqu""".split()
def vector_cases():
wide, quad, dword = (f"{w} ptr [rsi + 4*rdi + 16]" for w in ("xmmword", "qword", "dword"))
word = "word ptr [rsi + 4*rdi + 16]"
out = []
for op in PACKED:
out += [f"{op} xmm3, xmm9", f"{op} xmm10, {wide}", f"{op} xmm2, xmm2"]
for op in "movaps movapd movups movupd movdqa movdqu movntdq movntps movntpd".split():
out.append(f"{op} {wide}, xmm11")
for op, width in (("movss", dword), ("movsd", quad), ("movq", quad)):
out += [f"{op} xmm3, xmm9", f"{op} xmm10, {width}", f"{op} {width}, xmm11"]
for op in "movlps movlpd movhps movhpd".split():
out += [f"{op} xmm3, {quad}", f"{op} {quad}, xmm9"]
out += ["movhlps xmm3, xmm9", "movlhps xmm10, xmm1", "movhlps xmm2, xmm2", "movlhps xmm2, xmm2"]
out += ["movd xmm3, r9d", "movd xmm12, eax", "movq xmm3, r9", "movd r9d, xmm3", "movd ebx, xmm12",
"movq r9, xmm3", f"movd xmm3, {dword}", f"movd {dword}, xmm9"]
for op in "movmskps movmskpd pmovmskb".split():
out += [f"{op} ebx, xmm9", f"{op} r10d, xmm3"]
for op, bits in (("w", 16), ("d", 32), ("q", 64)):
for name in ("psll", "psrl", "psra"):
if name + op != "psraq":
out += [f"{name}{op} xmm{3 + 6 * (n % 2)}, {n}" for n in (0, 1, 7, bits - 1, bits, 255)]
for op in ("pslldq", "psrldq"):
out += [f"{op} xmm9, {n}" for n in (0, 1, 5, 15, 16, 255)]
for op in "pshufd pshufhw pshuflw shufps shufpd".split():
out += [f"{op} xmm3, xmm9, {n}" for n in (0, 27, 78, 177, 255)]
out += [f"{op} xmm10, {wide}, 114", f"{op} xmm2, xmm2, 57"]
for n in (0, 3, 7):
out += [f"pinsrw xmm9, ebx, {n}", f"pinsrw xmm3, {word}, {n}", f"pextrw r9d, xmm3, {n}"]
out += [f"stmxcsr {dword}"]
return list(dict.fromkeys(out))
def float_cases():
out = []
memory = {"ss": "dword", "sd": "qword", "ps": "xmmword", "pd": "xmmword"}
place = " ptr [rsi + 4*rdi + 16]"
for kind, width in memory.items():
for op in "add sub mul div min max sqrt".split():
out += [f"{op}{kind} xmm3, xmm9", f"{op}{kind} xmm3, {width}{place}"]
for code in range(8):
out += [f"cmp{kind} xmm3, xmm9, {code}", f"cmp{kind} xmm3, {width}{place}, {code}"]
for kind in ("ss", "sd"):
for op in ("comi", "ucomi"):
out += [f"{op}{kind} xmm3, xmm9", f"{op}{kind} xmm3, {memory[kind]}{place}"]
for op in ("cvt", "cvtt"):
for reg in ("r9d", "r9"):
out += [f"{op}{kind}2si {reg}, xmm9", f"{op}{kind}2si {reg}, {memory[kind]}{place}"]
for reg, width in (("r9d", "dword"), ("r9", "qword")):
out += [f"cvtsi2{kind} xmm3, {reg}", f"cvtsi2{kind} xmm3, {width}{place}"]
for op, width in (("cvtss2sd", "dword"), ("cvtsd2ss", "qword"), ("cvtps2pd", "qword"), ("cvtpd2ps", "xmmword"),
("cvtdq2ps", "xmmword"), ("cvtdq2pd", "qword"), ("cvtps2dq", "xmmword"), ("cvttps2dq", "xmmword"),
("cvtpd2dq", "xmmword"), ("cvttpd2dq", "xmmword")):
out += [f"{op} xmm3, xmm9", f"{op} xmm3, {width}{place}"]
return out
def assemble(lines):
with tempfile.TemporaryDirectory() as directory:
source, obj = Path(directory, "a.s"), Path(directory, "a.o")
source.write_text(".intel_syntax noprefix\n" + "\n".join(lines) + "\n")
subprocess.run(["clang", "-target", "x86_64-apple-macos", "-c", source, "-o", obj], check=True)
# One line per instruction: objdump never wraps its raw bytes.
listing = subprocess.run(["objdump", "-d", obj], check=True, capture_output=True, text=True).stdout
rows = [m.group(1).split() for m in re.finditer(r"^\s*[0-9a-f]+:\s((?:[0-9a-f]{2}\s)+)", listing, re.M)]
if len(rows) != len(lines):
sys.exit(f"{len(lines)} instructions assembled to {len(rows)} rows")
return "".join(f"{' '.join(row)} | {line}\n" for row, line in zip(rows, lines))
def main(argv):
if len(argv) != 2 or argv[1] not in ("generate", "--check"):
sys.exit("usage: assemble.py generate|--check")
for name, lines in (("integer.txt", cases()), ("vector.txt", vector_cases()),
("float.txt", float_cases())):
text = assemble(lines)
if argv[1] == "generate":
(HERE / name).write_text(text)
elif (HERE / name).read_text() != text:
sys.exit(f"{name} differs from the assembler output")
print(f"{name}: {len(lines)} instructions")
if __name__ == "__main__":
main(sys.argv)
+172
View File
@@ -0,0 +1,172 @@
f3 41 0f 58 d9 | addss xmm3, xmm9
f3 0f 58 5c be 10 | addss xmm3, dword ptr [rsi + 4*rdi + 16]
f3 41 0f 5c d9 | subss xmm3, xmm9
f3 0f 5c 5c be 10 | subss xmm3, dword ptr [rsi + 4*rdi + 16]
f3 41 0f 59 d9 | mulss xmm3, xmm9
f3 0f 59 5c be 10 | mulss xmm3, dword ptr [rsi + 4*rdi + 16]
f3 41 0f 5e d9 | divss xmm3, xmm9
f3 0f 5e 5c be 10 | divss xmm3, dword ptr [rsi + 4*rdi + 16]
f3 41 0f 5d d9 | minss xmm3, xmm9
f3 0f 5d 5c be 10 | minss xmm3, dword ptr [rsi + 4*rdi + 16]
f3 41 0f 5f d9 | maxss xmm3, xmm9
f3 0f 5f 5c be 10 | maxss xmm3, dword ptr [rsi + 4*rdi + 16]
f3 41 0f 51 d9 | sqrtss xmm3, xmm9
f3 0f 51 5c be 10 | sqrtss xmm3, dword ptr [rsi + 4*rdi + 16]
f3 41 0f c2 d9 00 | cmpss xmm3, xmm9, 0
f3 0f c2 5c be 10 00 | cmpss xmm3, dword ptr [rsi + 4*rdi + 16], 0
f3 41 0f c2 d9 01 | cmpss xmm3, xmm9, 1
f3 0f c2 5c be 10 01 | cmpss xmm3, dword ptr [rsi + 4*rdi + 16], 1
f3 41 0f c2 d9 02 | cmpss xmm3, xmm9, 2
f3 0f c2 5c be 10 02 | cmpss xmm3, dword ptr [rsi + 4*rdi + 16], 2
f3 41 0f c2 d9 03 | cmpss xmm3, xmm9, 3
f3 0f c2 5c be 10 03 | cmpss xmm3, dword ptr [rsi + 4*rdi + 16], 3
f3 41 0f c2 d9 04 | cmpss xmm3, xmm9, 4
f3 0f c2 5c be 10 04 | cmpss xmm3, dword ptr [rsi + 4*rdi + 16], 4
f3 41 0f c2 d9 05 | cmpss xmm3, xmm9, 5
f3 0f c2 5c be 10 05 | cmpss xmm3, dword ptr [rsi + 4*rdi + 16], 5
f3 41 0f c2 d9 06 | cmpss xmm3, xmm9, 6
f3 0f c2 5c be 10 06 | cmpss xmm3, dword ptr [rsi + 4*rdi + 16], 6
f3 41 0f c2 d9 07 | cmpss xmm3, xmm9, 7
f3 0f c2 5c be 10 07 | cmpss xmm3, dword ptr [rsi + 4*rdi + 16], 7
f2 41 0f 58 d9 | addsd xmm3, xmm9
f2 0f 58 5c be 10 | addsd xmm3, qword ptr [rsi + 4*rdi + 16]
f2 41 0f 5c d9 | subsd xmm3, xmm9
f2 0f 5c 5c be 10 | subsd xmm3, qword ptr [rsi + 4*rdi + 16]
f2 41 0f 59 d9 | mulsd xmm3, xmm9
f2 0f 59 5c be 10 | mulsd xmm3, qword ptr [rsi + 4*rdi + 16]
f2 41 0f 5e d9 | divsd xmm3, xmm9
f2 0f 5e 5c be 10 | divsd xmm3, qword ptr [rsi + 4*rdi + 16]
f2 41 0f 5d d9 | minsd xmm3, xmm9
f2 0f 5d 5c be 10 | minsd xmm3, qword ptr [rsi + 4*rdi + 16]
f2 41 0f 5f d9 | maxsd xmm3, xmm9
f2 0f 5f 5c be 10 | maxsd xmm3, qword ptr [rsi + 4*rdi + 16]
f2 41 0f 51 d9 | sqrtsd xmm3, xmm9
f2 0f 51 5c be 10 | sqrtsd xmm3, qword ptr [rsi + 4*rdi + 16]
f2 41 0f c2 d9 00 | cmpsd xmm3, xmm9, 0
f2 0f c2 5c be 10 00 | cmpsd xmm3, qword ptr [rsi + 4*rdi + 16], 0
f2 41 0f c2 d9 01 | cmpsd xmm3, xmm9, 1
f2 0f c2 5c be 10 01 | cmpsd xmm3, qword ptr [rsi + 4*rdi + 16], 1
f2 41 0f c2 d9 02 | cmpsd xmm3, xmm9, 2
f2 0f c2 5c be 10 02 | cmpsd xmm3, qword ptr [rsi + 4*rdi + 16], 2
f2 41 0f c2 d9 03 | cmpsd xmm3, xmm9, 3
f2 0f c2 5c be 10 03 | cmpsd xmm3, qword ptr [rsi + 4*rdi + 16], 3
f2 41 0f c2 d9 04 | cmpsd xmm3, xmm9, 4
f2 0f c2 5c be 10 04 | cmpsd xmm3, qword ptr [rsi + 4*rdi + 16], 4
f2 41 0f c2 d9 05 | cmpsd xmm3, xmm9, 5
f2 0f c2 5c be 10 05 | cmpsd xmm3, qword ptr [rsi + 4*rdi + 16], 5
f2 41 0f c2 d9 06 | cmpsd xmm3, xmm9, 6
f2 0f c2 5c be 10 06 | cmpsd xmm3, qword ptr [rsi + 4*rdi + 16], 6
f2 41 0f c2 d9 07 | cmpsd xmm3, xmm9, 7
f2 0f c2 5c be 10 07 | cmpsd xmm3, qword ptr [rsi + 4*rdi + 16], 7
41 0f 58 d9 | addps xmm3, xmm9
0f 58 5c be 10 | addps xmm3, xmmword ptr [rsi + 4*rdi + 16]
41 0f 5c d9 | subps xmm3, xmm9
0f 5c 5c be 10 | subps xmm3, xmmword ptr [rsi + 4*rdi + 16]
41 0f 59 d9 | mulps xmm3, xmm9
0f 59 5c be 10 | mulps xmm3, xmmword ptr [rsi + 4*rdi + 16]
41 0f 5e d9 | divps xmm3, xmm9
0f 5e 5c be 10 | divps xmm3, xmmword ptr [rsi + 4*rdi + 16]
41 0f 5d d9 | minps xmm3, xmm9
0f 5d 5c be 10 | minps xmm3, xmmword ptr [rsi + 4*rdi + 16]
41 0f 5f d9 | maxps xmm3, xmm9
0f 5f 5c be 10 | maxps xmm3, xmmword ptr [rsi + 4*rdi + 16]
41 0f 51 d9 | sqrtps xmm3, xmm9
0f 51 5c be 10 | sqrtps xmm3, xmmword ptr [rsi + 4*rdi + 16]
41 0f c2 d9 00 | cmpps xmm3, xmm9, 0
0f c2 5c be 10 00 | cmpps xmm3, xmmword ptr [rsi + 4*rdi + 16], 0
41 0f c2 d9 01 | cmpps xmm3, xmm9, 1
0f c2 5c be 10 01 | cmpps xmm3, xmmword ptr [rsi + 4*rdi + 16], 1
41 0f c2 d9 02 | cmpps xmm3, xmm9, 2
0f c2 5c be 10 02 | cmpps xmm3, xmmword ptr [rsi + 4*rdi + 16], 2
41 0f c2 d9 03 | cmpps xmm3, xmm9, 3
0f c2 5c be 10 03 | cmpps xmm3, xmmword ptr [rsi + 4*rdi + 16], 3
41 0f c2 d9 04 | cmpps xmm3, xmm9, 4
0f c2 5c be 10 04 | cmpps xmm3, xmmword ptr [rsi + 4*rdi + 16], 4
41 0f c2 d9 05 | cmpps xmm3, xmm9, 5
0f c2 5c be 10 05 | cmpps xmm3, xmmword ptr [rsi + 4*rdi + 16], 5
41 0f c2 d9 06 | cmpps xmm3, xmm9, 6
0f c2 5c be 10 06 | cmpps xmm3, xmmword ptr [rsi + 4*rdi + 16], 6
41 0f c2 d9 07 | cmpps xmm3, xmm9, 7
0f c2 5c be 10 07 | cmpps xmm3, xmmword ptr [rsi + 4*rdi + 16], 7
66 41 0f 58 d9 | addpd xmm3, xmm9
66 0f 58 5c be 10 | addpd xmm3, xmmword ptr [rsi + 4*rdi + 16]
66 41 0f 5c d9 | subpd xmm3, xmm9
66 0f 5c 5c be 10 | subpd xmm3, xmmword ptr [rsi + 4*rdi + 16]
66 41 0f 59 d9 | mulpd xmm3, xmm9
66 0f 59 5c be 10 | mulpd xmm3, xmmword ptr [rsi + 4*rdi + 16]
66 41 0f 5e d9 | divpd xmm3, xmm9
66 0f 5e 5c be 10 | divpd xmm3, xmmword ptr [rsi + 4*rdi + 16]
66 41 0f 5d d9 | minpd xmm3, xmm9
66 0f 5d 5c be 10 | minpd xmm3, xmmword ptr [rsi + 4*rdi + 16]
66 41 0f 5f d9 | maxpd xmm3, xmm9
66 0f 5f 5c be 10 | maxpd xmm3, xmmword ptr [rsi + 4*rdi + 16]
66 41 0f 51 d9 | sqrtpd xmm3, xmm9
66 0f 51 5c be 10 | sqrtpd xmm3, xmmword ptr [rsi + 4*rdi + 16]
66 41 0f c2 d9 00 | cmppd xmm3, xmm9, 0
66 0f c2 5c be 10 00 | cmppd xmm3, xmmword ptr [rsi + 4*rdi + 16], 0
66 41 0f c2 d9 01 | cmppd xmm3, xmm9, 1
66 0f c2 5c be 10 01 | cmppd xmm3, xmmword ptr [rsi + 4*rdi + 16], 1
66 41 0f c2 d9 02 | cmppd xmm3, xmm9, 2
66 0f c2 5c be 10 02 | cmppd xmm3, xmmword ptr [rsi + 4*rdi + 16], 2
66 41 0f c2 d9 03 | cmppd xmm3, xmm9, 3
66 0f c2 5c be 10 03 | cmppd xmm3, xmmword ptr [rsi + 4*rdi + 16], 3
66 41 0f c2 d9 04 | cmppd xmm3, xmm9, 4
66 0f c2 5c be 10 04 | cmppd xmm3, xmmword ptr [rsi + 4*rdi + 16], 4
66 41 0f c2 d9 05 | cmppd xmm3, xmm9, 5
66 0f c2 5c be 10 05 | cmppd xmm3, xmmword ptr [rsi + 4*rdi + 16], 5
66 41 0f c2 d9 06 | cmppd xmm3, xmm9, 6
66 0f c2 5c be 10 06 | cmppd xmm3, xmmword ptr [rsi + 4*rdi + 16], 6
66 41 0f c2 d9 07 | cmppd xmm3, xmm9, 7
66 0f c2 5c be 10 07 | cmppd xmm3, xmmword ptr [rsi + 4*rdi + 16], 7
41 0f 2f d9 | comiss xmm3, xmm9
0f 2f 5c be 10 | comiss xmm3, dword ptr [rsi + 4*rdi + 16]
41 0f 2e d9 | ucomiss xmm3, xmm9
0f 2e 5c be 10 | ucomiss xmm3, dword ptr [rsi + 4*rdi + 16]
f3 45 0f 2d c9 | cvtss2si r9d, xmm9
f3 44 0f 2d 4c be 10 | cvtss2si r9d, dword ptr [rsi + 4*rdi + 16]
f3 4d 0f 2d c9 | cvtss2si r9, xmm9
f3 4c 0f 2d 4c be 10 | cvtss2si r9, dword ptr [rsi + 4*rdi + 16]
f3 45 0f 2c c9 | cvttss2si r9d, xmm9
f3 44 0f 2c 4c be 10 | cvttss2si r9d, dword ptr [rsi + 4*rdi + 16]
f3 4d 0f 2c c9 | cvttss2si r9, xmm9
f3 4c 0f 2c 4c be 10 | cvttss2si r9, dword ptr [rsi + 4*rdi + 16]
f3 41 0f 2a d9 | cvtsi2ss xmm3, r9d
f3 0f 2a 5c be 10 | cvtsi2ss xmm3, dword ptr [rsi + 4*rdi + 16]
f3 49 0f 2a d9 | cvtsi2ss xmm3, r9
f3 48 0f 2a 5c be 10 | cvtsi2ss xmm3, qword ptr [rsi + 4*rdi + 16]
66 41 0f 2f d9 | comisd xmm3, xmm9
66 0f 2f 5c be 10 | comisd xmm3, qword ptr [rsi + 4*rdi + 16]
66 41 0f 2e d9 | ucomisd xmm3, xmm9
66 0f 2e 5c be 10 | ucomisd xmm3, qword ptr [rsi + 4*rdi + 16]
f2 45 0f 2d c9 | cvtsd2si r9d, xmm9
f2 44 0f 2d 4c be 10 | cvtsd2si r9d, qword ptr [rsi + 4*rdi + 16]
f2 4d 0f 2d c9 | cvtsd2si r9, xmm9
f2 4c 0f 2d 4c be 10 | cvtsd2si r9, qword ptr [rsi + 4*rdi + 16]
f2 45 0f 2c c9 | cvttsd2si r9d, xmm9
f2 44 0f 2c 4c be 10 | cvttsd2si r9d, qword ptr [rsi + 4*rdi + 16]
f2 4d 0f 2c c9 | cvttsd2si r9, xmm9
f2 4c 0f 2c 4c be 10 | cvttsd2si r9, qword ptr [rsi + 4*rdi + 16]
f2 41 0f 2a d9 | cvtsi2sd xmm3, r9d
f2 0f 2a 5c be 10 | cvtsi2sd xmm3, dword ptr [rsi + 4*rdi + 16]
f2 49 0f 2a d9 | cvtsi2sd xmm3, r9
f2 48 0f 2a 5c be 10 | cvtsi2sd xmm3, qword ptr [rsi + 4*rdi + 16]
f3 41 0f 5a d9 | cvtss2sd xmm3, xmm9
f3 0f 5a 5c be 10 | cvtss2sd xmm3, dword ptr [rsi + 4*rdi + 16]
f2 41 0f 5a d9 | cvtsd2ss xmm3, xmm9
f2 0f 5a 5c be 10 | cvtsd2ss xmm3, qword ptr [rsi + 4*rdi + 16]
41 0f 5a d9 | cvtps2pd xmm3, xmm9
0f 5a 5c be 10 | cvtps2pd xmm3, qword ptr [rsi + 4*rdi + 16]
66 41 0f 5a d9 | cvtpd2ps xmm3, xmm9
66 0f 5a 5c be 10 | cvtpd2ps xmm3, xmmword ptr [rsi + 4*rdi + 16]
41 0f 5b d9 | cvtdq2ps xmm3, xmm9
0f 5b 5c be 10 | cvtdq2ps xmm3, xmmword ptr [rsi + 4*rdi + 16]
f3 41 0f e6 d9 | cvtdq2pd xmm3, xmm9
f3 0f e6 5c be 10 | cvtdq2pd xmm3, qword ptr [rsi + 4*rdi + 16]
66 41 0f 5b d9 | cvtps2dq xmm3, xmm9
66 0f 5b 5c be 10 | cvtps2dq xmm3, xmmword ptr [rsi + 4*rdi + 16]
f3 41 0f 5b d9 | cvttps2dq xmm3, xmm9
f3 0f 5b 5c be 10 | cvttps2dq xmm3, xmmword ptr [rsi + 4*rdi + 16]
f2 41 0f e6 d9 | cvtpd2dq xmm3, xmm9
f2 0f e6 5c be 10 | cvtpd2dq xmm3, xmmword ptr [rsi + 4*rdi + 16]
66 41 0f e6 d9 | cvttpd2dq xmm3, xmm9
66 0f e6 5c be 10 | cvttpd2dq xmm3, xmmword ptr [rsi + 4*rdi + 16]
+441
View File
@@ -0,0 +1,441 @@
#!/usr/bin/env python3
"""Reference vectors for SSE and SSE2 floating point, from exact fractions.
generate write float_vectors.txt next to this file
--check recompute in memory and fail if the committed file differs
Every finite result is computed as an exact `fractions.Fraction` (square roots by
integer comparison) and then rounded by definition, so nothing here shares code
or method with crates/loader/src/softfloat.rs, and no host floating point is
used. Rules: Intel SDM Vol. 1, 4.8, 4.9 and 11.5, and the Vol. 2 operation
sections. Cases whose flags those sections leave open are not generated:
a denormal dividend over zero, flushing an exact denormal result, and the
precision flag of a denormal converted to an integer under DAZ.
Line: <operation> <mxcsr> <a> <b> <result> <mxcsr flags>, all values hex.
"""
import random
import sys
from fractions import Fraction
from math import isqrt
from pathlib import Path
OUT = Path(__file__).resolve().parent / "float_vectors.txt"
IE, DE, ZE, OE, UE, PE = 1, 2, 4, 8, 16, 32
NEAREST, DOWN, UP, ZERO = range(4)
class Fmt:
def __init__(self, bits, frac):
self.bits, self.frac = bits, frac
self.ebits = bits - 1 - frac
self.emax = 2 ** (self.ebits - 1) - 1
self.emin = 1 - self.emax
self.inf = (2 ** self.ebits - 1) << frac
self.quiet = 1 << (frac - 1)
self.top = 1 << (bits - 1)
def mag(self, v):
return v % self.top
def neg(self, v):
return v >= self.top
def nan(self, v):
return self.mag(v) > self.inf
def snan(self, v):
return self.nan(v) and not v & self.quiet
def isinf(self, v):
return self.mag(v) == self.inf
def denormal(self, v):
return 0 < self.mag(v) < (1 << self.frac)
def value(self, v):
m = self.mag(v)
field, fraction = m >> self.frac, m % (1 << self.frac)
if field == 0:
x = Fraction(fraction) * Fraction(2) ** (self.emin - self.frac)
else:
x = (1 + Fraction(fraction, 1 << self.frac)) * Fraction(2) ** (field - self.emax)
return -x if self.neg(v) else x
def encode(self, sign, x):
"""Bits of an exactly representable non-negative x."""
if x == 0:
m = 0
elif x < Fraction(2) ** self.emin:
m = int(x / Fraction(2) ** (self.emin - self.frac))
else:
e = exponent(x)
m = ((e + self.emax) << self.frac) + int((x / Fraction(2) ** e - 1) * (1 << self.frac))
return m + (self.top if sign else 0)
S, D = Fmt(32, 23), Fmt(64, 52)
def exponent(x):
"""floor(log2 x) for x > 0."""
e = x.numerator.bit_length() - x.denominator.bit_length()
return e if Fraction(2) ** e <= x else e - 1
def pick(below, above, position, sign, mode, even):
"""Choose between neighbours; position is -1, 0 or 1 against the midpoint,
or None when exactly `below`."""
if position is None:
return below
if mode == NEAREST:
if position == 0:
return below if even else above
return above if position > 0 else below
if mode == ZERO:
return below
return above if (mode == UP) != sign else below
def quantize(n, rest_sign, quantum, sign, mode):
"""n quanta below the value; rest_sign as in pick."""
return pick(n * quantum, (n + 1) * quantum, rest_sign, sign, mode, n % 2 == 0)
def locate(x, quantum):
"""Quanta below the positive fraction x, and its side of the midpoint."""
q = x / quantum
n = q.numerator // q.denominator
rest = q - n
if rest == 0:
return n, None
half = Fraction(1, 2)
return n, (rest > half) - (rest < half)
def locate_root(x, quantum):
"""As locate, for the square root of x."""
q = x / (quantum * quantum)
n = isqrt(q.numerator // q.denominator)
if n * n == q:
return n, None
middle = (Fraction(n) + Fraction(1, 2)) ** 2
return n, (q > middle) - (q < middle)
def finish(fmt, sign, e, locator, control):
"""Round a positive exact value with floor(log2) = e, given its locator."""
mode, ftz, flags = control["mode"], control["ftz"], 0
n, side = locator(Fraction(2) ** (e - fmt.frac))
unbounded = quantize(n, side, Fraction(2) ** (e - fmt.frac), sign, mode)
tiny = unbounded < Fraction(2) ** fmt.emin
quantum = Fraction(2) ** (max(e, fmt.emin) - fmt.frac)
n, side = locator(quantum)
result = quantize(n, side, quantum, sign, mode)
if tiny and ftz:
if side is None:
return None # flushing an exact denormal is left open
return fmt.encode(sign, Fraction(0)), UE | PE
if side is not None:
flags |= PE | (UE if tiny else 0)
if result >= Fraction(2) ** (fmt.emax + 1):
infinite = mode == NEAREST or (mode == UP and not sign) or (mode == DOWN and sign)
return (fmt.inf if infinite else fmt.inf - 1) + (fmt.top if sign else 0), OE | PE
return fmt.encode(sign, result), flags
def rounded(fmt, x, control):
sign = x < 0
x = abs(x)
return finish(fmt, sign, exponent(x), lambda q: locate(x, q), control)
def default(fmt):
return fmt.top + fmt.inf + fmt.quiet
def prepare(fmt, v, control):
if control["daz"] and fmt.denormal(v):
return fmt.top if fmt.neg(v) else 0
return v
def binary(op, fmt, a, b, control):
a, b = prepare(fmt, a, control), prepare(fmt, b, control)
de = DE if fmt.denormal(a) or fmt.denormal(b) else 0
if op in ("min", "max"):
if fmt.nan(a) or fmt.nan(b):
return b, IE
order = compare(fmt, a, b)
return (a if order == (-1 if op == "min" else 1) else b), de
if fmt.nan(a) or fmt.nan(b):
chosen = a if fmt.nan(a) else b
return chosen | fmt.quiet, IE if fmt.snan(a) or fmt.snan(b) else 0
if op == "sub":
b ^= fmt.top
sa, sb = fmt.neg(a), fmt.neg(b)
sign = sa != sb
signed = lambda m: m + (fmt.top if sign else 0)
if op in ("add", "sub"):
if fmt.isinf(a) and fmt.isinf(b) and sign:
return default(fmt), IE
if fmt.isinf(a):
return a, de
if fmt.isinf(b):
return b, de
x = fmt.value(a) + fmt.value(b)
if x == 0:
both = fmt.mag(a) == 0 and not sign
return (fmt.top if (sa if both else control["mode"] == DOWN) else 0), de
elif op == "mul":
if fmt.isinf(a) or fmt.isinf(b):
if fmt.mag(a) == 0 or fmt.mag(b) == 0:
return default(fmt), IE
return signed(fmt.inf), de
x = fmt.value(a) * fmt.value(b)
if x == 0:
return signed(0), de
else:
if (fmt.isinf(a) and fmt.isinf(b)) or (fmt.mag(a) == 0 and fmt.mag(b) == 0):
return default(fmt), IE
if fmt.isinf(a):
return signed(fmt.inf), de
if fmt.isinf(b):
return signed(0), de
if fmt.mag(b) == 0:
return None if de else (signed(fmt.inf), ZE)
x = fmt.value(a) / fmt.value(b)
if x == 0:
return signed(0), de
out = rounded(fmt, x, control)
return out and (out[0], out[1] | de)
def root(fmt, v, control):
v = prepare(fmt, v, control)
if fmt.nan(v):
return v | fmt.quiet, IE if fmt.snan(v) else 0
if fmt.mag(v) == 0:
return v, 0
if fmt.neg(v):
return default(fmt), IE
if fmt.isinf(v):
return v, 0
x = fmt.value(v)
bits, flags = finish(fmt, False, exponent(x) // 2, lambda q: locate_root(x, q), control)
return bits, flags | (DE if fmt.denormal(v) else 0)
def compare(fmt, a, b):
def key(v):
if fmt.isinf(v):
return Fraction(2) ** (fmt.emax + 2) * (-1 if fmt.neg(v) else 1)
return fmt.value(v)
return (key(a) > key(b)) - (key(a) < key(b))
def ordering(fmt, a, b, signaling, control):
"""(-1, 0, 1 or None for unordered), flags."""
a, b = prepare(fmt, a, control), prepare(fmt, b, control)
if fmt.nan(a) or fmt.nan(b):
return None, IE if signaling or fmt.snan(a) or fmt.snan(b) else 0
return compare(fmt, a, b), DE if fmt.denormal(a) or fmt.denormal(b) else 0
def predicate(code, fmt, a, b, control):
order, flags = ordering(fmt, a, b, code in (1, 2, 5, 6), control)
truth = [order == 0, order == -1, order in (-1, 0), order is None,
order != 0, order != -1, order not in (-1, 0), order is not None][code]
return (2 ** fmt.bits - 1 if truth else 0), flags
def comparison(fmt, a, b, signaling, control):
"""RFLAGS as ZF=4, PF=2, CF=1."""
order, flags = ordering(fmt, a, b, signaling, control)
return {None: 7, 1: 0, -1: 1, 0: 4}[order], flags
def widen(src, dst, v, control):
v = prepare(src, v, control)
sign = dst.top if src.neg(v) else 0
if src.nan(v):
payload = Fraction(src.mag(v) - src.inf) * Fraction(2) ** (dst.frac - src.frac)
return sign + dst.inf + (int(payload) | dst.quiet), IE if src.snan(v) else 0
if src.isinf(v):
return sign + dst.inf, 0
x = src.value(v)
if x == 0:
return sign, 0
out = rounded(dst, x, control)
return out and (out[0], out[1] | (DE if src.denormal(v) else 0))
def to_int(fmt, v, bits, truncate, control):
if control["daz"] and fmt.denormal(v):
return None
indefinite = 2 ** (bits - 1), IE
if fmt.nan(v) or fmt.isinf(v):
return indefinite
x = fmt.value(v)
n, side = locate(abs(x), Fraction(1))
r = int(quantize(n, side, Fraction(1), x < 0, ZERO if truncate else control["mode"]))
r = -r if x < 0 else r
if not -(2 ** (bits - 1)) <= r < 2 ** (bits - 1):
return indefinite
return r % 2 ** bits, 0 if side is None else PE
def from_int(fmt, v, bits, control):
x = v - 2 ** bits if v >= 2 ** (bits - 1) else v
return rounded(fmt, Fraction(x), control) if x else (0, 0)
def operands(fmt, rng):
one = fmt.emax << fmt.frac
least = 1 << fmt.frac
edge = [0, 1, 2, least - 1, least, least + 1, 2 * least, one - 1, one, one + 1, one + least,
one + fmt.quiet, one + (fmt.frac << fmt.frac), one + (fmt.frac << fmt.frac) + 1,
fmt.inf - 1, fmt.inf - least, fmt.inf, fmt.inf + fmt.quiet, fmt.inf + fmt.quiet + 5,
fmt.inf + 1, fmt.inf + fmt.quiet - 1]
choice = rng.randrange(6)
if choice < 2:
v = rng.choice(edge)
elif choice == 2:
v = rng.randrange(least) # denormal
elif choice == 3: # near one, few significant bits
v = one + (rng.randrange(-40, 41) << fmt.frac) + (rng.randrange(16) << (fmt.frac - 4))
elif choice == 4: # near the smallest and largest normals
v = rng.choice([least * rng.randrange(1, fmt.frac + 4), fmt.inf - least * rng.randrange(1, 4)]) + rng.randrange(least)
else:
v = rng.randrange(fmt.top)
v = min(v, fmt.top - 1)
return v + (fmt.top if rng.random() < 0.5 else 0)
def related(fmt, a, rng):
"""A second operand, often within a few exponents of the first."""
if rng.random() < 0.5 or fmt.mag(a) >= fmt.inf:
return operands(fmt, rng)
m = fmt.mag(a) + (rng.randrange(-fmt.frac - 3, fmt.frac + 4) << fmt.frac) + rng.randrange(-3, 4)
return max(0, min(m, fmt.inf)) + (fmt.top if rng.random() < 0.5 else 0)
def integers(bits, rng):
c = rng.randrange(4)
if c == 0:
return rng.choice([0, 1, 2 ** (bits - 1), 2 ** (bits - 1) - 1, 2 ** bits - 1])
if c == 1:
return (2 ** rng.randrange(bits) + rng.randrange(-2, 3)) % 2 ** bits
return rng.randrange(2 ** bits) >> rng.randrange(bits)
def near_int(fmt, bits, rng):
"""Values around halves, integers and the integer range limits."""
if rng.random() < 0.3:
return operands(fmt, rng)
base = rng.choice([Fraction(rng.randrange(-9, 10), 2), Fraction(rng.randrange(-2 ** 24, 2 ** 24), 4),
Fraction(2 ** (bits - 1)), Fraction(-(2 ** (bits - 1))), Fraction(rng.randrange(1, 2 ** 20)) * 2 ** rng.randrange(40)])
v = fmt.top if base == 0 and rng.random() < 0.5 else 0
if base:
v = rounded(fmt, base, {"mode": NEAREST, "ftz": False})[0]
m = max(0, fmt.mag(v) + rng.randrange(-2, 3))
return m + (fmt.top if fmt.neg(v) else 0)
def build():
rng = random.Random(0x58454E4F5241)
lines = []
def emit(name, make, compute, count):
done = 0
while done < count:
mode = rng.randrange(4)
control = {"mode": mode, "daz": rng.random() < 0.2, "ftz": rng.random() < 0.2}
mxcsr = 0x1F80 | mode << 13 | control["daz"] << 6 | control["ftz"] << 15
a, b = make()
out = compute(a, b, control)
if out is None:
continue
lines.append(f"{name} {mxcsr:x} {a:x} {b:x} {out[0]:x} {out[1]:x}\n")
done += 1
def direct(name, mode, a, b, out):
if out is not None:
lines.append(f"{name} {0x1F80 | mode << 13:x} {a:x} {b:x} {out[0]:x} {out[1]:x}\n")
for fmt, s in ((S, "ss"), (D, "sd")):
# Every pair of special operands, for every two-operand rule.
one, least = fmt.emax << fmt.frac, 1 << fmt.frac
special = [0, fmt.top, 1, one, fmt.top + one, fmt.inf - 1, fmt.inf, fmt.top + fmt.inf,
fmt.inf + fmt.quiet + 5, fmt.top + fmt.inf + 3]
for a in special:
for b in special:
for op in ("add", "sub", "mul", "div", "min", "max"):
mode = rng.randrange(4)
control = {"mode": mode, "daz": False, "ftz": False}
direct(op + s, mode, a, b, binary(op, fmt, a, b, control))
# Products within a rounding step of the smallest normal: (1 + t)(1 - t)
# times 2^emin. Tininess is judged after rounding, so some are not tiny.
root_of_least = fmt.emin // 2
for shift in range(fmt.frac // 2 - 3, fmt.frac // 2 + 6):
t = 1 << (fmt.frac - shift)
a = ((root_of_least + fmt.emax) << fmt.frac) + t
rest = fmt.emin - root_of_least
# 1 - t is in the binade below one, with twice the resolution.
b = ((rest - 1 + fmt.emax) << fmt.frac) + (least - 2 * t)
for mode in range(4):
for x, y in ((a, b), (a + fmt.top, b)):
control = {"mode": mode, "daz": False, "ftz": False}
direct("mul" + s, mode, x, y, binary("mul", fmt, x, y, control))
# The same neighbourhood for narrowing: 2^-126 (1 - 2^-k).
for k in range(22, 30):
b = D.encode(False, Fraction(2) ** S.emin * (1 - Fraction(1, 2 ** k)))
for mode in range(4):
for x in (b, b + D.top):
direct("cvtsd2ss", mode, 0, x, widen(D, S, x, {"mode": mode, "daz": False, "ftz": False}))
for fmt, s in ((S, "ss"), (D, "sd")):
def pair(fmt=fmt):
a = operands(fmt, rng)
return a, related(fmt, a, rng)
for op in ("add", "sub", "mul", "div", "min", "max"):
emit(op + s, pair, lambda a, b, c, op=op, fmt=fmt: binary(op, fmt, a, b, c),
260 if op in ("add", "sub", "mul", "div") else 100)
emit("sqrt" + s, lambda fmt=fmt: (0, operands(fmt, rng)), lambda a, b, c, fmt=fmt: root(fmt, b, c), 200)
for code in range(8):
emit(f"cmp{s}{code}", pair, lambda a, b, c, code=code, fmt=fmt: predicate(code, fmt, a, b, c), 40)
emit("comi" + s, pair, lambda a, b, c, fmt=fmt: comparison(fmt, a, b, True, c), 80)
emit("ucomi" + s, pair, lambda a, b, c, fmt=fmt: comparison(fmt, a, b, False, c), 80)
for bits, w in ((32, "d"), (64, "q")):
for name, truncate in (("cvt", False), ("cvtt", True)):
emit(f"{name}{s}2si{w}", lambda fmt=fmt, bits=bits: (0, near_int(fmt, bits, rng)),
lambda a, b, c, fmt=fmt, bits=bits, t=truncate: to_int(fmt, b, bits, t, c), 110)
emit(f"cvtsi2{s}{w}", lambda bits=bits: (0, integers(bits, rng)),
lambda a, b, c, fmt=fmt, bits=bits: from_int(fmt, b, bits, c), 80)
emit("cvtss2sd", lambda: (0, operands(S, rng)), lambda a, b, c: widen(S, D, b, c), 120)
def narrowing():
if rng.random() < 0.4:
return 0, operands(D, rng)
# A binary32 neighbourhood, with bits beyond its precision.
v = operands(S, rng)
x = widen(S, D, v, {"mode": NEAREST, "daz": False, "ftz": False})[0]
return 0, x ^ (rng.choice([0, 1, 1 << 28, (1 << 28) + 1, (1 << 29) - 1]) if D.mag(x) else 0)
emit("cvtsd2ss", narrowing, lambda a, b, c: widen(D, S, b, c), 260)
return "".join(lines)
def main(argv):
if len(argv) != 2 or argv[1] not in ("generate", "--check"):
sys.exit("usage: float_reference.py generate|--check")
text = build()
if argv[1] == "generate":
OUT.write_text(text)
elif OUT.read_text() != text:
sys.exit("float_vectors.txt is out of date")
print(f"{text.count(chr(10))} vectors")
if __name__ == "__main__":
main(sys.argv)
File diff suppressed because it is too large. Load diff
+985
View File
@@ -0,0 +1,985 @@
00 cb | add bl, cl
45 00 e1 | add r9b, r12b
00 c0 | add al, al
00 54 be 10 | add byte ptr [rsi + 4*rdi + 16], dl
44 02 54 be 10 | add r10b, byte ptr [rsi + 4*rdi + 16]
04 7f | add al, 0x7f
80 c3 7f | add bl, 0x7f
80 44 be 10 7f | add byte ptr [rsi + 4*rdi + 16], 0x7f
66 01 cb | add bx, cx
66 45 01 e1 | add r9w, r12w
66 01 c0 | add ax, ax
66 01 54 be 10 | add word ptr [rsi + 4*rdi + 16], dx
66 44 03 54 be 10 | add r10w, word ptr [rsi + 4*rdi + 16]
66 05 34 12 | add ax, 0x1234
66 81 c3 34 12 | add bx, 0x1234
66 81 44 be 10 34 12 | add word ptr [rsi + 4*rdi + 16], 0x1234
66 41 83 c3 fd | add r11w, -3
66 83 44 be 10 fd | add word ptr [rsi + 4*rdi + 16], -3
01 cb | add ebx, ecx
45 01 e1 | add r9d, r12d
01 c0 | add eax, eax
01 54 be 10 | add dword ptr [rsi + 4*rdi + 16], edx
44 03 54 be 10 | add r10d, dword ptr [rsi + 4*rdi + 16]
05 78 56 34 12 | add eax, 0x12345678
81 c3 78 56 34 12 | add ebx, 0x12345678
81 44 be 10 78 56 34 12 | add dword ptr [rsi + 4*rdi + 16], 0x12345678
41 83 c3 fd | add r11d, -3
83 44 be 10 fd | add dword ptr [rsi + 4*rdi + 16], -3
48 01 cb | add rbx, rcx
4d 01 e1 | add r9, r12
48 01 c0 | add rax, rax
48 01 54 be 10 | add qword ptr [rsi + 4*rdi + 16], rdx
4c 03 54 be 10 | add r10, qword ptr [rsi + 4*rdi + 16]
48 05 78 56 34 12 | add rax, 0x12345678
48 81 c3 78 56 34 12 | add rbx, 0x12345678
48 81 44 be 10 78 56 34 12 | add qword ptr [rsi + 4*rdi + 16], 0x12345678
49 83 c3 fd | add r11, -3
48 83 44 be 10 fd | add qword ptr [rsi + 4*rdi + 16], -3
00 dc | add ah, bl
00 f1 | add cl, dh
80 c7 55 | add bh, 0x55
08 cb | or bl, cl
45 08 e1 | or r9b, r12b
08 c0 | or al, al
08 54 be 10 | or byte ptr [rsi + 4*rdi + 16], dl
44 0a 54 be 10 | or r10b, byte ptr [rsi + 4*rdi + 16]
0c 7f | or al, 0x7f
80 cb 7f | or bl, 0x7f
80 4c be 10 7f | or byte ptr [rsi + 4*rdi + 16], 0x7f
66 09 cb | or bx, cx
66 45 09 e1 | or r9w, r12w
66 09 c0 | or ax, ax
66 09 54 be 10 | or word ptr [rsi + 4*rdi + 16], dx
66 44 0b 54 be 10 | or r10w, word ptr [rsi + 4*rdi + 16]
66 0d 34 12 | or ax, 0x1234
66 81 cb 34 12 | or bx, 0x1234
66 81 4c be 10 34 12 | or word ptr [rsi + 4*rdi + 16], 0x1234
66 41 83 cb fd | or r11w, -3
66 83 4c be 10 fd | or word ptr [rsi + 4*rdi + 16], -3
09 cb | or ebx, ecx
45 09 e1 | or r9d, r12d
09 c0 | or eax, eax
09 54 be 10 | or dword ptr [rsi + 4*rdi + 16], edx
44 0b 54 be 10 | or r10d, dword ptr [rsi + 4*rdi + 16]
0d 78 56 34 12 | or eax, 0x12345678
81 cb 78 56 34 12 | or ebx, 0x12345678
81 4c be 10 78 56 34 12 | or dword ptr [rsi + 4*rdi + 16], 0x12345678
41 83 cb fd | or r11d, -3
83 4c be 10 fd | or dword ptr [rsi + 4*rdi + 16], -3
48 09 cb | or rbx, rcx
4d 09 e1 | or r9, r12
48 09 c0 | or rax, rax
48 09 54 be 10 | or qword ptr [rsi + 4*rdi + 16], rdx
4c 0b 54 be 10 | or r10, qword ptr [rsi + 4*rdi + 16]
48 0d 78 56 34 12 | or rax, 0x12345678
48 81 cb 78 56 34 12 | or rbx, 0x12345678
48 81 4c be 10 78 56 34 12 | or qword ptr [rsi + 4*rdi + 16], 0x12345678
49 83 cb fd | or r11, -3
48 83 4c be 10 fd | or qword ptr [rsi + 4*rdi + 16], -3
08 dc | or ah, bl
08 f1 | or cl, dh
80 cf 55 | or bh, 0x55
10 cb | adc bl, cl
45 10 e1 | adc r9b, r12b
10 c0 | adc al, al
10 54 be 10 | adc byte ptr [rsi + 4*rdi + 16], dl
44 12 54 be 10 | adc r10b, byte ptr [rsi + 4*rdi + 16]
14 7f | adc al, 0x7f
80 d3 7f | adc bl, 0x7f
80 54 be 10 7f | adc byte ptr [rsi + 4*rdi + 16], 0x7f
66 11 cb | adc bx, cx
66 45 11 e1 | adc r9w, r12w
66 11 c0 | adc ax, ax
66 11 54 be 10 | adc word ptr [rsi + 4*rdi + 16], dx
66 44 13 54 be 10 | adc r10w, word ptr [rsi + 4*rdi + 16]
66 15 34 12 | adc ax, 0x1234
66 81 d3 34 12 | adc bx, 0x1234
66 81 54 be 10 34 12 | adc word ptr [rsi + 4*rdi + 16], 0x1234
66 41 83 d3 fd | adc r11w, -3
66 83 54 be 10 fd | adc word ptr [rsi + 4*rdi + 16], -3
11 cb | adc ebx, ecx
45 11 e1 | adc r9d, r12d
11 c0 | adc eax, eax
11 54 be 10 | adc dword ptr [rsi + 4*rdi + 16], edx
44 13 54 be 10 | adc r10d, dword ptr [rsi + 4*rdi + 16]
15 78 56 34 12 | adc eax, 0x12345678
81 d3 78 56 34 12 | adc ebx, 0x12345678
81 54 be 10 78 56 34 12 | adc dword ptr [rsi + 4*rdi + 16], 0x12345678
41 83 d3 fd | adc r11d, -3
83 54 be 10 fd | adc dword ptr [rsi + 4*rdi + 16], -3
48 11 cb | adc rbx, rcx
4d 11 e1 | adc r9, r12
48 11 c0 | adc rax, rax
48 11 54 be 10 | adc qword ptr [rsi + 4*rdi + 16], rdx
4c 13 54 be 10 | adc r10, qword ptr [rsi + 4*rdi + 16]
48 15 78 56 34 12 | adc rax, 0x12345678
48 81 d3 78 56 34 12 | adc rbx, 0x12345678
48 81 54 be 10 78 56 34 12 | adc qword ptr [rsi + 4*rdi + 16], 0x12345678
49 83 d3 fd | adc r11, -3
48 83 54 be 10 fd | adc qword ptr [rsi + 4*rdi + 16], -3
10 dc | adc ah, bl
10 f1 | adc cl, dh
80 d7 55 | adc bh, 0x55
18 cb | sbb bl, cl
45 18 e1 | sbb r9b, r12b
18 c0 | sbb al, al
18 54 be 10 | sbb byte ptr [rsi + 4*rdi + 16], dl
44 1a 54 be 10 | sbb r10b, byte ptr [rsi + 4*rdi + 16]
1c 7f | sbb al, 0x7f
80 db 7f | sbb bl, 0x7f
80 5c be 10 7f | sbb byte ptr [rsi + 4*rdi + 16], 0x7f
66 19 cb | sbb bx, cx
66 45 19 e1 | sbb r9w, r12w
66 19 c0 | sbb ax, ax
66 19 54 be 10 | sbb word ptr [rsi + 4*rdi + 16], dx
66 44 1b 54 be 10 | sbb r10w, word ptr [rsi + 4*rdi + 16]
66 1d 34 12 | sbb ax, 0x1234
66 81 db 34 12 | sbb bx, 0x1234
66 81 5c be 10 34 12 | sbb word ptr [rsi + 4*rdi + 16], 0x1234
66 41 83 db fd | sbb r11w, -3
66 83 5c be 10 fd | sbb word ptr [rsi + 4*rdi + 16], -3
19 cb | sbb ebx, ecx
45 19 e1 | sbb r9d, r12d
19 c0 | sbb eax, eax
19 54 be 10 | sbb dword ptr [rsi + 4*rdi + 16], edx
44 1b 54 be 10 | sbb r10d, dword ptr [rsi + 4*rdi + 16]
1d 78 56 34 12 | sbb eax, 0x12345678
81 db 78 56 34 12 | sbb ebx, 0x12345678
81 5c be 10 78 56 34 12 | sbb dword ptr [rsi + 4*rdi + 16], 0x12345678
41 83 db fd | sbb r11d, -3
83 5c be 10 fd | sbb dword ptr [rsi + 4*rdi + 16], -3
48 19 cb | sbb rbx, rcx
4d 19 e1 | sbb r9, r12
48 19 c0 | sbb rax, rax
48 19 54 be 10 | sbb qword ptr [rsi + 4*rdi + 16], rdx
4c 1b 54 be 10 | sbb r10, qword ptr [rsi + 4*rdi + 16]
48 1d 78 56 34 12 | sbb rax, 0x12345678
48 81 db 78 56 34 12 | sbb rbx, 0x12345678
48 81 5c be 10 78 56 34 12 | sbb qword ptr [rsi + 4*rdi + 16], 0x12345678
49 83 db fd | sbb r11, -3
48 83 5c be 10 fd | sbb qword ptr [rsi + 4*rdi + 16], -3
18 dc | sbb ah, bl
18 f1 | sbb cl, dh
80 df 55 | sbb bh, 0x55
20 cb | and bl, cl
45 20 e1 | and r9b, r12b
20 c0 | and al, al
20 54 be 10 | and byte ptr [rsi + 4*rdi + 16], dl
44 22 54 be 10 | and r10b, byte ptr [rsi + 4*rdi + 16]
24 7f | and al, 0x7f
80 e3 7f | and bl, 0x7f
80 64 be 10 7f | and byte ptr [rsi + 4*rdi + 16], 0x7f
66 21 cb | and bx, cx
66 45 21 e1 | and r9w, r12w
66 21 c0 | and ax, ax
66 21 54 be 10 | and word ptr [rsi + 4*rdi + 16], dx
66 44 23 54 be 10 | and r10w, word ptr [rsi + 4*rdi + 16]
66 25 34 12 | and ax, 0x1234
66 81 e3 34 12 | and bx, 0x1234
66 81 64 be 10 34 12 | and word ptr [rsi + 4*rdi + 16], 0x1234
66 41 83 e3 fd | and r11w, -3
66 83 64 be 10 fd | and word ptr [rsi + 4*rdi + 16], -3
21 cb | and ebx, ecx
45 21 e1 | and r9d, r12d
21 c0 | and eax, eax
21 54 be 10 | and dword ptr [rsi + 4*rdi + 16], edx
44 23 54 be 10 | and r10d, dword ptr [rsi + 4*rdi + 16]
25 78 56 34 12 | and eax, 0x12345678
81 e3 78 56 34 12 | and ebx, 0x12345678
81 64 be 10 78 56 34 12 | and dword ptr [rsi + 4*rdi + 16], 0x12345678
41 83 e3 fd | and r11d, -3
83 64 be 10 fd | and dword ptr [rsi + 4*rdi + 16], -3
48 21 cb | and rbx, rcx
4d 21 e1 | and r9, r12
48 21 c0 | and rax, rax
48 21 54 be 10 | and qword ptr [rsi + 4*rdi + 16], rdx
4c 23 54 be 10 | and r10, qword ptr [rsi + 4*rdi + 16]
48 25 78 56 34 12 | and rax, 0x12345678
48 81 e3 78 56 34 12 | and rbx, 0x12345678
48 81 64 be 10 78 56 34 12 | and qword ptr [rsi + 4*rdi + 16], 0x12345678
49 83 e3 fd | and r11, -3
48 83 64 be 10 fd | and qword ptr [rsi + 4*rdi + 16], -3
20 dc | and ah, bl
20 f1 | and cl, dh
80 e7 55 | and bh, 0x55
28 cb | sub bl, cl
45 28 e1 | sub r9b, r12b
28 c0 | sub al, al
28 54 be 10 | sub byte ptr [rsi + 4*rdi + 16], dl
44 2a 54 be 10 | sub r10b, byte ptr [rsi + 4*rdi + 16]
2c 7f | sub al, 0x7f
80 eb 7f | sub bl, 0x7f
80 6c be 10 7f | sub byte ptr [rsi + 4*rdi + 16], 0x7f
66 29 cb | sub bx, cx
66 45 29 e1 | sub r9w, r12w
66 29 c0 | sub ax, ax
66 29 54 be 10 | sub word ptr [rsi + 4*rdi + 16], dx
66 44 2b 54 be 10 | sub r10w, word ptr [rsi + 4*rdi + 16]
66 2d 34 12 | sub ax, 0x1234
66 81 eb 34 12 | sub bx, 0x1234
66 81 6c be 10 34 12 | sub word ptr [rsi + 4*rdi + 16], 0x1234
66 41 83 eb fd | sub r11w, -3
66 83 6c be 10 fd | sub word ptr [rsi + 4*rdi + 16], -3
29 cb | sub ebx, ecx
45 29 e1 | sub r9d, r12d
29 c0 | sub eax, eax
29 54 be 10 | sub dword ptr [rsi + 4*rdi + 16], edx
44 2b 54 be 10 | sub r10d, dword ptr [rsi + 4*rdi + 16]
2d 78 56 34 12 | sub eax, 0x12345678
81 eb 78 56 34 12 | sub ebx, 0x12345678
81 6c be 10 78 56 34 12 | sub dword ptr [rsi + 4*rdi + 16], 0x12345678
41 83 eb fd | sub r11d, -3
83 6c be 10 fd | sub dword ptr [rsi + 4*rdi + 16], -3
48 29 cb | sub rbx, rcx
4d 29 e1 | sub r9, r12
48 29 c0 | sub rax, rax
48 29 54 be 10 | sub qword ptr [rsi + 4*rdi + 16], rdx
4c 2b 54 be 10 | sub r10, qword ptr [rsi + 4*rdi + 16]
48 2d 78 56 34 12 | sub rax, 0x12345678
48 81 eb 78 56 34 12 | sub rbx, 0x12345678
48 81 6c be 10 78 56 34 12 | sub qword ptr [rsi + 4*rdi + 16], 0x12345678
49 83 eb fd | sub r11, -3
48 83 6c be 10 fd | sub qword ptr [rsi + 4*rdi + 16], -3
28 dc | sub ah, bl
28 f1 | sub cl, dh
80 ef 55 | sub bh, 0x55
30 cb | xor bl, cl
45 30 e1 | xor r9b, r12b
30 c0 | xor al, al
30 54 be 10 | xor byte ptr [rsi + 4*rdi + 16], dl
44 32 54 be 10 | xor r10b, byte ptr [rsi + 4*rdi + 16]
34 7f | xor al, 0x7f
80 f3 7f | xor bl, 0x7f
80 74 be 10 7f | xor byte ptr [rsi + 4*rdi + 16], 0x7f
66 31 cb | xor bx, cx
66 45 31 e1 | xor r9w, r12w
66 31 c0 | xor ax, ax
66 31 54 be 10 | xor word ptr [rsi + 4*rdi + 16], dx
66 44 33 54 be 10 | xor r10w, word ptr [rsi + 4*rdi + 16]
66 35 34 12 | xor ax, 0x1234
66 81 f3 34 12 | xor bx, 0x1234
66 81 74 be 10 34 12 | xor word ptr [rsi + 4*rdi + 16], 0x1234
66 41 83 f3 fd | xor r11w, -3
66 83 74 be 10 fd | xor word ptr [rsi + 4*rdi + 16], -3
31 cb | xor ebx, ecx
45 31 e1 | xor r9d, r12d
31 c0 | xor eax, eax
31 54 be 10 | xor dword ptr [rsi + 4*rdi + 16], edx
44 33 54 be 10 | xor r10d, dword ptr [rsi + 4*rdi + 16]
35 78 56 34 12 | xor eax, 0x12345678
81 f3 78 56 34 12 | xor ebx, 0x12345678
81 74 be 10 78 56 34 12 | xor dword ptr [rsi + 4*rdi + 16], 0x12345678
41 83 f3 fd | xor r11d, -3
83 74 be 10 fd | xor dword ptr [rsi + 4*rdi + 16], -3
48 31 cb | xor rbx, rcx
4d 31 e1 | xor r9, r12
48 31 c0 | xor rax, rax
48 31 54 be 10 | xor qword ptr [rsi + 4*rdi + 16], rdx
4c 33 54 be 10 | xor r10, qword ptr [rsi + 4*rdi + 16]
48 35 78 56 34 12 | xor rax, 0x12345678
48 81 f3 78 56 34 12 | xor rbx, 0x12345678
48 81 74 be 10 78 56 34 12 | xor qword ptr [rsi + 4*rdi + 16], 0x12345678
49 83 f3 fd | xor r11, -3
48 83 74 be 10 fd | xor qword ptr [rsi + 4*rdi + 16], -3
30 dc | xor ah, bl
30 f1 | xor cl, dh
80 f7 55 | xor bh, 0x55
38 cb | cmp bl, cl
45 38 e1 | cmp r9b, r12b
38 c0 | cmp al, al
38 54 be 10 | cmp byte ptr [rsi + 4*rdi + 16], dl
44 3a 54 be 10 | cmp r10b, byte ptr [rsi + 4*rdi + 16]
3c 7f | cmp al, 0x7f
80 fb 7f | cmp bl, 0x7f
80 7c be 10 7f | cmp byte ptr [rsi + 4*rdi + 16], 0x7f
66 39 cb | cmp bx, cx
66 45 39 e1 | cmp r9w, r12w
66 39 c0 | cmp ax, ax
66 39 54 be 10 | cmp word ptr [rsi + 4*rdi + 16], dx
66 44 3b 54 be 10 | cmp r10w, word ptr [rsi + 4*rdi + 16]
66 3d 34 12 | cmp ax, 0x1234
66 81 fb 34 12 | cmp bx, 0x1234
66 81 7c be 10 34 12 | cmp word ptr [rsi + 4*rdi + 16], 0x1234
66 41 83 fb fd | cmp r11w, -3
66 83 7c be 10 fd | cmp word ptr [rsi + 4*rdi + 16], -3
39 cb | cmp ebx, ecx
45 39 e1 | cmp r9d, r12d
39 c0 | cmp eax, eax
39 54 be 10 | cmp dword ptr [rsi + 4*rdi + 16], edx
44 3b 54 be 10 | cmp r10d, dword ptr [rsi + 4*rdi + 16]
3d 78 56 34 12 | cmp eax, 0x12345678
81 fb 78 56 34 12 | cmp ebx, 0x12345678
81 7c be 10 78 56 34 12 | cmp dword ptr [rsi + 4*rdi + 16], 0x12345678
41 83 fb fd | cmp r11d, -3
83 7c be 10 fd | cmp dword ptr [rsi + 4*rdi + 16], -3
48 39 cb | cmp rbx, rcx
4d 39 e1 | cmp r9, r12
48 39 c0 | cmp rax, rax
48 39 54 be 10 | cmp qword ptr [rsi + 4*rdi + 16], rdx
4c 3b 54 be 10 | cmp r10, qword ptr [rsi + 4*rdi + 16]
48 3d 78 56 34 12 | cmp rax, 0x12345678
48 81 fb 78 56 34 12 | cmp rbx, 0x12345678
48 81 7c be 10 78 56 34 12 | cmp qword ptr [rsi + 4*rdi + 16], 0x12345678
49 83 fb fd | cmp r11, -3
48 83 7c be 10 fd | cmp qword ptr [rsi + 4*rdi + 16], -3
38 dc | cmp ah, bl
38 f1 | cmp cl, dh
80 ff 55 | cmp bh, 0x55
84 cb | test bl, cl
45 84 e1 | test r9b, r12b
84 c0 | test al, al
84 54 be 10 | test byte ptr [rsi + 4*rdi + 16], dl
a8 7f | test al, 0x7f
f6 c3 7f | test bl, 0x7f
f6 44 be 10 7f | test byte ptr [rsi + 4*rdi + 16], 0x7f
66 85 cb | test bx, cx
66 45 85 e1 | test r9w, r12w
66 85 c0 | test ax, ax
66 85 54 be 10 | test word ptr [rsi + 4*rdi + 16], dx
66 a9 34 12 | test ax, 0x1234
66 f7 c3 34 12 | test bx, 0x1234
66 f7 44 be 10 34 12 | test word ptr [rsi + 4*rdi + 16], 0x1234
66 41 f7 c3 fd ff | test r11w, -3
66 f7 44 be 10 fd ff | test word ptr [rsi + 4*rdi + 16], -3
85 cb | test ebx, ecx
45 85 e1 | test r9d, r12d
85 c0 | test eax, eax
85 54 be 10 | test dword ptr [rsi + 4*rdi + 16], edx
a9 78 56 34 12 | test eax, 0x12345678
f7 c3 78 56 34 12 | test ebx, 0x12345678
f7 44 be 10 78 56 34 12 | test dword ptr [rsi + 4*rdi + 16], 0x12345678
41 f7 c3 fd ff ff ff | test r11d, -3
f7 44 be 10 fd ff ff ff | test dword ptr [rsi + 4*rdi + 16], -3
48 85 cb | test rbx, rcx
4d 85 e1 | test r9, r12
48 85 c0 | test rax, rax
48 85 54 be 10 | test qword ptr [rsi + 4*rdi + 16], rdx
48 a9 78 56 34 12 | test rax, 0x12345678
48 f7 c3 78 56 34 12 | test rbx, 0x12345678
48 f7 44 be 10 78 56 34 12 | test qword ptr [rsi + 4*rdi + 16], 0x12345678
49 f7 c3 fd ff ff ff | test r11, -3
48 f7 44 be 10 fd ff ff ff | test qword ptr [rsi + 4*rdi + 16], -3
84 dc | test ah, bl
84 f1 | test cl, dh
f6 c7 55 | test bh, 0x55
fe c1 | inc cl
41 fe c1 | inc r9b
fe 44 be 10 | inc byte ptr [rsi + 4*rdi + 16]
66 ff c1 | inc cx
66 41 ff c1 | inc r9w
66 ff 44 be 10 | inc word ptr [rsi + 4*rdi + 16]
ff c1 | inc ecx
41 ff c1 | inc r9d
ff 44 be 10 | inc dword ptr [rsi + 4*rdi + 16]
48 ff c1 | inc rcx
49 ff c1 | inc r9
48 ff 44 be 10 | inc qword ptr [rsi + 4*rdi + 16]
fe c5 | inc ch
fe c9 | dec cl
41 fe c9 | dec r9b
fe 4c be 10 | dec byte ptr [rsi + 4*rdi + 16]
66 ff c9 | dec cx
66 41 ff c9 | dec r9w
66 ff 4c be 10 | dec word ptr [rsi + 4*rdi + 16]
ff c9 | dec ecx
41 ff c9 | dec r9d
ff 4c be 10 | dec dword ptr [rsi + 4*rdi + 16]
48 ff c9 | dec rcx
49 ff c9 | dec r9
48 ff 4c be 10 | dec qword ptr [rsi + 4*rdi + 16]
fe cd | dec ch
f6 d9 | neg cl
41 f6 d9 | neg r9b
f6 5c be 10 | neg byte ptr [rsi + 4*rdi + 16]
66 f7 d9 | neg cx
66 41 f7 d9 | neg r9w
66 f7 5c be 10 | neg word ptr [rsi + 4*rdi + 16]
f7 d9 | neg ecx
41 f7 d9 | neg r9d
f7 5c be 10 | neg dword ptr [rsi + 4*rdi + 16]
48 f7 d9 | neg rcx
49 f7 d9 | neg r9
48 f7 5c be 10 | neg qword ptr [rsi + 4*rdi + 16]
f6 dd | neg ch
f6 d1 | not cl
41 f6 d1 | not r9b
f6 54 be 10 | not byte ptr [rsi + 4*rdi + 16]
66 f7 d1 | not cx
66 41 f7 d1 | not r9w
66 f7 54 be 10 | not word ptr [rsi + 4*rdi + 16]
f7 d1 | not ecx
41 f7 d1 | not r9d
f7 54 be 10 | not dword ptr [rsi + 4*rdi + 16]
48 f7 d1 | not rcx
49 f7 d1 | not r9
48 f7 54 be 10 | not qword ptr [rsi + 4*rdi + 16]
f6 d5 | not ch
f6 e1 | mul cl
41 f6 e1 | mul r9b
f6 64 be 10 | mul byte ptr [rsi + 4*rdi + 16]
66 f7 e1 | mul cx
66 41 f7 e1 | mul r9w
66 f7 64 be 10 | mul word ptr [rsi + 4*rdi + 16]
f7 e1 | mul ecx
41 f7 e1 | mul r9d
f7 64 be 10 | mul dword ptr [rsi + 4*rdi + 16]
48 f7 e1 | mul rcx
49 f7 e1 | mul r9
48 f7 64 be 10 | mul qword ptr [rsi + 4*rdi + 16]
f6 e5 | mul ch
f6 e9 | imul cl
41 f6 e9 | imul r9b
f6 6c be 10 | imul byte ptr [rsi + 4*rdi + 16]
66 f7 e9 | imul cx
66 41 f7 e9 | imul r9w
66 f7 6c be 10 | imul word ptr [rsi + 4*rdi + 16]
f7 e9 | imul ecx
41 f7 e9 | imul r9d
f7 6c be 10 | imul dword ptr [rsi + 4*rdi + 16]
48 f7 e9 | imul rcx
49 f7 e9 | imul r9
48 f7 6c be 10 | imul qword ptr [rsi + 4*rdi + 16]
f6 ed | imul ch
f6 f1 | div cl
41 f6 f1 | div r9b
f6 74 be 10 | div byte ptr [rsi + 4*rdi + 16]
66 f7 f1 | div cx
66 41 f7 f1 | div r9w
66 f7 74 be 10 | div word ptr [rsi + 4*rdi + 16]
f7 f1 | div ecx
41 f7 f1 | div r9d
f7 74 be 10 | div dword ptr [rsi + 4*rdi + 16]
48 f7 f1 | div rcx
49 f7 f1 | div r9
48 f7 74 be 10 | div qword ptr [rsi + 4*rdi + 16]
f6 f5 | div ch
f6 f9 | idiv cl
41 f6 f9 | idiv r9b
f6 7c be 10 | idiv byte ptr [rsi + 4*rdi + 16]
66 f7 f9 | idiv cx
66 41 f7 f9 | idiv r9w
66 f7 7c be 10 | idiv word ptr [rsi + 4*rdi + 16]
f7 f9 | idiv ecx
41 f7 f9 | idiv r9d
f7 7c be 10 | idiv dword ptr [rsi + 4*rdi + 16]
48 f7 f9 | idiv rcx
49 f7 f9 | idiv r9
48 f7 7c be 10 | idiv qword ptr [rsi + 4*rdi + 16]
f6 fd | idiv ch
d0 c3 | rol bl, 1
d0 44 be 10 | rol byte ptr [rsi + 4*rdi + 16], 1
c0 c3 03 | rol bl, 3
c0 44 be 10 03 | rol byte ptr [rsi + 4*rdi + 16], 3
c0 c3 07 | rol bl, 7
c0 44 be 10 07 | rol byte ptr [rsi + 4*rdi + 16], 7
d2 c3 | rol bl, cl
d2 44 be 10 | rol byte ptr [rsi + 4*rdi + 16], cl
41 c0 c5 07 | rol r13b, 7
41 c0 c5 00 | rol r13b, 0
66 d1 c3 | rol bx, 1
66 d1 44 be 10 | rol word ptr [rsi + 4*rdi + 16], 1
66 c1 c3 03 | rol bx, 3
66 c1 44 be 10 03 | rol word ptr [rsi + 4*rdi + 16], 3
66 c1 c3 07 | rol bx, 7
66 c1 44 be 10 07 | rol word ptr [rsi + 4*rdi + 16], 7
66 d3 c3 | rol bx, cl
66 d3 44 be 10 | rol word ptr [rsi + 4*rdi + 16], cl
66 41 c1 c5 0f | rol r13w, 15
66 41 c1 c5 00 | rol r13w, 0
d1 c3 | rol ebx, 1
d1 44 be 10 | rol dword ptr [rsi + 4*rdi + 16], 1
c1 c3 03 | rol ebx, 3
c1 44 be 10 03 | rol dword ptr [rsi + 4*rdi + 16], 3
c1 c3 07 | rol ebx, 7
c1 44 be 10 07 | rol dword ptr [rsi + 4*rdi + 16], 7
d3 c3 | rol ebx, cl
d3 44 be 10 | rol dword ptr [rsi + 4*rdi + 16], cl
41 c1 c5 1f | rol r13d, 31
41 c1 c5 00 | rol r13d, 0
48 d1 c3 | rol rbx, 1
48 d1 44 be 10 | rol qword ptr [rsi + 4*rdi + 16], 1
48 c1 c3 03 | rol rbx, 3
48 c1 44 be 10 03 | rol qword ptr [rsi + 4*rdi + 16], 3
48 c1 c3 07 | rol rbx, 7
48 c1 44 be 10 07 | rol qword ptr [rsi + 4*rdi + 16], 7
48 d3 c3 | rol rbx, cl
48 d3 44 be 10 | rol qword ptr [rsi + 4*rdi + 16], cl
49 c1 c5 3f | rol r13, 63
49 c1 c5 00 | rol r13, 0
d0 cb | ror bl, 1
d0 4c be 10 | ror byte ptr [rsi + 4*rdi + 16], 1
c0 cb 03 | ror bl, 3
c0 4c be 10 03 | ror byte ptr [rsi + 4*rdi + 16], 3
c0 cb 07 | ror bl, 7
c0 4c be 10 07 | ror byte ptr [rsi + 4*rdi + 16], 7
d2 cb | ror bl, cl
d2 4c be 10 | ror byte ptr [rsi + 4*rdi + 16], cl
41 c0 cd 07 | ror r13b, 7
41 c0 cd 00 | ror r13b, 0
66 d1 cb | ror bx, 1
66 d1 4c be 10 | ror word ptr [rsi + 4*rdi + 16], 1
66 c1 cb 03 | ror bx, 3
66 c1 4c be 10 03 | ror word ptr [rsi + 4*rdi + 16], 3
66 c1 cb 07 | ror bx, 7
66 c1 4c be 10 07 | ror word ptr [rsi + 4*rdi + 16], 7
66 d3 cb | ror bx, cl
66 d3 4c be 10 | ror word ptr [rsi + 4*rdi + 16], cl
66 41 c1 cd 0f | ror r13w, 15
66 41 c1 cd 00 | ror r13w, 0
d1 cb | ror ebx, 1
d1 4c be 10 | ror dword ptr [rsi + 4*rdi + 16], 1
c1 cb 03 | ror ebx, 3
c1 4c be 10 03 | ror dword ptr [rsi + 4*rdi + 16], 3
c1 cb 07 | ror ebx, 7
c1 4c be 10 07 | ror dword ptr [rsi + 4*rdi + 16], 7
d3 cb | ror ebx, cl
d3 4c be 10 | ror dword ptr [rsi + 4*rdi + 16], cl
41 c1 cd 1f | ror r13d, 31
41 c1 cd 00 | ror r13d, 0
48 d1 cb | ror rbx, 1
48 d1 4c be 10 | ror qword ptr [rsi + 4*rdi + 16], 1
48 c1 cb 03 | ror rbx, 3
48 c1 4c be 10 03 | ror qword ptr [rsi + 4*rdi + 16], 3
48 c1 cb 07 | ror rbx, 7
48 c1 4c be 10 07 | ror qword ptr [rsi + 4*rdi + 16], 7
48 d3 cb | ror rbx, cl
48 d3 4c be 10 | ror qword ptr [rsi + 4*rdi + 16], cl
49 c1 cd 3f | ror r13, 63
49 c1 cd 00 | ror r13, 0
d0 e3 | shl bl, 1
d0 64 be 10 | shl byte ptr [rsi + 4*rdi + 16], 1
c0 e3 03 | shl bl, 3
c0 64 be 10 03 | shl byte ptr [rsi + 4*rdi + 16], 3
c0 e3 07 | shl bl, 7
c0 64 be 10 07 | shl byte ptr [rsi + 4*rdi + 16], 7
d2 e3 | shl bl, cl
d2 64 be 10 | shl byte ptr [rsi + 4*rdi + 16], cl
41 c0 e5 07 | shl r13b, 7
41 c0 e5 00 | shl r13b, 0
66 d1 e3 | shl bx, 1
66 d1 64 be 10 | shl word ptr [rsi + 4*rdi + 16], 1
66 c1 e3 03 | shl bx, 3
66 c1 64 be 10 03 | shl word ptr [rsi + 4*rdi + 16], 3
66 c1 e3 07 | shl bx, 7
66 c1 64 be 10 07 | shl word ptr [rsi + 4*rdi + 16], 7
66 d3 e3 | shl bx, cl
66 d3 64 be 10 | shl word ptr [rsi + 4*rdi + 16], cl
66 41 c1 e5 0f | shl r13w, 15
66 41 c1 e5 00 | shl r13w, 0
d1 e3 | shl ebx, 1
d1 64 be 10 | shl dword ptr [rsi + 4*rdi + 16], 1
c1 e3 03 | shl ebx, 3
c1 64 be 10 03 | shl dword ptr [rsi + 4*rdi + 16], 3
c1 e3 07 | shl ebx, 7
c1 64 be 10 07 | shl dword ptr [rsi + 4*rdi + 16], 7
d3 e3 | shl ebx, cl
d3 64 be 10 | shl dword ptr [rsi + 4*rdi + 16], cl
41 c1 e5 1f | shl r13d, 31
41 c1 e5 00 | shl r13d, 0
48 d1 e3 | shl rbx, 1
48 d1 64 be 10 | shl qword ptr [rsi + 4*rdi + 16], 1
48 c1 e3 03 | shl rbx, 3
48 c1 64 be 10 03 | shl qword ptr [rsi + 4*rdi + 16], 3
48 c1 e3 07 | shl rbx, 7
48 c1 64 be 10 07 | shl qword ptr [rsi + 4*rdi + 16], 7
48 d3 e3 | shl rbx, cl
48 d3 64 be 10 | shl qword ptr [rsi + 4*rdi + 16], cl
49 c1 e5 3f | shl r13, 63
49 c1 e5 00 | shl r13, 0
d0 eb | shr bl, 1
d0 6c be 10 | shr byte ptr [rsi + 4*rdi + 16], 1
c0 eb 03 | shr bl, 3
c0 6c be 10 03 | shr byte ptr [rsi + 4*rdi + 16], 3
c0 eb 07 | shr bl, 7
c0 6c be 10 07 | shr byte ptr [rsi + 4*rdi + 16], 7
d2 eb | shr bl, cl
d2 6c be 10 | shr byte ptr [rsi + 4*rdi + 16], cl
41 c0 ed 07 | shr r13b, 7
41 c0 ed 00 | shr r13b, 0
66 d1 eb | shr bx, 1
66 d1 6c be 10 | shr word ptr [rsi + 4*rdi + 16], 1
66 c1 eb 03 | shr bx, 3
66 c1 6c be 10 03 | shr word ptr [rsi + 4*rdi + 16], 3
66 c1 eb 07 | shr bx, 7
66 c1 6c be 10 07 | shr word ptr [rsi + 4*rdi + 16], 7
66 d3 eb | shr bx, cl
66 d3 6c be 10 | shr word ptr [rsi + 4*rdi + 16], cl
66 41 c1 ed 0f | shr r13w, 15
66 41 c1 ed 00 | shr r13w, 0
d1 eb | shr ebx, 1
d1 6c be 10 | shr dword ptr [rsi + 4*rdi + 16], 1
c1 eb 03 | shr ebx, 3
c1 6c be 10 03 | shr dword ptr [rsi + 4*rdi + 16], 3
c1 eb 07 | shr ebx, 7
c1 6c be 10 07 | shr dword ptr [rsi + 4*rdi + 16], 7
d3 eb | shr ebx, cl
d3 6c be 10 | shr dword ptr [rsi + 4*rdi + 16], cl
41 c1 ed 1f | shr r13d, 31
41 c1 ed 00 | shr r13d, 0
48 d1 eb | shr rbx, 1
48 d1 6c be 10 | shr qword ptr [rsi + 4*rdi + 16], 1
48 c1 eb 03 | shr rbx, 3
48 c1 6c be 10 03 | shr qword ptr [rsi + 4*rdi + 16], 3
48 c1 eb 07 | shr rbx, 7
48 c1 6c be 10 07 | shr qword ptr [rsi + 4*rdi + 16], 7
48 d3 eb | shr rbx, cl
48 d3 6c be 10 | shr qword ptr [rsi + 4*rdi + 16], cl
49 c1 ed 3f | shr r13, 63
49 c1 ed 00 | shr r13, 0
d0 fb | sar bl, 1
d0 7c be 10 | sar byte ptr [rsi + 4*rdi + 16], 1
c0 fb 03 | sar bl, 3
c0 7c be 10 03 | sar byte ptr [rsi + 4*rdi + 16], 3
c0 fb 07 | sar bl, 7
c0 7c be 10 07 | sar byte ptr [rsi + 4*rdi + 16], 7
d2 fb | sar bl, cl
d2 7c be 10 | sar byte ptr [rsi + 4*rdi + 16], cl
41 c0 fd 07 | sar r13b, 7
41 c0 fd 00 | sar r13b, 0
66 d1 fb | sar bx, 1
66 d1 7c be 10 | sar word ptr [rsi + 4*rdi + 16], 1
66 c1 fb 03 | sar bx, 3
66 c1 7c be 10 03 | sar word ptr [rsi + 4*rdi + 16], 3
66 c1 fb 07 | sar bx, 7
66 c1 7c be 10 07 | sar word ptr [rsi + 4*rdi + 16], 7
66 d3 fb | sar bx, cl
66 d3 7c be 10 | sar word ptr [rsi + 4*rdi + 16], cl
66 41 c1 fd 0f | sar r13w, 15
66 41 c1 fd 00 | sar r13w, 0
d1 fb | sar ebx, 1
d1 7c be 10 | sar dword ptr [rsi + 4*rdi + 16], 1
c1 fb 03 | sar ebx, 3
c1 7c be 10 03 | sar dword ptr [rsi + 4*rdi + 16], 3
c1 fb 07 | sar ebx, 7
c1 7c be 10 07 | sar dword ptr [rsi + 4*rdi + 16], 7
d3 fb | sar ebx, cl
d3 7c be 10 | sar dword ptr [rsi + 4*rdi + 16], cl
41 c1 fd 1f | sar r13d, 31
41 c1 fd 00 | sar r13d, 0
48 d1 fb | sar rbx, 1
48 d1 7c be 10 | sar qword ptr [rsi + 4*rdi + 16], 1
48 c1 fb 03 | sar rbx, 3
48 c1 7c be 10 03 | sar qword ptr [rsi + 4*rdi + 16], 3
48 c1 fb 07 | sar rbx, 7
48 c1 7c be 10 07 | sar qword ptr [rsi + 4*rdi + 16], 7
48 d3 fb | sar rbx, cl
48 d3 7c be 10 | sar qword ptr [rsi + 4*rdi + 16], cl
49 c1 fd 3f | sar r13, 63
49 c1 fd 00 | sar r13, 0
66 41 0f af d9 | imul bx, r9w
66 0f af 5c be 10 | imul bx, word ptr [rsi + 4*rdi + 16]
66 44 6b c1 f9 | imul r8w, cx, -7
66 44 69 c1 34 12 | imul r8w, cx, 0x1234
66 44 69 44 be 10 34 12 | imul r8w, word ptr [rsi + 4*rdi + 16], 0x1234
66 41 0f bc d9 | bsf bx, r9w
66 44 0f bc 54 be 10 | bsf r10w, word ptr [rsi + 4*rdi + 16]
66 41 0f bd d9 | bsr bx, r9w
66 44 0f bd 54 be 10 | bsr r10w, word ptr [rsi + 4*rdi + 16]
66 f3 41 0f b8 d9 | popcnt bx, r9w
66 f3 44 0f b8 54 be 10 | popcnt r10w, word ptr [rsi + 4*rdi + 16]
66 f3 41 0f bc d9 | tzcnt bx, r9w
66 f3 44 0f bc 54 be 10 | tzcnt r10w, word ptr [rsi + 4*rdi + 16]
66 f3 41 0f bd d9 | lzcnt bx, r9w
66 f3 44 0f bd 54 be 10 | lzcnt r10w, word ptr [rsi + 4*rdi + 16]
66 44 0f a3 cb | bt bx, r9w
66 41 0f ba e2 05 | bt r10w, 5
66 0f ba 64 be 10 0f | bt word ptr [rsi + 4*rdi + 16], 15
66 44 0f ab cb | bts bx, r9w
66 41 0f ba ea 05 | bts r10w, 5
66 0f ba 6c be 10 0f | bts word ptr [rsi + 4*rdi + 16], 15
66 44 0f b3 cb | btr bx, r9w
66 41 0f ba f2 05 | btr r10w, 5
66 0f ba 74 be 10 0f | btr word ptr [rsi + 4*rdi + 16], 15
66 44 0f bb cb | btc bx, r9w
66 41 0f ba fa 05 | btc r10w, 5
66 0f ba 7c be 10 0f | btc word ptr [rsi + 4*rdi + 16], 15
66 41 0f 40 d9 | cmovo bx, r9w
66 44 0f 40 54 be 10 | cmovo r10w, word ptr [rsi + 4*rdi + 16]
66 41 0f 41 d9 | cmovno bx, r9w
66 44 0f 41 54 be 10 | cmovno r10w, word ptr [rsi + 4*rdi + 16]
66 41 0f 42 d9 | cmovb bx, r9w
66 44 0f 42 54 be 10 | cmovb r10w, word ptr [rsi + 4*rdi + 16]
66 41 0f 43 d9 | cmovae bx, r9w
66 44 0f 43 54 be 10 | cmovae r10w, word ptr [rsi + 4*rdi + 16]
66 41 0f 44 d9 | cmove bx, r9w
66 44 0f 44 54 be 10 | cmove r10w, word ptr [rsi + 4*rdi + 16]
66 41 0f 45 d9 | cmovne bx, r9w
66 44 0f 45 54 be 10 | cmovne r10w, word ptr [rsi + 4*rdi + 16]
66 41 0f 46 d9 | cmovbe bx, r9w
66 44 0f 46 54 be 10 | cmovbe r10w, word ptr [rsi + 4*rdi + 16]
66 41 0f 47 d9 | cmova bx, r9w
66 44 0f 47 54 be 10 | cmova r10w, word ptr [rsi + 4*rdi + 16]
66 41 0f 48 d9 | cmovs bx, r9w
66 44 0f 48 54 be 10 | cmovs r10w, word ptr [rsi + 4*rdi + 16]
66 41 0f 49 d9 | cmovns bx, r9w
66 44 0f 49 54 be 10 | cmovns r10w, word ptr [rsi + 4*rdi + 16]
66 41 0f 4a d9 | cmovp bx, r9w
66 44 0f 4a 54 be 10 | cmovp r10w, word ptr [rsi + 4*rdi + 16]
66 41 0f 4b d9 | cmovnp bx, r9w
66 44 0f 4b 54 be 10 | cmovnp r10w, word ptr [rsi + 4*rdi + 16]
66 41 0f 4c d9 | cmovl bx, r9w
66 44 0f 4c 54 be 10 | cmovl r10w, word ptr [rsi + 4*rdi + 16]
66 41 0f 4d d9 | cmovge bx, r9w
66 44 0f 4d 54 be 10 | cmovge r10w, word ptr [rsi + 4*rdi + 16]
66 41 0f 4e d9 | cmovle bx, r9w
66 44 0f 4e 54 be 10 | cmovle r10w, word ptr [rsi + 4*rdi + 16]
66 41 0f 4f d9 | cmovg bx, r9w
66 44 0f 4f 54 be 10 | cmovg r10w, word ptr [rsi + 4*rdi + 16]
66 41 0f b6 d9 | movzx bx, r9b
66 44 0f b6 54 be 10 | movzx r10w, byte ptr [rsi + 4*rdi + 16]
66 41 0f be d9 | movsx bx, r9b
66 44 0f be 54 be 10 | movsx r10w, byte ptr [rsi + 4*rdi + 16]
66 8d 5c be 10 | lea bx, [rsi + 4*rdi + 16]
66 45 8d 61 fb | lea r12w, [r9 - 5]
66 42 8d 04 d5 40 00 00 00 | lea ax, [8*r10 + 64]
41 0f af d9 | imul ebx, r9d
0f af 5c be 10 | imul ebx, dword ptr [rsi + 4*rdi + 16]
44 6b c1 f9 | imul r8d, ecx, -7
44 69 c1 34 12 00 00 | imul r8d, ecx, 0x1234
44 69 44 be 10 34 12 00 00 | imul r8d, dword ptr [rsi + 4*rdi + 16], 0x1234
41 0f bc d9 | bsf ebx, r9d
44 0f bc 54 be 10 | bsf r10d, dword ptr [rsi + 4*rdi + 16]
41 0f bd d9 | bsr ebx, r9d
44 0f bd 54 be 10 | bsr r10d, dword ptr [rsi + 4*rdi + 16]
f3 41 0f b8 d9 | popcnt ebx, r9d
f3 44 0f b8 54 be 10 | popcnt r10d, dword ptr [rsi + 4*rdi + 16]
f3 41 0f bc d9 | tzcnt ebx, r9d
f3 44 0f bc 54 be 10 | tzcnt r10d, dword ptr [rsi + 4*rdi + 16]
f3 41 0f bd d9 | lzcnt ebx, r9d
f3 44 0f bd 54 be 10 | lzcnt r10d, dword ptr [rsi + 4*rdi + 16]
44 0f a3 cb | bt ebx, r9d
41 0f ba e2 05 | bt r10d, 5
0f ba 64 be 10 1f | bt dword ptr [rsi + 4*rdi + 16], 31
44 0f ab cb | bts ebx, r9d
41 0f ba ea 05 | bts r10d, 5
0f ba 6c be 10 1f | bts dword ptr [rsi + 4*rdi + 16], 31
44 0f b3 cb | btr ebx, r9d
41 0f ba f2 05 | btr r10d, 5
0f ba 74 be 10 1f | btr dword ptr [rsi + 4*rdi + 16], 31
44 0f bb cb | btc ebx, r9d
41 0f ba fa 05 | btc r10d, 5
0f ba 7c be 10 1f | btc dword ptr [rsi + 4*rdi + 16], 31
41 0f 40 d9 | cmovo ebx, r9d
44 0f 40 54 be 10 | cmovo r10d, dword ptr [rsi + 4*rdi + 16]
41 0f 41 d9 | cmovno ebx, r9d
44 0f 41 54 be 10 | cmovno r10d, dword ptr [rsi + 4*rdi + 16]
41 0f 42 d9 | cmovb ebx, r9d
44 0f 42 54 be 10 | cmovb r10d, dword ptr [rsi + 4*rdi + 16]
41 0f 43 d9 | cmovae ebx, r9d
44 0f 43 54 be 10 | cmovae r10d, dword ptr [rsi + 4*rdi + 16]
41 0f 44 d9 | cmove ebx, r9d
44 0f 44 54 be 10 | cmove r10d, dword ptr [rsi + 4*rdi + 16]
41 0f 45 d9 | cmovne ebx, r9d
44 0f 45 54 be 10 | cmovne r10d, dword ptr [rsi + 4*rdi + 16]
41 0f 46 d9 | cmovbe ebx, r9d
44 0f 46 54 be 10 | cmovbe r10d, dword ptr [rsi + 4*rdi + 16]
41 0f 47 d9 | cmova ebx, r9d
44 0f 47 54 be 10 | cmova r10d, dword ptr [rsi + 4*rdi + 16]
41 0f 48 d9 | cmovs ebx, r9d
44 0f 48 54 be 10 | cmovs r10d, dword ptr [rsi + 4*rdi + 16]
41 0f 49 d9 | cmovns ebx, r9d
44 0f 49 54 be 10 | cmovns r10d, dword ptr [rsi + 4*rdi + 16]
41 0f 4a d9 | cmovp ebx, r9d
44 0f 4a 54 be 10 | cmovp r10d, dword ptr [rsi + 4*rdi + 16]
41 0f 4b d9 | cmovnp ebx, r9d
44 0f 4b 54 be 10 | cmovnp r10d, dword ptr [rsi + 4*rdi + 16]
41 0f 4c d9 | cmovl ebx, r9d
44 0f 4c 54 be 10 | cmovl r10d, dword ptr [rsi + 4*rdi + 16]
41 0f 4d d9 | cmovge ebx, r9d
44 0f 4d 54 be 10 | cmovge r10d, dword ptr [rsi + 4*rdi + 16]
41 0f 4e d9 | cmovle ebx, r9d
44 0f 4e 54 be 10 | cmovle r10d, dword ptr [rsi + 4*rdi + 16]
41 0f 4f d9 | cmovg ebx, r9d
44 0f 4f 54 be 10 | cmovg r10d, dword ptr [rsi + 4*rdi + 16]
41 0f b6 d9 | movzx ebx, r9b
44 0f b6 54 be 10 | movzx r10d, byte ptr [rsi + 4*rdi + 16]
41 0f be d9 | movsx ebx, r9b
44 0f be 54 be 10 | movsx r10d, byte ptr [rsi + 4*rdi + 16]
41 0f b7 d9 | movzx ebx, r9w
44 0f b7 54 be 10 | movzx r10d, word ptr [rsi + 4*rdi + 16]
41 0f bf d9 | movsx ebx, r9w
44 0f bf 54 be 10 | movsx r10d, word ptr [rsi + 4*rdi + 16]
8d 5c be 10 | lea ebx, [rsi + 4*rdi + 16]
45 8d 61 fb | lea r12d, [r9 - 5]
42 8d 04 d5 40 00 00 00 | lea eax, [8*r10 + 64]
49 0f af d9 | imul rbx, r9
48 0f af 5c be 10 | imul rbx, qword ptr [rsi + 4*rdi + 16]
4c 6b c1 f9 | imul r8, rcx, -7
4c 69 c1 34 12 00 00 | imul r8, rcx, 0x1234
4c 69 44 be 10 34 12 00 00 | imul r8, qword ptr [rsi + 4*rdi + 16], 0x1234
49 0f bc d9 | bsf rbx, r9
4c 0f bc 54 be 10 | bsf r10, qword ptr [rsi + 4*rdi + 16]
49 0f bd d9 | bsr rbx, r9
4c 0f bd 54 be 10 | bsr r10, qword ptr [rsi + 4*rdi + 16]
f3 49 0f b8 d9 | popcnt rbx, r9
f3 4c 0f b8 54 be 10 | popcnt r10, qword ptr [rsi + 4*rdi + 16]
f3 49 0f bc d9 | tzcnt rbx, r9
f3 4c 0f bc 54 be 10 | tzcnt r10, qword ptr [rsi + 4*rdi + 16]
f3 49 0f bd d9 | lzcnt rbx, r9
f3 4c 0f bd 54 be 10 | lzcnt r10, qword ptr [rsi + 4*rdi + 16]
4c 0f a3 cb | bt rbx, r9
49 0f ba e2 05 | bt r10, 5
48 0f ba 64 be 10 3f | bt qword ptr [rsi + 4*rdi + 16], 63
4c 0f ab cb | bts rbx, r9
49 0f ba ea 05 | bts r10, 5
48 0f ba 6c be 10 3f | bts qword ptr [rsi + 4*rdi + 16], 63
4c 0f b3 cb | btr rbx, r9
49 0f ba f2 05 | btr r10, 5
48 0f ba 74 be 10 3f | btr qword ptr [rsi + 4*rdi + 16], 63
4c 0f bb cb | btc rbx, r9
49 0f ba fa 05 | btc r10, 5
48 0f ba 7c be 10 3f | btc qword ptr [rsi + 4*rdi + 16], 63
49 0f 40 d9 | cmovo rbx, r9
4c 0f 40 54 be 10 | cmovo r10, qword ptr [rsi + 4*rdi + 16]
49 0f 41 d9 | cmovno rbx, r9
4c 0f 41 54 be 10 | cmovno r10, qword ptr [rsi + 4*rdi + 16]
49 0f 42 d9 | cmovb rbx, r9
4c 0f 42 54 be 10 | cmovb r10, qword ptr [rsi + 4*rdi + 16]
49 0f 43 d9 | cmovae rbx, r9
4c 0f 43 54 be 10 | cmovae r10, qword ptr [rsi + 4*rdi + 16]
49 0f 44 d9 | cmove rbx, r9
4c 0f 44 54 be 10 | cmove r10, qword ptr [rsi + 4*rdi + 16]
49 0f 45 d9 | cmovne rbx, r9
4c 0f 45 54 be 10 | cmovne r10, qword ptr [rsi + 4*rdi + 16]
49 0f 46 d9 | cmovbe rbx, r9
4c 0f 46 54 be 10 | cmovbe r10, qword ptr [rsi + 4*rdi + 16]
49 0f 47 d9 | cmova rbx, r9
4c 0f 47 54 be 10 | cmova r10, qword ptr [rsi + 4*rdi + 16]
49 0f 48 d9 | cmovs rbx, r9
4c 0f 48 54 be 10 | cmovs r10, qword ptr [rsi + 4*rdi + 16]
49 0f 49 d9 | cmovns rbx, r9
4c 0f 49 54 be 10 | cmovns r10, qword ptr [rsi + 4*rdi + 16]
49 0f 4a d9 | cmovp rbx, r9
4c 0f 4a 54 be 10 | cmovp r10, qword ptr [rsi + 4*rdi + 16]
49 0f 4b d9 | cmovnp rbx, r9
4c 0f 4b 54 be 10 | cmovnp r10, qword ptr [rsi + 4*rdi + 16]
49 0f 4c d9 | cmovl rbx, r9
4c 0f 4c 54 be 10 | cmovl r10, qword ptr [rsi + 4*rdi + 16]
49 0f 4d d9 | cmovge rbx, r9
4c 0f 4d 54 be 10 | cmovge r10, qword ptr [rsi + 4*rdi + 16]
49 0f 4e d9 | cmovle rbx, r9
4c 0f 4e 54 be 10 | cmovle r10, qword ptr [rsi + 4*rdi + 16]
49 0f 4f d9 | cmovg rbx, r9
4c 0f 4f 54 be 10 | cmovg r10, qword ptr [rsi + 4*rdi + 16]
49 0f b6 d9 | movzx rbx, r9b
4c 0f b6 54 be 10 | movzx r10, byte ptr [rsi + 4*rdi + 16]
49 0f be d9 | movsx rbx, r9b
4c 0f be 54 be 10 | movsx r10, byte ptr [rsi + 4*rdi + 16]
49 0f b7 d9 | movzx rbx, r9w
4c 0f b7 54 be 10 | movzx r10, word ptr [rsi + 4*rdi + 16]
49 0f bf d9 | movsx rbx, r9w
4c 0f bf 54 be 10 | movsx r10, word ptr [rsi + 4*rdi + 16]
48 8d 5c be 10 | lea rbx, [rsi + 4*rdi + 16]
4d 8d 61 fb | lea r12, [r9 - 5]
4a 8d 04 d5 40 00 00 00 | lea rax, [8*r10 + 64]
49 63 d9 | movsxd rbx, r9d
4c 63 54 be 10 | movsxd r10, dword ptr [rsi + 4*rdi + 16]
0f b6 dc | movzx ebx, ah
0f be cf | movsx ecx, bh
0f 90 c3 | seto bl
0f 90 44 be 10 | seto byte ptr [rsi + 4*rdi + 16]
0f 90 c4 | seto ah
0f 91 c3 | setno bl
0f 91 44 be 10 | setno byte ptr [rsi + 4*rdi + 16]
0f 91 c4 | setno ah
0f 92 c3 | setb bl
0f 92 44 be 10 | setb byte ptr [rsi + 4*rdi + 16]
0f 92 c4 | setb ah
0f 93 c3 | setae bl
0f 93 44 be 10 | setae byte ptr [rsi + 4*rdi + 16]
0f 93 c4 | setae ah
0f 94 c3 | sete bl
0f 94 44 be 10 | sete byte ptr [rsi + 4*rdi + 16]
0f 94 c4 | sete ah
0f 95 c3 | setne bl
0f 95 44 be 10 | setne byte ptr [rsi + 4*rdi + 16]
0f 95 c4 | setne ah
0f 96 c3 | setbe bl
0f 96 44 be 10 | setbe byte ptr [rsi + 4*rdi + 16]
0f 96 c4 | setbe ah
0f 97 c3 | seta bl
0f 97 44 be 10 | seta byte ptr [rsi + 4*rdi + 16]
0f 97 c4 | seta ah
0f 98 c3 | sets bl
0f 98 44 be 10 | sets byte ptr [rsi + 4*rdi + 16]
0f 98 c4 | sets ah
0f 99 c3 | setns bl
0f 99 44 be 10 | setns byte ptr [rsi + 4*rdi + 16]
0f 99 c4 | setns ah
0f 9a c3 | setp bl
0f 9a 44 be 10 | setp byte ptr [rsi + 4*rdi + 16]
0f 9a c4 | setp ah
0f 9b c3 | setnp bl
0f 9b 44 be 10 | setnp byte ptr [rsi + 4*rdi + 16]
0f 9b c4 | setnp ah
0f 9c c3 | setl bl
0f 9c 44 be 10 | setl byte ptr [rsi + 4*rdi + 16]
0f 9c c4 | setl ah
0f 9d c3 | setge bl
0f 9d 44 be 10 | setge byte ptr [rsi + 4*rdi + 16]
0f 9d c4 | setge ah
0f 9e c3 | setle bl
0f 9e 44 be 10 | setle byte ptr [rsi + 4*rdi + 16]
0f 9e c4 | setle ah
0f 9f c3 | setg bl
0f 9f 44 be 10 | setg byte ptr [rsi + 4*rdi + 16]
0f 9f c4 | setg ah
44 88 cb | mov bl, r9b
44 8a 54 be 10 | mov r10b, byte ptr [rsi + 4*rdi + 16]
88 54 be 10 | mov byte ptr [rsi + 4*rdi + 16], dl
41 b6 5a | mov r14b, 0x5a
c6 44 be 10 5a | mov byte ptr [rsi + 4*rdi + 16], 0x5a
41 86 d9 | xchg bl, r9b
86 54 be 10 | xchg byte ptr [rsi + 4*rdi + 16], dl
66 44 89 cb | mov bx, r9w
66 44 8b 54 be 10 | mov r10w, word ptr [rsi + 4*rdi + 16]
66 89 54 be 10 | mov word ptr [rsi + 4*rdi + 16], dx
66 41 be 5a 00 | mov r14w, 0x5a
66 c7 44 be 10 5a 00 | mov word ptr [rsi + 4*rdi + 16], 0x5a
66 41 87 d9 | xchg bx, r9w
66 87 54 be 10 | xchg word ptr [rsi + 4*rdi + 16], dx
44 89 cb | mov ebx, r9d
44 8b 54 be 10 | mov r10d, dword ptr [rsi + 4*rdi + 16]
89 54 be 10 | mov dword ptr [rsi + 4*rdi + 16], edx
41 be 5a 00 00 00 | mov r14d, 0x5a
c7 44 be 10 5a 00 00 00 | mov dword ptr [rsi + 4*rdi + 16], 0x5a
41 87 d9 | xchg ebx, r9d
87 54 be 10 | xchg dword ptr [rsi + 4*rdi + 16], edx
4c 89 cb | mov rbx, r9
4c 8b 54 be 10 | mov r10, qword ptr [rsi + 4*rdi + 16]
48 89 54 be 10 | mov qword ptr [rsi + 4*rdi + 16], rdx
49 c7 c6 5a 00 00 00 | mov r14, 0x5a
48 c7 44 be 10 5a 00 00 00 | mov qword ptr [rsi + 4*rdi + 16], 0x5a
49 87 d9 | xchg rbx, r9
48 87 54 be 10 | xchg qword ptr [rsi + 4*rdi + 16], rdx
88 dc | mov ah, bl
88 ea | mov dl, ch
b7 21 | mov bh, 0x21
86 e3 | xchg ah, bl
40 88 fe | mov sil, dil
49 bf 11 22 33 44 55 66 77 88 | movabs r15, 0x8877665544332211
48 c7 c1 fe ff ff ff | mov rcx, -2
0f cb | bswap ebx
49 0f c9 | bswap r9
66 98 | cbw
98 | cwde
48 98 | cdqe
66 99 | cwd
99 | cdq
48 99 | cqo
f8 | clc
f9 | stc
f5 | cmc
90 | nop
0f 1f 40 08 | nop dword ptr [rax + 8]
f3 90 | pause
41 51 | push r9
53 | push rbx
6a fb | push -5
68 78 56 34 12 | push 0x12345678
ff 74 be 10 | push qword ptr [rsi + 4*rdi + 16]
5b | pop rbx
41 5c | pop r12
8f 44 be 10 | pop qword ptr [rsi + 4*rdi + 16]
c9 | leave
+374
View File
@@ -0,0 +1,374 @@
66 41 0f 60 d9 | punpcklbw xmm3, xmm9
66 44 0f 60 54 be 10 | punpcklbw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 60 d2 | punpcklbw xmm2, xmm2
66 41 0f 61 d9 | punpcklwd xmm3, xmm9
66 44 0f 61 54 be 10 | punpcklwd xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 61 d2 | punpcklwd xmm2, xmm2
66 41 0f 62 d9 | punpckldq xmm3, xmm9
66 44 0f 62 54 be 10 | punpckldq xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 62 d2 | punpckldq xmm2, xmm2
66 41 0f 6c d9 | punpcklqdq xmm3, xmm9
66 44 0f 6c 54 be 10 | punpcklqdq xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 6c d2 | punpcklqdq xmm2, xmm2
66 41 0f 68 d9 | punpckhbw xmm3, xmm9
66 44 0f 68 54 be 10 | punpckhbw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 68 d2 | punpckhbw xmm2, xmm2
66 41 0f 69 d9 | punpckhwd xmm3, xmm9
66 44 0f 69 54 be 10 | punpckhwd xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 69 d2 | punpckhwd xmm2, xmm2
66 41 0f 6a d9 | punpckhdq xmm3, xmm9
66 44 0f 6a 54 be 10 | punpckhdq xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 6a d2 | punpckhdq xmm2, xmm2
66 41 0f 6d d9 | punpckhqdq xmm3, xmm9
66 44 0f 6d 54 be 10 | punpckhqdq xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 6d d2 | punpckhqdq xmm2, xmm2
66 41 0f 63 d9 | packsswb xmm3, xmm9
66 44 0f 63 54 be 10 | packsswb xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 63 d2 | packsswb xmm2, xmm2
66 41 0f 6b d9 | packssdw xmm3, xmm9
66 44 0f 6b 54 be 10 | packssdw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 6b d2 | packssdw xmm2, xmm2
66 41 0f 67 d9 | packuswb xmm3, xmm9
66 44 0f 67 54 be 10 | packuswb xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 67 d2 | packuswb xmm2, xmm2
66 41 0f 64 d9 | pcmpgtb xmm3, xmm9
66 44 0f 64 54 be 10 | pcmpgtb xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 64 d2 | pcmpgtb xmm2, xmm2
66 41 0f 65 d9 | pcmpgtw xmm3, xmm9
66 44 0f 65 54 be 10 | pcmpgtw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 65 d2 | pcmpgtw xmm2, xmm2
66 41 0f 66 d9 | pcmpgtd xmm3, xmm9
66 44 0f 66 54 be 10 | pcmpgtd xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 66 d2 | pcmpgtd xmm2, xmm2
66 41 0f 74 d9 | pcmpeqb xmm3, xmm9
66 44 0f 74 54 be 10 | pcmpeqb xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 74 d2 | pcmpeqb xmm2, xmm2
66 41 0f 75 d9 | pcmpeqw xmm3, xmm9
66 44 0f 75 54 be 10 | pcmpeqw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 75 d2 | pcmpeqw xmm2, xmm2
66 41 0f 76 d9 | pcmpeqd xmm3, xmm9
66 44 0f 76 54 be 10 | pcmpeqd xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 76 d2 | pcmpeqd xmm2, xmm2
66 41 0f fc d9 | paddb xmm3, xmm9
66 44 0f fc 54 be 10 | paddb xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f fc d2 | paddb xmm2, xmm2
66 41 0f fd d9 | paddw xmm3, xmm9
66 44 0f fd 54 be 10 | paddw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f fd d2 | paddw xmm2, xmm2
66 41 0f fe d9 | paddd xmm3, xmm9
66 44 0f fe 54 be 10 | paddd xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f fe d2 | paddd xmm2, xmm2
66 41 0f d4 d9 | paddq xmm3, xmm9
66 44 0f d4 54 be 10 | paddq xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f d4 d2 | paddq xmm2, xmm2
66 41 0f f8 d9 | psubb xmm3, xmm9
66 44 0f f8 54 be 10 | psubb xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f f8 d2 | psubb xmm2, xmm2
66 41 0f f9 d9 | psubw xmm3, xmm9
66 44 0f f9 54 be 10 | psubw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f f9 d2 | psubw xmm2, xmm2
66 41 0f fa d9 | psubd xmm3, xmm9
66 44 0f fa 54 be 10 | psubd xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f fa d2 | psubd xmm2, xmm2
66 41 0f fb d9 | psubq xmm3, xmm9
66 44 0f fb 54 be 10 | psubq xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f fb d2 | psubq xmm2, xmm2
66 41 0f ec d9 | paddsb xmm3, xmm9
66 44 0f ec 54 be 10 | paddsb xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f ec d2 | paddsb xmm2, xmm2
66 41 0f ed d9 | paddsw xmm3, xmm9
66 44 0f ed 54 be 10 | paddsw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f ed d2 | paddsw xmm2, xmm2
66 41 0f dc d9 | paddusb xmm3, xmm9
66 44 0f dc 54 be 10 | paddusb xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f dc d2 | paddusb xmm2, xmm2
66 41 0f dd d9 | paddusw xmm3, xmm9
66 44 0f dd 54 be 10 | paddusw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f dd d2 | paddusw xmm2, xmm2
66 41 0f e8 d9 | psubsb xmm3, xmm9
66 44 0f e8 54 be 10 | psubsb xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f e8 d2 | psubsb xmm2, xmm2
66 41 0f e9 d9 | psubsw xmm3, xmm9
66 44 0f e9 54 be 10 | psubsw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f e9 d2 | psubsw xmm2, xmm2
66 41 0f d8 d9 | psubusb xmm3, xmm9
66 44 0f d8 54 be 10 | psubusb xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f d8 d2 | psubusb xmm2, xmm2
66 41 0f d9 d9 | psubusw xmm3, xmm9
66 44 0f d9 54 be 10 | psubusw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f d9 d2 | psubusw xmm2, xmm2
66 41 0f d5 d9 | pmullw xmm3, xmm9
66 44 0f d5 54 be 10 | pmullw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f d5 d2 | pmullw xmm2, xmm2
66 41 0f e5 d9 | pmulhw xmm3, xmm9
66 44 0f e5 54 be 10 | pmulhw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f e5 d2 | pmulhw xmm2, xmm2
66 41 0f e4 d9 | pmulhuw xmm3, xmm9
66 44 0f e4 54 be 10 | pmulhuw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f e4 d2 | pmulhuw xmm2, xmm2
66 41 0f f4 d9 | pmuludq xmm3, xmm9
66 44 0f f4 54 be 10 | pmuludq xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f f4 d2 | pmuludq xmm2, xmm2
66 41 0f f5 d9 | pmaddwd xmm3, xmm9
66 44 0f f5 54 be 10 | pmaddwd xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f f5 d2 | pmaddwd xmm2, xmm2
66 41 0f f6 d9 | psadbw xmm3, xmm9
66 44 0f f6 54 be 10 | psadbw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f f6 d2 | psadbw xmm2, xmm2
66 41 0f e0 d9 | pavgb xmm3, xmm9
66 44 0f e0 54 be 10 | pavgb xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f e0 d2 | pavgb xmm2, xmm2
66 41 0f e3 d9 | pavgw xmm3, xmm9
66 44 0f e3 54 be 10 | pavgw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f e3 d2 | pavgw xmm2, xmm2
66 41 0f da d9 | pminub xmm3, xmm9
66 44 0f da 54 be 10 | pminub xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f da d2 | pminub xmm2, xmm2
66 41 0f de d9 | pmaxub xmm3, xmm9
66 44 0f de 54 be 10 | pmaxub xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f de d2 | pmaxub xmm2, xmm2
66 41 0f ea d9 | pminsw xmm3, xmm9
66 44 0f ea 54 be 10 | pminsw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f ea d2 | pminsw xmm2, xmm2
66 41 0f ee d9 | pmaxsw xmm3, xmm9
66 44 0f ee 54 be 10 | pmaxsw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f ee d2 | pmaxsw xmm2, xmm2
66 41 0f db d9 | pand xmm3, xmm9
66 44 0f db 54 be 10 | pand xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f db d2 | pand xmm2, xmm2
66 41 0f df d9 | pandn xmm3, xmm9
66 44 0f df 54 be 10 | pandn xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f df d2 | pandn xmm2, xmm2
66 41 0f eb d9 | por xmm3, xmm9
66 44 0f eb 54 be 10 | por xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f eb d2 | por xmm2, xmm2
66 41 0f ef d9 | pxor xmm3, xmm9
66 44 0f ef 54 be 10 | pxor xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f ef d2 | pxor xmm2, xmm2
41 0f 54 d9 | andps xmm3, xmm9
44 0f 54 54 be 10 | andps xmm10, xmmword ptr [rsi + 4*rdi + 16]
0f 54 d2 | andps xmm2, xmm2
66 41 0f 54 d9 | andpd xmm3, xmm9
66 44 0f 54 54 be 10 | andpd xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 54 d2 | andpd xmm2, xmm2
41 0f 55 d9 | andnps xmm3, xmm9
44 0f 55 54 be 10 | andnps xmm10, xmmword ptr [rsi + 4*rdi + 16]
0f 55 d2 | andnps xmm2, xmm2
66 41 0f 55 d9 | andnpd xmm3, xmm9
66 44 0f 55 54 be 10 | andnpd xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 55 d2 | andnpd xmm2, xmm2
41 0f 56 d9 | orps xmm3, xmm9
44 0f 56 54 be 10 | orps xmm10, xmmword ptr [rsi + 4*rdi + 16]
0f 56 d2 | orps xmm2, xmm2
66 41 0f 56 d9 | orpd xmm3, xmm9
66 44 0f 56 54 be 10 | orpd xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 56 d2 | orpd xmm2, xmm2
41 0f 57 d9 | xorps xmm3, xmm9
44 0f 57 54 be 10 | xorps xmm10, xmmword ptr [rsi + 4*rdi + 16]
0f 57 d2 | xorps xmm2, xmm2
66 41 0f 57 d9 | xorpd xmm3, xmm9
66 44 0f 57 54 be 10 | xorpd xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 57 d2 | xorpd xmm2, xmm2
41 0f 14 d9 | unpcklps xmm3, xmm9
44 0f 14 54 be 10 | unpcklps xmm10, xmmword ptr [rsi + 4*rdi + 16]
0f 14 d2 | unpcklps xmm2, xmm2
66 41 0f 14 d9 | unpcklpd xmm3, xmm9
66 44 0f 14 54 be 10 | unpcklpd xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 14 d2 | unpcklpd xmm2, xmm2
41 0f 15 d9 | unpckhps xmm3, xmm9
44 0f 15 54 be 10 | unpckhps xmm10, xmmword ptr [rsi + 4*rdi + 16]
0f 15 d2 | unpckhps xmm2, xmm2
66 41 0f 15 d9 | unpckhpd xmm3, xmm9
66 44 0f 15 54 be 10 | unpckhpd xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 15 d2 | unpckhpd xmm2, xmm2
66 41 0f f1 d9 | psllw xmm3, xmm9
66 44 0f f1 54 be 10 | psllw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f f1 d2 | psllw xmm2, xmm2
66 41 0f f2 d9 | pslld xmm3, xmm9
66 44 0f f2 54 be 10 | pslld xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f f2 d2 | pslld xmm2, xmm2
66 41 0f f3 d9 | psllq xmm3, xmm9
66 44 0f f3 54 be 10 | psllq xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f f3 d2 | psllq xmm2, xmm2
66 41 0f d1 d9 | psrlw xmm3, xmm9
66 44 0f d1 54 be 10 | psrlw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f d1 d2 | psrlw xmm2, xmm2
66 41 0f d2 d9 | psrld xmm3, xmm9
66 44 0f d2 54 be 10 | psrld xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f d2 d2 | psrld xmm2, xmm2
66 41 0f d3 d9 | psrlq xmm3, xmm9
66 44 0f d3 54 be 10 | psrlq xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f d3 d2 | psrlq xmm2, xmm2
66 41 0f e1 d9 | psraw xmm3, xmm9
66 44 0f e1 54 be 10 | psraw xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f e1 d2 | psraw xmm2, xmm2
66 41 0f e2 d9 | psrad xmm3, xmm9
66 44 0f e2 54 be 10 | psrad xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f e2 d2 | psrad xmm2, xmm2
41 0f 28 d9 | movaps xmm3, xmm9
44 0f 28 54 be 10 | movaps xmm10, xmmword ptr [rsi + 4*rdi + 16]
0f 28 d2 | movaps xmm2, xmm2
66 41 0f 28 d9 | movapd xmm3, xmm9
66 44 0f 28 54 be 10 | movapd xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 28 d2 | movapd xmm2, xmm2
41 0f 10 d9 | movups xmm3, xmm9
44 0f 10 54 be 10 | movups xmm10, xmmword ptr [rsi + 4*rdi + 16]
0f 10 d2 | movups xmm2, xmm2
66 41 0f 10 d9 | movupd xmm3, xmm9
66 44 0f 10 54 be 10 | movupd xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 10 d2 | movupd xmm2, xmm2
66 41 0f 6f d9 | movdqa xmm3, xmm9
66 44 0f 6f 54 be 10 | movdqa xmm10, xmmword ptr [rsi + 4*rdi + 16]
66 0f 6f d2 | movdqa xmm2, xmm2
f3 41 0f 6f d9 | movdqu xmm3, xmm9
f3 44 0f 6f 54 be 10 | movdqu xmm10, xmmword ptr [rsi + 4*rdi + 16]
f3 0f 6f d2 | movdqu xmm2, xmm2
44 0f 29 5c be 10 | movaps xmmword ptr [rsi + 4*rdi + 16], xmm11
66 44 0f 29 5c be 10 | movapd xmmword ptr [rsi + 4*rdi + 16], xmm11
44 0f 11 5c be 10 | movups xmmword ptr [rsi + 4*rdi + 16], xmm11
66 44 0f 11 5c be 10 | movupd xmmword ptr [rsi + 4*rdi + 16], xmm11
66 44 0f 7f 5c be 10 | movdqa xmmword ptr [rsi + 4*rdi + 16], xmm11
f3 44 0f 7f 5c be 10 | movdqu xmmword ptr [rsi + 4*rdi + 16], xmm11
66 44 0f e7 5c be 10 | movntdq xmmword ptr [rsi + 4*rdi + 16], xmm11
44 0f 2b 5c be 10 | movntps xmmword ptr [rsi + 4*rdi + 16], xmm11
66 44 0f 2b 5c be 10 | movntpd xmmword ptr [rsi + 4*rdi + 16], xmm11
f3 41 0f 10 d9 | movss xmm3, xmm9
f3 44 0f 10 54 be 10 | movss xmm10, dword ptr [rsi + 4*rdi + 16]
f3 44 0f 11 5c be 10 | movss dword ptr [rsi + 4*rdi + 16], xmm11
f2 41 0f 10 d9 | movsd xmm3, xmm9
f2 44 0f 10 54 be 10 | movsd xmm10, qword ptr [rsi + 4*rdi + 16]
f2 44 0f 11 5c be 10 | movsd qword ptr [rsi + 4*rdi + 16], xmm11
f3 41 0f 7e d9 | movq xmm3, xmm9
f3 44 0f 7e 54 be 10 | movq xmm10, qword ptr [rsi + 4*rdi + 16]
66 44 0f d6 5c be 10 | movq qword ptr [rsi + 4*rdi + 16], xmm11
0f 12 5c be 10 | movlps xmm3, qword ptr [rsi + 4*rdi + 16]
44 0f 13 4c be 10 | movlps qword ptr [rsi + 4*rdi + 16], xmm9
66 0f 12 5c be 10 | movlpd xmm3, qword ptr [rsi + 4*rdi + 16]
66 44 0f 13 4c be 10 | movlpd qword ptr [rsi + 4*rdi + 16], xmm9
0f 16 5c be 10 | movhps xmm3, qword ptr [rsi + 4*rdi + 16]
44 0f 17 4c be 10 | movhps qword ptr [rsi + 4*rdi + 16], xmm9
66 0f 16 5c be 10 | movhpd xmm3, qword ptr [rsi + 4*rdi + 16]
66 44 0f 17 4c be 10 | movhpd qword ptr [rsi + 4*rdi + 16], xmm9
41 0f 12 d9 | movhlps xmm3, xmm9
44 0f 16 d1 | movlhps xmm10, xmm1
0f 12 d2 | movhlps xmm2, xmm2
0f 16 d2 | movlhps xmm2, xmm2
66 41 0f 6e d9 | movd xmm3, r9d
66 44 0f 6e e0 | movd xmm12, eax
66 49 0f 6e d9 | movq xmm3, r9
66 41 0f 7e d9 | movd r9d, xmm3
66 44 0f 7e e3 | movd ebx, xmm12
66 49 0f 7e d9 | movq r9, xmm3
66 0f 6e 5c be 10 | movd xmm3, dword ptr [rsi + 4*rdi + 16]
66 44 0f 7e 4c be 10 | movd dword ptr [rsi + 4*rdi + 16], xmm9
41 0f 50 d9 | movmskps ebx, xmm9
44 0f 50 d3 | movmskps r10d, xmm3
66 41 0f 50 d9 | movmskpd ebx, xmm9
66 44 0f 50 d3 | movmskpd r10d, xmm3
66 41 0f d7 d9 | pmovmskb ebx, xmm9
66 44 0f d7 d3 | pmovmskb r10d, xmm3
66 0f 71 f3 00 | psllw xmm3, 0
66 41 0f 71 f1 01 | psllw xmm9, 1
66 41 0f 71 f1 07 | psllw xmm9, 7
66 41 0f 71 f1 0f | psllw xmm9, 15
66 0f 71 f3 10 | psllw xmm3, 16
66 41 0f 71 f1 ff | psllw xmm9, 255
66 0f 71 d3 00 | psrlw xmm3, 0
66 41 0f 71 d1 01 | psrlw xmm9, 1
66 41 0f 71 d1 07 | psrlw xmm9, 7
66 41 0f 71 d1 0f | psrlw xmm9, 15
66 0f 71 d3 10 | psrlw xmm3, 16
66 41 0f 71 d1 ff | psrlw xmm9, 255
66 0f 71 e3 00 | psraw xmm3, 0
66 41 0f 71 e1 01 | psraw xmm9, 1
66 41 0f 71 e1 07 | psraw xmm9, 7
66 41 0f 71 e1 0f | psraw xmm9, 15
66 0f 71 e3 10 | psraw xmm3, 16
66 41 0f 71 e1 ff | psraw xmm9, 255
66 0f 72 f3 00 | pslld xmm3, 0
66 41 0f 72 f1 01 | pslld xmm9, 1
66 41 0f 72 f1 07 | pslld xmm9, 7
66 41 0f 72 f1 1f | pslld xmm9, 31
66 0f 72 f3 20 | pslld xmm3, 32
66 41 0f 72 f1 ff | pslld xmm9, 255
66 0f 72 d3 00 | psrld xmm3, 0
66 41 0f 72 d1 01 | psrld xmm9, 1
66 41 0f 72 d1 07 | psrld xmm9, 7
66 41 0f 72 d1 1f | psrld xmm9, 31
66 0f 72 d3 20 | psrld xmm3, 32
66 41 0f 72 d1 ff | psrld xmm9, 255
66 0f 72 e3 00 | psrad xmm3, 0
66 41 0f 72 e1 01 | psrad xmm9, 1
66 41 0f 72 e1 07 | psrad xmm9, 7
66 41 0f 72 e1 1f | psrad xmm9, 31
66 0f 72 e3 20 | psrad xmm3, 32
66 41 0f 72 e1 ff | psrad xmm9, 255
66 0f 73 f3 00 | psllq xmm3, 0
66 41 0f 73 f1 01 | psllq xmm9, 1
66 41 0f 73 f1 07 | psllq xmm9, 7
66 41 0f 73 f1 3f | psllq xmm9, 63
66 0f 73 f3 40 | psllq xmm3, 64
66 41 0f 73 f1 ff | psllq xmm9, 255
66 0f 73 d3 00 | psrlq xmm3, 0
66 41 0f 73 d1 01 | psrlq xmm9, 1
66 41 0f 73 d1 07 | psrlq xmm9, 7
66 41 0f 73 d1 3f | psrlq xmm9, 63
66 0f 73 d3 40 | psrlq xmm3, 64
66 41 0f 73 d1 ff | psrlq xmm9, 255
66 41 0f 73 f9 00 | pslldq xmm9, 0
66 41 0f 73 f9 01 | pslldq xmm9, 1
66 41 0f 73 f9 05 | pslldq xmm9, 5
66 41 0f 73 f9 0f | pslldq xmm9, 15
66 41 0f 73 f9 10 | pslldq xmm9, 16
66 41 0f 73 f9 ff | pslldq xmm9, 255
66 41 0f 73 d9 00 | psrldq xmm9, 0
66 41 0f 73 d9 01 | psrldq xmm9, 1
66 41 0f 73 d9 05 | psrldq xmm9, 5
66 41 0f 73 d9 0f | psrldq xmm9, 15
66 41 0f 73 d9 10 | psrldq xmm9, 16
66 41 0f 73 d9 ff | psrldq xmm9, 255
66 41 0f 70 d9 00 | pshufd xmm3, xmm9, 0
66 41 0f 70 d9 1b | pshufd xmm3, xmm9, 27
66 41 0f 70 d9 4e | pshufd xmm3, xmm9, 78
66 41 0f 70 d9 b1 | pshufd xmm3, xmm9, 177
66 41 0f 70 d9 ff | pshufd xmm3, xmm9, 255
66 44 0f 70 54 be 10 72 | pshufd xmm10, xmmword ptr [rsi + 4*rdi + 16], 114
66 0f 70 d2 39 | pshufd xmm2, xmm2, 57
f3 41 0f 70 d9 00 | pshufhw xmm3, xmm9, 0
f3 41 0f 70 d9 1b | pshufhw xmm3, xmm9, 27
f3 41 0f 70 d9 4e | pshufhw xmm3, xmm9, 78
f3 41 0f 70 d9 b1 | pshufhw xmm3, xmm9, 177
f3 41 0f 70 d9 ff | pshufhw xmm3, xmm9, 255
f3 44 0f 70 54 be 10 72 | pshufhw xmm10, xmmword ptr [rsi + 4*rdi + 16], 114
f3 0f 70 d2 39 | pshufhw xmm2, xmm2, 57
f2 41 0f 70 d9 00 | pshuflw xmm3, xmm9, 0
f2 41 0f 70 d9 1b | pshuflw xmm3, xmm9, 27
f2 41 0f 70 d9 4e | pshuflw xmm3, xmm9, 78
f2 41 0f 70 d9 b1 | pshuflw xmm3, xmm9, 177
f2 41 0f 70 d9 ff | pshuflw xmm3, xmm9, 255
f2 44 0f 70 54 be 10 72 | pshuflw xmm10, xmmword ptr [rsi + 4*rdi + 16], 114
f2 0f 70 d2 39 | pshuflw xmm2, xmm2, 57
41 0f c6 d9 00 | shufps xmm3, xmm9, 0
41 0f c6 d9 1b | shufps xmm3, xmm9, 27
41 0f c6 d9 4e | shufps xmm3, xmm9, 78
41 0f c6 d9 b1 | shufps xmm3, xmm9, 177
41 0f c6 d9 ff | shufps xmm3, xmm9, 255
44 0f c6 54 be 10 72 | shufps xmm10, xmmword ptr [rsi + 4*rdi + 16], 114
0f c6 d2 39 | shufps xmm2, xmm2, 57
66 41 0f c6 d9 00 | shufpd xmm3, xmm9, 0
66 41 0f c6 d9 1b | shufpd xmm3, xmm9, 27
66 41 0f c6 d9 4e | shufpd xmm3, xmm9, 78
66 41 0f c6 d9 b1 | shufpd xmm3, xmm9, 177
66 41 0f c6 d9 ff | shufpd xmm3, xmm9, 255
66 44 0f c6 54 be 10 72 | shufpd xmm10, xmmword ptr [rsi + 4*rdi + 16], 114
66 0f c6 d2 39 | shufpd xmm2, xmm2, 57
66 44 0f c4 cb 00 | pinsrw xmm9, ebx, 0
66 0f c4 5c be 10 00 | pinsrw xmm3, word ptr [rsi + 4*rdi + 16], 0
66 44 0f c5 cb 00 | pextrw r9d, xmm3, 0
66 44 0f c4 cb 03 | pinsrw xmm9, ebx, 3
66 0f c4 5c be 10 03 | pinsrw xmm3, word ptr [rsi + 4*rdi + 16], 3
66 44 0f c5 cb 03 | pextrw r9d, xmm3, 3
66 44 0f c4 cb 07 | pinsrw xmm9, ebx, 7
66 0f c4 5c be 10 07 | pinsrw xmm3, word ptr [rsi + 4*rdi + 16], 7
66 44 0f c5 cb 07 | pextrw r9d, xmm3, 7
0f ae 5c be 10 | stmxcsr dword ptr [rsi + 4*rdi + 16]
+611
View File
@@ -0,0 +1,611 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! SSE and SSE2 floating-point tests.
//!
//! Expected values come from `tests/x86/float_vectors.txt`, computed with exact
//! fractions by `tests/x86/float_reference.py` from the Intel SDM rules, and, for
//! round-to-nearest values, from the ARM64 host's IEEE 754 hardware. Encodings
//! come from LLVM (`tests/x86/float.txt`). Neither shares code with
//! `softfloat.rs`.
use std::collections::BTreeMap;
use xenora_loader::cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, Mxcsr, RFlags};
use xenora_loader::dbt::DbtEngine;
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
use xenora_loader::softfloat::{self, Arithmetic, Control, F32, F64, Format};
const ENTRY: u64 = 0x1000;
const DATA: u64 = 0x2000;
/// Address of `[rsi + 4*rdi + 16]` with RSI = DATA and RDI = 4.
const OPERAND: u64 = DATA + 32;
const FILLER: u128 = 0x1122_3344_5566_7788_99AA_BBCC_DDEE_FF00;
fn fixture() -> BTreeMap<&'static str, Vec<u8>> {
include_str!("x86/float.txt")
.lines()
.map(|line| {
let (hex, text) = line.split_once(" | ").unwrap();
let code = hex
.split(' ')
.map(|b| u8::from_str_radix(b, 16).unwrap())
.collect();
(text, code)
})
.collect()
}
#[derive(Clone, Copy, Debug)]
struct Vector {
name: &'static str,
mxcsr: u32,
a: u64,
b: u64,
result: u64,
flags: u32,
}
fn vectors() -> Vec<Vector> {
include_str!("x86/float_vectors.txt")
.lines()
.map(|line| {
let parts: Vec<&str> = line.split(' ').collect();
let hex = |index: usize| u64::from_str_radix(parts[index], 16).unwrap();
Vector {
name: parts[0],
mxcsr: hex(1) as u32,
a: hex(2),
b: hex(3),
result: hex(4),
flags: hex(5) as u32,
}
})
.collect()
}
/// Where an operation's result goes and how wide its operands are.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Kind {
/// Lane 0 of XMM3, keeping the rest.
Scalar {
source: u32,
result: u32,
},
/// R9 from XMM9.
ToGeneral {
source: u32,
},
/// Lane 0 of XMM3 from R9.
FromGeneral {
source: u32,
result: u32,
},
Flags {
source: u32,
},
}
fn width(text: &str) -> u32 {
if text.contains("ss") { 32 } else { 64 }
}
/// Instruction text for the register form, and the kind, of a vector's name.
fn instruction(name: &str) -> (String, Kind) {
if name == "cvtss2sd" || name == "cvtsd2ss" {
let source = if name == "cvtss2sd" { 32 } else { 64 };
return (
format!("{name} xmm3, xmm9"),
Kind::Scalar {
source,
result: 96 - source,
},
);
}
if let Some(rest) = name.strip_prefix("cvtsi2") {
let (format, size) = rest.split_at(2);
let register = if size == "d" { "r9d" } else { "r9" };
let source = if size == "d" { 32 } else { 64 };
let text = format!("cvtsi2{format} xmm3, {register}");
return (
text,
Kind::FromGeneral {
source,
result: width(format),
},
);
}
if name.contains("2si") {
let (stem, size) = name.split_at(name.len() - 1);
let register = if size == "d" { "r9d" } else { "r9" };
let source = if stem.contains("ss2") { 32 } else { 64 };
return (
format!("{stem} {register}, xmm9"),
Kind::ToGeneral { source },
);
}
if name.contains("comi") {
let source = if name.ends_with("ss") { 32 } else { 64 };
return (format!("{name} xmm3, xmm9"), Kind::Flags { source });
}
if let Some(rest) = name.strip_prefix("cmp") {
let (format, code) = rest.split_at(2);
let bits = if format == "ss" { 32 } else { 64 };
return (
format!("cmp{format} xmm3, xmm9, {code}"),
Kind::Scalar {
source: bits,
result: bits,
},
);
}
let bits = if name.ends_with("ss") { 32 } else { 64 };
(
format!("{name} xmm3, xmm9"),
Kind::Scalar {
source: bits,
result: bits,
},
)
}
/// Memory-source text of a register form.
fn memory_text(text: &str, kind: Kind) -> String {
let source = match kind {
Kind::Scalar { source, .. }
| Kind::ToGeneral { source }
| Kind::FromGeneral { source, .. }
| Kind::Flags { source } => source,
};
let place = format!(
"{} ptr [rsi + 4*rdi + 16]",
if source == 32 { "dword" } else { "qword" }
);
let operand = match kind {
Kind::FromGeneral { .. } => text.rsplit(", ").next().unwrap(),
_ => "xmm9",
};
let (head, tail) = text.rsplit_once(operand).unwrap();
format!("{head}{place}{tail}")
}
fn merge(old: u128, value: u64, bits: u32, index: u32) -> u128 {
let modulus = 1u128 << bits;
let shift = bits * index;
let below = old & ((1u128 << shift) - 1);
let above = old.checked_shr(shift + bits).unwrap_or(0);
let above = above.checked_shl(shift + bits).unwrap_or(0);
below | ((u128::from(value) % modulus) << shift) | above
}
fn load(code: &[u8], mxcsr: u32, a: u128, b: u128, r9: u64) -> (CpuState, GuestMemory) {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, code)
.unwrap();
memory
.map_region(DATA, 0x100, MemoryPermissions::READ_WRITE)
.unwrap();
memory.write_bytes(OPERAND, &b.to_le_bytes()).unwrap();
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr[6] = DATA;
cpu.gpr[7] = 4;
cpu.gpr[9] = r9;
cpu.xmm = [FILLER; 16];
cpu.xmm[3] = a;
cpu.xmm[9] = b;
cpu.mxcsr = Mxcsr(mxcsr);
cpu.flags = RFlags {
cf: true,
zf: false,
sf: true,
of: true,
pf: false,
af: true,
};
(cpu, memory)
}
fn run(native: bool, cpu: &CpuState, memory: &mut GuestMemory, budget: usize) -> ExecutionResult {
if native {
DbtEngine::new(64 * 1024)
.unwrap()
.run(&mut cpu.clone(), memory, budget)
} else {
Interpreter::new(cpu.clone(), memory, budget).run()
}
}
/// Initial XMM3, source operand and R9 of a vector, with unrelated upper bits.
fn inputs(vector: &Vector, kind: Kind) -> (u128, u128, u64) {
match kind {
Kind::Scalar { source, .. } | Kind::Flags { source } => (
merge(FILLER, vector.a, source, 0),
merge(!FILLER, vector.b, source, 0),
0,
),
Kind::ToGeneral { source } => (FILLER, merge(!FILLER, vector.b, source, 0), u64::MAX),
Kind::FromGeneral { source, .. } => {
let upper = if source == 32 {
0xABCD_EF01_0000_0000
} else {
0
};
// The memory form reads the same value from the operand.
(FILLER, u128::from(vector.b), vector.b | upper)
}
}
}
fn expect(before: &CpuState, vector: &Vector, kind: Kind, length: usize) -> CpuState {
let mut after = before.clone();
after.rip = ENTRY + length as u64;
after.mxcsr = Mxcsr(before.mxcsr.0 | vector.flags);
match kind {
Kind::Scalar { result, .. } | Kind::FromGeneral { result, .. } => {
after.xmm[3] = merge(before.xmm[3], vector.result, result, 0);
}
Kind::ToGeneral { .. } => after.gpr[9] = vector.result,
Kind::Flags { .. } => {
after.flags = RFlags {
zf: vector.result & 4 != 0,
pf: vector.result & 2 != 0,
cf: vector.result & 1 != 0,
..RFlags::default()
};
}
}
after
}
#[test]
fn scalar_vectors_match_in_both_engines_from_registers_and_memory() {
let code = fixture();
let all = vectors();
assert!(all.len() > 5000);
for vector in &all {
let (text, kind) = instruction(vector.name);
let (a, b, r9) = inputs(vector, kind);
for text in [text.clone(), memory_text(&text, kind)] {
let code = code.get(text.as_str()).unwrap_or_else(|| panic!("{text}"));
for native in [false, true] {
let (cpu, mut memory) = load(code, vector.mxcsr, a, b, r9);
let result = run(native, &cpu, &mut memory, 1);
let wanted = expect(&cpu, vector, kind, code.len());
assert_eq!(
result.exit_reason,
ExitReason::StepLimitExceeded,
"{text} {vector:x?}"
);
assert_eq!(result.final_state, wanted, "{text} {vector:x?}");
}
}
}
}
#[test]
fn sticky_flags_accumulate_and_are_never_cleared() {
let code = fixture();
for vector in vectors().iter().step_by(7) {
let (text, kind) = instruction(vector.name);
let (a, b, r9) = inputs(vector, kind);
let code = &code[text.as_str()];
let (cpu, mut memory) = load(code, vector.mxcsr | 0x2A, a, b, r9);
let result = run(true, &cpu, &mut memory, 1);
assert_eq!(
result.final_state,
expect(&cpu, vector, kind, code.len()),
"{text}"
);
}
}
#[test]
fn packed_forms_apply_the_scalar_rules_to_every_lane() {
let code = fixture();
// Vectors of one operation and MXCSR, taken a register at a time.
let mut groups: BTreeMap<(&str, u32), Vec<Vector>> = BTreeMap::new();
for vector in vectors() {
groups
.entry((vector.name, vector.mxcsr))
.or_default()
.push(vector);
}
let mut checked = 0;
for ((name, mxcsr), group) in groups {
// (packed text, source width, result width, lanes, upper half zeroed)
let packed = match name {
"cvtss2sd" => ("cvtps2pd xmm3, xmm9".to_string(), 32, 64, 2),
"cvtsd2ss" => ("cvtpd2ps xmm3, xmm9".to_string(), 64, 32, 2),
"cvtss2sid" => ("cvtps2dq xmm3, xmm9".to_string(), 32, 32, 4),
"cvttss2sid" => ("cvttps2dq xmm3, xmm9".to_string(), 32, 32, 4),
"cvtsd2sid" => ("cvtpd2dq xmm3, xmm9".to_string(), 64, 32, 2),
"cvttsd2sid" => ("cvttpd2dq xmm3, xmm9".to_string(), 64, 32, 2),
"cvtsi2ssd" => ("cvtdq2ps xmm3, xmm9".to_string(), 32, 32, 4),
"cvtsi2sdd" => ("cvtdq2pd xmm3, xmm9".to_string(), 32, 64, 2),
_ if name.contains("comi") || name.contains("cvt") => continue,
_ => {
let (text, _) = instruction(name);
let bits = if name.contains("ss") && !name.starts_with("cmpsd") {
32
} else {
64
};
let text = if bits == 32 {
text.replacen("ss ", "ps ", 1)
} else {
text.replacen("sd ", "pd ", 1)
};
(text, bits, bits, 128 / bits)
}
};
let (text, source, result, lanes) = packed;
let code = code.get(text.as_str()).unwrap_or_else(|| panic!("{text}"));
for chunk in group.chunks_exact(lanes as usize) {
let (mut a, mut b) = (FILLER, !FILLER);
let mut wanted = 0;
let mut flags = 0;
for (index, vector) in chunk.iter().enumerate() {
a = merge(a, vector.a, source, index as u32);
b = merge(b, vector.b, source, index as u32);
wanted = merge(wanted, vector.result, result, index as u32);
flags |= vector.flags;
}
for native in [false, true] {
let (cpu, mut memory) = load(code, mxcsr, a, b, 0);
let outcome = run(native, &cpu, &mut memory, 1);
assert_eq!(outcome.exit_reason, ExitReason::StepLimitExceeded, "{text}");
assert_eq!(outcome.final_state.xmm[3], wanted, "{text} {chunk:x?}");
assert_eq!(
outcome.final_state.mxcsr.0,
mxcsr | flags,
"{text} {chunk:x?}"
);
checked += 1;
}
}
}
assert!(checked > 1500, "{checked}");
}
#[test]
fn unmasked_exceptions_stop_without_a_result() {
let code = fixture();
let mut seen = 0;
for vector in vectors().iter().filter(|vector| vector.flags != 0) {
let (text, kind) = instruction(vector.name);
let (a, b, r9) = inputs(vector, kind);
let code = &code[text.as_str()];
for bit in 0..6 {
if vector.flags & 1 << bit == 0 {
continue;
}
// Flush-to-zero applies only while underflow is masked.
if bit == 4 && vector.mxcsr & 1 << 15 != 0 {
continue;
}
let mxcsr = vector.mxcsr & !(1 << (bit + 7));
for native in [false, true] {
let (cpu, mut memory) = load(code, mxcsr, a, b, r9);
let result = run(native, &cpu, &mut memory, 1);
assert_eq!(
result.exit_reason,
ExitReason::SimdException,
"{text} {vector:x?}"
);
assert_eq!(result.instructions_executed, 0);
let flags = result.final_state.mxcsr.0 ^ mxcsr;
assert!(
flags & 1 << bit != 0 && flags & !vector.flags == 0,
"{text} {vector:x?}"
);
let mut unchanged = cpu.clone();
unchanged.mxcsr = result.final_state.mxcsr;
assert_eq!(result.final_state, unchanged, "{text} {vector:x?}");
seen |= 1 << bit;
}
}
}
assert_eq!(seen, 0x3F);
}
#[test]
fn pre_computation_exceptions_in_any_lane_come_first() {
let code = fixture();
let code = &code["addps xmm3, xmm9"];
// Lane 0 is inexact (1 + 2^-30); lane 1 is infinity minus infinity.
let one = 0x3F80_0000u128;
let a = one | 0x7F80_0000 << 32;
let b = 0x3080_0000 | 0xFF80_0000u128 << 32;
for (unmasked, flags) in [
(1 << 7, 1), // invalid: precision is not reported
(1 << 12, 1 | 1 << 5), // precision: both were raised
(1 << 7 | 1 << 12, 1), // both: only the pre-computation one
] {
for native in [false, true] {
let (cpu, mut memory) = load(code, 0x1F80 & !unmasked, a, b, 0);
let result = run(native, &cpu, &mut memory, 1);
assert_eq!(result.exit_reason, ExitReason::SimdException);
assert_eq!(result.final_state.mxcsr.0, 0x1F80 & !unmasked | flags);
assert_eq!(result.final_state.xmm, cpu.xmm);
}
}
}
#[test]
fn unmasked_underflow_reports_an_exact_denormal_result() {
let code = fixture();
let code = &code["mulss xmm3, xmm9"];
// 2^-126 * 0.5 is exactly representable, so it underflows only if unmasked.
let (a, b) = (0x0080_0000u128, 0x3F00_0000u128);
for native in [false, true] {
let (cpu, mut memory) = load(code, 0x1F80, a, b, 0);
let result = run(native, &cpu, &mut memory, 1);
assert_eq!(result.exit_reason, ExitReason::StepLimitExceeded);
assert_eq!(result.final_state.mxcsr.0, 0x1F80);
assert_eq!(result.final_state.xmm[3], 0x0040_0000);
for ftz in [0, 1 << 15] {
let mxcsr = 0x1F80 & !(1 << 11) | ftz;
let (cpu, mut memory) = load(code, mxcsr, a, b, 0);
let result = run(native, &cpu, &mut memory, 1);
assert_eq!(result.exit_reason, ExitReason::SimdException);
assert_eq!(result.final_state.mxcsr.0, mxcsr | 1 << 4);
}
}
}
#[test]
fn misaligned_packed_operands_fault() {
for (text, code) in fixture() {
if !text.contains("xmmword ptr") {
continue;
}
for native in [false, true] {
let (mut cpu, mut memory) = load(&code, 0x1F80, 0, 0, 0);
cpu.gpr[6] += 8;
let result = run(native, &cpu, &mut memory, 1);
assert_eq!(result.exit_reason, ExitReason::GeneralProtection, "{text}");
assert_eq!(result.final_state, cpu, "{text}");
}
}
}
struct Random(u64);
impl Random {
fn next(&mut self) -> u64 {
self.0 ^= self.0 >> 12;
self.0 ^= self.0 << 25;
self.0 ^= self.0 >> 27;
self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
}
/// A number biased towards nearby exponents, denormals and short fractions.
fn bits(&mut self, format: Format) -> u64 {
let fraction = if format.bits == 32 { 23 } else { 52 };
let mask = if format.bits == 32 {
u64::from(u32::MAX)
} else {
u64::MAX
};
let raw = self.next() & mask;
let sign = raw & 1 << (format.bits - 1);
match self.next() % 6 {
0 => raw & !(0x7FFu64 << fraction & mask) | sign,
1 => {
let exponent_bias = (1u64 << (format.bits - 2 - fraction)) - 1;
let exponent = exponent_bias - 30 + self.next() % 61;
sign | exponent << fraction | raw & ((1 << fraction) - 1)
}
2 => raw & !((1 << (fraction - 3)) - 1),
_ => raw,
}
}
}
const NEAREST: u32 = 0x1F80;
#[test]
fn nearest_rounding_agrees_with_host_hardware() {
let control = Control::from_mxcsr(NEAREST);
let mut random = Random(0x6A09_E667_F3BC_C909);
let kinds = [
Arithmetic::Add,
Arithmetic::Sub,
Arithmetic::Mul,
Arithmetic::Div,
];
let mut compared = 0;
for _ in 0..300_000 {
let (a, b) = (random.bits(F32), random.bits(F32));
let (x, y) = (f32::from_bits(a as u32), f32::from_bits(b as u32));
let hosts = [x + y, x - y, x * y, x / y];
for (kind, host) in kinds.into_iter().zip(hosts) {
let ours = softfloat::arithmetic(kind, F32, a, b, &control);
if host.is_nan() {
assert!(f32::from_bits(ours.bits as u32).is_nan());
} else {
assert_eq!(ours.bits as u32, host.to_bits(), "{kind:?} {a:x} {b:x}");
compared += 1;
}
}
let (a, b) = (random.bits(F64), random.bits(F64));
let (x, y) = (f64::from_bits(a), f64::from_bits(b));
let hosts = [x + y, x - y, x * y, x / y];
for (kind, host) in kinds.into_iter().zip(hosts) {
let ours = softfloat::arithmetic(kind, F64, a, b, &control);
if host.is_nan() {
assert!(f64::from_bits(ours.bits).is_nan());
} else {
assert_eq!(ours.bits, host.to_bits(), "{kind:?} {a:x} {b:x}");
compared += 1;
}
}
if x >= 0.0 {
let ours = softfloat::square_root(F64, a, &control).bits;
assert_eq!(ours, x.sqrt().to_bits(), "sqrt {a:x}");
}
let single = f32::from_bits(random.next() as u32);
if single >= 0.0 {
let ours = softfloat::square_root(F32, u64::from(single.to_bits()), &control).bits;
assert_eq!(ours as u32, single.sqrt().to_bits());
}
if !x.is_nan() {
let ours = softfloat::convert(F64, F32, a, &control).bits;
assert_eq!(ours as u32, (x as f32).to_bits(), "narrow {a:x}");
}
if !single.is_nan() {
let ours = softfloat::convert(F32, F64, u64::from(single.to_bits()), &control).bits;
assert_eq!(ours, f64::from(single).to_bits());
}
let integer = random.next() as i64 >> (random.next() % 64);
assert_eq!(
softfloat::from_integer(F64, integer, &control).bits,
(integer as f64).to_bits()
);
assert_eq!(
softfloat::from_integer(F32, integer, &control).bits as u32,
(integer as f32).to_bits()
);
}
assert!(compared > 2_000_000, "{compared}");
}
#[test]
fn float_sequences_agree_between_engines() {
let cases: Vec<(&str, Vec<u8>)> = fixture().into_iter().collect();
let mut random = Random(0xBB67_AE85_84CA_A73B);
for round in 0..2000 {
let mut code = Vec::new();
let mut text = Vec::new();
for _ in 0..1 + random.next() % 14 {
let case = &cases[(random.next() % cases.len() as u64) as usize];
code.extend_from_slice(&case.1);
text.push(case.0);
if random.next().is_multiple_of(3) {
code.extend_from_slice(&[0x0F, 0x92, 0xC0]); // setb al
}
}
code.push(0xF4);
let mut mxcsr = 0x1F80 | (random.next() as u32 & 0xE040);
if random.next().is_multiple_of(8) {
mxcsr &= !(1 << (7 + random.next() % 6));
}
let a = u128::from(random.bits(F64)) << 64 | u128::from(random.bits(F32)) << 32;
let b = u128::from(random.bits(F64)) << 64 | u128::from(random.bits(F64));
let (cpu, mut first) = load(&code, mxcsr, a, b, random.next());
let interpreted = run(false, &cpu, &mut first, 64);
let (_, mut second) = load(&code, mxcsr, a, b, 0);
let translated = run(true, &cpu, &mut second, 64);
assert_eq!(
translated.exit_reason, interpreted.exit_reason,
"{round}: {text:#?}"
);
assert_eq!(
translated.instructions_executed,
interpreted.instructions_executed
);
assert_eq!(
translated.final_state, interpreted.final_state,
"{round}: {text:#?}"
);
}
}
File diff suppressed because it is too large. Load diff
+203
View File
@@ -0,0 +1,203 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Regression tests for bounded x86-64 prefix decoding and the architectural
//! instruction-length limit, enforced across the static PE probe, the software
//! interpreter and the native DBT (issue #69).
//!
//! The architectural limit is 15 bytes. The production constant is
//! `xenora_loader::x86_decode::MAX_INSTRUCTION_LEN`; the value is mirrored here
//! so the tests fail against the pre-fix implementation rather than only
//! compiling.
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter};
use xenora_loader::dbt::DbtEngine;
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
use xenora_loader::probe::{InstructionRecord, ProbeConfig, probe_pe_bytes};
const MAX_INSTRUCTION_LEN: usize = 15;
const ENTRY: u64 = 0x1000;
/// Minimal synthetic PE32+ image with one executable section whose code
/// starts at RVA `ENTRY`. Modelled on the fixtures in `probe_static.rs`.
fn synthetic_pe_with_code(code: &[u8]) -> Vec<u8> {
let mut pe = vec![0u8; 1024];
pe[0] = b'M';
pe[1] = b'Z';
pe[0x3c] = 0x80;
pe[0x80..0x84].copy_from_slice(b"PE\0\0");
let coff = 0x84;
pe[coff..coff + 2].copy_from_slice(&0x8664u16.to_le_bytes());
pe[coff + 2..coff + 4].copy_from_slice(&1u16.to_le_bytes());
pe[coff + 16..coff + 18].copy_from_slice(&240u16.to_le_bytes());
let opt = coff + 20; // 0x98
pe[opt..opt + 2].copy_from_slice(&0x20bu16.to_le_bytes());
pe[opt + 16..opt + 20].copy_from_slice(&(ENTRY as u32).to_le_bytes()); // entry point RVA
pe[opt + 24..opt + 32].copy_from_slice(&0x140000000u64.to_le_bytes()); // image base
pe[opt + 32..opt + 36].copy_from_slice(&0x1000u32.to_le_bytes()); // section alignment
pe[opt + 36..opt + 40].copy_from_slice(&0x200u32.to_le_bytes()); // file alignment
pe[opt + 56..opt + 60].copy_from_slice(&0x2000u32.to_le_bytes()); // size of image
pe[opt + 60..opt + 64].copy_from_slice(&0x400u32.to_le_bytes()); // size of headers
pe[opt + 108..opt + 112].copy_from_slice(&16u32.to_le_bytes()); // number of rva and sizes
let sec = opt + 240;
pe[sec..sec + 5].copy_from_slice(b".text");
pe[sec + 8..sec + 12].copy_from_slice(&0x200u32.to_le_bytes()); // virtual size
pe[sec + 12..sec + 16].copy_from_slice(&(ENTRY as u32).to_le_bytes()); // virtual address
pe[sec + 16..sec + 20].copy_from_slice(&0x200u32.to_le_bytes()); // raw data size
pe[sec + 20..sec + 24].copy_from_slice(&0x200u32.to_le_bytes()); // raw data pointer
let chars: u32 = 0x6000_0020; // CODE | EXECUTE | READ
pe[sec + 36..sec + 40].copy_from_slice(&chars.to_le_bytes());
pe[0x200..0x200 + code.len()].copy_from_slice(code);
pe
}
fn probe_records(code: &[u8]) -> Vec<InstructionRecord> {
let pe = synthetic_pe_with_code(code);
probe_pe_bytes(&pe, &ProbeConfig::default())
.expect("probe should succeed")
.instruction_records
}
#[test]
fn probe_reports_overlong_segment_prefix_run() {
let records = probe_records(&[0x65; 16]);
assert!(
records.iter().any(|r| r.mnemonic == "overlong prefix run"),
"expected an overlong-prefix record, got {records:?}"
);
assert!(
records
.iter()
.all(|r| (1..=MAX_INSTRUCTION_LEN).contains(&r.bytes.len())),
"every record stays within the architectural limit: {records:?}"
);
}
#[test]
fn probe_instruction_lengths_stay_within_the_architectural_limit() {
// With 0..=13 prefixes the decoded instruction (prefixes + `xor eax,eax`)
// stays within the architectural 15-byte limit.
for prefixes in 0..=13usize {
let mut code = vec![0x65; prefixes];
code.extend_from_slice(&[0x31, 0xc0, 0xc3]); // xor eax, eax; ret
let records = probe_records(&code);
assert!(
records
.iter()
.all(|r| (1..=MAX_INSTRUCTION_LEN).contains(&r.bytes.len())),
"prefixes={prefixes}: {records:?}"
);
}
}
/// Replicate the `cpu_decode` fuzz target's `build_image` for the minimized
/// artifact and assert the fuzz target's length invariant on every record.
#[test]
fn probe_fuzz_harness_minimized_artifact() {
const PE_OFFSET: usize = 0x40;
const COFF: usize = PE_OFFSET + 4;
const OPTIONAL: usize = COFF + 20;
const OPTIONAL_LEN: u16 = 0xf0;
const TEXT: usize = OPTIONAL + OPTIONAL_LEN as usize;
const HEADER_LEN: usize = 0x200;
const TEXT_RVA: u32 = 0x1000;
const SECTION_ALIGNMENT: u32 = 0x1000;
// Minimized `cpu_decode` input recorded in the campaign ledger, kept inline
// because `fuzz/artifacts/` is not tracked.
let mut artifact = vec![0x65u8; 12];
artifact.push(0x73);
artifact.extend([0x65; 4]);
let mut header = [0u8; HEADER_LEN];
let mut write_field = |offset: usize, bytes: &[u8]| {
header[offset..offset + bytes.len()].copy_from_slice(bytes);
};
write_field(0, b"MZ");
write_field(0x3c, &(PE_OFFSET as u32).to_le_bytes());
write_field(PE_OFFSET, b"PE\0\0");
write_field(COFF, &0x8664u16.to_le_bytes()); // Machine
write_field(COFF + 2, &1u16.to_le_bytes()); // NumberOfSections
write_field(COFF + 16, &OPTIONAL_LEN.to_le_bytes());
write_field(OPTIONAL, &0x20bu16.to_le_bytes()); // Magic
write_field(OPTIONAL + 16, &TEXT_RVA.to_le_bytes()); // AddressOfEntryPoint
write_field(OPTIONAL + 24, &0x1_4000_0000u64.to_le_bytes()); // ImageBase
write_field(OPTIONAL + 32, &SECTION_ALIGNMENT.to_le_bytes());
write_field(OPTIONAL + 36, &0x200u32.to_le_bytes()); // FileAlignment
write_field(OPTIONAL + 108, &16u32.to_le_bytes()); // NumberOfRvaAndSizes
write_field(TEXT, b".text");
write_field(TEXT + 12, &TEXT_RVA.to_le_bytes()); // VirtualAddress
write_field(TEXT + 20, &(HEADER_LEN as u32).to_le_bytes()); // PointerToRawData
write_field(TEXT + 36, &0x6000_0020u32.to_le_bytes()); // CODE | EXECUTE | READ
let code_size = artifact.len() as u32;
write_field(TEXT + 8, &code_size.to_le_bytes()); // VirtualSize
write_field(TEXT + 16, &code_size.to_le_bytes()); // SizeOfRawData
let mut image = Vec::with_capacity(HEADER_LEN + artifact.len());
image.extend_from_slice(&header);
image.extend_from_slice(&artifact);
let report = probe_pe_bytes(&image, &ProbeConfig::default()).expect("probe should succeed");
assert!(
!report.instruction_records.is_empty(),
"entry is decoded at least once"
);
for rec in &report.instruction_records {
assert!(
(1..=MAX_INSTRUCTION_LEN).contains(&rec.bytes.len()),
"fuzz-harness record: {rec:?}"
);
}
}
#[test]
fn probe_minimized_overlong_prefix_run_input() {
// Minimized crash artifact found by the `cpu_decode` fuzz target:
// 12x GS + 0x73 (JAE rel8) + 4x GS = 17 bytes, which the fuzz invariant
// flags as a decoded instruction longer than 15 bytes.
let mut code = vec![0x65; 12];
code.push(0x73);
code.extend([0x65; 4]);
let records = probe_records(&code);
assert!(
records
.iter()
.all(|r| (1..=MAX_INSTRUCTION_LEN).contains(&r.bytes.len())),
"all records within the limit: {records:?}"
);
}
#[test]
fn interpreter_rejects_overlong_segment_prefix_run() {
let mut code = vec![0x65; 16];
code.push(0xC3);
let mut memory = GuestMemory::new();
memory
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, &code)
.unwrap();
let cpu = CpuState::new(ENTRY, 0);
let result = Interpreter::new(cpu, &mut memory, 8).run();
assert_eq!(result.exit_reason, ExitReason::IllegalInstruction(0x65));
assert_eq!(result.instructions_executed, 0);
assert_eq!(result.final_state.rip, ENTRY);
}
#[test]
fn dbt_rejects_overlong_segment_prefix_run() {
let mut code = vec![0x65; 16];
code.push(0xC3);
let mut memory = GuestMemory::new();
memory
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, &code)
.unwrap();
let mut cpu = CpuState::new(ENTRY, 0);
let result = DbtEngine::new(1024 * 1024)
.expect("JIT memory allocation")
.run(&mut cpu, &mut memory, 8);
assert!(
matches!(result.exit_reason, ExitReason::IllegalInstruction(_)),
"expected IllegalInstruction, got {:?}",
result.exit_reason
);
}
+799
View File
@@ -0,0 +1,799 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Independent tests of the SSE and SSE2 moves and packed integer forms.
//!
//! `tests/x86/vector.txt` pairs LLVM encodings with Intel-syntax text. The
//! reference below reads only the text and works on byte arrays with exact
//! integer arithmetic, following the operation sections of the Intel SDM Vol. 2.
//! It shares nothing with the registry, decoder, production semantics or NEON
//! lowering.
use xenora_loader::cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, Mxcsr, RFlags};
use xenora_loader::dbt::{DbtEngine, is_native};
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
use xenora_loader::x86_decode::decode;
const ENTRY: u64 = 0x1000;
const DATA: u64 = 0x2000;
/// Address of `[rsi + 4*rdi + 16]` with RSI = DATA and RDI = 4.
const OPERAND: u64 = DATA + 32;
type Bytes = [u8; 16];
struct Case {
code: Vec<u8>,
text: &'static str,
}
fn parse(fixture: &'static str) -> Vec<Case> {
fixture
.lines()
.map(|line| {
let (hex, text) = line.split_once(" | ").unwrap();
let code = hex
.split(' ')
.map(|b| u8::from_str_radix(b, 16).unwrap())
.collect();
Case { code, text }
})
.collect()
}
fn cases() -> Vec<Case> {
parse(include_str!("x86/vector.txt"))
}
struct Random(u64);
impl Random {
fn next(&mut self) -> u64 {
self.0 ^= self.0 >> 12;
self.0 ^= self.0 << 25;
self.0 ^= self.0 >> 27;
self.0.wrapping_mul(0x2545_F491_4F6C_DD1D)
}
/// Bytes biased towards lane boundaries and, at times, small shift counts.
fn vector(&mut self) -> Bytes {
const EDGES: [u8; 8] = [0, 1, 0x7F, 0x80, 0x81, 0xFE, 0xFF, 0x10];
let mode = self.next() % 4;
let mut out = [0; 16];
for byte in &mut out {
*byte = match mode {
0 => self.next() as u8,
_ => EDGES[(self.next() % 8) as usize],
};
}
if mode == 3 {
out[..8].copy_from_slice(&(self.next() % 70).to_le_bytes());
}
out
}
fn machine(&mut self) -> Machine {
let mut gpr = [0; 16];
for register in &mut gpr {
*register = self.next();
}
(gpr[6], gpr[7]) = (DATA, 4);
let mut xmm = [[0; 16]; 16];
for register in &mut xmm {
*register = self.vector();
}
Machine {
gpr,
xmm,
operand: self.vector(),
mxcsr: (self.next() & 0xFFFF) as u32,
}
}
}
#[derive(Clone)]
struct Machine {
gpr: [u64; 16],
xmm: [Bytes; 16],
operand: Bytes,
mxcsr: u32,
}
// --- reference -------------------------------------------------------------
/// Unsigned lanes of `width` bytes, lane 0 first.
fn split(bytes: &[u8], width: usize) -> Vec<i128> {
bytes
.chunks(width)
.map(|chunk| {
chunk
.iter()
.rev()
.fold(0, |value, byte| value * 256 + i128::from(*byte))
})
.collect()
}
fn join(lanes: &[i128], width: usize) -> Bytes {
let mut out = Vec::new();
for lane in lanes {
let mut rest = lane.rem_euclid(1i128 << (8 * width));
for _ in 0..width {
out.push((rest % 256) as u8);
rest /= 256;
}
}
out.try_into().unwrap()
}
fn negative_form(value: i128, width: usize) -> i128 {
let modulus = 1i128 << (8 * width);
if value >= modulus / 2 {
value - modulus
} else {
value
}
}
fn zip(a: &Bytes, b: &Bytes, width: usize, f: impl Fn(i128, i128) -> i128) -> Bytes {
let pairs: Vec<i128> = split(a, width)
.into_iter()
.zip(split(b, width))
.map(|(x, y)| f(x, y))
.collect();
join(&pairs, width)
}
fn zip_signed(a: &Bytes, b: &Bytes, width: usize, f: impl Fn(i128, i128) -> i128) -> Bytes {
zip(a, b, width, |x, y| {
f(negative_form(x, width), negative_form(y, width))
})
}
/// Lane width in bytes named by a mnemonic suffix.
fn suffix(name: &str) -> usize {
match name.as_bytes()[name.len() - 1] {
b'b' => 1,
b'w' => 2,
b'd' => 4,
_ => 8,
}
}
fn clamp(value: i128, low: i128, high: i128) -> i128 {
if value < low {
low
} else if value > high {
high
} else {
value
}
}
fn shifted(name: &str, value: &Bytes, count: i128) -> Bytes {
let width = suffix(name);
let bits = 8 * width as i128;
let lanes: Vec<i128> = split(value, width)
.into_iter()
.map(|lane| {
let mut lane = if name.starts_with("psra") {
negative_form(lane, width)
} else {
lane
};
for _ in 0..clamp(count, 0, bits) {
lane = if name.starts_with("psll") {
(lane * 2).rem_euclid(1 << bits)
} else {
lane.div_euclid(2) // floors, so negative lanes keep their sign
};
}
lane
})
.collect();
join(&lanes, width)
}
fn packed(name: &str, a: &Bytes, b: &Bytes) -> Bytes {
let canonical = match name {
"andps" | "andpd" => "pand",
"andnps" | "andnpd" => "pandn",
"orps" | "orpd" => "por",
"xorps" | "xorpd" => "pxor",
"unpcklps" => "punpckldq",
"unpcklpd" => "punpcklqdq",
"unpckhps" => "punpckhdq",
"unpckhpd" => "punpckhqdq",
other => other,
};
let name = canonical;
let width = suffix(name);
let top = 1i128 << (8 * width);
let truth = |value: bool| if value { -1 } else { 0 };
match name {
"pand" => zip(a, b, 1, |x, y| x & y),
"pandn" => zip(a, b, 1, |x, y| (255 - x) & y),
"por" => zip(a, b, 1, |x, y| x | y),
"pxor" => zip(a, b, 1, |x, y| x ^ y),
"paddb" | "paddw" | "paddd" | "paddq" => zip(a, b, width, |x, y| x + y),
"psubb" | "psubw" | "psubd" | "psubq" => zip(a, b, width, |x, y| x - y),
"paddsb" | "paddsw" => zip_signed(a, b, width, |x, y| clamp(x + y, -top / 2, top / 2 - 1)),
"psubsb" | "psubsw" => zip_signed(a, b, width, |x, y| clamp(x - y, -top / 2, top / 2 - 1)),
"paddusb" | "paddusw" => zip(a, b, width, |x, y| clamp(x + y, 0, top - 1)),
"psubusb" | "psubusw" => zip(a, b, width, |x, y| clamp(x - y, 0, top - 1)),
"pcmpeqb" | "pcmpeqw" | "pcmpeqd" => zip(a, b, width, |x, y| truth(x == y)),
"pcmpgtb" | "pcmpgtw" | "pcmpgtd" => zip_signed(a, b, width, |x, y| truth(x > y)),
"pminub" => zip(a, b, 1, |x, y| if x < y { x } else { y }),
"pmaxub" => zip(a, b, 1, |x, y| if x > y { x } else { y }),
"pminsw" => zip_signed(a, b, 2, |x, y| if x < y { x } else { y }),
"pmaxsw" => zip_signed(a, b, 2, |x, y| if x > y { x } else { y }),
"pavgb" | "pavgw" => zip(a, b, width, |x, y| (x + y + 1) / 2),
"pmullw" => zip(a, b, 2, |x, y| x * y),
"pmulhw" => zip_signed(a, b, 2, |x, y| (x * y).div_euclid(65536)),
"pmulhuw" => zip(a, b, 2, |x, y| x * y / 65536),
"pmuludq" => zip(a, b, 8, |x, y| (x % (1 << 32)) * (y % (1 << 32))),
"pmaddwd" => {
let (x, y) = (split(a, 2), split(b, 2));
let product = |i: usize| negative_form(x[i], 2) * negative_form(y[i], 2);
join(&[0, 2, 4, 6].map(|i| product(i) + product(i + 1)), 4)
}
"psadbw" => {
let difference = |i: usize| (i128::from(a[i]) - i128::from(b[i])).abs();
join(
&[(0..8).map(difference).sum(), (8..16).map(difference).sum()],
8,
)
}
"packsswb" | "packssdw" | "packuswb" => {
let from = if name == "packssdw" { 4 } else { 2 };
let half = 1i128 << (4 * from);
let (low, high) = if name == "packuswb" {
(0, half - 1)
} else {
(-half / 2, half / 2 - 1)
};
let lanes: Vec<i128> = split(a, from)
.into_iter()
.chain(split(b, from))
.map(|lane| clamp(negative_form(lane, from), low, high))
.collect();
join(&lanes, from / 2)
}
_ if name.starts_with("punpck") => {
let width = match &name[7..] {
"bw" => 1,
"wd" => 2,
"dq" => 4,
_ => 8,
};
let start = if name.as_bytes()[6] == b'h' { 8 } else { 0 };
let mut out = Vec::new();
for at in (start..start + 8).step_by(width) {
out.extend_from_slice(&a[at..at + width]);
out.extend_from_slice(&b[at..at + width]);
}
out.try_into().unwrap()
}
_ if name.starts_with("psll") || name.starts_with("psrl") || name.starts_with("psra") => {
shifted(name, a, split(&b[..8], 8)[0])
}
// Full-width loads.
"movaps" | "movapd" | "movups" | "movupd" | "movdqa" | "movdqu" => *b,
other => panic!("no reference for {other}"),
}
}
fn register(text: &str) -> Option<usize> {
text.strip_prefix("xmm")
.and_then(|index| index.parse().ok())
}
/// Index and width in bytes of a general register used by the fixture.
fn general(text: &str) -> Option<(usize, usize)> {
Some(match text {
"eax" => (0, 4),
"ebx" => (3, 4),
"r9d" => (9, 4),
"r10d" => (10, 4),
"r9" => (9, 8),
_ => return None,
})
}
fn reference(m: &mut Machine, text: &str) {
let (name, rest) = text.split_once(' ').unwrap();
let parts: Vec<&str> = rest.split(", ").collect();
let width = |text: &str| match text.split(' ').next().unwrap() {
"xmmword" => 16,
"qword" => 8,
"dword" => 4,
"word" => 2,
other => panic!("width {other}"),
};
if name == "stmxcsr" {
m.operand[..4].copy_from_slice(&m.mxcsr.to_le_bytes());
return;
}
let destination = parts[0];
if destination.contains(" ptr ") {
// Stores write exactly their operand width.
let source = m.xmm[register(parts[1]).unwrap()];
let start = if name.starts_with("movh") { 8 } else { 0 };
let bytes = width(destination);
m.operand[..bytes].copy_from_slice(&source[start..start + bytes]);
return;
}
let source_text = parts.get(1).copied().unwrap_or("");
let memory = source_text.contains(" ptr ");
if let Some((index, bytes)) = general(destination) {
let source = m.xmm[register(source_text).unwrap()];
let lanes = |width: usize| -> u64 {
split(&source, width)
.iter()
.enumerate()
.filter(|(_, lane)| **lane >= 1i128 << (8 * width - 1))
.map(|(at, _)| 1u64 << at)
.sum()
};
m.gpr[index] = match name {
"movmskps" => lanes(4),
"movmskpd" => lanes(8),
"pmovmskb" => lanes(1),
"pextrw" => split(&source, 2)[parts[2].parse::<usize>().unwrap()] as u64,
_ => split(&source, bytes)[0] as u64,
};
return;
}
let target = register(destination).unwrap();
let old = m.xmm[target];
if let Some((index, bytes)) = general(source_text) {
let value = m.gpr[index].to_le_bytes();
if name == "pinsrw" {
let at = 2 * parts[2].parse::<usize>().unwrap();
m.xmm[target][at..at + 2].copy_from_slice(&value[..2]);
} else {
let mut out = [0; 16];
out[..bytes].copy_from_slice(&value[..bytes]);
m.xmm[target] = out;
}
return;
}
if let Ok(count) = source_text.parse::<i128>() {
m.xmm[target] = match name {
"pslldq" | "psrldq" => {
let mut out = [0; 16];
for (at, byte) in out.iter_mut().enumerate() {
let from = at as i128 + if name == "pslldq" { -count } else { count };
if (0..16).contains(&from) {
*byte = old[from as usize];
}
}
out
}
_ => shifted(name, &old, count),
};
return;
}
let source = if memory {
m.operand
} else {
m.xmm[register(source_text).unwrap()]
};
let imm = parts.get(2).map(|text| text.parse::<usize>().unwrap());
let mut out = old;
match name {
"movss" | "movsd" | "movq" => {
let bytes = match name {
"movss" => 4,
_ => 8,
};
if memory || name == "movq" {
out = [0; 16];
}
out[..bytes].copy_from_slice(&source[..bytes]);
}
"movlps" | "movlpd" => out[..8].copy_from_slice(&source[..8]),
"movhps" | "movhpd" => out[8..].copy_from_slice(&source[..8]),
"movhlps" => out[..8].copy_from_slice(&source[8..]),
"movlhps" => out[8..].copy_from_slice(&source[..8]),
"movd" => {
out = [0; 16];
out[..4].copy_from_slice(&source[..4]);
}
"pinsrw" => {
let at = 2 * imm.unwrap();
out[at..at + 2].copy_from_slice(&source[..2]);
}
"pshufd" | "shufps" => {
for lane in 0..4 {
let from = imm.unwrap() / 4usize.pow(lane) % 4;
let lane = lane as usize;
let input = if name == "shufps" && lane < 2 {
old
} else {
source
};
out[4 * lane..4 * lane + 4].copy_from_slice(&input[4 * from..4 * from + 4]);
}
}
"pshuflw" | "pshufhw" => {
out = source;
let base = if name == "pshufhw" { 8 } else { 0 };
for lane in 0..4 {
let from = base + 2 * (imm.unwrap() / 4usize.pow(lane) % 4);
let to = base + 2 * lane as usize;
out[to..to + 2].copy_from_slice(&source[from..from + 2]);
}
}
"shufpd" => {
let low = 8 * (imm.unwrap() % 2);
let high = 8 * (imm.unwrap() / 2 % 2);
out[..8].copy_from_slice(&old[low..low + 8]);
out[8..].copy_from_slice(&source[high..high + 8]);
}
_ => out = packed(name, &old, &source),
}
m.xmm[target] = out;
}
// --- harness ---------------------------------------------------------------
fn load(machine: &Machine, code: &[u8], permissions: MemoryPermissions) -> (CpuState, GuestMemory) {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, code)
.unwrap();
let mut data = vec![0xEE; 0x100];
data[32..48].copy_from_slice(&machine.operand);
memory
.map_region_with_data(DATA, 0x100, permissions, &data)
.unwrap();
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr = machine.gpr;
cpu.xmm = machine.xmm.map(u128::from_le_bytes);
cpu.mxcsr = Mxcsr(machine.mxcsr);
cpu.flags = RFlags {
cf: true,
zf: false,
sf: true,
of: false,
pf: true,
af: false,
};
(cpu, memory)
}
fn run(native: bool, cpu: &CpuState, memory: &mut GuestMemory, budget: usize) -> ExecutionResult {
if native {
DbtEngine::new(256 * 1024)
.unwrap()
.run(&mut cpu.clone(), memory, budget)
} else {
Interpreter::new(cpu.clone(), memory, budget).run()
}
}
fn data(memory: &GuestMemory) -> Vec<u8> {
let mut out = vec![0; 0x100];
memory.read_bytes(DATA, &mut out).unwrap();
out
}
#[test]
fn every_vector_fixture_matches_the_reference_in_both_engines() {
let mut random = Random(0xA076_1D64_78BD_642F);
let mut native_forms = 0;
for case in cases() {
let text = case.text;
let insn = decode(ENTRY, |address| {
case.code.get((address - ENTRY) as usize).copied().ok_or(())
})
.unwrap_or_else(|error| panic!("{text}: {error:?}"));
let native = is_native(&insn);
native_forms += usize::from(native);
let mut engine = DbtEngine::new(64 * 1024).unwrap();
for _ in 0..64 {
let machine = random.machine();
let mut expected = machine.clone();
reference(&mut expected, text);
let (mut wanted, _) = load(&expected, &case.code, MemoryPermissions::READ_WRITE);
wanted.rip = ENTRY + case.code.len() as u64;
let (cpu, mut memory) = load(&machine, &case.code, MemoryPermissions::READ_WRITE);
let interpreted = Interpreter::new(cpu.clone(), &mut memory, 1).run();
let (mut dbt_cpu, mut dbt_memory) =
load(&machine, &case.code, MemoryPermissions::READ_WRITE);
let translated = engine.run(&mut dbt_cpu, &mut dbt_memory, 1);
for (result, memory) in [(interpreted, memory), (translated, dbt_memory)] {
assert_eq!(result.exit_reason, ExitReason::StepLimitExceeded, "{text}");
assert_eq!(result.final_state, wanted, "{text} from {cpu:x?}");
let mut bytes = vec![0xEE; 0x100];
bytes[32..48].copy_from_slice(&expected.operand);
assert_eq!(data(&memory), bytes, "{text}");
}
}
assert_eq!(engine.metrics.interpreter_fallbacks == 0, native, "{text}");
}
assert!(native_forms > 150, "{native_forms}");
}
#[test]
fn aligned_operands_fault_and_unaligned_operands_do_not() {
let mut random = Random(0x51);
let mut checked = [0, 0];
for case in cases()
.into_iter()
.filter(|case| case.text.contains("xmmword ptr"))
{
let name = case.text.split(' ').next().unwrap();
let unaligned = ["movups", "movupd", "movdqu"].contains(&name);
checked[usize::from(unaligned)] += 1;
for offset in [1, 4, 8, 15] {
let mut machine = random.machine();
machine.gpr[6] = DATA + offset;
for native in [false, true] {
let (cpu, mut memory) = load(&machine, &case.code, MemoryPermissions::READ_WRITE);
let before = data(&memory);
let result = run(native, &cpu, &mut memory, 1);
if unaligned {
assert_eq!(
result.exit_reason,
ExitReason::StepLimitExceeded,
"{}",
case.text
);
if case.text.starts_with(&format!("{name} xmm10")) {
let mut bytes = [0; 16];
bytes.copy_from_slice(&before[32 + offset as usize..48 + offset as usize]);
assert_eq!(result.final_state.xmm[10], u128::from_le_bytes(bytes));
}
} else {
assert_eq!(
result.exit_reason,
ExitReason::GeneralProtection,
"{}",
case.text
);
assert_eq!(result.final_state, cpu, "{}", case.text);
assert_eq!(data(&memory), before, "{}", case.text);
}
}
}
}
assert!(checked[0] > 60 && checked[1] == 6, "{checked:?}");
}
#[test]
fn faulting_vector_accesses_change_nothing() {
for case in cases()
.into_iter()
.filter(|case| case.text.contains(" ptr "))
{
let store = case.text.split(", ").next().unwrap().contains(" ptr ");
let mut machine = Random(0x77).machine();
let mut runs = vec![(0x9000, MemoryPermissions::READ_WRITE)];
if store {
runs.push((DATA, MemoryPermissions::READ_ONLY));
}
for (base, permissions) in runs {
machine.gpr[6] = base;
for native in [false, true] {
let (cpu, mut memory) = load(&machine, &case.code, permissions);
let before = data(&memory);
let result = run(native, &cpu, &mut memory, 1);
assert!(
matches!(result.exit_reason, ExitReason::MemoryFault(_)),
"{}",
case.text
);
assert_eq!(result.final_state, cpu, "{}", case.text);
assert_eq!(data(&memory), before, "{}", case.text);
}
}
}
}
#[test]
fn only_the_operand_width_is_accessed_at_the_end_of_a_region() {
for (code, width) in [
(&[0xF3u8, 0x0F, 0x10, 0x03][..], 4), // movss xmm0, [rbx]
(&[0xF2, 0x0F, 0x10, 0x03], 8), // movsd xmm0, [rbx]
(&[0xF3, 0x0F, 0x7E, 0x03], 8), // movq xmm0, [rbx]
(&[0x66, 0x0F, 0xC4, 0x03, 0x01], 2), // pinsrw xmm0, [rbx], 1
(&[0x0F, 0x10, 0x03], 16), // movups xmm0, [rbx]
(&[0x0F, 0x11, 0x03], 16), // movups [rbx], xmm0
] {
let end = DATA + 0x100;
for (address, ok) in [(end - width, true), (end - width + 1, false)] {
let mut machine = Random(0x99).machine();
machine.gpr[3] = address;
for native in [false, true] {
let (cpu, mut memory) = load(&machine, code, MemoryPermissions::READ_WRITE);
let result = run(native, &cpu, &mut memory, 1);
assert_eq!(
result.exit_reason == ExitReason::StepLimitExceeded,
ok,
"{code:02X?}"
);
}
}
}
}
#[test]
fn register_store_encodings_write_the_rm_operand() {
// The store opcodes with a register operand, which assemblers rarely emit;
// `objdump` (LLVM) disassembles each as the text given here.
let cases: &[(&str, &[u8])] = &[
("movaps xmm3, xmm9", &[0x44, 0x0F, 0x29, 0xCB]),
("movups xmm3, xmm9", &[0x44, 0x0F, 0x11, 0xCB]),
("movdqa xmm3, xmm9", &[0x66, 0x44, 0x0F, 0x7F, 0xCB]),
("movdqu xmm3, xmm9", &[0xF3, 0x44, 0x0F, 0x7F, 0xCB]),
("movss xmm3, xmm9", &[0xF3, 0x44, 0x0F, 0x11, 0xCB]),
("movsd xmm3, xmm9", &[0xF2, 0x44, 0x0F, 0x11, 0xCB]),
("movq xmm3, xmm9", &[0x66, 0x44, 0x0F, 0xD6, 0xCB]),
];
let mut random = Random(0x1234);
for (text, code) in cases {
for _ in 0..32 {
let machine = random.machine();
let mut expected = machine.clone();
reference(&mut expected, text);
for native in [false, true] {
let (cpu, mut memory) = load(&machine, code, MemoryPermissions::READ_WRITE);
let result = run(native, &cpu, &mut memory, 1);
assert_eq!(
result.final_state.xmm,
expected.xmm.map(u128::from_le_bytes),
"{text}"
);
}
}
}
}
#[test]
fn mxcsr_resets_loads_stores_and_rejects_reserved_bits() {
assert_eq!(CpuState::new(0, 0).mxcsr, Mxcsr(0x1F80));
assert_eq!(CpuState::default().mxcsr, Mxcsr(0x1F80));
for (value, accepted) in [
(0x1F80u32, true),
(0, true),
(0xFFFF, true),
(0x1_0000, false),
(0x8000_1F80, false),
] {
// ldmxcsr dword ptr [rbx]; stmxcsr dword ptr [rbx+4]
let code = [0x0F, 0xAE, 0x13, 0x0F, 0xAE, 0x5B, 0x04];
let mut machine = Random(0x55).machine();
machine.gpr[3] = OPERAND;
machine.operand[..4].copy_from_slice(&value.to_le_bytes());
for native in [false, true] {
let (cpu, mut memory) = load(&machine, &code, MemoryPermissions::READ_WRITE);
let result = run(native, &cpu, &mut memory, 2);
if accepted {
assert_eq!(result.exit_reason, ExitReason::StepLimitExceeded);
assert_eq!(result.final_state.mxcsr, Mxcsr(value));
assert_eq!(memory.read_u32(OPERAND + 4).unwrap(), value);
} else {
assert_eq!(result.exit_reason, ExitReason::GeneralProtection);
assert_eq!(result.final_state, cpu);
}
}
}
}
#[test]
fn unsupported_vector_encodings_are_rejected() {
let rejected: &[&[u8]] = &[
&[0x0F, 0xFC, 0xC1], // paddb mm0, mm1 (MMX)
&[0x0F, 0x53, 0xC1], // rcpps xmm0, xmm1 (approximation)
&[0xF3, 0x0F, 0x52, 0xC1], // rsqrtss xmm0, xmm1 (approximation)
&[0x0F, 0x2D, 0xC1], // cvtps2pi mm0, xmm1 (MMX)
&[0x66, 0x0F, 0x38, 0x00, 0xC1], // pshufb xmm0, xmm1
&[0xC5, 0xF9, 0xFC, 0xC1], // vpaddb (VEX)
&[0xF2, 0xF3, 0x0F, 0x10, 0xC1], // both mandatory prefixes
&[0x66, 0xF3, 0x0F, 0x10, 0xC1], // 66 with a scalar move
&[0x66, 0x0F, 0x12, 0xC1], // movlpd with a register source
&[0x0F, 0x13, 0xC1], // movlps register store
&[0x66, 0x0F, 0xE7, 0xC1], // movntdq with a register
&[0x66, 0x0F, 0x71, 0x11, 0x01], // psrlw with a memory operand
&[0x66, 0x0F, 0x71, 0xC1, 0x01], // 71 /0
&[0x0F, 0xAE, 0xD1], // ldmxcsr with a register
&[0x66, 0x0F, 0xAE, 0x13], // 66 with ldmxcsr
];
for code in rejected {
let padded = [code, &[0x90; 8][..]].concat();
let machine = Random(0x31).machine();
for native in [false, true] {
let (cpu, mut memory) = load(&machine, &padded, MemoryPermissions::READ_WRITE);
let result = run(native, &cpu, &mut memory, 1);
assert!(
matches!(result.exit_reason, ExitReason::IllegalInstruction(_)),
"{code:02X?}: {:?}",
result.exit_reason
);
assert_eq!(result.final_state, cpu, "{code:02X?}");
}
}
}
#[test]
fn mixed_vector_and_integer_sequences_agree() {
let vectors = cases();
let integers: Vec<Case> = parse(include_str!("x86/integer.txt"))
.into_iter()
.filter(|case| {
!["push", "pop", "leave", "div", "idiv"]
.iter()
.any(|name| case.text.starts_with(name))
&& case.text != "mov sil, dil"
})
.collect();
let mut random = Random(0xBEEF);
for round in 0..3000 {
let mut code = Vec::new();
let mut text = Vec::new();
for _ in 0..2 + random.next() % 30 {
let pool = if random.next().is_multiple_of(4) {
&integers
} else {
&vectors
};
let case = &pool[(random.next() % pool.len() as u64) as usize];
code.extend_from_slice(&case.code);
text.push(case.text);
}
code.push(0xF4);
let mut machine = random.machine();
if random.next().is_multiple_of(8) {
machine.gpr[6] += 1 + random.next() % 15; // misaligned operand
}
let budget = 1 + (random.next() % 40) as usize;
let (cpu, mut first) = load(&machine, &code, MemoryPermissions::READ_WRITE);
let interpreted = run(false, &cpu, &mut first, budget);
let (_, mut second) = load(&machine, &code, MemoryPermissions::READ_WRITE);
let translated = run(true, &cpu, &mut second, budget);
assert_eq!(
translated.exit_reason, interpreted.exit_reason,
"{round}: {text:#?}"
);
assert_eq!(
translated.instructions_executed, interpreted.instructions_executed,
"{round}: {text:#?}"
);
assert_eq!(
translated.final_state, interpreted.final_state,
"{round}: {text:#?}"
);
assert_eq!(data(&first), data(&second), "{round}: {text:#?}");
}
}
#[test]
fn vector_shift_counts_use_all_64_low_bits() {
// The count is the low quadword of the source; its high quadword is ignored.
for case in cases() {
let name = case.text.split(' ').next().unwrap();
let is_shift = ["psll", "psrl", "psra"]
.iter()
.any(|prefix| name.starts_with(prefix));
if !is_shift || !case.text.ends_with("xmm3, xmm9") {
continue;
}
for (low, high) in [
(1u64 << 32 | 1, 0u64),
(1 << 63, 0),
(u64::MAX, 0),
(3, u64::MAX),
] {
let mut machine = Random(0x41).machine();
machine.xmm[9][..8].copy_from_slice(&low.to_le_bytes());
machine.xmm[9][8..].copy_from_slice(&high.to_le_bytes());
let mut expected = machine.clone();
reference(&mut expected, case.text);
for native in [false, true] {
let (cpu, mut memory) = load(&machine, &case.code, MemoryPermissions::READ_WRITE);
let result = run(native, &cpu, &mut memory, 1);
let wanted = expected.xmm.map(u128::from_le_bytes);
assert_eq!(result.final_state.xmm, wanted, "{} by {low:#x}", case.text);
}
}
}
}
File diff suppressed because it is too large. Load diff
+1
View File
@@ -41,6 +41,7 @@ objc2-metal = { version = "=0.3.2", default-features = false, features = [
"MTLComputePipeline",
"MTLDepthStencil",
"MTLDevice",
"MTLEvent",
"MTLLibrary",
"MTLPixelFormat",
"MTLPipeline",
+427 -39
View File
@@ -1,9 +1,12 @@
use std::collections::BTreeMap;
use std::ffi::c_void;
use std::fmt;
use std::mem::size_of_val;
use std::ptr::{NonNull, copy_nonoverlapping};
use std::sync::{Mutex, MutexGuard, PoisonError};
use std::time::Instant;
use objc2::Message;
use objc2::rc::{Retained, autoreleasepool};
use objc2::runtime::{NSObjectProtocol, ProtocolObject};
use objc2::sel;
@@ -13,8 +16,8 @@ use objc2_metal::{
MTLCompileOptions, MTLComputeCommandEncoder, MTLComputePipelineState,
MTLCreateSystemDefaultDevice, MTLDevice, MTLFunction, MTLGPUFamily, MTLLibrary,
MTLMathFloatingPointFunctions, MTLMathMode, MTLOrigin, MTLPixelFormat, MTLRegion,
MTLResourceOptions, MTLShaderValidation, MTLSize, MTLStorageMode, MTLTexture,
MTLTextureDescriptor, MTLTextureUsage,
MTLResourceOptions, MTLSamplerState, MTLShaderValidation, MTLSharedEvent, MTLSize,
MTLStorageMode, MTLTexture, MTLTextureDescriptor, MTLTextureUsage,
};
use xenora_texture::{
Bc1Upload, BcAlphaFormat, BcAlphaUpload, BcChannelFormat, BcChannelUpload, TiledBc1,
@@ -33,6 +36,7 @@ const MAX_THREADS_PER_GROUP: usize = 64;
const MAX_GROUPS: usize = 64;
const MAX_GRID_WORDS: usize = MAX_GROUPS * MAX_THREADS_PER_GROUP;
const MAX_SOURCE_BYTES: usize = 64 * 1024;
const MAX_IN_FLIGHT: usize = 16;
const BC_READBACK: &str = r"
#include <metal_stdlib>
@@ -65,7 +69,7 @@ enum ComputeInput<'a> {
Texture(&'a ProtocolObject<dyn MTLTexture>, usize),
SampledTexture {
texture: &'a ProtocolObject<dyn MTLTexture>,
sampler: &'a ProtocolObject<dyn objc2_metal::MTLSamplerState>,
sampler: &'a ProtocolObject<dyn MTLSamplerState>,
coords: &'a [u32],
},
}
@@ -147,7 +151,18 @@ pub struct RunProfile {
pub library_seconds: f64,
pub pipeline_seconds: f64,
pub gpu_seconds: f64,
/// Host wall time from the start of setup until wait observes completion.
pub host_seconds: f64,
/// Host time to allocate the input and output shared buffers.
pub alloc_seconds: f64,
/// Host time to create the command buffer and encode the dispatch.
pub encode_seconds: f64,
/// Host time spent in `commit`.
pub commit_seconds: f64,
/// Host time spent in `waitUntilCompleted`.
pub wait_seconds: f64,
/// Host time to copy the output words back; not part of `host_seconds`.
pub readback_seconds: f64,
pub output: Vec<u32>,
}
@@ -155,10 +170,161 @@ pub struct RunProfile {
pub struct NativeCompute {
device: Retained<ProtocolObject<dyn MTLDevice>>,
queue: Retained<ProtocolObject<dyn MTLCommandQueue>>,
submissions: Mutex<SubmissionTable>,
}
/// A submitted dispatch whose result can be collected by its issuing context.
#[must_use]
pub struct Submission<'a> {
context: &'a NativeCompute,
id: u64,
}
impl Drop for Submission<'_> {
fn drop(&mut self) {
let mut table = self.context.submissions();
if let Some(entry) = table.entries.get_mut(&self.id) {
if entry.resources.is_some() {
entry.abandoned = true;
} else {
table.entries.remove(&self.id);
}
}
}
}
#[doc(hidden)]
pub struct SubmissionGate {
event: Retained<ProtocolObject<dyn MTLSharedEvent>>,
}
impl SubmissionGate {
pub fn open(&self) {
self.event.setSignaledValue(1);
}
}
impl Drop for SubmissionGate {
fn drop(&mut self) {
self.open();
}
}
#[derive(Default)]
struct SubmissionTable {
next_id: u64,
entries: BTreeMap<u64, SubmissionEntry>,
}
impl SubmissionTable {
fn in_flight(&self) -> usize {
self.entries
.values()
.filter(|entry| entry.resources.is_some())
.count()
}
fn check_capacity(&self) -> Result<(), MetalError> {
if self.in_flight() >= MAX_IN_FLIGHT {
return Err(MetalError::new(
"in-flight limit",
format!("at most {MAX_IN_FLIGHT} compute submissions may be in flight"),
));
}
Ok(())
}
}
struct SubmissionEntry {
resources: Option<InFlightResources>,
result: Result<RunProfile, MetalError>,
host_start: Instant,
abandoned: bool,
waiting: bool,
}
/// Owns every resource referenced by the unretained command buffer until
/// Metal reports Completed or Error.
struct InFlightResources {
command: Retained<ProtocolObject<dyn MTLCommandBuffer>>,
_pipeline: Retained<ProtocolObject<dyn MTLComputePipelineState>>,
_input: Option<Retained<ProtocolObject<dyn MTLBuffer>>>,
output: Retained<ProtocolObject<dyn MTLBuffer>>,
_texture: Option<Retained<ProtocolObject<dyn MTLTexture>>>,
_sampler: Option<Retained<ProtocolObject<dyn MTLSamplerState>>>,
gate: Option<Retained<ProtocolObject<dyn MTLSharedEvent>>>,
word_count: usize,
}
// SAFETY: Metal permits command buffers to move between threads with exclusive
// access. The table mutex and waiting flag keep sweeps off a command during its
// wait. Readback uses private shared storage after GPU completion. Retained
// textures and input buffers are only kept alive by the table.
unsafe impl Send for InFlightResources {}
impl SubmissionEntry {
fn retire(&mut self, status: MTLCommandBufferStatus) {
if !is_terminal(status) {
return;
}
let Some(resources) = self.resources.take() else {
return;
};
if let Err(error) = check_command_status(&resources.command, status) {
self.result = Err(error);
return;
}
if let Ok(profile) = &mut self.result {
profile.gpu_seconds = resources.command.GPUEndTime() - resources.command.GPUStartTime();
profile.host_seconds = self.host_start.elapsed().as_secs_f64();
let readback_start = Instant::now();
let byte_len = resources.word_count * size_of::<u32>();
// SAFETY: The initialized shared output is distinct from the host
// vector and the GPU has finished writing to it. Both ranges hold
// byte_len bytes and all u32 bit patterns are valid.
unsafe {
copy_nonoverlapping(
resources.output.contents().cast::<u8>().as_ptr(),
profile.output.as_mut_ptr().cast::<u8>(),
byte_len,
);
}
profile.readback_seconds = readback_start.elapsed().as_secs_f64();
}
}
}
impl Drop for NativeCompute {
fn drop(&mut self) {
// Tokens can be abandoned (or forgotten) while their work is pending.
// Open all remaining gates before draining the queue.
let table = self
.submissions
.get_mut()
.unwrap_or_else(PoisonError::into_inner);
for resources in table
.entries
.values()
.filter_map(|entry| entry.resources.as_ref())
{
if let Some(gate) = &resources.gate {
gate.setSignaledValue(1);
}
}
for (_, entry) in std::mem::take(&mut table.entries) {
if let Some(resources) = entry.resources {
resources.command.waitUntilCompleted();
if !is_terminal(resources.command.status()) {
// Preserve the resources if Metal unexpectedly returns before completion.
std::mem::forget(resources);
}
}
}
}
}
impl NativeCompute {
/// Open the default Apple GPU and create a retained-resource command queue.
/// Open the default Apple GPU and create a command queue.
///
/// # Errors
///
@@ -178,10 +344,47 @@ impl NativeCompute {
let queue = device
.newCommandQueue()
.ok_or_else(|| MetalError::new("newCommandQueue", "queue creation failed"))?;
Ok(Self { device, queue })
Ok(Self {
device,
queue,
submissions: Mutex::default(),
})
})
}
fn submissions(&self) -> MutexGuard<'_, SubmissionTable> {
self.submissions
.lock()
.unwrap_or_else(PoisonError::into_inner)
}
fn retire_completed(&self) {
self.submissions().entries.retain(|_, entry| {
if !entry.waiting
&& let Some(resources) = &entry.resources
{
entry.retire(resources.command.status());
}
!entry.abandoned || entry.resources.is_some()
});
}
fn begin_submission(&self) -> Instant {
let host_start = Instant::now();
self.retire_completed();
host_start
}
#[doc(hidden)]
pub fn in_flight(&self) -> usize {
self.submissions().in_flight()
}
#[doc(hidden)]
pub fn tracked(&self) -> usize {
self.submissions().entries.len()
}
/// Report the selected device's registered name.
pub fn device_name(&self) -> String {
autoreleasepool(|_| self.device.name().to_string())
@@ -561,6 +764,122 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
self.run_profiled_words(source, entry, input, None)
}
/// Submit trusted MSL with read-only words at buffer 0 and output words at buffer 1.
///
/// The trusted-kernel requirements of [`Self::run_words`] apply.
/// Use [`Self::wait`] to collect the result.
///
/// # Errors
///
/// Returns an error for invalid input or source, compilation or dispatch
/// setup failure, or a full in-flight table.
pub fn submit_words(
&self,
source: &str,
entry: &str,
input: &[u32],
) -> Result<Submission<'_>, MetalError> {
autoreleasepool(|_| {
let host_start = self.begin_submission();
validate_words(source, entry, input)?;
self.submit_sized(
source,
entry,
ComputeInput::Words(input),
None,
None,
host_start,
)
})
}
#[doc(hidden)]
pub fn submit_words_gated(
&self,
source: &str,
entry: &str,
input: &[u32],
) -> Result<(Submission<'_>, SubmissionGate), MetalError> {
autoreleasepool(|_| {
let host_start = self.begin_submission();
validate_words(source, entry, input)?;
let event = self
.device
.newSharedEvent()
.ok_or_else(|| MetalError::new("newSharedEvent", "gate creation failed"))?;
let submission = self.submit_sized(
source,
entry,
ComputeInput::Words(input),
None,
Some(&event),
host_start,
)?;
Ok((submission, SubmissionGate { event }))
})
}
/// Wait for this context's submission and return its readback and timings.
///
/// # Errors
///
/// Returns an error for a token from another context, an unknown submission,
/// or a Metal completion failure.
pub fn wait(&self, submission: Submission<'_>) -> Result<RunProfile, MetalError> {
if !std::ptr::eq(self, submission.context) {
return Err(MetalError::new(
"submission",
"token belongs to another context",
));
}
autoreleasepool(|_| {
let id = submission.id;
std::mem::forget(submission);
let result = self.take_result(id);
self.retire_completed();
result
})
}
fn take_result(&self, id: u64) -> Result<RunProfile, MetalError> {
let unknown = || MetalError::new("submission", "unknown submission id");
let command = {
let mut table = self.submissions();
let entry = table.entries.get_mut(&id).ok_or_else(unknown)?;
entry.resources.as_ref().map(|resources| {
entry.waiting = true;
resources.command.clone()
})
};
let wait_seconds = command.map_or(0.0, |command| {
// Keep the table available to other submitters while Metal waits.
let start = Instant::now();
command.waitUntilCompleted();
start.elapsed().as_secs_f64()
});
let mut table = self.submissions();
let entry = table.entries.get_mut(&id).ok_or_else(unknown)?;
entry.waiting = false;
let host_seconds = if let Some(resources) = &entry.resources {
let status = resources.command.status();
if !is_terminal(status) {
entry.abandoned = true;
check_command_status(&resources.command, status)?;
}
entry.retire(status);
None
} else {
Some(entry.host_start.elapsed().as_secs_f64())
};
let mut profile = table.entries.remove(&id).ok_or_else(unknown)?.result?;
profile.wait_seconds = wait_seconds;
if let Some(host_seconds) = host_seconds {
profile.host_seconds = host_seconds;
}
Ok(profile)
}
/// Run trusted MSL with an explicit one-dimensional threadgroup width.
///
/// The grid still contains one invocation per input word. The requested width
@@ -608,13 +927,7 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
input: &[u32],
group_width: Option<usize>,
) -> Result<RunProfile, MetalError> {
if !(1..=MAX_GRID_WORDS).contains(&input.len()) {
return Err(MetalError::new(
"dispatch bounds",
format!("expected 1..={MAX_GRID_WORDS} words, got {}", input.len()),
));
}
validate_source(source, &[entry])?;
validate_words(source, entry, input)?;
autoreleasepool(|_| self.run_sized(source, entry, ComputeInput::Words(input), group_width))
}
@@ -636,7 +949,20 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
input: ComputeInput<'_>,
group_width: Option<usize>,
) -> Result<RunProfile, MetalError> {
let host_start = Instant::now();
let host_start = self.begin_submission();
self.wait(self.submit_sized(source, entry, input, group_width, None, host_start)?)
}
fn submit_sized(
&self,
source: &str,
entry: &str,
input: ComputeInput<'_>,
group_width: Option<usize>,
gate: Option<&ProtocolObject<dyn MTLSharedEvent>>,
host_start: Instant,
) -> Result<Submission<'_>, MetalError> {
self.submissions().check_capacity()?;
let options = compile_options()?;
let library_start = Instant::now();
let library = self.compile_library(source, &options)?;
@@ -672,17 +998,29 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
"fixture exceeds device buffer limit",
));
}
let alloc_start = Instant::now();
let input_buffer = match input {
ComputeInput::Words(words) => Some(self.new_buffer(words)?),
ComputeInput::SampledTexture { coords, .. } => Some(self.new_buffer(coords)?),
ComputeInput::Texture(..) => None,
};
let mut words = vec![0xA5A5_A5A5; input.len()];
let words = vec![0xA5A5_A5A5; input.len()];
let output_buffer = self.new_buffer(&words)?;
let alloc_seconds = alloc_start.elapsed().as_secs_f64();
let mut table = self.submissions();
table.check_capacity()?;
let id = table.next_id;
table.next_id = id
.checked_add(1)
.ok_or_else(|| MetalError::new("submission", "submission ids exhausted"))?;
let encode_start = Instant::now();
let command = self
.queue
.commandBuffer()
.commandBufferWithUnretainedReferences()
.ok_or_else(|| MetalError::new("commandBuffer", "command buffer creation failed"))?;
if let Some(gate) = gate {
command.encodeWaitForEvent_value(gate.as_ref(), 1);
}
let encoder = command.computeCommandEncoder().ok_or_else(|| {
MetalError::new("computeCommandEncoder", "compute encoder creation failed")
})?;
@@ -710,27 +1048,49 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
}
encoder.dispatchThreads_threadsPerThreadgroup(size(input.len()), size(width));
encoder.endEncoding();
complete_command(&command)?;
let gpu_seconds = command.GPUEndTime() - command.GPUStartTime();
let host_seconds = host_start.elapsed().as_secs_f64();
// SAFETY: Metal copied the initialized words into distinct shared storage.
// The GPU finished before the CPU touches that storage. Both ranges are
// valid for byte_len bytes and don't overlap. A byte copy requires no
// additional alignment and all u32 bit patterns are valid.
unsafe {
copy_nonoverlapping(
output_buffer.contents().cast::<u8>().as_ptr(),
words.as_mut_ptr().cast::<u8>(),
byte_len,
);
}
Ok(RunProfile {
library_seconds,
pipeline_seconds,
gpu_seconds,
host_seconds,
output: words,
})
let encode_seconds = encode_start.elapsed().as_secs_f64();
let (texture, sampler) = match input {
ComputeInput::Texture(texture, _) => (Some(texture.retain()), None),
ComputeInput::SampledTexture {
texture, sampler, ..
} => (Some(texture.retain()), Some(sampler.retain())),
ComputeInput::Words(_) => (None, None),
};
let resources = InFlightResources {
command,
_pipeline: pipeline,
_input: input_buffer,
output: output_buffer,
_texture: texture,
_sampler: sampler,
gate: gate.map(Message::retain),
word_count: input.len(),
};
let commit_start = Instant::now();
resources.command.commit();
let commit_seconds = commit_start.elapsed().as_secs_f64();
table.entries.insert(
id,
SubmissionEntry {
resources: Some(resources),
result: Ok(RunProfile {
library_seconds,
pipeline_seconds,
gpu_seconds: 0.0,
host_seconds: 0.0,
alloc_seconds,
encode_seconds,
commit_seconds,
wait_seconds: 0.0,
readback_seconds: 0.0,
output: words,
}),
host_start,
abandoned: false,
waiting: false,
},
);
Ok(Submission { context: self, id })
}
fn compile_library(
@@ -790,6 +1150,16 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
}
}
fn validate_words(source: &str, entry: &str, input: &[u32]) -> Result<(), MetalError> {
if !(1..=MAX_GRID_WORDS).contains(&input.len()) {
return Err(MetalError::new(
"dispatch bounds",
format!("expected 1..={MAX_GRID_WORDS} words, got {}", input.len()),
));
}
validate_source(source, &[entry])
}
fn validate_source(source: &str, entries: &[&str]) -> Result<(), MetalError> {
if source.is_empty()
|| source.len() > MAX_SOURCE_BYTES
@@ -829,11 +1199,29 @@ fn find_function(
fn complete_command(command: &ProtocolObject<dyn MTLCommandBuffer>) -> Result<(), MetalError> {
command.commit();
command.waitUntilCompleted();
wait_command(command)
}
if command.status() != MTLCommandBufferStatus::Completed {
/// Block until a committed command buffer finishes and check its status.
fn wait_command(command: &ProtocolObject<dyn MTLCommandBuffer>) -> Result<(), MetalError> {
command.waitUntilCompleted();
check_command_status(command, command.status())
}
fn is_terminal(status: MTLCommandBufferStatus) -> bool {
matches!(
status,
MTLCommandBufferStatus::Completed | MTLCommandBufferStatus::Error
)
}
fn check_command_status(
command: &ProtocolObject<dyn MTLCommandBuffer>,
status: MTLCommandBufferStatus,
) -> Result<(), MetalError> {
if status != MTLCommandBufferStatus::Completed {
let error = command.error().map_or_else(
|| format!("unexpected command status {:?}", command.status()),
|| format!("unexpected command status {status:?}"),
|error| error.localizedDescription().to_string(),
);
return Err(MetalError::new("waitUntilCompleted", error));
+2 -1
View File
@@ -16,7 +16,8 @@ pub mod texture_pipeline;
pub use compute::{
BlendDraw, BlendFactor, BlendOperation, BlendPass, BlendState, ColorWriteMask, DepthCompare,
DepthDraw, DepthFill, DepthOutput, DepthPass, DepthState, GuestBuffer, GuestBufferView,
IndexBuffer, IndexedDraw, IndexedPass, MetalError, NativeCompute, RunProfile,
IndexBuffer, IndexedDraw, IndexedPass, MetalError, NativeCompute, RunProfile, Submission,
SubmissionGate,
};
#[cfg(all(target_arch = "aarch64", target_os = "macos"))]
+104
View File
@@ -0,0 +1,104 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use super::{context, fixture, native};
const ENTRY: &str = "fixture";
const INPUT: [u32; 4] = [0, 1, 71, u32::MAX];
const LIMIT: usize = 16;
fn source() -> String {
fixture("output[id] = input[id] * 3u + 7u;")
}
fn expected(input: &[u32]) -> Vec<u32> {
input
.iter()
.map(|word| word.wrapping_mul(3).wrapping_add(7))
.collect()
}
#[test]
fn sweep_keeps_resources_until_completion() {
let metal = context();
let source = source();
let (a, gate) = native(metal.submit_words_gated(&source, ENTRY, &INPUT));
assert_eq!(metal.in_flight(), 1);
let b = native(metal.submit_words(&source, ENTRY, &INPUT));
assert_eq!(metal.in_flight(), 2);
gate.open();
assert_eq!(native(metal.wait(a)).output, expected(&INPUT));
assert_eq!(native(metal.wait(b)).output, expected(&INPUT));
assert_eq!(metal.in_flight(), 0);
}
#[test]
fn batch_can_be_collected_in_either_order() {
let metal = context();
let source = source();
for reverse in [false, true] {
let mut batch = Vec::new();
for seed in 0..8 {
let input = INPUT.map(|word| word.wrapping_add(seed));
batch.push((input, native(metal.submit_words(&source, ENTRY, &input))));
}
if reverse {
batch.reverse();
}
for (input, submission) in batch {
let output = native(metal.wait(submission)).output;
assert_eq!(output, expected(&input));
assert_eq!(output, native(metal.run_words(&source, ENTRY, &input)));
}
assert_eq!(metal.tracked(), 0);
}
}
#[test]
fn full_queue_returns_in_flight_limit_error() {
let metal = context();
let source = source();
let (first, gate) = native(metal.submit_words_gated(&source, ENTRY, &INPUT));
let mut tokens = vec![first];
for _ in 1..LIMIT {
tokens.push(native(metal.submit_words(&source, ENTRY, &INPUT)));
}
assert_eq!(metal.in_flight(), LIMIT);
let Err(error) = metal.submit_words(&source, ENTRY, &INPUT) else {
panic!("submission past the in-flight limit succeeded");
};
assert_eq!(error.operation, "in-flight limit");
gate.open();
for token in tokens {
assert_eq!(native(metal.wait(token)).output, expected(&INPUT));
}
assert_eq!(metal.in_flight(), 0);
}
#[test]
fn dropped_token_retires_after_completion() {
let metal = context();
let source = source();
let (a, gate) = native(metal.submit_words_gated(&source, ENTRY, &INPUT));
drop(a);
let b = native(metal.submit_words(&source, ENTRY, &INPUT));
assert_eq!(metal.in_flight(), 2);
drop(gate);
assert_eq!(native(metal.wait(b)).output, expected(&INPUT));
assert_eq!(metal.in_flight(), 0);
assert_eq!(metal.tracked(), 0);
}
#[test]
fn finished_result_survives_later_submission() {
let metal = context();
let source = source();
let a = native(metal.submit_words(&source, ENTRY, &INPUT));
let b = native(metal.submit_words(&source, ENTRY, &[9]));
assert_eq!(native(metal.wait(b)).output, expected(&[9]));
assert_eq!(metal.in_flight(), 0);
assert_eq!(metal.tracked(), 1);
let profile = native(metal.wait(a));
assert_eq!(profile.output, expected(&INPUT));
assert_eq!(profile.wait_seconds, 0.0);
assert_eq!(metal.tracked(), 0);
}
+2
View File
@@ -16,6 +16,8 @@ mod indexed;
mod indexed_cases;
#[path = "native/offscreen.rs"]
mod offscreen;
#[path = "native/submission.rs"]
mod submission;
#[path = "native/texture.rs"]
mod texture;
#[path = "native/texture_bc_alpha.rs"]
+547 -71
View File
@@ -57,6 +57,10 @@ pub enum Op {
MoveScalar(u8, u8),
/// VOPC 32-bit integer compare writing the Wave32 mask to `vcc_lo`.
Compare(Comparison, CompareSource, u8),
/// VOPC 16- or 64-bit integer compare writing the Wave32 mask to
/// `vcc_lo`. For 64-bit forms a `Vector` or `Scalar` source and VSRC1 name
/// the low register of a pair.
WideCompare(Comparison, CompareWidth, CompareSource, u8),
/// SOP2 operation writing an SGPR and SCC.
Scalar(ScalarAlu, u8, Source, Source),
/// SOPC `s_cmp_eq_{i32,u32}` (opcodes 0 and 6, identical per guide 12.4).
@@ -69,6 +73,14 @@ 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),
/// VOP1 32-bit integer or bit form: VDST and SRC0 (VGPR, SGPR, `vcc_lo`,
/// inline integer or literal). Writes neither VCC nor SCC.
VectorUnary(VectorUnary, u8, CompareSource),
/// VOP1 `v_swap_b32` (opcode 101): exchanges VDST and the SRC0 VGPR.
Swap(u8, u8),
End,
}
@@ -76,38 +88,84 @@ pub enum Op {
///
/// AMD RDNA 2 ISA guide section 12.9, Tables 59 and 61: opcode 128 + offset
/// for signed and 192 + offset for unsigned 32-bit operands, with offsets
/// LT 1, EQ 2, LE 3, GT 4, NE 5, GE 6.
/// F 0, LT 1, EQ 2, LE 3, GT 4, NE 5, GE 6, T 7.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Comparison {
/// Opcode offset 1-6 within the 32-bit integer group.
/// Opcode offset 0-7 within the 32-bit integer group.
pub offset: u8,
/// Whether the operands are two's-complement integers.
pub signed: bool,
}
impl Comparison {
/// The per-lane result, from an exact comparison of the widened operands.
/// The per-lane result for 32-bit operands.
fn holds(self, s0: u32, s1: u32) -> bool {
let widen = |bits: u32| {
if self.signed {
i64::from(bits as i32)
} else {
i64::from(bits)
self.holds_at(CompareWidth::Word, u64::from(s0), u64::from(s1))
}
/// The per-lane result, from an exact comparison of the operands widened
/// from their low `width` bits; higher bits are ignored.
fn holds_at(self, width: CompareWidth, s0: u64, s1: u64) -> bool {
let widen = |bits: u64| -> i128 {
match (width, self.signed) {
(CompareWidth::Half, true) => i128::from(bits as u16 as i16),
(CompareWidth::Half, false) => i128::from(bits as u16),
(CompareWidth::Word, true) => i128::from(bits as u32 as i32),
(CompareWidth::Word, false) => i128::from(bits as u32),
(CompareWidth::Double, true) => i128::from(bits as i64),
(CompareWidth::Double, false) => i128::from(bits),
}
};
let (s0, s1) = (widen(s0), widen(s1));
match self.offset {
// Table 61: V_CMP_F_{I,U}{32,64} `D[threadId] = 0`.
0 => false,
1 => s0 < s1,
2 => s0 == s1,
3 => s0 <= s1,
4 => s0 > s1,
5 => s0 != s1,
_ => s0 >= s1,
6 => s0 >= s1,
// Table 61: V_CMP_T_{I,U}{32,64} `D[threadId] = 1`.
_ => true,
}
}
}
/// First source of a VOPC compare.
/// Operand width of a VOPC integer compare (guide 6.2: the data size is the
/// one named by the instruction).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CompareWidth {
/// `_I16`/`_U16`: bits 15:0 of each 32-bit source (6.2.5 and 6.8: VOPC
/// selects another half only through SDWA, which is not accepted).
Half,
/// `_I32`/`_U32`.
Word,
/// `_I64`/`_U64`: register pairs with the low dword in the lower register
/// (3.6.3 for SGPRs; for VGPRs the guide states it for 64-bit addresses,
/// 9.1: "ADDR has the LSBs, and ADDR+1 has the MSBs").
Double,
}
impl CompareWidth {
/// Guide 12.9 Tables 59-61: the base opcode of each accepted group plus
/// the relation offset; 16-bit groups have no F (offset 0) or T (7).
fn from_opcode(opcode: u16) -> Option<(Comparison, Self)> {
let (base, signed, width) = match opcode {
128..=135 => (128, true, Self::Word),
192..=199 => (192, false, Self::Word),
137..=142 => (136, true, Self::Half),
169..=174 => (168, false, Self::Half),
160..=167 => (160, true, Self::Double),
224..=231 => (224, false, Self::Double),
_ => return None,
};
let offset = (opcode - base) as u8;
Some((Comparison { offset, signed }, width))
}
}
/// First source of a VOPC compare or a VOP2 integer form.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CompareSource {
/// VGPR index.
@@ -164,6 +222,35 @@ 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
@@ -207,6 +294,138 @@ 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),
}
}
}
/// VOP1 32-bit integer and bit forms with a general SRC0 (AMD RDNA 2 ISA
/// guide section 12.8). None writes VCC or SCC.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VectorUnary {
/// 55: D = ~S0.
Not,
/// 56: D[31:0] = S0[0:31].
ReverseBits,
/// 57: zeros before the first one from the MSB, -1 if none.
FindFirstOneFromMsb,
/// 58: position of the first one from the LSB, -1 if none.
FindFirstOneFromLsb,
/// 59: bits after the sign bit that equal it, from the MSB; -1 if all
/// 32 bits are equal.
FindSignChange,
}
impl VectorUnary {
/// Opcode bits 16-9 of the VOP1 word.
fn from_opcode(opcode: u8) -> Option<Self> {
Some(match opcode {
55 => Self::Not,
56 => Self::ReverseBits,
57 => Self::FindFirstOneFromMsb,
58 => Self::FindFirstOneFromLsb,
59 => Self::FindSignChange,
_ => return None,
})
}
fn apply(self, s0: u32) -> u32 {
// -1 (all ones) when the scan finds nothing.
let found = |index: u32| if index == 32 { u32::MAX } else { index };
match self {
Self::Not => !s0,
Self::ReverseBits => s0.reverse_bits(),
Self::FindFirstOneFromMsb => found(s0.leading_zeros()),
Self::FindFirstOneFromLsb => found(s0.trailing_zeros()),
Self::FindSignChange => {
// Normalize to a non-negative word: the run after the sign bit
// is then a run of zeros.
let positive = if (s0 as i32) < 0 { !s0 } else { s0 };
found(positive.leading_zeros())
}
}
}
}
/// Execute original little-endian gfx1030 bytes with the synthetic binding ABI.
///
/// Each dispatched lane reads the corresponding input word and may write only
@@ -371,35 +590,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)?;
@@ -450,35 +680,70 @@ pub fn decode(code: &[u8]) -> Result<Vec<DecodedInstruction>, ReferenceError> {
}
// VOPC (bits 31-25 = 0b0111110): SRC0 bits 0-8, VSRC1 bits 9-16, OP bits 17-24.
[lo, packed, upper, tag @ 0x7c..=0x7d, tail @ ..]
if matches!(
if CompareWidth::from_opcode(
(u16::from(*tag & 1) << 7) | u16::from(*upper >> 1),
129..=134 | 193..=198
) =>
)
.is_some() =>
{
let opcode = (u16::from(*tag & 1) << 7) | u16::from(*upper >> 1);
let comparison = Comparison {
offset: (opcode & 0x3f) as u8,
signed: opcode < 192,
};
let (comparison, width) = CompareWidth::from_opcode(opcode).unwrap();
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)
// docs/shaders/vector-compare.md subset: no literal for 16-bit;
// 64-bit takes v[n:n+1] (n <= 254), s[2k:2k+1] (k <= 52) or
// an inline integer, with VSRC1 v[m:m+1] (m <= 254).
let accepted = match width {
CompareWidth::Half => selector != 255,
CompareWidth::Word => true,
CompareWidth::Double => {
vsrc1 != 255
&& matches!(selector, 0..=104 | 128..=208 | 256..=510)
&& (selector >= 128 || selector % 2 == 0)
}
256..=511 => (CompareSource::Vector(*lo), 4),
_ => return Err(error(offset, "unsupported VOPC source")),
};
(Op::Compare(comparison, src0, vsrc1), length)
if !accepted {
return Err(error(offset, "unsupported VOPC source"));
}
let (src0, length) =
decode_vector_source(*lo, *packed, tail, offset, "unsupported VOPC source")?;
let op = if width == CompareWidth::Word {
Op::Compare(comparison, src0, vsrc1)
} else {
Op::WideCompare(comparison, width, src0, vsrc1)
};
(op, 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)
}
// VOP1 integer forms (bits 31-25 = 0b0111111): VDST bits 17-24,
// OP 9-16, SRC0 0-8.
[lo, packed, upper, tag @ 0x7e..=0x7f, tail @ ..]
if VectorUnary::from_opcode((packed >> 1) | ((upper & 1) << 7)).is_some() =>
{
let kind = VectorUnary::from_opcode((packed >> 1) | ((upper & 1) << 7)).unwrap();
let dst = (upper >> 1) | ((tag & 1) << 7);
let (src0, length) =
decode_vector_source(*lo, *packed, tail, offset, "unsupported VOP1 source")?;
(Op::VectorUnary(kind, dst, src0), length)
}
// v_swap_b32: SRC0 must be a VGPR (256-511), since it is written.
[lo, packed, upper, tag @ 0x7e..=0x7f, ..]
if (packed >> 1) | ((upper & 1) << 7) == 101 =>
{
if packed & 1 == 0 {
return Err(error(offset, "v_swap_b32 SRC0 is not a VGPR"));
}
(Op::Swap((upper >> 1) | ((tag & 1) << 7), *lo), 4)
}
[lo, packed, upper, tag @ 0x7e..=0x7f, tail @ ..]
if packed & 0xfe == 2 && upper & 1 == 0 =>
@@ -564,6 +829,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(
@@ -654,7 +947,10 @@ 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, ..)
| Op::VectorUnary(_, dst, _)
| Op::Swap(dst, _) => {
if exec != 0
&& registers
.iter()
@@ -736,6 +1032,74 @@ 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::VectorUnary(kind, dst, src0) => {
if exec != 0 {
// Sources are checked once for the wave, as for VOP2.
match src0 {
CompareSource::Vector(register) => {
(0..lanes).try_for_each(|lane| read(lane, register).map(|_| ()))?
}
CompareSource::Scalar(register) => {
read_scalar(Source::Register(register))?;
}
CompareSource::Immediate(_) => {}
}
}
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)));
}
}
// Guide 12.8: tmp = D; D = S0; S0 = tmp, in each active lane.
Op::Swap(dst, src0) => {
if exec != 0 {
for register in [dst, src0] {
(0..lanes).try_for_each(|lane| read(lane, register).map(|_| ()))?;
}
}
let mut swapped = Vec::new();
for lane in (0..lanes).filter(|&lane| executes(lane)) {
swapped.push((lane, read(lane, dst)?, read(lane, src0)?));
}
if !swapped.is_empty()
&& pending_read.is_some_and(|register| register == dst || register == src0)
{
return Err(error(offset, "write to immutable or pending VGPR"));
}
for (lane, old_dst, old_src0) in swapped {
registers[lane][usize::from(dst)] = Some(old_src0);
registers[lane][usize::from(src0)] = Some(old_dst);
}
}
Op::ScalarMove(dst, src) => {
if dst < 8 {
return Err(error(offset, "write to a reserved resource SGPR"));
@@ -803,8 +1167,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 => {
@@ -833,6 +1202,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);
@@ -851,33 +1279,81 @@ 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) => {
Op::Compare(..) | Op::WideCompare(..) => {
let (comparison, width, src0, src1) = match op {
Op::Compare(comparison, src0, src1) => {
(comparison, CompareWidth::Word, src0, src1)
}
Op::WideCompare(comparison, width, src0, src1) => {
(comparison, width, src0, src1)
}
_ => unreachable!(),
};
let mut mask = 0u32;
if exec != 0 {
// The registers each source occupies: a pair for 64-bit forms.
let span = |register: u8| {
if width == CompareWidth::Double {
vec![register, register + 1]
} else {
vec![register]
}
};
// Sources are checked once for the wave, even if no present lane is active.
let check = |register: u8| {
(0..lanes).try_for_each(|lane| read(lane, register).map(|_| ()))
span(register).into_iter().try_for_each(|register| {
(0..lanes).try_for_each(|lane| read(lane, register).map(|_| ()))
})
};
let join = |values: Vec<u32>| {
values
.iter()
.rev()
.fold(0u64, |acc, &value| (acc << 32) | u64::from(value))
};
let read_pair = |lane: usize, register: u8| {
span(register)
.into_iter()
.map(|register| read(lane, register))
.collect::<Result<Vec<_>, _>>()
.map(join)
};
let read_scalar_pair = |register: u8| {
span(register)
.into_iter()
.map(|register| read_scalar(Source::Register(register)))
.collect::<Result<Vec<_>, _>>()
.map(join)
};
match src0 {
CompareSource::Vector(register) => check(register)?,
CompareSource::Scalar(register) => {
read_scalar(Source::Register(register))?;
read_scalar_pair(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,
CompareSource::Vector(register) => read_pair(lane, register)?,
CompareSource::Scalar(register) => read_scalar_pair(register)?,
// Table 20: an inline integer is the value 0..64 or
// -1..-16 at the operand's width (sign extended).
CompareSource::Immediate(bits) => bits as i32 as i64 as u64,
};
if comparison.holds(s0, read(lane, src1)?) {
if comparison.holds_at(width, s0, read_pair(lane, src1)?) {
mask |= 1 << lane;
}
}
+185 -73
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, VectorAluOp, VectorAluVop3Op,
VectorBinary, VectorCompareOp, VectorSource,
};
/// SGPR index of `vcc_lo`.
@@ -155,13 +156,7 @@ impl Op {
Binary::FloatAdd | Binary::FloatMul => format!(
"as_type<uint>(as_type<float>({left}) {symbol} as_type<float>({right}))"
),
Binary::ArithmeticShiftRight => {
format!("as_type<uint>(as_type<int>({left}) {symbol} ({right} & 31u))")
}
Binary::ShiftLeft | Binary::ShiftRight => {
format!("{left} {symbol} ({right} & 31u)")
}
_ => format!("{left} {symbol} {right}"),
Binary::Vector(operation) => vector_expression(operation, &left, &right),
}
}
Self::MergeLanes {
@@ -193,15 +188,18 @@ impl Op {
fn compare_expression(op: VectorCompareOp, left: &str, right: &str) -> String {
use xenora_decoder::CompareRelation;
let symbol = match op.relation {
let symbol = match op.relation() {
CompareRelation::Less => "<",
CompareRelation::Equal => "==",
CompareRelation::LessOrEqual => "<=",
CompareRelation::Greater => ">",
CompareRelation::NotEqual => "!=",
CompareRelation::GreaterOrEqual => ">=",
// F and T read no operand bits.
CompareRelation::False => return "false".to_owned(),
CompareRelation::True => return "true".to_owned(),
};
if op.signed {
if op.signed() {
format!("as_type<int>({left}) {symbol} as_type<int>({right})")
} else {
format!("{left} {symbol} {right}")
@@ -210,29 +208,79 @@ fn compare_expression(op: VectorCompareOp, left: &str, right: &str) -> String {
#[derive(Clone, Copy)]
enum Binary {
Add,
ShiftLeft,
ShiftRight,
ArithmeticShiftRight,
And,
Or,
Xor,
FloatAdd,
FloatMul,
/// A registry VOP2 integer operation (or its VOP3 encoding), lowered by its
/// typed template.
Vector(VectorBinary),
}
impl Binary {
fn operator(self) -> (&'static str, &'static str) {
match self {
Self::Add => ("add.u32", "+"),
Self::ShiftLeft => ("lshl.b32", "<<"),
Self::ShiftRight => ("lshr.b32", ">>"),
Self::ArithmeticShiftRight => ("ashr.i32", ">>"),
Self::And => ("and.b32", "&"),
Self::Or => ("or.b32", "|"),
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",
VectorBinary::And => "and.b32",
VectorBinary::Or => "or.b32",
VectorBinary::Xor => "xor.b32",
VectorBinary::ShiftLeft => "lshl.b32",
VectorBinary::ShiftRight => "lshr.b32",
VectorBinary::ArithmeticShiftRight => "ashr.i32",
},
"",
),
}
}
}
/// 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)),
VectorBinary::And => format!("{left} & {right}"),
VectorBinary::Or => format!("{left} | {right}"),
VectorBinary::Xor => format!("{left} ^ {right}"),
// MSL leaves shifts by 32 or more undefined; the guide reads S0[4:0].
VectorBinary::ShiftLeft => format!("{left} << ({right} & 31u)"),
VectorBinary::ShiftRight => format!("{left} >> ({right} & 31u)"),
VectorBinary::ArithmeticShiftRight => {
format!("as_type<uint>(as_type<int>({left}) >> ({right} & 31u))")
}
}
}
@@ -435,7 +483,7 @@ pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result<CompiledShade
let _ = writeln!(
ir,
"{offset:04x}: {dest} = wave.mask {} {src0}, {src1} exec=0x{exec:08x}",
op.mnemonic()
op.assembly_name()
);
emit_lane_mask(&mut msl, &operations, &uniform, index, op, src0, src1, exec);
continue;
@@ -473,7 +521,15 @@ fn emit_lane_mask(
exec: u32,
) {
let mut cone = vec![false; index];
let mut pending = vec![src0, src1];
// F and T do not depend on the operands, so their lanes compute none.
let mut pending = if matches!(
op.relation(),
xenora_decoder::CompareRelation::False | xenora_decoder::CompareRelation::True
) {
Vec::new()
} else {
vec![src0, src1]
};
while let Some(value) = pending.pop() {
if uniform[value.0] || cone[value.0] {
continue;
@@ -623,16 +679,28 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
if let Some((_, _, before)) = &region {
let dst = match instruction.instruction {
Instruction::MoveB32 { dst, .. }
| Instruction::AddNoCarryU32 { dst, .. }
| Instruction::VectorLshlrevB32 { dst, .. }
| Instruction::VectorLshrrevB32 { dst, .. }
| Instruction::VectorAshrrevI32 { dst, .. }
| Instruction::VectorAndB32 { dst, .. }
| Instruction::VectorOrB32 { dst, .. }
| Instruction::VectorXorB32 { dst, .. } => dst,
// Of the VOP3 variants, the contract admits only v_add_nc_u32_e64.
| Instruction::VectorAluVop3 {
op: VectorAluVop3Op::AddNcU32,
dst,
..
}
// Of the registry VOP2 forms, the contract admits only the six
// logical and shift forms that were hand-written before (#215 M27).
| Instruction::VectorAlu {
op:
VectorAluOp::LshlrevB32
| VectorAluOp::LshrrevB32
| VectorAluOp::AshrrevI32
| VectorAluOp::AndB32
| VectorAluOp::OrB32
| VectorAluOp::XorB32,
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 VOP2 logical and shift forms",
));
}
};
@@ -662,15 +730,10 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
if exec == 0 {
match instruction.instruction {
Instruction::MoveB32 { .. }
| Instruction::AddNoCarryU32 { .. }
| Instruction::VectorLshlrevB32 { .. }
| Instruction::VectorLshrrevB32 { .. }
| Instruction::VectorAshrrevI32 { .. }
| Instruction::VectorAndB32 { .. }
| Instruction::VectorOrB32 { .. }
| Instruction::VectorXorB32 { .. }
| Instruction::VectorAluVop3 { .. }
| Instruction::VectorAddF32 { .. }
| Instruction::VectorMulF32 { .. } => continue,
| Instruction::VectorMulF32 { .. }
| Instruction::VectorAlu { .. } => continue,
_ => {}
}
}
@@ -768,29 +831,22 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
Some(dst),
Op::Constant(read_scalar(ScalarSource::Register(register))?),
),
Instruction::AddNoCarryU32 { dst, src0, src1 } => {
(Some(dst), Op::Binary(Binary::Add, read(src0)?, read(src1)?))
}
Instruction::VectorLshlrevB32 { dst, src0, src1 } => (
Some(dst),
Op::Binary(Binary::ShiftLeft, read(src1)?, read(src0)?),
),
Instruction::VectorAshrrevI32 { dst, src0, src1 } => (
Some(dst),
Op::Binary(Binary::ArithmeticShiftRight, read(src1)?, read(src0)?),
),
Instruction::VectorLshrrevB32 { dst, src0, src1 } => (
Some(dst),
Op::Binary(Binary::ShiftRight, read(src1)?, read(src0)?),
),
Instruction::VectorAndB32 { dst, src0, src1 } => {
(Some(dst), Op::Binary(Binary::And, read(src0)?, read(src1)?))
}
Instruction::VectorOrB32 { dst, src0, src1 } => {
(Some(dst), Op::Binary(Binary::Or, read(src0)?, read(src1)?))
}
Instruction::VectorXorB32 { dst, src0, src1 } => {
(Some(dst), Op::Binary(Binary::Xor, read(src0)?, read(src1)?))
Instruction::VectorAluVop3 {
op,
dst,
src0,
src1,
} => {
let op = op.base();
let (left, right) = if op.swaps_sources() {
(read(src1)?, read(src0)?)
} else {
(read(src0)?, read(src1)?)
};
(
Some(dst),
Op::Binary(Binary::Vector(op.lowering()), left, right),
)
}
Instruction::ScalarMoveB32 { dst, src } => {
let value = read_scalar(src)?;
@@ -831,20 +887,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 } => {
@@ -938,6 +996,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)?),
@@ -964,15 +1060,18 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
};
let value_bits = match operation {
Op::Constant(bits) => KnownBits::constant(bits),
Op::Binary(Binary::And, left, right) => facts[left.0].and(facts[right.0]),
Op::Binary(Binary::Or, left, right) => facts[left.0].or(facts[right.0]),
Op::Binary(Binary::Xor, left, right) => facts[left.0].xor(facts[right.0]),
Op::Binary(Binary::Vector(VectorBinary::And), left, right) => facts[left.0].and(facts[right.0]),
Op::Binary(Binary::Vector(VectorBinary::Or), left, right) => facts[left.0].or(facts[right.0]),
Op::Binary(Binary::Vector(VectorBinary::Xor), left, right) => facts[left.0].xor(facts[right.0]),
Op::Binary(operator @ (Binary::FloatAdd | Binary::FloatMul), left, right) => {
exact_float_result(operator, facts[left.0], facts[right.0])
.ok_or_else(|| error("FP32 operation is not proven exact for positive normal operands and results"))?
}
_ => 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 {
@@ -987,7 +1086,7 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
&mut facts,
offset,
exec,
next,
produced,
registers[slot],
)?);
}
@@ -998,6 +1097,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
@@ -322,6 +322,48 @@ fn scalar_unary_results_reach_the_kernel_as_constants() {
);
}
#[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_f_and_t_compares_lower_to_operand_free_wave_masks() {
let code = include_bytes!("../../../fixtures/rdna2/vector-compare-ft.bin");
let result = compile(Architecture::Gfx1030, code).unwrap();
assert_eq!(
result.ir,
include_str!("../../../fixtures/golden/vector-compare-ft.ir")
);
assert_eq!(
result.msl,
include_str!("../../../fixtures/golden/vector-compare-ft.metal")
);
}
#[test]
fn vector_compares_lower_to_per_thread_wave_masks_and_selects() {
let code = include_bytes!("../../../fixtures/rdna2/vector-compare.bin");
+6
View File
@@ -31,6 +31,8 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
## Guest CPU and runtime experiments
- [Guest experiment guide](../experiments/x1/README.md) — Bounded x86-64 execution, executable loading, experimental services, native compute, and offscreen rendering.
- [x86-64 instruction registry](cpu/instruction-registry.md) — Shared decoder, generated tables, semantics, native lowering and how to add a verified instruction form.
- [Runtime service registry](runtime/registry.md) and [generated coverage](runtime/services.md) — Import resolution, typed Win64 adapters and how to add a tested service.
- [Guest CPU research](research/cpu-boundary.md) — Public specifications and unresolved console requirements.
- [Synthetic import fixtures](../tests/compat_fixtures/README.md) — Reproducible PE32+ builds and expected service behavior.
@@ -54,3 +56,7 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
- [Legal scope](legal.md), [dependency licensing](licenses.md), and [third-party notices](../THIRD_PARTY_NOTICES.md) — Input policy, attribution, and redistribution findings.
- [Contribution guidelines](../CONTRIBUTING.md) — Original authorship, Developer Certificate of Origin sign-off, and evidence requirements.
- [Agent task queue](coordination/agent-tasks.md) — Areas, claiming, leases, upstream sync, verification and the security model for parallel contributors and coding agents.
- [CPU/runtime expansion campaign ledger](coordination/cpu-campaign-ledger.md) — Progress ledger for the Xenora native CPU and runtime compatibility campaign: starting/current commits, completed batches, new forms, verification evidence and the next implementation target.
- [Infrastructure QA ownership](coordination/infrastructure-qa-ownership.md) — Non-overlapping paths for infrastructure and QA tooling.
- [Agent queue smoke evidence](coordination/agent-queue-smoke.md) — Live Actions results from the disposable smoke repository.
- [Infrastructure QA tooling](testing/infrastructure/README.md) — Advisory orchestration, PR validation, benchmark analysis and release checks.
+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: 72 of 72. Accepted Metal forms · Apple M5: 18 of 72. Accepted guest milestones · X1–X4: 4 of 4</desc>
<desc id="description">Decoded gfx1030 forms: 104 of 104. Accepted Metal forms · Apple M5: 18 of 104. Accepted guest milestones · X1–X4: 4 of 4</desc>
<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">72 / 72</text>
<text x="510" y="58" font-size="13" text-anchor="end">104 / 104</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 / 72</text>
<text x="510" y="96" font-size="13" text-anchor="end">18 / 104</text>
<rect x="20" y="103" width="490" height="4" rx="2" fill="#3c4a58"/>
<rect x="20" y="103" width="122.50" height="4" rx="2" fill="#88c6bd"/>
<rect x="20" y="103" width="84.81" 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
```
+128
View File
@@ -0,0 +1,128 @@
# Xenora CPU/Runtime Expansion Campaign — Progress Ledger
Evidence below is local to the named host unless stated. Nothing here is independently reviewed yet.
## Continuation checkpoint
- Continuation branch base: `0836936` (tip of `feat/cpu-runtime-expansion`), merged with main `d22f046` (#272, #273, #274) as `56febbb`. The merge had no conflicts.
- All recorded checkpoints (`a953ba9`, `9cd6f43`, `7e09c9c`, `bfd14e4`, `0836936`) exist upstream. The earlier session's uncommitted MOVSX patch was not available and was not used.
- Host: Apple M5 Pro, macOS, Rust 1.100.0, Apple clang 17.0.0. No Homebrew LLVM, `llvm-mc` or full Xcode.
- Baseline of the merge: `cargo test --locked --workspace --no-fail-fast` exited 101 with 392 passed, 1 failed, 21 ignored. The failure (`probe_fuzz_harness_minimized_artifact`) also occurs on `0836936`: the test read an untracked file.
## Corrections to earlier entries
- The earlier claim of 381 passed and 0 failed did not hold for a fresh checkout (see above).
- The SXTW encoding recorded as verified was wrong for most source registers.
- #65, #66 and #117 were marked complete prematurely. They stay open until reviewed against their own acceptance criteria.
## Milestones
| # | Commit subject | Scope | Evidence |
| --- | --- | --- | --- |
| 1 | cpu: correct the sign- and zero-extension family | MOVZX/MOVSX/MOVSXD, MOV-immediate regressions, SXTW, 32-bit access width, RIP-relative and LEA addressing, self-contained prefix test | `tests/movsxd.rs`: 9 tests over 93 LLVM-assembled register forms and 32 MOV immediates, each run by the interpreter and as native translated code; 16 of 16 targeted mutations caught |
| 2 | cpu: share one generated decoder and store guest flags | Registry, generator, shared decoder and semantics, integer expansion, architectural DBT flags, truthful probe support | `tests/x86_integer.rs`, `tests/arm64_encodings.rs`, `tests/x86_generator`; 37 targeted mutations: 36 caught (4 only after new tests), and one equivalent, whose redundant check was removed |
| 3 | cpu: add SSE2 state, moves and packed integer forms | XMM and MXCSR state, mandatory prefixes, SSE/SSE2 moves and packed integer operations, NEON lowering | `tests/x86_vector.rs` (9 tests, 374 LLVM-assembled instructions, 64 states each), `tests/arm64_encodings.rs`; 35 targeted mutations: 34 caught (1 only after a new test) and one equivalent |
| 4 | cpu: add exact SSE and SSE2 floating point | Software binary32/binary64 arithmetic with MXCSR, compares and conversions | `tests/x86_float.rs` (9 tests, 6,824 exact-fraction vectors, 172 LLVM-assembled instructions, over 2 million host comparisons); 53 targeted mutations: 52 caught (2 only after directed vectors), and one changes a rule deliberately left unasserted |
| 5 | runtime: one import resolver and typed service adapters | Bounded import parser shared by probe and binder, strict registry, transactional binding, Win64 preservation check, typed registry and generator, 20 services | `tests/runtime_services.rs` (19 tests; every service is called by translated guest code), generator unit tests (4); 33 valid targeted mutations: all caught, 2 only after new cases |
Encodings: `clang -target x86_64-apple-macos -c` and `clang -target arm64-apple-macos -c`, read back with `objdump -d`.
## Verification of milestone 2 (local, real exit codes)
| Gate | Result |
| --- | --- |
| `cargo fmt --all -- --check`; strict Clippy, workspace, all targets and features | exit 0; exit 0 |
| `cargo test --locked --workspace --no-fail-fast` | exit 0: 409 passed, 0 failed, 21 ignored |
| `generate_x86.py --check`, `assemble.py --check`, generator tests (8) | exit 0 |
| RDNA2 metadata, semantic registry, coverage and status checks; their Python tests | exit 0 |
| `scripts/audit/{claims,dependencies,native}.sh`, release build, `shaders coverage` | exit 0 |
| `scripts/test-gpu.sh` | first run exit 124 (its own timeout, in `sop2_arith`, straight after a release build); rerun exit 0: 69 passed, 0 failed, 1 ignored |
| `scripts/demo.sh`, `scripts/build-app.sh`, `--smoke-frame`, `--inspect` | exit 0 |
| `scripts/assemble-fixture.sh --check`; ignored LLVM tests in `xenora-isa` and `xenora-decoder` | not verified: need Homebrew LLVM (`llvm-mc`) |
| Fuzz and mutation campaigns | not run |
Coverage: 56 operations, 184 declared forms, 279 opcode slots. 985 LLVM-assembled instructions execute every form except control flow and exits, which have their own tests.
`dbt_bench` on an Apple M5 Pro, 101 samples, three runs each of `5ab561b` and milestone 2, middle run: interpreter 12.69 to 11.12 MIPS, cold DBT 10.43 to 8.86 MIPS, warm DBT 468.83 to 424.86 MIPS, native code 242,608 to 290,184 bytes. The slowdown comes with the new work of storing six flags and the shared decode; the earlier figures belong to code that computed wrong flags. Not optimized yet. These are synthetic and say nothing about games.
## Verification of milestone 3 (local, real exit codes)
Main `19bea60` (#278 and QA tooling) was merged first as `70f1793`; it does not touch `crates/loader`. `CHANGELOG.md` and `docs/README.md` conflicted and both sides were kept.
| Gate | Result |
| --- | --- |
| Formatting; strict Clippy, workspace, all targets and features | exit 0; exit 0 |
| `cargo test --locked --workspace --no-fail-fast` | exit 0: 429 passed, 0 failed, 22 ignored |
| `generate_x86.py --check`, `assemble.py --check`, generator tests (10) | exit 0 |
| RDNA2 metadata, semantic registry, coverage and status checks; their Python tests; claims, dependencies and native audits; release build | exit 0 |
| `scripts/test-gpu.sh`, `demo.sh`, `build-app.sh`, `--smoke-frame`, `--inspect` | exit 0; GPU 74 passed, 0 failed, 1 ignored |
| `scripts/assemble-fixture.sh --check` and ignored LLVM AMDGPU tests | not verified: need `llvm-mc` |
| Fuzz and mutation campaigns | not run |
The registry now has 139 operations, 306 forms and 401 opcode slots. `dbt_bench`, integer only, middle of three runs: interpreter 11.18, cold DBT 8.62 and warm DBT 430.19 MIPS, with the same 290,184 native bytes as milestone 2. No SIMD throughput benchmark exists yet.
## Verification of milestone 4 (local, real exit codes)
| Gate | Result |
| --- | --- |
| Formatting; strict Clippy, workspace, all targets and features | exit 0; exit 0 |
| `cargo test --locked --workspace --no-fail-fast` | exit 0: 438 passed, 0 failed, 22 ignored |
| `generate_x86.py --check`, `assemble.py --check`, `float_reference.py --check`, generator tests (10) | exit 0 |
| RDNA2 metadata, semantic registry, coverage and status checks; their Python tests; claims, dependencies and native audits; release build | exit 0 |
| `scripts/test-gpu.sh`, `demo.sh`, `build-app.sh`, `--smoke-frame`, `--inspect` | exit 0; GPU 74 passed, 0 failed, 1 ignored |
| `scripts/assemble-fixture.sh --check` and ignored LLVM AMDGPU tests | not verified: need `llvm-mc` |
| Fuzz and mutation campaigns | not run |
The registry now has 191 operations, 358 forms and 453 opcode slots. `dbt_bench`, integer only, middle of three runs: interpreter 11.32, cold DBT 8.81 and warm DBT 430.19 MIPS (one warm run read 377.43). No floating-point or SIMD throughput benchmark exists.
Main moved to 15 commits past this branch after milestone 3; they do not touch `crates/loader` and are not merged yet.
## Verification of milestone 5 (local, real exit codes)
Main `f685ede` (QA tooling) was merged first as `5e7c21b`.
| Gate | Result |
| --- | --- |
| Formatting; strict Clippy, workspace, all targets and features | exit 0; exit 0 |
| `cargo test --locked --workspace --no-fail-fast` | exit 0: 462 passed, 0 failed, 22 ignored |
| `xenora-runtime-gen --check`; CPU generator, assembler and float reference checks; generator tests | exit 0 |
| RDNA2 metadata, semantic registry, coverage and status checks; their Python tests; claims, dependencies and native audits; release build | exit 0 |
| `scripts/test-gpu.sh`, `demo.sh`, `build-app.sh`, `--smoke-frame`, `--inspect` | exit 0; GPU 74 passed, 0 failed, 1 ignored |
| `scripts/assemble-fixture.sh --check` and ignored LLVM AMDGPU tests | not verified: need `llvm-mc` |
| Fuzz and mutation campaigns | not run |
`dbt_bench`, middle of three runs: interpreter 11.08, cold DBT 8.48 and warm DBT 409.65 MIPS. Warm runs read 392 to 417, against 430 for milestone 4; no change here is known to affect that path and the cause was not investigated.
The panic of #270 was reproduced on `5e7c21b` (`range start index 1025 out of range`) and does not occur after this milestone.
## Integration of main `c6a354b`
Merged after milestone 5. It carries #280 (#72), #281 (#66) and #283 (#65), published while this branch was not; those issues are not claimed here and the published work takes precedence in authorship.
- Kept: every upstream test, unchanged (`tests/bootstrap.rs` and the three new tests in `dbt.rs`), and the assembler's `sxtb_32` and `sxth_32`, now checked against LLVM.
- Source: `cpu.rs` and `dbt.rs` keep the shared decoder and lowering, which already cover the merged behaviour.
- Adopted from upstream: FS and GS together are undefined, and GS applies. This branch used to reject the combination. RIP-relative, negative-displacement and fault-address regressions for both segments were added (11 encodings, both engines); 3 of 3 mutations of the rule caught.
- Compared: the integer fixture run through both trees in both engines. Upstream supports 142 instruction and engine pairs. They differ only where upstream stores no guest flags in the DBT (#64, #70), reads AH, CH, DH and BH as SPL, BPL, SIL and DIL (#68, including MOVZX and MOVSX in both engines), or writes eight bytes for a 32-bit store.
- Gates: workspace 474 passed, 0 failed, 22 ignored; formatting, strict Clippy, all generator checks, repository audits, release build, GPU suite, demo and app gates exit 0. GPU: 80 passed, 0 failed, 1 ignored.
Main `4db0b9c` (#286, #287) was merged next. #286 fixed #270 first; its test and its bounds check on section offsets are kept, and imports stay on the shared parser. Gates on that merge: workspace 477 passed, 0 failed, 22 ignored; GPU 84 passed, 0 failed, 1 ignored; formatting, strict Clippy, generator checks, audits, release build, demo and app gates exit 0.
## Known limitations
- Only the forms in `x86/instructions.toml` exist. The RCP and RSQRT approximations, SSE3 and later, MMX, VEX, string instructions, RCL, RCR, SHLD, SHRD, LOCK, fences and atomics are unsupported.
- Every floating-point form runs through software arithmetic in the DBT; none is lowered to NEON. No x86 hardware comparison exists, and `docs/cpu/instruction-registry.md` lists the choices left unasserted.
- Packs, shuffles, high multiplies, PSADBW, sign-mask extraction, word insertion and extraction, byte shifts and shifts by a register count run through the shared semantics in the DBT.
- The fixture graphics services, `XMemAlloc` and the `XMemFree` stub are outside the typed registry. Several older generated conformance tests check Rust library functions, not services.
- Last error is one value per process; per-thread isolation (#202) waits for guest threads.
- 8- and 16-bit ALU operations, shifts, MUL, DIV and bit operations run through the shared semantics in the DBT, not as ARM64.
- The reference and the implementation share an author.
- New CPU checks are not in CI; `.github` was left unchanged.
## Pending acceptance
- Two independent reviews required by `AGENTS.md`: not performed.
- Issues touched here have not been claimed on GitHub and stay open.
## Next task
Agree with the maintainer and the contributor of #280, #281, #283 and #286 how this branch should be offered, before more overlapping work. Then native CRT memory and string services, which are not started.
@@ -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.
+50
View File
@@ -0,0 +1,50 @@
# x86-64 instruction registry
The static PE probe, the interpreter and the native ARM64 dynamic binary translator (DBT) decode guest code through one function, `x86_decode::decode`. Its tables are generated from `crates/loader/x86/instructions.toml`.
| Part | File | Role |
| --- | --- | --- |
| Registry | `crates/loader/x86/instructions.toml` | Opcode map, opcode, ModRM digit, operand encoding, size, immediate, flag effects and public reference. Data only. |
| Generator | `crates/loader/generate_x86.py` | `validate`, `generate` and `--check`. Rejects overlapping encodings, opcodes that are prefixes, contradictory operand rules, unknown vocabulary and flags both written and undefined. |
| Tables | `crates/loader/src/x86_table.rs` | Generated static tables. No metadata is parsed at run time. |
| Semantics | `crates/loader/src/x86_exec.rs`, `x86_simd.rs`, `x86_float.rs`, `softfloat.rs` | Rust primitives for integer, vector and floating-point forms. Every instruction is all-or-nothing. |
| Lowering | `crates/loader/src/dbt.rs` | ARM64 for the forms `is_native` accepts. Every other form calls the shared semantics and is counted in `DbtMetrics::interpreter_fallbacks`. |
## Adding a form
1. Add the form, and its operation if new, to the registry with an Intel SDM or AMD APM reference.
2. Run `python3 crates/loader/generate_x86.py generate`.
3. Implement the operation in `x86_exec.rs`. Leave flags the manuals call undefined unchanged.
4. Add assembly text to `crates/loader/tests/x86/assemble.py`, run it with `generate`, and extend the reference in `tests/x86_integer.rs` or `tests/x86_vector.rs`. A declared form without a fixture fails `every_declared_form_is_executed_by_a_fixture`.
5. Lower it natively only if the ARM64 result and flags match. The same tests require native forms never to call the helper, and helper forms always to.
A declared form is decodable, not implemented. Count a form as supported only when the tests above cover it.
## Independence
The references in `tests/x86_integer.rs` and `tests/x86_vector.rs` read only LLVM assembly text. They do not use the encodings, registry, decoder or production semantics, and work bit by bit or on byte arrays. They were written by the same contributor as the implementation, so independent review is still required.
## Guest flags
The DBT stores CF, ZF, SF, OF, PF and AF in `CpuState::flags`. It skips the store only when a later instruction in the block overwrites all six before anything can read them, fault or leave the block.
FS and GS overrides together are architecturally undefined; GS applies, in both engines.
## Vector state
XMM registers live in `CpuState::xmm`, lane 0 in the low bits, and MXCSR in `CpuState::mxcsr`. A mandatory 0x66, F3 or F2 prefix selects a form; the generator rejects an opcode where 0x66 could be both a mandatory prefix and an operand size. A 16-byte memory operand must be aligned unless its form says otherwise, and a violation exits with `GeneralProtection` before any memory access. Non-temporal stores are ordinary stores.
## Floating point
`softfloat.rs` follows the Intel SDM (Vol. 1, 4.8, 4.9 and 11.5) without host floating point. Expected values come from exact fractions in `tests/x86/float_reference.py`. Some behaviour is implemented one way but not asserted, because the sections used leave it open or it was not found there:
- a denormal dividend over zero raises divide-by-zero only, not also denormal-operand;
- flush-to-zero also flushes a tiny result that is exact, raising underflow and precision;
- DAZ applies before conversion to an integer;
- an unmasked overflow also records precision.
None of it has been compared with x86 hardware.
## Rejected on purpose
LOCK, F2 or F3 where it is neither PAUSE nor part of a declared form, F2 combined with F3, address-size overrides, an ignored segment override after FS or GS, 16-bit stack and branch forms, 16-bit BSWAP and MOVSXD, bit tests of memory by a register index, RCL, RCR, SHLD, SHRD, string instructions, MMX, the RCP and RSQRT approximations, SSE3 and later, VEX, atomics and fences. The DBT also refuses raw SYSCALL.
+29
View File
@@ -0,0 +1,29 @@
# Runtime service registry
Guest imports resolve through one lookup, `ImportRegistry::resolve`. Binding, the static probe and the command-line reports all use it, and they read the import directory with one bounded parser, `import_table::parse_imports`.
| Part | File | Role |
| --- | --- | --- |
| Registry | `crates/loader/runtime/services.txt` | Library, symbol, typed signature, API-set aliases, failure contract, status, reference and tests. Data only. |
| Generator | `xenora-runtime-gen` in `crates/import-gen` | `validate`, `generate` and `--check`. Rejects conflicting keys, unlisted API sets, unsupported types, and behaviour without a named, existing test. |
| Adapters | `crates/loader/src/runtime_table.rs` | Generated Win64 argument and result adapters and static metadata. |
| Handlers | `handlers` in `crates/loader/src/services.rs` | Rust implementations. They see guest memory and service state, never the CPU. |
| Report | [services.md](services.md) | Generated counts. Aliases are counted apart from services. |
## Rules
- Module names compare without case; symbol names are exact. A name spelled `Ordinal#7` is not ordinal 7.
- An API set resolves only if the registry lists that exact set for that symbol. A similar name forwards nowhere.
- Registering a key twice is an error. A host module cannot replace a standard service.
- Binding resolves every import before it writes any slot. A malformed table or an unresolved import leaves every slot unbound.
- A service call reads its return address first, and stops the guest with `ServiceAbiViolation` if the service changed a nonvolatile register, including XMM6 to XMM15.
## Adding a service
1. Write a test in `crates/loader/tests/runtime_services.rs` that calls it from guest code and derives its expectations from the public documentation.
2. Add the entry to `services.txt` and the handler to `services.rs`.
3. Run `cargo run -p xenora-import-gen --bin xenora-runtime-gen generate`.
## Outside this registry
The fixture graphics services, `XMemAlloc` and the `XMemFree` stub are still registered by hand. The older import-list generator in `crates/import-gen` is separate: its output is not compiled into the loader, and several of its generated conformance tests check Rust library functions rather than a service.
+40
View File
@@ -0,0 +1,40 @@
# Typed runtime services
Generated by `xenora-runtime-gen` from `crates/loader/runtime/services.txt`. Do not edit.
A declared service is not a claim of compatibility. `implemented` and `partial` describe behaviour against the documented contract for the synthetic guest. No service has been independently accepted.
| Measure | Count |
| --- | ---: |
| Services with a declared ABI | 20 |
| Generated adapters | 20 |
| Unique handler implementations | 20 |
| Implemented | 7 |
| Partial | 13 |
| Stub | 0 |
| Conformance-tested through guest dispatch | 20 |
| API-set aliases (not services) | 20 |
| Independently accepted | 0 |
| Service | Signature | Status | Failure |
| --- | --- | --- | --- |
| `kernel32.dll!SetProcessPriorityBoost` | `(process: handle, disable: bool32) -> bool32` | partial | 0 with ERROR_INVALID_HANDLE |
| `kernel32.dll!GetProcessPriorityBoost` | `(process: handle, disabled: out<4>) -> bool32` | partial | 0 with ERROR_INVALID_HANDLE or ERROR_NOACCESS |
| `kernel32.dll!GetCurrentProcess` | `() -> handle` | implemented | never |
| `kernel32.dll!GetProcessId` | `(process: handle) -> u32` | partial | 0 with ERROR_INVALID_HANDLE |
| `kernel32.dll!GetCurrentThread` | `() -> handle` | implemented | never |
| `kernel32.dll!GetCurrentProcessId` | `() -> u32` | implemented | never |
| `kernel32.dll!GetCurrentThreadId` | `() -> u32` | implemented | never |
| `kernel32.dll!OpenThread` | `(access: u32, inherit: bool32, thread: u32) -> handle` | partial | 0 with ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED or ERROR_NOT_ENOUGH_MEMORY |
| `kernel32.dll!GetThreadPriority` | `(thread: handle) -> i32` | partial | THREAD_PRIORITY_ERROR_RETURN with ERROR_INVALID_HANDLE or ERROR_ACCESS_DENIED |
| `kernel32.dll!SetThreadPriority` | `(thread: handle, priority: i32) -> bool32` | partial | 0 with ERROR_INVALID_HANDLE, ERROR_ACCESS_DENIED, ERROR_NOT_SUPPORTED or ERROR_INVALID_PARAMETER |
| `kernel32.dll!CloseHandle` | `(object: handle) -> bool32` | partial | 0 with ERROR_INVALID_HANDLE |
| `kernel32.dll!GetSystemTimeAsFileTime` | `(time: out<8>) -> void` | implemented | guest fault on an invalid pointer |
| `kernel32.dll!GetLastError` | `() -> u32` | partial | never |
| `kernel32.dll!SetLastError` | `(code: u32) -> void` | partial | never |
| `kernel32.dll!VirtualAlloc` | `(address: ptr, size: u64, kind: u32, protect: u32) -> ptr` | partial | 0 with ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED, ERROR_INVALID_ADDRESS or ERROR_NOT_ENOUGH_MEMORY |
| `kernel32.dll!VirtualFree` | `(address: ptr, size: u64, kind: u32) -> bool32` | partial | 0 with ERROR_NOT_SUPPORTED, ERROR_INVALID_PARAMETER or ERROR_INVALID_ADDRESS |
| `ucrtbase.dll!sqrt` | `(x: f64) -> f64` | partial | NaN for a negative argument; errno is not set |
| `ucrtbase.dll!sqrtf` | `(x: f32) -> f32` | partial | NaN for a negative argument; errno is not set |
| `ucrtbase.dll!fabs` | `(x: f64) -> f64` | implemented | never |
| `ucrtbase.dll!fabsf` | `(x: f32) -> f32` | implemented | never |
+32
View File
@@ -61,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 |
@@ -73,6 +89,10 @@ The wider LLVM operand matrix exercises decoding only. ABI means application bin
| `v_cmp_gt_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (unsigned S0 > S1), fully written | `7D8802C0` | 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_ne_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (unsigned S0 != S1), fully written | `7D8A026A` | 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_ge_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0; VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & (unsigned S0 >= S1), fully written | `7D8C0D01` | 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_f_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0 (signed); VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & false, fully written | `7D000501` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_t_i32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0 (signed); VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & true, fully written | `7D0E0501` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_f_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0 (unsigned); VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & false, fully written | `7D800501` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `v_cmp_t_u32_e32` | VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0 (unsigned); VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & true, fully written | `7D8E0501` | yes | yes | three-way passed | per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select | implemented | local known-answer test passed | local Apple M5 readback passed; acceptance pending |
| `s_cbranch_scc0` | Nonnegative signed dword displacement | `BF840002` | yes | yes | three-way passed | resolved conditional branch | implemented | fixture verified | fixture verified |
| `s_branch` | Nonnegative signed dword displacement | `BF820001` | yes | yes | three-way passed | resolved branch | implemented | fixture verified | fixture verified |
| `v_and_b32_e32` | Two VGPR sources and one VGPR destination | `36020702` | yes | yes | three-way passed | MSL bitwise AND | implemented | fixture verified | fixture verified |
@@ -85,6 +105,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 -1
View File
@@ -8,12 +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)). |
| VOPC `V_CMP_{F,LT,EQ,LE,GT,NE,GE,T}_{I32,U32}` | Compare widened 64-bit values per active lane (F is false and T true for every 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). |
+46 -5
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 |
| --- | --- | --- |
@@ -31,7 +33,7 @@ ignored.
Sources are normal SGPRs, inline integers (-16 to 64) or one literal word.
These forms are declared as data in the semantic registry,
`crates/isa/semantics/rdna2.toml`: opcode, operation, signedness, carry-in,
`crates/isa/semantics/rdna2/sop2.toml`: opcode, operation, signedness, carry-in,
SCC effect, operand rule and guide references. `crates/isa/generate_semantics.py`
checks each declaration against the pinned AMD XML snapshot and rejects
contradictions (for example a carry-in on a bitwise form, or a signed form whose
@@ -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}`
+9 -5
View File
@@ -25,18 +25,18 @@ acceptance remain outside the verified count. All results concern synthetic fixt
| SCRATCH | 22 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| SMEM | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| SOP1 | 65 | 12 | 11 | 12 | 12 | 12 | 1 | 1 | 11 |
| SOP2 | 51 | 17 | 17 | 17 | 17 | 17 | 0 | 0 | 12 |
| 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 |
| VOP3 | 416 | 1 | 0 | 1 | 1 | 1 | 1 | 1 | 0 |
| VOP2 | 47 | 20 | 18 | 20 | 20 | 20 | 7 | 7 | 11 |
| VOP3 | 416 | 1 | 1 | 1 | 1 | 1 | 1 | 1 | 12 |
| VOP3P | 29 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| VOP3SDST | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
| VOPC | 190 | 12 | 0 | 12 | 12 | 12 | 0 | 0 | 0 |
| **Total** | 1465 | 72 | 40 | 76 | 72 | 72 | 18 | 18 | 30 |
| VOPC | 190 | 16 | 16 | 16 | 16 | 16 | 0 | 0 | 7 |
| **Total** | 1465 | 104 | 91 | 108 | 104 | 104 | 18 | 18 | 60 |
## Unsupported operand variants
@@ -47,3 +47,7 @@ The table counts distinct variant names per family across registry operand rules
| 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` |
| VOP2 | `vop2_vgpr2` | `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` |
| VOP3 | `vop3_vgpr2` | `modifiers`, `src2`, `src_exec`, `src_float_inline`, `src_inline`, `src_literal`, `src_m0`, `src_null`, `src_sgpr`, `src_special`, `src_ttmp`, `src_vcc` |
| VOPC | `vopc_vcc` | `src_exec`, `src_float_inline`, `src_m0`, `src_null`, `src_special`, `src_ttmp`, `src_vcc_hi` |
+121 -18
View File
@@ -12,7 +12,8 @@ The registry covers the nine SOP2 forms listed in [SOP2 scalar ALU](scalar-alu.m
| File | Role |
| --- | --- |
| `crates/isa/semantics/rdna2.toml` | The registry. Data only: every value comes from a closed vocabulary. |
| `crates/isa/semantics/rdna2.toml` | The registry root: schema, architecture, the snapshot hash, the cited documents and the ordered `include` list of family files. |
| `crates/isa/semantics/rdna2/<family>.toml` | One file per encoding family (`sop2.toml`, `sopc.toml`, `sop1.toml`, `vop2.toml`, `vopc.toml`, `vop3.toml`): that family's operand rules, forms and encoding variants only. Data only: every value comes from a closed vocabulary. |
| `crates/isa/generate_semantics.py` | Validates the registry and writes the Rust tables. Python 3.11 or newer, standard library only. |
| `crates/isa/data/rdna2.jsonl` | Pinned snapshot of the AMD machine-readable ISA XML, used to cross-check identity and operands. |
| `crates/isa/src/semantics_gen.rs` | Generated output. Never edit it by hand. |
@@ -20,9 +21,65 @@ The registry covers the nine SOP2 forms listed in [SOP2 scalar ALU](scalar-alu.m
| `crates/isa/src/primitive.rs` | The shared integer primitives that the generated `evaluate` calls. |
| `tests/semantics_generator/` | Unit tests for the generator. |
## Family files
The root lists its family files under `include`. The generator merges them in
that order, and forms keep their order within each file, so the merged registry
equals one file with the parts concatenated (splitting the original single file
left `semantics_gen.rs` byte-identical). A family file may hold only
`[operand_rules.*]`, `[[form]]` and `[[encoding_variant]]` entries of the family
it is named after: `rdna2/vop2.toml` holds VOP2 rules and forms and nothing else.
Each include must be `rdna2/<lower-case family>.toml`, a regular file in that directory (not a link). The loader rejects a form,
rule or variant of another family, a rule declared in two files, root keys in a
family file, any other include path, and a missing or repeated include. The
coverage report and the RDNA2 planner use the same loader. Work on different
families therefore never edits the same registry file. To add a family, create
`rdna2/<family>.toml` and append it to `include`; the generated order (and so
the generated file) changes only where the new file is placed.
## Encoding variants
An `[[encoding_variant]]` is another encoding of a form that is already declared,
such as the VOP3 (`_e64`) encoding of a VOP2 form. It is pure data in the family
file of its encoding (`rdna2/vop3.toml`) and has exactly these fields:
| Field | Meaning |
| --- | --- |
| `of` | The `name` of the declared base form |
| `family` | The encoding family of this variant; must differ from the form's |
| `opcode` | The XML opcode in that family |
| `operands` | An operand rule of that family whose kind can encode the base form (today `vop3_vgpr2` for VOP2 vector forms) |
| `spec`, `verify` | As for a form |
Everything else (operation, signedness, effects, source order) is inherited
from the base form, and the XML check runs on that inherited declaration with
the variant's family, opcode and operand rule, so the VOP3 operand widths and
formats must agree with it. The generator emits one enum per variant rule (`VectorAluVop3Op` for
`vop3_vgpr2`) holding exactly the declared variants, with `from_word` (encoding
bits, then an explicit match on the OP field), `base()` (the inherited form),
`assembly_name()` and `semantics()`, and one `FORMS` row per variant after the
forms. Because the enum has no undeclared members, an instruction cannot name a
VOP3 encoding that does not exist. Every explicit XML operand of the variant,
destination included, must have the data format of the base operand in the same
role (destination, then the sources in rule order). A variant-only rule says so
in the data (`variant_only = true`), so the RDNA2 planner does not count it as a
rule that can host new forms. A
variant-only rule (one marked `variant_of` in the generator) cannot be used by a
form. The validator rejects a variant of an undeclared form, one in the form's
own family, a duplicate encoding of a form or a duplicate `(family, opcode)`, a
rule that cannot encode the form, missing or unknown fields, and any XML
disagreement.
`vop3_vgpr2` is the subset the decoder accepted for `v_add_nc_u32_e64` before
the registry: VGPR destination, two VGPR sources, ABS, OP_SEL, CLAMP, OMOD and
NEG clear, and SRC2 the assembler's unused inline zero. `v_add_nc_u32_e64` is its
first variant; adding the VOP3 encoding of another VOP2 form under this rule is
one `[[encoding_variant]]` entry. Wider VOP3 operand rules (scalar and inline
sources, legal modifiers) come with the VOP3 batch.
## Fields
The top of the file holds:
The root file holds:
- `schema`: must be `1`.
- `architecture`: must be `"gfx1030"`.
@@ -33,12 +90,13 @@ The top of the file holds:
`guide` (the AMD RDNA 2 ISA reference guide) and `xml` (the AMD
machine-readable ISA) are allowed, and each must match the title and file
pinned in the generator, so a citation cannot point at another file.
- `[operand_rules.<name>]`: an operand rule shared by a whole family. The
decoder implements each rule once, and the generator only accepts a rule
whose declaration matches the decoder's implementation exactly. Today there
is one rule, `sop2_sgpr`: an SGPR destination `s0`-`s105`, two scalar sources
- `[operand_rules.<name>]`: an operand rule of one family, shared by its forms.
The decoder implements each rule once, and the generator only accepts a rule
whose declaration matches the decoder's implementation exactly. A family may
have several rules (VOP2 has `vop2_vgpr` and the VGPR-only `vop2_vgpr2`). For
example `sop2_sgpr` is an SGPR destination `s0`-`s105`, two scalar sources
(an SGPR, an inline integer -16 to 64, or a literal word) and at most one
literal. Its `unsupported` list names the encodings the rule rejects, which
literal. A rule's `unsupported` list names the encodings it rejects, which
stay unsupported instead of being guessed. The list must name exactly the
encodings the decoder rejects.
@@ -51,16 +109,18 @@ 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 |
| `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` |
| `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) |
| `source_order` | Vector forms only: `reversed` when the guide computes `op(S1, S0)` (the XML records no operand order); absent otherwise | `reversed` |
| `shift_amount` | `lshl_add` only: the fixed left shift of S0 before the add | `1` to `4`; required for `lshl_add`, rejected elsewhere |
| `shift_count_bits` | Shifts only: the low bits of the count source used as the count: S1, or S0 for a vector form with `source_order = "reversed"`. Scalar forms mask it in the generated evaluation, vector forms in their MSL template; the XML must list the count source as unsigned | `5` (log2 of `width`); required for shifts, rejected elsewhere |
| `scc` | What the form writes to SCC | `carry_out`, `borrow`, `signed_overflow`, `nonzero`, `relation` (SOPC compares only), `selected_src0` (min and max: S0 won the strict compare, so a tie gives 0), `unchanged` |
| `vcc`, `exec` | Effect on VCC and EXEC, stated rather than implied | `unchanged`; `vcc` is `lane_mask` exactly for the VOPC compares (VCC_LO bit n = EXEC[n] & test, fully written; VCC_HI unknown afterwards, see [vector-compare.md](vector-compare.md)); `exec` must be `unchanged` (no EXEC-writing contract yet) |
| `wave` | Wave sizes the form is valid in | `wave32` exactly for the VOPC compares (their one entry point is the Wave32 compute fixture ABI, vector-compare.md section 2), `any` for everything else; the decoder has no wave-size input, so no other form may claim `wave32` |
| `operands` | Name of an `[operand_rules]` entry for the same family | e.g. `sop2_sgpr` |
| `spec` | References `{ document, section, page }` | at least one `guide` reference with a page above 0 |
| `verify` | Evidence the form needs before it counts as verified | `reference`, `independent`, `metal`, `llvm_encoding` |
@@ -82,9 +142,47 @@ fixes the `scc` value:
| `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 |
A compare must use an operand rule of the compare kind (`sopc_scalar`: two
Vector forms (operand rules `vop2_vgpr` and `vop2_vgpr2`, kind `vector`; both
generate the one `VectorAluOp` enum, whose `operand_rule()` tells the decoder
which rule a form uses) use a separate table:
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` |
| `and`, `or`, `xor` / `bitwise` | `And`, `Or`, `Xor` |
| `lshl`, `lshr` / `bitwise`, `ashr` / `signed` (with `shift_count_bits = 5`) | `ShiftLeft`, `ShiftRight`, `ArithmeticShiftRight` |
`vop2_vgpr2` is the VGPR-only subset (SRC0 256-511) that the hand-written decoder
accepted for `v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`
and `v_ashrrev_i32` before they moved into the registry (#215 M27); widening them
to `vop2_vgpr` would be a behaviour change and needs its own oracle. The three
shifts declare `source_order = "reversed"` (D = S1 shifted by S0[4:0]), so the
generator checks the XML's unsigned count format on SRC0, not VSRC1.
VOPC compares (operand rule `vopc_vcc`, kind `vector_compare`: SRC0 a
`vector_source` as for VOP2, VSRC1 a VGPR, destination implicitly `vcc_lo`)
take the same `relation` and primitive as SOPC compares, but declare
`scc = "unchanged"`, `vcc = "lane_mask"` and `wave = "wave32"`. The XML's implicit
64-bit VCC output must be present and is accounted for by `lane_mask`. Signedness
still matters for `eq` and `lg`, because the MSL lowering casts signed operands.
`v_cmpx_*` (EXEC writes), the VOP3 encoding and Wave64 stay unsupported.
A SOPC compare must use an operand rule of the compare kind (`sopc_scalar`: two
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`.
@@ -98,12 +196,17 @@ 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;
- VOPC compares whose opcode is not the group base (128 for `signed`, 192
for `unsigned`) plus the relation's offset in guide Table 59 (F 0, LT 1,
EQ 2, LE 3, GT 4, LG/NE 5, GE 6, T 7), and a `lane_mask` form whose XML
does not have exactly one implicit VCC operand that is written and not read;
- 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;
+61 -9
View File
@@ -53,8 +53,13 @@ The 32-bit VOPC encoding (bits 31:25 = 0b0111110), no SDWA or DPP:
| v_cmp_gt_i32 / v_cmp_gt_u32 | S0 > S1 |
| v_cmp_ne_i32 / v_cmp_ne_u32 | S0 != S1 |
| v_cmp_ge_i32 / v_cmp_ge_u32 | S0 >= S1 |
| v_cmp_f_i32 / v_cmp_f_u32 | false (Table 59 offset 0) |
| v_cmp_t_i32 / v_cmp_t_u32 | true (offset 7) |
`_i32` compares the 32-bit two's-complement values, `_u32` the unsigned values.
The forms are declared in the semantic registry
(`crates/isa/semantics/rdna2/vopc.toml`, operand rule `vopc_vcc`); the decoder
dispatches them from the generated `VectorCompareOp`.
Operand order matters (S0 is SRC0): lt with swapped operands is gt.
SRC0 selectors, exhaustively: 0-105 (normal SGPR), 106 (VCC_LO, see 5),
@@ -70,6 +75,29 @@ stream carries no wave-size declaration (the VOPC word has no wave-size field),
so every caller of the translator and the reference establishes Wave32 by
using this ABI; there is no Wave64 entry point to reject.
### 2a. 16-bit and 64-bit compares (reference interpreters only)
The reference (`crates/ref`) and the second interpreter
(`tests/validation/independent_ref.rs`) also accept the `_e32` forms
`v_cmp_{lt,eq,le,gt,ne,ge}_{i16,u16}` (opcodes 137-142, 169-174) and
`v_cmp_{f,lt,eq,le,gt,ne,ge,t}_{i64,u64}` (160-167, 224-231). The decoder and
the translator still reject them (section 4); these forms have an oracle
but no translation yet.
- 16-bit forms read bits 15:0 of each 32-bit source and ignore bits 31:16
(an inference from guide 6.2, 6.2.5 and 6.8: only SDWA selects a half).
There is no literal source.
- 64-bit forms read a pair: v[n:n+1] with n <= 254, an even-aligned
s[2k:2k+1] with k <= 52 (3.6.3), or an inline integer, which is
sign-extended to 64 bits (-1 is all ones, also for `_u64`; a reading of
Table 20). VSRC1 is v[m:m+1] with m <= 254. Literals and VCC as a 64-bit
source are rejected.
- The result, EXEC masking, VCCZ and the empty-EXEC rule are those of
sections 3 and 5.
The expectations and the guide readings are in
`tests/validation/tests/vopc_wide.rs`.
## 3. Semantics of one supported compare, Wave32
Let E = EXEC_LO before the instruction and A = the set of lanes that exist in
@@ -95,7 +123,9 @@ this wave (all 32 except in a final partial wave, see 7). As an unsigned
- V_CMPX_* (writes EXEC: divergent execution; needs its own contract).
- The VOP3 encoding of any compare (arbitrary SGPR destination, modifiers).
- SDWA and DPP forms; F/T, 16-bit, 64-bit and float compares; v_cmp_class.
- SDWA and DPP forms; float compares; v_cmp_class.
- 16-bit and 64-bit compares in the decoder and translator (the reference
interpreters accept the subset in 2a).
- SRC0 inline float constants (240-248), SGPRs other than s0-s106, TTMPs,
M0, EXEC_LO/HI, VCC_HI, SCC/VCCZ/EXECZ selectors, LDS direct.
- A normal-SGPR SRC0 without a known value, when EXEC_LO != 0.
@@ -127,8 +157,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
@@ -191,7 +224,7 @@ instructions are pure 32-bit ALU and are evaluated unconditionally.
## 9. Verification
`fixtures/rdna2/vector-compare.s` is an original program, assembled by LLVM.
It uses all twelve forms with VGPR, SGPR, inline, literal and `vcc_lo`
It uses the twelve relational forms with VGPR, SGPR, inline, literal and `vcc_lo`
sources, a compare and a mask move under partial EXEC, a compare under empty
EXEC that must clear a stale VCC, SCC kept across compares, and a runtime
`s_cbranch_vccz`. Its expected output is written in
@@ -199,7 +232,13 @@ EXEC that must clear a stale VCC, SCC kept across compares, and a runtime
relation for each row. The test input has a wave whose branch is taken, one
whose branch is not, and a final partial wave of 9 lanes.
The same file runs each form against 10 boundary values (0, 1, 0x7ffffffe,
`fixtures/rdna2/vector-compare-ft.s` does the same for the four F and T
forms: an F that clears a stale VCC, T and F under partial EXEC, a T reading
`vcc_lo`, and runtime `s_cbranch_vccz` on a T result (never taken) and an F
result (always taken). The independent oracle for F and T is
`tests/validation/tests/vopc_f_t.rs`.
`tests/validation/known_answers.rs` runs each relational form against 10 boundary values (0, 1, 0x7ffffffe,
0x7fffffff, 0x80000000, 0x80000001, 0xfffffff0, 0xfffffffe, 0xffffffff,
0x0f0f0f0f), in both operand orders. That is 240 programs, checked against
exact i128 differences. It also covers partial and empty EXEC with seeded
@@ -207,11 +246,22 @@ destinations, both runtime branch edges in one dispatch, and 32 rejections
pinned to their byte offset. The translator, the reference (lockstep waves,
compares on widened i64 values) and the second interpreter (sign-bit flip,
then an unsigned compare) must all agree. The 9 ordered compare slots in the
fixture each change the result when their signedness is flipped. The same
programs, plus 2 mask-chain programs (252 in all), match on native Metal with API and shader validation
(`vector_compare_native_metal_known_answers`, run by `scripts/test-gpu.sh`).
relational fixture each change the result when their signedness is flipped. The same
programs, plus 2 mask-chain programs (252 in all), and the F/T fixture (253) match on native Metal with API and shader validation
(`vector_compare_native_metal_known_answers`, run by `scripts/test-gpu.sh`). The F/T oracle's own native Metal cases
run in `vopc_f_t_match_the_guide_on_native_metal`.
A deliberately broken copy of each implementation fails these tests: the
The 16-bit and 64-bit oracle (`tests/validation/tests/vopc_wide.rs`) checks
6,212 lane cases on both reference interpreters, plus 1,208 rejections and the
13 neighbouring opcodes, and that the production compiler still rejects all 28
forms. Its native Metal test stays ignored (and skipped by `scripts/test-gpu.sh`)
until the translator implements these forms. Deliberately broken copies of both
interpreters (16-bit reads of 32 bits, swapped pair halves, zero-extended
inline integers, flipped signedness, reads under empty EXEC and others) each
fail it.
For the 32-bit forms, a deliberately broken copy of each implementation fails
the tests above: the
reference with unsigned-only compares or with the EXEC test removed; the
second interpreter with unsigned-only compares or with no empty-EXEC rule;
the translator with a stale VCC under empty EXEC (CPU), and, on Metal, with
@@ -223,7 +273,9 @@ locally on Apple M5 Pro. It is not agreement with RDNA 2 or Xbox hardware.
## 10. Limitations
- Wave32 only. No `v_cmpx`, VOP3, SDWA, DPP, 16-bit, 64-bit or float compares.
- Wave32 only. No `v_cmpx`, VOP3, SDWA, DPP or float compares. 16-bit and
64-bit compares exist only in the reference interpreters (2a); native Metal
agreement for them is not shown.
- A lane-derived VCC_LO cannot reach EXEC or any scalar instruction, so there
is no divergent execution. That needs its own contract.
- The skipped region of a runtime `s_cbranch_vccz` holds only integer vector
+384
View File
@@ -615,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"
@@ -758,6 +950,54 @@ gpu = "local Apple M5 readback passed; acceptance pending"
recognized = true
decoded = true
llvm = "three-way passed"
[[instruction]]
form = "v_cmp_f_i32_e32"
encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0 (signed); VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & false, fully written"
representation = "`7D000501`"
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select"
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_t_i32_e32"
encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0 (signed); VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & true, fully written"
representation = "`7D0E0501`"
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select"
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_f_u32_e32"
encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0 (unsigned); VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & false, fully written"
representation = "`7D800501`"
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select"
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_t_u32_e32"
encoding = "VOPC, Wave32; VGPR, normal SGPR (known during translation), vcc_lo, inline integer or literal SRC0 (unsigned); VGPR VSRC1; VCC_LO[n] = EXEC_LO[n] & true, fully written"
representation = "`7D8E0501`"
lowering = "per-thread Wave32 mask over the dispatch's own 32 lanes, reading no operand bits; runtime s_cbranch_vccz as a join select"
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_cbranch_scc0"
encoding = "Nonnegative signed dword displacement"
@@ -902,6 +1142,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"
+58
View File
@@ -0,0 +1,58 @@
# 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 cpu-inventory --compact
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.
## Phase III — compatibility intelligence
Checkpoint ledger: [phase3-compat-ledger.md](phase3-compat-ledger.md).
`cpu-inventory` consumes the x86 instruction registry (not heuristic opcode scans).
Declared forms are decodable only; native vs shared-semantic partitions come from
read-only `dbt.rs` analysis. Unsupported intentional rejections stay in a separate catalog.
@@ -0,0 +1,20 @@
# Phase III compatibility-intelligence checkpoint ledger
Branch: `feat/infra-phase3-compat`. Issue #277.
Approved paths only. No push without separate authorization.
| Milestone | Status | Commit | Tests | Next |
| --- | --- | --- | --- | --- |
| M1 CPU inventory | done | `b2a36e9` | test_cpu_inventory 5 OK; cpu-inventory compact | M2 runtime inventory |
| M2 Runtime intelligence | done | `da92995` | test_runtime_inventory 2 OK; runtime-inventory compact | M3 compat gaps |
| M3 Compat gaps | pending | — | — | — |
| M4 Performance intel | pending | — | — | — |
| M5 Regression detection | pending | — | — | — |
| M6 Task planning | pending | — | — | — |
| M7 Unified diagnostics | pending | — | — | — |
| M8 Verify profiles | pending | — | — | — |
## Notes
- Do not inflate coverage. Declared ≠ implemented.
- Prefer focused `tests/qa` unit tests between milestones.
Binary file not shown.
+49
View File
@@ -0,0 +1,49 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Generate the clean-room binary asset fixture for Gate 6 VFS testing."""
import argparse
import math
from pathlib import Path
from struct import pack
def generate_asset():
data = bytearray()
# 1. Header: Magic 'XAST' (4B), version 1 (4B), width 2 (4B), height 2 (4B), audio_samples 256 (4B)
data += b"XAST"
data += pack("<IIII", 1, 2, 2, 256)
# 2. Texture data: 2x2 RGBA8 (16 bytes)
# (0,0): Orange [255, 128, 0, 255]
# (1,0): Purple [128, 0, 255, 255]
# (0,1): Teal [0, 255, 128, 255]
# (1,1): Pink [255, 0, 128, 255]
texture_bytes = bytes([
255, 128, 0, 255,
128, 0, 255, 255,
0, 255, 128, 255,
255, 0, 128, 255,
])
data += texture_bytes
# 3. Audio data: 256 samples of 440Hz sine wave (16-bit signed PCM mono, 512 bytes)
sample_rate = 48000
freq = 440.0
for i in range(256):
sample_val = int(32767.0 * 0.5 * math.sin(2.0 * math.pi * freq * (i / sample_rate)))
data += pack("<h", sample_val)
return bytes(data)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--check", action="store_true")
args = parser.parse_args()
path = Path(__file__).parent / "asset.bin"
expected = generate_asset()
if args.check:
if not path.exists() or path.read_bytes() != expected:
parser.exit(1, f"asset binary differs from generator: {path}\n")
else:
path.write_bytes(expected)
+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
Loaded 100 of 187 files, more files were not shown because too many files have changed in this diff. Show more