From 5b2fd02d9e4342bc9c3753adc28980ee8302ebf2 Mon Sep 17 00:00:00 2001 From: denn0x <55638248+denn0x@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:29:21 +0000 Subject: [PATCH] cpu: lower x64 string instructions in the shared lifter Lower MOVS, STOS, LODS, SCAS and CMPS in all four widths, bare and under REP, REPE and REPNE, together with CLD and STD. Dispatch is by iced Code because the SSE2 scalar MOVSD and CMPSD share the string mnemonics. Each iteration moves or compares one element and steps RSI and RDI by the width, downward when DF is set, so overlapping copies replicate as on the hardware. RCX is tested before each element and ZF after it, and a zero count leaves pointers, memory and flags unchanged. The 67h forms, REPNE on MOVS, STOS and LODS, and FS or GS sources are rejected. cpu_aot_string_ops builds 62 exports from MASM source and compares 39984 cases of memory, RAX, RSI, RDI, RCX, ZF and CF across the native DLL, the translation and a Python reference. Three mutated translations (memmove for REP MOVS, swapped CMPS operands, STD ignored) must mismatch. AI-assisted (Claude Code). --- CMakeLists.txt | 15 ++ docs/experiments.md | 2 + tests/cpu/string_ops.asm | 500 +++++++++++++++++++++++++++++++++++++ tests/cpu/string_ops.def | 63 +++++ tests/cpu/string_ops.py | 247 ++++++++++++++++++ tools/ffx_version_query.py | 50 +++- tools/form_coverage.py | 1 + 7 files changed, 877 insertions(+), 1 deletion(-) create mode 100644 tests/cpu/string_ops.asm create mode 100644 tests/cpu/string_ops.def create mode 100644 tests/cpu/string_ops.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 019a9f79b..84b393938 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -673,6 +673,21 @@ if(EXISTS "${INTAKE_PYTHON}") add_library(cpu_rotates_shifts_lifted SHARED "${rotates_shifts_fixture}") add_test(NAME cpu_aot_rotates_shifts COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/rotates_shifts.py" check "$" "$") + cpu_asm_fixture(cpu_string_ops string_ops) + # The lifted DLL and three mutated controls that the check requires to mismatch. + foreach(variant IN ITEMS lifted memmove swapped forward) + set(string_ops_fixture "${CMAKE_CURRENT_BINARY_DIR}/cpu_string_ops_${variant}.cpp") + add_custom_command(OUTPUT "${string_ops_fixture}" + COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/string_ops.py" + emit "$" "${string_ops_fixture}" ${variant} + DEPENDS cpu_string_ops tests/cpu/string_ops.py tools/ffx_version_query.py + tools/cpu_ranges.py tools/cpu_leaf_aot.py VERBATIM) + add_library(cpu_string_ops_${variant} SHARED "${string_ops_fixture}") + endforeach() + add_test(NAME cpu_aot_string_ops COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/string_ops.py" + check "$" "$" + "$" "$" + "$") cpu_translation(cpu_callback cpu_chained_aot call_context CALLBACK_OFFSET 8) cpu_asm_fixture(cpu_xlatb xlatb) # The lifted DLL and three mutated controls that the check requires to mismatch. diff --git a/docs/experiments.md b/docs/experiments.md index f95aa8d9a..eb57149b8 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -423,6 +423,8 @@ An immediate SHL, SHR or SAR whose masked count is zero leaves the flags unchang 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`. The shared lowering also handles 32-bit and 64-bit rotates and double-precision shifts (`rol`, `ror`, `shld`, `shrd`) with both immediate and `cl` counts, preserving flags on zero masked counts while zero-extending 32-bit destinations. `cpu_aot_rotates_shifts` builds all 12 exports from MASM source (`tests/cpu/rotates_shifts.asm`), translates them, and compares values and ZF/CF flags against the native DLL and a reference model. Run `cmake --build --preset dev --target cpu_rotates_shifts_lifted` and `ctest --preset dev --no-tests=error -R '^cpu_aot_rotates_shifts$' -V`. +The string instructions `movs`, `stos`, `lods`, `scas` and `cmps` lower in byte, word, dword and qword widths, bare or with REP (`movs`, `stos`, `lods`), REPE or REPNE (`scas`, `cmps`), together with `cld` and `std`. The lowering selects them by iced `Code`, because the SSE2 scalar `movsd` and `cmpsd` share their mnemonics. Each iteration moves or compares one element and then steps RSI and RDI by the width, downward when DF is set. Overlapping copies therefore replicate as on the hardware, which a whole-range `memmove` would not. A repeated form tests RCX before each element and ZF after it. A zero count leaves the pointers, memory and flags unchanged. `lodsb` and `lodsw` merge into RAX and `lodsd` zero-extends. `cmps` compares the source element with the destination element and `scas` compares the accumulator with the destination; only ZF and CF are modelled, like the rest of the lowering. DF starts clear in each translated function. The [x64 software conventions](https://learn.microsoft.com/en-us/cpp/build/x64-software-conventions#x64-register-usage) expect DF clear on function exit and on entry to runtime and system calls, so a conforming caller never enters with it set. The 67h forms that walk ESI, EDI and ECX, REPNE on `movs`, `stos` and `lods`, and FS or GS sources are rejected. `cpu_aot_string_ops` builds 62 exports from MASM source (`tests/cpu/string_ops.asm`). In 13 of them the instruction runs with DF set, and one sets DF and clears it again before the instruction. Each export takes its pointers, count, RAX and a flag preset from the caller and reports memory, RAX, RSI, RDI, RCX, ZF and CF. The check runs 39984 cases against the native DLL, the translation and a Python reference. The cases cover overlaps of one byte and of less than an element, zero counts under each flag preset, and REPE and REPNE exits on the first element, on a later one and at count exhaustion, with both CF results. Three mutated translations must each mismatch: a `memmove` for REP `movs`, swapped `cmps` operands, and STD ignored. A 1 KiB guard on each side of the buffer is compared too. Run `ctest --preset dev --no-tests=error -R '^cpu_aot_string_ops$' -V`. + ## Recompiling a direct x64 call The [caller and callee](../tests/cpu/direct.asm) each accept two unsigned 64-bit integers and an output pointer. The [translator](../tools/cpu_call_aot.py) starts at the caller export, follows the signed displacement in its E8 call and reads the target's runtime-function interval. It generates two C++ functions from the linked machine code. MSVC emits a separate x64 DLL with a non-inlined call. The Windows test checks the relative call against the two export addresses in both the input and output DLLs. diff --git a/tests/cpu/string_ops.asm b/tests/cpu/string_ops.asm new file mode 100644 index 000000000..fde8c0774 --- /dev/null +++ b/tests/cpu/string_ops.asm @@ -0,0 +1,500 @@ +; Source-owned differential fixture for the x64 string instructions MOVS, STOS, LODS, SCAS and CMPS +; in byte, word, dword and qword widths, with REP, REPE and REPNE and with DF set by STD. +; Each export takes (destination, source, count, state). It enters with RDI, RSI and RCX set from the +; first three arguments, RAX from state[1] and the flags from comparing state[0] with 1 (0: CF, 1: ZF, +; 2: neither). It writes (CF << 1) | ZF, RAX, RSI, RDI and RCX to state[0..4]. RSI and RDI are +; callee-saved and kept in R10 and R11. +.code + +STRING_ENTER MACRO + mov r10, rsi + mov r11, rdi + mov rdi, rcx + mov rsi, rdx + mov rcx, r8 + mov rax, qword ptr [r9+8] + cmp qword ptr [r9], 1 +ENDM + +STRING_LEAVE MACRO + LOCAL no_carry, no_zero + mov edx, 0 + jae short no_carry + mov edx, 2 +no_carry: + jne short no_zero + or edx, 1 +no_zero: + mov qword ptr [r9], rdx + mov qword ptr [r9+8], rax + mov qword ptr [r9+16], rsi + mov qword ptr [r9+24], rdi + mov qword ptr [r9+32], rcx + mov rsi, r10 + mov rdi, r11 + ret +ENDM + +once_movsb PROC FRAME + .endprolog + STRING_ENTER + movsb + STRING_LEAVE +once_movsb ENDP + +once_movsw PROC FRAME + .endprolog + STRING_ENTER + movsw + STRING_LEAVE +once_movsw ENDP + +once_movsd PROC FRAME + .endprolog + STRING_ENTER + movsd + STRING_LEAVE +once_movsd ENDP + +once_movsq PROC FRAME + .endprolog + STRING_ENTER + movsq + STRING_LEAVE +once_movsq ENDP + +once_stosb PROC FRAME + .endprolog + STRING_ENTER + stosb + STRING_LEAVE +once_stosb ENDP + +once_stosw PROC FRAME + .endprolog + STRING_ENTER + stosw + STRING_LEAVE +once_stosw ENDP + +once_stosd PROC FRAME + .endprolog + STRING_ENTER + stosd + STRING_LEAVE +once_stosd ENDP + +once_stosq PROC FRAME + .endprolog + STRING_ENTER + stosq + STRING_LEAVE +once_stosq ENDP + +once_lodsb PROC FRAME + .endprolog + STRING_ENTER + lodsb + STRING_LEAVE +once_lodsb ENDP + +once_lodsw PROC FRAME + .endprolog + STRING_ENTER + lodsw + STRING_LEAVE +once_lodsw ENDP + +once_lodsd PROC FRAME + .endprolog + STRING_ENTER + lodsd + STRING_LEAVE +once_lodsd ENDP + +once_lodsq PROC FRAME + .endprolog + STRING_ENTER + lodsq + STRING_LEAVE +once_lodsq ENDP + +once_scasb PROC FRAME + .endprolog + STRING_ENTER + scasb + STRING_LEAVE +once_scasb ENDP + +once_scasw PROC FRAME + .endprolog + STRING_ENTER + scasw + STRING_LEAVE +once_scasw ENDP + +once_scasd PROC FRAME + .endprolog + STRING_ENTER + scasd + STRING_LEAVE +once_scasd ENDP + +once_scasq PROC FRAME + .endprolog + STRING_ENTER + scasq + STRING_LEAVE +once_scasq ENDP + +once_cmpsb PROC FRAME + .endprolog + STRING_ENTER + cmpsb + STRING_LEAVE +once_cmpsb ENDP + +once_cmpsw PROC FRAME + .endprolog + STRING_ENTER + cmpsw + STRING_LEAVE +once_cmpsw ENDP + +once_cmpsd PROC FRAME + .endprolog + STRING_ENTER + cmpsd + STRING_LEAVE +once_cmpsd ENDP + +once_cmpsq PROC FRAME + .endprolog + STRING_ENTER + cmpsq + STRING_LEAVE +once_cmpsq ENDP + +rep_movsb PROC FRAME + .endprolog + STRING_ENTER + rep movsb + STRING_LEAVE +rep_movsb ENDP + +rep_movsw PROC FRAME + .endprolog + STRING_ENTER + rep movsw + STRING_LEAVE +rep_movsw ENDP + +rep_movsd PROC FRAME + .endprolog + STRING_ENTER + rep movsd + STRING_LEAVE +rep_movsd ENDP + +rep_movsq PROC FRAME + .endprolog + STRING_ENTER + rep movsq + STRING_LEAVE +rep_movsq ENDP + +rep_stosb PROC FRAME + .endprolog + STRING_ENTER + rep stosb + STRING_LEAVE +rep_stosb ENDP + +rep_stosw PROC FRAME + .endprolog + STRING_ENTER + rep stosw + STRING_LEAVE +rep_stosw ENDP + +rep_stosd PROC FRAME + .endprolog + STRING_ENTER + rep stosd + STRING_LEAVE +rep_stosd ENDP + +rep_stosq PROC FRAME + .endprolog + STRING_ENTER + rep stosq + STRING_LEAVE +rep_stosq ENDP + +rep_lodsb PROC FRAME + .endprolog + STRING_ENTER + rep lodsb + STRING_LEAVE +rep_lodsb ENDP + +rep_lodsw PROC FRAME + .endprolog + STRING_ENTER + rep lodsw + STRING_LEAVE +rep_lodsw ENDP + +rep_lodsd PROC FRAME + .endprolog + STRING_ENTER + rep lodsd + STRING_LEAVE +rep_lodsd ENDP + +rep_lodsq PROC FRAME + .endprolog + STRING_ENTER + rep lodsq + STRING_LEAVE +rep_lodsq ENDP + +repe_scasb PROC FRAME + .endprolog + STRING_ENTER + repe scasb + STRING_LEAVE +repe_scasb ENDP + +repe_scasw PROC FRAME + .endprolog + STRING_ENTER + repe scasw + STRING_LEAVE +repe_scasw ENDP + +repe_scasd PROC FRAME + .endprolog + STRING_ENTER + repe scasd + STRING_LEAVE +repe_scasd ENDP + +repe_scasq PROC FRAME + .endprolog + STRING_ENTER + repe scasq + STRING_LEAVE +repe_scasq ENDP + +repne_scasb PROC FRAME + .endprolog + STRING_ENTER + repne scasb + STRING_LEAVE +repne_scasb ENDP + +repne_scasw PROC FRAME + .endprolog + STRING_ENTER + repne scasw + STRING_LEAVE +repne_scasw ENDP + +repne_scasd PROC FRAME + .endprolog + STRING_ENTER + repne scasd + STRING_LEAVE +repne_scasd ENDP + +repne_scasq PROC FRAME + .endprolog + STRING_ENTER + repne scasq + STRING_LEAVE +repne_scasq ENDP + +repe_cmpsb PROC FRAME + .endprolog + STRING_ENTER + repe cmpsb + STRING_LEAVE +repe_cmpsb ENDP + +repe_cmpsw PROC FRAME + .endprolog + STRING_ENTER + repe cmpsw + STRING_LEAVE +repe_cmpsw ENDP + +repe_cmpsd PROC FRAME + .endprolog + STRING_ENTER + repe cmpsd + STRING_LEAVE +repe_cmpsd ENDP + +repe_cmpsq PROC FRAME + .endprolog + STRING_ENTER + repe cmpsq + STRING_LEAVE +repe_cmpsq ENDP + +repne_cmpsb PROC FRAME + .endprolog + STRING_ENTER + repne cmpsb + STRING_LEAVE +repne_cmpsb ENDP + +repne_cmpsw PROC FRAME + .endprolog + STRING_ENTER + repne cmpsw + STRING_LEAVE +repne_cmpsw ENDP + +repne_cmpsd PROC FRAME + .endprolog + STRING_ENTER + repne cmpsd + STRING_LEAVE +repne_cmpsd ENDP + +repne_cmpsq PROC FRAME + .endprolog + STRING_ENTER + repne cmpsq + STRING_LEAVE +repne_cmpsq ENDP + +std_movsw PROC FRAME + .endprolog + STRING_ENTER + std + movsw + cld + STRING_LEAVE +std_movsw ENDP + +std_rep_movsb PROC FRAME + .endprolog + STRING_ENTER + std + rep movsb + cld + STRING_LEAVE +std_rep_movsb ENDP + +std_rep_movsq PROC FRAME + .endprolog + STRING_ENTER + std + rep movsq + cld + STRING_LEAVE +std_rep_movsq ENDP + +std_stosb PROC FRAME + .endprolog + STRING_ENTER + std + stosb + cld + STRING_LEAVE +std_stosb ENDP + +std_rep_stosw PROC FRAME + .endprolog + STRING_ENTER + std + rep stosw + cld + STRING_LEAVE +std_rep_stosw ENDP + +std_rep_stosd PROC FRAME + .endprolog + STRING_ENTER + std + rep stosd + cld + STRING_LEAVE +std_rep_stosd ENDP + +std_lodsb PROC FRAME + .endprolog + STRING_ENTER + std + lodsb + cld + STRING_LEAVE +std_lodsb ENDP + +std_lodsq PROC FRAME + .endprolog + STRING_ENTER + std + lodsq + cld + STRING_LEAVE +std_lodsq ENDP + +std_cmpsb PROC FRAME + .endprolog + STRING_ENTER + std + cmpsb + cld + STRING_LEAVE +std_cmpsb ENDP + +std_repne_scasb PROC FRAME + .endprolog + STRING_ENTER + std + repne scasb + cld + STRING_LEAVE +std_repne_scasb ENDP + +std_repe_scasq PROC FRAME + .endprolog + STRING_ENTER + std + repe scasq + cld + STRING_LEAVE +std_repe_scasq ENDP + +std_repe_cmpsw PROC FRAME + .endprolog + STRING_ENTER + std + repe cmpsw + cld + STRING_LEAVE +std_repe_cmpsw ENDP + +std_repne_cmpsd PROC FRAME + .endprolog + STRING_ENTER + std + repne cmpsd + cld + STRING_LEAVE +std_repne_cmpsd ENDP + +std_cld_rep_movsb PROC FRAME + .endprolog + STRING_ENTER + std + cld + rep movsb + STRING_LEAVE +std_cld_rep_movsb ENDP + +END diff --git a/tests/cpu/string_ops.def b/tests/cpu/string_ops.def new file mode 100644 index 000000000..e247a5432 --- /dev/null +++ b/tests/cpu/string_ops.def @@ -0,0 +1,63 @@ +EXPORTS + once_movsb + once_movsw + once_movsd + once_movsq + once_stosb + once_stosw + once_stosd + once_stosq + once_lodsb + once_lodsw + once_lodsd + once_lodsq + once_scasb + once_scasw + once_scasd + once_scasq + once_cmpsb + once_cmpsw + once_cmpsd + once_cmpsq + rep_movsb + rep_movsw + rep_movsd + rep_movsq + rep_stosb + rep_stosw + rep_stosd + rep_stosq + rep_lodsb + rep_lodsw + rep_lodsd + rep_lodsq + repe_scasb + repe_scasw + repe_scasd + repe_scasq + repne_scasb + repne_scasw + repne_scasd + repne_scasq + repe_cmpsb + repe_cmpsw + repe_cmpsd + repe_cmpsq + repne_cmpsb + repne_cmpsw + repne_cmpsd + repne_cmpsq + std_movsw + std_rep_movsb + std_rep_movsq + std_stosb + std_rep_stosw + std_rep_stosd + std_lodsb + std_lodsq + std_cmpsb + std_repne_scasb + std_repe_scasq + std_repe_cmpsw + std_repne_cmpsd + std_cld_rep_movsb diff --git a/tests/cpu/string_ops.py b/tests/cpu/string_ops.py new file mode 100644 index 000000000..41587ccb8 --- /dev/null +++ b/tests/cpu/string_ops.py @@ -0,0 +1,247 @@ +"""Compare native and translated x64 string instructions (MOVS, STOS, LODS, SCAS, CMPS) with REP prefixes and DF.""" +import ctypes +from pathlib import Path +import re +import sys + +import pefile +from iced_x86 import Decoder + +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 +SUFFIX = {1: "b", 2: "w", 4: "d", 8: "q"} + +# (export, kind, width, repeat prefix, DF set around the instruction, STD then CLD before it) +EXPORTS = ( + *((f"once_{kind}{SUFFIX[w]}", kind, w, None, False, False) for kind in ("movs", "stos", "lods", "scas", "cmps") for w in SUFFIX), + *((f"rep_{kind}{SUFFIX[w]}", kind, w, "rep", False, False) for kind in ("movs", "stos", "lods") for w in SUFFIX), + *((f"{rep}_{kind}{SUFFIX[w]}", kind, w, rep, False, False) + for kind in ("scas", "cmps") for rep in ("repe", "repne") for w in SUFFIX), + ("std_movsw", "movs", 2, None, True, False), + ("std_rep_movsb", "movs", 1, "rep", True, False), + ("std_rep_movsq", "movs", 8, "rep", True, False), + ("std_stosb", "stos", 1, None, True, False), + ("std_rep_stosw", "stos", 2, "rep", True, False), + ("std_rep_stosd", "stos", 4, "rep", True, False), + ("std_lodsb", "lods", 1, None, True, False), + ("std_lodsq", "lods", 8, None, True, False), + ("std_cmpsb", "cmps", 1, None, True, False), + ("std_repne_scasb", "scas", 1, "repne", True, False), + ("std_repe_scasq", "scas", 8, "repe", True, False), + ("std_repe_cmpsw", "cmps", 2, "repe", True, False), + ("std_repne_cmpsd", "cmps", 4, "repne", True, False), + ("std_cld_rep_movsb", "movs", 1, "rep", False, True), +) + +# Source mutations of the generated C++. Each control DLL must disagree with the reference somewhere. +CONTROLS = { + # A whole-range memmove gives the same bytes only when the ranges do not overlap forward. + "memmove": (re.compile(r"while \(rcx != 0\) \{ store<(\w+)>\(rdi, load<\1>\(rsi\)\); rsi \+= step; rdi \+= step; --rcx; \}"), + r"if (rcx != 0) { std::memmove(reinterpret_cast(rdi), reinterpret_cast(rsi), " + r"rcx * sizeof(\1)); rsi += rcx * step; rdi += rcx * step; rcx = 0; }"), + # CMPS subtracts the destination element from the source element. + "swapped": (re.compile(r"a = load<(\w+)>\(rsi\), b = load<\1>\(rdi\)"), r"a = load<\1>(rdi), b = load<\1>(rsi)"), + # STD walks the pointers downward. + "forward": (re.compile(r"direction = true;"), "direction = false;"), +} + +SIZE = 1024 +BOUNDS = (16, SIZE - 16) # guard bytes on both ends must stay untouched +# (destination, source) offsets: 96 apart they match until the breaks at 520 and 616 (or start on them), +# 1 and 3 apart they overlap within an element, and 704/720 compare inside the 0x5a run. +PAIRS = ((608, 512), (512, 608), (616, 520), (520, 616), (401, 400), (400, 401), (403, 400), (400, 403), + (720, 704), (704, 720), (760, 800), (300, 900)) +COUNTS = (0, 1, 2, 5, 17, 40) +FLAG_SELECTORS = (0, 1, 2) # cmp state[0], 1: CF only, ZF only, neither + + +def pattern(): + """A period-16 pattern of distinct bytes, so offsets 16 apart compare equal, with planted breaks + at 520 and 616 (rel. 8 from 512 and 608), 480 below them, and a 0x5a run over 700..763 broken at 731.""" + base = bytes((n * 37 + 11) & 0xff for n in range(16)) + buf = bytearray(base[n % 16] for n in range(SIZE)) + buf[520], buf[616], buf[480] = 0x00, 0xff, 0x11 + buf[700:764] = b"\x5a" * 64 + buf[731] = 0x3c + return bytes(buf) + + +PATTERN = pattern() +# A wrong lowering (the mutated controls) can walk past the 1 KiB buffer, so it sits between 1 KiB pads of +# 0xcc. The comparison covers the pads too, so a stray write is a mismatch instead of heap corruption. +PAD = 1024 +PADDED = bytes([0xcc]) * PAD + PATTERN + bytes([0xcc]) * PAD +RAX_VALUES = (0x5a5a5a5a5a5a5a5a, 0x0123456789abcdef, int.from_bytes(PATTERN[1000:1008], "little")) + + +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)) + code = lower(region(pe, *bounds), ["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 reference(kind, width, repeat, down, buf, rdi, rsi, rcx, rax, flags): + """Architectural result: one element at a time, the count tested before and ZF after each element.""" + step = -width if down else width + mask = (1 << (8 * width)) - 1 + zf, cf = flags + touched = [] + + def element(address): + touched.append(address) + return int.from_bytes(buf[address:address + width], "little") + + def put(address, value): + touched.append(address) + buf[address:address + width] = (value & mask).to_bytes(width, "little") + + def once(): + nonlocal rdi, rsi, rax, zf, cf + if kind == "movs": + put(rdi, element(rsi)) + rsi += step + rdi += step + elif kind == "stos": + put(rdi, rax) + rdi += step + elif kind == "lods": + value = element(rsi) + rax = value if width >= 4 else (rax & ~mask) | value + rsi += step + else: + a = rax & mask if kind == "scas" else element(rsi) + b = element(rdi) + zf, cf = int(a == b), int(a < b) + if kind == "cmps": + rsi += step + rdi += step + + if repeat is None: + once() + else: + while rcx: + once() + rcx -= 1 + if (repeat == "repe" and not zf) or (repeat == "repne" and zf): + break + inside = all(BOUNDS[0] <= t and t + width <= BOUNDS[1] for t in touched) + return inside, (cf << 1 | zf, rax, rsi, rdi, rcx) + + +def load_lib(path): + lib = ctypes.CDLL(str(Path(path).resolve())) + for name, *_ in EXPORTS: + fn = getattr(lib, name) + fn.argtypes, fn.restype = [U64, U64, U64, ctypes.POINTER(U64 * 5)], U64 + return lib + + +def run(lib, name, buf, dst, src, count, selector, rax): + """Call one export on a fresh copy of the padded pattern; returns (state, memory) with pointers as offsets.""" + ctypes.memmove(buf, PADDED, len(PADDED)) + base = ctypes.addressof(buf) + PAD + state = (U64 * 5)(selector, rax, 0, 0, 0) + returned = getattr(lib, name)(base + dst, base + src, count, ctypes.byref(state)) + if returned != state[1]: + raise AssertionError(f"{name} returned {returned:#x} but stored RAX {state[1]:#x}") + flags, rax, rsi, rdi, rcx = state + return (flags, rax, (rsi - base) & 0xffffffffffffffff, (rdi - base) & 0xffffffffffffffff, rcx), bytes(buf) + + +def cases(): + for name, kind, width, repeat, down, _ in EXPORTS: + for dst, src in PAIRS: + for count in COUNTS: + for selector in FLAG_SELECTORS: + for rax in RAX_VALUES: + flags = ((0, 1), (1, 0), (0, 0))[selector] + buf = bytearray(PATTERN) + inside, state = reference(kind, width, repeat, down, buf, dst, src, count, rax, flags) + if inside: + yield name, (dst, src, count, selector, rax), state, PADDED[:PAD] + buf + PADDED[-PAD:] + + +def mismatches(lib, expected): + buf = (ctypes.c_uint8 * len(PADDED))() + found = [] + for name, args, state, memory in expected: + got = run(lib, name, buf, *args) + if got != (state, memory): + found.append((name, args, state, got[0])) + return found + + +def check(native_path, lifted_path, *control_paths): + expected = list(cases()) + per_export = {name: 0 for name, *_ in EXPORTS} + for name, *_ in expected: + per_export[name] += 1 + if min(per_export.values()) == 0: + raise AssertionError(f"exports without an in-bounds case: {[n for n, c in per_export.items() if not c]}") + 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}{args} = {got}, expected {want}") + print(f"{len(expected)} cases over {len(EXPORTS)} exports (memory, RAX, RSI, RDI, RCX, 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") + + +def check_rejections(): + for code, diagnostic in ( + ("67 f3 a4 c3", "unsupported string address size at 0x1000"), # rep movs [edi], [esi] + ("67 ae c3", "unsupported string address size at 0x1000"), # scas al, [edi] + ("f2 a4 c3", "unsupported REPNE string prefix at 0x1000"), # repne movsb + ("f2 48 ab c3", "unsupported REPNE string prefix at 0x1000"), # repne stosq + ("f2 ac c3", "unsupported REPNE string prefix at 0x1000"), # repne lodsb + ("64 a4 c3", "unsupported instruction prefix at 0x1000"), # movs from fs:[rsi] + ): + try: + lower(list(Decoder(64, bytes.fromhex(code), ip=0x1000)), [], {}, {}, {}) + except ValueError as exc: + if not str(exc).startswith(diagnostic): + raise AssertionError(f"{code}: unexpected diagnostic {exc}") from exc + else: + raise AssertionError(f"accepted {code}") + # The SSE2 scalar MOVSD and CMPSD share mnemonics with the string forms and stay unsupported here. + for code in ("f2 0f 10 c1 c3", "f2 0f c2 c1 00 c3"): + try: + lower(list(Decoder(64, bytes.fromhex(code), ip=0x1000)), [], {}, {}, {}) + except ValueError as exc: + if not str(exc).startswith("unsupported query operation at 0x1000"): + raise AssertionError(f"{code}: unexpected diagnostic {exc}") from exc + else: + raise AssertionError(f"accepted {code}") + print("rejected 67h string addressing, REPNE on MOVS/STOS/LODS, an FS source and the SSE2 MOVSD/CMPSD forms") + + +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) + check_rejections() + else: + raise ValueError(mode) diff --git a/tools/ffx_version_query.py b/tools/ffx_version_query.py index fe5b3539e..225391ab4 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 @@ -16,6 +16,14 @@ REGS = {getattr(R, n.upper()): n for n in "rax rbx rcx rdx rsi rdi rbp rsp r8 r9 r10 r11 r12 r13 r14 r15".split()} HIGH_BYTE = {R.AH, R.BH, R.CH, R.DH} UINT = {1: "uint8_t", 2: "uint16_t", 4: "uint32_t", 8: "uint64_t"} +# String instructions by Code: the SSE2 scalar MOVSD and CMPSD share their mnemonics. +STRING_OPS = { + C.MOVSB_M8_M8: ("movs", 1), C.MOVSW_M16_M16: ("movs", 2), C.MOVSD_M32_M32: ("movs", 4), C.MOVSQ_M64_M64: ("movs", 8), + C.STOSB_M8_AL: ("stos", 1), C.STOSW_M16_AX: ("stos", 2), C.STOSD_M32_EAX: ("stos", 4), C.STOSQ_M64_RAX: ("stos", 8), + C.LODSB_AL_M8: ("lods", 1), C.LODSW_AX_M16: ("lods", 2), C.LODSD_EAX_M32: ("lods", 4), C.LODSQ_RAX_M64: ("lods", 8), + C.SCASB_AL_M8: ("scas", 1), C.SCASW_AX_M16: ("scas", 2), C.SCASD_EAX_M32: ("scas", 4), C.SCASQ_RAX_M64: ("scas", 8), + C.CMPSB_M8_M8: ("cmps", 1), C.CMPSW_M16_M16: ("cmps", 2), C.CMPSD_M32_M32: ("cmps", 4), C.CMPSQ_M64_M64: ("cmps", 8), +} INTEGER_HEADER = """#include #include @@ -46,6 +54,37 @@ def region(pe, start, end): return ins +def string_op(i): + """One element per iteration in program order, so overlapping copies replicate as on the hardware.""" + kind, size = STRING_OPS[i.code] + if any(i.op_kind(n) not in (K.REGISTER, K.MEMORY_ESRDI, K.MEMORY_SEG_RSI) for n in range(i.op_count)): + # A 67h prefix walks ESI, EDI and ECX instead of the full registers. + raise ValueError(f"unsupported string address size at {i.ip:#x}: {i}") + if kind in ("scas", "cmps"): + repeat = "repe" if i.has_repe_prefix else "repne" if i.has_repne_prefix else None + elif i.has_repne_prefix: + raise ValueError(f"unsupported REPNE string prefix at {i.ip:#x}: {i}") + else: + repeat = "rep" if i.has_rep_prefix else None + t = UINT[size] + if kind == "movs": + step = f"store<{t}>(rdi, load<{t}>(rsi)); rsi += step; rdi += step;" + elif kind == "stos": + step = f"store<{t}>(rdi, static_cast<{t}>(rax)); rdi += step;" + elif kind == "lods": + # AL and AX merge into RAX; a 32-bit load zero-extends. + value = f"(rax & ~{(1 << (8*size)) - 1}ull) | load<{t}>(rsi)" if size < 4 else f"load<{t}>(rsi)" + step = f"rax = {value}; rsi += step;" + else: + lhs = f"static_cast<{t}>(rax)" if kind == "scas" else f"load<{t}>(rsi)" + advance = "rdi += step;" if kind == "scas" else "rsi += step; rdi += step;" + step = f"{{ const {t} a = {lhs}, b = load<{t}>(rdi); zero = a == b; carry = a < b; }} {advance}" + stop = {"repe": " if (!zero) break;", "repne": " if (zero) break;"}.get(repeat, "") + # A zero count performs no iteration and leaves the pointers and flags unchanged. + body = f"while (rcx != 0) {{ {step} --rcx;{stop} }}" if repeat else step + return f"{{ const word step = direction ? 0ull - {size}ull : {size}ull; {body} }}" + + def lower(body, initial, globals_, calls, exits, *, host_ops=None, x87=False): """Emit only query integer operations. All external edges and calls need named bindings.""" lines = ["word frame[16]{};", "word " + ", ".join(r + "=0" for r in REGS.values()) + ";", @@ -62,6 +101,9 @@ def lower(body, initial, globals_, calls, exits, *, host_ops=None, x87=False): # only byte storage on the desktop host. wide = {R.YMM0: "wide0", R.YMM1: "wide1", R.YMM2: "wide2"} has_wide = any(i.mnemonic == M.VMOVUPS for i in body) + if any(i.code in STRING_OPS or i.mnemonic in (M.CLD, M.STD) for i in body): + # The x64 software conventions expect DF clear on function exit and before calls, so it starts clear. + lines.append("bool direction=false;") if has_wide: if has_xmm_math: raise ValueError("mixed vector arithmetic and wide descriptor copies are unsupported") @@ -116,6 +158,12 @@ def write(expr): # FS/GS select a thread block base and LOCK makes the access atomic; # the flat loads and stores below would silently drop both. raise ValueError(f"unsupported instruction prefix at {i.ip:#x}: {i}") + elif i.code in STRING_OPS: + stmt = string_op(i) + elif op == M.CLD: + stmt = "direction = false;" + elif op == M.STD: + stmt = "direction = true;" elif op in (M.JE, M.JNE, M.JAE, M.JA, M.JB, M.JBE, M.JMP): target = i.near_branch_target if target not in allowed: diff --git a/tools/form_coverage.py b/tools/form_coverage.py index 01969a7bd..658133430 100644 --- a/tools/form_coverage.py +++ b/tools/form_coverage.py @@ -62,6 +62,7 @@ "movbe": "cpu_aot_movbe", "bmi1": "cpu_aot_bmi1", "rotates_shifts": "cpu_aot_rotates_shifts", + "string_ops": "cpu_aot_string_ops", "register_probe": None, # measurement harness "two_imports": None, # mapped and run unchanged by pe_map "exe_start": None, # mapped and run unchanged by pe_map