From bac83cb2604be1896de4b03f4a7863a4eacafcec Mon Sep 17 00:00:00 2001 From: lewisalex86 Date: Thu, 26 Nov 2026 00:22:20 +0000 Subject: [PATCH 1/2] runtime: add an opt-in console profile for the OEM ConsoleMode read X2W_DEVICE_TYPE (with X2W_RUNTIME_PROXY) answers the title's reads of HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM\ConsoleMode: 6 = 0x60 (Series S), 7 = 0x64 (Series X), 1 = value missing (PC). Unset, every call goes to the real registry. The proxy rewrites five registry imports of the EXE and package helpers (regular IAT and GetProcAddress by name); visit_imports_with takes a classifier for them and visit_imports keeps its own behaviour. Opening the key and reading the value are logged a few times either way. New fixture with a negative control: startup_console_mode, against fake registry functions; the control leaves the switch unset for the answered cases. --- CMakeLists.txt | 8 + docs/startup-runtime.md | 21 ++ src/startup_stubs/console_mode.h | 96 +++++++++ src/startup_stubs/registry_console_mode.inl | 227 ++++++++++++++++++++ src/startup_stubs/runtime_gpa_patch.h | 28 ++- src/startup_stubs/runtime_proxy.cpp | 11 + tests/startup_console_mode_check.cpp | 221 +++++++++++++++++++ 7 files changed, 603 insertions(+), 9 deletions(-) create mode 100644 src/startup_stubs/console_mode.h create mode 100644 src/startup_stubs/registry_console_mode.inl create mode 100644 tests/startup_console_mode_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index ad93d3a12f..7557485c2c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1055,6 +1055,14 @@ target_compile_features(startup_runtime_gpa_patch PRIVATE cxx_std_17) add_test(NAME startup_runtime_gpa_patch COMMAND startup_runtime_gpa_patch) add_test(NAME startup_runtime_gpa_patch_name_only_control COMMAND startup_runtime_gpa_patch --mutate name-only) set_tests_properties(startup_runtime_gpa_patch_name_only_control PROPERTIES PASS_REGULAR_EXPRESSION "FAIL: ") +# X2W_DEVICE_TYPE: the OEM ConsoleMode registry read, answered or passed on, against fake registry +# functions. The control leaves the switch unset for the answered cases and must FAIL. +add_executable(startup_console_mode tests/startup_console_mode_check.cpp) +target_include_directories(startup_console_mode PRIVATE src) +target_compile_features(startup_console_mode PRIVATE cxx_std_17) +add_test(NAME startup_console_mode COMMAND startup_console_mode) +add_test(NAME startup_console_mode_control COMMAND startup_console_mode --control) +set_tests_properties(startup_console_mode_control PROPERTIES PASS_REGULAR_EXPRESSION "FAIL: ") # EXE + late-loaded package helper through the real Windows loader: proxied xgameruntime QueryApiImpl, # unrelated same-named export stays original. Notification only enqueues; rewrite runs after link. if (WIN32) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index e38af186e6..603e68384a 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1360,6 +1360,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_RUNTIME_PROXY=1` | proxies the gaming runtime and logs every call. Rewrites regular-IAT `GetProcAddress` and a direct `xgameruntime.dll!QueryApiImpl` import on the main EXE and on DLLs that share its directory (package helpers). Dynamic `QueryApiImpl` / `InitializeApiImpl*` are wrapped only when the provider module's basename is `xgameruntime.dll`. `LdrRegisterDllNotification` only flags that another scan is needed. A worker holds each matching module live while rewriting after linking. Loading a helper and immediately calling it can precede the scan. The enabled proxy stays loaded until process exit. Delay-import IAT slots are not rewritten. Skips this stand-in's own `GetProcAddress` IAT so the hook does not recurse (`src/startup_stubs/runtime_gpa_patch.h`, `ctest --preset dev --no-tests=error -R '^startup_runtime_gpa_patch(_name_only_control)?$'`, and the control must print `FAIL:`; Windows also runs `startup_runtime_proxy_scope` for a late-loaded helper through the real loader) | | `X2W_FAKE_USER=1` | answers the user, gamertag and save APIs for one local user, and creates one offline store context for that user | | `X2W_RUNTIME_LOCAL=1` | with `X2W_RUNTIME_PROXY` and `X2W_FAKE_USER`, for a host where the system gaming runtime cannot initialize (no Gaming Services). The first failed `InitializeApiImpl*` is reported as `S_OK`, and every later initialization call returns `S_OK` without calling the real export. Once initialization failure is latched, a failed real `QueryApiImpl` call can fall back only with an exact match of both GUIDs to a supported provider/interface pair for user (including gamertag), game save, package, title, connectivity or store. Persistent local storage uses its existing fake-user gate and requires its exact provider GUID and IID. Unmatched failed queries keep the real HRESULT. The proxy clears a writable output on failure only when fake user is enabled and the initialization failure is latched. A local object's `QueryInterface` accepts only `IID_IUnknown` and the IID it was created for. The local answers above apply, calls that carry the local user or store handle fail as before, and other unanswered methods return `E_NOTIMPL`. `XUserAddAsync` and async operations completed on behalf of a local answer require the real runtime's `QueryApiImpl` to return the XAsync provider (`073b7dcb`). Those operations complete with `S_OK` through XAsync, or return the query failure if XAsync is unavailable (`ctest --preset dev --no-tests=error -R '^startup_runtime_local(_control)?$'`, and the control must print `FAIL:`). | +| `X2W_DEVICE_TYPE=` | with `X2W_RUNTIME_PROXY=1`, answers the title's reads of the OEM `ConsoleMode` registry value: `6` = 0x60 (Series S), `7` = 0x64 (Series X), `1` = value missing (PC); unset, the real registry answers. See [Console profile](#console-profile) | | `X2W_STORAGE_PATH`, `X2W_STORAGE_MB`, `X2W_TITLE_ID` | persistent local storage and the manifest values the runtime would return. The path is UTF-8, with a trailing separator added when missing. If the path is invalid or exceeds 259 bytes including the separator, the proxy logs the refusal and uses `S:\` (`src/startup_stubs/storage_root_utf8.h`, `ctest --preset release --no-tests=error -R '^startup_storage_root'`). | | `X2W_INPUT_SCRIPT=mask@sec,...` | timed virtual gamepad presses, holds, stick or trigger values and waits for the presented picture: see [Input script](#input-script); keyboard and XInput pad 0 also work. Up to 256 entries and 4,095 characters; a longer value is ignored and logged, and dropped or malformed entries are logged (`ctest --preset dev --no-tests=error -R '^startup_gameinput_script_(long|entries|syntax)$'`) | | `X2W_SAMPLER_HEAP=1` | `gfx2hlsl.py` translates a sampler-heap load with a run-time offset into `SamplerState qh[2048] : register(s0, space1)` and writes `smpheap 2048 1 fallback 2047`. The stand-in uses entries 0 to 2046 for the bound heap and reserves entry 2047 for unaligned or out-of-range offsets. It also accepts the original `smpheap 2048 1` manifest with all 2,048 entries available. [#1143](https://github.com/R0Y00/Xbox2Windows/issues/1143) | @@ -1387,6 +1388,26 @@ together under their original name. A 16-dword table load can contain two independent image descriptors at offsets 0 and 32 from the load address. For a read-only census of cached shader refusals, use `python -B tools/startup/gfx2hlsl.py --refusals [--json]` with a translator that supports the flag. Earlier versions treat it as `--pending` and write into the directory. See [Startup translator refusal census](experiments.md#startup-translator-refusal-census). +## Console profile + +`X2W_DEVICE_TYPE` answers the two registry reads a title makes of +`HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM\ConsoleMode` +(`src/startup_stubs/console_mode.h`, `registry_console_mode.inl`): with `X2W_RUNTIME_PROXY=1` the +stand-in rewrites the registry imports of the EXE and package helpers. `6` answers 0x60 (Series S), +`7` answers 0x64 (Series X) and `1` reports the value missing (PC); unset, every call goes to the real +registry. Opening the key and reading the value are logged a few times either way. What the values +mean on the console is taken from public notes, not measured here. +`ctest --preset dev --no-tests=error -R '^startup_console_mode(_control)?$'` runs it against fake +registry functions; the control leaves the switch unset for the answered cases and must print `FAIL:`. + +The switch changes only what the registry reads answer. A title can take a different start-up path +for each profile: on the Series S profile, one loaded an upscaler package module that the other +profiles do not, and that module met desktop refusals the other profiles did not reach +(`Device::slot76`, views with `ViewDimension` 0, and `R9G9B9E5_SHAREDEXP` textures with unordered +access, the last covered by the +[shared-exponent stand-in](#shared-exponent-render-and-unordered-access-targets)). Choosing a profile +is not evidence that the path it leads to runs. + ## D3D12 resource budget Set `X2W_D3D12_BUDGET=1` before startup to add one `x2w-budget` line to each diff --git a/src/startup_stubs/console_mode.h b/src/startup_stubs/console_mode.h new file mode 100644 index 0000000000..7bc01ac3fd --- /dev/null +++ b/src/startup_stubs/console_mode.h @@ -0,0 +1,96 @@ +// Experimental (docs/startup-runtime.md): which console the title is told it runs on. +// +// Public GDK documentation describes XSystemGetDeviceType and the XSystemDeviceType values +// (Pc = 1, XboxScarlettLockhart = 6, XboxScarlettAnaconda = 7). The proxied runtime calls seen in +// startup runs include no device-type method. A public runtime reimplementation's notes +// (github.com/Marvisak/VIctory, facts only) say the value is not a runtime call: title code reads +// HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM, DWORD value ConsoleMode, where 0x60 is +// Series S, 0x64 is Series X and a missing value is a PC. Those three readings are that source's, +// not measured here. +// +// X2W_DEVICE_TYPE= (with X2W_RUNTIME_PROXY) answers that one value: 6 -> 0x60, 7 -> 0x64, +// 1 -> missing. Unset or any other number passes every read to the real registry. +// Pure helpers, no Windows calls, so a source-built control can check them. +#pragma once + +#include +#include + +namespace x2w_console_mode { + +constexpr long status_ok = 0, status_not_found = 2, status_invalid = 87, status_more_data = 234, status_wrong_type = 1630; +constexpr unsigned long type_dword = 4; +constexpr unsigned long rrf_rt_reg_dword = 0x10; +constexpr std::uint32_t series_s = 0x60, series_x = 0x64; + +inline wchar_t fold(wchar_t c) noexcept +{ + return (c >= L'A' && c <= L'Z') ? static_cast(c - L'A' + L'a') : c; +} + +inline bool equal_ci(const wchar_t* a, const wchar_t* b) noexcept +{ + if (!a || !b) return false; + for (;; ++a, ++b) { + if (fold(*a) != fold(*b)) return false; + if (!*a) return true; + } +} + +// Subkey of HKEY_LOCAL_MACHINE. One leading or trailing backslash is accepted. +inline bool is_oem_subkey(const wchar_t* subkey) noexcept +{ + static constexpr wchar_t expect[] = L"software\\microsoft\\windows nt\\currentversion\\oem"; + if (!subkey) return false; + if (*subkey == L'\\') ++subkey; + std::size_t i = 0; + for (; expect[i]; ++i) + if (fold(subkey[i]) != expect[i]) return false; + return !subkey[i] || (subkey[i] == L'\\' && !subkey[i + 1]); +} + +inline bool is_console_mode_value(const wchar_t* name) noexcept +{ + return equal_ci(name, L"ConsoleMode"); +} + +enum class Answer { pass, value, missing }; + +// device_set is false when X2W_DEVICE_TYPE is absent or not a number. +inline Answer answer_for(bool device_set, unsigned long device_type, std::uint32_t* mode) noexcept +{ + if (!device_set) return Answer::pass; + switch (device_type) { + case 1: return Answer::missing; + case 6: if (mode) *mode = series_s; return Answer::value; + case 7: if (mode) *mode = series_x; return Answer::value; + default: return Answer::pass; + } +} + +// RegQueryValueExW's output rules for one REG_DWORD. +inline long fill_query(std::uint32_t value, unsigned long* type, unsigned char* data, unsigned long* bytes) noexcept +{ + if (data && !bytes) return status_invalid; + if (type) *type = type_dword; + if (!data) { + if (bytes) *bytes = sizeof(value); + return status_ok; + } + if (*bytes < sizeof(value)) { + *bytes = sizeof(value); + return status_more_data; + } + for (std::size_t i = 0; i < sizeof(value); ++i) data[i] = static_cast(value >> (8 * i)); + *bytes = sizeof(value); + return status_ok; +} + +// RegGetValueW's: the flags must allow a DWORD (RRF_RT_REG_DWORD, part of RRF_RT_DWORD and RRF_RT_ANY). +inline long fill_get(unsigned long flags, std::uint32_t value, unsigned long* type, void* data, unsigned long* bytes) noexcept +{ + if (!(flags & rrf_rt_reg_dword)) return status_wrong_type; + return fill_query(value, type, static_cast(data), bytes); +} + +} // namespace x2w_console_mode diff --git a/src/startup_stubs/registry_console_mode.inl b/src/startup_stubs/registry_console_mode.inl new file mode 100644 index 0000000000..c0c95d96f7 --- /dev/null +++ b/src/startup_stubs/registry_console_mode.inl @@ -0,0 +1,227 @@ +// Experimental (docs/startup-runtime.md): registry reads of the console mode (see console_mode.h). +// Included inside runtime_proxy.cpp's anonymous namespace, and on its own by +// tests/startup_console_mode_check.cpp. Needs , , local_log.h, +// runtime_gpa_patch.h and console_mode.h. +// +// With X2W_RUNTIME_PROXY the stand-in rewrites five registry imports of the EXE and package helpers +// (regular IAT and GetProcAddress by name). Every call goes to the real function except a read of +// ConsoleMode under HKLM\...\OEM while X2W_DEVICE_TYPE names a known console. Opening the OEM +// key and reading the value are logged a few times in either case, so a run shows whether the +// title asks at all. + +enum RegistryImport { reg_open_key_ex_w, reg_open_key_w, reg_query_value_ex_w, reg_get_value_w, reg_close_key, registry_imports }; +constexpr const char* registry_import_names[registry_imports] = {"RegOpenKeyExW", "RegOpenKeyW", "RegQueryValueExW", "RegGetValueW", + "RegCloseKey"}; +using RegOpenKeyExWFn = LSTATUS(WINAPI*)(HKEY, LPCWSTR, DWORD, REGSAM, PHKEY); +using RegOpenKeyWFn = LSTATUS(WINAPI*)(HKEY, LPCWSTR, PHKEY); +using RegQueryValueExWFn = LSTATUS(WINAPI*)(HKEY, LPCWSTR, LPDWORD, LPDWORD, LPBYTE, LPDWORD); +using RegGetValueWFn = LSTATUS(WINAPI*)(HKEY, LPCWSTR, LPCWSTR, DWORD, LPDWORD, PVOID, LPDWORD); +using RegCloseKeyFn = LSTATUS(WINAPI*)(HKEY); + +std::atomic real_registry[registry_imports]; + +int registry_import_index(const char* name) noexcept +{ + if (!name) return -1; + for (int i = 0; i < registry_imports; ++i) + if (std::strcmp(name, registry_import_names[i]) == 0) return i; + return -1; +} + +// ---- OEM key handles the title opened ----------------------------------------------------------- +SRWLOCK oem_lock = SRWLOCK_INIT; +HKEY oem_keys[16]; + +void track_oem(HKEY key) noexcept +{ + AcquireSRWLockExclusive(&oem_lock); + for (HKEY& slot : oem_keys) { + if (!slot) { + slot = key; + break; + } + } + ReleaseSRWLockExclusive(&oem_lock); +} + +bool oem_key(HKEY key) noexcept +{ + if (!key) return false; + AcquireSRWLockShared(&oem_lock); + bool found = false; + for (HKEY slot : oem_keys) found = found || slot == key; + ReleaseSRWLockShared(&oem_lock); + return found; +} + +void untrack_oem(HKEY key) noexcept +{ + AcquireSRWLockExclusive(&oem_lock); + for (HKEY& slot : oem_keys) + if (slot == key) slot = nullptr; + ReleaseSRWLockExclusive(&oem_lock); +} + +// ---- the answer --------------------------------------------------------------------------------- +x2w_console_mode::Answer console_answer(std::uint32_t* mode, unsigned long* device) noexcept +{ + const DWORD saved = GetLastError(); + char text[16]{}; + const DWORD length = GetEnvironmentVariableA("X2W_DEVICE_TYPE", text, sizeof(text)); + SetLastError(saved); + char* end = nullptr; + const unsigned long value = length && length < sizeof(text) ? std::strtoul(text, &end, 0) : 0; + const bool set = length && length < sizeof(text) && end && end != text && !*end; + *device = value; + return x2w_console_mode::answer_for(set, value, mode); +} + +void note_oem_open(const char* via, LSTATUS status) noexcept +{ + static volatile LONG logged; + if (x2w_local::first_calls(logged, 4)) + x2w_local::logf("x2w-runtime console mode: %s opened the OEM key, real status %ld", via, static_cast(status)); +} + +// One line per read (the first eight): what was answered, and the real status or value when passed on. +void note_console_read(const char* via, x2w_console_mode::Answer answer, unsigned long device, std::uint32_t value, LSTATUS status) noexcept +{ + static volatile LONG logged; + if (!x2w_local::first_calls(logged, 8)) return; + if (answer == x2w_console_mode::Answer::value) + x2w_local::logf("x2w-runtime console mode: %s ConsoleMode -> 0x%x for X2W_DEVICE_TYPE=%lu, status %ld", via, value, device, + static_cast(status)); + else if (answer == x2w_console_mode::Answer::missing) + x2w_local::logf("x2w-runtime console mode: %s ConsoleMode -> missing (PC) for X2W_DEVICE_TYPE=%lu", via, device); + else if (status == ERROR_SUCCESS) + x2w_local::logf("x2w-runtime console mode: %s ConsoleMode passed through -> 0x%x", via, value); + else + x2w_local::logf("x2w-runtime console mode: %s ConsoleMode passed through -> status %ld", via, static_cast(status)); +} + +template +Fn real_reg(RegistryImport which) noexcept +{ + return reinterpret_cast(real_registry[which].load(std::memory_order_acquire)); +} + +LSTATUS WINAPI hooked_reg_open_key_ex_w(HKEY root, LPCWSTR subkey, DWORD options, REGSAM access, PHKEY out) +{ + const auto real = real_reg(reg_open_key_ex_w); + if (!real) return ERROR_PROC_NOT_FOUND; + const LSTATUS status = real(root, subkey, options, access, out); + if (root == HKEY_LOCAL_MACHINE && x2w_console_mode::is_oem_subkey(subkey)) { + note_oem_open("RegOpenKeyExW", status); + if (status == ERROR_SUCCESS && out) track_oem(*out); + } + return status; +} + +LSTATUS WINAPI hooked_reg_open_key_w(HKEY root, LPCWSTR subkey, PHKEY out) +{ + const auto real = real_reg(reg_open_key_w); + if (!real) return ERROR_PROC_NOT_FOUND; + const LSTATUS status = real(root, subkey, out); + if (root == HKEY_LOCAL_MACHINE && x2w_console_mode::is_oem_subkey(subkey)) { + note_oem_open("RegOpenKeyW", status); + if (status == ERROR_SUCCESS && out) track_oem(*out); + } + return status; +} + +std::uint32_t dword_read(LSTATUS status, const void* data, const DWORD* bytes) noexcept +{ + std::uint32_t value = 0; + if (status == ERROR_SUCCESS && data && bytes && *bytes >= sizeof(value)) std::memcpy(&value, data, sizeof(value)); + return value; +} + +LSTATUS WINAPI hooked_reg_query_value_ex_w(HKEY key, LPCWSTR name, LPDWORD reserved, LPDWORD type, LPBYTE data, LPDWORD bytes) +{ + const auto real = real_reg(reg_query_value_ex_w); + if (!x2w_console_mode::is_console_mode_value(name) || !oem_key(key)) + return real ? real(key, name, reserved, type, data, bytes) : ERROR_PROC_NOT_FOUND; + std::uint32_t mode = 0; + unsigned long device = 0; + const auto answer = console_answer(&mode, &device); + LSTATUS status = ERROR_FILE_NOT_FOUND; + if (answer == x2w_console_mode::Answer::value) + status = x2w_console_mode::fill_query(mode, reinterpret_cast(type), data, reinterpret_cast(bytes)); + else if (answer == x2w_console_mode::Answer::pass) + status = real ? real(key, name, reserved, type, data, bytes) : ERROR_PROC_NOT_FOUND; + note_console_read("RegQueryValueExW", answer, device, answer == x2w_console_mode::Answer::value ? mode : dword_read(status, data, bytes), status); + return status; +} + +LSTATUS WINAPI hooked_reg_get_value_w(HKEY key, LPCWSTR subkey, LPCWSTR name, DWORD flags, LPDWORD type, PVOID data, LPDWORD bytes) +{ + const auto real = real_reg(reg_get_value_w); + const bool oem = (key == HKEY_LOCAL_MACHINE && x2w_console_mode::is_oem_subkey(subkey)) || (oem_key(key) && (!subkey || !*subkey)); + if (!oem || !x2w_console_mode::is_console_mode_value(name)) + return real ? real(key, subkey, name, flags, type, data, bytes) : ERROR_PROC_NOT_FOUND; + std::uint32_t mode = 0; + unsigned long device = 0; + const auto answer = console_answer(&mode, &device); + LSTATUS status = ERROR_FILE_NOT_FOUND; + if (answer == x2w_console_mode::Answer::value) + status = x2w_console_mode::fill_get(flags, mode, reinterpret_cast(type), data, reinterpret_cast(bytes)); + else if (answer == x2w_console_mode::Answer::pass) + status = real ? real(key, subkey, name, flags, type, data, bytes) : ERROR_PROC_NOT_FOUND; + note_console_read("RegGetValueW", answer, device, answer == x2w_console_mode::Answer::value ? mode : dword_read(status, data, bytes), status); + return status; +} + +LSTATUS WINAPI hooked_reg_close_key(HKEY key) +{ + const auto real = real_reg(reg_close_key); + untrack_oem(key); + return real ? real(key) : ERROR_PROC_NOT_FOUND; +} + +void* const registry_hooks[registry_imports] = { + reinterpret_cast(&hooked_reg_open_key_ex_w), reinterpret_cast(&hooked_reg_open_key_w), + reinterpret_cast(&hooked_reg_query_value_ex_w), reinterpret_cast(&hooked_reg_get_value_w), + reinterpret_cast(&hooked_reg_close_key)}; + +// Keep the first real address for each import; never one of the hooks themselves. +bool remember_registry(int which, void* real) noexcept +{ + if (which < 0 || which >= registry_imports || !real) return false; + for (void* hook : registry_hooks) + if (real == hook) return false; + void* expected = nullptr; + real_registry[which].compare_exchange_strong(expected, real, std::memory_order_acq_rel); + return true; +} + +// GetProcAddress by name: the hook for a registry import, or null for any other name. +FARPROC registry_hook_for(LPCSTR name, FARPROC real) noexcept +{ + const int which = registry_import_index(name); + if (which < 0 || !remember_registry(which, reinterpret_cast(real))) return nullptr; + return reinterpret_cast(registry_hooks[which]); +} + +// Rewrite one image's regular registry IAT slots. Delay-import slots hold a thunk and are left alone. +int patch_registry_imports(unsigned char* base, std::size_t image_size) noexcept +{ + int patched = 0; + const auto classify = [](const char*, const char* name, x2w_runtime_patch::Kind* kind) { + if (registry_import_index(name) < 0) return false; + *kind = x2w_runtime_patch::Kind::registry; + return true; + }; + x2w_runtime_patch::visit_imports_with(base, image_size, classify, [&](const x2w_runtime_patch::Hit& hit) { + if (hit.delay_import) return; + const int which = registry_import_index(hit.import_name); + auto* slot = reinterpret_cast(base + hit.first_thunk_rva); + if (*slot == reinterpret_cast(registry_hooks[which])) return; + if (!remember_registry(which, reinterpret_cast(*slot))) return; + DWORD old = 0; + if (!VirtualProtect(slot, 8, PAGE_READWRITE, &old)) return; + *slot = reinterpret_cast(registry_hooks[which]); + VirtualProtect(slot, 8, old, &old); + ++patched; + }); + return patched; +} diff --git a/src/startup_stubs/runtime_gpa_patch.h b/src/startup_stubs/runtime_gpa_patch.h index e5b23da826..b9dd8a4d09 100644 --- a/src/startup_stubs/runtime_gpa_patch.h +++ b/src/startup_stubs/runtime_gpa_patch.h @@ -16,7 +16,8 @@ namespace x2w_runtime_patch { -enum class Kind : unsigned char { get_proc_address = 1, query_api_impl = 2 }; +// registry: one of the registry imports named by console_mode.h (classified by its own caller). +enum class Kind : unsigned char { get_proc_address = 1, query_api_impl = 2, registry = 3 }; struct Hit { Kind kind; @@ -113,9 +114,9 @@ inline bool c_string_in_image(const unsigned char* base, std::size_t image_size, return false; } -template +template int visit_named_thunks(const unsigned char* base, std::size_t image_size, const char* dll, std::uint32_t name_table_rva, - std::uint32_t iat_rva, bool delay_import, Fn on_hit) + std::uint32_t iat_rva, bool delay_import, Classify classify, Fn on_hit) { int hits = 0; for (std::uint32_t ti = 0;; ++ti) { @@ -139,10 +140,11 @@ int visit_named_thunks(const unsigned char* base, std::size_t image_size, const return hits; } -// Walk a PE image's import and delay-import tables. Invokes `on_hit(Hit)` for each classified import. -// Returns the number of hits. Malformed images stop the walk and return what was found. -template -int visit_imports(const unsigned char* base, std::size_t image_size, Fn on_hit) +// Walk a PE image's import and delay-import tables. Invokes `on_hit(Hit)` for each import that +// `classify(dll, name, &kind)` accepts. Returns the number of hits. Malformed images stop the walk +// and return what was found. +template +int visit_imports_with(const unsigned char* base, std::size_t image_size, Classify classify, Fn on_hit) { if (!readable_range(base, image_size, 0, sizeof(DosStub))) return 0; const auto* dos = reinterpret_cast(base); @@ -167,7 +169,7 @@ int visit_imports(const unsigned char* base, std::size_t image_size, Fn on_hit) if (!imp->name || !imp->original_first_thunk || !imp->first_thunk) continue; if (!c_string_in_image(base, image_size, imp->name)) continue; const char* dll = reinterpret_cast(base + imp->name); - hits += visit_named_thunks(base, image_size, dll, imp->original_first_thunk, imp->first_thunk, false, on_hit); + hits += visit_named_thunks(base, image_size, dll, imp->original_first_thunk, imp->first_thunk, false, classify, on_hit); } } @@ -181,10 +183,18 @@ int visit_imports(const unsigned char* base, std::size_t image_size, Fn on_hit) if (!delay->dll_name || !delay->original_first_thunk || !delay->first_thunk) continue; if (!c_string_in_image(base, image_size, delay->dll_name)) continue; const char* dll = reinterpret_cast(base + delay->dll_name); - hits += visit_named_thunks(base, image_size, dll, delay->original_first_thunk, delay->first_thunk, true, on_hit); + hits += visit_named_thunks(base, image_size, dll, delay->original_first_thunk, delay->first_thunk, true, classify, on_hit); } } return hits; } +// The runtime proxy's own imports: GetProcAddress from any module, QueryApiImpl from xgameruntime.dll. +template +int visit_imports(const unsigned char* base, std::size_t image_size, Fn on_hit) +{ + return visit_imports_with(base, image_size, [](const char* dll, const char* name, Kind* kind) { return classify(dll, name, kind); }, + on_hit); +} + } // namespace x2w_runtime_patch diff --git a/src/startup_stubs/runtime_proxy.cpp b/src/startup_stubs/runtime_proxy.cpp index 7c9a170462..3774a12203 100644 --- a/src/startup_stubs/runtime_proxy.cpp +++ b/src/startup_stubs/runtime_proxy.cpp @@ -14,6 +14,7 @@ // X2W_FAKE_USER=1 additionally answers the user API for one local user (see fake_user below) // and, while the proxy is on, XStoreCreateContext for that user (see area_call). #include "startup_stubs/api_trace.h" +#include "startup_stubs/console_mode.h" #include "startup_stubs/local_log.h" #include "startup_stubs/runtime_gpa_patch.h" #include "startup_stubs/save_blob_pack.h" @@ -484,12 +485,15 @@ bool module_is_exe_or_package_helper(HMODULE module) noexcept return true; } +#include "startup_stubs/registry_console_mode.inl" + FARPROC WINAPI hooked_get_proc_address(HMODULE module, LPCSTR name) { const FARPROC real = GetProcAddress(module, name); if (real && reinterpret_cast(name) > 0xffff) { static LONG logged; if (x2w_local::first_calls(logged, 40)) x2w_local::logf("x2w-runtime GetProcAddress(%p, \"%s\") -> %p", static_cast(module), name, static_cast(real)); + if (const FARPROC hook = registry_hook_for(name, real)) return hook; // Wrap gaming-runtime exports only when the provider module is xgameruntime.dll. if (module_is_xgameruntime(module) && std::strcmp(name, "QueryApiImpl") == 0 && remember_real_query(reinterpret_cast(real))) @@ -555,6 +559,13 @@ int patch_module(HMODULE module) } VirtualProtect(slot, 8, old, &old); }); + // Registry imports for the console mode (registry_console_mode.inl), counted on their own line. + if (!self) { + const int registry = patch_registry_imports(base, image_size); + if (registry > 0) + x2w_local::logf("x2w-runtime console mode: %d registry import(s) patched in the %s", registry, + module == GetModuleHandleW(nullptr) ? "main module" : "package module"); + } return patched; } diff --git a/tests/startup_console_mode_check.cpp b/tests/startup_console_mode_check.cpp new file mode 100644 index 0000000000..75c34c3080 --- /dev/null +++ b/tests/startup_console_mode_check.cpp @@ -0,0 +1,221 @@ +// Source-built control for console_mode.h and registry_console_mode.inl: the console mode a title +// reads from HKLM\Software\Microsoft\Windows NT\CurrentVersion\OEM (value ConsoleMode). +// +// The real registry functions are replaced by local fakes that report the value as missing (a PC), +// so no machine state is read or changed. The hooks are reached the way a title reaches them +// through GetProcAddress. Cases: unset passes the read to the fake; 6 and 7 answer 0x60 and 0x64 +// without calling it; 1 answers missing; other keys, values and closed handles pass through. +// --control leaves X2W_DEVICE_TYPE unset for the answered cases, which must print FAIL. +#include + +#include +#include +#include +#include +#include + +#include "startup_stubs/console_mode.h" +#include "startup_stubs/local_log.h" +#include "startup_stubs/runtime_gpa_patch.h" + +namespace x2w_local { +std::string fixture_log; +void fixture_logf(const char* format, ...) +{ + char line[512]; + va_list args; + va_start(args, format); + std::vsnprintf(line, sizeof(line), format, args); + va_end(args); + fixture_log += line; + fixture_log += '\n'; +} +} // namespace x2w_local + +#define logf fixture_logf +namespace { +#include "../src/startup_stubs/registry_console_mode.inl" +} +#undef logf + +namespace { +int failures; +bool control; + +void check(const char* what, bool ok) +{ + if (!ok) { + std::printf("FAIL: %s\n", what); + ++failures; + } +} + +HKEY const fake_oem = reinterpret_cast(0x5100); +HKEY const fake_other = reinterpret_cast(0x5200); +int real_queries, real_gets, real_closes; + +LSTATUS WINAPI fake_open_ex(HKEY root, LPCWSTR subkey, DWORD, REGSAM, PHKEY out) +{ + if (root != HKEY_LOCAL_MACHINE || !out) return ERROR_FILE_NOT_FOUND; + *out = x2w_console_mode::is_oem_subkey(subkey) ? fake_oem : fake_other; + return ERROR_SUCCESS; +} +LSTATUS WINAPI fake_open(HKEY root, LPCWSTR subkey, PHKEY out) { return fake_open_ex(root, subkey, 0, 0, out); } +LSTATUS WINAPI fake_query(HKEY, LPCWSTR, LPDWORD, LPDWORD, LPBYTE, LPDWORD) +{ + ++real_queries; + return ERROR_FILE_NOT_FOUND; // as on a PC: the value is absent +} +LSTATUS WINAPI fake_get(HKEY, LPCWSTR, LPCWSTR, DWORD, LPDWORD, PVOID, LPDWORD) +{ + ++real_gets; + return ERROR_FILE_NOT_FOUND; +} +LSTATUS WINAPI fake_close(HKEY) +{ + ++real_closes; + return ERROR_SUCCESS; +} + +template +Fn hook(const char* name, Fn fake) +{ + return reinterpret_cast(registry_hook_for(name, reinterpret_cast(fake))); +} + +void device(const char* value, bool answered_case) +{ + // In the control the answered cases run without the switch, so their checks must fail. + if (!value || (control && answered_case)) + SetEnvironmentVariableA("X2W_DEVICE_TYPE", nullptr); + else + SetEnvironmentVariableA("X2W_DEVICE_TYPE", value); +} + +void pure_checks() +{ + using namespace x2w_console_mode; + check("OEM subkey", is_oem_subkey(L"Software\\Microsoft\\Windows NT\\CurrentVersion\\OEM")); + check("OEM subkey in capitals", is_oem_subkey(L"SOFTWARE\\MICROSOFT\\WINDOWS NT\\CURRENTVERSION\\OEM")); + check("OEM subkey with a leading and a trailing backslash", + is_oem_subkey(L"\\Software\\Microsoft\\Windows NT\\CurrentVersion\\OEM\\")); + check("a longer subkey is not the OEM key", !is_oem_subkey(L"Software\\Microsoft\\Windows NT\\CurrentVersion\\OEMx")); + check("a child of the OEM key is not the OEM key", !is_oem_subkey(L"Software\\Microsoft\\Windows NT\\CurrentVersion\\OEM\\a")); + check("a parent is not the OEM key", !is_oem_subkey(L"Software\\Microsoft\\Windows NT\\CurrentVersion")); + check("null subkey", !is_oem_subkey(nullptr)); + check("value name ignores case", is_console_mode_value(L"consolemode")); + check("other value name", !is_console_mode_value(L"ConsoleModeX")); + + std::uint32_t mode = 0; + check("unset passes", answer_for(false, 7, &mode) == Answer::pass); + check("6 is Series S", answer_for(true, 6, &mode) == Answer::value && mode == series_s); + check("7 is Series X", answer_for(true, 7, &mode) == Answer::value && mode == series_x); + check("1 is missing", answer_for(true, 1, &mode) == Answer::missing); + check("8 is passed on", answer_for(true, 8, &mode) == Answer::pass); + + unsigned long type = 0, bytes = 0; + unsigned char data[8] = {}; + check("size query", fill_query(series_x, &type, nullptr, &bytes) == status_ok && bytes == 4 && type == type_dword); + bytes = 3; + check("short buffer", fill_query(series_x, &type, data, &bytes) == status_more_data && bytes == 4 && data[0] == 0); + check("data without size", fill_query(series_x, &type, data, nullptr) == status_invalid); + bytes = sizeof(data); + check("value written", fill_query(series_x, &type, data, &bytes) == status_ok && bytes == 4 && data[0] == 0x64 && data[1] == 0); + bytes = sizeof(data); + check("RegGetValue refuses a string-only request", fill_get(0x2 /* RRF_RT_REG_SZ */, series_s, &type, data, &bytes) == status_wrong_type); + bytes = sizeof(data); + check("RegGetValue with RRF_RT_DWORD", fill_get(0x18, series_s, &type, data, &bytes) == status_ok && data[0] == 0x60); +} + +DWORD query(RegQueryValueExWFn query_fn, HKEY key, const wchar_t* name, LSTATUS* status) +{ + DWORD type = 0, value = 0xffffffff, bytes = sizeof(value); + *status = query_fn(key, name, nullptr, &type, reinterpret_cast(&value), &bytes); + return value; +} + +void hook_checks() +{ + const auto open_ex = hook("RegOpenKeyExW", &fake_open_ex); + const auto open = hook("RegOpenKeyW", &fake_open); + const auto query_fn = hook("RegQueryValueExW", &fake_query); + const auto get = hook("RegGetValueW", &fake_get); + const auto close = hook("RegCloseKey", &fake_close); + check("every registry name has a hook", open_ex && open && query_fn && get && close); + if (!(open_ex && open && query_fn && get && close)) return; + check("other names have no hook", !registry_hook_for("RegSetValueExW", reinterpret_cast(&fake_close))); + check("a hook is never kept as the real function", !registry_hook_for("RegCloseKey", reinterpret_cast(close))); + + const wchar_t* oem_path = L"Software\\Microsoft\\Windows NT\\CurrentVersion\\OEM"; + HKEY key = nullptr, other = nullptr; + check("OEM key opens through the hook", open_ex(HKEY_LOCAL_MACHINE, oem_path, 0, KEY_READ, &key) == ERROR_SUCCESS && key == fake_oem); + check("other key opens through the hook", open_ex(HKEY_LOCAL_MACHINE, L"Software\\Other", 0, KEY_READ, &other) == ERROR_SUCCESS); + + LSTATUS status = 0; + device(nullptr, false); + int before = real_queries; + query(query_fn, key, L"ConsoleMode", &status); + check("unset: the read reaches the registry", real_queries == before + 1 && status == ERROR_FILE_NOT_FOUND); + + device("6", true); + before = real_queries; + DWORD value = query(query_fn, key, L"ConsoleMode", &status); + check("6: Series S answered locally", status == ERROR_SUCCESS && value == 0x60 && real_queries == before); + + device("7", true); + value = query(query_fn, key, L"ConsoleMode", &status); + check("7: Series X answered locally", status == ERROR_SUCCESS && value == 0x64 && real_queries == before); + + DWORD type = 0, bytes = 0; + status = query_fn(key, L"ConsoleMode", nullptr, &type, nullptr, &bytes); + check("7: size query", status == ERROR_SUCCESS && bytes == 4 && type == REG_DWORD); + + DWORD got = 0, got_bytes = sizeof(got); + before = real_gets; + status = get(HKEY_LOCAL_MACHINE, oem_path, L"ConsoleMode", RRF_RT_REG_DWORD, &type, &got, &got_bytes); + check("7: RegGetValueW by path answered locally", status == ERROR_SUCCESS && got == 0x64 && real_gets == before); + + device("1", false); + before = real_queries; + query(query_fn, key, L"ConsoleMode", &status); + check("1: missing, as on a PC", status == ERROR_FILE_NOT_FOUND && real_queries == before); + + device("7", false); + before = real_queries; + query(query_fn, key, L"OtherValue", &status); + check("7: another value passes through", real_queries == before + 1); + query(query_fn, other, L"ConsoleMode", &status); + check("7: ConsoleMode under another key passes through", real_queries == before + 2); + device("not-a-number", false); + query(query_fn, key, L"ConsoleMode", &status); + check("a value that is not a number passes through", real_queries == before + 3); + + HKEY second = nullptr; + device("7", true); + check("RegOpenKeyW opens the OEM key", open(HKEY_LOCAL_MACHINE, oem_path, &second) == ERROR_SUCCESS && second == fake_oem); + check("RegCloseKey reaches the registry", close(key) == ERROR_SUCCESS && real_closes == 1); + device("7", false); + before = real_queries; + query(query_fn, key, L"ConsoleMode", &status); + check("a closed OEM handle passes through", real_queries == before + 1); + + device(nullptr, false); + const std::string& log = x2w_local::fixture_log; + check("open is logged", log.find("RegOpenKeyExW opened the OEM key, real status 0") != std::string::npos); + check("pass-through is logged", log.find("RegQueryValueExW ConsoleMode passed through -> status 2") != std::string::npos); + check("answer is logged", log.find("ConsoleMode -> 0x64 for X2W_DEVICE_TYPE=7") != std::string::npos); +} +} // namespace + +int main(int argc, char** argv) +{ + control = argc > 1 && std::strcmp(argv[1], "--control") == 0; + pure_checks(); + hook_checks(); + if (failures) { + std::printf("startup_console_mode: FAIL (%d)\n", failures); + return 1; + } + std::puts("startup_console_mode: ok"); + return 0; +} From 0ac58f7bb89f0a71ea4e99b14bf3b46c04684c5a Mon Sep 17 00:00:00 2001 From: lewisalex86 Date: Thu, 26 Nov 2026 01:06:24 +0000 Subject: [PATCH 2/2] runtime: hook registry imports only from the Windows registry providers Both console-mode routes matched the import name alone, so a package DLL exporting RegQueryValueExW or RegOpenKeyExW could be hooked and, because the first address is kept, become the registry later calls reach. The IAT route now needs the import DLL to be advapi32.dll, kernelbase.dll, kernel32.dll or an api-ms-win-core-registry-* API set, and the bound address to lie in the system-directory copy of one of those modules. The GetProcAddress route needs the module to be one of them. Only addresses inside them are remembered as the real function. startup_console_mode loads a source-built decoy DLL with the same export names and a distinct result. With X2W_DEVICE_TYPE unset and set, its GetProcAddress lookups and synthetic IAT entries naming it (or naming advapi32.dll but bound to it) stay untouched, and the hooks still reach the fake registry. startup_console_mode_provider_control matches by name alone and must fail. startup_runtime_proxy_scope checks the same through the real loader against advapi32.dll. A full 16-entry OEM handle table is now logged once. --- CMakeLists.txt | 18 +- docs/startup-runtime.md | 16 +- src/startup_stubs/registry_console_mode.inl | 103 +++++++++- src/startup_stubs/runtime_proxy.cpp | 3 +- tests/startup_console_mode_check.cpp | 196 +++++++++++++++++++- tests/startup_console_mode_decoy.cpp | 28 +++ tests/startup_console_mode_decoy.def | 5 + tests/startup_runtime_proxy_scope/decoy.cpp | 13 +- tests/startup_runtime_proxy_scope/decoy.def | 2 + tests/startup_runtime_proxy_scope/host.cpp | 37 +++- 10 files changed, 397 insertions(+), 24 deletions(-) create mode 100644 tests/startup_console_mode_decoy.cpp create mode 100644 tests/startup_console_mode_decoy.def diff --git a/CMakeLists.txt b/CMakeLists.txt index 7557485c2c..ab8eaa1ba6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1056,13 +1056,23 @@ add_test(NAME startup_runtime_gpa_patch COMMAND startup_runtime_gpa_patch) add_test(NAME startup_runtime_gpa_patch_name_only_control COMMAND startup_runtime_gpa_patch --mutate name-only) set_tests_properties(startup_runtime_gpa_patch_name_only_control PROPERTIES PASS_REGULAR_EXPRESSION "FAIL: ") # X2W_DEVICE_TYPE: the OEM ConsoleMode registry read, answered or passed on, against fake registry -# functions. The control leaves the switch unset for the answered cases and must FAIL. +# functions. A source-built decoy DLL exports the same registry names and must stay unhooked. The +# control leaves the switch unset for the answered cases; the provider control matches registry +# imports by name alone. Both must FAIL. +add_library(startup_console_mode_decoy SHARED + tests/startup_console_mode_decoy.cpp + tests/startup_console_mode_decoy.def) +target_compile_features(startup_console_mode_decoy PRIVATE cxx_std_17) add_executable(startup_console_mode tests/startup_console_mode_check.cpp) target_include_directories(startup_console_mode PRIVATE src) target_compile_features(startup_console_mode PRIVATE cxx_std_17) -add_test(NAME startup_console_mode COMMAND startup_console_mode) -add_test(NAME startup_console_mode_control COMMAND startup_console_mode --control) -set_tests_properties(startup_console_mode_control PROPERTIES PASS_REGULAR_EXPRESSION "FAIL: ") +add_dependencies(startup_console_mode startup_console_mode_decoy) +add_test(NAME startup_console_mode COMMAND startup_console_mode --decoy "$") +add_test(NAME startup_console_mode_control + COMMAND startup_console_mode --control --decoy "$") +add_test(NAME startup_console_mode_provider_control + COMMAND startup_console_mode --control provider --decoy "$") +set_tests_properties(startup_console_mode_control startup_console_mode_provider_control PROPERTIES PASS_REGULAR_EXPRESSION "FAIL: ") # EXE + late-loaded package helper through the real Windows loader: proxied xgameruntime QueryApiImpl, # unrelated same-named export stays original. Notification only enqueues; rewrite runs after link. if (WIN32) diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 603e68384a..972f564a4f 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1395,10 +1395,18 @@ For a read-only census of cached shader refusals, use `python -B tools/startup/g (`src/startup_stubs/console_mode.h`, `registry_console_mode.inl`): with `X2W_RUNTIME_PROXY=1` the stand-in rewrites the registry imports of the EXE and package helpers. `6` answers 0x60 (Series S), `7` answers 0x64 (Series X) and `1` reports the value missing (PC); unset, every call goes to the real -registry. Opening the key and reading the value are logged a few times either way. What the values -mean on the console is taken from public notes, not measured here. -`ctest --preset dev --no-tests=error -R '^startup_console_mode(_control)?$'` runs it against fake -registry functions; the control leaves the switch unset for the answered cases and must print `FAIL:`. +registry. Only registry imports that the Windows registry provides are rewritten: an IAT entry must +name `advapi32.dll`, `kernelbase.dll`, `kernel32.dll` or an `api-ms-win-core-registry-*` API set and be +bound inside the system-directory copy of the first three, and `GetProcAddress` must be called on one +of those modules. A package DLL that exports the same names keeps its own exports and is never kept as +the real registry. Opening the key and reading the value are logged a few times either way, and a +seventeenth OEM key handle open at once is logged once and not tracked. What the values mean on the +console is taken from public notes, not measured here. +`ctest --preset dev --no-tests=error -R '^startup_console_mode(_control|_provider_control)?$'` runs it +against fake registry functions and a source-built decoy DLL with the same export names, with the switch +unset and set. The control leaves the switch unset for the answered cases and the provider control +matches registry imports by name alone; both must print `FAIL:`. `startup_runtime_proxy_scope` checks the +same decoy rule through the real loader against `advapi32.dll`. The switch changes only what the registry reads answer. A title can take a different start-up path for each profile: on the Series S profile, one loaded an upscaler package module that the other diff --git a/src/startup_stubs/registry_console_mode.inl b/src/startup_stubs/registry_console_mode.inl index c0c95d96f7..7af9b49aea 100644 --- a/src/startup_stubs/registry_console_mode.inl +++ b/src/startup_stubs/registry_console_mode.inl @@ -4,7 +4,8 @@ // runtime_gpa_patch.h and console_mode.h. // // With X2W_RUNTIME_PROXY the stand-in rewrites five registry imports of the EXE and package helpers -// (regular IAT and GetProcAddress by name). Every call goes to the real function except a read of +// (regular IAT and GetProcAddress by name), only where the Windows registry provides them: see +// registry_provider_module below. Every call goes to the real function except a read of // ConsoleMode under HKLM\...\OEM while X2W_DEVICE_TYPE names a known console. Opening the OEM // key and reading the value are logged a few times in either case, so a run shows whether the // title asks at all. @@ -28,20 +29,102 @@ int registry_import_index(const char* name) noexcept return -1; } +// ---- which modules are the Windows registry ----------------------------------------------------- +// A package DLL can export the same names. Only these system modules count as the registry, for the +// GetProcAddress module, for the module that holds a bound IAT address and for what is remembered +// as the real function. The api-ms-win-core-registry API sets resolve to kernelbase.dll. +constexpr const wchar_t* registry_provider_names[] = {L"advapi32.dll", L"kernelbase.dll", L"kernel32.dll"}; + +#if defined(X2W_CONSOLE_MODE_FIXTURE) +// tests/startup_console_mode_check.cpp keeps its fake registry in the test EXE, which counts as one +// more provider there. Its provider control sets registry_any_provider (name-only matching), which +// the decoy checks must catch. +bool registry_any_provider; +bool fixture_registry_provider(HMODULE module) noexcept { return module == GetModuleHandleW(nullptr); } +#else +constexpr bool registry_any_provider = false; +constexpr bool fixture_registry_provider(HMODULE) noexcept { return false; } +#endif + +// The loaded system-directory copy of a provider, by full path, so a same-named DLL elsewhere does not match. +bool registry_provider_module(HMODULE module) noexcept +{ + if (registry_any_provider) return true; + if (!module) return false; + if (fixture_registry_provider(module)) return true; + const DWORD saved = GetLastError(); + wchar_t path[MAX_PATH]{}; + const UINT length = GetSystemDirectoryW(path, MAX_PATH); + bool found = false; + for (const wchar_t* name : registry_provider_names) { + if (found || !length || length >= MAX_PATH) break; + std::size_t at = length, i = 0; + path[at++] = L'\\'; + for (; name[i] && at + 1 < MAX_PATH; ++i) path[at++] = name[i]; + if (name[i]) break; + path[at] = 0; + found = GetModuleHandleW(path) == module; + } + SetLastError(saved); + return found; +} + +bool registry_provider_address(const void* address) noexcept +{ + if (registry_any_provider) return true; + const DWORD saved = GetLastError(); + HMODULE module = nullptr; + const bool known = address && GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + static_cast(address), &module); + SetLastError(saved); + return known && registry_provider_module(module); +} + +// Import DLL names (any case) that supply the registry: the providers above and the +// api-ms-win-core-registry-* API sets. +bool registry_provider_dll(const char* dll) noexcept +{ + if (registry_any_provider) return true; + if (!dll) return false; + const auto lower = [](char c) { return (c >= 'A' && c <= 'Z') ? static_cast(c - 'A' + 'a') : c; }; + const auto equal = [&](const char* expect) { + std::size_t i = 0; + for (; expect[i]; ++i) + if (lower(dll[i]) != expect[i]) return false; + return dll[i] == 0; + }; + if (equal("advapi32.dll") || equal("kernelbase.dll") || equal("kernel32.dll")) return true; + static constexpr char api_set[] = "api-ms-win-core-registry-"; + for (std::size_t i = 0; api_set[i]; ++i) + if (lower(dll[i]) != api_set[i]) return false; + return true; +} + // ---- OEM key handles the title opened ----------------------------------------------------------- SRWLOCK oem_lock = SRWLOCK_INIT; HKEY oem_keys[16]; +void note_oem_table_full() noexcept +{ + static volatile LONG logged; + if (x2w_local::first_calls(logged, 1)) + x2w_local::logf("x2w-runtime console mode: %u OEM key handles already open, another is not tracked", + static_cast(sizeof(oem_keys) / sizeof(oem_keys[0]))); +} + void track_oem(HKEY key) noexcept { AcquireSRWLockExclusive(&oem_lock); + bool tracked = false; for (HKEY& slot : oem_keys) { if (!slot) { slot = key; + tracked = true; break; } } ReleaseSRWLockExclusive(&oem_lock); + if (!tracked) note_oem_table_full(); } bool oem_key(HKEY key) noexcept @@ -183,31 +266,35 @@ void* const registry_hooks[registry_imports] = { reinterpret_cast(&hooked_reg_query_value_ex_w), reinterpret_cast(&hooked_reg_get_value_w), reinterpret_cast(&hooked_reg_close_key)}; -// Keep the first real address for each import; never one of the hooks themselves. +// Keep the first real address for each import: one inside a registry provider, never one of the +// hooks themselves. bool remember_registry(int which, void* real) noexcept { if (which < 0 || which >= registry_imports || !real) return false; for (void* hook : registry_hooks) if (real == hook) return false; + if (!registry_provider_address(real)) return false; void* expected = nullptr; real_registry[which].compare_exchange_strong(expected, real, std::memory_order_acq_rel); return true; } -// GetProcAddress by name: the hook for a registry import, or null for any other name. -FARPROC registry_hook_for(LPCSTR name, FARPROC real) noexcept +// GetProcAddress by name: the hook for a registry import looked up on a registry provider, or null +// for any other name or module. +FARPROC registry_hook_for(HMODULE module, LPCSTR name, FARPROC real) noexcept { const int which = registry_import_index(name); - if (which < 0 || !remember_registry(which, reinterpret_cast(real))) return nullptr; + if (which < 0 || !registry_provider_module(module) || !remember_registry(which, reinterpret_cast(real))) return nullptr; return reinterpret_cast(registry_hooks[which]); } -// Rewrite one image's regular registry IAT slots. Delay-import slots hold a thunk and are left alone. +// Rewrite one image's regular registry IAT slots that import from a registry provider and are bound +// inside one. Delay-import slots hold a thunk and are left alone. int patch_registry_imports(unsigned char* base, std::size_t image_size) noexcept { int patched = 0; - const auto classify = [](const char*, const char* name, x2w_runtime_patch::Kind* kind) { - if (registry_import_index(name) < 0) return false; + const auto classify = [](const char* dll, const char* name, x2w_runtime_patch::Kind* kind) { + if (registry_import_index(name) < 0 || !registry_provider_dll(dll)) return false; *kind = x2w_runtime_patch::Kind::registry; return true; }; diff --git a/src/startup_stubs/runtime_proxy.cpp b/src/startup_stubs/runtime_proxy.cpp index 3774a12203..1f0e7890af 100644 --- a/src/startup_stubs/runtime_proxy.cpp +++ b/src/startup_stubs/runtime_proxy.cpp @@ -493,7 +493,8 @@ FARPROC WINAPI hooked_get_proc_address(HMODULE module, LPCSTR name) if (real && reinterpret_cast(name) > 0xffff) { static LONG logged; if (x2w_local::first_calls(logged, 40)) x2w_local::logf("x2w-runtime GetProcAddress(%p, \"%s\") -> %p", static_cast(module), name, static_cast(real)); - if (const FARPROC hook = registry_hook_for(name, real)) return hook; + // Registry exports only when the module is a Windows registry provider (registry_console_mode.inl). + if (const FARPROC hook = registry_hook_for(module, name, real)) return hook; // Wrap gaming-runtime exports only when the provider module is xgameruntime.dll. if (module_is_xgameruntime(module) && std::strcmp(name, "QueryApiImpl") == 0 && remember_real_query(reinterpret_cast(real))) diff --git a/tests/startup_console_mode_check.cpp b/tests/startup_console_mode_check.cpp index 75c34c3080..79a8bde242 100644 --- a/tests/startup_console_mode_check.cpp +++ b/tests/startup_console_mode_check.cpp @@ -6,6 +6,14 @@ // through GetProcAddress. Cases: unset passes the read to the fake; 6 and 7 answer 0x60 and 0x64 // without calling it; 1 answers missing; other keys, values and closed handles pass through. // --control leaves X2W_DEVICE_TYPE unset for the answered cases, which must print FAIL. +// +// The fake registry lives in this EXE, which X2W_CONSOLE_MODE_FIXTURE counts as a registry +// provider. --decoy loads a source-built DLL that exports RegOpenKeyExW and RegQueryValueExW +// with a distinct result. With the switch unset and set, neither GetProcAddress on the decoy nor a +// synthetic IAT entry naming it (or naming advapi32.dll but bound to the decoy) may be hooked or +// remembered, and the hooks must still reach the fake registry. --control provider matches +// registry imports by name alone, which must print FAIL. +#define X2W_CONSOLE_MODE_FIXTURE 1 #include #include @@ -13,6 +21,8 @@ #include #include #include +#include +#include #include "startup_stubs/console_mode.h" #include "startup_stubs/local_log.h" @@ -77,10 +87,11 @@ LSTATUS WINAPI fake_close(HKEY) return ERROR_SUCCESS; } +// The fakes live in this EXE, the fixture's registry provider. template Fn hook(const char* name, Fn fake) { - return reinterpret_cast(registry_hook_for(name, reinterpret_cast(fake))); + return reinterpret_cast(registry_hook_for(GetModuleHandleW(nullptr), name, reinterpret_cast(fake))); } void device(const char* value, bool answered_case) @@ -143,8 +154,9 @@ void hook_checks() const auto close = hook("RegCloseKey", &fake_close); check("every registry name has a hook", open_ex && open && query_fn && get && close); if (!(open_ex && open && query_fn && get && close)) return; - check("other names have no hook", !registry_hook_for("RegSetValueExW", reinterpret_cast(&fake_close))); - check("a hook is never kept as the real function", !registry_hook_for("RegCloseKey", reinterpret_cast(close))); + const HMODULE exe = GetModuleHandleW(nullptr); + check("other names have no hook", !registry_hook_for(exe, "RegSetValueExW", reinterpret_cast(&fake_close))); + check("a hook is never kept as the real function", !registry_hook_for(exe, "RegCloseKey", reinterpret_cast(close))); const wchar_t* oem_path = L"Software\\Microsoft\\Windows NT\\CurrentVersion\\OEM"; HKEY key = nullptr, other = nullptr; @@ -199,18 +211,194 @@ void hook_checks() query(query_fn, key, L"ConsoleMode", &status); check("a closed OEM handle passes through", real_queries == before + 1); + // A full table of OEM handles: one more open is logged once and not tracked. + const char* full_line = "OEM key handles already open, another is not tracked"; + check("no full-table line before the table fills", x2w_local::fixture_log.find(full_line) == std::string::npos); + HKEY extra = nullptr; + for (int i = 0; i < 17; ++i) open_ex(HKEY_LOCAL_MACHINE, oem_path, 0, KEY_READ, &extra); + const std::size_t full_at = x2w_local::fixture_log.find(full_line); + check("a full OEM handle table is logged", full_at != std::string::npos); + check("the full-table line is logged once", full_at != std::string::npos && + x2w_local::fixture_log.find(full_line, full_at + 1) == std::string::npos); + close(second); + check("closing the OEM handle empties the table", !oem_key(fake_oem)); + device(nullptr, false); const std::string& log = x2w_local::fixture_log; check("open is logged", log.find("RegOpenKeyExW opened the OEM key, real status 0") != std::string::npos); check("pass-through is logged", log.find("RegQueryValueExW ConsoleMode passed through -> status 2") != std::string::npos); check("answer is logged", log.find("ConsoleMode -> 0x64 for X2W_DEVICE_TYPE=7") != std::string::npos); } + +// ---- a package DLL with the same export names ----------------------------------------------------- +constexpr LSTATUS decoy_status = 0x5EC0; // startup_console_mode_decoy.cpp + +struct Import { + const char* name; + void* bound; +}; +struct ImportDll { + const char* dll; + std::vector imports; +}; + +// Synthetic PE32+ image with one regular import descriptor per entry, each slot already bound. +std::vector build_image(const std::vector& dlls, std::vector>* slots) +{ + namespace patch = x2w_runtime_patch; + std::vector image(0x1000, 0); + auto* dos = reinterpret_cast(image.data()); + dos->e_magic = 0x5A4D; + dos->e_lfanew = 0x80; + auto* nt = image.data() + 0x80; + *reinterpret_cast(nt) = 0x00004550; + *reinterpret_cast(nt + 24) = 0x20B; + auto* dirs = reinterpret_cast(nt + 24 + 112); + dirs[1].virtual_address = 0x200; + dirs[1].size = static_cast(sizeof(patch::ImportDesc) * (dlls.size() + 1)); + std::uint32_t next = 0x400; + const auto take = [&](std::size_t bytes) { + const std::uint32_t at = next; + next = static_cast((next + bytes + 7) & ~std::size_t{7}); + return at; + }; + slots->clear(); + for (std::size_t d = 0; d < dlls.size(); ++d) { + auto* imp = reinterpret_cast(image.data() + 0x200) + d; + const std::size_t count = dlls[d].imports.size(); + imp->original_first_thunk = take(8 * (count + 1)); + imp->first_thunk = take(8 * (count + 1)); + imp->name = take(std::strlen(dlls[d].dll) + 1); + std::memcpy(image.data() + imp->name, dlls[d].dll, std::strlen(dlls[d].dll) + 1); + slots->emplace_back(); + for (std::size_t i = 0; i < count; ++i) { + const char* name = dlls[d].imports[i].name; + const std::uint32_t hint = take(2 + std::strlen(name) + 1); + std::memcpy(image.data() + hint + 2, name, std::strlen(name) + 1); + reinterpret_cast(image.data() + imp->original_first_thunk)[i].value = hint; + reinterpret_cast(image.data() + imp->first_thunk)[i].value = + reinterpret_cast(dlls[d].imports[i].bound); + slots->back().push_back(imp->first_thunk + static_cast(8 * i)); + } + } + return image; +} + +// What hooked_get_proc_address returns: the hook for a registry provider, else the real export. +FARPROC resolve(HMODULE module, const char* name) +{ + const FARPROC real = GetProcAddress(module, name); + const FARPROC hooked = real ? registry_hook_for(module, name, real) : nullptr; + return hooked ? hooked : real; +} + +void* remembered(RegistryImport which) { return real_registry[which].load(); } + +void decoy_checks(HMODULE decoy, const char* pass) +{ + using SeenFn = LONG(WINAPI*)(); + const auto seen = reinterpret_cast(GetProcAddress(decoy, "decoy_calls")); + void* const decoy_open = reinterpret_cast(GetProcAddress(decoy, "RegOpenKeyExW")); + void* const decoy_query = reinterpret_cast(GetProcAddress(decoy, "RegQueryValueExW")); + const std::string label = std::string(pass) + ": "; + const auto say = [&](const char* what, bool ok) { check((label + what).c_str(), ok); }; + say("the decoy exports both registry names", seen && decoy_open && decoy_query); + if (!(seen && decoy_open && decoy_query)) return; + + // GetProcAddress on the decoy: its own exports, which keep their own result. + const auto open_fn = reinterpret_cast(resolve(decoy, "RegOpenKeyExW")); + const auto query_fn = reinterpret_cast(resolve(decoy, "RegQueryValueExW")); + say("GetProcAddress(decoy, RegOpenKeyExW) is the decoy's export", reinterpret_cast(open_fn) == decoy_open); + say("GetProcAddress(decoy, RegQueryValueExW) is the decoy's export", reinterpret_cast(query_fn) == decoy_query); + LONG before = seen(); + HKEY out = nullptr; + LSTATUS status = 0; + query(query_fn, fake_other, L"ConsoleMode", &status); + say("the decoy's RegQueryValueExW answers its own result", status == decoy_status && seen() == before + 1); + say("the decoy's RegOpenKeyExW answers its own result", + open_fn(HKEY_LOCAL_MACHINE, L"Software\\Microsoft\\Windows NT\\CurrentVersion\\OEM", 0, KEY_READ, &out) == decoy_status && + seen() == before + 2); + say("a decoy address is refused under the provider module", + !registry_hook_for(GetModuleHandleW(nullptr), "RegQueryValueExW", reinterpret_cast(decoy_query))); + + // A synthetic IAT: the decoy by name, advapi32.dll by name but bound to the decoy, and + // advapi32.dll bound to the fake registry (the one entry that is rewritten). + std::vector> slots; + auto image = build_image({{"startup_console_mode_decoy.dll", {{"RegOpenKeyExW", decoy_open}, {"RegQueryValueExW", decoy_query}}}, + {"ADVAPI32.dll", {{"RegQueryValueExW", decoy_query}}}, + {"advapi32.dll", {{"RegQueryValueExW", reinterpret_cast(&fake_query)}, + {"RegCloseKey", reinterpret_cast(&fake_close)}}}}, + &slots); + const auto slot = [&](std::size_t d, std::size_t i) { return *reinterpret_cast(image.data() + slots[d][i]); }; + const int patched = patch_registry_imports(image.data(), image.size()); + say("only the provider-bound imports are rewritten", patched == 2); + say("the decoy's RegOpenKeyExW slot is untouched", slot(0, 0) == decoy_open); + say("the decoy's RegQueryValueExW slot is untouched", slot(0, 1) == decoy_query); + say("advapi32.dll bound to the decoy is untouched", slot(1, 0) == decoy_query); + say("advapi32.dll bound to the registry is rewritten", + slot(2, 0) == registry_hooks[reg_query_value_ex_w] && slot(2, 1) == registry_hooks[reg_close_key]); + before = seen(); + query(reinterpret_cast(slot(0, 1)), fake_other, L"ConsoleMode", &status); + say("a call through the decoy's slot reaches the decoy", status == decoy_status && seen() == before + 1); + + // Neither route made the decoy the real registry: the hooks still reach the fake registry. + say("the decoy's RegOpenKeyExW is never remembered", remembered(reg_open_key_ex_w) != decoy_open); + say("the decoy's RegQueryValueExW is never remembered", + remembered(reg_query_value_ex_w) != decoy_query && remembered(reg_query_value_ex_w) == reinterpret_cast(&fake_query)); + before = seen(); + const int real_before = real_queries; + query(reinterpret_cast(registry_hooks[reg_query_value_ex_w]), fake_other, L"ConsoleMode", &status); + say("the hook still reaches the registry, not the decoy", + status == ERROR_FILE_NOT_FOUND && real_queries == real_before + 1 && seen() == before); +} + +void provider_checks(HMODULE decoy) +{ + const HMODULE advapi = LoadLibraryW(L"advapi32.dll"); // this EXE does not import it + check("advapi32.dll is a registry provider", registry_provider_module(advapi)); + check("kernelbase.dll is a registry provider", registry_provider_module(GetModuleHandleW(L"kernelbase.dll"))); + check("advapi32.dll's RegQueryValueExW lies in a provider", + advapi && registry_provider_address(reinterpret_cast(GetProcAddress(advapi, "RegQueryValueExW")))); + check("the decoy is not a registry provider", decoy && !registry_provider_module(decoy)); + check("import names: advapi32.dll in any case", registry_provider_dll("ADVAPI32.dll")); + check("import names: the registry API set", registry_provider_dll("api-ms-win-core-registry-l1-1-0.dll")); + check("import names: kernelbase.dll", registry_provider_dll("KernelBase.dll")); + check("import names: the decoy is refused", !registry_provider_dll("startup_console_mode_decoy.dll")); + check("import names: a longer name is refused", !registry_provider_dll("advapi32.dll.x")); + check("import names: another API set is refused", !registry_provider_dll("api-ms-win-core-file-l1-1-0.dll")); +} } // namespace int main(int argc, char** argv) { - control = argc > 1 && std::strcmp(argv[1], "--control") == 0; + const char* decoy_path = nullptr; + for (int i = 1; i < argc; ++i) { + if (std::strcmp(argv[i], "--control") == 0) { + if (i + 1 < argc && std::strcmp(argv[i + 1], "provider") == 0) { + registry_any_provider = true; // name-only matching; the decoy checks must fail + ++i; + } else { + control = true; + } + } else if (std::strcmp(argv[i], "--decoy") == 0 && i + 1 < argc) { + decoy_path = argv[++i]; + } + } pure_checks(); + std::string decoy_file = decoy_path ? decoy_path : ""; + for (char& c : decoy_file) + if (c == '/') c = '\\'; + const HMODULE decoy = decoy_path ? LoadLibraryA(decoy_file.c_str()) : nullptr; + check("load the decoy DLL (--decoy)", decoy != nullptr); + if (!registry_any_provider) provider_checks(decoy); + // Before hook_checks registers the fake registry, so a name-only match would keep the decoy first. + if (decoy) { + SetEnvironmentVariableA("X2W_DEVICE_TYPE", nullptr); + decoy_checks(decoy, "decoy, switch unset"); + SetEnvironmentVariableA("X2W_DEVICE_TYPE", "7"); + decoy_checks(decoy, "decoy, X2W_DEVICE_TYPE=7"); + SetEnvironmentVariableA("X2W_DEVICE_TYPE", nullptr); + } hook_checks(); if (failures) { std::printf("startup_console_mode: FAIL (%d)\n", failures); diff --git a/tests/startup_console_mode_decoy.cpp b/tests/startup_console_mode_decoy.cpp new file mode 100644 index 0000000000..d0fa5f6770 --- /dev/null +++ b/tests/startup_console_mode_decoy.cpp @@ -0,0 +1,28 @@ +// Source-built package-style DLL for startup_console_mode: exports RegOpenKeyExW and +// RegQueryValueExW under the registry names (startup_console_mode_decoy.def) with a result no +// registry returns. The console-mode hooks must leave it alone: neither route may hook it or keep +// its address as the real registry function. +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#include + +namespace { +LONG calls; +constexpr LONG decoy_status = 0x5EC0; +} + +extern "C" LONG WINAPI decoy_calls() { return InterlockedCompareExchange(&calls, 0, 0); } + +extern "C" LONG WINAPI decoy_open_key_ex_w(HKEY, LPCWSTR, DWORD, REGSAM, PHKEY out) +{ + InterlockedIncrement(&calls); + if (out) *out = reinterpret_cast(static_cast(0xDEC0)); + return decoy_status; +} + +extern "C" LONG WINAPI decoy_query_value_ex_w(HKEY, LPCWSTR, LPDWORD, LPDWORD, LPBYTE, LPDWORD) +{ + InterlockedIncrement(&calls); + return decoy_status; +} diff --git a/tests/startup_console_mode_decoy.def b/tests/startup_console_mode_decoy.def new file mode 100644 index 0000000000..8e0e44b363 --- /dev/null +++ b/tests/startup_console_mode_decoy.def @@ -0,0 +1,5 @@ +LIBRARY startup_console_mode_decoy +EXPORTS + RegOpenKeyExW = decoy_open_key_ex_w + RegQueryValueExW = decoy_query_value_ex_w + decoy_calls diff --git a/tests/startup_runtime_proxy_scope/decoy.cpp b/tests/startup_runtime_proxy_scope/decoy.cpp index ddba2565e0..86f8aefe30 100644 --- a/tests/startup_runtime_proxy_scope/decoy.cpp +++ b/tests/startup_runtime_proxy_scope/decoy.cpp @@ -1,4 +1,5 @@ -// Unrelated DLL that also exports QueryApiImpl; must not become the cached gaming-runtime provider. +// Unrelated DLL that also exports QueryApiImpl and RegQueryValueExW; must not become the cached +// gaming-runtime provider or the remembered registry function. #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif @@ -6,6 +7,7 @@ namespace { LONG calls; +LONG registry_calls; } extern "C" __declspec(dllexport) LONG WINAPI query_calls() { return InterlockedCompareExchange(&calls, 0, 0); } @@ -16,3 +18,12 @@ extern "C" __declspec(dllexport) HRESULT WINAPI QueryApiImpl(const GUID*, const if (out) *out = nullptr; return 0xA11C0001; // distinct from the fake xgameruntime path } + +extern "C" LONG WINAPI registry_query_calls() { return InterlockedCompareExchange(®istry_calls, 0, 0); } + +// Exported as RegQueryValueExW (decoy.def): a result no registry returns. +extern "C" LONG WINAPI decoy_reg_query_value_ex_w(HKEY, LPCWSTR, LPDWORD, LPDWORD, LPBYTE, LPDWORD) +{ + InterlockedIncrement(®istry_calls); + return 0x5EC1; +} diff --git a/tests/startup_runtime_proxy_scope/decoy.def b/tests/startup_runtime_proxy_scope/decoy.def index 223c116b56..9da19864b5 100644 --- a/tests/startup_runtime_proxy_scope/decoy.def +++ b/tests/startup_runtime_proxy_scope/decoy.def @@ -2,3 +2,5 @@ LIBRARY startup_runtime_proxy_decoy EXPORTS QueryApiImpl query_calls + RegQueryValueExW = decoy_reg_query_value_ex_w + registry_query_calls diff --git a/tests/startup_runtime_proxy_scope/host.cpp b/tests/startup_runtime_proxy_scope/host.cpp index ec4221b3e9..516e652699 100644 --- a/tests/startup_runtime_proxy_scope/host.cpp +++ b/tests/startup_runtime_proxy_scope/host.cpp @@ -4,7 +4,8 @@ // unrelated decoy that also exports QueryApiImpl, then a helper beside the EXE. The helper's // GetProcAddress IAT is rewritten after linking (outside LdrDllNotification). Looking up // QueryApiImpl on xgameruntime must return the proxy; the same name on the decoy must still be the -// decoy's export. No game files. +// decoy's export. RegQueryValueExW is hooked on advapi32.dll only: the decoy's same-named export stays +// its own, with X2W_DEVICE_TYPE unset and set, and never becomes the registry the hook calls. No game files. #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif @@ -25,6 +26,8 @@ void check(const char* label, bool ok) using ResolveFn = FARPROC(WINAPI*)(HMODULE); using QueryFn = HRESULT(WINAPI*)(const GUID*, const GUID*, void**); +using RegQueryFn = LONG(WINAPI*)(HKEY, LPCWSTR, LPDWORD, LPDWORD, LPBYTE, LPDWORD); +using SeenFn = LONG(WINAPI*)(); std::wstring dir_of_self() { @@ -69,6 +72,11 @@ int main() const FARPROC xgr_query = xgr ? GetProcAddress(xgr, "QueryApiImpl") : nullptr; check("xgameruntime exports QueryApiImpl", xgr_query != nullptr); check("decoy and xgameruntime exports differ", decoy_query && xgr_query && decoy_query != xgr_query); + const FARPROC decoy_reg = decoy ? GetProcAddress(decoy, "RegQueryValueExW") : nullptr; + check("decoy exports RegQueryValueExW", decoy_reg != nullptr); + const HMODULE advapi = LoadLibraryW(L"advapi32.dll"); + const FARPROC advapi_reg = advapi ? GetProcAddress(advapi, "RegQueryValueExW") : nullptr; + check("advapi32.dll exports RegQueryValueExW", advapi_reg != nullptr && advapi_reg != decoy_reg); const HMODULE carrier = load_beside(dir, L"startup_runtime_proxy_carrier.dll"); check("load proxy carrier", carrier != nullptr); @@ -99,7 +107,6 @@ int main() check("helper GetProcAddress(decoy) stays original", helper_decoy == decoy_query); // Intended call: invoke the proxied entry; the fake xgameruntime must run. - using SeenFn = LONG(WINAPI*)(); const auto xgr_seen = xgr ? reinterpret_cast(GetProcAddress(xgr, "query_calls")) : nullptr; const auto decoy_seen = decoy ? reinterpret_cast(GetProcAddress(decoy, "query_calls")) : nullptr; const LONG xgr_before = xgr_seen ? xgr_seen() : -1; @@ -109,6 +116,32 @@ int main() check("proxied call reached xgameruntime", xgr_seen && xgr_seen() == xgr_before + 1); check("decoy call reached decoy only", decoy_seen && decoy_seen() == decoy_before + 1); + // Registry names, with the switch unset and set. The decoy is looked up first each time, so a + // match by name alone would keep the decoy as the registry the hook calls. + const auto decoy_reg_seen = decoy ? reinterpret_cast(GetProcAddress(decoy, "registry_query_calls")) : nullptr; + DWORD type = 0, bytes = 0; + const LONG expect_real = advapi_reg ? reinterpret_cast(advapi_reg)(nullptr, L"ConsoleMode", nullptr, &type, nullptr, &bytes) : -1; + check("advapi32.dll's own answer differs from the decoy's", expect_real != 0x5EC1); + for (const wchar_t* device : {static_cast(nullptr), L"7"}) { + SetEnvironmentVariableW(L"X2W_DEVICE_TYPE", device); + const std::string pass = device ? "X2W_DEVICE_TYPE=7: " : "switch unset: "; + const FARPROC host_decoy_reg = decoy ? GetProcAddress(decoy, "RegQueryValueExW") : nullptr; + check((pass + "host GetProcAddress(decoy, RegQueryValueExW) stays original").c_str(), host_decoy_reg == decoy_reg); + const LONG decoy_before = decoy_reg_seen ? decoy_reg_seen() : -1; + const LONG decoy_answer = + host_decoy_reg ? reinterpret_cast(host_decoy_reg)(nullptr, L"ConsoleMode", nullptr, &type, nullptr, &bytes) : -1; + check((pass + "decoy RegQueryValueExW answers its own result").c_str(), + decoy_answer == 0x5EC1 && decoy_reg_seen && decoy_reg_seen() == decoy_before + 1); + const FARPROC host_advapi_reg = advapi ? GetProcAddress(advapi, "RegQueryValueExW") : nullptr; + check((pass + "host GetProcAddress(advapi32, RegQueryValueExW) is hooked").c_str(), + host_advapi_reg && host_advapi_reg != advapi_reg && host_advapi_reg != decoy_reg); + const LONG hooked_answer = + host_advapi_reg ? reinterpret_cast(host_advapi_reg)(nullptr, L"ConsoleMode", nullptr, &type, nullptr, &bytes) : -1; + check((pass + "hooked RegQueryValueExW reaches advapi32.dll, not the decoy").c_str(), + hooked_answer == expect_real && decoy_reg_seen && decoy_reg_seen() == decoy_before + 1); + } + SetEnvironmentVariableW(L"X2W_DEVICE_TYPE", nullptr); + if (failures) { std::printf("startup_runtime_proxy_scope: FAIL (%d)\n", failures); return 1;