diff --git a/CMakeLists.txt b/CMakeLists.txt index dc5195497..38c296db4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -637,6 +637,21 @@ if(EXISTS "${INTAKE_PYTHON}") add_library(cpu_address_size_lifted SHARED "${address_fixture}") add_test(NAME cpu_aot_address_size COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/address_size.py" check "$" "$") + cpu_asm_fixture(cpu_movbe movbe) + # The lifted DLL and three mutated controls that the check requires to mismatch. + foreach(variant IN ITEMS lifted noswap clear16 flags) + set(movbe_fixture "${CMAKE_CURRENT_BINARY_DIR}/cpu_movbe_${variant}.cpp") + add_custom_command(OUTPUT "${movbe_fixture}" + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/movbe.py" + emit "$" "${movbe_fixture}" ${variant} + DEPENDS cpu_movbe tests/cpu/movbe.py tools/ffx_version_query.py + tools/cpu_ranges.py tools/cpu_leaf_aot.py VERBATIM) + add_library(cpu_movbe_${variant} SHARED "${movbe_fixture}") + endforeach() + add_test(NAME cpu_aot_movbe COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/movbe.py" + check "$" "$" + "$" "$" "$") + set_tests_properties(cpu_aot_movbe PROPERTIES SKIP_RETURN_CODE 77) cpu_asm_fixture(cpu_bmi1 bmi1) set(bmi1_fixture "${CMAKE_CURRENT_BINARY_DIR}/cpu_bmi1_lifted.cpp") add_custom_command(OUTPUT "${bmi1_fixture}" diff --git a/docs/experiments.md b/docs/experiments.md index 4904f0fc0..64fe40de5 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -406,6 +406,8 @@ cl /nologo /O2 /EHsc /LD /Fo:out/ffx-query/query.obj out/ffx-query/query.cpp /li The public CTest `cpu_aot_version_query` runs the same output checks against an independent MASM fixture and its translation. The fixture uses a different name and 64-bit ID. The two proprietary inputs and generated code stay local. +The integer lowering also handles MOVBE, the byte-reversing move between memory and a 16-, 32- or 64-bit register, in both directions. It changes no flags. A 16-bit register destination keeps bits 16 to 63, and a 32-bit destination clears its upper half. `cpu_aot_movbe` exits 77 (capability skip) when CPUID leaf 1 ECX bit 22 (`MOVBE`) is clear. Otherwise it builds ten exports from [MASM source](../tests/cpu/movbe.asm), covering loads, stores, REX registers, displacements, a scaled index and a load stored back. It compares RAX, ZF/CF, the data bytes and 64 guard bytes on each side, at nine offsets including misaligned ones, against the native DLL and an independent reference. Three controls mutate the generated C++ and must mismatch: `noswap` copies the bytes in memory order (2592/2880 cases), `clear16` zero-extends a 16-bit destination (360/2880), and `flags` clears ZF and CF (2160/2880). Run `ctest --preset dev --no-tests=error -R '^cpu_aot_movbe$' -V`. + The shared integer lowering in this tool emits flat loads and stores, so it rejects FS or GS segment overrides and LOCK prefixes instead of dropping them. A thread-block access such as `gs:[0x30]` would otherwise read absolute address 0x30, and a locked read-modify-write would lose its atomicity. Segment overrides without effect in 64-bit mode and `rep ret` lower like the bare instruction. A host operation that replaces an instruction bypasses the check. `ctest --preset dev --no-tests=error -R '^cpu_lower_prefixes$' -V` checks 11 rejected encodings and 6 accepted controls with synthetic bytes. A 67h address-size prefix selects 32-bit addressing. The lowering wraps base + index × scale + displacement at 32 bits and zero-extends the result, ignoring the upper halves of the registers as the hardware does. In this mode iced reports a displacement of -8 as `0xfffffff8`, so the wrap is also needed when the upper halves are zero. EIP-relative operands are rejected because the hardware adds the low 32 bits of the runtime RIP, which an RVA binding cannot represent. `cpu_aot_address_size` builds `lea`, load and store forms such as `lea rax, [ecx+edx*8-8]` and `mov [ecx+edx], r8d` from MASM source. It translates them and compares both images with a 32-bit reference over wrapped sums and upper-half noise. The loads and stores use a page committed below 4 GiB, and each store must leave the rest of the page unchanged. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_address_size$' -V`. diff --git a/tests/cpu/movbe.asm b/tests/cpu/movbe.asm new file mode 100644 index 000000000..51ba06ff1 --- /dev/null +++ b/tests/cpu/movbe.asm @@ -0,0 +1,108 @@ +; Source-owned differential fixture for MOVBE loads and stores in 16-, 32- and 64-bit widths. Each export +; takes (pointer, value, flag preset, state) in RCX, RDX, R8 and R9. The destination register starts as +; RDX, so a 16-bit load must keep its upper bits and a 32-bit load must clear them. ADD R8, R8 sets ZF and +; CF from the preset before the MOVBE, which leaves the flags alone; (CF << 1) | ZF goes to state[0]. +.code + +MOVBE_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 + ret +ENDM + +load16 PROC FRAME + .endprolog + mov rax, rdx + add r8, r8 + movbe ax, word ptr [rcx] + MOVBE_LEAVE +load16 ENDP + +load32 PROC FRAME + .endprolog + mov rax, rdx + add r8, r8 + movbe eax, dword ptr [rcx] + MOVBE_LEAVE +load32 ENDP + +load64 PROC FRAME + .endprolog + mov rax, rdx + add r8, r8 + movbe rax, qword ptr [rcx] + MOVBE_LEAVE +load64 ENDP + +; REX.R destinations with a displacement. +load16_r10 PROC FRAME + .endprolog + mov r10, rdx + add r8, r8 + movbe r10w, word ptr [rcx+1] + mov rax, r10 + MOVBE_LEAVE +load16_r10 ENDP + +load64_r11 PROC FRAME + .endprolog + mov r11, rdx + add r8, r8 + movbe r11, qword ptr [rcx+3] + mov rax, r11 + MOVBE_LEAVE +load64_r11 ENDP + +store16 PROC FRAME + .endprolog + mov rax, rdx + add r8, r8 + movbe word ptr [rcx], dx + MOVBE_LEAVE +store16 ENDP + +store32 PROC FRAME + .endprolog + mov rax, rdx + add r8, r8 + movbe dword ptr [rcx], edx + MOVBE_LEAVE +store32 ENDP + +store64 PROC FRAME + .endprolog + mov rax, rdx + add r8, r8 + movbe qword ptr [rcx], rdx + MOVBE_LEAVE +store64 ENDP + +; A REX.R source and a scaled index: the store lands at pointer + 3. +store64_index PROC FRAME + .endprolog + mov r10, rdx + mov eax, 2 + add r8, r8 + movbe qword ptr [rcx+rax*2-1], r10 + mov rax, r10 + MOVBE_LEAVE +store64_index ENDP + +; Load and store back eight bytes further on: the bytes there come out in the original order. +roundtrip32 PROC FRAME + .endprolog + mov rax, rdx + add r8, r8 + movbe eax, dword ptr [rcx] + movbe dword ptr [rcx+8], eax + MOVBE_LEAVE +roundtrip32 ENDP + +END diff --git a/tests/cpu/movbe.def b/tests/cpu/movbe.def new file mode 100644 index 000000000..1c9e2cfab --- /dev/null +++ b/tests/cpu/movbe.def @@ -0,0 +1,11 @@ +EXPORTS + load16 + load32 + load64 + load16_r10 + load64_r11 + store16 + store32 + store64 + store64_index + roundtrip32 diff --git a/tests/cpu/movbe.py b/tests/cpu/movbe.py new file mode 100644 index 000000000..8f5ae2749 --- /dev/null +++ b/tests/cpu/movbe.py @@ -0,0 +1,165 @@ +"""Compare native and translated MOVBE loads and stores (16-, 32- and 64-bit).""" +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 + +# name: (direction, bytes, displacement from the pointer, MOVBE Code the export must contain). +EXPORTS = { + "load16": ("load", 2, 0, Code.MOVBE_R16_M16), + "load32": ("load", 4, 0, Code.MOVBE_R32_M32), + "load64": ("load", 8, 0, Code.MOVBE_R64_M64), + "load16_r10": ("load", 2, 1, Code.MOVBE_R16_M16), + "load64_r11": ("load", 8, 3, Code.MOVBE_R64_M64), + "store16": ("store", 2, 0, Code.MOVBE_M16_R16), + "store32": ("store", 4, 0, Code.MOVBE_M32_R32), + "store64": ("store", 8, 0, Code.MOVBE_M64_R64), + "store64_index": ("store", 8, 3, Code.MOVBE_M64_R64), + "roundtrip32": ("roundtrip", 4, 0, Code.MOVBE_M32_R32), +} + +# Source mutations of the generated C++. Each control DLL must disagree with the reference somewhere. +SWAP = re.compile(r"v = static_cast<(\w+)>\(\(v << 8\) \| \(\(a >> \(8 \* k\)\) & 0xffu\)\);") +CONTROLS = { + # The bytes are copied in memory order instead of reversed. + "noswap": (SWAP, lambda m: f"v = static_cast<{m.group(1)}>((v << 8) | ((a >> (8 * (sizeof v - 1 - k))) & 0xffu));"), + # A 16-bit register destination is zero-extended like a 32-bit one. + "clear16": (re.compile(r"\(r\w+ & ~65535ull\) \| "), ""), + # The swap also clears ZF and CF, as a flag-writing instruction would. + "flags": (SWAP, lambda m: m.group(0) + " zero = false; carry = false;"), +} + +PAD = 64 # guard bytes on each side of the data, compared like the data +DATA = bytes((0x11 * k + 0x5a) & 0xff for k in range(48)) +OFFSETS = (0, 1, 2, 3, 5, 7, 8, 13, 16) +VALUES = (0, 1, 0x0102030405060708, 0x8000000000000001, 0xffffffffffffffff, 0x00ff00ff00ff00ff, + 0xdeadbeefcafef00d, 0x7f) +PRESETS = (0, 1, 1 << 63, 3 << 62) # add r8, r8: (ZF, CF) = (1, 0), (0, 0), (1, 1), (0, 1) + + +def emit(image, output, control="lifted"): + parts = [ + "#include \n", + INTEGER_HEADER, + 'extern "C" __declspec(dllexport) int host_has_movbe() {\n' + " int regs[4]{};\n" + " __cpuid(regs, 1);\n" + " return (regs[2] & (1 << 22)) != 0;\n" + "}\n", + ] + with pefile.PE(str(image), fast_load=True) as pe: + for name, (*_, code) in EXPORTS.items(): + (bounds,) = function_ranges(pe, export_rva(pe, name)) + body = region(pe, *bounds) + if code not in {i.code for i in body}: + raise AssertionError(f"{name} does not contain {code}") + lowered = 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{lowered}\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 swapped(raw): + return int.from_bytes(raw, "big") + + +def reference(name, offset, value, preset): + """(RAX, (CF << 1) | ZF, buffer) after the export runs on DATA between its guards.""" + direction, size, disp, _ = EXPORTS[name] + total = preset + preset + flags = int(total > MASK64) << 1 | int(total & MASK64 == 0) + buffer = bytearray(b"\xcc" * PAD + DATA + b"\xcc" * PAD) + at = PAD + offset + disp + if direction == "load": + loaded = swapped(buffer[at:at + size]) + rax = (value & ~0xffff | loaded) if size == 2 else loaded + elif direction == "store": + buffer[at:at + size] = (value & ((1 << 8 * size) - 1)).to_bytes(size, "big") + rax = value + else: + rax = swapped(buffer[at:at + size]) + buffer[at + 8:at + 8 + size] = buffer[at:at + size] + return rax, flags, bytes(buffer) + + +def cases(): + for name in EXPORTS: + for offset in OFFSETS: + for value in VALUES: + for preset in PRESETS: + yield name, (offset, value, preset) + + +def load_lib(path): + lib = ctypes.CDLL(str(Path(path).resolve())) + for name in EXPORTS: + fn = getattr(lib, name) + fn.argtypes, fn.restype = [ctypes.c_void_p, U64, U64, ctypes.POINTER(U64)], U64 + return lib + + +def mismatches(lib, expected): + found = [] + state = U64() + for name, (offset, value, preset), want in expected: + buffer = (ctypes.c_uint8 * (2 * PAD + len(DATA))).from_buffer_copy(b"\xcc" * PAD + DATA + b"\xcc" * PAD) + state.value = 0xdeadbeef + rax = getattr(lib, name)(ctypes.addressof(buffer) + PAD + offset, value, preset, ctypes.byref(state)) + got = (rax, state.value, bytes(buffer)) + if got != want: + found.append((name, (offset, value, preset), want, got)) + return found + + +def describe(case): + name, args, want, got = case + return (f"{name}(offset={args[0]}, value={args[1]:#x}, preset={args[2]:#x}) = (rax={got[0]:#x}, flags={got[1]}), " + f"expected (rax={want[0]:#x}, flags={want[1]})" + ("; memory differs" if got[2] != want[2] else "")) + + +def check(native_path, lifted_path, *control_paths): + lifted = ctypes.CDLL(str(Path(lifted_path).resolve())) + lifted.host_has_movbe.argtypes, lifted.host_has_movbe.restype = [], ctypes.c_int + if not lifted.host_has_movbe(): + print("Host CPU lacks MOVBE (CPUID leaf 1 ECX bit 22); skipping native differential check.") + sys.exit(77) + 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: + raise AssertionError(f"{label}: {len(bad)} mismatches; first {describe(bad[0])}") + print(f"{len(expected)} cases over {len(EXPORTS)} exports (RAX, ZF/CF, data and guard bytes) 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 327d5ab8f..2eb9cd678 100644 --- a/tools/ffx_version_query.py +++ b/tools/ffx_version_query.py @@ -132,6 +132,13 @@ def write(expr): stmt = write(f"(carry || zero) ? {operand(1)} : {operand(0)}") elif op == M.LEA: stmt = write(address()) + elif op == M.MOVBE: + # One operand is memory and the other a register of the same width; the bytes are reversed in + # either direction, no flag changes, and a 16-bit register destination keeps its upper bits. + width = UINT[MemorySizeExt.size(i.memory_size)] + stmt = (f"{{ const {width} a = {operand(1)}; {width} v = 0; " + f"for (unsigned k = 0; k < sizeof v; ++k) v = static_cast<{width}>((v << 8) | ((a >> (8 * k)) & 0xffu)); " + f"{write('v')} }}") elif op == M.CMP: # Sign-extended immediates arrive as 64-bit values; compare at the destination width. width = UINT[MemorySizeExt.size(i.memory_size) if i.op0_kind == K.MEMORY else RegisterExt.size(i.op0_register)] diff --git a/tools/form_coverage.py b/tools/form_coverage.py index 8ca62ddf0..ef596da90 100644 --- a/tools/form_coverage.py +++ b/tools/form_coverage.py @@ -55,6 +55,7 @@ "exe_entry": "cpu_aot_exe_entry", "address_size": "cpu_aot_address_size", "call_pair": "cpu_aot_call_pair", + "movbe": "cpu_aot_movbe", "bmi1": "cpu_aot_bmi1", "register_probe": None, # measurement harness "two_imports": None, # mapped and run unchanged by pe_map