run.rs 13 KB

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