Integrate PR #276 with explicit unsupported-service behavior

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
This commit is contained in:
atharvranjan committed 2026-11-24 21:57:08 -06:00
commit 2f68ee9d4a
8 files changed
+285 -7

No files matched your search

+2
View File
@@ -153,6 +153,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.
+7
View File
@@ -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",
],
_ => &[],
}
+28
View File
@@ -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
+66 -1
View File
@@ -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; 23] = [
ServiceMetadata {
library: "kernel32.dll",
symbol: "SetProcessPriorityBoost",
@@ -185,6 +185,39 @@ pub static SERVICES: [ServiceMetadata; 20] = [
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",
@@ -367,6 +400,38 @@ pub fn register(registry: &mut ImportRegistry, state: &Arc<ServicesState>) {
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)?;
+39
View File
@@ -722,6 +722,9 @@ pub(crate) mod handlers {
type Outcome<T> = Result<T, ExitReason>;
/// 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,
@@ -946,6 +949,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<bool> {
Err(RUNTIME_LIMIT)
}
pub fn virtual_query(
_: &mut ServiceContext<'_>,
_address: u64,
_information: OutPtr<48>,
_length: u64,
) -> Outcome<u64> {
Err(RUNTIME_LIMIT)
}
pub fn c_specific_handler(
_: &mut ServiceContext<'_>,
_record: u64,
_frame: u64,
_context: u64,
_dispatcher: u64,
) -> Outcome<i32> {
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;
+116
View File
@@ -659,6 +659,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<u8> = (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();
+18
View File
@@ -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
+9 -6
View File
@@ -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 | 23 |
| Generated adapters | 23 |
| Unique handler implementations | 23 |
| Implemented | 7 |
| Partial | 13 |
| Stub | 0 |
| Conformance-tested through guest dispatch | 20 |
| API-set aliases (not services) | 20 |
| Stub | 3 |
| Conformance-tested through guest dispatch | 23 |
| API-set aliases (not services) | 23 |
| 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 |