From d76c7d061c8076ffc6b2dcf9f94737cb7d566c08 Mon Sep 17 00:00:00 2001 From: Adeeb Rahman Date: Tue, 24 Nov 2026 01:22:38 -0500 Subject: [PATCH] Compare CRT byte strings through checked guest reads Signed-off-by: Adeeb Rahman --- CHANGELOG.md | 2 ++ crates/import-gen/src/classify.rs | 6 ++--- crates/import-gen/src/codegen.rs | 24 ------------------ crates/import-gen/tests/pipeline.rs | 6 ++--- crates/loader/src/services/crt.rs | 39 ++++++++++++++++++++++++++++- crates/loader/tests/runtime_x15.rs | 20 +++++++++++++++ docs/interfaces.md | 4 +++ 7 files changed, 70 insertions(+), 31 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7d616a2..5789957 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,8 @@ remains unsupported. ### Added +- Added checked guest CRT byte string comparison with `strcmp` and `strncmp`. + - Added bounded guest CRT byte fill, copy, move, and comparison services. - Added guest CRT string length services for UCRT and its string API set. diff --git a/crates/import-gen/src/classify.rs b/crates/import-gen/src/classify.rs index bf5e65c..08d6a05 100644 --- a/crates/import-gen/src/classify.rs +++ b/crates/import-gen/src/classify.rs @@ -205,7 +205,9 @@ 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", "memset", "memcpy", "memmove", "memcmp"] { + for symbol in [ + "strlen", "strnlen", "strcmp", "strncmp", "memset", "memcpy", "memmove", "memcmp", + ] { self.ins(module, symbol, Classification::StandardService); } } @@ -224,11 +226,9 @@ impl SymbolDb { ("toupper", "toupper"), ("memchr", "memchr"), ("strcat", "strcat"), - ("strcmp", "strcmp"), ("strcpy", "strcpy"), ("strcspn", "strcspn"), ("strncat", "strncat"), - ("strncmp", "strncmp"), ("strncpy", "strncpy"), ("strpbrk", "strpbrk"), ("strspn", "strspn"), diff --git a/crates/import-gen/src/codegen.rs b/crates/import-gen/src/codegen.rs index 155b4e6..7896565 100644 --- a/crates/import-gen/src/codegen.rs +++ b/crates/import-gen/src/codegen.rs @@ -347,30 +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 { - // strcmp(a, b) -> int - "strcmp" => r#"let a = args.rcx; - let b = args.rdx; - let mut i = 0u64; - loop { - let ca = mem.read_u8(a + i).map_err(ExitReason::MemoryFault)?; - let cb = mem.read_u8(b + i).map_err(ExitReason::MemoryFault)?; - if ca != cb { return Ok((ca as i64 - cb as i64) as u64); } - if ca == 0 { return Ok(0); } - i += 1; - }"# - .to_string(), - // strncmp(a, b, n) -> int - "strncmp" => r#"let a = args.rcx; - let b = args.rdx; - let n = args.r8 as usize; - for i in 0..n as u64 { - let ca = mem.read_u8(a + i).map_err(ExitReason::MemoryFault)?; - let cb = mem.read_u8(b + i).map_err(ExitReason::MemoryFault)?; - if ca != cb { return Ok((ca as i64 - cb as i64) as u64); } - if ca == 0 { return Ok(0); } - } - Ok(0)"# - .to_string(), // abs(int) -> int "abs" | "labs" => r#"let x = args.rcx as i32; Ok(x.abs() as u64)"# diff --git a/crates/import-gen/tests/pipeline.rs b/crates/import-gen/tests/pipeline.rs index 4f17a30..39da5ac 100644 --- a/crates/import-gen/tests/pipeline.rs +++ b/crates/import-gen/tests/pipeline.rs @@ -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","strcmp",0x1008 +"api-ms-win-crt-string-l1-1-0.dll","tolower",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("strcmp")); + assert!(files.crt_rs.contains("tolower")); 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_strcmp")); + assert!(files.tests_rs.contains("generated_test_tolower")); let out_dir = tmp_dir.join("out"); files.write_all(out_dir.to_str().unwrap()).unwrap(); diff --git a/crates/loader/src/services/crt.rs b/crates/loader/src/services/crt.rs index 2a66385..0aaa600 100644 --- a/crates/loader/src/services/crt.rs +++ b/crates/loader/src/services/crt.rs @@ -28,6 +28,34 @@ fn string_length(memory: &GuestMemory, address: u64, limit: u64) -> Result Result { + for offset in 0..limit.min(SCAN_BUDGET) { + let read = |base: u64| { + if base == 0 { + return Err(ExitReason::MemoryFault(MemoryError::UnmappedAddress(0))); + } + let address = base + .checked_add(offset) + .ok_or(ExitReason::MemoryFault(MemoryError::Overflow))?; + memory.read_u8(address).map_err(ExitReason::MemoryFault) + }; + let a = read(left)?; + let b = read(right)?; + if a != b || a == 0 { + return Ok(u64::from((i32::from(a) - i32::from(b)) as u32)); + } + } + if limit <= SCAN_BUDGET { + return Ok(0); + } + Err(ExitReason::IllegalInstruction(0xFE)) +} + fn transfer_buffer(count: u64, fill: u8) -> Result, ExitReason> { if count > SCAN_BUDGET { return Err(ExitReason::IllegalInstruction(0xFE)); @@ -49,6 +77,13 @@ pub(super) fn register(registry: &mut ImportRegistry) { string_length(memory, args.rcx, args.rdx) }); + registry.register(UCRT, "strcmp", |args, _, memory| { + compare_strings(memory, args.rcx, args.rdx, u64::MAX) + }); + registry.register(UCRT, "strncmp", |args, _, memory| { + compare_strings(memory, args.rcx, args.rdx, args.r8) + }); + registry.register(UCRT, "memset", |args, _, memory| { if args.r8 != 0 { let buffer = transfer_buffer(args.r8, args.rdx as u8)?; @@ -94,7 +129,9 @@ pub(super) fn register(registry: &mut ImportRegistry) { Ok(u64::from(result as u32)) }); - for symbol in ["strlen", "strnlen", "memset", "memcpy", "memmove", "memcmp"] { + for symbol in [ + "strlen", "strnlen", "strcmp", "strncmp", "memset", "memcpy", "memmove", "memcmp", + ] { 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 a4b39f7..74b8553 100644 --- a/crates/loader/tests/runtime_x15.rs +++ b/crates/loader/tests/runtime_x15.rs @@ -1061,6 +1061,26 @@ fn test_guest_crt_memory_through_iat() { } } +#[test] +fn test_guest_crt_string_comparison_through_iat() { + let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); + let slot = PROCESS_FIXTURE_OUTPUT; + for (symbol, a, b, limit, expected) in [ + ("strcmp", slot, slot + 8, 0, 255), + ("strcmp", slot + 8, slot, 0, -255), + ("strcmp", slot, slot, 0, 0), + ("strncmp", slot, slot + 1, 7, 0), + ("strncmp", slot, slot + 1, 8, 255), + ("strncmp", u64::MAX, u64::MAX, 0, 0), + ] { + let result = call_service_fixture(&state, "ucrtbase.dll", symbol, &[a, b, limit]); + assert_eq!( + result.execution.final_state.get(Register::Rax) as i32, + expected + ); + } +} + #[test] fn test_guest_crt_string_length_through_iat() { let state = Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))); diff --git a/docs/interfaces.md b/docs/interfaces.md index 82b225d..ed61b7c 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -148,6 +148,10 @@ 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). +The same modules expose `strcmp` and `strncmp`. These compare unsigned bytes +and stop at the first difference, null byte, or supplied comparison bound. +They share the 1 MiB scan budget. + The same modules expose `memset`, `memcpy`, `memmove`, and `memcmp` for spans up to 1 MiB. Each nonempty span must fit in one mapped guest region with the required permissions. Writes validate the full destination before changing