Expose guest CRT errno and report allocation failures

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
This commit is contained in:
Adeeb Rahman committed 2026-11-24 01:33:03 -05:00
1 parent f992721fda
commit edba4df430
7 files changed
+158 -24

No files matched your search

+2
View File
@@ -11,6 +11,8 @@ remains unsupported.
### Added
- Added guest CRT errno accessors and allocation failure reporting for the synthetic main thread.
- Added guest CRT allocation, zeroed array allocation, resizing, and release.
- Added private guest heap creation and destruction with per-heap allocation ownership.
+5 -8
View File
@@ -380,14 +380,11 @@ impl SymbolDb {
] {
self.crt_native(m, sym, libc, "ISO C runtime — identical ABI on macOS");
}
self.win32_stub(
m,
"_errno",
false,
"Windows errno accessor — returns pointer to thread errno",
);
self.win32_stub(m, "_get_errno", false, "Windows get_errno");
self.win32_stub(m, "_set_errno", false, "Windows set_errno");
for module in [m, "ucrtbase.dll"] {
for symbol in ["_errno", "_get_errno", "_set_errno"] {
self.ins(module, symbol, Classification::StandardService);
}
}
self.win32_stub(m, "_set_app_type", false, "CRT app-type hint — no-op");
self.win32_stub(m, "_set_fmode", false, "CRT file mode hint — no-op");
self.win32_stub(m, "_set_new_mode", false, "CRT new-mode hint — no-op");
+11
View File
@@ -120,6 +120,7 @@ pub struct GuestMemory {
regions: Vec<MappedRegion>,
private_heaps: std::collections::BTreeSet<u64>,
private_heap_serial: u64,
crt_errno: Option<u64>,
}
impl GuestMemory {
@@ -201,6 +202,16 @@ impl GuestMemory {
self.map_dynamic_allocation(requested_base, size, permissions, AllocationKind::Virtual)
}
pub(crate) fn crt_errno_address(&mut self) -> Result<u64, MemoryError> {
if let Some(address) = self.crt_errno {
return Ok(address);
}
let address = self.find_dynamic_base(4)?;
self.map_region(address, 4, MemoryPermissions::READ_WRITE)?;
self.crt_errno = Some(address);
Ok(address)
}
pub(crate) fn create_private_heap(&mut self, initial: u64) -> Option<u64> {
if initial > MAX_DYNAMIC_BYTES as u64
|| self.private_heaps.len() >= 256
+1
View File
@@ -396,6 +396,7 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc<Serv
events::register(registry, &state);
crt::register(registry);
crt::register_heap(registry);
crt::register_errno(registry);
heap::register(registry, &state);
// 1. GetSystemTimeAsFileTime(lpSystemTimeAsFileTime: *mut FILETIME)
+65 -15
View File
@@ -165,35 +165,85 @@ pub(super) fn register(registry: &mut ImportRegistry) {
}
}
const ENOMEM: u32 = 12;
const EINVAL: u32 = 22;
fn set_errno(memory: &mut GuestMemory, error: u32) -> Result<(), ExitReason> {
let address = memory
.crt_errno_address()
.map_err(ExitReason::MemoryFault)?;
memory
.write_u32(address, error)
.map_err(ExitReason::MemoryFault)
}
fn allocation_result(
memory: &mut GuestMemory,
result: Result<u64, MemoryError>,
) -> Result<u64, ExitReason> {
match result {
Ok(address) => Ok(address),
Err(_) => {
set_errno(memory, ENOMEM)?;
Ok(0)
}
}
}
pub(super) fn register_errno(registry: &mut ImportRegistry) {
registry.register(UCRT, "_errno", |_, _, memory| {
memory.crt_errno_address().map_err(ExitReason::MemoryFault)
});
registry.register(UCRT, "_set_errno", |args, _, memory| {
set_errno(memory, args.rcx as u32)?;
Ok(0)
});
registry.register(UCRT, "_get_errno", |args, _, memory| {
if args.rcx == 0 {
set_errno(memory, EINVAL)?;
return Ok(u64::from(EINVAL));
}
let address = memory
.crt_errno_address()
.map_err(ExitReason::MemoryFault)?;
let value = memory.read_u32(address).map_err(ExitReason::MemoryFault)?;
memory
.write_u32(args.rcx, value)
.map_err(ExitReason::MemoryFault)?;
Ok(0)
});
for symbol in ["_errno", "_set_errno", "_get_errno"] {
registry.alias("api-ms-win-crt-runtime-l1-1-0.dll", UCRT, symbol);
registry.set_status(UCRT, symbol, ServiceStatus::Partial);
}
}
pub(super) fn register_heap(registry: &mut ImportRegistry) {
registry.register(UCRT, "malloc", |args, _, memory| {
Ok(memory
.map_heap_allocation(PROCESS_HEAP, args.rcx.max(1) as usize)
.unwrap_or(0))
let result = memory.map_heap_allocation(PROCESS_HEAP, args.rcx.max(1) as usize);
allocation_result(memory, result)
});
registry.register(UCRT, "calloc", |args, _, memory| {
let Some(size) = args.rcx.checked_mul(args.rdx) else {
return Ok(0);
};
Ok(memory
.map_heap_allocation(PROCESS_HEAP, size.max(1) as usize)
.unwrap_or(0))
let result = args
.rcx
.checked_mul(args.rdx)
.ok_or(MemoryError::AllocationFailed)
.and_then(|size| memory.map_heap_allocation(PROCESS_HEAP, size.max(1) as usize));
allocation_result(memory, result)
});
registry.register(UCRT, "realloc", |args, _, memory| {
let address = args.rcx;
let size = args.rdx;
if address == 0 {
return Ok(memory
.map_heap_allocation(PROCESS_HEAP, size.max(1) as usize)
.unwrap_or(0));
let result = memory.map_heap_allocation(PROCESS_HEAP, size.max(1) as usize);
return allocation_result(memory, result);
}
if size == 0 {
free(memory, address)?;
return Ok(0);
}
Ok(memory
.resize_heap_allocation(PROCESS_HEAP, address, size as usize, false)
.unwrap_or(0))
let result = memory.resize_heap_allocation(PROCESS_HEAP, address, size as usize, false);
allocation_result(memory, result)
});
registry.register(UCRT, "free", |args, _, memory| {
free(memory, args.rcx)?;
+70
View File
@@ -1192,6 +1192,76 @@ fn test_guest_event_signaling_through_iat() {
assert_eq!(call(kernel, "CloseHandle", &[copy]), 1);
}
#[test]
fn test_guest_crt_errno_through_iat() {
const MODULE: &str = "api-ms-win-crt-runtime-l1-1-0.dll";
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0))));
let run = |first, argument: u64, second, output: u64| {
let mut code = vec![0x48, 0x83, 0xec, 0x28, 0x48, 0xb9];
code.extend_from_slice(&argument.to_le_bytes());
append_import_call(&mut code, 0x2060);
code.extend_from_slice(&[0x48, 0x89, 0xc3, 0x48, 0xb9]);
code.extend_from_slice(&output.to_le_bytes());
append_import_call(&mut code, 0x21a0);
code.extend_from_slice(&[0x48, 0x83, 0xc4, 0x28, 0xf4]);
let bytes = TestPeBuilder::new(0x140000000, 0x1000)
.add_import("ucrtbase.dll", first)
.add_import(MODULE, second)
.code(&code)
.build();
let mut imports = ImportRegistry::new();
register_standard_services(&mut imports, state.clone());
let result = run_synthetic_startup(
&bytes,
StartupLayout {
image_base: 0x140000000,
stack_top: PROCESS_FIXTURE_STACK_TOP,
tls_base: 0x300000000,
},
imports,
100,
)
.unwrap();
assert_eq!(result.bound_imports, 2);
assert_eq!(result.execution.exit_reason, ExitReason::Halt);
result
};
let output = PROCESS_FIXTURE_OUTPUT;
let failed = run("malloc", u64::MAX, "_get_errno", output);
assert_eq!(failed.execution.final_state.get(Register::Rbx), 0);
assert_eq!(failed.execution.final_state.get(Register::Rax), 0);
assert_eq!(failed.image.memory.read_u32(output).unwrap(), 12);
let set = run("_set_errno", 34, "_errno", 0);
let slot = set.execution.final_state.get(Register::Rax);
assert_eq!(set.image.memory.read_u32(slot).unwrap(), 34);
let fresh = run("_errno", 0, "_errno", 0);
assert_eq!(
fresh.execution.final_state.get(Register::Rbx),
fresh.execution.final_state.get(Register::Rax)
);
assert_eq!(
fresh
.image
.memory
.read_u32(fresh.execution.final_state.get(Register::Rax))
.unwrap(),
0
);
let invalid = run("_get_errno", 0, "_errno", 0);
assert_eq!(invalid.execution.final_state.get(Register::Rbx), 22);
assert_eq!(
invalid
.image
.memory
.read_u32(invalid.execution.final_state.get(Register::Rax))
.unwrap(),
22
);
}
#[test]
fn test_guest_crt_allocation_and_resize_through_iat() {
const IMAGE: u64 = 0x140000000;
+4 -1
View File
@@ -176,7 +176,10 @@ UCRT and the CRT heap API set expose `malloc`, `calloc`, `realloc`, and
`free` on the bounded default guest heap. `calloc` checks for size overflow.
`realloc(NULL, size)` allocates a new block, and resizing a nonnull block to
zero frees it. Allocation failures return null and preserve existing blocks.
CRT `errno` and new-handler callbacks remain unsupported. See
Allocation failures also set the synthetic main thread's CRT `errno` to
`ENOMEM`. The runtime API set and UCRT expose `_errno`, `_get_errno`, and
`_set_errno` through a stable guest memory slot. Additional guest threads
and CRT parameter or new-handler callbacks remain unsupported. See
[Microsoft CRT allocation documentation](https://learn.microsoft.com/cpp/c-runtime-library/memory-allocation).
### Event signaling