runtime(cpu): emulate BMI1, BMI2, MOVBE and patch LZCNT/TZCNT on AVX1 hosts #2190
No reviewers
No assignees
Labels
No labels
bug
dependencies
documentation
enhancement
missing claim
needs rebase
needs-triage
question
ready-for-agent
submodules
No project
No milestone
Dependencies
No dependencies set
Notifications
1 participant
Due date
No due date set.
Reference
leonida/mandy!2190
Loading…
Reference in a new issue
No description provided.
Delete branch "feat/rt-cpu-bmi-lzcnt-movbe"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Pull request successfully merged and closed
Summary
Add
runtime/src/bmi_emulation.hand wire it intogta6rtandLoader::protect_sectionsso pre-HaswellAVX1 + SSE4.2hosts (Intel Sandy Bridge and Ivy Bridge) can execute the game's integer Haswell/ABM instruction delta (docs/cpu_features.md, PR #2188):#UDemulation (STATUS_ILLEGAL_INSTRUCTION):andn,bextr,blsi,blsmsk,blsr(32-bit and 64-bit VEX encodings, exactCF/ZF/SF/OFflag semantics).bzhi,mulx(64x64->128 via_umul128, preservingEFlagsand high-half precedence when both destinations match),pdep,pext,rorx,sarx,shlx,shrx.0F 38 F0 /r) and stores (0F 38 F1 /r), keepingCRC32(F2 0F 38 F0/F1) and registerr/mencodings untouched.__movsbhelper (no_builtin), taking zero syscalls on valid pages while routing first-touchxmempages and write-watched D3D12 shadow pages through the front of the VEH chain and propagating genuineSTATUS_ACCESS_VIOLATION/STATUS_GUARD_PAGE_VIOLATIONrecords without advancingRIP.TZCNT/LZCNTpatching (Loader::protect_sections):CPUID.07H:EBX.BMI1/CPUID.80000001H:ECX.LZCNT, legacyF3 0F BC(TZCNT) andF3 0F BD(LZCNT) execute silently asBSFandBSRwithout raising#UD..pdatafunctions and0xCC-delimited leaf routines with an x86-64 instruction-length decoder before executable sections are write-protected:>=5-byte 32/64-bit register sites jump (E9 rel32) to branchlessBSF/BSR+CMOV+BTstubs within±2 GiB, and 4-byte, 16-bit or memory sites becomeUD2(0F 0B) backed by a side-table of original bytes for the#UDhandler (LEONIDA_LZCNT_PATCH=0disables patching).runtime/test/bmi_emulation_test.cpp):CONTEXTexecution + read-only fault propagation,.pdata+ leafTZCNT/LZCNTpatching (including an immediatemov eax, 0xBD0F48F3byte-trap and poisonedCF=1cmovbflag consumers), and live machine-code execution on hardware.Validation
ctest3x (bmi_emulation,cpu_emulation,clzero_patch,run_tiny_game) on an Intel Core i7-2600 (Sandy Bridge,AVX1 + SSE4.2,BMI1=0 BMI2=0 LZCNT=0 MOVBE=0), exercising the live#UDand patchedTZCNT/LZCNTpaths on real hardware.python -I -m unittest discover -s tests -p "test_ctest_registration.py"andtest_text_write_line_endings.py(OK).python -I scripts/check_no_game_data.py(clean).Claim: https://github.com/ubiquitarianism/leonida/issues/1608#issuecomment-7181466437
AI-assisted: yes (Antigravity, Gemini 4 Carbon)
Independent verification of head
a91f003b8merged into currentmain(ec91d695c). Regression check only: this CPU has all four instructions natively.Machine: profile M (AMD Ryzen 7 9800X3D,
BMI1=1 BMI2=1 LZCNT=1 MOVBE=1; RTX 4070 SUPER 12 GB, NVIDIA 621.01; Windows 11 Pro 26300), MSVC 14.52 (VS 2026, MSBuild generator), RelWithDebInfo. No game files.Merge conflict: the PR no longer merges into
main(it is labelledneeds rebase). The only conflict is in the include list ofruntime/src/main.cpp:mainadded#include "compile_gate_policy.h"where this PR adds#include "bmi_emulation.h". I kept both to test. Nothing else conflicts.Tests (on the merged tree):
bmi_emulation_testalone:host features: BMI1=1 BMI2=1 LZCNT=1 MOVBE=1,OK (65 checks). The synthetic#UDside-table path runs here too (it printsthis CPU has no LZCNT/TZCNT; emulating itfor its own trap sites, as expected).ctest -R "bmi_emulation|cpu_emulation|clzero|run_tiny": 23/23, three runs in a row.LEONIDA_LZCNT_PATCH=0:bmi_emulationandrun_tiny_gamestill pass.run_tiny_game -V: nolacks ...line and nopatched ... TZCNTline, so on a host that has the instructions the loader does not patch anything andgta6rtsays nothing new.ctest -j 6, then failures rerun alone): 500/502. The two failures,xbox_presentandd3d12_set_descriptor_heaps, fail on plainmainhere too (known). No new failure.Diff read (glue only, not the whole decoder): the new handler is installed at the front of the VEH chain but returns
EXCEPTION_CONTINUE_SEARCHfor anything other thanSTATUS_ILLEGAL_INSTRUCTION, and for any#UDit cannot decode, socpu_emulation's#UDcases and the xmem / write-watch access violations still reach their handlers.protect_sectionsonly walks the image when BMI1 or LZCNT is missing. No new build warnings in the PR's files.Not covered: the live
#UDand patched-stub paths on a CPU without these instructions. That needs a pre-Haswell host, which the author tested.No regression found on this machine. Please rebase for the
main.cppinclude conflict.AI-assisted (Claude Code).
Duplicate check (diff reading only, no build): not a duplicate, but the first PR of a stack. Its 2 commits are in #2191, and #2190 and #2191 are both in #2414 (
git merge-base --is-ancestor), which declaresDepends on: #2190, #2191.Suggest landing the stack as one: merging #2414 with a merge commit (not a squash) also lands #2190 and #2191, and GitHub then shows them as merged. With a squash merge of #2414, these two stay open and must be closed by hand.
AI-assisted (Claude Code).
Windows 11 Native Verification Report (
4ba23637e3merged ontoorigin/mainadfb3821a2)origin/main(adfb3821a2) and clean in a 5-PR runtime batch merge.10.0.26200, x64), MSVC19.44.35228, Python3.12.10.Diff Audit (
6files,+1,511/-0)runtime/src/bmi_emulation.h:BMI1(ANDN,BEXTR,BLSI,BLSMSK,BLSR), VEX-encodedBMI2(BZHI,MULX,PDEP,PEXT,RORX,SARX,SHLX,SHRX), legacyMOVBE(16/32/64-bit load/store), andTZCNT/LZCNTinside a vectored#UD(STATUS_ILLEGAL_INSTRUCTION) handler, forwarding memory access faults from SEH-wrappedsafe_read/safe_writewithout advancingRIP.patch_image()scans.pdatafunctions and0xCC-delimited leaf blocks beforeVirtualProtectlocks section permissions, rewriting>= 5-byte 32/64-bit registerTZCNT/LZCNTsites (excludingRSP) to branchlessBSF/BSR + CMOV + BTnative stubs within+-2 GiB, and 4-byte/16-bit/memory/RSPsites toUD2(0F 0B) backed by ashared_mutex-guarded sorted side-table (LEONIDA_LZCNT_PATCH=0disables load-time rewriting).runtime/src/pe_loader.cpp,runtime/src/main.cpp,runtime/CMakeLists.txt,runtime/README.md,runtime/test/bmi_emulation_test.cpp: wires startup detection/installation,Loader::protect_sectionspatching, CTest registration, and unit/live-execution tests.Red -> Green Verification
origin/mainadfb3821a2):runtime/src/bmi_emulation.handbmi_emulation_testare absent onorigin/main.#2190+origin/main):bmi_emulation_test.exe(/O2 /EHsc /W4 /permissive- /utf-8,0warnings):bmi_emulation_test: OK (65 checks)(0.09 s,rc=0), verifying VEX/legacy decoding and negative rejections (CRC32, registerMOVBE,VEX.L=1, non-zeroRORX vvvv,LOCK MOVBE),apply()semantics (32-bit zero-extension, 16-bit upper-bit preservation,R12SIB index,MULXidentical-destination high-half precedence, read-onlyMOVBEwrite-AV propagation), synthetic.pdata+ leafTZCNT/LZCNTstub/UD2patching (skipping embeddedmov eax, 0xBD0F48F3immediates and preservingCF/ZFintocmovb), and live executable-page runs.loader_test.exe(/O2 /EHsc /W4 /permissive- /utf-8,0warnings):115 checks, 0 failed(22.93 s,rc=0).runtime/src/main.cpp(/c /O2 /EHsc /W4 /permissive- /utf-8 /DLEONIDA_VULKAN_DEVICE): compiled cleanly (rc=0).test_docs_env_vars.py,test_docs_links.py,test_docs_repo_paths.py,test_docs_table_rows.py,test_docs_encoding.py,test_ctest_registration.py, andtest_ci_registration.pyall passed (OK,rc=0).Non-Blocking Audit Notes
VirtualSize == 0executable sections inLoader::protect_sections(runtime/src/pe_loader.cpp:2246):std::min(cs->Misc.VirtualSize, cs->SizeOfRawData)evaluates to0when an executable PE section hasMisc.VirtualSize == 0andSizeOfRawData > 0(whereasmap_imagemapsSizeOfRawDatabytes andprotect_sectionsmarkssec->Misc.VirtualSize ? sec->Misc.VirtualSize : sec->SizeOfRawDataexecutable at line 2274). Usingcs->Misc.VirtualSize ? std::min(cs->Misc.VirtualSize, cs->SizeOfRawData) : cs->SizeOfRawDatacovers that edge case.0x64(FS:) prefix indecode()/effective_addr()(runtime/src/bmi_emulation.h:104, 336, 665):decode()records both0x64(FS) and0x65(GS) ind.seg, whileeffective_addr()addsNtCurrentTeb()for0x65(GS) and treats0x64as flat0; rejecting0x64indecode()(or documenting x64 flatFS == 0assumption) avoids silent base-zero addressing if a0x64-prefixed instruction faults.bmi_emulation.h:1,main.cpp:564, andbmi_emulation_test.cpp:1citedocs/cpu_features.md, which is not yet onmain(test_docs_repo_paths.pystill passes).Verdict: PASS (with minor non-blocking follow-up notes above).
AI-assisted.