diff --git a/CHANGELOG.md b/CHANGELOG.md index 72bf118..453a6ec 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,7 @@ remains unsupported. - Moved the six hand-written gfx1030 VOP2 logical and shift forms (`v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`, `v_ashrrev_i32`, AMD guide section 12.7) into the semantic registry under a new VGPR-only operand rule `vop2_vgpr2`, with no behaviour change: a sweep of 132,608 VOP2, VOP1 and SOP1 words decodes to the same text, length and error before and after, the MSL goldens are unchanged, and the runtime-region allowlist admits exactly the same six forms. The per-lane `VectorBinary` gained `And`, `Or`, `Xor` and the three shifts (count masked to S0[4:0]); 6 hand-written instruction variants and their decoder and lowering arms are gone (17 hand-written forms remain). Part of #215. - Added non-blocking Metal compute submission through `submit_words` and `wait`, with completion-aware resource retirement and a sixteen-dispatch in-flight limit. Synchronous calls keep their existing behavior. The benchmark reports the host submission split and compares synchronous and pipelined batches. - Reuse up to 16 native Metal compute pipelines per context for repeated shader source and entry points. Pending dispatches retain their pipelines through completion, including after eviction. Dispatch profiles report zero library and pipeline setup time when a cached pipeline is reused. Closes #132. +- Avoided resolver allocations for permitted guest data reads and writes contained in one mapping, preserving checked fallback for split spans and faults (#105). - 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 @@ -31,6 +32,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 shader IR constant folding (`CompileOptions::fold_constants` / `compile_with`) for pure vector unary and binary ops whose operands are already constants (#141). Floating-point ops still use the exact positive-normal rules; loads, stores, lane masks, merges and branches are never folded. Default `compile` keeps the historical IR. Covered by hand-computed known-answer compiler tests (shifts by 32/33, ashr, min_i32 vs min_u32, mul_hi_i32_i24, ffbh_i32, exact float fold, load-derived float non-fold, and verify rejection of inexact constant float add) with a fold-on versus fold-off check, plus an MSL template drift check over every foldable op. - The loader now maps an image's PE headers at its image base (#333): the first `SizeOfHeaders` bytes of the file, read-only, in whole 4 KiB pages that are zero past `SizeOfHeaders`. Programs read their own headers this way; the mingw-w64 C runtime does so before `main`, and until now that read faulted. When startup relocates an image it writes the load base into the mapped `ImageBase` field after the relocations, so an entry aimed at that field cannot move it twice; this is Xenora's policy and has not been compared with Windows. A load is refused with the new `PeError::InvalidHeaderSize` when `SizeOfHeaders` is zero, ends before the section table, runs past the file, or its pages would reach into a section, and when the bytes handed to the loader are not the PE32+ headers that were parsed. The page rule refuses images with sub-page section alignment whose first section starts inside the header page, which loaded before. The header pages count toward the 256 MiB mapping budget, which is checked before anything is mapped. `ParsedPe::parse` and the static probe are unchanged. `tests/pe_headers.rs` covers guest reads at the preferred and a relocated base, a relocation aimed at `ImageBase`, the write and execute faults and each refusal with original hand-built images; the image in `pe_mapping_limits.rs` now carries a valid `SizeOfHeaders`. Awaiting independent re-review. - Added 35 known-answer cases for MOV with an immediate operand, opcodes C6 /0 and C7 /0 (#194), to `cpu_known_answers.rs`: byte, word, dword and qword stores through base, SIB, R12, R13, RSP and RBP addressing with 8-bit and 32-bit displacements; the imm32 sign extension of the 64-bit form; the register forms, including AH and a REX-selected SIL; unmapped and read-only store faults at each width; and #UD for reg field 1. Expected values come from the Intel SDM and were worked out by hand. The interpreter and the DBT already agreed with all of them, so this is new coverage and fixes no defect. The 16-bit forms covered are those that already run, and #118 stays open. Not compared with x86 hardware; awaiting independent review. - `dbt_bench` can also write its results as one JSON document when `XENORA_DBT_BENCH_JSON=` is set (#112). The document records the host CPU, OS and architecture, the git revision and whether the tree had local changes, debug assertions, the workload and sample counts, the median, minimum, maximum, p95, p99, IQR and MIPS for the interpreter and for cold and warm DBT, and the cold DBT counters. Anything the benchmark cannot determine is `null`. The text output and the timed work are unchanged. @@ -99,6 +101,8 @@ remains unsupported. - Added guest module lookup and named symbol resolution for built-in Kernel32 and UCRT services. +- Added process exit and the first Gate A milestone, A1 (#329). `kernel32.dll!ExitProcess` stops the guest with the new `ExitReason::ProcessExit(status)`, carrying all 32 bits of the status, and never ends the host; a returning entry point does the same with EAX. The exit closes every guest handle, including Winsock sockets and task-queue handles, and the engine that ran the guest executes nothing further. A TLS callback that exits ends startup with that exit as its outcome, and the remaining callbacks and the entry point do not run. Startup reserves the page holding the return addresses the engine intercepts, so an image mapped over them is refused. `atexit` functions are not run. A1 is an original C program with no C library linked (`tests/compat_fixtures/gate_a1.c`): `crates/loader/tests/gate_a1.rs` builds it from source with clang and an LLD on every run, executes it through the loader, the standard services and the DBT at `-O0`, `-O1`, `-O2` and `-Os`, and checks its exit status, its report, its files and its memory against values recomputed in Rust. `docs/testing/gate-a.md` records what A1 shows and that Gate A stays open until the hosted milestone, A2, passes. Verified locally with two compilers; awaiting independent review. + - Added same-process guest file handle duplication with a shared file position. - Added guest file and directory enumeration with typed search handles. diff --git a/crates/loader/src/cpu.rs b/crates/loader/src/cpu.rs index 047f671..1c44b00 100644 --- a/crates/loader/src/cpu.rs +++ b/crates/loader/src/cpu.rs @@ -173,6 +173,9 @@ pub enum ExitReason { SimdException, /// A host service changed a register the Win64 ABI requires it to preserve. ServiceAbiViolation, + /// The guest ended its own process with this exit status. Only the guest + /// stops; the host keeps running. + ProcessExit(u32), /// A service has to wait; it had no effect and runs again later. GuestBlocked, /// A service completed and asked the scheduler for a turn. @@ -194,6 +197,7 @@ impl fmt::Display for ExitReason { Self::DivideError => write!(f, "guest divide error"), Self::GeneralProtection => write!(f, "guest general-protection fault"), Self::SimdException => write!(f, "guest SIMD floating-point exception"), + Self::ProcessExit(status) => write!(f, "guest process exited with status {status}"), Self::ServiceAbiViolation => { write!(f, "host service changed a nonvolatile guest register") } diff --git a/crates/loader/src/dbt.rs b/crates/loader/src/dbt.rs index a357f7f..16e9452 100644 --- a/crates/loader/src/dbt.rs +++ b/crates/loader/src/dbt.rs @@ -48,6 +48,8 @@ pub struct DbtEngine { services: HashMap, pub import_registry: Option, pub metrics: DbtMetrics, + /// Exit status of a guest that ended its process on this engine. + exited: Option, } impl DbtEngine { @@ -62,6 +64,7 @@ impl DbtEngine { services: HashMap::new(), import_registry: None, metrics: DbtMetrics::default(), + exited: None, }) } @@ -79,6 +82,9 @@ impl DbtEngine { } /// Execute guest code starting at CPU RIP until HLT, budget exhaustion, or fault. + /// + /// Once the guest has ended its process, this engine executes nothing + /// further: every later call reports the same exit. pub fn run( &mut self, cpu: &mut CpuState, @@ -101,12 +107,36 @@ impl DbtEngine { self.run_bounded(cpu, memory, max_instructions, false) } + /// Both entry points go through the process-exit latch: once the guest + /// process has exited, no guest instruction runs again, whichever guest + /// thread the caller tries to run. fn run_bounded( &mut self, cpu: &mut CpuState, memory: &mut GuestMemory, max_instructions: usize, exact: bool, + ) -> ExecutionResult { + if let Some(status) = self.exited { + return ExecutionResult { + instructions_executed: 0, + final_state: cpu.clone(), + exit_reason: ExitReason::ProcessExit(status), + }; + } + let result = self.execute(cpu, memory, max_instructions, exact); + if let ExitReason::ProcessExit(status) = result.exit_reason { + self.exited = Some(status); + } + result + } + + fn execute( + &mut self, + cpu: &mut CpuState, + memory: &mut GuestMemory, + max_instructions: usize, + exact: bool, ) -> ExecutionResult { let mut instructions_count = 0; diff --git a/crates/loader/src/imports.rs b/crates/loader/src/imports.rs index 81d6f81..a712fff 100644 --- a/crates/loader/src/imports.rs +++ b/crates/loader/src/imports.rs @@ -196,6 +196,15 @@ fn trampoline_address(index: usize) -> u64 { } const CALLBACK_RETURN: u64 = IMPORT_TRAMPOLINE_BASE_VA - IMPORT_TRAMPOLINE_STRIDE; +/// Return address placed under a process entry point. Reaching it ends the +/// process with EAX as its exit status. +pub const ENTRY_RETURN: u64 = CALLBACK_RETURN - IMPORT_TRAMPOLINE_STRIDE; +/// The 4 KiB page that holds [`ENTRY_RETURN`] and the callback return +/// address. The engine intercepts those two addresses before it executes +/// anything there, so startup reserves the page: guest code mapped over it +/// would never run. +pub const RETURN_SENTINEL_PAGE: u64 = ENTRY_RETURN & !0xFFF; +const _: () = assert!(CALLBACK_RETURN & !0xFFF == RETURN_SENTINEL_PAGE); /// Nested guest callbacks allowed in one guest thread. const MAX_CALLBACK_DEPTH: usize = 32; @@ -646,6 +655,7 @@ impl ImportRegistry { /// Check if target RIP matches a synthetic service trampoline. pub fn is_service_trampoline(&self, rip: u64) -> bool { rip == CALLBACK_RETURN + || rip == ENTRY_RETURN || self.trampoline_to_service.contains_key(&rip) || self.dynamic_trampolines.get(rip).is_some() } @@ -657,6 +667,22 @@ impl ImportRegistry { cpu: &mut CpuState, memory: &mut GuestMemory, ) -> Result<(), ExitReason> { + if rip == ENTRY_RETURN { + // The entry point returned. Its result is the exit status, and it + // goes through ExitProcess when that is registered so both ways of + // ending do the same cleanup. + let status = cpu.get(Register::Rax) as u32; + let exit = ExitReason::ProcessExit(status); + let Some(index) = self.index("kernel32.dll", &ImportName::Name("ExitProcess".into())) + else { + return Err(exit); + }; + let mut args = Win64Args::new(cpu); + args.rcx = u64::from(status); + return Err((self.handlers[index].handler)(&args, cpu, memory) + .err() + .unwrap_or(exit)); + } if rip == CALLBACK_RETURN { let key = (cpu.gs_base, cpu.get(Register::Rsp)); let frame = memory diff --git a/crates/loader/src/memory.rs b/crates/loader/src/memory.rs index 76ff4ab..225adf0 100644 --- a/crates/loader/src/memory.rs +++ b/crates/loader/src/memory.rs @@ -5,7 +5,7 @@ //! Provides isolated, page-aligned guest virtual memory with permission checking //! (Read, Write, Execute) and bounds enforcement without host OS mapping tricks. -use std::fmt; +use std::{fmt, ops::Range}; pub(crate) const ALLOCATION_GRANULARITY: u64 = 65_536; @@ -520,14 +520,39 @@ impl GuestMemory { /// Write raw bytes into guest memory at the specified address, checking permissions. pub fn write_bytes(&mut self, address: u64, src: &[u8]) -> Result<(), MemoryError> { + if let Some((index, range)) = self.contiguous_region(address, src.len()) + && self.regions[index].permissions.write + { + self.regions[index].data[range].copy_from_slice(src); + return Ok(()); + } self.write_checked(address, src, Some("write")) } /// Read raw bytes from guest memory at the specified address, checking permissions. pub fn read_bytes(&self, address: u64, dst: &mut [u8]) -> Result<(), MemoryError> { + if let Some((index, range)) = self.contiguous_region(address, dst.len()) + && self.regions[index].permissions.read + { + dst.copy_from_slice(&self.regions[index].data[range]); + return Ok(()); + } self.read_checked(address, dst, Some("read")) } + // Only the first eligible mapping may supply the whole span. Otherwise + // the checked resolver must preserve split-access and overlap priority. + fn contiguous_region(&self, address: u64, len: usize) -> Option<(usize, Range)> { + let (index, region) = self + .regions + .iter() + .enumerate() + .find(|(_, region)| region.base + region.data.len() as u64 > address)?; + let offset = usize::try_from(address.checked_sub(region.base)?).ok()?; + let end = offset.checked_add(len)?; + (end <= region.data.len()).then_some((index, offset..end)) + } + /// Read an instruction byte from guest memory, verifying execute permission. pub fn fetch_instruction_byte(&self, address: u64) -> Result { address.checked_add(1).ok_or(MemoryError::Overflow)?; @@ -869,3 +894,590 @@ mod instruction_fetch_tests { assert_eq!(m.fetch_instruction_byte(BASE + 3), Ok(0x44)); } } + +#[cfg(test)] +mod data_access_contract_tests { + use super::{MemoryPermissions as P, *}; + const A: u64 = 0x10_0000; + + #[test] + fn data_permissions_are_independent_and_failed_reads_leave_output_untouched() { + for bits in 0..8 { + let p = P { + read: bits & 1 != 0, + write: bits & 2 != 0, + execute: bits & 4 != 0, + }; + let mut m = GuestMemory::new(); + m.map_region_with_data(A, 4, p, &[1, 2, 3, 4]).unwrap(); + let mut out = [0xee; 2]; + let read = m.read_bytes(A + 1, &mut out); + assert_eq!( + read, + if p.read { + Ok(()) + } else { + Err(MemoryError::PermissionViolation { + address: A + 1, + required: "read", + }) + } + ); + assert_eq!(out, if p.read { [2, 3] } else { [0xee; 2] }); + let write = m.write_bytes(A + 1, &[0x55, 0x66]); + assert_eq!( + write, + if p.write { + Ok(()) + } else { + Err(MemoryError::PermissionViolation { + address: A + 1, + required: "write", + }) + } + ); + let mut stored = [0; 4]; + m.read_checked(A, &mut stored, None).unwrap(); + assert_eq!( + stored, + if p.write { + [1, 0x55, 0x66, 4] + } else { + [1, 2, 3, 4] + } + ); + } + } + + #[test] + fn empty_data_spans_keep_inclusive_ends_and_ignore_permissions() { + let mut m = GuestMemory::new(); + m.map_region(A, 0, P::NO_ACCESS).unwrap(); + m.map_region(A + 16, 3, P::NO_ACCESS).unwrap(); + m.map_region(u64::MAX, 0, P::NO_ACCESS).unwrap(); + for at in [A, A + 16, A + 17, A + 19, u64::MAX] { + assert_eq!(m.read_bytes(at, &mut []), Ok(())); + assert_eq!(m.write_bytes(at, &[]), Ok(())); + } + for at in [A - 1, A + 1, A + 15, A + 20] { + assert_eq!( + m.read_bytes(at, &mut []), + Err(MemoryError::UnmappedAddress(at)) + ); + assert_eq!( + m.write_bytes(at, &[]), + Err(MemoryError::UnmappedAddress(at)) + ); + } + } + + #[test] + fn data_address_overflow_precedes_permissions_and_preserves_output() { + let mut m = GuestMemory::new(); + m.map_region(u64::MAX - 3, 3, P::NO_ACCESS).unwrap(); + let mut out = [0xee; 2]; + assert_eq!( + m.read_bytes(u64::MAX - 1, &mut out), + Err(MemoryError::Overflow) + ); + assert_eq!(out, [0xee; 2]); + assert_eq!( + m.write_bytes(u64::MAX - 1, &[1, 2]), + Err(MemoryError::Overflow) + ); + assert_eq!( + m.read_bytes(u64::MAX, &mut out[..1]), + Err(MemoryError::Overflow) + ); + assert_eq!(m.write_bytes(u64::MAX, &[1]), Err(MemoryError::Overflow)); + assert_eq!(m.read_u16(u64::MAX - 1), Err(MemoryError::Overflow)); + } + + #[test] + fn split_data_accesses_keep_exact_fallback_errors_and_atomicity() { + for (gap, right) in [ + (0, P::READ_WRITE), + (0, P::READ_ONLY), + (0, P::NO_ACCESS), + ( + 0, + P { + read: false, + write: true, + execute: false, + }, + ), + (1, P::READ_WRITE), + ] { + let mut m = GuestMemory::new(); + m.map_region_with_data(A, 8, P::READ_WRITE, &[0, 1, 2, 3, 4, 5, 6, 7]) + .unwrap(); + let b = A + 8 + gap; + m.map_region_with_data(b, 8, right, &[8, 9, 10, 11, 12, 13, 14, 15]) + .unwrap(); + let mut expected = m.clone(); + let mut actual_out = [0xee; 4]; + let mut expected_out = [0xee; 4]; + assert_eq!( + m.read_bytes(A + 6, &mut actual_out), + expected.read_checked(A + 6, &mut expected_out, Some("read")) + ); + assert_eq!(actual_out, expected_out); + assert_eq!( + actual_out, + if gap == 0 && right.read { + [6, 7, 8, 9] + } else { + [0xee; 4] + } + ); + let bytes = [0xa0, 0xa1, 0xa2, 0xa3]; + assert_eq!( + m.write_bytes(A + 6, &bytes), + expected.write_checked(A + 6, &bytes, Some("write")) + ); + let written = gap == 0 && right.write; + assert_eq!( + m.read_u64_bypass(A).unwrap().to_le_bytes(), + if written { + [0, 1, 2, 3, 4, 5, 0xa0, 0xa1] + } else { + [0, 1, 2, 3, 4, 5, 6, 7] + } + ); + assert_eq!( + m.read_u64_bypass(b).unwrap().to_le_bytes(), + if written { + [0xa2, 0xa3, 10, 11, 12, 13, 14, 15] + } else { + [8, 9, 10, 11, 12, 13, 14, 15] + } + ); + } + } + + #[test] + fn data_accesses_keep_first_mapping_priority_for_partial_overlaps() { + const BASE: u64 = 0x0000_0003_0000_0000; + for first in [P::READ_WRITE, P::READ_ONLY] { + let mut m = GuestMemory::new(); + m.map_region(0x1000, 1, P::NO_ACCESS).unwrap(); + m.map_region_with_data(BASE, 4, first, &[1, 2, 3, 4]) + .unwrap(); + let empty = m.map_heap_allocation(PROCESS_HEAP, 0).unwrap(); + assert_eq!(empty, BASE); + assert_eq!( + m.resize_heap_allocation(PROCESS_HEAP, empty, 8, true), + Ok(BASE) + ); + let mut out = [0xee; 8]; + assert_eq!(m.read_bytes(BASE, &mut out), Ok(())); + assert_eq!(out, [1, 2, 3, 4, 0, 0, 0, 0]); + assert_eq!(m.read_u16(BASE), Ok(0x0201)); + let bytes = [0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7]; + let mut expected = m.clone(); + assert_eq!( + m.write_bytes(BASE, &bytes), + expected.write_checked(BASE, &bytes, Some("write")) + ); + m.read_bytes(BASE, &mut out).unwrap(); + assert_eq!( + out, + if first.write { + bytes + } else { + [1, 2, 3, 4, 0, 0, 0, 0] + } + ); + } + } + + #[test] + fn data_accesses_observe_writes_clones_release_and_remap() { + let mut m = GuestMemory::new(); + m.map_region_with_data(A, 8, P::READ_WRITE, &[1; 8]) + .unwrap(); + let mut clone = m.clone(); + m.write_u64(A, 0x1122_3344_5566_7788).unwrap(); + clone.write_u32(A, 0xaabb_ccdd).unwrap(); + assert_eq!(m.read_u64(A), Ok(0x1122_3344_5566_7788)); + assert_eq!(clone.read_u64(A), Ok(0x0101_0101_aabb_ccdd)); + let b = m.map_virtual_allocation(0x4000, 2, P::READ_WRITE).unwrap(); + m.write_u16(b, 0x1234).unwrap(); + assert_eq!(m.read_u16(b), Ok(0x1234)); + assert!(m.release_virtual_allocation(b)); + assert_eq!(m.read_u16(b), Err(MemoryError::UnmappedAddress(b))); + m.map_region_with_data(b, 2, P::READ_ONLY, &[0x56, 0x78]) + .unwrap(); + assert_eq!(m.read_u16(b), Ok(0x7856)); + assert_eq!( + m.write_u8(b, 0), + Err(MemoryError::PermissionViolation { + address: b, + required: "write" + }) + ); + assert_eq!(clone.read_u16(b), Err(MemoryError::UnmappedAddress(b))); + } +} + +#[cfg(test)] +mod data_memory_bench { + use super::{MemoryPermissions as P, *}; + use crate::{CpuState, DbtEngine, ExitReason, Register}; + use std::{hint::black_box, time::Instant}; + + const CODE: u64 = 0x1000; + const VALUE: u64 = 0xffff_ff00; + #[derive(Clone, Copy)] + enum Kind { + Registers, + Counter, + Sequential, + Split, + } + + fn setting(name: &str, default: usize, maximum: usize) -> usize { + let value = std::env::var(name).map_or(default, |s| s.parse().expect(name)); + assert!((1..=maximum).contains(&value), "invalid {name}"); + value + } + fn quantile(sorted: &[f64], fraction: f64) -> f64 { + let rank = (sorted.len() - 1) as f64 * fraction; + let lo = rank.floor() as usize; + sorted[lo] + (sorted[rank.ceil() as usize] - sorted[lo]) * rank.fract() + } + fn guest(kind: Kind, iterations: usize, data: u64) -> (Vec, usize) { + // MOV RCX, iterations; MOV RDX, VALUE (control) or RSI, data; XOR EAX,EAX. + let registers = matches!(kind, Kind::Registers); + let sequential = matches!(kind, Kind::Sequential); + let mut code = vec![0x48, 0xb9]; + code.extend_from_slice(&(iterations as u64).to_le_bytes()); + code.extend_from_slice(&[0x48, if registers { 0xba } else { 0xbe }]); + let target = if registers { VALUE } else { data }; + code.extend_from_slice(&target.to_le_bytes()); + code.extend_from_slice(&[0x31, 0xc0]); + let per_iteration = if registers { + // ADD RAX,RDX; ADD RDX,1; DEC RCX; JNZ -12. + code.extend_from_slice(&[ + 0x48, 0x01, 0xd0, 0x48, 0x83, 0xc2, 0x01, 0x48, 0xff, 0xc9, 0x75, 0xf4, + ]); + 4 + } else { + // MOV RDX,[RSI]; ADD RAX,RDX; ADD RDX,1; MOV [RSI],RDX. + code.extend_from_slice(&[ + 0x48, 0x8b, 0x16, 0x48, 0x01, 0xd0, 0x48, 0x83, 0xc2, 0x01, 0x48, 0x89, 0x16, + ]); + if sequential { + code.extend_from_slice(&[0x48, 0x83, 0xc6, 0x08]); // ADD RSI,8. + } + // DEC RCX; JNZ -22 (sequential) or -18 (counter). + let back = if sequential { 0xea } else { 0xee }; + code.extend_from_slice(&[0x48, 0xff, 0xc9, 0x75, back]); + 6 + usize::from(sequential) + }; + code.push(0xf4); // HLT; three setup instructions and one halt. + (code, iterations * per_iteration + 4) + } + + // Run identical source on the baseline and candidate with the same release profile. + // Allocation counting is deliberately separate: instrumentation distorts these timings. + #[test] + #[ignore = "manual, correctness-gated warm DBT data-memory timing"] + fn warm_data_memory_benchmark() { + let samples = setting("XENORA_DATA_BENCH_SAMPLES", 31, 1001); + let counter = setting("XENORA_DATA_BENCH_ITERS", 32768, 65536); + let sequential = setting("XENORA_DATA_BENCH_STREAM_ITERS", 16384, 65536); + for (label, kind, regions, last) in [ + ("register-control", Kind::Registers, 4, false), + ("counter-front", Kind::Counter, 4, false), + ("counter-front-many", Kind::Counter, 64, false), + ("counter-first", Kind::Counter, 4, false), + ("counter-first-many", Kind::Counter, 64, false), + ("counter-third-many", Kind::Counter, 64, false), + ("counter-middle", Kind::Counter, 64, false), + ("counter-last", Kind::Counter, 64, true), + ("sequential-front", Kind::Sequential, 4, false), + ("sequential-front-many", Kind::Sequential, 64, false), + ("sequential-first", Kind::Sequential, 4, false), + ("sequential-first-many", Kind::Sequential, 64, false), + ("sequential-last", Kind::Sequential, 64, true), + ("split-counter-control", Kind::Split, 4, false), + ] { + let iterations = if matches!(kind, Kind::Sequential) { + sequential + } else { + counter + }; + let code_address = if label.contains("-first") { + 0x8000_0000 + } else { + CODE + }; + let data = if last { + 0x4000_0000 + } else if label.contains("-third") { + 0x20_1000 + } else if label.contains("-middle") { + 0x23_f000 + } else { + 0x1_0000 + }; + let (code, expected_instructions) = guest(kind, iterations, data); + let words = if matches!(kind, Kind::Sequential) { + iterations + } else { + 1 + }; + let initial: Vec = (0..words) + .flat_map(|i| (VALUE + i as u64).to_le_bytes()) + .collect(); + let increment = match kind { + Kind::Registers => 0, + Kind::Sequential => 1, + _ => iterations as u64, + }; + let expected: Vec = (0..words) + .flat_map(|i| (VALUE + i as u64 + increment).to_le_bytes()) + .collect(); + let mut memory = GuestMemory::new(); + memory + .map_region_with_data(code_address, 4096, P::READ_EXECUTE, &code) + .unwrap(); + let pieces = if matches!(kind, Kind::Split) { + memory + .map_region_with_data(data, 4, P::READ_WRITE, &initial[..4]) + .unwrap(); + memory + .map_region_with_data(data + 4, 4, P::READ_WRITE, &initial[4..]) + .unwrap(); + 2 + } else { + memory + .map_region_with_data(data, initial.len(), P::READ_WRITE, &initial) + .unwrap(); + 1 + }; + for i in 0..regions - pieces - 1 { + memory + .map_region(0x20_0000 + i as u64 * 8192, 4096, P::READ_ONLY) + .unwrap(); + } + let initial_cpu = CpuState::new(code_address, 0x8000_0000); // No stack instructions. + let mut dbt = DbtEngine::new(1024 * 1024).unwrap(); + let mut readback = vec![0; initial.len()]; + let n = iterations as u64; + let sum = n * VALUE + n * (n - 1) / 2; + let mut timings = Vec::with_capacity(samples); + let warmups = 5; + for sample in 0..samples + warmups { + memory.write_bytes(data, &initial).unwrap(); + let mut cpu = initial_cpu.clone(); + let before = dbt.metrics; + let started = Instant::now(); + let result = black_box(dbt.run(&mut cpu, &mut memory, expected_instructions + 16)); + let elapsed = started.elapsed(); + assert_eq!(result.exit_reason, ExitReason::Halt, "{label}"); + assert_eq!( + result.instructions_executed, expected_instructions, + "{label}" + ); + let state = ( + cpu.get(Register::Rax), + cpu.get(Register::Rdx), + cpu.get(Register::Rcx), + ); + assert_eq!(state, (sum, VALUE + n, 0), "{label}"); + memory.read_bytes(data, &mut readback).unwrap(); + assert_eq!(readback, expected, "{label}"); + assert_eq!(dbt.metrics.interpreter_fallbacks, 0, "{label}"); + if sample > 0 { + let compiled = |m: crate::DbtMetrics| { + (m.blocks_compiled, m.native_bytes_emitted, m.cache_misses) + }; + assert_eq!(compiled(dbt.metrics), compiled(before), "{label}"); + if sample >= warmups { + timings.push(elapsed.as_nanos() as f64 / n as f64); + } + } else { + assert!(dbt.metrics.blocks_compiled > 0, "{label}"); + } + } + timings.sort_by(f64::total_cmp); + println!( + "warm-data label={label} regions={regions} iterations={iterations} samples={samples} warmups={warmups} instructions={expected_instructions} median_ns_per_iteration={:.3} p10={:.3} p90={:.3}", + quantile(&timings, 0.5), + quantile(&timings, 0.1), + quantile(&timings, 0.9) + ); + } + } +} + +#[cfg(test)] +mod mapping_group_contract_tests { + use super::*; + + #[test] + fn aliases_preserve_bytes_across_resize_relocation_and_release() { + const BASE: u64 = 0x0000_0003_0000_0000; + let mut memory = GuestMemory::new(); + memory + .map_region(BASE - 16, 8, MemoryPermissions::READ_ONLY) + .unwrap(); + memory + .map_region_with_data(BASE, 4, MemoryPermissions::READ_ONLY, &[1, 2, 3, 4]) + .unwrap(); + memory + .map_region(BASE + 16, 8, MemoryPermissions::READ_ONLY) + .unwrap(); + let heap = memory.create_private_heap(0).unwrap(); + assert_eq!(memory.map_heap_allocation(PROCESS_HEAP, 0), Ok(BASE)); + assert_eq!(memory.map_heap_allocation(heap, 0), Ok(BASE)); + assert_eq!( + memory.resize_heap_allocation(PROCESS_HEAP, BASE, 8, true), + Err(MemoryError::AllocationFailed) + ); + assert_eq!(memory.resize_heap_allocation(heap, BASE, 8, true), Ok(BASE)); + memory.write_bytes(BASE + 4, &[5, 6, 7, 8]).unwrap(); + assert_eq!(memory.read_u64(BASE), Ok(0x0807_0605_0403_0201)); + assert_eq!( + memory.resize_heap_allocation(heap, BASE, 32, true), + Err(MemoryError::AllocationFailed) + ); + let moved = memory + .resize_heap_allocation(heap, BASE, 32, false) + .unwrap(); + assert_ne!(moved, BASE); + let mut bytes = [0xff; 32]; + memory.read_bytes(moved, &mut bytes).unwrap(); + let mut expected = [0; 32]; + expected[4..8].copy_from_slice(&[5, 6, 7, 8]); + assert_eq!(bytes, expected); + let mut failed = [0xff; 8]; + assert_eq!( + memory.read_bytes(BASE, &mut failed), + Err(MemoryError::UnmappedAddress(BASE + 4)) + ); + assert_eq!(failed, [0xff; 8]); + assert_eq!( + memory.resize_heap_allocation(PROCESS_HEAP, BASE, 8, true), + Ok(BASE) + ); + assert_eq!(memory.read_u64(BASE), Ok(0x0403_0201)); + assert_eq!( + memory.resize_heap_allocation(PROCESS_HEAP, BASE, 2, true), + Ok(BASE) + ); + assert_eq!(memory.read_u16(BASE + 2), Ok(0x0403)); + assert!(memory.release_heap_allocation(PROCESS_HEAP, BASE)); + assert_eq!(memory.read_u32(BASE), Ok(0x0403_0201)); + assert_eq!(memory.read_u64(BASE - 16), Ok(0)); + assert_eq!(memory.read_u64(BASE + 16), Ok(0)); + } +} + +#[cfg(test)] +mod bounds_access_contract_tests { + use super::*; + + #[test] + fn permitted_empty_spans_and_high_addresses_keep_exact_bounds() { + let mut memory = GuestMemory::new(); + memory + .map_region_with_data( + u64::MAX - 8, + 8, + MemoryPermissions::READ_WRITE, + &[1, 2, 3, 4, 5, 6, 7, 8], + ) + .unwrap(); + for at in [u64::MAX - 8, u64::MAX - 4, u64::MAX - 1, u64::MAX] { + assert_eq!(memory.read_bytes(at, &mut []), Ok(())); + assert_eq!(memory.write_bytes(at, &[]), Ok(())); + } + assert_eq!(memory.read_u64(u64::MAX - 8), Ok(0x0807_0605_0403_0201)); + assert_eq!(memory.read_u8(u64::MAX - 1), Ok(8)); + let mut failed = [0xee; 2]; + assert_eq!( + memory.read_bytes(u64::MAX - 1, &mut failed), + Err(MemoryError::Overflow) + ); + assert_eq!(failed, [0xee; 2]); + assert_eq!( + memory.write_u16(u64::MAX - 1, 0xffff), + Err(MemoryError::Overflow) + ); + assert_eq!(memory.read_u64(u64::MAX - 7), Err(MemoryError::Overflow)); + assert_eq!( + memory.write_u64(u64::MAX - 7, u64::MAX), + Err(MemoryError::Overflow) + ); + memory.write_u8(u64::MAX - 1, 0x99).unwrap(); + let mut actual = [0; 8]; + memory.read_bytes(u64::MAX - 8, &mut actual).unwrap(); + assert_eq!(actual, [1, 2, 3, 4, 5, 6, 7, 0x99]); + } +} + +#[cfg(test)] +mod mapping_search_contract_tests { + use super::*; + + #[test] + fn every_mapping_and_gap_keeps_its_bytes_across_table_sizes() { + const BASE: u64 = 0x40_0000; + for count in [0usize, 1, 2, 3, 4, 5, 7, 8, 9, 15, 16, 17, 31, 32, 33] { + let mut memory = GuestMemory::new(); + for index in (0..count).rev() { + memory + .map_region_with_data( + BASE + index as u64 * 0x100, + 8, + MemoryPermissions::READ_WRITE, + &[(index + 1) as u8; 8], + ) + .unwrap(); + } + assert_eq!( + memory.read_u8(BASE - 1), + Err(MemoryError::UnmappedAddress(BASE - 1)) + ); + if count == 0 { + assert_eq!( + memory.read_u8(BASE), + Err(MemoryError::UnmappedAddress(BASE)) + ); + assert_eq!( + memory.write_u8(BASE, 1), + Err(MemoryError::UnmappedAddress(BASE)) + ); + assert_eq!( + memory.read_bytes(BASE, &mut []), + Err(MemoryError::UnmappedAddress(BASE)) + ); + } + for index in 0..count { + let address = BASE + index as u64 * 0x100; + let mut actual = [0; 8]; + memory.read_bytes(address, &mut actual).unwrap(); + assert_eq!(actual, [(index + 1) as u8; 8]); + let replacement = [0x80 + index as u8; 8]; + memory.write_bytes(address, &replacement).unwrap(); + memory.read_bytes(address, &mut actual).unwrap(); + assert_eq!(actual, replacement); + assert_eq!(memory.read_bytes(address + 8, &mut []), Ok(())); + assert_eq!( + memory.read_u8(address + 8), + Err(MemoryError::UnmappedAddress(address + 8)) + ); + let mut failed = [0xee; 2]; + assert_eq!( + memory.read_bytes(address + 7, &mut failed), + Err(MemoryError::UnmappedAddress(address + 8)) + ); + assert_eq!(failed, [0xee; 2]); + } + } + } +} diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index 91e775d..3859703 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -20,6 +20,7 @@ mod gdk_queue; mod heap; mod modules; mod platform_fixture; +mod process; mod synch; pub mod sysinfo; mod task_fixture; @@ -203,6 +204,8 @@ pub struct ServicesState { pub(crate) hooks: Arc, /// Functions registered with `atexit`, run in reverse order by `_cexit`. atexit: Mutex>, + /// The status the guest process exited with. Set once. + exit_status: Mutex>, winsock: Mutex, task_fixture: Mutex, platform_fixture: Mutex, @@ -229,6 +232,7 @@ impl ServicesState { threads: Mutex::default(), hooks: Arc::default(), atexit: Mutex::default(), + exit_status: Mutex::default(), winsock: Mutex::default(), task_fixture: Mutex::default(), platform_fixture: Mutex::default(), @@ -252,6 +256,76 @@ impl ServicesState { self.priority_boost_disabled.load(Ordering::SeqCst) } + /// The status the guest process exited with, once it has exited. + pub fn exit_status(&self) -> Option { + *self.exit_status.lock().expect("guest exit status") + } + + /// How many guest handles are open: kernel objects, sockets and task + /// queues, which are kept in three separate tables. + pub fn open_handle_count(&self) -> usize { + let objects = self + .objects + .lock() + .expect("guest object state") + .handles + .len(); + let sockets = self + .winsock + .lock() + .expect("guest Winsock state") + .open_count(); + let queues = self + .gdk_queues + .lock() + .expect("GDK queue handle table") + .open_count(); + objects + sockets + queues + } + + /// A file on the synthetic `C:` drive, named as the guest names it. + pub fn file_contents(&self, path: &str) -> Option> { + let path = path.replace('/', "\\").to_ascii_lowercase(); + let name = path.strip_prefix("c:\\").unwrap_or(&path); + self.objects + .lock() + .expect("guest object state") + .files + .get(name) + .cloned() + } + + /// End the guest process. The first exit decides the status; a later one + /// reports it again and changes nothing. + /// + /// Every guest handle is closed: kernel objects, sockets and task queues. + /// Files stay on the synthetic drive, guest memory stays mapped for the + /// host to inspect, and `atexit` functions are not run. + fn exit_process(&self, status: u32) -> u32 { + let mut exited = self.exit_status.lock().expect("guest exit status"); + if let Some(first) = *exited { + return first; + } + *exited = Some(status); + // The three table locks are taken one at a time, never nested. + self.objects + .lock() + .expect("guest object state") + .handles + .clear(); + self.winsock + .lock() + .expect("guest Winsock state") + .close_all(); + self.winsock_changed.notify_all(); + self.gdk_queues + .lock() + .expect("GDK queue handle table") + .close_all(); + self.gdk_queue_changed.notify_all(); + status + } + /// Everything the guest has written to `stdout`, as the bytes a text-mode /// stream hands the operating system: each line feed the program wrote is /// a carriage return and a line feed here. @@ -653,6 +727,7 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc usize { + self.queues.len() + } + + /// Process exit: every handle is closed and nothing stays scheduled. + pub(super) fn close_all(&mut self) { + self.queues.clear(); + self.terminated.clear(); + self.pending.clear(); + } + fn open( &mut self, duplicate: Option, diff --git a/crates/loader/src/services/process.rs b/crates/loader/src/services/process.rs new file mode 100644 index 0000000..172472b --- /dev/null +++ b/crates/loader/src/services/process.rs @@ -0,0 +1,23 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Process termination. + +use super::{KERNEL32, ServicesState}; +use crate::cpu::ExitReason; +use crate::imports::{ImportRegistry, ServiceStatus}; +use std::sync::Arc; + +const PROCESS_THREADS_API: &str = "api-ms-win-core-processthreads-l1-1-0.dll"; + +pub(super) fn register(registry: &mut ImportRegistry, state: &Arc) { + // ExitProcess does not return (processthreadsapi.h). It stops the guest + // with its status and never ends the host. It is partial: there are no + // other threads or loaded DLLs to notify. + let s = Arc::clone(state); + registry.register(KERNEL32, "ExitProcess", move |args, _, _| { + // The status is a UINT, the low half of the first argument. + Err(ExitReason::ProcessExit(s.exit_process(args.rcx as u32))) + }); + registry.alias(PROCESS_THREADS_API, KERNEL32, "ExitProcess"); + registry.set_status(KERNEL32, "ExitProcess", ServiceStatus::Partial); +} diff --git a/crates/loader/src/services/winsock.rs b/crates/loader/src/services/winsock.rs index 46ff8c5..d8c1700 100644 --- a/crates/loader/src/services/winsock.rs +++ b/crates/loader/src/services/winsock.rs @@ -54,6 +54,16 @@ struct Socket { } impl Winsock { + /// Sockets the guest has open. + pub(super) fn open_count(&self) -> usize { + self.sockets.len() + } + + /// Process exit: every socket is closed. + pub(super) fn close_all(&mut self) { + self.sockets.clear(); + } + fn socket(&self, handle: u64) -> Result<&Socket, u32> { if self.refs == 0 { return Err(WSANOTINITIALISED); diff --git a/crates/loader/src/startup.rs b/crates/loader/src/startup.rs index 3afa920..12eefcd 100644 --- a/crates/loader/src/startup.rs +++ b/crates/loader/src/startup.rs @@ -3,14 +3,16 @@ //! Process startup for trusted, original PE32+ fixtures. use crate::dbt::DbtMetrics; +use crate::tls::TlsError; use crate::{ - CpuState, DbtEngine, ExecutionResult, ImportRegistry, LoadedImage, MemoryError, + CpuState, DbtEngine, ExecutionResult, ExitReason, ImportRegistry, LoadedImage, MemoryError, MemoryPermissions, ParsedPe, PeError, RelocationReport, apply_relocations, execute_tls_callbacks, parse_tls_directory, setup_tls, }; const STACK_SIZE: usize = 64 * 1024; const JIT_CAPACITY: usize = 1024 * 1024; +const RETURN_SENTINEL_PAGE_SIZE: usize = 0x1000; /// The TEB is placed this far above the TLS base and spans two 4 KiB pages. const TEB_OFFSET: u64 = 0x10000; const TEB_SIZE: usize = 0x2000; @@ -130,6 +132,14 @@ pub fn run_synthetic_startup_with_observer( } memory.map_region(stack_base, STACK_SIZE, MemoryPermissions::READ_WRITE)?; + // Keep guest code and data out of the page that holds the return + // addresses the engine intercepts. An image or layout that already covers + // it is refused here, and a later guest allocation there fails. + memory.map_region( + crate::imports::RETURN_SENTINEL_PAGE, + RETURN_SENTINEL_PAGE_SIZE, + MemoryPermissions::NO_ACCESS, + )?; map_teb(memory, teb_base, &layout, stack_base)?; @@ -139,28 +149,59 @@ pub fn run_synthetic_startup_with_observer( let mut tls_cpu = CpuState::new(image.entry_point, layout.stack_top); tls_cpu.gs_base = teb_base; let mut tls_callbacks = 0; + let mut exited_in_tls = None; if let Some(tls) = &tls { - tls_callbacks = execute_tls_callbacks( - &tls.callbacks, - layout.image_base, - pe.image_base, - layout.stack_top, - &mut tls_cpu, - memory, - &mut engine, - )?; + // One callback at a time, so that a callback which ends the process + // is seen as an exit and not as a fault, and the callbacks that + // finished before it are counted. + for callback in &tls.callbacks { + match execute_tls_callbacks( + std::slice::from_ref(callback), + layout.image_base, + pe.image_base, + layout.stack_top, + &mut tls_cpu, + memory, + &mut engine, + ) { + Ok(_) => tls_callbacks += 1, + Err(TlsError::CallbackExecutionFault(ExitReason::ProcessExit(status))) => { + exited_in_tls = Some(status); + break; + } + Err(error) => return Err(error.into()), + } + } } observe(StartupEvent::TlsCompleted { callbacks: tls_callbacks, native_steps: engine.metrics.instructions_executed, }); + if let Some(status) = exited_in_tls { + // The process ended before its entry point: the remaining callbacks + // and the entry point do not run, and this is an ordinary outcome. + return Ok(StartupResult { + image, + relocations, + bound_imports, + tls_callbacks, + execution: ExecutionResult { + instructions_executed: 0, + final_state: tls_cpu, + exit_reason: ExitReason::ProcessExit(status), + }, + dbt_metrics: engine.metrics, + }); + } observe(StartupEvent::Entering { step_limit: entry_budget, }); // Model function entry with the Win64 32-byte home area and return slot. - // The synthetic entry point terminates with HLT. + // An entry point may end with HLT, call ExitProcess, or return: the + // return slot holds the address that ends the process with EAX. + memory.write_u64_bypass(layout.stack_top - 40, crate::imports::ENTRY_RETURN)?; let mut entry_cpu = CpuState::new(image.entry_point, layout.stack_top - 40); entry_cpu.gs_base = teb_base; let execution = engine.run(&mut entry_cpu, memory, entry_budget); diff --git a/crates/loader/tests/gate_a1.rs b/crates/loader/tests/gate_a1.rs new file mode 100644 index 0000000..8a2c46e --- /dev/null +++ b/crates/loader/tests/gate_a1.rs @@ -0,0 +1,302 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Gate A1 (issue #329): an original C program with no C library linked, +//! built from source by this test and run through the loader, the standard +//! services and the ARM64 DBT. +//! +//! `tests/compat_fixtures/build-gate-a1.sh` compiles +//! `tests/compat_fixtures/gate_a1.c` with clang and links it with an LLD, so +//! the test needs both on the host. It fails, and does not skip, when they +//! are missing. +//! +//! Every expected value is recomputed here, in Rust, from the description of +//! the program: nothing is read back from a run and asserted. The host +//! arithmetic and the guest arithmetic share no code. + +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::{Arc, OnceLock}; +use xenora_loader::cpu::ExitReason; +use xenora_loader::imports::ImportRegistry; +use xenora_loader::services::{MockClock, ServicesState, register_standard_services}; +use xenora_loader::startup::{StartupLayout, StartupResult, run_synthetic_startup}; + +/// The status of a run in which every check passed. +const STATUS: u32 = 0x00A1_A1A1; +const RECORDS: u32 = 64; +/// Checks the program counts on a complete run, and the one that the +/// `GATE_BREAK` variant fails: three for allocation, 63 for the sort order, +/// then the Fibonacci check. +const CHECKS: u32 = 92; +const BROKEN_CHECK: u32 = 67; +/// Twelve from ucrtbase.dll and eight from kernel32.dll. +const IMPORTS: usize = 20; +/// The six entries of the program's table of function pointers. +const RELOCATIONS: usize = 6; + +/// Build every variant once and return the output directory. +fn built() -> &'static Path { + static OUT: OnceLock = OnceLock::new(); + OUT.get_or_init(|| { + // One directory per test process: two `cargo test` runs that share a + // target directory must not write and read the same files. + let out = PathBuf::from(env!("CARGO_TARGET_TMPDIR")) + .join(format!("gate-a1-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&out); + let script = concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../tests/compat_fixtures/build-gate-a1.sh" + ); + let build = Command::new("sh") + .arg(script) + .arg(&out) + .output() + .expect("run tests/compat_fixtures/build-gate-a1.sh"); + assert!( + build.status.success(), + "the Gate A1 program did not build; it needs clang and an LLD:\n{}{}", + String::from_utf8_lossy(&build.stdout), + String::from_utf8_lossy(&build.stderr) + ); + let toolchain = std::fs::read_to_string(out.join("toolchain.txt")).unwrap(); + println!("Gate A1 built with:\n{toolchain}"); + out + }) +} + +struct Outcome { + result: StartupResult, + state: Arc, +} + +/// Run one built variant through the real startup path with the standard +/// services, loaded away from its preferred base so its relocations matter. +fn run(name: &str, budget: usize) -> Result { + let bytes = std::fs::read(built().join(format!("{name}.exe"))).unwrap(); + let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); + let mut registry = ImportRegistry::new(); + register_standard_services(&mut registry, Arc::clone(&state)); + let layout = StartupLayout { + image_base: 0x2_5000_0000, + stack_top: 0x2_0001_0000, + tls_base: 0x3_0000_0000, + }; + match run_synthetic_startup(&bytes, layout, registry, budget) { + Ok(result) => Ok(Outcome { result, state }), + Err(error) => { + // Nothing may have run or been left behind. + assert_eq!(state.exit_status(), None, "{name}"); + assert_eq!(state.open_handle_count(), 0, "{name}"); + assert_eq!(state.file_contents("C:\\gate-a1.txt"), None, "{name}"); + Err(error.to_string()) + } + } +} + +// --------------------------------------------------------------------------- +// What the program computes, restated independently +// --------------------------------------------------------------------------- + +/// One of six steps chosen by the round number. +fn mix(value: u64, round: u32) -> u64 { + match round % 6 { + 0 => value + .wrapping_mul(6_364_136_223_846_793_005) + .wrapping_add(1_442_695_040_888_963_407), + 1 => value.rotate_left(13), + 2 => value / 7 + value % 1_000_003, + 3 => value ^ (value >> 29), + // C division of a signed 64-bit value truncates toward zero. + 4 => (value as i64 / -3) as u64, + _ => value.wrapping_sub(u64::from(round)), + } +} + +struct Expected { + report: String, + /// The sorted records as the program stores them: key, weight, ratio. + data: Vec, + key_checksum: u64, +} + +fn expected() -> Expected { + let mut state = 0x243F_6A88_85A3_08D3_u64; + let mut records = Vec::new(); + let mut weighted = 0u64; + for index in 0..RECORDS { + state = mix(state, index); + let fraction = state & 0xFFFF; + // The program sums fraction / 65536 * index in doubles. Every term + // and the sum are exact, so the scaled total is this integer. + weighted += fraction * u64::from(index); + // The index in the low six bits makes every key different. + let key = (((state >> 20) as u32) << 6) | index; + records.push((key, index, fraction as f64 / 65536.0)); + } + records.sort_by_key(|record| record.0); + assert!(records.windows(2).all(|pair| pair[0].0 != pair[1].0)); + + // FNV-1a over each key, least significant byte first. + let mut key_checksum = 0xCBF2_9CE4_8422_2325_u64; + let mut data = Vec::new(); + for (key, weight, ratio) in &records { + for byte in key.to_le_bytes() { + key_checksum = (key_checksum ^ u64::from(byte)).wrapping_mul(0x0100_0000_01B3); + } + data.extend(key.to_le_bytes()); + data.extend(weight.to_le_bytes()); + data.extend(ratio.to_le_bytes()); + } + let wide = (state % 1_000_000_007) as i64 * -977 / 13; + // Fibonacci(12) is 144. The text is 16 characters; its hexadecimal and + // decimal fields are 0x7b and -42. A missing file is error 2 + // (ERROR_FILE_NOT_FOUND) and an impossible allocation sets errno to 12 + // (ENOMEM). The data file holds 64 records of 16 bytes. + let report = format!( + "gate a1\nrecords {RECORDS}\nkeys {key_checksum}\nweighted {weighted}\nfibonacci 144\n\ + wide {wide}\nstrings 16 123 -42\nerrors 2 12\nfile {}\n", + data.len() + ); + Expected { + report, + data, + key_checksum, + } +} + +/// The program's result block, which it keeps in a section named `.gate`: +/// magic, check count, key checksum, kept pointer, freed pointer. +fn result_block(outcome: &Outcome) -> (u32, u32, u64, u64, u64) { + let image = &outcome.result.image; + let section = image + .pe + .sections + .iter() + .find(|section| section.name == ".gate") + .expect("a .gate section"); + let at = 0x2_5000_0000 + u64::from(section.virtual_address); + let memory = &image.memory; + ( + memory.read_u32(at).unwrap(), + memory.read_u32(at + 4).unwrap(), + memory.read_u64(at + 8).unwrap(), + memory.read_u64(at + 16).unwrap(), + memory.read_u64(at + 24).unwrap(), + ) +} + +// --------------------------------------------------------------------------- +// The gate +// --------------------------------------------------------------------------- + +#[test] +fn the_program_runs_to_its_exit_at_every_optimization_level() { + let wanted = expected(); + for name in ["gate-a1-O0", "gate-a1-O1", "gate-a1-O2", "gate-a1-Os"] { + let outcome = run(name, 2_000_000).unwrap_or_else(|error| panic!("{name}: {error}")); + let result = &outcome.result; + let state = &outcome.state; + + // It was loaded, relocated and bound by the real startup path. + assert_eq!(result.bound_imports, IMPORTS, "{name}"); + assert_eq!(result.relocations.applied_dir64, RELOCATIONS, "{name}"); + + // It ended itself, with all 32 bits of its status. + assert_eq!( + result.execution.exit_reason, + ExitReason::ProcessExit(STATUS), + "{name}" + ); + assert_eq!(state.exit_status(), Some(STATUS), "{name}"); + + // It ran as translated ARM64 code. + let metrics = &result.dbt_metrics; + assert!( + metrics.blocks_compiled > 0 && metrics.native_bytes_emitted > 0, + "{name}" + ); + assert!(metrics.instructions_executed > 1_000, "{name}"); + assert!(metrics.service_calls > 20, "{name}"); + println!( + "{name}: {} guest instructions, {} of them through the shared semantics, {} service \ + calls", + metrics.instructions_executed, metrics.interpreter_fallbacks, metrics.service_calls + ); + + // Output: the report it wrote. + let report = state.file_contents("C:\\gate-a1.txt").expect("a report"); + assert_eq!(String::from_utf8(report).unwrap(), wanted.report, "{name}"); + + // Filesystem: the data file holds the sorted records, the file it + // looked for was not created, and the report handle it left open was + // closed by the exit. + assert_eq!( + state.file_contents("C:\\gate-a1.bin").as_deref(), + Some(wanted.data.as_slice()), + "{name}" + ); + assert_eq!(state.file_contents("C:\\none.bin"), None, "{name}"); + assert_eq!(state.open_handle_count(), 0, "{name}"); + + // Memory: the result block, a block it kept and a block it freed. + let (magic, checks, key_checksum, kept, freed) = result_block(&outcome); + assert_eq!((magic, checks), (0x3141_5926, CHECKS), "{name}"); + assert_eq!(key_checksum, wanted.key_checksum, "{name}"); + let memory = &result.image.memory; + let mut text = [0u8; 16]; + memory.read_bytes(kept, &mut text).unwrap(); + assert_eq!(&text, b"kept by gate a1\0", "{name}"); + assert!( + memory.read_u8(freed).is_err(), + "{name}: freed block is still mapped" + ); + } +} + +#[test] +fn a_returning_entry_point_gives_the_same_result() { + let outcome = run("gate-a1-return", 2_000_000).unwrap(); + assert_eq!( + outcome.result.execution.exit_reason, + ExitReason::ProcessExit(STATUS) + ); + assert_eq!(outcome.state.exit_status(), Some(STATUS)); + assert_eq!(outcome.state.open_handle_count(), 0); + let report = outcome.state.file_contents("C:\\gate-a1.txt").unwrap(); + assert_eq!(String::from_utf8(report).unwrap(), expected().report); +} + +#[test] +fn a_wrong_expectation_exits_with_the_number_of_the_failed_check() { + // The variant expects Fibonacci(12) to be 145. Everything before that + // check passes, and nothing after it runs. + let outcome = run("gate-a1-break", 2_000_000).unwrap(); + assert_eq!( + outcome.result.execution.exit_reason, + ExitReason::ProcessExit(BROKEN_CHECK) + ); + assert_eq!(outcome.state.exit_status(), Some(BROKEN_CHECK)); + assert_eq!(result_block(&outcome).1, BROKEN_CHECK); + assert_eq!(outcome.state.file_contents("C:\\gate-a1.bin"), None); + assert_eq!(outcome.state.file_contents("C:\\gate-a1.txt"), None); +} + +#[test] +fn an_import_nobody_provides_is_refused_before_entry() { + let error = run("gate-a1-missing", 2_000_000).err().expect("refusal"); + assert_eq!( + error, + "unresolved import dependency: kernel32.dll!GateMissingService" + ); +} + +#[test] +fn a_step_budget_that_is_too_small_is_not_an_exit() { + let outcome = run("gate-a1-O1", 500).unwrap(); + assert_eq!( + outcome.result.execution.exit_reason, + ExitReason::StepLimitExceeded + ); + assert_eq!(outcome.state.exit_status(), None); + assert_eq!(outcome.state.file_contents("C:\\gate-a1.txt"), None); +} diff --git a/crates/loader/tests/process_exit.rs b/crates/loader/tests/process_exit.rs new file mode 100644 index 0000000..9e784b9 --- /dev/null +++ b/crates/loader/tests/process_exit.rs @@ -0,0 +1,540 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Process exit (issue #329): `ExitProcess`, a returning entry point, and the +//! rule that an exited guest runs nothing further. +//! +//! Expected behaviour is from the public Win32 documentation for +//! `ExitProcess` (processthreadsapi.h): it does not return, the status is a +//! `UINT`, and the process's handles are closed. The guest code is original. + +mod support; + +use std::sync::Arc; +use support::*; +use xenora_loader::cpu::{CpuState, ExitReason}; +use xenora_loader::import_table::ImportName; +use xenora_loader::imports::{ENTRY_RETURN, ImportRegistry, RETURN_SENTINEL_PAGE, Win64Args}; +use xenora_loader::memory::{GuestMemory, MemoryError, MemoryPermissions}; +use xenora_loader::services::{MockClock, ServicesState, register_standard_services}; +use xenora_loader::startup::{StartupLayout, run_synthetic_startup}; + +const KERNEL32: &str = "kernel32.dll"; +const THREADS: &str = "api-ms-win-core-processthreads-l1-1-0.dll"; +const UCRT: &str = "ucrtbase.dll"; + +const IMPORTS: &[(&str, &str)] = &[ + (KERNEL32, "ExitProcess"), + (KERNEL32, "SetLastError"), + (KERNEL32, "CreateFileW"), + (KERNEL32, "CreateEventW"), + (UCRT, "qsort"), + ("ws2_32.dll", "WSAStartup"), + ("ws2_32.dll", "socket"), + ("xgameruntime.dll", "XTaskQueueCreate"), +]; +const ALIAS: &[(&str, &str)] = &[(THREADS, "ExitProcess")]; + +/// Guest address of the stub `call [slot]; hlt` for import `index`. +fn stub(index: usize) -> u64 { + BASE + u64::from(CODE_RVA) + 16 * index as u64 +} + +#[test] +fn exit_process_stops_the_guest_with_its_whole_status() { + // The status is a 32-bit UINT: values above 255 survive, and the upper + // half of RCX is not part of it. + for (argument, status) in [ + (0, 0), + (1, 1), + (150, 150), + (0x1234_5678, 0x1234_5678), + (0xFFFF_FFFF, 0xFFFF_FFFF), + (0xAAAA_BBBB_0000_002A, 0x2A), + ] { + for imports in [IMPORTS, ALIAS] { + let mut guest = Guest::new(imports, &[]); + assert_eq!(guest.state.exit_status(), None); + // The stub is `call [ExitProcess]; hlt`. A service that returned + // would reach the HLT and report Halt. + let (_, exit) = guest.run("ExitProcess", &[argument]); + assert_eq!(exit, ExitReason::ProcessExit(status), "{argument:#x}"); + assert_eq!(guest.state.exit_status(), Some(status), "{argument:#x}"); + } + } +} + +#[test] +fn an_exited_guest_runs_nothing_further() { + let mut guest = Guest::new(IMPORTS, &[]); + assert_eq!(guest.run("ExitProcess", &[3]).1, ExitReason::ProcessExit(3)); + // Neither another service nor a second exit takes effect: the engine + // reports the first exit again without executing anything. + for (symbol, argument) in [("SetLastError", 5), ("ExitProcess", 9)] { + let (_, exit) = guest.run(symbol, &[argument]); + assert_eq!(exit, ExitReason::ProcessExit(3), "{symbol}"); + } + assert_eq!(guest.state.last_error(THREAD_A), 0); + assert_eq!(guest.state.exit_status(), Some(3)); +} + +/// Under the guest thread scheduler the engine runs in slices. A process exit +/// from the scheduled main thread stops the schedule with that exit as its +/// reason, and sets the engine's exit latch through the sliced entry point, so +/// nothing runs afterwards. The scheduler has no outcome of its own for a +/// process exit and reports it as the reason of a `Fault`. +#[test] +fn exit_process_under_the_scheduler_ends_the_run() { + use xenora_loader::scheduler::Outcome; + for quantum in [1, 64, 1_000_000] { + let mut guest = Guest::new(IMPORTS, &[]); + assert_ne!(guest.call("CreateEventW", &[0, 1, 0, 0]), 0); + let report = guest.scheduled("ExitProcess", &[0xAAAA_BBBB_0000_0015], quantum, 10_000); + assert!( + matches!( + report.outcome, + Outcome::Fault { + reason: ExitReason::ProcessExit(0x15), + .. + } + ), + "quantum {quantum}: {:?}", + report.outcome + ); + assert_eq!(guest.state.exit_status(), Some(0x15)); + assert_eq!(guest.state.open_handle_count(), 0); + // The engine is latched: an unsliced run executes nothing either. + let (_, exit) = guest.run("SetLastError", &[5]); + assert_eq!(exit, ExitReason::ProcessExit(0x15), "quantum {quantum}"); + assert_eq!(guest.state.last_error(THREAD_A), 0); + } +} + +#[test] +fn the_first_exit_decides_the_status() { + // Two calls of the service itself, with no engine in between to stop the + // second one. + let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); + let mut registry = ImportRegistry::new(); + register_standard_services(&mut registry, Arc::clone(&state)); + let exit = ®istry + .resolve(KERNEL32, &ImportName::Name("ExitProcess".into())) + .expect("ExitProcess is registered") + .handler; + let mut cpu = CpuState::new(0, 0); + let mut memory = GuestMemory::new(); + for status in [41, 42] { + let mut args = Win64Args::new(&cpu); + args.rcx = status; + assert_eq!( + exit(&args, &mut cpu, &mut memory), + Err(ExitReason::ProcessExit(41)) + ); + } + assert_eq!(state.exit_status(), Some(41)); +} + +#[test] +fn exit_from_inside_a_service_callback_ends_the_process() { + // A comparator for qsort that exits instead of comparing: + // sub rsp, 0x28 + // mov ecx, 9 + // call + // mov byte ptr [SCRATCH], 1 ; must never run + // add rsp, 0x28 + // ret + let call_end = routine(0) + 14; + let displacement = (stub(0).wrapping_sub(call_end) as u32).to_le_bytes(); + let mut comparator = vec![0x48, 0x83, 0xEC, 0x28, 0xB9, 9, 0, 0, 0, 0xE8]; + comparator.extend(displacement); + comparator.extend([0xC6, 0x04, 0x25]); + comparator.extend((SCRATCH as u32).to_le_bytes()); + comparator.extend([0x01, 0x48, 0x83, 0xC4, 0x28, 0xC3]); + + let mut guest = Guest::new(IMPORTS, &[comparator]); + let items = SCRATCH + 0x100; + guest.memory.write_u64(items, 2).unwrap(); + guest.memory.write_u64(items + 8, 1).unwrap(); + let (_, exit) = guest.run("qsort", &[items, 2, 8, routine(0)]); + assert_eq!(exit, ExitReason::ProcessExit(9)); + assert_eq!(guest.memory.read_u8(SCRATCH).unwrap(), 0); + // The sort never resumed, so the items are as the guest left them. + assert_eq!((guest.u64_at(items), guest.u64_at(items + 8)), (2, 1)); + assert_eq!(guest.state.exit_status(), Some(9)); +} + +#[test] +fn exit_closes_every_handle_and_keeps_the_files() { + let mut guest = Guest::new(IMPORTS, &[]); + let name: Vec = "C:\\exit.bin\0" + .encode_utf16() + .flat_map(u16::to_le_bytes) + .collect(); + guest.memory.write_bytes(SCRATCH, &name).unwrap(); + // CreateFileW(name, GENERIC_READ | GENERIC_WRITE, no sharing, null, + // CREATE_ALWAYS, 0, null) and an unnamed event. + let file = guest.call("CreateFileW", &[SCRATCH, 0xC000_0000, 0, 0, 2, 0, 0]); + assert_ne!(file, u64::MAX); + assert_ne!(guest.call("CreateEventW", &[0, 1, 0, 0]), 0); + assert_eq!(guest.state.open_handle_count(), 2); + + // Sockets and task queues live in tables of their own. WSAStartup(2.2), + // two UDP sockets, and XTaskQueueCreate(manual, manual, &handle). + assert_eq!(guest.call("WSAStartup", &[0x0202, SCRATCH + 0x200]), 0); + let first = guest.call("socket", &[2, 2, 17]); + let second = guest.call("socket", &[2, 2, 17]); + assert!(first != u64::MAX && second != u64::MAX && first != second); + assert_eq!(guest.state.open_handle_count(), 4); + assert_eq!(guest.call("XTaskQueueCreate", &[0, 0, SCRATCH + 0x400]), 0); + assert_ne!(guest.u64_at(SCRATCH + 0x400), 0); + assert_eq!(guest.state.open_handle_count(), 5); + + assert_eq!(guest.run("ExitProcess", &[0]).1, ExitReason::ProcessExit(0)); + assert_eq!(guest.state.open_handle_count(), 0); + // The drive is not the process: the file it created is still there. + assert_eq!(guest.state.file_contents("C:\\exit.bin"), Some(Vec::new())); + assert_eq!(guest.state.file_contents("C:\\absent.bin"), None); +} + +/// A PE32+ image with one executable section and no imports whose entry +/// point is `mov eax, status; ret`. +fn returning_image(status: u32) -> Vec { + let mut pe = vec![0u8; 0x400]; + let mut put = |at: usize, bytes: &[u8]| pe[at..at + bytes.len()].copy_from_slice(bytes); + put(0, b"MZ"); + put(0x3C, &0x80u32.to_le_bytes()); + put(0x80, b"PE\0\0"); + put(0x84, &0x8664u16.to_le_bytes()); // AMD64 + put(0x86, &1u16.to_le_bytes()); // one section + put(0x94, &240u16.to_le_bytes()); // optional header size + put(0x96, &0x0022u16.to_le_bytes()); // executable, large-address-aware + let optional = 0x98; + put(optional, &0x20Bu16.to_le_bytes()); // PE32+ + put(optional + 16, &0x1000u32.to_le_bytes()); // entry point + put(optional + 24, &0x1_4000_0000u64.to_le_bytes()); // image base + put(optional + 32, &0x1000u32.to_le_bytes()); // section alignment + put(optional + 36, &0x200u32.to_le_bytes()); // file alignment + put(optional + 56, &0x2000u32.to_le_bytes()); // size of image + put(optional + 60, &0x200u32.to_le_bytes()); // size of headers + put(optional + 108, &16u32.to_le_bytes()); // data directories + let section = optional + 240; + put(section, b".text"); + put(section + 8, &0x200u32.to_le_bytes()); // virtual size + put(section + 12, &0x1000u32.to_le_bytes()); // RVA + put(section + 16, &0x200u32.to_le_bytes()); // raw size + put(section + 20, &0x200u32.to_le_bytes()); // raw offset + put(section + 36, &0x6000_0020u32.to_le_bytes()); // code, execute, read + put(0x200, &[0xB8]); + put(0x201, &status.to_le_bytes()); + put(0x205, &[0xC3]); + pe +} + +fn layout() -> StartupLayout { + StartupLayout { + image_base: 0x1_4000_0000, + stack_top: 0x2_0001_0000, + tls_base: 0x3_0000_0000, + } +} + +#[test] +fn a_returning_entry_point_exits_with_eax() { + // With no ExitProcess registered the return still ends the process. + let bare = run_synthetic_startup( + &returning_image(0x1234_5678), + layout(), + ImportRegistry::new(), + 100, + ) + .unwrap(); + assert_eq!( + bare.execution.exit_reason, + ExitReason::ProcessExit(0x1234_5678) + ); + // `mov eax, imm32` and `ret`, then nothing. + assert_eq!(bare.execution.instructions_executed, 2); + + // With the standard services it goes through ExitProcess, so the status + // is recorded where a host can read it. + let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); + let mut registry = ImportRegistry::new(); + register_standard_services(&mut registry, Arc::clone(&state)); + let standard = run_synthetic_startup(&returning_image(77), layout(), registry, 100).unwrap(); + assert_eq!(standard.execution.exit_reason, ExitReason::ProcessExit(77)); + assert_eq!(state.exit_status(), Some(77)); +} + +// --------------------------------------------------------------------------- +// Exit before the entry point, and the reserved return addresses +// --------------------------------------------------------------------------- + +const IMAGE_BASE: u64 = 0x1_4000_0000; +const ENTRY_RVA: u32 = 0x1000; +/// TLS callback `n` is at this RVA plus 0x20 for each one before it. +const CALLBACK_RVA: u32 = 0x1040; +const IAT_RVA: u32 = 0x2070; +/// One byte per marker: a routine that ran sets its own to 1. +const MARKER_RVA: u32 = 0x2100; + +/// A PE32+ image that imports one kernel32 function. `entry` is its entry +/// point and each of `callbacks` is a TLS callback. +fn image(symbol: &str, entry: &[u8], callbacks: &[Vec]) -> Vec { + assert!(entry.len() <= 0x40 && callbacks.len() <= 4); + let mut pe = vec![0u8; 0x600]; + let mut put = |at: usize, bytes: &[u8]| pe[at..at + bytes.len()].copy_from_slice(bytes); + put(0, b"MZ"); + put(0x3C, &0x80u32.to_le_bytes()); + put(0x80, b"PE\0\0"); + put(0x84, &0x8664u16.to_le_bytes()); + put(0x86, &2u16.to_le_bytes()); + put(0x94, &240u16.to_le_bytes()); + put(0x96, &0x0022u16.to_le_bytes()); + let optional = 0x98; + put(optional, &0x20Bu16.to_le_bytes()); + put(optional + 16, &ENTRY_RVA.to_le_bytes()); + put(optional + 24, &IMAGE_BASE.to_le_bytes()); + put(optional + 32, &0x1000u32.to_le_bytes()); + put(optional + 36, &0x200u32.to_le_bytes()); + put(optional + 56, &0x3000u32.to_le_bytes()); + put(optional + 60, &0x200u32.to_le_bytes()); + put(optional + 108, &16u32.to_le_bytes()); + // Data directory 1: imports. Data directory 9: TLS. + put(optional + 120, &0x2000u32.to_le_bytes()); + put(optional + 124, &0x28u32.to_le_bytes()); + if !callbacks.is_empty() { + put(optional + 184, &0x2080u32.to_le_bytes()); + put(optional + 188, &40u32.to_le_bytes()); + } + for (index, (name, rva, raw, flags)) in [ + (b".text", 0x1000u32, 0x200u32, 0x6000_0020u32), + (b".data", 0x2000, 0x400, 0xC000_0040), + ] + .into_iter() + .enumerate() + { + let section = optional + 240 + 40 * index; + put(section, name); + put(section + 8, &0x200u32.to_le_bytes()); + put(section + 12, &rva.to_le_bytes()); + put(section + 16, &0x200u32.to_le_bytes()); + put(section + 20, &raw.to_le_bytes()); + put(section + 36, &flags.to_le_bytes()); + } + // `.data`, at file offset 0x400: the import descriptor, its strings, the + // lookup table and the address table. + let data = |rva: u32| 0x400 + (rva - 0x2000) as usize; + put(data(0x2000), &0x2060u32.to_le_bytes()); // lookup table + put(data(0x200C), &0x2040u32.to_le_bytes()); // DLL name + put(data(0x2010), &IAT_RVA.to_le_bytes()); + put(data(0x2040), KERNEL32.as_bytes()); + put(data(0x2052), symbol.as_bytes()); + put(data(0x2060), &0x2050u64.to_le_bytes()); + put(data(IAT_RVA), &0x2050u64.to_le_bytes()); + if !callbacks.is_empty() { + // The TLS directory: no template, an index slot, and the callbacks. + put(data(0x2080) + 16, &(IMAGE_BASE + 0x20C0).to_le_bytes()); + put(data(0x2080) + 24, &(IMAGE_BASE + 0x20D0).to_le_bytes()); + } + for (index, code) in callbacks.iter().enumerate() { + assert!(code.len() <= 0x20); + let rva = CALLBACK_RVA + 0x20 * index as u32; + put( + data(0x20D0) + 8 * index, + &(IMAGE_BASE + u64::from(rva)).to_le_bytes(), + ); + put(0x200 + (rva - 0x1000) as usize, code); + } + put(0x200, entry); + pe +} + +/// `mov byte [marker], 1`, for code that starts at `rva`. +fn set_marker(rva: u32, marker: u32) -> Vec { + let mut code = vec![0xC6, 0x05]; + code.extend((MARKER_RVA + marker - (rva + 7)).to_le_bytes()); + code.push(1); + code +} + +/// `mov ecx, status; call [import]; hlt`, for code that starts at `rva`. +fn call_import_with(rva: u32, status: u32) -> Vec { + let mut code = vec![0xB9]; + code.extend(status.to_le_bytes()); + code.extend([0xFF, 0x15]); + code.extend((IAT_RVA - (rva + 11)).to_le_bytes()); + code.push(0xF4); + code +} + +fn then(mut code: Vec, last: u8) -> Vec { + code.push(last); + code +} + +const RET: u8 = 0xC3; +const HLT: u8 = 0xF4; + +struct Started { + result: xenora_loader::startup::StartupResult, + state: Arc, +} + +impl Started { + fn markers(&self) -> [u8; 3] { + let mut markers = [0; 3]; + self.result + .image + .memory + .read_bytes(IMAGE_BASE + u64::from(MARKER_RVA), &mut markers) + .unwrap(); + markers + } +} + +fn start(bytes: &[u8]) -> Result { + let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); + let mut registry = ImportRegistry::new(); + register_standard_services(&mut registry, Arc::clone(&state)); + run_synthetic_startup(bytes, layout(), registry, 1_000) + .map(|result| Started { result, state }) + .map_err(|error| error.to_string()) +} + +#[test] +fn exit_in_a_tls_callback_is_an_exit_and_nothing_after_it_runs() { + // Markers: 0 and 1 for the two callbacks, 2 for the entry point. + let entry = then(set_marker(ENTRY_RVA, 2), HLT); + let first = CALLBACK_RVA; + let second = CALLBACK_RVA + 0x20; + + // Control: no callback exits. Both run, then the entry point. + let quiet = start(&image( + "ExitProcess", + &entry, + &[ + then(set_marker(first, 0), RET), + then(set_marker(second, 1), RET), + ], + )) + .unwrap(); + assert_eq!(quiet.result.execution.exit_reason, ExitReason::Halt); + assert_eq!(quiet.result.tls_callbacks, 2); + assert_eq!(quiet.markers(), [1, 1, 1]); + assert_eq!(quiet.state.exit_status(), None); + + // The first callback exits: the second and the entry point never run. + let early = start(&image( + "ExitProcess", + &entry, + &[ + call_import_with(first, 77), + then(set_marker(second, 1), RET), + ], + )) + .unwrap(); + assert_eq!( + early.result.execution.exit_reason, + ExitReason::ProcessExit(77) + ); + assert_eq!(early.result.execution.instructions_executed, 0); + assert_eq!(early.result.tls_callbacks, 0); + assert_eq!(early.markers(), [0, 0, 0]); + assert_eq!(early.state.exit_status(), Some(77)); + + // The second callback exits: the first finished, the entry point never runs. + let late = start(&image( + "ExitProcess", + &entry, + &[ + then(set_marker(first, 0), RET), + call_import_with(second, 0x1_0002), + ], + )) + .unwrap(); + assert_eq!( + late.result.execution.exit_reason, + ExitReason::ProcessExit(0x1_0002) + ); + assert_eq!(late.result.tls_callbacks, 1); + assert_eq!(late.markers(), [1, 0, 0]); + assert_eq!(late.state.exit_status(), Some(0x1_0002)); +} + +#[test] +fn a_fault_in_a_tls_callback_is_still_a_startup_error() { + let entry = then(set_marker(ENTRY_RVA, 2), HLT); + let error = start(&image("ExitProcess", &entry, &[vec![HLT]])) + .err() + .expect("a callback that halts is a fault"); + assert_eq!( + error, + "fault during TLS callback execution: guest executed HLT" + ); +} + +#[test] +fn an_image_over_the_reserved_return_addresses_is_refused() { + // The entry point of this image would be exactly the address that means + // "the entry point returned". Unreserved, the engine would report an exit + // with status 0 before running one instruction of it. + let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); + let mut registry = ImportRegistry::new(); + register_standard_services(&mut registry, Arc::clone(&state)); + let over = StartupLayout { + image_base: ENTRY_RETURN - u64::from(ENTRY_RVA), + ..layout() + }; + let error = run_synthetic_startup(&returning_image(5), over, registry, 100) + .err() + .expect("refused") + .to_string(); + assert_eq!( + error, + format!("overlapping memory region: base 0x{RETURN_SENTINEL_PAGE:016x}, size 0x1000") + ); + assert_eq!(state.exit_status(), None); +} + +#[test] +fn the_guest_cannot_map_the_reserved_return_addresses() { + // The page is there after startup, and nothing can read, write or run it. + let mut started = start(&image("ExitProcess", &[HLT], &[])).unwrap(); + let memory = &mut started.result.image.memory; + assert!(matches!( + memory.read_u8(ENTRY_RETURN), + Err(MemoryError::PermissionViolation { .. }) + )); + assert!(matches!( + memory.map_region(RETURN_SENTINEL_PAGE, 0x1000, MemoryPermissions::READ_WRITE), + Err(MemoryError::OverlappingRegion { .. }) + )); + + // The entry point calls VirtualAlloc(address, 0x1000, MEM_COMMIT | + // MEM_RESERVE, PAGE_READWRITE) and returns 1 if it got a null pointer. + let allocate_at = |address: u64| { + let mut code = vec![0x48, 0xB9]; // mov rcx, address + code.extend(address.to_le_bytes()); + code.extend([0xBA, 0x00, 0x10, 0x00, 0x00]); // mov edx, 0x1000 + code.extend([0x41, 0xB8, 0x00, 0x30, 0x00, 0x00]); // mov r8d, 0x3000 + code.extend([0x41, 0xB9, 0x04, 0x00, 0x00, 0x00]); // mov r9d, 4 + code.extend([0x48, 0x83, 0xEC, 0x28]); // sub rsp, 0x28 + code.extend([0xFF, 0x15]); // call [VirtualAlloc] + code.extend((IAT_RVA - (ENTRY_RVA + code.len() as u32 + 4)).to_le_bytes()); + code.extend([0x48, 0x83, 0xC4, 0x28]); // add rsp, 0x28 + code.extend([0x48, 0x85, 0xC0]); // test rax, rax + code.extend([0x0F, 0x94, 0xC0]); // setz al + code.extend([0x0F, 0xB6, 0xC0]); // movzx eax, al + code.push(RET); + start(&image("VirtualAlloc", &code, &[])) + .unwrap() + .result + .execution + .exit_reason + }; + // Control: a free address is allocated. + assert_eq!(allocate_at(0x6_0000_0000), ExitReason::ProcessExit(0)); + assert_eq!( + allocate_at(RETURN_SENTINEL_PAGE), + ExitReason::ProcessExit(1) + ); +} diff --git a/crates/loader/tests/support/mod.rs b/crates/loader/tests/support/mod.rs index 6528917..7cff5da 100644 --- a/crates/loader/tests/support/mod.rs +++ b/crates/loader/tests/support/mod.rs @@ -208,6 +208,33 @@ impl Guest { (cpu.get(Register::Rax), result.exit_reason) } + /// Call an import as the main thread of a scheduled run: the engine runs + /// in slices of `quantum` instructions under the guest thread scheduler. + pub fn scheduled( + &mut self, + symbol: &str, + args: &[u64], + quantum: usize, + budget: usize, + ) -> xenora_loader::scheduler::ScheduleReport { + let index = self + .imports + .iter() + .position(|(_, name)| *name == symbol) + .unwrap_or_else(|| panic!("{symbol} is not imported")); + let mut cpu = CpuState::new(BASE + u64::from(CODE_RVA) + 16 * index as u64, STACK_TOP); + cpu.gs_base = self.teb; + for (register, value) in [Register::Rcx, Register::Rdx, Register::R8, Register::R9] + .into_iter() + .zip(args) + { + cpu.set(register, *value); + } + xenora_loader::scheduler::Scheduler::new(Arc::clone(&self.state), quantum) + .run(&mut self.engine, &mut self.memory, &cpu, budget) + .expect("the scheduler attaches") + } + /// Run guest code from `entry` on the calling thread's TEB until it stops. pub fn execute(&mut self, entry: u64, max_instructions: usize) -> (CpuState, ExitReason) { let mut cpu = CpuState::new(entry, STACK_TOP); diff --git a/crates/shader/src/lib.rs b/crates/shader/src/lib.rs index 0d81ca6..5b67f2c 100644 --- a/crates/shader/src/lib.rs +++ b/crates/shader/src/lib.rs @@ -31,6 +31,20 @@ pub struct CompiledShader { pub msl: String, } +/// Optional translation passes applied after verification. +/// +/// Default options preserve the historical IR shape: constants from scalar +/// evaluation and immediates remain, but pure vector expressions between +/// constants are not rewritten. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct CompileOptions { + /// Replace pure vector unary/binary ops whose operands are already + /// `const.u32` with a single constant. Floating-point ops fold only when + /// the existing exact positive-normal rules accept the result. Loads, + /// stores, lane masks, merges and branches are never folded. + pub fold_constants: bool, +} + #[derive(Debug)] pub enum CompileError { InvalidLength { @@ -475,10 +489,23 @@ fn exact_float_result(operator: Binary, left: KnownBits, right: KnownBits) -> Op /// Compiles explicitly tagged raw machine code to a synthetic Metal compute kernel. /// /// Bind equal-length disjoint input and output word buffers and dispatch one -/// invocation per word in a one-dimensional grid. +/// invocation per word in a one-dimensional grid. Equivalent to +/// [`compile_with`] using [`CompileOptions::default`]. pub fn compile(architecture: Architecture, bytes: &[u8]) -> Result { + compile_with(architecture, bytes, CompileOptions::default()) +} + +/// Compiles like [`compile`], with optional IR passes selected by `options`. +pub fn compile_with( + architecture: Architecture, + bytes: &[u8], + options: CompileOptions, +) -> Result { let decoded = decode_fixture(architecture, bytes)?; - let operations = lift(&decoded, bytes.len())?; + let mut operations = lift(&decoded, bytes.len())?; + if options.fold_constants { + fold_constant_ops(&mut operations); + } let disassembly = decoded.iter().map(|line| format!("{line}\n")).collect(); let mut ir = String::new(); @@ -1462,6 +1489,118 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result { + const_value(operations, source).and_then(|bits| eval_unary(operator, bits)) + } + Op::Binary(operator, left, right) => { + match ( + const_value(operations, left), + const_value(operations, right), + ) { + (Some(left), Some(right)) => eval_binary(operator, left, right), + _ => None, + } + } + _ => None, + }; + if let Some(bits) = folded { + operations[index].1 = Op::Constant(bits); + } + } +} + +fn const_value(operations: &[(usize, Op)], value: Value) -> Option { + match operations.get(value.0).map(|(_, operation)| *operation)? { + Op::Constant(bits) => Some(bits), + _ => None, + } +} + +fn concrete_bits(facts: KnownBits) -> Option { + if let Some([first, second]) = facts.values { + return (first == second).then_some(first); + } + if facts.zero | facts.one == u32::MAX { + Some(facts.one) + } else { + None + } +} + +fn eval_unary(operator: VectorUnary, source: u32) -> Option { + Some(match operator { + VectorUnary::Not => !source, + VectorUnary::ReverseBits => source.reverse_bits(), + VectorUnary::FindHighUnsigned => { + if source == 0 { + 0xffff_ffff + } else { + source.leading_zeros() + } + } + VectorUnary::FindLow => { + if source == 0 { + 0xffff_ffff + } else { + source.trailing_zeros() + } + } + VectorUnary::FindHighSigned => { + if source == 0 || source == 0xffff_ffff { + 0xffff_ffff + } else { + (source ^ (0u32.wrapping_sub(source >> 31))).leading_zeros() + } + } + }) +} + +fn eval_binary(operator: Binary, left: u32, right: u32) -> Option { + match operator { + Binary::FloatAdd | Binary::FloatMul => concrete_bits(exact_float_result( + operator, + KnownBits::constant(left), + KnownBits::constant(right), + )?), + Binary::Vector(operation) => Some(eval_vector_binary(operation, left, right)), + } +} + +fn eval_vector_binary(operation: VectorBinary, left: u32, right: u32) -> u32 { + let i24 = |value: u32| ((value as i32) << 8) >> 8; + let u24 = |value: u32| value & 0x00ff_ffff; + match operation { + VectorBinary::Add => left.wrapping_add(right), + VectorBinary::Sub => left.wrapping_sub(right), + VectorBinary::Xnor => !(left ^ right), + VectorBinary::MinSigned => (left as i32).min(right as i32) as u32, + VectorBinary::MinUnsigned => left.min(right), + VectorBinary::MaxSigned => (left as i32).max(right as i32) as u32, + VectorBinary::MaxUnsigned => left.max(right), + VectorBinary::Mul24Signed => (i24(left) as u32).wrapping_mul(i24(right) as u32), + VectorBinary::Mul24Unsigned => u24(left).wrapping_mul(u24(right)), + VectorBinary::MulHi24Signed => { + ((i64::from(i24(left)) * i64::from(i24(right))) >> 32) as u32 + } + VectorBinary::MulHi24Unsigned => { + ((u64::from(u24(left)) * u64::from(u24(right))) >> 32) as u32 + } + VectorBinary::And => left & right, + VectorBinary::Or => left | right, + VectorBinary::Xor => left ^ right, + VectorBinary::ShiftLeft => left << (right & 31), + VectorBinary::ShiftRight => left >> (right & 31), + VectorBinary::ArithmeticShiftRight => ((left as i32) >> (right & 31)) as u32, + } +} + /// A wave-uniform constant operand at `offset`. fn constant( operations: &mut Vec<(usize, Op)>, @@ -1510,7 +1649,58 @@ fn merge_lanes( #[cfg(test)] mod tests { - use super::{Binary, KnownBits, exact_float_result}; + use super::{ + Binary, KnownBits, Op, Value, VectorBinary, VectorUnary, eval_unary, eval_vector_binary, + exact_float_result, vector_expression, + }; + + /// Every foldable vector op must keep a matching MSL template and eval arm + /// so the fold table cannot drift from emission. Match arms in + /// `vector_expression` / `eval_vector_binary` / unary `expression` are + /// exhaustive; this test calls both sides for each variant. + #[test] + fn every_foldable_vector_op_has_matching_msl_template() { + for operation in [ + VectorBinary::Add, + VectorBinary::Sub, + VectorBinary::Xnor, + VectorBinary::MinSigned, + VectorBinary::MinUnsigned, + VectorBinary::MaxSigned, + VectorBinary::MaxUnsigned, + VectorBinary::Mul24Signed, + VectorBinary::Mul24Unsigned, + VectorBinary::MulHi24Signed, + VectorBinary::MulHi24Unsigned, + VectorBinary::And, + VectorBinary::Or, + VectorBinary::Xor, + VectorBinary::ShiftLeft, + VectorBinary::ShiftRight, + VectorBinary::ArithmeticShiftRight, + ] { + let expression = vector_expression(operation, "left", "right"); + assert!( + !expression.is_empty(), + "missing MSL template for {operation:?}" + ); + let _ = eval_vector_binary(operation, 0x11, 0x22); + } + for operation in [ + VectorUnary::Not, + VectorUnary::ReverseBits, + VectorUnary::FindHighUnsigned, + VectorUnary::FindLow, + VectorUnary::FindHighSigned, + ] { + let expression = Op::Unary(operation, Value(0)).expression(&|v| v.to_string(), "", ""); + assert!( + !expression.is_empty(), + "missing MSL template for {operation:?}" + ); + assert!(eval_unary(operation, 0x8000_0001).is_some()); + } + } #[test] fn propagates_known_bits_through_integer_operators() { diff --git a/crates/shader/tests/compiler.rs b/crates/shader/tests/compiler.rs index d70f1f5..3243728 100644 --- a/crates/shader/tests/compiler.rs +++ b/crates/shader/tests/compiler.rs @@ -1,6 +1,6 @@ // SPDX-License-Identifier: GPL-3.0-or-later -use xenora_shader::{Architecture, CompileError, compile}; +use xenora_shader::{Architecture, CompileError, CompileOptions, compile, compile_with}; const FIXTURE: &[u8] = include_bytes!("../../../fixtures/rdna2/add.bin"); @@ -551,3 +551,314 @@ fn vop1_integer_fixture_lowers_unary_and_masked_swap() { include_str!("../../../fixtures/golden/vector-unary.metal") ); } + +// --- Opt-in constant folding: hand-computed known-answer fixtures ------------- +// Instruction words are built by hand to match the existing RDNA2 fixture shape +// (load, wait, mov literals, op, store). Expected constants are derived from the +// RDNA2 guide / MSL templates in lib.rs, then checked against fold-on IR. Fold-off +// (and default compile) must leave the op mnemonic in the IR. + +fn words(words: &[u32]) -> Vec { + words.iter().flat_map(|word| word.to_le_bytes()).collect() +} + +fn mov_lit(dst: u32) -> u32 { + 0x7e00_0000 | (dst << 17) | (1 << 9) | 255 +} + +fn vop2(op: u32, dst: u32, src0_vgpr: u32, src1_vgpr: u32) -> u32 { + (op << 25) | (dst << 17) | (src1_vgpr << 9) | (0x100 + src0_vgpr) +} + +fn vop1(op: u32, dst: u32, src_vgpr: u32) -> u32 { + 0x7e00_0000 | (dst << 17) | (op << 9) | (0x100 + src_vgpr) +} + +/// load v1; mov v2,A; mov v3,B; VOP2 dst=v2 (or v4); store the result VGPR. +fn binary_const_fixture(op: u32, left: u32, right: u32, dst_is_v4: bool) -> Vec { + let (dst, store_hi) = if dst_is_v4 { + (4u32, 0x8001_0400u32) + } else { + (2, 0x8001_0200) + }; + // For shift-rev forms the ISA encodes count in SRC0 and value in SRC1; the + // caller passes (count, value) already swapped into (src0, src1) via left/right + // naming below when needed. Non-rev forms use SRC0=v2, SRC1=v3. + let op_word = if dst_is_v4 { + // Shift-rev: v_l*rev dst, v3(count), v2(value) → SRC0=v3, SRC1=v2. + vop2(op, dst, 3, 2) + } else { + vop2(op, dst, 2, 3) + }; + words(&[ + 0xe030_2000, + 0x8000_0100, // buffer_load_dword v1 + 0xbf8c_3f70, // s_waitcnt vmcnt(0) + mov_lit(2), + left, // v_mov_b32 v2, left + mov_lit(3), + right, // v_mov_b32 v3, right + op_word, + 0xe070_2000, + store_hi, // buffer_store_dword result + 0xbbfd_0000, // s_waitcnt_vscnt + 0xbf81_0000, // s_endpgm + ]) +} + +fn unary_const_fixture(op: u32, source: u32) -> Vec { + words(&[ + 0xe030_2000, + 0x8000_0100, + 0xbf8c_3f70, + mov_lit(2), + source, // v_mov_b32 v2, source + vop1(op, 3, 2), // v_* v3, v2 + 0xe070_2000, + 0x8001_0300, // buffer_store_dword v3 + 0xbbfd_0000, + 0xbf81_0000, + ]) +} + +/// load; mov v2,A; mov v3,B; and v2,v2,v3; xor v1,v1,v2; store. +/// Hand-computed: 0x12345678 & 0xff00ff00 == 0x12005600. +fn constant_and_fixture() -> Vec { + const A: u32 = 0x1234_5678; + const B: u32 = 0xff00_ff00; + words(&[ + 0xe030_2000, + 0x8000_0100, + 0xbf8c_3f70, + mov_lit(2), + A, + mov_lit(3), + B, + 0x3604_0702, // v_and_b32 v2, v2, v3 (OP=27) + 0x3a02_0501, // v_xor_b32 v1, v1, v2 + 0xe070_2000, + 0x8001_0100, + 0xbbfd_0000, + 0xbf81_0000, + ]) +} + +fn compile_fold_off(code: &[u8]) -> xenora_shader::CompiledShader { + compile_with( + Architecture::Gfx1030, + code, + CompileOptions { + fold_constants: false, + }, + ) + .unwrap() +} + +fn compile_fold_on(code: &[u8]) -> xenora_shader::CompiledShader { + compile_with( + Architecture::Gfx1030, + code, + CompileOptions { + fold_constants: true, + }, + ) + .unwrap() +} + +fn assert_folds_to(code: &[u8], mnemonic: &str, expected: u32) { + let plain = compile_fold_off(code); + let folded = compile_fold_on(code); + let default = compile(Architecture::Gfx1030, code).unwrap(); + assert_eq!( + default.ir, plain.ir, + "default compile must match fold_constants: false" + ); + assert!( + plain.ir.contains(mnemonic), + "fold-off IR must keep {mnemonic}: {}", + plain.ir + ); + assert!( + !folded.ir.contains(mnemonic), + "fold-on IR must drop {mnemonic}: {}", + folded.ir + ); + let const_ir = format!("const.u32 0x{expected:08x}"); + assert!( + folded.ir.contains(&const_ir), + "fold-on IR must contain {const_ir}: {}", + folded.ir + ); + let const_msl = format!("0x{expected:08x}u"); + assert!( + folded.msl.contains(&const_msl), + "fold-on MSL must contain {const_msl}: {}", + folded.msl + ); +} + +#[test] +fn default_compile_matches_fold_constants_off() { + let code = constant_and_fixture(); + let baseline = compile(Architecture::Gfx1030, &code).unwrap(); + let explicit = compile_fold_off(&code); + assert_eq!(baseline.ir, explicit.ir); + assert_eq!(baseline.msl, explicit.msl); + assert!(baseline.ir.contains("and.b32")); +} + +#[test] +fn folds_constant_and_b32_to_known_answer() { + // 0x12345678 & 0xff00ff00 = 0x12005600 (bitwise and of each bit). + assert_folds_to(&constant_and_fixture(), "and.b32", 0x1200_5600); +} + +#[test] +fn folding_is_noop_on_add_fixture() { + let folded = compile_fold_on(FIXTURE); + let plain = compile(Architecture::Gfx1030, FIXTURE).unwrap(); + // add.bin has no pure constant-constant vector op, so folding is a no-op. + assert_eq!(folded.ir, plain.ir); + assert_eq!(folded.msl, plain.msl); + assert_eq!(plain.ir, include_str!("../../../fixtures/golden/add.ir")); +} + +#[test] +fn folds_lshl_by_32_as_shift_by_0() { + // Guide / MSL: count masked with S0[4:0] → 32 & 31 == 0, so 0xf0 << 0 == 0xf0. + // v_lshlrev_b32 OP=26; fixture stores into v4 (rev encoding). + let code = binary_const_fixture(26, 0x0000_00f0, 32, true); + assert_folds_to(&code, "lshl.b32", 0x0000_00f0); +} + +#[test] +fn folds_lshl_by_33_as_shift_by_1() { + // 33 & 31 == 1, so 0xf0 << 1 == 0x1e0. + let code = binary_const_fixture(26, 0x0000_00f0, 33, true); + assert_folds_to(&code, "lshl.b32", 0x0000_01e0); +} + +#[test] +fn folds_lshr_by_32_as_shift_by_0() { + // 32 & 31 == 0, so 0xf0 >> 0 == 0xf0. v_lshrrev_b32 OP=22. + let code = binary_const_fixture(22, 0x0000_00f0, 32, true); + assert_folds_to(&code, "lshr.b32", 0x0000_00f0); +} + +#[test] +fn folds_lshr_by_33_as_shift_by_1() { + // 33 & 31 == 1, so 0xf0 >> 1 == 0x78. + let code = binary_const_fixture(22, 0x0000_00f0, 33, true); + assert_folds_to(&code, "lshr.b32", 0x0000_0078); +} + +#[test] +fn folds_ashr_of_negative_value() { + // (-16 as i32) >> 4 == -1 → 0xffffffff. v_ashrrev_i32 OP=24. + let code = binary_const_fixture(24, 0xffff_fff0, 4, true); + assert_folds_to(&code, "ashr.i32", 0xffff_ffff); +} + +#[test] +fn folds_min_i32_and_min_u32_differ_on_sign_bit() { + // min_i32(0x80000000, 1) = min(-2^31, 1) = 0x80000000. + // min_u32(0x80000000, 1) = min(2^31, 1) = 1. + // They must differ. OP MinI32=17, MinU32=19. + assert_folds_to( + &binary_const_fixture(17, 0x8000_0000, 1, false), + "min.i32", + 0x8000_0000, + ); + assert_folds_to( + &binary_const_fixture(19, 0x8000_0000, 1, false), + "min.u32", + 1, + ); +} + +#[test] +fn folds_mul_hi_i32_i24_with_negative_input() { + // i24(0x00ffffff) = ((0x00ffffff << 8) >> 8) = -1; i24(2) = 2; + // (-1 * 2) as i64 >> 32 = -1 → 0xffffffff. v_mul_hi_i32_i24 OP=10. + let code = binary_const_fixture(10, 0x00ff_ffff, 2, false); + assert_folds_to(&code, "mulhi24.i32", 0xffff_ffff); +} + +#[test] +fn folds_ffbh_i32_on_zero_all_ones_and_one() { + // RDNA2 / MSL: return 0xffffffff when every bit matches the sign bit (0 or -1); + // else clz(x ^ (0 - (x >> 31))). For 1: clz(1) = 31. v_ffbh_i32 OP=59. + assert_folds_to(&unary_const_fixture(59, 0), "ffbh.i32", 0xffff_ffff); + assert_folds_to( + &unary_const_fixture(59, 0xffff_ffff), + "ffbh.i32", + 0xffff_ffff, + ); + assert_folds_to(&unary_const_fixture(59, 1), "ffbh.i32", 31); +} + +#[test] +fn folds_exact_positive_normal_float_add() { + // 1.0 + 2.0 = 3.0 exactly (positive normals). Bits: 0x3f800000 + 0x40000000 + // → 0x40400000. VOP2 add_f32 OP=3. + let code = binary_const_fixture(3, 0x3f80_0000, 0x4000_0000, false); + assert_folds_to(&code, "add.f32", 0x4040_0000); +} + +#[test] +fn float_add_from_load_stays_unfolded_with_fold_on() { + // float-exact.bin feeds add.f32 from a load-derived value (not a pure + // constant), so the op must remain even with fold_constants. Constant + // denormal / NaN / negative / inexact float pairs are rejected at verify + // (see rejects_inexact_float_add_of_constants_at_verify) and never reach + // the folder as stay-unfolded ops. + let plain = compile_fold_off(FLOAT); + let folded = compile_fold_on(FLOAT); + assert!( + plain.ir.contains("add.f32"), + "fold-off must keep add.f32: {}", + plain.ir + ); + assert!( + folded.ir.contains("add.f32"), + "fold-on must not rewrite load-derived add.f32: {}", + folded.ir + ); + assert!( + folded.ir.contains("mul.f32"), + "fold-on must not rewrite load-derived mul.f32: {}", + folded.ir + ); +} + +#[test] +fn rejects_inexact_float_add_of_constants_at_verify() { + // Both operands are positive normals, but 1.0 + 2^-24 is not representable + // in f32 (ulp of 1.0 is 2^-23), so exact_float_result refuses. Lift/verify + // rejects before fold_constant_ops runs; the op cannot "stay unfolded". + // Probed: fold_off and fold_on both return Verify at the add_f32 word. + let code = binary_const_fixture(3, 0x3f80_0000, 0x3380_0000, false); + let off = compile_with( + Architecture::Gfx1030, + &code, + CompileOptions { + fold_constants: false, + }, + ); + let on = compile_with( + Architecture::Gfx1030, + &code, + CompileOptions { + fold_constants: true, + }, + ); + assert!( + matches!(off, Err(CompileError::Verify { .. })), + "fold-off must reject inexact constant add.f32 at verify: {off:?}" + ); + assert!( + matches!(on, Err(CompileError::Verify { .. })), + "fold-on must reject inexact constant add.f32 at verify: {on:?}" + ); + // Folder unchanged: no stay-unfolded path exists for this pair. +} diff --git a/docs/README.md b/docs/README.md index 0b1dee5..89a2ada 100644 --- a/docs/README.md +++ b/docs/README.md @@ -48,6 +48,7 @@ either path. The [changelog](../CHANGELOG.md) records notable changes. - [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. +- [Gate A: a compiled C program](testing/gate-a.md) — The two milestones, what the A1 test checks and what it does not show. - [Mutation testing](testing/mutation.md) and [benchmark protocol](testing/benchmarks.md) — Test sensitivity, benchmark inputs, and timing requirements. ## Research and engineering decisions diff --git a/docs/interfaces.md b/docs/interfaces.md index e01565a..f6b0fb0 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -66,8 +66,34 @@ returns owned words after command completion or a stage-specific error. fixture, guest memory addresses, a service registry and an entry instruction budget. It maps and rebases the image, binds imports, initializes thread-local storage, invokes its callbacks and runs the entry point. The fixture entry point -uses a Win64-aligned stack and terminates with HLT. The result includes the loaded -guest memory and the entry execution outcome. +uses a Win64-aligned stack. It may end with HLT, call `ExitProcess`, or return. +The result includes the loaded guest memory and the entry execution outcome. + +A guest ends its process through `kernel32.dll!ExitProcess`, also reachable as +`api-ms-win-core-processthreads-l1-1-0.dll!ExitProcess`. Execution stops with +`ExitReason::ProcessExit(status)`, where the status is the full 32-bit value +the guest passed. Only the guest stops: the host process is not ended. A +returning entry point does the same with EAX as the status, which matches +Windows while the process has one thread. The exit closes every guest handle: +kernel objects, Winsock sockets and task-queue handles, which +`ServicesState::open_handle_count` counts together. Files stay on the synthetic `C:` drive, guest memory stays mapped so the host +can inspect it, and `atexit` functions are not run: that belongs to the C +runtime's `exit`, which is not implemented. `ServicesState::exit_status` +reports the status. After an exit the `DbtEngine` that ran the guest executes +no further guest instruction and answers every later `run` with the same +`ProcessExit`. A service callback that was in progress is never resumed. + +A TLS callback may end the process too. Startup then reports the exit as its +outcome, with the status, and runs neither the remaining callbacks nor the +entry point; `StartupResult::tls_callbacks` counts the callbacks that finished. +Any other stop inside a TLS callback is still a startup error. + +The engine recognises two return addresses, one under the entry point and one +under a guest callback, before it executes anything at them. Both are in the +4 KiB page at `imports::RETURN_SENTINEL_PAGE`, which startup reserves with no +access. An image or layout that covers that page is refused, and a guest +allocation there fails. The import trampolines above that page are intercepted +in the same way and are not reserved. Loading an image maps its headers as well as its sections. The first `SizeOfHeaders` bytes of the file are mapped read-only at the image base, in diff --git a/docs/testing/gate-a.md b/docs/testing/gate-a.md new file mode 100644 index 0000000..91a85eb --- /dev/null +++ b/docs/testing/gate-a.md @@ -0,0 +1,53 @@ +# Gate A: a compiled C program + +Gate A asks for an independently compiled C program, exercising allocation, +file operations, arithmetic, function calls and error handling, to run through +Xenora. The maintainer split it into two milestones. Gate A is complete only +when both pass. + +| Milestone | What it is | Status | +| --- | --- | --- | +| A1 | An original C program with no C library linked, importing documented `kernel32.dll` and `ucrtbase.dll` functions, run through the loader and the ARM64 DBT with proper process exit | Passes locally; awaiting independent review | +| A2 | A hosted C program: a real C runtime startup, the standard C library, `argc` and `argv`, stdio and formatted output, normal exit and runtime cleanup | Not started | + +## A1 + +The program is [`tests/compat_fixtures/gate_a1.c`](../../tests/compat_fixtures/gate_a1.c). +Its build configuration and provenance are in +[`tests/compat_fixtures/README.md`](../../tests/compat_fixtures/README.md#gate-a1-a-c-program-with-no-c-library). +The gate is `crates/loader/tests/gate_a1.rs`: + +```sh +cargo test --locked -p xenora-loader --test gate_a1 -- --nocapture +``` + +The test builds the program from source, then runs each build through +`run_synthetic_startup` with `register_standard_services`, loaded away from its +preferred base. It checks, at `-O0`, `-O1`, `-O2` and `-Os`: + +- the 20 imports are bound and the 6 base relocations applied; +- the guest ends with `ExitReason::ProcessExit(0x00A1A1A1)`, all 32 bits; +- it ran as translated code, with service calls; +- the text report it wrote matches a report recomputed in Rust; +- the data file holds the 64 sorted records, the file it looked for does not exist, and the handle it left open was closed by the exit; +- its result block in guest memory holds the expected values, the block it kept is readable and the block it freed is unmapped. + +Three controls must fail in the stated way: a wrong expectation exits with the +number of the failed check, an import that no service provides is refused +before entry, and a step budget that is too small is not an exit. A variant +whose entry point returns its status gives the same result as `ExitProcess`. + +### What A1 does not show + +- It is one program. Local runs used Homebrew clang 23.1.6 and Apple clang 17.0.0, each with LLD 23.1.5. Another compiler or a larger program can need instructions and services this one does not. +- Most services it calls are marked partial in the registry. They did what this program needs. +- It runs in the DBT only. The interpreter has no import dispatch. +- It reaches the guest through a test, not through `xenora run`, which accepts only two built-in fixtures. +- Nothing here concerns a commercial game or an Xbox launch environment. + +## A2 + +Not started. It needs at least the C standard I/O functions, `exit` with +`atexit` handlers, command-line and environment access, and a decision on +which C runtime startup code may be linked and under what licence. None of +those are registered today. diff --git a/tests/compat_fixtures/README.md b/tests/compat_fixtures/README.md index cb05814..423dceb 100644 --- a/tests/compat_fixtures/README.md +++ b/tests/compat_fixtures/README.md @@ -66,3 +66,47 @@ enabled. The runner prints the guest's exit value and returns a nonzero host status for load or interpreter faults. The gate compares both outcomes. These fixtures exercise synthetic commands and local Apple Silicon readback. + +## Gate A1: a C program with no C library + +`gate_a1.c` is an original C program that links no C library. It imports +twelve functions from `ucrtbase.dll` and eight from `kernel32.dll` by name, +with prototypes written from the public Windows SDK and C standard +declarations. It allocates and frees memory, sorts with a callback, does +64-bit and double arithmetic, uses the C string functions, writes and reads +files on the synthetic `C:` drive, checks two error paths, writes a text +report and ends with `ExitProcess`. + +`build-gate-a1.sh [output directory]` builds it. `cargo test -p xenora-loader +--test gate_a1` runs that script and then runs the result through +`run_synthetic_startup`, the standard services and the DBT. No built +executable is committed: the test builds from source every time, in CI too. + +Compiler configuration: + +| Step | Command | +| --- | --- | +| Compile | `clang --target=x86_64-pc-windows-msvc -O -ffreestanding -fno-stack-protector -Wall -Wextra -Werror` | +| Import libraries | `lld-link /lib /machine:x64 /def:.def` from the name lists in the script | +| Link | `lld-link /entry:gate_entry /subsystem:console /nodefaultlib /timestamp:0` | + +It is built at `-O0`, `-O1`, `-O2` and `-Os`, and three more times at `-O1` as +controls: `GATE_BREAK` (one wrong expectation), `GATE_RETURN` (the entry point +returns its status) and `GATE_MISSING` (an import no service provides). + +Tools. `CLANG` defaults to Homebrew LLVM when it is installed and otherwise to +the `clang` on `PATH`. `LLD_LINK` defaults to Homebrew `lld` when it is +installed and otherwise to the `rust-lld` inside the active Rust toolchain, +which is an LLD. On macOS the script requires both, and every library they +load that is a file on disk, to be ARM64: it checks each tool with `file` and +`lipo -archs`, and each library `otool -L` lists with `lipo -archs`, following +the tool's own run paths. The script writes the versions it used to +`toolchain.txt`, which the test prints, and what the native checks looked at to +`toolchain-native.txt`. The test builds into a directory of its own for each +test process under the Cargo target directory, so two runs that share a target +directory do not overwrite each other's files; `cargo clean` removes them. + +Provenance. The source, the name lists and the script were written for Xenora +and are GPL-3.0-or-later. Nothing from a Windows SDK, a C runtime or another +project is compiled or linked. The compiler and linker are LLVM projects +under the Apache License 2.0 with LLVM exceptions; they are tools, not inputs. diff --git a/tests/compat_fixtures/build-gate-a1.sh b/tests/compat_fixtures/build-gate-a1.sh new file mode 100755 index 0000000..acba22b --- /dev/null +++ b/tests/compat_fixtures/build-gate-a1.sh @@ -0,0 +1,140 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-3.0-or-later +# +# Build the Gate A1 program, tests/compat_fixtures/gate_a1.c, as x86-64 PE32+ +# executables with no C library linked. +# +# build-gate-a1.sh [output directory] default: artifacts/gate-a1 +# +# Tools, all native to the host: +# CLANG a clang that accepts --target=x86_64-pc-windows-msvc. Default: +# Homebrew LLVM if installed, otherwise the clang on PATH. +# LLD_LINK an lld-link. Default: Homebrew lld if installed, otherwise the +# rust-lld that ships in the active Rust toolchain. +# +# The linker also makes the two import libraries, from the definition files +# written below, so nothing from a Windows SDK or another C runtime is used. +set -eu +cd "$(dirname "$0")/../.." +root=$PWD +src="$root/tests/compat_fixtures/gate_a1.c" +out=${1:-"$root/artifacts/gate-a1"} + +clang=${CLANG:-} +if [ -z "$clang" ]; then + clang=/opt/homebrew/opt/llvm/bin/clang + [ -x "$clang" ] || clang=$(command -v clang) +fi +flavor= +linker=${LLD_LINK:-} +if [ -z "$linker" ]; then + linker=/opt/homebrew/opt/lld/bin/lld-link + if [ ! -x "$linker" ]; then + host=$(rustc -vV | sed -n 's/^host: //p') + linker="$(rustc --print sysroot)/lib/rustlib/$host/bin/rust-lld" + flavor="-flavor link" + fi +fi +for tool in "$clang" "$linker"; do + [ -x "$tool" ] || { echo "missing tool: $tool" >&2; exit 1; } +done +# AGENTS.md: host tools and what they load must be ARM64, checked with file, +# lipo -archs and otool -L. An @rpath library is looked up through the tool's +# own run paths. A library that is still not a file on disk is in the system's +# shared cache, and is listed only. +native= +if [ "$(uname -s)" = Darwin ]; then + for tool in "$clang" "$linker"; do + case "$(file -bL "$tool")" in + *arm64*) ;; + *) echo "ARM64 tool required (file): $tool" >&2; exit 1 ;; + esac + case "$(lipo -archs "$tool")" in + *arm64*) ;; + *) echo "ARM64 tool required (lipo): $tool" >&2; exit 1 ;; + esac + here=$(dirname "$tool") + runpaths=$(otool -l "$tool" | awk '/LC_RPATH/ { getline; getline; print $2 }' | + sed "s|@loader_path|$here|; s|@executable_path|$here|") + for library in $(otool -L "$tool" | awk 'NR > 1 { print $1 }'); do + case "$library" in + @rpath/*) + for runpath in $runpaths; do + if [ -f "$runpath/${library#@rpath/}" ]; then + library="$runpath/${library#@rpath/}" + break + fi + done ;; + esac + [ -f "$library" ] || continue + case "$(lipo -archs "$library")" in + *arm64*) ;; + *) echo "ARM64 library required by $tool: $library" >&2; exit 1 ;; + esac + native="$native $library: $(lipo -archs "$library") +" + done + native="$native$(file -bL "$tool") +$(otool -L "$tool") +" + done +fi +# $flavor is empty or two words on purpose. +# shellcheck disable=SC2086 +link() { "$linker" $flavor "$@"; } + +mkdir -p "$out" +cd "$out" +{ + "$clang" --version | head -1 + link --version | head -1 +} > toolchain.txt +# What the native checks above looked at. +printf '%s' "$native" > toolchain-native.txt + +cat > kernel32.def <<'DEF' +LIBRARY kernel32.dll +EXPORTS + CloseHandle + CreateFileW + ExitProcess + GateMissingService + GetFileSizeEx + GetLastError + ReadFile + SetFilePointerEx + WriteFile +DEF +cat > ucrtbase.def <<'DEF' +LIBRARY ucrtbase.dll +EXPORTS + _errno + free + malloc + memcmp + memcpy + memset + qsort + realloc + strcmp + strlen + strncmp + strtol +DEF +link /lib /machine:x64 /def:kernel32.def /out:kernel32.lib +link /lib /machine:x64 /def:ucrtbase.def /out:ucrtbase.lib + +# name, optimization level, extra definition +build() { + "$clang" --target=x86_64-pc-windows-msvc "-$2" -ffreestanding -fno-stack-protector \ + -Wall -Wextra -Werror ${3:+"-D$3"} -c "$src" -o "$1.obj" + link /entry:gate_entry /subsystem:console /nodefaultlib /timestamp:0 \ + "/out:$1.exe" "$1.obj" kernel32.lib ucrtbase.lib +} +for level in O0 O1 O2 Os; do + build "gate-a1-$level" "$level" "" +done +# Controls: a wrong expectation, a returning entry point, an import nobody provides. +build gate-a1-break O1 GATE_BREAK +build gate-a1-return O1 GATE_RETURN +build gate-a1-missing O1 GATE_MISSING diff --git a/tests/compat_fixtures/gate_a1.c b/tests/compat_fixtures/gate_a1.c new file mode 100644 index 0000000..68a1bdf --- /dev/null +++ b/tests/compat_fixtures/gate_a1.c @@ -0,0 +1,314 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// +// Gate A1: an original C program with no C library linked. +// +// It allocates and frees memory, sorts with a callback, does 64-bit and +// double arithmetic, uses the C string functions, reads and writes files on +// the synthetic C: drive, checks two error paths, writes a text report and +// ends its process with a status. Every outside function is imported by name +// from kernel32.dll or ucrtbase.dll; the prototypes below follow the public +// Windows SDK and C standard declarations. Nothing else is linked. +// +// Build with tests/compat_fixtures/build-gate-a1.sh. The test that runs it, +// crates/loader/tests/gate_a1.rs, recomputes every number in the report. + +typedef unsigned long long u64; +typedef long long i64; +typedef unsigned int u32; +typedef unsigned short wchar; +typedef unsigned char u8; + +#define IMPORT __declspec(dllimport) + +// ucrtbase.dll +IMPORT void *malloc(u64 size); +IMPORT void *realloc(void *block, u64 size); +IMPORT void free(void *block); +IMPORT int *_errno(void); +IMPORT u64 strlen(const char *text); +IMPORT int strcmp(const char *left, const char *right); +IMPORT int strncmp(const char *left, const char *right, u64 count); +IMPORT long strtol(const char *text, char **end, int base); +IMPORT void *memcpy(void *to, const void *from, u64 count); +IMPORT void *memset(void *to, int value, u64 count); +IMPORT int memcmp(const void *left, const void *right, u64 count); +IMPORT void qsort(void *base, u64 count, u64 size, int (*compare)(const void *, const void *)); + +// kernel32.dll +IMPORT void *CreateFileW(const wchar *name, u32 access, u32 share, void *security, + u32 disposition, u32 flags, void *template_file); +IMPORT int WriteFile(void *file, const void *data, u32 size, u32 *written, void *overlapped); +IMPORT int ReadFile(void *file, void *data, u32 size, u32 *read, void *overlapped); +IMPORT int SetFilePointerEx(void *file, i64 distance, i64 *position, u32 method); +IMPORT int GetFileSizeEx(void *file, i64 *size); +IMPORT int CloseHandle(void *object); +IMPORT u32 GetLastError(void); +IMPORT void ExitProcess(u32 status); +#ifdef GATE_MISSING +// Negative control: a name no service provides. +IMPORT void GateMissingService(void); +#endif + +#define INVALID_HANDLE ((void *)-1) +#define GENERIC_READ 0x80000000u +#define GENERIC_WRITE 0x40000000u +#define CREATE_ALWAYS 2 +#define OPEN_EXISTING 3 +#define ERROR_FILE_NOT_FOUND 2 +#define ENOMEM 12 + +// The status of a run in which every check passed. It is wider than a byte so +// the test can tell that all 32 bits arrive. +#define GATE_A1_STATUS 0x00A1A1A1u +#define RECORDS 64 + +// The compiler refers to this when a program uses floating point. +int _fltused = 0x9875; + +struct record { + u32 key; + u32 weight; + double ratio; +}; + +// What the host reads from guest memory afterwards, in a section of its own +// so the test can find it by name. +struct gate_result { + u32 magic; + u32 checks; + u64 key_checksum; + void *kept; + void *freed; +}; +#pragma section(".gate", read, write) +__declspec(allocate(".gate")) struct gate_result gate_result = {0x31415926u, 0, 0, 0, 0}; + +// Six steps reached through a table of pointers, which gives the image base +// relocations. The table is volatile so that an optimizer keeps it. +static u64 step_multiply(u64 value, u32 round) { + (void)round; + return value * 6364136223846793005ULL + 1442695040888963407ULL; +} +static u64 step_rotate(u64 value, u32 round) { + (void)round; + return (value << 13) | (value >> 51); +} +static u64 step_divide(u64 value, u32 round) { + (void)round; + return value / 7 + value % 1000003; +} +static u64 step_fold(u64 value, u32 round) { + (void)round; + return value ^ (value >> 29); +} +static u64 step_signed(u64 value, u32 round) { + (void)round; + return (u64)((i64)value / -3); +} +static u64 step_subtract(u64 value, u32 round) { return value - round; } + +static u64 (*volatile steps[6])(u64, u32) = {step_multiply, step_rotate, step_divide, + step_fold, step_signed, step_subtract}; + +static u64 mix(u64 value, u32 round) { return steps[round % 6](value, round); } + +static int by_key(const void *left, const void *right) { + const struct record *a = left, *b = right; + return a->key < b->key ? -1 : a->key > b->key; +} + +static u32 fibonacci(u32 n) { return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); } + +// FNV-1a over the keys, least significant byte first. +static u64 checksum_keys(const struct record *records, u32 count) { + u64 sum = 0xCBF29CE484222325ULL; + for (u32 index = 0; index < count; index++) + for (u32 byte = 0; byte < 4; byte++) + sum = (sum ^ ((records[index].key >> (8 * byte)) & 0xFF)) * 0x100000001B3ULL; + return sum; +} + +// A small text writer, since no formatted output function is linked. +struct text { + char *bytes; + u32 used; +}; +static void put_text(struct text *out, const char *text) { + u64 length = strlen(text); + memcpy(out->bytes + out->used, text, length); + out->used += (u32)length; +} +static void put_unsigned(struct text *out, u64 value) { + char digits[20]; + u32 count = 0; + do { + digits[count++] = (char)('0' + value % 10); + value /= 10; + } while (value); + while (count) + out->bytes[out->used++] = digits[--count]; +} +static void put_signed(struct text *out, i64 value) { + if (value < 0) { + out->bytes[out->used++] = '-'; + put_unsigned(out, (u64)0 - (u64)value); + } else { + put_unsigned(out, (u64)value); + } +} + +// A failed check ends the process with the number of that check. +#define CHECK(condition) \ + do { \ + gate_result.checks++; \ + if (!(condition)) \ + return gate_result.checks; \ + } while (0) + +static u32 run(void) { + // Allocation: fill a block, grow it, and keep what it held. + struct record *records = malloc(RECORDS * sizeof *records); + CHECK(records != 0); + u64 state = 0x243F6A8885A308D3ULL; + for (u32 index = 0; index < RECORDS; index++) { + state = mix(state, index); + // The index in the low six bits makes every key different, so the + // sorted order does not depend on how the sort treats equal keys. + records[index].key = ((u32)(state >> 20) << 6) | index; + records[index].weight = index; + records[index].ratio = (double)(state & 0xFFFF) / 65536.0; + } + u32 first_key = records[0].key; + struct record *grown = realloc(records, 2 * RECORDS * sizeof *records); + CHECK(grown != 0); + records = grown; + CHECK(records[0].key == first_key && records[RECORDS - 1].weight == RECORDS - 1); + + // Computation. Each product below is an exact double, and so is their sum, + // so the scaled total is an integer the host can recompute. + double total = 0; + for (u32 index = 0; index < RECORDS; index++) + total += records[index].ratio * records[index].weight; + u64 weighted = (u64)(total * 65536.0); + qsort(records, RECORDS, sizeof *records, by_key); + for (u32 index = 1; index < RECORDS; index++) + CHECK(records[index - 1].key <= records[index].key); + gate_result.key_checksum = checksum_keys(records, RECORDS); +#ifdef GATE_BREAK + // Negative control: one expectation is wrong, so this check fails. + CHECK(fibonacci(12) == 145); +#else + CHECK(fibonacci(12) == 144); +#endif + i64 wide = (i64)(state % 1000000007ULL) * -977 / 13; + + // Strings. + static const char line[] = "gate-a1:0x7b:-42"; + char scratch[32]; + char *end = 0; + CHECK(strlen(line) == 16); + CHECK(strcmp(line, "gate-a1:0x7b:-42") == 0 && strcmp("gate", "gave") < 0); + CHECK(strncmp(line, "gate-b9", 5) == 0 && strncmp(line, "gate-b9", 6) != 0); + long hex = strtol(line + 8, &end, 16); + CHECK(hex == 123 && end == line + 12); + long negative = strtol(line + 13, &end, 10); + CHECK(negative == -42 && *end == 0); + memset(scratch, '.', sizeof scratch); + memcpy(scratch, line, 7); + CHECK(memcmp(scratch, "gate-a1.", 8) == 0 && scratch[31] == '.'); + // Unequal blocks, in both orders: a memcmp that always says "equal" fails here. + CHECK(memcmp(scratch, "gate-a2.", 8) < 0 && memcmp("gate-b", scratch, 6) > 0); + + // Errors: a file that does not exist and an allocation that cannot succeed. + static const wchar none[] = {'C', ':', '\\', 'n', 'o', 'n', 'e', '.', 'b', 'i', 'n', 0}; + CHECK(CreateFileW(none, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0) == INVALID_HANDLE); + u32 missing = GetLastError(); + CHECK(missing == ERROR_FILE_NOT_FOUND); + *_errno() = 0; + CHECK(malloc(~0ULL) == 0); + int exhausted = *_errno(); + CHECK(exhausted == ENOMEM); + + // Files: write the sorted records, then read them back through the same + // handle and compare. + static const wchar data_name[] = {'C', ':', '\\', 'g', 'a', 't', 'e', '-', 'a', + '1', '.', 'b', 'i', 'n', 0}; + u32 bytes = RECORDS * (u32)sizeof *records; + u32 moved = 0; + i64 size = 0; + void *file = CreateFileW(data_name, GENERIC_READ | GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, 0); + CHECK(file != INVALID_HANDLE); + CHECK(WriteFile(file, records, bytes, &moved, 0) && moved == bytes); + CHECK(GetFileSizeEx(file, &size) && size == bytes); + CHECK(SetFilePointerEx(file, 0, 0, 0)); + u8 *copy = malloc(bytes); + CHECK(copy != 0); + CHECK(ReadFile(file, copy, bytes, &moved, 0) && moved == bytes); + CHECK(memcmp(copy, records, bytes) == 0); + // The same comparison without memcmp, and a one-bit difference in the + // last byte that memcmp has to see. + u32 same = 0; + for (u32 i = 0; i < bytes; i++) same += copy[i] == ((const u8 *)records)[i]; + CHECK(same == bytes); + copy[bytes - 1] ^= 1; + CHECK(memcmp(copy, records, bytes) != 0); + copy[bytes - 1] ^= 1; + CHECK(CloseHandle(file)); + + // Memory the host inspects afterwards: one block freed, one kept. + static const char kept_text[] = "kept by gate a1"; + char *kept = malloc(sizeof kept_text); + CHECK(kept != 0); + memcpy(kept, kept_text, sizeof kept_text); + gate_result.kept = kept; + gate_result.freed = copy; + free(copy); + free(records); + + // The report. Its handle is left open on purpose: ending the process has + // to close it. + static const wchar report_name[] = {'C', ':', '\\', 'g', 'a', 't', 'e', '-', 'a', + '1', '.', 't', 'x', 't', 0}; + struct text report = {malloc(256), 0}; + CHECK(report.bytes != 0); + put_text(&report, "gate a1\nrecords "); + put_unsigned(&report, RECORDS); + put_text(&report, "\nkeys "); + put_unsigned(&report, gate_result.key_checksum); + put_text(&report, "\nweighted "); + put_unsigned(&report, weighted); + put_text(&report, "\nfibonacci "); + put_unsigned(&report, fibonacci(12)); + put_text(&report, "\nwide "); + put_signed(&report, wide); + put_text(&report, "\nstrings "); + put_unsigned(&report, strlen(line)); + put_text(&report, " "); + put_signed(&report, hex); + put_text(&report, " "); + put_signed(&report, negative); + put_text(&report, "\nerrors "); + put_unsigned(&report, missing); + put_text(&report, " "); + put_signed(&report, exhausted); + put_text(&report, "\nfile "); + put_unsigned(&report, bytes); + put_text(&report, "\n"); + void *log = CreateFileW(report_name, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, 0); + CHECK(log != INVALID_HANDLE); + CHECK(WriteFile(log, report.bytes, report.used, &moved, 0) && moved == report.used); + return GATE_A1_STATUS; +} + +#ifdef GATE_RETURN +// Variant: the entry point returns its status instead of calling ExitProcess. +u32 gate_entry(void) { return run(); } +#else +void gate_entry(void) { +#ifdef GATE_MISSING + if (!gate_result.magic) + GateMissingService(); +#endif + ExitProcess(run()); +} +#endif