You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
runtime: step try_clzero_loop by VirtualQuery regions and guard wraparound in cpu_emulation - #2035
Coordination item: RT-CPU-EMULATION-CLZERO-REGION-AND-BOUNDS (claimed on #1608).
Why
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.
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.
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().
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:
main issued vq_64m=16384VirtualQuery 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).
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.
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 file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Coordination item:
RT-CPU-EMULATION-CLZERO-REGION-AND-BOUNDS(claimed on #1608).Why
rt::cpu_emulation::try_clzero_loop()inruntime/src/cpu_emulation.hcalledwritable(cur)(oneVirtualQuerysyscall) on every 4 KiB page (next_page = (cur & ~0xFFF) + 0x1000), issuing 16,384VirtualQuerysyscalls for a single 64 MiB contiguousMEM_COMMIT | PAGE_READWRITEzeroing batch even thoughVirtualQueryalready returnsBaseAddress + RegionSizefor the entire uniform protection run.try_clzero_loop():limit <= start + 64wrapped whenstart = UINT64_MAX - 63(0xFFFFFFFFFFFFFFC0), andend = start + 64wrapped to0, skipping thefor (cur < end)writability check entirely and executingstd::memset(0xFFFFFFFFFFFFFFC0, 0, 64)(immediate SIGSEGV).(limit - start + 63) & ~63wrapped to0whenlimit - start > UINT64_MAX - 63(e.g.start = 0, limit = UINT64_MAX), leavingend == start, skippingwritable(0), and returningClzeroLoopResult::okwithRipunchanged (infinite#UDloop).(cur & ~0xFFF) + 0x1000wrapped to0on the top page of 64-bit address space.readable()computedBaseAddress + RegionSizeandaddr + gotwithout overflow/bounds checks, anddecode(nullptr, ...)dereferencedcode[0]and did not enforce the architectural 15-byte x86-64 instruction length limit when callers passavail > 15.Changes
runtime/src/cpu_emulation.h:writable_region(addr, region_end)returning the end of the contiguous committed writableVirtualQueryrun, and steptry_clzero_loop()byregion_end(16,384× fewerVirtualQuerysyscalls on a contiguous 64 MiB buffer while preserving exact page-boundary fault splitting).limit <= start || limit - start <= 64, clampspan >= kMaxBatchbefore rounding up to 64 bytes, and verifytotal <= UINT64_MAX - start.readable()overflow-free using subtraction againstmbi.RegionSize.if (!code) return {};and capavail <= 15indecode().runtime/test/cpu_emulation_test.cpp: add tests fordecode(nullptr, ...), >15-byte overlong instruction rejection,[UINT64_MAX - 63, UINT64_MAX)wraparound rejection, and[0, UINT64_MAX)null-page fault.Verification
VirtualQuery/VirtualProtectWin32 stubs; Windows CI runs fullcpu_emulation_testwith realVirtualAlloc+ SEH).cpu_emulation.htest harness withclang++ -std=c++20 -Wall -Wextra -Werror:-O1 -g -fsanitize=address,undefined):vq_64m=1 res_max=2 (faulted) res_top=0 (no_match) fails=0.-O1 -g -fsanitize=thread):vq_64m=1 res_max=2 res_top=0 fails=0.-O2):vq_64m=1 res_max=2 res_top=0 fails=0.main'scpu_emulation.h:mainissuedvq_64m=16384VirtualQuerycalls (vs1here — 16,384× reduction), returnedres_max=1 (ok)withtotal=0on[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.