run.rs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. use std::path::Path;
  2. use anyhow::{Context, Result};
  3. use crate::{Console, Unimplemented};
  4. #[cfg(windows)]
  5. pub fn run(
  6. exe: &Path,
  7. unimplemented: Unimplemented,
  8. strict: bool,
  9. execute: bool,
  10. console: Console,
  11. ) -> Result<()> {
  12. use std::sync::Arc;
  13. use victory_hle::{HleResolver, HostPolicy};
  14. use victory_loader::{BindReport, UnimplementedPolicy, WithTitleDlls};
  15. // A title that relaunched itself: the old process must be gone first.
  16. victory_hle::modules::lifecycle::wait_for_previous();
  17. let cfg = victory_core::Config::load()?;
  18. let original = std::fs::read(exe).with_context(|| format!("reading {}", exe.display()))?;
  19. let prepared = victory_loader::prepare(&original)?;
  20. let hash = prepared.original_hash.to_hex();
  21. match victory_game::identify(&hash) {
  22. Some(build) => println!("build {} ({hash})", build.label),
  23. None => println!("build unknown ({hash})"),
  24. }
  25. let images = cfg.cache_subdir("images")?;
  26. victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?);
  27. let image = victory_loader::load(&prepared, &images)?;
  28. victory_hle::runtime::set_main_image(image.base());
  29. victory_hle::runtime::set_image_path(image.base(), exe);
  30. println!(
  31. "mapped at {:#x} (preferred {:#x})",
  32. image.base(),
  33. image.info().image_base
  34. );
  35. let resolver = HleResolver::new(if strict {
  36. HostPolicy::none()
  37. } else {
  38. HostPolicy::default()
  39. });
  40. let wanted = |dll: &str| title_dll(&resolver.host, dll);
  41. let title_dir = exe.parent().unwrap_or(Path::new("."));
  42. // A missing manifest leaves id 0 and no storage quota.
  43. let manifest =
  44. std::fs::read_to_string(title_dir.join("MicrosoftGame.config")).unwrap_or_default();
  45. let title = victory_hle::runtime::Title::from_manifest(&manifest);
  46. let storage = cfg.data_subdir(&format!("{:08X}/storage", title.id))?;
  47. println!(
  48. "title {:08X}, storage {} ({} MB)",
  49. title.id,
  50. storage.display(),
  51. title.storage_bytes >> 20
  52. );
  53. // The console's fixed drives: the package as `G:`, temporary files `T:`.
  54. victory_hle::modules::files::mount_at('G', title_dir);
  55. let temp = cfg.data_subdir(&format!("{:08X}/temp", title.id))?;
  56. victory_hle::modules::files::mount_at('T', &temp);
  57. victory_hle::runtime::set_title(victory_hle::runtime::Title { storage, ..title });
  58. victory_hle::console::set(match console {
  59. Console::SeriesX => victory_hle::console::Console::SeriesX,
  60. Console::SeriesS => victory_hle::console::Console::SeriesS,
  61. });
  62. println!("console {}", victory_hle::console::current().name());
  63. let dlls = victory_loader::load_title_dlls(image.info(), title_dir, &images, &wanted)?;
  64. for (name, dll) in &dlls {
  65. println!("title dll {name} at {:#x}", dll.base());
  66. victory_hle::runtime::set_image_path(dll.base(), &title_dir.join(name));
  67. }
  68. let policy = match unimplemented {
  69. Unimplemented::Trap => UnimplementedPolicy::Trap,
  70. Unimplemented::Zero => UnimplementedPolicy::ReturnZero,
  71. };
  72. let with_dlls = WithTitleDlls {
  73. inner: &resolver,
  74. dlls: &dlls,
  75. };
  76. let show = |name: &str, report: BindReport| {
  77. println!(
  78. "bound {name}: {} hle, {} host, {} title, {} missing",
  79. report.hle,
  80. report.host,
  81. report.title,
  82. report.missing.len()
  83. );
  84. for m in &report.missing {
  85. println!(" missing {}!{}", m.dll, m.symbol);
  86. }
  87. };
  88. for (name, dll) in &dlls {
  89. show(name, dll.bind_imports(&with_dlls, policy)?);
  90. }
  91. let exe_name = exe.file_name().unwrap_or_default().to_string_lossy();
  92. show(&exe_name, image.bind_imports(&with_dlls, policy)?);
  93. if !execute {
  94. println!("not executing (pass --execute to start the title)");
  95. return Ok(());
  96. }
  97. victory_loader::report_crashes();
  98. victory_loader::log_crashes_to(temp.with_file_name("crashes.log"));
  99. victory_hle::runtime::use_console_timers();
  100. #[cfg(feature = "diagnostics")]
  101. diagnostics(&image, &cfg);
  102. let late = LateDlls {
  103. host: resolver.host.clone(),
  104. title_dir: title_dir.to_owned(),
  105. cache_dir: images,
  106. policy,
  107. mapped: std::sync::Mutex::new(dlls.clone()),
  108. lock: LoaderLock::default(),
  109. };
  110. victory_hle::runtime::set_title_dll_loader(Box::new(move |file| {
  111. late.load(file, show).map_err(|e| format!("{e:#}"))
  112. }));
  113. // SAFETY: imports are bound; from here on we run title code.
  114. let main = unsafe { Arc::new(image).spawn_main(dlls)? };
  115. let code = main
  116. .join()
  117. .map_err(|_| anyhow::anyhow!("title main thread panicked"))??;
  118. println!("title exited with {code}");
  119. Ok(())
  120. }
  121. /// The debugging aids (README): scheduled stack dumps, watched values and
  122. /// memory saved on a crash.
  123. #[cfg(all(windows, feature = "diagnostics"))]
  124. fn diagnostics(image: &victory_loader::LoadedImage, cfg: &victory_core::Config) {
  125. victory_loader::dump_stacks_on_schedule();
  126. victory_hle::modules::audio::capture::start();
  127. watch(image.base(), image.info().size_of_image as usize);
  128. // Debugging aid: `VICTORY_CRASH_SAVE=<rva>:<len>,...` (hex) writes those
  129. // title ranges to `crash-<rva>.bin` in the cache dir on a crash.
  130. let size = image.info().size_of_image as usize;
  131. let ranges = std::env::var("VICTORY_CRASH_SAVE").unwrap_or_default();
  132. let hex = |s: &str| usize::from_str_radix(s.trim().trim_start_matches("0x"), 16).ok();
  133. victory_loader::save_on_crash(
  134. ranges
  135. .split(',')
  136. .filter_map(|r| r.split_once(':'))
  137. .filter_map(|(rva, len)| Some((hex(rva)?, hex(len)?)))
  138. .filter(|&(rva, len)| rva.checked_add(len).is_some_and(|end| end <= size))
  139. .map(|(rva, len)| {
  140. let file = cfg.cache_dir.join(format!("crash-{rva:x}.bin"));
  141. (image.base() + rva, len, file)
  142. })
  143. .collect(),
  144. );
  145. }
  146. /// Debugging aid: `VICTORY_WATCH=<rva>,...` (hex) logs the u32 at each
  147. /// title+rva whenever it changes, polled every 5 ms (an engine's state, say).
  148. #[cfg(all(windows, feature = "diagnostics"))]
  149. fn watch(base: usize, size: usize) {
  150. let Ok(list) = std::env::var("VICTORY_WATCH") else {
  151. return;
  152. };
  153. let rvas: Vec<usize> = list
  154. .split(',')
  155. .filter_map(|r| usize::from_str_radix(r.trim().trim_start_matches("0x"), 16).ok())
  156. .filter(|&rva| rva + 4 <= size)
  157. .collect();
  158. std::thread::spawn(move || {
  159. let mut seen = vec![None; rvas.len()];
  160. loop {
  161. for (&rva, seen) in rvas.iter().zip(&mut seen) {
  162. // SAFETY: four bytes inside the mapped image, checked above.
  163. let value = unsafe { ((base + rva) as *const u32).read_volatile() };
  164. if *seen != Some(value) {
  165. eprintln!("VIctory: title+{rva:#x} = {value:#x}");
  166. *seen = Some(value);
  167. }
  168. }
  169. std::thread::sleep(std::time::Duration::from_millis(5));
  170. }
  171. });
  172. }
  173. /// DLLs the host or our runtime provide are never taken from the title.
  174. #[cfg(windows)]
  175. fn title_dll(host: &victory_hle::HostPolicy, dll: &str) -> bool {
  176. !host.allows(dll) && !victory_hle::registry().iter().any(|m| m.serves(dll))
  177. }
  178. /// Title DLLs the title loads itself (`LoadLibrary`) that nothing imports,
  179. /// e.g. Grand Theft Auto VI's upscaler behind its FidelityFX loader.
  180. #[cfg(windows)]
  181. struct LateDlls {
  182. host: victory_hle::HostPolicy,
  183. title_dir: std::path::PathBuf,
  184. cache_dir: std::path::PathBuf,
  185. policy: victory_loader::UnimplementedPolicy,
  186. /// Every title DLL mapped so far, to bind new ones against.
  187. mapped: std::sync::Mutex<Vec<(String, victory_loader::LoadedImage)>>,
  188. lock: LoaderLock,
  189. }
  190. #[cfg(windows)]
  191. impl LateDlls {
  192. /// Every `LoadLibrary` of the title comes here first. Returns a title
  193. /// image called `file`, mapping it and the title DLLs it needs first,
  194. /// binding them and running their `DllMain` on the calling thread, as
  195. /// the Windows loader would; `None` if `file` is no title image.
  196. fn load(
  197. &self,
  198. file: &str,
  199. show: impl Fn(&str, victory_loader::BindReport),
  200. ) -> Result<Option<usize>> {
  201. use victory_hle::runtime::{forget_image, image_named, set_image_path};
  202. // Waits while another thread initialises a DLL; a `DllMain` that
  203. // loads another DLL re-enters.
  204. self.lock.hold(|| {
  205. if let Some(base) = image_named(file) {
  206. return Ok(Some(base));
  207. }
  208. let new = {
  209. let mut mapped = self.mapped.lock().unwrap_or_else(|e| e.into_inner());
  210. let wanted = |dll: &str| title_dll(&self.host, dll) && image_named(dll).is_none();
  211. let new = victory_loader::load_title_dll(
  212. file,
  213. &self.title_dir,
  214. &self.cache_dir,
  215. &wanted,
  216. )?;
  217. let hle = victory_hle::HleResolver::new(self.host.clone());
  218. let old = victory_loader::WithTitleDlls {
  219. inner: &hle,
  220. dlls: &mapped,
  221. };
  222. let resolver = victory_loader::WithTitleDlls {
  223. inner: &old,
  224. dlls: &new,
  225. };
  226. for (name, dll) in &new {
  227. println!(
  228. "title dll {name} at {:#x} (loaded by the title)",
  229. dll.base()
  230. );
  231. show(name, dll.bind_imports(&resolver, self.policy)?);
  232. set_image_path(dll.base(), &self.title_dir.join(name));
  233. }
  234. // Visible before their `DllMain`s run, which may load more.
  235. mapped.extend(new.iter().cloned());
  236. new
  237. };
  238. let failed = new.iter().enumerate().find_map(|(i, (name, dll))| {
  239. // SAFETY: bound above, dependencies attached first.
  240. let attached = unsafe { dll.attach() };
  241. attached
  242. .err()
  243. .map(|e| (i, e.context(format!("attaching {name}"))))
  244. });
  245. let Some((i, error)) = failed else {
  246. return Ok(new.last().map(|(_, dll)| dll.base()));
  247. };
  248. // As `LoadLibrary` does when a `DllMain` fails: detach what this
  249. // load attached (the failed one too) and unmap all of it.
  250. let bases: Vec<_> = new.iter().map(|(_, d)| d.base()).collect();
  251. self.mapped
  252. .lock()
  253. .unwrap_or_else(|e| e.into_inner())
  254. .retain(|(_, d)| !bases.contains(&d.base()));
  255. for (_, done) in new[..=i].iter().rev() {
  256. // SAFETY: attached (or failing to) on this thread just now.
  257. unsafe { done.detach() };
  258. }
  259. for (_, dll) in new {
  260. forget_image(dll.base());
  261. // SAFETY: detached, and no title code holds it yet.
  262. unsafe { dll.unload() };
  263. }
  264. Err(error)
  265. })
  266. }
  267. }
  268. /// The Windows loader lock's shape: one thread at a time, re-entered by
  269. /// the thread that holds it.
  270. #[cfg(windows)]
  271. #[derive(Default)]
  272. struct LoaderLock {
  273. owner: std::sync::Mutex<(Option<std::thread::ThreadId>, usize)>,
  274. free: std::sync::Condvar,
  275. }
  276. #[cfg(windows)]
  277. impl LoaderLock {
  278. fn hold<T>(&self, f: impl FnOnce() -> T) -> T {
  279. let me = std::thread::current().id();
  280. let lock = || self.owner.lock().unwrap_or_else(|e| e.into_inner());
  281. {
  282. let mut owner = lock();
  283. while owner.0.is_some_and(|o| o != me) {
  284. owner = self.free.wait(owner).unwrap_or_else(|e| e.into_inner());
  285. }
  286. *owner = (Some(me), owner.1 + 1);
  287. }
  288. let result = f();
  289. let mut owner = lock();
  290. owner.1 -= 1;
  291. if owner.1 == 0 {
  292. owner.0 = None;
  293. self.free.notify_one();
  294. }
  295. result
  296. }
  297. }
  298. #[cfg(all(test, windows))]
  299. mod tests {
  300. use std::sync::{Arc, Mutex};
  301. #[test]
  302. fn loader_lock_is_reentrant_and_exclusive() {
  303. let lock = Arc::new(super::LoaderLock::default());
  304. assert_eq!(lock.hold(|| lock.hold(|| 7)), 7);
  305. let order = Arc::new(Mutex::new(Vec::new()));
  306. let other = lock.hold(|| {
  307. let (theirs, their_order) = (lock.clone(), order.clone());
  308. let other = std::thread::spawn(move || {
  309. theirs.hold(|| their_order.lock().unwrap().push(2));
  310. });
  311. std::thread::sleep(std::time::Duration::from_millis(50));
  312. order.lock().unwrap().push(1);
  313. other
  314. });
  315. other.join().unwrap();
  316. assert_eq!(*order.lock().unwrap(), [1, 2]);
  317. }
  318. }
  319. #[cfg(not(windows))]
  320. pub fn run(_: &Path, _: Unimplemented, _: bool, _: bool, _: Console) -> Result<()> {
  321. anyhow::bail!("running titles requires Windows")
  322. }