Files
6gbvram---16gb-ram/crates/victory-hle/src/modules/lifecycle.rs
T

242 lines
7.2 KiB
Rust
Raw Normal View History

//! The title's life cycle. A console title is never told it is closing:
//! quitting it first suspends it (its suspend routines run, and it has a
//! second to save) and then ends the process. Closing the title's window
//! does the same here.
#![allow(non_snake_case)]
#![allow(clippy::not_unsafe_ptr_arg_deref)]
#![allow(clippy::too_many_arguments)]
use std::ffi::c_void;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Mutex, MutexGuard};
use std::time::Duration;
use windows_sys::Win32::Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, WPARAM};
use windows_sys::Win32::System::Threading::{GetCurrentProcess, TerminateProcess};
use windows_sys::Win32::UI::WindowsAndMessaging::{self as wm, HMENU};
use windows_sys::core::{PCSTR, PCWSTR, w};
use crate::{HleModule, hle_export};
type Routine = extern "system" fn(quiesced: u8, context: *mut c_void);
/// Registration id, routine and context of each suspend routine.
static ROUTINES: Mutex<Vec<(usize, Routine, usize)>> = Mutex::new(Vec::new());
fn routines() -> MutexGuard<'static, Vec<(usize, Routine, usize)>> {
ROUTINES.lock().unwrap_or_else(|e| e.into_inner())
}
/// How long the console lets suspend routines run before it ends the title.
const SUSPEND_DEADLINE: Duration = Duration::from_secs(1);
const ERROR_INVALID_PARAMETER: u32 = 87;
pub extern "system" fn RegisterAppStateChangeNotification(
routine: Option<Routine>,
context: *mut c_void,
registration: *mut usize,
) -> u32 {
let Some(routine) = routine else {
return ERROR_INVALID_PARAMETER;
};
if registration.is_null() {
return ERROR_INVALID_PARAMETER;
}
static NEXT: AtomicUsize = AtomicUsize::new(1);
let id = NEXT.fetch_add(1, Ordering::Relaxed);
routines().push((id, routine, context as usize));
// SAFETY: checked non-null; the title passes room for its registration.
unsafe { registration.write(id) };
0
}
pub extern "system" fn UnregisterAppStateChangeNotification(registration: usize) {
routines().retain(|&(id, ..)| id != registration);
}
/// The window procedure a title window had before ours.
const TITLE_PROC: PCWSTR = w!("victory.wndproc");
pub extern "system" fn CreateWindowExW(
ex_style: u32,
class: PCWSTR,
name: PCWSTR,
style: u32,
x: i32,
y: i32,
width: i32,
height: i32,
parent: HWND,
menu: HMENU,
instance: HINSTANCE,
param: *const c_void,
) -> HWND {
// SAFETY: the title's own arguments, forwarded.
let hwnd = unsafe {
wm::CreateWindowExW(
ex_style, class, name, style, x, y, width, height, parent, menu, instance, param,
)
};
hook(hwnd);
hwnd
}
/// See [`CreateWindowExW`].
pub extern "system" fn CreateWindowExA(
ex_style: u32,
class: PCSTR,
name: PCSTR,
style: u32,
x: i32,
y: i32,
width: i32,
height: i32,
parent: HWND,
menu: HMENU,
instance: HINSTANCE,
param: *const c_void,
) -> HWND {
// SAFETY: the title's own arguments, forwarded.
let hwnd = unsafe {
wm::CreateWindowExA(
ex_style, class, name, style, x, y, width, height, parent, menu, instance, param,
)
};
hook(hwnd);
hwnd
}
/// Puts our procedure in front of the title's.
fn hook(hwnd: HWND) {
if hwnd.is_null() {
return;
}
// SAFETY: a window this thread just created. The title's procedure is
// stored before ours can run.
unsafe {
let title = wm::GetWindowLongPtrW(hwnd, wm::GWLP_WNDPROC);
wm::SetPropW(hwnd, TITLE_PROC, title as *mut c_void);
wm::SetWindowLongPtrW(hwnd, wm::GWLP_WNDPROC, window_proc as *const () as isize);
}
}
extern "system" fn window_proc(
hwnd: HWND,
message: u32,
wparam: WPARAM,
lparam: LPARAM,
) -> LRESULT {
// A user close (close button, Alt+F4, window or taskbar menu); a
// console title never sees one, nor a WM_CLOSE from it.
if message == wm::WM_SYSCOMMAND && wparam & 0xFFF0 == wm::SC_CLOSE as usize {
quit();
return 0;
}
// SAFETY: the procedure `hook` stored, called the way the system would.
unsafe {
let title = wm::GetPropW(hwnd, TITLE_PROC);
if message == wm::WM_NCDESTROY {
wm::RemovePropW(hwnd, TITLE_PROC);
}
let title = std::mem::transmute::<*mut c_void, wm::WNDPROC>(title);
wm::CallWindowProcW(title, hwnd, message, wparam, lparam)
}
}
/// Suspends the title as the console would on quit, then ends the process.
fn quit() {
static QUITTING: AtomicBool = AtomicBool::new(false);
if QUITTING.swap(true, Ordering::Relaxed) {
return;
}
let suspend = routines().clone();
tracing::info!(routines = suspend.len(), "window closed: suspending the title");
// Not on the window thread: titles hand the suspend to that thread and
// wait for it inside the routine.
std::thread::spawn(move || {
for (_, routine, context) in suspend {
routine(1, context as *mut c_void);
}
tracing::info!("title suspended; ending it");
end();
});
std::thread::spawn(|| {
std::thread::sleep(SUSPEND_DEADLINE);
tracing::warn!("title did not finish suspending in time; ending it");
end();
});
}
fn end() {
// SAFETY: ends this process, as the console ends a suspended title.
unsafe { TerminateProcess(GetCurrentProcess(), 0) };
}
pub(crate) fn module() -> HleModule {
HleModule {
name: "lifecycle",
dlls: &[
"api-ms-win-core-psm-appnotify-*",
"ext-ms-win-rtcore-ntuser-window-*",
],
exports: vec![
hle_export!(RegisterAppStateChangeNotification),
hle_export!(UnregisterAppStateChangeNotification),
hle_export!(CreateWindowExW),
hle_export!(CreateWindowExA),
],
}
}
#[cfg(test)]
mod tests {
use super::*;
extern "system" fn noop(_: u8, _: *mut c_void) {}
#[test]
fn registrations_come_and_go() {
let (mut a, mut b) = (0, 0);
assert_eq!(
RegisterAppStateChangeNotification(Some(noop), std::ptr::null_mut(), &mut a),
0
);
assert_eq!(
RegisterAppStateChangeNotification(Some(noop), std::ptr::null_mut(), &mut b),
0
);
UnregisterAppStateChangeNotification(a);
let left: Vec<_> = routines().iter().map(|r| r.0).collect();
assert_eq!(left, [b]);
}
#[test]
fn hooked_windows_still_reach_the_title_procedure() {
let null = std::ptr::null_mut();
let hwnd = CreateWindowExW(
0,
w!("STATIC"),
w!("before"),
0,
0,
0,
10,
10,
null,
null,
null,
std::ptr::null(),
);
assert!(!hwnd.is_null());
let mut text = [0u16; 16];
// SAFETY: our window; the buffer holds 16 characters.
unsafe {
wm::SetWindowTextW(hwnd, w!("after"));
let n = wm::GetWindowTextW(hwnd, text.as_mut_ptr(), 16);
assert_eq!(String::from_utf16_lossy(&text[..n as usize]), "after");
assert!(!wm::GetPropW(hwnd, TITLE_PROC).is_null());
wm::DestroyWindow(hwnd);
}
}
}