diff --git a/crates/victory-hle/src/host.rs b/crates/victory-hle/src/host.rs index 8a2a875..7300687 100644 --- a/crates/victory-hle/src/host.rs +++ b/crates/victory-hle/src/host.rs @@ -122,11 +122,15 @@ mod imp { fn module(dll: &str) -> Option { let key = dll.to_ascii_lowercase(); - let mut cache = MODULES.lock().unwrap_or_else(|e| e.into_inner()); - if let Some(&m) = cache.get(&key) { - return Some(m); + let cache = || MODULES.lock().unwrap_or_else(|e| e.into_inner()); + let cached = cache().get(&key).copied(); + if cached.is_some() { + return cached; } let name = CString::new(key.as_str()).ok()?; + // Not under the cache's lock: loading takes the OS loader lock, and + // title code that runs under that one (a DLL's thread attach, a TLS + // callback) may look a function up here. // System32 only: never pick up a same-named DLL from the current folder or PATH. // SAFETY: NUL-terminated DLL name; only allow-listed system DLLs get here. let handle = unsafe { @@ -136,7 +140,95 @@ mod imp { LOAD_LIBRARY_SEARCH_SYSTEM32, ) } as usize; - (handle != 0).then(|| *cache.entry(key).or_insert(handle)) + // A thread that loaded it meanwhile got the same module, which stays loaded. + (handle != 0).then(|| *cache().entry(key).or_insert(handle)) + } + + #[cfg(test)] + mod tests { + use std::ffi::c_void; + use std::ptr::{null, null_mut}; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::time::{Duration, Instant}; + + use windows_sys::Win32::System::Threading::{ + CreateThread, INFINITE, Sleep, WaitForSingleObject, + }; + + const CHILD: &str = "VICTORY_HOST_LOCK_CHILD"; + static ARMED: AtomicBool = AtomicBool::new(false); + static IN_ATTACH: AtomicBool = AtomicBool::new(false); + static STARTED: AtomicBool = AtomicBool::new(false); + + /// Runs as title TLS callbacks do: under the loader lock, as a new + /// thread starts. + #[used] + #[unsafe(link_section = ".CRT$XLY")] + static ON_THREAD: unsafe extern "system" fn(*mut c_void, u32, *mut c_void) = attach; + + unsafe extern "system" fn attach(_: *mut c_void, reason: u32, _: *mut c_void) { + const DLL_THREAD_ATTACH: u32 = 2; + if reason == DLL_THREAD_ATTACH && ARMED.swap(false, Ordering::SeqCst) { + IN_ATTACH.store(true, Ordering::SeqCst); + // SAFETY: a plain sleep, for the other thread to start a load. + unsafe { Sleep(500) }; + let found = super::super::function("kernel32.dll", "GetTickCount"); + assert!(found.is_some()); + } + } + + unsafe extern "system" fn idle(_: *mut c_void) -> u32 { + 0 + } + + /// One thread loads a DLL nothing has loaded yet, which needs the + /// loader lock, while another thread's attach holds that lock and + /// looks a function up. Run in a child process: a deadlock inside the + /// loader keeps a process from exiting, so the parent kills it. + #[test] + fn loading_a_host_dll_does_not_block_thread_attach() { + if std::env::var_os(CHILD).is_none() { + let name = "host::imp::tests::loading_a_host_dll_does_not_block_thread_attach"; + let mut child = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", name]) + .env(CHILD, "1") + .spawn() + .unwrap(); + let start = Instant::now(); + loop { + if let Some(status) = child.try_wait().unwrap() { + assert!(status.success()); + return; + } + if start.elapsed() > Duration::from_secs(30) { + child.kill().unwrap(); + panic!("deadlock: a host DLL loads under the module cache's lock"); + } + std::thread::sleep(Duration::from_millis(50)); + } + } + // The attach below only needs the cache, no load of its own. + assert!(super::super::function("kernel32.dll", "GetTickCount").is_some()); + let loader = std::thread::spawn(|| { + STARTED.store(true, Ordering::SeqCst); + while !IN_ATTACH.load(Ordering::SeqCst) { + std::hint::spin_loop(); + } + super::super::function("cabinet.dll", "FDICreate") + }); + // Its own attach is over: the next is the thread below. + while !STARTED.load(Ordering::SeqCst) { + std::hint::spin_loop(); + } + ARMED.store(true, Ordering::SeqCst); + let (security, start) = (std::ptr::null(), Some(idle as _)); + // SAFETY: a thread that returns at once. + let thread = unsafe { CreateThread(security, 0, start, null(), 0, null_mut()) }; + assert!(!thread.is_null()); + assert!(loader.join().unwrap().is_some()); + // SAFETY: our own thread's handle. + unsafe { WaitForSingleObject(thread, INFINITE) }; + } } }