From 95f0f67562aaff1610d639b55dd0a603928ec4f5 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 25 Nov 2026 13:04:47 +0000 Subject: [PATCH 1/4] runtime: rewrite bound delay QueryApiImpl and always log it Account-picker TRACE_API still shows zero providers after the scoped package GPA patch. Delay-imported QueryApiImpl binds through the CRT helper (unhooked GetProcAddress), so the title keeps calling the real export. Rewrite that slot only after it equals the remembered export; leave unbound thunks alone. Always log GetProcAddress("QueryApiImpl") past the generic 40-line GPA cap, and record how the real export was first remembered. Synthetic PE control covers bound vs unbound delay slots; the Windows scope fixture delay-loads QueryApiImpl with unbound and pre-attach-cache negatives. Refs #870. Co-authored-by: SimSalabimse --- CMakeLists.txt | 17 +++- docs/startup-runtime.md | 2 +- src/startup_stubs/runtime_gpa_patch.h | 21 ++++- src/startup_stubs/runtime_proxy.cpp | 96 ++++++++++++++------ tests/startup_runtime_gpa_patch_check.cpp | 54 ++++++++--- tests/startup_runtime_proxy_scope/helper.cpp | 8 ++ tests/startup_runtime_proxy_scope/helper.def | 1 + tests/startup_runtime_proxy_scope/host.cpp | 66 +++++++++++++- 8 files changed, 212 insertions(+), 53 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 4eb247b362..b1aac31e4a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -965,7 +965,9 @@ add_test(NAME startup_runtime_gpa_patch COMMAND startup_runtime_gpa_patch) add_test(NAME startup_runtime_gpa_patch_name_only_control COMMAND startup_runtime_gpa_patch --mutate name-only) set_tests_properties(startup_runtime_gpa_patch_name_only_control PROPERTIES PASS_REGULAR_EXPRESSION "FAIL: ") # EXE + late-loaded package helper through the real Windows loader: proxied xgameruntime QueryApiImpl, -# unrelated same-named export stays original. Notification only enqueues; rewrite runs after link. +# unrelated same-named export stays original, bound delay QueryApiImpl is rewritten, unbound delay +# thunk and a pre-attach cached pointer are negative controls. Notification only enqueues; rewrite +# runs after link. if (WIN32) set(X2W_PROXY_SCOPE_DIR "${CMAKE_CURRENT_BINARY_DIR}/startup_runtime_proxy_scope") add_library(startup_runtime_proxy_carrier SHARED @@ -974,20 +976,25 @@ if (WIN32) target_include_directories(startup_runtime_proxy_carrier PRIVATE src) target_compile_features(startup_runtime_proxy_carrier PRIVATE cxx_std_17) target_link_libraries(startup_runtime_proxy_carrier PRIVATE psapi) - add_library(startup_runtime_proxy_helper SHARED - tests/startup_runtime_proxy_scope/helper.cpp - tests/startup_runtime_proxy_scope/helper.def) - target_compile_features(startup_runtime_proxy_helper PRIVATE cxx_std_17) add_library(startup_runtime_proxy_xgr SHARED tests/startup_runtime_proxy_scope/xgameruntime.cpp tests/startup_runtime_proxy_scope/xgameruntime.def) target_compile_features(startup_runtime_proxy_xgr PRIVATE cxx_std_17) set_target_properties(startup_runtime_proxy_xgr PROPERTIES OUTPUT_NAME xgameruntime) + add_library(startup_runtime_proxy_helper SHARED + tests/startup_runtime_proxy_scope/helper.cpp + tests/startup_runtime_proxy_scope/helper.def) + target_compile_features(startup_runtime_proxy_helper PRIVATE cxx_std_17) + # Delay-load the fake xgameruntime so the helper's QueryApiImpl slot starts as a thunk and only + # holds the real export after first use (the bound-delay rewrite path). + target_link_libraries(startup_runtime_proxy_helper PRIVATE startup_runtime_proxy_xgr delayimp) + target_link_options(startup_runtime_proxy_helper PRIVATE "/DELAYLOAD:xgameruntime.dll") add_library(startup_runtime_proxy_decoy SHARED tests/startup_runtime_proxy_scope/decoy.cpp tests/startup_runtime_proxy_scope/decoy.def) target_compile_features(startup_runtime_proxy_decoy PRIVATE cxx_std_17) add_executable(startup_runtime_proxy_scope tests/startup_runtime_proxy_scope/host.cpp) + target_include_directories(startup_runtime_proxy_scope PRIVATE src) target_compile_features(startup_runtime_proxy_scope PRIVATE cxx_std_17) foreach(tgt IN ITEMS startup_runtime_proxy_carrier startup_runtime_proxy_helper startup_runtime_proxy_xgr startup_runtime_proxy_decoy startup_runtime_proxy_scope) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 6923db7f78..9c2b063dad 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1157,7 +1157,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_HIDE_TITLE_WINDOW=1` (`run.sh --hide-title-window`) | once a present has reached the output window, hides the title's own window; dialogs stay visible, and the window is shown again when a present misses the output window, until the next present reaches it ([Output window and fallback diagnostics](#output-window-and-fallback-diagnostics)). Keyboard input to the title after the hide is not measured. Off by default on every host | | `X2W_DRAW_DUMP_FRAME=`, `X2W_DRAW_DUMP_DIR` | Full-resolution RGB snapshots of single-sample RGBA8/BGRA8 UNORM or sRGB targets after translated draws. A later present writes completed queue-fenced copies. At most 48 copies are pending or written; a copy whose fence reports device removal (`UINT64_MAX`) is released unwritten and frees its slot (`src/startup_stubs/draw_dump_tracking.h`, `ctest --preset dev --no-tests=error -R '^startup_dump_fence_(removed_control_)?warp$' -V`; the control must fail). | | `X2W_AUDIO_PERMISSIVE=1` | enables the audio stand-ins. Without a DSP provider, `XDspActivate` clears valid outputs and reports unavailable resources, and failed `XDspSubmitCommand` calls leave the sequence unchanged. `XDspDeactivate` and `XDspDisconnect` refuse null and unknown handles with `E_INVALIDARG`. | -| `X2W_RUNTIME_PROXY=1` | proxies the gaming runtime and logs every call. Rewrites regular-IAT `GetProcAddress` and a direct `xgameruntime.dll!QueryApiImpl` import on the main EXE and on DLLs that share its directory (package helpers). Dynamic `QueryApiImpl` / `InitializeApiImpl*` are wrapped only when the provider module's basename is `xgameruntime.dll`. `LdrRegisterDllNotification` only flags that another scan is needed. A worker holds each matching module live while rewriting after linking. Loading a helper and immediately calling it can precede the scan. The enabled proxy stays loaded until process exit. Delay-import IAT slots are not rewritten. Skips this stand-in's own `GetProcAddress` IAT so the hook does not recurse (`src/startup_stubs/runtime_gpa_patch.h`, `ctest --preset dev --no-tests=error -R '^startup_runtime_gpa_patch(_name_only_control)?$'`, and the control must print `FAIL:`; Windows also runs `startup_runtime_proxy_scope` for a late-loaded helper through the real loader) | +| `X2W_RUNTIME_PROXY=1` | proxies the gaming runtime and logs every call. Rewrites regular-IAT `GetProcAddress` and a direct `xgameruntime.dll!QueryApiImpl` import on the main EXE and on DLLs that share its directory (package helpers). Dynamic `QueryApiImpl` / `InitializeApiImpl*` are wrapped only when the provider module's basename is `xgameruntime.dll`. `LdrRegisterDllNotification` only flags that another scan is needed. A worker holds each matching module live while rewriting after linking. Loading a helper and immediately calling it can precede the scan. The enabled proxy stays loaded until process exit. Unbound delay-import IAT slots are left alone; a delay `QueryApiImpl` slot that already holds the real export is rewritten to the proxy on a later scan. `GetProcAddress("QueryApiImpl")` is always logged (generic GPA lines stay capped). Skips this stand-in's own `GetProcAddress` IAT so the hook does not recurse (`src/startup_stubs/runtime_gpa_patch.h`, `ctest --preset dev --no-tests=error -R '^startup_runtime_gpa_patch(_name_only_control)?$'`, and the control must print `FAIL:`; Windows also runs `startup_runtime_proxy_scope` for a late-loaded helper through the real loader) | | `X2W_FAKE_USER=1` | answers the user, gamertag and save APIs for one local user, and creates one offline store context for that user | | `X2W_RUNTIME_LOCAL=1` | with `X2W_RUNTIME_PROXY` and `X2W_FAKE_USER`, for a host where the system gaming runtime cannot initialize (no Gaming Services). The first failed `InitializeApiImpl*` is reported as `S_OK`, and every later initialization call returns `S_OK` without calling the real export. Once initialization failure is latched, a failed real `QueryApiImpl` call can fall back only with an exact match of both GUIDs to a supported provider/interface pair for user (including gamertag), game save, package, title, connectivity or store. Persistent local storage uses its existing fake-user gate and requires its exact provider GUID and IID. Unmatched failed queries keep the real HRESULT. The proxy clears a writable output on failure only when fake user is enabled and the initialization failure is latched. A local object's `QueryInterface` accepts only `IID_IUnknown` and the IID it was created for. The local answers above apply, calls that carry the local user or store handle fail as before, and other unanswered methods return `E_NOTIMPL`. `XUserAddAsync` and async operations completed on behalf of a local answer require the real runtime's `QueryApiImpl` to return the XAsync provider (`073b7dcb`). Those operations complete with `S_OK` through XAsync, or return the query failure if XAsync is unavailable (`ctest --preset dev --no-tests=error -R '^startup_runtime_local(_control)?$'`, and the control must print `FAIL:`). | | `X2W_STORAGE_PATH`, `X2W_STORAGE_MB`, `X2W_TITLE_ID` | persistent local storage and the manifest values the runtime would return. The path is UTF-8, with a trailing separator added when missing. If the path is invalid or exceeds 259 bytes including the separator, the proxy logs the refusal and uses `S:\` (`src/startup_stubs/storage_root_utf8.h`, `ctest --preset release --no-tests=error -R '^startup_storage_root'`). | diff --git a/src/startup_stubs/runtime_gpa_patch.h b/src/startup_stubs/runtime_gpa_patch.h index e5b23da826..42f8e0fc8d 100644 --- a/src/startup_stubs/runtime_gpa_patch.h +++ b/src/startup_stubs/runtime_gpa_patch.h @@ -4,10 +4,11 @@ // resolves QueryApiImpl through a package helper's GetProcAddress (or that imports QueryApiImpl from // xgameruntime.dll by name) never hits that hook, so FakeUser / X2W_TRACE_API see no providers. // This header lists the import shapes to notice — regular and delay-import tables. The stand-in -// rewrites only regular IAT slots on the EXE and package-directory helpers: a delay IAT holds a -// delay-load thunk until first use, so treating it as GetProcAddress or QueryApiImpl is wrong. -// Ordinal imports are ignored. Pure walk helpers — no Windows calls — so a source-built control can -// check them. +// rewrites regular GetProcAddress / QueryApiImpl IAT slots on the EXE and package-directory helpers. +// A delay IAT holds a delay-load thunk until first use; rewriting that thunk as if it were the +// export is wrong. After the delay helper binds, the same slot holds the real export address and +// may be rewritten to the proxy (see delay_query_slot_is_bound). Ordinal imports are ignored. +// Pure walk helpers — no Windows calls — so a source-built control can check them. #pragma once #include @@ -49,6 +50,15 @@ inline bool import_is_query_api_impl(const char* name) noexcept return name && std::strcmp(name, "QueryApiImpl") == 0; } +// True when a delay-import QueryApiImpl IAT slot already holds the real export (post-bind) and is +// not yet the proxy. A still-unbound thunk (any other non-zero value, typically inside the +// importer) must stay untouched so the delay helper can run. +inline bool delay_query_slot_is_bound(std::uint64_t slot_value, std::uint64_t real_query, + std::uint64_t proxy) noexcept +{ + return real_query != 0 && slot_value != 0 && slot_value != proxy && slot_value == real_query; +} + // Decide whether one named import of `dll_name` should be noticed. Ordinal imports are ignored. inline bool classify(const char* dll_name, const char* import_name, Kind* kind) noexcept { @@ -171,7 +181,8 @@ int visit_imports(const unsigned char* base, std::size_t image_size, Fn on_hit) } } - // DataDirectory[13] = delay imports (reported with delay_import=true; callers must not rewrite the slot as a real export). + // DataDirectory[13] = delay imports (reported with delay_import=true; rewrite only when + // delay_query_slot_is_bound says the slot already holds the real export). const auto& delay_dir = dirs[13]; if (delay_dir.virtual_address && delay_dir.size) { for (std::uint32_t at = delay_dir.virtual_address;; at += sizeof(DelayDesc)) { diff --git a/src/startup_stubs/runtime_proxy.cpp b/src/startup_stubs/runtime_proxy.cpp index 7c9a170462..f35d53b394 100644 --- a/src/startup_stubs/runtime_proxy.cpp +++ b/src/startup_stubs/runtime_proxy.cpp @@ -7,9 +7,11 @@ // (package helpers). Dynamic QueryApiImpl is wrapped only when the provider module's basename is // xgameruntime.dll. The pre-link load notification only requests another scan. A worker scans // and rewrites linked modules outside the notification, keeping each module live while it is patched. -// Enabled proxies remain loaded until process exit. Delay-import IAT slots are not -// rewritten. The wrapper hands out proxy objects whose methods log their first calls ("x2w-runtime") -// and forward to the real object. +// Enabled proxies remain loaded until process exit. Unbound delay-import IAT slots are left alone; +// once a delay QueryApiImpl slot holds the real export, a later scan rewrites it to the proxy. +// GetProcAddress("QueryApiImpl") is always logged (the generic GPA log stays capped). The wrapper +// hands out proxy objects whose methods log their first calls ("x2w-runtime") and forward to the +// real object. // // X2W_FAKE_USER=1 additionally answers the user API for one local user (see fake_user below) // and, while the proxy is on, XStoreCreateContext for that user (see area_call). @@ -70,12 +72,16 @@ bool keep_forward_target(FARPROC target) noexcept #endif } -bool remember_real_query(QueryApi query) noexcept +bool remember_real_query(QueryApi query, const char* source) noexcept { QueryApi expected = real_query.load(std::memory_order_acquire); if (expected) return expected == query; if (!keep_forward_target(reinterpret_cast(query))) return false; - return real_query.compare_exchange_strong(expected, query, std::memory_order_acq_rel) || expected == query; + if (!real_query.compare_exchange_strong(expected, query, std::memory_order_acq_rel)) + return expected == query; + x2w_local::logf("x2w-runtime QueryApiImpl remembered via %s -> %p", source ? source : "?", + static_cast(query)); + return true; } QueryApi load_real_query() noexcept { return real_query.load(std::memory_order_acquire); } @@ -489,10 +495,14 @@ FARPROC WINAPI hooked_get_proc_address(HMODULE module, LPCSTR name) const FARPROC real = GetProcAddress(module, name); if (real && reinterpret_cast(name) > 0xffff) { static LONG logged; - if (x2w_local::first_calls(logged, 40)) x2w_local::logf("x2w-runtime GetProcAddress(%p, \"%s\") -> %p", static_cast(module), name, static_cast(real)); + const bool query_name = std::strcmp(name, "QueryApiImpl") == 0; + // Always log QueryApiImpl so a late lookup is visible past the generic 40-line GPA cap. + if (query_name || x2w_local::first_calls(logged, 40)) + x2w_local::logf("x2w-runtime GetProcAddress(%p, \"%s\") -> %p", static_cast(module), name, + static_cast(real)); // Wrap gaming-runtime exports only when the provider module is xgameruntime.dll. - if (module_is_xgameruntime(module) && std::strcmp(name, "QueryApiImpl") == 0 && - remember_real_query(reinterpret_cast(real))) + if (module_is_xgameruntime(module) && query_name && + remember_real_query(reinterpret_cast(real), "gpa")) return reinterpret_cast(&proxy_query); if (runtime_local() && fake_user() && module_is_xgameruntime(module)) { static constexpr InitApi wrappers[3] = {&proxy_init<0>, &proxy_init<1>, &proxy_init<2>}; @@ -512,12 +522,21 @@ void remember_real_query_from_export() noexcept const HMODULE runtime = GetModuleHandleW(L"xgameruntime.dll"); if (!runtime || !module_is_xgameruntime(runtime)) return; // This stand-in's own GetProcAddress IAT is left unpatched, so this is the real export lookup. - remember_real_query(reinterpret_cast(GetProcAddress(runtime, "QueryApiImpl"))); + remember_real_query(reinterpret_cast(GetProcAddress(runtime, "QueryApiImpl")), "export"); +} + +void log_query_status_once() noexcept +{ + static LONG logged; + const HMODULE runtime = GetModuleHandleW(L"xgameruntime.dll"); + if (!runtime || !x2w_local::first_calls(logged, 1)) return; + x2w_local::logf("x2w-runtime QueryApiImpl status: xgameruntime loaded, real_query=%p", + static_cast(load_real_query())); } // Rewrite one module's regular GetProcAddress / xgameruntime.dll!QueryApiImpl IAT slots. -// Delay-import hits are not rewritten (slot is a delay thunk until first use). Caller must hold the -// module live (pin) for the duration of the rewrite. +// Unbound delay-import slots stay untouched. A delay QueryApiImpl slot that already holds the real +// export is rewritten to the proxy. Caller must hold the module live (pin) for the rewrite. int patch_module(HMODULE module) { if (!module || !module_is_exe_or_package_helper(module)) return 0; @@ -528,16 +547,28 @@ int patch_module(HMODULE module) if (nt->Signature != IMAGE_NT_SIGNATURE || nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) return 0; const auto image_size = static_cast(nt->OptionalHeader.SizeOfImage); const bool self = module == proxy_module; + const ULONGLONG proxy = reinterpret_cast(&proxy_query); int patched = 0; x2w_runtime_patch::visit_imports(base, image_size, [&](const x2w_runtime_patch::Hit& hit) { // Never rewrite this DLL's GetProcAddress: hooked_get_proc_address calls it for the real lookup. if (self && hit.kind == x2w_runtime_patch::Kind::get_proc_address) return; + auto* slot = reinterpret_cast(base + hit.first_thunk_rva); if (hit.delay_import) { - // Delay IAT holds a thunk, not the export. Do not rewrite; delay GetProcAddress is unhooked. - if (hit.kind == x2w_runtime_patch::Kind::query_api_impl) remember_real_query_from_export(); + // Delay GetProcAddress stays unhooked (CRT delay helper uses its own lookup). + if (hit.kind != x2w_runtime_patch::Kind::query_api_impl) return; + remember_real_query_from_export(); + const QueryApi real = load_real_query(); + if (!x2w_runtime_patch::delay_query_slot_is_bound(*slot, reinterpret_cast(real), proxy)) + return; + DWORD old = 0; + if (!VirtualProtect(slot, 8, PAGE_READWRITE, &old)) return; + if (*slot != proxy) { + *slot = proxy; + ++patched; + } + VirtualProtect(slot, 8, old, &old); return; } - auto* slot = reinterpret_cast(base + hit.first_thunk_rva); DWORD old = 0; if (!VirtualProtect(slot, 8, PAGE_READWRITE, &old)) return; if (hit.kind == x2w_runtime_patch::Kind::get_proc_address) { @@ -547,9 +578,8 @@ int patch_module(HMODULE module) } } else if (hit.kind == x2w_runtime_patch::Kind::query_api_impl) { // Regular import: slot holds the real export after the loader bound it. - if (*slot != reinterpret_cast(&proxy_query) && - remember_real_query(reinterpret_cast(*slot))) { - *slot = reinterpret_cast(&proxy_query); + if (*slot != proxy && remember_real_query(reinterpret_cast(*slot), "iat")) { + *slot = proxy; ++patched; } } @@ -559,14 +589,14 @@ int patch_module(HMODULE module) } // Pin the module, rewrite after linking, then drop the pin. Safe outside LdrDllNotification. -int patch_module_pinned(void* dll_base) +int patch_module_pinned(void* dll_base, bool announce) { if (!dll_base) return 0; HMODULE pinned = nullptr; if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, reinterpret_cast(dll_base), &pinned) || !pinned) return 0; const int n = patch_module(pinned); - if (n > 0) { + if (n > 0 && announce) { char name[64] = "?"; wchar_t path[MAX_PATH]{}; const DWORD length = GetModuleFileNameW(pinned, path, MAX_PATH); @@ -600,8 +630,9 @@ void CALLBACK dll_loaded(ULONG reason, const void*, void*) rescan_package_modules.store(true, std::memory_order_release); } -void patch_package_modules() +void patch_package_modules(bool announce) { + log_query_status_once(); std::vector modules(512); DWORD needed = 0; if (!EnumProcessModules(GetCurrentProcess(), modules.data(), static_cast(modules.size() * sizeof(HMODULE)), &needed) || !needed) @@ -625,15 +656,23 @@ void patch_package_modules() for (unsigned i = 0; i < count; ++i) { if (!module_is_exe_or_package_helper(modules[i])) continue; ++considered; - const int n = patch_module_pinned(modules[i]); + // Per-module lines only when a slot changed; quiet scans still report those rewrites. + const int n = patch_module_pinned(modules[i], true); if (n > 0) { ++modules_patched; slots += n; } } - if (slots > 0 || considered > 0) - x2w_local::logf("x2w-runtime proxy: %d import(s) in %u of %u package module(s) (%u loaded scanned)", slots, modules_patched, - considered, count); + // Announce every load-driven scan; quiet periodic passes only speak when they rewrote a slot + // (bound delay QueryApiImpl after first use). + if (announce) { + if (slots > 0 || considered > 0) + x2w_local::logf("x2w-runtime proxy: %d import(s) in %u of %u package module(s) (%u loaded scanned)", slots, + modules_patched, considered, count); + } else if (slots > 0) { + x2w_local::logf("x2w-runtime proxy: %d bound delay QueryApiImpl import(s) rewritten (%u of %u package, %u loaded)", + slots, modules_patched, considered, count); + } } // Patch the main EXE immediately. The load notice only requests another worker scan. @@ -659,11 +698,14 @@ void patch_imports() } if (HANDLE worker = CreateThread(nullptr, 0, [](void*) -> DWORD { // Outside DllMain and the pre-link notification. Clear the request before each scan so - // loads that arrive during the scan are picked up on the next pass. + // loads that arrive during the scan are picked up on the next pass. Periodic quiet passes + // catch delay QueryApiImpl slots that bind after the load-driven scan. rescan_package_modules.store(true, std::memory_order_release); - for (;;) { + for (unsigned tick = 0;; ++tick) { if (rescan_package_modules.exchange(false, std::memory_order_acq_rel)) - patch_package_modules(); + patch_package_modules(true); + else if (tick % 10 == 0) + patch_package_modules(false); Sleep(25); } }, nullptr, 0, nullptr)) { diff --git a/tests/startup_runtime_gpa_patch_check.cpp b/tests/startup_runtime_gpa_patch_check.cpp index 310c0a29ef..5a0b21d751 100644 --- a/tests/startup_runtime_gpa_patch_check.cpp +++ b/tests/startup_runtime_gpa_patch_check.cpp @@ -2,9 +2,10 @@ // // Which PE imports the stand-in notices on the EXE / package-helper import tables: GetProcAddress and // a direct xgameruntime.dll!QueryApiImpl on the regular import table, delay-import hits with -// delay_import set (without treating the delay IAT as a real export), and ordinal thunks ignored. -// A synthetic PE32+ image is walked; the mutated control classifies by import name alone (accepting -// QueryApiImpl from other.dll) and must fail. No Windows loader and no game files. +// delay_import set, and ordinal thunks ignored. Bound delay QueryApiImpl slots (slot == real export) +// are safe to rewrite; unbound thunks are not. A synthetic PE32+ image is walked; the mutated +// control classifies by import name alone (accepting QueryApiImpl from other.dll) and must fail. +// No Windows loader and no game files. #include "startup_stubs/runtime_gpa_patch.h" #include @@ -32,8 +33,8 @@ std::vector build_image() using patch::ImportDesc; using patch::Thunk64; // Layout must keep the import-descriptor array clear of the OFT/IAT/name RVAs it points at. - // Descriptors at 0x200 (2×20 → 0x228); delay desc at 0x400; thunks and strings above those. - std::vector image(0x600, 0); + // Descriptors at 0x200 (2×20 → 0x228); delay descs at 0x400; thunks and strings above those. + std::vector image(0x700, 0); auto* dos = reinterpret_cast(image.data()); dos->e_magic = 0x5A4D; dos->e_lfanew = 0x80; @@ -44,7 +45,7 @@ std::vector build_image() dirs[1].virtual_address = 0x200; dirs[1].size = sizeof(ImportDesc) * 2; dirs[13].virtual_address = 0x400; - dirs[13].size = sizeof(DelayDesc); + dirs[13].size = sizeof(DelayDesc) * 2; auto* imp = reinterpret_cast(image.data() + 0x200); imp[0].original_first_thunk = 0x240; @@ -85,9 +86,9 @@ std::vector build_image() // Delay-load kernel32!GetProcAddress — reported with delay_import; not a regular IAT rewrite target. auto* delay = reinterpret_cast(image.data() + 0x400); - delay->dll_name = 0x480; - delay->original_first_thunk = 0x4A0; - delay->first_thunk = 0x4B0; + delay[0].dll_name = 0x480; + delay[0].original_first_thunk = 0x4A0; + delay[0].first_thunk = 0x4B0; std::memcpy(image.data() + 0x480, "KERNEL32.dll", 13); reinterpret_cast(image.data() + 0x4A0)[0].value = 0x4C0; reinterpret_cast(image.data() + 0x4B0)[0].value = 0x3000; @@ -95,6 +96,19 @@ std::vector build_image() std::memcpy(image.data() + 0x4C2, "GetProcAddress", 15); reinterpret_cast(image.data() + 0x4A0)[1].value = 0; reinterpret_cast(image.data() + 0x4B0)[1].value = 0; + + // Delay-load xgameruntime!QueryApiImpl — noticed, but only rewriteable after the slot equals the + // real export (bound). Slot starts as an in-image thunk value. + delay[1].dll_name = 0x500; + delay[1].original_first_thunk = 0x520; + delay[1].first_thunk = 0x530; + std::memcpy(image.data() + 0x500, "xgameruntime.dll", 17); + reinterpret_cast(image.data() + 0x520)[0].value = 0x540; + reinterpret_cast(image.data() + 0x530)[0].value = 0x1400; // unbound thunk stand-in + image[0x540] = image[0x541] = 0; + std::memcpy(image.data() + 0x542, "QueryApiImpl", 13); + reinterpret_cast(image.data() + 0x520)[1].value = 0; + reinterpret_cast(image.data() + 0x530)[1].value = 0; return image; } } @@ -124,6 +138,13 @@ int main(int argc, char** argv) check("QueryApiImpl other dll refused", !patch::classify("other.dll", "QueryApiImpl", &kind)); check("unrelated refused", !patch::classify("xgameruntime.dll", "SomethingElse", &kind)); + constexpr std::uint64_t real_export = 0x7FF012340000ull; + constexpr std::uint64_t proxy = 0x7FF0ABCD0000ull; + check("bound delay slot matches real", patch::delay_query_slot_is_bound(real_export, real_export, proxy)); + check("unbound thunk refused", !patch::delay_query_slot_is_bound(0x1400, real_export, proxy)); + check("already proxied refused", !patch::delay_query_slot_is_bound(proxy, real_export, proxy)); + check("empty real refused", !patch::delay_query_slot_is_bound(real_export, 0, proxy)); + auto image = build_image(); int gpa = 0, query = 0, delay_hits = 0, regular_hits = 0; std::vector rvas; @@ -135,11 +156,16 @@ int main(int argc, char** argv) else if (hit.kind == patch::Kind::query_api_impl) ++query; }); check("visit finds GetProcAddress (import + delay)", gpa == 2); - check("visit finds one xgameruntime QueryApiImpl", query == 1); - check("visit hit count", hits == 3); - check("ordinal import skipped", gpa == 2 && hits == 3); - check("delay vs regular hits", delay_hits == 1 && regular_hits == 2); - check("first thunk RVAs", rvas.size() == 3 && rvas[0] == 0x270 && rvas[1] == 0x278 && rvas[2] == 0x4B0); + check("visit finds regular + delay QueryApiImpl", query == 2); + check("visit hit count", hits == 4); + check("ordinal import skipped", gpa == 2 && hits == 4); + check("delay vs regular hits", delay_hits == 2 && regular_hits == 2); + check("first thunk RVAs", + rvas.size() == 4 && rvas[0] == 0x270 && rvas[1] == 0x278 && rvas[2] == 0x4B0 && rvas[3] == 0x530); + + const auto unbound = *reinterpret_cast(image.data() + 0x530); + check("synthetic delay QueryApiImpl still unbound", + !patch::delay_query_slot_is_bound(unbound.value, real_export, proxy)); if (failures) { std::printf("startup_runtime_gpa_patch: FAIL (%d)\n", failures); diff --git a/tests/startup_runtime_proxy_scope/helper.cpp b/tests/startup_runtime_proxy_scope/helper.cpp index e6f65f93bc..5be4616f8a 100644 --- a/tests/startup_runtime_proxy_scope/helper.cpp +++ b/tests/startup_runtime_proxy_scope/helper.cpp @@ -1,10 +1,18 @@ // Package helper: imports GetProcAddress by name so the runtime proxy can rewrite its IAT after load. +// Also delay-imports xgameruntime!QueryApiImpl so a post-bind delay IAT rewrite can be exercised. #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include +extern "C" HRESULT WINAPI QueryApiImpl(const GUID*, const GUID*, void**); + extern "C" __declspec(dllexport) FARPROC WINAPI resolve_query(HMODULE module) { return GetProcAddress(module, "QueryApiImpl"); } + +extern "C" __declspec(dllexport) HRESULT WINAPI call_delay_query(const GUID* provider, const GUID* iid, void** out) +{ + return QueryApiImpl(provider, iid, out); +} diff --git a/tests/startup_runtime_proxy_scope/helper.def b/tests/startup_runtime_proxy_scope/helper.def index 0083a3197b..03c4b9f0eb 100644 --- a/tests/startup_runtime_proxy_scope/helper.def +++ b/tests/startup_runtime_proxy_scope/helper.def @@ -1,3 +1,4 @@ LIBRARY startup_runtime_proxy_helper EXPORTS resolve_query + call_delay_query diff --git a/tests/startup_runtime_proxy_scope/host.cpp b/tests/startup_runtime_proxy_scope/host.cpp index ec4221b3e9..865e5c4b63 100644 --- a/tests/startup_runtime_proxy_scope/host.cpp +++ b/tests/startup_runtime_proxy_scope/host.cpp @@ -4,12 +4,16 @@ // unrelated decoy that also exports QueryApiImpl, then a helper beside the EXE. The helper's // GetProcAddress IAT is rewritten after linking (outside LdrDllNotification). Looking up // QueryApiImpl on xgameruntime must return the proxy; the same name on the decoy must still be the -// decoy's export. No game files. +// decoy's export. A QueryApiImpl pointer cached before the proxy attaches stays the real export +// (pre-attach gap). A delay-imported QueryApiImpl that has already bound is rewritten to the proxy; +// an unbound delay thunk must not be. No game files. #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include +#include "startup_stubs/runtime_gpa_patch.h" + #include #include #include @@ -51,6 +55,35 @@ bool wait_for_helper_hook(ResolveFn resolve, HMODULE xgr, FARPROC expect_proxy, Sleep(10); } } + +ULONGLONG* delay_query_slot(HMODULE module) +{ + if (!module) return nullptr; + auto* base = reinterpret_cast(module); + const auto* dos = reinterpret_cast(base); + if (dos->e_magic != IMAGE_DOS_SIGNATURE) return nullptr; + const auto* nt = reinterpret_cast(base + dos->e_lfanew); + if (nt->Signature != IMAGE_NT_SIGNATURE || nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) + return nullptr; + const auto image_size = static_cast(nt->OptionalHeader.SizeOfImage); + ULONGLONG* found = nullptr; + x2w_runtime_patch::visit_imports(base, image_size, [&](const x2w_runtime_patch::Hit& hit) { + if (!hit.delay_import || hit.kind != x2w_runtime_patch::Kind::query_api_impl) return; + found = reinterpret_cast(base + hit.first_thunk_rva); + }); + return found; +} + +bool wait_for_slot(ULONGLONG* slot, ULONGLONG expect, int ms) +{ + if (!slot) return false; + const DWORD start = GetTickCount(); + for (;;) { + if (*slot == expect) return true; + if (GetTickCount() - start > static_cast(ms)) return false; + Sleep(10); + } +} } int main() @@ -70,6 +103,10 @@ int main() check("xgameruntime exports QueryApiImpl", xgr_query != nullptr); check("decoy and xgameruntime exports differ", decoy_query && xgr_query && decoy_query != xgr_query); + // Pre-attach cache: resolve before the proxy carrier loads. This pointer must stay the real + // export after attach (IAT/GPA hooks do not rewrite already-held function pointers). + const FARPROC cached_before_proxy = xgr_query; + const HMODULE carrier = load_beside(dir, L"startup_runtime_proxy_carrier.dll"); check("load proxy carrier", carrier != nullptr); if (!carrier) return 1; @@ -81,6 +118,7 @@ int main() // Host GetProcAddress is rewritten on attach; xgameruntime lookups become the proxy. const FARPROC host_xgr = xgr ? GetProcAddress(xgr, "QueryApiImpl") : nullptr; check("host GetProcAddress(xgameruntime) is proxied", host_xgr && host_xgr != xgr_query); + check("pre-attach cached QueryApiImpl stays real", cached_before_proxy == xgr_query); check("release the caller's runtime reference", xgr && FreeLibrary(xgr) != FALSE); check("the cached provider stays live", GetModuleHandleW(L"xgameruntime.dll") == xgr); if (failures) return 1; @@ -92,12 +130,34 @@ int main() check("late-load package helper", helper != nullptr); const auto resolve = helper ? reinterpret_cast(GetProcAddress(helper, "resolve_query")) : nullptr; check("helper exports resolve_query", resolve != nullptr); + const auto call_delay = helper ? reinterpret_cast(GetProcAddress(helper, "call_delay_query")) : nullptr; + check("helper exports call_delay_query", call_delay != nullptr); check("helper sees proxied xgameruntime QueryApiImpl", resolve && wait_for_helper_hook(resolve, xgr, host_xgr, 2000)); const FARPROC helper_decoy = resolve ? resolve(decoy) : nullptr; check("helper GetProcAddress(decoy) stays original", helper_decoy == decoy_query); + ULONGLONG* delay_slot = delay_query_slot(helper); + check("helper has delay QueryApiImpl slot", delay_slot != nullptr); + if (delay_slot) { + const ULONGLONG before_bind = *delay_slot; + check("delay slot unbound before first use", + !x2w_runtime_patch::delay_query_slot_is_bound(before_bind, reinterpret_cast(xgr_query), + reinterpret_cast(host_xgr))); + // Negative: give the quiet rebind pass time; an unbound thunk must stay untouched. + Sleep(300); + check("unbound delay slot not rewritten", *delay_slot == before_bind); + if (call_delay) call_delay(nullptr, nullptr, nullptr); + // The quiet rebind pass may already have swapped the slot for the proxy. + const ULONGLONG after_bind = *delay_slot; + check("delay bind wrote real export or proxy", + after_bind == reinterpret_cast(xgr_query) || + after_bind == reinterpret_cast(host_xgr)); + check("bound delay slot rewritten to proxy", + wait_for_slot(delay_slot, reinterpret_cast(host_xgr), 2000)); + } + // Intended call: invoke the proxied entry; the fake xgameruntime must run. using SeenFn = LONG(WINAPI*)(); const auto xgr_seen = xgr ? reinterpret_cast(GetProcAddress(xgr, "query_calls")) : nullptr; @@ -109,6 +169,10 @@ int main() check("proxied call reached xgameruntime", xgr_seen && xgr_seen() == xgr_before + 1); check("decoy call reached decoy only", decoy_seen && decoy_seen() == decoy_before + 1); + // Pre-attach cache still reaches the real export (not the proxy entry). + if (cached_before_proxy) reinterpret_cast(cached_before_proxy)(nullptr, nullptr, nullptr); + check("pre-attach cache still calls real export", xgr_seen && xgr_seen() == xgr_before + 2); + if (failures) { std::printf("startup_runtime_proxy_scope: FAIL (%d)\n", failures); return 1; From f8b51edb3d47f9d4e77e621d02a5061e99a6c5a6 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 26 Nov 2026 12:16:20 +0000 Subject: [PATCH 2/4] runtime: store a bound delay QueryApiImpl only when the slot still holds the export The write compare-exchanges the slot with the remembered export and counts the replacement only when that exchange stores the proxy. The source-built check covers a slot that stays the export and a slot restored to its thunk before the store. Quiet scans reuse an export that was already remembered. Co-authored-by: SimSalabimse --- CMakeLists.txt | 7 +-- docs/startup-runtime.md | 2 +- src/startup_stubs/runtime_gpa_patch.h | 21 +++++++-- src/startup_stubs/runtime_proxy.cpp | 34 +++++++++------ tests/startup_runtime_gpa_patch_check.cpp | 53 ++++++++++++++++++++++- 5 files changed, 95 insertions(+), 22 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index cf9a024d63..2a123258a3 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1130,9 +1130,10 @@ add_test(NAME startup_console_mode_provider_control COMMAND startup_console_mode --control provider --decoy "$") set_tests_properties(startup_console_mode_control startup_console_mode_provider_control PROPERTIES PASS_REGULAR_EXPRESSION "FAIL: ") # EXE + late-loaded package helper through the real Windows loader: proxied xgameruntime QueryApiImpl, -# unrelated same-named export stays original, bound delay QueryApiImpl is rewritten, unbound delay -# thunk and a pre-attach cached pointer are negative controls. Notification only enqueues; rewrite -# runs after link. +# unrelated same-named export stays original, a bound delay QueryApiImpl is rewritten while the slot +# still holds the real export, and an unbound delay thunk and a pre-attach cached pointer are +# negative controls. Notification only enqueues; rewrite runs after link. The gpa-patch check counts +# a replacement only when the slot still holds that export at the write. if (WIN32) set(X2W_PROXY_SCOPE_DIR "${CMAKE_CURRENT_BINARY_DIR}/startup_runtime_proxy_scope") add_library(startup_runtime_proxy_carrier SHARED diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 8bd437f163..3086879f63 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1489,7 +1489,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_DRAW_DUMP_FRAME=`, `X2W_DRAW_DUMP_DIR` | Full-resolution RGB snapshots of single-sample RGBA8/BGRA8 UNORM or sRGB targets after translated draws. A later present writes completed queue-fenced copies. At most 48 copies are pending or written; a copy whose fence reports device removal (`UINT64_MAX`) is released unwritten and frees its slot (`src/startup_stubs/draw_dump_tracking.h`, `ctest --preset dev --no-tests=error -R '^startup_dump_fence_(removed_control_)?warp$' -V`; the control must fail). | | `X2W_TEARDOWN_REPORT=1`, `X2W_TEARDOWN_NO_GUARD=` | Test accounting for the caches whose destructors run during the module's CRT teardown (`src/startup_stubs/d3d12_teardown.h`, #2572). With `X2W_TEARDOWN_REPORT`, each destroyed cache writes one `x2w-teardown detached= released=` line to stderr with `WriteFile`, because a stdio buffer would not be flushed from a CRT teardown. `X2W_TEARDOWN_NO_GUARD` names a cache whose detach at process exit becomes an ordinary release again: the negative control `startup_teardown_unload` runs against itself, where the termination check has to fail. Unset, both change nothing and no line is written. | | `X2W_AUDIO_PERMISSIVE=1` | enables the audio stand-ins. Without a DSP provider, `XDspActivate` clears valid outputs and reports unavailable resources, and failed `XDspSubmitCommand` calls leave the sequence unchanged. `XDspDeactivate` and `XDspDisconnect` refuse null and unknown handles with `E_INVALIDARG`. | -| `X2W_RUNTIME_PROXY=1` | proxies the gaming runtime and logs every call. Rewrites regular-IAT `GetProcAddress` and a direct `xgameruntime.dll!QueryApiImpl` import on the main EXE and on DLLs that share its directory (package helpers). Dynamic `QueryApiImpl` / `InitializeApiImpl*` are wrapped only when the provider module's basename is `xgameruntime.dll`. `LdrRegisterDllNotification` only flags that another scan is needed. A worker holds each matching module live while rewriting after linking. Loading a helper and immediately calling it can precede the scan. The enabled proxy stays loaded until process exit. Unbound delay-import IAT slots are left alone; a delay `QueryApiImpl` slot that already holds the real export is rewritten to the proxy on a later scan. `GetProcAddress("QueryApiImpl")` is always logged (generic GPA lines stay capped). Skips this stand-in's own `GetProcAddress` IAT so the hook does not recurse (`src/startup_stubs/runtime_gpa_patch.h`, `ctest --preset dev --no-tests=error -R '^startup_runtime_gpa_patch(_name_only_control)?$'`, and the control must print `FAIL:`; Windows also runs `startup_runtime_proxy_scope` for a late-loaded helper through the real loader) | +| `X2W_RUNTIME_PROXY=1` | proxies the gaming runtime and logs every call. Rewrites regular-IAT `GetProcAddress` and a direct `xgameruntime.dll!QueryApiImpl` import on the main EXE and on DLLs that share its directory (package helpers). Dynamic `QueryApiImpl` / `InitializeApiImpl*` are wrapped only when the provider module's basename is `xgameruntime.dll`. `LdrRegisterDllNotification` only flags that another scan is needed. A worker holds each matching module live while rewriting after linking. Loading a helper and immediately calling it can precede the scan. The enabled proxy stays loaded until process exit. Unbound delay-import IAT slots are left alone. A later scan stores the proxy in a delay `QueryApiImpl` slot only when a compare-exchange still sees the real export; a thunk restored after the eligibility read stays in place and is not counted. The source-built check covers both transitions. `GetProcAddress("QueryApiImpl")` is always logged (generic GPA lines stay capped). Skips this stand-in's own `GetProcAddress` IAT so the hook does not recurse (`src/startup_stubs/runtime_gpa_patch.h`, `ctest --preset dev --no-tests=error -R '^startup_runtime_gpa_patch(_name_only_control)?$'`, and the control must print `FAIL:`; Windows also runs `startup_runtime_proxy_scope` for a late-loaded helper through the real loader) | | `X2W_FAKE_USER=1` | answers the user, gamertag and save APIs for one local user, and creates one offline store context for that user | | `X2W_RUNTIME_LOCAL=1` | with `X2W_RUNTIME_PROXY` and `X2W_FAKE_USER`, for a host where the system gaming runtime cannot initialize (no Gaming Services). The first failed `InitializeApiImpl*` is reported as `S_OK`, and every later initialization call returns `S_OK` without calling the real export. Once initialization failure is latched, a failed real `QueryApiImpl` call can fall back only with an exact match of both GUIDs to a supported provider/interface pair for user (including gamertag), game save, package, title, connectivity or store. Persistent local storage uses its existing fake-user gate and requires its exact provider GUID and IID. Unmatched failed queries keep the real HRESULT. The proxy clears a writable output on failure only when fake user is enabled and the initialization failure is latched. A local object's `QueryInterface` accepts only `IID_IUnknown` and the IID it was created for. The local answers above apply, calls that carry the local user or store handle fail as before, and other unanswered methods return `E_NOTIMPL`. `XUserAddAsync` and async operations completed on behalf of a local answer require the real runtime's `QueryApiImpl` to return the XAsync provider (`073b7dcb`). Those operations complete with `S_OK` through XAsync, or return the query failure if XAsync is unavailable (`ctest --preset dev --no-tests=error -R '^startup_runtime_local(_control)?$'`, and the control must print `FAIL:`). | | `X2W_DEVICE_TYPE=` | with `X2W_RUNTIME_PROXY=1`, answers the title's reads of the OEM `ConsoleMode` registry value: `6` = 0x60 (Series S), `7` = 0x64 (Series X), `1` = value missing (PC); unset, the real registry answers. See [Console profile](#console-profile) | diff --git a/src/startup_stubs/runtime_gpa_patch.h b/src/startup_stubs/runtime_gpa_patch.h index 0d63e6c7c0..64983496aa 100644 --- a/src/startup_stubs/runtime_gpa_patch.h +++ b/src/startup_stubs/runtime_gpa_patch.h @@ -6,8 +6,10 @@ // This header lists the import shapes to notice — regular and delay-import tables. The stand-in // rewrites regular GetProcAddress / QueryApiImpl IAT slots on the EXE and package-directory helpers. // A delay IAT holds a delay-load thunk until first use; rewriting that thunk as if it were the -// export is wrong. After the delay helper binds, the same slot holds the real export address and -// may be rewritten to the proxy (see delay_query_slot_is_bound). Ordinal imports are ignored. +// export is wrong. After the delay helper binds, the same slot holds the real export address. +// replace_bound_delay_query stores the proxy only when a compare-exchange still sees that export, +// so a thunk restored after the eligibility read stays in place and is not counted. Ordinal +// imports are ignored. // Pure walk helpers — no Windows calls — so a source-built control can check them. #pragma once @@ -60,6 +62,19 @@ inline bool delay_query_slot_is_bound(std::uint64_t slot_value, std::uint64_t re return real_query != 0 && slot_value != 0 && slot_value != proxy && slot_value == real_query; } +// Store `proxy` only when `exchange` still observes `real_query`. `exchange(slot, desired, expected)` +// returns the previous value and writes `desired` only when the slot equals `expected` +// (InterlockedCompareExchange). An earlier read can see the export and the delay loader can then +// put the thunk back; that exchange leaves the thunk and this function returns false, so the caller +// does not count it. Returns true only when the proxy was stored. +template +inline bool replace_bound_delay_query(std::uint64_t* slot, std::uint64_t real_query, std::uint64_t proxy, + Exchange exchange) noexcept +{ + if (!slot || !delay_query_slot_is_bound(*slot, real_query, proxy)) return false; + return exchange(slot, proxy, real_query) == real_query; +} + // Decide whether one named import of `dll_name` should be noticed. Ordinal imports are ignored. inline bool classify(const char* dll_name, const char* import_name, Kind* kind) noexcept { @@ -184,7 +199,7 @@ int visit_imports_with(const unsigned char* base, std::size_t image_size, Classi } // DataDirectory[13] = delay imports (reported with delay_import=true; rewrite only when - // delay_query_slot_is_bound says the slot already holds the real export). + // replace_bound_delay_query still sees the real export at the store). const auto& delay_dir = dirs[13]; if (delay_dir.virtual_address && delay_dir.size) { for (std::uint32_t at = delay_dir.virtual_address;; at += sizeof(DelayDesc)) { diff --git a/src/startup_stubs/runtime_proxy.cpp b/src/startup_stubs/runtime_proxy.cpp index e492f06e4b..4ce9622d27 100644 --- a/src/startup_stubs/runtime_proxy.cpp +++ b/src/startup_stubs/runtime_proxy.cpp @@ -7,8 +7,9 @@ // (package helpers). Dynamic QueryApiImpl is wrapped only when the provider module's basename is // xgameruntime.dll. The pre-link load notification only requests another scan. A worker scans // and rewrites linked modules outside the notification, keeping each module live while it is patched. -// Enabled proxies remain loaded until process exit. Unbound delay-import IAT slots are left alone; -// once a delay QueryApiImpl slot holds the real export, a later scan rewrites it to the proxy. +// Enabled proxies remain loaded until process exit. Unbound delay-import IAT slots are left alone. +// A later scan stores the proxy in a delay QueryApiImpl slot only when that slot still holds the +// real export at the compare-exchange, and counts only that store. // GetProcAddress("QueryApiImpl") is always logged (the generic GPA log stays capped). The wrapper // hands out proxy objects whose methods log their first calls ("x2w-runtime") and forward to the // real object. @@ -540,8 +541,9 @@ void log_query_status_once() noexcept } // Rewrite one module's regular GetProcAddress / xgameruntime.dll!QueryApiImpl IAT slots. -// Unbound delay-import slots stay untouched. A delay QueryApiImpl slot that already holds the real -// export is rewritten to the proxy. Caller must hold the module live (pin) for the rewrite. +// Unbound delay-import slots stay untouched. A delay QueryApiImpl slot is rewritten only when the +// compare-exchange still sees the real export; a thunk restored after the eligibility read is left +// in place and is not counted. Caller must hold the module live (pin) for the rewrite. int patch_module(HMODULE module) { if (!module || !module_is_exe_or_package_helper(module)) return 0; @@ -561,16 +563,22 @@ int patch_module(HMODULE module) if (hit.delay_import) { // Delay GetProcAddress stays unhooked (CRT delay helper uses its own lookup). if (hit.kind != x2w_runtime_patch::Kind::query_api_impl) return; - remember_real_query_from_export(); - const QueryApi real = load_real_query(); - if (!x2w_runtime_patch::delay_query_slot_is_bound(*slot, reinterpret_cast(real), proxy)) - return; + // The export is remembered once. Later quiet scans already have it. + if (!load_real_query()) remember_real_query_from_export(); + const ULONGLONG real_bits = reinterpret_cast(load_real_query()); + // Skip the protection change when the slot is not the export. The store below still + // requires that same value: VirtualProtect can overlap a delay-loader restore. + if (!x2w_runtime_patch::delay_query_slot_is_bound(*slot, real_bits, proxy)) return; DWORD old = 0; if (!VirtualProtect(slot, 8, PAGE_READWRITE, &old)) return; - if (*slot != proxy) { - *slot = proxy; + if (x2w_runtime_patch::replace_bound_delay_query( + reinterpret_cast(slot), real_bits, proxy, + [](std::uint64_t* destination, std::uint64_t desired, std::uint64_t expected) noexcept { + return static_cast(InterlockedCompareExchange64( + reinterpret_cast(destination), static_cast(desired), + static_cast(expected))); + })) ++patched; - } VirtualProtect(slot, 8, old, &old); return; } @@ -675,8 +683,8 @@ void patch_package_modules(bool announce) slots += n; } } - // Announce every load-driven scan; quiet periodic passes only speak when they rewrote a slot - // (bound delay QueryApiImpl after first use). + // Announce every load-driven scan. Quiet periodic passes speak only when a compare-exchange + // stored the proxy (bound delay QueryApiImpl after first use). A restored thunk adds nothing. if (announce) { if (slots > 0 || considered > 0) x2w_local::logf("x2w-runtime proxy: %d import(s) in %u of %u package module(s) (%u loaded scanned)", slots, diff --git a/tests/startup_runtime_gpa_patch_check.cpp b/tests/startup_runtime_gpa_patch_check.cpp index 5a0b21d751..2b5e6edaa6 100644 --- a/tests/startup_runtime_gpa_patch_check.cpp +++ b/tests/startup_runtime_gpa_patch_check.cpp @@ -2,8 +2,9 @@ // // Which PE imports the stand-in notices on the EXE / package-helper import tables: GetProcAddress and // a direct xgameruntime.dll!QueryApiImpl on the regular import table, delay-import hits with -// delay_import set, and ordinal thunks ignored. Bound delay QueryApiImpl slots (slot == real export) -// are safe to rewrite; unbound thunks are not. A synthetic PE32+ image is walked; the mutated +// delay_import set, and ordinal thunks ignored. A bound delay QueryApiImpl slot is replaced only when +// the compare-exchange still sees the real export, and only that store is counted. A slot changed +// back to its thunk before the exchange stays untouched. A synthetic PE32+ image is walked; the mutated // control classifies by import name alone (accepting QueryApiImpl from other.dll) and must fail. // No Windows loader and no game files. #include "startup_stubs/runtime_gpa_patch.h" @@ -145,6 +146,54 @@ int main(int argc, char** argv) check("already proxied refused", !patch::delay_query_slot_is_bound(proxy, real_export, proxy)); check("empty real refused", !patch::delay_query_slot_is_bound(real_export, 0, proxy)); + // Compare-exchange: write `desired` only when the slot still equals `expected`. + const auto cas = [](std::uint64_t* destination, std::uint64_t desired, std::uint64_t expected) noexcept { + const std::uint64_t previous = *destination; + if (previous == expected) *destination = desired; + return previous; + }; + int replaced = 0; + std::uint64_t stays = real_export; + if (patch::replace_bound_delay_query(&stays, real_export, proxy, cas)) ++replaced; + check("slot still holding the real export is replaced", stays == proxy); + check("successful replacement counted", replaced == 1); + + constexpr std::uint64_t thunk = 0x1400; + std::uint64_t restored = real_export; + // The delay loader puts the thunk back after the eligibility read and before the store. + const auto restore_thunk = [thunk](std::uint64_t* destination, std::uint64_t desired, std::uint64_t expected) noexcept { + *destination = thunk; + const std::uint64_t previous = *destination; + if (previous == expected) *destination = desired; + return previous; + }; + int restored_replacements = 0; + if (patch::replace_bound_delay_query(&restored, real_export, proxy, restore_thunk)) ++restored_replacements; + check("slot restored to the thunk stays the thunk", restored == thunk); + check("restored thunk not counted", restored_replacements == 0); + + int later = 0; + std::uint64_t again = real_export; + if (patch::replace_bound_delay_query(&again, real_export, proxy, cas)) ++later; + check("later real export is replaced", again == proxy); + check("later real export counted", later == 1); + + std::uint64_t unbound_slot = thunk; + bool exchanged = false; + const auto note_exchange = [&](std::uint64_t*, std::uint64_t, std::uint64_t) noexcept { + exchanged = true; + return 0ull; + }; + check("unbound thunk is left alone", + !patch::replace_bound_delay_query(&unbound_slot, real_export, proxy, note_exchange) && !exchanged && + unbound_slot == thunk); + int already_replacements = 0; + std::uint64_t already = proxy; + if (patch::replace_bound_delay_query(&already, real_export, proxy, cas)) ++already_replacements; + check("proxy already installed stays", already == proxy); + check("proxy already installed is not counted", already_replacements == 0); + check("null slot refused", !patch::replace_bound_delay_query(nullptr, real_export, proxy, cas)); + auto image = build_image(); int gpa = 0, query = 0, delay_hits = 0, regular_hits = 0; std::vector rvas; From eafec814d39fb4392a820573ab23116b81cd7d93 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Fri, 27 Nov 2026 22:43:10 +0000 Subject: [PATCH 3/4] runtime: bind the delay QueryApiImpl slot before the proxy attaches The loader test called the delay import after GetProcAddress was already hooked, so the bind stored the proxy and the slot rewrite never ran. The helper now binds through the unhooked lookup first, and the test waits for that real export to become the proxy. A second helper is never called; after the scan its thunk must still lie inside its own image. Co-authored-by: SimSalabimse --- CMakeLists.txt | 23 +++-- docs/startup-runtime.md | 2 +- src/startup_stubs/runtime_gpa_patch.h | 7 ++ tests/startup_runtime_gpa_patch_check.cpp | 26 +++++- tests/startup_runtime_proxy_scope/helper.cpp | 3 +- .../helper_unbound.def | 4 + tests/startup_runtime_proxy_scope/host.cpp | 83 +++++++++++-------- 7 files changed, 105 insertions(+), 43 deletions(-) create mode 100644 tests/startup_runtime_proxy_scope/helper_unbound.def diff --git a/CMakeLists.txt b/CMakeLists.txt index 92b138c4b0..909dabebff 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1180,11 +1180,12 @@ add_test(NAME startup_console_mode_control add_test(NAME startup_console_mode_provider_control COMMAND startup_console_mode --control provider --decoy "$") set_tests_properties(startup_console_mode_control startup_console_mode_provider_control PROPERTIES PASS_REGULAR_EXPRESSION "FAIL: ") -# EXE + late-loaded package helper through the real Windows loader: proxied xgameruntime QueryApiImpl, -# unrelated same-named export stays original, a bound delay QueryApiImpl is rewritten while the slot -# still holds the real export, and an unbound delay thunk and a pre-attach cached pointer are -# negative controls. Notification only enqueues; rewrite runs after link. The gpa-patch check counts -# a replacement only when the slot still holds that export at the write. +# EXE + package helpers through the real Windows loader: proxied xgameruntime QueryApiImpl, +# unrelated same-named export stays original. One helper binds its delay QueryApiImpl slot to the +# real export before the proxy attaches; the scan must then store the proxy. A second helper is +# never called, and after the scan its thunk must still lie inside its own image. A pre-attach +# cached pointer stays the real export. Notification only enqueues; rewrite runs after link. The +# gpa-patch check counts a replacement only when the slot still holds that export at the write. if (WIN32) set(X2W_PROXY_SCOPE_DIR "${CMAKE_CURRENT_BINARY_DIR}/startup_runtime_proxy_scope") add_library(startup_runtime_proxy_carrier SHARED @@ -1206,6 +1207,13 @@ if (WIN32) # holds the real export after first use (the bound-delay rewrite path). target_link_libraries(startup_runtime_proxy_helper PRIVATE startup_runtime_proxy_xgr delayimp) target_link_options(startup_runtime_proxy_helper PRIVATE "/DELAYLOAD:xgameruntime.dll") + # Same delay import, never called. Its slot stays the in-image thunk. + add_library(startup_runtime_proxy_helper_unbound SHARED + tests/startup_runtime_proxy_scope/helper.cpp + tests/startup_runtime_proxy_scope/helper_unbound.def) + target_compile_features(startup_runtime_proxy_helper_unbound PRIVATE cxx_std_17) + target_link_libraries(startup_runtime_proxy_helper_unbound PRIVATE startup_runtime_proxy_xgr delayimp) + target_link_options(startup_runtime_proxy_helper_unbound PRIVATE "/DELAYLOAD:xgameruntime.dll") add_library(startup_runtime_proxy_decoy SHARED tests/startup_runtime_proxy_scope/decoy.cpp tests/startup_runtime_proxy_scope/decoy.def) @@ -1213,7 +1221,8 @@ if (WIN32) add_executable(startup_runtime_proxy_scope tests/startup_runtime_proxy_scope/host.cpp) target_include_directories(startup_runtime_proxy_scope PRIVATE src) target_compile_features(startup_runtime_proxy_scope PRIVATE cxx_std_17) - foreach(tgt IN ITEMS startup_runtime_proxy_carrier startup_runtime_proxy_helper startup_runtime_proxy_xgr + foreach(tgt IN ITEMS startup_runtime_proxy_carrier startup_runtime_proxy_helper + startup_runtime_proxy_helper_unbound startup_runtime_proxy_xgr startup_runtime_proxy_decoy startup_runtime_proxy_scope) set_target_properties(${tgt} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${X2W_PROXY_SCOPE_DIR}" @@ -1221,7 +1230,7 @@ if (WIN32) ARCHIVE_OUTPUT_DIRECTORY "${X2W_PROXY_SCOPE_DIR}") endforeach() add_dependencies(startup_runtime_proxy_scope startup_runtime_proxy_carrier startup_runtime_proxy_helper - startup_runtime_proxy_xgr startup_runtime_proxy_decoy) + startup_runtime_proxy_helper_unbound startup_runtime_proxy_xgr startup_runtime_proxy_decoy) add_test(NAME startup_runtime_proxy_scope COMMAND "$") set_tests_properties(startup_runtime_proxy_scope PROPERTIES TIMEOUT 60 RUN_SERIAL TRUE) endif() diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index ce08741a10..3367ff3239 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1614,7 +1614,7 @@ ctest --preset dev --no-tests=error -R '^startup_hook_(window|overlap)$' -V | `X2W_DRAW_DUMP_FRAME=`, `X2W_DRAW_DUMP_DIR`, `X2W_DRAW_DUMP_PIXEL=,` | Full-resolution RGB snapshots of single-sample RGBA8/BGRA8 UNORM or sRGB targets after translated draws. A later present writes completed queue-fenced copies. At most 48 copies are pending or written; a copy whose fence reports device removal (`UINT64_MAX`) is released unwritten and frees its slot (`src/startup_stubs/draw_dump_tracking.h`, `ctest --preset dev --no-tests=error -R '^startup_dump_fence_(removed_control_)?warp$' -V`; the control must fail). With `X2W_DRAW_DUMP_PIXEL`, each copy covers one texel instead and the present writes `pixel_history.txt` in `X2W_DRAW_DUMP_DIR`: one line per translated draw with `draw=`, `frame=`, `x=`, `y=`, `key=`, `count=`, `format=`, `raw=` and, for an 8-bit four-channel target, `rgba=`. The bounded history names the last draw that changed the texel (`src/startup_stubs/pixel_history.h`, `ctest --preset dev --no-tests=error -R '^startup_pixel_history_' -V`). | | `X2W_TEARDOWN_REPORT=1`, `X2W_TEARDOWN_NO_GUARD=` | Test accounting for the caches whose destructors run during the module's CRT teardown (`src/startup_stubs/d3d12_teardown.h`, #2572). With `X2W_TEARDOWN_REPORT`, each destroyed cache writes one `x2w-teardown detached= released=` line to stderr with `WriteFile`, because a stdio buffer would not be flushed from a CRT teardown. `X2W_TEARDOWN_NO_GUARD` names a cache whose detach at process exit becomes an ordinary release again: the negative control `startup_teardown_unload` runs against itself, where the termination check has to fail. Unset, both change nothing and no line is written. | | `X2W_AUDIO_PERMISSIVE=1` | enables the audio stand-ins. Without a DSP provider, `XDspActivate` clears valid outputs and reports unavailable resources, and failed `XDspSubmitCommand` calls leave the sequence unchanged. `XDspDeactivate` and `XDspDisconnect` refuse null and unknown handles with `E_INVALIDARG`. | -| `X2W_RUNTIME_PROXY=1` | proxies the gaming runtime and logs every call. Rewrites regular-IAT `GetProcAddress` and a direct `xgameruntime.dll!QueryApiImpl` import on the main EXE and on DLLs that share its directory (package helpers). Dynamic `QueryApiImpl` / `InitializeApiImpl*` are wrapped only when the provider module's basename is `xgameruntime.dll`. `LdrRegisterDllNotification` only flags that another scan is needed. A worker holds each matching module live while rewriting after linking. Loading a helper and immediately calling it can precede the scan. The enabled proxy stays loaded until process exit. Unbound delay-import IAT slots are left alone. A later scan stores the proxy in a delay `QueryApiImpl` slot only when a compare-exchange still sees the real export; a thunk restored after the eligibility read stays in place and is not counted. The source-built check covers both transitions. `GetProcAddress("QueryApiImpl")` is always logged (generic GPA lines stay capped). Skips this stand-in's own `GetProcAddress` IAT so the hook does not recurse (`src/startup_stubs/runtime_gpa_patch.h`, `ctest --preset dev --no-tests=error -R '^startup_runtime_gpa_patch(_name_only_control)?$'`, and the control must print `FAIL:`; Windows also runs `startup_runtime_proxy_scope` for a late-loaded helper through the real loader) | +| `X2W_RUNTIME_PROXY=1` | proxies the gaming runtime and logs every call. Rewrites regular-IAT `GetProcAddress` and a direct `xgameruntime.dll!QueryApiImpl` import on the main EXE and on DLLs that share its directory (package helpers). Dynamic `QueryApiImpl` / `InitializeApiImpl*` are wrapped only when the provider module's basename is `xgameruntime.dll`. `LdrRegisterDllNotification` only flags that another scan is needed. A worker holds each matching module live while rewriting after linking. Loading a helper and immediately calling it can precede the scan. The enabled proxy stays loaded until process exit. Unbound delay-import IAT slots are left alone. A later scan stores the proxy in a delay `QueryApiImpl` slot only when a compare-exchange still sees the real export; a thunk restored after the eligibility read stays in place and is not counted. The source-built check covers both transitions. `GetProcAddress("QueryApiImpl")` is always logged (generic GPA lines stay capped). Skips this stand-in's own `GetProcAddress` IAT so the hook does not recurse (`src/startup_stubs/runtime_gpa_patch.h`, `ctest --preset dev --no-tests=error -R '^startup_runtime_gpa_patch(_name_only_control)?$'`, and the control must print `FAIL:`; Windows also runs `startup_runtime_proxy_scope`: one helper binds the delay slot to the real export before the proxy attaches, and that slot must then become the proxy; a second helper that is never called must keep its thunk inside its own image) | | `X2W_FAKE_USER=1` | answers the user, gamertag and save APIs for one local user, and creates one offline store context for that user | | `X2W_RUNTIME_LOCAL=1` | with `X2W_RUNTIME_PROXY` and `X2W_FAKE_USER`, for a host where the system gaming runtime cannot initialize (no Gaming Services). The first failed `InitializeApiImpl*` is reported as `S_OK`, and every later initialization call returns `S_OK` without calling the real export. Once initialization failure is latched, a failed real `QueryApiImpl` call can fall back only with an exact match of both GUIDs to a supported provider/interface pair for user (including gamertag), game save, package, title, connectivity or store. Persistent local storage uses its existing fake-user gate and requires its exact provider GUID and IID. Unmatched failed queries keep the real HRESULT. The proxy clears a writable output on failure only when fake user is enabled and the initialization failure is latched. A local object's `QueryInterface` accepts only `IID_IUnknown` and the IID it was created for. The local answers above apply, calls that carry the local user or store handle fail as before, and other unanswered methods return `E_NOTIMPL`. `XUserAddAsync` and async operations completed on behalf of a local answer require the real runtime's `QueryApiImpl` to return the XAsync provider (`073b7dcb`). Those operations complete with `S_OK` through XAsync, or return the query failure if XAsync is unavailable (`ctest --preset dev --no-tests=error -R '^startup_runtime_local(_control)?$'`, and the control must print `FAIL:`). | | `X2W_DEVICE_TYPE=` | with `X2W_RUNTIME_PROXY=1`, answers the title's reads of the OEM `ConsoleMode` registry value: `6` = 0x60 (Series S), `7` = 0x64 (Series X), `1` = value missing (PC); unset, the real registry answers. See [Console profile](#console-profile) | diff --git a/src/startup_stubs/runtime_gpa_patch.h b/src/startup_stubs/runtime_gpa_patch.h index 64983496aa..41f044f125 100644 --- a/src/startup_stubs/runtime_gpa_patch.h +++ b/src/startup_stubs/runtime_gpa_patch.h @@ -62,6 +62,13 @@ inline bool delay_query_slot_is_bound(std::uint64_t slot_value, std::uint64_t re return real_query != 0 && slot_value != 0 && slot_value != proxy && slot_value == real_query; } +// True when `address` lies in [image_base, image_base + image_size). A delay thunk lives in the +// importing image; the real export and the proxy do not. +inline bool address_in_image(std::uint64_t address, std::uint64_t image_base, std::uint64_t image_size) noexcept +{ + return image_size != 0 && address >= image_base && (address - image_base) < image_size; +} + // Store `proxy` only when `exchange` still observes `real_query`. `exchange(slot, desired, expected)` // returns the previous value and writes `desired` only when the slot equals `expected` // (InterlockedCompareExchange). An earlier read can see the export and the delay loader can then diff --git a/tests/startup_runtime_gpa_patch_check.cpp b/tests/startup_runtime_gpa_patch_check.cpp index 2b5e6edaa6..0f5313aef0 100644 --- a/tests/startup_runtime_gpa_patch_check.cpp +++ b/tests/startup_runtime_gpa_patch_check.cpp @@ -4,7 +4,9 @@ // a direct xgameruntime.dll!QueryApiImpl on the regular import table, delay-import hits with // delay_import set, and ordinal thunks ignored. A bound delay QueryApiImpl slot is replaced only when // the compare-exchange still sees the real export, and only that store is counted. A slot changed -// back to its thunk before the exchange stays untouched. A synthetic PE32+ image is walked; the mutated +// back to its thunk before the exchange stays untouched. A slot that already holds the real export +// becomes the proxy only through that exchange, and an in-image thunk stays inside the image. +// A synthetic PE32+ image is walked; the mutated // control classifies by import name alone (accepting QueryApiImpl from other.dll) and must fail. // No Windows loader and no game files. #include "startup_stubs/runtime_gpa_patch.h" @@ -194,6 +196,28 @@ int main(int argc, char** argv) check("proxy already installed is not counted", already_replacements == 0); check("null slot refused", !patch::replace_bound_delay_query(nullptr, real_export, proxy, cas)); + // Same pass condition as the loader test: the slot is the real export before the proxy attaches, + // and only the exchange turns it into the proxy. An uncalled helper's thunk stays in its image. + constexpr std::uint64_t image_base = 0x180000000ull; + constexpr std::uint64_t image_size = 0x20000ull; + constexpr std::uint64_t image_thunk = image_base + 0x1400ull; + check("thunk lies inside the helper image", patch::address_in_image(image_thunk, image_base, image_size)); + check("real export lies outside the helper image", !patch::address_in_image(real_export, image_base, image_size)); + check("proxy lies outside the helper image", !patch::address_in_image(proxy, image_base, image_size)); + std::uint64_t prebound = real_export; + const bool rewritten = patch::replace_bound_delay_query(&prebound, real_export, proxy, cas); + check("bound delay slot rewritten to proxy", rewritten && prebound == proxy); + std::uint64_t still_thunk = image_thunk; + check("unbound delay thunk stays inside the helper", + !patch::replace_bound_delay_query(&still_thunk, real_export, proxy, cas) && + patch::address_in_image(still_thunk, image_base, image_size)); + // Passing the slot's own value as the export is the unsafe rewrite: the thunk becomes the proxy + // and no longer lies in the helper image. + std::uint64_t unsafe = image_thunk; + check("slot used as the export rewrites the thunk", + patch::replace_bound_delay_query(&unsafe, unsafe, proxy, cas) && unsafe == proxy); + check("rewritten thunk leaves the helper image", !patch::address_in_image(unsafe, image_base, image_size)); + auto image = build_image(); int gpa = 0, query = 0, delay_hits = 0, regular_hits = 0; std::vector rvas; diff --git a/tests/startup_runtime_proxy_scope/helper.cpp b/tests/startup_runtime_proxy_scope/helper.cpp index 5be4616f8a..fbc50e8bf6 100644 --- a/tests/startup_runtime_proxy_scope/helper.cpp +++ b/tests/startup_runtime_proxy_scope/helper.cpp @@ -1,5 +1,6 @@ // Package helper: imports GetProcAddress by name so the runtime proxy can rewrite its IAT after load. -// Also delay-imports xgameruntime!QueryApiImpl so a post-bind delay IAT rewrite can be exercised. +// Also delay-imports xgameruntime!QueryApiImpl. The host calls call_delay_query before the proxy +// attaches, so the slot holds the real export for the later rewrite. A second copy is never called. #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif diff --git a/tests/startup_runtime_proxy_scope/helper_unbound.def b/tests/startup_runtime_proxy_scope/helper_unbound.def new file mode 100644 index 0000000000..e17dc3172a --- /dev/null +++ b/tests/startup_runtime_proxy_scope/helper_unbound.def @@ -0,0 +1,4 @@ +LIBRARY startup_runtime_proxy_helper_unbound +EXPORTS + resolve_query + call_delay_query diff --git a/tests/startup_runtime_proxy_scope/host.cpp b/tests/startup_runtime_proxy_scope/host.cpp index 395325d078..16d3918797 100644 --- a/tests/startup_runtime_proxy_scope/host.cpp +++ b/tests/startup_runtime_proxy_scope/host.cpp @@ -1,14 +1,16 @@ -// Windows-only: EXE + late-loaded package helper through the real loader. +// Windows-only: EXE + package helpers through the real loader. // -// Loads a carrier DLL that hosts runtime_proxy (X2W_RUNTIME_PROXY=1), a fake xgameruntime.dll, an -// unrelated decoy that also exports QueryApiImpl, then a helper beside the EXE. The helper's -// GetProcAddress IAT is rewritten after linking (outside LdrDllNotification). Looking up -// QueryApiImpl on xgameruntime must return the proxy; the same name on the decoy must still be the -// decoy's export. A QueryApiImpl pointer cached before the proxy attaches stays the real export -// (pre-attach gap). A delay-imported QueryApiImpl that has already bound is rewritten to the proxy; -// an unbound delay thunk must not be. RegQueryValueExW is hooked on advapi32.dll only: the decoy's -// same-named export stays its own, with X2W_DEVICE_TYPE unset and set, and never becomes the registry -// the hook calls. No game files. +// Loads a fake xgameruntime.dll, an unrelated decoy that also exports QueryApiImpl, and two helpers +// beside the EXE, then a carrier DLL that hosts runtime_proxy (X2W_RUNTIME_PROXY=1). One helper calls +// its delay-imported QueryApiImpl before the carrier attaches, so the bind goes through the unhooked +// GetProcAddress and the slot holds the real export. After attach that slot must become the proxy: +// the hooked lookup is not what writes it. The other helper is never called. After the scan its delay +// slot must still point inside its own image. The helpers' GetProcAddress IATs are rewritten after +// linking (outside LdrDllNotification). Looking up QueryApiImpl on xgameruntime must return the proxy; +// the same name on the decoy must still be the decoy's export. A QueryApiImpl pointer cached before +// the proxy attaches stays the real export (pre-attach gap). RegQueryValueExW is hooked on +// advapi32.dll only: the decoy's same-named export stays its own, with X2W_DEVICE_TYPE unset and set, +// and never becomes the registry the hook calls. No game files. #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif @@ -88,6 +90,18 @@ bool wait_for_slot(ULONGLONG* slot, ULONGLONG expect, int ms) Sleep(10); } } + +bool slot_in_module(HMODULE module, ULONGLONG value) +{ + if (!module) return false; + auto* base = reinterpret_cast(module); + const auto* dos = reinterpret_cast(base); + if (dos->e_magic != IMAGE_DOS_SIGNATURE) return false; + const auto* nt = reinterpret_cast(base + dos->e_lfanew); + if (nt->Signature != IMAGE_NT_SIGNATURE || nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) + return false; + return x2w_runtime_patch::address_in_image(value, reinterpret_cast(module), nt->OptionalHeader.SizeOfImage); +} } int main() @@ -116,6 +130,25 @@ int main() // export after attach (IAT/GPA hooks do not rewrite already-held function pointers). const FARPROC cached_before_proxy = xgr_query; + // Bind the delay slot before the proxy exists, through the helper's own GetProcAddress. + const HMODULE helper = load_beside(dir, L"startup_runtime_proxy_helper.dll"); + check("load package helper before the proxy", helper != nullptr); + const auto call_delay = helper ? reinterpret_cast(GetProcAddress(helper, "call_delay_query")) : nullptr; + check("helper exports call_delay_query", call_delay != nullptr); + if (call_delay) call_delay(nullptr, nullptr, nullptr); + ULONGLONG* delay_slot = delay_query_slot(helper); + check("helper has delay QueryApiImpl slot", delay_slot != nullptr); + check("delay slot holds the real export before attach", + delay_slot && xgr_query && *delay_slot == reinterpret_cast(xgr_query)); + + // Never call this one. The scan must leave the delay thunk inside the helper image. + const HMODULE unbound = load_beside(dir, L"startup_runtime_proxy_helper_unbound.dll"); + check("load unbound helper", unbound != nullptr); + ULONGLONG* unbound_slot = delay_query_slot(unbound); + check("unbound helper has delay QueryApiImpl slot", unbound_slot != nullptr); + check("unbound delay thunk starts inside its image", unbound_slot && slot_in_module(unbound, *unbound_slot)); + if (failures) return 1; + const HMODULE carrier = load_beside(dir, L"startup_runtime_proxy_carrier.dll"); check("load proxy carrier", carrier != nullptr); if (!carrier) return 1; @@ -135,37 +168,21 @@ int main() const FARPROC host_decoy = decoy ? GetProcAddress(decoy, "QueryApiImpl") : nullptr; check("host GetProcAddress(decoy) stays original", host_decoy == decoy_query); - const HMODULE helper = load_beside(dir, L"startup_runtime_proxy_helper.dll"); - check("late-load package helper", helper != nullptr); const auto resolve = helper ? reinterpret_cast(GetProcAddress(helper, "resolve_query")) : nullptr; check("helper exports resolve_query", resolve != nullptr); - const auto call_delay = helper ? reinterpret_cast(GetProcAddress(helper, "call_delay_query")) : nullptr; - check("helper exports call_delay_query", call_delay != nullptr); check("helper sees proxied xgameruntime QueryApiImpl", resolve && wait_for_helper_hook(resolve, xgr, host_xgr, 2000)); const FARPROC helper_decoy = resolve ? resolve(decoy) : nullptr; check("helper GetProcAddress(decoy) stays original", helper_decoy == decoy_query); - ULONGLONG* delay_slot = delay_query_slot(helper); - check("helper has delay QueryApiImpl slot", delay_slot != nullptr); - if (delay_slot) { - const ULONGLONG before_bind = *delay_slot; - check("delay slot unbound before first use", - !x2w_runtime_patch::delay_query_slot_is_bound(before_bind, reinterpret_cast(xgr_query), - reinterpret_cast(host_xgr))); - // Negative: give the quiet rebind pass time; an unbound thunk must stay untouched. - Sleep(300); - check("unbound delay slot not rewritten", *delay_slot == before_bind); - if (call_delay) call_delay(nullptr, nullptr, nullptr); - // The quiet rebind pass may already have swapped the slot for the proxy. - const ULONGLONG after_bind = *delay_slot; - check("delay bind wrote real export or proxy", - after_bind == reinterpret_cast(xgr_query) || - after_bind == reinterpret_cast(host_xgr)); - check("bound delay slot rewritten to proxy", - wait_for_slot(delay_slot, reinterpret_cast(host_xgr), 2000)); - } + // The slot already held the real export. Only the delay-slot rewrite turns it into the proxy. + check("bound delay slot rewritten to proxy", + delay_slot && host_xgr && wait_for_slot(delay_slot, reinterpret_cast(host_xgr), 2000)); + // The bound slot and the unbound slot can be visited in either order. One more quiet pass + // covers a helper the successful rewrite's pass had not reached yet. + Sleep(400); + check("unbound delay thunk stays inside its image", unbound_slot && slot_in_module(unbound, *unbound_slot)); // Intended call: invoke the proxied entry; the fake xgameruntime must run. const auto xgr_seen = xgr ? reinterpret_cast(GetProcAddress(xgr, "query_calls")) : nullptr; From 3ceef4a44880560c5184a9d83b6bb077d3928e7c Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Sat, 28 Nov 2026 10:37:02 +0000 Subject: [PATCH 4/4] runtime: load the unbound delay helper after the proxy attaches The bound helper still binds QueryApiImpl to the real export before the carrier loads. The second helper loads after that scan, so its GetProcAddress hook needs the load-driven rescan and its thunk stays inside its image. Regular import slots are compared before VirtualProtect so a quiet pass does not change protection on a slot that is already patched. Co-authored-by: SimSalabimse --- CMakeLists.txt | 7 +++-- src/startup_stubs/runtime_proxy.cpp | 13 +++++++-- tests/startup_runtime_proxy_scope/host.cpp | 34 ++++++++++++---------- 3 files changed, 33 insertions(+), 21 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 2c24c4656a..3f75975fc0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1203,8 +1203,9 @@ set_tests_properties(startup_console_mode_control startup_console_mode_provider_ # EXE + package helpers through the real Windows loader: proxied xgameruntime QueryApiImpl, # unrelated same-named export stays original. One helper binds its delay QueryApiImpl slot to the # real export before the proxy attaches; the scan must then store the proxy. A second helper is -# never called, and after the scan its thunk must still lie inside its own image. A pre-attach -# cached pointer stays the real export. Notification only enqueues; rewrite runs after link. The +# never called. It loads after the proxy, so its GetProcAddress hook needs the load-driven rescan, +# and its thunk must still lie inside its own image. A pre-attach cached pointer stays the real +# export. Notification only enqueues; rewrite runs after link. The # gpa-patch check counts a replacement only when the slot still holds that export at the write. if (WIN32) set(X2W_PROXY_SCOPE_DIR "${CMAKE_CURRENT_BINARY_DIR}/startup_runtime_proxy_scope") @@ -1227,7 +1228,7 @@ if (WIN32) # holds the real export after first use (the bound-delay rewrite path). target_link_libraries(startup_runtime_proxy_helper PRIVATE startup_runtime_proxy_xgr delayimp) target_link_options(startup_runtime_proxy_helper PRIVATE "/DELAYLOAD:xgameruntime.dll") - # Same delay import, never called. Its slot stays the in-image thunk. + # Same delay import, never called, loaded after the carrier. Its slot stays the in-image thunk. add_library(startup_runtime_proxy_helper_unbound SHARED tests/startup_runtime_proxy_scope/helper.cpp tests/startup_runtime_proxy_scope/helper_unbound.def) diff --git a/src/startup_stubs/runtime_proxy.cpp b/src/startup_stubs/runtime_proxy.cpp index 4ce9622d27..17b8c3f7bf 100644 --- a/src/startup_stubs/runtime_proxy.cpp +++ b/src/startup_stubs/runtime_proxy.cpp @@ -582,11 +582,20 @@ int patch_module(HMODULE module) VirtualProtect(slot, 8, old, &old); return; } + // Compare first. A quiet pass must not change protection on a slot that is already patched. + const ULONGLONG hooked = reinterpret_cast(&hooked_get_proc_address); + if (hit.kind == x2w_runtime_patch::Kind::get_proc_address) { + if (*slot == hooked) return; + } else if (hit.kind == x2w_runtime_patch::Kind::query_api_impl) { + if (*slot == proxy) return; + } else { + return; + } DWORD old = 0; if (!VirtualProtect(slot, 8, PAGE_READWRITE, &old)) return; if (hit.kind == x2w_runtime_patch::Kind::get_proc_address) { - if (*slot != reinterpret_cast(&hooked_get_proc_address)) { - *slot = reinterpret_cast(&hooked_get_proc_address); + if (*slot != hooked) { + *slot = hooked; ++patched; } } else if (hit.kind == x2w_runtime_patch::Kind::query_api_impl) { diff --git a/tests/startup_runtime_proxy_scope/host.cpp b/tests/startup_runtime_proxy_scope/host.cpp index 16d3918797..25e2fb8dc4 100644 --- a/tests/startup_runtime_proxy_scope/host.cpp +++ b/tests/startup_runtime_proxy_scope/host.cpp @@ -1,12 +1,13 @@ // Windows-only: EXE + package helpers through the real loader. // -// Loads a fake xgameruntime.dll, an unrelated decoy that also exports QueryApiImpl, and two helpers -// beside the EXE, then a carrier DLL that hosts runtime_proxy (X2W_RUNTIME_PROXY=1). One helper calls -// its delay-imported QueryApiImpl before the carrier attaches, so the bind goes through the unhooked +// Loads a fake xgameruntime.dll and an unrelated decoy that also exports QueryApiImpl, then one helper, +// then a carrier DLL that hosts runtime_proxy (X2W_RUNTIME_PROXY=1). That helper calls its +// delay-imported QueryApiImpl before the carrier attaches, so the bind goes through the unhooked // GetProcAddress and the slot holds the real export. After attach that slot must become the proxy: -// the hooked lookup is not what writes it. The other helper is never called. After the scan its delay -// slot must still point inside its own image. The helpers' GetProcAddress IATs are rewritten after -// linking (outside LdrDllNotification). Looking up QueryApiImpl on xgameruntime must return the proxy; +// the hooked lookup is not what writes it. A second helper loads after the carrier and is never +// called. Its GetProcAddress hook needs the load-driven rescan, and its delay thunk must stay inside +// its own image. Rewrites run after linking (outside LdrDllNotification). Looking up QueryApiImpl on +// xgameruntime must return the proxy; // the same name on the decoy must still be the decoy's export. A QueryApiImpl pointer cached before // the proxy attaches stays the real export (pre-attach gap). RegQueryValueExW is hooked on // advapi32.dll only: the decoy's same-named export stays its own, with X2W_DEVICE_TYPE unset and set, @@ -140,13 +141,6 @@ int main() check("helper has delay QueryApiImpl slot", delay_slot != nullptr); check("delay slot holds the real export before attach", delay_slot && xgr_query && *delay_slot == reinterpret_cast(xgr_query)); - - // Never call this one. The scan must leave the delay thunk inside the helper image. - const HMODULE unbound = load_beside(dir, L"startup_runtime_proxy_helper_unbound.dll"); - check("load unbound helper", unbound != nullptr); - ULONGLONG* unbound_slot = delay_query_slot(unbound); - check("unbound helper has delay QueryApiImpl slot", unbound_slot != nullptr); - check("unbound delay thunk starts inside its image", unbound_slot && slot_in_module(unbound, *unbound_slot)); if (failures) return 1; const HMODULE carrier = load_beside(dir, L"startup_runtime_proxy_carrier.dll"); @@ -179,9 +173,17 @@ int main() // The slot already held the real export. Only the delay-slot rewrite turns it into the proxy. check("bound delay slot rewritten to proxy", delay_slot && host_xgr && wait_for_slot(delay_slot, reinterpret_cast(host_xgr), 2000)); - // The bound slot and the unbound slot can be visited in either order. One more quiet pass - // covers a helper the successful rewrite's pass had not reached yet. - Sleep(400); + + // After the carrier's first scan. The load notification has to request another one. + const HMODULE unbound = load_beside(dir, L"startup_runtime_proxy_helper_unbound.dll"); + check("late-load package helper", unbound != nullptr); + const auto unbound_resolve = unbound ? reinterpret_cast(GetProcAddress(unbound, "resolve_query")) : nullptr; + check("late-load helper exports resolve_query", unbound_resolve != nullptr); + ULONGLONG* unbound_slot = delay_query_slot(unbound); + check("unbound helper has delay QueryApiImpl slot", unbound_slot != nullptr); + check("unbound delay thunk starts inside its image", unbound_slot && slot_in_module(unbound, *unbound_slot)); + check("late-load helper sees proxied xgameruntime QueryApiImpl", + unbound_resolve && host_xgr && wait_for_helper_hook(unbound_resolve, xgr, host_xgr, 2000)); check("unbound delay thunk stays inside its image", unbound_slot && slot_in_module(unbound, *unbound_slot)); // Intended call: invoke the proxied entry; the fake xgameruntime must run.