Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions docs/runtime_imports.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 16 additions & 0 deletions runtime/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME)
shims/xbox_bvh_builder.cpp
shims/library_loader.cpp
shims/process.cpp
shims/lifecycle.cpp
shims/com_shim.cpp
shims/silent_audio.cpp
shims/bcrypt_rng.cpp
Expand Down Expand Up @@ -412,6 +413,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
Expand Down Expand Up @@ -1504,6 +1517,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()
Expand Down
254 changes: 254 additions & 0 deletions runtime/shims/lifecycle.cpp
Original file line number Diff line number Diff line change
@@ -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 <windows.h>

#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <cstdio>
#include <mutex>
#include <thread>
#include <utility>
#include <vector>

#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<Registration>& reg_list() {
static auto* list = new std::vector<Registration>;
return *list;
}

std::atomic<std::uintptr_t> g_next_reg_id{1};
std::atomic<bool> g_ending{false};
std::atomic<HWND> 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<ExitProcessFn>(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<std::uintptr_t> 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<WNDPROC>(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<WNDPROC>(prev) == &lifecycle_wnd_proc) return;
SetPropW(hwnd, kTitleProcProp, reinterpret_cast<HANDLE>(prev));
SetWindowLongPtrW(hwnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(&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<PVOID>(id);
return ERROR_SUCCESS;
}

void WINAPI unregister_app_state_change(PVOID registration) {
const auto id = reinterpret_cast<std::uintptr_t>(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<int, int> 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<double>(area_w) / static_cast<double>(width),
static_cast<double>(area_h) / static_cast<double>(height));
return {static_cast<int>(static_cast<double>(width) * scale),
static_cast<int>(static_cast<double>(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<void*>(&register_app_state_change)}, \
{dll, "UnregisterAppStateChangeNotification", reinterpret_cast<void*>(&unregister_app_state_change)}

#define WINDOW_API(dll) \
{dll, "CreateWindowExW", reinterpret_cast<void*>(&create_window_ex_w_shim)}, \
{dll, "CreateWindowExA", reinterpret_cast<void*>(&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<void*>(&create_window_ex_a_shim)},
);
21 changes: 21 additions & 0 deletions runtime/shims/lifecycle.h
Original file line number Diff line number Diff line change
@@ -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 <windows.h>

#include <cstddef>
#include <utility>

namespace rt::lifecycle {

// Scales down (width, height) proportionally to fit inside `area`, leaving fitting sizes and CW_USEDEFAULT / <= 0
// unchanged.
std::pair<int, int> 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
Loading
Loading