run.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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 policy = match unimplemented {
  105. Unimplemented::Trap => UnimplementedPolicy::Trap,
  106. Unimplemented::Zero => UnimplementedPolicy::ReturnZero,
  107. };
  108. let with_dlls = WithTitleDlls {
  109. inner: &resolver,
  110. dlls: &dlls,
  111. };
  112. let show = |name: &str, report: BindReport| {
  113. println!(
  114. "bound {name}: {} hle, {} host, {} title, {} missing",
  115. report.hle,
  116. report.host,
  117. report.title,
  118. report.missing.len()
  119. );
  120. for m in &report.missing {
  121. println!(" missing {}!{}", m.dll, m.symbol);
  122. }
  123. };
  124. for (name, dll) in &dlls {
  125. show(name, dll.bind_imports(&with_dlls, policy)?);
  126. }
  127. let exe_name = exe.file_name().unwrap_or_default().to_string_lossy();
  128. show(&exe_name, image.bind_imports(&with_dlls, policy)?);
  129. if !execute {
  130. println!("not executing (pass --execute to start the title)");
  131. return Ok(());
  132. }
  133. victory_loader::report_crashes();
  134. victory_loader::log_crashes_to(temp.with_file_name("crashes.log"));
  135. victory_hle::runtime::use_console_timers();
  136. #[cfg(feature = "diagnostics")]
  137. diagnostics(&image, &cfg);
  138. let late = LateDlls {
  139. host: resolver.host.clone(),
  140. title_dir: title_dir.to_owned(),
  141. cache_dir: images,
  142. policy,
  143. mapped: std::sync::Mutex::new(dlls.clone()),
  144. lock: LoaderLock::default(),
  145. };
  146. victory_hle::runtime::set_title_dll_loader(Box::new(move |file| {
  147. late.load(file, show).map_err(|e| format!("{e:#}"))
  148. }));
  149. // SAFETY: imports are bound; from here on we run title code.
  150. let main = unsafe { Arc::new(image).spawn_main(dlls)? };
  151. let code = main
  152. .join()
  153. .map_err(|_| anyhow::anyhow!("title main thread panicked"))??;
  154. println!("title exited with {code}");
  155. Ok(())
  156. }
  157. /// The debugging aids (README): scheduled stack dumps, watched values and
  158. /// memory saved on a crash.
  159. #[cfg(all(windows, feature = "diagnostics"))]
  160. fn diagnostics(image: &victory_loader::LoadedImage, cfg: &victory_core::Config) {
  161. victory_loader::dump_stacks_on_schedule();
  162. victory_hle::modules::audio::capture::start();
  163. watch(image.base(), image.info().size_of_image as usize);
  164. // Debugging aid: `VICTORY_CRASH_SAVE=<rva>:<len>,...` (hex) writes those
  165. // title ranges to `crash-<rva>.bin` in the cache dir on a crash.
  166. let size = image.info().size_of_image as usize;
  167. let ranges = std::env::var("VICTORY_CRASH_SAVE").unwrap_or_default();
  168. let hex = |s: &str| usize::from_str_radix(s.trim().trim_start_matches("0x"), 16).ok();
  169. victory_loader::save_on_crash(
  170. ranges
  171. .split(',')
  172. .filter_map(|r| r.split_once(':'))
  173. .filter_map(|(rva, len)| Some((hex(rva)?, hex(len)?)))
  174. .filter(|&(rva, len)| rva.checked_add(len).is_some_and(|end| end <= size))
  175. .map(|(rva, len)| {
  176. let file = cfg.cache_dir.join(format!("crash-{rva:x}.bin"));
  177. (image.base() + rva, len, file)
  178. })
  179. .collect(),
  180. );
  181. }
  182. /// Debugging aid: `VICTORY_WATCH=<rva>,...` (hex) logs the u32 at each
  183. /// title+rva whenever it changes, polled every 5 ms (an engine's state, say).
  184. #[cfg(all(windows, feature = "diagnostics"))]
  185. fn watch(base: usize, size: usize) {
  186. let Ok(list) = std::env::var("VICTORY_WATCH") else {
  187. return;
  188. };
  189. let rvas: Vec<usize> = list
  190. .split(',')
  191. .filter_map(|r| usize::from_str_radix(r.trim().trim_start_matches("0x"), 16).ok())
  192. .filter(|&rva| rva + 4 <= size)
  193. .collect();
  194. std::thread::spawn(move || {
  195. let mut seen = vec![None; rvas.len()];
  196. loop {
  197. for (&rva, seen) in rvas.iter().zip(&mut seen) {
  198. // SAFETY: four bytes inside the mapped image, checked above.
  199. let value = unsafe { ((base + rva) as *const u32).read_volatile() };
  200. if *seen != Some(value) {
  201. eprintln!("VIctory: title+{rva:#x} = {value:#x}");
  202. *seen = Some(value);
  203. }
  204. }
  205. std::thread::sleep(std::time::Duration::from_millis(5));
  206. }
  207. });
  208. }
  209. /// DLLs the host or our runtime provide are never taken from the title.
  210. #[cfg(windows)]
  211. fn title_dll(host: &victory_hle::HostPolicy, dll: &str) -> bool {
  212. !host.allows(dll) && !victory_hle::registry().iter().any(|m| m.serves(dll))
  213. }
  214. /// Title DLLs the title loads itself (`LoadLibrary`) that nothing imports,
  215. /// e.g. The title's upscaler behind its FidelityFX loader.
  216. #[cfg(windows)]
  217. struct LateDlls {
  218. host: victory_hle::HostPolicy,
  219. title_dir: std::path::PathBuf,
  220. cache_dir: std::path::PathBuf,
  221. policy: victory_loader::UnimplementedPolicy,
  222. /// Every title DLL mapped so far, to bind new ones against.
  223. mapped: std::sync::Mutex<Vec<(String, victory_loader::LoadedImage)>>,
  224. lock: LoaderLock,
  225. }
  226. #[cfg(windows)]
  227. impl LateDlls {
  228. /// Every `LoadLibrary` of the title comes here first. Returns a title
  229. /// image called `file`, mapping it and the title DLLs it needs first,
  230. /// binding them and running their `DllMain` on the calling thread, as
  231. /// the Windows loader would; `None` if `file` is no title image.
  232. fn load(
  233. &self,
  234. file: &str,
  235. show: impl Fn(&str, victory_loader::BindReport),
  236. ) -> Result<Option<usize>> {
  237. use victory_hle::runtime::{forget_image, image_named, set_image_path};
  238. // Waits while another thread initialises a DLL; a `DllMain` that
  239. // loads another DLL re-enters.
  240. self.lock.hold(|| {
  241. if let Some(base) = image_named(file) {
  242. return Ok(Some(base));
  243. }
  244. let new = {
  245. let mut mapped = self.mapped.lock().unwrap_or_else(|e| e.into_inner());
  246. let wanted = |dll: &str| title_dll(&self.host, dll) && image_named(dll).is_none();
  247. let new = victory_loader::load_title_dll(
  248. file,
  249. &self.title_dir,
  250. &self.cache_dir,
  251. &wanted,
  252. )?;
  253. let hle = victory_hle::HleResolver::new(self.host.clone());
  254. let old = victory_loader::WithTitleDlls {
  255. inner: &hle,
  256. dlls: &mapped,
  257. };
  258. let resolver = victory_loader::WithTitleDlls {
  259. inner: &old,
  260. dlls: &new,
  261. };
  262. for (name, dll) in &new {
  263. println!(
  264. "title dll {name} at {:#x} (loaded by the title)",
  265. dll.base()
  266. );
  267. show(name, dll.bind_imports(&resolver, self.policy)?);
  268. set_image_path(dll.base(), &self.title_dir.join(name));
  269. }
  270. // Visible before their `DllMain`s run, which may load more.
  271. mapped.extend(new.iter().cloned());
  272. new
  273. };
  274. let failed = new.iter().enumerate().find_map(|(i, (name, dll))| {
  275. // SAFETY: bound above, dependencies attached first.
  276. let attached = unsafe { dll.attach() };
  277. attached
  278. .err()
  279. .map(|e| (i, e.context(format!("attaching {name}"))))
  280. });
  281. let Some((i, error)) = failed else {
  282. return Ok(new.last().map(|(_, dll)| dll.base()));
  283. };
  284. // As `LoadLibrary` does when a `DllMain` fails: detach what this
  285. // load attached (the failed one too) and unmap all of it.
  286. let bases: Vec<_> = new.iter().map(|(_, d)| d.base()).collect();
  287. self.mapped
  288. .lock()
  289. .unwrap_or_else(|e| e.into_inner())
  290. .retain(|(_, d)| !bases.contains(&d.base()));
  291. for (_, done) in new[..=i].iter().rev() {
  292. // SAFETY: attached (or failing to) on this thread just now.
  293. unsafe { done.detach() };
  294. }
  295. for (_, dll) in new {
  296. forget_image(dll.base());
  297. // SAFETY: detached, and no title code holds it yet.
  298. unsafe { dll.unload() };
  299. }
  300. Err(error)
  301. })
  302. }
  303. }
  304. /// The Windows loader lock's shape: one thread at a time, re-entered by
  305. /// the thread that holds it.
  306. #[cfg(windows)]
  307. #[derive(Default)]
  308. struct LoaderLock {
  309. owner: std::sync::Mutex<(Option<std::thread::ThreadId>, usize)>,
  310. free: std::sync::Condvar,
  311. }
  312. #[cfg(windows)]
  313. impl LoaderLock {
  314. fn hold<T>(&self, f: impl FnOnce() -> T) -> T {
  315. let me = std::thread::current().id();
  316. let lock = || self.owner.lock().unwrap_or_else(|e| e.into_inner());
  317. {
  318. let mut owner = lock();
  319. while owner.0.is_some_and(|o| o != me) {
  320. owner = self.free.wait(owner).unwrap_or_else(|e| e.into_inner());
  321. }
  322. *owner = (Some(me), owner.1 + 1);
  323. }
  324. let result = f();
  325. let mut owner = lock();
  326. owner.1 -= 1;
  327. if owner.1 == 0 {
  328. owner.0 = None;
  329. self.free.notify_one();
  330. }
  331. result
  332. }
  333. }
  334. #[cfg(all(test, windows))]
  335. mod tests {
  336. use std::sync::{Arc, Mutex};
  337. #[test]
  338. fn loader_lock_is_reentrant_and_exclusive() {
  339. let lock = Arc::new(super::LoaderLock::default());
  340. assert_eq!(lock.hold(|| lock.hold(|| 7)), 7);
  341. let order = Arc::new(Mutex::new(Vec::new()));
  342. let other = lock.hold(|| {
  343. let (theirs, their_order) = (lock.clone(), order.clone());
  344. let other = std::thread::spawn(move || {
  345. theirs.hold(|| their_order.lock().unwrap().push(2));
  346. });
  347. std::thread::sleep(std::time::Duration::from_millis(50));
  348. order.lock().unwrap().push(1);
  349. other
  350. });
  351. other.join().unwrap();
  352. assert_eq!(*order.lock().unwrap(), [1, 2]);
  353. }
  354. #[test]
  355. fn cpu_feature_check_matches_host() {
  356. let skip = std::env::var(super::SKIP_CPU_CHECK_ENV).ok();
  357. #[cfg(target_arch = "x86_64")]
  358. let expected_ok =
  359. std::arch::is_x86_feature_detected!("avx2") || skip.as_deref() == Some("1");
  360. #[cfg(not(target_arch = "x86_64"))]
  361. let expected_ok = true;
  362. assert_eq!(super::check_cpu_features().is_ok(), expected_ok);
  363. }
  364. }
  365. #[cfg(test)]
  366. mod cpu_check_tests {
  367. use super::{SKIP_CPU_CHECK_ENV, check_cpu_features_with};
  368. #[test]
  369. fn avx2_present_passes() {
  370. assert!(check_cpu_features_with(true, None).is_ok());
  371. assert!(check_cpu_features_with(true, Some("0")).is_ok());
  372. assert!(check_cpu_features_with(true, Some("1")).is_ok());
  373. }
  374. #[test]
  375. fn avx2_missing_fails_with_clear_error() {
  376. for skip in [None, Some(""), Some("0"), Some("true")] {
  377. let err = check_cpu_features_with(false, skip).unwrap_err();
  378. let msg = err.to_string();
  379. assert!(msg.contains("AVX2"), "unexpected error: {msg}");
  380. assert!(msg.contains("Xbox Series"), "unexpected error: {msg}");
  381. assert!(msg.contains(SKIP_CPU_CHECK_ENV), "unexpected error: {msg}");
  382. }
  383. }
  384. #[test]
  385. fn skip_env_var_bypasses_missing_avx2() {
  386. assert!(check_cpu_features_with(false, Some("1")).is_ok());
  387. }
  388. }
  389. #[cfg(not(windows))]
  390. pub fn run(_: &Path, _: Unimplemented, _: bool, _: bool, _: Console) -> Result<()> {
  391. anyhow::bail!("running titles requires Windows")
  392. }