runtime.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. //! Process-wide state the implementations need.
  2. use std::path::{Path, PathBuf};
  3. use std::sync::Mutex;
  4. use std::sync::atomic::{AtomicUsize, Ordering};
  5. static MAIN_IMAGE_BASE: AtomicUsize = AtomicUsize::new(0);
  6. /// Records where the title's main image is mapped. The title expects
  7. /// `GetModuleHandle(NULL)` and friends to return this, not our own exe.
  8. pub fn set_main_image(base: usize) {
  9. MAIN_IMAGE_BASE.store(base, Ordering::Release);
  10. crate::image_watch::start(base);
  11. }
  12. pub fn main_image() -> Option<usize> {
  13. match MAIN_IMAGE_BASE.load(Ordering::Acquire) {
  14. 0 => None,
  15. base => Some(base),
  16. }
  17. }
  18. /// Original file of each title image we mapped, by base address.
  19. static IMAGE_PATHS: Mutex<Vec<(usize, PathBuf)>> = Mutex::new(Vec::new());
  20. /// Records the file a title image was mapped from: the title asks for its
  21. /// own path (`GetModuleFileName`) to find its data, and must not get our
  22. /// cache copy.
  23. pub fn set_image_path(base: usize, path: &Path) {
  24. let path = std::path::absolute(path).unwrap_or_else(|_| path.to_owned());
  25. let mut paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner());
  26. paths.retain(|(b, _)| *b != base);
  27. paths.push((base, path));
  28. }
  29. /// Forgets a title image that was unmapped again.
  30. pub fn forget_image(base: usize) {
  31. let mut paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner());
  32. paths.retain(|(b, _)| *b != base);
  33. }
  34. pub fn image_path(base: usize) -> Option<PathBuf> {
  35. let paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner());
  36. paths
  37. .iter()
  38. .find(|(b, _)| *b == base)
  39. .map(|(_, p)| p.clone())
  40. }
  41. /// The title image whose original file is called `file` (any case).
  42. pub fn image_named(file: &str) -> Option<usize> {
  43. let paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner());
  44. paths
  45. .iter()
  46. .find(|(_, p)| p.file_name().is_some_and(|n| n.eq_ignore_ascii_case(file)))
  47. .map(|(b, _)| *b)
  48. }
  49. static TITLE_ARGS: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
  50. /// The arguments the title's `main` gets (those after `--`). Set once, before
  51. /// the title starts; later calls are ignored.
  52. pub fn set_title_args(args: Vec<String>) {
  53. let _ = TITLE_ARGS.set(args);
  54. }
  55. pub fn title_args() -> &'static [String] {
  56. TITLE_ARGS.get().map_or(&[], Vec::as_slice)
  57. }
  58. /// Maps a title DLL the title loads itself (`LoadLibrary`) and returns its
  59. /// base; `Ok(None)` if `file` is not one of the title's DLLs.
  60. pub type TitleDllLoader = Box<dyn Fn(&str) -> Result<Option<usize>, String> + Send + Sync>;
  61. static TITLE_DLL_LOADER: std::sync::OnceLock<TitleDllLoader> = std::sync::OnceLock::new();
  62. /// Set once, by whoever mapped the title (it knows the folders and the
  63. /// resolver); later calls are ignored.
  64. pub fn set_title_dll_loader(loader: TitleDllLoader) {
  65. let _ = TITLE_DLL_LOADER.set(loader);
  66. }
  67. pub fn load_title_dll(file: &str) -> Result<Option<usize>, String> {
  68. TITLE_DLL_LOADER.get().map_or(Ok(None), |load| load(file))
  69. }
  70. /// What the title's manifest (`MicrosoftGame.config` beside its executable)
  71. /// says about it, and where its persistent local storage lives.
  72. #[derive(Debug, Clone, Default, PartialEq, Eq)]
  73. pub struct Title {
  74. pub id: u32,
  75. /// The store's product id (empty if the manifest has none).
  76. pub store_id: String,
  77. /// Persistent local storage: our folder for it and the title's quota.
  78. /// Game saves live beside it ([`Title::saves`]).
  79. pub storage: PathBuf,
  80. pub storage_bytes: u64,
  81. }
  82. impl Title {
  83. /// Id, store id and storage quota from the manifest (zero or empty
  84. /// where it has none); the storage folder is left for the caller.
  85. pub fn from_manifest(text: &str) -> Title {
  86. let elements = elements(text);
  87. let get = |path: &str| {
  88. elements
  89. .iter()
  90. .find(|(p, _)| p == path)
  91. .map(|(_, text)| text.as_str())
  92. };
  93. let id = get("Game/TitleId").and_then(|v| u32::from_str_radix(v, 16).ok());
  94. let storage_mb = get("Game/PersistentLocalStorage/SizeMB").and_then(|v| v.parse().ok());
  95. Title {
  96. id: id.unwrap_or(0),
  97. store_id: get("Game/StoreId").unwrap_or_default().to_owned(),
  98. storage: PathBuf::new(),
  99. storage_bytes: storage_mb.unwrap_or(0) << 20,
  100. }
  101. }
  102. /// Where game saves live: next to persistent local storage, under the
  103. /// data directory, never the cache.
  104. pub fn saves(&self) -> PathBuf {
  105. self.storage.with_file_name("saves")
  106. }
  107. }
  108. /// The trimmed text of one element: comments inside it are skipped, not
  109. /// treated as the end of its value. A manifest generator can write
  110. /// `<TitleId><!-- generated -->639AA8DD</TitleId>`, which must still give
  111. /// the title's id rather than an empty field.
  112. fn field_text(rest: &str) -> String {
  113. let mut out = String::new();
  114. let mut rest = rest;
  115. loop {
  116. let Some(open) = rest.find('<') else {
  117. out.push_str(rest);
  118. break;
  119. };
  120. out.push_str(&rest[..open]);
  121. if rest[open..].starts_with("<!--") {
  122. let Some(end) = rest[open..].find("-->") else {
  123. break;
  124. };
  125. rest = &rest[open + end + 3..];
  126. } else {
  127. // A child element, a closing tag or anything else ends the text.
  128. break;
  129. }
  130. }
  131. out.trim().to_owned()
  132. }
  133. /// Each element of an XML text as its path from the root (`Game/TitleId`)
  134. /// and its trimmed text up to the first child, the predefined entities
  135. /// decoded; comments, CDATA sections, declarations and attributes are
  136. /// skipped.
  137. fn elements(text: &str) -> Vec<(String, String)> {
  138. let mut out = Vec::new();
  139. let mut path: Vec<&str> = Vec::new();
  140. let mut rest = text;
  141. while let Some(open) = rest.find('<') {
  142. rest = &rest[open..];
  143. let end = if rest.starts_with("<!--") {
  144. rest.find("-->").map(|e| e + 3)
  145. } else if rest.starts_with("<![CDATA[") {
  146. rest.find("]]>").map(|e| e + 3)
  147. } else {
  148. tag_end(rest)
  149. };
  150. let Some(end) = end else { break };
  151. let tag = &rest[1..end - 1];
  152. rest = &rest[end..];
  153. if tag.starts_with(['!', '?']) {
  154. continue;
  155. }
  156. if let Some(name) = tag.strip_prefix('/') {
  157. if let Some(at) = path.iter().rposition(|n| *n == name.trim()) {
  158. path.truncate(at);
  159. }
  160. continue;
  161. }
  162. let closed = tag.ends_with('/');
  163. let name = tag
  164. .trim_end_matches('/')
  165. .split_whitespace()
  166. .next()
  167. .unwrap_or("");
  168. path.push(name);
  169. let body = field_text(rest);
  170. let body = [("&lt;", "<"), ("&gt;", ">"), ("&quot;", "\""), ("&apos;", "'"), ("&amp;", "&")]
  171. .iter()
  172. .fold(body, |b, (entity, c)| b.replace(entity, c));
  173. out.push((path.join("/"), body));
  174. if closed {
  175. path.pop();
  176. }
  177. }
  178. out
  179. }
  180. /// Where the tag that starts `text` ends, past its `>`; a `>` in a quoted
  181. /// attribute value is part of the value (XML allows it there unescaped).
  182. fn tag_end(text: &str) -> Option<usize> {
  183. let mut quote = None;
  184. for (at, c) in text.char_indices() {
  185. match (quote, c) {
  186. (None, '"' | '\'') => quote = Some(c),
  187. (Some(open), _) if c == open => quote = None,
  188. (None, '>') => return Some(at + 1),
  189. _ => {}
  190. }
  191. }
  192. None
  193. }
  194. static TITLE: Mutex<Option<Title>> = Mutex::new(None);
  195. pub fn set_title(title: Title) {
  196. *TITLE.lock().unwrap_or_else(|e| e.into_inner()) = Some(title);
  197. }
  198. /// The running title; the default (id 0, no storage) until set.
  199. pub fn title() -> Title {
  200. TITLE
  201. .lock()
  202. .unwrap_or_else(|e| e.into_inner())
  203. .clone()
  204. .unwrap_or_default()
  205. }
  206. /// Gives the process the console's millisecond timers. Titles pace
  207. /// themselves with short waits (the title's audio mixer sleeps
  208. /// about 4 ms per 5.3 ms block) and cannot tune the timer on the console;
  209. /// a desktop process waits in 15.6 ms ticks unless it asks for finer ones,
  210. /// and Windows 11 drops that request while the window is hidden unless the
  211. /// process opts out. Process-wide, for the whole run.
  212. #[cfg(windows)]
  213. pub fn use_console_timers() {
  214. use windows_sys::Win32::Media::timeBeginPeriod;
  215. use windows_sys::Win32::System::Threading::{
  216. GetCurrentProcess, PROCESS_POWER_THROTTLING_CURRENT_VERSION, PROCESS_POWER_THROTTLING_EXECUTION_SPEED,
  217. PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, PROCESS_POWER_THROTTLING_STATE,
  218. ProcessPowerThrottling, SetProcessInformation,
  219. };
  220. // Also: the system does not run this process at reduced speed (its
  221. // "efficiency mode": lower clock, the slow cores of a hybrid processor)
  222. // when its window is not the one in front, as while its owner works in
  223. // another window or streams. The console has eight cores alike and no
  224. // such mode. `VICTORY_EFFICIENCY_MODE=1` leaves the system its choice.
  225. let execution = if std::env::var_os("VICTORY_EFFICIENCY_MODE").is_some_and(|v| v == "1") {
  226. 0
  227. } else {
  228. PROCESS_POWER_THROTTLING_EXECUTION_SPEED
  229. };
  230. let keep = PROCESS_POWER_THROTTLING_STATE {
  231. Version: PROCESS_POWER_THROTTLING_CURRENT_VERSION,
  232. ControlMask: PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION | execution,
  233. StateMask: 0,
  234. };
  235. // SAFETY: plain process settings; `keep` outlives the call.
  236. unsafe {
  237. SetProcessInformation(
  238. GetCurrentProcess(),
  239. ProcessPowerThrottling,
  240. (&raw const keep).cast(),
  241. size_of_val(&keep) as u32,
  242. );
  243. timeBeginPeriod(1);
  244. }
  245. ahead_of_other_programs();
  246. }
  247. /// The title's streaming thread runs below normal priority (on the console
  248. /// nobody else wants its core) and does all of the title's loading: a
  249. /// program that keeps the processors busy at normal priority (a build, a
  250. /// virus scan) starved it, loading took 40 to 60 s instead of 28 to 33, and
  251. /// the opening ran without the models that were to be there (runs cpu-1,
  252. /// play-1125-0203). The process runs above normal, as long as it runs.
  253. /// `VICTORY_PROCESS_PRIORITY=normal`: as it was started.
  254. #[cfg(windows)]
  255. fn ahead_of_other_programs() {
  256. use windows_sys::Win32::System::Threading::{ABOVE_NORMAL_PRIORITY_CLASS, GetCurrentProcess, SetPriorityClass};
  257. if std::env::var_os("VICTORY_PROCESS_PRIORITY").is_some_and(|v| v == "normal" || v == "0") {
  258. return;
  259. }
  260. // SAFETY: a plain process setting.
  261. let set = unsafe { SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS) } != 0;
  262. tracing::info!(set, "the process runs above normal priority (VICTORY_PROCESS_PRIORITY=normal: not)");
  263. }
  264. #[cfg(test)]
  265. mod tests {
  266. use super::*;
  267. #[test]
  268. fn a_quoted_angle_bracket_does_not_end_its_tag() {
  269. let text = "<Game><ShellVisuals DefaultDisplayName=\"A > B\" Description='x>y'/>\
  270. <TitleId>639AA8DD</TitleId>\
  271. <PersistentLocalStorage><SizeMB>64</SizeMB></PersistentLocalStorage></Game>";
  272. let t = Title::from_manifest(text);
  273. assert_eq!((t.id, t.storage_bytes), (0x639A_A8DD, 64 << 20));
  274. }
  275. #[test]
  276. fn reads_title_id_store_id_and_storage_quota() {
  277. let text = "\u{feff}<?xml version=\"1.0\"?>\n<Game configVersion=\"1\">\
  278. <!-- <TitleId>00000000</TitleId> -->\
  279. <Identity Name=\"x\"/>\n <TitleId>639AA8DD</TitleId>\n\
  280. <![CDATA[ <TitleId>1</TitleId> ]]> <StoreId>9&amp;C</StoreId><Other><SizeMB>7</SizeMB></Other>\
  281. <PersistentLocalStorage>\n <SizeMB>1024</SizeMB> <!-- c -->\n\
  282. </PersistentLocalStorage></Game>";
  283. let t = Title::from_manifest(text);
  284. assert_eq!((t.id, t.storage_bytes), (0x639A_A8DD, 1024 << 20));
  285. assert_eq!(t.store_id, "9&C");
  286. assert_eq!(Title::from_manifest("").storage_bytes, 0);
  287. }
  288. #[test]
  289. fn inline_comments_do_not_truncate_a_field() {
  290. let text = "<Game>\
  291. <TitleId><!-- generated -->639AA8DD</TitleId>\
  292. <StoreId>9&amp;<!-- keep -->C</StoreId>\
  293. <PersistentLocalStorage><SizeMB><!-- n -->1024</SizeMB></PersistentLocalStorage>\
  294. </Game>";
  295. let t = Title::from_manifest(text);
  296. assert_eq!(t.id, 0x639A_A8DD);
  297. assert_eq!(t.store_id, "9&C");
  298. assert_eq!(t.storage_bytes, 1024 << 20);
  299. }
  300. }