runtime.rs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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. }
  11. pub fn main_image() -> Option<usize> {
  12. match MAIN_IMAGE_BASE.load(Ordering::Acquire) {
  13. 0 => None,
  14. base => Some(base),
  15. }
  16. }
  17. /// Original file of each title image we mapped, by base address.
  18. static IMAGE_PATHS: Mutex<Vec<(usize, PathBuf)>> = Mutex::new(Vec::new());
  19. /// Records the file a title image was mapped from: the title asks for its
  20. /// own path (`GetModuleFileName`) to find its data, and must not get our
  21. /// cache copy.
  22. pub fn set_image_path(base: usize, path: &Path) {
  23. let path = std::path::absolute(path).unwrap_or_else(|_| path.to_owned());
  24. let mut paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner());
  25. paths.retain(|(b, _)| *b != base);
  26. paths.push((base, path));
  27. }
  28. /// Forgets a title image that was unmapped again.
  29. pub fn forget_image(base: usize) {
  30. let mut paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner());
  31. paths.retain(|(b, _)| *b != base);
  32. }
  33. pub fn image_path(base: usize) -> Option<PathBuf> {
  34. let paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner());
  35. paths
  36. .iter()
  37. .find(|(b, _)| *b == base)
  38. .map(|(_, p)| p.clone())
  39. }
  40. /// The title image whose original file is called `file` (any case).
  41. pub fn image_named(file: &str) -> Option<usize> {
  42. let paths = IMAGE_PATHS.lock().unwrap_or_else(|e| e.into_inner());
  43. paths
  44. .iter()
  45. .find(|(_, p)| p.file_name().is_some_and(|n| n.eq_ignore_ascii_case(file)))
  46. .map(|(b, _)| *b)
  47. }
  48. /// Maps a title DLL the title loads itself (`LoadLibrary`) and returns its
  49. /// base; `Ok(None)` if `file` is not one of the title's DLLs.
  50. pub type TitleDllLoader = Box<dyn Fn(&str) -> Result<Option<usize>, String> + Send + Sync>;
  51. static TITLE_DLL_LOADER: std::sync::OnceLock<TitleDllLoader> = std::sync::OnceLock::new();
  52. /// Set once, by whoever mapped the title (it knows the folders and the
  53. /// resolver); later calls are ignored.
  54. pub fn set_title_dll_loader(loader: TitleDllLoader) {
  55. let _ = TITLE_DLL_LOADER.set(loader);
  56. }
  57. pub fn load_title_dll(file: &str) -> Result<Option<usize>, String> {
  58. TITLE_DLL_LOADER.get().map_or(Ok(None), |load| load(file))
  59. }
  60. /// What the title's manifest (`MicrosoftGame.config` beside its executable)
  61. /// says about it, and where its persistent local storage lives.
  62. #[derive(Debug, Clone, Default, PartialEq, Eq)]
  63. pub struct Title {
  64. pub id: u32,
  65. /// The store's product id (empty if the manifest has none).
  66. pub store_id: String,
  67. /// Persistent local storage: our folder for it and the title's quota.
  68. /// Game saves live beside it ([`Title::saves`]).
  69. pub storage: PathBuf,
  70. pub storage_bytes: u64,
  71. }
  72. impl Title {
  73. /// Id, store id and storage quota from the manifest (zero or empty
  74. /// where it has none); the storage folder is left for the caller.
  75. pub fn from_manifest(text: &str) -> Title {
  76. let elements = elements(text);
  77. let get = |path: &str| {
  78. elements
  79. .iter()
  80. .find(|(p, _)| p == path)
  81. .map(|(_, text)| text.as_str())
  82. };
  83. let id = get("Game/TitleId").and_then(|v| u32::from_str_radix(v, 16).ok());
  84. let storage_mb = get("Game/PersistentLocalStorage/SizeMB").and_then(|v| v.parse().ok());
  85. Title {
  86. id: id.unwrap_or(0),
  87. store_id: get("Game/StoreId").unwrap_or_default().to_owned(),
  88. storage: PathBuf::new(),
  89. storage_bytes: storage_mb.unwrap_or(0) << 20,
  90. }
  91. }
  92. /// Where game saves live: next to persistent local storage, under the
  93. /// data directory, never the cache.
  94. pub fn saves(&self) -> PathBuf {
  95. self.storage.with_file_name("saves")
  96. }
  97. }
  98. /// Each element of an XML text as its path from the root (`Game/TitleId`)
  99. /// and its trimmed text up to the first child, the predefined entities
  100. /// decoded; comments, CDATA sections, declarations and attributes are
  101. /// skipped.
  102. fn elements(text: &str) -> Vec<(String, String)> {
  103. let mut out = Vec::new();
  104. let mut path: Vec<&str> = Vec::new();
  105. let mut rest = text;
  106. while let Some(open) = rest.find('<') {
  107. rest = &rest[open..];
  108. let end = if rest.starts_with("<!--") {
  109. rest.find("-->").map(|e| e + 3)
  110. } else if rest.starts_with("<![CDATA[") {
  111. rest.find("]]>").map(|e| e + 3)
  112. } else {
  113. rest.find('>').map(|e| e + 1)
  114. };
  115. let Some(end) = end else { break };
  116. let tag = &rest[1..end - 1];
  117. rest = &rest[end..];
  118. if tag.starts_with(['!', '?']) {
  119. continue;
  120. }
  121. if let Some(name) = tag.strip_prefix('/') {
  122. if let Some(at) = path.iter().rposition(|n| *n == name.trim()) {
  123. path.truncate(at);
  124. }
  125. continue;
  126. }
  127. let closed = tag.ends_with('/');
  128. let name = tag
  129. .trim_end_matches('/')
  130. .split_whitespace()
  131. .next()
  132. .unwrap_or("");
  133. path.push(name);
  134. let body = rest[..rest.find('<').unwrap_or(rest.len())].trim();
  135. let body = [("&lt;", "<"), ("&gt;", ">"), ("&quot;", "\""), ("&apos;", "'"), ("&amp;", "&")]
  136. .iter()
  137. .fold(body.to_owned(), |b, (entity, c)| b.replace(entity, c));
  138. out.push((path.join("/"), body));
  139. if closed {
  140. path.pop();
  141. }
  142. }
  143. out
  144. }
  145. static TITLE: Mutex<Option<Title>> = Mutex::new(None);
  146. pub fn set_title(title: Title) {
  147. *TITLE.lock().unwrap_or_else(|e| e.into_inner()) = Some(title);
  148. }
  149. /// The running title; the default (id 0, no storage) until set.
  150. pub fn title() -> Title {
  151. TITLE
  152. .lock()
  153. .unwrap_or_else(|e| e.into_inner())
  154. .clone()
  155. .unwrap_or_default()
  156. }
  157. /// Gives the process the console's millisecond timers. Titles pace
  158. /// themselves with short waits (Grand Theft Auto VI's audio mixer sleeps
  159. /// about 4 ms per 5.3 ms block) and cannot tune the timer on the console;
  160. /// a desktop process waits in 15.6 ms ticks unless it asks for finer ones,
  161. /// and Windows 11 drops that request while the window is hidden unless the
  162. /// process opts out. Process-wide, for the whole run.
  163. #[cfg(windows)]
  164. pub fn use_console_timers() {
  165. use windows_sys::Win32::Media::timeBeginPeriod;
  166. use windows_sys::Win32::System::Threading::{
  167. GetCurrentProcess, PROCESS_POWER_THROTTLING_CURRENT_VERSION,
  168. PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION, PROCESS_POWER_THROTTLING_STATE,
  169. ProcessPowerThrottling, SetProcessInformation,
  170. };
  171. let keep = PROCESS_POWER_THROTTLING_STATE {
  172. Version: PROCESS_POWER_THROTTLING_CURRENT_VERSION,
  173. ControlMask: PROCESS_POWER_THROTTLING_IGNORE_TIMER_RESOLUTION,
  174. StateMask: 0,
  175. };
  176. // SAFETY: plain process settings; `keep` outlives the call.
  177. unsafe {
  178. SetProcessInformation(
  179. GetCurrentProcess(),
  180. ProcessPowerThrottling,
  181. (&raw const keep).cast(),
  182. size_of_val(&keep) as u32,
  183. );
  184. timeBeginPeriod(1);
  185. }
  186. }
  187. #[cfg(test)]
  188. mod tests {
  189. use super::*;
  190. #[test]
  191. fn reads_title_id_store_id_and_storage_quota() {
  192. let text = "\u{feff}<?xml version=\"1.0\"?>\n<Game configVersion=\"1\">\
  193. <!-- <TitleId>00000000</TitleId> -->\
  194. <Identity Name=\"x\"/>\n <TitleId>639AA8DD</TitleId>\n\
  195. <![CDATA[ <TitleId>1</TitleId> ]]> <StoreId>9&amp;C</StoreId><Other><SizeMB>7</SizeMB></Other>\
  196. <PersistentLocalStorage>\n <SizeMB>1024</SizeMB> <!-- c -->\n\
  197. </PersistentLocalStorage></Game>";
  198. let t = Title::from_manifest(text);
  199. assert_eq!((t.id, t.storage_bytes), (0x639A_A8DD, 1024 << 20));
  200. assert_eq!(t.store_id, "9&C");
  201. assert_eq!(Title::from_manifest("").storage_bytes, 0);
  202. }
  203. }