From 43c4f104c904e1036af0b10295a1677f62c3f205 Mon Sep 17 00:00:00 2001 From: andretuta Date: Tue, 24 Nov 2026 01:43:46 -0300 Subject: [PATCH 1/3] xgameruntime/lifecycle: speech WAV stream, display power request, XAppCapture, suspend-on-close - Implement silent 44-byte 16 kHz mono 16-bit PCM WAVE streams for XSpeechSynthesizer in XAccessibilityImpl. - Back XLauncherImpl::XDisplayAcquireTimeoutDeferral / Close with Win32 PowerCreateRequest / PowerSetRequest(PowerRequestDisplayRequired). - Add offline XAppCaptureImpl stub returning ERROR_NOT_SUPPORTED. - Add runtime/shims/lifecycle.{h,cpp} providing app-state notification registration and CreateWindowExA/W oversized-window fitting plus suspend-on-SC_CLOSE dispatch. --- runtime/CMakeLists.txt | 16 ++ runtime/shims/lifecycle.cpp | 211 +++++++++++++++++++++ runtime/shims/lifecycle.h | 21 ++ runtime/shims/xgameruntime_offline.cpp | 154 ++++++++++++--- runtime/test/lifecycle_test.cpp | 109 +++++++++++ runtime/test/xgameruntime_offline_test.cpp | 59 ++++-- runtime/test/xgameruntime_test.cpp | 3 +- scripts/build_runtime.ps1 | 4 +- tests/test_gdk_runtime_calls.py | 3 +- 9 files changed, 535 insertions(+), 45 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/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..992bc55d07 --- /dev/null +++ b/runtime/shims/lifecycle.cpp @@ -0,0 +1,211 @@ +// 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-*, fitting oversized +// top-level windows into the primary monitor work area and subclassing them so SC_CLOSE runs registered suspend +// callbacks before exiting cleanly. +#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); + +std::mutex& reg_mutex() { + // Intentionally immortal so shutdown/WM_SYSCOMMAND cannot race static destruction. + static auto* m = new std::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::vector snapshot_registrations() { + std::lock_guard lock(reg_mutex()); + return reg_list(); +} + +void trigger_suspend_and_exit() { + if (g_ending.exchange(true, std::memory_order_seq_cst)) return; + auto callbacks = snapshot_registrations(); + std::fprintf(stderr, "[rt] lifecycle: window closed; running %zu suspend routine(s)\n", callbacks.size()); + + // Run suspend callbacks off the UI thread so callbacks that synchronize with the window thread do not deadlock. + std::thread([callbacks = std::move(callbacks)]() { + for (const auto& entry : callbacks) { + if (entry.routine) entry.routine(TRUE, entry.context); + } + std::fprintf(stderr, "[rt] lifecycle: title suspended; exiting\n"); + TerminateProcess(GetCurrentProcess(), 0); + }).detach(); + + std::thread([]() { + std::this_thread::sleep_for(kSuspendDeadline); + std::fprintf(stderr, "[rt] lifecycle: suspend deadline elapsed; exiting\n"); + TerminateProcess(GetCurrentProcess(), 0); + }).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); + } + 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)); +} + +void fit_top_level_window(HWND parent, int& x, int& y, int& width, int& height) { + if (parent != nullptr) return; + RECT area{}; + if (!SystemParametersInfoW(SPI_GETWORKAREA, 0, &area, 0)) return; + const auto [fitted_w, fitted_h] = fit_window_to_area(area, width, height); + if (fitted_w == width && fitted_h == height) return; + 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; +} + +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) { + fit_top_level_window(parent, x, y, width, height); + const HWND hwnd = + ::CreateWindowExW(ex_style, class_name, window_name, style, x, y, width, height, parent, menu, instance, param); + if (hwnd && !parent) install_window_hook(hwnd); + 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) { + fit_top_level_window(parent, x, y, width, height); + const HWND hwnd = + ::CreateWindowExA(ex_style, class_name, window_name, style, x, y, width, height, parent, menu, instance, param); + if (hwnd && !parent) install_window_hook(hwnd); + 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() { + for (const auto& entry : snapshot_registrations()) { + if (entry.routine) entry.routine(TRUE, entry.context); + } +} + +} // 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"), +); 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/shims/xgameruntime_offline.cpp b/runtime/shims/xgameruntime_offline.cpp index cc7a91d211..bdcea72a1a 100644 --- a/runtime/shims/xgameruntime_offline.cpp +++ b/runtime/shims/xgameruntime_offline.cpp @@ -1,5 +1,5 @@ -// xgameruntime: XGameEventImpl, XGameUiImpl, XGameStreamingImpl, XDisplayImpl, XUserDeviceImpl, XAccessibilityImpl and -// XLauncherImpl, offline: small classes a title calls early. +// xgameruntime: XGameEventImpl, XGameUiImpl, XGameStreamingImpl, XDisplayImpl, XUserDeviceImpl, XAccessibilityImpl, +// XLauncherImpl and XAppCaptureImpl, offline: small classes a title calls early. // // Each XGameEvent*, XGameUi* and XGameStreaming* function in xgameruntime.lib asks QueryApiImpl for its class and // calls one slot with its own arguments after `this`. The class and interface ids and the method order are @@ -19,10 +19,12 @@ // their change registrations are kept until unregistered and never called back; the user has // no audio endpoint of its own; finding a controller shows no UI (as on desktop). // XAccessibilityImpl high contrast is Off, closed captions can't be configured, no voice is installed (enumerating -// calls back zero times), XSpeechSynthesizerCreate fails (E_FAIL) with a null handle, the other -// speech calls refuse the handle they were never given (E_INVALIDARG), speech-to-text display -// calls fail (E_FAIL). -// XLauncherImpl XLaunchUri and the display timeout deferral calls fail (E_FAIL); nothing is launched. +// calls back zero times), XSpeechSynthesizerCreate hands out a silent synthesizer whose +// text/SSML streams return a valid 44-byte empty 16 kHz mono 16-bit PCM WAVE header so titles +// that play narration continue cleanly; speech-to-text display calls fail (E_FAIL). +// XLauncherImpl XLaunchUri fails offline (E_FAIL); XDisplayAcquireTimeoutDeferral / Close acquire and clear a +// real Win32 PowerRequestDisplayRequired handle so the host display stays awake. +// XAppCaptureImpl implemented offline; TakeScreenshot reports ERROR_NOT_SUPPORTED. // // Slots whose signature the public pages don't give answer with a value that is safe whichever way the caller reads // it: see `client_not_connected` (XGameStreaming) and `offline_failure`. @@ -610,32 +612,70 @@ HRESULT STDMETHODCALLTYPE speech_enumerate_voices(void*, void* callback, void*) return callback ? S_OK : E_INVALIDARG; } -// 9: HRESULT XSpeechSynthesizerCreate(XSpeechSynthesizerHandle* handle): no synthesizer offline. -HRESULT STDMETHODCALLTYPE speech_create(void* self, void** handle) { - if (handle) *handle = nullptr; - return offline_failure(self); +// Valid 44-byte RIFF/WAVE header for 16 kHz, 16-bit mono PCM with 0 data bytes (silent speech stream). +constexpr uint8_t kSilentWave[44] = { + 'R', 'I', 'F', 'F', 0x24, 0x00, 0x00, 0x00, 'W', 'A', 'V', 'E', 'f', 'm', 't', ' ', + 0x10, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x80, 0x3e, 0x00, 0x00, 0x00, 0x7d, 0x00, 0x00, + 0x02, 0x00, 0x10, 0x00, 'd', 'a', 't', 'a', 0x00, 0x00, 0x00, 0x00, +}; + +uint8_t g_speech_synth_handle = 0; +uint8_t g_speech_stream_handle = 0; + +// 9: HRESULT XSpeechSynthesizerCreate(XSpeechSynthesizerHandle* handle): silent synthesizer handle. +HRESULT STDMETHODCALLTYPE speech_create(void*, void** handle) { + if (!handle) return E_POINTER; + *handle = &g_speech_synth_handle; + return S_OK; +} + +// 10: HRESULT XSpeechSynthesizerCloseHandle(XSpeechSynthesizerHandle handle) +HRESULT STDMETHODCALLTYPE speech_close_synth(void*, void* handle) { + return handle == &g_speech_synth_handle ? S_OK : E_INVALIDARG; +} + +// 11: HRESULT XSpeechSynthesizerSetDefaultVoice(XSpeechSynthesizerHandle handle) +HRESULT STDMETHODCALLTYPE speech_set_default_voice(void*, void* handle) { + return handle == &g_speech_synth_handle ? S_OK : E_INVALIDARG; } -// 10-12, 14: a synthesizer or stream handle is the first argument, and none was ever handed out: E_INVALIDARG. -HRESULT STDMETHODCALLTYPE speech_bad_handle(void*) { return E_INVALIDARG; } +// 12: HRESULT XSpeechSynthesizerSetCustomVoice(XSpeechSynthesizerHandle handle, const char* voiceId) +HRESULT STDMETHODCALLTYPE speech_set_custom_voice(void*, void* handle, const char*) { + return handle == &g_speech_synth_handle ? S_OK : E_INVALIDARG; +} // 13, 21: HRESULT XSpeechSynthesizerCreateStreamFromText/Ssml(synthesizer, const char* text, // XSpeechSynthesizerStreamHandle* stream) -HRESULT STDMETHODCALLTYPE speech_create_stream(void*, void*, const char*, void** stream) { +HRESULT STDMETHODCALLTYPE speech_create_stream(void*, void* synth, const char*, void** stream) { if (stream) *stream = nullptr; - return E_INVALIDARG; + if (synth != &g_speech_synth_handle) return E_INVALIDARG; + if (!stream) return E_POINTER; + *stream = &g_speech_stream_handle; + return S_OK; +} + +// 14: HRESULT XSpeechSynthesizerCloseStreamHandle(XSpeechSynthesizerStreamHandle stream) +HRESULT STDMETHODCALLTYPE speech_close_stream(void*, void* stream) { + return stream == &g_speech_stream_handle ? S_OK : E_INVALIDARG; } // 15: HRESULT XSpeechSynthesizerGetStreamDataSize(stream, size_t* size) -HRESULT STDMETHODCALLTYPE speech_stream_size(void*, void*, size_t* size) { +HRESULT STDMETHODCALLTYPE speech_stream_size(void*, void* stream, size_t* size) { if (size) *size = 0; - return E_INVALIDARG; + if (stream != &g_speech_stream_handle) return E_INVALIDARG; + if (!size) return E_POINTER; + *size = sizeof(kSilentWave); + return S_OK; } // 16: HRESULT XSpeechSynthesizerGetStreamData(stream, size_t size, void* buffer, size_t* used) -HRESULT STDMETHODCALLTYPE speech_stream_data(void*, void*, size_t, void*, size_t* used) { +HRESULT STDMETHODCALLTYPE speech_stream_data(void*, void* stream, size_t size, void* buffer, size_t* used) { if (used) *used = 0; - return E_INVALIDARG; + if (stream != &g_speech_stream_handle) return E_INVALIDARG; + if (!buffer || size < sizeof(kSilentWave)) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER); + std::memcpy(buffer, kSilentWave, sizeof(kSilentWave)); + if (used) *used = sizeof(kSilentWave); + return S_OK; } // The slots with no offline counterpart whose arguments the layout doesn't give: the caption properties (3) and @@ -654,11 +694,11 @@ const void* const kAccessibilityVtable[] = { FN(accessibility_offline<7>), // 7 XSpeechToTextSendString FN(speech_enumerate_voices), // 8 XSpeechSynthesizerEnumerateInstalledVoices FN(speech_create), // 9 XSpeechSynthesizerCreate - FN(speech_bad_handle), // 10 XSpeechSynthesizerCloseHandle - FN(speech_bad_handle), // 11 XSpeechSynthesizerSetDefaultVoice - FN(speech_bad_handle), // 12 XSpeechSynthesizerSetCustomVoice + FN(speech_close_synth), // 10 XSpeechSynthesizerCloseHandle + FN(speech_set_default_voice), // 11 XSpeechSynthesizerSetDefaultVoice + FN(speech_set_custom_voice), // 12 XSpeechSynthesizerSetCustomVoice FN(speech_create_stream), // 13 XSpeechSynthesizerCreateStreamFromText - FN(speech_bad_handle), // 14 XSpeechSynthesizerCloseStreamHandle + FN(speech_close_stream), // 14 XSpeechSynthesizerCloseStreamHandle FN(speech_stream_size), // 15 XSpeechSynthesizerGetStreamDataSize FN(speech_stream_data), // 16 XSpeechSynthesizerGetStreamData FN(accessibility_offline<17>), // 17 XSpeechToTextBeginHypothesisString @@ -680,11 +720,31 @@ constexpr char kLauncherName[] = "XLauncherImpl"; constexpr GUID kLauncherClass = {0x1b339674, 0x328d, 0x4283, {0xa2, 0x00, 0x31, 0x71, 0xf1, 0x8d, 0x36, 0x39}}; // 3: HRESULT XLaunchUri(XUserHandle user, const char* uri): nothing is launched; E_FAIL. -// 4: HRESULT XDisplayAcquireTimeoutDeferral(XDisplayTimeoutDeferralHandle* handle): none is handed out. -// 5: XDisplayCloseTimeoutDeferralHandle(handle): no handle exists; E_FAIL, which a void caller ignores. -HRESULT STDMETHODCALLTYPE launcher_acquire_deferral(void* self, void** handle) { - if (handle) *handle = nullptr; - return offline_failure(self); +// 4: HRESULT XDisplayAcquireTimeoutDeferral(XDisplayTimeoutDeferralHandle* handle): Win32 display power request. +// 5: void XDisplayCloseTimeoutDeferralHandle(XDisplayTimeoutDeferralHandle handle): clears and closes the request. +HRESULT STDMETHODCALLTYPE launcher_acquire_deferral(void*, void** handle) { + if (!handle) return E_POINTER; + *handle = nullptr; + wchar_t reason[] = L"Title display timeout deferral"; + REASON_CONTEXT ctx{}; + ctx.Version = POWER_REQUEST_CONTEXT_VERSION; + ctx.Flags = POWER_REQUEST_CONTEXT_SIMPLE_STRING; + ctx.Reason.SimpleReasonString = reason; + const HANDLE req = PowerCreateRequest(&ctx); + if (req == INVALID_HANDLE_VALUE) return HRESULT_FROM_WIN32(GetLastError()); + if (!PowerSetRequest(req, PowerRequestDisplayRequired)) { + const DWORD err = GetLastError(); + CloseHandle(req); + return HRESULT_FROM_WIN32(err); + } + *handle = req; + return S_OK; +} + +void STDMETHODCALLTYPE launcher_close_deferral(void*, void* handle) { + if (!handle) return; + PowerClearRequest(handle, PowerRequestDisplayRequired); + CloseHandle(handle); } HRESULT STDMETHODCALLTYPE launcher_query_interface(void*, REFIID iid, void** out); @@ -692,7 +752,7 @@ const void* const kLauncherVtable[] = { FN(launcher_query_interface), FN(object_add_ref), FN(object_release), // 0-2 IUnknown FN((offline_failure)), // 3 XLaunchUri FN(launcher_acquire_deferral), // 4 XDisplayAcquireTimeoutDeferral - FN((offline_failure)), // 5 XDisplayCloseTimeoutDeferralHandle + FN(launcher_close_deferral), // 5 XDisplayCloseTimeoutDeferralHandle }; static_assert(std::size(kLauncherVtable) == 6, "IUnknown + IXLauncherImpl's 3 methods"); ClassObject g_launcher_object{kLauncherVtable}; @@ -701,6 +761,40 @@ HRESULT STDMETHODCALLTYPE launcher_query_interface(void*, REFIID iid, void** out return answer(&g_launcher_object, &kLauncherClass, &kLauncherClass + 1, iid, out); } +// ======================= XAppCaptureImpl ======================= + +constexpr char kAppCaptureName[] = "XAppCaptureImpl"; +constexpr GUID kAppCaptureClass = {0xa4f1aee2, 0x4bf1, 0x4485, {0xb0, 0x08, 0xa7, 0xc2, 0x6d, 0x52, 0xac, 0x27}}; +const GUID kAppCaptureInterfaces[] = { + kAppCaptureClass, + {0x22e672d7, 0xb4e3, 0x406c, {0xbd, 0x50, 0x8f, 0x0d, 0x25, 0x23, 0x6f, 0x9e}}, // IXAppCaptureImpl +}; + +// 5: HRESULT XAppCaptureTakeScreenshot(XUserHandle user, XAppCaptureTakeScreenshotResult* result) +HRESULT STDMETHODCALLTYPE app_capture_take_screenshot(void*, void*, void*) { + static std::atomic s_logged{false}; + if (!s_logged.exchange(true)) + std::fprintf(stderr, "[rt] xgameruntime: XAppCaptureTakeScreenshot is not supported offline\n"); + return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); +} + +template HRESULT STDMETHODCALLTYPE app_capture_unknown(void* self) { + return unknown_slot(self); +} + +HRESULT STDMETHODCALLTYPE app_capture_query_interface(void*, REFIID iid, void** out); +const void* const kAppCaptureVtable[] = { + FN(app_capture_query_interface), FN(object_add_ref), FN(object_release), // 0-2 IUnknown + FN(app_capture_unknown<3>), // 3 diagnostic screenshot + FN(app_capture_unknown<4>), // 4 diagnostic clip + FN(app_capture_take_screenshot), // 5 XAppCaptureTakeScreenshot +}; +static_assert(std::size(kAppCaptureVtable) == 6, "IUnknown + IXAppCaptureImpl slots"); +ClassObject g_app_capture_object{kAppCaptureVtable}; +HRESULT STDMETHODCALLTYPE app_capture_query_interface(void*, REFIID iid, void** out) { + return answer(&g_app_capture_object, std::begin(kAppCaptureInterfaces), std::end(kAppCaptureInterfaces), iid, out); +} + #undef FN } // namespace @@ -737,6 +831,10 @@ bool xgameruntime_offline_query(const GUID& class_id, REFIID interface_id, void* *hr = launcher_query_interface(nullptr, interface_id, out); return true; } + if (class_id == kAppCaptureClass) { + *hr = app_capture_query_interface(nullptr, interface_id, out); + return true; + } return false; } diff --git a/runtime/test/lifecycle_test.cpp b/runtime/test/lifecycle_test.cpp new file mode 100644 index 0000000000..4238b68520 --- /dev/null +++ b/runtime/test/lifecycle_test.cpp @@ -0,0 +1,109 @@ +// 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; + } +} + +} // namespace + +int main() { + using RegFn = ULONG(WINAPI*)(void(WINAPI*)(BOOLEAN, PVOID), PVOID, PVOID*); + using UnregFn = void(WINAPI*)(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"); + if (!reg || !unreg || !create_w) return 1; + + // 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"); + + // 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); + } + + std::printf("%d check(s), %d failure(s)\n", g_checks, g_failures); + return g_failures ? 1 : 0; +} diff --git a/runtime/test/xgameruntime_offline_test.cpp b/runtime/test/xgameruntime_offline_test.cpp index 7668b6164b..ccdb4c7eec 100644 --- a/runtime/test/xgameruntime_offline_test.cpp +++ b/runtime/test/xgameruntime_offline_test.cpp @@ -293,19 +293,35 @@ int main() { check(at(acc, 8)(acc, reinterpret_cast(&on_state), nullptr) == S_OK && at(acc, 8)(acc, nullptr, nullptr) == E_INVALIDARG, "XSpeechSynthesizerEnumerateInstalledVoices: no voices, S_OK (a callback is required)"); - void* synth = reinterpret_cast(1); - check(at(acc, 9)(acc, &synth) == E_FAIL && synth == nullptr, - "XSpeechSynthesizerCreate fails offline and nulls the handle"); - void* stream = reinterpret_cast(1); - size_t size = 5, got = 5; + void* synth = nullptr; + check(at(acc, 9)(acc, &synth) == S_OK && synth != nullptr && + at(acc, 9)(acc, nullptr) == E_POINTER, + "XSpeechSynthesizerCreate returns a silent synthesizer handle"); + void* stream = nullptr; + size_t size = 0, got = 0; check(at(acc, 10)(acc, nullptr) == E_INVALIDARG && at(acc, 11)(acc, nullptr) == E_INVALIDARG && at(acc, 12)(acc, nullptr) == E_INVALIDARG && at(acc, 14)(acc, nullptr) == E_INVALIDARG, "close and set-voice calls on a null handle: E_INVALIDARG"); + check(at(acc, 11)(acc, synth) == S_OK, "XSpeechSynthesizerSetDefaultVoice succeeds on valid handle"); check(at(acc, 13)(acc, nullptr, "hi", &stream) == E_INVALIDARG && stream == nullptr, "CreateStreamFromText on a null synthesizer: E_INVALIDARG, no stream"); - stream = reinterpret_cast(1); - check(at(acc, 21)(acc, nullptr, "", &stream) == E_INVALIDARG && stream == nullptr, - "CreateStreamFromSsml on a null synthesizer: E_INVALIDARG, no stream"); + check(at(acc, 13)(acc, synth, "Hello", &stream) == S_OK && stream != nullptr, + "CreateStreamFromText returns a silent WAVE stream"); + check(at(acc, 15)(acc, stream, &size) == S_OK && size == 44, + "GetStreamDataSize reports the 44-byte empty WAVE header"); + uint8_t wav[64] = {}; + check(at(acc, 16)(acc, stream, 8, wav, &got) == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER) && got == 0, + "GetStreamData rejects an undersized buffer with ERROR_INSUFFICIENT_BUFFER"); + check(at(acc, 16)(acc, stream, sizeof(wav), wav, &got) == S_OK && got == 44 && + std::memcmp(wav, "RIFF", 4) == 0 && std::memcmp(wav + 8, "WAVEfmt ", 8) == 0 && + std::memcmp(wav + 36, "data", 4) == 0, + "GetStreamData writes a valid silent 16 kHz mono 16-bit PCM WAVE header"); + check(at(acc, 14)(acc, stream) == S_OK, "XSpeechSynthesizerCloseStreamHandle succeeds"); + stream = nullptr; + check(at(acc, 21)(acc, synth, "", &stream) == S_OK && stream != nullptr && + at(acc, 14)(acc, stream) == S_OK, + "CreateStreamFromSsml returns a silent WAVE stream"); + check(at(acc, 10)(acc, synth) == S_OK, "XSpeechSynthesizerCloseHandle succeeds"); check(at(acc, 15)(acc, nullptr, &size) == E_INVALIDARG && size == 0 && at(acc, 16)(acc, nullptr, 8, nullptr, &got) == E_INVALIDARG && got == 0, "stream size and data on a null stream: E_INVALIDARG, zero written"); @@ -317,18 +333,37 @@ int main() { void* launcher = nullptr; check(query(&kLauncherClass, kLauncherClass, &launcher) == S_OK && launcher, "XLauncherImpl for its class id"); if (!launcher) return 1; - void* deferral = reinterpret_cast(1); + void* deferral = nullptr; + using CloseDeferral = void(STDMETHODCALLTYPE*)(void*, void*); check(at(launcher, 3)(launcher, nullptr, "https://example.com") == E_FAIL, "XLaunchUri is not available offline"); - check(at(launcher, 4)(launcher, &deferral) == E_FAIL && deferral == nullptr && - at(launcher, 5)(launcher) == E_FAIL, - "the display timeout deferral is not available offline"); + check(at(launcher, 4)(launcher, nullptr) == E_POINTER, + "XDisplayAcquireTimeoutDeferral rejects null out pointer"); + check(at(launcher, 4)(launcher, &deferral) == S_OK && deferral != nullptr, + "XDisplayAcquireTimeoutDeferral acquires a display power request handle"); + at(launcher, 5)(launcher, deferral); + at(launcher, 5)(launcher, nullptr); + check(true, "XDisplayCloseTimeoutDeferralHandle closes handle and ignores null"); GUID other = kLauncherClass; other.Data1 ^= 1; void* none = reinterpret_cast(1); check(query(&kLauncherClass, other, &none) == E_NOINTERFACE && none == nullptr, "XLauncherImpl refuses an interface id it doesn't implement"); + // ---- XAppCapture ---- + const GUID kAppCaptureClass = {0xa4f1aee2, 0x4bf1, 0x4485, {0xb0, 0x08, 0xa7, 0xc2, 0x6d, 0x52, 0xac, 0x27}}; + const GUID kAppCaptureIid = {0x22e672d7, 0xb4e3, 0x406c, {0xbd, 0x50, 0x8f, 0x0d, 0x25, 0x23, 0x6f, 0x9e}}; + void* capture = nullptr; + void* capture_iid = nullptr; + check(query(&kAppCaptureClass, kAppCaptureClass, &capture) == S_OK && capture && + query(&kAppCaptureClass, kAppCaptureIid, &capture_iid) == S_OK && capture_iid == capture, + "XAppCaptureImpl answers its class id and interface id"); + if (capture) { + using TakeShot = HRESULT(STDMETHODCALLTYPE*)(void*, void*, void*); + check(at(capture, 5)(capture, nullptr, nullptr) == HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED), + "XAppCaptureTakeScreenshot returns ERROR_NOT_SUPPORTED offline"); + } + std::printf("xgameruntime_offline_test: %d checks, %d failures\n", g_checks, g_failures); return g_failures == 0 ? 0 : 1; } diff --git a/runtime/test/xgameruntime_test.cpp b/runtime/test/xgameruntime_test.cpp index af67045d42..0a040fdfbb 100644 --- a/runtime/test/xgameruntime_test.cpp +++ b/runtime/test/xgameruntime_test.cpp @@ -254,7 +254,6 @@ void check_measured_classes(QueryFn query, XSystemAnalyticsInfo (*named_analytic // Classes nobody serves are still refused, and logged, as before. const GUID refused[] = { - {0xa4f1aee2, 0x4bf1, 0x4485, {0xb0, 0x08, 0xa7, 0xc2, 0x6d, 0x52, 0xac, 0x27}}, // XAppCaptureImpl {0x12345678, 0x9abc, 0xdef0, {0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0}}, // no such class }; bool all_refused = true; @@ -262,7 +261,7 @@ void check_measured_classes(QueryFn query, XSystemAnalyticsInfo (*named_analytic void* out = reinterpret_cast(1); all_refused = all_refused && query(&cls, cls, &out) == static_cast(0x80070032) && out == nullptr; } - check(all_refused, "XAppCaptureImpl and an unknown class are still refused"); + check(all_refused, "an unknown class is still refused"); } // xgameruntime.lib's thunks don't import the runtime: they LoadLibraryW(L"xgameruntime.dll") and GetProcAddress five diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1 index 8bd74d1cf1..1483b12427 100644 --- a/scripts/build_runtime.ps1 +++ b/scripts/build_runtime.ps1 @@ -81,14 +81,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 diff --git a/tests/test_gdk_runtime_calls.py b/tests/test_gdk_runtime_calls.py index d9f2d9426a..614905235f 100644 --- a/tests/test_gdk_runtime_calls.py +++ b/tests/test_gdk_runtime_calls.py @@ -417,7 +417,8 @@ def test_the_default_source_is_every_runtime_shim(self): # xgameruntime.cpp serves XGameRuntimeFeatureImpl; the ids its feature table only names (k...ClassId) don't count. self.assertEqual(served.get("8836fe87-edb9-4fe3-8dad-05f0d2cd5b40"), "kGameRuntimeFeatureClass") self.assertEqual(served.get("1b339674-328d-4283-a200-3171f18d3639"), "kLauncherClass") # XLauncherImpl, xgameruntime_offline.cpp - self.assertNotIn("a4f1aee2-4bf1-4485-b008-a7c26d52ac27", served) # XAppCaptureImpl + self.assertEqual(served.get("a4f1aee2-4bf1-4485-b008-a7c26d52ac27"), "kAppCaptureClass") # XAppCaptureImpl, xgameruntime_offline.cpp + self.assertNotIn("0651aae2-4012-4077-bf84-8b9097090e2c", served) # XGameInviteImpl empty = os.path.join(self.tmp, "no-shims") os.makedirs(empty, exist_ok=True) with self.assertRaises(OSError): From a02134a9c60af52b8e0c6bdc6e2fa2bad72e7e75 Mon Sep 17 00:00:00 2001 From: andretuta Date: Tue, 24 Nov 2026 03:00:33 -0300 Subject: [PATCH 2/3] lifecycle: hook only the title window, end through ExitProcess, fix unregister race - Only the title's first top-level window (no parent, not WS_CHILD, not WS_EX_TOOLWINDOW) is fitted to the work area and gets the SC_CLOSE hook; WM_NCDESTROY releases the claim. Other windows the title creates are left alone instead of ending the process on close. - The suspend thread and the 1 s deadline end the run through the title's own ExitProcess shim (process.cpp end_run), so the host finishes its cleanup, instead of TerminateProcess. - Suspend callbacks run under the (now recursive) registration lock and each id is looked up again before its call, so a routine never runs after UnregisterAppStateChangeNotification returned, and an unregister from inside a callback works. - docs/runtime_imports.md: speech, XLauncher and XAppCapture text matches the code; new lifecycle shim paragraph. - lifecycle_test: unregister-from-callback and title-window claim checks. AI-assisted. Tested: lifecycle_test (29 checks), xgameruntime_offline_test (69 checks), docs and gdk_runtime_calls pytest; clang 23 / mingw x64. Co-Authored-By: Claude Opus 5.5 --- docs/runtime_imports.md | 48 +++++++++++------ runtime/shims/lifecycle.cpp | 92 +++++++++++++++++++++++---------- runtime/test/lifecycle_test.cpp | 69 ++++++++++++++++++++++++- 3 files changed, 165 insertions(+), 44 deletions(-) diff --git a/docs/runtime_imports.md b/docs/runtime_imports.md index 7b9f62d5a1..61d6361016 100644 --- a/docs/runtime_imports.md +++ b/docs/runtime_imports.md @@ -64,6 +64,14 @@ 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. 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 @@ -450,13 +458,18 @@ on the executable, the rest is not: - **Accessibility and speech** (`IXAccessibilityImpl2`, slots 3-21): `XHighContrastGetMode` (5) answers Off and `XClosedCaptionSetEnabled` (4) is accepted. No voice is installed: `XSpeechSynthesizerEnumerateInstalledVoices` - (8) calls back zero times and returns `S_OK`, `XSpeechSynthesizerCreate` (9) fails (`E_FAIL`) with a null handle, - and the handle calls (10-16, 21: close, default and custom voice, streams from text and SSML, stream size and - data) refuse the handle they were never given (`E_INVALIDARG`, outputs zeroed). The closed-caption properties (3) - and the speech-to-text display calls (6, 7, 17-20) fail with `E_FAIL`, writing nothing: their parameter lists - are not in the docs' layout. -- **`XLauncherImpl`** (`IXLauncherImpl`, slots 3-5): `XLaunchUri`, `XDisplayAcquireTimeoutDeferral` (null handle) - and `XDisplayCloseTimeoutDeferralHandle` fail with `E_FAIL`; nothing is launched. + (8) calls back zero times and returns `S_OK`. `XSpeechSynthesizerCreate` (9) hands out a silent synthesizer handle + (`E_POINTER` for a null out pointer). Close (10), set default voice (11) and set custom voice (12) accept that handle + and refuse any other with `E_INVALIDARG`. Streams from text (13) and SSML (21) are created from it and return a + stream handle; its close (14) accepts it. Stream size (15) reports 44 bytes and stream data (16) copies them: a valid + RIFF/WAVE header for 16 kHz, 16-bit mono PCM with zero data bytes, so a title that plays narration reads a silent + stream (a buffer under 44 bytes gets `ERROR_INSUFFICIENT_BUFFER`). A foreign handle on 15 or 16 gets `E_INVALIDARG`, + outputs zeroed. The closed-caption properties (3) and the speech-to-text display calls (6, 7, 17-20) fail with + `E_FAIL`, writing nothing: their parameter lists are not in the docs' layout. +- **`XLauncherImpl`** (`IXLauncherImpl`, slots 3-5): `XLaunchUri` fails with `E_FAIL`; nothing is launched. + `XDisplayAcquireTimeoutDeferral` (4) creates a Win32 `PowerRequestDisplayRequired` request and returns its handle (a + failing `PowerCreateRequest` or `PowerSetRequest` returns the Win32 error as an HRESULT). + `XDisplayCloseTimeoutDeferralHandle` (5) clears that request and closes the handle, so the display may sleep again. - **ASSUMPTION:** the parameter lists of the speech calls and `XHighContrastGetMode` (Off is 0), from the GDK reference; only the argument counts were measured, from `tools/gdk_runtime_calls.py` on the executable. - **HDR:** `XDisplayTryEnableHdrMode` answers Disabled, because the host output is SDR. With `LEONIDA_HDR=1` it @@ -484,11 +497,12 @@ layout with the documented argument count, and each behaves as Microsoft's refer | Class | Interface asked for | Slots (args after `this`) | Offline behaviour | |---|---|---|---| -| `XGameRuntimeFeatureImpl` | its class id | 3 `XGameRuntimeIsFeatureAvailable` (1, returns `bool`) | True when `QueryApiImpl` serves the class the feature's functions go through (whichever `xgameruntime*.cpp` serves it) and the feature is documented for Windows: today XAccessibility, XSpeechSynthesizer, XLauncher, XAsync, XAsyncProvider, XTaskQueue, XThread, XError, XGame, XGameSave, XGameUI, XNetworking, XPackage, XPersistentLocalStorage, XStore, XSystem, XUser, XGameEvent, XGameStreaming. False for XDisplay (served, but documented for the consoles only), for the classes not served (XAppCapture, XGameInvite) and for values past the enum | +| `XGameRuntimeFeatureImpl` | its class id | 3 `XGameRuntimeIsFeatureAvailable` (1, returns `bool`) | True when `QueryApiImpl` serves the class the feature's functions go through (whichever `xgameruntime*.cpp` serves it) and the feature is documented for Windows: today XAccessibility, XAppCapture, XSpeechSynthesizer, XLauncher, XAsync, XAsyncProvider, XTaskQueue, XThread, XError, XGame, XGameSave, XGameUI, XNetworking, XPackage, XPersistentLocalStorage, XStore, XSystem, XUser, XGameEvent, XGameStreaming. False for XDisplay (served, but documented for the consoles only), for the classes not served (XGameInvite) and for values past the enum | | `XSystemAnalyticsImpl` | its class id | 3 `XSystemGetAnalyticsInfo` (1: the result's address, as MSVC passes a returned struct to a member function) | The named export's `XSystemAnalyticsInfo` | -Not served yet, though `libHttpClient.GDK.dll` has thunks for them: `XAppCaptureImpl` and `XGameInviteImpl`, -among others. +Not served yet, though `libHttpClient.GDK.dll` has thunks for them: `XGameInviteImpl`, among others. +`XAppCaptureImpl` is served offline (`runtime/shims/xgameruntime_offline.cpp`): its class and interface ids answer, +`XAppCaptureTakeScreenshot` (5) returns `ERROR_NOT_SUPPORTED`, and slots 3 and 4 go through the unknown-slot path. Which classes the package's GDK modules reference, from a byte search for the class and interface GUIDs that xgameruntime-docs lists (16-byte in-memory form, every `.dll` of the package; counts only, nothing else read): @@ -519,9 +533,9 @@ therefore needs no module name beyond the `xgameruntime.dll` it already has, whi | Class | Thunks | Referenced | Served | |---|---:|---:|---| -| `XAccessibilityImpl` | 10 | 9 | no | -| `XAppCaptureImpl` | 1 | 1 | no | -| `XLauncherImpl` | 3 | 3 | no | +| `XAccessibilityImpl` | 10 | 9 | yes | +| `XAppCaptureImpl` | 1 | 1 | yes | +| `XLauncherImpl` | 3 | 3 | yes | | `XDisplayImpl` | 1 | 1 | yes | | `XGameEventImpl` | 1 | 1 | yes | | `XGameImpl` | 2 | 2 | yes | @@ -537,10 +551,10 @@ therefore needs no module name beyond the `xgameruntime.dll` it already has, whi | `XThreadingImpl` | 18 | 17 | yes | | `XUserImpl` | 21 | 21 | yes | -"Served" is the tool's answer for the runtime sources at that commit. The three that are not: `XAccessibilityImpl` -(the speech-synthesizer slots 8-13, 15, 16 and 21 are referenced; slot 14 is not), `XAppCaptureImpl` (slot 5, -`XAppCaptureTakeScreenshot`) and `XLauncherImpl` (slots 3-5: `XLaunchUri` and the two display timeout-deferral calls). -Open pull requests serve them: #4235, #4307 and #4248. The slots of `XUserImpl`, `XStoreImpl` and `XGameSaveImpl` the +"Served" is the tool's answer for the runtime sources on this branch (`served_classes` over every `runtime/shims/*.cpp`): +every class in the table is served now, `XAppCaptureImpl` and `XLauncherImpl` included. The executable references the +speech-synthesizer slots 8-13, 15, 16 and 21 (slot 14 is not), `XAppCaptureImpl` slot 5 (`XAppCaptureTakeScreenshot`) +and `XLauncherImpl` slots 3-5 (`XLaunchUri` and the two display timeout-deferral calls). The slots of `XUserImpl`, `XStoreImpl` and `XGameSaveImpl` the executable calls, and the argument counts the tool estimates from the registers, are in the report the tool writes. `XErrorImpl`, which `XCurl.dll` and `libHttpClient.GDK.dll` call, is not among the executable's classes. diff --git a/runtime/shims/lifecycle.cpp b/runtime/shims/lifecycle.cpp index 992bc55d07..8dc54f2a72 100644 --- a/runtime/shims/lifecycle.cpp +++ b/runtime/shims/lifecycle.cpp @@ -8,9 +8,9 @@ // 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-*, fitting oversized -// top-level windows into the primary monitor work area and subclassing them so SC_CLOSE runs registered suspend -// callbacks before exiting cleanly. +// - CreateWindowExW / CreateWindowExA on user32.dll and ext-ms-win-rtcore-ntuser-window-*, 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 @@ -47,9 +47,10 @@ struct Registration { constexpr wchar_t kTitleProcProp[] = L"leonida.title.wndproc"; constexpr auto kSuspendDeadline = std::chrono::seconds(1); -std::mutex& reg_mutex() { +// 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::mutex; + static auto* m = new std::recursive_mutex; return *m; } @@ -60,30 +61,58 @@ std::vector& reg_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); +} -std::vector snapshot_registrations() { +// 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()); - return reg_list(); + 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; - auto callbacks = snapshot_registrations(); - std::fprintf(stderr, "[rt] lifecycle: window closed; running %zu suspend routine(s)\n", callbacks.size()); + 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([callbacks = std::move(callbacks)]() { - for (const auto& entry : callbacks) { - if (entry.routine) entry.routine(TRUE, entry.context); - } + std::thread([]() { + run_suspend_callbacks(); std::fprintf(stderr, "[rt] lifecycle: title suspended; exiting\n"); - TerminateProcess(GetCurrentProcess(), 0); + end_title_run(); }).detach(); std::thread([]() { std::this_thread::sleep_for(kSuspendDeadline); std::fprintf(stderr, "[rt] lifecycle: suspend deadline elapsed; exiting\n"); - TerminateProcess(GetCurrentProcess(), 0); + end_title_run(); }).detach(); } @@ -95,6 +124,8 @@ LRESULT CALLBACK lifecycle_wnd_proc(HWND hwnd, UINT message, WPARAM wparam, LPAR 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); @@ -109,18 +140,29 @@ void install_window_hook(HWND hwnd) { SetWindowLongPtrW(hwnd, GWLP_WNDPROC, reinterpret_cast(&lifecycle_wnd_proc)); } -void fit_top_level_window(HWND parent, int& x, int& y, int& width, int& height) { - if (parent != nullptr) return; +// 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; + 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; + 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) { @@ -144,19 +186,19 @@ void WINAPI unregister_app_state_change(PVOID registration) { 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) { - fit_top_level_window(parent, x, y, width, height); + 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); - if (hwnd && !parent) install_window_hook(hwnd); + 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) { - fit_top_level_window(parent, x, y, width, height); + 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); - if (hwnd && !parent) install_window_hook(hwnd); + adopt_title_window(hwnd, candidate); return hwnd; } @@ -181,9 +223,7 @@ std::size_t registered_notification_count() { } void invoke_suspend_callbacks_for_test() { - for (const auto& entry : snapshot_registrations()) { - if (entry.routine) entry.routine(TRUE, entry.context); - } + run_suspend_callbacks(); } } // namespace rt::lifecycle diff --git a/runtime/test/lifecycle_test.cpp b/runtime/test/lifecycle_test.cpp index 4238b68520..6e6d344c32 100644 --- a/runtime/test/lifecycle_test.cpp +++ b/runtime/test/lifecycle_test.cpp @@ -39,11 +39,25 @@ void WINAPI on_app_state(BOOLEAN quiesced, PVOID context) { } } +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 UnregFn = void(WINAPI*)(PVOID); using CreateExWFn = HWND(WINAPI*)(DWORD, LPCWSTR, LPCWSTR, DWORD, int, int, int, int, HWND, HMENU, HINSTANCE, LPVOID); @@ -60,6 +74,7 @@ int main() { "CreateWindowExW resolves through user32 and ext-ms-win-rtcore-ntuser-window"); check(!rt::shims::owns_dll("user32.dll"), "user32.dll stays partially overridden"); 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; @@ -82,6 +97,33 @@ int main() { 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); @@ -104,6 +146,31 @@ int main() { 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; } From d7354f2b91de2917ba6639a053b9fe7cb82a5d23 Mon Sep 17 00:00:00 2001 From: andretuta Date: Tue, 24 Nov 2026 09:32:26 -0300 Subject: [PATCH 3/3] xgameruntime_offline: one silent voice, drop XAppCaptureImpl and the lifecycle shim (#401 review) - Speech is consistent now: XSpeechSynthesizerEnumerateInstalledVoices calls back once with a silent voice (XSpeechSynthesizerVoiceInformation in the GDK reference's layout), and SetCustomVoice accepts that voice id only. The enumeration takes (context, callback), the GDK reference's order; main read them the other way round. - XAppCaptureImpl is left to #537, which serves it in xgameruntime.cpp with its full layout. - The lifecycle shim (app-state callbacks, CreateWindowEx hook) moves to its own pull request. - docs/runtime_imports.md: the speech and launcher bullets match the code; the launcher's display power request is called out as a side effect on the host. Co-Authored-By: Claude Opus 5.5 --- docs/runtime_imports.md | 41 ++-- runtime/CMakeLists.txt | 16 -- runtime/shims/lifecycle.cpp | 251 --------------------- runtime/shims/lifecycle.h | 21 -- runtime/shims/xgameruntime_offline.cpp | 80 +++---- runtime/test/lifecycle_test.cpp | 176 --------------- runtime/test/xgameruntime_offline_test.cpp | 52 +++-- runtime/test/xgameruntime_test.cpp | 3 +- scripts/build_runtime.ps1 | 4 +- tests/test_gdk_runtime_calls.py | 3 +- 10 files changed, 87 insertions(+), 560 deletions(-) delete mode 100644 runtime/shims/lifecycle.cpp delete mode 100644 runtime/shims/lifecycle.h delete mode 100644 runtime/test/lifecycle_test.cpp diff --git a/docs/runtime_imports.md b/docs/runtime_imports.md index 61d6361016..e9bbc34e3c 100644 --- a/docs/runtime_imports.md +++ b/docs/runtime_imports.md @@ -64,14 +64,6 @@ 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. 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 @@ -457,10 +449,13 @@ on the executable, the rest is not: card and text entry, which fail before starting. - **Accessibility and speech** (`IXAccessibilityImpl2`, slots 3-21): `XHighContrastGetMode` (5) answers Off and - `XClosedCaptionSetEnabled` (4) is accepted. No voice is installed: `XSpeechSynthesizerEnumerateInstalledVoices` - (8) calls back zero times and returns `S_OK`. `XSpeechSynthesizerCreate` (9) hands out a silent synthesizer handle - (`E_POINTER` for a null out pointer). Close (10), set default voice (11) and set custom voice (12) accept that handle - and refuse any other with `E_INVALIDARG`. Streams from text (13) and SSML (21) are created from it and return a + `XClosedCaptionSetEnabled` (4) is accepted. One silent voice is installed: + `XSpeechSynthesizerEnumerateInstalledVoices(context, callback)` (8) calls back once, with voice id `leonida-silent` + and language `en-US` (the GDK reference's `XSpeechSynthesizerVoiceInformation` layout), and returns `S_OK` + (`E_INVALIDARG` without a callback). `XSpeechSynthesizerCreate` (9) hands + out a synthesizer handle that speaks with it (`E_POINTER` for a null out pointer). Close (10), set default voice (11) + and set custom voice (12, only for that voice id) accept that handle and refuse any other with `E_INVALIDARG`. + Streams from text (13) and SSML (21) are created from it and return a stream handle; its close (14) accepts it. Stream size (15) reports 44 bytes and stream data (16) copies them: a valid RIFF/WAVE header for 16 kHz, 16-bit mono PCM with zero data bytes, so a title that plays narration reads a silent stream (a buffer under 44 bytes gets `ERROR_INSUFFICIENT_BUFFER`). A foreign handle on 15 or 16 gets `E_INVALIDARG`, @@ -470,6 +465,7 @@ on the executable, the rest is not: `XDisplayAcquireTimeoutDeferral` (4) creates a Win32 `PowerRequestDisplayRequired` request and returns its handle (a failing `PowerCreateRequest` or `PowerSetRequest` returns the Win32 error as an HRESULT). `XDisplayCloseTimeoutDeferralHandle` (5) clears that request and closes the handle, so the display may sleep again. + Side effect on the host: while the title holds a deferral, Windows keeps the PC's display on. - **ASSUMPTION:** the parameter lists of the speech calls and `XHighContrastGetMode` (Off is 0), from the GDK reference; only the argument counts were measured, from `tools/gdk_runtime_calls.py` on the executable. - **HDR:** `XDisplayTryEnableHdrMode` answers Disabled, because the host output is SDR. With `LEONIDA_HDR=1` it @@ -497,12 +493,11 @@ layout with the documented argument count, and each behaves as Microsoft's refer | Class | Interface asked for | Slots (args after `this`) | Offline behaviour | |---|---|---|---| -| `XGameRuntimeFeatureImpl` | its class id | 3 `XGameRuntimeIsFeatureAvailable` (1, returns `bool`) | True when `QueryApiImpl` serves the class the feature's functions go through (whichever `xgameruntime*.cpp` serves it) and the feature is documented for Windows: today XAccessibility, XAppCapture, XSpeechSynthesizer, XLauncher, XAsync, XAsyncProvider, XTaskQueue, XThread, XError, XGame, XGameSave, XGameUI, XNetworking, XPackage, XPersistentLocalStorage, XStore, XSystem, XUser, XGameEvent, XGameStreaming. False for XDisplay (served, but documented for the consoles only), for the classes not served (XGameInvite) and for values past the enum | +| `XGameRuntimeFeatureImpl` | its class id | 3 `XGameRuntimeIsFeatureAvailable` (1, returns `bool`) | True when `QueryApiImpl` serves the class the feature's functions go through (whichever `xgameruntime*.cpp` serves it) and the feature is documented for Windows: today XAccessibility, XSpeechSynthesizer, XLauncher, XAsync, XAsyncProvider, XTaskQueue, XThread, XError, XGame, XGameSave, XGameUI, XNetworking, XPackage, XPersistentLocalStorage, XStore, XSystem, XUser, XGameEvent, XGameStreaming. False for XDisplay (served, but documented for the consoles only), for the classes not served (XAppCapture, XGameInvite) and for values past the enum | | `XSystemAnalyticsImpl` | its class id | 3 `XSystemGetAnalyticsInfo` (1: the result's address, as MSVC passes a returned struct to a member function) | The named export's `XSystemAnalyticsInfo` | -Not served yet, though `libHttpClient.GDK.dll` has thunks for them: `XGameInviteImpl`, among others. -`XAppCaptureImpl` is served offline (`runtime/shims/xgameruntime_offline.cpp`): its class and interface ids answer, -`XAppCaptureTakeScreenshot` (5) returns `ERROR_NOT_SUPPORTED`, and slots 3 and 4 go through the unknown-slot path. +Not served yet, though `libHttpClient.GDK.dll` has thunks for them: `XAppCaptureImpl` and `XGameInviteImpl`, +among others. Which classes the package's GDK modules reference, from a byte search for the class and interface GUIDs that xgameruntime-docs lists (16-byte in-memory form, every `.dll` of the package; counts only, nothing else read): @@ -533,9 +528,9 @@ therefore needs no module name beyond the `xgameruntime.dll` it already has, whi | Class | Thunks | Referenced | Served | |---|---:|---:|---| -| `XAccessibilityImpl` | 10 | 9 | yes | -| `XAppCaptureImpl` | 1 | 1 | yes | -| `XLauncherImpl` | 3 | 3 | yes | +| `XAccessibilityImpl` | 10 | 9 | no | +| `XAppCaptureImpl` | 1 | 1 | no | +| `XLauncherImpl` | 3 | 3 | no | | `XDisplayImpl` | 1 | 1 | yes | | `XGameEventImpl` | 1 | 1 | yes | | `XGameImpl` | 2 | 2 | yes | @@ -551,10 +546,10 @@ therefore needs no module name beyond the `xgameruntime.dll` it already has, whi | `XThreadingImpl` | 18 | 17 | yes | | `XUserImpl` | 21 | 21 | yes | -"Served" is the tool's answer for the runtime sources on this branch (`served_classes` over every `runtime/shims/*.cpp`): -every class in the table is served now, `XAppCaptureImpl` and `XLauncherImpl` included. The executable references the -speech-synthesizer slots 8-13, 15, 16 and 21 (slot 14 is not), `XAppCaptureImpl` slot 5 (`XAppCaptureTakeScreenshot`) -and `XLauncherImpl` slots 3-5 (`XLaunchUri` and the two display timeout-deferral calls). The slots of `XUserImpl`, `XStoreImpl` and `XGameSaveImpl` the +"Served" is the tool's answer for the runtime sources at that commit. The three that are not: `XAccessibilityImpl` +(the speech-synthesizer slots 8-13, 15, 16 and 21 are referenced; slot 14 is not), `XAppCaptureImpl` (slot 5, +`XAppCaptureTakeScreenshot`) and `XLauncherImpl` (slots 3-5: `XLaunchUri` and the two display timeout-deferral calls). +Open pull requests serve them: #4235, #4307 and #4248. The slots of `XUserImpl`, `XStoreImpl` and `XGameSaveImpl` the executable calls, and the argument counts the tool estimates from the registers, are in the report the tool writes. `XErrorImpl`, which `XCurl.dll` and `libHttpClient.GDK.dll` call, is not among the executable's classes. diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 65205113b3..64e346f40a 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -125,7 +125,6 @@ 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 @@ -294,18 +293,6 @@ 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 @@ -1185,9 +1172,6 @@ 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 deleted file mode 100644 index 8dc54f2a72..0000000000 --- a/runtime/shims/lifecycle.cpp +++ /dev/null @@ -1,251 +0,0 @@ -// 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-*, 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"), -); diff --git a/runtime/shims/lifecycle.h b/runtime/shims/lifecycle.h deleted file mode 100644 index a3d775738f..0000000000 --- a/runtime/shims/lifecycle.h +++ /dev/null @@ -1,21 +0,0 @@ -// 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/shims/xgameruntime_offline.cpp b/runtime/shims/xgameruntime_offline.cpp index bdcea72a1a..23a5e9d81c 100644 --- a/runtime/shims/xgameruntime_offline.cpp +++ b/runtime/shims/xgameruntime_offline.cpp @@ -1,5 +1,5 @@ -// xgameruntime: XGameEventImpl, XGameUiImpl, XGameStreamingImpl, XDisplayImpl, XUserDeviceImpl, XAccessibilityImpl, -// XLauncherImpl and XAppCaptureImpl, offline: small classes a title calls early. +// xgameruntime: XGameEventImpl, XGameUiImpl, XGameStreamingImpl, XDisplayImpl, XUserDeviceImpl, XAccessibilityImpl +// and XLauncherImpl, offline: small classes a title calls early. // // Each XGameEvent*, XGameUi* and XGameStreaming* function in xgameruntime.lib asks QueryApiImpl for its class and // calls one slot with its own arguments after `this`. The class and interface ids and the method order are @@ -18,19 +18,19 @@ // XUserDeviceImpl every device belongs to the offline user; associations and audio endpoints never change, so // their change registrations are kept until unregistered and never called back; the user has // no audio endpoint of its own; finding a controller shows no UI (as on desktop). -// XAccessibilityImpl high contrast is Off, closed captions can't be configured, no voice is installed (enumerating -// calls back zero times), XSpeechSynthesizerCreate hands out a silent synthesizer whose +// XAccessibilityImpl high contrast is Off, closed captions can't be configured, one silent voice is installed +// (enumerating calls back once), XSpeechSynthesizerCreate hands out a synthesizer whose // text/SSML streams return a valid 44-byte empty 16 kHz mono 16-bit PCM WAVE header so titles // that play narration continue cleanly; speech-to-text display calls fail (E_FAIL). // XLauncherImpl XLaunchUri fails offline (E_FAIL); XDisplayAcquireTimeoutDeferral / Close acquire and clear a // real Win32 PowerRequestDisplayRequired handle so the host display stays awake. -// XAppCaptureImpl implemented offline; TakeScreenshot reports ERROR_NOT_SUPPORTED. // // Slots whose signature the public pages don't give answer with a value that is safe whichever way the caller reads // it: see `client_not_connected` (XGameStreaming) and `offline_failure`. #include #include +#include #include #include #include @@ -606,10 +606,26 @@ HRESULT STDMETHODCALLTYPE accessibility_high_contrast(void*, uint32_t* mode) { // 4: HRESULT XClosedCaptionSetEnabled(bool enabled): there are no captions to show; accepted and dropped. HRESULT STDMETHODCALLTYPE accessibility_captions_set_enabled(void*, bool) { return S_OK; } -// 8: HRESULT XSpeechSynthesizerEnumerateInstalledVoices(callback, void* context): no voice is installed, so the -// callback runs zero times. ASSUMPTION: the argument order (GDK reference), only the count (2) was measured. -HRESULT STDMETHODCALLTYPE speech_enumerate_voices(void*, void* callback, void*) { - return callback ? S_OK : E_INVALIDARG; +// XSpeechSynthesizerVoiceInformation and its callback, in the GDK reference's member order (the gender is +// XSpeechSynthesizerVoiceGender, a uint32_t enum: Female 0, Male 1). +struct SpeechVoiceInformation { + const char* description; + const char* display_name; + uint32_t gender; + const char* voice_id; + const char* language; +}; +static_assert(offsetof(SpeechVoiceInformation, voice_id) == 24 && sizeof(SpeechVoiceInformation) == 40, "x64 layout"); +using InstalledVoicesCallback = bool(CALLBACK*)(const SpeechVoiceInformation* information, void* context); +constexpr SpeechVoiceInformation kSilentVoice = {"Leonida silent voice - English (United States)", + "Leonida silent voice", 0, "leonida-silent", "en-US"}; + +// 8: HRESULT XSpeechSynthesizerEnumerateInstalledVoices(void* context, callback): one voice, the silent one every +// synthesizer below speaks with. ASSUMPTION: the argument order (GDK reference), only the count (2) was measured. +HRESULT STDMETHODCALLTYPE speech_enumerate_voices(void*, void* context, InstalledVoicesCallback callback) { + if (!callback) return E_INVALIDARG; + callback(&kSilentVoice, context); + return S_OK; } // Valid 44-byte RIFF/WAVE header for 16 kHz, 16-bit mono PCM with 0 data bytes (silent speech stream). @@ -639,9 +655,11 @@ HRESULT STDMETHODCALLTYPE speech_set_default_voice(void*, void* handle) { return handle == &g_speech_synth_handle ? S_OK : E_INVALIDARG; } -// 12: HRESULT XSpeechSynthesizerSetCustomVoice(XSpeechSynthesizerHandle handle, const char* voiceId) -HRESULT STDMETHODCALLTYPE speech_set_custom_voice(void*, void* handle, const char*) { - return handle == &g_speech_synth_handle ? S_OK : E_INVALIDARG; +// 12: HRESULT XSpeechSynthesizerSetCustomVoice(XSpeechSynthesizerHandle handle, const char* voiceId): only the +// enumerated voice is installed. +HRESULT STDMETHODCALLTYPE speech_set_custom_voice(void*, void* handle, const char* voice_id) { + if (handle != &g_speech_synth_handle || !voice_id) return E_INVALIDARG; + return std::strcmp(voice_id, kSilentVoice.voice_id) == 0 ? S_OK : E_INVALIDARG; } // 13, 21: HRESULT XSpeechSynthesizerCreateStreamFromText/Ssml(synthesizer, const char* text, @@ -761,40 +779,6 @@ HRESULT STDMETHODCALLTYPE launcher_query_interface(void*, REFIID iid, void** out return answer(&g_launcher_object, &kLauncherClass, &kLauncherClass + 1, iid, out); } -// ======================= XAppCaptureImpl ======================= - -constexpr char kAppCaptureName[] = "XAppCaptureImpl"; -constexpr GUID kAppCaptureClass = {0xa4f1aee2, 0x4bf1, 0x4485, {0xb0, 0x08, 0xa7, 0xc2, 0x6d, 0x52, 0xac, 0x27}}; -const GUID kAppCaptureInterfaces[] = { - kAppCaptureClass, - {0x22e672d7, 0xb4e3, 0x406c, {0xbd, 0x50, 0x8f, 0x0d, 0x25, 0x23, 0x6f, 0x9e}}, // IXAppCaptureImpl -}; - -// 5: HRESULT XAppCaptureTakeScreenshot(XUserHandle user, XAppCaptureTakeScreenshotResult* result) -HRESULT STDMETHODCALLTYPE app_capture_take_screenshot(void*, void*, void*) { - static std::atomic s_logged{false}; - if (!s_logged.exchange(true)) - std::fprintf(stderr, "[rt] xgameruntime: XAppCaptureTakeScreenshot is not supported offline\n"); - return HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED); -} - -template HRESULT STDMETHODCALLTYPE app_capture_unknown(void* self) { - return unknown_slot(self); -} - -HRESULT STDMETHODCALLTYPE app_capture_query_interface(void*, REFIID iid, void** out); -const void* const kAppCaptureVtable[] = { - FN(app_capture_query_interface), FN(object_add_ref), FN(object_release), // 0-2 IUnknown - FN(app_capture_unknown<3>), // 3 diagnostic screenshot - FN(app_capture_unknown<4>), // 4 diagnostic clip - FN(app_capture_take_screenshot), // 5 XAppCaptureTakeScreenshot -}; -static_assert(std::size(kAppCaptureVtable) == 6, "IUnknown + IXAppCaptureImpl slots"); -ClassObject g_app_capture_object{kAppCaptureVtable}; -HRESULT STDMETHODCALLTYPE app_capture_query_interface(void*, REFIID iid, void** out) { - return answer(&g_app_capture_object, std::begin(kAppCaptureInterfaces), std::end(kAppCaptureInterfaces), iid, out); -} - #undef FN } // namespace @@ -831,10 +815,6 @@ bool xgameruntime_offline_query(const GUID& class_id, REFIID interface_id, void* *hr = launcher_query_interface(nullptr, interface_id, out); return true; } - if (class_id == kAppCaptureClass) { - *hr = app_capture_query_interface(nullptr, interface_id, out); - return true; - } return false; } diff --git a/runtime/test/lifecycle_test.cpp b/runtime/test/lifecycle_test.cpp deleted file mode 100644 index 6e6d344c32..0000000000 --- a/runtime/test/lifecycle_test.cpp +++ /dev/null @@ -1,176 +0,0 @@ -// 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"); - 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/runtime/test/xgameruntime_offline_test.cpp b/runtime/test/xgameruntime_offline_test.cpp index ccdb4c7eec..66b1100544 100644 --- a/runtime/test/xgameruntime_offline_test.cpp +++ b/runtime/test/xgameruntime_offline_test.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include @@ -74,7 +75,16 @@ constexpr GUID kAccessibilityClass = {0x3e241977, 0x6237, 0x41e9, {0x85, 0x59, 0 constexpr GUID kAccessibility2 = {0xd722b373, 0x8c4d, 0x4692, {0x9e, 0x51, 0xd6, 0xad, 0x9b, 0x37, 0xaa, 0x7d}}; constexpr GUID kLauncherClass = {0x1b339674, 0x328d, 0x4283, {0xa2, 0x00, 0x31, 0x71, 0xf1, 0x8d, 0x36, 0x39}}; -using EnumVoices = HRESULT(STDMETHODCALLTYPE*)(void*, void*, void*); +struct VoiceInformation { // XSpeechSynthesizerVoiceInformation, the GDK reference's member order + const char* description; + const char* display_name; + uint32_t gender; + const char* voice_id; + const char* language; +}; +using VoiceCallback = bool(CALLBACK*)(const VoiceInformation*, void*); +using EnumVoices = HRESULT(STDMETHODCALLTYPE*)(void*, void* context, VoiceCallback callback); +using SetCustomVoice = HRESULT(STDMETHODCALLTYPE*)(void*, void*, const char*); using SpeechCreate = HRESULT(STDMETHODCALLTYPE*)(void*, void**); using SpeechClose = HRESULT(STDMETHODCALLTYPE*)(void*, void*); using SpeechStream = HRESULT(STDMETHODCALLTYPE*)(void*, void*, const char*, void**); @@ -93,6 +103,19 @@ void* user_object(HRESULT(WINAPI* query)(const GUID*, REFIID, void**)) { void CALLBACK on_state(void*, uint64_t, uint32_t) {} +struct VoicesSeen { + int count = 0; + std::string voice_id; + std::string language; +}; +bool CALLBACK on_voice(const VoiceInformation* info, void* context) { + auto* seen = static_cast(context); + ++seen->count; + seen->voice_id = info && info->voice_id ? info->voice_id : ""; + seen->language = info && info->language ? info->language : ""; + return true; +} + // XUserDeviceImpl slots 4/5 (device association) and 7/8 (default audio endpoint): kept until unregistered, never // called back offline. long g_device_callbacks = 0; @@ -290,9 +313,12 @@ int main() { "XHighContrastGetMode reports Off"); check(at(acc, 4)(acc, true) == S_OK, "XClosedCaptionSetEnabled is accepted"); check(FAILED(at(acc, 3)(acc)), "the closed-caption properties are not available offline"); - check(at(acc, 8)(acc, reinterpret_cast(&on_state), nullptr) == S_OK && - at(acc, 8)(acc, nullptr, nullptr) == E_INVALIDARG, - "XSpeechSynthesizerEnumerateInstalledVoices: no voices, S_OK (a callback is required)"); + VoicesSeen seen; + check(at(acc, 8)(acc, &seen, &on_voice) == S_OK && seen.count == 1 && + seen.voice_id == "leonida-silent" && seen.language == "en-US", + "XSpeechSynthesizerEnumerateInstalledVoices(context, callback): one silent voice, its context passed back"); + check(at(acc, 8)(acc, nullptr, nullptr) == E_INVALIDARG, + "XSpeechSynthesizerEnumerateInstalledVoices: a callback is required"); void* synth = nullptr; check(at(acc, 9)(acc, &synth) == S_OK && synth != nullptr && at(acc, 9)(acc, nullptr) == E_POINTER, @@ -303,6 +329,10 @@ int main() { at(acc, 12)(acc, nullptr) == E_INVALIDARG && at(acc, 14)(acc, nullptr) == E_INVALIDARG, "close and set-voice calls on a null handle: E_INVALIDARG"); check(at(acc, 11)(acc, synth) == S_OK, "XSpeechSynthesizerSetDefaultVoice succeeds on valid handle"); + check(at(acc, 12)(acc, synth, seen.voice_id.c_str()) == S_OK && + at(acc, 12)(acc, synth, "not-installed") == E_INVALIDARG && + at(acc, 12)(acc, synth, nullptr) == E_INVALIDARG, + "XSpeechSynthesizerSetCustomVoice accepts the enumerated voice only"); check(at(acc, 13)(acc, nullptr, "hi", &stream) == E_INVALIDARG && stream == nullptr, "CreateStreamFromText on a null synthesizer: E_INVALIDARG, no stream"); check(at(acc, 13)(acc, synth, "Hello", &stream) == S_OK && stream != nullptr, @@ -350,20 +380,6 @@ int main() { check(query(&kLauncherClass, other, &none) == E_NOINTERFACE && none == nullptr, "XLauncherImpl refuses an interface id it doesn't implement"); - // ---- XAppCapture ---- - const GUID kAppCaptureClass = {0xa4f1aee2, 0x4bf1, 0x4485, {0xb0, 0x08, 0xa7, 0xc2, 0x6d, 0x52, 0xac, 0x27}}; - const GUID kAppCaptureIid = {0x22e672d7, 0xb4e3, 0x406c, {0xbd, 0x50, 0x8f, 0x0d, 0x25, 0x23, 0x6f, 0x9e}}; - void* capture = nullptr; - void* capture_iid = nullptr; - check(query(&kAppCaptureClass, kAppCaptureClass, &capture) == S_OK && capture && - query(&kAppCaptureClass, kAppCaptureIid, &capture_iid) == S_OK && capture_iid == capture, - "XAppCaptureImpl answers its class id and interface id"); - if (capture) { - using TakeShot = HRESULT(STDMETHODCALLTYPE*)(void*, void*, void*); - check(at(capture, 5)(capture, nullptr, nullptr) == HRESULT_FROM_WIN32(ERROR_NOT_SUPPORTED), - "XAppCaptureTakeScreenshot returns ERROR_NOT_SUPPORTED offline"); - } - std::printf("xgameruntime_offline_test: %d checks, %d failures\n", g_checks, g_failures); return g_failures == 0 ? 0 : 1; } diff --git a/runtime/test/xgameruntime_test.cpp b/runtime/test/xgameruntime_test.cpp index 0a040fdfbb..af67045d42 100644 --- a/runtime/test/xgameruntime_test.cpp +++ b/runtime/test/xgameruntime_test.cpp @@ -254,6 +254,7 @@ void check_measured_classes(QueryFn query, XSystemAnalyticsInfo (*named_analytic // Classes nobody serves are still refused, and logged, as before. const GUID refused[] = { + {0xa4f1aee2, 0x4bf1, 0x4485, {0xb0, 0x08, 0xa7, 0xc2, 0x6d, 0x52, 0xac, 0x27}}, // XAppCaptureImpl {0x12345678, 0x9abc, 0xdef0, {0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0}}, // no such class }; bool all_refused = true; @@ -261,7 +262,7 @@ void check_measured_classes(QueryFn query, XSystemAnalyticsInfo (*named_analytic void* out = reinterpret_cast(1); all_refused = all_refused && query(&cls, cls, &out) == static_cast(0x80070032) && out == nullptr; } - check(all_refused, "an unknown class is still refused"); + check(all_refused, "XAppCaptureImpl and an unknown class are still refused"); } // xgameruntime.lib's thunks don't import the runtime: they LoadLibraryW(L"xgameruntime.dll") and GetProcAddress five diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1 index 1483b12427..8bd74d1cf1 100644 --- a/scripts/build_runtime.ps1 +++ b/scripts/build_runtime.ps1 @@ -81,14 +81,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\lifecycle.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\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 user32.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 || 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 diff --git a/tests/test_gdk_runtime_calls.py b/tests/test_gdk_runtime_calls.py index 614905235f..d9f2d9426a 100644 --- a/tests/test_gdk_runtime_calls.py +++ b/tests/test_gdk_runtime_calls.py @@ -417,8 +417,7 @@ def test_the_default_source_is_every_runtime_shim(self): # xgameruntime.cpp serves XGameRuntimeFeatureImpl; the ids its feature table only names (k...ClassId) don't count. self.assertEqual(served.get("8836fe87-edb9-4fe3-8dad-05f0d2cd5b40"), "kGameRuntimeFeatureClass") self.assertEqual(served.get("1b339674-328d-4283-a200-3171f18d3639"), "kLauncherClass") # XLauncherImpl, xgameruntime_offline.cpp - self.assertEqual(served.get("a4f1aee2-4bf1-4485-b008-a7c26d52ac27"), "kAppCaptureClass") # XAppCaptureImpl, xgameruntime_offline.cpp - self.assertNotIn("0651aae2-4012-4077-bf84-8b9097090e2c", served) # XGameInviteImpl + self.assertNotIn("a4f1aee2-4bf1-4485-b008-a7c26d52ac27", served) # XAppCaptureImpl empty = os.path.join(self.tmp, "no-shims") os.makedirs(empty, exist_ok=True) with self.assertRaises(OSError):