diff --git a/crates/victory-hle/src/modules/kernel.rs b/crates/victory-hle/src/modules/kernel.rs index 94745f7..19210b0 100644 --- a/crates/victory-hle/src/modules/kernel.rs +++ b/crates/victory-hle/src/modules/kernel.rs @@ -180,6 +180,12 @@ pub extern "system" fn FreeLibrary(module: *mut c_void) -> i32 { host::free_library(module) } +/// Title images hear of thread starts and ends from us, not from the +/// Windows loader (`victory_loader::disable_thread_calls`). +pub extern "system" fn DisableThreadLibraryCalls(module: *mut c_void) -> i32 { + host::disable_thread_library_calls(module) +} + /// Title debug output goes to our log (no debugger needs to be attached). pub extern "system" fn OutputDebugStringA(text: *const u8) { if !text.is_null() { @@ -293,6 +299,7 @@ pub(crate) fn module() -> HleModule { hle_export!(LoadLibraryW), hle_export!(GetProcAddress), hle_export!(FreeLibrary), + hle_export!(DisableThreadLibraryCalls), hle_export!(OutputDebugStringA), hle_export!(OutputDebugStringW), hle_export!(exit), @@ -311,8 +318,8 @@ mod host { use windows_sys::Win32::Foundation::{FreeLibrary, SetLastError}; use windows_sys::Win32::System::Diagnostics::Debug::RtlCaptureStackBackTrace; use windows_sys::Win32::System::LibraryLoader::{ - GetModuleFileNameA, GetModuleFileNameW, GetModuleHandleA, GetModuleHandleW, GetProcAddress, - LoadLibraryExA, LoadLibraryExW, + DisableThreadLibraryCalls, GetModuleFileNameA, GetModuleFileNameW, GetModuleHandleA, + GetModuleHandleW, GetProcAddress, LoadLibraryExA, LoadLibraryExW, }; use windows_sys::Win32::System::Threading::TerminateProcess; @@ -375,6 +382,14 @@ mod host { unsafe { FreeLibrary(module) } } + pub(super) fn disable_thread_library_calls(module: *mut c_void) -> i32 { + match victory_loader::disable_thread_calls(module as usize) { + Some(done) => i32::from(done), + // SAFETY: see above. + None => unsafe { DisableThreadLibraryCalls(module) }, + } + } + pub(super) fn exit(code: i32) -> ! { // SAFETY: see above. unsafe { crt_exit(code) } @@ -448,6 +463,10 @@ mod host { 0 } + pub(super) fn disable_thread_library_calls(_: *mut c_void) -> i32 { + 0 + } + pub(super) fn exit(code: i32) -> ! { std::process::exit(code) } diff --git a/crates/victory-loader/src/lib.rs b/crates/victory-loader/src/lib.rs index 8a64c90..11f9793 100644 --- a/crates/victory-loader/src/lib.rs +++ b/crates/victory-loader/src/lib.rs @@ -18,13 +18,16 @@ //! anything unresolved to a generated stub that reports exactly what //! was called; //! 5. initialise the title's DLLs, then run TLS callbacks and the entry -//! point on a thread with the stack size the image asks for. +//! point on a thread with the stack size the image asks for; from then +//! on, pass every thread start and end on to the attached images. #[cfg(windows)] mod crash; pub mod prepare; pub mod resolve; #[cfg(windows)] +mod threads; +#[cfg(windows)] mod thunks; #[cfg(windows)] mod tls; @@ -36,6 +39,8 @@ pub use crash::{locate, report_crashes}; pub use prepare::{PrepareError, PreparedImage, prepare}; pub use resolve::{ImportResolver, Provenance, Resolution}; #[cfg(windows)] +pub use threads::disable_thread_calls; +#[cfg(windows)] pub use thunks::{UnimplementedPolicy, unimplemented_call_count}; #[cfg(windows)] pub use windows::{ diff --git a/crates/victory-loader/src/threads.rs b/crates/victory-loader/src/threads.rs new file mode 100644 index 0000000..664a647 --- /dev/null +++ b/crates/victory-loader/src/threads.rs @@ -0,0 +1,93 @@ +//! Thread notices for title images. The prepared copies have no entry point +//! and no TLS callbacks, so the Windows loader tells them nothing when a +//! thread starts or ends. Our own TLS callback, which Windows calls on every +//! thread of the process whoever created it (title, host CRT or our +//! runtime), passes each notice on to every attached image: its TLS +//! callbacks, then a DLL's `DllMain`. + +use std::ffi::c_void; +use std::sync::{Arc, Mutex}; + +use crate::LoadedImage; + +const DLL_THREAD_ATTACH: u32 = 2; +const DLL_THREAD_DETACH: u32 = 3; + +struct Mapped { + image: Arc, + /// Its `DLL_PROCESS_ATTACH` is done; only then does it get thread notices. + attached: bool, + /// `DisableThreadLibraryCalls`: no more `DllMain` thread notices. + quiet: bool, +} + +/// Every title image we mapped, in load order. +static IMAGES: Mutex> = Mutex::new(Vec::new()); + +fn images() -> std::sync::MutexGuard<'static, Vec> { + IMAGES.lock().unwrap_or_else(|e| e.into_inner()) +} + +pub(crate) fn mapped(image: &LoadedImage) { + // SAFETY: reads our own static, so the linker keeps it (and its section). + unsafe { std::ptr::from_ref(&ON_THREAD).read_volatile() }; + let image = Arc::new(image.clone()); + let mut images = images(); + images.retain(|m| m.image.base() != image.base()); + images.push(Mapped { + image, + attached: false, + quiet: false, + }); +} + +pub(crate) fn attached(base: usize) { + if let Some(m) = images().iter_mut().find(|m| m.image.base() == base) { + m.attached = true; + } +} + +pub(crate) fn unmapped(base: usize) { + images().retain(|m| m.image.base() != base); +} + +/// `DisableThreadLibraryCalls` for a title image; `None` if `base` is not +/// one. Fails, as on Windows, for an image with static TLS. +pub fn disable_thread_calls(base: usize) -> Option { + let mut images = images(); + let m = images.iter_mut().find(|m| m.image.base() == base)?; + if m.image.info().tls.is_some() { + return Some(false); + } + m.quiet = true; + Some(true) +} + +/// Windows calls every pointer between the CRT's markers `.CRT$XLA` and +/// `.CRT$XLZ`; `XLAV` sorts ahead of the usual `XLB`, so ours runs before +/// any other callback linked into the exe. +#[used] +#[unsafe(link_section = ".CRT$XLAV")] +static ON_THREAD: unsafe extern "system" fn(*mut c_void, u32, *mut c_void) = on_thread; + +unsafe extern "system" fn on_thread(_: *mut c_void, reason: u32, _: *mut c_void) { + if reason != DLL_THREAD_ATTACH && reason != DLL_THREAD_DETACH { + return; + } + // A snapshot: title code may map and attach another DLL from here. + let notify: Vec<_> = images() + .iter() + .filter(|m| m.attached) + .map(|m| (m.image.clone(), !m.quiet)) + .collect(); + // Starts in load order, ends in reverse, as the Windows loader does. + let notify_one = |(image, dll_main): &(Arc, bool)| { + // SAFETY: attached images have their imports bound. + unsafe { image.notify(reason, *dll_main) }; + }; + if reason == DLL_THREAD_ATTACH { + notify.iter().for_each(notify_one); + } else { + notify.iter().rev().for_each(notify_one); + } +} diff --git a/crates/victory-loader/src/windows.rs b/crates/victory-loader/src/windows.rs index 64c4b0c..890d3a8 100644 --- a/crates/victory-loader/src/windows.rs +++ b/crates/victory-loader/src/windows.rs @@ -87,6 +87,7 @@ pub fn load(prepared: &PreparedImage, dir: &Path) -> Result { path = %loaded.path.display(), "image mapped" ); + crate::threads::mapped(&loaded); Ok(loaded) } @@ -318,26 +319,39 @@ impl LoadedImage { } /// Initialises a DLL as the Windows loader would: its TLS callbacks, - /// then `DllMain(DLL_PROCESS_ATTACH)`. + /// then `DllMain(DLL_PROCESS_ATTACH)`. From then on it hears of every + /// thread start and end (see `threads`). /// /// # Safety /// Runs title code. Imports must be bound first, and the DLLs this one /// depends on attached. pub unsafe fn attach(&self) -> Result<()> { // SAFETY: forwarded from the caller. - unsafe { self.run_tls_callbacks(DLL_PROCESS_ATTACH) }; - if self.info.entry_rva == 0 { - return Ok(()); + if unsafe { self.notify(DLL_PROCESS_ATTACH, true) } == Some(0) { + bail!("DllMain returned FALSE"); + } + crate::threads::attached(self.base()); + Ok(()) + } + + /// Runs the image's TLS callbacks with `reason`, then, if `dll_main` and + /// the image is a DLL with an entry point, its `DllMain`, whose result + /// is returned. + /// + /// # Safety + /// Runs title code. Imports must be bound first. + pub(crate) unsafe fn notify(&self, reason: u32, dll_main: bool) -> Option { + // SAFETY: forwarded from the caller. + unsafe { self.run_tls_callbacks(reason) }; + if !dll_main || !self.info.is_dll() || self.info.entry_rva == 0 { + return None; } type DllMain = unsafe extern "system" fn(*mut c_void, u32, *mut c_void) -> i32; // SAFETY: the entry RVA came from the original image header. let main: DllMain = unsafe { std::mem::transmute(self.base() + self.info.entry_rva as usize) }; // SAFETY: forwarded from the caller. - if unsafe { main(self.module, DLL_PROCESS_ATTACH, std::ptr::null_mut()) } == 0 { - bail!("DllMain returned FALSE"); - } - Ok(()) + Some(unsafe { main(self.module, reason, std::ptr::null_mut()) }) } /// Starts the title: on a new thread with the stack size from the image @@ -367,6 +381,7 @@ impl LoadedImage { } // SAFETY: forwarded from the caller of `spawn_main`. unsafe { self.run_tls_callbacks(DLL_PROCESS_ATTACH) }; + crate::threads::attached(self.base()); type Entry = unsafe extern "system" fn(*mut c_void) -> u32; // SAFETY: the entry RVA came from the original image header. let entry: Entry = @@ -383,6 +398,7 @@ impl LoadedImage { /// No title code may be running or run later, and no pointer into the /// image may be used afterwards. pub unsafe fn unload(self) { + crate::threads::unmapped(self.base()); // SAFETY: guaranteed by the caller. unsafe { FreeLibrary(self.module) }; } diff --git a/crates/victory-loader/tests/load_probe.rs b/crates/victory-loader/tests/load_probe.rs index 94081e7..f235604 100644 --- a/crates/victory-loader/tests/load_probe.rs +++ b/crates/victory-loader/tests/load_probe.rs @@ -178,6 +178,35 @@ fn loads_binds_and_calls_probe() { assert_eq!(f(), 0); assert_eq!(unimplemented_call_count(), before + 1); + // Once attached, every thread start reaches its TLS callback and + // DllMain (other tests may start threads too, hence at least one). + assert!( + image + .info() + .tls + .as_ref() + .is_some_and(|t| !t.callback_rvas.is_empty()) + ); + image.attach().unwrap(); + let f: extern "system" fn() -> u64 = std::mem::transmute(call("probe_thread_starts")); + let before = f(); + std::thread::spawn(|| {}).join().unwrap(); + let after = f(); + assert!( + after >> 32 > before >> 32, + "TLS callback: {before:#x} → {after:#x}" + ); + assert!( + after as u32 > before as u32, + "DllMain: {before:#x} → {after:#x}" + ); + // It has static TLS, so Windows would refuse too. + assert_eq!( + victory_loader::disable_thread_calls(image.base()), + Some(false) + ); + assert_eq!(victory_loader::disable_thread_calls(1), None); + image.unload(); } } diff --git a/tests/fixtures/hle-probe/src/lib.rs b/tests/fixtures/hle-probe/src/lib.rs index 264dd6a..ec9d791 100644 --- a/tests/fixtures/hle-probe/src/lib.rs +++ b/tests/fixtures/hle-probe/src/lib.rs @@ -2,6 +2,11 @@ //! exist on a PC, which is exactly the situation victory-loader handles. //! Loaded normally, this DLL would fail with "module not found". +use std::ffi::c_void; +use std::sync::atomic::{AtomicU32, Ordering}; + +const DLL_THREAD_ATTACH: u32 = 2; + #[link(name = "xgameruntime", kind = "raw-dylib")] unsafe extern "system" { fn XGameRuntimeInitialize() -> i32; @@ -70,3 +75,35 @@ pub extern "system" fn probe_delayed() -> u32 { pub extern "system" fn probe_missing() -> u64 { unsafe { VIctoryProbeNotImplemented(42) } } + +static TLS_THREAD_STARTS: AtomicU32 = AtomicU32::new(0); +static MAIN_THREAD_STARTS: AtomicU32 = AtomicU32::new(0); + +/// A TLS callback, as titles have: counts thread starts. +unsafe extern "system" fn on_thread(_: *mut c_void, reason: u32, _: *mut c_void) { + if reason == DLL_THREAD_ATTACH { + TLS_THREAD_STARTS.fetch_add(1, Ordering::Relaxed); + } +} + +#[used] +#[unsafe(link_section = ".CRT$XLB")] +static ON_THREAD: unsafe extern "system" fn(*mut c_void, u32, *mut c_void) = on_thread; + +/// Called by the CRT's DLL entry point: counts thread starts too. +#[unsafe(no_mangle)] +pub extern "system" fn DllMain(_: *mut c_void, reason: u32, _: *mut c_void) -> i32 { + if reason == DLL_THREAD_ATTACH { + MAIN_THREAD_STARTS.fetch_add(1, Ordering::Relaxed); + } + 1 +} + +/// Thread starts seen by the TLS callback (high half) and `DllMain` (low). +#[unsafe(no_mangle)] +pub extern "system" fn probe_thread_starts() -> u64 { + // SAFETY: reading our own static keeps the linker from dropping it. + unsafe { std::ptr::from_ref(&ON_THREAD).read_volatile() }; + u64::from(TLS_THREAD_STARTS.load(Ordering::Relaxed)) << 32 + | u64::from(MAIN_THREAD_STARTS.load(Ordering::Relaxed)) +}