diff --git a/CMakeLists.txt b/CMakeLists.txt index 3416c77ea..eb2275ace 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -605,6 +605,21 @@ if(EXISTS "${INTAKE_PYTHON}") add_library(cpu_heap_layout_lifted SHARED "${heap_fixture}") add_test(NAME cpu_aot_heap_layout COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/heap_layout.py" check "$" "$") + cpu_asm_fixture(cpu_rcx_branches rcx_branches) + # The lifted DLL and three mutated controls that the check requires to mismatch. + foreach(variant IN ITEMS lifted noecx nozf jrcxz) + set(rcx_branches_fixture "${CMAKE_CURRENT_BINARY_DIR}/cpu_rcx_branches_${variant}.cpp") + add_custom_command(OUTPUT "${rcx_branches_fixture}" + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/rcx_branches.py" + emit "$" "${rcx_branches_fixture}" ${variant} + DEPENDS cpu_rcx_branches tests/cpu/rcx_branches.py tools/ffx_version_query.py + tools/cpu_ranges.py tools/cpu_leaf_aot.py VERBATIM) + add_library(cpu_rcx_branches_${variant} SHARED "${rcx_branches_fixture}") + endforeach() + add_test(NAME cpu_aot_rcx_branches COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/rcx_branches.py" + check "$" "$" + "$" "$" + "$") cpu_asm_fixture(cpu_shift_count shift_count) set(shift_fixture "${CMAKE_CURRENT_BINARY_DIR}/cpu_shift_count_lifted.cpp") add_custom_command(OUTPUT "${shift_fixture}" diff --git a/docs/experiments.md b/docs/experiments.md index 404aed322..99a946bc9 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -414,6 +414,24 @@ A 67h address-size prefix selects 32-bit addressing. The lowering wraps base + i XLATB replaces AL with the byte at RBX + AL. AL is zero-extended, and bits 8 to 63 of RAX and the flags are unchanged. With a 67h prefix the base is EBX and the sum wraps at 32 bits, so the upper half of RBX is ignored. A REX.W prefix (`48 d7`) does not change the operation. `cpu_aot_xlatb` builds four exports from [MASM source](../tests/cpu/xlatb.asm): the plain, REX.W and 67h forms, and two lookups in a row. Each export runs on a 256-byte permutation table in a page committed below 4 GiB. The check compares RAX and ZF/CF for every AL value, with noise in the upper bits of RAX and, for the 67h form, in the upper half of RBX, against the native DLL and an independent reference. Three controls mutate the generated C++ and must mismatch: `signed` sign-extends AL, `noaddr32` keeps the upper half of RBX in the 67h sum (whose reads fault), and `clear` writes the loaded byte over all of RAX. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_xlatb$' -V`. +The RCX-counted branches `loop`, `loope`, `loopne` and `jrcxz` lower to a decrement and a conditional `goto`, and so do their 67h forms, which count in ECX. The behaviour is as follows: +- None of them changes a flag. +- `loope` and `loopne` test ZF after the decrement. +- `jrcxz` and `jecxz` only test the count. +- The ECX forms decrement ECX as a 32-bit write, which clears the upper half of RCX. The native fixture confirms this on the cases with noise in the upper half. + +`cpu_aot_rcx_branches` builds eight exports from MASM source (`tests/cpu/rcx_branches.asm`) and compares 7712 cases against the native DLL, the translation and a Python reference. Each case records RAX, RCX, the final pointer and ZF/CF. The exports are: +- iteration counts with each ZF/CF preset, which must survive `loop`; +- byte scans under `loope` and `loopne` guarded by `jrcxz`, which exit on the first element, a later one or at count exhaustion; +- `jrcxz` and `jecxz` on counts that differ only in the upper half of RCX. + +Three mutated translations must each mismatch: +- the ECX decrement keeping the upper half of RCX, with `jecxz` testing all of RCX; +- `loope` and `loopne` ignoring ZF; +- `jrcxz` inverted. + +Run `ctest --preset dev --no-tests=error -R '^cpu_aot_rcx_branches$' -V`. + An immediate SHL, SHR or SAR whose masked count is zero leaves the flags unchanged, but a 32-bit destination is still written and its upper half clears. This covers `shl eax, 0` and `shl eax, 32`, because the count is masked to five bits. The lowering keeps the flags and emits the zero-extending write. A 64-bit destination keeps every bit. `cpu_aot_shift_count` builds these forms from MASM source, together with a nonzero control. It compares the native and translated images with a reference and checks that `sete` after a zero-count shift still observes the preceding compare. Before this change the translation returned `0xdeadbeef12345678` for `shl_zero(0xdeadbeef12345678)` where the hardware returns `0x12345678`. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_shift_count$' -V`. The shared lowering also handles 32-bit and 64-bit BMI1 bit-manipulation forms (`andn`, `bextr`, `blsi`, `blsmsk`, `blsr`, `tzcnt`), including their zero-extending 32-bit writes and ZF/CF updates. `cpu_aot_bmi1` probes CPUID leaf 7 EBX bit 3 (`BMI1`) before invoking the native fixture and exits 77 (capability skip) on hosts without BMI1; on BMI1-capable hosts it builds all twelve 32-bit and 64-bit exports from MASM source (`tests/cpu/bmi1.asm`), translates them, compares both values and observed ZF/CF flags against the native DLL and an independent reference, and checks that 16-bit `tzcnt` is rejected. Run `cmake --build --preset dev --target cpu_bmi1_lifted` and `ctest --preset dev --no-tests=error -R '^cpu_aot_bmi1$' -V`. diff --git a/tests/cpu/rcx_branches.asm b/tests/cpu/rcx_branches.asm new file mode 100644 index 000000000..5511443d4 --- /dev/null +++ b/tests/cpu/rcx_branches.asm @@ -0,0 +1,130 @@ +; Source-owned differential fixture for the RCX-counted branches LOOP, LOOPE, LOOPNE and JRCXZ, and their +; 67h (ECX) forms loopd, looped, loopned and jecxz. Each export takes (count, pointer, value or preset, +; state) in RCX, RDX, R8 and R9, returns RAX and writes (CF << 1) | ZF, RCX and the final pointer offset +; to state[0..2]. The 67h prefix of the ECX LOOP forms is emitted with db; jecxz has its own spelling. +.code + +BRANCH_LEAVE MACRO + LOCAL no_carry, no_zero + mov r11d, 0 + jae short no_carry + mov r11d, 2 +no_carry: + jne short no_zero + or r11d, 1 +no_zero: + mov qword ptr [r9], r11 + mov qword ptr [r9+8], rcx + sub r10, rdx + mov qword ptr [r9+16], r10 + ret +ENDM + +; RAX counts the iterations. LEA leaves the flags from add r8, r8 untouched, so they must survive LOOP. +loop_count PROC FRAME + .endprolog + mov r10, rdx + mov eax, 0 + add r8, r8 +again: + lea rax, [rax+1] + loop again + BRANCH_LEAVE +loop_count ENDP + +loopd_count PROC FRAME + .endprolog + mov r10, rdx + mov eax, 0 + add r8, r8 +again: + lea rax, [rax+1] + db 67h + loop again + BRANCH_LEAVE +loopd_count ENDP + +; Scan bytes from RDX while they equal (LOOPE) or differ from (LOOPNE) the low byte of R8. JRCXZ skips +; the scan for a zero count, and the flags then come from add r8, 0. +loope_scan PROC FRAME + .endprolog + mov r10, rdx + mov eax, 0 + add r8, 0 + jrcxz done +again: + cmp byte ptr [r10], r8b + lea r10, [r10+1] + loope again +done: + BRANCH_LEAVE +loope_scan ENDP + +loopne_scan PROC FRAME + .endprolog + mov r10, rdx + mov eax, 0 + add r8, 0 + jrcxz done +again: + cmp byte ptr [r10], r8b + lea r10, [r10+1] + loopne again +done: + BRANCH_LEAVE +loopne_scan ENDP + +looped_scan PROC FRAME + .endprolog + mov r10, rdx + mov eax, 0 + add r8, 0 + jecxz done +again: + cmp byte ptr [r10], r8b + lea r10, [r10+1] + db 67h + loope again +done: + BRANCH_LEAVE +looped_scan ENDP + +loopned_scan PROC FRAME + .endprolog + mov r10, rdx + mov eax, 0 + add r8, 0 + jecxz done +again: + cmp byte ptr [r10], r8b + lea r10, [r10+1] + db 67h + loopne again +done: + BRANCH_LEAVE +loopned_scan ENDP + +; RAX = 1 when the branch is taken, 2 otherwise; the flags from add r8, r8 must survive. +jrcxz_probe PROC FRAME + .endprolog + mov r10, rdx + mov eax, 1 + add r8, r8 + jrcxz taken + mov eax, 2 +taken: + BRANCH_LEAVE +jrcxz_probe ENDP + +jecxz_probe PROC FRAME + .endprolog + mov r10, rdx + mov eax, 1 + add r8, r8 + jecxz taken + mov eax, 2 +taken: + BRANCH_LEAVE +jecxz_probe ENDP + +END diff --git a/tests/cpu/rcx_branches.def b/tests/cpu/rcx_branches.def new file mode 100644 index 000000000..ce81e18ff --- /dev/null +++ b/tests/cpu/rcx_branches.def @@ -0,0 +1,9 @@ +EXPORTS + loop_count + loopd_count + loope_scan + loopne_scan + looped_scan + loopned_scan + jrcxz_probe + jecxz_probe diff --git a/tests/cpu/rcx_branches.py b/tests/cpu/rcx_branches.py new file mode 100644 index 000000000..3b5aea233 --- /dev/null +++ b/tests/cpu/rcx_branches.py @@ -0,0 +1,178 @@ +"""Compare native and translated LOOP, LOOPE, LOOPNE, JRCXZ and their ECX (67h) forms.""" +import ctypes +from pathlib import Path +import re +import sys + +import pefile +from iced_x86 import Code + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "tools")) +from cpu_leaf_aot import export_rva +from cpu_ranges import function_ranges +from ffx_version_query import INTEGER_HEADER, lower, region + +U64 = ctypes.c_uint64 +MASK64 = (1 << 64) - 1 +MASK32 = (1 << 32) - 1 + +# Every branch Code the fixture must contain, so a misassembled prefix cannot pass silently. +EXPECTED_CODES = { + "loop_count": Code.LOOP_REL8_64_RCX, "loopd_count": Code.LOOP_REL8_64_ECX, + "loope_scan": Code.LOOPE_REL8_64_RCX, "loopne_scan": Code.LOOPNE_REL8_64_RCX, + "looped_scan": Code.LOOPE_REL8_64_ECX, "loopned_scan": Code.LOOPNE_REL8_64_ECX, + "jrcxz_probe": Code.JRCXZ_REL8_64, "jecxz_probe": Code.JECXZ_REL8_64, +} +EXPORTS = tuple(EXPECTED_CODES) + +# Source mutations of the generated C++. Each control DLL must disagree with the reference somewhere. +CONTROLS = { + # The ECX decrement keeps the upper half of RCX, and JECXZ tests all of RCX. (A full 64-bit LOOP would + # run for about 2^47 iterations on the cases with upper-half noise, so the loop test stays on ECX.) + "noecx": (re.compile(r"rcx = static_cast\(rcx - 1\);|if \(static_cast\(rcx\) == 0\)"), + lambda m: ("rcx = (rcx & ~0xffffffffull) | static_cast(rcx - 1);" + if m.group(0).startswith("rcx =") else "if (rcx == 0)")), + # LOOPE and LOOPNE ignore ZF and behave like LOOP. + "nozf": (re.compile(r" && !?zero\)"), ")"), + # JRCXZ and JECXZ branch on a nonzero count. + "jrcxz": (re.compile(r"== 0\) goto"), "!= 0) goto"), +} + +# Runs of equal and unequal bytes. The final 0 ends every scan, even in a control that skips the zero-count +# guard, before it can leave the buffer. +SCAN = bytes([7] * 12 + [3] + [7] * 5 + [9, 9, 9, 7, 7, 7] + list(range(40, 80)) + [0]) +PRESETS = (0, 1, 1 << 63, 3 << 62) # add r8, r8: (ZF, CF) = (1, 0), (0, 0), (1, 1), (0, 1) +UPPER = (0, 0xabcd, MASK32) + + +def emit(image, output, control="lifted"): + parts = [INTEGER_HEADER] + with pefile.PE(str(image), fast_load=True) as pe: + for name in EXPORTS: + (bounds,) = function_ranges(pe, export_rva(pe, name)) + body = region(pe, *bounds) + codes = {i.code for i in body} + if EXPECTED_CODES[name] not in codes: + raise AssertionError(f"{name} does not contain {EXPECTED_CODES[name]}") + code = lower(body, ["rcx = a; rdx = b; r8 = c; r9 = state;"], {}, {}, {}) + parts.append(f'extern "C" __declspec(dllexport) word {name}(word a, word b, word c, word state) {{\n{code}\n}}\n') + text = "".join(parts) + if control != "lifted": + expression, replacement = CONTROLS[control] + text, count = expression.subn(replacement, text) + if not count: + raise AssertionError(f"control {control} changed nothing") + print(f"control {control}: {count} replacements") + output.write_text(text, encoding="ascii") + + +def preset_flags(preset): + total = preset + preset + return int(total & MASK64 == 0), int(total > MASK64) + + +def reference(name, count, offset, value): + """(RAX, state[0] flags, state[1] RCX, state[2] pointer offset).""" + ecx = name in ("loopd_count", "looped_scan", "loopned_scan", "jecxz_probe") + + def low(rcx): + return rcx & MASK32 if ecx else rcx + + def decrement(rcx): + return (rcx - 1) & MASK32 if ecx else (rcx - 1) & MASK64 # a 32-bit write zero-extends + + rcx = count + if name in ("loop_count", "loopd_count"): + zf, cf = preset_flags(value) + rax = 0 + while True: + rax += 1 + rcx = decrement(rcx) + if low(rcx) == 0: + break + return rax, cf << 1 | zf, rcx, 0 + if name in ("jrcxz_probe", "jecxz_probe"): + zf, cf = preset_flags(value) + return (1 if low(rcx) == 0 else 2), cf << 1 | zf, rcx, 0 + # Scans: the flags start from add r8, 0 and then come from each cmp. + zf, cf = int(value == 0), 0 + pointer = offset + if low(rcx) != 0: + while True: + a, b = SCAN[pointer], value & 0xff + zf, cf = int(a == b), int(a < b) + pointer += 1 + rcx = decrement(rcx) + keep = zf if name in ("loope_scan", "looped_scan") else not zf + if not (low(rcx) != 0 and keep): + break + return 0, cf << 1 | zf, rcx, pointer - offset + + +def cases(): + for name in EXPORTS: + if name in ("loop_count", "loopd_count"): + for upper in (UPPER if name == "loopd_count" else (0,)): + for n in (*range(1, 41), 1000): + for preset in PRESETS: + yield name, (upper << 32 | n, 0, preset) + elif name in ("jrcxz_probe", "jecxz_probe"): + for rcx in (0, 1, 1 << 32, MASK32, MASK64, 0xabcd00000000, 0xabcd00000001): + for preset in PRESETS: + yield name, (rcx, 0, preset) + else: + ecx = name.startswith(("looped", "loopned")) + for upper in (UPPER if ecx else (0,)): + for n in range(0, 25): + for offset in (0, 10, 12, 13, 18, 21, 24): + for value in (7, 3, 9, 0, 45): + yield name, (upper << 32 | n, offset, value) + + +def load_lib(path): + lib = ctypes.CDLL(str(Path(path).resolve())) + for name in EXPORTS: + fn = getattr(lib, name) + fn.argtypes, fn.restype = [U64, ctypes.c_void_p, U64, ctypes.POINTER(U64 * 3)], U64 + return lib + + +def mismatches(lib, expected): + buffer = (ctypes.c_uint8 * len(SCAN)).from_buffer_copy(SCAN) + state = (U64 * 3)() + found = [] + for name, (count, offset, value), want in expected: + state[0] = state[1] = state[2] = 0xdeadbeef + rax = getattr(lib, name)(count, ctypes.addressof(buffer) + offset, value, ctypes.byref(state)) + got = (rax, state[0], state[1], state[2]) + if got != want: + found.append((name, (count, offset, value), want, got)) + return found + + +def check(native_path, lifted_path, *control_paths): + expected = [(name, args, reference(name, *args)) for name, args in cases()] + for label, path in (("native", native_path), ("lifted", lifted_path)): + bad = mismatches(load_lib(path), expected) + if bad: + name, args, want, got = bad[0] + raise AssertionError(f"{label}: {len(bad)} mismatches; first {name}{tuple(hex(a) for a in args)} = " + f"{tuple(hex(g) for g in got)}, expected {tuple(hex(w) for w in want)}") + print(f"{len(expected)} cases over {len(EXPORTS)} exports (RAX, RCX, pointer, ZF/CF) matched the reference " + "in native and translated DLLs") + for path in control_paths: + control = Path(path).stem.rsplit("_", 1)[-1] + bad = mismatches(load_lib(path), expected) + print(f"control {control}: {len(bad)}/{len(expected)} mismatches") + if not bad: + raise AssertionError(f"control {control} matched every case") + + +if __name__ == "__main__": + mode, native, other, *rest = sys.argv[1:] + if mode == "emit": + emit(Path(native), Path(other), *rest) + elif mode == "check": + check(native, other, *rest) + else: + raise ValueError(mode) diff --git a/tools/ffx_version_query.py b/tools/ffx_version_query.py index 31864c21b..24bba6625 100644 --- a/tools/ffx_version_query.py +++ b/tools/ffx_version_query.py @@ -4,7 +4,7 @@ from pathlib import Path import pefile -from iced_x86 import Decoder, MemorySizeExt, Mnemonic as M, OpKind as K, Register as R, RegisterExt +from iced_x86 import Code as C, Decoder, MemorySizeExt, Mnemonic as M, OpKind as K, Register as R, RegisterExt from cpu_leaf_aot import export_rva from cpu_ranges import function_ranges, image_bytes @@ -123,6 +123,20 @@ def write(expr): cond = {M.JE: "if (zero) ", M.JNE: "if (!zero) ", M.JAE: "if (!carry) ", M.JA: "if (!carry && !zero) ", M.JB: "if (carry) ", M.JBE: "if (carry || zero) ", M.JMP: ""}[op] stmt = f"{cond}goto block_{target:x};" + elif op in (M.LOOP, M.LOOPE, M.LOOPNE, M.JRCXZ, M.JECXZ): + # RCX-counted branches. A 67h prefix selects ECX (loopd, jecxz). None of them changes a flag; + # LOOPE and LOOPNE test ZF after the decrement. + target = i.near_branch_target + if target not in allowed: + raise ValueError(f"unbound branch at {i.ip:#x}") + ecx = i.code in (C.LOOP_REL8_64_ECX, C.LOOPE_REL8_64_ECX, C.LOOPNE_REL8_64_ECX, C.JECXZ_REL8_64) + count = "static_cast(rcx)" if ecx else "rcx" + if op in (M.JRCXZ, M.JECXZ): + stmt = f"if ({count} == 0) goto block_{target:x};" + else: + decrement = "rcx = static_cast(rcx - 1);" if ecx else "--rcx;" + condition = {M.LOOP: "", M.LOOPE: " && zero", M.LOOPNE: " && !zero"}[op] + stmt = f"{decrement} if ({count} != 0{condition}) goto block_{target:x};" elif op in (M.MOV, M.MOVZX): stmt = write(operand(1)) elif op == M.MOVSXD: diff --git a/tools/form_coverage.py b/tools/form_coverage.py index 0b7f062e2..f7cfa8519 100644 --- a/tools/form_coverage.py +++ b/tools/form_coverage.py @@ -37,6 +37,7 @@ # map to None: their forms are known but never covered. An unlisted .asm is reported as unclassified. CPU_FIXTURES = { "branch": "cpu_leaf_aot_branches", + "rcx_branches": "cpu_aot_rcx_branches", "direct": "cpu_aot_direct_call", "chained": "cpu_aot_chained_ranges", "callback": "cpu_aot_object_callback",