From 58a283c3361d4a6452514c525489d15015b83d14 Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Fri, 13 Nov 2026 13:32:12 -0500 Subject: [PATCH 1/4] RR plugin: stay off when another Ray Reconstruction plugin is already active When another Ray Reconstruction plugin already holds the game's RR calls, or a second copy of WrongGPU-RR.asi is loaded, WrongGPU's RR plugin patches nothing, leaves Model M alone and writes one line to wronggpu-rr.log saying why. A plugin that loads later is found at the game's first call; WrongGPU's handlers then pass every call on unchanged. rr_other_plugin=take in wronggpu-rr.ini lets a player choose WrongGPU's RR on purpose. Every read of memory the plugin does not own is guarded; a read that fails counts as another plugin (the safe side). Two copies of the plugin write one log: each line is one append call under a process-wide lock, so lines never tear. The guard is read-only and generic (src/rr_guard.h/.cpp, HOOK-MODE.md "Another Ray Reconstruction plugin"). Tests: test_rr_guard (safe reads, jump forms, classification, one decision under 32 threads) and test_rr_guard_dll with a stand-in other plugin in every mode, for interface 2.7, 2.8 and 2.14, release and probe builds, plus a 200-run two-copy log stress. CI runs test_rr_guard. Fixes #22 Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> --- clean/rr_f/proxy/HOOK-MODE.md | 82 +++ clean/rr_f/proxy/src/hook_dll.cpp | 520 +++++++++++++++++-- clean/rr_f/proxy/src/log_append.h | 92 ++++ clean/rr_f/proxy/src/proxy_dll.cpp | 30 +- clean/rr_f/proxy/src/rr_guard.cpp | 335 ++++++++++++ clean/rr_f/proxy/src/rr_guard.h | 158 ++++++ clean/rr_f/proxy/tests/fake_other_rr.cpp | 201 +++++++ clean/rr_f/proxy/tests/guard_inject.cpp | 80 +++ clean/rr_f/proxy/tests/guard_scene.cpp | 137 +++++ clean/rr_f/proxy/tests/test_hook_dll.cpp | 7 + clean/rr_f/proxy/tests/test_rr_guard.cpp | 329 ++++++++++++ clean/rr_f/proxy/tests/test_rr_guard_dll.cpp | 462 ++++++++++++++++ clean/rr_f/proxy/tools/build.py | 80 ++- clean/rr_f/proxy/tools/guard_modelm.py | 106 ++++ tools/ci/run_proxy_core_tests.py | 3 +- 15 files changed, 2549 insertions(+), 73 deletions(-) create mode 100644 clean/rr_f/proxy/src/log_append.h create mode 100644 clean/rr_f/proxy/src/rr_guard.cpp create mode 100644 clean/rr_f/proxy/src/rr_guard.h create mode 100644 clean/rr_f/proxy/tests/fake_other_rr.cpp create mode 100644 clean/rr_f/proxy/tests/guard_inject.cpp create mode 100644 clean/rr_f/proxy/tests/guard_scene.cpp create mode 100644 clean/rr_f/proxy/tests/test_rr_guard.cpp create mode 100644 clean/rr_f/proxy/tests/test_rr_guard_dll.cpp create mode 100644 clean/rr_f/proxy/tools/guard_modelm.py diff --git a/clean/rr_f/proxy/HOOK-MODE.md b/clean/rr_f/proxy/HOOK-MODE.md index f868cf92..41227b1e 100644 --- a/clean/rr_f/proxy/HOOK-MODE.md +++ b/clean/rr_f/proxy/HOOK-MODE.md @@ -115,6 +115,88 @@ the display adapter's PCI identity through SetupAPI as well as DXGI; with the ho - **Tests:** `tests/test_setupapi_identity.cpp` (synthetic IDs through fake SetupAPI functions, the decision, and the redirect on the test exe's own imports with read-only SetupAPI queries of the PC's Display-class devices). +## Another Ray Reconstruction plugin (0.6.1) + +A player can end up with two RR plugins in one game (an integrator's installer may put this plugin next to another +one; the launcher is not involved then). Default: **WrongGPU RR stays off and says so in one line**; Model M is not +touched. The guard is generic and read-only (`src/rr_guard.{h,cpp}`, wired in `src/hook_dll.cpp`): it looks at where +the game's RR calls lead, never at another plugin's files or internals. Release and probe builds behave the same. + +**Signals, most reliable first** (each address is classified: this module, the game interface, the host = the module +that called `InitializeASI`, a copy of WrongGPU RR, another WrongGPU module, the exe, code outside every module, another +module; hook jumps are followed out of the interface and out of anonymous memory, up to 4): +1. **A second copy of WrongGPU RR** (`S0`): a process-wide marker (`Local\WrongGPU.rr-active.v1.`, holding the + active copy's path) taken at `InitializeASI`; a copy that finds it taken starts nothing (no hook, routes, NGX + provider, menu box, SetupAPI shim). A slot or export that leads into a module counting as WrongGPU RR (below) is the + same case. +2. **Import slots** (`S1`): before anything is patched, every loaded module's import slots of the game interface for + the roles this build would patch (and the exe's delay-load slots) must lead into the interface (a delay slot not + bound yet: the exe's own thunk; the host is accepted too). +3. **The RR exports' first bytes** (`S2`): the exports of is-supported, get-function, allocate and evaluate must not + jump out of the interface into another module (`jmp rel32/rel8`, `jmp [rip+disp32]`, `mov rax|r11, imm64; jmp reg`; + a `jmp [rip]` through the interface's own import table is its own code). The init export is not read: the host + patches it itself. +4. **Host routes** (plugin interface 3): `S2` on the module the host hooked (the host's trampolines, code outside every + module, are accepted there), then each route's next function (the host's `next`) after registering: another + plugin's route under ours leads to that plugin. Our routes cannot be taken back: they pass every call on. +5. **The NGX route** (plugin interface 4): the host keeps one RR provider; a refused registration means another + provider holds it, **for the NGX route only** (the game-interface route goes by its own signals). +6. **Later plugins** (`S4`): a plugin that loads after ours is found at `OptiPluginInit` and at the game's first call + into any of our handlers (decided once: concurrent first calls wait for the one decision): a slot we patched that + no longer holds our handler, or (while active) an RR export that now jumps away. Our handlers then pass every call + on unchanged (to the genuine export, which carries any later patch), and the NGX provider refuses creates. + +**Load orders.** Ours second: found at load, nothing patched, the core and the runtime are not loaded, no NGX provider. +Ours first: found at `OptiPluginInit` or the game's first call; pass-through from then on (the runtime is loaded but no +RR instance exists). Both late (run-time interface): the host-route checks above. The SetupAPI identity shim (not part +of the RR path) runs as configured while WrongGPU RR stays off because of another plugin; a second copy starts nothing. + +**Never a crash, and the safe side.** Every read of memory we do not own (slot values, export bytes, jump cells, the +host's next pointers, the module headers the scan walks) goes through `rr_guard`'s safe read: `VirtualQuery` for +committed, readable, non-guard pages, then a structured-exception-guarded copy (a cached region is re-checked by the +exception guard). A failed read is **unknown**, and unknown counts as another plugin (stays off, with the line). + +**False positives, known and accepted.** A mod that is not an RR plugin but hooks the interface's RR functions (for +example a frame-generation mod working through the same functions) makes WrongGPU RR stay off too: the line names its +module and `rr_other_plugin=take` puts WrongGPU RR back. Not triggers: the game's own RR (the calls lead into the +interface), the host's own init patch, WrongGPU.asi, a second copy of WrongGPU RR (its own line). + +**Override** (`wronggpu-rr.ini` next to the game exe): `rr_other_plugin = off` (default; also any unknown value, with a +line) or `take`. `take` with a plugin found at load: WrongGPU RR patches on top, answers the RR calls itself and +continues the other calls of the same functions through what the slot held before (the other plugin), so the other +plugin sees the game's other calls but never an RR create: one RR evaluate per frame. In host-route mode the same +through the host's next functions. `take` cannot be applied to a plugin that loads after ours (we never patch again; +no patch fights), to the NGX route, or to a second copy of WrongGPU RR. + +**Counting as WrongGPU.** A module counts as a copy of WrongGPU RR when it exports `WrongGPU_GetSettingsContract` +(the 60.9 contract export), and as another WrongGPU module (accepted, never "another plugin") when it exports +`WrongGpuAsiQuery` (WrongGPU.asi). The launcher can use the same exports to recognise WrongGPU's files. + +**Log lines** (`wronggpu-rr.log`, after the time stamp; the probe log adds `f=`). The launcher's Last run page +matches the **beginnings** of the first three; keep them exactly: +- `another Ray Reconstruction plugin is active; WrongGPU RR stays off (; nothing patched; rr_other_plugin=take in wronggpu-rr.ini uses WrongGPU's instead)` (found at load); + with host routes already installed: `...; WrongGPU's handlers pass every call on unchanged; rr_other_plugin=take ...)`; + found later: `another Ray Reconstruction plugin is active; WrongGPU RR stays off (; it loaded after WrongGPU: WrongGPU passes every call on unchanged; to use WrongGPU RR, move it aside)`; + NGX route: `another Ray Reconstruction plugin is active; WrongGPU RR stays off (NGX route only: the host refused WrongGPU's RR provider, another provider holds it; the game-interface route is decided on its own)`. +- `a second copy of WrongGPU RR is loaded ( is active); this copy () stays off` +- `a plugin loaded after WrongGPU replaced its hooks; rr_other_plugin=take cannot be applied: WrongGPU RR stays off and passes every call on unchanged (); move it aside to use WrongGPU RR` +- with take, found at load (RR is on): `another Ray Reconstruction plugin is active; rr_other_plugin=take: WrongGPU RR goes in front of it (; it gets the game's other calls, no RR work)` + +`` names the place and the module file, e.g. `the import slot of Game.exe leads to Other.asi`, `the +export of leads to Other.asi (through 2 hook jumps)`, `... could not be read`, `... leads to +code outside every module`. Diagnostics (not matched): `hook: coexistence check at load: ( address(es) read +in ms)` once per run (with its measured cost), `hook: coexistence re-check at : ...`, +`NGX: RR provider not registered: WrongGPU RR stays off in this process (see the line above)`. + +**Tests** (CPU only): `tests/test_rr_guard.cpp` (safe reads on PAGE_NOACCESS, reserved and guard pages and a page made +unreadable after caching; every jump form; synthetic modules; 32 threads at one decision); `tests/test_rr_guard_dll.cpp` +with our own stand-in other plugin `tests/fake_other_rr.cpp` (modes clean, first, inline, relay, anon, noaccess, +guardpage, late, late-replace, provider, owncopy, route, route-other, route-inline; `--take`; 16 threads at the first call), +for every interface version, release and probe (build.py); the existing hook runs check that no guard line appears. +`tools/guard_modelm.py` runs Model M's own ctest list unchanged with WrongGPU RR loaded into each test process before +its main and the guard tripped (none / off / take / owncopy / passthrough; `tests/guard_inject.cpp`, +`tests/guard_scene.cpp`). + ## Unload The plugin does **not** unload. OptiScaler keeps ASI plugins loaded for the process lifetime, and a patched IAT diff --git a/clean/rr_f/proxy/src/hook_dll.cpp b/clean/rr_f/proxy/src/hook_dll.cpp index ba2227ae..ddeb8fac 100644 --- a/clean/rr_f/proxy/src/hook_dll.cpp +++ b/clean/rr_f/proxy/src/hook_dll.cpp @@ -36,8 +36,17 @@ // compatible IDs of the real adapter report the same pair as DXGI. The exe's import slots of setupapi.dll are redirected // at InitializeASI; the decision is made at the game's first call (DXGI is not readable at InitializeASI; until it is, // the host's own spoof settings in OptiScaler.ini give the pair). wronggpu-rr.ini setupapi_identity=auto|off. +// +// RR guard: the coexistence guard (rr_guard.h, HOOK-MODE.md "Another Ray Reconstruction plugin"). Before +// anything is patched, the plugin reads where the game's RR calls lead (the import slots it would patch, the first bytes +// of the interface's RR exports, in host-route mode the host's continuation pointers). When they lead to another +// plugin, WrongGPU RR stays off (nothing patched, no NGX provider) and logs one line; a second copy of WrongGPU RR +// stays off too. A plugin that takes the calls after ours is found at OptiPluginInit or at the game's first call +// (decided once): our handlers then pass every call on unchanged. wronggpu-rr.ini rr_other_plugin=take puts WrongGPU RR +// in front of a plugin found at load. Every read of memory we do not own goes through rr_guard's safe reads. #define WIN32_LEAN_AND_MEAN #include +#include // RR guard: _ReturnAddress (the module that calls InitializeASI is the host) #include #include // NGX route: the device under a command list (a COM call only; no library) #include // clean/rr-sl-diag: the adapter of a LUID in the diagnostics (system dxgi.dll loaded at run time) @@ -55,9 +64,11 @@ #include +#include "log_append.h" #include "ngx_rr.h" #include "proxy_core.h" #include "rr_enabled.h" +#include "rr_guard.h" #include "rr_panel.h" #include "settings.h" #include "setupapi_identity.h" @@ -130,11 +141,19 @@ std::atomic g_last_rr_frame_ms{0}; std::atomic g_host_api{nullptr}; std::atomic g_host_api_plugin{nullptr}; std::mutex g_host_restore_mutex; +// RR guard (rr_guard.h): the guard's state for this process, the override, and the pass-through targets +wgrr::guard::Decision g_guard; +bool g_take = false; // wronggpu-rr.ini rr_other_plugin=take +std::atomic g_hook_done{false}; // our handlers are installed: the late check may run +HMODULE g_host_module = nullptr; // the module that called InitializeASI (the host) +void* g_prev[32] = {}; // take: what the exe's import slots held before us (the other plugin), by role +wgrr::OriginalApi g_fwd; // where a passing handler sends the call (the genuine export or the host's next) +HANDLE g_marker = nullptr; // the process-wide marker of the active WrongGPU RR copy (held for the run) #if WG_RR_PROBE wgrr::RrProbe* g_probe = nullptr; wgrr::ProbeLog* g_probe_log = nullptr; std::once_flag g_probe_log_once; -FILE* g_probe_file = nullptr; +std::wstring g_probe_path; // wronggpu-rr-probe.log (0.6.1: one append call per line, log_append.h) #else wgrr::RrProxy* g_proxy = nullptr; // clean/rr-ngx: the NGX RR provider (plugin interface 4) and the runtime / switch both routes share @@ -173,16 +192,17 @@ wgrr::ProbeLog* probe_log() { std::call_once(g_probe_log_once, [] { std::wstring path = data_dir() + L"wronggpu-rr-probe.log"; std::wstring prev = data_dir() + L"wronggpu-rr-probe.prev.log"; - MoveFileExW(path.c_str(), prev.c_str(), MOVEFILE_REPLACE_EXISTING); - g_probe_file = _wfopen(path.c_str(), L"wb"); + { + const wgrr::LogLock shared(path, wgrr::kLogLockWaitMs); + MoveFileExW(path.c_str(), prev.c_str(), MOVEFILE_REPLACE_EXISTING); + } + // RR guard, 0.6.1: a second WrongGPU RR copy appends its line to this file too: every line is one append + // call under the log's process-wide lock (log_append.h), so neither copy's line is torn or overwritten + g_probe_path = path; g_probe_log = new wgrr::ProbeLog([](const std::string& line) { std::lock_guard lock(g_log_mutex); - if (!g_probe_file) return; - SYSTEMTIME t; - GetLocalTime(&t); - fprintf(g_probe_file, "%02u:%02u:%02u.%03u %s\r\n", t.wHour, t.wMinute, t.wSecond, t.wMilliseconds, - line.c_str()); - fflush(g_probe_file); + const wgrr::LogLock shared(g_probe_path, wgrr::kLogLockWaitMs); + wgrr::append_log_text(g_probe_path, wgrr::log_stamp() + line + "\r\n"); // each write reaches the file at once }); g_probe_log->note(std::string("probe start: build Streamline 2.") + std::to_string(g_api_minor) + " (hook mode), process " + std::to_string(GetCurrentProcessId())); @@ -198,9 +218,10 @@ wchar_t g_log_path[MAX_PATH * 2] = {0}; // clean/060-rr-plugin-hunt: wronggpu-rr.log is appended to across game starts; past this size it is moved to // wronggpu-rr.log.old (replacing an older one) and a new file starts, so it cannot grow without end. constexpr uint64_t kLogCapBytes = 8ull << 20; -uint64_t g_log_bytes = UINT64_MAX; // the file's size as this process knows it (UINT64_MAX: not read yet); g_log_mutex +uint64_t g_log_rotate_blocked_below = 0; // a rotation that failed (the file held open elsewhere): again 1 MiB later; g_log_mutex #endif +// RR guard, 0.6.1: one line = one append call under the log's process-wide lock (log_append.h says why) void log_line(const std::string& s) { #if WG_RR_PROBE probe_log()->note(s); @@ -208,27 +229,24 @@ void log_line(const std::string& s) { std::lock_guard lock(g_log_mutex); std::wstring path = data_dir() + L"wronggpu-rr.log"; if (!g_log_path[0] && path.size() < sizeof g_log_path / sizeof g_log_path[0]) wcscpy_s(g_log_path, path.c_str()); - if (g_log_bytes == UINT64_MAX) { - WIN32_FILE_ATTRIBUTE_DATA a; - g_log_bytes = GetFileAttributesExW(path.c_str(), GetFileExInfoStandard, &a) - ? ((uint64_t)a.nFileSizeHigh << 32) | a.nFileSizeLow : 0; - } - bool rotated = false; - if (g_log_bytes >= kLogCapBytes) { - rotated = MoveFileExW(path.c_str(), (path + L".old").c_str(), MOVEFILE_REPLACE_EXISTING) != 0; - g_log_bytes = rotated ? 0 : kLogCapBytes - (1u << 20); // not movable now (held open elsewhere): again 1 MiB later - } - FILE* f = _wfopen(path.c_str(), L"ab"); - if (!f) return; - SYSTEMTIME t; - GetLocalTime(&t); - int n = 0; - if (rotated) - n += fprintf(f, "%02u:%02u:%02u.%03u log: wronggpu-rr.log reached %u MiB; the earlier lines are in wronggpu-rr.log.old\r\n", - t.wHour, t.wMinute, t.wSecond, t.wMilliseconds, (unsigned)(kLogCapBytes >> 20)); - n += fprintf(f, "%02u:%02u:%02u.%03u %s\r\n", t.wHour, t.wMinute, t.wSecond, t.wMilliseconds, s.c_str()); - fclose(f); - if (n > 0) g_log_bytes += (uint64_t)n; + const wgrr::LogLock shared(path, wgrr::kLogLockWaitMs); + const std::string ts = wgrr::log_stamp(); + std::string text; + // the size as the file has it now (another copy may have written): checked and rotated only while holding the lock + const uint64_t size = shared.owned() ? wgrr::log_file_size(path) : 0; + if (size >= kLogCapBytes && size >= g_log_rotate_blocked_below) { + if (MoveFileExW(path.c_str(), (path + L".old").c_str(), MOVEFILE_REPLACE_EXISTING)) { + char b[160]; + snprintf(b, sizeof b, "log: wronggpu-rr.log reached %u MiB; the earlier lines are in wronggpu-rr.log.old\r\n", + (unsigned)(kLogCapBytes >> 20)); + text = ts + b; + g_log_rotate_blocked_below = 0; + } else { + g_log_rotate_blocked_below = size + (1u << 20); + } + } + text += ts + s + "\r\n"; + wgrr::append_log_text(path, text); #endif } @@ -313,6 +331,10 @@ void bind(F& slot, int role) { slot = reinterpret_cast(g_route_next[role]); // host route: continue through the host's chain return; } + if (g_take && g_prev[role]) { // RR guard, take: continue through the other plugin (it sees no RR work) + slot = reinterpret_cast(g_prev[role]); + return; + } slot = name[0] ? reinterpret_cast(GetProcAddress(g_interposer, name)) : nullptr; } @@ -686,12 +708,23 @@ bool ngx_route_holds_rr(uint32_t feature) { #endif } +// RR guard: the late decision (below, with the IAT code), taken once at the first call after our handlers +// are installed; a handler passes the call on unchanged (to g_fwd) while WrongGPU RR is not active. +void guard_first_call(); +bool guard_pass() { + if (!g_guard.frozen() && g_hook_done.load(std::memory_order_acquire)) guard_first_call(); + return !g_guard.active(); +} +#define WG_PASS(field, ...) \ + if (guard_pass()) return g_fwd.field ? g_fwd.field(__VA_ARGS__) : WG_E_MISSING_OR_INVALID_API + } // namespace // ---------------------------------------------------------------- the handlers installed into the IAT extern "C" { WgResultCode wg_role_init(const WgPreferences* p, uint64_t v) { + WG_PASS(init, p, v); auto* t = entered(0); char buf[200]; snprintf(buf, sizeof buf, "init entered: thread %lu preferences=0x%llx sdk_version=0x%016llx (hook mode)", @@ -699,28 +732,65 @@ WgResultCode wg_role_init(const WgPreferences* p, uint64_t v) { log_line(buf); return t->init(p, v); } -WgResultCode wg_role_shutdown(void) { return entered(1)->shutdown(); } -WgResultCode wg_role_is_supported(uint32_t f, const WgAdapterInfo* a) { return entered(2)->is_supported(f, a); } -WgResultCode wg_role_is_loaded(uint32_t f, bool* l) { return entered(3)->is_loaded(f, l); } -WgResultCode wg_role_set_loaded(uint32_t f, bool l) { return entered(4)->set_loaded(f, l); } -WgResultCode wg_role_requirements(uint32_t f, WgRequirements* r) { return entered(5)->requirements(f, r); } -WgResultCode wg_role_version(uint32_t f, WgFeatureVersion* v) { return entered(6)->version(f, v); } -WgResultCode wg_role_get_function(uint32_t f, const char* n, void** o) { return entered(7)->get_function(f, n, o); } +WgResultCode wg_role_shutdown(void) { + WG_PASS(shutdown); + return entered(1)->shutdown(); +} +WgResultCode wg_role_is_supported(uint32_t f, const WgAdapterInfo* a) { + WG_PASS(is_supported, f, a); + return entered(2)->is_supported(f, a); +} +WgResultCode wg_role_is_loaded(uint32_t f, bool* l) { + WG_PASS(is_loaded, f, l); + return entered(3)->is_loaded(f, l); +} +WgResultCode wg_role_set_loaded(uint32_t f, bool l) { + WG_PASS(set_loaded, f, l); + return entered(4)->set_loaded(f, l); +} +WgResultCode wg_role_requirements(uint32_t f, WgRequirements* r) { + WG_PASS(requirements, f, r); + return entered(5)->requirements(f, r); +} +WgResultCode wg_role_version(uint32_t f, WgFeatureVersion* v) { + WG_PASS(version, f, v); + return entered(6)->version(f, v); +} +WgResultCode wg_role_get_function(uint32_t f, const char* n, void** o) { + WG_PASS(get_function, f, n, o); + return entered(7)->get_function(f, n, o); +} WgResultCode wg_role_allocate(void* c, uint32_t f, const WgViewport* v) { + WG_PASS(allocate, c, f, v); if (ngx_route_holds_rr(f)) return WG_E_INVALID_STATE; return entered(8)->allocate(c, f, v); } -WgResultCode wg_role_free(uint32_t f, const WgViewport* v) { return entered(9)->free_resources(f, v); } -WgResultCode wg_role_set_device(void* d) { return entered(10)->set_device(d); } -WgResultCode wg_role_tag(const WgViewport* v, const WgTag* t, uint32_t n, void* c) { return entered(12)->tag(v, t, n, c); } +WgResultCode wg_role_free(uint32_t f, const WgViewport* v) { + WG_PASS(free_resources, f, v); + return entered(9)->free_resources(f, v); +} +WgResultCode wg_role_set_device(void* d) { + WG_PASS(set_device, d); + return entered(10)->set_device(d); +} +WgResultCode wg_role_tag(const WgViewport* v, const WgTag* t, uint32_t n, void* c) { + WG_PASS(tag, v, t, n, c); + return entered(12)->tag(v, t, n, c); +} WgResultCode wg_role_tag_for_frame(const WgFrameToken* k, const WgViewport* v, const WgTag* t, uint32_t n, void* c) { + WG_PASS(tag_for_frame, k, v, t, n, c); return entered(13)->tag_for_frame(k, v, t, n, c); } WgResultCode wg_role_constants(const WgConstants* c, const WgFrameToken* k, const WgViewport* v) { + WG_PASS(constants, c, k, v); return entered(14)->constants(c, k, v); } -WgResultCode wg_role_new_frame_token(WgFrameToken** o, const uint32_t* i) { return entered(15)->new_frame_token(o, i); } +WgResultCode wg_role_new_frame_token(WgFrameToken** o, const uint32_t* i) { + WG_PASS(new_frame_token, o, i); + return entered(15)->new_frame_token(o, i); +} WgResultCode wg_role_evaluate(uint32_t f, const WgFrameToken* k, const WgHeader* const* in, uint32_t n, void* c) { + WG_PASS(evaluate, f, k, in, n, c); if (ngx_route_holds_rr(f)) return WG_E_INVALID_STATE; const WgResultCode rc = entered(16)->evaluate(f, k, in, n, c); if (rc == WG_OK && f == WG_FEAT_RAY_RECONSTRUCTION) { @@ -732,9 +802,18 @@ WgResultCode wg_role_evaluate(uint32_t f, const WgFrameToken* k, const WgHeader* return rc; } #if WG_RR_PROBE -WgResultCode wg_role_set_vulkan_info(const void* info) { return entered(11)->set_vulkan_info(info); } -WgResultCode wg_role_upgrade_interface(void** iface) { return entered(17)->upgrade_interface(iface); } -WgResultCode wg_role_native_interface(void* w, void** n) { return entered(18)->native_interface(w, n); } +WgResultCode wg_role_set_vulkan_info(const void* info) { + WG_PASS(set_vulkan_info, info); + return entered(11)->set_vulkan_info(info); +} +WgResultCode wg_role_upgrade_interface(void** iface) { + WG_PASS(upgrade_interface, iface); + return entered(17)->upgrade_interface(iface); +} +WgResultCode wg_role_native_interface(void* w, void** n) { + WG_PASS(native_interface, w, n); + return entered(18)->native_interface(w, n); +} #endif WgResultCode wg_rr_optimal_fn(const WgRrOptions* o, WgRrOptimal* s) { return entered("rr-optimal")->rr_optimal(o, s); } @@ -742,7 +821,8 @@ WgResultCode wg_rr_state_fn(const WgViewport* v, WgRrState* s) { return entered( WgResultCode wg_rr_options_fn(const WgViewport* v, const WgRrOptions* o) { return entered("rr-options")->rr_options(v, o); } const WgRrSettingsContract* wg_get_settings_contract(void) { - diagnostics(WG_RR_CONTRACT_EXPORT); + // RR guard: a second copy keeps its hands off the log (the active copy writes it) + if (g_guard.state() != wgrr::guard::State::kOwnCopy) diagnostics(WG_RR_CONTRACT_EXPORT); ensure_settings(); return wgrr::settings_contract(); } @@ -1043,6 +1123,242 @@ DWORD WINAPI slot_watch_thread(void*) { return 0; } +// ---------------------------------------------------------------- RR guard: another RR plugin (rr_guard.h) +// The roles whose exports' first bytes are read (S2): the ones that decide where RR goes. The init export is not among +// them: the host patches it itself (HOOK-MODE.md). +const int kWgDecisiveRoles[] = {2, 7, 8, 16}; // is-supported, get-function, allocate, evaluate + +double ms_since(const LARGE_INTEGER& t0) { + LARGE_INTEGER t1, f; + QueryPerformanceCounter(&t1); + QueryPerformanceFrequency(&f); + return f.QuadPart ? 1000.0 * (double)(t1.QuadPart - t0.QuadPart) / (double)f.QuadPart : 0.0; +} +std::string ms_text(double ms) { + char b[32]; + snprintf(b, sizeof b, "%.3f ms", ms); + return b; +} +std::string leaf_text(HMODULE m) { + std::wstring w; + module_leaf(m, &w); + return ascii(narrow(w)); +} + +// The hooked role (gen_forwarding.ROLES index) of an import name in this run's route, or -1. +int role_for_name(const char* name) { + for (unsigned i = 0; i < WG_BINDING_HOOK_ROLE_COUNT; ++i) { + const int role = kWgHookRoles[i]; + if (role_in_route(role) && kWgRoleNames[role][0] && handler_for(role) && strcmp(kWgRoleNames[role], name) == 0) + return role; + } + return -1; +} + +// Every import slot of `module` that names a hooked role from the DLL `leaf`, read through the guard's reader: f(role, +// import name, slot address). +template +void guard_import_slots(HMODULE module, const char* leaf, wgrr::guard::Reader& r, F f) { + const uint8_t* base = reinterpret_cast(module); + IMAGE_DOS_HEADER dos; + IMAGE_NT_HEADERS64 nt; + if (!r.get(base, &dos) || dos.e_magic != IMAGE_DOS_SIGNATURE || !r.get(base + dos.e_lfanew, &nt) || + nt.Signature != IMAGE_NT_SIGNATURE || nt.OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) + return; + const IMAGE_DATA_DIRECTORY& d = nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; + if (!d.VirtualAddress || !d.Size) return; + const IMAGE_IMPORT_DESCRIPTOR* desc = reinterpret_cast(base + d.VirtualAddress); + for (unsigned k = 0; k < 4096; ++k) { + IMAGE_IMPORT_DESCRIPTOR e; + if (!r.get(desc + k, &e) || !e.Name) return; + char dll[64]; + if (!r.str(base + e.Name, dll, sizeof dll) || _stricmp(dll, leaf) != 0) continue; + const IMAGE_THUNK_DATA64* names = + reinterpret_cast(base + (e.OriginalFirstThunk ? e.OriginalFirstThunk : e.FirstThunk)); + const IMAGE_THUNK_DATA64* iat = reinterpret_cast(base + e.FirstThunk); + for (unsigned i = 0; i < 4096; ++i) { + IMAGE_THUNK_DATA64 t; + if (!r.get(names + i, &t) || !t.u1.AddressOfData) break; + if (t.u1.Ordinal & IMAGE_ORDINAL_FLAG64) continue; + char nm[96]; + if (!r.str(base + t.u1.AddressOfData + offsetof(IMAGE_IMPORT_BY_NAME, Name), nm, sizeof nm)) continue; + const int role = role_for_name(nm); + if (role >= 0) f(role, nm, const_cast(reinterpret_cast(&iat[i].u1.Function))); + } + } +} + +// S0: the process-wide marker of the active WrongGPU RR copy. True: this copy is the first (it holds the marker). False: +// another copy holds it; this copy stays off (one line). +bool guard_claim_marker() { + wchar_t name[64]; + swprintf(name, 64, L"Local\\WrongGPU.rr-active.v1.%lu", (unsigned long)GetCurrentProcessId()); + HANDLE h = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, 4096, name); + if (!h) return true; // cannot tell: the slot scan still sees a copy that patched + const bool existed = GetLastError() == ERROR_ALREADY_EXISTS; + wchar_t* view = static_cast(MapViewOfFile(h, FILE_MAP_ALL_ACCESS, 0, 0, 4096)); + if (!existed) { + if (view) wcsncpy_s(view, 2047, own_path().c_str(), _TRUNCATE); + if (view) UnmapViewOfFile(view); + g_marker = h; + return true; + } + const std::wstring active = view ? std::wstring(view, wcsnlen(view, 2047)) : std::wstring(L"another copy"); + if (view) UnmapViewOfFile(view); + CloseHandle(h); + g_guard.set(wgrr::guard::State::kOwnCopy); + const std::string line = wgrr::guard::line_own_copy(ascii(narrow(active)), ascii(narrow(own_path()))); +#if WG_RR_PROBE + // the active copy writes the probe log (opening it here would start it again): append the one line to it + { + const std::wstring probe_path = data_dir() + L"wronggpu-rr-probe.log"; + const wgrr::LogLock shared(probe_path, wgrr::kLogLockWaitMs); // the active copy's writes and this one, in one order + wgrr::append_log_text(probe_path, wgrr::log_stamp() + line + "\r\n"); + } +#else + log_line(line); +#endif + return false; +} + +void guard_read_override() { + ensure_settings(); + std::string note; + g_take = wgrr::guard::override_take(g_settings.text(wgrr::guard::kOverrideKey), ¬e); + if (!note.empty()) log_line("hook: " + note); +} + +// S2: the first bytes of the interface's RR-deciding exports (module = the interface). anon_ok: code outside every module +// is accepted (host-route mode: the host's own trampolines). +void guard_scan_exports(HMODULE module, const wgrr::guard::Env& env, bool anon_ok, wgrr::guard::Verdict* v) { + const std::string leaf = leaf_text(module); + for (int role : kWgDecisiveRoles) { + if (!role_in_route(role) || !kWgRoleNames[role][0]) continue; + const void* e = reinterpret_cast(GetProcAddress(module, kWgRoleNames[role])); + if (!e) continue; + v->add(wgrr::guard::classify(e, env, true), std::string("the export ") + kWgRoleNames[role] + " of " + leaf, anon_ok, + false); + } +} + +// At load (do_hook, before the core is built and before anything is patched): S1 over every module's import slots of +// the interface (and the exe's delay-load slots), S2 over the RR exports. True: go on (active, or take). False: off. +bool guard_at_load(const IMAGE_DELAYLOAD_DESCRIPTOR* delay) { + namespace g = wgrr::guard; + guard_read_override(); + LARGE_INTEGER t0; + QueryPerformanceCounter(&t0); + const g::Env env = g::process_env(g_self, g_interposer, g_host_module); + g::Reader r; + g::Verdict v; + std::wstring leaf_w; + module_leaf(g_interposer, &leaf_w); + const std::string leaf = narrow(leaf_w); + HMODULE exe = GetModuleHandleW(nullptr); + void* prev[32] = {}; + HMODULE mods[1024]; + DWORD need = 0; + if (K32EnumProcessModules(GetCurrentProcess(), mods, sizeof mods, &need)) { + const unsigned count = (unsigned)(need / sizeof(HMODULE)) < 1024 ? (unsigned)(need / sizeof(HMODULE)) : 1024; + for (unsigned i = 0; i < count; ++i) { + if (mods[i] == g_self || mods[i] == g_interposer) continue; + guard_import_slots(mods[i], leaf.c_str(), r, [&](int role, const char* nm, void** slot) { + void* val = nullptr; + const g::Where w = r.get(slot, &val) ? g::classify(val, env, false) : g::Where(); + v.add(w, std::string("the import slot ") + nm + " of " + leaf_text(mods[i]), false, false); + if (mods[i] == exe && val && w.owner != g::Owner::kInterface) prev[role] = val; + }); + } + } + if (delay) { // the exe's delay-load slots: unbound ones hold the delay helper's thunk in the exe + const uint8_t* base = reinterpret_cast(exe); + const IMAGE_THUNK_DATA64* names = reinterpret_cast(base + delay->ImportNameTableRVA); + const IMAGE_THUNK_DATA64* iat = reinterpret_cast(base + delay->ImportAddressTableRVA); + for (unsigned i = 0; i < 4096; ++i) { + IMAGE_THUNK_DATA64 t; + if (!r.get(names + i, &t) || !t.u1.AddressOfData) break; + if (t.u1.Ordinal & IMAGE_ORDINAL_FLAG64) continue; + char nm[96]; + if (!r.str(base + t.u1.AddressOfData + offsetof(IMAGE_IMPORT_BY_NAME, Name), nm, sizeof nm)) continue; + const int role = role_for_name(nm); + if (role < 0) continue; + void* val = nullptr; + const g::Where w = r.get(&iat[i].u1.Function, &val) ? g::classify(val, env, false) : g::Where(); + v.add(w, std::string("the delay-load slot ") + nm + " of " + leaf_text(exe), false, true); + if (val && w.owner != g::Owner::kInterface && w.owner != g::Owner::kExeThunk && w.owner != g::Owner::kHost) + prev[role] = val; + } + } + guard_scan_exports(g_interposer, env, false, &v); + const double ms = ms_since(t0); + const char* result = v.kind == g::Verdict::kClean ? "no other Ray Reconstruction plugin found" + : v.kind == g::Verdict::kOwnCopy ? "a second copy of WrongGPU RR found" + : "another Ray Reconstruction plugin found"; + log_line("hook: coexistence check at load: " + std::string(result) + " (" + std::to_string(v.reads) + + " address(es) read in " + ms_text(ms) + ")"); + if (v.kind == g::Verdict::kOwnCopy) { + g_guard.set(g::State::kOwnCopy); + log_line(g::line_own_copy(v.detail, ascii(narrow(own_path())))); + return false; + } + if (v.kind == g::Verdict::kOther) { + if (!g_take) { + g_guard.set(g::State::kOff); + log_line(g::line_other(v.detail)); + return false; + } + memcpy(g_prev, prev, sizeof g_prev); + g_guard.set(g::State::kTaken); + log_line(g::line_take(v.detail)); + } + return true; +} + +// S4: after our handlers are installed. Our patched slots that no longer hold our handler lead somewhere else; while +// active (not taken) the RR exports are read again too. Returns the state to keep; logs only a finding (and, with +// log_clean, the clean result and its cost). +wgrr::guard::State guard_late(const char* why, bool log_clean) { + namespace g = wgrr::guard; + const g::State s = g_guard.state(); + if (s != g::State::kActive && s != g::State::kTaken) return s; + LARGE_INTEGER t0; + QueryPerformanceCounter(&t0); + const g::Env env = g::process_env(g_self, g_interposer, g_host_module); + g::Verdict v; + { + std::lock_guard lock(g_watch_mutex); + for (const SlotWatch& w : g_watch) { + if (!w.ours) continue; + void* val = nullptr; + if (g::safe_get(w.slot, &val) && val == w.ours) { + ++v.reads; + continue; + } + const size_t slash = w.module.find_last_of("\\/"); // the module's file name, as at load + v.add(val ? g::classify(val, env, false) : g::Where(), "the " + w.kind + " slot " + w.name + " of " + + (slash == std::string::npos ? w.module : w.module.substr(slash + 1)) + " (WrongGPU's hook)", false, false); + } + } + if (s == g::State::kActive && g_interposer && !g_route_mode.load()) guard_scan_exports(g_interposer, env, false, &v); + const double ms = ms_since(t0); + if (v.kind == g::Verdict::kClean) { + if (log_clean) + log_line(std::string("hook: coexistence re-check at ") + why + ": no other Ray Reconstruction plugin found (" + + std::to_string(v.reads) + " address(es) read in " + ms_text(ms) + ")"); + return s; + } + log_line(std::string("hook: coexistence re-check at ") + why + ": " + + (v.kind == g::Verdict::kOwnCopy ? "a second copy of WrongGPU RR" : "another Ray Reconstruction plugin") + + " took the RR calls after WrongGPU (" + std::to_string(v.reads) + " address(es) read in " + ms_text(ms) + ")"); + if (v.kind == g::Verdict::kOwnCopy) log_line(g::line_own_copy(v.detail, ascii(narrow(own_path())))); + else log_line(g_take ? g::line_cannot_take(v.detail) : g::line_other_later(v.detail)); + return g::State::kPassThrough; +} + +void guard_first_call() { + g_guard.freeze_once([] { return guard_late("the game's first call", true); }); +} + void do_hook() { diagnostics("InitializeASI"); std::wstring interposer_w; @@ -1082,6 +1398,10 @@ void do_hook() { g_api_minor = v[1]; log_line("hook: route Streamline 2." + std::to_string(g_api_minor) + " chosen for this game interface"); + // RR guard: another RR plugin already holding these calls keeps WrongGPU RR off (nothing built or patched) + if (!guard_at_load(delay)) return; + g_fwd = bind_original(); // where a passing handler sends a call (the late decision, guard_first_call) + // Build the core now, so our handlers forward to the genuine exports (the IAT's pre-patch addresses). (void)target(); // We loaded the interface ourselves for a delay-load import: nothing has called it, so the game's is still @@ -1138,6 +1458,7 @@ void do_hook() { #endif ) + ". Non-RR traffic reaches the game interface unchanged."); + g_hook_done.store(true, std::memory_order_release); // RR guard: the late check may run from now on } // The host hooked a game interface module (plugin interface 3): check its version against this build's binding, @@ -1160,6 +1481,36 @@ void on_host_hooked(void* module, uint32_t major, uint32_t minor, uint32_t patch } g_api_minor = minor; // before the core is built (target() below) log_line("hook: route Streamline 2." + std::to_string(g_api_minor) + " chosen for this game interface"); + // RR guard: the RR exports of the module the host hooked (its own trampolines are accepted), before our routes + namespace g = wgrr::guard; + if (!g_guard.active()) { + log_line("hook: no game-interface routes registered: WrongGPU RR stays off in this process (see the line above)"); + return; + } + guard_read_override(); + { + LARGE_INTEGER t0; + QueryPerformanceCounter(&t0); + g::Verdict v; + guard_scan_exports(static_cast(module), g::process_env(g_self, module, g_host_module), true, &v); + log_line(std::string("hook: coexistence check before the host routes: ") + + (v.kind == g::Verdict::kClean ? "no other Ray Reconstruction plugin found" : "another plugin found") + " (" + + std::to_string(v.reads) + " address(es) read in " + ms_text(ms_since(t0)) + ")"); + if (v.kind == g::Verdict::kOwnCopy) { + g_guard.set(g::State::kOwnCopy); + log_line(g::line_own_copy(v.detail, ascii(narrow(own_path())))); + return; + } + if (v.kind == g::Verdict::kOther && !g_take) { + g_guard.set(g::State::kOff); + log_line(g::line_other(v.detail)); + return; + } + if (v.kind == g::Verdict::kOther) { + g_guard.set(g::State::kTaken); + log_line(g::line_take(v.detail)); + } + } std::vector routes; for (unsigned i = 0; i < WG_BINDING_HOOK_ROLE_COUNT; ++i) { const int role = kWgHookRoles[i]; @@ -1176,6 +1527,35 @@ void on_host_hooked(void* module, uint32_t major, uint32_t minor, uint32_t patch } unsigned installed = 0; for (const WgHostSlRoute& r : routes) installed += (*r.next != nullptr); + // RR guard: where each route continues (the host's next): another plugin's route under ours means it holds + // the RR path below us. Our routes are installed and cannot be taken back: they pass every call on (or, with take, + // keep RR and pass the other calls on). + { + LARGE_INTEGER t0; + QueryPerformanceCounter(&t0); + const g::Env env = g::process_env(g_self, module, g_host_module); + g::Verdict v; + for (const WgHostSlRoute& r : routes) + if (*r.next) v.add(g::classify(*r.next, env, false), std::string("the host's next function of ") + r.export_name, + true, false); + log_line(std::string("hook: coexistence check of the host routes: ") + + (v.kind == g::Verdict::kClean ? "no other Ray Reconstruction plugin found" : "another plugin found") + " (" + + std::to_string(v.reads) + " address(es) read in " + ms_text(ms_since(t0)) + ")"); + g_fwd = bind_original(); // the host's next functions + if (v.kind != g::Verdict::kClean) { + if (v.kind == g::Verdict::kOther && g_take) { + g_guard.set(g::State::kTaken); + log_line(g::line_take(v.detail)); + } else { + g_guard.set(g::State::kPassThrough); + log_line(v.kind == g::Verdict::kOwnCopy ? g::line_own_copy(v.detail, ascii(narrow(own_path()))) + : g::line_other(v.detail, true)); + g_hook_done.store(true, std::memory_order_release); + return; + } + } + } + g_hook_done.store(true, std::memory_order_release); (void)target(); // the core forwards to the host's next functions from now on log_line("hook: " + std::to_string(installed) + " of " + std::to_string(routes.size()) + " game-interface route(s) installed by the host; RR " + @@ -1398,8 +1778,15 @@ void ngx_release_cpp(void* u, void* ctx) { ngx_fault("release (exception)"); } } +// RR guard: another RR plugin was found after the provider was registered: creates are refused (logged once) +bool ngx_guard_refuses() { + if (g_guard.active()) return false; + static std::atomic logged{false}; + if (!logged.exchange(true)) log_line("NGX: RR create refused: WrongGPU RR stays off in this process (see the line above)"); + return true; +} bool ngx_create_seh(void* u, void* dev, void* cl, const WgHostNgxParams* p, void** ctx) { - if (g_ngx_faulted.load()) return false; + if (g_ngx_faulted.load() || ngx_guard_refuses()) return false; __try { return ngx_create_cpp(u, dev, cl, p, ctx); } __except (EXCEPTION_EXECUTE_HANDLER) { @@ -1467,6 +1854,11 @@ void register_ngx_provider(const WgHostMenuApi* api, WgHostMenuPlugin* plugin) { } return; } + if (!g_guard.active()) { // RR guard: another RR plugin holds the game-interface path + log_line("NGX: RR provider not registered: WrongGPU RR stays off in this process (see the line above)"); + g_ngx_decided.store(true); + return; + } const wgrr::RrEnabled& enabled = rr_enabled(); if (!enabled.on) { log_line("NGX: RR provider not registered: rr_enabled=0 (" + enabled.source + "); games that call NGX directly " @@ -1515,8 +1907,8 @@ void register_ngx_provider(const WgHostMenuApi* api, WgHostMenuPlugin* plugin) { "): games that call NGX directly get WrongGPU RR" + (host_has ? "; the host restores the game's command-list state after each evaluate" : "; the host has no command-list restore (plugin interface 5)")); - } else { - log_line("NGX: the host refused the RR provider registration (another provider is registered?)"); + } else { // RR guard: the host keeps one NGX RR provider; another one holds it (NGX route only) + log_line(wgrr::guard::line_ngx_other()); } } #endif @@ -1525,7 +1917,14 @@ void register_ngx_provider(const WgHostMenuApi* api, WgHostMenuPlugin* plugin) { // OptiScaler's ASI entry (same convention WrongGPU.asi uses). All real work runs here, never under the loader lock. extern "C" __declspec(dllexport) void InitializeASI() { - std::call_once(g_init_once, [] { + // RR guard: the module that calls us is the host (it patches the interface's init export itself) + void* caller = _ReturnAddress(); + std::call_once(g_init_once, [caller] { + HMODULE host = nullptr; + if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + static_cast(caller), &host) && host != g_self) + g_host_module = host; + if (!guard_claim_marker()) return; // a second copy of WrongGPU RR: nothing of this copy starts (one line) #if !WG_RR_PROBE // RR runs while the core accepted an evaluate within the last second wgrr::panel::start( @@ -1548,6 +1947,17 @@ extern "C" __declspec(dllexport) void InitializeASI() { // OptiScaler's plugin interface (builds that have it call this right after InitializeASI): the WrongGPU tab, and for // games that load the game interface at run time, the host's game-interface routes (interface 3). extern "C" __declspec(dllexport) bool OptiPluginInit(const WgHostMenuApi* api, WgHostMenuPlugin* plugin) { + // RR guard: a second copy of WrongGPU RR registers nothing (no second tab, routes or provider) + if (g_guard.state() == wgrr::guard::State::kOwnCopy) return false; + if (!g_host_module && api) { // the host, when InitializeASI could not tell: the module holding its table + HMODULE host = nullptr; + if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + reinterpret_cast(api), &host) && host != g_self) + g_host_module = host; + } + // a plugin that took the RR calls after our InitializeASI (a non-freezing check; the game's first call decides last) + if (g_hook_done.load(std::memory_order_acquire)) + g_guard.check([] { return guard_late("OptiPluginInit", false); }); if (api && plugin) { // kept before the routes: the host may call back (and the core may start) at once g_host_api_plugin.store(plugin); g_host_api.store(api); @@ -1612,12 +2022,10 @@ void exit_summary() { "remove it for Ray Reconstruction\r\n"; } } - HANDLE h = CreateFileW(g_log_path, FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, - FILE_ATTRIBUTE_NORMAL, nullptr); - if (h == INVALID_HANDLE_VALUE) return; - DWORD n = 0; - WriteFile(h, line.data(), (DWORD)line.size(), &n, nullptr); - CloseHandle(h); + // 0.6.1: under the log's process-wide lock (a short bounded wait: this can run while the process unloads us), one + // append call either way (log_append.h) + const wgrr::LogLock shared(g_log_path, 500); + wgrr::append_log_text(g_log_path, line, OPEN_EXISTING); } } // namespace #endif diff --git a/clean/rr_f/proxy/src/log_append.h b/clean/rr_f/proxy/src/log_append.h new file mode 100644 index 00000000..4c369fc3 --- /dev/null +++ b/clean/rr_f/proxy/src/log_append.h @@ -0,0 +1,92 @@ +// SPDX-License-Identifier: MIT +// One log line, one append (RR guard, 0.6.1). Original code, written for this project. +// +// Two copies of WrongGPU RR in one process (an integrator's kit next to WrongGPU's own install: the case the +// coexistence guard is for) write the same wronggpu-rr.log. Lines used to be written through the C runtime's append +// mode (_wfopen "ab" + fprintf), which on Windows moves to the end and then writes on an ordinary write handle: when +// both copies moved to the same end, one write landed on top of the other and lines were torn (and the launcher's +// Last run no longer matched them). Each copy also had only its own in-module mutex. +// +// Now every write is ONE WriteFile of the whole text (timestamp, line, newline; a rotation notice in the same buffer) +// on a handle opened with FILE_APPEND_DATA alone, which the system appends at the end of the file as one piece. A +// process-wide named mutex, named after the log file's full path, puts the two copies' writes (and the size check and +// rotation) in one order; its wait is bounded, and when it fails the line is still written with the one append call. +#pragma once + +#include +#include +#include +#include + +#include + +namespace wgrr { + +constexpr DWORD kLogLockWaitMs = 2000; // bounded: a copy stuck holding the lock never stops this one + +// "Local\WrongGPU-RR-log-": the same name in every copy for the same file +inline std::wstring log_mutex_name(const std::wstring& path) { + wchar_t full[MAX_PATH * 2]; + const DWORD n = GetFullPathNameW(path.c_str(), (DWORD)(sizeof full / sizeof full[0]), full, nullptr); + std::wstring p = (n && n < sizeof full / sizeof full[0]) ? std::wstring(full, n) : path; + for (wchar_t& c : p) c = (wchar_t)towlower(c); // (no user32 in the plugin) + uint64_t h = 1469598103934665603ull; + for (wchar_t c : p) { + h ^= (uint16_t)c; + h *= 1099511628211ull; + } + wchar_t name[64]; + swprintf(name, sizeof name / sizeof name[0], L"Local\\WrongGPU-RR-log-%016llx", (unsigned long long)h); + return name; +} + +// Holds the log's process-wide mutex for one write; owned() is false when the wait failed (the caller writes anyway) +class LogLock { + public: + LogLock(const std::wstring& path, DWORD wait_ms) { + m_ = CreateMutexW(nullptr, FALSE, log_mutex_name(path).c_str()); + if (m_) { + const DWORD r = WaitForSingleObject(m_, wait_ms); + owned_ = r == WAIT_OBJECT_0 || r == WAIT_ABANDONED; // abandoned: the other copy's thread ended; the file is whole + } + } + ~LogLock() { + if (owned_) ReleaseMutex(m_); + if (m_) CloseHandle(m_); + } + bool owned() const { return owned_; } + LogLock(const LogLock&) = delete; + LogLock& operator=(const LogLock&) = delete; + + private: + HANDLE m_ = nullptr; + bool owned_ = false; +}; + +// The file's size now (0 when it is not there) +inline uint64_t log_file_size(const std::wstring& path) { + WIN32_FILE_ATTRIBUTE_DATA a; + return GetFileAttributesExW(path.c_str(), GetFileExInfoStandard, &a) ? ((uint64_t)a.nFileSizeHigh << 32) | a.nFileSizeLow : 0; +} + +// Appends `text` (whole lines with their newlines) in one WriteFile on a FILE_APPEND_DATA handle. False: not written. +inline bool append_log_text(const std::wstring& path, const std::string& text, DWORD disposition = OPEN_ALWAYS) { + HANDLE h = CreateFileW(path.c_str(), FILE_APPEND_DATA, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, + disposition, FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) return false; + DWORD n = 0; + const BOOL ok = WriteFile(h, text.data(), (DWORD)text.size(), &n, nullptr); + CloseHandle(h); + return ok && n == (DWORD)text.size(); +} + +// "HH:MM:SS.mmm " of now +inline std::string log_stamp() { + SYSTEMTIME t; + GetLocalTime(&t); + char ts[32]; + snprintf(ts, sizeof ts, "%02u:%02u:%02u.%03u ", t.wHour, t.wMinute, t.wSecond, t.wMilliseconds); + return ts; +} + +} // namespace wgrr diff --git a/clean/rr_f/proxy/src/proxy_dll.cpp b/clean/rr_f/proxy/src/proxy_dll.cpp index f0a0b992..4bf7751c 100644 --- a/clean/rr_f/proxy/src/proxy_dll.cpp +++ b/clean/rr_f/proxy/src/proxy_dll.cpp @@ -26,6 +26,7 @@ #include #include +#include "log_append.h" #include "proxy_core.h" #include "rr_enabled.h" #include "settings.h" @@ -59,7 +60,7 @@ std::mutex g_log_mutex; wgrr::RrProbe* g_probe = nullptr; wgrr::ProbeLog* g_probe_log = nullptr; std::once_flag g_probe_log_once; -FILE* g_probe_file = nullptr; +std::wstring g_probe_path; // wronggpu-rr-probe.log (0.6.1: one append call per line, log_append.h) #else wgrr::RrProxy* g_proxy = nullptr; #endif @@ -107,16 +108,19 @@ wgrr::ProbeLog* probe_log() { std::call_once(g_probe_log_once, [] { std::wstring path = own_dir() + L"wronggpu-rr-probe.log"; std::wstring prev = own_dir() + L"wronggpu-rr-probe.prev.log"; - MoveFileExW(path.c_str(), prev.c_str(), MOVEFILE_REPLACE_EXISTING); - g_probe_file = _wfopen(path.c_str(), L"wb"); + { + const wgrr::LogLock shared(path, wgrr::kLogLockWaitMs); + MoveFileExW(path.c_str(), prev.c_str(), MOVEFILE_REPLACE_EXISTING); + // a new, empty log (as the earlier "wb" open did, also when the old one could not be moved aside) + HANDLE fresh = CreateFileW(path.c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, + CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (fresh != INVALID_HANDLE_VALUE) CloseHandle(fresh); + } + g_probe_path = path; // 0.6.1: one append call per line under the log's process-wide lock (log_append.h) g_probe_log = new wgrr::ProbeLog([](const std::string& line) { std::lock_guard lock(g_log_mutex); - if (!g_probe_file) return; - SYSTEMTIME t; - GetLocalTime(&t); - fprintf(g_probe_file, "%02u:%02u:%02u.%03u %s\r\n", t.wHour, t.wMinute, t.wSecond, t.wMilliseconds, - line.c_str()); - fflush(g_probe_file); // a crash keeps everything logged so far + const wgrr::LogLock shared(g_probe_path, wgrr::kLogLockWaitMs); + wgrr::append_log_text(g_probe_path, wgrr::log_stamp() + line + "\r\n"); // on disk at once: a crash keeps it }); g_probe_log->note(std::string("probe start: build Streamline 2.") + std::to_string(WG_BINDING_API_MINOR) + ", loaded as " + narrow(own_stem()) + ", process " + std::to_string(GetCurrentProcessId())); @@ -131,12 +135,8 @@ void log_line(const std::string& s) { #else std::lock_guard lock(g_log_mutex); std::wstring path = own_dir() + L"wronggpu-rr.log"; - FILE* f = _wfopen(path.c_str(), L"ab"); - if (!f) return; - SYSTEMTIME t; - GetLocalTime(&t); - fprintf(f, "%02u:%02u:%02u.%03u %s\r\n", t.wHour, t.wMinute, t.wSecond, t.wMilliseconds, s.c_str()); - fclose(f); + const wgrr::LogLock shared(path, wgrr::kLogLockWaitMs); // 0.6.1: one append call under the process-wide lock + wgrr::append_log_text(path, wgrr::log_stamp() + s + "\r\n"); #endif } diff --git a/clean/rr_f/proxy/src/rr_guard.cpp b/clean/rr_f/proxy/src/rr_guard.cpp new file mode 100644 index 00000000..46832d80 --- /dev/null +++ b/clean/rr_f/proxy/src/rr_guard.cpp @@ -0,0 +1,335 @@ +// SPDX-License-Identifier: MIT +// RR guard: see rr_guard.h. +#define WIN32_LEAN_AND_MEAN +#include + +#include + +#include "rr_guard.h" + +namespace wgrr { +namespace guard { + +bool readable(const void* p, size_t n) { + if (!p || !n) return false; + uintptr_t a = reinterpret_cast(p); + const uintptr_t end = a + n; + if (end < a) return false; + while (a < end) { + MEMORY_BASIC_INFORMATION m; + if (!VirtualQuery(reinterpret_cast(a), &m, sizeof m)) return false; + if (m.State != MEM_COMMIT) return false; + const DWORD pr = m.Protect; + if (pr & (PAGE_GUARD | PAGE_NOACCESS)) return false; + if (!(pr & (PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | + PAGE_EXECUTE_WRITECOPY))) + return false; + const uintptr_t next = reinterpret_cast(m.BaseAddress) + m.RegionSize; + if (next <= a) return false; + a = next; + } + return true; +} + +namespace { +// No C++ objects in this frame (structured exception handling). +bool copy_guarded(const void* p, void* out, size_t n) { + __try { + const volatile uint8_t* s = static_cast(p); + uint8_t* d = static_cast(out); + for (size_t i = 0; i < n; ++i) d[i] = s[i]; + return true; + } __except (EXCEPTION_EXECUTE_HANDLER) { + return false; + } +} + +// Up to `want` code bytes from p, never past the readable region p lies in. *got: bytes read. +bool read_code(const void* p, uint8_t* buf, size_t want, size_t* got) { + *got = 0; + MEMORY_BASIC_INFORMATION m; + if (!p || !VirtualQuery(p, &m, sizeof m)) return false; + const uintptr_t end = reinterpret_cast(m.BaseAddress) + m.RegionSize; + const uintptr_t at = reinterpret_cast(p); + if (end <= at) return false; + const size_t n = (end - at) < want ? (size_t)(end - at) : want; + if (!safe_read(p, buf, n)) return false; + *got = n; + return true; +} + +int32_t rd32(const uint8_t* b) { + int32_t v; + memcpy(&v, b, 4); + return v; +} +} // namespace + +bool safe_read(const void* p, void* out, size_t n) { + if (!out || !readable(p, n)) return false; + return copy_guarded(p, out, n); +} + +bool Reader::read(const void* p, void* out, size_t n) { + const uintptr_t a = reinterpret_cast(p); + if (!p || !out || !n || a + n < a) return false; + if (a < lo_ || a + n > hi_) { + MEMORY_BASIC_INFORMATION m; + ++queries; + if (!VirtualQuery(p, &m, sizeof m)) return false; + const uintptr_t lo = reinterpret_cast(m.BaseAddress), hi = lo + m.RegionSize; + if (a + n > hi) return safe_read(p, out, n); // spans regions: the uncached check + if (!readable(p, n)) return false; + lo_ = lo; + hi_ = hi; + } + return copy_guarded(p, out, n); +} + +bool Reader::str(const void* p, char* out, size_t max) { + const char* s = static_cast(p); + for (size_t i = 0; i < max; ++i) { + if (!get(s + i, &out[i])) return false; + if (!out[i]) return true; + } + return false; +} + +bool decode_jump(const uint8_t* c, size_t n, const uint8_t* at, const void** target, const void** cell) { + if (cell) *cell = nullptr; + if (n >= 5 && c[0] == 0xE9) { // jmp rel32 + *target = at + 5 + rd32(c + 1); + return true; + } + if (n >= 2 && c[0] == 0xEB) { // jmp rel8 + *target = at + 2 + static_cast(c[1]); + return true; + } + const size_t r = (n >= 1 && c[0] == 0x48) ? 1 : 0; // REX.W jmp [rip+disp32] (same meaning) + if (n >= r + 6 && c[r] == 0xFF && c[r + 1] == 0x25) { // jmp [rip+disp32] + const uint8_t* slot = at + r + 6 + rd32(c + r + 2); + const void* t = nullptr; + if (!safe_get(slot, &t)) return false; + if (cell) *cell = slot; + *target = t; + return true; + } + if (n >= 12 && c[0] == 0x48 && c[1] == 0xB8 && ((c[10] == 0xFF && c[11] == 0xE0) || (c[10] == 0x50 && c[11] == 0xC3))) { + const void* t; // mov rax, imm64; jmp rax | push rax; ret + memcpy(&t, c + 2, sizeof t); + *target = t; + return true; + } + if (n >= 13 && c[0] == 0x49 && c[1] == 0xBB && c[10] == 0x41 && c[11] == 0xFF && c[12] == 0xE3) { + const void* t; // mov r11, imm64; jmp r11 + memcpy(&t, c + 2, sizeof t); + *target = t; + return true; + } + return false; +} + +const char* owner_word(Owner o) { + switch (o) { + case Owner::kUnknown: return "unknown (not readable)"; + case Owner::kSelf: return "WrongGPU RR (this copy)"; + case Owner::kInterface: return "the game interface"; + case Owner::kHost: return "the host"; + case Owner::kOwnCopy: return "another copy of WrongGPU RR"; + case Owner::kWrongGpu: return "another WrongGPU module"; + case Owner::kExeThunk: return "the exe's own code"; + case Owner::kAnonymous: return "code outside every module"; + case Owner::kForeign: return "another module"; + } + return "?"; +} + +Where classify(const void* p, const Env& env, bool follow_iface) { + Where w; + const void* cur = p; + for (;;) { + if (!cur || w.hops > kMaxHops) { + w.owner = Owner::kUnknown; + return w; + } + const void* m = env.module_of ? env.module_of(cur) : nullptr; + w.module = m && env.name_of ? env.name_of(m) : std::string(); + if (m && m == env.self) { w.owner = Owner::kSelf; return w; } + if (m && m == env.host) { w.owner = Owner::kHost; return w; } + if (m && m == env.iface) { + if (!follow_iface || w.hops != 0) { w.owner = Owner::kInterface; return w; } + uint8_t code[16]; + size_t got = 0; + if (!read_code(cur, code, sizeof code, &got)) { w.owner = Owner::kUnknown; return w; } + const void* target = nullptr; + const void* cell = nullptr; + if (!decode_jump(code, got, static_cast(cur), &target, &cell)) { + // a jmp [rip+disp32] whose cell could not be read decodes as "no jump": check that case explicitly + const size_t r = (got >= 1 && code[0] == 0x48) ? 1 : 0; + if (got >= r + 6 && code[r] == 0xFF && code[r + 1] == 0x25) { w.owner = Owner::kUnknown; return w; } + w.owner = Owner::kInterface; + return w; + } + const uint8_t* c8 = static_cast(cell); + if (c8 && c8 >= env.iface_iat_begin && c8 < env.iface_iat_end) { w.owner = Owner::kInterface; return w; } + if (env.module_of && env.module_of(target) == env.iface) { w.owner = Owner::kInterface; return w; } + cur = target; + ++w.hops; + continue; + } + if (m) { + if (env.exports && env.exports(m, kOwnRrExport)) w.owner = Owner::kOwnCopy; + else if (env.exports && env.exports(m, kWrongGpuAsiExport)) w.owner = Owner::kWrongGpu; + else if (m == env.exe) w.owner = Owner::kExeThunk; + else w.owner = Owner::kForeign; + return w; + } + // outside every module: a trampoline / relay; follow its jump, if any + uint8_t code[16]; + size_t got = 0; + if (!read_code(cur, code, sizeof code, &got)) { w.owner = Owner::kUnknown; return w; } + const void* target = nullptr; + if (!decode_jump(code, got, static_cast(cur), &target, nullptr)) { + const size_t r = (got >= 1 && code[0] == 0x48) ? 1 : 0; + w.owner = (got >= r + 6 && code[r] == 0xFF && code[r + 1] == 0x25) ? Owner::kUnknown : Owner::kAnonymous; + return w; + } + cur = target; + ++w.hops; + } +} + +bool trusted(Owner o, bool anon_ok, bool exe_ok) { + switch (o) { + case Owner::kSelf: case Owner::kInterface: case Owner::kHost: case Owner::kWrongGpu: return true; + case Owner::kAnonymous: return anon_ok; + case Owner::kExeThunk: return exe_ok; + default: return false; + } +} + +void Verdict::add(const Where& w, const std::string& what, bool anon_ok, bool exe_ok) { + ++reads; + if (kind == kOwnCopy) return; + const std::string via = w.hops ? " (through " + std::to_string(w.hops) + " hook jump" + (w.hops > 1 ? "s" : "") + ")" + : std::string(); + if (w.owner == Owner::kOwnCopy) { + kind = kOwnCopy; + detail = w.module; + return; + } + if (kind == kOther || trusted(w.owner, anon_ok, exe_ok)) return; + kind = kOther; + if (w.owner == Owner::kUnknown) detail = what + " could not be read" + via; + else if (w.owner == Owner::kAnonymous) detail = what + " leads to code outside every module" + via; + else detail = what + " leads to " + (w.module.empty() ? std::string("another module") : w.module) + via; +} + +bool override_take(const std::string& value, std::string* note) { + std::string v; + for (char c : value) + if (c != ' ' && c != '\t' && c != '\r' && c != '\n') v.push_back((char)(c >= 'A' && c <= 'Z' ? c - 'A' + 'a' : c)); + if (note) note->clear(); + if (v == "take") return true; + if (!v.empty() && v != "off" && note) + *note = std::string(kOverrideKey) + "=" + value + " in wronggpu-rr.ini not recognised (off | take); off is used"; + return false; +} + +// The lines start with the words the launcher's Last run page matches (no "hook: " prefix): kStem, kOwnCopyStem, +// kLaterStem. HOOK-MODE.md documents them; changing a beginning breaks that page. +static const char kStem[] = "another Ray Reconstruction plugin is active; WrongGPU RR stays off ("; +static const char kOwnCopyStem[] = "a second copy of WrongGPU RR is loaded ("; +static const char kLaterStem[] = "a plugin loaded after WrongGPU replaced its hooks; "; + +std::string line_other(const std::string& d, bool passing) { + return std::string(kStem) + d + + (passing ? "; WrongGPU's handlers pass every call on unchanged; " : "; nothing patched; ") + kOverrideKey + + "=take in wronggpu-rr.ini uses WrongGPU's instead)"; +} +std::string line_other_later(const std::string& d) { + return std::string(kStem) + d + + "; it loaded after WrongGPU: WrongGPU passes every call on unchanged; to use WrongGPU RR, move it aside)"; +} +std::string line_take(const std::string& d) { + return std::string("another Ray Reconstruction plugin is active; ") + kOverrideKey + + "=take: WrongGPU RR goes in front of it (" + d + "; it gets the game's other calls, no RR work)"; +} +std::string line_cannot_take(const std::string& d) { + return std::string(kLaterStem) + kOverrideKey + + "=take cannot be applied: WrongGPU RR stays off and passes every call on unchanged (" + d + + "); move it aside to use WrongGPU RR"; +} +std::string line_own_copy(const std::string& active, const std::string& self) { + return std::string(kOwnCopyStem) + active + " is active); this copy (" + self + ") stays off"; +} +std::string line_ngx_other() { + return std::string(kStem) + + "NGX route only: the host refused WrongGPU's RR provider, another provider holds it; the game-interface " + "route is decided on its own)"; +} + +void Decision::freeze_once(const std::function& decide) { + if (frozen()) return; + std::call_once(once_, [&] { + std::lock_guard lock(mu_); + set(decide()); + frozen_.store(true, std::memory_order_release); + }); +} + +void Decision::check(const std::function& decide) { + std::lock_guard lock(mu_); + if (frozen()) return; + set(decide()); +} + +// ---------------------------------------------------------------- the real process +namespace { +std::string leaf_utf8(const void* m) { + wchar_t buf[MAX_PATH * 2]; + const DWORD n = GetModuleFileNameW(static_cast(const_cast(m)), buf, MAX_PATH * 2); + std::wstring p(buf, n); + const size_t slash = p.find_last_of(L"\\/"); + if (slash != std::wstring::npos) p = p.substr(slash + 1); + const int k = WideCharToMultiByte(CP_UTF8, 0, p.c_str(), (int)p.size(), nullptr, 0, nullptr, nullptr); + std::string s(k > 0 ? k : 0, '\0'); + if (k > 0) WideCharToMultiByte(CP_UTF8, 0, p.c_str(), (int)p.size(), &s[0], k, nullptr, nullptr); + return s; +} +} // namespace + +Env process_env(const void* self, const void* iface, const void* host) { + Env e; + e.self = self; + e.iface = iface; + e.host = host; + e.exe = GetModuleHandleW(nullptr); + e.module_of = [](const void* a) -> const void* { + HMODULE m = nullptr; + if (!a || !GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + static_cast(a), &m)) + return nullptr; + return m; + }; + e.exports = [](const void* m, const char* name) { + return GetProcAddress(static_cast(const_cast(m)), name) != nullptr; + }; + e.name_of = leaf_utf8; + // the interface's own import address table (IMAGE_DIRECTORY_ENTRY_IAT), read through safe reads + const uint8_t* base = static_cast(iface); + IMAGE_DOS_HEADER dos; + IMAGE_NT_HEADERS64 nt; + if (base && safe_get(base, &dos) && dos.e_magic == IMAGE_DOS_SIGNATURE && safe_get(base + dos.e_lfanew, &nt) && + nt.Signature == IMAGE_NT_SIGNATURE) { + const IMAGE_DATA_DIRECTORY& d = nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IAT]; + if (d.VirtualAddress && d.Size) { + e.iface_iat_begin = base + d.VirtualAddress; + e.iface_iat_end = base + d.VirtualAddress + d.Size; + } + } + return e; +} + +} // namespace guard +} // namespace wgrr diff --git a/clean/rr_f/proxy/src/rr_guard.h b/clean/rr_f/proxy/src/rr_guard.h new file mode 100644 index 00000000..dbe18af5 --- /dev/null +++ b/clean/rr_f/proxy/src/rr_guard.h @@ -0,0 +1,158 @@ +// SPDX-License-Identifier: MIT +// RR guard: the coexistence guard of the hook-mode RR plugin (HOOK-MODE.md, "Another Ray Reconstruction +// plugin"). When another Ray Reconstruction plugin already holds the game's RR path in this process, WrongGPU RR stays +// off and logs one line; Model M is not touched. Generic and read-only: it looks at where the game's RR calls lead +// (import slots, the first bytes of the interface's RR exports, the host's continuation pointers), never at another +// plugin's files or internals. +// +// This header holds the parts without process state, so the CPU tests can drive them with synthetic memory: +// - safe_read: every read of memory we do not own (VirtualQuery for committed, readable, non-guard pages, then a +// structured-exception-guarded copy); a failed read is "unknown", never a fault; +// - decode_jump: the jump forms a hook puts at the start of a function (jmp rel32 / rel8, jmp [rip+disp32], +// mov rax|r11, imm64 + jmp reg); +// - classify: who an address belongs to (our module, the game interface, the host, another copy of WrongGPU RR, +// another WrongGPU module, the exe's own delay-load thunk, code outside every module, another module), following +// hook jumps out of the interface and out of anonymous memory, up to kMaxHops; +// - Verdict: the worst of several classifications, and the words for the log; +// - Decision: the once-only late decision (several game threads may make the first call at the same time). +#pragma once +#include +#include + +#include +#include +#include +#include + +namespace wgrr { +namespace guard { + +// The export a module must have to count as a copy of WrongGPU RR (the 60.9 settings contract), and the one of the +// other WrongGPU plugin (WrongGPU.asi, Model M's menu plugin). Documented in HOOK-MODE.md (the launcher matches them). +constexpr const char* kOwnRrExport = "WrongGPU_GetSettingsContract"; +constexpr const char* kWrongGpuAsiExport = "WrongGpuAsiQuery"; +// wronggpu-rr.ini: rr_other_plugin = off (default) | take +constexpr const char* kOverrideKey = "rr_other_plugin"; +constexpr int kMaxHops = 4; + +// True when [p, p + n) lies in committed pages that are readable and not guard pages (VirtualQuery only). +bool readable(const void* p, size_t n); +// Copies n bytes from p to out when readable() and the copy raises no structured exception. False: unknown. +bool safe_read(const void* p, void* out, size_t n); +template +bool safe_get(const void* p, T* out) { + return safe_read(p, out, sizeof(T)); +} + +// safe_read for walking a module's headers and tables: the last region VirtualQuery found readable is remembered, so +// reads inside it only take the structured-exception-guarded copy (the scan stays far below a millisecond). +class Reader { + public: + bool read(const void* p, void* out, size_t n); + template + bool get(const void* p, T* out) { + return read(p, out, sizeof(T)); + } + // A NUL-terminated string of at most max - 1 characters (false: unreadable or longer). + bool str(const void* p, char* out, size_t max); + unsigned queries = 0; // VirtualQuery calls made (the test checks the cache) + + private: + uintptr_t lo_ = 0, hi_ = 0; +}; + +// A hook jump at `at` (code holds the first bytes read from there, n of them). On success *target is where it goes; +// for jmp [rip+disp32] *cell is the pointer cell (read with safe_read; a failed read makes the decode fail). +bool decode_jump(const uint8_t* code, size_t n, const uint8_t* at, const void** target, const void** cell); + +enum class Owner { + kUnknown, // the memory could not be read (or a null pointer): the safe side is "another plugin" + kSelf, // this WrongGPU RR module + kInterface, // the game interface module (its own code) + kHost, // the host that loaded us (it patches the interface's init export itself) + kOwnCopy, // another loaded copy of WrongGPU RR (exports kOwnRrExport) + kWrongGpu, // another WrongGPU module (exports kWrongGpuAsiExport) + kExeThunk, // the exe's own code (a delay-load slot not bound yet holds the delay helper's thunk there) + kAnonymous, // readable code outside every module that does not jump on (a trampoline) + kForeign, // another module: another plugin +}; +const char* owner_word(Owner o); + +// The process as the classification sees it. The lookups are injectable (the unit test uses synthetic modules). +struct Env { + const void* self = nullptr; + const void* iface = nullptr; + const void* host = nullptr; + const void* exe = nullptr; + // the interface's import address table (its own imports): a jmp [rip+disp32] through a cell in it is the linker's + // import thunk, not a hook + const uint8_t* iface_iat_begin = nullptr; + const uint8_t* iface_iat_end = nullptr; + std::function module_of; // the module holding addr, or null + std::function exports; // the module exports `name` + std::function name_of; // the module's file name (for the log) +}; +// The real process: GetModuleHandleExW (from address, refcount unchanged), GetProcAddress, GetModuleFileNameW. +Env process_env(const void* self, const void* iface, const void* host); + +struct Where { + Owner owner = Owner::kUnknown; + std::string module; // file name of the module the address ends in ("" when none) + int hops = 0; // hook jumps followed +}; +// Where code at `p` leads. follow_iface: follow a hook jump at p when p is inside the interface (the first bytes of +// an export); a jump that stays inside the interface, or goes through the interface's own import table, is the +// interface's own code. Jumps are always followed out of anonymous memory. +Where classify(const void* p, const Env& env, bool follow_iface); + +// What a scan found: the first not-trusted address decides (a copy of WrongGPU RR before anything else). +struct Verdict { + enum Kind { kClean, kOwnCopy, kOther } kind = kClean; + std::string detail; // e.g. "the import slot slEvaluateFeature of Game.exe leads to other.asi" + unsigned reads = 0; // addresses looked at + // Takes one classification. `what` names the place ("the import slot X of Y"); anon_ok: code outside every + // module is accepted here (the host's own trampolines); exe_ok: the exe's own code is accepted (delay thunks). + void add(const Where& w, const std::string& what, bool anon_ok, bool exe_ok); +}; +bool trusted(Owner o, bool anon_ok, bool exe_ok); + +// rr_other_plugin from wronggpu-rr.ini: false = off (the default, also for an unknown value; *note says so). +bool override_take(const std::string& value, std::string* note); + +// The log lines (stable; HOOK-MODE.md documents them, the launcher's Last run page matches them). +// stays off at load (passing: WrongGPU's handlers were already installed by the host and pass every call on) +std::string line_other(const std::string& detail, bool passing = false); +std::string line_other_later(const std::string& detail); // stays off, found at the late check (pass-through) +std::string line_take(const std::string& detail); // rr_other_plugin=take: WrongGPU RR in front +std::string line_cannot_take(const std::string& detail); // take asked, the other plugin loaded later +std::string line_own_copy(const std::string& active, const std::string& self); +std::string line_ngx_other(); // the host refused our NGX provider + +// The guard's state for the whole process run. Active until a scan says otherwise; the late decision is taken once. +enum class State : int { kActive = 0, kOff = 1, kOwnCopy = 2, kPassThrough = 3, kTaken = 4 }; + +class Decision { + public: + State state() const { return static_cast(state_.load(std::memory_order_acquire)); } + // The calls go to WrongGPU RR's core (not off, not passing through). + bool active() const { + const State s = state(); + return s == State::kActive || s == State::kTaken; + } + void set(State s) { state_.store(static_cast(s), std::memory_order_release); } + bool frozen() const { return frozen_.load(std::memory_order_acquire); } + // Runs `decide` exactly once (the first caller; concurrent callers wait until it returned), then freezes. Later + // calls return at once. `decide` returns the state to keep. + void freeze_once(const std::function& decide); + // A non-freezing check (OptiPluginInit): runs `decide` under the same lock unless already frozen. + void check(const std::function& decide); + + private: + std::atomic state_{0}; + std::atomic frozen_{false}; + std::once_flag once_; + std::mutex mu_; +}; + +} // namespace guard +} // namespace wgrr diff --git a/clean/rr_f/proxy/tests/fake_other_rr.cpp b/clean/rr_f/proxy/tests/fake_other_rr.cpp new file mode 100644 index 00000000..3e6d8456 --- /dev/null +++ b/clean/rr_f/proxy/tests/fake_other_rr.cpp @@ -0,0 +1,201 @@ +// SPDX-License-Identifier: MIT +// RR guard: a stand-in "other Ray Reconstruction plugin" of our own (wgtest_other_rr.dll) for +// tests/test_rr_guard_dll.cpp. It knows nothing of any real plugin; it only takes the game interface's RR calls the +// generic ways a plugin can, so that WrongGPU RR's guard has something to find: +// wgtest_or_patch_iat redirects the exe's import slots of the hooked roles to its handlers (forward = 1: each +// handler continues with what the slot held, i.e. it wraps whatever was there; 0: it continues +// with the interface's export and replaces what was there) +// wgtest_or_patch_export overwrites the first bytes of an interface export with a jump to its handler (relay = 1: +// a jmp rel32 to an anonymous relay near the export that jumps on, as hooking libraries do) +// wgtest_or_set_slot writes any value into one import slot (code outside every module, an unreadable page) +// wgtest_or_routes registers its handlers as game-interface routes with the host (plugin interface 3) +// wgtest_or_register_ngx registers an NGX RR provider with the host (plugin interface 4) +// Its handlers answer the RR feature themselves (is-supported 0, evaluate / allocate / get-function counted and 0) and +// pass every other call on. The role names and order come from the hook binding (wg_binding.inc). +#define WIN32_LEAN_AND_MEAN +#include + +#include +#include + +#include "wg_binding.inc" +#include "../include/rr_proxy_abi.h" +#include "../include/wg_host_menu_abi.h" + +namespace { + +using Fwd = uint64_t (*)(uint64_t, uint64_t, uint64_t, uint64_t, uint64_t, uint64_t); + +struct OrState { + long calls[32]; // calls that reached each handler, by role + long rr_calls; // RR-feature calls the stand-in answered itself + long ngx_creates; // NGX provider creates +}; +OrState g_st; +Fwd g_next[32]; // where each handler continues +bool g_inline[32]; // the export of this role was overwritten (no way back to it): non-RR calls are answered here + +// the feature argument of a role, if it has one +bool feature_of(int role, uint64_t a, uint64_t b, uint32_t* f) { + switch (role) { + case 2: case 3: case 4: case 5: case 6: case 7: case 9: case 16: *f = (uint32_t)a; return true; + case 8: *f = (uint32_t)b; return true; // allocate(cmd_list, feature, viewport) + default: return false; + } +} + +template +uint64_t handler(uint64_t a, uint64_t b, uint64_t c, uint64_t d, uint64_t e, uint64_t f) { + InterlockedIncrement(&g_st.calls[R]); + uint32_t feat = 0; + if (feature_of(R, a, b, &feat) && feat == WG_FEAT_RAY_RECONSTRUCTION && (R == 2 || R == 7 || R == 8 || R == 16)) { + InterlockedIncrement(&g_st.rr_calls); + if (R == 7 && c) *reinterpret_cast(c) = reinterpret_cast(&handler); // "its" feature function + return 0; + } + if (g_inline[R]) return feature_of(R, a, b, &feat) ? 100u + feat % 50u : 0; // what the stand-in interface returns + return g_next[R] ? g_next[R](a, b, c, d, e, f) : (uint64_t)WG_E_MISSING_OR_INVALID_API; +} + +void* const kHandlers[19] = { + (void*)&handler<0>, (void*)&handler<1>, (void*)&handler<2>, (void*)&handler<3>, (void*)&handler<4>, + (void*)&handler<5>, (void*)&handler<6>, (void*)&handler<7>, (void*)&handler<8>, (void*)&handler<9>, + (void*)&handler<10>, (void*)&handler<11>, (void*)&handler<12>, (void*)&handler<13>, (void*)&handler<14>, + (void*)&handler<15>, (void*)&handler<16>, (void*)&handler<17>, (void*)&handler<18>}; + +int role_of(const char* name) { + for (unsigned i = 0; i < WG_BINDING_HOOK_ROLE_COUNT; ++i) { + const int r = kWgHookRoles[i]; + if (kWgRoleNames[r][0] && strcmp(kWgRoleNames[r], name) == 0) return r; + } + return -1; +} + +bool write_ptr(void** slot, void* value) { + DWORD old = 0; + if (!VirtualProtect(slot, sizeof(void*), PAGE_READWRITE, &old)) return false; + InterlockedExchangePointer(slot, value); + VirtualProtect(slot, sizeof(void*), old, &old); + return true; +} + +// f(role or -1, name, slot) for every by-name import of `leaf` in `module` +template +void each_import(HMODULE module, const char* leaf, F f) { + uint8_t* base = reinterpret_cast(module); + const IMAGE_NT_HEADERS64* nt = + reinterpret_cast(base + reinterpret_cast(base)->e_lfanew); + const IMAGE_DATA_DIRECTORY& d = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; + if (!d.VirtualAddress) return; + for (auto* imp = reinterpret_cast(base + d.VirtualAddress); imp->Name; ++imp) { + if (_stricmp(reinterpret_cast(base + imp->Name), leaf) != 0) continue; + auto* names = reinterpret_cast(base + (imp->OriginalFirstThunk ? imp->OriginalFirstThunk + : imp->FirstThunk)); + auto* iat = reinterpret_cast(base + imp->FirstThunk); + for (; names->u1.AddressOfData; ++names, ++iat) { + if (names->u1.Ordinal & IMAGE_ORDINAL_FLAG64) continue; + const char* nm = reinterpret_cast( + reinterpret_cast(base + names->u1.AddressOfData)->Name); + f(role_of(nm), nm, reinterpret_cast(&iat->u1.Function)); + } + } +} + +// a page within +-1.5 GB of `close_to` (for a jmp rel32), searched downward then upward +uint8_t* alloc_near(const void* close_to) { + const uintptr_t p = reinterpret_cast(close_to) & ~(uintptr_t)0xFFFF; + for (uintptr_t d = 0x10000; d < 0x60000000; d += 0x10000) { + for (int s = 0; s < 2; ++s) { + const uintptr_t a = s ? p + d : p - d; + void* m = VirtualAlloc(reinterpret_cast(a), 4096, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE); + if (m) return static_cast(m); + } + } + return nullptr; +} + +void put_abs(uint8_t* at, const void* target) { // jmp [rip+0]; dq target + at[0] = 0xFF; + at[1] = 0x25; + memset(at + 2, 0, 4); + memcpy(at + 6, &target, 8); +} + +// host routes: the host's next pointers of the routes this stand-in registered +void* g_route_next[32]; + +bool ngx_create(void*, void*, void*, const WgHostNgxParams*, void** ctx) { + InterlockedIncrement(&g_st.ngx_creates); + *ctx = &g_st; + return true; +} +bool ngx_evaluate(void*, void*, void*, const WgHostNgxParams*) { return true; } +void ngx_release(void*, void*) {} + +} // namespace + +extern "C" { + +__declspec(dllexport) const OrState* wgtest_or_state(void) { return &g_st; } + +__declspec(dllexport) int wgtest_or_patch_iat(HMODULE exe, const char* iface_leaf, int forward) { + HMODULE iface = GetModuleHandleA(iface_leaf); + int n = 0; + each_import(exe, iface_leaf, [&](int role, const char* nm, void** slot) { + if (role < 0) return; + g_next[role] = forward ? reinterpret_cast(*slot) : reinterpret_cast(GetProcAddress(iface, nm)); + if (write_ptr(slot, kHandlers[role])) ++n; + }); + return n; +} + +__declspec(dllexport) int wgtest_or_set_slot(HMODULE exe, const char* iface_leaf, const char* import_name, void* value) { + int n = 0; + each_import(exe, iface_leaf, [&](int, const char* nm, void** slot) { + if (strcmp(nm, import_name) == 0 && write_ptr(slot, value)) ++n; + }); + return n; +} + +__declspec(dllexport) int wgtest_or_patch_export(HMODULE iface, const char* name, int relay) { + const int role = role_of(name); + uint8_t* e = reinterpret_cast(GetProcAddress(iface, name)); + if (role < 0 || !e) return 0; + DWORD old = 0; + if (!VirtualProtect(e, 16, PAGE_EXECUTE_READWRITE, &old)) return 0; + g_inline[role] = true; + if (relay) { + uint8_t* r = alloc_near(e); + if (!r) return 0; + put_abs(r, kHandlers[role]); + e[0] = 0xE9; + const int32_t rel = (int32_t)(r - (e + 5)); + memcpy(e + 1, &rel, 4); + } else { + put_abs(e, kHandlers[role]); + } + VirtualProtect(e, 16, old, &old); + FlushInstructionCache(GetCurrentProcess(), e, 16); + return 1; +} + +__declspec(dllexport) int wgtest_or_routes(const WgHostMenuApi* api, WgHostMenuPlugin* plugin) { + WgHostSlRoute routes[4]; + const int roles[4] = {2, 7, 8, 16}; + for (int i = 0; i < 4; ++i) routes[i] = {kWgRoleNames[roles[i]], kHandlers[roles[i]], &g_route_next[roles[i]]}; + if (!api->register_streamline_routes(plugin, routes, 4)) return 0; + for (int i = 0; i < 4; ++i) g_next[roles[i]] = reinterpret_cast(g_route_next[roles[i]]); + return 4; +} + +__declspec(dllexport) bool wgtest_or_register_ngx(const WgHostMenuApi* api, WgHostMenuPlugin* plugin) { + static WgHostNgxRr p; + p.size = sizeof p; + p.user = &g_st; + p.create = ngx_create; + p.evaluate = ngx_evaluate; + p.release = ngx_release; + return api->register_ngx_rr(plugin, &p); +} + +} // extern "C" diff --git a/clean/rr_f/proxy/tests/guard_inject.cpp b/clean/rr_f/proxy/tests/guard_inject.cpp new file mode 100644 index 00000000..ea5816b1 --- /dev/null +++ b/clean/rr_f/proxy/tests/guard_inject.cpp @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: MIT +// RR guard: runs a test program with the guard scene (tests/guard_scene.cpp) loaded before its main +// (tools/guard_modelm.py). The program is started suspended, the scene DLL is loaded into it by a remote thread +// (LoadLibraryW), the scene's own thread sets the scene up and signals; then the program's main thread is resumed and +// runs unchanged. Exit code: the program's, or 90 when the scene failed (its result is printed), 91 on a start failure. +// guard_inject.exe [args...] (the working directory is inherited) +#define WIN32_LEAN_AND_MEAN +#include + +#include + +#include + +static std::wstring quote(const std::wstring& a) { + if (!a.empty() && a.find_first_of(L" \t\"") == std::wstring::npos) return a; + std::wstring q = L"\""; + for (wchar_t c : a) { + if (c == L'"') q += L'\\'; + q += c; + } + return q + L"\""; +} + +int wmain(int argc, wchar_t** argv) { + if (argc < 5) return 91; + const std::wstring scene = argv[1], stage = argv[2], mode = argv[3]; + std::wstring cmd; + for (int i = 4; i < argc; ++i) cmd += (cmd.empty() ? L"" : L" ") + quote(argv[i]); + const DWORD me = GetCurrentProcessId(); + const std::wstring event_name = L"Local\\wgtest-guard-scene-" + std::to_wstring(me); + const std::wstring result = stage + L"\\scene-result-" + std::to_wstring(me) + L".txt"; + DeleteFileW(result.c_str()); + HANDLE ev = CreateEventW(nullptr, TRUE, FALSE, event_name.c_str()); + SetEnvironmentVariableW(L"WGTEST_GUARD_STAGE", stage.c_str()); + SetEnvironmentVariableW(L"WGTEST_GUARD_MODE", mode.c_str()); + SetEnvironmentVariableW(L"WGTEST_GUARD_EVENT", event_name.c_str()); + SetEnvironmentVariableW(L"WGTEST_GUARD_RESULT", result.c_str()); + STARTUPINFOW si = {sizeof si}; + PROCESS_INFORMATION pi = {}; + if (!ev || !CreateProcessW(nullptr, &cmd[0], nullptr, nullptr, TRUE, CREATE_SUSPENDED, nullptr, nullptr, &si, &pi)) { + fprintf(stderr, "guard_inject: cannot start the program (error %lu)\n", GetLastError()); + return 91; + } + const size_t bytes = (scene.size() + 1) * sizeof(wchar_t); + void* remote = VirtualAllocEx(pi.hProcess, nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + SIZE_T written = 0; + auto load = reinterpret_cast( + reinterpret_cast(GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "LoadLibraryW"))); + HANDLE t = nullptr; + if (remote && WriteProcessMemory(pi.hProcess, remote, scene.c_str(), bytes, &written) && written == bytes) + t = CreateRemoteThread(pi.hProcess, nullptr, 0, load, remote, 0, nullptr); + DWORD loaded = 0; + const bool ok_thread = t && WaitForSingleObject(t, 30000) == WAIT_OBJECT_0 && GetExitCodeThread(t, &loaded) && loaded; + const bool ok_scene = ok_thread && WaitForSingleObject(ev, 30000) == WAIT_OBJECT_0; + if (t) CloseHandle(t); + std::string r; + if (FILE* f = _wfopen(result.c_str(), L"rb")) { + char b[1024] = {}; + fread(b, 1, sizeof b - 1, f); + fclose(f); + r = b; + } + DeleteFileW(result.c_str()); + if (!ok_scene || r.compare(0, 2, "ok") != 0) { + fprintf(stderr, "guard_inject: scene failed (%s): %s\n", ok_thread ? "scene" : "load", r.c_str()); + TerminateProcess(pi.hProcess, 90); + WaitForSingleObject(pi.hProcess, 10000); + return 90; + } + printf("guard_inject: %s\n", r.c_str()); + fflush(stdout); + ResumeThread(pi.hThread); + WaitForSingleObject(pi.hProcess, INFINITE); + DWORD code = 91; + GetExitCodeProcess(pi.hProcess, &code); + CloseHandle(pi.hThread); + CloseHandle(pi.hProcess); + CloseHandle(ev); + return (int)code; +} diff --git a/clean/rr_f/proxy/tests/guard_scene.cpp b/clean/rr_f/proxy/tests/guard_scene.cpp new file mode 100644 index 00000000..aa293d8f --- /dev/null +++ b/clean/rr_f/proxy/tests/guard_scene.cpp @@ -0,0 +1,137 @@ +// SPDX-License-Identifier: MIT +// RR guard: the scene DLL of the Model M check (tools/guard_modelm.py, tests/guard_inject.cpp). Loaded into a +// suspended Model M test process before its main runs, it loads WrongGPU RR (the hook plugin) next to our stand-in game +// interface and, per WGTEST_GUARD_MODE, trips the guard: +// none no other plugin (control: WrongGPU RR as it is without the guard tripping) +// off our stand-in other plugin patched the interface's evaluate export first: WrongGPU RR stays off +// take the same with rr_other_plugin=take (the injector writes wronggpu-rr.ini next to the test exe) +// owncopy two copies of WrongGPU RR: the second stays off +// passthrough the stand-in patches the export after InitializeASI; OptiPluginInit finds it: WrongGPU RR passes on +// It checks that WrongGPU RR logged its line (wronggpu-rr.log next to the test exe, the part written by this process), +// writes "ok"/"fail " to WGTEST_GUARD_RESULT and signals WGTEST_GUARD_EVENT; the injector then resumes the test. +// Files come from WGTEST_GUARD_STAGE (the stand-in interface, wgtest_other_rr.dll, the plugin and its copy). +#define WIN32_LEAN_AND_MEAN +#include + +#include +#include + +#include + +#include "wg_binding.inc" +#include "../include/wg_host_menu_abi.h" + +namespace { + +std::wstring env(const wchar_t* name) { + wchar_t buf[2048]; + const DWORD n = GetEnvironmentVariableW(name, buf, 2048); + return n && n < 2048 ? std::wstring(buf, n) : std::wstring(); +} + +std::string read_from(const std::wstring& path, long long from) { + std::string s; + FILE* f = _wfopen(path.c_str(), L"rb"); + if (!f) return s; + _fseeki64(f, from, SEEK_SET); + char b[4096]; + size_t n; + while ((n = fread(b, 1, sizeof b, f)) > 0) s.append(b, n); + fclose(f); + return s; +} + +long long size_of(const std::wstring& path) { + WIN32_FILE_ATTRIBUTE_DATA a; + return GetFileAttributesExW(path.c_str(), GetFileExInfoStandard, &a) ? ((long long)a.nFileSizeHigh << 32) | a.nFileSizeLow + : 0; +} + +size_t occurrences(const std::string& hay, const std::string& needle) { + size_t n = 0; + for (size_t at = hay.find(needle); at != std::string::npos; at = hay.find(needle, at + 1)) ++n; + return n; +} + +std::string run_scene() { + const std::wstring stage = env(L"WGTEST_GUARD_STAGE"); + const std::wstring mode_w = env(L"WGTEST_GUARD_MODE"); + const std::string mode(mode_w.begin(), mode_w.end()); + wchar_t exe[MAX_PATH]; + const DWORD en = GetModuleFileNameW(nullptr, exe, MAX_PATH); + std::wstring dir(exe, en); + dir = dir.substr(0, dir.find_last_of(L"\\/") + 1); + const std::wstring log = dir + L"wronggpu-rr.log"; + const long long from = size_of(log); + + HMODULE iface = LoadLibraryW((stage + L"\\" + std::wstring(kWgInterposerFile, kWgInterposerFile + strlen(kWgInterposerFile))).c_str()); + HMODULE other = LoadLibraryW((stage + L"\\wgtest_other_rr.dll").c_str()); + if (!iface || !other) return "fail: stand-ins not loaded"; + auto patch_export = reinterpret_cast(GetProcAddress(other, "wgtest_or_patch_export")); + const char* evaluate = kWgRoleNames[16]; + if ((mode == "off" || mode == "take") && patch_export(iface, evaluate, 0) != 1) return "fail: export not patched"; + const std::wstring hook(kWgHookFile, kWgHookFile + strlen(kWgHookFile)); + HMODULE asi = LoadLibraryW((stage + L"\\" + hook).c_str()); + if (!asi) return "fail: plugin not loaded"; + auto init = reinterpret_cast(GetProcAddress(asi, "InitializeASI")); + auto plugin_init = reinterpret_cast(GetProcAddress(asi, WG_HOST_MENU_INIT_EXPORT)); + if (!init || !plugin_init) return "fail: plugin entries missing"; + init(); + if (mode == "owncopy") { + HMODULE copy = LoadLibraryW((stage + L"\\WrongGPU-RR-copy.asi").c_str()); + auto init2 = copy ? reinterpret_cast(GetProcAddress(copy, "InitializeASI")) : nullptr; + if (!init2) return "fail: copy not loaded"; + init2(); + } + if (mode == "passthrough" && patch_export(iface, evaluate, 0) != 1) return "fail: export not patched"; + static WgHostMenuApi api = {}; // a host table without menu, routes or NGX provider + api.size = sizeof api; + api.version = 5; + plugin_init(&api, reinterpret_cast(0x1000)); + + const std::string got = read_from(log, from); + const std::string stem = "another Ray Reconstruction plugin is active; WrongGPU RR stays off ("; + struct Want { const char* text; size_t n; }; + Want want[3] = {}; + if (mode == "none") want[0] = {"hook: coexistence check at load: no other Ray Reconstruction plugin found (", 1}; + if (mode == "off") want[0] = {"; nothing patched; rr_other_plugin=take in wronggpu-rr.ini uses WrongGPU's instead)", 1}; + if (mode == "take") want[0] = {"another Ray Reconstruction plugin is active; rr_other_plugin=take: WrongGPU RR goes in front of it (", 1}; + if (mode == "owncopy") want[0] = {"a second copy of WrongGPU RR is loaded (", 1}; + if (mode == "passthrough") want[0] = {"; it loaded after WrongGPU: WrongGPU passes every call on unchanged; to use WrongGPU RR, move it aside)", 1}; + if (!want[0].text) return "fail: unknown mode " + mode; + if (occurrences(got, want[0].text) != want[0].n) return std::string("fail: log lacks \"") + want[0].text + "\""; + const size_t stems = occurrences(got, stem); + if (stems != ((mode == "off" || mode == "passthrough") ? 1u : 0u)) return "fail: " + std::to_string(stems) + " stays-off line(s)"; + return "ok " + mode; +} + +DWORD WINAPI scene_thread(void*) { + std::string r; + try { + r = run_scene(); + } catch (...) { + r = "fail: exception"; + } + const std::wstring result = env(L"WGTEST_GUARD_RESULT"); + FILE* f = _wfopen(result.c_str(), L"wb"); + if (f) { + fputs(r.c_str(), f); + fclose(f); + } + HANDLE ev = OpenEventW(EVENT_MODIFY_STATE, FALSE, env(L"WGTEST_GUARD_EVENT").c_str()); + if (ev) { + SetEvent(ev); + CloseHandle(ev); + } + return 0; +} + +} // namespace + +BOOL WINAPI DllMain(HINSTANCE inst, DWORD reason, LPVOID) { + if (reason == DLL_PROCESS_ATTACH) { + DisableThreadLibraryCalls(inst); + if (HANDLE t = CreateThread(nullptr, 0, scene_thread, nullptr, 0, nullptr)) CloseHandle(t); // runs after the lock + } + return TRUE; +} diff --git a/clean/rr_f/proxy/tests/test_hook_dll.cpp b/clean/rr_f/proxy/tests/test_hook_dll.cpp index faf6ddac..03a1acca 100644 --- a/clean/rr_f/proxy/tests/test_hook_dll.cpp +++ b/clean/rr_f/proxy/tests/test_hook_dll.cpp @@ -498,6 +498,7 @@ int main(int argc, char** argv) { #endif CHECK(count(L, "patched IAT slot") == 0); CHECK(count(L, "patched delay-load IAT slot") == 0); + CHECK(count(L, "another Ray Reconstruction plugin is active") == 0); // RR guard: not reached, quiet TEST_SUMMARY("test_hook_dll (wrong version)"); } @@ -529,6 +530,12 @@ int main(int argc, char** argv) { // Matching version: the ASI redirected our RR-role IAT slots (observed through the log). { std::vector L = read_lines(log_path); + // RR guard: no other RR plugin here (the stand-in host's init patch, the delay helper's thunks): the guard + // stays quiet (one clean check line, no "stays off" / second-copy / later-plugin line) + CHECK(count(L, "hook: coexistence check at load: no other Ray Reconstruction plugin found (") == 1); + CHECK(count(L, "another Ray Reconstruction plugin is active") == 0); + CHECK(count(L, "a second copy of WrongGPU RR is loaded") == 0); + CHECK(count(L, "a plugin loaded after WrongGPU replaced its hooks") == 0); #if WG_TEST_DELAYLOAD CHECK(count(L, "loaded for the exe's delay-load import") == 1); CHECK(count(L, "patched IAT slot") == 0); // the exe has no plain import of the interface diff --git a/clean/rr_f/proxy/tests/test_rr_guard.cpp b/clean/rr_f/proxy/tests/test_rr_guard.cpp new file mode 100644 index 00000000..ef767853 --- /dev/null +++ b/clean/rr_f/proxy/tests/test_rr_guard.cpp @@ -0,0 +1,329 @@ +// SPDX-License-Identifier: MIT +// RR guard: CPU unit test of the coexistence guard's pieces without process state (src/rr_guard.h). +// - safe reads: a readable buffer; a PAGE_NOACCESS page, a reserved page, a guard page (the guard flag must survive the +// check: nothing touched it); a read across a readable / unreadable boundary; the cached reader's structured-exception +// path (a page made unreadable after its region was cached); the cache keeps VirtualQuery calls few; +// - decode_jump: every jump form, and a jmp [rip+disp32] whose cell is not readable; +// - classify: synthetic modules (ranges of one allocation) and anonymous relays: the interface's own code, a hook jump +// to another module, a jump inside the interface, the linker's import thunk, a relay chain to the host, a relay loop +// (more than kMaxHops), anonymous code, an unreadable target, a copy of WrongGPU RR, WrongGPU.asi, the exe's thunk; +// - Verdict precedence, override parsing, the exact log lines; +// - Decision: 32 threads make the "first call" at once: decide runs exactly once, every thread sees the same state. +#define WIN32_LEAN_AND_MEAN +#include + +#include +#include +#include + +#include +#include +#include +#include + +#include "../src/rr_guard.h" +#include "test_util.h" + +using namespace wgrr::guard; + +static const size_t kPage = 4096; + +static void put_rel32(uint8_t* at, const void* target) { // E9 rel32 at `at` + at[0] = 0xE9; + const int32_t rel = (int32_t)((const uint8_t*)target - (at + 5)); + memcpy(at + 1, &rel, 4); +} +static void put_abs(uint8_t* at, const void* target) { // FF 25 00000000 + at[0] = 0xFF; + at[1] = 0x25; + memset(at + 2, 0, 4); + memcpy(at + 6, &target, 8); +} +static void put_rip_cell(uint8_t* at, const void* cell) { // FF 25 + at[0] = 0xFF; + at[1] = 0x25; + const int32_t disp = (int32_t)((const uint8_t*)cell - (at + 6)); + memcpy(at + 2, &disp, 4); +} + +int main() { + // ---------------------------------------------------------------- safe reads + { + uint64_t v = 0x1122334455667788ull, out = 0; + CHECK(safe_read(&v, &out, sizeof v) && out == v); + CHECK(!safe_read(nullptr, &out, 8)); + CHECK(!safe_read(&v, nullptr, 8)); + + uint8_t* blk = static_cast(VirtualAlloc(nullptr, 4 * kPage, MEM_RESERVE, PAGE_NOACCESS)); + CHECK(blk != nullptr); + // page 0 readable, page 1 PAGE_NOACCESS, page 2 guard page, page 3 reserved only + CHECK(VirtualAlloc(blk, kPage, MEM_COMMIT, PAGE_READWRITE) == blk); + CHECK(VirtualAlloc(blk + kPage, kPage, MEM_COMMIT, PAGE_NOACCESS) == blk + kPage); + CHECK(VirtualAlloc(blk + 2 * kPage, kPage, MEM_COMMIT, PAGE_READWRITE | PAGE_GUARD) == blk + 2 * kPage); + memset(blk, 0xAB, kPage); + uint8_t b[16] = {}; + CHECK(safe_read(blk + 8, b, 16) && b[0] == 0xAB && b[15] == 0xAB); + CHECK(readable(blk, kPage)); + CHECK(!readable(blk + kPage, 1)); + CHECK(!safe_read(blk + kPage, b, 1)); // PAGE_NOACCESS + CHECK(!safe_read(blk + 2 * kPage + 16, b, 8)); // guard page + CHECK(!safe_read(blk + 3 * kPage, b, 8)); // reserved, not committed + CHECK(!safe_read(blk + kPage - 4, b, 8)); // across readable -> unreadable + MEMORY_BASIC_INFORMATION m; + CHECK(VirtualQuery(blk + 2 * kPage, &m, sizeof m) && (m.Protect & PAGE_GUARD)); // never touched: still a guard page + uint64_t p64 = 0; + CHECK(!safe_get(blk + 3 * kPage, &p64)); + + // the cached reader: many reads in one region take one VirtualQuery; a page made unreadable after its region was + // cached is caught by the structured-exception path (no fault, false) + Reader r; + for (int i = 0; i < 200; ++i) CHECK(r.get(blk + 8 * i, &p64)); + CHECK(r.queries == 1); + CHECK(!r.get(blk + kPage, &p64)); + Reader r2; + CHECK(r2.get(blk + 64, &p64)); + DWORD old = 0; + CHECK(VirtualProtect(blk, kPage, PAGE_NOACCESS, &old)); + CHECK(!r2.get(blk + 128, &p64)); // cached as readable, now faults: caught + CHECK(VirtualProtect(blk, kPage, PAGE_READWRITE, &old)); + char s[8]; + memcpy(blk + kPage - 3, "abc", 3); // no NUL before the unreadable page + Reader r3; + CHECK(!r3.str(blk + kPage - 3, s, sizeof s)); + memcpy(blk + 100, "name", 5); + CHECK(r3.str(blk + 100, s, sizeof s) && strcmp(s, "name") == 0); + CHECK(!r3.str(blk + 100, s, 4)); // longer than the buffer + VirtualFree(blk, 0, MEM_RELEASE); + } + + // ---------------------------------------------------------------- decode_jump + { + uint8_t code[32]; + const void* t = nullptr; + const void* cell = nullptr; + const uint8_t* at = reinterpret_cast(0x10000000); + code[0] = 0xE9; + int32_t rel = 0x100; + memcpy(code + 1, &rel, 4); + CHECK(decode_jump(code, 5, at, &t, &cell) && t == at + 5 + 0x100 && cell == nullptr); + CHECK(!decode_jump(code, 4, at, &t, &cell)); // too short + code[0] = 0xEB; + code[1] = 0xF0; // -16 + CHECK(decode_jump(code, 2, at, &t, &cell) && t == at + 2 - 16); + uint64_t target = 0x123456789ull; + uint8_t mov_rax[12] = {0x48, 0xB8}; + memcpy(mov_rax + 2, &target, 8); + mov_rax[10] = 0xFF; + mov_rax[11] = 0xE0; + CHECK(decode_jump(mov_rax, 12, at, &t, &cell) && (uint64_t)(uintptr_t)t == target); + mov_rax[10] = 0x50; + mov_rax[11] = 0xC3; + CHECK(decode_jump(mov_rax, 12, at, &t, &cell) && (uint64_t)(uintptr_t)t == target); + uint8_t mov_r11[13] = {0x49, 0xBB}; + memcpy(mov_r11 + 2, &target, 8); + mov_r11[10] = 0x41; + mov_r11[11] = 0xFF; + mov_r11[12] = 0xE3; + CHECK(decode_jump(mov_r11, 13, at, &t, &cell) && (uint64_t)(uintptr_t)t == target); + // jmp [rip+0] with the cell right behind it (real memory: the cell is read) + uint8_t* live = static_cast(VirtualAlloc(nullptr, 2 * kPage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + put_abs(live, reinterpret_cast(target)); + CHECK(decode_jump(live, 14, live, &t, &cell) && (uint64_t)(uintptr_t)t == target && cell == live + 6); + // REX.W form + live[100] = 0x48; + put_abs(live + 101, reinterpret_cast(target)); + CHECK(decode_jump(live + 100, 15, live + 100, &t, &cell) && (uint64_t)(uintptr_t)t == target); + // a cell on an unreadable page: no decode (classify reports unknown) + DWORD old = 0; + put_rip_cell(live + 200, live + kPage + 8); + CHECK(VirtualProtect(live + kPage, kPage, PAGE_NOACCESS, &old)); + CHECK(!decode_jump(live + 200, 6, live + 200, &t, &cell)); + uint8_t plain[4] = {0x48, 0x89, 0x5C, 0x24}; // mov [rsp+..], rbx: not a jump + CHECK(!decode_jump(plain, 4, at, &t, &cell)); + VirtualFree(live, 0, MEM_RELEASE); + } + + // ---------------------------------------------------------------- classify (synthetic modules) + { + // one executable allocation split into "modules": iface, foreign, host, own copy, WrongGPU.asi, exe, self; + // the last pages are anonymous (no module); one page is made PAGE_NOACCESS + const size_t kMod = 4 * kPage; + const int kMods = 7; + uint8_t* blk = static_cast(VirtualAlloc(nullptr, kMods * kMod + 4 * kPage, MEM_RESERVE | MEM_COMMIT, + PAGE_EXECUTE_READWRITE)); + CHECK(blk != nullptr); + memset(blk, 0x90, kMods * kMod + 4 * kPage); // nop: "not a jump" + uint8_t* iface = blk; + uint8_t* foreign = blk + kMod; + uint8_t* host = blk + 2 * kMod; + uint8_t* copy = blk + 3 * kMod; + uint8_t* wgasi = blk + 4 * kMod; + uint8_t* exe = blk + 5 * kMod; + uint8_t* self = blk + 6 * kMod; + uint8_t* anon = blk + kMods * kMod; // 4 anonymous pages; the last one unreadable + const char* names[kMods] = {"iface.dll", "other.asi", "host.dll", "WrongGPU-RR-copy.asi", "WrongGPU.asi", "game.exe", + "WrongGPU-RR.asi"}; + Env env; + env.iface = iface; + env.host = host; + env.exe = exe; + env.self = self; + env.iface_iat_begin = iface + 3 * kPage; // the interface's import table: its last page + env.iface_iat_end = iface + 4 * kPage; + env.module_of = [=](const void* a) -> const void* { + const uint8_t* p = static_cast(a); + if (p < blk || p >= blk + kMods * kMod) return nullptr; + return blk + ((p - blk) / kMod) * kMod; + }; + env.exports = [=](const void* m, const char* name) { + return (m == copy && strcmp(name, kOwnRrExport) == 0) || (m == wgasi && strcmp(name, kWrongGpuAsiExport) == 0); + }; + env.name_of = [=](const void* m) { return std::string(names[(static_cast(m) - blk) / kMod]); }; + DWORD old = 0; + + Where w = classify(iface + 16, env, true); // the interface's own code + CHECK(w.owner == Owner::kInterface && w.module == "iface.dll" && w.hops == 0); + put_abs(iface + 64, foreign + 32); // a hook on an export: FF25 to another module + w = classify(iface + 64, env, true); + CHECK(w.owner == Owner::kForeign && w.module == "other.asi" && w.hops == 1); + w = classify(iface + 64, env, false); // a slot value inside the interface (no following) + CHECK(w.owner == Owner::kInterface); + put_rel32(iface + 128, iface + 1024); // a jump inside the interface: its own code + CHECK(classify(iface + 128, env, true).owner == Owner::kInterface); + void* foreign_fn = foreign + 48; + memcpy(iface + 3 * kPage + 8, &foreign_fn, 8); // the interface's import table cell + put_rip_cell(iface + 192, iface + 3 * kPage + 8); // the linker's import thunk: not a hook + CHECK(classify(iface + 192, env, true).owner == Owner::kInterface); + memcpy(iface + 2048, &foreign_fn, 8); + put_rip_cell(iface + 256, iface + 2048); // a cell outside the import table (a hook's cell): followed + w = classify(iface + 256, env, true); + CHECK(w.owner == Owner::kForeign && w.hops == 1); + // export -> E9 -> anonymous relay (FF25) -> host: the host's own trampoline chain + put_abs(anon + 16, host + 8); + put_rel32(iface + 320, anon + 16); + w = classify(iface + 320, env, true); + CHECK(w.owner == Owner::kHost && w.hops == 2); + // export -> relay -> relay -> foreign + put_abs(anon + 64, anon + 128); + put_abs(anon + 128, foreign + 64); + put_rel32(iface + 384, anon + 64); + w = classify(iface + 384, env, true); + CHECK(w.owner == Owner::kForeign && w.module == "other.asi" && w.hops == 3); + // a relay loop: more than kMaxHops -> unknown (the safe side) + put_abs(anon + 256, anon + 512); + put_abs(anon + 512, anon + 256); + CHECK(classify(anon + 256, env, false).owner == Owner::kUnknown); + // anonymous code that does not jump on + CHECK(classify(anon + 1024, env, false).owner == Owner::kAnonymous); + // an unreadable target: unknown, and an export whose jmp [rip] cell is unreadable: unknown + uint8_t* dead = anon + 3 * kPage; + CHECK(VirtualProtect(dead, kPage, PAGE_NOACCESS, &old)); + CHECK(classify(dead + 32, env, false).owner == Owner::kUnknown); + put_rel32(iface + 448, dead + 32); + CHECK(classify(iface + 448, env, true).owner == Owner::kUnknown); + put_rip_cell(iface + 512, dead + 64); + CHECK(classify(iface + 512, env, true).owner == Owner::kUnknown); + CHECK(classify(nullptr, env, false).owner == Owner::kUnknown); + // the other module kinds + CHECK(classify(copy + 8, env, false).owner == Owner::kOwnCopy); + CHECK(classify(wgasi + 8, env, false).owner == Owner::kWrongGpu); + CHECK(classify(exe + 8, env, false).owner == Owner::kExeThunk); + CHECK(classify(self + 8, env, false).owner == Owner::kSelf); + CHECK(classify(host + 8, env, false).owner == Owner::kHost); + // an export hooked straight into a copy of WrongGPU RR + put_abs(iface + 576, copy + 16); + w = classify(iface + 576, env, true); + CHECK(w.owner == Owner::kOwnCopy && w.module == "WrongGPU-RR-copy.asi"); + + // ---- Verdict + Verdict v; + v.add(classify(iface + 16, env, true), "the export A of iface.dll", false, false); + v.add(classify(host + 8, env, false), "the import slot B of game.exe", false, false); + v.add(classify(exe + 8, env, false), "the delay-load slot C of game.exe", false, true); + v.add(classify(anon + 1024, env, false), "the host's next function of D", true, false); + CHECK(v.kind == Verdict::kClean && v.reads == 4); + v.add(classify(iface + 384, env, true), "the export E of iface.dll", false, false); + CHECK(v.kind == Verdict::kOther); + CHECK(v.detail == "the export E of iface.dll leads to other.asi (through 3 hook jumps)"); + v.add(classify(dead + 32, env, false), "the import slot F of game.exe", false, false); + CHECK(v.detail == "the export E of iface.dll leads to other.asi (through 3 hook jumps)"); // the first one stays + v.add(classify(copy + 8, env, false), "the import slot G of game.exe", false, false); + CHECK(v.kind == Verdict::kOwnCopy && v.detail == "WrongGPU-RR-copy.asi"); // a copy of WrongGPU RR before all + v.add(classify(foreign + 8, env, false), "the import slot H of game.exe", false, false); + CHECK(v.kind == Verdict::kOwnCopy && v.reads == 8); + Verdict u; + u.add(classify(dead + 32, env, false), "the import slot F of game.exe", false, false); + CHECK(u.kind == Verdict::kOther && u.detail == "the import slot F of game.exe could not be read"); + Verdict a; + a.add(classify(anon + 1024, env, false), "the import slot I of game.exe", false, false); // anon not accepted here + CHECK(a.kind == Verdict::kOther && a.detail == "the import slot I of game.exe leads to code outside every module"); + Verdict e; + e.add(classify(exe + 8, env, false), "the import slot J of game.exe", false, false); // exe code not accepted here + CHECK(e.kind == Verdict::kOther && e.detail == "the import slot J of game.exe leads to game.exe"); + CHECK(trusted(Owner::kWrongGpu, false, false) && !trusted(Owner::kUnknown, true, true) && + !trusted(Owner::kForeign, true, true) && !trusted(Owner::kOwnCopy, true, true)); + VirtualFree(blk, 0, MEM_RELEASE); + } + + // ---------------------------------------------------------------- the override, the log lines + { + std::string note; + CHECK(!override_take("", ¬e) && note.empty()); + CHECK(!override_take("off", ¬e) && note.empty()); + CHECK(override_take("take", ¬e) && note.empty()); + CHECK(override_take(" Take \r", ¬e) && note.empty()); + CHECK(!override_take("ours", ¬e) && + note == "rr_other_plugin=ours in wronggpu-rr.ini not recognised (off | take); off is used"); + // the beginnings the launcher's Last run page matches (HOOK-MODE.md): exact, no prefix + const std::string stem = "another Ray Reconstruction plugin is active; WrongGPU RR stays off"; + CHECK(line_other("D") == stem + " (D; nothing patched; rr_other_plugin=take in wronggpu-rr.ini uses WrongGPU's " + "instead)"); + CHECK(line_other("D", true) == stem + " (D; WrongGPU's handlers pass every call on unchanged; rr_other_plugin=take " + "in wronggpu-rr.ini uses WrongGPU's instead)"); + CHECK(line_other_later("D") == stem + " (D; it loaded after WrongGPU: WrongGPU passes every call on unchanged; to " + "use WrongGPU RR, move it aside)"); + CHECK(line_cannot_take("D") == "a plugin loaded after WrongGPU replaced its hooks; rr_other_plugin=take cannot be " + "applied: WrongGPU RR stays off and passes every call on unchanged (D); move it aside " + "to use WrongGPU RR"); + CHECK(line_take("D") == "another Ray Reconstruction plugin is active; rr_other_plugin=take: WrongGPU RR goes in " + "front of it (D; it gets the game's other calls, no RR work)"); + CHECK(line_take("D").compare(0, stem.size(), stem) != 0); // RR is on: not a "stays off" line + CHECK(line_own_copy("A", "B") == "a second copy of WrongGPU RR is loaded (A is active); this copy (B) stays off"); + CHECK(line_ngx_other() == stem + " (NGX route only: the host refused WrongGPU's RR provider, another provider " + "holds it; the game-interface route is decided on its own)"); + } + + // ---------------------------------------------------------------- Decision: one decision under concurrent first calls + for (int round = 0; round < 20; ++round) { + Decision d; + std::atomic runs{0}, go{0}, wrong{0}; + std::vector th; + for (int i = 0; i < 32; ++i) + th.emplace_back([&] { + while (!go.load()) std::this_thread::yield(); + d.freeze_once([&] { + ++runs; + Sleep(2); // keep the others waiting inside + return State::kPassThrough; + }); + if (!d.frozen() || d.state() != State::kPassThrough || d.active()) ++wrong; // every caller sees the decision + }); + go.store(1); + for (auto& t : th) t.join(); + CHECK_EQ(runs.load(), 1); + CHECK_EQ(wrong.load(), 0); + int later = 0; + d.check([&] { ++later; return State::kActive; }); // frozen: a later check changes nothing + d.freeze_once([&] { ++later; return State::kActive; }); + CHECK(later == 0 && d.state() == State::kPassThrough); + } + { + Decision d; + CHECK(d.active() && !d.frozen()); + d.check([] { return State::kTaken; }); + CHECK(d.active() && d.state() == State::kTaken && !d.frozen()); + d.set(State::kOff); + CHECK(!d.active()); + } + TEST_SUMMARY("test_rr_guard"); +} diff --git a/clean/rr_f/proxy/tests/test_rr_guard_dll.cpp b/clean/rr_f/proxy/tests/test_rr_guard_dll.cpp new file mode 100644 index 00000000..6a3ee7df --- /dev/null +++ b/clean/rr_f/proxy/tests/test_rr_guard_dll.cpp @@ -0,0 +1,462 @@ +// SPDX-License-Identifier: MIT +// RR guard: end-to-end test of the coexistence guard in the hook-mode plugin (src/hook_dll.cpp + rr_guard.h). +// The executable is the fake game, as in test_hook_dll.cpp: it imports the RR path's functions by name from the stand-in +// interface (tests/gen_fake_original.py). The "other Ray Reconstruction plugin" is our own stand-in, +// wgtest_other_rr.dll (tests/fake_other_rr.cpp); no third-party file is used. +// test_rr_guard_dll.exe [--take] +// Modes (import build): +// clean no other plugin: active; 16 threads make the first call at once: one re-check line; the scan cost +// first the other plugin redirected the exe's import slots before ours loaded (wrapping): off, nothing patched +// inline the other plugin put a jmp [rip] on the evaluate export: off +// relay the same through a jmp rel32 to an anonymous relay: off ("through 2 hook jumps") +// anon one import slot leads to code outside every module: off +// noaccess one import slot leads to a PAGE_NOACCESS page: "could not be read", off, no fault +// guardpage one import slot leads to a guard page: the same, and the page is still a guard page afterwards +// late the other plugin wrapped our hooks after InitializeASI: 16 threads make the first call at once: one +// decision, one line, every call passed on unchanged +// late-replace the other plugin replaced our hooks after InitializeASI (no call reaches us): found at OptiPluginInit +// provider the other plugin holds the host's NGX RR provider: NGX route only, the game-interface route stays +// owncopy two copies of WrongGPU RR: the second stays off and registers nothing +// --take (wronggpu-rr.ini rr_other_plugin=take): first / inline: WrongGPU RR in front; late: the can't-take line. +// Modes (built with WG_TEST_NOIMPORT: the exe does not link the interface, the host routes are used): +// route no other plugin: our routes continue to the interface +// route-other the other plugin's routes were registered first (under ours): passing (take: RR ours) +// route-inline the other plugin patched the evaluate export before the host hooked the module: off, no routes +#define WIN32_LEAN_AND_MEAN +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "wg_binding.inc" +#include "../include/rr_proxy_abi.h" +#include "../include/wg_host_menu_abi.h" +#include "test_util.h" + +#ifndef WG_TEST_NOIMPORT +#define WG_TEST_NOIMPORT 0 +#endif + +#if !WG_TEST_NOIMPORT +extern "C" { +WgResultCode slIsFeatureSupported(uint32_t, const WgAdapterInfo*); +WgResultCode slEvaluateFeature(uint32_t, const WgFrameToken*, const WgHeader* const*, uint32_t, void*); +WgResultCode slGetFeatureFunction(uint32_t, const char*, void**); +WgResultCode slAllocateResources(void*, uint32_t, const WgViewport*); +WgResultCode slSetD3DDevice(void*); +WgResultCode slInit(const WgPreferences*, uint64_t); +} +// referenced, so that the linker keeps every one in the import table (the guard reads those slots) +void* volatile g_keep_imports[] = {(void*)&slIsFeatureSupported, (void*)&slEvaluateFeature, (void*)&slGetFeatureFunction, + (void*)&slAllocateResources, (void*)&slSetD3DDevice, (void*)&slInit}; +#endif + +namespace { + +struct OrState { long calls[32]; long rr_calls; long ngx_creates; }; +struct FoState { int calls; int last_index; const char* last_role; uint32_t feature; }; + +const uint32_t kRR = WG_FEAT_RAY_RECONSTRUCTION; +const uint32_t kOther = 1; // another feature: the stand-in interface answers 100 + 1 % 50 +const WgResultCode kIfaceAnswer = (WgResultCode)101; +const int kIsSupported = 2, kGetFunction = 7, kAllocate = 8, kEvaluate = 16; + +std::wstring widen(const std::string& s) { return std::wstring(s.begin(), s.end()); } +std::vector read_lines(const std::wstring& path) { + std::vector out; + FILE* f = _wfopen(path.c_str(), L"rb"); + if (!f) return out; + char buf[8192]; + while (fgets(buf, sizeof buf, f)) { + std::string s(buf); + while (!s.empty() && (s.back() == '\n' || s.back() == '\r')) s.pop_back(); + out.push_back(s); + } + fclose(f); + return out; +} +size_t count(const std::vector& v, const std::string& needle) { + size_t n = 0; + for (const auto& s : v) n += s.find(needle) != std::string::npos; + return n; +} +// 0.6.1: lines that do not start with the "hh:mm:ss.mmm " time stamp: a torn line (two copies' writes run into each +// other); every line the plugin writes starts with it +size_t torn_lines(const std::vector& v) { + size_t n = 0; + for (const auto& s : v) { + bool ok = s.size() > 13 && s[2] == ':' && s[5] == ':' && s[8] == '.' && s[12] == ' '; + for (int i : {0, 1, 3, 4, 6, 7, 9, 10, 11}) ok = ok && s.size() > (size_t)i && s[i] >= '0' && s[i] <= '9'; + n += !ok; + } + return n; +} +// the message of a log line starts after the "hh:mm:ss.mmm " time stamp (the probe log adds "f= ") +size_t count_starting(const std::vector& v, const std::string& start) { + size_t n = 0; + for (const auto& s : v) { + size_t at = 13; + if (s.compare(at, 2, "f=") == 0) at = s.find(' ', at) + 1; + n += s.size() > at && s.compare(at, start.size(), start) == 0; + } + return n; +} +void write_text(const std::wstring& p, const char* s) { + FILE* f = _wfopen(p.c_str(), L"wb"); + if (f) { fputs(s, f); fclose(f); } +} +// the cost of a coexistence check line ("... address(es) read in 0.123 ms)"), or -1 +double cost_of(const std::vector& v, const std::string& which) { + for (const auto& s : v) { + if (s.find(which) == std::string::npos) continue; + const size_t at = s.rfind(" read in "); + if (at != std::string::npos) return atof(s.c_str() + at + 9); + } + return -1.0; +} + +// ---- a stand-in host (plugin interface 3 / 4 / 5 fields only; no menu): routes chain per export, one NGX provider +namespace host { +HMODULE iface = nullptr; +std::map head; // the current front of each export's chain +std::map handler_of_plugin[2]; // [0] WrongGPU, [1] the other plugin: the handler per export +WgHostMenuPlugin* const kOurs = reinterpret_cast(0x1000); +WgHostMenuPlugin* const kTheirs = reinterpret_cast(0x2000); +int route_regs[2] = {0, 0}, ngx_regs = 0; +WgHostMenuPlugin* ngx_owner = nullptr; +void (*callback)(void*, uint32_t, uint32_t, uint32_t, void*) = nullptr; +void* callback_user = nullptr; +bool register_routes(WgHostMenuPlugin* p, const WgHostSlRoute* r, uint32_t n) { + const int who = p == kOurs ? 0 : 1; + ++route_regs[who]; + for (uint32_t i = 0; i < n; ++i) { + const std::string name = r[i].export_name; + void* next = head.count(name) ? head[name] : reinterpret_cast(GetProcAddress(iface, r[i].export_name)); + *r[i].next = next; + head[name] = r[i].handler; + handler_of_plugin[who][name] = r[i].handler; + } + return true; +} +bool set_callback(WgHostMenuPlugin*, void (*cb)(void*, uint32_t, uint32_t, uint32_t, void*), void* user) { + callback = cb; + callback_user = user; + return true; +} +bool register_ngx(WgHostMenuPlugin* p, const WgHostNgxRr* prov) { + ++ngx_regs; + if (ngx_owner || !prov || !prov->create) return false; + ngx_owner = p; + return true; +} +WgHostMenuApi table() { + WgHostMenuApi a = {}; + a.size = sizeof a; + a.version = 5; + a.register_streamline_routes = register_routes; + a.set_streamline_callback = set_callback; + a.register_ngx_rr = register_ngx; + return a; +} +} // namespace host + +using IsSupportedFn = WgResultCode (*)(uint32_t, const WgAdapterInfo*); + +// n threads released at once, each calling f(); returns how many returned `want` +template +int at_once(int n, F f, WgResultCode want) { + std::atomic go{0}, ok{0}; + std::vector th; + for (int i = 0; i < n; ++i) + th.emplace_back([&] { + while (!go.load()) std::this_thread::yield(); + if (f() == want) ++ok; + }); + go.store(1); + for (auto& t : th) t.join(); + return ok.load(); +} + +} // namespace + +int main(int argc, char** argv) { + if (argc < 3) return 2; + std::string stage = argv[1]; + if (stage.back() != '\\') stage += '\\'; + const std::string mode = argv[2]; + bool take = false; + for (int i = 3; i < argc; ++i) take = take || strcmp(argv[i], "--take") == 0; + const std::wstring ws = widen(stage); + const std::wstring log_path = ws + (WG_BINDING_PROBE ? L"wronggpu-rr-probe.log" : L"wronggpu-rr.log"); + DeleteFileW(log_path.c_str()); + DeleteFileW((ws + L"wronggpu-rr.ini").c_str()); + if (take) write_text(ws + L"wronggpu-rr.ini", "rr_other_plugin = take\r\n"); + CreateDirectoryW((ws + L"data").c_str(), nullptr); + write_text(ws + L"data\\wronggpu.ini", "[wronggpu]\r\nrr_mode = accurate\r\n"); + SetEnvironmentVariableW(L"WG_DATA_DIR", (ws + L"data\\").c_str()); + SetEnvironmentVariableW(L"WG_RR_SLOT_CHECKS", L"0"); + const std::string label = std::string("test_rr_guard_dll (") + (WG_BINDING_PROBE ? "probe" : "release") + ", " + mode + + (take ? ", take" : "") + ")"; + + HMODULE other = LoadLibraryW((ws + L"wgtest_other_rr.dll").c_str()); + CHECK(other != nullptr); + if (!other) TEST_SUMMARY(label.c_str()); + auto or_state = reinterpret_cast(GetProcAddress(other, "wgtest_or_state")); + auto or_patch_iat = reinterpret_cast(GetProcAddress(other, "wgtest_or_patch_iat")); + auto or_set_slot = + reinterpret_cast(GetProcAddress(other, "wgtest_or_set_slot")); + auto or_patch_export = reinterpret_cast(GetProcAddress(other, "wgtest_or_patch_export")); + auto or_routes = reinterpret_cast(GetProcAddress(other, "wgtest_or_routes")); + auto or_ngx = reinterpret_cast(GetProcAddress(other, "wgtest_or_register_ngx")); + const OrState* os = or_state(); + HMODULE exe = GetModuleHandleW(nullptr); + const std::string exe_leaf = "test_rr_guard_dll.exe"; + const std::string iface_leaf = kWgInterposerFile; + const std::string evaluate_name = kWgRoleNames[kEvaluate]; + const std::string stem = "another Ray Reconstruction plugin is active; WrongGPU RR stays off ("; + const WgHostMenuApi api = host::table(); + auto load_asi = [&](const std::wstring& file, void (**init)(), WgHostMenuInitFn* pinit) { + HMODULE m = LoadLibraryW((ws + file).c_str()); + CHECK(m != nullptr); + *init = m ? reinterpret_cast(GetProcAddress(m, "InitializeASI")) : nullptr; + *pinit = m ? reinterpret_cast(GetProcAddress(m, WG_HOST_MENU_INIT_EXPORT)) : nullptr; + CHECK(*init != nullptr && *pinit != nullptr); + return m; + }; + void (*init)() = nullptr; + WgHostMenuInitFn plugin_init = nullptr; + +#if !WG_TEST_NOIMPORT + HMODULE iface = GetModuleHandleA(kWgInterposerFile); + CHECK(iface != nullptr); + host::iface = iface; + FoState* fo = reinterpret_cast(GetProcAddress(iface, "wgtest_fo_state"))(); + const bool late = mode == "late" || mode == "late-replace"; + // ---- the other plugin before ours + void* odd_page = nullptr; + if (mode == "first") CHECK(or_patch_iat(exe, kWgInterposerFile, 1) >= 6); + if (mode == "inline") CHECK(or_patch_export(iface, evaluate_name.c_str(), 0) == 1); + if (mode == "relay") CHECK(or_patch_export(iface, evaluate_name.c_str(), 1) == 1); + if (mode == "anon") { + odd_page = VirtualAlloc(nullptr, 4096, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE); + memset(odd_page, 0xC3, 4096); // ret: code outside every module that does not jump on + CHECK(or_set_slot(exe, kWgInterposerFile, evaluate_name.c_str(), odd_page) == 1); + } + if (mode == "noaccess" || mode == "guardpage") { + odd_page = VirtualAlloc(nullptr, 4096, MEM_RESERVE | MEM_COMMIT, + mode == "noaccess" ? PAGE_NOACCESS : (PAGE_EXECUTE_READ | PAGE_GUARD)); + CHECK(or_set_slot(exe, kWgInterposerFile, evaluate_name.c_str(), odd_page) == 1); + } + if (mode == "provider") CHECK(or_ngx(&api, host::kTheirs)); + + // ---- WrongGPU RR (the host loads it and runs its entry) + load_asi(widen(kWgHookFile), &init, &plugin_init); + if (!init || !plugin_init) TEST_SUMMARY(label.c_str()); + init(); + if (mode == "owncopy") { // a second copy under another file name (build.py stages it) + void (*init2)() = nullptr; + WgHostMenuInitFn plugin_init2 = nullptr; + load_asi(L"WrongGPU-RR-copy.asi", &init2, &plugin_init2); + if (init2) init2(); + CHECK(plugin_init2 && !plugin_init2(&api, host::kOurs)); // the copy registers nothing + } + // ---- the other plugin after ours + if (mode == "late") CHECK(or_patch_iat(exe, kWgInterposerFile, 1) >= 6); // wraps our handlers + if (mode == "late-replace") CHECK(or_patch_iat(exe, kWgInterposerFile, 0) >= 6); // replaces them + // OptiPluginInit (late-replace: the check that finds it, as no call reaches our handlers any more); "late" makes the + // first call before it, so that the first call decides + if (mode != "late") plugin_init(&api, host::kOurs); + + // ---- the game's calls + if (mode == "clean" || mode == "late" || mode == "owncopy" || mode == "provider") { + // 16 threads make the game's first interface call at once + const int ok = at_once(16, [] { return slIsFeatureSupported(kOther, nullptr); }, kIfaceAnswer); + CHECK_EQ(ok, 16); + } + if (mode == "late") plugin_init(&api, host::kOurs); + std::vector L = read_lines(log_path); + printf("log lines %zu, torn %zu\n", L.size(), torn_lines(L)); + CHECK(torn_lines(L) == 0); // 0.6.1: one append call per line, also with two copies + const double load_cost = cost_of(L, "hook: coexistence check at load: "); + CHECK(load_cost >= 0.0 && load_cost < 5.0); + printf("coexistence check at load: %.3f ms\n", load_cost); + CHECK(count(L, "hook: coexistence check at load: ") == (mode == "owncopy" ? 1u : 1u)); + const long rr_before = os->rr_calls; + const WgResultCode rr = slIsFeatureSupported(kRR, nullptr); + const bool rr_by_other = os->rr_calls == rr_before + 1; + const std::string self_slot = "the import slot "; + + if (mode == "clean" || mode == "owncopy") { + CHECK(count(L, "hook: coexistence check at load: no other Ray Reconstruction plugin found (") == 1); + CHECK(count(L, "hook: coexistence re-check at the game's first call: no other Ray Reconstruction plugin found (") == 1); + CHECK(count(L, "another Ray Reconstruction plugin is active") == 0); + CHECK(count(L, std::string("hook: patched IAT slot ") + kWgRoleNames[kIsSupported] + " in ") == 1); // only one copy patched + CHECK(!rr_by_other); + if (mode == "owncopy") { + CHECK(count_starting(L, "a second copy of WrongGPU RR is loaded (") == 1); + CHECK(count(L, std::string(kWgHookFile) + " is active); this copy (") == 1); + CHECK(count(L, "WrongGPU-RR-copy.asi) stays off") == 1); + } +#if !WG_BINDING_PROBE + CHECK(count(L, "NGX: RR provider registered with the host") == 1); + CHECK(host::ngx_regs == 1 && host::ngx_owner == host::kOurs); +#endif + } else if (mode == "first" || mode == "inline" || mode == "relay" || mode == "anon" || mode == "noaccess" || + mode == "guardpage") { + const std::string detail = + mode == "first" ? self_slot // the first redirected slot in import order; the module is checked below + : mode == "inline" ? "the export " + evaluate_name + " of " + iface_leaf + " leads to wgtest_other_rr.dll (through 1 hook jump)" + : mode == "relay" ? "the export " + evaluate_name + " of " + iface_leaf + " leads to wgtest_other_rr.dll (through 2 hook jumps)" + : mode == "anon" ? self_slot + evaluate_name + " of " + exe_leaf + " leads to code outside every module" + : self_slot + evaluate_name + " of " + exe_leaf + " could not be read"; + CHECK(count(L, "hook: coexistence check at load: another Ray Reconstruction plugin found (") == 1); + if (take && (mode == "first" || mode == "inline")) { + CHECK(count_starting(L, "another Ray Reconstruction plugin is active; rr_other_plugin=take: WrongGPU RR goes in " + "front of it (" + detail) == 1); + CHECK(count(L, stem) == 0); + CHECK(count(L, std::string("hook: patched IAT slot ") + kWgRoleNames[kIsSupported] + " in ") == 1); + CHECK(!rr_by_other); // RR is WrongGPU's + if (mode == "first") { // the other calls go on through the other plugin (it sees them, no RR work) + const long before = os->calls[kIsSupported]; + CHECK_EQ(slIsFeatureSupported(kOther, nullptr), kIfaceAnswer); + CHECK(os->calls[kIsSupported] == before + 1); + } + } else { + CHECK(count_starting(L, stem + detail) == 1); + if (mode == "first") CHECK(count(L, " leads to wgtest_other_rr.dll; nothing patched; ") == 1); + CHECK(count(L, "; nothing patched; rr_other_plugin=take in wronggpu-rr.ini uses WrongGPU's instead)") == 1); + CHECK(count(L, "hook: patched IAT slot") == 0); + CHECK(count(L, "hook: coexistence re-check") == 0); + if (mode == "first" || mode == "inline" || mode == "relay") { + CHECK(mode == "first" ? rr_by_other : !rr_by_other); // inline: the game's import slot reaches the interface + CHECK_EQ(slIsFeatureSupported(kOther, nullptr), kIfaceAnswer); + } else { + CHECK(fo->last_role && strcmp(fo->last_role, "is-supported") == 0 && fo->feature == kRR); // untouched path + (void)rr; + } +#if !WG_BINDING_PROBE + CHECK(count(L, "NGX: RR provider not registered: WrongGPU RR stays off in this process") == 1); + CHECK(host::ngx_owner == nullptr); +#endif + } + if (mode == "guardpage") { + MEMORY_BASIC_INFORMATION m; + CHECK(VirtualQuery(odd_page, &m, sizeof m) && (m.Protect & PAGE_GUARD)); // never touched + } + } else if (late) { + CHECK(count(L, "hook: coexistence check at load: no other Ray Reconstruction plugin found (") == 1); + CHECK(count(L, std::string("hook: patched IAT slot ") + kWgRoleNames[kIsSupported] + " in ") == 1); + const std::string why = mode == "late" ? "the game's first call" : "OptiPluginInit"; + CHECK(count(L, "hook: coexistence re-check at " + why + ": another Ray Reconstruction plugin took the RR calls " + "after WrongGPU (") == 1); + CHECK(count(L, "hook: coexistence re-check") == 1); // one decision, one line, even with 16 threads at once + const std::string detail = "the import slot "; + if (take) { + CHECK(count_starting(L, "a plugin loaded after WrongGPU replaced its hooks; rr_other_plugin=take cannot be " + "applied: WrongGPU RR stays off and passes every call on unchanged (" + detail) == 1); + CHECK(count(L, stem) == 0); + } else { + CHECK(count_starting(L, stem + detail) == 1); + CHECK(count(L, " (WrongGPU's hook) leads to wgtest_other_rr.dll; it loaded after WrongGPU: WrongGPU passes every " + "call on unchanged; to use WrongGPU RR, move it aside)") == 1); + } + CHECK(rr_by_other); // RR is the other plugin's + // a call the other plugin passes on reaches our handler, which passes it on unchanged to the interface + const int before = fo->calls; + CHECK_EQ(slEvaluateFeature(kOther, nullptr, nullptr, 0, nullptr), kIfaceAnswer); + CHECK(fo->calls == before + 1 && fo->last_role && strcmp(fo->last_role, "evaluate") == 0); + CHECK_EQ(at_once(8, [] { return slIsFeatureSupported(kOther, nullptr); }, kIfaceAnswer), 8); // consistent after + CHECK(count(read_lines(log_path), "hook: coexistence re-check") == 1); +#if !WG_BINDING_PROBE + CHECK(count(read_lines(log_path), "NGX: RR provider not registered: WrongGPU RR stays off in this process") == 1); + CHECK(host::ngx_owner == nullptr); +#endif + } else if (mode == "provider") { +#if !WG_BINDING_PROBE + CHECK(count_starting(L, stem + "NGX route only: the host refused WrongGPU's RR provider, another provider holds it; " + "the game-interface route is decided on its own)") == 1); + CHECK(host::ngx_owner == host::kTheirs && host::ngx_regs == 2); + CHECK(count(L, std::string("hook: patched IAT slot ") + kWgRoleNames[kIsSupported] + " in ") == 1); // the route stays ours + CHECK(count(L, stem) == 1); + CHECK(!rr_by_other); +#endif + } else { + CHECK(!"unknown mode"); + } + printf("%s: other plugin answered %ld RR call(s)\n", label.c_str(), os->rr_calls); +#else // WG_TEST_NOIMPORT: host routes + (void)or_patch_iat; + (void)or_set_slot; + (void)or_ngx; + load_asi(widen(kWgHookFile), &init, &plugin_init); + if (!init || !plugin_init) TEST_SUMMARY(label.c_str()); + init(); // the interface is not loaded and not linked: waits for the host + plugin_init(&api, host::kOurs); + CHECK(host::callback != nullptr); + HMODULE iface = LoadLibraryW((ws + widen(kWgInterposerFile)).c_str()); // the game loads it at run time + CHECK(iface != nullptr); + host::iface = iface; + FoState* fo = reinterpret_cast(GetProcAddress(iface, "wgtest_fo_state"))(); + if (mode == "route-other") CHECK(or_routes(&api, host::kTheirs) == 4); + if (mode == "route-inline") CHECK(or_patch_export(iface, evaluate_name.c_str(), 0) == 1); + if (host::callback) host::callback(iface, 2, 14, 1, host::callback_user); + std::vector L = read_lines(log_path); + printf("log lines %zu, torn %zu\n", L.size(), torn_lines(L)); + CHECK(torn_lines(L) == 0); // 0.6.1: one append call per line, also with two copies + CHECK(count(L, "waiting for the host's game-interface routes") == 1); + auto ours = reinterpret_cast(host::handler_of_plugin[0][kWgRoleNames[kIsSupported]]); + if (mode == "route") { + CHECK(count(L, "hook: coexistence check before the host routes: no other Ray Reconstruction plugin found (") == 1); + CHECK(count(L, "hook: coexistence check of the host routes: no other Ray Reconstruction plugin found (") == 1); + CHECK(count(L, "another Ray Reconstruction plugin is active") == 0); + CHECK(ours != nullptr); + if (ours) { + CHECK_EQ(ours(kOther, nullptr), kIfaceAnswer); // continues to the interface + const long before = os->rr_calls; + ours(kRR, nullptr); + CHECK(os->rr_calls == before); + } + } else if (mode == "route-other") { + const std::string detail = "the host's next function of " + std::string(kWgRoleNames[kIsSupported]) + + " leads to wgtest_other_rr.dll"; + CHECK(ours != nullptr); + if (take) { + CHECK(count_starting(L, "another Ray Reconstruction plugin is active; rr_other_plugin=take: WrongGPU RR goes in " + "front of it (" + detail) == 1); + CHECK(count(L, stem) == 0); + if (ours) { + const long before = os->rr_calls, calls = os->calls[kIsSupported]; + ours(kRR, nullptr); + CHECK(os->rr_calls == before); // RR is WrongGPU's + CHECK_EQ(ours(kOther, nullptr), kIfaceAnswer); // the other calls continue through the other plugin + CHECK(os->calls[kIsSupported] == calls + 1); + } + } else { + CHECK(count_starting(L, stem + detail + "; WrongGPU's handlers pass every call on unchanged; rr_other_plugin=take " + "in wronggpu-rr.ini uses WrongGPU's instead)") == 1); + if (ours) { + const long before = os->rr_calls; + CHECK_EQ(ours(kRR, nullptr), (WgResultCode)0); // passed on: the other plugin answers RR + CHECK(os->rr_calls == before + 1); + CHECK_EQ(ours(kOther, nullptr), kIfaceAnswer); + } + } + } else if (mode == "route-inline") { + CHECK(count_starting(L, stem + "the export " + evaluate_name + " of " + iface_leaf + + " leads to wgtest_other_rr.dll (through 1 hook jump); nothing patched; ") == 1); + CHECK(host::route_regs[0] == 0); // no routes registered + } else { + CHECK(!"unknown mode"); + } + (void)fo; +#endif + TEST_SUMMARY(label.c_str()); +} diff --git a/clean/rr_f/proxy/tools/build.py b/clean/rr_f/proxy/tools/build.py index fd394351..170b8f45 100644 --- a/clean/rr_f/proxy/tools/build.py +++ b/clean/rr_f/proxy/tools/build.py @@ -31,6 +31,7 @@ import hashlib import json import os +import re import shutil import subprocess import sys @@ -235,6 +236,7 @@ def build_hook(binding, out, probe, name): sh(f'rc /nologo /fo "{res}" "{os.path.join(gen, "wg_version.rc")}"', out) files = CORE + (PROBE if probe else ["rr_panel.cpp", "ngx_rr.cpp"]) # the menu tab, the NGX route: release only files = files + ["setupapi_identity.cpp"] # clean/rr-sm2-shim: the SetupAPI identity shim (Spider-Man2.exe only) + files = files + ["rr_guard.cpp"] # RR guard: another Ray Reconstruction plugin (both builds) sources = " ".join(src("src", c) for c in files) flags = CLFLAGS + (" /DWG_RR_PROBE=1" if probe else "") built = os.path.join(out, n["proxy_file"]) @@ -393,9 +395,79 @@ def test_hook(built, binding, out, logs, probe, n=None, gen=None): + (f"\n{r.stderr.strip()}" if r.stderr.strip() else "")) if r.returncode: raise SystemExit("\n".join(logs)) + test_guard(built, out, logs, probe, n, gen, iface_dll, implib, iface_name) return n, built +# RR guard: the coexistence guard's modes (tests/test_rr_guard_dll.cpp) against our own stand-in "other Ray +# Reconstruction plugin" (tests/fake_other_rr.cpp); "route*" modes use the build without an import of the interface +GUARD_MODES_RELEASE = (["clean"], ["first"], ["first", "--take"], ["inline"], ["inline", "--take"], ["relay"], ["anon"], + ["noaccess"], ["guardpage"], ["late"], ["late", "--take"], ["late-replace"], ["provider"], ["owncopy"], + ["route"], ["route-other"], ["route-other", "--take"], ["route-inline"]) +GUARD_MODES_PROBE = (["clean"], ["first"], ["inline"], ["noaccess"], ["late"], ["owncopy"], ["route-other"]) + + +def test_guard(built, out, logs, probe, n, gen, iface_dll, implib, iface_name): + minor = n["minor"] + kind = "probe" if probe else "release" + g = os.path.join(out, "guard") + os.makedirs(g, exist_ok=True) + stub = os.path.join(g, "wgtest_other_rr.dll") + sh(f'cl {CLFLAGS} /LD /I"{gen}" {src("tests", "fake_other_rr.cpp")} /Fo"{g}\\\\" /Fe"{stub}"', out) + exes = {} + for noimport in (False, True): + sub = os.path.join(g, "noimport" if noimport else "import") + os.makedirs(sub, exist_ok=True) + exe = os.path.join(sub, "test_rr_guard_dll.exe") + sh(f'cl {CLFLAGS} {"/DWG_RR_PROBE=1 " if probe else ""}{"/DWG_TEST_NOIMPORT=1 " if noimport else ""}' + f'/I"{gen}" {src("tests", "test_rr_guard_dll.cpp")} {"" if noimport else chr(34) + implib + chr(34)} ' + f'/Fo"{sub}\\\\" /Fe"{exe}"', out) + exes[noimport] = exe + for noimport in (False, True): + stage = os.path.join(g, "stage-noimport" if noimport else "stage") + shutil.rmtree(stage, ignore_errors=True) + os.makedirs(stage) + for f in (exes[noimport], iface_dll, stub): + shutil.copy(f, stage) + shutil.copy(built, os.path.join(stage, n["proxy_file"])) + shutil.copy(built, os.path.join(stage, "WrongGPU-RR-copy.asi")) # the owncopy mode's second copy + if not probe: + shutil.copy(os.path.join(out, "wronggpu_runtime.dll"), stage) + for m in (GUARD_MODES_PROBE if probe else GUARD_MODES_RELEASE): + if m[0].startswith("route") != noimport: + continue + r = subprocess.run([os.path.join(stage, "test_rr_guard_dll.exe"), stage] + m, capture_output=True, text=True, + timeout=300) + logs.append(f"[2.{minor} guard {kind} {' '.join(m)}] {r.stdout.strip()}" + + (f"\n{r.stderr.strip()}" if r.stderr.strip() else "")) + if r.returncode: + raise SystemExit("\n".join(logs)) + if not probe and not noimport and minor == 14: + owncopy_stress(stage, logs) + + +# 0.6.1: two copies of WrongGPU RR in one process write one log: the owncopy case GUARD_OWNCOPY_STRESS times (release +# build); every run must pass and no line may be torn (one append call per line under the log's process-wide lock) +GUARD_OWNCOPY_STRESS = 200 + + +def owncopy_stress(stage, logs): + exe = os.path.join(stage, "test_rr_guard_dll.exe") + ok, torn, failed = 0, 0, [] + for i in range(GUARD_OWNCOPY_STRESS): + r = subprocess.run([exe, stage, "owncopy"], capture_output=True, text=True, timeout=300) + t = [int(x) for x in re.findall(r"log lines \d+, torn (\d+)", r.stdout)] + torn += sum(t) + if r.returncode == 0 and t: + ok += 1 + elif len(failed) < 3: + failed.append(f"run {i + 1}: exit {r.returncode}: {r.stdout.strip()[-600:]}") + logs.append(f"[2.14 guard release owncopy stress] {ok}/{GUARD_OWNCOPY_STRESS} runs passed, torn lines {torn}" + + ("".join("\n " + f for f in failed))) + if ok != GUARD_OWNCOPY_STRESS or torn: + raise SystemExit("\n".join(logs)) + + def sha256(path): with open(path, "rb") as f: return hashlib.sha256(f.read()).hexdigest() @@ -452,6 +524,12 @@ def main(): os.makedirs(sobj, exist_ok=True) sh(f'cl {CLFLAGS} {src("tests", "test_setupapi_identity.cpp")} {src("src", "setupapi_identity.cpp")} /Fo"{sobj}\\\\" ' f'/Fe"{sexe}"', core_dir) + # RR guard: the coexistence guard's pieces (safe reads, jump decoding, classification, one decision) + gexe = os.path.join(core_dir, "test_rr_guard.exe") + gobj = os.path.join(core_dir, "guard-obj") + os.makedirs(gobj, exist_ok=True) + sh(f'cl {CLFLAGS} {src("tests", "test_rr_guard.cpp")} {src("src", "rr_guard.cpp")} /Fo"{gobj}\\\\" /Fe"{gexe}"', + core_dir) pexe = os.path.join(core_dir, "test_probe_core.exe") pobj = os.path.join(core_dir, "probe-obj") os.makedirs(pobj, exist_ok=True) @@ -467,7 +545,7 @@ def main(): raise SystemExit(r.stderr) profiles = sorted(os.path.join(PROXY, "tests", "data", f) for f in os.listdir(os.path.join(PROXY, "tests", "data")) if f.endswith("-traffic.json")) - runs = [("core", [exe]), ("probe core", [pexe]), ("setupapi identity", [sexe]), + runs = [("core", [exe]), ("probe core", [pexe]), ("setupapi identity", [sexe]), ("rr guard", [gexe]), ("NGX provider", [nexe, os.path.join(PROXY, "tests", "data", "cp2077-2.14-rr-frames.json")])] + [(f"replay {os.path.basename(f)}", [rexe, f]) for f in profiles] for label, e in runs: r = subprocess.run(e, capture_output=True, text=True, timeout=300) diff --git a/clean/rr_f/proxy/tools/guard_modelm.py b/clean/rr_f/proxy/tools/guard_modelm.py new file mode 100644 index 00000000..429e6b4a --- /dev/null +++ b/clean/rr_f/proxy/tools/guard_modelm.py @@ -0,0 +1,106 @@ +# SPDX-License-Identifier: MIT +"""RR guard: Model M is not affected by WrongGPU RR's coexistence guard (CPU only). + + python clean/rr_f/proxy/tools/guard_modelm.py --fsr-build --rr-out + [--exclude REGEX] [--config Release] + +Runs every test of Model M's own ctest list (clean/fsr: WrongGPU.asi, the front end, the custom slot, the shared +settings), unchanged, once on its own and once per guard mode with WrongGPU RR loaded into the test process before +its main and the guard tripped (tests/guard_inject.cpp starts the program suspended and loads tests/guard_scene.cpp): +none (control: WrongGPU RR loaded, nothing tripped), off, take, owncopy, passthrough. Each guard mode must end exactly +as the control did (passed / skipped / failed), and the scene must have seen WrongGPU RR's line for that mode. A test +whose control differs from its plain run is listed as a note: that difference comes from WrongGPU RR being in the +process at all (e.g. a unit test that must create the process's shared settings block itself), not from the guard. +The stand-ins come from +build.py's guard stage of the 2.14 table (/2.14/hook-test/guard/stage). wronggpu-rr.ini (take) and +wronggpu-rr.log are written next to each test program and removed afterwards (only files this run created). Tests that +use a hardware GPU are excluded by default (fsr_overlay, fsr_dll_d3d12_*). +""" +import argparse +import json +import os +import re +import subprocess +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +import build # noqa: E402 + +MODES = ("none", "off", "take", "owncopy", "passthrough") + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--fsr-build", required=True) + ap.add_argument("--rr-out", default=build.DEFAULT_OUT) + ap.add_argument("--config", default="Release") + ap.add_argument("--exclude", default=r"^(fsr_overlay|fsr_dll_d3d12.*)$") + a = ap.parse_args() + hook_test = os.path.join(a.rr_out, "2.14", "hook-test") + stage = os.path.join(hook_test, "guard", "stage") + gen = os.path.join(hook_test, "gen") + if not os.path.isfile(os.path.join(stage, "wgtest_other_rr.dll")): + raise SystemExit(f"no guard stage in {stage}: run build.py first") + tools = os.path.join(a.rr_out, "guard-modelm") + os.makedirs(tools, exist_ok=True) + scene = os.path.join(tools, "guard_scene.dll") + inject = os.path.join(tools, "guard_inject.exe") + build.sh(f'cl {build.CLFLAGS} /LD /I"{gen}" {build.src("tests", "guard_scene.cpp")} /Fo"{tools}\\\\" /Fe"{scene}"', + tools) + build.sh(f'cl {build.CLFLAGS} {build.src("tests", "guard_inject.cpp")} /Fo"{tools}\\\\" /Fe"{inject}"', tools) + listing = build.sh(f'ctest --test-dir "{a.fsr_build}" -C {a.config} --show-only=json-v1', tools) + tests = json.loads(listing[listing.index("{"):])["tests"] + exclude = re.compile(a.exclude) + rows, failures, presence = [], 0, [] + for t in tests: + props = {p["name"]: p["value"] for p in t.get("properties", [])} + if exclude.search(t["name"]) or props.get("DISABLED") or "command" not in t: + continue + cmd, wd = t["command"], props.get("WORKING_DIRECTORY", os.path.dirname(t["command"][0])) + skip = int(props.get("SKIP_RETURN_CODE", -1)) if "SKIP_RETURN_CODE" in props else None + exe_dir = os.path.dirname(cmd[0]) + ini, log = os.path.join(exe_dir, "wronggpu-rr.ini"), os.path.join(exe_dir, "wronggpu-rr.log") + if os.path.exists(ini) or os.path.exists(log): + raise SystemExit(f"{exe_dir} already has wronggpu-rr.ini / wronggpu-rr.log: not touched, stopping") + + def outcome(rc): + return "skipped" if skip is not None and rc == skip else "passed" if rc == 0 else f"failed ({rc})" + + plain = subprocess.run(cmd, cwd=wd, capture_output=True, text=True, timeout=600) + row = [t["name"], outcome(plain.returncode)] + control = None # the "none" run: WrongGPU RR in the process, the guard not tripped + for mode in MODES: + if mode == "take": + with open(ini, "w") as f: + f.write("rr_other_plugin = take\n") + try: + r = subprocess.run([inject, scene, stage, mode] + cmd, cwd=wd, capture_output=True, text=True, timeout=600) + finally: + if os.path.exists(ini): + os.remove(ini) + got = outcome(r.returncode) + seen = f"guard_inject: ok {mode}" in r.stdout + if mode == "none": + control = got + if got != row[1]: # WrongGPU RR's presence itself, before any guard decision + presence.append((t["name"], row[1], got, (r.stdout + r.stderr).strip().splitlines()[-3:])) + # a guard mode must end exactly as the control does (the guard changes nothing for Model M) + same = got == control and seen + failures += not same + row.append(got if same else f"{got}{'' if seen else ', scene: ' + r.stderr.strip()[-200:]} <-- DIFFERS") + if os.path.exists(log): + os.remove(log) + rows.append(row) + print("test".ljust(34) + "plain".ljust(12) + "".join(m.ljust(14) for m in MODES)) + for row in rows: + print(row[0].ljust(34) + row[1].ljust(12) + "".join(c.ljust(14) for c in row[2:])) + print(f"{len(rows)} Model M test(s) x {len(MODES) - 1} guard mode(s) against the control: {failures} difference(s)") + for name, p, c, tail in presence: + print(f"note: {name}: {p} alone, {c} with WrongGPU RR in the process before any guard decision (control); " + f"the guard modes match the control. Last lines: {' | '.join(tail)}") + return 1 if failures else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/ci/run_proxy_core_tests.py b/tools/ci/run_proxy_core_tests.py index 20a22ff7..bf129741 100644 --- a/tools/ci/run_proxy_core_tests.py +++ b/tools/ci/run_proxy_core_tests.py @@ -18,7 +18,8 @@ def main(): data = os.path.join('clean', 'rr_f', 'proxy', 'tests', 'data') runs = [('core', [os.path.join(core, 'test_proxy_core.exe')]), ('probe core', [os.path.join(core, 'test_probe_core.exe')]), - ('setupapi identity', [os.path.join(core, 'test_setupapi_identity.exe')])] + ('setupapi identity', [os.path.join(core, 'test_setupapi_identity.exe')]), + ('rr guard', [os.path.join(core, 'test_rr_guard.exe')])] runs += [('RR provider ' + os.path.basename(f), [os.path.join(core, 'test_ngx_rr.exe'), f]) for f in sorted(glob.glob(os.path.join(data, '*-rr-frames.json')))] runs += [('replay ' + os.path.basename(f), [os.path.join(core, 'test_replay_profile.exe'), f]) From 44db7ed3fa1cc7968f6835ed16af94034d233e53 Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:55:45 -0500 Subject: [PATCH 2/4] RR plugin guard: switch off only on a positive finding; review fixes Review of the RR plugin guard, done in this commit: - Only a positive finding switches WrongGPU RR off: an address that ends in another named module (directly or through decoded hook jumps), or in a second copy of WrongGPU RR. Unreadable memory, code outside every module that does not jump on, the exe's own code and a jump chain longer than the hop limit are now inconclusive: counted, logged once with a "hook: coexistence check ...: inconclusive" line, and RR stays active. Execute-only pages count as readable for the code read (the copy is still guarded by the structured-exception handler). - The module holding the host's API table counts as the host too. When a separate loader called InitializeASI and the load check took the real host's own patches for another plugin, OptiPluginInit runs the load check again with that module as the host (nothing was patched before). New test mode hostsplit: a separate DLL calls InitializeASI. - The two-copies log test now makes every copy log at once: four more copies run InitializeASI / OptiPluginInit from threads while 16 game threads make the first call; no line may be torn. - The exit summary at DLL_PROCESS_DETACH only tries the log's process-wide lock (no wait under the loader lock); the comment says so. - A second copy of WrongGPU RR writes no exit summary. - The hook build's probe log starts a new empty file also when the old one could not be moved aside. - The hop limit and the docs agree: at most 4 hook jumps are followed, a fifth is too many (tested both ways). - g_take, the host modules and the pass-through targets are atomics. - The off modes check that the RR runtime is not loaded (and the clean mode that it is). - HOOK-MODE.md: what counts as a finding, the inconclusive cases, the known fail-open cases, the new log line and test modes. - Removed the Model M guard tools (tests/guard_inject.cpp, tests/guard_scene.cpp, tools/guard_modelm.py) and every reference. - The file-proxy build's log change (proxy_dll.cpp) is taken out of this pull request; it is not needed by the guard. Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> --- clean/rr_f/proxy/HOOK-MODE.md | 102 ++++++---- clean/rr_f/proxy/src/hook_dll.cpp | 106 ++++++++--- clean/rr_f/proxy/src/proxy_dll.cpp | 30 +-- clean/rr_f/proxy/src/rr_guard.cpp | 55 ++++-- clean/rr_f/proxy/src/rr_guard.h | 54 ++++-- clean/rr_f/proxy/tests/fake_other_rr.cpp | 19 ++ clean/rr_f/proxy/tests/guard_inject.cpp | 80 -------- clean/rr_f/proxy/tests/guard_scene.cpp | 137 -------------- clean/rr_f/proxy/tests/test_rr_guard.cpp | 112 +++++++++-- clean/rr_f/proxy/tests/test_rr_guard_dll.cpp | 188 ++++++++++++++++--- clean/rr_f/proxy/tools/build.py | 14 +- clean/rr_f/proxy/tools/guard_modelm.py | 106 ----------- 12 files changed, 525 insertions(+), 478 deletions(-) delete mode 100644 clean/rr_f/proxy/tests/guard_inject.cpp delete mode 100644 clean/rr_f/proxy/tests/guard_scene.cpp delete mode 100644 clean/rr_f/proxy/tools/guard_modelm.py diff --git a/clean/rr_f/proxy/HOOK-MODE.md b/clean/rr_f/proxy/HOOK-MODE.md index 41227b1e..afd4d9ad 100644 --- a/clean/rr_f/proxy/HOOK-MODE.md +++ b/clean/rr_f/proxy/HOOK-MODE.md @@ -118,24 +118,31 @@ the display adapter's PCI identity through SetupAPI as well as DXGI; with the ho ## Another Ray Reconstruction plugin (0.6.1) A player can end up with two RR plugins in one game (an integrator's installer may put this plugin next to another -one; the launcher is not involved then). Default: **WrongGPU RR stays off and says so in one line**; Model M is not -touched. The guard is generic and read-only (`src/rr_guard.{h,cpp}`, wired in `src/hook_dll.cpp`): it looks at where -the game's RR calls lead, never at another plugin's files or internals. Release and probe builds behave the same. +one; the launcher is not involved then). Default: **when another RR plugin is positively found, WrongGPU RR stays off +and says so in one line**; Model M is not touched. The guard is generic and read-only (`src/rr_guard.{h,cpp}`, wired in +`src/hook_dll.cpp`): it looks at where the game's RR calls lead, never at another plugin's files or internals. Release +and probe builds behave the same. + +**What counts as a finding.** Only a positive sign stops the plugin: an address that ends in **another named module** +(directly, or through decoded hook jumps), or in **a second copy of WrongGPU RR**. Anything the scan cannot explain is +**not** a sign of another plugin: it is logged once as inconclusive (see "Log lines") and WrongGPU RR **stays active**. **Signals, most reliable first** (each address is classified: this module, the game interface, the host = the module -that called `InitializeASI`, a copy of WrongGPU RR, another WrongGPU module, the exe, code outside every module, another -module; hook jumps are followed out of the interface and out of anonymous memory, up to 4): +that called `InitializeASI` and the module holding the host's API table, a copy of WrongGPU RR, another WrongGPU module, +the exe, code outside every module, another module; hook jumps are followed out of the interface and out of anonymous +memory, at most 4 of them per address; a fifth is "too many hops", inconclusive): 1. **A second copy of WrongGPU RR** (`S0`): a process-wide marker (`Local\WrongGPU.rr-active.v1.`, holding the active copy's path) taken at `InitializeASI`; a copy that finds it taken starts nothing (no hook, routes, NGX provider, menu box, SetupAPI shim). A slot or export that leads into a module counting as WrongGPU RR (below) is the same case. 2. **Import slots** (`S1`): before anything is patched, every loaded module's import slots of the game interface for - the roles this build would patch (and the exe's delay-load slots) must lead into the interface (a delay slot not - bound yet: the exe's own thunk; the host is accepted too). -3. **The RR exports' first bytes** (`S2`): the exports of is-supported, get-function, allocate and evaluate must not - jump out of the interface into another module (`jmp rel32/rel8`, `jmp [rip+disp32]`, `mov rax|r11, imm64; jmp reg`; - a `jmp [rip]` through the interface's own import table is its own code). The init export is not read: the host - patches it itself. + the roles this build would patch (and the exe's delay-load slots) are read. A slot that leads into another named + module is a finding; a slot that leads into the interface, the host, another WrongGPU module (or, for a delay slot + not bound yet, the exe's own thunk) is fine; any other slot is inconclusive. +3. **The RR exports' first bytes** (`S2`): the exports of is-supported, get-function, allocate and evaluate are read: + a jump out of the interface that ends in another named module is a finding (`jmp rel32/rel8`, `jmp [rip+disp32]`, + `mov rax|r11, imm64; jmp reg`; a `jmp [rip]` through the interface's own import table is its own code). The init + export is not read: the host patches it itself. 4. **Host routes** (plugin interface 3): `S2` on the module the host hooked (the host's trampolines, code outside every module, are accepted there), then each route's next function (the host's `next`) after registering: another plugin's route under ours leads to that plugin. Our routes cannot be taken back: they pass every call on. @@ -151,15 +158,35 @@ Ours first: found at `OptiPluginInit` or the game's first call; pass-through fro RR instance exists). Both late (run-time interface): the host-route checks above. The SetupAPI identity shim (not part of the RR path) runs as configured while WrongGPU RR stays off because of another plugin; a second copy starts nothing. -**Never a crash, and the safe side.** Every read of memory we do not own (slot values, export bytes, jump cells, the -host's next pointers, the module headers the scan walks) goes through `rr_guard`'s safe read: `VirtualQuery` for -committed, readable, non-guard pages, then a structured-exception-guarded copy (a cached region is re-checked by the -exception guard). A failed read is **unknown**, and unknown counts as another plugin (stays off, with the line). - -**False positives, known and accepted.** A mod that is not an RR plugin but hooks the interface's RR functions (for -example a frame-generation mod working through the same functions) makes WrongGPU RR stay off too: the line names its -module and `rr_other_plugin=take` puts WrongGPU RR back. Not triggers: the game's own RR (the calls lead into the -interface), the host's own init patch, WrongGPU.asi, a second copy of WrongGPU RR (its own line). +**Never a crash, and a positive finding only.** Every read of memory we do not own (slot values, export bytes, jump +cells, the host's next pointers, the module headers the scan walks) goes through `rr_guard`'s safe read: `VirtualQuery` +for committed, readable, non-guard pages (execute-only pages count as readable: code is read from them), then a +structured-exception-guarded copy (a cached region is re-checked by the exception guard). A failed read is **unknown**. +Unknown is not a finding. Only the positive findings above stop the plugin. These are **inconclusive**: they are +counted, one diagnostic line names the first of them, and WrongGPU RR stays active: +- memory that cannot be read (an import slot, an export, a jump cell, a PAGE_NOACCESS or guard page, a null pointer); +- a jump chain longer than 4 hops; +- code outside every module that does not jump on (a game's copy protection or a hooking library's trampoline may sit + there); +- a slot or export that leads into the exe's own code (a delay-load helper's thunk, or a game's own wrapper). + +**Fail-open cases (known).** The guard does not see these, so WrongGPU RR stays active next to such a plugin: a plugin +hooks after the game's first call (the late check runs at `OptiPluginInit` and once, at the first call, and never +again); inline hooks in forms other than the jump forms above (for example a hook placed deeper than the first bytes of +the export, or through a different instruction sequence); a plugin that hooks the function pointers the game-interface's +get-function export returns. In these cases the other plugin and WrongGPU RR may both answer RR and the log shows no +finding; remove the other plugin. + +**False positives, known and accepted.** A mod that is not an RR plugin but hooks the interface's RR functions so that +its code lives in a named module (for example a frame-generation mod working through the same functions) makes WrongGPU +RR stay off too: the line names its module and `rr_other_plugin=take` puts WrongGPU RR back. Not triggers: the game's +own RR (the calls lead into the interface), the host's own init patch, WrongGPU.asi, a second copy of WrongGPU RR (its +own line). The host is the module that called `InitializeASI` and also the module holding the host's API table +(`OptiPluginInit`): with a separate ASI loader the host's own patches look like another plugin at the load check, which +runs before the table is known. When `OptiPluginInit` then shows that the module named at load holds the host's table, a +`the module the load check took for another Ray Reconstruction plugin (...) holds the host's API table` line follows and +the load check runs again with that module as the host (nothing was patched before); the earlier "stays off" line stays +in the log. **Override** (`wronggpu-rr.ini` next to the game exe): `rr_other_plugin = off` (default; also any unknown value, with a line) or `take`. `take` with a plugin found at load: WrongGPU RR patches on top, answers the RR calls itself and @@ -182,20 +209,27 @@ matches the **beginnings** of the first three; keep them exactly: - `a plugin loaded after WrongGPU replaced its hooks; rr_other_plugin=take cannot be applied: WrongGPU RR stays off and passes every call on unchanged (); move it aside to use WrongGPU RR` - with take, found at load (RR is on): `another Ray Reconstruction plugin is active; rr_other_plugin=take: WrongGPU RR goes in front of it (; it gets the game's other calls, no RR work)` -`` names the place and the module file, e.g. `the import slot of Game.exe leads to Other.asi`, `the -export of leads to Other.asi (through 2 hook jumps)`, `... could not be read`, `... leads to -code outside every module`. Diagnostics (not matched): `hook: coexistence check at load: ( address(es) read -in ms)` once per run (with its measured cost), `hook: coexistence re-check at : ...`, -`NGX: RR provider not registered: WrongGPU RR stays off in this process (see the line above)`. - -**Tests** (CPU only): `tests/test_rr_guard.cpp` (safe reads on PAGE_NOACCESS, reserved and guard pages and a page made -unreadable after caching; every jump form; synthetic modules; 32 threads at one decision); `tests/test_rr_guard_dll.cpp` -with our own stand-in other plugin `tests/fake_other_rr.cpp` (modes clean, first, inline, relay, anon, noaccess, -guardpage, late, late-replace, provider, owncopy, route, route-other, route-inline; `--take`; 16 threads at the first call), -for every interface version, release and probe (build.py); the existing hook runs check that no guard line appears. -`tools/guard_modelm.py` runs Model M's own ctest list unchanged with WrongGPU RR loaded into each test process before -its main and the guard tripped (none / off / take / owncopy / passthrough; `tests/guard_inject.cpp`, -`tests/guard_scene.cpp`). +`` names the place and the module file of a positive finding, e.g. `the import slot of Game.exe leads to +Other.asi`, `the export of leads to Other.asi (through 2 hook jumps)`. Diagnostics (not +matched): `hook: coexistence check at load: ( address(es) read in ms)` once per run (with its measured +cost), `hook: coexistence re-check at : ...`, `NGX: RR provider not registered: WrongGPU RR stays off in this +process (see the line above)`, and the stay-on line `hook: coexistence check : inconclusive for address(es) +(first: could not be read | leads to code outside every module | leads into the exe's own code | leads through +more than 4 hook jumps); no other plugin was positively found, WrongGPU RR stays active` (it starts with `hook: `, never +with a matched beginning above). + +**Tests** (CPU only): `tests/test_rr_guard.cpp` (safe reads on PAGE_NOACCESS, reserved, guard and execute-only pages and a +page made unreadable after caching; every jump form; synthetic modules; exactly 4 hops followed and a fifth one too +many; which classifications are findings and which are inconclusive; 32 threads at one decision); +`tests/test_rr_guard_dll.cpp` with our own stand-in other plugin `tests/fake_other_rr.cpp` (modes clean, first, inline, +relay, execonly, anon, noaccess, guardpage, exe, hops, hostsplit, late, late-replace, provider, owncopy, route, +route-other, route-inline; `--take`; 16 threads at the first call): the foreign-module modes switch off (release: the +RR runtime is then not loaded; in clean it is); anon, noaccess, +guardpage, exe and hops log the inconclusive line and stay active; hostsplit has a separate loader DLL call +`InitializeASI` while the real host's DLL holds the API table; owncopy loads four more copies and runs their +`InitializeASI` / `OptiPluginInit` from threads while 16 game threads make the first call, then checks that no line is +torn and that freeing an inactive copy writes no exit summary; build.py repeats owncopy 200 times. Run for every interface +version, release and probe (build.py); the existing hook runs check that no guard line appears. ## Unload diff --git a/clean/rr_f/proxy/src/hook_dll.cpp b/clean/rr_f/proxy/src/hook_dll.cpp index ddeb8fac..5313b19b 100644 --- a/clean/rr_f/proxy/src/hook_dll.cpp +++ b/clean/rr_f/proxy/src/hook_dll.cpp @@ -143,11 +143,22 @@ std::atomic g_host_api_plugin{nullptr}; std::mutex g_host_restore_mutex; // RR guard (rr_guard.h): the guard's state for this process, the override, and the pass-through targets wgrr::guard::Decision g_guard; -bool g_take = false; // wronggpu-rr.ini rr_other_plugin=take +// g_take, g_host_module, g_host_api_module and g_fwd are written on the host's callback thread (OptiPluginInit, the +// host's hook callback) and read by the game's threads (the handlers, the late check): atomics, published with release +std::atomic g_take{false}; // wronggpu-rr.ini rr_other_plugin=take std::atomic g_hook_done{false}; // our handlers are installed: the late check may run -HMODULE g_host_module = nullptr; // the module that called InitializeASI (the host) +std::atomic g_host_module{nullptr}; // the module that called InitializeASI (taken as the host) +std::atomic g_host_api_module{nullptr}; // the module holding the host's API table (when another module) +// the module the first positive finding of a "stays off" load decision led to: when OptiPluginInit then shows that this +// module holds the host's API table (a separate loader called InitializeASI, and the real host's own patches were taken +// for another plugin), the load decision runs again with it as the host (see OptiPluginInit) +std::atomic g_load_off_module{nullptr}; +std::atomic g_load_rerun_done{false}; +// g_prev is written once by guard_at_load on the thread that then builds the core (do_hook): no other thread reads it +// before the core exists (bind() runs inside the core's construction), so it stays a plain array void* g_prev[32] = {}; // take: what the exe's import slots held before us (the other plugin), by role -wgrr::OriginalApi g_fwd; // where a passing handler sends the call (the genuine export or the host's next) +// where a passing handler sends the call (the genuine export or the host's next): an immutable snapshot, replaced whole +std::atomic g_fwd{nullptr}; HANDLE g_marker = nullptr; // the process-wide marker of the active WrongGPU RR copy (held for the run) #if WG_RR_PROBE wgrr::RrProbe* g_probe = nullptr; @@ -195,6 +206,10 @@ wgrr::ProbeLog* probe_log() { { const wgrr::LogLock shared(path, wgrr::kLogLockWaitMs); MoveFileExW(path.c_str(), prev.c_str(), MOVEFILE_REPLACE_EXISTING); + // a new, empty log (as proxy_dll.cpp does), also when the old one could not be moved aside: never append to it + HANDLE fresh = CreateFileW(path.c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (fresh != INVALID_HANDLE_VALUE) CloseHandle(fresh); } // RR guard, 0.6.1: a second WrongGPU RR copy appends its line to this file too: every line is one append // call under the log's process-wide lock (log_append.h), so neither copy's line is torn or overwritten @@ -331,7 +346,7 @@ void bind(F& slot, int role) { slot = reinterpret_cast(g_route_next[role]); // host route: continue through the host's chain return; } - if (g_take && g_prev[role]) { // RR guard, take: continue through the other plugin (it sees no RR work) + if (g_take.load() && g_prev[role]) { // RR guard, take: continue through the other plugin (it sees no RR work) slot = reinterpret_cast(g_prev[role]); return; } @@ -715,8 +730,14 @@ bool guard_pass() { if (!g_guard.frozen() && g_hook_done.load(std::memory_order_acquire)) guard_first_call(); return !g_guard.active(); } -#define WG_PASS(field, ...) \ - if (guard_pass()) return g_fwd.field ? g_fwd.field(__VA_ARGS__) : WG_E_MISSING_OR_INVALID_API +// publishes the pass-through targets (an immutable snapshot; a replaced one is leaked: a handful per run at most) +void set_fwd(const wgrr::OriginalApi& o) { g_fwd.store(new wgrr::OriginalApi(o), std::memory_order_release); } +#define WG_PASS(field, ...) \ + if (guard_pass()) { \ + const wgrr::OriginalApi* fwd_ = g_fwd.load(std::memory_order_acquire); \ + return fwd_ && fwd_->field ? fwd_->field(__VA_ARGS__) : WG_E_MISSING_OR_INVALID_API; \ + } \ + (void)0 } // namespace @@ -1224,10 +1245,21 @@ bool guard_claim_marker() { void guard_read_override() { ensure_settings(); std::string note; - g_take = wgrr::guard::override_take(g_settings.text(wgrr::guard::kOverrideKey), ¬e); + g_take.store(wgrr::guard::override_take(g_settings.text(wgrr::guard::kOverrideKey), ¬e)); if (!note.empty()) log_line("hook: " + note); } +// The guard's view of the process: the module that called InitializeASI and the one holding the host's API table are +// both the host (a separate ASI loader may be the first, OptiScaler the second). +wgrr::guard::Env guard_env(const void* iface) { + return wgrr::guard::process_env(g_self, iface, g_host_module.load(), g_host_api_module.load()); +} + +// One diagnostic line when a scan could not explain some addresses (never a finding: RR stays active) +void guard_log_unclear(const char* when, const wgrr::guard::Verdict& v) { + if (v.unclear) log_line(wgrr::guard::line_inconclusive(when, v.unclear, v.unclear_detail)); +} + // S2: the first bytes of the interface's RR-deciding exports (module = the interface). anon_ok: code outside every module // is accepted (host-route mode: the host's own trampolines). void guard_scan_exports(HMODULE module, const wgrr::guard::Env& env, bool anon_ok, wgrr::guard::Verdict* v) { @@ -1248,7 +1280,7 @@ bool guard_at_load(const IMAGE_DELAYLOAD_DESCRIPTOR* delay) { guard_read_override(); LARGE_INTEGER t0; QueryPerformanceCounter(&t0); - const g::Env env = g::process_env(g_self, g_interposer, g_host_module); + const g::Env env = guard_env(g_interposer); g::Reader r; g::Verdict v; std::wstring leaf_w; @@ -1296,13 +1328,15 @@ bool guard_at_load(const IMAGE_DELAYLOAD_DESCRIPTOR* delay) { : "another Ray Reconstruction plugin found"; log_line("hook: coexistence check at load: " + std::string(result) + " (" + std::to_string(v.reads) + " address(es) read in " + ms_text(ms) + ")"); + guard_log_unclear("at load", v); if (v.kind == g::Verdict::kOwnCopy) { g_guard.set(g::State::kOwnCopy); log_line(g::line_own_copy(v.detail, ascii(narrow(own_path())))); return false; } if (v.kind == g::Verdict::kOther) { - if (!g_take) { + if (!g_take.load()) { + g_load_off_module.store(v.other_module); // OptiPluginInit may find that this module is the host (see there) g_guard.set(g::State::kOff); log_line(g::line_other(v.detail)); return false; @@ -1323,7 +1357,7 @@ wgrr::guard::State guard_late(const char* why, bool log_clean) { if (s != g::State::kActive && s != g::State::kTaken) return s; LARGE_INTEGER t0; QueryPerformanceCounter(&t0); - const g::Env env = g::process_env(g_self, g_interposer, g_host_module); + const g::Env env = guard_env(g_interposer); g::Verdict v; { std::lock_guard lock(g_watch_mutex); @@ -1345,13 +1379,14 @@ wgrr::guard::State guard_late(const char* why, bool log_clean) { if (log_clean) log_line(std::string("hook: coexistence re-check at ") + why + ": no other Ray Reconstruction plugin found (" + std::to_string(v.reads) + " address(es) read in " + ms_text(ms) + ")"); + guard_log_unclear((std::string("re-check at ") + why).c_str(), v); return s; } log_line(std::string("hook: coexistence re-check at ") + why + ": " + (v.kind == g::Verdict::kOwnCopy ? "a second copy of WrongGPU RR" : "another Ray Reconstruction plugin") + " took the RR calls after WrongGPU (" + std::to_string(v.reads) + " address(es) read in " + ms_text(ms) + ")"); if (v.kind == g::Verdict::kOwnCopy) log_line(g::line_own_copy(v.detail, ascii(narrow(own_path())))); - else log_line(g_take ? g::line_cannot_take(v.detail) : g::line_other_later(v.detail)); + else log_line(g_take.load() ? g::line_cannot_take(v.detail) : g::line_other_later(v.detail)); return g::State::kPassThrough; } @@ -1400,7 +1435,7 @@ void do_hook() { // RR guard: another RR plugin already holding these calls keeps WrongGPU RR off (nothing built or patched) if (!guard_at_load(delay)) return; - g_fwd = bind_original(); // where a passing handler sends a call (the late decision, guard_first_call) + set_fwd(bind_original()); // where a passing handler sends a call (the late decision, guard_first_call) // Build the core now, so our handlers forward to the genuine exports (the IAT's pre-patch addresses). (void)target(); @@ -1492,16 +1527,17 @@ void on_host_hooked(void* module, uint32_t major, uint32_t minor, uint32_t patch LARGE_INTEGER t0; QueryPerformanceCounter(&t0); g::Verdict v; - guard_scan_exports(static_cast(module), g::process_env(g_self, module, g_host_module), true, &v); + guard_scan_exports(static_cast(module), guard_env(module), true, &v); log_line(std::string("hook: coexistence check before the host routes: ") + (v.kind == g::Verdict::kClean ? "no other Ray Reconstruction plugin found" : "another plugin found") + " (" + std::to_string(v.reads) + " address(es) read in " + ms_text(ms_since(t0)) + ")"); + guard_log_unclear("before the host routes", v); if (v.kind == g::Verdict::kOwnCopy) { g_guard.set(g::State::kOwnCopy); log_line(g::line_own_copy(v.detail, ascii(narrow(own_path())))); return; } - if (v.kind == g::Verdict::kOther && !g_take) { + if (v.kind == g::Verdict::kOther && !g_take.load()) { g_guard.set(g::State::kOff); log_line(g::line_other(v.detail)); return; @@ -1533,7 +1569,7 @@ void on_host_hooked(void* module, uint32_t major, uint32_t minor, uint32_t patch { LARGE_INTEGER t0; QueryPerformanceCounter(&t0); - const g::Env env = g::process_env(g_self, module, g_host_module); + const g::Env env = guard_env(module); g::Verdict v; for (const WgHostSlRoute& r : routes) if (*r.next) v.add(g::classify(*r.next, env, false), std::string("the host's next function of ") + r.export_name, @@ -1541,9 +1577,10 @@ void on_host_hooked(void* module, uint32_t major, uint32_t minor, uint32_t patch log_line(std::string("hook: coexistence check of the host routes: ") + (v.kind == g::Verdict::kClean ? "no other Ray Reconstruction plugin found" : "another plugin found") + " (" + std::to_string(v.reads) + " address(es) read in " + ms_text(ms_since(t0)) + ")"); - g_fwd = bind_original(); // the host's next functions + guard_log_unclear("of the host routes", v); + set_fwd(bind_original()); // the host's next functions if (v.kind != g::Verdict::kClean) { - if (v.kind == g::Verdict::kOther && g_take) { + if (v.kind == g::Verdict::kOther && g_take.load()) { g_guard.set(g::State::kTaken); log_line(g::line_take(v.detail)); } else { @@ -1923,7 +1960,7 @@ extern "C" __declspec(dllexport) void InitializeASI() { HMODULE host = nullptr; if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, static_cast(caller), &host) && host != g_self) - g_host_module = host; + g_host_module.store(host); if (!guard_claim_marker()) return; // a second copy of WrongGPU RR: nothing of this copy starts (one line) #if !WG_RR_PROBE // RR runs while the core accepted an evaluate within the last second @@ -1949,11 +1986,23 @@ extern "C" __declspec(dllexport) void InitializeASI() { extern "C" __declspec(dllexport) bool OptiPluginInit(const WgHostMenuApi* api, WgHostMenuPlugin* plugin) { // RR guard: a second copy of WrongGPU RR registers nothing (no second tab, routes or provider) if (g_guard.state() == wgrr::guard::State::kOwnCopy) return false; - if (!g_host_module && api) { // the host, when InitializeASI could not tell: the module holding its table + if (api) { // the module holding the host's table is the host as well (a separate ASI loader may have called InitializeASI) HMODULE host = nullptr; if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, - reinterpret_cast(api), &host) && host != g_self) - g_host_module = host; + reinterpret_cast(api), &host) && host && host != g_self && + host != g_host_module.load()) { + g_host_api_module.store(host); + // The load decision took this very module for another plugin (it ran before the host's table was known): it is + // the host; its own patches are not a second plugin. Nothing was patched then, so the load decision runs again. + if (g_guard.state() == wgrr::guard::State::kOff && host == g_load_off_module.load() && + !g_load_rerun_done.exchange(true)) { + log_line("hook: the module the load check took for another Ray Reconstruction plugin (" + leaf_text(host) + + ") holds the host's API table: it is the host (a separate loader called InitializeASI); the load " + "check runs again with it as the host"); + g_guard.set(wgrr::guard::State::kActive); + do_hook(); + } + } } // a plugin that took the RR calls after our InitializeASI (a non-freezing check; the game's first call decides last) if (g_hook_done.load(std::memory_order_acquire)) @@ -1975,10 +2024,15 @@ extern "C" __declspec(dllexport) bool OptiPluginInit(const WgHostMenuApi* api, W #if !WG_RR_PROBE namespace { -// clean/rr-sl-diag: the call summary at process exit (or unload). Other threads may be gone while holding the log's or the -// proxy's lock, so neither is taken: the counters are atomic and the line is appended with WriteFile. +// clean/rr-sl-diag: the call summary at process exit (or unload). This runs at DLL_PROCESS_DETACH, under the loader lock, +// and other threads may be gone while holding the log's in-process mutex or the proxy's lock: neither is taken, the +// counters are atomic, and the line is appended with one WriteFile. The log's process-wide named mutex is only tried +// (no wait, see the end): a copy stuck holding it must never hold up the process exit. void exit_summary() { if (!g_log_path[0]) return; // nothing was logged in this process + // a second copy of WrongGPU RR (it stays off) has no calls to summarise: the "never reached the plugin" line would + // mislead (the active copy writes its own summary) + if (g_guard.state() == wgrr::guard::State::kOwnCopy) return; std::string line = g_proxy ? g_proxy->diag_summary("process exit") : std::string("diag: summary (process exit): the game interface's calls never reached the plugin"); // clean/rr-sl-diag 2: the calls that reached each handler, the NGX route's calls, the slot checks done @@ -2022,9 +2076,9 @@ void exit_summary() { "remove it for Ray Reconstruction\r\n"; } } - // 0.6.1: under the log's process-wide lock (a short bounded wait: this can run while the process unloads us), one - // append call either way (log_append.h) - const wgrr::LogLock shared(g_log_path, 500); + // 0.6.1: the log's process-wide lock is tried with no wait (loader lock held here: waiting could deadlock or stall the + // exit); one append call either way (log_append.h), so the line is whole even when the lock was not ours + const wgrr::LogLock shared(g_log_path, 0); wgrr::append_log_text(g_log_path, line, OPEN_EXISTING); } } // namespace diff --git a/clean/rr_f/proxy/src/proxy_dll.cpp b/clean/rr_f/proxy/src/proxy_dll.cpp index 4bf7751c..f0a0b992 100644 --- a/clean/rr_f/proxy/src/proxy_dll.cpp +++ b/clean/rr_f/proxy/src/proxy_dll.cpp @@ -26,7 +26,6 @@ #include #include -#include "log_append.h" #include "proxy_core.h" #include "rr_enabled.h" #include "settings.h" @@ -60,7 +59,7 @@ std::mutex g_log_mutex; wgrr::RrProbe* g_probe = nullptr; wgrr::ProbeLog* g_probe_log = nullptr; std::once_flag g_probe_log_once; -std::wstring g_probe_path; // wronggpu-rr-probe.log (0.6.1: one append call per line, log_append.h) +FILE* g_probe_file = nullptr; #else wgrr::RrProxy* g_proxy = nullptr; #endif @@ -108,19 +107,16 @@ wgrr::ProbeLog* probe_log() { std::call_once(g_probe_log_once, [] { std::wstring path = own_dir() + L"wronggpu-rr-probe.log"; std::wstring prev = own_dir() + L"wronggpu-rr-probe.prev.log"; - { - const wgrr::LogLock shared(path, wgrr::kLogLockWaitMs); - MoveFileExW(path.c_str(), prev.c_str(), MOVEFILE_REPLACE_EXISTING); - // a new, empty log (as the earlier "wb" open did, also when the old one could not be moved aside) - HANDLE fresh = CreateFileW(path.c_str(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr, - CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); - if (fresh != INVALID_HANDLE_VALUE) CloseHandle(fresh); - } - g_probe_path = path; // 0.6.1: one append call per line under the log's process-wide lock (log_append.h) + MoveFileExW(path.c_str(), prev.c_str(), MOVEFILE_REPLACE_EXISTING); + g_probe_file = _wfopen(path.c_str(), L"wb"); g_probe_log = new wgrr::ProbeLog([](const std::string& line) { std::lock_guard lock(g_log_mutex); - const wgrr::LogLock shared(g_probe_path, wgrr::kLogLockWaitMs); - wgrr::append_log_text(g_probe_path, wgrr::log_stamp() + line + "\r\n"); // on disk at once: a crash keeps it + if (!g_probe_file) return; + SYSTEMTIME t; + GetLocalTime(&t); + fprintf(g_probe_file, "%02u:%02u:%02u.%03u %s\r\n", t.wHour, t.wMinute, t.wSecond, t.wMilliseconds, + line.c_str()); + fflush(g_probe_file); // a crash keeps everything logged so far }); g_probe_log->note(std::string("probe start: build Streamline 2.") + std::to_string(WG_BINDING_API_MINOR) + ", loaded as " + narrow(own_stem()) + ", process " + std::to_string(GetCurrentProcessId())); @@ -135,8 +131,12 @@ void log_line(const std::string& s) { #else std::lock_guard lock(g_log_mutex); std::wstring path = own_dir() + L"wronggpu-rr.log"; - const wgrr::LogLock shared(path, wgrr::kLogLockWaitMs); // 0.6.1: one append call under the process-wide lock - wgrr::append_log_text(path, wgrr::log_stamp() + s + "\r\n"); + FILE* f = _wfopen(path.c_str(), L"ab"); + if (!f) return; + SYSTEMTIME t; + GetLocalTime(&t); + fprintf(f, "%02u:%02u:%02u.%03u %s\r\n", t.wHour, t.wMinute, t.wSecond, t.wMilliseconds, s.c_str()); + fclose(f); #endif } diff --git a/clean/rr_f/proxy/src/rr_guard.cpp b/clean/rr_f/proxy/src/rr_guard.cpp index 46832d80..0f46e5fd 100644 --- a/clean/rr_f/proxy/src/rr_guard.cpp +++ b/clean/rr_f/proxy/src/rr_guard.cpp @@ -21,7 +21,8 @@ bool readable(const void* p, size_t n) { if (m.State != MEM_COMMIT) return false; const DWORD pr = m.Protect; if (pr & (PAGE_GUARD | PAGE_NOACCESS)) return false; - if (!(pr & (PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | + // PAGE_EXECUTE counts: a hooking library's trampolines may be execute-only, and the copy that follows is guarded + if (!(pr & (PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY))) return false; const uintptr_t next = reinterpret_cast(m.BaseAddress) + m.RegionSize; @@ -131,7 +132,7 @@ bool decode_jump(const uint8_t* c, size_t n, const uint8_t* at, const void** tar const char* owner_word(Owner o) { switch (o) { - case Owner::kUnknown: return "unknown (not readable)"; + case Owner::kUnknown: return "unknown (not readable, or too many hook jumps)"; case Owner::kSelf: return "WrongGPU RR (this copy)"; case Owner::kInterface: return "the game interface"; case Owner::kHost: return "the host"; @@ -147,15 +148,27 @@ const char* owner_word(Owner o) { Where classify(const void* p, const Env& env, bool follow_iface) { Where w; const void* cur = p; + // follows one hook jump to `target`; false (kUnknown, too_many_hops) when kMaxHops jumps were followed already + auto follow = [&](const void* target) { + if (w.hops >= kMaxHops) { + w.owner = Owner::kUnknown; + w.too_many_hops = true; + return false; + } + cur = target; + ++w.hops; + return true; + }; for (;;) { - if (!cur || w.hops > kMaxHops) { + if (!cur) { w.owner = Owner::kUnknown; return w; } const void* m = env.module_of ? env.module_of(cur) : nullptr; w.module = m && env.name_of ? env.name_of(m) : std::string(); + w.module_handle = m; if (m && m == env.self) { w.owner = Owner::kSelf; return w; } - if (m && m == env.host) { w.owner = Owner::kHost; return w; } + if (m && (m == env.host || (env.host_alt && m == env.host_alt))) { w.owner = Owner::kHost; return w; } if (m && m == env.iface) { if (!follow_iface || w.hops != 0) { w.owner = Owner::kInterface; return w; } uint8_t code[16]; @@ -173,8 +186,7 @@ Where classify(const void* p, const Env& env, bool follow_iface) { const uint8_t* c8 = static_cast(cell); if (c8 && c8 >= env.iface_iat_begin && c8 < env.iface_iat_end) { w.owner = Owner::kInterface; return w; } if (env.module_of && env.module_of(target) == env.iface) { w.owner = Owner::kInterface; return w; } - cur = target; - ++w.hops; + if (!follow(target)) return w; continue; } if (m) { @@ -194,8 +206,7 @@ Where classify(const void* p, const Env& env, bool follow_iface) { w.owner = (got >= r + 6 && code[r] == 0xFF && code[r + 1] == 0x25) ? Owner::kUnknown : Owner::kAnonymous; return w; } - cur = target; - ++w.hops; + if (!follow(target)) return w; } } @@ -218,11 +229,22 @@ void Verdict::add(const Where& w, const std::string& what, bool anon_ok, bool ex detail = w.module; return; } - if (kind == kOther || trusted(w.owner, anon_ok, exe_ok)) return; - kind = kOther; - if (w.owner == Owner::kUnknown) detail = what + " could not be read" + via; - else if (w.owner == Owner::kAnonymous) detail = what + " leads to code outside every module" + via; - else detail = what + " leads to " + (w.module.empty() ? std::string("another module") : w.module) + via; + if (trusted(w.owner, anon_ok, exe_ok)) return; + if (w.owner == Owner::kForeign) { // the one positive sign of another plugin: a named module that is not ours + if (kind == kOther) return; + kind = kOther; + other_module = w.module_handle; + detail = what + " leads to " + (w.module.empty() ? std::string("another module") : w.module) + via; + return; + } + // not a sign of another plugin: counted, the first one named for the log + ++unclear; + if (unclear > 1) return; + if (w.owner == Owner::kUnknown) + unclear_detail = w.too_many_hops ? what + " leads through more than " + std::to_string(kMaxHops) + " hook jumps" + : what + " could not be read" + via; + else if (w.owner == Owner::kAnonymous) unclear_detail = what + " leads to code outside every module" + via; + else unclear_detail = what + " leads into the exe's own code" + via; } bool override_take(const std::string& value, std::string* note) { @@ -268,6 +290,10 @@ std::string line_ngx_other() { "NGX route only: the host refused WrongGPU's RR provider, another provider holds it; the game-interface " "route is decided on its own)"; } +std::string line_inconclusive(const std::string& when, unsigned n, const std::string& first) { + return "hook: coexistence check " + when + ": inconclusive for " + std::to_string(n) + " address(es) (first: " + first + + "); no other plugin was positively found, WrongGPU RR stays active"; +} void Decision::freeze_once(const std::function& decide) { if (frozen()) return; @@ -299,11 +325,12 @@ std::string leaf_utf8(const void* m) { } } // namespace -Env process_env(const void* self, const void* iface, const void* host) { +Env process_env(const void* self, const void* iface, const void* host, const void* host_alt) { Env e; e.self = self; e.iface = iface; e.host = host; + e.host_alt = host_alt; e.exe = GetModuleHandleW(nullptr); e.module_of = [](const void* a) -> const void* { HMODULE m = nullptr; diff --git a/clean/rr_f/proxy/src/rr_guard.h b/clean/rr_f/proxy/src/rr_guard.h index dbe18af5..1a5c5ac5 100644 --- a/clean/rr_f/proxy/src/rr_guard.h +++ b/clean/rr_f/proxy/src/rr_guard.h @@ -1,9 +1,15 @@ // SPDX-License-Identifier: MIT // RR guard: the coexistence guard of the hook-mode RR plugin (HOOK-MODE.md, "Another Ray Reconstruction -// plugin"). When another Ray Reconstruction plugin already holds the game's RR path in this process, WrongGPU RR stays -// off and logs one line; Model M is not touched. Generic and read-only: it looks at where the game's RR calls lead -// (import slots, the first bytes of the interface's RR exports, the host's continuation pointers), never at another -// plugin's files or internals. +// plugin"). When another Ray Reconstruction plugin demonstrably holds the game's RR path in this process, WrongGPU RR +// stays off and logs one line; Model M is not touched. Generic and read-only: it looks at where the game's RR calls +// lead (import slots, the first bytes of the interface's RR exports, the host's continuation pointers), never at +// another plugin's files or internals. +// +// Only a POSITIVE finding stops the plugin: an address that ends in a named foreign module (also through decoded hook +// jumps), or in our own second copy. Everything else the scan cannot explain (unreadable memory, too many hops, code +// outside every module that does not jump on, the exe's own code) is logged once as inconclusive and the plugin stays +// active: a game's copy protection or a hooking library's trampolines must never switch RR off for a player who has no +// other plugin. // // This header holds the parts without process state, so the CPU tests can drive them with synthetic memory: // - safe_read: every read of memory we do not own (VirtualQuery for committed, readable, non-guard pages, then a @@ -12,8 +18,9 @@ // mov rax|r11, imm64 + jmp reg); // - classify: who an address belongs to (our module, the game interface, the host, another copy of WrongGPU RR, // another WrongGPU module, the exe's own delay-load thunk, code outside every module, another module), following -// hook jumps out of the interface and out of anonymous memory, up to kMaxHops; -// - Verdict: the worst of several classifications, and the words for the log; +// hook jumps out of the interface and out of anonymous memory, at most kMaxHops of them; +// - Verdict: the positive finding (if any) of several classifications, the inconclusive ones, and the words for the +// log; // - Decision: the once-only late decision (several game threads may make the first call at the same time). #pragma once #include @@ -33,9 +40,10 @@ constexpr const char* kOwnRrExport = "WrongGPU_GetSettingsContract"; constexpr const char* kWrongGpuAsiExport = "WrongGpuAsiQuery"; // wronggpu-rr.ini: rr_other_plugin = off (default) | take constexpr const char* kOverrideKey = "rr_other_plugin"; -constexpr int kMaxHops = 4; +constexpr int kMaxHops = 4; // hook jumps followed from one address (a fifth one is "too many hops": inconclusive) -// True when [p, p + n) lies in committed pages that are readable and not guard pages (VirtualQuery only). +// True when [p, p + n) lies in committed pages that are readable (execute-only pages count: code is read from them and +// the structured-exception guard of the copy covers a fault) and not guard pages (VirtualQuery only). bool readable(const void* p, size_t n); // Copies n bytes from p to out when readable() and the copy raises no structured exception. False: unknown. bool safe_read(const void* p, void* out, size_t n); @@ -66,15 +74,15 @@ class Reader { bool decode_jump(const uint8_t* code, size_t n, const uint8_t* at, const void** target, const void** cell); enum class Owner { - kUnknown, // the memory could not be read (or a null pointer): the safe side is "another plugin" + kUnknown, // the memory could not be read, a null pointer, or more than kMaxHops jumps: inconclusive kSelf, // this WrongGPU RR module kInterface, // the game interface module (its own code) - kHost, // the host that loaded us (it patches the interface's init export itself) - kOwnCopy, // another loaded copy of WrongGPU RR (exports kOwnRrExport) + kHost, // the host that loaded us, or the module holding its API table (it patches the interface itself) + kOwnCopy, // another loaded copy of WrongGPU RR (exports kOwnRrExport): positive kWrongGpu, // another WrongGPU module (exports kWrongGpuAsiExport) - kExeThunk, // the exe's own code (a delay-load slot not bound yet holds the delay helper's thunk there) - kAnonymous, // readable code outside every module that does not jump on (a trampoline) - kForeign, // another module: another plugin + kExeThunk, // the exe's own code (a delay-load slot not bound yet holds the delay helper's thunk there): inconclusive + kAnonymous, // readable code outside every module that does not jump on (a trampoline): inconclusive + kForeign, // another named module: another plugin (positive) }; const char* owner_word(Owner o); @@ -82,7 +90,8 @@ const char* owner_word(Owner o); struct Env { const void* self = nullptr; const void* iface = nullptr; - const void* host = nullptr; + const void* host = nullptr; // the module that called InitializeASI + const void* host_alt = nullptr; // the module holding the host's API table, when it is another module (a separate loader) const void* exe = nullptr; // the interface's import address table (its own imports): a jmp [rip+disp32] through a cell in it is the linker's // import thunk, not a hook @@ -93,23 +102,31 @@ struct Env { std::function name_of; // the module's file name (for the log) }; // The real process: GetModuleHandleExW (from address, refcount unchanged), GetProcAddress, GetModuleFileNameW. -Env process_env(const void* self, const void* iface, const void* host); +Env process_env(const void* self, const void* iface, const void* host, const void* host_alt = nullptr); struct Where { Owner owner = Owner::kUnknown; std::string module; // file name of the module the address ends in ("" when none) + const void* module_handle = nullptr; // the module the address ends in (null when none) int hops = 0; // hook jumps followed + bool too_many_hops = false; // kUnknown because the jump chain was longer than kMaxHops }; // Where code at `p` leads. follow_iface: follow a hook jump at p when p is inside the interface (the first bytes of // an export); a jump that stays inside the interface, or goes through the interface's own import table, is the // interface's own code. Jumps are always followed out of anonymous memory. Where classify(const void* p, const Env& env, bool follow_iface); -// What a scan found: the first not-trusted address decides (a copy of WrongGPU RR before anything else). +// What a scan found. kOther / kOwnCopy are positive findings only (an address that ends in another named module, or in +// a second copy of WrongGPU RR; the first foreign one decides, a copy of WrongGPU RR before anything else). Whatever +// could not be explained (unreadable, too many hops, anonymous code that does not jump on, the exe's own code) is +// counted in `unclear` and leaves the kind at kClean: the plugin stays active. struct Verdict { enum Kind { kClean, kOwnCopy, kOther } kind = kClean; std::string detail; // e.g. "the import slot slEvaluateFeature of Game.exe leads to other.asi" + const void* other_module = nullptr; // kOther: the module the first foreign finding ends in unsigned reads = 0; // addresses looked at + unsigned unclear = 0; // addresses that were neither trusted nor a positive finding + std::string unclear_detail; // the first of them, e.g. "the import slot X of Y could not be read" // Takes one classification. `what` names the place ("the import slot X of Y"); anon_ok: code outside every // module is accepted here (the host's own trampolines); exe_ok: the exe's own code is accepted (delay thunks). void add(const Where& w, const std::string& what, bool anon_ok, bool exe_ok); @@ -127,6 +144,9 @@ std::string line_take(const std::string& detail); // rr_other_plug std::string line_cannot_take(const std::string& detail); // take asked, the other plugin loaded later std::string line_own_copy(const std::string& active, const std::string& self); std::string line_ngx_other(); // the host refused our NGX provider +// The stay-on diagnostic (starts with "hook: "; never with the beginnings above): the scan could not explain `n` +// address(es), `first` is the first one. No finding, RR stays active. +std::string line_inconclusive(const std::string& when, unsigned n, const std::string& first); // The guard's state for the whole process run. Active until a scan says otherwise; the late decision is taken once. enum class State : int { kActive = 0, kOff = 1, kOwnCopy = 2, kPassThrough = 3, kTaken = 4 }; diff --git a/clean/rr_f/proxy/tests/fake_other_rr.cpp b/clean/rr_f/proxy/tests/fake_other_rr.cpp index 3e6d8456..73ce488c 100644 --- a/clean/rr_f/proxy/tests/fake_other_rr.cpp +++ b/clean/rr_f/proxy/tests/fake_other_rr.cpp @@ -10,6 +10,9 @@ // wgtest_or_set_slot writes any value into one import slot (code outside every module, an unreadable page) // wgtest_or_routes registers its handlers as game-interface routes with the host (plugin interface 3) // wgtest_or_register_ngx registers an NGX RR provider with the host (plugin interface 4) +// wgtest_or_host_table keeps a copy of a host API table in this module (the host's table lives in a module of its own) +// wgtest_or_call_init calls a function from inside this module (a separate ASI loader calling InitializeASI; the test +// loads a second copy of this DLL under another name for that) // Its handlers answer the RR feature themselves (is-supported 0, evaluate / allocate / get-function counted and 0) and // pass every other call on. The role names and order come from the hook binding (wg_binding.inc). #define WIN32_LEAN_AND_MEAN @@ -188,6 +191,22 @@ __declspec(dllexport) int wgtest_or_routes(const WgHostMenuApi* api, WgHostMenuP return 4; } +// "the host's API table held in this module": a copy of the caller's table kept in this DLL's data (the host that owns +// the table is a module of its own, as with OptiScaler); the pointer is what OptiPluginInit gets +__declspec(dllexport) const WgHostMenuApi* wgtest_or_host_table(const WgHostMenuApi* src) { + static WgHostMenuApi table; + table = *src; + return &table; +} + +// "a separate ASI loader": calls f (WrongGPU RR's InitializeASI) from inside this module, so that the module that +// called it is this one (not the exe). The volatile write keeps the call from becoming a tail jump. +__declspec(dllexport) void __declspec(noinline) wgtest_or_call_init(void (*f)()) { + static volatile int sink; + f(); + sink = 1; +} + __declspec(dllexport) bool wgtest_or_register_ngx(const WgHostMenuApi* api, WgHostMenuPlugin* plugin) { static WgHostNgxRr p; p.size = sizeof p; diff --git a/clean/rr_f/proxy/tests/guard_inject.cpp b/clean/rr_f/proxy/tests/guard_inject.cpp deleted file mode 100644 index ea5816b1..00000000 --- a/clean/rr_f/proxy/tests/guard_inject.cpp +++ /dev/null @@ -1,80 +0,0 @@ -// SPDX-License-Identifier: MIT -// RR guard: runs a test program with the guard scene (tests/guard_scene.cpp) loaded before its main -// (tools/guard_modelm.py). The program is started suspended, the scene DLL is loaded into it by a remote thread -// (LoadLibraryW), the scene's own thread sets the scene up and signals; then the program's main thread is resumed and -// runs unchanged. Exit code: the program's, or 90 when the scene failed (its result is printed), 91 on a start failure. -// guard_inject.exe [args...] (the working directory is inherited) -#define WIN32_LEAN_AND_MEAN -#include - -#include - -#include - -static std::wstring quote(const std::wstring& a) { - if (!a.empty() && a.find_first_of(L" \t\"") == std::wstring::npos) return a; - std::wstring q = L"\""; - for (wchar_t c : a) { - if (c == L'"') q += L'\\'; - q += c; - } - return q + L"\""; -} - -int wmain(int argc, wchar_t** argv) { - if (argc < 5) return 91; - const std::wstring scene = argv[1], stage = argv[2], mode = argv[3]; - std::wstring cmd; - for (int i = 4; i < argc; ++i) cmd += (cmd.empty() ? L"" : L" ") + quote(argv[i]); - const DWORD me = GetCurrentProcessId(); - const std::wstring event_name = L"Local\\wgtest-guard-scene-" + std::to_wstring(me); - const std::wstring result = stage + L"\\scene-result-" + std::to_wstring(me) + L".txt"; - DeleteFileW(result.c_str()); - HANDLE ev = CreateEventW(nullptr, TRUE, FALSE, event_name.c_str()); - SetEnvironmentVariableW(L"WGTEST_GUARD_STAGE", stage.c_str()); - SetEnvironmentVariableW(L"WGTEST_GUARD_MODE", mode.c_str()); - SetEnvironmentVariableW(L"WGTEST_GUARD_EVENT", event_name.c_str()); - SetEnvironmentVariableW(L"WGTEST_GUARD_RESULT", result.c_str()); - STARTUPINFOW si = {sizeof si}; - PROCESS_INFORMATION pi = {}; - if (!ev || !CreateProcessW(nullptr, &cmd[0], nullptr, nullptr, TRUE, CREATE_SUSPENDED, nullptr, nullptr, &si, &pi)) { - fprintf(stderr, "guard_inject: cannot start the program (error %lu)\n", GetLastError()); - return 91; - } - const size_t bytes = (scene.size() + 1) * sizeof(wchar_t); - void* remote = VirtualAllocEx(pi.hProcess, nullptr, bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); - SIZE_T written = 0; - auto load = reinterpret_cast( - reinterpret_cast(GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "LoadLibraryW"))); - HANDLE t = nullptr; - if (remote && WriteProcessMemory(pi.hProcess, remote, scene.c_str(), bytes, &written) && written == bytes) - t = CreateRemoteThread(pi.hProcess, nullptr, 0, load, remote, 0, nullptr); - DWORD loaded = 0; - const bool ok_thread = t && WaitForSingleObject(t, 30000) == WAIT_OBJECT_0 && GetExitCodeThread(t, &loaded) && loaded; - const bool ok_scene = ok_thread && WaitForSingleObject(ev, 30000) == WAIT_OBJECT_0; - if (t) CloseHandle(t); - std::string r; - if (FILE* f = _wfopen(result.c_str(), L"rb")) { - char b[1024] = {}; - fread(b, 1, sizeof b - 1, f); - fclose(f); - r = b; - } - DeleteFileW(result.c_str()); - if (!ok_scene || r.compare(0, 2, "ok") != 0) { - fprintf(stderr, "guard_inject: scene failed (%s): %s\n", ok_thread ? "scene" : "load", r.c_str()); - TerminateProcess(pi.hProcess, 90); - WaitForSingleObject(pi.hProcess, 10000); - return 90; - } - printf("guard_inject: %s\n", r.c_str()); - fflush(stdout); - ResumeThread(pi.hThread); - WaitForSingleObject(pi.hProcess, INFINITE); - DWORD code = 91; - GetExitCodeProcess(pi.hProcess, &code); - CloseHandle(pi.hThread); - CloseHandle(pi.hProcess); - CloseHandle(ev); - return (int)code; -} diff --git a/clean/rr_f/proxy/tests/guard_scene.cpp b/clean/rr_f/proxy/tests/guard_scene.cpp deleted file mode 100644 index aa293d8f..00000000 --- a/clean/rr_f/proxy/tests/guard_scene.cpp +++ /dev/null @@ -1,137 +0,0 @@ -// SPDX-License-Identifier: MIT -// RR guard: the scene DLL of the Model M check (tools/guard_modelm.py, tests/guard_inject.cpp). Loaded into a -// suspended Model M test process before its main runs, it loads WrongGPU RR (the hook plugin) next to our stand-in game -// interface and, per WGTEST_GUARD_MODE, trips the guard: -// none no other plugin (control: WrongGPU RR as it is without the guard tripping) -// off our stand-in other plugin patched the interface's evaluate export first: WrongGPU RR stays off -// take the same with rr_other_plugin=take (the injector writes wronggpu-rr.ini next to the test exe) -// owncopy two copies of WrongGPU RR: the second stays off -// passthrough the stand-in patches the export after InitializeASI; OptiPluginInit finds it: WrongGPU RR passes on -// It checks that WrongGPU RR logged its line (wronggpu-rr.log next to the test exe, the part written by this process), -// writes "ok"/"fail " to WGTEST_GUARD_RESULT and signals WGTEST_GUARD_EVENT; the injector then resumes the test. -// Files come from WGTEST_GUARD_STAGE (the stand-in interface, wgtest_other_rr.dll, the plugin and its copy). -#define WIN32_LEAN_AND_MEAN -#include - -#include -#include - -#include - -#include "wg_binding.inc" -#include "../include/wg_host_menu_abi.h" - -namespace { - -std::wstring env(const wchar_t* name) { - wchar_t buf[2048]; - const DWORD n = GetEnvironmentVariableW(name, buf, 2048); - return n && n < 2048 ? std::wstring(buf, n) : std::wstring(); -} - -std::string read_from(const std::wstring& path, long long from) { - std::string s; - FILE* f = _wfopen(path.c_str(), L"rb"); - if (!f) return s; - _fseeki64(f, from, SEEK_SET); - char b[4096]; - size_t n; - while ((n = fread(b, 1, sizeof b, f)) > 0) s.append(b, n); - fclose(f); - return s; -} - -long long size_of(const std::wstring& path) { - WIN32_FILE_ATTRIBUTE_DATA a; - return GetFileAttributesExW(path.c_str(), GetFileExInfoStandard, &a) ? ((long long)a.nFileSizeHigh << 32) | a.nFileSizeLow - : 0; -} - -size_t occurrences(const std::string& hay, const std::string& needle) { - size_t n = 0; - for (size_t at = hay.find(needle); at != std::string::npos; at = hay.find(needle, at + 1)) ++n; - return n; -} - -std::string run_scene() { - const std::wstring stage = env(L"WGTEST_GUARD_STAGE"); - const std::wstring mode_w = env(L"WGTEST_GUARD_MODE"); - const std::string mode(mode_w.begin(), mode_w.end()); - wchar_t exe[MAX_PATH]; - const DWORD en = GetModuleFileNameW(nullptr, exe, MAX_PATH); - std::wstring dir(exe, en); - dir = dir.substr(0, dir.find_last_of(L"\\/") + 1); - const std::wstring log = dir + L"wronggpu-rr.log"; - const long long from = size_of(log); - - HMODULE iface = LoadLibraryW((stage + L"\\" + std::wstring(kWgInterposerFile, kWgInterposerFile + strlen(kWgInterposerFile))).c_str()); - HMODULE other = LoadLibraryW((stage + L"\\wgtest_other_rr.dll").c_str()); - if (!iface || !other) return "fail: stand-ins not loaded"; - auto patch_export = reinterpret_cast(GetProcAddress(other, "wgtest_or_patch_export")); - const char* evaluate = kWgRoleNames[16]; - if ((mode == "off" || mode == "take") && patch_export(iface, evaluate, 0) != 1) return "fail: export not patched"; - const std::wstring hook(kWgHookFile, kWgHookFile + strlen(kWgHookFile)); - HMODULE asi = LoadLibraryW((stage + L"\\" + hook).c_str()); - if (!asi) return "fail: plugin not loaded"; - auto init = reinterpret_cast(GetProcAddress(asi, "InitializeASI")); - auto plugin_init = reinterpret_cast(GetProcAddress(asi, WG_HOST_MENU_INIT_EXPORT)); - if (!init || !plugin_init) return "fail: plugin entries missing"; - init(); - if (mode == "owncopy") { - HMODULE copy = LoadLibraryW((stage + L"\\WrongGPU-RR-copy.asi").c_str()); - auto init2 = copy ? reinterpret_cast(GetProcAddress(copy, "InitializeASI")) : nullptr; - if (!init2) return "fail: copy not loaded"; - init2(); - } - if (mode == "passthrough" && patch_export(iface, evaluate, 0) != 1) return "fail: export not patched"; - static WgHostMenuApi api = {}; // a host table without menu, routes or NGX provider - api.size = sizeof api; - api.version = 5; - plugin_init(&api, reinterpret_cast(0x1000)); - - const std::string got = read_from(log, from); - const std::string stem = "another Ray Reconstruction plugin is active; WrongGPU RR stays off ("; - struct Want { const char* text; size_t n; }; - Want want[3] = {}; - if (mode == "none") want[0] = {"hook: coexistence check at load: no other Ray Reconstruction plugin found (", 1}; - if (mode == "off") want[0] = {"; nothing patched; rr_other_plugin=take in wronggpu-rr.ini uses WrongGPU's instead)", 1}; - if (mode == "take") want[0] = {"another Ray Reconstruction plugin is active; rr_other_plugin=take: WrongGPU RR goes in front of it (", 1}; - if (mode == "owncopy") want[0] = {"a second copy of WrongGPU RR is loaded (", 1}; - if (mode == "passthrough") want[0] = {"; it loaded after WrongGPU: WrongGPU passes every call on unchanged; to use WrongGPU RR, move it aside)", 1}; - if (!want[0].text) return "fail: unknown mode " + mode; - if (occurrences(got, want[0].text) != want[0].n) return std::string("fail: log lacks \"") + want[0].text + "\""; - const size_t stems = occurrences(got, stem); - if (stems != ((mode == "off" || mode == "passthrough") ? 1u : 0u)) return "fail: " + std::to_string(stems) + " stays-off line(s)"; - return "ok " + mode; -} - -DWORD WINAPI scene_thread(void*) { - std::string r; - try { - r = run_scene(); - } catch (...) { - r = "fail: exception"; - } - const std::wstring result = env(L"WGTEST_GUARD_RESULT"); - FILE* f = _wfopen(result.c_str(), L"wb"); - if (f) { - fputs(r.c_str(), f); - fclose(f); - } - HANDLE ev = OpenEventW(EVENT_MODIFY_STATE, FALSE, env(L"WGTEST_GUARD_EVENT").c_str()); - if (ev) { - SetEvent(ev); - CloseHandle(ev); - } - return 0; -} - -} // namespace - -BOOL WINAPI DllMain(HINSTANCE inst, DWORD reason, LPVOID) { - if (reason == DLL_PROCESS_ATTACH) { - DisableThreadLibraryCalls(inst); - if (HANDLE t = CreateThread(nullptr, 0, scene_thread, nullptr, 0, nullptr)) CloseHandle(t); // runs after the lock - } - return TRUE; -} diff --git a/clean/rr_f/proxy/tests/test_rr_guard.cpp b/clean/rr_f/proxy/tests/test_rr_guard.cpp index ef767853..704eced0 100644 --- a/clean/rr_f/proxy/tests/test_rr_guard.cpp +++ b/clean/rr_f/proxy/tests/test_rr_guard.cpp @@ -5,9 +5,12 @@ // path (a page made unreadable after its region was cached); the cache keeps VirtualQuery calls few; // - decode_jump: every jump form, and a jmp [rip+disp32] whose cell is not readable; // - classify: synthetic modules (ranges of one allocation) and anonymous relays: the interface's own code, a hook jump -// to another module, a jump inside the interface, the linker's import thunk, a relay chain to the host, a relay loop -// (more than kMaxHops), anonymous code, an unreadable target, a copy of WrongGPU RR, WrongGPU.asi, the exe's thunk; -// - Verdict precedence, override parsing, the exact log lines; +// to another module, a jump inside the interface, the linker's import thunk, a relay chain to the host, exactly +// kMaxHops jumps (followed) and one more (too many hops), a relay loop, anonymous code, an unreadable target, an +// execute-only relay page (read), a copy of WrongGPU RR, WrongGPU.asi, the exe's thunk, the host's second module; +// - Verdict: only a positive finding (a named foreign module, a copy of WrongGPU RR) is a finding; unreadable memory, +// too many hops, non-jumping anonymous code and the exe's own code are inconclusive (counted, kind stays clean); +// precedence, override parsing, the exact log lines; // - Decision: 32 threads make the "first call" at once: decide runs exactly once, every thread sees the same state. #define WIN32_LEAN_AND_MEAN #include @@ -73,6 +76,15 @@ int main() { CHECK(VirtualQuery(blk + 2 * kPage, &m, sizeof m) && (m.Protect & PAGE_GUARD)); // never touched: still a guard page uint64_t p64 = 0; CHECK(!safe_get(blk + 3 * kPage, &p64)); + // an execute-only page counts as readable (a hooking library's trampolines); the copy is guarded either way + uint8_t* xo = static_cast(VirtualAlloc(nullptr, kPage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + CHECK(xo != nullptr); + memset(xo, 0xC3, kPage); + DWORD xold = 0; + CHECK(VirtualProtect(xo, kPage, PAGE_EXECUTE, &xold)); + CHECK(readable(xo, 16)); + (void)safe_read(xo, b, 1); // hardware without read-through-execute faults here: caught, false; no crash either way + VirtualFree(xo, 0, MEM_RELEASE); // the cached reader: many reads in one region take one VirtualQuery; a page made unreadable after its region was // cached is caught by the structured-exception path (no fault, false) @@ -209,10 +221,38 @@ int main() { put_rel32(iface + 384, anon + 64); w = classify(iface + 384, env, true); CHECK(w.owner == Owner::kForeign && w.module == "other.asi" && w.hops == 3); - // a relay loop: more than kMaxHops -> unknown (the safe side) + // a relay loop: more than kMaxHops -> unknown (inconclusive: not a sign of another plugin) put_abs(anon + 256, anon + 512); put_abs(anon + 512, anon + 256); - CHECK(classify(anon + 256, env, false).owner == Owner::kUnknown); + w = classify(anon + 256, env, false); + CHECK(w.owner == Owner::kUnknown && w.too_many_hops && w.hops == kMaxHops); + // exactly kMaxHops (4) jumps are followed to a foreign module; a fifth one is too many + static_assert(kMaxHops == 4, "the chains below are written for four hops"); + put_abs(anon + 2048, anon + 2112); + put_abs(anon + 2112, anon + 2176); + put_abs(anon + 2176, anon + 2240); + put_abs(anon + 2240, foreign + 72); + w = classify(anon + 2048, env, false); + CHECK(w.owner == Owner::kForeign && w.module == "other.asi" && w.hops == 4 && !w.too_many_hops); + put_abs(anon + 2240, anon + 2304); // lengthen it by one jump + put_abs(anon + 2304, foreign + 72); + w = classify(anon + 2048, env, false); + CHECK(w.owner == Owner::kUnknown && w.too_many_hops && w.hops == 4); + put_abs(anon + 2240, foreign + 72); // (kept four hops for the Verdict checks below) + // the host's API-table module (a separate loader called InitializeASI): a second host module + { + Env env2 = env; + env2.host_alt = foreign; + CHECK(classify(foreign + 8, env, false).owner == Owner::kForeign); + CHECK(classify(foreign + 8, env2, false).owner == Owner::kHost); + CHECK(classify(anon + 2048, env2, false).owner == Owner::kHost); // a hook chain that ends in it + } + // an execute-only relay page is read like any other + put_abs(anon + kPage + 16, foreign + 80); + CHECK(VirtualProtect(anon + kPage, kPage, PAGE_EXECUTE, &old)); + w = classify(anon + kPage + 16, env, false); + CHECK(w.owner == Owner::kForeign && w.hops == 1); + CHECK(VirtualProtect(anon + kPage, kPage, PAGE_EXECUTE_READWRITE, &old)); // anonymous code that does not jump on CHECK(classify(anon + 1024, env, false).owner == Owner::kAnonymous); // an unreadable target: unknown, and an export whose jmp [rip] cell is unreadable: unknown @@ -241,25 +281,55 @@ int main() { v.add(classify(host + 8, env, false), "the import slot B of game.exe", false, false); v.add(classify(exe + 8, env, false), "the delay-load slot C of game.exe", false, true); v.add(classify(anon + 1024, env, false), "the host's next function of D", true, false); - CHECK(v.kind == Verdict::kClean && v.reads == 4); + CHECK(v.kind == Verdict::kClean && v.reads == 4 && v.unclear == 0); + // not positive findings: unreadable memory, a null slot, too many hops, anonymous code that does not jump on (not + // accepted here), the exe's own code (not accepted here), a hook chain that ends in the exe: counted, kind stays clean + v.add(classify(dead + 32, env, false), "the import slot F of game.exe", false, false); + CHECK(v.kind == Verdict::kClean && v.unclear == 1 && v.unclear_detail == "the import slot F of game.exe could not be read"); + v.add(classify(nullptr, env, false), "the import slot N of game.exe", false, false); + v.add(classify(anon + 256, env, false), "the import slot L of game.exe", false, false); + v.add(classify(anon + 1024, env, false), "the import slot I of game.exe", false, false); + v.add(classify(exe + 8, env, false), "the import slot J of game.exe", false, false); + CHECK(v.kind == Verdict::kClean && v.unclear == 5 && v.reads == 9); + CHECK(v.unclear_detail == "the import slot F of game.exe could not be read"); // the first one stays + Verdict u; + u.add(classify(anon + 256, env, false), "the import slot L of game.exe", false, false); + CHECK(u.kind == Verdict::kClean && u.unclear == 1 && + u.unclear_detail == "the import slot L of game.exe leads through more than 4 hook jumps"); + Verdict a; + a.add(classify(anon + 1024, env, false), "the import slot I of game.exe", false, false); + CHECK(a.kind == Verdict::kClean && a.unclear == 1 && + a.unclear_detail == "the import slot I of game.exe leads to code outside every module"); + put_rel32(iface + 640, exe + 24); // an export hooked into the exe's own code + Verdict e; + e.add(classify(exe + 8, env, false), "the import slot J of game.exe", false, false); + e.add(classify(iface + 640, env, true), "the export K of iface.dll", false, false); + CHECK(e.kind == Verdict::kClean && e.unclear == 2 && + e.unclear_detail == "the import slot J of game.exe leads into the exe's own code"); + Verdict e2; + e2.add(classify(iface + 640, env, true), "the export K of iface.dll", false, false); + CHECK(e2.unclear_detail == "the export K of iface.dll leads into the exe's own code (through 1 hook jump)"); + Verdict ok; // the accepted places stay trusted + ok.add(classify(anon + 1024, env, false), "the host's next function of D", true, false); + ok.add(classify(exe + 8, env, false), "the delay-load slot C of game.exe", false, true); + CHECK(ok.kind == Verdict::kClean && ok.unclear == 0); + // positive findings v.add(classify(iface + 384, env, true), "the export E of iface.dll", false, false); - CHECK(v.kind == Verdict::kOther); + CHECK(v.kind == Verdict::kOther && v.other_module == foreign); CHECK(v.detail == "the export E of iface.dll leads to other.asi (through 3 hook jumps)"); - v.add(classify(dead + 32, env, false), "the import slot F of game.exe", false, false); + v.add(classify(foreign + 8, env, false), "the import slot M of game.exe", false, false); CHECK(v.detail == "the export E of iface.dll leads to other.asi (through 3 hook jumps)"); // the first one stays v.add(classify(copy + 8, env, false), "the import slot G of game.exe", false, false); CHECK(v.kind == Verdict::kOwnCopy && v.detail == "WrongGPU-RR-copy.asi"); // a copy of WrongGPU RR before all v.add(classify(foreign + 8, env, false), "the import slot H of game.exe", false, false); - CHECK(v.kind == Verdict::kOwnCopy && v.reads == 8); - Verdict u; - u.add(classify(dead + 32, env, false), "the import slot F of game.exe", false, false); - CHECK(u.kind == Verdict::kOther && u.detail == "the import slot F of game.exe could not be read"); - Verdict a; - a.add(classify(anon + 1024, env, false), "the import slot I of game.exe", false, false); // anon not accepted here - CHECK(a.kind == Verdict::kOther && a.detail == "the import slot I of game.exe leads to code outside every module"); - Verdict e; - e.add(classify(exe + 8, env, false), "the import slot J of game.exe", false, false); // exe code not accepted here - CHECK(e.kind == Verdict::kOther && e.detail == "the import slot J of game.exe leads to game.exe"); + CHECK(v.kind == Verdict::kOwnCopy && v.reads == 13); + Verdict f4; // a decoded chain of exactly kMaxHops jumps that ends in a foreign module is positive + f4.add(classify(anon + 2048, env, false), "the import slot P of game.exe", false, false); + CHECK(f4.kind == Verdict::kOther && f4.detail == "the import slot P of game.exe leads to other.asi (through 4 hook jumps)"); + Verdict f5; // the unreadable first read does not hide a later positive finding + f5.add(classify(dead + 32, env, false), "the import slot F of game.exe", false, false); + f5.add(classify(foreign + 8, env, false), "the import slot Q of game.exe", false, false); + CHECK(f5.kind == Verdict::kOther && f5.unclear == 1 && f5.detail == "the import slot Q of game.exe leads to other.asi"); CHECK(trusted(Owner::kWrongGpu, false, false) && !trusted(Owner::kUnknown, true, true) && !trusted(Owner::kForeign, true, true) && !trusted(Owner::kOwnCopy, true, true)); VirtualFree(blk, 0, MEM_RELEASE); @@ -291,6 +361,12 @@ int main() { CHECK(line_own_copy("A", "B") == "a second copy of WrongGPU RR is loaded (A is active); this copy (B) stays off"); CHECK(line_ngx_other() == stem + " (NGX route only: the host refused WrongGPU's RR provider, another provider " "holds it; the game-interface route is decided on its own)"); + // the stay-on diagnostic: never one of the matched beginnings + const std::string inc = line_inconclusive("at load", 2, "the import slot X of Game.exe could not be read"); + CHECK(inc == "hook: coexistence check at load: inconclusive for 2 address(es) (first: the import slot X of Game.exe " + "could not be read); no other plugin was positively found, WrongGPU RR stays active"); + CHECK(inc.compare(0, 6, "hook: ") == 0 && inc.find("plugin is active") == std::string::npos && + inc.find("stays off") == std::string::npos); } // ---------------------------------------------------------------- Decision: one decision under concurrent first calls diff --git a/clean/rr_f/proxy/tests/test_rr_guard_dll.cpp b/clean/rr_f/proxy/tests/test_rr_guard_dll.cpp index 6a3ee7df..2f2eccbc 100644 --- a/clean/rr_f/proxy/tests/test_rr_guard_dll.cpp +++ b/clean/rr_f/proxy/tests/test_rr_guard_dll.cpp @@ -4,19 +4,31 @@ // interface (tests/gen_fake_original.py). The "other Ray Reconstruction plugin" is our own stand-in, // wgtest_other_rr.dll (tests/fake_other_rr.cpp); no third-party file is used. // test_rr_guard_dll.exe [--take] +// Only a POSITIVE finding switches WrongGPU RR off (a named foreign module, also through decoded hook jumps; a second +// copy of WrongGPU RR); what the scan cannot explain is logged once as inconclusive and WrongGPU RR stays active. // Modes (import build): // clean no other plugin: active; 16 threads make the first call at once: one re-check line; the scan cost // first the other plugin redirected the exe's import slots before ours loaded (wrapping): off, nothing patched // inline the other plugin put a jmp [rip] on the evaluate export: off // relay the same through a jmp rel32 to an anonymous relay: off ("through 2 hook jumps") -// anon one import slot leads to code outside every module: off -// noaccess one import slot leads to a PAGE_NOACCESS page: "could not be read", off, no fault +// execonly one import slot leads to an execute-only relay page that jumps into the other plugin: off (the relay +// page is read although it is PAGE_EXECUTE) +// anon one import slot leads to code outside every module that does not jump on: inconclusive, stays active +// noaccess one import slot leads to a PAGE_NOACCESS page: "could not be read", inconclusive, stays active, no fault // guardpage one import slot leads to a guard page: the same, and the page is still a guard page afterwards +// exe one import slot leads into the exe's own code (a separate loader DLL calls InitializeASI, so the exe is +// not the host): inconclusive, stays active +// hops one import slot leads through five relay jumps (more than kMaxHops) to the other plugin: inconclusive, +// stays active +// hostsplit a separate loader DLL calls InitializeASI; the real host (a DLL holding the API table) patched the slots: +// found at load, then OptiPluginInit shows the module is the host and the load check runs again: active // late the other plugin wrapped our hooks after InitializeASI: 16 threads make the first call at once: one // decision, one line, every call passed on unchanged // late-replace the other plugin replaced our hooks after InitializeASI (no call reaches us): found at OptiPluginInit // provider the other plugin holds the host's NGX RR provider: NGX route only, the game-interface route stays -// owncopy two copies of WrongGPU RR: the second stays off and registers nothing +// owncopy WrongGPU RR and four more copies under other file names: the others stay off and register nothing; the +// copies' InitializeASI / OptiPluginInit run from threads while 16 game threads make the first call (every +// copy writes the one log at once: no torn line); freeing an inactive copy writes no exit summary // --take (wronggpu-rr.ini rr_other_plugin=take): first / inline: WrongGPU RR in front; late: the can't-take line. // Modes (built with WG_TEST_NOIMPORT: the exe does not link the interface, the host routes are used): // route no other plugin: our routes continue to the interface @@ -216,6 +228,7 @@ int main(int argc, char** argv) { auto or_patch_export = reinterpret_cast(GetProcAddress(other, "wgtest_or_patch_export")); auto or_routes = reinterpret_cast(GetProcAddress(other, "wgtest_or_routes")); auto or_ngx = reinterpret_cast(GetProcAddress(other, "wgtest_or_register_ngx")); + auto or_host_table = reinterpret_cast(GetProcAddress(other, "wgtest_or_host_table")); const OrState* os = or_state(); HMODULE exe = GetModuleHandleW(nullptr); const std::string exe_leaf = "test_rr_guard_dll.exe"; @@ -240,9 +253,10 @@ int main(int argc, char** argv) { host::iface = iface; FoState* fo = reinterpret_cast(GetProcAddress(iface, "wgtest_fo_state"))(); const bool late = mode == "late" || mode == "late-replace"; + const bool stays_on = mode == "anon" || mode == "noaccess" || mode == "guardpage" || mode == "exe" || mode == "hops"; // ---- the other plugin before ours void* odd_page = nullptr; - if (mode == "first") CHECK(or_patch_iat(exe, kWgInterposerFile, 1) >= 6); + if (mode == "first" || mode == "hostsplit") CHECK(or_patch_iat(exe, kWgInterposerFile, 1) >= 6); // (hostsplit: the host's own) if (mode == "inline") CHECK(or_patch_export(iface, evaluate_name.c_str(), 0) == 1); if (mode == "relay") CHECK(or_patch_export(iface, evaluate_name.c_str(), 1) == 1); if (mode == "anon") { @@ -255,40 +269,114 @@ int main(int argc, char** argv) { mode == "noaccess" ? PAGE_NOACCESS : (PAGE_EXECUTE_READ | PAGE_GUARD)); CHECK(or_set_slot(exe, kWgInterposerFile, evaluate_name.c_str(), odd_page) == 1); } + if (mode == "exe") CHECK(or_set_slot(exe, kWgInterposerFile, evaluate_name.c_str(), reinterpret_cast(&read_lines)) == 1); + if (mode == "hops" || mode == "execonly") { + // relay jumps (jmp [rip+0]; dq target) in code outside every module that lead to a function of the other plugin + uint8_t* p = static_cast(VirtualAlloc(nullptr, 4096, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE)); + CHECK(p != nullptr); + const void* to_other = reinterpret_cast(GetProcAddress(other, "wgtest_or_state")); + const int jumps = mode == "hops" ? 5 : 1; // five is more than kMaxHops (4) + for (int i = 0; i < jumps; ++i) { + const void* t = i + 1 < jumps ? static_cast(p + 32 * (i + 1)) : to_other; + p[32 * i] = 0xFF; + p[32 * i + 1] = 0x25; + memset(p + 32 * i + 2, 0, 4); + memcpy(p + 32 * i + 6, &t, sizeof t); + } + if (mode == "execonly") { + DWORD old = 0; + CHECK(VirtualProtect(p, 4096, PAGE_EXECUTE, &old)); // execute-only: the guard still reads the relay + } + odd_page = p; + CHECK(or_set_slot(exe, kWgInterposerFile, evaluate_name.c_str(), p) == 1); + } if (mode == "provider") CHECK(or_ngx(&api, host::kTheirs)); // ---- WrongGPU RR (the host loads it and runs its entry) load_asi(widen(kWgHookFile), &init, &plugin_init); if (!init || !plugin_init) TEST_SUMMARY(label.c_str()); - init(); - if (mode == "owncopy") { // a second copy under another file name (build.py stages it) - void (*init2)() = nullptr; - WgHostMenuInitFn plugin_init2 = nullptr; - load_asi(L"WrongGPU-RR-copy.asi", &init2, &plugin_init2); - if (init2) init2(); - CHECK(plugin_init2 && !plugin_init2(&api, host::kOurs)); // the copy registers nothing + const WgHostMenuApi* host_api = &api; // the table OptiPluginInit gets + if (mode == "hostsplit" || mode == "exe") { + // a separate ASI loader (another module) calls InitializeASI. A second instance of the stand-in DLL plays the + // loader. hostsplit: the real host is wgtest_other_rr.dll, which holds the API table and patched the slots itself. + // exe: the host is a DLL, as in a game (when this test exe called InitializeASI itself, the exe would be the host + // and its code trusted), so a slot that leads into the exe's code is the exe's own code. + HMODULE loader = LoadLibraryW((ws + L"wgtest_loader.dll").c_str()); + CHECK(loader != nullptr); + auto call_init = loader ? reinterpret_cast(GetProcAddress(loader, "wgtest_or_call_init")) : nullptr; + CHECK(call_init != nullptr && or_host_table != nullptr); + if (!call_init || !or_host_table) TEST_SUMMARY(label.c_str()); + call_init(init); + if (mode == "hostsplit") { + host_api = or_host_table(&api); + CHECK(host_api != nullptr); + } + } else { + init(); // (owncopy: this copy is the active one, the others follow below) } + struct Copy { + HMODULE module = nullptr; + void (*init)() = nullptr; + WgHostMenuInitFn plugin_init = nullptr; + }; + std::vector copies; // owncopy: more copies of WrongGPU RR under other file names (build.py stages them) + if (mode == "owncopy") + for (const wchar_t* f : {L"WrongGPU-RR-copy.asi", L"WrongGPU-RR-copy2.asi", L"WrongGPU-RR-copy3.asi", L"WrongGPU-RR-copy4.asi"}) { + Copy c; + c.module = load_asi(f, &c.init, &c.plugin_init); + CHECK(c.module != nullptr && c.init != nullptr && c.plugin_init != nullptr); + if (c.module) copies.push_back(c); + } // ---- the other plugin after ours if (mode == "late") CHECK(or_patch_iat(exe, kWgInterposerFile, 1) >= 6); // wraps our handlers if (mode == "late-replace") CHECK(or_patch_iat(exe, kWgInterposerFile, 0) >= 6); // replaces them // OptiPluginInit (late-replace: the check that finds it, as no call reaches our handlers any more); "late" makes the // first call before it, so that the first call decides - if (mode != "late") plugin_init(&api, host::kOurs); + if (mode == "owncopy") { + // every copy at once: the active copy's OptiPluginInit and the game's first call (16 threads), and in each other + // copy InitializeASI (two threads: the second waits for the first) followed by its OptiPluginInit. All of them + // write wronggpu-rr.log at the same moment; no line may be torn, the other copies register nothing. + std::atomic go{0}, answered{0}, registered{0}; + std::vector th; + auto spawn = [&](auto fn) { + th.emplace_back([&go, fn] { + while (!go.load()) std::this_thread::yield(); + fn(); + }); + }; + spawn([&] { plugin_init(host_api, host::kOurs); }); + for (int i = 0; i < 16; ++i) spawn([&] { answered += slIsFeatureSupported(kOther, nullptr) == kIfaceAnswer; }); + for (const Copy& c : copies) { + spawn([&c, ®istered, host_api] { + c.init(); + registered += c.plugin_init(host_api, host::kOurs) ? 1 : 0; + }); + spawn([&c] { c.init(); }); + } + go.store(1); + for (auto& t : th) t.join(); + CHECK_EQ(answered.load(), 16); + CHECK_EQ(registered.load(), 0); // the other copies register nothing + } else if (mode != "late") { + plugin_init(host_api, host::kOurs); + } // ---- the game's calls - if (mode == "clean" || mode == "late" || mode == "owncopy" || mode == "provider") { + if (mode == "clean" || mode == "late" || mode == "provider") { // 16 threads make the game's first interface call at once const int ok = at_once(16, [] { return slIsFeatureSupported(kOther, nullptr); }, kIfaceAnswer); CHECK_EQ(ok, 16); } - if (mode == "late") plugin_init(&api, host::kOurs); + if (mode == "late") plugin_init(host_api, host::kOurs); std::vector L = read_lines(log_path); printf("log lines %zu, torn %zu\n", L.size(), torn_lines(L)); - CHECK(torn_lines(L) == 0); // 0.6.1: one append call per line, also with two copies + CHECK(torn_lines(L) == 0); // 0.6.1: one append call per line, also with several copies const double load_cost = cost_of(L, "hook: coexistence check at load: "); CHECK(load_cost >= 0.0 && load_cost < 5.0); printf("coexistence check at load: %.3f ms\n", load_cost); - CHECK(count(L, "hook: coexistence check at load: ") == (mode == "owncopy" ? 1u : 1u)); + // the check's result lines (the stay-on line is a second line of the same check); hostsplit: the check runs again + CHECK(count(L, "hook: coexistence check at load: ") - count(L, "hook: coexistence check at load: inconclusive") == + (mode == "hostsplit" ? 2u : 1u)); const long rr_before = os->rr_calls; const WgResultCode rr = slIsFeatureSupported(kRR, nullptr); const bool rr_by_other = os->rr_calls == rr_before + 1; @@ -298,25 +386,75 @@ int main(int argc, char** argv) { CHECK(count(L, "hook: coexistence check at load: no other Ray Reconstruction plugin found (") == 1); CHECK(count(L, "hook: coexistence re-check at the game's first call: no other Ray Reconstruction plugin found (") == 1); CHECK(count(L, "another Ray Reconstruction plugin is active") == 0); + CHECK(count(L, "hook: coexistence check at load: inconclusive") == 0); CHECK(count(L, std::string("hook: patched IAT slot ") + kWgRoleNames[kIsSupported] + " in ") == 1); // only one copy patched CHECK(!rr_by_other); if (mode == "owncopy") { - CHECK(count_starting(L, "a second copy of WrongGPU RR is loaded (") == 1); - CHECK(count(L, std::string(kWgHookFile) + " is active); this copy (") == 1); + CHECK(count_starting(L, "a second copy of WrongGPU RR is loaded (") == copies.size()); // one line per other copy + CHECK(count(L, std::string(kWgHookFile) + " is active); this copy (") == copies.size()); CHECK(count(L, "WrongGPU-RR-copy.asi) stays off") == 1); + CHECK(count(L, "WrongGPU-RR-copy2.asi) stays off") == 1); + CHECK(count(L, "WrongGPU-RR-copy3.asi) stays off") == 1); + CHECK(count(L, "WrongGPU-RR-copy4.asi) stays off") == 1); + // an inactive copy has no calls to summarise: freeing it (DLL_PROCESS_DETACH under the loader lock) writes no + // exit summary (the line would say the calls never reached the plugin); the log lock is only tried there + for (const Copy& c : copies) CHECK(FreeLibrary(c.module)); + CHECK(count(read_lines(log_path), "diag: summary") == 0); } #if !WG_BINDING_PROBE CHECK(count(L, "NGX: RR provider registered with the host") == 1); CHECK(host::ngx_regs == 1 && host::ngx_owner == host::kOurs); + CHECK(GetModuleHandleW(L"wronggpu_runtime.dll") != nullptr); // active: the core loaded the RR runtime +#endif + } else if (mode == "hostsplit") { + // the load check took the host's own patches for another plugin (it ran before the host's table was known: the same + // line as for any plugin), then OptiPluginInit showed that the module holds the host's API table: the load check + // ran again with it as the host, nothing is switched off + CHECK(count_starting(L, stem + self_slot) == 1); + CHECK(count(L, "hook: coexistence check at load: another Ray Reconstruction plugin found (") == 1); + CHECK(count(L, "hook: coexistence check at load: no other Ray Reconstruction plugin found (") == 1); + CHECK(count_starting(L, "hook: the module the load check took for another Ray Reconstruction plugin (wgtest_other_rr.dll) " + "holds the host's API table: it is the host") == 1); + const std::vector L2 = read_lines(log_path); // after the game's first call (made above) + CHECK(count(L2, "hook: coexistence re-check at the game's first call: no other Ray Reconstruction plugin found (") == 1); + CHECK(count(L, std::string("hook: patched IAT slot ") + kWgRoleNames[kIsSupported] + " in ") == 1); + CHECK(count(L2, "took the RR calls after WrongGPU") == 0); + CHECK(!rr_by_other); // RR is WrongGPU's + CHECK_EQ(slIsFeatureSupported(kOther, nullptr), kIfaceAnswer); // the other calls reach the interface +#if !WG_BINDING_PROBE + CHECK(count(L, "NGX: RR provider registered with the host") == 1); + CHECK(host::ngx_owner == host::kOurs); #endif - } else if (mode == "first" || mode == "inline" || mode == "relay" || mode == "anon" || mode == "noaccess" || - mode == "guardpage") { + } else if (stays_on) { + // not a positive finding: logged once as inconclusive, WrongGPU RR stays active (it patched, RR is its own) + const std::string unclear = + mode == "anon" ? self_slot + evaluate_name + " of " + exe_leaf + " leads to code outside every module" + : mode == "exe" ? self_slot + evaluate_name + " of " + exe_leaf + " leads into the exe's own code" + : mode == "hops" ? self_slot + evaluate_name + " of " + exe_leaf + " leads through more than 4 hook jumps" + : self_slot + evaluate_name + " of " + exe_leaf + " could not be read"; + CHECK(count(L, "hook: coexistence check at load: no other Ray Reconstruction plugin found (") == 1); + CHECK(count_starting(L, "hook: coexistence check at load: inconclusive for 1 address(es) (first: " + unclear + + "); no other plugin was positively found, WrongGPU RR stays active") == 1); + CHECK(count(L, "another Ray Reconstruction plugin is active") == 0); + CHECK(count(L, "stays off") == 0); + CHECK(count(L, std::string("hook: patched IAT slot ") + kWgRoleNames[kIsSupported] + " in ") == 1); + CHECK(count(read_lines(log_path), "hook: coexistence re-check at the game's first call: no other Ray Reconstruction plugin found (") == 1); + CHECK(!rr_by_other); + CHECK_EQ(slIsFeatureSupported(kOther, nullptr), kIfaceAnswer); + if (mode == "guardpage") { + MEMORY_BASIC_INFORMATION m; + CHECK(VirtualQuery(odd_page, &m, sizeof m) && (m.Protect & PAGE_GUARD)); // never touched + } +#if !WG_BINDING_PROBE + CHECK(count(L, "NGX: RR provider registered with the host") == 1); + CHECK(host::ngx_owner == host::kOurs); +#endif + } else if (mode == "first" || mode == "inline" || mode == "relay" || mode == "execonly") { const std::string detail = mode == "first" ? self_slot // the first redirected slot in import order; the module is checked below : mode == "inline" ? "the export " + evaluate_name + " of " + iface_leaf + " leads to wgtest_other_rr.dll (through 1 hook jump)" : mode == "relay" ? "the export " + evaluate_name + " of " + iface_leaf + " leads to wgtest_other_rr.dll (through 2 hook jumps)" - : mode == "anon" ? self_slot + evaluate_name + " of " + exe_leaf + " leads to code outside every module" - : self_slot + evaluate_name + " of " + exe_leaf + " could not be read"; + : self_slot + evaluate_name + " of " + exe_leaf + " leads to wgtest_other_rr.dll (through 1 hook jump)"; CHECK(count(L, "hook: coexistence check at load: another Ray Reconstruction plugin found (") == 1); if (take && (mode == "first" || mode == "inline")) { CHECK(count_starting(L, "another Ray Reconstruction plugin is active; rr_other_plugin=take: WrongGPU RR goes in " @@ -345,12 +483,10 @@ int main(int argc, char** argv) { #if !WG_BINDING_PROBE CHECK(count(L, "NGX: RR provider not registered: WrongGPU RR stays off in this process") == 1); CHECK(host::ngx_owner == nullptr); + // off at load: the core is not built, so the RR runtime (staged next to the exe) is never loaded + CHECK(GetModuleHandleW(L"wronggpu_runtime.dll") == nullptr); #endif } - if (mode == "guardpage") { - MEMORY_BASIC_INFORMATION m; - CHECK(VirtualQuery(odd_page, &m, sizeof m) && (m.Protect & PAGE_GUARD)); // never touched - } } else if (late) { CHECK(count(L, "hook: coexistence check at load: no other Ray Reconstruction plugin found (") == 1); CHECK(count(L, std::string("hook: patched IAT slot ") + kWgRoleNames[kIsSupported] + " in ") == 1); diff --git a/clean/rr_f/proxy/tools/build.py b/clean/rr_f/proxy/tools/build.py index 170b8f45..5806c37e 100644 --- a/clean/rr_f/proxy/tools/build.py +++ b/clean/rr_f/proxy/tools/build.py @@ -401,10 +401,12 @@ def test_hook(built, binding, out, logs, probe, n=None, gen=None): # RR guard: the coexistence guard's modes (tests/test_rr_guard_dll.cpp) against our own stand-in "other Ray # Reconstruction plugin" (tests/fake_other_rr.cpp); "route*" modes use the build without an import of the interface -GUARD_MODES_RELEASE = (["clean"], ["first"], ["first", "--take"], ["inline"], ["inline", "--take"], ["relay"], ["anon"], - ["noaccess"], ["guardpage"], ["late"], ["late", "--take"], ["late-replace"], ["provider"], ["owncopy"], - ["route"], ["route-other"], ["route-other", "--take"], ["route-inline"]) -GUARD_MODES_PROBE = (["clean"], ["first"], ["inline"], ["noaccess"], ["late"], ["owncopy"], ["route-other"]) +GUARD_MODES_RELEASE = (["clean"], ["first"], ["first", "--take"], ["inline"], ["inline", "--take"], ["relay"], ["execonly"], + ["anon"], ["noaccess"], ["guardpage"], ["exe"], ["hops"], ["hostsplit"], ["late"], ["late", "--take"], + ["late-replace"], ["provider"], ["owncopy"], ["route"], ["route-other"], ["route-other", "--take"], + ["route-inline"]) +GUARD_MODES_PROBE = (["clean"], ["first"], ["inline"], ["execonly"], ["noaccess"], ["hops"], ["hostsplit"], ["late"], + ["owncopy"], ["route-other"]) def test_guard(built, out, logs, probe, n, gen, iface_dll, implib, iface_name): @@ -430,7 +432,9 @@ def test_guard(built, out, logs, probe, n, gen, iface_dll, implib, iface_name): for f in (exes[noimport], iface_dll, stub): shutil.copy(f, stage) shutil.copy(built, os.path.join(stage, n["proxy_file"])) - shutil.copy(built, os.path.join(stage, "WrongGPU-RR-copy.asi")) # the owncopy mode's second copy + for k in ("", "2", "3", "4"): # the owncopy mode's other copies of WrongGPU RR (separate files, separate images) + shutil.copy(built, os.path.join(stage, f"WrongGPU-RR-copy{k}.asi")) + shutil.copy(stub, os.path.join(stage, "wgtest_loader.dll")) # the hostsplit mode's separate ASI loader (a second image) if not probe: shutil.copy(os.path.join(out, "wronggpu_runtime.dll"), stage) for m in (GUARD_MODES_PROBE if probe else GUARD_MODES_RELEASE): diff --git a/clean/rr_f/proxy/tools/guard_modelm.py b/clean/rr_f/proxy/tools/guard_modelm.py deleted file mode 100644 index 429e6b4a..00000000 --- a/clean/rr_f/proxy/tools/guard_modelm.py +++ /dev/null @@ -1,106 +0,0 @@ -# SPDX-License-Identifier: MIT -"""RR guard: Model M is not affected by WrongGPU RR's coexistence guard (CPU only). - - python clean/rr_f/proxy/tools/guard_modelm.py --fsr-build --rr-out - [--exclude REGEX] [--config Release] - -Runs every test of Model M's own ctest list (clean/fsr: WrongGPU.asi, the front end, the custom slot, the shared -settings), unchanged, once on its own and once per guard mode with WrongGPU RR loaded into the test process before -its main and the guard tripped (tests/guard_inject.cpp starts the program suspended and loads tests/guard_scene.cpp): -none (control: WrongGPU RR loaded, nothing tripped), off, take, owncopy, passthrough. Each guard mode must end exactly -as the control did (passed / skipped / failed), and the scene must have seen WrongGPU RR's line for that mode. A test -whose control differs from its plain run is listed as a note: that difference comes from WrongGPU RR being in the -process at all (e.g. a unit test that must create the process's shared settings block itself), not from the guard. -The stand-ins come from -build.py's guard stage of the 2.14 table (/2.14/hook-test/guard/stage). wronggpu-rr.ini (take) and -wronggpu-rr.log are written next to each test program and removed afterwards (only files this run created). Tests that -use a hardware GPU are excluded by default (fsr_overlay, fsr_dll_d3d12_*). -""" -import argparse -import json -import os -import re -import subprocess -import sys - -HERE = os.path.dirname(os.path.abspath(__file__)) -sys.path.insert(0, HERE) -import build # noqa: E402 - -MODES = ("none", "off", "take", "owncopy", "passthrough") - - -def main(): - ap = argparse.ArgumentParser() - ap.add_argument("--fsr-build", required=True) - ap.add_argument("--rr-out", default=build.DEFAULT_OUT) - ap.add_argument("--config", default="Release") - ap.add_argument("--exclude", default=r"^(fsr_overlay|fsr_dll_d3d12.*)$") - a = ap.parse_args() - hook_test = os.path.join(a.rr_out, "2.14", "hook-test") - stage = os.path.join(hook_test, "guard", "stage") - gen = os.path.join(hook_test, "gen") - if not os.path.isfile(os.path.join(stage, "wgtest_other_rr.dll")): - raise SystemExit(f"no guard stage in {stage}: run build.py first") - tools = os.path.join(a.rr_out, "guard-modelm") - os.makedirs(tools, exist_ok=True) - scene = os.path.join(tools, "guard_scene.dll") - inject = os.path.join(tools, "guard_inject.exe") - build.sh(f'cl {build.CLFLAGS} /LD /I"{gen}" {build.src("tests", "guard_scene.cpp")} /Fo"{tools}\\\\" /Fe"{scene}"', - tools) - build.sh(f'cl {build.CLFLAGS} {build.src("tests", "guard_inject.cpp")} /Fo"{tools}\\\\" /Fe"{inject}"', tools) - listing = build.sh(f'ctest --test-dir "{a.fsr_build}" -C {a.config} --show-only=json-v1', tools) - tests = json.loads(listing[listing.index("{"):])["tests"] - exclude = re.compile(a.exclude) - rows, failures, presence = [], 0, [] - for t in tests: - props = {p["name"]: p["value"] for p in t.get("properties", [])} - if exclude.search(t["name"]) or props.get("DISABLED") or "command" not in t: - continue - cmd, wd = t["command"], props.get("WORKING_DIRECTORY", os.path.dirname(t["command"][0])) - skip = int(props.get("SKIP_RETURN_CODE", -1)) if "SKIP_RETURN_CODE" in props else None - exe_dir = os.path.dirname(cmd[0]) - ini, log = os.path.join(exe_dir, "wronggpu-rr.ini"), os.path.join(exe_dir, "wronggpu-rr.log") - if os.path.exists(ini) or os.path.exists(log): - raise SystemExit(f"{exe_dir} already has wronggpu-rr.ini / wronggpu-rr.log: not touched, stopping") - - def outcome(rc): - return "skipped" if skip is not None and rc == skip else "passed" if rc == 0 else f"failed ({rc})" - - plain = subprocess.run(cmd, cwd=wd, capture_output=True, text=True, timeout=600) - row = [t["name"], outcome(plain.returncode)] - control = None # the "none" run: WrongGPU RR in the process, the guard not tripped - for mode in MODES: - if mode == "take": - with open(ini, "w") as f: - f.write("rr_other_plugin = take\n") - try: - r = subprocess.run([inject, scene, stage, mode] + cmd, cwd=wd, capture_output=True, text=True, timeout=600) - finally: - if os.path.exists(ini): - os.remove(ini) - got = outcome(r.returncode) - seen = f"guard_inject: ok {mode}" in r.stdout - if mode == "none": - control = got - if got != row[1]: # WrongGPU RR's presence itself, before any guard decision - presence.append((t["name"], row[1], got, (r.stdout + r.stderr).strip().splitlines()[-3:])) - # a guard mode must end exactly as the control does (the guard changes nothing for Model M) - same = got == control and seen - failures += not same - row.append(got if same else f"{got}{'' if seen else ', scene: ' + r.stderr.strip()[-200:]} <-- DIFFERS") - if os.path.exists(log): - os.remove(log) - rows.append(row) - print("test".ljust(34) + "plain".ljust(12) + "".join(m.ljust(14) for m in MODES)) - for row in rows: - print(row[0].ljust(34) + row[1].ljust(12) + "".join(c.ljust(14) for c in row[2:])) - print(f"{len(rows)} Model M test(s) x {len(MODES) - 1} guard mode(s) against the control: {failures} difference(s)") - for name, p, c, tail in presence: - print(f"note: {name}: {p} alone, {c} with WrongGPU RR in the process before any guard decision (control); " - f"the guard modes match the control. Last lines: {' | '.join(tail)}") - return 1 if failures else 0 - - -if __name__ == "__main__": - sys.exit(main()) From 7ef3a340cda4675b3348ead0f82a6aff49fdaf90 Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:16:00 -0500 Subject: [PATCH 3/4] RR plugin guard: switch off only on contract evidence; a named module is inconclusive WrongGPU RR now switches itself off only on evidence that is positive by contract: a second copy of WrongGPU RR, or the host's plugin API refusing our registration (NGX provider slot taken, game-interface routes refused). A named module on the RR call path (a game's wrapper DLL, an overlay, a host helper, a forwarded export's implementation DLL, or another RR plugin) is inconclusive: RR stays active as in 0.6.0 and one line names the module and the place ("another module hooks the game's RR calls: (...)"). - rr_other_plugin = off (default) | take | yield. take goes in front of a module found at load or under our host routes and never switches RR off; yield keeps RR off whenever a named module is on the path. The policy is one table, rr_guard::decide. - The host guess (caller of InitializeASI, module of the API table) only shapes the wording; the load-check re-run is removed, so no misleading "stays off" line can remain. - The late check reports only exports that changed since the load check. - Another module's PE headers: e_lfanew, data directories and every RVA the walk follows are checked against SizeOfImage before an address is formed (PeView); jump targets are integer arithmetic. - Docs: the guard-page race and the log lock's best effort after a timeout are described instead of claimed away. - Tests: test_rr_guard covers the decide table for six layouts without a second RR provider, the own-copy cases and the PE bounds; test_rr_guard_dll adds wrapper, wrapper --yield, overlay, forward, helper, heaptable, helpertable, route-other --yield and route-refused, and the existing modes now expect "stays active" plus the one line. Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> --- clean/rr_f/proxy/HOOK-MODE.md | 202 +++++---- clean/rr_f/proxy/src/hook_dll.cpp | 298 ++++++------- clean/rr_f/proxy/src/log_append.h | 4 +- clean/rr_f/proxy/src/rr_guard.cpp | 153 +++++-- clean/rr_f/proxy/src/rr_guard.h | 125 ++++-- clean/rr_f/proxy/tests/fake_other_rr.cpp | 24 +- clean/rr_f/proxy/tests/test_hook_dll.cpp | 7 +- clean/rr_f/proxy/tests/test_rr_guard.cpp | 187 ++++++-- clean/rr_f/proxy/tests/test_rr_guard_dll.cpp | 426 +++++++++++-------- clean/rr_f/proxy/tools/build.py | 23 +- 10 files changed, 921 insertions(+), 528 deletions(-) diff --git a/clean/rr_f/proxy/HOOK-MODE.md b/clean/rr_f/proxy/HOOK-MODE.md index afd4d9ad..d1595a4b 100644 --- a/clean/rr_f/proxy/HOOK-MODE.md +++ b/clean/rr_f/proxy/HOOK-MODE.md @@ -118,118 +118,136 @@ the display adapter's PCI identity through SetupAPI as well as DXGI; with the ho ## Another Ray Reconstruction plugin (0.6.1) A player can end up with two RR plugins in one game (an integrator's installer may put this plugin next to another -one; the launcher is not involved then). Default: **when another RR plugin is positively found, WrongGPU RR stays off -and says so in one line**; Model M is not touched. The guard is generic and read-only (`src/rr_guard.{h,cpp}`, wired in +one; the launcher is not involved then). The guard is generic and read-only (`src/rr_guard.{h,cpp}`, wired in `src/hook_dll.cpp`): it looks at where the game's RR calls lead, never at another plugin's files or internals. Release -and probe builds behave the same. +and probe builds behave the same. Model M is never touched. -**What counts as a finding.** Only a positive sign stops the plugin: an address that ends in **another named module** -(directly, or through decoded hook jumps), or in **a second copy of WrongGPU RR**. Anything the scan cannot explain is -**not** a sign of another plugin: it is logged once as inconclusive (see "Log lines") and WrongGPU RR **stays active**. +**When WrongGPU RR switches itself off.** Only on evidence that is positive by contract: +- **a second copy of WrongGPU RR** (below, "Counting as WrongGPU"); +- **the host's plugin API** saying its RR provider slot is taken (the NGX route), or refusing our game-interface routes. -**Signals, most reliable first** (each address is classified: this module, the game interface, the host = the module -that called `InitializeASI` and the module holding the host's API table, a copy of WrongGPU RR, another WrongGPU module, -the exe, code outside every module, another module; hook jumps are followed out of the interface and out of anonymous -memory, at most 4 of them per address; a fifth is "too many hops", inconclusive): +Nothing else switches RR off on its own. In particular a **named module on the call path is inconclusive**: it may be +another RR plugin, but it may as well be a game's own wrapper DLL, an overlay, a security shim, a host helper in a +third image, a forwarded export's implementation DLL or an API-set target. WrongGPU RR then **stays active, as in +0.6.0**, and one line names the module and the place (see "Log lines"), so a bug report shows it. The player decides +with `rr_other_plugin` (below). + +**Signals** (each address is classified: this module, the game interface, the host, a copy of WrongGPU RR, another +WrongGPU module, the exe, code outside every module, another module; hook jumps are followed out of the interface and +out of anonymous memory, at most 4 of them per address; a fifth is "too many hops", inconclusive): 1. **A second copy of WrongGPU RR** (`S0`): a process-wide marker (`Local\WrongGPU.rr-active.v1.`, holding the active copy's path) taken at `InitializeASI`; a copy that finds it taken starts nothing (no hook, routes, NGX - provider, menu box, SetupAPI shim). A slot or export that leads into a module counting as WrongGPU RR (below) is the - same case. + provider, menu box, SetupAPI shim). A slot or export that leads into a module counting as WrongGPU RR is the same + case. 2. **Import slots** (`S1`): before anything is patched, every loaded module's import slots of the game interface for - the roles this build would patch (and the exe's delay-load slots) are read. A slot that leads into another named - module is a finding; a slot that leads into the interface, the host, another WrongGPU module (or, for a delay slot - not bound yet, the exe's own thunk) is fine; any other slot is inconclusive. + the roles this build would patch (and the exe's delay-load slots) are read. A slot that leads into the interface, + the host, another WrongGPU module (or, for a delay slot not bound yet, the exe's own thunk) is fine; a slot that + leads into another named module is named; anything else is inconclusive. 3. **The RR exports' first bytes** (`S2`): the exports of is-supported, get-function, allocate and evaluate are read: - a jump out of the interface that ends in another named module is a finding (`jmp rel32/rel8`, `jmp [rip+disp32]`, + a jump out of the interface that ends in another named module is named (`jmp rel32/rel8`, `jmp [rip+disp32]`, `mov rax|r11, imm64; jmp reg`; a `jmp [rip]` through the interface's own import table is its own code). The init export is not read: the host patches it itself. 4. **Host routes** (plugin interface 3): `S2` on the module the host hooked (the host's trampolines, code outside every - module, are accepted there), then each route's next function (the host's `next`) after registering: another - plugin's route under ours leads to that plugin. Our routes cannot be taken back: they pass every call on. + module, are accepted there), then each route's next function (the host's `next`) after registering. Our routes are + in front and cannot be taken back. A refused registration keeps the game-interface route off. 5. **The NGX route** (plugin interface 4): the host keeps one RR provider; a refused registration means another - provider holds it, **for the NGX route only** (the game-interface route goes by its own signals). -6. **Later plugins** (`S4`): a plugin that loads after ours is found at `OptiPluginInit` and at the game's first call - into any of our handlers (decided once: concurrent first calls wait for the one decision): a slot we patched that - no longer holds our handler, or (while active) an RR export that now jumps away. Our handlers then pass every call - on unchanged (to the genuine export, which carries any later patch), and the NGX provider refuses creates. - -**Load orders.** Ours second: found at load, nothing patched, the core and the runtime are not loaded, no NGX provider. -Ours first: found at `OptiPluginInit` or the game's first call; pass-through from then on (the runtime is loaded but no -RR instance exists). Both late (run-time interface): the host-route checks above. The SetupAPI identity shim (not part -of the RR path) runs as configured while WrongGPU RR stays off because of another plugin; a second copy starts nothing. - -**Never a crash, and a positive finding only.** Every read of memory we do not own (slot values, export bytes, jump -cells, the host's next pointers, the module headers the scan walks) goes through `rr_guard`'s safe read: `VirtualQuery` -for committed, readable, non-guard pages (execute-only pages count as readable: code is read from them), then a -structured-exception-guarded copy (a cached region is re-checked by the exception guard). A failed read is **unknown**. -Unknown is not a finding. Only the positive findings above stop the plugin. These are **inconclusive**: they are -counted, one diagnostic line names the first of them, and WrongGPU RR stays active: + provider holds it: **the NGX route stays off** (the game-interface route goes by its own signals). +6. **Later modules** (`S4`): a module that hooks after ours is looked for at `OptiPluginInit` and at the game's first + call into any of our handlers (decided once: concurrent first calls wait for the one decision): a slot we patched + that no longer holds our handler, or (while active) an RR export that now jumps somewhere else than at load. + +**The host.** The host is taken to be the module that called `InitializeASI` and also the module holding the host's API +table (`OptiPluginInit`). Their own patches are accepted and not named. This is a guess (a separate ASI loader may call +`InitializeASI`; the table may live on the heap or in a helper image), so it is used for the log's wording only: with +the default setting a wrong guess can no longer switch RR off. + +**Override** (`wronggpu-rr.ini` next to the game exe), `rr_other_plugin =`: +- `off` (the default; also any unknown value, with a line): only the positive evidence above switches WrongGPU RR off; a + named module is logged and WrongGPU RR stays active (it patches over a slot that leads to the module, its handlers + continue to the genuine export, as in 0.6.0). +- `take`: as `off`, and with a module named at load (or below our host routes) WrongGPU RR goes in front of it and + continues the other calls of the same functions through what the slot held before (that module), so it sees the + game's other calls but never an RR create: one RR evaluate per frame. A module that hooks after ours is only named + (we never patch again; no patch fights). `take` never switches WrongGPU RR off. +- `yield`: WrongGPU RR stays off whenever any named module is on the path: found at load, nothing is patched (the core + and the runtime are not loaded, no NGX provider); found later or below our host routes, our handlers pass every call + on unchanged and the NGX provider refuses creates. + +**Load orders** (with `yield`, or a second copy). Ours second: found at load, nothing patched. Ours first: found at +`OptiPluginInit` or the game's first call; pass-through from then on (the runtime is loaded but no RR instance exists). +Both late (run-time interface): the host-route checks above. The SetupAPI identity shim (not part of the RR path) runs +as configured; a second copy starts nothing. + +**Reads of memory we do not own.** Every read (slot values, export bytes, jump cells, the host's next pointers, the +module headers the scan walks) goes through `rr_guard`'s safe read: `VirtualQuery` for committed, readable, non-guard +pages (execute-only pages count as readable: code is read from them), then a structured-exception-guarded copy. A +failed read is **unknown**. The check and the copy are not one atomic step: if another thread unmaps or reprotects a +page in between, an access fault is caught (unknown), but a page made a guard page in that moment is touched and loses +its one-shot guard state. The cached region of the header walk is not queried again (only the exception guard covers +it). Another module's PE headers are used only after `e_lfanew`, every data directory and every RVA the walk follows +are checked against `SizeOfImage` (integers first, no address formed from an unchecked value); a header or table that +fails is treated as nothing found there. These are **inconclusive** (counted, one diagnostic line names the first, +WrongGPU RR stays active): - memory that cannot be read (an import slot, an export, a jump cell, a PAGE_NOACCESS or guard page, a null pointer); - a jump chain longer than 4 hops; - code outside every module that does not jump on (a game's copy protection or a hooking library's trampoline may sit there); - a slot or export that leads into the exe's own code (a delay-load helper's thunk, or a game's own wrapper). -**Fail-open cases (known).** The guard does not see these, so WrongGPU RR stays active next to such a plugin: a plugin -hooks after the game's first call (the late check runs at `OptiPluginInit` and once, at the first call, and never -again); inline hooks in forms other than the jump forms above (for example a hook placed deeper than the first bytes of -the export, or through a different instruction sequence); a plugin that hooks the function pointers the game-interface's -get-function export returns. In these cases the other plugin and WrongGPU RR may both answer RR and the log shows no -finding; remove the other plugin. - -**False positives, known and accepted.** A mod that is not an RR plugin but hooks the interface's RR functions so that -its code lives in a named module (for example a frame-generation mod working through the same functions) makes WrongGPU -RR stay off too: the line names its module and `rr_other_plugin=take` puts WrongGPU RR back. Not triggers: the game's -own RR (the calls lead into the interface), the host's own init patch, WrongGPU.asi, a second copy of WrongGPU RR (its -own line). The host is the module that called `InitializeASI` and also the module holding the host's API table -(`OptiPluginInit`): with a separate ASI loader the host's own patches look like another plugin at the load check, which -runs before the table is known. When `OptiPluginInit` then shows that the module named at load holds the host's table, a -`the module the load check took for another Ray Reconstruction plugin (...) holds the host's API table` line follows and -the load check runs again with that module as the host (nothing was patched before); the earlier "stays off" line stays -in the log. - -**Override** (`wronggpu-rr.ini` next to the game exe): `rr_other_plugin = off` (default; also any unknown value, with a -line) or `take`. `take` with a plugin found at load: WrongGPU RR patches on top, answers the RR calls itself and -continues the other calls of the same functions through what the slot held before (the other plugin), so the other -plugin sees the game's other calls but never an RR create: one RR evaluate per frame. In host-route mode the same -through the host's next functions. `take` cannot be applied to a plugin that loads after ours (we never patch again; -no patch fights), to the NGX route, or to a second copy of WrongGPU RR. +**What the guard does not see (known).** A module that hooks after the game's first call (the late check runs at +`OptiPluginInit` and once, at the first call, and never again); inline hooks in forms other than the jump forms above +(for example deeper than the first bytes of the export); hooks on the function pointers the game-interface's +get-function export returns. Such a module is not named; with another RR plugin among them, both may answer RR. **Counting as WrongGPU.** A module counts as a copy of WrongGPU RR when it exports `WrongGPU_GetSettingsContract` -(the 60.9 contract export), and as another WrongGPU module (accepted, never "another plugin") when it exports -`WrongGpuAsiQuery` (WrongGPU.asi). The launcher can use the same exports to recognise WrongGPU's files. - -**Log lines** (`wronggpu-rr.log`, after the time stamp; the probe log adds `f=`). The launcher's Last run page -matches the **beginnings** of the first three; keep them exactly: -- `another Ray Reconstruction plugin is active; WrongGPU RR stays off (; nothing patched; rr_other_plugin=take in wronggpu-rr.ini uses WrongGPU's instead)` (found at load); - with host routes already installed: `...; WrongGPU's handlers pass every call on unchanged; rr_other_plugin=take ...)`; - found later: `another Ray Reconstruction plugin is active; WrongGPU RR stays off (; it loaded after WrongGPU: WrongGPU passes every call on unchanged; to use WrongGPU RR, move it aside)`; - NGX route: `another Ray Reconstruction plugin is active; WrongGPU RR stays off (NGX route only: the host refused WrongGPU's RR provider, another provider holds it; the game-interface route is decided on its own)`. +(the 60.9 contract export), and as another WrongGPU module (accepted, never named) when it exports `WrongGpuAsiQuery` +(WrongGPU.asi). The launcher can use the same exports to recognise WrongGPU's files. + +**Log lines** (`wronggpu-rr.log`, after the time stamp; the probe log adds `f=`). A reader such as the launcher's +Last run page can match these **beginnings**; keep them exactly: +- `another module hooks the game's RR calls: (); ` with `` one of + - `it is not known to be a Ray Reconstruction plugin: WrongGPU RR stays active (rr_other_plugin=yield in wronggpu-rr.ini keeps WrongGPU RR off in this case)` (`off`; also `take` for a module that hooked after ours); + - `rr_other_plugin=take: WrongGPU RR goes in front of it (it gets the game's other calls, no RR work)`; + - `rr_other_plugin=yield: WrongGPU RR stays off (nothing patched)` (found at load) or + `rr_other_plugin=yield: WrongGPU RR stays off (WrongGPU's handlers pass every call on unchanged)` (later). + The launcher can say "another module hooks the game's RR calls: ``" from it. One such line per check that + names a module (the first module found; at the late checks once per run). - `a second copy of WrongGPU RR is loaded ( is active); this copy () stays off` -- `a plugin loaded after WrongGPU replaced its hooks; rr_other_plugin=take cannot be applied: WrongGPU RR stays off and passes every call on unchanged (); move it aside to use WrongGPU RR` -- with take, found at load (RR is on): `another Ray Reconstruction plugin is active; rr_other_plugin=take: WrongGPU RR goes in front of it (; it gets the game's other calls, no RR work)` - -`` names the place and the module file of a positive finding, e.g. `the import slot of Game.exe leads to -Other.asi`, `the export of leads to Other.asi (through 2 hook jumps)`. Diagnostics (not -matched): `hook: coexistence check at load: ( address(es) read in ms)` once per run (with its measured -cost), `hook: coexistence re-check at : ...`, `NGX: RR provider not registered: WrongGPU RR stays off in this -process (see the line above)`, and the stay-on line `hook: coexistence check : inconclusive for address(es) -(first: could not be read | leads to code outside every module | leads into the exe's own code | leads through -more than 4 hook jumps); no other plugin was positively found, WrongGPU RR stays active` (it starts with `hook: `, never -with a matched beginning above). - -**Tests** (CPU only): `tests/test_rr_guard.cpp` (safe reads on PAGE_NOACCESS, reserved, guard and execute-only pages and a -page made unreadable after caching; every jump form; synthetic modules; exactly 4 hops followed and a fifth one too -many; which classifications are findings and which are inconclusive; 32 threads at one decision); -`tests/test_rr_guard_dll.cpp` with our own stand-in other plugin `tests/fake_other_rr.cpp` (modes clean, first, inline, -relay, execonly, anon, noaccess, guardpage, exe, hops, hostsplit, late, late-replace, provider, owncopy, route, -route-other, route-inline; `--take`; 16 threads at the first call): the foreign-module modes switch off (release: the -RR runtime is then not loaded; in clean it is); anon, noaccess, -guardpage, exe and hops log the inconclusive line and stay active; hostsplit has a separate loader DLL call -`InitializeASI` while the real host's DLL holds the API table; owncopy loads four more copies and runs their -`InitializeASI` / `OptiPluginInit` from threads while 16 game threads make the first call, then checks that no line is -torn and that freeing an inactive copy writes no exit summary; build.py repeats owncopy 200 times. Run for every interface -version, release and probe (build.py); the existing hook runs check that no guard line appears. +- `another Ray Reconstruction plugin is active; WrongGPU RR stays off (NGX route only: the host refused WrongGPU's RR provider, another provider holds it; the game-interface route is decided on its own)` + +`` names the place, e.g. `the import slot of Game.exe leads to Other.dll`, `the export of + leads to Other.dll (through 2 hook jumps)`, `the import slot of Game.exe (WrongGPU's hook) +leads to Other.dll` (after ours). Diagnostics (all starting with `hook: ` or `NGX: `, never with a beginning above): +`hook: coexistence check at load: ( address(es) read in ms)` once per run (with its measured cost; +`` is `no other Ray Reconstruction plugin found`, `another module on the RR path (inconclusive)` or `a second +copy of WrongGPU RR found`), `hook: coexistence re-check at : ...`, `hook: the host refused our game-interface +routes; nothing was patched: WrongGPU RR stays off on the game-interface route`, `NGX: RR provider not registered: +WrongGPU RR stays off in this process (see the line above)`, and the stay-on line `hook: coexistence check : +inconclusive for address(es) (first: could not be read | leads to code outside every module | leads into the +exe's own code | leads through more than 4 hook jumps); no other plugin was positively found, WrongGPU RR stays active`. + +**The log with two copies.** Every line is one `WriteFile` on a `FILE_APPEND_DATA` handle (`src/log_append.h`), which +the system appends as one piece, so two copies' lines do not run into each other. The size check and the rotation run +under a process-wide named mutex; its wait is bounded (`kLogLockWaitMs`; no wait at all at process exit, under the loader lock). After a +timeout, or when the mutex cannot be created, a copy writes **without** it and does not rotate: the line is still one +append, but it may land in the file the other copy is just moving aside (`wronggpu-rr.log.old`). The serialisation is +best effort after a timeout, not a guarantee. + +**Tests** (CPU only, run by build.py and CI): `tests/test_rr_guard.cpp` (safe reads on PAGE_NOACCESS, reserved, guard +and execute-only pages and a page made unreadable after caching; PE header and directory bounds against SizeOfImage; +every jump form; synthetic modules; exactly 4 hops followed and a fifth one too many; the whole `decide` table: with no +second RR provider (a game-owned wrapper DLL, a host helper in a third image, an overlay-style wrapper, a forwarded +export, the heap-table and helper-table host layouts) RR stays active at every stage unless `yield`, `take` never +switches off, a copy of WrongGPU RR switches off in every mode; 32 threads at one decision); +`tests/test_rr_guard_dll.cpp` with our own stand-in `tests/fake_other_rr.cpp` (also staged under other file names as +innocent modules): the named-module modes (first, inline, relay, execonly, wrapper, overlay, forward, helper, +hostsplit, heaptable, helpertable, late, late-replace, route-other, route-inline) keep WrongGPU RR active and log the +one line (release: the RR runtime is loaded, the NGX provider is ours); `wrapper --yield` stays off with nothing +patched and the runtime not loaded; `route-other --yield` passes every call on; `--take` goes in front; owncopy (four +more copies, from threads, while 16 game threads make the first call; no torn line; no exit summary from an inactive +copy; build.py repeats it 200 times), provider (the NGX route stays off) and route-refused (the game-interface route +stays off) switch off; anon, noaccess, guardpage, exe and hops log the inconclusive line and stay active. Run for every +interface version, release and probe (build.py); the existing hook runs check that no guard line appears. ## Unload diff --git a/clean/rr_f/proxy/src/hook_dll.cpp b/clean/rr_f/proxy/src/hook_dll.cpp index 5313b19b..f3ecabf2 100644 --- a/clean/rr_f/proxy/src/hook_dll.cpp +++ b/clean/rr_f/proxy/src/hook_dll.cpp @@ -39,14 +39,16 @@ // // RR guard: the coexistence guard (rr_guard.h, HOOK-MODE.md "Another Ray Reconstruction plugin"). Before // anything is patched, the plugin reads where the game's RR calls lead (the import slots it would patch, the first bytes -// of the interface's RR exports, in host-route mode the host's continuation pointers). When they lead to another -// plugin, WrongGPU RR stays off (nothing patched, no NGX provider) and logs one line; a second copy of WrongGPU RR -// stays off too. A plugin that takes the calls after ours is found at OptiPluginInit or at the game's first call -// (decided once): our handlers then pass every call on unchanged. wronggpu-rr.ini rr_other_plugin=take puts WrongGPU RR -// in front of a plugin found at load. Every read of memory we do not own goes through rr_guard's safe reads. +// of the interface's RR exports, in host-route mode the host's continuation pointers); after its handlers are in place +// it reads them again at OptiPluginInit and at the game's first call (decided once). WrongGPU RR switches itself off +// only on evidence that is positive by contract: a second copy of WrongGPU RR, or the host's plugin API refusing our +// registration (the NGX provider slot taken, our routes refused). A named foreign module on the path is inconclusive: +// RR stays active and one line names the module and the place. wronggpu-rr.ini rr_other_plugin=yield makes such a +// module switch WrongGPU RR off; take puts WrongGPU RR in front of it. rr_guard::decide holds the policy. Every read of +// memory we do not own goes through rr_guard's safe reads. #define WIN32_LEAN_AND_MEAN #include -#include // RR guard: _ReturnAddress (the module that calls InitializeASI is the host) +#include // RR guard: _ReturnAddress (the module that calls InitializeASI is taken as the host) #include #include // NGX route: the device under a command list (a COM call only; no library) #include // clean/rr-sl-diag: the adapter of a LUID in the diagnostics (system dxgi.dll loaded at run time) @@ -143,17 +145,16 @@ std::atomic g_host_api_plugin{nullptr}; std::mutex g_host_restore_mutex; // RR guard (rr_guard.h): the guard's state for this process, the override, and the pass-through targets wgrr::guard::Decision g_guard; -// g_take, g_host_module, g_host_api_module and g_fwd are written on the host's callback thread (OptiPluginInit, the +// g_mode, g_host_module, g_host_api_module and g_fwd are written on the host's callback thread (OptiPluginInit, the // host's hook callback) and read by the game's threads (the handlers, the late check): atomics, published with release -std::atomic g_take{false}; // wronggpu-rr.ini rr_other_plugin=take +std::atomic g_mode{0}; // wronggpu-rr.ini rr_other_plugin (wgrr::guard::Mode) std::atomic g_hook_done{false}; // our handlers are installed: the late check may run -std::atomic g_host_module{nullptr}; // the module that called InitializeASI (taken as the host) -std::atomic g_host_api_module{nullptr}; // the module holding the host's API table (when another module) -// the module the first positive finding of a "stays off" load decision led to: when OptiPluginInit then shows that this -// module holds the host's API table (a separate loader called InitializeASI, and the real host's own patches were taken -// for another plugin), the load decision runs again with it as the host (see OptiPluginInit) -std::atomic g_load_off_module{nullptr}; -std::atomic g_load_rerun_done{false}; +// The host as far as the plugin can tell: the module that called InitializeASI and the module holding the host's API +// table. Used to accept the host's own patches and for the log's wording only: a wrong guess can no longer switch RR +// off (a named module is inconclusive unless rr_other_plugin=yield). +std::atomic g_host_module{nullptr}; +std::atomic g_host_api_module{nullptr}; // (when another module than the caller of InitializeASI) +std::atomic g_late_foreign_logged{false}; // the late check names a foreign module once per run // g_prev is written once by guard_at_load on the thread that then builds the core (do_hook): no other thread reads it // before the core exists (bind() runs inside the core's construction), so it stays a plain array void* g_prev[32] = {}; // take: what the exe's import slots held before us (the other plugin), by role @@ -346,7 +347,8 @@ void bind(F& slot, int role) { slot = reinterpret_cast(g_route_next[role]); // host route: continue through the host's chain return; } - if (g_take.load() && g_prev[role]) { // RR guard, take: continue through the other plugin (it sees no RR work) + if (g_guard.state() == wgrr::guard::State::kTaken && g_prev[role]) { // RR guard, take: continue through the + // other module (it sees no RR work) slot = reinterpret_cast(g_prev[role]); return; } @@ -1144,7 +1146,7 @@ DWORD WINAPI slot_watch_thread(void*) { return 0; } -// ---------------------------------------------------------------- RR guard: another RR plugin (rr_guard.h) +// ---------------------------------------------------------------- RR guard: other modules on the RR path (rr_guard.h) // The roles whose exports' first bytes are read (S2): the ones that decide where RR goes. The init export is not among // them: the host patches it itself (HOOK-MODE.md). const int kWgDecisiveRoles[] = {2, 7, 8, 16}; // is-supported, get-function, allocate, evaluate @@ -1176,36 +1178,41 @@ int role_for_name(const char* name) { return -1; } +// The by-name entries of one import (or delay-load) name table: f(role, import name, slot address) for each that names +// a hooked role. Every RVA (the name table, the address table, each name) is checked against the image's size (PeView) +// before an address is formed from it; an entry outside the image ends the walk (nothing found there). +template +void guard_thunks(const wgrr::guard::PeView& pe, wgrr::guard::Reader& r, uint32_t names_rva, uint32_t iat_rva, F f) { + for (unsigned i = 0; i < 4096; ++i) { + const uint64_t off = (uint64_t)i * sizeof(IMAGE_THUNK_DATA64); + const uint8_t* np = pe.at(names_rva + off, sizeof(IMAGE_THUNK_DATA64)); + const uint8_t* sp = pe.at(iat_rva + off, sizeof(IMAGE_THUNK_DATA64)); + IMAGE_THUNK_DATA64 t; + if (!np || !sp || !r.get(np, &t) || !t.u1.AddressOfData) return; + if (t.u1.Ordinal & IMAGE_ORDINAL_FLAG64) continue; + const uint8_t* by = pe.at(t.u1.AddressOfData, offsetof(IMAGE_IMPORT_BY_NAME, Name) + 1); + char nm[96]; + if (!by || !r.str(by + offsetof(IMAGE_IMPORT_BY_NAME, Name), nm, sizeof nm)) continue; + const int role = role_for_name(nm); + if (role >= 0) f(role, nm, const_cast(reinterpret_cast(sp))); + } +} + // Every import slot of `module` that names a hooked role from the DLL `leaf`, read through the guard's reader: f(role, // import name, slot address). template void guard_import_slots(HMODULE module, const char* leaf, wgrr::guard::Reader& r, F f) { - const uint8_t* base = reinterpret_cast(module); - IMAGE_DOS_HEADER dos; - IMAGE_NT_HEADERS64 nt; - if (!r.get(base, &dos) || dos.e_magic != IMAGE_DOS_SIGNATURE || !r.get(base + dos.e_lfanew, &nt) || - nt.Signature != IMAGE_NT_SIGNATURE || nt.OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) - return; - const IMAGE_DATA_DIRECTORY& d = nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; - if (!d.VirtualAddress || !d.Size) return; - const IMAGE_IMPORT_DESCRIPTOR* desc = reinterpret_cast(base + d.VirtualAddress); + wgrr::guard::PeView pe; + uint32_t rva = 0, size = 0; + if (!pe.open(module, r) || !pe.dir(IMAGE_DIRECTORY_ENTRY_IMPORT, &rva, &size)) return; for (unsigned k = 0; k < 4096; ++k) { + const uint8_t* dp = pe.at(rva + (uint64_t)k * sizeof(IMAGE_IMPORT_DESCRIPTOR), sizeof(IMAGE_IMPORT_DESCRIPTOR)); IMAGE_IMPORT_DESCRIPTOR e; - if (!r.get(desc + k, &e) || !e.Name) return; + if (!dp || !r.get(dp, &e) || !e.Name) return; + const uint8_t* np = pe.at(e.Name, 1); char dll[64]; - if (!r.str(base + e.Name, dll, sizeof dll) || _stricmp(dll, leaf) != 0) continue; - const IMAGE_THUNK_DATA64* names = - reinterpret_cast(base + (e.OriginalFirstThunk ? e.OriginalFirstThunk : e.FirstThunk)); - const IMAGE_THUNK_DATA64* iat = reinterpret_cast(base + e.FirstThunk); - for (unsigned i = 0; i < 4096; ++i) { - IMAGE_THUNK_DATA64 t; - if (!r.get(names + i, &t) || !t.u1.AddressOfData) break; - if (t.u1.Ordinal & IMAGE_ORDINAL_FLAG64) continue; - char nm[96]; - if (!r.str(base + t.u1.AddressOfData + offsetof(IMAGE_IMPORT_BY_NAME, Name), nm, sizeof nm)) continue; - const int role = role_for_name(nm); - if (role >= 0) f(role, nm, const_cast(reinterpret_cast(&iat[i].u1.Function))); - } + if (!np || !r.str(np, dll, sizeof dll) || _stricmp(dll, leaf) != 0) continue; + guard_thunks(pe, r, e.OriginalFirstThunk ? e.OriginalFirstThunk : e.FirstThunk, e.FirstThunk, f); } } @@ -1245,12 +1252,14 @@ bool guard_claim_marker() { void guard_read_override() { ensure_settings(); std::string note; - g_take.store(wgrr::guard::override_take(g_settings.text(wgrr::guard::kOverrideKey), ¬e)); + g_mode.store((int)wgrr::guard::parse_mode(g_settings.text(wgrr::guard::kOverrideKey), ¬e)); if (!note.empty()) log_line("hook: " + note); } +wgrr::guard::Mode guard_mode() { return static_cast(g_mode.load()); } // The guard's view of the process: the module that called InitializeASI and the one holding the host's API table are -// both the host (a separate ASI loader may be the first, OptiScaler the second). +// both taken as the host (a separate ASI loader may be the first, OptiScaler the second): their own patches are +// accepted and not named. A wrong guess only changes the wording (a named module is inconclusive). wgrr::guard::Env guard_env(const void* iface) { return wgrr::guard::process_env(g_self, iface, g_host_module.load(), g_host_api_module.load()); } @@ -1260,21 +1269,67 @@ void guard_log_unclear(const char* when, const wgrr::guard::Verdict& v) { if (v.unclear) log_line(wgrr::guard::line_inconclusive(when, v.unclear, v.unclear_detail)); } +// The result words of a check's summary line +const char* guard_result(const wgrr::guard::Verdict& v) { + return v.kind == wgrr::guard::Verdict::kClean ? "no other Ray Reconstruction plugin found" + : v.kind == wgrr::guard::Verdict::kOwnCopy ? "a second copy of WrongGPU RR found" + : "another module on the RR path (inconclusive)"; +} + +// Applies decide() to a verdict and logs what it means: the own-copy line, or the one line naming a foreign module +// (with the tail of the player's setting). Returns the new state (also stored). +wgrr::guard::State guard_apply(const wgrr::guard::Verdict& v, wgrr::guard::Stage stage) { + namespace g = wgrr::guard; + const g::State before = g_guard.state(); + const g::Mode mode = guard_mode(); + const g::State after = g::decide(v.kind, mode, stage, before); + if (before != g::State::kActive && before != g::State::kTaken) return before; + if (v.kind == g::Verdict::kOwnCopy) { + log_line(g::line_own_copy(v.detail, ascii(narrow(own_path())))); + } else if (v.kind == g::Verdict::kForeign) { + const g::Tail tail = mode == g::Mode::kYield ? (stage == g::Stage::kLoad ? g::Tail::kYieldOff : g::Tail::kYieldPassing) + : (mode == g::Mode::kTake && stage != g::Stage::kLate) ? g::Tail::kTakeInFront + : g::Tail::kStaysActive; + log_line(g::line_foreign(v.module, v.detail, tail)); + } + g_guard.set(after); + return after; +} + +// Where each RR export led at the load check (written by do_hook's thread before g_hook_done is published; read by the +// late check after it): an export that still leads to the same place was reported (or accepted) at load already and +// is not "taken after WrongGPU". +struct ExportSeen { + bool set = false; + wgrr::guard::Owner owner = wgrr::guard::Owner::kUnknown; + const void* module = nullptr; +}; +ExportSeen g_export_seen[32]; + // S2: the first bytes of the interface's RR-deciding exports (module = the interface). anon_ok: code outside every module -// is accepted (host-route mode: the host's own trampolines). -void guard_scan_exports(HMODULE module, const wgrr::guard::Env& env, bool anon_ok, wgrr::guard::Verdict* v) { +// is accepted (host-route mode: the host's own trampolines). record: remember where each led (the load check); +// unchanged_only: count an export that leads where it led at load as read, without classifying it again (late check). +void guard_scan_exports(HMODULE module, const wgrr::guard::Env& env, bool anon_ok, wgrr::guard::Verdict* v, + bool record = false, bool unchanged_only = false) { const std::string leaf = leaf_text(module); for (int role : kWgDecisiveRoles) { if (!role_in_route(role) || !kWgRoleNames[role][0]) continue; const void* e = reinterpret_cast(GetProcAddress(module, kWgRoleNames[role])); if (!e) continue; - v->add(wgrr::guard::classify(e, env, true), std::string("the export ") + kWgRoleNames[role] + " of " + leaf, anon_ok, - false); + const wgrr::guard::Where w = wgrr::guard::classify(e, env, true); + ExportSeen& seen = g_export_seen[role]; + if (record) seen = {true, w.owner, w.module_handle}; + if (unchanged_only && seen.set && seen.owner == w.owner && seen.module == w.module_handle) { + ++v->reads; + continue; + } + v->add(w, std::string("the export ") + kWgRoleNames[role] + " of " + leaf, anon_ok, false); } } // At load (do_hook, before the core is built and before anything is patched): S1 over every module's import slots of -// the interface (and the exe's delay-load slots), S2 over the RR exports. True: go on (active, or take). False: off. +// the interface (and the exe's delay-load slots), S2 over the RR exports. True: go on (active, or take). False: off (a +// second copy of WrongGPU RR, or rr_other_plugin=yield with a named module on the path). bool guard_at_load(const IMAGE_DELAYLOAD_DESCRIPTOR* delay) { namespace g = wgrr::guard; guard_read_override(); @@ -1302,55 +1357,29 @@ bool guard_at_load(const IMAGE_DELAYLOAD_DESCRIPTOR* delay) { }); } } - if (delay) { // the exe's delay-load slots: unbound ones hold the delay helper's thunk in the exe - const uint8_t* base = reinterpret_cast(exe); - const IMAGE_THUNK_DATA64* names = reinterpret_cast(base + delay->ImportNameTableRVA); - const IMAGE_THUNK_DATA64* iat = reinterpret_cast(base + delay->ImportAddressTableRVA); - for (unsigned i = 0; i < 4096; ++i) { - IMAGE_THUNK_DATA64 t; - if (!r.get(names + i, &t) || !t.u1.AddressOfData) break; - if (t.u1.Ordinal & IMAGE_ORDINAL_FLAG64) continue; - char nm[96]; - if (!r.str(base + t.u1.AddressOfData + offsetof(IMAGE_IMPORT_BY_NAME, Name), nm, sizeof nm)) continue; - const int role = role_for_name(nm); - if (role < 0) continue; + g::PeView pe; + if (delay && pe.open(exe, r)) { // the exe's delay-load slots: unbound ones hold the delay helper's thunk in the exe + guard_thunks(pe, r, delay->ImportNameTableRVA, delay->ImportAddressTableRVA, [&](int role, const char* nm, void** slot) { void* val = nullptr; - const g::Where w = r.get(&iat[i].u1.Function, &val) ? g::classify(val, env, false) : g::Where(); + const g::Where w = r.get(slot, &val) ? g::classify(val, env, false) : g::Where(); v.add(w, std::string("the delay-load slot ") + nm + " of " + leaf_text(exe), false, true); if (val && w.owner != g::Owner::kInterface && w.owner != g::Owner::kExeThunk && w.owner != g::Owner::kHost) prev[role] = val; - } + }); } - guard_scan_exports(g_interposer, env, false, &v); + guard_scan_exports(g_interposer, env, false, &v, true); const double ms = ms_since(t0); - const char* result = v.kind == g::Verdict::kClean ? "no other Ray Reconstruction plugin found" - : v.kind == g::Verdict::kOwnCopy ? "a second copy of WrongGPU RR found" - : "another Ray Reconstruction plugin found"; - log_line("hook: coexistence check at load: " + std::string(result) + " (" + std::to_string(v.reads) + + log_line("hook: coexistence check at load: " + std::string(guard_result(v)) + " (" + std::to_string(v.reads) + " address(es) read in " + ms_text(ms) + ")"); guard_log_unclear("at load", v); - if (v.kind == g::Verdict::kOwnCopy) { - g_guard.set(g::State::kOwnCopy); - log_line(g::line_own_copy(v.detail, ascii(narrow(own_path())))); - return false; - } - if (v.kind == g::Verdict::kOther) { - if (!g_take.load()) { - g_load_off_module.store(v.other_module); // OptiPluginInit may find that this module is the host (see there) - g_guard.set(g::State::kOff); - log_line(g::line_other(v.detail)); - return false; - } - memcpy(g_prev, prev, sizeof g_prev); - g_guard.set(g::State::kTaken); - log_line(g::line_take(v.detail)); - } - return true; + if (guard_mode() == g::Mode::kTake) memcpy(g_prev, prev, sizeof g_prev); // used only when the state becomes kTaken + const g::State s = guard_apply(v, g::Stage::kLoad); + return s == g::State::kActive || s == g::State::kTaken; } // S4: after our handlers are installed. Our patched slots that no longer hold our handler lead somewhere else; while -// active (not taken) the RR exports are read again too. Returns the state to keep; logs only a finding (and, with -// log_clean, the clean result and its cost). +// active (not taken) the RR exports are read again too. Returns the state to keep; logs a finding (a foreign module once +// per run) and, with log_clean, the clean result and its cost. wgrr::guard::State guard_late(const char* why, bool log_clean) { namespace g = wgrr::guard; const g::State s = g_guard.state(); @@ -1373,21 +1402,25 @@ wgrr::guard::State guard_late(const char* why, bool log_clean) { (slash == std::string::npos ? w.module : w.module.substr(slash + 1)) + " (WrongGPU's hook)", false, false); } } - if (s == g::State::kActive && g_interposer && !g_route_mode.load()) guard_scan_exports(g_interposer, env, false, &v); + if (s == g::State::kActive && g_interposer && !g_route_mode.load()) + guard_scan_exports(g_interposer, env, false, &v, false, true); // what changed since the load check const double ms = ms_since(t0); - if (v.kind == g::Verdict::kClean) { + const std::string cost = " (" + std::to_string(v.reads) + " address(es) read in " + ms_text(ms) + ")"; + const std::string head = std::string("hook: coexistence re-check at ") + why + ": "; + // a foreign module that stays inconclusive (off, take) is named once per run: OptiPluginInit and the first call may + // both see it + const bool quiet_foreign = v.kind == g::Verdict::kForeign && guard_mode() != g::Mode::kYield && + g_late_foreign_logged.exchange(true); + if (v.kind == g::Verdict::kClean || quiet_foreign) { if (log_clean) - log_line(std::string("hook: coexistence re-check at ") + why + ": no other Ray Reconstruction plugin found (" + - std::to_string(v.reads) + " address(es) read in " + ms_text(ms) + ")"); + log_line(head + (quiet_foreign ? "another module on the RR path, named above" : guard_result(v)) + cost); guard_log_unclear((std::string("re-check at ") + why).c_str(), v); return s; } - log_line(std::string("hook: coexistence re-check at ") + why + ": " + - (v.kind == g::Verdict::kOwnCopy ? "a second copy of WrongGPU RR" : "another Ray Reconstruction plugin") + - " took the RR calls after WrongGPU (" + std::to_string(v.reads) + " address(es) read in " + ms_text(ms) + ")"); - if (v.kind == g::Verdict::kOwnCopy) log_line(g::line_own_copy(v.detail, ascii(narrow(own_path())))); - else log_line(g_take.load() ? g::line_cannot_take(v.detail) : g::line_other_later(v.detail)); - return g::State::kPassThrough; + log_line(head + (v.kind == g::Verdict::kOwnCopy ? "a second copy of WrongGPU RR" : "another module") + + " took the RR calls after WrongGPU" + cost); + guard_log_unclear((std::string("re-check at ") + why).c_str(), v); + return guard_apply(v, g::Stage::kLate); } void guard_first_call() { @@ -1433,7 +1466,8 @@ void do_hook() { g_api_minor = v[1]; log_line("hook: route Streamline 2." + std::to_string(g_api_minor) + " chosen for this game interface"); - // RR guard: another RR plugin already holding these calls keeps WrongGPU RR off (nothing built or patched) + // RR guard: a second copy of WrongGPU RR (or rr_other_plugin=yield with a named module on the path) keeps WrongGPU RR + // off (nothing built or patched); a named module alone is only logged if (!guard_at_load(delay)) return; set_fwd(bind_original()); // where a passing handler sends a call (the late decision, guard_first_call) @@ -1528,24 +1562,11 @@ void on_host_hooked(void* module, uint32_t major, uint32_t minor, uint32_t patch QueryPerformanceCounter(&t0); g::Verdict v; guard_scan_exports(static_cast(module), guard_env(module), true, &v); - log_line(std::string("hook: coexistence check before the host routes: ") + - (v.kind == g::Verdict::kClean ? "no other Ray Reconstruction plugin found" : "another plugin found") + " (" + + log_line(std::string("hook: coexistence check before the host routes: ") + guard_result(v) + " (" + std::to_string(v.reads) + " address(es) read in " + ms_text(ms_since(t0)) + ")"); guard_log_unclear("before the host routes", v); - if (v.kind == g::Verdict::kOwnCopy) { - g_guard.set(g::State::kOwnCopy); - log_line(g::line_own_copy(v.detail, ascii(narrow(own_path())))); - return; - } - if (v.kind == g::Verdict::kOther && !g_take.load()) { - g_guard.set(g::State::kOff); - log_line(g::line_other(v.detail)); - return; - } - if (v.kind == g::Verdict::kOther) { - g_guard.set(g::State::kTaken); - log_line(g::line_take(v.detail)); - } + const g::State s = guard_apply(v, g::Stage::kLoad); // nothing of ours is in place yet + if (s != g::State::kActive && s != g::State::kTaken) return; // own copy, or yield: no routes } std::vector routes; for (unsigned i = 0; i < WG_BINDING_HOOK_ROLE_COUNT; ++i) { @@ -1557,15 +1578,18 @@ void on_host_hooked(void* module, uint32_t major, uint32_t minor, uint32_t patch g_interposer = static_cast(module); g_route_mode.store(true); if (!api->register_streamline_routes(g_host_plugin, routes.data(), (uint32_t)routes.size())) { + // the host's API refused our registration: positive by contract, the game-interface route stays off (the NGX route + // is decided by the host's own answer there) g_route_mode.store(false); - log_line("hook: the host refused our game-interface routes; nothing was patched"); + log_line("hook: the host refused our game-interface routes; nothing was patched: WrongGPU RR stays off on the " + "game-interface route"); return; } unsigned installed = 0; for (const WgHostSlRoute& r : routes) installed += (*r.next != nullptr); - // RR guard: where each route continues (the host's next): another plugin's route under ours means it holds - // the RR path below us. Our routes are installed and cannot be taken back: they pass every call on (or, with take, - // keep RR and pass the other calls on). + // RR guard: where each route continues (the host's next). Our routes are installed in front and cannot be taken back: + // a named module below them is inconclusive (RR stays WrongGPU's; the other calls continue through it); a copy of + // WrongGPU RR, or rr_other_plugin=yield with a named module, makes them pass every call on. { LARGE_INTEGER t0; QueryPerformanceCounter(&t0); @@ -1574,22 +1598,13 @@ void on_host_hooked(void* module, uint32_t major, uint32_t minor, uint32_t patch for (const WgHostSlRoute& r : routes) if (*r.next) v.add(g::classify(*r.next, env, false), std::string("the host's next function of ") + r.export_name, true, false); - log_line(std::string("hook: coexistence check of the host routes: ") + - (v.kind == g::Verdict::kClean ? "no other Ray Reconstruction plugin found" : "another plugin found") + " (" + + log_line(std::string("hook: coexistence check of the host routes: ") + guard_result(v) + " (" + std::to_string(v.reads) + " address(es) read in " + ms_text(ms_since(t0)) + ")"); guard_log_unclear("of the host routes", v); set_fwd(bind_original()); // the host's next functions - if (v.kind != g::Verdict::kClean) { - if (v.kind == g::Verdict::kOther && g_take.load()) { - g_guard.set(g::State::kTaken); - log_line(g::line_take(v.detail)); - } else { - g_guard.set(g::State::kPassThrough); - log_line(v.kind == g::Verdict::kOwnCopy ? g::line_own_copy(v.detail, ascii(narrow(own_path()))) - : g::line_other(v.detail, true)); - g_hook_done.store(true, std::memory_order_release); - return; - } + if (guard_apply(v, g::Stage::kRoutes) == g::State::kPassThrough) { + g_hook_done.store(true, std::memory_order_release); + return; } } g_hook_done.store(true, std::memory_order_release); @@ -1815,7 +1830,8 @@ void ngx_release_cpp(void* u, void* ctx) { ngx_fault("release (exception)"); } } -// RR guard: another RR plugin was found after the provider was registered: creates are refused (logged once) +// RR guard: WrongGPU RR went off after the provider was registered (a copy of WrongGPU RR, or yield): creates are +// refused (logged once) bool ngx_guard_refuses() { if (g_guard.active()) return false; static std::atomic logged{false}; @@ -1891,7 +1907,7 @@ void register_ngx_provider(const WgHostMenuApi* api, WgHostMenuPlugin* plugin) { } return; } - if (!g_guard.active()) { // RR guard: another RR plugin holds the game-interface path + if (!g_guard.active()) { // RR guard: off in this process (a copy of WrongGPU RR, or rr_other_plugin=yield) log_line("NGX: RR provider not registered: WrongGPU RR stays off in this process (see the line above)"); g_ngx_decided.store(true); return; @@ -1954,7 +1970,7 @@ void register_ngx_provider(const WgHostMenuApi* api, WgHostMenuPlugin* plugin) { // OptiScaler's ASI entry (same convention WrongGPU.asi uses). All real work runs here, never under the loader lock. extern "C" __declspec(dllexport) void InitializeASI() { - // RR guard: the module that calls us is the host (it patches the interface's init export itself) + // RR guard: the module that calls us is taken as the host (its own patches are accepted; wording only) void* caller = _ReturnAddress(); std::call_once(g_init_once, [caller] { HMODULE host = nullptr; @@ -1986,23 +2002,15 @@ extern "C" __declspec(dllexport) void InitializeASI() { extern "C" __declspec(dllexport) bool OptiPluginInit(const WgHostMenuApi* api, WgHostMenuPlugin* plugin) { // RR guard: a second copy of WrongGPU RR registers nothing (no second tab, routes or provider) if (g_guard.state() == wgrr::guard::State::kOwnCopy) return false; - if (api) { // the module holding the host's table is the host as well (a separate ASI loader may have called InitializeASI) + // The module holding the host's table is taken as the host as well (a separate ASI loader may have called + // InitializeASI): later checks accept its own patches and do not name it. A guess, used for the wording only: a table + // on the heap or in a helper image gives no module or another one, and nothing depends on it. + if (api) { HMODULE host = nullptr; if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, reinterpret_cast(api), &host) && host && host != g_self && - host != g_host_module.load()) { + host != g_host_module.load()) g_host_api_module.store(host); - // The load decision took this very module for another plugin (it ran before the host's table was known): it is - // the host; its own patches are not a second plugin. Nothing was patched then, so the load decision runs again. - if (g_guard.state() == wgrr::guard::State::kOff && host == g_load_off_module.load() && - !g_load_rerun_done.exchange(true)) { - log_line("hook: the module the load check took for another Ray Reconstruction plugin (" + leaf_text(host) + - ") holds the host's API table: it is the host (a separate loader called InitializeASI); the load " - "check runs again with it as the host"); - g_guard.set(wgrr::guard::State::kActive); - do_hook(); - } - } } // a plugin that took the RR calls after our InitializeASI (a non-freezing check; the game's first call decides last) if (g_hook_done.load(std::memory_order_acquire)) diff --git a/clean/rr_f/proxy/src/log_append.h b/clean/rr_f/proxy/src/log_append.h index 4c369fc3..66bf664c 100644 --- a/clean/rr_f/proxy/src/log_append.h +++ b/clean/rr_f/proxy/src/log_append.h @@ -10,7 +10,9 @@ // Now every write is ONE WriteFile of the whole text (timestamp, line, newline; a rotation notice in the same buffer) // on a handle opened with FILE_APPEND_DATA alone, which the system appends at the end of the file as one piece. A // process-wide named mutex, named after the log file's full path, puts the two copies' writes (and the size check and -// rotation) in one order; its wait is bounded, and when it fails the line is still written with the one append call. +// rotation) in one order while it is held. Its wait is bounded: after a timeout (or when the mutex cannot be created) +// the line is still written with the one append call but without the lock and without a size check, so it may land in +// the file another copy is just moving aside. Best effort, not a guarantee (HOOK-MODE.md, "The log with two copies"). #pragma once #include diff --git a/clean/rr_f/proxy/src/rr_guard.cpp b/clean/rr_f/proxy/src/rr_guard.cpp index 0f46e5fd..99070286 100644 --- a/clean/rr_f/proxy/src/rr_guard.cpp +++ b/clean/rr_f/proxy/src/rr_guard.cpp @@ -64,6 +64,11 @@ int32_t rd32(const uint8_t* b) { memcpy(&v, b, 4); return v; } + +// at + d as an address (integer arithmetic: a jump target may lie anywhere, it is only ever read through safe reads) +const void* rel(const uint8_t* at, intptr_t d) { + return reinterpret_cast(reinterpret_cast(at) + (uintptr_t)d); +} } // namespace bool safe_read(const void* p, void* out, size_t n) { @@ -96,19 +101,60 @@ bool Reader::str(const void* p, char* out, size_t max) { return false; } +bool PeView::open(const void* module, Reader& r) { + base_ = nullptr; + size_ = 0; + ndirs_ = 0; + const uint8_t* base = static_cast(module); + IMAGE_DOS_HEADER dos; + if (!base || !r.get(base, &dos) || dos.e_magic != IMAGE_DOS_SIGNATURE) return false; + // e_lfanew is a signed 32-bit offset: checked as an integer (positive, past the DOS header, not absurd) before the NT + // headers are read at all; against SizeOfImage once that is known + const LONG lfanew = dos.e_lfanew; + if (lfanew < (LONG)sizeof(IMAGE_DOS_HEADER) || lfanew > 0x100000) return false; + IMAGE_NT_HEADERS64 nt; + if (!r.get(base + lfanew, &nt) || nt.Signature != IMAGE_NT_SIGNATURE || + nt.OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) + return false; + const uint32_t size = nt.OptionalHeader.SizeOfImage; + if ((uint64_t)lfanew + sizeof(IMAGE_NT_HEADERS64) > size) return false; // the headers lie inside the image + if ((uintptr_t)base + size < (uintptr_t)base) return false; // the image does not wrap the address space + base_ = base; + size_ = size; + ndirs_ = nt.OptionalHeader.NumberOfRvaAndSizes < 16 ? nt.OptionalHeader.NumberOfRvaAndSizes : 16; + for (uint32_t i = 0; i < ndirs_; ++i) { + dir_rva_[i] = nt.OptionalHeader.DataDirectory[i].VirtualAddress; + dir_size_[i] = nt.OptionalHeader.DataDirectory[i].Size; + } + return true; +} + +bool PeView::dir(unsigned index, uint32_t* rva, uint32_t* size) const { + if (!base_ || index >= ndirs_ || !dir_rva_[index] || !dir_size_[index]) return false; + if (!at(dir_rva_[index], dir_size_[index])) return false; // the directory lies inside the image + *rva = dir_rva_[index]; + *size = dir_size_[index]; + return true; +} + +const uint8_t* PeView::at(uint64_t rva, uint64_t n) const { + if (!base_ || rva > size_ || n > (uint64_t)size_ - rva) return nullptr; + return base_ + rva; +} + bool decode_jump(const uint8_t* c, size_t n, const uint8_t* at, const void** target, const void** cell) { if (cell) *cell = nullptr; if (n >= 5 && c[0] == 0xE9) { // jmp rel32 - *target = at + 5 + rd32(c + 1); + *target = rel(at, 5 + (intptr_t)rd32(c + 1)); return true; } if (n >= 2 && c[0] == 0xEB) { // jmp rel8 - *target = at + 2 + static_cast(c[1]); + *target = rel(at, 2 + (intptr_t)static_cast(c[1])); return true; } const size_t r = (n >= 1 && c[0] == 0x48) ? 1 : 0; // REX.W jmp [rip+disp32] (same meaning) if (n >= r + 6 && c[r] == 0xFF && c[r + 1] == 0x25) { // jmp [rip+disp32] - const uint8_t* slot = at + r + 6 + rd32(c + r + 2); + const void* slot = rel(at, (intptr_t)(r + 6) + rd32(c + r + 2)); const void* t = nullptr; if (!safe_get(slot, &t)) return false; if (cell) *cell = slot; @@ -230,14 +276,16 @@ void Verdict::add(const Where& w, const std::string& what, bool anon_ok, bool ex return; } if (trusted(w.owner, anon_ok, exe_ok)) return; - if (w.owner == Owner::kForeign) { // the one positive sign of another plugin: a named module that is not ours - if (kind == kOther) return; - kind = kOther; + if (w.owner == Owner::kForeign) { // a named module that is not ours: inconclusive, named (the first one) in the log + ++foreign; + if (kind == kForeign) return; + kind = kForeign; other_module = w.module_handle; - detail = what + " leads to " + (w.module.empty() ? std::string("another module") : w.module) + via; + module = w.module.empty() ? std::string("another module") : w.module; + detail = what + " leads to " + module + via; return; } - // not a sign of another plugin: counted, the first one named for the log + // nothing could be told: counted, the first one named for the log ++unclear; if (unclear > 1) return; if (w.owner == Owner::kUnknown) @@ -247,40 +295,62 @@ void Verdict::add(const Where& w, const std::string& what, bool anon_ok, bool ex else unclear_detail = what + " leads into the exe's own code" + via; } -bool override_take(const std::string& value, std::string* note) { +Mode parse_mode(const std::string& value, std::string* note) { std::string v; for (char c : value) if (c != ' ' && c != '\t' && c != '\r' && c != '\n') v.push_back((char)(c >= 'A' && c <= 'Z' ? c - 'A' + 'a' : c)); if (note) note->clear(); - if (v == "take") return true; + if (v == "take") return Mode::kTake; + if (v == "yield") return Mode::kYield; if (!v.empty() && v != "off" && note) - *note = std::string(kOverrideKey) + "=" + value + " in wronggpu-rr.ini not recognised (off | take); off is used"; - return false; + *note = std::string(kOverrideKey) + "=" + value + " in wronggpu-rr.ini not recognised (off | take | yield); off is used"; + return Mode::kOff; } -// The lines start with the words the launcher's Last run page matches (no "hook: " prefix): kStem, kOwnCopyStem, -// kLaterStem. HOOK-MODE.md documents them; changing a beginning breaks that page. +const char* mode_word(Mode m) { + switch (m) { + case Mode::kOff: return "off"; + case Mode::kTake: return "take"; + case Mode::kYield: return "yield"; + } + return "?"; +} + +State decide(Verdict::Kind kind, Mode mode, Stage stage, State current) { + if (current != State::kActive && current != State::kTaken) return current; // off, own copy, passing: final + switch (kind) { + case Verdict::kClean: + return current; + case Verdict::kOwnCopy: // positive by contract + return stage == Stage::kLoad ? State::kOwnCopy : State::kPassThrough; + case Verdict::kForeign: // inconclusive: only the player's setting acts on it + if (mode == Mode::kYield) return stage == Stage::kLoad ? State::kOff : State::kPassThrough; + if (mode == Mode::kTake && stage != Stage::kLate) return State::kTaken; + return current; + } + return current; +} + +// The beginnings a reader can match (HOOK-MODE.md documents them; keep them exactly): kForeignStem, kStem (the NGX +// route's "stays off" line), kOwnCopyStem. None of them has the "hook: " prefix of the diagnostics. +static const char kForeignStem[] = "another module hooks the game's RR calls: "; static const char kStem[] = "another Ray Reconstruction plugin is active; WrongGPU RR stays off ("; static const char kOwnCopyStem[] = "a second copy of WrongGPU RR is loaded ("; -static const char kLaterStem[] = "a plugin loaded after WrongGPU replaced its hooks; "; -std::string line_other(const std::string& d, bool passing) { - return std::string(kStem) + d + - (passing ? "; WrongGPU's handlers pass every call on unchanged; " : "; nothing patched; ") + kOverrideKey + - "=take in wronggpu-rr.ini uses WrongGPU's instead)"; -} -std::string line_other_later(const std::string& d) { - return std::string(kStem) + d + - "; it loaded after WrongGPU: WrongGPU passes every call on unchanged; to use WrongGPU RR, move it aside)"; -} -std::string line_take(const std::string& d) { - return std::string("another Ray Reconstruction plugin is active; ") + kOverrideKey + - "=take: WrongGPU RR goes in front of it (" + d + "; it gets the game's other calls, no RR work)"; -} -std::string line_cannot_take(const std::string& d) { - return std::string(kLaterStem) + kOverrideKey + - "=take cannot be applied: WrongGPU RR stays off and passes every call on unchanged (" + d + - "); move it aside to use WrongGPU RR"; +std::string line_foreign(const std::string& module, const std::string& detail, Tail tail) { + std::string s = std::string(kForeignStem) + module + " (" + detail + "); "; + switch (tail) { + case Tail::kStaysActive: + return s + "it is not known to be a Ray Reconstruction plugin: WrongGPU RR stays active (" + kOverrideKey + + "=yield in wronggpu-rr.ini keeps WrongGPU RR off in this case)"; + case Tail::kTakeInFront: + return s + kOverrideKey + "=take: WrongGPU RR goes in front of it (it gets the game's other calls, no RR work)"; + case Tail::kYieldOff: + return s + kOverrideKey + "=yield: WrongGPU RR stays off (nothing patched)"; + case Tail::kYieldPassing: + return s + kOverrideKey + "=yield: WrongGPU RR stays off (WrongGPU's handlers pass every call on unchanged)"; + } + return s; } std::string line_own_copy(const std::string& active, const std::string& self) { return std::string(kOwnCopyStem) + active + " is active); this copy (" + self + ") stays off"; @@ -343,17 +413,14 @@ Env process_env(const void* self, const void* iface, const void* host, const voi return GetProcAddress(static_cast(const_cast(m)), name) != nullptr; }; e.name_of = leaf_utf8; - // the interface's own import address table (IMAGE_DIRECTORY_ENTRY_IAT), read through safe reads - const uint8_t* base = static_cast(iface); - IMAGE_DOS_HEADER dos; - IMAGE_NT_HEADERS64 nt; - if (base && safe_get(base, &dos) && dos.e_magic == IMAGE_DOS_SIGNATURE && safe_get(base + dos.e_lfanew, &nt) && - nt.Signature == IMAGE_NT_SIGNATURE) { - const IMAGE_DATA_DIRECTORY& d = nt.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IAT]; - if (d.VirtualAddress && d.Size) { - e.iface_iat_begin = base + d.VirtualAddress; - e.iface_iat_end = base + d.VirtualAddress + d.Size; - } + // the interface's own import address table (IMAGE_DIRECTORY_ENTRY_IAT), read through safe reads and checked against + // the image's size (PeView) + Reader r; + PeView pe; + uint32_t rva = 0, size = 0; + if (iface && pe.open(iface, r) && pe.dir(IMAGE_DIRECTORY_ENTRY_IAT, &rva, &size)) { + e.iface_iat_begin = pe.at(rva, size); + e.iface_iat_end = e.iface_iat_begin + size; } return e; } diff --git a/clean/rr_f/proxy/src/rr_guard.h b/clean/rr_f/proxy/src/rr_guard.h index 1a5c5ac5..89ad583e 100644 --- a/clean/rr_f/proxy/src/rr_guard.h +++ b/clean/rr_f/proxy/src/rr_guard.h @@ -1,26 +1,33 @@ // SPDX-License-Identifier: MIT // RR guard: the coexistence guard of the hook-mode RR plugin (HOOK-MODE.md, "Another Ray Reconstruction -// plugin"). When another Ray Reconstruction plugin demonstrably holds the game's RR path in this process, WrongGPU RR -// stays off and logs one line; Model M is not touched. Generic and read-only: it looks at where the game's RR calls -// lead (import slots, the first bytes of the interface's RR exports, the host's continuation pointers), never at -// another plugin's files or internals. +// plugin"). Generic and read-only: it looks at where the game's RR calls lead (import slots, the first bytes of the +// interface's RR exports, the host's continuation pointers), never at another plugin's files or internals. // -// Only a POSITIVE finding stops the plugin: an address that ends in a named foreign module (also through decoded hook -// jumps), or in our own second copy. Everything else the scan cannot explain (unreadable memory, too many hops, code -// outside every module that does not jump on, the exe's own code) is logged once as inconclusive and the plugin stays -// active: a game's copy protection or a hooking library's trampolines must never switch RR off for a player who has no -// other plugin. +// WrongGPU RR switches itself off automatically ONLY on evidence that is positive by contract: +// - a second copy of WrongGPU RR (the process-wide marker, or an address that ends in a module exporting +// kOwnRrExport); +// - the host's plugin API saying the RR provider slot is taken, or refusing our registration (hook_dll.cpp). +// Nothing else. A named foreign module on the call path is INCONCLUSIVE: it may be another RR plugin, but it may as well +// be a game's own wrapper DLL, an overlay, a security shim, a host helper in a third image or a forwarded export's +// implementation DLL. WrongGPU RR stays active (as in 0.6.0) and one line names the module and the place +// (line_foreign). wronggpu-rr.ini rr_other_plugin=yield makes such a module switch WrongGPU RR off; take puts WrongGPU RR +// in front of it. What the scan cannot explain at all (unreadable memory, too many hops, code outside every module that +// does not jump on, the exe's own code) is logged once as inconclusive (line_inconclusive) and changes nothing either. // // This header holds the parts without process state, so the CPU tests can drive them with synthetic memory: // - safe_read: every read of memory we do not own (VirtualQuery for committed, readable, non-guard pages, then a -// structured-exception-guarded copy); a failed read is "unknown", never a fault; +// structured-exception-guarded copy); a failed read is "unknown", never a fault. The check and the copy are not +// atomic (HOOK-MODE.md says what that leaves); +// - PeView: a module's PE64 headers read through the reader, with e_lfanew, every data directory and every RVA the +// scan follows checked against SizeOfImage before any address is formed from them; // - decode_jump: the jump forms a hook puts at the start of a function (jmp rel32 / rel8, jmp [rip+disp32], // mov rax|r11, imm64 + jmp reg); // - classify: who an address belongs to (our module, the game interface, the host, another copy of WrongGPU RR, // another WrongGPU module, the exe's own delay-load thunk, code outside every module, another module), following // hook jumps out of the interface and out of anonymous memory, at most kMaxHops of them; -// - Verdict: the positive finding (if any) of several classifications, the inconclusive ones, and the words for the -// log; +// - Verdict: what several classifications found (a copy of WrongGPU RR, the first foreign module, the inconclusive +// ones) and the words for the log; +// - Mode / decide: what a verdict means for WrongGPU RR under rr_other_plugin (one table, tested on its own); // - Decision: the once-only late decision (several game threads may make the first call at the same time). #pragma once #include @@ -38,12 +45,12 @@ namespace guard { // other WrongGPU plugin (WrongGPU.asi, Model M's menu plugin). Documented in HOOK-MODE.md (the launcher matches them). constexpr const char* kOwnRrExport = "WrongGPU_GetSettingsContract"; constexpr const char* kWrongGpuAsiExport = "WrongGpuAsiQuery"; -// wronggpu-rr.ini: rr_other_plugin = off (default) | take +// wronggpu-rr.ini: rr_other_plugin = off (default) | take | yield constexpr const char* kOverrideKey = "rr_other_plugin"; constexpr int kMaxHops = 4; // hook jumps followed from one address (a fifth one is "too many hops": inconclusive) // True when [p, p + n) lies in committed pages that are readable (execute-only pages count: code is read from them and -// the structured-exception guard of the copy covers a fault) and not guard pages (VirtualQuery only). +// the structured-exception guard of the copy covers a fault) and not guard pages, as VirtualQuery reports them now. bool readable(const void* p, size_t n); // Copies n bytes from p to out when readable() and the copy raises no structured exception. False: unknown. bool safe_read(const void* p, void* out, size_t n); @@ -69,6 +76,29 @@ class Reader { uintptr_t lo_ = 0, hi_ = 0; }; +// A loaded module's PE64 headers as the scan may use them. open() reads the DOS and NT headers through the reader and +// accepts them only when e_lfanew points inside the image (and the NT headers fit), the optional header is PE32+ and +// SizeOfImage is plausible; dir() hands out a data directory only when its RVA and size lie inside SizeOfImage. at() +// forms an address from an RVA only after checking [rva, rva + n) against SizeOfImage (integers first, no pointer +// arithmetic on unchecked values). Anything that fails is "not readable": the caller treats it as nothing found. +class PeView { + public: + bool open(const void* module, Reader& r); + // the directory `index` when present and inside the image (false: absent or out of bounds) + bool dir(unsigned index, uint32_t* rva, uint32_t* size) const; + // base + rva when [rva, rva + n) lies inside the image, else null + const uint8_t* at(uint64_t rva, uint64_t n) const; + uint32_t size_of_image() const { return size_; } + const uint8_t* base() const { return base_; } + + private: + const uint8_t* base_ = nullptr; + uint32_t size_ = 0; + uint32_t ndirs_ = 0; + uint32_t dir_rva_[16] = {}; + uint32_t dir_size_[16] = {}; +}; + // A hook jump at `at` (code holds the first bytes read from there, n of them). On success *target is where it goes; // for jmp [rip+disp32] *cell is the pointer cell (read with safe_read; a failed read makes the decode fail). bool decode_jump(const uint8_t* code, size_t n, const uint8_t* at, const void** target, const void** cell); @@ -78,11 +108,11 @@ enum class Owner { kSelf, // this WrongGPU RR module kInterface, // the game interface module (its own code) kHost, // the host that loaded us, or the module holding its API table (it patches the interface itself) - kOwnCopy, // another loaded copy of WrongGPU RR (exports kOwnRrExport): positive + kOwnCopy, // another loaded copy of WrongGPU RR (exports kOwnRrExport): positive, it switches this copy off kWrongGpu, // another WrongGPU module (exports kWrongGpuAsiExport) kExeThunk, // the exe's own code (a delay-load slot not bound yet holds the delay helper's thunk there): inconclusive kAnonymous, // readable code outside every module that does not jump on (a trampoline): inconclusive - kForeign, // another named module: another plugin (positive) + kForeign, // another named module: inconclusive (named in the log; only rr_other_plugin=yield acts on it) }; const char* owner_word(Owner o); @@ -116,16 +146,18 @@ struct Where { // interface's own code. Jumps are always followed out of anonymous memory. Where classify(const void* p, const Env& env, bool follow_iface); -// What a scan found. kOther / kOwnCopy are positive findings only (an address that ends in another named module, or in -// a second copy of WrongGPU RR; the first foreign one decides, a copy of WrongGPU RR before anything else). Whatever -// could not be explained (unreadable, too many hops, anonymous code that does not jump on, the exe's own code) is -// counted in `unclear` and leaves the kind at kClean: the plugin stays active. +// What a scan found. kOwnCopy: an address ends in a second copy of WrongGPU RR (it wins over everything). kForeign: an +// address ends in another named module (the first one is kept for the log; inconclusive, see decide()). Whatever could +// not be explained at all (unreadable, too many hops, anonymous code that does not jump on, the exe's own code) is +// counted in `unclear` and leaves the kind as it is. struct Verdict { - enum Kind { kClean, kOwnCopy, kOther } kind = kClean; - std::string detail; // e.g. "the import slot slEvaluateFeature of Game.exe leads to other.asi" - const void* other_module = nullptr; // kOther: the module the first foreign finding ends in + enum Kind { kClean, kOwnCopy, kForeign } kind = kClean; + std::string detail; // e.g. "the import slot slEvaluateFeature of Game.exe leads to other.dll" + std::string module; // kForeign: the file name of the module the first foreign address ends in ("another module") + const void* other_module = nullptr; // kForeign: that module + unsigned foreign = 0; // addresses that end in another named module unsigned reads = 0; // addresses looked at - unsigned unclear = 0; // addresses that were neither trusted nor a positive finding + unsigned unclear = 0; // addresses that were neither trusted nor a named module std::string unclear_detail; // the first of them, e.g. "the import slot X of Y could not be read" // Takes one classification. `what` names the place ("the import slot X of Y"); anon_ok: code outside every // module is accepted here (the host's own trampolines); exe_ok: the exe's own code is accepted (delay thunks). @@ -133,24 +165,43 @@ struct Verdict { }; bool trusted(Owner o, bool anon_ok, bool exe_ok); -// rr_other_plugin from wronggpu-rr.ini: false = off (the default, also for an unknown value; *note says so). -bool override_take(const std::string& value, std::string* note); +// rr_other_plugin from wronggpu-rr.ini. Unknown or empty values are off (*note says so for a nonempty unknown one). +enum class Mode { kOff, kTake, kYield }; +Mode parse_mode(const std::string& value, std::string* note); +const char* mode_word(Mode m); -// The log lines (stable; HOOK-MODE.md documents them, the launcher's Last run page matches them). -// stays off at load (passing: WrongGPU's handlers were already installed by the host and pass every call on) -std::string line_other(const std::string& detail, bool passing = false); -std::string line_other_later(const std::string& detail); // stays off, found at the late check (pass-through) -std::string line_take(const std::string& detail); // rr_other_plugin=take: WrongGPU RR in front -std::string line_cannot_take(const std::string& detail); // take asked, the other plugin loaded later +// The guard's state for the whole process run. Active until a decision says otherwise; the late decision is taken once. +enum class State : int { kActive = 0, kOff = 1, kOwnCopy = 2, kPassThrough = 3, kTaken = 4 }; + +// When a scan runs: before anything of ours is in place (kLoad: the exe's import slots and the exports at InitializeASI, +// the exports before the host routes), right after our host routes were installed in front (kRoutes: the host's next +// functions), or after our handlers were installed (kLate: OptiPluginInit, the game's first call). +enum class Stage { kLoad, kRoutes, kLate }; + +// What a scan's verdict means for WrongGPU RR (the whole policy, in one place): +// - not active already (off, own copy, passing): stays as it is; +// - clean: stays as it is; +// - a copy of WrongGPU RR: off at load (nothing patched), passing once our handlers or routes are in place; +// - a named foreign module: off -> stays as it is (active; the caller logs line_foreign); take -> kTaken while +// WrongGPU can still go in front of it (load, routes), else as it is; yield -> off at load, passing later. +State decide(Verdict::Kind kind, Mode mode, Stage stage, State current); + +// The log lines (stable; HOOK-MODE.md documents them; the beginnings are what a reader such as the launcher's Last run +// page can match: kForeignStem, the "stays off" stem of line_ngx_other, the own-copy stem). +// A named foreign module on the RR path: "another module hooks the game's RR calls: (); " +enum class Tail { + kStaysActive, // rr_other_plugin=off (also take after our handlers are in place): RR stays WrongGPU's + kTakeInFront, // take, at load or with our routes in front: WrongGPU RR in front, the module gets the other calls + kYieldOff, // yield at load: nothing patched + kYieldPassing, // yield with our handlers or routes in place: they pass every call on unchanged +}; +std::string line_foreign(const std::string& module, const std::string& detail, Tail tail); std::string line_own_copy(const std::string& active, const std::string& self); std::string line_ngx_other(); // the host refused our NGX provider -// The stay-on diagnostic (starts with "hook: "; never with the beginnings above): the scan could not explain `n` -// address(es), `first` is the first one. No finding, RR stays active. +// The stay-on diagnostic (starts with "hook: "; never with a beginning above): the scan could not explain `n` +// address(es), `first` is the first one. RR stays active. std::string line_inconclusive(const std::string& when, unsigned n, const std::string& first); -// The guard's state for the whole process run. Active until a scan says otherwise; the late decision is taken once. -enum class State : int { kActive = 0, kOff = 1, kOwnCopy = 2, kPassThrough = 3, kTaken = 4 }; - class Decision { public: State state() const { return static_cast(state_.load(std::memory_order_acquire)); } diff --git a/clean/rr_f/proxy/tests/fake_other_rr.cpp b/clean/rr_f/proxy/tests/fake_other_rr.cpp index 73ce488c..f4dbd7e3 100644 --- a/clean/rr_f/proxy/tests/fake_other_rr.cpp +++ b/clean/rr_f/proxy/tests/fake_other_rr.cpp @@ -13,8 +13,13 @@ // wgtest_or_host_table keeps a copy of a host API table in this module (the host's table lives in a module of its own) // wgtest_or_call_init calls a function from inside this module (a separate ASI loader calling InitializeASI; the test // loads a second copy of this DLL under another name for that) +// wgtest_or_bind_one binds one import slot to this module's handler, which continues with the interface's export +// (as the loader binds a forwarded export to its implementation DLL) +// wgtest_or_innocent 1: this copy is NOT an RR plugin (a game's wrapper DLL, an overlay, a host helper, a forwarded +// export's implementation): its handlers pass every call on, RR included // Its handlers answer the RR feature themselves (is-supported 0, evaluate / allocate / get-function counted and 0) and -// pass every other call on. The role names and order come from the hook binding (wg_binding.inc). +// pass every other call on, unless innocent. The test loads further copies of this DLL under other file names for the +// innocent layouts (each copy has its own state). The role names and order come from the hook binding (wg_binding.inc). #define WIN32_LEAN_AND_MEAN #include @@ -37,6 +42,7 @@ struct OrState { OrState g_st; Fwd g_next[32]; // where each handler continues bool g_inline[32]; // the export of this role was overwritten (no way back to it): non-RR calls are answered here +bool g_innocent; // not an RR plugin: every call is passed on (wgtest_or_innocent) // the feature argument of a role, if it has one bool feature_of(int role, uint64_t a, uint64_t b, uint32_t* f) { @@ -51,7 +57,8 @@ template uint64_t handler(uint64_t a, uint64_t b, uint64_t c, uint64_t d, uint64_t e, uint64_t f) { InterlockedIncrement(&g_st.calls[R]); uint32_t feat = 0; - if (feature_of(R, a, b, &feat) && feat == WG_FEAT_RAY_RECONSTRUCTION && (R == 2 || R == 7 || R == 8 || R == 16)) { + if (!g_innocent && feature_of(R, a, b, &feat) && feat == WG_FEAT_RAY_RECONSTRUCTION && + (R == 2 || R == 7 || R == 8 || R == 16)) { InterlockedIncrement(&g_st.rr_calls); if (R == 7 && c) *reinterpret_cast(c) = reinterpret_cast(&handler); // "its" feature function return 0; @@ -152,6 +159,19 @@ __declspec(dllexport) int wgtest_or_patch_iat(HMODULE exe, const char* iface_lea return n; } +__declspec(dllexport) void wgtest_or_innocent(int on) { g_innocent = on != 0; } + +__declspec(dllexport) int wgtest_or_bind_one(HMODULE exe, const char* iface_leaf, const char* import_name) { + HMODULE iface = GetModuleHandleA(iface_leaf); + int n = 0; + each_import(exe, iface_leaf, [&](int role, const char* nm, void** slot) { + if (role < 0 || strcmp(nm, import_name) != 0) return; + g_next[role] = reinterpret_cast(GetProcAddress(iface, nm)); + if (write_ptr(slot, kHandlers[role])) ++n; + }); + return n; +} + __declspec(dllexport) int wgtest_or_set_slot(HMODULE exe, const char* iface_leaf, const char* import_name, void* value) { int n = 0; each_import(exe, iface_leaf, [&](int, const char* nm, void** slot) { diff --git a/clean/rr_f/proxy/tests/test_hook_dll.cpp b/clean/rr_f/proxy/tests/test_hook_dll.cpp index 03a1acca..1adf2968 100644 --- a/clean/rr_f/proxy/tests/test_hook_dll.cpp +++ b/clean/rr_f/proxy/tests/test_hook_dll.cpp @@ -530,12 +530,13 @@ int main(int argc, char** argv) { // Matching version: the ASI redirected our RR-role IAT slots (observed through the log). { std::vector L = read_lines(log_path); - // RR guard: no other RR plugin here (the stand-in host's init patch, the delay helper's thunks): the guard - // stays quiet (one clean check line, no "stays off" / second-copy / later-plugin line) + // RR guard: no other module here (the stand-in host's init patch, the delay helper's thunks): the guard + // stays quiet (one clean check line, no named module / "stays off" / second-copy / later-module line) CHECK(count(L, "hook: coexistence check at load: no other Ray Reconstruction plugin found (") == 1); CHECK(count(L, "another Ray Reconstruction plugin is active") == 0); + CHECK(count(L, "another module hooks the game's RR calls: ") == 0); CHECK(count(L, "a second copy of WrongGPU RR is loaded") == 0); - CHECK(count(L, "a plugin loaded after WrongGPU replaced its hooks") == 0); + CHECK(count(L, "took the RR calls after WrongGPU") == 0); #if WG_TEST_DELAYLOAD CHECK(count(L, "loaded for the exe's delay-load import") == 1); CHECK(count(L, "patched IAT slot") == 0); // the exe has no plain import of the interface diff --git a/clean/rr_f/proxy/tests/test_rr_guard.cpp b/clean/rr_f/proxy/tests/test_rr_guard.cpp index 704eced0..9d5edbb8 100644 --- a/clean/rr_f/proxy/tests/test_rr_guard.cpp +++ b/clean/rr_f/proxy/tests/test_rr_guard.cpp @@ -1,16 +1,22 @@ // SPDX-License-Identifier: MIT // RR guard: CPU unit test of the coexistence guard's pieces without process state (src/rr_guard.h). // - safe reads: a readable buffer; a PAGE_NOACCESS page, a reserved page, a guard page (the guard flag must survive the -// check: nothing touched it); a read across a readable / unreadable boundary; the cached reader's structured-exception -// path (a page made unreadable after its region was cached); the cache keeps VirtualQuery calls few; +// check, with no other thread changing the page meanwhile); a read across a readable / unreadable boundary; the +// cached reader's structured-exception path (a page made unreadable after its region was cached); the cache keeps +// VirtualQuery calls few; +// - PeView: the real exe's headers; synthetic headers with a bad e_lfanew (negative, inside the DOS header, absurd, NT +// headers past SizeOfImage), directories past SizeOfImage or wrapping, too few directories, PE32, no signature; // - decode_jump: every jump form, and a jmp [rip+disp32] whose cell is not readable; // - classify: synthetic modules (ranges of one allocation) and anonymous relays: the interface's own code, a hook jump // to another module, a jump inside the interface, the linker's import thunk, a relay chain to the host, exactly // kMaxHops jumps (followed) and one more (too many hops), a relay loop, anonymous code, an unreadable target, an // execute-only relay page (read), a copy of WrongGPU RR, WrongGPU.asi, the exe's thunk, the host's second module; -// - Verdict: only a positive finding (a named foreign module, a copy of WrongGPU RR) is a finding; unreadable memory, -// too many hops, non-jumping anonymous code and the exe's own code are inconclusive (counted, kind stays clean); -// precedence, override parsing, the exact log lines; +// - Verdict: a copy of WrongGPU RR wins; a named foreign module is kept (the first one) as kForeign; unreadable memory, +// too many hops, non-jumping anonymous code and the exe's own code are counted as unclear; +// - decide: with NO second RR provider (a game-owned wrapper DLL, a host helper in a third image, an overlay-style +// wrapper, a forwarded export, the heap-table and helper-table host layouts) RR stays active at every stage unless +// rr_other_plugin=yield (take: in front, never off); a copy of WrongGPU RR switches it off in every mode; a decision +// already taken stays; override parsing (off | take | yield), the exact log lines; // - Decision: 32 threads make the "first call" at once: decide runs exactly once, every thread sees the same state. #define WIN32_LEAN_AND_MEAN #include @@ -73,7 +79,7 @@ int main() { CHECK(!safe_read(blk + 3 * kPage, b, 8)); // reserved, not committed CHECK(!safe_read(blk + kPage - 4, b, 8)); // across readable -> unreadable MEMORY_BASIC_INFORMATION m; - CHECK(VirtualQuery(blk + 2 * kPage, &m, sizeof m) && (m.Protect & PAGE_GUARD)); // never touched: still a guard page + CHECK(VirtualQuery(blk + 2 * kPage, &m, sizeof m) && (m.Protect & PAGE_GUARD)); // untouched by the check uint64_t p64 = 0; CHECK(!safe_get(blk + 3 * kPage, &p64)); // an execute-only page counts as readable (a hooking library's trampolines); the copy is guarded either way @@ -315,7 +321,7 @@ int main() { CHECK(ok.kind == Verdict::kClean && ok.unclear == 0); // positive findings v.add(classify(iface + 384, env, true), "the export E of iface.dll", false, false); - CHECK(v.kind == Verdict::kOther && v.other_module == foreign); + CHECK(v.kind == Verdict::kForeign && v.other_module == foreign && v.module == "other.asi" && v.foreign == 1); CHECK(v.detail == "the export E of iface.dll leads to other.asi (through 3 hook jumps)"); v.add(classify(foreign + 8, env, false), "the import slot M of game.exe", false, false); CHECK(v.detail == "the export E of iface.dll leads to other.asi (through 3 hook jumps)"); // the first one stays @@ -325,39 +331,164 @@ int main() { CHECK(v.kind == Verdict::kOwnCopy && v.reads == 13); Verdict f4; // a decoded chain of exactly kMaxHops jumps that ends in a foreign module is positive f4.add(classify(anon + 2048, env, false), "the import slot P of game.exe", false, false); - CHECK(f4.kind == Verdict::kOther && f4.detail == "the import slot P of game.exe leads to other.asi (through 4 hook jumps)"); + CHECK(f4.kind == Verdict::kForeign && f4.detail == "the import slot P of game.exe leads to other.asi (through 4 hook jumps)"); Verdict f5; // the unreadable first read does not hide a later positive finding f5.add(classify(dead + 32, env, false), "the import slot F of game.exe", false, false); f5.add(classify(foreign + 8, env, false), "the import slot Q of game.exe", false, false); - CHECK(f5.kind == Verdict::kOther && f5.unclear == 1 && f5.detail == "the import slot Q of game.exe leads to other.asi"); + CHECK(f5.kind == Verdict::kForeign && f5.unclear == 1 && f5.detail == "the import slot Q of game.exe leads to other.asi"); CHECK(trusted(Owner::kWrongGpu, false, false) && !trusted(Owner::kUnknown, true, true) && !trusted(Owner::kForeign, true, true) && !trusted(Owner::kOwnCopy, true, true)); + + // ---- layouts with NO second RR provider: a named module on the path is inconclusive, RR stays active (off) at + // every stage; only rr_other_plugin=yield switches it off, take puts WrongGPU RR in front while it still can + { + Env heap = env; // the host's API table on the heap: no module, so nothing but InitializeASI's caller is the host + heap.host_alt = nullptr; + Env helper_table = env; // the table in a helper image: a module, but not the one that patched + helper_table.host_alt = wgasi; + void* fwd_fn = foreign + 200; // a forwarded export: GetProcAddress resolves into the implementation DLL + struct Layout { const char* name; Where w; }; + const Layout layouts[] = { + {"game-owned wrapper DLL", classify(foreign + 8, env, false)}, // the exe's slot wraps through it + {"host helper in a third image", classify(foreign + 16, env, false)}, // the host is host.dll, not it + {"overlay-style wrapper", classify(iface + 384, env, true)}, // export -> relay -> relay -> module + {"forwarded export", classify(fwd_fn, env, true)}, // the export's address is in it + {"heap-table host layout", classify(foreign + 24, heap, false)}, // the real host's own patch + {"helper-table host layout", classify(foreign + 32, helper_table, false)}, + }; + for (const Layout& l : layouts) { + Verdict lv; + lv.add(l.w, std::string("the import slot X of game.exe (") + l.name + ")", false, false); + CHECK(lv.kind == Verdict::kForeign && lv.module == "other.asi"); + for (Stage st : {Stage::kLoad, Stage::kRoutes, Stage::kLate}) { + CHECK(decide(lv.kind, Mode::kOff, st, State::kActive) == State::kActive); // stays active + CHECK(decide(lv.kind, Mode::kOff, st, State::kTaken) == State::kTaken); + CHECK(decide(lv.kind, Mode::kTake, st, State::kActive) == + (st == Stage::kLate ? State::kActive : State::kTaken)); // never off with take + CHECK(decide(lv.kind, Mode::kYield, st, State::kActive) == + (st == Stage::kLoad ? State::kOff : State::kPassThrough)); + } + } + // the host's own patch, when the host is known (caller of InitializeASI or the table's module), is not named + Env split = env; + split.host_alt = foreign; + Verdict hv; + hv.add(classify(foreign + 24, split, false), "the import slot X of game.exe", false, false); + CHECK(hv.kind == Verdict::kClean && hv.unclear == 0 && hv.foreign == 0); + } + // ---- evidence that is positive by contract: a second copy of WrongGPU RR, at every stage and in every mode + for (Mode m : {Mode::kOff, Mode::kTake, Mode::kYield}) { + CHECK(decide(Verdict::kOwnCopy, m, Stage::kLoad, State::kActive) == State::kOwnCopy); + CHECK(decide(Verdict::kOwnCopy, m, Stage::kRoutes, State::kActive) == State::kPassThrough); + CHECK(decide(Verdict::kOwnCopy, m, Stage::kLate, State::kTaken) == State::kPassThrough); + for (Stage st : {Stage::kLoad, Stage::kRoutes, Stage::kLate}) { + CHECK(decide(Verdict::kClean, m, st, State::kActive) == State::kActive); // clean: nothing changes + CHECK(decide(Verdict::kClean, m, st, State::kTaken) == State::kTaken); + for (State done : {State::kOff, State::kOwnCopy, State::kPassThrough}) // a decision already taken stays + for (Verdict::Kind k : {Verdict::kClean, Verdict::kOwnCopy, Verdict::kForeign}) + CHECK(decide(k, m, st, done) == done); + } + } VirtualFree(blk, 0, MEM_RELEASE); } + // ---------------------------------------------------------------- PeView: header and directory bounds + { + // the real exe: headers accepted, its import directory inside the image + Reader r; + PeView pe; + CHECK(pe.open(GetModuleHandleW(nullptr), r) && pe.size_of_image() > 0); + uint32_t rva = 0, size = 0; + CHECK(pe.dir(IMAGE_DIRECTORY_ENTRY_IMPORT, &rva, &size) && pe.at(rva, size) != nullptr); + CHECK(pe.at(pe.size_of_image(), 0) != nullptr && pe.at(pe.size_of_image(), 1) == nullptr); + CHECK(pe.at(0xFFFFFFFFull, 2) == nullptr && pe.at(8, 0xFFFFFFFFFFFFFFF0ull) == nullptr); // no wrap-around + // a synthetic image: DOS header, NT headers at 0x80, SizeOfImage 0x2000, in 3 committed pages (one past the image) + uint8_t* img = static_cast(VirtualAlloc(nullptr, 3 * kPage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + CHECK(img != nullptr); + auto* dos = reinterpret_cast(img); + auto* nt = reinterpret_cast(img + 0x80); + auto reset = [&] { + memset(img, 0, 3 * kPage); + dos->e_magic = IMAGE_DOS_SIGNATURE; + dos->e_lfanew = 0x80; + nt->Signature = IMAGE_NT_SIGNATURE; + nt->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC; + nt->OptionalHeader.SizeOfImage = 0x2000; + nt->OptionalHeader.NumberOfRvaAndSizes = 16; + nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT] = {0x1000, 0x100}; + }; + reset(); + PeView s; + CHECK(s.open(img, r) && s.size_of_image() == 0x2000 && s.dir(IMAGE_DIRECTORY_ENTRY_IMPORT, &rva, &size) && + rva == 0x1000 && size == 0x100); + // e_lfanew negative, inside the DOS header, absurdly far, or with the NT headers past SizeOfImage: refused + for (LONG bad : {(LONG)-8, (LONG)4, (LONG)0x7FFFFFF0, (LONG)0x1FF0}) { + reset(); + if (bad == 0x1FF0) { // the NT headers copied there (readable memory, but outside the image's 0x2000 bytes) + memcpy(img + 0x1FF0, nt, sizeof(IMAGE_NT_HEADERS64)); + } + dos->e_lfanew = bad; + PeView b; + CHECK(!b.open(img, r)); + } + // a directory whose RVA or size runs past SizeOfImage (or wraps): not handed out + const IMAGE_DATA_DIRECTORY bad_dirs[] = {{0x2000, 1}, {0x1F00, 0x200}, {0xFFFFFFF0, 0x20}, {0x10, 0xFFFFFFF8}}; + for (const IMAGE_DATA_DIRECTORY& d : bad_dirs) { + reset(); + nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT] = d; + PeView b; + CHECK(b.open(img, r) && !b.dir(IMAGE_DIRECTORY_ENTRY_IMPORT, &rva, &size)); + } + // fewer directories than the index: absent; a PE32 optional header or a wrong signature: refused + reset(); + nt->OptionalHeader.NumberOfRvaAndSizes = 1; + PeView few; + CHECK(few.open(img, r) && !few.dir(IMAGE_DIRECTORY_ENTRY_IMPORT, &rva, &size)); + reset(); + nt->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR32_MAGIC; + PeView p32; + CHECK(!p32.open(img, r)); + reset(); + nt->Signature = 0; + PeView nosig; + CHECK(!nosig.open(img, r)); + VirtualFree(img, 0, MEM_RELEASE); + } + // ---------------------------------------------------------------- the override, the log lines { std::string note; - CHECK(!override_take("", ¬e) && note.empty()); - CHECK(!override_take("off", ¬e) && note.empty()); - CHECK(override_take("take", ¬e) && note.empty()); - CHECK(override_take(" Take \r", ¬e) && note.empty()); - CHECK(!override_take("ours", ¬e) && - note == "rr_other_plugin=ours in wronggpu-rr.ini not recognised (off | take); off is used"); - // the beginnings the launcher's Last run page matches (HOOK-MODE.md): exact, no prefix + CHECK(parse_mode("", ¬e) == Mode::kOff && note.empty()); + CHECK(parse_mode("off", ¬e) == Mode::kOff && note.empty()); + CHECK(parse_mode("take", ¬e) == Mode::kTake && note.empty()); + CHECK(parse_mode(" Take \r", ¬e) == Mode::kTake && note.empty()); + CHECK(parse_mode("yield", ¬e) == Mode::kYield && note.empty()); + CHECK(parse_mode("YIELD\t", ¬e) == Mode::kYield && note.empty()); + CHECK(parse_mode("ours", ¬e) == Mode::kOff && + note == "rr_other_plugin=ours in wronggpu-rr.ini not recognised (off | take | yield); off is used"); + CHECK(strcmp(mode_word(Mode::kOff), "off") == 0 && strcmp(mode_word(Mode::kTake), "take") == 0 && + strcmp(mode_word(Mode::kYield), "yield") == 0); + // the beginnings a reader matches (HOOK-MODE.md): exact, no prefix + const std::string fstem = "another module hooks the game's RR calls: "; + const std::string d = "the import slot X of Game.exe leads to Other.dll"; + CHECK(line_foreign("Other.dll", d, Tail::kStaysActive) == + fstem + "Other.dll (" + d + "); it is not known to be a Ray Reconstruction plugin: WrongGPU RR stays active " + "(rr_other_plugin=yield in wronggpu-rr.ini keeps WrongGPU RR off in this case)"); + CHECK(line_foreign("Other.dll", d, Tail::kTakeInFront) == + fstem + "Other.dll (" + d + "); rr_other_plugin=take: WrongGPU RR goes in front of it (it gets the game's " + "other calls, no RR work)"); + CHECK(line_foreign("Other.dll", d, Tail::kYieldOff) == + fstem + "Other.dll (" + d + "); rr_other_plugin=yield: WrongGPU RR stays off (nothing patched)"); + CHECK(line_foreign("Other.dll", d, Tail::kYieldPassing) == + fstem + "Other.dll (" + d + "); rr_other_plugin=yield: WrongGPU RR stays off (WrongGPU's handlers pass every " + "call on unchanged)"); + // only yield says "stays off"; nothing about a named module claims it is a Ray Reconstruction plugin const std::string stem = "another Ray Reconstruction plugin is active; WrongGPU RR stays off"; - CHECK(line_other("D") == stem + " (D; nothing patched; rr_other_plugin=take in wronggpu-rr.ini uses WrongGPU's " - "instead)"); - CHECK(line_other("D", true) == stem + " (D; WrongGPU's handlers pass every call on unchanged; rr_other_plugin=take " - "in wronggpu-rr.ini uses WrongGPU's instead)"); - CHECK(line_other_later("D") == stem + " (D; it loaded after WrongGPU: WrongGPU passes every call on unchanged; to " - "use WrongGPU RR, move it aside)"); - CHECK(line_cannot_take("D") == "a plugin loaded after WrongGPU replaced its hooks; rr_other_plugin=take cannot be " - "applied: WrongGPU RR stays off and passes every call on unchanged (D); move it aside " - "to use WrongGPU RR"); - CHECK(line_take("D") == "another Ray Reconstruction plugin is active; rr_other_plugin=take: WrongGPU RR goes in " - "front of it (D; it gets the game's other calls, no RR work)"); - CHECK(line_take("D").compare(0, stem.size(), stem) != 0); // RR is on: not a "stays off" line + for (Tail t : {Tail::kStaysActive, Tail::kTakeInFront, Tail::kYieldOff, Tail::kYieldPassing}) { + const std::string l = line_foreign("M", "D", t); + CHECK(l.compare(0, fstem.size(), fstem) == 0 && l.find("plugin is active") == std::string::npos); + CHECK((l.find("stays off") != std::string::npos) == (t == Tail::kYieldOff || t == Tail::kYieldPassing)); + } CHECK(line_own_copy("A", "B") == "a second copy of WrongGPU RR is loaded (A is active); this copy (B) stays off"); CHECK(line_ngx_other() == stem + " (NGX route only: the host refused WrongGPU's RR provider, another provider " "holds it; the game-interface route is decided on its own)"); diff --git a/clean/rr_f/proxy/tests/test_rr_guard_dll.cpp b/clean/rr_f/proxy/tests/test_rr_guard_dll.cpp index 2f2eccbc..9922289f 100644 --- a/clean/rr_f/proxy/tests/test_rr_guard_dll.cpp +++ b/clean/rr_f/proxy/tests/test_rr_guard_dll.cpp @@ -1,39 +1,51 @@ // SPDX-License-Identifier: MIT // RR guard: end-to-end test of the coexistence guard in the hook-mode plugin (src/hook_dll.cpp + rr_guard.h). // The executable is the fake game, as in test_hook_dll.cpp: it imports the RR path's functions by name from the stand-in -// interface (tests/gen_fake_original.py). The "other Ray Reconstruction plugin" is our own stand-in, -// wgtest_other_rr.dll (tests/fake_other_rr.cpp); no third-party file is used. -// test_rr_guard_dll.exe [--take] -// Only a POSITIVE finding switches WrongGPU RR off (a named foreign module, also through decoded hook jumps; a second -// copy of WrongGPU RR); what the scan cannot explain is logged once as inconclusive and WrongGPU RR stays active. -// Modes (import build): -// clean no other plugin: active; 16 threads make the first call at once: one re-check line; the scan cost -// first the other plugin redirected the exe's import slots before ours loaded (wrapping): off, nothing patched -// inline the other plugin put a jmp [rip] on the evaluate export: off -// relay the same through a jmp rel32 to an anonymous relay: off ("through 2 hook jumps") -// execonly one import slot leads to an execute-only relay page that jumps into the other plugin: off (the relay -// page is read although it is PAGE_EXECUTE) -// anon one import slot leads to code outside every module that does not jump on: inconclusive, stays active -// noaccess one import slot leads to a PAGE_NOACCESS page: "could not be read", inconclusive, stays active, no fault +// interface (tests/gen_fake_original.py). The "other module" is our own stand-in, wgtest_other_rr.dll +// (tests/fake_other_rr.cpp), and further copies of it under other file names; no third-party file is used. +// test_rr_guard_dll.exe [--take | --yield] +// WrongGPU RR switches itself off only on evidence that is positive by contract: a second copy of WrongGPU RR, or the +// host's plugin API refusing our registration. A named module on the call path is inconclusive: it is named in one +// line and WrongGPU RR stays active; --yield (rr_other_plugin=yield) makes it switch WrongGPU RR off, --take +// (rr_other_plugin=take) puts WrongGPU RR in front of it. +// Modes (import build). Named module on the path, RR stays active (no second RR provider in the innocent ones): +// first the stand-in RR plugin redirected the exe's import slots before ours loaded (wrapping) +// inline the stand-in RR plugin put a jmp [rip] on the evaluate export +// relay the same through a jmp rel32 to an anonymous relay ("through 2 hook jumps") +// execonly one import slot leads to an execute-only relay page that jumps into the stand-in (the relay is read) +// wrapper a game-owned wrapper DLL (wgtest_gamewrap.dll, innocent) wraps the exe's import slots +// overlay an overlay-style DLL (wgtest_overlay.dll, innocent) hooks the evaluate export through a relay +// forward the exe's evaluate slot is bound to an implementation DLL (wgtest_impl.dll, innocent), as the loader +// binds a forwarded export +// helper a separate loader DLL calls InitializeASI and holds the host table; a host helper in a third image +// (wgtest_hosthelper.dll, innocent) patched the slots +// hostsplit a separate loader DLL calls InitializeASI; the host DLL (wgtest_other_rr.dll, innocent) holds the API +// table and patched the slots +// heaptable the same with the host's API table on the heap (no module) +// helpertable the same with the host's API table in a helper image (wgtest_hosttable.dll) +// Nothing could be told, RR stays active (one inconclusive line): +// anon one import slot leads to code outside every module that does not jump on +// noaccess one import slot leads to a PAGE_NOACCESS page ("could not be read"), no fault // guardpage one import slot leads to a guard page: the same, and the page is still a guard page afterwards -// exe one import slot leads into the exe's own code (a separate loader DLL calls InitializeASI, so the exe is -// not the host): inconclusive, stays active -// hops one import slot leads through five relay jumps (more than kMaxHops) to the other plugin: inconclusive, -// stays active -// hostsplit a separate loader DLL calls InitializeASI; the real host (a DLL holding the API table) patched the slots: -// found at load, then OptiPluginInit shows the module is the host and the load check runs again: active -// late the other plugin wrapped our hooks after InitializeASI: 16 threads make the first call at once: one -// decision, one line, every call passed on unchanged -// late-replace the other plugin replaced our hooks after InitializeASI (no call reaches us): found at OptiPluginInit -// provider the other plugin holds the host's NGX RR provider: NGX route only, the game-interface route stays +// exe one import slot leads into the exe's own code (a separate loader DLL calls InitializeASI) +// hops one import slot leads through five relay jumps (more than kMaxHops) to the stand-in +// Later modules: +// late the stand-in RR plugin wrapped our hooks after InitializeASI: 16 threads make the first call at once: +// one decision, one line naming it, WrongGPU RR stays active behind it +// late-replace the stand-in replaced our hooks after InitializeASI: named at OptiPluginInit, stays active +// Positive by contract, WrongGPU RR (or that route) switches off: +// provider the stand-in holds the host's NGX RR provider: the NGX route stays off, the game-interface route stays // owncopy WrongGPU RR and four more copies under other file names: the others stay off and register nothing; the // copies' InitializeASI / OptiPluginInit run from threads while 16 game threads make the first call (every // copy writes the one log at once: no torn line); freeing an inactive copy writes no exit summary -// --take (wronggpu-rr.ini rr_other_plugin=take): first / inline: WrongGPU RR in front; late: the can't-take line. +// clean no other module: active; 16 threads make the first call at once: one re-check line; the scan cost +// --take: first / inline: WrongGPU RR in front; late: as without (never off). --yield: wrapper: off, nothing patched. // Modes (built with WG_TEST_NOIMPORT: the exe does not link the interface, the host routes are used): -// route no other plugin: our routes continue to the interface -// route-other the other plugin's routes were registered first (under ours): passing (take: RR ours) -// route-inline the other plugin patched the evaluate export before the host hooked the module: off, no routes +// route no other module: our routes continue to the interface +// route-other the stand-in's routes were registered first (under ours): RR ours, the other calls continue through +// it (take: the same, "in front" line; yield: our routes pass every call on) +// route-inline the stand-in patched the evaluate export before the host hooked the module: named, routes registered +// route-refused the host refuses our routes (positive by contract): the game-interface route stays off #define WIN32_LEAN_AND_MEAN #include @@ -121,6 +133,17 @@ size_t count_starting(const std::vector& v, const std::string& star } return n; } +// lines that start with `start` and end with `end` +size_t count_line(const std::vector& v, const std::string& start, const std::string& end) { + size_t n = 0; + for (const auto& s : v) { + size_t at = 13; + if (s.compare(at, 2, "f=") == 0) at = s.find(' ', at) + 1; + n += s.size() >= at + start.size() + end.size() && s.compare(at, start.size(), start) == 0 && + s.compare(s.size() - end.size(), end.size(), end) == 0; + } + return n; +} void write_text(const std::wstring& p, const char* s) { FILE* f = _wfopen(p.c_str(), L"wb"); if (f) { fputs(s, f); fclose(f); } @@ -143,12 +166,14 @@ std::map handler_of_plugin[2]; // [0] WrongGPU, [1] the oth WgHostMenuPlugin* const kOurs = reinterpret_cast(0x1000); WgHostMenuPlugin* const kTheirs = reinterpret_cast(0x2000); int route_regs[2] = {0, 0}, ngx_regs = 0; +bool refuse_routes = false; // route-refused: the host's API says no WgHostMenuPlugin* ngx_owner = nullptr; void (*callback)(void*, uint32_t, uint32_t, uint32_t, void*) = nullptr; void* callback_user = nullptr; bool register_routes(WgHostMenuPlugin* p, const WgHostSlRoute* r, uint32_t n) { const int who = p == kOurs ? 0 : 1; ++route_regs[who]; + if (refuse_routes) return false; for (uint32_t i = 0; i < n; ++i) { const std::string name = r[i].export_name; void* next = head.count(name) ? head[name] : reinterpret_cast(GetProcAddress(iface, r[i].export_name)); @@ -197,6 +222,11 @@ int at_once(int n, F f, WgResultCode want) { return ok.load(); } +template +F fn(HMODULE m, const char* name) { + return m ? reinterpret_cast(GetProcAddress(m, name)) : nullptr; +} + } // namespace int main(int argc, char** argv) { @@ -204,37 +234,60 @@ int main(int argc, char** argv) { std::string stage = argv[1]; if (stage.back() != '\\') stage += '\\'; const std::string mode = argv[2]; - bool take = false; - for (int i = 3; i < argc; ++i) take = take || strcmp(argv[i], "--take") == 0; + bool take = false, yield = false; + for (int i = 3; i < argc; ++i) { + take = take || strcmp(argv[i], "--take") == 0; + yield = yield || strcmp(argv[i], "--yield") == 0; + } const std::wstring ws = widen(stage); const std::wstring log_path = ws + (WG_BINDING_PROBE ? L"wronggpu-rr-probe.log" : L"wronggpu-rr.log"); DeleteFileW(log_path.c_str()); DeleteFileW((ws + L"wronggpu-rr.ini").c_str()); if (take) write_text(ws + L"wronggpu-rr.ini", "rr_other_plugin = take\r\n"); + if (yield) write_text(ws + L"wronggpu-rr.ini", "rr_other_plugin = yield\r\n"); CreateDirectoryW((ws + L"data").c_str(), nullptr); write_text(ws + L"data\\wronggpu.ini", "[wronggpu]\r\nrr_mode = accurate\r\n"); SetEnvironmentVariableW(L"WG_DATA_DIR", (ws + L"data\\").c_str()); SetEnvironmentVariableW(L"WG_RR_SLOT_CHECKS", L"0"); const std::string label = std::string("test_rr_guard_dll (") + (WG_BINDING_PROBE ? "probe" : "release") + ", " + mode + - (take ? ", take" : "") + ")"; + (take ? ", take" : "") + (yield ? ", yield" : "") + ")"; HMODULE other = LoadLibraryW((ws + L"wgtest_other_rr.dll").c_str()); CHECK(other != nullptr); if (!other) TEST_SUMMARY(label.c_str()); - auto or_state = reinterpret_cast(GetProcAddress(other, "wgtest_or_state")); - auto or_patch_iat = reinterpret_cast(GetProcAddress(other, "wgtest_or_patch_iat")); - auto or_set_slot = - reinterpret_cast(GetProcAddress(other, "wgtest_or_set_slot")); - auto or_patch_export = reinterpret_cast(GetProcAddress(other, "wgtest_or_patch_export")); - auto or_routes = reinterpret_cast(GetProcAddress(other, "wgtest_or_routes")); - auto or_ngx = reinterpret_cast(GetProcAddress(other, "wgtest_or_register_ngx")); - auto or_host_table = reinterpret_cast(GetProcAddress(other, "wgtest_or_host_table")); + using PatchIat = int (*)(HMODULE, const char*, int); + using PatchExport = int (*)(HMODULE, const char*, int); + using Innocent = void (*)(int); + using HostTable = const WgHostMenuApi* (*)(const WgHostMenuApi*); + auto or_state = fn(other, "wgtest_or_state"); + auto or_patch_iat = fn(other, "wgtest_or_patch_iat"); + auto or_set_slot = fn(other, "wgtest_or_set_slot"); + auto or_patch_export = fn(other, "wgtest_or_patch_export"); + auto or_routes = fn(other, "wgtest_or_routes"); + auto or_ngx = fn(other, "wgtest_or_register_ngx"); + auto or_host_table = fn(other, "wgtest_or_host_table"); + auto or_innocent = fn(other, "wgtest_or_innocent"); const OrState* os = or_state(); + // another copy of the stand-in under another file name (its own state): the innocent layouts + auto load_copy = [&](const wchar_t* file) { + HMODULE m = LoadLibraryW((ws + file).c_str()); + CHECK(m != nullptr); + if (Innocent f = fn(m, "wgtest_or_innocent")) f(1); + return m; + }; HMODULE exe = GetModuleHandleW(nullptr); const std::string exe_leaf = "test_rr_guard_dll.exe"; const std::string iface_leaf = kWgInterposerFile; const std::string evaluate_name = kWgRoleNames[kEvaluate]; const std::string stem = "another Ray Reconstruction plugin is active; WrongGPU RR stays off ("; + const std::string fstem = "another module hooks the game's RR calls: "; + const std::string tail_active = "; it is not known to be a Ray Reconstruction plugin: WrongGPU RR stays active " + "(rr_other_plugin=yield in wronggpu-rr.ini keeps WrongGPU RR off in this case)"; + const std::string tail_take = "; rr_other_plugin=take: WrongGPU RR goes in front of it (it gets the game's other calls, " + "no RR work)"; + const std::string tail_yield_off = "; rr_other_plugin=yield: WrongGPU RR stays off (nothing patched)"; + const std::string tail_yield_pass = "; rr_other_plugin=yield: WrongGPU RR stays off (WrongGPU's handlers pass every " + "call on unchanged)"; const WgHostMenuApi api = host::table(); auto load_asi = [&](const std::wstring& file, void (**init)(), WgHostMenuInitFn* pinit) { HMODULE m = LoadLibraryW((ws + file).c_str()); @@ -253,12 +306,47 @@ int main(int argc, char** argv) { host::iface = iface; FoState* fo = reinterpret_cast(GetProcAddress(iface, "wgtest_fo_state"))(); const bool late = mode == "late" || mode == "late-replace"; - const bool stays_on = mode == "anon" || mode == "noaccess" || mode == "guardpage" || mode == "exe" || mode == "hops"; - // ---- the other plugin before ours + const bool unclear_mode = mode == "anon" || mode == "noaccess" || mode == "guardpage" || mode == "exe" || mode == "hops"; + const bool host_layout = mode == "hostsplit" || mode == "heaptable" || mode == "helpertable"; + const bool loader_mode = host_layout || mode == "helper" || mode == "exe"; + const std::string self_slot = "the import slot "; + // a named module on the path at load: its file name and the beginning of the line's detail + std::string fmod, fdetail; + // ---- other modules before ours void* odd_page = nullptr; - if (mode == "first" || mode == "hostsplit") CHECK(or_patch_iat(exe, kWgInterposerFile, 1) >= 6); // (hostsplit: the host's own) - if (mode == "inline") CHECK(or_patch_export(iface, evaluate_name.c_str(), 0) == 1); - if (mode == "relay") CHECK(or_patch_export(iface, evaluate_name.c_str(), 1) == 1); + if (mode == "first" || host_layout) { + if (host_layout) or_innocent(1); // the host itself (not an RR plugin) + CHECK(or_patch_iat(exe, kWgInterposerFile, 1) >= 6); + fmod = "wgtest_other_rr.dll"; + fdetail = self_slot; // the first redirected slot in import order + } + if (mode == "inline" || mode == "relay") { + CHECK(or_patch_export(iface, evaluate_name.c_str(), mode == "relay") == 1); + fmod = "wgtest_other_rr.dll"; + fdetail = "the export " + evaluate_name + " of " + iface_leaf + " leads to wgtest_other_rr.dll (through " + + (mode == "relay" ? "2 hook jumps)" : "1 hook jump)"); + } + if (mode == "wrapper") { + CHECK(fn(load_copy(L"wgtest_gamewrap.dll"), "wgtest_or_patch_iat")(exe, kWgInterposerFile, 1) >= 6); + fmod = "wgtest_gamewrap.dll"; + fdetail = self_slot; + } + if (mode == "helper") { + CHECK(fn(load_copy(L"wgtest_hosthelper.dll"), "wgtest_or_patch_iat")(exe, kWgInterposerFile, 1) >= 6); + fmod = "wgtest_hosthelper.dll"; + fdetail = self_slot; + } + if (mode == "overlay") { + CHECK(fn(load_copy(L"wgtest_overlay.dll"), "wgtest_or_patch_export")(iface, evaluate_name.c_str(), 1) == 1); + fmod = "wgtest_overlay.dll"; + fdetail = "the export " + evaluate_name + " of " + iface_leaf + " leads to wgtest_overlay.dll (through 2 hook jumps)"; + } + if (mode == "forward") { + auto bind_one = fn(load_copy(L"wgtest_impl.dll"), "wgtest_or_bind_one"); + CHECK(bind_one && bind_one(exe, kWgInterposerFile, evaluate_name.c_str()) == 1); + fmod = "wgtest_impl.dll"; + fdetail = self_slot + evaluate_name + " of " + exe_leaf + " leads to wgtest_impl.dll"; + } if (mode == "anon") { odd_page = VirtualAlloc(nullptr, 4096, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE); memset(odd_page, 0xC3, 4096); // ret: code outside every module that does not jump on @@ -271,7 +359,7 @@ int main(int argc, char** argv) { } if (mode == "exe") CHECK(or_set_slot(exe, kWgInterposerFile, evaluate_name.c_str(), reinterpret_cast(&read_lines)) == 1); if (mode == "hops" || mode == "execonly") { - // relay jumps (jmp [rip+0]; dq target) in code outside every module that lead to a function of the other plugin + // relay jumps (jmp [rip+0]; dq target) in code outside every module that lead to a function of the stand-in uint8_t* p = static_cast(VirtualAlloc(nullptr, 4096, MEM_RESERVE | MEM_COMMIT, PAGE_EXECUTE_READWRITE)); CHECK(p != nullptr); const void* to_other = reinterpret_cast(GetProcAddress(other, "wgtest_or_state")); @@ -286,6 +374,8 @@ int main(int argc, char** argv) { if (mode == "execonly") { DWORD old = 0; CHECK(VirtualProtect(p, 4096, PAGE_EXECUTE, &old)); // execute-only: the guard still reads the relay + fmod = "wgtest_other_rr.dll"; + fdetail = self_slot + evaluate_name + " of " + exe_leaf + " leads to wgtest_other_rr.dll (through 1 hook jump)"; } odd_page = p; CHECK(or_set_slot(exe, kWgInterposerFile, evaluate_name.c_str(), p) == 1); @@ -296,21 +386,21 @@ int main(int argc, char** argv) { load_asi(widen(kWgHookFile), &init, &plugin_init); if (!init || !plugin_init) TEST_SUMMARY(label.c_str()); const WgHostMenuApi* host_api = &api; // the table OptiPluginInit gets - if (mode == "hostsplit" || mode == "exe") { - // a separate ASI loader (another module) calls InitializeASI. A second instance of the stand-in DLL plays the - // loader. hostsplit: the real host is wgtest_other_rr.dll, which holds the API table and patched the slots itself. - // exe: the host is a DLL, as in a game (when this test exe called InitializeASI itself, the exe would be the host - // and its code trusted), so a slot that leads into the exe's code is the exe's own code. + if (loader_mode) { + // a separate ASI loader (another module) calls InitializeASI: a second instance of the stand-in DLL plays the loader + // (in a game the host is a DLL; when this test exe called InitializeASI itself, the exe would be the host) HMODULE loader = LoadLibraryW((ws + L"wgtest_loader.dll").c_str()); CHECK(loader != nullptr); - auto call_init = loader ? reinterpret_cast(GetProcAddress(loader, "wgtest_or_call_init")) : nullptr; + auto call_init = fn(loader, "wgtest_or_call_init"); CHECK(call_init != nullptr && or_host_table != nullptr); if (!call_init || !or_host_table) TEST_SUMMARY(label.c_str()); call_init(init); - if (mode == "hostsplit") { - host_api = or_host_table(&api); - CHECK(host_api != nullptr); - } + if (mode == "hostsplit") host_api = or_host_table(&api); // in the host DLL that patched + if (mode == "heaptable") host_api = new WgHostMenuApi(api); // on the heap: no module + if (mode == "helpertable") // in a helper image + host_api = fn(load_copy(L"wgtest_hosttable.dll"), "wgtest_or_host_table")(&api); + if (mode == "helper") host_api = fn(loader, "wgtest_or_host_table")(&api); // in the loader itself + CHECK(host_api != nullptr); } else { init(); // (owncopy: this copy is the active one, the others follow below) } @@ -327,7 +417,7 @@ int main(int argc, char** argv) { CHECK(c.module != nullptr && c.init != nullptr && c.plugin_init != nullptr); if (c.module) copies.push_back(c); } - // ---- the other plugin after ours + // ---- the stand-in RR plugin after ours if (mode == "late") CHECK(or_patch_iat(exe, kWgInterposerFile, 1) >= 6); // wraps our handlers if (mode == "late-replace") CHECK(or_patch_iat(exe, kWgInterposerFile, 0) >= 6); // replaces them // OptiPluginInit (late-replace: the check that finds it, as no call reaches our handlers any more); "late" makes the @@ -338,10 +428,10 @@ int main(int argc, char** argv) { // write wronggpu-rr.log at the same moment; no line may be torn, the other copies register nothing. std::atomic go{0}, answered{0}, registered{0}; std::vector th; - auto spawn = [&](auto fn) { - th.emplace_back([&go, fn] { + auto spawn = [&](auto f) { + th.emplace_back([&go, f] { while (!go.load()) std::this_thread::yield(); - fn(); + f(); }); }; spawn([&] { plugin_init(host_api, host::kOurs); }); @@ -368,27 +458,34 @@ int main(int argc, char** argv) { CHECK_EQ(ok, 16); } if (mode == "late") plugin_init(host_api, host::kOurs); + // the RR query: WrongGPU's core answers it itself (it never reaches the interface); the stand-in RR plugin counts the + // ones it answered + const int fo_before = fo->calls; + const long rr_before = os->rr_calls; + const WgResultCode rr = slIsFeatureSupported(kRR, nullptr); + (void)rr; + const bool rr_by_other = os->rr_calls == rr_before + 1; + const bool rr_ours = fo->calls == fo_before && os->rr_calls == rr_before; std::vector L = read_lines(log_path); printf("log lines %zu, torn %zu\n", L.size(), torn_lines(L)); CHECK(torn_lines(L) == 0); // 0.6.1: one append call per line, also with several copies const double load_cost = cost_of(L, "hook: coexistence check at load: "); CHECK(load_cost >= 0.0 && load_cost < 5.0); printf("coexistence check at load: %.3f ms\n", load_cost); - // the check's result lines (the stay-on line is a second line of the same check); hostsplit: the check runs again - CHECK(count(L, "hook: coexistence check at load: ") - count(L, "hook: coexistence check at load: inconclusive") == - (mode == "hostsplit" ? 2u : 1u)); - const long rr_before = os->rr_calls; - const WgResultCode rr = slIsFeatureSupported(kRR, nullptr); - const bool rr_by_other = os->rr_calls == rr_before + 1; - const std::string self_slot = "the import slot "; + // the check's result line (the stay-on line is a second line of the same check); the load check runs once + CHECK(count(L, "hook: coexistence check at load: ") - count(L, "hook: coexistence check at load: inconclusive") == 1u); + const std::string patched = std::string("hook: patched IAT slot ") + kWgRoleNames[kIsSupported] + " in "; + const std::string clean_recheck = "hook: coexistence re-check at the game's first call: no other Ray Reconstruction " + "plugin found ("; if (mode == "clean" || mode == "owncopy") { CHECK(count(L, "hook: coexistence check at load: no other Ray Reconstruction plugin found (") == 1); - CHECK(count(L, "hook: coexistence re-check at the game's first call: no other Ray Reconstruction plugin found (") == 1); + CHECK(count(L, clean_recheck) == 1); CHECK(count(L, "another Ray Reconstruction plugin is active") == 0); + CHECK(count(L, fstem) == 0); CHECK(count(L, "hook: coexistence check at load: inconclusive") == 0); - CHECK(count(L, std::string("hook: patched IAT slot ") + kWgRoleNames[kIsSupported] + " in ") == 1); // only one copy patched - CHECK(!rr_by_other); + CHECK(count(L, patched) == 1); // only one copy patched + CHECK(rr_ours); if (mode == "owncopy") { CHECK(count_starting(L, "a second copy of WrongGPU RR is loaded (") == copies.size()); // one line per other copy CHECK(count(L, std::string(kWgHookFile) + " is active); this copy (") == copies.size()); @@ -406,27 +503,46 @@ int main(int argc, char** argv) { CHECK(host::ngx_regs == 1 && host::ngx_owner == host::kOurs); CHECK(GetModuleHandleW(L"wronggpu_runtime.dll") != nullptr); // active: the core loaded the RR runtime #endif - } else if (mode == "hostsplit") { - // the load check took the host's own patches for another plugin (it ran before the host's table was known: the same - // line as for any plugin), then OptiPluginInit showed that the module holds the host's API table: the load check - // ran again with it as the host, nothing is switched off - CHECK(count_starting(L, stem + self_slot) == 1); - CHECK(count(L, "hook: coexistence check at load: another Ray Reconstruction plugin found (") == 1); - CHECK(count(L, "hook: coexistence check at load: no other Ray Reconstruction plugin found (") == 1); - CHECK(count_starting(L, "hook: the module the load check took for another Ray Reconstruction plugin (wgtest_other_rr.dll) " - "holds the host's API table: it is the host") == 1); - const std::vector L2 = read_lines(log_path); // after the game's first call (made above) - CHECK(count(L2, "hook: coexistence re-check at the game's first call: no other Ray Reconstruction plugin found (") == 1); - CHECK(count(L, std::string("hook: patched IAT slot ") + kWgRoleNames[kIsSupported] + " in ") == 1); - CHECK(count(L2, "took the RR calls after WrongGPU") == 0); - CHECK(!rr_by_other); // RR is WrongGPU's - CHECK_EQ(slIsFeatureSupported(kOther, nullptr), kIfaceAnswer); // the other calls reach the interface + } else if (!fmod.empty()) { + // a named module on the path at load: one line names it and the place + CHECK(count(L, "hook: coexistence check at load: another module on the RR path (inconclusive) (") == 1); + CHECK(count_starting(L, fstem) == 1); + CHECK(count(L, "another Ray Reconstruction plugin is active") == 0); // nothing claims an RR plugin + if (yield) { + // rr_other_plugin=yield: WrongGPU RR stays off, nothing patched, the core and the runtime are not loaded + CHECK(count_line(L, fstem + fmod + " (" + fdetail, tail_yield_off) == 1); + CHECK(count(L, "hook: patched IAT slot") == 0); + CHECK(count(L, "hook: coexistence re-check") == 0); + CHECK(!rr_ours && fo->last_role && strcmp(fo->last_role, "is-supported") == 0 && fo->feature == kRR); + CHECK_EQ(slIsFeatureSupported(kOther, nullptr), kIfaceAnswer); #if !WG_BINDING_PROBE - CHECK(count(L, "NGX: RR provider registered with the host") == 1); - CHECK(host::ngx_owner == host::kOurs); + CHECK(count(L, "NGX: RR provider not registered: WrongGPU RR stays off in this process") == 1); + CHECK(host::ngx_owner == nullptr); + CHECK(GetModuleHandleW(L"wronggpu_runtime.dll") == nullptr); +#endif + } else { + // off (the default) and take: WrongGPU RR stays active and answers RR itself + CHECK(count_line(L, fstem + fmod + " (" + fdetail, take ? tail_take : tail_active) == 1); + CHECK(count(L, "stays off") == 0); + CHECK(count(L, patched) == 1); + CHECK(rr_ours); + CHECK(count(L, clean_recheck) == 1); // the export hooks were named at load: nothing new at the first call + CHECK(count(L, "took the RR calls after WrongGPU") == 0); + if (take && mode == "first") { // the other calls go on through the other module (it sees them, no RR work) + const long before = os->calls[kIsSupported]; + CHECK_EQ(slIsFeatureSupported(kOther, nullptr), kIfaceAnswer); + CHECK(os->calls[kIsSupported] == before + 1); + } else { + CHECK_EQ(slIsFeatureSupported(kOther, nullptr), kIfaceAnswer); + } +#if !WG_BINDING_PROBE + CHECK(count(L, "NGX: RR provider registered with the host") == 1); + CHECK(host::ngx_owner == host::kOurs); + CHECK(GetModuleHandleW(L"wronggpu_runtime.dll") != nullptr); // active: the core loaded the RR runtime #endif - } else if (stays_on) { - // not a positive finding: logged once as inconclusive, WrongGPU RR stays active (it patched, RR is its own) + } + } else if (unclear_mode) { + // nothing could be told: logged once as inconclusive, WrongGPU RR stays active (it patched, RR is its own) const std::string unclear = mode == "anon" ? self_slot + evaluate_name + " of " + exe_leaf + " leads to code outside every module" : mode == "exe" ? self_slot + evaluate_name + " of " + exe_leaf + " leads into the exe's own code" @@ -436,93 +552,51 @@ int main(int argc, char** argv) { CHECK(count_starting(L, "hook: coexistence check at load: inconclusive for 1 address(es) (first: " + unclear + "); no other plugin was positively found, WrongGPU RR stays active") == 1); CHECK(count(L, "another Ray Reconstruction plugin is active") == 0); + CHECK(count(L, fstem) == 0); CHECK(count(L, "stays off") == 0); - CHECK(count(L, std::string("hook: patched IAT slot ") + kWgRoleNames[kIsSupported] + " in ") == 1); - CHECK(count(read_lines(log_path), "hook: coexistence re-check at the game's first call: no other Ray Reconstruction plugin found (") == 1); - CHECK(!rr_by_other); + CHECK(count(L, patched) == 1); + CHECK(count(L, clean_recheck) == 1); + CHECK(rr_ours); CHECK_EQ(slIsFeatureSupported(kOther, nullptr), kIfaceAnswer); if (mode == "guardpage") { MEMORY_BASIC_INFORMATION m; - CHECK(VirtualQuery(odd_page, &m, sizeof m) && (m.Protect & PAGE_GUARD)); // never touched + CHECK(VirtualQuery(odd_page, &m, sizeof m) && (m.Protect & PAGE_GUARD)); // the check did not touch it } #if !WG_BINDING_PROBE CHECK(count(L, "NGX: RR provider registered with the host") == 1); CHECK(host::ngx_owner == host::kOurs); #endif - } else if (mode == "first" || mode == "inline" || mode == "relay" || mode == "execonly") { - const std::string detail = - mode == "first" ? self_slot // the first redirected slot in import order; the module is checked below - : mode == "inline" ? "the export " + evaluate_name + " of " + iface_leaf + " leads to wgtest_other_rr.dll (through 1 hook jump)" - : mode == "relay" ? "the export " + evaluate_name + " of " + iface_leaf + " leads to wgtest_other_rr.dll (through 2 hook jumps)" - : self_slot + evaluate_name + " of " + exe_leaf + " leads to wgtest_other_rr.dll (through 1 hook jump)"; - CHECK(count(L, "hook: coexistence check at load: another Ray Reconstruction plugin found (") == 1); - if (take && (mode == "first" || mode == "inline")) { - CHECK(count_starting(L, "another Ray Reconstruction plugin is active; rr_other_plugin=take: WrongGPU RR goes in " - "front of it (" + detail) == 1); - CHECK(count(L, stem) == 0); - CHECK(count(L, std::string("hook: patched IAT slot ") + kWgRoleNames[kIsSupported] + " in ") == 1); - CHECK(!rr_by_other); // RR is WrongGPU's - if (mode == "first") { // the other calls go on through the other plugin (it sees them, no RR work) - const long before = os->calls[kIsSupported]; - CHECK_EQ(slIsFeatureSupported(kOther, nullptr), kIfaceAnswer); - CHECK(os->calls[kIsSupported] == before + 1); - } - } else { - CHECK(count_starting(L, stem + detail) == 1); - if (mode == "first") CHECK(count(L, " leads to wgtest_other_rr.dll; nothing patched; ") == 1); - CHECK(count(L, "; nothing patched; rr_other_plugin=take in wronggpu-rr.ini uses WrongGPU's instead)") == 1); - CHECK(count(L, "hook: patched IAT slot") == 0); - CHECK(count(L, "hook: coexistence re-check") == 0); - if (mode == "first" || mode == "inline" || mode == "relay") { - CHECK(mode == "first" ? rr_by_other : !rr_by_other); // inline: the game's import slot reaches the interface - CHECK_EQ(slIsFeatureSupported(kOther, nullptr), kIfaceAnswer); - } else { - CHECK(fo->last_role && strcmp(fo->last_role, "is-supported") == 0 && fo->feature == kRR); // untouched path - (void)rr; - } -#if !WG_BINDING_PROBE - CHECK(count(L, "NGX: RR provider not registered: WrongGPU RR stays off in this process") == 1); - CHECK(host::ngx_owner == nullptr); - // off at load: the core is not built, so the RR runtime (staged next to the exe) is never loaded - CHECK(GetModuleHandleW(L"wronggpu_runtime.dll") == nullptr); -#endif - } } else if (late) { + // a module that took the calls after us: named once, WrongGPU RR stays active behind it (take: the same, never off) CHECK(count(L, "hook: coexistence check at load: no other Ray Reconstruction plugin found (") == 1); - CHECK(count(L, std::string("hook: patched IAT slot ") + kWgRoleNames[kIsSupported] + " in ") == 1); + CHECK(count(L, patched) == 1); const std::string why = mode == "late" ? "the game's first call" : "OptiPluginInit"; - CHECK(count(L, "hook: coexistence re-check at " + why + ": another Ray Reconstruction plugin took the RR calls " - "after WrongGPU (") == 1); + CHECK(count(L, "hook: coexistence re-check at " + why + ": another module took the RR calls after WrongGPU (") == 1); CHECK(count(L, "hook: coexistence re-check") == 1); // one decision, one line, even with 16 threads at once - const std::string detail = "the import slot "; - if (take) { - CHECK(count_starting(L, "a plugin loaded after WrongGPU replaced its hooks; rr_other_plugin=take cannot be " - "applied: WrongGPU RR stays off and passes every call on unchanged (" + detail) == 1); - CHECK(count(L, stem) == 0); - } else { - CHECK(count_starting(L, stem + detail) == 1); - CHECK(count(L, " (WrongGPU's hook) leads to wgtest_other_rr.dll; it loaded after WrongGPU: WrongGPU passes every " - "call on unchanged; to use WrongGPU RR, move it aside)") == 1); - } - CHECK(rr_by_other); // RR is the other plugin's - // a call the other plugin passes on reaches our handler, which passes it on unchanged to the interface + CHECK(count_line(L, fstem + "wgtest_other_rr.dll (the import slot ", + " (WrongGPU's hook) leads to wgtest_other_rr.dll)" + tail_active) == 1); + CHECK(count_starting(L, fstem) == 1); + CHECK(count(L, "stays off") == 0); + CHECK(rr_by_other); // the stand-in is in front and answers RR itself + // a call the stand-in passes on reaches the interface unchanged (through our active handler in "late") const int before = fo->calls; CHECK_EQ(slEvaluateFeature(kOther, nullptr, nullptr, 0, nullptr), kIfaceAnswer); CHECK(fo->calls == before + 1 && fo->last_role && strcmp(fo->last_role, "evaluate") == 0); CHECK_EQ(at_once(8, [] { return slIsFeatureSupported(kOther, nullptr); }, kIfaceAnswer), 8); // consistent after CHECK(count(read_lines(log_path), "hook: coexistence re-check") == 1); #if !WG_BINDING_PROBE - CHECK(count(read_lines(log_path), "NGX: RR provider not registered: WrongGPU RR stays off in this process") == 1); - CHECK(host::ngx_owner == nullptr); + CHECK(count(read_lines(log_path), "NGX: RR provider registered with the host") == 1); + CHECK(host::ngx_owner == host::kOurs); #endif } else if (mode == "provider") { #if !WG_BINDING_PROBE + // the host's API says its RR provider slot is taken: the NGX route stays off (positive by contract) CHECK(count_starting(L, stem + "NGX route only: the host refused WrongGPU's RR provider, another provider holds it; " "the game-interface route is decided on its own)") == 1); CHECK(host::ngx_owner == host::kTheirs && host::ngx_regs == 2); - CHECK(count(L, std::string("hook: patched IAT slot ") + kWgRoleNames[kIsSupported] + " in ") == 1); // the route stays ours + CHECK(count(L, patched) == 1); // the game-interface route stays ours CHECK(count(L, stem) == 1); - CHECK(!rr_by_other); + CHECK(rr_ours); #endif } else { CHECK(!"unknown mode"); @@ -532,6 +606,9 @@ int main(int argc, char** argv) { (void)or_patch_iat; (void)or_set_slot; (void)or_ngx; + (void)or_host_table; + (void)or_innocent; + (void)load_copy; load_asi(widen(kWgHookFile), &init, &plugin_init); if (!init || !plugin_init) TEST_SUMMARY(label.c_str()); init(); // the interface is not loaded and not linked: waits for the host @@ -543,16 +620,18 @@ int main(int argc, char** argv) { FoState* fo = reinterpret_cast(GetProcAddress(iface, "wgtest_fo_state"))(); if (mode == "route-other") CHECK(or_routes(&api, host::kTheirs) == 4); if (mode == "route-inline") CHECK(or_patch_export(iface, evaluate_name.c_str(), 0) == 1); + if (mode == "route-refused") host::refuse_routes = true; if (host::callback) host::callback(iface, 2, 14, 1, host::callback_user); std::vector L = read_lines(log_path); printf("log lines %zu, torn %zu\n", L.size(), torn_lines(L)); CHECK(torn_lines(L) == 0); // 0.6.1: one append call per line, also with two copies CHECK(count(L, "waiting for the host's game-interface routes") == 1); + CHECK(count(L, "another Ray Reconstruction plugin is active") == 0); auto ours = reinterpret_cast(host::handler_of_plugin[0][kWgRoleNames[kIsSupported]]); if (mode == "route") { CHECK(count(L, "hook: coexistence check before the host routes: no other Ray Reconstruction plugin found (") == 1); CHECK(count(L, "hook: coexistence check of the host routes: no other Ray Reconstruction plugin found (") == 1); - CHECK(count(L, "another Ray Reconstruction plugin is active") == 0); + CHECK(count(L, fstem) == 0); CHECK(ours != nullptr); if (ours) { CHECK_EQ(ours(kOther, nullptr), kIfaceAnswer); // continues to the interface @@ -561,34 +640,43 @@ int main(int argc, char** argv) { CHECK(os->rr_calls == before); } } else if (mode == "route-other") { - const std::string detail = "the host's next function of " + std::string(kWgRoleNames[kIsSupported]) + - " leads to wgtest_other_rr.dll"; + const std::string start = fstem + "wgtest_other_rr.dll (the host's next function of " + + std::string(kWgRoleNames[kIsSupported]) + " leads to wgtest_other_rr.dll)"; + CHECK(count(L, "hook: coexistence check of the host routes: another module on the RR path (inconclusive) (") == 1); CHECK(ours != nullptr); - if (take) { - CHECK(count_starting(L, "another Ray Reconstruction plugin is active; rr_other_plugin=take: WrongGPU RR goes in " - "front of it (" + detail) == 1); - CHECK(count(L, stem) == 0); + if (yield) { + CHECK(count_line(L, start, tail_yield_pass) == 1); + if (ours) { + const long before = os->rr_calls; + CHECK_EQ(ours(kRR, nullptr), (WgResultCode)0); // passed on: the stand-in answers RR + CHECK(os->rr_calls == before + 1); + CHECK_EQ(ours(kOther, nullptr), kIfaceAnswer); + } + } else { + CHECK(count_line(L, start, take ? tail_take : tail_active) == 1); + CHECK(count(L, "stays off") == 0); if (ours) { const long before = os->rr_calls, calls = os->calls[kIsSupported]; ours(kRR, nullptr); CHECK(os->rr_calls == before); // RR is WrongGPU's - CHECK_EQ(ours(kOther, nullptr), kIfaceAnswer); // the other calls continue through the other plugin + CHECK_EQ(ours(kOther, nullptr), kIfaceAnswer); // the other calls continue through the stand-in CHECK(os->calls[kIsSupported] == calls + 1); } - } else { - CHECK(count_starting(L, stem + detail + "; WrongGPU's handlers pass every call on unchanged; rr_other_plugin=take " - "in wronggpu-rr.ini uses WrongGPU's instead)") == 1); - if (ours) { - const long before = os->rr_calls; - CHECK_EQ(ours(kRR, nullptr), (WgResultCode)0); // passed on: the other plugin answers RR - CHECK(os->rr_calls == before + 1); - CHECK_EQ(ours(kOther, nullptr), kIfaceAnswer); - } } } else if (mode == "route-inline") { - CHECK(count_starting(L, stem + "the export " + evaluate_name + " of " + iface_leaf + - " leads to wgtest_other_rr.dll (through 1 hook jump); nothing patched; ") == 1); - CHECK(host::route_regs[0] == 0); // no routes registered + // named before the routes: RR stays active, our routes are registered in front + CHECK(count_line(L, fstem + "wgtest_other_rr.dll (the export " + evaluate_name + " of " + iface_leaf + + " leads to wgtest_other_rr.dll (through 1 hook jump))", + tail_active) == 1); + CHECK(host::route_regs[0] == 1 && ours != nullptr); + CHECK(count(L, "stays off") == 0); + if (ours) CHECK_EQ(ours(kOther, nullptr), kIfaceAnswer); + } else if (mode == "route-refused") { + // the host's API refused our registration (positive by contract): the game-interface route stays off + CHECK(count_starting(L, "hook: the host refused our game-interface routes; nothing was patched: WrongGPU RR stays " + "off on the game-interface route") == 1); + CHECK(host::route_regs[0] == 1 && ours == nullptr); + CHECK(count(L, "hook: coexistence check of the host routes") == 0); } else { CHECK(!"unknown mode"); } diff --git a/clean/rr_f/proxy/tools/build.py b/clean/rr_f/proxy/tools/build.py index 5806c37e..91dbca50 100644 --- a/clean/rr_f/proxy/tools/build.py +++ b/clean/rr_f/proxy/tools/build.py @@ -399,14 +399,20 @@ def test_hook(built, binding, out, logs, probe, n=None, gen=None): return n, built -# RR guard: the coexistence guard's modes (tests/test_rr_guard_dll.cpp) against our own stand-in "other Ray -# Reconstruction plugin" (tests/fake_other_rr.cpp); "route*" modes use the build without an import of the interface +# RR guard: the coexistence guard's modes (tests/test_rr_guard_dll.cpp) against our own stand-in "other module" +# (tests/fake_other_rr.cpp, also staged under other file names for the innocent layouts); "route*" modes use the build +# without an import of the interface GUARD_MODES_RELEASE = (["clean"], ["first"], ["first", "--take"], ["inline"], ["inline", "--take"], ["relay"], ["execonly"], - ["anon"], ["noaccess"], ["guardpage"], ["exe"], ["hops"], ["hostsplit"], ["late"], ["late", "--take"], - ["late-replace"], ["provider"], ["owncopy"], ["route"], ["route-other"], ["route-other", "--take"], - ["route-inline"]) -GUARD_MODES_PROBE = (["clean"], ["first"], ["inline"], ["execonly"], ["noaccess"], ["hops"], ["hostsplit"], ["late"], - ["owncopy"], ["route-other"]) + ["wrapper"], ["wrapper", "--yield"], ["overlay"], ["forward"], ["helper"], ["hostsplit"], + ["heaptable"], ["helpertable"], ["anon"], ["noaccess"], ["guardpage"], ["exe"], ["hops"], ["late"], + ["late", "--take"], ["late-replace"], ["provider"], ["owncopy"], ["route"], ["route-other"], + ["route-other", "--take"], ["route-other", "--yield"], ["route-inline"], ["route-refused"]) +GUARD_MODES_PROBE = (["clean"], ["first"], ["inline"], ["execonly"], ["wrapper"], ["wrapper", "--yield"], ["overlay"], + ["forward"], ["heaptable"], ["noaccess"], ["hops"], ["late"], ["owncopy"], ["route-other"], + ["route-refused"]) +# the stand-in under other file names (each its own image and state): the loader, the innocent modules, the table image +GUARD_STUB_COPIES = ("wgtest_loader.dll", "wgtest_gamewrap.dll", "wgtest_hosthelper.dll", "wgtest_hosttable.dll", + "wgtest_overlay.dll", "wgtest_impl.dll") def test_guard(built, out, logs, probe, n, gen, iface_dll, implib, iface_name): @@ -434,7 +440,8 @@ def test_guard(built, out, logs, probe, n, gen, iface_dll, implib, iface_name): shutil.copy(built, os.path.join(stage, n["proxy_file"])) for k in ("", "2", "3", "4"): # the owncopy mode's other copies of WrongGPU RR (separate files, separate images) shutil.copy(built, os.path.join(stage, f"WrongGPU-RR-copy{k}.asi")) - shutil.copy(stub, os.path.join(stage, "wgtest_loader.dll")) # the hostsplit mode's separate ASI loader (a second image) + for copy in GUARD_STUB_COPIES: + shutil.copy(stub, os.path.join(stage, copy)) if not probe: shutil.copy(os.path.join(out, "wronggpu_runtime.dll"), stage) for m in (GUARD_MODES_PROBE if probe else GUARD_MODES_RELEASE): From 334c93c30bccebed2e4cade69fca32d7c638323f Mon Sep 17 00:00:00 2001 From: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> Date: Fri, 13 Nov 2026 19:22:29 -0500 Subject: [PATCH 4/4] RR plugin guard: bounded PE walk with a fail-open budget; a refused NGX registration claims no other plugin Third review. The load scan reads another module's headers only within the image's real extent (min of SizeOfImage and the mapping, measured first), reads names byte by byte inside it, reads import descriptors only within the directory's declared size, holds a module reference around module APIs, and stops after 200000 entries or 100 ms (inconclusive, RR stays active). The NGX refusal line says only that the host refused (its API gives one false for every refusal). take / yield wording in HOOK-MODE.md. Fixes #22 Signed-off-by: phantoslayer21 <156617979+phantoslayer21@users.noreply.github.com> --- clean/rr_f/proxy/HOOK-MODE.md | 64 +++++--- clean/rr_f/proxy/src/hook_dll.cpp | 70 ++++----- clean/rr_f/proxy/src/rr_guard.cpp | 129 ++++++++++++++-- clean/rr_f/proxy/src/rr_guard.h | 93 ++++++++++-- clean/rr_f/proxy/tests/test_rr_guard.cpp | 149 ++++++++++++++++++- clean/rr_f/proxy/tests/test_rr_guard_dll.cpp | 28 ++-- clean/rr_f/proxy/tools/build.py | 5 +- 7 files changed, 443 insertions(+), 95 deletions(-) diff --git a/clean/rr_f/proxy/HOOK-MODE.md b/clean/rr_f/proxy/HOOK-MODE.md index d1595a4b..39181767 100644 --- a/clean/rr_f/proxy/HOOK-MODE.md +++ b/clean/rr_f/proxy/HOOK-MODE.md @@ -124,7 +124,8 @@ and probe builds behave the same. Model M is never touched. **When WrongGPU RR switches itself off.** Only on evidence that is positive by contract: - **a second copy of WrongGPU RR** (below, "Counting as WrongGPU"); -- **the host's plugin API** saying its RR provider slot is taken (the NGX route), or refusing our game-interface routes. +- **the host's plugin API** refusing a registration: our NGX RR provider (the NGX route stays off) or our game-interface + routes (that route stays off). The API does not say why it refused, so the log says only that it refused. Nothing else switches RR off on its own. In particular a **named module on the call path is inconclusive**: it may be another RR plugin, but it may as well be a game's own wrapper DLL, an overlay, a security shim, a host helper in a @@ -150,8 +151,10 @@ out of anonymous memory, at most 4 of them per address; a fifth is "too many hop 4. **Host routes** (plugin interface 3): `S2` on the module the host hooked (the host's trampolines, code outside every module, are accepted there), then each route's next function (the host's `next`) after registering. Our routes are in front and cannot be taken back. A refused registration keeps the game-interface route off. -5. **The NGX route** (plugin interface 4): the host keeps one RR provider; a refused registration means another - provider holds it: **the NGX route stays off** (the game-interface route goes by its own signals). +5. **The NGX route** (plugin interface 4): the host keeps one RR provider. A refused registration keeps **the NGX + route off** (the game-interface route goes by its own signals). The host's API returns the same false for an + occupied slot and for a structure it does not accept, so the line says that the host refused, not that another + plugin is active. 6. **Later modules** (`S4`): a module that hooks after ours is looked for at `OptiPluginInit` and at the game's first call into any of our handlers (decided once: concurrent first calls wait for the one decision): a slot we patched that no longer holds our handler, or (while active) an RR export that now jumps somewhere else than at load. @@ -168,10 +171,16 @@ the default setting a wrong guess can no longer switch RR off. - `take`: as `off`, and with a module named at load (or below our host routes) WrongGPU RR goes in front of it and continues the other calls of the same functions through what the slot held before (that module), so it sees the game's other calls but never an RR create: one RR evaluate per frame. A module that hooks after ours is only named - (we never patch again; no patch fights). `take` never switches WrongGPU RR off. -- `yield`: WrongGPU RR stays off whenever any named module is on the path: found at load, nothing is patched (the core - and the runtime are not loaded, no NGX provider); found later or below our host routes, our handlers pass every call - on unchanged and the NGX provider refuses creates. + (we never patch again; no patch fights). `take` never switches WrongGPU RR off **because of a named module**; a copy + of WrongGPU RR (the marker or the export) still stops it, and a refusal by the host still keeps the refused route + off. +- `yield`: WrongGPU RR stays off whenever any named module outside the recognised images (this module, the game + interface, the exe, the two images taken as the host, another WrongGPU module) is on the path: found at load, nothing + is patched (the core and the runtime are not loaded, no NGX provider); found later or below our host routes, our + handlers pass every call on unchanged and the NGX provider refuses creates. `yield` cannot establish who owns that + module: a game's own wrapper DLL, an overlay, a host helper in a third image or a forwarded export's implementation + DLL switch it off as well (the load scan runs before the host's table is known), and a module wrongly taken as the + host is not named. **Load orders** (with `yield`, or a second copy). Ours second: found at load, nothing patched. Ours first: found at `OptiPluginInit` or the game's first call; pass-through from then on (the runtime is loaded but no RR instance exists). @@ -184,10 +193,25 @@ pages (execute-only pages count as readable: code is read from them), then a str failed read is **unknown**. The check and the copy are not one atomic step: if another thread unmaps or reprotects a page in between, an access fault is caught (unknown), but a page made a guard page in that moment is touched and loses its one-shot guard state. The cached region of the header walk is not queried again (only the exception guard covers -it). Another module's PE headers are used only after `e_lfanew`, every data directory and every RVA the walk follows -are checked against `SizeOfImage` (integers first, no address formed from an unchecked value); a header or table that -fails is treated as nothing found there. These are **inconclusive** (counted, one diagnostic line names the first, -WrongGPU RR stays active): +it). + +**Another module's PE headers** are used only within the image's **extent**: the smaller of its `SizeOfImage` and what +is really mapped at the module (`VirtualQuery` over the committed regions of the module's allocation, measured before +any header is read; a forged larger `SizeOfImage` does not widen it). The DOS header is read only inside the mapping; +`e_lfanew` is checked as an integer against the mapping before the NT headers are read; every data directory, every +RVA the walk follows and every byte of an import name are checked against the extent before an address is formed (an +import name without its NUL inside the image is skipped, never read past). Import descriptors are read only within the +import directory's declared size. `GetProcAddress` and `GetModuleFileNameW` run while the scan holds a reference to +the module (`GetModuleHandleExW`, released afterwards); a module unloaded in between counts as nothing found. The extent +bounds where the walk reads; it does not make the memory stable (another thread can still unmap or reprotect a page: +see above). A header or table that fails is treated as nothing found there. + +**The load scan's budget.** The scan at load counts every module, import descriptor and name-table entry it visits. +After 200000 entries or 100 ms (the time is looked at every 64 entries) it stops: nothing it found is acted on, one +line says so, and **WrongGPU RR stays active in every mode** (`yield` included; the process marker still stops a second +copy). Besides, at most 1024 modules, 4096 descriptors per import directory and 4096 entries per name table are read. + +These are **inconclusive** (counted, one diagnostic line names the first, WrongGPU RR stays active): - memory that cannot be read (an import slot, an export, a jump cell, a PAGE_NOACCESS or guard page, a null pointer); - a jump chain longer than 4 hops; - code outside every module that does not jump on (a game's copy protection or a hooking library's trampoline may sit @@ -213,7 +237,7 @@ Last run page can match these **beginnings**; keep them exactly: The launcher can say "another module hooks the game's RR calls: ``" from it. One such line per check that names a module (the first module found; at the late checks once per run). - `a second copy of WrongGPU RR is loaded ( is active); this copy () stays off` -- `another Ray Reconstruction plugin is active; WrongGPU RR stays off (NGX route only: the host refused WrongGPU's RR provider, another provider holds it; the game-interface route is decided on its own)` +- `the host refused WrongGPU's NGX RR provider registration; the NGX route stays off (the game-interface route is decided on its own)` `` names the place, e.g. `the import slot of Game.exe leads to Other.dll`, `the export of leads to Other.dll (through 2 hook jumps)`, `the import slot of Game.exe (WrongGPU's hook) @@ -224,7 +248,9 @@ copy of WrongGPU RR found`), `hook: coexistence re-check at : ...`, `hook: routes; nothing was patched: WrongGPU RR stays off on the game-interface route`, `NGX: RR provider not registered: WrongGPU RR stays off in this process (see the line above)`, and the stay-on line `hook: coexistence check : inconclusive for address(es) (first: could not be read | leads to code outside every module | leads into the -exe's own code | leads through more than 4 hook jumps); no other plugin was positively found, WrongGPU RR stays active`. +exe's own code | leads through more than 4 hook jumps); no other plugin was positively found, WrongGPU RR stays active`, +and when the load scan runs out of its budget `hook: coexistence check at load: stopped after entries ( ms), over +its budget of 200000 entries / 100 ms; inconclusive, WrongGPU RR stays active`. **The log with two copies.** Every line is one `WriteFile` on a `FILE_APPEND_DATA` handle (`src/log_append.h`), which the system appends as one piece, so two copies' lines do not run into each other. The size check and the rotation run @@ -234,7 +260,10 @@ append, but it may land in the file the other copy is just moving aside (`wrongg best effort after a timeout, not a guarantee. **Tests** (CPU only, run by build.py and CI): `tests/test_rr_guard.cpp` (safe reads on PAGE_NOACCESS, reserved, guard -and execute-only pages and a page made unreadable after caching; PE header and directory bounds against SizeOfImage; +and execute-only pages and a page made unreadable after caching; PE header and directory bounds against SizeOfImage +and the mapping, a SizeOfImage larger than the mapping; the import walk: an import name at the image's last byte with +no NUL inside the image (readable bytes after it: skipped, not read), an import directory smaller than its descriptors +(only the declared ones read), the budget by entries and by time; every jump form; synthetic modules; exactly 4 hops followed and a fifth one too many; the whole `decide` table: with no second RR provider (a game-owned wrapper DLL, a host helper in a third image, an overlay-style wrapper, a forwarded export, the heap-table and helper-table host layouts) RR stays active at every stage unless `yield`, `take` never @@ -245,9 +274,10 @@ hostsplit, heaptable, helpertable, late, late-replace, route-other, route-inline one line (release: the RR runtime is loaded, the NGX provider is ours); `wrapper --yield` stays off with nothing patched and the runtime not loaded; `route-other --yield` passes every call on; `--take` goes in front; owncopy (four more copies, from threads, while 16 game threads make the first call; no torn line; no exit summary from an inactive -copy; build.py repeats it 200 times), provider (the NGX route stays off) and route-refused (the game-interface route -stays off) switch off; anon, noaccess, guardpage, exe and hops log the inconclusive line and stay active. Run for every -interface version, release and probe (build.py); the existing hook runs check that no guard line appears. +copy; build.py repeats it 200 times), provider and provider-refused (the host refuses our provider with and without another +provider installed: the NGX route stays off, the line claims no other plugin) and route-refused (the game-interface +route stays off) switch off; anon, noaccess, guardpage, exe and hops log the inconclusive line and stay active. Run for +every interface version, release and probe (build.py); the existing hook runs check that no guard line appears. ## Unload diff --git a/clean/rr_f/proxy/src/hook_dll.cpp b/clean/rr_f/proxy/src/hook_dll.cpp index f3ecabf2..acc8de8f 100644 --- a/clean/rr_f/proxy/src/hook_dll.cpp +++ b/clean/rr_f/proxy/src/hook_dll.cpp @@ -1178,42 +1178,26 @@ int role_for_name(const char* name) { return -1; } -// The by-name entries of one import (or delay-load) name table: f(role, import name, slot address) for each that names -// a hooked role. Every RVA (the name table, the address table, each name) is checked against the image's size (PeView) -// before an address is formed from it; an entry outside the image ends the walk (nothing found there). +// The by-name entries of one import (or delay-load) name table that name a hooked role: f(role, import name, slot +// address). The walk (wgrr::guard::thunks) checks every RVA and every byte of a name against the image's extent +// (PeView) before an address is formed from it, and counts each entry against the scan's budget. template -void guard_thunks(const wgrr::guard::PeView& pe, wgrr::guard::Reader& r, uint32_t names_rva, uint32_t iat_rva, F f) { - for (unsigned i = 0; i < 4096; ++i) { - const uint64_t off = (uint64_t)i * sizeof(IMAGE_THUNK_DATA64); - const uint8_t* np = pe.at(names_rva + off, sizeof(IMAGE_THUNK_DATA64)); - const uint8_t* sp = pe.at(iat_rva + off, sizeof(IMAGE_THUNK_DATA64)); - IMAGE_THUNK_DATA64 t; - if (!np || !sp || !r.get(np, &t) || !t.u1.AddressOfData) return; - if (t.u1.Ordinal & IMAGE_ORDINAL_FLAG64) continue; - const uint8_t* by = pe.at(t.u1.AddressOfData, offsetof(IMAGE_IMPORT_BY_NAME, Name) + 1); - char nm[96]; - if (!by || !r.str(by + offsetof(IMAGE_IMPORT_BY_NAME, Name), nm, sizeof nm)) continue; +void guard_thunks(const wgrr::guard::PeView& pe, wgrr::guard::Reader& r, wgrr::guard::Budget& b, uint32_t names_rva, + uint32_t iat_rva, F f) { + wgrr::guard::thunks(pe, r, b, names_rva, iat_rva, [&](const char* nm, void** slot) { const int role = role_for_name(nm); - if (role >= 0) f(role, nm, const_cast(reinterpret_cast(sp))); - } + if (role >= 0) f(role, nm, slot); + }); } -// Every import slot of `module` that names a hooked role from the DLL `leaf`, read through the guard's reader: f(role, -// import name, slot address). +// Every import slot of `module` that names a hooked role from the DLL `leaf` (wgrr::guard::import_slots: descriptors +// within the import directory's declared size): f(role, import name, slot address). template -void guard_import_slots(HMODULE module, const char* leaf, wgrr::guard::Reader& r, F f) { - wgrr::guard::PeView pe; - uint32_t rva = 0, size = 0; - if (!pe.open(module, r) || !pe.dir(IMAGE_DIRECTORY_ENTRY_IMPORT, &rva, &size)) return; - for (unsigned k = 0; k < 4096; ++k) { - const uint8_t* dp = pe.at(rva + (uint64_t)k * sizeof(IMAGE_IMPORT_DESCRIPTOR), sizeof(IMAGE_IMPORT_DESCRIPTOR)); - IMAGE_IMPORT_DESCRIPTOR e; - if (!dp || !r.get(dp, &e) || !e.Name) return; - const uint8_t* np = pe.at(e.Name, 1); - char dll[64]; - if (!np || !r.str(np, dll, sizeof dll) || _stricmp(dll, leaf) != 0) continue; - guard_thunks(pe, r, e.OriginalFirstThunk ? e.OriginalFirstThunk : e.FirstThunk, e.FirstThunk, f); - } +void guard_import_slots(HMODULE module, const char* leaf, wgrr::guard::Reader& r, wgrr::guard::Budget& b, F f) { + wgrr::guard::import_slots(module, leaf, r, b, [&](const char* nm, void** slot) { + const int role = role_for_name(nm); + if (role >= 0) f(role, nm, slot); + }); } // S0: the process-wide marker of the active WrongGPU RR copy. True: this copy is the first (it holds the marker). False: @@ -1311,6 +1295,8 @@ ExportSeen g_export_seen[32]; // unchanged_only: count an export that leads where it led at load as read, without classifying it again (late check). void guard_scan_exports(HMODULE module, const wgrr::guard::Env& env, bool anon_ok, wgrr::guard::Verdict* v, bool record = false, bool unchanged_only = false) { + const wgrr::guard::ModuleRef ref(module); // the interface stays loaded while its exports are looked up + if (!ref.held()) return; const std::string leaf = leaf_text(module); for (int role : kWgDecisiveRoles) { if (!role_in_route(role) || !kWgRoleNames[role][0]) continue; @@ -1338,6 +1324,7 @@ bool guard_at_load(const IMAGE_DELAYLOAD_DESCRIPTOR* delay) { const g::Env env = guard_env(g_interposer); g::Reader r; g::Verdict v; + g::Budget budget(g::kScanMaxEntries, g::kScanMaxMs); // the whole load scan: over it, inconclusive (RR stays active) std::wstring leaf_w; module_leaf(g_interposer, &leaf_w); const std::string leaf = narrow(leaf_w); @@ -1347,9 +1334,11 @@ bool guard_at_load(const IMAGE_DELAYLOAD_DESCRIPTOR* delay) { DWORD need = 0; if (K32EnumProcessModules(GetCurrentProcess(), mods, sizeof mods, &need)) { const unsigned count = (unsigned)(need / sizeof(HMODULE)) < 1024 ? (unsigned)(need / sizeof(HMODULE)) : 1024; - for (unsigned i = 0; i < count; ++i) { + for (unsigned i = 0; i < count && budget.step(); ++i) { if (mods[i] == g_self || mods[i] == g_interposer) continue; - guard_import_slots(mods[i], leaf.c_str(), r, [&](int role, const char* nm, void** slot) { + const g::ModuleRef ref(mods[i]); // the module stays loaded while its tables are read (unloaded: skipped) + if (!ref.held()) continue; + guard_import_slots(mods[i], leaf.c_str(), r, budget, [&](int role, const char* nm, void** slot) { void* val = nullptr; const g::Where w = r.get(slot, &val) ? g::classify(val, env, false) : g::Where(); v.add(w, std::string("the import slot ") + nm + " of " + leaf_text(mods[i]), false, false); @@ -1358,8 +1347,10 @@ bool guard_at_load(const IMAGE_DELAYLOAD_DESCRIPTOR* delay) { } } g::PeView pe; - if (delay && pe.open(exe, r)) { // the exe's delay-load slots: unbound ones hold the delay helper's thunk in the exe - guard_thunks(pe, r, delay->ImportNameTableRVA, delay->ImportAddressTableRVA, [&](int role, const char* nm, void** slot) { + // the exe's delay-load slots: unbound ones hold the delay helper's thunk in the exe + if (delay && !budget.over() && pe.open(exe, r)) { + guard_thunks(pe, r, budget, delay->ImportNameTableRVA, delay->ImportAddressTableRVA, + [&](int role, const char* nm, void** slot) { void* val = nullptr; const g::Where w = r.get(slot, &val) ? g::classify(val, env, false) : g::Where(); v.add(w, std::string("the delay-load slot ") + nm + " of " + leaf_text(exe), false, true); @@ -1367,6 +1358,10 @@ bool guard_at_load(const IMAGE_DELAYLOAD_DESCRIPTOR* delay) { prev[role] = val; }); } + if (budget.over()) { // fails open: nothing is decided from a partial scan (the process marker still found any copy) + log_line(g::line_over_budget(budget.entries(), ms_since(t0))); + return true; + } guard_scan_exports(g_interposer, env, false, &v, true); const double ms = ms_since(t0); log_line("hook: coexistence check at load: " + std::string(guard_result(v)) + " (" + std::to_string(v.reads) + @@ -1960,8 +1955,9 @@ void register_ngx_provider(const WgHostMenuApi* api, WgHostMenuPlugin* plugin) { "): games that call NGX directly get WrongGPU RR" + (host_has ? "; the host restores the game's command-list state after each evaluate" : "; the host has no command-list restore (plugin interface 5)")); - } else { // RR guard: the host keeps one NGX RR provider; another one holds it (NGX route only) - log_line(wgrr::guard::line_ngx_other()); + } else { // RR guard: the host refused the provider (its API gives the same false for an occupied slot and for an + // incomplete structure, so nothing more is claimed); the NGX route stays off + log_line(wgrr::guard::line_ngx_refused()); } } #endif diff --git a/clean/rr_f/proxy/src/rr_guard.cpp b/clean/rr_f/proxy/src/rr_guard.cpp index 99070286..e1514a21 100644 --- a/clean/rr_f/proxy/src/rr_guard.cpp +++ b/clean/rr_f/proxy/src/rr_guard.cpp @@ -3,6 +3,8 @@ #define WIN32_LEAN_AND_MEAN #include +#include +#include #include #include "rr_guard.h" @@ -101,17 +103,37 @@ bool Reader::str(const void* p, char* out, size_t max) { return false; } +size_t mapped_extent(const void* p) { + MEMORY_BASIC_INFORMATION m; + if (!p || !VirtualQuery(p, &m, sizeof m) || m.State != MEM_COMMIT) return 0; + const void* alloc = m.AllocationBase; + const uintptr_t a = reinterpret_cast(p); + uintptr_t end = reinterpret_cast(m.BaseAddress) + m.RegionSize; + for (unsigned i = 0; i < 4096 && end > a; ++i) { + if (!VirtualQuery(reinterpret_cast(end), &m, sizeof m) || m.AllocationBase != alloc || + m.State != MEM_COMMIT) + break; + const uintptr_t next = reinterpret_cast(m.BaseAddress) + m.RegionSize; + if (next <= end) break; + end = next; + } + return end > a ? (size_t)(end - a) : 0; +} + bool PeView::open(const void* module, Reader& r) { base_ = nullptr; size_ = 0; ndirs_ = 0; const uint8_t* base = static_cast(module); + // what is really mapped at the module bounds every header read below (SizeOfImage is only a claim of the header) + const size_t mapped = mapped_extent(base); IMAGE_DOS_HEADER dos; - if (!base || !r.get(base, &dos) || dos.e_magic != IMAGE_DOS_SIGNATURE) return false; - // e_lfanew is a signed 32-bit offset: checked as an integer (positive, past the DOS header, not absurd) before the NT - // headers are read at all; against SizeOfImage once that is known + if (mapped < sizeof dos || !r.get(base, &dos) || dos.e_magic != IMAGE_DOS_SIGNATURE) return false; + // e_lfanew is a signed 32-bit offset: checked as an integer (positive, past the DOS header, not absurd, the NT + // headers inside the mapping) before the NT headers are read at all; against SizeOfImage once that is known const LONG lfanew = dos.e_lfanew; if (lfanew < (LONG)sizeof(IMAGE_DOS_HEADER) || lfanew > 0x100000) return false; + if ((uint64_t)lfanew + sizeof(IMAGE_NT_HEADERS64) > mapped) return false; IMAGE_NT_HEADERS64 nt; if (!r.get(base + lfanew, &nt) || nt.Signature != IMAGE_NT_SIGNATURE || nt.OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) @@ -120,7 +142,7 @@ bool PeView::open(const void* module, Reader& r) { if ((uint64_t)lfanew + sizeof(IMAGE_NT_HEADERS64) > size) return false; // the headers lie inside the image if ((uintptr_t)base + size < (uintptr_t)base) return false; // the image does not wrap the address space base_ = base; - size_ = size; + size_ = (uint64_t)size < (uint64_t)mapped ? size : (uint32_t)mapped; // a larger SizeOfImage does not widen the image ndirs_ = nt.OptionalHeader.NumberOfRvaAndSizes < 16 ? nt.OptionalHeader.NumberOfRvaAndSizes : 16; for (uint32_t i = 0; i < ndirs_; ++i) { dir_rva_[i] = nt.OptionalHeader.DataDirectory[i].VirtualAddress; @@ -142,6 +164,68 @@ const uint8_t* PeView::at(uint64_t rva, uint64_t n) const { return base_ + rva; } +bool PeView::str(uint64_t rva, char* out, size_t max, Reader& r) const { + for (size_t i = 0; i < max; ++i) { + const uint8_t* p = at(rva + i, 1); // every byte inside the extent: a name cut off by the image's end is refused + if (!p || !r.get(p, &out[i])) return false; + if (!out[i]) return true; + } + return false; +} + +Budget::Budget(unsigned max_entries, unsigned max_ms) : max_entries_(max_entries), max_ms_((double)max_ms) { + LARGE_INTEGER f, t; + QueryPerformanceFrequency(&f); + QueryPerformanceCounter(&t); + freq_ = f.QuadPart > 0 ? f.QuadPart : 1; + t0_ = t.QuadPart; +} + +double Budget::elapsed_ms() const { + LARGE_INTEGER t; + QueryPerformanceCounter(&t); + return (double)(t.QuadPart - t0_) * 1000.0 / (double)freq_; +} + +bool Budget::step() { + if (over_) return false; + ++entries_; + if (entries_ > max_entries_ || ((entries_ & 63) == 0 && elapsed_ms() > max_ms_)) over_ = true; + return !over_; +} + +void thunks(const PeView& pe, Reader& r, Budget& b, uint32_t names_rva, uint32_t iat_rva, + const std::function& f) { + for (unsigned i = 0; i < 4096 && b.step(); ++i) { + const uint64_t off = (uint64_t)i * sizeof(IMAGE_THUNK_DATA64); + const uint8_t* np = pe.at(names_rva + off, sizeof(IMAGE_THUNK_DATA64)); + const uint8_t* sp = pe.at(iat_rva + off, sizeof(IMAGE_THUNK_DATA64)); + IMAGE_THUNK_DATA64 t; + if (!np || !sp || !r.get(np, &t) || !t.u1.AddressOfData) return; + if (t.u1.Ordinal & IMAGE_ORDINAL_FLAG64) continue; + char nm[96]; + if (!pe.str(t.u1.AddressOfData + offsetof(IMAGE_IMPORT_BY_NAME, Name), nm, sizeof nm, r)) continue; + f(nm, const_cast(reinterpret_cast(sp))); + } +} + +void import_slots(const void* module, const char* leaf, Reader& r, Budget& b, + const std::function& f) { + PeView pe; + uint32_t rva = 0, size = 0; + if (!pe.open(module, r) || !pe.dir(IMAGE_DIRECTORY_ENTRY_IMPORT, &rva, &size)) return; + // the descriptors the directory declares, no more (the null descriptor usually ends the walk earlier) + const uint32_t count = size / sizeof(IMAGE_IMPORT_DESCRIPTOR) < 4096 ? size / sizeof(IMAGE_IMPORT_DESCRIPTOR) : 4096; + for (uint32_t k = 0; k < count && b.step(); ++k) { + const uint8_t* dp = pe.at(rva + (uint64_t)k * sizeof(IMAGE_IMPORT_DESCRIPTOR), sizeof(IMAGE_IMPORT_DESCRIPTOR)); + IMAGE_IMPORT_DESCRIPTOR e; + if (!dp || !r.get(dp, &e) || !e.Name) return; + char dll[64]; + if (!pe.str(e.Name, dll, sizeof dll, r) || _stricmp(dll, leaf) != 0) continue; + thunks(pe, r, b, e.OriginalFirstThunk ? e.OriginalFirstThunk : e.FirstThunk, e.FirstThunk, f); + } +} + bool decode_jump(const uint8_t* c, size_t n, const uint8_t* at, const void** target, const void** cell) { if (cell) *cell = nullptr; if (n >= 5 && c[0] == 0xE9) { // jmp rel32 @@ -331,10 +415,11 @@ State decide(Verdict::Kind kind, Mode mode, Stage stage, State current) { return current; } -// The beginnings a reader can match (HOOK-MODE.md documents them; keep them exactly): kForeignStem, kStem (the NGX -// route's "stays off" line), kOwnCopyStem. None of them has the "hook: " prefix of the diagnostics. +// The beginnings a reader can match (HOOK-MODE.md documents them; keep them exactly): kForeignStem, kRefusedStem (the +// NGX route's refusal), kOwnCopyStem. None of them has the "hook: " prefix of the diagnostics. static const char kForeignStem[] = "another module hooks the game's RR calls: "; -static const char kStem[] = "another Ray Reconstruction plugin is active; WrongGPU RR stays off ("; +static const char kRefusedStem[] = + "the host refused WrongGPU's NGX RR provider registration; the NGX route stays off ("; static const char kOwnCopyStem[] = "a second copy of WrongGPU RR is loaded ("; std::string line_foreign(const std::string& module, const std::string& detail, Tail tail) { @@ -355,16 +440,23 @@ std::string line_foreign(const std::string& module, const std::string& detail, T std::string line_own_copy(const std::string& active, const std::string& self) { return std::string(kOwnCopyStem) + active + " is active); this copy (" + self + ") stays off"; } -std::string line_ngx_other() { - return std::string(kStem) + - "NGX route only: the host refused WrongGPU's RR provider, another provider holds it; the game-interface " - "route is decided on its own)"; +std::string line_ngx_refused() { + // the host API gives one false for an occupied slot and for an incomplete structure: only the refusal is known + return std::string(kRefusedStem) + "the game-interface route is decided on its own)"; } std::string line_inconclusive(const std::string& when, unsigned n, const std::string& first) { return "hook: coexistence check " + when + ": inconclusive for " + std::to_string(n) + " address(es) (first: " + first + "); no other plugin was positively found, WrongGPU RR stays active"; } +std::string line_over_budget(unsigned entries, double ms) { + char t[32]; + snprintf(t, sizeof t, "%.1f ms", ms); + return "hook: coexistence check at load: stopped after " + std::to_string(entries) + " entries (" + t + + "), over its budget of " + std::to_string(kScanMaxEntries) + " entries / " + std::to_string(kScanMaxMs) + + " ms; inconclusive, WrongGPU RR stays active"; +} + void Decision::freeze_once(const std::function& decide) { if (frozen()) return; std::call_once(once_, [&] { @@ -381,10 +473,20 @@ void Decision::check(const std::function& decide) { } // ---------------------------------------------------------------- the real process +ModuleRef::ModuleRef(const void* m) { + HMODULE h = nullptr; + if (m && GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, static_cast(m), &h)) h_ = h; +} +ModuleRef::~ModuleRef() { + if (h_) FreeLibrary(static_cast(h_)); +} + namespace { std::string leaf_utf8(const void* m) { + const ModuleRef ref(m); // the module stays loaded while its name is read + if (!ref.held()) return std::string(); wchar_t buf[MAX_PATH * 2]; - const DWORD n = GetModuleFileNameW(static_cast(const_cast(m)), buf, MAX_PATH * 2); + const DWORD n = GetModuleFileNameW(static_cast(ref.handle()), buf, MAX_PATH * 2); std::wstring p(buf, n); const size_t slash = p.find_last_of(L"\\/"); if (slash != std::wstring::npos) p = p.substr(slash + 1); @@ -410,7 +512,8 @@ Env process_env(const void* self, const void* iface, const void* host, const voi return m; }; e.exports = [](const void* m, const char* name) { - return GetProcAddress(static_cast(const_cast(m)), name) != nullptr; + const ModuleRef ref(m); // the module stays loaded while its exports are looked up (unloaded: exports nothing) + return ref.held() && GetProcAddress(static_cast(ref.handle()), name) != nullptr; }; e.name_of = leaf_utf8; // the interface's own import address table (IMAGE_DIRECTORY_ENTRY_IAT), read through safe reads and checked against diff --git a/clean/rr_f/proxy/src/rr_guard.h b/clean/rr_f/proxy/src/rr_guard.h index 89ad583e..1726070c 100644 --- a/clean/rr_f/proxy/src/rr_guard.h +++ b/clean/rr_f/proxy/src/rr_guard.h @@ -6,7 +6,9 @@ // WrongGPU RR switches itself off automatically ONLY on evidence that is positive by contract: // - a second copy of WrongGPU RR (the process-wide marker, or an address that ends in a module exporting // kOwnRrExport); -// - the host's plugin API saying the RR provider slot is taken, or refusing our registration (hook_dll.cpp). +// - the host's plugin API refusing a registration (hook_dll.cpp): the route it refused stays off. The API does not +// say why (an occupied slot and an incomplete structure give the same false), so the log says only that it +// refused. // Nothing else. A named foreign module on the call path is INCONCLUSIVE: it may be another RR plugin, but it may as well // be a game's own wrapper DLL, an overlay, a security shim, a host helper in a third image or a forwarded export's // implementation DLL. WrongGPU RR stays active (as in 0.6.0) and one line names the module and the place @@ -18,8 +20,11 @@ // - safe_read: every read of memory we do not own (VirtualQuery for committed, readable, non-guard pages, then a // structured-exception-guarded copy); a failed read is "unknown", never a fault. The check and the copy are not // atomic (HOOK-MODE.md says what that leaves); -// - PeView: a module's PE64 headers read through the reader, with e_lfanew, every data directory and every RVA the -// scan follows checked against SizeOfImage before any address is formed from them; +// - PeView: a module's PE64 headers read through the reader. The image's extent is the smaller of SizeOfImage and +// what is really mapped there (mapped_extent); e_lfanew, every data directory, every RVA the scan follows and +// every byte of a name are checked against that extent before an address is formed from them; +// - thunks / import_slots: the import walk of the load scan (descriptors only within the import directory's +// declared size), under a Budget (entries visited, elapsed time) that ends the scan as inconclusive when spent; // - decode_jump: the jump forms a hook puts at the start of a function (jmp rel32 / rel8, jmp [rip+disp32], // mov rax|r11, imm64 + jmp reg); // - classify: who an address belongs to (our module, the game interface, the host, another copy of WrongGPU RR, @@ -76,11 +81,20 @@ class Reader { uintptr_t lo_ = 0, hi_ = 0; }; -// A loaded module's PE64 headers as the scan may use them. open() reads the DOS and NT headers through the reader and -// accepts them only when e_lfanew points inside the image (and the NT headers fit), the optional header is PE32+ and -// SizeOfImage is plausible; dir() hands out a data directory only when its RVA and size lie inside SizeOfImage. at() -// forms an address from an RVA only after checking [rva, rva + n) against SizeOfImage (integers first, no pointer -// arithmetic on unchecked values). Anything that fails is "not readable": the caller treats it as nothing found. +// The bytes from p to the end of the committed regions of the allocation p lies in (VirtualQuery, at most 4096 +// regions). 0: p is not in committed memory. +size_t mapped_extent(const void* p); + +// A loaded module's PE64 headers as the scan may use them. open() first measures what is mapped at the module +// (mapped_extent), reads the DOS header only inside that, checks e_lfanew as an integer against it before the NT +// headers are read, and accepts them only when they fit inside both SizeOfImage and the mapping, the optional header +// is PE32+ and SizeOfImage is plausible. The image's extent is then the smaller of SizeOfImage and the mapping (a +// forged larger SizeOfImage does not widen it). dir() hands out a data directory only when its RVA and size lie inside +// the extent. +// at() forms an address from an RVA only after checking [rva, rva + n) against the extent (integers first, no pointer +// arithmetic on unchecked values); str() reads a name byte by byte, each byte checked the same way, so a name without +// its NUL before the end of the image is refused, never read past. Anything that fails is "not readable": the caller +// treats it as nothing found. class PeView { public: bool open(const void* module, Reader& r); @@ -88,7 +102,9 @@ class PeView { bool dir(unsigned index, uint32_t* rva, uint32_t* size) const; // base + rva when [rva, rva + n) lies inside the image, else null const uint8_t* at(uint64_t rva, uint64_t n) const; - uint32_t size_of_image() const { return size_; } + // the NUL-terminated string at rva, at most max - 1 characters, every byte inside the extent (false otherwise) + bool str(uint64_t rva, char* out, size_t max, Reader& r) const; + uint32_t size_of_image() const { return size_; } // the extent: min(SizeOfImage, the mapping) const uint8_t* base() const { return base_; } private: @@ -99,6 +115,40 @@ class PeView { uint32_t dir_size_[16] = {}; }; +// The work budget of one scan: entries visited (modules, import descriptors, name-table entries) and elapsed time. +// step() counts one entry; false once either limit is passed (the time is looked at every 64 entries), and it stays +// false. A scan over its budget is inconclusive: it decides nothing (RR stays active) and logs line_over_budget. +class Budget { + public: + Budget(unsigned max_entries, unsigned max_ms); + bool step(); + bool over() const { return over_; } + unsigned entries() const { return entries_; } + double elapsed_ms() const; + + private: + unsigned max_entries_, entries_ = 0; + double max_ms_; + int64_t t0_ = 0, freq_ = 1; + bool over_ = false; +}; +// The load scan's budget: far above a game's import tables (a few thousand entries, well under a millisecond), far +// below a stall a player would notice. +constexpr unsigned kScanMaxEntries = 200000; +constexpr unsigned kScanMaxMs = 100; + +// The by-name entries of one import (or delay-load) name table at names_rva with its address table at iat_rva: +// f(import name, slot address) for each, in order. It stops at the table's null entry, at an entry outside the image, +// after 4096 entries, or when the budget is spent; ordinal entries and names that are unreadable or not terminated +// inside the image are skipped. +void thunks(const PeView& pe, Reader& r, Budget& b, uint32_t names_rva, uint32_t iat_rva, + const std::function& f); +// Every by-name import slot of the image at `module` from the DLL named `leaf` (case-insensitive): the import +// descriptors are read only within the import directory's declared size (and up to the null descriptor), each named +// DLL's name table through thunks(). +void import_slots(const void* module, const char* leaf, Reader& r, Budget& b, + const std::function& f); + // A hook jump at `at` (code holds the first bytes read from there, n of them). On success *target is where it goes; // for jmp [rip+disp32] *cell is the pointer cell (read with safe_read; a failed read makes the decode fail). bool decode_jump(const uint8_t* code, size_t n, const uint8_t* at, const void** target, const void** cell); @@ -131,7 +181,24 @@ struct Env { std::function exports; // the module exports `name` std::function name_of; // the module's file name (for the log) }; -// The real process: GetModuleHandleExW (from address, refcount unchanged), GetProcAddress, GetModuleFileNameW. +// A reference to the module holding the address m (GetModuleHandleExW from address, refcount raised; released at the +// end of the scope), so the module cannot unload while a module API (GetProcAddress, GetModuleFileNameW) runs on it. +// held() false: no module holds m any more (unloaded meanwhile); the caller treats it as nothing found. +class ModuleRef { + public: + explicit ModuleRef(const void* m); + ~ModuleRef(); + ModuleRef(const ModuleRef&) = delete; + ModuleRef& operator=(const ModuleRef&) = delete; + bool held() const { return h_ != nullptr; } + void* handle() const { return h_; } + + private: + void* h_ = nullptr; +}; + +// The real process: GetModuleHandleExW (from address, refcount unchanged) for module_of; GetProcAddress and +// GetModuleFileNameW under a ModuleRef. Env process_env(const void* self, const void* iface, const void* host, const void* host_alt = nullptr); struct Where { @@ -187,7 +254,7 @@ enum class Stage { kLoad, kRoutes, kLate }; State decide(Verdict::Kind kind, Mode mode, Stage stage, State current); // The log lines (stable; HOOK-MODE.md documents them; the beginnings are what a reader such as the launcher's Last run -// page can match: kForeignStem, the "stays off" stem of line_ngx_other, the own-copy stem). +// page can match: kForeignStem, the refusal stem of line_ngx_refused, the own-copy stem). // A named foreign module on the RR path: "another module hooks the game's RR calls: (); " enum class Tail { kStaysActive, // rr_other_plugin=off (also take after our handlers are in place): RR stays WrongGPU's @@ -197,10 +264,12 @@ enum class Tail { }; std::string line_foreign(const std::string& module, const std::string& detail, Tail tail); std::string line_own_copy(const std::string& active, const std::string& self); -std::string line_ngx_other(); // the host refused our NGX provider +std::string line_ngx_refused(); // the host refused our NGX provider // The stay-on diagnostic (starts with "hook: "; never with a beginning above): the scan could not explain `n` // address(es), `first` is the first one. RR stays active. std::string line_inconclusive(const std::string& when, unsigned n, const std::string& first); +// The load scan ran out of its budget (entries visited, elapsed time): inconclusive, WrongGPU RR stays active +std::string line_over_budget(unsigned entries, double ms); class Decision { public: diff --git a/clean/rr_f/proxy/tests/test_rr_guard.cpp b/clean/rr_f/proxy/tests/test_rr_guard.cpp index 9d5edbb8..8c989685 100644 --- a/clean/rr_f/proxy/tests/test_rr_guard.cpp +++ b/clean/rr_f/proxy/tests/test_rr_guard.cpp @@ -5,7 +5,12 @@ // cached reader's structured-exception path (a page made unreadable after its region was cached); the cache keeps // VirtualQuery calls few; // - PeView: the real exe's headers; synthetic headers with a bad e_lfanew (negative, inside the DOS header, absurd, NT -// headers past SizeOfImage), directories past SizeOfImage or wrapping, too few directories, PE32, no signature; +// headers past SizeOfImage or past the mapping), directories past SizeOfImage or wrapping, too few directories, +// PE32, no signature; a SizeOfImage larger than the mapping (the extent is the mapping); mapped_extent; +// - the import walk (import_slots / thunks): a name whose RVA is the image's last byte with no NUL inside the image +// (skipped, never read past), names ending at the last byte, an import directory smaller than its descriptors +// (only the declared ones), another DLL's name; the budget by entries and by time (over: the walk stops, stays +// over); // - decode_jump: every jump form, and a jmp [rip+disp32] whose cell is not readable; // - classify: synthetic modules (ranges of one allocation) and anonymous relays: the interface's own code, a hook jump // to another module, a jump inside the interface, the linker's import thunk, a relay chain to the host, exactly @@ -452,6 +457,135 @@ int main() { nt->Signature = 0; PeView nosig; CHECK(!nosig.open(img, r)); + // the image's extent is what is mapped, not what the header claims: SizeOfImage 0x10000 over 3 mapped pages + reset(); + nt->OptionalHeader.SizeOfImage = 0x10000; + PeView big; + CHECK(big.open(img, r) && big.size_of_image() == 3 * kPage && big.at(3 * kPage - 1, 1) != nullptr && + big.at(3 * kPage, 1) == nullptr); + // NT headers that would end past the mapping: refused before they are read (e_lfanew within the 1 MiB cap) + reset(); + dos->e_lfanew = (LONG)(3 * kPage - 0x40); + PeView past; + CHECK(!past.open(img, r)); + CHECK(mapped_extent(img) == 3 * kPage && mapped_extent(img + 0x123) == 3 * kPage - 0x123 && + mapped_extent(nullptr) == 0); + VirtualFree(img, 0, MEM_RELEASE); + } + + // ---------------------------------------------------------------- the import walk: bounded names, the declared + // directory size, the budget + { + // a synthetic image (SizeOfImage 0x2000) in 3 committed pages: the page after the image is readable, so a read past + // the image would not fault; only the bounds keep the walk inside + uint8_t* img = static_cast(VirtualAlloc(nullptr, 3 * kPage, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + CHECK(img != nullptr); + auto* dos = reinterpret_cast(img); + auto* nt = reinterpret_cast(img + 0x80); + auto* desc = reinterpret_cast(img + 0x1000); + auto thunk = [&](uint32_t rva) { return reinterpret_cast(img + rva); }; + auto name = [&](uint32_t rva, const char* text) { // IMAGE_IMPORT_BY_NAME: hint (2 bytes), then the name + memcpy(img + rva + 2, text, strlen(text) + 1); + }; + auto build = [&](uint32_t dir_size) { + memset(img, 0, 3 * kPage); + dos->e_magic = IMAGE_DOS_SIGNATURE; + dos->e_lfanew = 0x80; + nt->Signature = IMAGE_NT_SIGNATURE; + nt->OptionalHeader.Magic = IMAGE_NT_OPTIONAL_HDR64_MAGIC; + nt->OptionalHeader.SizeOfImage = 0x2000; + nt->OptionalHeader.NumberOfRvaAndSizes = 16; + nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT] = {0x1000, dir_size}; + // two descriptors of iface.dll and the null one + desc[0].OriginalFirstThunk = 0x1100; + desc[0].FirstThunk = 0x1200; + desc[0].Name = 0x1300; + desc[1].OriginalFirstThunk = 0x1180; + desc[1].FirstThunk = 0x1280; + desc[1].Name = 0x1300; + memcpy(img + 0x1300, "iface.dll", 10); + // descriptor 0: fnA, fnB, a name whose RVA is the image's last bytes and has no NUL inside the image (the bytes + // after it, past the image, are readable and not NUL), fnD; descriptor 1: fnC + const uint32_t cut_off = 0x2000 - 3; // hint at the image's last 3 bytes but one, its name at the last byte + uint64_t* names0 = thunk(desc[0].OriginalFirstThunk); + names0[0] = 0x1400; + names0[1] = 0x1420; + names0[2] = cut_off; + names0[3] = 0x1440; + thunk(desc[1].OriginalFirstThunk)[0] = 0x1460; + name(0x1400, "fnA"); + name(0x1420, "fnB"); + name(0x1440, "fnD"); + name(0x1460, "fnC"); + img[0x1FFF] = 'Z'; // the cut-off name's one byte inside the image + memset(img + 0x2000, 'Z', 64); + }; + std::vector got; + std::vector slots; + auto collect = [&](const char* nm, void** slot) { + got.push_back(nm); + slots.push_back(slot); + }; + Reader r; + // the whole directory (three descriptors): every name, the cut-off one skipped (never read past the image) + build(3 * sizeof(IMAGE_IMPORT_DESCRIPTOR)); + { + Budget b(kScanMaxEntries, kScanMaxMs); + import_slots(img, "IFACE.DLL", r, b, collect); + CHECK(got == std::vector({"fnA", "fnB", "fnD", "fnC"}) && !b.over()); + CHECK(slots.size() == 4 && slots[0] == reinterpret_cast(img + 0x1200) && + slots[2] == reinterpret_cast(img + 0x1218) && slots[3] == reinterpret_cast(img + 0x1280)); + } + // the same name bytes terminated inside the image are read + { + PeView pe; + char nm[8]; + CHECK(pe.open(img, r) && !pe.str(0x1FFF, nm, sizeof nm, r)); // 'Z' at the last byte, no NUL before the end + img[0x1FFF] = 0; + CHECK(pe.str(0x1FFF, nm, sizeof nm, r) && nm[0] == 0); + memcpy(img + 0x1FFC, "abc", 4); // "abc" ending with the image's last byte + CHECK(pe.str(0x1FFC, nm, sizeof nm, r) && strcmp(nm, "abc") == 0); + CHECK(!pe.str(0x1FFC, nm, 3, r)); // longer than the buffer + } + // an import directory smaller than its descriptors: only the declared one is read + build(sizeof(IMAGE_IMPORT_DESCRIPTOR)); + got.clear(), slots.clear(); + { + Budget b(kScanMaxEntries, kScanMaxMs); + import_slots(img, "iface.dll", r, b, collect); + CHECK(got == std::vector({"fnA", "fnB", "fnD"})); + } + build(sizeof(IMAGE_IMPORT_DESCRIPTOR) - 1); // less than one descriptor: none + got.clear(), slots.clear(); + { + Budget b(kScanMaxEntries, kScanMaxMs); + import_slots(img, "iface.dll", r, b, collect); + CHECK(got.empty()); + } + // another DLL's name: nothing + build(3 * sizeof(IMAGE_IMPORT_DESCRIPTOR)); + got.clear(), slots.clear(); + { + Budget b(kScanMaxEntries, kScanMaxMs); + import_slots(img, "other.dll", r, b, collect); + CHECK(got.empty() && b.entries() == 3); // the two descriptors and the null one, no name table + } + // the budget: three entries (a descriptor, two name-table entries) and the walk stops, over its budget + got.clear(), slots.clear(); + { + Budget b(3, kScanMaxMs); + import_slots(img, "iface.dll", r, b, collect); + CHECK(b.over() && got == std::vector({"fnA", "fnB"})); + CHECK(!b.step() && b.over()); // stays over + } + // the time budget: looked at every 64 entries; with 0 ms and the clock moved on, over at the 64th + { + Budget b(kScanMaxEntries, 0); + Sleep(2); + unsigned n = 0; + while (b.step()) ++n; + CHECK(n == 63 && b.over() && b.entries() == 64 && b.elapsed_ms() > 0.0); + } VirtualFree(img, 0, MEM_RELEASE); } @@ -483,15 +617,22 @@ int main() { fstem + "Other.dll (" + d + "); rr_other_plugin=yield: WrongGPU RR stays off (WrongGPU's handlers pass every " "call on unchanged)"); // only yield says "stays off"; nothing about a named module claims it is a Ray Reconstruction plugin - const std::string stem = "another Ray Reconstruction plugin is active; WrongGPU RR stays off"; for (Tail t : {Tail::kStaysActive, Tail::kTakeInFront, Tail::kYieldOff, Tail::kYieldPassing}) { const std::string l = line_foreign("M", "D", t); CHECK(l.compare(0, fstem.size(), fstem) == 0 && l.find("plugin is active") == std::string::npos); CHECK((l.find("stays off") != std::string::npos) == (t == Tail::kYieldOff || t == Tail::kYieldPassing)); } CHECK(line_own_copy("A", "B") == "a second copy of WrongGPU RR is loaded (A is active); this copy (B) stays off"); - CHECK(line_ngx_other() == stem + " (NGX route only: the host refused WrongGPU's RR provider, another provider " - "holds it; the game-interface route is decided on its own)"); + // the host's refusal says only that it refused (its API gives one false for an occupied slot and for an + // incomplete structure): no other plugin is claimed + CHECK(line_ngx_refused() == + "the host refused WrongGPU's NGX RR provider registration; the NGX route stays off (the game-interface route " + "is decided on its own)"); + CHECK(line_ngx_refused().find("plugin is active") == std::string::npos && + line_ngx_refused().find("another provider") == std::string::npos); + CHECK(line_over_budget(200001, 3.25) == + "hook: coexistence check at load: stopped after 200001 entries (3.2 ms), over its budget of 200000 entries / " + "100 ms; inconclusive, WrongGPU RR stays active"); // the stay-on diagnostic: never one of the matched beginnings const std::string inc = line_inconclusive("at load", 2, "the import slot X of Game.exe could not be read"); CHECK(inc == "hook: coexistence check at load: inconclusive for 2 address(es) (first: the import slot X of Game.exe " diff --git a/clean/rr_f/proxy/tests/test_rr_guard_dll.cpp b/clean/rr_f/proxy/tests/test_rr_guard_dll.cpp index 9922289f..7b21a39a 100644 --- a/clean/rr_f/proxy/tests/test_rr_guard_dll.cpp +++ b/clean/rr_f/proxy/tests/test_rr_guard_dll.cpp @@ -5,7 +5,8 @@ // (tests/fake_other_rr.cpp), and further copies of it under other file names; no third-party file is used. // test_rr_guard_dll.exe [--take | --yield] // WrongGPU RR switches itself off only on evidence that is positive by contract: a second copy of WrongGPU RR, or the -// host's plugin API refusing our registration. A named module on the call path is inconclusive: it is named in one +// host's plugin API refusing our registration (the refused route stays off; the API does not say why, so the log +// claims no other plugin). A named module on the call path is inconclusive: it is named in one // line and WrongGPU RR stays active; --yield (rr_other_plugin=yield) makes it switch WrongGPU RR off, --take // (rr_other_plugin=take) puts WrongGPU RR in front of it. // Modes (import build). Named module on the path, RR stays active (no second RR provider in the innocent ones): @@ -34,7 +35,10 @@ // one decision, one line naming it, WrongGPU RR stays active behind it // late-replace the stand-in replaced our hooks after InitializeASI: named at OptiPluginInit, stays active // Positive by contract, WrongGPU RR (or that route) switches off: -// provider the stand-in holds the host's NGX RR provider: the NGX route stays off, the game-interface route stays +// provider the stand-in holds the host's NGX RR provider: the host refuses ours, the NGX route stays off (the +// line says the host refused, not why), the game-interface route stays +// provider-refused the host refuses our NGX provider with no provider installed (an incomplete structure gives the +// same false): the same line, no other plugin claimed, the game-interface route stays // owncopy WrongGPU RR and four more copies under other file names: the others stay off and register nothing; the // copies' InitializeASI / OptiPluginInit run from threads while 16 game threads make the first call (every // copy writes the one log at once: no torn line); freeing an inactive copy writes no exit summary @@ -167,6 +171,7 @@ WgHostMenuPlugin* const kOurs = reinterpret_cast(0x1000); WgHostMenuPlugin* const kTheirs = reinterpret_cast(0x2000); int route_regs[2] = {0, 0}, ngx_regs = 0; bool refuse_routes = false; // route-refused: the host's API says no +bool refuse_ngx = false; // provider-refused: the host refuses the NGX provider though no provider holds the slot WgHostMenuPlugin* ngx_owner = nullptr; void (*callback)(void*, uint32_t, uint32_t, uint32_t, void*) = nullptr; void* callback_user = nullptr; @@ -190,7 +195,7 @@ bool set_callback(WgHostMenuPlugin*, void (*cb)(void*, uint32_t, uint32_t, uint3 } bool register_ngx(WgHostMenuPlugin* p, const WgHostNgxRr* prov) { ++ngx_regs; - if (ngx_owner || !prov || !prov->create) return false; + if (refuse_ngx || ngx_owner || !prov || !prov->create) return false; ngx_owner = p; return true; } @@ -279,7 +284,7 @@ int main(int argc, char** argv) { const std::string exe_leaf = "test_rr_guard_dll.exe"; const std::string iface_leaf = kWgInterposerFile; const std::string evaluate_name = kWgRoleNames[kEvaluate]; - const std::string stem = "another Ray Reconstruction plugin is active; WrongGPU RR stays off ("; + const std::string stem = "the host refused WrongGPU's NGX RR provider registration; the NGX route stays off ("; const std::string fstem = "another module hooks the game's RR calls: "; const std::string tail_active = "; it is not known to be a Ray Reconstruction plugin: WrongGPU RR stays active " "(rr_other_plugin=yield in wronggpu-rr.ini keeps WrongGPU RR off in this case)"; @@ -381,6 +386,7 @@ int main(int argc, char** argv) { CHECK(or_set_slot(exe, kWgInterposerFile, evaluate_name.c_str(), p) == 1); } if (mode == "provider") CHECK(or_ngx(&api, host::kTheirs)); + if (mode == "provider-refused") host::refuse_ngx = true; // ---- WrongGPU RR (the host loads it and runs its entry) load_asi(widen(kWgHookFile), &init, &plugin_init); @@ -452,7 +458,7 @@ int main(int argc, char** argv) { } // ---- the game's calls - if (mode == "clean" || mode == "late" || mode == "provider") { + if (mode == "clean" || mode == "late" || mode == "provider" || mode == "provider-refused") { // 16 threads make the game's first interface call at once const int ok = at_once(16, [] { return slIsFeatureSupported(kOther, nullptr); }, kIfaceAnswer); CHECK_EQ(ok, 16); @@ -588,12 +594,14 @@ int main(int argc, char** argv) { CHECK(count(read_lines(log_path), "NGX: RR provider registered with the host") == 1); CHECK(host::ngx_owner == host::kOurs); #endif - } else if (mode == "provider") { + } else if (mode == "provider" || mode == "provider-refused") { #if !WG_BINDING_PROBE - // the host's API says its RR provider slot is taken: the NGX route stays off (positive by contract) - CHECK(count_starting(L, stem + "NGX route only: the host refused WrongGPU's RR provider, another provider holds it; " - "the game-interface route is decided on its own)") == 1); - CHECK(host::ngx_owner == host::kTheirs && host::ngx_regs == 2); + // the host's API refuses our provider: the NGX route stays off (positive by contract). Its false does not say why + // (an occupied slot, an incomplete structure), so the line says only that the host refused + CHECK(count_starting(L, stem + "the game-interface route is decided on its own)") == 1); + CHECK(count(L, "another Ray Reconstruction plugin is active") == 0 && count(L, "another provider") == 0); + if (mode == "provider") CHECK(host::ngx_owner == host::kTheirs && host::ngx_regs == 2); + else CHECK(host::ngx_owner == nullptr && host::ngx_regs == 1); // no provider anywhere CHECK(count(L, patched) == 1); // the game-interface route stays ours CHECK(count(L, stem) == 1); CHECK(rr_ours); diff --git a/clean/rr_f/proxy/tools/build.py b/clean/rr_f/proxy/tools/build.py index 91dbca50..c0ddf16d 100644 --- a/clean/rr_f/proxy/tools/build.py +++ b/clean/rr_f/proxy/tools/build.py @@ -405,8 +405,9 @@ def test_hook(built, binding, out, logs, probe, n=None, gen=None): GUARD_MODES_RELEASE = (["clean"], ["first"], ["first", "--take"], ["inline"], ["inline", "--take"], ["relay"], ["execonly"], ["wrapper"], ["wrapper", "--yield"], ["overlay"], ["forward"], ["helper"], ["hostsplit"], ["heaptable"], ["helpertable"], ["anon"], ["noaccess"], ["guardpage"], ["exe"], ["hops"], ["late"], - ["late", "--take"], ["late-replace"], ["provider"], ["owncopy"], ["route"], ["route-other"], - ["route-other", "--take"], ["route-other", "--yield"], ["route-inline"], ["route-refused"]) + ["late", "--take"], ["late-replace"], ["provider"], ["provider-refused"], ["owncopy"], ["route"], + ["route-other"], ["route-other", "--take"], ["route-other", "--yield"], ["route-inline"], + ["route-refused"]) GUARD_MODES_PROBE = (["clean"], ["first"], ["inline"], ["execonly"], ["wrapper"], ["wrapper", "--yield"], ["overlay"], ["forward"], ["heaptable"], ["noaccess"], ["hops"], ["late"], ["owncopy"], ["route-other"], ["route-refused"])