Skip to content

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

Open
IlyassRS3 wants to merge 1 commit into
ProjectLeonida:mainfrom
IlyassRS3:fix/rt-cpu-emulation-clzero-region-and-bounds
Open

IlyassRS3 wants to merge 1 commit into
ProjectLeonida:mainfrom
IlyassRS3:fix/rt-cpu-emulation-clzero-region-and-bounds

Conversation

@IlyassRS3

Copy link
Copy Markdown
Contributor

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 AI balanced review requested due to automatic review settings November 25, 2026 18:39

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Contributor

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants