runtime.rs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. /// Each element of an XML text as its path from the root (`Game/TitleId`)
  109. /// and its trimmed text up to the first child, the predefined entities
  110. /// decoded; comments, CDATA sections, declarations and attributes are
  111. /// skipped.
  112. fn elements(text: &str) -> Vec<(String, String)> {
  113. let mut out = Vec::new();
  114. let mut path: Vec<&str> = Vec::new();
  115. let mut rest = text;
  116. while let Some(open) = rest.find('<') {
  117. rest = &rest[open..];
  118. let end = if rest.starts_with("<!--") {
  119. rest.find("-->").map(|e| e + 3)
  120. } else if rest.starts_with("<![CDATA[") {
  121. rest.find("]]>").map(|e| e + 3)
  122. } else {
  123. tag_end(rest)
  124. };
  125. let Some(end) = end else { break };
  126. let tag = &rest[1..end - 1];
  127. rest = &rest[end..];
  128. if tag.starts_with(['!', '?']) {
  129. continue;
  130. }
  131. if let Some(name) = tag.strip_prefix('/') {
  132. if let Some(at) = path.iter().rposition(|n| *n == name.trim()) {
  133. path.truncate(at);
  134. }
  135. continue;
  136. }
  137. let closed = tag.ends_with('/');
  138. let name = tag
  139. .trim_end_matches('/')
  140. .split_whitespace()
  141. .next()
  142. .unwrap_or("");
  143. path.push(name);
  144. let body = rest[..rest.find('<').unwrap_or(rest.len())].trim();
  145. let body = [("&lt;", "<"), ("&gt;", ">"), ("&quot;", "\""), ("&apos;", "'"), ("&amp;", "&")]
  146. .iter()
  147. .fold(body.to_owned(), |b, (entity, c)| b.replace(entity, c));
  148. out.push((path.join("/"), body));
  149. if closed {
  150. path.pop();
  151. }
  152. }
  153. out
  154. }
  155. /// Where the tag that starts `text` ends, past its `>`; a `>` in a quoted
  156. /// attribute value is part of the value (XML allows it there unescaped).
  157. fn tag_end(text: &str) -> Option<usize> {
  158. let mut quote = None;
  159. for (at, c) in text.char_indices() {
  160. match (quote, c) {
  161. (None, '"' | '\'') => quote = Some(c),
  162. (Some(open), _) if c == open => quote = None,
  163. (None, '>') => return Some(at + 1),
  164. _ => {}
  165. }
  166. }
  167. None
  168. }
  169. static TITLE: Mutex<Option<Title>> = Mutex::new(None);
  170. pub fn set_title(title: Title) {
  171. *TITLE.lock().unwrap_or_else(|e| e.into_inner()) = Some(title);
  172. }
  173. /// The running title; the default (id 0, no storage) until set.
  174. pub fn title() -> Title {
  175. TITLE
  176. .lock()
  177. .unwrap_or_else(|e| e.into_inner())
  178. .clone()
  179. .unwrap_or_default()
  180. }
  181. /// Gives the process the console's millisecond timers. Titles pace
  182. /// themselves with short waits (the title's audio mixer sleeps
  183. /// about 4 ms per 5.3 ms block) and cannot tune the timer on the console;
  184. /// a desktop process waits in 15.6 ms ticks unless it asks for finer ones,
  185. /// and Windows 11 drops that request while the window is hidden unless the
  186. /// process opts out. Process-wide, for the whole run.
  187. #[cfg(windows)]
  188. pub fn use_console_timers() {
  189. use windows_sys::Win32::Media::timeBeginPeriod;
  190. use windows_sys::Win32::System::Threading::{
  191. GetCurrentProcess, PROCESS_POWER_THROTTLING_CURRENT_VERSION,
  192. PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, PROCESS_POWER_THROTTLING_STATE,
  193. ProcessPowerThrottling, SetProcessInformation,
  194. };
  195. let keep = PROCESS_POWER_THROTTLING_STATE {
  196. Version: PROCESS_POWER_THROTTLING_CURRENT_VERSION,
  197. ControlMask: PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION,
  198. StateMask: 0,
  199. };
  200. // SAFETY: plain process settings; `keep` outlives the call.
  201. unsafe {
  202. SetProcessInformation(
  203. GetCurrentProcess(),
  204. ProcessPowerThrottling,
  205. (&raw const keep).cast(),
  206. size_of_val(&keep) as u32,
  207. );
  208. timeBeginPeriod(1);
  209. }
  210. }
  211. #[cfg(test)]
  212. mod tests {
  213. use super::*;
  214. #[test]
  215. fn a_quoted_angle_bracket_does_not_end_its_tag() {
  216. let text = "<Game><ShellVisuals DefaultDisplayName=\"A > B\" Description='x>y'/>\
  217. <TitleId>639AA8DD</TitleId>\
  218. <PersistentLocalStorage><SizeMB>64</SizeMB></PersistentLocalStorage></Game>";
  219. let t = Title::from_manifest(text);
  220. assert_eq!((t.id, t.storage_bytes), (0x639A_A8DD, 64 << 20));
  221. }
  222. #[test]
  223. fn reads_title_id_store_id_and_storage_quota() {
  224. let text = "\u{feff}<?xml version=\"1.0\"?>\n<Game configVersion=\"1\">\
  225. <!-- <TitleId>00000000</TitleId> -->\
  226. <Identity Name=\"x\"/>\n <TitleId>639AA8DD</TitleId>\n\
  227. <![CDATA[ <TitleId>1</TitleId> ]]> <StoreId>9&amp;C</StoreId><Other><SizeMB>7</SizeMB></Other>\
  228. <PersistentLocalStorage>\n <SizeMB>1024</SizeMB> <!-- c -->\n\
  229. </PersistentLocalStorage></Game>";
  230. let t = Title::from_manifest(text);
  231. assert_eq!((t.id, t.storage_bytes), (0x639A_A8DD, 1024 << 20));
  232. assert_eq!(t.store_id, "9&C");
  233. assert_eq!(Title::from_manifest("").storage_bytes, 0);
  234. }
  235. }