runtime: patch GetProcAddress in every loaded module #2158
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/2166"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Imported from R0Y00/Xbox2Windows. Originally posted by SimSalabimse on 2026-11-25T02:32:48Z.
Change
Account-picker TRACE_API (
X2W_TRACE_API=1) showed Y reaching GameInput (buttons 0x20) andGetKeyState, but zeroQueryApiImpl/ user-provider /x2w-apilines. The proxy had rewritten only the main EXEGetProcAddressIAT (1 GetProcAddress import(s) of the main module patched), so a helper DLL or delay-load path never hit the hook and FakeUser never wrapped a user provider.This change rewrites, in every loaded module (and later loads via
LdrRegisterDllNotification):GetProcAddressby name (regular and delay-import IAT)xgameruntime.dll!QueryApiImplnamed importThe GameInput stand-in’s own
GetProcAddressslot is left alone so the hook does not recurse.Refs #870. Does not complete FakeUser
XUserAddAsync(slot 7); that remains unjustified until a re-run shows provider calls after Y.AI-assisted.
Verification
On Windows after configure:
Windows runtime / D3D12 rebuild of
startup_stub_gameinputwas not run on this Linux host.Evidence and follow-up
Synthetic PE32+ image only (no game files). Negative control: name-only mutate must print
FAIL:.docs/startup-runtime.mdX2W_RUNTIME_PROXYrow updated.User re-run after this build: same
run.ps1with$env:X2W_TRACE_API='1', press Y, and check for multi-module patch lines plus anyQueryApiImpl/provider … proxied/ slot 7/8. If still zero providers, resolution is outside the patched IAT/GPA path.Checklist
Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-25T02:39:08Z.
Review: COMMENTED
Review of head
fbc106173da1b94496f12494a590cf63c77ee6ba.CI: Linux checks, gfx1013 fixtures and Windows build/test pass. Mergeable. Title is neutral, no game data.
Commands executed locally (Linux):
Mutations on the new logic:
dirs[13]->dirs[0]): test FAILS (3 mismatches). Killed.visit_named_thunks: test still passes. SURVIVED (see P2-2).P1
src/startup_stubs/runtime_proxy.cpp(patch_module, QueryApiImpl branch, ~line 437-443) plusruntime_gpa_patch.h(delay-import walk). Delay-import IAT slots do not hold the real function before the first call. They hold the delay-load thunk. The delay helper later writes the resolved address over the slot.xgameruntime.dll!QueryApiImpl,real_querycan be set to the delay thunk address (whenreal_queryis still null). Laterreal_query(...)calls (lines ~713, 743, 871 andproxy_query) then jump into the thunk, not the export.GetProcAddress, the slot is replaced by the hook, then the helper overwrites it at first use. The hook is lost, so the delay path the PR text claims to cover is not actually hooked.GetProcAddress(GetModuleHandle("xgameruntime.dll"), "QueryApiImpl")and do not read*slot. Or only recordreal_queryfrom a non-delay slot. Hook delayGetProcAddressthrough the delay-load hook (__pfnDliNotifyHook), or state that delay imports are not covered.P2
runtime_proxy.cpppatch_imports/patch_all_loaded_modules: the enumeration runs on a separate thread whiledll_loadedruns in loader context. Both callpatch_moduleand writereal_query(plain global, no atomic or lock). The slot compare avoids double patching, butreal_querycan race. Make itstd::atomicor set it once under a lock. Also, a module loaded between registration and enumeration is covered twice, which is fine, but a module loaded before registration and after the main-module patch is only covered by the thread, so a title that callsGetProcAddressright at startup can still miss the hook. Say so in the docs.tests/startup_runtime_gpa_patch_check.cpp: no ordinal-import case. Mutation removing the ordinal skip survived. Add an ordinal thunk (high bit set) beside the named ones and expect no hit and no out-of-range read.patch_all_loaded_modules: fixedHMODULE modules[512]. Ifneededexceeds the buffer, the first 512 are patched and the rest are skipped silently. The log printscountas if all were handled. Log a truncation or loop with a bigger buffer.Nits
runtime_gpa_patch.hvisit_imports:continueon a descriptor with a missing field still advances; fine, but a descriptor table without a terminator relies only on the range check. OK.AI-assisted; commands listed were executed locally.
Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-25T02:48:22Z.
Review: COMMENTED
Re-review of head
1f1b770f211b94496f12494a590cf63c77ee6ba(previous review was onfbc10617).CI at review time: Linux Python checks pass. Windows build/test and gfx1013 fixtures were still pending. Mergeable. Title is neutral, no game data.
Previous findings
visit_importsnow reports delay hits withdelay_import=true.patch_module(runtime_proxy.cpp~455-459) never rewrites or reads those slots. A delayQueryApiImplseedsreal_querythroughGetProcAddress(GetModuleHandle("xgameruntime.dll"), "QueryApiImpl"). DelayGetProcAddressstays unhooked, and the header and docs now say so.real_queryrace: RESOLVED. It isstd::atomicwith compare-exchange (first writer wins) and all readers useload_real_query(). Not re-checked: the docs note about a title callingGetProcAddressbefore the thread finishes.Commands executed locally
Mutations (reverted with
git checkout -- .):visit_named_thunks: test FAILS (5 mismatches). Killed. This is the mutant that survived last time.delay_import=false: test FAILS ("delay vs regular hits"). Killed.P1
None.
P2
None.
Nits
runtime_proxy.cppis Windows-only. It was not compiled or run here. It needs the Windows CI job (pending when I looked) to go green before Ready. The test covers the header logic only, not theVirtualProtectrewrite or the module enumeration.GetProcAddressis still not hooked. This is documented and acceptable for this slice. A later slice could use the delay-load notify hook.AI-assisted; commands listed were executed locally.
Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-25T02:56:42Z.
Review: CHANGES_REQUESTED
I would hold this revision on two points.
patch_module, which callsVirtualProtectand can callGetModuleHandleW/GetProcAddresson the delay-import path. For a newly loaded helper it also treats the regular IAT as already bound. Windows documents that this notification is pre-link and that calling into another module from it is unsafe. Please move the work to a point after linking and outside the notification, with the module held live while its slots are used. Windows loader callback contractQueryApiImpl. The current hook can wrap an unrelated DLL's same-named export and let it become the first cached provider address. The synthetic import-table walk covers a direct-import collision only. A source-built EXE and helper should exercise a late-loaded helper through the actual loader, verify the intended call is observed, and show an unrelated same-name export still reaches its original target. The zero-provider trace is an observation; which module and lookup path produced it remains open.Imported from R0Y00/Xbox2Windows. Originally posted by SimSalabimse on 2026-11-25T02:46:18Z.
Addressed @tedin7’s review on head
1f1b770f(follow-up commit on this branch).P1 — delay-import
Hitnow carriesdelay_import.xgameruntime.dll!QueryApiImplonly seedsreal_queryviaGetProcAddress(GetModuleHandleW(L"xgameruntime.dll"), "QueryApiImpl")(this stand-in’s own GPA IAT stays unpatched).GetProcAddressis not hooked; documented in the file header and theX2W_RUNTIME_PROXYrow indocs/startup-runtime.md.P2
real_queryisstd::atomicwith compare-exchange first-writer; callers useload_real_query().GetProcAddresshint RVA — removing the ordinal skip makes the test fail (confirmed locally).EnumProcessModules: grow the buffer when truncated and log; if still truncated after resize, log and patch the first N.GetProcAddresscan miss the hook.Verification (Linux)
AI-assisted.
Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-25T03:09:44Z.
Review: CHANGES_REQUESTED
The new loader fixture and moving Win32 calls out of the notification address the first review. Two lifetime issues remain in this head.
Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-25T03:11:57Z.
Review: COMMENTED
Re-review of head
efaaaebb402c26e932b61300fb061976380da24c(previous review was on1f1b770f; the branch was rewritten, now 3 commits).CI at review time: Linux Python checks pass, Windows build/test pass, gfx1013 fixtures pass.
/O2job skipped. Mergeable, not Draft. Title is neutral, no game data.What changed since the last review
dll_loaded(LdrDllNotification) only enqueues the base into a static ring (runtime_proxy.cpp~540-555). A worker thread drains it, pins the module withGetModuleHandleExW, rewrites, then drops the pin. This matches the rule that the pre-link callback must not call other modules.module_is_exe_or_package_helper). System modules are out.QueryApiImplis wrapped only when the provider basename isxgameruntime.dll.GetProcAddressIAT is left alone (selfcheck), so the hook cannot recurse.tests/startup_runtime_proxy_scope/*) passes in CI.Earlier findings (delay-import IAT,
real_queryrace, ordinal case, fixed module buffer) remain resolved.Commands executed locally
Mutation (reverted with
git checkout -- .): remove the ordinal skip atruntime_gpa_patch.h:128. Test FAILS. Killed.Not run locally:
runtime_proxy.cppand the loader-scope test are Windows-only. I rely on the green Windows CI job for them.P1
None.
P2
None.
Nits
dll_loadedoverwrites unread slots. The wrap log indrain_pending_loadsfires only whenpublished - read > pending_cap, and the worker already lost those bases. The 25 ms poll makes this unlikely. A fallback rescan ofEnumProcessModuleson that log line would close it.GetProcAddressis still unhooked (documented).AI-assisted; commands listed were executed locally.
Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-25T03:22:48Z.
Review: APPROVED
The revised source-built carrier test verifies the post-link helper and provider lifetime on this head. The coalesced rescan has no per-notification buffer, and the build collision is gone. Application first-call coverage remains unverified.
Imported from R0Y00/Xbox2Windows. Originally posted by tedin7 on 2026-11-25T03:26:28Z.
Review: COMMENTED
Re-review of head
4b1853f9be8f1e78eb7ac2e9ae878219e1b626f0(delta sinceefaaaebb: "Coalesce runtime loader notifications and keep proxy targets live").Scope checked:
src/startup_stubs/runtime_proxy.cpp,tests/startup_runtime_proxy_scope/host.cpp,docs/startup-runtime.md, CMake wiring.Commands executed locally (Linux):
git diff --stat origin/main...HEAD-> 14 files, +857/-40git diff --check origin/main...HEAD-> cleanpython3 -B tests/docs_links_check.py->Checked 18 Markdown files and 404 links.python3 -B tests/bidi_controls_check.py->no bidirectional controlsgh pr checks 2166-> Windows build+test, Linux Python checks, gfx1013 fixtures: pass; /O2 job skipping.What looks right
atomic<bool>(lock-free,static_asserted). It calls nothing in other modules and no longer has a fixed-size ring that could overwrite pending work. A burst of loads collapses to one rescan.GetModuleHandleExWwaits on the loader lock, so a module is not touched before it is linked.remember_real_query/keep_forward_targetpin the forward target before a proxy is handed out. If a different real target was already cached, the hook now returns the original pointer instead of a proxy that would forward to the wrong provider. The same pin guard covers theInitializeApiImpl*wrappers.GetModuleFileNameWtruncation (length >= MAX_PATH) is now treated as failure in all three call sites, so a truncated path cannot match the basename or directory gate.P1: none.
P2: none.
Nits
runtime_proxy.cppworker loop (patch_imports): pollsSleep(25)forever even when the flag is idle. Harmless, but an event/WaitOnAddresswould avoid a permanent wakeup every 25 ms. Not blocking.keep_forward_targetunderX2W_RUNTIME_PROXY_FIXTURE(runtime_proxy.cpp:64) returnstarget != nullptrwithout pinning, so the "target stays live" guarantee is only exercised by the scope fixture (real code path), not bystartup_runtime_local. Fine for stub targets; worth a comment.neededstays above the grown buffer inpatch_package_modules, later modules are silently skipped (a log line is emitted). Acceptable given the log.Not done / limits
host.cppassertions are the guard I would mutate (drop thePINflag inkeep_forward_target) on Windows.AI-assisted; commands listed were executed locally.
Imported from R0Y00/Xbox2Windows. Originally posted by SimSalabimse on 2026-11-25T03:07:13Z.
Addressed @R0Y00 CHANGES_REQUESTED (review 6051182008) on head
efaaaebb.1. LdrDllNotification (pre-link / no cross-module calls)
DllBasein a static ring and advances a published counter. NoVirtualProtect,GetModuleHandle,GetProcAddress, logging, or other cross-module calls (loader callback contract).GetModuleHandleEx(FROM_ADDRESS), rewrites regular IAT slots, thenFreeLibrarys the pin so the image stays live for the rewrite.2. Scope + provider module gate + loader fixture
QueryApiImpl/InitializeApiImpl*are wrapped only when the provider module basename isxgameruntime.dll(an unrelated same-named export is returned unchanged and cannot become the first cached provider).startup_runtime_proxy_scope: source-built EXE + carrier + fakexgameruntime.dll+ decoy + late-loaded helper through the real loader; asserts the helper sees the proxied xgameruntime entry and the decoy’sQueryApiImplstill hits the original. (X2W_RUNTIME_PROXY_FIXTUREkeepsstartup_runtime_local’s stubbed GPA path working.)Verification
Windows CI / local:
ctest --preset dev --no-tests=error -R '^startup_runtime_proxy_scope$'(and the existingstartup_runtime_gpa_patch*/startup_runtime_local*checks).Zero-provider account-picker traces remain observation only; this change does not claim that path is identified.
AI-assisted.
Imported from R0Y00/Xbox2Windows. Originally posted by R0Y00 on 2026-11-25T03:21:55Z.
The native build of
efaaaebbfailed because the load ring's pending_read collided with the save-read function already in the translation unit. This revision replaces the ring with a coalesced rescan flag and keeps the enabled proxy and its cached forwarding target live. The source-built loader fixture drops both caller references before making the calls, and a same-name decoy remains untouched. Release passed all five runtime checks and 30 consecutive runs of the loader fixture. The worker still provides eventual interception and first-call application coverage remains open.