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

Open
github-bot wants to merge 1 commit from github-bot/gh-2035 into main AGit
Owner

@⁠IlyassRS3 on GitHub · 2026-11-25 18:39 UTC · original
IlyassRS3:fix/rt-cpu-emulation-clzero-region-and-bounds → main · +56 −14 · 2 files · 1 commits · open

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.
**@⁠IlyassRS3** on GitHub · 2026-11-25 18:39 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/2035) `IlyassRS3:fix/rt-cpu-emulation-clzero-region-and-bounds` → `main` · +56 −14 · 2 files · 1 commits · open 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.
github-bot locked as GitHub sync and limited conversation to collaborators 2026-11-26 10:15:37 +00:00
Author
Owner

@⁠copilot-pull-request-reviewer[bot] on GitHub · 2026-11-25 18:40 UTC · original · reviewed

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.

**@⁠copilot-pull-request-reviewer[bot]** on GitHub · 2026-11-25 18:40 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/2035#pullrequestreview-6063043506) · **reviewed** 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.
Author
Owner

@⁠moffington on GitHub · 2026-11-26 04:45 UTC · original

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.

**@⁠moffington** on GitHub · 2026-11-26 04:45 UTC · [original](https://github.com/ubiquitarianism/leonida/pull/2035#issuecomment-7182872773) 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.
This pull request can be merged automatically.
This branch is out-of-date with the base branch
You are not authorized to merge this pull request.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin '+refs/pull/2035/head:github-bot/gh-2035'
git switch 'github-bot/gh-2035'

Merge

Merge the changes and update on Forgejo.
git switch 'main'
git merge --no-ff 'github-bot/gh-2035'
git switch 'github-bot/gh-2035'
git rebase 'main'
git switch 'main'
git merge --ff-only 'github-bot/gh-2035'
git switch 'github-bot/gh-2035'
git rebase 'main'
git switch 'main'
git merge --no-ff 'github-bot/gh-2035'
git switch 'main'
git merge --squash 'github-bot/gh-2035'
git switch 'main'
git merge --ff-only 'github-bot/gh-2035'
git switch 'main'
git merge 'github-bot/gh-2035'
git push origin 'main'
This discussion has been locked. Commenting is limited to contributors.
No description provided.