diff --git a/apps/victory/src/run.rs b/apps/victory/src/run.rs index 54f14e5..10bac4b 100644 --- a/apps/victory/src/run.rs +++ b/apps/victory/src/run.rs @@ -33,10 +33,7 @@ pub fn run(exe: &Path, unimplemented: Unimplemented, strict: bool, execute: bool } else { HostPolicy::default() }); - // DLLs the host or our runtime provide are never taken from the title. - let wanted = |dll: &str| { - !resolver.host.allows(dll) && !victory_hle::registry().iter().any(|m| m.serves(dll)) - }; + let wanted = |dll: &str| title_dll(&resolver.host, dll); let title_dir = exe.parent().unwrap_or(Path::new(".")); // A missing manifest leaves id 0 and no storage quota. let manifest = @@ -86,6 +83,16 @@ pub fn run(exe: &Path, unimplemented: Unimplemented, strict: bool, execute: bool return Ok(()); } victory_loader::report_crashes(); + let late = LateDlls { + host: resolver.host.clone(), + title_dir: title_dir.to_owned(), + cache_dir: images, + policy, + mapped: std::sync::Mutex::new(dlls.clone()), + }; + victory_hle::runtime::set_title_dll_loader(Box::new(move |file| { + late.load(file, show).map_err(|e| format!("{e:#}")) + })); // SAFETY: imports are bound; from here on we run title code. let main = unsafe { Arc::new(image).spawn_main(dlls)? }; let code = main @@ -95,6 +102,66 @@ pub fn run(exe: &Path, unimplemented: Unimplemented, strict: bool, execute: bool Ok(()) } +/// DLLs the host or our runtime provide are never taken from the title. +#[cfg(windows)] +fn title_dll(host: &victory_hle::HostPolicy, dll: &str) -> bool { + !host.allows(dll) && !victory_hle::registry().iter().any(|m| m.serves(dll)) +} + +/// Title DLLs the title loads itself (`LoadLibrary`) that nothing imports, +/// e.g. Grand Theft Auto VI's upscaler behind its FidelityFX loader. +#[cfg(windows)] +struct LateDlls { + host: victory_hle::HostPolicy, + title_dir: std::path::PathBuf, + cache_dir: std::path::PathBuf, + policy: victory_loader::UnimplementedPolicy, + /// Every title DLL mapped so far, to bind new ones against. + mapped: std::sync::Mutex>, +} + +#[cfg(windows)] +impl LateDlls { + /// Maps `file` and the title DLLs it needs, binds them and runs their + /// `DllMain` on the calling thread, as the Windows loader would. + fn load( + &self, + file: &str, + show: impl Fn(&str, victory_loader::BindReport), + ) -> Result> { + use victory_hle::runtime::{image_named, set_image_path}; + // shortcut: not reentrant, so a DllMain that loads another new title + // DLL deadlocks; use a reentrant lock if a title does that. + let mut mapped = self.mapped.lock().unwrap_or_else(|e| e.into_inner()); + let wanted = |dll: &str| title_dll(&self.host, dll) && image_named(dll).is_none(); + let new = victory_loader::load_title_dll(file, &self.title_dir, &self.cache_dir, &wanted)?; + let hle = victory_hle::HleResolver::new(self.host.clone()); + let old = victory_loader::WithTitleDlls { + inner: &hle, + dlls: &mapped, + }; + let resolver = victory_loader::WithTitleDlls { + inner: &old, + dlls: &new, + }; + for (name, dll) in &new { + println!( + "title dll {name} at {:#x} (loaded by the title)", + dll.base() + ); + show(name, dll.bind_imports(&resolver, self.policy)?); + set_image_path(dll.base(), &self.title_dir.join(name)); + } + for (name, dll) in &new { + // SAFETY: bound above, dependencies attached first. + unsafe { dll.attach() }.with_context(|| format!("attaching {name}"))?; + } + let base = new.last().map(|(_, dll)| dll.base()); + mapped.extend(new); + Ok(base) + } +} + #[cfg(not(windows))] pub fn run(_: &Path, _: Unimplemented, _: bool, _: bool) -> Result<()> { anyhow::bail!("running titles requires Windows") diff --git a/crates/victory-hle/src/modules/kernel.rs b/crates/victory-hle/src/modules/kernel.rs index 9062464..94745f7 100644 --- a/crates/victory-hle/src/modules/kernel.rs +++ b/crates/victory-hle/src/modules/kernel.rs @@ -11,20 +11,38 @@ use std::ffi::{CStr, c_void}; use crate::{HleModule, HostPolicy, hle_export, registry, runtime}; -/// `GetModuleHandleW(NULL)` must return the title's image, not our exe. +/// `GetModuleHandleW(NULL)` must return the title's image, not our exe; +/// title images and our console modules are found by name. pub extern "system" fn GetModuleHandleW(name: *const u16) -> *mut c_void { if name.is_null() { return runtime::main_image().unwrap_or(0) as *mut c_void; } - host::get_module_handle_w(name) + find_module(&wide(name), false).unwrap_or_else(|| host::get_module_handle_w(name)) } -/// `GetModuleHandleA(NULL)` must return the title's image, not our exe. +/// See [`GetModuleHandleW`]. pub extern "system" fn GetModuleHandleA(name: *const u8) -> *mut c_void { if name.is_null() { return runtime::main_image().unwrap_or(0) as *mut c_void; } - host::get_module_handle_a(name) + find_module(&narrow(name), false).unwrap_or_else(|| host::get_module_handle_a(name)) +} + +/// A NUL-terminated string from the title. +fn narrow(text: *const u8) -> String { + // SAFETY: the title passes a NUL-terminated string. + unsafe { CStr::from_ptr(text.cast()) } + .to_string_lossy() + .into_owned() +} + +/// See [`narrow`]. +fn wide(text: *const u16) -> String { + // SAFETY: the title passes a NUL-terminated string. + unsafe { + let len = (0..).take_while(|&i| *text.add(i) != 0).count(); + String::from_utf16_lossy(std::slice::from_raw_parts(text, len)) + } } /// A title image's path is its original file, not our cache copy; @@ -81,18 +99,17 @@ fn copy_truncated(text: &[T], out: &mut [T]) -> u32 { const ERROR_INSUFFICIENT_BUFFER: u32 = 122; /// Console-only DLLs we implement load as a pseudo handle (titles load -/// `xgameruntime.dll` this way); anything else loads on the host. +/// `xgameruntime.dll` this way), the title's DLLs as the images we map +/// (on first use if nothing imports them); anything else loads on the host. pub extern "system" fn LoadLibraryExA( name: *const u8, file: *mut c_void, flags: u32, ) -> *mut c_void { - if !name.is_null() { - // SAFETY: the title passes a NUL-terminated file name. - let text = unsafe { CStr::from_ptr(name.cast()) }.to_string_lossy(); - if let Some(handle) = console_module(&text) { - return handle; - } + if !name.is_null() + && let Some(handle) = find_module(&narrow(name), runs_code(flags)) + { + return handle; } host::load_library_ex_a(name, file, flags) } @@ -103,19 +120,21 @@ pub extern "system" fn LoadLibraryExW( file: *mut c_void, flags: u32, ) -> *mut c_void { - if !name.is_null() { - // SAFETY: the title passes a NUL-terminated file name. - let text = unsafe { - let len = (0..).take_while(|&i| *name.add(i) != 0).count(); - String::from_utf16_lossy(std::slice::from_raw_parts(name, len)) - }; - if let Some(handle) = console_module(&text) { - return handle; - } + if !name.is_null() + && let Some(handle) = find_module(&wide(name), runs_code(flags)) + { + return handle; } host::load_library_ex_w(name, file, flags) } +/// False for loads as data or resources (`DONT_RESOLVE_DLL_REFERENCES`, +/// `LOAD_LIBRARY_AS_DATAFILE(_EXCLUSIVE)`, `AS_IMAGE_RESOURCE`): those run +/// no code, so a title DLL we have not mapped can go to the host. +fn runs_code(flags: u32) -> bool { + flags & (0x1 | 0x2 | 0x20 | 0x40) == 0 +} + pub extern "system" fn LoadLibraryA(name: *const u8) -> *mut c_void { LoadLibraryExA(name, std::ptr::null_mut(), 0) } @@ -150,8 +169,12 @@ pub extern "system" fn GetProcAddress(module: *mut c_void, name: *const u8) -> * } } +/// Our pseudo modules and the title's images stay loaded: `LoadLibrary` +/// took no reference on them, so the host's count must not drop. pub extern "system" fn FreeLibrary(module: *mut c_void) -> i32 { - if registry().iter().any(|m| handle(m) == module) { + if registry().iter().any(|m| handle(m) == module) + || runtime::image_path(module as usize).is_some() + { return 1; } host::free_library(module) @@ -160,21 +183,14 @@ pub extern "system" fn FreeLibrary(module: *mut c_void) -> i32 { /// 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() { - // SAFETY: the title passes a NUL-terminated string. - let text = unsafe { CStr::from_ptr(text.cast()) }.to_string_lossy(); - tracing::info!(target: "title", "{}", text.trim_end()); + tracing::info!(target: "title", "{}", narrow(text).trim_end()); } } /// See [`OutputDebugStringA`]. pub extern "system" fn OutputDebugStringW(text: *const u16) { if !text.is_null() { - // SAFETY: the title passes a NUL-terminated string. - let text = unsafe { - let len = (0..).take_while(|&i| *text.add(i) != 0).count(); - String::from_utf16_lossy(std::slice::from_raw_parts(text, len)) - }; - tracing::info!(target: "title", "{}", text.trim_end()); + tracing::info!(target: "title", "{}", wide(text).trim_end()); } } @@ -217,17 +233,44 @@ fn handle(m: &HleModule) -> *mut c_void { m as *const HleModule as *mut c_void } -fn console_module(path: &str) -> Option<*mut c_void> { +/// The title's images and our console modules by name; `None` leaves the +/// name to the host. With `load`, a title DLL not mapped yet is mapped now. +fn find_module(path: &str, load: bool) -> Option<*mut c_void> { let file = path.rsplit(['\\', '/']).next().unwrap_or(path); + // As the Windows loader does, a name without extension means a DLL. + let file = if file.contains('.') { + file.to_owned() + } else { + format!("{file}.dll") + }; + if let Some(base) = runtime::image_named(&file) { + return Some(base as *mut c_void); + } // DLLs the host has too are real host modules, whatever `--strict` says. - if HostPolicy::default().allows(file) { + if !HostPolicy::default().allows(&file) + && let Some(m) = registry().iter().find(|m| m.serves(&file)) + { + if load { + tracing::info!(dll = file, "loaded as a pseudo module"); + } + return Some(handle(m)); + } + if !load { return None; } - let m = registry().iter().find(|m| m.serves(file))?; - tracing::info!(dll = file, "loaded as a pseudo module"); - Some(handle(m)) + match runtime::load_title_dll(&file) { + Ok(base) => base.map(|b| b as *mut c_void), + // Not the host: it would load the unpatched DLL from the title's folder. + Err(error) => { + tracing::error!(dll = file, %error, "mapping a title DLL failed"); + host::set_last_error(ERROR_MOD_NOT_FOUND); + Some(std::ptr::null_mut()) + } + } } +const ERROR_MOD_NOT_FOUND: u32 = 126; + pub(crate) fn module() -> HleModule { HleModule { name: "kernel", @@ -444,4 +487,39 @@ mod tests { assert_eq!(GetModuleFileNameA(module, small.as_mut_ptr(), 4), 4); assert_eq!(&small, &[b'C', b':', b'\\', 0]); } + + fn w(text: &str) -> Vec { + text.encode_utf16().chain(Some(0)).collect() + } + + #[test] + fn title_dlls_and_pseudo_modules_are_found_by_name() { + let base = 0x7100_0000_0000usize; + runtime::set_image_path(base, std::path::Path::new(r"C:\title\Mapped.dll")); + runtime::set_title_dll_loader(Box::new(|file| match file { + "late.dll" => Ok(Some(0x7200_0000_0000)), + "broken.dll" => Err("bad image".into()), + _ => Ok(None), + })); + let mapped = base as *mut c_void; + assert_eq!(GetModuleHandleW(w("MAPPED").as_ptr()), mapped); + assert_eq!(GetModuleHandleA(c"sub\\mapped.dll".as_ptr().cast()), mapped); + assert_eq!(LoadLibraryW(w("mapped.dll").as_ptr()), mapped); + assert_eq!(FreeLibrary(mapped), 1, "title images stay loaded"); + + // Not mapped yet: `LoadLibrary` maps it, `GetModuleHandle` does not. + assert!(GetModuleHandleW(w("late.dll").as_ptr()).is_null()); + assert_eq!( + LoadLibraryA(c"late".as_ptr().cast()) as usize, + 0x7200_0000_0000 + ); + assert!(LoadLibraryA(c"broken.dll".as_ptr().cast()).is_null()); + // As data it runs no code, so the host loads it (and finds nothing). + let data = LoadLibraryExW(w("late.dll").as_ptr(), std::ptr::null_mut(), 0x2); + assert_ne!(data as usize, 0x7200_0000_0000); + + let runtime = LoadLibraryA(c"xgameruntime.dll".as_ptr().cast()); + assert!(!runtime.is_null()); + assert_eq!(GetModuleHandleW(w("XGameRuntime.dll").as_ptr()), runtime); + } } diff --git a/crates/victory-hle/src/runtime.rs b/crates/victory-hle/src/runtime.rs index 3bb5ad7..8c8f3f8 100644 --- a/crates/victory-hle/src/runtime.rs +++ b/crates/victory-hle/src/runtime.rs @@ -40,6 +40,31 @@ pub fn image_path(base: usize) -> Option { .map(|(_, p)| p.clone()) } +/// The title image whose original file is called `file` (any case). +pub fn image_named(file: &str) -> Option { + let paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner()); + paths + .iter() + .find(|(_, p)| p.file_name().is_some_and(|n| n.eq_ignore_ascii_case(file))) + .map(|(b, _)| *b) +} + +/// Maps a title DLL the title loads itself (`LoadLibrary`) and returns its +/// base; `Ok(None)` if `file` is not one of the title's DLLs. +pub type TitleDllLoader = Box Result, String> + Send + Sync>; + +static TITLE_DLL_LOADER: std::sync::OnceLock = std::sync::OnceLock::new(); + +/// Set once, by whoever mapped the title (it knows the folders and the +/// resolver); later calls are ignored. +pub fn set_title_dll_loader(loader: TitleDllLoader) { + let _ = TITLE_DLL_LOADER.set(loader); +} + +pub fn load_title_dll(file: &str) -> Result, String> { + TITLE_DLL_LOADER.get().map_or(Ok(None), |load| load(file)) +} + /// What the title's manifest (`MicrosoftGame.config` beside its executable) /// says about it, and where its persistent local storage lives. #[derive(Debug, Clone, Default, PartialEq, Eq)] diff --git a/crates/victory-loader/src/lib.rs b/crates/victory-loader/src/lib.rs index 8124319..8a64c90 100644 --- a/crates/victory-loader/src/lib.rs +++ b/crates/victory-loader/src/lib.rs @@ -38,7 +38,9 @@ pub use resolve::{ImportResolver, Provenance, Resolution}; #[cfg(windows)] pub use thunks::{UnimplementedPolicy, unimplemented_call_count}; #[cfg(windows)] -pub use windows::{BindReport, LoadedImage, MissingImport, WithTitleDlls, load, load_title_dlls}; +pub use windows::{ + BindReport, LoadedImage, MissingImport, WithTitleDlls, load, load_title_dll, load_title_dlls, +}; /// `DLL_PROCESS_ATTACH`, for TLS callbacks. pub const DLL_PROCESS_ATTACH: u32 = 1; diff --git a/crates/victory-loader/src/windows.rs b/crates/victory-loader/src/windows.rs index 61568d5..64c4b0c 100644 --- a/crates/victory-loader/src/windows.rs +++ b/crates/victory-loader/src/windows.rs @@ -16,8 +16,9 @@ use windows_sys::Win32::System::Memory::{PAGE_READWRITE, VirtualProtect}; use crate::thunks::{ImportSite, ThunkBlock, UnimplementedPolicy}; use crate::{DLL_PROCESS_ATTACH, ImportResolver, PreparedImage, Provenance, Resolution, prepare}; -/// A title image mapped into this process. -#[derive(Debug)] +/// A title image mapped into this process. A clone names the same mapping +/// (no reference of its own): unload one copy only. +#[derive(Debug, Clone)] pub struct LoadedImage { module: HMODULE, path: PathBuf, @@ -99,34 +100,61 @@ pub fn load_title_dlls( cache_dir: &Path, wanted: &dyn Fn(&str) -> bool, ) -> Result> { - fn visit( - info: &ImageInfo, - dirs: (&Path, &Path), - wanted: &dyn Fn(&str) -> bool, - seen: &mut HashSet, - loaded: &mut Vec<(String, LoadedImage)>, - ) -> Result<()> { - for module in info.imports.iter().chain(&info.delay_imports) { - let name = module.dll.to_ascii_lowercase(); - let path = dirs.0.join(&name); - if !seen.insert(name.clone()) || !wanted(&name) || !path.is_file() { - continue; - } - let original = - std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?; - let image = load(&prepare(&original)?, dirs.1) - .with_context(|| format!("loading {}", path.display()))?; - visit(&image.info, dirs, wanted, seen, loaded)?; - loaded.push((name, image)); - } - Ok(()) - } let mut loaded = Vec::new(); let dirs = (title_dir, cache_dir); - visit(main, dirs, wanted, &mut HashSet::new(), &mut loaded)?; + map_imports(main, dirs, wanted, &mut HashSet::new(), &mut loaded)?; Ok(loaded) } +/// Maps the DLL `name` from `title_dir` like [`load_title_dlls`] does, with +/// the title DLLs it imports (dependencies first, `name` last); empty if +/// `wanted` refuses it or the folder has no such file. For DLLs a title +/// loads itself; `wanted` must refuse those already mapped. +pub fn load_title_dll( + name: &str, + title_dir: &Path, + cache_dir: &Path, + wanted: &dyn Fn(&str) -> bool, +) -> Result> { + let mut loaded = Vec::new(); + let dirs = (title_dir, cache_dir); + map_dll(name, dirs, wanted, &mut HashSet::new(), &mut loaded)?; + Ok(loaded) +} + +fn map_imports( + info: &ImageInfo, + dirs: (&Path, &Path), + wanted: &dyn Fn(&str) -> bool, + seen: &mut HashSet, + loaded: &mut Vec<(String, LoadedImage)>, +) -> Result<()> { + for module in info.imports.iter().chain(&info.delay_imports) { + map_dll(&module.dll, dirs, wanted, seen, loaded)?; + } + Ok(()) +} + +fn map_dll( + name: &str, + dirs: (&Path, &Path), + wanted: &dyn Fn(&str) -> bool, + seen: &mut HashSet, + loaded: &mut Vec<(String, LoadedImage)>, +) -> Result<()> { + let name = name.to_ascii_lowercase(); + let path = dirs.0.join(&name); + if !seen.insert(name.clone()) || !wanted(&name) || !path.is_file() { + return Ok(()); + } + let original = std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?; + let image = load(&prepare(&original)?, dirs.1) + .with_context(|| format!("loading {}", path.display()))?; + map_imports(&image.info, dirs, wanted, seen, loaded)?; + loaded.push((name, image)); + Ok(()) +} + /// Resolves through `inner`, then through the exports of the title's DLLs. pub struct WithTitleDlls<'a> { pub inner: &'a dyn ImportResolver, diff --git a/crates/victory-loader/tests/load_probe.rs b/crates/victory-loader/tests/load_probe.rs index d6e8f16..94081e7 100644 --- a/crates/victory-loader/tests/load_probe.rs +++ b/crates/victory-loader/tests/load_probe.rs @@ -181,3 +181,24 @@ fn loads_binds_and_calls_probe() { image.unload(); } } + +#[test] +fn maps_a_title_dll_the_title_loads_itself() { + let title_dir = tempfile::tempdir().unwrap(); + let cache = tempfile::tempdir().unwrap(); + // Any real DLL will do; it imports only host DLLs, which are not in the folder. + std::fs::copy( + r"C:\Windows\System32\version.dll", + title_dir.path().join("Late.dll"), + ) + .unwrap(); + let load = |name: &str, wanted: &dyn Fn(&str) -> bool| { + victory_loader::load_title_dll(name, title_dir.path(), cache.path(), wanted).unwrap() + }; + let dlls = load("LATE.DLL", &|_| true); + let names: Vec<_> = dlls.iter().map(|(n, _)| n.as_str()).collect(); + assert_eq!(names, ["late.dll"]); + assert!(dlls[0].1.export("GetFileVersionInfoW").is_some()); + assert!(load("absent.dll", &|_| true).is_empty()); + assert!(load("late.dll", &|_| false).is_empty()); +} diff --git a/docs/architecture.md b/docs/architecture.md index 468d294..336721e 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -58,6 +58,8 @@ For every `dll!function` the title imports, in order: `LoadLibrary*` of a console-only DLL we implement (e.g. `xgameruntime.dll`) returns a pseudo handle; `GetProcAddress` on it finds our functions. +`LoadLibrary*` of a title DLL returns its mapped image, mapping it first if +nothing imports it. `QueryApiImpl` hands out our runtime objects by provider (task queues and async blocks so far, `victory-hle::modules::xasync`).