Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -649,6 +649,20 @@ if(EXISTS "${INTAKE_PYTHON}")
check "$<TARGET_FILE:cpu_bmi1>" "$<TARGET_FILE:cpu_bmi1_lifted>")
set_tests_properties(cpu_aot_bmi1 PROPERTIES SKIP_RETURN_CODE 77)
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.
foreach(variant IN ITEMS lifted signed noaddr32 clear)
set(xlatb_fixture "${CMAKE_CURRENT_BINARY_DIR}/cpu_xlatb_${variant}.cpp")
add_custom_command(OUTPUT "${xlatb_fixture}"
COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/xlatb.py"
emit "$<TARGET_FILE:cpu_xlatb>" "${xlatb_fixture}" ${variant}
DEPENDS cpu_xlatb tests/cpu/xlatb.py tools/ffx_version_query.py
tools/cpu_ranges.py tools/cpu_leaf_aot.py VERBATIM)
add_library(cpu_xlatb_${variant} SHARED "${xlatb_fixture}")
endforeach()
add_test(NAME cpu_aot_xlatb COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/cpu/xlatb.py"
check "$<TARGET_FILE:cpu_xlatb>" "$<TARGET_FILE:cpu_xlatb_lifted>"
"$<TARGET_FILE:cpu_xlatb_signed>" "$<TARGET_FILE:cpu_xlatb_noaddr32>" "$<TARGET_FILE:cpu_xlatb_clear>")
cpu_asm_fixture(cpu_destroy destroy)
target_link_libraries(cpu_destroy PRIVATE ucrt.lib)
cpu_translation(cpu_destroy cpu_chained_aot release_context FFX_DESTROY)
Expand Down
2 changes: 2 additions & 0 deletions docs/experiments.md
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,8 @@ The shared integer lowering in this tool emits flat loads and stores, so it reje

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`.

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`.

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`.
Expand Down
67 changes: 67 additions & 0 deletions tests/cpu/xlatb.asm
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
; Source-owned differential fixture for XLATB (AL = [RBX + AL]), its REX.W spelling and its 67h form
; (AL = [EBX + AL], wrapped at 32 bits). Each export takes (table, RAX, flag preset, state) in RCX, RDX,
; R8 and R9. RBX is saved in R11 and restored before the return. ADD R8, R8 sets ZF and CF from the
; preset; XLATB leaves them alone, and (CF << 1) | ZF goes to state[0].
.code

XLAT_LEAVE MACRO
LOCAL no_carry, no_zero
mov rbx, r11
mov r10d, 0
jae short no_carry
mov r10d, 2
no_carry:
jne short no_zero
or r10d, 1
no_zero:
mov qword ptr [r9], r10
ret
ENDM

xlat_basic PROC FRAME
.endprolog
mov r11, rbx
mov rbx, rcx
mov rax, rdx
add r8, r8
xlatb
XLAT_LEAVE
xlat_basic ENDP

; 48 D7: REX.W does not change the operation.
xlat_rexw PROC FRAME
.endprolog
mov r11, rbx
mov rbx, rcx
mov rax, rdx
add r8, r8
db 48h
xlatb
XLAT_LEAVE
xlat_rexw ENDP

; 67 D7: the table address is EBX + AL modulo 2^32, so the upper half of RBX is ignored.
xlat_addr32 PROC FRAME
.endprolog
mov r11, rbx
mov rbx, rcx
mov rax, rdx
add r8, r8
db 67h
xlatb
XLAT_LEAVE
xlat_addr32 ENDP

; Two lookups in a row: AL = table[table[AL]].
xlat_twice PROC FRAME
.endprolog
mov r11, rbx
mov rbx, rcx
mov rax, rdx
add r8, r8
xlatb
xlatb
XLAT_LEAVE
xlat_twice ENDP

END
5 changes: 5 additions & 0 deletions tests/cpu/xlatb.def
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
EXPORTS
xlat_basic
xlat_rexw
xlat_addr32
xlat_twice
148 changes: 148 additions & 0 deletions tests/cpu/xlatb.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
"""Compare native and translated XLATB, its REX.W spelling and its 67h (EBX-based) form."""
import ctypes
from pathlib import Path
import re
import sys

import pefile
from iced_x86 import Code, Register

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
MASK32 = (1 << 32) - 1
MASK64 = (1 << 64) - 1

# name: (number of XLATB instructions, table base register iced must decode).
EXPORTS = {
"xlat_basic": (1, Register.RBX), "xlat_rexw": (1, Register.RBX),
"xlat_addr32": (1, Register.EBX), "xlat_twice": (2, Register.RBX),
}

# Source mutations of the generated C++. Each control DLL must disagree with the reference somewhere.
CONTROLS = {
# AL is sign-extended instead of zero-extended, so indices 128 to 255 read below the table.
"signed": (re.compile(r"\+ static_cast<uint8_t>\(rax\)"), "+ static_cast<int8_t>(rax)"),
# The 67h sum keeps the upper half of RBX. Those reads fault, and a fault counts as a mismatch.
"noaddr32": (re.compile(r"static_cast<uint32_t>\((rbx \+ static_cast<uint8_t>\(rax\))\)"), r"(\1)"),
# The loaded byte replaces all of RAX.
"clear": (re.compile(r"rax = \(rax & ~0xffull\) \| load<uint8_t>"), "rax = load<uint8_t>"),
}

PAGE = 0x1000
TABLE_AT = 0x400 # the table sits mid-page; the rest of the page holds 0xcc
TABLE = bytes((167 * k + 13) & 0xff for k in range(256)) # a permutation: 167 is odd
RAX_UPPER = (0, 0xdeadbeefcafe00, 0xffffffffffffff00)
RBX_UPPER = (0, 0xdeadbeef, 0xffffffff, 0x80000000)
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 = [INTEGER_HEADER]
with pefile.PE(str(image), fast_load=True) as pe:
for name, (count, base) in EXPORTS.items():
(bounds,) = function_ranges(pe, export_rva(pe, name))
body = region(pe, *bounds)
xlat = [i for i in body if i.code == Code.XLAT_M8]
if len(xlat) != count or any(i.memory_base != base for i in xlat):
raise AssertionError(f"{name} does not contain {count} XLATB with base {base}")
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 low_page():
"""Commit a page below 4 GiB so a 32-bit table address can reach it."""
virtual_alloc = ctypes.windll.kernel32.VirtualAlloc
virtual_alloc.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_uint32, ctypes.c_uint32]
virtual_alloc.restype = ctypes.c_void_p
for hint in range(0x10000000, 0xf0000000, 0x01000000):
address = virtual_alloc(hint, PAGE, 0x3000, 0x04) # MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE
if address and address + PAGE <= 1 << 32:
return address
raise RuntimeError("no committable page below 4 GiB")


def reference(name, rax, preset):
total = preset + preset
flags = int(total > MASK64) << 1 | int(total & MASK64 == 0)
al = rax & 0xff
for _ in range(EXPORTS[name][0]):
al = TABLE[al]
return (rax & ~0xff) | al, flags


def cases():
for name in EXPORTS:
for upper in (RBX_UPPER if name == "xlat_addr32" else (0,)):
for noise in RAX_UPPER:
for al in range(256):
for preset in PRESETS:
yield name, (upper, noise | al, preset)


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)], U64
return lib


def mismatches(lib, expected, page):
table = page + TABLE_AT
found = []
state = U64()
for name, (upper, rax, preset), want in expected:
state.value = 0xdeadbeef
try:
got = (getattr(lib, name)(upper << 32 | table, rax, preset, ctypes.byref(state)), state.value)
except OSError as exc: # ctypes turns an access violation into OSError
got = (f"fault: {exc}", None)
if got != want:
found.append((name, (upper, rax, preset), want, got))
return found


def check(native_path, lifted_path, *control_paths):
page = low_page()
ctypes.memmove(page, b"\xcc" * PAGE, PAGE)
ctypes.memmove(page + TABLE_AT, TABLE, len(TABLE))
expected = [(name, args, reference(name, args[1], args[2])) for name, args in cases()]
for label, path in (("native", native_path), ("lifted", lifted_path)):
bad = mismatches(load_lib(path), expected, page)
if bad:
name, (upper, rax, preset), want, got = bad[0]
raise AssertionError(f"{label}: {len(bad)} mismatches; first {name}(rbx upper {upper:#x}, rax {rax:#x}, "
f"preset {preset:#x}) = {got}, expected {tuple(hex(w) for w in want)}")
if ctypes.string_at(page + TABLE_AT, len(TABLE)) != TABLE:
raise AssertionError("the table changed")
print(f"{len(expected)} cases over {len(EXPORTS)} exports (RAX and ZF/CF) matched the reference in native and "
f"translated DLLs; table at {page + TABLE_AT:#x}")
for path in control_paths:
control = Path(path).stem.rsplit("_", 1)[-1]
bad = mismatches(load_lib(path), expected, page)
faults = sum(1 for *_, got in bad if isinstance(got[0], str))
print(f"control {control}: {len(bad)}/{len(expected)} mismatches ({faults} faults)")
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)
7 changes: 7 additions & 0 deletions tools/ffx_version_query.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,6 +236,13 @@ def write(expr):
stmt = write("zero")
elif op == M.CALL:
stmt = calls[i.ip]
elif op == M.XLATB:
# AL = [RBX + AL]: iced names AL as the index, and address() would add all of RAX. The sum
# wraps at 32 bits under 67h (base EBX). The flags and bits 8 to 63 of RAX are unchanged.
table = f"{reg(i.memory_base)} + static_cast<uint8_t>(rax)"
if RegisterExt.size(i.memory_base) == 4:
table = f"static_cast<uint32_t>({table})"
stmt = f"rax = (rax & ~0xffull) | load<uint8_t>({table});"
elif op == M.RET:
stmt = "return rax;"
else:
Expand Down
1 change: 1 addition & 0 deletions tools/form_coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
"fourth_arg": "cpu_aot_fourth_argument",
"repeat_call": "cpu_aot_repeated_call",
"working_set_delta": "cpu_working_set_delta",
"xlatb": "cpu_aot_xlatb",
"exe_entry": "cpu_aot_exe_entry",
"address_size": "cpu_aot_address_size",
"call_pair": "cpu_aot_call_pair",
Expand Down