runtime: free unused thunk on zero redirects and harden code_hooks bounds #2056

Merged
IlyassRS3 merged 1 commit from upstream-pr/2056 into main 2026-11-28 18:13:41 +00:00
IlyassRS3 commented 2026-11-25 19:09:21 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by IlyassRS3 on 2026-11-25T19:09:21Z.


Claim ID: RT-CODE-HOOKS-THUNK-LEAK-AND-GRANULARITY-GUARDS

Summary

Fixes a thunk + unwind-table leak and hardens bounds checks in runtime/src/code_hooks.h:

  1. Free unused thunk when redirect_image_calls redirects 0 branches: Previously free_thunk(thunk) was only called in the VirtualProtect failure path when r.redirected == 0, so a valid executable target with no direct E8/E9 callers leaked both its executable 4 KiB page and its global RtlAddFunctionTable entry permanently. Calling if (r.redirected == 0) free_thunk(thunk); after the section loop closes the leak.
  2. Guard zero/non-power-of-two allocation granularity in alloc_near: Falls back to 0x10000 if dwAllocationGranularity == 0 (preventing an infinite loop on delta += 0), aligns center without assuming power-of-two granularity, and guards delta addition against wrapping span.
  3. Validate thunk and unwind buffer bounds in finish_thunk: Rejects null t, code_size == 0, code_size > kThunkUnwindOffset, and unwind.size() > kThunkFunctionOffset - kThunkUnwindOffset (freeing the page rather than overwriting RUNTIME_FUNCTION).
  4. Overflow-free rel32 distance check and e_lfanew bound: Replaces signed intptr_t difference casting in redirect_direct_branches with an unsigned magnitude check against [INT32_MIN, INT32_MAX], and guards lfanew > UINT32_MAX - sizeof(IMAGE_NT_HEADERS64) before forming nt.
  5. Regression tests: Extends runtime/test/code_hooks_test.cpp with a finish_thunk(nullptr, ...) check and a zero-caller synthetic PE64 image test verifying RtlLookupFunctionEntry returns null for the freed unused thunk.

Verification

  • AI-assisted: yes (Antigravity agent by Google DeepMind)
  • GPUs tested: none (verified locally on macOS arm64 with Apple Clang 17 and minimal Win32 PE/memory stubs; Windows MSVC CI run of code_hooks pending)
  • Sanitizers & tests (standalone harness exercising code_hooks.h):
    • clang++ -std=c++20 -O1 -g -fsanitize=address,undefined -Wall -Wextra -Werror: PASS (failures=0)
    • clang++ -std=c++20 -O1 -g -fsanitize=thread -Wall -Wextra -Werror: PASS (failures=0)
    • clang++ -std=c++20 -O2 -Wall -Wextra -Werror: PASS (failures=0)
    • Negative control on main: confirmed both leaks when redirected == 0 (live thunk page + live RUNTIME_FUNCTION table left registered, main_exit=1).
  • Repository checks: python3 -I scripts/check_no_game_data.py clean; python3 -I tests/test_text_write_line_endings.py (3/3 OK).
<!-- greyfinch-sync:ubiquitarianism/leonida:issue:5497490391 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2056). Originally posted by [IlyassRS3](https://github.com/IlyassRS3) on 2026-11-25T19:09:21Z. --- Claim ID: `RT-CODE-HOOKS-THUNK-LEAK-AND-GRANULARITY-GUARDS` ### Summary Fixes a thunk + unwind-table leak and hardens bounds checks in `runtime/src/code_hooks.h`: 1. **Free unused thunk when `redirect_image_calls` redirects 0 branches:** Previously `free_thunk(thunk)` was only called in the `VirtualProtect` failure path when `r.redirected == 0`, so a valid executable target with no direct `E8`/`E9` callers leaked both its executable 4 KiB page and its global `RtlAddFunctionTable` entry permanently. Calling `if (r.redirected == 0) free_thunk(thunk);` after the section loop closes the leak. 2. **Guard zero/non-power-of-two allocation granularity in `alloc_near`:** Falls back to `0x10000` if `dwAllocationGranularity == 0` (preventing an infinite loop on `delta += 0`), aligns `center` without assuming power-of-two granularity, and guards `delta` addition against wrapping `span`. 3. **Validate thunk and unwind buffer bounds in `finish_thunk`:** Rejects null `t`, `code_size == 0`, `code_size > kThunkUnwindOffset`, and `unwind.size() > kThunkFunctionOffset - kThunkUnwindOffset` (freeing the page rather than overwriting `RUNTIME_FUNCTION`). 4. **Overflow-free `rel32` distance check and `e_lfanew` bound:** Replaces signed `intptr_t` difference casting in `redirect_direct_branches` with an unsigned magnitude check against `[INT32_MIN, INT32_MAX]`, and guards `lfanew > UINT32_MAX - sizeof(IMAGE_NT_HEADERS64)` before forming `nt`. 5. **Regression tests:** Extends `runtime/test/code_hooks_test.cpp` with a `finish_thunk(nullptr, ...)` check and a zero-caller synthetic PE64 image test verifying `RtlLookupFunctionEntry` returns null for the freed unused thunk. ### Verification - **AI-assisted:** yes (Antigravity agent by Google DeepMind) - **GPUs tested:** none (verified locally on macOS arm64 with Apple Clang 17 and minimal Win32 PE/memory stubs; Windows MSVC CI run of `code_hooks` pending) - **Sanitizers & tests (standalone harness exercising `code_hooks.h`):** - `clang++ -std=c++20 -O1 -g -fsanitize=address,undefined -Wall -Wextra -Werror`: PASS (`failures=0`) - `clang++ -std=c++20 -O1 -g -fsanitize=thread -Wall -Wextra -Werror`: PASS (`failures=0`) - `clang++ -std=c++20 -O2 -Wall -Wextra -Werror`: PASS (`failures=0`) - Negative control on `main`: confirmed both leaks when `redirected == 0` (live thunk page + live `RUNTIME_FUNCTION` table left registered, `main_exit=1`). - **Repository checks:** `python3 -I scripts/check_no_game_data.py` clean; `python3 -I tests/test_text_write_line_endings.py` (3/3 OK).
copilot-pull-request-reviewer[bot] commented 2026-11-25 19:09:33 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by copilot-pull-request-reviewer[bot] on 2026-11-25T19:09:33Z.

Review: COMMENTED


Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

<!-- greyfinch-sync:ubiquitarianism/leonida:review:6063442125 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2056#pullrequestreview-6063442125). Originally posted by [copilot-pull-request-reviewer[bot]](https://github.com/apps/copilot-pull-request-reviewer) on 2026-11-25T19:09:33Z. **Review:** COMMENTED --- Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.
zmasi commented 2026-11-28 11:28:37 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by zmasi on 2026-11-28T11:28:37Z.


Verified on Windows 11 (10.0.26200.9974) with MSVC 19.44.35228 (x64, /std:c++20 /EHsc /W4 /permissive- /utf-8 /O2) against main 4a54aedcb + 9fc1862fa (claim #2570#issuecomment-7238486276):

  • Line-by-line diff audit: Clean (runtime/src/code_hooks.h, runtime/test/code_hooks_test.cpp); zero-initializes SYSTEM_INFO, handles arbitrary non-power-of-two dwAllocationGranularity and delta step bounds in alloc_near, validates finish_thunk null/size bounds (freeing t on invalid size), computes unsigned rel32 displacements without UB, bounds e_lfanew, and frees unused thunks + unwind tables when r.redirected == 0. check_no_game_data.py clean.
  • Red (4a54aedcb + PR test): code_hooks_test.exe crashes with 0xc0000005 (STATUS_ACCESS_VIOLATION on finish_thunk(nullptr, ...)).
  • Green (4a54aedcb + 9fc1862fa merge): Merges cleanly (rc=0), compiles with 0 /W4 warnings, and code_hooks_test.exe passes (code_hooks_test: 62 checks, 0 failures, rc=0).

AI-assisted.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7238576609 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2056#issuecomment-7238576609). Originally posted by [zmasi](https://github.com/zmasi) on 2026-11-28T11:28:37Z. --- Verified on Windows 11 (`10.0.26200.9974`) with MSVC `19.44.35228` (`x64`, `/std:c++20 /EHsc /W4 /permissive- /utf-8 /O2`) against `main` `4a54aedcb` + `9fc1862fa` (claim `#2570#issuecomment-7238486276`): - **Line-by-line diff audit**: Clean (`runtime/src/code_hooks.h`, `runtime/test/code_hooks_test.cpp`); zero-initializes `SYSTEM_INFO`, handles arbitrary non-power-of-two `dwAllocationGranularity` and `delta` step bounds in `alloc_near`, validates `finish_thunk` null/size bounds (freeing `t` on invalid size), computes unsigned `rel32` displacements without UB, bounds `e_lfanew`, and frees unused thunks + unwind tables when `r.redirected == 0`. `check_no_game_data.py` clean. - **Red (`4a54aedcb` + PR test)**: `code_hooks_test.exe` crashes with `0xc0000005` (`STATUS_ACCESS_VIOLATION` on `finish_thunk(nullptr, ...)`). - **Green (`4a54aedcb` + `9fc1862fa` merge)**: Merges cleanly (`rc=0`), compiles with `0` `/W4` warnings, and `code_hooks_test.exe` passes (`code_hooks_test: 62 checks, 0 failures`, `rc=0`). AI-assisted.
MoonEyes commented 2026-11-28 18:13:38 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-11-28T18:13:38Z.


Red/green: On main code_hooks_test crashes with a segmentation fault, and with the PR ctest -R "^code_hooks$" passes.
Independent tester (OreoFR, RTX 4070, Windows 11): PR head merged with the other PRs of its batch on main c1ecf04ed, full ctest run (485 tests, tests that launch the game excluded): no new failure compared with main.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7243628296 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2056#issuecomment-7243628296). Originally posted by [MoonEyes](https://github.com/MoonEyes) on 2026-11-28T18:13:38Z. --- Red/green: On main code_hooks_test crashes with a segmentation fault, and with the PR ctest -R "^code_hooks$" passes. Independent tester (OreoFR, RTX 4070, Windows 11): PR head merged with the other PRs of its batch on main c1ecf04ed, full ctest run (485 tests, tests that launch the game excluded): no new failure compared with main.
OreoFR commented 2026-11-28 21:59:16 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by OreoFR on 2026-11-28T21:59:16Z.


Verified by OreoFR

  • Base: main c1ecf04ed + PR head 9fc1862fa; green run in a merge package of 16 PRs, no new ctest failure vs main
  • Test: ctest -R "^code_hooks$"
  • Red on main: crash (SegFault)
  • Green with the PR: OK
  • Verdict: READY
  • Machine: RTX 4070 Laptop 8 GB, NVIDIA 621.40, Intel Core Ultra 7 155H, Windows 11

AI-assisted (Claude Code, Claude Opus 5.5).

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7246415393 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2056#issuecomment-7246415393). Originally posted by [OreoFR](https://github.com/OreoFR) on 2026-11-28T21:59:16Z. --- **Verified by OreoFR** - Base: main `c1ecf04ed` + PR head `9fc1862fa`; green run in a merge package of 16 PRs, no new ctest failure vs main - Test: `ctest -R "^code_hooks$"` - Red on main: crash (SegFault) - Green with the PR: OK - Verdict: READY - Machine: RTX 4070 Laptop 8 GB, NVIDIA 621.40, Intel Core Ultra 7 155H, Windows 11 AI-assisted (Claude Code, Claude Opus 5.5).
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
ProjectLeonida/mandy!2056
No description provided.