[PR #2035] runtime: step try_clzero_loop by VirtualQuery regions and guard wraparound in cpu_emulation #2042

Open
opened 2026-11-26 21:19:50 +01:00 by 4ld0 · 0 comments
Owner

📋 Pull Request Information

Original PR: https://github.com/ubiquitarianism/leonida/pull/2035
Author: @IlyassRS3
Created: 11/25/2026
Status: 🔄 Open

Base: main ← Head: fix/rt-cpu-emulation-clzero-region-and-bounds


📝 Commits (1)

  • 7f56e6a runtime: step try_clzero_loop by VirtualQuery regions and guard wraparound in cpu_emulation

📊 Changes

2 files changed (+56 additions, -14 deletions)

View changed files

📝 runtime/src/cpu_emulation.h (+33 -14)
📝 runtime/test/cpu_emulation_test.cpp (+23 -0)

📄 Description

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.

🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.

## 📋 Pull Request Information **Original PR:** https://github.com/ubiquitarianism/leonida/pull/2035 **Author:** [@IlyassRS3](https://github.com/IlyassRS3) **Created:** 11/25/2026 **Status:** 🔄 Open **Base:** `main` ← **Head:** `fix/rt-cpu-emulation-clzero-region-and-bounds` --- ### 📝 Commits (1) - [`7f56e6a`](https://github.com/ubiquitarianism/leonida/commit/7f56e6a50b45ea8d760d93df855b6acc04594f0c) runtime: step try_clzero_loop by VirtualQuery regions and guard wraparound in cpu_emulation ### 📊 Changes **2 files changed** (+56 additions, -14 deletions) <details> <summary>View changed files</summary> 📝 `runtime/src/cpu_emulation.h` (+33 -14) 📝 `runtime/test/cpu_emulation_test.cpp` (+23 -0) </details> ### 📄 Description 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. --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
Sign in to join this conversation.
No labels
bug
pull-request
No milestone
No project
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.

Dependencies

No dependencies set

Reference
starred/leonida#2042
No description provided.