Fix ANSI path encoding, HLE alias stubs/handles, ordinal/forwarder resolution, and stub race

This commit is contained in:
raylitebull
2026-11-23 12:04:32 +01:00
parent 60599a948f
commit eac85f952e
5 changed files with 568 additions and 51 deletions
+69 -3
View File
@@ -1131,16 +1131,41 @@ pub unsafe extern "system" fn GetProcAddress(h: usize, name: *const u8) -> usize
}
fn module_handle_impl(name: &str) -> usize {
module_handle_in(crate::hle::registry(), name)
}
fn module_handle_in(reg: &crate::hle::Registry, name: &str) -> usize {
let key = dll_key(name);
let reg = crate::hle::registry();
if let Some(m) = reg.hle_for(&key) {
if !(m.aliases_are_system() && key != m.name) {
match reg.route(&key) {
Some(crate::hle::Route::Hle(i)) => {
let m = &reg.modules[*i];
if m.aliases_are_system() && key != m.name {
// Real Windows DLLs (kernel32 / kernelbase / advapi32 / Windows API sets) keep
// their genuine HMODULE; console-only aliases (advapi32legacy, kernel32legacy,
// minappmodelx) fall back to the HLE pseudo handle, matching LoadLibrary.
// SAFETY: `wide(name)` produces a valid NUL-terminated UTF-16 string.
let real = unsafe { ll::GetModuleHandleW(crate::util::wide(name).as_ptr()) as usize };
if real != 0 {
return real;
}
}
return modules::hle_handle(m.name);
}
Some(crate::hle::Route::Stub) => {
// Return the pseudo handle only if the @stub DLL has already been loaded or imported,
// preserving GetModuleHandle's non-loading probe semantics for optional DLLs.
return modules::find_hle_handle(&key).unwrap_or(0);
}
Some(crate::hle::Route::System) => {
// SAFETY: `wide(name)` produces a valid NUL-terminated UTF-16 string.
return unsafe { ll::GetModuleHandleW(crate::util::wide(name).as_ptr()) as usize };
}
None => {}
}
if let Some(m) = modules::find_mapped_by_name(&key) {
return m.base;
}
// SAFETY: `wide(name)` produces a valid NUL-terminated UTF-16 string.
unsafe { ll::GetModuleHandleW(crate::util::wide(name).as_ptr()) as usize }
}
@@ -1565,4 +1590,45 @@ mod tests {
}
}
}
#[test]
fn get_module_handle_matches_load_library_for_console_aliases_and_stubs() {
unsafe {
// Real Windows system DLL keeps its genuine Windows HMODULE.
let real_k32 = ll::GetModuleHandleW(crate::util::wide("kernel32.dll").as_ptr()) as usize;
assert_ne!(real_k32, 0);
assert_eq!(GetModuleHandleW(crate::util::wide("kernel32.dll").as_ptr()), real_k32);
assert_eq!(GetModuleHandleA(c"kernel32.dll".as_ptr() as *const u8), real_k32);
// Console-only kernelx aliases return the kernelx HLE pseudo handle (matching LoadLibrary).
let kx = modules::hle_handle(crate::hle::KERNELX);
for dll in ["advapi32legacy.dll", "kernel32legacy.dll", "minappmodelx.dll"] {
let w = crate::util::wide(dll);
let h_load = LoadLibraryW(w.as_ptr());
assert_eq!(h_load, kx, "LoadLibraryW({dll})");
assert_eq!(GetModuleHandleW(w.as_ptr()), kx, "GetModuleHandleW({dll})");
let c = std::ffi::CString::new(dll).unwrap();
assert_eq!(GetModuleHandleA(c.as_ptr() as *const u8), kx, "GetModuleHandleA({dll})");
let mut out = 0usize;
assert_eq!(GetModuleHandleExW(0, w.as_ptr(), &mut out), 1, "GetModuleHandleExW({dll})");
assert_eq!(out, kx);
}
// Unknown DLL still returns NULL + ERROR_MOD_NOT_FOUND.
fnd::SetLastError(0);
assert_eq!(GetModuleHandleW(crate::util::wide("no_such_optional_dll_xyz.dll").as_ptr()), 0);
assert_eq!(fnd::GetLastError(), fnd::ERROR_MOD_NOT_FOUND);
}
// @stub DLLs: unloaded probe returns 0; once loaded (hle_handle created), returns that handle.
let mut cfg = crate::config::Config::default();
cfg.aliases.insert("unit_stub_probe.dll".into(), "@stub".into());
let reg = crate::hle::build(&cfg);
assert_eq!(module_handle_in(&reg, "unit_stub_probe.dll"), 0);
let stub_h = modules::hle_handle("unit_stub_probe.dll");
assert_ne!(stub_h, 0);
assert_eq!(module_handle_in(&reg, "unit_stub_probe.dll"), stub_h);
}
}
+6
View File
@@ -114,6 +114,12 @@ pub fn hle_handle(module_name: &str) -> usize {
p as usize
}
pub fn find_hle_handle(module_name: &str) -> Option<usize> {
let key = crate::util::dll_key(module_name);
let g = HLE_HANDLES.lock().ok()?;
g.as_ref()?.get(&key).copied()
}
pub fn hle_name_by_handle(h: usize) -> Option<String> {
let g = HLE_HANDLES.lock().ok()?;
g.as_ref()?.iter().find(|(_, &v)| v == h).map(|(k, _)| k.clone())
+183 -26
View File
@@ -104,14 +104,19 @@ fn hle_name_for<'a>(m: &'a HleModule, dll: &str, what: &'a ImportName) -> Option
/// HLE lookup with cross-module search and (kernel family) system fallback.
fn resolve_hle(m: &HleModule, key: &str, what: &ImportName) -> Option<(usize, Source)> {
let name = hle_name_for(m, key, what)?;
if let Some(&a) = m.exports.get(name) {
return Some((a, Source::Hle(m.name.to_string())));
}
if let Some((other, a)) = registry().find_any(name) {
return Some((a, Source::HleOther(other.name.to_string())));
}
let n = ImportName::Name { hint: 0, name: name.to_string() };
let fallback_what = if let Some(name) = hle_name_for(m, key, what) {
if let Some(&a) = m.exports.get(name) {
return Some((a, Source::Hle(m.name.to_string())));
}
if let Some((other, a)) = registry().find_any(name) {
return Some((a, Source::HleOther(other.name.to_string())));
}
Some(ImportName::Name { hint: 0, name: name.to_string() })
} else {
None
};
let query = fallback_what.as_ref().unwrap_or(what);
let ordinal_only = fallback_what.is_none();
for &c in m.fallback {
let c = if c == crate::hle::SELF {
if key == m.name {
@@ -121,7 +126,11 @@ fn resolve_hle(m: &HleModule, key: &str, what: &ImportName) -> Option<(usize, So
} else {
c
};
if let Some(a) = system_proc(c, &n) {
// Raw ordinals are DLL-specific: never resolve one DLL's ordinal in a different DLL.
if ordinal_only && c != key {
continue;
}
if let Some(a) = system_proc(c, query) {
return Some((a, Source::System(c.to_string())));
}
}
@@ -152,6 +161,15 @@ pub fn find_game_dll(name: &str) -> Option<PathBuf> {
}
pub fn resolve_export_of_mapped(m: &modules::MappedModule, what: &ImportName, depth: u32) -> Option<usize> {
resolve_export_of_mapped_inner(m, what, depth, false)
}
fn resolve_export_of_mapped_inner(
m: &modules::MappedModule,
what: &ImportName,
depth: u32,
allow_stub: bool,
) -> Option<usize> {
let t = match what {
ImportName::Name { name, .. } => m.exports.by_name.get(name)?,
ImportName::Ordinal(o) => m.exports.by_ordinal.get(&(*o as u32))?,
@@ -162,67 +180,85 @@ pub fn resolve_export_of_mapped(m: &modules::MappedModule, what: &ImportName, de
if depth > 8 {
return None;
}
let (dll, func) = f.split_once('.')?;
let (dll, func) = f.rsplit_once('.')?;
if dll.is_empty() || func.is_empty() {
return None;
}
let what = match func.strip_prefix('#') {
Some(n) => ImportName::Ordinal(n.parse().ok()?),
None => ImportName::Name { hint: 0, name: func.to_string() },
};
Some(resolve_inner(&dll_key(dll), &what, depth + 1).0)
let target_key = if dll.to_ascii_lowercase().ends_with(".dll") {
dll_key(dll)
} else {
dll_key(&format!("{dll}.dll"))
};
resolve_inner_opt(&target_key, &what, depth + 1, allow_stub).map(|(a, _)| a)
}
}
}
fn stub_for(key: &str, what: &ImportName) -> (usize, Source) {
fn stub_for(key: &str, fallback_dll: Option<&str>, what: &ImportName) -> (usize, Source) {
let name = fname(what);
let ret = stubs::db().return_for(key, &name);
let ret = stubs::db().return_for_with_fallback(key, fallback_dll, &name);
(stubs::make_stub(key, &name, ret), Source::Stub)
}
fn resolve_inner(key: &str, what: &ImportName, depth: u32) -> (usize, Source) {
resolve_inner_opt(key, what, depth, true).expect("allow_stub=true always resolves")
}
fn resolve_inner_opt(key: &str, what: &ImportName, depth: u32, allow_stub: bool) -> Option<(usize, Source)> {
let reg = registry();
match reg.route(key) {
Some(Route::Stub) => return stub_for(key, what),
Some(Route::Stub) => {
return allow_stub.then(|| {
modules::hle_handle(key);
stub_for(key, None, what)
});
}
Some(Route::System) => {
return match system_proc(key, what) {
Some(a) => (a, Source::System(key.to_string())),
None => stub_for(key, what),
Some(a) => Some((a, Source::System(key.to_string()))),
None => allow_stub.then(|| stub_for(key, None, what)),
}
}
Some(Route::Hle(i)) => {
let m = &reg.modules[*i];
return resolve_hle(m, key, what).unwrap_or_else(|| stub_for(key, what));
let fallback = (m.name != key).then_some(m.name);
return resolve_hle(m, key, what).or_else(|| allow_stub.then(|| stub_for(key, fallback, what)));
}
None => {}
}
// DLL shipped with the game → our loader
if let Some(m) = modules::find_mapped_by_name(key) {
if let Some(a) = resolve_export_of_mapped(&m, what, depth) {
return (a, Source::GameDll(key.to_string()));
if let Some(a) = resolve_export_of_mapped_inner(&m, what, depth, allow_stub) {
return Some((a, Source::GameDll(key.to_string())));
}
return stub_for(key, what);
return allow_stub.then(|| stub_for(key, None, what));
}
if let Some(path) = find_game_dll(key) {
match crate::loader::load_game_dll(&path) {
Ok(m) => {
if let Some(a) = resolve_export_of_mapped(&m, what, depth) {
return (a, Source::GameDll(key.to_string()));
if let Some(a) = resolve_export_of_mapped_inner(&m, what, depth, allow_stub) {
return Some((a, Source::GameDll(key.to_string())));
}
return stub_for(key, what);
return allow_stub.then(|| stub_for(key, None, what));
}
Err(e) => crate::xlog_error!("failed to load {}: {e}", path.display()),
}
}
// Real Windows DLL
if let Some(a) = system_proc(key, what) {
return (a, Source::System(key.to_string()));
return Some((a, Source::System(key.to_string())));
}
// A known console function imported from an unexpected DLL
if let ImportName::Name { name, .. } = what {
if let Some((m, a)) = reg.find_any(name) {
return (a, Source::HleOther(m.name.to_string()));
return Some((a, Source::HleOther(m.name.to_string())));
}
}
stub_for(key, what)
allow_stub.then(|| stub_for(key, None, what))
}
/// Resolve one static/delay import and record the outcome for the report.
@@ -395,4 +431,125 @@ mod tests {
let (a, s) = resolve_inner("advapi32.dll", &name("RegSetValueExW"), 0);
assert!(a != 0 && matches!(s, Source::System(ref d) if d == "advapi32.dll"), "{s:?}");
}
#[test]
fn hle_alias_stubs_inherit_canonical_module_default() {
let name = |s: &str| ImportName::Name { hint: 0, name: s.into() };
let e_notimpl = crate::util::E_NOTIMPL as u32 as u64;
for (dll, sym) in [
("xgameplatform.dll", "XUnimplementedAliasProbe"),
("xgameruntime.thunks.dll", "XUnimplementedThunkProbe"),
("d3d12x.dll", "D3D12UnimplementedAliasProbe"),
] {
let (addr, src) = resolve_inner(dll, &name(sym), 0);
assert_eq!(src, Source::Stub, "{dll}!{sym}");
let info = stubs::info_of_stub(addr).expect("stub info registered");
assert_eq!(info.ret, e_notimpl, "{dll}!{sym} should inherit E_NOTIMPL");
assert!(info.dll.eq_ignore_ascii_case(dll));
let f: extern "system" fn() -> u64 = unsafe { std::mem::transmute(addr) };
assert_eq!(f(), e_notimpl, "{dll}!{sym} thunk return");
}
// Kernel-family aliases keep default 0 (BOOL/handle APIs).
let (addr, src) = resolve_inner("advapi32legacy.dll", &name("UnimplementedKernelAliasProbe"), 0);
assert_eq!(src, Source::Stub);
assert_eq!(stubs::info_of_stub(addr).unwrap().ret, 0);
}
#[test]
fn ordinal_imports_fall_through_only_to_matching_system_dll() {
let ord1 = ImportName::Ordinal(1);
let expected = system_proc("kernel32.dll", &ord1).expect("kernel32 ordinal #1 exists");
let (addr, src) = resolve_inner("kernel32.dll", &ord1, 0);
assert_eq!(src, Source::System("kernel32.dll".into()));
assert_eq!(addr, expected);
// Console-only kernelx aliases must NOT borrow unrelated ordinals from kernelbase/kernel32.
let reg = registry();
let kx = reg.module_by_name(crate::hle::KERNELX).unwrap();
assert!(resolve_hle(kx, "kernelx.dll", &ord1).is_none());
assert!(resolve_hle(kx, "advapi32legacy.dll", &ord1).is_none());
}
#[test]
fn mapped_forwarders_preserve_get_proc_address_contract_and_dotted_dll_names() {
use std::sync::atomic::AtomicBool;
use std::sync::Arc;
use windows_sys::Win32::System::Memory::{VirtualAlloc, MEM_RESERVE, PAGE_NOACCESS};
// Reserve two disjoint 64 KiB ranges (0 committed RAM) so test bases never collide with
// real Windows DLLs in `modules::image_base_for_addr`.
let target_base = unsafe { VirtualAlloc(std::ptr::null(), 0x10000, MEM_RESERVE, PAGE_NOACCESS) } as usize;
let proxy_base = unsafe { VirtualAlloc(std::ptr::null(), 0x10000, MEM_RESERVE, PAGE_NOACCESS) } as usize;
assert_ne!(target_base, 0);
assert_ne!(proxy_base, 0);
let mut target_exports = crate::pe::OwnedExports::default();
target_exports.by_name.insert("RealExport".into(), ExportTarget::Rva(0x1234));
let target_mod = Arc::new(modules::MappedModule {
name: "dotted.fwdtarget.dll".into(),
path: PathBuf::from("dotted.fwdtarget.dll"),
base: target_base,
size: 0x10000,
entry_rva: 0,
is_dll: true,
exports: target_exports,
tls_callbacks: Mutex::new(Vec::new()),
no_thread_calls: AtomicBool::new(false),
initialized: AtomicBool::new(true),
stack_reserve: 0,
});
modules::register_mapped(target_mod);
let mut proxy_exports = crate::pe::OwnedExports::default();
proxy_exports
.by_name
.insert("MissingFwd".into(), ExportTarget::Forwarder("nonexistent_fwd_target.MissingApi".into()));
proxy_exports.by_name.insert(
"MissingHleFwd".into(),
ExportTarget::Forwarder("xgameruntime.thunks.XMissingForwardedApi".into()),
);
proxy_exports
.by_name
.insert("DottedFwd".into(), ExportTarget::Forwarder("dotted.fwdtarget.RealExport".into()));
proxy_exports
.by_name
.insert("KernelFwd".into(), ExportTarget::Forwarder("KERNEL32.GetCurrentProcessId".into()));
let proxy_mod = Arc::new(modules::MappedModule {
name: "fwd_proxy_unit.dll".into(),
path: PathBuf::from("fwd_proxy_unit.dll"),
base: proxy_base,
size: 0x10000,
entry_rva: 0,
is_dll: true,
exports: proxy_exports,
tls_callbacks: Mutex::new(Vec::new()),
no_thread_calls: AtomicBool::new(false),
initialized: AtomicBool::new(true),
stack_reserve: 0,
});
modules::register_mapped(Arc::clone(&proxy_mod));
let name = |s: &str| ImportName::Name { hint: 0, name: s.into() };
// GetProcAddress must return None (NOT synthesize a stub) on unresolvable forwarders.
assert_eq!(get_proc_address(proxy_base, &name("MissingFwd")), None);
assert_eq!(get_proc_address(proxy_base, &name("MissingHleFwd")), None);
// Dotted DLL forwarders split on the LAST dot and resolve cleanly.
assert_eq!(get_proc_address(proxy_base, &name("DottedFwd")), Some(target_base + 0x1234));
assert_eq!(
get_proc_address(proxy_base, &name("KernelFwd")),
system_proc("kernel32.dll", &name("GetCurrentProcessId"))
);
// Static import resolution through a mapped forwarder still synthesizes a stub when missing,
// including inheriting canonical E_NOTIMPL for dotted HLE alias forwarders.
let (stub_addr, _) = resolve_inner("fwd_proxy_unit.dll", &name("MissingHleFwd"), 0);
assert_eq!(
stubs::info_of_stub(stub_addr).map(|i| i.ret),
Some(crate::util::E_NOTIMPL as u32 as u64)
);
}
}
+81 -12
View File
@@ -35,7 +35,7 @@ pub type StubHook = fn(&StubInfo, usize);
static ALL: Mutex<Vec<&'static StubInfo>> = Mutex::new(Vec::new());
static ARENA: Mutex<(usize, usize)> = Mutex::new((0, 0)); // (next, end)
static BY_KEY: OnceLock<Mutex<HashMap<String, usize>>> = OnceLock::new();
static BY_KEY: OnceLock<Mutex<HashMap<String, (usize, &'static StubInfo)>>> = OnceLock::new();
const THUNK_SIZE: usize = 48;
const ARENA_CHUNK: usize = 64 * 1024;
@@ -104,9 +104,7 @@ fn alloc_thunk() -> *mut u8 {
pub fn info_of_stub(addr: usize) -> Option<&'static StubInfo> {
let map = BY_KEY.get()?;
let g = map.lock().ok()?;
let key = g.iter().find(|(_, &a)| a == addr).map(|(k, _)| k.clone())?;
drop(g);
ALL.lock().ok()?.iter().copied().find(|s| format!("{}!{}", s.dll.to_ascii_lowercase(), s.name) == key)
g.values().find(|&&(a, _)| a == addr).map(|&(_, info)| info)
}
/// Create (or reuse) a stub for `dll!name`. Returns the callable address.
@@ -118,11 +116,9 @@ pub fn make_stub(dll: &str, name: &str, ret: u64) -> usize {
pub fn make_stub_info(dll: &str, name: &str, ret: u64) -> (usize, &'static StubInfo) {
let key = format!("{}!{}", dll.to_ascii_lowercase(), name);
let map = BY_KEY.get_or_init(|| Mutex::new(HashMap::new()));
if let Some(&addr) = map.lock().unwrap().get(&key) {
let info = ALL.lock().unwrap().iter().copied().find(|s| s.dll.eq_ignore_ascii_case(dll) && s.name == name);
if let Some(i) = info {
return (addr, i);
}
let mut g = map.lock().unwrap();
if let Some(&entry) = g.get(&key) {
return entry;
}
let info: &'static StubInfo = Box::leak(Box::new(StubInfo {
dll: dll.to_string(),
@@ -144,6 +140,7 @@ pub fn make_stub_info(dll: &str, name: &str, ret: u64) -> (usize, &'static StubI
code.extend_from_slice(&[0x48, 0x83, 0xC4, 0x28]); // add rsp, 0x28
code.push(0xC3); // ret
debug_assert!(code.len() <= THUNK_SIZE);
// SAFETY: `p` is freshly allocated with at least `THUNK_SIZE >= code.len()` bytes of RWX memory.
unsafe {
std::ptr::copy_nonoverlapping(code.as_ptr(), p, code.len());
windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache(
@@ -153,8 +150,9 @@ pub fn make_stub_info(dll: &str, name: &str, ret: u64) -> (usize, &'static StubI
);
}
ALL.lock().unwrap().push(info);
map.lock().unwrap().insert(key, p as usize);
(p as usize, info)
let entry = (p as usize, info);
g.insert(key, entry);
entry
}
pub fn all_stubs() -> Vec<&'static StubInfo> {
@@ -219,15 +217,36 @@ impl StubDb {
}
pub fn return_for(&self, dll: &str, name: &str) -> u64 {
self.return_for_with_fallback(dll, None, name)
}
/// Look up the stub return value for `dll!name`, falling back to `fallback_dll` (e.g. a
/// canonical HLE module name when `dll` is a routed alias) if `dll` has no explicit override
/// or module default.
pub fn return_for_with_fallback(&self, dll: &str, fallback_dll: Option<&str>, name: &str) -> u64 {
let dll = dll.to_ascii_lowercase();
let fallback = fallback_dll.map(str::to_ascii_lowercase);
let n = name.to_ascii_lowercase();
if let Some(&r) = self.functions.get(&format!("{dll}!{n}")) {
return r;
}
if let Some(fb) = fallback.as_deref().filter(|&fb| fb != dll) {
if let Some(&r) = self.functions.get(&format!("{fb}!{n}")) {
return r;
}
}
if let Some(&r) = self.functions.get(&format!("*!{n}")) {
return r;
}
self.module_defaults.get(&dll).copied().unwrap_or(0)
if let Some(&r) = self.module_defaults.get(&dll) {
return r;
}
if let Some(fb) = fallback.as_deref() {
if let Some(&r) = self.module_defaults.get(fb) {
return r;
}
}
0
}
pub fn ordinal_name(&self, dll: &str, ordinal: u16) -> Option<&str> {
@@ -264,10 +283,60 @@ mod tests {
fn builtin_db_parses_with_overrides() {
let mut ov = std::collections::BTreeMap::new();
ov.insert("kernelx.dll!Foo".to_string(), "7".to_string());
ov.insert("xgameplatform.dll!PerAlias".to_string(), "0".to_string());
ov.insert("xgameruntime.dll!CanonicalFn".to_string(), "1".to_string());
let db = StubDb::parse(BUILTIN_DB, &ov);
assert_eq!(db.return_for("kernelx.dll", "Foo"), 7);
assert_eq!(db.return_for("xgameruntime.dll", "XSomethingUnknown"), 0x8000_4001);
assert_eq!(db.return_for("kernelx.dll", "SomethingUnknown"), 0);
assert_eq!(db.ordinal_name("d3d12_x.dll", 7), Some("D3D12CreateDevice"));
// Routed HLE aliases inherit canonical module defaults while preserving per-alias overrides.
assert_eq!(db.return_for_with_fallback("xgameplatform.dll", Some("xgameruntime.dll"), "XUnknown"), 0x8000_4001);
assert_eq!(db.return_for_with_fallback("d3d12x.dll", Some("d3d12_xs.dll"), "D3D12Unknown"), 0x8000_4001);
assert_eq!(db.return_for_with_fallback("xgameplatform.dll", Some("xgameruntime.dll"), "PerAlias"), 0);
assert_eq!(db.return_for_with_fallback("xgameplatform.dll", Some("xgameruntime.dll"), "CanonicalFn"), 1);
assert_eq!(db.return_for_with_fallback("xgameplatform.dll", Some("xgameruntime.dll"), "XGameUiShowErrorDialogAsync"), 0x8000_4004);
assert_eq!(db.return_for_with_fallback("advapi32legacy.dll", Some("kernelx.dll"), "SomethingUnknown"), 0);
}
#[test]
fn make_stub_info_is_race_free_under_concurrency() {
use std::sync::{Arc, Barrier};
const THREADS: usize = 8;
const ITERS: usize = 50;
for iter in 0..ITERS {
let func = format!("ConcurrentRaceFn_{iter}");
let barrier = Arc::new(Barrier::new(THREADS));
let handles: Vec<_> = (0..THREADS)
.map(|t| {
let barrier = Arc::clone(&barrier);
let func = func.clone();
let dll = if t % 2 == 0 { "RaceStub.dll" } else { "racestub.dll" };
std::thread::spawn(move || {
barrier.wait();
let (addr, info) = make_stub_info(dll, &func, 0x8000_4001);
(addr, info as *const StubInfo as usize)
})
})
.collect();
let results: Vec<(usize, usize)> = handles.into_iter().map(|h| h.join().unwrap()).collect();
let first = results[0];
assert_ne!(first.0, 0);
for &r in &results[1..] {
assert_eq!(r, first, "iter {iter}: concurrent callers received different stubs");
}
assert_eq!(
info_of_stub(first.0).map(|i| i as *const StubInfo as usize),
Some(first.1)
);
let count = all_stubs()
.into_iter()
.filter(|s| s.dll.eq_ignore_ascii_case("racestub.dll") && s.name == func)
.count();
assert_eq!(count, 1, "iter {iter}: duplicate StubInfo pushed to ALL");
}
}
}
+229 -10
View File
@@ -154,20 +154,122 @@ pub unsafe fn write_wide_out(src: &str, buf: *mut u16, size: u32) -> u32 {
}
}
pub unsafe fn write_ansi_out(src: &str, buf: *mut u8, size: u32) -> u32 {
/// Encode `src` into `buf` (capacity `size` bytes, including NUL) using Windows `codepage`
/// (`GetModuleFileNameA` semantics): returns bytes written (without terminator), or `size` with
/// `ERROR_INSUFFICIENT_BUFFER` when truncated. Truncation always stops at a complete character
/// boundary so multi-byte sequences (DBCS / UTF-8) and UTF-16 surrogate pairs are never split.
unsafe fn write_codepage_out(src: &str, codepage: u32, buf: *mut u8, size: u32) -> u32 {
use windows_sys::Win32::Foundation::{SetLastError, ERROR_INSUFFICIENT_BUFFER};
use windows_sys::Win32::Globalization::WideCharToMultiByte;
if buf.is_null() || size == 0 {
return 0;
}
let b = src.as_bytes();
let n = b.len().min(size as usize - 1);
std::ptr::copy_nonoverlapping(b.as_ptr(), buf, n);
*buf.add(n) = 0;
if b.len() >= size as usize {
windows_sys::Win32::Foundation::SetLastError(122);
size
} else {
n as u32
let w: Vec<u16> = src.encode_utf16().collect();
if w.is_empty() {
// SAFETY: `buf` is non-null and `size >= 1`.
*buf = 0;
return 0;
}
let Ok(w_len) = i32::try_from(w.len()) else {
// SAFETY: `buf` is non-null and `size >= 1`.
*buf = 0;
return 0;
};
let needed = WideCharToMultiByte(
codepage,
0,
w.as_ptr(),
w_len,
std::ptr::null_mut(),
0,
std::ptr::null(),
std::ptr::null_mut(),
);
if needed <= 0 {
// SAFETY: `buf` is non-null and `size >= 1`.
*buf = 0;
return 0;
}
let cap = (size as usize - 1).min(i32::MAX as usize);
if (needed as usize) <= cap {
let written = WideCharToMultiByte(
codepage,
0,
w.as_ptr(),
w_len,
buf,
needed,
std::ptr::null(),
std::ptr::null_mut(),
);
if written <= 0 {
// SAFETY: `buf` is non-null and `size >= 1`.
*buf = 0;
return 0;
}
// SAFETY: `written <= needed <= cap <= size - 1`, so `buf.add(written)` is in bounds.
*buf.add(written as usize) = 0;
return written as u32;
}
let written = if cap == 0 {
0
} else {
let mut bounds = Vec::with_capacity(src.len() + 1);
bounds.push(0usize);
let mut u16_pos = 0usize;
for ch in src.chars() {
u16_pos += ch.len_utf16();
bounds.push(u16_pos);
}
let mut lo = 0usize;
let mut hi = bounds.len() - 1;
while lo + 1 < hi {
let mid = lo + (hi - lo) / 2;
let n = WideCharToMultiByte(
codepage,
0,
w.as_ptr(),
bounds[mid] as i32,
std::ptr::null_mut(),
0,
std::ptr::null(),
std::ptr::null_mut(),
);
if n >= 0 && (n as usize) <= cap {
lo = mid;
} else {
hi = mid;
}
}
let fit_u16 = bounds[lo];
if fit_u16 == 0 {
0
} else {
let n = WideCharToMultiByte(
codepage,
0,
w.as_ptr(),
fit_u16 as i32,
buf,
cap as i32,
std::ptr::null(),
std::ptr::null_mut(),
);
n.max(0) as usize
}
};
// SAFETY: `written <= cap <= size - 1`, so `buf.add(written)` is in bounds.
*buf.add(written) = 0;
SetLastError(ERROR_INSUFFICIENT_BUFFER);
size
}
/// Win32-style "copy ANSI string" (GetModuleFileNameA semantics): converts `src` to `CP_ACP`,
/// NUL-terminates, and returns bytes written (without terminator) or `size` when truncated.
pub unsafe fn write_ansi_out(src: &str, buf: *mut u8, size: u32) -> u32 {
write_codepage_out(src, windows_sys::Win32::Globalization::CP_ACP, buf, size)
}
/// Wrapper to keep raw pointers in statics.
@@ -216,4 +318,121 @@ mod tests {
assert_eq!(used, 11);
}
}
#[test]
fn ansi_out_encodes_codepage_and_truncates_on_char_boundaries() {
use windows_sys::Win32::Foundation::{GetLastError, SetLastError, ERROR_INSUFFICIENT_BUFFER};
use windows_sys::Win32::Globalization::{GetACP, MultiByteToWideChar, CP_UTF8};
unsafe fn decode_cp(bytes: &[u8], cp: u32) -> String {
let nul = bytes.iter().position(|&b| b == 0).unwrap_or(bytes.len());
if nul == 0 {
return String::new();
}
let n = MultiByteToWideChar(cp, 0, bytes.as_ptr(), nul as i32, std::ptr::null_mut(), 0);
assert!(n > 0);
let mut w = vec![0u16; n as usize];
MultiByteToWideChar(cp, 0, bytes.as_ptr(), nul as i32, w.as_mut_ptr(), n);
String::from_utf16_lossy(&w)
}
unsafe {
// Null / zero-size / empty edge cases.
let mut tiny = [0xAAu8; 4];
assert_eq!(write_ansi_out("abc", std::ptr::null_mut(), 4), 0);
assert_eq!(write_ansi_out("abc", tiny.as_mut_ptr(), 0), 0);
assert_eq!(write_ansi_out("", tiny.as_mut_ptr(), 1), 0);
assert_eq!(tiny[0], 0);
// CP1252: non-ASCII French path encodes as single bytes (0xC9 / 0xE9), not UTF-8.
let fr = "C:\\Jeux\\Été\\game.exe";
let mut buf = [0xCCu8; 64];
let n = write_codepage_out(fr, 1252, buf.as_mut_ptr(), buf.len() as u32);
assert_eq!(n, 20);
assert_eq!(buf[n as usize], 0);
assert_eq!(decode_cp(&buf, 1252), fr);
// CP1250: Central European diacritics ("Č" = 0xC8, "Ž" = 0x8E) round-trip cleanly.
let cz = "C:\\Hry\\Český_Život\\game.exe";
buf.fill(0xCC);
let n = write_codepage_out(cz, 1250, buf.as_mut_ptr(), buf.len() as u32);
assert_eq!(n, 27);
assert_eq!(buf[n as usize], 0);
assert_eq!(decode_cp(&buf, 1250), cz);
// CJK character outside CP1252 maps cleanly to the codepage default char ('?').
let cjk = "C:\\Games\\漢\\game.exe";
buf.fill(0xCC);
let n = write_codepage_out(cjk, 1252, buf.as_mut_ptr(), buf.len() as u32);
assert_eq!(n, 19);
assert_eq!(buf[n as usize], 0);
assert_eq!(decode_cp(&buf, 1252), "C:\\Games\\?\\game.exe");
// Active CP_ACP round-trip through write_ansi_out -> from_ansi_ptr.
let acp = GetACP();
let sample = match acp {
1250 => cz,
1252 | 65001 => fr,
_ => "C:\\Games\\Title\\game.exe",
};
buf.fill(0xCC);
let n = write_ansi_out(sample, buf.as_mut_ptr(), buf.len() as u32);
assert!(n > 0 && (n as usize) < buf.len());
assert_eq!(buf[n as usize], 0);
assert_eq!(from_ansi_ptr(buf.as_ptr()).as_deref(), Some(sample));
// Active CP_ACP with CJK path: round-trips if ACP supports it, else substitutes '?' cleanly.
buf.fill(0xCC);
let n = write_ansi_out(cjk, buf.as_mut_ptr(), buf.len() as u32);
assert!(n > 0 && (n as usize) < buf.len());
assert_eq!(buf[n as usize], 0);
let decoded_cjk = from_ansi_ptr(buf.as_ptr()).unwrap();
assert!(
decoded_cjk == cjk || decoded_cjk == "C:\\Games\\?\\game.exe",
"unexpected CP_ACP ({acp}) round-trip for CJK path: {decoded_cjk:?}"
);
// DBCS truncation (CP932, 2 bytes per Hiragana char): never splits a lead/trail byte.
let jp = "あいう";
buf.fill(0xCC);
SetLastError(0);
assert_eq!(write_codepage_out(jp, 932, buf.as_mut_ptr(), 2), 2);
assert_eq!(GetLastError(), ERROR_INSUFFICIENT_BUFFER);
assert_eq!(buf[0], 0);
buf.fill(0xCC);
SetLastError(0);
assert_eq!(write_codepage_out(jp, 932, buf.as_mut_ptr(), 4), 4);
assert_eq!(GetLastError(), ERROR_INSUFFICIENT_BUFFER);
assert_eq!(decode_cp(&buf, 932), "あ");
assert_eq!(buf[2], 0);
buf.fill(0xCC);
SetLastError(0);
assert_eq!(write_codepage_out(jp, 932, buf.as_mut_ptr(), 5), 5);
assert_eq!(GetLastError(), ERROR_INSUFFICIENT_BUFFER);
assert_eq!(decode_cp(&buf, 932), "あい");
assert_eq!(buf[4], 0);
buf.fill(0xCC);
assert_eq!(write_codepage_out(jp, 932, buf.as_mut_ptr(), 7), 6);
assert_eq!(decode_cp(&buf, 932), jp);
assert_eq!(buf[6], 0);
// UTF-8 truncation with a 4-byte emoji (UTF-16 surrogate pair): never splits codepoint.
let emoji = "a😀b";
buf.fill(0xCC);
SetLastError(0);
assert_eq!(write_codepage_out(emoji, CP_UTF8, buf.as_mut_ptr(), 5), 5);
assert_eq!(GetLastError(), ERROR_INSUFFICIENT_BUFFER);
assert_eq!(&buf[..2], b"a\0");
buf.fill(0xCC);
SetLastError(0);
assert_eq!(write_codepage_out(emoji, CP_UTF8, buf.as_mut_ptr(), 6), 6);
assert_eq!(GetLastError(), ERROR_INSUFFICIENT_BUFFER);
assert_eq!(decode_cp(&buf, CP_UTF8), "a😀");
assert_eq!(buf[5], 0);
}
}
}