From 64a0cb1596ca5225df17f09288d9e6affe7715f7 Mon Sep 17 00:00:00 2001 From: zachdoxsee Date: Tue, 24 Nov 2026 23:14:10 +0100 Subject: [PATCH 1/2] loader: add nine C runtime startup services a hosted C program imports (#382) A program built with the mingw-w64 runtime imports _set_app_type, _set_new_mode, _configthreadlocale, __setusermatherr, _set_invalid_parameter_handler, __p__fmode, __p__commode, signal and SetUnhandledExceptionFilter, and memcpy through api-ms-win-crt-private-l1-1-0.dll. None resolved, so the loader refused the program before its entry point. Each service records what it is given and returns what its public documentation says. Nothing acts on a recorded value yet, so all nine are declared partial in the typed registry. Part of Gate A2. Signed-off-by: zachdoxsee --- CHANGELOG.md | 1 + crates/loader/runtime/services.txt | 75 ++++++ crates/loader/src/runtime_table.rs | 172 ++++++++++++- crates/loader/src/services.rs | 100 ++++++++ crates/loader/src/services/crt.rs | 6 +- crates/loader/src/services/crt_startup.rs | 116 +++++++++ crates/loader/tests/runtime_services.rs | 283 +++++++++++++++++++++- docs/interfaces.md | 27 +++ docs/runtime/services.md | 21 +- 9 files changed, 789 insertions(+), 12 deletions(-) create mode 100644 crates/loader/src/services/crt_startup.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 698965f..f885da5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,7 @@ remains unsupported. - Added a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status. ### Added +- Added nine C runtime services that a C program's startup code calls or imports before `main`, and one alias (#382, part of Gate A2): `_set_app_type`, `_set_new_mode`, `_configthreadlocale`, `__setusermatherr`, `_set_invalid_parameter_handler`, `__p__fmode`, `__p__commode`, `signal` and `SetUnhandledExceptionFilter`, plus `memcpy` through `api-ms-win-crt-private-l1-1-0.dll`. A program built with the mingw-w64 runtime imports all of them, and the loader refused it before its entry point because they did not resolve. Each records what it is given and returns what its public documentation says: the previous mode, setting or handler, the documented failure value, or the address of the guest variables `_fmode` and `_commode`. All nine are declared `partial` in the typed registry because nothing acts on a recorded value: no handler or filter is ever called, no signal is raised, there is no locale, and nothing reads `_fmode` yet. `ServicesState` gains two read-only accessors, `crt_app_type` and `crt_user_math_error`. Five tests in `runtime_services.rs` call the services from guest code through a bound import table. Not compared with Windows; awaiting independent review. - `dbt_bench` can also write its results as one JSON document when `XENORA_DBT_BENCH_JSON=` is set (#112). The document records the host CPU, OS and architecture, the git revision and whether the tree had local changes, debug assertions, the workload and sample counts, the median, minimum, maximum, p95, p99, IQR and MIPS for the interpreter and for cold and warm DBT, and the cold DBT counters. Anything the benchmark cannot determine is `null`. The text output and the timed work are unchanged. - Added synthetic guest handle-lifetime regression tests (#205) for capacity reuse, stale handles, duplicate rights and lifetime, wrong object types, thread pseudo handles and failed-output nonmutation. Runtime behavior is unchanged; independent acceptance is pending. - Added a documented independent acceptance rule for promoting AMD RDNA2 desktop GPU (gfx1030) forms from local CPU and Metal results to `fixture verified`, including clean-commit evidence, reviewer independence, raw-log location, review-log summary, failure handling and status regeneration (#302). diff --git a/crates/loader/runtime/services.txt b/crates/loader/runtime/services.txt index c3fd65a..69d273c 100644 --- a/crates/loader/runtime/services.txt +++ b/crates/loader/runtime/services.txt @@ -179,3 +179,78 @@ service ucrtbase.dll fabsf(x: f32) -> f32 fails never ref math.h fabsf (ISO C, IEC 60559 abs) test floating_arguments_and_results_use_xmm_registers + +# What a C program's startup code configures before `main`. Each value is +# recorded and returned as documented; nothing in the runtime acts on it. + +service ucrtbase.dll _set_app_type(kind: i32) -> void + handler set_app_type + status partial + alias api-ms-win-crt-runtime-l1-1-0.dll + fails never + ref corecrt_startup.h _set_app_type + test crt_app_type_and_math_error_handler_are_recorded + +service ucrtbase.dll _set_new_mode(mode: i32) -> i32 + handler set_new_mode + status partial + alias api-ms-win-crt-heap-l1-1-0.dll + fails -1 with errno EINVAL for a mode other than 0 or 1 + ref new.h _set_new_mode + test crt_startup_modes_return_the_previous_setting + +service ucrtbase.dll _configthreadlocale(request: i32) -> i32 + handler configure_thread_locale + status partial + alias api-ms-win-crt-locale-l1-1-0.dll + fails -1 with errno EINVAL for a request other than 0, 1 or 2 + ref locale.h _configthreadlocale + test crt_startup_modes_return_the_previous_setting + +service ucrtbase.dll __setusermatherr(handler: ptr) -> void + handler set_user_math_error + status partial + alias api-ms-win-crt-math-l1-1-0.dll + fails never + ref corecrt_startup.h __setusermatherr + test crt_app_type_and_math_error_handler_are_recorded + +service ucrtbase.dll _set_invalid_parameter_handler(handler: ptr) -> ptr + handler set_invalid_parameter_handler + status partial + alias api-ms-win-crt-runtime-l1-1-0.dll + fails never + ref stdlib.h _set_invalid_parameter_handler + test crt_startup_handlers_return_the_previous_handler + +service ucrtbase.dll __p__fmode() -> ptr + handler file_mode_pointer + status partial + alias api-ms-win-crt-stdio-l1-1-0.dll + fails stops the guest when the variable cannot be allocated + ref Microsoft Learn, C runtime library reference, __p__fmode + test crt_file_mode_variables_are_guest_memory + +service ucrtbase.dll __p__commode() -> ptr + handler commit_mode_pointer + status partial + alias api-ms-win-crt-stdio-l1-1-0.dll + fails stops the guest when the variable cannot be allocated + ref Microsoft Learn, C runtime library reference, __p__commode + test crt_file_mode_variables_are_guest_memory + +service ucrtbase.dll signal(signal: i32, handler: ptr) -> ptr + handler signal + status partial + alias api-ms-win-crt-runtime-l1-1-0.dll + fails SIG_ERR with errno EINVAL for a signal the documentation does not list + ref signal.h signal + test crt_startup_handlers_return_the_previous_handler + +service kernel32.dll SetUnhandledExceptionFilter(filter: ptr) -> ptr + handler set_unhandled_exception_filter + status partial + alias api-ms-win-core-errorhandling-l1-1-0.dll + fails never + ref errhandlingapi.h SetUnhandledExceptionFilter + test crt_startup_handlers_return_the_previous_handler diff --git a/crates/loader/src/runtime_table.rs b/crates/loader/src/runtime_table.rs index efa48eb..85e5bd9 100644 --- a/crates/loader/src/runtime_table.rs +++ b/crates/loader/src/runtime_table.rs @@ -8,7 +8,7 @@ use crate::runtime::{Call, Parameter, Return, ServiceContext, ServiceMetadata}; use crate::services::{ServicesState, handlers}; use std::sync::Arc; -pub static SERVICES: [ServiceMetadata; 20] = [ +pub static SERVICES: [ServiceMetadata; 29] = [ ServiceMetadata { library: "kernel32.dll", symbol: "SetProcessPriorityBoost", @@ -229,6 +229,105 @@ pub static SERVICES: [ServiceMetadata; 20] = [ reference: "math.h fabsf (ISO C, IEC 60559 abs)", tests: &["floating_arguments_and_results_use_xmm_registers"], }, + ServiceMetadata { + library: "ucrtbase.dll", + symbol: "_set_app_type", + parameters: &[Parameter { name: "kind", kind: "i32" }], + result: "void", + status: ServiceStatus::Partial, + aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"], + failure: "never", + reference: "corecrt_startup.h _set_app_type", + tests: &["crt_app_type_and_math_error_handler_are_recorded"], + }, + ServiceMetadata { + library: "ucrtbase.dll", + symbol: "_set_new_mode", + parameters: &[Parameter { name: "mode", kind: "i32" }], + result: "i32", + status: ServiceStatus::Partial, + aliases: &["api-ms-win-crt-heap-l1-1-0.dll"], + failure: "-1 with errno EINVAL for a mode other than 0 or 1", + reference: "new.h _set_new_mode", + tests: &["crt_startup_modes_return_the_previous_setting"], + }, + ServiceMetadata { + library: "ucrtbase.dll", + symbol: "_configthreadlocale", + parameters: &[Parameter { name: "request", kind: "i32" }], + result: "i32", + status: ServiceStatus::Partial, + aliases: &["api-ms-win-crt-locale-l1-1-0.dll"], + failure: "-1 with errno EINVAL for a request other than 0, 1 or 2", + reference: "locale.h _configthreadlocale", + tests: &["crt_startup_modes_return_the_previous_setting"], + }, + ServiceMetadata { + library: "ucrtbase.dll", + symbol: "__setusermatherr", + parameters: &[Parameter { name: "handler", kind: "ptr" }], + result: "void", + status: ServiceStatus::Partial, + aliases: &["api-ms-win-crt-math-l1-1-0.dll"], + failure: "never", + reference: "corecrt_startup.h __setusermatherr", + tests: &["crt_app_type_and_math_error_handler_are_recorded"], + }, + ServiceMetadata { + library: "ucrtbase.dll", + symbol: "_set_invalid_parameter_handler", + parameters: &[Parameter { name: "handler", kind: "ptr" }], + result: "ptr", + status: ServiceStatus::Partial, + aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"], + failure: "never", + reference: "stdlib.h _set_invalid_parameter_handler", + tests: &["crt_startup_handlers_return_the_previous_handler"], + }, + ServiceMetadata { + library: "ucrtbase.dll", + symbol: "__p__fmode", + parameters: &[], + result: "ptr", + status: ServiceStatus::Partial, + aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"], + failure: "stops the guest when the variable cannot be allocated", + reference: "Microsoft Learn, C runtime library reference, __p__fmode", + tests: &["crt_file_mode_variables_are_guest_memory"], + }, + ServiceMetadata { + library: "ucrtbase.dll", + symbol: "__p__commode", + parameters: &[], + result: "ptr", + status: ServiceStatus::Partial, + aliases: &["api-ms-win-crt-stdio-l1-1-0.dll"], + failure: "stops the guest when the variable cannot be allocated", + reference: "Microsoft Learn, C runtime library reference, __p__commode", + tests: &["crt_file_mode_variables_are_guest_memory"], + }, + ServiceMetadata { + library: "ucrtbase.dll", + symbol: "signal", + parameters: &[Parameter { name: "signal", kind: "i32" }, Parameter { name: "handler", kind: "ptr" }], + result: "ptr", + status: ServiceStatus::Partial, + aliases: &["api-ms-win-crt-runtime-l1-1-0.dll"], + failure: "SIG_ERR with errno EINVAL for a signal the documentation does not list", + reference: "signal.h signal", + tests: &["crt_startup_handlers_return_the_previous_handler"], + }, + ServiceMetadata { + library: "kernel32.dll", + symbol: "SetUnhandledExceptionFilter", + parameters: &[Parameter { name: "filter", kind: "ptr" }], + result: "ptr", + status: ServiceStatus::Partial, + aliases: &["api-ms-win-core-errorhandling-l1-1-0.dll"], + failure: "never", + reference: "errhandlingapi.h SetUnhandledExceptionFilter", + tests: &["crt_startup_handlers_return_the_previous_handler"], + }, ]; /// Register every generated service and its API-set aliases. @@ -398,6 +497,77 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc) { let result: crate::runtime::Float32 = handlers::fabsf(&mut context, a0)?; Ok(result.place(cpu)) }); + let s = state.clone(); + registry.register_with_status("ucrtbase.dll", "_set_app_type", ServiceStatus::Partial, move |args, cpu, memory| { + let call = Call::new(args, cpu, memory); + let a0 = call.i32(0)?; + let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base }; + let () = handlers::set_app_type(&mut context, a0)?; + Ok(0) + }); + let s = state.clone(); + registry.register_with_status("ucrtbase.dll", "_set_new_mode", ServiceStatus::Partial, move |args, cpu, memory| { + let call = Call::new(args, cpu, memory); + let a0 = call.i32(0)?; + let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base }; + let result: i32 = handlers::set_new_mode(&mut context, a0)?; + Ok(result.place(cpu)) + }); + let s = state.clone(); + registry.register_with_status("ucrtbase.dll", "_configthreadlocale", ServiceStatus::Partial, move |args, cpu, memory| { + let call = Call::new(args, cpu, memory); + let a0 = call.i32(0)?; + let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base }; + let result: i32 = handlers::configure_thread_locale(&mut context, a0)?; + Ok(result.place(cpu)) + }); + let s = state.clone(); + registry.register_with_status("ucrtbase.dll", "__setusermatherr", 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, teb: cpu.gs_base }; + let () = handlers::set_user_math_error(&mut context, a0)?; + Ok(0) + }); + let s = state.clone(); + registry.register_with_status("ucrtbase.dll", "_set_invalid_parameter_handler", 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, teb: cpu.gs_base }; + let result: u64 = handlers::set_invalid_parameter_handler(&mut context, a0)?; + Ok(result.place(cpu)) + }); + let s = state.clone(); + registry.register_with_status("ucrtbase.dll", "__p__fmode", ServiceStatus::Partial, move |args, cpu, memory| { + let _ = args; + let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base }; + let result: u64 = handlers::file_mode_pointer(&mut context)?; + Ok(result.place(cpu)) + }); + let s = state.clone(); + registry.register_with_status("ucrtbase.dll", "__p__commode", ServiceStatus::Partial, move |args, cpu, memory| { + let _ = args; + let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base }; + let result: u64 = handlers::commit_mode_pointer(&mut context)?; + Ok(result.place(cpu)) + }); + let s = state.clone(); + registry.register_with_status("ucrtbase.dll", "signal", ServiceStatus::Partial, move |args, cpu, memory| { + let call = Call::new(args, cpu, memory); + let a0 = call.i32(0)?; + let a1 = call.u64(1)?; + let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base }; + let result: u64 = handlers::signal(&mut context, a0, a1)?; + Ok(result.place(cpu)) + }); + let s = state.clone(); + registry.register_with_status("kernel32.dll", "SetUnhandledExceptionFilter", 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, teb: cpu.gs_base }; + let result: u64 = handlers::set_unhandled_exception_filter(&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) { diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index 1f588ae..7430d7c 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -11,6 +11,7 @@ mod crt; mod crt_callbacks; +mod crt_startup; mod events; mod files; mod gdk_queue; @@ -195,6 +196,7 @@ pub struct ServicesState { synch: Mutex, /// Functions registered with `atexit`, run in reverse order by `_cexit`. atexit: Mutex>, + crt_startup: Mutex, winsock: Mutex, task_fixture: Mutex, platform_fixture: Mutex, @@ -218,6 +220,7 @@ impl ServicesState { last_errors: Mutex::default(), synch: Mutex::default(), atexit: Mutex::default(), + crt_startup: Mutex::default(), winsock: Mutex::default(), task_fixture: Mutex::default(), platform_fixture: Mutex::default(), @@ -275,6 +278,22 @@ impl ServicesState { } } + fn crt_startup(&self) -> std::sync::MutexGuard<'_, crt_startup::CrtStartup> { + self.crt_startup.lock().expect("C runtime startup state") + } + + /// The application type the guest passed to `_set_app_type`, zero until it + /// does. Nothing in the runtime depends on it. + pub fn crt_app_type(&self) -> i32 { + self.crt_startup().app_type() + } + + /// The guest function passed to `__setusermatherr`, zero until one is. It + /// is never called. + pub fn crt_user_math_error(&self) -> u64 { + self.crt_startup().user_math_error() + } + /// Record a guest error and return the documented failure value. fn fail(&self, teb: u64, error: u32, value: T) -> Result { self.set_last_error(teb, error); @@ -835,4 +854,85 @@ pub(crate) mod handlers { pub fn fabsf(_: &mut ServiceContext<'_>, x: Float32) -> Outcome { Ok(Float32(x.0 & !(1 << 31))) } + + // What a C program's startup code configures (#382). Each value is + // recorded and returned; `crt_startup.rs` says what does not act on it. + + pub fn set_app_type(context: &mut ServiceContext<'_>, kind: i32) -> Outcome<()> { + context.state.crt_startup().set_app_type(kind); + Ok(()) + } + + pub fn set_new_mode(context: &mut ServiceContext<'_>, mode: i32) -> Outcome { + let previous = context.state.crt_startup().set_new_mode(mode); + match previous { + Some(previous) => Ok(previous), + None => { + crt::set_errno(context.memory, context.teb, crt::EINVAL)?; + Ok(-1) + } + } + } + + pub fn configure_thread_locale(context: &mut ServiceContext<'_>, request: i32) -> Outcome { + let previous = context.state.crt_startup().configure_thread_locale(request); + match previous { + Some(previous) => Ok(previous), + None => { + crt::set_errno(context.memory, context.teb, crt::EINVAL)?; + Ok(-1) + } + } + } + + pub fn set_user_math_error(context: &mut ServiceContext<'_>, handler: u64) -> Outcome<()> { + context.state.crt_startup().set_user_math_error(handler); + Ok(()) + } + + pub fn set_invalid_parameter_handler( + context: &mut ServiceContext<'_>, + handler: u64, + ) -> Outcome { + Ok(context + .state + .crt_startup() + .set_invalid_parameter_handler(handler)) + } + + pub fn file_mode_pointer(context: &mut ServiceContext<'_>) -> Outcome { + context + .state + .crt_startup() + .file_mode_address(context.memory, 0) + } + + pub fn commit_mode_pointer(context: &mut ServiceContext<'_>) -> Outcome { + context + .state + .crt_startup() + .file_mode_address(context.memory, 1) + } + + pub fn signal(context: &mut ServiceContext<'_>, signal: i32, handler: u64) -> Outcome { + let previous = context.state.crt_startup().signal(signal, handler); + match previous { + Some(previous) => Ok(previous), + None => { + crt::set_errno(context.memory, context.teb, crt::EINVAL)?; + // SIG_ERR is (void (*)(int))-1. + Ok(u64::MAX) + } + } + } + + pub fn set_unhandled_exception_filter( + context: &mut ServiceContext<'_>, + filter: u64, + ) -> Outcome { + Ok(context + .state + .crt_startup() + .set_unhandled_exception_filter(filter)) + } } diff --git a/crates/loader/src/services/crt.rs b/crates/loader/src/services/crt.rs index 4d54869..68b51b3 100644 --- a/crates/loader/src/services/crt.rs +++ b/crates/loader/src/services/crt.rs @@ -163,12 +163,14 @@ pub(super) fn register(registry: &mut ImportRegistry) { registry.alias(CRT_STRING_API, UCRT, symbol); registry.set_status(UCRT, symbol, ServiceStatus::Partial); } + // The mingw-w64 C runtime imports `memcpy` through this API set. + registry.alias("api-ms-win-crt-private-l1-1-0.dll", UCRT, "memcpy"); } const ENOMEM: u32 = 12; -const EINVAL: u32 = 22; +pub(super) const EINVAL: u32 = 22; -fn set_errno(memory: &mut GuestMemory, teb: u64, error: u32) -> Result<(), ExitReason> { +pub(super) fn set_errno(memory: &mut GuestMemory, teb: u64, error: u32) -> Result<(), ExitReason> { let address = memory .crt_errno_address(teb) .map_err(ExitReason::MemoryFault)?; diff --git a/crates/loader/src/services/crt_startup.rs b/crates/loader/src/services/crt_startup.rs new file mode 100644 index 0000000..d7b0444 --- /dev/null +++ b/crates/loader/src/services/crt_startup.rs @@ -0,0 +1,116 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +//! What a C program's startup code configures in the C runtime before `main`. +//! +//! Each value is recorded and returned as its public documentation says, and +//! nothing acts on any of them yet. No invalid-parameter handler, signal +//! handler, exception filter, math-error handler or new handler is ever called, +//! there is no locale, and nothing reads `_fmode` or `_commode` until stdio +//! exists. The registry therefore declares every service here `partial`. + +use crate::cpu::ExitReason; +use crate::memory::{GuestMemory, PROCESS_HEAP}; +use std::collections::BTreeMap; + +/// `_O_TEXT` (fcntl.h), the documented initial value of `_fmode`. +const O_TEXT: u32 = 0x4000; +/// `_ENABLE_PER_THREAD_LOCALE` and `_DISABLE_PER_THREAD_LOCALE` (locale.h). +const ENABLE_PER_THREAD_LOCALE: i32 = 1; +const DISABLE_PER_THREAD_LOCALE: i32 = 2; +/// The signals the documentation of `signal` lists, by their signal.h values: +/// SIGINT, SIGILL, SIGFPE, SIGSEGV, SIGTERM and SIGABRT. +const SIGNALS: [i32; 6] = [2, 4, 8, 11, 15, 22]; + +#[derive(Default)] +pub(super) struct CrtStartup { + app_type: i32, + /// Whether `malloc` would call the new handler on failure. It never does. + new_mode: i32, + per_thread_locale: bool, + user_math_error: u64, + invalid_parameter_handler: u64, + unhandled_exception_filter: u64, + /// Handlers other than the default, `SIG_DFL`, which is zero. + signals: BTreeMap, + /// Guest address of `_fmode`. `_commode` is the `int` after it. + file_modes: Option, +} + +impl CrtStartup { + pub(super) fn app_type(&self) -> i32 { + self.app_type + } + + pub(super) fn set_app_type(&mut self, kind: i32) { + self.app_type = kind; + } + + /// The previous mode, or `None` for a mode that is neither 0 nor 1. + pub(super) fn set_new_mode(&mut self, mode: i32) -> Option { + matches!(mode, 0 | 1).then(|| std::mem::replace(&mut self.new_mode, mode)) + } + + /// The setting before the call, or `None` for a request that is not 0 + /// (query), enable or disable. A new process uses the global locale. + pub(super) fn configure_thread_locale(&mut self, request: i32) -> Option { + let before = if self.per_thread_locale { + ENABLE_PER_THREAD_LOCALE + } else { + DISABLE_PER_THREAD_LOCALE + }; + match request { + 0 => {} + ENABLE_PER_THREAD_LOCALE => self.per_thread_locale = true, + DISABLE_PER_THREAD_LOCALE => self.per_thread_locale = false, + _ => return None, + } + Some(before) + } + + pub(super) fn user_math_error(&self) -> u64 { + self.user_math_error + } + + pub(super) fn set_user_math_error(&mut self, handler: u64) { + self.user_math_error = handler; + } + + pub(super) fn set_invalid_parameter_handler(&mut self, handler: u64) -> u64 { + std::mem::replace(&mut self.invalid_parameter_handler, handler) + } + + pub(super) fn set_unhandled_exception_filter(&mut self, filter: u64) -> u64 { + std::mem::replace(&mut self.unhandled_exception_filter, filter) + } + + /// The previous handler, or `None` for a signal the documentation does not + /// list. One table serves the whole process. + pub(super) fn signal(&mut self, signal: i32, handler: u64) -> Option { + SIGNALS + .contains(&signal) + .then(|| self.signals.insert(signal, handler).unwrap_or(0)) + } + + /// Guest address of `_fmode` (`index` 0) or `_commode` (`index` 1). Both + /// are allocated together from the process heap on first use. `_fmode` + /// starts as `_O_TEXT`, as documented. `_commode` starts as zero: its + /// documentation gives no initial value, and zero is "no commit". + pub(super) fn file_mode_address( + &mut self, + memory: &mut GuestMemory, + index: u64, + ) -> Result { + let base = match self.file_modes { + Some(base) => base, + None => { + let base = memory + .map_heap_allocation(PROCESS_HEAP, 8) + .and_then(|base| memory.write_u32(base, O_TEXT).map(|()| base)) + .map_err(ExitReason::MemoryFault)?; + self.file_modes = Some(base); + base + } + }; + Ok(base + 4 * index) + } +} diff --git a/crates/loader/tests/runtime_services.rs b/crates/loader/tests/runtime_services.rs index 5d5d2fa..14f7e95 100644 --- a/crates/loader/tests/runtime_services.rs +++ b/crates/loader/tests/runtime_services.rs @@ -132,7 +132,8 @@ fn standard_with_state(clock: u64) -> (ImportRegistry, Arc, Arc Self { - let imports: Vec<(&str, Symbol)> = SERVICES + let mut imports: Vec<(&str, Symbol)> = SERVICES .iter() .map(|service| (service.library, Symbol::Name(service.symbol))) .collect(); + imports.push(("ucrtbase.dll", Symbol::Name("_errno"))); let image = build(&imports); let pe = ParsedPe::parse(&image.bytes).unwrap(); let mut memory = pe.load_into_memory(&image.bytes).unwrap().memory; @@ -162,7 +164,7 @@ impl Guest { let bound = registry .bind_imports(&pe, &image.bytes, BASE, &mut memory) .unwrap(); - assert_eq!(bound, SERVICES.len()); + assert_eq!(bound, SERVICES.len() + 1); let mut engine = DbtEngine::new(256 * 1024).unwrap(); engine.set_import_registry(registry); Self { @@ -179,6 +181,7 @@ impl Guest { let index = SERVICES .iter() .position(|service| service.symbol == symbol) + .or((symbol == "_errno").then_some(SERVICES.len())) .unwrap(); let mut cpu = CpuState::new(BASE + u64::from(CODE_RVA) + 16 * index as u64, STACK_TOP); cpu.gs_base = self.teb; @@ -223,6 +226,17 @@ impl Guest { fn last_error(&mut self) -> u64 { self.call("GetLastError", &[]) } + + /// The calling thread's `errno`, read through the pointer `_errno` returns. + fn errno(&mut self) -> u32 { + let address = self.call("_errno", &[]); + self.memory.read_u32(address).unwrap() + } + + fn set_errno(&mut self, value: u32) { + let address = self.call("_errno", &[]); + self.memory.write_u32(address, value).unwrap(); + } } const PROCESS: u64 = u64::MAX; @@ -736,6 +750,269 @@ fn arguments_are_assigned_by_position_and_read_the_stack_after_the_fourth() { // --- registry ---------------------------------------------------------------- +/// Bits above an `int` argument are not part of it. +const JUNK: u64 = 0xFFFF_FFFF_0000_0000; +/// The low 32 bits of an `int` result of -1. +const MINUS_ONE: u64 = 0xFFFF_FFFF; +const EINVAL: u32 = 22; + +/// `_set_new_mode` (new.h) and `_configthreadlocale` (locale.h), from their +/// Microsoft Learn pages: each returns the setting before the call, and -1 for +/// an argument outside its documented set, with `errno` set to `EINVAL`. +#[test] +fn crt_startup_modes_return_the_previous_setting() { + let mut guest = Guest::new(); + let result = |value: u64| value & 0xFFFF_FFFF; + // malloc does not call the new handler by default, so the first mode is 0. + assert_eq!(result(guest.call("_set_new_mode", &[1])), 0); + assert_eq!(result(guest.call("_set_new_mode", &[1])), 1); + assert_eq!(result(guest.call("_set_new_mode", &[JUNK])), 1); + assert_eq!(result(guest.call("_set_new_mode", &[JUNK | 1])), 0); + guest.set_errno(0); + for invalid in [2, 3, MINUS_ONE, 0x8000_0000] { + assert_eq!(result(guest.call("_set_new_mode", &[invalid])), MINUS_ONE); + assert_eq!(guest.errno(), EINVAL, "{invalid:#x}"); + guest.set_errno(0); + } + // A refused mode changes nothing, and a valid call leaves errno alone. + assert_eq!(result(guest.call("_set_new_mode", &[0])), 1); + assert_eq!(guest.errno(), 0); + + // _ENABLE_PER_THREAD_LOCALE is 1, _DISABLE_PER_THREAD_LOCALE is 2, and 0 + // only asks. A program starts with the global locale. + let locale = + |guest: &mut Guest, request: u64| result(guest.call("_configthreadlocale", &[request])); + assert_eq!(locale(&mut guest, 0), 2); + assert_eq!(locale(&mut guest, 0), 2); + assert_eq!(locale(&mut guest, 1), 2); + assert_eq!(locale(&mut guest, 0), 1); + assert_eq!(locale(&mut guest, JUNK | 2), 1); + assert_eq!(locale(&mut guest, JUNK), 2); + assert_eq!(locale(&mut guest, 1), 2); + assert_eq!(guest.errno(), 0); + for invalid in [3, 4, MINUS_ONE, 0x8000_0001] { + assert_eq!(locale(&mut guest, invalid), MINUS_ONE, "{invalid:#x}"); + assert_eq!(guest.errno(), EINVAL, "{invalid:#x}"); + guest.set_errno(0); + } + // A refused request changes nothing, and a valid one leaves errno alone. + assert_eq!(locale(&mut guest, 0), 1); + assert_eq!(guest.errno(), 0); + // The two settings are separate. + assert_eq!(result(guest.call("_set_new_mode", &[0])), 0); +} + +/// `_set_invalid_parameter_handler` (stdlib.h), `SetUnhandledExceptionFilter` +/// (errhandlingapi.h) and `signal` (signal.h), from their Microsoft Learn +/// pages: each returns the handler it replaces. The first two start with none, +/// which is a null pointer; a signal starts at `SIG_DFL`, which is zero. +/// `signal` returns `SIG_ERR`, which is -1 as a pointer, and sets `errno` to +/// `EINVAL` for a signal that is not one of the six its page lists. +#[test] +fn crt_startup_handlers_return_the_previous_handler() { + let mut guest = Guest::new(); + const A: u64 = 0x1_4000_1230; + const B: u64 = 0x7FFF_FFFF_FFFF_FFF0; + for symbol in [ + "_set_invalid_parameter_handler", + "SetUnhandledExceptionFilter", + ] { + assert_eq!(guest.call(symbol, &[A]), 0, "{symbol}"); + assert_eq!(guest.call(symbol, &[B]), A, "{symbol}"); + assert_eq!(guest.call(symbol, &[0]), B, "{symbol}"); + assert_eq!(guest.call(symbol, &[0]), 0, "{symbol}"); + } + // One does not see the other's handler. + assert_eq!(guest.call("_set_invalid_parameter_handler", &[A]), 0); + assert_eq!(guest.call("SetUnhandledExceptionFilter", &[B]), 0); + assert_eq!(guest.call("_set_invalid_parameter_handler", &[0]), A); + assert_eq!(guest.call("SetUnhandledExceptionFilter", &[0]), B); + + // SIGINT 2, SIGILL 4, SIGFPE 8, SIGSEGV 11, SIGTERM 15, SIGABRT 22. + const SIGNALS: [u64; 6] = [2, 4, 8, 11, 15, 22]; + guest.set_errno(0); + for signal in SIGNALS { + assert_eq!(guest.call("signal", &[signal, A + signal]), 0, "{signal}"); + } + // Each signal has its own handler, and the number is an int. + for signal in SIGNALS { + assert_eq!( + guest.call("signal", &[JUNK | signal, B]), + A + signal, + "{signal}" + ); + } + // SIG_DFL is 0 and SIG_IGN is 1; either is stored like a function. + assert_eq!(guest.call("signal", &[2, 1]), B); + assert_eq!(guest.call("signal", &[2, 0]), 1); + assert_eq!(guest.call("signal", &[2, A]), 0); + assert_eq!(guest.errno(), 0); + for unlisted in [ + 0, + 1, + 3, + 5, + 7, + 9, + 10, + 12, + 14, + 16, + 23, + 64, + MINUS_ONE, + 0x8000_0002, + ] { + assert_eq!( + guest.call("signal", &[unlisted, B]), + u64::MAX, + "{unlisted:#x}" + ); + assert_eq!(guest.errno(), EINVAL, "{unlisted:#x}"); + guest.set_errno(0); + } + // A refused call changed no handler. + assert_eq!(guest.call("signal", &[2, 0]), A); + for signal in &SIGNALS[1..] { + assert_eq!(guest.call("signal", &[*signal, 0]), B, "{signal}"); + } +} + +/// `__p__fmode` and `__p__commode`, from their Microsoft Learn pages: each +/// returns a pointer to a global `int`, `_fmode` and `_commode`. The `_fmode` +/// page gives its default as `_O_TEXT`, which fcntl.h defines as 0x4000. No +/// page gives `_commode` an initial value; zero, "no commit", is Xenora's. +#[test] +fn crt_file_mode_variables_are_guest_memory() { + let mut guest = Guest::new(); + let fmode = guest.call("__p__fmode", &[]); + let commode = guest.call("__p__commode", &[]); + assert_ne!(fmode, 0); + assert_ne!(commode, 0); + // Two ints that do not overlap. + assert!(fmode.abs_diff(commode) >= 4); + assert_eq!(guest.memory.read_u32(fmode).unwrap(), 0x4000); + assert_eq!(guest.memory.read_u32(commode).unwrap(), 0); + // The program assigns through the pointers: _O_BINARY is 0x8000 and + // _IOCOMMIT is 0x4000. + guest.memory.write_u32(fmode, 0x8000).unwrap(); + assert_eq!(guest.memory.read_u32(commode).unwrap(), 0); + guest.memory.write_u32(commode, 0x4000).unwrap(); + // The variables stay where they are and keep what was stored. + assert_eq!(guest.call("__p__fmode", &[]), fmode); + assert_eq!(guest.call("__p__commode", &[]), commode); + assert_eq!(guest.memory.read_u32(fmode).unwrap(), 0x8000); + assert_eq!(guest.memory.read_u32(commode).unwrap(), 0x4000); + + // The order of the first calls does not matter. + let mut other = Guest::new(); + let commode = other.call("__p__commode", &[]); + assert_eq!(other.memory.read_u32(commode).unwrap(), 0); + let fmode = other.call("__p__fmode", &[]); + assert_eq!(other.memory.read_u32(fmode).unwrap(), 0x4000); + assert!(fmode.abs_diff(commode) >= 4); +} + +/// `_set_app_type` and `__setusermatherr` (corecrt_startup.h) return nothing. +/// What they were given is visible to the host only. +#[test] +fn crt_app_type_and_math_error_handler_are_recorded() { + let mut guest = Guest::new(); + assert_eq!(guest.state.crt_app_type(), 0); // _crt_unknown_app + assert_eq!(guest.state.crt_user_math_error(), 0); + guest.call("_set_app_type", &[JUNK | 1]); // _crt_console_app + assert_eq!(guest.state.crt_app_type(), 1); + assert_eq!(guest.state.crt_user_math_error(), 0); + guest.call("__setusermatherr", &[0x1_4000_2340]); + assert_eq!(guest.state.crt_user_math_error(), 0x1_4000_2340); + assert_eq!(guest.state.crt_app_type(), 1); + guest.call("_set_app_type", &[2]); // _crt_gui_app + guest.call("__setusermatherr", &[0]); + assert_eq!(guest.state.crt_app_type(), 2); + assert_eq!(guest.state.crt_user_math_error(), 0); + // Neither touched errno or the last error. + assert_eq!(guest.errno(), 0); + assert_eq!(guest.last_error(), 0); +} + +/// The module and symbol pairs a program built with mingw-w64 14.0.0 (UCRT) +/// imports these services by, read from such a program's import table. +#[test] +fn crt_startup_services_resolve_as_mingw_w64_imports_them() { + let (registry, _) = standard(0); + for (module, symbol, canonical) in [ + ( + "api-ms-win-crt-runtime-l1-1-0.dll", + "_set_app_type", + "ucrtbase.dll", + ), + ( + "api-ms-win-crt-heap-l1-1-0.dll", + "_set_new_mode", + "ucrtbase.dll", + ), + ( + "api-ms-win-crt-locale-l1-1-0.dll", + "_configthreadlocale", + "ucrtbase.dll", + ), + ( + "api-ms-win-crt-math-l1-1-0.dll", + "__setusermatherr", + "ucrtbase.dll", + ), + ( + "api-ms-win-crt-runtime-l1-1-0.dll", + "_set_invalid_parameter_handler", + "ucrtbase.dll", + ), + ( + "api-ms-win-crt-stdio-l1-1-0.dll", + "__p__fmode", + "ucrtbase.dll", + ), + ( + "api-ms-win-crt-stdio-l1-1-0.dll", + "__p__commode", + "ucrtbase.dll", + ), + ( + "api-ms-win-crt-runtime-l1-1-0.dll", + "signal", + "ucrtbase.dll", + ), + ( + "KERNEL32.dll", + "SetUnhandledExceptionFilter", + "kernel32.dll", + ), + ( + "api-ms-win-crt-private-l1-1-0.dll", + "memcpy", + "ucrtbase.dll", + ), + ] { + let service = registry + .resolve(module, &named(symbol)) + .unwrap_or_else(|| panic!("{module}!{symbol}")); + let target = registry.resolve(canonical, &named(symbol)).unwrap(); + assert!(std::ptr::eq(service, target), "{module}!{symbol}"); + assert_eq!(service.status, ServiceStatus::Partial, "{symbol}"); + } + // An API set forwards only the symbols listed for it. + for (module, symbol) in [ + ("api-ms-win-crt-heap-l1-1-0.dll", "_set_app_type"), + ("api-ms-win-crt-runtime-l1-1-0.dll", "_set_new_mode"), + ("api-ms-win-crt-stdio-l1-1-0.dll", "signal"), + ("api-ms-win-crt-private-l1-1-0.dll", "_set_app_type"), + ] { + assert!( + registry.resolve(module, &named(symbol)).is_none(), + "{module}!{symbol}" + ); + } +} + fn named(name: &str) -> ImportName { ImportName::Name(name.to_owned()) } diff --git a/docs/interfaces.md b/docs/interfaces.md index b00bd7a..00397c1 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -407,6 +407,33 @@ initialization use `api-ms-win-core-synch-l1-2-0`; SLists use `api-ms-win-core-processthreads-l1-1-0`; and FLS uses `api-ms-win-core-fibers-l1-1-0`. +### C runtime startup configuration + +A C program's startup code configures the C runtime before `main`. Nine +services record what it sets and return what their public documentation says. +They are declared in the typed registry (`docs/runtime/services.md`), all +`partial`, because nothing acts on a recorded value: + +| Service | Returns | Not provided | +| --- | --- | --- | +| `_set_app_type(type)` | nothing | Nothing depends on the type | +| `_set_new_mode(mode)` | the previous mode; -1 and `errno` `EINVAL` unless the mode is 0 or 1 | `malloc` never calls a new handler | +| `_configthreadlocale(request)` | the setting before the call (1 enabled, 2 disabled; a program starts disabled); -1 and `errno` `EINVAL` unless the request is 0, 1 or 2 | There is no locale | +| `__setusermatherr(handler)` | nothing | The handler is never called | +| `_set_invalid_parameter_handler(handler)` | the previous handler, null at first | No service calls it for an invalid argument | +| `__p__fmode()`, `__p__commode()` | the address of the guest `int` `_fmode` (initially `_O_TEXT`, `0x4000`, as documented) or `_commode` (initially 0; its documentation gives no initial value) | Nothing reads either until stdio exists | +| `signal(sig, handler)` | the previous handler, `SIG_DFL` at first; `SIG_ERR` and `errno` `EINVAL` for a signal other than `SIGINT`, `SIGILL`, `SIGFPE`, `SIGSEGV`, `SIGTERM` and `SIGABRT` | No signal is ever raised. One table serves the process | +| `SetUnhandledExceptionFilter(filter)` | the previous filter, null at first | No exception reaches it | + +`_fmode` and `_commode` share one 8-byte block allocated from the process heap +on the first call to either. `ServicesState::crt_app_type` and +`ServicesState::crt_user_math_error` let a host read the two values no service +returns. `signal.h` also defines `SIGBREAK` and `SIGABRT_COMPAT`, which the +documentation of `signal` does not list; they are refused, and whether Windows +accepts them was not checked. `memcpy` also resolves through +`api-ms-win-crt-private-l1-1-0.dll`, the API set the mingw-w64 runtime imports +it from. None of this has been compared with Windows. + ## Synthetic tiled textures The texture crate reads original fixtures in an array-layer-major layout. Each diff --git a/docs/runtime/services.md b/docs/runtime/services.md index 009bfaa..2ff1604 100644 --- a/docs/runtime/services.md +++ b/docs/runtime/services.md @@ -6,14 +6,14 @@ A declared service is not a claim of compatibility. `implemented` and `partial` | Measure | Count | | --- | ---: | -| Services with a declared ABI | 20 | -| Generated adapters | 20 | -| Unique handler implementations | 20 | +| Services with a declared ABI | 29 | +| Generated adapters | 29 | +| Unique handler implementations | 29 | | Implemented | 7 | -| Partial | 13 | +| Partial | 22 | | Stub | 0 | -| Conformance-tested through guest dispatch | 20 | -| API-set aliases (not services) | 20 | +| Conformance-tested through guest dispatch | 29 | +| API-set aliases (not services) | 29 | | Independently accepted | 0 | | Service | Signature | Status | Failure | @@ -38,3 +38,12 @@ A declared service is not a claim of compatibility. `implemented` and `partial` | `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 | +| `ucrtbase.dll!_set_app_type` | `(kind: i32) -> void` | partial | never | +| `ucrtbase.dll!_set_new_mode` | `(mode: i32) -> i32` | partial | -1 with errno EINVAL for a mode other than 0 or 1 | +| `ucrtbase.dll!_configthreadlocale` | `(request: i32) -> i32` | partial | -1 with errno EINVAL for a request other than 0, 1 or 2 | +| `ucrtbase.dll!__setusermatherr` | `(handler: ptr) -> void` | partial | never | +| `ucrtbase.dll!_set_invalid_parameter_handler` | `(handler: ptr) -> ptr` | partial | never | +| `ucrtbase.dll!__p__fmode` | `() -> ptr` | partial | stops the guest when the variable cannot be allocated | +| `ucrtbase.dll!__p__commode` | `() -> ptr` | partial | stops the guest when the variable cannot be allocated | +| `ucrtbase.dll!signal` | `(signal: i32, handler: ptr) -> ptr` | partial | SIG_ERR with errno EINVAL for a signal the documentation does not list | +| `kernel32.dll!SetUnhandledExceptionFilter` | `(filter: ptr) -> ptr` | partial | never | From 985d3b9e7871f080cda9a73e2b7d17724e396e7c Mon Sep 17 00:00:00 2001 From: zachdoxsee Date: Wed, 25 Nov 2026 02:14:00 +0100 Subject: [PATCH 2/2] Move the changelog entry down the list Every merge to main adds its entry at the head of the Added list, and so did this branch, so each of those merges put this branch in conflict over one line. The entry is unchanged; it now sits lower down, in a place of its own. Signed-off-by: zachdoxsee --- CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ef5dcbd..d677ce0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,7 +31,6 @@ remains unsupported. - Added a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status. ### Added -- Added nine C runtime services that a C program's startup code calls or imports before `main`, and one alias (#382, part of Gate A2): `_set_app_type`, `_set_new_mode`, `_configthreadlocale`, `__setusermatherr`, `_set_invalid_parameter_handler`, `__p__fmode`, `__p__commode`, `signal` and `SetUnhandledExceptionFilter`, plus `memcpy` through `api-ms-win-crt-private-l1-1-0.dll`. A program built with the mingw-w64 runtime imports all of them, and the loader refused it before its entry point because they did not resolve. Each records what it is given and returns what its public documentation says: the previous mode, setting or handler, the documented failure value, or the address of the guest variables `_fmode` and `_commode`. All nine are declared `partial` in the typed registry because nothing acts on a recorded value: no handler or filter is ever called, no signal is raised, there is no locale, and nothing reads `_fmode` yet. `ServicesState` gains two read-only accessors, `crt_app_type` and `crt_user_math_error`. Five tests in `runtime_services.rs` call the services from guest code through a bound import table. Not compared with Windows; awaiting independent review. - The loader now maps an image's PE headers at its image base (#333): the first `SizeOfHeaders` bytes of the file, read-only, in whole 4 KiB pages that are zero past `SizeOfHeaders`. Programs read their own headers this way; the mingw-w64 C runtime does so before `main`, and until now that read faulted. When startup relocates an image it writes the load base into the mapped `ImageBase` field after the relocations, so an entry aimed at that field cannot move it twice; this is Xenora's policy and has not been compared with Windows. A load is refused with the new `PeError::InvalidHeaderSize` when `SizeOfHeaders` is zero, ends before the section table, runs past the file, or its pages would reach into a section, and when the bytes handed to the loader are not the PE32+ headers that were parsed. The page rule refuses images with sub-page section alignment whose first section starts inside the header page, which loaded before. The header pages count toward the 256 MiB mapping budget, which is checked before anything is mapped. `ParsedPe::parse` and the static probe are unchanged. `tests/pe_headers.rs` covers guest reads at the preferred and a relocated base, a relocation aimed at `ImageBase`, the write and execute faults and each refusal with original hand-built images; the image in `pe_mapping_limits.rs` now carries a valid `SizeOfHeaders`. Awaiting independent re-review. - Added 35 known-answer cases for MOV with an immediate operand, opcodes C6 /0 and C7 /0 (#194), to `cpu_known_answers.rs`: byte, word, dword and qword stores through base, SIB, R12, R13, RSP and RBP addressing with 8-bit and 32-bit displacements; the imm32 sign extension of the 64-bit form; the register forms, including AH and a REX-selected SIL; unmapped and read-only store faults at each width; and #UD for reg field 1. Expected values come from the Intel SDM and were worked out by hand. The interpreter and the DBT already agreed with all of them, so this is new coverage and fixes no defect. The 16-bit forms covered are those that already run, and #118 stays open. Not compared with x86 hardware; awaiting independent review. - `dbt_bench` can also write its results as one JSON document when `XENORA_DBT_BENCH_JSON=` is set (#112). The document records the host CPU, OS and architecture, the git revision and whether the tree had local changes, debug assertions, the workload and sample counts, the median, minimum, maximum, p95, p99, IQR and MIPS for the interpreter and for cold and warm DBT, and the cold DBT counters. Anything the benchmark cannot determine is `null`. The text output and the timed work are unchanged. @@ -124,6 +123,8 @@ remains unsupported. - Added guest CRT errno accessors and allocation failure reporting for the synthetic main thread. +- Added nine C runtime services that a C program's startup code calls or imports before `main`, and one alias (#382, part of Gate A2): `_set_app_type`, `_set_new_mode`, `_configthreadlocale`, `__setusermatherr`, `_set_invalid_parameter_handler`, `__p__fmode`, `__p__commode`, `signal` and `SetUnhandledExceptionFilter`, plus `memcpy` through `api-ms-win-crt-private-l1-1-0.dll`. A program built with the mingw-w64 runtime imports all of them, and the loader refused it before its entry point because they did not resolve. Each records what it is given and returns what its public documentation says: the previous mode, setting or handler, the documented failure value, or the address of the guest variables `_fmode` and `_commode`. All nine are declared `partial` in the typed registry because nothing acts on a recorded value: no handler or filter is ever called, no signal is raised, there is no locale, and nothing reads `_fmode` yet. `ServicesState` gains two read-only accessors, `crt_app_type` and `crt_user_math_error`. Five tests in `runtime_services.rs` call the services from guest code through a bound import table. Not compared with Windows; awaiting independent review. + - Added guest CRT allocation, zeroed array allocation, resizing, and release. - Added private guest heap creation and destruction with per-heap allocation ownership.