Skip to content

runtime: emulate CLZERO from a #UD handler on CPUs that lack it (RT-5, #7013) - #7055

Closed
tedin7 wants to merge 4 commits into
ProjectLeonida:mainfrom
tedin7:c2-ud-clzero
Closed

tedin7 wants to merge 4 commits into
ProjectLeonida:mainfrom
tedin7:c2-ud-clzero

Conversation

@tedin7

@tedin7 tedin7 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

What

Adds runtime/src/cpu_ud_emulate.{h,cpp}: a vectored exception handler that emulates x64 instructions the host CPU lacks, raised as STATUS_ILLEGAL_INSTRUCTION. It is table driven (kTable, one emulator function and one line per instruction), so MONITORX/MWAITX, CLWB and SSE4a follow as small separate PRs. This PR has one entry: CLZERO (0F 01 FC), which zeroes the 64-byte line at RAX & ~63 and moves RIP past it.

The handler is installed at startup in gta6rt only when the host CPU lacks CLZERO (CPUID 8000_0008h EBX bit 0). It returns EXCEPTION_CONTINUE_SEARCH for any other exception and any instruction it does not know. If the target line is not writable (read-only, no-access, guard, unmapped, non-canonical or wrapping), the emulator returns write_fault(address) and the dispatcher rewrites the record in place into STATUS_ACCESS_VIOLATION (ExceptionInformation = {1, line address}) and returns EXCEPTION_CONTINUE_SEARCH, so the next handler sees the fault the CPU would raise. EmulatorFn is unchanged. CLZERO is accepted with the legacy prefixes 66/F2/F3/2E/36/3E/26/64/65, a trailing REX, and 67 (EAX as address); LOCK stays a #UD. New test target cpu_ud_emulate_test, and a section in runtime/README.md.

Why

The executable targets the console's AMD CPU; a desktop CPU without CLZERO would die on the first one it reaches.
RT-500 (#7013) lists which instructions the executable contains; this is the run-time half for them, starting with CLZERO.

Tested

p2 (RTX 4090, AMD EPYC, so the CPU has CLZERO), cpu_ud_emulate_test under Wine: 46 checks, 0 failed.

  • Synthetic CONTEXT/EXCEPTION_RECORD: 64 bytes zeroed, both neighbouring lines intact, RIP+3, RAX unchanged, CONTINUE_EXECUTION; unaligned RAX (+37, +63) zeroes the containing line.
  • Passed on, nothing modified: 0F 01 FD, NOP, instruction cut off by unreadable memory, other exception code, null info, read-only page, no-access page, unmapped address.
  • Installed handler: UD2 reaches the next handler; the host's native CLZERO zeroes the same line the emulation does.
  • Negative control: old source with the new tests: 25 of 46 fail (every fault, prefix and 67 case); with LOCK accepted as a prefix, the 2 LOCK checks fail; restored, 0 fail.
  • Faults: read-only, no-access, guard, unmapped, non-canonical and wrapping lines give an access violation with write flag and line address, CONTEXT and memory untouched.
  • Prefixes: each of 66 F2 F3 2E 36 3E 26 64 65 and REX 40/48/4F, a 7-byte stack, 15-byte maximum; refused: LOCK, REX before a legacy prefix, two REX, 16 bytes.
  • Review fixes: a CLZERO line that wraps past the top of memory is declined, and the write runs under SEH so a racing unmap cannot crash the handler.
  • Not run: the real CLZERO-through-the-handler case needs a CPU without CLZERO; on this host the test prints SKIP.

@ItsNotRexed: an exe PR, as you asked.

Claim: #6910 (comment)

A table-driven dispatcher for STATUS_ILLEGAL_INSTRUCTION (cpu_ud_emulate), installed at startup only when the host CPU has no CLZERO. Unknown instructions and unwritable targets pass on untouched.

@SirKingg SirKingg left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

AI-assisted independent Windows review of 9ce3dda. Requesting changes for two reproducible behavioral differences:

  1. runtime/src/cpu_ud_emulate.cpp:45-46: a read-only target returns EXCEPTION_CONTINUE_SEARCH with the original STATUS_ILLEGAL_INSTRUCTION. On a Ryzen 7 5700X, the native CLZERO on the same read-only allocation instead raises STATUS_ACCESS_VIOLATION with write operation 1. An exception filter or later handler that expects the real write fault will therefore see the wrong exception and can fail to recover. The same issue applies to other rejected targets; please preserve the appropriate memory-fault semantics rather than passing on the #UD.

  2. runtime/src/cpu_ud_emulate.cpp:42: matching only 0F 01 FC at RIP rejects valid prefixed CLZERO encodings. With synthetic code in an isolated child process, native CLZERO on this AMD CPU succeeded and zeroed the line with prefixes 66, 48, F2, and F3; the dispatcher declined each corresponding synthetic #UD without zeroing. Please decode valid prefixes and instruction length (and distinguish invalid LOCK), or establish and explicitly constrain the supported instruction contract.

Validation: Windows x64, MSVC 2022, Ryzen 7 5700X, CPUID max extended leaf 80000023, 80000008 EBX[0]=1. Compiled the PR's test directly with MSVC and ran it in a child process: 20 checks passed; its real CLZERO-through-#UD test was skipped because this CPU implements CLZERO. Separately compiled and ran two synthetic-only child-process probes: native versus synthetic read-only fault, and native versus synthetic instruction prefixes. F0 was rejected natively with illegal instruction. No game files or external process memory were used. The actual unsupported-CPU CLZERO exception path was not exercised; no deterministic unmap/reprotect race stress test was run.

The SEH write can still partially modify the line if protection changes after VirtualQuery; a nested access violation also reaches vectored handlers before the local SEH filter. I did not reproduce that race, so this is a limitation of the review rather than a separate confirmed finding. Installation/removal uses an unsynchronized global; the current startup-only installation does not itself establish a concurrent lifecycle problem.

@dadsmallbuk1

Copy link
Copy Markdown

Tested 9ce3dda on an Intel Core i9-13900K (no CLZERO), NVIDIA GeForce RTX 5090 driver 617.42, Windows 11 (26200), native MSVC 2022 RelWithDebInfo: pass. This covers the real-hardware path the PR's own run had to skip.

  • cpu_ud_emulate_test: 20 checks, 0 failed, including the one that only runs on a CPU without the instruction: CLZERO on a CPU without it: emulated by the installed handler, the next handler never sees it. A real 0F 01 FC raised #UD and was emulated, not just a synthetic CONTEXT.
  • gta6rt --dry-run on the retail exe (own 1.0.2.1 copy; no title code runs) prints [rt] cpu: emulating instructions this CPU lacks at startup, so the CPUID check installs the handler on this CPU. Mapping is unchanged: 5 modules, 30 unimplemented imports.
  • Code read: writability is checked with VirtualQuery, the write runs under SEH, the emulator works on a copy of the CONTEXT, and anything unrecognised returns EXCEPTION_CONTINUE_SEARCH. No other behaviour changes.

AI-assisted (Claude Code).

@tedin7

tedin7 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @SirKingg, both points are fixed in 7e4b0ab: a CLZERO line that cannot be written (read-only, no-access, guard, unmapped, non-canonical, wrapping) is now reported as the STATUS_ACCESS_VIOLATION the CPU raises (write flag, line address) instead of the original #UD, and the decoder accepts the legacy prefixes (66 F2 F3 and the six segment overrides), a trailing REX and 67; LOCK stays a #UD. 46 checks, 25 of them fail on the old source. Two simplifications, tell me if you want them different: a guard page gives a plain access violation (the CPU would give STATUS_GUARD_PAGE_VIOLATION), and a non-canonical address reports the line address.

Krashgamer added a commit to Krashgamer/Leonida that referenced this pull request Nov 23, 2026
…ult; accept 66 on 0F 01 FC/FA/FB

A line CLZERO cannot write now reaches the next handlers as the access violation (or guard-page
violation) the instruction raises, with the write flag and the line address, instead of the #UD.
The 66 prefix and segment overrides are accepted on CLZERO/MONITORX/MWAITX; F2/F3 (other
instructions there, F3 0F 01 FA is MCOMMIT) and LOCK stay #UD. Points raised by SirKingg on ItsNotRexed#7055.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@Flyander Flyander left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Additional valid-prefix case reproduced at 7e4b0ab6. The decoder and its tests intentionally decline REX-before-legacy and repeated REX, but this Ryzen accepts both encodings as CLZERO (the non-final REX is ignored).

On this Windows 11 / Ryzen 7 5800X3D host, I executed synthetic stubs 48 89 C8 48 66 0F 01 FC C3 and 48 89 C8 48 48 0F 01 FC C3, passing an aligned buffer pointer. Both zeroed only the target 64-byte line; adjacent lines were unchanged. In runtime/test/cpu_ud_emulate_test.cpp, these are the rex_then_legacy and two_rex cases and both are asserted to be declined.

On a host without CLZERO, emulate_clzero returns 0 for these encodings and the handler passes their #UD onward, so they cannot be emulated. Please consider ignoring non-final REX prefixes and accepting the last REX, with these two cases as regression tests. I confirmed native decode and the current decoder refusal; I could not test the unsupported-CPU handler path on this CLZERO-capable host.

@tedin7

tedin7 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @Flyander: fixed in e1a4764. The last REX before 0F is the one that counts and a non-final REX is ignored, so 48 66 0F 01 FC and 48 48 0F 01 FC are emulated (the two declined cases are now emulation cases, plus a three-REX one). LOCK, the 15-byte limit and the 67 rule are unchanged.

@7ROBE

7ROBE commented Nov 23, 2026

Copy link
Copy Markdown

Tested e1a4764 on AMD Radeon RX 9060 XT, 26.11.2, Windows 11 (Intel i5-14600KF, CPU without CLZERO): pass

  • cmake -S runtime -B runtime/build -DLEONIDA_VULKAN_HEADERS_FETCH=ON && cmake --build runtime/build --config RelWithDebInfo --target cpu_ud_emulate_test gta6rt: built cleanly (MSVC 19.51.36263.0).
  • cpu_ud_emulate_test.exe: 47 checks, 0 failed — including the real #UD handler test (ok CLZERO on a CPU without it: emulated by the installed handler, the next handler never sees it).
  • ctest --test-dir runtime/build -C RelWithDebInfo -R '^cpu_ud_emulate$' --output-on-failure: 1/1 passed.

AI-assisted: yes (automated PR testing).

Krashgamer added a commit to Krashgamer/Leonida that referenced this pull request Nov 23, 2026
… xmm1[127:64]; AMD prefix forms; no SEH

- INSERTQ xmm, xmm took the length and index from swapped fields. The APM (vol. 4) has the length in
  xmm2[69:64] and the index in xmm2[77:72]; a Ryzen 9800X3D and a Ryzen 5700X agree (TheHoracio,
  Mayzkl on ItsNotRexed#7111). The measured 0x0810 case is a unit check now.
- INSERTQ/EXTRQ zero xmm1[127:64], as the Zen 3 measured in the same review does in all four forms.
- Decode REX bytes among the legacy prefixes (a non-final REX is ignored) and accept F2/F3 on CLZERO,
  as Zen 3 runs them (ItsNotRexed#7055's reviews); F2/F3 stay #UD on MONITORX/MWAITX.
- Check the CLZERO line's page and the instruction bytes' readability with VirtualQuery instead of
  catching a fault in a local __try, which clang-cl without /EHa does not cover for inline stores
  (venetanji on ItsNotRexed#7111).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@crastinator

Copy link
Copy Markdown
Contributor

Tested e1a47642 merged onto main 26ecd9f9 (clean merge) on a Zen 3 host under Wine: pass.

AMD Ryzen 7 5700X (Zen 3; has CLZERO, MONITORX/MWAITX, CLWB and SSE4a natively), CachyOS, Linux 7.3.5; runtime cross-compiled with clang-cl 23.1.5 + xwin (SDK 10.0.26100), tests run under Wine 11.22.

  • cpu_ud_emulate_test: 47 checks, 0 failed. The one SKIP is "CLZERO through the vectored handler: this CPU has CLZERO", as expected on a CPU that has it.
  • gta6rt and the test build with no new warnings from cpu_ud_emulate.*.

Also built and ran the three PRs stacked on this one (#7096, #7098, #7100), each merged onto main: all pass, results on each PR.

AI-assisted (Claude Code).

@throny throny left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Tested e1a4764 on Windows 11, MSVC 14.44, i9-12900K (no SSE4a/CLZERO/MONITORX, has CLWB): pass

This CPU lacks CLZERO (CPUID 8000_0008h EBX[0] = 0 on all 24 logical CPUs), so the emulation path through the real #UD runs here, not only the synthetic-CONTEXT path.

Commands (CMake + Ninja, RelWithDebInfo, VS 2022 BuildTools vcvars64, Vulkan SDK 1.4.363.0):

  • cmake --build b -j 6 at e1a4764: all 665 targets build.
  • cpu_ud_emulate_test.exe: 47 checks, 0 failed, no SKIP line, so both the 67-prefix case (memory below 4 GiB was found) and "CLZERO on a CPU without it: emulated by the installed handler" ran.
  • Full ctest -j 6 with the Vulkan ICD hidden (no GPU on this run): 230 passed, 33 skipped (GPU/game-file tests), 3 failed: d3d12_sparse_queue_family, vk_bindless_ps_tex, vk_bindless_ps_imgatomic, each at vkCreateInstance (-9) because I hid the driver; none touches the files this PR changes.

Negative control and extra edge cases (scratch program linking this head's cpu_ud_emulate.cpp, real instructions, not pushed): 11/11

  • Without the handler, mov rax,rcx; clzero; ret raises STATUS_ILLEGAL_INSTRUCTION here.
  • install() without force installs on this CPU.
  • Through the installed handler, real CLZERO, RAX = last byte of a line: that line zeroed, neighbours untouched.
  • Last line of a page followed by a no-access page: zeroed, no fault.
  • No-access page / read-only page: the __except after the handler sees STATUS_ACCESS_VIOLATION, ExceptionInformation = {1, line address}, memory unchanged; RAX = 0x30 gives the AV at line 0.
  • Guard page: AV, and the page is still PAGE_GUARD afterwards (not consumed).
  • 16 threads × 2,000 real CLZEROs through the handler: every line zeroed.
  • Cost: 1.35 µs per emulated CLZERO here.

Findings

  • runtime/src/cpu_ud_emulate.cpp:20 (behaviour, not a test failure): a guard page becomes STATUS_ACCESS_VIOLATION. On hardware a CLZERO into a guard page raises STATUS_GUARD_PAGE_VIOLATION, and on a thread's stack guard page the kernel grows the stack and the instruction succeeds. Emulated, the same instruction becomes an AV and the thread dies. This is unlikely for a heap clear but differs from the CPU; the header calls it intentional, so I'm only noting it.
  • Overlap: #7100, #7096 and #7098 are stacked on this head (it is an ancestor of all three). Each of them edits cpu_ud_emulate.cpp/.h (kTable, install()) differently, so git merge-tree shows content conflicts for 7096+7100, 7096+7098 and 7098+7100. Whichever lands second needs a rebase. #7111 adds a separate cpu_emulation.h for the same instructions and conflicts with this PR (and the three above) in runtime/src/main.cpp. If both merge, two vectored handlers would emulate CLZERO. Each merges cleanly into main on its own.

AI-assisted.

@shdann

shdann commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Tested e1a47642 on Windows 11, MSVC 14.51, Ninja, RelWithDebInfo. CPU: AMD Ryzen 7 7700X (Zen 4), which runs CLZERO, MONITORX/MWAITX, CLWB and SSE4a natively. An AI tool helped me to do these tests. No game files; hand-written operands only. Result: pass.

  • cpu_ud_emulate_test: 47 checks, 0 failed. As expected on this CPU, the check through the real #UD is skipped (the CPU has CLZERO).

I also built a separate program (not part of this pull request) that runs each instruction natively and then calls emulate() from this head with a synthetic CONTEXT and EXCEPTION_RECORD that hold the same operands, and compares the results bit for bit.

Case Result
0F 01 FC, RAX at offsets 0 to 255 from a line start (all alignments in four lines) 256 of 256: the 4 KiB buffer is equal after the native and after the emulated CLZERO; RIP advance 3
67 0F 01 FC, memory below 4 GiB, RAX bits 32 to 47 set (the CPU uses EAX) 5 of 5 offsets equal; RIP advance 4

This is a Zen 4 result for the native comparison. The earlier reports are from Intel CPUs (emulated path only) and a Zen 3 under Wine.

@rgvxsthi

Copy link
Copy Markdown
Contributor

Tested e1a476425 merged onto main 8575d36ed on an AMD Ryzen 7 9700X (Zen 5, has CLZERO), Windows 11 Pro 26300, native MSVC 19.44 RelWithDebInfo: pass.

  • cpu_ud_emulate_test: 47 checks, 0 failed (ctest -R cpu_ud passes). CLZERO runs natively here and zeroes the same line the emulation does passes. As expected on a CPU with CLZERO, the case that goes through the handler prints SKIP.
  • gta6rt --dry-run on the 1.0.2.1 executable with this build: exit 0, and no [rt] cpu: emulating line. On a CPU that has CLZERO, the handler stays uninstalled.
  • The previous head, 7e4b0ab6b, also passed here (46 checks, 0 failed).

This adds Zen 5 on native Windows to the runs above. The dry run also shows that with the real executable, the handler is not installed on a CPU that has CLZERO.

AI-assisted (Claude Code).

@LastThylacine

Copy link
Copy Markdown

Defect, reproduced at e1a4764: on a CPU without CLZERO, each emulated clzero costs about 0.3 ms, spent in writable()'s VirtualQuery.

Host: Intel Core i5-13600KF (no CLZERO, SSE4a or MONITORX; CLWB runs natively), Windows 11 Pro 26300 under Hyper-V (CPUID hypervisor bit set), MSVC 19.44. CPU only, no game files.

The emulation itself is correct with real faults. Code in an RWX buffer with install(): clzero at aligned and unaligned rax zeroes exactly its line, and cpu_ud_emulate_test passes (47 checks, 0 failed). I ran the same real-fault checks on #7100's head (2,800 random insertq against an APM reference, plus monitorx/mwaitx): 0 failures. Its ReadProcessMemory code fetch is cheap (2.6 µs per insertq fault, all in). The cost is in the line check:

Line clzero
in the middle of a 256 MiB read-write region 306 µs
the same with the change below 1.6 µs
a bare vectored-handler round trip on this host about 1 µs

Cause. VirtualQuery sizes the run of pages with the same attributes after the address, so its cost grows with the rest of the region. On this host it takes 0.3 µs in a 64 KiB region, 467 µs at the start of a 256 MiB one and 230 µs in its middle. QueryWorkingSetEx on one page takes 0.3 µs in every case. writable() calls VirtualQuery on every clzero, and heaps are large regions. At 306 µs, clearing 1 MiB (16,384 lines, one fault each) takes 5 s.

Suggested change. When the line is in one page, ask QueryWorkingSetEx first, and fall back to the existing VirtualQuery loop when the page isn't resident. A guard page is never resident, and zero_line()'s SEH stays the backstop. QueryWorkingSetEx resolves to K32QueryWorkingSetEx in kernel32, so no new library is needed. #7096, #7098 and #7100 carry the same writable() and would pick this up on a rebase.

Diff (runtime/src/cpu_ud_emulate.cpp)
diff --git a/runtime/src/cpu_ud_emulate.cpp b/runtime/src/cpu_ud_emulate.cpp
index 63b82caae..d6d179a20 100644
--- a/runtime/src/cpu_ud_emulate.cpp
+++ b/runtime/src/cpu_ud_emulate.cpp
@@ -1,6 +1,7 @@
 #include "cpu_ud_emulate.h"
 
 #include <intrin.h>
+#include <psapi.h>
 
 #include <cstring>
 
@@ -14,6 +15,18 @@ constexpr size_t kCacheLine = 64;
 bool writable(const void* p, size_t n) {
     const auto begin = reinterpret_cast<uintptr_t>(p);
     const uintptr_t end = begin + n;
+    // A resident page answers from the working set in constant time; VirtualQuery's cost grows with the rest of
+    // its region (it sizes the run of pages with the same attributes). A guard page is never resident.
+    if ((begin >> 12) == ((end - 1) >> 12)) {
+        PSAPI_WORKING_SET_EX_INFORMATION ws{};
+        ws.VirtualAddress = reinterpret_cast<void*>(begin & ~uintptr_t(0xFFF));
+        if (QueryWorkingSetEx(GetCurrentProcess(), &ws, sizeof ws) && ws.VirtualAttributes.Valid) {
+            const DWORD prot = DWORD(ws.VirtualAttributes.Win32Protection);
+            if (!(prot & (PAGE_GUARD | PAGE_NOACCESS)) &&
+                (prot & (PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY)))
+                return true;
+        }
+    }
     for (uintptr_t at = begin; at < end;) {
         MEMORY_BASIC_INFORMATION mbi;
         if (VirtualQuery(reinterpret_cast<const void*>(at), &mbi, sizeof mbi) != sizeof mbi) return false;
Steps to reproduce

On an x64 CPU without CLZERO (any Intel), from a checkout of this PR:

cl /nologo /O2 /EHa /std:c++20 repro_7055.cpp runtime/src/cpu_ud_emulate.cpp
repro_7055.exe

Output at e1a4764: clzero 305.5 us/fault. With the change: clzero 1.6 us/fault.

// cl /nologo /O2 /EHa /std:c++20 repro_7055.cpp runtime/src/cpu_ud_emulate.cpp   (x64, on a CPU without CLZERO)
#include "runtime/src/cpu_ud_emulate.h"
#include <chrono>
#include <cstdio>
#include <cstring>
int main() {
    rt::cpu_ud_emulate::install();
    const size_t text = 96u << 20, heap = 256u << 20;
    auto* t = static_cast<unsigned char*>(VirtualAlloc(nullptr, text, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
    auto* h = static_cast<unsigned char*>(VirtualAlloc(nullptr, heap, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
    memset(t, 0xCC, text);  // resident pages, as in a mapped image and a used heap
    memset(h, 0xAB, heap);
    // mov rax,rcx ; L: clzero ; add rax,40h ; cmp rax,rdx ; jb L ; ret
    const unsigned char cz[] = {0x48,0x89,0xC8, 0x0F,0x01,0xFC, 0x48,0x83,0xC0,0x40, 0x48,0x39,0xD0, 0x72,0xF4, 0xC3};
    memcpy(t, cz, sizeof cz);
    DWORD old;
    VirtualProtect(t, text, PAGE_EXECUTE_READ, &old);
    unsigned char* line = h + (128u << 20);
    auto t0 = std::chrono::steady_clock::now();
    reinterpret_cast<void (*)(void*, void*)>(t)(line, line + (1u << 20));  // 16384 clzero
    auto t1 = std::chrono::steady_clock::now();
    std::printf("clzero %.1f us/fault\n", std::chrono::duration<double, std::micro>(t1 - t0).count() / 16384);
}

AI-assisted (Claude Code).

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.