Skip to content

RT-500: gta6rt emulates the Zen 2 instructions an Intel CPU lacks (INSERTQ/EXTRQ, CLZERO, MONITORX/MWAITX, CLWB) - #7111

Closed
Krashgamer wants to merge 11 commits into
ProjectLeonida:mainfrom
Krashgamer:runtime/emulate-zen2-insns
Closed

Krashgamer wants to merge 11 commits into
ProjectLeonida:mainfrom
Krashgamer:runtime/emulate-zen2-insns

Conversation

@Krashgamer

@Krashgamer Krashgamer commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

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 — and clwb (8, Intel only since Ice Lake). All 41 read as real code (by hand, statically). Boots on Intel hosts reach clzero and clwb, 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 #UD there and the game stops.

  • runtime/src/cpu_emulation.h: a vectored exception handler for STATUS_ILLEGAL_INSTRUCTION. It decodes those encodings at the faulting RIP (prefixes, REX, ModRM/SIB/displacement for clwb), does the same work on the thread's CONTEXT and steps past the instruction. insertq/extrq (immediate and register forms) work on the low quadword of the XMM register; clzero zeroes the 64-byte line rAX points into; monitorx and clwb need nothing on coherent write-back memory; mwaitx returns at once, an exit the manual allows. Anything else, and a clzero on 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: gta6rt installs 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") and docs/cpu_features.md describe 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, CTest cpu_emulation; no game files):

  • the decoder on hand-written encodings: every form, REX-extended registers, 67 for clzero, all clwb addressing forms (SIB, disp8/disp32, RIP-relative), and the near misses it must leave alone (0F 78 without a prefix is VMREAD, 0F AE /6 without 66 is XSAVEOPT, 66 0F AE /7 is CLFLUSHOPT, a cut-off instruction, one longer than 15 bytes, monitorx/mwaitx with 66, F2 or F3, ud2);
  • the bit-field helpers, and apply on a synthetic CONTEXT (results, RIP, the kept upper quadword, clzero on an unwritable line refused);
  • every form run for real from an executable buffer with the handler installed, against the same expected values: natively on a Zen host, through the handler on an Intel one. One case runs insertq between AVX code and checks ymm0[255:128] survives; another checks execution continues at the right byte after two clwbs; ud2 still faults.

On this machine (Intel Core i7-10700K, which lacks all four features, so every form took the emulated path): cpu_emulation_test all checks pass. Full ctest (RelWithDebInfo, MSVC 14.51, Ninja): 262 of 266 pass, including loader, pe_loader and every run_tiny_* test that starts gta6rt. 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

Krashgamer and others added 3 commits November 23, 2026 16:44
… 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>
@tedin7

tedin7 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

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 #UD dispatcher), #7096 (MONITORX/MWAITX), #7098 (CLWB) and #7100 (SSE4a INSERTQ), the last three stacked on #7055. Yours came first in claim order, so I do not want to block it. Whoever merges (or you) can pick which to keep, or take the tests of one into the other. Things my side already has, in case they help: #7055 turns an unwritable CLZERO line into the real write access violation and accepts prefixes after review by SirKingg, and dadsmallbuk1 ran the first version on an i9-13900K without CLZERO. I will not open more PRs for these four instructions.

…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>
@Krashgamer

Copy link
Copy Markdown
Contributor Author

@tedin7 thanks, no harm done, and thanks for the pointers. Both are in #7111 now (3fe388b): a clzero line that can't be written reaches the next handlers as the fault the write raised (access violation with the write flag and the line address, or guard-page violation) instead of the #UD, and 66 and segment prefixes are accepted on 0F 01 FC/FA/FB (F2/F3 and LOCK stay #UD). New live check: clzero on a read-only page gives an access violation; all checks pass on an i7-10700K. Happy for the maintainer to take whichever they prefer, or to fold your tests in.

@devnull34 devnull34 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.

Verified on Windows 11 (MSVC RelWithDebInfo):

  • Built cpu_emulation_test cleanly.
  • cpu_emulation_test.exe passed all checks:
    • Validated CLZERO write-fault translation on unwritable lines (EXCEPTION_ACCESS_VIOLATION with 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.
  • CTest target 48: cpu_emulation passed 100% (0.01s).
  • Whitespace clean (git diff HEAD~1..HEAD --check).

@theswiss24

Copy link
Copy Markdown

Tested 3fe388b39 with the retail executable on a CPU without CLWB: an Intel Core i9-9900K (Coffee Lake), Windows 11, RTX 4070. The title's code was only looked at locally; this is API names and counts.

Without this PR: in a local combined build that gets the title as far as descriptor-heap setup, the title raises 0xc000001d (illegal instruction). The faulting instruction is a clwb loop that writes back 64-byte lines over a range right after the title writes descriptors.

With this PR (and #7013) merged into the same build:

  • cpu_emulation_test passes on this CPU, with clzero, monitorx/mwaitx and clwb all on the emulated path.
  • The runtime logs this CPU lacks SSE4a CLZERO MONITORX CLWB; the game's uses are emulated, then this CPU has no CLWB; emulating it.
  • The title carries on past that loop to device slots 17/18/19 (views with translated CPU handles) and 70, the same in three runs out of three.

So the clwb path is reached by the real title at startup on a Coffee Lake host, and the emulation is what gets it through. That adds to the i7-10700K synthetic run and to the Zen 1 note. #7055 covers clzero only, so it wouldn't help here.

Tested and written by Claude (Claude Code).

@Pipodi

Pipodi commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Tested 3fe388b39 on the retail boot: pass. Intel CPU (no SSE4a/CLZERO/MONITORX), Windows 11, RTX 4090 / 617.42, own 1.0.2.1 copy, LEONIDA_D3D12=vulkan, on boot-integration plus #7115, #6891, #7201, #7163, #7330 and a local DirectStorage zlib stage. The four commits cherry-picked; only docs/README.md and runtime/CMakeLists.txt conflicted (I kept both sides).

  • Without it, the run stopped with C000001D (illegal instruction) on a CLZERO in a loop that clears cache lines, right after frame start.
  • With it, the start-up line reports this CPU lacks SSE4a CLZERO MONITORX; the game's uses are emulated, the first CLZERO is emulated, and the title goes on through queue slots 35, 16 and 32 and list slot 52: 1,691 D3D12 calls. It stops later at an unrelated access violation that I'm looking at now.

I didn't test tedin7's per-instruction PRs (#7055, #7096, #7098, #7100) separately; they cover the same stop.

AI-assisted (Claude Code).

@venetanji

Copy link
Copy Markdown
Contributor

Independent Linux/Intel verification of #7111 at 3fe388b39daccee1e8ff1b595be3889260552518: the existing instruction cases work with an explicit unoptimized asynchronous-SEH build, but the documented default cross-build fails here, and the CLZERO prefix gaps discussed on #7055 also affect this head.

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.

  1. runtime/src/cpu_emulation.h:51 and runtime/src/cpu_emulation.h:66 decline F2 0F 01 FC, F3 0F 01 FC, 48 66 0F 01 FC, and 48 48 0F 01 FC. A native Linux probe calling this exact head's decoder reports 8 checks, 4 failures; canonical and 66 CLZERO, LOCK refusal, and UD2 refusal pass. The expected acceptance comes from the existing native-AMD reviews by SirKingg and by Flyander. I independently reproduced this head's decoder refusals; I did not repeat the native-AMD executions. runtime/test/cpu_emulation_test.cpp:61 currently asserts that the F2 encoding should be declined. The MCOMMIT distinction for F3 0F 01 FA still needs to be retained when reconciling these cases.
  2. The documented clang-cl/xwin RelWithDebInfo build (/EHsc /O2 /Ob1) builds successfully, but ctest -R '^cpu_emulation$' fails before handler installation. The fault is the optimized zeroing store in apply(CLZERO) at RVA 0x45D8, writing the synthetic null line; the local SEH does not catch it in this configuration. The same published head already documents and applies Clang's /EHa requirement for the fault-catching tiny_dll fixture (runtime/CMakeLists.txt:501), while cpu_emulation_test has no such option. Supplemental /EHsc /Od /Ob0 also faults. With /EHa /O2 /Ob1, an instrumented companion reaches all 69 checks but fails 2 memory-fault checks: the synthetic fault record remains zero and the read-only live case's captured exception code is zero. With /EHa /Od /Ob0, both checks receive the expected access violation. The initial /EHsc failure therefore matches an existing compiler-configuration requirement; the optimized /EHa metadata failure remains unresolved. I have not isolated a compiler bug independently of Wine and make no native-Windows regression claim.

The passing alternate build uses the unmodified published test and header, configured with -DCMAKE_CXX_FLAGS_RELWITHDEBINFO='/Zi /Od /Ob0 /DNDEBUG /EHa'. It gives CTest 1/1 passed. A separate copy that only adds counters and diagnostics reports 69 checks, 0 failures: 31 decoder, 7 bit helpers, 11 synthetic-context, 1 handler installation, and 19 live checks. Both host-conditional checks and the read-only allocation case run; zero CPU cases are skipped. The test uses ordinary check(...) predicates, which remain active with the normal RelWithDebInfo NDEBUG setting.

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 /EHa /Od /Ob0 negative-control copy that deliberately omits handler installation fails 18 of 69 predicates, with all handler counters zero. That is a synthetic negative control, not a base-build comparison. The dependency's tests/test_cpu_feature_scan.py also passes all 22 tests.

Environment: Intel Core i9-10900K, Arch Linux kernel 7.2.11-arch1-1, Wine 11.20, clang-cl/lld 23.1.3, xwin-layout MSVC CRT/STL 14.44.17.14, Windows SDK 10.0.26100. All Wine processes run with a separate prefix, a 45-second outer bound, Xvfb/software EGL, and an unshared network namespace. No GPU devices, game binaries, or game data are exposed to the test sandbox.

Revisions: published head above; PR base ref at inspection ed3ae01e2ee3643e88e5f03c4b577744f1e526ac, merge base 413ffd6eb25da7e13907928bbc87e4c7e04fe026, scanner dependency head 2f9e1e3e3c32892a6145ac9f526b73274da7d040. No base runtime build, full CTest suite, AMD native execution, or native Windows run was performed. The detached source worktree remains unchanged. AI-assisted with Codex.

@TheHoracio

Copy link
Copy Markdown
Contributor

INSERTQ register form: length and index are swapped (AI-assisted review; no game files).

runtime/src/cpu_emulation.h, Op::insertq_reg:

lo(c, d.dst) = insert_bits(lo(c, d.dst), lo(c, d.src), unsigned(ctl >> 8) & 63, unsigned(ctl) & 63);

insert_bits takes (dst, src, len, idx), so this reads the length from xmm2[77:72] and the index from xmm2[69:64]. The AMD APM (vol. 4, INSERTQ) has it the other way around: xmm2[69:64] is the length and xmm2[77:72] the index, the same order as EXTRQ's xmm2[5:0]/[13:8] (which this file decodes correctly). #7100's cpu_ud_emulate.cpp reads it the APM way too.

Hardware check: on a Ryzen 7 9800X3D (Zen 5, SSE4a present, so test_live runs the instruction natively), cpu_emulation_test fails insertq reg result: the CPU's answer is the APM order, while the expected value (insert_bits(in[0], in[2], 7, 33) for in[3] = (7 << 8) | 33) follows the swapped decode. The unit check insertq reg takes len and idx from the upper half encodes the same swap ((12 << 8) | 20 commented as "len 12 at bits 77:72"). On an Intel CPU, where the emulation actually runs, both tests pass and the title would get the wrong bit field.

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 ce::insert_bits(in[0], in[2], 33, 7) in test_live and High = (20ll << 8) | 12 for the unit check. Worth running the live test on an Intel CPU after the change to see the emulated path agree.

@Mayzkl

Mayzkl commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

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, runtime/src/cpu_emulation.h at 3fe388b39. A standalone harness (not part of the PR) calls the header's decode() on the real encodings and apply() on a CONTEXT, and compares against the CPU via the MSVC SSE4a intrinsics (_mm_insert_si64, _mm_inserti_si64, _mm_extract_si64, _mm_extracti_si64). Every len 0..63 × idx 0..63, 32 random operand pairs each, random bits in the unused control bits:

Form len+idx ≤ 64 (defined) len+idx > 64 with the swap fix
INSERTQ xmm, xmm (F2 0F 79) 65,437 / 66,560 differ 63,462 / 64,512 differ 0 / 131,072
INSERTQ xmm, xmm, imm, imm (F2 0F 78) 0 / 66,560 0 / 64,512 0
EXTRQ xmm, xmm (66 0F 79) 0 / 66,560 0 / 64,512 0
EXTRQ xmm, imm, imm (66 0F 78 /0) 0 / 66,560 0 / 64,512 0

So with len = ctl & 63, idx = (ctl >> 8) & 63 the emulation agrees with this CPU on every input, the undefined len + idx > 64 region included (both keep the bits that fit). A by-hand check of the native register form: control 0x0810 (bits 5:0 = 16, bits 13:8 = 8) on 0x1234 inserts 16 bits of 0xAB at bit 8 → 0xAB34, i.e. length from xmm2[69:64], as the APM says.

One more data point, not a bug: in all four forms this Zen 3 zeroes xmm1[127:64] (destination high qword 0x1111222233334444 came back 0), while the emulator keeps it. The APM calls it undefined, so either is allowed. Zeroing would match what a Zen host does, if you'd rather have the emulated path behave like the native one.

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>
@Krashgamer

Copy link
Copy Markdown
Contributor Author

Thanks all, fixed in 978d525 (all checks pass on an i7-10700K, emulated path):

  • @TheHoracio @Mayzkl: right, the register form of insertq had length and index swapped. It now reads the length from xmm2[69:64] and the index from xmm2[77:72] (APM vol. 4). The unit and live expectations follow, and Mayzkl's 0x0810 case is a fixed check. All four forms also zero xmm1[127:64] now, matching your Zen 3 measurement.
  • @venetanji: (1) REX bytes are decoded among the legacy prefixes (a non-final REX is ignored), and clzero accepts F2/F3, per the Zen 3 measurements on runtime: emulate CLZERO from a #UD handler on CPUs that lack it (RT-5, #7013) #7055. F2/F3 stay #UD on monitorx/mwaitx (MCOMMIT), and LOCK stays #UD. New decoder checks cover 48 66, 48 48, F2, F3. (2) No local __try is left: the clzero line's page and the instruction bytes are checked with VirtualQuery before the access, so the result no longer depends on /EHa or optimization. I couldn't rerun the clang-cl/xwin build here.
  • @devnull34: thanks for the run. It was on the earlier head, so the prefix line in it describes the old behaviour.

@throny

throny commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

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 SetThreadGroupAffinity:

  • SSE4a (0x80000001 ECX[6]), MONITORX (ECX[29]), CLZERO (0x80000008 EBX[0]): absent on all 24.
  • CLWB (leaf 7 EBX[24]): present on all 16 P-core threads (core type 0x40) and all 8 E cores (0x20).

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).

@venetanji

Copy link
Copy Markdown
Contributor

Retested the updated published head 978d525d99413cce232efde07efbf392d1e782a5 on Intel i9-10900K / Arch Linux / Wine 11.20 / clang-cl and lld 23.1.3: the unmodified cpu_emulation CTest now passes with the standard optimized RelWithDebInfo configuration (/EHsc /O2 /Ob1, no /EHa or /Od override).

This follows my earlier report on 3fe388b39; its default cross-build failure and four CLZERO prefix refusals are resolved in this retest.

  • Built with the repository's clang-cl/xwin CMake toolchain, xwin-layout MSVC CRT/STL 14.44.17.14 and Windows SDK 10.0.26100; cmake --build out/intel-cpu-windows --target cpu_emulation_test --parallel 2, then ctest -R '^cpu_emulation$' --output-on-failure -V: 1/1 passed, exit 0.
  • A separate copy adding only counters reports 77 checks, 0 failures: 38 decoder, 7 bit-helper, 12 synthetic-context, 1 installation, 19 live checks. Both host-conditional cases and the read-only allocation case run; zero CPU cases skipped. All published positive checks remain active.
  • CPUID again reports SSE4a=0, MONITORX=0, CLZERO=0, CLWB=0. Actual handler counters: INSERTQ=3, EXTRQ=2, CLZERO=2, MONITORX=1, MWAITX=1, CLWB=2. The updated INSERTQ register-control expectation and fixed 0x0810 case pass, along with XMM high-half zeroing, YMM upper-half preservation, null/read-only CLZERO fault handling, and unrelated UD2 refusal.
  • The unchanged native-Linux decoder probe from the earlier report now gives 8 checks, 0 failures. This includes the formerly refused F2/F3 CLZERO and non-final/repeated REX forms, plus canonical/66 and LOCK/UD2 refusal controls. This verifies the decoder against the cited AMD measurements; it is not a new AMD-native execution result.
  • A matching optimized negative-control copy that deliberately omits handler installation fails 17 of 77 predicates, with every handler counter zero. This is a synthetic control, not a base runtime comparison.

The detached published-head worktree has no tracked changes. Dependency remains #7013 (2f9e1e3e3c32892a6145ac9f526b73274da7d040, included in this branch). Wine runs use a separate prefix, Xvfb/software EGL, an unshared network namespace, and a 45-second outer limit. No GPU devices or game files are exposed. No full runtime suite, native Windows/AMD run, game boot, or concurrent unmap/protection-change stress test was performed.

Verification follow-up for TEST-1685. AI-assisted with Codex.

@Cryptoteep

Copy link
Copy Markdown
Contributor

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):

  • Built cpu_emulation_test cleanly under MSVC 19.51.36231 (RelWithDebInfo, Ninja).
  • cpu_emulation_test.exe passed all checks:
    • Host CPU confirmed without all 4 instruction classes (host: SSE4a 0, MONITORX 0, CLZERO 0, CLWB 0).
    • Emulation paths executed and validated:
      • insertq imm: emulated
      • extrq: emulated
      • clzero: emulated
      • monitorx/mwaitx: emulated
      • clwb: emulated
    • YMM upper-half preservation confirmed across AVX transitions.
    • Exception propagation on unwritable lines confirmed.
  • CTest #48: cpu_emulation passed in 0.01 s.
  • python -I tests/test_cpu_feature_scan.py passed all 22 tests in 0.065 s.
  • Synthetic inputs only, clean of game data.

@Cryptoteep

Copy link
Copy Markdown
Contributor

Independent Pre-Merge Verification on Intel Coffee Lake Host

Tested 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 (/std:c++20 /O2).

Hardware Detection & Trapping

Because Coffee Lake lacks all four target extensions, the host query reports:

host: SSE4a 0, MONITORX 0, CLZERO 0, CLWB 0

Running cpu_emulation_test.exe triggered the #UD vectored exception handler for each instruction sequence:

  • insertq imm: emulated (proper bitfield insertion into low quadword of XMM)
  • extrq: emulated (low quadword bit extraction)
  • clzero: emulated (zeroes 64-byte aligned cache line)
  • monitorx/mwaitx: emulated (immediate return)
  • clwb: emulated (treated as write-back NOP on cache-coherent host memory)
  • Output: cpu_emulation: all checks passed.

Test Suite & Repository Checks

  • python -I scripts/check_no_game_data.py runtime/src/cpu_emulation.h runtime/test/cpu_emulation_test.cpp tools/cpu_feature_scan.py tests/test_cpu_feature_scan.py docs/cpu_features.md -> Clean (0 bytes).
  • python -I tests/test_cpu_feature_scan.py -> 22/22 tests passed.
  • Merge test against upstream/main (098131177): Merges cleanly with zero conflicts (docs/design.md, runtime/CMakeLists.txt resolve automatically).

Verified and ready to merge.

@SweatierKey

Copy link
Copy Markdown
Contributor

checked: #711139b757a | with: clean merge onto main@6312c057f, python3 -I tests/test_cpu_feature_scan.py, python3 -m unittest tests/test_docs_repo_paths.py, python3 -I scripts/check_no_game_data.py (all 10 files), plus a standalone GCC C++20 -O2 -Wall -Wextra -Wconversion -Werror -fsanitize=address,undefined probe of the portable portion of runtime/src/cpu_emulation.h (decode, insert_bits, extract_bits) | on: Linux x86-64, GCC C++20, Python 3.13, CPU-only (Windows VEH / cpu_emulation_test not run on this host) | result: test_cpu_feature_scan.py 22/22 OK, test_docs_repo_paths.py 3/3 OK, check_no_game_data.py exit 0, portable cpu_emulation.h compiles warning-free under -Werror + ASan/UBSan; two minor decoder edge-case notes below.

Minor decoder notes (runtime/src/cpu_emulation.h:decode)

  1. 15-byte x86-64 instruction-length cap: the prefix loop bounds i < 14, so when avail > 15 a 13–14 byte prefix run followed by 0F 01 FC or 0F 78 C0 08 04 decodes with length = 16 (clzero) and length = 19 (extrq_imm) respectively. The VEH path passes at most 15 bytes via readable(), so this doesn't hurt live execution, but checking if (i > 15) return {}; inside decode() keeps the decoder self-contained against invalid >15-byte encodings.
  2. 66 prefix on MONITORX / MWAITX: (pf2 || pf3) && m != 0xFC currently accepts 66 0F 01 FA (monitorx) and 66 0F 01 FB (mwaitx). Per AMD64 APM Vol. 3, 66 is #UD on MONITORX/MWAITX (unlike CLZERO, where 66 was measured on Zen 3), so checking (p66 || pf2 || pf3) && m != 0xFC is tighter.

(Note: tests/test_docs_env_vars.py currently fails on main@6312c057f solely for LEONIDA_TLS_GA_PATCH in pe_loader.cpp:519 — unrelated to this PR. Synthetic inputs only; no game data.)

…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>
@Krashgamer

Copy link
Copy Markdown
Contributor Author

@SweatierKey thanks, both taken in aa1e9aa0c:

  1. decode() now reads at most 15 bytes, so a clzero behind 13 prefixes or a 17-byte extrq is refused even when more bytes are readable.
  2. monitorx/mwaitx are only taken without 66, F2 or F3. clzero keeps the 66/F2/F3 forms measured on Zen 3. The title's own monitorx/mwaitx sites have no prefix, so the boot is unaffected.

New decoder checks cover both, and all four fail with the old header. cpu_emulation passes on an i7-10700K (MSVC 14.51, RelWithDebInfo).

AI-assisted (Claude Code).

@LastThylacine

Copy link
Copy Markdown

Defect, reproduced at aa1e9aa: on a CPU that lacks these instructions, every emulated instruction costs 0.4-0.7 ms, spent in VirtualQuery.

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 install() and compared 2,800 random insertq (both forms, xmm0-15 with REX) against an APM reference; clzero at aligned and unaligned rax and monitorx/mwaitx were checked too. 0 failures, and cpu_emulation_test passes. On this host every one of these encodings raises STATUS_ILLEGAL_INSTRUCTION, Hyper-V included. Each fault is slow, though:

Code and line insertq clzero
code at the start of a 96 MiB execute-read region, line in the middle of a 256 MiB read-write region 380 µs 680 µs
the same with the change below 1.0 µs 1.3 µ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. The handler calls VirtualQuery on every fault for the code at RIP (readable), and on every clzero for the line (writable). A mapped executable's code is one large execute-read region, and heaps are large regions too. At 680 µs, clearing 1 MiB (16,384 lines, one fault each) takes 11 s.

Suggested change. It keeps the handler's behaviour:

  • The CPU has just fetched the instruction from RIP's page, so the code only needs a query when the 15-byte window crosses into the next page.
  • For the line, ask QueryWorkingSetEx about its one page first, and fall back to the existing VirtualQuery path when the page isn't resident. A guard page is never resident, so the guard handling is unchanged. QueryWorkingSetEx resolves to K32QueryWorkingSetEx in kernel32, so no new library is needed.

With it, cpu_emulation_test passes, my real-fault checks pass, and the repro gives the numbers in the second row.

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 reproduce

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

cl /nologo /O2 /EHa /std:c++20 /I runtime/src repro_7111.cpp
repro_7111.exe

Output at aa1e9aa: clzero 680.0 us/fault, insertq 379.8 us/fault. With the change: clzero 1.3 us/fault, insertq 1.0 us/fault.

// 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).

@sh1shu1

sh1shu1 commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

Tested 39b757a (as merged in tibzejoker:rt5-integration 5fef1f1) on Intel i7-8700 (Coffee Lake: no SSE4a, CLZERO, MONITORX or CLWB), RTX 4070 SUPER 616.92, Windows 11 26200, native MSVC RelWithDebInfo: pass on the retail executable (own 1.0.2.1 copy, outbound blocked). [rt] cpu: names the four as emulated; three --runs never fault on an instruction and go on past device creation to 13k-62k D3D12 calls (stops 26-27 of the boot ladder). Not run: ctest. Counts in #9401 (comment). AI-assisted (Claude Code, Claude Fable 5.1).

@Anarbb

Anarbb commented Nov 23, 2026

Copy link
Copy Markdown

checked: #7111aa1e9aa | with: cmake --build runtime/build/windows --target gta6rt gta6rt_tls_host (clang-cl, lld-link and xwin, cross-built on Linux), retail run with LEONIDA_D3D12=vulkan | on: Linux 6.18 (CachyOS), Proton-CachyOS 11.0 (wine-11.0), Intel Core i5-12400F (no SSE4a, CLZERO or MONITORX), RTX 4060, driver 620.70.06 | result: pass. [rt] cpu: names SSE4a, CLZERO and MONITORX as missing, the retail boot runs through the emulated instructions under Wine with no #UD, and with the base below the title reaches its frame loop and runs 330 s without an exception. Base: tibzejoker/rt5-integration@5fef1f1b1 (already merges #7111) + #8783 + #7216 + #7290 + #6885 + #6981 + #7529 + #8890 + #7746 + #8225. Not run on AMD.
agent: yes

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>
@Krashgamer

Copy link
Copy Markdown
Contributor Author

@LastThylacine thanks, good catch. Taken as suggested in c5f025fac:

  • The handler reads the instruction bytes in RIP's page without a query, and queries only when the 15-byte window reaches into the next page.
  • writable() asks QueryWorkingSetEx about the line's page first. A page that isn't resident, isn't plainly writable, or carries a guard takes the existing VirtualQuery path.

Your repro on an i7-10700K (no SSE4a, CLZERO, MONITORX or CLWB), native Windows 11, MSVC 14.51:

clzero insertq
aa1e9aa0c 1,458 µs/fault 533 µs/fault
c5f025fac 2.1 µs/fault 1.6 µs/fault

New live checks cover the fast path's edge cases. A clzero on a page that was written (so it's resident) and then made read-only still raises an access violation. The same page with PAGE_GUARD raises a guard-page violation, and the next clzero zeroes the line once the guard is gone. cpu_emulation passes and gta6rt builds.

AI-assisted (Claude Code).

@BatSmacker84

Copy link
Copy Markdown

Checked the new head c5f025fac (merges cleanly onto main 5d74c2723) against the retail executable on Windows 11 26200. Static reads and CPU tests only; the new native tests and hot-path timings need a runtime build and weren't run.

Pass

  • Instruction-family counts (total / inside .pdata): SSE4a 19/17, CLZERO 10/0, MONITORX/MWAITX 4/4, CLWB 8/6.
  • Scanner tests 22/22.
  • Since aa1e9aa0c, the handler uses QueryWorkingSetEx for resident writable CLZERO pages, no longer queries RIP's first page, and adds resident read-only and guard cases.

Needs changes

  • The "all of them are real code" and "without asking CPUID" wording is unchanged and still goes beyond static evidence. Suggested: "Static disassembly finds 41 candidate sites across four instruction families. Earlier boot traces reached CLZERO and CLWB on the tested stacks. Reachability of the remaining sites and CPUID gating remain unverified."

AI-assisted: Codex GPT-6.2 Sol ran the checks, Claude Opus 5.5 reviewed the report. The retail executable (SHA-256 e95020b2…8993) and package PE images were read in place; static reads and CPU tests only, and only names, counts and constants the PR uses are given.

@BatSmacker84

Copy link
Copy Markdown

Runtime test of c5f025fac merged onto main 5d74c2723 on AMD Ryzen 7 9800X3D (Zen 5), Windows 11 26200, MSVC 19.44 RelWithDebInfo: pass.

  • 19/19 ctest entries pass, including the new native tests; the live cases run on native hardware here (this CPU has the instructions, so it covers the native path, not the Intel emulation path).
  • This complements my earlier static check of the same head (counts reproduce; wording still to narrow).

AI-assisted: Codex GPT-6.2 Sol ran the tests, Claude Opus 5.5 reviewed the report. No game files used.

Krashgamer and others added 3 commits November 23, 2026 22:25
… 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>
@Krashgamer

Copy link
Copy Markdown
Contributor Author

@BatSmacker84 thanks for both runs. On the wording: agreed for CPUID, partly for "real code".

  • "Real code" was a hand reading of each site's surroundings, which separates instructions from data decoded as instructions. It says nothing about which sites run. docs/cpu_features.md now says it "read as real code" and that this is a static reading that doesn't show which sites run or whether a CPUID check guards any of them (a56267c80 on RT-500: cpu_feature_scan lists the executable's CPU instructions a desktop CPU may lack (AMD-only SSE4a, CLZERO, MONITORX; CLWB) #7013, merged here).
  • CPUID: nobody measured the guards. What the boots on Intel hosts show is that clzero and clwb are reached, so no CPUID check keeps those two from an Intel CPU. For the SSE4a and MONITORX sites it is open. runtime/README.md now says exactly that (23bf06a34), and so do both PR descriptions.

Which sites a boot reaches stays on the "Not measured" line in docs/cpu_features.md. #8537 adds that measurement.

AI-assisted (Claude Code).

@BatSmacker84

Copy link
Copy Markdown

Thanks. Re-checked 23bf06a34 (three commits since c5f025fac, docs only; still merges cleanly): the wording now matches the evidence. docs/cpu_features.md calls the 41 sites a static reading that doesn't show which run or whether a CPUID check guards them, and runtime/README.md limits the "no CPUID guard" statement to CLZERO and CLWB, which the Intel boots reach. Pass from my side; the code is unchanged from the head I ran (19/19 ctests, scanner 22/22).

AI-assisted: Claude Opus 5.5 compared the new commits with the earlier checks.

@byPreaZy

Copy link
Copy Markdown

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.

@Hussein5645

Copy link
Copy Markdown

Independent Intel check of 23bf06a34120d05771e27197ea19e51bfbbd5f64: PASS.

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.

  • Compiled the PR's unmodified cpu_emulation_test.cpp and cpu_emulation.h with cl /nologo /std:c++17 /EHsc /O2 /Zi cpu_emulation_test.cpp /Fe:cpu_emulation_test.exe; executable exited 0, all checks passed.
  • CPUID reports SSE4a=0, MONITORX=0, CLZERO=0, CLWB=1. Live INSERTQ/EXTRQ, CLZERO and MONITORX/MWAITX exercised emulation; CLWB ran natively.
  • Decoder and synthetic CONTEXT checks, upper YMM preservation, read-only/resident read-only memory, guard-page recovery and unknown UD2 checks passed.

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 79b6d1b252b751827e7b048792dc004782c651e8 (header) and 3e05f63b8789a7e7f404bb907e17c923d2a8ae51 (test).

Synthetic inputs only; no game files accessed. AI-assisted: Codex.

@hammokko

Copy link
Copy Markdown

checked: #711123bf06a | with: merged into a local retail-boot stack (main 867d922 + the boot PRs listed in #6824), retail 1.0.2.1 gta6rt --run, ctest -R cpu_emulation | on: Windows 11 26200, Intel i5-12400F, RTX 5060, MSVC 14.44 RelWithDebInfo | result: pass. The retail boot hit CLZERO (0xC000001D) on this Intel CPU right before; with this PR the runtime logs "this CPU has no CLZERO; emulating it" and the boot continues to the first PresentX. AI-assisted (Claude).

ItsNotRexed pushed a commit that referenced this pull request Nov 23, 2026
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
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.