From b358d9062d10e63fbd90bfbb08c4bac8b9ef0b30 Mon Sep 17 00:00:00 2001 From: andretuta Date: Tue, 24 Nov 2026 10:33:06 -0300 Subject: [PATCH] lifecycle: suspend callbacks on window close and fit the title window (split from #401) RegisterAppStateChangeNotification / UnregisterAppStateChangeNotification under api-ms-win-core-psm-appnotify-l1-1-0/-l1-1-1 and kernelbase.dll, and CreateWindowExW/A under user32.dll and ext-ms-win-rtcore-ntuser-window-l1-1-0/-l1-1-1, plus CreateWindowExA under ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0, the set the title's import table names. The title's first top-level window is fitted to the work area and hooked: SC_CLOSE runs the suspend callbacks (quiesced TRUE) and ends the run through the title's ExitProcess, with a 1 s deadline. Split from #401 (a02134a9c), as the maintainer asked for one topic per pull request. Co-Authored-By: Claude Opus 5.5 --- docs/runtime_imports.md | 10 ++ runtime/CMakeLists.txt | 16 ++ runtime/shims/lifecycle.cpp | 254 ++++++++++++++++++++++++++++++++ runtime/shims/lifecycle.h | 21 +++ runtime/test/lifecycle_test.cpp | 181 +++++++++++++++++++++++ scripts/build_runtime.ps1 | 4 +- 6 files changed, 484 insertions(+), 2 deletions(-) create mode 100644 runtime/shims/lifecycle.cpp create mode 100644 runtime/shims/lifecycle.h create mode 100644 runtime/test/lifecycle_test.cpp diff --git a/docs/runtime_imports.md b/docs/runtime_imports.md index 7b9f62d5a1..84e003dc02 100644 --- a/docs/runtime_imports.md +++ b/docs/runtime_imports.md @@ -64,6 +64,16 @@ Since the library-loader shims (`runtime/shims/library_loader.cpp`), a module's The process shim (`runtime/shims/process.cpp`) serves `ExitProcess` and `GetCommandLineA/W` the same way: through `kernel32`, `kernelbase`, and `api-ms-win-core-processthreads-l1-1-0` and `api-ms-win-core-processenvironment-l1-1-0`, the sets the API-set umbrella libraries (`OneCore_apiset.lib`, `mincore.lib`) bind them to. `vcomp140.dll` imports `ExitProcess` from the first of these. The UCRT's `_get_narrow_winmain_command_line` and `_get_wide_winmain_command_line` are served too, so a `WinMain` executable gets the game's command line as `lpCmdLine`. `abort()` raises `SIGABRT` when the guest installed a handler (the guest's `signal()` import binds to the host CRT, so its table is the one raised here); with the default or ignore disposition, or a handler that returns, the run still ends with code 3. `run_tiny_game_abort_exit_codes` compares that with a native run of the stand-in image. The table above is `gta6rt --dry-run` on each DLL at the commit that added this paragraph. +The lifecycle shim (`runtime/shims/lifecycle.cpp`) serves `RegisterAppStateChangeNotification` and +`UnregisterAppStateChangeNotification` under `api-ms-win-core-psm-appnotify-l1-1-0`, `-l1-1-1` and `kernelbase.dll`, and +`CreateWindowExW`/`CreateWindowExA` under `user32.dll` and the two `ext-ms-win-rtcore-ntuser-window-l1-1-*` sets, and +`CreateWindowExA` under `ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0`. The title's import table names +`RegisterAppStateChangeNotification` from `api-ms-win-core-psm-appnotify-l1-1-0` and `CreateWindowExA` from that ANSI +set (`tools/pe_inspect.py`). Only the title's first top-level window (no parent, not a child, not a tool window) is fitted to the work area and hooked: its +`SC_CLOSE` runs the registered suspend callbacks with `quiesced` TRUE under the registration lock, then the run ends +through the title's own `ExitProcess`, so the host finishes its cleanup. A 1 s deadline ends the run the same way if the +callbacks have not returned. + The shims added since account for the rest of the difference from the first version of the table. The UCRT's `_configure_narrow_argv`, `_configure_wide_argv`, `__p___argc`, `__p___wargv` and `abort` are served by `runtime/shims/process.cpp`, which is why almost every DLL gained one or two. The file-system calls listed in *Console paths and the write overlay* below (`CreateFile2`, `CopyFile2`, `CreateDirectoryW`, `FindFirstFileExW`, `SetFileAttributesW` and the rest) account for `msvcp140.dll`, `vcomp140.dll`, `Bink2Scarlett.dll`'s `CreateFile2` and part of the two HTTP clients. `winhttp.dll` is a module the shims own (*WinHTTP offline* below), so every `WinHttp*` import binds to it: 15 in `libHttpClient.GDK.dll` (all 16 but `WinHttpCrackUrl`) and 15 in `XCurl.dll` (all but `WinHttpQueryOption`). That is why the two HTTP clients moved the most: 11 to 26 and 9 to 24 shim imports. The UCRT argv configuration imports honor the executable's startup mode. Each run starts with `argc == 0` and diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 64e346f40a..65205113b3 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -125,6 +125,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) shims/xgameruntime_offline.cpp shims/library_loader.cpp shims/process.cpp + shims/lifecycle.cpp shims/com_shim.cpp shims/bcrypt_rng.cpp shims/xapu_chad.cpp @@ -293,6 +294,18 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) target_link_options(process_cmdline_test PRIVATE /OPT:NOREF) target_link_libraries(process_cmdline_test PRIVATE shell32) + # Console lifecycle shim: RegisterAppStateChangeNotification, oversized window fitting, and subclass forwarding. + add_executable(lifecycle_test + test/lifecycle_test.cpp + shims/lifecycle.cpp + shims/registry.cpp + ) + target_include_directories(lifecycle_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) + target_compile_definitions(lifecycle_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(lifecycle_test PRIVATE /W4 /permissive- /utf-8) + target_link_options(lifecycle_test PRIVATE /OPT:NOREF) + target_link_libraries(lifecycle_test PRIVATE user32) + # Console paths (GAME:) and the write overlay: the file shims resolved through the registry, over temporary folders. add_executable(file_system_test test/file_system_test.cpp @@ -1172,6 +1185,9 @@ if(BUILD_TESTING) if(WIN32 AND TARGET process_cmdline_test) add_test(NAME process_cmdline COMMAND process_cmdline_test) endif() + if(WIN32 AND TARGET lifecycle_test) + add_test(NAME lifecycle COMMAND lifecycle_test) + endif() if(WIN32 AND TARGET file_system_test) add_test(NAME file_system COMMAND file_system_test) endif() diff --git a/runtime/shims/lifecycle.cpp b/runtime/shims/lifecycle.cpp new file mode 100644 index 0000000000..0e28be82e2 --- /dev/null +++ b/runtime/shims/lifecycle.cpp @@ -0,0 +1,254 @@ +// lifecycle: console application lifecycle shims for mapped titles. +// +// Console titles never receive a normal desktop WM_CLOSE; quitting suspends the title (running its +// RegisterAppStateChangeNotification callbacks with quiesced = TRUE, giving it ~1 s to flush saves) and then ends the +// process. Additionally, console titles often size their top-level window to a 4K render target (3840x2160), which +// overflows smaller desktop work areas. +// +// This shim provides: +// - RegisterAppStateChangeNotification / UnregisterAppStateChangeNotification on api-ms-win-core-psm-appnotify-* +// and kernelbase.dll; +// - CreateWindowExW / CreateWindowExA on user32.dll and ext-ms-win-rtcore-ntuser-window-* (CreateWindowExA also on +// the -ansi- set), fitting the title's first top-level window into the primary monitor work area and +// subclassing it so SC_CLOSE runs registered suspend callbacks before the run ends. +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "lifecycle.h" +#include "shims.h" + +namespace rt::lifecycle { +namespace { + +using AppStateRoutine = void(WINAPI*)(BOOLEAN quiesced, PVOID context); + +struct Registration { + std::uintptr_t id; + AppStateRoutine routine; + void* context; +}; + +constexpr wchar_t kTitleProcProp[] = L"leonida.title.wndproc"; +constexpr auto kSuspendDeadline = std::chrono::seconds(1); + +// Recursive so a callback can unregister from inside run_suspend_callbacks() on the same thread. +std::recursive_mutex& reg_mutex() { + // Intentionally immortal so shutdown/WM_SYSCOMMAND cannot race static destruction. + static auto* m = new std::recursive_mutex; + return *m; +} + +std::vector& reg_list() { + static auto* list = new std::vector; + return *list; +} + +std::atomic g_next_reg_id{1}; +std::atomic g_ending{false}; +std::atomic g_title_window{nullptr}; + +// Ends the run through the title's own ExitProcess (process.cpp's game_exit_process -> end_run, which lets the host +// finish its cleanup), not TerminateProcess. Falls back to ExitProcess if the shim table has no binding. +[[noreturn]] void end_title_run() { + using ExitProcessFn = void(__stdcall*)(UINT); + if (auto* exit_process = reinterpret_cast(rt::shims::find("kernel32.dll", "ExitProcess"))) { + exit_process(0); + } + ExitProcess(0); +} + +// Runs every registration still in the list, with the registration lock held for the whole loop: an Unregister on +// another thread waits for the callback in flight, and one from inside a callback re-enters the recursive lock and +// stops the later calls of its id. Ids come from a snapshot and are looked up again, so an entry removed by an +// earlier callback is skipped. +// ponytail: a callback that blocks on another thread which is itself in Register/Unregister stalls until the 1 s +// deadline ends the run. +void run_suspend_callbacks() { + std::lock_guard lock(reg_mutex()); + std::vector ids; + for (const auto& r : reg_list()) ids.push_back(r.id); + for (const auto id : ids) { + AppStateRoutine routine = nullptr; + void* context = nullptr; + for (const auto& r : reg_list()) { + if (r.id == id) { + routine = r.routine; + context = r.context; + break; + } + } + if (routine) routine(TRUE, context); + } +} + +void trigger_suspend_and_exit() { + if (g_ending.exchange(true, std::memory_order_seq_cst)) return; + std::fprintf(stderr, "[rt] lifecycle: window closed; running %zu suspend routine(s)\n", + registered_notification_count()); + + // Run suspend callbacks off the UI thread so callbacks that synchronize with the window thread do not deadlock. + std::thread([]() { + run_suspend_callbacks(); + std::fprintf(stderr, "[rt] lifecycle: title suspended; exiting\n"); + end_title_run(); + }).detach(); + + std::thread([]() { + std::this_thread::sleep_for(kSuspendDeadline); + std::fprintf(stderr, "[rt] lifecycle: suspend deadline elapsed; exiting\n"); + end_title_run(); + }).detach(); +} + +LRESULT CALLBACK lifecycle_wnd_proc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { + if (message == WM_SYSCOMMAND && (wparam & 0xFFF0u) == SC_CLOSE) { + trigger_suspend_and_exit(); + return 0; + } + const HANDLE prop = GetPropW(hwnd, kTitleProcProp); + if (message == WM_NCDESTROY) { + RemovePropW(hwnd, kTitleProcProp); + HWND expected = hwnd; + g_title_window.compare_exchange_strong(expected, nullptr); // a later main window may be claimed + } + auto original = reinterpret_cast(prop); + if (!original) return DefWindowProcW(hwnd, message, wparam, lparam); + return CallWindowProcW(original, hwnd, message, wparam, lparam); +} + +void install_window_hook(HWND hwnd) { + if (!hwnd) return; + const LONG_PTR prev = GetWindowLongPtrW(hwnd, GWLP_WNDPROC); + if (!prev || reinterpret_cast(prev) == &lifecycle_wnd_proc) return; + SetPropW(hwnd, kTitleProcProp, reinterpret_cast(prev)); + SetWindowLongPtrW(hwnd, GWLP_WNDPROC, reinterpret_cast(&lifecycle_wnd_proc)); +} + +// Before CreateWindowEx: a candidate is a top-level, non-child, non-tool window. Returns whether it is one, and fits +// it only when it is the first candidate (no title window claimed yet). +bool prepare_title_window(HWND parent, DWORD style, DWORD ex_style, int& x, int& y, int& width, int& height) { + if (parent != nullptr || (style & WS_CHILD) || (ex_style & WS_EX_TOOLWINDOW)) return false; + if (g_title_window.load() != nullptr) return true; + RECT area{}; + if (!SystemParametersInfoW(SPI_GETWORKAREA, 0, &area, 0)) return true; + const auto [fitted_w, fitted_h] = fit_window_to_area(area, width, height); + if (fitted_w == width && fitted_h == height) return true; + std::fprintf(stderr, "[rt] lifecycle: fitted oversized title window %dx%d -> %dx%d\n", width, height, fitted_w, + fitted_h); + width = fitted_w; + height = fitted_h; + x = area.left + ((area.right - area.left) - width) / 2; + y = area.top + ((area.bottom - area.top) - height) / 2; + return true; +} + +// After CreateWindowEx: the first candidate to succeed claims the title window and gets the SC_CLOSE hook. +void adopt_title_window(HWND hwnd, bool candidate) { + if (!hwnd || !candidate) return; + HWND expected = nullptr; + if (g_title_window.compare_exchange_strong(expected, hwnd)) install_window_hook(hwnd); +} + +ULONG WINAPI register_app_state_change(AppStateRoutine routine, PVOID context, PVOID* registration) { + if (!routine || !registration) return ERROR_INVALID_PARAMETER; + const std::uintptr_t id = g_next_reg_id.fetch_add(1, std::memory_order_relaxed); + { + std::lock_guard lock(reg_mutex()); + reg_list().push_back({id, routine, context}); + } + *registration = reinterpret_cast(id); + return ERROR_SUCCESS; +} + +void WINAPI unregister_app_state_change(PVOID registration) { + const auto id = reinterpret_cast(registration); + std::lock_guard lock(reg_mutex()); + auto& list = reg_list(); + list.erase(std::remove_if(list.begin(), list.end(), [id](const Registration& r) { return r.id == id; }), + list.end()); +} + +HWND WINAPI create_window_ex_w_shim(DWORD ex_style, LPCWSTR class_name, LPCWSTR window_name, DWORD style, int x, int y, + int width, int height, HWND parent, HMENU menu, HINSTANCE instance, LPVOID param) { + const bool candidate = prepare_title_window(parent, style, ex_style, x, y, width, height); + const HWND hwnd = + ::CreateWindowExW(ex_style, class_name, window_name, style, x, y, width, height, parent, menu, instance, param); + adopt_title_window(hwnd, candidate); + return hwnd; +} + +HWND WINAPI create_window_ex_a_shim(DWORD ex_style, LPCSTR class_name, LPCSTR window_name, DWORD style, int x, int y, + int width, int height, HWND parent, HMENU menu, HINSTANCE instance, LPVOID param) { + const bool candidate = prepare_title_window(parent, style, ex_style, x, y, width, height); + const HWND hwnd = + ::CreateWindowExA(ex_style, class_name, window_name, style, x, y, width, height, parent, menu, instance, param); + adopt_title_window(hwnd, candidate); + return hwnd; +} + +} // namespace + +std::pair fit_window_to_area(const RECT& area, int width, int height) { + const int area_w = area.right - area.left; + const int area_h = area.bottom - area.top; + if (width <= 0 || height <= 0 || area_w <= 0 || area_h <= 0 || (width <= area_w && height <= area_h)) { + return {width, height}; + } + const double scale = + std::min(static_cast(area_w) / static_cast(width), + static_cast(area_h) / static_cast(height)); + return {static_cast(static_cast(width) * scale), + static_cast(static_cast(height) * scale)}; +} + +std::size_t registered_notification_count() { + std::lock_guard lock(reg_mutex()); + return reg_list().size(); +} + +void invoke_suspend_callbacks_for_test() { + run_suspend_callbacks(); +} + +} // namespace rt::lifecycle + +namespace { +using namespace rt::lifecycle; + +#define APP_NOTIFY_API(dll) \ + {dll, "RegisterAppStateChangeNotification", reinterpret_cast(®ister_app_state_change)}, \ + {dll, "UnregisterAppStateChangeNotification", reinterpret_cast(&unregister_app_state_change)} + +#define WINDOW_API(dll) \ + {dll, "CreateWindowExW", reinterpret_cast(&create_window_ex_w_shim)}, \ + {dll, "CreateWindowExA", reinterpret_cast(&create_window_ex_a_shim)} + +} // namespace + +SHIM_TABLE(lifecycle, + APP_NOTIFY_API("api-ms-win-core-psm-appnotify-l1-1-0.dll"), + APP_NOTIFY_API("api-ms-win-core-psm-appnotify-l1-1-1.dll"), + APP_NOTIFY_API("kernelbase.dll"), + WINDOW_API("user32.dll"), + WINDOW_API("ext-ms-win-rtcore-ntuser-window-l1-1-0.dll"), + WINDOW_API("ext-ms-win-rtcore-ntuser-window-l1-1-1.dll"), + // The title's import table names CreateWindowExA from the ANSI set. + {"ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0.dll", "CreateWindowExA", + reinterpret_cast(&create_window_ex_a_shim)}, +); diff --git a/runtime/shims/lifecycle.h b/runtime/shims/lifecycle.h new file mode 100644 index 0000000000..a3d775738f --- /dev/null +++ b/runtime/shims/lifecycle.h @@ -0,0 +1,21 @@ +// App lifecycle notifications (RegisterAppStateChangeNotification / UnregisterAppStateChangeNotification) and +// oversized top-level console window fitting + suspend-on-close hook (CreateWindowExA/W). +#pragma once + +#include + +#include +#include + +namespace rt::lifecycle { + +// Scales down (width, height) proportionally to fit inside `area`, leaving fitting sizes and CW_USEDEFAULT / <= 0 +// unchanged. +std::pair fit_window_to_area(const RECT& area, int width, int height); + +// For tests: number of currently registered app-state change callbacks, and synchronous suspend invocation +// (quiesced = TRUE) without terminating the process. +std::size_t registered_notification_count(); +void invoke_suspend_callbacks_for_test(); + +} // namespace rt::lifecycle diff --git a/runtime/test/lifecycle_test.cpp b/runtime/test/lifecycle_test.cpp new file mode 100644 index 0000000000..8f1f51dd97 --- /dev/null +++ b/runtime/test/lifecycle_test.cpp @@ -0,0 +1,181 @@ +// Checks the console lifecycle shim (runtime/shims/lifecycle.cpp): app-state change registrations, suspend +// callback delivery, oversized window fitting, and window subclass forwarding. +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif + +#include + +#include +#include + +#include "lifecycle.h" +#include "shims.h" + +namespace { + +int g_checks = 0; +int g_failures = 0; + +void check(bool condition, const char* what) { + ++g_checks; + std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); + if (!condition) ++g_failures; +} + +struct SuspendProbe { + int calls = 0; + BOOLEAN last_quiesced = FALSE; +}; + +void WINAPI on_app_state(BOOLEAN quiesced, PVOID context) { + auto* probe = static_cast(context); + if (probe) { + ++probe->calls; + probe->last_quiesced = quiesced; + } +} + +using UnregFn = void(WINAPI*)(PVOID); +UnregFn g_unreg = nullptr; + +// Context for a callback that unregisters `target` (another registration, or its own handle) when it runs. +struct UnregProbe { + int calls = 0; + PVOID target = nullptr; +}; + +void WINAPI on_app_state_unregister(BOOLEAN, PVOID context) { + auto* probe = static_cast(context); + ++probe->calls; + if (probe->target) g_unreg(probe->target); +} + +} // namespace + +int main() { + using RegFn = ULONG(WINAPI*)(void(WINAPI*)(BOOLEAN, PVOID), PVOID, PVOID*); + using CreateExWFn = HWND(WINAPI*)(DWORD, LPCWSTR, LPCWSTR, DWORD, int, int, int, int, HWND, HMENU, HINSTANCE, + LPVOID); + + const auto reg = reinterpret_cast( + rt::shims::find("api-ms-win-core-psm-appnotify-l1-1-0.dll", "RegisterAppStateChangeNotification")); + const auto unreg = reinterpret_cast( + rt::shims::find("api-ms-win-core-psm-appnotify-l1-1-0.dll", "UnregisterAppStateChangeNotification")); + const auto create_w = reinterpret_cast(rt::shims::find("user32.dll", "CreateWindowExW")); + const auto create_w_ext = + reinterpret_cast(rt::shims::find("ext-ms-win-rtcore-ntuser-window-l1-1-0.dll", "CreateWindowExW")); + + check(reg != nullptr && unreg != nullptr, "Register/UnregisterAppStateChangeNotification resolve"); + check(create_w != nullptr && create_w == create_w_ext, + "CreateWindowExW resolves through user32 and ext-ms-win-rtcore-ntuser-window"); + check(!rt::shims::owns_dll("user32.dll"), "user32.dll stays partially overridden"); + // The title imports CreateWindowExA from the ANSI window set, not from user32.dll. + const void* create_a = rt::shims::find("user32.dll", "CreateWindowExA"); + check(create_a != nullptr && + rt::shims::find("ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0.dll", "CreateWindowExA") == create_a, + "CreateWindowExA resolves through ext-ms-win-rtcore-ntuser-window-ansi to the same shim"); + if (!reg || !unreg || !create_w) return 1; + g_unreg = unreg; + + // 1. Parameter validation and registration / unregistration / suspend dispatch. + PVOID handle_a = nullptr, handle_b = nullptr; + check(reg(nullptr, nullptr, &handle_a) == ERROR_INVALID_PARAMETER, "null routine returns ERROR_INVALID_PARAMETER"); + check(reg(&on_app_state, nullptr, nullptr) == ERROR_INVALID_PARAMETER, + "null registration out pointer returns ERROR_INVALID_PARAMETER"); + + SuspendProbe probe_a{}, probe_b{}; + check(reg(&on_app_state, &probe_a, &handle_a) == ERROR_SUCCESS && handle_a != nullptr, "register callback A"); + check(reg(&on_app_state, &probe_b, &handle_b) == ERROR_SUCCESS && handle_b != nullptr && handle_b != handle_a, + "register callback B with distinct handle"); + check(rt::lifecycle::registered_notification_count() == 2, "two registrations active"); + + unreg(handle_a); + check(rt::lifecycle::registered_notification_count() == 1, "unregister removes callback A"); + + rt::lifecycle::invoke_suspend_callbacks_for_test(); + check(probe_a.calls == 0 && probe_b.calls == 1 && probe_b.last_quiesced == TRUE, + "suspend dispatch invokes only remaining callback with quiesced=TRUE"); + unreg(handle_b); + check(rt::lifecycle::registered_notification_count() == 0, "all registrations removed"); + + // 1b. A callback that unregisters a later registration: the later one is skipped during the same dispatch. + PVOID handle_later = nullptr, handle_first = nullptr; + SuspendProbe later_probe{}; + UnregProbe first_probe{}; + check(reg(&on_app_state_unregister, &first_probe, &handle_first) == ERROR_SUCCESS, + "register unregistering callback"); + check(reg(&on_app_state, &later_probe, &handle_later) == ERROR_SUCCESS, "register later callback"); + first_probe.target = handle_later; + rt::lifecycle::invoke_suspend_callbacks_for_test(); + check(first_probe.calls == 1 && later_probe.calls == 0, + "unregistered later callback does not run in the same dispatch"); + check(rt::lifecycle::registered_notification_count() == 1, "later registration is gone, the first remains"); + unreg(handle_first); + check(rt::lifecycle::registered_notification_count() == 0, "dispatch test registrations removed"); + + // 1c. A callback that unregisters itself: no deadlock, it runs once, and it is gone afterwards. + PVOID handle_self = nullptr; + UnregProbe self_probe{}; + check(reg(&on_app_state_unregister, &self_probe, &handle_self) == ERROR_SUCCESS, + "register self-unregistering callback"); + self_probe.target = handle_self; + rt::lifecycle::invoke_suspend_callbacks_for_test(); + check(self_probe.calls == 1 && rt::lifecycle::registered_notification_count() == 0, + "self-unregistering callback runs once and is removed without deadlock"); + rt::lifecycle::invoke_suspend_callbacks_for_test(); + check(self_probe.calls == 1, "removed self-unregistering callback is not called again"); + + // 2. Oversized window scaling math. + const RECT area{0, 0, 1920, 1040}; + const auto fitted_4k = rt::lifecycle::fit_window_to_area(area, 3840, 2160); + check(fitted_4k.first == 1848 && fitted_4k.second == 1040, + "3840x2160 scales proportionally to 1848x1040 inside 1920x1040 work area"); + const auto fitted_720 = rt::lifecycle::fit_window_to_area(area, 1280, 720); + check(fitted_720.first == 1280 && fitted_720.second == 720, "1280x720 stays unchanged"); + const auto fitted_def = rt::lifecycle::fit_window_to_area(area, CW_USEDEFAULT, 0); + check(fitted_def.first == CW_USEDEFAULT && fitted_def.second == 0, "CW_USEDEFAULT stays unchanged"); + + // 3. Subclassed window still forwards normal messages to its original window procedure. + const HWND hwnd = create_w(0, L"STATIC", L"before", 0, 0, 0, 16, 16, nullptr, nullptr, nullptr, nullptr); + check(hwnd != nullptr, "CreateWindowExW shim creates a live window"); + if (hwnd) { + SetWindowTextW(hwnd, L"after"); + wchar_t buf[16] = {}; + const int n = GetWindowTextW(hwnd, buf, 16); + check(n == 5 && std::wcscmp(buf, L"after") == 0, "subclassed window forwards WM_SETTEXT/WM_GETTEXT"); + check(GetPropW(hwnd, L"leonida.title.wndproc") != nullptr, "original WNDPROC property installed"); + DestroyWindow(hwnd); + } + + // 4. Only the title's first top-level window is hooked; a window is released when it is destroyed. Hidden windows + // only: no SC_CLOSE is posted. + const wchar_t* kHookProp = L"leonida.title.wndproc"; + WNDCLASSEXW wc{}; + wc.cbSize = sizeof(wc); + wc.lpfnWndProc = DefWindowProcW; + wc.hInstance = GetModuleHandleW(nullptr); + wc.lpszClassName = L"LeonidaLifecycleTest"; + RegisterClassExW(&wc); + const DWORD kMain = WS_OVERLAPPEDWINDOW; + const wchar_t* kClass = L"LeonidaLifecycleTest"; + HWND main_win = create_w(0, kClass, L"main", kMain, 0, 0, 64, 64, nullptr, nullptr, nullptr, nullptr); + check(main_win && GetPropW(main_win, kHookProp) != nullptr, "first parentless window is the hooked title window"); + HWND second = create_w(0, kClass, L"second", kMain, 0, 0, 64, 64, nullptr, nullptr, nullptr, nullptr); + check(second && GetPropW(second, kHookProp) == nullptr, "a second parentless window is not hooked"); + HWND tool = create_w(WS_EX_TOOLWINDOW, L"LeonidaLifecycleTest", L"tool", WS_POPUP, 0, 0, 64, 64, nullptr, nullptr, + nullptr, nullptr); + check(tool && GetPropW(tool, kHookProp) == nullptr, "a WS_EX_TOOLWINDOW window is not hooked"); + if (main_win) DestroyWindow(main_win); + HWND again = create_w(0, kClass, L"again", kMain, 0, 0, 64, 64, nullptr, nullptr, nullptr, nullptr); + check(again && GetPropW(again, kHookProp) != nullptr, "after the title window is destroyed, a new one is hooked"); + for (HWND w : {second, tool, again}) { + if (w) DestroyWindow(w); + } + + std::printf("%d check(s), %d failure(s)\n", g_checks, g_failures); + return g_failures ? 1 : 0; +} diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1 index 63acb7ce35..44dda01e3f 100644 --- a/scripts/build_runtime.ps1 +++ b/scripts/build_runtime.ps1 @@ -86,14 +86,14 @@ $build || exit /b 1 Write-Warning "CMake and Ninja weren't found (neither VS C++ CMake tools nor native PATH tools): building with cl.exe directly, without the GameInput shim (SDL3). Install CMake + Ninja or VS's CMake tools component to get it." $xtaskqueueDir = Join-Path $root "third_party\xtaskqueue" $xtaskqueueFiles = "Source\Task\TaskQueue.cpp", "Source\Task\AsyncLib.cpp", "Source\Task\ThreadPool_win32.cpp", "Source\Task\WaitTimer_win32.cpp" | ForEach-Object { "`"$xtaskqueueDir\$_`"" } - $files = "src\main.cpp", "src\host_cpu.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\xg_xs.cpp", "shims\acphal.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\xgameruntime_user.cpp", "shims\xgameruntime_gamesave.cpp", "shims\xgameruntime_store.cpp", "shims\xgameruntime_offline.cpp", "shims\winhttp_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp", "shims\com_shim.cpp", "shims\bcrypt_rng.cpp", "shims\xapu_chad.cpp", "shims\dstorage.cpp" | ForEach-Object { "`"$src\$_`"" } + $files = "src\main.cpp", "src\host_cpu.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\xg_xs.cpp", "shims\acphal.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\xgameruntime_user.cpp", "shims\xgameruntime_gamesave.cpp", "shims\xgameruntime_store.cpp", "shims\xgameruntime_offline.cpp", "shims\winhttp_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp", "shims\lifecycle.cpp", "shims\com_shim.cpp", "shims\bcrypt_rng.cpp", "shims\xapu_chad.cpp", "shims\dstorage.cpp" | ForEach-Object { "`"$src\$_`"" } $includes = "/I `"$src\src`" /I `"$src\shims`" /I `"$src\shims\xtaskqueue`" /I `"$xtaskqueueDir\Include`" /I `"$xtaskqueueDir\Source\Task`" /I `"$xtaskqueueDir\Source\Common`"" $opt = if ($Debug) { "/Od /MDd" } else { "/O2 /MD" } $body = @" cd /d "$out" || exit /b 1 rem BUILD-1457: a game thread with the default stack size gets this program's reserve, and drivers compile on it. The same number as in CMakeLists.txt. rem Keep the host base in step with runtime\CMakeLists.txt GTA6RT_HOST_BASE. -cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /Zi $opt /MP$jobs /DWIN32_LEAN_AND_MEAN /DNOMINMAX /DUNICODE /D_UNICODE $includes $($files -join ' ') $($xtaskqueueFiles -join ' ') /Fe:gta6rt.exe /link /OPT:NOREF /BASE:0x10000000000 /STACK:8388608 psapi.lib ole32.lib || exit /b 1 +cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /Zi $opt /MP$jobs /DWIN32_LEAN_AND_MEAN /DNOMINMAX /DUNICODE /D_UNICODE $includes $($files -join ' ') $($xtaskqueueFiles -join ' ') /Fe:gta6rt.exe /link /OPT:NOREF /BASE:0x10000000000 /STACK:8388608 psapi.lib ole32.lib user32.lib || exit /b 1 cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /MT /DWIN32_LEAN_AND_MEAN /DNOMINMAX "$src\src\tls_host.cpp" /LD /Fe:gta6rt_tls_host.dll || exit /b 1 cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\shims" "$src\shims\d3d12_xs_rootsig.cpp" "$src\shims\registry.cpp" "$src\shims\d3d12_xs.cpp" "$src\shims\d3d12_xs_device.cpp" "$src\test\root_sig_test.cpp" /Fe:root_sig_test.exe /link d3d12.lib || exit /b 1 cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I "$src\shims" "$src\shims\d3d12_xs_rootsig.cpp" "$src\shims\registry.cpp" "$src\shims\d3d12_xs.cpp" "$src\shims\d3d12_xs_device.cpp" "$src\test\device_proxy_test.cpp" /Fe:device_proxy_test.exe /link d3d12.lib dxgi.lib || exit /b 1