Compare commits

...
Author SHA1 Message Date
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
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
18 changed files with 1683 additions and 13 deletions

No files matched your search

+2
View File
@@ -99,6 +99,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.
+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
+75
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;
@@ -198,6 +199,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 +226,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 +250,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 +704,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)
);
}
+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);
+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