mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-26 03:39:52 +00:00
Serve bounded CRT byte string lengths through the guest registry
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
This commit is contained in:
1 parent
7130da2635
commit
e4b1898b00
9 files changed
+90
-17
No files matched your search
@@ -11,6 +11,8 @@ remains unsupported.
|
||||
|
||||
### Added
|
||||
|
||||
- Added guest CRT string length services for UCRT and its string API set.
|
||||
|
||||
- Added unnamed guest events with manual and automatic reset, signaling, immediate waits, and same-process handle duplication.
|
||||
|
||||
- Added same-process duplication of synthetic thread handles with independent closure.
|
||||
|
||||
@@ -204,6 +204,11 @@ impl SymbolDb {
|
||||
|
||||
fn populate_crt_string(&mut self) {
|
||||
let m = "api-ms-win-crt-string-l1-1-0.dll";
|
||||
for module in [m, "ucrtbase.dll"] {
|
||||
for symbol in ["strlen", "strnlen"] {
|
||||
self.ins(module, symbol, Classification::StandardService);
|
||||
}
|
||||
}
|
||||
for (sym, libc) in &[
|
||||
("isalnum", "isalnum"),
|
||||
("isalpha", "isalpha"),
|
||||
@@ -226,7 +231,6 @@ impl SymbolDb {
|
||||
("strcmp", "strcmp"),
|
||||
("strcpy", "strcpy"),
|
||||
("strcspn", "strcspn"),
|
||||
("strlen", "strlen"),
|
||||
("strncat", "strncat"),
|
||||
("strncmp", "strncmp"),
|
||||
("strncpy", "strncpy"),
|
||||
|
||||
@@ -347,18 +347,6 @@ fn symbol_to_ident_lower(sym: &str) -> String {
|
||||
/// Returns a dispatch body for CRT calls with a compatible guest ABI adapter.
|
||||
fn crt_dispatch_expr(symbol: &str) -> Option<String> {
|
||||
Some(match symbol {
|
||||
"strlen" => r#"// strlen: RCX = guest pointer to null-terminated string
|
||||
let ptr = args.rcx;
|
||||
if ptr == 0 { return Ok(0); }
|
||||
let mut len: u64 = 0;
|
||||
loop {
|
||||
let b = mem.read_u8(ptr + len).map_err(ExitReason::MemoryFault)?;
|
||||
if b == 0 { break; }
|
||||
len += 1;
|
||||
if len > 1_048_576 { break; } // safety cap 1 MiB
|
||||
}
|
||||
Ok(len)"#
|
||||
.to_string(),
|
||||
// memset(dst, val, count) -> dst
|
||||
"memset" => r#"let dst = args.rcx;
|
||||
let val = (args.rdx & 0xFF) as u8;
|
||||
|
||||
@@ -193,6 +193,14 @@ impl MetadataCatalog {
|
||||
"<string.h>",
|
||||
"Calculates the length of a string in guest memory",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"strnlen",
|
||||
AbiType::U64,
|
||||
vec![("str", AbiType::StringAnsi), ("count", AbiType::U64)],
|
||||
"<string.h>",
|
||||
"Calculates a byte string length up to the supplied bound",
|
||||
);
|
||||
self.add(
|
||||
"ucrtbase.dll",
|
||||
"strcmp",
|
||||
|
||||
@@ -16,7 +16,7 @@ fn test_builtin_db_classifies_crt_math() {
|
||||
fn test_builtin_db_classifies_crt_string() {
|
||||
let db = SymbolDb::builtin();
|
||||
let strlen_cls = db.get("api-ms-win-crt-string-l1-1-0.dll", "strlen");
|
||||
assert!(matches!(strlen_cls, Some(Classification::CrtNative { .. })));
|
||||
assert!(matches!(strlen_cls, Some(Classification::StandardService)));
|
||||
|
||||
let strcat_s_cls = db.get("api-ms-win-crt-string-l1-1-0.dll", "strcat_s");
|
||||
assert!(matches!(
|
||||
@@ -37,7 +37,7 @@ fn test_builtin_db_case_insensitive() {
|
||||
fn test_manifest_and_codegen_pipeline() {
|
||||
let csv_content = r#""module","symbol_or_ordinal","iat_rva"
|
||||
"api-ms-win-crt-math-l1-1-0.dll","acos",0x1000
|
||||
"api-ms-win-crt-string-l1-1-0.dll","strlen",0x1008
|
||||
"api-ms-win-crt-string-l1-1-0.dll","memset",0x1008
|
||||
"api-ms-win-core-processthreads-l1-1-0.dll","CreateThread",0x1010
|
||||
"custom.dll","UnknownCustomFunc",0x1018
|
||||
"kernel32.dll","QueryPerformanceCounter",0x1020
|
||||
@@ -68,7 +68,7 @@ fn test_manifest_and_codegen_pipeline() {
|
||||
|
||||
let files = generate(&manifest, &db);
|
||||
assert!(files.crt_rs.contains("register_generated_crt_services"));
|
||||
assert!(files.crt_rs.contains("strlen"));
|
||||
assert!(files.crt_rs.contains("memset"));
|
||||
let acos = files.crt_rs.split_once("\"acos\"").unwrap().1;
|
||||
let (acos, _) = acos.split_once("registry.register_with_status").unwrap();
|
||||
assert!(acos.contains("ServiceStatus::Stub"));
|
||||
@@ -79,7 +79,7 @@ fn test_manifest_and_codegen_pipeline() {
|
||||
assert!(!files.stubs_rs.contains("GetThreadId"));
|
||||
assert!(!files.stubs_rs.contains("DuplicateHandle"));
|
||||
assert!(!files.stubs_rs.contains("GetTickCount64"));
|
||||
assert!(files.tests_rs.contains("generated_test_strlen"));
|
||||
assert!(files.tests_rs.contains("generated_test_memset"));
|
||||
|
||||
let out_dir = tmp_dir.join("out");
|
||||
files.write_all(out_dir.to_str().unwrap()).unwrap();
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
//! - Virtual memory: `VirtualAlloc`, `VirtualFree`
|
||||
//! - Xbox physical memory: `XMemAlloc`, `XMemFree`
|
||||
|
||||
mod crt;
|
||||
mod events;
|
||||
|
||||
use crate::cpu::ExitReason;
|
||||
@@ -392,6 +393,7 @@ pub fn register_standard_services(registry: &mut ImportRegistry, state: Arc<Serv
|
||||
registry.set_status(KERNEL32, "DuplicateHandle", ServiceStatus::Partial);
|
||||
|
||||
events::register(registry, &state);
|
||||
crt::register(registry);
|
||||
|
||||
// 1. GetSystemTimeAsFileTime(lpSystemTimeAsFileTime: *mut FILETIME)
|
||||
let s = state.clone();
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
//! C runtime services that operate on checked guest memory.
|
||||
|
||||
use crate::cpu::ExitReason;
|
||||
use crate::imports::{ImportRegistry, ServiceStatus};
|
||||
use crate::memory::{GuestMemory, MemoryError};
|
||||
|
||||
const SCAN_BUDGET: u64 = 1_048_576;
|
||||
const UCRT: &str = "ucrtbase.dll";
|
||||
const CRT_STRING_API: &str = "api-ms-win-crt-string-l1-1-0.dll";
|
||||
|
||||
fn string_length(memory: &GuestMemory, address: u64, limit: u64) -> Result<u64, ExitReason> {
|
||||
if limit != 0 && address == 0 {
|
||||
return Err(ExitReason::MemoryFault(MemoryError::UnmappedAddress(0)));
|
||||
}
|
||||
for offset in 0..limit.min(SCAN_BUDGET) {
|
||||
let address = address
|
||||
.checked_add(offset)
|
||||
.ok_or(ExitReason::MemoryFault(MemoryError::Overflow))?;
|
||||
if memory.read_u8(address).map_err(ExitReason::MemoryFault)? == 0 {
|
||||
return Ok(offset);
|
||||
}
|
||||
}
|
||||
if limit <= SCAN_BUDGET {
|
||||
return Ok(limit);
|
||||
}
|
||||
Err(ExitReason::IllegalInstruction(0xFE))
|
||||
}
|
||||
|
||||
pub(super) fn register(registry: &mut ImportRegistry) {
|
||||
registry.register(UCRT, "strlen", |args, _, memory| {
|
||||
string_length(memory, args.rcx, u64::MAX)
|
||||
});
|
||||
registry.register(UCRT, "strnlen", |args, _, memory| {
|
||||
string_length(memory, args.rcx, args.rdx)
|
||||
});
|
||||
|
||||
for symbol in ["strlen", "strnlen"] {
|
||||
registry.alias(CRT_STRING_API, UCRT, symbol);
|
||||
registry.set_status(UCRT, symbol, ServiceStatus::Partial);
|
||||
}
|
||||
}
|
||||
@@ -1022,6 +1022,24 @@ fn test_guest_duplicates_thread_handle_through_iat() {
|
||||
assert_eq!(call("GetThreadId", copy), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_guest_crt_string_length_through_iat() {
|
||||
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0))));
|
||||
for module in ["ucrtbase.dll", "api-ms-win-crt-string-l1-1-0.dll"] {
|
||||
// The fixture seeds the output slot with eight 0xff bytes followed by zeroed stack bytes.
|
||||
for (symbol, address, bound, expected) in [
|
||||
("strlen", PROCESS_FIXTURE_OUTPUT, 0, 8),
|
||||
("strlen", PROCESS_FIXTURE_OUTPUT + 8, 0, 0),
|
||||
("strnlen", PROCESS_FIXTURE_OUTPUT, 3, 3),
|
||||
("strnlen", PROCESS_FIXTURE_OUTPUT, 12, 8),
|
||||
("strnlen", PROCESS_FIXTURE_STACK_TOP, 0, 0),
|
||||
] {
|
||||
let result = call_service_fixture(&state, module, symbol, &[address, bound]);
|
||||
assert_eq!(result.execution.final_state.get(Register::Rax), expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_guest_event_signaling_through_iat() {
|
||||
let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0))));
|
||||
|
||||
@@ -140,6 +140,14 @@ 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.
|
||||
|
||||
### CRT byte strings
|
||||
|
||||
The standard registry provides `strlen` and `strnlen` under UCRT and the CRT
|
||||
string API set. They count bytes using checked guest memory. The scan stops at
|
||||
a null byte or the requested bound for `strnlen`. A scan that would continue
|
||||
past 1 MiB reports an unsupported-service fault. See the
|
||||
[Microsoft CRT string-length contract](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/strnlen-strnlen-s).
|
||||
|
||||
### Event signaling
|
||||
|
||||
The synthetic runtime supports unnamed manual-reset and auto-reset events
|
||||
|
||||
Reference in new issue
Block a user