diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c8551d..9405387 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -136,6 +136,8 @@ remains unsupported. - Added the synthetic default process heap with allocation, size queries, and release. +- Added `VirtualProtect`, `VirtualQuery` and `__C_specific_handler` as `stub` services so that a C program built with the mingw-w64 runtime can bind its imports (#388, part of Gate A2). Such a program imports all three and does not call them on a normal run; without them the loader refused it before its entry point. A call to any of them stops the guest with the runtime-limit fault (`IllegalInstruction(0xFE)`) and writes nothing, so a program that needs one stops there and cannot run on with a made-up result. No page protection is changed, no region is described and no exception is dispatched. The service generator's API-set table gains `api-ms-win-crt-private-l1-1-0.dll` for `ucrtbase.dll`, which is inferred and not taken from a document that names it. Two tests in `runtime_services.rs` call the stubs from guest code and check how they resolve. Not compared with Windows; awaiting independent review. + - Added Win64 signatures for wide-string length and comparison and overlapping byte moves to the import catalog. - Added guest CRT wide-string length and comparison using Windows 16-bit code units. diff --git a/crates/import-gen/src/apiset.rs b/crates/import-gen/src/apiset.rs index d28dfc6..e94b2db 100644 --- a/crates/import-gen/src/apiset.rs +++ b/crates/import-gen/src/apiset.rs @@ -71,6 +71,13 @@ pub fn get_api_sets_for_canonical(canonical: &str) -> &'static [&'static str] { "api-ms-win-crt-filesystem-l1-1-0.dll", "api-ms-win-crt-locale-l1-1-0.dll", "api-ms-win-crt-environment-l1-1-0.dll", + // The API set a program built with the mingw-w64 UCRT runtime + // imports `memcpy` and `__C_specific_handler` from. That it + // forwards to ucrtbase.dll is inferred from its name and from + // Microsoft's "Universal CRT deployment" page, which says the + // Universal CRT ships as ucrtbase.dll plus `api-ms-win-*.dll` + // forwarders. No document naming this set was found. + "api-ms-win-crt-private-l1-1-0.dll", ], _ => &[], } diff --git a/crates/loader/runtime/services.txt b/crates/loader/runtime/services.txt index 69d273c..53b31fd 100644 --- a/crates/loader/runtime/services.txt +++ b/crates/loader/runtime/services.txt @@ -148,6 +148,34 @@ service kernel32.dll VirtualFree(address: ptr, size: u64, kind: u32) -> bool32 ref memoryapi.h VirtualFree test virtual_memory_is_mapped_released_and_bounded +# Stubs. A program built with the mingw-w64 runtime imports these three and +# does not call them on a normal run. They exist so that its imports bind. A +# call stops the guest with the runtime-limit fault and changes nothing. + +service kernel32.dll VirtualProtect(address: ptr, size: u64, protect: u32, old: out<4>) -> bool32 + handler virtual_protect + status stub + alias api-ms-win-core-memory-l1-1-0.dll + fails always: stops the guest with the runtime-limit fault; no protection changes + ref memoryapi.h VirtualProtect + test memory_and_exception_stubs_stop_the_guest_and_change_nothing + +service kernel32.dll VirtualQuery(address: ptr, information: out<48>, length: u64) -> u64 + handler virtual_query + status stub + alias api-ms-win-core-memory-l1-1-0.dll + fails always: stops the guest with the runtime-limit fault; nothing is written + ref memoryapi.h VirtualQuery + test memory_and_exception_stubs_stop_the_guest_and_change_nothing + +service ucrtbase.dll __C_specific_handler(record: ptr, frame: ptr, context: ptr, dispatcher: ptr) -> i32 + handler c_specific_handler + status stub + alias api-ms-win-crt-private-l1-1-0.dll + fails always: stops the guest with the runtime-limit fault; no exception is dispatched + ref Microsoft Learn, x64 exception handling, language-specific handler + test memory_and_exception_stubs_stop_the_guest_and_change_nothing + service ucrtbase.dll sqrt(x: f64) -> f64 handler sqrt status partial diff --git a/crates/loader/src/runtime_table.rs b/crates/loader/src/runtime_table.rs index 85e5bd9..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; 29] = [ +pub static SERVICES: [ServiceMetadata; 32] = [ ServiceMetadata { library: "kernel32.dll", symbol: "SetProcessPriorityBoost", @@ -185,6 +185,39 @@ pub static SERVICES: [ServiceMetadata; 29] = [ reference: "memoryapi.h VirtualFree", tests: &["virtual_memory_is_mapped_released_and_bounded"], }, + ServiceMetadata { + library: "kernel32.dll", + symbol: "VirtualProtect", + parameters: &[Parameter { name: "address", kind: "ptr" }, Parameter { name: "size", kind: "u64" }, Parameter { name: "protect", kind: "u32" }, Parameter { name: "old", kind: "out<4>" }], + result: "bool32", + status: ServiceStatus::Stub, + aliases: &["api-ms-win-core-memory-l1-1-0.dll"], + failure: "always: stops the guest with the runtime-limit fault; no protection changes", + reference: "memoryapi.h VirtualProtect", + tests: &["memory_and_exception_stubs_stop_the_guest_and_change_nothing"], + }, + ServiceMetadata { + library: "kernel32.dll", + symbol: "VirtualQuery", + parameters: &[Parameter { name: "address", kind: "ptr" }, Parameter { name: "information", kind: "out<48>" }, Parameter { name: "length", kind: "u64" }], + result: "u64", + status: ServiceStatus::Stub, + aliases: &["api-ms-win-core-memory-l1-1-0.dll"], + failure: "always: stops the guest with the runtime-limit fault; nothing is written", + reference: "memoryapi.h VirtualQuery", + tests: &["memory_and_exception_stubs_stop_the_guest_and_change_nothing"], + }, + ServiceMetadata { + library: "ucrtbase.dll", + symbol: "__C_specific_handler", + parameters: &[Parameter { name: "record", kind: "ptr" }, Parameter { name: "frame", kind: "ptr" }, Parameter { name: "context", kind: "ptr" }, Parameter { name: "dispatcher", kind: "ptr" }], + result: "i32", + status: ServiceStatus::Stub, + aliases: &["api-ms-win-crt-private-l1-1-0.dll"], + failure: "always: stops the guest with the runtime-limit fault; no exception is dispatched", + reference: "Microsoft Learn, x64 exception handling, language-specific handler", + tests: &["memory_and_exception_stubs_stop_the_guest_and_change_nothing"], + }, ServiceMetadata { library: "ucrtbase.dll", symbol: "sqrt", @@ -466,6 +499,38 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc) { Ok(result.place(cpu)) }); let s = state.clone(); + registry.register_with_status("kernel32.dll", "VirtualProtect", ServiceStatus::Stub, 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.out::<4>(3)?; + let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base }; + let result: bool = handlers::virtual_protect(&mut context, a0, a1, a2, a3)?; + Ok(result.place(cpu)) + }); + let s = state.clone(); + registry.register_with_status("kernel32.dll", "VirtualQuery", ServiceStatus::Stub, move |args, cpu, memory| { + let call = Call::new(args, cpu, memory); + let a0 = call.u64(0)?; + let a1 = call.out::<48>(1)?; + let a2 = call.u64(2)?; + let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base }; + let result: u64 = handlers::virtual_query(&mut context, a0, a1, a2)?; + Ok(result.place(cpu)) + }); + let s = state.clone(); + registry.register_with_status("ucrtbase.dll", "__C_specific_handler", ServiceStatus::Stub, move |args, cpu, memory| { + let call = Call::new(args, cpu, memory); + let a0 = call.u64(0)?; + let a1 = call.u64(1)?; + let a2 = call.u64(2)?; + let a3 = call.u64(3)?; + let mut context = ServiceContext { state: &s, memory, teb: cpu.gs_base }; + let result: i32 = handlers::c_specific_handler(&mut context, a0, a1, a2, a3)?; + 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)?; diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index 07ad537..454da35 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -735,6 +735,9 @@ pub(crate) mod handlers { type Outcome = Result; + /// The exit for a request the runtime does not model. + const RUNTIME_LIMIT: ExitReason = ExitReason::IllegalInstruction(0xFE); + pub fn set_process_priority_boost( context: &mut ServiceContext<'_>, process: u64, @@ -959,6 +962,42 @@ pub(crate) mod handlers { Ok(true) } + // Stubs (#388). A program built with the mingw-w64 runtime imports these + // three and does not call them on a normal run: the first two serve its + // runtime pseudo-relocations and the third is the language handler Windows + // calls while dispatching a structured exception. None is modelled, so a + // call stops the guest with the runtime-limit fault. Returning a made-up + // result would let the program run on with wrong state. + + pub fn virtual_protect( + _: &mut ServiceContext<'_>, + _address: u64, + _size: u64, + _protect: u32, + _old: OutPtr<4>, + ) -> Outcome { + Err(RUNTIME_LIMIT) + } + + pub fn virtual_query( + _: &mut ServiceContext<'_>, + _address: u64, + _information: OutPtr<48>, + _length: u64, + ) -> Outcome { + Err(RUNTIME_LIMIT) + } + + pub fn c_specific_handler( + _: &mut ServiceContext<'_>, + _record: u64, + _frame: u64, + _context: u64, + _dispatcher: u64, + ) -> Outcome { + Err(RUNTIME_LIMIT) + } + /// 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; diff --git a/crates/loader/tests/runtime_services.rs b/crates/loader/tests/runtime_services.rs index 14f7e95..0e0f78b 100644 --- a/crates/loader/tests/runtime_services.rs +++ b/crates/loader/tests/runtime_services.rs @@ -672,6 +672,122 @@ fn virtual_memory_is_mapped_released_and_bounded() { assert_eq!(guest.call("VirtualFree", &[address, 0, RELEASE]), 0); } +/// `VirtualProtect`, `VirtualQuery` and `__C_specific_handler` are stubs: a +/// hosted C program imports them and does not call them on a normal run. A +/// call stops the guest with the runtime-limit fault. The service writes +/// nothing: not the output buffers, not a result, not the last-error value. +#[test] +fn memory_and_exception_stubs_stop_the_guest_and_change_nothing() { + let mut guest = Guest::new(); + const READ_WRITE: u64 = 0x04; + const LIMIT: ExitReason = ExitReason::IllegalInstruction(0xFE); + let scratch: Vec = (0..0x100).map(|index| index as u8 ^ 0xA5).collect(); + guest.memory.write_bytes(SCRATCH, &scratch).unwrap(); + guest.call("SetLastError", &[0x1234]); + + for (symbol, args) in [ + // The scratch page, read-write as it already is, with the old + // protection going to the scratch page too. + ( + "VirtualProtect", + [SCRATCH, 0x100, READ_WRITE, SCRATCH + 0x80], + ), + ("VirtualProtect", [0, 0, 0, 0]), + // A full MEMORY_BASIC_INFORMATION, 48 bytes, about a mapped address. + ("VirtualQuery", [SCRATCH, SCRATCH + 0x40, 48, 0]), + ("VirtualQuery", [0, 0, 0, 0]), + ( + "__C_specific_handler", + [SCRATCH, STACK_TOP, SCRATCH + 0x40, SCRATCH + 0x80], + ), + ("__C_specific_handler", [0, 0, 0, 0]), + ] { + let (cpu, exit) = guest.run(symbol, &args); + assert_eq!(exit, LIMIT, "{symbol} {args:x?}"); + // Every general register but the stack pointer is as the caller left + // it: no result in RAX, no argument register cleared. + for (index, value) in cpu.gpr.iter().enumerate() { + let argument = [Register::Rcx, Register::Rdx, Register::R8, Register::R9] + .iter() + .position(|register| *register as usize == index); + let wanted = match argument { + Some(position) => args[position], + None => 0x0101_0101_0101_0101 * (index as u64 + 1), + }; + if index != Register::Rsp as usize { + assert_eq!(*value, wanted, "{symbol} register {index}"); + } + } + assert_eq!(cpu.xmm[..4], guest.xmm, "{symbol}"); + let mut after = vec![0; scratch.len()]; + guest.memory.read_bytes(SCRATCH, &mut after).unwrap(); + assert_eq!(after, scratch, "{symbol} {args:x?}"); + } + // The stopped calls recorded no error, and the guest still runs. + assert_eq!(guest.last_error(), 0x1234); + // The scratch page kept its protection: it is still writable. + guest.memory.write_u8(SCRATCH, 1).unwrap(); +} + +/// The three stubs resolve by the module and symbol pairs a program built +/// with mingw-w64 14.0.0 (UCRT) imports them by, and say they are stubs. +#[test] +fn memory_and_exception_stubs_bind_and_are_declared_stubs() { + let (registry, _) = standard(0); + let named = |name: &str| ImportName::Name(name.to_owned()); + for (module, symbol, canonical) in [ + ("KERNEL32.dll", "VirtualProtect", "kernel32.dll"), + ("KERNEL32.dll", "VirtualQuery", "kernel32.dll"), + ( + "api-ms-win-core-memory-l1-1-0.dll", + "VirtualProtect", + "kernel32.dll", + ), + ( + "api-ms-win-core-memory-l1-1-0.dll", + "VirtualQuery", + "kernel32.dll", + ), + ( + "api-ms-win-crt-private-l1-1-0.dll", + "__C_specific_handler", + "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::Stub, "{symbol}"); + } + // The real services beside them are not stubs, and the API sets forward + // only the symbols listed for them. + let alloc = registry + .resolve("kernel32.dll", &named("VirtualAlloc")) + .unwrap(); + assert_eq!(alloc.status, ServiceStatus::Partial); + for (module, symbol) in [ + ("api-ms-win-crt-private-l1-1-0.dll", "VirtualProtect"), + ("api-ms-win-core-memory-l1-1-0.dll", "__C_specific_handler"), + ("kernel32.dll", "__C_specific_handler"), + ] { + assert!( + registry.resolve(module, &named(symbol)).is_none(), + "{module}!{symbol}" + ); + } + let stubs: Vec<&str> = SERVICES + .iter() + .filter(|service| service.status == ServiceStatus::Stub) + .map(|service| service.symbol) + .collect(); + assert_eq!( + stubs, + ["VirtualProtect", "VirtualQuery", "__C_specific_handler"] + ); +} + #[test] fn floating_arguments_and_results_use_xmm_registers() { let mut guest = Guest::new(); diff --git a/docs/interfaces.md b/docs/interfaces.md index 44ebf09..2daa70a 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -222,6 +222,24 @@ References include Microsoft's [virtual allocation](https://learn.microsoft.com/windows/win32/api/memoryapi/nf-memoryapi-virtualalloc), and [virtual release](https://learn.microsoft.com/windows/win32/api/memoryapi/nf-memoryapi-virtualfree) contracts. +### Stubs a hosted C program binds + +`VirtualProtect`, `VirtualQuery` and `__C_specific_handler` are declared +`stub` in the typed registry (`docs/runtime/services.md`). A C program built +with the mingw-w64 runtime imports all three and does not call them on a +normal run: the first two serve its runtime pseudo-relocations, and the third +is the language handler Windows calls while dispatching a structured +exception. They exist so that such a program's imports bind. + +A call to any of them stops the guest with the runtime-limit fault +(`IllegalInstruction(0xFE)`). The service writes nothing: no output buffer, no +result and no last-error value. It does not return a made-up success or a +failure code Windows would not give, so a program that needs one of them +stops at that call. Nothing here changes a page protection, describes a +region or dispatches an exception; each needs work the runtime does not have +yet (regions that can be split, translated-code invalidation for executable +pages, recorded allocation bases, exception dispatch). + ### CRT strings and byte memory The standard registry provides `strlen` and `strnlen` under UCRT and the CRT diff --git a/docs/runtime/services.md b/docs/runtime/services.md index 2ff1604..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 | 29 | -| Generated adapters | 29 | -| Unique handler implementations | 29 | +| Services with a declared ABI | 32 | +| Generated adapters | 32 | +| Unique handler implementations | 32 | | Implemented | 7 | | Partial | 22 | -| Stub | 0 | -| Conformance-tested through guest dispatch | 29 | -| API-set aliases (not services) | 29 | +| Stub | 3 | +| Conformance-tested through guest dispatch | 32 | +| API-set aliases (not services) | 32 | | Independently accepted | 0 | | Service | Signature | Status | Failure | @@ -34,6 +34,9 @@ A declared service is not a claim of compatibility. `implemented` and `partial` | `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 | +| `kernel32.dll!VirtualProtect` | `(address: ptr, size: u64, protect: u32, old: out<4>) -> bool32` | stub | always: stops the guest with the runtime-limit fault; no protection changes | +| `kernel32.dll!VirtualQuery` | `(address: ptr, information: out<48>, length: u64) -> u64` | stub | always: stops the guest with the runtime-limit fault; nothing is written | +| `ucrtbase.dll!__C_specific_handler` | `(record: ptr, frame: ptr, context: ptr, dispatcher: ptr) -> i32` | stub | always: stops the guest with the runtime-limit fault; no exception is dispatched | | `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 |