run.rs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. use std::path::Path;
  2. use anyhow::{Context, Result};
  3. use crate::{Console, Unimplemented};
  4. #[cfg(any(windows, test))]
  5. const SKIP_CPU_CHECK_ENV: &str = "VICTORY_SKIP_CPU_CHECK";
  6. #[cfg(any(windows, test))]
  7. fn skip_cpu_check(value: Option<&str>) -> bool {
  8. value == Some("1")
  9. }
  10. #[cfg(any(windows, test))]
  11. fn check_cpu_features_with(has_avx2: bool, skip_env: Option<&str>) -> Result<()> {
  12. if has_avx2 || skip_cpu_check(skip_env) {
  13. return Ok(());
  14. }
  15. anyhow::bail!(
  16. "this CPU does not support AVX2, which Xbox Series titles require; \
  17. set {SKIP_CPU_CHECK_ENV}=1 to bypass this check (for example under CPU emulation such as Intel SDE)"
  18. );
  19. }
  20. /// Pre-flight check before executing title code: Xbox Series binaries are
  21. /// compiled for Zen 2 and require AVX2.
  22. #[cfg(windows)]
  23. fn check_cpu_features() -> Result<()> {
  24. #[cfg(target_arch = "x86_64")]
  25. let has_avx2 = std::arch::is_x86_feature_detected!("avx2");
  26. #[cfg(not(target_arch = "x86_64"))]
  27. let has_avx2 = true;
  28. let skip = std::env::var(SKIP_CPU_CHECK_ENV).ok();
  29. check_cpu_features_with(has_avx2, skip.as_deref())
  30. }
  31. #[cfg(windows)]
  32. pub fn run(
  33. exe: &Path,
  34. unimplemented: Unimplemented,
  35. strict: bool,
  36. execute: bool,
  37. console: Console,
  38. ) -> Result<()> {
  39. use std::sync::Arc;
  40. use victory_hle::{HleResolver, HostPolicy};
  41. use victory_loader::{BindReport, UnimplementedPolicy, WithTitleDlls};
  42. if execute {
  43. check_cpu_features()?;
  44. }
  45. // A title that relaunched itself: the old process must be gone first.
  46. victory_hle::modules::lifecycle::wait_for_previous();
  47. let cfg = victory_core::Config::load()?;
  48. let original = std::fs::read(exe).with_context(|| format!("reading {}", exe.display()))?;
  49. let prepared = victory_loader::prepare(&original)?;
  50. let hash = prepared.original_hash.to_hex();
  51. match victory_game::identify(&hash) {
  52. Some(build) => println!("build {} ({hash})", build.label),
  53. None => println!("build unknown ({hash})"),
  54. }
  55. let images = cfg.cache_subdir("images")?;
  56. victory_hle::modules::d3d12x::use_shader_cache(cfg.cache_subdir("shaders")?);
  57. let image = victory_loader::load(&prepared, &images)?;
  58. // The program is mapped from the copy `load` wrote: the file's bytes
  59. // and their patched copy are not read again, and were held for the
  60. // whole run (two blocks of 114.7 MB each for the title, in
  61. // physical memory: run 65's memory map).
  62. drop(prepared);
  63. drop(original);
  64. victory_hle::runtime::set_main_image(image.base());
  65. victory_hle::runtime::set_image_path(image.base(), exe);
  66. println!(
  67. "mapped at {:#x} (preferred {:#x})",
  68. image.base(),
  69. image.info().image_base
  70. );
  71. let resolver = HleResolver::new(if strict {
  72. HostPolicy::none()
  73. } else {
  74. HostPolicy::default()
  75. });
  76. let wanted = |dll: &str| title_dll(&resolver.host, dll);
  77. let title_dir = exe.parent().unwrap_or(Path::new("."));
  78. // A missing manifest leaves id 0 and no storage quota.
  79. let manifest =
  80. std::fs::read_to_string(title_dir.join("MicrosoftGame.config")).unwrap_or_default();
  81. let title = victory_hle::runtime::Title::from_manifest(&manifest);
  82. let storage = cfg.data_subdir(&format!("{:08X}/storage", title.id))?;
  83. println!(
  84. "title {:08X}, storage {} ({} MB)",
  85. title.id,
  86. storage.display(),
  87. title.storage_bytes >> 20
  88. );
  89. // The console's fixed drives: the package as `G:`, temporary files `T:`.
  90. victory_hle::modules::files::mount_at('G', title_dir);
  91. let temp = cfg.data_subdir(&format!("{:08X}/temp", title.id))?;
  92. victory_hle::modules::files::mount_at('T', &temp);
  93. victory_hle::runtime::set_title(victory_hle::runtime::Title { storage, ..title });
  94. victory_hle::console::set(match console {
  95. Console::SeriesX => victory_hle::console::Console::SeriesX,
  96. Console::SeriesS => victory_hle::console::Console::SeriesS,
  97. });
  98. println!("console {}", victory_hle::console::current().name());
  99. let dlls = victory_loader::load_title_dlls(image.info(), title_dir, &images, &wanted)?;
  100. for (name, dll) in &dlls {
  101. println!("title dll {name} at {:#x}", dll.base());
  102. victory_hle::runtime::set_image_path(dll.base(), &title_dir.join(name));
  103. }
  104. let imported: Vec<&str> = image
  105. .info()
  106. .imports
  107. .iter()
  108. .map(|m| m.dll.as_str())
  109. .collect();
  110. let mapped: Vec<&str> = dlls.iter().map(|(name, _)| name.as_str()).collect();
  111. let absent = absent_title_dlls(&imported, &mapped, &wanted);
  112. if !absent.is_empty() {
  113. let message = format!(
  114. "{} not in {}, and neither the host nor VIctory provides {}: the package is \
  115. incomplete; copy every file of the package next to the executable",
  116. absent.join(", "),
  117. title_dir.display(),
  118. if absent.len() == 1 { "it" } else { "them" },
  119. );
  120. println!("missing dlls {message}");
  121. // None of their imports can be bound, so the title stops at its first
  122. // call into one (Grand Theft Auto VI 1.0.2.1 at +0x2237178 during
  123. // System Init, #930) with nothing saying why. Stubs only if asked for.
  124. if execute && matches!(unimplemented, Unimplemented::Trap) {
  125. anyhow::bail!(
  126. "the title's own DLLs are missing: {message} (`--unimplemented zero` runs it anyway)"
  127. );
  128. }
  129. }
  130. let policy = match unimplemented {
  131. Unimplemented::Trap => UnimplementedPolicy::Trap,
  132. Unimplemented::Zero => UnimplementedPolicy::ReturnZero,
  133. };
  134. let with_dlls = WithTitleDlls {
  135. inner: &resolver,
  136. dlls: &dlls,
  137. };
  138. let show = |name: &str, report: BindReport| {
  139. println!(
  140. "bound {name}: {} hle, {} host, {} title, {} missing",
  141. report.hle,
  142. report.host,
  143. report.title,
  144. report.missing.len()
  145. );
  146. for m in &report.missing {
  147. println!(" missing {}!{}", m.dll, m.symbol);
  148. }
  149. };
  150. for (name, dll) in &dlls {
  151. show(name, dll.bind_imports(&with_dlls, policy)?);
  152. }
  153. let exe_name = exe.file_name().unwrap_or_default().to_string_lossy();
  154. show(&exe_name, image.bind_imports(&with_dlls, policy)?);
  155. if !execute {
  156. println!("not executing (pass --execute to start the title)");
  157. return Ok(());
  158. }
  159. victory_loader::report_crashes();
  160. victory_loader::log_crashes_to(temp.with_file_name("crashes.log"));
  161. victory_hle::runtime::use_console_timers();
  162. #[cfg(feature = "diagnostics")]
  163. diagnostics(&image, &cfg);
  164. let late = LateDlls {
  165. host: resolver.host.clone(),
  166. title_dir: title_dir.to_owned(),
  167. cache_dir: images,
  168. policy,
  169. mapped: std::sync::Mutex::new(dlls.clone()),
  170. lock: LoaderLock::default(),
  171. };
  172. victory_hle::runtime::set_title_dll_loader(Box::new(move |file| {
  173. late.load(file, show).map_err(|e| format!("{e:#}"))
  174. }));
  175. // SAFETY: imports are bound; from here on we run title code.
  176. let main = unsafe { Arc::new(image).spawn_main(dlls)? };
  177. let code = main
  178. .join()
  179. .map_err(|_| anyhow::anyhow!("title main thread panicked"))??;
  180. println!("title exited with {code}");
  181. Ok(())
  182. }
  183. /// The debugging aids (README): scheduled stack dumps, watched values and
  184. /// memory saved on a crash.
  185. #[cfg(all(windows, feature = "diagnostics"))]
  186. fn diagnostics(image: &victory_loader::LoadedImage, cfg: &victory_core::Config) {
  187. victory_loader::dump_stacks_on_schedule();
  188. victory_hle::modules::audio::capture::start();
  189. watch(image.base(), image.info().size_of_image as usize);
  190. // Debugging aid: `VICTORY_CRASH_SAVE=<rva>:<len>,...` (hex) writes those
  191. // title ranges to `crash-<rva>.bin` in the cache dir on a crash.
  192. let size = image.info().size_of_image as usize;
  193. let ranges = std::env::var("VICTORY_CRASH_SAVE").unwrap_or_default();
  194. let hex = |s: &str| usize::from_str_radix(s.trim().trim_start_matches("0x"), 16).ok();
  195. victory_loader::save_on_crash(
  196. ranges
  197. .split(',')
  198. .filter_map(|r| r.split_once(':'))
  199. .filter_map(|(rva, len)| Some((hex(rva)?, hex(len)?)))
  200. .filter(|&(rva, len)| rva.checked_add(len).is_some_and(|end| end <= size))
  201. .map(|(rva, len)| {
  202. let file = cfg.cache_dir.join(format!("crash-{rva:x}.bin"));
  203. (image.base() + rva, len, file)
  204. })
  205. .collect(),
  206. );
  207. }
  208. /// Debugging aid: `VICTORY_WATCH=<rva>,...` (hex) logs the u32 at each
  209. /// title+rva whenever it changes, polled every 5 ms (an engine's state, say).
  210. #[cfg(all(windows, feature = "diagnostics"))]
  211. fn watch(base: usize, size: usize) {
  212. let Ok(list) = std::env::var("VICTORY_WATCH") else {
  213. return;
  214. };
  215. let rvas: Vec<usize> = list
  216. .split(',')
  217. .filter_map(|r| usize::from_str_radix(r.trim().trim_start_matches("0x"), 16).ok())
  218. .filter(|&rva| rva + 4 <= size)
  219. .collect();
  220. std::thread::spawn(move || {
  221. let mut seen = vec![None; rvas.len()];
  222. loop {
  223. for (&rva, seen) in rvas.iter().zip(&mut seen) {
  224. // SAFETY: four bytes inside the mapped image, checked above.
  225. let value = unsafe { ((base + rva) as *const u32).read_volatile() };
  226. if *seen != Some(value) {
  227. eprintln!("VIctory: title+{rva:#x} = {value:#x}");
  228. *seen = Some(value);
  229. }
  230. }
  231. std::thread::sleep(std::time::Duration::from_millis(5));
  232. }
  233. });
  234. }
  235. /// DLLs the host or our runtime provide are never taken from the title.
  236. #[cfg(windows)]
  237. fn title_dll(host: &victory_hle::HostPolicy, dll: &str) -> bool {
  238. !host.allows(dll) && !victory_hle::registry().iter().any(|m| m.serves(dll))
  239. }
  240. /// The DLLs among `imported` (the main image's static imports) that must
  241. /// come from the title's folder (`wanted`) but were not mapped from it:
  242. /// none of their imports can be bound. Each named once, case ignored.
  243. #[cfg(any(windows, test))]
  244. fn absent_title_dlls(
  245. imported: &[&str],
  246. mapped: &[&str],
  247. wanted: &dyn Fn(&str) -> bool,
  248. ) -> Vec<String> {
  249. let mut absent: Vec<String> = Vec::new();
  250. for &dll in imported {
  251. let known = |list: &[&str]| list.iter().any(|m| m.eq_ignore_ascii_case(dll));
  252. if wanted(dll) && !known(mapped) && !absent.iter().any(|a| a.eq_ignore_ascii_case(dll)) {
  253. absent.push(dll.to_owned());
  254. }
  255. }
  256. absent
  257. }
  258. /// Title DLLs the title loads itself (`LoadLibrary`) that nothing imports,
  259. /// e.g. The title's upscaler behind its FidelityFX loader.
  260. #[cfg(windows)]
  261. struct LateDlls {
  262. host: victory_hle::HostPolicy,
  263. title_dir: std::path::PathBuf,
  264. cache_dir: std::path::PathBuf,
  265. policy: victory_loader::UnimplementedPolicy,
  266. /// Every title DLL mapped so far, to bind new ones against.
  267. mapped: std::sync::Mutex<Vec<(String, victory_loader::LoadedImage)>>,
  268. lock: LoaderLock,
  269. }
  270. #[cfg(windows)]
  271. impl LateDlls {
  272. /// Every `LoadLibrary` of the title comes here first. Returns a title
  273. /// image called `file`, mapping it and the title DLLs it needs first,
  274. /// binding them and running their `DllMain` on the calling thread, as
  275. /// the Windows loader would; `None` if `file` is no title image.
  276. fn load(
  277. &self,
  278. file: &str,
  279. show: impl Fn(&str, victory_loader::BindReport),
  280. ) -> Result<Option<usize>> {
  281. use victory_hle::runtime::{forget_image, image_named, set_image_path};
  282. // Waits while another thread initialises a DLL; a `DllMain` that
  283. // loads another DLL re-enters.
  284. self.lock.hold(|| {
  285. if let Some(base) = image_named(file) {
  286. return Ok(Some(base));
  287. }
  288. let new = {
  289. let mut mapped = self.mapped.lock().unwrap_or_else(|e| e.into_inner());
  290. let wanted = |dll: &str| title_dll(&self.host, dll) && image_named(dll).is_none();
  291. let new = victory_loader::load_title_dll(
  292. file,
  293. &self.title_dir,
  294. &self.cache_dir,
  295. &wanted,
  296. )?;
  297. let hle = victory_hle::HleResolver::new(self.host.clone());
  298. let old = victory_loader::WithTitleDlls {
  299. inner: &hle,
  300. dlls: &mapped,
  301. };
  302. let resolver = victory_loader::WithTitleDlls {
  303. inner: &old,
  304. dlls: &new,
  305. };
  306. for (name, dll) in &new {
  307. println!(
  308. "title dll {name} at {:#x} (loaded by the title)",
  309. dll.base()
  310. );
  311. show(name, dll.bind_imports(&resolver, self.policy)?);
  312. set_image_path(dll.base(), &self.title_dir.join(name));
  313. }
  314. // Visible before their `DllMain`s run, which may load more.
  315. mapped.extend(new.iter().cloned());
  316. new
  317. };
  318. let failed = new.iter().enumerate().find_map(|(i, (name, dll))| {
  319. // SAFETY: bound above, dependencies attached first.
  320. let attached = unsafe { dll.attach() };
  321. attached
  322. .err()
  323. .map(|e| (i, e.context(format!("attaching {name}"))))
  324. });
  325. let Some((i, error)) = failed else {
  326. return Ok(new.last().map(|(_, dll)| dll.base()));
  327. };
  328. // As `LoadLibrary` does when a `DllMain` fails: detach what this
  329. // load attached (the failed one too) and unmap all of it.
  330. let bases: Vec<_> = new.iter().map(|(_, d)| d.base()).collect();
  331. self.mapped
  332. .lock()
  333. .unwrap_or_else(|e| e.into_inner())
  334. .retain(|(_, d)| !bases.contains(&d.base()));
  335. for (_, done) in new[..=i].iter().rev() {
  336. // SAFETY: attached (or failing to) on this thread just now.
  337. unsafe { done.detach() };
  338. }
  339. for (_, dll) in new {
  340. forget_image(dll.base());
  341. // SAFETY: detached, and no title code holds it yet.
  342. unsafe { dll.unload() };
  343. }
  344. Err(error)
  345. })
  346. }
  347. }
  348. /// The Windows loader lock's shape: one thread at a time, re-entered by
  349. /// the thread that holds it.
  350. #[cfg(windows)]
  351. #[derive(Default)]
  352. struct LoaderLock {
  353. owner: std::sync::Mutex<(Option<std::thread::ThreadId>, usize)>,
  354. free: std::sync::Condvar,
  355. }
  356. #[cfg(windows)]
  357. impl LoaderLock {
  358. fn hold<T>(&self, f: impl FnOnce() -> T) -> T {
  359. let me = std::thread::current().id();
  360. let lock = || self.owner.lock().unwrap_or_else(|e| e.into_inner());
  361. {
  362. let mut owner = lock();
  363. while owner.0.is_some_and(|o| o != me) {
  364. owner = self.free.wait(owner).unwrap_or_else(|e| e.into_inner());
  365. }
  366. *owner = (Some(me), owner.1 + 1);
  367. }
  368. let result = f();
  369. let mut owner = lock();
  370. owner.1 -= 1;
  371. if owner.1 == 0 {
  372. owner.0 = None;
  373. self.free.notify_one();
  374. }
  375. result
  376. }
  377. }
  378. #[cfg(test)]
  379. mod absent_tests {
  380. use super::absent_title_dlls;
  381. #[test]
  382. fn title_dlls_missing_from_the_folder_are_named_once() {
  383. // The host provides kernel32, our runtime d3d12_xs; the rest are the
  384. // title's own (#930: the four DLLs beside the executable missing).
  385. let wanted = |dll: &str| {
  386. !["KERNEL32.dll", "d3d12_xs.dll"]
  387. .iter()
  388. .any(|h| h.eq_ignore_ascii_case(dll))
  389. };
  390. let imported = [
  391. "KERNEL32.dll",
  392. "d3d12_xs.dll",
  393. "XboxBvhBuilder.dll",
  394. "MSVCP140.dll",
  395. "Bink2Scarlett.dll",
  396. "xboxbvhbuilder.dll",
  397. ];
  398. let mapped = ["msvcp140.dll"];
  399. assert_eq!(
  400. absent_title_dlls(&imported, &mapped, &wanted),
  401. ["XboxBvhBuilder.dll", "Bink2Scarlett.dll"]
  402. );
  403. }
  404. #[test]
  405. fn a_complete_package_has_nothing_absent() {
  406. let wanted = |dll: &str| dll.starts_with("Title");
  407. assert!(absent_title_dlls(&["Title.dll", "Host.dll"], &["TITLE.DLL"], &wanted).is_empty());
  408. assert!(absent_title_dlls(&[], &[], &wanted).is_empty());
  409. }
  410. }
  411. #[cfg(all(test, windows))]
  412. mod tests {
  413. use std::sync::{Arc, Mutex};
  414. #[test]
  415. fn loader_lock_is_reentrant_and_exclusive() {
  416. let lock = Arc::new(super::LoaderLock::default());
  417. assert_eq!(lock.hold(|| lock.hold(|| 7)), 7);
  418. let order = Arc::new(Mutex::new(Vec::new()));
  419. let other = lock.hold(|| {
  420. let (theirs, their_order) = (lock.clone(), order.clone());
  421. let other = std::thread::spawn(move || {
  422. theirs.hold(|| their_order.lock().unwrap().push(2));
  423. });
  424. std::thread::sleep(std::time::Duration::from_millis(50));
  425. order.lock().unwrap().push(1);
  426. other
  427. });
  428. other.join().unwrap();
  429. assert_eq!(*order.lock().unwrap(), [1, 2]);
  430. }
  431. #[test]
  432. fn cpu_feature_check_matches_host() {
  433. let skip = std::env::var(super::SKIP_CPU_CHECK_ENV).ok();
  434. #[cfg(target_arch = "x86_64")]
  435. let expected_ok =
  436. std::arch::is_x86_feature_detected!("avx2") || skip.as_deref() == Some("1");
  437. #[cfg(not(target_arch = "x86_64"))]
  438. let expected_ok = true;
  439. assert_eq!(super::check_cpu_features().is_ok(), expected_ok);
  440. }
  441. }
  442. #[cfg(test)]
  443. mod cpu_check_tests {
  444. use super::{SKIP_CPU_CHECK_ENV, check_cpu_features_with};
  445. #[test]
  446. fn avx2_present_passes() {
  447. assert!(check_cpu_features_with(true, None).is_ok());
  448. assert!(check_cpu_features_with(true, Some("0")).is_ok());
  449. assert!(check_cpu_features_with(true, Some("1")).is_ok());
  450. }
  451. #[test]
  452. fn avx2_missing_fails_with_clear_error() {
  453. for skip in [None, Some(""), Some("0"), Some("true")] {
  454. let err = check_cpu_features_with(false, skip).unwrap_err();
  455. let msg = err.to_string();
  456. assert!(msg.contains("AVX2"), "unexpected error: {msg}");
  457. assert!(msg.contains("Xbox Series"), "unexpected error: {msg}");
  458. assert!(msg.contains(SKIP_CPU_CHECK_ENV), "unexpected error: {msg}");
  459. }
  460. }
  461. #[test]
  462. fn skip_env_var_bypasses_missing_avx2() {
  463. assert!(check_cpu_features_with(false, Some("1")).is_ok());
  464. }
  465. }
  466. #[cfg(not(windows))]
  467. pub fn run(_: &Path, _: Unimplemented, _: bool, _: bool, _: Console) -> Result<()> {
  468. anyhow::bail!("running titles requires Windows")
  469. }