Repository navigation
RT-500: gta6rt emulates the Zen 2 instructions an Intel CPU lacks (INSERTQ/EXTRQ, CLZERO, MONITORX/MWAITX, CLWB) - #7111
Krashgamer wants to merge 11 commits into
Conversation
… desktop CPU may lack The runtime runs the Xbox Series (Zen 2) executable natively, so an instruction the host CPU lacks raises #UD where it is reached. tools/cpu_feature_scan.py streams dumpbin /disasm like inline_scan.py, maps each instruction to its CPUID feature or privilege class (AMD-only, newer-Intel-only, not on Zen 2, privileged, kernel call, host query, baseline), and splits the counts by .pdata range. docs/cpu_features.md records the 1.0.2.1 result (counts only): 19 SSE4a, 10 CLZERO and 4 MONITORX/MWAITX sites (AMD only) and 8 CLWB sites, all real code; the privileged hits are jump-table data. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… the first Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…Q/EXTRQ, CLZERO, MONITORX/MWAITX, CLWB) The executable uses SSE4a INSERTQ, CLZERO and MONITORX/MWAITX (AMD only) and CLWB (Intel since Ice Lake) without asking CPUID (docs/cpu_features.md). A host without one raises #UD there. src/cpu_emulation.h adds a vectored handler that recognises those encodings at the faulting RIP, does the same work on the CONTEXT and steps past the instruction; gta6rt installs it before any image code runs, after the startup trace's handler so it runs first. One [rt] line names what the host lacks, one more per instruction on first use. cpu_emulation_test checks the decoder on hand-written encodings, the bit-field helpers and apply() on a synthetic CONTEXT, then runs every form for real from an executable buffer: natively on a Zen host, through the handler on an Intel one, with the same expected values. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8f3da11 to
62b410e
Compare
|
Hi @Krashgamer, a heads-up about overlap, and sorry for it: I did not see your "RT-500 part 2" claim on #6750 (I only looked at #6910 before claiming), so I opened four small PRs for the same instructions before your PR landed: #7055 (CLZERO and 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>
|
@tedin7 thanks, no harm done, and thanks for the pointers. Both are in #7111 now (3fe388b): a |
devnull34
left a comment
There was a problem hiding this comment.
Verified on Windows 11 (MSVC RelWithDebInfo):
- Built
cpu_emulation_testcleanly. cpu_emulation_test.exepassed all checks:- Validated CLZERO write-fault translation on unwritable lines (
EXCEPTION_ACCESS_VIOLATIONwith write flag and faulting line address). - Validated prefix handling: 0x66 prefix and segment overrides accepted on
0F 01 FC/FA/FB(CLZERO/MONITORX/MWAITX), while F2/F3 and LOCK properly trigger#UD. - SSE4a (INSERTQ/EXTRQ) and MONITORX/MWAITX emulation verified.
- Validated CLZERO write-fault translation on unwritable lines (
- CTest target
48: cpu_emulationpassed 100% (0.01s). - Whitespace clean (
git diff HEAD~1..HEAD --check).
|
Tested Without this PR: in a local combined build that gets the title as far as descriptor-heap setup, the title raises With this PR (and #7013) merged into the same build:
So the Tested and written by Claude (Claude Code). |
|
Tested
I didn't test tedin7's per-instruction PRs (#7055, #7096, #7098, #7100) separately; they cover the same stop. AI-assisted (Claude Code). |
|
Independent Linux/Intel verification of #7111 at Verification item TEST-1685, claim: #7231 (comment), carried into #7333. This verifies the existing RT-500 implementation; implementation ownership and the #7111/#7055 selection remain with their authors/maintainer. Depends on: #7013.
The passing alternate build uses the unmodified published test and header, configured with CPUID from the test reports SSE4a=0, MONITORX=0, CLZERO=0, CLWB=0. The passing companion's actual handler counters are INSERTQ=3, EXTRQ=2, CLZERO=2, MONITORX=1, MWAITX=1, CLWB=2. This covers the real unsupported-instruction path, both INSERTQ/EXTRQ forms, AVX upper-register preservation, CLZERO/read-only CLZERO, MONITORX/MWAITX, CLWB continuation, and unrelated UD2 refusal. A matching Environment: Intel Core i9-10900K, Arch Linux kernel Revisions: published head above; PR base ref at inspection |
|
INSERTQ register form: length and index are swapped (AI-assisted review; no game files).
lo(c, d.dst) = insert_bits(lo(c, d.dst), lo(c, d.src), unsigned(ctl >> 8) & 63, unsigned(ctl) & 63);
Hardware check: on a Ryzen 7 9800X3D (Zen 5, SSE4a present, so Fix that passes on Zen 5 (native) here: lo(c, d.dst) = insert_bits(lo(c, d.dst), lo(c, d.src), unsigned(ctl) & 63, unsigned(ctl >> 8) & 63);plus |
|
Hardware confirmation of @TheHoracio's INSERTQ finding on a second Zen generation, with a full sweep instead of one case: the register form is the only one that differs, and his one-line fix makes all four forms match the CPU exactly. AMD Ryzen 7 5700X (Zen 3, SSE4a native), Windows 11, MSVC 14.44,
So with One more data point, not a bug: in all four forms this Zen 3 zeroes xmm1[127:64] (destination high qword AI-assisted (Claude Code). Synthetic inputs only, no game files. |
… 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>
|
Thanks all, fixed in 978d525 (all checks pass on an i7-10700K, emulated path):
|
|
Data point for RT-500 on a hybrid Intel CPU: i9-12900K (Alder Lake, 8 P + 8 E cores, 24 logical), Windows 11 26300. CPUID read on every logical CPU, each pinned with
So on this host 33 of the 41 sites #7013 flags (insertq 19, clzero 10, monitorx/mwaitx 4) need the emulation this PR adds, and the 8 clwb sites run natively, with no difference between P and E cores. Static read and CPUID only; nothing of the game was run. AI-assisted (Claude Code). |
|
Retested the updated published head This follows my earlier report on
The detached published-head worktree has no tracked changes. Dependency remains #7013 ( Verification follow-up for TEST-1685. AI-assisted with Codex. |
|
Independent verification on Windows 11 with Intel CC150 (Coffee Lake Refresh, 8C/16T @ 3.50 GHz locked base frequency, Z390, no SSE4a/CLZERO/MONITORX/CLWB):
|
Independent Pre-Merge Verification on Intel Coffee Lake HostTested on native Windows 11 host with an Intel CC150 CPU (8 cores / 16 threads, Coffee Lake-R @ 3.50 GHz, Family 6 Model 158 Stepping 13) and MSVC 18.x ( Hardware Detection & TrappingBecause Coffee Lake lacks all four target extensions, the host query reports: Running
Test Suite & Repository Checks
Verified and ready to merge. |
|
checked: #711139b757a | with: clean merge onto Minor decoder notes (
|
…fix stay #UD An x86 instruction is at most 15 bytes, so decode() now reads no further than that: a CLZERO behind 13 prefixes or a 17-byte EXTRQ is refused even when more bytes are readable (the handler already passed at most 15). MONITORX and MWAITX are only taken without 66/F2/F3; CLZERO keeps the 66/F2/F3 forms measured on Zen 3. The title's MONITORX/MWAITX sites carry no prefix. New decoder checks cover both; they fail without the header change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
@SweatierKey thanks, both taken in
New decoder checks cover both, and all four fail with the old header. AI-assisted (Claude Code). |
|
Defect, reproduced at aa1e9aa: on a CPU that lacks these instructions, every emulated instruction costs 0.4-0.7 ms, spent in Host: Intel Core i5-13600KF (no SSE4a, CLZERO 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. I ran the code from an RWX buffer with
Cause. Suggested change. It keeps the handler's behaviour:
With it, Diff (runtime/src/cpu_emulation.h)diff --git a/runtime/src/cpu_emulation.h b/runtime/src/cpu_emulation.h
index ed27563dd..d03f2a8ae 100644
--- a/runtime/src/cpu_emulation.h
+++ b/runtime/src/cpu_emulation.h
@@ -135,6 +135,7 @@ inline uint64_t extract_bits(uint64_t src, unsigned len, unsigned idx) {
#ifdef _WIN32
#include <windows.h>
#include <intrin.h>
+#include <psapi.h>
#include <atomic>
#include <cstdio>
@@ -191,6 +192,17 @@ inline std::atomic<uint64_t>& count(Op op) {
// 0 when the page holding `addr` can be written; otherwise the exception a write raises there. A guard page loses
// its guard on that first touch and reports STATUS_GUARD_PAGE_VIOLATION, as the system does for a real access.
inline DWORD writable(uint64_t addr) {
+ // A resident page answers from the working set in constant time; VirtualQuery's cost grows with the rest of
+ // the region (it sizes the run of pages with the same attributes). A guard page is never resident.
+ PSAPI_WORKING_SET_EX_INFORMATION ws{};
+ ws.VirtualAddress = reinterpret_cast<void*>(addr & ~uint64_t(0xFFF));
+ if (QueryWorkingSetEx(GetCurrentProcess(), &ws, sizeof ws) && ws.VirtualAttributes.Valid) {
+ const DWORD wp = DWORD(ws.VirtualAttributes.Win32Protection);
+ const DWORD p = wp & 0xFF;
+ if (!(wp & PAGE_GUARD) && (p == PAGE_READWRITE || p == PAGE_WRITECOPY || p == PAGE_EXECUTE_READWRITE ||
+ p == PAGE_EXECUTE_WRITECOPY))
+ return 0;
+ }
MEMORY_BASIC_INFORMATION mbi;
if (!VirtualQuery(reinterpret_cast<void*>(addr), &mbi, sizeof mbi) || mbi.State != MEM_COMMIT)
return DWORD(STATUS_ACCESS_VIOLATION);
@@ -278,7 +290,9 @@ inline LONG CALLBACK handler(EXCEPTION_POINTERS* info) {
if (info->ExceptionRecord->ExceptionCode != STATUS_ILLEGAL_INSTRUCTION) return EXCEPTION_CONTINUE_SEARCH;
CONTEXT* c = info->ContextRecord;
uint8_t code[15] = {};
- const std::size_t avail = readable(c->Rip, sizeof code); // the instruction may end at a page boundary
+ // The CPU fetched this instruction from RIP's page, so only bytes past that page need a query.
+ const std::size_t in_page = std::size_t(0x1000 - (c->Rip & 0xFFF));
+ const std::size_t avail = in_page >= sizeof code ? sizeof code : in_page + readable(c->Rip + in_page, sizeof code - in_page);
std::memcpy(code, reinterpret_cast<const void*>(c->Rip), avail);
const Decoded d = decode(code, avail);
if (d.op == Op::none) return EXCEPTION_CONTINUE_SEARCH;Steps to reproduceOn an x64 CPU without SSE4a and CLZERO (any Intel), from a checkout of this PR: Output at aa1e9aa: // cl /nologo /O2 /EHa /std:c++20 /I runtime/src repro_7111.cpp (x64, on a CPU without SSE4a and CLZERO)
#include "cpu_emulation.h"
#include <chrono>
#include <cstdio>
#include <cstring>
int main() {
rt::cpu_emulation::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};
// mov eax,ecx ; L: insertq xmm0,xmm1,8,8 ; dec eax ; jnz L ; ret
const unsigned char iq[] = {0x89,0xC8, 0xF2,0x0F,0x78,0xC1,0x08,0x08, 0xFF,0xC8, 0x75,0xF6, 0xC3};
memcpy(t, cz, sizeof cz);
memcpy(t + 64, iq, sizeof iq);
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();
reinterpret_cast<void (*)(size_t)>(t + 64)(20000); // 20000 insertq
auto t2 = std::chrono::steady_clock::now();
std::printf("clzero %.1f us/fault, insertq %.1f us/fault\n",
std::chrono::duration<double, std::micro>(t1 - t0).count() / 16384,
std::chrono::duration<double, std::micro>(t2 - t1).count() / 20000);
}AI-assisted (Claude Code). |
|
Tested 39b757a (as merged in |
|
checked: #7111aa1e9aa | with: |
VirtualQuery sizes the run of pages with the same attributes after the address, so its cost grows with the rest of the region: in a mapped image or a large heap each emulated instruction took 0.4-1.5 ms (LastThylacine's measurement on ItsNotRexed#7111; 1.5 ms per CLZERO and 0.5 ms per INSERTQ on an i7-10700K). - The handler reads the instruction bytes in RIP's page without a query (the CPU just fetched them there) and queries only when the 15-byte window reaches into the next page. - writable() asks QueryWorkingSetEx about the line's page first; a resident, plainly writable page returns at once. Anything else (not resident, read-only, guard) takes the VirtualQuery path as before. Now about 2 us per emulated instruction. New live checks: CLZERO on a resident read-only page still raises an access violation, on a resident guard page a guard-page violation, and zeroes the line once the guard is gone. Suggested by LastThylacine in the ItsNotRexed#7111 review. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
@LastThylacine thanks, good catch. Taken as suggested in
Your repro on an i7-10700K (no SSE4a, CLZERO, MONITORX or CLWB), native Windows 11, MSVC 14.51:
New live checks cover the fast path's edge cases. A AI-assisted (Claude Code). |
|
Checked the new head Pass
Needs changes
AI-assisted: Codex GPT-6.2 Sol ran the checks, Claude Opus 5.5 reviewed the report. The retail executable (SHA-256 |
|
Runtime test of
AI-assisted: Codex GPT-6.2 Sol ran the tests, Claude Opus 5.5 reviewed the report. No game files used. |
… is not measured The 41 sites read as real code by their surroundings, but the scan shows neither which of them run nor whether a CPUID check keeps any of them from an Intel host. Say so instead of implying both (BatSmacker84's review on ItsNotRexed#7111). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…UID guard Intel boots reach CLZERO and CLWB, so no CPUID check keeps those two from an Intel host; for SSE4a and MONITORX that is not measured. Say so instead of "without asking CPUID" for all of them (BatSmacker84's review). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
@BatSmacker84 thanks for both runs. On the wording: agreed for CPUID, partly for "real code".
Which sites a boot reaches stays on the "Not measured" line in AI-assisted (Claude Code). |
|
Thanks. Re-checked AI-assisted: Claude Opus 5.5 compared the new commits with the earlier checks. |
|
checked: #7111 | with: applied the diff on main 5d74c27, built and ran cpu_emulation_test (all checks passed; host has every emulated instruction natively so #UD paths are structural only here), ran tests/test_cpu_feature_scan.py (22 tests OK) | on: Windows 11, RX 9060 XT host | result: PASS AI-assisted check. |
|
Independent Intel check of Host: Intel Core i5-12400F, Windows 11 Pro build 26200, MSVC x64. RTX 4060 Ti, driver 610.88 (32.0.16.1088); GPU not used.
Scope: standalone test only, not a full runtime build, CTest suite, merged-main integration, performance measurement or retail boot. Git/HTTPS downloads timed out locally, so the two files were fetched at the exact revision through the GitHub connector; their Git blob hashes were verified as Synthetic inputs only; no game files accessed. AI-assisted: Codex. |
|
checked: #711123bf06a | with: merged into a local retail-boot stack (main 867d922 + the boot PRs listed in #6824), retail 1.0.2.1 |
A measurement page in its own file: which stops of docs/retail_boot_chain.md and of #8554's ladder hold on an Intel CPU with #7111's emulation, the stop that is specific to a 16 GB host (the 6.1 GiB physical-page request against the commit limit, cleared by #7556), the frame loop to the 900 s timeout with stub pipelines, and what the layer refuses at that depth, including the console mesh-shader stream subobject. Counts and slot numbers only; no addresses. Plus the docs/README.md row. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01GDgoLP2cV47KaCDkbmckob
RT-500 part 2 (RT-5 / EXE), claimed in the coordination issue: #6750 (comment)
Depends on: #7013 (this branch sits on it; the change of this PR is the last commit,
gta6rt: emulate ...).What
#7013 measured that the retail executable contains four Zen 2 instructions: SSE4a
insertq(19 sites),clzero(10),monitorx/mwaitx(4) — no Intel CPU has these — andclwb(8, Intel only since Ice Lake). All 41 read as real code (by hand, statically). Boots on Intel hosts reachclzeroandclwb, so no CPUID check keeps those two from an Intel CPU; for the SSE4a and MONITORX sites that is not measured. On a host without one, the CPU raises#UDthere and the game stops.runtime/src/cpu_emulation.h: a vectored exception handler forSTATUS_ILLEGAL_INSTRUCTION. It decodes those encodings at the faulting RIP (prefixes, REX, ModRM/SIB/displacement forclwb), does the same work on the thread'sCONTEXTand steps past the instruction.insertq/extrq(immediate and register forms) work on the low quadword of the XMM register;clzerozeroes the 64-byte line rAX points into;monitorxandclwbneed nothing on coherent write-back memory;mwaitxreturns at once, an exit the manual allows. Anything else, and aclzeroon unwritable memory, is left to the next handler unchanged. Semantics are from the AMD64 APM (vol. 3 and 4) and the Intel SDM vol. 2; the sources are named in the header.runtime/src/main.cpp:gta6rtinstalls it before any image code runs, after the startup trace's handler so it runs first and an emulated instruction isn't logged as an exception. One[rt] cpu:line names what the host lacks; one more line the first time each instruction is emulated.runtime/README.md("PE loader") anddocs/cpu_features.mddescribe it. On a host that has the features the CPU runs them and the handler never sees them.Not done here: each emulated instruction costs an exception round trip, so a hot loop of them is slow; patching such sites in place would be a later step if a trace shows one is hot.
Tests
cpu_emulation_test(new, CTestcpu_emulation; no game files):67forclzero, allclwbaddressing forms (SIB, disp8/disp32, RIP-relative), and the near misses it must leave alone (0F 78without a prefix is VMREAD,0F AE /6without66is XSAVEOPT,66 0F AE /7is CLFLUSHOPT, a cut-off instruction, one longer than 15 bytes,monitorx/mwaitxwith66,F2orF3,ud2);applyon a syntheticCONTEXT(results, RIP, the kept upper quadword,clzeroon an unwritable line refused);insertqbetween AVX code and checksymm0[255:128]survives; another checks execution continues at the right byte after twoclwbs;ud2still faults.On this machine (Intel Core i7-10700K, which lacks all four features, so every form took the emulated path):
cpu_emulation_testall checks pass. Fullctest(RelWithDebInfo, MSVC 14.51, Ninja): 262 of 266 pass, includingloader,pe_loaderand everyrun_tiny_*test that startsgta6rt. The 4 failures (d3d12_vulkan_device,d3d12_indirect_dispatch_count,d3d12_indirect_rt,d3d12_bindless_churn_validated) are standalone D3D12/Vulkan tests that don't include or link any file this PR changes. Not run on an AMD host, so the native path of the live test is untested here; the retail executable was not run.Windows 11, Intel Core i7-10700K, NVIDIA RTX 3080 (driver 610.88), MSVC 14.51.
AI-assisted (Claude Code).
🤖 Generated with Claude Code