cpu: lower 32-bit and 64-bit MUL, DIV, IDIV, XADD, and CMPXCHG instructions #326

Merged
Vonsek merged 5 commits from upstream-pr/331 into main 2026-11-22 08:56:18 +00:00
Vonsek commented 2026-11-21 22:24:29 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by Vonsek on 2026-11-21T22:24:29Z.


Change

  • Lower 32-bit and 64-bit mul, div, idiv, xadd, and cmpxchg in tools/ffx_version_query.py using portable 128-bit arithmetic for 64-bit widening multiply/divide, zero-extending 32-bit writes, and keeping LOCK prefix rejection intact.
  • Add a source-built MASM fixture (tests/cpu/mul_div.asm, tests/cpu/mul_div.def) and differential test (tests/cpu/mul_div.py) wired into CMakeLists.txt as cpu_aot_mul_div, verifying all 10 exports (467 cases including 128/64 unsigned and signed division and ZF/CF flag updates) against both the native DLL and a reference model.
  • Classify mul_div -> cpu_aot_mul_div in tools/form_coverage.py (+5 baseline x64 Integer mnemonics in docs/coverage/x64_zen2.tsv) and document the test in docs/experiments.md.

Verification

Tested on Windows 11 (VS 2022 Build Tools 17.14, MSVC 19.44, ML64 14.44, Windows SDK 10.0.26100, Python 3.12):

  • Before the change, cmake --build --preset dev --target cpu_mul_div_lifted failed with:
    ValueError: unsupported query operation at 0x100d: mul r10d
    
  • After the change:
    • cmake --build --preset dev --target cpu_mul_div_lifted succeeded.
    • ctest --preset dev --no-tests=error -R "^(cpu_aot_mul_div|cpu_aot_shift_count|cpu_aot_version_query|cpu_aot_address_size)$" -V: 4/4 passed (467 MUL, DIV, IDIV, XADD, and CMPXCHG cases matched native and translated DLLs).
    • python -B tests/form_coverage_check.py: form coverage checks passed.

Evidence and follow-up

  • Adds five uncovered baseline x64 Integer mnemonics (cmpxchg, div, idiv, mul, xadd) to docs/coverage/x64_zen2.tsv coverage; all are baseline x86-64 instructions requiring no optional CPUID feature gate.
  • All binaries are source-built via MASM and CMake; no game files or external dumps are included.

Checklist

  • Focused, single-purpose change
  • Source-built test that fails without the change and passes with it
  • Verified locally on Windows
<!-- greyfinch-sync:R0Y00/Xbox2Windows:issue:6535189636 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/331). Originally posted by [Vonsek](https://github.com/Vonsek) on 2026-11-21T22:24:29Z. --- ## Change - Lower 32-bit and 64-bit `mul`, `div`, `idiv`, `xadd`, and `cmpxchg` in `tools/ffx_version_query.py` using portable 128-bit arithmetic for 64-bit widening multiply/divide, zero-extending 32-bit writes, and keeping `LOCK` prefix rejection intact. - Add a source-built MASM fixture (`tests/cpu/mul_div.asm`, `tests/cpu/mul_div.def`) and differential test (`tests/cpu/mul_div.py`) wired into `CMakeLists.txt` as `cpu_aot_mul_div`, verifying all 10 exports (467 cases including 128/64 unsigned and signed division and ZF/CF flag updates) against both the native DLL and a reference model. - Classify `mul_div` -> `cpu_aot_mul_div` in `tools/form_coverage.py` (+5 baseline x64 Integer mnemonics in `docs/coverage/x64_zen2.tsv`) and document the test in `docs/experiments.md`. ## Verification Tested on Windows 11 (VS 2022 Build Tools 17.14, MSVC 19.44, ML64 14.44, Windows SDK 10.0.26100, Python 3.12): - Before the change, `cmake --build --preset dev --target cpu_mul_div_lifted` failed with: ```text ValueError: unsupported query operation at 0x100d: mul r10d ``` - After the change: - `cmake --build --preset dev --target cpu_mul_div_lifted` succeeded. - `ctest --preset dev --no-tests=error -R "^(cpu_aot_mul_div|cpu_aot_shift_count|cpu_aot_version_query|cpu_aot_address_size)$" -V`: 4/4 passed (`467 MUL, DIV, IDIV, XADD, and CMPXCHG cases matched native and translated DLLs`). - `python -B tests/form_coverage_check.py`: `form coverage checks passed`. ## Evidence and follow-up - Adds five uncovered baseline x64 Integer mnemonics (`cmpxchg`, `div`, `idiv`, `mul`, `xadd`) to `docs/coverage/x64_zen2.tsv` coverage; all are baseline x86-64 instructions requiring no optional CPUID feature gate. - All binaries are source-built via MASM and CMake; no game files or external dumps are included. ## Checklist - [x] Focused, single-purpose change - [x] Source-built test that fails without the change and passes with it - [x] Verified locally on Windows
upstream-sync closed this pull request 2026-11-24 06:42:27 +00:00
chatgpt-codex-connector[bot commented 2026-11-24 06:42:28 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-21T22:33:45Z.

Review: COMMENTED


💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 85491d3932

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review:6008626851 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/331#pullrequestreview-6008626851). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-21T22:33:45Z. **Review:** COMMENTED --- <!-- codex-review-receipt:v1 --> ### 💡 Codex Review Here are some automated review suggestions for this pull request. **Reviewed commit:** `85491d3932` <details> <summary>ℹ️ About Codex in GitHub</summary> <br/> [Your team has set up Codex to review pull requests in this repo](https://chatgpt.com/codex/cloud/settings/general). Reviews are triggered when you - Open a pull request for review - Mark a draft as ready - Comment "@codex review". If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". </details>
chatgpt-codex-connector[bot commented 2026-11-24 06:48:09 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-21T22:27:44Z.


Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-21T22:33:48.759860Z 85491d3 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7070197422 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/331#issuecomment-7070197422). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-21T22:27:44Z. --- <!-- codex-pull-request-review-summary --> <!-- codex-review-state:v1 {"code_review":{"commit_sha":"85491d3932e4eb7490ca69fc0ca40fb976f2a2bd","has_any_findings":true,"has_unresolved_findings":true,"status":"completed"},"security_review":{"commit_sha":null,"has_any_findings":null,"has_unresolved_findings":null,"status":null}} --> <details> <summary><strong>Codex Review Summary</strong>: ✅ Completed</summary> This comment shows the latest Codex review activity on this pull request. | Review | Status | Commit | Review trigger | | --- | --- | --- | --- | | 📝 **Code Review** | ✅ **Completed** <relative-time datetime="2026-11-21T22:33:48.759860Z">2026-11-21T22:33:48.759860Z</relative-time> | `85491d3` | Draft marked ready | <details> <summary>ℹ️ About Codex in GitHub</summary> <br/> [Your team has set up Codex to review pull requests in this repo](https://chatgpt.com/codex/cloud/settings/general). Reviews are triggered when you - Open a pull request for review - Mark a draft as ready - Comment "@codex review" or "@codex security review". Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. </details> </details>
Vonsek commented 2026-11-24 06:48:09 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by Vonsek on 2026-11-21T22:38:37Z.


Addressed both findings:

  • Snapshot the effective address once before updating the source register in memory-operand XADD (and CMPXCHG), and added xadd64_mem (xadd qword ptr [rcx], rcx) to tests/cpu/mul_div.asm.
  • Added zero-divisor and quotient-overflow #DE checks (raise_de()) to 32-bit and 64-bit DIV/IDIV before writing guest registers, and verified 8 #DE fault cases against both the native and translated DLLs in tests/cpu/mul_div.py.
<!-- greyfinch-sync:R0Y00/Xbox2Windows:comment:7070324851 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/331#issuecomment-7070324851). Originally posted by [Vonsek](https://github.com/Vonsek) on 2026-11-21T22:38:37Z. --- Addressed both findings: - Snapshot the effective address once before updating the source register in memory-operand `XADD` (and `CMPXCHG`), and added `xadd64_mem` (`xadd qword ptr [rcx], rcx`) to `tests/cpu/mul_div.asm`. - Added zero-divisor and quotient-overflow `#DE` checks (`raise_de()`) to 32-bit and 64-bit `DIV`/`IDIV` before writing guest registers, and verified 8 `#DE` fault cases against both the native and translated DLLs in `tests/cpu/mul_div.py`.
chatgpt-codex-connector[bot commented 2026-11-24 06:50:36 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-21T22:33:46Z.

Code review location: tools/ffx_version_query.py; line 210

@@ -163,33 +163,54 @@ def write(expr):
                       M.INC: "", M.DEC: "", M.XOR: "carry = false;", M.AND: "carry = false;", M.OR: "carry = false;"}[op]
             stmt = (f"{{ const {width} a = {operand(0)}, b = static_cast<{width}>({rhs}); "
                     f"const {width} v = static_cast<{width}>({expr}); {update} zero = v == 0; {write('v')} }}")
-        elif op in (M.ANDN, M.BEXTR, M.BLSI, M.BLSMSK, M.BLSR, M.TZCNT) and RegisterExt.size(i.op0_register) in (4, 8):
-            size = RegisterExt.size(i.op0_register)
-            width, bits = UINT[size], 8 * size
-            if op == M.ANDN:
-                stmt = (f"{{ const {width} v = static_cast<{width}>(~static_cast<{width}>({operand(1)}) "
-                        f"& static_cast<{width}>({operand(2)})); carry = false; zero = v == 0; {write('v')} }}")
-            elif op == M.BEXTR:
-                stmt = (f"{{ const {width} a = {operand(1)}, ctrl = {operand(2)}; "
-                        f"const unsigned start = static_cast<unsigned>(ctrl & 0xffu), "
-                        f"len = static_cast<unsigned>((ctrl >> 8) & 0xffu); "
-                        f"{width} v = 0; if (start < {bits}u && len > 0u) {{ "
-                        f"const {width} s = a >> start; "
-                        f"v = len >= {bits}u ? s : static_cast<{width}>(s & ((static_cast<{width}>(1) << len) - 1)); }} "
-                        f"carry = false; zero = v == 0; {write('v')} }}")
-            elif op == M.BLSI:
-                stmt = (f"{{ const {width} a = {operand(1)}, v = static_cast<{width}>(a & (static_cast<{width}>(0) - a)); "
-                        f"carry = a != 0; zero = v == 0; {write('v')} }}")
-            elif op == M.BLSMSK:
-                stmt = (f"{{ const {width} a = {operand(1)}, v = static_cast<{width}>(a ^ (a - 1)); "
-                        f"carry = a == 0; zero = false; {write('v')} }}")
-            elif op == M.BLSR:
-                stmt = (f"{{ const {width} a = {operand(1)}, v = static_cast<{width}>(a & (a - 1)); "
-                        f"carry = a == 0; zero = v == 0; {write('v')} }}")
-            else:  # M.TZCNT
-                stmt = (f"{{ const {width} a = {operand(1)}; {width} v = 0; "
-                        f"if (a == 0) {{ v = {bits}; }} else {{ while (((a >> v) & 1) == 0) ++v; }} "
-                        f"carry = a == 0; zero = v == 0; {write('v')} }}")
+        elif op in (M.MUL, M.DIV, M.IDIV):
+            size = MemorySizeExt.size(i.memory_size) if i.op0_kind == K.MEMORY else RegisterExt.size(i.op0_register)
+            if size not in (4, 8):
+                raise ValueError(f"unsupported query operation at {i.ip:#x}: {i}")
+            if op == M.MUL:
+                if size == 4:
+                    stmt = (f"{{ const uint64_t p = static_cast<uint64_t>(static_cast<uint32_t>(rax)) * static_cast<uint32_t>({operand(0)}); "
+                            f"rax = static_cast<uint32_t>(p); rdx = static_cast<uint32_t>(p >> 32); carry = rdx != 0; }}")
+                else:
+                    stmt = (f"{{ const uint64_t a = rax, b = {operand(0)}; "
+                            f"const uint64_t a0 = static_cast<uint32_t>(a), a1 = a >> 32, b0 = static_cast<uint32_t>(b), b1 = b >> 32; "
+                            f"const uint64_t p0 = a0 * b0, p1 = a0 * b1, p2 = a1 * b0, p3 = a1 * b1; "
+                            f"const uint64_t mid = (p0 >> 32) + static_cast<uint32_t>(p1) + static_cast<uint32_t>(p2); "
+                            f"rax = (p0 & 0xffffffffull) | (mid << 32); rdx = p3 + (p1 >> 32) + (p2 >> 32) + (mid >> 32); carry = rdx != 0; }}")
+            elif op == M.DIV:
+                if size == 4:
+                    stmt = (f"{{ const uint64_t num = (static_cast<uint64_t>(static_cast<uint32_t>(rdx)) << 32) | static_cast<uint32_t>(rax); "
+                            f"const uint32_t den = {operand(0)}; rax = static_cast<uint32_t>(num / den); rdx = static_cast<uint32_t>(num % den); }}")
+                else:
+                    stmt = (f"{{ uint64_t hi = rdx, lo = rax, den = {operand(0)}, q = 0; "
+                            f"for (int b = 63; b >= 0; --b) {{ const bool top = (hi >> 63) != 0; "
+                            f"hi = (hi << 1) | ((lo >> b) & 1u); if (top || hi >= den) {{ hi -= den; q |= 1ull << b; }} }} "
+                            f"rax = q; rdx = hi; }}")
+            else:  # M.IDIV
+                if size == 4:
+                    stmt = (f"{{ const int64_t num = static_cast<int64_t>((static_cast<uint64_t>(static_cast<uint32_t>(rdx)) << 32) | static_cast<uint32_t>(rax)); "
+                            f"const int32_t den = static_cast<int32_t>({operand(0)}); "
+                            f"rax = static_cast<uint32_t>(static_cast<int32_t>(num / den)); rdx = static_cast<uint32_t>(static_cast<int32_t>(num % den)); }}")
+                else:
+                    stmt = (f"{{ uint64_t hi = rdx, lo = rax, d = {operand(0)}; "
+                            f"const bool neg_n = (hi >> 63) != 0, neg_d = (d >> 63) != 0; "
+                            f"if (neg_n) {{ lo = 0ull - lo; hi = ~hi + (lo == 0ull ? 1ull : 0ull); }} "
+                            f"if (neg_d) {{ d = 0ull - d; }} uint64_t q = 0; "
+                            f"for (int b = 63; b >= 0; --b) {{ const bool top = (hi >> 63) != 0; "
+                            f"hi = (hi << 1) | ((lo >> b) & 1u); if (top || hi >= d) {{ hi -= d; q |= 1ull << b; }} }} "
+                            f"rax = (neg_n != neg_d) ? (0ull - q) : q; rdx = neg_n ? (0ull - hi) : hi; }}")
+        elif op in (M.XADD, M.CMPXCHG):
+            size = MemorySizeExt.size(i.memory_size) if i.op0_kind == K.MEMORY else RegisterExt.size(i.op0_register)
+            if size not in (4, 8):
+                raise ValueError(f"unsupported query operation at {i.ip:#x}: {i}")
+            width = UINT[size]
+            if op == M.XADD:
+                src_dst = reg(i.op1_register)
+                stmt = (f"{{ const {width} a = {operand(0)}, b = {operand(1)}, v = static_cast<{width}>(a + b); "
+                        f"carry = v < a; zero = v == 0; {src_dst} = a; {write('v')} }}")

P1 Badge Snapshot the effective address before updating the XADD source

When the memory operand uses the source register as its base or index (e.g. xadd qword ptr [rcx], rcx), this assignment updates rcx before write('v') reevaluates address(). The store therefore goes to an address derived from the old memory contents rather than the original effective address, potentially corrupting unrelated memory or faulting. This reproduced in a native-versus-emitted Linux/x86-64 probe. Capture the effective address before updating the source register and reuse it for the load and store.

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4655335491 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/331#discussion_r4655335491). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-21T22:33:46Z. **Code review location:** `tools/ffx_version_query.py`; line 210 ~~~~diff @@ -163,33 +163,54 @@ def write(expr): M.INC: "", M.DEC: "", M.XOR: "carry = false;", M.AND: "carry = false;", M.OR: "carry = false;"}[op] stmt = (f"{{ const {width} a = {operand(0)}, b = static_cast<{width}>({rhs}); " f"const {width} v = static_cast<{width}>({expr}); {update} zero = v == 0; {write('v')} }}") - elif op in (M.ANDN, M.BEXTR, M.BLSI, M.BLSMSK, M.BLSR, M.TZCNT) and RegisterExt.size(i.op0_register) in (4, 8): - size = RegisterExt.size(i.op0_register) - width, bits = UINT[size], 8 * size - if op == M.ANDN: - stmt = (f"{{ const {width} v = static_cast<{width}>(~static_cast<{width}>({operand(1)}) " - f"& static_cast<{width}>({operand(2)})); carry = false; zero = v == 0; {write('v')} }}") - elif op == M.BEXTR: - stmt = (f"{{ const {width} a = {operand(1)}, ctrl = {operand(2)}; " - f"const unsigned start = static_cast<unsigned>(ctrl & 0xffu), " - f"len = static_cast<unsigned>((ctrl >> 8) & 0xffu); " - f"{width} v = 0; if (start < {bits}u && len > 0u) {{ " - f"const {width} s = a >> start; " - f"v = len >= {bits}u ? s : static_cast<{width}>(s & ((static_cast<{width}>(1) << len) - 1)); }} " - f"carry = false; zero = v == 0; {write('v')} }}") - elif op == M.BLSI: - stmt = (f"{{ const {width} a = {operand(1)}, v = static_cast<{width}>(a & (static_cast<{width}>(0) - a)); " - f"carry = a != 0; zero = v == 0; {write('v')} }}") - elif op == M.BLSMSK: - stmt = (f"{{ const {width} a = {operand(1)}, v = static_cast<{width}>(a ^ (a - 1)); " - f"carry = a == 0; zero = false; {write('v')} }}") - elif op == M.BLSR: - stmt = (f"{{ const {width} a = {operand(1)}, v = static_cast<{width}>(a & (a - 1)); " - f"carry = a == 0; zero = v == 0; {write('v')} }}") - else: # M.TZCNT - stmt = (f"{{ const {width} a = {operand(1)}; {width} v = 0; " - f"if (a == 0) {{ v = {bits}; }} else {{ while (((a >> v) & 1) == 0) ++v; }} " - f"carry = a == 0; zero = v == 0; {write('v')} }}") + elif op in (M.MUL, M.DIV, M.IDIV): + size = MemorySizeExt.size(i.memory_size) if i.op0_kind == K.MEMORY else RegisterExt.size(i.op0_register) + if size not in (4, 8): + raise ValueError(f"unsupported query operation at {i.ip:#x}: {i}") + if op == M.MUL: + if size == 4: + stmt = (f"{{ const uint64_t p = static_cast<uint64_t>(static_cast<uint32_t>(rax)) * static_cast<uint32_t>({operand(0)}); " + f"rax = static_cast<uint32_t>(p); rdx = static_cast<uint32_t>(p >> 32); carry = rdx != 0; }}") + else: + stmt = (f"{{ const uint64_t a = rax, b = {operand(0)}; " + f"const uint64_t a0 = static_cast<uint32_t>(a), a1 = a >> 32, b0 = static_cast<uint32_t>(b), b1 = b >> 32; " + f"const uint64_t p0 = a0 * b0, p1 = a0 * b1, p2 = a1 * b0, p3 = a1 * b1; " + f"const uint64_t mid = (p0 >> 32) + static_cast<uint32_t>(p1) + static_cast<uint32_t>(p2); " + f"rax = (p0 & 0xffffffffull) | (mid << 32); rdx = p3 + (p1 >> 32) + (p2 >> 32) + (mid >> 32); carry = rdx != 0; }}") + elif op == M.DIV: + if size == 4: + stmt = (f"{{ const uint64_t num = (static_cast<uint64_t>(static_cast<uint32_t>(rdx)) << 32) | static_cast<uint32_t>(rax); " + f"const uint32_t den = {operand(0)}; rax = static_cast<uint32_t>(num / den); rdx = static_cast<uint32_t>(num % den); }}") + else: + stmt = (f"{{ uint64_t hi = rdx, lo = rax, den = {operand(0)}, q = 0; " + f"for (int b = 63; b >= 0; --b) {{ const bool top = (hi >> 63) != 0; " + f"hi = (hi << 1) | ((lo >> b) & 1u); if (top || hi >= den) {{ hi -= den; q |= 1ull << b; }} }} " + f"rax = q; rdx = hi; }}") + else: # M.IDIV + if size == 4: + stmt = (f"{{ const int64_t num = static_cast<int64_t>((static_cast<uint64_t>(static_cast<uint32_t>(rdx)) << 32) | static_cast<uint32_t>(rax)); " + f"const int32_t den = static_cast<int32_t>({operand(0)}); " + f"rax = static_cast<uint32_t>(static_cast<int32_t>(num / den)); rdx = static_cast<uint32_t>(static_cast<int32_t>(num % den)); }}") + else: + stmt = (f"{{ uint64_t hi = rdx, lo = rax, d = {operand(0)}; " + f"const bool neg_n = (hi >> 63) != 0, neg_d = (d >> 63) != 0; " + f"if (neg_n) {{ lo = 0ull - lo; hi = ~hi + (lo == 0ull ? 1ull : 0ull); }} " + f"if (neg_d) {{ d = 0ull - d; }} uint64_t q = 0; " + f"for (int b = 63; b >= 0; --b) {{ const bool top = (hi >> 63) != 0; " + f"hi = (hi << 1) | ((lo >> b) & 1u); if (top || hi >= d) {{ hi -= d; q |= 1ull << b; }} }} " + f"rax = (neg_n != neg_d) ? (0ull - q) : q; rdx = neg_n ? (0ull - hi) : hi; }}") + elif op in (M.XADD, M.CMPXCHG): + size = MemorySizeExt.size(i.memory_size) if i.op0_kind == K.MEMORY else RegisterExt.size(i.op0_register) + if size not in (4, 8): + raise ValueError(f"unsupported query operation at {i.ip:#x}: {i}") + width = UINT[size] + if op == M.XADD: + src_dst = reg(i.op1_register) + stmt = (f"{{ const {width} a = {operand(0)}, b = {operand(1)}, v = static_cast<{width}>(a + b); " + f"carry = v < a; zero = v == 0; {src_dst} = a; {write('v')} }}") ~~~~ --- **<sub><sub>![P1 Badge](https://img.shields.io/badge/P1-orange?style=flat)</sub></sub> Snapshot the effective address before updating the XADD source** When the memory operand uses the source register as its base or index (e.g. `xadd qword ptr [rcx], rcx`), this assignment updates `rcx` before `write('v')` reevaluates `address()`. The store therefore goes to an address derived from the old memory contents rather than the original effective address, potentially corrupting unrelated memory or faulting. This reproduced in a native-versus-emitted Linux/x86-64 probe. Capture the effective address before updating the source register and reuse it for the load and store. Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
chatgpt-codex-connector[bot commented 2026-11-24 06:50:36 +00:00 (Migrated from github.com)

Imported from R0Y00/Xbox2Windows. Originally posted by chatgpt-codex-connector[bot] on 2026-11-21T22:33:46Z.

Code review location: tools/ffx_version_query.py; line 188

@@ -163,33 +163,54 @@ def write(expr):
                       M.INC: "", M.DEC: "", M.XOR: "carry = false;", M.AND: "carry = false;", M.OR: "carry = false;"}[op]
             stmt = (f"{{ const {width} a = {operand(0)}, b = static_cast<{width}>({rhs}); "
                     f"const {width} v = static_cast<{width}>({expr}); {update} zero = v == 0; {write('v')} }}")
-        elif op in (M.ANDN, M.BEXTR, M.BLSI, M.BLSMSK, M.BLSR, M.TZCNT) and RegisterExt.size(i.op0_register) in (4, 8):
-            size = RegisterExt.size(i.op0_register)
-            width, bits = UINT[size], 8 * size
-            if op == M.ANDN:
-                stmt = (f"{{ const {width} v = static_cast<{width}>(~static_cast<{width}>({operand(1)}) "
-                        f"& static_cast<{width}>({operand(2)})); carry = false; zero = v == 0; {write('v')} }}")
-            elif op == M.BEXTR:
-                stmt = (f"{{ const {width} a = {operand(1)}, ctrl = {operand(2)}; "
-                        f"const unsigned start = static_cast<unsigned>(ctrl & 0xffu), "
-                        f"len = static_cast<unsigned>((ctrl >> 8) & 0xffu); "
-                        f"{width} v = 0; if (start < {bits}u && len > 0u) {{ "
-                        f"const {width} s = a >> start; "
-                        f"v = len >= {bits}u ? s : static_cast<{width}>(s & ((static_cast<{width}>(1) << len) - 1)); }} "
-                        f"carry = false; zero = v == 0; {write('v')} }}")
-            elif op == M.BLSI:
-                stmt = (f"{{ const {width} a = {operand(1)}, v = static_cast<{width}>(a & (static_cast<{width}>(0) - a)); "
-                        f"carry = a != 0; zero = v == 0; {write('v')} }}")
-            elif op == M.BLSMSK:
-                stmt = (f"{{ const {width} a = {operand(1)}, v = static_cast<{width}>(a ^ (a - 1)); "
-                        f"carry = a == 0; zero = false; {write('v')} }}")
-            elif op == M.BLSR:
-                stmt = (f"{{ const {width} a = {operand(1)}, v = static_cast<{width}>(a & (a - 1)); "
-                        f"carry = a == 0; zero = v == 0; {write('v')} }}")
-            else:  # M.TZCNT
-                stmt = (f"{{ const {width} a = {operand(1)}; {width} v = 0; "
-                        f"if (a == 0) {{ v = {bits}; }} else {{ while (((a >> v) & 1) == 0) ++v; }} "
-                        f"carry = a == 0; zero = v == 0; {write('v')} }}")
+        elif op in (M.MUL, M.DIV, M.IDIV):
+            size = MemorySizeExt.size(i.memory_size) if i.op0_kind == K.MEMORY else RegisterExt.size(i.op0_register)
+            if size not in (4, 8):
+                raise ValueError(f"unsupported query operation at {i.ip:#x}: {i}")
+            if op == M.MUL:
+                if size == 4:
+                    stmt = (f"{{ const uint64_t p = static_cast<uint64_t>(static_cast<uint32_t>(rax)) * static_cast<uint32_t>({operand(0)}); "
+                            f"rax = static_cast<uint32_t>(p); rdx = static_cast<uint32_t>(p >> 32); carry = rdx != 0; }}")
+                else:
+                    stmt = (f"{{ const uint64_t a = rax, b = {operand(0)}; "
+                            f"const uint64_t a0 = static_cast<uint32_t>(a), a1 = a >> 32, b0 = static_cast<uint32_t>(b), b1 = b >> 32; "
+                            f"const uint64_t p0 = a0 * b0, p1 = a0 * b1, p2 = a1 * b0, p3 = a1 * b1; "
+                            f"const uint64_t mid = (p0 >> 32) + static_cast<uint32_t>(p1) + static_cast<uint32_t>(p2); "
+                            f"rax = (p0 & 0xffffffffull) | (mid << 32); rdx = p3 + (p1 >> 32) + (p2 >> 32) + (mid >> 32); carry = rdx != 0; }}")
+            elif op == M.DIV:
+                if size == 4:
+                    stmt = (f"{{ const uint64_t num = (static_cast<uint64_t>(static_cast<uint32_t>(rdx)) << 32) | static_cast<uint32_t>(rax); "
+                            f"const uint32_t den = {operand(0)}; rax = static_cast<uint32_t>(num / den); rdx = static_cast<uint32_t>(num % den); }}")
+                else:
+                    stmt = (f"{{ uint64_t hi = rdx, lo = rax, den = {operand(0)}, q = 0; "
+                            f"for (int b = 63; b >= 0; --b) {{ const bool top = (hi >> 63) != 0; "
+                            f"hi = (hi << 1) | ((lo >> b) & 1u); if (top || hi >= den) {{ hi -= den; q |= 1ull << b; }} }} "
+                            f"rax = q; rdx = hi; }}")

P2 Badge Preserve divide errors for zero divisors and quotient overflow

For a zero divisor or an out-of-range quotient, x86 DIV/IDIV must raise #DE, but these paths continue with fabricated results. In a native-versus-emitted Linux/x86-64 probe, div r64 with RDX:RAX=0:7 and divisor 0 returned UINT64_MAX here, and 32-bit div with EDX:EAX=1:0 and divisor 1 returned 0; both native instructions faulted. The signed branches likewise omit quotient-range checks. Check the divisor and quotient bounds before updating guest registers, and add the corresponding failure cases to the new fixture.

AGENTS.md reference: AGENTS.md:L133-L133

Useful? React with 👍 / 👎.

<!-- greyfinch-sync:R0Y00/Xbox2Windows:review-comment:4655335499 --> Imported from [R0Y00/Xbox2Windows](https://github.com/R0Y00/Xbox2Windows/pull/331#discussion_r4655335499). Originally posted by [chatgpt-codex-connector[bot]](https://github.com/chatgpt-codex-connector%5Bbot%5D) on 2026-11-21T22:33:46Z. **Code review location:** `tools/ffx_version_query.py`; line 188 ~~~~diff @@ -163,33 +163,54 @@ def write(expr): M.INC: "", M.DEC: "", M.XOR: "carry = false;", M.AND: "carry = false;", M.OR: "carry = false;"}[op] stmt = (f"{{ const {width} a = {operand(0)}, b = static_cast<{width}>({rhs}); " f"const {width} v = static_cast<{width}>({expr}); {update} zero = v == 0; {write('v')} }}") - elif op in (M.ANDN, M.BEXTR, M.BLSI, M.BLSMSK, M.BLSR, M.TZCNT) and RegisterExt.size(i.op0_register) in (4, 8): - size = RegisterExt.size(i.op0_register) - width, bits = UINT[size], 8 * size - if op == M.ANDN: - stmt = (f"{{ const {width} v = static_cast<{width}>(~static_cast<{width}>({operand(1)}) " - f"& static_cast<{width}>({operand(2)})); carry = false; zero = v == 0; {write('v')} }}") - elif op == M.BEXTR: - stmt = (f"{{ const {width} a = {operand(1)}, ctrl = {operand(2)}; " - f"const unsigned start = static_cast<unsigned>(ctrl & 0xffu), " - f"len = static_cast<unsigned>((ctrl >> 8) & 0xffu); " - f"{width} v = 0; if (start < {bits}u && len > 0u) {{ " - f"const {width} s = a >> start; " - f"v = len >= {bits}u ? s : static_cast<{width}>(s & ((static_cast<{width}>(1) << len) - 1)); }} " - f"carry = false; zero = v == 0; {write('v')} }}") - elif op == M.BLSI: - stmt = (f"{{ const {width} a = {operand(1)}, v = static_cast<{width}>(a & (static_cast<{width}>(0) - a)); " - f"carry = a != 0; zero = v == 0; {write('v')} }}") - elif op == M.BLSMSK: - stmt = (f"{{ const {width} a = {operand(1)}, v = static_cast<{width}>(a ^ (a - 1)); " - f"carry = a == 0; zero = false; {write('v')} }}") - elif op == M.BLSR: - stmt = (f"{{ const {width} a = {operand(1)}, v = static_cast<{width}>(a & (a - 1)); " - f"carry = a == 0; zero = v == 0; {write('v')} }}") - else: # M.TZCNT - stmt = (f"{{ const {width} a = {operand(1)}; {width} v = 0; " - f"if (a == 0) {{ v = {bits}; }} else {{ while (((a >> v) & 1) == 0) ++v; }} " - f"carry = a == 0; zero = v == 0; {write('v')} }}") + elif op in (M.MUL, M.DIV, M.IDIV): + size = MemorySizeExt.size(i.memory_size) if i.op0_kind == K.MEMORY else RegisterExt.size(i.op0_register) + if size not in (4, 8): + raise ValueError(f"unsupported query operation at {i.ip:#x}: {i}") + if op == M.MUL: + if size == 4: + stmt = (f"{{ const uint64_t p = static_cast<uint64_t>(static_cast<uint32_t>(rax)) * static_cast<uint32_t>({operand(0)}); " + f"rax = static_cast<uint32_t>(p); rdx = static_cast<uint32_t>(p >> 32); carry = rdx != 0; }}") + else: + stmt = (f"{{ const uint64_t a = rax, b = {operand(0)}; " + f"const uint64_t a0 = static_cast<uint32_t>(a), a1 = a >> 32, b0 = static_cast<uint32_t>(b), b1 = b >> 32; " + f"const uint64_t p0 = a0 * b0, p1 = a0 * b1, p2 = a1 * b0, p3 = a1 * b1; " + f"const uint64_t mid = (p0 >> 32) + static_cast<uint32_t>(p1) + static_cast<uint32_t>(p2); " + f"rax = (p0 & 0xffffffffull) | (mid << 32); rdx = p3 + (p1 >> 32) + (p2 >> 32) + (mid >> 32); carry = rdx != 0; }}") + elif op == M.DIV: + if size == 4: + stmt = (f"{{ const uint64_t num = (static_cast<uint64_t>(static_cast<uint32_t>(rdx)) << 32) | static_cast<uint32_t>(rax); " + f"const uint32_t den = {operand(0)}; rax = static_cast<uint32_t>(num / den); rdx = static_cast<uint32_t>(num % den); }}") + else: + stmt = (f"{{ uint64_t hi = rdx, lo = rax, den = {operand(0)}, q = 0; " + f"for (int b = 63; b >= 0; --b) {{ const bool top = (hi >> 63) != 0; " + f"hi = (hi << 1) | ((lo >> b) & 1u); if (top || hi >= den) {{ hi -= den; q |= 1ull << b; }} }} " + f"rax = q; rdx = hi; }}") ~~~~ --- **<sub><sub>![P2 Badge](https://img.shields.io/badge/P2-yellow?style=flat)</sub></sub> Preserve divide errors for zero divisors and quotient overflow** For a zero divisor or an out-of-range quotient, x86 `DIV`/`IDIV` must raise `#DE`, but these paths continue with fabricated results. In a native-versus-emitted Linux/x86-64 probe, `div r64` with `RDX:RAX=0:7` and divisor 0 returned `UINT64_MAX` here, and 32-bit `div` with `EDX:EAX=1:0` and divisor 1 returned 0; both native instructions faulted. The signed branches likewise omit quotient-range checks. Check the divisor and quotient bounds before updating guest registers, and add the corresponding failure cases to the new fixture. AGENTS.md reference: [AGENTS.md:L133-L133](https://github.com/R0Y00/Xbox2Windows/blob/85491d3932e4eb7490ca69fc0ca40fb976f2a2bd/AGENTS.md#L133-L133) Useful? React with 👍 / 👎. <!-- codex-code-review-finding:v1 -->
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
R0Y00/Xbox2Windows!326
No description provided.