runtime(cpu): emulate BMI1, BMI2, MOVBE and patch LZCNT/TZCNT on AVX1 hosts #2190

Merged
leonida/mandy
robot00f merged 2 commits from feat/rt-cpu-bmi-lzcnt-movbe into main 2026-11-29 01:02:54 +00:00

Pull request successfully merged and closed

robot00f commented 2026-11-26 04:01:28 +00:00

Summary

Add runtime/src/bmi_emulation.h and wire it into gta6rt and Loader::protect_sections so pre-Haswell AVX1 + SSE4.2 hosts (Intel Sandy Bridge and Ivy Bridge) can execute the game's integer Haswell/ABM instruction delta (docs/cpu_features.md, PR #2188):

  • #UD emulation (STATUS_ILLEGAL_INSTRUCTION):
    • BMI1: andn, bextr, blsi, blsmsk, blsr (32-bit and 64-bit VEX encodings, exact CF/ZF/SF/OF flag semantics).
    • BMI2: bzhi, mulx (64x64->128 via _umul128, preserving EFlags and high-half precedence when both destinations match), pdep, pext, rorx, sarx, shlx, shrx.
    • MOVBE: 16/32/64-bit big-endian loads (0F 38 F0 /r) and stores (0F 38 F1 /r), keeping CRC32 (F2 0F 38 F0/F1) and register r/m encodings untouched.
    • Memory operands copy through a non-inlined SEH-guarded __movsb helper (no_builtin), taking zero syscalls on valid pages while routing first-touch xmem pages and write-watched D3D12 shadow pages through the front of the VEH chain and propagating genuine STATUS_ACCESS_VIOLATION / STATUS_GUARD_PAGE_VIOLATION records without advancing RIP.
  • Load-time TZCNT / LZCNT patching (Loader::protect_sections):
    • Without CPUID.07H:EBX.BMI1 / CPUID.80000001H:ECX.LZCNT, legacy F3 0F BC (TZCNT) and F3 0F BD (LZCNT) execute silently as BSF and BSR without raising #UD.
    • Walks .pdata functions and 0xCC-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 branchless BSF/BSR + CMOV + BT stubs within ±2 GiB, and 4-byte, 16-bit or memory sites become UD2 (0F 0B) backed by a side-table of original bytes for the #UD handler (LEONIDA_LZCNT_PATCH=0 disables patching).
  • Tests (runtime/test/bmi_emulation_test.cpp):
    • Decoder positive/negative cases, synthetic CONTEXT execution + read-only fault propagation, .pdata + leaf TZCNT/LZCNT patching (including an immediate mov eax, 0xBD0F48F3 byte-trap and poisoned CF=1 cmovb flag consumers), and live machine-code execution on hardware.

Validation

  • Built and executed ctest 3x (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 #UD and patched TZCNT/LZCNT paths on real hardware.
  • python -I -m unittest discover -s tests -p "test_ctest_registration.py" and test_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)

## Summary Add `runtime/src/bmi_emulation.h` and wire it into `gta6rt` and `Loader::protect_sections` so pre-Haswell `AVX1 + SSE4.2` hosts (Intel Sandy Bridge and Ivy Bridge) can execute the game's integer Haswell/ABM instruction delta (`docs/cpu_features.md`, PR #2188): - **`#UD` emulation (`STATUS_ILLEGAL_INSTRUCTION`):** - **BMI1:** `andn`, `bextr`, `blsi`, `blsmsk`, `blsr` (32-bit and 64-bit VEX encodings, exact `CF`/`ZF`/`SF`/`OF` flag semantics). - **BMI2:** `bzhi`, `mulx` (64x64->128 via `_umul128`, preserving `EFlags` and high-half precedence when both destinations match), `pdep`, `pext`, `rorx`, `sarx`, `shlx`, `shrx`. - **MOVBE:** 16/32/64-bit big-endian loads (`0F 38 F0 /r`) and stores (`0F 38 F1 /r`), keeping `CRC32` (`F2 0F 38 F0/F1`) and register `r/m` encodings untouched. - Memory operands copy through a non-inlined SEH-guarded `__movsb` helper (`no_builtin`), taking zero syscalls on valid pages while routing first-touch `xmem` pages and write-watched D3D12 shadow pages through the front of the VEH chain and propagating genuine `STATUS_ACCESS_VIOLATION` / `STATUS_GUARD_PAGE_VIOLATION` records without advancing `RIP`. - **Load-time `TZCNT` / `LZCNT` patching (`Loader::protect_sections`):** - Without `CPUID.07H:EBX.BMI1` / `CPUID.80000001H:ECX.LZCNT`, legacy `F3 0F BC` (`TZCNT`) and `F3 0F BD` (`LZCNT`) execute silently as `BSF` and `BSR` without raising `#UD`. - Walks `.pdata` functions and `0xCC`-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 branchless `BSF`/`BSR` + `CMOV` + `BT` stubs within `±2 GiB`, and 4-byte, 16-bit or memory sites become `UD2` (`0F 0B`) backed by a side-table of original bytes for the `#UD` handler (`LEONIDA_LZCNT_PATCH=0` disables patching). - **Tests (`runtime/test/bmi_emulation_test.cpp`):** - Decoder positive/negative cases, synthetic `CONTEXT` execution + read-only fault propagation, `.pdata` + leaf `TZCNT`/`LZCNT` patching (including an immediate `mov eax, 0xBD0F48F3` byte-trap and poisoned `CF=1` `cmovb` flag consumers), and live machine-code execution on hardware. ## Validation - Built and executed `ctest` 3x (`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 `#UD` and patched `TZCNT`/`LZCNT` paths on real hardware. - `python -I -m unittest discover -s tests -p "test_ctest_registration.py"` and `test_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)
Tyrannys commented 2026-11-27 14:57:23 +00:00

Independent verification of head a91f003b8 merged into current main (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 labelled needs rebase). The only conflict is in the include list of runtime/src/main.cpp: main added #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_test alone: host features: BMI1=1 BMI2=1 LZCNT=1 MOVBE=1, OK (65 checks). The synthetic #UD side-table path runs here too (it prints this CPU has no LZCNT/TZCNT; emulating it for its own trap sites, as expected).
  • ctest -R "bmi_emulation|cpu_emulation|clzero|run_tiny": 23/23, three runs in a row.
  • With LEONIDA_LZCNT_PATCH=0: bmi_emulation and run_tiny_game still pass.
  • run_tiny_game -V: no lacks ... line and no patched ... TZCNT line, so on a host that has the instructions the loader does not patch anything and gta6rt says nothing new.
  • Full suite (ctest -j 6, then failures rerun alone): 500/502. The two failures, xbox_present and d3d12_set_descriptor_heaps, fail on plain main here 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_SEARCH for anything other than STATUS_ILLEGAL_INSTRUCTION, and for any #UD it cannot decode, so cpu_emulation's #UD cases and the xmem / write-watch access violations still reach their handlers. protect_sections only walks the image when BMI1 or LZCNT is missing. No new build warnings in the PR's files.

Not covered: the live #UD and 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.cpp include conflict.

AI-assisted (Claude Code).

Independent verification of head `a91f003b8` merged into current `main` (`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 labelled `needs rebase`). The only conflict is in the include list of `runtime/src/main.cpp`: `main` added `#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_test` alone: `host features: BMI1=1 BMI2=1 LZCNT=1 MOVBE=1`, `OK (65 checks)`. The synthetic `#UD` side-table path runs here too (it prints `this CPU has no LZCNT/TZCNT; emulating it` for its own trap sites, as expected). - `ctest -R "bmi_emulation|cpu_emulation|clzero|run_tiny"`: 23/23, three runs in a row. - With `LEONIDA_LZCNT_PATCH=0`: `bmi_emulation` and `run_tiny_game` still pass. - `run_tiny_game -V`: no `lacks ...` line and no `patched ... TZCNT` line, so on a host that has the instructions the loader does not patch anything and `gta6rt` says nothing new. - Full suite (`ctest -j 6`, then failures rerun alone): 500/502. The two failures, `xbox_present` and `d3d12_set_descriptor_heaps`, fail on plain `main` here 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_SEARCH` for anything other than `STATUS_ILLEGAL_INSTRUCTION`, and for any `#UD` it cannot decode, so `cpu_emulation`'s `#UD` cases and the xmem / write-watch access violations still reach their handlers. `protect_sections` only walks the image when BMI1 or LZCNT is missing. No new build warnings in the PR's files. **Not covered:** the live `#UD` and 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.cpp` include conflict. AI-assisted (Claude Code).
TheGeogeo commented 2026-11-28 22:16:31 +00:00

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

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 declares `Depends 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).
zmasi commented 2026-11-28 23:25:46 +00:00

Windows 11 Native Verification Report (4ba23637e3 merged onto origin/main adfb3821a2)

  • Merge Status: Clean merge onto origin/main (adfb3821a2) and clean in a 5-PR runtime batch merge.
  • Environment: Windows 11 (10.0.26200, x64), MSVC 19.44.35228, Python 3.12.10.

Diff Audit (6 files, +1,511/-0)

  • runtime/src/bmi_emulation.h:
    • Decodes and emulates VEX-encoded BMI1 (ANDN, BEXTR, BLSI, BLSMSK, BLSR), VEX-encoded BMI2 (BZHI, MULX, PDEP, PEXT, RORX, SARX, SHLX, SHRX), legacy MOVBE (16/32/64-bit load/store), and TZCNT/LZCNT inside a vectored #UD (STATUS_ILLEGAL_INSTRUCTION) handler, forwarding memory access faults from SEH-wrapped safe_read/safe_write without advancing RIP.
    • patch_image() scans .pdata functions and 0xCC-delimited leaf blocks before VirtualProtect locks section permissions, rewriting >= 5-byte 32/64-bit register TZCNT/LZCNT sites (excluding RSP) to branchless BSF/BSR + CMOV + BT native stubs within +-2 GiB, and 4-byte/16-bit/memory/RSP sites to UD2 (0F 0B) backed by a shared_mutex-guarded sorted side-table (LEONIDA_LZCNT_PATCH=0 disables 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_sections patching, CTest registration, and unit/live-execution tests.

Red -> Green Verification

  1. Red (origin/main adfb3821a2):
    • runtime/src/bmi_emulation.h and bmi_emulation_test are absent on origin/main.
  2. Green (#2190 + origin/main):
    • bmi_emulation_test.exe (/O2 /EHsc /W4 /permissive- /utf-8, 0 warnings): bmi_emulation_test: OK (65 checks) (0.09 s, rc=0), verifying VEX/legacy decoding and negative rejections (CRC32, register MOVBE, VEX.L=1, non-zero RORX vvvv, LOCK MOVBE), apply() semantics (32-bit zero-extension, 16-bit upper-bit preservation, R12 SIB index, MULX identical-destination high-half precedence, read-only MOVBE write-AV propagation), synthetic .pdata + leaf TZCNT/LZCNT stub/UD2 patching (skipping embedded mov eax, 0xBD0F48F3 immediates and preserving CF/ZF into cmovb), and live executable-page runs.
    • loader_test.exe (/O2 /EHsc /W4 /permissive- /utf-8, 0 warnings): 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).
    • Repo & CI gates: 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, and test_ci_registration.py all passed (OK, rc=0).

Non-Blocking Audit Notes

  1. VirtualSize == 0 executable sections in Loader::protect_sections (runtime/src/pe_loader.cpp:2246): std::min(cs->Misc.VirtualSize, cs->SizeOfRawData) evaluates to 0 when an executable PE section has Misc.VirtualSize == 0 and SizeOfRawData > 0 (whereas map_image maps SizeOfRawData bytes and protect_sections marks sec->Misc.VirtualSize ? sec->Misc.VirtualSize : sec->SizeOfRawData executable at line 2274). Using cs->Misc.VirtualSize ? std::min(cs->Misc.VirtualSize, cs->SizeOfRawData) : cs->SizeOfRawData covers that edge case.
  2. 0x64 (FS:) prefix in decode() / effective_addr() (runtime/src/bmi_emulation.h:104, 336, 665): decode() records both 0x64 (FS) and 0x65 (GS) in d.seg, while effective_addr() adds NtCurrentTeb() for 0x65 (GS) and treats 0x64 as flat 0; rejecting 0x64 in decode() (or documenting x64 flat FS == 0 assumption) avoids silent base-zero addressing if a 0x64-prefixed instruction faults.
  3. Comment path reference: comments in bmi_emulation.h:1, main.cpp:564, and bmi_emulation_test.cpp:1 cite docs/cpu_features.md, which is not yet on main (test_docs_repo_paths.py still passes).

Verdict: PASS (with minor non-blocking follow-up notes above).

AI-assisted.

### Windows 11 Native Verification Report (`4ba23637e3` merged onto `origin/main` `adfb3821a2`) - **Merge Status**: Clean merge onto `origin/main` (`adfb3821a2`) and clean in a 5-PR runtime batch merge. - **Environment**: Windows 11 (`10.0.26200`, x64), MSVC `19.44.35228`, Python `3.12.10`. #### Diff Audit (`6` files, `+1,511/-0`) - `runtime/src/bmi_emulation.h`: - Decodes and emulates VEX-encoded `BMI1` (`ANDN`, `BEXTR`, `BLSI`, `BLSMSK`, `BLSR`), VEX-encoded `BMI2` (`BZHI`, `MULX`, `PDEP`, `PEXT`, `RORX`, `SARX`, `SHLX`, `SHRX`), legacy `MOVBE` (16/32/64-bit load/store), and `TZCNT`/`LZCNT` inside a vectored `#UD` (`STATUS_ILLEGAL_INSTRUCTION`) handler, forwarding memory access faults from SEH-wrapped `safe_read`/`safe_write` without advancing `RIP`. - `patch_image()` scans `.pdata` functions and `0xCC`-delimited leaf blocks before `VirtualProtect` locks section permissions, rewriting `>= 5`-byte 32/64-bit register `TZCNT`/`LZCNT` sites (excluding `RSP`) to branchless `BSF`/`BSR + CMOV + BT` native stubs within `+-2 GiB`, and 4-byte/16-bit/memory/`RSP` sites to `UD2` (`0F 0B`) backed by a `shared_mutex`-guarded sorted side-table (`LEONIDA_LZCNT_PATCH=0` disables 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_sections` patching, CTest registration, and unit/live-execution tests. #### Red -> Green Verification 1. **Red (`origin/main` `adfb3821a2`)**: - `runtime/src/bmi_emulation.h` and `bmi_emulation_test` are absent on `origin/main`. 2. **Green (`#2190` + `origin/main`)**: - `bmi_emulation_test.exe` (`/O2 /EHsc /W4 /permissive- /utf-8`, **`0` warnings**): **`bmi_emulation_test: OK (65 checks)`** (`0.09 s`, `rc=0`), verifying VEX/legacy decoding and negative rejections (`CRC32`, register `MOVBE`, `VEX.L=1`, non-zero `RORX vvvv`, `LOCK MOVBE`), `apply()` semantics (32-bit zero-extension, 16-bit upper-bit preservation, `R12` SIB index, `MULX` identical-destination high-half precedence, read-only `MOVBE` write-AV propagation), synthetic `.pdata` + leaf `TZCNT`/`LZCNT` stub/`UD2` patching (skipping embedded `mov eax, 0xBD0F48F3` immediates and preserving `CF`/`ZF` into `cmovb`), and live executable-page runs. - `loader_test.exe` (`/O2 /EHsc /W4 /permissive- /utf-8`, **`0` warnings**): **`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`). - Repo & CI gates: `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`, and `test_ci_registration.py` all passed (`OK`, `rc=0`). #### Non-Blocking Audit Notes 1. **`VirtualSize == 0` executable sections in `Loader::protect_sections` (`runtime/src/pe_loader.cpp:2246`)**: `std::min(cs->Misc.VirtualSize, cs->SizeOfRawData)` evaluates to `0` when an executable PE section has `Misc.VirtualSize == 0` and `SizeOfRawData > 0` (whereas `map_image` maps `SizeOfRawData` bytes and `protect_sections` marks `sec->Misc.VirtualSize ? sec->Misc.VirtualSize : sec->SizeOfRawData` executable at line 2274). Using `cs->Misc.VirtualSize ? std::min(cs->Misc.VirtualSize, cs->SizeOfRawData) : cs->SizeOfRawData` covers that edge case. 2. **`0x64` (`FS:`) prefix in `decode()` / `effective_addr()` (`runtime/src/bmi_emulation.h:104, 336, 665`)**: `decode()` records both `0x64` (`FS`) and `0x65` (`GS`) in `d.seg`, while `effective_addr()` adds `NtCurrentTeb()` for `0x65` (`GS`) and treats `0x64` as flat `0`; rejecting `0x64` in `decode()` (or documenting x64 flat `FS == 0` assumption) avoids silent base-zero addressing if a `0x64`-prefixed instruction faults. 3. **Comment path reference**: comments in `bmi_emulation.h:1`, `main.cpp:564`, and `bmi_emulation_test.cpp:1` cite `docs/cpu_features.md`, which is not yet on `main` (`test_docs_repo_paths.py` still passes). **Verdict**: **PASS** (with minor non-blocking follow-up notes above). AI-assisted.
Sign in to join this conversation.
No description provided.