diff --git a/clean/rr_f/proxy/HOOK-MODE.md b/clean/rr_f/proxy/HOOK-MODE.md index f868cf92..39181767 100644 --- a/clean/rr_f/proxy/HOOK-MODE.md +++ b/clean/rr_f/proxy/HOOK-MODE.md @@ -115,6 +115,170 @@ 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). 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. 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** 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 +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 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 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 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. 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 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. + +**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 **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). +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 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 + 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). + +**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 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` +- `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) +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`, +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 +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 +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 +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 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 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..acc8de8f 100644 --- a/clean/rr_f/proxy/src/hook_dll.cpp +++ b/clean/rr_f/proxy/src/hook_dll.cpp @@ -36,8 +36,19 @@ // 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); 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 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) @@ -55,9 +66,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 +143,29 @@ 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; +// 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_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 +// 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 +// 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; 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 +204,21 @@ 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); + // 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 + 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 +234,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 +245,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 +347,11 @@ void bind(F& slot, int role) { slot = reinterpret_cast(g_route_next[role]); // host route: continue through the host's chain return; } + 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; + } slot = name[0] ? reinterpret_cast(GetProcAddress(g_interposer, name)) : nullptr; } @@ -686,12 +725,29 @@ 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(); +} +// 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 // ---------------------------------------------------------------- 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 +755,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 +825,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 +844,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 +1146,282 @@ DWORD WINAPI slot_watch_thread(void*) { return 0; } +// ---------------------------------------------------------------- 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 + +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; +} + +// 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, 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, slot); + }); +} + +// 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, 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: +// 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_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 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()); +} + +// 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)); +} + +// 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). 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 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; + const void* e = reinterpret_cast(GetProcAddress(module, kWgRoleNames[role])); + if (!e) continue; + 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 (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(); + LARGE_INTEGER t0; + QueryPerformanceCounter(&t0); + 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); + 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 && budget.step(); ++i) { + if (mods[i] == g_self || mods[i] == g_interposer) continue; + 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); + if (mods[i] == exe && val && w.owner != g::Owner::kInterface) prev[role] = val; + }); + } + } + g::PeView pe; + // 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); + if (val && w.owner != g::Owner::kInterface && w.owner != g::Owner::kExeThunk && w.owner != g::Owner::kHost) + 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) + + " address(es) read in " + ms_text(ms) + ")"); + guard_log_unclear("at load", v); + 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 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(); + if (s != g::State::kActive && s != g::State::kTaken) return s; + LARGE_INTEGER t0; + QueryPerformanceCounter(&t0); + const g::Env env = guard_env(g_interposer); + 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, false, true); // what changed since the load check + const double ms = ms_since(t0); + 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(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(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() { + g_guard.freeze_once([] { return guard_late("the game's first call", true); }); +} + void do_hook() { diagnostics("InitializeASI"); std::wstring interposer_w; @@ -1082,6 +1461,11 @@ 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: 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) + // 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 +1522,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 +1545,24 @@ 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), guard_env(module), true, &v); + 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); + 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) { const int role = kWgHookRoles[i]; @@ -1170,12 +1573,36 @@ 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). 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); + 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, + true, false); + 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 (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); (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 +1825,16 @@ void ngx_release_cpp(void* u, void* ctx) { ngx_fault("release (exception)"); } } +// 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}; + 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 +1902,11 @@ void register_ngx_provider(const WgHostMenuApi* api, WgHostMenuPlugin* plugin) { } return; } + 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; + } 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 +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 { - log_line("NGX: the host refused the RR provider registration (another provider is registered?)"); + } 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 @@ -1525,7 +1966,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 taken as the host (its own patches are accepted; wording only) + 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.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 wgrr::panel::start( @@ -1548,6 +1996,21 @@ 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; + // 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()) + g_host_api_module.store(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); @@ -1565,10 +2028,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 @@ -1612,12 +2080,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: 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 #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..66bf664c --- /dev/null +++ b/clean/rr_f/proxy/src/log_append.h @@ -0,0 +1,94 @@ +// 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 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 +#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/rr_guard.cpp b/clean/rr_f/proxy/src/rr_guard.cpp new file mode 100644 index 00000000..e1514a21 --- /dev/null +++ b/clean/rr_f/proxy/src/rr_guard.cpp @@ -0,0 +1,532 @@ +// SPDX-License-Identifier: MIT +// RR guard: see rr_guard.h. +#define WIN32_LEAN_AND_MEAN +#include + +#include +#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; + // 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; + 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; +} + +// 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) { + 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; +} + +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 (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) + 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_ = (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; + 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 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 + *target = rel(at, 5 + (intptr_t)rd32(c + 1)); + return true; + } + if (n >= 2 && c[0] == 0xEB) { // jmp rel8 + *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 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; + *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, 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"; + 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; + // 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.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 || (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]; + 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; } + if (!follow(target)) return w; + 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; + } + if (!follow(target)) return w; + } +} + +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 (trusted(w.owner, anon_ok, exe_ok)) return; + 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; + module = w.module.empty() ? std::string("another module") : w.module; + detail = what + " leads to " + module + via; + return; + } + // nothing could be told: 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; +} + +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 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 | yield); off is used"; + return Mode::kOff; +} + +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, 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 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) { + 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"; +} +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_, [&] { + 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 +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(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); + 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, 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; + 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) { + 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 + // 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; +} + +} // 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..1726070c --- /dev/null +++ b/clean/rr_f/proxy/src/rr_guard.h @@ -0,0 +1,298 @@ +// SPDX-License-Identifier: MIT +// RR guard: the coexistence guard of the hook-mode RR plugin (HOOK-MODE.md, "Another Ray Reconstruction +// 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. +// +// 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 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 +// (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. 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. 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, +// 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: 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 +#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 | 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, 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); +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; +}; + +// 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); + // 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; + // 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: + const uint8_t* base_ = nullptr; + uint32_t size_ = 0; + uint32_t ndirs_ = 0; + uint32_t dir_rva_[16] = {}; + 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); + +enum class Owner { + 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, or the module holding its API table (it patches the interface itself) + 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: inconclusive (named in the log; only rr_other_plugin=yield acts on it) +}; +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; // 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 + 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) +}; +// 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 { + 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. 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, 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 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). + 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. 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 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 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 + 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_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: + 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..f4dbd7e3 --- /dev/null +++ b/clean/rr_f/proxy/tests/fake_other_rr.cpp @@ -0,0 +1,240 @@ +// 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) +// 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, 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 + +#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 +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) { + 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 (!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; + } + 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) 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) { + 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; +} + +// "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; + 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/test_hook_dll.cpp b/clean/rr_f/proxy/tests/test_hook_dll.cpp index faf6ddac..1adf2968 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,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 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, "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 new file mode 100644 index 00000000..8c989685 --- /dev/null +++ b/clean/rr_f/proxy/tests/test_rr_guard.cpp @@ -0,0 +1,677 @@ +// 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, 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 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 +// 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: 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 + +#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)); // 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 + 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) + 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 (inconclusive: not a sign of another plugin) + put_abs(anon + 256, anon + 512); + put_abs(anon + 512, anon + 256); + 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 + 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.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::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 + 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 == 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::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::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)); + // 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); + } + + // ---------------------------------------------------------------- the override, the log lines + { + std::string note; + 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 + 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"); + // 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 " + "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 + 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..7b21a39a --- /dev/null +++ b/clean/rr_f/proxy/tests/test_rr_guard_dll.cpp @@ -0,0 +1,694 @@ +// 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 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 (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): +// 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) +// 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 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 +// 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 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 + +#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; +} +// 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); } +} +// 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; +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; +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)); + *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 (refuse_ngx || 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(); +} + +template +F fn(HMODULE m, const char* name) { + return m ? reinterpret_cast(GetProcAddress(m, name)) : nullptr; +} + +} // 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, 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" : "") + (yield ? ", yield" : "") + ")"; + + HMODULE other = LoadLibraryW((ws + L"wgtest_other_rr.dll").c_str()); + CHECK(other != nullptr); + if (!other) TEST_SUMMARY(label.c_str()); + 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 = "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)"; + 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()); + 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"; + 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" || 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 + 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 == "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 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")); + 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 + 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); + } + 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); + if (!init || !plugin_init) TEST_SUMMARY(label.c_str()); + const WgHostMenuApi* host_api = &api; // the table OptiPluginInit gets + 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 = 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); // 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) + } + 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 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 + // first call before it, so that the first call decides + 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 f) { + th.emplace_back([&go, f] { + while (!go.load()) std::this_thread::yield(); + f(); + }); + }; + 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 == "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); + } + 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 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, 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, 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()); + 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 (!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 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 (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" + : 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, fstem) == 0); + CHECK(count(L, "stays off") == 0); + 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)); // 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 (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, patched) == 1); + const std::string why = mode == "late" ? "the game's first call" : "OptiPluginInit"; + 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 + 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 registered with the host") == 1); + CHECK(host::ngx_owner == host::kOurs); +#endif + } else if (mode == "provider" || mode == "provider-refused") { +#if !WG_BINDING_PROBE + // 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); +#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; + (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 + 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 (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, fstem) == 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 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 (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 stand-in + CHECK(os->calls[kIsSupported] == calls + 1); + } + } + } else if (mode == "route-inline") { + // 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"); + } + (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..c0ddf16d 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,91 @@ 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 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"], + ["wrapper"], ["wrapper", "--yield"], ["overlay"], ["forward"], ["helper"], ["hostsplit"], + ["heaptable"], ["helpertable"], ["anon"], ["noaccess"], ["guardpage"], ["exe"], ["hops"], ["late"], + ["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"]) +# 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): + 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"])) + 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")) + 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): + 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 +536,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 +557,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/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])