From fee956293dafd9bb6234bd0002e4c2ce3f238499 Mon Sep 17 00:00:00 2001 From: ates Date: Wed, 25 Nov 2026 07:52:19 +0300 Subject: [PATCH 01/15] Add the verified CPU/loader coverage map Document what the CPU and loader tests verify, per operation family, in docs/testing/cpu-coverage.md: the declared-form inventory (213 operations, 403 forms, 498 opcode slots from the validated registry), the per-operation engine split (93 native-lowered, 120 shared-semantic, with the conditional width and encoding gates), a per-artifact evidence table with exact pass counts from one full workspace gate run on Apple M5, the reconciliation of the eight operations covered by model tests instead of the assembly-fixture corpus, and a recorded note that three advisory qa cpu-inventory unsupported-catalog rows are stale against the implemented and tested forms. Also updates the docs/README.md description line and adds the CHANGELOG entry under [Unreleased]. Closes #154. Signed-off-by: ates --- CHANGELOG.md | 1 + docs/README.md | 2 +- docs/testing/cpu-coverage.md | 164 +++++++++++++++++++++++++++++++++-- 3 files changed, 161 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e407bd8..caf1e53 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -40,6 +40,7 @@ remains unsupported. - 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 +- Added a verified CPU/loader coverage map to `docs/testing/cpu-coverage.md` (#154): the declared-form inventory (213 operations, 403 forms, 498 opcode slots from the validated registry), the per-operation engine split (93 native-lowered, 120 shared-semantic, with the width and encoding gates that keep some forms on the helper path), a per-artifact evidence table with exact pass counts from one full `cargo test --locked --workspace` run on Apple M5 (971 passed, 0 failed, 35 ignored; ignored tests are Metal-gated, a manual timing profile or the known DBT self-modifying defect), the reconciliation of the eight operations covered by model tests rather than the assembly-fixture corpus, and a recorded note that the advisory `qa cpu-inventory` unsupported-catalog rows for RCL/RCR/SHLD/SHRD, string instructions and atomics/fences are stale against the implemented and tested forms. Local documentation evidence only; no runtime change; not independently reviewed. - 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. diff --git a/docs/README.md b/docs/README.md index 3f623cc..4fbccdc 100644 --- a/docs/README.md +++ b/docs/README.md @@ -48,7 +48,7 @@ Historical phase checkpoints retain their original evidence scope. - [Testing and acceptance index](testing/README.md) — Entry point for test procedures, evidence and review records. - [AMD RDNA2 desktop GPU (gfx1030) form acceptance](testing/shader-form-acceptance.md) — Independence, command, log and promotion rules for fixture-verified instruction forms. - [Engineering progress](progress.md) — Verification commands, metric definitions, and open release gates. -- [CPU test runtime and shard selection](testing/cpu-coverage.md) — Measured CPU gate cost and deterministic test-target shards. +- [CPU test runtime, shards and coverage map](testing/cpu-coverage.md) — Measured CPU gate cost, deterministic test-target shards, and a verified per-operation CPU/loader coverage map with exact test evidence. - [Test inventory comparison](testing/test-inventory.md) — Detect missing or newly ignored Cargo tests across commits. - [Persistent resource and translated rendering acceptance](testing/x9-acceptance.md) — Pinned upstream tests, native ARM64 results and unsupported cases. - [Baseline acceptance](testing/phase-02-baseline.md), [Phase 01 assurance](testing/phase01-assurance.md), and [independent reviews](testing/review-log.md) — Candidate-specific results and release findings. diff --git a/docs/testing/cpu-coverage.md b/docs/testing/cpu-coverage.md index 96b8558..7909776 100644 --- a/docs/testing/cpu-coverage.md +++ b/docs/testing/cpu-coverage.md @@ -1,9 +1,10 @@ -# CPU test runtime and shard selection +# CPU test runtime, shards and coverage map -This page records what the CPU test gate costs and describes -`scripts/cpu-tests.sh`, which splits that gate into deterministic shards. The -shards are a convenience for local iteration and parallel runners. They do not -replace any gate: `cargo test --locked --workspace` stays the full CPU gate, and +This page records what the CPU test gate costs, describes +`scripts/cpu-tests.sh`, which splits that gate into deterministic shards, and +maps which x86-64 and loader behavior the tests verify. The shards are a +convenience for local iteration and parallel runners. They do not replace any +gate: `cargo test --locked --workspace` stays the full CPU gate, and `scripts/test-gpu.sh` stays the GPU gate. ## What counts as a CPU test @@ -96,3 +97,156 @@ than the full gate, because each target pays Cargo start-up. different commits are not comparable. - The experiment workspace `experiments/x1` is outside the selection. CI runs it separately. + +# CPU and loader coverage map + +This map inventories what the CPU and loader tests verify, per operation +family, with the exact evidence commands and counts behind every number. It is +documentation of verified state, not a compatibility claim, and it contains no +percentages: every figure below is a count that a recorded command produced on +one machine. The behavioral rules behind the map (how forms are declared, what +"implemented" means, which forms are rejected on purpose) are documented in +[docs/cpu/instruction-registry.md](../cpu/instruction-registry.md) and are not +repeated here except where the map adds evidence. + +## Method and revision + +All commands ran on Apple M5, macOS 26.6.2, native arm64, Rust +`1.100.0-aarch64-apple-darwin` (the revision CI pins), `CARGO_BUILD_JOBS=2`, +one run, on the branch holding this change, based on upstream `main` at +`d26af53` (2026-11-25). Recorded evidence commands: + +```sh +python3 crates/loader/generate_x86.py validate # 213 operations, 403 forms, 498 opcode slots +python3 crates/loader/generate_x86.py --check # x86_table.rs is fresh +PYTHONPATH=scripts python3 -m qa cpu-inventory # advisory partitions, cross-checked below +cargo test --locked --workspace # 113 result lines: 971 passed, 0 failed, 35 ignored +``` + +The registry numbers are the generator's own count, not a hand count. The +advisory `qa cpu-inventory` output was cross-checked against the code before +use, and one stale row is called out under "Intentionally rejected forms". +Ignored tests are not passes; every ignore in the run is a Metal-gated test +(run by `scripts/test-gpu.sh`), a manual timing profile, or the one known DBT +defect test, named below. + +## Declared instruction inventory + +`crates/loader/x86/instructions.toml` declares the decodable x86-64 surface. +`generate_x86.py validate` reports **213 operations, 403 forms, 498 opcode +slots** at this revision. By opcode map the slots split 235 one-byte and 263 +`0F`; by mandatory prefix 352 none, 107 `66`, 16 `F2`, 23 `F3`; by operand size +96 byte (`b`), 139 variable 16/32/64 (`v`), 160 XMM 16-byte (`x`), 58 no +operand (`n`), 22 32/64-only (`y`), 23 64-bit (`q`). + +A declared form is decodable, not implemented. A form counts as supported only +when it has semantics and fixture evidence. The fixture half is enforced: +`every_declared_form_is_executed_by_a_fixture` in +`crates/loader/tests/x86_integer.rs` decodes every line of the three assembly +corpora (`tests/x86/integer.txt`, `vector.txt`, `float.txt`) and fails if any +declared form is never executed. It lists the operations that are covered +elsewhere instead (control flow and exits, `LDMXCSR`, and the +`MOVS`/`STOS`/`CLD`/`STD` string family, which need their own memory layout and +are covered form by form in `tests/cpu_rep.rs` and the loop tests). + +## Engine path per operation + +Every one of the 213 operations runs in exactly one primary path in the native +DBT: **93 are lowered to ARM64** by `is_native` in +`crates/loader/src/dbt.rs`, and **120 use the shared interpreter semantics** +through a helper call, counted in `DbtMetrics::interpreter_fallbacks`. +`SYSCALL` is decoded but the DBT refuses to translate it (`is_translatable`), +so it ends translated execution. The conditional gates inside `is_native` +matter when reading the split: + +- `ADD`, `SUB`, `CMP`, `AND`, `OR`, `XOR`, `TEST`, `INC`, `DEC`, `NEG`, `NOT` + and `CMOV` are native only at 32- and 64-bit width; 8- and 16-bit forms use + the shared semantics. +- `ADC` and `SBB` are native only for register and immediate operands; a memory + destination stays on the helper path. +- `BT` is native only in the `0F A3` register-index form; the `0F BA` + immediate-index form can write memory and stays on the helper path. +- `BSF` and `BSR` are native at 16/32/64-bit width. +- `POP` is native only in the opcode-register form. + +`tests/x86_integer.rs` asserts the split both ways for every fixture: native +forms must never call the helper, and helper forms always must. The interpreter +runs all 213 operations through the shared semantics. + +## Test evidence by artifact + +Counts are from the full gate run recorded above (target name, tests run, +passed/ignored). Expectation sources are named so independence can be judged. + +| Artifact (under `crates/loader/tests/`) | Expectations derived from | Run result | +| --- | --- | --- | +| `x86_integer.rs` + `x86/integer.txt` (1230 fixture lines) | LLVM-assembled encodings; byte-level references written from the SDM/APM operation text, independent of the production semantics | 16 passed, 0 failed | +| `x86_vector.rs` + `x86/vector.txt` (374 lines) | same method, SSE2 packed forms | 9 passed | +| `x86_float.rs` + `x86/float.txt` (172), `x86/float_vectors.txt` (6824), `x86/float_reference.py` | exact-fraction reference computed by script, following SDM Vol. 1 floating-point rules | 9 passed | +| `cpu_known_answers.rs` (50 tests, 1019 case lines) | Intel SDM and AMD APM sections cited per case; both engines run each case | 49 passed, 1 ignored | +| `movsxd.rs` | SDM operation text; modular arithmetic in the test; LLVM-assembled encodings | 9 passed | +| `x86_atomic.rs` | SDM LOCK/XADD/CMPXCHG rules; both compare outcomes, unaligned operands, faults | 5 passed | +| `x86_carry_chain.rs` | widening `u128`/`i128` reference arithmetic on 256-bit chains | 8 passed | +| `x86_prefix_length.rs` | SDM prefix and length rules | 8 passed | +| `cpu_loop.rs` | a loop-model reference over every count, match point and budget | 3 passed | +| `cpu_rep.rs` | a byte-array model over every MOVS/STOS form, direction and count, plus step accounting and faults | 7 passed | +| `cpu_features.rs` | CPUID feature-bit pairing per the SDM; each reported bit requires the feature's fixtures, each commonly-tested unreported bit requires a refused witness | 4 passed | +| `cpu_differential.rs` | interpreter and DBT must agree on shared fixtures | 5 passed | +| `arm64_encodings.rs` | LLVM encodings for the assembler's emitted ARM64 | 3 passed | +| `memory_page_boundaries.rs`, `memory_validation.rs` | mapping/permission/boundary contracts | 8 + 9 passed | +| `generated_conformance.rs`, `bootstrap.rs`, `gate_a1.rs`, `gate_a2.rs`, `indirect_control.rs`, `bswap.rs`, `dbt_render.rs`, `process_exit.rs` | per-file documented contracts (generated conformance vectors, startup gates, control flow) | all passed except one Metal-gated ignore in `dbt_render.rs` | + +The one ignore in `cpu_known_answers.rs` is +`defect_dbt_executes_modified_code_after_a_jump`, the known DBT defect that +keeps a translated block after the guest rewrites its code, tracked by issue +#79. It stays ignored at this revision until the cache-identity fix lands. The +loader package's remaining ignores in the run are Metal-gated tests (run by +`scripts/test-gpu.sh`) and one manual TLS timing profile; none is counted as a +pass. + +## Operations covered by model tests instead of the fixture corpus + +The mnemonic-level fixture scan behind the advisory +`PYTHONPATH=scripts python3 -m qa cpu-inventory` reports no assembly-text +fixture for eight operations: `cld`, `std`, `jrcxz`, `loop`, `loope`, +`loopne`, `movs`, `stos`. That is by design, not a gap: those operations need +their own memory layout or counter model and are covered form by form in +`tests/cpu_rep.rs` (MOVS/STOS/REP, the direction flag set by `STD` and cleared +by `CLD`) and `tests/cpu_loop.rs` (LOOP/LOOPE/LOOPNE, JRCXZ on zero RCX). The +declared-form enforcement test exempts exactly these families with a comment +saying so, and it still requires every other declared form to appear in the +corpora. + +## Intentionally rejected forms + +The rejection list with its scope rules (LOCK limited to the memory forms of +XADD and CMPXCHG, every x87 instruction except FNINIT, +LODS/CMPS/SCAS/REPE/REPNE, MMX, RCP/RSQRT approximations, SSE3 and later, +VEX, address-size overrides, 16-bit stack/branch forms, 16-bit BSWAP and +MOVSXD, bit tests of memory by register index, CMPXCHG8B/16B, and the DBT +refusing raw SYSCALL) is maintained in +[docs/cpu/instruction-registry.md](../cpu/instruction-registry.md) and is +tested by refusal cases inside the files above; this map does not duplicate it. + +One advisory-tool discrepancy is recorded for its owner: the hand-written +`unsupported_catalog` in `scripts/qa/cpu_inventory.py` lists "RCL/RCR/SHLD/ +SHRD", "string instructions" and "atomics/fences", which is stale against the +code and tests at this revision — RCL/RCR/SHLD/SHRD are declared registry +forms with implemented semantics (`x86_exec.rs`), 21 RCL and 16 SHLD/SHRD +known-answer cases, and 72 SHLD/SHRD assembly fixtures; MOVS/STOS and the +LOCK forms of XADD/CMPXCHG and the fences are supported within the documented +scope. The catalog is advisory only and does not feed any gate. + +## Map limitations + +- Every count is pinned to the revision, host and single run named above. +- The fixture evidence is mnemonic-level where it comes from the assembly + corpora: it proves every declared form executes somewhere, not that every + encoding variant of a form has its own expected-value case. The known-answer + files carry the per-case expectations; their case lines are counted, not + audited one by one here. +- The native/shared partition is read from `is_native` at this revision and + asserted by the fixtures; it is not a promise for other revisions. +- Nothing here was compared with x86 hardware, no compatibility percentage is + implied, and this is local documentation evidence, not independent + acceptance. From b40bbae1da9128955be31fcf26ef50b5eb8f3e8c Mon Sep 17 00:00:00 2001 From: ates Date: Wed, 25 Nov 2026 08:05:10 +0300 Subject: [PATCH 02/15] Refresh the coverage map at merged main b2654e9 The branch now contains main b2654e9, which includes the merged DBT cache-identity pull and the migration-benchmark checks, so the map pins its single gate run to that revision: the former self-modifying-code defect test executes and passes in both DBT engines (cpu_known_answers 50 passed, 0 ignored) and the workspace gate reports 116 result lines with 1015 passed, 0 failed and 34 ignored. The ignore taxonomy in the map names all three kinds from their own messages: Metal-gated, LLVM-gated (gfx1030 AMDGPU target) and manual timing runs. Signed-off-by: ates --- docs/testing/cpu-coverage.md | 52 ++++++++++++++++++++---------------- 1 file changed, 29 insertions(+), 23 deletions(-) diff --git a/docs/testing/cpu-coverage.md b/docs/testing/cpu-coverage.md index 650d4c8..236b004 100644 --- a/docs/testing/cpu-coverage.md +++ b/docs/testing/cpu-coverage.md @@ -113,22 +113,25 @@ repeated here except where the map adds evidence. All commands ran on Apple M5, macOS 26.6.2, native arm64, Rust `1.100.0-aarch64-apple-darwin` (the revision CI pins), `CARGO_BUILD_JOBS=2`, -in one run against source at `d26af53` (2026-11-25). The table below -preserves the counts from that revision. Recorded evidence commands: +one run, on the branch holding this change, based on upstream `main` at +`b2654e9` (2026-11-25, including the merged DBT cache-identity fix). +Recorded evidence commands: ```sh python3 crates/loader/generate_x86.py validate # 213 operations, 403 forms, 498 opcode slots python3 crates/loader/generate_x86.py --check # x86_table.rs is fresh PYTHONPATH=scripts python3 -m qa cpu-inventory # advisory partitions, cross-checked below -cargo test --locked --workspace # 113 result lines: 971 passed, 0 failed, 35 ignored +cargo test --locked --workspace # 116 result lines: 1015 passed, 0 failed, 34 ignored ``` The registry numbers are the generator's own count, not a hand count. The advisory `qa cpu-inventory` output was cross-checked against the code before use, and one stale row is called out under "Intentionally rejected forms". -Ignored tests are not passes; every ignore in the run is a Metal-gated test -(run by `scripts/test-gpu.sh`), a manual timing profile, or the one known DBT -defect test, named below. +Ignored tests are not passes; at this revision every ignore is one of three +kinds, each named by its own ignore message: a Metal-gated test (run by +`scripts/test-gpu.sh`), an LLVM-gated test (`requires LLVM with the gfx1030 +AMDGPU target`, five of them), or a manual timing/profile run that demands an +idle host (three of them). ## Declared instruction inventory @@ -151,21 +154,21 @@ are covered form by form in `tests/cpu_rep.rs` and the loop tests). ## Engine path per operation -Of the 213 declared operations, **93 have an ARM64 lowering** for at least -one form and **119 use the shared interpreter semantics for every translated -form**. Calls to those semantics count toward -`DbtMetrics::interpreter_fallbacks`. The remaining operation, `SYSCALL`, -decodes but `is_translatable` refuses it in the DBT. For operations with an -ARM64 lowering, `is_native` in `crates/loader/src/dbt.rs` applies these -form-specific rules: +Every one of the 213 operations runs in exactly one primary path in the native +DBT: **93 are lowered to ARM64** by `is_native` in +`crates/loader/src/dbt.rs`, and **120 use the shared interpreter semantics** +through a helper call, counted in `DbtMetrics::interpreter_fallbacks`. +`SYSCALL` is decoded but the DBT refuses to translate it (`is_translatable`), +so it ends translated execution. The conditional gates inside `is_native` +matter when reading the split: - `ADD`, `SUB`, `CMP`, `AND`, `OR`, `XOR`, `TEST`, `INC`, `DEC`, `NEG`, `NOT` and `CMOV` are native only at 32- and 64-bit width; 8- and 16-bit forms use the shared semantics. - `ADC` and `SBB` are native only for register and immediate operands; a memory destination stays on the helper path. -- `BT` is native only in the `0F A3` register-index form. The `0F BA /4` - immediate-index form uses the helper and can read a memory operand. +- `BT` is native only in the `0F A3` register-index form; the `0F BA` + immediate-index form can write memory and stays on the helper path. - `BSF` and `BSR` are native at 16/32/64-bit width. - `POP` is native only in the opcode-register form. @@ -183,7 +186,7 @@ passed/ignored). Expectation sources are named so independence can be judged. | `x86_integer.rs` + `x86/integer.txt` (1230 fixture lines) | LLVM-assembled encodings; byte-level references written from the SDM/APM operation text, independent of the production semantics | 16 passed, 0 failed | | `x86_vector.rs` + `x86/vector.txt` (374 lines) | same method, SSE2 packed forms | 9 passed | | `x86_float.rs` + `x86/float.txt` (172), `x86/float_vectors.txt` (6824), `x86/float_reference.py` | exact-fraction reference computed by script, following SDM Vol. 1 floating-point rules | 9 passed | -| `cpu_known_answers.rs` (50 tests, 1019 case lines) | Intel SDM and AMD APM sections cited per case; both engines run each case | 49 passed, 1 ignored | +| `cpu_known_answers.rs` (50 tests, 1019 case lines) | Intel SDM and AMD APM sections cited per case; both engines run each case | 50 passed, 0 ignored | | `movsxd.rs` | SDM operation text; modular arithmetic in the test; LLVM-assembled encodings | 9 passed | | `x86_atomic.rs` | SDM LOCK/XADD/CMPXCHG rules; both compare outcomes, unaligned operands, faults | 5 passed | | `x86_carry_chain.rs` | widening `u128`/`i128` reference arithmetic on 256-bit chains | 8 passed | @@ -196,13 +199,16 @@ passed/ignored). Expectation sources are named so independence can be judged. | `memory_page_boundaries.rs`, `memory_validation.rs` | mapping/permission/boundary contracts | 8 + 9 passed | | `generated_conformance.rs`, `bootstrap.rs`, `gate_a1.rs`, `gate_a2.rs`, `indirect_control.rs`, `bswap.rs`, `dbt_render.rs`, `process_exit.rs` | per-file documented contracts (generated conformance vectors, startup gates, control flow) | all passed except one Metal-gated ignore in `dbt_render.rs` | -At `d26af53`, the one ignore in `cpu_known_answers.rs` was -`defect_dbt_executes_modified_code_after_a_jump`, the known DBT defect that -kept a translated block after the guest rewrote its code. The cache -revalidation change in [PR #269](https://github.com/MacosPorters/betterxen/pull/269) -restored the test as `dbt_executes_modified_code_after_a_jump`. The other -loader ignores in the recorded run were Metal-gated tests and one manual TLS -timing profile. +The former defect test `defect_dbt_executes_modified_code_after_a_jump` — +`dbt_executes_modified_code_after_a_jump` since the fix — used to be the one +ignored test in `cpu_known_answers.rs`, recording that the DBT kept a stale +translation after the guest rewrites its code. The cache-identity change has +merged (issue #79, pull #269), and in this run the test executes and passes in +both DBT engines, so the target reports 50 passed and 0 ignored. The loader +package's +remaining ignores are the Metal-gated tests named above plus three manual +timing/profile runs (TLS template, relocation, warm data memory); none is +counted as a pass. ## Operations covered by model tests instead of the fixture corpus From d33a7c694173aae8e1ebc3b1c7f5c74cb68c6011 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Wed, 25 Nov 2026 00:23:04 -0500 Subject: [PATCH 03/15] Report trusted fixture startup progress Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 1 + crates/cli/src/runner.rs | 103 +++++++-- crates/cli/src/startup_report.rs | 342 +++++++++++++++++++++++++++++ crates/cli/tests/startup_report.rs | 65 ++++++ docs/interfaces.md | 23 ++ 5 files changed, 519 insertions(+), 15 deletions(-) create mode 100644 crates/cli/src/startup_report.rs create mode 100644 crates/cli/tests/startup_report.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index af426af..f0a2179 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,6 +42,7 @@ remains unsupported. - 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 +- Added opt-in `betterxen run --startup-report ` JSON diagnostics with the last observed startup stage, fixture verification outcome and preserved failure or termination detail (#255). - Recorded the migrated PR integration decisions, native verification and scope exclusions in the testing documentation. - Added `xenora-bench startup` (#178), which measures Metal startup in fresh processes and in repeated submissions within one process, phase by phase (launch, device and queue, translation, library, pipeline, diff --git a/crates/cli/src/runner.rs b/crates/cli/src/runner.rs index 45b2a4a..c2db69c 100644 --- a/crates/cli/src/runner.rs +++ b/crates/cli/src/runner.rs @@ -5,7 +5,7 @@ use std::ffi::OsString; use std::fs::{self, File}; use std::io::Read; use std::path::{Path, PathBuf}; -use std::process::{Command, ExitCode, Stdio}; +use std::process::{Child, Command, ExitCode, Stdio}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; @@ -16,6 +16,10 @@ use xenora_loader::{ use xenora_metal::NativeCompute; use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile_graphics}; +#[path = "startup_report.rs"] +mod startup_report; +use startup_report::{Events, Journal, Termination}; + const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/trusted-runner.exe"); const SERVICES_FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/runtime-services.exe"); const WALL_LIMIT: Duration = Duration::from_secs(15); @@ -27,7 +31,7 @@ const TICKET: u64 = 17; const DRAW_RESULT: u64 = 0x42; const EXTENT: [usize; 2] = [4, 3]; const EXPECTED_PIXEL: [u8; 4] = [255, 0, 0, 255]; -const USAGE: &str = "usage: betterxen run --pe --experimental [--trace] [--metal-hud] [--max-steps <1..=10000>]"; +const USAGE: &str = "usage: betterxen run --pe --experimental [--trace] [--metal-hud] [--max-steps <1..=10000>] [--startup-report ]"; struct Options { path: PathBuf, @@ -35,6 +39,8 @@ struct Options { worker: bool, trace: bool, hud: bool, + report: Option, + journal: Option, } impl Options { @@ -42,6 +48,8 @@ impl Options { let mut args = args.into_iter(); let mut path = None; let mut max_steps = None; + let mut report = None; + let mut journal = None; let (mut experimental, mut trace, mut hud, mut worker) = (false, false, false, false); while let Some(arg) = args.next() { match arg.to_str() { @@ -56,6 +64,16 @@ impl Options { .ok_or("--max-steps must be in 1..=10000")?, ); } + Some("--startup-report") if report.is_none() => { + report = Some(PathBuf::from( + args.next().ok_or("missing --startup-report path")?, + )); + } + Some("--startup-journal") if journal.is_none() => { + journal = Some(PathBuf::from( + args.next().ok_or("missing worker journal path")?, + )); + } Some("--experimental") if !experimental => experimental = true, Some("--trace") if !trace => trace = true, Some("--metal-hud") if !hud => hud = true, @@ -66,12 +84,17 @@ impl Options { if !experimental { return Err("run requires --experimental".into()); } + if (worker && report.is_some()) || (!worker && journal.is_some()) { + return Err("invalid startup report option for this process".into()); + } Ok(Self { path: path.ok_or("missing --pe path")?, max_steps: max_steps.unwrap_or(DEFAULT_STEPS), worker, trace, hud, + report, + journal, }) } } @@ -85,7 +108,7 @@ pub fn command(args: impl IntoIterator) -> ExitCode { } }; let result = if options.worker { - run_worker(&options).map(|()| ExitCode::SUCCESS) + worker_command(&options).map(|()| ExitCode::SUCCESS) } else { launch_worker(&options) }; @@ -99,8 +122,14 @@ pub fn command(args: impl IntoIterator) -> ExitCode { } fn launch_worker(options: &Options) -> Result> { + let journal = options + .report + .as_ref() + .map(|_| Journal::create()) + .transpose()?; let started = Instant::now(); - let mut child = Command::new(std::env::current_exe()?) + let mut command = Command::new(std::env::current_exe()?); + command .args([ "run", "--experimental", @@ -112,29 +141,55 @@ fn launch_worker(options: &Options) -> Result> { .arg(options.max_steps.to_string()) .arg("--pe") .arg(&options.path) - .stdin(Stdio::null()) - .spawn()?; + .stdin(Stdio::null()); + if let Some(journal) = &journal { + command.arg("--startup-journal").arg(journal.path()); + } + let termination = command + .spawn() + .and_then(|child| supervise(child, started, WALL_LIMIT)); + if let (Some(journal), Some(path)) = (&journal, &options.report) { + journal + .finish(path, &termination) + .map_err(|error| format!("could not write startup report: {error}"))?; + } + match termination? { + Termination::Exited(status) => match status.code() { + Some(code) => Ok(ExitCode::from(u8::try_from(code)?)), + None => Err(format!("worker terminated: {status}").into()), + }, + Termination::Deadline => { + Err("experimental worker exceeded its 15 second wall deadline".into()) + } + } +} + +fn supervise(mut child: Child, started: Instant, limit: Duration) -> std::io::Result { loop { match child.try_wait() { - Ok(Some(status)) => { - return match status.code() { - Some(code) => Ok(ExitCode::from(u8::try_from(code)?)), - None => Err(format!("worker terminated: {status}").into()), - }; - } - Ok(None) if started.elapsed() < WALL_LIMIT => { + Ok(Some(status)) => return Ok(Termination::Exited(status)), + Ok(None) if started.elapsed() < limit => { std::thread::sleep(Duration::from_millis(10)); } status => { let _ = child.kill(); child.wait()?; status?; - return Err("experimental worker exceeded its 15 second wall deadline".into()); + return Ok(Termination::Deadline); } } } } +fn worker_command(options: &Options) -> Result<(), Box> { + let mut events = options.journal.as_deref().map(Events::open).transpose()?; + let result = run_worker(options, events.as_mut()); + if let (Some(events), Err(error)) = (events.as_mut(), &result) { + events.failure(error.as_ref()); + } + result +} + fn verify_fixture(path: &Path) -> Result<&'static [u8], Box> { let valid_metadata = |metadata: fs::Metadata| metadata.is_file() && metadata.len() == FIXTURE.len() as u64; @@ -158,7 +213,7 @@ fn verify_fixture(path: &Path) -> Result<&'static [u8], Box> { .ok_or_else(|| rejection.into()) } -fn run_worker(options: &Options) -> Result<(), Box> { +fn run_worker(options: &Options, mut events: Option<&mut Events>) -> Result<(), Box> { std::thread::Builder::new() .name("xenora-deadline".into()) .spawn(|| { @@ -232,6 +287,16 @@ fn run_worker(options: &Options) -> Result<(), Box> { imports, options.max_steps, |event| { + if let Some(events) = events.as_deref_mut() { + events.stage(match &event { + StartupEvent::Parsed { .. } => "parsed", + StartupEvent::Mapped { .. } => "mapped", + StartupEvent::Relocated { .. } => "relocated", + StartupEvent::ImportsBound { .. } => "imports_bound", + StartupEvent::TlsCompleted { .. } => "tls_completed", + StartupEvent::Entering { .. } => "entry", + }); + } if options.trace { trace_startup(event); } @@ -244,6 +309,11 @@ fn run_worker(options: &Options) -> Result<(), Box> { .take(); let exit = startup.execution.exit_reason; let rax = startup.execution.final_state.get(Register::Rax); + if exit == ExitReason::Halt + && let Some(events) = events.as_deref_mut() + { + events.stage("exit"); + } if options.trace { println!( "trace stage=exit entry_steps={} exit={exit:?} rax={rax:#x}", @@ -264,6 +334,9 @@ fn run_worker(options: &Options) -> Result<(), Box> { return Err("trusted fixture startup or result differs from the expected values".into()); } let frame = result.ok_or("guest halted without a draw")??; + if let Some(events) = events { + events.stage("framebuffer"); + } if options.trace { println!( "trace stage=framebuffer extent={}x{} verified_pixels={}", diff --git a/crates/cli/src/startup_report.rs b/crates/cli/src/startup_report.rs new file mode 100644 index 0000000..960ee5e --- /dev/null +++ b/crates/cli/src/startup_report.rs @@ -0,0 +1,342 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +use std::fmt::Write as _; +use std::fs::{self, File, OpenOptions}; +use std::io::{self, Read, Write}; +use std::os::unix::fs::DirBuilderExt; +use std::path::{Path, PathBuf}; +use std::process::ExitStatus; +use std::sync::atomic::{AtomicUsize, Ordering}; + +const VERSION: &str = "1"; +const RECORD_SEPARATOR: char = '\t'; +const MAX_BYTES: usize = 8192; +const MAX_ERROR_BYTES: usize = 2048; +const STAGES: [&str; 8] = [ + "parsed", + "mapped", + "relocated", + "imports_bound", + "tls_completed", + "entry", + "exit", + "framebuffer", +]; + +pub(super) struct Journal(PathBuf); + +impl Journal { + pub(super) fn create() -> io::Result { + static NEXT: AtomicUsize = AtomicUsize::new(0); + loop { + let id = NEXT.fetch_add(1, Ordering::Relaxed); + let directory = + std::env::temp_dir().join(format!("betterxen-startup-{}-{id}", std::process::id())); + match fs::DirBuilder::new().mode(0o700).create(&directory) { + Ok(()) => return Ok(Self(directory)), + Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue, + Err(error) => return Err(error), + } + } + } + + pub(super) fn path(&self) -> PathBuf { + self.0.join("events") + } + + fn read(&self) -> Report { + let mut bytes = Vec::new(); + match File::open(self.path()) + .and_then(|file| file.take((MAX_BYTES + 1) as u64).read_to_end(&mut bytes)) + { + Ok(_) => Report::parse(&bytes), + Err(error) if error.kind() == io::ErrorKind::NotFound => Report::default(), + Err(_) => Report { + integrity: "unreadable", + ..Report::default() + }, + } + } + + pub(super) fn finish( + &self, + path: &Path, + termination: &io::Result, + ) -> io::Result<()> { + let report = self.read().json(termination); + OpenOptions::new() + .write(true) + .create_new(true) + .open(path)? + .write_all(report.as_bytes()) + } +} + +impl Drop for Journal { + fn drop(&mut self) { + let _ = fs::remove_file(self.path()); + let _ = fs::remove_dir(&self.0); + } +} + +pub(super) struct Events(File); + +impl Events { + pub(super) fn open(path: &Path) -> io::Result { + OpenOptions::new() + .write(true) + .create_new(true) + .open(path) + .map(Self) + } + + pub(super) fn stage(&mut self, stage: &str) { + let _ = writeln!(self.0, "{VERSION}\t{stage}"); + } + + pub(super) fn failure(&mut self, error: &dyn std::error::Error) { + let message = error.to_string(); + let end = message.floor_char_boundary(MAX_ERROR_BYTES); + let mut encoded = String::with_capacity(end * 2); + for byte in message[..end].bytes() { + write!(encoded, "{byte:02x}").unwrap(); + } + let _ = writeln!( + self.0, + "{VERSION}\tfailure\t{}\t{encoded}", + u8::from(end < message.len()) + ); + } +} + +pub(super) enum Termination { + Exited(ExitStatus), + Deadline, +} + +struct Report { + completed: usize, + error: Option, + error_truncated: bool, + integrity: &'static str, +} + +impl Default for Report { + fn default() -> Self { + Self { + completed: 0, + error: None, + error_truncated: false, + integrity: "complete", + } + } +} + +impl Report { + fn parse(bytes: &[u8]) -> Self { + let mut report = Self::default(); + let bounded = &bytes[..bytes.len().min(MAX_BYTES)]; + for line in bounded.split_inclusive(|&byte| byte == b'\n') { + let Some(line) = line.strip_suffix(b"\n") else { + report.integrity = "truncated"; + break; + }; + if !std::str::from_utf8(line).is_ok_and(|line| report.record(line)) { + report.integrity = "malformed"; + break; + } + } + if bytes.len() > MAX_BYTES { + report.integrity = "oversized"; + } + report + } + + fn record(&mut self, line: &str) -> bool { + let Some((VERSION, record)) = line.split_once(RECORD_SEPARATOR) else { + return false; + }; + if self.error.is_some() || self.completed == STAGES.len() { + return false; + } + if STAGES.get(self.completed) == Some(&record) { + self.completed += 1; + return true; + } + let Some((truncated, encoded)) = record + .strip_prefix("failure\t") + .and_then(|s| s.split_once('\t')) + else { + return false; + }; + if !matches!(truncated, "0" | "1") + || encoded.len() > MAX_ERROR_BYTES * 2 + || !encoded.len().is_multiple_of(2) + || !encoded.bytes().all(|byte| byte.is_ascii_hexdigit()) + { + return false; + } + let (pairs, _) = encoded.as_bytes().as_chunks::<2>(); + let Some(message) = pairs + .iter() + .map(|pair| u8::from_str_radix(std::str::from_utf8(pair).ok()?, 16).ok()) + .collect::>>() + .and_then(|bytes| String::from_utf8(bytes).ok()) + else { + return false; + }; + self.error = Some(message); + self.error_truncated = truncated == "1"; + true + } + + fn json(&self, termination: &io::Result) -> String { + let (outcome, status, detail) = match termination { + Ok(Termination::Deadline) => ( + "timeout", + None, + Some("worker exceeded the wall deadline".into()), + ), + Err(error) => ("unknown", None, Some(error.to_string())), + Ok(Termination::Exited(status)) if status.code() == Some(124) => ( + "timeout", + Some(status), + Some("worker watchdog expired".into()), + ), + Ok(Termination::Exited(status)) + if status.success() + && self.completed == STAGES.len() + && self.integrity == "complete" => + { + ("verified", Some(status), None) + } + Ok(Termination::Exited(status)) if !status.success() && self.error.is_some() => { + ("stage_failure", Some(status), None) + } + Ok(Termination::Exited(status)) if status.code().is_some() && !status.success() => { + ("early_exit", Some(status), Some(status.to_string())) + } + Ok(Termination::Exited(status)) => ("unknown", Some(status), Some(status.to_string())), + }; + let stages = &STAGES[..self.completed]; + let records = stages + .iter() + .map(|stage| format!(r#"{{"schema_version":{VERSION},"stage":"{stage}"}}"#)) + .collect::>() + .join(","); + let last = json_string(stages.last().copied()); + let error = json_string(self.error.as_deref()); + let detail = json_string(detail.as_deref()); + let code = status + .and_then(|status| status.code()) + .map_or("null".into(), |code| code.to_string()); + format!( + "{{\"schema_version\":{VERSION},\"outcome\":\"{outcome}\",\"last_completed_stage\":{last},\"record_integrity\":\"{}\",\"worker_exit_code\":{code},\"termination_detail\":{detail},\"error\":{error},\"error_truncated\":{},\"stages\":[{records}]}}\n", + self.integrity, self.error_truncated + ) + } +} + +fn json_string(value: Option<&str>) -> String { + let Some(value) = value else { + return String::from("null"); + }; + let mut escaped = String::from("\""); + for ch in value.chars() { + match ch { + '"' => escaped.push_str("\\\""), + '\\' => escaped.push_str("\\\\"), + '\0'..='\u{1f}' => write!(escaped, "\\u{:04x}", u32::from(ch)).unwrap(), + _ => escaped.push(ch), + } + } + escaped.push('"'); + escaped +} + +#[cfg(test)] +mod tests { + use super::*; + use std::process::Command; + use std::time::{Duration, Instant}; + + #[test] + fn supervisor_distinguishes_early_exit_watchdog_signal_and_deadline() { + for (script, limit, outcome, code) in [ + ("exit 9", Duration::from_secs(2), "early_exit", "9"), + ("exit 124", Duration::from_secs(2), "timeout", "124"), + ("kill -TERM $$", Duration::from_secs(2), "unknown", "null"), + ( + "exec sleep 5", + Duration::from_millis(250), + "timeout", + "null", + ), + ] { + let journal = Journal::create().unwrap(); + let started = Instant::now(); + let child = Command::new("/bin/sh") + .args([ + "-c", + &format!("printf '1\\tparsed\\n' > \"$1\"; {script}"), + "worker", + ]) + .arg(journal.path()) + .spawn() + .unwrap(); + let termination = super::super::supervise(child, started, limit); + let report = journal.read().json(&termination); + assert!( + report.contains(&format!(r#""outcome":"{outcome}""#)), + "{report}" + ); + assert!( + report.contains(&format!(r#""worker_exit_code":{code}"#)), + "{report}" + ); + assert!( + report.contains(r#""last_completed_stage":"parsed""#), + "{report}" + ); + } + } + + #[test] + fn invalid_records_keep_only_the_valid_prefix() { + let mut oversized = b"1\tparsed\n1\tmapped".to_vec(); + oversized.resize(MAX_BYTES + 1, b'x'); + for (bytes, integrity) in [ + (&b"1\tparsed\n1\tmapped"[..], "truncated"), + (&b"1\tparsed\n1\tentry\n1\tmapped\n"[..], "malformed"), + (&b"1\tparsed\n1\tfailure\t0\tqq\n"[..], "malformed"), + (oversized.as_slice(), "oversized"), + ] { + let journal = Journal::create().unwrap(); + fs::write(journal.path(), bytes).unwrap(); + let report = journal.read(); + assert_eq!(report.completed, 1); + assert_eq!(report.integrity, integrity); + assert!(report.error.is_none()); + } + } + + #[test] + fn failure_preserves_original_context_with_bounded_utf8() { + let journal = Journal::create().unwrap(); + let mut events = Events::open(&journal.path()).unwrap(); + events.stage("parsed"); + let message = format!("line\nwith \"quote\" and \\{}", "é".repeat(MAX_ERROR_BYTES)); + events.failure(&io::Error::other(&message[..])); + let report = journal.read(); + assert_eq!( + report.error.as_deref(), + Some(&message[..message.floor_char_boundary(MAX_ERROR_BYTES)]) + ); + assert!(report.error_truncated); + let json = report.json(&Ok(Termination::Deadline)); + assert!( + json.contains(r#"line\u000awith \"quote\" and \\"#), + "{json}" + ); + } +} diff --git a/crates/cli/tests/startup_report.rs b/crates/cli/tests/startup_report.rs new file mode 100644 index 0000000..058f902 --- /dev/null +++ b/crates/cli/tests/startup_report.rs @@ -0,0 +1,65 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +use std::process::Command; + +#[test] +fn trusted_fixture_reports_verified_progress_and_step_failure() { + let folder = std::env::temp_dir().join(format!("betterxen-report-test-{}", std::process::id())); + std::fs::create_dir(&folder).unwrap(); + let fixture = concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../fixtures/pe/trusted-runner.exe" + ); + for (steps, outcome, last, success) in [ + ("100", "verified", "framebuffer", true), + ("1", "stage_failure", "entry", false), + ] { + let path = folder.join(steps); + let output = Command::new(env!("CARGO_BIN_EXE_betterxen")) + .args([ + "run", + "--experimental", + "--pe", + fixture, + "--max-steps", + steps, + "--startup-report", + ]) + .arg(&path) + .output() + .unwrap(); + let report = std::fs::read_to_string(&path); + assert_eq!(output.status.success(), success, "{output:?}, {report:?}"); + let report = report.unwrap(); + assert!( + report.contains(&format!(r#""outcome":"{outcome}""#)), + "{report}" + ); + assert!( + report.contains(&format!(r#""last_completed_stage":"{last}""#)), + "{report}" + ); + assert!(report.contains(r#""schema_version":1"#), "{report}"); + let mut remaining = report.as_str(); + for stage in [ + "parsed", + "mapped", + "relocated", + "imports_bound", + "tls_completed", + "entry", + ] { + remaining = remaining + .split_once(&format!(r#""stage":"{stage}""#)) + .unwrap() + .1; + } + if success { + assert!(remaining.contains(r#""stage":"exit""#)); + assert!(remaining.contains(r#""stage":"framebuffer""#)); + } else { + assert!(report.contains("step budget exhausted"), "{report}"); + } + } + std::fs::remove_dir_all(folder).unwrap(); +} diff --git a/docs/interfaces.md b/docs/interfaces.md index bee1b6a..7e0990e 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -141,6 +141,29 @@ pages count toward the 256 MiB mapping budget of one image, which is checked before anything is mapped. `ParsedPe::parse` does not make these checks, so static inspection of a file is unchanged. +`betterxen run --experimental --pe --startup-report ` +writes a versioned JSON summary after the worker stops. The path must be new. +The report is optional and uses the same exact-byte fixture admission, startup +observer and wall deadline as an ordinary run. + +Schema version 1 lists the observed stages in order in `stages` and copies +the last valid stage to `last_completed_stage` (null if none). The order is +`parsed`, `mapped`, `relocated`, `imports_bound`, `tls_completed`, `entry`, +`exit`, and `framebuffer`. `entry` records the handoff to guest entry. +`exit` records the fixture halt, and `framebuffer` records verification of its +offscreen readback. The supervisor reports an `outcome` of `verified`, +`stage_failure`, `early_exit`, `timeout`, or `unknown`. It includes the +worker exit code when available, termination detail when applicable, and the +original reported error when available. Errors are capped at 2 KiB of UTF-8 +and carry an `error_truncated` flag. + +The supervisor reads at most 8 KiB plus one byte from the worker journal. +`record_integrity` reports `complete`, `truncated`, `malformed`, `oversized` +or `unreadable`. Only the valid ordered prefix counts toward progress. A +complete journal may still contain only a partial startup if the worker +stopped between records. These records describe runtime observations from +the trusted fixtures. + `betterxen probe --mode static` inventories ordinary and delay-loaded PE imports without guest execution. Without `--report` it writes to `diagnostics/probe`, where `betterxen imports sync` also looks. `missing_imports.csv` lists unresolved ordinary keys From e4ddb05a1a0ce5d7c9b282d011594c2459dbb1b1 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Wed, 25 Nov 2026 00:27:42 -0500 Subject: [PATCH 04/15] Run startup draw check on native Metal hardware Signed-off-by: Adeeb Rahman --- crates/cli/tests/startup_report.rs | 122 ++++++++++++++++------------- 1 file changed, 68 insertions(+), 54 deletions(-) diff --git a/crates/cli/tests/startup_report.rs b/crates/cli/tests/startup_report.rs index 058f902..983c21c 100644 --- a/crates/cli/tests/startup_report.rs +++ b/crates/cli/tests/startup_report.rs @@ -2,64 +2,78 @@ use std::process::Command; +const STARTUP_STAGES: &[&str] = &[ + "parsed", + "mapped", + "relocated", + "imports_bound", + "tls_completed", + "entry", +]; + #[test] -fn trusted_fixture_reports_verified_progress_and_step_failure() { - let folder = std::env::temp_dir().join(format!("betterxen-report-test-{}", std::process::id())); - std::fs::create_dir(&folder).unwrap(); +fn trusted_fixture_preserves_step_failure() { + let report = run_fixture("1", false); + assert!(report.contains(r#""outcome":"stage_failure""#), "{report}"); + assert!( + report.contains(r#""last_completed_stage":"entry""#), + "{report}" + ); + assert!(report.contains("step budget exhausted"), "{report}"); + assert_stages(&report, STARTUP_STAGES); + assert!(!report.contains(r#""stage":"exit""#), "{report}"); +} + +#[test] +#[ignore = "requires a native Metal device with Apple family 7 capabilities"] +fn trusted_fixture_reports_verified_progress() { + let report = run_fixture("100", true); + assert!(report.contains(r#""outcome":"verified""#), "{report}"); + assert!( + report.contains(r#""last_completed_stage":"framebuffer""#), + "{report}" + ); + let stages = [STARTUP_STAGES, &["exit", "framebuffer"]].concat(); + assert_stages(&report, &stages); +} + +fn run_fixture(steps: &str, success: bool) -> String { + let path = std::env::temp_dir().join(format!( + "betterxen-report-test-{}-{steps}.json", + std::process::id() + )); let fixture = concat!( env!("CARGO_MANIFEST_DIR"), "/../../fixtures/pe/trusted-runner.exe" ); - for (steps, outcome, last, success) in [ - ("100", "verified", "framebuffer", true), - ("1", "stage_failure", "entry", false), - ] { - let path = folder.join(steps); - let output = Command::new(env!("CARGO_BIN_EXE_betterxen")) - .args([ - "run", - "--experimental", - "--pe", - fixture, - "--max-steps", - steps, - "--startup-report", - ]) - .arg(&path) - .output() - .unwrap(); - let report = std::fs::read_to_string(&path); - assert_eq!(output.status.success(), success, "{output:?}, {report:?}"); - let report = report.unwrap(); - assert!( - report.contains(&format!(r#""outcome":"{outcome}""#)), - "{report}" - ); - assert!( - report.contains(&format!(r#""last_completed_stage":"{last}""#)), - "{report}" - ); - assert!(report.contains(r#""schema_version":1"#), "{report}"); - let mut remaining = report.as_str(); - for stage in [ - "parsed", - "mapped", - "relocated", - "imports_bound", - "tls_completed", - "entry", - ] { - remaining = remaining - .split_once(&format!(r#""stage":"{stage}""#)) - .unwrap() - .1; - } - if success { - assert!(remaining.contains(r#""stage":"exit""#)); - assert!(remaining.contains(r#""stage":"framebuffer""#)); - } else { - assert!(report.contains("step budget exhausted"), "{report}"); - } + let output = Command::new(env!("CARGO_BIN_EXE_betterxen")) + .args([ + "run", + "--experimental", + "--pe", + fixture, + "--max-steps", + steps, + "--startup-report", + ]) + .arg(&path) + .output() + .unwrap(); + let report = std::fs::read_to_string(&path); + if report.is_ok() { + std::fs::remove_file(&path).unwrap(); + } + assert_eq!(output.status.success(), success, "{output:?}, {report:?}"); + report.unwrap() +} + +fn assert_stages(report: &str, stages: &[&str]) { + assert!(report.contains(r#""schema_version":1"#), "{report}"); + let mut remaining = report; + for stage in stages { + remaining = remaining + .split_once(&format!(r#""stage":"{stage}""#)) + .unwrap() + .1; } - std::fs::remove_dir_all(folder).unwrap(); } From 1ea898b4bf00318d73776ba84631c8b69e812dfc Mon Sep 17 00:00:00 2001 From: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:53:00 -0300 Subject: [PATCH 05/15] app: keep inspection results tied to the latest selection (#251) InspectionModel.inspect started a detached read per call and published status, report and busy whenever any of them finished. A slow first inspection that completed after a fast second one replaced the newer report and status, and could clear busy while the newer read was still running. - Each inspect call takes a request number; a completion is applied only while it is still the latest, so stale success and stale failure are discarded. Picker, drag and drop and Finder Open With all go through inspect and share this. - A new selection clears the previous report, and a failed inspection of the latest file is shown in red above its report. - The read is unchanged: size checked before reading, balanced security-scoped access, nothing executed. The reader is injectable only for the smoke check. - --smoke-inspection-order drives the model with an injected slow and fast reader: slow then fast with either outcome, and busy held for the newer request while an older read finishes. scripts/build-app.sh runs it after --smoke. All four checks fail without the change. Ported from XenoraOSS/Xenora#423. Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com> --- CHANGELOG.md | 1 + app/Sources/Xenora/main.swift | 73 ++++++++++++++++++++++++++++++++++- scripts/build-app.sh | 1 + 3 files changed, 74 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 78da0a4..aaff069 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,7 @@ remains unsupported. - Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits. ### Fixed +- Fixed the app's executable inspector so a late result from an earlier selection can no longer replace a newer one (#251). Each selection from the file picker, drag and drop or Finder Open With now takes a request number, and only the latest request may publish its report and status or clear the busy state. The previous report is cleared when a new file is chosen, and a failed inspection of the latest file is shown in red above its report. The read itself is unchanged: size checked before reading, balanced security-scoped access, nothing executed. `BetterXen --smoke-inspection-order`, run by `scripts/build-app.sh`, drives the model with an injected slow and fast reader and checks a stale success, a stale failure and a busy state held for the newer request; all four checks fail without the change. Checked locally on Apple Silicon; not yet independently reviewed. - Restored the DBT benchmark report-test fixture after the cache-invalidation counter was added. Its existing percentile, JSON and comparison tests now run in ordinary workspace CI instead of requiring a separate benchmark test-harness command. - DBT cache hits now compare an executable-generation token instead of rereading every instruction byte. Address-space or executable-memory changes trigger byte and execute-permission revalidation before a translation can be reused; changed code is retranslated. Ordinary data writes retain the fast path. Tests cover cloned spaces, loader bypass writes, split writes, remapping and bounded cache exhaustion. Same-dispatch self-modification and discarded-code reclamation remain unsupported. - Gate A2 checks the cross-compiler driver before invoking it, then checks its helpers before fixture compilation. CI also verifies the driver architecture before requesting its version. diff --git a/app/Sources/Xenora/main.swift b/app/Sources/Xenora/main.swift index 9ab6667..ddba3d4 100644 --- a/app/Sources/Xenora/main.swift +++ b/app/Sources/Xenora/main.swift @@ -640,11 +640,31 @@ final class InspectionModel: ObservableObject { @Published var busy = false @Published var importing = false + /// Reads and reports one file off the main thread. Replaceable only for the + /// `--smoke-inspection-order` check. + private let reader: @Sendable (URL) -> (Int32, String) + /// Number of the latest `inspect` call. Only that call may publish a result. + private var latestRequest: UInt64 = 0 + + init(reader: @escaping @Sendable (URL) -> (Int32, String) = InspectionModel.run) { + self.reader = reader + } + + var failed: Bool { !busy && fileName != nil && status != Int32(XENORA_OK) } + func inspect(_ url: URL) { + latestRequest &+= 1 + let request = latestRequest fileName = url.lastPathComponent + report = "" + status = Int32(XENORA_OK) busy = true + let reader = reader Task { - let (newStatus, newReport) = await Task.detached { InspectionModel.run(url) }.value + let (newStatus, newReport) = await Task.detached { reader(url) }.value + // A newer selection owns the published state, including `busy`; + // an older read that finishes late is discarded. + guard request == latestRequest else { return } status = newStatus report = newReport busy = false @@ -696,6 +716,10 @@ struct InspectorView: View { } if let name = model.fileName { LabeledContent("File", value: model.busy ? "\(name) (inspecting…)" : name) + if model.failed { + Text("Inspection of \(name) failed (status \(model.status)).") + .foregroundStyle(.red) + } ScrollView { Text(model.report) .font(.system(.caption, design: .monospaced)) @@ -1009,6 +1033,53 @@ if CommandLine.arguments.contains("--smoke-frame") { exit(frame.status == XENORA_OK ? 0 : 1) } +// `--smoke-inspection-order` checks that only the latest selection publishes an +// inspection result. Files are never read: an injected reader answers after a delay +// named by the file. It needs no GPU. +if CommandLine.arguments.contains("--smoke-inspection-order") { + let reader: @Sendable (URL) -> (Int32, String) = { url in + // "--" + let parts = url.lastPathComponent.split(separator: "-") + Thread.sleep(forTimeInterval: Double(parts[0])! / 1000) + let status = parts[1] == "ok" ? Int32(XENORA_OK) : Int32(XENORA_INVALID_ARGUMENT) + return (status, "report \(url.lastPathComponent)") + } + func file(_ name: String) -> URL { URL(fileURLWithPath: "/nonexistent/\(name)") } + func pause(_ ms: UInt64) async { try? await Task.sleep(nanoseconds: ms * 1_000_000) } + + Task { @MainActor in + var failures: [String] = [] + @MainActor func expect(_ model: InspectionModel, _ name: String, busy: Bool, report: String, ok: Bool, _ label: String) { + let actual = "file=\(model.fileName ?? "-") busy=\(model.busy) status=\(model.status) report=\(model.report)" + if model.fileName != name || model.busy != busy || model.report != report + || (model.status == Int32(XENORA_OK)) != ok { + failures.append("\(label): \(actual)") + } + } + // A slow first read finishing after a fast second one, with either outcome. + for (first, second, ok) in [("400-ok-a", "0-ok-b", true), ("400-fail-a", "0-ok-b", true), + ("400-ok-a", "0-fail-b", false)] { + let model = InspectionModel(reader: reader) + model.inspect(file(first)) + model.inspect(file(second)) + await pause(700) + expect(model, second, busy: false, report: "report \(second)", ok: ok, "\(first) then \(second)") + } + // An older read that finishes first must not clear the newer request's busy state. + let model = InspectionModel(reader: reader) + model.inspect(file("100-ok-a")) + model.inspect(file("500-fail-b")) + await pause(300) + expect(model, "500-fail-b", busy: true, report: "", ok: true, "while the newer read runs") + await pause(500) + expect(model, "500-fail-b", busy: false, report: "report 500-fail-b", ok: false, "after the newer read") + for failure in failures { print("smoke-inspection-order: FAILED \(failure)") } + print("smoke-inspection-order: \(failures.isEmpty ? "ok" : "\(failures.count) failed")") + exit(failures.isEmpty ? 0 : 1) + } + dispatchMain() +} + // `--smoke` prints the probe and exits without opening a window, for scripts and CI. if CommandLine.arguments.contains("--smoke") { let probe = RuntimeProbe.run() diff --git a/scripts/build-app.sh b/scripts/build-app.sh index e5e16a7..03e58e3 100755 --- a/scripts/build-app.sh +++ b/scripts/build-app.sh @@ -72,4 +72,5 @@ for dependency in $dependencies; do esac done "$binary" --smoke +"$binary" --smoke-inspection-order echo "build-app: built $bundle" From ae804f0530cb933845d6ed5cb915bcaf2b78d277 Mon Sep 17 00:00:00 2001 From: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:13:23 -0300 Subject: [PATCH 06/15] app: gate the inspection-order smoke check instead of sleeping (#251) Review follow-up. The check used fixed 300/700 ms pauses, so on a loaded host a late stale read could arrive after an assertion, or the newer read could finish before the busy-state check. The injected reader now blocks until the check releases that file, and the check waits on InspectionModel.finishedReads, which counts every finished read whether it was published or discarded. A five-second deadline bounds the wait without deciding the order. Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com> --- CHANGELOG.md | 2 +- app/Sources/Xenora/main.swift | 88 ++++++++++++++++++++++++++--------- 2 files changed, 67 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index aaff069..3725e7f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,7 +41,7 @@ remains unsupported. - Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits. ### Fixed -- Fixed the app's executable inspector so a late result from an earlier selection can no longer replace a newer one (#251). Each selection from the file picker, drag and drop or Finder Open With now takes a request number, and only the latest request may publish its report and status or clear the busy state. The previous report is cleared when a new file is chosen, and a failed inspection of the latest file is shown in red above its report. The read itself is unchanged: size checked before reading, balanced security-scoped access, nothing executed. `BetterXen --smoke-inspection-order`, run by `scripts/build-app.sh`, drives the model with an injected slow and fast reader and checks a stale success, a stale failure and a busy state held for the newer request; all four checks fail without the change. Checked locally on Apple Silicon; not yet independently reviewed. +- Fixed the app's executable inspector so a late result from an earlier selection can no longer replace a newer one (#251). Each selection from the file picker, drag and drop or Finder Open With now takes a request number, and only the latest request may publish its report and status or clear the busy state. The previous report is cleared when a new file is chosen, and a failed inspection of the latest file is shown in red above its report. The read itself is unchanged: size checked before reading, balanced security-scoped access, nothing executed. `BetterXen --smoke-inspection-order`, run by `scripts/build-app.sh`, drives the model with an injected reader that blocks until the check releases each file, so the check (not timing) decides which read finishes first; it checks a stale success, a stale failure and a busy state held for the newer request, and all four checks fail without the change. Checked locally on Apple Silicon; not yet independently reviewed. - Restored the DBT benchmark report-test fixture after the cache-invalidation counter was added. Its existing percentile, JSON and comparison tests now run in ordinary workspace CI instead of requiring a separate benchmark test-harness command. - DBT cache hits now compare an executable-generation token instead of rereading every instruction byte. Address-space or executable-memory changes trigger byte and execute-permission revalidation before a translation can be reused; changed code is retranslated. Ordinary data writes retain the fast path. Tests cover cloned spaces, loader bypass writes, split writes, remapping and bounded cache exhaustion. Same-dispatch self-modification and discarded-code reclamation remain unsupported. - Gate A2 checks the cross-compiler driver before invoking it, then checks its helpers before fixture compilation. CI also verifies the driver architecture before requesting its version. diff --git a/app/Sources/Xenora/main.swift b/app/Sources/Xenora/main.swift index ddba3d4..83bc36c 100644 --- a/app/Sources/Xenora/main.swift +++ b/app/Sources/Xenora/main.swift @@ -645,6 +645,9 @@ final class InspectionModel: ObservableObject { private let reader: @Sendable (URL) -> (Int32, String) /// Number of the latest `inspect` call. Only that call may publish a result. private var latestRequest: UInt64 = 0 + /// Reads that have finished, whether their result was published or discarded. + /// `--smoke-inspection-order` waits on it instead of on a fixed delay. + private(set) var finishedReads: UInt64 = 0 init(reader: @escaping @Sendable (URL) -> (Int32, String) = InspectionModel.run) { self.reader = reader @@ -662,6 +665,7 @@ final class InspectionModel: ObservableObject { let reader = reader Task { let (newStatus, newReport) = await Task.detached { reader(url) }.value + finishedReads &+= 1 // A newer selection owns the published state, including `busy`; // an older read that finishes late is discarded. guard request == latestRequest else { return } @@ -1034,21 +1038,49 @@ if CommandLine.arguments.contains("--smoke-frame") { } // `--smoke-inspection-order` checks that only the latest selection publishes an -// inspection result. Files are never read: an injected reader answers after a delay -// named by the file. It needs no GPU. +// inspection result. Files are never read: an injected reader blocks until the check +// releases that file, so the check, not timing, decides which read finishes first. +// It needs no GPU. if CommandLine.arguments.contains("--smoke-inspection-order") { + final class ReadGates: @unchecked Sendable { + private let lock = NSLock() + private var gates: [String: DispatchSemaphore] = [:] + func gate(_ name: String) -> DispatchSemaphore { + lock.lock() + defer { lock.unlock() } + if let gate = gates[name] { return gate } + let gate = DispatchSemaphore(value: 0) + gates[name] = gate + return gate + } + func release(_ name: String) { gate(name).signal() } + } + let gates = ReadGates() + // "--"; a gate that is never released times out + // instead of hanging, and the check then fails on its own deadline. let reader: @Sendable (URL) -> (Int32, String) = { url in - // "--" - let parts = url.lastPathComponent.split(separator: "-") - Thread.sleep(forTimeInterval: Double(parts[0])! / 1000) - let status = parts[1] == "ok" ? Int32(XENORA_OK) : Int32(XENORA_INVALID_ARGUMENT) - return (status, "report \(url.lastPathComponent)") + let name = url.lastPathComponent + _ = gates.gate(name).wait(timeout: .now() + 10) + let status = name.hasSuffix("-ok") ? Int32(XENORA_OK) : Int32(XENORA_INVALID_ARGUMENT) + return (status, "report \(name)") } func file(_ name: String) -> URL { URL(fileURLWithPath: "/nonexistent/\(name)") } - func pause(_ ms: UInt64) async { try? await Task.sleep(nanoseconds: ms * 1_000_000) } Task { @MainActor in var failures: [String] = [] + // Waits for the model to finish `count` reads. The deadline only bounds the + // check; the order of completions is set by releasing gates. + @MainActor func settle(_ model: InspectionModel, _ count: UInt64, _ label: String) async -> Bool { + let deadline = Date().addingTimeInterval(5) + while model.finishedReads < count { + if Date() > deadline { + failures.append("\(label): read \(count) did not finish") + return false + } + try? await Task.sleep(nanoseconds: 2_000_000) + } + return true + } @MainActor func expect(_ model: InspectionModel, _ name: String, busy: Bool, report: String, ok: Bool, _ label: String) { let actual = "file=\(model.fileName ?? "-") busy=\(model.busy) status=\(model.status) report=\(model.report)" if model.fileName != name || model.busy != busy || model.report != report @@ -1056,23 +1088,35 @@ if CommandLine.arguments.contains("--smoke-inspection-order") { failures.append("\(label): \(actual)") } } - // A slow first read finishing after a fast second one, with either outcome. - for (first, second, ok) in [("400-ok-a", "0-ok-b", true), ("400-fail-a", "0-ok-b", true), - ("400-ok-a", "0-fail-b", false)] { + // The newer read finishes first; the older one finishes afterwards and must + // change nothing, whatever its outcome. + for (scenario, first, second, ok) in [("s1", "a-ok", "b-ok", true), ("s2", "a-fail", "b-ok", true), + ("s3", "a-ok", "b-fail", false)] { + let (older, newer) = ("\(scenario)-\(first)", "\(scenario)-\(second)") let model = InspectionModel(reader: reader) - model.inspect(file(first)) - model.inspect(file(second)) - await pause(700) - expect(model, second, busy: false, report: "report \(second)", ok: ok, "\(first) then \(second)") + model.inspect(file(older)) + model.inspect(file(newer)) + gates.release(newer) + if await settle(model, 1, "\(older) then \(newer)") { + expect(model, newer, busy: false, report: "report \(newer)", ok: ok, "\(newer) finished") + } + gates.release(older) + if await settle(model, 2, "\(older) then \(newer)") { + expect(model, newer, busy: false, report: "report \(newer)", ok: ok, "stale \(older) finished") + } } - // An older read that finishes first must not clear the newer request's busy state. + // The older read finishes first and must not clear the newer request's busy state. let model = InspectionModel(reader: reader) - model.inspect(file("100-ok-a")) - model.inspect(file("500-fail-b")) - await pause(300) - expect(model, "500-fail-b", busy: true, report: "", ok: true, "while the newer read runs") - await pause(500) - expect(model, "500-fail-b", busy: false, report: "report 500-fail-b", ok: false, "after the newer read") + model.inspect(file("s4-a-ok")) + model.inspect(file("s4-b-fail")) + gates.release("s4-a-ok") + if await settle(model, 1, "s4") { + expect(model, "s4-b-fail", busy: true, report: "", ok: true, "stale s4-a-ok finished first") + } + gates.release("s4-b-fail") + if await settle(model, 2, "s4") { + expect(model, "s4-b-fail", busy: false, report: "report s4-b-fail", ok: false, "s4-b-fail finished") + } for failure in failures { print("smoke-inspection-order: FAILED \(failure)") } print("smoke-inspection-order: \(failures.isEmpty ? "ok" : "\(failures.count) failed")") exit(failures.isEmpty ? 0 : 1) From 9a26e1ee361059348b0bd3b3c4206c1ca00f51fd Mon Sep 17 00:00:00 2001 From: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:55:17 -0300 Subject: [PATCH 07/15] docs: inventory texture formats and layouts by stage (#260) Add docs/research/texture-formats.md, built from BetterXen main. For RGBA8, BC1-BC7 and Depth32Float it separates container recognition, CPU decoding, layout conversion, native Metal upload and readback, translated sampling and guest reachability, linking the implementing files and tests for each cell, including the packed BC footprints from It cross-references #208 and #209 rather than opening duplicate tasks, records console layouts, console descriptors and asset or audio containers as unknowns, and ranks three proposed follow-ups with an original-fixture recipe, an independent source of expected values and an owner each. Deferred formats with no demonstrated need are listed. docs/README.md indexes the page. Research only; no code changed. Ported from XenoraOSS/Xenora#427 and re-checked against BetterXen main. Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com> --- CHANGELOG.md | 1 + docs/README.md | 1 + docs/research/texture-formats.md | 94 ++++++++++++++++++++++++++++++++ 3 files changed, 96 insertions(+) create mode 100644 docs/research/texture-formats.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 78da0a4..4045fcd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game remains unsupported. ### Added +- Added `docs/research/texture-formats.md`, an inventory of the texture formats and layouts BetterXen handles (#260). For BC1–BC7, RGBA8 and Depth32Float it separates container recognition, CPU decoding, layout conversion, native Metal upload and readback, translated sampling and guest reachability, and links the implementing files, tests and public specifications, including the packed BC footprints from #241. It cross-references #208 and #209 instead of opening duplicate tasks, lists console layouts, console descriptors and asset or audio containers as unknowns, and ranks three proposed follow-ups with fixture recipes and owners. Research only; no implementation changed. - Rewrote the README around the six development phases and the first-launchable-application target (#311), with colour-coded Mermaid diagrams (system flow, milestone roadmap, CPU, runtime-service and shader-form charts built from the generated registries), badges, a repository overview, a contributing section and corrected texture-sampling wording. The older X1–X25 capability map is kept in a collapsible section. The diagrams were not render-tested locally. - Added a fast "Repository hygiene" check (`.github/workflows/hygiene.yml`, `scripts/audit/docs_hygiene.py`). It runs on Ubuntu without a Rust toolchain or network access and fails only on merge-conflict markers, broken relative Markdown links and invalid workflow YAML in tracked files. A separate advisory step warns, without failing, when source or script changes have no changelog entry. A local run over the 626 tracked files found no problems, and planted failures of each kind were caught; it has not yet run on GitHub. diff --git a/docs/README.md b/docs/README.md index 254a1ce..30c0636 100644 --- a/docs/README.md +++ b/docs/README.md @@ -60,6 +60,7 @@ Historical phase checkpoints retain their original evidence scope. - [Public sources](research/sources.md), [RDNA 2 notes](research/rdna2.md), and [Xbox GPU evidence](research/xbox-gpu.md) — Specifications, evidence scope, and unknown console behavior. - [Shader inputs](research/shader-containers.md) and [risk register](risk-register.md) — Input provenance and unresolved engineering risks. +- [Texture format inventory](research/texture-formats.md) — Formats and layouts by stage (decode, layout, native upload, sampling, guest), their public specifications, unknowns and ranked follow-ups. - [PortWatch native macOS research](research/portwatch-native-macos.md) — Screening of public Xbox-on-Windows port projects for native macOS planning; discovery only. - [Synthetic integration and upstream evidence](research/synthetic-integration.md) — Audited source snapshots and remaining commercial startup prerequisites. diff --git a/docs/research/texture-formats.md b/docs/research/texture-formats.md new file mode 100644 index 0000000..53843d1 --- /dev/null +++ b/docs/research/texture-formats.md @@ -0,0 +1,94 @@ +# Texture format and layout inventory + +This page records which texture formats and memory layouts BetterXen handles today, and at which stage. It also records which gaps are worth closing and which are deferred. It is an inventory of the repository at the time of writing, built from the code and tests it links. It is not a support claim: a format listed here works only for the original synthetic fixtures named, on desktop specifications, and nothing here says anything about Xbox hardware or commercial titles. + +## Stages + +A format can be handled at one stage and missing at the next. The columns below keep them apart: + +- **Container**: recognising a file or package format that holds textures (DDS, KTX and similar). +- **CPU decode**: turning one compressed block into texels on the CPU, used as an independent reference. +- **Layout**: converting between a stored memory layout and the row-major layout Metal expects. +- **Native**: uploading to a Metal texture of that pixel format and reading it back on the GPU. +- **Sampling**: a translated RDNA 2 image instruction reading the texture inside a shader. +- **Guest**: a guest program reaching the path through the project's D3D12-style graphics services. + +"—" means not implemented. "Rejected" means the input is refused with an error rather than handled. + +## Formats + +| Format | Container | CPU decode | Layout | Native | Sampling | Guest | +| --- | --- | --- | --- | --- | --- | --- | +| RGBA8 unorm | — | not needed | row-major mips, direct or budgeted staged upload (`crates/metal/src/texture_pipeline.rs`) | upload and render target (`render_rgba8*`, `crates/metal/tests/native/texture_sampling.rs`) | `image_sample_lz`, 2D, level 0 (`crates/isa/src/lib.rs`, `crates/metal/tests/native/translated_render.rs`) | one-level 2D SRV, `DXGI_FORMAT_R8G8B8A8_UNORM` (`crates/loader/src/graphics.rs`, `crates/loader/tests/graphics_textures.rs`) | +| BC1 | — | `decode_bc1` (`crates/texture/src/lib.rs`) | synthetic tiled layout, pitched uploads (`TiledBc1`, `Bc1Upload`) and per-subresource packed footprints (`BcTextureLayout`, `PackedBcUpload`) | `read_tiled_bc1`, `read_bc1_upload`, including packed footprints (`crates/metal/tests/native/texture.rs`, `crates/metal/tests/packed_bc_upload.rs`) | sampled by the translated `image_sample_lz` pixel stage (`render_rgba8_sampled_bc1`, `crates/metal/tests/native/translated_bc1.rs`) | one-level 2D SRV, `DXGI_FORMAT_BC1_UNORM` (same files as RGBA8) | +| BC2, BC3 | — | `decode_bc2`, `decode_bc3` (`crates/texture/src/bc.rs`, `crates/texture/tests/bc_formats.rs`) | pitched upload (`BcAlphaUpload`) and packed footprints | `read_bc_alpha_upload`, including packed footprints (`crates/metal/tests/native/texture_bc_alpha.rs`, `crates/metal/tests/packed_bc_upload.rs`) | — | — | +| BC4, BC5 (unorm, snorm) | — | `decode_bc4_*`, `decode_bc5_*` (`crates/texture/src/bc.rs`, `crates/texture/tests/bc_formats.rs`) | pitched upload (`BcChannelUpload`) and packed footprints | `read_bc_channel_upload`, including packed footprints (`crates/metal/tests/native/texture_bc_channel.rs`, `crates/metal/tests/packed_bc_upload.rs`) | — | — | +| BC6H (ufloat, sfloat) | — | single-subset modes only; two-subset modes rejected (`crates/texture/src/bc6h.rs`, `crates/texture/tests/bc6h.rs`) | packed footprints only, 16-byte blocks (`crates/texture/src/footprint.rs`) | — | — | — | +| BC7 unorm | — | all eight modes (`crates/texture/src/bc7.rs`, `crates/texture/tests/bc7.rs`) | packed footprints only, 16-byte blocks (`crates/texture/src/footprint.rs`) | — | — | — | +| BC7 sRGB | — | same bytes as BC7; the sRGB transfer function is outside the decoder | — | — | — | — | +| Depth32Float | — | not needed | render attachment | `render_depth` with depth readback (`crates/metal/tests/native/depth.rs`) | — | — | + +Sampler state is limited to nearest filtering and clamp-to-edge addressing (`crates/texture/src/sampler.rs`). Other filter or address modes are rejected. + +Native BC paths require `supportsBCTextureCompression`. A device without it fails as a capability error (`crates/metal/src/compute.rs`), separately from implementation failures. + +Known source differences, recorded where they are implemented: + +- **BC6H:** the Khronos text and Microsoft's sample code disagree on whether a negative value that rounds to zero keeps its sign (`-0.0` against `0.0`). `bc6h.rs` follows Khronos. +- **BC1:** Apple's hardware rounds BC1's interpolated palette entries differently from the spec-exact decoder (171/84 against 170/85, see `CHANGELOG.md`). The sampled BC1 fixtures therefore use only endpoint colours. + +## Layouts + +| Layout | State | Where | +| --- | --- | --- | +| Row-major RGBA8 mips | implemented | `crates/metal/src/texture_pipeline.rs` | +| Budgeted staged RGBA8 upload | implemented | `MetalRgba8Texture::upload_staged`, `crates/metal/src/texture_pipeline.rs` | +| Pitched, layer-major BC uploads (one pitch for every mip, padded slices) | implemented for BC1–BC5 | `crates/texture/src/upload.rs` | +| Per-subresource packed footprints for block-compressed mip chains (tight or aligned rows) | layout implemented for BC1–BC7; native readback covers BC1–BC5 (#241, PR #278) | `crates/texture/src/footprint.rs`, `crates/texture/tests/bc_footprint.rs`, `crates/metal/tests/packed_bc_upload.rs` | +| The synthetic 2×2-tile BC1 layout | implemented; defined by the project's fixtures, not by any console | `crates/texture/src/lib.rs` | +| Desktop RDNA 2 surface tiling (swizzle modes) | unknown; not researched in this repository | — | +| Console texture memory layouts | unknown; no public source reviewed | — | + +## Public specifications + +These are the primary sources the implementations above cite. The format rows already name them in their source files. + +- Khronos Data Format Specification 1.3: the S3TC section (BC1–BC3), the RGTC section (BC4, BC5), section 20.1 "BC7" and section 20.2 "BC6H". +- Microsoft Direct3D documentation: "Texture Block Compression in Direct3D 11", "Block Compression (Direct3D 10)", "BC6H Format" and "BC7 Format". These are used for the format definitions and DXGI format codes, not for console behaviour. +- Apple Metal documentation: `MTLPixelFormat` and `MTLDevice.supportsBCTextureCompression`, for the native pixel formats and the capability check. +- AMD "RDNA 2" Instruction Set Architecture reference guide (GPUOpen): MIMG instructions such as `image_sample_lz`, and the image resource and sampler descriptor formats. These cover desktop gfx1030 only. [Xbox GPU evidence](xbox-gpu.md) records why desktop statements do not transfer to the console without separate evidence. + +## Unknowns + +These are research questions, not missing features: + +- **Console texture memory layouts and tiling.** No public specification has been reviewed. Desktop RDNA 2 tiling would be a separate research note and would still not establish console behaviour. +- **Console resource descriptor formats.** Unknown. See [Xbox GPU evidence](xbox-gpu.md), which lists descriptor layout among the unresolved items. +- **Asset and audio containers.** BetterXen parses none. The runtime's audio path accepts only raw PCM (`XENORA_AUDIO_FORMAT_PCM_S16LE` and `PCM_F32LE` in `crates/ffi/include/xenora.h`). No original workload has shown a need for a container or a compressed audio format. + +## Follow-ups + +Ranked by how close each is to existing tested paths. The first item is already tracked; the others are proposals, so do not start them without an issue and a claim. + +1. **BC6H two-subset modes and native BC6H/BC7.** Tracked in #208 (CPU decode, with an archived request to take it) and #209 (native upload and readback, whose imported proposal waits for maintainer approval). BC6H and BC7 already have packed footprints, so #209 can build on `PackedBcUpload`. Do not duplicate them. +2. **Translated sampling of BC2–BC5.** + - Fixture: original blocks with hand-chosen endpoints and indices, sampled by the existing `image_sample_lz` pixel stage. + - Expected values: derived by hand from the Khronos tables. The `bc.rs` decoders must not produce them, so that the decoder and the reference stay independent. + - Owners: Metal and Compiler. +3. **Additional sampler state** (linear filtering, wrap and mirror addressing). + - Fixture: a small original RGBA8 texture with distinct texels. + - Expected values: from the public Direct3D and Metal sampling equations, computed in exact fractions. + - Owners: Metal and Compiler. +4. **Desktop RDNA 2 image resource descriptor decoding.** Needed before guest-supplied descriptors can select formats. + - Fixture: original descriptor words for each supported format. + - Expected values: from the AMD RDNA 2 ISA guide's descriptor tables. + - Owner: ISA. + - This does not cover console descriptors. + +Deferred, with no demonstrated need: + +- BC7 sRGB +- DDS and KTX containers +- ASTC and ETC (not part of the desktop Direct3D 12 BC set this target uses) +- any compressed audio format +- console tiling, until a public source exists From 2b113a2e5ed6e4fc0d65e4b10019df5d26580cab Mon Sep 17 00:00:00 2001 From: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:17:44 -0300 Subject: [PATCH 08/15] docs: separate host API coverage from guest reachability and link sources (#260) Review follow-up. The Guest column credited the descriptor-table SRVs, which tests call directly from Rust and the interface contract says are not yet wired to guest imports. The table now has a Host graphics API column for them and keeps Guest for paths an original PE fixture reaches through imported services: today only RGBA8, through the synthetic xenora.dll texture services of the Gate 5 fixture. Every repository path is now a relative link, and each format row links the exact Khronos DFS 1.3 section and Microsoft or Apple page it relies on. Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com> --- CHANGELOG.md | 2 +- docs/research/texture-formats.md | 48 +++++++++++++++++--------------- 2 files changed, 26 insertions(+), 24 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4045fcd..7d4e221 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,7 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game remains unsupported. ### Added -- Added `docs/research/texture-formats.md`, an inventory of the texture formats and layouts BetterXen handles (#260). For BC1–BC7, RGBA8 and Depth32Float it separates container recognition, CPU decoding, layout conversion, native Metal upload and readback, translated sampling and guest reachability, and links the implementing files, tests and public specifications, including the packed BC footprints from #241. It cross-references #208 and #209 instead of opening duplicate tasks, lists console layouts, console descriptors and asset or audio containers as unknowns, and ranks three proposed follow-ups with fixture recipes and owners. Research only; no implementation changed. +- Added `docs/research/texture-formats.md`, an inventory of the texture formats and layouts BetterXen handles (#260). For BC1–BC7, RGBA8 and Depth32Float it separates container recognition, CPU decoding, layout conversion, native Metal upload and readback, translated sampling, the host-side D3D12-shaped API (called from Rust, not wired to guest imports) and guest reachability through imported services, and links each cell's implementing files and tests and each format's exact public specification sections, including the packed BC footprints from #241. It cross-references #208 and #209 instead of opening duplicate tasks, lists console layouts, console descriptors and asset or audio containers as unknowns, and ranks three proposed follow-ups with fixture recipes and owners. Research only; no implementation changed. - Rewrote the README around the six development phases and the first-launchable-application target (#311), with colour-coded Mermaid diagrams (system flow, milestone roadmap, CPU, runtime-service and shader-form charts built from the generated registries), badges, a repository overview, a contributing section and corrected texture-sampling wording. The older X1–X25 capability map is kept in a collapsible section. The diagrams were not render-tested locally. - Added a fast "Repository hygiene" check (`.github/workflows/hygiene.yml`, `scripts/audit/docs_hygiene.py`). It runs on Ubuntu without a Rust toolchain or network access and fails only on merge-conflict markers, broken relative Markdown links and invalid workflow YAML in tracked files. A separate advisory step warns, without failing, when source or script changes have no changelog entry. A local run over the 626 tracked files found no problems, and planted failures of each kind were caught; it has not yet run on GitHub. diff --git a/docs/research/texture-formats.md b/docs/research/texture-formats.md index 53843d1..2dc5d6e 100644 --- a/docs/research/texture-formats.md +++ b/docs/research/texture-formats.md @@ -11,26 +11,28 @@ A format can be handled at one stage and missing at the next. The columns below - **Layout**: converting between a stored memory layout and the row-major layout Metal expects. - **Native**: uploading to a Metal texture of that pixel format and reading it back on the GPU. - **Sampling**: a translated RDNA 2 image instruction reading the texture inside a shader. -- **Guest**: a guest program reaching the path through the project's D3D12-style graphics services. +- **Host graphics API**: the D3D12-shaped `GraphicsContext` entry points, exercised by tests that call them directly from Rust. [The interface contract](../interfaces.md#guest-texture-binding-descriptor-tables) states they are not yet wired to guest imports, so this column is not guest evidence. +- **Guest**: an original guest program (PE fixture) reaching the path through imported services, with a test that runs it. +- **Specification**: the public sections the implementation and its expected values cite. "—" means not implemented. "Rejected" means the input is refused with an error rather than handled. ## Formats -| Format | Container | CPU decode | Layout | Native | Sampling | Guest | -| --- | --- | --- | --- | --- | --- | --- | -| RGBA8 unorm | — | not needed | row-major mips, direct or budgeted staged upload (`crates/metal/src/texture_pipeline.rs`) | upload and render target (`render_rgba8*`, `crates/metal/tests/native/texture_sampling.rs`) | `image_sample_lz`, 2D, level 0 (`crates/isa/src/lib.rs`, `crates/metal/tests/native/translated_render.rs`) | one-level 2D SRV, `DXGI_FORMAT_R8G8B8A8_UNORM` (`crates/loader/src/graphics.rs`, `crates/loader/tests/graphics_textures.rs`) | -| BC1 | — | `decode_bc1` (`crates/texture/src/lib.rs`) | synthetic tiled layout, pitched uploads (`TiledBc1`, `Bc1Upload`) and per-subresource packed footprints (`BcTextureLayout`, `PackedBcUpload`) | `read_tiled_bc1`, `read_bc1_upload`, including packed footprints (`crates/metal/tests/native/texture.rs`, `crates/metal/tests/packed_bc_upload.rs`) | sampled by the translated `image_sample_lz` pixel stage (`render_rgba8_sampled_bc1`, `crates/metal/tests/native/translated_bc1.rs`) | one-level 2D SRV, `DXGI_FORMAT_BC1_UNORM` (same files as RGBA8) | -| BC2, BC3 | — | `decode_bc2`, `decode_bc3` (`crates/texture/src/bc.rs`, `crates/texture/tests/bc_formats.rs`) | pitched upload (`BcAlphaUpload`) and packed footprints | `read_bc_alpha_upload`, including packed footprints (`crates/metal/tests/native/texture_bc_alpha.rs`, `crates/metal/tests/packed_bc_upload.rs`) | — | — | -| BC4, BC5 (unorm, snorm) | — | `decode_bc4_*`, `decode_bc5_*` (`crates/texture/src/bc.rs`, `crates/texture/tests/bc_formats.rs`) | pitched upload (`BcChannelUpload`) and packed footprints | `read_bc_channel_upload`, including packed footprints (`crates/metal/tests/native/texture_bc_channel.rs`, `crates/metal/tests/packed_bc_upload.rs`) | — | — | -| BC6H (ufloat, sfloat) | — | single-subset modes only; two-subset modes rejected (`crates/texture/src/bc6h.rs`, `crates/texture/tests/bc6h.rs`) | packed footprints only, 16-byte blocks (`crates/texture/src/footprint.rs`) | — | — | — | -| BC7 unorm | — | all eight modes (`crates/texture/src/bc7.rs`, `crates/texture/tests/bc7.rs`) | packed footprints only, 16-byte blocks (`crates/texture/src/footprint.rs`) | — | — | — | -| BC7 sRGB | — | same bytes as BC7; the sRGB transfer function is outside the decoder | — | — | — | — | -| Depth32Float | — | not needed | render attachment | `render_depth` with depth readback (`crates/metal/tests/native/depth.rs`) | — | — | +| Format | Container | CPU decode | Layout | Native | Sampling | Host graphics API | Guest | Specification | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | +| RGBA8 unorm | — | not needed | row-major mips, direct or budgeted staged upload ([`crates/metal/src/texture_pipeline.rs`](../../crates/metal/src/texture_pipeline.rs)) | upload and render target (`render_rgba8*`, [`crates/metal/tests/native/texture_sampling.rs`](../../crates/metal/tests/native/texture_sampling.rs)) | `image_sample_lz`, 2D, level 0 ([`crates/isa/src/lib.rs`](../../crates/isa/src/lib.rs), [`crates/metal/tests/native/translated_render.rs`](../../crates/metal/tests/native/translated_render.rs)) | one-level 2D SRV, `DXGI_FORMAT_R8G8B8A8_UNORM`, called from Rust ([`crates/loader/src/graphics.rs`](../../crates/loader/src/graphics.rs), [`crates/loader/tests/graphics_textures.rs`](../../crates/loader/tests/graphics_textures.rs)) | synthetic `xenora.dll` texture services (`texture_create`, `texture_update`, `frame_submit_textured`, `texture_destroy`) driven by the Gate 5 original PE fixture ([`crates/ffi/src/lib.rs`](../../crates/ffi/src/lib.rs), test `textured_pe_fixture_executes_dynamic_updates_and_retirement` in [`crates/ffi/tests/resources.rs`](../../crates/ffi/tests/resources.rs)); not through the descriptor-table API | [`MTLPixelFormat.rgba8Unorm`](https://developer.apple.com/documentation/metal/mtlpixelformat/rgba8unorm) | +| BC1 | — | `decode_bc1` ([`crates/texture/src/lib.rs`](../../crates/texture/src/lib.rs)) | synthetic tiled layout, pitched uploads (`TiledBc1`, `Bc1Upload`) and per-subresource packed footprints (`BcTextureLayout`, `PackedBcUpload`) | `read_tiled_bc1`, `read_bc1_upload`, including packed footprints ([`crates/metal/tests/native/texture.rs`](../../crates/metal/tests/native/texture.rs), [`crates/metal/tests/packed_bc_upload.rs`](../../crates/metal/tests/packed_bc_upload.rs)) | sampled by the translated `image_sample_lz` pixel stage (`render_rgba8_sampled_bc1`, [`crates/metal/tests/native/translated_bc1.rs`](../../crates/metal/tests/native/translated_bc1.rs)) | one-level 2D SRV, `DXGI_FORMAT_BC1_UNORM`, called from Rust (same files as RGBA8) | — | [Khronos DFS 1.3, S3TC](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#S3TC) (BC1 with and without alpha); [Microsoft, BC1](https://learn.microsoft.com/en-us/windows/win32/direct3d11/texture-block-compression-in-direct3d-11) | +| BC2, BC3 | — | `decode_bc2`, `decode_bc3` ([`crates/texture/src/bc.rs`](../../crates/texture/src/bc.rs), [`crates/texture/tests/bc_formats.rs`](../../crates/texture/tests/bc_formats.rs)) | pitched upload (`BcAlphaUpload`) and packed footprints | `read_bc_alpha_upload`, including packed footprints ([`crates/metal/tests/native/texture_bc_alpha.rs`](../../crates/metal/tests/native/texture_bc_alpha.rs), [`crates/metal/tests/packed_bc_upload.rs`](../../crates/metal/tests/packed_bc_upload.rs)) | — | — | — | [Khronos DFS 1.3, S3TC BC2](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#s3tc_bc2) and [BC3](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#s3tc_bc3); [Microsoft, BC2 and BC3](https://learn.microsoft.com/en-us/windows/win32/direct3d11/texture-block-compression-in-direct3d-11) | +| BC4, BC5 (unorm, snorm) | — | `decode_bc4_*`, `decode_bc5_*` ([`crates/texture/src/bc.rs`](../../crates/texture/src/bc.rs), [`crates/texture/tests/bc_formats.rs`](../../crates/texture/tests/bc_formats.rs)) | pitched upload (`BcChannelUpload`) and packed footprints | `read_bc_channel_upload`, including packed footprints ([`crates/metal/tests/native/texture_bc_channel.rs`](../../crates/metal/tests/native/texture_bc_channel.rs), [`crates/metal/tests/packed_bc_upload.rs`](../../crates/metal/tests/packed_bc_upload.rs)) | — | — | — | [Khronos DFS 1.3, RGTC BC4](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#rgtc_bc4) and [BC5](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#rgtc_bc5); [Microsoft, BC4 and BC5](https://learn.microsoft.com/en-us/windows/win32/direct3d11/texture-block-compression-in-direct3d-11) | +| BC6H (ufloat, sfloat) | — | single-subset modes only; two-subset modes rejected ([`crates/texture/src/bc6h.rs`](../../crates/texture/src/bc6h.rs), [`crates/texture/tests/bc6h.rs`](../../crates/texture/tests/bc6h.rs), vectors [`crates/texture/tests/fixtures/bc6h_vectors.txt`](../../crates/texture/tests/fixtures/bc6h_vectors.txt)) | packed footprints only, 16-byte blocks ([`crates/texture/src/footprint.rs`](../../crates/texture/src/footprint.rs)) | — | — | — | — | [Khronos DFS 1.3, BPTC BC6H](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#bptc_bc6h) (section 20.2, Tables 121 and 122); [Microsoft, BC6H Format](https://learn.microsoft.com/en-us/windows/win32/direct3d11/bc6h-format) | +| BC7 unorm | — | all eight modes ([`crates/texture/src/bc7.rs`](../../crates/texture/src/bc7.rs), [`crates/texture/tests/bc7.rs`](../../crates/texture/tests/bc7.rs), vectors [`crates/texture/tests/fixtures/bc7_vectors.txt`](../../crates/texture/tests/fixtures/bc7_vectors.txt)) | packed footprints only, 16-byte blocks ([`crates/texture/src/footprint.rs`](../../crates/texture/src/footprint.rs)) | — | — | — | — | [Khronos DFS 1.3, BPTC BC7](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#bptc_bc7) (section 20.1, Tables 109–120); [Microsoft, BC7 Format](https://learn.microsoft.com/en-us/windows/win32/direct3d11/bc7-format) | +| BC7 sRGB | — | same bytes as BC7; the sRGB transfer function is outside the decoder | — | — | — | — | — | as BC7 | +| Depth32Float | — | not needed | render attachment | `render_depth` with depth readback ([`crates/metal/tests/native/depth.rs`](../../crates/metal/tests/native/depth.rs)) | — | — | — | [`MTLPixelFormat.depth32Float`](https://developer.apple.com/documentation/metal/mtlpixelformat/depth32float) | -Sampler state is limited to nearest filtering and clamp-to-edge addressing (`crates/texture/src/sampler.rs`). Other filter or address modes are rejected. +Sampler state is limited to nearest filtering and clamp-to-edge addressing ([`crates/texture/src/sampler.rs`](../../crates/texture/src/sampler.rs)). Other filter or address modes are rejected. -Native BC paths require `supportsBCTextureCompression`. A device without it fails as a capability error (`crates/metal/src/compute.rs`), separately from implementation failures. +Native BC paths require `supportsBCTextureCompression`. A device without it fails as a capability error ([`crates/metal/src/compute.rs`](../../crates/metal/src/compute.rs)), separately from implementation failures. Known source differences, recorded where they are implemented: @@ -41,11 +43,11 @@ Known source differences, recorded where they are implemented: | Layout | State | Where | | --- | --- | --- | -| Row-major RGBA8 mips | implemented | `crates/metal/src/texture_pipeline.rs` | -| Budgeted staged RGBA8 upload | implemented | `MetalRgba8Texture::upload_staged`, `crates/metal/src/texture_pipeline.rs` | -| Pitched, layer-major BC uploads (one pitch for every mip, padded slices) | implemented for BC1–BC5 | `crates/texture/src/upload.rs` | -| Per-subresource packed footprints for block-compressed mip chains (tight or aligned rows) | layout implemented for BC1–BC7; native readback covers BC1–BC5 (#241, PR #278) | `crates/texture/src/footprint.rs`, `crates/texture/tests/bc_footprint.rs`, `crates/metal/tests/packed_bc_upload.rs` | -| The synthetic 2×2-tile BC1 layout | implemented; defined by the project's fixtures, not by any console | `crates/texture/src/lib.rs` | +| Row-major RGBA8 mips | implemented | [`crates/metal/src/texture_pipeline.rs`](../../crates/metal/src/texture_pipeline.rs) | +| Budgeted staged RGBA8 upload | implemented | `MetalRgba8Texture::upload_staged`, [`crates/metal/src/texture_pipeline.rs`](../../crates/metal/src/texture_pipeline.rs) | +| Pitched, layer-major BC uploads (one pitch for every mip, padded slices) | implemented for BC1–BC5 | [`crates/texture/src/upload.rs`](../../crates/texture/src/upload.rs) | +| Per-subresource packed footprints for block-compressed mip chains (tight or aligned rows) | layout implemented for BC1–BC7; native readback covers BC1–BC5 (#241, PR #278) | [`crates/texture/src/footprint.rs`](../../crates/texture/src/footprint.rs), [`crates/texture/tests/bc_footprint.rs`](../../crates/texture/tests/bc_footprint.rs), [`crates/metal/tests/packed_bc_upload.rs`](../../crates/metal/tests/packed_bc_upload.rs) | +| The synthetic 2×2-tile BC1 layout | implemented; defined by the project's fixtures, not by any console | [`crates/texture/src/lib.rs`](../../crates/texture/src/lib.rs) | | Desktop RDNA 2 surface tiling (swizzle modes) | unknown; not researched in this repository | — | | Console texture memory layouts | unknown; no public source reviewed | — | @@ -53,10 +55,10 @@ Known source differences, recorded where they are implemented: These are the primary sources the implementations above cite. The format rows already name them in their source files. -- Khronos Data Format Specification 1.3: the S3TC section (BC1–BC3), the RGTC section (BC4, BC5), section 20.1 "BC7" and section 20.2 "BC6H". -- Microsoft Direct3D documentation: "Texture Block Compression in Direct3D 11", "Block Compression (Direct3D 10)", "BC6H Format" and "BC7 Format". These are used for the format definitions and DXGI format codes, not for console behaviour. -- Apple Metal documentation: `MTLPixelFormat` and `MTLDevice.supportsBCTextureCompression`, for the native pixel formats and the capability check. -- AMD "RDNA 2" Instruction Set Architecture reference guide (GPUOpen): MIMG instructions such as `image_sample_lz`, and the image resource and sampler descriptor formats. These cover desktop gfx1030 only. [Xbox GPU evidence](xbox-gpu.md) records why desktop statements do not transfer to the console without separate evidence. +- [Khronos Data Format Specification 1.3](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html): the [S3TC](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#S3TC) section (BC1–BC3), the [RGTC](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#RGTC) section (BC4, BC5), section 20.1 ["BC7"](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#bptc_bc7) and section 20.2 ["BC6H"](https://registry.khronos.org/DataFormat/specs/1.3/dataformat.1.3.html#bptc_bc6h). +- Microsoft Direct3D documentation: ["Texture Block Compression in Direct3D 11"](https://learn.microsoft.com/en-us/windows/win32/direct3d11/texture-block-compression-in-direct3d-11), ["Block Compression (Direct3D 10)"](https://learn.microsoft.com/en-us/windows/win32/direct3d10/d3d10-graphics-programming-guide-resources-block-compression), ["BC6H Format"](https://learn.microsoft.com/en-us/windows/win32/direct3d11/bc6h-format) and ["BC7 Format"](https://learn.microsoft.com/en-us/windows/win32/direct3d11/bc7-format). These are used for the format definitions and DXGI format codes, not for console behaviour. +- Apple Metal documentation: [`MTLPixelFormat`](https://developer.apple.com/documentation/metal/mtlpixelformat) and [`MTLDevice.supportsBCTextureCompression`](https://developer.apple.com/documentation/metal/mtldevice/supportsbctexturecompression), for the native pixel formats and the capability check. +- AMD "RDNA 2" Instruction Set Architecture reference guide ([GPUOpen architecture documentation](https://gpuopen.com/amd-gpu-architecture-programming-documentation/)): MIMG instructions such as `image_sample_lz`, and the image resource and sampler descriptor formats. These cover desktop gfx1030 only. [Xbox GPU evidence](xbox-gpu.md) records why desktop statements do not transfer to the console without separate evidence. ## Unknowns @@ -64,7 +66,7 @@ These are research questions, not missing features: - **Console texture memory layouts and tiling.** No public specification has been reviewed. Desktop RDNA 2 tiling would be a separate research note and would still not establish console behaviour. - **Console resource descriptor formats.** Unknown. See [Xbox GPU evidence](xbox-gpu.md), which lists descriptor layout among the unresolved items. -- **Asset and audio containers.** BetterXen parses none. The runtime's audio path accepts only raw PCM (`XENORA_AUDIO_FORMAT_PCM_S16LE` and `PCM_F32LE` in `crates/ffi/include/xenora.h`). No original workload has shown a need for a container or a compressed audio format. +- **Asset and audio containers.** BetterXen parses none. The runtime's audio path accepts only raw PCM (`XENORA_AUDIO_FORMAT_PCM_S16LE` and `PCM_F32LE` in [`crates/ffi/include/xenora.h`](../../crates/ffi/include/xenora.h)). No original workload has shown a need for a container or a compressed audio format. ## Follow-ups From 84f561b12b122905762e610448af76cb2123619c Mon Sep 17 00:00:00 2001 From: ates Date: Wed, 25 Nov 2026 16:14:50 +0300 Subject: [PATCH 09/15] Fix the documented known-answer count command Signed-off-by: ates --- docs/testing/cpu-coverage.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/docs/testing/cpu-coverage.md b/docs/testing/cpu-coverage.md index 7821696..4a90989 100644 --- a/docs/testing/cpu-coverage.md +++ b/docs/testing/cpu-coverage.md @@ -209,9 +209,7 @@ with the following command. This excludes section directives, format comments and Rust match arms. ```sh -rg -c '^[a-zA-Z0-9_]+:.* =>' crates/loader/tests/cpu_known_answers.rs -]* =>[^ -]*$' crates/loader/tests/cpu_known_answers.rs +rg -c '^[A-Za-z0-9_]+:.*=>' crates/loader/tests/cpu_known_answers.rs ``` The cache revalidation change in [PR #269](https://github.com/MacosPorters/betterxen/pull/269) From 873652d6855fd30f1a24d11df1cc3c2aba15b25e Mon Sep 17 00:00:00 2001 From: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:38:12 -0300 Subject: [PATCH 10/15] app: run inspection reads on a Dispatch queue, not a concurrency worker (#251) Review follow-up. The reader blocks on file I/O, and in the --smoke-inspection-order check on its gate semaphore. Inside Task.detached that blocked a Swift concurrency worker; with a single-worker cooperative pool the released newer read could not start while the older one waited, and the check timed out. The read now runs on DispatchQueue.global(qos: .userInitiated) and is bridged back with withCheckedContinuation. The request-number guard is unchanged. Signed-off-by: maridogolpeador <354308468+maridogolpeador@users.noreply.github.com> --- app/Sources/Xenora/main.swift | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/app/Sources/Xenora/main.swift b/app/Sources/Xenora/main.swift index 83bc36c..e720d71 100644 --- a/app/Sources/Xenora/main.swift +++ b/app/Sources/Xenora/main.swift @@ -664,7 +664,14 @@ final class InspectionModel: ObservableObject { busy = true let reader = reader Task { - let (newStatus, newReport) = await Task.detached { reader(url) }.value + // The read blocks on file I/O (and, in `--smoke-inspection-order`, on + // its gate), so it runs on a Dispatch queue instead of occupying a + // Swift concurrency worker that other tasks may need. + let (newStatus, newReport) = await withCheckedContinuation { continuation in + DispatchQueue.global(qos: .userInitiated).async { + continuation.resume(returning: reader(url)) + } + } finishedReads &+= 1 // A newer selection owns the published state, including `busy`; // an older read that finishes late is discarded. From 8d2662dcd7be868ad6d3720680a9581f370630d4 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Wed, 25 Nov 2026 09:56:31 -0500 Subject: [PATCH 11/15] Preserve startup report delivery and worker errors Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 1 + crates/cli/src/runner.rs | 58 ++++++++++++++----- crates/cli/src/startup_report.rs | 91 ++++++++++++++++++++++++------ crates/cli/tests/startup_report.rs | 30 ++++++++++ docs/interfaces.md | 8 ++- 5 files changed, 154 insertions(+), 34 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 35eefcd..ef49423 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,7 @@ remains unsupported. - Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits. ### Fixed +- Startup reports now reject existing destinations before guest execution, surface journal write failures, and preserve late errors alongside signal termination. - Restored the DBT benchmark report-test fixture after the cache-invalidation counter was added. Its existing percentile, JSON and comparison tests now run in ordinary workspace CI instead of requiring a separate benchmark test-harness command. - DBT cache hits now compare an executable-generation token instead of rereading every instruction byte. Address-space or executable-memory changes trigger byte and execute-permission revalidation before a translation can be reused; changed code is retranslated. Ordinary data writes retain the fast path. Tests cover cloned spaces, loader bypass writes, split writes, remapping and bounded cache exhaustion. Same-dispatch self-modification and discarded-code reclamation remain unsupported. - Gate A2 checks the cross-compiler driver before invoking it, then checks its helpers before fixture compilation. CI also verifies the driver architecture before requesting its version. diff --git a/crates/cli/src/runner.rs b/crates/cli/src/runner.rs index c2db69c..0c02761 100644 --- a/crates/cli/src/runner.rs +++ b/crates/cli/src/runner.rs @@ -2,7 +2,7 @@ use std::error::Error; use std::ffi::OsString; -use std::fs::{self, File}; +use std::fs::{self, File, OpenOptions}; use std::io::Read; use std::path::{Path, PathBuf}; use std::process::{Child, Command, ExitCode, Stdio}; @@ -18,7 +18,7 @@ use xenora_shader::{Architecture, PIXEL_ENTRY_POINT, VERTEX_ENTRY_POINT, compile #[path = "startup_report.rs"] mod startup_report; -use startup_report::{Events, Journal, Termination}; +use startup_report::{Events, JOURNAL_ERROR_EXIT, Journal, Termination, WATCHDOG_EXIT}; const FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/trusted-runner.exe"); const SERVICES_FIXTURE: &[u8] = include_bytes!("../../../fixtures/pe/runtime-services.exe"); @@ -108,7 +108,7 @@ pub fn command(args: impl IntoIterator) -> ExitCode { } }; let result = if options.worker { - worker_command(&options).map(|()| ExitCode::SUCCESS) + worker_command(&options) } else { launch_worker(&options) }; @@ -127,8 +127,20 @@ fn launch_worker(options: &Options) -> Result> { .as_ref() .map(|_| Journal::create()) .transpose()?; + let executable = std::env::current_exe()?; + let destination = options + .report + .as_ref() + .map(|path| { + OpenOptions::new() + .write(true) + .create_new(true) + .open(path) + .map_err(|error| format!("could not create startup report: {error}")) + }) + .transpose()?; let started = Instant::now(); - let mut command = Command::new(std::env::current_exe()?); + let mut command = Command::new(executable); command .args([ "run", @@ -148,10 +160,13 @@ fn launch_worker(options: &Options) -> Result> { let termination = command .spawn() .and_then(|child| supervise(child, started, WALL_LIMIT)); - if let (Some(journal), Some(path)) = (&journal, &options.report) { - journal - .finish(path, &termination) - .map_err(|error| format!("could not write startup report: {error}"))?; + if let (Some(journal), Some(destination)) = (&journal, destination) + && let Err(error) = journal.finish(destination, &termination) + { + eprintln!("could not write startup report: {error}"); + if matches!(&termination, Ok(Termination::Exited(status)) if status.success()) { + return Ok(ExitCode::FAILURE); + } } match termination? { Termination::Exited(status) => match status.code() { @@ -181,13 +196,28 @@ fn supervise(mut child: Child, started: Instant, limit: Duration) -> std::io::Re } } -fn worker_command(options: &Options) -> Result<(), Box> { - let mut events = options.journal.as_deref().map(Events::open).transpose()?; +fn worker_command(options: &Options) -> Result> { + let mut events = match options.journal.as_deref().map(Events::open).transpose() { + Ok(events) => events, + Err(error) => { + eprintln!("could not open startup journal: {error}"); + return Ok(ExitCode::from(JOURNAL_ERROR_EXIT)); + } + }; let result = run_worker(options, events.as_mut()); - if let (Some(events), Err(error)) = (events.as_mut(), &result) { - events.failure(error.as_ref()); + if let Some(events) = events.as_mut() { + if let Err(error) = &result { + events.failure(error.as_ref()); + } + if let Some(error) = events.write_error() { + if let Err(error) = result { + eprintln!("run failed: {error}"); + } + eprintln!("could not write startup journal: {error}"); + return Ok(ExitCode::from(JOURNAL_ERROR_EXIT)); + } } - result + result.map(|()| ExitCode::SUCCESS) } fn verify_fixture(path: &Path) -> Result<&'static [u8], Box> { @@ -220,7 +250,7 @@ fn run_worker(options: &Options, mut events: Option<&mut Events>) -> Result<(), std::thread::sleep(WALL_LIMIT); // The supervisor also enforces this deadline. The worker retains // its own deadline if it is invoked directly. - std::process::exit(124); + std::process::exit(i32::from(WATCHDOG_EXIT)); })?; let fixture = verify_fixture(&options.path)?; let (name, ticket, bound_imports) = if fixture == SERVICES_FIXTURE { diff --git a/crates/cli/src/startup_report.rs b/crates/cli/src/startup_report.rs index 960ee5e..7451986 100644 --- a/crates/cli/src/startup_report.rs +++ b/crates/cli/src/startup_report.rs @@ -8,6 +8,8 @@ use std::path::{Path, PathBuf}; use std::process::ExitStatus; use std::sync::atomic::{AtomicUsize, Ordering}; +pub(super) const WATCHDOG_EXIT: u8 = 124; +pub(super) const JOURNAL_ERROR_EXIT: u8 = 125; const VERSION: &str = "1"; const RECORD_SEPARATOR: char = '\t'; const MAX_BYTES: usize = 8192; @@ -60,15 +62,10 @@ impl Journal { pub(super) fn finish( &self, - path: &Path, + mut destination: File, termination: &io::Result, ) -> io::Result<()> { - let report = self.read().json(termination); - OpenOptions::new() - .write(true) - .create_new(true) - .open(path)? - .write_all(report.as_bytes()) + destination.write_all(self.read().json(termination).as_bytes()) } } @@ -79,7 +76,7 @@ impl Drop for Journal { } } -pub(super) struct Events(File); +pub(super) struct Events(File, Option); impl Events { pub(super) fn open(path: &Path) -> io::Result { @@ -87,11 +84,11 @@ impl Events { .write(true) .create_new(true) .open(path) - .map(Self) + .map(|file| Self(file, None)) } pub(super) fn stage(&mut self, stage: &str) { - let _ = writeln!(self.0, "{VERSION}\t{stage}"); + self.record(format_args!("{VERSION}\t{stage}")); } pub(super) fn failure(&mut self, error: &dyn std::error::Error) { @@ -101,11 +98,19 @@ impl Events { for byte in message[..end].bytes() { write!(encoded, "{byte:02x}").unwrap(); } - let _ = writeln!( - self.0, + self.record(format_args!( "{VERSION}\tfailure\t{}\t{encoded}", u8::from(end < message.len()) - ); + )); + } + fn record(&mut self, arguments: std::fmt::Arguments<'_>) { + if self.1.is_none() { + self.1 = writeln!(self.0, "{arguments}").err(); + } + } + + pub(super) fn write_error(&self) -> Option<&io::Error> { + self.1.as_ref() } } @@ -156,7 +161,7 @@ impl Report { let Some((VERSION, record)) = line.split_once(RECORD_SEPARATOR) else { return false; }; - if self.error.is_some() || self.completed == STAGES.len() { + if self.error.is_some() { return false; } if STAGES.get(self.completed) == Some(&record) { @@ -191,6 +196,13 @@ impl Report { } fn json(&self, termination: &io::Result) -> String { + let unwritable = matches!(termination, Ok(Termination::Exited(status)) + if status.code() == Some(i32::from(JOURNAL_ERROR_EXIT))); + let integrity = if unwritable { + "unwritable" + } else { + self.integrity + }; let (outcome, status, detail) = match termination { Ok(Termination::Deadline) => ( "timeout", @@ -198,19 +210,27 @@ impl Report { Some("worker exceeded the wall deadline".into()), ), Err(error) => ("unknown", None, Some(error.to_string())), - Ok(Termination::Exited(status)) if status.code() == Some(124) => ( + Ok(Termination::Exited(status)) if status.code() == Some(i32::from(WATCHDOG_EXIT)) => ( "timeout", Some(status), Some("worker watchdog expired".into()), ), + Ok(Termination::Exited(status)) if unwritable => ( + "unknown", + Some(status), + Some("worker could not write its startup journal".into()), + ), Ok(Termination::Exited(status)) if status.success() + && self.error.is_none() && self.completed == STAGES.len() && self.integrity == "complete" => { ("verified", Some(status), None) } - Ok(Termination::Exited(status)) if !status.success() && self.error.is_some() => { + Ok(Termination::Exited(status)) + if status.code().is_some() && !status.success() && self.error.is_some() => + { ("stage_failure", Some(status), None) } Ok(Termination::Exited(status)) if status.code().is_some() && !status.success() => { @@ -232,7 +252,7 @@ impl Report { .map_or("null".into(), |code| code.to_string()); format!( "{{\"schema_version\":{VERSION},\"outcome\":\"{outcome}\",\"last_completed_stage\":{last},\"record_integrity\":\"{}\",\"worker_exit_code\":{code},\"termination_detail\":{detail},\"error\":{error},\"error_truncated\":{},\"stages\":[{records}]}}\n", - self.integrity, self.error_truncated + integrity, self.error_truncated ) } } @@ -260,6 +280,43 @@ mod tests { use std::process::Command; use std::time::{Duration, Instant}; + #[test] + fn journal_write_error_surfaces_in_report() { + use std::os::unix::process::ExitStatusExt; + let journal = Journal::create().unwrap(); + fs::write(journal.path(), b"1\tparsed\n").unwrap(); + let mut events = Events(File::open(journal.path()).unwrap(), None); + events.stage("mapped"); + assert!(events.write_error().is_some()); + let status = ExitStatus::from_raw(i32::from(JOURNAL_ERROR_EXIT) << 8); + let result = journal.read().json(&Ok(Termination::Exited(status))); + assert!( + result.contains(r#""record_integrity":"unwritable""#), + "{result}" + ); + assert!( + result.contains(r#""last_completed_stage":"parsed""#), + "{result}" + ); + } + + #[test] + fn terminal_failure_keeps_signal_detail_after_all_stages() { + use std::os::unix::process::ExitStatusExt; + let journal = Journal::create().unwrap(); + let mut events = Events::open(&journal.path()).unwrap(); + for stage in STAGES { + events.stage(stage); + } + events.failure(&io::Error::other("late error")); + let report = journal.read(); + assert_eq!(report.integrity, "complete"); + let result = report.json(&Ok(Termination::Exited(ExitStatus::from_raw(15)))); + assert!(result.contains(r#""outcome":"unknown""#), "{result}"); + assert!(result.contains(r#""error":"late error""#), "{result}"); + assert!(result.contains("signal: 15"), "{result}"); + } + #[test] fn supervisor_distinguishes_early_exit_watchdog_signal_and_deadline() { for (script, limit, outcome, code) in [ diff --git a/crates/cli/tests/startup_report.rs b/crates/cli/tests/startup_report.rs index 983c21c..af812cb 100644 --- a/crates/cli/tests/startup_report.rs +++ b/crates/cli/tests/startup_report.rs @@ -77,3 +77,33 @@ fn assert_stages(report: &str, stages: &[&str]) { .1; } } + +#[test] +fn existing_report_path_prevents_worker_launch() { + let path = std::env::temp_dir().join(format!( + "betterxen-report-existing-{}.json", + std::process::id() + )); + std::fs::write(&path, "previous report").unwrap(); + let result = Command::new(env!("CARGO_BIN_EXE_betterxen")) + .args([ + "run", + "--experimental", + "--pe", + "missing-fixture", + "--startup-report", + ]) + .arg(&path) + .output() + .unwrap(); + let contents = std::fs::read_to_string(&path).unwrap(); + std::fs::remove_file(&path).unwrap(); + assert_eq!(contents, "previous report"); + assert!(!result.status.success()); + let stderr = String::from_utf8(result.stderr).unwrap(); + assert!( + stderr.contains("could not create startup report"), + "{stderr}" + ); + assert!(!stderr.contains("No such file or directory"), "{stderr}"); +} diff --git a/docs/interfaces.md b/docs/interfaces.md index 7e0990e..533e053 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -142,7 +142,7 @@ before anything is mapped. `ParsedPe::parse` does not make these checks, so static inspection of a file is unchanged. `betterxen run --experimental --pe --startup-report ` -writes a versioned JSON summary after the worker stops. The path must be new. +writes a versioned JSON summary after the worker stops. The supervisor creates the new report path before launching the worker. The report is optional and uses the same exact-byte fixture admission, startup observer and wall deadline as an ordinary run. @@ -158,8 +158,10 @@ original reported error when available. Errors are capped at 2 KiB of UTF-8 and carry an `error_truncated` flag. The supervisor reads at most 8 KiB plus one byte from the worker journal. -`record_integrity` reports `complete`, `truncated`, `malformed`, `oversized` -or `unreadable`. Only the valid ordered prefix counts toward progress. A +`record_integrity` reports `complete`, `truncated`, `malformed`, `oversized`, +`unreadable`, or `unwritable`. Worker exit codes 124 and 125 are reserved for +its watchdog and journal I/O errors, respectively. `--startup-journal` is an +internal worker option. Only the valid ordered prefix counts toward progress. A complete journal may still contain only a partial startup if the worker stopped between records. These records describe runtime observations from the trusted fixtures. From 478e9218acb16ab4dae9e7640a83714161b2934b Mon Sep 17 00:00:00 2001 From: Thilo Schaeffer <38328877+Thxlx@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:21:18 +0100 Subject: [PATCH 12/15] docs: specify the guest AVX and AVX2 contract Signed-off-by: Thilo Schaeffer <38328877+Thxlx@users.noreply.github.com> --- CHANGELOG.md | 1 + docs/README.md | 1 + docs/cpu/avx-contract.md | 114 ++++++++++++++++++++++++++++ tests/compat_fixtures/avx/README.md | 88 +++++++++++++++++++++ 4 files changed, 204 insertions(+) create mode 100644 docs/cpu/avx-contract.md create mode 100644 tests/compat_fixtures/avx/README.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 78da0a4..04181cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ remains unsupported. ### Added - Rewrote the README around the six development phases and the first-launchable-application target (#311), with colour-coded Mermaid diagrams (system flow, milestone roadmap, CPU, runtime-service and shader-form charts built from the generated registries), badges, a repository overview, a contributing section and corrected texture-sampling wording. The older X1–X25 capability map is kept in a collapsible section. The diagrams were not render-tested locally. - Added a fast "Repository hygiene" check (`.github/workflows/hygiene.yml`, `scripts/audit/docs_hygiene.py`). It runs on Ubuntu without a Rust toolchain or network access and fails only on merge-conflict markers, broken relative Markdown links and invalid workflow YAML in tracked files. A separate advisory step warns, without failing, when source or script changes have no changelog entry. A local run over the 626 tracked files found no problems, and planted failures of each kind were caught; it has not yet run on GitHub. +- Documented the proposed guest AVX/AVX2 state and decoding contract and specified an original integer fixture with known results and fault controls (#299). ### Removed - Removed the "PR template" check (`.github/workflows/pr-template.yml`, `scripts/pr_template_check.py` and its tests) and its CI test step. Also removed `.github/PULL_REQUEST_TEMPLATE.md`. Pull request descriptions are no longer validated or pre-filled; CONTRIBUTING.md still asks for the same information and the claim-first rule still applies. diff --git a/docs/README.md b/docs/README.md index 254a1ce..4bc2f9b 100644 --- a/docs/README.md +++ b/docs/README.md @@ -38,6 +38,7 @@ Historical phase checkpoints retain their original evidence scope. - [Guest experiment guide](../experiments/x1/README.md) — Bounded x86-64 execution, executable loading, experimental services, native compute, and offscreen rendering. - [x86-64 instruction registry](cpu/instruction-registry.md) — Shared decoder, generated tables, semantics, native lowering and how to add a verified instruction form. +- [Proposed AVX and AVX2 guest contract](cpu/avx-contract.md) — VEX decoding, vector state, fault behavior and an original integer fixture specification. - [Runtime service registry](runtime/registry.md) and [generated coverage](runtime/services.md) — Import resolution, typed Win64 adapters and how to add a tested service. - [Guest threads](runtime/threads.md) — Deterministic scheduler, thread services, limits and tests. - [Guest CPU research](research/cpu-boundary.md) — Public specifications and unresolved console requirements. diff --git a/docs/cpu/avx-contract.md b/docs/cpu/avx-contract.md new file mode 100644 index 0000000..616ca2e --- /dev/null +++ b/docs/cpu/avx-contract.md @@ -0,0 +1,114 @@ +# Proposed AVX and AVX2 guest contract + +[Issue #299](https://github.com/MacosPorters/betterxen/issues/299) defines a +reviewable first step for Advanced Vector Extensions (AVX) in the x86-64 guest. +The current [instruction registry](instruction-registry.md) rejects VEX prefixes. +[`CpuState`](../../crates/loader/src/cpu.rs) holds 16 XMM registers and MXCSR, +the SIMD floating-point control and status register. The synthetic `CPUID` +advertises basic leaves through 1 and reports no AVX or extended-state support. + +## Architectural state and encoding + +In 64-bit mode, XMM0–XMM15 alias bits 127:0 of YMM0–YMM15. A legacy SSE +instruction that writes an XMM destination preserves bits 255:128. For the +packed VEX.128 forms in this proposal, writing an XMM destination clears that +register's upper 128 bits. A VEX.256 register destination replaces all 256 bits. +A store to memory leaves its source vector register intact. The proposed moves +and integer add leave RFLAGS and MXCSR unchanged. [Intel SDM, Vol. 1, §14.8; +Vol. 2, MOVDQU and PADDD](https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html). + +The shared [decoder](../../crates/loader/src/x86_decode.rs) should retain the +prefix family, opcode map, mandatory prefix, operand width and register +extensions until it selects the form. In 64-bit mode the VEX lead byte +identifies the prefix length. The table lists each payload byte's fields +from bit 7 to bit 0. + +| Lead byte | Payload byte 1 | Payload byte 2 | Implied fields | +| --- | --- | --- | --- | +| `C5` | `~R ~vvvv L pp` | — | Map `0F`, `W=0`, logical `X=B=0` | +| `C4` | `~R ~X ~B mmmmm` | `W ~vvvv L pp` | Map selected by `mmmmm` | + +The tilde indicates an inverted encoding. `R` extends ModRM.reg, while `X` +and `B` extend the applicable index and r/m or base fields. `vvvv` supplies +the first source of `VPADDD`. For `VMOVDQU` its encoded bits must be `1111b`. +`L=0` selects 128 bits and `L=1` selects 256 bits for these forms. The three +standard VEX maps are `00001b` (`0F`), `00010b` (`0F 38`) and `00011b` +(`0F 3A`). `pp` values 0 through 3 represent no mandatory prefix, `66`, `F3` +and `F2`. Both initial opcodes are in `0F`, with `W` ignored (`WIG`). Decode +both valid prefix lengths for them. Reject reserved maps and encodings, +including a physical `LOCK`, `66`, `F2`, `F3` or REX prefix before VEX, through +the existing illegal-instruction path. Legal forms outside the implemented +subset also stop explicitly. Keep the existing register and effective-address +rules and 15-byte fetch limit. [Intel SDM, Vol. 2, §2.3 and individual +opcode entries](https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html). + +## First implementation increments + +1. Append one upper 128-bit half per vector register to `CpuState`, retaining + the existing XMM storage as the low halves. Add layout assertions for the + offsets the dynamic binary translator (DBT) uses. Initialize both halves + in a fresh guest thread and carry them with the thread state when switching + or resuming. Add the shared VEX decoder and encoding controls before execution. +2. Implement `VMOVDQU` (128 and 256 bits, `F3.0F`, `6F /r` and `7F /r`, + register and checked memory forms) and `VPADDD` (128 and 256 bits, + `66.0F`, `FE /r`, register sources initially). The instruction entries + assign both move widths and 128-bit `VPADDD` to AVX, and 256-bit `VPADDD` + to AVX2. Read all sources before publishing the destination, including + when the destination aliases a source. Compare both engines with the + [original fixture specification](../../tests/compat_fixtures/avx/README.md). +3. After shared semantics pass, lower register moves and `VPADDD` to native + ARM64 vector operations on one or two 128-bit halves. Each `VPADDD` half + is four independent 32-bit additions modulo 2³². Use the checked-memory + helper for loads and stores. Check the DBT's fallback counter so a run + through that helper establishes only helper coverage for those forms. + +Stage memory-source `VPADDD` and aligned moves separately. Reject masked +moves, gathers, cross-half permutations, floating-point forms, FMA, EVEX +and guest extended-state instructions in the initial slice. AMD64 bytes +remain guest data. All host execution uses native ARM64 code or checked +Rust helpers. + +## Memory, faults and instruction budget + +`VMOVDQU` permits unaligned operands. Check the complete 16- or 32-byte +guest span before publishing a load result or writing a store. A split +span across adjacent permitted mappings succeeds. A missing or protected +mapping produces the existing guest memory fault at the first inaccessible +byte. A non-canonical address produces `GeneralProtection`. For a later +`VMOVDQA` form, a memory operand must be aligned to its width (16 or 32 +bytes), with a misaligned operand raising `GeneralProtection`. These checks +use guest addresses and permissions. [Intel SDM, Vol. 2, MOVDQU and +MOVDQA](https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html). + +Before adding masked moves, use a separate per-lane access contract. For +`VPMASKMOVD`, only lanes with the high mask bit set may access memory or +report a memory fault. A clear bit zeroes a load lane and leaves a store +lane untouched. A test with lane 4 on an unmapped page must pass with that +lane disabled and fault with it enabled. A full-width span check would +incorrectly reject the disabled case. Specify store commit behavior before +admitting that form. [Intel SDM, Vol. 2, +VPMASKMOV](https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html). + +Require interpreter and DBT parity for the exit reason, fault address when +reported, RIP, instruction count and complete guest register and memory +state. A rejected move or add has no partial destination update and does +not retire. A successful 256-bit instruction consumes one guest step even +when the DBT emits two halves. With an exhausted budget, stop at the next +guest RIP before decoding or executing that instruction. Check cold and warm +DBT paths and resume in the middle of the same sequence. + +## Feature exposure + +Run the initial forms only in explicitly enabled synthetic test cases. +Keep normal guest `CPUID` and extended-state behavior at the current baseline. +Before guest-visible AVX support, the guest OS model needs coherent reporting +for `CPUID.1:ECX` bits 26 (XSAVE), 27 (OSXSAVE) and 28 (AVX), and `XGETBV` +with `ECX=0` must report both XMM and YMM state enabled in `XCR0[2:1]`. The +extended-state layout reported by `CPUID.0Dh`, save and restore behavior, +and per-thread ownership must agree. Verify the exception behavior for +disabled state and invalid `XGETBV` selectors before exposing the facility. +AVX2 separately requires `CPUID.(7,0):EBX[5]` and the same OS state. Gate +each advertised feature on its full instruction and state contract, +with probes for enabled and disabled combinations. [Intel SDM, Vol. 1, +§14.3 and §14.7.1; Vol. 2, CPUID, XGETBV, XSAVE and +XRSTOR](https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html). diff --git a/tests/compat_fixtures/avx/README.md b/tests/compat_fixtures/avx/README.md new file mode 100644 index 0000000..6862cdb --- /dev/null +++ b/tests/compat_fixtures/avx/README.md @@ -0,0 +1,88 @@ +# Original AVX integer fixture specification + +This fixture is a proposed known-answer test for the +[guest AVX contract](../../../docs/cpu/avx-contract.md). It uses only the +source below, fixed register values and synthetic guest memory. Run the +eventual fixture in both guest engines on fresh copies of the same initial +state. Use the independent expected values below for each engine. + +## Guest sequence + +Set `r8` and `r9` to separate readable ranges containing arrays A and B. +Set `r10` to a writable 96-byte output region initialized to `0xA5` with +mapped sentinel bytes before and after it. Map the code separately as guest +executable memory. Initialize flags, MXCSR and untouched vector registers to +known nonzero values, then record their initial values. The sequence uses no +stack, imports or host calls. + +```asm +.intel_syntax noprefix +.text +vmovdqu ymm1, ymmword ptr [r8] +vmovdqu ymm2, ymmword ptr [r9] +vpaddd ymm3, ymm1, ymm2 +vmovdqu ymmword ptr [r10], ymm3 +movdqu xmm3, xmm1 +vmovdqu ymmword ptr [r10 + 32], ymm3 +vmovdqu xmm3, xmm2 +vmovdqu ymmword ptr [r10 + 64], ymm3 +hlt +``` + +The high base registers require three-byte VEX for the memory moves, while +the low-register `VPADDD` and register `VMOVDQU` can use two-byte VEX. +Store each table row as eight little-endian 32-bit words, with lane 0 at +the lowest address. All entries are hexadecimal. + +| Words | Lane 0 | Lane 1 | Lane 2 | Lane 3 | Lane 4 | Lane 5 | Lane 6 | Lane 7 | +| --- | --- | --- | --- | --- | --- | --- | --- | --- | +| A | `ffffffff` | `7fffffff` | `80000000` | `00000000` | `00000010` | `fffffffe` | `12345678` | `aaaaaaaa` | +| B | `00000001` | `00000001` | `80000000` | `ffffffff` | `00000020` | `00000003` | `11111111` | `55555556` | +| Output +0 | `00000000` | `80000000` | `00000000` | `ffffffff` | `00000030` | `00000001` | `23456789` | `00000000` | +| Output +32 | `ffffffff` | `7fffffff` | `80000000` | `00000000` | `00000030` | `00000001` | `23456789` | `00000000` | +| Output +64 | `00000001` | `00000001` | `80000000` | `ffffffff` | `00000000` | `00000000` | `00000000` | `00000000` | + +For output +0, add corresponding words as unsigned integers and discard +bits above bit 31 in each sum. For example, lane 0 wraps `0x100000000` to +zero, so lane 1 has no incoming carry. At +32, the legacy move replaces the +low four words with A and retains the high four words of the sum. At +64, +the VEX.128 move replaces the low four words with B and clears the high +four. Final YMM1 and YMM2 equal A and B. Final YMM3 equals output +64. +All other vector registers, the input bytes, sentinels, general-purpose +registers, flags and MXCSR retain their initial values. Expect `Halt` with +nine steps, including the terminal `HLT`. + +## Controls + +| Case | Expected result | +| --- | --- | +| `VPADDD` writes to one of its input registers | Same eight-word sum using both inputs as they stood before the instruction. The other source survives. | +| 128-bit `VPADDD` with seeded destination upper half | Output +0's low four words and four zero words. Both sources survive when distinct from the destination. | +| 128-bit `VMOVDQU` store with sentinels | Exactly the low 16 bytes are stored. The entire source YMM and memory outside the operand survive. | +| 256-bit `VMOVDQU` at a 32-byte-aligned address, at an address offset by one byte, and at `P-16` across adjacent accessible mappings | Same 32 bytes at each address. `P` is the start of the second mapping. | +| Split load at `P-16`, with the second mapping unreadable or unmapped | Memory fault at `P`. Every destination bit retains its pre-instruction value. | +| Split store at `P-16`, with the second mapping read-only or unmapped | Memory fault at `P`. The 16 writable bytes before `P` retain their sentinels. | +| Future `VMOVDQA` at aligned and misaligned addresses | An aligned, permitted span transfers the same bytes. A span misaligned by one byte produces `GeneralProtection` and has no data effects. Run at both widths. | +| Future masked dword load from `P-16` | With only lanes 0–3 enabled, load four words and zero lanes 4–7 even if the mapping at `P` is absent. Enabling lane 4 faults at `P`. An all-zero mask reads no lanes and returns an all-zero destination. | +| Future masked dword store to the same split span | With only lanes 0–3 enabled, write those four words; disabled lanes neither access the second mapping nor alter any bytes there when it is mapped. Enabling lane 4 with its mapping absent faults at `P`. | +| Reserved move `vvvv`, reserved VEX map, prohibited prefix before VEX | Illegal instruction at the offending instruction's RIP. No destination or memory update. | +| Equivalent legal `C5` and `C4` register forms, including both `W` values for `WIG` | Equal results and state, with RIP advancement matching each encoding length. Include a high ModRM.reg destination and high `vvvv` source. | +| Budget of two steps | Stop at `VPADDD` (`entry + 0xA` with the encoding shown below) with both inputs loaded, YMM3 and output untouched. Resume with seven steps and reach the same final state as a nine-step run. Repeat with a warm DBT cache. | + +For faults, place a completed instruction before the failing instruction. +Assert that only the earlier instruction retires and its effects persist. +Check snapshots of the full destination or nearby memory as appropriate. + +## Build provenance + +Use native Apple Silicon LLVM tools to assemble the sequence as an x86-64 +object, for example with `xcrun clang -arch x86_64 -c avx-fixture.s`. +Verify the resolved Clang and `llvm-objdump` executables support ARM64 before +running them. Record their versions and the output of disassembling the +object. Apple Clang 21.0.0 emits `C4 C1 7E 6F 08` for the first load and +`C5 F5 FE DA` for `VPADDD` at offset `0xA`. Keep generated sources and +objects under ignored `artifacts/`. +The test harness consumes only the object's verified instruction bytes +as guest data. Reserved encodings can be authored separately from Intel's +bit-field tables, since an assembler may reject them. Use source-derived +lane values and checked-memory expectations for the test oracle. From 4c92c88b29b7b39ea8ca3dc7fab9c2ae9c53b72e Mon Sep 17 00:00:00 2001 From: Thilo Schaeffer <38328877+Thxlx@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:31:03 +0100 Subject: [PATCH 13/15] perf: shorten ARM64 loads for zero-extended constants Signed-off-by: Thilo Schaeffer <38328877+Thxlx@users.noreply.github.com> --- CHANGELOG.md | 1 + crates/loader/src/arm64.rs | 42 +++++++++++++++++++++++++++++--------- 2 files changed, 33 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 78da0a4..9d5d620 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,7 @@ remains unsupported. - The native ARM64 DBT now runs the 32- and 64-bit register and immediate forms of ADC and SBB itself instead of falling back to the shared interpreter (#195). The guest CF is moved into the host carry before ADCS or SBCS, inverted for SBB because SBCS subtracts NOT C while SBB subtracts CF. Memory forms and 8- and 16-bit forms still use the shared semantics. `tests/x86_carry_chain.rs` runs 256-bit add and subtract chains of 64- and 32-bit limbs, in one block and split one block per limb, against widening `u128`/`i128` reference arithmetic in both engines, plus immediate 128-bit increments and decrements and the `sbb reg, reg` carry mask. Locally verified on Apple M5 only. - Removed the temporary region-list allocation from each instruction-byte fetch while preserving lookup order, execute-permission checks and error behavior (part of #104). - Release and bench builds now use fat link-time optimization with one codegen unit (#116). On a local Apple M5, `dbt_bench` medians over five alternating runs dropped by about 6 % for the interpreter (903 to 845 µs) and about 9 % for cold DBT (1.155 to 1.046 ms), while warm DBT (cache hits) became about 2 % slower (21.83-22.08 to 22.29-22.54 µs over four further runs). The `xenora` binary shrank from 2.73 to 2.11 MB. A clean release build of the workspace takes about 14 s instead of 6 s. Debug and test builds are unchanged. +- The ARM64 assembler uses one 32-bit `MOVN` for zero-extended constants such as `0xFFFF1234` that previously took two wide moves (#89). On an Apple M1 Pro, a synthetic workload with 4,096 affected loads emitted 163,920 native bytes, down from 180,304 (9.1%). The native tests verify the encoding and the full 64-bit register result. - The ARM64 assembler loads 64-bit constants with the fewest MOVZ or MOVN plus MOVK instructions (#92). It no longer emits MOVK for zero halfwords and starts from MOVN when more halfwords are 0xFFFF than zero, so small negative values take one instruction instead of four. On Apple M5 the DBT benchmark emits 245,168 instead of 290,184 native bytes for its 626 blocks (-15.5%) and the 1,048 integer fixture instructions 128,724 instead of 145,732 (-11.7%); benchmark run times did not change measurably. New tests check the sequences against LLVM encodings and execute 1,056 of them on the host through the JIT. - Resolve the tiled BC1 mip and array layer once per linearization and copy contiguous block runs within each tile row. Partial edge blocks are retained and padding slots are skipped. Closes #349. - Changed the default report folder of `xenora probe` and `xenora imports sync` to `diagnostics/probe`, which Git ignores (#364). Anyone relying on the earlier default has to pass `--report`. diff --git a/crates/loader/src/arm64.rs b/crates/loader/src/arm64.rs index 078ce86..3e7026c 100644 --- a/crates/loader/src/arm64.rs +++ b/crates/loader/src/arm64.rs @@ -633,15 +633,22 @@ impl Arm64Assembler { self.emit(0x92800000 | (hw << 21) | ((imm16 as u32) << 5) | (xd as u32 & 0x1f)); } - /// Load a full 64-bit constant into register Xd with the fewest MOVZ or - /// MOVN plus MOVK instructions: one for each halfword that differs from - /// the background the first instruction leaves, and always at least one. - /// MOVZ leaves zero halfwords and MOVN leaves 0xFFFF ones, so MOVN is used - /// when more halfwords are 0xFFFF than zero. + /// Load a full 64-bit constant into Xd with the fewest wide moves. + /// A 32-bit MOVN leaves one low halfword set to 0xFFFF and zero-extends + /// the result into Xd. For other values, select a 64-bit MOVZ or MOVN + /// background and use MOVK for the remaining halfwords. pub fn load_imm_64(&mut self, xd: u8, val: u64) { let halves: [u16; 4] = std::array::from_fn(|i| (val >> (16 * i)) as u16); let zeros = halves.iter().filter(|&&h| h == 0).count(); let ones = halves.iter().filter(|&&h| h == 0xffff).count(); + // With only the top two halfwords zero, a 32-bit MOVN saves one + // instruction when either of the lower halfwords is all ones. + if zeros == 2 && ones != 0 && val >> 32 == 0 { + let index = usize::from(halves[1] != u16::MAX); + let imm16 = u32::from(!halves[index]); + self.emit(0x1280_0000 | ((index as u32) << 21) | (imm16 << 5) | u32::from(xd & 0x1f)); + return; + } let background = if ones > zeros { 0xffff } else { 0 }; // The first halfword that differs from the background, or halfword 0 // when none does (val is 0 or all ones). @@ -883,12 +890,14 @@ mod tests { } /// Constants at the halfword boundaries the MOVZ/MOVN choice depends on. - const IMMEDIATE_EDGES: [u64; 16] = [ + const IMMEDIATE_EDGES: [u64; 18] = [ 0, 1, 0xffff, 0x1_0000, 0x8000_0000, + 0xffff_1234, + 0x1234_ffff, 0xffff_ffff, 0x1_0000_0000, 0x1234_0000_0000_0000, @@ -904,10 +913,13 @@ mod tests { #[test] fn immediate_sequences_match_llvm_encodings() { - // llvm-mc -triple=aarch64-apple-macos -show-encoding. + // A64 words from llvm-mc and Apple Clang's integrated assembler. let cases: &[(u64, &[u32])] = &[ (0, &[0xd2800000]), // movz x0, #0 (u64::MAX, &[0x92800000]), // movn x0, #0 + (0xffff_1234, &[0x129db960]), // movn w0, #0xedcb + (0x1234_ffff, &[0x12bdb960]), // movn w0, #0xedcb, lsl #16 + (0xffff_ffff, &[0x12800000]), // movn w0, #0 (0xffff_ffff_ffff_1234, &[0x929db960]), // movn x0, #0xedcb (0x1234_0000_0000_0000, &[0xd2e24680]), // movz x0, #0x1234, lsl #48 (0xffff_0000_ffff_ffff, &[0x92dfffe0]), // movn x0, #0xffff, lsl #32 @@ -930,9 +942,16 @@ mod tests { ); } - /// Fewest MOVZ/MOVN/MOVK instructions for `value`: every halfword that is - /// neither zero (after MOVZ) nor 0xFFFF (after MOVN), and at least one. + /// A 32-bit MOVN can write a zero-extended value if its low word's + /// complement fits in a single halfword. Otherwise count the halfwords + /// that differ from either 64-bit initializer's background. fn shortest_wide_move(value: u64) -> usize { + if let Ok(low) = u32::try_from(value) { + let complement = !low; + if complement <= u32::from(u16::MAX) || complement.trailing_zeros() >= 16 { + return 1; + } + } let halves = (0..4).map(|i| (value >> (16 * i)) & 0xffff); let not_zero = halves.clone().filter(|&h| h != 0).count(); let not_ones = halves.filter(|&h| h != 0xffff).count(); @@ -964,9 +983,12 @@ mod tests { for value in values { for register in [X0, X9] { let mut asm = Arm64Assembler::new(); + // Seed the destination so a W-register load must clear the high bits. + asm.movn_64(register, 0, 0); + let start = asm.current_offset(); asm.load_imm_64(register, value); assert_eq!( - asm.instructions().len(), + asm.current_offset() - start, shortest_wide_move(value), "{value:#x}" ); From d486d2181340d2c24b46639a62bde3b7a14ec93a Mon Sep 17 00:00:00 2001 From: Thilo Schaeffer <38328877+Thxlx@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:45:04 +0100 Subject: [PATCH 14/15] docs: clarify AVX exception policy and Intel references Signed-off-by: Thilo Schaeffer <38328877+Thxlx@users.noreply.github.com> --- docs/cpu/avx-contract.md | 50 +++++++++++++++++++++-------- tests/compat_fixtures/avx/README.md | 2 ++ 2 files changed, 38 insertions(+), 14 deletions(-) diff --git a/docs/cpu/avx-contract.md b/docs/cpu/avx-contract.md index 616ca2e..e4a164c 100644 --- a/docs/cpu/avx-contract.md +++ b/docs/cpu/avx-contract.md @@ -7,6 +7,13 @@ The current [instruction registry](instruction-registry.md) rejects VEX prefixes the SIMD floating-point control and status register. The synthetic `CPUID` advertises basic leaves through 1 and reports no AVX or extended-state support. +The architectural expectations come from the public Intel Software Developer's +Manual and apply to BetterXen's synthetic x86-64 guest profile. Which AVX and +AVX2 features Xbox Series X|S CPUs expose, and which extended register state +the console OS enables for applications, remain open research questions. +Resolving them requires public platform documentation or authorized hardware +evidence. + ## Architectural state and encoding In 64-bit mode, XMM0–XMM15 alias bits 127:0 of YMM0–YMM15. A legacy SSE @@ -14,8 +21,8 @@ instruction that writes an XMM destination preserves bits 255:128. For the packed VEX.128 forms in this proposal, writing an XMM destination clears that register's upper 128 bits. A VEX.256 register destination replaces all 256 bits. A store to memory leaves its source vector register intact. The proposed moves -and integer add leave RFLAGS and MXCSR unchanged. [Intel SDM, Vol. 1, §14.8; -Vol. 2, MOVDQU and PADDD](https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html). +and integer add leave RFLAGS and MXCSR unchanged. [Intel SDM Vol. 1, §14.8, +Accessing YMM Registers][sdm-ymm]. [Intel SDM Vol. 2B, MOVDQU and PADDD][sdm-2b]. The shared [decoder](../../crates/loader/src/x86_decode.rs) should retain the prefix family, opcode map, mandatory prefix, operand width and register @@ -39,8 +46,8 @@ both valid prefix lengths for them. Reject reserved maps and encodings, including a physical `LOCK`, `66`, `F2`, `F3` or REX prefix before VEX, through the existing illegal-instruction path. Legal forms outside the implemented subset also stop explicitly. Keep the existing register and effective-address -rules and 15-byte fetch limit. [Intel SDM, Vol. 2, §2.3 and individual -opcode entries](https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html). +rules and 15-byte fetch limit. [Intel SDM Vol. 2A, §2.3, VEX encoding][sdm-2a]. +[Intel SDM Vol. 2B, MOVDQU and PADDD][sdm-2b]. ## First implementation increments @@ -74,11 +81,19 @@ Rust helpers. guest span before publishing a load result or writing a store. A split span across adjacent permitted mappings succeeds. A missing or protected mapping produces the existing guest memory fault at the first inaccessible -byte. A non-canonical address produces `GeneralProtection`. For a later -`VMOVDQA` form, a memory operand must be aligned to its width (16 or 32 -bytes), with a misaligned operand raising `GeneralProtection`. These checks -use guest addresses and permissions. [Intel SDM, Vol. 2, MOVDQU and -MOVDQA](https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html). +byte. For a later `VMOVDQA` form, a memory operand must be aligned to its +width (16 or 32 bytes), with a misaligned operand raising +`GeneralProtection`. [Intel SDM Vol. 2B, MOVDQU and MOVDQA][sdm-2b]. + +Intel's Type 4 rules for `VMOVDQU` specify `#SS(0)` when a memory reference +through the stack segment (SS) has a noncanonical address and `#GP(0)` +for other noncanonical references. The initial BetterXen profile uses the +[existing 48-bit guest address check](../../crates/loader/src/x86_exec.rs) +and reports `GeneralProtection` for either segment case, including a span +whose first byte is canonical and whose last byte is noncanonical. Check +canonicality before guest memory lookup and before committing the move. +Distinct stack-segment exception reporting remains outside this profile. +[Intel SDM Vol. 2A, Table 2-21, Type 4 exceptions][sdm-2a]. Before adding masked moves, use a separate per-lane access contract. For `VPMASKMOVD`, only lanes with the high mask bit set may access memory or @@ -86,8 +101,7 @@ report a memory fault. A clear bit zeroes a load lane and leaves a store lane untouched. A test with lane 4 on an unmapped page must pass with that lane disabled and fault with it enabled. A full-width span check would incorrectly reject the disabled case. Specify store commit behavior before -admitting that form. [Intel SDM, Vol. 2, -VPMASKMOV](https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html). +admitting that form. [Intel SDM Vol. 2C, VPMASKMOV][sdm-2c]. Require interpreter and DBT parity for the exit reason, fault address when reported, RIP, instruction count and complete guest register and memory @@ -109,6 +123,14 @@ and per-thread ownership must agree. Verify the exception behavior for disabled state and invalid `XGETBV` selectors before exposing the facility. AVX2 separately requires `CPUID.(7,0):EBX[5]` and the same OS state. Gate each advertised feature on its full instruction and state contract, -with probes for enabled and disabled combinations. [Intel SDM, Vol. 1, -§14.3 and §14.7.1; Vol. 2, CPUID, XGETBV, XSAVE and -XRSTOR](https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html). +with probes for enabled and disabled combinations. [Intel SDM Vol. 1, +§14.3, AVX detection][sdm-avx]. [Intel SDM Vol. 1, §14.7.1, AVX2 detection][sdm-avx2]. +[Intel SDM Vol. 2A, CPUID][sdm-2a]. [Intel SDM Vol. 2D, XGETBV, XSAVE and XRSTOR][sdm-2d]. + +[sdm-ymm]: https://cdrdv2-public.intel.com/843827/253665-sdm-vol-1-dec-24.pdf#page=376 +[sdm-avx]: https://cdrdv2-public.intel.com/843827/253665-sdm-vol-1-dec-24.pdf#page=359 +[sdm-avx2]: https://cdrdv2-public.intel.com/843827/253665-sdm-vol-1-dec-24.pdf#page=375 +[sdm-2a]: https://cdrdv2-public.intel.com/929353/253666-093-sdm-vol-2a.pdf +[sdm-2b]: https://cdrdv2-public.intel.com/929354/253667-093-sdm-vol-2b.pdf +[sdm-2c]: https://cdrdv2-public.intel.com/929355/326018-093-sdm-vol-2c.pdf +[sdm-2d]: https://cdrdv2-public.intel.com/929356/334569-093-sdm-vol-2d.pdf diff --git a/tests/compat_fixtures/avx/README.md b/tests/compat_fixtures/avx/README.md index 6862cdb..a3a37c8 100644 --- a/tests/compat_fixtures/avx/README.md +++ b/tests/compat_fixtures/avx/README.md @@ -62,6 +62,8 @@ nine steps, including the terminal `HLT`. | 256-bit `VMOVDQU` at a 32-byte-aligned address, at an address offset by one byte, and at `P-16` across adjacent accessible mappings | Same 32 bytes at each address. `P` is the start of the second mapping. | | Split load at `P-16`, with the second mapping unreadable or unmapped | Memory fault at `P`. Every destination bit retains its pre-instruction value. | | Split store at `P-16`, with the second mapping read-only or unmapped | Memory fault at `P`. The 16 writable bytes before `P` retain their sentinels. | +| 256-bit `VMOVDQU` load and store at `0x0000_7fff_ffff_fff0` | Map the first 16 bytes read/write and leave the noncanonical half starting at `0x0000_8000_0000_0000` unmapped. Both operations report `GeneralProtection` under the BetterXen profile. The destination register and the mapped bytes retain their original values. | +| 256-bit `VMOVDQU` load from `[rsp]` with `rsp = 0x0000_8000_0000_0000` | The BetterXen profile reports `GeneralProtection` and preserves the destination. Intel's Type 4 rules specify `#SS(0)` for this SS-based operand. | | Future `VMOVDQA` at aligned and misaligned addresses | An aligned, permitted span transfers the same bytes. A span misaligned by one byte produces `GeneralProtection` and has no data effects. Run at both widths. | | Future masked dword load from `P-16` | With only lanes 0–3 enabled, load four words and zero lanes 4–7 even if the mapping at `P` is absent. Enabling lane 4 faults at `P`. An all-zero mask reads no lanes and returns an all-zero destination. | | Future masked dword store to the same split span | With only lanes 0–3 enabled, write those four words; disabled lanes neither access the second mapping nor alter any bytes there when it is mapped. Enabling lane 4 with its mapping absent faults at `P`. | From 1fe07f45ee4e2162b3788176157348f9d2ac0fa3 Mon Sep 17 00:00:00 2001 From: Thilo Schaeffer <38328877+Thxlx@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:45:05 +0100 Subject: [PATCH 15/15] test: clarify ARM64 assembler offset units Signed-off-by: Thilo Schaeffer <38328877+Thxlx@users.noreply.github.com> --- crates/loader/src/arm64.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/loader/src/arm64.rs b/crates/loader/src/arm64.rs index 3e7026c..8254e61 100644 --- a/crates/loader/src/arm64.rs +++ b/crates/loader/src/arm64.rs @@ -985,6 +985,7 @@ mod tests { let mut asm = Arm64Assembler::new(); // Seed the destination so a W-register load must clear the high bits. asm.movn_64(register, 0, 0); + // Assembler offsets count 32-bit instruction words. let start = asm.current_offset(); asm.load_imm_64(register, value); assert_eq!(