diff --git a/CHANGELOG.md b/CHANGELOG.md index 36b69d1..8e7f1b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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. diff --git a/crates/import-gen/src/classify.rs b/crates/import-gen/src/classify.rs index eb9f3b8..838a8b3 100644 --- a/crates/import-gen/src/classify.rs +++ b/crates/import-gen/src/classify.rs @@ -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"), diff --git a/crates/import-gen/src/codegen.rs b/crates/import-gen/src/codegen.rs index 7cd8ebb..d56b237 100644 --- a/crates/import-gen/src/codegen.rs +++ b/crates/import-gen/src/codegen.rs @@ -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 { 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; diff --git a/crates/import-gen/src/metadata.rs b/crates/import-gen/src/metadata.rs index 8d6be1c..42e60a7 100644 --- a/crates/import-gen/src/metadata.rs +++ b/crates/import-gen/src/metadata.rs @@ -193,6 +193,14 @@ impl MetadataCatalog { "", "Calculates the length of a string in guest memory", ); + self.add( + "ucrtbase.dll", + "strnlen", + AbiType::U64, + vec![("str", AbiType::StringAnsi), ("count", AbiType::U64)], + "", + "Calculates a byte string length up to the supplied bound", + ); self.add( "ucrtbase.dll", "strcmp", diff --git a/crates/import-gen/tests/pipeline.rs b/crates/import-gen/tests/pipeline.rs index a030106..179c696 100644 --- a/crates/import-gen/tests/pipeline.rs +++ b/crates/import-gen/tests/pipeline.rs @@ -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(); diff --git a/crates/loader/src/services.rs b/crates/loader/src/services.rs index 8968051..e8ff905 100644 --- a/crates/loader/src/services.rs +++ b/crates/loader/src/services.rs @@ -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 Result { + 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); + } +} diff --git a/crates/loader/tests/runtime_x15.rs b/crates/loader/tests/runtime_x15.rs index a9e0be0..3c11461 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -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)))); diff --git a/docs/interfaces.md b/docs/interfaces.md index 9d4b8d5..44cd378 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -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