diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f0f6db..77e46b3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game remains unsupported. ### Added +- 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. - Added XMM0-XMM15 and MXCSR to the guest CPU state, and the SSE and SSE2 moves and packed integer forms: aligned, unaligned, scalar, half and non-temporal moves, MOVD/MOVQ, sign-mask extraction, bitwise operations, wrapping and saturating arithmetic, compares, minimum, maximum, average, multiplies, PSADBW, packs, unpacks, shifts, shuffles, PINSRW, PEXTRW, LDMXCSR and STMXCSR (parts of #124, #125, #126 and #128; awaiting independent review). Operations with identical NEON lane semantics are translated to ARM64; the rest call the shared semantics. Misaligned 16-byte operands and reserved MXCSR bits raise a distinct general-protection exit. MXCSR is state only: floating-point arithmetic is not implemented. @@ -89,12 +90,17 @@ remains unsupported. - Added Win64 TEB allocation and `gs_base` initialization to synthetic guest startup. ### Changed +- Registering an import key twice is now an error instead of silently replacing the first service, ordinals are distinct from names, and API sets in the import generator match exactly instead of by prefix. +- `GetSystemTimeAsFileTime` now stops the guest on a null pointer, as on any other invalid pointer, instead of setting the last error. - Simplified the claim rules in `AGENTS.md`, `CONTRIBUTING.md` and the pull request template at the maintainer's request: claim an issue by replying on it in plain words, never claim over an existing claim, and treat a claim as stale only after about one week without a pull request. The task-queue lease (`lease_hours` in `.github/agent-queue.json`) is now 168 hours to match, and `docs/coordination/agent-tasks.md` marks the queue commands as optional. - The static PE probe now marks x86-64 SIB memory addressing as DBT-supported, matching the native DBT. ### Fixed +- Fixed the static probe panicking on a truncated import name (#270), and made the probe and the binder share one bounded import parser. Truncated, unterminated, empty or non-ASCII names, reserved bits and endless tables are reported by the probe and refused by the binder. +- Fixed import binding writing some slots before finding an unresolved import, and service calls taking effect before an unreadable return address was noticed. A service that changes a nonvolatile register, including XMM6 to XMM15, now stops the guest (part of #201). +- Fixed older import-generator templates that reported success for unimplemented wrappers, used a nonexistent exit reason, and read floating-point arguments from integer registers. - Fixed guest flags in the native DBT (#64, #70). They lived only in host NZCV, so they were lost across helper calls and block boundaries and register ADD, SUB and XOR set none. JB, JAE, JBE and JA used ARM carry polarity, which is inverted for subtraction. Flags are now stored in the guest state. - Fixed the static probe reporting support for forms an engine rejects, including NOP, TEST, most conditional branches and the FF group in the interpreter. - Fixed the native DBT's `SXTW` encoding, which set bit 3 of the source register and was right only for registers that already had it set; the previous test used such a register by chance. diff --git a/crates/import-gen/src/apiset.rs b/crates/import-gen/src/apiset.rs index eb80941..39264b8 100644 --- a/crates/import-gen/src/apiset.rs +++ b/crates/import-gen/src/apiset.rs @@ -10,49 +10,26 @@ //! Source: Public Windows SDK `apisetcounters.h` and documented Microsoft API-set schema. /// Resolve an API-set virtual DLL name to its canonical Windows module name. +/// +/// API sets are matched exactly against [`get_api_sets_for_canonical`]. A name +/// that merely starts like a known family is not assumed to forward anywhere. pub fn resolve_api_set_canonical(module: &str) -> &'static str { let lower = module.to_ascii_lowercase(); - let trimmed = lower.strip_suffix(".dll").unwrap_or(&lower); - - if trimmed.starts_with("api-ms-win-core-processthreads") - || trimmed.starts_with("api-ms-win-core-processtopology") - || trimmed.starts_with("api-ms-win-core-profile") - || trimmed.starts_with("api-ms-win-core-sysinfo") - || trimmed.starts_with("api-ms-win-core-interlocked") - || trimmed.starts_with("api-ms-win-core-libraryloader") - || trimmed.starts_with("api-ms-win-core-namedpipe") - || trimmed.starts_with("api-ms-win-core-handle") - || trimmed.starts_with("api-ms-win-core-errorhandling") - || trimmed.starts_with("api-ms-win-core-debug") - || trimmed.starts_with("api-ms-win-core-datetime") - || trimmed.starts_with("api-ms-win-core-timezone") - || trimmed.starts_with("api-ms-win-core-processenvironment") - || trimmed.starts_with("api-ms-win-core-file") - || trimmed.starts_with("api-ms-win-core-io") - || trimmed.starts_with("api-ms-win-core-synch") - || trimmed.starts_with("api-ms-win-core-memory") - || trimmed.starts_with("api-ms-win-core-heap") - || trimmed.starts_with("api-ms-win-core-string") - || trimmed.starts_with("api-ms-win-core-localization") - { - "kernel32.dll" - } else if trimmed.starts_with("api-ms-win-core-rtlsupport") { - "ntdll.dll" - } else if trimmed.starts_with("api-ms-win-crt-") { - "ucrtbase.dll" - } else if trimmed == "vcruntime140" || trimmed == "vcruntime140_1" { - "vcruntime140.dll" - } else if trimmed == "msvcp140" || trimmed == "msvcp140_1" || trimmed == "msvcp140_2" { - "msvcp140.dll" - } else { - match module.to_ascii_lowercase().as_str() { - "kernel32.dll" | "kernelbase.dll" => "kernel32.dll", - "ntdll.dll" => "ntdll.dll", - "ws2_32.dll" => "ws2_32.dll", - "advapi32.dll" => "advapi32.dll", - _ => "unknown.dll", + for canonical in ["kernel32.dll", "ucrtbase.dll"] { + if get_api_sets_for_canonical(canonical).contains(&lower.as_str()) { + return canonical; } } + match lower.as_str() { + "kernel32.dll" | "kernelbase.dll" => "kernel32.dll", + "ucrtbase.dll" => "ucrtbase.dll", + "ntdll.dll" => "ntdll.dll", + "ws2_32.dll" => "ws2_32.dll", + "advapi32.dll" => "advapi32.dll", + "vcruntime140.dll" | "vcruntime140_1.dll" => "vcruntime140.dll", + "msvcp140.dll" | "msvcp140_1.dll" | "msvcp140_2.dll" => "msvcp140.dll", + _ => "unknown.dll", + } } /// Known API sets that forward to the given canonical host module. @@ -78,6 +55,7 @@ pub fn get_api_sets_for_canonical(canonical: &str) -> &'static [&'static str] { "api-ms-win-core-interlocked-l1-1-0.dll", "api-ms-win-core-datetime-l1-1-1.dll", "api-ms-win-core-timezone-l1-1-0.dll", + "api-ms-win-core-memory-l1-1-0.dll", ], "ucrtbase.dll" => &[ "api-ms-win-crt-math-l1-1-0.dll", @@ -100,6 +78,26 @@ pub fn get_api_sets_for_canonical(canonical: &str) -> &'static [&'static str] { mod tests { use super::*; + #[test] + fn only_listed_api_sets_resolve() { + for unknown in [ + "api-ms-win-core-file-l9-9-9.dll", + "api-ms-win-core-processthreads", + "api-ms-win-core-filesomething.dll", + "api-ms-win-crt-unknown-l1-1-0.dll", + ] { + assert_eq!( + resolve_api_set_canonical(unknown), + "unknown.dll", + "{unknown}" + ); + } + assert_eq!( + resolve_api_set_canonical("API-MS-Win-Core-Memory-L1-1-0.DLL"), + "kernel32.dll" + ); + } + #[test] fn test_api_set_resolution() { assert_eq!( diff --git a/crates/import-gen/src/bin/xenora-runtime-gen.rs b/crates/import-gen/src/bin/xenora-runtime-gen.rs new file mode 100644 index 0000000..74b74e3 --- /dev/null +++ b/crates/import-gen/src/bin/xenora-runtime-gen.rs @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Generate the typed runtime adapters and report. Run from the repository root. +//! `--check` regenerates in memory and fails if a committed file differs. + +use std::process::ExitCode; +use xenora_import_gen::typed::{generate_report, generate_rust, parse}; + +const REGISTRY: &str = "crates/loader/runtime/services.txt"; +const TESTS: &str = "crates/loader/tests/runtime_services.rs"; +const RUST: &str = "crates/loader/src/runtime_table.rs"; +const REPORT: &str = "docs/runtime/services.md"; + +fn run() -> Result { + let mode = std::env::args().nth(1).unwrap_or_default(); + let read = |path: &str| std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}")); + let services = + parse(&read(REGISTRY)?, &read(TESTS)?).map_err(|e| format!("{REGISTRY}: {e}"))?; + let outputs = [ + (RUST, generate_rust(&services)), + (REPORT, generate_report(&services)), + ]; + for (path, text) in &outputs { + match mode.as_str() { + "generate" => std::fs::write(path, text).map_err(|e| format!("{path}: {e}"))?, + "--check" if read(path)? != *text => { + return Err(format!( + "{path} is out of date; run xenora-runtime-gen generate" + )); + } + "--check" | "validate" => {} + _ => return Err("usage: xenora-runtime-gen validate|generate|--check".into()), + } + } + Ok(format!("{} services", services.len())) +} + +fn main() -> ExitCode { + match run() { + Ok(message) => { + println!("{message}"); + ExitCode::SUCCESS + } + Err(message) => { + eprintln!("{message}"); + ExitCode::FAILURE + } + } +} diff --git a/crates/import-gen/src/codegen.rs b/crates/import-gen/src/codegen.rs index be5a3d0..21a9a8c 100644 --- a/crates/import-gen/src/codegen.rs +++ b/crates/import-gen/src/codegen.rs @@ -130,7 +130,7 @@ fn gen_crt_native_registration(module: &str, symbol: &str, libc_sym: &str, note: registry.register_with_status( "{module}", "{symbol}", ServiceStatus::Partial, // upgraded to Implemented when conformance test passes - |args: &Win64Args, _cpu: &mut CpuState, mem: &mut GuestMemory| -> Result {{ + |args: &Win64Args, cpu: &mut CpuState, mem: &mut GuestMemory| -> Result {{ {dispatch} }}, ); @@ -151,9 +151,8 @@ fn gen_crt_wrapper_registration(module: &str, symbol: &str, _libc_sym: &str, not "{module}", "{symbol}", ServiceStatus::Stub, |args: &Win64Args, _cpu: &mut CpuState, mem: &mut GuestMemory| -> Result {{ - // Safe-CRT wrapper: delegates to underlying function, ignores size argument. - // Guest memory is already bounds-checked by the caller's service dispatch. - Ok(0) // success + // Not implemented: fails explicitly instead of reporting success. + Err(ExitReason::IllegalInstruction(0xFE)) // 0xFE = Unsupported Host Service Call }}, ); "#, @@ -162,15 +161,8 @@ fn gen_crt_wrapper_registration(module: &str, symbol: &str, _libc_sym: &str, not /// Generate a registration for a runtime helper (EH frame handlers, etc.). fn gen_runtime_helper_registration(module: &str, symbol: &str, note: &str) -> String { - // Most runtime helpers either call abort or return 0 - let body = if symbol.contains("Throw") - || symbol.contains("terminate") - || symbol.contains("purecall") - { - "// C++ exception/terminate: halt guest execution.\n Err(ExitReason::Halted)" - } else { - "Ok(0)" - }; + // Not implemented: fails explicitly instead of reporting success. + let body = "Err(ExitReason::IllegalInstruction(0xFE)) // 0xFE = Unsupported Host Service Call"; format!( r#" // {note} @@ -194,7 +186,7 @@ fn gen_stubs(manifest: &Manifest) -> String { out.push_str( r#" //! Auto-generated Win32 service stubs. -//! Each stub logs its call site (module + symbol) and returns a safe default value. +//! Each stub stops the guest with an explicit unsupported-service exit. //! Do not edit manually — regenerate with `xenora imports generate`. use crate::cpu::{CpuState, ExitReason}; @@ -350,10 +342,11 @@ fn crt_dispatch_expr(symbol: &str, libc_sym: &str) -> String { "acos" | "asin" | "atan" | "cos" | "sin" | "tan" | "exp" | "log" | "log10" | "log2" | "sqrt" | "fabs" | "floor" | "ceil" | "round" | "trunc" | "exp2" => { format!( - r#"let x = f64::from_bits(args.rcx); + r#"let x = f64::from_bits(cpu.xmm[0] as u64); extern "C" {{ fn {libc_sym}(x: f64) -> f64; }} let r = unsafe {{ {libc_sym}(x) }}; - Ok(r.to_bits())"#, + cpu.xmm[0] = u128::from(r.to_bits()); + Ok(0)"#, libc_sym = libc_sym, ) } @@ -362,49 +355,54 @@ fn crt_dispatch_expr(symbol: &str, libc_sym: &str) -> String { | "log2f" | "sqrtf" | "fabsf" | "floorf" | "ceilf" | "roundf" | "truncf" | "cbrtf" | "erff" | "exp2f" => { format!( - r#"let x = f32::from_bits(args.rcx as u32); + r#"let x = f32::from_bits(cpu.xmm[0] as u32); extern "C" {{ fn {libc_sym}(x: f32) -> f32; }} let r = unsafe {{ {libc_sym}(x) }}; - Ok(r.to_bits() as u64)"#, + cpu.xmm[0] = u128::from(r.to_bits()); + Ok(0)"#, libc_sym = libc_sym, ) } // Math f64 × f64 → f64, two args "atan2" | "pow" | "fmod" | "hypot" | "fmax" | "fmin" | "copysign" => { format!( - r#"let x = f64::from_bits(args.rcx); - let y = f64::from_bits(args.rdx); + r#"let x = f64::from_bits(cpu.xmm[0] as u64); + let y = f64::from_bits(cpu.xmm[1] as u64); extern "C" {{ fn {libc_sym}(x: f64, y: f64) -> f64; }} let r = unsafe {{ {libc_sym}(x, y) }}; - Ok(r.to_bits())"#, + cpu.xmm[0] = u128::from(r.to_bits()); + Ok(0)"#, libc_sym = libc_sym, ) } // Math f32 × f32 → f32 "atan2f" | "powf" | "fmodf" | "hypotf" | "fmaxf" | "fminf" | "copysignf" => { format!( - r#"let x = f32::from_bits(args.rcx as u32); - let y = f32::from_bits(args.rdx as u32); + r#"let x = f32::from_bits(cpu.xmm[0] as u32); + let y = f32::from_bits(cpu.xmm[1] as u32); extern "C" {{ fn {libc_sym}(x: f32, y: f32) -> f32; }} let r = unsafe {{ {libc_sym}(x, y) }}; - Ok(r.to_bits() as u64)"#, + cpu.xmm[0] = u128::from(r.to_bits()); + Ok(0)"#, libc_sym = libc_sym, ) } // Math f64 × f64 × f64 → f64 (fma) - "fma" => r#"let x = f64::from_bits(args.rcx); - let y = f64::from_bits(args.rdx); - let z = f64::from_bits(args.r8); + "fma" => r#"let x = f64::from_bits(cpu.xmm[0] as u64); + let y = f64::from_bits(cpu.xmm[1] as u64); + let z = f64::from_bits(cpu.xmm[2] as u64); extern "C" { fn fma(x: f64, y: f64, z: f64) -> f64; } let r = unsafe { fma(x, y, z) }; - Ok(r.to_bits())"# + cpu.xmm[0] = u128::from(r.to_bits()); + Ok(0)"# .to_string(), - "fmaf" => r#"let x = f32::from_bits(args.rcx as u32); - let y = f32::from_bits(args.rdx as u32); - let z = f32::from_bits(args.r8 as u32); + "fmaf" => r#"let x = f32::from_bits(cpu.xmm[0] as u32); + let y = f32::from_bits(cpu.xmm[1] as u32); + let z = f32::from_bits(cpu.xmm[2] as u32); extern "C" { fn fmaf(x: f32, y: f32, z: f32) -> f32; } let r = unsafe { fmaf(x, y, z) }; - Ok(r.to_bits() as u64)"# + cpu.xmm[0] = u128::from(r.to_bits()); + Ok(0)"# .to_string(), // strlen(ptr) -> size_t "strlen" => r#"// strlen: RCX = guest pointer to null-terminated string diff --git a/crates/import-gen/src/lib.rs b/crates/import-gen/src/lib.rs index 8bfb305..4311fb3 100644 --- a/crates/import-gen/src/lib.rs +++ b/crates/import-gen/src/lib.rs @@ -31,6 +31,7 @@ pub mod ingest; pub mod manifest; pub mod metadata; pub mod parse; +pub mod typed; pub mod verify; pub use apiset::{get_api_sets_for_canonical, resolve_api_set_canonical}; diff --git a/crates/import-gen/src/typed.rs b/crates/import-gen/src/typed.rs new file mode 100644 index 0000000..1bcb1cc --- /dev/null +++ b/crates/import-gen/src/typed.rs @@ -0,0 +1,453 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Typed runtime services: parse and validate the declarative registry, and +//! generate Win64 adapters, static metadata and a coverage report. + +use crate::apiset::get_api_sets_for_canonical; +use std::collections::{BTreeMap, BTreeSet}; +use std::fmt::Write as _; + +/// Most arguments one service may declare. +const MAX_PARAMETERS: usize = 16; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Parameter { + pub name: String, + pub kind: String, +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Service { + pub library: String, + pub symbol: String, + pub parameters: Vec, + pub result: String, + pub handler: String, + pub status: String, + pub aliases: Vec, + pub failure: String, + pub reference: String, + pub tests: Vec, +} + +fn is_identifier(text: &str) -> bool { + !text.is_empty() + && !text.as_bytes()[0].is_ascii_digit() + && text.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') +} + +/// Adapter expression reading parameter `index`, or `None` for an unknown type. +fn reader(kind: &str, index: usize) -> Option { + Some(match kind { + "u32" | "i32" | "u64" | "bool32" | "f32" | "f64" => format!("call.{kind}({index})?"), + "handle" | "ptr" => format!("call.u64({index})?"), + _ => { + let size: u32 = kind.strip_prefix("out<")?.strip_suffix('>')?.parse().ok()?; + if !(1..=4096).contains(&size) { + return None; + } + format!("call.out::<{size}>({index})?") + } + }) +} + +/// Rust type of a result other than void. +fn result_type(kind: &str) -> &'static str { + match kind { + "u32" => "u32", + "i32" => "i32", + "bool32" => "bool", + "f32" => "crate::runtime::Float32", + "f64" => "crate::runtime::Float64", + _ => "u64", + } +} + +const RESULTS: [&str; 9] = [ + "void", "u32", "i32", "u64", "bool32", "handle", "ptr", "f32", "f64", +]; + +/// Parse and validate the registry. `test_source` is the text of the test file +/// that must define every named test. +pub fn parse(text: &str, test_source: &str) -> Result, String> { + let mut services: Vec = Vec::new(); + let mut seen_fields = BTreeSet::new(); + for (number, raw) in text.lines().enumerate() { + let at = |message: &str| format!("line {}: {message}", number + 1); + let line = raw.trim(); + if line.is_empty() || line.starts_with('#') { + continue; + } + let (keyword, rest) = line.split_once(' ').ok_or_else(|| at("missing value"))?; + let rest = rest.trim(); + if keyword == "service" { + services.push(parse_signature(rest).map_err(|message| at(&message))?); + seen_fields.clear(); + continue; + } + let service = services + .last_mut() + .ok_or_else(|| at("field outside a service"))?; + let repeatable = matches!(keyword, "alias" | "test"); + if !repeatable && !seen_fields.insert(keyword.to_owned()) { + return Err(at(&format!("repeated field {keyword}"))); + } + match keyword { + "handler" => service.handler = rest.to_owned(), + "status" => service.status = rest.to_owned(), + "alias" => service.aliases.push(rest.to_owned()), + "fails" => service.failure = rest.to_owned(), + "ref" => service.reference = rest.to_owned(), + "test" => service.tests.push(rest.to_owned()), + other => return Err(at(&format!("unknown field {other}"))), + } + } + validate(&services, test_source)?; + Ok(services) +} + +fn parse_signature(text: &str) -> Result { + let (library, rest) = text.split_once(' ').ok_or("missing symbol")?; + let (symbol, rest) = rest.split_once('(').ok_or("missing parameter list")?; + let (list, result) = rest.rsplit_once(") -> ").ok_or("missing result type")?; + let mut parameters = Vec::new(); + if !list.trim().is_empty() { + for parameter in list.split(',') { + let (name, kind) = parameter.split_once(':').ok_or("parameter needs a type")?; + parameters.push(Parameter { + name: name.trim().to_owned(), + kind: kind.trim().to_owned(), + }); + } + } + Ok(Service { + library: library.to_owned(), + symbol: symbol.trim().to_owned(), + parameters, + result: result.trim().to_owned(), + handler: String::new(), + status: String::new(), + aliases: Vec::new(), + failure: String::new(), + reference: String::new(), + tests: Vec::new(), + }) +} + +fn validate(services: &[Service], test_source: &str) -> Result<(), String> { + // Every key a guest could import, with the service it resolves to. + let mut keys: BTreeMap<(String, &str), usize> = BTreeMap::new(); + for (index, service) in services.iter().enumerate() { + let name = format!("{}!{}", service.library, service.symbol); + let fail = |message: String| Err(format!("{name}: {message}")); + if service.library != service.library.to_ascii_lowercase() + || !service.library.ends_with(".dll") + || service.library.starts_with("api-ms-") + { + return fail("library must be a lower-case canonical module".into()); + } + if !is_identifier(&service.symbol) { + return fail("symbol is not an identifier".into()); + } + if !is_identifier(&service.handler) { + return fail("missing or invalid handler".into()); + } + if service.parameters.len() > MAX_PARAMETERS { + return fail("too many parameters".into()); + } + let mut names = BTreeSet::new(); + for (position, parameter) in service.parameters.iter().enumerate() { + if !is_identifier(¶meter.name) || !names.insert(¶meter.name) { + return fail(format!("invalid parameter name {:?}", parameter.name)); + } + if reader(¶meter.kind, position).is_none() { + return fail(format!("unsupported parameter type {:?}", parameter.kind)); + } + } + if !RESULTS.contains(&service.result.as_str()) { + return fail(format!("unsupported result type {:?}", service.result)); + } + if !matches!(service.status.as_str(), "implemented" | "partial" | "stub") { + return fail("status must be implemented, partial or stub".into()); + } + if service.failure.is_empty() || service.reference.is_empty() { + return fail("needs a failure contract and a reference".into()); + } + if service.tests.is_empty() && service.status != "stub" { + return fail("needs a test before it may claim behaviour".into()); + } + for test in &service.tests { + if !is_identifier(test) || !test_source.contains(&format!("fn {test}()")) { + return fail(format!("test {test} does not exist")); + } + } + let documented = get_api_sets_for_canonical(&service.library); + let modules = std::iter::once(&service.library).chain(&service.aliases); + for module in modules { + if module != &service.library && !documented.contains(&module.as_str()) { + return fail(format!("{module} is not a listed API set of its library")); + } + if keys + .insert((module.clone(), &service.symbol), index) + .is_some() + { + return fail(format!("{module} already resolves this symbol")); + } + } + } + Ok(()) +} + +fn status_variant(status: &str) -> &'static str { + match status { + "implemented" => "Implemented", + "partial" => "Partial", + _ => "Stub", + } +} + +fn string_list(items: &[String]) -> String { + let quoted: Vec = items.iter().map(|item| format!("{item:?}")).collect(); + format!("&[{}]", quoted.join(", ")) +} + +/// Rust source of the adapters and metadata. +pub fn generate_rust(services: &[Service]) -> String { + let mut out = String::from( + "// SPDX-License-Identifier: GPL-3.0-or-later\n\n\ + // Generated by xenora-runtime-gen from crates/loader/runtime/services.txt.\n\ + // Do not edit.\n\n\ + use crate::imports::{ImportRegistry, ServiceStatus};\n\ + use crate::runtime::{Call, Parameter, Return, ServiceContext, ServiceMetadata};\n\ + use crate::services::{ServicesState, handlers};\n\ + use std::sync::Arc;\n\n", + ); + let _ = writeln!( + out, + "pub static SERVICES: [ServiceMetadata; {}] = [", + services.len() + ); + for service in services { + let parameters: Vec = service + .parameters + .iter() + .map(|p| format!("Parameter {{ name: {:?}, kind: {:?} }}", p.name, p.kind)) + .collect(); + let _ = writeln!( + out, + " ServiceMetadata {{\n library: {:?},\n symbol: {:?},\n \ + parameters: &[{}],\n result: {:?},\n status: ServiceStatus::{},\n \ + aliases: {},\n failure: {:?},\n reference: {:?},\n tests: {},\n }},", + service.library, + service.symbol, + parameters.join(", "), + service.result, + status_variant(&service.status), + string_list(&service.aliases), + service.failure, + service.reference, + string_list(&service.tests), + ); + } + out.push_str( + "];\n\n/// Register every generated service and its API-set aliases.\n\ + pub fn register(registry: &mut ImportRegistry, state: &Arc) {\n", + ); + for service in services { + let count = service.parameters.len(); + let names: String = (0..count).map(|index| format!(", a{index}")).collect(); + let _ = writeln!( + out, + " let s = state.clone();\n registry.register_with_status({:?}, {:?}, ServiceStatus::{}, move |args, cpu, memory| {{", + service.library, + service.symbol, + status_variant(&service.status), + ); + if count == 0 { + out.push_str(" let _ = (args, &Call::new);\n"); + } else { + out.push_str(" let call = Call::new(args, cpu, memory);\n"); + } + for (index, parameter) in service.parameters.iter().enumerate() { + let read = reader(¶meter.kind, index).unwrap_or_default(); + let _ = writeln!(out, " let a{index} = {read};"); + } + // The declared type is stated so that a handler returning another one + // does not compile. + let binding = match service.result.as_str() { + "void" => "let ()".to_owned(), + result => format!("let result: {}", result_type(result)), + }; + let place = if service.result == "void" { + "Ok(0)" + } else { + "Ok(result.place(cpu))" + }; + let cpu = if service.result == "void" && count == 0 { + " let _ = cpu;\n" + } else { + "" + }; + let _ = writeln!( + out, + "{cpu} let mut context = ServiceContext {{ state: &s, memory }};\n {binding} = handlers::{}(&mut context{names})?;\n {place}\n }});", + service.handler + ); + } + out.push_str(" for service in &SERVICES {\n for alias in service.aliases {\n if let Err(error) = registry.try_alias(alias, service.library, service.symbol) {\n panic!(\"{error}\");\n }\n }\n }\n}\n"); + out.replace( + " let _ = (args, &Call::new);\n", + " let _ = args;\n", + ) +} + +/// Coverage report. Each count is distinct; aliases are never services. +pub fn generate_report(services: &[Service]) -> String { + let count = |status: &str| services.iter().filter(|s| s.status == status).count(); + let handlers: BTreeSet<&str> = services.iter().map(|s| s.handler.as_str()).collect(); + let aliases: usize = services.iter().map(|s| s.aliases.len()).sum(); + let tested = services.iter().filter(|s| !s.tests.is_empty()).count(); + let mut out = String::from( + "# Typed runtime services\n\nGenerated by `xenora-runtime-gen` from `crates/loader/runtime/services.txt`. Do not edit.\n\n\ + A declared service is not a claim of compatibility. `implemented` and `partial` describe behaviour against the documented contract for the synthetic guest. No service has been independently accepted.\n\n\ + | Measure | Count |\n| --- | ---: |\n", + ); + for (label, value) in [ + ("Services with a declared ABI", services.len()), + ("Generated adapters", services.len()), + ("Unique handler implementations", handlers.len()), + ("Implemented", count("implemented")), + ("Partial", count("partial")), + ("Stub", count("stub")), + ("Conformance-tested through guest dispatch", tested), + ("API-set aliases (not services)", aliases), + ("Independently accepted", 0), + ] { + let _ = writeln!(out, "| {label} | {value} |"); + } + out.push_str("\n| Service | Signature | Status | Failure |\n| --- | --- | --- | --- |\n"); + for service in services { + let parameters: Vec = service + .parameters + .iter() + .map(|p| format!("{}: {}", p.name, p.kind)) + .collect(); + let _ = writeln!( + out, + "| `{}!{}` | `({}) -> {}` | {} | {} |", + service.library, + service.symbol, + parameters.join(", "), + service.result, + service.status, + service.failure + ); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + const TESTS: &str = "fn works() {}"; + + fn entry(signature: &str, extra: &str) -> String { + format!( + "service {signature}\nhandler h\nstatus partial\nfails never\nref x.h\ntest works\n{extra}\n" + ) + } + + fn rejects(text: &str, message: &str) { + let error = parse(text, TESTS).unwrap_err(); + assert!(error.contains(message), "{error}"); + } + + #[test] + fn valid_entries_parse_and_generate_deterministically() { + let text = entry( + "kernel32.dll F(a: u32, b: f64, c: out<8>) -> handle", + "alias api-ms-win-core-memory-l1-1-0.dll", + ); + let services = parse(&text, TESTS).unwrap(); + assert_eq!(services[0].parameters[2].kind, "out<8>"); + let rust = generate_rust(&services); + assert_eq!(rust, generate_rust(&services)); + for expected in ["call.u32(0)?", "call.f64(1)?", "call.out::<8>(2)?"] { + assert!(rust.contains(expected), "{expected}"); + } + assert!(generate_report(&services).contains("| Unique handler implementations | 1 |")); + } + + #[test] + fn conflicting_keys_are_rejected() { + let one = entry("kernel32.dll F() -> void", ""); + rejects(&(one.clone() + &one), "already resolves"); + let aliased = entry( + "kernel32.dll F() -> void", + "alias api-ms-win-core-memory-l1-1-0.dll", + ); + let twice = entry( + "kernel32.dll G() -> void", + "alias api-ms-win-core-memory-l1-1-0.dll\nalias api-ms-win-core-memory-l1-1-0.dll", + ); + assert!(parse(&aliased, TESTS).is_ok()); + rejects(&twice, "already resolves"); + } + + #[test] + fn unsupported_declarations_are_rejected() { + rejects( + &entry("kernel32.dll F(a: struct) -> void", ""), + "parameter type", + ); + rejects( + &entry("kernel32.dll F(a: out<0>) -> void", ""), + "parameter type", + ); + rejects( + &entry("kernel32.dll F(a: void) -> void", ""), + "parameter type", + ); + rejects(&entry("kernel32.dll F() -> out<4>", ""), "result type"); + rejects( + &entry("kernel32.dll F(a: u32, a: u32) -> void", ""), + "parameter name", + ); + rejects(&entry("Kernel32.dll F() -> void", ""), "canonical module"); + rejects( + &entry("api-ms-win-core-memory-l1-1-0.dll F() -> void", ""), + "canonical module", + ); + rejects( + &entry( + "kernel32.dll F() -> void", + "alias api-ms-win-core-made-up-l1-1-0.dll", + ), + "not a listed API set", + ); + rejects( + &entry("kernel32.dll F() -> void", "colour blue"), + "unknown field", + ); + rejects( + &entry("kernel32.dll F() -> void", "status stub"), + "repeated field", + ); + } + + #[test] + fn behaviour_needs_evidence() { + let untested = + "service kernel32.dll F() -> void\nhandler h\nstatus partial\nfails never\nref x.h\n"; + rejects(untested, "needs a test"); + rejects(&(untested.to_owned() + "test missing\n"), "does not exist"); + let stub = untested.replace("partial", "stub"); + assert!(parse(&stub, TESTS).is_ok()); + rejects( + &untested.replace("ref x.h\n", "test works\n"), + "needs a failure contract", + ); + rejects("handler h\n", "outside a service"); + } +} diff --git a/crates/loader/runtime/services.txt b/crates/loader/runtime/services.txt new file mode 100644 index 0000000..c3fd65a --- /dev/null +++ b/crates/loader/runtime/services.txt @@ -0,0 +1,181 @@ +# Typed runtime service registry. +# +# Data only. `cargo run -p xenora-import-gen --bin xenora-runtime-gen` validates +# it and writes crates/loader/src/runtime_table.rs (typed Win64 adapters and +# static metadata) and docs/runtime/services.md (coverage counts). +# +# service (: , ...) -> +# handler +# status implemented | partial | stub +# alias +# fails +# ref +# test +# +# Types: u32 i32 u64 bool32 handle ptr out f32 f64, and void as a result. +# A bool32 argument is true when nonzero. out is a guest pointer to N bytes +# the service writes. Arguments are assigned by position (Microsoft x64 calling +# convention): RCX, RDX, R8, R9 or XMM0-XMM3 for floats, then the stack. +# +# "status" describes behaviour against the documented contract. A service needs +# at least one test before it may be implemented or partial. + +service kernel32.dll SetProcessPriorityBoost(process: handle, disable: bool32) -> bool32 + handler set_process_priority_boost + status partial + alias api-ms-win-core-processthreads-l1-1-2.dll + fails 0 with ERROR_INVALID_HANDLE + ref processthreadsapi.h SetProcessPriorityBoost + test priority_boost_round_trips_and_checks_its_handle + +service kernel32.dll GetProcessPriorityBoost(process: handle, disabled: out<4>) -> bool32 + handler get_process_priority_boost + status partial + alias api-ms-win-core-processthreads-l1-1-2.dll + fails 0 with ERROR_INVALID_HANDLE or ERROR_NOACCESS + ref processthreadsapi.h GetProcessPriorityBoost + test priority_boost_round_trips_and_checks_its_handle + +service kernel32.dll GetCurrentProcess() -> handle + handler get_current_process + status implemented + alias api-ms-win-core-processthreads-l1-1-0.dll + fails never + ref processthreadsapi.h GetCurrentProcess + test identity_services_return_documented_pseudo_handles_and_ids + +service kernel32.dll GetProcessId(process: handle) -> u32 + handler get_process_id + status partial + alias api-ms-win-core-processthreads-l1-1-0.dll + fails 0 with ERROR_INVALID_HANDLE + ref processthreadsapi.h GetProcessId + test identity_services_return_documented_pseudo_handles_and_ids + +service kernel32.dll GetCurrentThread() -> handle + handler get_current_thread + status implemented + alias api-ms-win-core-processthreads-l1-1-0.dll + fails never + ref processthreadsapi.h GetCurrentThread + test identity_services_return_documented_pseudo_handles_and_ids + +service kernel32.dll GetCurrentProcessId() -> u32 + handler get_current_process_id + status implemented + alias api-ms-win-core-processthreads-l1-1-0.dll + fails never + ref processthreadsapi.h GetCurrentProcessId + test identity_services_return_documented_pseudo_handles_and_ids + +service kernel32.dll GetCurrentThreadId() -> u32 + handler get_current_thread_id + status implemented + alias api-ms-win-core-processthreads-l1-1-0.dll + fails never + ref processthreadsapi.h GetCurrentThreadId + test identity_services_return_documented_pseudo_handles_and_ids + +service kernel32.dll OpenThread(access: u32, inherit: bool32, thread: u32) -> handle + handler open_thread + status partial + alias api-ms-win-core-processthreads-l1-1-0.dll + fails 0 with ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED or ERROR_NOT_ENOUGH_MEMORY + ref processthreadsapi.h OpenThread + test thread_handles_check_access_and_are_rejected_once_closed + +service kernel32.dll GetThreadPriority(thread: handle) -> i32 + handler get_thread_priority + status partial + alias api-ms-win-core-processthreads-l1-1-0.dll + fails THREAD_PRIORITY_ERROR_RETURN with ERROR_INVALID_HANDLE or ERROR_ACCESS_DENIED + ref processthreadsapi.h GetThreadPriority + test thread_handles_check_access_and_are_rejected_once_closed + +service kernel32.dll SetThreadPriority(thread: handle, priority: i32) -> bool32 + handler set_thread_priority + status partial + alias api-ms-win-core-processthreads-l1-1-0.dll + fails 0 with ERROR_INVALID_HANDLE, ERROR_ACCESS_DENIED, ERROR_NOT_SUPPORTED or ERROR_INVALID_PARAMETER + ref processthreadsapi.h SetThreadPriority + test thread_handles_check_access_and_are_rejected_once_closed + +service kernel32.dll CloseHandle(object: handle) -> bool32 + handler close_handle + status partial + alias api-ms-win-core-handle-l1-1-0.dll + fails 0 with ERROR_INVALID_HANDLE + ref handleapi.h CloseHandle + test thread_handles_check_access_and_are_rejected_once_closed + +service kernel32.dll GetSystemTimeAsFileTime(time: out<8>) -> void + handler get_system_time_as_file_time + status implemented + alias api-ms-win-core-sysinfo-l1-1-0.dll + fails guest fault on an invalid pointer + ref sysinfoapi.h GetSystemTimeAsFileTime + test system_time_comes_from_the_injected_clock + +service kernel32.dll GetLastError() -> u32 + handler get_last_error + status partial + alias api-ms-win-core-errorhandling-l1-1-0.dll + fails never + ref errhandlingapi.h GetLastError + test last_error_is_set_by_failures_and_by_the_guest + +service kernel32.dll SetLastError(code: u32) -> void + handler set_last_error + status partial + alias api-ms-win-core-errorhandling-l1-1-0.dll + fails never + ref errhandlingapi.h SetLastError + test last_error_is_set_by_failures_and_by_the_guest + +service kernel32.dll VirtualAlloc(address: ptr, size: u64, kind: u32, protect: u32) -> ptr + handler virtual_alloc + status partial + alias api-ms-win-core-memory-l1-1-0.dll + fails 0 with ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED, ERROR_INVALID_ADDRESS or ERROR_NOT_ENOUGH_MEMORY + ref memoryapi.h VirtualAlloc + test virtual_memory_is_mapped_released_and_bounded + +service kernel32.dll VirtualFree(address: ptr, size: u64, kind: u32) -> bool32 + handler virtual_free + status partial + alias api-ms-win-core-memory-l1-1-0.dll + fails 0 with ERROR_NOT_SUPPORTED, ERROR_INVALID_PARAMETER or ERROR_INVALID_ADDRESS + ref memoryapi.h VirtualFree + test virtual_memory_is_mapped_released_and_bounded + +service ucrtbase.dll sqrt(x: f64) -> f64 + handler sqrt + status partial + alias api-ms-win-crt-math-l1-1-0.dll + fails NaN for a negative argument; errno is not set + ref math.h sqrt (ISO C, IEC 60559 squareRoot) + test floating_arguments_and_results_use_xmm_registers + +service ucrtbase.dll sqrtf(x: f32) -> f32 + handler sqrtf + status partial + alias api-ms-win-crt-math-l1-1-0.dll + fails NaN for a negative argument; errno is not set + ref math.h sqrtf (ISO C, IEC 60559 squareRoot) + test floating_arguments_and_results_use_xmm_registers + +service ucrtbase.dll fabs(x: f64) -> f64 + handler fabs + status implemented + alias api-ms-win-crt-math-l1-1-0.dll + fails never + ref math.h fabs (ISO C, IEC 60559 abs) + test floating_arguments_and_results_use_xmm_registers + +service ucrtbase.dll fabsf(x: f32) -> f32 + handler fabsf + status implemented + alias api-ms-win-crt-math-l1-1-0.dll + fails never + ref math.h fabsf (ISO C, IEC 60559 abs) + test floating_arguments_and_results_use_xmm_registers diff --git a/crates/loader/src/cpu.rs b/crates/loader/src/cpu.rs index 6538ec0..92c9cf6 100644 --- a/crates/loader/src/cpu.rs +++ b/crates/loader/src/cpu.rs @@ -139,6 +139,8 @@ pub enum ExitReason { GeneralProtection, /// An unmasked SSE floating-point exception (#XM); MXCSR holds its flags. SimdException, + /// A host service changed a register the Win64 ABI requires it to preserve. + ServiceAbiViolation, } impl fmt::Display for ExitReason { @@ -154,6 +156,9 @@ 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::ServiceAbiViolation => { + write!(f, "host service changed a nonvolatile guest register") + } } } } diff --git a/crates/loader/src/import_table.rs b/crates/loader/src/import_table.rs new file mode 100644 index 0000000..bcab819 --- /dev/null +++ b/crates/loader/src/import_table.rs @@ -0,0 +1,218 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Bounded parser for the PE32+ import directory (Microsoft PE format, +//! "The .idata Section"). Binding and static inspection both use it, so they +//! agree on which imports an image has and how they are named. + +use std::fmt; + +/// Most import descriptors accepted in one image. +pub const MAX_DESCRIPTORS: usize = 1024; +/// Most imported symbols accepted in one image. +pub const MAX_IMPORTS: usize = 65_536; +/// Longest module or symbol name accepted, in bytes. +pub const MAX_NAME_LEN: usize = 4096; + +const DESCRIPTOR_LEN: u32 = 20; +const ORDINAL_FLAG: u64 = 1 << 63; + +/// How an import names its target. A symbol that happens to be spelled like an +/// ordinal is still a name. +#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum ImportName { + Name(String), + Ordinal(u16), +} + +impl fmt::Display for ImportName { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Name(name) => f.write_str(name), + Self::Ordinal(ordinal) => write!(f, "Ordinal#{ordinal}"), + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ImportEntry { + /// Module name as spelled in the image. + pub module: String, + pub name: ImportName, + /// RVA of the import address table slot. + pub iat_rva: u32, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ImportTableError { + /// A structure at this RVA is not fully backed by section data. + OutOfBounds { + rva: u32, + }, + /// A name is empty, unterminated, too long or not printable ASCII. + MalformedName { + rva: u32, + }, + /// A lookup entry at this RVA sets reserved bits. + ReservedBits { + rva: u32, + }, + TooManyDescriptors, + TooManyImports, +} + +impl fmt::Display for ImportTableError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::OutOfBounds { rva } => write!(f, "import data at RVA 0x{rva:08x} is truncated"), + Self::MalformedName { rva } => write!(f, "malformed import name at RVA 0x{rva:08x}"), + Self::ReservedBits { rva } => { + write!( + f, + "reserved bits set in the import lookup at RVA 0x{rva:08x}" + ) + } + Self::TooManyDescriptors => write!(f, "more than {MAX_DESCRIPTORS} import descriptors"), + Self::TooManyImports => write!(f, "more than {MAX_IMPORTS} imported symbols"), + } + } +} + +impl std::error::Error for ImportTableError {} + +/// Reads image bytes by RVA, requiring every byte to be backed by the file. +struct Reader<'a, F> { + bytes: &'a [u8], + rva_to_offset: F, +} + +impl Option> Reader<'_, F> { + fn byte(&self, rva: u32) -> Option { + self.bytes.get((self.rva_to_offset)(rva)?).copied() + } + + fn array(&self, rva: u32) -> Result<[u8; N], ImportTableError> { + let mut out = [0; N]; + for (index, byte) in out.iter_mut().enumerate() { + *byte = rva + .checked_add(index as u32) + .and_then(|rva| self.byte(rva)) + .ok_or(ImportTableError::OutOfBounds { rva })?; + } + Ok(out) + } + + fn u32(&self, rva: u32) -> Result { + self.array(rva).map(u32::from_le_bytes) + } + + fn name(&self, rva: u32) -> Result { + let malformed = ImportTableError::MalformedName { rva }; + let mut name = String::new(); + for index in 0..=MAX_NAME_LEN as u32 { + let byte = rva + .checked_add(index) + .and_then(|rva| self.byte(rva)) + .ok_or(malformed)?; + match byte { + 0 if name.is_empty() => return Err(malformed), + 0 => return Ok(name), + 0x21..=0x7E => name.push(char::from(byte)), + _ => return Err(malformed), + } + } + Err(malformed) + } +} + +/// Parse the import directory at `directory_rva`. +/// +/// Returns every import before the first problem, and the problem. Callers that +/// execute an image must refuse it if there is one; inspection may report both. +pub fn parse_imports( + bytes: &[u8], + directory_rva: u32, + rva_to_offset: impl Fn(u32) -> Option, +) -> (Vec, Option) { + let reader = Reader { + bytes, + rva_to_offset, + }; + let mut entries = Vec::new(); + let error = collect(&reader, directory_rva, &mut entries).err(); + (entries, error) +} + +fn collect Option>( + reader: &Reader<'_, F>, + directory_rva: u32, + entries: &mut Vec, +) -> Result<(), ImportTableError> { + let mut descriptor = directory_rva; + for _ in 0..MAX_DESCRIPTORS { + // Reading the whole descriptor also proves its field RVAs do not overflow. + reader.array::<{ DESCRIPTOR_LEN as usize }>(descriptor)?; + let lookup_rva = reader.u32(descriptor)?; + let name_rva = reader.u32(descriptor + 12)?; + let address_rva = reader.u32(descriptor + 16)?; + // The table ends with an empty descriptor. + if lookup_rva == 0 && name_rva == 0 && address_rva == 0 { + return Ok(()); + } + let module = reader.name(name_rva)?; + collect_symbols(reader, &module, lookup_rva, address_rva, entries)?; + descriptor = descriptor + .checked_add(DESCRIPTOR_LEN) + .ok_or(ImportTableError::OutOfBounds { rva: descriptor })?; + } + Err(ImportTableError::TooManyDescriptors) +} + +fn collect_symbols Option>( + reader: &Reader<'_, F>, + module: &str, + lookup_rva: u32, + address_rva: u32, + entries: &mut Vec, +) -> Result<(), ImportTableError> { + // Without a lookup table the address table holds the same entries on disk. + let start = if lookup_rva != 0 { + lookup_rva + } else { + address_rva + }; + for index in 0.. { + let at = |base: u32| { + base.checked_add(index * 8) + .ok_or(ImportTableError::OutOfBounds { rva: base }) + }; + let lookup = at(start)?; + let value = u64::from_le_bytes(reader.array(lookup)?); + if value == 0 { + return Ok(()); + } + if entries.len() == MAX_IMPORTS { + return Err(ImportTableError::TooManyImports); + } + let iat_rva = at(address_rva)?; + let name = if value & ORDINAL_FLAG != 0 { + let ordinal = value & !ORDINAL_FLAG; + ImportName::Ordinal( + u16::try_from(ordinal) + .map_err(|_| ImportTableError::ReservedBits { rva: lookup })?, + ) + } else { + let hint = u32::try_from(value) + .ok() + .filter(|rva| rva >> 31 == 0) + .ok_or(ImportTableError::ReservedBits { rva: lookup })?; + // The name follows a two-byte export-table hint. + ImportName::Name(reader.name(hint + 2)?) + }; + entries.push(ImportEntry { + module: module.to_owned(), + name, + iat_rva, + }); + } + Ok(()) +} diff --git a/crates/loader/src/imports.rs b/crates/loader/src/imports.rs index f0d47b7..df94c3e 100644 --- a/crates/loader/src/imports.rs +++ b/crates/loader/src/imports.rs @@ -7,6 +7,7 @@ //! guest services without exposing raw host function pointers. use crate::cpu::{CpuState, ExitReason, Register}; +use crate::import_table::{ImportName, ImportTableError, MAX_NAME_LEN, parse_imports}; use crate::memory::{GuestMemory, MemoryError}; use crate::pe::ParsedPe; use std::collections::HashMap; @@ -19,8 +20,7 @@ pub const IMPORT_TRAMPOLINE_STRIDE: u64 = 16; /// Typed error resulting from import resolution or service dispatch. #[derive(Clone, Debug, PartialEq, Eq)] pub enum ImportError { - MalformedDirectory, - DirectoryOutOfBounds { rva: u32 }, + Table(ImportTableError), UnresolvedImport { module: String, symbol: String }, Memory(MemoryError), } @@ -28,10 +28,7 @@ pub enum ImportError { impl fmt::Display for ImportError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Self::MalformedDirectory => write!(f, "malformed PE import directory"), - Self::DirectoryOutOfBounds { rva } => { - write!(f, "import directory at RVA 0x{rva:08x} is out of bounds") - } + Self::Table(e) => write!(f, "malformed PE imports: {e}"), Self::UnresolvedImport { module, symbol } => { write!(f, "unresolved import dependency: {module}!{symbol}") } @@ -42,6 +39,38 @@ impl fmt::Display for ImportError { impl std::error::Error for ImportError {} +/// Why a service could not be added to the registry. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum RegistryError { + /// The key already names a different service. + Duplicate { + module: String, + symbol: String, + }, + /// An alias names a service that does not exist. + UnknownTarget { + module: String, + symbol: String, + }, + InvalidName { + module: String, + symbol: String, + }, +} + +impl fmt::Display for RegistryError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let (problem, module, symbol) = match self { + Self::Duplicate { module, symbol } => ("is already registered", module, symbol), + Self::UnknownTarget { module, symbol } => ("is not registered", module, symbol), + Self::InvalidName { module, symbol } => ("is not a valid name", module, symbol), + }; + write!(f, "import {module}!{symbol} {problem}") + } +} + +impl std::error::Error for RegistryError {} + impl From for ImportError { fn from(e: MemoryError) -> Self { Self::Memory(e) @@ -128,7 +157,8 @@ pub struct ServiceDescriptor { /// Registry for resolving and binding import symbols to guest trampoline VAs. pub struct ImportRegistry { - services: HashMap<(String, String), usize>, // (module_lowercase, symbol) -> service_index + // (lower-case module, name) -> service index. Symbol names keep their case. + services: HashMap<(String, ImportName), usize>, handlers: Vec, trampoline_to_service: HashMap, // Trampoline VA -> service_index } @@ -148,18 +178,82 @@ impl ImportRegistry { } } - fn service_index(&self, module: &str, symbol: &str) -> Option { + /// The one lookup used by binding, inspection and reports. Module names + /// compare without case, as Windows does; symbol names are exact. API sets + /// resolve only through registered aliases. + pub fn resolve(&self, module: &str, name: &ImportName) -> Option<&ServiceDescriptor> { + self.index(module, name).map(|index| &self.handlers[index]) + } + + fn index(&self, module: &str, name: &ImportName) -> Option { self.services - .get(&(module.to_ascii_lowercase(), symbol.to_owned())) + .get(&(module.to_ascii_lowercase(), name.clone())) .copied() } + fn service_index(&self, module: &str, symbol: &str) -> Option { + self.index(module, &ImportName::Name(symbol.to_owned())) + } + + fn check_key(module: &str, name: &ImportName) -> Result<(), RegistryError> { + let printable = |text: &str| { + !text.is_empty() + && text.len() <= MAX_NAME_LEN + && text.bytes().all(|b| b.is_ascii_graphic()) + }; + let valid = printable(module) + && match name { + ImportName::Name(symbol) => printable(symbol), + ImportName::Ordinal(_) => true, + }; + if valid { + Ok(()) + } else { + Err(RegistryError::InvalidName { + module: module.to_owned(), + symbol: name.to_string(), + }) + } + } + /// Check whether the exact import key has a binding, including stub handlers. pub fn has_binding(&self, module: &str, symbol: &str) -> bool { self.service_index(module, symbol).is_some() } - /// Register a host-provided guest service. + /// Register a host-provided guest service under a name or an ordinal. + pub fn try_register( + &mut self, + module: &str, + name: ImportName, + status: ServiceStatus, + handler: ServiceHandler, + ) -> Result<(), RegistryError> { + Self::check_key(module, &name)?; + let key = (module.to_ascii_lowercase(), name); + if self.services.contains_key(&key) { + return Err(RegistryError::Duplicate { + module: key.0, + symbol: key.1.to_string(), + }); + } + let index = self.handlers.len(); + self.handlers.push(ServiceDescriptor { + module: key.0.clone(), + symbol: key.1.to_string(), + handler, + status, + }); + self.services.insert(key, index); + Ok(()) + } + + /// Register a named service. + /// + /// # Panics + /// + /// If the name is invalid or already registered, so that one host module + /// cannot silently replace another's service. pub fn register(&mut self, module: &str, symbol: &str, handler: F) where F: Fn(&Win64Args, &mut CpuState, &mut GuestMemory) -> Result @@ -167,16 +261,7 @@ impl ImportRegistry { + Sync + 'static, { - let mod_key = module.to_ascii_lowercase(); - let sym_key = symbol.to_string(); - let index = self.handlers.len(); - self.handlers.push(ServiceDescriptor { - module: mod_key.clone(), - symbol: sym_key.clone(), - handler: Box::new(handler), - status: ServiceStatus::Implemented, - }); - self.services.insert((mod_key, sym_key), index); + self.register_with_status(module, symbol, ServiceStatus::Implemented, handler); } /// Describe the canonical binding behind an import without calling it. @@ -200,7 +285,10 @@ impl ImportRegistry { pub fn iter_aliases(&self) -> impl Iterator { // `services` maps (module_lc, symbol) -> handler_index. // An alias exists when module_lc != handlers[index].module.to_lowercase(). - self.services.iter().filter_map(|((mod_lc, sym), &idx)| { + self.services.iter().filter_map(|((mod_lc, name), &idx)| { + let ImportName::Name(sym) = name else { + return None; + }; let canonical_mod = self.handlers[idx].module.to_ascii_lowercase(); if *mod_lc != canonical_mod { Some(( @@ -221,7 +309,11 @@ impl ImportRegistry { self.handlers[index].status = status; } - /// Register a service with an explicit implementation status. + /// Register a named service with an explicit implementation status. + /// + /// # Panics + /// + /// As [`Self::register`]. pub fn register_with_status( &mut self, module: &str, @@ -234,17 +326,40 @@ impl ImportRegistry { + Sync + 'static, { - self.register(module, symbol, handler); - self.set_status(module, symbol, status); + let name = ImportName::Name(symbol.to_owned()); + if let Err(error) = self.try_register(module, name, status, Box::new(handler)) { + panic!("{error}"); + } } - /// Point an API-set import at an existing handler and its trampoline. - pub(crate) fn alias(&mut self, module: &str, target: &str, symbol: &str) { + /// Make `module` resolve `symbol` to the service registered as + /// `target!symbol`, sharing its trampoline. + pub fn try_alias( + &mut self, + module: &str, + target: &str, + symbol: &str, + ) -> Result<(), RegistryError> { + let name = ImportName::Name(symbol.to_owned()); + Self::check_key(module, &name)?; let index = self - .service_index(target, symbol) - .expect("registered alias target"); - self.services - .insert((module.to_ascii_lowercase(), symbol.to_owned()), index); + .index(target, &name) + .ok_or_else(|| RegistryError::UnknownTarget { + module: target.to_owned(), + symbol: symbol.to_owned(), + })?; + let previous = *self + .services + .entry((module.to_ascii_lowercase(), name)) + .or_insert(index); + if previous == index { + Ok(()) + } else { + Err(RegistryError::Duplicate { + module: module.to_owned(), + symbol: symbol.to_owned(), + }) + } } /// Bind the PE's Import Address Table (IAT) in guest memory to synthetic trampoline VAs. @@ -255,103 +370,37 @@ impl ImportRegistry { loaded_base: u64, memory: &mut GuestMemory, ) -> Result { - let import_dir = find_import_directory(bytes)?; - let Some((import_rva, import_size)) = import_dir else { + let Some(directory) = find_import_directory(bytes) else { return Ok(0); }; - if import_size == 0 { - return Ok(0); + let (entries, error) = parse_imports(bytes, directory, |rva| pe.rva_to_file_offset(rva)); + if let Some(error) = error { + return Err(ImportError::Table(error)); } - let mut desc_file_off = pe - .rva_to_file_offset(import_rva) - .ok_or(ImportError::DirectoryOutOfBounds { rva: import_rva })?; - - let mut bound_count = 0; - - while desc_file_off + 20 <= bytes.len() { - let oft = - u32::from_le_bytes(bytes[desc_file_off..desc_file_off + 4].try_into().unwrap()); - let name_rva = u32::from_le_bytes( - bytes[desc_file_off + 12..desc_file_off + 16] - .try_into() - .unwrap(), - ); - let ft = u32::from_le_bytes( - bytes[desc_file_off + 16..desc_file_off + 20] - .try_into() - .unwrap(), - ); - - if oft == 0 && name_rva == 0 && ft == 0 { - break; - } - desc_file_off += 20; - - let mod_name = if let Some(no) = pe.rva_to_file_offset(name_rva) { - let mut end = no; - while end < bytes.len() && bytes[end] != 0 { - end += 1; - } - String::from_utf8_lossy(&bytes[no..end]).into_owned() - } else { - "UNKNOWN.dll".to_string() + // Resolve everything first: a refused image must leave memory unbound. + let mut slots = Vec::with_capacity(entries.len()); + for entry in entries { + let Some(index) = self.index(&entry.module, &entry.name) else { + return Err(ImportError::UnresolvedImport { + module: entry.module, + symbol: entry.name.to_string(), + }); }; - - let thunk_rva = if oft != 0 { oft } else { ft }; - let iat_base_rva = ft; - - let Some(mut thunk_off) = pe.rva_to_file_offset(thunk_rva) else { - continue; - }; - - let mut idx = 0u32; - while thunk_off + 8 <= bytes.len() { - let val = u64::from_le_bytes(bytes[thunk_off..thunk_off + 8].try_into().unwrap()); - if val == 0 { - break; - } - thunk_off += 8; - let iat_rva = iat_base_rva + idx * 8; - idx += 1; - - let sym_name = if (val & (1 << 63)) != 0 { - format!("Ordinal#{}", val & 0xFFFF) - } else { - let hint_rva = (val & 0x7FFF_FFFF) as u32; - if let Some(ho) = pe.rva_to_file_offset(hint_rva) { - let str_start = ho + 2; - let mut str_end = str_start; - while str_end < bytes.len() && bytes[str_end] != 0 { - str_end += 1; - } - String::from_utf8_lossy(&bytes[str_start..str_end]).into_owned() - } else { - "UNKNOWN_SYM".to_string() - } - }; - - let Some(service_idx) = self.service_index(&mod_name, &sym_name) else { - return Err(ImportError::UnresolvedImport { - module: mod_name, - symbol: sym_name, - }); - }; - - // Assign a deterministic synthetic trampoline VA - let trampoline_va = - IMPORT_TRAMPOLINE_BASE_VA + (service_idx as u64) * IMPORT_TRAMPOLINE_STRIDE; - self.trampoline_to_service - .insert(trampoline_va, service_idx); - - // Write trampoline_va into guest IAT entry at (loaded_base + iat_rva) - let iat_va = loaded_base + iat_rva as u64; - memory.write_u64_bypass(iat_va, trampoline_va)?; - bound_count += 1; - } + let address = loaded_base + .checked_add(u64::from(entry.iat_rva)) + .ok_or(MemoryError::Overflow)?; + // The loader writes slots regardless of page permissions, so only + // mapping is checked here. + memory.read_u64_bypass(address)?; + slots.push((address, index)); } - - Ok(bound_count) + for &(address, index) in &slots { + let trampoline = IMPORT_TRAMPOLINE_BASE_VA + (index as u64) * IMPORT_TRAMPOLINE_STRIDE; + memory.write_u64_bypass(address, trampoline)?; + self.trampoline_to_service.insert(trampoline, index); + } + Ok(slots.len()) } /// Check if target RIP matches a synthetic service trampoline. @@ -373,60 +422,58 @@ impl ImportRegistry { let descriptor = &self.handlers[service_idx]; - // 1. Extract arguments according to Win64 convention - let args = Win64Args::new(cpu); - - // 2. Execute service handler - let ret_val = (descriptor.handler)(&args, cpu, memory)?; - - // 3. Store return value into RAX - cpu.set(Register::Rax, ret_val); - - // 4. Emulate RET instruction: pop return address from guest stack into RIP + // Read the return address first, so a call that cannot return has no effect. let rsp = cpu.get(Register::Rsp); let ret_addr = memory.read_u64(rsp).map_err(ExitReason::MemoryFault)?; - cpu.set(Register::Rsp, rsp + 8); - cpu.rip = ret_addr; + let after = rsp + .checked_add(8) + .ok_or(ExitReason::MemoryFault(MemoryError::Overflow))?; + let args = Win64Args::new(cpu); + let preserved = Nonvolatile::of(cpu); + let value = (descriptor.handler)(&args, cpu, memory)?; + if Nonvolatile::of(cpu) != preserved { + return Err(ExitReason::ServiceAbiViolation); + } + + cpu.set(Register::Rax, value); + cpu.set(Register::Rsp, after); + cpu.rip = ret_addr; Ok(()) } } -fn find_import_directory(bytes: &[u8]) -> Result, ImportError> { - if bytes.len() < 0x40 { - return Ok(None); - } - let e_lfanew = u32::from_le_bytes(bytes[0x3C..0x40].try_into().unwrap()) as usize; - let opt_offset = e_lfanew + 24; - let coff_offset = e_lfanew + 4; - if bytes.len() < coff_offset + 18 { - return Ok(None); - } - let size_of_opt = u16::from_le_bytes( - bytes[coff_offset + 16..coff_offset + 18] - .try_into() - .unwrap(), - ) as usize; +/// Registers a Win64 callee must preserve (Microsoft x64 calling convention). +#[derive(PartialEq, Eq)] +struct Nonvolatile { + gpr: [u64; 9], + xmm: [u128; 10], +} - // Import directory is directory index 1 (offset 112 + 1 * 8 = 120 in Optional Header) - if size_of_opt < 128 || bytes.len() < opt_offset + 128 { - return Ok(None); - } - - let import_rva = u32::from_le_bytes( - bytes[opt_offset + 120..opt_offset + 124] - .try_into() - .unwrap(), - ); - let import_size = u32::from_le_bytes( - bytes[opt_offset + 124..opt_offset + 128] - .try_into() - .unwrap(), - ); - - if import_rva == 0 || import_size == 0 { - Ok(None) - } else { - Ok(Some((import_rva, import_size))) +impl Nonvolatile { + fn of(cpu: &CpuState) -> Self { + use Register::{R12, R13, R14, R15, Rbp, Rbx, Rdi, Rsi, Rsp}; + let mut xmm = [0; 10]; + xmm.copy_from_slice(&cpu.xmm[6..]); + Self { + gpr: [Rbx, Rbp, Rdi, Rsi, Rsp, R12, R13, R14, R15].map(|register| cpu.get(register)), + xmm, + } } } + +/// RVA of the import directory, if the image has one. +pub(crate) fn find_import_directory(bytes: &[u8]) -> Option { + let field = |offset: usize, len: usize| bytes.get(offset..offset.checked_add(len)?); + let u32_at = |offset| Some(u32::from_le_bytes(field(offset, 4)?.try_into().ok()?)); + let coff = (u32_at(0x3C)? as usize).checked_add(4)?; + let optional = coff.checked_add(20)?; + let optional_len = u16::from_le_bytes(field(coff + 16, 2)?.try_into().ok()?); + // The import directory is data directory 1, at offset 120. + if optional_len < 128 { + return None; + } + let rva = u32_at(optional.checked_add(120)?)?; + let size = u32_at(optional.checked_add(124)?)?; + (rva != 0 && size != 0).then_some(rva) +} diff --git a/crates/loader/src/lib.rs b/crates/loader/src/lib.rs index 0469dc9..6449b9c 100644 --- a/crates/loader/src/lib.rs +++ b/crates/loader/src/lib.rs @@ -9,12 +9,16 @@ pub mod arm64; pub mod cpu; pub mod dbt; pub mod graphics; +pub mod import_table; pub mod imports; pub mod jit; pub mod memory; pub mod pe; pub mod probe; pub mod reloc; +pub mod runtime; +#[rustfmt::skip] +pub mod runtime_table; pub mod services; pub mod softfloat; pub mod startup; diff --git a/crates/loader/src/probe.rs b/crates/loader/src/probe.rs index 8bdf510..b373cb0 100644 --- a/crates/loader/src/probe.rs +++ b/crates/loader/src/probe.rs @@ -11,6 +11,7 @@ //! startup blockers. use crate::dbt::{is_native, is_translatable}; +use crate::import_table::{ImportTableError, parse_imports}; use crate::imports::{ImportRegistry, ServiceStatus}; use crate::memory::MemoryPermissions; use crate::pe::{IMAGE_FILE_MACHINE_AMD64, PE32_PLUS_MAGIC, ParsedPe, PeError, PeSection}; @@ -671,7 +672,10 @@ pub struct ProbeReport { pub parsed: ParsedPe, pub relocations: RelocationCensus, pub tls: TlsCensus, + /// Imports before the first malformed entry, if any. pub imports: Vec, + /// Why the import table could not be read to its end. + pub import_error: Option, pub instruction_records: Vec, pub first_unsupported_dbt_insn: Option, } @@ -945,76 +949,33 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result = entries + .into_iter() + .map(|entry| { + let binding = registry.resolve(&entry.module, &entry.name); + ImportedSymbol { + category: ProbeReport::categorize_dll(&entry.module), + dll: entry.module, + symbol: entry.name.to_string(), + iat_rva: entry.iat_rva, + is_supported: binding.is_some(), + service_status: binding.map(|service| service.status), + canonical_module: binding.map(|service| service.module.clone()), } - desc_off += 20; - - let dll_name = if let Some(no) = rva_to_offset(name_rva) { - let mut end = no; - while end < bytes.len() && bytes[end] != 0 { - end += 1; - } - String::from_utf8_lossy(&bytes[no..end]).into_owned() - } else { - "UNKNOWN.dll".to_string() - }; - - let category = ProbeReport::categorize_dll(&dll_name); - let thunk_rva = if oft != 0 { oft } else { ft }; - let iat_base_rva = ft; - - if let Some(mut thunk_off) = rva_to_offset(thunk_rva) { - let mut idx = 0u32; - while thunk_off + 8 <= bytes.len() { - let val = - u64::from_le_bytes(bytes[thunk_off..thunk_off + 8].try_into().unwrap()); - if val == 0 { - break; - } - thunk_off += 8; - let iat_rva = iat_base_rva + idx * 8; - idx += 1; - - let sym_name = if (val & (1 << 63)) != 0 { - format!("Ordinal#{}", val & 0xFFFF) - } else { - let hint_rva = (val & 0x7FFF_FFFF) as u32; - if let Some(ho) = rva_to_offset(hint_rva) { - let str_start = ho + 2; - let mut str_end = str_start; - while str_end < bytes.len() && bytes[str_end] != 0 { - str_end += 1; - } - String::from_utf8_lossy(&bytes[str_start..str_end]).into_owned() - } else { - "UNKNOWN_SYM".to_string() - } - }; - - let binding = registry.binding(&dll_name, &sym_name); - imports.push(ImportedSymbol { - dll: dll_name.clone(), - symbol: sym_name, - iat_rva, - category, - is_supported: binding.is_some(), - service_status: binding.map(|service| service.status), - canonical_module: binding.map(|service| service.module.clone()), - }); - } - } - } - } + }) + .collect(); // 4. Control-Flow-Aware Static Disassembly // @@ -1149,6 +1110,7 @@ pub fn probe_pe_bytes(bytes: &[u8], config: &ProbeConfig) -> Result>( "- **Unresolved standard import thunks**: `{missing}`. See `missing_imports.csv`. A registered handler may be a stub.\n" ); + if let Some(error) = &report.import_error { + let _ = writeln!( + md, + "- **Import table is malformed**: {error}. Only the imports before it are listed, and binding refuses the image.\n" + ); + } if trusted_runner_slots > 0 { let _ = writeln!( md, diff --git a/crates/loader/src/runtime.rs b/crates/loader/src/runtime.rs new file mode 100644 index 0000000..0ca0b26 --- /dev/null +++ b/crates/loader/src/runtime.rs @@ -0,0 +1,155 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Typed Win64 adapters for generated service registrations. +//! +//! `runtime_table.rs` is generated from `runtime/services.txt`. Each adapter +//! reads typed arguments by position (Microsoft x64 calling convention), calls a +//! handler that sees only guest memory and service state, and places the typed +//! result. Handlers never receive the CPU, so they cannot disturb nonvolatile +//! registers. + +use crate::cpu::{CpuState, ExitReason}; +use crate::imports::{ServiceStatus, Win64Args}; +use crate::memory::{GuestMemory, MemoryError}; +use crate::services::ServicesState; + +/// What a service may use. +pub struct ServiceContext<'a> { + pub state: &'a ServicesState, + pub memory: &'a mut GuestMemory, +} + +/// Guest pointer to `N` bytes the service writes. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct OutPtr(pub u64); + +impl OutPtr { + /// Checked, all-or-nothing store. + pub fn store(self, memory: &mut GuestMemory, bytes: [u8; N]) -> Result<(), MemoryError> { + memory.write_bytes(self.0, &bytes) + } +} + +/// Raw bits of a floating-point argument or result. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Float32(pub u32); + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Float64(pub u64); + +/// Reads typed arguments. Only the low bits of a narrow argument are defined. +pub struct Call<'a> { + args: &'a Win64Args, + cpu: &'a CpuState, + memory: &'a GuestMemory, +} + +impl<'a> Call<'a> { + pub fn new(args: &'a Win64Args, cpu: &'a CpuState, memory: &'a GuestMemory) -> Self { + Self { args, cpu, memory } + } + + pub fn u64(&self, index: usize) -> Result { + self.args + .get(index, self.memory) + .map_err(ExitReason::MemoryFault) + } + + pub fn u32(&self, index: usize) -> Result { + Ok(self.u64(index)? as u32) + } + + pub fn i32(&self, index: usize) -> Result { + Ok(self.u32(index)? as i32) + } + + pub fn bool32(&self, index: usize) -> Result { + Ok(self.u32(index)? != 0) + } + + pub fn out(&self, index: usize) -> Result, ExitReason> { + self.u64(index).map(OutPtr) + } + + /// The first four positions use XMM0-XMM3; later ones use the stack. + fn float_bits(&self, index: usize) -> Result { + if index < 4 { + Ok(self.cpu.xmm[index] as u64) + } else { + self.u64(index) + } + } + + pub fn f32(&self, index: usize) -> Result { + Ok(Float32(self.float_bits(index)? as u32)) + } + + pub fn f64(&self, index: usize) -> Result { + self.float_bits(index).map(Float64) + } +} + +/// Places a typed result and returns the value for RAX. +pub trait Return { + fn place(self, cpu: &mut CpuState) -> u64; +} + +impl Return for u32 { + fn place(self, _: &mut CpuState) -> u64 { + u64::from(self) + } +} + +impl Return for i32 { + fn place(self, _: &mut CpuState) -> u64 { + u64::from(self as u32) + } +} + +impl Return for u64 { + fn place(self, _: &mut CpuState) -> u64 { + self + } +} + +impl Return for bool { + fn place(self, _: &mut CpuState) -> u64 { + u64::from(self) + } +} + +impl Return for Float32 { + fn place(self, cpu: &mut CpuState) -> u64 { + cpu.xmm[0] = u128::from(self.0); + 0 + } +} + +impl Return for Float64 { + fn place(self, cpu: &mut CpuState) -> u64 { + cpu.xmm[0] = u128::from(self.0); + 0 + } +} + +/// A declared parameter. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Parameter { + pub name: &'static str, + pub kind: &'static str, +} + +/// Static description of a generated service. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ServiceMetadata { + pub library: &'static str, + pub symbol: &'static str, + pub parameters: &'static [Parameter], + pub result: &'static str, + pub status: ServiceStatus, + /// API sets that resolve to this service. + pub aliases: &'static [&'static str], + pub failure: &'static str, + pub reference: &'static str, + pub tests: &'static [&'static str], +} diff --git a/crates/loader/src/runtime_table.rs b/crates/loader/src/runtime_table.rs new file mode 100644 index 0000000..4938444 --- /dev/null +++ b/crates/loader/src/runtime_table.rs @@ -0,0 +1,408 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +// Generated by xenora-runtime-gen from crates/loader/runtime/services.txt. +// Do not edit. + +use crate::imports::{ImportRegistry, ServiceStatus}; +use crate::runtime::{Call, Parameter, Return, ServiceContext, ServiceMetadata}; +use crate::services::{ServicesState, handlers}; +use std::sync::Arc; + +pub static SERVICES: [ServiceMetadata; 20] = [ + ServiceMetadata { + library: "kernel32.dll", + symbol: "SetProcessPriorityBoost", + parameters: &[Parameter { name: "process", kind: "handle" }, Parameter { name: "disable", kind: "bool32" }], + result: "bool32", + status: ServiceStatus::Partial, + aliases: &["api-ms-win-core-processthreads-l1-1-2.dll"], + failure: "0 with ERROR_INVALID_HANDLE", + reference: "processthreadsapi.h SetProcessPriorityBoost", + tests: &["priority_boost_round_trips_and_checks_its_handle"], + }, + ServiceMetadata { + library: "kernel32.dll", + symbol: "GetProcessPriorityBoost", + parameters: &[Parameter { name: "process", kind: "handle" }, Parameter { name: "disabled", kind: "out<4>" }], + result: "bool32", + status: ServiceStatus::Partial, + aliases: &["api-ms-win-core-processthreads-l1-1-2.dll"], + failure: "0 with ERROR_INVALID_HANDLE or ERROR_NOACCESS", + reference: "processthreadsapi.h GetProcessPriorityBoost", + tests: &["priority_boost_round_trips_and_checks_its_handle"], + }, + ServiceMetadata { + library: "kernel32.dll", + symbol: "GetCurrentProcess", + parameters: &[], + result: "handle", + status: ServiceStatus::Implemented, + aliases: &["api-ms-win-core-processthreads-l1-1-0.dll"], + failure: "never", + reference: "processthreadsapi.h GetCurrentProcess", + tests: &["identity_services_return_documented_pseudo_handles_and_ids"], + }, + ServiceMetadata { + library: "kernel32.dll", + symbol: "GetProcessId", + parameters: &[Parameter { name: "process", kind: "handle" }], + result: "u32", + status: ServiceStatus::Partial, + aliases: &["api-ms-win-core-processthreads-l1-1-0.dll"], + failure: "0 with ERROR_INVALID_HANDLE", + reference: "processthreadsapi.h GetProcessId", + tests: &["identity_services_return_documented_pseudo_handles_and_ids"], + }, + ServiceMetadata { + library: "kernel32.dll", + symbol: "GetCurrentThread", + parameters: &[], + result: "handle", + status: ServiceStatus::Implemented, + aliases: &["api-ms-win-core-processthreads-l1-1-0.dll"], + failure: "never", + reference: "processthreadsapi.h GetCurrentThread", + tests: &["identity_services_return_documented_pseudo_handles_and_ids"], + }, + ServiceMetadata { + library: "kernel32.dll", + symbol: "GetCurrentProcessId", + parameters: &[], + result: "u32", + status: ServiceStatus::Implemented, + aliases: &["api-ms-win-core-processthreads-l1-1-0.dll"], + failure: "never", + reference: "processthreadsapi.h GetCurrentProcessId", + tests: &["identity_services_return_documented_pseudo_handles_and_ids"], + }, + ServiceMetadata { + library: "kernel32.dll", + symbol: "GetCurrentThreadId", + parameters: &[], + result: "u32", + status: ServiceStatus::Implemented, + aliases: &["api-ms-win-core-processthreads-l1-1-0.dll"], + failure: "never", + reference: "processthreadsapi.h GetCurrentThreadId", + tests: &["identity_services_return_documented_pseudo_handles_and_ids"], + }, + ServiceMetadata { + library: "kernel32.dll", + symbol: "OpenThread", + parameters: &[Parameter { name: "access", kind: "u32" }, Parameter { name: "inherit", kind: "bool32" }, Parameter { name: "thread", kind: "u32" }], + result: "handle", + status: ServiceStatus::Partial, + aliases: &["api-ms-win-core-processthreads-l1-1-0.dll"], + failure: "0 with ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED or ERROR_NOT_ENOUGH_MEMORY", + reference: "processthreadsapi.h OpenThread", + tests: &["thread_handles_check_access_and_are_rejected_once_closed"], + }, + ServiceMetadata { + library: "kernel32.dll", + symbol: "GetThreadPriority", + parameters: &[Parameter { name: "thread", kind: "handle" }], + result: "i32", + status: ServiceStatus::Partial, + aliases: &["api-ms-win-core-processthreads-l1-1-0.dll"], + failure: "THREAD_PRIORITY_ERROR_RETURN with ERROR_INVALID_HANDLE or ERROR_ACCESS_DENIED", + reference: "processthreadsapi.h GetThreadPriority", + tests: &["thread_handles_check_access_and_are_rejected_once_closed"], + }, + ServiceMetadata { + library: "kernel32.dll", + symbol: "SetThreadPriority", + parameters: &[Parameter { name: "thread", kind: "handle" }, Parameter { name: "priority", kind: "i32" }], + result: "bool32", + status: ServiceStatus::Partial, + aliases: &["api-ms-win-core-processthreads-l1-1-0.dll"], + failure: "0 with ERROR_INVALID_HANDLE, ERROR_ACCESS_DENIED, ERROR_NOT_SUPPORTED or ERROR_INVALID_PARAMETER", + reference: "processthreadsapi.h SetThreadPriority", + tests: &["thread_handles_check_access_and_are_rejected_once_closed"], + }, + ServiceMetadata { + library: "kernel32.dll", + symbol: "CloseHandle", + parameters: &[Parameter { name: "object", kind: "handle" }], + result: "bool32", + status: ServiceStatus::Partial, + aliases: &["api-ms-win-core-handle-l1-1-0.dll"], + failure: "0 with ERROR_INVALID_HANDLE", + reference: "handleapi.h CloseHandle", + tests: &["thread_handles_check_access_and_are_rejected_once_closed"], + }, + ServiceMetadata { + library: "kernel32.dll", + symbol: "GetSystemTimeAsFileTime", + parameters: &[Parameter { name: "time", kind: "out<8>" }], + result: "void", + status: ServiceStatus::Implemented, + aliases: &["api-ms-win-core-sysinfo-l1-1-0.dll"], + failure: "guest fault on an invalid pointer", + reference: "sysinfoapi.h GetSystemTimeAsFileTime", + tests: &["system_time_comes_from_the_injected_clock"], + }, + ServiceMetadata { + library: "kernel32.dll", + symbol: "GetLastError", + parameters: &[], + result: "u32", + status: ServiceStatus::Partial, + aliases: &["api-ms-win-core-errorhandling-l1-1-0.dll"], + failure: "never", + reference: "errhandlingapi.h GetLastError", + tests: &["last_error_is_set_by_failures_and_by_the_guest"], + }, + ServiceMetadata { + library: "kernel32.dll", + symbol: "SetLastError", + parameters: &[Parameter { name: "code", kind: "u32" }], + result: "void", + status: ServiceStatus::Partial, + aliases: &["api-ms-win-core-errorhandling-l1-1-0.dll"], + failure: "never", + reference: "errhandlingapi.h SetLastError", + tests: &["last_error_is_set_by_failures_and_by_the_guest"], + }, + ServiceMetadata { + library: "kernel32.dll", + symbol: "VirtualAlloc", + parameters: &[Parameter { name: "address", kind: "ptr" }, Parameter { name: "size", kind: "u64" }, Parameter { name: "kind", kind: "u32" }, Parameter { name: "protect", kind: "u32" }], + result: "ptr", + status: ServiceStatus::Partial, + aliases: &["api-ms-win-core-memory-l1-1-0.dll"], + failure: "0 with ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED, ERROR_INVALID_ADDRESS or ERROR_NOT_ENOUGH_MEMORY", + reference: "memoryapi.h VirtualAlloc", + tests: &["virtual_memory_is_mapped_released_and_bounded"], + }, + ServiceMetadata { + library: "kernel32.dll", + symbol: "VirtualFree", + parameters: &[Parameter { name: "address", kind: "ptr" }, Parameter { name: "size", kind: "u64" }, Parameter { name: "kind", kind: "u32" }], + result: "bool32", + status: ServiceStatus::Partial, + aliases: &["api-ms-win-core-memory-l1-1-0.dll"], + failure: "0 with ERROR_NOT_SUPPORTED, ERROR_INVALID_PARAMETER or ERROR_INVALID_ADDRESS", + reference: "memoryapi.h VirtualFree", + tests: &["virtual_memory_is_mapped_released_and_bounded"], + }, + ServiceMetadata { + library: "ucrtbase.dll", + symbol: "sqrt", + parameters: &[Parameter { name: "x", kind: "f64" }], + result: "f64", + status: ServiceStatus::Partial, + aliases: &["api-ms-win-crt-math-l1-1-0.dll"], + failure: "NaN for a negative argument; errno is not set", + reference: "math.h sqrt (ISO C, IEC 60559 squareRoot)", + tests: &["floating_arguments_and_results_use_xmm_registers"], + }, + ServiceMetadata { + library: "ucrtbase.dll", + symbol: "sqrtf", + parameters: &[Parameter { name: "x", kind: "f32" }], + result: "f32", + status: ServiceStatus::Partial, + aliases: &["api-ms-win-crt-math-l1-1-0.dll"], + failure: "NaN for a negative argument; errno is not set", + reference: "math.h sqrtf (ISO C, IEC 60559 squareRoot)", + tests: &["floating_arguments_and_results_use_xmm_registers"], + }, + ServiceMetadata { + library: "ucrtbase.dll", + symbol: "fabs", + parameters: &[Parameter { name: "x", kind: "f64" }], + result: "f64", + status: ServiceStatus::Implemented, + aliases: &["api-ms-win-crt-math-l1-1-0.dll"], + failure: "never", + reference: "math.h fabs (ISO C, IEC 60559 abs)", + tests: &["floating_arguments_and_results_use_xmm_registers"], + }, + ServiceMetadata { + library: "ucrtbase.dll", + symbol: "fabsf", + parameters: &[Parameter { name: "x", kind: "f32" }], + result: "f32", + status: ServiceStatus::Implemented, + aliases: &["api-ms-win-crt-math-l1-1-0.dll"], + failure: "never", + reference: "math.h fabsf (ISO C, IEC 60559 abs)", + tests: &["floating_arguments_and_results_use_xmm_registers"], + }, +]; + +/// Register every generated service and its API-set aliases. +pub fn register(registry: &mut ImportRegistry, state: &Arc) { + let s = state.clone(); + registry.register_with_status("kernel32.dll", "SetProcessPriorityBoost", ServiceStatus::Partial, move |args, cpu, memory| { + let call = Call::new(args, cpu, memory); + let a0 = call.u64(0)?; + let a1 = call.bool32(1)?; + let mut context = ServiceContext { state: &s, memory }; + let result: bool = handlers::set_process_priority_boost(&mut context, a0, a1)?; + Ok(result.place(cpu)) + }); + let s = state.clone(); + registry.register_with_status("kernel32.dll", "GetProcessPriorityBoost", ServiceStatus::Partial, move |args, cpu, memory| { + let call = Call::new(args, cpu, memory); + let a0 = call.u64(0)?; + let a1 = call.out::<4>(1)?; + let mut context = ServiceContext { state: &s, memory }; + let result: bool = handlers::get_process_priority_boost(&mut context, a0, a1)?; + Ok(result.place(cpu)) + }); + let s = state.clone(); + registry.register_with_status("kernel32.dll", "GetCurrentProcess", ServiceStatus::Implemented, move |args, cpu, memory| { + let _ = args; + let mut context = ServiceContext { state: &s, memory }; + let result: u64 = handlers::get_current_process(&mut context)?; + Ok(result.place(cpu)) + }); + let s = state.clone(); + registry.register_with_status("kernel32.dll", "GetProcessId", ServiceStatus::Partial, move |args, cpu, memory| { + let call = Call::new(args, cpu, memory); + let a0 = call.u64(0)?; + let mut context = ServiceContext { state: &s, memory }; + let result: u32 = handlers::get_process_id(&mut context, a0)?; + Ok(result.place(cpu)) + }); + let s = state.clone(); + registry.register_with_status("kernel32.dll", "GetCurrentThread", ServiceStatus::Implemented, move |args, cpu, memory| { + let _ = args; + let mut context = ServiceContext { state: &s, memory }; + let result: u64 = handlers::get_current_thread(&mut context)?; + Ok(result.place(cpu)) + }); + let s = state.clone(); + registry.register_with_status("kernel32.dll", "GetCurrentProcessId", ServiceStatus::Implemented, move |args, cpu, memory| { + let _ = args; + let mut context = ServiceContext { state: &s, memory }; + let result: u32 = handlers::get_current_process_id(&mut context)?; + Ok(result.place(cpu)) + }); + let s = state.clone(); + registry.register_with_status("kernel32.dll", "GetCurrentThreadId", ServiceStatus::Implemented, move |args, cpu, memory| { + let _ = args; + let mut context = ServiceContext { state: &s, memory }; + let result: u32 = handlers::get_current_thread_id(&mut context)?; + Ok(result.place(cpu)) + }); + let s = state.clone(); + registry.register_with_status("kernel32.dll", "OpenThread", ServiceStatus::Partial, move |args, cpu, memory| { + let call = Call::new(args, cpu, memory); + let a0 = call.u32(0)?; + let a1 = call.bool32(1)?; + let a2 = call.u32(2)?; + let mut context = ServiceContext { state: &s, memory }; + let result: u64 = handlers::open_thread(&mut context, a0, a1, a2)?; + Ok(result.place(cpu)) + }); + let s = state.clone(); + registry.register_with_status("kernel32.dll", "GetThreadPriority", ServiceStatus::Partial, move |args, cpu, memory| { + let call = Call::new(args, cpu, memory); + let a0 = call.u64(0)?; + let mut context = ServiceContext { state: &s, memory }; + let result: i32 = handlers::get_thread_priority(&mut context, a0)?; + Ok(result.place(cpu)) + }); + let s = state.clone(); + registry.register_with_status("kernel32.dll", "SetThreadPriority", ServiceStatus::Partial, move |args, cpu, memory| { + let call = Call::new(args, cpu, memory); + let a0 = call.u64(0)?; + let a1 = call.i32(1)?; + let mut context = ServiceContext { state: &s, memory }; + let result: bool = handlers::set_thread_priority(&mut context, a0, a1)?; + Ok(result.place(cpu)) + }); + let s = state.clone(); + registry.register_with_status("kernel32.dll", "CloseHandle", ServiceStatus::Partial, move |args, cpu, memory| { + let call = Call::new(args, cpu, memory); + let a0 = call.u64(0)?; + let mut context = ServiceContext { state: &s, memory }; + let result: bool = handlers::close_handle(&mut context, a0)?; + Ok(result.place(cpu)) + }); + let s = state.clone(); + registry.register_with_status("kernel32.dll", "GetSystemTimeAsFileTime", ServiceStatus::Implemented, move |args, cpu, memory| { + let call = Call::new(args, cpu, memory); + let a0 = call.out::<8>(0)?; + let mut context = ServiceContext { state: &s, memory }; + let () = handlers::get_system_time_as_file_time(&mut context, a0)?; + Ok(0) + }); + let s = state.clone(); + registry.register_with_status("kernel32.dll", "GetLastError", ServiceStatus::Partial, move |args, cpu, memory| { + let _ = args; + let mut context = ServiceContext { state: &s, memory }; + let result: u32 = handlers::get_last_error(&mut context)?; + Ok(result.place(cpu)) + }); + let s = state.clone(); + registry.register_with_status("kernel32.dll", "SetLastError", ServiceStatus::Partial, move |args, cpu, memory| { + let call = Call::new(args, cpu, memory); + let a0 = call.u32(0)?; + let mut context = ServiceContext { state: &s, memory }; + let () = handlers::set_last_error(&mut context, a0)?; + Ok(0) + }); + let s = state.clone(); + registry.register_with_status("kernel32.dll", "VirtualAlloc", ServiceStatus::Partial, move |args, cpu, memory| { + let call = Call::new(args, cpu, memory); + let a0 = call.u64(0)?; + let a1 = call.u64(1)?; + let a2 = call.u32(2)?; + let a3 = call.u32(3)?; + let mut context = ServiceContext { state: &s, memory }; + let result: u64 = handlers::virtual_alloc(&mut context, a0, a1, a2, a3)?; + Ok(result.place(cpu)) + }); + let s = state.clone(); + registry.register_with_status("kernel32.dll", "VirtualFree", ServiceStatus::Partial, move |args, cpu, memory| { + let call = Call::new(args, cpu, memory); + let a0 = call.u64(0)?; + let a1 = call.u64(1)?; + let a2 = call.u32(2)?; + let mut context = ServiceContext { state: &s, memory }; + let result: bool = handlers::virtual_free(&mut context, a0, a1, a2)?; + Ok(result.place(cpu)) + }); + let s = state.clone(); + registry.register_with_status("ucrtbase.dll", "sqrt", ServiceStatus::Partial, move |args, cpu, memory| { + let call = Call::new(args, cpu, memory); + let a0 = call.f64(0)?; + let mut context = ServiceContext { state: &s, memory }; + let result: crate::runtime::Float64 = handlers::sqrt(&mut context, a0)?; + Ok(result.place(cpu)) + }); + let s = state.clone(); + registry.register_with_status("ucrtbase.dll", "sqrtf", ServiceStatus::Partial, move |args, cpu, memory| { + let call = Call::new(args, cpu, memory); + let a0 = call.f32(0)?; + let mut context = ServiceContext { state: &s, memory }; + let result: crate::runtime::Float32 = handlers::sqrtf(&mut context, a0)?; + Ok(result.place(cpu)) + }); + let s = state.clone(); + registry.register_with_status("ucrtbase.dll", "fabs", ServiceStatus::Implemented, move |args, cpu, memory| { + let call = Call::new(args, cpu, memory); + let a0 = call.f64(0)?; + let mut context = ServiceContext { state: &s, memory }; + let result: crate::runtime::Float64 = handlers::fabs(&mut context, a0)?; + Ok(result.place(cpu)) + }); + let s = state.clone(); + registry.register_with_status("ucrtbase.dll", "fabsf", ServiceStatus::Implemented, move |args, cpu, memory| { + let call = Call::new(args, cpu, memory); + let a0 = call.f32(0)?; + let mut context = ServiceContext { state: &s, memory }; + let result: crate::runtime::Float32 = handlers::fabsf(&mut context, a0)?; + Ok(result.place(cpu)) + }); + for service in &SERVICES { + for alias in service.aliases { + if let Err(error) = registry.try_alias(alias, service.library, service.symbol) { + panic!("{error}"); + } + } + } +} diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index 2d27294..5e3723b 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -33,9 +33,6 @@ const PAGE_SIZE: u64 = 4096; const MEM_COMMIT_RESERVE: u32 = 0x3000; const MEM_RELEASE: u32 = 0x8000; const ERROR_NOACCESS: u32 = 998; -const KERNEL32: &str = "kernel32.dll"; -const PROCESS_THREADS_V1: &str = "api-ms-win-core-processthreads-l1-1-0.dll"; -const PROCESS_THREADS_V2: &str = "api-ms-win-core-processthreads-l1-1-2.dll"; /// Clock trait for injecting deterministic time in tests or host time in production. pub trait Clock: Send + Sync { @@ -136,9 +133,10 @@ impl ServicesState { self.priority_boost_disabled.load(Ordering::SeqCst) } - fn fail(&self, error: u32, return_value: u64) -> Result { + /// Record a guest error and return the documented failure value. + fn fail(&self, error: u32, value: T) -> Result { self.last_error.store(error, Ordering::SeqCst); - Ok(return_value) + Ok(value) } fn is_current_process(&self, handle: u64) -> bool { @@ -151,264 +149,10 @@ impl ServicesState { } } -/// Register standard Windows core and Xbox memory services into the registry. +/// Register the services generated from `runtime/services.txt` and the +/// hand-written fixture services. pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc) { - let s = state.clone(); - registry.register(KERNEL32, "SetProcessPriorityBoost", move |args, _, mem| { - if !s.is_current_process(args.get(0, mem).map_err(ExitReason::MemoryFault)?) { - return Ok(0); - } - let disable = args.get(1, mem).map_err(ExitReason::MemoryFault)? as u32; - s.priority_boost_disabled - .store(disable != 0, Ordering::SeqCst); - Ok(1) - }); - registry.alias(PROCESS_THREADS_V2, KERNEL32, "SetProcessPriorityBoost"); - - registry.set_status(KERNEL32, "SetProcessPriorityBoost", ServiceStatus::Partial); - - let s = state.clone(); - registry.register(KERNEL32, "GetProcessPriorityBoost", move |args, _, mem| { - if !s.is_current_process(args.get(0, mem).map_err(ExitReason::MemoryFault)?) { - return Ok(0); - } - let output = args.get(1, mem).map_err(ExitReason::MemoryFault)?; - if mem - .write_u32(output, u32::from(s.priority_boost_disabled())) - .is_err() - { - s.last_error.store(ERROR_NOACCESS, Ordering::SeqCst); - return Ok(0); - } - Ok(1) - }); - registry.alias(PROCESS_THREADS_V2, KERNEL32, "GetProcessPriorityBoost"); - registry.set_status(KERNEL32, "GetProcessPriorityBoost", ServiceStatus::Partial); - - registry.register(KERNEL32, "GetCurrentProcess", |_, _, _| Ok(CURRENT_PROCESS)); - registry.alias(PROCESS_THREADS_V1, KERNEL32, "GetCurrentProcess"); - - let s = state.clone(); - registry.register(KERNEL32, "GetProcessId", move |args, _, mem| { - if !s.is_current_process(args.get(0, mem).map_err(ExitReason::MemoryFault)?) { - return Ok(0); - } - Ok(u64::from(s.process_id)) - }); - registry.alias(PROCESS_THREADS_V1, KERNEL32, "GetProcessId"); - registry.set_status(KERNEL32, "GetProcessId", ServiceStatus::Partial); - - registry.register(KERNEL32, "GetCurrentThread", |_, _, _| Ok(CURRENT_THREAD)); - registry.alias(PROCESS_THREADS_V1, KERNEL32, "GetCurrentThread"); - - let s = state.clone(); - registry.register(KERNEL32, "OpenThread", move |args, _, mem| { - let access = args.get(0, mem).map_err(ExitReason::MemoryFault)? as u32; - let inherit = args.get(1, mem).map_err(ExitReason::MemoryFault)? as u32; - let id = args.get(2, mem).map_err(ExitReason::MemoryFault)? as u32; - if id != s.thread_id { - return s.fail(ERROR_INVALID_PARAMETER, 0); - } - if inherit != 0 || access & !THREAD_SUPPORTED_RIGHTS != 0 { - return s.fail(ERROR_NOT_SUPPORTED, 0); - } - let mut thread = s.thread.lock().expect("guest thread state"); - let Some(handle) = thread - .last_handle - .checked_add(4) - .filter(|_| thread.handles.len() < MAX_THREAD_HANDLES) - else { - return s.fail(ERROR_NOT_ENOUGH_MEMORY, 0); - }; - thread.handles.insert(handle, access); - thread.last_handle = handle; - Ok(handle) - }); - - let s = state.clone(); - registry.register(KERNEL32, "GetThreadPriority", move |args, _, mem| { - let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?; - let thread = s.thread.lock().expect("guest thread state"); - if let Err(error) = thread.check_access(handle, THREAD_QUERY_RIGHTS) { - return s.fail(error, THREAD_PRIORITY_ERROR_RETURN); - } - Ok(u64::from(thread.priority as u32)) - }); - - let s = state.clone(); - registry.register(KERNEL32, "SetThreadPriority", move |args, _, mem| { - let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?; - let priority = args.get(1, mem).map_err(ExitReason::MemoryFault)? as i32; - let mut thread = s.thread.lock().expect("guest thread state"); - if let Err(error) = thread.check_access(handle, THREAD_SET_RIGHTS) { - return s.fail(error, 0); - } - if matches!(priority, 0x0001_0000 | 0x0002_0000) { - return s.fail(ERROR_NOT_SUPPORTED, 0); - } - if !matches!(priority, -15 | -2..=2 | 15) { - return s.fail(ERROR_INVALID_PARAMETER, 0); - } - thread.priority = priority; - Ok(1) - }); - - for symbol in ["OpenThread", "GetThreadPriority", "SetThreadPriority"] { - registry.alias(PROCESS_THREADS_V1, KERNEL32, symbol); - registry.set_status(KERNEL32, symbol, ServiceStatus::Partial); - } - - let s = state.clone(); - registry.register(KERNEL32, "CloseHandle", move |args, _, mem| { - let handle = args.get(0, mem).map_err(ExitReason::MemoryFault)?; - if matches!(handle, CURRENT_PROCESS | CURRENT_THREAD) - || s.thread - .lock() - .expect("guest thread state") - .handles - .remove(&handle) - .is_some() - { - return Ok(1); - } - s.fail(ERROR_INVALID_HANDLE, 0) - }); - registry.alias("api-ms-win-core-handle-l1-1-0.dll", KERNEL32, "CloseHandle"); - registry.set_status(KERNEL32, "CloseHandle", ServiceStatus::Partial); - - // 1. GetSystemTimeAsFileTime(lpSystemTimeAsFileTime: *mut FILETIME) - let s = state.clone(); - let handler = move |args: &crate::imports::Win64Args, - _cpu: &mut crate::cpu::CpuState, - mem: &mut GuestMemory| - -> Result { - let ptr = args.get(0, mem).map_err(ExitReason::MemoryFault)?; - if ptr == 0 { - s.last_error.store(87, Ordering::SeqCst); // ERROR_INVALID_PARAMETER - return Ok(0); - } - let ft = s.clock.now_filetime(); - mem.write_u64(ptr, ft).map_err(ExitReason::MemoryFault)?; - Ok(0) - }; - registry.register(KERNEL32, "GetSystemTimeAsFileTime", handler); - registry.alias( - "api-ms-win-core-sysinfo-l1-1-0.dll", - KERNEL32, - "GetSystemTimeAsFileTime", - ); - - // 2. GetCurrentProcessId() -> DWORD - let s = state.clone(); - let handler = move |_args: &crate::imports::Win64Args, - _cpu: &mut crate::cpu::CpuState, - _mem: &mut GuestMemory| - -> Result { Ok(s.process_id as u64) }; - registry.register(KERNEL32, "GetCurrentProcessId", handler); - registry.alias(PROCESS_THREADS_V1, KERNEL32, "GetCurrentProcessId"); - - // 3. GetCurrentThreadId() -> DWORD - let s = state.clone(); - let handler = move |_args: &crate::imports::Win64Args, - _cpu: &mut crate::cpu::CpuState, - _mem: &mut GuestMemory| - -> Result { Ok(s.thread_id as u64) }; - registry.register(KERNEL32, "GetCurrentThreadId", handler); - registry.alias(PROCESS_THREADS_V1, KERNEL32, "GetCurrentThreadId"); - - // 4. GetLastError() -> DWORD - let s = state.clone(); - let handler = - move |_args: &crate::imports::Win64Args, - _cpu: &mut crate::cpu::CpuState, - _mem: &mut GuestMemory| - -> Result { Ok(s.last_error.load(Ordering::SeqCst) as u64) }; - registry.register(KERNEL32, "GetLastError", handler); - registry.alias( - "api-ms-win-core-errorhandling-l1-1-0.dll", - KERNEL32, - "GetLastError", - ); - - // 5. SetLastError(dwErrCode: DWORD) - let s = state.clone(); - let handler = move |args: &crate::imports::Win64Args, - _cpu: &mut crate::cpu::CpuState, - mem: &mut GuestMemory| - -> Result { - let code = args.get(0, mem).map_err(ExitReason::MemoryFault)? as u32; - s.last_error.store(code, Ordering::SeqCst); - Ok(0) - }; - registry.register(KERNEL32, "SetLastError", handler); - registry.alias( - "api-ms-win-core-errorhandling-l1-1-0.dll", - KERNEL32, - "SetLastError", - ); - - let s = state.clone(); - registry.register(KERNEL32, "VirtualAlloc", move |args, _, mem| { - let requested = args.get(0, mem).map_err(ExitReason::MemoryFault)?; - let size = args.get(1, mem).map_err(ExitReason::MemoryFault)?; - let allocation_type = args.get(2, mem).map_err(ExitReason::MemoryFault)? as u32; - let protect = args.get(3, mem).map_err(ExitReason::MemoryFault)? as u32; - - if size == 0 { - return s.fail(ERROR_INVALID_PARAMETER, 0); - } - if allocation_type != MEM_COMMIT_RESERVE { - return s.fail(ERROR_NOT_SUPPORTED, 0); - } - // Executable allocations require guest translation cache invalidation. - let permissions = match protect { - 0x01 => MemoryPermissions::NO_ACCESS, - 0x02 => MemoryPermissions::READ_ONLY, - 0x04 => MemoryPermissions::READ_WRITE, - _ => return s.fail(ERROR_INVALID_PARAMETER, 0), - }; - let base = requested & !(ALLOCATION_GRANULARITY - 1); - if requested != 0 && base == 0 { - return s.fail(ERROR_INVALID_ADDRESS, 0); - } - let Some(size) = size - .checked_add(requested - base) - .and_then(|span| span.checked_next_multiple_of(PAGE_SIZE)) - .and_then(|span| usize::try_from(span).ok()) - else { - return s.fail(ERROR_INVALID_PARAMETER, 0); - }; - - match mem.map_virtual_allocation(base, size, permissions) { - Ok(address) => Ok(address), - Err(MemoryError::OverlappingRegion { .. } | MemoryError::Overflow) => { - s.fail(ERROR_INVALID_ADDRESS, 0) - } - Err(_) => s.fail(ERROR_NOT_ENOUGH_MEMORY, 0), - } - }); - - let s = state.clone(); - registry.register(KERNEL32, "VirtualFree", move |args, _, mem| { - let address = args.get(0, mem).map_err(ExitReason::MemoryFault)?; - let size = args.get(1, mem).map_err(ExitReason::MemoryFault)?; - let free_type = args.get(2, mem).map_err(ExitReason::MemoryFault)? as u32; - if free_type != MEM_RELEASE { - return s.fail(ERROR_NOT_SUPPORTED, 0); - } - if size != 0 { - return s.fail(ERROR_INVALID_PARAMETER, 0); - } - if !mem.release_virtual_allocation(address) { - return s.fail(ERROR_INVALID_ADDRESS, 0); - } - Ok(1) - }); - - for symbol in ["VirtualAlloc", "VirtualFree"] { - registry.alias("api-ms-win-core-memory-l1-1-0.dll", KERNEL32, symbol); - registry.set_status(KERNEL32, symbol, ServiceStatus::Partial); - } + crate::runtime_table::register(registry, &state); // 8. XMemAlloc(dwSize, dwAllocAttributes) -> LPVOID (Xbox Scarlett allocator in xmem.dll) let s = state.clone(); @@ -582,3 +326,244 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc = Result; + + pub fn set_process_priority_boost( + context: &mut ServiceContext<'_>, + process: u64, + disable: bool, + ) -> Outcome { + if !context.state.is_current_process(process) { + return Ok(false); + } + context + .state + .priority_boost_disabled + .store(disable, Ordering::SeqCst); + Ok(true) + } + + pub fn get_process_priority_boost( + context: &mut ServiceContext<'_>, + process: u64, + disabled: OutPtr<4>, + ) -> Outcome { + if !context.state.is_current_process(process) { + return Ok(false); + } + let value = u32::from(context.state.priority_boost_disabled()); + if disabled.store(context.memory, value.to_le_bytes()).is_err() { + return context.state.fail(ERROR_NOACCESS, false); + } + Ok(true) + } + + pub fn get_current_process(_: &mut ServiceContext<'_>) -> Outcome { + Ok(CURRENT_PROCESS) + } + + pub fn get_process_id(context: &mut ServiceContext<'_>, process: u64) -> Outcome { + Ok(if context.state.is_current_process(process) { + context.state.process_id + } else { + 0 + }) + } + + pub fn get_current_thread(_: &mut ServiceContext<'_>) -> Outcome { + Ok(CURRENT_THREAD) + } + + pub fn get_current_process_id(context: &mut ServiceContext<'_>) -> Outcome { + Ok(context.state.process_id) + } + + pub fn get_current_thread_id(context: &mut ServiceContext<'_>) -> Outcome { + Ok(context.state.thread_id) + } + + pub fn open_thread( + context: &mut ServiceContext<'_>, + access: u32, + inherit: bool, + id: u32, + ) -> Outcome { + let state = context.state; + if id != state.thread_id { + return state.fail(ERROR_INVALID_PARAMETER, 0); + } + if inherit || access & !THREAD_SUPPORTED_RIGHTS != 0 { + return state.fail(ERROR_NOT_SUPPORTED, 0); + } + let mut thread = state.thread.lock().expect("guest thread state"); + let Some(handle) = thread + .last_handle + .checked_add(4) + .filter(|_| thread.handles.len() < MAX_THREAD_HANDLES) + else { + return state.fail(ERROR_NOT_ENOUGH_MEMORY, 0); + }; + thread.handles.insert(handle, access); + thread.last_handle = handle; + Ok(handle) + } + + pub fn get_thread_priority(context: &mut ServiceContext<'_>, handle: u64) -> Outcome { + let thread = context.state.thread.lock().expect("guest thread state"); + if let Err(error) = thread.check_access(handle, THREAD_QUERY_RIGHTS) { + return context + .state + .fail(error, THREAD_PRIORITY_ERROR_RETURN as i32); + } + Ok(thread.priority) + } + + pub fn set_thread_priority( + context: &mut ServiceContext<'_>, + handle: u64, + priority: i32, + ) -> Outcome { + let state = context.state; + let mut thread = state.thread.lock().expect("guest thread state"); + if let Err(error) = thread.check_access(handle, THREAD_SET_RIGHTS) { + return state.fail(error, false); + } + if matches!(priority, 0x0001_0000 | 0x0002_0000) { + return state.fail(ERROR_NOT_SUPPORTED, false); + } + if !matches!(priority, -15 | -2..=2 | 15) { + return state.fail(ERROR_INVALID_PARAMETER, false); + } + thread.priority = priority; + Ok(true) + } + + pub fn close_handle(context: &mut ServiceContext<'_>, handle: u64) -> Outcome { + let closed = matches!(handle, CURRENT_PROCESS | CURRENT_THREAD) + || context + .state + .thread + .lock() + .expect("guest thread state") + .handles + .remove(&handle) + .is_some(); + if closed { + Ok(true) + } else { + context.state.fail(ERROR_INVALID_HANDLE, false) + } + } + + pub fn get_system_time_as_file_time( + context: &mut ServiceContext<'_>, + time: OutPtr<8>, + ) -> Outcome<()> { + let now = context.state.clock.now_filetime(); + time.store(context.memory, now.to_le_bytes()) + .map_err(ExitReason::MemoryFault) + } + + pub fn get_last_error(context: &mut ServiceContext<'_>) -> Outcome { + Ok(context.state.last_error.load(Ordering::SeqCst)) + } + + pub fn set_last_error(context: &mut ServiceContext<'_>, code: u32) -> Outcome<()> { + context.state.last_error.store(code, Ordering::SeqCst); + Ok(()) + } + + pub fn virtual_alloc( + context: &mut ServiceContext<'_>, + requested: u64, + size: u64, + kind: u32, + protect: u32, + ) -> Outcome { + let state = context.state; + if size == 0 { + return state.fail(ERROR_INVALID_PARAMETER, 0); + } + if kind != MEM_COMMIT_RESERVE { + return state.fail(ERROR_NOT_SUPPORTED, 0); + } + // Executable allocations require guest translation cache invalidation. + let permissions = match protect { + 0x01 => MemoryPermissions::NO_ACCESS, + 0x02 => MemoryPermissions::READ_ONLY, + 0x04 => MemoryPermissions::READ_WRITE, + _ => return state.fail(ERROR_INVALID_PARAMETER, 0), + }; + let base = requested & !(ALLOCATION_GRANULARITY - 1); + if requested != 0 && base == 0 { + return state.fail(ERROR_INVALID_ADDRESS, 0); + } + let Some(size) = size + .checked_add(requested - base) + .and_then(|span| span.checked_next_multiple_of(PAGE_SIZE)) + .and_then(|span| usize::try_from(span).ok()) + else { + return state.fail(ERROR_INVALID_PARAMETER, 0); + }; + match context + .memory + .map_virtual_allocation(base, size, permissions) + { + Ok(address) => Ok(address), + Err(MemoryError::OverlappingRegion { .. } | MemoryError::Overflow) => { + state.fail(ERROR_INVALID_ADDRESS, 0) + } + Err(_) => state.fail(ERROR_NOT_ENOUGH_MEMORY, 0), + } + } + + pub fn virtual_free( + context: &mut ServiceContext<'_>, + address: u64, + size: u64, + kind: u32, + ) -> Outcome { + let state = context.state; + if kind != MEM_RELEASE { + return state.fail(ERROR_NOT_SUPPORTED, false); + } + if size != 0 { + return state.fail(ERROR_INVALID_PARAMETER, false); + } + if !context.memory.release_virtual_allocation(address) { + return state.fail(ERROR_INVALID_ADDRESS, false); + } + Ok(true) + } + + /// The guest MXCSR is not visible to a service, so results use the default + /// rounding and raise no guest flags; the registry marks them partial. + const DEFAULT_MXCSR: u32 = crate::cpu::Mxcsr::RESET; + + pub fn sqrt(_: &mut ServiceContext<'_>, x: Float64) -> Outcome { + let control = Control::from_mxcsr(DEFAULT_MXCSR); + Ok(Float64(square_root(F64, x.0, &control).bits)) + } + + pub fn sqrtf(_: &mut ServiceContext<'_>, x: Float32) -> Outcome { + let control = Control::from_mxcsr(DEFAULT_MXCSR); + let bits = square_root(F32, u64::from(x.0), &control).bits; + Ok(Float32(bits as u32)) + } + + pub fn fabs(_: &mut ServiceContext<'_>, x: Float64) -> Outcome { + Ok(Float64(x.0 & !(1 << 63))) + } + + pub fn fabsf(_: &mut ServiceContext<'_>, x: Float32) -> Outcome { + Ok(Float32(x.0 & !(1 << 31))) + } +} diff --git a/crates/loader/tests/generated_runtime_integration.rs b/crates/loader/tests/generated_runtime_integration.rs index a1be735..047de08 100644 --- a/crates/loader/tests/generated_runtime_integration.rs +++ b/crates/loader/tests/generated_runtime_integration.rs @@ -7,33 +7,18 @@ use xenora_loader::memory::{GuestMemory, MemoryPermissions}; use xenora_loader::services::{MockClock, ServicesState, register_standard_services}; #[test] -fn test_generated_crt_math_in_runtime_registry() { +fn test_crt_math_resolves_through_its_api_set_and_uses_xmm0() { let mut registry = ImportRegistry::new(); let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(100)))); register_standard_services(&mut registry, state); - // Register a sample generated CRT handler (e.g. sqrt) - registry.register_with_status( - "api-ms-win-crt-math-l1-1-0.dll", - "sqrt", - ServiceStatus::Partial, - |args: &Win64Args, - _cpu: &mut CpuState, - _mem: &mut GuestMemory| - -> Result { - let x = f64::from_bits(args.rcx); - let r = x.sqrt(); - Ok(r.to_bits()) - }, - ); - let mut cpu = CpuState::new(0x1000, 0x8000); let mut mem = GuestMemory::new(); mem.map_region(0x1000, 0x10000, MemoryPermissions::READ_WRITE_EXECUTE) .unwrap(); - + cpu.xmm[0] = u128::from(16.0f64.to_bits()); let args = Win64Args { - rcx: (16.0f64).to_bits(), + rcx: 9.0f64.to_bits(), rdx: 0, r8: 0, r9: 0, @@ -43,8 +28,8 @@ fn test_generated_crt_math_in_runtime_registry() { let desc = registry .binding("api-ms-win-crt-math-l1-1-0.dll", "sqrt") .unwrap(); - let res = (desc.handler)(&args, &mut cpu, &mut mem).unwrap(); - assert_eq!(f64::from_bits(res), 4.0); + (desc.handler)(&args, &mut cpu, &mut mem).unwrap(); + assert_eq!(f64::from_bits(cpu.xmm[0] as u64), 4.0); } #[test] diff --git a/crates/loader/tests/runtime_services.rs b/crates/loader/tests/runtime_services.rs new file mode 100644 index 0000000..f8417d4 --- /dev/null +++ b/crates/loader/tests/runtime_services.rs @@ -0,0 +1,981 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! Typed runtime services, called by translated guest code through a bound +//! import table, and the import parser and registry behind them. +//! +//! Expected values come from the public Win32, ISO C and Microsoft x64 calling +//! convention documentation, not from the registry or the handlers. + +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use xenora_loader::cpu::{CpuState, ExitReason, Register}; +use xenora_loader::dbt::DbtEngine; +use xenora_loader::import_table::{ImportName, ImportTableError, MAX_IMPORTS, parse_imports}; +use xenora_loader::imports::{ + ImportError, ImportRegistry, RegistryError, ServiceStatus, Win64Args, +}; +use xenora_loader::memory::{GuestMemory, MemoryPermissions}; +use xenora_loader::pe::ParsedPe; +use xenora_loader::probe::{ProbeConfig, ProbeReport, probe_pe_bytes}; +use xenora_loader::runtime::{Call, Float32, Float64}; +use xenora_loader::runtime_table::SERVICES; +use xenora_loader::services::{MockClock, ServicesState, register_standard_services}; + +const BASE: u64 = 0x1_4000_0000; +const CODE_RVA: u32 = 0x1000; +const IDATA_RVA: u32 = 0x10000; +const IDATA_RAW: usize = 0x2200; +const IDATA_LEN: usize = 0x4000; +const SCRATCH: u64 = 0x5_0000; +const STACK: u64 = 0x8_0000; +const STACK_TOP: u64 = STACK + 0x800; + +#[derive(Clone)] +enum Symbol { + Name(&'static str), + Ordinal(u16), +} + +/// Original PE32+ image importing `imports`, one descriptor each. The code for +/// import `n`, at RVA 0x1000 + 16n, is `call [its slot]; hlt`. +struct Image { + bytes: Vec, + slots: Vec, +} + +fn build(imports: &[(&str, Symbol)]) -> Image { + let mut pe = vec![0u8; IDATA_RAW + IDATA_LEN]; + fn put(pe: &mut [u8], at: usize, bytes: &[u8]) { + pe[at..at + bytes.len()].copy_from_slice(bytes); + } + put(&mut pe, 0, b"MZ"); + put(&mut pe, 0x3C, &0x80u32.to_le_bytes()); + put(&mut pe, 0x80, b"PE\0\0"); + put(&mut pe, 0x84, &0x8664u16.to_le_bytes()); + put(&mut pe, 0x86, &2u16.to_le_bytes()); + put(&mut pe, 0x94, &240u16.to_le_bytes()); + let optional = 0x98; + put(&mut pe, optional, &0x20Bu16.to_le_bytes()); + put(&mut pe, optional + 16, &CODE_RVA.to_le_bytes()); + put(&mut pe, optional + 24, &BASE.to_le_bytes()); + put(&mut pe, optional + 32, &0x1000u32.to_le_bytes()); + put(&mut pe, optional + 36, &0x200u32.to_le_bytes()); + put(&mut pe, optional + 56, &0x20000u32.to_le_bytes()); + put(&mut pe, optional + 60, &0x200u32.to_le_bytes()); + put(&mut pe, optional + 108, &16u32.to_le_bytes()); + put(&mut pe, optional + 120, &IDATA_RVA.to_le_bytes()); + put(&mut pe, optional + 124, &0x100u32.to_le_bytes()); + for (index, (name, rva, raw, len, flags)) in [ + (b".text", CODE_RVA, 0x200, 0x2000, 0x6000_0020u32), + (b".idat", IDATA_RVA, IDATA_RAW, IDATA_LEN, 0xC000_0040), + ] + .into_iter() + .enumerate() + { + let section = optional + 240 + 40 * index; + put(&mut pe, section, name); + put(&mut pe, section + 8, &(len as u32).to_le_bytes()); + put(&mut pe, section + 12, &rva.to_le_bytes()); + put(&mut pe, section + 16, &(len as u32).to_le_bytes()); + put(&mut pe, section + 20, &(raw as u32).to_le_bytes()); + put(&mut pe, section + 36, &flags.to_le_bytes()); + } + + let file = |rva: u32| IDATA_RAW + (rva - IDATA_RVA) as usize; + let mut next = IDATA_RVA + 20 * (imports.len() as u32 + 1); + let mut take = |len: usize| { + let rva = next; + next = (next + len as u32 + 7) & !7; + rva + }; + let mut slots = Vec::new(); + for (index, (module, symbol)) in imports.iter().enumerate() { + let module_rva = take(module.len() + 1); + put(&mut pe, file(module_rva), module.as_bytes()); + let entry = match symbol { + Symbol::Ordinal(ordinal) => 1 << 63 | u64::from(*ordinal), + Symbol::Name(name) => { + let hint = take(name.len() + 3); + put(&mut pe, file(hint) + 2, name.as_bytes()); + u64::from(hint) + } + }; + let (lookup, slot) = (take(16), take(16)); + put(&mut pe, file(lookup), &entry.to_le_bytes()); + put(&mut pe, file(slot), &entry.to_le_bytes()); + let descriptor = file(IDATA_RVA) + 20 * index; + put(&mut pe, descriptor, &lookup.to_le_bytes()); + put(&mut pe, descriptor + 12, &module_rva.to_le_bytes()); + put(&mut pe, descriptor + 16, &slot.to_le_bytes()); + slots.push(slot); + + let code_rva = CODE_RVA + 16 * index as u32; + let displacement = slot.wrapping_sub(code_rva + 6); + let at = 0x200 + 16 * index; + put(&mut pe, at, &[0xFF, 0x15]); // call qword ptr [rip + displacement] + put(&mut pe, at + 2, &displacement.to_le_bytes()); + put(&mut pe, at + 6, &[0xF4]); // hlt + } + Image { bytes: pe, slots } +} + +fn standard(clock: u64) -> (ImportRegistry, Arc) { + let clock = Arc::new(MockClock::new(clock)); + let mut registry = ImportRegistry::new(); + register_standard_services(&mut registry, Arc::new(ServicesState::new(clock.clone()))); + (registry, clock) +} + +/// A guest whose image imports every generated service from its own library. +struct Guest { + engine: DbtEngine, + memory: GuestMemory, + clock: Arc, + /// Upper halves and XMM lanes of unrelated arguments hold this pattern. + xmm: [u128; 4], +} + +impl Guest { + fn new() -> Self { + let imports: Vec<(&str, Symbol)> = SERVICES + .iter() + .map(|service| (service.library, Symbol::Name(service.symbol))) + .collect(); + let image = build(&imports); + let pe = ParsedPe::parse(&image.bytes).unwrap(); + let mut memory = pe.load_into_memory(&image.bytes).unwrap().memory; + memory + .map_region(SCRATCH, 0x100, MemoryPermissions::READ_WRITE) + .unwrap(); + memory + .map_region(STACK, 0x1000, MemoryPermissions::READ_WRITE) + .unwrap(); + let (mut registry, clock) = standard(0x01DA_0000_1234_5678); + let bound = registry + .bind_imports(&pe, &image.bytes, BASE, &mut memory) + .unwrap(); + assert_eq!(bound, SERVICES.len()); + let mut engine = DbtEngine::new(256 * 1024).unwrap(); + engine.set_import_registry(registry); + Self { + engine, + memory, + clock, + xmm: [0xAAAA_BBBB_CCCC_DDDD_EEEE_FFFF_0123_4567; 4], + } + } + + fn run(&mut self, symbol: &str, args: &[u64]) -> (CpuState, ExitReason) { + let index = SERVICES + .iter() + .position(|service| service.symbol == symbol) + .unwrap(); + let mut cpu = CpuState::new(BASE + u64::from(CODE_RVA) + 16 * index as u64, STACK_TOP); + for (index, register) in cpu.gpr.iter_mut().enumerate() { + if index != Register::Rsp as usize { + *register = 0x0101_0101_0101_0101 * (index as u64 + 1); + } + } + for (register, value) in [Register::Rcx, Register::Rdx, Register::R8, Register::R9] + .into_iter() + .zip(args) + { + cpu.set(register, *value); + } + for (index, register) in cpu.xmm.iter_mut().enumerate() { + *register = 0x1111_2222_3333_4444_5555_6666_7777_0000 + index as u128; + } + cpu.xmm[..4].copy_from_slice(&self.xmm); + let before = cpu.clone(); + let result = self.engine.run(&mut cpu, &mut self.memory, 8); + if result.exit_reason == ExitReason::Halt { + use Register::{R12, R13, R14, R15, Rbp, Rbx, Rdi, Rsi, Rsp}; + for register in [Rbx, Rbp, Rdi, Rsi, Rsp, R12, R13, R14, R15] { + assert_eq!( + cpu.get(register), + before.get(register), + "{symbol} {register:?}" + ); + } + assert_eq!(cpu.xmm[6..], before.xmm[6..], "{symbol}"); + assert_eq!(cpu.mxcsr, before.mxcsr, "{symbol}"); + } + (cpu, result.exit_reason) + } + + fn call(&mut self, symbol: &str, args: &[u64]) -> u64 { + let (cpu, exit) = self.run(symbol, args); + assert_eq!(exit, ExitReason::Halt, "{symbol}"); + cpu.get(Register::Rax) + } + + fn last_error(&mut self) -> u64 { + self.call("GetLastError", &[]) + } +} + +const PROCESS: u64 = u64::MAX; +const THREAD: u64 = u64::MAX - 1; + +#[test] +fn identity_services_return_documented_pseudo_handles_and_ids() { + let mut guest = Guest::new(); + assert_eq!(guest.call("GetCurrentProcess", &[]), PROCESS); + assert_eq!(guest.call("GetCurrentThread", &[]), THREAD); + let id = guest.call("GetCurrentProcessId", &[]); + assert!(id != 0 && id <= u64::from(u32::MAX)); + assert_ne!(guest.call("GetCurrentThreadId", &[]), id); + assert_eq!(guest.call("GetProcessId", &[PROCESS]), id); + assert_eq!(guest.call("GetProcessId", &[THREAD]), 0); + assert_eq!(guest.last_error(), 6); // ERROR_INVALID_HANDLE +} + +#[test] +fn priority_boost_round_trips_and_checks_its_handle() { + let mut guest = Guest::new(); + let read = |guest: &mut Guest| { + guest.memory.write_u64(SCRATCH, u64::MAX).unwrap(); + assert_eq!( + guest.call("GetProcessPriorityBoost", &[PROCESS, SCRATCH]), + 1 + ); + // A BOOL is four bytes; the next four stay untouched. + assert_eq!(guest.memory.read_u32(SCRATCH + 4).unwrap(), u32::MAX); + guest.memory.read_u32(SCRATCH).unwrap() + }; + assert_eq!(read(&mut guest), 0); + // Any nonzero BOOL disables; bits above 32 are not part of the argument. + assert_eq!( + guest.call("SetProcessPriorityBoost", &[PROCESS, 0xFFFF_FFFF_0000_0002]), + 1 + ); + assert_eq!(read(&mut guest), 1); + assert_eq!( + guest.call("SetProcessPriorityBoost", &[PROCESS, 0xFFFF_FFFF_0000_0000]), + 1 + ); + assert_eq!(read(&mut guest), 0); + assert_eq!(guest.call("SetProcessPriorityBoost", &[THREAD, 1]), 0); + assert_eq!(guest.last_error(), 6); + assert_eq!( + guest.call("GetProcessPriorityBoost", &[PROCESS, 0x9000_0000]), + 0 + ); + assert_eq!(guest.last_error(), 998); // ERROR_NOACCESS +} + +#[test] +fn thread_handles_check_access_and_are_rejected_once_closed() { + let mut guest = Guest::new(); + let id = guest.call("GetCurrentThreadId", &[]); + // THREAD_QUERY_INFORMATION only. + let query = guest.call("OpenThread", &[0x40, 0, id]); + assert_ne!(query, 0); + assert_eq!(guest.call("GetThreadPriority", &[query]), 0); + assert_eq!(guest.call("SetThreadPriority", &[query, 1]), 0); + assert_eq!(guest.last_error(), 5); // ERROR_ACCESS_DENIED + assert_eq!(guest.call("GetThreadPriority", &[query]), 0); + // THREAD_SET_INFORMATION | THREAD_QUERY_INFORMATION. + let full = guest.call("OpenThread", &[0x60, 0, id]); + assert_ne!(full, query); + // A negative int is returned in EAX with the upper half clear. + assert_eq!( + guest.call("SetThreadPriority", &[full, 0xABCD_0000_FFFF_FFFE]), + 1 + ); + assert_eq!(guest.call("GetThreadPriority", &[full]), 0xFFFF_FFFE); + assert_eq!(guest.call("SetThreadPriority", &[full, 3]), 0); + assert_eq!(guest.last_error(), 87); // ERROR_INVALID_PARAMETER + assert_eq!(guest.call("CloseHandle", &[full]), 1); + assert_eq!(guest.call("GetThreadPriority", &[full]), 0x7FFF_FFFF); + assert_eq!(guest.last_error(), 6); + assert_eq!(guest.call("CloseHandle", &[full]), 0); + assert_eq!(guest.call("OpenThread", &[0x40, 0, id + 1]), 0); + assert_eq!(guest.last_error(), 87); + assert_eq!(guest.call("OpenThread", &[0x40, 1, id]), 0); + assert_eq!(guest.last_error(), 50); // ERROR_NOT_SUPPORTED + assert_ne!( + guest.call("OpenThread", &[0x40, 0, id]), + full, + "handles are not reused" + ); +} + +#[test] +fn system_time_comes_from_the_injected_clock() { + let mut guest = Guest::new(); + guest.call("GetSystemTimeAsFileTime", &[SCRATCH + 3]); + assert_eq!( + guest.memory.read_u64(SCRATCH + 3).unwrap(), + 0x01DA_0000_1234_5678 + ); + guest.clock.advance(10); + guest.call("GetSystemTimeAsFileTime", &[SCRATCH]); + assert_eq!( + guest.memory.read_u64(SCRATCH).unwrap(), + 0x01DA_0000_1234_5682 + ); + for pointer in [0, SCRATCH + 0xFC] { + let before = guest.memory.read_u32(SCRATCH + 0xFC).unwrap(); + let (_, exit) = guest.run("GetSystemTimeAsFileTime", &[pointer]); + assert!(matches!(exit, ExitReason::MemoryFault(_)), "{exit:?}"); + assert_eq!(guest.memory.read_u32(SCRATCH + 0xFC).unwrap(), before); + } +} + +#[test] +fn last_error_is_set_by_failures_and_by_the_guest() { + let mut guest = Guest::new(); + assert_eq!(guest.last_error(), 0); + guest.call("SetLastError", &[0xFFFF_FFFF_8000_0001]); + assert_eq!(guest.last_error(), 0x8000_0001); + assert_eq!(guest.call("GetCurrentProcess", &[]), PROCESS); + assert_eq!( + guest.last_error(), + 0x8000_0001, + "success leaves it unchanged" + ); + guest.call("CloseHandle", &[0x1234]); + assert_eq!(guest.last_error(), 6); +} + +#[test] +fn virtual_memory_is_mapped_released_and_bounded() { + let mut guest = Guest::new(); + const COMMIT_RESERVE: u64 = 0x3000; + const RELEASE: u64 = 0x8000; + let address = guest.call("VirtualAlloc", &[0, 5000, COMMIT_RESERVE, 0x04]); + assert!(address != 0 && address.is_multiple_of(0x1_0000)); + assert_eq!( + guest.memory.read_u64(address + 8184).unwrap(), + 0, + "zeroed, whole pages" + ); + assert!(guest.memory.read_u8(address + 8192).is_err()); + guest.memory.write_u64(address, 7).unwrap(); + for (args, error) in [ + ([0, 0, COMMIT_RESERVE, 0x04], 87), + ([0, 4096, 0x1000, 0x04], 50), + ([0, 4096, COMMIT_RESERVE, 0x40], 87), + ([address, 4096, COMMIT_RESERVE, 0x04], 487), + ([0, u64::MAX, COMMIT_RESERVE, 0x04], 87), + ([0, 1 << 40, COMMIT_RESERVE, 0x04], 8), + ] { + assert_eq!(guest.call("VirtualAlloc", &args), 0, "{args:x?}"); + assert_eq!(guest.last_error(), error, "{args:x?}"); + } + for (args, error) in [ + ([address, 4096, RELEASE], 87), + ([address, 0, 0x4000], 50), + ([address + 4096, 0, RELEASE], 487), + ] { + assert_eq!(guest.call("VirtualFree", &args), 0, "{args:x?}"); + assert_eq!(guest.last_error(), error, "{args:x?}"); + } + assert_eq!(guest.call("VirtualFree", &[address, 0, RELEASE]), 1); + assert!(guest.memory.read_u8(address).is_err()); + assert_eq!(guest.call("VirtualFree", &[address, 0, RELEASE]), 0); +} + +#[test] +fn floating_arguments_and_results_use_xmm_registers() { + let mut guest = Guest::new(); + let mut float = |symbol: &str, bits: u64| { + // Only the low lane is the argument, and RCX must be ignored. + guest.xmm[0] = 0xFFFF_FFFF_FFFF_FFFF << 64 | u128::from(bits); + let (cpu, exit) = guest.run(symbol, &[0x4022_0000_0000_0000]); + assert_eq!(exit, ExitReason::Halt); + cpu.xmm[0] + }; + assert_eq!( + float("sqrt", 0x4030_0000_0000_0000) as u64, + 0x4010_0000_0000_0000 + ); // 16 -> 4 + assert_eq!( + float("sqrt", 0x4000_0000_0000_0000) as u64, + 0x3FF6_A09E_667F_3BCD + ); // sqrt 2 + assert_eq!( + float("sqrt", 0x8000_0000_0000_0000) as u64, + 0x8000_0000_0000_0000 + ); // -0 + assert_eq!( + float("sqrt", 0x7FF0_0000_0000_0000) as u64, + 0x7FF0_0000_0000_0000 + ); + let nan = float("sqrt", 0xBFF0_0000_0000_0000) as u64; + assert!(f64::from_bits(nan).is_nan()); + assert_eq!( + float("fabs", 0xC004_0000_0000_0000) as u64, + 0x4004_0000_0000_0000 + ); // -2.5 + assert_eq!(float("fabs", 0x8000_0000_0000_0000) as u64, 0); + let garbage = 0xDEAD_BEEF_0000_0000; + assert_eq!(float("sqrtf", garbage | 0x4110_0000) as u32, 0x4040_0000); // 9 -> 3 + assert_eq!(float("fabsf", garbage | 0xBF80_0000) as u32, 0x3F80_0000); // -1 +} + +#[test] +fn arguments_are_assigned_by_position_and_read_the_stack_after_the_fourth() { + let mut memory = GuestMemory::new(); + memory + .map_region(STACK, 0x1000, MemoryPermissions::READ_WRITE) + .unwrap(); + // [RSP] return address, 32 bytes of shadow space, then arguments 4 and 5. + memory + .write_u64(STACK_TOP + 40, 0x1122_3344_5566_7788) + .unwrap(); + memory + .write_u64(STACK_TOP + 48, 0x4008_0000_0000_0000) + .unwrap(); + let mut cpu = CpuState::new(0, STACK_TOP); + for (index, register) in [Register::Rcx, Register::Rdx, Register::R8, Register::R9] + .into_iter() + .enumerate() + { + cpu.set(register, 0xFFFF_FFFF_0000_0010 + index as u64); + cpu.xmm[index] = (1 << 100) + 0xAAAA_AAAA_0000_0020 + index as u128; + } + let args = Win64Args::new(&cpu); + let call = Call::new(&args, &cpu, &memory); + assert_eq!(call.u32(0), Ok(0x10)); + assert_eq!(call.f64(1), Ok(Float64(0xAAAA_AAAA_0000_0021))); + assert_eq!(call.f32(2), Ok(Float32(0x22))); + assert_eq!(call.u64(3), Ok(0xFFFF_FFFF_0000_0013)); + assert_eq!(call.i32(4), Ok(0x5566_7788)); + assert_eq!(call.f64(5), Ok(Float64(0x4008_0000_0000_0000))); + cpu.set(Register::Rsp, STACK + 0xFF0); + let args = Win64Args::new(&cpu); + let call = Call::new(&args, &cpu, &memory); + assert!(matches!(call.u64(4), Err(ExitReason::MemoryFault(_)))); + cpu.set(Register::Rsp, u64::MAX - 8); + let args = Win64Args::new(&cpu); + assert!(Call::new(&args, &cpu, &memory).f64(4).is_err()); +} + +// --- registry ---------------------------------------------------------------- + +fn named(name: &str) -> ImportName { + ImportName::Name(name.to_owned()) +} + +#[test] +fn generated_metadata_matches_the_live_registry() { + let (registry, _) = standard(0); + for service in &SERVICES { + let descriptor = registry + .resolve(service.library, &named(service.symbol)) + .unwrap(); + assert_eq!(descriptor.status, service.status, "{}", service.symbol); + assert!(!service.tests.is_empty()); + for alias in service.aliases { + let upper = alias.to_ascii_uppercase(); + let aliased = registry.resolve(&upper, &named(service.symbol)).unwrap(); + assert!( + std::ptr::eq(aliased, descriptor), + "{alias}!{}", + service.symbol + ); + } + // Symbol names are exact, and unlisted API sets do not resolve. + assert!( + registry + .resolve( + service.library, + &named(&service.symbol.to_ascii_uppercase()) + ) + .is_none() + || service.symbol == service.symbol.to_ascii_uppercase() + ); + assert!( + registry + .resolve("api-ms-win-core-file-l1-1-0.dll", &named(service.symbol)) + .is_none() + ); + } +} + +#[test] +fn conflicting_or_invalid_registrations_are_refused() { + let handler = || Box::new(|_: &Win64Args, _: &mut CpuState, _: &mut GuestMemory| Ok(0)); + let mut registry = ImportRegistry::new(); + let mut add = |module: &str, name: ImportName| { + registry.try_register(module, name, ServiceStatus::Stub, handler()) + }; + assert_eq!(add("a.dll", named("F")), Ok(())); + assert_eq!( + add("a.dll", named("f")), + Ok(()), + "symbols are case-sensitive" + ); + assert_eq!(add("b.dll", named("F")), Ok(())); + assert!(matches!( + add("A.DLL", named("F")), + Err(RegistryError::Duplicate { .. }) + )); + assert_eq!(add("a.dll", ImportName::Ordinal(7)), Ok(())); + assert!(matches!( + add("a.dll", ImportName::Ordinal(7)), + Err(RegistryError::Duplicate { .. }) + )); + assert_eq!( + add("a.dll", named("Ordinal#7")), + Ok(()), + "a name is never an ordinal" + ); + for (module, symbol) in [("", "F"), ("a.dll", ""), ("a b.dll", "F"), ("a.dll", "F\n")] { + assert!(matches!( + add(module, named(symbol)), + Err(RegistryError::InvalidName { .. }) + )); + } + assert_eq!(registry.try_alias("set.dll", "a.dll", "F"), Ok(())); + assert_eq!( + registry.try_alias("set.dll", "a.dll", "F"), + Ok(()), + "repeating is harmless" + ); + assert!(matches!( + registry.try_alias("set.dll", "b.dll", "F"), + Err(RegistryError::Duplicate { .. }) + )); + assert!(matches!( + registry.try_alias("b.dll", "a.dll", "F"), + Err(RegistryError::Duplicate { .. }) + )); + assert!(matches!( + registry.try_alias("x.dll", "a.dll", "G"), + Err(RegistryError::UnknownTarget { .. }) + )); +} + +#[test] +#[should_panic(expected = "kernel32.dll!CloseHandle is already registered")] +fn a_host_module_cannot_replace_a_standard_service() { + let (mut registry, _) = standard(0); + registry.register("KERNEL32.dll", "CloseHandle", |_, _, _| Ok(1)); +} + +fn bind(registry: &mut ImportRegistry, image: &Image) -> (Result, GuestMemory) { + let pe = ParsedPe::parse(&image.bytes).unwrap(); + let mut memory = pe.load_into_memory(&image.bytes).unwrap().memory; + let result = registry.bind_imports(&pe, &image.bytes, BASE, &mut memory); + (result, memory) +} + +#[test] +fn an_unresolved_import_leaves_every_slot_unbound() { + let image = build(&[ + ("kernel32.dll", Symbol::Name("GetLastError")), + ("kernel32.dll", Symbol::Name("NoSuchFunction")), + ]); + let (mut registry, _) = standard(0); + let (result, memory) = bind(&mut registry, &image); + let expected = ImportError::UnresolvedImport { + module: "kernel32.dll".into(), + symbol: "NoSuchFunction".into(), + }; + assert_eq!(result, Err(expected)); + for slot in &image.slots { + let file = IDATA_RAW + (slot - IDATA_RVA) as usize; + let original = u64::from_le_bytes(image.bytes[file..file + 8].try_into().unwrap()); + assert_eq!(memory.read_u64(BASE + u64::from(*slot)).unwrap(), original); + } +} + +#[test] +fn aliases_share_a_trampoline_and_ordinals_bind_only_ordinals() { + let (mut registry, _) = standard(0); + registry + .try_register( + "o.dll", + ImportName::Ordinal(7), + ServiceStatus::Partial, + Box::new(|_, _, _| Ok(77)), + ) + .unwrap(); + let image = build(&[ + ("KERNEL32.dll", Symbol::Name("GetLastError")), + ( + "API-MS-Win-Core-ErrorHandling-L1-1-0.dll", + Symbol::Name("GetLastError"), + ), + ("O.DLL", Symbol::Ordinal(7)), + ]); + let (result, memory) = bind(&mut registry, &image); + assert_eq!(result, Ok(3)); + let slot = |index: usize| { + memory + .read_u64(BASE + u64::from(image.slots[index])) + .unwrap() + }; + assert_eq!(slot(0), slot(1)); + assert_ne!(slot(0), slot(2)); + for symbol in [Symbol::Name("Ordinal#7"), Symbol::Ordinal(8)] { + let (result, _) = bind(&mut registry, &build(&[("o.dll", symbol)])); + assert!( + matches!(result, Err(ImportError::UnresolvedImport { .. })), + "{result:?}" + ); + } +} + +/// A registry with one service bound, and its trampoline address. +fn bound_service(handler: F) -> (ImportRegistry, GuestMemory, u64) +where + F: Fn(&Win64Args, &mut CpuState, &mut GuestMemory) -> Result + + Send + + Sync + + 'static, +{ + let mut registry = ImportRegistry::new(); + registry.register("t.dll", "F", handler); + let image = build(&[("t.dll", Symbol::Name("F"))]); + let (result, mut memory) = bind(&mut registry, &image); + assert_eq!(result, Ok(1)); + memory + .map_region(STACK, 0x1000, MemoryPermissions::READ_WRITE) + .unwrap(); + memory.write_u64(STACK_TOP, 0x1234).unwrap(); + let trampoline = memory.read_u64(BASE + u64::from(image.slots[0])).unwrap(); + (registry, memory, trampoline) +} + +#[test] +fn a_service_that_changes_a_nonvolatile_register_stops_the_guest() { + use Register::{R8, R9, R10, R11, R12, R13, R14, R15, Rbp, Rbx, Rcx, Rdi, Rdx, Rsi, Rsp}; + let dispatch = |change: fn(&mut CpuState, usize), which: usize| { + let (registry, mut memory, trampoline) = bound_service(move |_, cpu, _| { + change(cpu, which); + Ok(5) + }); + let mut cpu = CpuState::new(trampoline, STACK_TOP); + let result = registry.dispatch(trampoline, &mut cpu, &mut memory); + (result, cpu) + }; + for register in [Rbx, Rbp, Rdi, Rsi, Rsp, R12, R13, R14, R15] { + let (result, _) = dispatch(|cpu, index| cpu.gpr[index] ^= 8, register as usize); + assert_eq!(result, Err(ExitReason::ServiceAbiViolation), "{register:?}"); + } + for register in [Rcx, Rdx, R8, R9, R10, R11] { + let (result, cpu) = dispatch(|cpu, index| cpu.gpr[index] ^= 8, register as usize); + assert_eq!(result, Ok(()), "{register:?}"); + assert_eq!( + (cpu.rip, cpu.get(Rsp), cpu.get(Register::Rax)), + (0x1234, STACK_TOP + 8, 5) + ); + } + for index in 0..16 { + let (result, _) = dispatch(|cpu, index| cpu.xmm[index] ^= 1 << 127, index); + let expected = if index < 6 { + Ok(()) + } else { + Err(ExitReason::ServiceAbiViolation) + }; + assert_eq!(result, expected, "xmm{index}"); + } +} + +#[test] +fn a_call_that_cannot_return_runs_no_service() { + let calls = Arc::new(AtomicUsize::new(0)); + let counter = calls.clone(); + let (registry, mut memory, trampoline) = bound_service(move |_, _, _| { + counter.fetch_add(1, Ordering::SeqCst); + Ok(0) + }); + for rsp in [0x9000_0000, STACK + 0xFFC, u64::MAX - 7] { + let mut cpu = CpuState::new(trampoline, rsp); + let before = cpu.clone(); + assert!( + registry + .dispatch(trampoline, &mut cpu, &mut memory) + .is_err() + ); + assert_eq!(cpu, before); + } + assert_eq!(calls.load(Ordering::SeqCst), 0); + let mut cpu = CpuState::new(trampoline, STACK_TOP); + assert_eq!(registry.dispatch(trampoline, &mut cpu, &mut memory), Ok(())); + assert_eq!(calls.load(Ordering::SeqCst), 1); +} + +// --- import table -------------------------------------------------------------- + +fn inspect(image: &Image) -> ProbeReport { + probe_pe_bytes(&image.bytes, &ProbeConfig::default()).unwrap() +} + +/// File offset of an RVA in the import section. +fn file(rva: u32) -> usize { + IDATA_RAW + (rva - IDATA_RVA) as usize +} + +fn u32_at(image: &Image, at: usize) -> u32 { + u32::from_le_bytes(image.bytes[at..at + 4].try_into().unwrap()) +} + +#[test] +fn malformed_import_tables_are_reported_and_never_bound() { + let base = || { + build(&[ + ("kernel32.dll", Symbol::Name("GetLastError")), + ("kernel32.dll", Symbol::Name("CloseHandle")), + ]) + }; + let end = IDATA_RVA + IDATA_LEN as u32; + let second = IDATA_RAW + 20; + type Damage = fn(&mut Image, usize, u32); + type Expected = fn(&ImportTableError) -> bool; + // (damage to the second descriptor, expected error) + let cases: &[(&str, Damage, Expected)] = &[ + ( + "name runs off the section (issue #270)", + |image, second, end| { + let lookup = u32_at(image, second); + image.bytes[file(lookup)..file(lookup) + 8] + .copy_from_slice(&u64::from(end - 6).to_le_bytes()); + let at = file(end - 4); + image.bytes[at..at + 4].copy_from_slice(b"Name"); + }, + |error| matches!(error, ImportTableError::MalformedName { .. }), + ), + ( + "name pointer at the last byte", + |image, second, end| { + let lookup = u32_at(image, second); + image.bytes[file(lookup)..file(lookup) + 8] + .copy_from_slice(&u64::from(end - 1).to_le_bytes()); + }, + |error| matches!(error, ImportTableError::MalformedName { .. }), + ), + ( + "empty name", + |image, second, _| { + let lookup = u32_at(image, second); + let hint = u32_at(image, file(lookup)); + image.bytes[file(hint) + 2] = 0; + }, + |error| matches!(error, ImportTableError::MalformedName { .. }), + ), + ( + "non-ASCII name", + |image, second, _| { + let lookup = u32_at(image, second); + let hint = u32_at(image, file(lookup)); + image.bytes[file(hint) + 4] = 0xC3; + }, + |error| matches!(error, ImportTableError::MalformedName { .. }), + ), + ( + "module name outside every section", + |image, second, _| { + image.bytes[second + 12..second + 16].copy_from_slice(&0x7000_0000u32.to_le_bytes()) + }, + |error| matches!(error, ImportTableError::MalformedName { .. }), + ), + ( + "lookup table outside every section", + |image, second, _| { + image.bytes[second..second + 4].copy_from_slice(&u32::MAX.to_le_bytes()) + }, + |error| matches!(error, ImportTableError::OutOfBounds { .. }), + ), + ( + "reserved bits in a name entry", + |image, second, _| { + let lookup = u32_at(image, second); + image.bytes[file(lookup) + 5] = 1; + }, + |error| matches!(error, ImportTableError::ReservedBits { .. }), + ), + ( + "bit 31 in a name entry", + |image, second, _| { + let lookup = u32_at(image, second); + image.bytes[file(lookup) + 3] |= 0x80; + }, + |error| matches!(error, ImportTableError::ReservedBits { .. }), + ), + ( + "name continues in bytes after the section", + |image, second, end| { + let lookup = u32_at(image, second); + image.bytes[file(lookup)..file(lookup) + 8] + .copy_from_slice(&u64::from(end - 6).to_le_bytes()); + let at = file(end - 4); + image.bytes[at..at + 4].copy_from_slice(b"Name"); + image.bytes.extend_from_slice(b"Tail\0"); + }, + |error| matches!(error, ImportTableError::MalformedName { .. }), + ), + ( + "reserved bits in an ordinal entry", + |image, second, _| { + let lookup = u32_at(image, second); + image.bytes[file(lookup)..file(lookup) + 8] + .copy_from_slice(&(1u64 << 63 | 0x1_0000).to_le_bytes()); + }, + |error| matches!(error, ImportTableError::ReservedBits { .. }), + ), + ]; + for (what, damage, expected) in cases { + let mut image = base(); + damage(&mut image, second, end); + let (mut registry, _) = standard(0); + let (result, _) = bind(&mut registry, &image); + match &result { + Err(ImportError::Table(error)) => assert!(expected(error), "{what}: {error:?}"), + other => panic!("{what}: {other:?}"), + } + let report = inspect(&image); + assert_eq!( + report.import_error.map(ImportError::Table), + result.err(), + "{what}" + ); + assert_eq!( + report.imports.len(), + 1, + "{what}: the first import is still listed" + ); + assert_eq!(report.imports[0].symbol, "GetLastError"); + } +} + +#[test] +fn endless_tables_are_bounded() { + // A descriptor at 0, a module name at 0x40, a hint and name at 0x60 and a + // lookup entry at 0x80. The mapping repeats one structure without end. + let mut bytes = vec![0u8; 0x88]; + bytes[0..4].copy_from_slice(&0x80u32.to_le_bytes()); + bytes[12..16].copy_from_slice(&0x40u32.to_le_bytes()); + bytes[16..20].copy_from_slice(&0x80u32.to_le_bytes()); + bytes[0x40..0x46].copy_from_slice(b"m.dll\0"); + bytes[0x62..0x64].copy_from_slice(b"F\0"); + bytes[0x80] = 0x60; + + // Lookup entries repeat from 0x80 on. + let (entries, error) = parse_imports(&bytes, 0, |rva| { + let rva = rva as usize; + Some(if rva < 0x80 { rva } else { 0x80 + rva % 8 }) + }); + assert_eq!(error, Some(ImportTableError::TooManyImports)); + assert_eq!(entries.len(), MAX_IMPORTS); + + // Descriptors repeat from 0x1000 on; each has one symbol. + bytes.extend([0; 8]); + let (entries, error) = parse_imports(&bytes, 0x1000, |rva| { + let rva = rva as usize; + Some(if rva < 0x1000 { + rva + } else { + (rva - 0x1000) % 20 + }) + }); + assert_eq!(error, Some(ImportTableError::TooManyDescriptors)); + assert_eq!(entries.len(), 1024); +} + +#[test] +fn inspection_and_binding_agree_on_damaged_tables() { + let base = build(&[ + ("kernel32.dll", Symbol::Name("GetLastError")), + ( + "api-ms-win-core-handle-l1-1-0.dll", + Symbol::Name("CloseHandle"), + ), + ("ucrtbase.dll", Symbol::Name("sqrt")), + ("o.dll", Symbol::Ordinal(3)), + ]); + let mut state = 0x2545_F491_4F6C_DD1Du64; + let mut next = || { + state ^= state >> 12; + state ^= state << 25; + state ^= state >> 27; + state.wrapping_mul(0x9E37_79B9_7F4A_7C15) + }; + let (mut bound, mut malformed, mut unresolved) = (0, 0, 0); + for _ in 0..6000 { + let mut image = Image { + bytes: base.bytes.clone(), + slots: base.slots.clone(), + }; + for _ in 0..1 + next() % 3 { + let at = IDATA_RAW + (next() % 0x220) as usize; + image.bytes[at] = match next() % 4 { + 0 => 0, + 1 => 0xFF, + _ => next() as u8, + }; + } + let (mut registry, _) = standard(0); + registry + .try_register( + "o.dll", + ImportName::Ordinal(3), + ServiceStatus::Stub, + Box::new(|_, _, _| Ok(0)), + ) + .unwrap(); + let pe = ParsedPe::parse(&image.bytes).unwrap(); + let mut memory = pe.load_into_memory(&image.bytes).unwrap().memory; + let result = registry.bind_imports(&pe, &image.bytes, BASE, &mut memory); + let report = inspect(&image); + match result { + Ok(count) => { + bound += 1; + assert_eq!(report.import_error, None); + assert_eq!(report.imports.len(), count); + } + Err(ImportError::Table(error)) => { + malformed += 1; + assert_eq!(report.import_error, Some(error)); + } + Err(ImportError::UnresolvedImport { module, symbol }) => { + unresolved += 1; + assert_eq!(report.import_error, None); + assert!( + report + .imports + .iter() + .any(|import| import.dll == module && import.symbol == symbol) + ); + } + Err(ImportError::Memory(_)) => {} + } + } + assert!( + bound > 100 && malformed > 100 && unresolved > 100, + "{bound} {malformed} {unresolved}" + ); +} + +#[test] +fn inspection_reports_exactly_what_binding_resolves() { + let image = build(&[ + ("KERNEL32.dll", Symbol::Name("GetLastError")), + ("kernel32.dll", Symbol::Name("getlasterror")), + ( + "api-ms-win-core-errorhandling-l1-1-0.dll", + Symbol::Name("SetLastError"), + ), + ( + "api-ms-win-core-errorhandling-l1-1-3.dll", + Symbol::Name("SetLastError"), + ), + ("kernel32.dll", Symbol::Ordinal(1)), + ]); + let report = inspect(&image); + let supported: Vec = report + .imports + .iter() + .map(|import| import.is_supported) + .collect(); + assert_eq!(supported, [true, false, true, false, false]); + assert_eq!( + report.imports[2].canonical_module.as_deref(), + Some("kernel32.dll") + ); + assert_eq!(report.imports[4].symbol, "Ordinal#1"); +} diff --git a/docs/README.md b/docs/README.md index 3fbeae9..1efd494 100644 --- a/docs/README.md +++ b/docs/README.md @@ -32,6 +32,7 @@ either path. The [changelog](../CHANGELOG.md) records notable changes. - [Guest experiment guide](../experiments/x1/README.md) — Bounded x86-64 execution, executable loading, experimental services, native compute, and offscreen rendering. - [x86-64 instruction registry](cpu/instruction-registry.md) — Shared decoder, generated tables, semantics, native lowering and how to add a verified instruction form. +- [Runtime service registry](runtime/registry.md) and [generated coverage](runtime/services.md) — Import resolution, typed Win64 adapters and how to add a tested service. - [Guest CPU research](research/cpu-boundary.md) — Public specifications and unresolved console requirements. - [Synthetic import fixtures](../tests/compat_fixtures/README.md) — Reproducible PE32+ builds and expected service behavior. diff --git a/docs/coordination/cpu-campaign-ledger.md b/docs/coordination/cpu-campaign-ledger.md index 421de07..7ce21ce 100644 --- a/docs/coordination/cpu-campaign-ledger.md +++ b/docs/coordination/cpu-campaign-ledger.md @@ -23,6 +23,7 @@ Evidence below is local to the named host unless stated. Nothing here is indepen | 2 | cpu: share one generated decoder and store guest flags | Registry, generator, shared decoder and semantics, integer expansion, architectural DBT flags, truthful probe support | `tests/x86_integer.rs`, `tests/arm64_encodings.rs`, `tests/x86_generator`; 37 targeted mutations: 36 caught (4 only after new tests), and one equivalent, whose redundant check was removed | | 3 | cpu: add SSE2 state, moves and packed integer forms | XMM and MXCSR state, mandatory prefixes, SSE/SSE2 moves and packed integer operations, NEON lowering | `tests/x86_vector.rs` (9 tests, 374 LLVM-assembled instructions, 64 states each), `tests/arm64_encodings.rs`; 35 targeted mutations: 34 caught (1 only after a new test) and one equivalent | | 4 | cpu: add exact SSE and SSE2 floating point | Software binary32/binary64 arithmetic with MXCSR, compares and conversions | `tests/x86_float.rs` (9 tests, 6,824 exact-fraction vectors, 172 LLVM-assembled instructions, over 2 million host comparisons); 53 targeted mutations: 52 caught (2 only after directed vectors), and one changes a rule deliberately left unasserted | +| 5 | runtime: one import resolver and typed service adapters | Bounded import parser shared by probe and binder, strict registry, transactional binding, Win64 preservation check, typed registry and generator, 20 services | `tests/runtime_services.rs` (19 tests; every service is called by translated guest code), generator unit tests (4); 33 valid targeted mutations: all caught, 2 only after new cases | Encodings: `clang -target x86_64-apple-macos -c` and `clang -target arm64-apple-macos -c`, read back with `objdump -d`. @@ -76,12 +77,36 @@ The registry now has 191 operations, 358 forms and 453 opcode slots. `dbt_bench` Main moved to 15 commits past this branch after milestone 3; they do not touch `crates/loader` and are not merged yet. +## Verification of milestone 5 (local, real exit codes) + +Main `f685ede` (QA tooling) was merged first as `5e7c21b`. + +| Gate | Result | +| --- | --- | +| Formatting; strict Clippy, workspace, all targets and features | exit 0; exit 0 | +| `cargo test --locked --workspace --no-fail-fast` | exit 0: 462 passed, 0 failed, 22 ignored | +| `xenora-runtime-gen --check`; CPU generator, assembler and float reference checks; generator tests | exit 0 | +| RDNA2 metadata, semantic registry, coverage and status checks; their Python tests; claims, dependencies and native audits; release build | exit 0 | +| `scripts/test-gpu.sh`, `demo.sh`, `build-app.sh`, `--smoke-frame`, `--inspect` | exit 0; GPU 74 passed, 0 failed, 1 ignored | +| `scripts/assemble-fixture.sh --check` and ignored LLVM AMDGPU tests | not verified: need `llvm-mc` | +| Fuzz and mutation campaigns | not run | + +`dbt_bench`, middle of three runs: interpreter 11.08, cold DBT 8.48 and warm DBT 409.65 MIPS. Warm runs read 392 to 417, against 430 for milestone 4; no change here is known to affect that path and the cause was not investigated. + +The panic of #270 was reproduced on `5e7c21b` (`range start index 1025 out of range`) and does not occur after this milestone. + +## Overlap with upstream (needs coordination) + +- #65, #66 and #72 were claimed by another contributor, and #283, #281 and #280 merged into main (`c6a354b`) while this branch was unpublished. Milestones 1 and 2 cover the same ground, so `cpu.rs`, `dbt.rs` and `arm64.rs` now conflict. This branch claims none of those issues. +- #286 is open for #270, which milestone 5 also fixes. Theirs is published and takes precedence. + ## Known limitations - Only the forms in `x86/instructions.toml` exist. The RCP and RSQRT approximations, SSE3 and later, MMX, VEX, string instructions, RCL, RCR, SHLD, SHRD, LOCK, fences and atomics are unsupported. - Every floating-point form runs through software arithmetic in the DBT; none is lowered to NEON. No x86 hardware comparison exists, and `docs/cpu/instruction-registry.md` lists the choices left unasserted. - Packs, shuffles, high multiplies, PSADBW, sign-mask extraction, word insertion and extraction, byte shifts and shifts by a register count run through the shared semantics in the DBT. -- XMM6-XMM15 preservation across Win64 service calls has no test yet. +- The fixture graphics services, `XMemAlloc` and the `XMemFree` stub are outside the typed registry. Several older generated conformance tests check Rust library functions, not services. +- Last error is one value per process; per-thread isolation (#202) waits for guest threads. - 8- and 16-bit ALU operations, shifts, MUL, DIV and bit operations run through the shared semantics in the DBT, not as ARM64. - The reference and the implementation share an author. - New CPU checks are not in CI; `.github` was left unchanged. @@ -93,4 +118,4 @@ Main moved to 15 commits past this branch after milestone 3; they do not touch ` ## Next task -Runtime resolution and typed import metadata: one lookup for execution and static inspection, conflict detection and truthful unsupported diagnostics. Then Win64 ABI checks, including XMM6-XMM15 across service calls. Nothing in those areas is started. +Integrate main `c6a354b` with its contributor: keep upstream's regression tests, resolve the three source conflicts, and agree how milestones 1 and 2 relate to the merged fixes. Then native CRT memory and string services. Those are not started. diff --git a/docs/runtime/registry.md b/docs/runtime/registry.md new file mode 100644 index 0000000..81d3e32 --- /dev/null +++ b/docs/runtime/registry.md @@ -0,0 +1,29 @@ +# Runtime service registry + +Guest imports resolve through one lookup, `ImportRegistry::resolve`. Binding, the static probe and the command-line reports all use it, and they read the import directory with one bounded parser, `import_table::parse_imports`. + +| Part | File | Role | +| --- | --- | --- | +| Registry | `crates/loader/runtime/services.txt` | Library, symbol, typed signature, API-set aliases, failure contract, status, reference and tests. Data only. | +| Generator | `xenora-runtime-gen` in `crates/import-gen` | `validate`, `generate` and `--check`. Rejects conflicting keys, unlisted API sets, unsupported types, and behaviour without a named, existing test. | +| Adapters | `crates/loader/src/runtime_table.rs` | Generated Win64 argument and result adapters and static metadata. | +| Handlers | `handlers` in `crates/loader/src/services.rs` | Rust implementations. They see guest memory and service state, never the CPU. | +| Report | [services.md](services.md) | Generated counts. Aliases are counted apart from services. | + +## Rules + +- Module names compare without case; symbol names are exact. A name spelled `Ordinal#7` is not ordinal 7. +- An API set resolves only if the registry lists that exact set for that symbol. A similar name forwards nowhere. +- Registering a key twice is an error. A host module cannot replace a standard service. +- Binding resolves every import before it writes any slot. A malformed table or an unresolved import leaves every slot unbound. +- A service call reads its return address first, and stops the guest with `ServiceAbiViolation` if the service changed a nonvolatile register, including XMM6 to XMM15. + +## Adding a service + +1. Write a test in `crates/loader/tests/runtime_services.rs` that calls it from guest code and derives its expectations from the public documentation. +2. Add the entry to `services.txt` and the handler to `services.rs`. +3. Run `cargo run -p xenora-import-gen --bin xenora-runtime-gen generate`. + +## Outside this registry + +The fixture graphics services, `XMemAlloc` and the `XMemFree` stub are still registered by hand. The older import-list generator in `crates/import-gen` is separate: its output is not compiled into the loader, and several of its generated conformance tests check Rust library functions rather than a service. diff --git a/docs/runtime/services.md b/docs/runtime/services.md new file mode 100644 index 0000000..009bfaa --- /dev/null +++ b/docs/runtime/services.md @@ -0,0 +1,40 @@ +# Typed runtime services + +Generated by `xenora-runtime-gen` from `crates/loader/runtime/services.txt`. Do not edit. + +A declared service is not a claim of compatibility. `implemented` and `partial` describe behaviour against the documented contract for the synthetic guest. No service has been independently accepted. + +| Measure | Count | +| --- | ---: | +| Services with a declared ABI | 20 | +| Generated adapters | 20 | +| Unique handler implementations | 20 | +| Implemented | 7 | +| Partial | 13 | +| Stub | 0 | +| Conformance-tested through guest dispatch | 20 | +| API-set aliases (not services) | 20 | +| Independently accepted | 0 | + +| Service | Signature | Status | Failure | +| --- | --- | --- | --- | +| `kernel32.dll!SetProcessPriorityBoost` | `(process: handle, disable: bool32) -> bool32` | partial | 0 with ERROR_INVALID_HANDLE | +| `kernel32.dll!GetProcessPriorityBoost` | `(process: handle, disabled: out<4>) -> bool32` | partial | 0 with ERROR_INVALID_HANDLE or ERROR_NOACCESS | +| `kernel32.dll!GetCurrentProcess` | `() -> handle` | implemented | never | +| `kernel32.dll!GetProcessId` | `(process: handle) -> u32` | partial | 0 with ERROR_INVALID_HANDLE | +| `kernel32.dll!GetCurrentThread` | `() -> handle` | implemented | never | +| `kernel32.dll!GetCurrentProcessId` | `() -> u32` | implemented | never | +| `kernel32.dll!GetCurrentThreadId` | `() -> u32` | implemented | never | +| `kernel32.dll!OpenThread` | `(access: u32, inherit: bool32, thread: u32) -> handle` | partial | 0 with ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED or ERROR_NOT_ENOUGH_MEMORY | +| `kernel32.dll!GetThreadPriority` | `(thread: handle) -> i32` | partial | THREAD_PRIORITY_ERROR_RETURN with ERROR_INVALID_HANDLE or ERROR_ACCESS_DENIED | +| `kernel32.dll!SetThreadPriority` | `(thread: handle, priority: i32) -> bool32` | partial | 0 with ERROR_INVALID_HANDLE, ERROR_ACCESS_DENIED, ERROR_NOT_SUPPORTED or ERROR_INVALID_PARAMETER | +| `kernel32.dll!CloseHandle` | `(object: handle) -> bool32` | partial | 0 with ERROR_INVALID_HANDLE | +| `kernel32.dll!GetSystemTimeAsFileTime` | `(time: out<8>) -> void` | implemented | guest fault on an invalid pointer | +| `kernel32.dll!GetLastError` | `() -> u32` | partial | never | +| `kernel32.dll!SetLastError` | `(code: u32) -> void` | partial | never | +| `kernel32.dll!VirtualAlloc` | `(address: ptr, size: u64, kind: u32, protect: u32) -> ptr` | partial | 0 with ERROR_INVALID_PARAMETER, ERROR_NOT_SUPPORTED, ERROR_INVALID_ADDRESS or ERROR_NOT_ENOUGH_MEMORY | +| `kernel32.dll!VirtualFree` | `(address: ptr, size: u64, kind: u32) -> bool32` | partial | 0 with ERROR_NOT_SUPPORTED, ERROR_INVALID_PARAMETER or ERROR_INVALID_ADDRESS | +| `ucrtbase.dll!sqrt` | `(x: f64) -> f64` | partial | NaN for a negative argument; errno is not set | +| `ucrtbase.dll!sqrtf` | `(x: f32) -> f32` | partial | NaN for a negative argument; errno is not set | +| `ucrtbase.dll!fabs` | `(x: f64) -> f64` | implemented | never | +| `ucrtbase.dll!fabsf` | `(x: f32) -> f32` | implemented | never |