Repository navigation
Conversation
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.
…EH; fix the startup message quoting
SirKingg
left a comment
There was a problem hiding this comment.
AI-assisted independent Windows review of 9ce3dda. Requesting changes for two reproducible behavioral differences:
-
runtime/src/cpu_ud_emulate.cpp:45-46: a read-only target returnsEXCEPTION_CONTINUE_SEARCHwith the originalSTATUS_ILLEGAL_INSTRUCTION. On a Ryzen 7 5700X, the native CLZERO on the same read-only allocation instead raisesSTATUS_ACCESS_VIOLATIONwith 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. -
runtime/src/cpu_ud_emulate.cpp:42: matching only0F 01 FCat 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 prefixes66,48,F2, andF3; the dispatcher declined each corresponding synthetic #UD without zeroing. Please decode valid prefixes and instruction length (and distinguish invalidLOCK), 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.
|
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.
AI-assisted (Claude Code). |
|
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 |
…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
left a comment
There was a problem hiding this comment.
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.
|
Tested e1a4764 on AMD Radeon RX 9060 XT, 26.11.2, Windows 11 (Intel i5-14600KF, CPU without CLZERO): pass
AI-assisted: yes (automated PR testing). |
… 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>
|
Tested 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.
Also built and ran the three PRs stacked on this one (#7096, #7098, #7100), each merged onto AI-assisted (Claude Code). |
throny
left a comment
There was a problem hiding this comment.
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 6at e1a4764: all 665 targets build.cpu_ud_emulate_test.exe: 47 checks, 0 failed, noSKIPline, 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 6with 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 atvkCreateInstance(-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; retraisesSTATUS_ILLEGAL_INSTRUCTIONhere. install()withoutforceinstalls 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
__exceptafter the handler seesSTATUS_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_GUARDafterwards (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 becomesSTATUS_ACCESS_VIOLATION. On hardware a CLZERO into a guard page raisesSTATUS_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, sogit merge-treeshows content conflicts for 7096+7100, 7096+7098 and 7098+7100. Whichever lands second needs a rebase. #7111 adds a separatecpu_emulation.hfor the same instructions and conflicts with this PR (and the three above) inruntime/src/main.cpp. If both merge, two vectored handlers would emulate CLZERO. Each merges cleanly into main on its own.
AI-assisted.
|
Tested
I also built a separate program (not part of this pull request) that runs each instruction natively and then calls
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. |
|
Tested
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). |
|
Defect, reproduced at e1a4764: on a CPU without CLZERO, each emulated 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
Cause. Suggested change. When the line is in one page, ask 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 reproduceOn an x64 CPU without CLZERO (any Intel), from a checkout of this PR: Output at e1a4764: // 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). |
What
Adds
runtime/src/cpu_ud_emulate.{h,cpp}: a vectored exception handler that emulates x64 instructions the host CPU lacks, raised asSTATUS_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 atRAX & ~63and moves RIP past it.The handler is installed at startup in
gta6rtonly when the host CPU lacks CLZERO (CPUID 8000_0008h EBX bit 0). It returnsEXCEPTION_CONTINUE_SEARCHfor 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 returnswrite_fault(address)and the dispatcher rewrites the record in place intoSTATUS_ACCESS_VIOLATION(ExceptionInformation = {1, line address}) and returnsEXCEPTION_CONTINUE_SEARCH, so the next handler sees the fault the CPU would raise.EmulatorFnis unchanged. CLZERO is accepted with the legacy prefixes 66/F2/F3/2E/36/3E/26/64/65, a trailing REX, and67(EAX as address); LOCK stays a #UD. New test targetcpu_ud_emulate_test, and a section inruntime/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_testunder Wine: 46 checks, 0 failed.CONTEXT/EXCEPTION_RECORD: 64 bytes zeroed, both neighbouring lines intact, RIP+3, RAX unchanged,CONTINUE_EXECUTION; unaligned RAX (+37, +63) zeroes the containing line.SKIP.@ItsNotRexed: an exe PR, as you asked.
Claim: #6910 (comment)