diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index b9c726f6f3..b010f11111 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -250,6 +250,7 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) shims/xapu_queue.cpp shims/xapu_chad.cpp shims/dstorage.cpp + shims/appnotify.cpp ) # These sources use __try to handle access violations. MSVC always catches them; clang-cl needs asynchronous # exceptions (as for tiny_dll below). A source file property also applies to dstorage_test. @@ -632,6 +633,17 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) target_compile_options(console_registry_test PRIVATE /W4 /permissive- /utf-8) target_link_options(console_registry_test PRIVATE /OPT:NOREF) + # PSM app-notification and WER file registration shims, driven through rt::shims::find. + add_executable(appnotify_test + test/appnotify_test.cpp + shims/appnotify.cpp + shims/registry.cpp + ) + target_include_directories(appnotify_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) + target_compile_definitions(appnotify_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(appnotify_test PRIVATE /W4 /permissive- /utf-8) + target_link_options(appnotify_test PRIVATE /OPT:NOREF) + # Synthetic tests for the atomic API reference lifecycle. add_executable(api_ref_state_test test/api_ref_state_test.cpp) target_include_directories(api_ref_state_test PRIVATE @@ -1732,6 +1744,9 @@ if(BUILD_TESTING) if(WIN32 AND TARGET console_registry_test) add_test(NAME console_registry COMMAND console_registry_test) endif() + if(WIN32 AND TARGET appnotify_test) + add_test(NAME appnotify COMMAND appnotify_test) + endif() if(WIN32 AND TARGET api_ref_state_test) add_test(NAME api_ref_state COMMAND api_ref_state_test) set_tests_properties(api_ref_state PROPERTIES TIMEOUT 30) diff --git a/runtime/shims/appnotify.cpp b/runtime/shims/appnotify.cpp new file mode 100644 index 0000000000..a32c37fe93 --- /dev/null +++ b/runtime/shims/appnotify.cpp @@ -0,0 +1,236 @@ +// PSM constrained-notification and Windows Error Reporting registration shims. +// +// Xbox GDK / UWP-linked titles import RegisterAppConstrainedChangeNotification / +// UnregisterAppConstrainedChangeNotification (api-ms-win-core-psm-appnotify-l1-1-0/1) to track constrained +// transitions, and WerRegisterFile / WerUnregisterFile (api-ms-win-core-windowserrorreporting-l1-1-0/1) to attach +// logs/dumps. (RegisterAppStateChangeNotification / UnregisterAppStateChangeNotification live in lifecycle.cpp via +// #769 so callbacks fire cleanly on suspend/close without duplicate SHIM_TABLE entries.) +// On an unpackaged desktop Win32 host (gta6rt): +// - RegisterAppConstrainedChangeNotification returns ERROR_SUCCESS without writing *Registration, leaving caller +// stack state uninitialized or null; +// - UnregisterAppConstrainedChangeNotification(nullptr) or foreign handles must not fault; +// - host WerRegisterFile registers paths into gta6rt's own WER block and has no console drive mapping for GAME:/G:/T:. +// +// Each registration returns a distinct tracked handle in-process, never touches freed or foreign handles on unregister, +// and normalizes console/host WER paths offline without writing to disk or mutating host WER state. +#include + +#include +#include +#include +#include +#include + +#include "shims.h" + +namespace rt::appnotify { +namespace { + +using NotifyCallback = void(WINAPI*)(BOOLEAN state, PVOID context); + +struct Registration { + NotifyCallback callback; + void* context; + Registration* next; +}; + +struct WerEntry { + std::wstring key; + int file_type; + DWORD flags; + WerEntry* next; +}; + +// Constant-initialized synchronization and raw linked lists avoid MSVC function-local static TLS init guards +// (_Init_thread_header) and C++ destructor ordering hazards during ExitProcess teardown. +SRWLOCK g_lock = SRWLOCK_INIT; +Registration* g_registrations = nullptr; +WerEntry* g_wer_entries = nullptr; + +DWORD WINAPI register_app_constrained(NotifyCallback callback, PVOID context, PVOID* registration) { + if (!registration) return ERROR_INVALID_PARAMETER; + *registration = nullptr; + if (!callback) return ERROR_INVALID_PARAMETER; + + auto* entry = new (std::nothrow) Registration{callback, context, nullptr}; + if (!entry) return ERROR_OUTOFMEMORY; + + AcquireSRWLockExclusive(&g_lock); + entry->next = g_registrations; + g_registrations = entry; + ReleaseSRWLockExclusive(&g_lock); + + *registration = entry; + return ERROR_SUCCESS; +} + +void WINAPI unregister_app_constrained(PVOID registration) { + if (!registration) return; + + Registration* removed = nullptr; + AcquireSRWLockExclusive(&g_lock); + Registration** cur = &g_registrations; + while (*cur) { + if (*cur == registration) { + removed = *cur; + *cur = removed->next; + break; + } + cur = &((*cur)->next); + } + ReleaseSRWLockExclusive(&g_lock); + delete removed; +} + +bool ascii_iequals(wchar_t a, wchar_t b) { + if (a >= L'A' && a <= L'Z') a = static_cast(a + 32); + if (b >= L'A' && b <= L'Z') b = static_cast(b + 32); + return a == b; +} + +// Normalizes a WER file path for in-process tracking and rejects ".." segments that climb above GAME:, G:, or T:. +bool normalize_wer_key(PCWSTR raw_path, std::wstring& out_key, HRESULT& out_error) { + out_error = S_OK; + if (!raw_path) { + out_error = E_INVALIDARG; + return false; + } + + std::wstring path(raw_path); + size_t console_prefix = 0; + std::wstring drive_tag; + if (path.size() >= 5 && ascii_iequals(path[0], L'g') && ascii_iequals(path[1], L'a') && + ascii_iequals(path[2], L'm') && ascii_iequals(path[3], L'e') && path[4] == L':') { + console_prefix = 5; + drive_tag = L"game:"; + } else if (path.size() >= 2 && (ascii_iequals(path[0], L'g') || ascii_iequals(path[0], L't')) && path[1] == L':') { + console_prefix = 2; + drive_tag = ascii_iequals(path[0], L'g') ? L"g:" : L"t:"; + } + + if (console_prefix != 0) { + size_t pos = console_prefix; + if (pos < path.size() && (path[pos] == L'\\' || path[pos] == L'/')) ++pos; + size_t depth = 0; + std::wstring normalized = drive_tag + L"\\"; + bool first_part = true; + while (pos <= path.size()) { + size_t next = path.find_first_of(L"\\/", pos); + if (next == std::wstring::npos) next = path.size(); + const std::wstring seg = path.substr(pos, next - pos); + if (seg == L"..") { + if (depth == 0) { + out_error = HRESULT_FROM_WIN32(ERROR_INVALID_NAME); + return false; + } + --depth; + const size_t slash = normalized.find_last_of(L'\\'); + if (slash == drive_tag.size()) { + normalized.erase(slash + 1); + first_part = true; + } else if (slash != std::wstring::npos && slash > drive_tag.size()) { + normalized.erase(slash); + } + } else if (!seg.empty() && seg != L".") { + if (!first_part) normalized += L'\\'; + first_part = false; + normalized += seg; + ++depth; + } + if (next == path.size()) break; + pos = next + 1; + } + out_key = normalized; + return true; + } + + for (wchar_t& c : path) { + if (c == L'/') c = L'\\'; + } + out_key = path; + return true; +} + +constexpr int kWerRegFileTypeUserDocument = 1; +constexpr int kWerRegFileTypeOther = 2; +constexpr DWORD kWerKnownFlagsMask = 0x3u; // WER_FILE_DELETE_WHEN_DONE (1) | WER_FILE_ANONYMOUS_DATA (2) + +HRESULT WINAPI wer_register_file(PCWSTR file, int reg_file_type, DWORD flags) { + if (!file || (reg_file_type != kWerRegFileTypeUserDocument && reg_file_type != kWerRegFileTypeOther) || + (flags & ~kWerKnownFlagsMask) != 0) { + return E_INVALIDARG; + } + + std::wstring key; + HRESULT parse_hr = S_OK; + if (!normalize_wer_key(file, key, parse_hr)) return parse_hr; + + AcquireSRWLockExclusive(&g_lock); + for (WerEntry* cur = g_wer_entries; cur; cur = cur->next) { + if (_wcsicmp(cur->key.c_str(), key.c_str()) == 0) { + cur->file_type = reg_file_type; + cur->flags = flags; + ReleaseSRWLockExclusive(&g_lock); + return S_OK; + } + } + auto* entry = new (std::nothrow) WerEntry{key, reg_file_type, flags, g_wer_entries}; + if (!entry) { + ReleaseSRWLockExclusive(&g_lock); + return E_OUTOFMEMORY; + } + g_wer_entries = entry; + ReleaseSRWLockExclusive(&g_lock); + return S_OK; +} + +HRESULT WINAPI wer_unregister_file(PCWSTR file) { + std::wstring key; + HRESULT parse_hr = S_OK; + if (!normalize_wer_key(file, key, parse_hr)) return parse_hr; + + WerEntry* removed = nullptr; + AcquireSRWLockExclusive(&g_lock); + WerEntry** cur = &g_wer_entries; + while (*cur) { + if (_wcsicmp((*cur)->key.c_str(), key.c_str()) == 0) { + removed = *cur; + *cur = removed->next; + break; + } + cur = &((*cur)->next); + } + ReleaseSRWLockExclusive(&g_lock); + delete removed; + return removed ? S_OK : HRESULT_FROM_WIN32(ERROR_NOT_FOUND); +} + +} // namespace +} // namespace rt::appnotify + +namespace { + +using namespace rt::appnotify; + +#define APPNOTIFY_API(dll) \ + {dll, "RegisterAppConstrainedChangeNotification", reinterpret_cast(®ister_app_constrained)}, \ + {dll, "UnregisterAppConstrainedChangeNotification", reinterpret_cast(&unregister_app_constrained)} + +#define WER_API(dll) \ + {dll, "WerRegisterFile", reinterpret_cast(&wer_register_file)}, \ + {dll, "WerUnregisterFile", reinterpret_cast(&wer_unregister_file)} + +} // namespace + +SHIM_TABLE(appnotify, + APPNOTIFY_API("kernel32.dll"), + APPNOTIFY_API("kernelbase.dll"), + APPNOTIFY_API("twinapi.appcore.dll"), + APPNOTIFY_API("api-ms-win-core-psm-appnotify-l1-1-0.dll"), + APPNOTIFY_API("api-ms-win-core-psm-appnotify-l1-1-1.dll"), + WER_API("kernel32.dll"), + WER_API("kernelbase.dll"), + WER_API("wer.dll"), + WER_API("api-ms-win-core-windowserrorreporting-l1-1-0.dll"), + WER_API("api-ms-win-core-windowserrorreporting-l1-1-1.dll"), +); diff --git a/runtime/test/appnotify_test.cpp b/runtime/test/appnotify_test.cpp new file mode 100644 index 0000000000..441c27e67f --- /dev/null +++ b/runtime/test/appnotify_test.cpp @@ -0,0 +1,159 @@ +// Tests for runtime/shims/appnotify.cpp through rt::shims::find. +#include + +#include +#include +#include +#include + +#include "shims.h" + +namespace { + +using NotifyCallback = void(WINAPI*)(BOOLEAN, PVOID); +using RegisterNotifyFn = DWORD(WINAPI*)(NotifyCallback, PVOID, PVOID*); +using UnregisterNotifyFn = void(WINAPI*)(PVOID); +using WerRegisterFileFn = HRESULT(WINAPI*)(PCWSTR, int, DWORD); +using WerUnregisterFileFn = HRESULT(WINAPI*)(PCWSTR); + +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; +} + +template +Fn resolve(const char* dll, const char* name) { + return reinterpret_cast(rt::shims::find(dll, name)); +} + +void WINAPI dummy_notify(BOOLEAN, PVOID) {} + +void test_registry_coverage() { + for (const char* dll : {"kernel32.dll", "kernelbase.dll", "twinapi.appcore.dll", + "api-ms-win-core-psm-appnotify-l1-1-0.dll", + "api-ms-win-core-psm-appnotify-l1-1-1.dll"}) { + check(resolve(dll, "RegisterAppConstrainedChangeNotification") != nullptr, + "RegisterAppConstrainedChangeNotification resolves"); + check(resolve(dll, "UnregisterAppConstrainedChangeNotification") != nullptr, + "UnregisterAppConstrainedChangeNotification resolves"); + } + + for (const char* dll : {"kernel32.dll", "kernelbase.dll", "wer.dll", + "api-ms-win-core-windowserrorreporting-l1-1-0.dll", + "api-ms-win-core-windowserrorreporting-l1-1-1.dll"}) { + check(resolve(dll, "WerRegisterFile") != nullptr, "WerRegisterFile resolves"); + check(resolve(dll, "WerUnregisterFile") != nullptr, "WerUnregisterFile resolves"); + } +} + +void test_appnotify_registrations() { + auto reg_constrained = resolve("api-ms-win-core-psm-appnotify-l1-1-1.dll", + "RegisterAppConstrainedChangeNotification"); + auto unreg_constrained = resolve("api-ms-win-core-psm-appnotify-l1-1-1.dll", + "UnregisterAppConstrainedChangeNotification"); + + check(reg_constrained(dummy_notify, nullptr, nullptr) == ERROR_INVALID_PARAMETER, + "RegisterAppConstrainedChangeNotification rejects null registration pointer"); + + void* sentinel = reinterpret_cast(static_cast(0xdeadbeef)); + void* out = sentinel; + check(reg_constrained(nullptr, nullptr, &out) == ERROR_INVALID_PARAMETER && out == nullptr, + "RegisterAppConstrainedChangeNotification rejects null callback and zeroes out handle"); + + void* constrained_handle1 = sentinel; + void* constrained_handle2 = sentinel; + int ctx = 42; + check(reg_constrained(dummy_notify, &ctx, &constrained_handle1) == ERROR_SUCCESS && + constrained_handle1 != nullptr && constrained_handle1 != sentinel, + "RegisterAppConstrainedChangeNotification returns non-null handle"); + check(reg_constrained(dummy_notify, &ctx, &constrained_handle2) == ERROR_SUCCESS && + constrained_handle2 != nullptr && constrained_handle2 != sentinel && + constrained_handle2 != constrained_handle1, + "RegisterAppConstrainedChangeNotification returns distinct handles"); + + // Unregister nullptr and foreign pointer must not fault. + unreg_constrained(nullptr); + unreg_constrained(reinterpret_cast(static_cast(0x1234))); + + // Real unregister and double-unregister are safe. + unreg_constrained(constrained_handle1); + unreg_constrained(constrained_handle1); + unreg_constrained(constrained_handle2); + unreg_constrained(constrained_handle2); + check(true, "unregister handles null, foreign, and double-unregister cleanly"); + + // Concurrent multi-thread registration/unregistration. + std::vector workers; + bool thread_ok[4] = {false, false, false, false}; + for (int t = 0; t < 4; ++t) { + workers.emplace_back([&, t]() { + bool ok = true; + for (int i = 0; i < 64; ++i) { + void* h1 = nullptr; + void* h2 = nullptr; + if (reg_constrained(dummy_notify, nullptr, &h1) != ERROR_SUCCESS || !h1) ok = false; + if (reg_constrained(dummy_notify, nullptr, &h2) != ERROR_SUCCESS || !h2 || h1 == h2) ok = false; + unreg_constrained(h1); + unreg_constrained(h2); + } + thread_ok[t] = ok; + }); + } + for (auto& w : workers) w.join(); + check(thread_ok[0] && thread_ok[1] && thread_ok[2] && thread_ok[3], + "concurrent register/unregister across threads succeeds"); +} + +void test_wer_file_registration() { + auto wer_reg = resolve("api-ms-win-core-windowserrorreporting-l1-1-0.dll", "WerRegisterFile"); + auto wer_unreg = + resolve("api-ms-win-core-windowserrorreporting-l1-1-0.dll", "WerUnregisterFile"); + + check(wer_reg(nullptr, 1, 2) == E_INVALIDARG, "WerRegisterFile rejects nullptr path"); + check(wer_reg(L"GAME:\\log.txt", 0, 2) == E_INVALIDARG, "WerRegisterFile rejects file type 0"); + check(wer_reg(L"GAME:\\log.txt", 3, 2) == E_INVALIDARG, "WerRegisterFile rejects file type 3"); + check(wer_reg(L"GAME:\\log.txt", 1, 0x10) == E_INVALIDARG, "WerRegisterFile rejects unknown flags"); + + const HRESULT invalid_name = HRESULT_FROM_WIN32(ERROR_INVALID_NAME); + const HRESULT not_found = HRESULT_FROM_WIN32(ERROR_NOT_FOUND); + + check(wer_reg(L"GAME:\\..\\escape.txt", 2, 2) == invalid_name, + "WerRegisterFile refuses GAME: traversal past root"); + check(wer_reg(L"G:/../escape.txt", 2, 2) == invalid_name, "WerRegisterFile refuses G: traversal past root"); + check(wer_reg(L"T:\\sub\\..\\..\\escape.txt", 2, 2) == invalid_name, + "WerRegisterFile refuses T: nested traversal past root"); + check(wer_unreg(nullptr) == E_INVALIDARG, "WerUnregisterFile rejects nullptr"); + check(wer_unreg(L"GAME:\\..\\escape.txt") == invalid_name, + "WerUnregisterFile refuses traversal past root"); + check(wer_unreg(L"GAME:\\missing.txt") == not_found, + "WerUnregisterFile returns ERROR_NOT_FOUND for unregistered file"); + + check(wer_reg(L"GAME:\\logs\\boot.txt", 2, 2) == S_OK, "WerRegisterFile accepts GAME: path"); + check(wer_reg(L"game:/LOGS/boot.txt", 1, 1) == S_OK, "WerRegisterFile updates matching normalized entry"); + check(wer_unreg(L"GAME:\\logs\\BOOT.TXT") == S_OK, "WerUnregisterFile removes normalized entry"); + check(wer_unreg(L"GAME:\\logs\\boot.txt") == not_found, + "WerUnregisterFile reports ERROR_NOT_FOUND after removal"); + + check(wer_reg(L"T:\\sub\\..\\crash.dmp", 2, 3) == S_OK, "WerRegisterFile accepts T: dot-dot within root"); + check(wer_unreg(L"t:/crash.dmp") == S_OK, "WerUnregisterFile matches normalized T: path"); + + check(wer_reg(L"GAME:\\", 2, 2) == S_OK, "WerRegisterFile accepts console drive root"); + check(wer_unreg(L"game:\\sub\\..") == S_OK, "WerUnregisterFile normalizes trailing dot-dot to root"); + + check(wer_reg(L"C:\\host\\trace.log", 2, 2) == S_OK, "WerRegisterFile accepts host path"); + check(wer_unreg(L"c:/HOST/trace.log") == S_OK, "WerUnregisterFile matches normalized host path"); +} + +} // namespace + +int main() { + test_registry_coverage(); + test_appnotify_registrations(); + test_wer_file_registration(); + 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 bb25cccd7e..40111b4c50 100644 --- a/scripts/build_runtime.ps1 +++ b/scripts/build_runtime.ps1 @@ -1,4 +1,4 @@ -# Builds runtime\build\gta6rt.exe with MSVC at BelowNormal priority, on half the cores by default. +# Builds runtime\build\gta6rt.exe with MSVC at BelowNormal priority, on half the cores by default. # Uses VS's CMake + Ninja when the "C++ CMake tools" component is installed (or native Windows cmake + ninja on PATH), # otherwise calls cl.exe directly. # The GameInput controller shim (SDL3, docs/gameinput.md) is built only on the CMake path: with an installed SDL3, or @@ -86,7 +86,7 @@ $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) and without the Rust XMA2 decoder (XMA voices are silent). 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\thread_stacks.cpp", "src\bcpack.cpp", "src\host_cpu.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\console_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_pso_stream.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\ws2_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp", "shims\lifecycle.cpp", "shims\xbox_bvh_builder.cpp", "shims\com_shim.cpp", "shims\silent_audio.cpp", "shims\bcrypt_rng.cpp", "shims\xapu_queue.cpp", "shims\xapu_chad.cpp", "shims\dstorage.cpp" | ForEach-Object { "`"$src\$_`"" } + $files = "src\main.cpp", "src\thread_stacks.cpp", "src\bcpack.cpp", "src\host_cpu.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\console_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_pso_stream.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\ws2_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp", "shims\lifecycle.cpp", "shims\xbox_bvh_builder.cpp", "shims\com_shim.cpp", "shims\silent_audio.cpp", "shims\bcrypt_rng.cpp", "shims\xapu_queue.cpp", "shims\xapu_chad.cpp", "shims\dstorage.cpp", "shims\appnotify.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 = @"