From 78b70e1ab9c97e5252e163359d985a8a454df6de Mon Sep 17 00:00:00 2001 From: Hunter Jozwiak Date: Sun, 1 Nov 2026 21:15:59 -0500 Subject: [PATCH] Add native per-program hook exclusions Parse --exclude-hook-program in the helper, gate foreground hooks and dialog reading by program, and forward the list to the 32-bit hook host. Emit the flags from the Orca extension and cover the matching, validation, and manager behavior with regression tests. --- CMakeLists.txt | 5 +++ README.md | 7 ++- foreground_hooks.h | 7 ++- hook_exclusions.h | 80 ++++++++++++++++++++++++++++++++++ main.cpp | 49 ++++++++++++++++++++- menu_host32.c | 15 ++++++- orca/README.md | 5 ++- orca/tests/test_manager.py | 20 ++++++++- orca/wine_access/__init__.py | 6 ++- orca/wine_access/manager.py | 21 +++++++++ tests/hook_exclusions_test.cpp | 71 ++++++++++++++++++++++++++++++ 11 files changed, 278 insertions(+), 8 deletions(-) create mode 100644 hook_exclusions.h create mode 100644 tests/hook_exclusions_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 0b06040..bfce15d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -104,6 +104,11 @@ if(BUILD_TESTING) target_compile_options(text-limits-test PRIVATE -Wall -Wextra) target_link_libraries(text-limits-test PRIVATE PkgConfig::GIO user32) add_wine_test(text-limits 35 dbus-run-session -- "${CMAKE_CURRENT_BINARY_DIR}/text-limits-test.exe") + add_executable(hook-exclusions-test tests/hook_exclusions_test.cpp) + target_compile_features(hook-exclusions-test PRIVATE cxx_std_20) + target_compile_options(hook-exclusions-test PRIVATE -Wall -Wextra) + target_link_libraries(hook-exclusions-test PRIVATE user32) + add_wine_test(hook-exclusions 35 "${CMAKE_CURRENT_BINARY_DIR}/hook-exclusions-test.exe") add_executable(review-capture-test tests/review_capture_test.cpp) target_compile_features(review-capture-test PRIVATE cxx_std_20) target_compile_options(review-capture-test PRIVATE -Wall -Wextra) diff --git a/README.md b/README.md index ed8cce9..b5216b2 100644 --- a/README.md +++ b/README.md @@ -296,7 +296,12 @@ Orca's existing `SpeakMessage` and `DisplayMessage` methods have different names/signatures. Wine Access does not translate to those methods. An Orca contributor must implement the Wine methods above for the capabilities they want to enable. `--no-controller` and `--no-dialog-reader` can disable either -capability while bringing up the integration. +capability while bringing up the integration. Repeatable +`--exclude-hook-program ` arguments list programs the helper must +never hook or dialog-read, while still serving their controller speech; +readers use them for games whose anti-tamper code objects to injected hooks, +so the protection holds from the helper's first foreground poll rather than +only after the reader's next supervision pass. Review retains the shared `/org/stormux/Cthulhu1/WineReview` object path and `org.stormux.Cthulhu1.WineReview` interface for both readers. Use the helper's diff --git a/foreground_hooks.h b/foreground_hooks.h index def12c3..6d08eb3 100644 --- a/foreground_hooks.h +++ b/foreground_hooks.h @@ -2,12 +2,14 @@ #pragma once #include #include "bootstrapper_hook.h" +#include "hook_exclusions.h" typedef struct WineAccessForegroundHooks { HMODULE module; HOOKPROC menu_callback, input_callback; HHOOK menu, input; DWORD thread; + const WineAccessHookExclusions *exclusions; } WineAccessForegroundHooks; static inline void wine_access_release_hooks(WineAccessForegroundHooks *hooks) { @@ -26,8 +28,11 @@ static inline void wine_access_update_hooks(WineAccessForegroundHooks *hooks, BO HANDLE process = pid ? OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid) : NULL; BOOL wow64 = FALSE; BOOL known = process && IsWow64Process(process, &wow64); + // An excluded program's thread never receives the hooks; its controller + // speech does not need them and its anti-tamper code may object to them. + BOOL excluded = process && wine_access_process_hook_excluded(hooks->exclusions, process); if (process) CloseHandle(process); - if (!known || wow64 != target_wow64) thread = 0; + if (!known || wow64 != target_wow64 || excluded) thread = 0; if (thread == hooks->thread) return; wine_access_release_hooks(hooks); if (!thread || !hooks->menu_callback || !hooks->input_callback) return; diff --git a/hook_exclusions.h b/hook_exclusions.h new file mode 100644 index 0000000..18e6a16 --- /dev/null +++ b/hook_exclusions.h @@ -0,0 +1,80 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +#pragma once +#include + +// Programs whose threads must never receive the native menu/input hooks, +// named by executable file name. Readers pass one --exclude-hook-program +// argument per program; the 64-bit helper forwards the same list to the +// 32-bit hook host through WINE_ACCESS_EXCLUDE_HOOK_PROGRAMS (';'-joined), +// an internal channel the reader never sets. The bounds mirror the +// readers' own validation so either side rejects the same names. +#define WINE_ACCESS_MAX_HOOK_EXCLUSIONS 256 +#define WINE_ACCESS_MAX_HOOK_EXCLUSION_LENGTH 255 + +typedef struct WineAccessHookExclusions { + WCHAR names[WINE_ACCESS_MAX_HOOK_EXCLUSIONS][WINE_ACCESS_MAX_HOOK_EXCLUSION_LENGTH + 1]; + int count; +} WineAccessHookExclusions; + +static inline BOOL wine_access_hook_exclusion_valid(const WCHAR *name) { + if (!name) return FALSE; + int length = 0; + while (length <= WINE_ACCESS_MAX_HOOK_EXCLUSION_LENGTH && name[length]) ++length; + if (!length || length > WINE_ACCESS_MAX_HOOK_EXCLUSION_LENGTH) return FALSE; + if (name[0] <= L' ' || name[length - 1] <= L' ') return FALSE; + for (int index = 0; index < length; ++index) + if (name[index] < L' ' || name[index] == L'/' || name[index] == L'\\') return FALSE; + return TRUE; +} + +static inline BOOL wine_access_hook_exclusions_add(WineAccessHookExclusions *list, + const WCHAR *name) { + if (!list || !wine_access_hook_exclusion_valid(name)) return FALSE; + for (int index = 0; index < list->count; ++index) + if (!lstrcmpiW(list->names[index], name)) return TRUE; + if (list->count >= WINE_ACCESS_MAX_HOOK_EXCLUSIONS) return FALSE; + lstrcpyW(list->names[list->count++], name); + return TRUE; +} + +static inline BOOL wine_access_hook_exclusions_match(const WineAccessHookExclusions *list, + const WCHAR *program) { + if (!list || !program) return FALSE; + const WCHAR *name = program; + for (const WCHAR *cursor = program; *cursor; ++cursor) + if (*cursor == L'\\' || *cursor == L'/') name = cursor + 1; + if (!*name) return FALSE; + for (int index = 0; index < list->count; ++index) + if (!lstrcmpiW(list->names[index], name)) return TRUE; + return FALSE; +} + +static inline int wine_access_hook_exclusions_parse(WineAccessHookExclusions *list, + const WCHAR *value) { + if (!list || !value) return 0; + const int before = list->count; + const WCHAR *start = value; + for (;;) { + const WCHAR *end = start; + while (*end && *end != L';') ++end; + const int length = (int)(end - start); + if (length && length <= WINE_ACCESS_MAX_HOOK_EXCLUSION_LENGTH) { + WCHAR name[WINE_ACCESS_MAX_HOOK_EXCLUSION_LENGTH + 1]; + for (int index = 0; index < length; ++index) name[index] = start[index]; + name[length] = 0; + wine_access_hook_exclusions_add(list, name); + } + if (!*end) break; + start = end + 1; + } + return list->count - before; +} + +static inline BOOL wine_access_process_hook_excluded(const WineAccessHookExclusions *list, + HANDLE process) { + if (!list || !list->count || !process) return FALSE; + WCHAR path[4096]; + DWORD length = ARRAYSIZE(path); + if (!QueryFullProcessImageNameW(process, 0, path, &length)) return FALSE; + return wine_access_hook_exclusions_match(list, path); +} diff --git a/main.cpp b/main.cpp index c2b0b1d..83325a0 100644 --- a/main.cpp +++ b/main.cpp @@ -10,6 +10,7 @@ #include "review_service.h" #include "foreground_focus.h" #include "foreground_hooks.h" +#include "hook_exclusions.h" #include "reader_endpoint.h" #include "msaa_events.h" #include "reader_events.h" @@ -57,6 +58,9 @@ std::deque menuEvents; std::deque textEvents; std::deque notificationEvents; bool editReaderActive = false; +WineAccessHookExclusions hookExclusions; +DWORD hookExclusionPid = 0; +bool hookExclusionPidExcluded = false; std::string lastMenuEvent; ULONGLONG lastMenuOwner = 0; HWND lastTextControl = nullptr; @@ -497,6 +501,24 @@ ControlDescription describe_standard_control(HWND window) { return control; } +bool hook_excluded_pid(DWORD pid) { + if (!pid || !hookExclusions.count) return false; + if (pid == hookExclusionPid) return hookExclusionPidExcluded; + HANDLE process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid); + const bool excluded = process && wine_access_process_hook_excluded(&hookExclusions, process); + if (process) CloseHandle(process); + hookExclusionPid = pid; + hookExclusionPidExcluded = excluded; + return excluded; +} + +bool hook_excluded_window(HWND window) { + if (!window || !hookExclusions.count) return false; + DWORD pid = 0; + GetWindowThreadProcessId(window, &pid); + return hook_excluded_pid(pid); +} + bool present_standard_focus(HWND window) { // Read through the subclass so returning from a menu reports the caret's // line, not the beginning of the document. Never block on the callback. @@ -514,7 +536,7 @@ void poll_control_focus(bool refresh = false) { GUITHREADINFO info{}; info.cbSize = sizeof(info); HWND foreground = GetForegroundWindow(); - const bool focused = foreground && + const bool focused = foreground && !hook_excluded_window(foreground) && GetGUIThreadInfo(GetWindowThreadProcessId(foreground, nullptr), &info) && !(info.flags & GUI_INMENUMODE); HWND bootstrapper = focused && info.hwndFocus == foreground && @@ -904,6 +926,10 @@ void CALLBACK winevent_callback(HWINEVENTHOOK, DWORD event, HWND window, return; if (editReaderActive && GetPropW(window, EDIT_STATE_PROPERTY)) return; + // Excluded programs get no dialog reading. Focus invalidation above has + // already retired the previous application's pending events. + if (hook_excluded_window(window)) + return; if (HWND combo = combo_event_control(window, event)) { // The combo's internal list can emit focus events even while the combo // retains keyboard focus. Keep a single source for focus and value updates. @@ -1151,6 +1177,12 @@ int WINAPI WinMain(HINSTANCE instance, HINSTANCE, char *, int) { dialogReaderEnabled = false; continue; } + if (lstrcmpW(arguments[index], L"--exclude-hook-program") == 0) { + if (++index == argumentCount || + !wine_access_hook_exclusions_add(&hookExclusions, arguments[index])) + std::fprintf(stderr, "wine-access: ignoring invalid --exclude-hook-program value\n"); + continue; + } if (lstrcmpW(arguments[index], L"--no-controller") == 0) { controllerEnabled = false; continue; @@ -1190,6 +1222,20 @@ int WINAPI WinMain(HINSTANCE instance, HINSTANCE, char *, int) { // These strings remain alive until the workers have stopped at shutdown. if (!readerPath.empty()) readerEndpoint.objectPath = readerPath.c_str(); if (!readerInterface.empty()) readerEndpoint.interfaceName = readerInterface.c_str(); + // The 32-bit hook host inherits this process environment; publish the + // exclusions there (or clear any inherited list) so both hook hosts gate + // the same programs. Readers communicate them by argument only. + if (hookExclusions.count) { + std::wstring joined; + for (int index = 0; index < hookExclusions.count; ++index) { + if (index) joined += L';'; + joined += hookExclusions.names[index]; + } + SetEnvironmentVariableW(L"WINE_ACCESS_EXCLUDE_HOOK_PROGRAMS", joined.c_str()); + std::fprintf(stderr, "wine-access: hook exclusions for %d program(s)\n", hookExclusions.count); + } else { + SetEnvironmentVariableW(L"WINE_ACCESS_EXCLUDE_HOOK_PROGRAMS", nullptr); + } if (!dialogReaderEnabled && !controllerEnabled) { std::fprintf(stderr, "wine-access: disabled by command-line options\n"); return 0; @@ -1306,6 +1352,7 @@ int WINAPI WinMain(HINSTANCE instance, HINSTANCE, char *, int) { if (!foregroundHooks.menu_callback) menuHookError = GetLastError(); foregroundHooks.input_callback = std::bit_cast(GetProcAddress(menuModule, "WineAccessInputHook")); if (!foregroundHooks.input_callback) inputHookError = GetLastError(); + foregroundHooks.exclusions = &hookExclusions; editReaderActive = foregroundHooks.menu_callback && foregroundHooks.input_callback; wine_access_update_hooks(&foregroundHooks, FALSE); } diff --git a/menu_host32.c b/menu_host32.c index 92be293..9f58a60 100644 --- a/menu_host32.c +++ b/menu_host32.c @@ -4,6 +4,9 @@ #include #include +static WineAccessHookExclusions hookExclusions; +static WCHAR hookExclusionsValue[32767]; + // Hook DLLs must match the application's architecture. This small PE host // supplies 32-bit menu/editor hooks without requiring 32-bit Linux GLib/Winelib. int WINAPI WinMain(HINSTANCE instance, HINSTANCE previous, LPSTR args, int show) { @@ -16,6 +19,16 @@ int WINAPI WinMain(HINSTANCE instance, HINSTANCE previous, LPSTR args, int show) if (!parentId || bridgeProcess != parentId) return 1; HANDLE parent = OpenProcess(SYNCHRONIZE, FALSE, parentId); if (!parent) return 1; + // The parent helper publishes its --exclude-hook-program list here. An + // unreadable list must not silently un-exclude a program: run no hooks. + DWORD exclusionsLength = GetEnvironmentVariableW( + L"WINE_ACCESS_EXCLUDE_HOOK_PROGRAMS", hookExclusionsValue, ARRAYSIZE(hookExclusionsValue)); + if (exclusionsLength >= ARRAYSIZE(hookExclusionsValue)) { + fprintf(stderr, "wine-access: 32-bit hook exclusions unavailable\n"); + CloseHandle(parent); + return 1; + } + if (exclusionsLength) wine_access_hook_exclusions_parse(&hookExclusions, hookExclusionsValue); WCHAR path[4096] = {0}; DWORD length = GetModuleFileNameW(NULL, path, 4096); @@ -31,7 +44,7 @@ int WINAPI WinMain(HINSTANCE instance, HINSTANCE previous, LPSTR args, int show) HMODULE module = LoadLibraryW(path); HOOKPROC callback = module ? (HOOKPROC)GetProcAddress(module, "WineAccessMenuHook") : NULL; HOOKPROC inputCallback = module ? (HOOKPROC)GetProcAddress(module, "WineAccessInputHook") : NULL; - WineAccessForegroundHooks hooks = {module, callback, inputCallback, NULL, NULL, 0}; + WineAccessForegroundHooks hooks = {module, callback, inputCallback, NULL, NULL, 0, &hookExclusions}; if (!callback || !inputCallback) fprintf(stderr, "wine-access: 32-bit menu/editor hooks unavailable (error %lu)\n", GetLastError()); if (callback && inputCallback) { diff --git a/orca/README.md b/orca/README.md index 48da190..62e6713 100644 --- a/orca/README.md +++ b/orca/README.md @@ -108,7 +108,10 @@ preferences offer controller-only mode: helpers run with `--no-dialog-reader`, injecting nothing and polling no controls, while NVDA/Tolk speech and braille keep working. Enable it for all applications there, or list executable names (e.g. `Diablo IV.exe`) to -apply it per game. Settings are read when a helper starts, so neither +apply it per game. Listed programs are also passed to every helper as +`--exclude-hook-program` arguments, so the helper itself never hooks or +dialog-reads them even in the first passes before a prefix's helper has been +restarted controller-only. Settings are read when a helper starts, so neither Orca nor the reader needs a restart; relaunch the game to switch modes. `WINE_ACCESS_NO_DIALOG_READER=1` in Orca's environment forces the same mode for every helper, for testing. diff --git a/orca/tests/test_manager.py b/orca/tests/test_manager.py index 4e144d7..3dfd656 100644 --- a/orca/tests/test_manager.py +++ b/orca/tests/test_manager.py @@ -13,7 +13,8 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "wine_access")) import manager as manager_module # noqa: E402 from manager import (HelperManager, controller_only_arguments, # noqa: E402 - extra_helper_arguments, loader_for, prefix_for) + excluded_hook_arguments, extra_helper_arguments, + loader_for, prefix_for) class FakeProcess: @@ -125,6 +126,23 @@ class DiscoveryTests(unittest.TestCase): self.assertEqual(controller_only_arguments(set(), [], True), ["--no-dialog-reader"]) + def test_excluded_hook_arguments(self): + self.assertEqual(excluded_hook_arguments([]), []) + self.assertEqual(excluded_hook_arguments(None), []) + self.assertEqual( + excluded_hook_arguments(["Diablo IV.exe", "Game.EXE"]), + ["--exclude-hook-program", "diablo iv.exe", + "--exclude-hook-program", "game.exe"]) + self.assertEqual( + excluded_hook_arguments(("Game.EXE",)), + ["--exclude-hook-program", "game.exe"]) + + def test_excluded_hook_arguments_drop_invalid_names(self): + listed = ["", "../Game.exe", r"C:\Game.exe", " Game.exe", + "Game.exe ", "a" * 256, 7, "Valid.exe"] + self.assertEqual(excluded_hook_arguments(listed), + ["--exclude-hook-program", "valid.exe"]) + def test_discovery_collects_program_names(self): self.fake.add(17, "wine", {"WINEPREFIX": "/p/x"}, r"S:\games\Game.exe") self.fake.add(18, "wine", {"WINEPREFIX": "/p/x"}, r"S:\games\launcher.exe") diff --git a/orca/wine_access/__init__.py b/orca/wine_access/__init__.py index 62e193c..280f382 100644 --- a/orca/wine_access/__init__.py +++ b/orca/wine_access/__init__.py @@ -16,7 +16,8 @@ from orca import debug, presentation_manager, typing_echo_presenter from orca.extension import Extension from orca.extension_preferences import ExtensionPreference -from .manager import HelperManager, controller_only_arguments, extra_helper_arguments +from .manager import (HelperManager, controller_only_arguments, + excluded_hook_arguments, extra_helper_arguments) from .presenter import WineEvent, WineEventPresenter from .review import DialogReader, gio_capture from .service import INTERFACE, OBJECT_PATH, WineAccessInterface @@ -75,7 +76,8 @@ class WineAccess(Extension): always = self.settings.get("controller-only", False) listed = self.settings.get("controller-only-programs", []) - return controller_only_arguments(programs, listed, always is True) + return [*excluded_hook_arguments(listed), + *controller_only_arguments(programs, listed, always is True)] # Extension lifecycle diff --git a/orca/wine_access/manager.py b/orca/wine_access/manager.py index 199a8ba..3b67b9f 100644 --- a/orca/wine_access/manager.py +++ b/orca/wine_access/manager.py @@ -104,6 +104,27 @@ def controller_only_arguments(programs: set[str], listed, return [] +def excluded_hook_arguments(listed) -> list[str]: + """--exclude-hook-program flags for the listed executable names. + + The helper itself enforces these from its first foreground poll, so a + listed program's thread is never hooked even in the passes before + discovery sees it and the whole-prefix controller-only restart lands. + Validation mirrors Cthulhu's settings rules: bare executable names + only, passed lower-case, at most as many as the helper stores. + """ + + if not isinstance(listed, (list, tuple)): + return [] + arguments: list[str] = [] + names = sorted(name for name in listed if isinstance(name, str)) + for name in names[:256]: + if (name and len(name) <= 255 and name.strip() == name + and not any(char in name for char in "\0\r\n/\\")): + arguments += ["--exclude-hook-program", name.lower()] + return arguments + + def find_helper() -> str | None: for path in helper_candidates(): if os.access(path, os.X_OK): diff --git a/tests/hook_exclusions_test.cpp b/tests/hook_exclusions_test.cpp new file mode 100644 index 0000000..ca05016 --- /dev/null +++ b/tests/hook_exclusions_test.cpp @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: LGPL-2.1-or-later +#include "../hook_exclusions.h" +#include +#include + +static bool check(bool value, const char *message) { + if (!value) std::fprintf(stderr, "FAIL: %s\n", message); + return value; +} + +int main() { + bool ok = true; + static WineAccessHookExclusions exclusions; + ok &= check(!wine_access_hook_exclusions_match(&exclusions, L"Game.exe"), + "empty list excludes nothing"); + ok &= check(wine_access_hook_exclusions_add(&exclusions, L"Diablo IV.exe"), + "valid exclusion is stored"); + ok &= check(wine_access_hook_exclusions_add(&exclusions, L"diablo iv.EXE"), + "duplicate exclusion is accepted"); + ok &= check(exclusions.count == 1, "duplicate exclusion is stored once"); + ok &= check(wine_access_hook_exclusions_match(&exclusions, L"Diablo IV.exe"), + "exclusion matches its file name"); + ok &= check(wine_access_hook_exclusions_match( + &exclusions, L"C:\\Program Files\\Diablo IV\\Diablo IV.exe"), + "exclusion matches a Windows path by file name"); + ok &= check(wine_access_hook_exclusions_match( + &exclusions, L"Z:/games/diablo iv.exe"), + "exclusion matches a forward-slash path by file name"); + ok &= check(!wine_access_hook_exclusions_match(&exclusions, L"Diablo IV Launcher.exe"), + "exclusion does not match a different program"); + ok &= check(!wine_access_hook_exclusions_match(&exclusions, nullptr), + "exclusion does not match a missing program"); + ok &= check(!wine_access_hook_exclusions_add(&exclusions, L""), + "empty exclusion is rejected"); + ok &= check(!wine_access_hook_exclusions_add(&exclusions, L"../Game.exe"), + "exclusion with a forward slash is rejected"); + ok &= check(!wine_access_hook_exclusions_add(&exclusions, L"C:\\Game.exe"), + "exclusion with a backslash is rejected"); + ok &= check(!wine_access_hook_exclusions_add(&exclusions, L" Game.exe"), + "exclusion with leading whitespace is rejected"); + ok &= check(!wine_access_hook_exclusions_add(&exclusions, L"Game.exe "), + "exclusion with trailing whitespace is rejected"); + std::vector oversized(WINE_ACCESS_MAX_HOOK_EXCLUSION_LENGTH + 2, L'a'); + oversized.back() = 0; + ok &= check(!wine_access_hook_exclusions_add(&exclusions, oversized.data()), + "oversized exclusion is rejected"); + oversized[WINE_ACCESS_MAX_HOOK_EXCLUSION_LENGTH] = 0; + ok &= check(wine_access_hook_exclusions_add(&exclusions, oversized.data()), + "maximum-size exclusion is accepted"); + + static WineAccessHookExclusions parsed; + const int added = wine_access_hook_exclusions_parse( + &parsed, L"One.exe;two.exe;C:\\bad.exe;;Two.EXE"); + ok &= check(added == 2 && parsed.count == 2, + "semicolon list keeps valid unique exclusions"); + ok &= check(wine_access_hook_exclusions_match(&parsed, L"ONE.EXE"), + "parsed exclusion matches its program"); + + static WineAccessHookExclusions full; + WCHAR name[32]; + bool filled = true; + for (int index = 0; index < WINE_ACCESS_MAX_HOOK_EXCLUSIONS; ++index) { + wsprintfW(name, L"game%d.exe", index); + filled &= wine_access_hook_exclusions_add(&full, name); + } + ok &= check(filled && full.count == WINE_ACCESS_MAX_HOOK_EXCLUSIONS, + "exclusion list fills to its bound"); + ok &= check(!wine_access_hook_exclusions_add(&full, L"overflow.exe"), + "exclusion past the bound is rejected"); + return ok ? 0 : 1; +}