Compare commits

..
Author SHA1 Message Date
atharvranjan cf4010ba94 Synchronize PR #271 with verified migration fixes
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:58:14 -06:00
atharvranjan e755ee94ed Merge pull request #264 from MacosPorters/archive/pull/340/head
benchmarks: measure gfx1030 metadata identification
2026-11-24 21:57:34 -06:00
atharvranjan 238b5a001b Keep benchmark fixture tests lint-clean without a benchmark harness
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:51:38 -06:00
atharvranjan e289318132 Merge pull request #267 from MacosPorters/archive/pull/359/head
loader: draw nothing for zero-instance flat draws and reject unsupported ones (#148)
2026-11-24 21:49:39 -06:00
atharvranjan 522560d0a2 Integrate PR #271 while preserving BetterXen terminology
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:48:34 -06:00
atharvranjan f685b54e32 Merge pull request #268 from MacosPorters/archive/pull/369/head
loader: add Win64 service ABI preservation tests (#201)
2026-11-24 21:48:28 -06:00
atharvranjan 0690a3ecb4 Merge pull request #284 from MacosPorters/archive/pull/422/head
loader: copy mid-size TLS templates into the zeroed block (#111)
2026-11-24 21:48:22 -06:00
atharvranjan 7286989296 Merge pull request #270 from MacosPorters/archive/pull/374/head
Fix ARM64 variable shift register encoding
2026-11-24 21:47:03 -06:00
atharvranjan d28d539a90 Integrate PR #274 instruction-length fault handling
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:46:54 -06:00
atharvranjan 8c4b2344df Integrate PR #272 benchmark comparison mode
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:46:50 -06:00
atharvranjan a75d018435 Integrate PR #264 and run identification fixture in workspace tests
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:46:15 -06:00
atharvranjan 4652eb08cb Integrate PR #267 with current native runtime
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:45:36 -06:00
atharvranjan d1bcd0249d Integrate PR #268 and clarify Win64 shadow-space expectations
Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 21:44:49 -06:00
zachdoxsee e5d83e87ac Move the changelog entry down the list
Every merge to main adds its entry at the head of the Added list, and so did
this branch, so each of those merges put this branch in conflict over one
line. The entry is unchanged; it now sits lower down, in a place of its own.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:14:00 +01:00
zachdoxsee 501117c4d8 Merge upstream main into task/378-fninit
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:10:46 +01:00
zachdoxsee 26148f49f6 Merge upstream main into task/378-fninit
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 01:56:51 +01:00
Bartosz Szczepański 0d6cef6c4e loader: raise #GP for instructions longer than 15 bytes (#384)
The shared decoder already stopped before fetching a 16th byte, but it
reported the instruction as unsupported, so both engines exited with an
illegal instruction. It now returns DecodeError::TooLong, which maps to
ExitReason::GeneralProtection (Intel SDM Vol. 3A, 7.15). The DBT retries a
block that fails this way one instruction at a time, as it already does for
illegal instructions and fetch faults, so earlier instructions in the block
complete and the fault reports the overlong instruction's RIP.

The known answer recorded as a defect by #155 is enabled, with three more
cases, and two page-end tests check that no 16th byte is fetched.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-24 23:16:49 +01:00
Bartosz Szczepański 53e5e38a4e bench: compare two dbt_bench JSON results (#114)
With XENORA_DBT_BENCH_COMPARE=<baseline.json>,<candidate.json> set,
dbt_bench reads two documents written through XENORA_DBT_BENCH_JSON and
compares them instead of running. For the interpreter and cold and warm
DBT it prints both medians, the change, and whether the change exceeds
the larger recorded IQR, and it lists changed cold DBT counters.

It refuses, with exit status 1 and the differing field named, to compare
runs whose CPU, OS or architecture differ or are unknown, or whose
workload, sample or warmup counts, debug assertions or build label
differ. The new optional XENORA_DBT_BENCH_BUILD_LABEL records build
settings the benchmark cannot observe, such as LTO; version 1 documents
without it count as unlabelled.

The documents are read by a small RFC 8259 reader in the bench file, so
no dependency is added. Unit tests cover the reader, reading back an
exported document, the report lines, and every refusal rule.

Signed-off-by: Bartosz Szczepański <bartosz.szczepanski@hotmail.com>
2026-11-24 23:08:04 +01:00
zachdoxsee 47a819e05b loader: add FNINIT and the x87 control, status and tag words (#378)
The decoder refused FNINIT (DB E3), which the mingw-w64 C runtime runs
once before main. Guest state gains the x87 control, status and tag
words, and FNINIT sets them to the Intel SDM values 037F, 0 and FFFF.
Both engines run the shared semantics.

The registry gains a form key, rm, that pins a register-only form to one
ModRM byte: the other bytes of DB /4 are different instructions. No other
x87 instruction is added and CPUID still reports no FPU.

Part of Gate A2.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 23:01:33 +01:00
Arthur Lacoste af1b84ad75 loader: fix needless_range_loop in Win64 ABI tests (#201)
Address review feedback from zachdoxsee on PR #369: replace index-only XMM range loops with iterator-based loops so strict clippy passes on Rust 1.100.

Signed-off-by: Arthur Lacoste <arthurlacoste@users.noreply.github.com>
2026-11-24 22:14:29 +01:00
Arthur Lacoste cf438e25aa Merge remote-tracking branch 'origin/main' into runtime/win64-service-abi-201
# Conflicts:
#	CHANGELOG.md
2026-11-24 22:13:14 +01:00
Arthur Lacoste 7246ab5ea6 loader: add Win64 service ABI preservation tests (#201)
Add dispatch and DBT-backed runtime service tests that verify Win64 callee entry alignment, caller-owned shadow space, return state, and preservation of nonvolatile GPRs/XMM registers across registered service calls.

AI-Assisted: Codex (GPT-5) helped draft the tests; I reviewed the diff and ran fmt/clippy(loader)/loader tests locally.
Signed-off-by: Arthur Lacoste <arthurlacoste@users.noreply.github.com>
2026-11-24 20:57:41 +01:00
Swastickc 729e1b4cb1 loader: draw nothing for zero-instance flat draws and reject unsupported ones (#148)
Flat DrawInstanced ignored InstanceCount, StartInstanceLocation and
StartVertexLocation, so a zero-instance draw still drew and a changed
start vertex drew the first triangle. Zero instances or fewer than three
vertices now draw nothing; other unsupported parameters fail with
GraphicsError::Unsupported. Vertex reads use the range-checked
read_resource, so a view past its buffer or an overflowing guest address
fails with IndexOutOfRange.

Add tests/repeated_frames.rs: repeated reset, record, close and execute
frames with hand-derived pixels on the software reference backend.

Signed-off-by: Swastickc <28708247+Swastickc@users.noreply.github.com>
2026-11-25 00:34:19 +05:30
ates 1dcf722323 benchmarks: measure gfx1030 metadata identification
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-24 20:36:15 +03:00
24 changed files with 2445 additions and 614 deletions

No files matched your search

+8
View File
@@ -34,16 +34,22 @@ remains unsupported.
### Fixed
- Non-canonical 64-bit guest data addresses now raise `#GP` instead of a memory fault in both the interpreter and native DBT, including accesses that cross the canonical-address boundary. The synthetic architectural test is enabled again.
- An instruction longer than 15 bytes now stops both engines with a general-protection fault instead of an illegal-instruction exit (#384; Intel SDM Vol. 3A, 7.15). The decoder still stops before fetching a 16th byte, and the DBT translates the faulting instruction on its own so the instructions before it in a block complete first. The `defect_overlong_instruction` known answer from #155 is now verified, with three more cases.
- Made the native semantic-review timeout in `scripts/test-gpu.sh` configurable with `XENORA_SEMANTIC_TIMEOUT` and raised its default from 120 to 300 seconds, so cold Apple Silicon runs do not fail while the expanded Metal known-answer suite is still progressing.
- Added a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status.
### Added
- The gfx1030 identification benchmark fixture now runs as an ordinary integration test, so workspace tests check LLVM-derived names, families, lengths and byte boundaries without invoking a timing run.
- Added a CPU benchmark for gfx1030 metadata identification (#173). It verifies instruction boundaries on a mixed-family stream assembled with LLVM and reports first-pass and repeated-pass throughput.
- Added a Win64 ABI regression showing that a service may write the caller-allocated shadow space. Existing negative controls cover nonvolatile XMM-register corruption; the unchanged-home-slot test now describes its handler rather than implying an ABI preservation requirement.
- Added a BetterXen development phase plan based on current source, pending PRs and existing acceptance records, linked from both contributor entry points. It separates baseline reconciliation, hosted C execution, guest threading, translated rendering, application integration and measured optimization; no new runtime or compatibility acceptance is claimed.
- Added `tests/runtime_clock.rs`, which reads the performance counter, its frequency, both tick counts, the unbiased interrupt time and the system time from one injected clock and checks that they report the same elapsed time in their own units, after a host advance and after a guest `Sleep`, and that none of them decreases up to and past the end of the clock (#204). Expected values are worked out by hand from the documented units. Timed waits still return without consuming clock time.
- Added opt-in shader IR constant folding (`CompileOptions::fold_constants` / `compile_with`) for pure vector unary and binary ops whose operands are already constants (#141). Floating-point ops still use the exact positive-normal rules; loads, stores, lane masks, merges and branches are never folded. Default `compile` keeps the historical IR. Covered by hand-computed known-answer compiler tests (shifts by 32/33, ashr, min_i32 vs min_u32, mul_hi_i32_i24, ffbh_i32, exact float fold, load-derived float non-fold, and verify rejection of inexact constant float add) with a fold-on versus fold-off check, plus an MSL template drift check over every foldable op.
- Added opt-in shader IR common-subexpression elimination (`CompileOptions::eliminate_common_subexpressions` / `compile_with`) that reuses the first result of an equivalent pure vector unary or binary (#142). Equivalence is the same operation and the same operand values in the same order; constant operands match by bit pattern. Loads, stores, constant definitions, lane masks, merges, branches and other side-effecting or execution-mask-dependent ops are left in place. The pass runs after constant folding, so folded results stay constants and a later pure op on two equal folded constants can still be reused. Default `compile` keeps the historical IR. Covered by hand-derived known-answer compiler tests for reuse (and/xor, not, exact float add), for rejected loads, swapped subtracts, lane masks, lane merges and VCC selects, and for the four combinations with constant folding (1 + 2 = 3, and 1.0 + 2.0 = 3.0), and a check that the 13 golden fixtures, none of which repeats an expression, compile unchanged with the pass on. No speedup is claimed.
- The loader now maps an image's PE headers at its image base (#333): the first `SizeOfHeaders` bytes of the file, read-only, in whole 4 KiB pages that are zero past `SizeOfHeaders`. Programs read their own headers this way; the mingw-w64 C runtime does so before `main`, and until now that read faulted. When startup relocates an image it writes the load base into the mapped `ImageBase` field after the relocations, so an entry aimed at that field cannot move it twice; this is Xenora's policy and has not been compared with Windows. A load is refused with the new `PeError::InvalidHeaderSize` when `SizeOfHeaders` is zero, ends before the section table, runs past the file, or its pages would reach into a section, and when the bytes handed to the loader are not the PE32+ headers that were parsed. The page rule refuses images with sub-page section alignment whose first section starts inside the header page, which loaded before. The header pages count toward the 256 MiB mapping budget, which is checked before anything is mapped. `ParsedPe::parse` and the static probe are unchanged. `tests/pe_headers.rs` covers guest reads at the preferred and a relocated base, a relocation aimed at `ImageBase`, the write and execute faults and each refusal with original hand-built images; the image in `pe_mapping_limits.rs` now carries a valid `SizeOfHeaders`. Awaiting independent re-review.
- Added 35 known-answer cases for MOV with an immediate operand, opcodes C6 /0 and C7 /0 (#194), to `cpu_known_answers.rs`: byte, word, dword and qword stores through base, SIB, R12, R13, RSP and RBP addressing with 8-bit and 32-bit displacements; the imm32 sign extension of the 64-bit form; the register forms, including AH and a REX-selected SIL; unmapped and read-only store faults at each width; and #UD for reg field 1. Expected values come from the Intel SDM and were worked out by hand. The interpreter and the DBT already agreed with all of them, so this is new coverage and fixes no defect. The 16-bit forms covered are those that already run, and #118 stays open. Not compared with x86 hardware; awaiting independent review.
- Added Win64 service-call ABI tests in `crates/loader/tests/runtime_services.rs` for #201. A dispatch-level test and a DBT guest-call test verify 16-byte-aligned call entry (`RSP % 16 == 8`), caller-owned 32-byte shadow space accessibility/integrity, return-value/stack/RIP return state, and preservation of RBX/RBP/RDI/RSI/R12-R15 and XMM6-XMM15 across registered service calls. Expected values are derived from the Microsoft x64 calling convention, not from current implementation behavior.
- `dbt_bench` can compare two of its JSON documents when `XENORA_DBT_BENCH_COMPARE=<baseline.json>,<candidate.json>` is set (#114). It prints each median with its change and whether the change exceeds the larger recorded IQR, and lists changed DBT counters. It refuses, with exit status 1 and the differing field named, to compare runs from different CPUs, operating systems or architectures, with unknown host fields, or with different workloads, sample counts, debug assertions or build labels. A new optional `XENORA_DBT_BENCH_BUILD_LABEL` records build settings the benchmark cannot see, such as LTO. No benchmark runs in this mode.
- `dbt_bench` can also write its results as one JSON document when `XENORA_DBT_BENCH_JSON=<path>` is set (#112). The document records the host CPU, OS and architecture, the git revision and whether the tree had local changes, debug assertions, the workload and sample counts, the median, minimum, maximum, p95, p99, IQR and MIPS for the interpreter and for cold and warm DBT, and the cold DBT counters. Anything the benchmark cannot determine is `null`. The text output and the timed work are unchanged.
- Added synthetic guest handle-lifetime regression tests (#205) for capacity reuse, stale handles, duplicate rights and lifetime, wrong object types, thread pseudo handles and failed-output nonmutation. Runtime behavior is unchanged; independent acceptance is pending.
- Added a documented independent acceptance rule for promoting AMD RDNA2 desktop GPU (gfx1030) forms from local CPU and Metal results to `fixture verified`, including clean-commit evidence, reviewer independence, raw-log location, review-log summary, failure handling and status regeneration (#302).
@@ -86,6 +92,7 @@ remains unsupported.
- 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 FNINIT (`DB E3`), the one instruction a C program built with the mingw-w64 runtime needs that the decoder refused (#378, part of Gate A2). Guest state gains the x87 control, status and tag words in `CpuState::x87`, and FNINIT sets them to the Intel SDM values `037F`, `0` and `FFFF`. Both engines run the shared semantics; nothing is lowered to ARM64 and the host's floating-point state is never touched. The registry gains a form key, `rm`, that pins a register-only form to one ModRM byte, because the other bytes of `DB /4` are different instructions. No other x87 instruction exists: FNSTCW, FLDCW, FNCLEX, FWAIT and all x87 arithmetic stay rejected, there are no x87 data registers, nothing can read the three words back, and CPUID still reports no FPU. Nine SDM-derived cases in `cpu_known_answers.rs`, whose harness now starts every case with the three words away from their reset values and requires every other instruction to keep them, one assembled fixture checked by the text-only reference in `x86_integer.rs`, and a sweep of every ModRM byte under opcodes `D8` to `DF` in both engines cover it. Not compared with x86 hardware; awaiting independent review.
- 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.
@@ -242,6 +249,7 @@ remains unsupported.
- Fixed the address reported when a guest memory access faults part-way across a 4 KiB page boundary (#175). An access that starts in a mapped page and runs into an unmapped or forbidden one now reports the first byte it may not touch; it used to report the start of the access. An access whose first byte fails reports the same address as before, and a failed access still reads and writes nothing. Three Intel SDM page-fault cases in `cpu_known_answers.rs` moved from open defect to verified on both engines. `crates/loader/tests/memory_page_boundaries.rs` checks permissions, adjacent pages, address overflow and the fault address at every 4 KiB guest boundary across two host pages (16 KiB each on Apple Silicon). Guest memory is checked in software, so the host page size does not affect these results. Four #82 expectations and one CRT `memmove` expectation that pinned the start address were corrected. Not compared with x86 hardware; awaiting independent review.
- Fixed the native dependency audit reading Cargo JSON and inspection-tool output in the process locale encoding; it now reads and reports UTF-8 paths and diagnostics under an ASCII locale (#363).
- Fixed a latent ARM64 `LSLV` encoding bug that forced bit 1 of the shift-count register field (part of #131). The dynamic binary translator uses `X10` in its only call, which already has that bit set. `RBIT`, `CLZ` and `LSLV` now panic on out-of-range register numbers before emitting an instruction. Encoding tests use words checked against LLVM's assembler.
- Fixed flat (untextured) guest `DrawInstanced` draws in the synthetic D3D12-style graphics context (#148). A draw with zero instances or fewer than three vertices now draws nothing. A non-zero start vertex or start instance, more than one instance or more than three vertices now fails with `GraphicsError::Unsupported` instead of drawing the view's first triangle. Vertex reads stay inside the vertex buffer, so a view past its end, or one whose guest address would overflow, fails with `IndexOutOfRange` instead of reading neighbouring guest memory or panicking. `crates/loader/tests/repeated_frames.rs` runs these through repeated reset, record, close and execute frames on the software reference backend, with hand-derived pixels; no native Metal result is claimed.
- 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 TLS callback metadata that was accepted or misread without an error (#78). A non-zero `AddressOfCallbacks` outside the image's sections, or 4 GiB or more above the image base, is now refused; it used to mean "no callbacks" or read the list from an unrelated place. The callback list must reach its null entry inside its section, where the section's zero-filled tail counts, and a list of more than 64 callbacks is refused where it used to be cut short. `execute_tls_callbacks` refuses a stack top that is not 16-byte aligned or cannot hold the entry frame, which used to overflow a subtraction, and a file cut inside the TLS data-directory entry no longer panics the parser. `TlsError` gains four variants for these cases. Twelve unit tests in `crates/loader/src/tls.rs` use original headers and code, and also check the argument registers, the stack pointer at entry and after return, callback order and the instruction budget. Expectations come from Microsoft's public PE Format and x64 calling convention pages; nothing ran on Windows, and independent review is pending.
- Fixed the thread's TLS pointer naming the TLS data itself (#76). Compiled code loads the pointer from the thread environment block, indexes it by the module's TLS index to get the address of the data block, and then adds a variable's offset; the loader had mapped the data where the pointer array belongs, so the first eight bytes of the template were used as the block address. `setup_tls` now maps a pointer array at the thread's TLS base and the data block one page above it, and stores the block address in the slot of the index it assigns. `crates/loader/tests/tls_layout.rs` follows that access sequence through guest memory for a template with zero fill, a rebased image and a zero-fill-only directory. The data block of the fixture harness can now be at most 60 KiB, down from 64 KiB, before it would meet the thread environment block. Alignment requests above 4 KiB and more than one module's TLS are not handled. The access sequence follows Microsoft's public PE Format page; nothing ran on Windows, and independent review is pending.
Generated
+1
View File
@@ -166,6 +166,7 @@ dependencies = [
name = "xenora-benchmarks"
version = "0.1.0"
dependencies = [
"xenora-isa",
"xenora-metal",
"xenora-ref",
"xenora-shader",
+7
View File
@@ -17,3 +17,10 @@ path = "src/main.rs"
xenora-shader = { path = "../crates/shader" }
xenora-ref = { path = "../crates/ref" }
xenora-metal = { path = "../crates/metal" }
[dev-dependencies]
xenora-isa = { path = "../crates/isa" }
[[bench]]
name = "gfx1030_identify"
harness = false
@@ -0,0 +1,16 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Original gfx1030 Wave32 instruction stream for metadata identification.
s_mov_b32 s12, 0x89abcdef
v_add_f32_e32 v4, v5, v9
s_cmp_lt_u32 s12, s13
ds_read_b32 v8, v2 offset:12
v_mov_b32_dpp v9, v6 quad_perm:[2,3,0,1] row_mask:0xf bank_mask:0xf
s_add_u32 s16, s17, s18
buffer_store_dword v7, off, s[4:7], 0
v_fma_f32 v5, v8, v10, 0x3f800003
s_movk_i32 s19, 0x2345
global_load_dword v3, v[10:11], off
v_cmp_lt_u32_e32 vcc_lo, v3, v7
s_load_dword s20, s[22:23], 0x20
v_pk_add_f16 v3, v4, v6
s_waitcnt vmcnt(0)
+143
View File
@@ -0,0 +1,143 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! CPU-only gfx1030 metadata benchmark.
//!
//! Run `cargo bench --locked -p xenora-benchmarks --bench gfx1030_identify`
//! from the repository root. Repeat the command to collect independent
//! first-pass samples. The first pass is the first identification in a fresh
//! process with the input already in memory. It does not measure process
//! startup or guarantee cold hardware caches. Repeated passes use the same
//! stream after the untimed correctness check.
//!
//! To verify the fixture bytes and instruction lengths independently, run:
//! ```sh
//! llvm-mc -triple=amdgcn-amd-amdhsa -mcpu=gfx1030 -mattr=+wavefrontsize32 \
//! -show-encoding benchmarks/benches/fixtures/gfx1030_mixed.s
//! ```
use std::hint::black_box;
use std::time::{Duration, Instant};
use xenora_isa::meta::{EncodingFamily, Identified, identify};
const COPIES: usize = 4096;
const WARM_PASSES: usize = 9;
// Encodings and lengths come from llvm-mc, one row per instruction in
// fixtures/gfx1030_mixed.s. Each word is stored in little-endian order.
const FIXTURE: &[(&str, EncodingFamily, &[u32])] = {
use EncodingFamily::*;
&[
("S_MOV_B32", Sop1, &[0xbe8c03ff, 0x89abcdef]),
("V_ADD_F32", Vop2, &[0x06081305]),
("S_CMP_LT_U32", Sopc, &[0xbf0a0d0c]),
("DS_READ_B32", Ds, &[0xd8d8000c, 0x08000002]),
("V_MOV_B32", Vop1, &[0x7e1202fa, 0xff004e06]),
("S_ADD_U32", Sop2, &[0x80101211]),
("BUFFER_STORE_DWORD", Mubuf, &[0xe0700000, 0x80010700]),
("V_FMA_F32", Vop3, &[0xd54b0005, 0x03fe1508, 0x3f800003]),
("S_MOVK_I32", Sopk, &[0xb0132345]),
("GLOBAL_LOAD_DWORD", Global, &[0xdc308000, 0x037d000a]),
("V_CMP_LT_U32", Vopc, &[0x7d820f03]),
("S_LOAD_DWORD", Smem, &[0xf400050b, 0xfa000020]),
("V_PK_ADD_F16", Vop3p, &[0xcc0f4003, 0x1a020d04]),
("S_WAITCNT", Sopp, &[0xbf8c3f70]),
]
};
fn walk(stream: &[u8], mut observe: impl FnMut(usize, Identified)) -> usize {
let mut offset = 0;
let mut count = 0;
while offset < stream.len() {
let identified = identify(&stream[offset..])
.unwrap_or_else(|error| panic!("identification failed at byte {offset}: {error}"));
observe(offset, identified);
offset += identified.len;
count += 1;
}
count
}
fn verify(stream: &[u8]) {
let mut expected_offset = 0;
let mut expected = FIXTURE.iter().cycle();
let count = walk(stream, |offset, identified| {
let &(name, family, words) = expected.next().expect("fixture is nonempty");
let len = std::mem::size_of_val(words);
assert_eq!(offset, expected_offset, "byte boundary for {name}");
assert_eq!(identified.len, len, "length of {name} at byte {offset}");
assert_eq!(identified.form.name, name, "mnemonic at byte {offset}");
assert_eq!(identified.form.family, family, "family at byte {offset}");
expected_offset += len;
});
assert_eq!(expected_offset, stream.len());
assert_eq!(count, COPIES * FIXTURE.len());
}
fn measure(stream: &[u8]) -> Duration {
let start = Instant::now();
let count = walk(black_box(stream), |_, identified| {
black_box(identified);
});
let elapsed = start.elapsed();
assert_eq!(count, COPIES * FIXTURE.len());
elapsed
}
fn report(label: &str, elapsed: Duration, byte_count: usize) {
let seconds = elapsed.as_secs_f64();
let count = (COPIES * FIXTURE.len()) as f64;
println!(
"{label}: {:.3} ms, {:.2} ns/instruction, {:.2} MiB/s",
seconds * 1e3,
seconds * 1e9 / count,
byte_count as f64 / (1024.0 * 1024.0) / seconds
);
}
fn main() {
let block: Vec<u8> = FIXTURE
.iter()
.flat_map(|(_, _, words)| words.iter().flat_map(|word| word.to_le_bytes()))
.collect();
let stream = block.repeat(COPIES);
// 'cargo test --all-targets' checks the fixture without timing it.
if !std::env::args().any(|arg| arg == "--bench") {
verify(&stream);
return;
}
// Keep the first pass ahead of any metadata lookups. Validate the entire
// stream before reporting any timings. That validation also warms the path.
let first = measure(&stream);
verify(&stream);
let mut warm = [Duration::ZERO; WARM_PASSES];
for sample in &mut warm {
*sample = measure(&stream);
}
warm.sort_unstable();
println!(
"gfx1030 metadata identification: {} instructions, {} bytes, {} repeated passes",
COPIES * FIXTURE.len(),
stream.len(),
WARM_PASSES
);
report("First pass in a fresh process", first, stream.len());
report("Repeated minimum", warm[0], stream.len());
report("Repeated median", warm[WARM_PASSES / 2], stream.len());
report("Repeated maximum", warm[WARM_PASSES - 1], stream.len());
}
#[cfg(test)]
mod tests {
#[test]
fn mixed_llvm_fixture_preserves_names_families_lengths_and_boundaries() {
let block: Vec<u8> = super::FIXTURE
.iter()
.flat_map(|(_, _, words)| words.iter().flat_map(|word| word.to_le_bytes()))
.collect();
super::verify(&block.repeat(super::COPIES));
}
}
+5
View File
@@ -0,0 +1,5 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// Exercise the benchmark's LLVM-derived fixture during ordinary workspace tests.
#[allow(dead_code)]
#[path = "../benches/gfx1030_identify.rs"]
mod benchmark;
+778 -3
View File
@@ -5,7 +5,14 @@
//! Set `XENORA_DBT_BENCH_JSON=<path>` to also write the results as one JSON
//! document (format version 1). The text output does not change. Values the
//! benchmark cannot determine, such as the git revision outside a checkout,
//! are written as `null`.
//! are written as `null`. The benchmark cannot see build settings such as LTO,
//! so `XENORA_DBT_BENCH_BUILD_LABEL=<text>` records a label of your choosing
//! for them.
//!
//! Set `XENORA_DBT_BENCH_COMPARE=<baseline.json>,<candidate.json>` to compare
//! two such documents instead of running the benchmark. The comparison is
//! refused, with exit status 1, unless both runs used the same host, workload,
//! build settings and sample counts.
//!
//! The benchmark target disables Cargo's test harness. To run the percentile
//! unit tests, build with
@@ -154,6 +161,7 @@ struct RunInfo {
revision: Option<String>,
dirty: Option<bool>,
debug_assertions: bool,
build_label: Option<String>,
guest_code_bytes: usize,
warmup: usize,
}
@@ -187,6 +195,7 @@ fn run_info(guest_code_bytes: usize, warmup: usize) -> RunInfo {
dirty: command_output("git", &["status", "--porcelain", "--untracked-files=no"])
.map(|status| !status.is_empty()),
debug_assertions: cfg!(debug_assertions),
build_label: non_empty(std::env::var("XENORA_DBT_BENCH_BUILD_LABEL").ok()),
guest_code_bytes,
warmup,
}
@@ -274,7 +283,10 @@ fn json_document(
),
(
"build",
json_object(&[("debug_assertions", info.debug_assertions.to_string())]),
json_object(&[
("debug_assertions", info.debug_assertions.to_string()),
("label", json_option(info.build_label.as_ref(), string)),
]),
),
(
"workload",
@@ -319,7 +331,471 @@ fn json_document(
])
}
/// A parsed JSON value. Numbers keep their source text, so integers compare exactly.
#[derive(Clone, Debug, PartialEq)]
enum Json {
Null,
Bool(bool),
Number(String),
String(String),
Array(Vec<Json>),
Object(Vec<(String, Json)>),
}
impl Json {
/// The value at a dotted path such as `host.cpu`, if every step is an object key.
fn get(&self, path: &str) -> Option<&Json> {
path.split('.').try_fold(self, |value, key| match value {
Json::Object(fields) => fields.iter().find(|(k, _)| k == key).map(|(_, v)| v),
_ => None,
})
}
}
const MAX_JSON_DEPTH: usize = 32;
/// Reads one JSON document (RFC 8259) and rejects anything after it.
fn parse_json(text: &str) -> Result<Json, String> {
let mut reader = JsonReader {
bytes: text.as_bytes(),
pos: 0,
};
let value = reader.value(0)?;
reader.skip_whitespace();
if reader.pos != reader.bytes.len() {
return reader.error("unexpected data after the document");
}
Ok(value)
}
struct JsonReader<'a> {
bytes: &'a [u8],
pos: usize,
}
impl JsonReader<'_> {
fn error<T>(&self, what: &str) -> Result<T, String> {
Err(format!("{what} at byte {}", self.pos))
}
fn peek(&self) -> Option<u8> {
self.bytes.get(self.pos).copied()
}
fn skip_whitespace(&mut self) {
while matches!(self.peek(), Some(b' ' | b'\t' | b'\n' | b'\r')) {
self.pos += 1;
}
}
fn expect(&mut self, byte: u8) -> Result<(), String> {
if self.peek() == Some(byte) {
self.pos += 1;
Ok(())
} else {
self.error(&format!("expected '{}'", byte as char))
}
}
fn value(&mut self, depth: usize) -> Result<Json, String> {
if depth > MAX_JSON_DEPTH {
return self.error("nesting too deep");
}
self.skip_whitespace();
match self.peek() {
None => self.error("unexpected end of input"),
Some(b'n') => self.literal("null", Json::Null),
Some(b't') => self.literal("true", Json::Bool(true)),
Some(b'f') => self.literal("false", Json::Bool(false)),
Some(b'"') => Ok(Json::String(self.string()?)),
Some(b'[') => self.array(depth),
Some(b'{') => self.object(depth),
Some(b'-' | b'0'..=b'9') => self.number(),
Some(_) => self.error("unexpected character"),
}
}
fn literal(&mut self, word: &str, value: Json) -> Result<Json, String> {
if self.bytes[self.pos..].starts_with(word.as_bytes()) {
self.pos += word.len();
Ok(value)
} else {
self.error("invalid literal")
}
}
fn array(&mut self, depth: usize) -> Result<Json, String> {
self.expect(b'[')?;
let mut items = Vec::new();
self.skip_whitespace();
if self.peek() == Some(b']') {
self.pos += 1;
return Ok(Json::Array(items));
}
loop {
items.push(self.value(depth + 1)?);
self.skip_whitespace();
match self.peek() {
Some(b',') => self.pos += 1,
Some(b']') => {
self.pos += 1;
return Ok(Json::Array(items));
}
_ => return self.error("expected ',' or ']'"),
}
}
}
fn object(&mut self, depth: usize) -> Result<Json, String> {
self.expect(b'{')?;
let mut fields: Vec<(String, Json)> = Vec::new();
self.skip_whitespace();
if self.peek() == Some(b'}') {
self.pos += 1;
return Ok(Json::Object(fields));
}
loop {
self.skip_whitespace();
let key = self.string()?;
if fields.iter().any(|(k, _)| *k == key) {
return self.error(&format!("duplicate key `{key}`"));
}
self.skip_whitespace();
self.expect(b':')?;
let value = self.value(depth + 1)?;
fields.push((key, value));
self.skip_whitespace();
match self.peek() {
Some(b',') => self.pos += 1,
Some(b'}') => {
self.pos += 1;
return Ok(Json::Object(fields));
}
_ => return self.error("expected ',' or '}'"),
}
}
}
fn digits(&mut self) -> usize {
let start = self.pos;
while matches!(self.peek(), Some(b'0'..=b'9')) {
self.pos += 1;
}
self.pos - start
}
fn number(&mut self) -> Result<Json, String> {
let start = self.pos;
if self.peek() == Some(b'-') {
self.pos += 1;
}
match self.peek() {
Some(b'0') => self.pos += 1,
Some(b'1'..=b'9') => {
self.digits();
}
_ => return self.error("invalid number"),
}
if self.peek() == Some(b'.') {
self.pos += 1;
if self.digits() == 0 {
return self.error("invalid number");
}
}
if matches!(self.peek(), Some(b'e' | b'E')) {
self.pos += 1;
if matches!(self.peek(), Some(b'+' | b'-')) {
self.pos += 1;
}
if self.digits() == 0 {
return self.error("invalid number");
}
}
// Only ASCII digits and signs were consumed.
Ok(Json::Number(
String::from_utf8_lossy(&self.bytes[start..self.pos]).into_owned(),
))
}
fn hex4(&mut self) -> Result<u32, String> {
let digits = self.bytes.get(self.pos..self.pos + 4);
let value = digits
.and_then(|d| std::str::from_utf8(d).ok())
.and_then(|d| u32::from_str_radix(d, 16).ok());
match value {
Some(value) if digits.is_some_and(|d| d.iter().all(u8::is_ascii_hexdigit)) => {
self.pos += 4;
Ok(value)
}
_ => self.error("invalid \\u escape"),
}
}
fn unicode_escape(&mut self) -> Result<char, String> {
let first = self.hex4()?;
let code = match first {
0xD800..=0xDBFF => {
if !self.bytes[self.pos..].starts_with(b"\\u") {
return self.error("unpaired surrogate");
}
self.pos += 2;
let second = self.hex4()?;
if !(0xDC00..=0xDFFF).contains(&second) {
return self.error("unpaired surrogate");
}
0x10000 + ((first - 0xD800) << 10) + (second - 0xDC00)
}
0xDC00..=0xDFFF => return self.error("unpaired surrogate"),
code => code,
};
char::from_u32(code).map_or_else(|| self.error("invalid code point"), Ok)
}
fn string(&mut self) -> Result<String, String> {
self.expect(b'"')?;
let mut out = String::new();
loop {
// Copy the run up to the next quote, backslash or control byte. Those
// are ASCII, so the run never ends inside a multi-byte character.
let start = self.pos;
while matches!(self.peek(), Some(b) if b != b'"' && b != b'\\' && b >= 0x20) {
self.pos += 1;
}
match std::str::from_utf8(&self.bytes[start..self.pos]) {
Ok(run) => out.push_str(run),
Err(_) => return self.error("invalid UTF-8"),
}
match self.peek() {
Some(b'"') => {
self.pos += 1;
return Ok(out);
}
Some(b'\\') => {
self.pos += 1;
let escaped = self.peek();
self.pos += 1;
out.push(match escaped {
Some(b'"') => '"',
Some(b'\\') => '\\',
Some(b'/') => '/',
Some(b'b') => '\u{8}',
Some(b'f') => '\u{c}',
Some(b'n') => '\n',
Some(b'r') => '\r',
Some(b't') => '\t',
Some(b'u') => self.unicode_escape()?,
_ => {
self.pos -= 1;
return self.error("invalid escape");
}
});
}
Some(_) => return self.error("control character in string"),
None => return self.error("unterminated string"),
}
}
}
}
/// Fields that must be equal for two runs to be compared. A field listed in
/// `OPTIONAL_FIELDS` counts as `null` when a document does not have it.
const MATCHING_FIELDS: [&str; 15] = [
"format_version",
"benchmark",
"host.cpu",
"host.os",
"host.arch",
"build.debug_assertions",
"build.label",
"workload.name",
"workload.guest_instructions",
"workload.guest_code_bytes",
"workload.instruction_budget",
"workload.warmup_rounds",
"timings.interpreter.samples",
"timings.cold_dbt.samples",
"timings.warm_dbt.samples",
];
/// Older version 1 documents predate the build label.
const OPTIONAL_FIELDS: [&str; 1] = ["build.label"];
/// Host fields that must be known: two unknown CPUs are not the same CPU.
const KNOWN_FIELDS: [&str; 3] = ["host.cpu", "host.os", "host.arch"];
const SERIES: [(&str, &str); 3] = [
("interpreter", "Interpreter"),
("cold_dbt", "Cold DBT"),
("warm_dbt", "Warm DBT"),
];
const COUNTERS: [&str; 8] = [
"blocks_compiled",
"cache_hits",
"cache_misses",
"native_bytes_emitted",
"dbt_dispatches",
"instructions_executed",
"interpreter_fallbacks",
"service_calls",
];
fn field<'a>(doc: &'a Json, path: &str) -> Result<&'a Json, String> {
match doc.get(path) {
Some(value) => Ok(value),
None if OPTIONAL_FIELDS.contains(&path) => Ok(&Json::Null),
None => Err(format!("missing field `{path}`")),
}
}
fn integer(doc: &Json, path: &str) -> Result<u128, String> {
match field(doc, path)? {
Json::Number(text) => text
.parse()
.map_err(|_| format!("`{path}` is not a non-negative integer")),
_ => Err(format!("`{path}` is not a number")),
}
}
fn text(doc: &Json, path: &str) -> String {
match doc.get(path) {
Some(Json::String(value)) => value.clone(),
Some(Json::Bool(value)) => value.to_string(),
Some(Json::Number(value)) => value.clone(),
// The build label is optional, so its absence is not an unknown value.
_ if OPTIONAL_FIELDS.contains(&path) => "none".to_owned(),
_ => "unknown".to_owned(),
}
}
fn duration(ns: u128) -> Duration {
Duration::from_nanos(u64::try_from(ns).unwrap_or(u64::MAX))
}
fn change(before: u128, after: u128) -> String {
if before == 0 {
return "n/a".to_owned();
}
format!(
"{:+.2}%",
(after as f64 - before as f64) / before as f64 * 100.0
)
}
fn source(doc: &Json) -> String {
let dirty = match doc.get("source.dirty") {
Some(Json::Bool(true)) => " with local changes",
Some(Json::Bool(false)) => "",
_ => ", local changes unknown",
};
format!("{}{dirty}", text(doc, "source.revision"))
}
/// Compares two exported documents. Returns the report lines, or why the runs
/// cannot be compared.
fn compare_documents(baseline: &Json, candidate: &Json) -> Result<Vec<String>, String> {
for doc in [baseline, candidate] {
if field(doc, "format_version")? != &Json::Number("1".to_owned()) {
return Err("only format version 1 is supported".to_owned());
}
}
for path in KNOWN_FIELDS {
for (name, doc) in [("baseline", baseline), ("candidate", candidate)] {
if field(doc, path)? == &Json::Null {
return Err(format!(
"`{path}` is unknown in the {name}, so the hosts cannot be shown to match"
));
}
}
}
for path in MATCHING_FIELDS {
if field(baseline, path)? != field(candidate, path)? {
return Err(format!(
"`{path}` differs: baseline {}, candidate {}",
text(baseline, path),
text(candidate, path)
));
}
}
let mut lines = vec![
format!("Baseline: {}", source(baseline)),
format!("Candidate: {}", source(candidate)),
format!(
"Host: {}, {} {}; debug assertions {}; build label {}",
text(baseline, "host.cpu"),
text(baseline, "host.os"),
text(baseline, "host.arch"),
text(baseline, "build.debug_assertions"),
text(baseline, "build.label"),
),
];
if field(baseline, "host.os_version")? != field(candidate, "host.os_version")? {
lines.push(format!(
"Note: OS version differs: baseline {}, candidate {}",
text(baseline, "host.os_version"),
text(candidate, "host.os_version")
));
}
for (key, label) in SERIES {
let path = |stat: &str| format!("timings.{key}.{stat}");
let before = integer(baseline, &path("median_ns"))?;
let after = integer(candidate, &path("median_ns"))?;
let spread = integer(baseline, &path("iqr_ns"))?.max(integer(candidate, &path("iqr_ns"))?);
let verdict = if before.abs_diff(after) > spread {
"larger than"
} else {
"within"
};
lines.push(format!(
"{label}: median {:?} -> {:?} ({}), {verdict} the larger IQR {:?}",
duration(before),
duration(after),
change(before, after),
duration(spread)
));
}
let mut counters_changed = false;
for counter in COUNTERS {
let path = format!("cold_dbt_metrics.{counter}");
let (before, after) = (integer(baseline, &path)?, integer(candidate, &path)?);
if before != after {
counters_changed = true;
lines.push(format!(
"Cold DBT {counter}: {before} -> {after} ({})",
change(before, after)
));
}
}
if !counters_changed {
lines.push("Cold DBT counters are identical".to_owned());
}
Ok(lines)
}
fn compare_files(spec: &str) -> Result<Vec<String>, String> {
let (baseline, candidate) = spec
.split_once(',')
.ok_or("expected <baseline.json>,<candidate.json>")?;
let read = |path: &str| {
let text = std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?;
parse_json(&text).map_err(|e| format!("{path}: {e}"))
};
compare_documents(&read(baseline)?, &read(candidate)?)
}
fn main() {
if let Ok(spec) = std::env::var("XENORA_DBT_BENCH_COMPARE") {
match compare_files(&spec) {
Ok(lines) => lines.iter().for_each(|line| println!("{line}")),
Err(reason) => {
eprintln!("dbt_bench: cannot compare: {reason}");
std::process::exit(1);
}
}
return;
}
let sample_count = std::env::var("XENORA_DBT_BENCH_SAMPLES")
.map_or(101, |value| value.parse::<usize>().expect("sample count"));
assert!(sample_count > 0);
@@ -494,6 +970,7 @@ mod tests {
revision: Some("0123abcd".to_owned()),
dirty: Some(false),
debug_assertions: false,
build_label: Some("fat-lto".to_owned()),
guest_code_bytes: 40_011,
warmup: 10,
}
@@ -528,7 +1005,7 @@ mod tests {
r#"{{"format_version":1,"benchmark":"dbt_bench","unix_time":1700000000,"#,
r#""host":{{"cpu":"Test \"CPU\"\\1","os":"macos","os_version":null,"arch":"aarch64"}},"#,
r#""source":{{"revision":"0123abcd","dirty":false}},"#,
r#""build":{{"debug_assertions":false}},"#,
r#""build":{{"debug_assertions":false,"label":"fat-lto"}},"#,
r#""workload":{{"name":"add_rax_chain","guest_instructions":{},"guest_code_bytes":40011,"instruction_budget":20000,"warmup_rounds":10}},"#,
r#""timings":{{"interpreter":{},"cold_dbt":{},"warm_dbt":{}}},"#,
r#""cold_dbt_metrics":{{"blocks_compiled":626,"cache_hits":0,"cache_misses":626,"native_bytes_emitted":245168,"dbt_dispatches":626,"instructions_executed":10002,"interpreter_fallbacks":1,"service_calls":0}}}}"#,
@@ -580,4 +1057,302 @@ mod tests {
assert_eq!(s.iqr, Duration::from_micros(30));
assert_eq!(s.mips, INSTRUCTIONS as f64 / 25e-6 / 1e6);
}
// `cargo bench` builds this target with `--cfg test` but without `--test`,
// so this module is compiled with its #[test] functions removed and shared
// helpers look unused there.
#[allow(dead_code)]
fn comparable_document() -> super::Json {
super::parse_json(concat!(
r#"{"format_version":1,"benchmark":"dbt_bench","unix_time":1,"#,
r#""host":{"cpu":"Apple M5","os":"macos","os_version":"27.2.1","arch":"aarch64"},"#,
r#""source":{"revision":"aaaa","dirty":false},"#,
r#""build":{"debug_assertions":false,"label":null},"#,
r#""workload":{"name":"add_rax_chain","guest_instructions":10002,"guest_code_bytes":40011,"instruction_budget":20000,"warmup_rounds":10},"#,
r#""timings":{"#,
r#""interpreter":{"samples":101,"median_ns":900000,"min_ns":1,"max_ns":2,"p95_ns":1,"p99_ns":1,"iqr_ns":20000,"median_mips":11.1},"#,
r#""cold_dbt":{"samples":101,"median_ns":1100000,"min_ns":1,"max_ns":2,"p95_ns":1,"p99_ns":1,"iqr_ns":40000,"median_mips":9.1},"#,
r#""warm_dbt":{"samples":101,"median_ns":22000,"min_ns":1,"max_ns":2,"p95_ns":1,"p99_ns":1,"iqr_ns":500,"median_mips":454.6}},"#,
r#""cold_dbt_metrics":{"blocks_compiled":626,"cache_hits":0,"cache_misses":626,"native_bytes_emitted":245168,"dbt_dispatches":626,"instructions_executed":10002,"interpreter_fallbacks":0,"service_calls":0}}"#,
))
.expect("fixture parses")
}
/// Replaces the value at a dotted path, which must exist except for its last key.
#[allow(dead_code)]
fn set(doc: &mut super::Json, path: &str, value: super::Json) {
let (parent, key) = path.rsplit_once('.').map_or(("", path), |(p, k)| (p, k));
let mut node = doc;
for step in parent.split('.').filter(|s| !s.is_empty()) {
let super::Json::Object(fields) = node else {
panic!("{step} is not in an object")
};
node = &mut fields.iter_mut().find(|(k, _)| k == step).expect(step).1;
}
let super::Json::Object(fields) = node else {
panic!("{path} has no parent object")
};
match fields.iter_mut().find(|(k, _)| k == key) {
Some(entry) => entry.1 = value,
None => fields.push((key.to_owned(), value)),
}
}
#[test]
fn reader_accepts_json_values() {
use super::{Json, parse_json};
let doc = parse_json(
r#" { "a" : [1, -0.5, 2e3, 3E-2, true, false, null, {}, []], "s": "q\"b\\s\/n\n\té😀 Zażółć" } "#,
)
.unwrap();
assert_eq!(
doc.get("a"),
Some(&Json::Array(vec![
Json::Number("1".to_owned()),
Json::Number("-0.5".to_owned()),
Json::Number("2e3".to_owned()),
Json::Number("3E-2".to_owned()),
Json::Bool(true),
Json::Bool(false),
Json::Null,
Json::Object(vec![]),
Json::Array(vec![]),
]))
);
assert_eq!(
doc.get("s"),
Some(&Json::String("q\"b\\s/n\n\té😀 Zażółć".to_owned()))
);
assert_eq!(doc.get("a.b"), None);
assert_eq!(doc.get("missing"), None);
}
#[test]
fn reader_rejects_malformed_json() {
use super::parse_json;
let deep = "[".repeat(40) + &"]".repeat(40);
for bad in [
"",
"{",
r#"{"a":1,}"#,
r#"{"a" 1}"#,
r#"{"a":1,"a":2}"#,
"[1 2]",
"01",
"1.",
"-",
"1e",
"+1",
"tru",
r#""open"#,
"\"tab\tinside\"",
r#""\x""#,
r#""\u12g4""#,
r#""\u+123""#,
r#""\ud83d""#,
r#""\ude00""#,
r#""\ud83dA""#,
"{} {}",
deep.as_str(),
] {
assert!(parse_json(bad).is_err(), "accepted {bad:?}");
}
}
#[test]
fn exported_document_reads_back() {
use super::{DbtMetrics, Duration, Json, RunInfo, Summary, json_document, parse_json};
let summary = Summary {
samples: 7,
median: Duration::from_nanos(1_234_567),
min: Duration::from_nanos(1),
max: Duration::from_nanos(9),
p95: Duration::from_nanos(8),
p99: Duration::from_nanos(9),
iqr: Duration::from_nanos(3),
mips: 8.25,
};
let info = RunInfo {
unix_time: None,
cpu: Some("CPU \"x\" \\ \u{1}".to_owned()),
os: "macos",
os_version: None,
arch: "aarch64",
revision: None,
dirty: Some(true),
debug_assertions: true,
build_label: Some("é label".to_owned()),
guest_code_bytes: 5,
warmup: 2,
};
let metrics = DbtMetrics {
native_bytes_emitted: 42,
..DbtMetrics::default()
};
let doc = parse_json(&json_document(
&info, &summary, &summary, &summary, &metrics,
))
.unwrap();
let string = |s: &str| Some(Json::String(s.to_owned()));
assert_eq!(doc.get("host.cpu").cloned(), string("CPU \"x\" \\ \u{1}"));
assert_eq!(doc.get("build.label").cloned(), string("é label"));
assert_eq!(doc.get("host.os_version"), Some(&Json::Null));
assert_eq!(doc.get("source.dirty"), Some(&Json::Bool(true)));
assert_eq!(
doc.get("timings.cold_dbt.median_ns"),
Some(&Json::Number("1234567".to_owned()))
);
assert_eq!(
doc.get("cold_dbt_metrics.native_bytes_emitted"),
Some(&Json::Number("42".to_owned()))
);
}
#[test]
fn comparison_reports_changes_against_the_spread() {
use super::{Json, compare_documents};
let baseline = comparable_document();
let mut candidate = comparable_document();
set(
&mut candidate,
"source.revision",
Json::String("bbbb".to_owned()),
);
set(&mut candidate, "source.dirty", Json::Bool(true));
// 900 µs -> 846 µs is 54 µs, beyond the larger IQR of 20 µs.
set(
&mut candidate,
"timings.interpreter.median_ns",
Json::Number("846000".to_owned()),
);
// 1.1 ms -> 1.12 ms is 20 µs, within the larger IQR of 45 µs.
set(
&mut candidate,
"timings.cold_dbt.median_ns",
Json::Number("1120000".to_owned()),
);
set(
&mut candidate,
"timings.cold_dbt.iqr_ns",
Json::Number("45000".to_owned()),
);
set(
&mut candidate,
"cold_dbt_metrics.native_bytes_emitted",
Json::Number("290184".to_owned()),
);
set(
&mut candidate,
"host.os_version",
Json::String("27.3".to_owned()),
);
let lines = compare_documents(&baseline, &candidate).unwrap();
assert_eq!(
lines,
[
"Baseline: aaaa",
"Candidate: bbbb with local changes",
"Host: Apple M5, macos aarch64; debug assertions false; build label none",
"Note: OS version differs: baseline 27.2.1, candidate 27.3",
"Interpreter: median 900µs -> 846µs (-6.00%), larger than the larger IQR 20µs",
"Cold DBT: median 1.1ms -> 1.12ms (+1.82%), within the larger IQR 45µs",
"Warm DBT: median 22µs -> 22µs (+0.00%), within the larger IQR 500ns",
"Cold DBT native_bytes_emitted: 245168 -> 290184 (+18.36%)",
]
);
let same = compare_documents(&baseline, &baseline).unwrap();
assert_eq!(same.last().unwrap(), "Cold DBT counters are identical");
}
#[test]
fn comparison_rejects_every_mismatching_field() {
use super::{Json, compare_documents};
// Written out independently of MATCHING_FIELDS, so dropping a field
// there fails this test.
for path in [
"format_version",
"benchmark",
"host.cpu",
"host.os",
"host.arch",
"build.debug_assertions",
"build.label",
"workload.name",
"workload.guest_instructions",
"workload.guest_code_bytes",
"workload.instruction_budget",
"workload.warmup_rounds",
"timings.interpreter.samples",
"timings.cold_dbt.samples",
"timings.warm_dbt.samples",
] {
let mut candidate = comparable_document();
let other = match path {
"build.debug_assertions" => Json::Bool(true),
"build.label" => Json::String("fat-lto".to_owned()),
// A valid but different version is refused as unsupported first.
"format_version" => Json::Number("2".to_owned()),
p if p.contains("samples")
|| p.starts_with("workload.") && p != "workload.name" =>
{
Json::Number("7".to_owned())
}
_ => Json::String("other".to_owned()),
};
set(&mut candidate, path, other);
let error = compare_documents(&comparable_document(), &candidate).expect_err(path);
assert!(
error.contains(path) || path == "format_version" && error.contains("version"),
"{path}: {error}"
);
}
}
#[test]
fn comparison_needs_known_hosts_and_matching_labels() {
use super::{Json, compare_documents};
for path in ["host.cpu", "host.os", "host.arch"] {
let mut unknown = comparable_document();
set(&mut unknown, path, Json::Null);
let error = compare_documents(&unknown, &unknown).expect_err(path);
assert!(error.contains("unknown in the baseline"), "{error}");
}
// A document written before the label existed counts as having no label.
let mut old = comparable_document();
let Json::Object(fields) = &mut old else {
unreachable!()
};
let build = &mut fields.iter_mut().find(|(k, _)| k == "build").unwrap().1;
let Json::Object(build) = build else {
unreachable!()
};
build.retain(|(k, _)| k != "label");
assert!(compare_documents(&old, &comparable_document()).is_ok());
let mut labelled = comparable_document();
set(
&mut labelled,
"build.label",
Json::String("fat-lto".to_owned()),
);
assert!(compare_documents(&old, &labelled).is_err());
assert!(compare_documents(&labelled, &labelled).is_ok());
let mut missing = comparable_document();
let Json::Object(fields) = &mut missing else {
unreachable!()
};
fields.retain(|(k, _)| k != "workload");
let error = compare_documents(&comparable_document(), &missing).unwrap_err();
assert!(error.contains("missing field `workload.name`"), "{error}");
}
}
+12 -4
View File
@@ -7,9 +7,9 @@
differs. Never writes.
Rejects unknown keys and vocabulary, overlapping encodings, digit and plain
forms sharing an opcode, operand constraints that contradict each other, LOCK
on a form that cannot write memory, and flags declared both written and
undefined. Standard library only (Python 3.11+).
forms sharing an opcode, operand constraints that contradict each other, a
fixed r/m field on a form that could take memory, LOCK on a form that cannot
write memory, and flags declared both written and undefined. Standard library only (Python 3.11+).
"""
import sys
@@ -27,7 +27,7 @@ RUST = HERE / "src/x86_table.rs"
TOP_KEYS = {"schema", "architecture", "documents", "operation", "alu", "form", "group"}
OPERATION_KEYS = {"reads", "writes", "undefined", "conditional", "terminator", "faults", "ref"}
FORM_KEYS = {"op", "map", "prefix", "opcode", "count", "digit", "enc", "size", "imm", "src",
"memory_only", "register_only", "no_rex_b", "unaligned", "lock"}
"memory_only", "register_only", "rm", "no_rex_b", "unaligned", "lock"}
GROUP_KEYS = {"map", "opcodes", "digits"}
FLAGS = ["cf", "zf", "sf", "of", "pf", "af"]
MAPS = {"1": "ONE_BYTE", "0f": "TWO_BYTE"}
@@ -169,6 +169,13 @@ def load(text):
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")
form.setdefault("rm", None)
if form["rm"] is not None:
# bool is an int in Python; `rm = true` is not a field value.
if type(form["rm"]) is not int or not 0 <= form["rm"] <= 7:
fail(f"{where}: rm must be a ModRM r/m field value 0-7")
if not form.get("register_only") or form["digit"] is None:
fail(f"{where}: a fixed r/m field needs register_only and a digit")
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")
@@ -273,6 +280,7 @@ def generate(operations, forms):
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"fixed_rm: {'None' if form['rm'] is None else 'Some(%d)' % form['rm']}, "
f"no_rex_b: {str(bool(form.get('no_rex_b'))).lower()}, "
f"unaligned: {str(bool(form.get('unaligned'))).lower()}, "
f"lockable: {str(bool(form.get('lock'))).lower()} }},")
+51 -1
View File
@@ -85,6 +85,36 @@ impl Default for Mxcsr {
}
}
/// x87 FPU control, status and tag words.
///
/// FNINIT is the only instruction that writes them and nothing reads them yet.
/// The x87 data registers and every other x87 instruction are not modelled.
/// The host's floating-point state is never involved.
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct X87State {
pub control: u16,
pub status: u16,
pub tag: u16,
}
impl X87State {
/// What FINIT and FNINIT set (Intel SDM Vol. 2A, "FINIT/FNINIT"; Vol. 1,
/// 8.1.3 to 8.1.7): every exception masked, 64-bit precision, round to
/// nearest; no flag, top of stack 0; every register tagged empty.
pub const INIT: Self = Self {
control: 0x037F,
status: 0,
tag: 0xFFFF,
};
}
impl Default for X87State {
fn default() -> Self {
Self::INIT
}
}
/// x86-64 CPU state. Native DBT accesses the general registers and RIP by offset.
#[repr(C)]
#[derive(Clone, Debug, Default, PartialEq, Eq)]
@@ -99,6 +129,9 @@ pub struct CpuState {
pub mxcsr: Mxcsr,
/// Direction flag: string instructions step RSI and RDI down when set.
pub df: bool,
/// Starts as FNINIT leaves it. The value an operating system gives a new
/// thread is not modelled.
pub x87: X87State,
}
impl CpuState {
@@ -114,6 +147,7 @@ impl CpuState {
xmm: [0; 16],
mxcsr: Mxcsr::default(),
df: false,
x87: X87State::INIT,
}
}
@@ -212,7 +246,21 @@ impl std::error::Error for ExitReason {}
#[cfg(test)]
mod layout_tests {
use super::{CpuState, RFlags, Register};
use super::{CpuState, RFlags, Register, X87State};
/// Intel SDM Vol. 2A, "FINIT/FNINIT", Operation.
#[test]
fn a_new_guest_starts_with_the_x87_words_fninit_sets() {
let init = X87State {
control: 0x037F,
status: 0,
tag: 0xFFFF,
};
assert_eq!(X87State::INIT, init);
assert_eq!(X87State::default(), init);
assert_eq!(CpuState::default().x87, init);
assert_eq!(CpuState::new(0x1000, 0x2000).x87, init);
}
/// The native translator addresses guest registers and RIP by raw byte
/// offset. Keep these assertions next to the struct so a layout change
@@ -483,6 +531,8 @@ impl From<DecodeError<MemoryError>> for ExitReason {
match error {
DecodeError::Fetch(fault) => Self::MemoryFault(fault),
DecodeError::Unsupported(byte) => Self::IllegalInstruction(byte),
// Intel SDM Vol. 3A, 7.15: exceeding the 15-byte limit is #GP(0).
DecodeError::TooLong => Self::GeneralProtection,
}
}
}
+3 -1
View File
@@ -184,7 +184,9 @@ impl DbtEngine {
if block_limit > 1
&& matches!(
block,
Err(ExitReason::IllegalInstruction(_) | ExitReason::MemoryFault(_))
Err(ExitReason::IllegalInstruction(_)
| ExitReason::MemoryFault(_)
| ExitReason::GeneralProtection)
)
{
block = self.get_or_compile_block(cpu.rip, memory, 1);
+24 -15
View File
@@ -120,10 +120,11 @@ pub enum GraphicsError {
/// 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.
/// after applying the base vertex, outside its vertex buffer, or a flat
/// draw reads its vertices outside the vertex buffer.
IndexOutOfRange,
/// A descriptor heap, view, sampler, root signature or binding outside
/// the supported texture-binding subset. Nothing is drawn.
/// A descriptor heap, view, sampler, root signature, binding or draw
/// outside the supported subset. Nothing is drawn.
Unsupported(&'static str),
}
@@ -151,8 +152,8 @@ impl std::fmt::Display for GraphicsError {
Self::InvalidIndexFormat(format) => {
write!(f, "unsupported index buffer format {format}")
}
Self::IndexOutOfRange => write!(f, "indexed draw outside its index or vertex buffer"),
Self::Unsupported(what) => write!(f, "unsupported texture binding: {what}"),
Self::IndexOutOfRange => write!(f, "draw outside its index or vertex buffer"),
Self::Unsupported(what) => write!(f, "unsupported graphics operation: {what}"),
}
}
}
@@ -1673,9 +1674,22 @@ impl GraphicsContext {
rendered_output = Some(pixels);
continue;
}
if *vertex_count_per_instance < 3 {
// Zero instances, or fewer vertices than one triangle,
// draw nothing. The flat path draws only the first
// triangle of the view, once; anything else is rejected
// rather than drawn as a different triangle.
if *vertex_count_per_instance < 3 || *instance_count == 0 {
continue;
}
if *vertex_count_per_instance != 3
|| *instance_count != 1
|| *start_vertex_location != 0
|| *start_instance_location != 0
{
return Err(GraphicsError::Unsupported(
"flat draw other than one instance of the view's first three vertices",
));
}
draw_count += 1;
let v_res_handle =
vertex_resource.ok_or(GraphicsError::InvalidResourceHandle)?;
@@ -1684,15 +1698,10 @@ impl GraphicsContext {
.get(&v_res_handle)
.ok_or(GraphicsError::InvalidResourceHandle)?;
// Read vertices from guest memory backing or resource data
let mut raw_vtx = [0u8; 48]; // 3 * 4 * float32
if let Some(guest_addr) = v_res.guest_backing_addr {
memory.read_bytes(guest_addr + vertex_offset as u64, &mut raw_vtx)?;
} else if v_res.data.len() >= vertex_offset + 48 {
raw_vtx.copy_from_slice(&v_res.data[vertex_offset..vertex_offset + 48]);
} else {
return Err(GraphicsError::InvalidDescriptor);
}
// Three float4 positions, inside the resource whether it
// is backed by guest memory or by its own bytes.
let mut raw_vtx = [0u8; 48];
Self::read_resource(v_res, memory, vertex_offset, &mut raw_vtx)?;
let mut vertices = [[0.0f32; 4]; 3];
for (i, row) in vertices.iter_mut().enumerate() {
+11 -12
View File
@@ -14,8 +14,9 @@ use crate::x86_table::{
/// 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.
/// Length"). Decoding stops before a 16th byte would be fetched and reports
/// [`DecodeError::TooLong`], a general-protection fault (Intel SDM Vol. 3A,
/// 7.15).
pub const MAX_INSTRUCTION_LEN: usize = 15;
/// Number of leading legacy segment prefix bytes (0x64 FS, 0x65 GS) at the
@@ -47,6 +48,9 @@ pub struct Form {
pub has_modrm: bool,
pub memory_only: bool,
pub register_only: bool,
/// The only ModRM r/m field value the form accepts. Set only on
/// register-only forms, so such a form matches exactly one ModRM byte.
pub fixed_rm: Option<u8>,
pub no_rex_b: bool,
/// A 16-byte memory operand may have any alignment.
pub unaligned: bool,
@@ -204,24 +208,24 @@ pub enum DecodeError<E> {
Fetch(E),
/// No declared form matches; carries the byte that decided it.
Unsupported(u8),
/// The instruction would be longer than [`MAX_INSTRUCTION_LEN`] bytes.
TooLong,
}
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));
return Err(DecodeError::TooLong);
}
let byte =
(self.fetch)(self.rip.wrapping_add(self.len as u64)).map_err(DecodeError::Fetch)?;
self.len += 1;
self.last = byte;
Ok(byte)
}
@@ -260,12 +264,7 @@ 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 cursor = Cursor { fetch, rip, len: 0 };
let mut operand_size = false;
let mut rep = false;
let mut repne = false;
@@ -430,7 +429,7 @@ pub fn decode<E>(
reg = register((modrm >> 3) & 7, rex_r, size);
let mode = modrm >> 6;
if mode == 3 {
if form.memory_only {
if form.memory_only || form.fixed_rm.is_some_and(|field| field != modrm & 7) {
return Err(DecodeError::Unsupported(opcode));
}
rm = Some(RmOperand::Reg(register(modrm & 7, rex_b, rm_size)));
+7 -1
View File
@@ -10,7 +10,7 @@
//! the state unchanged. Flags that the architecture leaves undefined keep their
//! previous value, which is permitted but not something guests may rely on.
use crate::cpu::{CpuState, ExitReason, RFlags, Register, cpuid};
use crate::cpu::{CpuState, ExitReason, RFlags, Register, X87State, cpuid};
use crate::memory::GuestMemory;
use crate::x86_decode::{Encoding, Insn, MemOperand, RegOperand, RmOperand, Segment};
use crate::x86_simd;
@@ -700,6 +700,12 @@ pub fn execute(
// instruction starts, on one host thread, so guest accesses are already
// totally ordered and a fence has nothing further to enforce.
Op::Lfence | Op::Mfence | Op::Sfence => {}
// The control, status and tag words take their initial values. The
// no-wait form checks no pending exception, and the data registers,
// which Xenora does not model, are left alone and only tagged empty
// (Intel SDM Vol. 2A, "FINIT/FNINIT"). FNINIT also clears the x87
// instruction and data pointers and last opcode, which are not modelled.
Op::Fninit => cpu.x87 = X87State::INIT,
Op::Cpuid => {
// The leaf is EAX and the subleaf ECX. Each result is a 32-bit
// register write, so the upper halves are cleared.
File diff suppressed because it is too large. Load diff
+72 -6
View File
@@ -41,6 +41,8 @@
//! `f=*` and `keep=` require the initial value. A case without `f=` on the
//! left runs with all flags clear and again with all flags set.
//! * `mx=` is MXCSR; `mx=~20:1b88` ignores the bits in `20`. `=?` ignores a value.
//! * `fcw=`, `fsw=` and `ftw=` are the x87 control, status and tag words. Every
//! case starts with all three away from their FNINIT values.
//! * Symbols: `D` writable data, `U` the unmapped page after it, `R` read-only
//! data, `S` stack, `C` code, `FSB` and `GSB` segment bases.
//! * Faults: `DE`, `GP`, `UD`, `XM`, and page faults `PFR`, `PFW`, `PFX` with
@@ -50,7 +52,7 @@
use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write as _;
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, Mxcsr, RFlags};
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, Mxcsr, RFlags, X87State};
use xenora_loader::dbt::{DbtEngine, is_native};
use xenora_loader::memory::{GuestMemory, MemoryError, MemoryPermissions};
use xenora_loader::x86_decode::decode;
@@ -1533,6 +1535,36 @@ fences_change_no_register_or_flag: rax=1122334455667788 rbx=99aabbccddeeff00 =>
fences_ignore_the_rm_field: rax=1122334455667788 => f=*
";
/// FNINIT, the only x87 instruction (#378). The three words it sets are all the
/// x87 state there is: no data register, pointer or last opcode is modelled, and
/// nothing can read the words back yet, so the cases look at guest state.
const X87_INIT: &str = r"
@ fninit
dbe3
SDM 2A FINIT/FNINIT (Operation); 1 8.1.5 (control word 037FH); 1 8.1.7 (tag FFFFH)
fninit_sets_control_status_and_tag: fcw=0040 fsw=3a41 ftw=0000 => fcw=037f fsw=0 ftw=ffff f=*
fninit_from_every_bit_set: fcw=ffff fsw=ffff ftw=0000 => fcw=037f fsw=0 ftw=ffff f=*
fninit_from_every_bit_clear: fcw=0 fsw=0 ftw=0 => fcw=037f fsw=0 ftw=ffff f=*
fninit_twice_is_the_same: fcw=037f fsw=0 ftw=ffff => fcw=037f fsw=0 ftw=ffff f=*
fninit_from_the_harness_default: => fcw=037f fsw=0 ftw=ffff f=*
@ fninit
dbe3
SDM 2A FINIT/FNINIT (the x87 words only; Flags Affected: C0 to C3 cleared, which are status-word bits)
fninit_keeps_registers_flags_xmm_and_mxcsr: rax=1122334455667788 rbx=99aabbccddeeff00 x3=q:0123456789abcdef,fedcba9876543210 mx=5fbf => fcw=037f fsw=0 ftw=ffff f=*
@ mov [rdi], rax; fninit; mov rbx, [rdi]
488907 dbe3 488b1f
SDM 2A FINIT/FNINIT
fninit_touches_no_memory: rdi=D rax=1122334455667788 m0=0000000000000000 => rbx=1122334455667788 m0=8877665544332211 fcw=037f fsw=0 ftw=ffff f=*
@ fninit; add al, bl
dbe3 00d8
SDM 2A FINIT/FNINIT; 2A ADD
fninit_then_integer_code_runs_on: rax=7f rbx=1 => rax=80 fcw=037f fsw=0 ftw=ffff f=cpAzSO
@ add al, bl
00d8
SDM 2A ADD (no x87 state is named)
integer_code_keeps_the_x87_words: rax=7f rbx=1 fcw=1a2b fsw=3c4d ftw=5e6f => rax=80 f=cpAzSO
";
const MEMORY_FAULTS: &str = r"
@ mov r8d, 1; add al, bl; mov rcx, [rsi]; mov r9d, 2
41b801000000 00d8 !488b0e 41b902000000
@@ -2814,11 +2846,23 @@ dpps_mask: x1=d:3f800000,40000000,40400000,40800000 x2=d:3f800000,3f800000,3f800
movddup_movsldup_movshdup: x2=d:7f800001,2,3,4 => x1=d:7f800001,2,7f800001,2 x3=d:7f800001,7f800001,3,3 x4=d:2,2,4,4 f=*
";
const DEFECT_OVERLONG_INSTRUCTION: &str = r"
const INSTRUCTION_LENGTH: &str = r"
@ .byte 0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x01,0xd8
!666666666666666666666666666601d8
SDM 3A 7.15 Interrupt 13 (instruction length over 15 bytes)
sixteen_byte_redundant_operand_size_prefixes: => ! GP
@ .byte 0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x05,0x34,0x12
666666666666666666666666053412
SDM 2A 2.2.1 (15-byte limit); 2A ADD
fifteen_bytes_ending_in_the_immediate_execute: rax=ffffffffffff0001 => rax=ffffffffffff1235 f=cPazso
@ .byte 0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x05,0x34,0x12
!66666666666666666666666666053412
SDM 3A 7.15 Interrupt 13 (instruction length over 15 bytes)
sixteenth_byte_in_the_immediate_is_gp: rax=1 => ! GP
@ mov eax, 1; .byte 0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x66,0x05,0x34,0x12
b801000000 !66666666666666666666666666053412
SDM 3A 7.15 Interrupt 13 (instruction length over 15 bytes)
overlong_after_an_instruction_retires_it_first: rax=ffffffffffffffff => rax=1 ! GP
";
const PAGE_CROSSING: &str = r"
@@ -2875,6 +2919,7 @@ const GROUPS: &[(&str, &str)] = &[
("fs_gs", FS_GS),
("decoding", DECODING),
("fences", FENCES),
("x87_init", X87_INIT),
("memory_faults", MEMORY_FAULTS),
("straddling_fault_address", STRADDLING_FAULT_ADDRESS),
("noncanonical_address", NONCANONICAL_ADDRESS),
@@ -2889,7 +2934,7 @@ const GROUPS: &[(&str, &str)] = &[
("fp_packed_and_sticky", FP_PACKED_AND_STICKY),
("fp_mxcsr_and_unmasked", FP_MXCSR_AND_UNMASKED),
("fp_beyond_sse2", FP_BEYOND_SSE2),
("defect_overlong_instruction", DEFECT_OVERLONG_INSTRUCTION),
("instruction_length", INSTRUCTION_LENGTH),
("exact_unmasked_overflow", EXACT_UNMASKED_OVERFLOW),
("page_crossing", PAGE_CROSSING),
];
@@ -3219,6 +3264,13 @@ fn initial_cpu() -> CpuState {
}
cpu.fs_base = FS_BASE;
cpu.gs_base = GS_BASE;
// None of the three is what FNINIT sets, so a reset is always visible and
// an instruction that wrongly resets one is caught by any case.
cpu.x87 = X87State {
control: 0x0c40,
status: 0x2b05,
tag: 0x5a5a,
};
cpu
}
@@ -3279,6 +3331,13 @@ fn apply(text: &str, expected: &mut Expected) {
expected.cpu.rip = value(data);
} else if key == "gsbase" {
expected.cpu.gs_base = value(data);
} else if let Some(word) = match key {
"fcw" => Some(&mut expected.cpu.x87.control),
"fsw" => Some(&mut expected.cpu.x87.status),
"ftw" => Some(&mut expected.cpu.x87.tag),
_ => None,
} {
*word = u16::try_from(value(data)).expect("a 16-bit x87 word");
} else if key == "mx" {
if data == "?" {
expected.mxcsr_mask = 0;
@@ -3513,6 +3572,9 @@ fn check(case: &Case, engine: Engine, initial_flags: u8) -> Result<(), String> {
if (cpu.fs_base, cpu.gs_base) != (want.cpu.fs_base, want.cpu.gs_base) {
text.push_str(" segment base changed;");
}
if cpu.x87 != want.cpu.x87 {
let _ = write!(text, " x87={:04x?} want {:04x?};", cpu.x87, want.cpu.x87);
}
let memory_text = Image::store(&memory).differences(&want.image);
if !memory_text.is_empty() {
let _ = write!(text, " memory{memory_text};");
@@ -3655,6 +3717,11 @@ fn fences() {
check_group(FENCES);
}
#[test]
fn x87_init() {
check_group(X87_INIT);
}
#[test]
fn memory_faults() {
check_group(MEMORY_FAULTS);
@@ -3726,9 +3793,8 @@ fn fp_beyond_sse2() {
}
#[test]
#[ignore = "known defect (#155): an instruction over 15 bytes is illegal, not #GP"]
fn defect_overlong_instruction() {
check_group(DEFECT_OVERLONG_INSTRUCTION);
fn instruction_length() {
check_group(INSTRUCTION_LENGTH);
}
#[test]
+325
View File
@@ -0,0 +1,325 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Repeated-frame regression for the guest graphics context (issue #148).
//!
//! One device, queue, allocator and command list are driven through the
//! per-frame loop a D3D12 guest uses: reset, record, close, execute. Each
//! frame changes the guest-backed vertex data, the clear colour or the draw
//! parameters. Expected pixels are written out by hand below for triangles
//! chosen so their coverage of a 4×3 viewport is obvious; they are not
//! computed by the rasterizer under test. These tests use the software
//! reference backend only; no native Metal result is claimed here.
use xenora_loader::graphics::{
CommandListType, GraphicsBackendId, GraphicsContext, GraphicsError, GraphicsHandle,
ResourceDesc, ResourceDimension, ResourceStates,
};
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
const WIDTH: usize = 4;
const HEIGHT: usize = 3;
const VERTICES: u64 = 0x0010_0000;
/// Two triangles of three float4 positions each.
const VERTEX_BYTES: usize = 96;
const RED: [u8; 4] = [255, 0, 0, 255];
/// Covers every pixel centre of the viewport.
const FULL: [[f32; 4]; 3] = [
[-1.0, -1.0, 0.0, 1.0],
[3.0, -1.0, 0.0, 1.0],
[-1.0, 3.0, 0.0, 1.0],
];
/// Its right edge is x = 0 in clip space, so it covers the two left columns
/// (centres at x = -0.75 and -0.25) and none of the two right ones.
const LEFT_HALF: [[f32; 4]; 3] = [
[0.0, 10.0, 0.0, 1.0],
[0.0, -10.0, 0.0, 1.0],
[-30.0, 0.0, 0.0, 1.0],
];
/// Lies wholly outside the viewport.
const OFFSCREEN: [[f32; 4]; 3] = [
[2.0, 2.0, 0.0, 1.0],
[3.0, 2.0, 0.0, 1.0],
[2.0, 3.0, 0.0, 1.0],
];
struct Rig {
ctx: GraphicsContext,
memory: GuestMemory,
queue: GraphicsHandle,
alloc: GraphicsHandle,
list: GraphicsHandle,
vertices: GraphicsHandle,
target: GraphicsHandle,
}
fn rig() -> Rig {
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();
// A new list starts open; close it so every frame begins with a reset.
ctx.close_command_list(list).unwrap();
let mut memory = GuestMemory::new();
memory
.map_region(VERTICES, 0x1000, MemoryPermissions::READ_WRITE)
.unwrap();
let buffer = ResourceDesc {
dimension: ResourceDimension::Buffer,
width: VERTEX_BYTES as u64,
height: 1,
depth_or_array_size: 1,
mip_levels: 1,
format_rgba8: false,
};
let vertices = ctx
.create_committed_resource(
device,
buffer,
ResourceStates::VERTEX_AND_CONSTANT_BUFFER,
Some(VERTICES),
)
.unwrap();
let texture = ResourceDesc {
dimension: ResourceDimension::Texture2D,
width: WIDTH as u64,
height: HEIGHT as u32,
depth_or_array_size: 1,
mip_levels: 1,
format_rgba8: true,
};
let target = ctx
.create_committed_resource(device, texture, ResourceStates::PRESENT, None)
.unwrap();
Rig {
ctx,
memory,
queue,
alloc,
list,
vertices,
target,
}
}
fn write_triangle(memory: &mut GuestMemory, slot: u64, triangle: [[f32; 4]; 3]) {
let bytes: Vec<u8> = triangle
.iter()
.flatten()
.flat_map(|value| value.to_le_bytes())
.collect();
memory.write_bytes(VERTICES + slot * 48, &bytes).unwrap();
}
/// Pixels with `columns` red from the left and the rest in `clear`.
fn expected(columns: usize, clear: [u8; 4]) -> Vec<u8> {
(0..WIDTH * HEIGHT)
.flat_map(|pixel| if pixel % WIDTH < columns { RED } else { clear })
.collect()
}
struct Draw {
clear: [u8; 4],
offset: usize,
vertex_count: u32,
instance_count: u32,
start_vertex: u32,
start_instance: u32,
}
impl Draw {
fn one(clear: [u8; 4]) -> Self {
Self {
clear,
offset: 0,
vertex_count: 3,
instance_count: 1,
start_vertex: 0,
start_instance: 0,
}
}
}
/// Record one frame: target to RENDER_TARGET, draw, back to PRESENT.
fn record(rig: &mut Rig, draw: &Draw) -> Result<(), GraphicsError> {
let ctx = &mut rig.ctx;
ctx.reset_command_list(rig.list, rig.alloc)?;
ctx.cmd_resource_barrier(
rig.list,
rig.target,
ResourceStates::PRESENT,
ResourceStates::RENDER_TARGET,
)?;
ctx.cmd_set_viewport(rig.list, WIDTH, HEIGHT)?;
ctx.cmd_set_render_targets(rig.list, Some(rig.target), draw.clear)?;
ctx.cmd_set_vertex_buffer(rig.list, rig.vertices, draw.offset, 48)?;
ctx.cmd_draw_instanced(
rig.list,
draw.vertex_count,
draw.instance_count,
draw.start_vertex,
draw.start_instance,
)?;
ctx.cmd_resource_barrier(
rig.list,
rig.target,
ResourceStates::RENDER_TARGET,
ResourceStates::PRESENT,
)?;
ctx.close_command_list(rig.list)
}
fn frame(rig: &mut Rig, draw: &Draw) -> Result<(Vec<u8>, usize), GraphicsError> {
record(rig, draw)?;
let outcome = rig
.ctx
.execute_command_list(rig.queue, rig.list, &rig.memory)?;
assert_eq!(outcome.backend, GraphicsBackendId::SoftwareReference);
assert_eq!((outcome.width, outcome.height), (WIDTH, HEIGHT));
Ok((outcome.pixels, outcome.draw_count))
}
fn frame_index(rig: &Rig) -> u64 {
rig.ctx.last_presentation.lock().unwrap().frame_index
}
#[test]
fn each_frame_reflects_its_own_guest_vertices_and_clear_colour() {
let mut rig = rig();
let frames = [
(LEFT_HALF, [0, 0, 64, 255], 2),
(FULL, [10, 20, 30, 255], WIDTH),
(OFFSCREEN, [1, 2, 3, 4], 0),
(LEFT_HALF, [9, 9, 9, 255], 2),
];
for (index, (triangle, clear, columns)) in frames.into_iter().enumerate() {
write_triangle(&mut rig.memory, 0, triangle);
let (pixels, draws) = frame(&mut rig, &Draw::one(clear)).unwrap();
let want = expected(columns, clear);
assert_eq!(pixels, want, "frame {index}");
assert_eq!(draws, 1, "frame {index}");
assert_eq!(frame_index(&rig), index as u64 + 1);
// The presentation holds this frame's pixels, not an earlier one's.
let presented = rig.ctx.last_presentation.lock().unwrap().pixels.clone();
assert_eq!(presented, want, "presented frame {index}");
}
}
#[test]
fn a_zero_instance_or_zero_vertex_frame_draws_nothing() {
let mut rig = rig();
write_triangle(&mut rig.memory, 0, FULL);
let clear = [5, 6, 7, 255];
for (vertices, instances) in [(3, 0), (0, 1), (2, 1)] {
let draw = Draw {
vertex_count: vertices,
instance_count: instances,
..Draw::one(clear)
};
let (pixels, draws) = frame(&mut rig, &draw).unwrap();
assert_eq!(pixels, expected(0, clear), "{vertices} x {instances}");
assert_eq!(draws, 0, "{vertices} x {instances}");
}
// The next ordinary frame still draws.
let (pixels, draws) = frame(&mut rig, &Draw::one(clear)).unwrap();
assert_eq!((pixels, draws), (expected(WIDTH, clear), 1));
}
#[test]
fn unsupported_draw_parameters_fail_and_the_next_frame_recovers() {
let mut rig = rig();
write_triangle(&mut rig.memory, 0, LEFT_HALF);
write_triangle(&mut rig.memory, 1, FULL);
let clear = [0, 0, 0, 255];
frame(&mut rig, &Draw::one(clear)).unwrap();
let rejected = [
Draw {
start_vertex: 3,
..Draw::one(clear)
},
Draw {
instance_count: 2,
..Draw::one(clear)
},
Draw {
start_instance: 1,
..Draw::one(clear)
},
Draw {
vertex_count: 6,
..Draw::one(clear)
},
];
for draw in &rejected {
// Only the draw is rejected. The barrier before it already ran, so
// the target is left in RENDER_TARGET, as a guest would see it.
let before = frame_index(&rig);
let result = frame(&mut rig, draw);
assert!(
matches!(result, Err(GraphicsError::Unsupported(_))),
"{result:?}"
);
assert_eq!(frame_index(&rig), before, "a failed frame is not presented");
rig.ctx.reset_command_list(rig.list, rig.alloc).unwrap();
rig.ctx
.cmd_resource_barrier(
rig.list,
rig.target,
ResourceStates::RENDER_TARGET,
ResourceStates::PRESENT,
)
.unwrap();
rig.ctx.close_command_list(rig.list).unwrap();
rig.ctx
.execute_command_list(rig.queue, rig.list, &rig.memory)
.unwrap();
}
// The second triangle is still reachable through the view offset.
let draw = Draw {
offset: 48,
..Draw::one(clear)
};
let (pixels, _) = frame(&mut rig, &draw).unwrap();
assert_eq!(pixels, expected(WIDTH, clear));
}
#[test]
fn a_vertex_view_outside_its_buffer_fails_without_reading_past_it() {
let mut rig = rig();
write_triangle(&mut rig.memory, 0, FULL);
write_triangle(&mut rig.memory, 1, FULL);
// Mapped guest memory continues past the buffer; the view must not.
write_triangle(&mut rig.memory, 2, FULL);
let clear = [0, 0, 0, 255];
for offset in [VERTEX_BYTES - 47, VERTEX_BYTES, usize::MAX - 100] {
let draw = Draw {
offset,
..Draw::one(clear)
};
assert_eq!(
frame(&mut rig, &draw),
Err(GraphicsError::IndexOutOfRange),
"offset {offset}"
);
rig.ctx.reset_command_list(rig.list, rig.alloc).unwrap();
rig.ctx
.cmd_resource_barrier(
rig.list,
rig.target,
ResourceStates::RENDER_TARGET,
ResourceStates::PRESENT,
)
.unwrap();
rig.ctx.close_command_list(rig.list).unwrap();
rig.ctx
.execute_command_list(rig.queue, rig.list, &rig.memory)
.unwrap();
}
}
+187
View File
@@ -7,6 +7,7 @@
//! convention documentation, not from the registry or the handlers.
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::{AtomicUsize, Ordering};
use xenora_loader::cpu::{CpuState, ExitReason, Register};
use xenora_loader::dbt::DbtEngine;
@@ -696,6 +697,76 @@ fn floating_arguments_and_results_use_xmm_registers() {
assert_eq!(float("fabsf", garbage | 0xBF80_0000) as u32, 0x3F80_0000); // -1
}
#[test]
fn guest_call_through_dbt_preserves_win64_abi_state() {
use Register::{R8, R9, R12, R13, R14, R15, Rax, Rbp, Rbx, Rcx, Rdi, Rdx, Rsi, Rsp};
let observed = Arc::new(Mutex::new(None::<(u64, u64, [u64; 4])>));
let seen = observed.clone();
let mut registry = ImportRegistry::new();
registry.register("t.dll", "F", move |_args, cpu, mem| {
let rsp = cpu.get(Rsp);
let shadow = [
mem.read_u64(rsp + 8).unwrap(),
mem.read_u64(rsp + 16).unwrap(),
mem.read_u64(rsp + 24).unwrap(),
mem.read_u64(rsp + 32).unwrap(),
];
*seen.lock().unwrap() = Some((rsp, cpu.rip, shadow));
cpu.set(Rcx, 0x11);
cpu.set(Rdx, 0x22);
cpu.set(R8, 0x33);
cpu.set(R9, 0x44);
for (reg, lane) in cpu.xmm[..6].iter_mut().enumerate() {
*lane = u128::from(0x55_u64 + reg as u64);
}
Ok(0x99AA_BBCC_DDEE_F001)
});
let image = build(&[("t.dll", Symbol::Name("F"))]);
let pe = ParsedPe::parse(&image.bytes).unwrap();
let mut memory = pe.load_into_memory(&image.bytes).unwrap().memory;
memory
.map_region(STACK, 0x1000, MemoryPermissions::READ_WRITE)
.unwrap();
registry
.bind_imports(&pe, &image.bytes, BASE, &mut memory)
.unwrap();
let mut engine = DbtEngine::new(256 * 1024).unwrap();
engine.set_import_registry(registry);
// Before CALL RSP is 16-byte aligned; CALL pushes return address so the
// callee sees RSP % 16 == 8. Shadow space is [entry_rsp+8, entry_rsp+40).
let initial_rsp = STACK_TOP;
assert_eq!(initial_rsp % 16, 0);
let entry_rsp_expected = initial_rsp - 8;
for slot in 0..4u64 {
memory
.write_u64(entry_rsp_expected + 8 + slot * 8, 0x7000 + slot)
.unwrap();
}
let mut cpu = CpuState::new(BASE + u64::from(CODE_RVA), initial_rsp);
let nonvolatile_gpr = [Rbx, Rbp, Rdi, Rsi, R12, R13, R14, R15];
for (index, register) in nonvolatile_gpr.into_iter().enumerate() {
cpu.set(register, 0x6100 + index as u64);
}
for (offset, lane) in cpu.xmm[6..16].iter_mut().enumerate() {
*lane = u128::from(0x6200_u64 + (offset + 6) as u64);
}
let result = engine.run(&mut cpu, &mut memory, 1000);
assert_eq!(result.exit_reason, ExitReason::Halt);
let (entry_rsp, _, shadow) = observed.lock().unwrap().expect("service ran");
assert_eq!(entry_rsp, entry_rsp_expected);
assert_eq!(entry_rsp % 16, 8);
assert_eq!(shadow, [0x7000, 0x7001, 0x7002, 0x7003]);
assert_eq!(cpu.get(Rax), 0x99AA_BBCC_DDEE_F001);
assert_eq!(cpu.get(Rsp), initial_rsp);
for (index, register) in nonvolatile_gpr.into_iter().enumerate() {
assert_eq!(cpu.get(register), 0x6100 + index as u64, "{register:?}");
}
for (offset, lane) in cpu.xmm[6..16].iter().enumerate() {
let index = offset + 6;
assert_eq!(*lane, u128::from(0x6200_u64 + index as u64), "xmm{index}");
}
}
#[test]
fn arguments_are_assigned_by_position_and_read_the_stack_after_the_fourth() {
let mut memory = GuestMemory::new();
@@ -957,6 +1028,122 @@ fn a_service_that_changes_a_nonvolatile_register_stops_the_guest() {
}
}
#[test]
fn service_may_write_its_caller_allocated_shadow_space() {
// Microsoft x64 calling convention: the caller reserves four home slots,
// but the callee may use them. Their contents are not nonvolatile state.
let (registry, mut memory, trampoline) = bound_service(|_, cpu, memory| {
for slot in 0..4u64 {
memory
.write_u64(cpu.get(Register::Rsp) + 8 + slot * 8, 0xA000 + slot)
.unwrap();
}
Ok(7)
});
let entry_rsp = STACK_TOP - 8;
memory.write_u64(entry_rsp, 0x1234).unwrap();
let mut cpu = CpuState::new(trampoline, entry_rsp);
assert_eq!(registry.dispatch(trampoline, &mut cpu, &mut memory), Ok(()));
assert_eq!(cpu.rip, 0x1234);
assert_eq!(cpu.get(Register::Rsp), entry_rsp + 8);
assert_eq!(cpu.get(Register::Rax), 7);
for slot in 0..4u64 {
assert_eq!(memory.read_u64(entry_rsp + 8 + slot * 8), Ok(0xA000 + slot));
}
}
#[test]
fn service_calls_preserve_win64_abi_state() {
// Microsoft x64 calling convention: at entry RSP % 16 == 8 (return address
// pushed by CALL). Callee preserves RBX,RBP,RDI,RSI,R12-R15 and XMM6-XMM15.
// Caller allocates 32-byte shadow/home space at [RSP+8, RSP+40), which
// the callee may use. This handler leaves it unchanged; the separate
// shadow-space test checks a handler that writes it. RAX carries the
// return value; RCX,RDX,R8,R9,R10,R11,XMM0-XMM5 are volatile.
use Register::{R8, R9, R10, R11, R12, R13, R14, R15, Rax, Rbp, Rbx, Rcx, Rdi, Rdx, Rsi, Rsp};
let observed = Arc::new(Mutex::new(None::<(u64, u64, [u64; 4], u64)>));
let seen = observed.clone();
let (registry, mut memory, trampoline) = bound_service(move |args, cpu, mem| {
let rsp = cpu.get(Rsp);
let shadow = [
mem.read_u64(rsp + 8).unwrap(),
mem.read_u64(rsp + 16).unwrap(),
mem.read_u64(rsp + 24).unwrap(),
mem.read_u64(rsp + 32).unwrap(),
];
*seen.lock().unwrap() = Some((rsp, cpu.rip, shadow, args.rcx));
// Clobber volatile registers; dispatcher must still return correctly and
// nonvolatile state must be preserved after return.
cpu.set(Rcx, 0xA1);
cpu.set(Rdx, 0xA2);
cpu.set(R8, 0xA3);
cpu.set(R9, 0xA4);
cpu.set(R10, 0xA5);
cpu.set(R11, 0xA6);
for (reg, lane) in cpu.xmm[..6].iter_mut().enumerate() {
*lane = u128::from(0xB0_u64 + reg as u64);
}
Ok(0x1122_3344_5566_7788)
});
// Win64: before CALL RSP is 16-byte aligned; CALL pushes return address,
// so callee entry sees RSP % 16 == 8.
let call_rsp = STACK_TOP - 8;
assert_eq!(call_rsp % 16, 8);
memory.write_u64(call_rsp, 0x1234).unwrap();
for slot in 0..4u64 {
memory
.write_u64(call_rsp + 8 + slot * 8, 0xC000 + slot)
.unwrap();
}
let mut cpu = CpuState::new(trampoline, call_rsp);
let nonvolatile_gpr = [Rbx, Rbp, Rdi, Rsi, R12, R13, R14, R15];
for (index, register) in nonvolatile_gpr.into_iter().enumerate() {
cpu.set(register, 0x5AA5_0000_0001_0000 + index as u64);
}
for (offset, lane) in cpu.xmm[6..16].iter_mut().enumerate() {
*lane = u128::from(0xD000_0000_0000_0000_u64 + (offset + 6) as u64);
}
cpu.set(Rcx, 0x1357_9BDF_2468_ACE0);
let result = registry.dispatch(trampoline, &mut cpu, &mut memory);
assert_eq!(result, Ok(()));
let (entry_rsp, entry_rip, shadow, entry_rcx) = observed.lock().unwrap().expect("service ran");
assert_eq!(entry_rip, trampoline);
assert_eq!(
entry_rsp, call_rsp,
"service sees caller RSP at return address"
);
assert_eq!(entry_rsp % 16, 8, "Win64 entry RSP must be 8 mod 16");
assert_eq!(entry_rcx, 0x1357_9BDF_2468_ACE0);
// Shadow/home space is caller-owned and must be addressable by the service.
assert_eq!(shadow, [0xC000, 0xC001, 0xC002, 0xC003]);
for slot in 0..4u64 {
assert_eq!(
memory.read_u64(call_rsp + 8 + slot * 8).unwrap(),
0xC000 + slot,
"this handler leaves its home slots untouched"
);
}
// Post-return ABI state.
assert_eq!(cpu.get(Rax), 0x1122_3344_5566_7788);
assert_eq!(cpu.get(Rsp), call_rsp + 8);
assert_eq!(cpu.rip, 0x1234);
for (index, register) in nonvolatile_gpr.into_iter().enumerate() {
assert_eq!(
cpu.get(register),
0x5AA5_0000_0001_0000 + index as u64,
"nonvolatile {register:?} must be preserved"
);
}
for (offset, lane) in cpu.xmm[6..16].iter().enumerate() {
let index = offset + 6;
assert_eq!(
*lane,
u128::from(0xD000_0000_0000_0000_u64 + index as u64),
"nonvolatile xmm{index} must be preserved"
);
}
}
#[test]
fn a_call_that_cannot_return_runs_no_service() {
let calls = Arc::new(AtomicUsize::new(0));
+1 -1
View File
@@ -103,7 +103,7 @@ def cases():
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", "cpuid",
"nop dword ptr [rax + 8]", "pause", "lfence", "mfence", "sfence",
"nop dword ptr [rax + 8]", "pause", "lfence", "mfence", "sfence", "fninit",
f"movnti {mem(32)}, ebx", f"movnti {mem(64)}, rbx",
f"movnti {mem(32)}, r9d", f"movnti {mem(64)}, r14", "push r9", "push rbx", "push -5", "push 0x12345678",
f"push {mem(64)}", "pop rbx", "pop r12", f"pop {mem(64)}", "leave"]
+1
View File
@@ -1192,6 +1192,7 @@ f3 90 | pause
0f ae e8 | lfence
0f ae f0 | mfence
0f ae f8 | sfence
db e3 | fninit
0f c3 5c be 10 | movnti dword ptr [rsi + 4*rdi + 16], ebx
48 0f c3 5c be 10 | movnti qword ptr [rsi + 4*rdi + 16], rbx
44 0f c3 4c be 10 | movnti dword ptr [rsi + 4*rdi + 16], r9d
+107 -1
View File
@@ -11,7 +11,7 @@
//! but the interpreter and the DBT must still agree on the complete state.
use std::collections::{BTreeMap, BTreeSet};
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, RFlags};
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, RFlags, X87State};
use xenora_loader::dbt::{DbtEngine, is_native};
use xenora_loader::memory::{GuestMemory, MemoryError, MemoryPermissions};
use xenora_loader::x86_decode::decode;
@@ -67,6 +67,8 @@ struct Machine {
/// Stack qwords at STACK_TOP - 8 and STACK_TOP.
pushed: u64,
top: u64,
/// x87 control, status and tag words.
x87: [u16; 3],
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
@@ -789,6 +791,13 @@ fn reference(m: &mut Machine, text: &str) -> Outcome {
}
// The fences order memory accesses and compute nothing.
"nop" | "pause" | "lfence" | "mfence" | "sfence" => Outcome::Done(none),
"fninit" => {
// Intel SDM Vol. 2A, "FINIT/FNINIT", Operation: FPUControlWord :=
// 037FH, FPUStatusWord := 0, FPUTagWord := FFFFH. Nothing else here
// is x87 state.
m.x87 = [0x037F, 0, 0xFFFF];
Outcome::Done(none)
}
"cpuid" => {
// Xenora's guest CPUID contract, restated: the vendor "Xenora guest"
// and the four features whose every instruction exists, CMOV and
@@ -898,6 +907,8 @@ impl Random {
operand: self.value(),
pushed: self.next(),
top: self.value(),
// Any bit pattern: nothing interprets these words.
x87: [self.next() as u16, self.next() as u16, self.next() as u16],
}
}
}
@@ -926,6 +937,12 @@ fn load(machine: &Machine, code: &[u8]) -> (CpuState, GuestMemory) {
pf: f.pf,
af: f.af,
};
let [control, status, tag] = machine.x87;
cpu.x87 = X87State {
control,
status,
tag,
};
(cpu, memory)
}
@@ -984,6 +1001,13 @@ fn every_fixture_instruction_matches_the_reference_in_both_engines() {
"{text}"
);
assert_eq!(state.rip, ENTRY + case.code.len() as u64, "{text}");
let x87 = state.x87;
assert_eq!(
[x87.control, x87.status, x87.tag],
expected.x87,
"{text}: x87 words from {:04x?}",
machine.x87
);
if !undefined.destination {
assert_eq!(state.gpr, expected.gpr, "{text} from {cpu:x?}");
assert_eq!(
@@ -1289,6 +1313,12 @@ fn undeclared_and_ambiguous_encodings_are_rejected() {
&[0x0F, 0xC3, 0xC1], // movnti with a register destination
&[0x66, 0x0F, 0xC3, 0x06], // 66 with movnti
&[0x0F, 0xA3, 0x06], // bt [rsi], eax
&[0x9B], // fwait
&[0x9B, 0xDB, 0xE3], // finit: fwait, then fninit
&[0x66, 0xDB, 0xE3], // 66 with fninit
&[0xF3, 0xDB, 0xE3], // F3 with fninit
&[0xF2, 0xDB, 0xE3], // F2 with fninit
&[0xF0, 0xDB, 0xE3], // lock fninit
&[0xC6, 0xC8, 0x01], // C6 /1
&[0xFF, 0xF8], // FF /7
&[0xFE, 0xD0], // FE /2
@@ -1321,6 +1351,81 @@ fn undeclared_and_ambiguous_encodings_are_rejected() {
}
}
/// FNINIT (DB E3) is the only x87 instruction. Every other ModRM byte under the
/// eight x87 escape opcodes, D8 to DF, stops both engines and changes nothing.
/// That includes FNINIT's neighbours of the same digit, such as FNCLEX (DB E2),
/// and the memory forms of that digit.
#[test]
fn fninit_is_the_only_x87_encoding_accepted() {
let machine = Random(7).machine();
assert_ne!(
machine.x87,
[0x037F, 0, 0xFFFF],
"the reset must be visible"
);
let mut accepted = Vec::new();
for opcode in 0xD8..=0xDF_u8 {
for modrm in 0..=0xFF_u8 {
// The padding is a SIB byte and displacement for the memory forms.
let code = [opcode, modrm, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90];
for native in [false, true] {
let (mut cpu, mut memory) = load(&machine, &code);
let before = cpu.clone();
let data = bytes(&memory);
let result = if native {
DbtEngine::new(16 * 1024)
.unwrap()
.run(&mut cpu, &mut memory, 1)
} else {
Interpreter::new(cpu, &mut memory, 1).run()
};
let what = format!("{opcode:02X} {modrm:02X}, native {native}");
assert_eq!(bytes(&memory), data, "{what}");
if matches!(result.exit_reason, ExitReason::IllegalInstruction(_)) {
assert_eq!(result.final_state, before, "{what}");
continue;
}
accepted.push((opcode, modrm, native));
assert_eq!(result.exit_reason, ExitReason::StepLimitExceeded, "{what}");
// Only RIP and the three x87 words may differ.
let mut wanted = before;
wanted.rip = ENTRY + 2;
wanted.x87 = X87State {
control: 0x037F,
status: 0,
tag: 0xFFFF,
};
assert_eq!(result.final_state, wanted, "{what}");
}
}
}
assert_eq!(accepted, [(0xDB, 0xE3, false), (0xDB, 0xE3, true)]);
}
/// A local rule, pinned so it cannot change unnoticed: a segment override or a
/// REX prefix before FNINIT is accepted and has no effect, as the decoder
/// treats them before any form without operands. It is not derived from a
/// manual statement. The prefixes that are refused are in
/// `undeclared_and_ambiguous_encodings_are_rejected`.
#[test]
fn prefixes_accepted_before_fninit_have_no_effect() {
let machine = Random(11).machine();
for prefix in [0x2E_u8, 0x64, 0x65, 0x40, 0x41, 0x48, 0x4F] {
let code = [prefix, 0xDB, 0xE3, 0x90];
let (cpu, _) = load(&machine, &code);
let mut wanted = cpu;
wanted.rip = ENTRY + 3;
wanted.x87 = X87State {
control: 0x037F,
status: 0,
tag: 0xFFFF,
};
let (state, exit, _) = run_both(&machine, &code, 1);
assert_eq!(exit, ExitReason::StepLimitExceeded, "{prefix:02X}");
assert_eq!(state, wanted, "{prefix:02X}");
}
}
#[test]
fn raw_syscalls_are_refused_by_the_dbt_only() {
let machine = Random(9).machine();
@@ -1447,6 +1552,7 @@ fn bit_scans_and_bit_tests_follow_the_architecture() {
operand: 0,
pushed: 0,
top: STACK_TOP,
x87: [0x037F, 0, 0xFFFF],
}
}
+58 -6
View File
@@ -178,7 +178,7 @@ fn interpreter_rejects_overlong_segment_prefix_run() {
.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.exit_reason, ExitReason::GeneralProtection);
assert_eq!(result.instructions_executed, 0);
assert_eq!(result.final_state.rip, ENTRY);
}
@@ -195,9 +195,61 @@ fn dbt_rejects_overlong_segment_prefix_run() {
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
);
assert_eq!(result.exit_reason, ExitReason::GeneralProtection);
assert_eq!(result.instructions_executed, 0);
assert_eq!(cpu.rip, ENTRY);
}
/// Runs `prefixes` bytes of 0x66 that end exactly at the end of a mapped page,
/// with nothing mapped after it, on both engines.
fn run_prefixes_at_page_end(prefixes: usize) -> [(ExitReason, u64, u64); 2] {
const PAGE: u64 = 0x2000;
const PAGE_LEN: usize = 0x1000;
let mut data = vec![0x90; PAGE_LEN];
data[PAGE_LEN - prefixes..].fill(0x66);
let entry = PAGE + (PAGE_LEN - prefixes) as u64;
let mut memory = GuestMemory::new();
memory
.map_region_with_data(PAGE, PAGE_LEN, MemoryPermissions::READ_EXECUTE, &data)
.unwrap();
let interpreted = Interpreter::new(CpuState::new(entry, 0), &mut memory, 8).run();
let mut cpu = CpuState::new(entry, 0);
let translated = DbtEngine::new(1024 * 1024)
.expect("JIT memory allocation")
.run(&mut cpu, &mut memory, 8);
[
(
interpreted.exit_reason,
interpreted.final_state.rip,
interpreted.instructions_executed,
),
(
translated.exit_reason,
cpu.rip,
translated.instructions_executed,
),
]
.map(|(exit, rip, count)| (exit, rip.wrapping_sub(entry), count as u64))
}
/// Fifteen prefixes are already too long whatever follows, so the 16th byte is
/// never fetched: #GP, not a fetch fault on the unmapped page after them
/// (Intel SDM Vol. 3A, 7.15).
#[test]
fn overlong_instruction_is_gp_without_fetching_the_sixteenth_byte() {
for (exit, rip_offset, count) in run_prefixes_at_page_end(MAX_INSTRUCTION_LEN) {
assert_eq!(exit, ExitReason::GeneralProtection);
assert_eq!((rip_offset, count), (0, 0));
}
}
/// Control for the test above: fourteen prefixes leave room for an opcode, so
/// the fetch of the 15th byte is what fails.
#[test]
fn fourteen_prefixes_at_a_page_end_fault_on_the_fetch() {
for (exit, rip_offset, count) in run_prefixes_at_page_end(MAX_INSTRUCTION_LEN - 1) {
assert!(matches!(exit, ExitReason::MemoryFault(_)), "{exit:?}");
assert_eq!((rip_offset, count), (0, 0));
}
}
+16
View File
@@ -16,6 +16,9 @@
# lock = true accepts the LOCK prefix (F0) when the ModRM operand is memory.
# Every other use of LOCK is rejected, as the architecture's #UD.
#
# rm = N requires the ModRM r/m field to be N. It needs register_only, so the
# form matches exactly one ModRM byte. At most one form per opcode and digit.
#
# prefix is a mandatory prefix: "66", "f3" or "f2". SSE forms use size x (XMM)
# and give the ModRM operand width in src: x = 16 bytes, q = 8, d = 4, w = 2.
# A 16-byte memory operand must be aligned unless unaligned = true.
@@ -100,6 +103,7 @@ cmc = { reads = "cf", writes = "cf", ref = "sdm CMC" }
cpuid = { ref = "sdm CPUID" }
cld = { ref = "sdm CLD" }
std = { ref = "sdm STD" }
fninit = { ref = "sdm FINIT/FNINIT" }
# A REP form repeats by leaving RIP on itself, so these end a translated block.
movs = { terminator = true, ref = "sdm MOVS/MOVSB/MOVSW/MOVSD/MOVSQ" }
stos = { terminator = true, ref = "sdm STOS/STOSB/STOSW/STOSD/STOSQ" }
@@ -672,6 +676,18 @@ opcode = 0xFD
enc = "none"
size = "n"
# FNINIT is DB E3 and nothing else: the other register bytes of digit 4 are
# different instructions (DB E2 is FNCLEX) and the memory forms are not x87
# initialisation at all. No other x87 form is declared.
[[form]]
op = "fninit"
opcode = 0xDB
digit = 4
enc = "rm_unread"
size = "n"
register_only = true
rm = 3
[[form]]
op = "movzx"
map = "0f"
+19 -4
View File
@@ -5,14 +5,14 @@ The static PE probe, the interpreter and the native ARM64 dynamic binary transla
| Part | File | Role |
| --- | --- | --- |
| Registry | `crates/loader/x86/instructions.toml` | Opcode map, opcode, ModRM digit, operand encoding, size, immediate, flag effects and public reference. Data only. |
| Generator | `crates/loader/generate_x86.py` | `validate`, `generate` and `--check`. Rejects overlapping encodings, opcodes that are prefixes, contradictory operand rules, unknown vocabulary and flags both written and undefined. |
| Generator | `crates/loader/generate_x86.py` | `validate`, `generate` and `--check`. Rejects overlapping encodings, opcodes that are prefixes, contradictory operand rules, a fixed r/m field on a form that could take memory, unknown vocabulary and flags both written and undefined. |
| Tables | `crates/loader/src/x86_table.rs` | Generated static tables. No metadata is parsed at run time. |
| Semantics | `crates/loader/src/x86_exec.rs`, `x86_simd.rs`, `x86_float.rs`, `softfloat.rs` | Rust primitives for integer, vector and floating-point forms. Every instruction is all-or-nothing. |
| Lowering | `crates/loader/src/dbt.rs` | ARM64 for the forms `is_native` accepts. Every other form calls the shared semantics and is counted in `DbtMetrics::interpreter_fallbacks`. |
## Adding a form
1. Add the form, and its operation if new, to the registry with an Intel SDM or AMD APM reference.
1. Add the form, and its operation if new, to the registry with an Intel SDM or AMD APM reference. A form that is one exact ModRM byte, not a whole digit, takes `register_only = true` and `rm = N`.
2. Run `python3 crates/loader/generate_x86.py generate`.
3. Implement the operation in `x86_exec.rs`. Leave flags the manuals call undefined unchanged.
4. Add assembly text to `crates/loader/tests/x86/assemble.py`, run it with `generate`, and extend the reference in `tests/x86_integer.rs` or `tests/x86_vector.rs`. A declared form without a fixture fails `every_declared_form_is_executed_by_a_fixture`.
@@ -68,6 +68,21 @@ MFENCE, LFENCE and SFENCE (`0F AE` with a register ModRM byte and digit 6, 5 or
This holds only while guest threads do not run on several host threads. ARM64 orders memory more weakly than x86, so an engine that ran guest threads in parallel would have to restore x86's ordering for ordinary accesses and give the fences a real effect. Nothing here provides or tests that. `tests/cpu_known_answers.rs` holds the single-thread cases: a store, a fence and a later load in program order, and no change to any other state. None of it has been compared with x86 hardware.
## x87 state and FNINIT
FNINIT (`DB E3`) is the only x87 instruction. It exists because the mingw-w64 C runtime runs it once before `main`, in `_fpreset`, and a program built with that runtime could not start without it.
`CpuState::x87` holds the control, status and tag words. FNINIT sets them to the values the Intel SDM gives (Vol. 2A, "FINIT/FNINIT"): control `037F` (every exception masked, 64-bit precision, round to nearest), status `0` and tag `FFFF` (every register empty). It changes nothing else, and both engines run the same shared code for it; nothing is lowered to ARM64. The host's floating-point state is never read or written.
What this does not include:
- **No other x87 instruction.** FNSTCW, FLDCW, FNCLEX, FWAIT (so FINIT, which is `9B DB E3`), every load, store and arithmetic form stay rejected. Nothing can read the three words back, so today they are only visible to a host that inspects `CpuState`.
- **No data registers.** FNINIT leaves them unchanged on a real processor and tags them empty; Xenora has none. The x87 instruction and data pointers and the last opcode, which FNINIT also clears, are not modelled either.
- **No operating-system start value.** A new `CpuState` holds the FNINIT values. An operating system may start a thread with a different control word, which is not modelled.
- **CPUID still reports no FPU.** One instruction of the feature is not the feature.
The registry key `rm = 3` makes the form match that one ModRM byte. The other register bytes of `DB /4` are different instructions (`DB E2` is FNCLEX), so the form cannot ignore the r/m field the way the fences do. `fninit_is_the_only_x87_encoding_accepted` in `tests/x86_integer.rs` tries every ModRM byte under the eight x87 opcodes, `D8` to `DF`, in both engines. A segment override or REX prefix before FNINIT is accepted and has no effect, as for other forms without operands. `prefixes_accepted_before_fninit_have_no_effect` pins that as a local rule; it was not derived from a manual statement. The 0x66, F2, F3 and LOCK prefixes are refused. Nothing here has been compared with x86 hardware.
## String instructions
MOVS and STOS exist for 8-, 16-, 32- and 64-bit elements, alone and with REP (F3), together with the direction flag and CLD and STD. `CpuState::df` holds the flag. It is not one of the six status flags the registry tracks.
@@ -94,7 +109,7 @@ CPUID (`0F A2`) returns a fixed table that never reads the host. It describes a
A feature bit is set only when every instruction of that feature is implemented. That is stricter than "some of it works", and it has consequences:
- SSE and SSE2 are not reported, although most of their instructions exist, because parts are still rejected: RSQRTPS and MASKMOVDQU, for example. BMI1 is not reported although TZCNT exists, because ANDN does not. The x87 FPU, MMX, FXSAVE, CMPXCHG8B, the time-stamp counter, LAHF and SYSRET are absent too.
- SSE and SSE2 are not reported, although most of their instructions exist, because parts are still rejected: RSQRTPS and MASKMOVDQU, for example. BMI1 is not reported although TZCNT exists, because ANDN does not. The x87 FPU is not reported although FNINIT exists. MMX, FXSAVE, CMPXCHG8B, the time-stamp counter, LAHF and SYSRET are absent too.
- The table is therefore truthful about BetterXen, not plausible as hardware: every real 64-bit processor reports the FPU and SSE2. A guest that tests a bit before using a feature avoids it; a guest that assumes SSE2 because it runs in 64-bit mode still gets every form that exists and an illegal-instruction exit for one that does not.
- A leaf that is not listed returns zeros, whatever the subleaf. Intel processors answer a leaf above the highest basic one with that leaf's data instead; software is expected to read the highest leaf first.
@@ -104,4 +119,4 @@ A feature bit is set only when every instruction of that feature is implemented.
## Rejected on purpose
LOCK except as described above, F2 or F3 where it is neither PAUSE nor part of a declared form, F2 combined with F3, address-size overrides, an ignored segment override after FS or GS, 16-bit stack and branch forms, 16-bit BSWAP and MOVSXD, bit tests of memory by a register index, LODS, CMPS, SCAS, REPE and REPNE, MMX, the RCP and RSQRT approximations, SSE3 and later, VEX, CMPXCHG8B and CMPXCHG16B. The DBT also refuses raw SYSCALL.
LOCK except as described above, F2 or F3 where it is neither PAUSE nor part of a declared form, F2 combined with F3, address-size overrides, an ignored segment override after FS or GS, 16-bit stack and branch forms, 16-bit BSWAP and MOVSXD, bit tests of memory by a register index, LODS, CMPS, SCAS, REPE and REPNE, every x87 instruction except FNINIT, MMX, the RCP and RSQRT approximations, SSE3 and later, VEX, CMPXCHG8B and CMPXCHG16B. The DBT also refuses raw SYSCALL.
+23
View File
@@ -75,6 +75,29 @@ class GenerateX86(unittest.TestCase):
self.rejects(self.form('op = "mov"\nopcode = 0xD7\nenc = "reg_rm"\nsize = "v"\nlock = true'), message)
self.rejects(self.form('op = "xadd"\nopcode = 0xD7\nenc = "rm_reg"\nsize = "v"\nregister_only = true\nlock = true'), message)
def test_a_fixed_rm_field_needs_a_register_only_digit_form(self):
base = 'op = "nop"\nopcode = 0xD9\nenc = "rm_unread"\nsize = "n"\n'
message = "needs register_only and a digit"
self.rejects(self.form(base + "digit = 0\nrm = 3"), message)
self.rejects(self.form(base + "digit = 0\nmemory_only = true\nrm = 3"), message)
self.rejects(self.form(base + "register_only = true\nrm = 3"), message)
for value in ("8", "-1", "true", '"3"'):
self.rejects(self.form(base + f"digit = 0\nregister_only = true\nrm = {value}"), "r/m field value 0-7")
# A second form on the same opcode and digit is an overlap, whatever its r/m field.
self.rejects(self.form('op = "nop"\nopcode = 0xDB\ndigit = 4\nenc = "rm_unread"\nsize = "n"\n'
"register_only = true\nrm = 2"), "overlapping")
# The valid shape loads, and the key reaches the generated table.
operations, forms = generate_x86.load(self.form(base + "digit = 0\nregister_only = true\nrm = 7"))
self.assertEqual([f["rm"] for f in forms if f["map"] == "1" and f["opcode"] == 0xD9], [7])
self.assertIn("register_only: true, fixed_rm: Some(7),", generate_x86.generate(operations, forms))
def test_fninit_is_the_only_form_with_a_fixed_rm_field_and_the_only_x87_form(self):
_, forms = generate_x86.load(REGISTRY)
fixed = [(f["op"], f["map"], f["opcode"], f["digit"], f["rm"]) for f in forms if f["rm"] is not None]
self.assertEqual(fixed, [("fninit", "1", 0xDB, 4, 3)])
x87 = [f["op"] for f in forms if f["map"] == "1" and 0xD8 <= f["opcode"] <= 0xDF]
self.assertEqual(x87, ["fninit"])
def test_only_xadd_and_cmpxchg_are_lockable(self):
_, forms = generate_x86.load(REGISTRY)
self.assertEqual({form["op"] for form in forms if form.get("lock")}, {"cmpxchg", "xadd"})