Compare commits

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

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

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

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

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

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

Closes #62

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Refs #157

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

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

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

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

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 02:46:58 -06:00
Ranveer Soni 077a215d49 Merge pull request #243 from elforeign/task/138-threadgroup-sizing
metal: measure threadgroup sizing; keep the 64-thread default (#138)
2026-11-24 14:08:26 +05:30
Ranveer Soni 3c710b53ba Merge pull request #242 from atesahmet0/task/200-indirect-control
Verify indirect CALL and JMP target fetch, stack and retirement
2026-11-24 14:06:31 +05:30
Ranveer Soni 4886e9cd80 Merge pull request #241 from atesahmet0/task/86-precise-faults
Preserve precise guest fault state and retired instructions
2026-11-24 14:06:25 +05:30
ates 7aa8166cf2 Verify indirect CALL and JMP target fetch, stack and retirement
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-24 11:30:08 +03:00
ates c107f3a43f Preserve precise guest fault state and retired instructions
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-24 11:30:08 +03:00
244 changed files with 61465 additions and 3071 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
+6
View File
@@ -38,6 +38,8 @@ jobs:
- name: Check generated status and PE fixtures
run: |
python3 crates/isa/generate_rdna2_meta.py --check
python3 crates/isa/generate_semantics.py --check
python3 scripts/audit/semantic_coverage.py --check
python3 scripts/audit/status.py --check
for fixture in x2 x3 x4; do
python3 "experiments/x1/fixtures/$fixture.py" --check || exit 1
@@ -48,6 +50,10 @@ jobs:
sh -n scripts/agent-queue.sh scripts/agent-sync.sh
- name: Test pull request template check
run: PYTHONPATH=scripts python3 -m unittest discover -s tests/pr_template
- name: Test semantic registry generator and coverage report
run: |
python3 -m unittest discover -s tests/semantics_generator
PYTHONPATH=scripts python3 -m unittest discover -s tests/semantic_coverage
- name: Check formatting and lint
run: |
cargo fmt --all -- --check
+3
View File
@@ -37,3 +37,6 @@ __pycache__/
*.pyc
/diagnostics/gta6-candidate-*/
/diagnostics/gta6-check/
# Native application build output
/app/.build/
+52 -1
View File
@@ -9,8 +9,48 @@ exact revision and known limitations.
Guest execution uses original, purpose-built test programs. Commercial Xbox game execution
remains unsupported.
### Added
### Changed
- 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 `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 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.
- Added the gfx1030 SOPC compares `s_cmp_{eq,lg,gt,ge,lt,le}_{i32,u32}` through the semantic registry, which replaces the hand-written `s_cmp_eq_u32` path. Each sets only SCC to whether the relation holds with SSRC0 on the left (AMD guide section 12.4); the registry gained a `compare` operation with a declared `relation` and a `sopc_scalar` operand rule. `Instruction::ScalarCompareEqU32` is now `Instruction::ScalarCompare { op: ScalarCompareOp, .. }`; `s_cmp_eq_u32` behaves as before. The reference and independent semantic-review interpreters, written separately from the guide, evaluate all twelve, checked against 7,824 guide-derived cases on both CPU interpreters and on native Metal with validation; 348 rejected programs are refused by both interpreters and by the compiler. A new LLVM-assembled fixture covers all twelve. Two literal selectors stay rejected. Part of #215, stage D.
- Added eight gfx1030 SOP2 forms through the semantic registry alone: `s_andn2_b32`, `s_orn2_b32`, `s_nand_b32`, `s_nor_b32`, `s_xnor_b32`, `s_lshl_b32`, `s_lshr_b32` and `s_ashr_i32`, each with SCC = result != 0. Each is one registry entry with no per-form Rust; the registry gained these primitives and a declared shift-count width (`shift_count_bits = 5`, so shifts use S1[4:0] as in the AMD guide, section 12.1), which the generator applies as a mask and checks against the XML's unsigned count operand. The reference interpreter and the independent semantic-review interpreter, written separately from the guide, now evaluate the same eight forms and are checked against 6,896 guide-derived cases; a new LLVM-assembled fixture (`fixtures/rdna2/scalar-logic.s`) runs on CPU and native Metal with validation. A NULL destination (s125) stays rejected. Part of #215, stage C.
- Added an independent operand-domain verification harness for the 9 supported SOP2 scalar ALU forms and 12 VOPC integer compares (`tests/validation/tests/operand_domains.rs`, part of #215 stage E): 4,788 generated cases (boundary values, 64-bit carry and borrow chains, aliased registers, every integer inline constant, literals, s105 and v255, partial and zero EXEC, VCCZ) and 498 rejections (missing literal words, and encodings outside Xenora's supported subset) run on `xenora_ref` and, as an ignored test picked up by `scripts/test-gpu.sh`, on native Metal. Expected values come from the public AMD RDNA 2 guide's pseudocode, written out in the test without Xenora code; this is agreement with a spec-derived reference, not with Xbox hardware. Local verification only: 32 deliberate code breaks were each caught; the guide leaves the width of `S1 + SCC` in `s_subb_u32` open, and those 8 cases are kept in their own family.
- Added a declarative semantic registry for gfx1030 instruction forms (`crates/isa/semantics/rdna2.toml`, schema 1) and its generator, `crates/isa/generate_semantics.py`, with `validate`, `generate` and `--check` modes. The generator checks every declaration against a closed vocabulary and the pinned AMD XML snapshot (opcode, family, SCC input and output, operand widths and signed formats), rejects contradictory, incomplete or duplicate definitions, and emits static Rust tables marked as generated. The nine SOP2 forms moved onto it with no change in behaviour: the decoder's SOP2 dispatch and `ScalarAluOp`'s mnemonic, SCC read and evaluation are now generated, and evaluation goes through shared primitives instead of per-opcode code. All existing SOP2 tests, including the native Metal known answers and the LLVM comparison, pass unchanged. Decoding speed is unchanged (10.2 ns before, 10.1 ns after, per SOP2 instruction, release build on an Apple M5 Pro). Also added `scripts/audit/semantic_coverage.py`, which generates `docs/shaders/semantic-coverage.md`: per-family counts of identified, declared, decoded, lowered, reference-verified and Metal-verified forms, taking evidence only from `docs/status.toml`. Part of #215, stages A and B.
- Added a native Metal blend pass, `NativeCompute::render_blend`: up to 16 flat-coloured triangles drawn in order into an RGBA8 target, each with its own colour write mask (any subset of R, G, B, A) and either blending disabled or separate RGB and alpha blend factors (Zero, One, source and destination colour and alpha, and their one-minus forms) and operations (Add, Subtract, ReverseSubtract, and Min and Max, which take the unweighted values). Checked on the GPU with Metal validation in 39 passes over two original overlapping triangles: a clear-only pass; blending disabled; each source factor with the destination term zeroed and each destination factor with the source term zeroed; every operation; additive clamping; separate alpha factors; a separate alpha operation; eight write masks (each channel alone, RGB, none, RGBA, and RG with blending); and a pass whose first draw is itself blended and masked. Colours are compared per channel against images derived independently (in exact fractions) from the public Metal blend equations, which a new CPU reference in `xenora-ref` also reproduces. The tolerance was fixed before measuring: channels whose exact result is a whole 8-bit value must match exactly, and channels that need rounding may differ by 1. On an Apple M5 Pro every rounded channel matched round-to-nearest exactly. Synthetic fixtures only; no console blend state is involved.
- Added indexed triangle draws. Native Metal: `NativeCompute::render_indexed` issues one real `drawIndexedPrimitives` call per draw (up to 16) on a 16- or 32-bit index buffer with a start index and a signed base vertex, into an RGBA8 target; a draw can sample an original BC1 texture uploaded natively. Before encoding anything it rejects the whole pass for a bad index count, an index range past the buffer, any `index + base vertex` outside the vertex buffer, and, as this API's policy, a raw all-ones index (the primitive-restart value, which Metal does not define for triangle lists). Loader: a synthetic, CPU-side index buffer binding (resource handle and offset, the view running to the end of the resource) with `cmd_set_index_buffer` and `cmd_draw_indexed_instanced`, which fetch one triangle, drawn once, through the index buffer, start index and base vertex and pass it to the existing one-triangle backend; each drawn triangle replaces the previous output. Recording rejects formats other than DXGI `R16_UINT` and `R32_UINT`, offsets not aligned to the index size or past the resource, and unknown resources. Execution checks each draw in turn, so earlier draws have already rendered when a later one fails: index counts other than 0 or 3, more than one instance or a nonzero start instance, a missing index buffer, indices past the buffer and an `index + base vertex` outside the vertex buffer are typed errors; a valid zero index or instance count draws nothing. All-ones indices are ordinary indices there. Checked on the GPU with Metal validation in 16 passes (both index sizes, 32-bit indices above 16 bits, odd 16-bit start, positive and negative base vertex, reversed winding, flat and textured two-triangle draws, draw order, BC1-textured draws), compared per pixel against images derived independently from the geometry, the public D3D12 and Metal index semantics and the public BC1 rules, which a new CPU reference in `xenora-ref` also reproduces; the loader's fetch is checked against literal positions with synthetic guest-backed buffers and through the native Metal renderer. Synthetic fixtures only; no console index-buffer views, guest programs or console draw state are involved.
- Added a `cpu_decode` cargo-fuzz target for the static x86-64 decoder used by the read-only PE probe. It places up to 4,096 fuzz bytes as the code section of a fixed, original PE32+ header and runs `probe_pe_bytes` twice with a bounded `ProbeConfig` (4,096 bytes, 2,048 instructions, 1,024 worklist entries); nothing is executed. It checks that the two reports are identical and that every decoded instruction is 1 to 15 bytes long, lies inside the code and matches the input bytes. A startup self-check aborts the run if the synthetic header stops reaching the decoder. A 600-second local campaign (nightly cargo-fuzz, one fork-mode worker, seeded from instruction bytes in the loader's probe tests; about 2.38 million executions, coverage 1,350 edges) found one decoder defect, reported to the CPU owner on #74 and not fixed here: the probe accepts unlimited FS/GS segment prefixes and reports instructions longer than 15 bytes (minimized input: 16 bytes of `0x65`). Run it with `rustup run nightly cargo fuzz run cpu_decode`; `scripts/fuzz.sh` does not list it yet.
- Added a `pe_parse` cargo-fuzz target that feeds malformed bytes to the PE32+ parser (`ParsedPe::parse`, `rva_to_file_offset`) and, only when the summed section mapping size and `SizeOfImage` are both at most 64 MiB, to the checked guest-memory mapping step (`load_into_memory`); nothing is executed. A 600-second local campaign (nightly cargo-fuzz, fork mode, seeded from the repository's synthetic PE fixtures, about 120,000 executions, coverage 267 edges) found two loader panics, reported to the CPU owner and not fixed here: truncated optional headers panic on out-of-range slices in `parse`, and `rva_to_file_offset` overflows `u32` when a section's address plus size exceeds 4 GiB. Run it with `rustup run nightly cargo fuzz run pe_parse`; `scripts/fuzz.sh` does not list it yet.
- Added `NativeCompute::run_words_with_group_width` and `max_group_width` to run a trusted kernel at an explicit threadgroup width, rejecting zero and widths above the device or pipeline limit. Native tests check 91 legal width and grid-size pairs (widths 1 to 1,024, including non-divisible grids) against independently computed outputs, and confirm the dispatched group sizes, including trimmed last groups. On an Apple M5 Pro, in three release runs of a 4,096-thread integer-mixing kernel (30 samples per width), widths 64, 128 and 256 were within 0.3 % of each other in two runs, at a median of 58.8 µs of GPU time. Width 512 was 5 to 6 % slower and width 1,024 about twice as slow in all three runs. The first run was about 4.7 times slower overall for reasons not determined, and in it 128 and 256 were 3 to 4 % faster than 64. The default width of 64 is unchanged. This was measured on one device and one workload.
- Added a native Metal depth pass, `NativeCompute::render_depth`: up to 16 triangles drawn in order into an RGBA8 target with an optional `Depth32Float` attachment, a chosen clear depth, a per-draw depth compare function (all eight) and depth write enable. A pass without an attachment accepts only `DepthState::DISABLED`. Colour and the stored depth are both read back; the depth values are returned as the texture read gives them, without numeric conversion. A draw can sample an original BC1 texture whose blocks are uploaded to a native `BC1_RGBA` texture without CPU decoding, gated on `supportsBCTextureCompression`. Checked on the GPU with Metal validation in 30 passes of original overlapping triangles: clear, every compare function at three depths, write enabled and disabled, depth test disabled (`Always` without writes) with an attachment and no attachment at all, and a BC1-textured draw. Colour and depth are compared per pixel against expectations derived independently from the geometry, the Metal compare semantics and the public BC1 rules, which a new CPU reference in `xenora-ref` also reproduces. These are synthetic fixtures only; no console depth formats or guest render state are involved.
- Added a CPU BC7 block decoder in `xenora-texture` for all eight modes, with explicit handling of the invalid all-zero mode byte. It is checked by hand-derived tests and 430 known-answer vectors from a separate clean-room reference written from the Khronos Data Format Specification (merged in PR #224 without a changelog entry).
@@ -63,12 +103,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],
Generated
+9
View File
@@ -179,6 +179,15 @@ dependencies = [
"xenora-ref",
]
[[package]]
name = "xenora-ffi"
version = "0.1.0"
dependencies = [
"xenora-loader",
"xenora-metal",
"xenora-shader",
]
[[package]]
name = "xenora-import-gen"
version = "0.1.0"
+51 -14
View File
@@ -2,13 +2,17 @@
**Experimental Xbox Series X|S emulation research for Apple Silicon Macs.**
Xenora is an open-source project written primarily in Rust, exploring native Xbox Series X|S compatibility on ARM64 macOS.
The project combines a bounded x86-64 guest execution environment, Portable Executable (PE32+) loading, AMD RDNA 2 shader translation, and a native Apple Metal graphics backend.
Xenora is an open-source project written primarily in Rust that builds and verifies a native, bounded execution environment on Apple Silicon: an independent x86-64 guest path, original PE32+ loading, AMD RDNA 2 shader translation, and a native Apple Metal graphics backend.
**No Wine. No CrossOver. No Rosetta. No Vulkan runtime.**
Xenora is still experimental. It currently executes independently authored synthetic guest programs and shaders. **Commercial Xbox games, including Grand Theft Auto VI, do not boot.** Authentic Xbox executable loading and system-service compatibility remain unsupported.
Xenora is still experimental. Verified work is restricted to independently authored synthetic programs and shaders; authentic Xbox executable loading, system-service compatibility and commercial game execution remain unsupported. See the [current limitations](#current-limitations).
### At a glance
- **Native graphics:** translated gfx1030 vertex and pixel stages and native passes (indexed draws, blend, depth) run on Apple Silicon GPUs — verified, see [Blend pass](#blend-pass) and [Verified Apple M5 results](#verified-apple-m5-results).
- **Guest execution:** bounded x86-64 execution, original PE32+ loading, synthetic services and guest-driven GPU dispatch — verified milestones X1–X9.
- **Not supported:** authentic Xbox executable loading and commercial game execution; see the [milestone table](#development-milestones).
[![Native Rust checks](https://github.com/ranveersoni98/Xenora/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/ranveersoni98/Xenora/actions/workflows/ci.yml)
@@ -18,7 +22,7 @@ Xenora is still experimental. It currently executes independently authored synth
Xenora has progressed from executing individual x86-64 instructions to running original PE32+ guest programs that interact with translated GPU workloads on Apple Silicon.
The latest verified milestone includes **translated gfx1030 vertex and pixel shaders executing through native Apple Metal**, with rendered pixels compared against independently calculated reference results.
The latest verified milestones include **translated gfx1030 vertex and pixel shaders executing through native Apple Metal**, the native Metal **blend pass** (`NativeCompute::render_blend`) and **indexed triangle draws** (`NativeCompute::render_indexed`) into offscreen targets, with rendered pixels compared against independently calculated reference results.
### Development milestones
@@ -33,14 +37,14 @@ The latest verified milestone includes **translated gfx1030 vertex and pixel sha
| X7 — Imported services | Named imports, guest-to-host service dispatch and result validation | Verified |
| X8 — Translated compute | Original gfx1030 compute shaders executing on Metal, partial Wave32 handling and BC1 readback | Verified subset |
| X9 — Translated graphics | Persistent resource handles, translated vertex/pixel stages and offscreen Metal rendering | Verified subset |
| X10 — Texture sampling | Translate RDNA2 image instructions, implement samplers, mipmapping and guest-backed texture bindings | Planned |
| X11 — Graphics pipeline | Multiple draw calls, vertex buffers, index buffers, depth/stencil testing, blending and render targets | Planned |
| X10 — Texture sampling | Translated image instructions are still planned; upload, readback and decode of BC compressed formats is implemented (see [Texture support](#texture-support)) | Planned |
| X11 — Graphics pipeline | Bounded multi-draw passes into offscreen RGBA8 targets: translated vertex and pixel stages, indexed triangle draws, colour write masks and blend state | Implemented |
| X12 — Wave execution | Expand Wave32/Wave64 semantics, divergent control flow, cross-lane operations, LDS and barriers | Planned |
| X13 — Advanced shaders | Mesh, geometry and additional compute shader capabilities with verified Metal execution | Planned |
| X14 — CPU recompilation | Native ARM64 dynamic recompilation of supported x86-64 instructions in synthetic fixtures | Implemented subset |
| X15 — Executable compatibility | Static PE inspection reports sections, relocations, thread-local storage (TLS) callbacks, imports and entry-point instructions | Static probe implemented |
| X16 — Guest memory and threading | Virtual memory mapping, thread scheduling, synchronization primitives and atomic operations | Implemented subset |
| X17 — System services | Implement a tested subset of Xbox-compatible runtime APIs, memory services, filesystem access and application lifecycle | Implemented subet |
| X17 — System services | Implement a tested subset of Xbox-compatible runtime APIs, memory services, filesystem access and application lifecycle | Implemented subset |
| X18 — Graphics API translation | Translate supported Xbox graphics commands, resource descriptors, command queues, barriers and fences into Metal operations | Planned |
| X19 — Advanced GPU features | Indirect rendering, asynchronous compute, additional texture formats and ray-tracing compatibility research | Planned |
| X20 — Integrated guest runtime | Connect CPU recompilation, executable loading, system services and graphics translation into one persistent runtime | Planned |
@@ -97,14 +101,35 @@ The current graphics subset supports:
- Offscreen RGBA8 render targets.
- Native GPU readback and pixel-by-pixel validation.
- Explicit rejection of unsupported shader forms.
- Flat-coloured triangle draws with colour write masks and blending (see [Blend pass](#blend-pass)).
- Indexed triangle draws (see [Indexed draws](#indexed-draws)).
- Depth testing with an optional `Depth32Float` attachment (see [Depth pass](#depth-pass)).
These are genuine translated shader stages, not merely demonstrations using handwritten Metal vertex and fragment programs.
The current rendering tests are deliberately narrow: original fixtures, a single triangle per draw, and controlled shader inputs and outputs.
### Blend pass
`NativeCompute::render_blend` draws up to 16 flat-coloured triangles in order into an offscreen RGBA8 target. Each draw has its own colour write mask (any subset of R, G, B, A) and either blending disabled or separate RGB and alpha blend factors (Zero, One, source and destination colour and alpha, and their one-minus forms) and operations (Add, Subtract, ReverseSubtract, and Min and Max). Colours are compared per channel against images derived independently (in exact fractions) from the public Metal blend equations.
GPU verification (Metal API and shader validation enabled): 39 Metal-validated passes over two original overlapping triangles — a clear-only pass; blending disabled; each source factor with the destination term zeroed and each destination factor with the source term zeroed; every operation; additive clamping; separate alpha factors; a separate alpha operation; eight write masks; and a pass whose first draw is itself blended and masked. On an Apple M5 Pro every rounded channel matched round-to-nearest exactly.
### Indexed draws
`NativeCompute::render_indexed` issues one real `drawIndexedPrimitives` call per draw (up to 16) on a 16- or 32-bit index buffer with a start index and a signed base vertex, into an offscreen RGBA8 target. A draw can sample an original BC1 texture uploaded natively.
GPU verification (Metal API and shader validation enabled): 16 Metal-validated passes (both index sizes, 32-bit indices above 16 bits, odd 16-bit start, positive and negative base vertex, reversed winding, flat and textured two-triangle draws, draw order, BC1-textured draws), compared per pixel against images derived independently from the geometry, the public D3D12 and Metal index semantics and the public BC1 rules.
### Depth pass
`NativeCompute::render_depth` draws up to 16 triangles in order into an offscreen RGBA8 target with an optional `Depth32Float` attachment, a chosen clear depth, a per-draw depth compare function (all eight) and depth write enable. Colour and the stored depth are both read back.
GPU verification (Metal API and shader validation enabled): 30 Metal-validated passes of original overlapping triangles: clear, every compare function at three depths, write enabled and disabled, depth test disabled with an attachment and no attachment at all, and a BC1-textured draw.
### Verified Apple M5 results
The X9 native Metal acceptance run reported **20 passing tests, zero failures and zero ignored tests**, with Metal API and GPU validation enabled.
The X9 native Metal acceptance run reported **20 passing tests, zero failures and zero ignored tests**, with Metal API and GPU validation enabled. The newer passes below are separate Metal-validated campaigns, also with Metal API and shader validation enabled.
Representative checks include:
@@ -115,6 +140,9 @@ Representative checks include:
| Perspective interpolation | Exact checks of 16 pixels and another 16 after swapping vertex color channels |
| BC1 texture handling | 33 texels across selected mip levels and array layers |
| Guest rendering | PE32+ guest receives and checks the translated render output |
| Blend pass | 39 Metal-validated passes over two overlapping triangles |
| Indexed draws | 16 Metal-validated passes (both index sizes, signed base vertices, draw order) |
| Depth pass | 30 Metal-validated passes (all eight compare functions, no-attachment case) |
The expected results were calculated independently of the production shader translation path.
@@ -141,20 +169,20 @@ The resource system remains experimental. Native GPU work already in flight duri
## Texture support
Xenora includes an original BC1 texture-processing path.
Xenora includes original texture upload, readback and block-compression paths.
Implemented and tested functionality includes:
- Validated mip levels and array layers.
- Pitched texture uploads.
- Block-compressed texture handling.
- Block-compressed texture handling, including BC4/BC5 upload and readback and a CPU BC7 decoder for the eight modes.
- Native Metal texture readback.
- Edge-block and transparency tests.
- Invalid descriptor and bounds rejection.
**Translated texture-sampling instructions are not yet implemented.**
The existing texture readback path uses an authored Metal kernel. It should not be confused with executing arbitrary RDNA2 texture-fetch instructions.
The existing texture readback path uses authored Metal kernels. It should not be confused with executing arbitrary RDNA2 texture-fetch instructions.
Xbox-specific texture layouts and additional compression formats require further research and validation.
@@ -209,6 +237,8 @@ flowchart TD
Xenora's host execution environment is native ARM64. The guest architecture being interpreted is x86-64.
The native graphics pipeline runs translated vertex and pixel stages, the indexed-draw and blend passes and the depth pass into offscreen Metal targets, with GPU readback compared against independent CPU references.
The project does not currently provide a general-purpose x86-64 dynamic recompiler or a complete Xbox operating-system implementation.
See [Interface Contracts](docs/interfaces.md) for the documented execution and resource boundaries.
@@ -227,8 +257,8 @@ The following remain unsupported or incomplete:
| Executable loader | General relocations, TLS, DLL initialization and authentic Xbox startup |
| Xbox runtime | Console-specific services, system APIs, filesystem and application lifecycle |
| RDNA2 shaders | General control flow, broader instructions, Wave64, cross-lane operations and mesh stages |
| Graphics | Translated texture sampling, broader resource binding, synchronization and general draw workloads |
| Textures | Authentic Xbox memory layouts and broader compressed-format support |
| Graphics | Translated texture sampling and broader resource binding |
| Textures | Authentic Xbox memory layouts and translated sampling |
| Performance | Production-scale workloads, CPU/GPU profiling and optimized execution |
| Game compatibility | No demonstrated execution of commercial Xbox titles |
@@ -272,6 +302,10 @@ cargo clippy --locked --workspace --all-targets -- -D warnings
cargo test --locked --workspace
```
The format, lint and test trio is the standard check set. The native Metal
passes use Metal API and shader validation; `scripts/audit/status.py --check`
verifies the generated status tables.
### Run native Metal tests
These require a Metal-capable Apple Silicon Mac.
@@ -320,6 +354,9 @@ Testing distinguishes between:
Compiling a shader is not equivalent to proving its GPU output is correct.
### Where the work is heading
See the [roadmap table](#development-milestones) for proposed milestones, and the [changelog](CHANGELOG.md) for the current unreleased additions, such as the native blend pass, indexed draws and the depth pass. The remaining research steps are the outstanding items in [current limitations](#current-limitations).
---
+13
View File
@@ -0,0 +1,13 @@
// swift-tools-version: 6.0
// SPDX-License-Identifier: GPL-3.0-or-later
// Build with scripts/build-app.sh, which builds the Rust static library first.
import PackageDescription
let package = Package(
name: "Xenora",
platforms: [.macOS(.v14)],
targets: [
.systemLibrary(name: "CXenora", path: "Sources/CXenora"),
.executableTarget(name: "Xenora", dependencies: ["CXenora"]),
]
)
+5
View File
@@ -0,0 +1,5 @@
module CXenora [system] {
header "../../../crates/ffi/include/xenora.h"
link "xenora_ffi"
export *
}
+679
View File
@@ -0,0 +1,679 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//
// Native shell over the versioned C interface. "Run trusted fixture" executes the
// bundled trusted PE fixture (x86-64 translated to ARM64; its draw request is rendered
// by native Metal) and shows the verified read-back frame. No other executable can run.
import AppKit
import CXenora
import Foundation
import SwiftUI
import UniformTypeIdentifiers
struct RuntimeProbe {
var abiVersion: UInt32 = 0
var status: Int32 = -1
var sections: UInt32 = 0
var entryRVA: UInt32 = 0
var connected: Bool { abiVersion == XENORA_ABI_VERSION && status == XENORA_OK }
static func run() -> RuntimeProbe {
var probe = RuntimeProbe(abiVersion: xenora_abi_version())
var session: xenora_session = 0
probe.status = xenora_session_create(XENORA_ABI_VERSION, &session)
guard probe.status == XENORA_OK else { return probe }
defer { _ = xenora_session_destroy(session) }
probe.status = xenora_session_inspect_trusted_fixture(session, &probe.sections, &probe.entryRVA)
return probe
}
var summary: String {
String(format: "abi=%u status=%d sections=%u entry_rva=0x%x", abiVersion, status, sections, entryRVA)
}
}
/// The frame produced by one run of the trusted fixture.
struct GuestFrame {
let status: Int32
let width: Int
let height: Int
let rgba: [UInt8]
static func run() -> GuestFrame {
var session: xenora_session = 0
var status = xenora_session_create(XENORA_ABI_VERSION, &session)
guard status == XENORA_OK else { return GuestFrame(status: status, width: 0, height: 0, rgba: []) }
defer { _ = xenora_session_destroy(session) }
var rgba = [UInt8](repeating: 0, count: Int(XENORA_FIXTURE_FRAME_WIDTH * XENORA_FIXTURE_FRAME_HEIGHT * 4))
var width: UInt32 = 0
var height: UInt32 = 0
status = rgba.withUnsafeMutableBufferPointer { buffer in
xenora_session_run_trusted_fixture(session, buffer.baseAddress, UInt64(buffer.count), &width, &height)
}
return GuestFrame(status: status, width: Int(width), height: Int(height), rgba: status == XENORA_OK ? rgba : [])
}
var image: CGImage? {
guard status == XENORA_OK, let provider = CGDataProvider(data: Data(rgba) as CFData) else { return nil }
return CGImage(
width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: width * 4,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue),
provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent)
}
var summary: String {
let first = rgba.prefix(4).map(String.init).joined(separator: ",")
return "status=\(status) frame=\(width)x\(height) first_pixel=\(first)"
}
}
/// The frame produced by running the textured fixture (Gate 5, #279).
struct TexturedFrame {
let status: Int32
let width: Int
let height: Int
let rgba: [UInt8]
static func run() -> TexturedFrame {
var session: xenora_session = 0
var status = xenora_session_create(XENORA_ABI_VERSION, &session)
guard status == XENORA_OK else { return TexturedFrame(status: status, width: 0, height: 0, rgba: []) }
defer { _ = xenora_session_destroy(session) }
var rgba = [UInt8](repeating: 0, count: 16)
var width: UInt32 = 0
var height: UInt32 = 0
status = rgba.withUnsafeMutableBufferPointer { buffer in
xenora_session_run_textured_fixture(session, buffer.baseAddress, UInt64(buffer.count), &width, &height)
}
return TexturedFrame(status: status, width: Int(width), height: Int(height), rgba: status == XENORA_OK ? rgba : [])
}
var image: CGImage? {
guard status == XENORA_OK, let provider = CGDataProvider(data: Data(rgba) as CFData) else { return nil }
return CGImage(
width: width, height: height, bitsPerComponent: 8, bitsPerPixel: 32, bytesPerRow: width * 4,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue),
provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent)
}
var summary: String {
let pixels = rgba.map(String.init).joined(separator: ",")
return "status=\(status) frame=\(width)x\(height) pixels=[\(pixels)]"
}
}
/// 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
Task {
// The fixture blocks while it executes and renders, so keep it off the main thread.
frame = await Task.detached { GuestFrame.run() }.value
running = false
}
}
func runTextured() {
runningTextured = true
Task {
texturedFrame = await Task.detached { TexturedFrame.run() }.value
runningTextured = false
}
}
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.
@MainActor
final class InspectionModel: ObservableObject {
static let shared = InspectionModel()
@Published var fileName: String?
@Published var report = ""
@Published var status: Int32 = Int32(XENORA_OK)
@Published var busy = false
@Published var importing = false
func inspect(_ url: URL) {
fileName = url.lastPathComponent
busy = true
Task {
let (newStatus, newReport) = await Task.detached { InspectionModel.run(url) }.value
status = newStatus
report = newReport
busy = false
}
}
nonisolated static func run(_ url: URL) -> (Int32, String) {
let scoped = url.startAccessingSecurityScopedResource()
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
// Check the size before reading so an oversized file is never loaded into memory.
guard let size = (try? url.resourceValues(forKeys: [.fileSizeKey]))?.fileSize else {
return (Int32(XENORA_INVALID_ARGUMENT), "Could not read the file's size.")
}
guard UInt64(size) <= UInt64(XENORA_MAX_INSPECT_BYTES) else {
return (Int32(XENORA_LIMIT_EXCEEDED), "The file is \(size) bytes; inspection accepts at most \(XENORA_MAX_INSPECT_BYTES).")
}
guard let data = try? Data(contentsOf: url) else {
return (Int32(XENORA_INVALID_ARGUMENT), "Could not read the file.")
}
return data.withUnsafeBytes { raw in
let bytes = raw.bindMemory(to: UInt8.self).baseAddress
var required: UInt64 = 0
var probe: CChar = 0
var status = xenora_inspect_executable(bytes, UInt64(data.count), &probe, 1, &required)
guard status == Int32(XENORA_BUFFER_TOO_SMALL) else { return (status, "Inspection failed (status \(status)).") }
var text = [CChar](repeating: 0, count: Int(required))
status = xenora_inspect_executable(bytes, UInt64(data.count), &text, required, &required)
return (status, String(cString: text))
}
}
}
/// Receives files opened from Finder (double-click or Open With).
final class AppDelegate: NSObject, NSApplicationDelegate {
func application(_ application: NSApplication, open urls: [URL]) {
guard let url = urls.first else { return }
MainActor.assumeIsolated { InspectionModel.shared.inspect(url) }
}
}
struct InspectorView: View {
@ObservedObject var model: InspectionModel
var body: some View {
Section("Executable inspection (read-only)") {
HStack {
Button("Open Executable…") { model.importing = true }
Text("or drop a file on this window").foregroundStyle(.secondary)
}
if let name = model.fileName {
LabeledContent("File", value: model.busy ? "\(name) (inspecting…)" : name)
ScrollView {
Text(model.report)
.font(.system(.caption, design: .monospaced))
.textSelection(.enabled)
.frame(maxWidth: .infinity, alignment: .leading)
}
.frame(minHeight: 160, maxHeight: 320)
}
Text("Opened files are inspected only. Running them is not available.")
.font(.callout)
.foregroundStyle(.secondary)
}
}
}
struct ContentView: View {
let probe = RuntimeProbe.run()
@ObservedObject var model: FrameModel
@ObservedObject var loop: FrameLoopModel
@ObservedObject var inspection = InspectionModel.shared
private var frame: GuestFrame? { model.frame }
private var running: Bool { model.running }
var body: some View {
Form {
InspectorView(model: inspection)
Section("Guest display") {
if let image = frame?.image {
Image(decorative: image, scale: 1)
.resizable()
.interpolation(.none)
.aspectRatio(contentMode: .fit)
.frame(maxWidth: .infinity, minHeight: 120, maxHeight: 240)
.accessibilityLabel("Guest frame, \(frame!.width) by \(frame!.height) pixels")
Text("Guest code ran, its draw was rendered by native Metal, and all \(frame!.width * frame!.height) pixels matched the fixture shader's output.")
.font(.callout)
.foregroundStyle(.secondary)
} else if let frame {
Text("Run failed (status \(frame.status)). No frame is shown.")
.foregroundStyle(.red)
}
if let tImage = model.texturedFrame?.image {
Image(decorative: tImage, scale: 1)
.resizable()
.interpolation(.none)
.aspectRatio(contentMode: .fit)
.frame(maxWidth: .infinity, minHeight: 80, maxHeight: 160)
.accessibilityLabel("Textured guest frame, 2 by 2 pixels")
Text("Textured fixture ran: persistent texture created, dynamically updated, rendered on Metal, and retired.")
.font(.callout)
.foregroundStyle(.secondary)
}
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 fixtures (single-frame, frame-loop, and interactive guest) can run. Presentation uses read-back Metal frames. Arbitrary executables are not available yet.")
.foregroundStyle(.secondary)
}
.formStyle(.grouped)
.fileImporter(isPresented: $inspection.importing, allowedContentTypes: [.item]) { result in
if case .success(let url) = result { inspection.inspect(url) }
}
.dropDestination(for: URL.self) { urls, _ in
guard let url = urls.first, url.isFileURL else { return false }
inspection.inspect(url)
return true
}
.frame(minWidth: 520, minHeight: 680)
}
}
struct XenoraApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) var delegate
let model = FrameModel()
let loop = FrameLoopModel()
var body: some Scene {
WindowGroup("Xenora") { ContentView(model: model, loop: loop) }
}
}
// `--inspect <path>` prints the read-only report for a file and exits with its status.
if let flag = CommandLine.arguments.firstIndex(of: "--inspect"), flag + 1 < CommandLine.arguments.count {
let (status, report) = InspectionModel.run(URL(fileURLWithPath: CommandLine.arguments[flag + 1]))
print(report.hasSuffix("\n") ? report : report + "\n", terminator: "")
print("status=\(status)")
exit(status == Int32(XENORA_OK) ? 0 : 1)
}
// `--smoke-resources` tests persistent texture lifecycle, dynamic subregion updates, and retirement on Metal.
if CommandLine.arguments.contains("--smoke-resources") {
let frame = TexturedFrame.run()
print("smoke-resources: \(frame.summary)")
let expected: [UInt8] = [255, 255, 0, 255, 0, 255, 255, 255, 255, 0, 255, 255, 64, 64, 64, 255]
exit(frame.status == XENORA_OK && frame.width == 2 && frame.height == 2 && frame.rgba == expected ? 0 : 1)
}
// `--smoke-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()
print(frame.summary)
exit(frame.status == XENORA_OK ? 0 : 1)
}
// `--smoke` prints the probe and exits without opening a window, for scripts and CI.
if CommandLine.arguments.contains("--smoke") {
let probe = RuntimeProbe.run()
print(probe.summary)
exit(probe.connected ? 0 : 1)
}
XenoraApp.main()
+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
}
+96 -87
View File
@@ -4,62 +4,59 @@ use std::fmt;
pub use xenora_isa::{
Architecture, CompareRelation, ExportTarget, Instruction, InterpolationPhase, ScalarAluOp,
ScalarSource, VectorCompareOp, VectorSource,
ScalarCompareOp, ScalarSource, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp,
VectorSource,
};
use xenora_isa::{
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_ADD_I32, S_ADD_U32, S_ADDC_U32,
S_AND_B32, S_BRANCH, S_CBRANCH_EXECZ, S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM,
S_MOV_B32, S_OR_B32, S_SUB_I32, S_SUB_U32, S_SUBB_U32, S_WAITCNT, S_WAITCNT_VSCNT, S_XOR_B32,
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,
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_AND_B32, V_ASHRREV_I32, V_INTERP_P1_F32, V_INTERP_P2_F32, V_LSHLREV_B32, V_LSHRREV_B32,
V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32, VCC_LO,
};
use xenora_isa::meta::EncodingFamily;
use xenora_isa::semantics::FORM_IDS;
pub use xenora_isa::semantics::VectorBinary;
/// Metadata forms that [`decode`] turns into an [`Instruction`] for at least one
/// operand combination. Operand restrictions are listed in docs/status.toml;
/// every other form in [`xenora_isa::meta::FORMS`] is rejected as unsupported.
pub const SEMANTIC_FORMS: [(&str, EncodingFamily); 46] = [
/// operand combination: the hand-written forms below followed by every form of
/// the semantic registry ([`xenora_isa::semantics::FORM_IDS`]). Operand
/// restrictions are listed in docs/status.toml; every other form in
/// [`xenora_isa::meta::FORMS`] is rejected as unsupported.
pub const SEMANTIC_FORMS: [(&str, EncodingFamily); HANDWRITTEN_FORMS.len() + FORM_IDS.len()] =
concat_forms();
const fn concat_forms<const N: usize>() -> [(&'static str, EncodingFamily); N] {
let mut forms = [("", EncodingFamily::Sop2); N];
let mut index = 0;
while index < N {
forms[index] = if index < HANDWRITTEN_FORMS.len() {
HANDWRITTEN_FORMS[index]
} else {
FORM_IDS[index - HANDWRITTEN_FORMS.len()]
};
index += 1;
}
forms
}
/// Decoded forms not yet described by the semantic registry.
const HANDWRITTEN_FORMS: [(&str, EncodingFamily); 23] = [
("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf),
("BUFFER_STORE_DWORD", EncodingFamily::Mubuf),
("EXP", EncodingFamily::Exp),
("IMAGE_SAMPLE_LZ", EncodingFamily::Mimg),
("S_ADD_I32", EncodingFamily::Sop2),
("S_ADD_U32", EncodingFamily::Sop2),
("S_ADDC_U32", EncodingFamily::Sop2),
("S_AND_B32", EncodingFamily::Sop2),
("S_BRANCH", EncodingFamily::Sopp),
("S_CBRANCH_EXECZ", EncodingFamily::Sopp),
("S_CBRANCH_SCC0", EncodingFamily::Sopp),
("S_CBRANCH_VCCZ", EncodingFamily::Sopp),
("S_CMP_EQ_U32", EncodingFamily::Sopc),
("S_ENDPGM", EncodingFamily::Sopp),
("S_MOV_B32", EncodingFamily::Sop1),
("S_OR_B32", EncodingFamily::Sop2),
("S_SUB_I32", EncodingFamily::Sop2),
("S_SUB_U32", EncodingFamily::Sop2),
("S_SUBB_U32", EncodingFamily::Sop2),
("S_WAITCNT", EncodingFamily::Sopp),
("S_WAITCNT_VSCNT", EncodingFamily::Sopk),
("S_XOR_B32", EncodingFamily::Sop2),
("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),
@@ -327,31 +324,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;
@@ -364,19 +342,30 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
let (src, len) = scalar_source(first as u8, bytes, "s_mov_b32")?;
return Ok((Instruction::ScalarMoveB32 { dst, src }, len));
}
if S_CMP_EQ_U32.matches(first) {
if let Some(op) = ScalarUnaryOp::from_word(first) {
// SOP1: SSRC0 in bits 0-7, SDST in bits 16-22.
let mnemonic = op.mnemonic();
let dst = ((first >> 16) & 0x7f) as u8;
if dst > 105 {
return Err(unsupported(mnemonic, "expected a normal SGPR destination"));
}
let (src, len) = scalar_source(first as u8, bytes, mnemonic)?;
return Ok((Instruction::ScalarUnary { op, dst, src }, len));
}
if let Some(op) = ScalarCompareOp::from_word(first) {
let mnemonic = op.mnemonic();
let src0_bits = first as u8;
let src1_bits = (first >> 8) as u8;
if src0_bits == 255 && src1_bits == 255 {
return Err(unsupported(
"s_cmp_eq_u32",
mnemonic,
"only one source may select a literal",
));
}
let (src0, len0) = scalar_source(src0_bits, bytes, "s_cmp_eq_u32")?;
let (src1, len1) = scalar_source(src1_bits, bytes, "s_cmp_eq_u32")?;
let (src0, len0) = scalar_source(src0_bits, bytes, mnemonic)?;
let (src1, len1) = scalar_source(src1_bits, bytes, mnemonic)?;
return Ok((
Instruction::ScalarCompareEqU32 { src0, src1 },
Instruction::ScalarCompare { op, src0, src1 },
len0.max(len1),
));
}
@@ -384,20 +373,8 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
let target = branch_target(first, offset, "s_branch")?;
return Ok((Instruction::Branch { target }, S_BRANCH.byte_len()));
}
for (opcode, op) in [
(S_ADD_U32, ScalarAluOp::AddU32),
(S_SUB_U32, ScalarAluOp::SubU32),
(S_ADD_I32, ScalarAluOp::AddI32),
(S_SUB_I32, ScalarAluOp::SubI32),
(S_ADDC_U32, ScalarAluOp::AddcU32),
(S_SUBB_U32, ScalarAluOp::SubbU32),
(S_AND_B32, ScalarAluOp::AndB32),
(S_OR_B32, ScalarAluOp::OrB32),
(S_XOR_B32, ScalarAluOp::XorB32),
] {
if opcode.matches(first) {
return scalar_alu(op, first, bytes);
}
if let Some(op) = ScalarAluOp::from_word(first) {
return scalar_alu(op, first, bytes);
}
if S_CBRANCH_SCC0.matches(first) {
let target = branch_target(first, offset, "s_cbranch_scc0")?;
@@ -420,6 +397,21 @@ fn decode_gfx1030(bytes: &[u8], offset: usize) -> Result<(Instruction, u8), Deco
S_CBRANCH_VCCZ.byte_len(),
));
}
if let Some(op) = VectorAluOp::from_word(first) {
// VOP2: SRC0 in bits 0-8, VSRC1 in bits 9-16, VDST in bits 17-24.
let dst = ((first >> 17) & 0xff) as u8;
let src1 = ((first >> 9) & 0xff) as u8;
let (src0, len) = vector_src0(first, bytes, op.assembly_name())?;
return Ok((
Instruction::VectorAlu {
op,
dst,
src0,
src1,
},
len,
));
}
if V_LSHLREV_B32.matches(first) {
let (dst, src0, src1) = vop2_registers(first, "v_lshlrev_b32_e32")?;
return Ok((
@@ -689,10 +681,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 => (
@@ -706,12 +709,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> {
@@ -744,18 +746,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,
+121 -14
View File
@@ -4,9 +4,14 @@ use std::process::{Command, Stdio};
use xenora_decoder::{
Architecture, CompareRelation, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction,
ScalarAluOp, ScalarSource, 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,
};
use xenora_ref::{BranchCondition, CompareSource, Comparison, Op, ScalarAlu, Source, VectorAlu};
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin");
const BITWISE_FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/bitwise-branch.bin");
@@ -39,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,
@@ -340,15 +346,75 @@ fn reference_op(instruction: Instruction) -> Op {
ScalarAluOp::AndB32 => ScalarAlu::And,
ScalarAluOp::OrB32 => ScalarAlu::Or,
ScalarAluOp::XorB32 => ScalarAlu::Xor,
ScalarAluOp::Andn2B32 => ScalarAlu::AndNot,
ScalarAluOp::Orn2B32 => ScalarAlu::OrNot,
ScalarAluOp::NandB32 => ScalarAlu::Nand,
ScalarAluOp::NorB32 => ScalarAlu::Nor,
ScalarAluOp::XnorB32 => ScalarAlu::Xnor,
ScalarAluOp::LshlB32 => ScalarAlu::ShiftLeft,
ScalarAluOp::LshrB32 => ScalarAlu::ShiftRight,
ScalarAluOp::AshrI32 => ScalarAlu::ArithmeticShiftRight,
ScalarAluOp::MinI32 => ScalarAlu::Minimum { signed: true },
ScalarAluOp::MinU32 => ScalarAlu::Minimum { signed: false },
ScalarAluOp::MaxI32 => ScalarAlu::Maximum { signed: true },
ScalarAluOp::MaxU32 => ScalarAlu::Maximum { signed: false },
ScalarAluOp::CselectB32 => ScalarAlu::Select,
ScalarAluOp::BfmB32 => ScalarAlu::BitfieldMask,
ScalarAluOp::MulI32 => ScalarAlu::Multiply,
ScalarAluOp::BfeU32 => ScalarAlu::BitfieldExtract { signed: false },
ScalarAluOp::BfeI32 => ScalarAlu::BitfieldExtract { signed: true },
ScalarAluOp::AbsdiffI32 => ScalarAlu::AbsoluteDifference,
ScalarAluOp::Lshl1AddU32 => ScalarAlu::ShiftLeftAdd(1),
ScalarAluOp::Lshl2AddU32 => ScalarAlu::ShiftLeftAdd(2),
ScalarAluOp::Lshl3AddU32 => ScalarAlu::ShiftLeftAdd(3),
ScalarAluOp::Lshl4AddU32 => ScalarAlu::ShiftLeftAdd(4),
ScalarAluOp::MulHiU32 => ScalarAlu::MultiplyHigh { signed: false },
ScalarAluOp::MulHiI32 => ScalarAlu::MultiplyHigh { signed: true },
},
dst,
reference_scalar(src0),
reference_scalar(src1),
),
Instruction::AddNoCarryU32 { dst, src0, src1 } => Op::Add(dst, src0, src1),
// 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::ScalarCompareEqU32 { src0, src1 } => {
Op::CompareEqual(reference_scalar(src0), reference_scalar(src1))
Instruction::ScalarUnary { op, dst, src } => Op::ScalarUnary(
match op {
ScalarUnaryOp::NotB32 => ScalarUnary::Not,
ScalarUnaryOp::BrevB32 => ScalarUnary::ReverseBits,
ScalarUnaryOp::Bcnt0I32B32 => ScalarUnary::CountZeros,
ScalarUnaryOp::Bcnt1I32B32 => ScalarUnary::CountOnes,
ScalarUnaryOp::Ff0I32B32 => ScalarUnary::FindFirstZero,
ScalarUnaryOp::Ff1I32B32 => ScalarUnary::FindFirstOne,
ScalarUnaryOp::FlbitI32B32 => ScalarUnary::FindLastBit,
ScalarUnaryOp::FlbitI32 => ScalarUnary::FindLastSignBit,
ScalarUnaryOp::SextI32I8 => ScalarUnary::SignExtendByte,
ScalarUnaryOp::SextI32I16 => ScalarUnary::SignExtendShort,
ScalarUnaryOp::AbsI32 => ScalarUnary::Absolute,
},
dst,
reference_scalar(src),
),
Instruction::ScalarCompare { op, src0, src1 } => {
let (src0, src1) = (reference_scalar(src0), reference_scalar(src1));
// The reference keeps CompareEqual for EQ and uses its VOPC relation
// offsets (LT 1, EQ 2, LE 3, GT 4, NE 5, GE 6) for the rest.
match op.relation() {
CompareRelation::Equal => Op::CompareEqual(src0, src1),
relation => Op::ScalarCompare(
Comparison {
offset: relation as u8 + 1,
signed: op.semantics().signedness == Signedness::Signed,
},
src0,
src1,
),
}
}
Instruction::BranchSccZero { target } => Op::Branch {
target,
@@ -396,15 +462,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),
@@ -413,6 +481,34 @@ fn reference_op(instruction: Instruction) -> Op {
},
src1,
),
Instruction::VectorAlu {
op,
dst,
src0,
src1,
} => Op::VectorInteger(
match op {
VectorAluOp::MulI32I24 => VectorInteger::Multiply24 { signed: true },
VectorAluOp::MulHiI32I24 => VectorInteger::MultiplyHigh24 { signed: true },
VectorAluOp::MulU32U24 => VectorInteger::Multiply24 { signed: false },
VectorAluOp::MulHiU32U24 => VectorInteger::MultiplyHigh24 { signed: false },
VectorAluOp::MinI32 => VectorInteger::Minimum { signed: true },
VectorAluOp::MaxI32 => VectorInteger::Maximum { signed: true },
VectorAluOp::MinU32 => VectorInteger::Minimum { signed: false },
VectorAluOp::MaxU32 => VectorInteger::Maximum { signed: false },
VectorAluOp::XnorB32 => VectorInteger::Xnor,
VectorAluOp::AddNcU32 => VectorInteger::Add,
VectorAluOp::SubNcU32 => VectorInteger::Subtract,
VectorAluOp::SubrevNcU32 => VectorInteger::SubtractReverse,
},
dst,
match src0 {
VectorSource::Register(reg) => CompareSource::Vector(reg),
VectorSource::Scalar(reg) => CompareSource::Scalar(reg),
VectorSource::Immediate(bits) => CompareSource::Immediate(bits),
},
src1,
),
Instruction::EndProgram => Op::End,
}
}
@@ -434,13 +530,19 @@ fn compares_fixture_instructions_against_llvm() {
SHIFT_FIXTURE,
include_bytes!("../../../fixtures/rdna2/ashr.bin"),
include_bytes!("../../../fixtures/rdna2/scalar-alu.bin"),
include_bytes!("../../../fixtures/rdna2/scalar-logic.bin"),
include_bytes!("../../../fixtures/rdna2/scalar-compare.bin"),
include_bytes!("../../../fixtures/rdna2/scalar-unary.bin"),
include_bytes!("../../../fixtures/rdna2/scalar-arith.bin"),
include_bytes!("../../../fixtures/rdna2/vector-integer.bin"),
include_bytes!("../../../fixtures/rdna2/vector-compare.bin"),
include_bytes!("../../../fixtures/rdna2/vector-compare-ft.bin"),
high_registers,
&matrix,
] {
count += compare_against_llvm(fixture, &mut forms);
}
assert_eq!(forms.len(), 42, "forms compared: {forms:?}");
assert_eq!(forms.len(), 104, "forms compared: {forms:?}");
eprintln!(
"{count} three-way instruction comparisons across {} forms",
forms.len()
@@ -505,7 +607,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",
@@ -653,8 +755,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
@@ -724,7 +824,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}"),
@@ -900,7 +1006,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
+8
View File
@@ -49,3 +49,11 @@ fn declared_semantic_forms_are_exactly_those_decoded_from_fixtures() {
);
}
}
#[test]
fn registry_forms_do_not_duplicate_hand_written_forms() {
// A form declared in the semantic registry and also decoded by hand-written
// code would have two implementations; the hand-written one would win.
let unique: BTreeSet<_> = SEMANTIC_FORMS.into_iter().collect();
assert_eq!(unique.len(), SEMANTIC_FORMS.len());
}
+22
View File
@@ -0,0 +1,22 @@
[package]
name = "xenora-ffi"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
description = "Versioned C interface between the native macOS application and the Xenora runtime"
[lib]
crate-type = ["staticlib", "rlib"]
[lints]
workspace = true
[features]
# Runs the tests that need a native Metal device (scripts/test-gpu.sh).
gpu-tests = []
[dependencies]
xenora-loader = { path = "../loader" }
xenora-metal = { path = "../metal" }
xenora-shader = { path = "../shader" }
+371
View File
@@ -0,0 +1,371 @@
/* SPDX-License-Identifier: GPL-3.0-or-later */
/*
* Xenora native application interface, version 1.
*
* Every function returns a xenora_status. Sessions are identified by opaque
* 64-bit handles, never by pointers; 0 is never a valid handle. A destroyed
* handle stays invalid even if its slot is reused. Output pointers are owned
* by the caller and are written only when the call returns XENORA_OK.
* All functions are thread-safe. No Rust panic crosses this boundary: one is
* reported as XENORA_INTERNAL_ERROR.
*/
#ifndef XENORA_H
#define XENORA_H
#include <stdint.h>
#define XENORA_ABI_VERSION 1u
typedef int32_t xenora_status;
enum {
XENORA_OK = 0,
XENORA_INVALID_ARGUMENT = 1,
XENORA_INVALID_HANDLE = 2,
XENORA_VERSION_MISMATCH = 3,
XENORA_INTERNAL_ERROR = 4,
XENORA_PE_ERROR = 5,
XENORA_LIMIT_EXCEEDED = 6,
XENORA_BUFFER_TOO_SMALL = 7,
XENORA_EXECUTION_FAILED = 8,
XENORA_INVALID_STATE = 9,
};
/* Frame-loop states reported by xenora_session_frame_loop_status. */
enum {
XENORA_LOOP_NONE = 0,
XENORA_LOOP_RUNNING = 1,
XENORA_LOOP_PAUSED = 2,
XENORA_LOOP_FINISHED = 3,
XENORA_LOOP_STOPPED = 4,
XENORA_LOOP_FAILED = 5,
};
#define XENORA_FRAME_LOOP_MAX_FRAMES 100000u
/* Frame id reported when no frame has been completed yet. */
#define XENORA_NO_FRAME 0xFFFFFFFFu
/* Input snapshot delivered to guest runtime services (Gate 4, #276). */
typedef struct {
uint32_t buttons;
int16_t stick_x;
int16_t stick_y;
int16_t mouse_dx;
int16_t mouse_dy;
uint8_t mouse_buttons;
uint8_t connected;
uint16_t reserved;
} xenora_input_state;
#define XENORA_INPUT_NONE 0u
#define XENORA_INPUT_RIGHT (1u << 0)
#define XENORA_INPUT_LEFT (1u << 1)
#define XENORA_INPUT_UP (1u << 2)
#define XENORA_INPUT_DOWN (1u << 3)
#define XENORA_INPUT_ACTION_A (1u << 4)
#define XENORA_INPUT_ACTION_B (1u << 5)
/* Size of the frame drawn by the trusted fixture: RGBA8, rows top to bottom. */
#define XENORA_FIXTURE_FRAME_WIDTH 4u
#define XENORA_FIXTURE_FRAME_HEIGHT 3u
typedef uint64_t xenora_session;
/* The interface version this library implements. */
uint32_t xenora_abi_version(void);
/* Create a session. `abi_version` must equal XENORA_ABI_VERSION. */
xenora_status xenora_session_create(uint32_t abi_version, xenora_session *out_session);
/* Destroy a session. Destroying it again returns XENORA_INVALID_HANDLE. */
xenora_status xenora_session_destroy(xenora_session session);
/* Parse the bundled trusted PE fixture with the runtime loader. No guest code runs. */
xenora_status xenora_session_inspect_trusted_fixture(
xenora_session session,
uint32_t *out_section_count,
uint32_t *out_entry_rva);
/*
* Run the bundled trusted PE fixture: its x86-64 code is translated and executed,
* and its single draw request is rendered on the native Metal device. On XENORA_OK,
* `out_rgba` holds width * height * 4 bytes of the read-back frame, which has been
* checked against the fixture shader's known output. `capacity` is the size of
* `out_rgba` in bytes. Blocks the calling thread; call it off the main thread.
* Only the embedded fixture can run; no caller-supplied executable is accepted.
*/
xenora_status xenora_session_run_trusted_fixture(
xenora_session session,
uint8_t *out_rgba,
uint64_t capacity,
uint32_t *out_width,
uint32_t *out_height);
/*
* Persistent rendering (one frame loop per session). Start runs the embedded
* frame-loop fixture on a session-owned guest thread: the guest submits frames
* 0, 1, 2, ... and each is rendered on native Metal and verified before it
* becomes the latest frame. The guest stops after `frame_count` frames
* (1..=XENORA_FRAME_LOOP_MAX_FRAMES). Pause holds the guest at its next frame
* submission; resume continues it; stop makes it leave its loop and halt, and
* waits for its thread. Destroying the session stops the loop first. Starting a
* second loop on the same session returns XENORA_INVALID_STATE.
*/
xenora_status xenora_session_start_frame_loop(xenora_session session, uint32_t frame_count);
xenora_status xenora_session_start_interactive_loop(xenora_session session, uint32_t frame_count);
xenora_status xenora_session_send_input(xenora_session session, const xenora_input_state *input);
xenora_status xenora_session_queue_input(xenora_session session, const xenora_input_state *input);
xenora_status xenora_session_pause_frame_loop(xenora_session session);
xenora_status xenora_session_resume_frame_loop(xenora_session session);
xenora_status xenora_session_stop_frame_loop(xenora_session session);
/*
* Retrieve a previously completed frame by sequence index (0 <= frame_index < completed).
* Used for deterministic replay verification and frame inspection.
*/
xenora_status xenora_session_get_recorded_frame(
xenora_session session,
uint32_t frame_index,
uint32_t *out_frame_id,
uint8_t *out_rgba,
uint64_t capacity
);
/*
* Report the loop's state, the number of completed frames, and the latest
* verified frame: its id (XENORA_NO_FRAME if none yet) and, when one exists,
* its RGBA8 pixels (XENORA_FIXTURE_FRAME_WIDTH x HEIGHT) in `out_rgba`.
*/
xenora_status xenora_session_frame_loop_status(
xenora_session session,
uint32_t *out_state,
uint32_t *out_completed,
uint32_t *out_frame_id,
uint8_t *out_rgba,
uint64_t capacity);
/* Largest file xenora_inspect_executable accepts, in bytes. */
#define XENORA_MAX_INSPECT_BYTES 268435456u
/* Opaque persistent GPU resource handle (Gate 5, #279) */
typedef uint64_t xenora_resource;
#define XENORA_NO_RESOURCE 0u
enum {
XENORA_RESOURCE_TYPE_TEXTURE_2D = 1,
XENORA_RESOURCE_TYPE_BUFFER = 2,
};
/*
* Create a persistent RGBA8 2D texture owned by the session.
* If `initial_rgba` is non-null, it must point to at least width * height * 4 bytes.
*/
xenora_status xenora_session_create_texture(
xenora_session session,
uint32_t width,
uint32_t height,
const uint8_t *initial_rgba,
xenora_resource *out_resource
);
/*
* Dynamically update a subregion of a persistent texture.
*/
xenora_status xenora_session_update_texture(
xenora_session session,
xenora_resource resource,
uint32_t x,
uint32_t y,
uint32_t width,
uint32_t height,
const uint8_t *rgba,
uint64_t byte_count
);
/*
* Destroy or retire a persistent resource. If in-flight GPU execution is using
* the resource, destruction is deferred until the execution completes.
*/
xenora_status xenora_session_destroy_resource(
xenora_session session,
xenora_resource resource
);
/*
* Query type, dimensions, and in-flight status of a persistent resource.
*/
xenora_status xenora_session_resource_info(
xenora_session session,
xenora_resource resource,
uint32_t *out_type,
uint32_t *out_width,
uint32_t *out_height,
uint32_t *out_in_flight
);
/*
* Render a frame using a persistent texture resource.
*/
xenora_status xenora_session_render_textured(
xenora_session session,
xenora_resource resource,
uint8_t *out_rgba,
uint64_t capacity,
uint32_t *out_width,
uint32_t *out_height
);
/*
* Run the original textured PE fixture and verify its read-back frame.
*/
xenora_status xenora_session_run_textured_fixture(
xenora_session session,
uint8_t *out_rgba,
uint64_t capacity,
uint32_t *out_width,
uint32_t *out_height
);
/* 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.
* On XENORA_OK, XENORA_PE_ERROR or XENORA_INTERNAL_ERROR, `out_report` holds a
* NUL-terminated UTF-8 report of `*out_required` bytes including the NUL.
* XENORA_PE_ERROR means the file is not an acceptable PE32+ image;
* XENORA_INTERNAL_ERROR means Xenora's own probe failed on it. The report says which. If `capacity`
* is too small the call returns XENORA_BUFFER_TOO_SMALL with `*out_required`
* set and nothing else written. Files over XENORA_MAX_INSPECT_BYTES return
* XENORA_LIMIT_EXCEEDED.
*/
xenora_status xenora_inspect_executable(
const uint8_t *bytes,
uint64_t length,
char *out_report,
uint64_t capacity,
uint64_t *out_required);
#endif
+313
View File
@@ -0,0 +1,313 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Persistent guest rendering for one session (Gate 3, #266).
//!
//! The embedded `frame-loop.exe` fixture calls `xenora.dll!frame_submit(index)`
//! with index 0, 1, 2, ... and halts when the call returns 0. The guest runs on
//! its own thread for the session's lifetime. Pause, resume and stop act at the
//! frame-submit boundary: a paused guest waits inside that call with its
//! architectural state untouched, and a stop request makes the call return 0 so
//! the guest leaves its loop and halts.
use std::cell::RefCell;
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use std::thread::JoinHandle;
use xenora_loader::startup::{StartupLayout, run_synthetic_startup};
use xenora_loader::{ExitReason, ImportRegistry, Register};
use xenora_metal::NativeCompute;
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/frame-loop.exe");
const INTERACTIVE_FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/interactive.exe");
pub const WIDTH: usize = 4;
pub const HEIGHT: usize = 3;
pub const FRAME_BYTES: usize = WIDTH * HEIGHT * 4;
pub const MAX_FRAMES: u32 = 100_000;
/// Guest instructions per loop iteration (mov, call, inc, test, jnz) plus slack.
const STEPS_PER_FRAME: usize = 8;
const STEPS_PER_INTERACTIVE_FRAME: usize = 24;
/// `x9-constant-ps.s` exports (1, 0, 0, 1): opaque red. Everything else is the clear colour.
const RED: [u8; 4] = [255, 0, 0, 255];
const CLEAR: [u8; 4] = [19, 43, 93, 251];
pub const RUNNING: u32 = 1;
pub const PAUSED: u32 = 2;
pub const FINISHED: u32 = 3;
pub const STOPPED: u32 = 4;
pub const FAILED: u32 = 5;
#[derive(Default, Copy, Clone)]
#[repr(C)]
pub struct InputState {
pub buttons: u32,
pub stick_x: i16,
pub stick_y: i16,
pub mouse_dx: i16,
pub mouse_dy: i16,
pub mouse_buttons: u8,
pub connected: u8,
pub reserved: u16,
}
#[derive(Default)]
struct State {
status: u32,
paused: bool,
stop: bool,
interactive: bool,
limit: u32,
completed: u32,
input: InputState,
input_queue: std::collections::VecDeque<InputState>,
recorded_frames: Vec<(u32, Vec<u8>)>,
/// Every `frame_submit` call the guest made, including the one answered with 0.
calls: u64,
latest: Option<(u32, Vec<u8>)>,
}
#[derive(Default)]
pub struct FrameLoop {
state: Mutex<State>,
wake: Condvar,
thread: Mutex<Option<JoinHandle<()>>>,
}
pub struct Snapshot {
pub status: u32,
pub completed: u32,
pub latest: Option<(u32, Vec<u8>)>,
}
impl FrameLoop {
fn lock(&self) -> MutexGuard<'_, State> {
self.state
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
pub fn start(limit: u32, interactive: bool) -> Arc<Self> {
let shared = Arc::new(Self::default());
{
let mut state = shared.lock();
state.status = RUNNING;
state.limit = limit;
state.interactive = interactive;
}
let guest = Arc::clone(&shared);
let handle = std::thread::Builder::new()
.name("xenora-guest".into())
.spawn(move || guest.run())
.ok();
if handle.is_none() {
shared.lock().status = FAILED;
}
*shared.thread.lock().unwrap_or_else(|p| p.into_inner()) = handle;
shared
}
/// Pause or resume. Returns false unless the loop is running or paused.
pub fn set_paused(&self, paused: bool) -> bool {
let mut state = self.lock();
if !matches!(state.status, RUNNING | PAUSED) {
return false;
}
state.paused = paused;
state.status = if paused { PAUSED } else { RUNNING };
self.wake.notify_all();
true
}
/// Ask the guest to stop at its next frame submission and wait for its thread.
pub fn stop(&self) {
{
let mut state = self.lock();
state.stop = true;
self.wake.notify_all();
}
if let Some(handle) = self.thread.lock().unwrap_or_else(|p| p.into_inner()).take() {
let _ = handle.join();
}
}
pub fn send_input(&self, input: InputState) {
let mut state = self.lock();
state.input = input;
}
pub fn queue_input(&self, input: InputState) {
let mut state = self.lock();
state.input_queue.push_back(input);
}
pub fn get_recorded_frame(&self, index: usize) -> Option<(u32, Vec<u8>)> {
let state = self.lock();
state.recorded_frames.get(index).cloned()
}
pub fn snapshot(&self) -> Snapshot {
let state = self.lock();
Snapshot {
status: state.status,
completed: state.completed,
latest: state.latest.clone(),
}
}
fn run(self: Arc<Self>) {
let outcome = self.execute();
let mut state = self.lock();
state.status = match outcome {
Err(_) => FAILED,
Ok(()) if state.stop && state.completed < state.limit => STOPPED,
Ok(()) => FINISHED,
};
}
fn execute(self: &Arc<Self>) -> Result<(), String> {
let shader = compile_graphics(
Architecture::Gfx1030,
include_bytes!("../../../fixtures/rdna2/x9-constant-vs.bin"),
include_bytes!("../../../fixtures/rdna2/x9-constant-ps.bin"),
)
.map_err(|e| format!("shader translation: {e}"))?;
let gpu = NativeCompute::new().map_err(|e| format!("Metal device: {e}"))?;
// The session's GPU resources live on the guest thread, where the import runs.
GPU.with(|slot| *slot.borrow_mut() = Some((gpu, shader.msl)));
let shared = Arc::clone(self);
let mut imports = ImportRegistry::new();
imports.register("xenora.dll", "frame_submit", move |args, _, memory| {
let index = args.get(0, memory).map_err(ExitReason::MemoryFault)?;
shared
.submit(index)
.ok_or(ExitReason::IllegalInstruction(0xff))
});
if self.lock().interactive {
let shared_poll = Arc::clone(self);
imports.register("xenora.dll", "input_poll", move |_args, _, _memory| {
let mut state = shared_poll.lock();
let input = state.input_queue.pop_front().unwrap_or(state.input);
let cmd = if input.buttons & crate::XENORA_INPUT_RIGHT != 0 {
1u64
} else if input.buttons & crate::XENORA_INPUT_LEFT != 0 {
2u64
} else {
0u64
};
Ok(cmd)
});
}
let limit = self.lock().limit as usize;
let is_interactive = self.lock().interactive;
let fixture_bytes = if is_interactive {
INTERACTIVE_FIXTURE
} else {
FIXTURE
};
let steps_per_frame = if is_interactive {
STEPS_PER_INTERACTIVE_FRAME
} else {
STEPS_PER_FRAME
};
let startup = run_synthetic_startup(
fixture_bytes,
StartupLayout {
image_base: 0x1_4000_0000,
stack_top: 0x2_0001_0000,
tls_base: 0x3_0000_0000,
},
imports,
(limit + 1) * steps_per_frame + 32,
)
.map_err(|e| format!("startup: {e}"));
GPU.with(|slot| slot.borrow_mut().take());
let startup = startup?;
let calls = self.lock().calls;
let rbx = startup.execution.final_state.get(Register::Rbx);
if startup.execution.exit_reason != ExitReason::Halt {
return Err(format!(
"guest ended with {:?}",
startup.execution.exit_reason
));
}
if !is_interactive && rbx != calls {
return Err(format!("guest ended with rbx={rbx}, calls={calls}"));
}
Ok(())
}
/// Handle one `frame_submit`: wait while paused, then render and verify the
/// frame. `None` fails the guest; `Some(0)` tells it to stop.
fn submit(&self, index: u64) -> Option<u64> {
let mut state = self.lock();
state.calls += 1;
while state.paused && !state.stop {
state = self.wake.wait(state).unwrap_or_else(|p| p.into_inner());
}
if state.stop || state.completed >= state.limit {
return Some(0);
}
if state.interactive {
if index >= WIDTH as u64 {
return None; // column must be inside 0..WIDTH
}
} else if index != u64::from(state.completed) {
return None; // frame identities must arrive in order
}
drop(state);
let pixels = render(index as u32)?;
let mut state = self.lock();
state.completed += 1;
state.latest = Some((index as u32, pixels.clone()));
if state.interactive {
state.recorded_frames.push((index as u32, pixels));
}
Some(u64::from(state.completed < state.limit && !state.stop))
}
}
thread_local! {
static GPU: RefCell<Option<(NativeCompute, String)>> = const { RefCell::new(None) };
}
/// Frame `index` is a red strip in column `index % 4` on the clear colour.
///
/// The triangle (x0, -10), (x0 + 0.7, 0), (x0, 10) in clip space, with x0 the
/// column's left edge, covers that column's pixel centres in all three rows and
/// none of its neighbours'.
fn render(index: u32) -> Option<Vec<u8>> {
let column = (index as usize % WIDTH) as f32;
let x0 = -1.0 + column * (2.0 / WIDTH as f32);
let pixels = GPU.with(|slot| {
let slot = slot.borrow();
let (gpu, msl) = slot.as_ref()?;
gpu.render_rgba8(
msl,
[VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT],
&[
[x0, -10.0, 0.5, 1.0],
[x0 + 0.7, 0.0, 0.5, 1.0],
[x0, 10.0, 0.5, 1.0],
],
&[[0.0; 4]; 3],
[WIDTH, HEIGHT],
CLEAR,
)
.ok()
})?;
(pixels == expected(index)).then_some(pixels)
}
/// The expected frame for `index`, from the strip rule alone.
pub fn expected(index: u32) -> Vec<u8> {
(0..WIDTH * HEIGHT)
.flat_map(|pixel| {
if pixel % WIDTH == index as usize % WIDTH {
RED
} else {
CLEAR
}
})
.collect()
}
File diff suppressed because it is too large. Load diff
+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);
}
+278
View File
@@ -0,0 +1,278 @@
// 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));
}
}
/// Footprint once it has stopped changing. After a session is destroyed, Metal gives
/// back its memory asynchronously: measured on an Apple M5, a reading taken right after
/// destroy was up to about 45 MiB above the floor it returned to within one second,
/// every time. A single immediate reading therefore mixes in memory that is already on
/// its way out. Read every 50 ms until two consecutive readings agree within 1 MiB
/// (at most 5 s). A genuine leak still settles high, so it is still caught.
fn settled_footprint() -> u64 {
let deadline = Instant::now() + Duration::from_secs(5);
let mut previous = footprint();
loop {
std::thread::sleep(Duration::from_millis(50));
let current = footprint();
if current.abs_diff(previous) < 1 << 20 || Instant::now() >= deadline {
return current;
}
previous = current;
}
}
/// 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 = settled_footprint();
for _ in 0..5 {
run();
}
let after = settled_footprint();
let growth = after.saturating_sub(baseline);
println!("footprint baseline={baseline} after_5_sessions={after} growth={growth}");
assert!(
growth < 16 << 20,
"footprint grew by {growth} bytes over 5 sessions of 300 frames"
);
}
+298
View File
@@ -0,0 +1,298 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Gate 4 acceptance on a native Metal device: interactive guest execution with
//! dynamic input handling and rendering through the C interface.
//! Needs `--features gpu-tests` (scripts/test-gpu.sh).
#![cfg(feature = "gpu-tests")]
use std::sync::Mutex;
use std::time::{Duration, Instant};
use xenora_ffi::*;
/// Tests share the process-wide session table and one GPU; run them one at a time.
static SERIAL: Mutex<()> = Mutex::new(());
/// Expected frame `column` (0..3): column `column` is opaque red (255, 0, 0, 255);
/// all other columns keep the clear colour (19, 43, 93, 251).
fn expected(column: u32) -> Vec<u8> {
let mut frame = Vec::new();
for _row in 0..3 {
for col in 0..4 {
if col == column % 4 {
frame.extend([255, 0, 0, 255]);
} else {
frame.extend([19, 43, 93, 251]);
}
}
}
frame
}
struct Status {
state: u32,
completed: u32,
frame_id: u32,
rgba: [u8; 48],
}
fn status(session: u64) -> Status {
let mut s = Status {
state: 99,
completed: 0,
frame_id: 0,
rgba: [0; 48],
};
let code = unsafe {
xenora_session_frame_loop_status(
session,
&mut s.state,
&mut s.completed,
&mut s.frame_id,
s.rgba.as_mut_ptr(),
48,
)
};
assert_eq!(code, XENORA_OK);
s
}
fn session() -> u64 {
let mut session = 0;
assert_eq!(
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut session) },
XENORA_OK
);
session
}
fn send_buttons(session: u64, buttons: u32) {
let input = xenora_input_state {
buttons,
stick_x: 0,
stick_y: 0,
mouse_dx: 0,
mouse_dy: 0,
mouse_buttons: 0,
connected: 1,
reserved: 0,
};
assert_eq!(
unsafe { xenora_session_send_input(session, &input) },
XENORA_OK
);
}
fn queue_buttons(session: u64, buttons: u32) {
let input = xenora_input_state {
buttons,
stick_x: 0,
stick_y: 0,
mouse_dx: 0,
mouse_dy: 0,
mouse_buttons: 0,
connected: 1,
reserved: 0,
};
assert_eq!(
unsafe { xenora_session_queue_input(session, &input) },
XENORA_OK
);
}
fn wait_until(session: u64, what: &str, done: impl Fn(&Status) -> bool) -> Status {
let deadline = Instant::now() + Duration::from_secs(60);
loop {
let s = status(session);
if done(&s) {
return s;
}
assert!(
Instant::now() < deadline,
"timed out waiting for {what} (state {}, completed {})",
s.state,
s.completed
);
std::thread::sleep(Duration::from_millis(2));
}
}
#[test]
fn interactive_input_moves_guest_column_and_updates_pixels() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
let session = session();
// Start interactive loop with 120 frames
assert_eq!(
xenora_session_start_interactive_loop(session, 120),
XENORA_OK
);
// Initial frames without input stay at column 0
let s = wait_until(session, "initial frames", |s| s.completed >= 5);
assert_eq!(s.frame_id, 0);
assert_eq!(s.rgba.to_vec(), expected(0));
// Send Right input: column should advance 0 -> 1 -> 2 -> 3 -> 0
send_buttons(session, XENORA_INPUT_RIGHT);
let s_right = wait_until(session, "column moves right", |s| {
s.completed >= 15 && s.frame_id != 0
});
assert_eq!(s_right.rgba.to_vec(), expected(s_right.frame_id));
// Release input: position stops moving
send_buttons(session, XENORA_INPUT_NONE);
let s_hold_start = wait_until(session, "wait for release frame", |s| {
s.completed >= s_right.completed + 2
});
let hold_col = s_hold_start.frame_id;
let s_hold = wait_until(session, "position holds on release", |s| {
s.completed >= s_hold_start.completed + 10
});
assert_eq!(s_hold.frame_id, hold_col);
assert_eq!(s_hold.rgba.to_vec(), expected(s_hold.frame_id));
// Send Left input: column should move left
send_buttons(session, XENORA_INPUT_LEFT);
let s_left = wait_until(session, "column moves left", |s| {
s.completed >= s_hold.completed + 10 && s.frame_id != hold_col
});
assert_eq!(s_left.rgba.to_vec(), expected(s_left.frame_id));
// Wait until finished
let s_end = wait_until(session, "loop finish", |s| s.state == XENORA_LOOP_FINISHED);
assert_eq!(s_end.completed, 120);
assert_eq!(xenora_session_destroy(session), XENORA_OK);
}
#[test]
fn deterministic_input_replay_produces_identical_frames() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
// Timeline of inputs across 60 frames:
// frames 0..15: Right
// frames 15..30: None
// frames 30..45: Left
// frames 45..60: Right
let replay_sequence: Vec<u32> = (0..60)
.map(|f| {
if f < 15 {
XENORA_INPUT_RIGHT
} else if f < 30 {
XENORA_INPUT_NONE
} else if f < 45 {
XENORA_INPUT_LEFT
} else {
XENORA_INPUT_RIGHT
}
})
.collect();
let run_replay = || {
let session = session();
assert_eq!(
xenora_session_start_interactive_loop(session, 60),
XENORA_OK
);
// Pre-queue the complete input sequence
for &btn in &replay_sequence {
queue_buttons(session, btn);
}
// Wait until all 60 frames are rendered
let s = wait_until(session, "replay completion", |s| {
s.state == XENORA_LOOP_FINISHED && s.completed == 60
});
assert_eq!(s.completed, 60);
// Inspect all 60 recorded frames
let mut frames = Vec::with_capacity(60);
for i in 0..60 {
let mut id = 0u32;
let mut rgba = [0u8; 48];
let code = unsafe {
xenora_session_get_recorded_frame(session, i, &mut id, rgba.as_mut_ptr(), 48)
};
assert_eq!(code, XENORA_OK);
assert_eq!(rgba.to_vec(), expected(id));
frames.push((id, rgba));
}
assert_eq!(xenora_session_destroy(session), XENORA_OK);
frames
};
let run1 = run_replay();
let run2 = run_replay();
assert_eq!(run1.len(), 60);
assert_eq!(run2.len(), 60);
for i in 0..60 {
assert_eq!(
run1[i].0, run2[i].0,
"frame {} column mismatch: {} vs {}",
i, run1[i].0, run2[i].0
);
assert_eq!(run1[i].1, run2[i].1, "frame {} pixel mismatch", i);
}
}
#[test]
fn focus_loss_and_release_resets_input_cleanly() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
let session = session();
assert_eq!(
xenora_session_start_interactive_loop(session, 100),
XENORA_OK
);
// Send Right
send_buttons(session, XENORA_INPUT_RIGHT);
let s1 = wait_until(session, "moving right", |s| s.completed >= 10);
// Simulate focus loss / key release
send_buttons(session, XENORA_INPUT_NONE);
// Wait for the release to take effect in the guest
let s_released = wait_until(session, "release takes effect", |s| {
s.completed >= s1.completed + 2
});
let stopped_col = s_released.frame_id;
// Check next 15 frames: frame_id must remain fixed at stopped_col
let s2 = wait_until(session, "hold after release", |s| {
s.completed >= s_released.completed + 15
});
assert_eq!(s2.frame_id, stopped_col);
assert_eq!(s2.rgba.to_vec(), expected(stopped_col));
// Clean stop
assert_eq!(xenora_session_stop_frame_loop(session), XENORA_OK);
let s_stopped = wait_until(session, "stopped", |s| s.state == XENORA_LOOP_STOPPED);
assert_eq!(s_stopped.state, XENORA_LOOP_STOPPED);
assert_eq!(xenora_session_destroy(session), XENORA_OK);
}
#[test]
fn destroying_interactive_session_stops_cleanly() {
let _serial = SERIAL.lock().unwrap_or_else(|p| p.into_inner());
let session = session();
assert_eq!(
xenora_session_start_interactive_loop(session, 5000),
XENORA_OK
);
// Wait until it actually starts rendering
wait_until(session, "running", |s| s.completed >= 5);
let start = Instant::now();
assert_eq!(xenora_session_destroy(session), XENORA_OK);
assert!(
start.elapsed() < Duration::from_millis(500),
"destroy took too long: {:?}",
start.elapsed()
);
}
+40
View File
@@ -0,0 +1,40 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Runs the trusted fixture through the C interface on a native Metal device.
//! Needs `--features gpu-tests` (scripts/test-gpu.sh).
#![cfg(feature = "gpu-tests")]
use xenora_ffi::*;
/// fixtures/rdna2/x9-constant-ps.s: `v_mov_b32 v8, 1.0; v_mov_b32 v9, 0;
/// exp mrt0, v8, v9, v9, v8` writes (1, 0, 0, 1); as RGBA8 unorm that is (255, 0, 0, 255).
const SHADER_OUTPUT: [u8; 4] = [255, 0, 0, 255];
#[test]
fn guest_fixture_frame_reaches_the_caller_through_metal() {
for run in 0..3 {
let mut session = 0;
assert_eq!(
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut session) },
XENORA_OK
);
let (mut rgba, mut width, mut height) = ([0u8; 64], 0u32, 0u32);
let status = unsafe {
xenora_session_run_trusted_fixture(
session,
rgba.as_mut_ptr(),
64,
&mut width,
&mut height,
)
};
assert_eq!(status, XENORA_OK, "run {run}");
assert_eq!((width, height), (4, 3));
assert_eq!(&rgba[..48], SHADER_OUTPUT.repeat(12).as_slice());
assert!(
rgba[48..].iter().all(|&b| b == 0),
"no write past the frame"
);
assert_eq!(xenora_session_destroy(session), XENORA_OK);
}
}
+375
View File
@@ -0,0 +1,375 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Gate 5 acceptance on a native Metal device: persistent GPU resources,
//! dynamic texture updates, and completion-aware resource retirement through
//! the C interface (#279).
//! Needs `--features gpu-tests` (scripts/test-gpu.sh).
#![cfg(feature = "gpu-tests")]
use std::sync::Mutex;
use xenora_ffi::*;
/// Tests share the process-wide session table and one GPU; run them one at a time.
static SERIAL: Mutex<()> = Mutex::new(());
fn session() -> u64 {
let mut handle = 0;
assert_eq!(
unsafe { xenora_session_create(XENORA_ABI_VERSION, &mut handle) },
XENORA_OK
);
assert_ne!(handle, 0);
handle
}
#[test]
fn persistent_texture_lifecycle_survives_across_multiple_frames() {
let _guard = SERIAL.lock().unwrap();
let sess = session();
// 2x2 initial texture:
// (0,0)=red, (1,0)=green, (0,1)=blue, (1,1)=white
let initial_rgba: [u8; 16] = [
255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
];
let mut res = 0u64;
assert_eq!(
unsafe { xenora_session_create_texture(sess, 2, 2, initial_rgba.as_ptr(), &mut res) },
XENORA_OK
);
assert_ne!(res, XENORA_NO_RESOURCE);
// Render 5 consecutive frames from this single persistent texture resource without re-allocation.
for frame_idx in 0..5 {
let mut out_rgba = [0u8; 16];
let mut out_w = 0u32;
let mut out_h = 0u32;
assert_eq!(
unsafe {
xenora_session_render_textured(
sess,
res,
out_rgba.as_mut_ptr(),
16,
&mut out_w,
&mut out_h,
)
},
XENORA_OK,
"render frame {} failed",
frame_idx
);
assert_eq!(out_w, 2);
assert_eq!(out_h, 2);
assert_eq!(
out_rgba, initial_rgba,
"frame {} pixel mismatch with persistent texture",
frame_idx
);
}
// Verify resource is still live and un-retired after all frames
let (mut r_type, mut r_w, mut r_h, mut r_flight) = (0u32, 0u32, 0u32, 0u32);
assert_eq!(
unsafe {
xenora_session_resource_info(sess, res, &mut r_type, &mut r_w, &mut r_h, &mut r_flight)
},
XENORA_OK
);
assert_eq!(r_type, XENORA_RESOURCE_TYPE_TEXTURE_2D);
assert_eq!(r_w, 2);
assert_eq!(r_h, 2);
assert_eq!(r_flight, 0);
assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK);
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
}
#[test]
fn dynamic_texture_subregion_update_is_reflected_on_metal() {
let _guard = SERIAL.lock().unwrap();
let sess = session();
// 2x2 initial texture:
// (0,0)=red, (1,0)=green, (0,1)=blue, (1,1)=white
let initial_rgba: [u8; 16] = [
255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
];
let mut res = 0u64;
assert_eq!(
unsafe { xenora_session_create_texture(sess, 2, 2, initial_rgba.as_ptr(), &mut res) },
XENORA_OK
);
// 1. Update 1x1 subregion at (x=1, y=0) from green to yellow [255, 255, 0, 255]
let yellow_pixel = [255u8, 255, 0, 255];
assert_eq!(
unsafe { xenora_session_update_texture(sess, res, 1, 0, 1, 1, yellow_pixel.as_ptr(), 4) },
XENORA_OK
);
let mut frame1 = [0u8; 16];
let (mut w, mut h) = (0u32, 0u32);
assert_eq!(
unsafe {
xenora_session_render_textured(sess, res, frame1.as_mut_ptr(), 16, &mut w, &mut h)
},
XENORA_OK
);
let expected_frame1: [u8; 16] = [
255, 0, 0, 255, // (0,0) red (untouched)
255, 255, 0, 255, // (1,0) yellow (updated)
0, 0, 255, 255, // (0,1) blue (untouched)
255, 255, 255, 255, // (1,1) white (untouched)
];
assert_eq!(
frame1, expected_frame1,
"Metal read-back did not reflect 1x1 subregion update"
);
// 2. Update 2x1 subregion across the bottom row: (0,1) and (1,1)
// (0,1)=magenta [255, 0, 255, 255], (1,1)=cyan [0, 255, 255, 255]
let bottom_row = [255u8, 0, 255, 255, 0, 255, 255, 255];
assert_eq!(
unsafe { xenora_session_update_texture(sess, res, 0, 1, 2, 1, bottom_row.as_ptr(), 8) },
XENORA_OK
);
let mut frame2 = [0u8; 16];
assert_eq!(
unsafe {
xenora_session_render_textured(sess, res, frame2.as_mut_ptr(), 16, &mut w, &mut h)
},
XENORA_OK
);
let expected_frame2: [u8; 16] = [
255, 0, 0, 255, // (0,0) red
255, 255, 0, 255, // (1,0) yellow
255, 0, 255, 255, // (0,1) magenta
0, 255, 255, 255, // (1,1) cyan
];
assert_eq!(
frame2, expected_frame2,
"Metal read-back did not reflect 2x1 bottom row update"
);
assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK);
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
}
#[test]
fn deferred_resource_retirement_safely_waits_for_completion() {
let _guard = SERIAL.lock().unwrap();
let sess = session();
let mut res = 0u64;
assert_eq!(
unsafe { xenora_session_create_texture(sess, 2, 2, std::ptr::null(), &mut res) },
XENORA_OK
);
// Acquire an in-flight reference simulating active GPU encoding/submission
assert_eq!(test_acquire_resource_in_flight(sess, res), Ok(()));
let (mut r_type, mut r_w, mut r_h, mut r_flight) = (0u32, 0u32, 0u32, 0u32);
assert_eq!(
unsafe {
xenora_session_resource_info(sess, res, &mut r_type, &mut r_w, &mut r_h, &mut r_flight)
},
XENORA_OK
);
assert_eq!(r_flight, 1);
// Calling destroy while in-flight marks the resource retired without dangling pointers
assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK);
// Subsequent caller operations on the retired handle are rejected
assert_eq!(
unsafe {
xenora_session_resource_info(sess, res, &mut r_type, &mut r_w, &mut r_h, &mut r_flight)
},
XENORA_INVALID_HANDLE
);
assert_eq!(
xenora_session_destroy_resource(sess, res),
XENORA_INVALID_HANDLE
);
let dummy_pixel = [0u8; 4];
assert_eq!(
unsafe { xenora_session_update_texture(sess, res, 0, 0, 1, 1, dummy_pixel.as_ptr(), 4) },
XENORA_INVALID_HANDLE
);
let mut out_rgba = [0u8; 16];
let (mut w, mut h) = (0u32, 0u32);
assert_eq!(
unsafe {
xenora_session_render_textured(sess, res, out_rgba.as_mut_ptr(), 16, &mut w, &mut h)
},
XENORA_INVALID_HANDLE
);
// Now in-flight execution completes and releases its reference
assert_eq!(test_release_resource_in_flight(sess, res), Ok(()));
// The slot is now safely reclaimed; the next allocation reuses the slot with a new generation
let mut res2 = 0u64;
assert_eq!(
unsafe { xenora_session_create_texture(sess, 2, 2, std::ptr::null(), &mut res2) },
XENORA_OK
);
assert_eq!((res & 0xFFFF_FFFF), (res2 & 0xFFFF_FFFF)); // same slot index
assert_ne!(res >> 32, res2 >> 32); // higher generation
assert_eq!(xenora_session_destroy_resource(sess, res2), XENORA_OK);
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
}
#[test]
fn invalid_stale_and_double_destroyed_resource_handles_are_rejected() {
let _guard = SERIAL.lock().unwrap();
let sess = session();
// Zero handle
assert_eq!(
xenora_session_destroy_resource(sess, XENORA_NO_RESOURCE),
XENORA_INVALID_HANDLE
);
// Unallocated slot index
let unallocated_handle = (1u64 << 32) | 999u64;
assert_eq!(
xenora_session_destroy_resource(sess, unallocated_handle),
XENORA_INVALID_HANDLE
);
// Create and destroy a valid resource
let mut res = 0u64;
assert_eq!(
unsafe { xenora_session_create_texture(sess, 2, 2, std::ptr::null(), &mut res) },
XENORA_OK
);
assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK);
// Double destroy
assert_eq!(
xenora_session_destroy_resource(sess, res),
XENORA_INVALID_HANDLE
);
// Stale handle queries
let (mut r_type, mut r_w, mut r_h, mut r_flight) = (0u32, 0u32, 0u32, 0u32);
assert_eq!(
unsafe {
xenora_session_resource_info(sess, res, &mut r_type, &mut r_w, &mut r_h, &mut r_flight)
},
XENORA_INVALID_HANDLE
);
let pixel = [0u8; 4];
assert_eq!(
unsafe { xenora_session_update_texture(sess, res, 0, 0, 1, 1, pixel.as_ptr(), 4) },
XENORA_INVALID_HANDLE
);
let mut out_rgba = [0u8; 16];
let (mut w, mut h) = (0u32, 0u32);
assert_eq!(
unsafe {
xenora_session_render_textured(sess, res, out_rgba.as_mut_ptr(), 16, &mut w, &mut h)
},
XENORA_INVALID_HANDLE
);
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
}
#[test]
fn repeated_resource_allocations_and_retirements_do_not_leak_slots() {
let _guard = SERIAL.lock().unwrap();
let sess = session();
let initial = [
255u8, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255,
];
let update = [255u8, 255, 0, 255];
// Run 200 cycles of create -> update -> render -> destroy
for i in 0..200 {
let mut res = 0u64;
assert_eq!(
unsafe { xenora_session_create_texture(sess, 2, 2, initial.as_ptr(), &mut res) },
XENORA_OK,
"create failed at cycle {}",
i
);
// Verify slot index is reused (res_idx is 0)
let slot_idx = (res & 0xFFFF_FFFF) as usize;
assert_eq!(slot_idx, 0, "slot index leaked at cycle {}", i);
assert_eq!(
unsafe { xenora_session_update_texture(sess, res, 0, 0, 1, 1, update.as_ptr(), 4) },
XENORA_OK
);
let mut out = [0u8; 16];
let (mut w, mut h) = (0u32, 0u32);
assert_eq!(
unsafe {
xenora_session_render_textured(sess, res, out.as_mut_ptr(), 16, &mut w, &mut h)
},
XENORA_OK
);
assert_eq!(xenora_session_destroy_resource(sess, res), XENORA_OK);
}
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
}
#[test]
fn textured_pe_fixture_executes_dynamic_updates_and_retirement() {
let _guard = SERIAL.lock().unwrap();
let sess = session();
let mut out_rgba = [0u8; 16];
let mut out_w = 0u32;
let mut out_h = 0u32;
assert_eq!(
unsafe {
xenora_session_run_textured_fixture(
sess,
out_rgba.as_mut_ptr(),
16,
&mut out_w,
&mut out_h,
)
},
XENORA_OK
);
assert_eq!(out_w, 2);
assert_eq!(out_h, 2);
let expected_final: [u8; 16] = [
255, 255, 0, 255, // (0,0) yellow
0, 255, 255, 255, // (1,0) cyan
255, 0, 255, 255, // (0,1) magenta
64, 64, 64, 255, // (1,1) dark grey
];
assert_eq!(
out_rgba, expected_final,
"guest textured fixture read-back frame mismatch"
);
assert_eq!(xenora_session_destroy(sess), XENORA_OK);
}
+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");
}
}
-10
View File
@@ -17,16 +17,6 @@ VARIANTS = (
("V_ADD_NC_U32", "ENC_VOP3"),
("S_ENDPGM", "ENC_SOPP"),
("S_MOV_B32", "ENC_SOP1"),
("S_CMP_EQ_U32", "ENC_SOPC"),
("S_ADD_U32", "ENC_SOP2"),
("S_SUB_U32", "ENC_SOP2"),
("S_ADD_I32", "ENC_SOP2"),
("S_SUB_I32", "ENC_SOP2"),
("S_ADDC_U32", "ENC_SOP2"),
("S_SUBB_U32", "ENC_SOP2"),
("S_AND_B32", "ENC_SOP2"),
("S_OR_B32", "ENC_SOP2"),
("S_XOR_B32", "ENC_SOP2"),
("S_CBRANCH_SCC0", "ENC_SOPP"),
("S_CBRANCH_EXECZ", "ENC_SOPP"),
("S_CBRANCH_VCCZ", "ENC_SOPP"),
+1395
View File
File diff suppressed because it is too large. Load diff
+52
View File
@@ -0,0 +1,52 @@
# Declarative semantic registry for gfx1030 (AMD RDNA 2) instruction forms.
#
# Data only: no code strings, no expressions. Every value is a member of a closed
# vocabulary that crates/isa/generate_semantics.py validates and turns into static
# Rust tables (crates/isa/src/semantics_gen.rs). Identity, family, opcode and
# operand facts are cross-checked against the pinned AMD XML snapshot
# (crates/isa/data/rdna2.jsonl); behaviour comes from the public AMD guide cited
# 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 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]
title = "AMD RDNA 2 Instruction Set Architecture Reference Guide"
file = "rdna2-shader-instruction-set-architecture.pdf"
pages = 291
[documents.xml]
title = "AMD RDNA 2 machine-readable ISA (pinned XML)"
file = "amdgpu_isa_rdna2.xml"
# 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 (closed vocabulary in generate_semantics.py OPERATIONS)
# signedness unsigned | signed | bitwise (bitwise iff a logical operation)
# carry_in none | scc (scc for unsigned add/sub carry and the cselect condition)
# width operand and result width in bits
# scc unchanged | carry_out | borrow | signed_overflow | nonzero | relation | selected_src0
# vcc, exec unchanged (stated, not implied) | lane_mask (vcc of a Wave32 VOPC compare)
# wave any | wave32 (wave32 exactly for the VOPC lane-mask compares)
# 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
+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"]
+225
View File
@@ -0,0 +1,225 @@
# 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"]
+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"]
+63 -157
View File
@@ -3,17 +3,23 @@
use std::fmt;
pub mod meta;
pub mod primitive;
mod rdna2;
pub mod semantics;
#[rustfmt::skip]
mod rdna2_meta;
#[rustfmt::skip]
mod semantics_gen;
pub use rdna2::{
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_ADD_I32, S_ADD_U32, S_ADDC_U32,
S_AND_B32, S_BRANCH, S_CBRANCH_EXECZ, S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM,
S_MOV_B32, S_OR_B32, S_SUB_I32, S_SUB_U32, S_SUBB_U32, S_WAITCNT, S_WAITCNT_VSCNT, S_XOR_B32,
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,
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,
};
pub use semantics_gen::{
ScalarAluOp, ScalarCompareOp, ScalarUnaryOp, VectorAluOp, VectorAluVop3Op, VectorCompareOp,
};
/// SGPR index of `vcc_lo`, the Wave32 vector condition code.
@@ -89,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).
@@ -104,144 +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(),
}
}
}
/// SOP2 32-bit integer operations in the supported scalar subset.
///
/// SCC behaviour follows the pinned AMD RDNA 2 XML descriptions: additions
/// store the carry-out, subtractions the borrow, ADDC and SUBB also consume
/// SCC as carry-in or borrow-in, signed forms store signed overflow (RDNA 2 ISA
/// guide 12.1), and bitwise operations set SCC iff the result is nonzero. See
/// docs/shaders/scalar-alu.md for the sources.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ScalarAluOp {
/// `s_add_u32`: D = S0 + S1, SCC = carry-out.
AddU32,
/// `s_sub_u32`: D = S0 - S1, SCC = borrow (S1 > S0).
SubU32,
/// `s_add_i32`: D = S0 + S1, SCC = signed overflow.
AddI32,
/// `s_sub_i32`: D = S0 - S1, SCC = signed overflow.
SubI32,
/// `s_addc_u32`: D = S0 + S1 + SCC, SCC = carry-out.
AddcU32,
/// `s_subb_u32`: D = S0 - S1 - SCC, SCC = borrow.
SubbU32,
/// `s_and_b32`: D = S0 & S1, SCC = D != 0.
AndB32,
/// `s_or_b32`: D = S0 | S1, SCC = D != 0.
OrB32,
/// `s_xor_b32`: D = S0 ^ S1, SCC = D != 0.
XorB32,
}
impl ScalarAluOp {
/// Lower-case mnemonic.
pub fn mnemonic(self) -> &'static str {
match self {
Self::AddU32 => "s_add_u32",
Self::SubU32 => "s_sub_u32",
Self::AddI32 => "s_add_i32",
Self::SubI32 => "s_sub_i32",
Self::AddcU32 => "s_addc_u32",
Self::SubbU32 => "s_subb_u32",
Self::AndB32 => "s_and_b32",
Self::OrB32 => "s_or_b32",
Self::XorB32 => "s_xor_b32",
}
}
/// The 32-bit result and the new SCC, with `carry_in` the SCC read by
/// ADDC and SUBB (ignored by the other operations).
pub fn evaluate(self, src0: u32, src1: u32, carry_in: bool) -> (u32, bool) {
let carry = u32::from(carry_in && self.reads_scc());
match self {
Self::AddU32 | Self::AddcU32 => {
let (partial, first) = src0.overflowing_add(src1);
let (value, second) = partial.overflowing_add(carry);
(value, first || second)
}
Self::SubU32 | Self::SubbU32 => {
let (partial, first) = src0.overflowing_sub(src1);
let (value, second) = partial.overflowing_sub(carry);
(value, first || second)
}
Self::AddI32 => {
let (value, overflow) = (src0 as i32).overflowing_add(src1 as i32);
(value as u32, overflow)
}
Self::SubI32 => {
let (value, overflow) = (src0 as i32).overflowing_sub(src1 as i32);
(value as u32, overflow)
}
Self::AndB32 => (src0 & src1, src0 & src1 != 0),
Self::OrB32 => (src0 | src1, src0 | src1 != 0),
Self::XorB32 => (src0 ^ src1, src0 ^ src1 != 0),
}
}
/// Whether the operation reads SCC as a carry-in or borrow-in.
pub fn reads_scc(self) -> bool {
matches!(self, Self::AddcU32 | Self::SubbU32)
}
/// Never holds (VOPC F, offset 0).
False,
/// Always holds (VOPC T, offset 7).
True,
}
/// Output targeted by a supported uncompressed four-component export.
@@ -281,19 +154,34 @@ 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 },
/// SOP2 32-bit integer operation writing a normal SGPR (s0-s105) and SCC.
/// SOP1 32-bit unary integer operation writing a normal SGPR (s0-s105) and,
/// for some operations, SCC.
ScalarUnary {
op: ScalarUnaryOp,
dst: u8,
src: ScalarSource,
},
/// SOP2 32-bit integer operation writing a normal SGPR (s0-s105) and, for
/// most operations, SCC; `s_cselect_b32` also reads SCC.
ScalarAlu {
op: ScalarAluOp,
dst: u8,
src0: ScalarSource,
src1: ScalarSource,
},
/// SOPC 32-bit equality comparison writing SCC.
ScalarCompareEqU32 {
/// SOPC 32-bit integer compare writing only SCC.
ScalarCompare {
op: ScalarCompareOp,
src0: ScalarSource,
src1: ScalarSource,
},
@@ -304,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.
@@ -380,11 +277,13 @@ 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::ScalarCompareEqU32 { .. } => "s_cmp_eq_u32",
Self::VectorCompare { op, .. } => op.mnemonic(),
Self::ScalarCompare { 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",
@@ -435,7 +334,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::VectorAluVop3 {
dst, src0, src1, ..
}
| Self::VectorLshlrevB32 { dst, src0, src1 }
| Self::VectorLshrrevB32 { dst, src0, src1 }
| Self::VectorAshrrevI32 { dst, src0, src1 }
@@ -446,16 +347,21 @@ impl fmt::Display for Instruction {
| Self::VectorMulF32 { dst, src0, src1 } => {
write!(formatter, " v{dst}, v{src0}, v{src1}")
}
Self::ScalarMoveB32 { dst, src } => {
Self::ScalarMoveB32 { dst, src } | Self::ScalarUnary { dst, src, .. } => {
write!(formatter, " {}, {src}", ScalarDestination(dst))
}
Self::ScalarAlu {
dst, src0, src1, ..
} => write!(formatter, " {}, {src0}, {src1}", ScalarDestination(dst)),
Self::ScalarCompareEqU32 { src0, src1 } => write!(formatter, " {src0}, {src1}"),
Self::ScalarCompare { src0, src1, .. } => write!(formatter, " {src0}, {src1}"),
Self::VectorCompare { src0, src1, .. } => {
write!(formatter, " vcc_lo, {src0}, v{src1}")
}
Self::VectorAlu {
dst, src0, src1, ..
} => {
write!(formatter, " v{dst}, {src0}, v{src1}")
}
Self::Branch { target }
| Self::BranchSccZero { target }
| Self::BranchExecZero { target }
+328
View File
@@ -0,0 +1,328 @@
//! Reusable integer semantic primitives selected by the generated registry dispatch.
//!
//! Each function implements one closed [`crate::semantics::Operation`] at one
//! signedness, with the condition-code rule the RDNA 2 guide gives for it
//! (section 5.3, "Scalar Condition Code", and the SOP2 pseudocode in 12.1).
//! Forms share a primitive only when their declared operation, signedness and
//! SCC effect are identical; the generator never selects one by mnemonic.
/// Unsigned `a + b + carry_in` and the carry-out of bit 31.
pub const fn add_carry_u32(a: u32, b: u32, carry_in: bool) -> (u32, bool) {
let (partial, first) = a.overflowing_add(b);
let (value, second) = partial.overflowing_add(carry_in as u32);
(value, first || second)
}
/// Unsigned `a - b - borrow_in` and the borrow (`b + borrow_in > a`).
pub const fn sub_borrow_u32(a: u32, b: u32, borrow_in: bool) -> (u32, bool) {
let (partial, first) = a.overflowing_sub(b);
let (value, second) = partial.overflowing_sub(borrow_in as u32);
(value, first || second)
}
/// Two's-complement `a + b` and whether the exact sum leaves the i32 range.
pub const fn add_overflow_i32(a: u32, b: u32) -> (u32, bool) {
let (value, overflow) = (a as i32).overflowing_add(b as i32);
(value as u32, overflow)
}
/// Two's-complement `a - b` and whether the exact difference leaves the i32 range.
pub const fn sub_overflow_i32(a: u32, b: u32) -> (u32, bool) {
let (value, overflow) = (a as i32).overflowing_sub(b as i32);
(value as u32, overflow)
}
/// Bitwise AND and whether the result is nonzero.
pub const fn and_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = a & b;
(value, value != 0)
}
/// Bitwise OR and whether the result is nonzero.
pub const fn or_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = a | b;
(value, value != 0)
}
/// Bitwise XOR and whether the result is nonzero.
pub const fn xor_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = a ^ b;
(value, value != 0)
}
/// Bitwise `a & !b` and whether the result is nonzero.
pub const fn andn2_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = a & !b;
(value, value != 0)
}
/// Bitwise `a | !b` and whether the result is nonzero.
pub const fn orn2_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = a | !b;
(value, value != 0)
}
/// Bitwise `!(a & b)` and whether the result is nonzero.
pub const fn nand_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = !(a & b);
(value, value != 0)
}
/// Bitwise `!(a | b)` and whether the result is nonzero.
pub const fn nor_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = !(a | b);
(value, value != 0)
}
/// Bitwise `!(a ^ b)` and whether the result is nonzero.
pub const fn xnor_nonzero_b32(a: u32, b: u32) -> (u32, bool) {
let value = !(a ^ b);
(value, value != 0)
}
/// `a << count` and whether the result is nonzero. The caller masks the count
/// to the declared count width, so `count` is below 32.
pub const fn lshl_nonzero_b32(a: u32, count: u32) -> (u32, bool) {
let value = a << count;
(value, value != 0)
}
/// Logical `a >> count` (zero fill) and whether the result is nonzero; `count` is below 32.
pub const fn lshr_nonzero_b32(a: u32, count: u32) -> (u32, bool) {
let value = a >> count;
(value, value != 0)
}
/// Arithmetic `a >> count` (sign fill) and whether the result is nonzero; `count` is below 32.
pub const fn ashr_nonzero_i32(a: u32, count: u32) -> (u32, bool) {
let value = ((a as i32) >> count) as u32;
(value, value != 0)
}
/// 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
}
/// `a != b` on the raw bits (the guide's LG, "less or greater").
pub const fn ne_b32(a: u32, b: u32) -> bool {
a != b
}
/// Two's-complement `a > b`.
pub const fn gt_i32(a: u32, b: u32) -> bool {
(a as i32) > (b as i32)
}
/// Two's-complement `a >= b`.
pub const fn ge_i32(a: u32, b: u32) -> bool {
(a as i32) >= (b as i32)
}
/// Two's-complement `a < b`.
pub const fn lt_i32(a: u32, b: u32) -> bool {
(a as i32) < (b as i32)
}
/// Two's-complement `a <= b`.
pub const fn le_i32(a: u32, b: u32) -> bool {
(a as i32) <= (b as i32)
}
/// Unsigned `a > b`.
pub const fn gt_u32(a: u32, b: u32) -> bool {
a > b
}
/// Unsigned `a >= b`.
pub const fn ge_u32(a: u32, b: u32) -> bool {
a >= b
}
/// Unsigned `a < b`.
pub const fn lt_u32(a: u32, b: u32) -> bool {
a < b
}
/// Unsigned `a <= b`.
pub const fn le_u32(a: u32, b: u32) -> bool {
a <= b
}
/// `!a` and whether the result is nonzero.
pub const fn not_nonzero_b32(a: u32) -> (u32, bool) {
let value = !a;
(value, value != 0)
}
/// `a` with bit `i` moved to bit `31 - i`.
pub const fn brev_b32(a: u32) -> u32 {
a.reverse_bits()
}
/// Number of zero bits and whether that count is nonzero.
pub const fn bcnt0_nonzero_b32(a: u32) -> (u32, bool) {
let value = a.count_zeros();
(value, value != 0)
}
/// Number of one bits and whether that count is nonzero.
pub const fn bcnt1_nonzero_b32(a: u32) -> (u32, bool) {
let value = a.count_ones();
(value, value != 0)
}
/// Index of the lowest zero bit, or `0xffffffff` (-1) when every bit is one.
pub const fn ff0_b32(a: u32) -> u32 {
if a == u32::MAX {
u32::MAX
} else {
a.trailing_ones()
}
}
/// Index of the lowest one bit, or `0xffffffff` (-1) when every bit is zero.
pub const fn ff1_b32(a: u32) -> u32 {
if a == 0 { u32::MAX } else { a.trailing_zeros() }
}
/// Zeros above the highest one bit, or `0xffffffff` (-1) when `a` is zero.
pub const fn flbit_b32(a: u32) -> u32 {
if a == 0 { u32::MAX } else { a.leading_zeros() }
}
/// Bits above the highest bit that differs from the sign bit, or `0xffffffff`
/// (-1) when every bit equals the sign bit (`a` is 0 or -1).
pub const fn flbit_i32(a: u32) -> u32 {
let differing = if a >> 31 == 0 { a } else { !a };
if differing == 0 {
u32::MAX
} else {
differing.leading_zeros()
}
}
/// The low `bits` of `a` sign-extended to 32 bits; `bits` is 8 or 16.
pub const fn sext_i32(a: u32, bits: u32) -> u32 {
let shift = 32 - bits;
(((a << shift) as i32) >> shift) as u32
}
/// Two's-complement absolute value (wrapping, so `0x80000000` stays) and
/// whether the result is nonzero.
pub const fn abs_nonzero_i32(a: u32) -> (u32, bool) {
let value = (a as i32).wrapping_abs() as u32;
(value, value != 0)
}
/// Two's-complement minimum and whether S0 was strictly smaller (so equal
/// operands give S1 and `false`).
pub const fn min_i32(a: u32, b: u32) -> (u32, bool) {
let first = (a as i32) < (b as i32);
(if first { a } else { b }, first)
}
/// Unsigned minimum and whether S0 was strictly smaller.
pub const fn min_u32(a: u32, b: u32) -> (u32, bool) {
let first = a < b;
(if first { a } else { b }, first)
}
/// Two's-complement maximum and whether S0 was strictly greater (so equal
/// operands give S1 and `false`).
pub const fn max_i32(a: u32, b: u32) -> (u32, bool) {
let first = (a as i32) > (b as i32);
(if first { a } else { b }, first)
}
/// Unsigned maximum and whether S0 was strictly greater.
pub const fn max_u32(a: u32, b: u32) -> (u32, bool) {
let first = a > b;
(if first { a } else { b }, first)
}
/// `a` when `condition` (SCC) is set, otherwise `b`.
pub const fn cselect_b32(a: u32, b: u32, condition: bool) -> u32 {
if condition { a } else { b }
}
/// `((1 << a[4:0]) - 1) << b[4:0]`: a mask of `a[4:0]` ones starting at bit `b[4:0]`.
pub const fn bfm_b32(a: u32, b: u32) -> u32 {
((1u32 << (a & 0x1f)) - 1) << (b & 0x1f)
}
/// The low 32 bits of the product (identical for signed and unsigned operands).
pub const fn mul_lo_i32(a: u32, b: u32) -> u32 {
a.wrapping_mul(b)
}
/// The high 32 bits of the unsigned 64-bit product.
pub const fn mul_hi_u32(a: u32, b: u32) -> u32 {
((a as u64 * b as u64) >> 32) as u32
}
/// The high 32 bits of the two's-complement 64-bit product.
pub const fn mul_hi_i32(a: u32, b: u32) -> u32 {
((a as i32 as i64 * b as i32 as i64) >> 32) as u32
}
/// The `bfe` field descriptor: offset `b[4:0]` and width `b[22:16]` (0-127).
const fn bfe_field(b: u32) -> (u32, u32) {
(b & 0x1f, (b >> 16) & 0x7f)
}
/// Unsigned bit-field extract: `(a >> offset) & ((1 << width) - 1)`, where a
/// width of 32 or more keeps every shifted bit; and whether the result is nonzero.
pub const fn bfe_nonzero_u32(a: u32, b: u32) -> (u32, bool) {
let (offset, width) = bfe_field(b);
let shifted = a >> offset;
let value = if width == 0 {
0
} else if width >= 32 {
shifted
} else {
shifted & ((1 << width) - 1)
};
(value, value != 0)
}
/// Signed bit-field extract: `a` shifted arithmetically by the offset, the low
/// `width` bits kept and sign-extended from bit `width - 1` (a width of 32 or
/// more keeps the whole shifted word); and whether the result is nonzero.
pub const fn bfe_nonzero_i32(a: u32, b: u32) -> (u32, bool) {
let (offset, width) = bfe_field(b);
let shifted = ((a as i32) >> offset) as u32;
let value = if width == 0 {
0
} else if width >= 32 {
shifted
} else {
let unused = 32 - width;
(((shifted << unused) as i32) >> unused) as u32
};
(value, value != 0)
}
/// `|a - b|` of the wrapped 32-bit difference (so `0x80000000` stays) and
/// whether the result is nonzero.
pub const fn absdiff_nonzero_i32(a: u32, b: u32) -> (u32, bool) {
let value = (a.wrapping_sub(b) as i32).unsigned_abs();
(value, value != 0)
}
/// `(a << shift) + b` and the carry out of the exact sum, which counts the bits
/// shifted out of `a`; `shift` is 1 to 4.
pub const fn lshl_add_carry_u32(a: u32, b: u32, shift: u32) -> (u32, bool) {
let sum = ((a as u64) << shift) + b as u64;
(sum as u32, sum >> 32 != 0)
}
-50
View File
@@ -45,56 +45,6 @@ pub const S_MOV_B32: Opcode = Opcode {
bits: 0xbe800300,
bytes: 4,
};
pub const S_CMP_EQ_U32: Opcode = Opcode {
mask: 0xffff0000,
bits: 0xbf060000,
bytes: 4,
};
pub const S_ADD_U32: Opcode = Opcode {
mask: 0xff800000,
bits: 0x80000000,
bytes: 4,
};
pub const S_SUB_U32: Opcode = Opcode {
mask: 0xff800000,
bits: 0x80800000,
bytes: 4,
};
pub const S_ADD_I32: Opcode = Opcode {
mask: 0xff800000,
bits: 0x81000000,
bytes: 4,
};
pub const S_SUB_I32: Opcode = Opcode {
mask: 0xff800000,
bits: 0x81800000,
bytes: 4,
};
pub const S_ADDC_U32: Opcode = Opcode {
mask: 0xff800000,
bits: 0x82000000,
bytes: 4,
};
pub const S_SUBB_U32: Opcode = Opcode {
mask: 0xff800000,
bits: 0x82800000,
bytes: 4,
};
pub const S_AND_B32: Opcode = Opcode {
mask: 0xff800000,
bits: 0x87000000,
bytes: 4,
};
pub const S_OR_B32: Opcode = Opcode {
mask: 0xff800000,
bits: 0x88000000,
bytes: 4,
};
pub const S_XOR_B32: Opcode = Opcode {
mask: 0xff800000,
bits: 0x89000000,
bytes: 4,
};
pub const S_CBRANCH_SCC0: Opcode = Opcode {
mask: 0xffff0000,
bits: 0xbf840000,
+283
View File
@@ -0,0 +1,283 @@
//! Typed vocabulary of the declarative semantic registry (`crates/isa/semantics/rdna2.toml`).
//!
//! The registry is data. `crates/isa/generate_semantics.py` validates it against
//! this closed vocabulary and the pinned AMD XML snapshot, then emits
//! `semantics_gen.rs`: the typed operation enums, their opcode dispatch and one
//! static [`FormSemantics`] row per form. Nothing here interprets metadata at run
//! time; the decoder and translator call the generated `const fn`s and `match`es.
//!
//! The reference interpreter (`crates/ref`) and the independent interpreter
//! (`tests/validation/independent_ref.rs`) must not use this module.
use crate::CompareRelation;
use crate::meta::EncodingFamily;
pub use crate::semantics_gen::{FORM_IDS, FORMS, GENERATED_SCHEMA};
/// Version of the registry schema this crate was generated against.
pub const SCHEMA: u32 = 1;
/// Reusable semantic primitive selected by a form. Closed: the generator rejects
/// any other name, and each primitive has one implementation in `primitive.rs`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Operation {
/// Integer addition.
Add,
/// Integer subtraction.
Sub,
/// Bitwise AND.
And,
/// Bitwise OR.
Or,
/// Bitwise exclusive OR.
Xor,
/// Bitwise AND with the complement of S1.
AndNot,
/// Bitwise OR with the complement of S1.
OrNot,
/// Complement of bitwise AND.
Nand,
/// Complement of bitwise OR.
Nor,
/// Complement of bitwise exclusive OR.
Xnor,
/// Shift S0 left by the masked count in S1, filling with zeros.
ShiftLeft,
/// Shift S0 right by the masked count in S1, filling with zeros.
LogicalShiftRight,
/// Shift S0 right by the masked count in S1, filling with its sign bit.
ArithmeticShiftRight,
/// Compare S0 with S1 under the form's relation; writes only SCC.
Compare,
/// Bitwise complement of S0.
Not,
/// S0 with its bit order reversed.
ReverseBits,
/// Number of zero bits in S0.
CountZeros,
/// Number of one bits in S0.
CountOnes,
/// Index of the lowest zero bit of S0, or -1 when there is none.
FindFirstZero,
/// Index of the lowest one bit of S0, or -1 when there is none.
FindFirstOne,
/// Unsigned: count of zeros above the highest one bit; signed: count of bits
/// above the highest bit that differs from the sign bit. -1 when none.
FindLastBit,
/// Sign-extend the low `source_bits` of S0 to 32 bits.
SignExtend,
/// Two's-complement absolute value; the most negative value maps to itself.
Absolute,
/// S0 when it is strictly less than S1, otherwise S1.
Minimum,
/// S0 when it is strictly greater than S1, otherwise S1.
Maximum,
/// S0 when SCC is set, otherwise S1.
Select,
/// `((1 << S0[4:0]) - 1) << S1[4:0]`.
BitfieldMask,
/// Low 32 bits of the product.
Multiply,
/// High 32 bits of the 64-bit product.
MultiplyHigh,
/// The field of S0 at offset S1[4:0] with width S1[22:16]; sign-extended when signed.
BitfieldExtract,
/// Absolute value of the wrapped 32-bit difference S0 - S1.
AbsoluteDifference,
/// `(S0 << shift_amount) + S1`.
ShiftLeftAdd,
/// Low 32 bits of the product of S0[23:0] and S1[23:0] (sign-extended when signed).
Multiply24,
/// Bits 63:32 of the product of S0[23:0] and S1[23:0] (sign-extended when signed).
MultiplyHigh24,
}
/// The per-lane integer operation a vector form lowers to. One reusable MSL
/// template exists per variant; a form selects it through its declared
/// operation and signedness, never through its opcode.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VectorBinary {
/// Wrapping `a + b`.
Add,
/// Wrapping `a - b`.
Sub,
/// `!(a ^ b)`.
Xnor,
/// Two's-complement minimum.
MinSigned,
/// Unsigned minimum.
MinUnsigned,
/// Two's-complement maximum.
MaxSigned,
/// Unsigned maximum.
MaxUnsigned,
/// Low 32 bits of `sext(a[23:0]) * sext(b[23:0])`.
Mul24Signed,
/// Low 32 bits of `a[23:0] * b[23:0]`.
Mul24Unsigned,
/// Bits 63:32 of `sext(a[23:0]) * sext(b[23:0])`.
MulHi24Signed,
/// Bits 63:32 of `a[23:0] * b[23:0]`.
MulHi24Unsigned,
}
/// How the operands are interpreted. `Bitwise` exactly when the operation is logical.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Signedness {
/// Unsigned integers.
Unsigned,
/// Two's-complement integers.
Signed,
/// Untyped bits.
Bitwise,
}
/// Whether the operation reads SCC.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CarryIn {
/// SCC is not read.
None,
/// SCC as carry-in (add), borrow-in (sub) or the select condition (select).
Scc,
}
/// What a form writes to SCC.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SccEffect {
/// SCC is not written.
Unchanged,
/// Unsigned carry-out of the top bit.
CarryOut,
/// Unsigned borrow (subtrahend plus borrow-in exceeds the minuend).
Borrow,
/// Two's-complement overflow of the exact result.
SignedOverflow,
/// The result is not zero.
Nonzero,
/// The compare's relation holds for S0 and S1.
Relation,
/// The result is S0 by the strict comparison (min, max): equal operands give 0.
SelectedSrc0,
}
/// What a form writes to VCC or EXEC.
#[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.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Wave {
/// Behaviour does not depend on the wave size.
Any,
/// Only Wave32 behaviour is declared; Wave64 stays unsupported.
Wave32,
}
/// Shared operand rule. The decoder implements each rule once.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum OperandRule {
/// SOP2: SDST is s0-s105; SSRC0/SSRC1 are s0-s105, inline integers -16..64
/// or one literal word. Everything else is rejected as unsupported.
Sop2Sgpr,
/// SOPC: no destination; SSRC0/SSRC1 as for SOP2 sources (s0-s105, inline
/// integers -16..64 or one literal word). Everything else is rejected.
SopcScalar,
/// SOP1 unary: SDST is s0-s105; SSRC0 is s0-s105, an inline integer -16..64 or
/// a literal word. Everything else is rejected as unsupported.
Sop1Sgpr,
/// 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,
}
/// Evidence a form needs before it counts as verified.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Evidence {
/// `crates/ref` lockstep reference.
Reference,
/// `tests/validation/independent_ref.rs`.
Independent,
/// Native Metal known-answer runs.
Metal,
/// LLVM assembler/disassembler encoding agreement.
LlvmEncoding,
}
/// Public document a [`SpecRef`] points at.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Document {
/// AMD RDNA 2 ISA reference guide (PDF).
Guide,
/// Pinned AMD machine-readable XML.
Xml,
}
/// One public specification reference.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct SpecRef {
/// Source document.
pub document: Document,
/// Section number, for example `"12.1"`.
pub section: &'static str,
/// Page in the document, or 0 when the page has not been recorded.
pub page: u16,
}
/// One validated registry row, emitted as a static table by the generator.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct FormSemantics {
/// XML instruction name, the stable form identity.
pub name: &'static str,
/// Encoding family (matches [`crate::meta::FORMS`]).
pub family: EncodingFamily,
/// Opcode within the family.
pub opcode: u16,
/// Primitive.
pub operation: Operation,
/// Operand interpretation.
pub signedness: Signedness,
/// SCC input.
pub carry_in: CarryIn,
/// Operand and result width in bits.
pub width: u8,
/// Low bits of S1 used as the shift count by shift operations; 0 otherwise.
pub shift_count_bits: u8,
/// Fixed left shift of S0 for shift-and-add operations (1 to 4); 0 otherwise.
pub shift_amount: u8,
/// Whether the operation reads its sources in reverse order (`D = op(S1, S0)`).
pub swap_sources: bool,
/// Low bits of S0 that the operation reads: `width`, or 8 or 16 for sign extension.
pub source_bits: u8,
/// The relation tested by compares (S0 on the left); `None` otherwise.
pub relation: Option<CompareRelation>,
/// SCC write.
pub scc: SccEffect,
/// VCC write.
pub vcc: MaskEffect,
/// EXEC write.
pub exec: MaskEffect,
/// Wave-size restriction.
pub wave: Wave,
/// Operand rule.
pub operands: OperandRule,
/// Public references.
pub spec: &'static [SpecRef],
/// Required evidence.
pub verify: &'static [Evidence],
}
File diff suppressed because it is too large. Load diff
+201
View File
@@ -0,0 +1,201 @@
//! 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, 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() {
assert_eq!(GENERATED_SCHEMA, SCHEMA);
assert_eq!(FORM_IDS.len(), FORMS.len());
for (row, (name, family)) in FORMS.iter().zip(FORM_IDS) {
assert_eq!((row.name, row.family), (name, family));
let meta = META_FORMS
.iter()
.find(|form| form.name == row.name && form.family == row.family)
.unwrap_or_else(|| panic!("{} is not an identified form", row.name));
assert_eq!(meta.opcode, row.opcode, "{}", row.name);
}
}
/// Every word of `family` that the XML metadata identifies selects an operation
/// exactly when the registry declares that form, and no 32-bit word of another
/// family selects one.
fn dispatch_selects_exactly(family: EncodingFamily, select: impl Fn(u32) -> Option<&'static str>) {
let declared: Vec<_> = FORMS.iter().filter(|row| row.family == family).collect();
let mut selected = 0;
for meta in META_FORMS.iter().filter(|form| form.family == family) {
match select(meta.bits as u32) {
Some(name) => {
assert_eq!(name, meta.name);
selected += 1;
}
None => assert!(
declared.iter().all(|row| row.name != meta.name),
"{} is declared but not dispatched",
meta.name
),
}
}
assert_eq!(selected, declared.len());
for meta in META_FORMS
.iter()
.filter(|form| form.family != family && form.bytes == 4)
{
assert_eq!(select(meta.bits as u32), None, "{}", meta.name);
}
}
#[test]
fn scalar_alu_dispatch_selects_exactly_the_registry_sop2_forms() {
for op in ScalarAluOp::ALL {
let row = op.semantics();
assert_eq!(row.family, EncodingFamily::Sop2);
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
assert_eq!(op.reads_scc(), row.carry_in == CarryIn::Scc);
assert_eq!(op.writes_scc(), row.scc != SccEffect::Unchanged);
}
dispatch_selects_exactly(EncodingFamily::Sop2, |word| {
ScalarAluOp::from_word(word).map(|op| op.semantics().name)
});
}
#[test]
fn scalar_compare_dispatch_selects_exactly_the_registry_sopc_forms() {
for op in ScalarCompareOp::ALL {
let row = op.semantics();
assert_eq!(row.family, EncodingFamily::Sopc);
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
assert_eq!(row.relation, Some(op.relation()));
}
dispatch_selects_exactly(EncodingFamily::Sopc, |word| {
ScalarCompareOp::from_word(word).map(|op| op.semantics().name)
});
}
#[test]
fn scalar_unary_dispatch_selects_exactly_the_registry_sop1_forms() {
for op in ScalarUnaryOp::ALL {
let row = op.semantics();
assert_eq!(row.family, EncodingFamily::Sop1);
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
assert_eq!(op.writes_scc(), row.scc != SccEffect::Unchanged);
}
// s_mov_b32 (opcode 3) stays hand-written, so it must not be dispatched here.
dispatch_selects_exactly(EncodingFamily::Sop1, |word| {
ScalarUnaryOp::from_word(word).map(|op| op.semantics().name)
});
}
#[test]
fn vector_alu_dispatch_selects_exactly_the_registry_vop2_forms() {
for op in VectorAluOp::ALL {
let row = op.semantics();
assert_eq!(row.family, EncodingFamily::Vop2);
assert_eq!(row.name.to_ascii_lowercase(), op.mnemonic());
assert_eq!(op.assembly_name(), format!("{}_e32", op.mnemonic()));
assert_eq!(op.swaps_sources(), row.swap_sources);
assert_eq!(row.scc, SccEffect::Unchanged);
}
// The hand-written VOP2 forms (v_and_b32, v_add_f32, ...) must not be
// dispatched here.
dispatch_selects_exactly(EncodingFamily::Vop2, |word| {
VectorAluOp::from_word(word).map(|op| op.semantics().name)
});
}
#[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(
+227 -497
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.
@@ -54,12 +56,33 @@ impl Register {
}
/// 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.
@@ -71,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 {
@@ -83,6 +109,8 @@ impl CpuState {
flags: RFlags::default(),
gs_base: 0,
fs_base: 0,
xmm: [0; 16],
mxcsr: Mxcsr::default(),
}
}
@@ -105,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 {
@@ -117,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")
}
}
}
}
@@ -137,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;
@@ -153,6 +202,167 @@ mod layout_tests {
}
}
#[cfg(test)]
mod prefix_tests {
use super::{CpuState, ExitReason, Interpreter, Register};
use crate::memory::{GuestMemory, MemoryPermissions};
const CODE_BASE: u64 = 0x1000;
const CODE_SIZE: usize = 0x1000;
const STACK_BASE: u64 = 0x8000_0000;
const STACK_SIZE: usize = 0x10000;
const FS_BASE: u64 = 0x9000;
const GS_BASE: u64 = 0xA000;
/// A guest memory image with executable code, a stack and distinct FS and
/// GS bases.
fn memory_with_code(code: &[u8]) -> GuestMemory {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(
CODE_BASE,
CODE_SIZE,
MemoryPermissions::READ_WRITE_EXECUTE,
code,
)
.expect("code region");
memory
.map_region(STACK_BASE, STACK_SIZE, MemoryPermissions::READ_WRITE)
.expect("stack region");
// The segment bases are distinct so a swapped prefix is visible.
memory
.map_region(FS_BASE, 0x1000, MemoryPermissions::READ_WRITE)
.expect("fs region");
memory
.map_region(GS_BASE, 0x1000, MemoryPermissions::READ_WRITE)
.expect("gs region");
memory
}
/// Run `code` on the interpreter and return the final state and exit reason.
fn run(code: &[u8]) -> (CpuState, ExitReason) {
let mut memory = memory_with_code(code);
let cpu = CpuState::new(CODE_BASE, STACK_BASE + 0x8000);
let mut interp = Interpreter::new(cpu, &mut memory, 64);
let result = interp.run();
(result.final_state, result.exit_reason)
}
/// `mov r8, imm64`: 49 B8 <imm64>.
fn mov_r8_imm64(value: u64) -> Vec<u8> {
let mut code = vec![0x49, 0xB8];
code.extend_from_slice(&value.to_le_bytes());
code
}
/// `mov rbx, imm64`: 48 BB <imm64>.
fn mov_rbx_imm64(value: u64) -> Vec<u8> {
let mut code = vec![0x48, 0xBB];
code.extend_from_slice(&value.to_le_bytes());
code
}
/// `mov rax, imm64`: 48 B8 <imm64>.
fn mov_rax_imm64(value: u64) -> Vec<u8> {
let mut code = vec![0x48, 0xB8];
code.extend_from_slice(&value.to_le_bytes());
code
}
/// REX.B extends the ModRM `rm` field, so `rm=0` selects r8.
///
/// Encoding 49 89 D8 is `mov r8, rbx`.
#[test]
fn rex_b_extends_the_rm_field_to_r8() {
let mut code = mov_rbx_imm64(0x1122_3344_5566_7788);
code.extend_from_slice(&[0x49, 0x89, 0xD8]); // mov r8, rbx
code.push(0xF4); // hlt
let (state, reason) = run(&code);
assert_eq!(reason, ExitReason::Halt);
assert_eq!(state.get(Register::Rbx), 0x1122_3344_5566_7788);
assert_eq!(state.get(Register::R8), 0x1122_3344_5566_7788);
// No prefix in this encoding selects r9.
assert_eq!(state.get(Register::R9), 0);
}
/// REX.R extends the ModRM `reg` field, so `reg=0` selects r8.
///
/// Encoding 4C 89 C3 is `mov rbx, r8`.
#[test]
fn rex_r_extends_the_reg_field_to_r8() {
let mut code = mov_r8_imm64(0x1122_3344_5566_7788);
code.extend_from_slice(&[0x4C, 0x89, 0xC3]); // mov rbx, r8
code.push(0xF4); // hlt
let (state, reason) = run(&code);
assert_eq!(reason, ExitReason::Halt);
assert_eq!(state.get(Register::R8), 0x1122_3344_5566_7788);
assert_eq!(state.get(Register::Rbx), 0x1122_3344_5566_7788);
// No prefix in this encoding selects r9.
assert_eq!(state.get(Register::R9), 0);
}
/// REX.R and REX.B extend independent fields, so the destination r9 and
/// the source r12 are chosen by different prefix bits.
///
/// Encoding 4D 89 E1 is `mov r9, r12`.
#[test]
fn rex_r_and_rex_b_extend_independent_fields() {
let mut code = mov_r8_imm64(0x1122_3344_5566_7788);
code.extend_from_slice(&[0x4D, 0x89, 0xE1]); // mov r9, r12
code.push(0xF4); // hlt
let (state, reason) = run(&code);
assert_eq!(reason, ExitReason::Halt);
// r9 receives r12, which is zero here, and not the value in r8.
assert_eq!(state.get(Register::R9), 0);
assert_eq!(state.get(Register::R12), 0);
assert_eq!(state.get(Register::R8), 0x1122_3344_5566_7788);
}
/// Without REX.W the move is 32-bit wide, so the destination keeps only the
/// low half of the source and its upper half is cleared.
///
/// Encoding 89 D8 is `mov eax, ebx`.
#[test]
fn a_move_without_rex_w_is_32_bit_wide() {
let mut code = mov_rbx_imm64(0x1122_3344_5566_7788);
code.extend_from_slice(&[0x89, 0xD8]); // mov eax, ebx
code.push(0xF4); // hlt
let (state, reason) = run(&code);
assert_eq!(reason, ExitReason::Halt);
// Only the low 32 bits of ebx survive, and rax's upper half is cleared.
assert_eq!(state.get(Register::Rax), 0x5566_7788);
assert_eq!(state.get(Register::Rbx), 0x1122_3344_5566_7788);
}
/// The FS segment override adds the FS base to the effective address.
///
/// Encoding 64 48 89 04 25 08 00 00 00 is `mov fs:[0x8], rax`.
#[test]
fn the_fs_prefix_adds_the_fs_base() {
let mut code = mov_rax_imm64(0x1122_3344_5566_7788);
code.extend_from_slice(&[0x64, 0x48, 0x89, 0x04, 0x25, 0x08, 0x00, 0x00, 0x00]);
code.push(0xF4); // hlt
let mut memory = memory_with_code(&code);
let mut cpu = CpuState::new(CODE_BASE, STACK_BASE + 0x8000);
cpu.fs_base = FS_BASE;
cpu.gs_base = GS_BASE;
let mut interp = Interpreter::new(cpu, &mut memory, 64);
let result = interp.run();
assert_eq!(result.exit_reason, ExitReason::Halt);
assert_eq!(
memory.read_u64(FS_BASE + 0x8).expect("fs read"),
0x1122_3344_5566_7788
);
// The GS base is untouched: the GS-prefixed store did not happen.
assert_eq!(memory.read_u64(GS_BASE + 0x8).expect("gs read"), 0);
}
}
/// Result returned after running guest execution.
#[derive(Debug)]
pub struct ExecutionResult {
@@ -211,503 +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 mut rex_w = false;
let mut rex_r = false;
let mut rex_b = false;
let mut seg_gs = false;
let mut seg_fs = false;
let mut byte = self.fetch_u8()?;
// Handle legacy segment prefixes: 0x65 (GS), 0x64 (FS)
while byte == 0x65 || byte == 0x64 {
if byte == 0x65 {
seg_gs = true;
} else {
seg_fs = true;
}
byte = self.fetch_u8()?;
}
// Handle REX prefix (0x40 - 0x4F)
if (byte & 0xF0) == 0x40 {
rex_w = (byte & 0x08) != 0;
rex_r = (byte & 0x04) != 0;
rex_b = (byte & 0x01) != 0;
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(rex_b) << 3));
let value = self.cpu.get(reg);
let reversed = if rex_w {
value.swap_bytes()
} else {
u64::from((value as u32).swap_bytes())
};
self.cpu.set(reg, reversed);
Ok(None)
}
op => Err(ExitReason::IllegalInstruction(op)),
},
// MOV r32, imm32 (0xB8 + reg) or MOV r64, imm64 with REX.W
0xB8..=0xBF => {
let reg_idx = (byte - 0xB8) + if rex_b { 8 } else { 0 };
let reg = Register::from_index(reg_idx);
if 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, rex_r, rex_b)?;
let (src, dst) = if byte == 0x31 { (reg, rm) } else { (rm, reg) };
let val1 = self.cpu.get(dst);
let val2 = self.cpu.get(src);
let res = if rex_w {
val1 ^ val2
} else {
(val1 as u32 ^ val2 as u32) as u64
};
self.cpu.set(dst, res);
self.update_flags_logic(res, rex_w);
Ok(None)
}
// ADD r/m, reg (0x01) or ADD reg, r/m (0x03)
0x01 | 0x03 => {
let modrm = self.fetch_u8()?;
let (reg, rm) = self.decode_modrm_reg_reg(modrm, rex_r, rex_b)?;
let (src, dst) = if byte == 0x01 { (reg, rm) } else { (rm, reg) };
let val1 = self.cpu.get(dst);
let val2 = self.cpu.get(src);
let (res, flags) = if rex_w {
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, rex_r, rex_b)?;
let (src, dst) = if byte == 0x29 { (reg, rm) } else { (rm, reg) };
let val1 = self.cpu.get(dst);
let val2 = self.cpu.get(src);
let (res, flags) = if rex_w {
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, rex_r, rex_b)?;
let (v1, v2) = if byte == 0x39 {
(self.cpu.get(rm), self.cpu.get(reg))
} else {
(self.cpu.get(reg), self.cpu.get(rm))
};
let (_, flags) = if rex_w {
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, rex_r, rex_b)?;
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 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 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 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, rex_w, rex_r, rex_b, byte == 0x8B, seg_gs, seg_fs)
}
// 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 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 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,
rex_r: bool,
rex_b: bool,
) -> Result<(Register, Register), ExitReason> {
let mode = (modrm >> 6) & 3;
if mode != 3 {
return Err(ExitReason::IllegalInstruction(modrm));
}
let reg_idx = ((modrm >> 3) & 7) + if rex_r { 8 } else { 0 };
let rm_idx = (modrm & 7) + if rex_b { 8 } else { 0 };
Ok((Register::from_index(reg_idx), Register::from_index(rm_idx)))
}
#[allow(clippy::too_many_arguments)]
fn execute_mov_rm(
&mut self,
modrm: u8,
rex_w: bool,
rex_r: bool,
rex_b: bool,
is_load: bool,
seg_gs: bool,
seg_fs: bool,
) -> Result<Option<ExitReason>, ExitReason> {
let mode = (modrm >> 6) & 3;
let reg_idx = ((modrm >> 3) & 7) + if rex_r { 8 } else { 0 };
let rm_idx = (modrm & 7) + if rex_b { 8 } else { 0 };
let reg = 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 rex_w { val } else { val as u32 as u64 });
} else {
let val = self.cpu.get(reg);
self.cpu
.set(rm, if rex_w { val } else { val as u32 as u64 });
}
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 rex_r { 8 } else { 0 }; // SIB.index can use REX.X; here index_raw
let base_raw = (sib & 7) + if rex_b { 8 } else { 0 };
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 seg_gs {
effective_addr = effective_addr.wrapping_add(self.cpu.gs_base);
} else if seg_fs {
effective_addr = effective_addr.wrapping_add(self.cpu.fs_base);
}
if is_load {
// Load from memory to reg
if rex_w {
let val = self
.memory
.read_u64(effective_addr)
.map_err(ExitReason::MemoryFault)?;
self.cpu.set(reg, val);
} else {
let val = self
.memory
.read_u32(effective_addr)
.map_err(ExitReason::MemoryFault)?;
self.cpu.set(reg, val as u64);
}
} else {
// Store from reg to memory
let val = self.cpu.get(reg);
if rex_w {
self.memory
.write_u64(effective_addr, val)
.map_err(ExitReason::MemoryFault)?;
} else {
self.memory
.write_u32(effective_addr, val as u32)
.map_err(ExitReason::MemoryFault)?;
}
}
Ok(None)
}
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),
}
}
}
+1527 -1211
View File
File diff suppressed because it is too large. Load diff
+241 -1
View File
@@ -117,6 +117,11 @@ pub enum GraphicsError {
DeviceCreationFailure(String),
BackendError(String),
NativeMetalRequired,
/// An index buffer format other than DXGI `R16_UINT` (57) or `R32_UINT` (42).
InvalidIndexFormat(u32),
/// An indexed draw reads past its index buffer or fetches a vertex,
/// after applying the base vertex, outside its vertex buffer.
IndexOutOfRange,
}
impl std::fmt::Display for GraphicsError {
@@ -140,6 +145,10 @@ impl std::fmt::Display for GraphicsError {
f,
"native Metal backend required but not provided or failed"
),
Self::InvalidIndexFormat(format) => {
write!(f, "unsupported index buffer format {format}")
}
Self::IndexOutOfRange => write!(f, "indexed draw outside its index or vertex buffer"),
}
}
}
@@ -173,6 +182,32 @@ pub struct GraphicsResource {
pub data: Vec<u8>,
}
/// Index size of an index buffer view, as `D3D12_INDEX_BUFFER_VIEW::Format`.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum IndexFormat {
R16Uint,
R32Uint,
}
impl IndexFormat {
/// The format for a DXGI format code: `R16_UINT` (57) or `R32_UINT` (42).
pub const fn from_dxgi(format: u32) -> Option<Self> {
match format {
57 => Some(Self::R16Uint),
42 => Some(Self::R32Uint),
_ => None,
}
}
/// Bytes per index.
pub const fn size(self) -> usize {
match self {
Self::R16Uint => 2,
Self::R32Uint => 4,
}
}
}
/// Primitive Draw Command recorded in a Command List.
#[derive(Clone, Debug)]
pub enum GraphicsCommand {
@@ -200,6 +235,18 @@ pub enum GraphicsCommand {
start_vertex_location: u32,
start_instance_location: u32,
},
SetIndexBuffer {
resource: GraphicsHandle,
offset: usize,
format: IndexFormat,
},
DrawIndexedInstanced {
index_count_per_instance: u32,
instance_count: u32,
start_index_location: u32,
base_vertex_location: i32,
start_instance_location: u32,
},
}
/// Command List in recording or closed state.
@@ -548,6 +595,72 @@ impl GraphicsContext {
Ok(())
}
/// Record set index buffer. `format` is a DXGI format code; only
/// `R16_UINT` (57) and `R32_UINT` (42) are index formats.
pub fn cmd_set_index_buffer(
&mut self,
list: GraphicsHandle,
resource: GraphicsHandle,
offset: usize,
format: u32,
) -> Result<(), GraphicsError> {
let cmd_list = self
.command_lists
.get_mut(&list)
.ok_or(GraphicsError::InvalidCommandListHandle)?;
if !cmd_list.is_recording {
return Err(GraphicsError::CommandListNotRecording);
}
let format =
IndexFormat::from_dxgi(format).ok_or(GraphicsError::InvalidIndexFormat(format))?;
let res = self
.resources
.get(&resource)
.ok_or(GraphicsError::InvalidResourceHandle)?;
if !offset.is_multiple_of(format.size()) || offset > res.data.len() {
return Err(GraphicsError::InvalidDescriptor);
}
cmd_list.commands.push(GraphicsCommand::SetIndexBuffer {
resource,
offset,
format,
});
Ok(())
}
/// Record draw indexed instanced. Each draw renders one triangle once: at
/// execution the index count must be 0 or 3, the instance count 0 or 1 and
/// the start instance 0, or the draw is rejected; a zero index or instance
/// count draws nothing. Index values are ordinary triangle-list indices
/// (no primitive restart), range checked after adding the base vertex.
pub fn cmd_draw_indexed_instanced(
&mut self,
list: GraphicsHandle,
index_count_per_instance: u32,
instance_count: u32,
start_index_location: u32,
base_vertex_location: i32,
start_instance_location: u32,
) -> Result<(), GraphicsError> {
let cmd_list = self
.command_lists
.get_mut(&list)
.ok_or(GraphicsError::InvalidCommandListHandle)?;
if !cmd_list.is_recording {
return Err(GraphicsError::CommandListNotRecording);
}
cmd_list
.commands
.push(GraphicsCommand::DrawIndexedInstanced {
index_count_per_instance,
instance_count,
start_index_location,
base_vertex_location,
start_instance_location,
});
Ok(())
}
/// Close command list.
pub fn close_command_list(&mut self, list: GraphicsHandle) -> Result<(), GraphicsError> {
let cmd_list = self
@@ -649,6 +762,8 @@ impl GraphicsContext {
let mut target_handle: Option<GraphicsHandle> = None;
let mut vertex_resource: Option<GraphicsHandle> = None;
let mut vertex_offset = 0usize;
let mut vertex_stride = 0usize;
let mut index_buffer: Option<(GraphicsHandle, usize, IndexFormat)> = None;
let mut rendered_output: Option<Vec<u8>> = None;
let mut draw_count = 0usize;
@@ -679,10 +794,57 @@ impl GraphicsContext {
viewport = (*width, *height);
}
GraphicsCommand::SetVertexBuffer {
resource, offset, ..
resource,
offset,
stride,
} => {
vertex_resource = Some(*resource);
vertex_offset = *offset;
vertex_stride = *stride;
}
GraphicsCommand::SetIndexBuffer {
resource,
offset,
format,
} => index_buffer = Some((*resource, *offset, *format)),
GraphicsCommand::DrawIndexedInstanced {
index_count_per_instance,
instance_count,
start_index_location,
base_vertex_location,
start_instance_location,
} => {
if !matches!(index_count_per_instance, 0 | 3)
|| *instance_count > 1
|| *start_instance_location != 0
{
return Err(GraphicsError::InvalidDescriptor);
}
if *index_count_per_instance == 0 || *instance_count == 0 {
continue;
}
let vertices = self.fetch_indexed_triangle(
memory,
index_buffer,
(vertex_resource, vertex_offset, vertex_stride),
*start_index_location,
*base_vertex_location,
)?;
draw_count += 1;
let pixels = if let Some(renderer) = backend_renderer {
renderer(&vertices, viewport, clear_color)?
} else if backend_id == GraphicsBackendId::MetalNative {
return Err(GraphicsError::NativeMetalRequired);
} else {
Self::execute_software_reference_draw(&vertices, viewport, clear_color)?
};
if let Some(th) = target_handle
&& let Some(target_res) = self.resources.get_mut(&th)
&& target_res.data.len() >= pixels.len()
{
target_res.data[..pixels.len()].copy_from_slice(&pixels);
}
rendered_output = Some(pixels);
}
GraphicsCommand::DrawInstanced {
vertex_count_per_instance,
@@ -761,6 +923,84 @@ impl GraphicsContext {
})
}
/// The three float4 positions one indexed triangle fetches: index `k` is
/// read at `offset + (start + k) * size` of the index buffer, and vertex
/// `index + base_vertex` at `offset + vertex * stride` of the vertex buffer.
fn fetch_indexed_triangle(
&self,
memory: &GuestMemory,
index_buffer: Option<(GraphicsHandle, usize, IndexFormat)>,
(vertex_resource, vertex_offset, vertex_stride): (Option<GraphicsHandle>, usize, usize),
start: u32,
base_vertex: i32,
) -> Result<[[f32; 4]; 3], GraphicsError> {
let resource = |handle: Option<GraphicsHandle>| {
handle
.and_then(|handle| self.resources.get(&handle))
.ok_or(GraphicsError::InvalidResourceHandle)
};
let (index_handle, index_offset, format) =
index_buffer.ok_or(GraphicsError::InvalidResourceHandle)?;
let index_res = resource(Some(index_handle))?;
let vertex_res = resource(vertex_resource)?;
if vertex_stride < 16 {
return Err(GraphicsError::InvalidDescriptor);
}
let size = format.size();
let mut raw_indices = [0u8; 12];
let raw_indices = &mut raw_indices[..3 * size];
let first = (start as usize)
.checked_mul(size)
.and_then(|bytes| bytes.checked_add(index_offset))
.ok_or(GraphicsError::IndexOutOfRange)?;
Self::read_resource(index_res, memory, first, raw_indices)?;
let mut vertices = [[0.0f32; 4]; 3];
for (row, index) in vertices.iter_mut().zip(raw_indices.chunks_exact(size)) {
let index = if size == 2 {
u32::from(u16::from_le_bytes([index[0], index[1]]))
} else {
u32::from_le_bytes(index.try_into().unwrap())
};
let vertex = usize::try_from(i64::from(index) + i64::from(base_vertex))
.map_err(|_| GraphicsError::IndexOutOfRange)?;
let at = vertex
.checked_mul(vertex_stride)
.and_then(|bytes| bytes.checked_add(vertex_offset))
.ok_or(GraphicsError::IndexOutOfRange)?;
let mut raw = [0u8; 16];
Self::read_resource(vertex_res, memory, at, &mut raw)?;
for (value, bytes) in row.iter_mut().zip(raw.as_chunks::<4>().0) {
*value = f32::from_le_bytes(*bytes);
}
}
Ok(vertices)
}
/// Read `out.len()` bytes at `offset` of a resource, from its guest backing
/// when it has one. The range must lie inside the resource's size.
fn read_resource(
res: &GraphicsResource,
memory: &GuestMemory,
offset: usize,
out: &mut [u8],
) -> Result<(), GraphicsError> {
let end = offset
.checked_add(out.len())
.filter(|&end| end <= res.data.len())
.ok_or(GraphicsError::IndexOutOfRange)?;
match res.guest_backing_addr {
Some(guest_addr) => {
let address = guest_addr
.checked_add(offset as u64)
.filter(|address| address.checked_add(out.len() as u64).is_some())
.ok_or(GraphicsError::IndexOutOfRange)?;
memory.read_bytes(address, out)?;
}
None => out.copy_from_slice(&res.data[offset..end]),
}
Ok(())
}
/// Software reference rasterizer for deterministic test verification when GPU tests are off.
pub fn execute_software_reference_draw(
vertices: &[[f32; 4]; 3],
+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)
}
+89 -6
View File
@@ -47,8 +47,8 @@ unsafe impl Sync for JitMemory {}
impl JitMemory {
/// Allocate a new JIT memory region using `MAP_JIT`.
pub fn new(capacity: usize) -> Result<Self, JitError> {
let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) as usize };
let aligned_capacity = (capacity + page_size - 1) & !(page_size - 1);
let page_size = unsafe { libc::sysconf(libc::_SC_PAGESIZE) };
let aligned_capacity = aligned_capacity(capacity, page_size)?;
let ptr = unsafe {
libc::mmap(
@@ -98,10 +98,7 @@ impl JitMemory {
/// Automatically manages `pthread_jit_write_protect_np`, copies bytes,
/// flushes data cache and invalidates instruction cache.
pub fn emit_block(&mut self, instructions: &[u32]) -> Result<*const u8, JitError> {
let bytes_len = instructions.len() * 4;
if self.used + bytes_len > self.capacity {
return Err(JitError::CapacityExceeded);
}
let bytes_len = emit_len(self.used, instructions.len(), self.capacity)?;
let emit_offset = self.used;
let dst_ptr = unsafe { self.ptr.as_ptr().add(emit_offset) };
@@ -131,6 +128,27 @@ impl JitMemory {
}
}
/// Round `capacity` up to a whole number of pages, rejecting an invalid page size
/// (`sysconf` failure, zero or not a power of two) and arithmetic overflow.
fn aligned_capacity(capacity: usize, page_size: libc::c_long) -> Result<usize, JitError> {
let page_size = usize::try_from(page_size)
.ok()
.filter(|p| p.is_power_of_two())
.ok_or(JitError::AllocationFailed(libc::EINVAL))?;
capacity
.checked_add(page_size - 1)
.map(|c| c & !(page_size - 1))
.ok_or(JitError::CapacityExceeded)
}
/// Byte length of `count` 4-byte instructions, if they fit after `used` bytes.
fn emit_len(used: usize, count: usize, capacity: usize) -> Result<usize, JitError> {
count
.checked_mul(4)
.filter(|len| used.checked_add(*len).is_some_and(|end| end <= capacity))
.ok_or(JitError::CapacityExceeded)
}
impl Drop for JitMemory {
fn drop(&mut self) {
unsafe {
@@ -138,3 +156,68 @@ impl Drop for JitMemory {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn capacity_rounds_up_to_whole_pages() {
assert_eq!(aligned_capacity(1, 16384), Ok(16384));
assert_eq!(aligned_capacity(16384, 16384), Ok(16384));
assert_eq!(aligned_capacity(16385, 16384), Ok(32768));
assert_eq!(aligned_capacity(0, 4096), Ok(0));
}
#[test]
fn invalid_page_size_is_rejected() {
for page in [-1, 0, 3, 12288] {
assert_eq!(
aligned_capacity(4096, page),
Err(JitError::AllocationFailed(libc::EINVAL)),
"page size {page}"
);
}
}
#[test]
fn capacity_rounding_overflow_is_rejected() {
assert_eq!(
aligned_capacity(usize::MAX, 16384),
Err(JitError::CapacityExceeded)
);
assert_eq!(
aligned_capacity(usize::MAX - 16382, 16384),
Err(JitError::CapacityExceeded)
);
}
#[test]
fn emit_length_is_checked() {
assert_eq!(emit_len(0, 4, 16), Ok(16));
assert_eq!(emit_len(4, 3, 16), Ok(12));
assert_eq!(emit_len(4, 4, 16), Err(JitError::CapacityExceeded));
// count * 4 overflows usize.
assert_eq!(
emit_len(0, usize::MAX / 2, usize::MAX),
Err(JitError::CapacityExceeded)
);
// used + len overflows usize.
assert_eq!(
emit_len(usize::MAX - 3, 2, usize::MAX),
Err(JitError::CapacityExceeded)
);
}
#[test]
fn emit_past_capacity_fails_and_leaves_usage_unchanged() {
let mut jit = JitMemory::new(1).expect("MAP_JIT allocation");
let words = jit.capacity() / 4;
assert!(jit.emit_block(&vec![0xD503_201F; words]).is_ok()); // NOP fills the page
assert_eq!(
jit.emit_block(&[0xD503_201F]),
Err(JitError::CapacityExceeded)
);
assert_eq!(jit.used(), jit.capacity());
}
}
+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};
+90 -66
View File
@@ -226,57 +226,102 @@ impl GuestMemory {
true
}
/// Write raw bytes into guest memory at the specified address, checking permissions.
pub fn write_bytes(&mut self, address: u64, src: &[u8]) -> Result<(), MemoryError> {
for region in &mut self.regions {
if region.contains(address, src.len()) {
if !region.permissions.write {
return Err(MemoryError::PermissionViolation {
address,
required: "write",
});
}
let offset = (address - region.base) as usize;
region.data[offset..offset + src.len()].copy_from_slice(src);
return Ok(());
/// Resolve `[address, address + len)` to `(region index, offset, length)` pieces.
///
/// An access may span adjacent regions, as it would span adjacent pages, but every
/// byte must be mapped and every region must grant `required` (`None` bypasses
/// permission checks for the loader). The whole range is checked before any byte
/// is copied, so a failed access never partially reads or writes.
fn resolve(
&self,
address: u64,
len: usize,
required: Option<&'static str>,
) -> Result<Vec<(usize, usize, usize)>, MemoryError> {
let end = address
.checked_add(len as u64)
.ok_or(MemoryError::Overflow)?;
if len == 0 {
return if self.regions.iter().any(|r| r.contains(address, 0)) {
Ok(Vec::new())
} else {
Err(MemoryError::UnmappedAddress(address))
};
}
let mut pieces = Vec::new();
let mut cursor = address;
for (index, region) in self.regions.iter().enumerate() {
let region_end = region.base + region.data.len() as u64;
if region_end <= cursor {
continue;
}
if region.base > cursor {
break;
}
let permitted = match required {
None => true,
Some("read") => region.permissions.read,
Some("write") => region.permissions.write,
Some(_) => region.permissions.execute,
};
if let (false, Some(required)) = (permitted, required) {
return Err(MemoryError::PermissionViolation { address, required });
}
let take = (end.min(region_end) - cursor) as usize;
pieces.push((index, (cursor - region.base) as usize, take));
cursor += take as u64;
if cursor == end {
return Ok(pieces);
}
}
Err(MemoryError::UnmappedAddress(address))
}
fn read_checked(
&self,
address: u64,
dst: &mut [u8],
required: Option<&'static str>,
) -> Result<(), MemoryError> {
let mut done = 0;
for (index, offset, take) in self.resolve(address, dst.len(), required)? {
dst[done..done + take]
.copy_from_slice(&self.regions[index].data[offset..offset + take]);
done += take;
}
Ok(())
}
fn write_checked(
&mut self,
address: u64,
src: &[u8],
required: Option<&'static str>,
) -> Result<(), MemoryError> {
let mut done = 0;
for (index, offset, take) in self.resolve(address, src.len(), required)? {
self.regions[index].data[offset..offset + take]
.copy_from_slice(&src[done..done + take]);
done += take;
}
Ok(())
}
/// Write raw bytes into guest memory at the specified address, checking permissions.
pub fn write_bytes(&mut self, address: u64, src: &[u8]) -> Result<(), MemoryError> {
self.write_checked(address, src, Some("write"))
}
/// Read raw bytes from guest memory at the specified address, checking permissions.
pub fn read_bytes(&self, address: u64, dst: &mut [u8]) -> Result<(), MemoryError> {
for region in &self.regions {
if region.contains(address, dst.len()) {
if !region.permissions.read {
return Err(MemoryError::PermissionViolation {
address,
required: "read",
});
}
let offset = (address - region.base) as usize;
dst.copy_from_slice(&region.data[offset..offset + dst.len()]);
return Ok(());
}
}
Err(MemoryError::UnmappedAddress(address))
self.read_checked(address, dst, Some("read"))
}
/// Read an instruction byte from guest memory, verifying execute permission.
pub fn fetch_instruction_byte(&self, address: u64) -> Result<u8, MemoryError> {
for region in &self.regions {
if region.contains(address, 1) {
if !region.permissions.execute {
return Err(MemoryError::PermissionViolation {
address,
required: "execute",
});
}
let offset = (address - region.base) as usize;
return Ok(region.data[offset]);
}
}
Err(MemoryError::UnmappedAddress(address))
let mut buf = [0u8; 1];
self.read_checked(address, &mut buf, Some("execute"))?;
Ok(buf[0])
}
/// Read a 64-bit integer (little endian) from guest memory.
@@ -288,14 +333,9 @@ impl GuestMemory {
/// Read a 64-bit integer ignoring region read permissions (e.g. loader/relocation phase).
pub fn read_u64_bypass(&self, address: u64) -> Result<u64, MemoryError> {
for region in &self.regions {
if region.contains(address, 8) {
let offset = (address - region.base) as usize;
let buf: [u8; 8] = region.data[offset..offset + 8].try_into().unwrap();
return Ok(u64::from_le_bytes(buf));
}
}
Err(MemoryError::UnmappedAddress(address))
let mut buf = [0u8; 8];
self.read_checked(address, &mut buf, None)?;
Ok(u64::from_le_bytes(buf))
}
/// Write a 64-bit integer (little endian) to guest memory.
@@ -305,15 +345,7 @@ impl GuestMemory {
/// Write a 64-bit integer ignoring region write permissions (e.g. loader/relocation phase).
pub fn write_u64_bypass(&mut self, address: u64, value: u64) -> Result<(), MemoryError> {
let bytes = value.to_le_bytes();
for region in &mut self.regions {
if region.contains(address, 8) {
let offset = (address - region.base) as usize;
region.data[offset..offset + 8].copy_from_slice(&bytes);
return Ok(());
}
}
Err(MemoryError::UnmappedAddress(address))
self.write_checked(address, &value.to_le_bytes(), None)
}
/// Read a 32-bit integer (little endian) from guest memory.
@@ -330,15 +362,7 @@ impl GuestMemory {
/// Write a 32-bit integer ignoring region write permissions (e.g. loader/relocation phase).
pub fn write_u32_bypass(&mut self, address: u64, value: u32) -> Result<(), MemoryError> {
let bytes = value.to_le_bytes();
for region in &mut self.regions {
if region.contains(address, 4) {
let offset = (address - region.base) as usize;
region.data[offset..offset + 4].copy_from_slice(&bytes);
return Ok(());
}
}
Err(MemoryError::UnmappedAddress(address))
self.write_checked(address, &value.to_le_bytes(), None)
}
/// Read a single byte from guest memory.
+108 -51
View File
@@ -91,6 +91,20 @@ pub const IMAGE_SCN_MEM_WRITE: u32 = 0x80000000;
// Standard Constants
pub const IMAGE_FILE_MACHINE_AMD64: u16 = 0x8664;
pub const PE32_PLUS_MAGIC: u16 = 0x020B;
/// PE32+ optional header length up to and including NumberOfRvaAndSizes.
const PE32_PLUS_MIN_OPTIONAL_HEADER: usize = 112;
const SECTION_HEADER_SIZE: usize = 40;
/// Host memory budget for all mapped sections of one image. This is a loader policy
/// limit, not a property of the PE format.
const MAX_MAPPED_IMAGE_BYTES: u64 = 256 * 1024 * 1024;
fn read_u16(bytes: &[u8], at: usize) -> u16 {
u16::from_le_bytes([bytes[at], bytes[at + 1]])
}
fn read_u32(bytes: &[u8], at: usize) -> u32 {
u32::from_le_bytes(bytes[at..at + 4].try_into().unwrap())
}
impl ParsedPe {
/// Parse PE32+ headers from an in-memory byte slice.
@@ -105,80 +119,85 @@ impl ParsedPe {
}
let e_lfanew = u32::from_le_bytes(bytes[0x3C..0x40].try_into().unwrap()) as usize;
if bytes.len() < e_lfanew + 24 {
let coff_offset = e_lfanew.checked_add(4).ok_or(PeError::TooSmall)?;
if bytes.len() < coff_offset.checked_add(20).ok_or(PeError::TooSmall)? {
return Err(PeError::TooSmall);
}
// 2. PE Signature
if &bytes[e_lfanew..e_lfanew + 4] != b"PE\0\0" {
if &bytes[e_lfanew..coff_offset] != b"PE\0\0" {
return Err(PeError::InvalidPeSignature);
}
// 3. COFF File Header
let coff_offset = e_lfanew + 4;
let machine = u16::from_le_bytes(bytes[coff_offset..coff_offset + 2].try_into().unwrap());
let machine = read_u16(bytes, coff_offset);
if machine != IMAGE_FILE_MACHINE_AMD64 {
return Err(PeError::UnsupportedMachine(machine));
}
let number_of_sections = read_u16(bytes, coff_offset + 2);
let time_date_stamp = read_u32(bytes, coff_offset + 4);
let size_of_optional_header = usize::from(read_u16(bytes, coff_offset + 16));
let number_of_sections =
u16::from_le_bytes(bytes[coff_offset + 2..coff_offset + 4].try_into().unwrap());
let time_date_stamp =
u32::from_le_bytes(bytes[coff_offset + 4..coff_offset + 8].try_into().unwrap());
let size_of_optional_header = u16::from_le_bytes(
bytes[coff_offset + 16..coff_offset + 18]
.try_into()
.unwrap(),
) as usize;
// 4. Optional Header (PE32+ is required)
// 4. Optional Header (PE32+ is required). The fixed PE32+ fields end at
// NumberOfRvaAndSizes (offset 108, 4 bytes); a shorter header is malformed.
let opt_offset = coff_offset + 20;
if bytes.len() < opt_offset + size_of_optional_header {
let section_table_offset = opt_offset + size_of_optional_header;
if bytes.len() < opt_offset + 2 {
return Err(PeError::TooSmall);
}
let magic = u16::from_le_bytes(bytes[opt_offset..opt_offset + 2].try_into().unwrap());
let magic = read_u16(bytes, opt_offset);
if magic != PE32_PLUS_MAGIC {
return Err(PeError::InvalidMagic(magic));
}
if size_of_optional_header < PE32_PLUS_MIN_OPTIONAL_HEADER
|| bytes.len() < section_table_offset
{
return Err(PeError::TooSmall);
}
let entry_point_rva =
u32::from_le_bytes(bytes[opt_offset + 16..opt_offset + 20].try_into().unwrap());
let entry_point_rva = read_u32(bytes, opt_offset + 16);
let image_base =
u64::from_le_bytes(bytes[opt_offset + 24..opt_offset + 32].try_into().unwrap());
let section_alignment =
u32::from_le_bytes(bytes[opt_offset + 32..opt_offset + 36].try_into().unwrap());
let file_alignment =
u32::from_le_bytes(bytes[opt_offset + 36..opt_offset + 40].try_into().unwrap());
let size_of_image =
u32::from_le_bytes(bytes[opt_offset + 56..opt_offset + 60].try_into().unwrap());
let size_of_headers =
u32::from_le_bytes(bytes[opt_offset + 60..opt_offset + 64].try_into().unwrap());
let section_alignment = read_u32(bytes, opt_offset + 32);
let file_alignment = read_u32(bytes, opt_offset + 36);
let size_of_image = read_u32(bytes, opt_offset + 56);
let size_of_headers = read_u32(bytes, opt_offset + 60);
// 5. Section Headers
let mut sections = Vec::with_capacity(number_of_sections as usize);
let section_table_offset = opt_offset + size_of_optional_header;
let section_header_size = 40;
if bytes.len() < section_table_offset + (number_of_sections as usize * section_header_size)
{
let table_end = usize::from(number_of_sections)
.checked_mul(SECTION_HEADER_SIZE)
.and_then(|len| section_table_offset.checked_add(len))
.ok_or(PeError::InvalidSectionHeaders)?;
if bytes.len() < table_end {
return Err(PeError::InvalidSectionHeaders);
}
for i in 0..number_of_sections as usize {
let offset = section_table_offset + i * section_header_size;
let sec_bytes = &bytes[offset..offset + section_header_size];
let mut sections = Vec::with_capacity(usize::from(number_of_sections));
for sec_bytes in bytes[section_table_offset..table_end]
.as_chunks::<SECTION_HEADER_SIZE>()
.0
{
// Section name (up to 8 bytes UTF-8 or null-padded ASCII)
let name_raw = &sec_bytes[0..8];
let name_len = name_raw.iter().position(|&b| b == 0).unwrap_or(8);
let name = String::from_utf8_lossy(&name_raw[..name_len]).into_owned();
let virtual_size = u32::from_le_bytes(sec_bytes[8..12].try_into().unwrap());
let virtual_address = u32::from_le_bytes(sec_bytes[12..16].try_into().unwrap());
let raw_data_size = u32::from_le_bytes(sec_bytes[16..20].try_into().unwrap());
let raw_data_ptr = u32::from_le_bytes(sec_bytes[20..24].try_into().unwrap());
let characteristics = u32::from_le_bytes(sec_bytes[36..40].try_into().unwrap());
let virtual_size = read_u32(sec_bytes, 8);
let virtual_address = read_u32(sec_bytes, 12);
let raw_data_size = read_u32(sec_bytes, 16);
let raw_data_ptr = read_u32(sec_bytes, 20);
let characteristics = read_u32(sec_bytes, 36);
// The mapped range must fit in the 32-bit RVA space, and raw data must be in the file.
virtual_address
.checked_add(virtual_size.max(raw_data_size))
.ok_or(PeError::InvalidSectionHeaders)?;
if raw_data_size > 0 {
let raw_end = u64::from(raw_data_ptr) + u64::from(raw_data_size);
if raw_end > bytes.len() as u64 {
return Err(PeError::InvalidSectionHeaders);
}
}
let permissions = MemoryPermissions {
read: (characteristics & IMAGE_SCN_MEM_READ) != 0,
@@ -197,6 +216,32 @@ impl ParsedPe {
});
}
// Mapped section ranges must not overlap. Zero-sized sections map nothing.
let mut ranges: Vec<(u32, u32)> = sections
.iter()
.map(|s| {
(
s.virtual_address,
s.virtual_address + s.virtual_size.max(s.raw_data_size),
)
})
.filter(|(start, end)| start < end)
.collect();
ranges.sort_unstable();
if ranges.windows(2).any(|w| w[1].0 < w[0].1) {
return Err(PeError::InvalidSectionHeaders);
}
// The entry point must lie inside an executable section.
let entry_ok = sections.iter().any(|s| {
s.permissions.execute
&& entry_point_rva >= s.virtual_address
&& entry_point_rva - s.virtual_address < s.virtual_size.max(s.raw_data_size)
});
if !entry_ok {
return Err(PeError::InvalidEntryPoint);
}
Ok(ParsedPe {
machine,
number_of_sections,
@@ -214,13 +259,12 @@ impl ParsedPe {
/// Translate a Relative Virtual Address (RVA) to a raw file offset.
pub fn rva_to_file_offset(&self, rva: u32) -> Option<usize> {
for sec in &self.sections {
let start = sec.virtual_address;
let size = std::cmp::max(sec.virtual_size, sec.raw_data_size);
if rva >= start && rva < start + size {
let diff = (rva - start) as usize;
if diff < sec.raw_data_size as usize {
return Some(sec.raw_data_ptr as usize + diff);
}
// Sections are public and may not come from `parse`, so stay checked here.
let Some(diff) = rva.checked_sub(sec.virtual_address) else {
continue;
};
if diff < sec.virtual_size.max(sec.raw_data_size) && diff < sec.raw_data_size {
return (sec.raw_data_ptr as usize).checked_add(diff as usize);
}
}
None
@@ -232,6 +276,17 @@ impl ParsedPe {
}
pub(crate) fn load_at_base(&self, bytes: &[u8], base: u64) -> Result<LoadedImage, PeError> {
// Each section becomes a zero-filled host allocation, so bound the total before
// allocating anything. Sections may not overlap, so the sum is the mapped size.
let mapped: u64 = self
.sections
.iter()
.map(|sec| u64::from(sec.virtual_size.max(sec.raw_data_size)))
.sum();
if mapped > MAX_MAPPED_IMAGE_BYTES {
return Err(PeError::SectionMappingError(MemoryError::AllocationFailed));
}
let mut memory = GuestMemory::new();
for sec in &self.sections {
@@ -245,7 +300,9 @@ impl ParsedPe {
let initial_data = if sec.raw_data_size > 0 && sec.raw_data_ptr > 0 {
let start = sec.raw_data_ptr as usize;
let end = start + sec.raw_data_size as usize;
let end = start
.checked_add(sec.raw_data_size as usize)
.ok_or(PeError::InvalidSectionHeaders)?;
bytes
.get(start..end)
.ok_or(PeError::InvalidSectionHeaders)?
+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,
+33 -5
View File
@@ -117,7 +117,10 @@ pub fn apply_relocations(
size: reloc_size,
})?;
if reloc_file_offset + (reloc_size as usize) > bytes.len() {
if reloc_file_offset
.checked_add(reloc_size as usize)
.is_none_or(|end| end > bytes.len())
{
return Err(RelocationError::DirectoryOutOfBounds {
rva: reloc_rva,
size: reloc_size,
@@ -127,13 +130,20 @@ pub fn apply_relocations(
let mut read_bytes = 0usize;
let max_read = reloc_size as usize;
while read_bytes + 8 <= max_read {
while read_bytes < max_read {
// A partial block header after the last block is malformed, not padding.
if max_read - read_bytes < 8 {
return Err(RelocationError::MalformedBlockHeader {
offset: reloc_file_offset + read_bytes,
});
}
let block_start = reloc_file_offset + read_bytes;
let page_rva = u32::from_le_bytes(bytes[block_start..block_start + 4].try_into().unwrap());
let block_size =
u32::from_le_bytes(bytes[block_start + 4..block_start + 8].try_into().unwrap());
if block_size < 8 {
// A block is an 8-byte header followed by whole 2-byte entries.
if block_size < 8 || block_size % 2 != 0 {
return Err(RelocationError::MalformedBlockHeader {
offset: block_start,
});
@@ -166,6 +176,15 @@ pub fn apply_relocations(
let target_rva = page_rva
.checked_add(offset_in_page)
.ok_or(RelocationError::ArithmeticOverflow)?;
// The 8-byte target must lie inside the image, not in other mapped memory.
if target_rva
.checked_add(8)
.is_none_or(|end| end > pe.size_of_image)
{
return Err(RelocationError::TargetOutOfBounds {
target_va: loaded_base.wrapping_add(u64::from(target_rva)),
});
}
let target_va = loaded_base
.checked_add(target_rva as u64)
.ok_or(RelocationError::ArithmeticOverflow)?;
@@ -213,8 +232,8 @@ fn find_reloc_directory(
return Ok(None);
}
let e_lfanew = u32::from_le_bytes(bytes[0x3C..0x40].try_into().unwrap()) as usize;
let opt_offset = e_lfanew + 24;
let coff_offset = e_lfanew + 4;
let opt_offset = coff_offset + 20;
if bytes.len() < coff_offset + 18 {
return Ok(None);
}
@@ -224,10 +243,19 @@ fn find_reloc_directory(
.unwrap(),
) as usize;
// Relocation directory is directory index 5 (offset 112 + 5 * 8 = 152 in Optional Header)
// Relocation directory is directory index 5 (offset 112 + 5 * 8 = 152 in Optional Header).
// It exists only when NumberOfRvaAndSizes (offset 108) covers index 5.
if size_of_opt < 160 || bytes.len() < opt_offset + 160 {
return Ok(None);
}
let number_of_rva_and_sizes = u32::from_le_bytes(
bytes[opt_offset + 108..opt_offset + 112]
.try_into()
.unwrap(),
);
if number_of_rva_and_sizes < 6 {
return Ok(None);
}
let reloc_rva = u32::from_le_bytes(
bytes[opt_offset + 152..opt_offset + 156]
+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 },
}
}
+136 -16
View File
@@ -11,6 +11,14 @@ use crate::{
const STACK_SIZE: usize = 64 * 1024;
const JIT_CAPACITY: usize = 1024 * 1024;
/// The TEB is placed this far above the TLS base and spans two 4 KiB pages.
const TEB_OFFSET: u64 = 0x10000;
const TEB_SIZE: usize = 0x2000;
// Win64 TEB fields (NT_TIB prefix plus the TLS slot) written by the harness.
const TEB_STACK_BASE: u64 = 0x08;
const TEB_STACK_LIMIT: u64 = 0x10;
const TEB_SELF: u64 = 0x30;
const TEB_TLS_POINTER: u64 = 0x58;
/// Guest addresses reserved by the fixture harness.
pub struct StartupLayout {
@@ -79,6 +87,8 @@ pub fn run_synthetic_startup_with_observer(
)
.into());
}
// Reject an impossible layout before parsing or mapping anything.
let (stack_base, teb_base) = layout_regions(&layout)?;
let pe = ParsedPe::parse(bytes)?;
observe(StartupEvent::Parsed {
sections: pe.sections.len(),
@@ -112,24 +122,9 @@ pub fn run_synthetic_startup_with_observer(
)?;
}
let stack_base = layout
.stack_top
.checked_sub(STACK_SIZE as u64)
.ok_or(MemoryError::Overflow)?;
memory.map_region(stack_base, STACK_SIZE, MemoryPermissions::READ_WRITE)?;
// Allocate and initialize Win64 TEB (Thread Environment Block)
// Layout in TEB:
// +0x08: StackBase (highest address)
// +0x10: StackLimit (lowest address)
// +0x30: Self pointer (TEB linear address)
// +0x58: ThreadLocalStoragePointer
let teb_base = layout.tls_base.saturating_add(0x10000);
memory.map_region(teb_base, 0x2000, MemoryPermissions::READ_WRITE)?;
memory.write_u64_bypass(teb_base + 0x08, layout.stack_top)?;
memory.write_u64_bypass(teb_base + 0x10, stack_base)?;
memory.write_u64_bypass(teb_base + 0x30, teb_base)?;
memory.write_u64_bypass(teb_base + 0x58, layout.tls_base)?;
map_teb(memory, teb_base, &layout, stack_base)?;
let mut engine = DbtEngine::new(JIT_CAPACITY)?;
engine.set_import_registry(imports);
@@ -171,3 +166,128 @@ pub fn run_synthetic_startup_with_observer(
dbt_metrics: engine.metrics,
})
}
/// Validate the harness layout and return `(stack_base, teb_base)`.
///
/// The stack occupies `[stack_top - STACK_SIZE, stack_top)` and the TEB
/// `[tls_base + TEB_OFFSET, + TEB_SIZE)`. Both ranges must fit in the address
/// space and must not overlap each other.
fn layout_regions(layout: &StartupLayout) -> Result<(u64, u64), MemoryError> {
let stack_base = layout
.stack_top
.checked_sub(STACK_SIZE as u64)
.ok_or(MemoryError::Overflow)?;
let teb_base = layout
.tls_base
.checked_add(TEB_OFFSET)
.ok_or(MemoryError::Overflow)?;
let teb_end = teb_base
.checked_add(TEB_SIZE as u64)
.ok_or(MemoryError::Overflow)?;
if teb_base < layout.stack_top && stack_base < teb_end {
return Err(MemoryError::OverlappingRegion {
base: teb_base,
size: TEB_SIZE as u64,
});
}
Ok((stack_base, teb_base))
}
/// Map the Win64 TEB and write the fields the harness provides.
fn map_teb(
memory: &mut crate::GuestMemory,
teb_base: u64,
layout: &StartupLayout,
stack_base: u64,
) -> Result<(), MemoryError> {
memory.map_region(teb_base, TEB_SIZE, MemoryPermissions::READ_WRITE)?;
memory.write_u64_bypass(teb_base + TEB_STACK_BASE, layout.stack_top)?;
memory.write_u64_bypass(teb_base + TEB_STACK_LIMIT, stack_base)?;
memory.write_u64_bypass(teb_base + TEB_SELF, teb_base)?;
memory.write_u64_bypass(teb_base + TEB_TLS_POINTER, layout.tls_base)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::GuestMemory;
fn layout(stack_top: u64, tls_base: u64) -> StartupLayout {
StartupLayout {
image_base: 0x1_4000_0000,
stack_top,
tls_base,
}
}
#[test]
fn valid_layout_places_stack_and_teb() {
let regions = layout_regions(&layout(0x2_0001_0000, 0x3_0000_0000));
assert_eq!(regions, Ok((0x2_0000_0000, 0x3_0001_0000)));
}
#[test]
fn stack_below_zero_is_rejected() {
assert_eq!(
layout_regions(&layout(0x8000, 0x3_0000_0000)),
Err(MemoryError::Overflow)
);
}
#[test]
fn teb_address_overflow_is_rejected_not_saturated() {
for tls_base in [u64::MAX, u64::MAX - 0xFFFF, u64::MAX - TEB_OFFSET - 0x1FFF] {
assert_eq!(
layout_regions(&layout(0x2_0001_0000, tls_base)),
Err(MemoryError::Overflow),
"tls_base {tls_base:#x}"
);
}
// The highest TEB that fits ends at u64::MAX: an end of 2^64 is not
// representable, and GuestMemory could not map that range either.
let top = u64::MAX - TEB_OFFSET - TEB_SIZE as u64;
assert!(layout_regions(&layout(0x2_0001_0000, top)).is_ok());
}
#[test]
fn teb_overlapping_stack_is_rejected() {
// TEB at 0x2_0000_8000..0x2_0000_A000 lies inside the stack 0x2_0000_0000..0x2_0001_0000.
let collide = layout(0x2_0001_0000, 0x1_FFFF_8000);
assert!(matches!(
layout_regions(&collide),
Err(MemoryError::OverlappingRegion { .. })
));
// Directly above the stack is fine.
assert!(layout_regions(&layout(0x2_0001_0000, 0x2_0000_0000)).is_ok());
}
#[test]
fn invalid_layout_fails_before_parsing() {
// Empty bytes would fail PE parsing; the layout error must come first.
let err = run_synthetic_startup(
&[],
layout(0x2_0001_0000, u64::MAX),
ImportRegistry::new(),
1,
)
.err()
.expect("startup must fail");
assert_eq!(
err.downcast_ref::<MemoryError>(),
Some(&MemoryError::Overflow)
);
}
#[test]
fn teb_fields_are_at_win64_offsets() {
let l = layout(0x2_0001_0000, 0x3_0000_0000);
let (stack_base, teb) = layout_regions(&l).unwrap();
let mut memory = GuestMemory::new();
map_teb(&mut memory, teb, &l, stack_base).unwrap();
assert_eq!(memory.read_u64(teb + 0x08), Ok(0x2_0001_0000));
assert_eq!(memory.read_u64(teb + 0x10), Ok(0x2_0000_0000));
assert_eq!(memory.read_u64(teb + 0x30), Ok(teb));
assert_eq!(memory.read_u64(teb + 0x58), Ok(0x3_0000_0000));
assert!(memory.read_u8(teb + TEB_SIZE as u64).is_err());
}
}
+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;
@@ -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]
+411
View File
@@ -590,3 +590,414 @@ fn test_guest_dbt_graphics_pipeline_metal_render_dual_inputs() {
let expected_clear = [10, 20, 30, 255];
assert_eq!(pixels2, expected_clear.repeat(12));
}
/// Guest addresses of the indexed-draw fixtures.
const INDEXED_VB: u64 = 0x7000_0000;
const INDEXED_IB: u64 = 0x7100_0000;
/// Vertex stride of the indexed fixtures: a float4 position and 16 unused bytes.
const INDEXED_STRIDE: usize = 32;
/// Triangle (4,3) (16,4) (6,16) of a 16x16 target in clip space; no pixel
/// centre lies on one of its edges.
const INDEXED_TRIANGLE: [[f32; 4]; 3] = [
[-0.5, 0.625, 0.5, 1.0],
[1.0, 0.5, 0.5, 1.0],
[-0.25, -1.0, 0.5, 1.0],
];
/// Ten vertices: the triangle at vertices 5, 7 and 2, and decoys elsewhere,
/// so a wrong fetch passes different positions.
fn indexed_vertices() -> Vec<u8> {
let mut bytes = Vec::new();
for vertex in 0..10 {
let position = match vertex {
5 => INDEXED_TRIANGLE[0],
7 => INDEXED_TRIANGLE[1],
2 => INDEXED_TRIANGLE[2],
other => [other as f32 * 0.125 - 0.75, -0.5, 0.5, 1.0],
};
for value in position {
bytes.extend(value.to_le_bytes());
}
bytes.extend([0xAB; 16]);
}
bytes
}
struct IndexedRig {
ctx: GraphicsContext,
memory: GuestMemory,
queue: GraphicsHandle,
alloc: GraphicsHandle,
list: GraphicsHandle,
vb: GraphicsHandle,
ib16: GraphicsHandle,
ib32: GraphicsHandle,
}
/// A context with guest-backed vertex and index buffers. The 16-bit buffer
/// holds 9, 9, 6, 8, 3, 5, 0 and the 32-bit buffer 9, 3, 5, 0, 7 and three
/// indices above 16 bits, 0x10003, 0x10005, 0x10000.
fn indexed_rig() -> IndexedRig {
use xenora_loader::memory::MemoryPermissions;
let mut ctx = GraphicsContext::new();
let device = ctx.create_device().unwrap();
let queue = ctx
.create_command_queue(device, CommandListType::Direct)
.unwrap();
let alloc = ctx
.create_command_allocator(device, CommandListType::Direct)
.unwrap();
let list = ctx
.create_command_list(device, alloc, CommandListType::Direct)
.unwrap();
let buffer = |ctx: &mut GraphicsContext, bytes: usize, addr| {
let desc = ResourceDesc {
dimension: ResourceDimension::Buffer,
width: bytes as u64,
height: 1,
depth_or_array_size: 1,
mip_levels: 1,
format_rgba8: false,
};
ctx.create_committed_resource(device, desc, ResourceStates::COMMON, Some(addr))
.unwrap()
};
let vertices = indexed_vertices();
let ib16: Vec<u8> = [9u16, 9, 6, 8, 3, 5, 0]
.iter()
.flat_map(|index| index.to_le_bytes())
.collect();
let ib32: Vec<u8> = [9u32, 3, 5, 0, 7, 0x1_0003, 0x1_0005, 0x1_0000]
.iter()
.flat_map(|index| index.to_le_bytes())
.collect();
let vb = buffer(&mut ctx, vertices.len(), INDEXED_VB);
let ib16_handle = buffer(&mut ctx, ib16.len(), INDEXED_IB);
let ib32_handle = buffer(&mut ctx, ib32.len(), INDEXED_IB + 0x1000);
let mut memory = GuestMemory::new();
for (addr, bytes) in [
(INDEXED_VB, &vertices),
(INDEXED_IB, &ib16),
(INDEXED_IB + 0x1000, &ib32),
] {
memory
.map_region_with_data(addr, 0x1000, MemoryPermissions::READ_ONLY, bytes)
.unwrap();
}
IndexedRig {
ctx,
memory,
queue,
alloc,
list,
vb,
ib16: ib16_handle,
ib32: ib32_handle,
}
}
/// Record one indexed draw (16x16 viewport, the rig's vertex buffer) and run it.
fn run_indexed(
rig: &mut IndexedRig,
index_buffer: (GraphicsHandle, usize, u32),
draw: (u32, u32, u32, i32),
) -> Result<xenora_loader::graphics::ExecutionOutcome, GraphicsError> {
let ctx = &mut rig.ctx;
ctx.reset_command_list(rig.list, rig.alloc)?;
ctx.cmd_set_viewport(rig.list, 16, 16)?;
ctx.cmd_set_vertex_buffer(rig.list, rig.vb, 0, INDEXED_STRIDE)?;
ctx.cmd_set_index_buffer(rig.list, index_buffer.0, index_buffer.1, index_buffer.2)?;
let (count, instances, start, base) = draw;
ctx.cmd_draw_indexed_instanced(rig.list, count, instances, start, base, 0)?;
ctx.close_command_list(rig.list)?;
ctx.execute_command_list(rig.queue, rig.list, &rig.memory)
}
const R16_UINT: u32 = 57;
const R32_UINT: u32 = 42;
/// Start index, signed base vertex, index size and buffer offset all select
/// vertices 5, 7, 2: the backend receives exactly the triangle's positions
/// (literal values), never a decoy.
#[test]
fn test_d3d12_indexed_draw_fetches_start_and_base_vertex() {
let mut rig = indexed_rig();
let seen = Arc::new(std::sync::Mutex::new(Vec::new()));
let record = seen.clone();
rig.ctx.set_metal_backend(move |vtx, viewport, clear| {
record.lock().unwrap().push(*vtx);
GraphicsContext::execute_software_reference_draw(vtx, viewport, clear)
});
let (ib16, ib32) = (rig.ib16, rig.ib32);
for (name, buffer, draw) in [
// 16-bit indices 3, 5, 0 at index 4, base vertex +2.
("u16 positive base", (ib16, 0, R16_UINT), (3, 1, 4, 2)),
// 16-bit indices 6, 8, 3 at index 2, base vertex -1.
("u16 negative base", (ib16, 0, R16_UINT), (3, 1, 2, -1)),
// The same through a buffer offset of one index (2 bytes).
("u16 buffer offset", (ib16, 2, R16_UINT), (3, 1, 1, -1)),
// 32-bit indices 3, 5, 0 at index 1, base vertex +2.
("u32 positive base", (ib32, 0, R32_UINT), (3, 1, 1, 2)),
// 32-bit indices above 16 bits, base vertex -65534: all 32 bits count.
("u32 wide indices", (ib32, 0, R32_UINT), (3, 1, 5, -65534)),
] {
seen.lock().unwrap().clear();
let outcome = run_indexed(&mut rig, buffer, draw).expect(name);
assert_eq!(outcome.draw_count, 1, "{name}");
assert_eq!(*seen.lock().unwrap(), vec![INDEXED_TRIANGLE], "{name}");
assert_eq!(
outcome.pixels,
GraphicsContext::execute_software_reference_draw(
&INDEXED_TRIANGLE,
(16, 16),
[0, 0, 0, 255]
)
.unwrap(),
"{name}"
);
}
// A vertex buffer offset of two vertices does the base vertex's work.
seen.lock().unwrap().clear();
let ctx = &mut rig.ctx;
ctx.reset_command_list(rig.list, rig.alloc).unwrap();
ctx.cmd_set_viewport(rig.list, 16, 16).unwrap();
ctx.cmd_set_vertex_buffer(rig.list, rig.vb, 2 * INDEXED_STRIDE, INDEXED_STRIDE)
.unwrap();
ctx.cmd_set_index_buffer(rig.list, ib16, 0, R16_UINT)
.unwrap();
ctx.cmd_draw_indexed_instanced(rig.list, 3, 1, 4, 0, 0)
.unwrap();
ctx.close_command_list(rig.list).unwrap();
let outcome = ctx
.execute_command_list(rig.queue, rig.list, &rig.memory)
.expect("vertex buffer offset");
assert_eq!(outcome.draw_count, 1);
assert_eq!(*seen.lock().unwrap(), vec![INDEXED_TRIANGLE]);
// Zero indices or zero instances draw nothing and never call the backend.
seen.lock().unwrap().clear();
for draw in [(0, 1, 0, 0), (3, 0, 0, 0)] {
let outcome = run_indexed(&mut rig, (ib16, 0, R16_UINT), draw).unwrap();
assert_eq!(outcome.draw_count, 0);
}
assert!(seen.lock().unwrap().is_empty());
}
/// Index format, offset, count, range, negative fetch and unknown or missing
/// buffers each fail with a typed error, and nothing reaches the backend.
#[test]
fn test_d3d12_indexed_draw_errors() {
let mut rig = indexed_rig();
let calls = Arc::new(std::sync::Mutex::new(0usize));
let counter = calls.clone();
rig.ctx.set_metal_backend(move |vtx, viewport, clear| {
*counter.lock().unwrap() += 1;
GraphicsContext::execute_software_reference_draw(vtx, viewport, clear)
});
let (ib16, ib32) = (rig.ib16, rig.ib32);
let unknown = GraphicsHandle {
id: 999,
generation: 1,
};
for format in [0, 41, 56, 58, 28] {
assert_eq!(
run_indexed(&mut rig, (ib16, 0, format), (3, 1, 0, 0)).unwrap_err(),
GraphicsError::InvalidIndexFormat(format)
);
}
for (name, buffer, draw, error) in [
(
"misaligned offset",
(ib32, 2, R32_UINT),
(3, 1, 0, 0),
GraphicsError::InvalidDescriptor,
),
(
"offset past buffer",
(ib16, 16, R16_UINT),
(3, 1, 0, 0),
GraphicsError::InvalidDescriptor,
),
(
"unknown buffer",
(unknown, 0, R16_UINT),
(3, 1, 0, 0),
GraphicsError::InvalidResourceHandle,
),
(
"count not one triangle",
(ib16, 0, R16_UINT),
(6, 1, 0, 0),
GraphicsError::InvalidDescriptor,
),
(
"bad count with zero instances",
(ib16, 0, R16_UINT),
(6, 0, 0, 0),
GraphicsError::InvalidDescriptor,
),
(
"two instances",
(ib16, 0, R16_UINT),
(3, 2, 4, 2),
GraphicsError::InvalidDescriptor,
),
(
"indices past buffer",
(ib16, 0, R16_UINT),
(3, 1, 5, 0),
GraphicsError::IndexOutOfRange,
),
(
"start overflow",
(ib32, 0, R32_UINT),
(3, 1, u32::MAX, 0),
GraphicsError::IndexOutOfRange,
),
(
"negative vertex",
(ib16, 0, R16_UINT),
(3, 1, 4, -1),
GraphicsError::IndexOutOfRange,
),
(
"vertex past buffer",
(ib16, 0, R16_UINT),
(3, 1, 0, 1),
GraphicsError::IndexOutOfRange,
),
(
"base overflow",
(ib32, 0, R32_UINT),
(3, 1, 0, i32::MAX),
GraphicsError::IndexOutOfRange,
),
] {
let got = run_indexed(&mut rig, buffer, draw);
assert_eq!(got.unwrap_err(), error, "{name}");
}
// A draw without an index buffer is rejected at execution.
let ctx = &mut rig.ctx;
ctx.reset_command_list(rig.list, rig.alloc).unwrap();
ctx.cmd_set_vertex_buffer(rig.list, rig.vb, 0, INDEXED_STRIDE)
.unwrap();
ctx.cmd_draw_indexed_instanced(rig.list, 3, 1, 0, 0, 0)
.unwrap();
ctx.close_command_list(rig.list).unwrap();
assert_eq!(
ctx.execute_command_list(rig.queue, rig.list, &rig.memory),
Err(GraphicsError::InvalidResourceHandle)
);
// A stride smaller than one float4 position is rejected.
ctx.reset_command_list(rig.list, rig.alloc).unwrap();
ctx.cmd_set_vertex_buffer(rig.list, rig.vb, 0, 12).unwrap();
ctx.cmd_set_index_buffer(rig.list, ib16, 0, R16_UINT)
.unwrap();
ctx.cmd_draw_indexed_instanced(rig.list, 3, 1, 4, 2, 0)
.unwrap();
ctx.close_command_list(rig.list).unwrap();
assert_eq!(
ctx.execute_command_list(rig.queue, rig.list, &rig.memory),
Err(GraphicsError::InvalidDescriptor)
);
// A nonzero start instance is rejected.
ctx.reset_command_list(rig.list, rig.alloc).unwrap();
ctx.cmd_set_vertex_buffer(rig.list, rig.vb, 0, INDEXED_STRIDE)
.unwrap();
ctx.cmd_set_index_buffer(rig.list, ib16, 0, R16_UINT)
.unwrap();
ctx.cmd_draw_indexed_instanced(rig.list, 3, 1, 4, 2, 1)
.unwrap();
ctx.close_command_list(rig.list).unwrap();
assert_eq!(
ctx.execute_command_list(rig.queue, rig.list, &rig.memory),
Err(GraphicsError::InvalidDescriptor)
);
// An index buffer whose guest backing would wrap the address space is
// rejected, not read at a wrapped address.
let device = ctx.create_device().unwrap();
// The read's start wraps (start 8 at 2 bytes each), then only its end does.
for (guest_addr, start) in [(u64::MAX - 8, 8), (u64::MAX - 2, 0)] {
let wrapping = rig
.ctx
.create_committed_resource(
device,
ResourceDesc {
dimension: ResourceDimension::Buffer,
width: 64,
height: 1,
depth_or_array_size: 1,
mip_levels: 1,
format_rgba8: false,
},
ResourceStates::COMMON,
Some(guest_addr),
)
.unwrap();
assert_eq!(
run_indexed(&mut rig, (wrapping, 0, R16_UINT), (3, 1, start, 0)).unwrap_err(),
GraphicsError::IndexOutOfRange,
"guest address {guest_addr:#x} start {start}"
);
}
// No rejected draw reached the backend.
assert_eq!(*calls.lock().unwrap(), 0);
}
/// The loader's indexed fetch feeds the native Metal renderer: the GPU image
/// of the fetched triangle equals the image of the literal triangle.
#[test]
#[cfg_attr(
not(feature = "gpu-tests"),
ignore = "needs native Metal device; run scripts/test-gpu.sh"
)]
fn test_d3d12_indexed_draw_native_metal() {
use xenora_metal::NativeCompute;
use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics};
let vs_bytes = include_bytes!("../../../fixtures/rdna2/x9-constant-vs.bin");
let ps_bytes = include_bytes!("../../../fixtures/rdna2/x9-constant-ps.bin");
let msl = compile_graphics(Architecture::Gfx1030, vs_bytes, ps_bytes)
.expect("compile graphics RDNA2 shaders")
.msl;
let gpu = Arc::new(NativeCompute::new().expect("native Metal GPU device"));
let render = {
let gpu = gpu.clone();
let msl = msl.clone();
move |vtx: &[[f32; 4]; 3], vp: (usize, usize), cc: [u8; 4]| {
gpu.render_rgba8(
&msl,
[VERTEX_ENTRY_POINT, PIXEL_ENTRY_POINT],
vtx,
&[[0.0; 4]; 3],
[vp.0, vp.1],
cc,
)
.map_err(|e| GraphicsError::BackendError(format!("Metal GPU error: {e:?}")))
}
};
let direct = render(&INDEXED_TRIANGLE, (16, 16), [0, 0, 0, 255]).expect("direct render");
let mut rig = indexed_rig();
rig.ctx.set_metal_backend(render);
let ib16 = rig.ib16;
let outcome = run_indexed(&mut rig, (ib16, 0, R16_UINT), (3, 1, 2, -1)).expect("indexed");
assert_eq!(outcome.backend, GraphicsBackendId::MetalNative);
assert_eq!(outcome.pixels, direct);
// The constant shader paints the covered pixels red; the CPU rasteriser
// agrees pixel for pixel, and the triangle covers some but not all pixels.
let reference = GraphicsContext::execute_software_reference_draw(
&INDEXED_TRIANGLE,
(16, 16),
[0, 0, 0, 255],
)
.unwrap();
assert_eq!(outcome.pixels, reference);
let red = outcome
.pixels
.chunks(4)
.filter(|p| *p == [255, 0, 0, 255])
.count();
assert!((1..256).contains(&red), "{red} red pixels");
println!("indexed native Metal draw: {red} of 256 pixels covered");
}
+95
View File
@@ -0,0 +1,95 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use xenora_loader::cpu::{CpuState, ExitReason, Register};
use xenora_loader::dbt::DbtEngine;
use xenora_loader::memory::{GuestMemory, MemoryError, MemoryPermissions};
#[test]
fn native_indirect_transfers_commit_before_target_fetch() {
const ENTRY: u64 = 0x2000;
const SLOT: u64 = 0x1800;
const TARGET: u64 = 0x3000;
const STACK: u64 = 0x4000;
const SENTINEL: u64 = 0xabcd_1234;
// R9 or [RIP - 0x806]. Both memory operands point back to SLOT.
for (branch, call) in [
(&[0x41, 0xff, 0xd1][..], true),
(&[0x41, 0xff, 0xe1][..], false),
(&[0xff, 0x15, 0xfa, 0xf7, 0xff, 0xff][..], true),
(&[0xff, 0x25, 0xfa, 0xf7, 0xff, 0xff][..], false),
] {
for target_permissions in [
Some(MemoryPermissions::READ_EXECUTE),
Some(MemoryPermissions::READ_WRITE),
None,
] {
let return_address = ENTRY + branch.len() as u64;
let mut code = branch.to_vec();
code.push(0xf4);
let mut memory = GuestMemory::new();
memory
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, &code)
.unwrap();
memory
.map_region_with_data(
SLOT,
8,
MemoryPermissions::READ_WRITE,
&TARGET.to_le_bytes(),
)
.unwrap();
memory
.map_region_with_data(
STACK,
8,
MemoryPermissions::READ_WRITE,
&SENTINEL.to_le_bytes(),
)
.unwrap();
if let Some(permissions) = target_permissions {
let target_opcode = if call { 0xc3 } else { 0xf4 };
memory
.map_region_with_data(TARGET, 1, permissions, &[target_opcode])
.unwrap();
}
let mut cpu = CpuState::new(ENTRY, STACK + 8);
cpu.set(Register::R9, TARGET);
let mut engine = DbtEngine::new(16 * 1024).unwrap();
let transfer = engine.run(&mut cpu, &mut memory, 1);
assert_eq!(transfer.exit_reason, ExitReason::StepLimitExceeded);
assert_eq!(transfer.instructions_executed, 1);
assert_eq!(cpu.rip, TARGET);
let stack_after_transfer = if call { STACK } else { STACK + 8 };
assert_eq!(cpu.get(Register::Rsp), stack_after_transfer);
assert_eq!(
memory.read_u64(STACK).unwrap(),
if call { return_address } else { SENTINEL }
);
let resumed = engine.run(&mut cpu, &mut memory, 3);
match target_permissions {
Some(MemoryPermissions::READ_EXECUTE) => {
assert_eq!(resumed.exit_reason, ExitReason::Halt);
assert_eq!(resumed.instructions_executed, if call { 2 } else { 1 });
assert_eq!(cpu.rip, if call { return_address + 1 } else { TARGET + 1 });
assert_eq!(cpu.get(Register::Rsp), STACK + 8);
}
permissions => {
let fault = if permissions.is_some() {
MemoryError::PermissionViolation {
address: TARGET,
required: "execute",
}
} else {
MemoryError::UnmappedAddress(TARGET)
};
assert_eq!(resumed.exit_reason, ExitReason::MemoryFault(fault));
assert_eq!(resumed.instructions_executed, 0);
assert_eq!(cpu.rip, TARGET);
assert_eq!(cpu.get(Register::Rsp), stack_after_transfer);
}
}
}
}
}
+159
View File
@@ -0,0 +1,159 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Guest memory boundary regression tests (#82).
//!
//! Expected behavior follows x86-64 data access rules: an access is valid when
//! every byte it touches is mapped with the required permission, whether or not
//! it is aligned or crosses into an adjacent mapping. A faulting access changes
//! nothing.
use xenora_loader::{GuestMemory, MemoryError, MemoryPermissions as P};
const A: u64 = 0x10_0000;
fn two_regions(first: P, second: P) -> GuestMemory {
let mut m = GuestMemory::new();
m.map_region_with_data(A, 0x1000, first, &[0x11; 0x1000])
.unwrap();
m.map_region_with_data(A + 0x1000, 0x1000, second, &[0x22; 0x1000])
.unwrap();
m
}
fn bypass_bytes(m: &GuestMemory, at: u64) -> u64 {
m.read_u64_bypass(at).unwrap()
}
#[test]
fn permissions_are_enforced_per_access_kind() {
let mut m = GuestMemory::new();
m.map_region(A, 0x1000, P::NO_ACCESS).unwrap();
m.map_region(A + 0x1000, 0x1000, P::READ_ONLY).unwrap();
m.map_region(A + 0x2000, 0x1000, P::READ_WRITE).unwrap();
let violation = |address, required| MemoryError::PermissionViolation { address, required };
assert_eq!(m.read_u8(A), Err(violation(A, "read")));
assert_eq!(
m.write_u8(A + 0x1000, 1),
Err(violation(A + 0x1000, "write"))
);
assert_eq!(
m.fetch_instruction_byte(A + 0x2000),
Err(violation(A + 0x2000, "execute"))
);
assert!(m.read_u8(A + 0x1000).is_ok());
assert!(m.write_u8(A + 0x2000, 1).is_ok());
}
#[test]
fn region_end_is_exclusive() {
let m = two_regions(P::READ_ONLY, P::NO_ACCESS);
assert!(m.read_u32(A + 0xFFC).is_ok());
assert!(matches!(
m.read_u32(A + 0xFFD),
Err(MemoryError::PermissionViolation { .. })
));
let mut lone = GuestMemory::new();
lone.map_region(A, 0x1000, P::READ_ONLY).unwrap();
assert_eq!(
lone.read_u32(A + 0xFFD),
Err(MemoryError::UnmappedAddress(A + 0xFFD))
);
assert_eq!(
lone.read_u8(A - 1),
Err(MemoryError::UnmappedAddress(A - 1))
);
}
#[test]
fn unaligned_accesses_succeed_inside_a_region() {
let mut m = two_regions(P::READ_WRITE, P::READ_WRITE);
m.write_u64(A + 3, 0x0102_0304_0506_0708).unwrap();
assert_eq!(m.read_u64(A + 3), Ok(0x0102_0304_0506_0708));
assert_eq!(m.read_u16(A + 3), Ok(0x0708));
assert_eq!(m.read_u32(A + 5), Ok(0x0304_0506));
}
#[test]
fn access_spanning_adjacent_permitted_regions_succeeds() {
let mut m = two_regions(P::READ_WRITE, P::READ_WRITE);
m.write_u64(A + 0xFFC, 0x8877_6655_4433_2211).unwrap();
assert_eq!(m.read_u64(A + 0xFFC), Ok(0x8877_6655_4433_2211));
assert_eq!(m.read_u32(A + 0xFFC), Ok(0x4433_2211)); // low half in the first region
assert_eq!(m.read_u32(A + 0x1000), Ok(0x8877_6655)); // high half in the second
}
#[test]
fn spanning_into_a_gap_fails_without_partial_write() {
let mut m = GuestMemory::new();
m.map_region_with_data(A, 0x1000, P::READ_WRITE, &[0x11; 0x1000])
.unwrap();
m.map_region(A + 0x2000, 0x1000, P::READ_WRITE).unwrap();
assert_eq!(
m.write_u64(A + 0xFFC, u64::MAX),
Err(MemoryError::UnmappedAddress(A + 0xFFC))
);
assert_eq!(m.read_u32(A + 0xFFC), Ok(0x1111_1111));
}
#[test]
fn spanning_into_a_forbidden_region_fails_atomically() {
let mut m = two_regions(P::READ_WRITE, P::READ_ONLY);
assert_eq!(
m.write_u64(A + 0xFFC, u64::MAX),
Err(MemoryError::PermissionViolation {
address: A + 0xFFC,
required: "write"
})
);
assert_eq!(bypass_bytes(&m, A + 0xFFC), 0x2222_2222_1111_1111);
let m = two_regions(P::READ_EXECUTE, P::READ_WRITE);
assert!(m.read_u64(A + 0xFFC).is_ok());
assert!(m.fetch_instruction_byte(A + 0xFFF).is_ok());
assert!(m.fetch_instruction_byte(A + 0x1000).is_err());
}
#[test]
fn loader_bypass_ignores_permissions_but_not_mapping() {
let mut m = two_regions(P::READ_ONLY, P::NO_ACCESS);
m.write_u64_bypass(A + 0xFFC, 0x0A0B_0C0D_0E0F_1011)
.unwrap();
assert_eq!(m.read_u64_bypass(A + 0xFFC), Ok(0x0A0B_0C0D_0E0F_1011));
m.write_u32_bypass(A, 7).unwrap();
assert_eq!(m.read_u32(A), Ok(7));
assert_eq!(
m.write_u64_bypass(A + 0x1FFC, 0),
Err(MemoryError::UnmappedAddress(A + 0x1FFC))
);
}
#[test]
fn address_overflow_is_reported() {
let mut m = GuestMemory::new();
m.map_region(u64::MAX - 0xFFF, 0xFFF, P::READ_WRITE)
.unwrap();
assert_eq!(m.read_u64(u64::MAX - 3), Err(MemoryError::Overflow));
assert_eq!(
m.write_u64_bypass(u64::MAX - 3, 0),
Err(MemoryError::Overflow)
);
assert_eq!(
m.map_region(u64::MAX, 2, P::READ_WRITE),
Err(MemoryError::Overflow)
);
}
#[test]
fn overlapping_mappings_are_rejected_and_adjacent_ones_accepted() {
let mut m = GuestMemory::new();
m.map_region(A, 0x1000, P::READ_WRITE).unwrap();
assert_eq!(
m.map_region(A + 0xFFF, 0x10, P::READ_WRITE),
Err(MemoryError::OverlappingRegion {
base: A + 0xFFF,
size: 0x10
})
);
assert!(m.map_region(A + 0x1000, 0x10, P::READ_WRITE).is_ok());
assert!(m.map_region(A - 0x10, 0x10, P::READ_WRITE).is_ok());
}
+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
}
+96
View File
@@ -0,0 +1,96 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! PE image mapping budget tests (#80).
//!
//! A section's mapped size is max(VirtualSize, SizeOfRawData) and the loader
//! backs it with zero-filled host memory, so a small file can request a large
//! allocation. The loader's documented budget is 256 MiB per image.
use xenora_loader::{MemoryError, ParsedPe, PeError};
const BUDGET: u32 = 256 * 1024 * 1024;
/// An original synthetic image: one 0x200-byte code section at RVA 0x1000 followed by
/// uninitialized sections (no raw data) of the given virtual sizes, packed back to back.
fn build(bss_sizes: &[u32]) -> Vec<u8> {
let mut pe = vec![0u8; 0x400];
pe[0..2].copy_from_slice(b"MZ");
pe[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
pe[0x40..0x44].copy_from_slice(b"PE\0\0");
let coff = 0x44;
pe[coff..coff + 2].copy_from_slice(&0x8664u16.to_le_bytes());
pe[coff + 2..coff + 4].copy_from_slice(&(1 + bss_sizes.len() as u16).to_le_bytes());
pe[coff + 16..coff + 18].copy_from_slice(&112u16.to_le_bytes());
let opt = coff + 20;
pe[opt..opt + 2].copy_from_slice(&0x020Bu16.to_le_bytes());
pe[opt + 16..opt + 20].copy_from_slice(&0x1000u32.to_le_bytes());
pe[opt + 24..opt + 32].copy_from_slice(&0x1_4000_0000u64.to_le_bytes());
let mut section = |i: usize, va: u32, vsize: u32, raw: u32, flags: u32| {
let h = opt + 112 + i * 40;
pe[h + 8..h + 12].copy_from_slice(&vsize.to_le_bytes());
pe[h + 12..h + 16].copy_from_slice(&va.to_le_bytes());
pe[h + 16..h + 20].copy_from_slice(&(if raw == 0 { 0 } else { 0x200u32 }).to_le_bytes());
pe[h + 20..h + 24].copy_from_slice(&raw.to_le_bytes());
pe[h + 36..h + 40].copy_from_slice(&flags.to_le_bytes());
};
section(0, 0x1000, 0x200, 0x200, 0x6000_0020);
let mut va = 0x2000u32;
for (i, &size) in bss_sizes.iter().enumerate() {
section(i + 1, va, size, 0, 0xC000_0080);
va += size;
}
pe
}
fn over_budget() -> PeError {
PeError::SectionMappingError(MemoryError::AllocationFailed)
}
#[test]
fn small_image_loads() {
let bytes = build(&[0x1000]);
let pe = ParsedPe::parse(&bytes).unwrap();
assert!(pe.load_into_memory(&bytes).is_ok());
}
#[test]
fn image_exactly_at_budget_loads() {
let bytes = build(&[BUDGET - 0x200]);
let pe = ParsedPe::parse(&bytes).unwrap();
assert!(pe.load_into_memory(&bytes).is_ok());
}
#[test]
fn one_byte_over_budget_is_rejected() {
let bytes = build(&[BUDGET - 0x1FF]);
let pe = ParsedPe::parse(&bytes).unwrap();
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
}
#[test]
fn budget_counts_all_sections_together() {
// Three 128 MiB sections: each fits alone, the total (384 MiB) does not.
let bytes = build(&[128 << 20; 3]);
let pe = ParsedPe::parse(&bytes).unwrap();
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
}
#[test]
fn near_4_gib_request_from_a_1_kib_file_is_rejected_before_allocation() {
let bytes = build(&[0xF000_0000]);
assert_eq!(bytes.len(), 0x400);
let pe = ParsedPe::parse(&bytes).expect("headers are valid; only the size is excessive");
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
}
#[test]
fn repository_fixture_is_within_budget() {
let path = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../fixtures/pe/trusted-runner.exe"
);
let bytes = std::fs::read(path).unwrap();
let pe = ParsedPe::parse(&bytes).unwrap();
assert!(pe.load_into_memory(&bytes).is_ok());
}
+239
View File
@@ -0,0 +1,239 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Malformed-input regression tests for the PE32+ parser (#79).
//!
//! Every image here is built byte by byte from the Microsoft PE/COFF
//! specification layout: DOS header with e_lfanew at 0x3C, "PE\0\0", the
//! 20-byte COFF header, the PE32+ optional header (112 fixed bytes before the
//! data directories) and 40-byte section headers.
use xenora_loader::{ParsedPe, PeError, PeSection};
const RX: u32 = 0x6000_0020; // code | execute | read
const R: u32 = 0x4000_0040; // initialized data | read
struct Sec {
va: u32,
vsize: u32,
raw_ptr: u32,
raw_size: u32,
flags: u32,
}
/// A two-section image: .text at RVA 0x1000 (file 0x200) and .rdata at RVA 0x2000 (file 0x400).
fn valid_sections() -> Vec<Sec> {
vec![
Sec {
va: 0x1000,
vsize: 0x100,
raw_ptr: 0x200,
raw_size: 0x200,
flags: RX,
},
Sec {
va: 0x2000,
vsize: 0x80,
raw_ptr: 0x400,
raw_size: 0x200,
flags: R,
},
]
}
fn build(opt_size: u16, entry: u32, secs: &[Sec]) -> Vec<u8> {
let mut pe = vec![0u8; 0x600];
pe[0..2].copy_from_slice(b"MZ");
pe[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
pe[0x40..0x44].copy_from_slice(b"PE\0\0");
let coff = 0x44;
pe[coff..coff + 2].copy_from_slice(&0x8664u16.to_le_bytes());
pe[coff + 2..coff + 4].copy_from_slice(&(secs.len() as u16).to_le_bytes());
pe[coff + 16..coff + 18].copy_from_slice(&opt_size.to_le_bytes());
let opt = coff + 20;
pe[opt..opt + 2].copy_from_slice(&0x020Bu16.to_le_bytes());
pe[opt + 16..opt + 20].copy_from_slice(&entry.to_le_bytes());
pe[opt + 24..opt + 32].copy_from_slice(&0x1_4000_0000u64.to_le_bytes());
pe[opt + 32..opt + 36].copy_from_slice(&0x1000u32.to_le_bytes());
pe[opt + 36..opt + 40].copy_from_slice(&0x200u32.to_le_bytes());
pe[opt + 56..opt + 60].copy_from_slice(&0x3000u32.to_le_bytes());
pe[opt + 60..opt + 64].copy_from_slice(&0x200u32.to_le_bytes());
let table = opt + usize::from(opt_size);
for (i, s) in secs.iter().enumerate() {
let h = table + i * 40;
pe[h..h + 5].copy_from_slice(b".sect");
pe[h + 8..h + 12].copy_from_slice(&s.vsize.to_le_bytes());
pe[h + 12..h + 16].copy_from_slice(&s.va.to_le_bytes());
pe[h + 16..h + 20].copy_from_slice(&s.raw_size.to_le_bytes());
pe[h + 20..h + 24].copy_from_slice(&s.raw_ptr.to_le_bytes());
pe[h + 36..h + 40].copy_from_slice(&s.flags.to_le_bytes());
}
pe
}
#[test]
fn valid_image_parses_maps_and_translates() {
let bytes = build(112, 0x1010, &valid_sections());
let pe = ParsedPe::parse(&bytes).expect("valid image");
assert_eq!(pe.entry_point_rva, 0x1010);
assert_eq!(pe.sections.len(), 2);
assert_eq!(pe.rva_to_file_offset(0x1010), Some(0x210));
assert_eq!(pe.rva_to_file_offset(0x2004), Some(0x404));
assert_eq!(pe.rva_to_file_offset(0x3000), None);
let loaded = pe.load_into_memory(&bytes).expect("load");
assert_eq!(loaded.entry_point, 0x1_4000_1010);
}
#[test]
fn optional_header_with_data_directories_is_accepted() {
let bytes = build(240, 0x1000, &valid_sections());
assert!(ParsedPe::parse(&bytes).is_ok());
}
#[test]
fn repository_fixtures_still_parse_and_load() {
let root = concat!(env!("CARGO_MANIFEST_DIR"), "/../..");
for path in [
"fixtures/pe/trusted-runner.exe",
"experiments/x1/fixtures/x2.exe",
"experiments/x1/fixtures/x3.exe",
"experiments/x1/fixtures/x4-17.exe",
"experiments/x1/fixtures/x4-93.exe",
"experiments/x1/fixtures/x5.exe",
"experiments/x1/fixtures/x6.exe",
] {
let bytes = std::fs::read(format!("{root}/{path}")).expect(path);
let pe = ParsedPe::parse(&bytes).unwrap_or_else(|e| panic!("{path}: {e}"));
pe.load_into_memory(&bytes)
.unwrap_or_else(|e| panic!("{path}: {e}"));
}
}
/// Reproducer from #79: 90 bytes, SizeOfOptionalHeader = 2, file ends after the magic.
#[test]
fn truncated_optional_header_is_rejected_not_panicking() {
let mut bytes = vec![0u8; 90];
bytes[0..2].copy_from_slice(b"MZ");
bytes[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
bytes[0x40..0x44].copy_from_slice(b"PE\0\0");
bytes[0x44..0x46].copy_from_slice(&0x8664u16.to_le_bytes());
bytes[0x54..0x56].copy_from_slice(&2u16.to_le_bytes());
bytes[0x58..0x5A].copy_from_slice(&0x020Bu16.to_le_bytes());
assert_eq!(ParsedPe::parse(&bytes).unwrap_err(), PeError::TooSmall);
}
#[test]
fn optional_header_shorter_than_pe32_plus_fixed_fields_is_rejected() {
for opt_size in [24u16, 64, 111] {
let bytes = build(opt_size, 0x1000, &valid_sections());
assert_eq!(
ParsedPe::parse(&bytes).unwrap_err(),
PeError::TooSmall,
"{opt_size}"
);
}
}
#[test]
fn e_lfanew_past_end_of_file_is_rejected() {
let mut bytes = build(112, 0x1000, &valid_sections());
bytes[0x3C..0x40].copy_from_slice(&u32::MAX.to_le_bytes());
assert_eq!(ParsedPe::parse(&bytes).unwrap_err(), PeError::TooSmall);
}
#[test]
fn section_table_past_end_of_file_is_rejected() {
let mut bytes = build(112, 0x1000, &valid_sections());
bytes[0x46..0x48].copy_from_slice(&u16::MAX.to_le_bytes());
assert_eq!(
ParsedPe::parse(&bytes).unwrap_err(),
PeError::InvalidSectionHeaders
);
}
#[test]
fn section_range_overflowing_rva_space_is_rejected() {
let mut secs = valid_sections();
secs[1].va = 0xFFFF_F000;
secs[1].vsize = 0x2000;
let bytes = build(112, 0x1000, &secs);
assert_eq!(
ParsedPe::parse(&bytes).unwrap_err(),
PeError::InvalidSectionHeaders
);
}
/// Reproducer from #79: lookup over a section whose end overflows u32 must not panic or wrap.
#[test]
fn rva_lookup_with_overflowing_section_returns_none() {
let bytes = build(112, 0x1000, &valid_sections());
let mut pe = ParsedPe::parse(&bytes).unwrap();
pe.sections.insert(
0,
PeSection {
name: "wrap".into(),
virtual_address: 0xFFFF_FF00,
virtual_size: 0x200,
raw_data_ptr: 0x200,
raw_data_size: 0x200,
characteristics: R,
permissions: pe.sections[1].permissions,
},
);
// A wrapped end (0xFFFF_FF00 + 0x200 = 0x100) would wrongly capture RVA 0x80.
assert_eq!(pe.rva_to_file_offset(0x80), None);
assert_eq!(pe.rva_to_file_offset(0xFFFF_FF10), Some(0x210));
assert_eq!(pe.rva_to_file_offset(0x1004), Some(0x204));
}
#[test]
fn overlapping_sections_are_rejected() {
let mut secs = valid_sections();
secs[1].va = 0x1100; // .text maps 0x1000..0x1200 (raw size wins)
let bytes = build(112, 0x1000, &secs);
assert_eq!(
ParsedPe::parse(&bytes).unwrap_err(),
PeError::InvalidSectionHeaders
);
}
#[test]
fn adjacent_sections_are_accepted() {
let mut secs = valid_sections();
secs[1].va = 0x1200;
let bytes = build(112, 0x1000, &secs);
assert!(ParsedPe::parse(&bytes).is_ok());
}
#[test]
fn truncated_section_data_is_rejected() {
let mut secs = valid_sections();
secs[1].raw_size = 0x201; // file is 0x600 bytes; 0x400 + 0x201 runs one byte past the end
let bytes = build(112, 0x1000, &secs);
assert_eq!(
ParsedPe::parse(&bytes).unwrap_err(),
PeError::InvalidSectionHeaders
);
secs[1].raw_size = 0x200;
secs[1].raw_ptr = u32::MAX;
let bytes = build(112, 0x1000, &secs);
assert_eq!(
ParsedPe::parse(&bytes).unwrap_err(),
PeError::InvalidSectionHeaders
);
}
#[test]
fn entry_point_outside_executable_section_is_rejected() {
// Past the end of .text's mapped range, in non-executable .rdata, and outside every section.
for entry in [0x1200, 0x2000, 0x0, u32::MAX] {
let bytes = build(112, entry, &valid_sections());
assert_eq!(
ParsedPe::parse(&bytes).unwrap_err(),
PeError::InvalidEntryPoint,
"entry {entry:#x}"
);
}
// Last byte of .text is still inside it.
assert!(ParsedPe::parse(&build(112, 0x11FF, &valid_sections())).is_ok());
}
+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());
}
}
@@ -0,0 +1,271 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Base relocation regression tests (#81).
//!
//! Images are built byte by byte from the PE/COFF layout: data directory 5
//! (Base Relocation Table) at optional-header offset 152, and blocks made of a
//! 4-byte page RVA, a 4-byte block size and 2-byte entries whose top 4 bits
//! are the type (0 = ABSOLUTE padding, 3 = HIGHLOW, 10 = DIR64).
use xenora_loader::{GuestMemory, ParsedPe, RelocationError, apply_relocations};
const PREFERRED: u64 = 0x1_4000_0000;
const RELOC_FILE: usize = 0x400;
/// .text at RVA 0x1000 (file 0x200) holding two pointers, .reloc at RVA 0x2000 (file 0x400).
/// `NumberOfRvaAndSizes` and the relocation table bytes are parameters.
fn build(rva_and_sizes: u32, table: &[u8], dir_size: u32) -> Vec<u8> {
let mut pe = vec![0u8; 0x600];
pe[0..2].copy_from_slice(b"MZ");
pe[0x3C..0x40].copy_from_slice(&0x40u32.to_le_bytes());
pe[0x40..0x44].copy_from_slice(b"PE\0\0");
let coff = 0x44;
pe[coff..coff + 2].copy_from_slice(&0x8664u16.to_le_bytes());
pe[coff + 2..coff + 4].copy_from_slice(&2u16.to_le_bytes());
pe[coff + 16..coff + 18].copy_from_slice(&240u16.to_le_bytes());
let opt = coff + 20;
pe[opt..opt + 2].copy_from_slice(&0x020Bu16.to_le_bytes());
pe[opt + 16..opt + 20].copy_from_slice(&0x1000u32.to_le_bytes());
pe[opt + 24..opt + 32].copy_from_slice(&PREFERRED.to_le_bytes());
pe[opt + 32..opt + 36].copy_from_slice(&0x1000u32.to_le_bytes());
pe[opt + 36..opt + 40].copy_from_slice(&0x200u32.to_le_bytes());
pe[opt + 56..opt + 60].copy_from_slice(&0x3000u32.to_le_bytes());
pe[opt + 60..opt + 64].copy_from_slice(&0x200u32.to_le_bytes());
pe[opt + 108..opt + 112].copy_from_slice(&rva_and_sizes.to_le_bytes());
pe[opt + 152..opt + 156].copy_from_slice(&0x2000u32.to_le_bytes());
pe[opt + 156..opt + 160].copy_from_slice(&dir_size.to_le_bytes());
let sections: [(&[u8], u32, u32, u32, u32); 2] = [
(b".text", 0x1000, 0x200, 0x200, 0x6000_0020),
// .reloc fills the image up to SizeOfImage (0x3000).
(b".reloc", 0x2000, 0x1000, RELOC_FILE as u32, 0x4200_0040),
];
for (i, (name, va, vsize, raw, flags)) in sections.into_iter().enumerate() {
let h = opt + 240 + i * 40;
pe[h..h + name.len()].copy_from_slice(name);
pe[h + 8..h + 12].copy_from_slice(&vsize.to_le_bytes());
pe[h + 12..h + 16].copy_from_slice(&va.to_le_bytes());
pe[h + 16..h + 20].copy_from_slice(&0x200u32.to_le_bytes());
pe[h + 20..h + 24].copy_from_slice(&raw.to_le_bytes());
pe[h + 36..h + 40].copy_from_slice(&flags.to_le_bytes());
}
// Two absolute pointers into the image, at RVAs 0x1010 and 0x1018.
pe[0x210..0x218].copy_from_slice(&(PREFERRED + 0x1100).to_le_bytes());
pe[0x218..0x220].copy_from_slice(&(PREFERRED + 0x2000).to_le_bytes());
pe[RELOC_FILE..RELOC_FILE + table.len()].copy_from_slice(table);
pe
}
fn block(page_rva: u32, entries: &[u16]) -> Vec<u8> {
let mut b = page_rva.to_le_bytes().to_vec();
b.extend_from_slice(&(8 + 2 * entries.len() as u32).to_le_bytes());
for e in entries {
b.extend_from_slice(&e.to_le_bytes());
}
b
}
/// DIR64 at 0x1010 and 0x1018, plus one ABSOLUTE padding entry to keep 4-byte alignment.
fn standard_table() -> Vec<u8> {
block(0x1000, &[0xA010, 0xA018, 0x0000])
}
fn load(bytes: &[u8], base: u64) -> (ParsedPe, GuestMemory) {
let pe = ParsedPe::parse(bytes).expect("parse");
let mut memory = GuestMemory::new();
for s in &pe.sections {
let raw = &bytes[s.raw_data_ptr as usize..(s.raw_data_ptr + s.raw_data_size) as usize];
memory
.map_region_with_data(
base + u64::from(s.virtual_address),
0x200,
s.permissions,
raw,
)
.expect("map");
}
(pe, memory)
}
fn relocate(
bytes: &[u8],
base: u64,
) -> (
Result<xenora_loader::RelocationReport, RelocationError>,
GuestMemory,
) {
let (pe, mut memory) = load(bytes, base);
let result = apply_relocations(&pe, bytes, base, &mut memory);
(result, memory)
}
#[test]
fn positive_rebase_adds_delta_to_each_dir64_target() {
let table = standard_table();
let bytes = build(16, &table, table.len() as u32);
let base = PREFERRED + 0x1_0000_0000;
let (result, memory) = relocate(&bytes, base);
let report = result.expect("relocate");
assert_eq!(report.delta, 0x1_0000_0000);
assert_eq!(report.applied_dir64, 2);
assert_eq!(report.skipped_absolute, 1);
assert_eq!(report.total_entries, 3);
assert_eq!(
memory.read_u64_bypass(base + 0x1010).unwrap(),
base + 0x1100
);
assert_eq!(
memory.read_u64_bypass(base + 0x1018).unwrap(),
base + 0x2000
);
}
#[test]
fn negative_rebase_subtracts_delta() {
let table = standard_table();
let bytes = build(16, &table, table.len() as u32);
let base = 0x1000_0000;
let (result, memory) = relocate(&bytes, base);
assert_eq!(
result.expect("relocate").delta,
base as i64 - PREFERRED as i64
);
assert_eq!(
memory.read_u64_bypass(base + 0x1010).unwrap(),
base + 0x1100
);
assert_eq!(
memory.read_u64_bypass(base + 0x1018).unwrap(),
base + 0x2000
);
}
#[test]
fn preferred_base_leaves_targets_unchanged() {
let table = standard_table();
let bytes = build(16, &table, table.len() as u32);
let (result, memory) = relocate(&bytes, PREFERRED);
assert_eq!(result.expect("relocate").applied_dir64, 0);
assert_eq!(
memory.read_u64_bypass(PREFERRED + 0x1010).unwrap(),
PREFERRED + 0x1100
);
}
#[test]
fn directory_beyond_declared_count_is_ignored() {
// NumberOfRvaAndSizes = 5 means directory index 5 does not exist.
let table = standard_table();
let bytes = build(5, &table, table.len() as u32);
let base = PREFERRED + 0x1_0000_0000;
let (result, memory) = relocate(&bytes, base);
assert_eq!(result.expect("relocate").applied_dir64, 0);
assert_eq!(
memory.read_u64_bypass(base + 0x1010).unwrap(),
PREFERRED + 0x1100
);
}
#[test]
fn unsupported_type_is_rejected() {
let table = block(0x1000, &[0x3010, 0x0000]); // HIGHLOW is not a PE32+ fixup here
let bytes = build(16, &table, table.len() as u32);
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
assert_eq!(
result.unwrap_err(),
RelocationError::UnsupportedRelocationType(3)
);
}
#[test]
fn malformed_block_sizes_are_rejected() {
let base = PREFERRED + 0x1000;
for size in [0u32, 4, 7, 11] {
let mut table = 0x1000u32.to_le_bytes().to_vec();
table.extend_from_slice(&size.to_le_bytes());
table.extend_from_slice(&[0; 8]);
let bytes = build(16, &table, table.len() as u32);
let (result, _) = relocate(&bytes, base);
assert_eq!(
result.unwrap_err(),
RelocationError::MalformedBlockHeader { offset: RELOC_FILE },
"block size {size}"
);
}
}
#[test]
fn block_larger_than_directory_is_rejected() {
let table = standard_table(); // 14 bytes
let bytes = build(16, &table, 12);
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
assert_eq!(
result.unwrap_err(),
RelocationError::BlockSizeOutOfBounds {
block_size: 14,
max_size: 12
}
);
}
#[test]
fn trailing_partial_block_header_is_rejected() {
let mut table = block(0x1000, &[0xA010, 0x0000]);
table.extend_from_slice(&[0; 4]);
let bytes = build(16, &table, table.len() as u32);
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
assert_eq!(
result.unwrap_err(),
RelocationError::MalformedBlockHeader {
offset: RELOC_FILE + 12
}
);
}
#[test]
fn directory_past_end_of_file_is_rejected() {
let table = standard_table();
let bytes = build(16, &table, 0x300); // .reloc raw data starts at 0x400 in a 0x600-byte file
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
assert_eq!(
result.unwrap_err(),
RelocationError::DirectoryOutOfBounds {
rva: 0x2000,
size: 0x300
}
);
}
#[test]
fn target_outside_image_is_rejected_even_if_mapped() {
// SizeOfImage is 0x3000; RVA 0x3000 is past the image but mapped by another region.
let table = block(0x3000, &[0xA000, 0x0000]);
let bytes = build(16, &table, table.len() as u32);
let base = PREFERRED + 0x1000;
let (pe, mut memory) = load(&bytes, base);
let rw = pe.sections[1].permissions;
memory
.map_region(base + 0x3000, 0x1000, rw)
.expect("adjacent mapping");
memory.write_u64_bypass(base + 0x3000, 0x55).unwrap();
let result = apply_relocations(&pe, &bytes, base, &mut memory);
assert_eq!(
result.unwrap_err(),
RelocationError::TargetOutOfBounds {
target_va: base + 0x3000
}
);
assert_eq!(memory.read_u64_bypass(base + 0x3000).unwrap(), 0x55);
}
#[test]
fn target_rva_at_top_of_address_space_is_rejected() {
let table = block(0xFFFF_F000, &[0xAFFC, 0x0000]);
let bytes = build(16, &table, table.len() as u32);
let (result, _) = relocate(&bytes, PREFERRED + 0x1000);
assert!(matches!(
result,
Err(RelocationError::TargetOutOfBounds { .. })
));
}
+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
+2
View File
@@ -32,6 +32,7 @@ objc2-foundation = { version = "=0.3.2", default-features = false, features = ["
objc2-metal = { version = "=0.3.2", default-features = false, features = [
"std",
"MTLAllocation",
"MTLArgument",
"MTLBuffer",
"MTLCommandBuffer",
"MTLCommandEncoder",
@@ -40,6 +41,7 @@ objc2-metal = { version = "=0.3.2", default-features = false, features = [
"MTLComputePipeline",
"MTLDepthStencil",
"MTLDevice",
"MTLEvent",
"MTLLibrary",
"MTLPixelFormat",
"MTLPipeline",
+432 -40
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,
@@ -23,12 +26,17 @@ use xenora_texture::{
#[path = "render.rs"]
mod render;
pub use render::{DepthCompare, DepthDraw, DepthFill, DepthOutput, DepthPass, DepthState};
pub use render::{
BlendDraw, BlendFactor, BlendOperation, BlendPass, BlendState, ColorWriteMask, DepthCompare,
DepthDraw, DepthFill, DepthOutput, DepthPass, DepthState, IndexBuffer, IndexedDraw,
IndexedPass,
};
const MAX_THREADS_PER_GROUP: usize = 64;
const MAX_GROUPS: usize = 64;
const MAX_GRID_WORDS: usize = MAX_GROUPS * MAX_THREADS_PER_GROUP;
const MAX_SOURCE_BYTES: usize = 64 * 1024;
const MAX_IN_FLIGHT: usize = 16;
const BC_READBACK: &str = r"
#include <metal_stdlib>
@@ -61,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],
},
}
@@ -143,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>,
}
@@ -151,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
///
@@ -174,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())
@@ -557,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
@@ -604,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))
}
@@ -632,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)?;
@@ -668,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")
})?;
@@ -706,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(
@@ -786,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
@@ -825,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));
+4 -2
View File
@@ -14,8 +14,10 @@ pub mod texture_pipeline;
#[cfg(all(target_arch = "aarch64", target_os = "macos"))]
pub use compute::{
DepthCompare, DepthDraw, DepthFill, DepthOutput, DepthPass, DepthState, GuestBuffer,
GuestBufferView, MetalError, NativeCompute, RunProfile,
BlendDraw, BlendFactor, BlendOperation, BlendPass, BlendState, ColorWriteMask, DepthCompare,
DepthDraw, DepthFill, DepthOutput, DepthPass, DepthState, GuestBuffer, GuestBufferView,
IndexBuffer, IndexedDraw, IndexedPass, MetalError, NativeCompute, RunProfile, Submission,
SubmissionGate,
};
#[cfg(all(target_arch = "aarch64", target_os = "macos"))]
+594 -6
View File
@@ -6,12 +6,12 @@ use objc2::rc::{Retained, autoreleasepool};
use objc2::runtime::{NSObjectProtocol, ProtocolObject};
use objc2::sel;
use objc2_metal::{
MTLClearColor, MTLCommandBuffer, MTLCommandEncoder, MTLCommandQueue, MTLCompareFunction,
MTLDepthStencilDescriptor, MTLDepthStencilState, MTLDevice, MTLFunction, MTLLoadAction,
MTLOrigin, MTLPixelFormat, MTLPrimitiveType, MTLRegion, MTLRenderCommandEncoder,
MTLRenderPassDescriptor, MTLRenderPipelineDescriptor, MTLRenderPipelineState,
MTLShaderValidation, MTLSize, MTLStorageMode, MTLStoreAction, MTLTexture, MTLTextureDescriptor,
MTLTextureUsage, MTLViewport,
MTLBlendFactor, MTLBlendOperation, MTLClearColor, MTLColorWriteMask, MTLCommandBuffer,
MTLCommandEncoder, MTLCommandQueue, MTLCompareFunction, MTLDepthStencilDescriptor,
MTLDepthStencilState, MTLDevice, MTLFunction, MTLIndexType, MTLLoadAction, MTLOrigin,
MTLPixelFormat, MTLPrimitiveType, MTLRegion, MTLRenderCommandEncoder, MTLRenderPassDescriptor,
MTLRenderPipelineDescriptor, MTLRenderPipelineState, MTLShaderValidation, MTLSize,
MTLStorageMode, MTLStoreAction, MTLTexture, MTLTextureDescriptor, MTLTextureUsage, MTLViewport,
};
use xenora_texture::{Bc1Subresource, Bc1Upload};
@@ -717,6 +717,312 @@ impl NativeCompute {
}
}
const MAX_INDEXED_VERTICES: usize = 1024;
const MAX_INDICES: usize = 4096;
/// An index buffer of 16- or 32-bit unsigned indices.
#[derive(Clone, Copy, Debug)]
pub enum IndexBuffer<'a> {
U16(&'a [u16]),
U32(&'a [u32]),
}
impl IndexBuffer<'_> {
fn len(self) -> usize {
match self {
Self::U16(indices) => indices.len(),
Self::U32(indices) => indices.len(),
}
}
fn index(self, position: usize) -> u32 {
match self {
Self::U16(indices) => u32::from(indices[position]),
Self::U32(indices) => indices[position],
}
}
fn restart(self) -> u32 {
match self {
Self::U16(_) => u32::from(u16::MAX),
Self::U32(_) => u32::MAX,
}
}
fn size(self) -> usize {
match self {
Self::U16(_) => 2,
Self::U32(_) => 4,
}
}
/// The indices packed into little-endian words, the last one zero-padded.
fn words(self) -> Vec<u32> {
match self {
Self::U16(indices) => indices
.chunks(2)
.map(|pair| {
u32::from(pair[0]) | pair.get(1).map_or(0, |&high| u32::from(high) << 16)
})
.collect(),
Self::U32(indices) => indices.to_vec(),
}
}
}
/// One indexed triangle-list draw: `index_count` indices from `start_index`,
/// each fetching vertex `index + base_vertex`.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct IndexedDraw {
pub start_index: usize,
pub index_count: usize,
pub base_vertex: i32,
pub fill: DepthFill,
}
/// An offscreen pass of up to 16 indexed draws, in order, into a cleared
/// RGBA8Unorm target without depth attachment.
#[derive(Clone, Copy, Debug)]
pub struct IndexedPass<'a> {
pub extent: [usize; 2],
pub clear_color: [u8; 4],
/// Up to 1024 clip-space float4 positions.
pub vertices: &'a [[f32; 4]],
/// Up to 4096 indices shared by every draw.
pub indices: IndexBuffer<'a>,
pub draws: &'a [IndexedDraw],
/// As [`DepthPass::texture`], for [`DepthFill::Bc1Texture`] draws.
pub texture: Option<&'a Bc1Upload<'a>>,
}
impl NativeCompute {
/// Draw an indexed offscreen pass and read back its colour.
///
/// Each draw is one native `drawIndexedPrimitives` call on the pass's
/// index buffer with the draw's start offset and signed base vertex, so
/// Metal itself fetches the vertices. Every fetched vertex is checked
/// against the vertex buffer first: out-of-range fetches and raw
/// primitive-restart values are rejected, never left to the GPU. Base vertex needs no capability query: the
/// Apple family 7 that [`NativeCompute::new`] requires supports it.
///
/// # Errors
///
/// Returns an error for an invalid extent, too many draws, vertices or
/// indices, non-finite positions, an index count that is zero or not a
/// multiple of 3, an index range past the buffer, a primitive-restart
/// index, a fetched vertex outside the vertex buffer, a textured draw without texture, unavailable BC
/// compression (operation `supportsBCTextureCompression`), or Metal setup
/// or execution failure.
pub fn render_indexed(&self, pass: &IndexedPass<'_>) -> Result<Vec<u8>, MetalError> {
let [width, height] = pass.extent;
let pixels = width
.checked_mul(height)
.filter(|&count| (1..=MAX_PIXELS).contains(&count))
.ok_or_else(|| MetalError::new("render bounds", "expected 1..=4096 pixels"))?;
validate_indexed_pass(pass)?;
let bc1 = pass
.texture
.map(|upload| {
let level = upload.subresource(0, 0).map_err(|error| {
MetalError::new("texture subresource", format!("{error:?}"))
})?;
self.validate_bc_extent(level.width, level.height, "BC1")?;
self.new_bc1_texture(&level)
})
.transpose()?;
autoreleasepool(|_| {
let options = compile_options()?;
let library = self.compile_library(DEPTH_SOURCE, &options)?;
let vertex = find_function(&library, "depth_vertex")?;
let flat = self.depth_pipeline(
&vertex,
&*find_function(&library, "depth_flat")?,
MTLPixelFormat::Invalid,
)?;
let textured = self.depth_pipeline(
&vertex,
&*find_function(&library, "depth_textured")?,
MTLPixelFormat::Invalid,
)?;
let color = self.new_target(
PIXEL_FORMAT,
width,
height,
MTLStorageMode::Shared,
MTLTextureUsage::RenderTarget,
)?;
let pass_descriptor = MTLRenderPassDescriptor::renderPassDescriptor();
// SAFETY: Slot zero is the only color attachment for this pass.
let attachment = unsafe {
pass_descriptor
.colorAttachments()
.objectAtIndexedSubscript(0)
};
attachment.setTexture(Some(&color));
attachment.setLoadAction(MTLLoadAction::Clear);
let [red, green, blue, alpha] = pass.clear_color.map(|value| f64::from(value) / 255.0);
attachment.setClearColor(MTLClearColor {
red,
green,
blue,
alpha,
});
attachment.setStoreAction(MTLStoreAction::Store);
let positions: Vec<u32> = pass
.vertices
.as_flattened()
.iter()
.map(|value| value.to_bits())
.collect();
let positions = self.new_buffer(&positions)?;
let indices = self.new_buffer(&pass.indices.words())?;
let index_type = match pass.indices {
IndexBuffer::U16(_) => MTLIndexType::UInt16,
IndexBuffer::U32(_) => MTLIndexType::UInt32,
};
let command = self.queue.commandBuffer().ok_or_else(|| {
MetalError::new("commandBuffer", "render command buffer creation failed")
})?;
let encoder = command
.renderCommandEncoderWithDescriptor(&pass_descriptor)
.ok_or_else(|| {
MetalError::new(
"renderCommandEncoderWithDescriptor",
"render encoder creation failed",
)
})?;
encoder.setViewport(MTLViewport {
originX: 0.0,
originY: 0.0,
width: width as f64,
height: height as f64,
znear: 0.0,
zfar: 1.0,
});
let extent = [width as f32, height as f32];
for draw in pass.draws {
// SAFETY: Validation proved that every index the draw reads lies
// inside the index buffer, that the offset is a multiple of the
// index size, and that every `index + base_vertex` names a float4
// of the position buffer, the only memory the vertex stage reads.
// Fragment constants are copied by Metal and match the declared
// types. The texture, when bound, is a live BC1 texture of this
// device; both buffers outlive the command.
unsafe {
encoder.setVertexBuffer_offset_atIndex(Some(&positions), 0, 0);
match draw.fill {
DepthFill::Flat(rgba) => {
encoder.setRenderPipelineState(&flat);
let rgba = rgba.map(|value| f32::from(value) / 255.0);
encoder.setFragmentBytes_length_atIndex(
NonNull::from(&rgba).cast(),
size_of_val(&rgba),
0,
);
}
DepthFill::Bc1Texture => {
encoder.setRenderPipelineState(&textured);
encoder.setFragmentTexture_atIndex(bc1.as_deref(), 0);
encoder.setFragmentBytes_length_atIndex(
NonNull::from(&extent).cast(),
size_of_val(&extent),
0,
);
}
}
encoder.drawIndexedPrimitives_indexCount_indexType_indexBuffer_indexBufferOffset_instanceCount_baseVertex_baseInstance(
MTLPrimitiveType::Triangle,
draw.index_count,
index_type,
&indices,
draw.start_index * pass.indices.size(),
1,
draw.base_vertex as isize,
0,
);
}
}
encoder.endEncoding();
complete_command(&command)?;
let mut output = vec![0; pixels * 4];
// SAFETY: GPU writes have completed, and the initialized output
// allocation fits the entire shared texture with tightly packed rows.
unsafe {
color.getBytes_bytesPerRow_fromRegion_mipmapLevel(
NonNull::from(output.as_mut_slice()).cast(),
width * 4,
whole(width, height),
0,
);
}
Ok(output)
})
}
}
fn validate_indexed_pass(pass: &IndexedPass<'_>) -> Result<(), MetalError> {
let invalid = |reason: String| Err(MetalError::new("indexed pass", reason));
if pass.draws.len() > MAX_DEPTH_DRAWS {
return invalid("expected at most 16 draws".to_owned());
}
if !(1..=MAX_INDEXED_VERTICES).contains(&pass.vertices.len())
|| !(1..=MAX_INDICES).contains(&pass.indices.len())
{
return invalid("expected 1..=1024 vertices and 1..=4096 indices".to_owned());
}
if pass
.vertices
.as_flattened()
.iter()
.any(|value| !value.is_finite())
{
return Err(MetalError::new(
"render input",
"expected finite vertex data",
));
}
for (number, draw) in pass.draws.iter().enumerate() {
if draw.index_count == 0 || !draw.index_count.is_multiple_of(3) {
return invalid(format!(
"draw {number}: index count must be a nonzero multiple of 3"
));
}
let end = draw
.start_index
.checked_add(draw.index_count)
.filter(|&end| end <= pass.indices.len())
.ok_or_else(|| {
MetalError::new(
"indexed pass",
format!("draw {number}: index range past the index buffer"),
)
})?;
for position in draw.start_index..end {
let index = pass.indices.index(position);
// Metal documents 0xFFFF / 0xFFFFFFFF as the primitive-restart value
// of indexed draws without defining it for triangle lists, so the
// raw value is rejected whatever the base vertex.
if index == pass.indices.restart() {
return invalid(format!(
"draw {number}: index {position} is the primitive-restart value"
));
}
let vertex = i64::from(index) + i64::from(draw.base_vertex);
if !(0..pass.vertices.len() as i64).contains(&vertex) {
return invalid(format!(
"draw {number}: index {position} fetches vertex {vertex} outside the vertex buffer"
));
}
}
if draw.fill == DepthFill::Bc1Texture && pass.texture.is_none() {
return invalid("textured draw without texture".to_owned());
}
}
Ok(())
}
fn validate_depth_pass(pass: &DepthPass<'_>) -> Result<(), MetalError> {
if pass.draws.len() > MAX_DEPTH_DRAWS {
return Err(MetalError::new("depth pass", "expected at most 16 draws"));
@@ -775,3 +1081,285 @@ fn whole(width: usize, height: usize) -> MTLRegion {
},
}
}
/// A blend factor, as Metal defines it for the RGB and the alpha channel.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BlendFactor {
Zero,
One,
SourceColor,
OneMinusSourceColor,
SourceAlpha,
OneMinusSourceAlpha,
DestinationColor,
OneMinusDestinationColor,
DestinationAlpha,
OneMinusDestinationAlpha,
}
impl BlendFactor {
fn metal(self) -> MTLBlendFactor {
match self {
Self::Zero => MTLBlendFactor::Zero,
Self::One => MTLBlendFactor::One,
Self::SourceColor => MTLBlendFactor::SourceColor,
Self::OneMinusSourceColor => MTLBlendFactor::OneMinusSourceColor,
Self::SourceAlpha => MTLBlendFactor::SourceAlpha,
Self::OneMinusSourceAlpha => MTLBlendFactor::OneMinusSourceAlpha,
Self::DestinationColor => MTLBlendFactor::DestinationColor,
Self::OneMinusDestinationColor => MTLBlendFactor::OneMinusDestinationColor,
Self::DestinationAlpha => MTLBlendFactor::DestinationAlpha,
Self::OneMinusDestinationAlpha => MTLBlendFactor::OneMinusDestinationAlpha,
}
}
}
/// A blend operation combining the weighted source and destination; `Min`
/// and `Max` take the unweighted values and ignore the factors.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BlendOperation {
Add,
Subtract,
ReverseSubtract,
Min,
Max,
}
impl BlendOperation {
fn metal(self) -> MTLBlendOperation {
match self {
Self::Add => MTLBlendOperation::Add,
Self::Subtract => MTLBlendOperation::Subtract,
Self::ReverseSubtract => MTLBlendOperation::ReverseSubtract,
Self::Min => MTLBlendOperation::Min,
Self::Max => MTLBlendOperation::Max,
}
}
}
/// Separate RGB and alpha blend equations of one draw.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct BlendState {
pub source_rgb: BlendFactor,
pub destination_rgb: BlendFactor,
pub rgb_operation: BlendOperation,
pub source_alpha: BlendFactor,
pub destination_alpha: BlendFactor,
pub alpha_operation: BlendOperation,
}
/// The colour channels a draw writes; the others keep the stored value.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ColorWriteMask {
pub red: bool,
pub green: bool,
pub blue: bool,
pub alpha: bool,
}
impl ColorWriteMask {
pub const ALL: Self = Self {
red: true,
green: true,
blue: true,
alpha: true,
};
fn metal(self) -> MTLColorWriteMask {
[
(self.red, MTLColorWriteMask::Red),
(self.green, MTLColorWriteMask::Green),
(self.blue, MTLColorWriteMask::Blue),
(self.alpha, MTLColorWriteMask::Alpha),
]
.into_iter()
.filter(|(on, _)| *on)
.fold(MTLColorWriteMask::None, |mask, (_, bit)| mask | bit)
}
}
/// One flat-coloured triangle of a blend pass.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BlendDraw {
pub positions: [[f32; 4]; 3],
pub color: [u8; 4],
/// `None` disables blending: the source replaces the masked channels.
pub blend: Option<BlendState>,
pub write_mask: ColorWriteMask,
}
/// An offscreen pass of up to 16 triangles drawn in order into a cleared
/// RGBA8Unorm target without depth attachment.
#[derive(Clone, Copy, Debug)]
pub struct BlendPass<'a> {
pub extent: [usize; 2],
pub clear_color: [u8; 4],
pub draws: &'a [BlendDraw],
}
impl NativeCompute {
/// Draw a blended, write-masked offscreen pass and read back its colour.
///
/// Blend state and write mask are pipeline state in Metal, so each draw
/// gets its own pipeline built from exactly the draw's settings.
///
/// # Errors
///
/// Returns an error for an invalid extent, too many draws, non-finite
/// positions, or Metal setup or execution failure.
pub fn render_blend(&self, pass: &BlendPass<'_>) -> Result<Vec<u8>, MetalError> {
let [width, height] = pass.extent;
let pixels = width
.checked_mul(height)
.filter(|&count| (1..=MAX_PIXELS).contains(&count))
.ok_or_else(|| MetalError::new("render bounds", "expected 1..=4096 pixels"))?;
if pass.draws.len() > MAX_DEPTH_DRAWS {
return Err(MetalError::new("blend pass", "expected at most 16 draws"));
}
if pass
.draws
.iter()
.flat_map(|draw| draw.positions.as_flattened())
.any(|value| !value.is_finite())
{
return Err(MetalError::new(
"render input",
"expected finite vertex data",
));
}
autoreleasepool(|_| {
let options = compile_options()?;
let library = self.compile_library(DEPTH_SOURCE, &options)?;
let vertex = find_function(&library, "depth_vertex")?;
let fragment = find_function(&library, "depth_flat")?;
let pipelines = pass
.draws
.iter()
.map(|draw| self.blend_pipeline(&vertex, &fragment, draw))
.collect::<Result<Vec<_>, _>>()?;
let color = self.new_target(
PIXEL_FORMAT,
width,
height,
MTLStorageMode::Shared,
MTLTextureUsage::RenderTarget,
)?;
let pass_descriptor = MTLRenderPassDescriptor::renderPassDescriptor();
// SAFETY: Slot zero is the only color attachment for this pass.
let attachment = unsafe {
pass_descriptor
.colorAttachments()
.objectAtIndexedSubscript(0)
};
attachment.setTexture(Some(&color));
attachment.setLoadAction(MTLLoadAction::Clear);
let [red, green, blue, alpha] = pass.clear_color.map(|value| f64::from(value) / 255.0);
attachment.setClearColor(MTLClearColor {
red,
green,
blue,
alpha,
});
attachment.setStoreAction(MTLStoreAction::Store);
let words: Vec<u32> = pass
.draws
.iter()
.flat_map(|draw| draw.positions.as_flattened())
.map(|value| value.to_bits())
.collect();
let positions = (!words.is_empty())
.then(|| self.new_buffer(&words))
.transpose()?;
let command = self.queue.commandBuffer().ok_or_else(|| {
MetalError::new("commandBuffer", "render command buffer creation failed")
})?;
let encoder = command
.renderCommandEncoderWithDescriptor(&pass_descriptor)
.ok_or_else(|| {
MetalError::new(
"renderCommandEncoderWithDescriptor",
"render encoder creation failed",
)
})?;
encoder.setViewport(MTLViewport {
originX: 0.0,
originY: 0.0,
width: width as f64,
height: height as f64,
znear: 0.0,
zfar: 1.0,
});
for (index, (draw, pipeline)) in pass.draws.iter().zip(&pipelines).enumerate() {
encoder.setRenderPipelineState(pipeline);
let rgba = draw.color.map(|value| f32::from(value) / 255.0);
// SAFETY: The position buffer holds three float4s per draw and
// the vertex stage reads only this draw's three. The fragment
// constant is copied by Metal and matches the declared float4.
unsafe {
encoder.setVertexBuffer_offset_atIndex(positions.as_deref(), index * 48, 0);
encoder.setFragmentBytes_length_atIndex(
NonNull::from(&rgba).cast(),
size_of_val(&rgba),
0,
);
encoder.drawPrimitives_vertexStart_vertexCount(
MTLPrimitiveType::Triangle,
0,
3,
);
}
}
encoder.endEncoding();
complete_command(&command)?;
let mut output = vec![0; pixels * 4];
// SAFETY: GPU writes have completed, and the initialized output
// allocation fits the entire shared texture with tightly packed rows.
unsafe {
color.getBytes_bytesPerRow_fromRegion_mipmapLevel(
NonNull::from(output.as_mut_slice()).cast(),
width * 4,
whole(width, height),
0,
);
}
Ok(output)
})
}
fn blend_pipeline(
&self,
vertex: &ProtocolObject<dyn MTLFunction>,
fragment: &ProtocolObject<dyn MTLFunction>,
draw: &BlendDraw,
) -> Result<Retained<ProtocolObject<dyn MTLRenderPipelineState>>, MetalError> {
let descriptor = MTLRenderPipelineDescriptor::new();
descriptor.setVertexFunction(Some(vertex));
descriptor.setFragmentFunction(Some(fragment));
// SAFETY: Slot zero is the only color attachment for this pipeline.
let attachment = unsafe { descriptor.colorAttachments().objectAtIndexedSubscript(0) };
attachment.setPixelFormat(PIXEL_FORMAT);
attachment.setWriteMask(draw.write_mask.metal());
attachment.setBlendingEnabled(draw.blend.is_some());
if let Some(blend) = draw.blend {
attachment.setSourceRGBBlendFactor(blend.source_rgb.metal());
attachment.setDestinationRGBBlendFactor(blend.destination_rgb.metal());
attachment.setRgbBlendOperation(blend.rgb_operation.metal());
attachment.setSourceAlphaBlendFactor(blend.source_alpha.metal());
attachment.setDestinationAlphaBlendFactor(blend.destination_alpha.metal());
attachment.setAlphaBlendOperation(blend.alpha_operation.metal());
}
let pipeline = self
.device
.newRenderPipelineStateWithDescriptor_error(&descriptor)
.map_err(|error| {
MetalError::new(
"newRenderPipelineStateWithDescriptor",
error.localizedDescription().to_string(),
)
})?;
verify_render_validation(&pipeline)?;
Ok(pipeline)
}
}
+36
View File
@@ -0,0 +1,36 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! CPU check: the blend reference agrees with the independently derived
//! expectations for every blend case, colour and rounding flags alike. Runs
//! without a GPU.
#[path = "support/blend_cases.rs"]
mod blend_cases;
use blend_cases::{CLEAR, SIZE, cases, expected};
use xenora_ref::blend::{RefBlendDraw, render_blend};
#[test]
fn reference_matches_independent_expectations() {
let (cases, expected) = (cases(), expected());
assert_eq!(cases.len(), 39);
assert_eq!(expected.len(), cases.len());
for (case, want) in cases.iter().zip(&expected) {
assert_eq!(case.name, want.name);
let draws: Vec<_> = case
.draws
.iter()
.map(|draw| RefBlendDraw {
positions: draw.positions,
color: draw.color,
blend: draw.blend,
mask: draw.mask,
})
.collect();
let pixels = render_blend([SIZE, SIZE], CLEAR, &draws).expect("reference render");
let color: Vec<_> = pixels.iter().map(|p| p.map(|c| c.value)).collect();
let exact: Vec<_> = pixels.iter().map(|p| p.map(|c| c.exact)).collect();
assert_eq!(color, want.color, "{} colour", case.name);
assert_eq!(exact, want.exact, "{} rounding flags", case.name);
}
}
+842
View File
@@ -0,0 +1,842 @@
case clear
palette A 32 64 96 128 eeee
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
color AAAAAAAAAAAAAAAA
end
case disabled
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 60 180 240 96 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCCCCCCC
color AAAACCCCCCCCCCCB
color AAAAACCCCCCCCCBB
color AAAAACCCCCCCCBBB
color AAAAACCCCCCCBBBB
color AAABBCCCCCCBBBBB
color AABBBCCCCCCBBBBB
color ABBBBCCCCCBBBBBB
color BBBBBCCCCBBBBBBB
color BBBBBBCCBBBBBBBB
color BBBBBBCBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case src_Zero
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 0 0 0 0 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCCCCCCC
color AAAACCCCCCCCCCCB
color AAAAACCCCCCCCCBB
color AAAAACCCCCCCCBBB
color AAAAACCCCCCCBBBB
color AAABBCCCCCCBBBBB
color AABBBCCCCCCBBBBB
color ABBBBCCCCCBBBBBB
color BBBBBCCCCBBBBBBB
color BBBBBBCCBBBBBBBB
color BBBBBBCBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case src_One
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 60 180 240 96 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCCCCCCC
color AAAACCCCCCCCCCCB
color AAAAACCCCCCCCCBB
color AAAAACCCCCCCCBBB
color AAAAACCCCCCCBBBB
color AAABBCCCCCCBBBBB
color AABBBCCCCCCBBBBB
color ABBBBCCCCCBBBBBB
color BBBBBCCCCBBBBBBB
color BBBBBBCCBBBBBBBB
color BBBBBBCBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case src_SourceColor
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 14 127 226 36 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCCCCCCC
color AAAACCCCCCCCCCCB
color AAAAACCCCCCCCCBB
color AAAAACCCCCCCCBBB
color AAAAACCCCCCCBBBB
color AAABBCCCCCCBBBBB
color AABBBCCCCCCBBBBB
color ABBBBCCCCCBBBBBB
color BBBBBCCCCBBBBBBB
color BBBBBBCCBBBBBBBB
color BBBBBBCBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case src_OneMinusSourceColor
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 46 53 14 60 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCCCCCCC
color AAAACCCCCCCCCCCB
color AAAAACCCCCCCCCBB
color AAAAACCCCCCCCBBB
color AAAAACCCCCCCBBBB
color AAABBCCCCCCBBBBB
color AABBBCCCCCCBBBBB
color ABBBBCCCCCBBBBBB
color BBBBBCCCCBBBBBBB
color BBBBBBCCBBBBBBBB
color BBBBBBCBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case src_SourceAlpha
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 23 68 90 36 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCCCCCCC
color AAAACCCCCCCCCCCB
color AAAAACCCCCCCCCBB
color AAAAACCCCCCCCBBB
color AAAAACCCCCCCBBBB
color AAABBCCCCCCBBBBB
color AABBBCCCCCCBBBBB
color ABBBBCCCCCBBBBBB
color BBBBBCCCCBBBBBBB
color BBBBBBCCBBBBBBBB
color BBBBBBCBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case src_OneMinusSourceAlpha
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 37 112 150 60 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCCCCCCC
color AAAACCCCCCCCCCCB
color AAAAACCCCCCCCCBB
color AAAAACCCCCCCCBBB
color AAAAACCCCCCCBBBB
color AAABBCCCCCCBBBBB
color AABBBCCCCCCBBBBB
color ABBBBCCCCCBBBBBB
color BBBBBCCCCBBBBBBB
color BBBBBBCCBBBBBBBB
color BBBBBBCBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case src_DestinationColor
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 47 71 47 60 rrrr
palette D 8 45 90 48 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case src_OneMinusDestinationColor
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 13 109 193 36 rrrr
palette D 52 135 150 48 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case src_DestinationAlpha
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 38 113 151 60 rrrr
palette D 30 90 120 48 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case src_OneMinusDestinationAlpha
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 22 67 89 36 rrrr
palette D 30 90 120 48 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case dst_Zero
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 0 0 0 0 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCCCCCCC
color AAAACCCCCCCCCCCB
color AAAAACCCCCCCCCBB
color AAAAACCCCCCCCBBB
color AAAAACCCCCCCBBBB
color AAABBCCCCCCBBBBB
color AABBBCCCCCCBBBBB
color ABBBBCCCCCBBBBBB
color BBBBBCCCCBBBBBBB
color BBBBBBCCBBBBBBBB
color BBBBBBCBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case dst_One
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAAAAAAAAABBBBB
color AAAAAAAAAABBBBBB
color AAAAAAAAABBBBBBB
color AAAAAAABBBBBBBBB
color AAAAAABBBBBBBBBB
color AAAAABBBBBBBBBBB
color AAABBBBBBBBBBBBB
color AABBBBBBBBBBBBBB
color ABBBBBBBBBBBBBBB
color BBBBBBBBBBBBBBBB
color BBBBBBBBBBBBBBBB
color BBBBBBBBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case dst_SourceColor
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 47 71 47 60 rrrr
palette D 8 45 90 48 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case dst_OneMinusSourceColor
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 153 29 3 100 rrrr
palette D 24 19 6 80 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case dst_SourceAlpha
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 75 38 19 60 rrrr
palette D 12 24 36 48 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case dst_OneMinusSourceAlpha
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 125 62 31 100 rrrr
palette D 20 40 60 80 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case dst_DestinationColor
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 157 39 10 100 rrrr
palette D 4 16 36 64 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case dst_OneMinusDestinationColor
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 43 61 40 60 rrrr
palette D 28 48 60 64 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case dst_DestinationAlpha
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 125 63 31 100 rrrr
palette D 16 32 48 64 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case dst_OneMinusDestinationAlpha
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 75 37 19 60 rrrr
palette D 16 32 48 64 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case op_Add
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 147 130 122 136 rrrr
palette D 43 108 150 116 rrrr
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case op_Subtract
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 0 5 59 0 erre
palette D 3 28 30 0 rrre
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case op_ReverseSubtract
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 102 0 0 64 reer
palette D 0 0 0 44 eeer
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case op_Min
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 60 100 50 96 eeee
palette D 32 64 96 96 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case op_Max
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 200 180 240 160 eeee
palette D 60 180 240 128 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case additive_clamp
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 255 255 255 255 eeee
palette D 92 244 255 224 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case separate_alpha
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 147 130 122 96 rrre
palette D 43 108 150 96 rrre
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case mask_R
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 60 100 50 160 eeee
palette D 60 64 96 128 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case mask_G
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 200 180 50 160 eeee
palette D 32 180 96 128 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case mask_B
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 200 100 240 160 eeee
palette D 32 64 240 128 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case mask_A
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 200 100 50 96 eeee
palette D 32 64 96 96 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case mask_RGB
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 60 180 240 160 eeee
palette D 60 180 240 128 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case mask_none
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAAAAAAAAABBBBB
color AAAAAAAAAABBBBBB
color AAAAAAAAABBBBBBB
color AAAAAAABBBBBBBBB
color AAAAAABBBBBBBBBB
color AAAAABBBBBBBBBBB
color AAABBBBBBBBBBBBB
color AABBBBBBBBBBBBBB
color ABBBBBBBBBBBBBBB
color BBBBBBBBBBBBBBBB
color BBBBBBBBBBBBBBBB
color BBBBBBBBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case mask_RGBA
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 60 180 240 96 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCCCCCCC
color AAAACCCCCCCCCCCB
color AAAAACCCCCCCCCBB
color AAAAACCCCCCCCBBB
color AAAAACCCCCCCBBBB
color AAABBCCCCCCBBBBB
color AABBBCCCCCCBBBBB
color ABBBBCCCCCBBBBBB
color BBBBBCCCCBBBBBBB
color BBBBBBCCBBBBBBBB
color BBBBBBCBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case mask_RG_blended
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 147 130 50 160 rree
palette D 43 108 96 128 rree
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case separate_operation
palette A 200 100 50 160 eeee
palette B 32 64 96 128 eeee
palette C 147 130 122 64 rrre
palette D 43 108 150 32 rrre
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
case first_draw_blended
palette A 32 87 67 148 errr
palette B 32 64 96 128 eeee
palette C 60 180 67 148 eerr
palette D 60 180 96 128 eeee
color AAAAAAAAAAAAAAAB
color AAAAAAAAAAAAAABB
color AAAAAAAAAAAAABBB
color AAAACCCCCCABBBBB
color AAAACCCCCCDDDDDD
color AAAACCCCCDDDDDDB
color AAAAACCDDDDDDDBB
color AAAAACDDDDDDDBBB
color AAAAADDDDDDDBBBB
color AAABBDDDDDDBBBBB
color AABBBDDDDDDBBBBB
color ABBBBDDDDDBBBBBB
color BBBBBDDDDBBBBBBB
color BBBBBBDDBBBBBBBB
color BBBBBBDBBBBBBBBB
color BBBBBBBBBBBBBBBB
end
+361
View File
@@ -0,0 +1,361 @@
case clear
palette 0 16 32 48 255
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
end
case u16_first
fetch 0 1 2
palette 0 255 0 0 255
palette 1 0 0 0 255
color 0000000000000001
color 0000000000000011
color 0000000000000111
color 0000000000011111
color 0000000000111111
color 0000000001111111
color 0000000111111111
color 0000001111111111
color 0000011111111111
color 0001111111111111
color 0011111111111111
color 0111111111111111
color 1111111111111111
color 1111111111111111
color 1111111111111111
color 1111111111111111
end
case u32_first
fetch 0 1 2
palette 0 255 0 0 255
palette 1 0 0 0 255
color 0000000000000001
color 0000000000000011
color 0000000000000111
color 0000000000011111
color 0000000000111111
color 0000000001111111
color 0000000111111111
color 0000001111111111
color 0000011111111111
color 0001111111111111
color 0011111111111111
color 0111111111111111
color 1111111111111111
color 1111111111111111
color 1111111111111111
color 1111111111111111
end
case u16_odd_start
fetch 3 4 5
palette 0 0 0 0 255
palette 1 0 255 0 255
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000111111000000
color 0000111111111111
color 0000111111111110
color 0000011111111100
color 0000011111111000
color 0000011111110000
color 0000011111100000
color 0000011111100000
color 0000011111000000
color 0000011110000000
color 0000001100000000
color 0000001000000000
color 0000000000000000
end
case u32_start
fetch 3 4 5
palette 0 0 0 0 255
palette 1 0 255 0 255
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000111111000000
color 0000111111111111
color 0000111111111110
color 0000011111111100
color 0000011111111000
color 0000011111110000
color 0000011111100000
color 0000011111100000
color 0000011111000000
color 0000011110000000
color 0000001100000000
color 0000001000000000
color 0000000000000000
end
case u16_base_positive
fetch 6 7 8
palette 0 0 0 0 255
palette 1 0 0 255 255
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 1111111110000000
color 1111111100000000
color 1111111000000000
color 1111110000000000
color 1111000000000000
color 1110000000000000
color 1100000000000000
color 1000000000000000
end
case u16_base_negative
fetch 6 7 8
palette 0 0 0 0 255
palette 1 0 0 255 255
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 1111111110000000
color 1111111100000000
color 1111111000000000
color 1111110000000000
color 1111000000000000
color 1110000000000000
color 1100000000000000
color 1000000000000000
end
case u32_base_negative
fetch 6 7 8
palette 0 0 0 0 255
palette 1 0 0 255 255
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 1111111110000000
color 1111111100000000
color 1111111000000000
color 1111110000000000
color 1111000000000000
color 1110000000000000
color 1100000000000000
color 1000000000000000
end
case reversed_winding
fetch 2 1 0
palette 0 255 0 0 255
palette 1 0 0 0 255
color 0000000000000001
color 0000000000000011
color 0000000000000111
color 0000000000011111
color 0000000000111111
color 0000000001111111
color 0000000111111111
color 0000001111111111
color 0000011111111111
color 0001111111111111
color 0011111111111111
color 0111111111111111
color 1111111111111111
color 1111111111111111
color 1111111111111111
color 1111111111111111
end
case two_triangles_textured
fetch 9 10 11 9 11 12
palette 0 255 0 0 255
palette 1 0 0 255 255
palette 2 0 0 0 0
palette 3 0 255 0 255
palette 4 255 255 255 255
palette 5 255 255 0 255
palette 6 132 130 132 255
palette 7 8 8 8 255
palette 8 0 0 0 255
color 0011001122223333
color 0011001122223333
color 1100110033332222
color 1100110033332222
color 0000111133223344
color 0000111133223344
color 1111000044332233
color 1111000044332233
color 5555555566777766
color 5555555566777766
color 8888888877666677
color 8888888877666677
color 5555555566777766
color 5555555566777766
color 8888888877666677
color 8888888888888888
end
case textured_base_vertex
fetch 9 10 11
palette 0 0 0 0 255
palette 1 255 0 0 255
palette 2 0 0 255 255
palette 3 0 0 0 0
palette 4 0 255 0 255
palette 5 255 255 255 255
palette 6 132 130 132 255
palette 7 8 8 8 255
color 0122112233334444
color 0022112233334444
color 0001221144443333
color 0000221144443333
color 0000022244334455
color 0000002244334455
color 0000000155443344
color 0000000055443344
color 0000000006777766
color 0000000000777766
color 0000000000066677
color 0000000000006677
color 0000000000000766
color 0000000000000066
color 0000000000000007
color 0000000000000000
end
case painter_order
fetch 0 1 2
fetch 3 4 5
fetch 6 7 8
palette 0 255 0 0 255
palette 1 0 0 0 255
palette 2 0 255 0 255
palette 3 0 0 255 255
color 0000000000000001
color 0000000000000011
color 0000000000000111
color 0000222222011111
color 0000222222222222
color 0000222222222221
color 0000022222222211
color 0000022222222111
color 3333333332221111
color 3333333322211111
color 3333333222211111
color 3333332222111111
color 3333122221111111
color 3331112211111111
color 3311112111111111
color 3111111111111111
end
case u32_mixed
fetch 9 10 11 9 11 12
fetch 9 10 11
fetch 0 1 2
palette 0 255 0 0 255
palette 1 0 255 0 255
palette 2 255 255 0 255
palette 3 132 130 132 255
palette 4 0 0 0 255
palette 5 8 8 8 255
color 0000000000000001
color 0000000000000011
color 0000000000000111
color 0000000000011111
color 0000000000111111
color 0000000001111111
color 0000000111111111
color 0000000011111111
color 0000022231111111
color 0002222233111111
color 0044444455311111
color 0444444455331111
color 2222222233555111
color 2222222233555511
color 4444444455333351
color 4444444444444444
end
case flat_two_triangles
fetch 9 10 11 9 11 12
palette 0 0 255 0 255
palette 1 0 0 0 255
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000000000000
color 0000000011111111
end
case textured_first
fetch 0 1 2
palette 0 255 0 0 255
palette 1 0 0 255 255
palette 2 0 0 0 0
palette 3 0 255 0 255
palette 4 0 0 0 255
palette 5 255 255 0 255
color 0011001122223334
color 0011001122223344
color 1100110033332444
color 1100110033344444
color 0000111133444444
color 0000111134444444
color 1111000444444444
color 1111004444444444
color 5555544444444444
color 5554444444444444
color 4444444444444444
color 4444444444444444
color 4444444444444444
color 4444444444444444
color 4444444444444444
color 4444444444444444
end
case u32_high_indices
fetch 9 10 11
palette 0 0 0 0 255
palette 1 255 0 0 255
color 0111111111111111
color 0011111111111111
color 0001111111111111
color 0000111111111111
color 0000011111111111
color 0000001111111111
color 0000000111111111
color 0000000011111111
color 0000000001111111
color 0000000000111111
color 0000000000011111
color 0000000000001111
color 0000000000000111
color 0000000000000011
color 0000000000000001
color 0000000000000000
end
+73
View File
@@ -0,0 +1,73 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! CPU check: the reference index fetch and rasteriser agree with the
//! independently derived expectations for every indexed case. Runs without a GPU.
#[path = "support/indexed_cases.rs"]
mod indexed_cases;
use indexed_cases::{BC1_BLOCKS, Fill, INDICES, SIZE, cases, expected, vertices, wide_indices};
use xenora_ref::depth::{RefFill, RefTexture};
use xenora_ref::indexed::{RefIndexedDraw, RefIndices, fetch, render_indexed};
fn bc1_texels() -> Vec<[u8; 4]> {
let mut texels = vec![[0; 4]; 64];
for (block, bytes) in BC1_BLOCKS.as_chunks::<8>().0.iter().enumerate() {
for (index, texel) in xenora_texture::decode_bc1(*bytes).iter().enumerate() {
texels[((block / 2) * 4 + index / 4) * 8 + (block % 2) * 4 + index % 4] = *texel;
}
}
texels
}
#[test]
fn reference_matches_independent_expectations() {
let texels = bc1_texels();
let texture = RefTexture {
width: 8,
height: 8,
texels: &texels,
};
let wide = wide_indices();
let vertices = vertices();
let (cases, expected) = (cases(), expected());
assert_eq!(cases.len(), 16);
assert_eq!(expected.len(), cases.len());
for (case, want) in cases.iter().zip(&expected) {
assert_eq!(case.name, want.name);
let indices = if case.wide {
RefIndices::U32(&wide)
} else {
RefIndices::U16(&INDICES)
};
let draws: Vec<_> = case
.draws
.iter()
.map(|draw| RefIndexedDraw {
start: draw.start,
count: draw.count,
base_vertex: draw.base_vertex,
fill: match draw.fill {
Fill::Flat(rgba) => RefFill::Flat(rgba),
Fill::Texture => RefFill::Texture,
},
})
.collect();
let fetched: Vec<_> = draws
.iter()
.enumerate()
.map(|(number, draw)| fetch(number, draw, indices, vertices.len()).expect("fetch"))
.collect();
assert_eq!(fetched, want.fetch, "{} fetch", case.name);
let color = render_indexed(
[SIZE, SIZE],
case.clear_color,
&vertices,
indices,
&draws,
Some(texture),
)
.expect("reference render");
assert_eq!(color, want.color, "{} colour", case.name);
}
}
+150
View File
@@ -0,0 +1,150 @@
use xenora_metal::{BlendDraw, BlendFactor, BlendOperation, BlendPass, BlendState, ColorWriteMask};
use xenora_ref::blend::{RefBlend, RefBlendFactor, RefBlendOperation};
use super::blend_cases::{CLEAR, Case, SIZE, cases, expected};
use super::{context, native};
/// Tolerance, fixed before any native measurement: a channel whose exact
/// result is a whole unorm8 value must match exactly; a channel that needs
/// rounding may differ by at most this much, because Metal does not document
/// how it rounds blended unorm values.
const ROUNDING_TOLERANCE: u8 = 1;
fn factor(factor: RefBlendFactor) -> BlendFactor {
match factor {
RefBlendFactor::Zero => BlendFactor::Zero,
RefBlendFactor::One => BlendFactor::One,
RefBlendFactor::SourceColor => BlendFactor::SourceColor,
RefBlendFactor::OneMinusSourceColor => BlendFactor::OneMinusSourceColor,
RefBlendFactor::SourceAlpha => BlendFactor::SourceAlpha,
RefBlendFactor::OneMinusSourceAlpha => BlendFactor::OneMinusSourceAlpha,
RefBlendFactor::DestinationColor => BlendFactor::DestinationColor,
RefBlendFactor::OneMinusDestinationColor => BlendFactor::OneMinusDestinationColor,
RefBlendFactor::DestinationAlpha => BlendFactor::DestinationAlpha,
RefBlendFactor::OneMinusDestinationAlpha => BlendFactor::OneMinusDestinationAlpha,
}
}
fn operation(operation: RefBlendOperation) -> BlendOperation {
match operation {
RefBlendOperation::Add => BlendOperation::Add,
RefBlendOperation::Subtract => BlendOperation::Subtract,
RefBlendOperation::ReverseSubtract => BlendOperation::ReverseSubtract,
RefBlendOperation::Min => BlendOperation::Min,
RefBlendOperation::Max => BlendOperation::Max,
}
}
fn state(blend: RefBlend) -> BlendState {
BlendState {
source_rgb: factor(blend.source_rgb),
destination_rgb: factor(blend.destination_rgb),
rgb_operation: operation(blend.rgb_operation),
source_alpha: factor(blend.source_alpha),
destination_alpha: factor(blend.destination_alpha),
alpha_operation: operation(blend.alpha_operation),
}
}
fn metal_draws(case: &Case) -> Vec<BlendDraw> {
case.draws
.iter()
.map(|draw| BlendDraw {
positions: draw.positions,
color: draw.color,
blend: draw.blend.map(state),
write_mask: ColorWriteMask {
red: draw.mask[0],
green: draw.mask[1],
blue: draw.mask[2],
alpha: draw.mask[3],
},
})
.collect()
}
/// Each case's native colour must equal the independently derived image,
/// per channel: exactly where the exact result is a whole unorm8 value, and
/// within [`ROUNDING_TOLERANCE`] where it needs rounding.
#[test]
fn blend_known_answers() {
let gpu = context();
let (cases, expected) = (cases(), expected());
assert_eq!(cases.len(), expected.len());
let (mut rounded, mut off_by_one, mut largest) = (0usize, 0usize, 0u8);
for (case, want) in cases.iter().zip(&expected) {
assert_eq!(case.name, want.name);
let draws = metal_draws(case);
let color = native(gpu.render_blend(&BlendPass {
extent: [SIZE, SIZE],
clear_color: CLEAR,
draws: &draws,
}));
assert_eq!(color.len(), SIZE * SIZE * 4);
for (index, ((pixel, wanted), exact)) in color
.as_chunks::<4>()
.0
.iter()
.zip(&want.color)
.zip(&want.exact)
.enumerate()
{
let (x, y) = (index % SIZE, index / SIZE);
for channel in 0..4 {
let difference = pixel[channel].abs_diff(wanted[channel]);
let allowed = if exact[channel] {
0
} else {
ROUNDING_TOLERANCE
};
assert!(
difference <= allowed,
"{} at ({x}, {y}) channel {channel}: {pixel:?} vs {wanted:?} (allowed {allowed})",
case.name
);
if !exact[channel] {
rounded += 1;
off_by_one += usize::from(difference == 1);
largest = largest.max(difference);
}
}
}
}
println!(
"checked {} blend passes; {rounded} rounded channels, {off_by_one} off by one, largest difference {largest}",
cases.len()
);
}
#[test]
fn too_many_blend_draws_are_rejected() {
let gpu = context();
let draw = BlendDraw {
positions: [
[-1.0, -1.0, 0.5, 1.0],
[3.0, -1.0, 0.5, 1.0],
[-1.0, 3.0, 0.5, 1.0],
],
color: [255; 4],
blend: None,
write_mask: ColorWriteMask::ALL,
};
let error = gpu
.render_blend(&BlendPass {
extent: [SIZE, SIZE],
clear_color: CLEAR,
draws: &[draw; 17],
})
.expect_err("17 draws must be rejected");
assert!(error.to_string().contains("at most 16 draws"), "{error}");
let mut bad = draw;
bad.positions[1][0] = f32::NAN;
let error = gpu
.render_blend(&BlendPass {
extent: [SIZE, SIZE],
clear_color: CLEAR,
draws: &[bad],
})
.expect_err("non-finite positions must be rejected");
assert!(error.to_string().contains("finite"), "{error}");
}
Loaded 100 of 244 files, more files were not shown because too many files have changed in this diff. Show more