Execute emitted CRT and stub handlers in generated conformance tests

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
This commit is contained in:
Adeeb Rahman committed 2026-11-24 08:09:03 -05:00
1 parent 3922f56d68
commit 5617b883b9
3 files changed
+89 -288

No files matched your search

+2
View File
@@ -13,6 +13,8 @@ remains unsupported.
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
### Added
- Generated import conformance tests now execute emitted service handlers and verify unsupported stubs.
- Added a typed runtime service registry (`crates/loader/runtime/services.txt`) and `xenora-runtime-gen`, which generates Win64 argument and result adapters, static metadata and a coverage report. It covers 20 services: 16 existing kernel32 services moved to typed handlers, and `sqrt`, `sqrtf`, `fabs` and `fabsf` with arguments and results in XMM registers. Conflicting keys, unlisted API sets, unsupported types and behaviour without an existing test are rejected. See `docs/runtime/registry.md`.
- Added SSE and SSE2 floating point in scalar and packed, binary32 and binary64 forms: add, subtract, multiply, divide, minimum, maximum, square root, compares, COMI/UCOMI and the conversions between formats and integers (parts of #127 and #128; awaiting independent review). `crates/loader/src/softfloat.rs` computes every result exactly and rounds once, with MXCSR rounding modes, sticky flags, denormals-are-zero, flush-to-zero, tininess after rounding and x86 NaN rules; host floating point is not used because ARM64 differs. An unmasked exception exits with `SimdException` and leaves everything but MXCSR unchanged. RCP, RSQRT and MMX conversions are rejected, and no floating-point form is translated to NEON yet.
- Added 6,824 floating-point vectors computed with exact fractions by `tests/x86/float_reference.py`, run through both engines from registers and memory and through the packed forms, and more than two million round-to-nearest results compared with the host's IEEE 754 hardware.
+73 -282
View File
@@ -40,6 +40,13 @@ fn write_file(dir: &str, name: &str, content: &str) -> Result<(), String> {
std::fs::write(&path, content).map_err(|e| format!("write {path}: {e}"))
}
fn unique_entries(manifest: &Manifest) -> impl Iterator<Item = &crate::manifest::ManifestEntry> {
let mut seen = std::collections::BTreeSet::new();
manifest.entries.iter().filter(move |entry| {
seen.insert((entry.module.to_ascii_lowercase(), entry.symbol.as_str()))
})
}
/// Generate all files from the manifest.
pub fn generate(manifest: &Manifest, _db: &SymbolDb) -> GeneratedFiles {
let crt_rs = gen_crt(manifest);
@@ -81,7 +88,7 @@ pub fn register_generated_crt_services(registry: &mut ImportRegistry) {
"#,
);
for entry in manifest.entries.iter() {
for entry in unique_entries(manifest) {
match &entry.classification {
Classification::CrtNative { libc_sym, note } => {
out.push_str(&gen_crt_native_registration(
@@ -204,7 +211,7 @@ pub fn register_generated_stubs(registry: &mut ImportRegistry) {
"#,
);
for entry in manifest.entries.iter() {
for entry in unique_entries(manifest) {
if let Classification::Win32Stub { note, .. } = &entry.classification {
out.push_str(&format!(
r#"
@@ -237,72 +244,65 @@ fn gen_tests(manifest: &Manifest) -> String {
let mut out = file_header("generated_tests.rs");
out.push_str(
r#"
//! Auto-generated conformance tests for CRT bindings.
//! Each test verifies that the generated service handler returns a correct value
//! for a canonical input against a known-good expected output.
//! Do not edit manually — regenerate with `xenora imports generate`.
//!
//! Run with: cargo test -p xenora-loader --test generated
//! Conformance tests for emitted service registrations.
//! Place this file and the two generated registration files together as
//! an integration test in a Cargo package that depends on xenora-loader.
use xenora_loader::imports::{ImportRegistry, Win64Args};
use xenora_loader::cpu::CpuState;
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
use xenora_loader::services::register_standard_services;
pub use xenora_loader::{cpu, imports, memory};
/// Build a minimal test registry with generated bindings loaded.
fn test_registry() -> ImportRegistry {
let mut reg = ImportRegistry::new();
let clock = std::sync::Arc::new(xenora_loader::services::SystemClock);
let state = std::sync::Arc::new(xenora_loader::services::ServicesState::new(clock));
register_standard_services(&mut reg, state);
// Generated registrations would be loaded here in integration.
reg
#[path = "generated_crt.rs"]
mod generated_crt;
#[path = "generated_stubs.rs"]
mod generated_stubs;
use cpu::{CpuState, ExitReason};
use imports::{ImportRegistry, ServiceStatus, Win64Args};
use memory::GuestMemory;
fn check(module: &str, symbol: &str, input: u64, status: ServiceStatus, expected: Result<u64, ExitReason>) {
let mut registry = ImportRegistry::new();
generated_crt::register_generated_crt_services(&mut registry);
generated_stubs::register_generated_stubs(&mut registry);
let service = registry.binding(module, symbol).expect("generated binding");
assert_eq!(service.status, status);
let args = Win64Args { rcx: input, rdx: 0, r8: 0, r9: 0, rsp: 0x8000 };
let mut cpu = CpuState::new(0x1000, 0x8000);
let mut memory = GuestMemory::new();
assert_eq!((service.handler)(&args, &mut cpu, &mut memory), expected);
}
fn fresh_state() -> (CpuState, GuestMemory) {
let cpu = CpuState::new(0x1000, 0x8000);
let mut mem = GuestMemory::new();
mem.map_region(0x1000, 0x20000, MemoryPermissions::READ_WRITE_EXECUTE)
.expect("map test region");
(cpu, mem)
}
"#,
);
// Generate a test per CrtNative entry that has a testable canonical case
for entry in manifest.entries.iter() {
if let Classification::CrtNative { libc_sym, .. } = &entry.classification
&& crt_dispatch_expr(&entry.symbol).is_some()
&& let Some(test) = canonical_test(&entry.symbol, libc_sym)
{
out.push_str(&format!(
r#"
for (index, entry) in unique_entries(manifest).enumerate() {
let (input, status, expected) = match &entry.classification {
Classification::CrtNative { .. } if crt_dispatch_expr(&entry.symbol).is_some() => {
let Some((input, expected)) = canonical_integer_case(&entry.symbol) else {
continue;
};
(input, "Partial", format!("Ok({expected})"))
}
Classification::CrtNative { .. }
| Classification::CrtWrapper { .. }
| Classification::RuntimeHelper { .. }
| Classification::Win32Stub { .. } => (
0,
"Stub",
"Err(ExitReason::IllegalInstruction(0xFE))".to_owned(),
),
_ => continue,
};
out.push_str(&format!(
r#"
#[test]
fn generated_test_{fn_name}() {{
{test}
fn generated_test_{name}_{index}() {{
check({module:?}, {symbol:?}, {input}, ServiceStatus::{status}, {expected});
}}
"#,
fn_name = symbol_to_ident_lower(&entry.symbol),
test = test,
));
}
name = symbol_to_ident_lower(&entry.symbol),
module = entry.module,
symbol = entry.symbol,
));
}
// Test that every generated stub is registered and returns without error
out.push_str(
r#"
#[test]
fn generated_stubs_are_all_registered() {
// Verify that the manifest-driven registration functions compile and
// that every generated stub returns Ok without panicking.
// This test validates the generated source compiles; individual stubs
// are tested separately when they have known-good canonical inputs.
let _ = test_registry();
}
"#,
);
out
}
@@ -380,228 +380,19 @@ fn crt_dispatch_expr(symbol: &str) -> Option<String> {
})
}
/// Returns a Rust test body for symbols where we can derive a known-good expected value.
fn canonical_test(symbol: &str, _libc_sym: &str) -> Option<String> {
match symbol {
"strlen" => Some(
r#"
let (_cpu, mut mem) = fresh_state();
// Write "hello\0" at 0x2000 (already mapped by fresh_state)
for (i, b) in b"hello\0".iter().enumerate() {
mem.write_u8(0x2000 + i as u64, *b).unwrap();
}
let _args = Win64Args { rcx: 0x2000, rdx: 0, r8: 0, r9: 0, rsp: 0x8000 };
// strlen should return 5
// (This test validates the generated dispatch body compiles and executes correctly.)
let result = {
let mut len: u64 = 0;
loop {
let b = mem.read_u8(0x2000 + len).unwrap();
if b == 0 { break; }
len += 1;
}
len
};
assert_eq!(result, 5, "strlen('hello') == 5");
"#
.to_string(),
),
"memset" => Some(
r#"
let (_cpu, mut mem) = fresh_state();
for i in 0..8u64 {
mem.write_u8(0x3000 + i, 0xAA).unwrap();
}
// memset(0x3000, 0xBB, 4)
let val: u8 = 0xBB;
for i in 0..4u64 {
mem.write_u8(0x3000 + i, val).unwrap();
}
for i in 0..4u64 {
assert_eq!(mem.read_u8(0x3000 + i).unwrap(), 0xBB, "memset byte {i}");
}
// bytes 4..8 should still be 0xAA
for i in 4..8u64 {
assert_eq!(mem.read_u8(0x3000 + i).unwrap(), 0xAA, "memset preserved byte {i}");
}
"#
.to_string(),
),
"memcmp" => Some(
r#"
let (_cpu, mut mem) = fresh_state();
for (i, b) in b"ABCDE".iter().enumerate() {
mem.write_u8(0x4000 + i as u64, *b).unwrap();
mem.write_u8(0x4100 + i as u64, *b).unwrap();
}
// memcmp equal regions
let mut result = 0i64;
for i in 0..5u64 {
let ba = mem.read_u8(0x4000 + i).unwrap();
let bb = mem.read_u8(0x4100 + i).unwrap();
if ba != bb { result = ba as i64 - bb as i64; break; }
}
assert_eq!(result, 0, "memcmp equal regions");
"#
.to_string(),
),
"strcmp" => Some(
r#"
let (_cpu, mut mem) = fresh_state();
for (i, b) in b"hello\0".iter().enumerate() {
mem.write_u8(0x5000 + i as u64, *b).unwrap();
mem.write_u8(0x5100 + i as u64, *b).unwrap();
}
let mut i = 0u64;
let result = loop {
let ca = mem.read_u8(0x5000 + i).unwrap();
let cb = mem.read_u8(0x5100 + i).unwrap();
if ca != cb { break (ca as i64 - cb as i64) as u64; }
if ca == 0 { break 0; }
i += 1;
};
assert_eq!(result, 0, "strcmp equal strings");
"#
.to_string(),
),
// Math tests using known values
"sqrt" => Some(
r#"
// sqrt(4.0) == 2.0 — basic sanity check
let x: f64 = 4.0;
let result = x.sqrt();
assert!((result - 2.0).abs() < 1e-10, "sqrt(4.0) = {result}");
"#
.to_string(),
),
"sqrtf" => Some(
r#"
let x: f32 = 9.0;
let result = x.sqrt();
assert!((result - 3.0).abs() < 1e-6, "sqrtf(9.0) = {result}");
"#
.to_string(),
),
"fabs" => Some(
r#"
let x: f64 = -3.14;
let result = x.abs();
assert!((result - 3.14).abs() < 1e-10, "fabs(-3.14) = {result}");
"#
.to_string(),
),
"fabsf" => Some(
r#"
let x: f32 = -2.5;
let result = x.abs();
assert!((result - 2.5f32).abs() < 1e-6, "fabsf(-2.5) = {result}");
"#
.to_string(),
),
"isalpha" => Some(
r#"
let result_a = b'A'.is_ascii_alphabetic();
let result_1 = b'1'.is_ascii_alphabetic();
assert!(result_a, "isalpha('A') should be true");
assert!(!result_1, "isalpha('1') should be false");
"#
.to_string(),
),
"isdigit" => Some(
r#"
assert!(b'5'.is_ascii_digit(), "isdigit('5') should be true");
assert!(!b'x'.is_ascii_digit(), "isdigit('x') should be false");
"#
.to_string(),
),
"abs" => Some(
r#"
let x: i32 = -42;
assert_eq!(x.abs(), 42, "abs(-42) == 42");
"#
.to_string(),
),
"llabs" => Some(
r#"
let x: i64 = -9_000_000_000;
assert_eq!(x.unsigned_abs(), 9_000_000_000u64, "llabs(-9e9) == 9e9");
"#
.to_string(),
),
"cos" => Some(
r#"
let result = (0.0f64).cos();
assert!((result - 1.0).abs() < 1e-10, "cos(0.0) = {result}");
"#
.to_string(),
),
"cosf" => Some(
r#"
let result = (0.0f32).cos();
assert!((result - 1.0).abs() < 1e-6, "cosf(0.0) = {result}");
"#
.to_string(),
),
"sin" => Some(
r#"
let result = (0.0f64).sin();
assert!(result.abs() < 1e-10, "sin(0.0) = {result}");
"#
.to_string(),
),
"sinf" => Some(
r#"
let result = (0.0f32).sin();
assert!(result.abs() < 1e-6, "sinf(0.0) = {result}");
"#
.to_string(),
),
"floor" => Some(
r#"
let result = (3.7f64).floor();
assert_eq!(result, 3.0, "floor(3.7) = {result}");
"#
.to_string(),
),
"ceil" => Some(
r#"
let result = (3.2f64).ceil();
assert_eq!(result, 4.0, "ceil(3.2) = {result}");
"#
.to_string(),
),
"strncmp" => Some(
r#"
let (_cpu, mut mem) = fresh_state();
for (i, b) in b"hello world\0".iter().enumerate() {
mem.write_u8(0x6000 + i as u64, *b).unwrap();
mem.write_u8(0x6100 + i as u64, *b).unwrap();
}
let n = 5usize;
let mut diff = 0i64;
for i in 0..n as u64 {
let ca = mem.read_u8(0x6000 + i).unwrap();
let cb = mem.read_u8(0x6100 + i).unwrap();
if ca != cb { diff = ca as i64 - cb as i64; break; }
}
assert_eq!(diff, 0, "strncmp first 5 chars match");
"#
.to_string(),
),
"tolower" => Some(
r#"
let c = b'A' as char;
assert_eq!(c.to_ascii_lowercase(), 'a');
"#
.to_string(),
),
"toupper" => Some(
r#"
let c = b'z' as char;
assert_eq!(c.to_ascii_uppercase(), 'Z');
"#
.to_string(),
),
_ => None,
}
/// Independent canonical inputs and expected integer return bits.
fn canonical_integer_case(symbol: &str) -> Option<(u64, u64)> {
Some(match symbol {
"abs" | "labs" | "llabs" => ((-42i64) as u64, 42),
"tolower" => (65, 97),
"toupper" => (122, 90),
"isalnum" | "isalpha" | "isupper" | "isxdigit" => (65, 1),
"isdigit" => (53, 1),
"islower" => (122, 1),
"isspace" => (32, 1),
"isprint" => (65, 1),
"iscntrl" => (127, 1),
"ispunct" => (33, 1),
_ => return None,
})
}
+14 -6
View File
@@ -38,6 +38,7 @@ fn test_manifest_and_codegen_pipeline() {
let csv_content = r#""module","symbol_or_ordinal","iat_rva"
"api-ms-win-crt-math-l1-1-0.dll","acos",0x1000
"api-ms-win-crt-string-l1-1-0.dll","tolower",0x1008
"API-MS-WIN-CRT-STRING-L1-1-0.DLL","tolower",0x1048
"api-ms-win-core-processthreads-l1-1-0.dll","CreateThread",0x1010
"custom.dll","UnknownCustomFunc",0x1018
"kernel32.dll","QueryPerformanceCounter",0x1020
@@ -53,27 +54,34 @@ fn test_manifest_and_codegen_pipeline() {
std::fs::write(&csv_file, csv_content).unwrap();
let records = parse_csv(csv_file.to_str().unwrap()).unwrap();
assert_eq!(records.len(), 9);
assert_eq!(records.len(), 10);
let db = SymbolDb::builtin();
let manifest = Manifest::build(&records, &db);
let summary = manifest.summary();
assert_eq!(*summary.get("crt-native").unwrap_or(&0), 2);
assert_eq!(*summary.get("crt-native").unwrap_or(&0), 3);
assert_eq!(*summary.get("win32-stub").unwrap_or(&0), 1);
assert_eq!(*summary.get("manual").unwrap_or(&0), 1);
assert_eq!(summary.get("standard-service"), Some(&5));
assert_eq!(manifest.generatable().count(), 3);
assert_eq!(manifest.generatable().count(), 4);
let files = generate(&manifest, &db);
assert!(files.crt_rs.contains("register_generated_crt_services"));
assert!(files.crt_rs.contains("tolower"));
assert_eq!(files.crt_rs.matches("\"tolower\"").count(), 1);
let acos = files.crt_rs.split_once("\"acos\"").unwrap().1;
let (acos, _) = acos.split_once("registry.register_with_status").unwrap();
let acos = acos.split("registry.register_with_status").next().unwrap();
assert!(acos.contains("ServiceStatus::Stub"));
assert!(acos.contains("Err(ExitReason::IllegalInstruction(0xFE))"));
assert!(!files.tests_rs.contains("generated_test_acos"));
assert!(files.tests_rs.contains("generated_test_acos"));
assert!(
files
.tests_rs
.contains("generated_crt::register_generated_crt_services")
);
assert!(files.tests_rs.contains("(service.handler)"));
assert!(files.tests_rs.contains("generated_test_createthread"));
assert!(files.stubs_rs.contains("CreateThread"));
assert!(!files.stubs_rs.contains("QueryPerformance"));
assert!(!files.stubs_rs.contains("GetThreadId"));