From 1306e7934f0a7ee520c57ea31d708b3952fa83fa Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 25 Nov 2026 13:40:32 +0000 Subject: [PATCH 1/3] runtime: trampoline xgameruntime QueryApiImpl for pre-attach caches IAT/GPA rewrites leave a QueryApiImpl pointer resolved before proxy attach as the real export, so FakeUser / TRACE_API never see providers on that path. Install an absolute-JMP at xgameruntime!QueryApiImpl after attach (stolen prologue stub for real_query); leave unrelated same-named exports alone. Refs #870. Fixes #2350. Co-authored-by: SimSalabimse --- CMakeLists.txt | 4 +- docs/startup-runtime.md | 2 +- src/startup_stubs/runtime_gpa_patch.h | 146 ++++++++++++++++++ src/startup_stubs/runtime_proxy.cpp | 100 +++++++++++- tests/startup_runtime_gpa_patch_check.cpp | 24 ++- tests/startup_runtime_proxy_scope/host.cpp | 47 +++++- .../xgameruntime.cpp | 26 +++- .../xgameruntime.def | 1 + 8 files changed, 336 insertions(+), 14 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 8c9c36f51..be7c2652c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -965,7 +965,8 @@ 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, pre-attach cached pointer forwards via export trampoline. +# 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 @@ -988,6 +989,7 @@ if (WIN32) 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 47ff5f8ef..a545595b8 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1174,7 +1174,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. Delay-import IAT slots are not rewritten. When `xgameruntime.dll` is loaded the worker also installs an absolute-JMP trampoline at its `QueryApiImpl` export so a pointer cached before attach still enters the proxy; other modules that export the same name are not patched, and an unknown prologue is left alone. 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 e5b23da82..5172bf52d 100644 --- a/src/startup_stubs/runtime_gpa_patch.h +++ b/src/startup_stubs/runtime_gpa_patch.h @@ -8,6 +8,10 @@ // 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. +// +// Also: absolute-JMP export trampoline helpers for a QueryApiImpl pointer resolved before the proxy +// attaches. IAT/GPA rewrites do not touch already-held function pointers; patching the export body +// so those calls enter the proxy does. Only xgameruntime.dll is in scope (see the stand-in). #pragma once #include @@ -49,6 +53,148 @@ inline bool import_is_query_api_impl(const char* name) noexcept return name && std::strcmp(name, "QueryApiImpl") == 0; } +// x64 absolute indirect jump: FF 25 00 00 00 00 + 8-byte absolute address (14 bytes). +constexpr unsigned abs_jmp_bytes = 14; + +inline void write_abs_jmp(unsigned char* at, const void* target) noexcept +{ + at[0] = 0xFF; + at[1] = 0x25; + at[2] = at[3] = at[4] = at[5] = 0; + const auto addr = reinterpret_cast(target); + for (int i = 0; i < 8; ++i) at[6 + i] = static_cast((addr >> (8 * i)) & 0xff); +} + +inline const void* abs_jmp_target(const unsigned char* at) noexcept +{ + if (!at || at[0] != 0xFF || at[1] != 0x25 || at[2] || at[3] || at[4] || at[5]) return nullptr; + std::uint64_t addr = 0; + for (int i = 0; i < 8; ++i) addr |= static_cast(at[6 + i]) << (8 * i); + return reinterpret_cast(addr); +} + +inline bool is_abs_jmp_to(const unsigned char* at, const void* target) noexcept +{ + return abs_jmp_target(at) == target; +} + +// Length of one x64 instruction starting at `p`, or 0 when unknown / unsafe to relocate into a +// trampoline stub (relative call/jmp, rip-relative that would break, or incomplete buffer). +// Covers the MSVC x64 prologues seen on QueryApiImpl fixtures and typical gaming-runtime exports. +inline unsigned x64_insn_len(const unsigned char* p, unsigned max_bytes) noexcept +{ + if (!p || max_bytes == 0) return 0; + unsigned i = 0; + bool operand66 = false; + // Legacy prefixes + REX. + while (i < max_bytes) { + const unsigned char b = p[i]; + if (b == 0x66) { + operand66 = true; + ++i; + continue; + } + if (b == 0xF2 || b == 0xF3 || b == 0x64 || b == 0x65 || b == 0x67 || b == 0x2E || b == 0x3E) { + ++i; + continue; + } + break; + } + bool rex_w = false; + if (i < max_bytes && (p[i] & 0xF0) == 0x40) { + rex_w = (p[i] & 0x08) != 0; + ++i; + } + if (i >= max_bytes) return 0; + const unsigned char op = p[i++]; + auto modrm_len = [&](unsigned at) -> unsigned { + if (at >= max_bytes) return 0; + const unsigned char modrm = p[at]; + const unsigned mod = modrm >> 6; + const unsigned rm = modrm & 7; + unsigned n = 1; + if (mod != 3 && rm == 4) { // SIB + if (at + n >= max_bytes) return 0; + ++n; + } + if (mod == 1) { + if (at + n >= max_bytes) return 0; + ++n; + } else if (mod == 2 || (mod == 0 && rm == 5) || (mod == 0 && rm == 4 && at + 1 < max_bytes && (p[at + 1] & 7) == 5)) { + // disp32, or [rip+disp32], or [sib with base=5] + if (at + n + 3 >= max_bytes) return 0; + n += 4; + } + return n; + }; + // push/pop r64 + if (op >= 0x50 && op <= 0x5F) return i; + // nop / int3 / ret — single byte; ret is fine as a whole instruction but useless for a hook site. + if (op == 0x90 || op == 0xCC || op == 0xC3) return i; + // imm pushes + if (op == 0x6A) return (i < max_bytes) ? i + 1 : 0; + if (op == 0x68) return (i + 3 < max_bytes) ? i + 4 : 0; + // mov r64, imm64 / mov r32, imm32 + if (op >= 0xB8 && op <= 0xBF) { + const unsigned imm = rex_w ? 8u : (operand66 ? 2u : 4u); + return (i + imm - 1 < max_bytes) ? i + imm : 0; + } + if (op >= 0xB0 && op <= 0xB7) return (i < max_bytes) ? i + 1 : 0; + // Relative call/jmp: refuse (would need relocation in the stub). + if (op == 0xE8 || op == 0xE9 || op == 0xEB) return 0; + // ALU / mov / lea / test with ModRM + if (op == 0x01 || op == 0x03 || op == 0x09 || op == 0x0B || op == 0x11 || op == 0x13 || op == 0x19 || op == 0x1B || + op == 0x21 || op == 0x23 || op == 0x29 || op == 0x2B || op == 0x31 || op == 0x33 || op == 0x39 || op == 0x3B || + op == 0x85 || op == 0x87 || op == 0x88 || op == 0x89 || op == 0x8A || op == 0x8B || op == 0x8D) { + // rip-relative (mod=0, rm=5) breaks when relocated into the stub. + if (i < max_bytes && (p[i] & 0xC7) == 0x05) return 0; + const unsigned m = modrm_len(i); + return m ? i + m : 0; + } + // imm8 / imm32 groups: 80-83 / C6 / C7 + if (op == 0x80 || op == 0x82 || op == 0x83 || op == 0xC6) { + if (i < max_bytes && (p[i] & 0xC7) == 0x05) return 0; + const unsigned m = modrm_len(i); + if (!m || i + m >= max_bytes) return 0; + return i + m + 1; + } + if (op == 0x81 || op == 0xC7) { + if (i < max_bytes && (p[i] & 0xC7) == 0x05) return 0; + const unsigned m = modrm_len(i); + const unsigned imm = operand66 ? 2u : 4u; + if (!m || i + m + imm - 1 >= max_bytes) return 0; + return i + m + imm; + } + // sub/add/xor/cmp r/m, imm already covered. 0F multi-byte: only short nops. + if (op == 0x0F) { + if (i >= max_bytes) return 0; + const unsigned char op2 = p[i++]; + if (op2 == 0x1F) { // nop r/m + const unsigned m = modrm_len(i); + return m ? i + m : 0; + } + return 0; + } + // FF /0-/6: refuse call/jmp forms; allow /0-/6 only for inc/dec that are rare in prologues. + if (op == 0xFF) return 0; + return 0; +} + +// How many whole prologue bytes to steal so an abs_jmp_bytes patch fits, or 0 if the prologue cannot +// be sized safely. Fills any leftover bytes in the live patch with NOPs at the call site. +inline unsigned stolen_bytes_for_abs_jmp(const unsigned char* code, unsigned max_scan) noexcept +{ + if (!code || max_scan < abs_jmp_bytes) return 0; + unsigned total = 0; + while (total < abs_jmp_bytes) { + const unsigned n = x64_insn_len(code + total, max_scan - total); + if (!n) return 0; + total += n; + if (total > max_scan) return 0; + } + return total; +} + // 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 { diff --git a/src/startup_stubs/runtime_proxy.cpp b/src/startup_stubs/runtime_proxy.cpp index 7c9a17046..b7d15fac3 100644 --- a/src/startup_stubs/runtime_proxy.cpp +++ b/src/startup_stubs/runtime_proxy.cpp @@ -7,8 +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") +// Enabled proxies remain loaded until process exit. Delay-import IAT slots are not rewritten. When +// xgameruntime.dll is loaded, the worker also installs an absolute-JMP trampoline at the +// QueryApiImpl export so a pointer cached before attach still enters the proxy (IAT/GPA rewrites do +// not touch already-held function pointers). Unrelated modules that export the same name are not +// patched. 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) @@ -56,8 +59,12 @@ SRWLOCK proxy_lock = SRWLOCK_INIT; void* slot_table[max_slots]; using QueryApi = HRESULT(__stdcall*)(const GUID*, const GUID*, void**); -// Written from the GPA hook and the post-link scan; first non-null wins. +// Written from the GPA hook and the post-link scan; first non-null wins. After the export trampoline +// installs, this points at the stolen-prologue stub rather than the live export site. std::atomic real_query{nullptr}; +// Live xgameruntime!QueryApiImpl address (patched in place). Null until the trampoline installs. +std::atomic query_export_site{nullptr}; +std::atomic query_export_trampoline_done{false}; bool keep_forward_target(FARPROC target) noexcept { @@ -73,7 +80,13 @@ bool keep_forward_target(FARPROC target) noexcept bool remember_real_query(QueryApi query) noexcept { QueryApi expected = real_query.load(std::memory_order_acquire); - if (expected) return expected == query; + if (expected) { + if (expected == query) return true; + // After the export trampoline, callers may still pass the live export site; accept it so + // GPA/IAT paths keep returning the proxy wrapper. + const void* site = query_export_site.load(std::memory_order_acquire); + return site && reinterpret_cast(query) == site; + } if (!keep_forward_target(reinterpret_cast(query))) return false; return real_query.compare_exchange_strong(expected, query, std::memory_order_acq_rel) || expected == query; } @@ -484,6 +497,75 @@ bool module_is_exe_or_package_helper(HMODULE module) noexcept return true; } +// Install an absolute-JMP at xgameruntime!QueryApiImpl so pre-attach cached pointers enter the +// proxy. Builds a stolen-prologue stub for real_query. Idempotent; refuses unknown prologues and +// never patches a non-xgameruntime module. Runs outside DllMain (worker / GPA path after attach). +bool install_query_export_trampoline() noexcept +{ + static SRWLOCK lock = SRWLOCK_INIT; + AcquireSRWLockExclusive(&lock); + const auto unlock = [](SRWLOCK* l) { ReleaseSRWLockExclusive(l); }; + struct Guard { + SRWLOCK* l; + ~Guard() { unlock(l); } + } guard{&lock}; + + if (query_export_trampoline_done.load(std::memory_order_relaxed)) { + return query_export_site.load(std::memory_order_relaxed) != nullptr; + } + const HMODULE runtime = GetModuleHandleW(L"xgameruntime.dll"); + if (!runtime || !module_is_xgameruntime(runtime)) return false; + // Unpatched GetProcAddress: this stand-in's own IAT is left alone. + const FARPROC export_fn = GetProcAddress(runtime, "QueryApiImpl"); + if (!export_fn || export_fn == reinterpret_cast(&proxy_query)) return false; + auto* site = reinterpret_cast(export_fn); + if (x2w_runtime_patch::is_abs_jmp_to(site, reinterpret_cast(&proxy_query))) { + query_export_site.store(site, std::memory_order_release); + query_export_trampoline_done.store(true, std::memory_order_release); + return true; + } + HMODULE owner = nullptr; + if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, reinterpret_cast(site), &owner) || + !module_is_xgameruntime(owner)) + return false; + const unsigned stolen = x2w_runtime_patch::stolen_bytes_for_abs_jmp(site, 32); + if (!stolen) { + static LONG logged; + if (x2w_local::first_calls(logged, 1)) + x2w_local::logf("x2w-runtime QueryApiImpl export trampoline refused: cannot size prologue at %p", + static_cast(site)); + query_export_trampoline_done.store(true, std::memory_order_release); + return false; + } + auto* stub = static_cast( + VirtualAlloc(nullptr, stolen + x2w_runtime_patch::abs_jmp_bytes, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE)); + if (!stub) { + query_export_trampoline_done.store(true, std::memory_order_release); + return false; + } + std::memcpy(stub, site, stolen); + x2w_runtime_patch::write_abs_jmp(stub + stolen, site + stolen); + // Prefer the stub as real_query before patching live bytes so proxy_query never re-enters the site. + remember_real_query(reinterpret_cast(export_fn)); + real_query.store(reinterpret_cast(stub), std::memory_order_release); + DWORD old = 0; + if (!VirtualProtect(site, stolen, PAGE_EXECUTE_READWRITE, &old)) { + VirtualFree(stub, 0, MEM_RELEASE); + real_query.store(reinterpret_cast(export_fn), std::memory_order_release); + query_export_trampoline_done.store(true, std::memory_order_release); + return false; + } + x2w_runtime_patch::write_abs_jmp(site, reinterpret_cast(&proxy_query)); + for (unsigned i = x2w_runtime_patch::abs_jmp_bytes; i < stolen; ++i) site[i] = 0x90; + VirtualProtect(site, stolen, old, &old); + FlushInstructionCache(GetCurrentProcess(), site, stolen); + query_export_site.store(site, std::memory_order_release); + query_export_trampoline_done.store(true, std::memory_order_release); + x2w_local::logf("x2w-runtime QueryApiImpl export trampoline installed at %p -> proxy (stub %p, stolen %u)", + static_cast(site), static_cast(stub), stolen); + return true; +} + FARPROC WINAPI hooked_get_proc_address(HMODULE module, LPCSTR name) { const FARPROC real = GetProcAddress(module, name); @@ -491,9 +573,11 @@ FARPROC WINAPI hooked_get_proc_address(HMODULE module, LPCSTR name) 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)); // 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))) - return reinterpret_cast(&proxy_query); + if (module_is_xgameruntime(module) && std::strcmp(name, "QueryApiImpl") == 0) { + remember_real_query(reinterpret_cast(real)); + install_query_export_trampoline(); + if (load_real_query()) 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>}; for (int k = 0; k < 3; ++k) { @@ -602,6 +686,8 @@ void CALLBACK dll_loaded(ULONG reason, const void*, void*) void patch_package_modules() { + // Pre-attach GPA caches: trampoline the export once xgameruntime.dll is loaded (IAT alone cannot). + install_query_export_trampoline(); std::vector modules(512); DWORD needed = 0; if (!EnumProcessModules(GetCurrentProcess(), modules.data(), static_cast(modules.size() * sizeof(HMODULE)), &needed) || !needed) diff --git a/tests/startup_runtime_gpa_patch_check.cpp b/tests/startup_runtime_gpa_patch_check.cpp index 310c0a29e..4bb55f5a4 100644 --- a/tests/startup_runtime_gpa_patch_check.cpp +++ b/tests/startup_runtime_gpa_patch_check.cpp @@ -3,8 +3,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 (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. +// Also checks absolute-JMP export trampoline helpers (prologue sizing). 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 @@ -124,6 +125,25 @@ 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)); + // Export trampoline helpers: absolute JMP bytes and prologue sizing (no Windows loader). + unsigned char patch_buf[16] = {}; + void* const proxy_addr = reinterpret_cast(static_cast(0x7FF0ABCD0000ull)); + patch::write_abs_jmp(patch_buf, proxy_addr); + check("abs jmp encodes target", patch::is_abs_jmp_to(patch_buf, proxy_addr)); + check("abs jmp rejects other target", + !patch::is_abs_jmp_to(patch_buf, reinterpret_cast(static_cast(0x1)))); + // mov [rsp+8], rbx; mov [rsp+10h], rsi; push rdi; sub rsp, 20h — 15 whole bytes (>= 14). + const unsigned char msvc_prologue[] = { + 0x48, 0x89, 0x5C, 0x24, 0x08, 0x48, 0x89, 0x74, 0x24, 0x10, 0x57, 0x48, 0x83, 0xEC, 0x20, 0x90}; + check("MSVC-like prologue steals 15", patch::stolen_bytes_for_abs_jmp(msvc_prologue, sizeof(msvc_prologue)) == 15); + const unsigned char relative_call[] = {0xE8, 0x00, 0x00, 0x00, 0x00, 0x90, 0x90, 0x90, + 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90}; + check("relative call prologue refused", patch::stolen_bytes_for_abs_jmp(relative_call, sizeof(relative_call)) == 0); + // Negative: a rip-relative mov must not be stolen into a relocated stub. + const unsigned char rip_relative[] = {0x48, 0x8B, 0x05, 0x00, 0x00, 0x00, 0x00, 0x90, + 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90, 0x90}; + check("rip-relative prologue refused", patch::stolen_bytes_for_abs_jmp(rip_relative, sizeof(rip_relative)) == 0); + 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/host.cpp b/tests/startup_runtime_proxy_scope/host.cpp index ec4221b3e..4c4aa3284 100644 --- a/tests/startup_runtime_proxy_scope/host.cpp +++ b/tests/startup_runtime_proxy_scope/host.cpp @@ -4,12 +4,15 @@ // 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 must forward through the +// export trampoline (proxied object). The decoy export body is not trampolined. 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 @@ -25,6 +28,7 @@ void check(const char* label, bool ok) using ResolveFn = FARPROC(WINAPI*)(HMODULE); using QueryFn = HRESULT(WINAPI*)(const GUID*, const GUID*, void**); +using ObjectFn = void*(WINAPI*)(); std::wstring dir_of_self() { @@ -51,6 +55,18 @@ bool wait_for_helper_hook(ResolveFn resolve, HMODULE xgr, FARPROC expect_proxy, Sleep(10); } } + +bool wait_for_export_trampoline(FARPROC export_site, FARPROC proxy, int ms) +{ + if (!export_site || !proxy) return false; + const auto* site = reinterpret_cast(export_site); + const DWORD start = GetTickCount(); + for (;;) { + if (x2w_runtime_patch::is_abs_jmp_to(site, proxy)) return true; + if (GetTickCount() - start > static_cast(ms)) return false; + Sleep(10); + } +} } int main() @@ -63,6 +79,8 @@ int main() check("load decoy", decoy != nullptr); const FARPROC decoy_query = decoy ? GetProcAddress(decoy, "QueryApiImpl") : nullptr; check("decoy exports QueryApiImpl", decoy_query != nullptr); + unsigned char decoy_prologue[16] = {}; + if (decoy_query) std::memcpy(decoy_prologue, reinterpret_cast(decoy_query), sizeof(decoy_prologue)); const HMODULE xgr = load_beside(dir, L"xgameruntime.dll"); check("load fake xgameruntime", xgr != nullptr); @@ -70,6 +88,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. After attach the export trampoline + // must make this same pointer enter the proxy (IAT/GPA alone leave it as the real export). + 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,12 +103,16 @@ 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("export trampoline installed at pre-attach site", + wait_for_export_trampoline(cached_before_proxy, host_xgr, 2000)); 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; const FARPROC host_decoy = decoy ? GetProcAddress(decoy, "QueryApiImpl") : nullptr; check("host GetProcAddress(decoy) stays original", host_decoy == decoy_query); + check("decoy export not trampolined", + decoy_query && std::memcmp(decoy_prologue, reinterpret_cast(decoy_query), sizeof(decoy_prologue)) == 0); const HMODULE helper = load_beside(dir, L"startup_runtime_proxy_helper.dll"); check("late-load package helper", helper != nullptr); @@ -101,6 +127,7 @@ int main() // 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; + const auto xgr_object = xgr ? reinterpret_cast(GetProcAddress(xgr, "query_object")) : nullptr; const auto decoy_seen = decoy ? reinterpret_cast(GetProcAddress(decoy, "query_calls")) : nullptr; const LONG xgr_before = xgr_seen ? xgr_seen() : -1; const LONG decoy_before = decoy_seen ? decoy_seen() : -1; @@ -109,6 +136,24 @@ 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: same pointer value, now trampolined into the proxy; readable GUIDs yield a + // proxied object distinct from the fake export's raw object. + GUID provider{}; + provider.Data1 = 0x11111111; + void* out = nullptr; + const HRESULT cached_hr = + cached_before_proxy ? reinterpret_cast(cached_before_proxy)(&provider, &provider, &out) : E_FAIL; + check("pre-attach cache call succeeded", cached_hr == S_OK); + check("pre-attach cache reached xgameruntime", xgr_seen && xgr_seen() == xgr_before + 2); + const void* raw = xgr_object ? xgr_object() : nullptr; + check("pre-attach cache returns proxied object", out && raw && out != raw); + + // Negative: decoy still answers with its own HRESULT and is not the gaming-runtime proxy. + void* decoy_out = reinterpret_cast(0x1); + const HRESULT decoy_hr = + decoy_query ? reinterpret_cast(decoy_query)(&provider, &provider, &decoy_out) : S_OK; + check("decoy QueryApiImpl stays decoy", decoy_hr == static_cast(0xA11C0001)); + if (failures) { std::printf("startup_runtime_proxy_scope: FAIL (%d)\n", failures); return 1; diff --git a/tests/startup_runtime_proxy_scope/xgameruntime.cpp b/tests/startup_runtime_proxy_scope/xgameruntime.cpp index 8863b87a4..0fdd46da7 100644 --- a/tests/startup_runtime_proxy_scope/xgameruntime.cpp +++ b/tests/startup_runtime_proxy_scope/xgameruntime.cpp @@ -6,13 +6,35 @@ namespace { LONG calls; +void* fake_slots[8]; +struct FakeObject { + void** vtable; +}; +FakeObject fake_object{fake_slots}; } extern "C" __declspec(dllexport) LONG WINAPI query_calls() { return InterlockedCompareExchange(&calls, 0, 0); } -extern "C" __declspec(dllexport) HRESULT WINAPI QueryApiImpl(const GUID*, const GUID*, void** out) +extern "C" __declspec(dllexport) void* WINAPI query_object() { return &fake_object; } + +// Keep a conventional MSVC x64 prologue (mov [rsp+…], … / push / sub rsp) so the export trampoline +// can size whole instructions. An optimised body often starts with rip-relative lock xadd, which +// the trampoline refuses to relocate. +#if defined(_MSC_VER) +#pragma optimize("", off) +#endif +extern "C" __declspec(dllexport) HRESULT WINAPI QueryApiImpl(const GUID* provider, const GUID*, void** out) { InterlockedIncrement(&calls); - if (out) *out = nullptr; + if (!out) return E_INVALIDARG; + // Readable provider GUID → hand back a real object so the proxy can wrap it (provider … proxied). + if (provider) { + *out = &fake_object; + return S_OK; + } + *out = nullptr; return E_FAIL; } +#if defined(_MSC_VER) +#pragma optimize("", on) +#endif diff --git a/tests/startup_runtime_proxy_scope/xgameruntime.def b/tests/startup_runtime_proxy_scope/xgameruntime.def index cfb3cf1ba..b0009f4be 100644 --- a/tests/startup_runtime_proxy_scope/xgameruntime.def +++ b/tests/startup_runtime_proxy_scope/xgameruntime.def @@ -2,3 +2,4 @@ LIBRARY xgameruntime EXPORTS QueryApiImpl query_calls + query_object From 8fa334b3800c07c599a1487d11d96a032f7bbca5 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 25 Nov 2026 14:39:59 +0000 Subject: [PATCH 2/3] runtime: fix MSVC C2326 in QueryApiImpl trampoline lock guard Nested Guard::~Guard cannot access an enclosing-function local under MSVC. Use a self-contained SrwExclusive that owns the SRWLOCK pointer. Co-authored-by: SimSalabimse --- src/startup_stubs/runtime_proxy.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/startup_stubs/runtime_proxy.cpp b/src/startup_stubs/runtime_proxy.cpp index b7d15fac3..316c79ef7 100644 --- a/src/startup_stubs/runtime_proxy.cpp +++ b/src/startup_stubs/runtime_proxy.cpp @@ -503,11 +503,12 @@ bool module_is_exe_or_package_helper(HMODULE module) noexcept bool install_query_export_trampoline() noexcept { static SRWLOCK lock = SRWLOCK_INIT; - AcquireSRWLockExclusive(&lock); - const auto unlock = [](SRWLOCK* l) { ReleaseSRWLockExclusive(l); }; - struct Guard { + struct SrwExclusive { SRWLOCK* l; - ~Guard() { unlock(l); } + explicit SrwExclusive(SRWLOCK* lock) noexcept : l(lock) { AcquireSRWLockExclusive(l); } + ~SrwExclusive() { ReleaseSRWLockExclusive(l); } + SrwExclusive(const SrwExclusive&) = delete; + SrwExclusive& operator=(const SrwExclusive&) = delete; } guard{&lock}; if (query_export_trampoline_done.load(std::memory_order_relaxed)) { From 1e9f0f96372f5482295eead5efc2d29c6ae6d0b9 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 25 Nov 2026 14:50:52 +0000 Subject: [PATCH 3/3] runtime: log QueryApiImpl trampoline pending and attach-window misses ce75 showed tip code with zero install/refuse lines because xgameruntime.dll never mapped; silent retries made that indistinguishable from a wrong deploy. Log rate-limited pending while the DLL is missing, abort on VirtualAlloc / VirtualProtect failure, note Ldr loads of xgameruntime.dll, and emit a one-shot after a 30s attach window. Co-authored-by: SimSalabimse --- docs/startup-runtime.md | 2 +- src/startup_stubs/runtime_proxy.cpp | 125 +++++++++++++++++++-- tests/startup_runtime_proxy_scope/host.cpp | 3 + 3 files changed, 120 insertions(+), 10 deletions(-) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index a545595b8..2446ddca0 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1174,7 +1174,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. When `xgameruntime.dll` is loaded the worker also installs an absolute-JMP trampoline at its `QueryApiImpl` export so a pointer cached before attach still enters the proxy; other modules that export the same name are not patched, and an unknown prologue is left alone. 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 (and notes an `xgameruntime.dll` load). 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. When `xgameruntime.dll` is loaded the worker also installs an absolute-JMP trampoline at its `QueryApiImpl` export so a pointer cached before attach still enters the proxy; other modules that export the same name are not patched, and an unknown prologue is left alone. While that DLL is missing the worker logs `export trampoline pending` (rate-limited) and, after 30 s, a one-shot `never loaded after 30s attach window` (or `still incomplete` if the module was seen); `VirtualAlloc` / `VirtualProtect` failures log `aborted` instead of failing silently. 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_proxy.cpp b/src/startup_stubs/runtime_proxy.cpp index 316c79ef7..fbc4ded97 100644 --- a/src/startup_stubs/runtime_proxy.cpp +++ b/src/startup_stubs/runtime_proxy.cpp @@ -11,8 +11,10 @@ // xgameruntime.dll is loaded, the worker also installs an absolute-JMP trampoline at the // QueryApiImpl export so a pointer cached before attach still enters the proxy (IAT/GPA rewrites do // not touch already-held function pointers). Unrelated modules that export the same name are not -// patched. The wrapper hands out proxy objects whose methods log their first calls ("x2w-runtime") -// and forward to the real object. +// patched. While the DLL is missing, the worker logs rate-limited "trampoline pending" lines and a +// one-shot "never loaded after 30s attach window" so silence is not ambiguous; VirtualAlloc / +// VirtualProtect failures log "aborted". 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). @@ -65,6 +67,9 @@ std::atomic real_query{nullptr}; // Live xgameruntime!QueryApiImpl address (patched in place). Null until the trampoline installs. std::atomic query_export_site{nullptr}; std::atomic query_export_trampoline_done{false}; +// Set when GetModuleHandle / Ldr load notice sees xgameruntime.dll (even if trampoline later aborts). +std::atomic xgr_module_seen{false}; +volatile LONG trampoline_pending_logs; bool keep_forward_target(FARPROC target) noexcept { @@ -497,9 +502,27 @@ bool module_is_exe_or_package_helper(HMODULE module) noexcept return true; } +// Rate-limited so a missing xgameruntime.dll is visible without flooding stderr (first + ~every 5 s +// when the worker scans every 25 ms). +void log_trampoline_pending(const char* reason) noexcept +{ + const LONG n = InterlockedIncrement(&trampoline_pending_logs); + if (n == 1 || n % 200 == 0) + x2w_local::logf("x2w-runtime QueryApiImpl export trampoline pending: %s", reason ? reason : "?"); +} + +void log_trampoline_abort(const char* reason, DWORD err) noexcept +{ + static LONG logged; + if (x2w_local::first_calls(logged, 1)) + x2w_local::logf("x2w-runtime QueryApiImpl export trampoline aborted: %s (err %lu)", reason ? reason : "?", + static_cast(err)); +} + // Install an absolute-JMP at xgameruntime!QueryApiImpl so pre-attach cached pointers enter the // proxy. Builds a stolen-prologue stub for real_query. Idempotent; refuses unknown prologues and // never patches a non-xgameruntime module. Runs outside DllMain (worker / GPA path after attach). +// Silent early returns are avoided: not-loaded stays pending (logged); hard failures abort with a line. bool install_query_export_trampoline() noexcept { static SRWLOCK lock = SRWLOCK_INIT; @@ -515,10 +538,25 @@ bool install_query_export_trampoline() noexcept return query_export_site.load(std::memory_order_relaxed) != nullptr; } const HMODULE runtime = GetModuleHandleW(L"xgameruntime.dll"); - if (!runtime || !module_is_xgameruntime(runtime)) return false; + if (!runtime) { + log_trampoline_pending("xgameruntime.dll not loaded yet"); + return false; + } + if (!module_is_xgameruntime(runtime)) { + log_trampoline_pending("GetModuleHandle(xgameruntime.dll) was not that basename"); + return false; + } + xgr_module_seen.store(true, std::memory_order_release); // Unpatched GetProcAddress: this stand-in's own IAT is left alone. const FARPROC export_fn = GetProcAddress(runtime, "QueryApiImpl"); - if (!export_fn || export_fn == reinterpret_cast(&proxy_query)) return false; + if (!export_fn) { + static LONG logged; + if (x2w_local::first_calls(logged, 1)) + x2w_local::logf("x2w-runtime QueryApiImpl export trampoline refused: QueryApiImpl export missing"); + query_export_trampoline_done.store(true, std::memory_order_release); + return false; + } + if (export_fn == reinterpret_cast(&proxy_query)) return false; auto* site = reinterpret_cast(export_fn); if (x2w_runtime_patch::is_abs_jmp_to(site, reinterpret_cast(&proxy_query))) { query_export_site.store(site, std::memory_order_release); @@ -527,8 +565,13 @@ bool install_query_export_trampoline() noexcept } HMODULE owner = nullptr; if (!GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, reinterpret_cast(site), &owner) || - !module_is_xgameruntime(owner)) + !module_is_xgameruntime(owner)) { + static LONG logged; + if (x2w_local::first_calls(logged, 1)) + x2w_local::logf("x2w-runtime QueryApiImpl export trampoline refused: export site not in xgameruntime.dll"); + query_export_trampoline_done.store(true, std::memory_order_release); return false; + } const unsigned stolen = x2w_runtime_patch::stolen_bytes_for_abs_jmp(site, 32); if (!stolen) { static LONG logged; @@ -541,6 +584,7 @@ bool install_query_export_trampoline() noexcept auto* stub = static_cast( VirtualAlloc(nullptr, stolen + x2w_runtime_patch::abs_jmp_bytes, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE)); if (!stub) { + log_trampoline_abort("VirtualAlloc for stolen-prologue stub failed", GetLastError()); query_export_trampoline_done.store(true, std::memory_order_release); return false; } @@ -551,8 +595,10 @@ bool install_query_export_trampoline() noexcept real_query.store(reinterpret_cast(stub), std::memory_order_release); DWORD old = 0; if (!VirtualProtect(site, stolen, PAGE_EXECUTE_READWRITE, &old)) { + const DWORD err = GetLastError(); VirtualFree(stub, 0, MEM_RELEASE); real_query.store(reinterpret_cast(export_fn), std::memory_order_release); + log_trampoline_abort("VirtualProtect on QueryApiImpl export failed", err); query_export_trampoline_done.store(true, std::memory_order_release); return false; } @@ -679,10 +725,56 @@ constexpr ULONG ldr_dll_notification_reason_loaded = 1; std::atomic rescan_package_modules{false}; static_assert(std::atomic::is_always_lock_free); -void CALLBACK dll_loaded(ULONG reason, const void*, void*) +bool wide_basename_is_xgameruntime(const wchar_t* name, USHORT bytes) noexcept { - if (reason == ldr_dll_notification_reason_loaded) - rescan_package_modules.store(true, std::memory_order_release); + if (!name || bytes < sizeof(L"xgameruntime.dll") - sizeof(wchar_t)) return false; + static constexpr wchar_t expect[] = L"xgameruntime.dll"; + const USHORT chars = static_cast(bytes / sizeof(wchar_t)); + // Match the final path component (BaseDllName is usually bare; FullDllName may include dirs). + USHORT start = 0; + for (USHORT i = 0; i < chars; ++i) + if (name[i] == L'\\' || name[i] == L'/') start = static_cast(i + 1); + const USHORT len = static_cast(chars - start); + constexpr USHORT expect_len = static_cast((sizeof(expect) / sizeof(expect[0])) - 1); + if (len != expect_len) return false; + for (USHORT i = 0; i < expect_len; ++i) { + wchar_t c = name[start + i]; + if (c >= L'A' && c <= L'Z') c = static_cast(c - L'A' + L'a'); + if (c != expect[i]) return false; + } + return true; +} + +void note_xgr_load_if_named(const void* notification_data) noexcept +{ + // LDR_DLL_LOADED_NOTIFICATION_DATA (ntdll): Flags, FullDllName, BaseDllName, DllBase, SizeOfImage. + struct UnicodeString { + USHORT Length; + USHORT MaximumLength; + wchar_t* Buffer; + }; + struct Loaded { + ULONG Flags; + const UnicodeString* FullDllName; + const UnicodeString* BaseDllName; + void* DllBase; + ULONG SizeOfImage; + }; + if (!notification_data) return; + const auto* loaded = static_cast(notification_data); + const UnicodeString* base = loaded->BaseDllName ? loaded->BaseDllName : loaded->FullDllName; + if (!base || !base->Buffer || !wide_basename_is_xgameruntime(base->Buffer, base->Length)) return; + if (xgr_module_seen.exchange(true, std::memory_order_acq_rel)) return; + static LONG logged; + if (x2w_local::first_calls(logged, 1)) + x2w_local::logf("x2w-runtime QueryApiImpl: xgameruntime.dll load noticed (Ldr)"); +} + +void CALLBACK dll_loaded(ULONG reason, const void* data, void*) +{ + if (reason != ldr_dll_notification_reason_loaded) return; + note_xgr_load_if_named(data); + rescan_package_modules.store(true, std::memory_order_release); } void patch_package_modules() @@ -746,11 +838,26 @@ 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. After a 30 s attach + // window, one line says whether xgameruntime.dll ever appeared (ce75: silence was ambiguous). rescan_package_modules.store(true, std::memory_order_release); + const DWORD attach_start = GetTickCount(); + bool logged_attach_window = false; for (;;) { if (rescan_package_modules.exchange(false, std::memory_order_acq_rel)) patch_package_modules(); + if (!logged_attach_window && !query_export_trampoline_done.load(std::memory_order_acquire) && + GetTickCount() - attach_start >= 30000u) { + logged_attach_window = true; + if (!xgr_module_seen.load(std::memory_order_acquire) && !GetModuleHandleW(L"xgameruntime.dll")) + x2w_local::logf( + "x2w-runtime QueryApiImpl export trampoline: xgameruntime.dll never loaded after 30s " + "attach window"); + else if (!query_export_trampoline_done.load(std::memory_order_acquire)) + x2w_local::logf( + "x2w-runtime QueryApiImpl export trampoline: still incomplete after 30s attach window " + "(xgameruntime seen)"); + } Sleep(25); } }, nullptr, 0, nullptr)) { diff --git a/tests/startup_runtime_proxy_scope/host.cpp b/tests/startup_runtime_proxy_scope/host.cpp index 4c4aa3284..f4a202d3f 100644 --- a/tests/startup_runtime_proxy_scope/host.cpp +++ b/tests/startup_runtime_proxy_scope/host.cpp @@ -82,6 +82,9 @@ int main() unsigned char decoy_prologue[16] = {}; if (decoy_query) std::memcpy(decoy_prologue, reinterpret_cast(decoy_query), sizeof(decoy_prologue)); + // Negative precondition: trampoline has nothing to patch until xgameruntime.dll is mapped. + check("xgameruntime not loaded before fixture maps it", GetModuleHandleW(L"xgameruntime.dll") == nullptr); + const HMODULE xgr = load_beside(dir, L"xgameruntime.dll"); check("load fake xgameruntime", xgr != nullptr); const FARPROC xgr_query = xgr ? GetProcAddress(xgr, "QueryApiImpl") : nullptr;