lifecycle.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. //! The title's life cycle. A console title is never told it is closing:
  2. //! quitting it or launching a new game first suspends it (its suspend
  3. //! routines run, and it has a second to save) and then ends the process.
  4. //! Closing the title's window does the same here; a new launch then starts
  5. //! `victory` again, which waits for this process to be gone.
  6. #![allow(non_snake_case)]
  7. #![allow(clippy::not_unsafe_ptr_arg_deref)]
  8. #![allow(clippy::too_many_arguments)]
  9. use std::ffi::c_void;
  10. use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
  11. use std::sync::{Mutex, MutexGuard};
  12. use std::time::Duration;
  13. use windows_sys::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, RECT, WPARAM};
  14. use windows_sys::Win32::System::Threading::{GetCurrentProcess, TerminateProcess};
  15. use windows_sys::Win32::UI::WindowsAndMessaging::{self as wm, HMENU};
  16. use windows_sys::core::{PCSTR, PCWSTR, w};
  17. use crate::{HleModule, hle_export};
  18. type Routine = extern "system" fn(quiesced: u8, context: *mut c_void);
  19. /// Registration id, routine and context of each suspend routine.
  20. static ROUTINES: Mutex<Vec<(usize, Routine, usize)>> = Mutex::new(Vec::new());
  21. fn routines() -> MutexGuard<'static, Vec<(usize, Routine, usize)>> {
  22. ROUTINES.lock().unwrap_or_else(|e| e.into_inner())
  23. }
  24. /// How long the console lets suspend routines run before it ends the title.
  25. const SUSPEND_DEADLINE: Duration = Duration::from_secs(1);
  26. const ERROR_INVALID_PARAMETER: u32 = 87;
  27. pub extern "system" fn RegisterAppStateChangeNotification(
  28. routine: Option<Routine>,
  29. context: *mut c_void,
  30. registration: *mut usize,
  31. ) -> u32 {
  32. let Some(routine) = routine else {
  33. return ERROR_INVALID_PARAMETER;
  34. };
  35. if registration.is_null() {
  36. return ERROR_INVALID_PARAMETER;
  37. }
  38. static NEXT: AtomicUsize = AtomicUsize::new(1);
  39. let id = NEXT.fetch_add(1, Ordering::Relaxed);
  40. routines().push((id, routine, context as usize));
  41. // SAFETY: checked non-null; the title passes room for its registration.
  42. unsafe { registration.write(id) };
  43. 0
  44. }
  45. pub extern "system" fn UnregisterAppStateChangeNotification(registration: usize) {
  46. routines().retain(|&(id, ..)| id != registration);
  47. }
  48. /// The window procedure a title window had before ours.
  49. const TITLE_PROC: PCWSTR = w!("victory.wndproc");
  50. pub extern "system" fn CreateWindowExW(
  51. ex_style: u32,
  52. class: PCWSTR,
  53. name: PCWSTR,
  54. style: u32,
  55. x: i32,
  56. y: i32,
  57. width: i32,
  58. height: i32,
  59. parent: HWND,
  60. menu: HMENU,
  61. instance: HINSTANCE,
  62. param: *const c_void,
  63. ) -> HWND {
  64. let (x, y, width, height) = fit(parent, x, y, width, height);
  65. // SAFETY: the title's own arguments, forwarded (the size fitted).
  66. let hwnd = unsafe {
  67. wm::CreateWindowExW(
  68. ex_style, class, name, style, x, y, width, height, parent, menu, instance, param,
  69. )
  70. };
  71. hook(hwnd);
  72. hwnd
  73. }
  74. /// See [`CreateWindowExW`].
  75. pub extern "system" fn CreateWindowExA(
  76. ex_style: u32,
  77. class: PCSTR,
  78. name: PCSTR,
  79. style: u32,
  80. x: i32,
  81. y: i32,
  82. width: i32,
  83. height: i32,
  84. parent: HWND,
  85. menu: HMENU,
  86. instance: HINSTANCE,
  87. param: *const c_void,
  88. ) -> HWND {
  89. let (x, y, width, height) = fit(parent, x, y, width, height);
  90. // SAFETY: the title's own arguments, forwarded (the size fitted).
  91. let hwnd = unsafe {
  92. wm::CreateWindowExA(
  93. ex_style, class, name, style, x, y, width, height, parent, menu, instance, param,
  94. )
  95. };
  96. hook(hwnd);
  97. hwnd
  98. }
  99. /// A console title sizes its window to its render target (Grand Theft
  100. /// Auto VI: 3840x2160 on a Series X), which can exceed the host's screen.
  101. /// A top-level window larger than the work area is shrunk to fit, keeping
  102. /// its proportions, and centred; what it shows is scaled to it (the swap
  103. /// chain stretches).
  104. fn fit(parent: HWND, x: i32, y: i32, width: i32, height: i32) -> (i32, i32, i32, i32) {
  105. let mut area = RECT::default();
  106. // SAFETY: `area` receives the primary monitor's work area.
  107. let known =
  108. unsafe { wm::SystemParametersInfoW(wm::SPI_GETWORKAREA, 0, (&raw mut area).cast(), 0) };
  109. let fitted = fit_into(&area, width, height);
  110. if !parent.is_null() || known == 0 || fitted == (width, height) {
  111. return (x, y, width, height);
  112. }
  113. tracing::info!(width, height, to = ?fitted, "title window fitted to the screen");
  114. let (w, h) = fitted;
  115. let left = area.left + (area.right - area.left - w) / 2;
  116. let top = area.top + (area.bottom - area.top - h) / 2;
  117. (left, top, w, h)
  118. }
  119. /// `width` x `height` scaled down to fit `area`, or unchanged if it fits
  120. /// (or is `CW_USEDEFAULT`).
  121. fn fit_into(area: &RECT, width: i32, height: i32) -> (i32, i32) {
  122. let (aw, ah) = (area.right - area.left, area.bottom - area.top);
  123. if width <= 0 || height <= 0 || aw <= 0 || ah <= 0 || (width <= aw && height <= ah) {
  124. return (width, height);
  125. }
  126. let scale = f64::min(
  127. f64::from(aw) / f64::from(width),
  128. f64::from(ah) / f64::from(height),
  129. );
  130. (
  131. (f64::from(width) * scale) as i32,
  132. (f64::from(height) * scale) as i32,
  133. )
  134. }
  135. /// Puts our procedure in front of the title's.
  136. fn hook(hwnd: HWND) {
  137. if hwnd.is_null() {
  138. return;
  139. }
  140. // SAFETY: a window this thread just created. The title's procedure is
  141. // stored before ours can run.
  142. unsafe {
  143. let title = wm::GetWindowLongPtrW(hwnd, wm::GWLP_WNDPROC);
  144. wm::SetPropW(hwnd, TITLE_PROC, title as *mut c_void);
  145. wm::SetWindowLongPtrW(hwnd, wm::GWLP_WNDPROC, window_proc as *const () as isize);
  146. }
  147. }
  148. extern "system" fn window_proc(
  149. hwnd: HWND,
  150. message: u32,
  151. wparam: WPARAM,
  152. lparam: LPARAM,
  153. ) -> LRESULT {
  154. // A user close (close button, Alt+F4, window or taskbar menu); a
  155. // console title never sees one, nor a WM_CLOSE from it.
  156. if message == wm::WM_SYSCOMMAND && wparam & 0xFFF0 == wm::SC_CLOSE as usize {
  157. end_title("window closed", Box::new(|| {}));
  158. return 0;
  159. }
  160. // SAFETY: the procedure `hook` stored, called the way the system would.
  161. unsafe {
  162. let title = wm::GetPropW(hwnd, TITLE_PROC);
  163. if message == wm::WM_NCDESTROY {
  164. wm::RemovePropW(hwnd, TITLE_PROC);
  165. }
  166. let title = std::mem::transmute::<*mut c_void, wm::WNDPROC>(title);
  167. wm::CallWindowProcW(title, hwnd, message, wparam, lparam)
  168. }
  169. }
  170. /// Suspends the title as the console does when it ends it, runs `then`
  171. /// (once), then ends the process. Returns at once; later calls do nothing.
  172. pub(crate) fn end_title(why: &'static str, then: Box<dyn FnOnce() + Send>) {
  173. static ENDING: AtomicBool = AtomicBool::new(false);
  174. if ENDING.swap(true, Ordering::SeqCst) {
  175. return;
  176. }
  177. let suspend = routines().clone();
  178. tracing::info!(routines = suspend.len(), "{why}: suspending the title");
  179. // Whoever comes first (the routines or the deadline) runs `then`; the
  180. // other waits for it, so the process never ends halfway through.
  181. let then = std::sync::Arc::new(Mutex::new(Some(then)));
  182. let finish = move |how: &str| {
  183. let mut then = then.lock().unwrap_or_else(|e| e.into_inner());
  184. tracing::info!("{how}; ending the title");
  185. if let Some(then) = then.take() {
  186. then();
  187. }
  188. end();
  189. };
  190. let late = finish.clone();
  191. // Not on the calling thread: titles hand the suspend to their window
  192. // thread and wait for it inside the routine.
  193. std::thread::spawn(move || {
  194. for (_, routine, context) in suspend {
  195. routine(1, context as *mut c_void);
  196. }
  197. finish("title suspended");
  198. });
  199. std::thread::spawn(move || {
  200. std::thread::sleep(SUSPEND_DEADLINE);
  201. late("title did not finish suspending in time");
  202. });
  203. }
  204. /// Set in the environment of a relaunched `victory`: an inherited handle
  205. /// of the process it replaces.
  206. const RELAUNCHED_FROM: &str = "VICTORY_RELAUNCHED_FROM";
  207. /// Starts `victory` again with `args` (after the title has suspended); the
  208. /// new process waits until this one has ended.
  209. pub(crate) fn relaunch(args: Vec<std::ffi::OsString>) {
  210. use windows_sys::Win32::Foundation::{DUPLICATE_SAME_ACCESS, DuplicateHandle, HANDLE};
  211. let mut me: HANDLE = std::ptr::null_mut();
  212. // SAFETY: an inheritable duplicate of our own process handle.
  213. let duplicated = unsafe {
  214. DuplicateHandle(
  215. GetCurrentProcess(),
  216. GetCurrentProcess(),
  217. GetCurrentProcess(),
  218. &mut me,
  219. 0,
  220. 1,
  221. DUPLICATE_SAME_ACCESS,
  222. )
  223. } != 0;
  224. let spawned = std::env::current_exe().and_then(|exe| {
  225. let mut command = std::process::Command::new(exe);
  226. command.args(&args);
  227. if duplicated {
  228. command.env(RELAUNCHED_FROM, (me as usize).to_string());
  229. }
  230. command.spawn()
  231. });
  232. match spawned {
  233. Ok(child) => tracing::info!(pid = child.id(), ?args, "relaunched"),
  234. Err(e) => tracing::warn!(%e, "relaunch failed; the title just ends"),
  235. }
  236. }
  237. /// In a relaunched `victory`: waits (30 s at most) for the process it
  238. /// replaces to be gone, so the two never share the title's files.
  239. pub fn wait_for_previous() {
  240. use windows_sys::Win32::Foundation::{CloseHandle, HANDLE};
  241. use windows_sys::Win32::System::Threading::WaitForSingleObject;
  242. let Some(handle) = std::env::var(RELAUNCHED_FROM)
  243. .ok()
  244. .and_then(|h| h.parse::<usize>().ok())
  245. else {
  246. return;
  247. };
  248. // SAFETY: removing our own variable before any other thread reads it.
  249. unsafe { std::env::remove_var(RELAUNCHED_FROM) };
  250. let handle = handle as HANDLE;
  251. // SAFETY: the inherited process handle the previous process gave us.
  252. unsafe {
  253. WaitForSingleObject(handle, 30_000);
  254. CloseHandle(handle);
  255. }
  256. }
  257. fn end() {
  258. // Compiled host pipelines kept for the next run.
  259. #[cfg(windows)]
  260. victory_gpu::pipeline::save_pipeline_cache();
  261. // SAFETY: ends this process, as the console ends a suspended title.
  262. unsafe { TerminateProcess(GetCurrentProcess(), 0) };
  263. }
  264. pub(crate) fn module() -> HleModule {
  265. HleModule {
  266. name: "lifecycle",
  267. dlls: &[
  268. "api-ms-win-core-psm-appnotify-*",
  269. "ext-ms-win-rtcore-ntuser-window-*",
  270. ],
  271. exports: vec![
  272. hle_export!(RegisterAppStateChangeNotification),
  273. hle_export!(UnregisterAppStateChangeNotification),
  274. hle_export!(CreateWindowExW),
  275. hle_export!(CreateWindowExA),
  276. ],
  277. }
  278. }
  279. #[cfg(test)]
  280. mod tests {
  281. use super::*;
  282. extern "system" fn noop(_: u8, _: *mut c_void) {}
  283. #[test]
  284. fn registrations_come_and_go() {
  285. let (mut a, mut b) = (0, 0);
  286. assert_eq!(
  287. RegisterAppStateChangeNotification(Some(noop), std::ptr::null_mut(), &mut a),
  288. 0
  289. );
  290. assert_eq!(
  291. RegisterAppStateChangeNotification(Some(noop), std::ptr::null_mut(), &mut b),
  292. 0
  293. );
  294. UnregisterAppStateChangeNotification(a);
  295. let left: Vec<_> = routines().iter().map(|r| r.0).collect();
  296. assert_eq!(left, [b]);
  297. }
  298. #[test]
  299. fn oversized_windows_shrink_to_the_screen() {
  300. let area = RECT {
  301. left: 0,
  302. top: 0,
  303. right: 1920,
  304. bottom: 1040,
  305. };
  306. assert_eq!(fit_into(&area, 3840, 2160), (1848, 1040));
  307. assert_eq!(fit_into(&area, 1280, 720), (1280, 720));
  308. assert_eq!(
  309. fit_into(&area, wm::CW_USEDEFAULT, 0),
  310. (wm::CW_USEDEFAULT, 0)
  311. );
  312. }
  313. #[test]
  314. fn hooked_windows_still_reach_the_title_procedure() {
  315. let null = std::ptr::null_mut();
  316. let hwnd = CreateWindowExW(
  317. 0,
  318. w!("STATIC"),
  319. w!("before"),
  320. 0,
  321. 0,
  322. 0,
  323. 10,
  324. 10,
  325. null,
  326. null,
  327. null,
  328. std::ptr::null(),
  329. );
  330. assert!(!hwnd.is_null());
  331. let mut text = [0u16; 16];
  332. // SAFETY: our window; the buffer holds 16 characters.
  333. unsafe {
  334. wm::SetWindowTextW(hwnd, w!("after"));
  335. let n = wm::GetWindowTextW(hwnd, text.as_mut_ptr(), 16);
  336. assert_eq!(String::from_utf16_lossy(&text[..n as usize]), "after");
  337. assert!(!wm::GetPropW(hwnd, TITLE_PROC).is_null());
  338. wm::DestroyWindow(hwnd);
  339. }
  340. }
  341. }