diff --git a/CHANGELOG.md b/CHANGELOG.md index 3b4faba..8605b9c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -145,6 +145,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. diff --git a/crates/loader/runtime/services.txt b/crates/loader/runtime/services.txt index fd7ee10..53b31fd 100644 --- a/crates/loader/runtime/services.txt +++ b/crates/loader/runtime/services.txt @@ -207,3 +207,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 ff4e327..e160409 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; 23] = [ +pub static SERVICES: [ServiceMetadata; 32] = [ ServiceMetadata { library: "kernel32.dll", symbol: "SetProcessPriorityBoost", @@ -262,6 +262,105 @@ pub static SERVICES: [ServiceMetadata; 23] = [ 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. @@ -463,6 +562,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 e961944..9e667d8 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; @@ -207,6 +208,7 @@ pub struct ServicesState { atexit: Mutex>, /// The status the guest process exited with. Set once. exit_status: Mutex>, + crt_startup: Mutex, winsock: Mutex, task_fixture: Mutex, platform_fixture: Mutex, @@ -233,6 +235,7 @@ impl ServicesState { hooks: Arc::default(), atexit: Mutex::default(), exit_status: Mutex::default(), + crt_startup: Mutex::default(), winsock: Mutex::default(), task_fixture: Mutex::default(), platform_fixture: Mutex::default(), @@ -360,6 +363,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); @@ -1007,4 +1026,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 85b5491..0a0b263 100644 --- a/crates/loader/src/services/crt.rs +++ b/crates/loader/src/services/crt.rs @@ -190,12 +190,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 d55a057..ab09df5 100644 --- a/crates/loader/tests/runtime_services.rs +++ b/crates/loader/tests/runtime_services.rs @@ -133,7 +133,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; @@ -163,7 +165,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 { @@ -180,6 +182,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; @@ -224,6 +227,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; @@ -923,6 +937,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 855971e..d78daf4 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -485,6 +485,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 6186d07..4d486ba 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 | 23 | -| Generated adapters | 23 | -| Unique handler implementations | 23 | +| Services with a declared ABI | 32 | +| Generated adapters | 32 | +| Unique handler implementations | 32 | | Implemented | 7 | -| Partial | 13 | +| Partial | 22 | | Stub | 3 | -| Conformance-tested through guest dispatch | 23 | -| API-set aliases (not services) | 23 | +| Conformance-tested through guest dispatch | 32 | +| API-set aliases (not services) | 32 | | Independently accepted | 0 | | Service | Signature | Status | Failure | @@ -41,3 +41,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 |