Compare commits

...
Author SHA1 Message Date
devil8blade 0caca18634 shader: opt-in IR common-subexpression elimination (#142)
Reuse the first equivalent pure vector unary or binary when
CompileOptions::eliminate_common_subexpressions is set. The flag defaults
off, so existing output stays byte-identical. Loads, stores, constant
definitions, lane masks, merges, branches and other side-effecting or
mask-dependent ops are not reused. Constant folding still runs first.

Signed-off-by: devil8blade <360741796+devil8blade@users.noreply.github.com>
2026-11-24 20:49:19 -05:00
Ranveer Soni 2ea75603be Merge pull request #338 from LanaCodes-Boop/runtime/guest-clock-fixtures
loader: stop the mock clock wrapping and test time services against one clock (#204)
2026-11-25 06:56:35 +05:30
Ranveer Soni 6fc06dccff Merge branch 'main' into runtime/guest-clock-fixtures 2026-11-25 06:56:20 +05:30
Ranveer Soni a1295d5a48 Merge pull request #331 from zachdoxsee/task/329-gate-a1
loader: add process exit and the Gate A1 compiled C program (#329)
2026-11-25 06:55:50 +05:30
zachdoxsee 0929d0214b Move the changelog entry down the list
Every merge to main adds its entry at the head of the Added list, and so did
this branch, so each of those merges put this branch in conflict over one
line. The entry is unchanged; it now sits lower down, in a place of its own.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:14:00 +01:00
zachdoxsee 66f7127553 Merge upstream main into task/329-gate-a1
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 02:10:46 +01:00
zachdoxsee 9d94c0f40a Merge upstream main into task/329-gate-a1
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 01:56:40 +01:00
zachdoxsee 4e18000798 Merge upstream main into task/329-gate-a1
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 01:56:31 +01:00
zachdoxsee e6fa931264 Merge upstream main into task/329-gate-a1
Any conflict was in CHANGELOG.md, where every entry is kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 22:24:13 +01:00
zachdoxsee 04ee981103 Merge upstream main into task/329-gate-a1
Any conflict was in CHANGELOG.md, where every entry is kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 22:01:29 +01:00
zachdoxsee 35de41bd5f Merge upstream main into task/329-gate-a1
Conflict in CHANGELOG.md only: every entry is kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 21:43:49 +01:00
zachdoxsee a0d4b7bf5d Merge upstream main into task/329-gate-a1
Conflict in CHANGELOG.md only: every entry is kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 20:21:39 +01:00
zachdoxsee 830f93ff14 loader: address review of process exit and the Gate A1 program (#329)
- An ExitProcess call in a TLS callback is a normal startup outcome with
  its status. The remaining callbacks and the entry point do not run.
- Exit closes Winsock sockets and task-queue handles as well as kernel
  objects, and open_handle_count counts all three tables.
- Startup reserves the page holding the entry-return and callback-return
  addresses, so an image mapped over them is refused and a guest
  allocation there fails.
- The Gate A1 program checks unequal memcmp results and compares the
  bytes it read back without memcmp.
- The gate test builds in a directory of its own per test process.
- The build script checks its tools and their libraries with file,
  lipo -archs and otool -L.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 19:55:20 +01:00
zachdoxsee 4962f054c8 Merge upstream main into task/329-gate-a1
Conflict in CHANGELOG.md only: both new entries are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 19:47:49 +01:00
zachdoxsee 48e1e5c8c1 Merge upstream main into task/329-gate-a1
Conflict in CHANGELOG.md only: both new entries are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 18:24:36 +01:00
LanaCodes-Boop 94732d90ca Merge remote-tracking branch 'upstream/main' into runtime/guest-clock-fixtures
Signed-off-by: LanaCodes-Boop <139008131+LanaCodes-Boop@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 14:22:11 -03:00
LanaCodes-Boop 1e8893a6bf loader: stop the mock clock wrapping and test time services against one clock (#204)
Signed-off-by: LanaCodes-Boop <139008131+LanaCodes-Boop@users.noreply.github.com>
2026-11-24 14:21:14 -03:00
zachdoxsee 47cb26ebdd loader: add process exit and the Gate A1 compiled C program (#329)
A guest can now end its process. kernel32.dll!ExitProcess stops execution
with the new ExitReason::ProcessExit(status), keeping all 32 bits of the
status, and never ends the host. A returning entry point does the same
with EAX: startup puts an exit address under the entry point. The exit
closes every guest handle, and the DbtEngine that ran the guest executes
no further guest instruction.

Gate A1 is an original C program with no C library linked. The test
builds it from source with clang and an LLD, runs it through
run_synthetic_startup, the standard services and the DBT at four
optimization levels, and checks its exit status, report, files and
memory against values recomputed in Rust. Three controls must fail in
the stated way. Gate A stays open until the hosted milestone, A2.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 17:42:09 +01:00
21 changed files with 2695 additions and 17 deletions

No files matched your search

+5
View File
@@ -32,7 +32,9 @@ remains unsupported.
- Added a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status.
### Added
- Added `tests/runtime_clock.rs`, which reads the performance counter, its frequency, both tick counts, the unbiased interrupt time and the system time from one injected clock and checks that they report the same elapsed time in their own units, after a host advance and after a guest `Sleep`, and that none of them decreases up to and past the end of the clock (#204). Expected values are worked out by hand from the documented units. Timed waits still return without consuming clock time.
- Added opt-in shader IR constant folding (`CompileOptions::fold_constants` / `compile_with`) for pure vector unary and binary ops whose operands are already constants (#141). Floating-point ops still use the exact positive-normal rules; loads, stores, lane masks, merges and branches are never folded. Default `compile` keeps the historical IR. Covered by hand-computed known-answer compiler tests (shifts by 32/33, ashr, min_i32 vs min_u32, mul_hi_i32_i24, ffbh_i32, exact float fold, load-derived float non-fold, and verify rejection of inexact constant float add) with a fold-on versus fold-off check, plus an MSL template drift check over every foldable op.
- Added opt-in shader IR common-subexpression elimination (`CompileOptions::eliminate_common_subexpressions` / `compile_with`) that reuses the first result of an equivalent pure vector unary or binary (#142). Equivalence is the same operation and the same operand values in the same order; constant operands match by bit pattern. Loads, stores, constant definitions, lane masks, merges, branches and other side-effecting or execution-mask-dependent ops are left in place. The pass runs after constant folding, so folded results stay constants and a later pure op on two equal folded constants can still be reused. Default `compile` keeps the historical IR. Covered by hand-derived known-answer compiler tests for reuse (and/xor, not, exact float add), for rejected loads, swapped subtracts, lane masks, lane merges and VCC selects, and for the four combinations with constant folding (1 + 2 = 3, and 1.0 + 2.0 = 3.0), and a check that the 13 golden fixtures, none of which repeats an expression, compile unchanged with the pass on. No speedup is claimed.
- The loader now maps an image's PE headers at its image base (#333): the first `SizeOfHeaders` bytes of the file, read-only, in whole 4 KiB pages that are zero past `SizeOfHeaders`. Programs read their own headers this way; the mingw-w64 C runtime does so before `main`, and until now that read faulted. When startup relocates an image it writes the load base into the mapped `ImageBase` field after the relocations, so an entry aimed at that field cannot move it twice; this is Xenora's policy and has not been compared with Windows. A load is refused with the new `PeError::InvalidHeaderSize` when `SizeOfHeaders` is zero, ends before the section table, runs past the file, or its pages would reach into a section, and when the bytes handed to the loader are not the PE32+ headers that were parsed. The page rule refuses images with sub-page section alignment whose first section starts inside the header page, which loaded before. The header pages count toward the 256 MiB mapping budget, which is checked before anything is mapped. `ParsedPe::parse` and the static probe are unchanged. `tests/pe_headers.rs` covers guest reads at the preferred and a relocated base, a relocation aimed at `ImageBase`, the write and execute faults and each refusal with original hand-built images; the image in `pe_mapping_limits.rs` now carries a valid `SizeOfHeaders`. Awaiting independent re-review.
- Added 35 known-answer cases for MOV with an immediate operand, opcodes C6 /0 and C7 /0 (#194), to `cpu_known_answers.rs`: byte, word, dword and qword stores through base, SIB, R12, R13, RSP and RBP addressing with 8-bit and 32-bit displacements; the imm32 sign extension of the 64-bit form; the register forms, including AH and a REX-selected SIL; unmapped and read-only store faults at each width; and #UD for reg field 1. Expected values come from the Intel SDM and were worked out by hand. The interpreter and the DBT already agreed with all of them, so this is new coverage and fixes no defect. The 16-bit forms covered are those that already run, and #118 stays open. Not compared with x86 hardware; awaiting independent review.
- `dbt_bench` can also write its results as one JSON document when `XENORA_DBT_BENCH_JSON=<path>` is set (#112). The document records the host CPU, OS and architecture, the git revision and whether the tree had local changes, debug assertions, the workload and sample counts, the median, minimum, maximum, p95, p99, IQR and MIPS for the interpreter and for cold and warm DBT, and the cold DBT counters. Anything the benchmark cannot determine is `null`. The text output and the timed work are unchanged.
@@ -101,6 +103,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.
@@ -226,6 +230,7 @@ remains unsupported.
native DBT.
### Fixed
- `MockClock::advance` no longer wraps the FILETIME. A large advance made the synthetic wall clock run backwards while the performance count beside it stopped at its maximum; both now stop at their maximum (#204).
- Fixed `DuplicateHandle` and `GetThreadId` naming the main thread from other guest threads, `OwningThread` in critical sections always holding the main thread's ID, the callback-depth limit being shared by all guest threads, and pending one-time initializations being unbounded.
- Fixed the address reported when a guest memory access faults part-way across a 4 KiB page boundary (#175). An access that starts in a mapped page and runs into an unmapped or forbidden one now reports the first byte it may not touch; it used to report the start of the access. An access whose first byte fails reports the same address as before, and a failed access still reads and writes nothing. Three Intel SDM page-fault cases in `cpu_known_answers.rs` moved from open defect to verified on both engines. `crates/loader/tests/memory_page_boundaries.rs` checks permissions, adjacent pages, address overflow and the fault address at every 4 KiB guest boundary across two host pages (16 KiB each on Apple Silicon). Guest memory is checked in software, so the host page size does not affect these results. Four #82 expectations and one CRT `memmove` expectation that pinned the start address were corrected. Not compared with x86 hardware; awaiting independent review.
- Fixed the native dependency audit reading Cargo JSON and inspection-tool output in the process locale encoding; it now reads and reports UTF-8 paths and diagnostics under an ASCII locale (#363).
+4
View File
@@ -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")
}
+30
View File
@@ -48,6 +48,8 @@ pub struct DbtEngine {
services: HashMap<u64, HostServiceFn>,
pub import_registry: Option<crate::imports::ImportRegistry>,
pub metrics: DbtMetrics,
/// Exit status of a guest that ended its process on this engine.
exited: Option<u32>,
}
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;
+26
View File
@@ -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
+82 -1
View File
@@ -17,6 +17,7 @@ mod gdk_queue;
mod heap;
mod modules;
mod platform_fixture;
mod process;
mod synch;
pub mod sysinfo;
mod task_fixture;
@@ -93,8 +94,14 @@ impl MockClock {
}
}
/// Move both readings forward by `intervals` 100-nanosecond ticks. Each
/// stops at its maximum, so neither ever runs backwards.
pub fn advance(&self, intervals: u64) {
self.current.fetch_add(intervals, Ordering::SeqCst);
self.current
.try_update(Ordering::SeqCst, Ordering::SeqCst, |current| {
Some(current.saturating_add(intervals))
})
.expect("clock update always returns a value");
self.performance_count
.try_update(Ordering::SeqCst, Ordering::SeqCst, |count| {
Some(count.saturating_add(intervals).min(MAX_PERFORMANCE_COUNT))
@@ -198,6 +205,8 @@ pub struct ServicesState {
pub(crate) hooks: Arc<threads::SchedulerHooks>,
/// Functions registered with `atexit`, run in reverse order by `_cexit`.
atexit: Mutex<Vec<u64>>,
/// The status the guest process exited with. Set once.
exit_status: Mutex<Option<u32>>,
winsock: Mutex<winsock::Winsock>,
task_fixture: Mutex<task_fixture::TaskFixture>,
platform_fixture: Mutex<platform_fixture::PlatformFixture>,
@@ -223,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(),
@@ -246,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<u32> {
*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<Vec<u8>> {
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
}
/// Read the last-error value for a guest thread's TEB.
pub fn last_error(&self, teb: u64) -> u32 {
self.last_errors
@@ -630,6 +710,7 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc<Serv
platform_fixture::register(registry, &state);
gdk_queue::register(registry, &state);
modules::register(registry, &state);
process::register(registry, &state);
}
/// Implementations behind the generated adapters. A failure the guest can
+12
View File
@@ -41,6 +41,18 @@ struct ScheduledCallback {
}
impl QueueHandles {
/// Task-queue handles the guest has open.
pub(super) fn open_count(&self) -> 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<Queue>,
+23
View File
@@ -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<ServicesState>) {
// 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);
}
+10
View File
@@ -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);
+52 -11
View File
@@ -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);
+302
View File
@@ -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<PathBuf> = 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<ServicesState>,
}
/// 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<Outcome, String> {
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<u8>,
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);
}
+540
View File
@@ -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 = &registry
.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 <ExitProcess stub>
// 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<u8> = "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<u8> {
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<u8>]) -> Vec<u8> {
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<u8> {
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<u8> {
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<u8>, last: u8) -> Vec<u8> {
code.push(last);
code
}
const RET: u8 = 0xC3;
const HLT: u8 = 0xF4;
struct Started {
result: xenora_loader::startup::StartupResult,
state: Arc<ServicesState>,
}
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<Started, String> {
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)
);
}
+170
View File
@@ -0,0 +1,170 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! The injected guest clock read through every time service at once.
//!
//! Units come from the public Windows documentation: a FILETIME and the
//! unbiased interrupt time count 100-nanosecond intervals, the tick counts are
//! milliseconds, and a performance count divided by the reported frequency is
//! seconds. Expected values are worked out by hand from those units, not taken
//! from the service code.
mod support;
use std::sync::Arc;
use support::*;
use xenora_loader::services::{MockClock, ServicesState};
const KERNEL32: &str = "kernel32.dll";
const IMPORTS: &[(&str, &str)] = &[
(KERNEL32, "QueryPerformanceCounter"),
(KERNEL32, "QueryPerformanceFrequency"),
(KERNEL32, "GetTickCount"),
(KERNEL32, "GetTickCount64"),
(KERNEL32, "QueryUnbiasedInterruptTime"),
(KERNEL32, "GetSystemTimeAsFileTime"),
(KERNEL32, "Sleep"),
];
/// 2026-11-24 12:34:56 UTC as a FILETIME: 1,795,523,696 Unix seconds plus the
/// 11,644,473,600 seconds between 1601 and 1970, times ten million.
const START_FILETIME: u64 = 134_399_972_960_000_000;
/// Clock time that passes before the guest process starts.
const BEFORE_START: u64 = 1_234;
/// One reading of every time service.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Reading {
counter: u64,
frequency: u64,
tick: u64,
tick64: u64,
interrupt: u64,
filetime: u64,
}
fn guest() -> (Guest, Arc<MockClock>) {
let clock = Arc::new(MockClock::new(START_FILETIME));
clock.advance(BEFORE_START);
let guest = Guest::with_state(IMPORTS, &[], ServicesState::new(clock.clone()));
(guest, clock)
}
fn read(guest: &mut Guest) -> Reading {
let output = |guest: &mut Guest, symbol: &str| {
guest.memory.write_u64(SCRATCH, 0).unwrap();
guest.call(symbol, &[SCRATCH]);
guest.u64_at(SCRATCH)
};
Reading {
counter: output(guest, "QueryPerformanceCounter"),
frequency: output(guest, "QueryPerformanceFrequency"),
interrupt: output(guest, "QueryUnbiasedInterruptTime"),
filetime: output(guest, "GetSystemTimeAsFileTime"),
tick: guest.call("GetTickCount", &[]),
tick64: guest.call("GetTickCount64", &[]),
}
}
#[test]
fn every_time_service_reports_the_same_elapsed_time_in_its_own_unit() {
let (mut guest, clock) = guest();
// Uptime starts with the process; the counter and the calendar do not.
assert_eq!(
read(&mut guest),
Reading {
counter: 1_234,
frequency: 10_000_000,
tick: 0,
tick64: 0,
interrupt: 0,
filetime: 134_399_972_960_001_234,
}
);
// 3 s + 7 ms + 3 intervals.
clock.advance(30_070_003);
let after = read(&mut guest);
assert_eq!(
after,
Reading {
counter: 30_071_237,
frequency: 10_000_000,
tick: 3_007,
tick64: 3_007,
interrupt: 30_070_003,
filetime: 134_399_972_990_071_237,
}
);
assert_eq!((after.counter - 1_234) / after.frequency, 3);
// A guest sleep is the same time as a host advance: 250 ms.
assert_eq!(guest.call("Sleep", &[250]), 0);
assert_eq!(
read(&mut guest),
Reading {
counter: 32_571_237,
frequency: 10_000_000,
tick: 3_257,
tick64: 3_257,
interrupt: 32_570_003,
filetime: 134_399_972_992_571_237,
}
);
}
#[test]
fn no_reading_decreases_up_to_and_past_the_end_of_the_clock() {
let (mut guest, clock) = guest();
let mut last = read(&mut guest);
let steps = [
0,
1,
9_998,
1,
10_000_000,
1 << 40,
i64::MAX as u64 / 2,
i64::MAX as u64 / 2,
u64::MAX / 2,
u64::MAX,
1,
];
for step in steps {
clock.advance(step);
let now = read(&mut guest);
assert!(
now.counter >= last.counter,
"{step}: {now:?} after {last:?}"
);
assert!(now.tick64 >= last.tick64, "{step}: {now:?} after {last:?}");
assert!(
now.interrupt >= last.interrupt,
"{step}: {now:?} after {last:?}"
);
assert!(
now.filetime >= last.filetime,
"{step}: {now:?} after {last:?}"
);
// The 32-bit count is the low half of the 64-bit one and may wrap.
assert_eq!(now.tick, now.tick64 & 0xFFFF_FFFF, "{step}");
assert_eq!(now.frequency, 10_000_000, "{step}");
last = now;
}
// Both readings stop at their maximum; neither wraps.
let end = Reading {
counter: 0x7FFF_FFFF_FFFF_FFFF,
frequency: 10_000_000,
// (2^63 - 1 - 1,234) intervals, in whole milliseconds.
tick: 922_337_203_685_477 & 0xFFFF_FFFF,
tick64: 922_337_203_685_477,
interrupt: 0x7FFF_FFFF_FFFF_FFFF - 1_234,
filetime: u64::MAX,
};
assert_eq!(last, end);
// Sleeping at the end of the clock still returns and changes nothing.
assert_eq!(guest.call("Sleep", &[1]), 0);
assert_eq!(read(&mut guest), end);
}
+27
View File
@@ -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);
+171 -3
View File
@@ -2,6 +2,7 @@
//! Verified compilation for Xenora's synthetic compute and graphics ABIs.
use std::collections::HashMap;
use std::fmt::{self, Write};
mod graphics;
@@ -34,8 +35,8 @@ pub struct CompiledShader {
/// 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.
/// evaluation and immediates remain, pure vector expressions between
/// constants are not rewritten, and duplicate pure expressions are not reused.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct CompileOptions {
/// Replace pure vector unary/binary ops whose operands are already
@@ -43,6 +44,12 @@ pub struct CompileOptions {
/// the existing exact positive-normal rules accept the result. Loads,
/// stores, lane masks, merges and branches are never folded.
pub fold_constants: bool,
/// Reuse the first result of an equivalent pure vector unary or binary
/// expression. Equivalence is the same operation and the same operand
/// values in the same order; constant operands compare by bit pattern.
/// Loads, stores, constants, lane masks, merges, branches and other
/// mask-dependent or side-effecting ops are never reused.
pub eliminate_common_subexpressions: bool,
}
#[derive(Debug)]
@@ -155,6 +162,9 @@ enum Op {
fallthrough: Value,
taken: Value,
},
/// The value is the earlier pure result `source`. The definition index stays
/// so later operands do not need renumbering.
Reuse(Value),
}
impl Op {
@@ -186,6 +196,7 @@ impl Op {
fallthrough,
taken,
} => vec![mask, fallthrough, taken],
Self::Reuse(source) => vec![source],
}
}
@@ -262,6 +273,7 @@ impl Op {
_ => unreachable!("not a VCC arithmetic operation"),
}
}
Self::Reuse(source) => name(source),
Self::Store(_)
| Self::ScalarBranch { .. }
| Self::CarryMask { .. }
@@ -303,7 +315,7 @@ fn compare_expression(op: VectorCompareOp, left: &str, right: &str) -> String {
}
}
#[derive(Clone, Copy)]
#[derive(Clone, Copy, PartialEq, Eq)]
enum Binary {
FloatAdd,
FloatMul,
@@ -506,6 +518,11 @@ pub fn compile_with(
if options.fold_constants {
fold_constant_ops(&mut operations);
}
// Fold first so a constant expression is `const.u32` before reuse. CSE does
// not fold, and it does not turn those constants back into arithmetic.
if options.eliminate_common_subexpressions {
eliminate_common_subexpressions(&mut operations);
}
let disassembly = decoded.iter().map(|line| format!("{line}\n")).collect();
let mut ir = String::new();
@@ -685,6 +702,10 @@ pub fn compile_with(
format!("store.u32 output[index], {value}"),
format!("output[index] = {value};"),
),
Op::Reuse(source) => (
format!("{dest} = reuse.u32 {source}"),
format!("uint {dest} = {source};"),
),
};
// Writing to a String is infallible.
let _ = writeln!(ir, "{offset:04x}: {step}");
@@ -1489,6 +1510,153 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
})
}
/// Reuse the first equivalent pure vector unary or binary.
///
/// Equivalence is the operation plus its operand values in order. Constant
/// operands match by bit pattern, so two temps folded to the same `const.u32`
/// compare equal. That match only selects reuse: an op that is kept keeps
/// its own constant operands, so a shader with no repeat compiles unchanged.
/// Loads, stores, the constant definitions themselves, lane masks, merges,
/// branches and other mask-dependent or side-effecting ops are never
/// candidates. A reused definition stays at its index as `reuse.u32`.
fn eliminate_common_subexpressions(operations: &mut [(usize, Op)]) {
let mut expr_alias = vec![None; operations.len()];
let mut const_bits: HashMap<u32, usize> = HashMap::new();
let mut seen: Vec<(PureExpr, usize)> = Vec::new();
for index in 0..operations.len() {
let current = operations[index].1;
if let Op::Constant(bits) = current {
const_bits.entry(bits).or_insert(index);
continue;
}
let canonical = match current {
Op::Unary(operator, source) => Op::Unary(
operator,
equivalent_value(&expr_alias, &const_bits, operations, source),
),
Op::Binary(operator, left, right) => Op::Binary(
operator,
equivalent_value(&expr_alias, &const_bits, operations, left),
equivalent_value(&expr_alias, &const_bits, operations, right),
),
other => other,
};
let rewritten = map_uses(current, |value| reused_value(&expr_alias, value));
if let Some(key) = pure_expr(canonical) {
if let Some(&(_, first)) = seen.iter().find(|(seen_key, _)| *seen_key == key) {
expr_alias[index] = Some(first);
operations[index].1 = Op::Reuse(Value(first));
continue;
}
seen.push((key, index));
}
operations[index].1 = rewritten;
}
}
fn reused_value(expr_alias: &[Option<usize>], value: Value) -> Value {
match expr_alias.get(value.0).and_then(|slot| *slot) {
Some(index) => Value(index),
None => value,
}
}
/// SSA value to use when matching a pure expression. Follows a reuse edge, then
/// the earliest constant with the same bits.
fn equivalent_value(
expr_alias: &[Option<usize>],
const_bits: &HashMap<u32, usize>,
operations: &[(usize, Op)],
value: Value,
) -> Value {
let root = reused_value(expr_alias, value);
match operations.get(root.0).map(|(_, operation)| *operation) {
Some(Op::Constant(bits)) => const_bits.get(&bits).copied().map(Value).unwrap_or(root),
_ => root,
}
}
fn map_uses(operation: Op, map: impl Fn(Value) -> Value) -> Op {
match operation {
Op::Load | Op::Constant(_) | Op::ScalarBranch { .. } => operation,
Op::Binary(operator, left, right) => Op::Binary(operator, map(left), map(right)),
Op::Unary(operator, source) => Op::Unary(operator, map(source)),
Op::MergeLanes {
mask,
active,
inactive,
} => Op::MergeLanes {
mask,
active: map(active),
inactive: map(inactive),
},
Op::Store(value) => Op::Store(map(value)),
Op::VccArithmetic {
primitive,
left,
right,
mask,
flag,
} => Op::VccArithmetic {
primitive,
left: map(left),
right: map(right),
mask: map(mask),
flag,
},
Op::CarryMask { flag, exec } => Op::CarryMask {
flag: map(flag),
exec,
},
Op::LaneMask {
op,
name,
sdst,
src0,
src1,
high,
exec,
} => Op::LaneMask {
op,
name,
sdst,
src0: map(src0),
src1: map(src1),
high: high.map(|(left, right)| (map(left), map(right))),
exec,
},
Op::RuntimeBranch { mask, target } => Op::RuntimeBranch {
mask: map(mask),
target,
},
Op::JoinVccz {
mask,
fallthrough,
taken,
} => Op::JoinVccz {
mask: map(mask),
fallthrough: map(fallthrough),
taken: map(taken),
},
Op::Reuse(source) => Op::Reuse(map(source)),
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum PureExpr {
Unary(VectorUnary, usize),
Binary(Binary, usize, usize),
}
fn pure_expr(operation: Op) -> Option<PureExpr> {
match operation {
Op::Unary(operator, source) => Some(PureExpr::Unary(operator, source.0)),
Op::Binary(operator, left, right) => Some(PureExpr::Binary(operator, left.0, right.0)),
_ => None,
}
}
/// Replace pure constant expressions with `Op::Constant` in place.
///
/// Operands stay addressable by their original `Value` indices so later uses
+661
View File
@@ -649,6 +649,7 @@ fn compile_fold_off(code: &[u8]) -> xenora_shader::CompiledShader {
code,
CompileOptions {
fold_constants: false,
..CompileOptions::default()
},
)
.unwrap()
@@ -660,6 +661,7 @@ fn compile_fold_on(code: &[u8]) -> xenora_shader::CompiledShader {
code,
CompileOptions {
fold_constants: true,
..CompileOptions::default()
},
)
.unwrap()
@@ -843,6 +845,7 @@ fn rejects_inexact_float_add_of_constants_at_verify() {
&code,
CompileOptions {
fold_constants: false,
..CompileOptions::default()
},
);
let on = compile_with(
@@ -850,6 +853,7 @@ fn rejects_inexact_float_add_of_constants_at_verify() {
&code,
CompileOptions {
fold_constants: true,
..CompileOptions::default()
},
);
assert!(
@@ -862,3 +866,660 @@ fn rejects_inexact_float_add_of_constants_at_verify() {
);
// Folder unchanged: no stay-unfolded path exists for this pair.
}
// --- Opt-in common-subexpression elimination (#142) ---------------------------
// Expected IR is derived from the lifter's value order and the reuse rule
// (same unary/binary op, same operand values in order), not from the pass
// output. Constant bits cited below are computed by hand.
fn compile_options(code: &[u8], fold: bool, cse: bool) -> xenora_shader::CompiledShader {
compile_with(
Architecture::Gfx1030,
code,
CompileOptions {
fold_constants: fold,
eliminate_common_subexpressions: cse,
},
)
.unwrap()
}
fn vopc(op: u32, src0_vgpr: u32, src1_vgpr: u32) -> u32 {
// VOPC: encoding bits 0x7c00_0000, OP in bits 17-24, VSRC1 in bits 9-16,
// SRC0 in bits 0-8 (VGPR selector 256 + register).
0x7c00_0000 | (op << 17) | (src1_vgpr << 9) | (0x100 + src0_vgpr)
}
/// load; mov v2, 0xff00ff00; and v3 and v4 with v1, v2; xor each and with v2.
/// The two ands are the same pure op. The two xors become the same pure op
/// only after the second and is reused, so the second xor must reuse the first.
fn duplicate_and_xor_fixture() -> Vec<u8> {
words(&[
0xe030_2000,
0x8000_0100,
0xbf8c_3f70,
mov_lit(2),
0xff00_ff00,
vop2(27, 3, 1, 2), // v_and_b32 v3, v1, v2
vop2(27, 4, 1, 2), // v_and_b32 v4, v1, v2
vop2(29, 5, 3, 2), // v_xor_b32 v5, v3, v2
vop2(29, 6, 4, 2), // v_xor_b32 v6, v4, v2
0xe070_2000,
0x8001_0600, // buffer_store_dword v6
0xbbfd_0000,
0xbf81_0000,
])
}
const DUPLICATE_AND_OFF: &str = "\
0000: t0 = load.u32 input[index]
000c: t1 = const.u32 0xff00ff00
0014: t2 = and.b32 t0, t1
0018: t3 = and.b32 t0, t1
001c: t4 = xor.b32 t2, t1
0020: t5 = xor.b32 t3, t1
0024: store.u32 output[index], t5
";
const DUPLICATE_AND_ON: &str = "\
0000: t0 = load.u32 input[index]
000c: t1 = const.u32 0xff00ff00
0014: t2 = and.b32 t0, t1
0018: t3 = reuse.u32 t2
001c: t4 = xor.b32 t2, t1
0020: t5 = reuse.u32 t4
0024: store.u32 output[index], t4
";
const DUPLICATE_AND_MSL_OFF: &str = "\
#include <metal_stdlib>
using namespace metal;
kernel void xenora_compute(
device const uint* input [[buffer(0)]],
device uint* output [[buffer(1)]],
uint index [[thread_position_in_grid]]) {
uint t0 = input[index];
uint t1 = 0xff00ff00u;
uint t2 = t0 & t1;
uint t3 = t0 & t1;
uint t4 = t2 ^ t1;
uint t5 = t3 ^ t1;
output[index] = t5;
}
";
const DUPLICATE_AND_MSL_ON: &str = "\
#include <metal_stdlib>
using namespace metal;
kernel void xenora_compute(
device const uint* input [[buffer(0)]],
device uint* output [[buffer(1)]],
uint index [[thread_position_in_grid]]) {
uint t0 = input[index];
uint t1 = 0xff00ff00u;
uint t2 = t0 & t1;
uint t3 = t2;
uint t4 = t2 ^ t1;
uint t5 = t4;
output[index] = t4;
}
";
#[test]
fn default_compile_matches_cse_off() {
assert_eq!(
CompileOptions::default(),
CompileOptions {
fold_constants: false,
eliminate_common_subexpressions: false,
}
);
let code = duplicate_and_xor_fixture();
let baseline = compile(Architecture::Gfx1030, &code).unwrap();
let explicit = compile_options(&code, false, false);
assert_eq!(baseline.ir, explicit.ir);
assert_eq!(baseline.msl, explicit.msl);
assert_eq!(baseline.ir, DUPLICATE_AND_OFF);
assert_eq!(baseline.msl, DUPLICATE_AND_MSL_OFF);
// add.bin has no duplicate pure expression. CSE on must not touch it.
let add = compile(Architecture::Gfx1030, FIXTURE).unwrap();
let add_cse = compile_options(FIXTURE, false, true);
assert_eq!(add.ir, include_str!("../../../fixtures/golden/add.ir"));
assert_eq!(add_cse.ir, add.ir);
assert_eq!(add_cse.msl, add.msl);
}
#[test]
fn reuses_duplicate_and_and_the_xor_of_that_and() {
// Off: two and.b32 and two xor.b32. On: one of each, plus reuse.u32.
// The xor is not evaluated: xor of a value with a different operand stays
// xor.b32. (xor with itself is not what this fixture computes.)
let code = duplicate_and_xor_fixture();
let off = compile_options(&code, false, false);
let on = compile_options(&code, false, true);
assert_eq!(off.ir, DUPLICATE_AND_OFF);
assert_eq!(off.msl, DUPLICATE_AND_MSL_OFF);
assert_eq!(on.ir, DUPLICATE_AND_ON);
assert_eq!(on.msl, DUPLICATE_AND_MSL_ON);
assert_eq!(off.ir.matches("and.b32").count(), 2);
assert_eq!(on.ir.matches("and.b32").count(), 1);
assert_eq!(off.ir.matches("xor.b32").count(), 2);
assert_eq!(on.ir.matches("xor.b32").count(), 1);
assert_eq!(on.ir.matches("store.u32").count(), 1);
}
#[test]
fn reuses_duplicate_not() {
// v_not_b32 twice on the loaded word. ~x computed once.
let code = words(&[
0xe030_2000,
0x8000_0100,
0xbf8c_3f70,
vop1(55, 2, 1), // v_not_b32 v2, v1 (VOP1 opcode 55)
vop1(55, 3, 1), // v_not_b32 v3, v1
0xe070_2000,
0x8001_0300,
0xbbfd_0000,
0xbf81_0000,
]);
let off = "\
0000: t0 = load.u32 input[index]
000c: t1 = not.b32 t0
0010: t2 = not.b32 t0
0014: store.u32 output[index], t2
";
let on = "\
0000: t0 = load.u32 input[index]
000c: t1 = not.b32 t0
0010: t2 = reuse.u32 t1
0014: store.u32 output[index], t1
";
assert_eq!(compile_options(&code, false, false).ir, off);
assert_eq!(compile_options(&code, false, true).ir, on);
let msl = compile_options(&code, false, true).msl;
assert!(msl.contains("uint t1 = ~t0;"));
assert!(msl.contains("uint t2 = t1;"));
assert_eq!(msl.matches("~t0").count(), 1);
}
#[test]
fn does_not_reuse_swapped_subtract() {
// sub is not commutative: if the load is 0, v1 - 1 = 0xffffffff and
// 1 - v1 = 1. The third sub repeats the first and is reused.
let code = words(&[
0xe030_2000,
0x8000_0100,
0xbf8c_3f70,
mov_lit(2),
1,
vop2(38, 3, 1, 2), // v_sub_nc_u32 v3, v1, v2
vop2(38, 4, 2, 1), // v_sub_nc_u32 v4, v2, v1
vop2(38, 5, 1, 2), // v_sub_nc_u32 v5, v1, v2
0xe070_2000,
0x8001_0500,
0xbbfd_0000,
0xbf81_0000,
]);
let off = "\
0000: t0 = load.u32 input[index]
000c: t1 = const.u32 0x00000001
0014: t2 = sub.u32 t0, t1
0018: t3 = sub.u32 t1, t0
001c: t4 = sub.u32 t0, t1
0020: store.u32 output[index], t4
";
let on = "\
0000: t0 = load.u32 input[index]
000c: t1 = const.u32 0x00000001
0014: t2 = sub.u32 t0, t1
0018: t3 = sub.u32 t1, t0
001c: t4 = reuse.u32 t2
0020: store.u32 output[index], t2
";
assert_eq!(compile_options(&code, false, false).ir, off);
assert_eq!(compile_options(&code, false, true).ir, on);
assert_eq!(
compile_options(&code, false, true)
.ir
.matches("sub.u32")
.count(),
2
);
}
#[test]
fn does_not_reuse_a_different_opcode() {
// and vs or of the same bits differ. 0xff00ff00 & 0x0f0f0f0f = 0x0f000f00;
// 0xff00ff00 | 0x0f0f0f0f = 0xff0fff0f.
let code = words(&[
0xe030_2000,
0x8000_0100,
0xbf8c_3f70,
mov_lit(2),
0xff00_ff00,
vop2(27, 3, 1, 2), // v_and_b32
vop2(28, 4, 1, 2), // v_or_b32
0xe070_2000,
0x8001_0300,
0xbbfd_0000,
0xbf81_0000,
]);
let ir = "\
0000: t0 = load.u32 input[index]
000c: t1 = const.u32 0xff00ff00
0014: t2 = and.b32 t0, t1
0018: t3 = or.b32 t0, t1
001c: store.u32 output[index], t2
";
let off = compile_options(&code, false, false);
let on = compile_options(&code, false, true);
assert_eq!(off.ir, ir);
assert_eq!(on.ir, ir);
assert!(!on.ir.contains("reuse.u32"));
}
#[test]
fn does_not_merge_loads_or_duplicate_constant_definitions() {
// Two loads of input[index] stay two loads. Two movs of the same immediate
// stay two const.u32 definitions. The ands use different constant temps
// with equal bits, so the pure and is reused and the consts remain.
let code = words(&[
0xe030_2000,
0x8000_0100, // buffer_load_dword v1
0xbf8c_3f70,
0xe030_2000,
0x8000_0200, // buffer_load_dword v2
0xbf8c_3f70,
mov_lit(3),
0x1234_5678,
mov_lit(4),
0x1234_5678,
vop2(27, 5, 1, 3), // v_and_b32 v5, v1, v3
vop2(27, 6, 1, 4), // v_and_b32 v6, v1, v4
0xe070_2000,
0x8001_0600,
0xbbfd_0000,
0xbf81_0000,
]);
let off = "\
0000: t0 = load.u32 input[index]
000c: t1 = load.u32 input[index]
0018: t2 = const.u32 0x12345678
0020: t3 = const.u32 0x12345678
0028: t4 = and.b32 t0, t2
002c: t5 = and.b32 t0, t3
0030: store.u32 output[index], t5
";
// Constant temps compare by bits, so the second and reuses the first.
// The load temps differ, and neither load is removed.
let on = "\
0000: t0 = load.u32 input[index]
000c: t1 = load.u32 input[index]
0018: t2 = const.u32 0x12345678
0020: t3 = const.u32 0x12345678
0028: t4 = and.b32 t0, t2
002c: t5 = reuse.u32 t4
0030: store.u32 output[index], t4
";
assert_eq!(compile_options(&code, false, false).ir, off);
assert_eq!(compile_options(&code, false, true).ir, on);
assert_eq!(
compile_options(&code, false, true)
.ir
.matches("load.u32")
.count(),
2
);
assert_eq!(
compile_options(&code, false, true)
.ir
.matches("const.u32 0x12345678")
.count(),
2
);
}
#[test]
fn does_not_merge_lane_masks() {
// Two identical v_cmp_eq_u32_e32 (VOPC opcode 194) write the wave mask.
// The results are lane-mask values and are not reused.
let code = words(&[
mov_lit(1),
1,
mov_lit(2),
2,
vopc(194, 1, 2),
vopc(194, 1, 2),
mov_lit(3),
0,
0xe070_2000,
0x8001_0300,
0xbbfd_0000,
0xbf81_0000,
]);
let ir = "\
0000: t0 = const.u32 0x00000001
0008: t1 = const.u32 0x00000002
0010: t2 = wave.mask v_cmp_eq_u32_e32 t0, t1 exec=0xffffffff
0014: t3 = wave.mask v_cmp_eq_u32_e32 t0, t1 exec=0xffffffff
0018: t4 = const.u32 0x00000000
0020: store.u32 output[index], t4
";
let off = compile_options(&code, false, false);
let on = compile_options(&code, false, true);
assert_eq!(off.ir, ir);
assert_eq!(on.ir, ir);
assert_eq!(on.ir.matches("wave.mask").count(), 2);
assert!(!on.ir.contains("reuse.u32"));
}
#[test]
fn does_not_merge_lane_merges_under_partial_exec() {
// EXEC = 1 merges each and with that destination's previous value.
// The and itself is pure and is reused. The two merges see different
// inactive values (the two zero temps) and both remain.
let code = words(&[
0xe030_2000,
0x8000_0100,
0xbf8c_3f70,
mov_lit(2),
0xff00_ff00,
mov_lit(3),
0, // v3 initialized before the partial write
mov_lit(4),
0, // v4 initialized before the partial write
0xbefe_0381, // s_mov_b32 exec_lo, 1
vop2(27, 3, 1, 2), // v_and_b32 v3, v1, v2
vop2(27, 4, 1, 2), // v_and_b32 v4, v1, v2
0xbefe_03c1, // s_mov_b32 exec_lo, -1
0xe070_2000,
0x8001_0300, // buffer_store_dword v3
0xbbfd_0000,
0xbf81_0000,
]);
let off = "\
0000: t0 = load.u32 input[index]
000c: t1 = const.u32 0xff00ff00
0014: t2 = const.u32 0x00000000
001c: t3 = const.u32 0x00000000
0028: t4 = and.b32 t0, t1
0028: t5 = merge.lanes mask=0x00000001, t4, t2
002c: t6 = and.b32 t0, t1
002c: t7 = merge.lanes mask=0x00000001, t6, t3
0034: store.u32 output[index], t5
";
let on = "\
0000: t0 = load.u32 input[index]
000c: t1 = const.u32 0xff00ff00
0014: t2 = const.u32 0x00000000
001c: t3 = const.u32 0x00000000
0028: t4 = and.b32 t0, t1
0028: t5 = merge.lanes mask=0x00000001, t4, t2
002c: t6 = reuse.u32 t4
002c: t7 = merge.lanes mask=0x00000001, t4, t3
0034: store.u32 output[index], t5
";
assert_eq!(compile_options(&code, false, false).ir, off);
assert_eq!(compile_options(&code, false, true).ir, on);
assert_eq!(
compile_options(&code, false, true)
.ir
.matches("merge.lanes")
.count(),
2
);
}
#[test]
fn does_not_merge_vcc_select() {
// v_cndmask_b32 reads VCC. Two identical selects stay two vcc.Select ops.
let code = words(&[
0xe030_2000,
0x8000_0100,
0xbf8c_3f70,
mov_lit(2),
0x1111_1111,
0xbeea_0381, // s_mov_b32 vcc_lo, 1
vop2(1, 3, 1, 2), // v_cndmask_b32 v3, v1, v2
vop2(1, 4, 1, 2), // v_cndmask_b32 v4, v1, v2
0xe070_2000,
0x8001_0300,
0xbbfd_0000,
0xbf81_0000,
]);
let ir = "\
0000: t0 = load.u32 input[index]
000c: t1 = const.u32 0x11111111
0018: t2 = const.u32 0x00000001
0018: t3 = vcc.Select t0, t1, t2
001c: t4 = const.u32 0x00000001
001c: t5 = vcc.Select t0, t1, t4
0020: store.u32 output[index], t3
";
let off = compile_options(&code, false, false);
let on = compile_options(&code, false, true);
assert_eq!(off.ir, ir);
assert_eq!(on.ir, ir);
assert_eq!(on.ir.matches("vcc.Select").count(), 2);
assert!(!on.ir.contains("reuse.u32"));
}
#[test]
fn cse_leaves_branch_and_float_fixtures_unchanged() {
// No duplicate pure expression, so the pass is a no-op, including on the
// uniform branches and the load-derived float ops.
for (code, ir) in [
(
BRANCH,
include_str!("../../../fixtures/golden/bitwise-branch.ir"),
),
(
FLOAT,
include_str!("../../../fixtures/golden/float-exact.ir"),
),
] {
let plain = compile(Architecture::Gfx1030, code).unwrap();
let on = compile_options(code, false, true);
assert_eq!(plain.ir, ir);
assert_eq!(on.ir, plain.ir);
assert_eq!(on.msl, plain.msl);
}
}
#[test]
fn cse_leaves_every_golden_fixture_unchanged() {
// None of these fixtures repeats a pure op. Several use equal-bit
// constants in different ops whose operands must not be renamed.
macro_rules! golden {
($name:literal) => {{
let code = include_bytes!(concat!("../../../fixtures/rdna2/", $name, ".bin"));
let shader = compile_options(code, false, true);
assert_eq!(
shader.ir,
include_str!(concat!("../../../fixtures/golden/", $name, ".ir")),
"ir changed for {}",
$name
);
assert_eq!(
shader.msl,
include_str!(concat!("../../../fixtures/golden/", $name, ".metal")),
"msl changed for {}",
$name
);
}};
}
golden!("add");
golden!("bitwise-branch");
golden!("float-exact");
golden!("scalar-alu");
golden!("scalar-arith");
golden!("scalar-compare");
golden!("scalar-immediate");
golden!("scalar-logic");
golden!("scalar-unary");
golden!("vector-compare");
golden!("vector-compare-ft");
golden!("vector-integer");
golden!("vector-unary");
}
/// 1 + 2 = 3, and the same add twice, then and the load with each sum.
fn fold_and_cse_fixture() -> Vec<u8> {
words(&[
0xe030_2000,
0x8000_0100,
0xbf8c_3f70,
mov_lit(2),
1,
mov_lit(3),
2,
vop2(37, 4, 2, 3), // v_add_nc_u32 v4, v2, v3
vop2(37, 5, 2, 3), // v_add_nc_u32 v5, v2, v3
vop2(27, 6, 1, 4), // v_and_b32 v6, v1, v4
vop2(27, 7, 1, 5), // v_and_b32 v7, v1, v5
0xe070_2000,
0x8001_0700,
0xbbfd_0000,
0xbf81_0000,
])
}
#[test]
fn cse_interacts_with_constant_folding() {
// Hand-computed: 1 + 2 = 3 (0x00000003). Folding rewrites the adds and
// does not reuse the ands. CSE reuses both the add and the and, and does
// not invent the constant 3. Both passes: the adds are constants first,
// the two const 3 temps stay, and the ands reuse because those temps have
// the same bits.
let code = fold_and_cse_fixture();
let off = "\
0000: t0 = load.u32 input[index]
000c: t1 = const.u32 0x00000001
0014: t2 = const.u32 0x00000002
001c: t3 = add.u32 t1, t2
0020: t4 = add.u32 t1, t2
0024: t5 = and.b32 t0, t3
0028: t6 = and.b32 t0, t4
002c: store.u32 output[index], t6
";
let cse_only = "\
0000: t0 = load.u32 input[index]
000c: t1 = const.u32 0x00000001
0014: t2 = const.u32 0x00000002
001c: t3 = add.u32 t1, t2
0020: t4 = reuse.u32 t3
0024: t5 = and.b32 t0, t3
0028: t6 = reuse.u32 t5
002c: store.u32 output[index], t5
";
let fold_only = "\
0000: t0 = load.u32 input[index]
000c: t1 = const.u32 0x00000001
0014: t2 = const.u32 0x00000002
001c: t3 = const.u32 0x00000003
0020: t4 = const.u32 0x00000003
0024: t5 = and.b32 t0, t3
0028: t6 = and.b32 t0, t4
002c: store.u32 output[index], t6
";
let both = "\
0000: t0 = load.u32 input[index]
000c: t1 = const.u32 0x00000001
0014: t2 = const.u32 0x00000002
001c: t3 = const.u32 0x00000003
0020: t4 = const.u32 0x00000003
0024: t5 = and.b32 t0, t3
0028: t6 = reuse.u32 t5
002c: store.u32 output[index], t5
";
assert_eq!(compile_options(&code, false, false).ir, off);
assert_eq!(compile_options(&code, false, true).ir, cse_only);
assert_eq!(compile_options(&code, true, false).ir, fold_only);
assert_eq!(compile_options(&code, true, true).ir, both);
assert!(!cse_only.contains("0x00000003"));
assert_eq!(fold_only.matches("const.u32 0x00000003").count(), 2);
assert_eq!(both.matches("and.b32").count(), 1);
assert!(!both.contains("add.u32"));
}
#[test]
fn cse_does_not_fold_exact_float_add() {
// 1.0 + 2.0 = 3.0 exactly. Bits 0x3f800000 + 0x40000000 = 0x40400000.
// CSE reuses the add and leaves the operation. Folding replaces both
// adds with that constant. Enabling both matches folding alone: the adds
// are gone before reuse, and the two result constants are not merged.
let code = words(&[
mov_lit(2),
0x3f80_0000,
mov_lit(3),
0x4000_0000,
vop2(3, 4, 2, 3), // v_add_f32 v4, v2, v3
vop2(3, 5, 2, 3), // v_add_f32 v5, v2, v3
0xe070_2000,
0x8001_0500,
0xbbfd_0000,
0xbf81_0000,
]);
let cse_ir = "\
0000: t0 = const.u32 0x3f800000
0008: t1 = const.u32 0x40000000
0010: t2 = add.f32 t0, t1
0014: t3 = reuse.u32 t2
0018: store.u32 output[index], t2
";
let fold_ir = "\
0000: t0 = const.u32 0x3f800000
0008: t1 = const.u32 0x40000000
0010: t2 = const.u32 0x40400000
0014: t3 = const.u32 0x40400000
0018: store.u32 output[index], t3
";
let cse_msl = "\
#include <metal_stdlib>
using namespace metal;
kernel void xenora_compute(
device const uint* input [[buffer(0)]],
device uint* output [[buffer(1)]],
uint index [[thread_position_in_grid]]) {
#pragma clang fp contract(off)
#pragma clang fp reassociate(off)
uint t0 = 0x3f800000u;
uint t1 = 0x40000000u;
uint t2 = as_type<uint>(as_type<float>(t0) + as_type<float>(t1));
uint t3 = t2;
output[index] = t2;
}
";
let folded = compile_options(&code, true, false);
let both = compile_options(&code, true, true);
assert_eq!(compile_options(&code, false, true).ir, cse_ir);
assert_eq!(compile_options(&code, false, true).msl, cse_msl);
assert_eq!(folded.ir, fold_ir);
assert_eq!(both.ir, folded.ir);
assert_eq!(both.msl, folded.msl);
assert!(!cse_ir.contains("0x40400000"));
assert_eq!(fold_ir.matches("const.u32 0x40400000").count(), 2);
}
#[test]
fn cse_does_not_bypass_inexact_float_verification() {
// Same pair the folder refuses: 1.0 + 2^-24 is not an f32 value. Verify
// rejects it before either optional pass.
let code = binary_const_fixture(3, 0x3f80_0000, 0x3380_0000, false);
for fold in [false, true] {
for cse in [false, true] {
let result = compile_with(
Architecture::Gfx1030,
&code,
CompileOptions {
fold_constants: fold,
eliminate_common_subexpressions: cse,
},
);
assert!(
matches!(result, Err(CompileError::Verify { .. })),
"fold={fold} cse={cse} must reject at verify: {result:?}"
);
}
}
}
+1
View File
@@ -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
+28 -2
View File
@@ -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
+53
View File
@@ -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.
+44
View File
@@ -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<level> -ffreestanding -fno-stack-protector -Wall -Wextra -Werror` |
| Import libraries | `lld-link /lib /machine:x64 /def:<kernel32 or ucrtbase>.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.
+140
View File
@@ -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
+314
View File
@@ -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