run.rs 20 KB

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