diff --git a/CHANGELOG.md b/CHANGELOG.md index afc7a26..3c2ceca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,8 +11,10 @@ remains unsupported. ### Added - Added File > Open Executable… with Command-O to the app (#252). It opens the focused window's read-only file importer, the same one as that window's button, and is disabled when no window can present it; each window keeps its own importer, so with several windows only the focused one shows the picker. The chosen file goes through the same inspection path as the button, drag and drop and Finder Open With; nothing is executed. A file-importer failure is now shown in red with the system's description instead of being ignored, a cancelled picker shows nothing, and the message clears on the next selection. `BetterXen --smoke-import-result`, run by `scripts/build-app.sh`, checks cancellation, a shown failure and its clearing; it fails on the previous importer handling. Checked locally on Apple Silicon in the running app (Command-O and the menu item open the picker, cancel shows no error, a second Command-O opens it again, with two windows only the focused one presents it, and with every window closed the menu item is disabled); not yet independently reviewed. +- 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. +- 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. @@ -29,6 +31,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`. @@ -42,6 +45,8 @@ 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 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. +- 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. @@ -51,7 +56,9 @@ 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). - Added a `Native app build and smoke` CI job (#248). On the same native `macos-26` runner image and pinned Rust toolchain as the Rust checks, it runs `scripts/build-app.sh`, which builds the locked C ABI library and the Swift app together, bundles and ad-hoc signs `BetterXen.app`, and runs its `--smoke` check, so a Swift compile, link or smoke failure is designed to fail CI (implemented and verified locally; not yet shown on a CI run). `scripts/build-app.sh` also prints `file` and a single `otool -L` listing for the executable, fails if that listing fails or is empty, and fails if the executable links any library outside `/System/Library/` and `/usr/lib/`, naming bundle-relative (`@rpath`, `@executable_path`, `@loader_path`) entries separately (checked locally against stubbed failing, empty, bundle-relative and non-system listings). The job is an app build and smoke result; it runs no Metal fixture and is not GPU verification. +- Added a CPU and loader coverage map (#154) with decoder inventory, native and shared execution paths, and test counts from a pinned Apple M5 run. - 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/app/Sources/Xenora/main.swift b/app/Sources/Xenora/main.swift index ccaf0d4..beb2802 100644 --- a/app/Sources/Xenora/main.swift +++ b/app/Sources/Xenora/main.swift @@ -660,12 +660,43 @@ final class InspectionModel: ObservableObject { } } + /// 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 + /// 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 + } + + var failed: Bool { !busy && fileName != nil && status != Int32(XENORA_OK) } + func inspect(_ url: URL) { + latestRequest &+= 1 + let request = latestRequest selectionError = nil fileName = url.lastPathComponent + report = "" + status = Int32(XENORA_OK) busy = true + let reader = reader Task { - let (newStatus, newReport) = await Task.detached { InspectionModel.run(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. + guard request == latestRequest else { return } status = newStatus report = newReport busy = false @@ -747,6 +778,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)) @@ -1069,6 +1104,93 @@ 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 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 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)") } + + 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 + || (model.status == Int32(XENORA_OK)) != ok { + failures.append("\(label): \(actual)") + } + } + // 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(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") + } + } + // The older read finishes first and must not clear the newer request's busy state. + let model = InspectionModel(reader: reader) + 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) + } + dispatchMain() +} + // `--smoke-import-result` checks how a file-importer result reaches the inspector: // a cancelled picker shows nothing, a failure is shown, and a new selection clears it. // No file is opened or read. diff --git a/crates/cli/src/runner.rs b/crates/cli/src/runner.rs index 45b2a4a..0c02761 100644 --- a/crates/cli/src/runner.rs +++ b/crates/cli/src/runner.rs @@ -2,10 +2,10 @@ 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::{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_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"); 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) } else { launch_worker(&options) }; @@ -99,8 +122,26 @@ pub fn command(args: impl IntoIterator) -> ExitCode { } fn launch_worker(options: &Options) -> Result> { + let journal = options + .report + .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 child = Command::new(std::env::current_exe()?) + let mut command = Command::new(executable); + command .args([ "run", "--experimental", @@ -112,29 +153,73 @@ 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(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() { + 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> { + 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) = 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.map(|()| ExitCode::SUCCESS) +} + 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,14 +243,14 @@ 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(|| { 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 { @@ -232,6 +317,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 +339,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 +364,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..7451986 --- /dev/null +++ b/crates/cli/src/startup_report.rs @@ -0,0 +1,399 @@ +// 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}; + +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; +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, + mut destination: File, + termination: &io::Result, + ) -> io::Result<()> { + destination.write_all(self.read().json(termination).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, Option); + +impl Events { + pub(super) fn open(path: &Path) -> io::Result { + OpenOptions::new() + .write(true) + .create_new(true) + .open(path) + .map(|file| Self(file, None)) + } + + pub(super) fn stage(&mut self, stage: &str) { + self.record(format_args!("{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(); + } + 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() + } +} + +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() { + 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 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", + None, + Some("worker exceeded the wall deadline".into()), + ), + Err(error) => ("unknown", None, Some(error.to_string())), + 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.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() => { + ("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", + 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 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 [ + ("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..af812cb --- /dev/null +++ b/crates/cli/tests/startup_report.rs @@ -0,0 +1,109 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +use std::process::Command; + +const STARTUP_STAGES: &[&str] = &[ + "parsed", + "mapped", + "relocated", + "imports_bound", + "tls_completed", + "entry", +]; + +#[test] +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" + ); + 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; + } +} + +#[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/crates/loader/src/arm64.rs b/crates/loader/src/arm64.rs index 078ce86..8254e61 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,13 @@ 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); + // Assembler offsets count 32-bit instruction words. + 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}" ); diff --git a/docs/README.md b/docs/README.md index 254a1ce..66d5eea 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. @@ -49,7 +50,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. @@ -60,6 +61,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/cpu/avx-contract.md b/docs/cpu/avx-contract.md new file mode 100644 index 0000000..e4a164c --- /dev/null +++ b/docs/cpu/avx-contract.md @@ -0,0 +1,136 @@ +# 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. + +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 +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, +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 +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. 2A, §2.3, VEX encoding][sdm-2a]. +[Intel SDM Vol. 2B, MOVDQU and PADDD][sdm-2b]. + +## 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. 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 +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. 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 +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, 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/docs/interfaces.md b/docs/interfaces.md index bee1b6a..533e053 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -141,6 +141,31 @@ 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 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. + +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`, +`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. + `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 diff --git a/docs/research/texture-formats.md b/docs/research/texture-formats.md new file mode 100644 index 0000000..2dc5d6e --- /dev/null +++ b/docs/research/texture-formats.md @@ -0,0 +1,96 @@ +# 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. +- **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 | 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`](../../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`](../../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`](../../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 | — | + +## 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](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 + +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`](../../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 diff --git a/docs/testing/cpu-coverage.md b/docs/testing/cpu-coverage.md index 96b8558..4a90989 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,168 @@ 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`, +on the branch holding this change, based on upstream `main` at +`67b8cff` (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 # 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". +The default run recorded 34 ignored tests. + +| Count | Category | Files | +| --- | --- | --- | +| 26 | Native Metal correctness | Five in `crates/loader/tests/` (`dbt_render.rs`, `graphics_d3d12.rs`, `graphics_textures.rs`, `runtime_x15.rs`), seven in `tests/validation/known_answers.rs`, and fourteen across `tests/validation/tests/` (`operand_domains.rs`, `sop1_unary.rs`, `sop2_arith.rs`, `sop2_stage_c.rs`, `sopc_stage_d.rs`, `sopk.rs`, `vop1_integer.rs`, `vop2_integer.rs`, `vop2_vcc.rs`, `vop3_compare.rs`, `vop3_integer.rs`, `vopc_f_t.rs`, `vopc_wide.rs`). | +| 5 | LLVM AMDGPU oracle | Two in `crates/decoder/tests/gfx1030.rs` and one each in `crates/isa/tests/extension_word_negative.rs`, `meta_corpus.rs` and `meta_llvm.rs`. | +| 3 | Manual CPU timing | Warm guest memory in `crates/loader/src/memory.rs`, relocation in `crates/loader/src/reloc.rs` and TLS templates in `crates/loader/src/tls.rs`. | + +The two manual GPU timing tests in `crates/metal/tests/native_compute.rs` +are outside these totals. Cargo requires the `gpu-tests` feature to build +that target. + +### 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 + +Of the 213 declared operations, **93 have at least one ARM64-lowered form**. +Some other forms of those operations still use the shared interpreter helper. +**119 operations use the helper for every translated form**, and **one**, +`SYSCALL`, is decoded but refused by `is_translatable` in the DBT. Helper +calls count toward `DbtMetrics::interpreter_fallbacks`. The conditional gates +in `is_native` in `crates/loader/src/dbt.rs` apply at form level. + +- `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 can read a memory operand and uses the helper. +- `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, 838 named 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 | +| `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` | + +Count named known-answer rows, including both byte-encoded and decoded cases, +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 +``` + +The cache revalidation change in [PR #269](https://github.com/MacosPorters/betterxen/pull/269) +restored `dbt_executes_modified_code_after_a_jump`. It passed in this run, +and `cpu_known_answers.rs` reported 50 passes and zero ignores. + +### 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 also exempts `LDMXCSR`, `Jcc`, `JMP`, +`CALL`, `RET`, `HLT` and `SYSCALL`. It checks the remaining forms against 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`), 9 named `rcl*` cases and 8 named `shld*` or `shrd*` cases using the rule above, +and 72 SHLD/SHRD assembly fixture lines; 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. diff --git a/scripts/build-app.sh b/scripts/build-app.sh index d37df6f..2059403 100755 --- a/scripts/build-app.sh +++ b/scripts/build-app.sh @@ -72,5 +72,6 @@ for dependency in $dependencies; do esac done "$binary" --smoke +"$binary" --smoke-inspection-order "$binary" --smoke-import-result echo "build-app: built $bundle" diff --git a/tests/compat_fixtures/avx/README.md b/tests/compat_fixtures/avx/README.md new file mode 100644 index 0000000..a3a37c8 --- /dev/null +++ b/tests/compat_fixtures/avx/README.md @@ -0,0 +1,90 @@ +# 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. | +| 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`. | +| 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.