runtime: step try_clzero_loop by VirtualQuery regions and guard wraparound in cpu_emulation #2035

Merged
IlyassRS3 merged 1 commit from upstream-pr/2035 into main 2026-11-28 17:53:58 +00:00
IlyassRS3 commented 2026-11-25 18:39:53 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by IlyassRS3 on 2026-11-25T18:39:53Z.


Coordination item: RT-CPU-EMULATION-CLZERO-REGION-AND-BOUNDS (claimed on #1608).

Why

  1. rt::cpu_emulation::try_clzero_loop() in runtime/src/cpu_emulation.h called writable(cur) (one VirtualQuery syscall) on every 4 KiB page (next_page = (cur & ~0xFFF) + 0x1000), issuing 16,384 VirtualQuery syscalls for a single 64 MiB contiguous MEM_COMMIT | PAGE_READWRITE zeroing batch even though VirtualQuery already returns BaseAddress + RegionSize for the entire uniform protection run.
  2. Arithmetic wraparound bugs in try_clzero_loop():
    • limit <= start + 64 wrapped when start = UINT64_MAX - 63 (0xFFFFFFFFFFFFFFC0), and end = start + 64 wrapped to 0, skipping the for (cur < end) writability check entirely and executing std::memset(0xFFFFFFFFFFFFFFC0, 0, 64) (immediate SIGSEGV).
    • (limit - start + 63) & ~63 wrapped to 0 when limit - start > UINT64_MAX - 63 (e.g. start = 0, limit = UINT64_MAX), leaving end == start, skipping writable(0), and returning ClzeroLoopResult::ok with Rip unchanged (infinite #UD loop).
    • (cur & ~0xFFF) + 0x1000 wrapped to 0 on the top page of 64-bit address space.
  3. readable() computed BaseAddress + RegionSize and addr + got without overflow/bounds checks, and decode(nullptr, ...) dereferenced code[0] and did not enforce the architectural 15-byte x86-64 instruction length limit when callers pass avail > 15.

Changes

  • runtime/src/cpu_emulation.h:
    • Add writable_region(addr, region_end) returning the end of the contiguous committed writable VirtualQuery run, and step try_clzero_loop() by region_end (16,384× fewer VirtualQuery syscalls on a contiguous 64 MiB buffer while preserving exact page-boundary fault splitting).
    • Use overflow-free limit <= start || limit - start <= 64, clamp span >= kMaxBatch before rounding up to 64 bytes, and verify total <= UINT64_MAX - start.
    • Make readable() overflow-free using subtraction against mbi.RegionSize.
    • Guard if (!code) return {}; and cap avail <= 15 in decode().
  • runtime/test/cpu_emulation_test.cpp: add tests for decode(nullptr, ...), >15-byte overlong instruction rejection, [UINT64_MAX - 63, UINT64_MAX) wraparound rejection, and [0, UINT64_MAX) null-page fault.

Verification

  • AI-assisted: yes (Antigravity agent by Google DeepMind).
  • GPUs tested: none (CPU-only verification on macOS arm64 using mock VirtualQuery/VirtualProtect Win32 stubs; Windows CI runs full cpu_emulation_test with real VirtualAlloc + SEH).
  • Compiled and ran cpu_emulation.h test harness with clang++ -std=c++20 -Wall -Wextra -Werror:
    • ASan+UBSan (-O1 -g -fsanitize=address,undefined): vq_64m=1 res_max=2 (faulted) res_top=0 (no_match) fails=0.
    • TSan (-O1 -g -fsanitize=thread): vq_64m=1 res_max=2 res_top=0 fails=0.
    • Release (-O2): vq_64m=1 res_max=2 res_top=0 fails=0.
  • Negative control against main's cpu_emulation.h:
    • main issued vq_64m=16384 VirtualQuery calls (vs 1 here — 16,384× reduction), returned res_max=1 (ok) with total=0 on [0, UINT64_MAX), and crashed with SIGSEGV (exit 139) on [UINT64_MAX - 63, UINT64_MAX).
  • python3 -I scripts/check_no_game_data.py runtime/src/cpu_emulation.h runtime/test/cpu_emulation_test.cpp: clean.
  • python3 -I tests/test_text_write_line_endings.py: 3/3 OK.
<!-- greyfinch-sync:ubiquitarianism/leonida:issue:5497069482 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2035). Originally posted by [IlyassRS3](https://github.com/IlyassRS3) on 2026-11-25T18:39:53Z. --- Coordination item: `RT-CPU-EMULATION-CLZERO-REGION-AND-BOUNDS` (claimed on #1608). ### Why 1. `rt::cpu_emulation::try_clzero_loop()` in `runtime/src/cpu_emulation.h` called `writable(cur)` (one `VirtualQuery` syscall) on every 4 KiB page (`next_page = (cur & ~0xFFF) + 0x1000`), issuing **16,384 `VirtualQuery` syscalls** for a single 64 MiB contiguous `MEM_COMMIT | PAGE_READWRITE` zeroing batch even though `VirtualQuery` already returns `BaseAddress + RegionSize` for the entire uniform protection run. 2. Arithmetic wraparound bugs in `try_clzero_loop()`: - `limit <= start + 64` wrapped when `start = UINT64_MAX - 63` (`0xFFFFFFFFFFFFFFC0`), and `end = start + 64` wrapped to `0`, skipping the `for (cur < end)` writability check entirely and executing `std::memset(0xFFFFFFFFFFFFFFC0, 0, 64)` (immediate SIGSEGV). - `(limit - start + 63) & ~63` wrapped to `0` when `limit - start > UINT64_MAX - 63` (e.g. `start = 0, limit = UINT64_MAX`), leaving `end == start`, skipping `writable(0)`, and returning `ClzeroLoopResult::ok` with `Rip` unchanged (infinite `#UD` loop). - `(cur & ~0xFFF) + 0x1000` wrapped to `0` on the top page of 64-bit address space. 3. `readable()` computed `BaseAddress + RegionSize` and `addr + got` without overflow/bounds checks, and `decode(nullptr, ...)` dereferenced `code[0]` and did not enforce the architectural 15-byte x86-64 instruction length limit when callers pass `avail > 15`. ### Changes - `runtime/src/cpu_emulation.h`: - Add `writable_region(addr, region_end)` returning the end of the contiguous committed writable `VirtualQuery` run, and step `try_clzero_loop()` by `region_end` (**16,384× fewer `VirtualQuery` syscalls** on a contiguous 64 MiB buffer while preserving exact page-boundary fault splitting). - Use overflow-free `limit <= start || limit - start <= 64`, clamp `span >= kMaxBatch` before rounding up to 64 bytes, and verify `total <= UINT64_MAX - start`. - Make `readable()` overflow-free using subtraction against `mbi.RegionSize`. - Guard `if (!code) return {};` and cap `avail <= 15` in `decode()`. - `runtime/test/cpu_emulation_test.cpp`: add tests for `decode(nullptr, ...)`, >15-byte overlong instruction rejection, `[UINT64_MAX - 63, UINT64_MAX)` wraparound rejection, and `[0, UINT64_MAX)` null-page fault. ### Verification - AI-assisted: yes (Antigravity agent by Google DeepMind). - GPUs tested: none (CPU-only verification on macOS arm64 using mock `VirtualQuery`/`VirtualProtect` Win32 stubs; Windows CI runs full `cpu_emulation_test` with real `VirtualAlloc` + SEH). - Compiled and ran `cpu_emulation.h` test harness with `clang++ -std=c++20 -Wall -Wextra -Werror`: - ASan+UBSan (`-O1 -g -fsanitize=address,undefined`): `vq_64m=1 res_max=2 (faulted) res_top=0 (no_match) fails=0`. - TSan (`-O1 -g -fsanitize=thread`): `vq_64m=1 res_max=2 res_top=0 fails=0`. - Release (`-O2`): `vq_64m=1 res_max=2 res_top=0 fails=0`. - Negative control against `main`'s `cpu_emulation.h`: - `main` issued `vq_64m=16384` `VirtualQuery` calls (vs **`1`** here — **16,384× reduction**), returned `res_max=1 (ok)` with `total=0` on `[0, UINT64_MAX)`, and crashed with SIGSEGV (exit 139) on `[UINT64_MAX - 63, UINT64_MAX)`. - `python3 -I scripts/check_no_game_data.py runtime/src/cpu_emulation.h runtime/test/cpu_emulation_test.cpp`: clean. - `python3 -I tests/test_text_write_line_endings.py`: 3/3 OK.
copilot-pull-request-reviewer[bot] commented 2026-11-25 18:40:05 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by copilot-pull-request-reviewer[bot] on 2026-11-25T18:40:05Z.

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:6063043506 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2035#pullrequestreview-6063043506). Originally posted by [copilot-pull-request-reviewer[bot]](https://github.com/apps/copilot-pull-request-reviewer) on 2026-11-25T18:40:05Z. **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.
moffington commented 2026-11-26 04:45:16 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by moffington on 2026-11-26T04:45:16Z.


Heads-up from #826, which touches the same CLZERO path: the region scan here rejects pages reported as MEM_RESERVE. For XMem, ordinary stores to reserved backing succeed after first-touch commit (the fault handler in xmem.cpp commits and resumes; xmem_test.cpp covers it), so CLZERO would report a write fault where the equivalent store succeeds.

#826 handles this in writable() by committing eligible XMem backing and then rechecking the destination's live protection, so read-only, no-access and guard pages still fault.

Is the blanket rejection intentional? If not, I'm happy to coordinate: the two headers conflict, so whichever lands second has to carry the first-touch check into writable_region(). #826 also adds a batched CLZERO test (crossing from reserved XMem into a protected page, in both SEC_RESERVE and SEC_COMMIT modes) that should run against the batched path here with little change.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7182872773 --> Imported from [ubiquitarianism/leonida](https://github.com/ubiquitarianism/leonida/pull/2035#issuecomment-7182872773). Originally posted by [moffington](https://github.com/moffington) on 2026-11-26T04:45:16Z. --- Heads-up from #826, which touches the same CLZERO path: the region scan here rejects pages reported as `MEM_RESERVE`. For XMem, ordinary stores to reserved backing succeed after first-touch commit (the fault handler in `xmem.cpp` commits and resumes; `xmem_test.cpp` covers it), so CLZERO would report a write fault where the equivalent store succeeds. #826 handles this in `writable()` by committing eligible XMem backing and then rechecking the destination's live protection, so read-only, no-access and guard pages still fault. Is the blanket rejection intentional? If not, I'm happy to coordinate: the two headers conflict, so whichever lands second has to carry the first-touch check into `writable_region()`. #826 also adds a batched CLZERO test (crossing from reserved XMem into a protected page, in both `SEC_RESERVE` and `SEC_COMMIT` modes) that should run against the batched path here with little change.
zmasi commented 2026-11-28 11:35:30 +00:00 (Migrated from github.com)

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


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 + 7f56e6a50 (claim #2570#issuecomment-7238618828):

  • Line-by-line diff audit: Clean (runtime/src/cpu_emulation.h, runtime/test/cpu_emulation_test.cpp); guards null code and caps avail at the 15-byte x86-64 architectural instruction limit in decode, steps try_clzero_loop by VirtualQuery contiguous writable regions via writable_region, and guards UINT64_MAX wraparound in readable and try_clzero_loop. check_no_game_data.py clean.
  • Red (4a54aedcb + PR test): cpu_emulation_test.exe crashes with 0xc0000005 (STATUS_ACCESS_VIOLATION on ce::decode(nullptr, 15)).
  • Green (4a54aedcb + 7f56e6a50 merge): Auto-merges cleanly (rc=0), compiles with 0 /W4 warnings, and cpu_emulation_test.exe passes (rc=0).

AI-assisted.

<!-- greyfinch-sync:ubiquitarianism/leonida:comment:7238652981 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2035#issuecomment-7238652981). Originally posted by [zmasi](https://github.com/zmasi) on 2026-11-28T11:35:30Z. --- 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` + `7f56e6a50` (claim `#2570#issuecomment-7238618828`): - **Line-by-line diff audit**: Clean (`runtime/src/cpu_emulation.h`, `runtime/test/cpu_emulation_test.cpp`); guards null `code` and caps `avail` at the 15-byte x86-64 architectural instruction limit in `decode`, steps `try_clzero_loop` by `VirtualQuery` contiguous writable regions via `writable_region`, and guards `UINT64_MAX` wraparound in `readable` and `try_clzero_loop`. `check_no_game_data.py` clean. - **Red (`4a54aedcb` + PR test)**: `cpu_emulation_test.exe` crashes with `0xc0000005` (`STATUS_ACCESS_VIOLATION` on `ce::decode(nullptr, 15)`). - **Green (`4a54aedcb` + `7f56e6a50` merge)**: Auto-merges cleanly (`rc=0`), compiles with `0` `/W4` warnings, and `cpu_emulation_test.exe` passes (`rc=0`). AI-assisted.
MoonEyes commented 2026-11-28 17:53:55 +00:00 (Migrated from github.com)

Imported from ubiquitarianism/leonida. Originally posted by MoonEyes on 2026-11-28T17:53:55Z.


Red/green: On main cpu_emulation_test crashes with 0xC0000005, and with the PR ctest -R "^cpu_emulation$" 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:7243373051 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2035#issuecomment-7243373051). Originally posted by [MoonEyes](https://github.com/MoonEyes) on 2026-11-28T17:53:55Z. --- Red/green: On main cpu_emulation_test crashes with 0xC0000005, and with the PR ctest -R "^cpu_emulation$" 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:58:24 +00:00 (Migrated from github.com)

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


Verified by OreoFR

  • Base: main c1ecf04ed + PR head 7f56e6a50; green run in a merge package of 16 PRs, no new ctest failure vs main
  • Test: ctest -R ^cpu_emulation$
  • Red on main: crash 0xC0000005 (try_clzero_loop on an unmapped region)
  • 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:7246405366 --> Imported from [ubiquitarianism/leonida](https://github.com/ProjectLeonida/mandy/pull/2035#issuecomment-7246405366). Originally posted by [OreoFR](https://github.com/OreoFR) on 2026-11-28T21:58:24Z. --- **Verified by OreoFR** - Base: main `c1ecf04ed` + PR head `7f56e6a50`; green run in a merge package of 16 PRs, no new ctest failure vs main - Test: `ctest -R ^cpu_emulation$` - Red on main: crash 0xC0000005 (try_clzero_loop on an unmapped region) - 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!2035
No description provided.