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>
This commit is contained in:
zachdoxsee committed 2026-11-24 17:42:09 +01:00
1 parent 1d363c3c34
commit 47cb26ebdd
15 files changed
+1161 -3

No files matched your search

+1
View File
@@ -17,6 +17,7 @@ remains unsupported.
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
### Added
- 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, and the engine that ran the guest executes nothing further. `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 four Wave32 gfx1030 VOP2 select and carry forms through the semantic registry. Conditional select, add with carry and both subtract orders with borrow use a per-lane VCC bit and have a guide-derived oracle that passes on both CPU interpreters and on native Metal (local Apple M5, API and shader validation); independent acceptance is pending. Part of #215.
- Added decoding and Metal shader translation for twelve Wave32 VOPC 16-bit integer compares (#215). The signed and unsigned forms compare the low 16 bits of each source and write the Wave32 VCC mask. CPU verification covers 1,572 compiler acceptance cases and 408 rejections from the guide-derived oracle, which also passes on native Metal (1,572 cases in 1,420 programs on a local Apple M5 under API and shader validation); acceptance is pending.
- Added MOVS and STOS for 8- to 64-bit elements, with and without REP, and the direction flag with CLD and STD (#129). A REP form runs one element per step and stays on the instruction until RCX is zero, so every element counts against the step budget, a repeat can stop part-way and resume, a zero count touches nothing, and a fault keeps the elements already done with RSI, RDI and RCX at the one that faulted. An FS or GS override applies to the MOVS source only. Both engines run these on the shared semantics with no bulk-copy path, so large copies are slow. LODS, CMPS, SCAS, REPE, REPNE and the address-size override stay rejected. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and `tests/cpu_rep.rs` adds a byte-array model over every form, direction and count; not compared with x86 hardware and awaiting independent review.
+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),
}
impl fmt::Display for ExitReason {
@@ -188,6 +191,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")
}
+26
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,11 +82,34 @@ 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,
memory: &mut GuestMemory,
max_instructions: usize,
) -> 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);
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,
) -> ExecutionResult {
let mut instructions_count = 0;
+20
View File
@@ -196,6 +196,9 @@ 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;
const MAX_CALLBACK_DEPTH: usize = 32;
pub(crate) struct GuestCallback {
@@ -635,6 +638,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()
}
@@ -646,6 +650,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
+51
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;
@@ -195,6 +196,8 @@ pub struct ServicesState {
synch: Mutex<synch::Synch>,
/// 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>,
@@ -218,6 +221,7 @@ impl ServicesState {
last_errors: Mutex::default(),
synch: Mutex::default(),
atexit: Mutex::default(),
exit_status: Mutex::default(),
winsock: Mutex::default(),
task_fixture: Mutex::default(),
platform_fixture: Mutex::default(),
@@ -241,6 +245,52 @@ 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.
pub fn open_handle_count(&self) -> usize {
self.objects
.lock()
.expect("guest object state")
.handles
.len()
}
/// 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. 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);
self.objects
.lock()
.expect("guest object state")
.handles
.clear();
status
}
/// Read the last-error value for a guest thread's TEB.
pub fn last_error(&self, teb: u64) -> u32 {
self.last_errors
@@ -602,6 +652,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
+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);
}
+3 -1
View File
@@ -153,7 +153,9 @@ pub fn run_synthetic_startup_with_observer(
});
// 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);
+298
View File
@@ -0,0 +1,298 @@
// 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 = 89;
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(|| {
let out = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("gate-a1");
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);
}
+219
View File
@@ -0,0 +1,219 @@
// 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::{ImportRegistry, Win64Args};
use xenora_loader::memory::GuestMemory;
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"),
];
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));
}
#[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);
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));
}
+1
View File
@@ -44,6 +44,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
+15 -2
View File
@@ -66,8 +66,21 @@ 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.
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.
`xenora probe --mode static` inventories ordinary and delay-loaded PE imports
without guest execution. `missing_imports.csv` lists unresolved ordinary keys
+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.
+38
View File
@@ -66,3 +66,41 @@ 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 to be ARM64. The script
writes the versions it used to `toolchain.txt`, and the test prints 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.
+105
View File
@@ -0,0 +1,105 @@
#!/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
if [ "$(uname -s)" = Darwin ]; then
for tool in "$clang" "$linker"; do
case "$(lipo -archs "$tool")" in
*arm64*) ;;
*) echo "ARM64 tool required: $tool" >&2; exit 1 ;;
esac
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
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
+304
View File
@@ -0,0 +1,304 @@
// 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] == '.');
// 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);
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