diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0e35ed7..f7f1b65 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -35,6 +35,19 @@ jobs: run: | rustup toolchain install "$RUSTUP_TOOLCHAIN" --profile minimal --component rustfmt --component clippy rustc -vV + - name: Install the Gate A2 C toolchain + # crates/loader/tests/gate_a2.rs builds a hosted C program from source + # with mingw-w64 and fails, never skips, when the compiler is missing. + env: + HOMEBREW_NO_AUTO_UPDATE: 1 + HOMEBREW_NO_INSTALL_CLEANUP: 1 + run: | + brew install mingw-w64 + compiler="$(brew --prefix mingw-w64)/bin/x86_64-w64-mingw32-gcc" + file -bL "$compiler" | grep arm64 + lipo -archs "$compiler" | grep arm64 + otool -L "$compiler" + "$compiler" --version | head -1 - name: Check generated status and PE fixtures run: | python3 crates/isa/generate_rdna2_meta.py --check diff --git a/CHANGELOG.md b/CHANGELOG.md index e93c679..e407bd8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,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. ### Fixed +- Gate A2 checks the cross-compiler driver before invoking it, then checks its helpers before fixture compilation. CI also verifies the driver architecture before requesting its version. - Non-canonical 64-bit guest data addresses now raise `#GP` instead of a memory fault in both the interpreter and native DBT, including accesses that cross the canonical-address boundary. The synthetic architectural test is enabled again. - An instruction longer than 15 bytes now stops both engines with a general-protection fault instead of an illegal-instruction exit (#384; Intel SDM Vol. 3A, 7.15). The decoder still stops before fetching a 16th byte, and the DBT translates the faulting instruction on its own so the instructions before it in a block complete first. The `defect_overlong_instruction` known answer from #155 is now verified, with three more cases. - Made the native semantic-review timeout in `scripts/test-gpu.sh` configurable with `XENORA_SEMANTIC_TIMEOUT` and raised its default from 120 to 300 seconds, so cold Apple Silicon runs do not fail while the expanded Metal known-answer suite is still progressing. @@ -129,6 +130,8 @@ remains unsupported. - Added nested guest directories and checked file deletion on the synthetic drive. +- Added the second Gate A milestone, A2 (#419): an original hosted C program, `tests/compat_fixtures/gate_a2.c`, built from source by the new test `crates/loader/tests/gate_a2.rs` with the mingw-w64 C runtime (UCRT) and run through the loader, the standard services and the ARM64 DBT. The runtime's own startup code runs before `main`. The program takes `argc` and `argv`, sorts heap data with `qsort`, prints with `printf`, writes a report with `fprintf` and reads it back with `fgets`, registers a function with `atexit` and returns from `main`. At `-O0`, `-O1`, `-O2` and `-Os` it ends with exit status 0, and its captured output and its report match, byte for byte, text recomputed in Rust. Seven more tests cover other arguments, four wrong command lines, a step budget that is too small, and control variants that end in a failed check, in `exit(42)` and in `abort()`. The test needs mingw-w64 on the host and fails, not skips, without it, so the CI workflow now installs it. Nothing from mingw-w64 is stored in the repository. Local runs used mingw-w64 14.0.0 with GCC 16.2.0. This is one program and one C runtime, compared by hand with a native build of the same source and not with Windows or x86 hardware; `docs/testing/gate-a.md` lists what it does not show. Awaiting independent review. + - Added file seeking and end-of-file resizing on the synthetic guest drive. - Added a bounded synthetic guest drive with synchronous file open, read, write, and size queries. diff --git a/crates/loader/tests/gate_a2.rs b/crates/loader/tests/gate_a2.rs new file mode 100644 index 0000000..2a79f8a --- /dev/null +++ b/crates/loader/tests/gate_a2.rs @@ -0,0 +1,440 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Gate A2 (issue #419): a hosted C program, built from source by this test +//! with the mingw-w64 C runtime and run through the loader, the standard +//! services and the ARM64 DBT. +//! +//! "Hosted" means the C runtime's own startup code runs before `main`, and +//! the program uses the standard C library as an ordinary program does: +//! command-line arguments, heap memory, `qsort` with a callback, `printf`, a +//! file written with `fprintf` and read back with `fgets`, `atexit`, and a +//! return from `main`. +//! +//! `tests/compat_fixtures/build-gate-a2.sh` compiles +//! `tests/compat_fixtures/gate_a2.c` with `x86_64-w64-mingw32-gcc`, so the +//! test needs mingw-w64 on the host. It fails, and does not skip, when the +//! compiler is 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. The program also +//! checks its own results and exits with the number of the first check that +//! fails, and three control variants end in three other ways, so a runtime +//! that reported success for everything would fail this test. + +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}; + +const REPORT: &str = "C:\\gate-a2-report.txt"; +const COUNT: usize = 48; +const SEED: u32 = 2026; +const LABEL: &str = "xenora"; +const ARGUMENTS: [&str; 3] = ["gate-a2.exe", "2026", LABEL]; +const BUDGET: usize = 2_000_000; + +/// Build every variant once and return the output directory. +fn built() -> &'static Path { + static OUT: OnceLock = OnceLock::new(); + OUT.get_or_init(|| { + // One directory per test process: two `cargo test` runs that share a + // target directory must not write and read the same files. + let out = PathBuf::from(env!("CARGO_TARGET_TMPDIR")) + .join(format!("gate-a2-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&out); + let script = concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../tests/compat_fixtures/build-gate-a2.sh" + ); + let build = Command::new("sh") + .arg(script) + .arg(&out) + .output() + .expect("run tests/compat_fixtures/build-gate-a2.sh"); + assert!( + build.status.success(), + "the Gate A2 program did not build; it needs mingw-w64 \ + (x86_64-w64-mingw32-gcc):\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 A2 built with:\n{toolchain}"); + out + }) +} + +struct Outcome { + result: StartupResult, + state: Arc, +} + +impl Outcome { + fn output(&self) -> String { + String::from_utf8(self.state.standard_output()).expect("ASCII output") + } + + fn errors(&self) -> String { + String::from_utf8(self.state.standard_error()).expect("ASCII output") + } +} + +/// Run one built variant through the real startup path with the standard +/// services and the given command line, loaded away from its preferred base +/// so its relocations matter. +fn run_with(name: &str, arguments: Option<&[&str]>, budget: usize) -> Outcome { + let bytes = std::fs::read(built().join(format!("{name}.exe"))).unwrap(); + let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); + if let Some(arguments) = arguments { + state.set_program_arguments(arguments).unwrap(); + } + 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, + }; + let result = run_synthetic_startup(&bytes, layout, registry, budget) + .unwrap_or_else(|error| panic!("{name}: {error}")); + Outcome { result, state } +} + +fn run(name: &str) -> Outcome { + run_with(name, Some(&ARGUMENTS), BUDGET) +} + +// --------------------------------------------------------------------------- +// What the program computes, restated independently +// --------------------------------------------------------------------------- + +/// The program's generator: a linear congruential step, then bits 8 to 23. +fn values(seed: u32) -> Vec { + let mut state = seed; + (0..COUNT) + .map(|_| { + state = state.wrapping_mul(1_103_515_245).wrapping_add(12_345); + (state >> 8) & 0xFFFF + }) + .collect() +} + +/// 64-bit FNV-1a over each value's four bytes, low byte first. +fn checksum(values: &[u32]) -> u64 { + values + .iter() + .flat_map(|value| value.to_le_bytes()) + .fold(14_695_981_039_346_656_037, |sum, byte| { + (sum ^ u64::from(byte)).wrapping_mul(1_099_511_628_211) + }) +} + +struct Expected { + /// Standard output of a complete run, with the line ends a text-mode + /// stream produces. + output: String, + /// The report file as it is stored on the drive. + report: String, + /// What the program prints before its first self-check on the data. + arguments: String, + sorted_line: String, +} + +/// How many checks the program counts on a complete run: five on its +/// arguments, one for the allocation, 47 on the sort order, one on the total, +/// the first `fopen`, five on writing the report, fifteen on reading it back +/// and one for the missing file. +const CHECKS: u32 = 5 + 1 + 47 + 1 + 1 + 5 + 15 + 1; + +fn expected() -> Expected { + let unsorted = values(SEED); + let mut sorted = unsorted.clone(); + sorted.sort_unstable(); + let total: u64 = unsorted.iter().map(|value| u64::from(*value)).sum(); + let (min, max) = (sorted[0], sorted[COUNT - 1]); + // A text-mode stream stores each line feed as a carriage return and a + // line feed. + let arguments = format!( + "gate a2: 3 arguments\r\n argv[0] = \"gate-a2.exe\"\r\n argv[1] = \"{SEED}\"\r\n \ + argv[2] = \"{LABEL}\"\r\n" + ); + let sorted_line = format!("sorted {COUNT} values: min {min}, max {max}, total {total}\r\n"); + let output = format!( + "{arguments}{sorted_line}checksum before {:016x}, after {:016x}\r\nreport \ + gate-a2-report.txt read back and verified\r\natexit: {CHECKS} checks passed\r\n", + checksum(&unsorted), + checksum(&sorted) + ); + let report = format!("label {LABEL}\r\ntotal {total}\r\nrange {min} {max}\r\nend\r\n"); + Expected { + output, + report, + arguments, + sorted_line, + } +} + +#[test] +fn the_restated_program_is_not_trivial() { + // The generator really produces varied data, the sort really changes it, + // and the two checksums really differ: the expected text is not built + // from degenerate values. + let unsorted = values(SEED); + let mut sorted = unsorted.clone(); + sorted.sort_unstable(); + assert_ne!(unsorted, sorted); + assert_ne!(checksum(&unsorted), checksum(&sorted)); + let mut distinct = sorted.clone(); + distinct.dedup(); + assert!(distinct.len() > COUNT / 2); + assert_eq!(CHECKS, 76); +} + +// --------------------------------------------------------------------------- +// The gate +// --------------------------------------------------------------------------- + +#[test] +fn the_program_runs_to_its_exit_at_every_optimization_level() { + let wanted = expected(); + for name in ["gate-a2-O0", "gate-a2-O1", "gate-a2-O2", "gate-a2-Os"] { + let outcome = run(name); + let result = &outcome.result; + let state = &outcome.state; + + // It returned from main, and the C runtime turned that into exit(0). + assert_eq!( + result.execution.exit_reason, + ExitReason::ProcessExit(0), + "{name}: stdout {:?}, stderr {:?}", + outcome.output(), + outcome.errors() + ); + assert_eq!(state.exit_status(), Some(0), "{name}"); + + // Standard output, byte for byte, including the line the function + // registered with atexit printed after main returned. + assert_eq!(outcome.output(), wanted.output, "{name}"); + assert_eq!(outcome.errors(), "", "{name}"); + + // The report file is on the drive as the program wrote it, and the + // file it looked for was not created. + let report = state.file_contents(REPORT).expect("a report"); + assert_eq!(String::from_utf8(report).unwrap(), wanted.report, "{name}"); + assert_eq!( + state.file_contents("C:\\gate-a2-missing.txt"), + None, + "{name}" + ); + assert_eq!(state.open_handle_count(), 0, "{name}"); + + // It was loaded, relocated and bound by the real startup path, and + // ran as translated ARM64 code. The C runtime's startup code is most + // of what runs. + assert!( + result.bound_imports >= 40, + "{name}: {}", + result.bound_imports + ); + assert!(result.relocations.applied_dir64 > 0, "{name}"); + let metrics = &result.dbt_metrics; + assert!( + metrics.blocks_compiled > 0 && metrics.native_bytes_emitted > 0, + "{name}" + ); + assert!(metrics.instructions_executed > 5_000, "{name}"); + assert!(metrics.service_calls > 60, "{name}"); + println!( + "{name}: {} imports bound, {} guest instructions, {} of them through the shared \ + semantics, {} service calls", + result.bound_imports, + metrics.instructions_executed, + metrics.interpreter_fallbacks, + metrics.service_calls + ); + } +} + +#[test] +fn other_arguments_give_other_results() { + // A different seed and label change the data, the checksums and the + // report, so the expected text above is not a constant the runtime could + // echo. + let outcome = run_with("gate-a2-O1", Some(&["a2", "7", "seven"]), BUDGET); + assert_eq!( + outcome.result.execution.exit_reason, + ExitReason::ProcessExit(0) + ); + let unsorted = values(7); + let mut sorted = unsorted.clone(); + sorted.sort_unstable(); + let total: u64 = unsorted.iter().map(|value| u64::from(*value)).sum(); + let output = outcome.output(); + assert!( + output.starts_with( + "gate a2: 3 arguments\r\n argv[0] = \"a2\"\r\n argv[1] = \"7\"\r\n argv[2] = \ + \"seven\"\r\n" + ), + "{output:?}" + ); + assert!( + output.contains(&format!( + "sorted {COUNT} values: min {}, max {}, total {total}\r\n", + sorted[0], + sorted[COUNT - 1] + )), + "{output:?}" + ); + assert!( + output.contains(&format!( + "checksum before {:016x}, after {:016x}\r\n", + checksum(&unsorted), + checksum(&sorted) + )), + "{output:?}" + ); + let report = outcome.state.file_contents(REPORT).unwrap(); + assert_eq!( + String::from_utf8(report).unwrap(), + format!( + "label seven\r\ntotal {total}\r\nrange {} {}\r\nend\r\n", + sorted[0], + sorted[COUNT - 1] + ) + ); +} + +#[test] +fn wrong_arguments_fail_the_check_that_looks_at_them() { + // (arguments, exit status, the lines printed before the failure) + let cases: [(Option<&[&str]>, u32, &str); 4] = [ + // No host arguments: one empty argument, so the count is wrong. + (None, 11, "gate a2: 1 arguments\r\n argv[0] = \"\"\r\n"), + ( + Some(&["a2", "5"]), + 11, + "gate a2: 2 arguments\r\n argv[0] = \"a2\"\r\n argv[1] = \"5\"\r\n", + ), + // A seed that is not a number. + ( + Some(&["a2", "5x", "label"]), + 13, + "gate a2: 3 arguments\r\n argv[0] = \"a2\"\r\n argv[1] = \"5x\"\r\n argv[2] = \ + \"label\"\r\n", + ), + // An empty label. + ( + Some(&["a2", "5", ""]), + 14, + "gate a2: 3 arguments\r\n argv[0] = \"a2\"\r\n argv[1] = \"5\"\r\n argv[2] = \ + \"\"\r\n", + ), + ]; + for (arguments, status, printed) in cases { + let outcome = run_with("gate-a2-O1", arguments, BUDGET); + let what = format!("{arguments:?}"); + assert_eq!( + outcome.result.execution.exit_reason, + ExitReason::ProcessExit(status), + "{what}" + ); + // The failed check says so on standard error, and the function + // registered with atexit still runs, because main returned. It + // reports the checks that passed before the failure: registering + // itself, and then one for each argument check before this one. + assert_eq!( + outcome.errors(), + format!("gate a2: check {status} failed\r\n"), + "{what}" + ); + let passed = status - 10; + assert_eq!( + outcome.output(), + format!("{printed}atexit: {passed} checks passed\r\n"), + "{what}" + ); + assert_eq!(outcome.state.file_contents(REPORT), None, "{what}"); + } +} + +#[test] +fn a_wrong_expectation_exits_with_the_number_of_the_failed_check() { + // The variant expects the sorted total to be one more than it is. + // Everything before that check passes, and nothing after it runs. + let wanted = expected(); + let outcome = run("gate-a2-break"); + assert_eq!( + outcome.result.execution.exit_reason, + ExitReason::ProcessExit(22) + ); + assert_eq!(outcome.state.exit_status(), Some(22)); + assert_eq!(outcome.errors(), "gate a2: check 22 failed\r\n"); + // Five argument checks, the allocation and 47 comparisons passed. + assert_eq!( + outcome.output(), + format!("{}atexit: 53 checks passed\r\n", wanted.arguments) + ); + assert_eq!(outcome.state.file_contents(REPORT), None); +} + +#[test] +fn exit_half_way_runs_the_registered_function_and_nothing_after() { + // The variant calls exit(42) after the sort. The status is exit's, the + // function registered with atexit runs, and the report is never written. + let wanted = expected(); + let outcome = run("gate-a2-exit"); + assert_eq!( + outcome.result.execution.exit_reason, + ExitReason::ProcessExit(42) + ); + assert_eq!(outcome.state.exit_status(), Some(42)); + assert_eq!(outcome.errors(), ""); + let output = outcome.output(); + assert!( + output.starts_with(&format!("{}{}", wanted.arguments, wanted.sorted_line)), + "{output:?}" + ); + // Through check 22: 5 + 1 + 47 + 1. + assert!( + output.ends_with("atexit: 54 checks passed\r\n"), + "{output:?}" + ); + assert!(!output.contains("report "), "{output:?}"); + assert_eq!(outcome.state.file_contents(REPORT), None); +} + +#[test] +fn abort_half_way_runs_no_registered_function() { + // The variant calls abort() after the sort: exit code 3, and the function + // registered with atexit does not run. + let wanted = expected(); + let outcome = run("gate-a2-abort"); + assert_eq!( + outcome.result.execution.exit_reason, + ExitReason::ProcessExit(3) + ); + assert_eq!(outcome.state.exit_status(), Some(3)); + let output = outcome.output(); + assert!( + output.starts_with(&format!("{}{}", wanted.arguments, wanted.sorted_line)), + "{output:?}" + ); + assert!(!output.contains("atexit:"), "{output:?}"); + assert_eq!(outcome.state.file_contents(REPORT), None); +} + +#[test] +fn a_step_budget_that_is_too_small_is_not_an_exit() { + let outcome = run_with("gate-a2-O1", Some(&ARGUMENTS), 200); + assert_eq!( + outcome.result.execution.exit_reason, + ExitReason::StepLimitExceeded + ); + assert_eq!(outcome.state.exit_status(), None); + assert_eq!(outcome.output(), ""); + assert_eq!(outcome.state.file_contents(REPORT), None); +} diff --git a/docs/README.md b/docs/README.md index 36f4ea6..3f623cc 100644 --- a/docs/README.md +++ b/docs/README.md @@ -52,7 +52,7 @@ Historical phase checkpoints retain their original evidence scope. - [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. +- [Gate A: a compiled C program](testing/gate-a.md) — The two milestones, what the A1 and A2 tests check and what they do not show. - [Mutation testing](testing/mutation.md) and [benchmark protocol](testing/benchmarks.md) — Test sensitivity, benchmark inputs, and timing requirements. ## Research and engineering decisions diff --git a/docs/testing/gate-a.md b/docs/testing/gate-a.md index cbd0a83..7d7dc9d 100644 --- a/docs/testing/gate-a.md +++ b/docs/testing/gate-a.md @@ -8,7 +8,7 @@ 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 | In progress; does not pass | +| 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 | Passes locally; awaiting independent review | ## A1 @@ -47,22 +47,59 @@ whose entry point returns its status gives the same result as `ExitProcess`. ## A2 -In progress. It does not pass, and there is no A2 test in the repository yet. +The program is [`tests/compat_fixtures/gate_a2.c`](../../tests/compat_fixtures/gate_a2.c). +Its build configuration and provenance are in +[`tests/compat_fixtures/README.md`](../../tests/compat_fixtures/README.md#gate-a2-a-hosted-c-program). +The gate is `crates/loader/tests/gate_a2.rs`: -The target is an original C program built with the mingw-w64 runtime (UCRT), -whose own startup code runs before `main`. Such a program needs pieces that -are being added one issue at a time. This page records only what is in the -tree it is part of: +```sh +cargo test --locked -p xenora-loader --test gate_a2 -- --nocapture +``` -| Piece | State here | -| --- | --- | -| Normal exit: `exit` with its `atexit` functions, `_exit` and `abort` | Present (#395), on top of the process exit A1 added | -| The PE headers mapped at the image base, which the startup code reads | Separate change (#333) | -| `FNINIT`, the one instruction the startup code needs that was refused | Separate change (#378) | -| The C runtime startup calls, and the functions a program imports but does not call | Separate changes (#382, #388) | -| `argc`, `argv` and the environment table | Separate change (#392) | -| Standard streams, files and formatted output | Not started | -| The A2 program itself, its build and its test | Not started | +"Hosted" means the program is linked with a real C runtime, whose own startup +code runs before `main`. Here that runtime is mingw-w64's, in its UCRT +flavour: the startup objects and a little of GCC's support library are linked +into the executable, and the C library itself is imported by name from the +Universal C Runtime's API-set DLLs and from `kernel32.dll`. Xenora's services +answer those imports. Nothing from Windows is loaded. -Until the last two rows exist nothing here shows a hosted C program running, -and A2 must not be reported as passing. +The test builds the program from source with `x86_64-w64-mingw32-gcc`. It +fails, and does not skip, when that compiler is missing. It then runs each +build through `run_synthetic_startup` with `register_standard_services`, +loaded away from its preferred base, with the command line +`gate-a2.exe 2026 xenora` set through `ServicesState::set_program_arguments`. +It checks, at `-O0`, `-O1`, `-O2` and `-Os`: + +- every import is bound (50 at each level with the toolchain used locally; the test prints the count) and base relocations are applied; +- the guest ends with `ExitReason::ProcessExit(0)`: `main` returned and the runtime's startup code passed its result to `exit`; +- captured standard output equals, byte for byte, text recomputed in Rust from the description of the program, including the line a function registered with `atexit` prints after `main` has returned; standard error is empty; +- the report file the program wrote with `fprintf` and `fputs` is on the in-memory drive with the recomputed contents, the file it looked for was not created, and no handle is left open; +- it ran as translated code, with service calls. + +The program checks its own results as well: it prints its arguments, fills +heap memory from a small generator, sorts it with `qsort` and a callback, +checksums it before and after, writes the report, reads it back with `fgets`, +`strtoul` and `strtoull`, and confirms that a missing file is reported. It +exits with the number of the first check that fails, and counts the checks +that passed; a complete run counts 76. + +Seven more tests guard against a runtime that reports success for everything: + +- another seed and label give another output and another report; +- four wrong command lines each fail the check that looks at them, with that check's number as the exit status and its message on standard error; +- a variant with one wrong expectation exits with 22; +- a variant that calls `exit(42)` half way ends with 42, its `atexit` function still runs, and the report is never written; +- a variant that calls `abort()` half way ends with 3 and its `atexit` function does not run; +- a step budget that is too small is not an exit; +- the Rust restatement of the program is itself checked not to be degenerate. + +### What A2 does not show + +- It is one program and one C runtime: mingw-w64 14.0.0 with GCC 16.2.0 locally. A program built with Microsoft's compiler starts differently and imports other functions; none has been tried. A larger program can need instructions and services this one does not. +- The same source built natively with Apple clang prints the same text once carriage returns are removed. That comparison was made by hand and is not part of the test. Nothing was compared with Windows or with x86 hardware. +- No floating point is formatted and no input is read. `printf` refuses the floating-point and wide-character conversions, and `stdin` and the `scanf` family do not exist. +- Most services the program calls are marked partial in the registry. No locale exists, no signal handler or exception filter is ever called, the environment table is empty, and a C stream is unbuffered and has no seek. They did what this program needs. +- `VirtualProtect`, `VirtualQuery` and `__C_specific_handler` are stubs that stop the guest if called. The program imports them and never calls them. +- It runs in the DBT only, on one guest thread. +- It reaches the guest through a test, not through `xenora run`. +- Nothing here concerns a commercial game or an Xbox launch environment. diff --git a/tests/compat_fixtures/README.md b/tests/compat_fixtures/README.md index 33ce38f..ecaa725 100644 --- a/tests/compat_fixtures/README.md +++ b/tests/compat_fixtures/README.md @@ -110,3 +110,54 @@ Provenance. The source, the name lists and the script were written for BetterXen 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. + +## Gate A2: a hosted C program + +`gate_a2.c` is an original C program that uses the standard C library as an +ordinary program does. It includes only ``, `` and +``. It prints its arguments, fills heap memory from a small +generator, sorts it with `qsort` and a callback, checksums it, writes a +report with `fprintf` and `fputs`, reads it back with `fgets`, `strtoul` and +`strtoull`, confirms that a missing file is reported, registers a function +with `atexit`, and returns from `main`. It checks every result itself and +exits with the number of the first check that fails. It uses no floating +point and reads no input. + +`build-gate-a2.sh [output directory]` builds it. `cargo test -p xenora-loader +--test gate_a2` 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. +The test fails, and does not skip, when the compiler is missing. + +Compiler configuration: + +| Step | Command | +| --- | --- | +| Compile and link | `x86_64-w64-mingw32-gcc -O -Wall -Wextra -Werror -o .exe gate_a2.c` | + +It is built at `-O0`, `-O1`, `-O2` and `-Os`, and three more times at `-O1` as +controls: `GATE_BREAK` (one wrong expectation), `GATE_EXIT` (`exit(42)` half +way) and `GATE_ABORT` (`abort()` half way). + +Tools. `MINGW_GCC` defaults to Homebrew's mingw-w64 when it is installed and +otherwise to the `x86_64-w64-mingw32-gcc` on `PATH`. The toolchain must use +the Universal C Runtime, which Homebrew's does; a toolchain built for the +older `msvcrt.dll` produces a program that imports other functions. On macOS +the script requires the compiler driver, the compiler proper, the assembler +and the linker, and every library they load that is a file on disk, to be +ARM64: it checks each with `file` and `lipo -archs`, and each library +`otool -L` lists with `lipo -archs`. It writes the compiler version 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. + +Provenance. The source and the script were written for Xenora and are +GPL-3.0-or-later. Unlike the Gate A1 program, each built executable contains +code that is not Xenora's: mingw-w64's startup objects and a little of GCC's +support library, as any program built with that toolchain does. Neither is +stored in the repository or in its history; the executables are test output. +mingw-w64's `COPYING` file says its runtime is under the Zope Public License +2.1 except for parts marked as public domain, BSD or LGPL; GCC's support +library is GPL-3.0-or-later with the GCC Runtime Library Exception. The C +library itself is not linked: the program imports it by name, and Xenora's +own services answer. diff --git a/tests/compat_fixtures/build-gate-a2.sh b/tests/compat_fixtures/build-gate-a2.sh new file mode 100755 index 0000000..6afe037 --- /dev/null +++ b/tests/compat_fixtures/build-gate-a2.sh @@ -0,0 +1,96 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-3.0-or-later +# +# Build the Gate A2 program, tests/compat_fixtures/gate_a2.c, as x86-64 PE32+ +# executables linked with the mingw-w64 C runtime (UCRT flavour). The +# runtime's own startup code runs before main, which is what makes the program +# "hosted". +# +# build-gate-a2.sh [output directory] default: artifacts/gate-a2 +# +# Tool, native to the host: +# MINGW_GCC an x86_64-w64-mingw32-gcc. Default: Homebrew mingw-w64 if +# installed, otherwise the one on PATH. +# +# Nothing from mingw-w64 is stored in the repository. Each built executable +# contains that project's startup objects and a little of GCC's support +# library, as any program built with it does; the executables are test +# output and are not committed. +set -eu +cd "$(dirname "$0")/../.." +root=$PWD +src="$root/tests/compat_fixtures/gate_a2.c" +out=${1:-"$root/artifacts/gate-a2"} + +gcc=${MINGW_GCC:-} +if [ -z "$gcc" ]; then + gcc=/opt/homebrew/opt/mingw-w64/bin/x86_64-w64-mingw32-gcc + [ -x "$gcc" ] || gcc=$(command -v x86_64-w64-mingw32-gcc || true) +fi +if [ -z "$gcc" ] || [ ! -x "$gcc" ]; then + echo "missing tool: x86_64-w64-mingw32-gcc (set MINGW_GCC, or install mingw-w64)" >&2 + exit 1 +fi +# AGENTS.md: host tools must be ARM64, checked with file, lipo -archs and +# otool -L. The driver is a symbolic link into the toolchain; the compiler +# proper, the assembler and the linker it runs are checked as well. +native= +check_native_tool() { + tool=$1 + 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 + for library in $(otool -L "$tool" | awk 'NR > 1 { print $1 }'); do + [ -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$tool: $(file -bL "$tool") +" +} +if [ "$(uname -s)" = Darwin ]; then + # Check the driver before asking it about helpers: even -print-prog-name + # executes the binary and must never start an Intel-only compiler. + check_native_tool "$gcc" + for helper in cc1 as ld collect2; do + path=$("$gcc" -print-prog-name="$helper") + case "$path" in + /*) ;; + *) path=$(command -v "$path" || true) ;; + esac + if [ -z "$path" ] || [ ! -x "$path" ]; then + echo "missing compiler helper: $helper" >&2 + exit 1 + fi + check_native_tool "$path" + done +fi + +mkdir -p "$out" +cd "$out" +{ + "$gcc" --version | head -1 + printf 'target: %s\n' "$("$gcc" -dumpmachine)" +} > toolchain.txt +printf '%s' "$native" > toolchain-native.txt + +# name, optimization level, extra definition +build() { + "$gcc" "-$2" -Wall -Wextra -Werror ${3:+"-D$3"} -o "$1.exe" "$src" +} +for level in O0 O1 O2 Os; do + build "gate-a2-$level" "$level" "" +done +# Controls: a wrong expectation, exit() half way, abort() half way. +build gate-a2-break O1 GATE_BREAK +build gate-a2-exit O1 GATE_EXIT +build gate-a2-abort O1 GATE_ABORT diff --git a/tests/compat_fixtures/gate_a2.c b/tests/compat_fixtures/gate_a2.c new file mode 100644 index 0000000..21538d4 --- /dev/null +++ b/tests/compat_fixtures/gate_a2.c @@ -0,0 +1,157 @@ +/* SPDX-License-Identifier: GPL-3.0-or-later */ + +/* + * Gate A2 (issue #419): a hosted C program. Original code written for Xenora. + * + * It is built with a real C runtime's startup code, which runs before main, + * and uses the standard C library the way an ordinary program does: + * command-line arguments, heap memory, sorting with a callback, formatted + * output, a file written and read back, a function registered with atexit, + * and a normal return from main. + * + * Every result is checked by the program itself. The exit status is 0 when + * every check passed and otherwise names the first one that failed, so a + * runtime that computes something wrongly cannot report success. + * + * It needs no floating point and no input. + * + * Control variants, selected at build time, each end in a different way so + * that the test can tell a real pass from a runtime that reports success for + * everything: + * GATE_BREAK expects a wrong total, so check 22 fails + * GATE_EXIT calls exit(42) half way, without returning from main + * GATE_ABORT calls abort() half way + */ +#include +#include +#include + +#define COUNT 48 + +static unsigned checks_passed; +static const char *report_name = "gate-a2-report.txt"; + +static void say_goodbye(void) { + /* Runs from exit, after main has returned. */ + printf("atexit: %u checks passed\n", checks_passed); +} + +static int by_value(const void *left, const void *right) { + unsigned a = *(const unsigned *)left, b = *(const unsigned *)right; + return (a > b) - (a < b); +} + +/* A linear congruential generator, so the data does not depend on a library. */ +static unsigned next_value(unsigned *state) { + *state = *state * 1103515245u + 12345u; + return (*state >> 8) & 0xffffu; +} + +static unsigned long long checksum(const unsigned *values, size_t count) { + unsigned long long sum = 14695981039346656037ull; /* FNV-1a, 64-bit */ + for (size_t i = 0; i < count; i++) { + for (int shift = 0; shift < 32; shift += 8) { + sum ^= (values[i] >> shift) & 0xffu; + sum *= 1099511628211ull; + } + } + return sum; +} + +#define CHECK(code, condition) \ + do { \ + if (!(condition)) { \ + fprintf(stderr, "gate a2: check %d failed\n", (code)); \ + return (code); \ + } \ + checks_passed++; \ + } while (0) + +int main(int argc, char **argv) { + CHECK(10, atexit(say_goodbye) == 0); + + /* Arguments: a program name, a seed and a label. */ + printf("gate a2: %d arguments\n", argc); + for (int i = 0; i < argc; i++) printf(" argv[%d] = \"%s\"\n", i, argv[i]); + CHECK(11, argc == 3); + CHECK(12, argv[argc] == NULL); + char *end = NULL; + unsigned long seed = strtoul(argv[1], &end, 10); + CHECK(13, end != argv[1] && *end == '\0'); + const char *label = argv[2]; + CHECK(14, strlen(label) > 0 && strlen(label) < 32); + + /* Heap memory, filled, sorted through a callback and verified. */ + unsigned *values = malloc(COUNT * sizeof *values); + CHECK(20, values != NULL); + unsigned state = (unsigned)seed; + unsigned long long total = 0; + for (size_t i = 0; i < COUNT; i++) { + values[i] = next_value(&state); + total += values[i]; + } + unsigned long long before = checksum(values, COUNT); + qsort(values, COUNT, sizeof *values, by_value); + unsigned long long sorted_total = 0; + for (size_t i = 0; i < COUNT; i++) { + if (i > 0) CHECK(21, values[i - 1] <= values[i]); + sorted_total += values[i]; + } +#ifdef GATE_BREAK + CHECK(22, sorted_total == total + 1); +#else + CHECK(22, sorted_total == total); +#endif + unsigned long long after = checksum(values, COUNT); + printf("sorted %d values: min %u, max %u, total %llu\n", + COUNT, values[0], values[COUNT - 1], total); + printf("checksum before %016llx, after %016llx\n", before, after); + +#ifdef GATE_EXIT + /* The registered function still runs, and nothing after this does. */ + exit(42); +#endif +#ifdef GATE_ABORT + /* Nothing registered runs, and the status is abort's. */ + abort(); +#endif + + /* A file written with formatted output. */ + FILE *report = fopen(report_name, "w"); + if (report == NULL) { + perror(report_name); + return 30; + } + checks_passed++; + CHECK(31, fprintf(report, "label %s\n", label) > 0); + CHECK(32, fprintf(report, "total %llu\n", total) > 0); + CHECK(33, fprintf(report, "range %u %u\n", values[0], values[COUNT - 1]) > 0); + CHECK(34, fputs("end\n", report) >= 0); + CHECK(35, fclose(report) == 0); + + /* The same file read back line by line and compared. */ + report = fopen(report_name, "r"); + CHECK(40, report != NULL); + char line[96]; + CHECK(41, fgets(line, sizeof line, report) != NULL); + CHECK(42, strncmp(line, "label ", 6) == 0); + CHECK(43, strlen(line) == 6 + strlen(label) + 1); + CHECK(44, strncmp(line + 6, label, strlen(label)) == 0 && line[strlen(line) - 1] == '\n'); + CHECK(45, fgets(line, sizeof line, report) != NULL); + CHECK(46, strncmp(line, "total ", 6) == 0); + CHECK(47, strtoull(line + 6, &end, 10) == total && *end == '\n'); + CHECK(48, fgets(line, sizeof line, report) != NULL); + CHECK(49, strncmp(line, "range ", 6) == 0); + CHECK(50, strtoul(line + 6, &end, 10) == values[0] && *end == ' '); + CHECK(51, strtoul(end, &end, 10) == values[COUNT - 1] && *end == '\n'); + CHECK(52, fgets(line, sizeof line, report) != NULL && strcmp(line, "end\n") == 0); + CHECK(53, fgets(line, sizeof line, report) == NULL); + CHECK(54, fclose(report) == 0); + + /* A file that does not exist is reported, not opened. */ + CHECK(60, fopen("gate-a2-missing.txt", "r") == NULL); + + free(values); + printf("report %s read back and verified\n", report_name); + return 0; +}